(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i { typeStripped = element._type.replace(/QDM::/, ''); dataElementsInit.push(new AllDataElements[typeStripped](element)); }); this.set({ dataElements: dataElementsInit }); }; QDMPatientSchema.methods.id = function id() { return this._id; }; // Returns an array of elements that exist on this patient, that // match the given HQMF data criteria OID. QDMPatientSchema.methods.getByHqmfOid = function getByHqmfOid(hqmfOid) { return this.dataElements.filter(element => element.hqmfOid === hqmfOid); }; // Returns an array of elements that exist on this patient, that // match the given QRDA data criteria OID. QDMPatientSchema.methods.getByQrdaOid = function getByQrdaOid(qrdaOid) { return this.dataElements.filter(element => element.qrdaOid === qrdaOid); }; // Returns an array of elements that exist on this patient. Optionally // takes a qdmCategory, which returns all elements of that QDM qdmCategory. // Example: patient.getDataElements({qdmCategory: 'encounters'}) will return // all Encounter QDM data types active on the patient. QDMPatientSchema.methods.getDataElements = function getDataElements(params) { if (params !== undefined && params.qdmCategory !== undefined && params.qdmStatus !== undefined) { return this.dataElements.filter(element => (element.qdmCategory === params.qdmCategory) && (element.qdmStatus === params.qdmStatus)); } else if (params !== undefined && params.qdmCategory !== undefined) { return this.dataElements.filter(element => element.qdmCategory === params.qdmCategory); } return this.dataElements; }; // Returns an array of dataElements that exist on the patient, queried by // QDM profile // @param {string} profile - the data criteria requested by the execution engine // @param {boolean} isNegated - whether dataElements should be returned based on their negation status // @returns {DataElement[]} QDMPatientSchema.methods.getByProfile = function getByProfile(profile, isNegated = null) { // If isNegated == true, only return data elements with a negationRationale that is not null. // If isNegated == false, only return data elements with a null negationRationale. // If isNegated == null, return all matching data elements by type, regardless of negationRationale. const results = this.dataElements.filter(element => (element._type === `QDM::${profile}` || element._type === profile) && (isNegated === null || !!element.negationRationale === isNegated)); return results.map((result) => { const removedMongooseItems = new AllDataElements[profile](result).toObject({ virtuals: true }); // toObject() will remove all mongoose functions but also remove the schema methods, so we add them back Object.entries(result.schema.methods).forEach(([method_name, method]) => { removedMongooseItems[method_name] = method; }); return removedMongooseItems; }); }; // This method is called by the CQL execution engine on a CQLPatient when // the execution engine wants information on a record. A record could be patient // characteristic information about the patient, or it could be data criteria // that currently exist on this patient (data criteria you drag on a patient // in Bonnie patient builder). // @param {String} profile - the data criteria requested by the execution engine // @returns {Object} QDMPatientSchema.methods.findRecords = function findRecords(profile) { // Clear profile cache for this patient if there is no cache or the patient has changed if (QDMPatientSchema.dataElementCache == null || QDMPatientSchema.dataElementCachePatientId !== this._id) { QDMPatientSchema.dataElementCache = {}; QDMPatientSchema.dataElementCachePatientId = this._id; } // If there is a cache 'hit', return it if (Object.prototype.hasOwnProperty.call(QDMPatientSchema.dataElementCache, profile)) { return QDMPatientSchema.dataElementCache[profile]; } let profileStripped; if (profile === 'Patient') { // Requested generic patient info const info = { birthDatetime: this.birthDatetime }; QDMPatientSchema.dataElementCache[profile] = [info]; return [info]; } else if (/PatientCharacteristic/.test(profile)) { // Requested a patient characteristic profileStripped = profile.replace(/ *\{[^)]*\} */g, ''); QDMPatientSchema.dataElementCache[profile] = this.getByProfile(profileStripped); return QDMPatientSchema.dataElementCache[profile]; } else if (profile != null) { // Requested something else (probably a QDM data type). // Strip model details from request. The requested profile string contains // a lot of things we do not need or care about. Example, we might see // something like: // "{urn:healthit-gov:qdm:v5_0_draft}PatientCharacteristicEthnicity" // Where we only care about: "PatientCharacteristicEthnicity". profileStripped = profile.replace(/ *\{[^)]*\} */g, ''); // Check and handle negation status if (/Positive/.test(profileStripped)) { profileStripped = profileStripped.replace(/Positive/, ''); // Since the data criteria is 'Positive', it is not negated. QDMPatientSchema.dataElementCache[profile] = this.getByProfile(profileStripped, false); return QDMPatientSchema.dataElementCache[profile]; } else if (/Negative/.test(profileStripped)) { profileStripped = profileStripped.replace(/Negative/, ''); // Since the data criteria is 'Negative', it is negated. QDMPatientSchema.dataElementCache[profile] = this.getByProfile(profileStripped, true); return QDMPatientSchema.dataElementCache[profile]; } // No negation status, proceed normally QDMPatientSchema.dataElementCache[profile] = this.getByProfile(profileStripped); return QDMPatientSchema.dataElementCache[profile]; } return []; }; QDMPatientSchema.methods.adverse_events = function adverse_events() { return this.getDataElements({ qdmCategory: 'adverse_event' }); }; QDMPatientSchema.methods.allergies = function allergies() { return this.getDataElements({ qdmCategory: 'allergy' }); }; QDMPatientSchema.methods.assessments = function assessments() { return this.getDataElements({ qdmCategory: 'assessment' }); }; QDMPatientSchema.methods.care_experiences = function care_experiences() { return this.getDataElements({ qdmCategory: 'care_experience' }); }; QDMPatientSchema.methods.care_goals = function care_goals() { return this.getDataElements({ qdmCategory: 'care_goal' }); }; QDMPatientSchema.methods.communications = function communications() { return this.getDataElements({ qdmCategory: 'communication' }); }; QDMPatientSchema.methods.conditions = function conditions() { return this.getDataElements({ qdmCategory: 'condition' }); }; QDMPatientSchema.methods.devices = function devices() { return this.getDataElements({ qdmCategory: 'device' }); }; QDMPatientSchema.methods.diagnostic_studies = function diagnostic_studies() { return this.getDataElements({ qdmCategory: 'diagnostic_study' }); }; QDMPatientSchema.methods.encounters = function encounters() { return this.getDataElements({ qdmCategory: 'encounter' }); }; QDMPatientSchema.methods.family_history = function family_history() { return this.getDataElements({ qdmCategory: 'family_history' }); }; QDMPatientSchema.methods.functional_statuses = function functional_statuses() { return this.getDataElements({ qdmCategory: 'functional_status' }); }; QDMPatientSchema.methods.immunizations = function immunizations() { return this.getDataElements({ qdmCategory: 'immunization' }); }; QDMPatientSchema.methods.interventions = function interventions() { return this.getDataElements({ qdmCategory: 'intervention' }); }; QDMPatientSchema.methods.laboratory_tests = function laboratory_tests() { return this.getDataElements({ qdmCategory: 'laboratory_test' }); }; QDMPatientSchema.methods.medical_equipment = function medical_equipment() { return this.getDataElements({ qdmCategory: 'medical_equipment' }); }; QDMPatientSchema.methods.medications = function medications() { return this.getDataElements({ qdmCategory: 'medication' }); }; QDMPatientSchema.methods.patient_characteristics = function patient_characteristics() { return this.getDataElements({ qdmCategory: 'patient_characteristic' }); }; QDMPatientSchema.methods.physical_exams = function physical_exams() { return this.getDataElements({ qdmCategory: 'physical_exam' }); }; QDMPatientSchema.methods.preferences = function preferences() { return this.getDataElements({ qdmCategory: 'preference' }); }; QDMPatientSchema.methods.procedures = function procedures() { return this.getDataElements({ qdmCategory: 'procedure' }); }; QDMPatientSchema.methods.results = function results() { return this.getDataElements({ qdmCategory: 'result' }); }; QDMPatientSchema.methods.risk_category_assessments = function risk_category_assessments() { return this.getDataElements({ qdmCategory: 'risk_category_assessment' }); }; QDMPatientSchema.methods.social_history = function social_history() { return this.getDataElements({ qdmCategory: 'social_history' }); }; QDMPatientSchema.methods.substances = function substances() { return this.getDataElements({ qdmCategory: 'substance' }); }; QDMPatientSchema.methods.symptoms = function symptoms() { return this.getDataElements({ qdmCategory: 'symptom' }); }; QDMPatientSchema.methods.system_characteristics = function system_characteristics() { return this.getDataElements({ qdmCategory: 'system_characteristic' }); }; QDMPatientSchema.methods.transfers = function transfers() { return this.getDataElements({ qdmCategory: 'transfer' }); }; QDMPatientSchema.methods.vital_signs = function vital_signs() { return this.getDataElements({ qdmCategory: 'vital_sign' }); }; QDMPatientSchema.clearDataElementCache = function clearDataElementCache() { QDMPatientSchema.dataElementCachePatientId = null; QDMPatientSchema.dataElementCache = null; }; module.exports.QDMPatientSchema = QDMPatientSchema; class QDMPatient extends mongoose.Document { constructor(object) { super(object, QDMPatientSchema); this.initializeDataElements(); } } module.exports.QDMPatient = QDMPatient; },{"./AllDataElements":2,"./basetypes/Code":69,"./basetypes/DateTime":71,"./basetypes/Interval":72,"./basetypes/Quantity":74,"mongoose/browser":184}],50:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { IdentifierSchema } = require('./attributes/Identifier'); const { DataElementSchema } = require('./basetypes/DataElement'); const Code = require('./basetypes/Code'); const Interval = require('./basetypes/Interval'); const Quantity = require('./basetypes/Quantity'); const DateTime = require('./basetypes/DateTime'); const QDMDate = require('./basetypes/QDMDate'); const Any = require('./basetypes/Any'); const AnyEntity = require('./basetypes/AnyEntity'); const { ComponentSchema } = require('./attributes/Component'); const { FacilityLocationSchema } = require('./attributes/FacilityLocation'); const { EntitySchema } = require('./attributes/Entity'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const RelatedPersonSchema = DataElementSchema({ identifier: IdentifierSchema, linkedPatientId: String, qdmTitle: { type: String, default: 'Related Person' }, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.141' }, qdmCategory: { type: String, default: 'related_person' }, qdmVersion: { type: String, default: '5.6' }, _type: { type: String, default: 'QDM::RelatedPerson' }, }); module.exports.RelatedPersonSchema = RelatedPersonSchema; class RelatedPerson extends mongoose.Document { constructor(object) { super(object, RelatedPersonSchema); this._type = 'QDM::RelatedPerson'; } } module.exports.RelatedPerson = RelatedPerson; },{"./attributes/Component":57,"./attributes/Entity":59,"./attributes/FacilityLocation":60,"./attributes/Identifier":61,"./basetypes/Any":67,"./basetypes/AnyEntity":68,"./basetypes/Code":69,"./basetypes/DataElement":70,"./basetypes/DateTime":71,"./basetypes/Interval":72,"./basetypes/QDMDate":73,"./basetypes/Quantity":74,"mongoose/browser":184}],51:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const PlaceholderResultSchema = mongoose.Schema({ cache_id: String, measure_id: String, sub_id: String, test_id: String, effective_date: Number, filters: Object, prefilter: Object, calculation_time: Date, status: Object, population_ids: Object, STRAT: Number, IPP: Number, DENOM: Number, NUMER: Number, NUMEX: Number, DENEX: Number, DENEXCEP: Number, MSRPOPL: Number, OBSERV: Number, MSRPOPLEX: Number, supplemental_data: Object, }); module.exports.ResultSchema = PlaceholderResultSchema; class PlaceholderResult extends mongoose.Document { constructor(object) { super(object, PlaceholderResultSchema); } } module.exports.PlaceholderResult = PlaceholderResult; },{"mongoose/browser":184}],52:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { IdentifierSchema } = require('./attributes/Identifier'); const { DataElementSchema } = require('./basetypes/DataElement'); const Code = require('./basetypes/Code'); const Interval = require('./basetypes/Interval'); const Quantity = require('./basetypes/Quantity'); const DateTime = require('./basetypes/DateTime'); const QDMDate = require('./basetypes/QDMDate'); const Any = require('./basetypes/Any'); const AnyEntity = require('./basetypes/AnyEntity'); const { ComponentSchema } = require('./attributes/Component'); const { FacilityLocationSchema } = require('./attributes/FacilityLocation'); const { EntitySchema } = require('./attributes/Entity'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const SubstanceAdministeredSchema = DataElementSchema({ authorDatetime: DateTime, relevantDatetime: DateTime, relevantPeriod: Interval, dosage: Quantity, frequency: Code, route: Code, negationRationale: Code, performer: [AnyEntity], qdmTitle: { type: String, default: 'Substance, Administered' }, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.73' }, qdmCategory: { type: String, default: 'substance' }, qdmStatus: { type: String, default: 'administered' }, qdmVersion: { type: String, default: '5.6' }, _type: { type: String, default: 'QDM::SubstanceAdministered' }, }); module.exports.SubstanceAdministeredSchema = SubstanceAdministeredSchema; class SubstanceAdministered extends mongoose.Document { constructor(object) { super(object, SubstanceAdministeredSchema); this._type = 'QDM::SubstanceAdministered'; } } module.exports.SubstanceAdministered = SubstanceAdministered; },{"./attributes/Component":57,"./attributes/Entity":59,"./attributes/FacilityLocation":60,"./attributes/Identifier":61,"./basetypes/Any":67,"./basetypes/AnyEntity":68,"./basetypes/Code":69,"./basetypes/DataElement":70,"./basetypes/DateTime":71,"./basetypes/Interval":72,"./basetypes/QDMDate":73,"./basetypes/Quantity":74,"mongoose/browser":184}],53:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { IdentifierSchema } = require('./attributes/Identifier'); const { DataElementSchema } = require('./basetypes/DataElement'); const Code = require('./basetypes/Code'); const Interval = require('./basetypes/Interval'); const Quantity = require('./basetypes/Quantity'); const DateTime = require('./basetypes/DateTime'); const QDMDate = require('./basetypes/QDMDate'); const Any = require('./basetypes/Any'); const AnyEntity = require('./basetypes/AnyEntity'); const { ComponentSchema } = require('./attributes/Component'); const { FacilityLocationSchema } = require('./attributes/FacilityLocation'); const { EntitySchema } = require('./attributes/Entity'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const SubstanceOrderSchema = DataElementSchema({ authorDatetime: DateTime, relevantPeriod: Interval, reason: Code, dosage: Quantity, supply: Quantity, frequency: Code, refills: Number, route: Code, negationRationale: Code, requester: [AnyEntity], qdmTitle: { type: String, default: 'Substance, Order' }, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.77' }, qdmCategory: { type: String, default: 'substance' }, qdmStatus: { type: String, default: 'order' }, qdmVersion: { type: String, default: '5.6' }, _type: { type: String, default: 'QDM::SubstanceOrder' }, }); module.exports.SubstanceOrderSchema = SubstanceOrderSchema; class SubstanceOrder extends mongoose.Document { constructor(object) { super(object, SubstanceOrderSchema); this._type = 'QDM::SubstanceOrder'; } } module.exports.SubstanceOrder = SubstanceOrder; },{"./attributes/Component":57,"./attributes/Entity":59,"./attributes/FacilityLocation":60,"./attributes/Identifier":61,"./basetypes/Any":67,"./basetypes/AnyEntity":68,"./basetypes/Code":69,"./basetypes/DataElement":70,"./basetypes/DateTime":71,"./basetypes/Interval":72,"./basetypes/QDMDate":73,"./basetypes/Quantity":74,"mongoose/browser":184}],54:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { IdentifierSchema } = require('./attributes/Identifier'); const { DataElementSchema } = require('./basetypes/DataElement'); const Code = require('./basetypes/Code'); const Interval = require('./basetypes/Interval'); const Quantity = require('./basetypes/Quantity'); const DateTime = require('./basetypes/DateTime'); const QDMDate = require('./basetypes/QDMDate'); const Any = require('./basetypes/Any'); const AnyEntity = require('./basetypes/AnyEntity'); const { ComponentSchema } = require('./attributes/Component'); const { FacilityLocationSchema } = require('./attributes/FacilityLocation'); const { EntitySchema } = require('./attributes/Entity'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const SubstanceRecommendedSchema = DataElementSchema({ authorDatetime: DateTime, reason: Code, dosage: Quantity, frequency: Code, refills: Number, route: Code, negationRationale: Code, requester: [AnyEntity], qdmTitle: { type: String, default: 'Substance, Recommended' }, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.78' }, qdmCategory: { type: String, default: 'substance' }, qdmStatus: { type: String, default: 'recommended' }, qdmVersion: { type: String, default: '5.6' }, _type: { type: String, default: 'QDM::SubstanceRecommended' }, }); module.exports.SubstanceRecommendedSchema = SubstanceRecommendedSchema; class SubstanceRecommended extends mongoose.Document { constructor(object) { super(object, SubstanceRecommendedSchema); this._type = 'QDM::SubstanceRecommended'; } } module.exports.SubstanceRecommended = SubstanceRecommended; },{"./attributes/Component":57,"./attributes/Entity":59,"./attributes/FacilityLocation":60,"./attributes/Identifier":61,"./basetypes/Any":67,"./basetypes/AnyEntity":68,"./basetypes/Code":69,"./basetypes/DataElement":70,"./basetypes/DateTime":71,"./basetypes/Interval":72,"./basetypes/QDMDate":73,"./basetypes/Quantity":74,"mongoose/browser":184}],55:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { IdentifierSchema } = require('./attributes/Identifier'); const { DataElementSchema } = require('./basetypes/DataElement'); const Code = require('./basetypes/Code'); const Interval = require('./basetypes/Interval'); const Quantity = require('./basetypes/Quantity'); const DateTime = require('./basetypes/DateTime'); const QDMDate = require('./basetypes/QDMDate'); const Any = require('./basetypes/Any'); const AnyEntity = require('./basetypes/AnyEntity'); const { ComponentSchema } = require('./attributes/Component'); const { FacilityLocationSchema } = require('./attributes/FacilityLocation'); const { EntitySchema } = require('./attributes/Entity'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const SymptomSchema = DataElementSchema({ prevalencePeriod: Interval, severity: Code, recorder: [AnyEntity], qdmTitle: { type: String, default: 'Symptom' }, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.116' }, qrdaOid: { type: String, default: '2.16.840.1.113883.10.20.24.3.136' }, qdmCategory: { type: String, default: 'symptom' }, qdmVersion: { type: String, default: '5.6' }, _type: { type: String, default: 'QDM::Symptom' }, }); module.exports.SymptomSchema = SymptomSchema; class Symptom extends mongoose.Document { constructor(object) { super(object, SymptomSchema); this._type = 'QDM::Symptom'; } } module.exports.Symptom = Symptom; },{"./attributes/Component":57,"./attributes/Entity":59,"./attributes/FacilityLocation":60,"./attributes/Identifier":61,"./basetypes/Any":67,"./basetypes/AnyEntity":68,"./basetypes/Code":69,"./basetypes/DataElement":70,"./basetypes/DateTime":71,"./basetypes/Interval":72,"./basetypes/QDMDate":73,"./basetypes/Quantity":74,"mongoose/browser":184}],56:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { EntitySchemaFunction } = require('./Entity'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const CarePartnerSchema = EntitySchemaFunction({ relationship: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.134' }, qrdaOid: { type: String, default: '2.16.840.1.113883.10.20.24.3.160' }, _type: { type: String, default: 'QDM::CarePartner' }, }); module.exports.CarePartnerSchema = CarePartnerSchema; class CarePartner extends mongoose.Document { constructor(object) { super(object, CarePartnerSchema); this._type = 'QDM::CarePartner'; } } module.exports.CarePartner = CarePartner; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"./Entity":59,"mongoose/browser":184}],57:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Schema] = [mongoose.Schema]; const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const ComponentSchema = new mongoose.Schema({ code: Code, result: Any, qdmVersion: { type: String, default: '5.6' }, _type: { type: String, default: 'QDM::Component' }, }); module.exports.ComponentSchema = ComponentSchema; class Component extends mongoose.Document { constructor(object) { super(object, ComponentSchema); this._type = 'QDM::Component'; } } function ComponentSchemaFunction(add, options) { const extended = new Schema({ code: Code, result: Any, qdmVersion: { type: String, default: '5.6' }, _type: { type: String, default: 'QDM::Component' }, }, options); if (add) { extended.add(add); } return extended; } module.exports.Component = Component; module.exports.ComponentSchemaFunction = ComponentSchemaFunction; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"mongoose/browser":184}],58:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const DiagnosisComponentSchema = new mongoose.Schema({ code: Code, presentOnAdmissionIndicator: Code, rank: Number, qdmVersion: { type: String, default: '5.6' }, _type: { type: String, default: 'QDM::DiagnosisComponent' }, }); module.exports.DiagnosisComponentSchema = DiagnosisComponentSchema; class DiagnosisComponent extends mongoose.Document { constructor(object) { super(object, DiagnosisComponentSchema); this._type = 'QDM::DiagnosisComponent'; } } module.exports.DiagnosisComponent = DiagnosisComponent; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"mongoose/browser":184}],59:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { IdentifierSchema } = require('./Identifier'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Schema] = [mongoose.Schema]; const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const EntitySchema = new mongoose.Schema({ id: String, identifier: IdentifierSchema, qdmVersion: { type: String, default: '5.6' }, _type: { type: String, default: 'QDM::Entity' }, }); module.exports.EntitySchema = EntitySchema; class Entity extends mongoose.Document { constructor(object) { super(object, EntitySchema); this._type = 'QDM::Entity'; } } function EntitySchemaFunction(add, options) { const extended = new Schema({ identifier: IdentifierSchema, qdmVersion: { type: String, default: '5.6' }, _type: { type: String, default: 'QDM::Entity' }, id: { type: String, default() { return this._id ? this._id.toString() : mongoose.Types.ObjectId().toString(); }, }, }, options); if (add) { extended.add(add); } return extended; } module.exports.Entity = Entity; module.exports.EntitySchemaFunction = EntitySchemaFunction; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"./Identifier":61,"mongoose/browser":184}],60:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const FacilityLocationSchema = new mongoose.Schema({ code: Code, locationPeriod: Interval, qdmVersion: { type: String, default: '5.6' }, _type: { type: String, default: 'QDM::FacilityLocation' }, }); module.exports.FacilityLocationSchema = FacilityLocationSchema; class FacilityLocation extends mongoose.Document { constructor(object) { super(object, FacilityLocationSchema); this._type = 'QDM::FacilityLocation'; } } module.exports.FacilityLocation = FacilityLocation; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"mongoose/browser":184}],61:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const IdentifierSchema = mongoose.Schema({ namingSystem: String, value: String, qdmVersion: { type: String, default: '5.6' }, _type: { type: String, default: 'QDM::Identifier' }, }, { _id: false, id: false }); module.exports.IdentifierSchema = IdentifierSchema; class Identifier extends mongoose.Document { constructor(object) { super(object, IdentifierSchema); this._type = 'QDM::Identifier'; } } module.exports.Identifier = Identifier; },{"mongoose/browser":184}],62:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { EntitySchemaFunction } = require('./Entity'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const LocationSchema = EntitySchemaFunction({ locationType: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.142' }, _type: { type: String, default: 'QDM::Location' }, }); module.exports.LocationSchema = LocationSchema; class Location extends mongoose.Document { constructor(object) { super(object, LocationSchema); this._type = 'QDM::Location'; } } module.exports.Location = Location; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"./Entity":59,"mongoose/browser":184}],63:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { EntitySchemaFunction } = require('./Entity'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const OrganizationSchema = EntitySchemaFunction({ organizationType: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.135' }, qrdaOid: { type: String, default: '2.16.840.1.113883.10.20.24.3.163' }, _type: { type: String, default: 'QDM::Organization' }, }); module.exports.OrganizationSchema = OrganizationSchema; class Organization extends mongoose.Document { constructor(object) { super(object, OrganizationSchema); this._type = 'QDM::Organization'; } } module.exports.Organization = Organization; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"./Entity":59,"mongoose/browser":184}],64:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { EntitySchemaFunction } = require('./Entity'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PatientEntitySchema = EntitySchemaFunction({ hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.136' }, qrdaOid: { type: String, default: '2.16.840.1.113883.10.20.24.3.161' }, _type: { type: String, default: 'QDM::PatientEntity' }, }); module.exports.PatientEntitySchema = PatientEntitySchema; class PatientEntity extends mongoose.Document { constructor(object) { super(object, PatientEntitySchema); this._type = 'QDM::PatientEntity'; } } module.exports.PatientEntity = PatientEntity; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"./Entity":59,"mongoose/browser":184}],65:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { EntitySchemaFunction } = require('./Entity'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PractitionerSchema = EntitySchemaFunction({ role: Code, specialty: Code, qualification: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.137' }, qrdaOid: { type: String, default: '2.16.840.1.113883.10.20.24.3.162' }, _type: { type: String, default: 'QDM::Practitioner' }, }); module.exports.PractitionerSchema = PractitionerSchema; class Practitioner extends mongoose.Document { constructor(object) { super(object, PractitionerSchema); this._type = 'QDM::Practitioner'; } } module.exports.Practitioner = Practitioner; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"./Entity":59,"mongoose/browser":184}],66:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { ComponentSchemaFunction } = require('./Component'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const ResultComponentSchema = ComponentSchemaFunction({ referenceRange: Interval, _type: { type: String, default: 'QDM::ResultComponent' }, }); module.exports.ResultComponentSchema = ResultComponentSchema; class ResultComponent extends mongoose.Document { constructor(object) { super(object, ResultComponentSchema); this._type = 'QDM::ResultComponent'; } } module.exports.ResultComponent = ResultComponent; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"./Component":57,"mongoose/browser":184}],67:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const cql = require('cql-execution'); function Any(key, options) { mongoose.SchemaType.call(this, key, options, 'Any'); } Any.prototype = Object.create(mongoose.SchemaType.prototype); function RecursiveCast(any) { if (any && any.value && any.unit) { return new cql.Quantity(any.value, any.unit); } if (any && any.numerator && any.denominator) { const numerator = new cql.Quantity(any.numerator.value, any.numerator.unit); const denominator = new cql.Quantity(any.denominator.value, any.denominator.unit); return new cql.Ratio(numerator, denominator); } if (any.isCode || any.isConcept || any.isValueSet || any.isList || any.isDateTime || any.isDate || any.isRatio || any.isQuantiy || any.isInterval || any.isBooleanLiteral || any.isIntegerLiteral || any.isDecimalLiteral || any.isStringLiteral || any.isTuple) { return any; } if (any && any.code && any.system) { const val = { code: any.code, system: any.system }; val.display = (typeof any.display !== 'undefined') ? any.display : null; val.version = (typeof any.version !== 'undefined') ? any.version : null; return new cql.Code(val.code, val.system, val.version, val.display); } if (any && any.low) { const casted = new cql.Interval(any.low, any.high, any.lowClosed, any.highClosed); // Cast Low and High values to Quantities if it is a quantity if (casted.low && casted.low.unit && casted.low.value) { casted.low = new cql.Quantity(casted.low.value, casted.low.unit); if (casted.high && casted.high.unit && casted.high.value) { casted.high = new cql.Quantity(casted.high.value, casted.high.unit); } return casted; } // Cast to DateTime if it is a string representing a DateTime if (casted.low && Date.parse(casted.low)) { casted.low = cql.DateTime.fromJSDate(new Date(casted.low), 0); } if (casted.high && Date.parse(casted.high)) { casted.high = cql.DateTime.fromJSDate(new Date(casted.high), 0); } return casted; } if (Array.isArray(any)) { const casted = []; any.forEach((val) => { casted.push(RecursiveCast(val)); }); return casted; } if (Number.isFinite(any)) { return any; } if (Date.parse(any) || Date.parse(`1984-01-01T${any}`)) { if (any.match(/T/) || any.match(/\+/)) { // If it has a T or a timezoneoffset, it must be a DateTime return cql.DateTime.fromJSDate(new Date(any), 0); } if (any.match(/:/)) { // If it has a : but no T or timezoneoffset, it must be a Time return cql.DateTime.fromJSDate(new Date(`1984-01-01T${any}`), 0).getTime(); } // Must be a Date return cql.DateTime.fromJSDate(new Date(any), 0).getDate(); } return any; } Any.prototype.cast = any => RecursiveCast(any); mongoose.Schema.Types.Any = Any; module.exports = Any; },{"cql-execution":132,"mongoose/browser":184}],68:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { PatientEntity } = require('../attributes/PatientEntity'); const { Practitioner } = require('../attributes/Practitioner'); const { CarePartner } = require('../attributes/CarePartner'); const { Organization } = require('../attributes/Organization'); const { Location } = require('../attributes/Location'); function AnyEntity(key, options) { mongoose.SchemaType.call(this, key, options, 'AnyEntity'); } AnyEntity.prototype = Object.create(mongoose.SchemaType.prototype); AnyEntity.prototype.cast = (entity) => { if (entity == null) { return null; } if (entity instanceof PatientEntity || entity instanceof Practitioner || entity instanceof CarePartner || entity instanceof Organization) { return entity; } if (entity._type != null) { // copy _id to id if it isn't defined if (entity.id == null && entity._id != null) { entity.id = entity._id; } switch (entity._type) { case 'QDM::PatientEntity': return new PatientEntity(entity); case 'QDM::Practitioner': return new Practitioner(entity); case 'QDM::CarePartner': return new CarePartner(entity); case 'QDM::Organization': return new Organization(entity); case 'QDM::Location': return new Location(entity); default: throw new Error(`Could not find entity type "${entity._type}".`); } } else { throw new Error('Could not find _type indicator for entity.'); } }; mongoose.Schema.Types.AnyEntity = AnyEntity; module.exports = AnyEntity; },{"../attributes/CarePartner":56,"../attributes/Location":62,"../attributes/Organization":63,"../attributes/PatientEntity":64,"../attributes/Practitioner":65,"mongoose/browser":184}],69:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const cql = require('cql-execution'); function Code(key, options) { mongoose.SchemaType.call(this, key, options, 'Code'); } Code.prototype = Object.create(mongoose.SchemaType.prototype); Code.prototype.cast = (code) => { if (code != null) { // return code if it doesn't even need casting if (code.isCode) { return code; } // handles codes that have not yet been cast to a code and those that have already been cast to a code if (code.code && code.system) { const val = { code: code.code, system: code.system }; val.display = (typeof code.display !== 'undefined') ? code.display : null; val.version = (typeof code.version !== 'undefined') ? code.version : null; return new cql.Code(val.code, val.system, val.version, val.display); } throw new Error(`Expected a code. Received ${code}.`); } else { // returns a null or undefined if what is passed in is null or undefined return code; } }; mongoose.Schema.Types.Code = Code; module.exports = Code; },{"cql-execution":132,"mongoose/browser":184}],70:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const Code = require('./Code.js'); const cql = require('cql-execution'); const Identifier = require('../attributes/Identifier'); const [Schema] = [mongoose.Schema]; function DataElementSchema(add, options) { const extended = new Schema({ dataElementCodes: { type: [Code] }, description: { type: String }, codeListId: { type: String }, id: { type: String, default() { return this._id ? this._id.toString() : mongoose.Types.ObjectId().toString(); }, }, }, options); if (add) { extended.add(add); } // Returns all of the codes on this data element in a format usable by // the cql-execution framework. extended.methods.getCode = function getCode() { if (this.dataElementCodes) { return this.dataElementCodes.map((code) => { if (code.isCode) { return code; } return new cql.Code(code.code, code.system, code.version, code.display); }); } return null; }; // Return the first code on this data element in a format usable by // the cql-execution framework. extended.methods.code = function code() { if (this.dataElementCodes && this.dataElementCodes[0]) { const qdmCode = this.dataElementCodes[0]; if (qdmCode.isCode) { return qdmCode; } return new cql.Code(qdmCode.code, qdmCode.system, qdmCode.version, qdmCode.display); } return null; }; return extended; } module.exports.DataElementSchema = DataElementSchema; },{"../attributes/Identifier":61,"./Code.js":69,"cql-execution":132,"mongoose/browser":184}],71:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const cql = require('cql-execution'); function DateTime(key, options) { mongoose.SchemaType.call(this, key, options, 'DateTime'); } DateTime.prototype = Object.create(mongoose.SchemaType.prototype); DateTime.prototype.cast = (dateTime) => { if (dateTime.isDateTime) { return dateTime; } if (!Date.parse(dateTime)) { throw new Error(`DateTime: ${dateTime} is not a valid DateTime`); } return cql.DateTime.fromJSDate(new Date(dateTime), 0); }; mongoose.Schema.Types.DateTime = DateTime; module.exports = DateTime; },{"cql-execution":132,"mongoose/browser":184}],72:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const cql = require('cql-execution'); const DateTime = require('./DateTime'); function Interval(key, options) { mongoose.SchemaType.call(this, key, options, 'Interval'); } Interval.prototype = Object.create(mongoose.SchemaType.prototype); Interval.prototype.cast = (interval) => { if (interval.isInterval) { return interval; } const casted = new cql.Interval(interval.low, interval.high, interval.lowClosed, interval.highClosed); // Cast Low and High values to Quantities if it is a quantity if (casted.low && casted.low.unit && casted.low.value) { casted.low = new cql.Quantity(casted.low.value, casted.low.unit); if (casted.high && casted.high.unit && casted.high.value) { casted.high = new cql.Quantity(casted.high.value, casted.high.unit); } return casted; } // Cast to DateTime if it is a string representing a DateTime if (casted.low) { casted.low = DateTime.prototype.cast(casted.low); } if (casted.high) { casted.high = DateTime.prototype.cast(casted.high); } return casted; }; mongoose.Schema.Types.Interval = Interval; module.exports = Interval; },{"./DateTime":71,"cql-execution":132,"mongoose/browser":184}],73:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const cql = require('cql-execution'); function QDMDate(key, options) { mongoose.SchemaType.call(this, key, options, 'Date'); } QDMDate.prototype = Object.create(mongoose.SchemaType.prototype); QDMDate.prototype.cast = (date) => { if (date == null) { return date; } // Already a CQL Date if (date.isDate) { return date; } // Object if (typeof date === 'object') { const keys = Object.keys(date); if (keys.includes('year') && keys.includes('month') && keys.includes('day')) { return new cql.Date(date.year, date.month, date.day); } } // Date String if (!cql.Date.parse(date)) { throw new Error(`Date: ${date} is not a valid Date`); } else { return cql.Date.parse(date); } }; mongoose.Schema.Types.QDMDate = QDMDate; module.exports = QDMDate; },{"cql-execution":132,"mongoose/browser":184}],74:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const cql = require('cql-execution'); function Quantity(key, options) { mongoose.SchemaType.call(this, key, options, 'Quantity'); } Quantity.prototype = Object.create(mongoose.SchemaType.prototype); Quantity.prototype.cast = (quantity) => { if (typeof quantity.value === 'undefined') { throw new Error(`Quantity: ${quantity} does not have a value`); } else if (typeof quantity.unit === 'undefined') { throw new Error(`Quantity: ${quantity} does not have a unit`); } return new cql.Quantity(quantity.value, quantity.unit); }; mongoose.Schema.Types.Quantity = Quantity; module.exports = Quantity; },{"cql-execution":132,"mongoose/browser":184}],75:[function(require,module,exports){ window.cqm = window.cqm || {}; window.cqm.models = require('./index'); },{"./index":88}],76:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { StatementDependencySchema } = require('./CQLStatementDependency'); const [Mixed, mDate] = [ mongoose.Schema.Types.Mixed, mongoose.Schema.Types.Date, ]; const CQLLibrarySchema = new mongoose.Schema( { library_name: String, library_version: String, cql: String, elm: Mixed, elm_annotations: Mixed, is_main_library: { type: Boolean, default: false }, is_top_level: { type: Boolean, default: true }, statement_dependencies: [StatementDependencySchema], }, // Options { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }, // These are the Mongoid conventions for timestamps } ); module.exports.CQLLibrarySchema = CQLLibrarySchema; class CQLLibrary extends mongoose.Document { constructor(object) { super(object, CQLLibrarySchema); } } module.exports.CQLLibrary = CQLLibrary; },{"./CQLStatementDependency":77,"mongoose/browser":184}],77:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const StatementReferenceSchema = new mongoose.Schema({ library_name: String, statement_name: String, hqmf_id: String, }); const StatementDependencySchema = new mongoose.Schema({ statement_name: String, statement_references: [StatementReferenceSchema], }); module.exports.StatementReferenceSchema = StatementReferenceSchema; class StatementReference extends mongoose.Document { constructor(object) { super(object, StatementReferenceSchema); } } module.exports.StatementReference = StatementReference; module.exports.StatementDependencySchema = StatementDependencySchema; class StatementDependency extends mongoose.Document { constructor(object) { super(object, StatementDependencySchema); } } module.exports.StatementDependency = StatementDependency; },{"mongoose/browser":184}],78:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const [String, Mixed] = [ mongoose.Schema.Types.String, mongoose.Schema.Types.Mixed, ]; const ClauseResultSchema = mongoose.Schema({ // Library the clause this result is for is in library_name: String, // Statement the clause this result is for is in statement_name: String, // LocalId of the clause this result is for localId: String, // Final, processed result of raw calculation final: String, // Raw result of clause calculation raw: Mixed, }); module.exports.ClauseResultSchema = ClauseResultSchema; class ClauseResult extends mongoose.Document { constructor(object) { super(object, ClauseResultSchema); } } module.exports.ClauseResult = ClauseResult; },{"mongoose/browser":184}],79:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const ConceptSchema = new mongoose.Schema({ code: String, code_system_oid: String, code_system_name: String, code_system_version: String, display_name: String, }); module.exports.ConceptSchema = ConceptSchema; class Concept extends mongoose.Document { constructor(object) { super(object, ConceptSchema); } } module.exports.Concept = Concept; },{"mongoose/browser":184}],80:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { ClauseResultSchema } = require('./ClauseResult'); const { StatementResultSchema } = require('./StatementResult'); const [Number, String, Mixed, ObjectId] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, mongoose.Schema.Types.Mixed, mongoose.Schema.Types.ObjectId, ]; const IndividualResultSchema = mongoose.Schema( { // Population Attributes STRAT: Number, IPP: Number, DENOM: Number, NUMER: Number, NUMEX: Number, DENEX: Number, DENEXCEP: Number, MSRPOPL: Number, OBSERV: Number, MSRPOPLEX: Number, // Result Attributes clause_results: [ClauseResultSchema], statement_results: [StatementResultSchema], population_relevance: Mixed, episode_results: Mixed, observation_values: [Number], // This field is for application specific information only. If both Bonnie and // Cypress use a common field, it should be made a field on this model, // and not put into extendedData. extendedData: { type: Mixed, default: {}, }, // Calculation State attributes state: { type: String, enum: ['queued', 'running', 'complete', 'cancelled', 'failed'], default: 'queued', }, // Relations to other model classes // 'alias' field makes it so you can call obj.measure, and get the object referenced by measure_id measure_id: { type: ObjectId, ref: 'Measure', alias: 'measure' }, patient_id: { type: ObjectId, ref: 'Patient', alias: 'patient' }, }, // Options { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }, // These are the Mongoid conventions for timestamps } ); IndividualResultSchema.methods.clause_results_by_clause = function clause_results_by_clause() { const clause_results_hash = {}; this.clause_results.forEach((result) => { if (!clause_results_hash[result.library_name]) { clause_results_hash[result.library_name] = {}; } clause_results_hash[result.library_name][result.localId] = result; }); return clause_results_hash; }; IndividualResultSchema.methods.statement_results_by_statement = function statement_results_by_statement() { const statement_results_hash = {}; this.statement_results.forEach((result) => { if (!statement_results_hash[result.library_name]) { statement_results_hash[result.library_name] = {}; } statement_results_hash[result.library_name][result.statement_name] = result; }); return statement_results_hash; }; module.exports.IndividualResultSchema = IndividualResultSchema; class IndividualResult extends mongoose.Document { constructor(object) { super(object, IndividualResultSchema); } } module.exports.IndividualResult = IndividualResult; },{"./ClauseResult":78,"./StatementResult":86,"mongoose/browser":184}],81:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DataElementSchema = require('../basetypes/DataElement').DataElementSchema(); const AllDataElements = require('../AllDataElements'); const { CQLLibrarySchema } = require('./CQLLibrary'); const { PopulationSetSchema } = require('./PopulationSet'); const [Number, String, Boolean, Mixed, ObjectId, Date] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, mongoose.Schema.Types.Boolean, mongoose.Schema.Types.Mixed, mongoose.Schema.Types.ObjectId, mongoose.Schema.Types.Date, ]; const MeasureSchema = new mongoose.Schema( { // A version-specific UUID for the measure hqmf_id: String, // A version-neutral UUID for the measure hqmf_set_id: String, // A Semantic Version-compliant string (e.g. "2.3.4") for the measure hqmf_version_number: String, // A CMS-style string (e.g. "CMS2v4") for the measure cms_id: String, title: String, description: String, // Composite/component measure fields composite: { type: Boolean, default: false, }, component: { type: Boolean, default: false, }, component_hqmf_set_ids: [String], composite_hqmf_set_id: String, // Measure type variables measure_scoring: { type: String, enum: ['PROPORTION', 'RATIO', 'CONTINUOUS_VARIABLE', 'COHORT'], default: 'PROPORTION', }, calculation_method: { type: String, enum: ['PATIENT', 'EPISODE_OF_CARE'], default: 'PATIENT', }, calculate_sdes: Boolean, // ELM/CQL Measure-logic related data encapsulated in CQLLibrarySchema // Field name changed from 'cql' to 'cql_libraries' because the semantics of // embeds_many: cqls (on the Ruby side) sounded weird, // and we wanted to keep the API consistent cql_libraries: [CQLLibrarySchema], main_cql_library: String, // HQMF/Tacoma-specific Measure-logic related data population_criteria: Mixed, source_data_criteria: [], measure_period: Mixed, measure_attributes: [], population_sets: [PopulationSetSchema], // Relations to other model classes bundle: { type: ObjectId, ref: 'Bundle' }, // Cypress-specific, until we migrate the Bundle into cqm-models package: { type: ObjectId, ref: 'MeasurePackage' }, // Bonnie-specific patients: [{ type: ObjectId, ref: 'Patient', index: true }], value_sets: [{ type: ObjectId, ref: 'ValueSet' }], }, // Options { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }, // These are the Mongoid conventions for timestamps } ); // After initialization of a Measure model, initialize every individual data element // to its respective Mongoose Model MeasureSchema.methods.initializeDataElements = function initializeDataElements() { let typeStripped; const sourceDataCriteriaInit = []; this.source_data_criteria.forEach((element) => { typeStripped = element._type.replace(/QDM::/, ''); sourceDataCriteriaInit.push(new AllDataElements[typeStripped](element)); }); this.set('source_data_criteria', sourceDataCriteriaInit); }; MeasureSchema.methods.all_stratifications = function all_stratifications() { return this.population_sets.flatMap(ps => ps.stratifications); }; module.exports.MeasureSchema = MeasureSchema; class Measure extends mongoose.Document { constructor(object) { super(object, MeasureSchema); this.initializeDataElements(); } } module.exports.Measure = Measure; },{"../AllDataElements":2,"../basetypes/Code":69,"../basetypes/DataElement":70,"../basetypes/Interval":72,"../basetypes/Quantity":74,"./CQLLibrary":76,"./PopulationSet":84,"mongoose/browser":184}],82:[function(require,module,exports){ const mongoose = require('mongoose/browser'); // using mBuffer to not conflict with system Buffer const [mBuffer, ObjectId] = [ mongoose.Schema.Types.Buffer, mongoose.Schema.Types.ObjectId, ]; const MeasurePackageSchema = new mongoose.Schema( { file: mBuffer, measure: { type: ObjectId, ref: 'Measure' }, }, // Options { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }, } ); module.exports.MeasurePackageSchema = MeasurePackageSchema; class MeasurePackage extends mongoose.Document { constructor(object) { super(object, MeasurePackageSchema); } } module.exports.MeasurePackage = MeasurePackage; },{"mongoose/browser":184}],83:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const { QDMPatientSchema, QDMPatient } = require('../QDMPatient'); const { ProviderSchema } = require('./Provider'); const [Schema, Number, String, Mixed] = [ mongoose.Schema, mongoose.Schema.Types.Number, mongoose.Schema.Types.String, mongoose.Schema.Types.Mixed, ]; const PatientSchema = new Schema({ givenNames: [String], familyName: String, bundleId: String, expectedValues: [], notes: String, qdmPatient: QDMPatientSchema, providers: [ProviderSchema], measure_ids: [String], }, { id: false }); module.exports.PatientSchema = PatientSchema; class Patient extends mongoose.Document { constructor(object) { super(object, PatientSchema); if (this.qdmPatient) { this.qdmPatient = new QDMPatient(this.qdmPatient.toJSON()); } } } module.exports.Patient = Patient; },{"../QDMPatient":49,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/Quantity":74,"./Provider":85,"mongoose/browser":184}],84:[function(require,module,exports){ /* eslint-disable no-unused-vars, no-param-reassign */ const mongoose = require('mongoose/browser'); const { StatementReferenceSchema } = require('./CQLStatementDependency'); const [Mixed] = [ mongoose.Schema.Types.Mixed, ]; // TODO: figure out if there is a better way to handle inheritance like mongoid. // _type is how mongoid stores the specific type of the embedded document. const PopulationMapSchema = new mongoose.Schema({ _type: String, IPP: StatementReferenceSchema, DENOM: StatementReferenceSchema, NUMER: StatementReferenceSchema, NUMEX: StatementReferenceSchema, DENEX: StatementReferenceSchema, DENEXCEP: StatementReferenceSchema, MSRPOPL: StatementReferenceSchema, MSRPOPLEX: StatementReferenceSchema, // STRAT is only here so cqm-execution can handle stratification results compliation with the current approach. STRAT: StatementReferenceSchema, }); if (!PopulationMapSchema.options.toObject) PopulationMapSchema.options.toObject = {}; PopulationMapSchema.options.toObject.transform = function transform(doc, ret, options) { // remove the _id and _type of every document before returning the result delete ret._id; delete ret._type; return ret; }; const StratificationSchema = new mongoose.Schema({ title: String, stratification_id: String, hqmf_id: String, statement: StatementReferenceSchema, }); const ObservationSchema = new mongoose.Schema({ title: String, observation_function: StatementReferenceSchema, observation_parameter: StatementReferenceSchema, aggregation_type: String, hqmf_id: String, }); const PopulationSetSchema = new mongoose.Schema({ title: String, population_set_id: String, populations: PopulationMapSchema, stratifications: [StratificationSchema], supplemental_data_elements: [StatementReferenceSchema], observations: [ObservationSchema], }); module.exports.StratificationSchema = StratificationSchema; class Stratification extends mongoose.Document { constructor(object) { super(object, StratificationSchema); } } module.exports.Stratification = Stratification; module.exports.ObservationSchema = ObservationSchema; class Observation extends mongoose.Document { constructor(object) { super(object, ObservationSchema); } } module.exports.Observation = Observation; module.exports.PopulationMapSchema = PopulationMapSchema; class PopulationMap extends mongoose.Document { constructor(object) { super(object, PopulationMapSchema); } } module.exports.PopulationMap = PopulationMap; module.exports.PopulationSetSchema = PopulationSetSchema; class PopulationSet extends mongoose.Document { constructor(object) { super(object, PopulationSetSchema); } } module.exports.PopulationSet = PopulationSet; },{"./CQLStatementDependency":77,"mongoose/browser":184}],85:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const [Schema, String, Boolean] = [ mongoose.Schema, mongoose.Schema.Types.String, mongoose.Schema.Types.Boolean, ]; const AddressSchema = new mongoose.Schema({ street: [String], city: String, state: String, zip: String, country: String, use: String, }); const TelecomSchema = new mongoose.Schema({ use: String, value: String, preferred: Boolean, }); const ProviderSchema = new Schema({ _type: { type: String, default: 'Provider' }, givenNames: [String], familyName: String, specialty: String, title: String, addresses: [AddressSchema], telecoms: [TelecomSchema], }, { id: false }); module.exports.ProviderSchema = ProviderSchema; class Provider extends mongoose.Document { constructor(object) { super(object, ProviderSchema); } } module.exports.Provider = Provider; },{"mongoose/browser":184}],86:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const [String, Mixed] = [ mongoose.Schema.Types.String, mongoose.Schema.Types.Mixed, ]; const StatementResultSchema = mongoose.Schema({ // Library the statement this result is for is in library_name: String, // Statement this result is for is in statement_name: String, // Result, processed for display, of the statement this result is for pretty: String, // Final, processed result of raw calculation final: String, // Raw result of clause calculation raw: Mixed, /* * 'NA' - Not applicable. This statement is not relevant to any population calculation in this population_set. Common * for unused library statements or statements only used for other population sets. * * 'FALSE' - This statement is not relevant to any of this patient's population inclusion calculations. * * 'TRUE' - This statement is relevant for one or more of the population inclusion calculations. */ relevance: { type: String, enum: ['NA', 'TRUE', 'FALSE'], default: 'NA', }, }); module.exports.StatementResultSchema = StatementResultSchema; class StatementResult extends mongoose.Document { constructor(object) { super(object, StatementResultSchema); } } module.exports.StatementResult = StatementResult; },{"mongoose/browser":184}],87:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const Concept = require('./Concept.js'); const [String] = [mongoose.Schema.Types.String]; const ValueSetSchema = new mongoose.Schema( { oid: String, display_name: String, version: String, concepts: [Concept.ConceptSchema], }, // Options { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }, } ); module.exports.ValueSetSchema = ValueSetSchema; class ValueSet extends mongoose.Document { constructor(object) { super(object, ValueSetSchema); } } module.exports.ValueSet = ValueSet; },{"./Concept.js":79,"mongoose/browser":184}],88:[function(require,module,exports){ module.exports = require('./AllDataElements.js'); module.exports.CQL = require('cql-execution'); module.exports.Result = require('./Result.js').Result; module.exports.ResultSchema = require('./Result.js').ResultSchema; module.exports.Measure = require('./cqm/Measure.js').Measure; module.exports.MeasureSchema = require('./cqm/Measure.js').MeasureSchema; module.exports.MeasurePackage = require('./cqm/MeasurePackage.js').MeasurePackage; module.exports.MeasurePackageSchema = require('./cqm/MeasurePackage.js').MeasurePackageSchema; module.exports.Patient = require('./cqm/Patient.js').Patient; module.exports.PatientSchema = require('./cqm/Patient.js').PatientSchema; module.exports.Provider = require('./cqm/Provider.js').Provider; module.exports.ProviderSchema = require('./cqm/Provider.js').ProviderSchema; module.exports.StatementDependency = require('./cqm/CQLStatementDependency.js').StatementDependency; module.exports.StatementDependencySchema = require('./cqm/CQLStatementDependency.js').StatementDependencySchema; module.exports.PopulationSet = require('./cqm/PopulationSet.js').PopulationSet; module.exports.PopulationSetSchema = require('./cqm/PopulationSet.js').PopulationSetSchema; module.exports.CQLLibrary = require('./cqm/CQLLibrary.js').CQLLibrary; module.exports.CQLLibrarySchema = require('./cqm/CQLLibrary.js').CQLLibrarySchema; module.exports.ValueSet = require('./cqm/ValueSet.js').ValueSet; module.exports.ValueSetSchema = require('./cqm/ValueSet.js').ValueSetSchema; module.exports.Concept = require('./cqm/Concept.js').Concept; module.exports.ConceptSchema = require('./cqm/Concept.js').ConceptSchema; module.exports.IndividualResult = require('./cqm/IndividualResult.js').IndividualResult; module.exports.IndividualResultSchema = require('./cqm/IndividualResult.js').IndividualResultSchema; module.exports.ClauseResult = require('./cqm/ClauseResult.js').ClauseResult; module.exports.ClauseResultSchema = require('./cqm/ClauseResult.js').ClauseResultSchema; module.exports.StatementResult = require('./cqm/StatementResult.js').StatementResult; module.exports.StatementResultSchema = require('./cqm/StatementResult.js').StatementResultchema; },{"./AllDataElements.js":2,"./Result.js":51,"./cqm/CQLLibrary.js":76,"./cqm/CQLStatementDependency.js":77,"./cqm/ClauseResult.js":78,"./cqm/Concept.js":79,"./cqm/IndividualResult.js":80,"./cqm/Measure.js":81,"./cqm/MeasurePackage.js":82,"./cqm/Patient.js":83,"./cqm/PopulationSet.js":84,"./cqm/Provider.js":85,"./cqm/StatementResult.js":86,"./cqm/ValueSet.js":87,"cql-execution":132}],89:[function(require,module,exports){ module.exports={"license":"The following data (prefixes and units) was generated by the UCUM LHC code from the UCUM data and selected LOINC combinations of UCUM units. The license for the UCUM LHC code (demo and library code as well as the combined units) is located at https://github.com/lhncbc/ucum-lhc/blob/LICENSE.md.","prefixes":{"config":["code_","ciCode_","name_","printSymbol_","value_","exp_"],"data":[["E","EX","exa","E",1000000000000000000,"18"],["G","GA","giga","G",1000000000,"9"],["Gi","GIB","gibi","Gi",1073741824,null],["Ki","KIB","kibi","Ki",1024,null],["M","MA","mega","M",1000000,"6"],["Mi","MIB","mebi","Mi",1048576,null],["P","PT","peta","P",1000000000000000,"15"],["T","TR","tera","T",1000000000000,"12"],["Ti","TIB","tebi","Ti",1099511627776,null],["Y","YA","yotta","Y",1e+24,"24"],["Z","ZA","zetta","Z",1e+21,"21"],["a","A","atto","a",1e-18,"-18"],["c","C","centi","c",0.01,"-2"],["d","D","deci","d",0.1,"-1"],["da","DA","deka","da",10,"1"],["f","F","femto","f",1e-15,"-15"],["h","H","hecto","h",100,"2"],["k","K","kilo","k",1000,"3"],["m","M","milli","m",0.001,"-3"],["n","N","nano","n",1e-9,"-9"],["p","P","pico","p",1e-12,"-12"],["u","U","micro","μ",0.000001,"-6"],["y","YO","yocto","y",1.0000000000000001e-24,"-24"],["z","ZO","zepto","z",1e-21,"-21"]]},"units":{"config":["isBase_","name_","csCode_","ciCode_","property_","magnitude_",["dim_","dimVec_"],"printSymbol_","class_","isMetric_","variable_","cnv_","cnvPfx_","isSpecial_","isArbitrary_","moleExp_","synonyms_","source_","loincProperty_","category_","guidance_","csUnitString_","ciUnitString_","baseFactorStr_","baseFactor_","defError_"],"data":[[true,"meter","m","M","length",1,[1,0,0,0,0,0,0],"m",null,false,"L",null,1,false,false,0,"meters; metres; distance","UCUM","Len","Clinical","unit of length = 1.09361 yards",null,null,null,null,false],[true,"second - time","s","S","time",1,[0,1,0,0,0,0,0],"s",null,false,"T",null,1,false,false,0,"seconds","UCUM","Time","Clinical","",null,null,null,null,false],[true,"gram","g","G","mass",1,[0,0,1,0,0,0,0],"g",null,false,"M",null,1,false,false,0,"grams; gm","UCUM","Mass","Clinical","",null,null,null,null,false],[true,"radian","rad","RAD","plane angle",1,[0,0,0,1,0,0,0],"rad",null,false,"A",null,1,false,false,0,"radians","UCUM","Angle","Clinical","unit of angular measure where 1 radian = 1/2π turn = 57.296 degrees. ",null,null,null,null,false],[true,"degree Kelvin","K","K","temperature",1,[0,0,0,0,1,0,0],"K",null,false,"C",null,1,false,false,0,"Kelvin; degrees","UCUM","Temp","Clinical","absolute, thermodynamic temperature scale ",null,null,null,null,false],[true,"coulomb","C","C","electric charge",1,[0,0,0,0,0,1,0],"C",null,false,"Q",null,1,false,false,0,"coulombs","UCUM","","Clinical","defined as amount of 1 electron charge = 6.2415093×10^18 e, and equivalent to 1 Ampere-second",null,null,null,null,false],[true,"candela","cd","CD","luminous intensity",1,[0,0,0,0,0,0,1],"cd",null,false,"F",null,1,false,false,0,"candelas","UCUM","","Clinical","SI base unit of luminous intensity",null,null,null,null,false],[false,"the number ten for arbitrary powers","10*","10*","number",10,[0,0,0,0,0,0,0],"10","dimless",false,null,null,1,false,false,0,"10^; 10 to the arbitrary powers","UCUM","Num","Clinical","10* by itself is the same as 10, but users can add digits after the *. For example, 10*3 = 1000.","1","1","10",10,false],[false,"the number ten for arbitrary powers","10^","10^","number",10,[0,0,0,0,0,0,0],"10","dimless",false,null,null,1,false,false,0,"10*; 10 to the arbitrary power","UCUM","Num","Clinical","10* by itself is the same as 10, but users can add digits after the *. For example, 10*3 = 1000.","1","1","10",10,false],[false,"the number pi","[pi]","[PI]","number",3.141592653589793,[0,0,0,0,0,0,0],"π","dimless",false,null,null,1,false,false,0,"π","UCUM","","Constant","a mathematical constant; the ratio of a circle's circumference to its diameter ≈ 3.14159","1","1","3.1415926535897932384626433832795028841971693993751058209749445923",3.141592653589793,false],[false,"","%","%","fraction",0.01,[0,0,0,0,0,0,0],"%","dimless",false,null,null,1,false,false,0,"percents","UCUM","FR; NFR; MFR; CFR; SFR Rto; etc. ","Clinical","","10*-2","10*-2","1",1,false],[false,"parts per thousand","[ppth]","[PPTH]","fraction",0.001,[0,0,0,0,0,0,0],"ppth","dimless",false,null,null,1,false,false,0,"ppth; 10^-3","UCUM","MCnc; MCnt","Clinical","[ppth] is often used in solution concentrations as 1 g/L or 1 g/kg.\n\nCan be ambigous and would be better if the metric units was used directly. ","10*-3","10*-3","1",1,false],[false,"parts per million","[ppm]","[PPM]","fraction",0.000001,[0,0,0,0,0,0,0],"ppm","dimless",false,null,null,1,false,false,0,"ppm; 10^-6","UCUM","MCnt; MCnc; SFr","Clinical","[ppm] is often used in solution concentrations as 1 mg/L or 1 mg/kg. Also used to express mole fractions as 1 mmol/mol.\n\n[ppm] is also used in nuclear magnetic resonance (NMR) to represent chemical shift - the difference of a measured frequency in parts per million from the reference frequency.\n\nCan be ambigous and would be better if the metric units was used directly. ","10*-6","10*-6","1",1,false],[false,"parts per billion","[ppb]","[PPB]","fraction",1e-9,[0,0,0,0,0,0,0],"ppb","dimless",false,null,null,1,false,false,0,"ppb; 10^-9","UCUM","MCnt; MCnc; SFr","Clinical","[ppb] is often used in solution concentrations as 1 ug/L or 1 ug/kg. Also used to express mole fractions as 1 umol/mol.\n\nCan be ambigous and would be better if the metric units was used directly. ","10*-9","10*-9","1",1,false],[false,"parts per trillion","[pptr]","[PPTR]","fraction",1e-12,[0,0,0,0,0,0,0],"pptr","dimless",false,null,null,1,false,false,0,"pptr; 10^-12","UCUM","MCnt; MCnc; SFr","Clinical","[pptr] is often used in solution concentrations as 1 ng/L or 1 ng/kg. Also used to express mole fractions as 1 nmol/mol.\n\nCan be ambigous and would be better if the metric units was used directly. ","10*-12","10*-12","1",1,false],[false,"mole","mol","MOL","amount of substance",6.0221367e+23,[0,0,0,0,0,0,0],"mol","si",true,null,null,1,false,false,1,"moles","UCUM","Sub","Clinical","Measure the number of molecules ","10*23","10*23","6.0221367",6.0221367,false],[false,"steradian - solid angle","sr","SR","solid angle",1,[0,0,0,2,0,0,0],"sr","si",true,null,null,1,false,false,0,"square radian; rad2; rad^2","UCUM","Angle","Clinical","unit of solid angle in three-dimensional geometry analagous to radian; used in photometry which measures the perceived brightness of object by human eye (e.g. radiant intensity = watt/steradian)","rad2","RAD2","1",1,false],[false,"hertz","Hz","HZ","frequency",1,[0,-1,0,0,0,0,0],"Hz","si",true,null,null,1,false,false,0,"Herz; frequency; frequencies","UCUM","Freq; Num","Clinical","equal to one cycle per second","s-1","S-1","1",1,false],[false,"newton","N","N","force",1000,[1,-2,1,0,0,0,0],"N","si",true,null,null,1,false,false,0,"Newtons","UCUM","Force","Clinical","unit of force with base units kg.m/s2","kg.m/s2","KG.M/S2","1",1,false],[false,"pascal","Pa","PAL","pressure",1000,[-1,-2,1,0,0,0,0],"Pa","si",true,null,null,1,false,false,0,"pascals","UCUM","Pres","Clinical","standard unit of pressure equal to 1 newton per square meter (N/m2)","N/m2","N/M2","1",1,false],[false,"joule","J","J","energy",1000,[2,-2,1,0,0,0,0],"J","si",true,null,null,1,false,false,0,"joules","UCUM","Enrg","Clinical","unit of energy defined as the work required to move an object 1 m with a force of 1 N (N.m) or an electric charge of 1 C through 1 V (C.V), or to produce 1 W for 1 s (W.s) ","N.m","N.M","1",1,false],[false,"watt","W","W","power",1000,[2,-3,1,0,0,0,0],"W","si",true,null,null,1,false,false,0,"watts","UCUM","EngRat","Clinical","unit of power equal to 1 Joule per second (J/s) = kg⋅m2⋅s−3","J/s","J/S","1",1,false],[false,"Ampere","A","A","electric current",1,[0,-1,0,0,0,1,0],"A","si",true,null,null,1,false,false,0,"Amperes","UCUM","ElpotRat","Clinical","unit of electric current equal to flow rate of electrons equal to 16.2415×10^18 elementary charges moving past a boundary in one second or 1 Coulomb/second","C/s","C/S","1",1,false],[false,"volt","V","V","electric potential",1000,[2,-2,1,0,0,-1,0],"V","si",true,null,null,1,false,false,0,"volts","UCUM","Elpot","Clinical","unit of electric potential (voltage) = 1 Joule per Coulomb (J/C)","J/C","J/C","1",1,false],[false,"farad","F","F","electric capacitance",0.001,[-2,2,-1,0,0,2,0],"F","si",true,null,null,1,false,false,0,"farads; electric capacitance","UCUM","","Clinical","CGS unit of electric capacitance with base units C/V (Coulomb per Volt)","C/V","C/V","1",1,false],[false,"ohm","Ohm","OHM","electric resistance",1000,[2,-1,1,0,0,-2,0],"Ω","si",true,null,null,1,false,false,0,"Ω; resistance; ohms","UCUM","","Clinical","unit of electrical resistance with units of Volt per Ampere","V/A","V/A","1",1,false],[false,"siemens","S","SIE","electric conductance",0.001,[-2,1,-1,0,0,2,0],"S","si",true,null,null,1,false,false,0,"Reciprocal ohm; mho; Ω−1; conductance","UCUM","","Clinical","unit of electric conductance (the inverse of electrical resistance) equal to ohm^-1","Ohm-1","OHM-1","1",1,false],[false,"weber","Wb","WB","magnetic flux",1000,[2,-1,1,0,0,-1,0],"Wb","si",true,null,null,1,false,false,0,"magnetic flux; webers","UCUM","","Clinical","unit of magnetic flux equal to Volt second","V.s","V.S","1",1,false],[false,"degree Celsius","Cel","CEL","temperature",1,[0,0,0,0,1,0,0],"°C","si",true,null,"Cel",1,true,false,0,"°C; degrees","UCUM","Temp","Clinical","","K",null,null,1,false],[false,"tesla","T","T","magnetic flux density",1000,[0,-1,1,0,0,-1,0],"T","si",true,null,null,1,false,false,0,"Teslas; magnetic field","UCUM","","Clinical","SI unit of magnetic field strength for magnetic field B equal to 1 Weber/square meter = 1 kg/(s2*A)","Wb/m2","WB/M2","1",1,false],[false,"henry","H","H","inductance",1000,[2,0,1,0,0,-2,0],"H","si",true,null,null,1,false,false,0,"henries; inductance","UCUM","","Clinical","unit of electrical inductance; usually expressed in millihenrys (mH) or microhenrys (uH).","Wb/A","WB/A","1",1,false],[false,"lumen","lm","LM","luminous flux",1,[0,0,0,2,0,0,1],"lm","si",true,null,null,1,false,false,0,"luminous flux; lumens","UCUM","","Clinical","unit of luminous flux defined as 1 lm = 1 cd⋅sr (candela times sphere)","cd.sr","CD.SR","1",1,false],[false,"lux","lx","LX","illuminance",1,[-2,0,0,2,0,0,1],"lx","si",true,null,null,1,false,false,0,"illuminance; luxes","UCUM","","Clinical","unit of illuminance equal to one lumen per square meter. ","lm/m2","LM/M2","1",1,false],[false,"becquerel","Bq","BQ","radioactivity",1,[0,-1,0,0,0,0,0],"Bq","si",true,null,null,1,false,false,0,"activity; radiation; becquerels","UCUM","","Clinical","measure of the atomic radiation rate with units s^-1","s-1","S-1","1",1,false],[false,"gray","Gy","GY","energy dose",1,[2,-2,0,0,0,0,0],"Gy","si",true,null,null,1,false,false,0,"absorbed doses; ionizing radiation doses; kerma; grays","UCUM","EngCnt","Clinical","unit of ionizing radiation dose with base units of 1 joule of radiation energy per kilogram of matter","J/kg","J/KG","1",1,false],[false,"sievert","Sv","SV","dose equivalent",1,[2,-2,0,0,0,0,0],"Sv","si",true,null,null,1,false,false,0,"sieverts; radiation dose quantities; equivalent doses; effective dose; operational dose; committed dose","UCUM","","Clinical","SI unit for radiation dose equivalent equal to 1 Joule/kilogram.","J/kg","J/KG","1",1,false],[false,"degree - plane angle","deg","DEG","plane angle",0.017453292519943295,[0,0,0,1,0,0,0],"°","iso1000",false,null,null,1,false,false,0,"°; degree of arc; arc degree; arcdegree; angle","UCUM","Angle","Clinical","one degree is equivalent to π/180 radians.","[pi].rad/360","[PI].RAD/360","2",2,false],[false,"gon","gon","GON","plane angle",0.015707963267948967,[0,0,0,1,0,0,0],"□g","iso1000",false,null,null,1,false,false,0,"gon (grade); gons","UCUM","Angle","Nonclinical","unit of plane angle measurement equal to 1/400 circle","deg","DEG","0.9",0.9,false],[false,"arc minute","'","'","plane angle",0.0002908882086657216,[0,0,0,1,0,0,0],"'","iso1000",false,null,null,1,false,false,0,"arcminutes; arcmin; arc minutes; arc mins","UCUM","Angle","Clinical","equal to 1/60 degree; used in optometry and opthamology (e.g. visual acuity tests)","deg/60","DEG/60","1",1,false],[false,"arc second","''","''","plane angle",0.00000484813681109536,[0,0,0,1,0,0,0],"''","iso1000",false,null,null,1,false,false,0,"arcseconds; arcsecs","UCUM","Angle","Clinical","equal to 1/60 arcminute = 1/3600 degree; used in optometry and opthamology (e.g. visual acuity tests)","'/60","'/60","1",1,false],[false,"Liters","l","L","volume",0.001,[3,0,0,0,0,0,0],"l","iso1000",true,null,null,1,false,false,0,"cubic decimeters; decimeters cubed; decimetres; dm3; dm^3; litres; liters, LT ","UCUM","Vol","Clinical","Because lower case \"l\" can be read as the number \"1\", though this is a valid UCUM units. UCUM strongly reccomends using \"L\"","dm3","DM3","1",1,false],[false,"Liters","L","L","volume",0.001,[3,0,0,0,0,0,0],"L","iso1000",true,null,null,1,false,false,0,"cubic decimeters; decimeters cubed; decimetres; dm3; dm^3; litres; liters, LT ","UCUM","Vol","Clinical","Because lower case \"l\" can be read as the number \"1\", though this is a valid UCUM units. UCUM strongly reccomends using \"L\"","l",null,"1",1,false],[false,"are","ar","AR","area",100,[2,0,0,0,0,0,0],"a","iso1000",true,null,null,1,false,false,0,"100 m2; 100 m^2; 100 square meter; meters squared; metres","UCUM","Area","Clinical","metric base unit for area defined as 100 m^2","m2","M2","100",100,false],[false,"minute","min","MIN","time",60,[0,1,0,0,0,0,0],"min","iso1000",false,null,null,1,false,false,0,"minutes","UCUM","Time","Clinical","","s","S","60",60,false],[false,"hour","h","HR","time",3600,[0,1,0,0,0,0,0],"h","iso1000",false,null,null,1,false,false,0,"hours; hrs; age","UCUM","Time","Clinical","","min","MIN","60",60,false],[false,"day","d","D","time",86400,[0,1,0,0,0,0,0],"d","iso1000",false,null,null,1,false,false,0,"days; age; dy; 24 hours; 24 hrs","UCUM","Time","Clinical","","h","HR","24",24,false],[false,"tropical year","a_t","ANN_T","time",31556925.216,[0,1,0,0,0,0,0],"at","iso1000",false,null,null,1,false,false,0,"solar years; a tropical; years","UCUM","Time","Clinical","has an average of 365.242181 days but is constantly changing.","d","D","365.24219",365.24219,false],[false,"mean Julian year","a_j","ANN_J","time",31557600,[0,1,0,0,0,0,0],"aj","iso1000",false,null,null,1,false,false,0,"mean Julian yr; a julian; years","UCUM","Time","Clinical","has an average of 365.25 days, and in everyday use, has been replaced by the Gregorian year. However, this unit is used in astronomy to calculate light year. ","d","D","365.25",365.25,false],[false,"mean Gregorian year","a_g","ANN_G","time",31556952,[0,1,0,0,0,0,0],"ag","iso1000",false,null,null,1,false,false,0,"mean Gregorian yr; a gregorian; years","UCUM","Time","Clinical","has an average of 365.2425 days and is the most internationally used civil calendar.","d","D","365.2425",365.2425,false],[false,"year","a","ANN","time",31557600,[0,1,0,0,0,0,0],"a","iso1000",false,null,null,1,false,false,0,"years; a; yr, yrs; annum","UCUM","Time","Clinical","","a_j","ANN_J","1",1,false],[false,"week","wk","WK","time",604800,[0,1,0,0,0,0,0],"wk","iso1000",false,null,null,1,false,false,0,"weeks; wks","UCUM","Time","Clinical","","d","D","7",7,false],[false,"synodal month","mo_s","MO_S","time",2551442.976,[0,1,0,0,0,0,0],"mos","iso1000",false,null,null,1,false,false,0,"Moon; synodic month; lunar month; mo-s; mo s; months; moons","UCUM","Time","Nonclinical","has an average of 29.53 days per month, unit used in astronomy","d","D","29.53059",29.53059,false],[false,"mean Julian month","mo_j","MO_J","time",2629800,[0,1,0,0,0,0,0],"moj","iso1000",false,null,null,1,false,false,0,"mo-julian; mo Julian; months","UCUM","Time","Clinical","has an average of 30.435 days per month","a_j/12","ANN_J/12","1",1,false],[false,"mean Gregorian month","mo_g","MO_G","time",2629746,[0,1,0,0,0,0,0],"mog","iso1000",false,null,null,1,false,false,0,"months; month-gregorian; mo-gregorian","UCUM","Time","Clinical","has an average 30.436875 days per month and is from the most internationally used civil calendar.","a_g/12","ANN_G/12","1",1,false],[false,"month","mo","MO","time",2629800,[0,1,0,0,0,0,0],"mo","iso1000",false,null,null,1,false,false,0,"months; duration","UCUM","Time","Clinical","based on Julian calendar which has an average of 30.435 days per month (this unit is used in astronomy but not in everyday life - see mo_g)","mo_j","MO_J","1",1,false],[false,"metric ton","t","TNE","mass",1000000,[0,0,1,0,0,0,0],"t","iso1000",true,null,null,1,false,false,0,"tonnes; megagrams; tons","UCUM","Mass","Nonclinical","equal to 1000 kg used in the US (recognized by NIST as metric ton), and internationally (recognized as tonne)","kg","KG","1e3",1000,false],[false,"bar","bar","BAR","pressure",100000000,[-1,-2,1,0,0,0,0],"bar","iso1000",true,null,null,1,false,false,0,"bars","UCUM","Pres","Nonclinical","unit of pressure equal to 10^5 Pascals, primarily used by meteorologists and in weather forecasting","Pa","PAL","1e5",100000,false],[false,"unified atomic mass unit","u","AMU","mass",1.6605402e-24,[0,0,1,0,0,0,0],"u","iso1000",true,null,null,1,false,false,0,"unified atomic mass units; amu; Dalton; Da","UCUM","Mass","Clinical","the mass of 1/12 of an unbound Carbon-12 atom nuclide equal to 1.6606x10^-27 kg ","g","G","1.6605402e-24",1.6605402e-24,false],[false,"astronomic unit","AU","ASU","length",149597870691,[1,0,0,0,0,0,0],"AU","iso1000",false,null,null,1,false,false,0,"AU; units","UCUM","Len","Clinical","unit of length used in astronomy for measuring distance in Solar system","Mm","MAM","149597.870691",149597.870691,false],[false,"parsec","pc","PRS","length",30856780000000000,[1,0,0,0,0,0,0],"pc","iso1000",true,null,null,1,false,false,0,"parsecs","UCUM","Len","Clinical","unit of length equal to 3.26 light years, nad used to measure large distances to objects outside our Solar System","m","M","3.085678e16",30856780000000000,false],[false,"velocity of light in a vacuum","[c]","[C]","velocity",299792458,[1,-1,0,0,0,0,0],"c","const",true,null,null,1,false,false,0,"speed of light","UCUM","Vel","Constant","equal to 299792458 m/s (approximately 3 x 10^8 m/s)","m/s","M/S","299792458",299792458,false],[false,"Planck constant","[h]","[H]","action",6.6260755e-31,[2,-1,1,0,0,0,0],"h","const",true,null,null,1,false,false,0,"Planck's constant","UCUM","","Constant","constant = 6.62607004 × 10-34 m2.kg/s; defined as quantum of action","J.s","J.S","6.6260755e-34",6.6260755e-34,false],[false,"Boltzmann constant","[k]","[K]","(unclassified)",1.380658e-20,[2,-2,1,0,-1,0,0],"k","const",true,null,null,1,false,false,0,"k; kB","UCUM","","Constant","physical constant relating energy at the individual particle level with temperature = 1.38064852 ×10^−23 J/K","J/K","J/K","1.380658e-23",1.380658e-23,false],[false,"permittivity of vacuum - electric","[eps_0]","[EPS_0]","electric permittivity",8.854187817000001e-15,[-3,2,-1,0,0,2,0],"ε0","const",true,null,null,1,false,false,0,"ε0; Electric Constant; vacuum permittivity; permittivity of free space ","UCUM","","Constant","approximately equal to 8.854 × 10^−12 F/m (farads per meter)","F/m","F/M","8.854187817e-12",8.854187817e-12,false],[false,"permeability of vacuum - magnetic","[mu_0]","[MU_0]","magnetic permeability",0.0012566370614359172,[1,0,1,0,0,-2,0],"μ0","const",true,null,null,1,false,false,0,"μ0; vacuum permeability; permeability of free space; magnetic constant","UCUM","","Constant","equal to 4π×10^−7 N/A2 (Newtons per square ampere) ≈ 1.2566×10^−6 H/m (Henry per meter)","N/A2","4.[PI].10*-7.N/A2","1",0.0000012566370614359173,false],[false,"elementary charge","[e]","[E]","electric charge",1.60217733e-19,[0,0,0,0,0,1,0],"e","const",true,null,null,1,false,false,0,"e; q; electric charges","UCUM","","Constant","the magnitude of the electric charge carried by a single electron or proton ≈ 1.60217×10^-19 Coulombs","C","C","1.60217733e-19",1.60217733e-19,false],[false,"electronvolt","eV","EV","energy",1.60217733e-16,[2,-2,1,0,0,0,0],"eV","iso1000",true,null,null,1,false,false,0,"Electron Volts; electronvolts","UCUM","Eng","Clinical","unit of kinetic energy = 1 V * 1.602×10^−19 C = 1.6×10−19 Joules","[e].V","[E].V","1",1,false],[false,"electron mass","[m_e]","[M_E]","mass",9.1093897e-28,[0,0,1,0,0,0,0],"me","const",true,null,null,1,false,false,0,"electron rest mass; me","UCUM","Mass","Constant","approximately equal to 9.10938356 × 10-31 kg; defined as the mass of a stationary electron","g","g","9.1093897e-28",9.1093897e-28,false],[false,"proton mass","[m_p]","[M_P]","mass",1.6726231e-24,[0,0,1,0,0,0,0],"mp","const",true,null,null,1,false,false,0,"mp; masses","UCUM","Mass","Constant","approximately equal to 1.672622×10−27 kg","g","g","1.6726231e-24",1.6726231e-24,false],[false,"Newtonian constant of gravitation","[G]","[GC]","(unclassified)",6.67259e-14,[3,-2,-1,0,0,0,0],"G","const",true,null,null,1,false,false,0,"G; gravitational constant; Newton's constant","UCUM","","Constant","gravitational constant = 6.674×10−11 N⋅m2/kg2","m3.kg-1.s-2","M3.KG-1.S-2","6.67259e-11",6.67259e-11,false],[false,"standard acceleration of free fall","[g]","[G]","acceleration",9.80665,[1,-2,0,0,0,0,0],"gn","const",true,null,null,1,false,false,0,"standard gravity; g; ɡ0; ɡn","UCUM","Accel","Constant","defined by standard = 9.80665 m/s2","m/s2","M/S2","980665e-5",9.80665,false],[false,"Torr","Torr","Torr","pressure",133322,[-1,-2,1,0,0,0,0],"Torr","const",false,null,null,1,false,false,0,"torrs","UCUM","Pres","Clinical","1 torr = 1 mmHg; unit used to measure blood pressure","Pa","PAL","133.322",133.322,false],[false,"standard atmosphere","atm","ATM","pressure",101325000,[-1,-2,1,0,0,0,0],"atm","const",false,null,null,1,false,false,0,"reference pressure; atmos; std atmosphere","UCUM","Pres","Clinical","defined as being precisely equal to 101,325 Pa","Pa","PAL","101325",101325,false],[false,"light-year","[ly]","[LY]","length",9460730472580800,[1,0,0,0,0,0,0],"l.y.","const",true,null,null,1,false,false,0,"light years; ly","UCUM","Len","Constant","unit of astronomal distance = 5.88×10^12 mi","[c].a_j","[C].ANN_J","1",1,false],[false,"gram-force","gf","GF","force",9.80665,[1,-2,1,0,0,0,0],"gf","const",true,null,null,1,false,false,0,"Newtons; gram forces","UCUM","Force","Clinical","May be specific to unit related to cardiac output","g.[g]","G.[G]","1",1,false],[false,"Kayser","Ky","KY","lineic number",100,[-1,0,0,0,0,0,0],"K","cgs",true,null,null,1,false,false,0,"wavenumbers; kaysers","UCUM","InvLen","Clinical","unit of wavelength equal to cm^-1","cm-1","CM-1","1",1,false],[false,"Gal","Gal","GL","acceleration",0.01,[1,-2,0,0,0,0,0],"Gal","cgs",true,null,null,1,false,false,0,"galileos; Gals","UCUM","Accel","Clinical","unit of acceleration used in gravimetry; equivalent to cm/s2 ","cm/s2","CM/S2","1",1,false],[false,"dyne","dyn","DYN","force",0.01,[1,-2,1,0,0,0,0],"dyn","cgs",true,null,null,1,false,false,0,"dynes","UCUM","Force","Clinical","unit of force equal to 10^-5 Newtons","g.cm/s2","G.CM/S2","1",1,false],[false,"erg","erg","ERG","energy",0.0001,[2,-2,1,0,0,0,0],"erg","cgs",true,null,null,1,false,false,0,"10^-7 Joules, 10-7 Joules; 100 nJ; 100 nanoJoules; 1 dyne cm; 1 g.cm2/s2","UCUM","Eng","Clinical","unit of energy = 1 dyne centimeter = 10^-7 Joules","dyn.cm","DYN.CM","1",1,false],[false,"Poise","P","P","dynamic viscosity",100,[-1,-1,1,0,0,0,0],"P","cgs",true,null,null,1,false,false,0,"dynamic viscosity; poises","UCUM","Visc","Clinical","unit of dynamic viscosity where 1 Poise = 1/10 Pascal second","dyn.s/cm2","DYN.S/CM2","1",1,false],[false,"Biot","Bi","BI","electric current",10,[0,-1,0,0,0,1,0],"Bi","cgs",true,null,null,1,false,false,0,"Bi; abamperes; abA","UCUM","ElpotRat","Clinical","equal to 10 amperes","A","A","10",10,false],[false,"Stokes","St","ST","kinematic viscosity",0.0001,[2,-1,0,0,0,0,0],"St","cgs",true,null,null,1,false,false,0,"kinematic viscosity","UCUM","Visc","Clinical","unit of kimematic viscosity with units cm2/s","cm2/s","CM2/S","1",1,false],[false,"Maxwell","Mx","MX","flux of magnetic induction",0.00001,[2,-1,1,0,0,-1,0],"Mx","cgs",true,null,null,1,false,false,0,"magnetix flux; Maxwells","UCUM","","Clinical","unit of magnetic flux","Wb","WB","1e-8",1e-8,false],[false,"Gauss","G","GS","magnetic flux density",0.1,[0,-1,1,0,0,-1,0],"Gs","cgs",true,null,null,1,false,false,0,"magnetic fields; magnetic flux density; induction; B","UCUM","magnetic","Clinical","CGS unit of magnetic flux density, known as magnetic field B; defined as one maxwell unit per square centimeter (see Oersted for CGS unit for H field)","T","T","1e-4",0.0001,false],[false,"Oersted","Oe","OE","magnetic field intensity",79.57747154594767,[-1,-1,0,0,0,1,0],"Oe","cgs",true,null,null,1,false,false,0,"H magnetic B field; Oersteds","UCUM","","Clinical","CGS unit of the auxiliary magnetic field H defined as 1 dyne per unit pole = 1000/4π amperes per meter (see Gauss for CGS unit for B field)","A/m","/[PI].A/M","250",79.57747154594767,false],[false,"Gilbert","Gb","GB","magnetic tension",0.7957747154594768,[0,-1,0,0,0,1,0],"Gb","cgs",true,null,null,1,false,false,0,"Gi; magnetomotive force; Gilberts","UCUM","","Clinical","unit of magnetomotive force (magnetic potential)","Oe.cm","OE.CM","1",1,false],[false,"stilb","sb","SB","lum. intensity density",10000,[-2,0,0,0,0,0,1],"sb","cgs",true,null,null,1,false,false,0,"stilbs","UCUM","","Obsolete","unit of luminance; equal to and replaced by unit candela per square centimeter (cd/cm2)","cd/cm2","CD/CM2","1",1,false],[false,"Lambert","Lmb","LMB","brightness",3183.098861837907,[-2,0,0,0,0,0,1],"L","cgs",true,null,null,1,false,false,0,"luminance; lamberts","UCUM","","Clinical","unit of luminance defined as 1 lambert = 1/ π candela per square meter","cd/cm2/[pi]","CD/CM2/[PI]","1",1,false],[false,"phot","ph","PHT","illuminance",0.0001,[-2,0,0,2,0,0,1],"ph","cgs",true,null,null,1,false,false,0,"phots","UCUM","","Clinical","CGS photometric unit of illuminance, or luminous flux through an area equal to 10000 lumens per square meter = 10000 lux","lx","LX","1e-4",0.0001,false],[false,"Curie","Ci","CI","radioactivity",37000000000,[0,-1,0,0,0,0,0],"Ci","cgs",true,null,null,1,false,false,0,"curies","UCUM","","Obsolete","unit for measuring atomic disintegration rate; replaced by the Bequerel (Bq) unit","Bq","BQ","37e9",37000000000,false],[false,"Roentgen","R","ROE","ion dose",2.58e-7,[0,0,-1,0,0,1,0],"R","cgs",true,null,null,1,false,false,0,"röntgen; Roentgens","UCUM","","Clinical","unit of exposure of X-rays and gamma rays in air; unit used primarily in the US but strongly discouraged by NIST","C/kg","C/KG","2.58e-4",0.000258,false],[false,"radiation absorbed dose","RAD","[RAD]","energy dose",0.01,[2,-2,0,0,0,0,0],"RAD","cgs",true,null,null,1,false,false,0,"doses","UCUM","","Clinical","unit of radiation absorbed dose used primarily in the US with base units 100 ergs per gram of material. Also see the SI unit Gray (Gy).","erg/g","ERG/G","100",100,false],[false,"radiation equivalent man","REM","[REM]","dose equivalent",0.01,[2,-2,0,0,0,0,0],"REM","cgs",true,null,null,1,false,false,0,"Roentgen Equivalent in Man; rems; dose equivalents","UCUM","","Clinical","unit of equivalent dose which measures the effect of radiation on humans equal to 0.01 sievert. Used primarily in the US. Also see SI unit Sievert (Sv)","RAD","[RAD]","1",1,false],[false,"inch","[in_i]","[IN_I]","length",0.025400000000000002,[1,0,0,0,0,0,0],"in","intcust",false,null,null,1,false,false,0,"inches; in; international inch; body height","UCUM","Len","Clinical","standard unit for inch in the US and internationally","cm","CM","254e-2",2.54,false],[false,"foot","[ft_i]","[FT_I]","length",0.3048,[1,0,0,0,0,0,0],"ft","intcust",false,null,null,1,false,false,0,"ft; fts; foot; international foot; feet; international feet; height","UCUM","Len","Clinical","unit used in the US and internationally","[in_i]","[IN_I]","12",12,false],[false,"yard","[yd_i]","[YD_I]","length",0.9144000000000001,[1,0,0,0,0,0,0],"yd","intcust",false,null,null,1,false,false,0,"international yards; yds; distance","UCUM","Len","Clinical","standard unit used in the US and internationally","[ft_i]","[FT_I]","3",3,false],[false,"mile","[mi_i]","[MI_I]","length",1609.344,[1,0,0,0,0,0,0],"mi","intcust",false,null,null,1,false,false,0,"international miles; mi I; statute mile","UCUM","Len","Clinical","standard unit used in the US and internationally","[ft_i]","[FT_I]","5280",5280,false],[false,"fathom","[fth_i]","[FTH_I]","depth of water",1.8288000000000002,[1,0,0,0,0,0,0],"fth","intcust",false,null,null,1,false,false,0,"international fathoms","UCUM","Len","Nonclinical","unit used in the US and internationally to measure depth of water; same length as the US fathom","[ft_i]","[FT_I]","6",6,false],[false,"nautical mile","[nmi_i]","[NMI_I]","length",1852,[1,0,0,0,0,0,0],"n.mi","intcust",false,null,null,1,false,false,0,"nautical mile; nautical miles; international nautical mile; international nautical miles; nm; n.m.; nmi","UCUM","Len","Nonclinical","standard unit used in the US and internationally","m","M","1852",1852,false],[false,"knot","[kn_i]","[KN_I]","velocity",0.5144444444444445,[1,-1,0,0,0,0,0],"knot","intcust",false,null,null,1,false,false,0,"kn; kt; international knots","UCUM","Vel","Nonclinical","defined as equal to one nautical mile (1.852 km) per hour","[nmi_i]/h","[NMI_I]/H","1",1,false],[false,"square inch","[sin_i]","[SIN_I]","area",0.0006451600000000001,[2,0,0,0,0,0,0],null,"intcust",false,null,null,1,false,false,0,"in2; in^2; inches squared; sq inch; inches squared; international","UCUM","Area","Clinical","standard unit used in the US and internationally","[in_i]2","[IN_I]2","1",1,false],[false,"square foot","[sft_i]","[SFT_I]","area",0.09290304,[2,0,0,0,0,0,0],null,"intcust",false,null,null,1,false,false,0,"ft2; ft^2; ft squared; sq ft; feet; international","UCUM","Area","Clinical","standard unit used in the US and internationally","[ft_i]2","[FT_I]2","1",1,false],[false,"square yard","[syd_i]","[SYD_I]","area",0.8361273600000002,[2,0,0,0,0,0,0],null,"intcust",false,null,null,1,false,false,0,"yd2; yd^2; sq. yds; yards squared; international","UCUM","Area","Clinical","standard unit used in the US and internationally","[yd_i]2","[YD_I]2","1",1,false],[false,"cubic inch","[cin_i]","[CIN_I]","volume",0.000016387064000000003,[3,0,0,0,0,0,0],null,"intcust",false,null,null,1,false,false,0,"in3; in^3; in*3; inches^3; inches*3; cu. in; cu in; cubic inches; inches cubed; cin","UCUM","Vol","Clinical","standard unit used in the US and internationally","[in_i]3","[IN_I]3","1",1,false],[false,"cubic foot","[cft_i]","[CFT_I]","volume",0.028316846592000004,[3,0,0,0,0,0,0],null,"intcust",false,null,null,1,false,false,0,"ft3; ft^3; ft*3; cu. ft; cubic feet; cubed; [ft_i]3; international","UCUM","Vol","Clinical","","[ft_i]3","[FT_I]3","1",1,false],[false,"cubic yard","[cyd_i]","[CYD_I]","volume",0.7645548579840002,[3,0,0,0,0,0,0],"cu.yd","intcust",false,null,null,1,false,false,0,"cubic yards; cubic yds; cu yards; CYs; yards^3; yd^3; yds^3; yd3; yds3","UCUM","Vol","Nonclinical","standard unit used in the US and internationally","[yd_i]3","[YD_I]3","1",1,false],[false,"board foot","[bf_i]","[BF_I]","volume",0.002359737216,[3,0,0,0,0,0,0],null,"intcust",false,null,null,1,false,false,0,"BDFT; FBM; BF; board feet; international","UCUM","Vol","Nonclinical","unit of volume used to measure lumber","[in_i]3","[IN_I]3","144",144,false],[false,"cord","[cr_i]","[CR_I]","volume",3.6245563637760005,[3,0,0,0,0,0,0],null,"intcust",false,null,null,1,false,false,0,"crd I; international cords","UCUM","Vol","Nonclinical","unit of measure of dry volume used to measure firewood equal 128 ft3","[ft_i]3","[FT_I]3","128",128,false],[false,"mil","[mil_i]","[MIL_I]","length",0.000025400000000000004,[1,0,0,0,0,0,0],"mil","intcust",false,null,null,1,false,false,0,"thou, thousandth; mils; international","UCUM","Len","Clinical","equal to 0.001 international inch","[in_i]","[IN_I]","1e-3",0.001,false],[false,"circular mil","[cml_i]","[CML_I]","area",5.067074790974979e-10,[2,0,0,0,0,0,0],"circ.mil","intcust",false,null,null,1,false,false,0,"circular mils; cml I; international","UCUM","Area","Clinical","","[pi]/4.[mil_i]2","[PI]/4.[MIL_I]2","1",1,false],[false,"hand","[hd_i]","[HD_I]","height of horses",0.10160000000000001,[1,0,0,0,0,0,0],"hd","intcust",false,null,null,1,false,false,0,"hands; international","UCUM","Len","Nonclinical","used to measure horse height","[in_i]","[IN_I]","4",4,false],[false,"foot - US","[ft_us]","[FT_US]","length",0.3048006096012192,[1,0,0,0,0,0,0],"ftus","us-lengths",false,null,null,1,false,false,0,"US foot; foot US; us ft; ft us; height; visual distance; feet","UCUM","Len","Obsolete","Better to use [ft_i] which refers to the length used worldwide, including in the US; [ft_us] may be confused with land survey units. ","m/3937","M/3937","1200",1200,false],[false,"yard - US","[yd_us]","[YD_US]","length",0.9144018288036575,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,"US yards; us yds; distance","UCUM","Len; Nrat","Obsolete","Better to use [yd_i] which refers to the length used worldwide, including in the US; [yd_us] refers to unit used in land surveys in the US","[ft_us]","[FT_US]","3",3,false],[false,"inch - US","[in_us]","[IN_US]","length",0.0254000508001016,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,"US inches; in us; us in; inch US","UCUM","Len","Obsolete","Better to use [in_i] which refers to the length used worldwide, including in the US","[ft_us]/12","[FT_US]/12","1",1,false],[false,"rod - US","[rd_us]","[RD_US]","length",5.029210058420117,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,"US rod; US rods; rd US; US rd","UCUM","Len","Obsolete","","[ft_us]","[FT_US]","16.5",16.5,false],[false,"Gunter's chain - US","[ch_us]","[CH_US]","length",20.116840233680467,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,"surveyor's chain; Surveyor's chain USA; Gunter’s measurement; surveyor’s measurement; Gunter's Chain USA","UCUM","Len","Obsolete","historical unit used for land survey used only in the US","[rd_us]","[RD_US]","4",4,false],[false,"link for Gunter's chain - US","[lk_us]","[LK_US]","length",0.20116840233680466,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,"Links for Gunter's Chain USA","UCUM","Len","Obsolete","","[ch_us]/100","[CH_US]/100","1",1,false],[false,"Ramden's chain - US","[rch_us]","[RCH_US]","length",30.480060960121918,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,"Ramsden's chain; engineer's chains","UCUM","Len","Obsolete","distance measuring device used for land survey","[ft_us]","[FT_US]","100",100,false],[false,"link for Ramden's chain - US","[rlk_us]","[RLK_US]","length",0.3048006096012192,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,"links for Ramsden's chain","UCUM","Len","Obsolete","","[rch_us]/100","[RCH_US]/100","1",1,false],[false,"fathom - US","[fth_us]","[FTH_US]","length",1.828803657607315,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,"US fathoms; fathom USA; fth us","UCUM","Len","Obsolete","same length as the international fathom - better to use international fathom ([fth_i])","[ft_us]","[FT_US]","6",6,false],[false,"furlong - US","[fur_us]","[FUR_US]","length",201.16840233680466,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,"US furlongs; fur us","UCUM","Len","Nonclinical","distance unit in horse racing","[rd_us]","[RD_US]","40",40,false],[false,"mile - US","[mi_us]","[MI_US]","length",1609.3472186944373,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,"U.S. Survey Miles; US statute miles; survey mi; US mi; distance","UCUM","Len","Nonclinical","Better to use [mi_i] which refers to the length used worldwide, including in the US","[fur_us]","[FUR_US]","8",8,false],[false,"acre - US","[acr_us]","[ACR_US]","area",4046.872609874252,[2,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,"Acre USA Survey; Acre USA; survey acres","UCUM","Area","Nonclinical","an older unit based on pre 1959 US statute lengths that is still sometimes used in the US only for land survey purposes. ","[rd_us]2","[RD_US]2","160",160,false],[false,"square rod - US","[srd_us]","[SRD_US]","area",25.292953811714074,[2,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,"rod2; rod^2; sq. rod; rods squared","UCUM","Area","Nonclinical","Used only in the US to measure land area, based on US statute land survey length units","[rd_us]2","[RD_US]2","1",1,false],[false,"square mile - US","[smi_us]","[SMI_US]","area",2589998.470319521,[2,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,"mi2; mi^2; sq mi; miles squared","UCUM","Area","Nonclinical","historical unit used only in the US for land survey purposes (based on the US survey mile), not the internationally recognized [mi_i]","[mi_us]2","[MI_US]2","1",1,false],[false,"section","[sct]","[SCT]","area",2589998.470319521,[2,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,"sct; sections","UCUM","Area","Nonclinical","tract of land approximately equal to 1 mile square containing 640 acres","[mi_us]2","[MI_US]2","1",1,false],[false,"township","[twp]","[TWP]","area",93239944.93150276,[2,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,"twp; townships","UCUM","Area","Nonclinical","land measurement equal to 6 mile square","[sct]","[SCT]","36",36,false],[false,"mil - US","[mil_us]","[MIL_US]","length",0.0000254000508001016,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,"thou, thousandth; mils","UCUM","Len","Obsolete","better to use [mil_i] which is based on the internationally recognized inch","[in_us]","[IN_US]","1e-3",0.001,false],[false,"inch - British","[in_br]","[IN_BR]","length",0.025399980000000003,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,"imperial inches; imp in; br in; british inches","UCUM","Len","Obsolete","","cm","CM","2.539998",2.539998,false],[false,"foot - British","[ft_br]","[FT_BR]","length",0.30479976000000003,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,"British Foot; Imperial Foot; feet; imp fts; br fts","UCUM","Len","Obsolete","","[in_br]","[IN_BR]","12",12,false],[false,"rod - British","[rd_br]","[RD_BR]","length",5.02919604,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,"British rods; br rd","UCUM","Len","Obsolete","","[ft_br]","[FT_BR]","16.5",16.5,false],[false,"Gunter's chain - British","[ch_br]","[CH_BR]","length",20.11678416,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,"Gunter's Chain British; Gunters Chain British; Surveyor's Chain British","UCUM","Len","Obsolete","historical unit used for land survey used only in Great Britain","[rd_br]","[RD_BR]","4",4,false],[false,"link for Gunter's chain - British","[lk_br]","[LK_BR]","length",0.2011678416,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,"Links for Gunter's Chain British","UCUM","Len","Obsolete","","[ch_br]/100","[CH_BR]/100","1",1,false],[false,"fathom - British","[fth_br]","[FTH_BR]","length",1.82879856,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,"British fathoms; imperial fathoms; br fth; imp fth","UCUM","Len","Obsolete","","[ft_br]","[FT_BR]","6",6,false],[false,"pace - British","[pc_br]","[PC_BR]","length",0.7619994000000001,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,"British paces; br pc","UCUM","Len","Nonclinical","traditional unit of length equal to 152.4 centimeters, or 1.52 meter. ","[ft_br]","[FT_BR]","2.5",2.5,false],[false,"yard - British","[yd_br]","[YD_BR]","length",0.91439928,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,"British yards; Br yds; distance","UCUM","Len","Obsolete","","[ft_br]","[FT_BR]","3",3,false],[false,"mile - British","[mi_br]","[MI_BR]","length",1609.3427328000002,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,"imperial miles; British miles; English statute miles; imp mi, br mi","UCUM","Len","Obsolete","","[ft_br]","[FT_BR]","5280",5280,false],[false,"nautical mile - British","[nmi_br]","[NMI_BR]","length",1853.1825408000002,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,"British nautical miles; Imperial nautical miles; Admiralty miles; n.m. br; imp nm","UCUM","Len","Obsolete","","[ft_br]","[FT_BR]","6080",6080,false],[false,"knot - British","[kn_br]","[KN_BR]","velocity",0.5147729280000001,[1,-1,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,"British knots; kn br; kt","UCUM","Vel","Obsolete","based on obsolete British nautical mile ","[nmi_br]/h","[NMI_BR]/H","1",1,false],[false,"acre","[acr_br]","[ACR_BR]","area",4046.850049400269,[2,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,"Imperial acres; British; a; ac; ar; acr","UCUM","Area","Nonclinical","the standard unit for acre used in the US and internationally","[yd_br]2","[YD_BR]2","4840",4840,false],[false,"gallon - US","[gal_us]","[GAL_US]","fluid volume",0.0037854117840000006,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"US gallons; US liquid gallon; gal us; Queen Anne's wine gallon","UCUM","Vol","Nonclinical","only gallon unit used in the US; [gal_us] is only used in some other countries in South American and Africa to measure gasoline volume","[in_i]3","[IN_I]3","231",231,false],[false,"barrel - US","[bbl_us]","[BBL_US]","fluid volume",0.158987294928,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"bbl","UCUM","Vol","Nonclinical","[bbl_us] is the standard unit for oil barrel, which is a unit only used in the US to measure the volume oil. ","[gal_us]","[GAL_US]","42",42,false],[false,"quart - US","[qt_us]","[QT_US]","fluid volume",0.0009463529460000001,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"US quarts; us qts","UCUM","Vol","Clinical","Used only in the US","[gal_us]/4","[GAL_US]/4","1",1,false],[false,"pint - US","[pt_us]","[PT_US]","fluid volume",0.00047317647300000007,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"US pints; pint US; liquid pint; pt us; us pt","UCUM","Vol","Clinical","Used only in the US","[qt_us]/2","[QT_US]/2","1",1,false],[false,"gill - US","[gil_us]","[GIL_US]","fluid volume",0.00011829411825000002,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"US gills; gil us","UCUM","Vol","Nonclinical","only used in the context of alcohol volume in the US","[pt_us]/4","[PT_US]/4","1",1,false],[false,"fluid ounce - US","[foz_us]","[FOZ_US]","fluid volume",0.000029573529562500005,[3,0,0,0,0,0,0],"oz fl","us-volumes",false,null,null,1,false,false,0,"US fluid ounces; fl ozs; FO; fl. oz.; foz us","UCUM","Vol","Clinical","unit used only in the US","[gil_us]/4","[GIL_US]/4","1",1,false],[false,"fluid dram - US","[fdr_us]","[FDR_US]","fluid volume",0.0000036966911953125006,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"US fluid drams; fdr us","UCUM","Vol","Nonclinical","equal to 1/8 US fluid ounce = 3.69 mL; used informally to mean small amount of liquor, especially Scotch whiskey","[foz_us]/8","[FOZ_US]/8","1",1,false],[false,"minim - US","[min_us]","[MIN_US]","fluid volume",6.1611519921875e-8,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"min US; US min; ♏ US","UCUM","Vol","Obsolete","","[fdr_us]/60","[FDR_US]/60","1",1,false],[false,"cord - US","[crd_us]","[CRD_US]","fluid volume",3.6245563637760005,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"US cord; US cords; crd us; us crd","UCUM","Vol","Nonclinical","unit of measure of dry volume used to measure firewood equal 128 ft3 (the same as international cord [cr_i])","[ft_i]3","[FT_I]3","128",128,false],[false,"bushel - US","[bu_us]","[BU_US]","dry volume",0.03523907016688001,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"US bushels; US bsh; US bu","UCUM","Vol","Obsolete","Historical unit of dry volume that is rarely used today","[in_i]3","[IN_I]3","2150.42",2150.42,false],[false,"gallon - historical","[gal_wi]","[GAL_WI]","dry volume",0.004404883770860001,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"Corn Gallon British; Dry Gallon US; Gallons Historical; Grain Gallon British; Winchester Corn Gallon; historical winchester gallons; wi gal","UCUM","Vol","Obsolete","historical unit of dry volume no longer used","[bu_us]/8","[BU_US]/8","1",1,false],[false,"peck - US","[pk_us]","[PK_US]","dry volume",0.008809767541720002,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"US pecks; US pk","UCUM","Vol","Nonclinical","unit of dry volume rarely used today (can be used to measure volume of apples)","[bu_us]/4","[BU_US]/4","1",1,false],[false,"dry quart - US","[dqt_us]","[DQT_US]","dry volume",0.0011012209427150002,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"dry quarts; dry quart US; US dry quart; dry qt; us dry qt; dqt; dqt us","UCUM","Vol","Nonclinical","historical unit of dry volume only in the US, but is rarely used today","[pk_us]/8","[PK_US]/8","1",1,false],[false,"dry pint - US","[dpt_us]","[DPT_US]","dry volume",0.0005506104713575001,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"dry pints; dry pint US; US dry pint; dry pt; dpt; dpt us","UCUM","Vol","Nonclinical","historical unit of dry volume only in the US, but is rarely used today","[dqt_us]/2","[DQT_US]/2","1",1,false],[false,"tablespoon - US","[tbs_us]","[TBS_US]","volume",0.000014786764781250002,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"Tbs; tbsp; tbs us; US tablespoons","UCUM","Vol","Clinical","unit defined as 0.5 US fluid ounces or 3 teaspoons - used only in the US. See [tbs_m] for the unit used internationally and in the US for nutrional labelling. ","[foz_us]/2","[FOZ_US]/2","1",1,false],[false,"teaspoon - US","[tsp_us]","[TSP_US]","volume",0.0000049289215937500005,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"tsp; t; US teaspoons","UCUM","Vol","Nonclinical","unit defined as 1/6 US fluid ounces - used only in the US. See [tsp_m] for the unit used internationally and in the US for nutrional labelling. ","[tbs_us]/3","[TBS_US]/3","1",1,false],[false,"cup - US customary","[cup_us]","[CUP_US]","volume",0.00023658823650000004,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"cup us; us cups","UCUM","Vol","Nonclinical","Unit defined as 1/2 US pint or 16 US tablespoons ≈ 236.59 mL, which is not the standard unit defined by the FDA of 240 mL - see [cup_m] (metric cup)","[tbs_us]","[TBS_US]","16",16,false],[false,"fluid ounce - metric","[foz_m]","[FOZ_M]","fluid volume",0.000029999999999999997,[3,0,0,0,0,0,0],"oz fl","us-volumes",false,null,null,1,false,false,0,"metric fluid ounces; fozs m; fl ozs m","UCUM","Vol","Clinical","unit used only in the US for nutritional labelling, as set by the FDA","mL","ML","30",30,false],[false,"cup - US legal","[cup_m]","[CUP_M]","volume",0.00023999999999999998,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"cup m; metric cups","UCUM","Vol","Clinical","standard unit equal to 240 mL used in the US for nutritional labelling, as defined by the FDA. Note that this is different from the US customary cup (236.59 mL) and the metric cup used in Commonwealth nations (250 mL).","mL","ML","240",240,false],[false,"teaspoon - metric","[tsp_m]","[TSP_M]","volume",0.0000049999999999999996,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"tsp; t; metric teaspoons","UCUM","Vol","Clinical","standard unit used in the US and internationally","mL","mL","5",5,false],[false,"tablespoon - metric","[tbs_m]","[TBS_M]","volume",0.000014999999999999999,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,"metric tablespoons; Tbs; tbsp; T; tbs m","UCUM","Vol","Clinical","standard unit used in the US and internationally","mL","mL","15",15,false],[false,"gallon- British","[gal_br]","[GAL_BR]","volume",0.004546090000000001,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,"imperial gallons, UK gallons; British gallons; br gal; imp gal","UCUM","Vol","Nonclinical","Used only in Great Britain and other Commonwealth countries","l","L","4.54609",4.54609,false],[false,"peck - British","[pk_br]","[PK_BR]","volume",0.009092180000000002,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,"imperial pecks; British pecks; br pk; imp pk","UCUM","Vol","Nonclinical","unit of dry volume rarely used today (can be used to measure volume of apples)","[gal_br]","[GAL_BR]","2",2,false],[false,"bushel - British","[bu_br]","[BU_BR]","volume",0.03636872000000001,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,"British bushels; imperial; br bsh; br bu; imp","UCUM","Vol","Obsolete","Historical unit of dry volume that is rarely used today","[pk_br]","[PK_BR]","4",4,false],[false,"quart - British","[qt_br]","[QT_BR]","volume",0.0011365225000000002,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,"British quarts; imperial quarts; br qts","UCUM","Vol","Clinical","Used only in Great Britain and other Commonwealth countries","[gal_br]/4","[GAL_BR]/4","1",1,false],[false,"pint - British","[pt_br]","[PT_BR]","volume",0.0005682612500000001,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,"British pints; imperial pints; pt br; br pt; imp pt; pt imp","UCUM","Vol","Clinical","Used only in Great Britain and other Commonwealth countries","[qt_br]/2","[QT_BR]/2","1",1,false],[false,"gill - British","[gil_br]","[GIL_BR]","volume",0.00014206531250000003,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,"imperial gills; British gills; imp gill, br gill","UCUM","Vol","Nonclinical","only used in the context of alcohol volume in Great Britain","[pt_br]/4","[PT_BR]/4","1",1,false],[false,"fluid ounce - British","[foz_br]","[FOZ_BR]","volume",0.000028413062500000005,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,"British fluid ounces; Imperial fluid ounces; br fozs; imp fozs; br fl ozs","UCUM","Vol","Clinical","Used only in Great Britain and other Commonwealth countries","[gil_br]/5","[GIL_BR]/5","1",1,false],[false,"fluid dram - British","[fdr_br]","[FDR_BR]","volume",0.0000035516328125000006,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,"British fluid drams; fdr br","UCUM","Vol","Nonclinical","equal to 1/8 Imperial fluid ounce = 3.55 mL; used informally to mean small amount of liquor, especially Scotch whiskey","[foz_br]/8","[FOZ_BR]/8","1",1,false],[false,"minim - British","[min_br]","[MIN_BR]","volume",5.919388020833334e-8,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,"min br; br min; ♏ br","UCUM","Vol","Obsolete","","[fdr_br]/60","[FDR_BR]/60","1",1,false],[false,"grain","[gr]","[GR]","mass",0.06479891,[0,0,1,0,0,0,0],null,"avoirdupois",false,null,null,1,false,false,0,"gr; grains","UCUM","Mass","Nonclinical","an apothecary measure of mass rarely used today","mg","MG","64.79891",64.79891,false],[false,"pound","[lb_av]","[LB_AV]","mass",453.59237,[0,0,1,0,0,0,0],"lb","avoirdupois",false,null,null,1,false,false,0,"avoirdupois pounds, international pounds; av lbs; pounds","UCUM","Mass","Clinical","standard unit used in the US and internationally","[gr]","[GR]","7000",7000,false],[false,"pound force - US","[lbf_av]","[LBF_AV]","force",4448.2216152605,[1,-2,1,0,0,0,0],"lbf","const",false,null,null,1,false,false,0,"lbfs; US lbf; US pound forces","UCUM","Force","Clinical","only rarely needed in health care - see [lb_av] which is the more common unit to express weight","[lb_av].[g]","[LB_AV].[G]","1",1,false],[false,"ounce","[oz_av]","[OZ_AV]","mass",28.349523125,[0,0,1,0,0,0,0],"oz","avoirdupois",false,null,null,1,false,false,0,"ounces; international ounces; avoirdupois ounces; av ozs","UCUM","Mass","Clinical","standard unit used in the US and internationally","[lb_av]/16","[LB_AV]/16","1",1,false],[false,"Dram mass unit","[dr_av]","[DR_AV]","mass",1.7718451953125,[0,0,1,0,0,0,0],null,"avoirdupois",false,null,null,1,false,false,0,"Dram; drams avoirdupois; avoidupois dram; international dram","UCUM","Mass","Clinical","unit from the avoirdupois system, which is used in the US and internationally","[oz_av]/16","[OZ_AV]/16","1",1,false],[false,"short hundredweight","[scwt_av]","[SCWT_AV]","mass",45359.237,[0,0,1,0,0,0,0],null,"avoirdupois",false,null,null,1,false,false,0,"hundredweights; s cwt; scwt; avoirdupois","UCUM","Mass","Nonclinical","Used only in the US to equal 100 pounds","[lb_av]","[LB_AV]","100",100,false],[false,"long hundredweight","[lcwt_av]","[LCWT_AV]","mass",50802.345440000005,[0,0,1,0,0,0,0],null,"avoirdupois",false,null,null,1,false,false,0,"imperial hundredweights; imp cwt; lcwt; avoirdupois","UCUM","Mass","Obsolete","","[lb_av]","[LB_AV]","112",112,false],[false,"short ton - US","[ston_av]","[STON_AV]","mass",907184.74,[0,0,1,0,0,0,0],null,"avoirdupois",false,null,null,1,false,false,0,"ton; US tons; avoirdupois tons","UCUM","Mass","Clinical","Used only in the US","[scwt_av]","[SCWT_AV]","20",20,false],[false,"long ton - British","[lton_av]","[LTON_AV]","mass",1016046.9088000001,[0,0,1,0,0,0,0],null,"avoirdupois",false,null,null,1,false,false,0,"imperial tons; weight tons; British long tons; long ton avoirdupois","UCUM","Mass","Nonclinical","Used only in Great Britain and other Commonwealth countries","[lcwt_av]","[LCWT_AV]","20",20,false],[false,"stone - British","[stone_av]","[STONE_AV]","mass",6350.293180000001,[0,0,1,0,0,0,0],null,"avoirdupois",false,null,null,1,false,false,0,"British stones; avoirdupois","UCUM","Mass","Nonclinical","Used primarily in the UK and Ireland to measure body weight","[lb_av]","[LB_AV]","14",14,false],[false,"pennyweight - troy","[pwt_tr]","[PWT_TR]","mass",1.5551738400000001,[0,0,1,0,0,0,0],null,"troy",false,null,null,1,false,false,0,"dwt; denarius weights","UCUM","Mass","Obsolete","historical unit used to measure mass and cost of precious metals","[gr]","[GR]","24",24,false],[false,"ounce - troy","[oz_tr]","[OZ_TR]","mass",31.103476800000003,[0,0,1,0,0,0,0],null,"troy",false,null,null,1,false,false,0,"troy ounces; tr ozs","UCUM","Mass","Nonclinical","unit of mass for precious metals and gemstones only","[pwt_tr]","[PWT_TR]","20",20,false],[false,"pound - troy","[lb_tr]","[LB_TR]","mass",373.2417216,[0,0,1,0,0,0,0],null,"troy",false,null,null,1,false,false,0,"troy pounds; tr lbs","UCUM","Mass","Nonclinical","only used for weighing precious metals","[oz_tr]","[OZ_TR]","12",12,false],[false,"scruple","[sc_ap]","[SC_AP]","mass",1.2959782,[0,0,1,0,0,0,0],null,"apoth",false,null,null,1,false,false,0,"scruples; sc ap","UCUM","Mass","Obsolete","","[gr]","[GR]","20",20,false],[false,"dram - apothecary","[dr_ap]","[DR_AP]","mass",3.8879346,[0,0,1,0,0,0,0],null,"apoth",false,null,null,1,false,false,0,"ʒ; drachm; apothecaries drams; dr ap; dram ap","UCUM","Mass","Nonclinical","unit still used in the US occasionally to measure amount of drugs in pharmacies","[sc_ap]","[SC_AP]","3",3,false],[false,"ounce - apothecary","[oz_ap]","[OZ_AP]","mass",31.1034768,[0,0,1,0,0,0,0],null,"apoth",false,null,null,1,false,false,0,"apothecary ounces; oz ap; ap ozs; ozs ap","UCUM","Mass","Obsolete","","[dr_ap]","[DR_AP]","8",8,false],[false,"pound - apothecary","[lb_ap]","[LB_AP]","mass",373.2417216,[0,0,1,0,0,0,0],null,"apoth",false,null,null,1,false,false,0,"apothecary pounds; apothecaries pounds; ap lb; lb ap; ap lbs; lbs ap","UCUM","Mass","Obsolete","","[oz_ap]","[OZ_AP]","12",12,false],[false,"ounce - metric","[oz_m]","[OZ_M]","mass",28,[0,0,1,0,0,0,0],null,"apoth",false,null,null,1,false,false,0,"metric ounces; m ozs","UCUM","Mass","Clinical","see [oz_av] (the avoirdupois ounce) for the standard ounce used internationally; [oz_m] is equal to 28 grams and is based on the apothecaries' system of mass units which is used in some US pharmacies. ","g","g","28",28,false],[false,"line","[lne]","[LNE]","length",0.002116666666666667,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,"British lines; br L; L; l","UCUM","Len","Obsolete","","[in_i]/12","[IN_I]/12","1",1,false],[false,"point (typography)","[pnt]","[PNT]","length",0.0003527777777777778,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,"DTP points; desktop publishing point; pt; pnt","UCUM","Len","Nonclinical","typography unit for typesetter's length","[lne]/6","[LNE]/6","1",1,false],[false,"pica (typography)","[pca]","[PCA]","length",0.004233333333333334,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,"picas","UCUM","Len","Nonclinical","typography unit for typesetter's length","[pnt]","[PNT]","12",12,false],[false,"Printer's point (typography)","[pnt_pr]","[PNT_PR]","length",0.00035145980000000004,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,"pnt pr","UCUM","Len","Nonclinical","typography unit for typesetter's length","[in_i]","[IN_I]","0.013837",0.013837,false],[false,"Printer's pica (typography)","[pca_pr]","[PCA_PR]","length",0.004217517600000001,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,"pca pr; Printer's picas","UCUM","Len","Nonclinical","typography unit for typesetter's length","[pnt_pr]","[PNT_PR]","12",12,false],[false,"pied","[pied]","[PIED]","length",0.3248,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,"pieds du roi; Paris foot; royal; French; feet","UCUM","Len","Obsolete","","cm","CM","32.48",32.48,false],[false,"pouce","[pouce]","[POUCE]","length",0.027066666666666666,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,"historical French inches; French royal inches","UCUM","Len","Obsolete","","[pied]/12","[PIED]/12","1",1,false],[false,"ligne","[ligne]","[LIGNE]","length",0.0022555555555555554,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,"Paris lines; lignes","UCUM","Len","Obsolete","","[pouce]/12","[POUCE]/12","1",1,false],[false,"didot","[didot]","[DIDOT]","length",0.0003759259259259259,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,"Didot point; dd; Didots Point; didots; points","UCUM","Len","Obsolete","typography unit for typesetter's length","[ligne]/6","[LIGNE]/6","1",1,false],[false,"cicero","[cicero]","[CICERO]","length",0.004511111111111111,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,"Didot's pica; ciceros; picas","UCUM","Len","Obsolete","typography unit for typesetter's length","[didot]","[DIDOT]","12",12,false],[false,"degrees Fahrenheit","[degF]","[DEGF]","temperature",0.5555555555555556,[0,0,0,0,1,0,0],"°F","heat",false,null,"degF",1,true,false,0,"°F; deg F","UCUM","Temp","Clinical","","K",null,null,0.5555555555555556,false],[false,"degrees Rankine","[degR]","[degR]","temperature",0.5555555555555556,[0,0,0,0,1,0,0],"°R","heat",false,null,null,1,false,false,0,"°R; °Ra; Rankine","UCUM","Temp","Obsolete","Replaced by Kelvin","K/9","K/9","5",5,false],[false,"degrees Réaumur","[degRe]","[degRe]","temperature",1.25,[0,0,0,0,1,0,0],"°Ré","heat",false,null,"degRe",1,true,false,0,"°Ré, °Re, °r; Réaumur; degree Reaumur; Reaumur","UCUM","Temp","Obsolete","replaced by Celsius","K",null,null,1.25,false],[false,"calorie at 15°C","cal_[15]","CAL_[15]","energy",4185.8,[2,-2,1,0,0,0,0],"cal15°C","heat",true,null,null,1,false,false,0,"calorie 15 C; cals 15 C; calories at 15 C","UCUM","Enrg","Nonclinical","equal to 4.1855 joules; calorie most often used in engineering","J","J","4.18580",4.1858,false],[false,"calorie at 20°C","cal_[20]","CAL_[20]","energy",4181.9,[2,-2,1,0,0,0,0],"cal20°C","heat",true,null,null,1,false,false,0,"calorie 20 C; cal 20 C; calories at 20 C","UCUM","Enrg","Clinical","equal to 4.18190 joules. ","J","J","4.18190",4.1819,false],[false,"mean calorie","cal_m","CAL_M","energy",4190.0199999999995,[2,-2,1,0,0,0,0],"calm","heat",true,null,null,1,false,false,0,"mean cals; mean calories","UCUM","Enrg","Clinical","equal to 4.19002 joules. ","J","J","4.19002",4.19002,false],[false,"international table calorie","cal_IT","CAL_IT","energy",4186.8,[2,-2,1,0,0,0,0],"calIT","heat",true,null,null,1,false,false,0,"calories IT; IT cals; international steam table calories","UCUM","Enrg","Nonclinical","used in engineering steam tables and defined as 1/860 international watt-hour; equal to 4.1868 joules","J","J","4.1868",4.1868,false],[false,"thermochemical calorie","cal_th","CAL_TH","energy",4184,[2,-2,1,0,0,0,0],"calth","heat",true,null,null,1,false,false,0,"thermochemical calories; th cals","UCUM","Enrg","Clinical","equal to 4.184 joules; used as the unit in medicine and biochemistry (equal to cal)","J","J","4.184",4.184,false],[false,"calorie","cal","CAL","energy",4184,[2,-2,1,0,0,0,0],"cal","heat",true,null,null,1,false,false,0,"gram calories; small calories","UCUM","Enrg","Clinical","equal to 4.184 joules (the same value as the thermochemical calorie, which is the most common calorie used in medicine and biochemistry)","cal_th","CAL_TH","1",1,false],[false,"nutrition label Calories","[Cal]","[CAL]","energy",4184000,[2,-2,1,0,0,0,0],"Cal","heat",false,null,null,1,false,false,0,"food calories; Cal; kcal","UCUM","Eng","Clinical","","kcal_th","KCAL_TH","1",1,false],[false,"British thermal unit at 39°F","[Btu_39]","[BTU_39]","energy",1059670,[2,-2,1,0,0,0,0],"Btu39°F","heat",false,null,null,1,false,false,0,"BTU 39F; BTU 39 F; B.T.U. 39 F; B.Th.U. 39 F; BThU 39 F; British thermal units","UCUM","Eng","Nonclinical","equal to 1.05967 kJ; used as a measure of power in the electric power, steam generation, heating, and air conditioning industries","kJ","kJ","1.05967",1.05967,false],[false,"British thermal unit at 59°F","[Btu_59]","[BTU_59]","energy",1054800,[2,-2,1,0,0,0,0],"Btu59°F","heat",false,null,null,1,false,false,0,"BTU 59 F; BTU 59F; B.T.U. 59 F; B.Th.U. 59 F; BThU 59F; British thermal units","UCUM","Eng","Nonclinical","equal to 1.05480 kJ; used as a measure of power in the electric power, steam generation, heating, and air conditioning industries","kJ","kJ","1.05480",1.0548,false],[false,"British thermal unit at 60°F","[Btu_60]","[BTU_60]","energy",1054680,[2,-2,1,0,0,0,0],"Btu60°F","heat",false,null,null,1,false,false,0,"BTU 60 F; BTU 60F; B.T.U. 60 F; B.Th.U. 60 F; BThU 60 F; British thermal units 60 F","UCUM","Eng","Nonclinical","equal to 1.05468 kJ; used as a measure of power in the electric power, steam generation, heating, and air conditioning industries","kJ","kJ","1.05468",1.05468,false],[false,"mean British thermal unit","[Btu_m]","[BTU_M]","energy",1055870,[2,-2,1,0,0,0,0],"Btum","heat",false,null,null,1,false,false,0,"BTU mean; B.T.U. mean; B.Th.U. mean; BThU mean; British thermal units mean; ","UCUM","Eng","Nonclinical","equal to 1.05587 kJ; used as a measure of power in the electric power, steam generation, heating, and air conditioning industries","kJ","kJ","1.05587",1.05587,false],[false,"international table British thermal unit","[Btu_IT]","[BTU_IT]","energy",1055055.85262,[2,-2,1,0,0,0,0],"BtuIT","heat",false,null,null,1,false,false,0,"BTU IT; B.T.U. IT; B.Th.U. IT; BThU IT; British thermal units IT","UCUM","Eng","Nonclinical","equal to 1.055 kJ; used as a measure of power in the electric power, steam generation, heating, and air conditioning industries","kJ","kJ","1.05505585262",1.05505585262,false],[false,"thermochemical British thermal unit","[Btu_th]","[BTU_TH]","energy",1054350,[2,-2,1,0,0,0,0],"Btuth","heat",false,null,null,1,false,false,0,"BTU Th; B.T.U. Th; B.Th.U. Th; BThU Th; thermochemical British thermal units","UCUM","Eng","Nonclinical","equal to 1.054350 kJ; used as a measure of power in the electric power, steam generation, heating, and air conditioning industries","kJ","kJ","1.054350",1.05435,false],[false,"British thermal unit","[Btu]","[BTU]","energy",1054350,[2,-2,1,0,0,0,0],"btu","heat",false,null,null,1,false,false,0,"BTU; B.T.U. ; B.Th.U.; BThU; British thermal units","UCUM","Eng","Nonclinical","equal to the thermochemical British thermal unit equal to 1.054350 kJ; used as a measure of power in the electric power, steam generation, heating, and air conditioning industries","[Btu_th]","[BTU_TH]","1",1,false],[false,"horsepower - mechanical","[HP]","[HP]","power",745699.8715822703,[2,-3,1,0,0,0,0],null,"heat",false,null,null,1,false,false,0,"imperial horsepowers","UCUM","EngRat","Nonclinical","refers to mechanical horsepower, which is unit used to measure engine power primarily in the US. ","[ft_i].[lbf_av]/s","[FT_I].[LBF_AV]/S","550",550,false],[false,"tex","tex","TEX","linear mass density (of textile thread)",0.001,[-1,0,1,0,0,0,0],"tex","heat",true,null,null,1,false,false,0,"linear mass density; texes","UCUM","","Clinical","unit of linear mass density for fibers equal to gram per 1000 meters","g/km","G/KM","1",1,false],[false,"Denier (linear mass density)","[den]","[DEN]","linear mass density (of textile thread)",0.0001111111111111111,[-1,0,1,0,0,0,0],"den","heat",false,null,null,1,false,false,0,"den; deniers","UCUM","","Nonclinical","equal to the mass in grams per 9000 meters of the fiber (1 denier = 1 strand of silk)","g/9/km","G/9/KM","1",1,false],[false,"meter of water column","m[H2O]","M[H2O]","pressure",9806650,[-1,-2,1,0,0,0,0],"m HO2","clinical",true,null,null,1,false,false,0,"mH2O; m H2O; meters of water column; metres; pressure","UCUM","Pres","Clinical","","kPa","KPAL","980665e-5",9.80665,false],[false,"meter of mercury column","m[Hg]","M[HG]","pressure",133322000,[-1,-2,1,0,0,0,0],"m Hg","clinical",true,null,null,1,false,false,0,"mHg; m Hg; meters of mercury column; metres; pressure","UCUM","Pres","Clinical","","kPa","KPAL","133.3220",133.322,false],[false,"inch of water column","[in_i'H2O]","[IN_I'H2O]","pressure",249088.91000000003,[-1,-2,1,0,0,0,0],"in HO2","clinical",false,null,null,1,false,false,0,"inches WC; inAq; in H2O; inch of water gauge; iwg; pressure","UCUM","Pres","Clinical","unit of pressure, especially in respiratory and ventilation care","m[H2O].[in_i]/m","M[H2O].[IN_I]/M","1",1,false],[false,"inch of mercury column","[in_i'Hg]","[IN_I'HG]","pressure",3386378.8000000003,[-1,-2,1,0,0,0,0],"in Hg","clinical",false,null,null,1,false,false,0,"inHg; in Hg; pressure; inches","UCUM","Pres","Clinical","unit of pressure used in US to measure barometric pressure and occasionally blood pressure (see mm[Hg] for unit used internationally)","m[Hg].[in_i]/m","M[HG].[IN_I]/M","1",1,false],[false,"peripheral vascular resistance unit","[PRU]","[PRU]","fluid resistance",133322000000,[-4,-1,1,0,0,0,0],"P.R.U.","clinical",false,null,null,1,false,false,0,"peripheral vascular resistance units; peripheral resistance unit; peripheral resistance units; PRU","UCUM","FldResist","Clinical","used to assess blood flow in the capillaries; equal to 1 mmH.min/mL = 133.3 Pa·min/mL","mm[Hg].s/ml","MM[HG].S/ML","1",1,false],[false,"Wood unit","[wood'U]","[WOOD'U]","fluid resistance",7999320000,[-4,-1,1,0,0,0,0],"Wood U.","clinical",false,null,null,1,false,false,0,"hybrid reference units; HRU; mmHg.min/L; vascular resistance","UCUM","Pres","Clinical","simplified unit of measurement for for measuring pulmonary vascular resistance that uses pressure; equal to mmHg.min/L","mm[Hg].min/L","MM[HG].MIN/L","1",1,false],[false,"diopter (lens)","[diop]","[DIOP]","refraction of a lens",1,[1,0,0,0,0,0,0],"dpt","clinical",false,null,"inv",1,false,false,0,"diopters; diop; dioptre; dpt; refractive power","UCUM","InvLen","Clinical","unit of optical power of lens represented by inverse meters (m^-1)","m","/M","1",1,false],[false,"prism diopter (magnifying power)","[p'diop]","[P'DIOP]","refraction of a prism",1,[0,0,0,1,0,0,0],"PD","clinical",false,null,"tanTimes100",1,true,false,0,"diopters; dioptres; p diops; pdiop; dpt; pdptr; Δ; cm/m; centimeter per meter; centimetre; metre","UCUM","Angle","Clinical","unit for prism correction in eyeglass prescriptions","rad",null,null,1,false],[false,"percent of slope","%[slope]","%[SLOPE]","slope",0.017453292519943295,[0,0,0,1,0,0,0],"%","clinical",false,null,"100tan",1,true,false,0,"% slope; %slope; percents slopes","UCUM","VelFr; ElpotRatFr; VelRtoFr; AccelFr","Clinical","","deg",null,null,1,false],[false,"mesh","[mesh_i]","[MESH_I]","lineic number",0.025400000000000002,[1,0,0,0,0,0,0],null,"clinical",false,null,"inv",1,false,false,0,"meshes","UCUM","NLen (lineic number)","Clinical","traditional unit of length defined as the number of strands or particles per inch","[in_i]","/[IN_I]","1",1,false],[false,"French (catheter gauge) ","[Ch]","[CH]","gauge of catheters",0.0003333333333333333,[1,0,0,0,0,0,0],"Ch","clinical",false,null,null,1,false,false,0,"Charrières, French scales; French gauges; Fr, Fg, Ga, FR, Ch","UCUM","Len; Circ; Diam","Clinical","","mm/3","MM/3","1",1,false],[false,"drop - metric (1/20 mL)","[drp]","[DRP]","volume",5e-8,[3,0,0,0,0,0,0],"drp","clinical",false,null,null,1,false,false,0,"drop dosing units; metric drops; gtt","UCUM","Vol","Clinical","standard unit used in the US and internationally for clinical medicine but note that although [drp] is defined as 1/20 milliliter, in practice, drop sizes will vary due to external factors","ml/20","ML/20","1",1,false],[false,"Hounsfield unit","[hnsf'U]","[HNSF'U]","x-ray attenuation",1,[0,0,0,0,0,0,0],"HF","clinical",false,null,null,1,false,false,0,"HU; units","UCUM","","Clinical","used to measure X-ray attenuation, especially in CT scans.","1","1","1",1,false],[false,"Metabolic Equivalent of Task ","[MET]","[MET]","metabolic cost of physical activity",5.833333333333334e-11,[3,-1,-1,0,0,0,0],"MET","clinical",false,null,null,1,false,false,0,"metabolic equivalents","UCUM","RelEngRat","Clinical","unit used to measure rate of energy expenditure per power in treadmill and other functional tests","mL/min/kg","ML/MIN/KG","3.5",3.5,false],[false,"homeopathic potency of decimal series (retired)","[hp'_X]","[HP'_X]","homeopathic potency (retired)",1,[0,0,0,0,0,0,0],"X","clinical",false,null,"hpX",1,true,false,0,null,"UCUM",null,null,null,"1",null,null,1,false],[false,"homeopathic potency of centesimal series (retired)","[hp'_C]","[HP'_C]","homeopathic potency (retired)",1,[0,0,0,0,0,0,0],"C","clinical",false,null,"hpC",1,true,false,0,null,"UCUM",null,null,null,"1",null,null,1,false],[false,"homeopathic potency of millesimal series (retired)","[hp'_M]","[HP'_M]","homeopathic potency (retired)",1,[0,0,0,0,0,0,0],"M","clinical",false,null,"hpM",1,true,false,0,null,"UCUM",null,null,null,"1",null,null,1,false],[false,"homeopathic potency of quintamillesimal series (retired)","[hp'_Q]","[HP'_Q]","homeopathic potency (retired)",1,[0,0,0,0,0,0,0],"Q","clinical",false,null,"hpQ",1,true,false,0,null,"UCUM",null,null,null,"1",null,null,1,false],[false,"homeopathic potency of decimal hahnemannian series","[hp_X]","[HP_X]","homeopathic potency (Hahnemann)",1,[0,0,0,0,0,0,0],"X","clinical",false,null,null,1,false,true,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"homeopathic potency of centesimal hahnemannian series","[hp_C]","[HP_C]","homeopathic potency (Hahnemann)",1,[0,0,0,0,0,0,0],"C","clinical",false,null,null,1,false,true,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"homeopathic potency of millesimal hahnemannian series","[hp_M]","[HP_M]","homeopathic potency (Hahnemann)",1,[0,0,0,0,0,0,0],"M","clinical",false,null,null,1,false,true,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"homeopathic potency of quintamillesimal hahnemannian series","[hp_Q]","[HP_Q]","homeopathic potency (Hahnemann)",1,[0,0,0,0,0,0,0],"Q","clinical",false,null,null,1,false,true,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"homeopathic potency of decimal korsakovian series","[kp_X]","[KP_X]","homeopathic potency (Korsakov)",1,[0,0,0,0,0,0,0],"X","clinical",false,null,null,1,false,true,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"homeopathic potency of centesimal korsakovian series","[kp_C]","[KP_C]","homeopathic potency (Korsakov)",1,[0,0,0,0,0,0,0],"C","clinical",false,null,null,1,false,true,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"homeopathic potency of millesimal korsakovian series","[kp_M]","[KP_M]","homeopathic potency (Korsakov)",1,[0,0,0,0,0,0,0],"M","clinical",false,null,null,1,false,true,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"homeopathic potency of quintamillesimal korsakovian series","[kp_Q]","[KP_Q]","homeopathic potency (Korsakov)",1,[0,0,0,0,0,0,0],"Q","clinical",false,null,null,1,false,true,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"equivalent","eq","EQ","amount of substance",6.0221367e+23,[0,0,0,0,0,0,0],"eq","chemical",true,null,null,1,false,false,1,"equivalents","UCUM","Sub","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"osmole","osm","OSM","amount of substance (dissolved particles)",6.0221367e+23,[0,0,0,0,0,0,0],"osm","chemical",true,null,null,1,false,false,1,"osmoles; osmols","UCUM","Osmol","Clinical","the number of moles of solute that contribute to the osmotic pressure of a solution","mol","MOL","1",1,false],[false,"pH","[pH]","[PH]","acidity",6.0221366999999994e+26,[-3,0,0,0,0,0,0],"pH","chemical",false,null,"pH",1,true,false,0,"pH scale","UCUM","LogCnc","Clinical","Log concentration of H+","mol/l",null,null,1,false],[false,"gram percent","g%","G%","mass concentration",10000,[-3,0,1,0,0,0,0],"g%","chemical",true,null,null,1,false,false,0,"gram %; gram%; grams per deciliter; g/dL; gm per dL; gram percents","UCUM","MCnc","Clinical","equivalent to unit gram per deciliter (g/dL), a unit often used in medical tests to represent solution concentrations","g/dl","G/DL","1",1,false],[false,"Svedberg unit","[S]","[S]","sedimentation coefficient",1e-13,[0,1,0,0,0,0,0],"S","chemical",false,null,null,1,false,false,0,"Sv; 10^-13 seconds; 100 fs; 100 femtoseconds","UCUM","Time","Clinical","unit of time used in measuring particle's sedimentation rate, usually after centrifugation. ","s","10*-13.S","1",1e-13,false],[false,"high power field (microscope)","[HPF]","[HPF]","view area in microscope",1,[0,0,0,0,0,0,0],"HPF","chemical",false,null,null,1,false,false,0,"HPF","UCUM","Area","Clinical","area visible under the maximum magnification power of the objective in microscopy (usually 400x)\n","1","1","1",1,false],[false,"low power field (microscope)","[LPF]","[LPF]","view area in microscope",1,[0,0,0,0,0,0,0],"LPF","chemical",false,null,null,1,false,false,0,"LPF; fields","UCUM","Area","Clinical","area visible under the low magnification of the objective in microscopy (usually 100 x)\n","1","1","100",100,false],[false,"katal","kat","KAT","catalytic activity",6.0221367e+23,[0,-1,0,0,0,0,0],"kat","chemical",true,null,null,1,false,false,1,"mol/secs; moles per second; mol*sec-1; mol*s-1; mol.s-1; katals; catalytic activity; enzymatic; enzyme units; activities","UCUM","CAct","Clinical","kat is a unit of catalytic activity with base units = mol/s. Rarely used because its units are too large to practically express catalytic activity. See enzyme unit [U] which is the standard unit for catalytic activity.","mol/s","MOL/S","1",1,false],[false,"enzyme unit","U","U","catalytic activity",10036894500000000,[0,-1,0,0,0,0,0],"U","chemical",true,null,null,1,false,false,1,"micromoles per minute; umol/min; umol per minute; umol min-1; enzymatic activity; enzyme activity","UCUM","CAct","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"international unit - arbitrary","[iU]","[IU]","arbitrary",1,[0,0,0,0,0,0,0],"IU","chemical",true,null,null,1,false,true,0,"international units; IE; F2","UCUM","Arb","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","1","1","1",1,false],[false,"international unit - arbitrary","[IU]","[IU]","arbitrary",1,[0,0,0,0,0,0,0],"i.U.","chemical",true,null,null,1,false,true,0,"international units; IE; F2","UCUM","Arb","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"arbitary unit","[arb'U]","[ARB'U]","arbitrary",1,[0,0,0,0,0,0,0],"arb. U","chemical",false,null,null,1,false,true,0,"arbitary units; arb units; arbU","UCUM","Arb","Clinical","relative unit of measurement to show the ratio of test measurement to reference measurement","1","1","1",1,false],[false,"United States Pharmacopeia unit","[USP'U]","[USP'U]","arbitrary",1,[0,0,0,0,0,0,0],"U.S.P.","chemical",false,null,null,1,false,true,0,"USP U; USP'U","UCUM","Arb","Clinical","a dose unit to express potency of drugs and vitamins defined by the United States Pharmacopoeia; usually 1 USP = 1 IU","1","1","1",1,false],[false,"GPL unit","[GPL'U]","[GPL'U]","biologic activity of anticardiolipin IgG",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,"GPL Units; GPL U; IgG anticardiolipin units; IgG Phospholipid","UCUM","ACnc; AMass","Clinical","Units for an antiphospholipid test","1","1","1",1,false],[false,"MPL unit","[MPL'U]","[MPL'U]","biologic activity of anticardiolipin IgM",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,"MPL units; MPL U; MPL'U; IgM anticardiolipin units; IgM Phospholipid Units ","UCUM","ACnc","Clinical","units for antiphospholipid test","1","1","1",1,false],[false,"APL unit","[APL'U]","[APL'U]","biologic activity of anticardiolipin IgA",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,"APL units; APL U; IgA anticardiolipin; IgA Phospholipid; biologic activity of","UCUM","AMass; ACnc","Clinical","Units for an anti phospholipid syndrome test","1","1","1",1,false],[false,"Bethesda unit","[beth'U]","[BETH'U]","biologic activity of factor VIII inhibitor",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,"BU","UCUM","ACnc","Clinical","measures of blood coagulation inhibitior for many blood factors","1","1","1",1,false],[false,"anti factor Xa unit","[anti'Xa'U]","[ANTI'XA'U]","biologic activity of factor Xa inhibitor (heparin)",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,"units","UCUM","ACnc","Clinical","[anti'Xa'U] unit is equivalent to and can be converted to IU/mL. ","1","1","1",1,false],[false,"Todd unit","[todd'U]","[TODD'U]","biologic activity antistreptolysin O",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,"units","UCUM","InvThres; RtoThres","Clinical","the unit for the results of the testing for antistreptolysin O (ASO)","1","1","1",1,false],[false,"Dye unit","[dye'U]","[DYE'U]","biologic activity of amylase",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,"units","UCUM","CCnc","Obsolete","equivalent to the Somogyi unit, which is an enzyme unit for amylase but better to use U, the standard enzyme unit for measuring catalytic activity","1","1","1",1,false],[false,"Somogyi unit","[smgy'U]","[SMGY'U]","biologic activity of amylase",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,"Somogyi units; smgy U","UCUM","CAct","Clinical","measures the enzymatic activity of amylase in blood serum - better to use base units mg/mL ","1","1","1",1,false],[false,"Bodansky unit","[bdsk'U]","[BDSK'U]","biologic activity of phosphatase",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,"","UCUM","ACnc","Obsolete","Enzyme unit specific to alkaline phosphatase - better to use standard enzyme unit of U","1","1","1",1,false],[false,"King-Armstrong unit","[ka'U]","[KA'U]","biologic activity of phosphatase",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,"King-Armstrong Units; King units","UCUM","AMass","Obsolete","enzyme units for acid phosphatase - better to use enzyme unit [U]","1","1","1",1,false],[false,"Kunkel unit","[knk'U]","[KNK'U]","arbitrary biologic activity",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"Mac Lagan unit","[mclg'U]","[MCLG'U]","arbitrary biologic activity",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,"galactose index; galactose tolerance test; thymol turbidity test unit; mclg U; units; indexes","UCUM","ACnc","Obsolete","unit for liver tests - previously used in thymol turbidity tests for liver disease diagnoses, and now is sometimes referred to in the oral galactose tolerance test","1","1","1",1,false],[false,"tuberculin unit","[tb'U]","[TB'U]","biologic activity of tuberculin",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,"TU; units","UCUM","Arb","Clinical","amount of tuberculin antigen -usually in reference to a TB skin test ","1","1","1",1,false],[false,"50% cell culture infectious dose","[CCID_50]","[CCID_50]","biologic activity (infectivity) of an infectious agent preparation",1,[0,0,0,0,0,0,0],"CCID50","chemical",false,null,null,1,false,true,0,"CCID50; 50% cell culture infective doses","UCUM","NumThres","Clinical","","1","1","1",1,false],[false,"50% tissue culture infectious dose","[TCID_50]","[TCID_50]","biologic activity (infectivity) of an infectious agent preparation",1,[0,0,0,0,0,0,0],"TCID50","chemical",false,null,null,1,false,true,0,"TCID50; 50% tissue culture infective dose","UCUM","NumThres","Clinical","","1","1","1",1,false],[false,"50% embryo infectious dose","[EID_50]","[EID_50]","biologic activity (infectivity) of an infectious agent preparation",1,[0,0,0,0,0,0,0],"EID50","chemical",false,null,null,1,false,true,0,"EID50; 50% embryo infective doses; EID50 Egg Infective Dosage","UCUM","thresNum","Clinical","","1","1","1",1,false],[false,"plaque forming units","[PFU]","[PFU]","amount of an infectious agent",1,[0,0,0,0,0,0,0],"PFU","chemical",false,null,null,1,false,true,0,"PFU","UCUM","ACnc","Clinical","tests usually report unit as number of PFU per unit volume","1","1","1",1,false],[false,"focus forming units (cells)","[FFU]","[FFU]","amount of an infectious agent",1,[0,0,0,0,0,0,0],"FFU","chemical",false,null,null,1,false,true,0,"FFU","UCUM","EntNum","Clinical","","1","1","1",1,false],[false,"colony forming units","[CFU]","[CFU]","amount of a proliferating organism",1,[0,0,0,0,0,0,0],"CFU","chemical",false,null,null,1,false,true,0,"CFU","UCUM","Num","Clinical","","1","1","1",1,false],[false,"index of reactivity (allergen)","[IR]","[IR]","amount of an allergen callibrated through in-vivo testing using the Stallergenes® method.",1,[0,0,0,0,0,0,0],"IR","chemical",false,null,null,1,false,true,0,"IR; indexes","UCUM","Acnc","Clinical","amount of an allergen callibrated through in-vivo testing using the Stallergenes method. Usually reported in tests as IR/mL","1","1","1",1,false],[false,"bioequivalent allergen unit","[BAU]","[BAU]","amount of an allergen callibrated through in-vivo testing based on the ID50EAL method of (intradermal dilution for 50mm sum of erythema diameters",1,[0,0,0,0,0,0,0],"BAU","chemical",false,null,null,1,false,true,0,"BAU; Bioequivalent Allergy Units; bioequivalent allergen units","UCUM","Arb","Clinical","","1","1","1",1,false],[false,"allergy unit","[AU]","[AU]","procedure defined amount of an allergen using some reference standard",1,[0,0,0,0,0,0,0],"AU","chemical",false,null,null,1,false,true,0,"allergy units; allergen units; AU","UCUM","Arb","Clinical","Most standard test allergy units are reported as [IU] or as %. ","1","1","1",1,false],[false,"allergen unit for Ambrosia artemisiifolia","[Amb'a'1'U]","[AMB'A'1'U]","procedure defined amount of the major allergen of ragweed.",1,[0,0,0,0,0,0,0],"Amb a 1 U","chemical",false,null,null,1,false,true,0,"Amb a 1 unit; Antigen E; AgE U; allergen units","UCUM","Arb","Clinical","Amb a 1 is the major allergen in short ragweed, and can be converted Bioequivalent allergen units (BAU) where 350 Amb a 1 U/mL = 100,000 BAU/mL","1","1","1",1,false],[false,"protein nitrogen unit (allergen testing)","[PNU]","[PNU]","procedure defined amount of a protein substance",1,[0,0,0,0,0,0,0],"PNU","chemical",false,null,null,1,false,true,0,"protein nitrogen units; PNU","UCUM","Mass","Clinical","defined as 0.01 ug of phosphotungstic acid-precipitable protein nitrogen. Being replaced by bioequivalent allergy units (BAU).","1","1","1",1,false],[false,"Limit of flocculation","[Lf]","[LF]","procedure defined amount of an antigen substance",1,[0,0,0,0,0,0,0],"Lf","chemical",false,null,null,1,false,true,0,"Lf doses","UCUM","Arb","Clinical","the antigen content forming 1:1 ratio against 1 unit of antitoxin","1","1","1",1,false],[false,"D-antigen unit (polio)","[D'ag'U]","[D'AG'U]","procedure defined amount of a poliomyelitis d-antigen substance",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,"DAgU; units","UCUM","Acnc","Clinical","unit of potency of poliovirus vaccine used for poliomyelitis prevention reported as D antigen units/mL. The unit is poliovirus type-specific.","1","1","1",1,false],[false,"fibrinogen equivalent units","[FEU]","[FEU]","amount of fibrinogen broken down into the measured d-dimers",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,"FEU","UCUM","MCnc","Clinical","Note both the FEU and DDU units are used to report D-dimer measurements. 1 DDU = 1/2 FFU","1","1","1",1,false],[false,"ELISA unit","[ELU]","[ELU]","arbitrary ELISA unit",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,"Enzyme-Linked Immunosorbent Assay Units; ELU; EL. U","UCUM","ACnc","Clinical","","1","1","1",1,false],[false,"Ehrlich units (urobilinogen)","[EU]","[EU]","Ehrlich unit",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,"EU/dL; mg{urobilinogen}/dL","UCUM","ACnc","Clinical","","1","1","1",1,false],[false,"neper","Np","NEP","level",1,[0,0,0,0,0,0,0],"Np","levels",true,null,"ln",1,true,false,0,"nepers","UCUM","LogRto","Clinical","logarithmic unit for ratios of measurements of physical field and power quantities, such as gain and loss of electronic signals","1",null,null,1,false],[false,"bel","B","B","level",1,[0,0,0,0,0,0,0],"B","levels",true,null,"lg",1,true,false,0,"bels","UCUM","LogRto","Clinical","Logarithm of the ratio of power- or field-type quantities; usually expressed in decibels ","1",null,null,1,false],[false,"bel sound pressure","B[SPL]","B[SPL]","pressure level",0.02,[-1,-2,1,0,0,0,0],"B(SPL)","levels",true,null,"lgTimes2",1,true,false,0,"bel SPL; B SPL; sound pressure bels","UCUM","LogRto","Clinical","used to measure sound level in acoustics","Pa",null,null,0.00002,false],[false,"bel volt","B[V]","B[V]","electric potential level",1000,[2,-2,1,0,0,-1,0],"B(V)","levels",true,null,"lgTimes2",1,true,false,0,"bel V; B V; volts bels","UCUM","LogRtoElp","Clinical","used to express power gain in electrical circuits","V",null,null,1,false],[false,"bel millivolt","B[mV]","B[MV]","electric potential level",1,[2,-2,1,0,0,-1,0],"B(mV)","levels",true,null,"lgTimes2",1,true,false,0,"bel mV; B mV; millivolt bels; 10^-3V bels; 10*-3V ","UCUM","LogRtoElp","Clinical","used to express power gain in electrical circuits","mV",null,null,1,false],[false,"bel microvolt","B[uV]","B[UV]","electric potential level",0.001,[2,-2,1,0,0,-1,0],"B(μV)","levels",true,null,"lgTimes2",1,true,false,0,"bel uV; B uV; microvolts bels; 10^-6V bel; 10*-6V bel","UCUM","LogRto","Clinical","used to express power gain in electrical circuits","uV",null,null,1,false],[false,"bel 10 nanovolt","B[10.nV]","B[10.NV]","electric potential level",0.000010000000000000003,[2,-2,1,0,0,-1,0],"B(10 nV)","levels",true,null,"lgTimes2",1,true,false,0,"bel 10 nV; B 10 nV; 10 nanovolts bels","UCUM","LogRtoElp","Clinical","used to express power gain in electrical circuits","nV",null,null,10,false],[false,"bel watt","B[W]","B[W]","power level",1000,[2,-3,1,0,0,0,0],"B(W)","levels",true,null,"lg",1,true,false,0,"bel W; b W; b Watt; Watts bels","UCUM","LogRto","Clinical","used to express power","W",null,null,1,false],[false,"bel kilowatt","B[kW]","B[KW]","power level",1000000,[2,-3,1,0,0,0,0],"B(kW)","levels",true,null,"lg",1,true,false,0,"bel kW; B kW; kilowatt bel; kW bel; kW B","UCUM","LogRto","Clinical","used to express power","kW",null,null,1,false],[false,"stere","st","STR","volume",1,[3,0,0,0,0,0,0],"st","misc",true,null,null,1,false,false,0,"stère; m3; cubic meter; m^3; meters cubed; metre","UCUM","Vol","Nonclinical","equal to one cubic meter, usually used for measuring firewoord","m3","M3","1",1,false],[false,"Ångström","Ao","AO","length",1.0000000000000002e-10,[1,0,0,0,0,0,0],"Å","misc",false,null,null,1,false,false,0,"Å; Angstroms; Ao; Ångströms","UCUM","Len","Clinical","equal to 10^-10 meters; used to express wave lengths and atom scaled differences ","nm","NM","0.1",0.1,false],[false,"barn","b","BRN","action area",9.999999999999999e-29,[2,0,0,0,0,0,0],"b","misc",false,null,null,1,false,false,0,"barns","UCUM","Area","Clinical","used in high-energy physics to express cross-sectional areas","fm2","FM2","100",100,false],[false,"technical atmosphere","att","ATT","pressure",98066499.99999999,[-1,-2,1,0,0,0,0],"at","misc",false,null,null,1,false,false,0,"at; tech atm; tech atmosphere; kgf/cm2; atms; atmospheres","UCUM","Pres","Obsolete","non-SI unit of pressure equal to one kilogram-force per square centimeter","kgf/cm2","KGF/CM2","1",1,false],[false,"mho","mho","MHO","electric conductance",0.001,[-2,1,-1,0,0,2,0],"mho","misc",true,null,null,1,false,false,0,"siemens; ohm reciprocals; Ω^−1; Ω-1 ","UCUM","","Obsolete","unit of electric conductance (the inverse of electrical resistance) equal to ohm^-1","S","S","1",1,false],[false,"pound per square inch","[psi]","[PSI]","pressure",6894757.293168359,[-1,-2,1,0,0,0,0],"psi","misc",false,null,null,1,false,false,0,"psi; lb/in2; lb per in2","UCUM","Pres","Clinical","","[lbf_av]/[in_i]2","[LBF_AV]/[IN_I]2","1",1,false],[false,"circle - plane angle","circ","CIRC","plane angle",6.283185307179586,[0,0,0,1,0,0,0],"circ","misc",false,null,null,1,false,false,0,"angles; circles","UCUM","Angle","Clinical","","[pi].rad","[PI].RAD","2",2,false],[false,"spere - solid angle","sph","SPH","solid angle",12.566370614359172,[0,0,0,2,0,0,0],"sph","misc",false,null,null,1,false,false,0,"speres","UCUM","Angle","Clinical","equal to the solid angle of an entire sphere = 4πsr (sr = steradian) ","[pi].sr","[PI].SR","4",4,false],[false,"metric carat","[car_m]","[CAR_M]","mass",0.2,[0,0,1,0,0,0,0],"ctm","misc",false,null,null,1,false,false,0,"carats; ct; car m","UCUM","Mass","Nonclinical","unit of mass for gemstones","g","G","2e-1",0.2,false],[false,"carat of gold alloys","[car_Au]","[CAR_AU]","mass fraction",0.041666666666666664,[0,0,0,0,0,0,0],"ctAu","misc",false,null,null,1,false,false,0,"karats; k; kt; car au; carats","UCUM","MFr","Nonclinical","unit of purity for gold alloys","/24","/24","1",1,false],[false,"Smoot","[smoot]","[SMOOT]","length",1.7018000000000002,[1,0,0,0,0,0,0],null,"misc",false,null,null,1,false,false,0,"","UCUM","Len","Nonclinical","prank unit of length from MIT","[in_i]","[IN_I]","67",67,false],[false,"meter per square seconds per square root of hertz","[m/s2/Hz^(1/2)]","[M/S2/HZ^(1/2)]","amplitude spectral density",1,[2,-3,0,0,0,0,0],null,"misc",false,null,"sqrt",1,true,false,0,"m/s2/(Hz^.5); m/s2/(Hz^(1/2)); m per s2 per Hz^1/2","UCUM","","Constant","measures amplitude spectral density, and is equal to the square root of power spectral density\n ","m2/s4/Hz",null,null,1,false],[false,"bit - logarithmic","bit_s","BIT_S","amount of information",1,[0,0,0,0,0,0,0],"bits","infotech",false,null,"ld",1,true,false,0,"bit-s; bit s; bit logarithmic","UCUM","LogA","Nonclinical","defined as the log base 2 of the number of distinct signals; cannot practically be used to express more than 1000 bits\n\nIn information theory, the definition of the amount of self-information and information entropy is often expressed with the binary logarithm (log base 2)","1",null,null,1,false],[false,"bit","bit","BIT","amount of information",1,[0,0,0,0,0,0,0],"bit","infotech",true,null,null,1,false,false,0,"bits","UCUM","","Nonclinical","dimensionless information unit of 1 used in computing and digital communications","1","1","1",1,false],[false,"byte","By","BY","amount of information",8,[0,0,0,0,0,0,0],"B","infotech",true,null,null,1,false,false,0,"bytes","UCUM","","Nonclinical","equal to 8 bits","bit","bit","8",8,false],[false,"baud","Bd","BD","signal transmission rate",1,[0,1,0,0,0,0,0],"Bd","infotech",true,null,"inv",1,false,false,0,"Bd; bauds","UCUM","Freq","Nonclinical","unit to express rate in symbols per second or pulses per second. ","s","/s","1",1,false],[false,"per twelve hour","/(12.h)","/HR","",0.000023148148148148147,[0,-1,0,0,0,0,0],"/h",null,false,null,null,1,false,false,0,"per 12 hours; 12hrs; 12 hrs; /12hrs","LOINC","Rat","Clinical","",null,null,null,null,false],[false,"per arbitrary unit","/[arb'U]","/[ARB'U]","",1,[0,0,0,0,0,0,0],"/arb/ U",null,false,null,null,1,false,true,0,"/arbU","LOINC","InvA ","Clinical","",null,null,null,null,false],[false,"per high power field","/[HPF]","/[HPF]","",1,[0,0,0,0,0,0,0],"/HPF",null,false,null,null,1,false,false,0,"/HPF; per HPF","LOINC","Naric","Clinical","",null,null,null,null,false],[false,"per international unit","/[IU]","/[IU]","",1,[0,0,0,0,0,0,0],"/i/U.",null,false,null,null,1,false,true,0,"international units; /IU; per IU","LOINC","InvA","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)",null,null,null,null,false],[false,"per low power field","/[LPF]","/[LPF]","",1,[0,0,0,0,0,0,0],"/LPF",null,false,null,null,1,false,false,0,"/LPF; per LPF","LOINC","Naric","Clinical","",null,null,null,null,false],[false,"per 10 billion ","/10*10","/10*10","",1e-10,[0,0,0,0,0,0,0],"/1010<.sup>",null,false,null,null,1,false,false,0,"/10^10; per 10*10","LOINC","NFr","Clinical","used for counting entities, e.g. blood cells; usually these kinds of terms have numerators such as moles or milligrams, and counting that amount per the number in the denominator",null,null,null,null,false],[false,"per trillion ","/10*12","/10*12","",1e-12,[0,0,0,0,0,0,0],"/1012<.sup>",null,false,null,null,1,false,false,0,"/10^12; per 10*12","LOINC","NFr","Clinical","used for counting entities, e.g. blood cells; usually these kinds of terms have numerators such as moles or milligrams, and counting that amount per the number in the denominator",null,null,null,null,false],[false,"per thousand","/10*3","/10*3","",0.001,[0,0,0,0,0,0,0],"/103<.sup>",null,false,null,null,1,false,false,0,"/10^3; per 10*3","LOINC","NFr","Clinical","used for counting entities, e.g. blood cells; usually these kinds of terms have numerators such as moles or milligrams, and counting that amount per the number in the denominator",null,null,null,null,false],[false,"per million","/10*6","/10*6","",0.000001,[0,0,0,0,0,0,0],"/106<.sup>",null,false,null,null,1,false,false,0,"/10^6; per 10*6;","LOINC","NFr","Clinical","used for counting entities, e.g. blood cells; usually these kinds of terms have numerators such as moles or milligrams, and counting that amount per the number in the denominator",null,null,null,null,false],[false,"per billion","/10*9","/10*9","",1e-9,[0,0,0,0,0,0,0],"/109<.sup>",null,false,null,null,1,false,false,0,"/10^9; per 10*9","LOINC","NFr","Clinical","used for counting entities, e.g. blood cells; usually these kinds of terms have numerators such as moles or milligrams, and counting that amount per the number in the denominator",null,null,null,null,false],[false,"per 100","/100","","",0.01,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,"per hundred; 10^2; 10*2","LOINC","NFr","Clinical","used for counting entities, e.g. blood cells; usually these kinds of terms have numerators such as moles or milligrams, and counting that amount per the number in the denominator",null,null,null,null,false],[false,"per 100 cells","/100{cells}","","",0.01,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,"/100 cells; /100cells; per hundred","LOINC","EntMass; EntNum; NFr","Clinical","",null,null,null,null,false],[false,"per 100 neutrophils","/100{neutrophils}","","",0.01,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,"/100 neutrophils; /100neutrophils; per hundred","LOINC","EntMass; EntNum; NFr","Clinical","",null,null,null,null,false],[false,"per 100 spermatozoa","/100{spermatozoa}","","",0.01,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,"/100 spermatozoa; /100spermatozoa; per hundred","LOINC","NFr","Clinical","",null,null,null,null,false],[false,"per 100 white blood cells","/100{WBCs}","","",0.01,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,"/100 WBCs; /100WBCs; per hundred","LOINC","Ratio; NFr","Clinical","",null,null,null,null,false],[false,"per year","/a","/ANN","",3.168808781402895e-8,[0,-1,0,0,0,0,0],"/a",null,false,null,null,1,false,false,0,"/Years; /yrs; yearly","LOINC","NRat","Clinical","",null,null,null,null,false],[false,"per centimeter of water","/cm[H2O]","/CM[H2O]","",0.000010197162129779282,[1,2,-1,0,0,0,0],"/cm HO2<.r>",null,false,null,null,1,false,false,0,"/cmH2O; /cm H2O; centimeters; centimetres","LOINC","InvPress","Clinical","",null,null,null,null,false],[false,"per day","/d","/D","",0.000011574074074074073,[0,-1,0,0,0,0,0],"/d",null,false,null,null,1,false,false,0,"/dy; per day","LOINC","NRat","Clinical","",null,null,null,null,false],[false,"per deciliter","/dL","/DL","",10000,[-3,0,0,0,0,0,0],"/dL",null,false,null,null,1,false,false,0,"per dL; /deciliter; decilitre","LOINC","NCnc","Clinical","",null,null,null,null,false],[false,"per gram","/g","/G","",1,[0,0,-1,0,0,0,0],"/g",null,false,null,null,1,false,false,0,"/gm; /gram; per g","LOINC","NCnt","Clinical","",null,null,null,null,false],[false,"per hour","/h","/HR","",0.0002777777777777778,[0,-1,0,0,0,0,0],"/h",null,false,null,null,1,false,false,0,"/hr; /hour; per hr","LOINC","NRat","Clinical","",null,null,null,null,false],[false,"per kilogram","/kg","/KG","",0.001,[0,0,-1,0,0,0,0],"/kg",null,false,null,null,1,false,false,0,"per kg; per kilogram","LOINC","NCnt","Clinical","",null,null,null,null,false],[false,"per liter","/L","/L","",1000,[-3,0,0,0,0,0,0],"/L",null,false,null,null,1,false,false,0,"/liter; litre","LOINC","NCnc","Clinical","",null,null,null,null,false],[false,"per square meter","/m2","/M2","",1,[-2,0,0,0,0,0,0],"/m2<.sup>",null,false,null,null,1,false,false,0,"/m^2; /m*2; /sq. m; per square meter; meter squared; metre","LOINC","Naric","Clinical","",null,null,null,null,false],[false,"per cubic meter","/m3","/M3","",1,[-3,0,0,0,0,0,0],"/m3<.sup>",null,false,null,null,1,false,false,0,"/m^3; /m*3; /cu. m; per cubic meter; meter cubed; per m3; metre","LOINC","NCncn","Clinical","",null,null,null,null,false],[false,"per milligram","/mg","/MG","",1000,[0,0,-1,0,0,0,0],"/mg",null,false,null,null,1,false,false,0,"/milligram; per mg","LOINC","NCnt","Clinical","",null,null,null,null,false],[false,"per minute","/min","/MIN","",0.016666666666666666,[0,-1,0,0,0,0,0],"/min",null,false,null,null,1,false,false,0,"/minute; per mins; breaths beats per minute","LOINC","NRat","Clinical","",null,null,null,null,false],[false,"per milliliter","/mL","/ML","",1000000,[-3,0,0,0,0,0,0],"/mL",null,false,null,null,1,false,false,0,"/milliliter; per mL; millilitre","LOINC","NCncn","Clinical","",null,null,null,null,false],[false,"per millimeter","/mm","/MM","",1000,[-1,0,0,0,0,0,0],"/mm",null,false,null,null,1,false,false,0,"/millimeter; per mm; millimetre","LOINC","InvLen","Clinical","",null,null,null,null,false],[false,"per month","/mo","/MO","",3.802570537683474e-7,[0,-1,0,0,0,0,0],"/mo",null,false,null,null,1,false,false,0,"/month; per mo; monthly; month","LOINC","NRat","Clinical","",null,null,null,null,false],[false,"per second","/s","/S","",1,[0,-1,0,0,0,0,0],"/s",null,false,null,null,1,false,false,0,"/second; /sec; per sec; frequency; Hertz; Herz; Hz; becquerels; Bq; s-1; s^-1","LOINC","NRat","Clinical","",null,null,null,null,false],[false,"per enzyme unit","/U","/U","",9.963241120049633e-17,[0,1,0,0,0,0,0],"/U",null,false,null,null,1,false,false,-1,"/enzyme units; per U","LOINC","InvC; NCat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)",null,null,null,null,false],[false,"per microliter","/uL","/UL","",999999999.9999999,[-3,0,0,0,0,0,0],"/μL",null,false,null,null,1,false,false,0,"/microliter; microlitre; /mcl; per uL","LOINC","ACnc","Clinical","",null,null,null,null,false],[false,"per week","/wk","/WK","",0.0000016534391534391535,[0,-1,0,0,0,0,0],"/wk",null,false,null,null,1,false,false,0,"/week; per wk; weekly, weeks","LOINC","NRat","Clinical","",null,null,null,null,false],[false,"APL unit per milliliter","[APL'U]/mL","[APL'U]/ML","biologic activity of anticardiolipin IgA",1000000,[-3,0,0,0,0,0,0],"/mL","chemical",false,null,null,1,false,true,0,"APL/mL; APL'U/mL; APL U/mL; APL/milliliter; IgA anticardiolipin units per milliliter; IgA Phospholipid Units; millilitre; biologic activity of","LOINC","ACnc","Clinical","Units for an anti phospholipid syndrome test","1","1","1",1,false],[false,"arbitrary unit per milliliter","[arb'U]/mL","[ARB'U]/ML","arbitrary",1000000,[-3,0,0,0,0,0,0],"(arb. U)/mL","chemical",false,null,null,1,false,true,0,"arb'U/mL; arbU/mL; arb U/mL; arbitrary units per milliliter; millilitre","LOINC","ACnc","Clinical","relative unit of measurement to show the ratio of test measurement to reference measurement","1","1","1",1,false],[false,"colony forming units per liter","[CFU]/L","[CFU]/L","amount of a proliferating organism",1000,[-3,0,0,0,0,0,0],"CFU/L","chemical",false,null,null,1,false,true,0,"CFU per Liter; CFU/L","LOINC","NCnc","Clinical","","1","1","1",1,false],[false,"colony forming units per milliliter","[CFU]/mL","[CFU]/ML","amount of a proliferating organism",1000000,[-3,0,0,0,0,0,0],"CFU/mL","chemical",false,null,null,1,false,true,0,"CFU per mL; CFU/mL","LOINC","NCnc","Clinical","","1","1","1",1,false],[false,"foot per foot - US","[ft_us]/[ft_us]","[FT_US]/[FT_US]","length",1,[0,0,0,0,0,0,0],"(ftus)/(ftus)","us-lengths",false,null,null,1,false,false,0,"ft/ft; ft per ft; feet per feet; visual acuity","","LenRto","Clinical","distance ratio to measure 20:20 vision","m/3937","M/3937","1200",1200,false],[false,"GPL unit per milliliter","[GPL'U]/mL","[GPL'U]/ML","biologic activity of anticardiolipin IgG",1000000,[-3,0,0,0,0,0,0],"/mL","chemical",false,null,null,1,false,true,0,"GPL U/mL; GPL'U/mL; GPL/mL; GPL U per mL; IgG Phospholipid Units per milliliters; IgG anticardiolipin units; millilitres ","LOINC","ACnc; AMass","Clinical","Units for an antiphospholipid test","1","1","1",1,false],[false,"international unit per 2 hour","[IU]/(2.h)","[IU]/HR","arbitrary",0.0001388888888888889,[0,-1,0,0,0,0,0],"(i.U.)/h","chemical",true,null,null,1,false,true,0,"IU/2hrs; IU/2 hours; IU per 2 hrs; international units per 2 hours","LOINC","ARat","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per 24 hour","[IU]/(24.h)","[IU]/HR","arbitrary",0.000011574074074074073,[0,-1,0,0,0,0,0],"(i.U.)/h","chemical",true,null,null,1,false,true,0,"IU/24hr; IU/24 hours; IU per 24 hrs; international units per 24 hours","LOINC","ARat","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per day","[IU]/d","[IU]/D","arbitrary",0.000011574074074074073,[0,-1,0,0,0,0,0],"(i.U.)/d","chemical",true,null,null,1,false,true,0,"IU/dy; IU/days; IU per dys; international units per day","LOINC","ARat","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per deciliter","[IU]/dL","[IU]/DL","arbitrary",10000,[-3,0,0,0,0,0,0],"(i.U.)/dL","chemical",true,null,null,1,false,true,0,"IU/dL; IU per dL; international units per deciliters; decilitres","LOINC","ACnc","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per gram","[IU]/g","[IU]/G","arbitrary",1,[0,0,-1,0,0,0,0],"(i.U.)/g","chemical",true,null,null,1,false,true,0,"IU/gm; IU/gram; IU per gm; IU per g; international units per gram","LOINC","ACnt","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per hour","[IU]/h","[IU]/HR","arbitrary",0.0002777777777777778,[0,-1,0,0,0,0,0],"(i.U.)/h","chemical",true,null,null,1,false,true,0,"IU/hrs; IU per hours; international units per hour","LOINC","ARat","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per kilogram","[IU]/kg","[IU]/KG","arbitrary",0.001,[0,0,-1,0,0,0,0],"(i.U.)/kg","chemical",true,null,null,1,false,true,0,"IU/kg; IU/kilogram; IU per kg; units","LOINC","ACnt","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per kilogram per day","[IU]/kg/d","[IU]/KG/D","arbitrary",1.1574074074074074e-8,[0,-1,-1,0,0,0,0],"(i.U.)/kg/d","chemical",true,null,null,1,false,true,0,"IU/kg/dy; IU/kg/day; IU/kilogram/day; IU per kg per day; units","LOINC","ACntRat","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per liter","[IU]/L","[IU]/L","arbitrary",1000,[-3,0,0,0,0,0,0],"(i.U.)/L","chemical",true,null,null,1,false,true,0,"IU/L; IU/liter; IU per liter; units; litre","LOINC","ACnc","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per minute","[IU]/min","[IU]/MIN","arbitrary",0.016666666666666666,[0,-1,0,0,0,0,0],"(i.U.)/min","chemical",true,null,null,1,false,true,0,"IU/min; IU/minute; IU per minute; international units","LOINC","ARat","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per milliliter","[IU]/mL","[IU]/ML","arbitrary",1000000,[-3,0,0,0,0,0,0],"(i.U.)/mL","chemical",true,null,null,1,false,true,0,"IU/mL; IU per mL; international units per milliliter; millilitre","LOINC","ACnc","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"MPL unit per milliliter","[MPL'U]/mL","[MPL'U]/ML","biologic activity of anticardiolipin IgM",1000000,[-3,0,0,0,0,0,0],"/mL","chemical",false,null,null,1,false,true,0,"MPL/mL; MPL U/mL; MPL'U/mL; IgM anticardiolipin units; IgM Phospholipid Units; millilitre ","LOINC","ACnc","Clinical","units for antiphospholipid test\n","1","1","1",1,false],[false,"number per high power field","{#}/[HPF]","/[HPF]","",1,[0,0,0,0,0,0,0],"/HPF",null,false,null,null,1,false,false,0,"#/HPF; # per HPF; number/HPF; numbers per high power field","LOINC","Naric","Clinical","",null,null,null,null,false],[false,"number per low power field","{#}/[LPF]","/[LPF]","",1,[0,0,0,0,0,0,0],"/LPF",null,false,null,null,1,false,false,0,"#/LPF; # per LPF; number/LPF; numbers per low power field","LOINC","Naric","Clinical","",null,null,null,null,false],[false,"IgA antiphosphatidylserine unit ","{APS'U}","","",1,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,"APS Unit; Phosphatidylserine Antibody IgA Units","LOINC","ACnc","Clinical","unit for antiphospholipid test",null,null,null,null,false],[false,"EIA index","{EIA_index}","","",1,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,"enzyme immunoassay index","LOINC","ACnc","Clinical","",null,null,null,null,false],[false,"kaolin clotting time","{KCT'U}","","",1,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,"KCT","LOINC","Time","Clinical","sensitive test to detect lupus anticoagulants; measured in seconds",null,null,null,null,false],[false,"IgM antiphosphatidylserine unit","{MPS'U}","","",1,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,"Phosphatidylserine Antibody IgM Measurement ","LOINC","ACnc","Clinical","",null,null,null,null,false],[false,"trillion per liter","10*12/L","(10*12)/L","number",1000000000000000,[-3,0,0,0,0,0,0],"(1012)/L","dimless",false,null,null,1,false,false,0,"10^12/L; 10*12 per Liter; trillion per liter; litre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"10^3 (used for cell count)","10*3","10*3","number",1000,[0,0,0,0,0,0,0],"103","dimless",false,null,null,1,false,false,0,"10^3; thousand","LOINC","Num","Clinical","usually used for counting entities (e.g. blood cells) per volume","1","1","10",10,false],[false,"thousand per liter","10*3/L","(10*3)/L","number",1000000,[-3,0,0,0,0,0,0],"(103)/L","dimless",false,null,null,1,false,false,0,"10^3/L; 10*3 per liter; litre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"thousand per milliliter","10*3/mL","(10*3)/ML","number",1000000000,[-3,0,0,0,0,0,0],"(103)/mL","dimless",false,null,null,1,false,false,0,"10^3/mL; 10*3 per mL; thousand per milliliter; millilitre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"thousand per microliter","10*3/uL","(10*3)/UL","number",999999999999.9999,[-3,0,0,0,0,0,0],"(103)/μL","dimless",false,null,null,1,false,false,0,"10^3/uL; 10*3 per uL; thousand per microliter; microlitre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"10 thousand per microliter","10*4/uL","(10*4)/UL","number",10000000000000,[-3,0,0,0,0,0,0],"(104)/μL","dimless",false,null,null,1,false,false,0,"10^4/uL; 10*4 per uL; microlitre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"10^5 ","10*5","10*5","number",100000,[0,0,0,0,0,0,0],"105","dimless",false,null,null,1,false,false,0,"one hundred thousand","LOINC","Num","Clinical","","1","1","10",10,false],[false,"10^6","10*6","10*6","number",1000000,[0,0,0,0,0,0,0],"106","dimless",false,null,null,1,false,false,0,"","LOINC","Num","Clinical","","1","1","10",10,false],[false,"million colony forming unit per liter","10*6.[CFU]/L","(10*6).[CFU]/L","number",1000000000,[-3,0,0,0,0,0,0],"(106).CFU/L","dimless",false,null,null,1,false,true,0,"10*6 CFU/L; 10^6 CFU/L; 10^6CFU; 10^6 CFU per liter; million colony forming units; litre","LOINC","ACnc","Clinical","","1","1","10",10,false],[false,"million international unit","10*6.[IU]","(10*6).[IU]","number",1000000,[0,0,0,0,0,0,0],"(106).(i.U.)","dimless",false,null,null,1,false,true,0,"10*6 IU; 10^6 IU; international units","LOINC","arb","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","1","1","10",10,false],[false,"million per 24 hour","10*6/(24.h)","(10*6)/HR","number",11.574074074074074,[0,-1,0,0,0,0,0],"(106)/h","dimless",false,null,null,1,false,false,0,"10*6/24hrs; 10^6/24 hrs; 10*6 per 24 hrs; 10^6 per 24 hours","LOINC","NRat","Clinical","","1","1","10",10,false],[false,"million per kilogram","10*6/kg","(10*6)/KG","number",1000,[0,0,-1,0,0,0,0],"(106)/kg","dimless",false,null,null,1,false,false,0,"10^6/kg; 10*6 per kg; 10*6 per kilogram; millions","LOINC","NCnt","Clinical","","1","1","10",10,false],[false,"million per liter","10*6/L","(10*6)/L","number",1000000000,[-3,0,0,0,0,0,0],"(106)/L","dimless",false,null,null,1,false,false,0,"10^6/L; 10*6 per Liter; 10^6 per Liter; litre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"million per milliliter","10*6/mL","(10*6)/ML","number",1000000000000,[-3,0,0,0,0,0,0],"(106)/mL","dimless",false,null,null,1,false,false,0,"10^6/mL; 10*6 per mL; 10*6 per milliliter; millilitre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"million per microliter","10*6/uL","(10*6)/UL","number",1000000000000000,[-3,0,0,0,0,0,0],"(106)/μL","dimless",false,null,null,1,false,false,0,"10^6/uL; 10^6 per uL; 10^6/mcl; 10^6 per mcl; 10^6 per microliter; microlitre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"10^8","10*8","10*8","number",100000000,[0,0,0,0,0,0,0],"108","dimless",false,null,null,1,false,false,0,"100 million; one hundred million; 10^8","LOINC","Num","Clinical","","1","1","10",10,false],[false,"billion per liter","10*9/L","(10*9)/L","number",1000000000000,[-3,0,0,0,0,0,0],"(109)/L","dimless",false,null,null,1,false,false,0,"10^9/L; 10*9 per Liter; litre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"billion per milliliter","10*9/mL","(10*9)/ML","number",1000000000000000,[-3,0,0,0,0,0,0],"(109)/mL","dimless",false,null,null,1,false,false,0,"10^9/mL; 10*9 per mL; 10^9 per mL; 10*9 per milliliter; millilitre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"billion per microliter","10*9/uL","(10*9)/UL","number",1000000000000000000,[-3,0,0,0,0,0,0],"(109)/μL","dimless",false,null,null,1,false,false,0,"10^9/uL; 10^9 per uL; 10^9/mcl; 10^9 per mcl; 10*9 per uL; 10*9 per mcl; 10*9/mcl; 10^9 per microliter; microlitre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"10 liter per minute per square meter","10.L/(min.m2)","L/(MIN.M2)","",0.00016666666666666666,[1,-1,0,0,0,0,0],"L/(min.(m2))",null,false,null,null,1,false,false,0,"10 liters per minutes per square meter; 10 L per min per m2; m^2; 10 L/(min*m2); 10L/(min*m^2); litres; sq. meter; metre; meters squared","LOINC","ArVRat","Clinical","",null,null,null,null,false],[false,"10 liter per minute","10.L/min","L/MIN","",0.00016666666666666666,[3,-1,0,0,0,0,0],"L/min",null,false,null,null,1,false,false,0,"10 liters per minute; 10 L per min; 10L; 10 L/min; litre","LOINC","VRat","Clinical","",null,null,null,null,false],[false,"10 micronewton second per centimeter to the fifth power per square meter","10.uN.s/(cm5.m2)","(UN.S)/(CM5.M2)","",100000000,[-6,-1,1,0,0,0,0],"(μN.s)/(cm5).(m2)",null,false,null,null,1,false,false,0,"dyne seconds per centimeter5 and square meter; dyn.s/(cm5.m2); dyn.s/cm5/m2; cm^5; m^2","LOINC","","Clinical","unit to measure systemic vascular resistance per body surface area",null,null,null,null,false],[false,"24 hour","24.h","HR","",86400,[0,1,0,0,0,0,0],"h",null,false,null,null,1,false,false,0,"24hrs; 24 hrs; 24 hours; days; dy","LOINC","Time","Clinical","",null,null,null,null,false],[false,"ampere per meter","A/m","A/M","electric current",1,[-1,-1,0,0,0,1,0],"A/m","si",true,null,null,1,false,false,0,"A/m; amp/meter; magnetic field strength; H; B; amperes per meter; metre","LOINC","","Clinical","unit of magnetic field strength","C/s","C/S","1",1,false],[true,"centigram","cg","CG","mass",0.01,[0,0,1,0,0,0,0],"cg",null,false,"M",null,1,false,false,0,"centigrams; cg; cgm","LOINC","Mass","Clinical","",null,null,null,null,false],[false,"centiliter","cL","CL","volume",0.00001,[3,0,0,0,0,0,0],"cL","iso1000",true,null,null,1,false,false,0,"centiliters; centilitres","LOINC","Vol","Clinical","","l",null,"1",1,false],[true,"centimeter","cm","CM","length",0.01,[1,0,0,0,0,0,0],"cm",null,false,"L",null,1,false,false,0,"centimeters; centimetres","LOINC","Len","Clinical","",null,null,null,null,false],[false,"centimeter of water","cm[H2O]","CM[H2O]","pressure",98066.5,[-1,-2,1,0,0,0,0],"cm HO2","clinical",true,null,null,1,false,false,0,"cm H2O; cmH2O; centimetres; pressure","LOINC","Pres","Clinical","unit of pressure mostly applies to blood pressure","kPa","KPAL","980665e-5",9.80665,false],[false,"centimeter of water per liter per second","cm[H2O]/L/s","(CM[H2O]/L)/S","pressure",98066500,[-4,-3,1,0,0,0,0],"(cm HO2)/L/s","clinical",true,null,null,1,false,false,0,"cm[H2O]/(L/s); cm[H2O].s/L; cm H2O/L/sec; cmH2O/L/sec; cmH2O/Liter; cmH2O per L per secs; centimeters of water per liters per second; centimetres; litres; cm[H2O]/(L/s)","LOINC","PresRat","Clinical","unit used to measure mean pulmonary resistance","kPa","KPAL","980665e-5",9.80665,false],[false,"centimeter of water per second per meter","cm[H2O]/s/m","(CM[H2O]/S)/M","pressure",98066.5,[-2,-3,1,0,0,0,0],"(cm HO2)/s/m","clinical",true,null,null,1,false,false,0,"cm[H2O]/(s.m); cm H2O/s/m; cmH2O; cmH2O/sec/m; cmH2O per secs per meters; centimeters of water per seconds per meter; centimetres; metre","LOINC","PresRat","Clinical","unit used to measure pulmonary pressure time product","kPa","KPAL","980665e-5",9.80665,false],[false,"centimeter of mercury","cm[Hg]","CM[HG]","pressure",1333220,[-1,-2,1,0,0,0,0],"cm Hg","clinical",true,null,null,1,false,false,0,"centimeters of mercury; centimetres; cmHg; cm Hg","LOINC","Pres","Clinical","unit of pressure where 1 cmHg = 10 torr","kPa","KPAL","133.3220",133.322,false],[true,"square centimeter","cm2","CM2","length",0.0001,[2,0,0,0,0,0,0],"cm2",null,false,"L",null,1,false,false,0,"cm^2; sq cm; centimeters squared; square centimeters; centimetre; area","LOINC","Area","Clinical","",null,null,null,null,false],[true,"square centimeter per second","cm2/s","CM2/S","length",0.0001,[2,-1,0,0,0,0,0],"(cm2)/s",null,false,"L",null,1,false,false,0,"cm^2/sec; square centimeters per second; sq cm per sec; cm2; centimeters squared; centimetres","LOINC","AreaRat","Clinical","",null,null,null,null,false],[false,"centipoise","cP","CP","dynamic viscosity",1,[-1,-1,1,0,0,0,0],"cP","cgs",true,null,null,1,false,false,0,"cps; centiposes","LOINC","Visc","Clinical","unit of dynamic viscosity in the CGS system with base units: 10^−3 Pa.s = 1 mPa·.s (1 millipascal second)","dyn.s/cm2","DYN.S/CM2","1",1,false],[false,"centistoke","cSt","CST","kinematic viscosity",0.0000010000000000000002,[2,-1,0,0,0,0,0],"cSt","cgs",true,null,null,1,false,false,0,"centistokes","LOINC","Visc","Clinical","unit for kinematic viscosity with base units of mm^2/s (square millimeter per second)","cm2/s","CM2/S","1",1,false],[false,"dekaliter per minute","daL/min","DAL/MIN","volume",0.00016666666666666666,[3,-1,0,0,0,0,0],"daL/min","iso1000",true,null,null,1,false,false,0,"dekalitres; dekaliters per minute; per min","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"dekaliter per minute per square meter","daL/min/m2","(DAL/MIN)/M2","volume",0.00016666666666666666,[1,-1,0,0,0,0,0],"(daL/min)/(m2)","iso1000",true,null,null,1,false,false,0,"daL/min/m^2; daL/minute/m2; sq. meter; dekaliters per minutes per square meter; meter squared; dekalitres; metre","LOINC","ArVRat","Clinical","The area usually is the body surface area used to normalize cardiovascular measures for patient's size","l",null,"1",1,false],[false,"decibel","dB","DB","level",1,[0,0,0,0,0,0,0],"dB","levels",true,null,"lg",0.1,true,false,0,"decibels","LOINC","LogRto","Clinical","unit most commonly used in acoustics as unit of sound pressure level. (also see B[SPL] or bel sound pressure level). ","1",null,null,1,false],[false,"degree per second","deg/s","DEG/S","plane angle",0.017453292519943295,[0,-1,0,1,0,0,0],"°/s","iso1000",false,null,null,1,false,false,0,"deg/sec; deg per sec; °/sec; twist rate; angular speed; rotational speed","LOINC","ARat","Clinical","unit of angular (rotational) speed used to express turning rate","[pi].rad/360","[PI].RAD/360","2",2,false],[true,"decigram","dg","DG","mass",0.1,[0,0,1,0,0,0,0],"dg",null,false,"M",null,1,false,false,0,"decigrams; dgm; 0.1 grams; 1/10 gm","LOINC","Mass","Clinical","equal to 1/10 gram",null,null,null,null,false],[false,"deciliter","dL","DL","volume",0.0001,[3,0,0,0,0,0,0],"dL","iso1000",true,null,null,1,false,false,0,"deciliters; decilitres; 0.1 liters; 1/10 L","LOINC","Vol","Clinical","equal to 1/10 liter","l",null,"1",1,false],[true,"decimeter","dm","DM","length",0.1,[1,0,0,0,0,0,0],"dm",null,false,"L",null,1,false,false,0,"decimeters; decimetres; 0.1 meters; 1/10 m; 10 cm; centimeters","LOINC","Len","Clinical","equal to 1/10 meter or 10 centimeters",null,null,null,null,false],[true,"square decimeter per square second","dm2/s2","DM2/S2","length",0.010000000000000002,[2,-2,0,0,0,0,0],"(dm2)/(s2)",null,false,"L",null,1,false,false,0,"dm2 per s2; dm^2/s^2; decimeters squared per second squared; sq dm; sq sec","LOINC","EngMass (massic energy)","Clinical","units for energy per unit mass or Joules per kilogram (J/kg = kg.m2/s2/kg = m2/s2) ",null,null,null,null,false],[false,"dyne second per centimeter per square meter","dyn.s/(cm.m2)","(DYN.S)/(CM.M2)","force",1,[-2,-1,1,0,0,0,0],"(dyn.s)/(cm.(m2))","cgs",true,null,null,1,false,false,0,"(dyn*s)/(cm*m2); (dyn*s)/(cm*m^2); dyn s per cm per m2; m^2; dyne seconds per centimeters per square meter; centimetres; sq. meter; squared","LOINC","","Clinical","","g.cm/s2","G.CM/S2","1",1,false],[false,"dyne second per centimeter","dyn.s/cm","(DYN.S)/CM","force",1,[0,-1,1,0,0,0,0],"(dyn.s)/cm","cgs",true,null,null,1,false,false,0,"(dyn*s)/cm; dyn sec per cm; seconds; centimetre; dyne seconds","LOINC","","Clinical","","g.cm/s2","G.CM/S2","1",1,false],[false,"equivalent per liter","eq/L","EQ/L","amount of substance",6.0221366999999994e+26,[-3,0,0,0,0,0,0],"eq/L","chemical",true,null,null,1,false,false,1,"eq/liter; eq/litre; eqs; equivalents per liter; litre","LOINC","SCnc","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"equivalent per milliliter","eq/mL","EQ/ML","amount of substance",6.0221367e+29,[-3,0,0,0,0,0,0],"eq/mL","chemical",true,null,null,1,false,false,1,"equivalent/milliliter; equivalents per milliliter; eq per mL; millilitre","LOINC","SCnc","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"equivalent per millimole","eq/mmol","EQ/MMOL","amount of substance",1000,[0,0,0,0,0,0,0],"eq/mmol","chemical",true,null,null,1,false,false,0,"equivalent/millimole; equivalents per millimole; eq per mmol","LOINC","SRto","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"equivalent per micromole","eq/umol","EQ/UMOL","amount of substance",1000000,[0,0,0,0,0,0,0],"eq/μmol","chemical",true,null,null,1,false,false,0,"equivalent/micromole; equivalents per micromole; eq per umol","LOINC","SRto","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[true,"femtogram","fg","FG","mass",1e-15,[0,0,1,0,0,0,0],"fg",null,false,"M",null,1,false,false,0,"fg; fgm; femtograms; weight","LOINC","Mass","Clinical","equal to 10^-15 grams",null,null,null,null,false],[false,"femtoliter","fL","FL","volume",1e-18,[3,0,0,0,0,0,0],"fL","iso1000",true,null,null,1,false,false,0,"femtolitres; femtoliters","LOINC","Vol; EntVol","Clinical","equal to 10^-15 liters","l",null,"1",1,false],[true,"femtometer","fm","FM","length",1e-15,[1,0,0,0,0,0,0],"fm",null,false,"L",null,1,false,false,0,"femtometres; femtometers","LOINC","Len","Clinical","equal to 10^-15 meters",null,null,null,null,false],[false,"femtomole","fmol","FMOL","amount of substance",602213670,[0,0,0,0,0,0,0],"fmol","si",true,null,null,1,false,false,1,"femtomoles","LOINC","EntSub","Clinical","equal to 10^-15 moles","10*23","10*23","6.0221367",6.0221367,false],[false,"femtomole per gram","fmol/g","FMOL/G","amount of substance",602213670,[0,0,-1,0,0,0,0],"fmol/g","si",true,null,null,1,false,false,1,"femtomoles; fmol/gm; fmol per gm","LOINC","SCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"femtomole per liter","fmol/L","FMOL/L","amount of substance",602213670000,[-3,0,0,0,0,0,0],"fmol/L","si",true,null,null,1,false,false,1,"femtomoles; fmol per liter; litre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"femtomole per milligram","fmol/mg","FMOL/MG","amount of substance",602213670000,[0,0,-1,0,0,0,0],"fmol/mg","si",true,null,null,1,false,false,1,"fmol per mg; femtomoles","LOINC","SCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"femtomole per milliliter","fmol/mL","FMOL/ML","amount of substance",602213670000000,[-3,0,0,0,0,0,0],"fmol/mL","si",true,null,null,1,false,false,1,"femtomoles; millilitre; fmol per mL; fmol per milliliter","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[true,"gram meter","g.m","G.M","mass",1,[1,0,1,0,0,0,0],"g.m",null,false,"M",null,1,false,false,0,"g*m; gxm; meters; metres","LOINC","Enrg","Clinical","Unit for measuring stroke work (heart work)",null,null,null,null,false],[true,"gram per 100 gram","g/(100.g)","G/G","mass",0.01,[0,0,0,0,0,0,0],"g/g",null,false,"M",null,1,false,false,0,"g/100 gm; 100gm; grams per 100 grams; gm per 100 gm","LOINC","MCnt","Clinical","",null,null,null,null,false],[true,"gram per 12 hour","g/(12.h)","G/HR","mass",0.000023148148148148147,[0,-1,1,0,0,0,0],"g/h",null,false,"M",null,1,false,false,0,"gm/12hrs; 12 hrs; gm per 12 hrs; 12hrs; grams per 12 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"gram per 24 hour","g/(24.h)","G/HR","mass",0.000011574074074074073,[0,-1,1,0,0,0,0],"g/h",null,false,"M",null,1,false,false,0,"gm/24hrs; gm/24 hrs; gm per 24 hrs; 24hrs; grams per 24 hours; gm/dy; gm per dy; grams per day","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"gram per 3 days","g/(3.d)","G/D","mass",0.000003858024691358025,[0,-1,1,0,0,0,0],"g/d",null,false,"M",null,1,false,false,0,"gm/3dy; gm/3 dy; gm per 3 days; grams","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"gram per 4 hour","g/(4.h)","G/HR","mass",0.00006944444444444444,[0,-1,1,0,0,0,0],"g/h",null,false,"M",null,1,false,false,0,"gm/4hrs; gm/4 hrs; gm per 4 hrs; 4hrs; grams per 4 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"gram per 48 hour","g/(48.h)","G/HR","mass",0.000005787037037037037,[0,-1,1,0,0,0,0],"g/h",null,false,"M",null,1,false,false,0,"gm/48hrs; gm/48 hrs; gm per 48 hrs; 48hrs; grams per 48 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"gram per 5 hour","g/(5.h)","G/HR","mass",0.00005555555555555556,[0,-1,1,0,0,0,0],"g/h",null,false,"M",null,1,false,false,0,"gm/5hrs; gm/5 hrs; gm per 5 hrs; 5hrs; grams per 5 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"gram per 6 hour","g/(6.h)","G/HR","mass",0.000046296296296296294,[0,-1,1,0,0,0,0],"g/h",null,false,"M",null,1,false,false,0,"gm/6hrs; gm/6 hrs; gm per 6 hrs; 6hrs; grams per 6 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"gram per 72 hour","g/(72.h)","G/HR","mass",0.000003858024691358025,[0,-1,1,0,0,0,0],"g/h",null,false,"M",null,1,false,false,0,"gm/72hrs; gm/72 hrs; gm per 72 hrs; 72hrs; grams per 72 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"gram per cubic centimeter","g/cm3","G/CM3","mass",999999.9999999999,[-3,0,1,0,0,0,0],"g/(cm3)",null,false,"M",null,1,false,false,0,"g/cm^3; gm per cm3; g per cm^3; grams per centimeter cubed; cu. cm; centimetre; g/mL; gram per milliliter; millilitre","LOINC","MCnc","Clinical","g/cm3 = g/mL",null,null,null,null,false],[true,"gram per day","g/d","G/D","mass",0.000011574074074074073,[0,-1,1,0,0,0,0],"g/d",null,false,"M",null,1,false,false,0,"gm/dy; gm per dy; grams per day; gm/24hrs; gm/24 hrs; gm per 24 hrs; 24hrs; grams per 24 hours; serving","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"gram per deciliter","g/dL","G/DL","mass",10000,[-3,0,1,0,0,0,0],"g/dL",null,false,"M",null,1,false,false,0,"gm/dL; gm per dL; grams per deciliter; decilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"gram per gram","g/g","G/G","mass",1,[0,0,0,0,0,0,0],"g/g",null,false,"M",null,1,false,false,0,"gm; grams","LOINC","MRto ","Clinical","",null,null,null,null,false],[true,"gram per hour","g/h","G/HR","mass",0.0002777777777777778,[0,-1,1,0,0,0,0],"g/h",null,false,"M",null,1,false,false,0,"gm/hr; gm per hr; grams; intake; output","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"gram per hour per square meter","g/h/m2","(G/HR)/M2","mass",0.0002777777777777778,[-2,-1,1,0,0,0,0],"(g/h)/(m2)",null,false,"M",null,1,false,false,0,"gm/hr/m2; gm/h/m2; /m^2; sq. m; g per hr per m2; grams per hours per square meter; meter squared; metre","LOINC","ArMRat","Clinical","",null,null,null,null,false],[true,"gram per kilogram","g/kg ","G/KG","mass",0.001,[0,0,0,0,0,0,0],"g/kg",null,false,"M",null,1,false,false,0,"g per kg; gram per kilograms","LOINC","MCnt","Clinical","",null,null,null,null,false],[true,"gram per kilogram per 8 hour ","g/kg/(8.h)","(G/KG)/HR","mass",3.472222222222222e-8,[0,-1,0,0,0,0,0],"(g/kg)/h",null,false,"M",null,1,false,false,0,"g/(8.kg.h); gm/kg/8hrs; 8 hrs; g per kg per 8 hrs; 8hrs; grams per kilograms per 8 hours; shift","LOINC","MCntRat; RelMRat","Clinical","unit often used to describe mass in grams of protein consumed in a 8 hours, divided by the subject's body weight in kilograms. Also used to measure mass dose rate per body mass",null,null,null,null,false],[true,"gram per kilogram per day","g/kg/d","(G/KG)/D","mass",1.1574074074074074e-8,[0,-1,0,0,0,0,0],"(g/kg)/d",null,false,"M",null,1,false,false,0,"g/(kg.d); gm/kg/dy; gm per kg per dy; grams per kilograms per day","LOINC","RelMRat","Clinical","unit often used to describe mass in grams of protein consumed in a day, divided by the subject's body weight in kilograms. Also used to measure mass dose rate per body mass",null,null,null,null,false],[true,"gram per kilogram per hour","g/kg/h","(G/KG)/HR","mass",2.7777777777777776e-7,[0,-1,0,0,0,0,0],"(g/kg)/h",null,false,"M",null,1,false,false,0,"g/(kg.h); g/kg/hr; g per kg per hrs; grams per kilograms per hour","LOINC","MCntRat; RelMRat","Clinical","unit used to measure mass dose rate per body mass",null,null,null,null,false],[true,"gram per kilogram per minute","g/kg/min","(G/KG)/MIN","mass",0.000016666666666666667,[0,-1,0,0,0,0,0],"(g/kg)/min",null,false,"M",null,1,false,false,0,"g/(kg.min); g/kg/min; g per kg per min; grams per kilograms per minute","LOINC","MCntRat; RelMRat","Clinical","unit used to measure mass dose rate per body mass",null,null,null,null,false],[true,"gram per liter","g/L","G/L","mass",1000,[-3,0,1,0,0,0,0],"g/L",null,false,"M",null,1,false,false,0,"gm per liter; g/liter; grams per liter; litre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"gram per square meter","g/m2","G/M2","mass",1,[-2,0,1,0,0,0,0],"g/(m2)",null,false,"M",null,1,false,false,0,"g/m^2; gram/square meter; g/sq m; g per m2; g per m^2; grams per square meter; meters squared; metre","LOINC","ArMass","Clinical","Tests measure myocardial mass (heart ventricle system) per body surface area; unit used to measure mass dose per body surface area",null,null,null,null,false],[true,"gram per milligram","g/mg","G/MG","mass",1000,[0,0,0,0,0,0,0],"g/mg",null,false,"M",null,1,false,false,0,"g per mg; grams per milligram","LOINC","MCnt; MRto","Clinical","",null,null,null,null,false],[true,"gram per minute","g/min","G/MIN","mass",0.016666666666666666,[0,-1,1,0,0,0,0],"g/min",null,false,"M",null,1,false,false,0,"g per min; grams per minute; gram/minute","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"gram per milliliter","g/mL","G/ML","mass",1000000,[-3,0,1,0,0,0,0],"g/mL",null,false,"M",null,1,false,false,0,"g per mL; grams per milliliter; millilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"gram per millimole","g/mmol","G/MMOL","mass",1.6605401866749388e-21,[0,0,1,0,0,0,0],"g/mmol",null,false,"M",null,1,false,false,-1,"grams per millimole; g per mmol","LOINC","Ratio","Clinical","",null,null,null,null,false],[false,"joule per liter","J/L","J/L","energy",1000000,[-1,-2,1,0,0,0,0],"J/L","si",true,null,null,1,false,false,0,"joules per liter; litre; J per L","LOINC","EngCnc","Clinical","","N.m","N.M","1",1,false],[true,"degree Kelvin per Watt","K/W","K/W","temperature",0.001,[-2,3,-1,0,1,0,0],"K/W",null,false,"C",null,1,false,false,0,"degree Kelvin/Watt; K per W; thermal ohm; thermal resistance; degrees","LOINC","TempEngRat","Clinical","unit for absolute thermal resistance equal to the reciprocal of thermal conductance. Unit used for tests to measure work of breathing",null,null,null,null,false],[false,"kilo international unit per liter","k[IU]/L","K[IU]/L","arbitrary",1000000,[-3,0,0,0,0,0,0],"(ki.U.)/L","chemical",true,null,null,1,false,true,0,"kIU/L; kIU per L; kIU per liter; kilo international units; litre; allergens; allergy units","LOINC","ACnc","Clinical","IgE has an WHO reference standard so IgE allergen testing can be reported as k[IU]/L","[iU]","[IU]","1",1,false],[false,"kilo international unit per milliliter","k[IU]/mL","K[IU]/ML","arbitrary",1000000000,[-3,0,0,0,0,0,0],"(ki.U.)/mL","chemical",true,null,null,1,false,true,0,"kIU/mL; kIU per mL; kIU per milliliter; kilo international units; millilitre; allergens; allergy units","LOINC","ACnc","Clinical","IgE has an WHO reference standard so IgE allergen testing can be reported as k[IU]/mL","[iU]","[IU]","1",1,false],[false,"katal per kilogram","kat/kg","KAT/KG","catalytic activity",602213670000000000000,[0,-1,-1,0,0,0,0],"kat/kg","chemical",true,null,null,1,false,false,1,"kat per kg; katals per kilogram; mol/s/kg; moles per seconds per kilogram","LOINC","CCnt","Clinical","kat is a unit of catalytic activity with base units = mol/s. Rarely used because its units are too large to practically express catalytic activity. See enzyme unit [U] which is the standard unit for catalytic activity.","mol/s","MOL/S","1",1,false],[false,"katal per liter","kat/L","KAT/L","catalytic activity",6.0221366999999994e+26,[-3,-1,0,0,0,0,0],"kat/L","chemical",true,null,null,1,false,false,1,"kat per L; katals per liter; litre; mol/s/L; moles per seconds per liter","LOINC","CCnc","Clinical","kat is a unit of catalytic activity with base units = mol/s. Rarely used because its units are too large to practically express catalytic activity. See enzyme unit [U] which is the standard unit for catalytic activity.","mol/s","MOL/S","1",1,false],[false,"kilocalorie","kcal","KCAL","energy",4184000,[2,-2,1,0,0,0,0],"kcal","heat",true,null,null,1,false,false,0,"kilogram calories; large calories; food calories; kcals","LOINC","EngRat","Clinical","It is equal to 1000 calories (equal to 4.184 kJ). But in practical usage, kcal refers to food calories which excludes caloric content in fiber and other constitutes that is not digestible by humans. Also see nutrition label Calories ([Cal])","cal_th","CAL_TH","1",1,false],[false,"kilocalorie per 24 hour","kcal/(24.h)","KCAL/HR","energy",48.425925925925924,[2,-3,1,0,0,0,0],"kcal/h","heat",true,null,null,1,false,false,0,"kcal/24hrs; kcal/24 hrs; kcal per 24hrs; kilocalories per 24 hours; kilojoules; kJ/24hr; kJ/(24.h); kJ/dy; kilojoules per days; intake; calories burned; metabolic rate; food calories","","EngRat","Clinical","","cal_th","CAL_TH","1",1,false],[false,"kilocalorie per ounce","kcal/[oz_av]","KCAL/[OZ_AV]","energy",147586.25679704445,[2,-2,0,0,0,0,0],"kcal/oz","heat",true,null,null,1,false,false,0,"kcal/oz; kcal per ozs; large calories per ounces; food calories; servings; international","LOINC","EngCnt","Clinical","used in nutrition to represent calorie of food","cal_th","CAL_TH","1",1,false],[false,"kilocalorie per day","kcal/d","KCAL/D","energy",48.425925925925924,[2,-3,1,0,0,0,0],"kcal/d","heat",true,null,null,1,false,false,0,"kcal/dy; kcal per day; kilocalories per days; kilojoules; kJ/dy; kilojoules per days; intake; calories burned; metabolic rate; food calories","LOINC","EngRat","Clinical","unit in nutrition for food intake (measured in calories) in a day","cal_th","CAL_TH","1",1,false],[false,"kilocalorie per hour","kcal/h","KCAL/HR","energy",1162.2222222222222,[2,-3,1,0,0,0,0],"kcal/h","heat",true,null,null,1,false,false,0,"kcal/hrs; kcals per hr; intake; kilocalories per hours; kilojoules","LOINC","EngRat","Clinical","used in nutrition to represent caloric requirement or consumption","cal_th","CAL_TH","1",1,false],[false,"kilocalorie per kilogram per 24 hour","kcal/kg/(24.h)","(KCAL/KG)/HR","energy",0.04842592592592593,[2,-3,0,0,0,0,0],"(kcal/kg)/h","heat",true,null,null,1,false,false,0,"kcal/kg/24hrs; 24 hrs; kcal per kg per 24hrs; kilocalories per kilograms per 24 hours; kilojoules","LOINC","EngCntRat","Clinical","used in nutrition to represent caloric requirement per day based on subject's body weight in kilograms","cal_th","CAL_TH","1",1,false],[true,"kilogram","kg","KG","mass",1000,[0,0,1,0,0,0,0],"kg",null,false,"M",null,1,false,false,0,"kilograms; kgs","LOINC","Mass","Clinical","",null,null,null,null,false],[true,"kilogram meter per second","kg.m/s","(KG.M)/S","mass",1000,[1,-1,1,0,0,0,0],"(kg.m)/s",null,false,"M",null,1,false,false,0,"kg*m/s; kg.m per sec; kg*m per sec; p; momentum","LOINC","","Clinical","unit for momentum = mass times velocity",null,null,null,null,false],[true,"kilogram per second per square meter","kg/(s.m2)","KG/(S.M2)","mass",1000,[-2,-1,1,0,0,0,0],"kg/(s.(m2))",null,false,"M",null,1,false,false,0,"kg/(s*m2); kg/(s*m^2); kg per s per m2; per sec; per m^2; kilograms per seconds per square meter; meter squared; metre","LOINC","ArMRat","Clinical","",null,null,null,null,false],[true,"kilogram per hour","kg/h","KG/HR","mass",0.2777777777777778,[0,-1,1,0,0,0,0],"kg/h",null,false,"M",null,1,false,false,0,"kg/hr; kg per hr; kilograms per hour","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"kilogram per liter","kg/L","KG/L","mass",1000000,[-3,0,1,0,0,0,0],"kg/L",null,false,"M",null,1,false,false,0,"kg per liter; litre; kilograms","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"kilogram per square meter","kg/m2","KG/M2","mass",1000,[-2,0,1,0,0,0,0],"kg/(m2)",null,false,"M",null,1,false,false,0,"kg/m^2; kg/sq. m; kg per m2; per m^2; per sq. m; kilograms; meter squared; metre; BMI","LOINC","Ratio","Clinical","units for body mass index (BMI)",null,null,null,null,false],[true,"kilogram per cubic meter","kg/m3","KG/M3","mass",1000,[-3,0,1,0,0,0,0],"kg/(m3)",null,false,"M",null,1,false,false,0,"kg/m^3; kg/cu. m; kg per m3; per m^3; per cu. m; kilograms; meters cubed; metre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"kilogram per minute","kg/min","KG/MIN","mass",16.666666666666668,[0,-1,1,0,0,0,0],"kg/min",null,false,"M",null,1,false,false,0,"kilogram/minute; kg per min; kilograms per minute","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"kilogram per mole","kg/mol","KG/MOL","mass",1.6605401866749388e-21,[0,0,1,0,0,0,0],"kg/mol",null,false,"M",null,1,false,false,-1,"kilogram/mole; kg per mol; kilograms per mole","LOINC","SCnt","Clinical","",null,null,null,null,false],[true,"kilogram per second","kg/s","KG/S","mass",1000,[0,-1,1,0,0,0,0],"kg/s",null,false,"M",null,1,false,false,0,"kg/sec; kilogram/second; kg per sec; kilograms; second","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"kiloliter","kL","KL","volume",1,[3,0,0,0,0,0,0],"kL","iso1000",true,null,null,1,false,false,0,"kiloliters; kilolitres; m3; m^3; meters cubed; metre","LOINC","Vol","Clinical","","l",null,"1",1,false],[true,"kilometer","km","KM","length",1000,[1,0,0,0,0,0,0],"km",null,false,"L",null,1,false,false,0,"kilometers; kilometres; distance","LOINC","Len","Clinical","",null,null,null,null,false],[false,"kilopascal","kPa","KPAL","pressure",1000000,[-1,-2,1,0,0,0,0],"kPa","si",true,null,null,1,false,false,0,"kilopascals; pressure","LOINC","Pres; PPresDiff","Clinical","","N/m2","N/M2","1",1,false],[true,"kilosecond","ks","KS","time",1000,[0,1,0,0,0,0,0],"ks",null,false,"T",null,1,false,false,0,"kiloseconds; ksec","LOINC","Time","Clinical","",null,null,null,null,false],[false,"kilo enzyme unit","kU","KU","catalytic activity",10036894500000000000,[0,-1,0,0,0,0,0],"kU","chemical",true,null,null,1,false,false,1,"units; mmol/min; millimoles per minute","LOINC","CAct","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 kU = 1 mmol/min","umol/min","UMOL/MIN","1",1,false],[false,"kilo enzyme unit per gram","kU/g","KU/G","catalytic activity",10036894500000000000,[0,-1,-1,0,0,0,0],"kU/g","chemical",true,null,null,1,false,false,1,"units per grams; kU per gm","LOINC","CCnt","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 kU = 1 mmol/min","umol/min","UMOL/MIN","1",1,false],[false,"kilo enzyme unit per liter","kU/L","KU/L","catalytic activity",1.00368945e+22,[-3,-1,0,0,0,0,0],"kU/L","chemical",true,null,null,1,false,false,1,"units per liter; litre; enzymatic activity; enzyme activity per volume; activities","LOINC","ACnc; CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 kU = 1 mmol/min","umol/min","UMOL/MIN","1",1,false],[false,"kilo enzyme unit per milliliter","kU/mL","KU/ML","catalytic activity",1.00368945e+25,[-3,-1,0,0,0,0,0],"kU/mL","chemical",true,null,null,1,false,false,1,"kU per mL; units per milliliter; millilitre; enzymatic activity per volume; enzyme activities","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 kU = 1 mmol/min","umol/min","UMOL/MIN","1",1,false],[false,"Liters per 24 hour","L/(24.h)","L/HR","volume",1.1574074074074074e-8,[3,-1,0,0,0,0,0],"L/h","iso1000",true,null,null,1,false,false,0,"L/24hrs; L/24 hrs; L per 24hrs; liters per 24 hours; day; dy; litres; volume flow rate","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"Liters per 8 hour","L/(8.h)","L/HR","volume",3.472222222222222e-8,[3,-1,0,0,0,0,0],"L/h","iso1000",true,null,null,1,false,false,0,"L/8hrs; L/8 hrs; L per 8hrs; liters per 8 hours; litres; volume flow rate; shift","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"Liters per minute per square meter","L/(min.m2) ","L/(MIN.M2)","volume",0.000016666666666666667,[1,-1,0,0,0,0,0],"L/(min.(m2))","iso1000",true,null,null,1,false,false,0,"L/(min.m2); L/min/m^2; L/min/sq. meter; L per min per m2; m^2; liters per minutes per square meter; meter squared; litres; metre ","LOINC","ArVRat","Clinical","unit for tests that measure cardiac output per body surface area (cardiac index)","l",null,"1",1,false],[false,"Liters per day","L/d","L/D","volume",1.1574074074074074e-8,[3,-1,0,0,0,0,0],"L/d","iso1000",true,null,null,1,false,false,0,"L/dy; L per day; 24hrs; 24 hrs; 24 hours; liters; litres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"Liters per hour","L/h","L/HR","volume",2.7777777777777776e-7,[3,-1,0,0,0,0,0],"L/h","iso1000",true,null,null,1,false,false,0,"L/hr; L per hr; litres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"Liters per kilogram","L/kg","L/KG","volume",0.000001,[3,0,-1,0,0,0,0],"L/kg","iso1000",true,null,null,1,false,false,0,"L per kg; litre","LOINC","VCnt","Clinical","","l",null,"1",1,false],[false,"Liters per liter","L/L","L/L","volume",1,[0,0,0,0,0,0,0],"L/L","iso1000",true,null,null,1,false,false,0,"L per L; liter/liter; litre","LOINC","VFr","Clinical","","l",null,"1",1,false],[false,"Liters per minute","L/min","L/MIN","volume",0.000016666666666666667,[3,-1,0,0,0,0,0],"L/min","iso1000",true,null,null,1,false,false,0,"liters per minute; litre","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"Liters per minute per square meter","L/min/m2","(L/MIN)/M2","volume",0.000016666666666666667,[1,-1,0,0,0,0,0],"(L/min)/(m2)","iso1000",true,null,null,1,false,false,0,"L/(min.m2); L/min/m^2; L/min/sq. meter; L per min per m2; m^2; liters per minutes per square meter; meter squared; litres; metre ","","ArVRat","Clinical","unit for tests that measure cardiac output per body surface area (cardiac index)","l",null,"1",1,false],[false,"Liters per second","L/s","L/S","volume",0.001,[3,-1,0,0,0,0,0],"L/s","iso1000",true,null,null,1,false,false,0,"L per sec; litres","LOINC","VRat","Clinical","unit used often to measure gas flow and peak expiratory flow","l",null,"1",1,false],[false,"Liters per second per square second","L/s/s2","(L/S)/S2","volume",0.001,[3,-3,0,0,0,0,0],"(L/s)/(s2)","iso1000",true,null,null,1,false,false,0,"L/s/s^2; L/sec/sec2; L/sec/sec^2; L/sec/sq. sec; L per s per s2; L per sec per sec2; s^2; sec^2; liters per seconds per square second; second squared; litres ","LOINC","ArVRat","Clinical","unit for tests that measure cardiac output/body surface area","l",null,"1",1,false],[false,"lumen square meter","lm.m2","LM.M2","luminous flux",1,[2,0,0,2,0,0,1],"lm.(m2)","si",true,null,null,1,false,false,0,"lm*m2; lm*m^2; lumen meters squared; lumen sq. meters; metres","LOINC","","Clinical","","cd.sr","CD.SR","1",1,false],[true,"meter per second","m/s","M/S","length",1,[1,-1,0,0,0,0,0],"m/s",null,false,"L",null,1,false,false,0,"meter/second; m per sec; meters per second; metres; velocity; speed","LOINC","Vel","Clinical","unit of velocity",null,null,null,null,false],[true,"meter per square second","m/s2","M/S2","length",1,[1,-2,0,0,0,0,0],"m/(s2)",null,false,"L",null,1,false,false,0,"m/s^2; m/sq. sec; m per s2; per s^2; meters per square second; second squared; sq second; metres; acceleration","LOINC","Accel","Clinical","unit of acceleration",null,null,null,null,false],[false,"milli international unit per liter","m[IU]/L","M[IU]/L","arbitrary",1,[-3,0,0,0,0,0,0],"(mi.U.)/L","chemical",true,null,null,1,false,true,0,"mIU/L; m IU/L; mIU per liter; units; litre","LOINC","ACnc","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"milli international unit per milliliter","m[IU]/mL","M[IU]/ML","arbitrary",1000.0000000000001,[-3,0,0,0,0,0,0],"(mi.U.)/mL","chemical",true,null,null,1,false,true,0,"mIU/mL; m IU/mL; mIU per mL; milli international units per milliliter; millilitre","LOINC","ACnc","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[true,"square meter","m2","M2","length",1,[2,0,0,0,0,0,0],"m2",null,false,"L",null,1,false,false,0,"m^2; sq m; square meters; meters squared; metres","LOINC","Area","Clinical","unit often used to represent body surface area",null,null,null,null,false],[true,"square meter per second","m2/s","M2/S","length",1,[2,-1,0,0,0,0,0],"(m2)/s",null,false,"L",null,1,false,false,0,"m^2/sec; m2 per sec; m^2 per sec; sq m/sec; meters squared/seconds; sq m per sec; meters squared; metres","LOINC","ArRat","Clinical","",null,null,null,null,false],[true,"cubic meter per second","m3/s","M3/S","length",1,[3,-1,0,0,0,0,0],"(m3)/s",null,false,"L",null,1,false,false,0,"m^3/sec; m3 per sec; m^3 per sec; cu m/sec; cubic meters per seconds; meters cubed; metres","LOINC","VRat","Clinical","",null,null,null,null,false],[false,"milliampere","mA","MA","electric current",0.001,[0,-1,0,0,0,1,0],"mA","si",true,null,null,1,false,false,0,"mamp; milliamperes","LOINC","ElpotRat","Clinical","unit of electric current","C/s","C/S","1",1,false],[false,"millibar","mbar","MBAR","pressure",100000,[-1,-2,1,0,0,0,0],"mbar","iso1000",true,null,null,1,false,false,0,"millibars","LOINC","Pres","Clinical","unit of pressure","Pa","PAL","1e5",100000,false],[false,"millibar second per liter","mbar.s/L","(MBAR.S)/L","pressure",100000000,[-4,-1,1,0,0,0,0],"(mbar.s)/L","iso1000",true,null,null,1,false,false,0,"mbar*s/L; mbar.s per L; mbar*s per L; millibar seconds per liter; millibar second per litre","LOINC","","Clinical","unit to measure expiratory resistance","Pa","PAL","1e5",100000,false],[false,"millibar per liter per second","mbar/L/s","(MBAR/L)/S","pressure",100000000,[-4,-3,1,0,0,0,0],"(mbar/L)/s","iso1000",true,null,null,1,false,false,0,"mbar/(L.s); mbar/L/sec; mbar/liter/second; mbar per L per sec; mbar per liter per second; millibars per liters per seconds; litres","LOINC","PresCncRat","Clinical","unit to measure expiratory resistance","Pa","PAL","1e5",100000,false],[false,"milliequivalent","meq","MEQ","amount of substance",602213670000000000000,[0,0,0,0,0,0,0],"meq","chemical",true,null,null,1,false,false,1,"milliequivalents; meqs","LOINC","Sub","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per 2 hour","meq/(2.h)","MEQ/HR","amount of substance",83640787500000000,[0,-1,0,0,0,0,0],"meq/h","chemical",true,null,null,1,false,false,1,"meq/2hrs; meq/2 hrs; meq per 2 hrs; milliequivalents per 2 hours","LOINC","SRat","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per 24 hour","meq/(24.h)","MEQ/HR","amount of substance",6970065625000000,[0,-1,0,0,0,0,0],"meq/h","chemical",true,null,null,1,false,false,1,"meq/24hrs; meq/24 hrs; meq per 24 hrs; milliequivalents per 24 hours","LOINC","SRat","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per 8 hour","meq/(8.h)","MEQ/HR","amount of substance",20910196875000000,[0,-1,0,0,0,0,0],"meq/h","chemical",true,null,null,1,false,false,1,"meq/8hrs; meq/8 hrs; meq per 8 hrs; milliequivalents per 8 hours; shift","LOINC","SRat","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per day","meq/d","MEQ/D","amount of substance",6970065625000000,[0,-1,0,0,0,0,0],"meq/d","chemical",true,null,null,1,false,false,1,"meq/dy; meq per day; milliquivalents per days; meq/24hrs; meq/24 hrs; meq per 24 hrs; milliequivalents per 24 hours","LOINC","SRat","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per deciliter","meq/dL","MEQ/DL","amount of substance",6.022136699999999e+24,[-3,0,0,0,0,0,0],"meq/dL","chemical",true,null,null,1,false,false,1,"meq per dL; milliequivalents per deciliter; decilitre","LOINC","SCnc","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per gram","meq/g","MEQ/G","amount of substance",602213670000000000000,[0,0,-1,0,0,0,0],"meq/g","chemical",true,null,null,1,false,false,1,"mgq/gm; meq per gm; milliequivalents per gram","LOINC","MCnt","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per hour","meq/h","MEQ/HR","amount of substance",167281575000000000,[0,-1,0,0,0,0,0],"meq/h","chemical",true,null,null,1,false,false,1,"meq/hrs; meq per hrs; milliequivalents per hour","LOINC","SRat","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per kilogram","meq/kg","MEQ/KG","amount of substance",602213670000000000,[0,0,-1,0,0,0,0],"meq/kg","chemical",true,null,null,1,false,false,1,"meq per kg; milliequivalents per kilogram","LOINC","SCnt","Clinical","equivalence equals moles per valence; used to measure dose per patient body mass","mol","MOL","1",1,false],[false,"milliequivalent per kilogram per hour","meq/kg/h","(MEQ/KG)/HR","amount of substance",167281575000000,[0,-1,-1,0,0,0,0],"(meq/kg)/h","chemical",true,null,null,1,false,false,1,"meq/(kg.h); meq/kg/hr; meq per kg per hr; milliequivalents per kilograms per hour","LOINC","SCntRat","Clinical","equivalence equals moles per valence; unit used to measure dose rate per patient body mass","mol","MOL","1",1,false],[false,"milliequivalent per liter","meq/L","MEQ/L","amount of substance",6.0221367e+23,[-3,0,0,0,0,0,0],"meq/L","chemical",true,null,null,1,false,false,1,"milliequivalents per liter; litre; meq per l; acidity","LOINC","SCnc","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per square meter","meq/m2","MEQ/M2","amount of substance",602213670000000000000,[-2,0,0,0,0,0,0],"meq/(m2)","chemical",true,null,null,1,false,false,1,"meq/m^2; meq/sq. m; milliequivalents per square meter; meter squared; metre","LOINC","ArSub","Clinical","equivalence equals moles per valence; note that the use of m2 in clinical units ofter refers to body surface area","mol","MOL","1",1,false],[false,"milliequivalent per minute","meq/min","MEQ/MIN","amount of substance",10036894500000000000,[0,-1,0,0,0,0,0],"meq/min","chemical",true,null,null,1,false,false,1,"meq per min; milliequivalents per minute","LOINC","SRat","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per milliliter","meq/mL","MEQ/ML","amount of substance",6.0221367e+26,[-3,0,0,0,0,0,0],"meq/mL","chemical",true,null,null,1,false,false,1,"meq per mL; milliequivalents per milliliter; millilitre","LOINC","SCnc","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[true,"milligram","mg","MG","mass",0.001,[0,0,1,0,0,0,0],"mg",null,false,"M",null,1,false,false,0,"milligrams","LOINC","Mass","Clinical","",null,null,null,null,false],[true,"milligram per 10 hour","mg/(10.h)","MG/HR","mass",2.7777777777777777e-8,[0,-1,1,0,0,0,0],"mg/h",null,false,"M",null,1,false,false,0,"mg/10hrs; mg/10 hrs; mg per 10 hrs; milligrams per 10 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"milligram per 12 hour","mg/(12.h)","MG/HR","mass",2.3148148148148148e-8,[0,-1,1,0,0,0,0],"mg/h",null,false,"M",null,1,false,false,0,"mg/12hrs; mg/12 hrs; per 12 hrs; 12hrs; milligrams per 12 hours","LOINC","MRat","Clinical","units used for tests in urine",null,null,null,null,false],[true,"milligram per 2 hour","mg/(2.h)","MG/HR","mass",1.3888888888888888e-7,[0,-1,1,0,0,0,0],"mg/h",null,false,"M",null,1,false,false,0,"mg/2hrs; mg/2 hrs; mg per 2 hrs; 2hrs; milligrams per 2 hours","LOINC","MRat","Clinical","units used for tests in urine",null,null,null,null,false],[true,"milligram per 24 hour","mg/(24.h)","MG/HR","mass",1.1574074074074074e-8,[0,-1,1,0,0,0,0],"mg/h",null,false,"M",null,1,false,false,0,"mg/24hrs; mg/24 hrs; milligrams per 24 hours; mg/kg/dy; mg per kg per day; milligrams per kilograms per days","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"milligram per 6 hour","mg/(6.h)","MG/HR","mass",4.6296296296296295e-8,[0,-1,1,0,0,0,0],"mg/h",null,false,"M",null,1,false,false,0,"mg/6hrs; mg/6 hrs; mg per 6 hrs; 6hrs; milligrams per 6 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"milligram per 72 hour","mg/(72.h)","MG/HR","mass",3.858024691358025e-9,[0,-1,1,0,0,0,0],"mg/h",null,false,"M",null,1,false,false,0,"mg/72hrs; mg/72 hrs; 72 hrs; 72hrs; milligrams per 72 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"milligram per 8 hour","mg/(8.h)","MG/HR","mass",3.472222222222222e-8,[0,-1,1,0,0,0,0],"mg/h",null,false,"M",null,1,false,false,0,"mg/8hrs; mg/8 hrs; milligrams per 8 hours; shift","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"milligram per day","mg/d","MG/D","mass",1.1574074074074074e-8,[0,-1,1,0,0,0,0],"mg/d",null,false,"M",null,1,false,false,0,"mg/24hrs; mg/24 hrs; milligrams per 24 hours; mg/dy; mg per day; milligrams","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"milligram per deciliter","mg/dL","MG/DL","mass",10,[-3,0,1,0,0,0,0],"mg/dL",null,false,"M",null,1,false,false,0,"mg per dL; milligrams per deciliter; decilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"milligram per gram","mg/g","MG/G","mass",0.001,[0,0,0,0,0,0,0],"mg/g",null,false,"M",null,1,false,false,0,"mg per gm; milligrams per gram","LOINC","MCnt; MRto","Clinical","",null,null,null,null,false],[true,"milligram per hour","mg/h","MG/HR","mass",2.7777777777777776e-7,[0,-1,1,0,0,0,0],"mg/h",null,false,"M",null,1,false,false,0,"mg/hr; mg per hr; milligrams","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"milligram per kilogram","mg/kg","MG/KG","mass",0.000001,[0,0,0,0,0,0,0],"mg/kg",null,false,"M",null,1,false,false,0,"mg per kg; milligrams per kilograms","LOINC","MCnt","Clinical","",null,null,null,null,false],[true,"milligram per kilogram per 8 hour","mg/kg/(8.h)","(MG/KG)/HR","mass",3.472222222222222e-11,[0,-1,0,0,0,0,0],"(mg/kg)/h",null,false,"M",null,1,false,false,0,"mg/(8.h.kg); mg/kg/8hrs; mg/kg/8 hrs; mg per kg per 8hrs; 8 hrs; milligrams per kilograms per 8 hours; shift","LOINC","RelMRat; MCntRat","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[true,"milligram per kilogram per day","mg/kg/d","(MG/KG)/D","mass",1.1574074074074074e-11,[0,-1,0,0,0,0,0],"(mg/kg)/d",null,false,"M",null,1,false,false,0,"mg/(kg.d); mg/(kg.24.h)mg/kg/dy; mg per kg per day; milligrams per kilograms per days; mg/kg/(24.h); mg/kg/24hrs; 24 hrs; 24 hours","LOINC","RelMRat ","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[true,"milligram per kilogram per hour","mg/kg/h","(MG/KG)/HR","mass",2.7777777777777777e-10,[0,-1,0,0,0,0,0],"(mg/kg)/h",null,false,"M",null,1,false,false,0,"mg/(kg.h); mg/kg/hr; mg per kg per hr; milligrams per kilograms per hour","LOINC","RelMRat; MCntRat","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[true,"milligram per kilogram per minute","mg/kg/min","(MG/KG)/MIN","mass",1.6666666666666667e-8,[0,-1,0,0,0,0,0],"(mg/kg)/min",null,false,"M",null,1,false,false,0,"mg/(kg.min); mg per kg per min; milligrams per kilograms per minute","LOINC","RelMRat; MCntRat","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[true,"milligram per liter","mg/L","MG/L","mass",1,[-3,0,1,0,0,0,0],"mg/L",null,false,"M",null,1,false,false,0,"mg per l; milligrams per liter; litre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"milligram per square meter","mg/m2","MG/M2","mass",0.001,[-2,0,1,0,0,0,0],"mg/(m2)",null,false,"M",null,1,false,false,0,"mg/m^2; mg/sq. m; mg per m2; mg per m^2; mg per sq. milligrams; meter squared; metre","LOINC","ArMass","Clinical","",null,null,null,null,false],[true,"milligram per cubic meter","mg/m3","MG/M3","mass",0.001,[-3,0,1,0,0,0,0],"mg/(m3)",null,false,"M",null,1,false,false,0,"mg/m^3; mg/cu. m; mg per m3; milligrams per cubic meter; meter cubed; metre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"milligram per milligram","mg/mg","MG/MG","mass",1,[0,0,0,0,0,0,0],"mg/mg",null,false,"M",null,1,false,false,0,"mg per mg; milligrams; milligram/milligram","LOINC","MRto","Clinical","",null,null,null,null,false],[true,"milligram per minute","mg/min","MG/MIN","mass",0.000016666666666666667,[0,-1,1,0,0,0,0],"mg/min",null,false,"M",null,1,false,false,0,"mg per min; milligrams per minutes; milligram/minute","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"milligram per milliliter","mg/mL","MG/ML","mass",1000.0000000000001,[-3,0,1,0,0,0,0],"mg/mL",null,false,"M",null,1,false,false,0,"mg per mL; milligrams per milliliters; millilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"milligram per millimole","mg/mmol","MG/MMOL","mass",1.660540186674939e-24,[0,0,1,0,0,0,0],"mg/mmol",null,false,"M",null,1,false,false,-1,"mg per mmol; milligrams per millimole; ","LOINC","Ratio","Clinical","",null,null,null,null,false],[true,"milligram per week","mg/wk","MG/WK","mass",1.6534391534391535e-9,[0,-1,1,0,0,0,0],"mg/wk",null,false,"M",null,1,false,false,0,"mg/week; mg per wk; milligrams per weeks; milligram/week","LOINC","Mrat","Clinical","",null,null,null,null,false],[false,"milliliter","mL","ML","volume",0.000001,[3,0,0,0,0,0,0],"mL","iso1000",true,null,null,1,false,false,0,"milliliters; millilitres","LOINC","Vol","Clinical","","l",null,"1",1,false],[false,"milliliter per 10 hour","mL/(10.h)","ML/HR","volume",2.7777777777777777e-11,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,"ml/10hrs; ml/10 hrs; mL per 10hrs; 10 hrs; milliliters per 10 hours; millilitres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 12 hour","mL/(12.h)","ML/HR","volume",2.3148148148148147e-11,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,"ml/12hrs; ml/12 hrs; mL per 12hrs; 12 hrs; milliliters per 12 hours; millilitres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 2 hour","mL/(2.h)","ML/HR","volume",1.3888888888888888e-10,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,"ml/2hrs; ml/2 hrs; mL per 2hrs; 2 hrs; milliliters per 2 hours; millilitres ","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 24 hour","mL/(24.h)","ML/HR","volume",1.1574074074074074e-11,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,"ml/24hrs; ml/24 hrs; mL per 24hrs; 24 hrs; milliliters per 24 hours; millilitres; ml/dy; /day; ml per dy; days; fluid outputs; fluid inputs; flow rate","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 4 hour","mL/(4.h)","ML/HR","volume",6.944444444444444e-11,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,"ml/4hrs; ml/4 hrs; mL per 4hrs; 4 hrs; milliliters per 4 hours; millilitres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 5 hour","mL/(5.h)","ML/HR","volume",5.5555555555555553e-11,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,"ml/5hrs; ml/5 hrs; mL per 5hrs; 5 hrs; milliliters per 5 hours; millilitres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 6 hour","mL/(6.h)","ML/HR","volume",4.6296296296296294e-11,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,"ml/6hrs; ml/6 hrs; mL per 6hrs; 6 hrs; milliliters per 6 hours; millilitres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 72 hour","mL/(72.h)","ML/HR","volume",3.8580246913580245e-12,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,"ml/72hrs; ml/72 hrs; mL per 72hrs; 72 hrs; milliliters per 72 hours; millilitres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 8 hour","mL/(8.h)","ML/HR","volume",3.472222222222222e-11,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,"ml/8hrs; ml/8 hrs; mL per 8hrs; 8 hrs; milliliters per 8 hours; millilitres; shift","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 8 hour per kilogram","mL/(8.h)/kg","(ML/HR)/KG","volume",3.472222222222222e-14,[3,-1,-1,0,0,0,0],"(mL/h)/kg","iso1000",true,null,null,1,false,false,0,"mL/kg/(8.h); ml/8h/kg; ml/8 h/kg; ml/8hr/kg; ml/8 hr/kgr; mL per 8h per kg; 8 h; 8hr; 8 hr; milliliters per 8 hours per kilogram; millilitres; shift","LOINC","VRatCnt","Clinical","unit used to measure renal excretion volume rate per body mass","l",null,"1",1,false],[false,"milliliter per square inch (international)","mL/[sin_i]","ML/[SIN_I]","volume",0.0015500031000061998,[1,0,0,0,0,0,0],"mL","iso1000",true,null,null,1,false,false,0,"mL/sin; mL/in2; mL/in^2; mL per sin; in2; in^2; sq. in; milliliters per square inch; inch squared","LOINC","ArVol","Clinical","","l",null,"1",1,false],[false,"milliliter per centimeter of water","mL/cm[H2O]","ML/CM[H2O]","volume",1.0197162129779282e-11,[4,2,-1,0,0,0,0],"mL/(cm HO2)","iso1000",true,null,null,1,false,false,0,"milliliters per centimeter of water; millilitre per centimetre of water; millilitres per centimetre of water; mL/cmH2O; mL/cm H2O; mL per cmH2O; mL per cm H2O","LOINC","Compli","Clinical","unit used to measure dynamic lung compliance","l",null,"1",1,false],[false,"milliliter per day","mL/d","ML/D","volume",1.1574074074074074e-11,[3,-1,0,0,0,0,0],"mL/d","iso1000",true,null,null,1,false,false,0,"ml/day; ml per day; milliliters per day; 24 hours; 24hrs; millilitre;","LOINC","VRat","Clinical","usually used to measure fluid output or input; flow rate","l",null,"1",1,false],[false,"milliliter per deciliter","mL/dL","ML/DL","volume",0.009999999999999998,[0,0,0,0,0,0,0],"mL/dL","iso1000",true,null,null,1,false,false,0,"mL per dL; millilitres; decilitre; milliliters","LOINC","VFr; VFrDiff","Clinical","","l",null,"1",1,false],[false,"milliliter per hour","mL/h","ML/HR","volume",2.7777777777777777e-10,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,"mL/hr; mL per hr; milliliters per hour; millilitres; fluid intake; fluid output","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per kilogram","mL/kg","ML/KG","volume",9.999999999999999e-10,[3,0,-1,0,0,0,0],"mL/kg","iso1000",true,null,null,1,false,false,0,"mL per kg; milliliters per kilogram; millilitres","LOINC","VCnt","Clinical","","l",null,"1",1,false],[false,"milliliter per kilogram per 8 hour","mL/kg/(8.h)","(ML/KG)/HR","volume",3.472222222222222e-14,[3,-1,-1,0,0,0,0],"(mL/kg)/h","iso1000",true,null,null,1,false,false,0,"mL/(8.h.kg); mL/kg/8hrs; mL/kg/8 hrs; mL per kg per 8hrs; 8 hrs; milliliters per kilograms per 8 hours; millilitres; shift","LOINC","VCntRat; RelEngRat","Clinical","unit used to measure renal excretion volume rate per body mass","l",null,"1",1,false],[false,"milliliter per kilogram per day","mL/kg/d","(ML/KG)/D","volume",1.1574074074074072e-14,[3,-1,-1,0,0,0,0],"(mL/kg)/d","iso1000",true,null,null,1,false,false,0,"mL/(kg.d); mL/kg/dy; mL per kg per day; milliliters per kilograms per day; mg/kg/24hrs; 24 hrs; per 24 hours millilitres","LOINC","VCntRat; RelEngRat","Clinical","unit used to measure renal excretion volume rate per body mass","l",null,"1",1,false],[false,"milliliter per kilogram per hour","mL/kg/h","(ML/KG)/HR","volume",2.7777777777777774e-13,[3,-1,-1,0,0,0,0],"(mL/kg)/h","iso1000",true,null,null,1,false,false,0,"mL/(kg.h); mL/kg/hr; mL per kg per hr; milliliters per kilograms per hour; millilitres","LOINC","VCntRat; RelEngRat","Clinical","unit used to measure renal excretion volume rate per body mass","l",null,"1",1,false],[false,"milliliter per kilogram per minute","mL/kg/min","(ML/KG)/MIN","volume",1.6666666666666664e-11,[3,-1,-1,0,0,0,0],"(mL/kg)/min","iso1000",true,null,null,1,false,false,0,"mL/(kg.min); mL/kg/dy; mL per kg per day; milliliters per kilograms per day; millilitres","LOINC","RelEngRat","Clinical","used for tests that measure activity metabolic rate compared to standard resting metabolic rate ","l",null,"1",1,false],[false,"milliliter per square meter","mL/m2","ML/M2","volume",0.000001,[1,0,0,0,0,0,0],"mL/(m2)","iso1000",true,null,null,1,false,false,0,"mL/m^2; mL/sq. meter; mL per m2; m^2; sq. meter; milliliters per square meter; millilitres; meter squared","LOINC","ArVol","Clinical","used for tests that relate to heart work - e.g. ventricular stroke volume; atrial volume per body surface area","l",null,"1",1,false],[false,"milliliter per millibar","mL/mbar","ML/MBAR","volume",1e-11,[4,2,-1,0,0,0,0],"mL/mbar","iso1000",true,null,null,1,false,false,0,"mL per mbar; milliliters per millibar; millilitres","LOINC","","Clinical","unit used to measure dynamic lung compliance","l",null,"1",1,false],[false,"milliliter per minute","mL/min","ML/MIN","volume",1.6666666666666667e-8,[3,-1,0,0,0,0,0],"mL/min","iso1000",true,null,null,1,false,false,0,"mL per min; milliliters; millilitres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per minute per square meter","mL/min/m2","(ML/MIN)/M2","volume",1.6666666666666667e-8,[1,-1,0,0,0,0,0],"(mL/min)/(m2)","iso1000",true,null,null,1,false,false,0,"ml/min/m^2; ml/min/sq. meter; mL per min per m2; m^2; sq. meter; milliliters per minutes per square meter; millilitres; metre; meter squared","LOINC","ArVRat","Clinical","unit used to measure volume per body surface area; oxygen consumption index","l",null,"1",1,false],[false,"milliliter per millimeter","mL/mm","ML/MM","volume",0.001,[2,0,0,0,0,0,0],"mL/mm","iso1000",true,null,null,1,false,false,0,"mL per mm; milliliters per millimeter; millilitres; millimetre","LOINC","Lineic Volume","Clinical","","l",null,"1",1,false],[false,"milliliter per second","mL/s","ML/S","volume",0.000001,[3,-1,0,0,0,0,0],"mL/s","iso1000",true,null,null,1,false,false,0,"ml/sec; mL per sec; milliliters per second; millilitres","LOINC","Vel; VelRat; VRat","Clinical","","l",null,"1",1,false],[true,"millimeter","mm","MM","length",0.001,[1,0,0,0,0,0,0],"mm",null,false,"L",null,1,false,false,0,"millimeters; millimetres; height; length; diameter; thickness; axis; curvature; size","LOINC","Len","Clinical","",null,null,null,null,false],[true,"millimeter per hour","mm/h","MM/HR","length",2.7777777777777776e-7,[1,-1,0,0,0,0,0],"mm/h",null,false,"L",null,1,false,false,0,"mm/hr; mm per hr; millimeters per hour; millimetres","LOINC","Vel","Clinical","unit to measure sedimentation rate",null,null,null,null,false],[true,"millimeter per minute","mm/min","MM/MIN","length",0.000016666666666666667,[1,-1,0,0,0,0,0],"mm/min",null,false,"L",null,1,false,false,0,"mm per min; millimeters per minute; millimetres","LOINC","Vel","Clinical","",null,null,null,null,false],[false,"millimeter of water","mm[H2O]","MM[H2O]","pressure",9806.65,[-1,-2,1,0,0,0,0],"mm HO2","clinical",true,null,null,1,false,false,0,"mmH2O; mm H2O; millimeters of water; millimetres","LOINC","Pres","Clinical","","kPa","KPAL","980665e-5",9.80665,false],[false,"millimeter of mercury","mm[Hg]","MM[HG]","pressure",133322,[-1,-2,1,0,0,0,0],"mm Hg","clinical",true,null,null,1,false,false,0,"mmHg; mm Hg; millimeters of mercury; millimetres","LOINC","Pres; PPres; Ratio","Clinical","1 mm[Hg] = 1 torr; unit to measure blood pressure","kPa","KPAL","133.3220",133.322,false],[true,"square millimeter","mm2","MM2","length",0.000001,[2,0,0,0,0,0,0],"mm2",null,false,"L",null,1,false,false,0,"mm^2; sq. mm.; sq. millimeters; millimeters squared; millimetres","LOINC","Area","Clinical","",null,null,null,null,false],[false,"millimole","mmol","MMOL","amount of substance",602213670000000000000,[0,0,0,0,0,0,0],"mmol","si",true,null,null,1,false,false,1,"millimoles","LOINC","Sub","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per 12 hour","mmol/(12.h)","MMOL/HR","amount of substance",13940131250000000,[0,-1,0,0,0,0,0],"mmol/h","si",true,null,null,1,false,false,1,"mmol/12hrs; mmol/12 hrs; mmol per 12 hrs; 12hrs; millimoles per 12 hours","LOINC","SRat","Clinical","unit for tests related to urine","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per 2 hour","mmol/(2.h)","MMOL/HR","amount of substance",83640787500000000,[0,-1,0,0,0,0,0],"mmol/h","si",true,null,null,1,false,false,1,"mmol/2hrs; mmol/2 hrs; mmol per 2 hrs; 2hrs; millimoles per 2 hours","LOINC","SRat","Clinical","unit for tests related to urine","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per 24 hour","mmol/(24.h)","MMOL/HR","amount of substance",6970065625000000,[0,-1,0,0,0,0,0],"mmol/h","si",true,null,null,1,false,false,1,"mmol/24hrs; mmol/24 hrs; mmol per 24 hrs; 24hrs; millimoles per 24 hours","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per 5 hour","mmol/(5.h)","MMOL/HR","amount of substance",33456315000000000,[0,-1,0,0,0,0,0],"mmol/h","si",true,null,null,1,false,false,1,"mmol/5hrs; mmol/5 hrs; mmol per 5 hrs; 5hrs; millimoles per 5 hours","LOINC","SRat","Clinical","unit for tests related to doses","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per 6 hour","mmol/(6.h)","MMOL/HR","amount of substance",27880262500000000,[0,-1,0,0,0,0,0],"mmol/h","si",true,null,null,1,false,false,1,"mmol/6hrs; mmol/6 hrs; mmol per 6 hrs; 6hrs; millimoles per 6 hours","LOINC","SRat","Clinical","unit for tests related to urine","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per 8 hour","mmol/(8.h)","MMOL/HR","amount of substance",20910196875000000,[0,-1,0,0,0,0,0],"mmol/h","si",true,null,null,1,false,false,1,"mmol/8hrs; mmol/8 hrs; mmol per 8 hrs; 8hrs; millimoles per 8 hours; shift","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per day","mmol/d","MMOL/D","amount of substance",6970065625000000,[0,-1,0,0,0,0,0],"mmol/d","si",true,null,null,1,false,false,1,"mmol/24hrs; mmol/24 hrs; mmol per 24 hrs; 24hrs; millimoles per 24 hours","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per deciliter","mmol/dL","MMOL/DL","amount of substance",6.022136699999999e+24,[-3,0,0,0,0,0,0],"mmol/dL","si",true,null,null,1,false,false,1,"mmol per dL; millimoles; decilitre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per gram","mmol/g","MMOL/G","amount of substance",602213670000000000000,[0,0,-1,0,0,0,0],"mmol/g","si",true,null,null,1,false,false,1,"mmol per gram; millimoles","LOINC","SCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per hour","mmol/h","MMOL/HR","amount of substance",167281575000000000,[0,-1,0,0,0,0,0],"mmol/h","si",true,null,null,1,false,false,1,"mmol/hr; mmol per hr; millimoles per hour","LOINC","SRat","Clinical","unit for tests related to urine","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per kilogram","mmol/kg","MMOL/KG","amount of substance",602213670000000000,[0,0,-1,0,0,0,0],"mmol/kg","si",true,null,null,1,false,false,1,"mmol per kg; millimoles per kilogram","LOINC","SCnt","Clinical","unit for tests related to stool","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per kilogram per 8 hour","mmol/kg/(8.h)","(MMOL/KG)/HR","amount of substance",20910196875000,[0,-1,-1,0,0,0,0],"(mmol/kg)/h","si",true,null,null,1,false,false,1,"mmol/(8.h.kg); mmol/kg/8hrs; mmol/kg/8 hrs; mmol per kg per 8hrs; 8 hrs; millimoles per kilograms per 8 hours; shift","LOINC","CCnt","Clinical","unit used to measure molar dose rate per patient body mass","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per kilogram per day","mmol/kg/d","(MMOL/KG)/D","amount of substance",6970065625000,[0,-1,-1,0,0,0,0],"(mmol/kg)/d","si",true,null,null,1,false,false,1,"mmol/kg/dy; mmol/kg/day; mmol per kg per dy; millimoles per kilograms per day","LOINC","RelSRat","Clinical","unit used to measure molar dose rate per patient body mass","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per kilogram per hour","mmol/kg/h","(MMOL/KG)/HR","amount of substance",167281575000000,[0,-1,-1,0,0,0,0],"(mmol/kg)/h","si",true,null,null,1,false,false,1,"mmol/kg/hr; mmol per kg per hr; millimoles per kilograms per hour","LOINC","CCnt","Clinical","unit used to measure molar dose rate per patient body mass","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per kilogram per minute","mmol/kg/min","(MMOL/KG)/MIN","amount of substance",10036894500000000,[0,-1,-1,0,0,0,0],"(mmol/kg)/min","si",true,null,null,1,false,false,1,"mmol/(kg.min); mmol/kg/min; mmol per kg per min; millimoles per kilograms per minute","LOINC","CCnt","Clinical","unit used to measure molar dose rate per patient body mass; note that the unit for the enzyme unit U = umol/min. mmol/kg/min = kU/kg; ","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per liter","mmol/L","MMOL/L","amount of substance",6.0221367e+23,[-3,0,0,0,0,0,0],"mmol/L","si",true,null,null,1,false,false,1,"mmol per L; millimoles per liter; litre","LOINC","SCnc","Clinical","unit for tests related to doses","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per square meter","mmol/m2","MMOL/M2","amount of substance",602213670000000000000,[-2,0,0,0,0,0,0],"mmol/(m2)","si",true,null,null,1,false,false,1,"mmol/m^2; mmol/sq. meter; mmol per m2; m^2; sq. meter; millimoles; meter squared; metre","LOINC","ArSub","Clinical","unit used to measure molar dose per patient body surface area","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per minute","mmol/min","MMOL/MIN","amount of substance",10036894500000000000,[0,-1,0,0,0,0,0],"mmol/min","si",true,null,null,1,false,false,1,"mmol per min; millimoles per minute","LOINC","Srat; CAct","Clinical","unit for the enzyme unit U = umol/min. mmol/min = kU","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per millimole","mmol/mmol","MMOL/MMOL","amount of substance",1,[0,0,0,0,0,0,0],"mmol/mmol","si",true,null,null,1,false,false,0,"mmol per mmol; millimoles per millimole","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per mole","mmol/mol","MMOL/MOL","amount of substance",0.001,[0,0,0,0,0,0,0],"mmol/mol","si",true,null,null,1,false,false,0,"mmol per mol; millimoles per mole","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per second per liter","mmol/s/L","(MMOL/S)/L","amount of substance",6.0221367e+23,[-3,-1,0,0,0,0,0],"(mmol/s)/L","si",true,null,null,1,false,false,1,"mmol/sec/L; mmol per s per L; per sec; millimoles per seconds per liter; litre","LOINC","CCnc ","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"mole per kilogram","mol/kg","MOL/KG","amount of substance",602213670000000000000,[0,0,-1,0,0,0,0],"mol/kg","si",true,null,null,1,false,false,1,"mol per kg; moles; mols","LOINC","SCnt","Clinical","unit for tests related to stool","10*23","10*23","6.0221367",6.0221367,false],[false,"mole per kilogram per second","mol/kg/s","(MOL/KG)/S","amount of substance",602213670000000000000,[0,-1,-1,0,0,0,0],"(mol/kg)/s","si",true,null,null,1,false,false,1,"mol/kg/sec; mol per kg per sec; moles per kilograms per second; mols","LOINC","CCnt","Clinical","unit of catalytic activity (mol/s) per mass (kg)","10*23","10*23","6.0221367",6.0221367,false],[false,"mole per liter","mol/L","MOL/L","amount of substance",6.0221366999999994e+26,[-3,0,0,0,0,0,0],"mol/L","si",true,null,null,1,false,false,1,"mol per L; moles per liter; litre; moles; mols","LOINC","SCnc","Clinical","unit often used in tests measuring oxygen content","10*23","10*23","6.0221367",6.0221367,false],[false,"mole per cubic meter","mol/m3","MOL/M3","amount of substance",6.0221367e+23,[-3,0,0,0,0,0,0],"mol/(m3)","si",true,null,null,1,false,false,1,"mol/m^3; mol/cu. m; mol per m3; m^3; cu. meter; mols; moles; meters cubed; metre; mole per kiloliter; kilolitre; mol/kL","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"mole per milliliter","mol/mL","MOL/ML","amount of substance",6.0221367e+29,[-3,0,0,0,0,0,0],"mol/mL","si",true,null,null,1,false,false,1,"mol per mL; moles; millilitre; mols","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"mole per mole","mol/mol","MOL/MOL","amount of substance",1,[0,0,0,0,0,0,0],"mol/mol","si",true,null,null,1,false,false,0,"mol per mol; moles per mol; mols","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"mole per second","mol/s","MOL/S","amount of substance",6.0221367e+23,[0,-1,0,0,0,0,0],"mol/s","si",true,null,null,1,false,false,1,"mol per sec; moles per second; mols","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"milliosmole","mosm","MOSM","amount of substance (dissolved particles)",602213670000000000000,[0,0,0,0,0,0,0],"mosm","chemical",true,null,null,1,false,false,1,"milliosmoles","LOINC","Osmol","Clinical","equal to 1/1000 of an osmole","mol","MOL","1",1,false],[false,"milliosmole per kilogram","mosm/kg","MOSM/KG","amount of substance (dissolved particles)",602213670000000000,[0,0,-1,0,0,0,0],"mosm/kg","chemical",true,null,null,1,false,false,1,"mosm per kg; milliosmoles per kilogram","LOINC","Osmol","Clinical","","mol","MOL","1",1,false],[false,"milliosmole per liter","mosm/L","MOSM/L","amount of substance (dissolved particles)",6.0221367e+23,[-3,0,0,0,0,0,0],"mosm/L","chemical",true,null,null,1,false,false,1,"mosm per liter; litre; milliosmoles","LOINC","Osmol","Clinical","","mol","MOL","1",1,false],[false,"millipascal","mPa","MPAL","pressure",1,[-1,-2,1,0,0,0,0],"mPa","si",true,null,null,1,false,false,0,"millipascals","LOINC","Pres","Clinical","unit of pressure","N/m2","N/M2","1",1,false],[false,"millipascal second","mPa.s","MPAL.S","pressure",1,[-1,-1,1,0,0,0,0],"mPa.s","si",true,null,null,1,false,false,0,"mPa*s; millipoise; mP; dynamic viscosity","LOINC","Visc","Clinical","base units for millipoise, a measurement of dynamic viscosity","N/m2","N/M2","1",1,false],[true,"megasecond","Ms","MAS","time",1000000,[0,1,0,0,0,0,0],"Ms",null,false,"T",null,1,false,false,0,"megaseconds","LOINC","Time","Clinical","",null,null,null,null,false],[true,"millisecond","ms","MS","time",0.001,[0,1,0,0,0,0,0],"ms",null,false,"T",null,1,false,false,0,"milliseconds; duration","LOINC","Time","Clinical","",null,null,null,null,false],[false,"milli enzyme unit per gram","mU/g","MU/G","catalytic activity",10036894500000,[0,-1,-1,0,0,0,0],"mU/g","chemical",true,null,null,1,false,false,1,"mU per gm; milli enzyme units per gram; enzyme activity; enzymatic activity per mass","LOINC","CCnt","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 mU = 1 nmol/min","umol/min","UMOL/MIN","1",1,false],[false,"milli enzyme unit per liter","mU/L","MU/L","catalytic activity",10036894500000000,[-3,-1,0,0,0,0,0],"mU/L","chemical",true,null,null,1,false,false,1,"mU per liter; litre; milli enzyme units enzymatic activity per volume; enzyme activity","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 mU = 1 nmol/min","umol/min","UMOL/MIN","1",1,false],[false,"milli enzyme unit per milligram","mU/mg","MU/MG","catalytic activity",10036894500000000,[0,-1,-1,0,0,0,0],"mU/mg","chemical",true,null,null,1,false,false,1,"mU per mg; milli enzyme units per milligram","LOINC","CCnt","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 mU = 1 nmol/min","umol/min","UMOL/MIN","1",1,false],[false,"milli enzyme unit per milliliter","mU/mL","MU/ML","catalytic activity",10036894500000000000,[-3,-1,0,0,0,0,0],"mU/mL","chemical",true,null,null,1,false,false,1,"mU per mL; milli enzyme units per milliliter; millilitre; enzymatic activity per volume; enzyme activity","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 mU = 1 nmol/min","umol/min","UMOL/MIN","1",1,false],[false,"milli enzyme unit per milliliter per minute","mU/mL/min","(MU/ML)/MIN","catalytic activity",167281575000000000,[-3,-2,0,0,0,0,0],"(mU/mL)/min","chemical",true,null,null,1,false,false,1,"mU per mL per min; mU per milliliters per minute; millilitres; milli enzyme units; enzymatic activity; enzyme activity","LOINC","CCncRat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 mU = 1 nmol/min","umol/min","UMOL/MIN","1",1,false],[false,"millivolt","mV","MV","electric potential",1,[2,-2,1,0,0,-1,0],"mV","si",true,null,null,1,false,false,0,"millivolts","LOINC","Elpot","Clinical","unit of electric potential (voltage)","J/C","J/C","1",1,false],[false,"Newton centimeter","N.cm","N.CM","force",10,[2,-2,1,0,0,0,0],"N.cm","si",true,null,null,1,false,false,0,"N*cm; Ncm; N cm; Newton*centimeters; Newton* centimetres; torque; work","LOINC","","Clinical","as a measurement of work, N.cm = 1/100 Joules;\nnote that N.m is the standard unit of measurement for torque (although dimensionally equivalent to Joule), and N.cm can also be thought of as a torqe unit","kg.m/s2","KG.M/S2","1",1,false],[false,"Newton second","N.s","N.S","force",1000,[1,-1,1,0,0,0,0],"N.s","si",true,null,null,1,false,false,0,"Newton*seconds; N*s; N s; Ns; impulse; imp","LOINC","","Clinical","standard unit of impulse","kg.m/s2","KG.M/S2","1",1,false],[true,"nanogram","ng","NG","mass",1e-9,[0,0,1,0,0,0,0],"ng",null,false,"M",null,1,false,false,0,"nanograms","LOINC","Mass","Clinical","",null,null,null,null,false],[true,"nanogram per 24 hour","ng/(24.h)","NG/HR","mass",1.1574074074074075e-14,[0,-1,1,0,0,0,0],"ng/h",null,false,"M",null,1,false,false,0,"ng/24hrs; ng/24 hrs; nanograms per 24 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"nanogram per 8 hour","ng/(8.h)","NG/HR","mass",3.4722222222222224e-14,[0,-1,1,0,0,0,0],"ng/h",null,false,"M",null,1,false,false,0,"ng/8hrs; ng/8 hrs; nanograms per 8 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"nanogram per million","ng/10*6","NG/(10*6)","mass",1e-15,[0,0,1,0,0,0,0],"ng/(106)",null,false,"M",null,1,false,false,0,"ng/10^6; ng per 10*6; 10^6; nanograms","LOINC","MNum","Clinical","",null,null,null,null,false],[true,"nanogram per day","ng/d","NG/D","mass",1.1574074074074075e-14,[0,-1,1,0,0,0,0],"ng/d",null,false,"M",null,1,false,false,0,"ng/dy; ng per day; nanograms ","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"nanogram per deciliter","ng/dL","NG/DL","mass",0.00001,[-3,0,1,0,0,0,0],"ng/dL",null,false,"M",null,1,false,false,0,"ng per dL; nanograms per deciliter; decilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"nanogram per gram","ng/g","NG/G","mass",1e-9,[0,0,0,0,0,0,0],"ng/g",null,false,"M",null,1,false,false,0,"ng/gm; ng per gm; nanograms per gram","LOINC","MCnt","Clinical","",null,null,null,null,false],[true,"nanogram per hour","ng/h","NG/HR","mass",2.777777777777778e-13,[0,-1,1,0,0,0,0],"ng/h",null,false,"M",null,1,false,false,0,"ng/hr; ng per hr; nanograms per hour","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"nanogram per kilogram","ng/kg","NG/KG","mass",1e-12,[0,0,0,0,0,0,0],"ng/kg",null,false,"M",null,1,false,false,0,"ng per kg; nanograms per kilogram","LOINC","MCnt","Clinical","",null,null,null,null,false],[true,"nanogram per kilogram per 8 hour","ng/kg/(8.h)","(NG/KG)/HR","mass",3.472222222222222e-17,[0,-1,0,0,0,0,0],"(ng/kg)/h",null,false,"M",null,1,false,false,0,"ng/(8.h.kg); ng/kg/8hrs; ng/kg/8 hrs; ng per kg per 8hrs; 8 hrs; nanograms per kilograms per 8 hours; shift","LOINC","MRtoRat ","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[true,"nanogram per kilogram per hour","ng/kg/h","(NG/KG)/HR","mass",2.7777777777777775e-16,[0,-1,0,0,0,0,0],"(ng/kg)/h",null,false,"M",null,1,false,false,0,"ng/(kg.h); ng/kg/hr; ng per kg per hr; nanograms per kilograms per hour","LOINC","MRtoRat ","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[true,"nanogram per kilogram per minute","ng/kg/min","(NG/KG)/MIN","mass",1.6666666666666667e-14,[0,-1,0,0,0,0,0],"(ng/kg)/min",null,false,"M",null,1,false,false,0,"ng/(kg.min); ng per kg per min; nanograms per kilograms per minute","LOINC","MRtoRat ","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[true,"nanogram per liter","ng/L","NG/L","mass",0.000001,[-3,0,1,0,0,0,0],"ng/L",null,false,"M",null,1,false,false,0,"ng per L; nanograms per liter; litre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"nanogram per square meter","ng/m2","NG/M2","mass",1e-9,[-2,0,1,0,0,0,0],"ng/(m2)",null,false,"M",null,1,false,false,0,"ng/m^2; ng/sq. m; ng per m2; m^2; sq. meter; nanograms; meter squared; metre","LOINC","ArMass","Clinical","unit used to measure mass dose per patient body surface area",null,null,null,null,false],[true,"nanogram per milligram","ng/mg","NG/MG","mass",0.000001,[0,0,0,0,0,0,0],"ng/mg",null,false,"M",null,1,false,false,0,"ng per mg; nanograms","LOINC","MCnt","Clinical","",null,null,null,null,false],[true,"nanogram per milligram per hour","ng/mg/h","(NG/MG)/HR","mass",2.7777777777777777e-10,[0,-1,0,0,0,0,0],"(ng/mg)/h",null,false,"M",null,1,false,false,0,"ng/mg/hr; ng per mg per hr; nanograms per milligrams per hour","LOINC","MRtoRat ","Clinical","",null,null,null,null,false],[true,"nanogram per minute","ng/min","NG/MIN","mass",1.6666666666666667e-11,[0,-1,1,0,0,0,0],"ng/min",null,false,"M",null,1,false,false,0,"ng per min; nanograms","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"nanogram per millliiter","ng/mL","NG/ML","mass",0.001,[-3,0,1,0,0,0,0],"ng/mL",null,false,"M",null,1,false,false,0,"ng per mL; nanograms; millilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"nanogram per milliliter per hour","ng/mL/h","(NG/ML)/HR","mass",2.7777777777777776e-7,[-3,-1,1,0,0,0,0],"(ng/mL)/h",null,false,"M",null,1,false,false,0,"ng/mL/hr; ng per mL per mL; nanograms per milliliter per hour; nanogram per millilitre per hour; nanograms per millilitre per hour; enzymatic activity per volume; enzyme activity per milliliters","LOINC","CCnc","Clinical","tests that measure enzymatic activity",null,null,null,null,false],[true,"nanogram per second","ng/s","NG/S","mass",1e-9,[0,-1,1,0,0,0,0],"ng/s",null,false,"M",null,1,false,false,0,"ng/sec; ng per sec; nanograms per second","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"nanogram per enzyme unit","ng/U","NG/U","mass",9.963241120049634e-26,[0,1,1,0,0,0,0],"ng/U",null,false,"M",null,1,false,false,-1,"ng per U; nanograms per enzyme unit","LOINC","CMass","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)",null,null,null,null,false],[false,"nanokatal","nkat","NKAT","catalytic activity",602213670000000,[0,-1,0,0,0,0,0],"nkat","chemical",true,null,null,1,false,false,1,"nanokatals","LOINC","CAct","Clinical","kat is a unit of catalytic activity with base units = mol/s. Rarely used because its units are too large to practically express catalytic activity. See enzyme unit [U] which is the standard unit for catalytic activity.","mol/s","MOL/S","1",1,false],[false,"nanoliter","nL","NL","volume",1.0000000000000002e-12,[3,0,0,0,0,0,0],"nL","iso1000",true,null,null,1,false,false,0,"nanoliters; nanolitres","LOINC","Vol","Clinical","","l",null,"1",1,false],[true,"nanometer","nm","NM","length",1e-9,[1,0,0,0,0,0,0],"nm",null,false,"L",null,1,false,false,0,"nanometers; nanometres","LOINC","Len","Clinical","",null,null,null,null,false],[true,"nanometer per second per liter","nm/s/L","(NM/S)/L","length",0.000001,[-2,-1,0,0,0,0,0],"(nm/s)/L",null,false,"L",null,1,false,false,0,"nm/sec/liter; nm/sec/litre; nm per s per l; nm per sec per l; nanometers per second per liter; nanometre per second per litre; nanometres per second per litre","LOINC","VelCnc","Clinical","",null,null,null,null,false],[false,"nanomole","nmol","NMOL","amount of substance",602213670000000,[0,0,0,0,0,0,0],"nmol","si",true,null,null,1,false,false,1,"nanomoles","LOINC","Sub","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per 24 hour","nmol/(24.h)","NMOL/HR","amount of substance",6970065625,[0,-1,0,0,0,0,0],"nmol/h","si",true,null,null,1,false,false,1,"nmol/24hr; nmol/24 hr; nanomoles per 24 hours; nmol/day; nanomoles per day; nmol per day; nanomole/day; nanomol/day","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per day","nmol/d","NMOL/D","amount of substance",6970065625,[0,-1,0,0,0,0,0],"nmol/d","si",true,null,null,1,false,false,1,"nmol/day; nanomoles per day; nmol per day; nanomole/day; nanomol/day; nmol/24hr; nmol/24 hr; nanomoles per 24 hours; ","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per deciliter","nmol/dL","NMOL/DL","amount of substance",6022136700000000000,[-3,0,0,0,0,0,0],"nmol/dL","si",true,null,null,1,false,false,1,"nmol per dL; nanomoles per deciliter; nanomole per decilitre; nanomoles per decilitre; nanomole/deciliter; nanomole/decilitre; nanomol/deciliter; nanomol/decilitre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per gram","nmol/g","NMOL/G","amount of substance",602213670000000,[0,0,-1,0,0,0,0],"nmol/g","si",true,null,null,1,false,false,1,"nmol per gram; nanomoles per gram; nanomole/gram","LOINC","SCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per hour per liter","nmol/h/L","(NMOL/HR)/L","amount of substance",167281575000000,[-3,-1,0,0,0,0,0],"(nmol/h)/L","si",true,null,null,1,false,false,1,"nmol/hrs/L; nmol per hrs per L; nanomoles per hours per liter; litre; enzymatic activity per volume; enzyme activities","LOINC","CCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per liter","nmol/L","NMOL/L","amount of substance",602213670000000000,[-3,0,0,0,0,0,0],"nmol/L","si",true,null,null,1,false,false,1,"nmol per L; nanomoles per liter; litre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per milligram","nmol/mg","NMOL/MG","amount of substance",602213670000000000,[0,0,-1,0,0,0,0],"nmol/mg","si",true,null,null,1,false,false,1,"nmol per mg; nanomoles per milligram","LOINC","SCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per milligram per hour","nmol/mg/h","(NMOL/MG)/HR","amount of substance",167281575000000,[0,-1,-1,0,0,0,0],"(nmol/mg)/h","si",true,null,null,1,false,false,1,"nmol/mg/hr; nmol per mg per hr; nanomoles per milligrams per hour","LOINC","SCntRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per milligram of protein","nmol/mg{prot}","NMOL/MG","amount of substance",602213670000000000,[0,0,-1,0,0,0,0],"nmol/mg","si",true,null,null,1,false,false,1,"nanomoles; nmol/mg prot; nmol per mg prot","LOINC","Ratio; CCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per minute","nmol/min","NMOL/MIN","amount of substance",10036894500000,[0,-1,0,0,0,0,0],"nmol/min","si",true,null,null,1,false,false,1,"nmol per min; nanomoles per minute; milli enzyme units; enzyme activity per volume; enzymatic activity","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min. nmol/min = mU (milli enzyme unit)","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per minute per milliliter","nmol/min/mL","(NMOL/MIN)/ML","amount of substance",10036894500000000000,[-3,-1,0,0,0,0,0],"(nmol/min)/mL","si",true,null,null,1,false,false,1,"nmol per min per mL; nanomoles per minutes per milliliter; millilitre; milli enzyme units per volume; enzyme activity; enzymatic activity","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min. nmol/mL/min = mU/mL","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per milliliter","nmol/mL","NMOL/ML","amount of substance",602213670000000000000,[-3,0,0,0,0,0,0],"nmol/mL","si",true,null,null,1,false,false,1,"nmol per mL; nanomoles per milliliter; millilitre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per milliliter per hour","nmol/mL/h","(NMOL/ML)/HR","amount of substance",167281575000000000,[-3,-1,0,0,0,0,0],"(nmol/mL)/h","si",true,null,null,1,false,false,1,"nmol/mL/hr; nmol per mL per hr; nanomoles per milliliters per hour; millilitres; milli enzyme units per volume; enzyme activity; enzymatic activity","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min.","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per milliliter per minute","nmol/mL/min","(NMOL/ML)/MIN","amount of substance",10036894500000000000,[-3,-1,0,0,0,0,0],"(nmol/mL)/min","si",true,null,null,1,false,false,1,"nmol per mL per min; nanomoles per milliliters per min; millilitres; milli enzyme units per volume; enzyme activity; enzymatic activity","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min. nmol/mL/min = mU/mL","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per millimole","nmol/mmol","NMOL/MMOL","amount of substance",0.000001,[0,0,0,0,0,0,0],"nmol/mmol","si",true,null,null,1,false,false,0,"nmol per mmol; nanomoles per millimole","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per millimole of creatinine","nmol/mmol{creat}","NMOL/MMOL","amount of substance",0.000001,[0,0,0,0,0,0,0],"nmol/mmol","si",true,null,null,1,false,false,0,"nanomoles","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per mole","nmol/mol","NMOL/MOL","amount of substance",1e-9,[0,0,0,0,0,0,0],"nmol/mol","si",true,null,null,1,false,false,0,"nmol per mole; nanomoles","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per nanomole","nmol/nmol","NMOL/NMOL","amount of substance",1,[0,0,0,0,0,0,0],"nmol/nmol","si",true,null,null,1,false,false,0,"nmol per nmol; nanomoles","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per second","nmol/s","NMOL/S","amount of substance",602213670000000,[0,-1,0,0,0,0,0],"nmol/s","si",true,null,null,1,false,false,1,"nmol/sec; nmol per sec; nanomoles per sercond; milli enzyme units; enzyme activity; enzymatic activity","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min.","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per second per liter","nmol/s/L","(NMOL/S)/L","amount of substance",602213670000000000,[-3,-1,0,0,0,0,0],"(nmol/s)/L","si",true,null,null,1,false,false,1,"nmol/sec/L; nmol per s per L; nmol per sec per L; nanomoles per seconds per liter; litre; milli enzyme units per volume; enzyme activity; enzymatic activity","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min.","10*23","10*23","6.0221367",6.0221367,false],[true,"nanosecond","ns","NS","time",1e-9,[0,1,0,0,0,0,0],"ns",null,false,"T",null,1,false,false,0,"nanoseconds","LOINC","Time","Clinical","",null,null,null,null,false],[false,"nanoenzyme unit per milliliter","nU/mL","NU/ML","catalytic activity",10036894500000,[-3,-1,0,0,0,0,0],"nU/mL","chemical",true,null,null,1,false,false,1,"nU per mL; nanoenzyme units per milliliter; millilitre; enzymatic activity per volume; enzyme activity","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 fU = pmol/min","umol/min","UMOL/MIN","1",1,false],[false,"Ohm meter","Ohm.m","OHM.M","electric resistance",1000,[3,-1,1,0,0,-2,0],"Ω.m","si",true,null,null,1,false,false,0,"electric resistivity; meters; metres","LOINC","","Clinical","unit of electric resistivity","V/A","V/A","1",1,false],[false,"osmole per kilogram","osm/kg","OSM/KG","amount of substance (dissolved particles)",602213670000000000000,[0,0,-1,0,0,0,0],"osm/kg","chemical",true,null,null,1,false,false,1,"osm per kg; osmoles per kilogram; osmols","LOINC","Osmol","Clinical","","mol","MOL","1",1,false],[false,"osmole per liter","osm/L","OSM/L","amount of substance (dissolved particles)",6.0221366999999994e+26,[-3,0,0,0,0,0,0],"osm/L","chemical",true,null,null,1,false,false,1,"osm per L; osmoles per liter; litre; osmols","LOINC","Osmol","Clinical","","mol","MOL","1",1,false],[false,"picoampere","pA","PA","electric current",1e-12,[0,-1,0,0,0,1,0],"pA","si",true,null,null,1,false,false,0,"picoamperes","LOINC","","Clinical","equal to 10^-12 amperes","C/s","C/S","1",1,false],[true,"picogram","pg","PG","mass",1e-12,[0,0,1,0,0,0,0],"pg",null,false,"M",null,1,false,false,0,"picograms","LOINC","Mass; EntMass","Clinical","",null,null,null,null,false],[true,"picogram per deciliter","pg/dL","PG/DL","mass",9.999999999999999e-9,[-3,0,1,0,0,0,0],"pg/dL",null,false,"M",null,1,false,false,0,"pg per dL; picograms; decilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"picogram per liter","pg/L","PG/L","mass",1e-9,[-3,0,1,0,0,0,0],"pg/L",null,false,"M",null,1,false,false,0,"pg per L; picograms; litre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"picogram per milligram","pg/mg","PG/MG","mass",1e-9,[0,0,0,0,0,0,0],"pg/mg",null,false,"M",null,1,false,false,0,"pg per mg; picograms","LOINC","MCnt","Clinical","",null,null,null,null,false],[true,"picogram per milliliter","pg/mL","PG/ML","mass",0.000001,[-3,0,1,0,0,0,0],"pg/mL",null,false,"M",null,1,false,false,0,"pg per mL; picograms per milliliter; millilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"picogram per millimeter","pg/mm","PG/MM","mass",1e-9,[-1,0,1,0,0,0,0],"pg/mm",null,false,"M",null,1,false,false,0,"pg per mm; picogram/millimeter; picogram/millimetre; picograms per millimeter; millimetre","LOINC","Lineic Mass","Clinical","",null,null,null,null,false],[false,"picokatal","pkat","PKAT","catalytic activity",602213670000,[0,-1,0,0,0,0,0],"pkat","chemical",true,null,null,1,false,false,1,"pkats; picokatals","LOINC","CAct","Clinical","kat is a unit of catalytic activity with base units = mol/s. Rarely used because its units are too large to practically express catalytic activity. See enzyme unit [U] which is the standard unit for catalytic activity.","mol/s","MOL/S","1",1,false],[false,"picoliter","pL","PL","volume",1e-15,[3,0,0,0,0,0,0],"pL","iso1000",true,null,null,1,false,false,0,"picoliters; picolitres","LOINC","Vol","Clinical","","l",null,"1",1,false],[true,"picometer","pm","PM","length",1e-12,[1,0,0,0,0,0,0],"pm",null,false,"L",null,1,false,false,0,"picometers; picometres","LOINC","Len","Clinical","",null,null,null,null,false],[false,"picomole","pmol","PMOL","amount of substance",602213670000,[0,0,0,0,0,0,0],"pmol","si",true,null,null,1,false,false,1,"picomoles; pmols","LOINC","Sub","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per 24 hour","pmol/(24.h)","PMOL/HR","amount of substance",6970065.625,[0,-1,0,0,0,0,0],"pmol/h","si",true,null,null,1,false,false,1,"pmol/24hrs; pmol/24 hrs; pmol per 24 hrs; 24hrs; days; dy; picomoles per 24 hours","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per day","pmol/d","PMOL/D","amount of substance",6970065.625,[0,-1,0,0,0,0,0],"pmol/d","si",true,null,null,1,false,false,1,"pmol/dy; pmol per day; 24 hours; 24hrs; 24 hrs; picomoles","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per deciliter","pmol/dL","PMOL/DL","amount of substance",6022136700000000,[-3,0,0,0,0,0,0],"pmol/dL","si",true,null,null,1,false,false,1,"pmol per dL; picomoles per deciliter; decilitre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per gram","pmol/g","PMOL/G","amount of substance",602213670000,[0,0,-1,0,0,0,0],"pmol/g","si",true,null,null,1,false,false,1,"pmol per gm; picomoles per gram; picomole/gram","LOINC","SCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per hour per milliliter ","pmol/h/mL","(PMOL/HR)/ML","amount of substance",167281575000000,[-3,-1,0,0,0,0,0],"(pmol/h)/mL","si",true,null,null,1,false,false,1,"pmol/hrs/mL; pmol per hrs per mL; picomoles per hour per milliliter; millilitre; micro enzyme units per volume; enzymatic activity; enzyme activity","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min. ","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per liter","pmol/L","PMOL/L","amount of substance",602213670000000,[-3,0,0,0,0,0,0],"pmol/L","si",true,null,null,1,false,false,1,"picomole/liter; pmol per L; picomoles; litre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per minute","pmol/min","PMOL/MIN","amount of substance",10036894500,[0,-1,0,0,0,0,0],"pmol/min","si",true,null,null,1,false,false,1,"picomole/minute; pmol per min; picomoles per minute; micro enzyme units; enzymatic activity; enzyme activity","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min. pmol/min = uU (micro enzyme unit)","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per milliliter","pmol/mL","PMOL/ML","amount of substance",602213670000000000,[-3,0,0,0,0,0,0],"pmol/mL","si",true,null,null,1,false,false,1,"picomole/milliliter; picomole/millilitre; pmol per mL; picomoles; millilitre; picomols; pmols","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per micromole","pmol/umol","PMOL/UMOL","amount of substance",0.000001,[0,0,0,0,0,0,0],"pmol/μmol","si",true,null,null,1,false,false,0,"pmol/mcgmol; picomole/micromole; pmol per umol; pmol per mcgmol; picomoles ","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[true,"picosecond","ps","PS","time",1e-12,[0,1,0,0,0,0,0],"ps",null,false,"T",null,1,false,false,0,"picoseconds; psec","LOINC","Time","Clinical","",null,null,null,null,false],[false,"picotesla","pT","PT","magnetic flux density",1e-9,[0,-1,1,0,0,-1,0],"pT","si",true,null,null,1,false,false,0,"picoteslas","LOINC","","Clinical","SI unit of magnetic field strength for magnetic field B","Wb/m2","WB/M2","1",1,false],[false,"enzyme unit per 12 hour","U/(12.h)","U/HR","catalytic activity",232335520833.33334,[0,-2,0,0,0,0,0],"U/h","chemical",true,null,null,1,false,false,1,"U/12hrs; U/ 12hrs; U per 12 hrs; 12hrs; enzyme units per 12 hours; enzyme activity; enzymatic activity per time; umol per min per 12 hours; micromoles per minute per 12 hours; umol/min/12hr","LOINC","CRat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per 2 hour","U/(2.h)","U/HR","catalytic activity",1394013125000,[0,-2,0,0,0,0,0],"U/h","chemical",true,null,null,1,false,false,1,"U/2hrs; U/ 2hrs; U per 2 hrs; 2hrs; enzyme units per 2 hours; enzyme activity; enzymatic activity per time; umol per minute per 2 hours; micromoles per minute; umol/min/2hr; umol per min per 2hr","LOINC","CRat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per 24 hour","U/(24.h)","U/HR","catalytic activity",116167760416.66667,[0,-2,0,0,0,0,0],"U/h","chemical",true,null,null,1,false,false,1,"U/24hrs; U/ 24hrs; U per 24 hrs; 24hrs; enzyme units per 24 hours; enzyme activity; enzymatic activity per time; micromoles per minute per 24 hours; umol/min/24hr; umol per min per 24hr","LOINC","CRat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per 10","U/10","U","catalytic activity",1003689450000000,[0,-1,0,0,0,0,0],"U","chemical",true,null,null,1,false,false,1,"enzyme unit/10; U per 10; enzyme units per 10; enzymatic activity; enzyme activity; micromoles per minute; umol/min/10","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per 10 billion","U/10*10","U/(10*10)","catalytic activity",1003689.45,[0,-1,0,0,0,0,0],"U/(1010)","chemical",true,null,null,1,false,false,1,"U per 10*10; enzyme units per 10*10; U per 10 billion; enzyme units; enzymatic activity; micromoles per minute per 10 billion; umol/min/10*10","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per trillion","U/10*12","U/(10*12)","catalytic activity",10036.8945,[0,-1,0,0,0,0,0],"U/(1012)","chemical",true,null,null,1,false,false,1,"enzyme unit/10*12; U per 10*12; enzyme units per 10*12; enzyme units per trillion; enzymatic activity; micromoles per minute per trillion; umol/min/10*12; umol per min per 10*12","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per million","U/10*6","U/(10*6)","catalytic activity",10036894500,[0,-1,0,0,0,0,0],"U/(106)","chemical",true,null,null,1,false,false,1,"enzyme unit/10*6; U per 10*6; enzyme units per 10*6; enzyme units; enzymatic activity per volume; micromoles per minute per million; umol/min/10*6; umol per min per 10*6","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per billion","U/10*9","U/(10*9)","catalytic activity",10036894.5,[0,-1,0,0,0,0,0],"U/(109)","chemical",true,null,null,1,false,false,1,"enzyme unit/10*9; U per 10*9; enzyme units per 10*9; enzymatic activity per volume; micromoles per minute per billion; umol/min/10*9; umol per min per 10*9","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per day","U/d","U/D","catalytic activity",116167760416.66667,[0,-2,0,0,0,0,0],"U/d","chemical",true,null,null,1,false,false,1,"U/dy; enzyme units per day; enzyme units; enzyme activity; enzymatic activity per time; micromoles per minute per day; umol/min/day; umol per min per day","LOINC","CRat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per deciliter","U/dL","U/DL","catalytic activity",100368945000000000000,[-3,-1,0,0,0,0,0],"U/dL","chemical",true,null,null,1,false,false,1,"U per dL; enzyme units per deciliter; decilitre; micromoles per minute per deciliter; umol/min/dL; umol per min per dL","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per gram","U/g","U/G","catalytic activity",10036894500000000,[0,-1,-1,0,0,0,0],"U/g","chemical",true,null,null,1,false,false,1,"U/gm; U per gm; enzyme units per gram; micromoles per minute per gram; umol/min/g; umol per min per g","LOINC","CCnt","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per hour","U/h","U/HR","catalytic activity",2788026250000,[0,-2,0,0,0,0,0],"U/h","chemical",true,null,null,1,false,false,1,"U/hr; U per hr; enzyme units per hour; micromoles per minute per hour; umol/min/hr; umol per min per hr","LOINC","CRat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per liter","U/L","U/L","catalytic activity",10036894500000000000,[-3,-1,0,0,0,0,0],"U/L","chemical",true,null,null,1,false,false,1,"enzyme unit/liter; enzyme unit/litre; U per L; enzyme units per liter; enzyme unit per litre; micromoles per minute per liter; umol/min/L; umol per min per L","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per minute","U/min","U/MIN","catalytic activity",167281575000000,[0,-2,0,0,0,0,0],"U/min","chemical",true,null,null,1,false,false,1,"enzyme unit/minute; U per min; enzyme units; umol/min/min; micromoles per minute per minute; micromoles per min per min; umol","LOINC","CRat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per milliliter","U/mL","U/ML","catalytic activity",1.00368945e+22,[-3,-1,0,0,0,0,0],"U/mL","chemical",true,null,null,1,false,false,1,"U per mL; enzyme units per milliliter; millilitre; micromoles per minute per milliliter; umol/min/mL; umol per min per mL","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per second","U/s","U/S","catalytic activity",10036894500000000,[0,-2,0,0,0,0,0],"U/s","chemical",true,null,null,1,false,false,1,"U/sec; U per second; enzyme units per second; micromoles per minute per second; umol/min/sec; umol per min per sec","LOINC","CRat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"micro international unit","u[IU]","U[IU]","arbitrary",0.000001,[0,0,0,0,0,0,0],"μi.U.","chemical",true,null,null,1,false,true,0,"uIU; u IU; microinternational units","LOINC","Arb","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"micro international unit per liter","u[IU]/L","U[IU]/L","arbitrary",0.001,[-3,0,0,0,0,0,0],"(μi.U.)/L","chemical",true,null,null,1,false,true,0,"uIU/L; u IU/L; uIU per L; microinternational units per liter; litre; ","LOINC","ACnc","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"micro international unit per milliliter","u[IU]/mL","U[IU]/ML","arbitrary",1,[-3,0,0,0,0,0,0],"(μi.U.)/mL","chemical",true,null,null,1,false,true,0,"uIU/mL; u IU/mL; uIU per mL; microinternational units per milliliter; millilitre","LOINC","ACnc","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"microequivalent","ueq","UEQ","amount of substance",602213670000000000,[0,0,0,0,0,0,0],"μeq","chemical",true,null,null,1,false,false,1,"microequivalents; 10^-6 equivalents; 10-6 equivalents","LOINC","Sub","Clinical","","mol","MOL","1",1,false],[false,"microequivalent per liter","ueq/L","UEQ/L","amount of substance",602213670000000000000,[-3,0,0,0,0,0,0],"μeq/L","chemical",true,null,null,1,false,false,1,"ueq per liter; litre; microequivalents","LOINC","MCnc","Clinical","","mol","MOL","1",1,false],[false,"microequivalent per milliliter","ueq/mL","UEQ/ML","amount of substance",6.0221367000000003e+23,[-3,0,0,0,0,0,0],"μeq/mL","chemical",true,null,null,1,false,false,1,"ueq per milliliter; millilitre; microequivalents","LOINC","MCnc","Clinical","","mol","MOL","1",1,false],[true,"microgram","ug","UG","mass",0.000001,[0,0,1,0,0,0,0],"μg",null,false,"M",null,1,false,false,0,"mcg; micrograms; 10^-6 grams; 10-6 grams","LOINC","Mass","Clinical","",null,null,null,null,false],[true,"microgram per 100 gram","ug/(100.g)","UG/G","mass",1e-8,[0,0,0,0,0,0,0],"μg/g",null,false,"M",null,1,false,false,0,"ug/100gm; ug/100 gm; mcg; ug per 100g; 100 gm; mcg per 100g; micrograms per 100 grams","LOINC","MCnt","Clinical","",null,null,null,null,false],[true,"microgram per 24 hour","ug/(24.h)","UG/HR","mass",1.1574074074074074e-11,[0,-1,1,0,0,0,0],"μg/h",null,false,"M",null,1,false,false,0,"ug/24hrs; ug/24 hrs; mcg/24hrs; ug per 24hrs; mcg per 24hrs; 24 hrs; micrograms per 24 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"microgram per 8 hour","ug/(8.h)","UG/HR","mass",3.472222222222222e-11,[0,-1,1,0,0,0,0],"μg/h",null,false,"M",null,1,false,false,0,"ug/8hrs; ug/8 hrs; mcg/8hrs; ug per 8hrs; mcg per 8hrs; 8 hrs; micrograms per 8 hours; shift","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"microgram per square foot (international)","ug/[sft_i]","UG/[SFT_I]","mass",0.000010763910416709721,[-2,0,1,0,0,0,0],"μg",null,false,"M",null,1,false,false,0,"ug/sft; ug/ft2; ug/ft^2; ug/sq. ft; micrograms; sq. foot; foot squared","LOINC","ArMass","Clinical","",null,null,null,null,false],[true,"microgram per day","ug/d","UG/D","mass",1.1574074074074074e-11,[0,-1,1,0,0,0,0],"μg/d",null,false,"M",null,1,false,false,0,"ug/dy; mcg/dy; ug per day; mcg; micrograms per day","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"microgram per deciliter","ug/dL","UG/DL","mass",0.009999999999999998,[-3,0,1,0,0,0,0],"μg/dL",null,false,"M",null,1,false,false,0,"ug per dL; mcg/dl; mcg per dl; micrograms per deciliter; decilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"microgram per gram","ug/g","UG/G","mass",0.000001,[0,0,0,0,0,0,0],"μg/g",null,false,"M",null,1,false,false,0,"ug per gm; mcg/gm; mcg per g; micrograms per gram","LOINC","MCnt","Clinical","",null,null,null,null,false],[true,"microgram per hour","ug/h","UG/HR","mass",2.7777777777777777e-10,[0,-1,1,0,0,0,0],"μg/h",null,false,"M",null,1,false,false,0,"ug/hr; mcg/hr; mcg per hr; ug per hr; ug per hour; micrograms","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"microgram per kilogram","ug/kg","UG/KG","mass",9.999999999999999e-10,[0,0,0,0,0,0,0],"μg/kg",null,false,"M",null,1,false,false,0,"ug per kg; mcg/kg; mcg per kg; micrograms per kilogram","LOINC","MCnt","Clinical","",null,null,null,null,false],[true,"microgram per kilogram per 8 hour","ug/kg/(8.h)","(UG/KG)/HR","mass",3.472222222222222e-14,[0,-1,0,0,0,0,0],"(μg/kg)/h",null,false,"M",null,1,false,false,0,"ug/kg/8hrs; mcg/kg/8hrs; ug/kg/8 hrs; mcg/kg/8 hrs; ug per kg per 8hrs; 8 hrs; mcg per kg per 8hrs; micrograms per kilograms per 8 hours; shift","LOINC","","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[true,"microgram per kilogram per day","ug/kg/d","(UG/KG)/D","mass",1.1574074074074072e-14,[0,-1,0,0,0,0,0],"(μg/kg)/d",null,false,"M",null,1,false,false,0,"ug/(kg.d); ug/kg/dy; mcg/kg/day; ug per kg per dy; 24 hours; 24hrs; mcg; kilograms; microgram per kilogram and day","LOINC","","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[true,"microgram per kilogram per hour","ug/kg/h","(UG/KG)/HR","mass",2.7777777777777774e-13,[0,-1,0,0,0,0,0],"(μg/kg)/h",null,false,"M",null,1,false,false,0,"ug/(kg.h); ug/kg/hr; mcg/kg/hr; ug per kg per hr; mcg per kg per hr; kilograms","LOINC","","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[true,"microgram per kilogram per minute","ug/kg/min","(UG/KG)/MIN","mass",1.6666666666666664e-11,[0,-1,0,0,0,0,0],"(μg/kg)/min",null,false,"M",null,1,false,false,0,"ug/kg/min; ug/kg/min; mcg/kg/min; ug per kg per min; mcg; micrograms per kilograms per minute ","LOINC","","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[true,"microgram per liter","ug/L","UG/L","mass",0.001,[-3,0,1,0,0,0,0],"μg/L",null,false,"M",null,1,false,false,0,"mcg/L; ug per L; mcg; micrograms per liter; litre ","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"microgram per liter per 24 hour","ug/L/(24.h)","(UG/L)/HR","mass",1.1574074074074074e-8,[-3,-1,1,0,0,0,0],"(μg/L)/h",null,false,"M",null,1,false,false,0,"ug/L/24hrs; ug/L/24 hrs; mcg/L/24hrs; ug per L per 24hrs; 24 hrs; day; dy mcg; micrograms per liters per 24 hours; litres","LOINC","","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[true,"microgram per square meter","ug/m2","UG/M2","mass",0.000001,[-2,0,1,0,0,0,0],"μg/(m2)",null,false,"M",null,1,false,false,0,"ug/m^2; ug/sq. m; mcg/m2; mcg/m^2; mcg/sq. m; ug per m2; m^2; sq. meter; mcg; micrograms per square meter; meter squared; metre","LOINC","ArMass","Clinical","unit used to measure mass dose per patient body surface area",null,null,null,null,false],[true,"microgram per cubic meter","ug/m3","UG/M3","mass",0.000001,[-3,0,1,0,0,0,0],"μg/(m3)",null,false,"M",null,1,false,false,0,"ug/m^3; ug/cu. m; mcg/m3; mcg/m^3; mcg/cu. m; ug per m3; ug per m^3; ug per cu. m; mcg; micrograms per cubic meter; meter cubed; metre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"microgram per milligram","ug/mg","UG/MG","mass",0.001,[0,0,0,0,0,0,0],"μg/mg",null,false,"M",null,1,false,false,0,"ug per mg; mcg/mg; mcg per mg; micromilligrams per milligram","LOINC","MCnt","Clinical","",null,null,null,null,false],[true,"microgram per minute","ug/min","UG/MIN","mass",1.6666666666666667e-8,[0,-1,1,0,0,0,0],"μg/min",null,false,"M",null,1,false,false,0,"ug per min; mcg/min; mcg per min; microminutes per minute","LOINC","MRat","Clinical","",null,null,null,null,false],[true,"microgram per milliliter","ug/mL","UG/ML","mass",1,[-3,0,1,0,0,0,0],"μg/mL",null,false,"M",null,1,false,false,0,"ug per mL; mcg/mL; mcg per mL; micrograms per milliliter; millilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[true,"microgram per millimole","ug/mmol","UG/MMOL","mass",1.660540186674939e-27,[0,0,1,0,0,0,0],"μg/mmol",null,false,"M",null,1,false,false,-1,"ug per mmol; mcg/mmol; mcg per mmol; micrograms per millimole","LOINC","Ratio","Clinical","",null,null,null,null,false],[true,"microgram per nanogram","ug/ng","UG/NG","mass",999.9999999999999,[0,0,0,0,0,0,0],"μg/ng",null,false,"M",null,1,false,false,0,"ug per ng; mcg/ng; mcg per ng; micrograms per nanogram","LOINC","MCnt","Clinical","",null,null,null,null,false],[false,"microkatal","ukat","UKAT","catalytic activity",602213670000000000,[0,-1,0,0,0,0,0],"μkat","chemical",true,null,null,1,false,false,1,"microkatals; ukats","LOINC","CAct","Clinical","kat is a unit of catalytic activity with base units = mol/s. Rarely used because its units are too large to practically express catalytic activity. See enzyme unit [U] which is the standard unit for catalytic activity.","mol/s","MOL/S","1",1,false],[false,"microliter","uL","UL","volume",1e-9,[3,0,0,0,0,0,0],"μL","iso1000",true,null,null,1,false,false,0,"microliters; microlitres; mcl","LOINC","Vol","Clinical","","l",null,"1",1,false],[false,"microliter per 2 hour","uL/(2.h)","UL/HR","volume",1.388888888888889e-13,[3,-1,0,0,0,0,0],"μL/h","iso1000",true,null,null,1,false,false,0,"uL/2hrs; uL/2 hrs; mcg/2hr; mcg per 2hr; uL per 2hr; uL per 2 hrs; microliters per 2 hours; microlitres ","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"microliter per hour","uL/h","UL/HR","volume",2.777777777777778e-13,[3,-1,0,0,0,0,0],"μL/h","iso1000",true,null,null,1,false,false,0,"uL/hr; mcg/hr; mcg per hr; uL per hr; microliters per hour; microlitres","LOINC","VRat","Clinical","","l",null,"1",1,false],[true,"micrometer","um","UM","length",0.000001,[1,0,0,0,0,0,0],"μm",null,false,"L",null,1,false,false,0,"micrometers; micrometres; μm; microns","LOINC","Len","Clinical","Unit of length that is usually used in tests related to the eye",null,null,null,null,false],[true,"microns per second","um/s","UM/S","length",0.000001,[1,-1,0,0,0,0,0],"μm/s",null,false,"L",null,1,false,false,0,"um/sec; micron/second; microns/second; um per sec; micrometers per second; micrometres","LOINC","Vel","Clinical","",null,null,null,null,false],[false,"micromole","umol","UMOL","amount of substance",602213670000000000,[0,0,0,0,0,0,0],"μmol","si",true,null,null,1,false,false,1,"micromoles; umols","LOINC","Sub","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per 2 hour","umol/(2.h)","UMOL/HR","amount of substance",83640787500000,[0,-1,0,0,0,0,0],"μmol/h","si",true,null,null,1,false,false,1,"umol/2hrs; umol/2 hrs; umol per 2 hrs; 2hrs; micromoles per 2 hours","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per 24 hour","umol/(24.h)","UMOL/HR","amount of substance",6970065625000,[0,-1,0,0,0,0,0],"μmol/h","si",true,null,null,1,false,false,1,"umol/24hrs; umol/24 hrs; umol per 24 hrs; per 24hrs; micromoles per 24 hours","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per 8 hour","umol/(8.h)","UMOL/HR","amount of substance",20910196875000,[0,-1,0,0,0,0,0],"μmol/h","si",true,null,null,1,false,false,1,"umol/8hr; umol/8 hr; umol per 8 hr; umol per 8hr; umols per 8hr; umol per 8 hours; micromoles per 8 hours; shift","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per day","umol/d","UMOL/D","amount of substance",6970065625000,[0,-1,0,0,0,0,0],"μmol/d","si",true,null,null,1,false,false,1,"umol/day; umol per day; umols per day; umol per days; micromoles per days; umol/24hr; umol/24 hr; umol per 24 hr; umol per 24hr; umols per 24hr; umol per 24 hours; micromoles per 24 hours","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per deciliter","umol/dL","UMOL/DL","amount of substance",6.0221367e+21,[-3,0,0,0,0,0,0],"μmol/dL","si",true,null,null,1,false,false,1,"micromole/deciliter; micromole/decilitre; umol per dL; micromoles per deciliters; micromole per decilitres","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per gram","umol/g","UMOL/G","amount of substance",602213670000000000,[0,0,-1,0,0,0,0],"μmol/g","si",true,null,null,1,false,false,1,"micromole/gram; umol per g; micromoles per gram","LOINC","SCnt; Ratio","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per hour","umol/h","UMOL/HR","amount of substance",167281575000000,[0,-1,0,0,0,0,0],"μmol/h","si",true,null,null,1,false,false,1,"umol/hr; umol per hr; umol per hour; micromoles per hours","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per kilogram","umol/kg","UMOL/KG","amount of substance",602213670000000,[0,0,-1,0,0,0,0],"μmol/kg","si",true,null,null,1,false,false,1,"umol per kg; micromoles per kilogram","LOINC","SCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per liter","umol/L","UMOL/L","amount of substance",602213670000000000000,[-3,0,0,0,0,0,0],"μmol/L","si",true,null,null,1,false,false,1,"micromole/liter; micromole/litre; umol per liter; micromoles per liter; litre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per liter per hour","umol/L/h","(UMOL/L)/HR","amount of substance",167281575000000000,[-3,-1,0,0,0,0,0],"(μmol/L)/h","si",true,null,null,1,false,false,1,"umol/liter/hr; umol/litre/hr; umol per L per hr; umol per liter per hour; micromoles per liters per hour; litre","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min; umol/L/h is a derived unit of enzyme units","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per milligram","umol/mg","UMOL/MG","amount of substance",602213670000000000000,[0,0,-1,0,0,0,0],"μmol/mg","si",true,null,null,1,false,false,1,"micromole/milligram; umol per mg; micromoles per milligram","LOINC","SCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per minute","umol/min","UMOL/MIN","amount of substance",10036894500000000,[0,-1,0,0,0,0,0],"μmol/min","si",true,null,null,1,false,false,1,"micromole/minute; umol per min; micromoles per minute; enzyme units","LOINC","CAct","Clinical","unit for the enzyme unit U = umol/min","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per minute per gram","umol/min/g","(UMOL/MIN)/G","amount of substance",10036894500000000,[0,-1,-1,0,0,0,0],"(μmol/min)/g","si",true,null,null,1,false,false,1,"umol/min/gm; umol per min per gm; micromoles per minutes per gram; U/g; enzyme units","LOINC","CCnt","Clinical","unit for the enzyme unit U = umol/min. umol/min/g = U/g","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per minute per liter","umol/min/L","(UMOL/MIN)/L","amount of substance",10036894500000000000,[-3,-1,0,0,0,0,0],"(μmol/min)/L","si",true,null,null,1,false,false,1,"umol/min/liter; umol/minute/liter; micromoles per minutes per liter; litre; enzyme units; U/L","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min. umol/min/L = U/L","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per milliliter","umol/mL","UMOL/ML","amount of substance",6.0221367000000003e+23,[-3,0,0,0,0,0,0],"μmol/mL","si",true,null,null,1,false,false,1,"umol per mL; micromoles per milliliter; millilitre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per milliliter per minute","umol/mL/min","(UMOL/ML)/MIN","amount of substance",1.00368945e+22,[-3,-1,0,0,0,0,0],"(μmol/mL)/min","si",true,null,null,1,false,false,1,"umol per mL per min; micromoles per milliliters per minute; millilitres","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min. umol/mL/min = U/mL","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per millimole","umol/mmol","UMOL/MMOL","amount of substance",0.001,[0,0,0,0,0,0,0],"μmol/mmol","si",true,null,null,1,false,false,0,"umol per mmol; micromoles per millimole","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per mole","umol/mol","UMOL/MOL","amount of substance",0.000001,[0,0,0,0,0,0,0],"μmol/mol","si",true,null,null,1,false,false,0,"umol per mol; micromoles per mole","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per micromole","umol/umol","UMOL/UMOL","amount of substance",1,[0,0,0,0,0,0,0],"μmol/μmol","si",true,null,null,1,false,false,0,"umol per umol; micromoles per micromole","LOINC","Srto; SFr; EntSRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"microOhm","uOhm","UOHM","electric resistance",0.001,[2,-1,1,0,0,-2,0],"μΩ","si",true,null,null,1,false,false,0,"microOhms; µΩ","LOINC","","Clinical","unit of electric resistance","V/A","V/A","1",1,false],[true,"microsecond","us","US","time",0.000001,[0,1,0,0,0,0,0],"μs",null,false,"T",null,1,false,false,0,"microseconds","LOINC","Time","Clinical","",null,null,null,null,false],[false,"micro enzyme unit per gram","uU/g","UU/G","catalytic activity",10036894500,[0,-1,-1,0,0,0,0],"μU/g","chemical",true,null,null,1,false,false,1,"uU per gm; micro enzyme units per gram; micro enzymatic activity per mass; enzyme activity","LOINC","CCnt","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 uU = 1pmol/min","umol/min","UMOL/MIN","1",1,false],[false,"micro enzyme unit per liter","uU/L","UU/L","catalytic activity",10036894500000,[-3,-1,0,0,0,0,0],"μU/L","chemical",true,null,null,1,false,false,1,"uU per L; micro enzyme units per liter; litre; enzymatic activity per volume; enzyme activity ","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 uU = 1pmol/min","umol/min","UMOL/MIN","1",1,false],[false,"micro enzyme unit per milliliter","uU/mL","UU/ML","catalytic activity",10036894500000000,[-3,-1,0,0,0,0,0],"μU/mL","chemical",true,null,null,1,false,false,1,"uU per mL; micro enzyme units per milliliter; millilitre; enzymatic activity per volume; enzyme activity","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 uU = 1pmol/min","umol/min","UMOL/MIN","1",1,false],[false,"microvolt","uV","UV","electric potential",0.001,[2,-2,1,0,0,-1,0],"μV","si",true,null,null,1,false,false,0,"microvolts","LOINC","Elpot","Clinical","unit of electric potential (voltage)","J/C","J/C","1",1,false]]}} },{}],90:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Ucum = void 0; /* * This defines the namespace for the UCUM classes and provides * a place for the definition of global variables and constants. * * The javascript for this UCUM implementation uses syntax as * defined by the ECMAScript 6 standard */ var Ucum = { /** * Flag indicating whether or not we're using case sensitive labels * I don't think we need this. I think we're just going with * case sensitive, per Clem. Gunther's code has this flag, but I * am removing it, at least for now. lm, 6/2016 */ //caseSensitive_: true , /** * The number of elements in a Dimension array. Currently this * is set as a configuration variable, but when we get to the point * of loading the unit definitions from a file, this value will be * set from that. */ dimLen_: 7, /** * The characters used as valid operators in a UCUM unit expression, * where '.' is for multiplication and '/' is for division. */ validOps_: ['.', '/'], /** * The string used to separate a unit code and unit name when they * are displayed together */ codeSep_: ': ', // Message text variations for validation methods and conversion methods valMsgStart_: 'Did you mean ', valMsgEnd_: '?', cnvMsgStart_: 'We assumed you meant ', cnvMsgEnd_: '.', /** * Default opening string used to emphasize portions of error messages. * Used when NOT displaying messages on a web site, i.e., for output * from the library methods or to a file. */ openEmph_: ' ->', /** * Default closing string used to emphasize portions of error messages. * Used when NOT displaying messages on a web site, i.e., for output * from the library methods or to a file. */ closeEmph_: '<- ', /** * Opening HTML used to emphasize portions of error messages. Used when * displaying messages on a web site; should be blank when output is * to a file. */ openEmphHTML_: '', /** * Closing HTML used to emphasize portions of error messages. Used when * displaying messages on a web site; should be blank when output is * to a file. */ closeEmphHTML_: '', /** * Message that is displayed when annotations are included in a unit * string, to let the user know how they are interpreted. */ bracesMsg_: 'FYI - annotations (text in curly braces {}) are ignored, ' + 'except that an annotation without a leading symbol implies ' + 'the default unit 1 (the unity).', /** * Message that is displayed or returned when a conversion is requested * for two units where (only) a mass<->moles conversion is appropriate * but no molecular weight was specified. */ needMoleWeightMsg_: 'Did you wish to convert between mass and moles? The ' + 'molecular weight of the substance represented by the ' + 'units is required to perform the conversion.', /** * Hash that matches unit column names to names used in the csv file * that is submitted to the data updater. */ csvCols_: { 'case-sensitive code': 'csCode_', 'LOINC property': 'loincProperty_', 'name (display)': 'name_', 'synonyms': 'synonyms_', 'source': 'source_', 'category': 'category_', 'Guidance': 'guidance_' }, /** * Name of the column in the csv file that serves as the key */ inputKey_: 'case-sensitive code', /** * Special codes that contain operators within brackets. The operator * within these codes causes them to parse incorrectly if they are preceded * by a prefix, because the parsing algorithm splits them up on the operator. * So we use this object to identify them and substitute placeholders to * avoid that. */ specUnits_: { 'B[10.nV]': 'specialUnitOne', '[m/s2/Hz^(1/2)]': 'specialUnitTwo' } }; exports.Ucum = Ucum; },{}],91:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Dimension = void 0; /** * This class implements an object containing the vector of exponents for * a unit and its operations for addition, subtraction, and multiplication * with a scalar. * * This object should exist for each unit that can be expressed as a * vector of numbers. This excludes arbitrary units, e.g., (10*23), and * units that are not numbers but are an expression based solely on numbers, * e.g., mol (mole) which is based on 10*23. * * @author Lee Mericle, based on java version by Gunther Schadow */ var UC = require('./config.js'); var isInteger = require("is-integer"); class Dimension { /** * Constructor. * * @param dimSetting an optional parameter that may be: * null, which means that the dimVec_ attribute for this object will be null; or * an array, which must be the length defined by Ucum.dimLen_, and * whose contents will be copied to this new object's vector; or * an integer, which must be between 0 and 1 less than the vector length * defined by Ucum.dimLen_. This new object's vector will be * initialized to zero for all elements except the one whose index * matches the number passed in. That element will be set to one. * @throws an error if the dimSetting parameter does not meet the types * listed above. * An error will also be thrown if Ucum.dimLen_ has not been set yet, * i.e., is still zero. Currently that won't happen, because the * value is set in the config.js file. But further down the road * the setting will come from a definitions input file, so we check * here anyway. * */ constructor(dimSetting) { if (UC.Ucum.dimLen_ === 0) { throw new Error('Dimension.setDimensionLen must be called before ' + 'Dimension constructor'); } if (dimSetting === undefined || dimSetting === null) { this.assignZero(); } else if (dimSetting instanceof Array) { if (dimSetting.length !== UC.Ucum.dimLen_) { throw new Error('Parameter error, incorrect length of vector passed to ' + `Dimension constructor, vector = ${JSON.stringify(dimSetting)}`); } this.dimVec_ = []; for (let d = 0; d < UC.Ucum.dimLen_; d++) this.dimVec_.push(dimSetting[d]); } // In es6 this should be Number.isInteger(dimSetting). But Babel // doesn't transpile that correctly, so we need to use the isInteger // module. :0 else if (isInteger(dimSetting)) { if (dimSetting < 0 || dimSetting >= UC.Ucum.dimLen_) { throw new Error('Parameter error, invalid element number specified for ' + 'Dimension constructor'); } this.assignZero(); this.dimVec_[dimSetting] = 1; } } // end constructor /** * Sets the element at the specified position to a specified value. The * default value is 1. If the dimension vector is null when this is called * a zero-filled vector is created and then the indicated position is set. * * @param indexPos the index of the element to be set * @param value the value to assign to the specified element; optional, * default value is 1 * @throws an exception if the specified position is invalid, i.e., not a * number or is less than 0 or greater than Ucum.dimLen_ **/ setElementAt(indexPos, value) { if (!isInteger(indexPos) || indexPos < 0 || indexPos >= UC.Ucum.dimLen_) { throw new Error(`Dimension.setElementAt called with an invalid index ` + `position (${indexPos})`); } if (!this.dimVec_) { this.assignZero(); } if (value === undefined || value === null) value = 1; this.dimVec_[indexPos] = value; } /** * Gets the value of the element at the specified position * * @param indexPos the index of the element whose value is to be returned * @return the value of the element at indexPos, or null if the dimension * vector is null * @throws an exception if the specified position is invalid, i.e., not a * number or is less than 0 or greater than Ucum.dimLen_ **/ getElementAt(indexPos) { if (!isInteger(indexPos) || indexPos < 0 || indexPos >= UC.Ucum.dimLen_) { throw new Error(`Dimension.getElementAt called with an invalid index ` + `position (${indexPos})`); } let ret = null; if (this.dimVec_) ret = this.dimVec_[indexPos]; return ret; } /** * This returns the value of the property named by the parameter * passed in. Although we currently only have one property, dimVec_, * that this will get, it's possible that we'll have additional * properties. If we don't this could just be replaced by a * getVector function. * * @param propertyName name of the property to be returned, with * or without the trailing underscore. * @return the requested property, if found for this Dimension * @throws an error if the property is not found for this Dimension */ getProperty(propertyName) { let uProp = propertyName.charAt(propertyName.length - 1) === '_' ? propertyName : propertyName + '_'; return this[uProp]; } // end getProperty /** * Return a string that represents the dimension vector. Returns null if * the dimension vector is null. * * @return the string that represents the dimension vector. The * values are enclosed in square brackets, each separated * by a comma and a space **/ toString() { let ret = null; if (this.dimVec_) ret = '[' + this.dimVec_.join(', ') + ']'; return ret; } /** * Adds the vector of the dimension object passed in to this * dimension object's vector. This object's vector is changed. * If either dimension vector is null, no changes are made to this object. * * * @param dim2 the dimension whose vector is to be added to this one * @return this object * @throws an exception if dim2 is not a Dimension object **/ add(dim2) { if (!dim2 instanceof Dimension) { throw new Error(`Dimension.add called with an invalid parameter - ` + `${typeof dim2} instead of a Dimension object`); } if (this.dimVec_ && dim2.dimVec_) { for (let i = 0; i < UC.Ucum.dimLen_; i++) this.dimVec_[i] += dim2.dimVec_[i]; } return this; } /** * Subtracts the vector of the dimension object passed in from this * dimension object's vector. This object's vector is changed. * If either dimension vector is null, no changes are made to this object. * * @param dim2 the dimension whose vector is to be subtracted from this one * @return this object * @throws an exception if dim2 is not a Dimension object **/ sub(dim2) { if (!dim2 instanceof Dimension) { throw new Error(`Dimension.sub called with an invalid parameter - ` + `${typeof dim2} instead of a Dimension object`); } if (this.dimVec_ && dim2.dimVec_) { for (let i = 0; i < UC.Ucum.dimLen_; i++) this.dimVec_[i] -= dim2.dimVec_[i]; } return this; } /** * Inverts this dimension object's vector (by multiplying each element * by negative 1). This object's vector is changed - unless it is null, * in which case it stays that way. * * @return this object **/ minus() { if (this.dimVec_) { for (let i = 0; i < UC.Ucum.dimLen_; i++) this.dimVec_[i] = -this.dimVec_[i]; } return this; } /** * Multiplies this dimension object's vector with a scalar. This is used * when a unit is raised to a power. This object's vector is changed unless * the vector is null, in which case it stays that way. * * @param s the scalar to use * @return this object * @throws an exception if s is not a number */ mul(s) { if (!isInteger(s)) { throw new Error(`Dimension.sub called with an invalid parameter - ` + `${typeof dim2} instead of a number`); } if (this.dimVec_) { for (let i = 0; i < UC.Ucum.dimLen_; i++) this.dimVec_[i] *= s; } return this; } /** * Tests for equality of this dimension object's vector and that of * the dimension object passed in. If the dimension vector for one of * the objects is null, the dimension vector for the other object must * also be null for the two to be equal. (I know - duh. still) * * @param dim2 the dimension object whose vector is to be compared to this one * @return true if the two vectors are equal; false otherwise. * @throws an exception if dim2 is not a Dimension object */ equals(dim2) { if (!dim2 instanceof Dimension) { throw new Error(`Dimension.equals called with an invalid parameter - ` + `${typeof dim2} instead of a Dimension object`); } let isEqual = true; let dimVec2 = dim2.dimVec_; if (this.dimVec_ && dimVec2) { for (let i = 0; isEqual && i < UC.Ucum.dimLen_; i++) isEqual = this.dimVec_[i] === dimVec2[i]; } else { isEqual = this.dimVec_ === null && dimVec2 === null; } return isEqual; } /** * Assigns the contents of the vector belonging to the dimension object * passed in to this dimension's vector. If this dimension vector is null * and the other is not, this one will get the contents of the other. If * this dimension vector is not null but the one passed in is null, this * one will be set to null. * * @param dim2 the dimension object with the vector whose contents are * to be assigned to this dimension's vector * @return this object (not sure why) * @throws an exception if dim2 is not a Dimension object */ assignDim(dim2) { if (!dim2 instanceof Dimension) { throw new Error(`Dimension.assignDim called with an invalid parameter - ` + `${typeof dim2} instead of a Dimension object`); } if (dim2.dimVec_ === null) this.dimVec_ = null;else { if (this.dimVec_ === null) { this.dimVec_ = []; } for (let i = 0; i < UC.Ucum.dimLen_; i++) this.dimVec_[i] = dim2.dimVec_[i]; } return this; } /** * Sets all elements of this dimension object's vector to zero. * If this object's vector is null, it is created as a zero-filled vector. * * @return this object (not sure why) */ assignZero() { if (this.dimVec_ === null || this.dimVec_ === undefined) this.dimVec_ = []; for (let i = 0; i < UC.Ucum.dimLen_; i++) { this.dimVec_.push(0); } return this; } /** * Tests for a dimension vector set to all zeroes. * * @return true if exponents (elements) of this dimension's vector are all * zero; false otherwise (including if the current vector is null). * */ isZero() { let allZero = this.dimVec_ !== null; if (this.dimVec_) { for (let i = 0; allZero && i < UC.Ucum.dimLen_; i++) allZero = this.dimVec_[i] === 0; } return allZero; } /** * Tests for a Dimension object with no dimension vector (dimVec_ is null). * * @return true the dimension vector is null; false if it is not * */ isNull() { return this.dimVec_ === null; } /** * Creates and returns a clone of this Dimension object * * @return the clone */ clone() { let that = new Dimension(); that.assignDim(this); return that; } } // end Dimension class exports.Dimension = Dimension; },{"./config.js":90,"is-integer":181}],92:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.packArray = packArray; exports.unpackArray = unpackArray; /** * This file provides functions to reduce the size of an array of objects of the same structure in JSON. */ const pushFn = Array.prototype.push; function isObject(value) { return Object.prototype.toString.call(value) === '[object Object]'; } /** * Makes human readable config used to pack/unpack array of objects of the same structure to store with packed data. * @param {Object} refObj - reference item of array of objects of the same structure * @returns {Array} */ function createConfig(refObj) { return Object.keys(refObj).reduce((config, key) => { if (isObject(refObj[key])) { pushFn.apply(config, createConfig(refObj[key]).map(keyTail => [key, ...[].concat(keyTail)])); } else { config.push(key); } return config; }, []); } /** * Prepares config created with createConfig function to use in packItem/unpackItem functions. * @param {Array} config * @returns {Array} */ function prepareConfig(config) { return config.map(key => Array.isArray(key) ? key : [key]); } /** * Converts an object to an array of values in the order of keys from configuration array. * @param {Array} config - configuration array * @param {Object} item - input object * @returns {Array} */ function packItem(config, item) { if (config.join() !== prepareConfig(createConfig(item)).join()) { throw new Error('Object of unusual structure'); } return config.map(keyArr => { let place = item; keyArr.forEach(key => { place = place[key]; if (place === undefined) { throw new Error('Object of unusual structure'); } }); return place; }); } /** * Performs the reverse of packItem function. * @param {Array} config - configuration array * @param {Array} item - input object * @returns {Object} */ function unpackItem(config, item) { let result = {}; config.forEach((keyArr, i) => { let place = result; for (let i = 0; i < keyArr.length - 1; i++) { place = place[keyArr[i]] = place[keyArr[i]] || {}; } place[keyArr[keyArr.length - 1]] = item[i]; }); return result; } /** * Reduces size of an array of objects of the same structure before serialize it to JSON * @param {Array} arr * @returns {Object} */ function packArray(arr) { if (arr && arr.length) { const config = createConfig(arr[0]), _config = prepareConfig(config); if (config.length) { return { config: config, data: arr.map(packItem.bind(null, _config)) }; } } return { config: [], data: arr }; } /** * Restores an array of objects of the same structure after deserializing this object from JSON * @param {Object} obj * @returns {Array} */ function unpackArray(obj) { const config = obj && obj.config; if (config) { if (config.length && obj.data) { const _config = prepareConfig(config); return obj.data.map(unpackItem.bind(null, _config)); } else { return obj.data; } } return obj; } },{}],93:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Prefix = void 0; /** * Prefix objects are defined in this file. */ /** * This class implements the prefix object. Prefixes are used as multipliers * for units, e.g., km for kilometers * * @author Lee Mericle, based on java version by Gunther Schadow * */ var Ucum = require('./config.js'); class Prefix { /** * Creates a single prefix object. * * @param attrs a hash of the values to use in creating the prefix object. * They should be: * code_ - which is the case-sensitive code used for the prefix, * e.g., k for kilo * ciCode_ - which is the case-insensitive code used for the prefix, * e.g., K for kilo * name_ - which is the name of the prefix, e.g., kilo * printSymbol_ - which is the print symbol for the prefix, e.g., k for kilo * value_ - which is teh value to use in multiplying the magnitude of * a unit, e.g., for a prefix of c the value will be .01. * exp_ - which is the exponent used to get the value. For decimal based * prefixes the base is 10 and the exp_ is applied to 10, e.g., for a * prefix of c, the exponent will be -2. For prefixes that are not * decimal based, this will be null (but must not be undefined). * * @throws an error if the not all required parameters are provided */ constructor(attrs) { if (attrs['code_'] === undefined || attrs['code_'] === null || attrs['name_'] === undefined || attrs['name_'] === null || attrs['value_'] === undefined || attrs['value_'] === null || attrs['exp_'] === undefined) { throw new Error('Prefix constructor called missing one or more parameters. ' + 'Prefix codes (cs or ci), name, value and exponent must all be specified ' + 'and all but the exponent must not be null.'); } /** * The prefix code, e.g., k for kilo. This should be the case-sensitive * code. Since there's no way to check to see if it's the case-sensitive * one as opposed to the case-insensitive one (because although * case-insensitive codes all seem to be uppercase, some case-sensitive * codes are also all uppercase), we'll just have to believe that the * right one was passed in. */ this.code_ = attrs['code_']; /** * The case-insensitive code, e.g., K for kilo */ this.ciCode_ = attrs['ciCode_']; /** * The prefix name, e.g., kilo */ this.name_ = attrs['name_']; /** * The printSymbol for the prefix, e.g., k for kilo */ this.printSymbol_ = attrs['printSymbol_']; /** * The value to use in multiplying the magnitude of a unit */ if (typeof attrs['value_'] === 'string') this.value_ = parseFloat(attrs['value_']);else this.value_ = attrs['value_']; /** * The exponent used to create the value from 10. For prefixes that are * not based on 10, this will be null. */ this.exp_ = attrs['exp_']; } // end constructor /** * Returns the value for the current prefix object * @return the value for the prefix object with the specified code * */ getValue() { return this.value_; } /** * Returns the prefix code for the current prefix object * @return the code for the current prefix object */ getCode() { return this.code_; } /** * Returns the case-insensitive code for the current prefix object * @return the case_insensitive code for the current prefix object */ getCiCode() { return this.ciCode_; } /** * Returns the prefix name for the current prefix object * @return the name for the current prefix object */ getName() { return this.name_; } /** * Returns the print symbol for the current prefix object * @return the print symbol for the current prefix object */ getPrintSymbol() { return this.printSymbol_; } /** * Returns the exponent for the current prefix object * @return the exponent for the current prefix object */ getExp() { return this.exp_; } /** * Provides way to tell if one prefix equals another. The second prefix * must match all attribute values. * * @param prefix2 prefix object to check for a match * @return true for a match; false if one or more attributes don't match */ equals(prefix2) { return this.code_ === prefix2.code_ && this.ciCode_ === prefix2.ciCode_ && this.name_ === prefix2.name_ && this.printSymbol_ === prefix2.printSymbol_ && this.value_ === prefix2.value_ && this.exp_ === prefix2.exp_; } } // end Prefix class exports.Prefix = Prefix; },{"./config.js":90}],94:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PrefixTables = exports.PrefixTablesFactory = void 0; /** * The tables of defined prefixes is defined in this file. */ /** * This class implements the table of multiplier prefixes. * * @author Lee Mericle, based on java version by Gunther Schadow * */ class PrefixTablesFactory { /** * Constructor. This creates the empty PrefixTable hashes once. * There is one hash whose key is the prefix code and one whose * key is the prefix value. * * Implementation of this as a singleton is based on the UnitTables * implementation. See that class for details. */ constructor() { this.byCode_ = {}; this.byValue_ = {}; } /** * Provides the number of prefix objects in each table * @returns count of the number of prefix objects in each table */ prefixCount() { return Object.keys(this.byCode_).length; } /** * This is used to get all prefix objects by value. Currently it is used * to create a csv file with all prefixes and units. * @returns csv string containing all prefix objects, ordered by value. */ allPrefixesByValue() { let prefixBuff = ''; let pList = Object.keys(this.byValue_); //pList.sort() ; let pLen = pList.length; for (let p = 0; p < pLen; p++) { let pfx = this.getPrefixByValue(pList[p]); prefixBuff += pfx.code_ + ',' + pfx.name_ + ',,' + pfx.value_ + '\r\n'; } return prefixBuff; } /** * This is used to get all prefix objects. Currently it is used * to get the objects to write to the json ucum definitions file * that is used to provide prefix and unit definition objects for * conversions and validations. * * @returns an array containing all prefix objects, ordered by code. */ allPrefixesByCode() { let prefixList = []; let pList = Object.keys(this.byCode_); pList.sort(); let pLen = pList.length; for (let p = 0; p < pLen; p++) { prefixList.push(this.getPrefixByCode(pList[p])); } return prefixList; } /** * Adds a prefix object to the tables * * @param prefixObj the object to be added to the tables */ add(prefixObj) { this.byCode_[prefixObj.getCode()] = prefixObj; this.byValue_[prefixObj.getValue()] = prefixObj; } /** * Tests whether a prefix object is found for a specified code. This * is used to determine whether or not a prefix object has been created * for the code. * * @param code the code to be used to find the prefix object * @return boolean indicating whether or not a prefix object was found * for the specified code */ isDefined(code) { return this.byCode_[code] !== null && this.byCode_[code] !== undefined; } /** * Obtains a prefix object for a specified code. * * @param code the code to be used to find the prefix object * @return the prefix object found, or null if nothing was found */ getPrefixByCode(code) { return this.byCode_[code]; } /** * Obtains a prefix object for a specified value. * * @param value the value to be used to find the prefix object * @return the prefix object found, or null if nothing was found */ getPrefixByValue(value) { return this.byValue_[value]; } } // end PrefixTablesFactory class // Create a singleton instance and (to preserve the existing API) an object that // provides that instance via getInstance(). exports.PrefixTablesFactory = PrefixTablesFactory; var prefixTablesInstance = new PrefixTablesFactory(); const PrefixTables = { getInstance: function () { return prefixTablesInstance; } }; exports.PrefixTables = PrefixTables; },{}],95:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; /* * This class manages the special functions used by some units. * * @author Lee Mericle, based on java version by Gunther Schadow * */ class UcumFunctions { /** * Constructor * * Creates the singleton object that contains the list of functions used * to convert special units. */ constructor() { // Create the hash containing the function pairs this.funcs = {}; // Celsius - convert to Celsius from kelvin and from Celsius to kelvin // where kelvin is the base unit for temperature this.funcs['cel'] = { cnvTo: function (x) { return x - 273.15; }, cnvFrom: function (x) { return x + 273.15; } }; // Fahrenheit - convert to Fahrenheit from kelvin and from Fahrenheit to // kelvin - which is the base unit for temperature this.funcs['degf'] = { cnvTo: function (x) { return x - 459.67; }, cnvFrom: function (x) { return x + 459.67; } }; // Reaumur - convert between Reaumur and Kelvin. Because of the way the // calling code in the Units class is set up (in the convertFrom method), // what is given here as the convertTo function is actually the convert // from method and vice versa. //this.funcs['degre'] = {cnvTo : function(x){return x + 273.15;}, // cnvFrom : function(x){return x - 273.15;}}; this.funcs['degre'] = { cnvTo: function (x) { return x - 273.15; }, cnvFrom: function (x) { return x + 273.15; } }; // pH - convert to pH from moles per liter and from moles per liter to pH // where a mole is an amount of a substance (a count of particles) this.funcs['ph'] = { cnvTo: function (x) { return -Math.log(x) / Math.LN10; }, cnvFrom: function (x) { return Math.pow(10, -x); } }; // ln - natural logarithm (base e 2.71828) - apply (cnvTo) and invert (cnvFrom) // and 2ln - two times the natural logarithm this.funcs['ln'] = { cnvTo: function (x) { return Math.log(x); }, cnvFrom: function (x) { return Math.exp(x); } }; this.funcs['2ln'] = { cnvTo: function (x) { return 2 * Math.log(x); }, cnvFrom: function (x) { return Math.exp(x / 2); } }; // lg - the decadic logarithm (base 10) this.funcs['lg'] = { cnvTo: function (x) { return Math.log(x) / Math.LN10; }, cnvFrom: function (x) { return Math.pow(10, x); } }; this.funcs['10lg'] = { cnvTo: function (x) { return 10 * Math.log(x) / Math.LN10; }, cnvFrom: function (x) { return Math.pow(10, x / 10); } }; this.funcs['20lg'] = { cnvTo: function (x) { return 20 * Math.log(x) / Math.LN10; }, cnvFrom: function (x) { return Math.pow(10, x / 20); } }; // The plain text ucum units file uses '2lg' this.funcs['2lg'] = { cnvTo: function (x) { return 2 * Math.log(x) / Math.LN10; }, cnvFrom: function (x) { return Math.pow(10, x / 2); } }; // The xml essence ucum file uses lgTimes2 this.funcs['lgtimes2'] = this.funcs['2lg']; // ld - dual logarithm (base 2) this.funcs['ld'] = { cnvTo: function (x) { return Math.log(x) / Math.LN2; }, cnvFrom: function (x) { return Math.pow(2, x); } }; // tan - tangent this.funcs['100tan'] = { cnvTo: function (x) { return Math.tan(x) * 100; }, cnvFrom: function (x) { return Math.atan(x / 100); } }; // the xml essence ucum file uses both 100tan and tanTimes100 this.funcs['tanTimes100'] = this.funcs['100tan']; // sqrt - square root this.funcs['sqrt'] = { cnvTo: function (x) { return Math.sqrt(x); }, cnvFrom: function (x) { return x * x; } }; // inv - inverse this.funcs['inv'] = { cnvTo: function (x) { return 1.0 / x; }, cnvFrom: function (x) { return 1.0 / x; } }; // homeopathic potency functions this.funcs['hpX'] = { cnvTo: function (x) { return -this.funcs['lg'](x); }, cnvFrom: function (x) { return Math.pow(10, -x); } }; this.funcs['hpC'] = { cnvTo: function (x) { return -this.func['ln'](x) / this.funcs['ln'](100); }, cnvFrom: function (x) { return Math.pow(100, -x); } }; this.funcs['hpM'] = { cnvTo: function (x) { return -this.funcs['ln'](x) / this.funcs['ln'](1000); }, cnvFrom: function (x) { return Math.pow(1000, -x); } }; this.funcs['hpQ'] = { cnvTo: function (x) { return -this.funcs['ln'](x) / this.funcs['ln'](50000); }, cnvFrom: function (x) { return Math.pow(50000, -x); } }; } // end of constructor /** * Returns the function with the name specified * * @param fname name of the function to be returned * @return the function with the specified name * @throws an error message if the function is not found */ forName(fname) { fname = fname.toLowerCase(); let f = this.funcs[fname]; if (f === null) throw new Error(`Requested function ${fname} is not defined`); return f; } /** * Returns a flag indicating whether or not the function has been * defined. * * @param fname name of the function in question * @return true if it has been defined; false if not */ isDefined(fname) { fname = fname.toLowerCase(); return this.funcs[fname] !== null; } } // end of UcumFunctions class var _default = new UcumFunctions(); // one singleton instance exports.default = _default; },{}],96:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isNumericString = isNumericString; exports.isIntegerUnit = isIntegerUnit; exports.getSynonyms = getSynonyms; /** * Internal utilities used by multiple UCUM classes. For example, * isNumericString is used by both the UnitString and UcumLhcUtils * classes. If it's in the UnitString class the UcumLhcUtils class * needs to require the UnitString class. But the checkSynonyms * class is used by the UnitString class - but was in the UcumLhcUtils * class. Requiring the UcumLhcUtils class from the UnitString class * made everything break (cyclical requires). * * So now they're here. */ /** * This module implements internal ucum utilities. * * @author Lee Mericle, based on java version by Gunther Schadow * */ var UnitTables = require('./unitTables.js').UnitTables; /** * This function tests a string to see if it contains only numbers (digits, * a period, leading - or +). This code was taken from a stackoverflow * solution: * https://stackoverflow.com/questions/175739/is-there-a-built-in-way-in-javascript-to-check-if-a-string-is-a-valid-number/42356340#42356340 * * @params theString * @returns true if the string contains only numbers; false otherwise */ function isNumericString(theString) { let num = "" + theString; //coerce num to be a string return !isNaN(num) && !isNaN(parseFloat(num)); } // end isNumericString /** * Checks whether a string qualifies as an integer unit. Section 2.2.8 ("integer * numbers", says, "A positive integer number may appear in place of a simple * unit symbol. Only a pure string of decimal digits (‘0’–‘9’) is * interpreted as a number." * Note: This leaves open the question of whether "0" is a valid unit, since * it is positive, but you can't measure anything in units of zero. * @param str the string to check */ function isIntegerUnit(str) { return /^\d+$/.test(str); } /** * This method accepts a term and looks for units that include it as * a synonym - or that include the term in its name. * * @param theSyn the term to search for. This is assumed to be * a string and not undefined. The calling method should do any * necessary checking before calling this. * @returns a hash with up to three elements: * 'status' contains the status of the request, which can be 'error', * 'failed' or succeeded'; * 'msg' which contains a message for an error or if no units were found; and * 'units' which is an array that contains one array for each unit found: * the unit's csCode_, the unit's name_, and the unit's guidance_ * */ function getSynonyms(theSyn) { let retObj = {}; let utab = UnitTables.getInstance(); let resp = {}; resp = utab.getUnitBySynonym(theSyn); // If we didn't get any units, transfer the status and message if (!resp['units']) { retObj['status'] = resp['status']; retObj['msg'] = resp['msg']; } else { retObj['status'] = 'succeeded'; let aLen = resp['units'].length; retObj['units'] = []; for (let a = 0; a < aLen; a++) { let theUnit = resp['units'][a]; retObj['units'][a] = { 'code': theUnit.csCode_, 'name': theUnit.name_, 'guidance': theUnit.guidance_ }; } // end do for all units returned } // end if we got a units list return retObj; } // end getSynonyms },{"./unitTables.js":102}],97:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ucumJsonDefs = exports.UcumJsonDefs = void 0; /** * This class handles opening, reading and loading the JSON file of ucum * definitions (prefixes, base units, and unit atoms). * * @author Lee Mericle * */ var Pfx = require("./prefix.js"); var PfxT = require("./prefixTables.js"); var Un = require("./unit.js"); var Utab = require('./unitTables.js'); var unpackArray = require('./jsonArrayPack.js').unpackArray; class UcumJsonDefs { /** * This method loads the JSON prefix and unit objects into the prefix and * unit tables. * * @returns nothing */ loadJsonDefs() { // requiring the file will take care of opening it for use const jsonDefs = require('../data/ucumDefs.min.json'); jsonDefs.prefixes = unpackArray(jsonDefs.prefixes); jsonDefs.units = unpackArray(jsonDefs.units); if (Utab.UnitTables.getInstance().unitsCount() === 0) { let pTab = PfxT.PrefixTables.getInstance(); let prefixes = jsonDefs["prefixes"]; let plen = prefixes.length; for (let p = 0; p < plen; p++) { let newPref = new Pfx.Prefix(prefixes[p]); pTab.add(newPref); } let uTab = Utab.UnitTables.getInstance(); let units = jsonDefs["units"]; let ulen = units.length; for (let u = 0; u < ulen; u++) { let newUnit = new Un.Unit(units[u]); uTab.addUnit(newUnit); } } // end if the data has not already been loaded } // end loadJsonDefs } // end UcumJsonDefs class exports.UcumJsonDefs = UcumJsonDefs; var ucumJsonDefs = new UcumJsonDefs(); exports.ucumJsonDefs = ucumJsonDefs; },{"../data/ucumDefs.min.json":89,"./jsonArrayPack.js":92,"./prefix.js":93,"./prefixTables.js":94,"./unit.js":100,"./unitTables.js":102}],98:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UcumLhcUtils = void 0; var _ucumJsonDefs = require("./ucumJsonDefs.js"); var intUtils_ = _interopRequireWildcard(require("./ucumInternalUtils.js")); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /** * This class provides a single point of access to the LHC UCUM utilities * * @author Lee Mericle * */ var Ucum = require('./config.js').Ucum; var UnitTables = require('./unitTables.js').UnitTables; var UnitString = require('./unitString.js').UnitString; /** * UCUM external utilities class */ class UcumLhcUtils { /** * Constructor. This loads the json prefix and unit definitions if * they haven't been loaded already and creates itself as a singleton object. * */ constructor() { if (UnitTables.getInstance().unitsCount() === 0) { // Load the prefix and unit objects _ucumJsonDefs.ucumJsonDefs.loadJsonDefs(); } // Get the UnitString parser that will be used with this instance // of the LHC Utilities this.uStrParser_ = UnitString.getInstance(); } // end constructor /** * This method calls the useHTMLInMessages method on the UnitString * object. It should be called by web applications that use * these utilities. * * @param use flag indicating whether or not to use the braces message; * defaults to true */ useHTMLInMessages(use) { if (use === undefined) use = true; this.uStrParser_.useHTMLInMessages(use); } /** * This method calls the useBraceMsgForEachString method on the UnitString * object. It should be called by web applications where unit * strings are validated individually (as opposed to validating a whole * file of unit strings). * * @param use flag indicating whether or not to use the braces message; * defaults to true */ useBraceMsgForEachString(use) { if (use === undefined) use = true; this.uStrParser_.useBraceMsgForEachString(use); } /** * This method validates a unit string. It first checks to see if the * string passed in is a unit code that is found in the unit codes table. * If it is not found it parses the string to see if it resolves to a * valid unit string. * * If a valid unit cannot be found, the string is tested for some common * errors, such as missing brackets or a missing multiplication operator. * If found, the error is reported in the messages array that is returned. * * If a valid unit cannot be found and an error cannot be discerned, this * may return, if requested, a list of suggested units in the messages * array that is returned. Suggestions are based on matching the expression * with unit names and synonyms. * * @param uStr the string to be validated * @param suggest a boolean to indicate whether or not suggestions are * requested for a string that cannot be resolved to a valid unit; * true indicates suggestions are wanted; false indicates they are not, * and is the default if the parameter is not specified; * @param valConv a string indicating if this validation request was initiated * by a validation task ('validate') or a conversion task ('convert'), * used only for the demo code, and the default is 'Validator' if the * parameter is not specified; * @returns an object with five properties: * 'status' will be 'valid' (the uStr is a valid UCUM code), 'invalid' * (the uStr is not a valid UCUM code, and substitutions or * suggestions may or may not be returned, depending on what was * requested and found); or 'error' (an input or programming error * occurred); * 'ucumCode' the valid ucum code, which may differ from what was passed * in (e.g., if 'Gauss' is passed in, this will contain 'G') OR null if * the string was flagged as invalid or an error occurred; * 'msg' is an array of one or more messages, if the string is invalid or * an error occurred, indicating the problem, or an explanation of a * substitution such as the substitution of 'G' for 'Gauss', or * an empty array if no messages were generated; * 'unit' which is null if no unit is found, or a hash for a unit found: * 'code' is the unit's ucum code (G in the above example; * 'name' is the unit's name (Gauss in the above example); and * 'guidance' is the unit's guidance/description data; and * 'suggestions' if suggestions were requested and found, this is an array * of one or more hash objects. Each hash contains three elements: * 'msg' which is a message indicating what part of the uStr input * parameter the suggestions are for; * 'invalidUnit' which is the unit expression the suggestions are * for; and * 'units' which is an array of data for each suggested unit found. * Each array will contain the unit code, the unit name and the * unit guidance (if any). * If no suggestions were requested and found, this property is not * returned. */ validateUnitString(uStr, suggest, valConv) { if (suggest === undefined) suggest = false; if (valConv === undefined) valConv = 'validate'; let resp = this.getSpecifiedUnit(uStr, valConv, suggest); let theUnit = resp['unit']; let retObj = {}; if (!theUnit) { retObj = { 'status': !resp['origString'] || resp['origString'] === null ? 'error' : 'invalid', 'ucumCode': null }; } else { retObj = { 'status': resp['origString'] === uStr ? 'valid' : 'invalid', 'ucumCode': resp['origString'], 'unit': { 'code': theUnit.csCode_, 'name': theUnit.name_, 'guidance': theUnit.guidance_ } }; } if (resp['suggestions']) { retObj['suggestions'] = resp['suggestions']; } retObj['msg'] = resp['retMsg']; return retObj; } // end validateUnitString /** * This method converts one unit to another * * @param fromUnitCode the unit code/expression/string of the unit to be converted * @param fromVal the number of "from" units to be converted to "to" units * @param toUnitCode the unit code/expression/string of the unit that the from * field is to be converted to * @param suggest a boolean to indicate whether or not suggestions are * requested for a string that cannot be resolved to a valid unit; * true indicates suggestions are wanted; false indicates they are not, * and is the default if the parameter is not specified; * @param molecularWeight the molecular weight of the substance in question * when a conversion is being requested from mass to moles and vice versa. * This is required when one of the units represents a value in moles. It is * ignored if neither unit includes a measurement in moles. * @returns a hash with six elements: * 'status' that will be: 'succeeded' if the conversion was successfully * calculated; 'failed' if the conversion could not be made, e.g., if * the units are not commensurable; or 'error' if an error occurred; * 'toVal' the numeric value indicating the conversion amount, or null * if the conversion failed (e.g., if the units are not commensurable); * 'msg' is an array message, if the string is invalid or an error occurred, * indicating the problem, or an explanation of a substitution such as * the substitution of 'G' for 'Gauss', or an empty array if no * messages were generated; * 'suggestions' if suggestions were requested and found, this is a hash * that contains at most two elements: * 'from' which, if the fromUnitCode input parameter or one or more of * its components could not be found, is an array one or more hash * objects. Each hash contains three elements: * 'msg' which is a message indicating what unit expression the * suggestions are for; * 'invalidUnit' which is the unit expression the suggestions * are for; and * 'units' which is an array of data for each suggested unit found. * Each array will contain the unit code, the unit name and the * unit guidance (if any). * If no suggestions were found for the fromUnitCode this element * will not be included. * 'to' which, if the "to" unit expression or one or more of its * components could not be found, is an array one or more hash objects. Each hash * contains three elements: * 'msg' which is a message indicating what toUnitCode input * parameter the suggestions are for; * 'invalidUnit' which is the unit expression the suggestions * are for; and * 'units' which is an array of data for each suggested unit found. * Each array will contain the unit code, the unit name and the * unit guidance (if any). * If no suggestions were found for the toUnitCode this element * will not be included. * No 'suggestions' element will be included in the returned hash * object if none were found, whether or not they were requested. * 'fromUnit' the unit object for the fromUnitCode passed in; returned * in case it's needed for additional data from the object; and * 'toUnit' the unit object for the toUnitCode passed in; returned * in case it's needed for additional data from the object. */ convertUnitTo(fromUnitCode, fromVal, toUnitCode, suggest, molecularWeight) { if (suggest === undefined) suggest = false; if (molecularWeight === undefined) molecularWeight = null; let returnObj = { 'status': 'failed', 'toVal': null, 'msg': [] }; if (fromUnitCode) { fromUnitCode = fromUnitCode.trim(); } if (!fromUnitCode || fromUnitCode == '') { returnObj['status'] = 'error'; returnObj['msg'].push('No "from" unit expression specified.'); } if (fromVal === null || isNaN(fromVal) || typeof fromVal !== 'number' && !intUtils_.isNumericString(fromVal)) { returnObj['status'] = 'error'; returnObj['msg'].push('No "from" value, or an invalid "from" value, ' + 'was specified.'); } if (toUnitCode) { toUnitCode = toUnitCode.trim(); } if (!toUnitCode || toUnitCode == '') { returnObj['status'] = 'error'; returnObj['msg'].push('No "to" unit expression specified.'); } if (returnObj['status'] !== 'error') { try { let fromUnit = null; let parseResp = this.getSpecifiedUnit(fromUnitCode, 'convert', suggest); fromUnit = parseResp['unit']; if (parseResp['retMsg']) returnObj['msg'] = returnObj['msg'].concat(parseResp['retMsg']); if (parseResp['suggestions']) { returnObj['suggestions'] = {}; returnObj['suggestions']['from'] = parseResp['suggestions']; } if (!fromUnit) { returnObj['msg'].push(`Unable to find a unit for ${fromUnitCode}, ` + `so no conversion could be performed.`); } let toUnit = null; parseResp = this.getSpecifiedUnit(toUnitCode, 'convert', suggest); toUnit = parseResp['unit']; if (parseResp['retMsg']) returnObj['msg'] = returnObj['msg'].concat(parseResp['retMsg']); if (parseResp['suggestions']) { if (!returnObj['suggestions']) returnObj['suggestions'] = {}; returnObj['suggestions']['to'] = parseResp['suggestions']; } if (!toUnit) { returnObj['msg'].push(`Unable to find a unit for ${toUnitCode}, ` + `so no conversion could be performed.`); } if (fromUnit && toUnit) { try { // if no molecular weight was specified perform a normal conversion if (!molecularWeight) { returnObj['toVal'] = toUnit.convertFrom(fromVal, fromUnit); } else { if (fromUnit.moleExp_ !== 0 && toUnit.moleExp_ !== 0) { throw new Error('A molecular weight was specified ' + 'but a mass <-> mole conversion cannot be executed for two ' + 'mole-based units. No conversion was attempted.'); } if (fromUnit.moleExp_ === 0 && toUnit.moleExp_ === 0) { throw new Error('A molecular weight was specified ' + 'but a mass <-> mole conversion cannot be executed when ' + 'neither unit is mole-based. No conversion was attempted.'); } if (!fromUnit.isMoleMassCommensurable(toUnit)) { throw new Error(`Sorry. ${fromUnitCode} cannot be ` + `converted to ${toUnitCode}.`); } // if the "from" unit is a mole-based unit, assume a mole to mass // request if (fromUnit.moleExp_ !== 0) { returnObj['toVal'] = fromUnit.convertMolToMass(fromVal, toUnit, molecularWeight); } // else the "to" unit must be the mole-based unit, so assume a // mass to mole request else { returnObj['toVal'] = fromUnit.convertMassToMol(fromVal, toUnit, molecularWeight); } } // end if a molecular weight was specified // if an error hasn't been thrown - either from convertFrom or here, // set the return object to show success returnObj['status'] = 'succeeded'; returnObj['fromUnit'] = fromUnit; returnObj['toUnit'] = toUnit; } catch (err) { returnObj['status'] = 'failed'; returnObj['msg'].push(err.message); } } // end if we have the from and to units } catch (err) { if (err.message == Ucum.needMoleWeightMsg_) returnObj['status'] = 'failed';else returnObj['status'] = 'error'; returnObj['msg'].push(err.message); } } return returnObj; } // end convertUnitTo /** * This method accepts a term and looks for units that include it as * a synonym - or that include the term in its name. * * @param theSyn the term to search for * @returns a hash with up to three elements: * 'status' contains the status of the request, which can be 'error', * 'failed' or succeeded'; * 'msg' which contains a message for an error or if no units were found; and * 'units' which is an array that contains one hash for each unit found: * 'code' is the unit's csCode_ * 'name' is the unit's name_ * 'guidance' is the unit's guidance_ * */ checkSynonyms(theSyn) { let retObj = {}; if (theSyn === undefined || theSyn === null) { retObj['status'] = 'error'; retObj['msg'] = 'No term specified for synonym search.'; } else { retObj = intUtils_.getSynonyms(theSyn); } // end if a search synonym was supplied return retObj; } // end checkSynonyms /** * This method parses a unit string to get (or try to get) the unit * represented by the string. It returns an error message if no string was specified * or if any errors were encountered trying to get the unit. * * @param uName the expression/string representing the unit * @param valConv indicates what type of request this is for - a request to * validate (pass in 'validate') or a request to convert (pass in 'convert') * @param suggest a boolean to indicate whether or not suggestions are * requested for a string that cannot be resolved to a valid unit; * true indicates suggestions are wanted; false indicates they are not, * and is the default if the parameter is not specified; * @returns a hash containing: * 'unit' the unit object (or null if there were problems creating the * unit); * 'origString' the possibly updated unit string passed in; * 'retMsg' an array of user messages (informational, error or warning) if * any were generated (IF any were generated, otherwise will be an * empty array); and * 'suggestions' is an array of 1 or more hash objects. Each hash * contains three elements: * 'msg' which is a message indicating what unit expression the * suggestions are for; * 'invalidUnit' which is the unit expression the suggestions are * for; and * 'units' which is an array of data for each suggested unit found. * Each array will contain the unit code, the unit name and the * unit guidance (if any). * The return hash will not contain a suggestions array if a valid unit * was found or if suggestions were not requested and found. */ getSpecifiedUnit(uName, valConv, suggest) { if (suggest === undefined) suggest = false; let retObj = {}; retObj['retMsg'] = []; if (!uName) { retObj['retMsg'].push('No unit string specified.'); } else { let utab = UnitTables.getInstance(); uName = uName.trim(); // go ahead and just try using the name as the code. This may or may not // work, but if it does, it cuts out a lot of parsing. let theUnit = utab.getUnitByCode(uName); // If we found it, set the returned unit string to what was passed in; // otherwise try parsing as a unit string if (theUnit) { retObj['unit'] = theUnit; retObj['origString'] = uName; } else { try { let resp = this.uStrParser_.parseString(uName, valConv, suggest); retObj['unit'] = resp[0]; retObj['origString'] = resp[1]; if (resp[2]) retObj['retMsg'] = resp[2]; retObj['suggestions'] = resp[3]; } catch (err) { console.log(`Unit requested for unit string ${uName}.` + 'request unsuccessful; error thrown = ' + err.message); retObj['retMsg'].unshift(`${uName} is not a valid unit. ` + `${err.message}`); } } // end if the unit was not found as a unit name } // end if a unit expression was specified return retObj; } // end getSpecifiedUnit /** * This method retrieves a list of units commensurable, i.e., that can be * converted from and to, a specified unit. Returns an error if the "from" * unit cannot be found. * * @param fromName the name/unit string of the "from" unit * @returns an array containing two elements; * first element is the list of commensurable units if any were found * second element is an error message if the "from" unit is not found */ commensurablesList(fromName) { let retMsg = []; let commUnits = null; let parseResp = this.getSpecifiedUnit(fromName, 'validate', false); let fromUnit = parseResp['unit']; if (parseResp['retMsg'].length > 0) retMsg = parseResp['retMsg']; if (!fromUnit) { retMsg.push(`Could not find unit ${fromName}.`); } else { let dimVec = null; let fromDim = fromUnit.getProperty('dim_'); if (!fromDim) { retMsg.push('No commensurable units were found for ' + fromName); } else { try { dimVec = fromDim.getProperty('dimVec_'); } catch (err) { retMsg.push(err.message); if (err.message === "Dimension does not have requested property(dimVec_)") dimVec = null; } if (dimVec) { let utab = UnitTables.getInstance(); commUnits = utab.getUnitsByDimension(dimVec); } } // end if the from unit has a dimension vector } // end if we found a "from" unit return [commUnits, retMsg]; } // end commensurablesList } // end UcumLhcUtils class /** * This function exists ONLY until the original UcumLhcUtils constructor * is called for the first time. It's defined here in case getInstance * is called before the constructor. This calls the constructor. * * The constructor redefines the getInstance function to return the * singleton UcumLhcUtils object. This is based on the UnitTables singleton * implementation; see more detail in the UnitTables constructor description. * * NO LONGER TRUE - not implemented as a singleton. This method retained to * avoid problems with calls to it that exist throughout the code. * * @return the (formerly singleton) UcumLhcUtils object. */ exports.UcumLhcUtils = UcumLhcUtils; UcumLhcUtils.getInstance = function () { return new UcumLhcUtils(); }; },{"./config.js":90,"./ucumInternalUtils.js":96,"./ucumJsonDefs.js":97,"./unitString.js":101,"./unitTables.js":102}],99:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UnitTables = exports.UcumLhcUtils = exports.Ucum = void 0; /** * This exports definitions for ucum classes that need references to them * available to the demo code. The actual code will be in the ucumPkg * library found in the dist directory. This file provides the hooks to * those classes within the library. */ var Ucum = require("./config.js").Ucum; exports.Ucum = Ucum; var UcumLhcUtils = require("./ucumLhcUtils.js").UcumLhcUtils; exports.UcumLhcUtils = UcumLhcUtils; var UnitTables = require("./unitTables.js").UnitTables; exports.UnitTables = UnitTables; },{"./config.js":90,"./ucumLhcUtils.js":98,"./unitTables.js":102}],100:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Unit = void 0; var _ucumFunctions = _interopRequireDefault(require("./ucumFunctions.js")); var intUtils_ = _interopRequireWildcard(require("./ucumInternalUtils.js")); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * This class represents one unit of measure. It includes * functions to cover constructor, accessor, and assignment tasks as * well as operators to calculate multiplication, division and raising * to a power. * * @author Lee Mericle, based on java version by Gunther Schadow * */ var Ucum = require('./config.js').Ucum; var Dimension = require('./dimension.js').Dimension; var UnitTables; var isInteger = require("is-integer"); class Unit { /** * Constructor. * * @param attrs an optional parameter that may be: * a string, which is parsed by the unit parser, which creates * the unit from the parsed string; or * a hash containing all or some values for the attributes of * the unit, where the keys are the attribute names, without a * trailing underscore, e.g., name instead of name_; or * null, in which case an empty hash is created and used to * set the values forthe attributes. * If a hash (empty or not) is used, attributes for which no value * is specified are assigned a default value. * */ constructor(attrs = {}) { // Process the attrs hash passed in, which may be empty. // Create and assign values (from the attrs hash or defaults) to all // attributes. From Class Declarations in Understanding ECMAScript, // https://leanpub.com/understandinges6/read/#leanpub-auto-class-declarations, // "Own properties, properties that occur on the instance rather than the // prototype, can only be created inside of a class constructor or method. // It's recommended to create all possible own properties inside of the // constructor function so there's a single place that's responsible for // all of them." /* * Flag indicating whether or not this is a base unit */ this.isBase_ = attrs['isBase_'] || false; /* * The unit name, e.g., meter */ this.name_ = attrs['name_'] || ''; /* * The unit's case-sensitive code, e.g., m */ this.csCode_ = attrs['csCode_'] || ''; /* * The unit's case-insensitive code, e.g., M */ this.ciCode_ = attrs['ciCode_'] || ''; /* * The unit's property, e.g., length */ this.property_ = attrs['property_'] || ''; /* * The magnitude of the unit, e.g., 3600/3937 for a yard, * where a yard - 3600/3973 * m(eter). The Dimension * property specifies the meter - which is the unit on which * a yard is based, and this magnitude specifies how to figure * this unit based on the base unit. */ this.magnitude_ = attrs['magnitude_'] || 1; /* * The Dimension object of the unit */ if (attrs['dim_'] === undefined || attrs['dim_'] === null) { this.dim_ = new Dimension(); } // When the unit data stored in json format is reloaded, the dimension data // is recognized as a a hash, not as a Dimension object. else if (attrs['dim_']['dimVec_'] !== undefined) { this.dim_ = new Dimension(attrs['dim_']['dimVec_']); } else if (attrs['dim_'] instanceof Dimension) { this.dim_ = attrs['dim_']; } else if (attrs['dim_'] instanceof Array || isInteger(attrs['dim_'])) { this.dim_ = new Dimension(attrs['dim_']); } else { this.dim_ = new Dimension(); } /* * The print symbol of the unit, e.g., m */ this.printSymbol_ = attrs['printSymbol_'] || null; /* * The class of the unit, where given, e.g., dimless */ this.class_ = attrs['class_'] || null; /* * A flag indicating whether or not the unit is metric */ this.isMetric_ = attrs['isMetric_'] || false; /* * The "variable" - which I think is used only for base units * The symbol for the variable as used in equations, e.g., s for distance */ this.variable_ = attrs['variable_'] || null; // comes from 'dim' in XML /* * The conversion function */ this.cnv_ = attrs['cnv_'] || null; /* * The conversion prefix */ this.cnvPfx_ = attrs['cnvPfx_'] || 1; /* * Flag indicating whether or not this is a "special" unit, i.e., is * constructed using a function specific to the measurement, e.g., * fahrenheit and celsius */ this.isSpecial_ = attrs['isSpecial_'] || false; /* * Flag indicating whether or not this is an arbitrary unit */ this.isArbitrary_ = attrs['isArbitrary_'] || false; /* * Integer indicating what level of exponent applies to a mole-based portion * of the unit. So, for the unit "mol", this will be 1. For "mol2" this * will be 2. For "1/mol" this will be -1. Any unit that does not include * a mole will have a 0 in this field. This is used to determine * commensurability for mole<->mass conversions. */ this.moleExp_ = attrs['moleExp_'] || 0; /* * Added when added LOINC list of units * synonyms are used by the autocompleter to enhance lookup capabilities * while source says where the unit first shows up. Current sources are * UCUM - which are units from the unitsofmeasure.org list and LOINC - * which are units from the LOINC data. */ this.synonyms_ = attrs['synonyms_'] || null; this.source_ = attrs['source_'] || null; this.loincProperty_ = attrs['loincProperty_'] || null; this.category_ = attrs['category_'] || null; this.guidance_ = attrs['guidance_'] || null; /* * Used to compute dimension; storing for now until I complete * unit definition parsing */ /* * Case sensitive (cs) and case insensitive (ci) base unit strings, * includes exponent and prefix if applicable - specified in * nnn -- the unit part -- * in the ucum-essence.xml file, and may be specified by a user * when requesting conversion or validation of a unit string. The * magnitude (base factor) is used with this to determine the new unit. * For example, a Newton (unit code N) is created from the string * kg.m/s2, and the value of 1 (base factor defined below). An hour * (unit code h) is created from the unit min (minute) with a value * of 60. */ this.csUnitString_ = attrs['csUnitString_'] || null; this.ciUnitString_ = attrs['ciUnitString_'] || null; /* * String and numeric versions of factor applied to unit specified in * nnn -- the value part */ this.baseFactorStr_ = attrs['baseFactorStr_'] || null; this.baseFactor_ = attrs['baseFactor_'] || null; /* * Flag used to indicate units where the definition process failed * when parsing units from the official units definitions file * (currently using the ucum-essence.xml file). We keep these * so that we can use them to at least validate them as valid * units, but we don't try to convert them. This is temporary * and only to account for instances where the code does not * take into account various special cases in the xml file. * * This is NOT used when trying to validate a unit string * submitted during a conversion or validation attempt. */ this.defError_ = attrs['defError_'] || false; } // end constructor /** * Assign the unity (= dimensionless unit 1) to this unit. * * @return this unit */ assignUnity() { this.name_ = ""; this.magnitude_ = 1; if (!this.dim_) this.dim_ = new Dimension(); this.dim_.assignZero(); this.cnv_ = null; this.cnvPfx_ = 1; return this; } // end assignUnity /** * This assigns one or more values, as provided in the hash passed in, * to this unit. * * @param vals hash of values to be assigned to the attributes * specified by the key(s), which should be the attribute * name without the trailing underscore, e.g., name instead * of name_. * @return nothing */ assignVals(vals) { for (let key in vals) { let uKey = !key.charAt(key.length - 1) === '_' ? key + '_' : key; if (this.hasOwnProperty(uKey)) this[uKey] = vals[key];else throw new Error(`Parameter error; ${key} is not a property of a Unit`); } } // end assignVals /** * This creates a clone of this unit. * * @return the clone */ clone() { let retUnit = new Unit(); Object.getOwnPropertyNames(this).forEach(val => { if (val === 'dim_') { if (this['dim_']) retUnit['dim_'] = this['dim_'].clone();else retUnit['dim_'] = null; } else retUnit[val] = this[val]; }); return retUnit; } // end clone /** * This assigns all properties of a unit passed to it to this unit. * * @param unit2 the unit whose properties are to be assigned to this one. * @return nothing; this unit is updated */ assign(unit2) { Object.getOwnPropertyNames(unit2).forEach(val => { if (val === 'dim_') { if (unit2['dim_']) this['dim_'] = unit2['dim_'].clone();else this['dim_'] = null; } else { this[val] = unit2[val]; } }); } // end assign /** * This determines whether or not object properties of the unit * passed in are equal to the corresponding properties in this unit. * The following properties are the only ones checked: * magnitude_, dim_, cnv_ and cnvPfx_ * * @param unit2 the unit whose properties are to be checked. * @return boolean indicating whether or not they match */ equals(unit2) { return this.magnitude_ === unit2.magnitude_ && this.cnv_ === unit2.cnv_ && this.cnvPfx_ === unit2.cnvPfx_ && (this.dim_ === null && unit2.dim_ === null || this.dim_.equals(unit2.dim_)); } // end equals /** * This method compares every attribute of two objects to determine * if they all match. * * @param unit2 the unit that is to be compared to this unit * @return boolean indicating whether or not every attribute matches */ fullEquals(unit2) { let thisAttr = Object.keys(this).sort(); let u2Attr = Object.keys(unit2).sort(); let keyLen = thisAttr.length; let match = keyLen === u2Attr.length; // check each attribute. Dimension objects have to checked using // the equals function of the Dimension class. for (let k = 0; k < keyLen && match; k++) { if (thisAttr[k] === u2Attr[k]) { if (thisAttr[k] === 'dim_') match = this.dim_.equals(unit2.dim_);else match = this[thisAttr[k]] === unit2[thisAttr[k]]; } else match = false; } // end do for each key and attribute return match; } // end of fullEquals /** * This returns the value of the property named by the parameter * passed in. * * @param propertyName name of the property to be returned, with * or without the trailing underscore. * @return the requested property, if found for this unit * @throws an error if the property is not found for this unit */ getProperty(propertyName) { let uProp = propertyName.charAt(propertyName.length - 1) === '_' ? propertyName : propertyName + '_'; return this[uProp]; } // end getProperty /** * Takes a measurement consisting of a number of units and a unit and returns * the equivalent number of this unit. So, 15 mL would translate * to 1 tablespoon if this object is a tablespoon. * * Note that the number returned may not be what is normally expected. * For example, converting 10 Celsius units to Fahrenheit would "normally" * return a value of 50. But in this case you'll get back something like * 49.99999999999994. * * If either unit is an arbitrary unit an exception is raised. * * @param num the magnitude for the unit to be translated (e.g. 15 for 15 mL) * @param fromUnit the unit to be translated to one of this type (e.g. a mL unit) * * @return the number of converted units (e.g. 1 for 1 tablespoon) * @throws an error if the dimension of the fromUnit differs from this unit's * dimension */ convertFrom(num, fromUnit) { let newNum = 0.0; if (this.isArbitrary_) throw new Error(`Attempt to convert arbitrary unit ${this.name_}`); if (fromUnit.isArbitrary_) throw new Error(`Attempt to convert to arbitrary unit ${fromUnit.name_}`); // reject request if both units have dimensions that are not equal if (fromUnit.dim_ && this.dim_ && !fromUnit.dim_.equals(this.dim_)) { // check first to see if a mole<->mass conversion is appropriate if (this.isMoleMassCommensurable(fromUnit)) { throw new Error(Ucum.needMoleWeightMsg_); } else { throw new Error(`Sorry. ${fromUnit.csCode_} cannot be converted ` + `to ${this.csCode_}.`); } } // reject request if there is a "from" dimension but no "to" dimension if (fromUnit.dim_ && (!this.dim_ || this.dim_.isNull())) { throw new Error(`Sorry. ${fromUnit.csCode_} cannot be converted ` + `to ${this.csCode_}.`); } // reject request if there is a "to" dimension but no "from" dimension if (this.dim_ && (!fromUnit.dim_ || fromUnit.dim_.isNull())) { throw new Error(`Sorry. ${fromUnit.csCode_} cannot be converted ` + `to ${this.csCode_}.`); } let fromCnv = fromUnit.cnv_; let fromMag = fromUnit.magnitude_; // If the same conversion function is specified for both units, which // includes neither unit having a conversion function, multiply the // "from" unit's magnitude by the number passed in and then divide // that result by this unit's magnitude. Do this for units with // and without dimension vectors. PROBLEM with 2 non-commensurable // units with no dimension vector or function, e.g., byte to mol if (fromCnv === this.cnv_) { newNum = num * fromMag / this.magnitude_; } // else use a function to get the number to be returned else { let x = 0.0; if (fromCnv != null) { // turn num * fromUnit.magnitude into its ratio scale equivalent, // e.g., convert Celsius to Kelvin let fromFunc = _ucumFunctions.default.forName(fromCnv); x = fromFunc.cnvFrom(num * fromUnit.cnvPfx_) * fromMag; //x = fromFunc.cnvFrom(num * fromMag) * fromUnit.cnvPfx_; } else { x = num * fromMag; } if (this.cnv_ != null) { // turn mag * origUnit on ratio scale into a non-ratio unit, // e.g. convert Kelvin to Fahrenheit let toFunc = _ucumFunctions.default.forName(this.cnv_); newNum = toFunc.cnvTo(x / this.magnitude_) / this.cnvPfx_; } else { newNum = x / this.magnitude_; } } // end if either unit has a conversion function return newNum; } // end convertFrom /** * Takes a number and a target unit and returns the number for a measurement * of this unit that corresponds to the number of the target unit passed in. * So, 1 tablespoon (where this unit represents a tablespoon) would translate * to 15 mL. * * See the note on convertFrom about return values. * * @param mag the magnitude for this unit (e.g. 1 for 1 tablespoon) * @param toUnit the unit to which this unit is to be translated * (e.g. an mL unit) * * @return the converted number value (e.g. 15 mL) * @throws an error if the dimension of the toUnit differs from this unit's * dimension */ convertTo(num, toUnit) { return toUnit.convertFrom(num, this); } // end convertTo /** * Takes a given number of this unit returns the number of this unit * if it is converted into a coherent unit. Does not change this unit. * * If this is a coherent unit already, just gives back the number * passed in. * * @param num the number for the coherent version of this unit * @return the number for the coherent version of this unit */ convertCoherent(num) { // convert mag' * u' into canonical number * u on ratio scale if (this.cnv_ !== null) num = this.cnv_.f_from(num / this.cnvPfx_) * this.magnitude_; return num; } // end convertCoherent /** * Mutates this unit into a coherent unit and converts a given number of * units to the appropriate value for this unit as a coherent unit * * @param num the number for this unit before conversion * @return the number of this unit after conversion * @throws an error if the dimensions differ */ mutateCoherent(num) { // convert mu' * u' into canonical mu * u on ratio scale num = this.convertCoherent(num); // mutate to coherent unit this.magnitude_ = 1; this.cnv_ = null; this.cnvPfx_ = 1; this.name_ = ""; // build a name as a term of coherent base units // This is probably ALL WRONG and a HORRIBLE MISTAKE // but until we figure out what the heck the name being // built here really is, it will have to stay. for (let i = 0, max = Dimension.getMax(); i < max; i++) { let elem = this.dim_.getElementAt(i); let tabs = this._getUnitTables(); let uA = tabs.getUnitsByDimension(new Dimension(i)); if (uA == null) throw new Error(`Can't find base unit for dimension ${i}`); this.name_ = uA.name + elem; } return num; } // end mutateCoherent /** * Calculates the number of units that would result from converting a unit * expressed in mass/grams to a unit expressed in moles. The "this" unit is * the unit expressed in some form of mass (g, mg, mmg, kg, whatever) and the * target or "to" unit - the molUnit parameter - is a unit expressed in moles * - mol, umol, mmol, etc. The unit expressions surrounding the moles and * mass must be convertible. No validation of this requirement is performed. * * @param amt the quantity of this unit to be converted * @param molUnit the target/to unit for which the converted # is wanted * @param molecularWeight the molecular weight of the substance for which the * conversion is being made * @return the equivalent amount in molUnit */ convertMassToMol(amt, molUnit, molecularWeight) { // The prefix values that have been applied to this unit, which is the mass // (grams) unit, are reflected in the magnitude. So the number of moles // represented by this unit equals the number of grams -- amount * magnitude // divided by the molecular Weight let molAmt = this.magnitude_ * amt / molecularWeight; // The molUnit's basic magnitude, before prefixes are applied, // is avogadro's number, get that and divide it out of the current magnitude. let tabs = this._getUnitTables(); let avoNum = tabs.getUnitByCode('mol').magnitude_; let molesFactor = molUnit.magnitude_ / avoNum; // return the molAmt divided by the molesFactor as the number of moles // for the molUnit return molAmt / molesFactor; } /** * Calculates the number of units that would result from converting a unit * expressed in moles to a unit expressed in mass (grams). The "this" unit * is the unit expressed in some form of moles, e.g., mol, umol, mmol, etc., * and the target or "to" unit is a unit expressed in some form of mass, e.g., * g, mg, mmg, kg, etc. Any unit expressions surrounding the moles and mass * must be convertible. No validation of this requirement is performed. * * @param amt the quantity of this unit to be converted * @param massUnit the target/to unit for which the converted # is wanted * @param molecularWeight the molecular weight of the substance for which the * conversion is being made * @return the equivalent amount in massUnit */ convertMolToMass(amt, massUnit, molecularWeight) { // A simple mole unit has a magnitude of avogadro's number. Get that // number now (since not everyone agrees on what it is, and what is // being used in this system might change). let tabs = this._getUnitTables(); let avoNum = tabs.getUnitByCode('mol').magnitude_; // Determine what prefix values (mg or mg/dL, etc.) have been applied to // this unit by dividing the simple mole unit magnitude out of the // current mole unit magnitude. let molesFactor = this.magnitude_ / avoNum; // The number of grams (mass) is equal to the number of moles (amt) // times the molecular weight. We also multiply that by the prefix values // applied to the current unit (molesFactor) to get the grams for this // particular unit. let massAmt = molesFactor * amt * molecularWeight; // Finally, we return the mass amount/grams for this particular unit // divided by any effects of prefixes applied to the "to" unit, which // is assumed to be some form of a gram unit return massAmt / massUnit.magnitude_; } /** * Mutates this unit into a unit on a ratio scale and converts a specified * number of units to an appropriate value for this converted unit * * @param num the number of this unit before it's converted * @return the magnitude of this unit after it's converted * @throw an error if the dimensions differ */ mutateRatio(num) { if (this.cnv_ == null) return this.mutateCoherent(num);else return num; } // end mutateRatio /** * Multiplies this unit with a scalar. Special meaning for * special units so that (0.1*B) is 1 dB. * * This function DOES NOT modify this unit. * * @param s the value by which this unit is to be multiplied * @return a copy this unit multiplied by s * */ multiplyThis(s) { let retUnit = this.clone(); if (retUnit.cnv_ != null) retUnit.cnvPfx_ *= s;else retUnit.magnitude_ *= s; let mulVal = s.toString(); retUnit.name_ = this._concatStrs(mulVal, '*', this.name_, '[', ']'); retUnit.csCode_ = this._concatStrs(mulVal, '.', this.csCode_, '(', ')'); retUnit.ciCode_ = this._concatStrs(mulVal, '.', this.ciCode_, '(', ')'); retUnit.printSymbol_ = this._concatStrs(mulVal, '.', this.printSymbol_, '(', ')'); return retUnit; } // end multiplyThis /** * Multiplies this unit with another unit. If one of the * units is a non-ratio unit the other must be dimensionless or * else an exception is thrown. * * This function does NOT modify this unit * @param unit2 the unit to be multiplied with this one * @return this unit after it is multiplied * @throws an error if one of the units is not on a ratio-scale * and the other is not dimensionless. */ multiplyThese(unit2) { var retUnit = this.clone(); if (retUnit.cnv_ != null) { if (unit2.cnv_ == null && (!unit2.dim_ || unit2.dim_.isZero())) retUnit.cnvPfx_ *= unit2.magnitude_;else throw new Error(`Attempt to multiply non-ratio unit ${retUnit.name_} ` + 'failed.'); } // end if this unit has a conversion function else if (unit2.cnv_ != null) { if (!retUnit.dim_ || retUnit.dim_.isZero()) { retUnit.cnvPfx_ = unit2.cnvPfx_ * retUnit.magnitude_; retUnit.cnv_ = unit2.cnv_; } else throw new Error(`Attempt to multiply non-ratio unit ${unit2.name_}`); } // end if unit2 has a conversion function // else neither unit has a conversion function else { retUnit.magnitude_ *= unit2.magnitude_; } // end if unit2 does not have a conversion function // If this.dim_ isn't there, clone the dimension in unit2 - if dimVec_ // is a dimension in unit2.dim_; else just transfer it to this dimension if (!retUnit.dim_ || retUnit.dim_ && !retUnit.dim_.dimVec_) { if (unit2.dim_) retUnit.dim_ = unit2.dim_.clone();else retUnit.dim_ = unit2.dim_; } // Else this.dim_ is there. If there is a dimension for unit2, // add it to this one. else if (unit2.dim_ && unit2.dim_ instanceof Dimension) { retUnit.dim_.add(unit2.dim_); } // Concatenate the unit info (name, code, etc) for all cases // where the multiplication was performed (an error wasn't thrown) retUnit.name_ = this._concatStrs(retUnit.name_, '*', unit2.name_, '[', ']'); retUnit.csCode_ = this._concatStrs(retUnit.csCode_, '.', unit2.csCode_, '(', ')'); if (retUnit.ciCode_ && unit2.ciCode_) retUnit.ciCode_ = this._concatStrs(retUnit.ciCode_, '.', unit2.ciCode_, '(', ')');else if (unit2.ciCode_) retUnit.ciCode_ = unit2.ciCode_; retUnit.guidance_ = ''; if (retUnit.printSymbol_ && unit2.printSymbol_) retUnit.printSymbol_ = this._concatStrs(retUnit.printSymbol_, '.', unit2.printSymbol_, '(', ')');else if (unit2.printSymbol_) retUnit.printSymbol_ = unit2.printSymbol_; // Update the mole exponent count by adding the count for unit2 to the // count for this unit. retUnit.moleExp_ = retUnit.moleExp_ + unit2.moleExp_; // A unit that has the arbitrary attribute taints any unit created from it // via an arithmetic operation. Taint accordingly // if (!retUnit.isMole_) // retUnit.isMole_ = unit2.isMole_ ; if (!retUnit.isArbitrary_) retUnit.isArbitrary_ = unit2.isArbitrary_; return retUnit; } // end multiplyThese /** * Divides this unit by another unit. If this unit is not on a ratio * scale an exception is raised. Mutating to a ratio scale unit * is not possible for a unit, only for a measurement. * * This unit is NOT modified by this function. * @param unit2 the unit by which to divide this one * @return this unit after it is divided by unit2 * @throws an error if either of the units is not on a ratio scale. * */ divide(unit2) { var retUnit = this.clone(); if (retUnit.cnv_ != null) throw new Error(`Attempt to divide non-ratio unit ${retUnit.name_}`); if (unit2.cnv_ != null) throw new Error(`Attempt to divide by non-ratio unit ${unit2.name_}`); if (retUnit.name_ && unit2.name_) retUnit.name_ = this._concatStrs(retUnit.name_, '/', unit2.name_, '[', ']');else if (unit2.name_) retUnit.name_ = unit2.invertString(unit2.name_); retUnit.csCode_ = this._concatStrs(retUnit.csCode_, '/', unit2.csCode_, '(', ')'); if (retUnit.ciCode_ && unit2.ciCode_) retUnit.ciCode_ = this._concatStrs(retUnit.ciCode_, '/', unit2.ciCode_, '(', ')');else if (unit2.ciCode_) retUnit.ciCode_ = unit2.invertString(unit2.ciCode_); retUnit.guidance_ = ''; retUnit.magnitude_ /= unit2.magnitude_; if (retUnit.printSymbol_ && unit2.printSymbol_) retUnit.printSymbol_ = this._concatStrs(retUnit.printSymbol_, '/', unit2.printSymbol_, '(', ')');else if (unit2.printSymbol_) retUnit.printSymbol_ = unit2.invertString(unit2.printSymbol_); // Continue if unit2 has a dimension object. // If this object has a dimension object, subtract unit2's dim_ object from // this one. The sub method will take care of cases where the dimVec_ arrays // are missing on one or both dim_ objects. if (unit2.dim_) { if (retUnit.dim_) { if (retUnit.dim_.isNull()) retUnit.dim_.assignZero(); retUnit.dim_ = retUnit.dim_.sub(unit2.dim_); } // end if this.dim_ exists // Else if this dim_ object is missing, clone unit2's dim_ object // and give the inverted clone to this unit. else retUnit.dim_ = unit2.dim_.clone().minus(); } // end if unit2 has a dimension object // Update the mole exponent count by subtracting the count for unit2 from // the // count for this unit. retUnit.moleExp_ = retUnit.moleExp_ - unit2.moleExp_; // A unit that has the arbitrary attribute taints any unit created from // it via an arithmetic operation. Taint accordingly // if (!retUnit.isMole_) // retUnit.isMole_ = unit2.isMole_ ; if (!retUnit.isArbitrary_) retUnit.isArbitrary_ = unit2.isArbitrary_; return retUnit; } // end divide /** * Invert this unit with respect to multiplication. If this unit is not * on a ratio scale an exception is thrown. Mutating to a ratio scale unit * is not possible for a unit, only for a measurement (the magnitude and * dimension). * * This unit is modified by this function. * @return this unit after being inverted * @throws and error if this unit is not on a ratio scale */ invert() { if (this.cnv_ != null) throw new Error(`Attempt to invert a non-ratio unit - ${this.name_}`); this.name_ = this.invertString(this.name_); this.magnitude_ = 1 / this.magnitude_; this.dim_.minus(); return this; } // end invert /** * Inverts a string, where the string is assumed to be a code or a name * of a division operation where the string is the divisor and the dividend * is blank. * * @param the string to be inverted * @return the inverted string */ invertString(theString) { if (theString.length > 0) { let stringRep = theString.replace('/', "!").replace('.', '/').replace("!", '.'); switch (stringRep.charAt(0)) { case '.': theString = stringRep.substr(1); break; case '/': theString = stringRep; break; default: theString = "/" + stringRep; } } return theString; } // end invertString /** * This function handles concatenation of two strings and an operator. * It's called to build unit data, e.g., unit name, unit code, etc., from * two different units, joined by the specified operator. * * @param str1 the first string to appear in the result * @param operator the operator ('*', '.' or '/') to appear between the strings * @param str2 the second string to appear in the result * @param startChar the starting character to be used, when needed, to * enclose a string * @param endChar the ending character to be used, when needed, to enclose * a string * @returns the built string */ _concatStrs(str1, operator, str2, startChar, endChar) { return this._buildOneString(str1, startChar, endChar) + operator + this._buildOneString(str2, startChar, endChar); } /** * This function handles creation of one string to be included in a * concatenated string. Basically it checks to see if the string * needs to be enclosed either in parentheses or square brackets. * * The string is enclosed if it is not a number, does not start with * a parenthesis or square bracket, and includes a period, and asterisk, * a slash or a blank space. * * @param str the string * @param startChar starting enclosing character * @param endChar ending enclosing character * @returns the string */ _buildOneString(str, startChar, endChar) { let ret = ''; if (intUtils_.isNumericString(str)) { ret = str; } else { if (str.charAt(0) === '(' || str.charAt(0) === '[') { ret = str; } else if (/[./* ]/.test(str)) { ret = startChar + str + endChar; } else { ret = str; } } return ret; } /** * Raises the unit to a power. For example * kg.m/s2 raised to the -2 power would be kg-2.m-2/s-4 * * If this unit is not on a ratio scale an error is thrown. Mutating * to a ratio scale unit is not possible for a unit, only for a * measurement (magnitude and dimension). * * This is based on the pow method in Gunter Schadow's java version, * although it uses javascript capabilities to simplify the processing. * * This unit is modified by this function * * @param p the power to with this unit is to be raise * @return this unit after it is raised * @throws an error if this unit is not on a ratio scale. */ power(p) { if (this.cnv_ != null) throw new Error(`Attempt to raise a non-ratio unit, ${this.name_}, ` + 'to a power.'); //this.name_ = UnitString.pow(this.name_, p); // the above line is replaced with the code below, as the pow method // never actually existing in the UnitString class. (Tried to use // Schadow java code but this way ended up being a lot easier). let uStr = this.csCode_; let uArray = uStr.match(/([./]|[^./]+)/g); let arLen = uArray.length; for (let i = 0; i < arLen; i++) { let un = uArray[i]; if (un !== '/' && un !== '.') { let nun = parseInt(un); if (isInteger(nun)) uArray[i] = Math.pow(nun, p).toString();else { let uLen = un.length; for (let u = uLen - 1; u >= 0; u--) { let uChar = parseInt(un[u]); if (!isInteger(uChar)) { if (un[u] === '-' || un[u] === '+') { u--; } if (u < uLen - 1) { let exp = parseInt(un.substr(u)); exp = Math.pow(exp, p); uArray[i] = un.substr(0, u) + exp.toString(); u = -1; } else { uArray[i] += p.toString(); u = -1; } // end if there are/aren't some numbers at the end u = -1; } // end if this character is not a number } // end searching backwards for start of exponent } // end if this element is not a number } // end if the current element is not an operator } // end do for each element of the units array // reassemble the updated units array to a string this.csCode_ = uArray.join(''); this.magnitude_ = Math.pow(this.magnitude_, p); if (this.dim_) { this.dim_.mul(p); } return this; } // end power /* * This function tests this unit against the unit passed in to see if the * two are mole to mass commensurable. It assumes that one of the units * is a mole-based unit and the other is a mass-based unit. It also assumes * that the mole-based unit has a single mole unit in the numerator and that * the mass-based unit has a single mass unit in the numerator. It does NOT * check to validate those assumptions. * * The check is made by setting the dimension vector element corresponding * to the base mass unit (gram) in the mole unit, and then comparing the * two dimension vectors. If they match, the units are commensurable. * Otherwise they are not. * * @param unit2 the unit to be compared to this one * @returns boolean indicating commensurability */ isMoleMassCommensurable(unit2) { let tabs = this._getUnitTables(); let d = tabs.getMassDimensionIndex(); let commensurable = false; if (this.moleExp_ === 1 && unit2.moleExp_ === 0) { let testDim = this.dim_.clone(); let curVal = testDim.getElementAt(d); testDim.setElementAt(d, curVal + this.moleExp_); commensurable = testDim.equals(unit2.dim_); } else if (unit2.moleExp_ === 1 && this.moleExp_ === 0) { let testDim = unit2.dim_.clone(); let curVal = testDim.getElementAt(d); testDim.setElementAt(d, curVal + unit2.moleExp_); commensurable = testDim.equals(this.dim_); } return commensurable; } /** * This returns the UnitTables singleton object. Including the require * statement included here causes a circular dependency condition that * resulted in the UnitTables object not being defined for the Unit object. * sigh. Thanks, Paul, for figuring this out. * * @private */ _getUnitTables() { if (!UnitTables) UnitTables = require('./unitTables.js').UnitTables; return UnitTables.getInstance(); } } // end Unit class exports.Unit = Unit; },{"./config.js":90,"./dimension.js":91,"./ucumFunctions.js":95,"./ucumInternalUtils.js":96,"./unitTables.js":102,"is-integer":181}],101:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UnitString = void 0; var intUtils_ = _interopRequireWildcard(require("./ucumInternalUtils.js")); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /** * This class handles the parsing of a unit string into a unit object */ var Ucum = require('./config.js').Ucum; var Unit = require('./unit.js').Unit; var UnitTables = require('./unitTables.js').UnitTables; var PrefixTables = require('./prefixTables.js').PrefixTables; class UnitString { /** * Constructor */ constructor() { // Get instances of the unit and prefix tables and the utilities this.utabs_ = UnitTables.getInstance(); this.pfxTabs_ = PrefixTables.getInstance(); // Set emphasis characters to defaults. These are used to emphasize // certain characters or strings in user messages. They can be reset in // the useHTMLInMessages method. this.openEmph_ = Ucum.openEmph_; this.closeEmph_ = Ucum.closeEmph_; // Set the braces message to blank. This message is displayed for each // validation request on the web page, but is included separately as // a note on the validation spreadsheet. The useBraceMsgForEachString // method should be used to set the message to be displayed for each // unit string. this.bracesMsg_ = ''; // Set the flags used, with indices, as place holders in unit strings // for parenthetical strings and strings within braces. this.parensFlag_ = "parens_placeholder"; // in lieu of Jehoshaphat this.pFlagLen_ = this.parensFlag_.length; this.braceFlag_ = "braces_placeholder"; // in lieu of Nebuchadnezzar this.bFlagLen_ = this.braceFlag_.length; // Initialize the message start/end strings, which will be set when // parseString is called. this.vcMsgStart_ = null; this.vcMsgEnd_ = null; // Arrays used by multiple methods within this class to hold persistent // data. Just gets too bulky to pass these guys around. // Messages to be returned to the calling function this.retMsg_ = []; // Units for parenthetical unit strings this.parensUnits_ = []; // annotation text for annotations found in unit strings this.annotations_ = []; // suggestions for unit strings that for which no unit was found this.suggestions = []; } // end constructor /** * Sets the emphasis strings to the HTML used in the webpage display - or * blanks them out, depending on the use parameter. * * @param use flag indicating whether or not to use the html message format; * defaults to true */ useHTMLInMessages(use) { if (use === undefined || use) { this.openEmph_ = Ucum.openEmphHTML_; this.closeEmph_ = Ucum.closeEmphHTML_; } else { this.openEmph_ = Ucum.openEmph_; this.closeEmph_ = Ucum.closeEmph_; } } // end useHTMLInMessages /** * Sets the braces message to be displayed for each unit string validation * requested, as appropriate. * * @param use flag indicating whether or not to use the braces message; * defaults to true */ useBraceMsgForEachString(use) { if (use === undefined || use) this.bracesMsg_ = Ucum.bracesMsg_;else this.bracesMsg_ = ''; } /** * Parses a unit string, returns a unit, a possibly updated version of * the string passed in, and messages and suggestions where appropriate. * * The string returned may be updated if the input string contained unit * names, e.g., "pound". The unit code ([lb_av] for pound) is placed in * the string returned, a the returned messages array includes a note * explaining the substitution. * * @param uStr the string defining the unit * @param valConv indicates what type of request this is for - a request to * validate (pass in 'validate') or a request to convert (pass in 'convert'); * optional, defaults to 'validate' * @param suggest a boolean to indicate whether or not suggestions are * requested for a string that cannot be resolved to a valid unit; * true indicates suggestions are wanted; false indicates they are not, * and is the default if the parameter is not specified; * @returns an array containing: * the unit object or null if a unit could not be created. In cases where * a fix was found for a problem string, .e.g., 2.mg for 2mg, a unit will * be returned but an error message will also be returned, describing * the substitution; * the possibly updated unit string passed in; * an array of any user messages (informational, error or warning) * generated (or an empty array); and * a suggestions array of hash objects (1 or more). Each hash contains * three elements: * 'msg' which is a message indicating what unit expression the * suggestions are for; * 'invalidUnit' which is the unit expression the suggestions are * for; and * 'units' which is an array of data for each suggested unit found. * Each array will contain the unit code, the unit name and the * unit guidance (if any). * The return array will not contain a suggestions array if a valid unit * was found or if suggestions were not requested. * @throws an error if nothing was specified. */ parseString(uStr, valConv, suggest) { uStr = uStr.trim(); // Make sure we have something to work with if (uStr === '' || uStr === null) { throw new Error('Please specify a unit expression to be validated.'); } if (valConv === 'validate') { this.vcMsgStart_ = Ucum.valMsgStart_; this.vcMsgEnd_ = Ucum.valMsgEnd_; } else { this.vcMsgStart_ = Ucum.cnvMsgStart_; this.vcMsgEnd_ = Ucum.cnvMsgEnd_; } if (suggest === undefined || suggest === false) { this.suggestions_ = null; } else { this.suggestions_ = []; } this.retMsg_ = []; this.parensUnits_ = []; this.annotations_ = []; let origString = uStr; let retObj = []; // Extract any annotations, i.e., text enclosed in braces ({}) from the // string before further processing. Store each one in this.annotations_ // array and put a placeholder in the string for the annotation. Do // this before other processing in case an annotation contains characters // that will be interpreted as parenthetical markers or operators in // subsequent processing. uStr = this._getAnnotations(uStr); if (this.retMsg_.length > 0) { retObj[0] = null; retObj[1] = null; } else { // Flag used to block further processing on an unrecoverable error let endProcessing = this.retMsg_.length > 0; // First check for one of the "special" units. If it's one of those, put // in a substitution phrase for it to avoid having it separated on its // embedded operator. This will only happen, by the way, if it is // preceded by a prefix or followed by an operator and another unit. let sUnit = null; for (sUnit in Ucum.specUnits_) { while (uStr.indexOf(sUnit) !== -1) uStr = uStr.replace(sUnit, Ucum.specUnits_[sUnit]); } // Check for spaces and throw an error if any are found. The spec // explicitly forbids spaces except in annotations, which is why any // annotations are extracted before this check is made. if (uStr.indexOf(' ') > -1) { throw new Error('Blank spaces are not allowed in unit expressions.'); } // end if blanks were found in the string // assign the array returned to retObj. It will contain 2 elements: // the unit returned in position 0; and the origString (possibly // modified in position 1. The origString in position 1 will not // be changed by subsequent processing. retObj = this._parseTheString(uStr, origString); let finalUnit = retObj[0]; // Do a final check to make sure that finalUnit is a unit and not // just a number. Something like "8/{HCP}" will return a "unit" of 8 // - which is not a unit. Hm - evidently it is. So just create a unit // object for it. if (intUtils_.isIntegerUnit(finalUnit) || typeof finalUnit === 'number') { finalUnit = new Unit({ 'csCode_': origString, 'magnitude_': finalUnit, 'name_': origString }); retObj[0] = finalUnit; } // end final check } // end if no annotation errors were found retObj[2] = this.retMsg_; if (this.suggestions_ && this.suggestions_.length > 0) retObj[3] = this.suggestions_; return retObj; } // end parseString /** * Parses a unit string, returns a unit, a possibly updated version of * the string passed in, and messages where appropriate. This should * only be called from within this class (or by test code). * * The string returned may be updated if the input string contained unit * names, e.g., "pound". The unit code ([lb_av] for pound) is placed in * the string returned, a the returned messages array includes a note * explaining the substitution. * * @param uStr the string defining the unit * @param origString the original unit string passed in * * @returns * an array containing: * the unit object (or null if there were problems creating the unit); and * the possibly updated unit string passed in. * * the this.retMsg_ array will be updated with any user messages * (informational, error or warning) generated by this or called methods * the this.parensUnits_ array is referenced and possibly populated by * methods called within this one * the this.annotations_ array is referenced by methods called within * this one * the this.suggestions_ array may be populated by methods called within * this one */ _parseTheString(uStr, origString) { // Unit to be returned let finalUnit = null; // Flag used to block further processing on an unrecoverable error let endProcessing = this.retMsg_.length > 0; // Call _processParens to search for and process any/all parenthetical // strings in uStr. Units created for parenthetical strings will be // stored in the this.parensUnits_ array. let parensResp = this._processParens(uStr, origString); endProcessing = parensResp[2]; // The array used to hold the units and their operators. let uArray = []; // Continue if we didn't hit a problem if (!endProcessing) { uStr = parensResp[0]; origString = parensResp[1]; // Call _makeUnitsArray to convert the string to an array of unit // descriptors with operators. let mkUArray = this._makeUnitsArray(uStr, origString); endProcessing = mkUArray[2]; if (!endProcessing) { uArray = mkUArray[0]; origString = mkUArray[1]; // Create a unit object out of each un element let uLen = uArray.length; for (let u1 = 0; u1 < uLen; u1++) { //for (let u1 = 0; u1 < uLen && !endProcessing; u1++) { let curCode = uArray[u1]['un']; // Determine the type of the "un" attribute of the current array element // Check to see if it's a number. If so write the number version of // the number back to the "un" attribute and move on if (intUtils_.isIntegerUnit(curCode)) { uArray[u1]['un'] = Number(curCode); } else { // The current unit array element is a string. Check now to see // if it is or contains a parenthesized unit from this.parensUnits_. // If so, call _getParens to process the string and get the unit. if (curCode.indexOf(this.parensFlag_) >= 0) { let parenUnit = this._getParensUnit(curCode, origString); // if we couldn't process the string, set the end flag and bypass // further processing. if (!endProcessing) endProcessing = parenUnit[1]; // If we're good, put the unit in the uArray and replace the // curCode, which contains the parentheses placeholders, etc., // with the unit's code - including any substitutions. if (!endProcessing) { uArray[u1]['un'] = parenUnit[0]; } } // end if the curCode contains a parenthesized unit // Else it's not a parenthetical unit and not a number. Call // _makeUnit to create a unit for it. else { let uRet = this._makeUnit(curCode, origString); // If we didn't get a unit, set the endProcessing flag. if (uRet[0] === null) { endProcessing = true; } else { uArray[u1]['un'] = uRet[0]; origString = uRet[1]; } } // end if the curCode is not a parenthetical expression } // end if the "un" array is a not a number } // end do for each element in the units array } // end if _makeUnitsArray did not return an error } // end if _processParens did not find an error that causes a stop // If we're still good, continue if (!endProcessing) { // Process the units (and numbers) to create one final unit object if ((uArray[0] === null || uArray[0] === ' ' || uArray[0]['un'] === undefined || uArray[0]['un'] === null) && this.retMsg_.length === 0) { // not sure what this might be, but this is a safeguard this.retMsg_.push(`Unit string (${origString}) did not contain ` + `anything that could be used to create a unit, or else something ` + `that is not handled yet by this package. Sorry`); endProcessing = true; } } if (!endProcessing) { finalUnit = this._performUnitArithmetic(uArray, origString); } return [finalUnit, origString]; } // end _parseTheString /** * Extracts all annotations from a unit string, replacing them with * placeholders for later evaluation. The annotations are stored in the * this.annotations_ array. This should only be called from within this * class (or by test code). * * @param uString the unit string being parsed * @returns the string after the annotations are replaced with placeholders * * the this.retMsg_ array will be updated with any user messages * (informational, error or warning) generated by this or called methods * the this.annotations_ array is populated by this method */ _getAnnotations(uString) { let openBrace = uString.indexOf('{'); while (openBrace >= 0) { let closeBrace = uString.indexOf('}'); if (closeBrace < 0) { this.retMsg_.push('Missing closing brace for annotation starting at ' + this.openEmph_ + uString.substr(openBrace) + this.closeEmph_); openBrace = -1; } else { let braceStr = uString.substring(openBrace, closeBrace + 1); let aIdx = this.annotations_.length.toString(); uString = uString.replace(braceStr, this.braceFlag_ + aIdx + this.braceFlag_); this.annotations_.push(braceStr); openBrace = uString.indexOf('{'); } } // end do while we have an opening brace // check for a stray/unmatched closing brace let closeBrace = uString.indexOf('}'); if (closeBrace >= 0) this.retMsg_.push('Missing opening brace for closing brace found at ' + this.openEmph_ + uString.substring(0, closeBrace + 1) + this.closeEmph_); return uString; } // end _getAnnotations /** * Finds and processes any/all parenthesized unit strings. This should only * be called from within this class (or by test code). * * Nested parenthesized strings are processed from the inside out. The * parseString function is called from within this one for each parenthesized * unit string, and the resulting unit object is stored in this.parensUnits_, * to be processed after all strings are translated to units. * * A placeholder is placed in the unit string returned to indicate that the * unit object should be obtained from the this.parensUnits_ array. The * placeholder consists of the parenthesis flag (this.parensFlag_) followed * by the index of the unit in this.parensUnits_ followed by this.parensFlag_. * * @param uString the unit string being parsed, where this will be the full * string the first time this is called and parenthesized strings on any * subsequent calls * @param origString the original string first passed in to parseString * @returns * an array containing: * the string after the parentheses are replaced; * the original string; and * a boolean flag indicating whether or not an error occurred that * should stop processing. * * the this.retMsg_ array will be updated with any user messages * (informational, error or warning) generated by this or called methods * this this.parensUnits_ array will be populated with units found for * parenthetical unit strings */ _processParens(uString, origString) { // Unit strings array and index let uStrArray = []; let uStrAryPos = 0; let stopProcessing = false; let pu = this.parensUnits_.length; // Count of characters trimmed off the beginning of the unit string (uString) // as units are removed from it; used for error messages to provide // context. let trimmedCt = 0; // Break the unit string into pieces that consist of text outside of // parenthetical strings and placeholders for the parenthetical units. // This method is called recursively for parenthetical strings and the units // returned are stored in the this.parensUnits_ array. while (uString !== "" && !stopProcessing) { let openCt = 0; let closeCt = 0; let openPos = uString.indexOf('('); // If an opening parenthesis was not found, check for an unmatched // close parenthesis. If one was found report the error and end // processing. if (openPos < 0) { let closePos = uString.indexOf(')'); if (closePos >= 0) { let theMsg = `Missing open parenthesis for close ` + `parenthesis at ${uString.substring(0, closePos + trimmedCt)}` + `${this.openEmph_}${uString.substr(closePos, 1)}${this.closeEmph_}`; if (closePos < uString.length - 1) { theMsg += `${uString.substr(closePos + 1)}`; } this.retMsg_.push(theMsg); uStrArray[uStrAryPos] = uString; stopProcessing = true; } // end if a close parenthesis was found // If no parentheses were found in the current unit string, transfer // it to the units array and blank out the string, which will end // the search for parenthetical units. else { uStrArray[uStrAryPos] = uString; uString = ""; } // end if no close parenthesis was found } // end if no open parenthesis was found // Otherwise an open parenthesis was found. Process the string that // includes the parenthetical group else { openCt += 1; // Write the text before the parentheses (if any) to the unit strings array let uLen = uString.length; if (openPos > 0) { uStrArray[uStrAryPos++] = uString.substr(0, openPos); } // Find the matching closePos, i.e., the one that closes the // parenthetical group that this one opens. Look also for // another open parenthesis, in case this includes nested parenthetical // strings. This continues until it finds the same number of close // parentheses as open parentheses, or runs out of string to check. // In the case of nested parentheses this will identify the outer set // of parentheses. let closePos = 0; let c = openPos + 1; for (; c < uLen && openCt != closeCt; c++) { if (uString[c] === '(') openCt += 1;else if (uString[c] === ')') closeCt += 1; } // Put a placeholder for the group in the unit strings array and recursively // call this method for the parenthetical group. Put the unit returned // in this.parensUnits_. Set the unit string to whatever follows // the position of the closing parenthesis for this group, to be // processed by the next iteration of this loop. If there's nothing // left uString is set to "". if (openCt === closeCt) { closePos = c; uStrArray[uStrAryPos++] = this.parensFlag_ + pu.toString() + this.parensFlag_; let parseResp = this._parseTheString(uString.substring(openPos + 1, closePos - 1), origString); if (parseResp[0] === null) stopProcessing = true;else { origString = parseResp[1]; this.parensUnits_[pu++] = parseResp[0]; uString = uString.substr(closePos); trimmedCt = closePos; } } // end if the number of open and close parentheses matched // If the number of open and close parentheses doesn't match, indicate // an error. else { uStrArray.push(origString.substr(openPos)); this.retMsg_.push(`Missing close parenthesis for open parenthesis at ` + `${origString.substring(0, openPos + trimmedCt)}` + `${this.openEmph_}${origString.substr(openPos, 1)}` + `${this.closeEmph_}${origString.substr(openPos + 1)}`); stopProcessing = true; } } // end if an open parenthesis was found } // end do while the input string is not empty if (stopProcessing) this.parensUnits_ = []; return [uStrArray.join(''), origString, stopProcessing]; } // end _processParens /** * Breaks the unit string into an array of unit descriptors and operators. * If a unit descriptor consists of a number preceding a unit code, with * no multiplication operator, e.g., 2mg instead of 2.mg, it is handled * as if it were a parenthetical expression. * * This should only be called from within this class (or by test code). * * @param uStr the unit string being parsed * @param origString the original string passed to parseString * @returns * an array containing: * the array representing the unit string; * the original string passed in, possibly updated with corrections; and * and a flag indicating whether or not processing can continue. * * the this.retMsg_ array will be updated with any user messages * (informational, error or warning) generated by this or called methods */ _makeUnitsArray(uStr, origString) { // Separate the string into pieces based on delimiters / (division) and . // (multiplication). The idea is to get an array of units on which we // can then perform any operations (prefixes, multiplication, division). let uArray1 = uStr.match(/([./]|[^./]+)/g); let endProcessing = false; let uArray = []; let startNumCheck = /(^[0-9]+)(\[?[a-zA-Z\_0-9a-zA-Z\_]+\]?$)/; // If the first element in the array is the division operator (/), the // string started with '/'. Add a first element containing 1 to the // array, which will cause the correct computation to be performed (inversion). if (uArray1[0] === "/") { uArray1.unshift("1"); } // If the first element in the array is the multiplication operator (.) // return an error. else if (uArray1[0] === '.') { this.retMsg_.push(`${origString} is not a valid UCUM code. ` + `The multiplication operator at the beginning of the expression is ` + `not valid. A multiplication operator must appear only between ` + `two codes.`); endProcessing = true; } if (!endProcessing) { // Check to see if there is a number preceding a unit code, e.g., 2mg // If so, update the first element to remove the number (2mg -> mg) and // add two elements to the beginning of the array - the number and the // multiplication operator. if (!intUtils_.isNumericString(uArray1[0])) { let numRes = uArray1[0].match(startNumCheck); if (numRes && numRes.length === 3 && numRes[1] !== '' && numRes[2] !== '' && numRes[2].indexOf(this.braceFlag_) !== 0) { let dispVal = numRes[2]; if (!endProcessing && numRes[2].indexOf(this.parensFlag_) !== -1) { let parensback = this._getParensUnit(numRes[2], origString); numRes[2] = parensback[0]['csCode_']; dispVal = `(${numRes[2]})`; endProcessing = parensback[1]; } if (!endProcessing) { this.retMsg_.push(`${numRes[1]}${dispVal} is not a valid UCUM code.` + ` ${this.vcMsgStart_}${numRes[1]}.${dispVal}${this.vcMsgEnd_}`); origString = origString.replace(`${numRes[1]}${dispVal}`, `${numRes[1]}.${dispVal}`); uArray1[0] = numRes[2]; uArray1.unshift(numRes[1], '.'); } } } // end if the first element is not a number (only) // Create an array of unit/operator objects. The unit is, for now, the // string containing the unit code (e.g., Hz for hertz) including // a possible prefix and exponent. The operator is the operator to be // applied to that unit and the one preceding it. So, a.b would give // us two objects. The first will have a unit of a, and a blank operator // (because it's the first unit). The second would have a unit of b // and the multiplication operator (.). if (!endProcessing) { let u1 = uArray1.length; uArray = [{ op: "", un: uArray1[0] }]; for (let n = 1; n < u1; n++) { // check to make sure that we don't have two operators together, e.g., // mg./K. If so, let the user know the problem. let theOp = uArray1[n++]; // oh wait - check to make sure something is even there, that the // user didn't end the expression with an operator. if (!uArray1[n]) { this.retMsg_.push(`${origString} is not a valid UCUM code. ` + `It is terminated with the operator ${this.openEmph_}` + `${theOp}${this.closeEmph_}.`); n = u1; endProcessing = true; } else if (Ucum.validOps_.indexOf(uArray1[n]) !== -1) { this.retMsg_.push(`${origString} is not a valid UCUM code. ` + `A unit code is missing between${this.openEmph_}` + `${theOp}${this.closeEmph_}and${this.openEmph_}` + `${uArray1[n]}${this.closeEmph_}in${this.openEmph_}` + `${theOp}${uArray1[n]}${this.closeEmph_}.`); n = u1; endProcessing = true; } else { // Check to see if a number precedes a unit code. // If so, send the element to _processParens, inserting the multiplication // operator where it belongs. Treating it as parenthetical keeps it from // being interpreted incorrectly because of operator parentheses. For // example, if the whole string is mg/2kJ we don't want to rewrite it as // mg/2.kJ - because mg/2 would be performed, followed by .kJ. Instead, // handling 2kJ as a parenthesized unit will make sure mg is divided by // 2.kJ. if (!intUtils_.isNumericString(uArray1[n])) { let numRes2 = uArray1[n].match(startNumCheck); if (numRes2 && numRes2.length === 3 && numRes2[1] !== '' && numRes2[2] !== '' && numRes2[2].indexOf(this.braceFlag_) !== 0) { let invalidString = numRes2[0]; if (!endProcessing && numRes2[2].indexOf(this.parensFlag_) !== -1) { let parensback = this._getParensUnit(numRes2[2], origString); numRes2[2] = parensback[0]['csCode_']; invalidString = `(${numRes2[2]})`; endProcessing = parensback[1]; if (!endProcessing) { this.retMsg_.push(`${numRes2[1]}${invalidString} is not a ` + `valid UCUM code. ${this.vcMsgStart_}${numRes2[1]}.${invalidString}` + `${this.vcMsgEnd_}`); let parensString = `(${numRes2[1]}.${invalidString})`; origString = origString.replace(`${numRes2[1]}${invalidString}`, parensString); let nextParens = this._processParens(parensString, origString); endProcessing = nextParens[2]; if (!endProcessing) { uArray.push({ op: theOp, un: nextParens[0] }); } //uArray.push({op: '.', un: numRes2[2]}); } } // end if the string represents a parenthesized unit else { let parensStr = '(' + numRes2[1] + '.' + numRes2[2] + ')'; let parensResp = this._processParens(parensStr, origString); // if a "stop processing" flag was returned, set the n index to end // the loop and set the endProcessing flag if (parensResp[2]) { n = u1; endProcessing = true; } else { this.retMsg_.push(`${numRes2[0]} is not a ` + `valid UCUM code. ${this.vcMsgStart_}${numRes2[1]}.${numRes2[2]}` + `${this.vcMsgEnd_}`); origString = origString.replace(numRes2[0], parensStr); uArray.push({ op: theOp, un: parensResp[0] }); } // end if no error on the processParens call } // end if the string does not represent a parenthesized unit } // end if the string is a number followed by a string else { uArray.push({ op: theOp, un: uArray1[n] }); } } else { uArray.push({ op: theOp, un: uArray1[n] }); } } // end if there isn't a missing operator or unit code } // end do for each element in uArray1 } // end if a processing error didn't occur in getParensUnit } // end if the string did not begin with a '.' with no following digit return [uArray, origString, endProcessing]; } // end _makeUnitsArray /** * Takes a unit string containing parentheses flags and returns the unit they * represent. Any text found before and/or after the parenthetical * expression is checked to see if we can tell what the user meant and * let them know what it should have been. For example, 2(mg), which * would resolve to 2mg, should be 2.mg. * * This should only be called from within this class (or by test code). * * @param pStr the string being parsed * @param origString the original unit string passed in; passed through * to _getAnnonText if annotation flags are found in any text preceding * or following the parenthetical unit * @returns * an array containing * the unit object; and * a flag indicating whether or not processing should be ended. * True indicates that the string was invalid and no corrections * (substitutions or suggestions) could be found; * False indicates that it was either valid or substitutions/suggestions * were made. * the this.retMsg_ array will be updated with any user messages * (informational, error or warning) generated by this or called methods * this this.parensUnits_ array contains the units that are acquired by * this method * @throws an error if an invalid parensUnit index was found. This is * a processing error. */ _getParensUnit(pStr, origString) { let endProcessing = false; let retAry = []; let retUnit = null; let befAnnoText = null; let aftAnnoText = null; // Get the location of the flags. We're assuming there are only two // because _processParens takes care of nesting. By the time we get // here we should not be looking a nested parens. Also get any text // before and after the parentheses. Once we get the unit we update // the input string with the unit's csCode_, which will wipe out any // before and after text let psIdx = pStr.indexOf(this.parensFlag_); let befText = null; if (psIdx > 0) { befText = pStr.substr(0, psIdx - 1); } let peIdx = pStr.lastIndexOf(this.parensFlag_); let aftText = null; if (peIdx + this.pFlagLen_ < pStr.length) { aftText = pStr.substr(peIdx + this.pFlagLen_); } // Get the text between the flags let pNumText = pStr.substring(psIdx + this.pFlagLen_, peIdx); // Make sure the index is a number, and if it is, get the unit from the // this.parensUnits_ array if (intUtils_.isNumericString(pNumText)) { retUnit = this.parensUnits_[Number(pNumText)]; if (!intUtils_.isIntegerUnit(retUnit)) { pStr = retUnit.csCode_; } else { pStr = retUnit; } } // If it's not a number, it's a programming error. Throw a fit. else { throw new Error(`Processing error - invalid parens number ${pNumText} ` + `found in ${pStr}.`); } // If there's something in front of the starting parentheses flag, check to // see if it's a number or an annotation. if (befText) { // If it's a number, assume that multiplication was assumed if (intUtils_.isNumericString(befText)) { let nMag = retUnit.getProperty('magnitude_'); nMag *= Number(befText); retUnit.assignVals({ 'magnitude_': nMag }); pStr = `${befText}.${pStr}`; this.retMsg_.push(`${befText}${pStr} is not a valid UCUM code.\n` + this.vcMsgStart_ + pStr + this.vcMsgEnd_); } else { if (befText.indexOf(this.braceFlag_) >= 0) { let annoRet = this._getAnnoText(befText, origString); // if we found not only an annotation, but text before or after // the annotation (remembering that this is all before the // parentheses) throw an error - because we don't know what // to do with it. Could it be missing an operator? if (annoRet[1] || annoRet[2]) { throw new Error(`Text found before the parentheses (` + `${befText}) included an annotation along with other text ` + `for parenthetical unit ${retUnit.csCode_}`); } // Otherwise put the annotation after the unit string and note // the misplacement. pStr += annoRet[0]; this.retMsg_.push(`The annotation ${annoRet[0]} before the unit ` + `code is invalid.\n` + this.vcMsgStart_ + pStr + this.vcMsgEnd_); } // else the text before the parentheses is neither a number nor // an annotation. If suggestions were NOT requested, record an // error. else if (!this.suggestions_) { this.retMsg_.push(`${befText} preceding the unit code ${pStr} ` + `is invalid. Unable to make a substitution.`); endProcessing = true; } // otherwise try for suggestions else { let suggestStat = this._getSuggestions(befText); endProcessing = suggestStat !== 'succeeded'; } // end if a brace was found or, if not, suggestions were not or // were requested } // end if text preceding the parentheses was not a number } // end if there was text before the parentheses // Process any text after the parentheses if (aftText) { // if it's an annotation, get it and add it to the pStr if (aftText.indexOf(this.braceFlag_) >= 0) { let annoRet = this._getAnnoText(aftText, origString); // if we found not only an annotation, but text before or after // the annotation (remembering that this is all after the // parentheses) throw an error - because we don't know what // to do with it. Could it be missing an operator? if (annoRet[1] || annoRet[2]) { throw new Error(`Text found after the parentheses (` + `${aftText}) included an annotation along with other text ` + `for parenthetical unit ${retUnit.csCode_}`); } // Otherwise put the annotation after the unit string - no message // needed. pStr += annoRet[0]; } // Otherwise check to see if it's an exponent. If so, warn the // user that it's not valid - but try it anyway else { if (intUtils_.isNumericString(aftText)) { pStr += aftText; retUnit = retUnit.power(Number(aftText)); this.retMsg_.push(`An exponent (${aftText}) following a parenthesis ` + `is invalid as of revision 1.9 of the UCUM Specification.\n ` + this.vcMsgStart_ + pStr + this.vcMsgEnd_); } // else the text after the parentheses is neither a number nor // an annotation. If suggestions were NOT requested, record an // error. else if (!this.suggestions_) { this.retMsg_.push(`Text ${aftText} following the unit code ${pStr} ` + `is invalid. Unable to make a substitution.`); endProcessing = true; } // otherwise try for suggestions else { let suggestStat = this._getSuggestions(befText); endProcessing = suggestStat !== 'succeeded'; } // end if text following the parentheses not an exponent } // end if text following the parentheses is not an annotation } // end if there is text following the parentheses if (!endProcessing) { if (!retUnit) { retUnit = new Unit({ 'csCode_': pStr, 'magnitude_': 1, 'name_': pStr }); } else if (intUtils_.isIntegerUnit(retUnit)) { retUnit = new Unit({ 'csCode_': retUnit, 'magnitude_': retUnit, 'name_': retUnit }); } else { retUnit.csCode_ = pStr; } } return [retUnit, endProcessing]; } // end _getParensUnit /** * Takes a unit string containing annotation flags and returns the * annotation they represent. This also returns any text found before * the annotation and any found after the annotation. * * This should only be called from within this class (or by test code). * NEEDS FIX in next branch to handle string with multiple annotations. * * @param pStr the string being parsed * @param origString the original string being parsed; used in error msg * thrown for an invalid index to the annotations array * @returns * an array containing * the annotation for the pStr; * any text found before the annotation; and * any text found after the annotation. * * the this.retMsg_ array will be updated with any user messages * (informational, error or warning) generated by this or called methods * the this.annotations_ array is used as the source for the annotations text * @throws an error if for a processing error - an invalid annotation index. */ _getAnnoText(pStr, origString) { // if the starting braces flag is not at index 0, get the starting // text and the adjust the pStr to omit it. let asIdx = pStr.indexOf(this.braceFlag_); let startText = asIdx > 0 ? pStr.substring(0, asIdx) : null; if (asIdx !== 0) { pStr = pStr.substr(asIdx); } // Get the location of the end flag and, if text follows it, get the text let aeIdx = pStr.indexOf(this.braceFlag_, 1); let endText = aeIdx + this.bFlagLen_ < pStr.length ? pStr.substr(aeIdx + this.bFlagLen_) : null; // Get the index of the annotation in this.annotations_. // Check it to make sure it's valid, and if not, throw an error let idx = pStr.substring(this.bFlagLen_, aeIdx); let idxNum = Number(idx); if (!intUtils_.isNumericString(idx) || idxNum >= this.annotations_.length) { throw new Error(`Processing Error - invalid annotation index ${idx} found ` + `in ${pStr} that was created from ${origString}`); } // Replace the flags and annotation index with the annotation expression pStr = this.annotations_[idxNum]; return [pStr, startText, endText]; } // end _getAnnoText /** * Takes a unit string and looks for suggested units. This should be * called for unit strings that cannot be resolved to unit codes. The * string is searched for in the synonyms table found in the UnitTables * class. That table includes all synonyms and unit names for the units * in the unit data table. * * @param pStr the string being parsed * @returns an object that contains an element named 'status', whose * value indicates the status of the request: * 'succeeded' indicates that synonyms were found; * 'failed' indicates that no synonyms were found; or * 'error' which indicates that an error occurred * * the this.retMsg_ array will be updated with a message indicating whether * or not synonyms/suggestions were found * the this.suggestions_ array will be updated with a hash (added to the * array if it already contains others) that contains three elements: * 'msg' which is a message indicating what unit expression the * suggestions are for; * 'invalidUnit' which is the unit expression the suggestions are for; and * 'units' which is an array of data for each suggested unit found. * Each array will contain the unit code, the unit name and the * unit guidance (if any). */ _getSuggestions(pStr) { let retObj = intUtils_.getSynonyms(pStr); if (retObj['status'] === 'succeeded') { let suggSet = {}; suggSet['msg'] = `${pStr} is not a valid UCUM code. We found possible ` + `units that might be what was meant:`; suggSet['invalidUnit'] = pStr; let synLen = retObj['units'].length; suggSet['units'] = []; for (let s = 0; s < synLen; s++) { let unit = retObj['units'][s]; let unitArray = [unit['code'], unit['name'], unit['guidance']]; suggSet['units'].push(unitArray); } this.suggestions_.push(suggSet); } else { this.retMsg_.push(`${pStr} is not a valid UCUM code. No alternatives ` + `were found.`); } return retObj['status']; } // end getSuggestions /** * Creates a unit object from a string defining one unit. The string * should consist of a unit code for a unit already defined (base or * otherwise). It may include a prefix and an exponent, e.g., cm2 * (centimeter squared). This should only be called from within this * class (or by test code). * * @params uCode the string defining the unit * @param origString the original string to be parsed; used to provide * context for messages * @returns * an array containing: * a unit object, or null if there were problems creating the unit; and * the origString passed in, which may be updated if a unit name was * translated to a unit code. * * the this.retMsg_ array will be updated with any user messages * (informational, error or warning) generated by this or called methods * the this.suggestions_ array will be populated if no unit (with or without * substitutions) could be found and suggestions were requested */ _makeUnit(uCode, origString) { // First try the code just as is, without looking for annotations, // prefixes, exponents, or elephants. let retUnit = this.utabs_.getUnitByCode(uCode); if (retUnit) { retUnit = retUnit.clone(); } // If we found it, we're done. No need to parse for those elephants (or // other stuff). else if (uCode.indexOf(this.braceFlag_) >= 0) { let getAnnoRet = this._getUnitWithAnnotation(uCode, origString); retUnit = getAnnoRet[0]; if (retUnit) { origString = getAnnoRet[1]; } // If a unit is not found, retUnit will be returned null and // the this.retMsg_ array will contain a message describing the problem. // If a unit is found, of course, all is good. So ... nothing left // to see here, move along. } // end if the uCode includes an annotation else { // So we didn't find a unit for the full uCode or for one with // annotations. Try looking for a unit that uses a carat (^) // instead of an asterisk (*) if (uCode.indexOf('^') > -1) { let tryCode = uCode.replace('^', '*'); retUnit = this.utabs_.getUnitByCode(tryCode); if (retUnit) { retUnit = retUnit.clone(); retUnit.csCode_ = retUnit.csCode_.replace('*', '^'); retUnit.ciCode_ = retUnit.ciCode_.replace('*', '^'); } } // If that didn't work, check to see if it should have brackets // around it (uCode = degF when it should be [degF] if (!retUnit) { let addBrackets = '[' + uCode + ']'; retUnit = this.utabs_.getUnitByCode(addBrackets); if (retUnit) { retUnit = retUnit.clone(); origString = origString.replace(uCode, addBrackets); this.retMsg_.push(`${uCode} is not a valid unit expression, but ` + `${addBrackets} is.\n` + this.vcMsgStart_ + `${addBrackets} (${retUnit.name_})${this.vcMsgEnd_}`); } // end if we found the unit after adding brackets } // end trying to add brackets // If we didn't find it, try it as a name if (!retUnit) { let retUnitAry = this.utabs_.getUnitByName(uCode); if (retUnitAry && retUnitAry.length > 0) { retUnit = retUnitAry[0].clone(); let mString = 'The UCUM code for ' + uCode + ' is ' + retUnit.csCode_ + '.\n' + this.vcMsgStart_ + retUnit.csCode_ + this.vcMsgEnd_; let dupMsg = false; for (let r = 0; r < this.retMsg_.length && !dupMsg; r++) dupMsg = this.retMsg_[r] === mString; if (!dupMsg) this.retMsg_.push(mString); let rStr = new RegExp('(^|[.\/({])(' + uCode + ')($|[.\/)}])'); let res = origString.match(rStr); origString = origString.replace(rStr, res[1] + retUnit.csCode_ + res[3]); uCode = retUnit.csCode_; } } // If we still don't have a unit, try assuming a modifier (prefix and/or // exponent) and look for a unit without the modifier if (!retUnit) { // Well, first see if it's one of the special units. If so, // replace the placeholder text with the actual unit string, keeping // whatever text (probably a prefix) goes with the unit string. let sUnit = null; for (sUnit in Ucum.specUnits_) { if (uCode.indexOf(Ucum.specUnits_[sUnit]) !== -1) uCode = uCode.replace(Ucum.specUnits_[sUnit], sUnit); } retUnit = this.utabs_.getUnitByCode(uCode); if (retUnit) retUnit = retUnit.clone(); } if (!retUnit) { let origCode = uCode; let origUnit = null; let exp = null; let pfxCode = null; let pfxObj = null; let pfxVal = null; let pfxExp = null; // Look first for an exponent. If we got one, separate it out and // try to get the unit again let codeAndExp = this._isCodeWithExponent(uCode); if (codeAndExp) { uCode = codeAndExp[0]; exp = codeAndExp[1]; origUnit = this.utabs_.getUnitByCode(uCode); } // If we still don't have a unit, separate out the prefix, if any, // and try without it. if (!origUnit) { // Try for a single character prefix first. pfxCode = uCode.charAt(0); pfxObj = this.pfxTabs_.getPrefixByCode(pfxCode); // if we got a prefix, get its info and remove it from the unit code if (pfxObj) { pfxVal = pfxObj.getValue(); pfxExp = pfxObj.getExp(); let pCodeLen = pfxCode.length; uCode = uCode.substr(pCodeLen); // try again for the unit origUnit = this.utabs_.getUnitByCode(uCode); // If we still don't have a unit, see if the prefix could be the // two character "da" (deka) prefix. That's the only prefix with // two characters, and without this check it's interpreted as "d" // (deci) and the "a" is considered part of the unit code. if (!origUnit && pfxCode == 'd' && uCode.substr(0, 1) == 'a') { pfxCode = 'da'; pfxObj = this.pfxTabs_.getPrefixByCode(pfxCode); pfxVal = pfxObj.getValue(); uCode = uCode.substr(1); // try one more time for the unit origUnit = this.utabs_.getUnitByCode(uCode); } } // end if we found a prefix } // end if we didn't get a unit after removing an exponent // If we still haven't found anything, we're done looking. // (We tried with the full unit string, with the unit string // without the exponent, the unit string without a prefix, // common errors, etc. That's all we can try). if (!origUnit) { retUnit = null; // BUT if the user asked for suggestions, at least look for them if (this.suggestions_) { let suggestStat = this._getSuggestions(origCode); } else { this.retMsg_.push(`${origCode} is not a valid UCUM code.`); } } else { // Otherwise we found a unit object. Clone it and then apply the // prefix and exponent, if any, to it. And remove the guidance. retUnit = origUnit.clone(); retUnit.guidance_ = ''; let theDim = retUnit.getProperty('dim_'); let theMag = retUnit.getProperty('magnitude_'); let theName = retUnit.getProperty('name_'); let theCiCode = retUnit.getProperty('ciCode_'); let thePrintSymbol = retUnit.getProperty('printSymbol_'); // If there is an exponent for the unit, apply it to the dimension // and magnitude now if (exp) { exp = parseInt(exp); let expMul = exp; if (theDim) theDim = theDim.mul(exp); theMag = Math.pow(theMag, exp); retUnit.assignVals({ 'magnitude_': theMag }); // If there is also a prefix, apply the exponent to the prefix. if (pfxObj) { // if the prefix base is 10 it will have an exponent. Multiply // the current prefix exponent by the exponent for the unit // we're working with. Then raise the prefix value to the level // defined by the exponent. if (pfxExp) { expMul *= pfxObj.getExp(); pfxVal = Math.pow(10, expMul); } // If the prefix base is not 10, it won't have an exponent. // At the moment I don't see any units using the prefixes // that aren't base 10. But if we get one the prefix value // will be applied to the magnitude (below) if the unit does // not have a conversion function, and to the conversion prefix // if it does. } // end if there's a prefix as well as the exponent } // end if there's an exponent // Now apply the prefix, if there is one, to the conversion // prefix or the magnitude if (pfxObj) { if (retUnit.cnv_) { retUnit.assignVals({ 'cnvPfx_': pfxVal }); } else { theMag *= pfxVal; retUnit.assignVals({ 'magnitude_': theMag }); } } // if we have a prefix and/or an exponent, add them to the unit // attributes - name, csCode, ciCode and print symbol let theCode = retUnit.csCode_; if (pfxObj) { theName = pfxObj.getName() + theName; theCode = pfxCode + theCode; theCiCode = pfxObj.getCiCode() + theCiCode; thePrintSymbol = pfxObj.getPrintSymbol() + thePrintSymbol; retUnit.assignVals({ 'name_': theName, 'csCode_': theCode, 'ciCode_': theCiCode, 'printSymbol_': thePrintSymbol }); } if (exp) { let expStr = exp.toString(); retUnit.assignVals({ 'name_': theName + '' + expStr + '', 'csCode_': theCode + expStr, 'ciCode_': theCiCode + expStr, 'printSymbol_': thePrintSymbol + '' + expStr + '' }); } } // end if an original unit was found (without prefix and/or exponent) } // end if we didn't get a unit for the full unit code (w/out modifiers) } // end if we didn't find the unit on the first try, before parsing return [retUnit, origString]; } // end _makeUnit /** * This method handles unit creation when an annotation is included * in the unit string. This basically isolates and retrieves the * annotation and then calls _makeUnit to try to get a unit from * any text that precedes or follows the annotation. * * @param uCode the string defining the unit * @param origString the original full string submitted to parseString * @returns the unit object found, or null if one could not be found * * the this.retMsg_ array will be updated with any user messages * (informational, error or warning) generated by this or called methods */ _getUnitWithAnnotation(uCode, origString) { let retUnit = null; // Get the annotation and anything that precedes or follows it. let annoRet = this._getAnnoText(uCode, origString); let annoText = annoRet[0]; let befAnnoText = annoRet[1]; let aftAnnoText = annoRet[2]; // Add the warning about annotations - just once. if (this.bracesMsg_ && this.retMsg_.indexOf(this.bracesMsg_) === -1) this.retMsg_.push(this.bracesMsg_); // If there's no text before or after the annotation, it's probably // something that should be interpreted as a 1, e.g., {KCT'U}. // HOWEVER, it could also be a case where someone used braces instead // of brackets, e.g., {degF} instead of [degF]. Check for that before // we assume it should be a 1. let msgLen = this.retMsg_.length; if (!befAnnoText && !aftAnnoText) { let tryBrackets = '[' + annoText.substring(1, annoText.length - 1) + ']'; let mkUnitRet = this._makeUnit(tryBrackets, origString); // If we got back a unit, assign it to the returned unit, and add // a message to advise the user that brackets should enclose the code if (mkUnitRet[0]) { retUnit = mkUnitRet[0]; origString = origString.replace(annoText, tryBrackets); this.retMsg_.push(`${annoText} is not a valid unit expression, but ` + `${tryBrackets} is.\n` + this.vcMsgStart_ + `${tryBrackets} (${retUnit.name_})${this.vcMsgEnd_}`); } // Otherwise assume that this should be interpreted as a 1 else { // remove error message generated for trybrackets if (this.retMsg_.length > msgLen) { this.retMsg_.pop(); } uCode = 1; retUnit = 1; } } // end if it's only an annotation else { // if there's text before and no text after, assume the text before // the annotation is the unit code (with an annotation following it). // Call _makeUnit for the text before the annotation. if (befAnnoText && !aftAnnoText) { // make sure that what's before the annoText is not a number, e.g., // /100{cells}. But f it is a number, just set the return unit to // the number. if (intUtils_.isIntegerUnit(befAnnoText)) { retUnit = befAnnoText; } // Otherwise try to find a unit else { let mkUnitRet = this._makeUnit(befAnnoText, origString); // if a unit was returned if (mkUnitRet[0]) { retUnit = mkUnitRet[0]; retUnit.csCode_ += annoText; origString = mkUnitRet[1]; } // Otherwise add a not found message else { this.retMsg_.push(`Unable to find a unit for ${befAnnoText} that ` + `precedes the annotation ${annoText}.`); } } } // else if there's only text after the annotation, try for a unit // from the after text and assume the user put the annotation in // the wrong place (and tell them) else if (!befAnnoText && aftAnnoText) { // Again, test for a number and if it is a number, set the return // unit to the number. if (intUtils_.isIntegerUnit(aftAnnoText)) { retUnit = aftAnnoText + annoText; this.retMsg_.push(`The annotation ${annoText} before the ``${aftAnnoText} is invalid.\n` + this.vcMsgStart_ + retUnit + this.vcMsgEnd_); } else { let mkUnitRet = this._makeUnit(aftAnnoText, origString); if (mkUnitRet[0]) { retUnit = mkUnitRet[0]; retUnit.csCode_ += annoText; origString = retUnit.csCode_; this.retMsg_.push(`The annotation ${annoText} before the unit ` + `code is invalid.\n` + this.vcMsgStart_ + retUnit.csCode_ + this.vcMsgEnd_); } // Otherwise add a not found message else { this.retMsg_.push(`Unable to find a unit for ${befAnnoText} that ` + `follows the annotation ${annoText}.`); } } } // else it's got text before AND after the annotation. Now what? // For now this is an error. This may be a case of a missing // operator but that is not handled yet. else { this.retMsg_.push(`Unable to find a unit for ${befAnnoText}${annoText}` + `${aftAnnoText}.\nWe are not sure how to interpret text both before ` + `and after the annotation. Sorry`); } } // else if there's text before/and or after the annotation return [retUnit, origString]; } // end _getUnitWithAnnotations /** * Performs unit arithmetic for the units in the units array. That array * contains units/numbers and the operators (division or multiplication) to * be performed on each unit/unit or unit/number pair in the array. This * should only be called from within this class (or by test code). * * @params uArray the array that contains the units, numbers and operators * derived from the unit string passed in to parseString * @param origString the original string to be parsed; used to provide * context for messages * * @returns a single unit object that is the result of the unit arithmetic * * the this.retMsg_ array will be updated with any user messages * (informational, error or warning) generated by this or called methods */ _performUnitArithmetic(uArray, origString) { let finalUnit = uArray[0]['un']; if (intUtils_.isIntegerUnit(finalUnit)) { finalUnit = new Unit({ 'csCode_': finalUnit, 'magnitude_': Number(finalUnit), 'name_': finalUnit }); } let uLen = uArray.length; let endProcessing = false; // Perform the arithmetic for the units, starting with the first 2 units. // We only need to do the arithmetic if we have more than one unit. for (let u2 = 1; u2 < uLen && !endProcessing; u2++) { let nextUnit = uArray[u2]['un']; if (intUtils_.isIntegerUnit(nextUnit)) { nextUnit = new Unit({ 'csCode_': nextUnit, 'magnitude_': Number(nextUnit), 'name_': nextUnit }); } if (nextUnit === null || typeof nextUnit !== 'number' && !nextUnit.getProperty) { let msgString = `Unit string (${origString}) contains unrecognized ` + 'element'; if (nextUnit) { msgString += ` (${this.openEmph_}${nextUnit.toString()}` + `${this.closeEmph_})`; } msgString += '; could not parse full string. Sorry'; this.retMsg_.push(msgString); endProcessing = true; } else { try { // Is the operation division? let thisOp = uArray[u2]['op']; let isDiv = thisOp === '/'; // Perform the operation. Both the finalUnit and nextUnit // are unit objects. isDiv ? finalUnit = finalUnit.divide(nextUnit) : finalUnit = finalUnit.multiplyThese(nextUnit); } catch (err) { this.retMsg_.unshift(err.message); endProcessing = true; finalUnit = null; } } // end if we have another valid unit/number to process } // end do for each unit after the first one return finalUnit; } // end _performUnitArithmetic /** * This tests a string to see if it starts with characters and ends with * digits. This is used to test for an exponent on a UCUM code (or what * we think might be a UCUM code). This is broken out to a separate * function so that the regular expression can be verified to provide the * results we expect, in case someone changes it. (Per Paul Lynch) * See "Test _isCodeWithExponent method" in testUnitString.spec.js * * This particular regex has been tweaked several times. This one * works with the following test strings: * "m[H2O]-21 gives ["m[H2O]-21", "m[H2O]", "-21"] * "m[H2O]+21 gives ["m[H2O]+21", "m[H2O]", "+21"] * "m[H2O]21 gives ["m[H2O]-21", "m[H2O]", "21"] * "s2" gives ["s2", "s, "2"] * "kg" gives null * "m[H2O]" gives null * "m[H2O]23X" gives null * * @params uCode the code being tested * @returns an array containing: (1) the code without the exponent (or * trailing number); and (2) the exponent/trailing number. Returns null * if there is no trailing number or something follows the trailing * number, or if the first part is not characters. */ _isCodeWithExponent(uCode) { let ret = []; let res = uCode.match(/(^[^\-\+]+?)([\-\+\d]+)$/); // If we got a return with an exponent, separate the exponent from the // unit and return both (as separate values) if (res && res[2] && res[2] !== "") { ret.push(res[1]); ret.push(res[2]); } // end if we got an exponent else { ret = null; } return ret; } // end _isCodeWithExponent } // end class UnitString /** * This function exists ONLY until the original UnitString constructor * is called for the first time. It's defined here in case getInstance * is called before the constructor. This calls the constructor. * * The constructor redefines the getInstance function to return the * singleton UnitString object. This is based on the UnitTables singleton * implementation; see more detail in the UnitTables constructor description. * * @return the singleton UnitString object. */ exports.UnitString = UnitString; UnitString.getInstance = function () { return new UnitString(); }; /* // Perform the first request for the object, to set the getInstance method. UnitString.getInstance(); */ },{"./config.js":90,"./prefixTables.js":94,"./ucumInternalUtils.js":96,"./unit.js":100,"./unitTables.js":102}],102:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UnitTables = void 0; /** * This class manages Hashtables that provide references to * defined units. * * @author Lee Mericle, based on java version by Gunther Schadow * */ var Ucum = require('./config.js').Ucum; class UnitTablesFactory { /** * Constructor. This creates the empty unit tables (hashes) once. After the * tables are created, it redefines this constructor to throw an error * stating that the constructor is no longer available and that the * getInstance function must be used. Here's a description of the first * and then all subsequent calls to this constructor. * * First call to constructor: * 1. creates OBJECT1 * 2. initializes attributes of OBJECT1 * 3. stores reference to OBJECT1.prototype in holdthis local variable * 4. redefines OBJECT1 as a function that throws an error * 5. defines the getInstance function (which is also defined outside of * the class definition - see below). * * All subsequent calls to constructor: * 1. throw error message referring to getInstance * 2. call getInstance, returns this - which is OBJECT1. */ constructor() { /** * Tracks units by name * @type hash - key is the name; * value is an array of references to the Unit objects * with the name. More than one unit may have the same * name, e.g., "second", which is shared by the base unit * with the code = "s" and the unit with code = "'". */ this.unitNames_ = {}; /** * Tracks units by code using case-sensitive version. * * @type hash - key is the code; * value is the reference to the Unit object. Codes must * be unique. */ this.unitCodes_ = {}; /** * Keeps track of the order in which units are defined. The order is * important because unit definitions build on previous definitions. * * @type {Array} */ this.codeOrder_ = []; /** * Tracks units by unit strings, e.g., cm-1 * * @type hash - key is the unit string * value is an array of unit objects with that ciUnitString. */ this.unitStrings_ = {}; /** * Tracks units by Dimension vector * * @type hash - key is the dimension vector (not the object, just the * vector); * value is an array of references to the Unit objects * with that vector. More than one unit may have the same * unit vector, and this can be used to provide a list * of commensurable units. */ this.unitDimensions_ = {}; /** * Maps synonyms to units. Not built until first requested. * * @type hash - key is the synonym * value is an array of references to Unit objects that * include that synonym. */ this.unitSynonyms_ = {}; /* * Holds onto the index of the index of the dimension vector flag for * the base mass unit (gram). This is set when the base unit (gram) is * created, and is stored here so that it doesn't have to be found * over and over again to try to determine whether or not a unit is * mass-based (for mole<->mass conversions) * * @type integer */ this.massDimIndex_ = 0; } /** * Provides the number of unit objects written to the tables, using the * codes table since codes must be unique. * * @returns count of the number of unit objects in the unitCodes_ table. */ unitsCount() { return Object.keys(this.unitCodes_).length; } /** * Adds a Unit object to the tables. * * @param theUnit the unit to be added * @returns nothing * @throws passes on an error if one is thrown by the called functions for * a problem with the unit code or unit name */ addUnit(theUnit) { let uName = theUnit['name_']; if (uName) { this.addUnitName(theUnit); } this.addUnitCode(theUnit); this.addUnitString(theUnit); try { if (theUnit['dim_'].getProperty('dimVec_')) this.addUnitDimension(theUnit); } catch (err) {// do nothing - throws error if the property is null // and that's OK here. } } // end addUnit /** * Adds a Unit object to the unitNames_ table. More than one unit * can have the same name, e.g., the two units with the name "second", * where the code for one of them is 's' and the code for the other is * "'". Because of this, an array of unit objects is stored for the * name. In most cases it will be an array of one object, but this * clarifies that there may be more than one. * * @param theUnit the unit to be added * @returns nothing * @throws an error if the unit has no name */ addUnitName(theUnit) { let uName = theUnit['name_']; if (uName) { if (this.unitNames_[uName]) this.unitNames_[uName].push(theUnit);else this.unitNames_[uName] = [theUnit]; } else throw new Error('UnitTables.addUnitName called for a unit with no name. ' + `Unit code = ${theUnit['csCode_']}.`); } // end addUnitName /** * Adds a Unit object to the unitCodes_, unitUcCodes_, unitLcCodes_ and * codeOrder_ tables. This also sets the mass dimension index when the * base mass unit (gram) is read. * * @param theUnit the unit to be added * @returns nothing * @throws an error if the unitCodes_ table already contains a unit with * the code */ addUnitCode(theUnit) { let uCode = theUnit['csCode_']; if (uCode) { if (this.unitCodes_[uCode]) throw new Error(`UnitTables.addUnitCode called, already contains entry for ` + `unit with code = ${uCode}`);else { this.unitCodes_[uCode] = theUnit; this.codeOrder_.push(uCode); if (uCode == 'g') { let dimVec = theUnit.dim_.dimVec_; let d = 0; for (; d < dimVec.length && dimVec[d] < 1; d++); this.massDimIndex_ = d; } } } else throw new Error('UnitTables.addUnitCode called for unit that has ' + 'no code.'); } // end addUnitCode /** * Adds a unit object to the unitStrings_ table. More than one unit * can have the same string, so an array of unit objects is stored * for the string. The unit string is the string that creates a non-base * unit, e.g., a Newton has a unit code of N, a name of Newton, and a * unitString of kg.m/s2. * * If the unit has no string, nothing is stored and no error is reported. * * @param theUnit the unit to be added * @returns nothing */ addUnitString(theUnit) { let uString = null; if (Ucum.caseSensitive_ == true) uString = theUnit['csUnitString_'];else uString = theUnit['ciUnitString_']; if (uString) { let uEntry = { mag: theUnit['baseFactorStr_'], unit: theUnit }; if (this.unitStrings_[uString]) this.unitStrings_[uString].push(uEntry);else this.unitStrings_[uString] = [uEntry]; } } // end addUnitString /** * Adds a Unit object to the unitDimensions_ table. More than one unit * can have the same dimension (commensurable units have the same dimension). * Because of this, an array of unit objects is stored for the * dimension. * * @param theUnit the unit to be added * @returns nothing * @throws an error if the unit has no dimension */ addUnitDimension(theUnit) { let uDim = theUnit['dim_'].getProperty('dimVec_'); if (uDim) { if (this.unitDimensions_[uDim]) this.unitDimensions_[uDim].push(theUnit);else this.unitDimensions_[uDim] = [theUnit]; } else throw new Error('UnitTables.addUnitDimension called for a unit with no dimension. ' + `Unit code = ${theUnit['csCode_']}.`); } // end addUnitDimension /** * Builds the unitSynonyms_ table. This is called the first time the * getUnitsBySynonym method is called. The table/hash contains each word * (once) from each synonym as well as each word from each unit name. * * Hash keys are the words. Hash values are an array of unit codes for * each unit that has that word in its synonyms or name. * * @returns nothing */ buildUnitSynonyms() { for (let code in this.unitCodes_) { let theUnit = this.unitCodes_[code]; let uSyns = theUnit.synonyms_; // If the current unit has synonyms, process each synonym (often multiples) if (uSyns) { let synsAry = uSyns.split(';'); if (synsAry[0] !== '') { let aLen = synsAry.length; for (let a = 0; a < aLen; a++) { let theSyn = synsAry[a].trim(); // call addSynonymCodes to process each word in the // synonym, e.g., "British fluid ounces" this.addSynonymCodes(code, theSyn); } // end do for each synonym } // end if the current unit has a non-null synonym attribute } // end if the unit has any synonyms // Now call addSynonymCodes to process each word in the unit's name this.addSynonymCodes(code, theUnit.name_); } // end do for each unit } // end buildUnitSynonyms /** * Adds unit code entries to the synonyms table for a string containing * one or more words to be considered as synonyms. * * @param theCode the unit code to be connected to the synonyms * @param theSynonyms a string containing one or more words to be * considered synonyms (and thus to be added to the unitSynonyms hash). */ addSynonymCodes(theCode, theSynonyms) { let words = theSynonyms.split(' '); let wLen = words.length; for (let w = 0; w < wLen; w++) { let word = words[w]; // if there is already a synonyms entry for the word, // get the array of unit codes currently assigned to // the word and add the code for the current word to // the synonyms array if it's not already there. if (this.unitSynonyms_[word]) { let synCodes = this.unitSynonyms_[word]; if (synCodes.indexOf(theCode) === -1) { this.unitSynonyms_[word].push(theCode); } } // else there are no synonyms entry for the word. Create a // synonyms array for the word, setting it to contain the unit code. else { this.unitSynonyms_[word] = [theCode]; } } // end do for each word in the synonyms being processed } // end addSynonymCodes /** * Returns a unit object with a case-sensitive code matching the * uCode parameter, or null if no unit is found with that code. * * @param uCode the code of the unit to be returned * @returns the unit object or null if it is not found */ getUnitByCode(uCode) { let retUnit = null; if (uCode) { retUnit = this.unitCodes_[uCode]; } return retUnit; } /** * Returns a array of unit objects based on the unit's name. Usually this * will be an array of one, but there may be more, since unit names are * not necessarily unique. * * @param uName the name of the unit to be returned. If more than one * unit has the same name and you only want one specific unit, append the * csCode of the unit you want to the end of the name, separated by the * Ucum.codeSep_ value, e.g., inch - [in_i] vs. inch - [in_us]. * @returns null if no unit was found for the specified name OR an array of * unit objects with the specified name. Normally this will be an array * of one object. * @throws an error if no name is provided to search on */ getUnitByName(uName) { if (uName === null || uName === undefined) { throw new Error('Unable to find unit by name because no name was provided.'); } let sepPos = uName.indexOf(Ucum.codeSep_); let uCode = null; if (sepPos >= 1) { uCode = uName.substr(sepPos + Ucum.codeSep_.length); uName = uName.substr(0, sepPos); } let retUnits = this.unitNames_[uName]; if (retUnits) { let uLen = retUnits.length; if (uCode && uLen > 1) { let i = 0; for (; retUnits[i].csCode_ !== uCode && i < uLen; i++); if (i < uLen) retUnits = [retUnits[i]];else { retUnits = null; } } // end if we need to find both a name and a code } // end if we got an array of units return retUnits; } // end getUnitByName /** * Returns an array of unit objects with the specified unit string. * The array may contain one or more unit reference objects. * Or none, if no units have a matching unit string (which is not * considered an error) * * @param name the name of the unit to be returned * @returns the array of unit references or null if none were found */ getUnitByString(uString) { let retAry = null; if (uString) { retAry = this.unitStrings_[uString]; if (retAry === undefined) retAry = null; } return retAry; } /** * Returns a array of unit objects based on the unit's dimension vector. * * @param uName the dimension vector of the units to be returned. * * @returns null if no unit was found for the specified vector OR an array of * one or more unit objects with the specified vector. * @throws an error if no vector is provided to search on * logs an error to the console if no unit is found */ getUnitsByDimension(uDim) { let unitsArray = null; if (uDim === null || uDim === undefined) { throw new Error('Unable to find unit by because no dimension ' + 'vector was provided.'); } unitsArray = this.unitDimensions_[uDim]; if (unitsArray === undefined || unitsArray === null) { console.log(`Unable to find unit with dimension = ${uDim}`); } return unitsArray; } // end getUnitsByDimension /** * Returns a array of unit objects that include the specified synonym. * * @param uSyn the synonym of the units to be returned. * * @returns an object with two of the following three elements: * 'status' will be error, failed or succeeded * 'msg' will be included for returns with status = error or failed and * will explain why the request did not return any units * 'units' any array of unit objects with the specified synonym will be * returned for requests with status = succeeded */ getUnitBySynonym(uSyn) { let retObj = {}; let unitsArray = []; try { if (uSyn === null || uSyn === undefined) { retObj['status'] = 'error'; throw new Error('Unable to find unit by synonym because no synonym ' + 'was provided.'); } // If this is the first request for a unit by synonym, build the hash map if (Object.keys(this.unitSynonyms_).length === 0) { this.buildUnitSynonyms(); } let foundCodes = []; foundCodes = this.unitSynonyms_[uSyn]; if (foundCodes) { retObj['status'] = 'succeeded'; let fLen = foundCodes.length; for (let f = 0; f < fLen; f++) { unitsArray.push(this.unitCodes_[foundCodes[f]]); } retObj['units'] = unitsArray; } if (unitsArray.length === 0) { retObj['status'] = 'failed'; retObj['msg'] = `Unable to find any units with synonym = ${uSyn}`; } } catch (err) { retObj['msg'] = err.message; } return retObj; } // end getUnitBySynonym /** * Gets a list of all unit names in the Unit tables * * @returns an array of the unit names */ getAllUnitNames() { return Object.keys(this.unitNames_); } // end getAllUnitNames /** * Gets a list of all unit names in the tables. Where more than one * unit has the same name, the unit code, in parentheses, is appended * to the end of the name. * * @returns {Array} */ getUnitNamesList() { let nameList = []; let codes = Object.keys(this.unitCodes_); codes.sort(this.compareCodes); let uLen = codes.length; for (let i = 0; i < uLen; i++) { nameList[i] = codes[i] + Ucum.codeSep_ + this.unitCodes_[codes[i]].name_; } // end do for each code return nameList; } /* * Returns the mass dimension index * @returns this.massDimIndex_ */ getMassDimensionIndex() { return this.massDimIndex_; } /** * This provides a sort function for unit codes so that sorting ignores * square brackets and case. * * @param a first value * @param b second value * @returns -1 if a is should fall before b; otherwise 1. */ compareCodes(a, b) { a = a.replace(/[\[\]]/g, ''); a = a.toLowerCase(); b = b.replace(/[\[\]]/g, ''); b = b.toLowerCase(); return a < b ? -1 : 1; } /** * Gets a list of all unit codes in the Unit tables * * @returns an array of the unit names */ getAllUnitCodes() { return Object.keys(this.unitCodes_); } // end getAllUnitNames /** * This is used to get all unit objects. Currently it is used * to get the objects to write to the json ucum definitions file * that is used to provide prefix and unit definition objects for * conversions and validations. * * @returns an array containing all unit objects, ordered by definition * order */ allUnitsByDef() { let unitsList = []; let uLen = this.codeOrder_.length; for (let u = 0; u < uLen; u++) { unitsList.push(this.getUnitByCode(this.codeOrder_[u])); } return unitsList; } // end allUnitsByDef /** * This is used to get all unit objects, ordered by unit name. Currently it * is used to create a csv list of all units. * @param sep separator character (or string) to be used to separate each * column in the output. Optional, defaults to '|' if not specified. * (Used to use ; but the synonyms use that extensively). Don't use a * comma or any other punctuation found in the output data. * @returns a buffer containing all unit objects, ordered by name * order */ allUnitsByName(cols, sep) { if (sep === undefined || sep === null) sep = '|'; let unitBuff = ''; let unitsList = this.getAllUnitNames(); let uLen = unitsList.length; let cLen = cols.length; for (let i = 0; i < uLen; i++) { let nameRecs = this.getUnitByName(unitsList[i]); for (let u = 0; u < nameRecs.length; u++) { let rec = nameRecs[u]; for (let c = 0; c < cLen; c++) { if (c > 0) unitBuff += sep; if (cols[c] === 'dim_') { if (rec.dim_ !== null && rec.dim_ !== undefined && rec.dim_.dimVec_ instanceof Array) unitBuff += '[' + rec.dim_.dimVec_.join(',') + ']';else unitBuff += ''; } else { let cbuf = rec[cols[c]]; if (typeof cbuf === 'string') unitBuff += cbuf.replace(/[\n\r]/g, ' ');else unitBuff += cbuf; } } // end do for each column requested unitBuff += '\r\n'; } // end do for each unit in the unit names array } return unitBuff; } // end allUnitsByName /** * This creates a list of all units in the tables. It uses the byCode * table, and uses the codeOrder_ array to determine the order in which * the units are listed. * * @param doLong boolean indicating how much to output. If true, all data * from the unit objects is included. If false, only a few major values * are included. * @param sep separator character (or string) to be used to separate each * column in the output. Optional, defaults to '|' if not specified. * (Used to use ; but the synonyms use that extensively). * @returns {string} buffer containing all the listings */ printUnits(doLong, sep) { if (doLong === undefined) doLong = false; if (sep === undefined) sep = '|'; let codeList = ''; let uLen = this.codeOrder_.length; let unitString = 'csCode' + sep; if (doLong) { unitString += 'ciCode' + sep; } unitString += 'name' + sep; if (doLong) unitString += 'isBase' + sep; unitString += 'magnitude' + sep + 'dimension' + sep + 'from unit(s)' + sep + 'value' + sep + 'function' + sep; if (doLong) unitString += 'property' + sep + 'printSymbol' + sep + 'synonyms' + sep + 'source' + sep + 'class' + sep + 'isMetric' + sep + 'variable' + sep + 'isSpecial' + sep + 'isAbitrary' + sep; unitString += 'comment'; codeList = unitString + '\n'; for (let u = 0; u < uLen; u++) { let curUnit = this.getUnitByCode(this.codeOrder_[u]); unitString = this.codeOrder_[u] + sep; if (doLong) { unitString += curUnit.getProperty('ciCode_') + sep; } unitString += curUnit.getProperty('name_') + sep; if (doLong) { if (curUnit.getProperty('isBase_')) unitString += 'true' + sep;else unitString += 'false' + sep; } unitString += curUnit.getProperty('magnitude_') + sep; let curDim = curUnit.getProperty('dim_'); if (curDim) { unitString += curDim.dimVec_ + sep; } else { unitString += 'null' + sep; } if (curUnit.csUnitString_) unitString += curUnit.csUnitString_ + sep + curUnit.baseFactor_ + sep;else unitString += 'null' + sep + 'null' + sep; if (curUnit.cnv_) unitString += curUnit.cnv_ + sep;else unitString += 'null' + sep; if (doLong) { unitString += curUnit.getProperty('property_') + sep + curUnit.getProperty('printSymbol_') + sep + curUnit.getProperty('synonyms_') + sep + curUnit.getProperty('source_') + sep + curUnit.getProperty('class_') + sep + curUnit.getProperty('isMetric_') + sep + curUnit.getProperty('variable_') + sep + curUnit.getProperty('isSpecial_') + sep + curUnit.getProperty('isArbitrary_') + sep; } if (curUnit.defError_) unitString += 'problem parsing this one, deferred to later.'; codeList += unitString + '\n'; } return codeList; } } // end UnitTablesFactory // Create a singleton instance and (to preserve the existing API) an object that // provides that instance via getInstance(). var unitTablesInstance = new UnitTablesFactory(); const UnitTables = { getInstance: function () { return unitTablesInstance; } }; exports.UnitTables = UnitTables; },{"./config.js":90}],103:[function(require,module,exports){ (function (global){(function (){ 'use strict'; var objectAssign = require('object-assign'); // compare and isBuffer 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; } function isBuffer(b) { if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { return global.Buffer.isBuffer(b); } return !!(b != null && b._isBuffer); } // based on node assert, original notice: // NB: The URL to the CommonJS spec is kept just for tradition. // node-assert has evolved a lot since then, both in API and behavior. // http://wiki.commonjs.org/wiki/Unit_Testing/1.0 // // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! // // 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. var util = require('util/'); var hasOwn = Object.prototype.hasOwnProperty; var pSlice = Array.prototype.slice; var functionsHaveNames = (function () { return function foo() {}.name === 'foo'; }()); function pToString (obj) { return Object.prototype.toString.call(obj); } function isView(arrbuf) { if (isBuffer(arrbuf)) { return false; } if (typeof global.ArrayBuffer !== 'function') { return false; } if (typeof ArrayBuffer.isView === 'function') { return ArrayBuffer.isView(arrbuf); } if (!arrbuf) { return false; } if (arrbuf instanceof DataView) { return true; } if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { return true; } return false; } // 1. 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; // 2. The AssertionError is defined in assert. // new assert.AssertionError({ message: message, // actual: actual, // expected: expected }) var regex = /\s*function\s+([^\(\s]*)\s*/; // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js function getName(func) { if (!util.isFunction(func)) { return; } if (functionsHaveNames) { return func.name; } var str = func.toString(); var match = str.match(regex); return match && match[1]; } assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; if (options.message) { this.message = options.message; this.generatedMessage = false; } else { this.message = getMessage(this); this.generatedMessage = true; } var stackStartFunction = options.stackStartFunction || fail; if (Error.captureStackTrace) { Error.captureStackTrace(this, stackStartFunction); } else { // non v8 browsers so we can have a stacktrace var err = new Error(); if (err.stack) { var out = err.stack; // try to strip useless frames var fn_name = getName(stackStartFunction); var idx = out.indexOf('\n' + fn_name); if (idx >= 0) { // once we have located the function frame // we need to strip out everything before it (and its line) var next_line = out.indexOf('\n', idx + 1); out = out.substring(next_line + 1); } this.stack = out; } } }; // assert.AssertionError instanceof Error util.inherits(assert.AssertionError, Error); function truncate(s, n) { if (typeof s === 'string') { return s.length < n ? s : s.slice(0, n); } else { return s; } } function inspect(something) { if (functionsHaveNames || !util.isFunction(something)) { return util.inspect(something); } var rawname = getName(something); var name = rawname ? ': ' + rawname : ''; return '[Function' + name + ']'; } function getMessage(self) { return truncate(inspect(self.actual), 128) + ' ' + self.operator + ' ' + truncate(inspect(self.expected), 128); } // At present only the three keys mentioned above are used and // understood by the spec. Implementations or sub modules can pass // other keys to the AssertionError's constructor - they will be // ignored. // 3. 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 fail(actual, expected, message, operator, stackStartFunction) { throw new assert.AssertionError({ message: message, actual: actual, expected: expected, operator: operator, stackStartFunction: stackStartFunction }); } // EXTENSION! allows for well behaved errors defined elsewhere. assert.fail = fail; // 4. Pure assertion tests whether a value is truthy, as determined // by !!guard. // assert.ok(guard, message_opt); // This statement is equivalent to assert.equal(true, !!guard, // message_opt);. To test strictly for the value true, use // assert.strictEqual(true, guard, message_opt);. function ok(value, message) { if (!value) fail(value, true, message, '==', assert.ok); } assert.ok = ok; // 5. The equality assertion tests shallow, coercive equality with // ==. // assert.equal(actual, expected, message_opt); assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; // 6. The non-equality assertion tests for whether two objects are not equal // with != assert.notEqual(actual, expected, message_opt); assert.notEqual = function notEqual(actual, expected, message) { if (actual == expected) { fail(actual, expected, message, '!=', assert.notEqual); } }; // 7. The equivalence assertion tests a deep equality relation. // assert.deepEqual(actual, expected, message_opt); assert.deepEqual = function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected, false)) { fail(actual, expected, message, 'deepEqual', assert.deepEqual); } }; assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { if (!_deepEqual(actual, expected, true)) { fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); } }; function _deepEqual(actual, expected, strict, memos) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (isBuffer(actual) && isBuffer(expected)) { return compare(actual, expected) === 0; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (util.isDate(actual) && util.isDate(expected)) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). } else if (util.isRegExp(actual) && util.isRegExp(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; // 7.4. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if ((actual === null || typeof actual !== 'object') && (expected === null || typeof expected !== 'object')) { return strict ? actual === expected : actual == expected; // If both values are instances of typed arrays, wrap their underlying // ArrayBuffers in a Buffer each to increase performance // This optimization requires the arrays to have the same type as checked by // Object.prototype.toString (aka pToString). Never perform binary // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their // bit patterns are not identical. } else if (isView(actual) && isView(expected) && pToString(actual) === pToString(expected) && !(actual instanceof Float32Array || actual instanceof Float64Array)) { return compare(new Uint8Array(actual.buffer), new Uint8Array(expected.buffer)) === 0; // 7.5 For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else if (isBuffer(actual) !== isBuffer(expected)) { return false; } else { memos = memos || {actual: [], expected: []}; var actualIndex = memos.actual.indexOf(actual); if (actualIndex !== -1) { if (actualIndex === memos.expected.indexOf(expected)) { return true; } } memos.actual.push(actual); memos.expected.push(expected); return objEquiv(actual, expected, strict, memos); } } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b, strict, actualVisitedObjects) { if (a === null || a === undefined || b === null || b === undefined) return false; // if one is a primitive, the other must be same if (util.isPrimitive(a) || util.isPrimitive(b)) return a === b; if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false; var aIsArgs = isArguments(a); var bIsArgs = isArguments(b); if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) return false; if (aIsArgs) { a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b, strict); } var ka = objectKeys(a); var kb = objectKeys(b); var key, i; // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length !== kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] !== kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) return false; } return true; } // 8. The non-equivalence assertion tests for any deep inequality. // assert.notDeepEqual(actual, expected, message_opt); assert.notDeepEqual = function notDeepEqual(actual, expected, message) { if (_deepEqual(actual, expected, false)) { fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); } }; assert.notDeepStrictEqual = notDeepStrictEqual; function notDeepStrictEqual(actual, expected, message) { if (_deepEqual(actual, expected, true)) { fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); } } // 9. The strict equality assertion tests strict equality, as determined by ===. // assert.strictEqual(actual, expected, message_opt); assert.strictEqual = function strictEqual(actual, expected, message) { if (actual !== expected) { fail(actual, expected, message, '===', assert.strictEqual); } }; // 10. The strict non-equality assertion tests for strict inequality, as // determined by !==. assert.notStrictEqual(actual, expected, message_opt); assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (actual === expected) { fail(actual, expected, message, '!==', assert.notStrictEqual); } }; function expectedException(actual, expected) { if (!actual || !expected) { return false; } if (Object.prototype.toString.call(expected) == '[object RegExp]') { return expected.test(actual); } try { if (actual instanceof expected) { return true; } } catch (e) { // Ignore. The instanceof check doesn't work for arrow functions. } if (Error.isPrototypeOf(expected)) { return false; } return expected.call({}, actual) === true; } function _tryBlock(block) { var error; try { block(); } catch (e) { error = e; } return error; } function _throws(shouldThrow, block, expected, message) { var actual; if (typeof block !== 'function') { throw new TypeError('"block" argument must be a function'); } if (typeof expected === 'string') { message = expected; expected = null; } actual = _tryBlock(block); message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); if (shouldThrow && !actual) { fail(actual, expected, 'Missing expected exception' + message); } var userProvidedMessage = typeof message === 'string'; var isUnwantedException = !shouldThrow && util.isError(actual); var isUnexpectedException = !shouldThrow && actual && !expected; if ((isUnwantedException && userProvidedMessage && expectedException(actual, expected)) || isUnexpectedException) { fail(actual, expected, 'Got unwanted exception' + message); } if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { throw actual; } } // 11. Expected to throw an error: // assert.throws(block, Error_opt, message_opt); assert.throws = function(block, /*optional*/error, /*optional*/message) { _throws(true, block, error, message); }; // EXTENSION! This is annoying to write outside this module. assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { _throws(false, block, error, message); }; assert.ifError = function(err) { if (err) throw err; }; // Expose a strict only variant of assert function strict(value, message) { if (!value) fail(value, true, message, '==', strict); } assert.strict = objectAssign(strict, assert, { equal: assert.strictEqual, deepEqual: assert.deepStrictEqual, notEqual: assert.notStrictEqual, notDeepEqual: assert.notDeepStrictEqual }); assert.strict.strict = assert.strict; var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { if (hasOwn.call(obj, key)) keys.push(key); } return keys; }; }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"object-assign":324,"util/":106}],104:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],105:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } },{}],106:[function(require,module,exports){ (function (process,global){(function (){ // 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 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) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.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 '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + 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()`. 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; 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; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = require('./support/isBuffer'); 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 = require('inherits'); 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); } }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./support/isBuffer":105,"_process":325,"inherits":104}],107:[function(require,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('') } },{}],108:[function(require,module,exports){ (function (process,global,setImmediate){(function (){ /* @preserve * The MIT License (MIT) * * Copyright (c) 2013-2017 Petka Antonov * * 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. * */ /** * bluebird build version 3.5.1 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0) { var fn = queue.shift(); if (typeof fn !== "function") { fn._settlePromises(); continue; } var receiver = queue.shift(); var arg = queue.shift(); fn.call(receiver, arg); } }; Async.prototype._drainQueues = function () { this._drainQueue(this._normalQueue); this._reset(); this._haveDrainedQueues = true; this._drainQueue(this._lateQueue); }; Async.prototype._queueTick = function () { if (!this._isTickUsed) { this._isTickUsed = true; this._schedule(this.drainQueues); } }; Async.prototype._reset = function () { this._isTickUsed = false; }; module.exports = Async; module.exports.firstLineError = firstLineError; },{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { var calledBind = false; var rejectThis = function(_, e) { this._reject(e); }; var targetRejected = function(e, context) { context.promiseRejectionQueued = true; context.bindingPromise._then(rejectThis, rejectThis, null, this, e); }; var bindingResolved = function(thisArg, context) { if (((this._bitField & 50397184) === 0)) { this._resolveCallback(context.target); } }; var bindingRejected = function(e, context) { if (!context.promiseRejectionQueued) this._reject(e); }; Promise.prototype.bind = function (thisArg) { if (!calledBind) { calledBind = true; Promise.prototype._propagateFrom = debug.propagateFromFunction(); Promise.prototype._boundValue = debug.boundValueFunction(); } var maybePromise = tryConvertToPromise(thisArg); var ret = new Promise(INTERNAL); ret._propagateFrom(this, 1); var target = this._target(); ret._setBoundTo(maybePromise); if (maybePromise instanceof Promise) { var context = { promiseRejectionQueued: false, promise: ret, target: target, bindingPromise: maybePromise }; target._then(INTERNAL, targetRejected, undefined, ret, context); maybePromise._then( bindingResolved, bindingRejected, undefined, ret, context); ret._setOnCancel(maybePromise); } else { ret._resolveCallback(target); } return ret; }; Promise.prototype._setBoundTo = function (obj) { if (obj !== undefined) { this._bitField = this._bitField | 2097152; this._boundTo = obj; } else { this._bitField = this._bitField & (~2097152); } }; Promise.prototype._isBound = function () { return (this._bitField & 2097152) === 2097152; }; Promise.bind = function (thisArg, value) { return Promise.resolve(value).bind(thisArg); }; }; },{}],4:[function(_dereq_,module,exports){ "use strict"; var old; if (typeof Promise !== "undefined") old = Promise; function noConflict() { try { if (Promise === bluebird) Promise = old; } catch (e) {} return bluebird; } var bluebird = _dereq_("./promise")(); bluebird.noConflict = noConflict; module.exports = bluebird; },{"./promise":22}],5:[function(_dereq_,module,exports){ "use strict"; var cr = Object.create; if (cr) { var callerCache = cr(null); var getterCache = cr(null); callerCache[" size"] = getterCache[" size"] = 0; } module.exports = function(Promise) { var util = _dereq_("./util"); var canEvaluate = util.canEvaluate; var isIdentifier = util.isIdentifier; var getMethodCaller; var getGetter; if (!true) { var makeMethodCaller = function (methodName) { return new Function("ensureMethod", " \n\ return function(obj) { \n\ 'use strict' \n\ var len = this.length; \n\ ensureMethod(obj, 'methodName'); \n\ switch(len) { \n\ case 1: return obj.methodName(this[0]); \n\ case 2: return obj.methodName(this[0], this[1]); \n\ case 3: return obj.methodName(this[0], this[1], this[2]); \n\ case 0: return obj.methodName(); \n\ default: \n\ return obj.methodName.apply(obj, this); \n\ } \n\ }; \n\ ".replace(/methodName/g, methodName))(ensureMethod); }; var makeGetter = function (propertyName) { return new Function("obj", " \n\ 'use strict'; \n\ return obj.propertyName; \n\ ".replace("propertyName", propertyName)); }; var getCompiled = function(name, compiler, cache) { var ret = cache[name]; if (typeof ret !== "function") { if (!isIdentifier(name)) { return null; } ret = compiler(name); cache[name] = ret; cache[" size"]++; if (cache[" size"] > 512) { var keys = Object.keys(cache); for (var i = 0; i < 256; ++i) delete cache[keys[i]]; cache[" size"] = keys.length - 256; } } return ret; }; getMethodCaller = function(name) { return getCompiled(name, makeMethodCaller, callerCache); }; getGetter = function(name) { return getCompiled(name, makeGetter, getterCache); }; } function ensureMethod(obj, methodName) { var fn; if (obj != null) fn = obj[methodName]; if (typeof fn !== "function") { var message = "Object " + util.classString(obj) + " has no method '" + util.toString(methodName) + "'"; throw new Promise.TypeError(message); } return fn; } function caller(obj) { var methodName = this.pop(); var fn = ensureMethod(obj, methodName); return fn.apply(obj, this); } Promise.prototype.call = function (methodName) { var args = [].slice.call(arguments, 1);; if (!true) { if (canEvaluate) { var maybeCaller = getMethodCaller(methodName); if (maybeCaller !== null) { return this._then( maybeCaller, undefined, undefined, args, undefined); } } } args.push(methodName); return this._then(caller, undefined, undefined, args, undefined); }; function namedGetter(obj) { return obj[this]; } function indexedGetter(obj) { var index = +this; if (index < 0) index = Math.max(0, index + obj.length); return obj[index]; } Promise.prototype.get = function (propertyName) { var isIndex = (typeof propertyName === "number"); var getter; if (!isIndex) { if (canEvaluate) { var maybeGetter = getGetter(propertyName); getter = maybeGetter !== null ? maybeGetter : namedGetter; } else { getter = namedGetter; } } else { getter = indexedGetter; } return this._then(getter, undefined, undefined, propertyName, undefined); }; }; },{"./util":36}],6:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, debug) { var util = _dereq_("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var async = Promise._async; Promise.prototype["break"] = Promise.prototype.cancel = function() { if (!debug.cancellation()) return this._warn("cancellation is disabled"); var promise = this; var child = promise; while (promise._isCancellable()) { if (!promise._cancelBy(child)) { if (child._isFollowing()) { child._followee().cancel(); } else { child._cancelBranched(); } break; } var parent = promise._cancellationParent; if (parent == null || !parent._isCancellable()) { if (promise._isFollowing()) { promise._followee().cancel(); } else { promise._cancelBranched(); } break; } else { if (promise._isFollowing()) promise._followee().cancel(); promise._setWillBeCancelled(); child = promise; promise = parent; } } }; Promise.prototype._branchHasCancelled = function() { this._branchesRemainingToCancel--; }; Promise.prototype._enoughBranchesHaveCancelled = function() { return this._branchesRemainingToCancel === undefined || this._branchesRemainingToCancel <= 0; }; Promise.prototype._cancelBy = function(canceller) { if (canceller === this) { this._branchesRemainingToCancel = 0; this._invokeOnCancel(); return true; } else { this._branchHasCancelled(); if (this._enoughBranchesHaveCancelled()) { this._invokeOnCancel(); return true; } } return false; }; Promise.prototype._cancelBranched = function() { if (this._enoughBranchesHaveCancelled()) { this._cancel(); } }; Promise.prototype._cancel = function() { if (!this._isCancellable()) return; this._setCancelled(); async.invoke(this._cancelPromises, this, undefined); }; Promise.prototype._cancelPromises = function() { if (this._length() > 0) this._settlePromises(); }; Promise.prototype._unsetOnCancel = function() { this._onCancelField = undefined; }; Promise.prototype._isCancellable = function() { return this.isPending() && !this._isCancelled(); }; Promise.prototype.isCancellable = function() { return this.isPending() && !this.isCancelled(); }; Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { if (util.isArray(onCancelCallback)) { for (var i = 0; i < onCancelCallback.length; ++i) { this._doInvokeOnCancel(onCancelCallback[i], internalOnly); } } else if (onCancelCallback !== undefined) { if (typeof onCancelCallback === "function") { if (!internalOnly) { var e = tryCatch(onCancelCallback).call(this._boundValue()); if (e === errorObj) { this._attachExtraTrace(e.e); async.throwLater(e.e); } } } else { onCancelCallback._resultCancelled(this); } } }; Promise.prototype._invokeOnCancel = function() { var onCancelCallback = this._onCancel(); this._unsetOnCancel(); async.invoke(this._doInvokeOnCancel, this, onCancelCallback); }; Promise.prototype._invokeInternalOnCancel = function() { if (this._isCancellable()) { this._doInvokeOnCancel(this._onCancel(), true); this._unsetOnCancel(); } }; Promise.prototype._resultCancelled = function() { this.cancel(); }; }; },{"./util":36}],7:[function(_dereq_,module,exports){ "use strict"; module.exports = function(NEXT_FILTER) { var util = _dereq_("./util"); var getKeys = _dereq_("./es5").keys; var tryCatch = util.tryCatch; var errorObj = util.errorObj; function catchFilter(instances, cb, promise) { return function(e) { var boundTo = promise._boundValue(); predicateLoop: for (var i = 0; i < instances.length; ++i) { var item = instances[i]; if (item === Error || (item != null && item.prototype instanceof Error)) { if (e instanceof item) { return tryCatch(cb).call(boundTo, e); } } else if (typeof item === "function") { var matchesPredicate = tryCatch(item).call(boundTo, e); if (matchesPredicate === errorObj) { return matchesPredicate; } else if (matchesPredicate) { return tryCatch(cb).call(boundTo, e); } } else if (util.isObject(e)) { var keys = getKeys(item); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; if (item[key] != e[key]) { continue predicateLoop; } } return tryCatch(cb).call(boundTo, e); } } return NEXT_FILTER; }; } return catchFilter; }; },{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var longStackTraces = false; var contextStack = []; Promise.prototype._promiseCreated = function() {}; Promise.prototype._pushContext = function() {}; Promise.prototype._popContext = function() {return null;}; Promise._peekContext = Promise.prototype._peekContext = function() {}; function Context() { this._trace = new Context.CapturedTrace(peekContext()); } Context.prototype._pushContext = function () { if (this._trace !== undefined) { this._trace._promiseCreated = null; contextStack.push(this._trace); } }; Context.prototype._popContext = function () { if (this._trace !== undefined) { var trace = contextStack.pop(); var ret = trace._promiseCreated; trace._promiseCreated = null; return ret; } return null; }; function createContext() { if (longStackTraces) return new Context(); } function peekContext() { var lastIndex = contextStack.length - 1; if (lastIndex >= 0) { return contextStack[lastIndex]; } return undefined; } Context.CapturedTrace = null; Context.create = createContext; Context.deactivateLongStackTraces = function() {}; Context.activateLongStackTraces = function() { var Promise_pushContext = Promise.prototype._pushContext; var Promise_popContext = Promise.prototype._popContext; var Promise_PeekContext = Promise._peekContext; var Promise_peekContext = Promise.prototype._peekContext; var Promise_promiseCreated = Promise.prototype._promiseCreated; Context.deactivateLongStackTraces = function() { Promise.prototype._pushContext = Promise_pushContext; Promise.prototype._popContext = Promise_popContext; Promise._peekContext = Promise_PeekContext; Promise.prototype._peekContext = Promise_peekContext; Promise.prototype._promiseCreated = Promise_promiseCreated; longStackTraces = false; }; longStackTraces = true; Promise.prototype._pushContext = Context.prototype._pushContext; Promise.prototype._popContext = Context.prototype._popContext; Promise._peekContext = Promise.prototype._peekContext = peekContext; Promise.prototype._promiseCreated = function() { var ctx = this._peekContext(); if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; }; }; return Context; }; },{}],9:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, Context) { var getDomain = Promise._getDomain; var async = Promise._async; var Warning = _dereq_("./errors").Warning; var util = _dereq_("./util"); var canAttachTrace = util.canAttachTrace; var unhandledRejectionHandled; var possiblyUnhandledRejection; var bluebirdFramePattern = /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; var stackFramePattern = null; var formatStack = null; var indentStackFrames = false; var printWarning; var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && (true || util.env("BLUEBIRD_DEBUG") || util.env("NODE_ENV") === "development")); var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && (debugging || util.env("BLUEBIRD_WARNINGS"))); var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); Promise.prototype.suppressUnhandledRejections = function() { var target = this._target(); target._bitField = ((target._bitField & (~1048576)) | 524288); }; Promise.prototype._ensurePossibleRejectionHandled = function () { if ((this._bitField & 524288) !== 0) return; this._setRejectionIsUnhandled(); var self = this; setTimeout(function() { self._notifyUnhandledRejection(); }, 1); }; Promise.prototype._notifyUnhandledRejectionIsHandled = function () { fireRejectionEvent("rejectionHandled", unhandledRejectionHandled, undefined, this); }; Promise.prototype._setReturnedNonUndefined = function() { this._bitField = this._bitField | 268435456; }; Promise.prototype._returnedNonUndefined = function() { return (this._bitField & 268435456) !== 0; }; Promise.prototype._notifyUnhandledRejection = function () { if (this._isRejectionUnhandled()) { var reason = this._settledValue(); this._setUnhandledRejectionIsNotified(); fireRejectionEvent("unhandledRejection", possiblyUnhandledRejection, reason, this); } }; Promise.prototype._setUnhandledRejectionIsNotified = function () { this._bitField = this._bitField | 262144; }; Promise.prototype._unsetUnhandledRejectionIsNotified = function () { this._bitField = this._bitField & (~262144); }; Promise.prototype._isUnhandledRejectionNotified = function () { return (this._bitField & 262144) > 0; }; Promise.prototype._setRejectionIsUnhandled = function () { this._bitField = this._bitField | 1048576; }; Promise.prototype._unsetRejectionIsUnhandled = function () { this._bitField = this._bitField & (~1048576); if (this._isUnhandledRejectionNotified()) { this._unsetUnhandledRejectionIsNotified(); this._notifyUnhandledRejectionIsHandled(); } }; Promise.prototype._isRejectionUnhandled = function () { return (this._bitField & 1048576) > 0; }; Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { return warn(message, shouldUseOwnTrace, promise || this); }; Promise.onPossiblyUnhandledRejection = function (fn) { var domain = getDomain(); possiblyUnhandledRejection = typeof fn === "function" ? (domain === null ? fn : util.domainBind(domain, fn)) : undefined; }; Promise.onUnhandledRejectionHandled = function (fn) { var domain = getDomain(); unhandledRejectionHandled = typeof fn === "function" ? (domain === null ? fn : util.domainBind(domain, fn)) : undefined; }; var disableLongStackTraces = function() {}; Promise.longStackTraces = function () { if (async.haveItemsQueued() && !config.longStackTraces) { throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } if (!config.longStackTraces && longStackTracesIsSupported()) { var Promise_captureStackTrace = Promise.prototype._captureStackTrace; var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; config.longStackTraces = true; disableLongStackTraces = function() { if (async.haveItemsQueued() && !config.longStackTraces) { throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } Promise.prototype._captureStackTrace = Promise_captureStackTrace; Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; Context.deactivateLongStackTraces(); async.enableTrampoline(); config.longStackTraces = false; }; Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; Context.activateLongStackTraces(); async.disableTrampolineIfNecessary(); } }; Promise.hasLongStackTraces = function () { return config.longStackTraces && longStackTracesIsSupported(); }; var fireDomEvent = (function() { try { if (typeof CustomEvent === "function") { var event = new CustomEvent("CustomEvent"); util.global.dispatchEvent(event); return function(name, event) { var domEvent = new CustomEvent(name.toLowerCase(), { detail: event, cancelable: true }); return !util.global.dispatchEvent(domEvent); }; } else if (typeof Event === "function") { var event = new Event("CustomEvent"); util.global.dispatchEvent(event); return function(name, event) { var domEvent = new Event(name.toLowerCase(), { cancelable: true }); domEvent.detail = event; return !util.global.dispatchEvent(domEvent); }; } else { var event = document.createEvent("CustomEvent"); event.initCustomEvent("testingtheevent", false, true, {}); util.global.dispatchEvent(event); return function(name, event) { var domEvent = document.createEvent("CustomEvent"); domEvent.initCustomEvent(name.toLowerCase(), false, true, event); return !util.global.dispatchEvent(domEvent); }; } } catch (e) {} return function() { return false; }; })(); var fireGlobalEvent = (function() { if (util.isNode) { return function() { return process.emit.apply(process, arguments); }; } else { if (!util.global) { return function() { return false; }; } return function(name) { var methodName = "on" + name.toLowerCase(); var method = util.global[methodName]; if (!method) return false; method.apply(util.global, [].slice.call(arguments, 1)); return true; }; } })(); function generatePromiseLifecycleEventObject(name, promise) { return {promise: promise}; } var eventToObjectGenerator = { promiseCreated: generatePromiseLifecycleEventObject, promiseFulfilled: generatePromiseLifecycleEventObject, promiseRejected: generatePromiseLifecycleEventObject, promiseResolved: generatePromiseLifecycleEventObject, promiseCancelled: generatePromiseLifecycleEventObject, promiseChained: function(name, promise, child) { return {promise: promise, child: child}; }, warning: function(name, warning) { return {warning: warning}; }, unhandledRejection: function (name, reason, promise) { return {reason: reason, promise: promise}; }, rejectionHandled: generatePromiseLifecycleEventObject }; var activeFireEvent = function (name) { var globalEventFired = false; try { globalEventFired = fireGlobalEvent.apply(null, arguments); } catch (e) { async.throwLater(e); globalEventFired = true; } var domEventFired = false; try { domEventFired = fireDomEvent(name, eventToObjectGenerator[name].apply(null, arguments)); } catch (e) { async.throwLater(e); domEventFired = true; } return domEventFired || globalEventFired; }; Promise.config = function(opts) { opts = Object(opts); if ("longStackTraces" in opts) { if (opts.longStackTraces) { Promise.longStackTraces(); } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { disableLongStackTraces(); } } if ("warnings" in opts) { var warningsOption = opts.warnings; config.warnings = !!warningsOption; wForgottenReturn = config.warnings; if (util.isObject(warningsOption)) { if ("wForgottenReturn" in warningsOption) { wForgottenReturn = !!warningsOption.wForgottenReturn; } } } if ("cancellation" in opts && opts.cancellation && !config.cancellation) { if (async.haveItemsQueued()) { throw new Error( "cannot enable cancellation after promises are in use"); } Promise.prototype._clearCancellationData = cancellationClearCancellationData; Promise.prototype._propagateFrom = cancellationPropagateFrom; Promise.prototype._onCancel = cancellationOnCancel; Promise.prototype._setOnCancel = cancellationSetOnCancel; Promise.prototype._attachCancellationCallback = cancellationAttachCancellationCallback; Promise.prototype._execute = cancellationExecute; propagateFromFunction = cancellationPropagateFrom; config.cancellation = true; } if ("monitoring" in opts) { if (opts.monitoring && !config.monitoring) { config.monitoring = true; Promise.prototype._fireEvent = activeFireEvent; } else if (!opts.monitoring && config.monitoring) { config.monitoring = false; Promise.prototype._fireEvent = defaultFireEvent; } } return Promise; }; function defaultFireEvent() { return false; } Promise.prototype._fireEvent = defaultFireEvent; Promise.prototype._execute = function(executor, resolve, reject) { try { executor(resolve, reject); } catch (e) { return e; } }; Promise.prototype._onCancel = function () {}; Promise.prototype._setOnCancel = function (handler) { ; }; Promise.prototype._attachCancellationCallback = function(onCancel) { ; }; Promise.prototype._captureStackTrace = function () {}; Promise.prototype._attachExtraTrace = function () {}; Promise.prototype._clearCancellationData = function() {}; Promise.prototype._propagateFrom = function (parent, flags) { ; ; }; function cancellationExecute(executor, resolve, reject) { var promise = this; try { executor(resolve, reject, function(onCancel) { if (typeof onCancel !== "function") { throw new TypeError("onCancel must be a function, got: " + util.toString(onCancel)); } promise._attachCancellationCallback(onCancel); }); } catch (e) { return e; } } function cancellationAttachCancellationCallback(onCancel) { if (!this._isCancellable()) return this; var previousOnCancel = this._onCancel(); if (previousOnCancel !== undefined) { if (util.isArray(previousOnCancel)) { previousOnCancel.push(onCancel); } else { this._setOnCancel([previousOnCancel, onCancel]); } } else { this._setOnCancel(onCancel); } } function cancellationOnCancel() { return this._onCancelField; } function cancellationSetOnCancel(onCancel) { this._onCancelField = onCancel; } function cancellationClearCancellationData() { this._cancellationParent = undefined; this._onCancelField = undefined; } function cancellationPropagateFrom(parent, flags) { if ((flags & 1) !== 0) { this._cancellationParent = parent; var branchesRemainingToCancel = parent._branchesRemainingToCancel; if (branchesRemainingToCancel === undefined) { branchesRemainingToCancel = 0; } parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; } if ((flags & 2) !== 0 && parent._isBound()) { this._setBoundTo(parent._boundTo); } } function bindingPropagateFrom(parent, flags) { if ((flags & 2) !== 0 && parent._isBound()) { this._setBoundTo(parent._boundTo); } } var propagateFromFunction = bindingPropagateFrom; function boundValueFunction() { var ret = this._boundTo; if (ret !== undefined) { if (ret instanceof Promise) { if (ret.isFulfilled()) { return ret.value(); } else { return undefined; } } } return ret; } function longStackTracesCaptureStackTrace() { this._trace = new CapturedTrace(this._peekContext()); } function longStackTracesAttachExtraTrace(error, ignoreSelf) { if (canAttachTrace(error)) { var trace = this._trace; if (trace !== undefined) { if (ignoreSelf) trace = trace._parent; } if (trace !== undefined) { trace.attachExtraTrace(error); } else if (!error.__stackCleaned__) { var parsed = parseStackAndMessage(error); util.notEnumerableProp(error, "stack", parsed.message + "\n" + parsed.stack.join("\n")); util.notEnumerableProp(error, "__stackCleaned__", true); } } } function checkForgottenReturns(returnValue, promiseCreated, name, promise, parent) { if (returnValue === undefined && promiseCreated !== null && wForgottenReturn) { if (parent !== undefined && parent._returnedNonUndefined()) return; if ((promise._bitField & 65535) === 0) return; if (name) name = name + " "; var handlerLine = ""; var creatorLine = ""; if (promiseCreated._trace) { var traceLines = promiseCreated._trace.stack.split("\n"); var stack = cleanStack(traceLines); for (var i = stack.length - 1; i >= 0; --i) { var line = stack[i]; if (!nodeFramePattern.test(line)) { var lineMatches = line.match(parseLinePattern); if (lineMatches) { handlerLine = "at " + lineMatches[1] + ":" + lineMatches[2] + ":" + lineMatches[3] + " "; } break; } } if (stack.length > 0) { var firstUserLine = stack[0]; for (var i = 0; i < traceLines.length; ++i) { if (traceLines[i] === firstUserLine) { if (i > 0) { creatorLine = "\n" + traceLines[i - 1]; } break; } } } } var msg = "a promise was created in a " + name + "handler " + handlerLine + "but was not returned from it, " + "see http://goo.gl/rRqMUw" + creatorLine; promise._warn(msg, true, promiseCreated); } } function deprecated(name, replacement) { var message = name + " is deprecated and will be removed in a future version."; if (replacement) message += " Use " + replacement + " instead."; return warn(message); } function warn(message, shouldUseOwnTrace, promise) { if (!config.warnings) return; var warning = new Warning(message); var ctx; if (shouldUseOwnTrace) { promise._attachExtraTrace(warning); } else if (config.longStackTraces && (ctx = Promise._peekContext())) { ctx.attachExtraTrace(warning); } else { var parsed = parseStackAndMessage(warning); warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); } if (!activeFireEvent("warning", warning)) { formatAndLogError(warning, "", true); } } function reconstructStack(message, stacks) { for (var i = 0; i < stacks.length - 1; ++i) { stacks[i].push("From previous event:"); stacks[i] = stacks[i].join("\n"); } if (i < stacks.length) { stacks[i] = stacks[i].join("\n"); } return message + "\n" + stacks.join("\n"); } function removeDuplicateOrEmptyJumps(stacks) { for (var i = 0; i < stacks.length; ++i) { if (stacks[i].length === 0 || ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { stacks.splice(i, 1); i--; } } } function removeCommonRoots(stacks) { var current = stacks[0]; for (var i = 1; i < stacks.length; ++i) { var prev = stacks[i]; var currentLastIndex = current.length - 1; var currentLastLine = current[currentLastIndex]; var commonRootMeetPoint = -1; for (var j = prev.length - 1; j >= 0; --j) { if (prev[j] === currentLastLine) { commonRootMeetPoint = j; break; } } for (var j = commonRootMeetPoint; j >= 0; --j) { var line = prev[j]; if (current[currentLastIndex] === line) { current.pop(); currentLastIndex--; } else { break; } } current = prev; } } function cleanStack(stack) { var ret = []; for (var i = 0; i < stack.length; ++i) { var line = stack[i]; var isTraceLine = " (No stack trace)" === line || stackFramePattern.test(line); var isInternalFrame = isTraceLine && shouldIgnore(line); if (isTraceLine && !isInternalFrame) { if (indentStackFrames && line.charAt(0) !== " ") { line = " " + line; } ret.push(line); } } return ret; } function stackFramesAsArray(error) { var stack = error.stack.replace(/\s+$/g, "").split("\n"); for (var i = 0; i < stack.length; ++i) { var line = stack[i]; if (" (No stack trace)" === line || stackFramePattern.test(line)) { break; } } if (i > 0 && error.name != "SyntaxError") { stack = stack.slice(i); } return stack; } function parseStackAndMessage(error) { var stack = error.stack; var message = error.toString(); stack = typeof stack === "string" && stack.length > 0 ? stackFramesAsArray(error) : [" (No stack trace)"]; return { message: message, stack: error.name == "SyntaxError" ? stack : cleanStack(stack) }; } function formatAndLogError(error, title, isSoft) { if (typeof console !== "undefined") { var message; if (util.isObject(error)) { var stack = error.stack; message = title + formatStack(stack, error); } else { message = title + String(error); } if (typeof printWarning === "function") { printWarning(message, isSoft); } else if (typeof console.log === "function" || typeof console.log === "object") { console.log(message); } } } function fireRejectionEvent(name, localHandler, reason, promise) { var localEventFired = false; try { if (typeof localHandler === "function") { localEventFired = true; if (name === "rejectionHandled") { localHandler(promise); } else { localHandler(reason, promise); } } } catch (e) { async.throwLater(e); } if (name === "unhandledRejection") { if (!activeFireEvent(name, reason, promise) && !localEventFired) { formatAndLogError(reason, "Unhandled rejection "); } } else { activeFireEvent(name, promise); } } function formatNonError(obj) { var str; if (typeof obj === "function") { str = "[function " + (obj.name || "anonymous") + "]"; } else { str = obj && typeof obj.toString === "function" ? obj.toString() : util.toString(obj); var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; if (ruselessToString.test(str)) { try { var newStr = JSON.stringify(obj); str = newStr; } catch(e) { } } if (str.length === 0) { str = "(empty array)"; } } return ("(<" + snip(str) + ">, no stack trace)"); } function snip(str) { var maxChars = 41; if (str.length < maxChars) { return str; } return str.substr(0, maxChars - 3) + "..."; } function longStackTracesIsSupported() { return typeof captureStackTrace === "function"; } var shouldIgnore = function() { return false; }; var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; function parseLineInfo(line) { var matches = line.match(parseLineInfoRegex); if (matches) { return { fileName: matches[1], line: parseInt(matches[2], 10) }; } } function setBounds(firstLineError, lastLineError) { if (!longStackTracesIsSupported()) return; var firstStackLines = firstLineError.stack.split("\n"); var lastStackLines = lastLineError.stack.split("\n"); var firstIndex = -1; var lastIndex = -1; var firstFileName; var lastFileName; for (var i = 0; i < firstStackLines.length; ++i) { var result = parseLineInfo(firstStackLines[i]); if (result) { firstFileName = result.fileName; firstIndex = result.line; break; } } for (var i = 0; i < lastStackLines.length; ++i) { var result = parseLineInfo(lastStackLines[i]); if (result) { lastFileName = result.fileName; lastIndex = result.line; break; } } if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || firstFileName !== lastFileName || firstIndex >= lastIndex) { return; } shouldIgnore = function(line) { if (bluebirdFramePattern.test(line)) return true; var info = parseLineInfo(line); if (info) { if (info.fileName === firstFileName && (firstIndex <= info.line && info.line <= lastIndex)) { return true; } } return false; }; } function CapturedTrace(parent) { this._parent = parent; this._promisesCreated = 0; var length = this._length = 1 + (parent === undefined ? 0 : parent._length); captureStackTrace(this, CapturedTrace); if (length > 32) this.uncycle(); } util.inherits(CapturedTrace, Error); Context.CapturedTrace = CapturedTrace; CapturedTrace.prototype.uncycle = function() { var length = this._length; if (length < 2) return; var nodes = []; var stackToIndex = {}; for (var i = 0, node = this; node !== undefined; ++i) { nodes.push(node); node = node._parent; } length = this._length = i; for (var i = length - 1; i >= 0; --i) { var stack = nodes[i].stack; if (stackToIndex[stack] === undefined) { stackToIndex[stack] = i; } } for (var i = 0; i < length; ++i) { var currentStack = nodes[i].stack; var index = stackToIndex[currentStack]; if (index !== undefined && index !== i) { if (index > 0) { nodes[index - 1]._parent = undefined; nodes[index - 1]._length = 1; } nodes[i]._parent = undefined; nodes[i]._length = 1; var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; if (index < length - 1) { cycleEdgeNode._parent = nodes[index + 1]; cycleEdgeNode._parent.uncycle(); cycleEdgeNode._length = cycleEdgeNode._parent._length + 1; } else { cycleEdgeNode._parent = undefined; cycleEdgeNode._length = 1; } var currentChildLength = cycleEdgeNode._length + 1; for (var j = i - 2; j >= 0; --j) { nodes[j]._length = currentChildLength; currentChildLength++; } return; } } }; CapturedTrace.prototype.attachExtraTrace = function(error) { if (error.__stackCleaned__) return; this.uncycle(); var parsed = parseStackAndMessage(error); var message = parsed.message; var stacks = [parsed.stack]; var trace = this; while (trace !== undefined) { stacks.push(cleanStack(trace.stack.split("\n"))); trace = trace._parent; } removeCommonRoots(stacks); removeDuplicateOrEmptyJumps(stacks); util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); util.notEnumerableProp(error, "__stackCleaned__", true); }; var captureStackTrace = (function stackDetection() { var v8stackFramePattern = /^\s*at\s*/; var v8stackFormatter = function(stack, error) { if (typeof stack === "string") return stack; if (error.name !== undefined && error.message !== undefined) { return error.toString(); } return formatNonError(error); }; if (typeof Error.stackTraceLimit === "number" && typeof Error.captureStackTrace === "function") { Error.stackTraceLimit += 6; stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; var captureStackTrace = Error.captureStackTrace; shouldIgnore = function(line) { return bluebirdFramePattern.test(line); }; return function(receiver, ignoreUntil) { Error.stackTraceLimit += 6; captureStackTrace(receiver, ignoreUntil); Error.stackTraceLimit -= 6; }; } var err = new Error(); if (typeof err.stack === "string" && err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { stackFramePattern = /@/; formatStack = v8stackFormatter; indentStackFrames = true; return function captureStackTrace(o) { o.stack = new Error().stack; }; } var hasStackAfterThrow; try { throw new Error(); } catch(e) { hasStackAfterThrow = ("stack" in e); } if (!("stack" in err) && hasStackAfterThrow && typeof Error.stackTraceLimit === "number") { stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; return function captureStackTrace(o) { Error.stackTraceLimit += 6; try { throw new Error(); } catch(e) { o.stack = e.stack; } Error.stackTraceLimit -= 6; }; } formatStack = function(stack, error) { if (typeof stack === "string") return stack; if ((typeof error === "object" || typeof error === "function") && error.name !== undefined && error.message !== undefined) { return error.toString(); } return formatNonError(error); }; return null; })([]); if (typeof console !== "undefined" && typeof console.warn !== "undefined") { printWarning = function (message) { console.warn(message); }; if (util.isNode && process.stderr.isTTY) { printWarning = function(message, isSoft) { var color = isSoft ? "\u001b[33m" : "\u001b[31m"; console.warn(color + message + "\u001b[0m\n"); }; } else if (!util.isNode && typeof (new Error().stack) === "string") { printWarning = function(message, isSoft) { console.warn("%c" + message, isSoft ? "color: darkorange" : "color: red"); }; } } var config = { warnings: warnings, longStackTraces: false, cancellation: false, monitoring: false }; if (longStackTraces) Promise.longStackTraces(); return { longStackTraces: function() { return config.longStackTraces; }, warnings: function() { return config.warnings; }, cancellation: function() { return config.cancellation; }, monitoring: function() { return config.monitoring; }, propagateFromFunction: function() { return propagateFromFunction; }, boundValueFunction: function() { return boundValueFunction; }, checkForgottenReturns: checkForgottenReturns, setBounds: setBounds, warn: warn, deprecated: deprecated, CapturedTrace: CapturedTrace, fireDomEvent: fireDomEvent, fireGlobalEvent: fireGlobalEvent }; }; },{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { function returner() { return this.value; } function thrower() { throw this.reason; } Promise.prototype["return"] = Promise.prototype.thenReturn = function (value) { if (value instanceof Promise) value.suppressUnhandledRejections(); return this._then( returner, undefined, undefined, {value: value}, undefined); }; Promise.prototype["throw"] = Promise.prototype.thenThrow = function (reason) { return this._then( thrower, undefined, undefined, {reason: reason}, undefined); }; Promise.prototype.catchThrow = function (reason) { if (arguments.length <= 1) { return this._then( undefined, thrower, undefined, {reason: reason}, undefined); } else { var _reason = arguments[1]; var handler = function() {throw _reason;}; return this.caught(reason, handler); } }; Promise.prototype.catchReturn = function (value) { if (arguments.length <= 1) { if (value instanceof Promise) value.suppressUnhandledRejections(); return this._then( undefined, returner, undefined, {value: value}, undefined); } else { var _value = arguments[1]; if (_value instanceof Promise) _value.suppressUnhandledRejections(); var handler = function() {return _value;}; return this.caught(value, handler); } }; }; },{}],11:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseReduce = Promise.reduce; var PromiseAll = Promise.all; function promiseAllThis() { return PromiseAll(this); } function PromiseMapSeries(promises, fn) { return PromiseReduce(promises, fn, INTERNAL, INTERNAL); } Promise.prototype.each = function (fn) { return PromiseReduce(this, fn, INTERNAL, 0) ._then(promiseAllThis, undefined, undefined, this, undefined); }; Promise.prototype.mapSeries = function (fn) { return PromiseReduce(this, fn, INTERNAL, INTERNAL); }; Promise.each = function (promises, fn) { return PromiseReduce(promises, fn, INTERNAL, 0) ._then(promiseAllThis, undefined, undefined, promises, undefined); }; Promise.mapSeries = PromiseMapSeries; }; },{}],12:[function(_dereq_,module,exports){ "use strict"; var es5 = _dereq_("./es5"); var Objectfreeze = es5.freeze; var util = _dereq_("./util"); var inherits = util.inherits; var notEnumerableProp = util.notEnumerableProp; function subError(nameProperty, defaultMessage) { function SubError(message) { if (!(this instanceof SubError)) return new SubError(message); notEnumerableProp(this, "message", typeof message === "string" ? message : defaultMessage); notEnumerableProp(this, "name", nameProperty); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { Error.call(this); } } inherits(SubError, Error); return SubError; } var _TypeError, _RangeError; var Warning = subError("Warning", "warning"); var CancellationError = subError("CancellationError", "cancellation error"); var TimeoutError = subError("TimeoutError", "timeout error"); var AggregateError = subError("AggregateError", "aggregate error"); try { _TypeError = TypeError; _RangeError = RangeError; } catch(e) { _TypeError = subError("TypeError", "type error"); _RangeError = subError("RangeError", "range error"); } var methods = ("join pop push shift unshift slice filter forEach some " + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); for (var i = 0; i < methods.length; ++i) { if (typeof Array.prototype[methods[i]] === "function") { AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; } } es5.defineProperty(AggregateError.prototype, "length", { value: 0, configurable: false, writable: true, enumerable: true }); AggregateError.prototype["isOperational"] = true; var level = 0; AggregateError.prototype.toString = function() { var indent = Array(level * 4 + 1).join(" "); var ret = "\n" + indent + "AggregateError of:" + "\n"; level++; indent = Array(level * 4 + 1).join(" "); for (var i = 0; i < this.length; ++i) { var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; var lines = str.split("\n"); for (var j = 0; j < lines.length; ++j) { lines[j] = indent + lines[j]; } str = lines.join("\n"); ret += str + "\n"; } level--; return ret; }; function OperationalError(message) { if (!(this instanceof OperationalError)) return new OperationalError(message); notEnumerableProp(this, "name", "OperationalError"); notEnumerableProp(this, "message", message); this.cause = message; this["isOperational"] = true; if (message instanceof Error) { notEnumerableProp(this, "message", message.message); notEnumerableProp(this, "stack", message.stack); } else if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } inherits(OperationalError, Error); var errorTypes = Error["__BluebirdErrorTypes__"]; if (!errorTypes) { errorTypes = Objectfreeze({ CancellationError: CancellationError, TimeoutError: TimeoutError, OperationalError: OperationalError, RejectionError: OperationalError, AggregateError: AggregateError }); es5.defineProperty(Error, "__BluebirdErrorTypes__", { value: errorTypes, writable: false, enumerable: false, configurable: false }); } module.exports = { Error: Error, TypeError: _TypeError, RangeError: _RangeError, CancellationError: errorTypes.CancellationError, OperationalError: errorTypes.OperationalError, TimeoutError: errorTypes.TimeoutError, AggregateError: errorTypes.AggregateError, Warning: Warning }; },{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){ var isES5 = (function(){ "use strict"; return this === undefined; })(); if (isES5) { module.exports = { freeze: Object.freeze, defineProperty: Object.defineProperty, getDescriptor: Object.getOwnPropertyDescriptor, keys: Object.keys, names: Object.getOwnPropertyNames, getPrototypeOf: Object.getPrototypeOf, isArray: Array.isArray, isES5: isES5, propertyIsWritable: function(obj, prop) { var descriptor = Object.getOwnPropertyDescriptor(obj, prop); return !!(!descriptor || descriptor.writable || descriptor.set); } }; } else { var has = {}.hasOwnProperty; var str = {}.toString; var proto = {}.constructor.prototype; var ObjectKeys = function (o) { var ret = []; for (var key in o) { if (has.call(o, key)) { ret.push(key); } } return ret; }; var ObjectGetDescriptor = function(o, key) { return {value: o[key]}; }; var ObjectDefineProperty = function (o, key, desc) { o[key] = desc.value; return o; }; var ObjectFreeze = function (obj) { return obj; }; var ObjectGetPrototypeOf = function (obj) { try { return Object(obj).constructor.prototype; } catch (e) { return proto; } }; var ArrayIsArray = function (obj) { try { return str.call(obj) === "[object Array]"; } catch(e) { return false; } }; module.exports = { isArray: ArrayIsArray, keys: ObjectKeys, names: ObjectKeys, defineProperty: ObjectDefineProperty, getDescriptor: ObjectGetDescriptor, freeze: ObjectFreeze, getPrototypeOf: ObjectGetPrototypeOf, isES5: isES5, propertyIsWritable: function() { return true; } }; } },{}],14:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseMap = Promise.map; Promise.prototype.filter = function (fn, options) { return PromiseMap(this, fn, options, INTERNAL); }; Promise.filter = function (promises, fn, options) { return PromiseMap(promises, fn, options, INTERNAL); }; }; },{}],15:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { var util = _dereq_("./util"); var CancellationError = Promise.CancellationError; var errorObj = util.errorObj; var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); function PassThroughHandlerContext(promise, type, handler) { this.promise = promise; this.type = type; this.handler = handler; this.called = false; this.cancelPromise = null; } PassThroughHandlerContext.prototype.isFinallyHandler = function() { return this.type === 0; }; function FinallyHandlerCancelReaction(finallyHandler) { this.finallyHandler = finallyHandler; } FinallyHandlerCancelReaction.prototype._resultCancelled = function() { checkCancel(this.finallyHandler); }; function checkCancel(ctx, reason) { if (ctx.cancelPromise != null) { if (arguments.length > 1) { ctx.cancelPromise._reject(reason); } else { ctx.cancelPromise._cancel(); } ctx.cancelPromise = null; return true; } return false; } function succeed() { return finallyHandler.call(this, this.promise._target()._settledValue()); } function fail(reason) { if (checkCancel(this, reason)) return; errorObj.e = reason; return errorObj; } function finallyHandler(reasonOrValue) { var promise = this.promise; var handler = this.handler; if (!this.called) { this.called = true; var ret = this.isFinallyHandler() ? handler.call(promise._boundValue()) : handler.call(promise._boundValue(), reasonOrValue); if (ret === NEXT_FILTER) { return ret; } else if (ret !== undefined) { promise._setReturnedNonUndefined(); var maybePromise = tryConvertToPromise(ret, promise); if (maybePromise instanceof Promise) { if (this.cancelPromise != null) { if (maybePromise._isCancelled()) { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); errorObj.e = reason; return errorObj; } else if (maybePromise.isPending()) { maybePromise._attachCancellationCallback( new FinallyHandlerCancelReaction(this)); } } return maybePromise._then( succeed, fail, undefined, this, undefined); } } } if (promise.isRejected()) { checkCancel(this); errorObj.e = reasonOrValue; return errorObj; } else { checkCancel(this); return reasonOrValue; } } Promise.prototype._passThrough = function(handler, type, success, fail) { if (typeof handler !== "function") return this.then(); return this._then(success, fail, undefined, new PassThroughHandlerContext(this, type, handler), undefined); }; Promise.prototype.lastly = Promise.prototype["finally"] = function (handler) { return this._passThrough(handler, 0, finallyHandler, finallyHandler); }; Promise.prototype.tap = function (handler) { return this._passThrough(handler, 1, finallyHandler); }; Promise.prototype.tapCatch = function (handlerOrPredicate) { var len = arguments.length; if(len === 1) { return this._passThrough(handlerOrPredicate, 1, undefined, finallyHandler); } else { var catchInstances = new Array(len - 1), j = 0, i; for (i = 0; i < len - 1; ++i) { var item = arguments[i]; if (util.isObject(item)) { catchInstances[j++] = item; } else { return Promise.reject(new TypeError( "tapCatch statement predicate: " + "expecting an object but got " + util.classString(item) )); } } catchInstances.length = j; var handler = arguments[i]; return this._passThrough(catchFilter(catchInstances, handler, this), 1, undefined, finallyHandler); } }; return PassThroughHandlerContext; }; },{"./catch_filter":7,"./util":36}],16:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug) { var errors = _dereq_("./errors"); var TypeError = errors.TypeError; var util = _dereq_("./util"); var errorObj = util.errorObj; var tryCatch = util.tryCatch; var yieldHandlers = []; function promiseFromYieldHandler(value, yieldHandlers, traceParent) { for (var i = 0; i < yieldHandlers.length; ++i) { traceParent._pushContext(); var result = tryCatch(yieldHandlers[i])(value); traceParent._popContext(); if (result === errorObj) { traceParent._pushContext(); var ret = Promise.reject(errorObj.e); traceParent._popContext(); return ret; } var maybePromise = tryConvertToPromise(result, traceParent); if (maybePromise instanceof Promise) return maybePromise; } return null; } function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { if (debug.cancellation()) { var internal = new Promise(INTERNAL); var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); this._promise = internal.lastly(function() { return _finallyPromise; }); internal._captureStackTrace(); internal._setOnCancel(this); } else { var promise = this._promise = new Promise(INTERNAL); promise._captureStackTrace(); } this._stack = stack; this._generatorFunction = generatorFunction; this._receiver = receiver; this._generator = undefined; this._yieldHandlers = typeof yieldHandler === "function" ? [yieldHandler].concat(yieldHandlers) : yieldHandlers; this._yieldedPromise = null; this._cancellationPhase = false; } util.inherits(PromiseSpawn, Proxyable); PromiseSpawn.prototype._isResolved = function() { return this._promise === null; }; PromiseSpawn.prototype._cleanup = function() { this._promise = this._generator = null; if (debug.cancellation() && this._finallyPromise !== null) { this._finallyPromise._fulfill(); this._finallyPromise = null; } }; PromiseSpawn.prototype._promiseCancelled = function() { if (this._isResolved()) return; var implementsReturn = typeof this._generator["return"] !== "undefined"; var result; if (!implementsReturn) { var reason = new Promise.CancellationError( "generator .return() sentinel"); Promise.coroutine.returnSentinel = reason; this._promise._attachExtraTrace(reason); this._promise._pushContext(); result = tryCatch(this._generator["throw"]).call(this._generator, reason); this._promise._popContext(); } else { this._promise._pushContext(); result = tryCatch(this._generator["return"]).call(this._generator, undefined); this._promise._popContext(); } this._cancellationPhase = true; this._yieldedPromise = null; this._continue(result); }; PromiseSpawn.prototype._promiseFulfilled = function(value) { this._yieldedPromise = null; this._promise._pushContext(); var result = tryCatch(this._generator.next).call(this._generator, value); this._promise._popContext(); this._continue(result); }; PromiseSpawn.prototype._promiseRejected = function(reason) { this._yieldedPromise = null; this._promise._attachExtraTrace(reason); this._promise._pushContext(); var result = tryCatch(this._generator["throw"]) .call(this._generator, reason); this._promise._popContext(); this._continue(result); }; PromiseSpawn.prototype._resultCancelled = function() { if (this._yieldedPromise instanceof Promise) { var promise = this._yieldedPromise; this._yieldedPromise = null; promise.cancel(); } }; PromiseSpawn.prototype.promise = function () { return this._promise; }; PromiseSpawn.prototype._run = function () { this._generator = this._generatorFunction.call(this._receiver); this._receiver = this._generatorFunction = undefined; this._promiseFulfilled(undefined); }; PromiseSpawn.prototype._continue = function (result) { var promise = this._promise; if (result === errorObj) { this._cleanup(); if (this._cancellationPhase) { return promise.cancel(); } else { return promise._rejectCallback(result.e, false); } } var value = result.value; if (result.done === true) { this._cleanup(); if (this._cancellationPhase) { return promise.cancel(); } else { return promise._resolveCallback(value); } } else { var maybePromise = tryConvertToPromise(value, this._promise); if (!(maybePromise instanceof Promise)) { maybePromise = promiseFromYieldHandler(maybePromise, this._yieldHandlers, this._promise); if (maybePromise === null) { this._promiseRejected( new TypeError( "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) + "From coroutine:\u000a" + this._stack.split("\n").slice(1, -7).join("\n") ) ); return; } } maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { this._yieldedPromise = maybePromise; maybePromise._proxy(this, null); } else if (((bitField & 33554432) !== 0)) { Promise._async.invoke( this._promiseFulfilled, this, maybePromise._value() ); } else if (((bitField & 16777216) !== 0)) { Promise._async.invoke( this._promiseRejected, this, maybePromise._reason() ); } else { this._promiseCancelled(); } } }; Promise.coroutine = function (generatorFunction, options) { if (typeof generatorFunction !== "function") { throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var yieldHandler = Object(options).yieldHandler; var PromiseSpawn$ = PromiseSpawn; var stack = new Error().stack; return function () { var generator = generatorFunction.apply(this, arguments); var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, stack); var ret = spawn.promise(); spawn._generator = generator; spawn._promiseFulfilled(undefined); return ret; }; }; Promise.coroutine.addYieldHandler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } yieldHandlers.push(fn); }; Promise.spawn = function (generatorFunction) { debug.deprecated("Promise.spawn()", "Promise.coroutine()"); if (typeof generatorFunction !== "function") { return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var spawn = new PromiseSpawn(generatorFunction, this); var ret = spawn.promise(); spawn._run(Promise.spawn); return ret; }; }; },{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain) { var util = _dereq_("./util"); var canEvaluate = util.canEvaluate; var tryCatch = util.tryCatch; var errorObj = util.errorObj; var reject; if (!true) { if (canEvaluate) { var thenCallback = function(i) { return new Function("value", "holder", " \n\ 'use strict'; \n\ holder.pIndex = value; \n\ holder.checkFulfillment(this); \n\ ".replace(/Index/g, i)); }; var promiseSetter = function(i) { return new Function("promise", "holder", " \n\ 'use strict'; \n\ holder.pIndex = promise; \n\ ".replace(/Index/g, i)); }; var generateHolderClass = function(total) { var props = new Array(total); for (var i = 0; i < props.length; ++i) { props[i] = "this.p" + (i+1); } var assignment = props.join(" = ") + " = null;"; var cancellationCode= "var promise;\n" + props.map(function(prop) { return " \n\ promise = " + prop + "; \n\ if (promise instanceof Promise) { \n\ promise.cancel(); \n\ } \n\ "; }).join("\n"); var passedArguments = props.join(", "); var name = "Holder$" + total; var code = "return function(tryCatch, errorObj, Promise, async) { \n\ 'use strict'; \n\ function [TheName](fn) { \n\ [TheProperties] \n\ this.fn = fn; \n\ this.asyncNeeded = true; \n\ this.now = 0; \n\ } \n\ \n\ [TheName].prototype._callFunction = function(promise) { \n\ promise._pushContext(); \n\ var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ promise._popContext(); \n\ if (ret === errorObj) { \n\ promise._rejectCallback(ret.e, false); \n\ } else { \n\ promise._resolveCallback(ret); \n\ } \n\ }; \n\ \n\ [TheName].prototype.checkFulfillment = function(promise) { \n\ var now = ++this.now; \n\ if (now === [TheTotal]) { \n\ if (this.asyncNeeded) { \n\ async.invoke(this._callFunction, this, promise); \n\ } else { \n\ this._callFunction(promise); \n\ } \n\ \n\ } \n\ }; \n\ \n\ [TheName].prototype._resultCancelled = function() { \n\ [CancellationCode] \n\ }; \n\ \n\ return [TheName]; \n\ }(tryCatch, errorObj, Promise, async); \n\ "; code = code.replace(/\[TheName\]/g, name) .replace(/\[TheTotal\]/g, total) .replace(/\[ThePassedArguments\]/g, passedArguments) .replace(/\[TheProperties\]/g, assignment) .replace(/\[CancellationCode\]/g, cancellationCode); return new Function("tryCatch", "errorObj", "Promise", "async", code) (tryCatch, errorObj, Promise, async); }; var holderClasses = []; var thenCallbacks = []; var promiseSetters = []; for (var i = 0; i < 8; ++i) { holderClasses.push(generateHolderClass(i + 1)); thenCallbacks.push(thenCallback(i + 1)); promiseSetters.push(promiseSetter(i + 1)); } reject = function (reason) { this._reject(reason); }; }} Promise.join = function () { var last = arguments.length - 1; var fn; if (last > 0 && typeof arguments[last] === "function") { fn = arguments[last]; if (!true) { if (last <= 8 && canEvaluate) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var HolderClass = holderClasses[last - 1]; var holder = new HolderClass(fn); var callbacks = thenCallbacks; for (var i = 0; i < last; ++i) { var maybePromise = tryConvertToPromise(arguments[i], ret); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { maybePromise._then(callbacks[i], reject, undefined, ret, holder); promiseSetters[i](maybePromise, holder); holder.asyncNeeded = false; } else if (((bitField & 33554432) !== 0)) { callbacks[i].call(ret, maybePromise._value(), holder); } else if (((bitField & 16777216) !== 0)) { ret._reject(maybePromise._reason()); } else { ret._cancel(); } } else { callbacks[i].call(ret, maybePromise, holder); } } if (!ret._isFateSealed()) { if (holder.asyncNeeded) { var domain = getDomain(); if (domain !== null) { holder.fn = util.domainBind(domain, holder.fn); } } ret._setAsyncGuaranteed(); ret._setOnCancel(holder); } return ret; } } } var args = [].slice.call(arguments);; if (fn) args.pop(); var ret = new PromiseArray(args).promise(); return fn !== undefined ? ret.spread(fn) : ret; }; }; },{"./util":36}],18:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { var getDomain = Promise._getDomain; var util = _dereq_("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var async = Promise._async; function MappingPromiseArray(promises, fn, limit, _filter) { this.constructor$(promises); this._promise._captureStackTrace(); var domain = getDomain(); this._callback = domain === null ? fn : util.domainBind(domain, fn); this._preservedValues = _filter === INTERNAL ? new Array(this.length()) : null; this._limit = limit; this._inFlight = 0; this._queue = []; async.invoke(this._asyncInit, this, undefined); } util.inherits(MappingPromiseArray, PromiseArray); MappingPromiseArray.prototype._asyncInit = function() { this._init$(undefined, -2); }; MappingPromiseArray.prototype._init = function () {}; MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { var values = this._values; var length = this.length(); var preservedValues = this._preservedValues; var limit = this._limit; if (index < 0) { index = (index * -1) - 1; values[index] = value; if (limit >= 1) { this._inFlight--; this._drainQueue(); if (this._isResolved()) return true; } } else { if (limit >= 1 && this._inFlight >= limit) { values[index] = value; this._queue.push(index); return false; } if (preservedValues !== null) preservedValues[index] = value; var promise = this._promise; var callback = this._callback; var receiver = promise._boundValue(); promise._pushContext(); var ret = tryCatch(callback).call(receiver, value, index, length); var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, preservedValues !== null ? "Promise.filter" : "Promise.map", promise ); if (ret === errorObj) { this._reject(ret.e); return true; } var maybePromise = tryConvertToPromise(ret, this._promise); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { if (limit >= 1) this._inFlight++; values[index] = maybePromise; maybePromise._proxy(this, (index + 1) * -1); return false; } else if (((bitField & 33554432) !== 0)) { ret = maybePromise._value(); } else if (((bitField & 16777216) !== 0)) { this._reject(maybePromise._reason()); return true; } else { this._cancel(); return true; } } values[index] = ret; } var totalResolved = ++this._totalResolved; if (totalResolved >= length) { if (preservedValues !== null) { this._filter(values, preservedValues); } else { this._resolve(values); } return true; } return false; }; MappingPromiseArray.prototype._drainQueue = function () { var queue = this._queue; var limit = this._limit; var values = this._values; while (queue.length > 0 && this._inFlight < limit) { if (this._isResolved()) return; var index = queue.pop(); this._promiseFulfilled(values[index], index); } }; MappingPromiseArray.prototype._filter = function (booleans, values) { var len = values.length; var ret = new Array(len); var j = 0; for (var i = 0; i < len; ++i) { if (booleans[i]) ret[j++] = values[i]; } ret.length = j; this._resolve(ret); }; MappingPromiseArray.prototype.preservedValues = function () { return this._preservedValues; }; function map(promises, fn, options, _filter) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var limit = 0; if (options !== undefined) { if (typeof options === "object" && options !== null) { if (typeof options.concurrency !== "number") { return Promise.reject( new TypeError("'concurrency' must be a number but it is " + util.classString(options.concurrency))); } limit = options.concurrency; } else { return Promise.reject(new TypeError( "options argument must be an object but it is " + util.classString(options))); } } limit = typeof limit === "number" && isFinite(limit) && limit >= 1 ? limit : 0; return new MappingPromiseArray(promises, fn, limit, _filter).promise(); } Promise.prototype.map = function (fn, options) { return map(this, fn, options, null); }; Promise.map = function (promises, fn, options, _filter) { return map(promises, fn, options, _filter); }; }; },{"./util":36}],19:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { var util = _dereq_("./util"); var tryCatch = util.tryCatch; Promise.method = function (fn) { if (typeof fn !== "function") { throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); } return function () { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value = tryCatch(fn).apply(this, arguments); var promiseCreated = ret._popContext(); debug.checkForgottenReturns( value, promiseCreated, "Promise.method", ret); ret._resolveFromSyncValue(value); return ret; }; }; Promise.attempt = Promise["try"] = function (fn) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value; if (arguments.length > 1) { debug.deprecated("calling Promise.try with more than 1 argument"); var arg = arguments[1]; var ctx = arguments[2]; value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) : tryCatch(fn).call(ctx, arg); } else { value = tryCatch(fn)(); } var promiseCreated = ret._popContext(); debug.checkForgottenReturns( value, promiseCreated, "Promise.try", ret); ret._resolveFromSyncValue(value); return ret; }; Promise.prototype._resolveFromSyncValue = function (value) { if (value === util.errorObj) { this._rejectCallback(value.e, false); } else { this._resolveCallback(value, true); } }; }; },{"./util":36}],20:[function(_dereq_,module,exports){ "use strict"; var util = _dereq_("./util"); var maybeWrapAsError = util.maybeWrapAsError; var errors = _dereq_("./errors"); var OperationalError = errors.OperationalError; var es5 = _dereq_("./es5"); function isUntypedError(obj) { return obj instanceof Error && es5.getPrototypeOf(obj) === Error.prototype; } var rErrorKey = /^(?:name|message|stack|cause)$/; function wrapAsOperationalError(obj) { var ret; if (isUntypedError(obj)) { ret = new OperationalError(obj); ret.name = obj.name; ret.message = obj.message; ret.stack = obj.stack; var keys = es5.keys(obj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!rErrorKey.test(key)) { ret[key] = obj[key]; } } return ret; } util.markAsOriginatingFromRejection(obj); return obj; } function nodebackForPromise(promise, multiArgs) { return function(err, value) { if (promise === null) return; if (err) { var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); promise._attachExtraTrace(wrapped); promise._reject(wrapped); } else if (!multiArgs) { promise._fulfill(value); } else { var args = [].slice.call(arguments, 1);; promise._fulfill(args); } promise = null; }; } module.exports = nodebackForPromise; },{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var util = _dereq_("./util"); var async = Promise._async; var tryCatch = util.tryCatch; var errorObj = util.errorObj; function spreadAdapter(val, nodeback) { var promise = this; if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); var ret = tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); if (ret === errorObj) { async.throwLater(ret.e); } } function successAdapter(val, nodeback) { var promise = this; var receiver = promise._boundValue(); var ret = val === undefined ? tryCatch(nodeback).call(receiver, null) : tryCatch(nodeback).call(receiver, null, val); if (ret === errorObj) { async.throwLater(ret.e); } } function errorAdapter(reason, nodeback) { var promise = this; if (!reason) { var newReason = new Error(reason + ""); newReason.cause = reason; reason = newReason; } var ret = tryCatch(nodeback).call(promise._boundValue(), reason); if (ret === errorObj) { async.throwLater(ret.e); } } Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, options) { if (typeof nodeback == "function") { var adapter = successAdapter; if (options !== undefined && Object(options).spread) { adapter = spreadAdapter; } this._then( adapter, errorAdapter, undefined, this, nodeback ); } return this; }; }; },{"./util":36}],22:[function(_dereq_,module,exports){ "use strict"; module.exports = function() { var makeSelfResolutionError = function () { return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); }; var reflectHandler = function() { return new Promise.PromiseInspection(this._target()); }; var apiRejection = function(msg) { return Promise.reject(new TypeError(msg)); }; function Proxyable() {} var UNDEFINED_BINDING = {}; var util = _dereq_("./util"); var getDomain; if (util.isNode) { getDomain = function() { var ret = process.domain; if (ret === undefined) ret = null; return ret; }; } else { getDomain = function() { return null; }; } util.notEnumerableProp(Promise, "_getDomain", getDomain); var es5 = _dereq_("./es5"); var Async = _dereq_("./async"); var async = new Async(); es5.defineProperty(Promise, "_async", {value: async}); var errors = _dereq_("./errors"); var TypeError = Promise.TypeError = errors.TypeError; Promise.RangeError = errors.RangeError; var CancellationError = Promise.CancellationError = errors.CancellationError; Promise.TimeoutError = errors.TimeoutError; Promise.OperationalError = errors.OperationalError; Promise.RejectionError = errors.OperationalError; Promise.AggregateError = errors.AggregateError; var INTERNAL = function(){}; var APPLY = {}; var NEXT_FILTER = {}; var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); var PromiseArray = _dereq_("./promise_array")(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable); var Context = _dereq_("./context")(Promise); /*jshint unused:false*/ var createContext = Context.create; var debug = _dereq_("./debuggability")(Promise, Context); var CapturedTrace = debug.CapturedTrace; var PassThroughHandlerContext = _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); var nodebackForPromise = _dereq_("./nodeback"); var errorObj = util.errorObj; var tryCatch = util.tryCatch; function check(self, executor) { if (self == null || self.constructor !== Promise) { throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } if (typeof executor !== "function") { throw new TypeError("expecting a function but got " + util.classString(executor)); } } function Promise(executor) { if (executor !== INTERNAL) { check(this, executor); } this._bitField = 0; this._fulfillmentHandler0 = undefined; this._rejectionHandler0 = undefined; this._promise0 = undefined; this._receiver0 = undefined; this._resolveFromExecutor(executor); this._promiseCreated(); this._fireEvent("promiseCreated", this); } Promise.prototype.toString = function () { return "[object Promise]"; }; Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { var len = arguments.length; if (len > 1) { var catchInstances = new Array(len - 1), j = 0, i; for (i = 0; i < len - 1; ++i) { var item = arguments[i]; if (util.isObject(item)) { catchInstances[j++] = item; } else { return apiRejection("Catch statement predicate: " + "expecting an object but got " + util.classString(item)); } } catchInstances.length = j; fn = arguments[i]; return this.then(undefined, catchFilter(catchInstances, fn, this)); } return this.then(undefined, fn); }; Promise.prototype.reflect = function () { return this._then(reflectHandler, reflectHandler, undefined, this, undefined); }; Promise.prototype.then = function (didFulfill, didReject) { if (debug.warnings() && arguments.length > 0 && typeof didFulfill !== "function" && typeof didReject !== "function") { var msg = ".then() only accepts functions but was passed: " + util.classString(didFulfill); if (arguments.length > 1) { msg += ", " + util.classString(didReject); } this._warn(msg); } return this._then(didFulfill, didReject, undefined, undefined, undefined); }; Promise.prototype.done = function (didFulfill, didReject) { var promise = this._then(didFulfill, didReject, undefined, undefined, undefined); promise._setIsFinal(); }; Promise.prototype.spread = function (fn) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } return this.all()._then(fn, undefined, undefined, APPLY, undefined); }; Promise.prototype.toJSON = function () { var ret = { isFulfilled: false, isRejected: false, fulfillmentValue: undefined, rejectionReason: undefined }; if (this.isFulfilled()) { ret.fulfillmentValue = this.value(); ret.isFulfilled = true; } else if (this.isRejected()) { ret.rejectionReason = this.reason(); ret.isRejected = true; } return ret; }; Promise.prototype.all = function () { if (arguments.length > 0) { this._warn(".all() was passed arguments but it does not take any"); } return new PromiseArray(this).promise(); }; Promise.prototype.error = function (fn) { return this.caught(util.originatesFromRejection, fn); }; Promise.getNewLibraryCopy = module.exports; Promise.is = function (val) { return val instanceof Promise; }; Promise.fromNode = Promise.fromCallback = function(fn) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs : false; var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); if (result === errorObj) { ret._rejectCallback(result.e, true); } if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); return ret; }; Promise.all = function (promises) { return new PromiseArray(promises).promise(); }; Promise.cast = function (obj) { var ret = tryConvertToPromise(obj); if (!(ret instanceof Promise)) { ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._setFulfilled(); ret._rejectionHandler0 = obj; } return ret; }; Promise.resolve = Promise.fulfilled = Promise.cast; Promise.reject = Promise.rejected = function (reason) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._rejectCallback(reason, true); return ret; }; Promise.setScheduler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } return async.setScheduler(fn); }; Promise.prototype._then = function ( didFulfill, didReject, _, receiver, internalData ) { var haveInternalData = internalData !== undefined; var promise = haveInternalData ? internalData : new Promise(INTERNAL); var target = this._target(); var bitField = target._bitField; if (!haveInternalData) { promise._propagateFrom(this, 3); promise._captureStackTrace(); if (receiver === undefined && ((this._bitField & 2097152) !== 0)) { if (!((bitField & 50397184) === 0)) { receiver = this._boundValue(); } else { receiver = target === this ? undefined : this._boundTo; } } this._fireEvent("promiseChained", this, promise); } var domain = getDomain(); if (!((bitField & 50397184) === 0)) { var handler, value, settler = target._settlePromiseCtx; if (((bitField & 33554432) !== 0)) { value = target._rejectionHandler0; handler = didFulfill; } else if (((bitField & 16777216) !== 0)) { value = target._fulfillmentHandler0; handler = didReject; target._unsetRejectionIsUnhandled(); } else { settler = target._settlePromiseLateCancellationObserver; value = new CancellationError("late cancellation observer"); target._attachExtraTrace(value); handler = didReject; } async.invoke(settler, target, { handler: domain === null ? handler : (typeof handler === "function" && util.domainBind(domain, handler)), promise: promise, receiver: receiver, value: value }); } else { target._addCallbacks(didFulfill, didReject, promise, receiver, domain); } return promise; }; Promise.prototype._length = function () { return this._bitField & 65535; }; Promise.prototype._isFateSealed = function () { return (this._bitField & 117506048) !== 0; }; Promise.prototype._isFollowing = function () { return (this._bitField & 67108864) === 67108864; }; Promise.prototype._setLength = function (len) { this._bitField = (this._bitField & -65536) | (len & 65535); }; Promise.prototype._setFulfilled = function () { this._bitField = this._bitField | 33554432; this._fireEvent("promiseFulfilled", this); }; Promise.prototype._setRejected = function () { this._bitField = this._bitField | 16777216; this._fireEvent("promiseRejected", this); }; Promise.prototype._setFollowing = function () { this._bitField = this._bitField | 67108864; this._fireEvent("promiseResolved", this); }; Promise.prototype._setIsFinal = function () { this._bitField = this._bitField | 4194304; }; Promise.prototype._isFinal = function () { return (this._bitField & 4194304) > 0; }; Promise.prototype._unsetCancelled = function() { this._bitField = this._bitField & (~65536); }; Promise.prototype._setCancelled = function() { this._bitField = this._bitField | 65536; this._fireEvent("promiseCancelled", this); }; Promise.prototype._setWillBeCancelled = function() { this._bitField = this._bitField | 8388608; }; Promise.prototype._setAsyncGuaranteed = function() { if (async.hasCustomScheduler()) return; this._bitField = this._bitField | 134217728; }; Promise.prototype._receiverAt = function (index) { var ret = index === 0 ? this._receiver0 : this[ index * 4 - 4 + 3]; if (ret === UNDEFINED_BINDING) { return undefined; } else if (ret === undefined && this._isBound()) { return this._boundValue(); } return ret; }; Promise.prototype._promiseAt = function (index) { return this[ index * 4 - 4 + 2]; }; Promise.prototype._fulfillmentHandlerAt = function (index) { return this[ index * 4 - 4 + 0]; }; Promise.prototype._rejectionHandlerAt = function (index) { return this[ index * 4 - 4 + 1]; }; Promise.prototype._boundValue = function() {}; Promise.prototype._migrateCallback0 = function (follower) { var bitField = follower._bitField; var fulfill = follower._fulfillmentHandler0; var reject = follower._rejectionHandler0; var promise = follower._promise0; var receiver = follower._receiverAt(0); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._migrateCallbackAt = function (follower, index) { var fulfill = follower._fulfillmentHandlerAt(index); var reject = follower._rejectionHandlerAt(index); var promise = follower._promiseAt(index); var receiver = follower._receiverAt(index); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._addCallbacks = function ( fulfill, reject, promise, receiver, domain ) { var index = this._length(); if (index >= 65535 - 4) { index = 0; this._setLength(0); } if (index === 0) { this._promise0 = promise; this._receiver0 = receiver; if (typeof fulfill === "function") { this._fulfillmentHandler0 = domain === null ? fulfill : util.domainBind(domain, fulfill); } if (typeof reject === "function") { this._rejectionHandler0 = domain === null ? reject : util.domainBind(domain, reject); } } else { var base = index * 4 - 4; this[base + 2] = promise; this[base + 3] = receiver; if (typeof fulfill === "function") { this[base + 0] = domain === null ? fulfill : util.domainBind(domain, fulfill); } if (typeof reject === "function") { this[base + 1] = domain === null ? reject : util.domainBind(domain, reject); } } this._setLength(index + 1); return index; }; Promise.prototype._proxy = function (proxyable, arg) { this._addCallbacks(undefined, undefined, arg, proxyable, null); }; Promise.prototype._resolveCallback = function(value, shouldBind) { if (((this._bitField & 117506048) !== 0)) return; if (value === this) return this._rejectCallback(makeSelfResolutionError(), false); var maybePromise = tryConvertToPromise(value, this); if (!(maybePromise instanceof Promise)) return this._fulfill(value); if (shouldBind) this._propagateFrom(maybePromise, 2); var promise = maybePromise._target(); if (promise === this) { this._reject(makeSelfResolutionError()); return; } var bitField = promise._bitField; if (((bitField & 50397184) === 0)) { var len = this._length(); if (len > 0) promise._migrateCallback0(this); for (var i = 1; i < len; ++i) { promise._migrateCallbackAt(this, i); } this._setFollowing(); this._setLength(0); this._setFollowee(promise); } else if (((bitField & 33554432) !== 0)) { this._fulfill(promise._value()); } else if (((bitField & 16777216) !== 0)) { this._reject(promise._reason()); } else { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); this._reject(reason); } }; Promise.prototype._rejectCallback = function(reason, synchronous, ignoreNonErrorWarnings) { var trace = util.ensureErrorObject(reason); var hasStack = trace === reason; if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { var message = "a promise was rejected with a non-error: " + util.classString(reason); this._warn(message, true); } this._attachExtraTrace(trace, synchronous ? hasStack : false); this._reject(reason); }; Promise.prototype._resolveFromExecutor = function (executor) { if (executor === INTERNAL) return; var promise = this; this._captureStackTrace(); this._pushContext(); var synchronous = true; var r = this._execute(executor, function(value) { promise._resolveCallback(value); }, function (reason) { promise._rejectCallback(reason, synchronous); }); synchronous = false; this._popContext(); if (r !== undefined) { promise._rejectCallback(r, true); } }; Promise.prototype._settlePromiseFromHandler = function ( handler, receiver, value, promise ) { var bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; promise._pushContext(); var x; if (receiver === APPLY) { if (!value || typeof value.length !== "number") { x = errorObj; x.e = new TypeError("cannot .spread() a non-array: " + util.classString(value)); } else { x = tryCatch(handler).apply(this._boundValue(), value); } } else { x = tryCatch(handler).call(receiver, value); } var promiseCreated = promise._popContext(); bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; if (x === NEXT_FILTER) { promise._reject(value); } else if (x === errorObj) { promise._rejectCallback(x.e, false); } else { debug.checkForgottenReturns(x, promiseCreated, "", promise, this); promise._resolveCallback(x); } }; Promise.prototype._target = function() { var ret = this; while (ret._isFollowing()) ret = ret._followee(); return ret; }; Promise.prototype._followee = function() { return this._rejectionHandler0; }; Promise.prototype._setFollowee = function(promise) { this._rejectionHandler0 = promise; }; Promise.prototype._settlePromise = function(promise, handler, receiver, value) { var isPromise = promise instanceof Promise; var bitField = this._bitField; var asyncGuaranteed = ((bitField & 134217728) !== 0); if (((bitField & 65536) !== 0)) { if (isPromise) promise._invokeInternalOnCancel(); if (receiver instanceof PassThroughHandlerContext && receiver.isFinallyHandler()) { receiver.cancelPromise = promise; if (tryCatch(handler).call(receiver, value) === errorObj) { promise._reject(errorObj.e); } } else if (handler === reflectHandler) { promise._fulfill(reflectHandler.call(receiver)); } else if (receiver instanceof Proxyable) { receiver._promiseCancelled(promise); } else if (isPromise || promise instanceof PromiseArray) { promise._cancel(); } else { receiver.cancel(); } } else if (typeof handler === "function") { if (!isPromise) { handler.call(receiver, value, promise); } else { if (asyncGuaranteed) promise._setAsyncGuaranteed(); this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (receiver instanceof Proxyable) { if (!receiver._isResolved()) { if (((bitField & 33554432) !== 0)) { receiver._promiseFulfilled(value, promise); } else { receiver._promiseRejected(value, promise); } } } else if (isPromise) { if (asyncGuaranteed) promise._setAsyncGuaranteed(); if (((bitField & 33554432) !== 0)) { promise._fulfill(value); } else { promise._reject(value); } } }; Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { var handler = ctx.handler; var promise = ctx.promise; var receiver = ctx.receiver; var value = ctx.value; if (typeof handler === "function") { if (!(promise instanceof Promise)) { handler.call(receiver, value, promise); } else { this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (promise instanceof Promise) { promise._reject(value); } }; Promise.prototype._settlePromiseCtx = function(ctx) { this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); }; Promise.prototype._settlePromise0 = function(handler, value, bitField) { var promise = this._promise0; var receiver = this._receiverAt(0); this._promise0 = undefined; this._receiver0 = undefined; this._settlePromise(promise, handler, receiver, value); }; Promise.prototype._clearCallbackDataAtIndex = function(index) { var base = index * 4 - 4; this[base + 2] = this[base + 3] = this[base + 0] = this[base + 1] = undefined; }; Promise.prototype._fulfill = function (value) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; if (value === this) { var err = makeSelfResolutionError(); this._attachExtraTrace(err); return this._reject(err); } this._setFulfilled(); this._rejectionHandler0 = value; if ((bitField & 65535) > 0) { if (((bitField & 134217728) !== 0)) { this._settlePromises(); } else { async.settlePromises(this); } } }; Promise.prototype._reject = function (reason) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; this._setRejected(); this._fulfillmentHandler0 = reason; if (this._isFinal()) { return async.fatalError(reason, util.isNode); } if ((bitField & 65535) > 0) { async.settlePromises(this); } else { this._ensurePossibleRejectionHandled(); } }; Promise.prototype._fulfillPromises = function (len, value) { for (var i = 1; i < len; i++) { var handler = this._fulfillmentHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, value); } }; Promise.prototype._rejectPromises = function (len, reason) { for (var i = 1; i < len; i++) { var handler = this._rejectionHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, reason); } }; Promise.prototype._settlePromises = function () { var bitField = this._bitField; var len = (bitField & 65535); if (len > 0) { if (((bitField & 16842752) !== 0)) { var reason = this._fulfillmentHandler0; this._settlePromise0(this._rejectionHandler0, reason, bitField); this._rejectPromises(len, reason); } else { var value = this._rejectionHandler0; this._settlePromise0(this._fulfillmentHandler0, value, bitField); this._fulfillPromises(len, value); } this._setLength(0); } this._clearCancellationData(); }; Promise.prototype._settledValue = function() { var bitField = this._bitField; if (((bitField & 33554432) !== 0)) { return this._rejectionHandler0; } else if (((bitField & 16777216) !== 0)) { return this._fulfillmentHandler0; } }; function deferResolve(v) {this.promise._resolveCallback(v);} function deferReject(v) {this.promise._rejectCallback(v, false);} Promise.defer = Promise.pending = function() { debug.deprecated("Promise.defer", "new Promise"); var promise = new Promise(INTERNAL); return { promise: promise, resolve: deferResolve, reject: deferReject }; }; util.notEnumerableProp(Promise, "_makeSelfResolutionError", makeSelfResolutionError); _dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug); _dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); _dereq_("./direct_resolve")(Promise); _dereq_("./synchronous_inspection")(Promise); _dereq_("./join")( Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); Promise.Promise = Promise; Promise.version = "3.5.1"; _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); _dereq_('./call_get.js')(Promise); _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); _dereq_('./timers.js')(Promise, INTERNAL, debug); _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); _dereq_('./nodeify.js')(Promise); _dereq_('./promisify.js')(Promise, INTERNAL); _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); _dereq_('./settle.js')(Promise, PromiseArray, debug); _dereq_('./some.js')(Promise, PromiseArray, apiRejection); _dereq_('./filter.js')(Promise, INTERNAL); _dereq_('./each.js')(Promise, INTERNAL); _dereq_('./any.js')(Promise); util.toFastProperties(Promise); util.toFastProperties(Promise.prototype); function fillTypes(value) { var p = new Promise(INTERNAL); p._fulfillmentHandler0 = value; p._rejectionHandler0 = value; p._promise0 = value; p._receiver0 = value; } // Complete slack tracking, opt out of field-type tracking and // stabilize map fillTypes({a: 1}); fillTypes({b: 2}); fillTypes({c: 3}); fillTypes(1); fillTypes(function(){}); fillTypes(undefined); fillTypes(false); fillTypes(new Promise(INTERNAL)); debug.setBounds(Async.firstLineError, util.lastLineError); return Promise; }; },{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable) { var util = _dereq_("./util"); var isArray = util.isArray; function toResolutionValue(val) { switch(val) { case -2: return []; case -3: return {}; case -6: return new Map(); } } function PromiseArray(values) { var promise = this._promise = new Promise(INTERNAL); if (values instanceof Promise) { promise._propagateFrom(values, 3); } promise._setOnCancel(this); this._values = values; this._length = 0; this._totalResolved = 0; this._init(undefined, -2); } util.inherits(PromiseArray, Proxyable); PromiseArray.prototype.length = function () { return this._length; }; PromiseArray.prototype.promise = function () { return this._promise; }; PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { var values = tryConvertToPromise(this._values, this._promise); if (values instanceof Promise) { values = values._target(); var bitField = values._bitField; ; this._values = values; if (((bitField & 50397184) === 0)) { this._promise._setAsyncGuaranteed(); return values._then( init, this._reject, undefined, this, resolveValueIfEmpty ); } else if (((bitField & 33554432) !== 0)) { values = values._value(); } else if (((bitField & 16777216) !== 0)) { return this._reject(values._reason()); } else { return this._cancel(); } } values = util.asArray(values); if (values === null) { var err = apiRejection( "expecting an array or an iterable object but got " + util.classString(values)).reason(); this._promise._rejectCallback(err, false); return; } if (values.length === 0) { if (resolveValueIfEmpty === -5) { this._resolveEmptyArray(); } else { this._resolve(toResolutionValue(resolveValueIfEmpty)); } return; } this._iterate(values); }; PromiseArray.prototype._iterate = function(values) { var len = this.getActualLength(values.length); this._length = len; this._values = this.shouldCopyValues() ? new Array(len) : this._values; var result = this._promise; var isResolved = false; var bitField = null; for (var i = 0; i < len; ++i) { var maybePromise = tryConvertToPromise(values[i], result); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); bitField = maybePromise._bitField; } else { bitField = null; } if (isResolved) { if (bitField !== null) { maybePromise.suppressUnhandledRejections(); } } else if (bitField !== null) { if (((bitField & 50397184) === 0)) { maybePromise._proxy(this, i); this._values[i] = maybePromise; } else if (((bitField & 33554432) !== 0)) { isResolved = this._promiseFulfilled(maybePromise._value(), i); } else if (((bitField & 16777216) !== 0)) { isResolved = this._promiseRejected(maybePromise._reason(), i); } else { isResolved = this._promiseCancelled(i); } } else { isResolved = this._promiseFulfilled(maybePromise, i); } } if (!isResolved) result._setAsyncGuaranteed(); }; PromiseArray.prototype._isResolved = function () { return this._values === null; }; PromiseArray.prototype._resolve = function (value) { this._values = null; this._promise._fulfill(value); }; PromiseArray.prototype._cancel = function() { if (this._isResolved() || !this._promise._isCancellable()) return; this._values = null; this._promise._cancel(); }; PromiseArray.prototype._reject = function (reason) { this._values = null; this._promise._rejectCallback(reason, false); }; PromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); return true; } return false; }; PromiseArray.prototype._promiseCancelled = function() { this._cancel(); return true; }; PromiseArray.prototype._promiseRejected = function (reason) { this._totalResolved++; this._reject(reason); return true; }; PromiseArray.prototype._resultCancelled = function() { if (this._isResolved()) return; var values = this._values; this._cancel(); if (values instanceof Promise) { values.cancel(); } else { for (var i = 0; i < values.length; ++i) { if (values[i] instanceof Promise) { values[i].cancel(); } } } }; PromiseArray.prototype.shouldCopyValues = function () { return true; }; PromiseArray.prototype.getActualLength = function (len) { return len; }; return PromiseArray; }; },{"./util":36}],24:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var THIS = {}; var util = _dereq_("./util"); var nodebackForPromise = _dereq_("./nodeback"); var withAppended = util.withAppended; var maybeWrapAsError = util.maybeWrapAsError; var canEvaluate = util.canEvaluate; var TypeError = _dereq_("./errors").TypeError; var defaultSuffix = "Async"; var defaultPromisified = {__isPromisified__: true}; var noCopyProps = [ "arity", "length", "name", "arguments", "caller", "callee", "prototype", "__isPromisified__" ]; var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); var defaultFilter = function(name) { return util.isIdentifier(name) && name.charAt(0) !== "_" && name !== "constructor"; }; function propsFilter(key) { return !noCopyPropsPattern.test(key); } function isPromisified(fn) { try { return fn.__isPromisified__ === true; } catch (e) { return false; } } function hasPromisified(obj, key, suffix) { var val = util.getDataPropertyOrDefault(obj, key + suffix, defaultPromisified); return val ? isPromisified(val) : false; } function checkValid(ret, suffix, suffixRegexp) { for (var i = 0; i < ret.length; i += 2) { var key = ret[i]; if (suffixRegexp.test(key)) { var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); for (var j = 0; j < ret.length; j += 2) { if (ret[j] === keyWithoutAsyncSuffix) { throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" .replace("%s", suffix)); } } } } } function promisifiableMethods(obj, suffix, suffixRegexp, filter) { var keys = util.inheritedDataKeys(obj); var ret = []; for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var value = obj[key]; var passesDefaultFilter = filter === defaultFilter ? true : defaultFilter(key, value, obj); if (typeof value === "function" && !isPromisified(value) && !hasPromisified(obj, key, suffix) && filter(key, value, obj, passesDefaultFilter)) { ret.push(key, value); } } checkValid(ret, suffix, suffixRegexp); return ret; } var escapeIdentRegex = function(str) { return str.replace(/([$])/, "\\$"); }; var makeNodePromisifiedEval; if (!true) { var switchCaseArgumentOrder = function(likelyArgumentCount) { var ret = [likelyArgumentCount]; var min = Math.max(0, likelyArgumentCount - 1 - 3); for(var i = likelyArgumentCount - 1; i >= min; --i) { ret.push(i); } for(var i = likelyArgumentCount + 1; i <= 3; ++i) { ret.push(i); } return ret; }; var argumentSequence = function(argumentCount) { return util.filledRange(argumentCount, "_arg", ""); }; var parameterDeclaration = function(parameterCount) { return util.filledRange( Math.max(parameterCount, 3), "_arg", ""); }; var parameterCount = function(fn) { if (typeof fn.length === "number") { return Math.max(Math.min(fn.length, 1023 + 1), 0); } return 0; }; makeNodePromisifiedEval = function(callback, receiver, originalName, fn, _, multiArgs) { var newParameterCount = Math.max(0, parameterCount(fn) - 1); var argumentOrder = switchCaseArgumentOrder(newParameterCount); var shouldProxyThis = typeof callback === "string" || receiver === THIS; function generateCallForArgumentCount(count) { var args = argumentSequence(count).join(", "); var comma = count > 0 ? ", " : ""; var ret; if (shouldProxyThis) { ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; } else { ret = receiver === undefined ? "ret = callback({{args}}, nodeback); break;\n" : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; } return ret.replace("{{args}}", args).replace(", ", comma); } function generateArgumentSwitchCase() { var ret = ""; for (var i = 0; i < argumentOrder.length; ++i) { ret += "case " + argumentOrder[i] +":" + generateCallForArgumentCount(argumentOrder[i]); } ret += " \n\ default: \n\ var args = new Array(len + 1); \n\ var i = 0; \n\ for (var i = 0; i < len; ++i) { \n\ args[i] = arguments[i]; \n\ } \n\ args[i] = nodeback; \n\ [CodeForCall] \n\ break; \n\ ".replace("[CodeForCall]", (shouldProxyThis ? "ret = callback.apply(this, args);\n" : "ret = callback.apply(receiver, args);\n")); return ret; } var getFunctionCode = typeof callback === "string" ? ("this != null ? this['"+callback+"'] : fn") : "fn"; var body = "'use strict'; \n\ var ret = function (Parameters) { \n\ 'use strict'; \n\ var len = arguments.length; \n\ var promise = new Promise(INTERNAL); \n\ promise._captureStackTrace(); \n\ var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ var ret; \n\ var callback = tryCatch([GetFunctionCode]); \n\ switch(len) { \n\ [CodeForSwitchCase] \n\ } \n\ if (ret === errorObj) { \n\ promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ } \n\ if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ return promise; \n\ }; \n\ notEnumerableProp(ret, '__isPromisified__', true); \n\ return ret; \n\ ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) .replace("[GetFunctionCode]", getFunctionCode); body = body.replace("Parameters", parameterDeclaration(newParameterCount)); return new Function("Promise", "fn", "receiver", "withAppended", "maybeWrapAsError", "nodebackForPromise", "tryCatch", "errorObj", "notEnumerableProp", "INTERNAL", body)( Promise, fn, receiver, withAppended, maybeWrapAsError, nodebackForPromise, util.tryCatch, util.errorObj, util.notEnumerableProp, INTERNAL); }; } function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { var defaultThis = (function() {return this;})(); var method = callback; if (typeof method === "string") { callback = fn; } function promisified() { var _receiver = receiver; if (receiver === THIS) _receiver = this; var promise = new Promise(INTERNAL); promise._captureStackTrace(); var cb = typeof method === "string" && this !== defaultThis ? this[method] : callback; var fn = nodebackForPromise(promise, multiArgs); try { cb.apply(_receiver, withAppended(arguments, fn)); } catch(e) { promise._rejectCallback(maybeWrapAsError(e), true, true); } if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); return promise; } util.notEnumerableProp(promisified, "__isPromisified__", true); return promisified; } var makeNodePromisified = canEvaluate ? makeNodePromisifiedEval : makeNodePromisifiedClosure; function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); var methods = promisifiableMethods(obj, suffix, suffixRegexp, filter); for (var i = 0, len = methods.length; i < len; i+= 2) { var key = methods[i]; var fn = methods[i+1]; var promisifiedKey = key + suffix; if (promisifier === makeNodePromisified) { obj[promisifiedKey] = makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); } else { var promisified = promisifier(fn, function() { return makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); }); util.notEnumerableProp(promisified, "__isPromisified__", true); obj[promisifiedKey] = promisified; } } util.toFastProperties(obj); return obj; } function promisify(callback, receiver, multiArgs) { return makeNodePromisified(callback, receiver, undefined, callback, null, multiArgs); } Promise.promisify = function (fn, options) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } if (isPromisified(fn)) { return fn; } options = Object(options); var receiver = options.context === undefined ? THIS : options.context; var multiArgs = !!options.multiArgs; var ret = promisify(fn, receiver, multiArgs); util.copyDescriptors(fn, ret, propsFilter); return ret; }; Promise.promisifyAll = function (target, options) { if (typeof target !== "function" && typeof target !== "object") { throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } options = Object(options); var multiArgs = !!options.multiArgs; var suffix = options.suffix; if (typeof suffix !== "string") suffix = defaultSuffix; var filter = options.filter; if (typeof filter !== "function") filter = defaultFilter; var promisifier = options.promisifier; if (typeof promisifier !== "function") promisifier = makeNodePromisified; if (!util.isIdentifier(suffix)) { throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var keys = util.inheritedDataKeys(target); for (var i = 0; i < keys.length; ++i) { var value = target[keys[i]]; if (keys[i] !== "constructor" && util.isClass(value)) { promisifyAll(value.prototype, suffix, filter, promisifier, multiArgs); promisifyAll(value, suffix, filter, promisifier, multiArgs); } } return promisifyAll(target, suffix, filter, promisifier, multiArgs); }; }; },{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, PromiseArray, tryConvertToPromise, apiRejection) { var util = _dereq_("./util"); var isObject = util.isObject; var es5 = _dereq_("./es5"); var Es6Map; if (typeof Map === "function") Es6Map = Map; var mapToEntries = (function() { var index = 0; var size = 0; function extractEntry(value, key) { this[index] = value; this[index + size] = key; index++; } return function mapToEntries(map) { size = map.size; index = 0; var ret = new Array(map.size * 2); map.forEach(extractEntry, ret); return ret; }; })(); var entriesToMap = function(entries) { var ret = new Es6Map(); var length = entries.length / 2 | 0; for (var i = 0; i < length; ++i) { var key = entries[length + i]; var value = entries[i]; ret.set(key, value); } return ret; }; function PropertiesPromiseArray(obj) { var isMap = false; var entries; if (Es6Map !== undefined && obj instanceof Es6Map) { entries = mapToEntries(obj); isMap = true; } else { var keys = es5.keys(obj); var len = keys.length; entries = new Array(len * 2); for (var i = 0; i < len; ++i) { var key = keys[i]; entries[i] = obj[key]; entries[i + len] = key; } } this.constructor$(entries); this._isMap = isMap; this._init$(undefined, isMap ? -6 : -3); } util.inherits(PropertiesPromiseArray, PromiseArray); PropertiesPromiseArray.prototype._init = function () {}; PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { var val; if (this._isMap) { val = entriesToMap(this._values); } else { val = {}; var keyOffset = this.length(); for (var i = 0, len = this.length(); i < len; ++i) { val[this._values[i + keyOffset]] = this._values[i]; } } this._resolve(val); return true; } return false; }; PropertiesPromiseArray.prototype.shouldCopyValues = function () { return false; }; PropertiesPromiseArray.prototype.getActualLength = function (len) { return len >> 1; }; function props(promises) { var ret; var castValue = tryConvertToPromise(promises); if (!isObject(castValue)) { return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } else if (castValue instanceof Promise) { ret = castValue._then( Promise.props, undefined, undefined, undefined, undefined); } else { ret = new PropertiesPromiseArray(castValue).promise(); } if (castValue instanceof Promise) { ret._propagateFrom(castValue, 2); } return ret; } Promise.prototype.props = function () { return props(this); }; Promise.props = function (promises) { return props(promises); }; }; },{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){ "use strict"; function arrayMove(src, srcIndex, dst, dstIndex, len) { for (var j = 0; j < len; ++j) { dst[j + dstIndex] = src[j + srcIndex]; src[j + srcIndex] = void 0; } } function Queue(capacity) { this._capacity = capacity; this._length = 0; this._front = 0; } Queue.prototype._willBeOverCapacity = function (size) { return this._capacity < size; }; Queue.prototype._pushOne = function (arg) { var length = this.length(); this._checkCapacity(length + 1); var i = (this._front + length) & (this._capacity - 1); this[i] = arg; this._length = length + 1; }; Queue.prototype.push = function (fn, receiver, arg) { var length = this.length() + 3; if (this._willBeOverCapacity(length)) { this._pushOne(fn); this._pushOne(receiver); this._pushOne(arg); return; } var j = this._front + length - 3; this._checkCapacity(length); var wrapMask = this._capacity - 1; this[(j + 0) & wrapMask] = fn; this[(j + 1) & wrapMask] = receiver; this[(j + 2) & wrapMask] = arg; this._length = length; }; Queue.prototype.shift = function () { var front = this._front, ret = this[front]; this[front] = undefined; this._front = (front + 1) & (this._capacity - 1); this._length--; return ret; }; Queue.prototype.length = function () { return this._length; }; Queue.prototype._checkCapacity = function (size) { if (this._capacity < size) { this._resizeTo(this._capacity << 1); } }; Queue.prototype._resizeTo = function (capacity) { var oldCapacity = this._capacity; this._capacity = capacity; var front = this._front; var length = this._length; var moveItemsCount = (front + length) & (oldCapacity - 1); arrayMove(this, 0, this, oldCapacity, moveItemsCount); }; module.exports = Queue; },{}],27:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, INTERNAL, tryConvertToPromise, apiRejection) { var util = _dereq_("./util"); var raceLater = function (promise) { return promise.then(function(array) { return race(array, promise); }); }; function race(promises, parent) { var maybePromise = tryConvertToPromise(promises); if (maybePromise instanceof Promise) { return raceLater(maybePromise); } else { promises = util.asArray(promises); if (promises === null) return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); } var ret = new Promise(INTERNAL); if (parent !== undefined) { ret._propagateFrom(parent, 3); } var fulfill = ret._fulfill; var reject = ret._reject; for (var i = 0, len = promises.length; i < len; ++i) { var val = promises[i]; if (val === undefined && !(i in promises)) { continue; } Promise.cast(val)._then(fulfill, reject, undefined, ret, null); } return ret; } Promise.race = function (promises) { return race(promises, undefined); }; Promise.prototype.race = function () { return race(this, undefined); }; }; },{"./util":36}],28:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { var getDomain = Promise._getDomain; var util = _dereq_("./util"); var tryCatch = util.tryCatch; function ReductionPromiseArray(promises, fn, initialValue, _each) { this.constructor$(promises); var domain = getDomain(); this._fn = domain === null ? fn : util.domainBind(domain, fn); if (initialValue !== undefined) { initialValue = Promise.resolve(initialValue); initialValue._attachCancellationCallback(this); } this._initialValue = initialValue; this._currentCancellable = null; if(_each === INTERNAL) { this._eachValues = Array(this._length); } else if (_each === 0) { this._eachValues = null; } else { this._eachValues = undefined; } this._promise._captureStackTrace(); this._init$(undefined, -5); } util.inherits(ReductionPromiseArray, PromiseArray); ReductionPromiseArray.prototype._gotAccum = function(accum) { if (this._eachValues !== undefined && this._eachValues !== null && accum !== INTERNAL) { this._eachValues.push(accum); } }; ReductionPromiseArray.prototype._eachComplete = function(value) { if (this._eachValues !== null) { this._eachValues.push(value); } return this._eachValues; }; ReductionPromiseArray.prototype._init = function() {}; ReductionPromiseArray.prototype._resolveEmptyArray = function() { this._resolve(this._eachValues !== undefined ? this._eachValues : this._initialValue); }; ReductionPromiseArray.prototype.shouldCopyValues = function () { return false; }; ReductionPromiseArray.prototype._resolve = function(value) { this._promise._resolveCallback(value); this._values = null; }; ReductionPromiseArray.prototype._resultCancelled = function(sender) { if (sender === this._initialValue) return this._cancel(); if (this._isResolved()) return; this._resultCancelled$(); if (this._currentCancellable instanceof Promise) { this._currentCancellable.cancel(); } if (this._initialValue instanceof Promise) { this._initialValue.cancel(); } }; ReductionPromiseArray.prototype._iterate = function (values) { this._values = values; var value; var i; var length = values.length; if (this._initialValue !== undefined) { value = this._initialValue; i = 0; } else { value = Promise.resolve(values[0]); i = 1; } this._currentCancellable = value; if (!value.isRejected()) { for (; i < length; ++i) { var ctx = { accum: null, value: values[i], index: i, length: length, array: this }; value = value._then(gotAccum, undefined, undefined, ctx, undefined); } } if (this._eachValues !== undefined) { value = value ._then(this._eachComplete, undefined, undefined, this, undefined); } value._then(completed, completed, undefined, value, this); }; Promise.prototype.reduce = function (fn, initialValue) { return reduce(this, fn, initialValue, null); }; Promise.reduce = function (promises, fn, initialValue, _each) { return reduce(promises, fn, initialValue, _each); }; function completed(valueOrReason, array) { if (this.isFulfilled()) { array._resolve(valueOrReason); } else { array._reject(valueOrReason); } } function reduce(promises, fn, initialValue, _each) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var array = new ReductionPromiseArray(promises, fn, initialValue, _each); return array.promise(); } function gotAccum(accum) { this.accum = accum; this.array._gotAccum(accum); var value = tryConvertToPromise(this.value, this.array._promise); if (value instanceof Promise) { this.array._currentCancellable = value; return value._then(gotValue, undefined, undefined, this, undefined); } else { return gotValue.call(this, value); } } function gotValue(value) { var array = this.array; var promise = array._promise; var fn = tryCatch(array._fn); promise._pushContext(); var ret; if (array._eachValues !== undefined) { ret = fn.call(promise._boundValue(), value, this.index, this.length); } else { ret = fn.call(promise._boundValue(), this.accum, value, this.index, this.length); } if (ret instanceof Promise) { array._currentCancellable = ret; } var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", promise ); return ret; } }; },{"./util":36}],29:[function(_dereq_,module,exports){ "use strict"; var util = _dereq_("./util"); var schedule; var noAsyncScheduler = function() { throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); }; var NativePromise = util.getNativePromise(); if (util.isNode && typeof MutationObserver === "undefined") { var GlobalSetImmediate = global.setImmediate; var ProcessNextTick = process.nextTick; schedule = util.isRecentNode ? function(fn) { GlobalSetImmediate.call(global, fn); } : function(fn) { ProcessNextTick.call(process, fn); }; } else if (typeof NativePromise === "function" && typeof NativePromise.resolve === "function") { var nativePromise = NativePromise.resolve(); schedule = function(fn) { nativePromise.then(fn); }; } else if ((typeof MutationObserver !== "undefined") && !(typeof window !== "undefined" && window.navigator && (window.navigator.standalone || window.cordova))) { schedule = (function() { var div = document.createElement("div"); var opts = {attributes: true}; var toggleScheduled = false; var div2 = document.createElement("div"); var o2 = new MutationObserver(function() { div.classList.toggle("foo"); toggleScheduled = false; }); o2.observe(div2, opts); var scheduleToggle = function() { if (toggleScheduled) return; toggleScheduled = true; div2.classList.toggle("foo"); }; return function schedule(fn) { var o = new MutationObserver(function() { o.disconnect(); fn(); }); o.observe(div, opts); scheduleToggle(); }; })(); } else if (typeof setImmediate !== "undefined") { schedule = function (fn) { setImmediate(fn); }; } else if (typeof setTimeout !== "undefined") { schedule = function (fn) { setTimeout(fn, 0); }; } else { schedule = noAsyncScheduler; } module.exports = schedule; },{"./util":36}],30:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, debug) { var PromiseInspection = Promise.PromiseInspection; var util = _dereq_("./util"); function SettledPromiseArray(values) { this.constructor$(values); } util.inherits(SettledPromiseArray, PromiseArray); SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { this._values[index] = inspection; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); return true; } return false; }; SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { var ret = new PromiseInspection(); ret._bitField = 33554432; ret._settledValueField = value; return this._promiseResolved(index, ret); }; SettledPromiseArray.prototype._promiseRejected = function (reason, index) { var ret = new PromiseInspection(); ret._bitField = 16777216; ret._settledValueField = reason; return this._promiseResolved(index, ret); }; Promise.settle = function (promises) { debug.deprecated(".settle()", ".reflect()"); return new SettledPromiseArray(promises).promise(); }; Promise.prototype.settle = function () { return Promise.settle(this); }; }; },{"./util":36}],31:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection) { var util = _dereq_("./util"); var RangeError = _dereq_("./errors").RangeError; var AggregateError = _dereq_("./errors").AggregateError; var isArray = util.isArray; var CANCELLATION = {}; function SomePromiseArray(values) { this.constructor$(values); this._howMany = 0; this._unwrap = false; this._initialized = false; } util.inherits(SomePromiseArray, PromiseArray); SomePromiseArray.prototype._init = function () { if (!this._initialized) { return; } if (this._howMany === 0) { this._resolve([]); return; } this._init$(undefined, -5); var isArrayResolved = isArray(this._values); if (!this._isResolved() && isArrayResolved && this._howMany > this._canPossiblyFulfill()) { this._reject(this._getRangeError(this.length())); } }; SomePromiseArray.prototype.init = function () { this._initialized = true; this._init(); }; SomePromiseArray.prototype.setUnwrap = function () { this._unwrap = true; }; SomePromiseArray.prototype.howMany = function () { return this._howMany; }; SomePromiseArray.prototype.setHowMany = function (count) { this._howMany = count; }; SomePromiseArray.prototype._promiseFulfilled = function (value) { this._addFulfilled(value); if (this._fulfilled() === this.howMany()) { this._values.length = this.howMany(); if (this.howMany() === 1 && this._unwrap) { this._resolve(this._values[0]); } else { this._resolve(this._values); } return true; } return false; }; SomePromiseArray.prototype._promiseRejected = function (reason) { this._addRejected(reason); return this._checkOutcome(); }; SomePromiseArray.prototype._promiseCancelled = function () { if (this._values instanceof Promise || this._values == null) { return this._cancel(); } this._addRejected(CANCELLATION); return this._checkOutcome(); }; SomePromiseArray.prototype._checkOutcome = function() { if (this.howMany() > this._canPossiblyFulfill()) { var e = new AggregateError(); for (var i = this.length(); i < this._values.length; ++i) { if (this._values[i] !== CANCELLATION) { e.push(this._values[i]); } } if (e.length > 0) { this._reject(e); } else { this._cancel(); } return true; } return false; }; SomePromiseArray.prototype._fulfilled = function () { return this._totalResolved; }; SomePromiseArray.prototype._rejected = function () { return this._values.length - this.length(); }; SomePromiseArray.prototype._addRejected = function (reason) { this._values.push(reason); }; SomePromiseArray.prototype._addFulfilled = function (value) { this._values[this._totalResolved++] = value; }; SomePromiseArray.prototype._canPossiblyFulfill = function () { return this.length() - this._rejected(); }; SomePromiseArray.prototype._getRangeError = function (count) { var message = "Input array must contain at least " + this._howMany + " items but contains only " + count + " items"; return new RangeError(message); }; SomePromiseArray.prototype._resolveEmptyArray = function () { this._reject(this._getRangeError(0)); }; function some(promises, howMany) { if ((howMany | 0) !== howMany || howMany < 0) { return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var ret = new SomePromiseArray(promises); var promise = ret.promise(); ret.setHowMany(howMany); ret.init(); return promise; } Promise.some = function (promises, howMany) { return some(promises, howMany); }; Promise.prototype.some = function (howMany) { return some(this, howMany); }; Promise._SomePromiseArray = SomePromiseArray; }; },{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { function PromiseInspection(promise) { if (promise !== undefined) { promise = promise._target(); this._bitField = promise._bitField; this._settledValueField = promise._isFateSealed() ? promise._settledValue() : undefined; } else { this._bitField = 0; this._settledValueField = undefined; } } PromiseInspection.prototype._settledValue = function() { return this._settledValueField; }; var value = PromiseInspection.prototype.value = function () { if (!this.isFulfilled()) { throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } return this._settledValue(); }; var reason = PromiseInspection.prototype.error = PromiseInspection.prototype.reason = function () { if (!this.isRejected()) { throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } return this._settledValue(); }; var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { return (this._bitField & 33554432) !== 0; }; var isRejected = PromiseInspection.prototype.isRejected = function () { return (this._bitField & 16777216) !== 0; }; var isPending = PromiseInspection.prototype.isPending = function () { return (this._bitField & 50397184) === 0; }; var isResolved = PromiseInspection.prototype.isResolved = function () { return (this._bitField & 50331648) !== 0; }; PromiseInspection.prototype.isCancelled = function() { return (this._bitField & 8454144) !== 0; }; Promise.prototype.__isCancelled = function() { return (this._bitField & 65536) === 65536; }; Promise.prototype._isCancelled = function() { return this._target().__isCancelled(); }; Promise.prototype.isCancelled = function() { return (this._target()._bitField & 8454144) !== 0; }; Promise.prototype.isPending = function() { return isPending.call(this._target()); }; Promise.prototype.isRejected = function() { return isRejected.call(this._target()); }; Promise.prototype.isFulfilled = function() { return isFulfilled.call(this._target()); }; Promise.prototype.isResolved = function() { return isResolved.call(this._target()); }; Promise.prototype.value = function() { return value.call(this._target()); }; Promise.prototype.reason = function() { var target = this._target(); target._unsetRejectionIsUnhandled(); return reason.call(target); }; Promise.prototype._value = function() { return this._settledValue(); }; Promise.prototype._reason = function() { this._unsetRejectionIsUnhandled(); return this._settledValue(); }; Promise.PromiseInspection = PromiseInspection; }; },{}],33:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var util = _dereq_("./util"); var errorObj = util.errorObj; var isObject = util.isObject; function tryConvertToPromise(obj, context) { if (isObject(obj)) { if (obj instanceof Promise) return obj; var then = getThen(obj); if (then === errorObj) { if (context) context._pushContext(); var ret = Promise.reject(then.e); if (context) context._popContext(); return ret; } else if (typeof then === "function") { if (isAnyBluebirdPromise(obj)) { var ret = new Promise(INTERNAL); obj._then( ret._fulfill, ret._reject, undefined, ret, null ); return ret; } return doThenable(obj, then, context); } } return obj; } function doGetThen(obj) { return obj.then; } function getThen(obj) { try { return doGetThen(obj); } catch (e) { errorObj.e = e; return errorObj; } } var hasProp = {}.hasOwnProperty; function isAnyBluebirdPromise(obj) { try { return hasProp.call(obj, "_promise0"); } catch (e) { return false; } } function doThenable(x, then, context) { var promise = new Promise(INTERNAL); var ret = promise; if (context) context._pushContext(); promise._captureStackTrace(); if (context) context._popContext(); var synchronous = true; var result = util.tryCatch(then).call(x, resolve, reject); synchronous = false; if (promise && result === errorObj) { promise._rejectCallback(result.e, true, true); promise = null; } function resolve(value) { if (!promise) return; promise._resolveCallback(value); promise = null; } function reject(reason) { if (!promise) return; promise._rejectCallback(reason, synchronous, true); promise = null; } return ret; } return tryConvertToPromise; }; },{"./util":36}],34:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, debug) { var util = _dereq_("./util"); var TimeoutError = Promise.TimeoutError; function HandleWrapper(handle) { this.handle = handle; } HandleWrapper.prototype._resultCancelled = function() { clearTimeout(this.handle); }; var afterValue = function(value) { return delay(+this).thenReturn(value); }; var delay = Promise.delay = function (ms, value) { var ret; var handle; if (value !== undefined) { ret = Promise.resolve(value) ._then(afterValue, null, null, ms, undefined); if (debug.cancellation() && value instanceof Promise) { ret._setOnCancel(value); } } else { ret = new Promise(INTERNAL); handle = setTimeout(function() { ret._fulfill(); }, +ms); if (debug.cancellation()) { ret._setOnCancel(new HandleWrapper(handle)); } ret._captureStackTrace(); } ret._setAsyncGuaranteed(); return ret; }; Promise.prototype.delay = function (ms) { return delay(ms, this); }; var afterTimeout = function (promise, message, parent) { var err; if (typeof message !== "string") { if (message instanceof Error) { err = message; } else { err = new TimeoutError("operation timed out"); } } else { err = new TimeoutError(message); } util.markAsOriginatingFromRejection(err); promise._attachExtraTrace(err); promise._reject(err); if (parent != null) { parent.cancel(); } }; function successClear(value) { clearTimeout(this.handle); return value; } function failureClear(reason) { clearTimeout(this.handle); throw reason; } Promise.prototype.timeout = function (ms, message) { ms = +ms; var ret, parent; var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { if (ret.isPending()) { afterTimeout(ret, message, parent); } }, ms)); if (debug.cancellation()) { parent = this.then(); ret = parent._then(successClear, failureClear, undefined, handleWrapper, undefined); ret._setOnCancel(handleWrapper); } else { ret = this._then(successClear, failureClear, undefined, handleWrapper, undefined); } return ret; }; }; },{"./util":36}],35:[function(_dereq_,module,exports){ "use strict"; module.exports = function (Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug) { var util = _dereq_("./util"); var TypeError = _dereq_("./errors").TypeError; var inherits = _dereq_("./util").inherits; var errorObj = util.errorObj; var tryCatch = util.tryCatch; var NULL = {}; function thrower(e) { setTimeout(function(){throw e;}, 0); } function castPreservingDisposable(thenable) { var maybePromise = tryConvertToPromise(thenable); if (maybePromise !== thenable && typeof thenable._isDisposable === "function" && typeof thenable._getDisposer === "function" && thenable._isDisposable()) { maybePromise._setDisposable(thenable._getDisposer()); } return maybePromise; } function dispose(resources, inspection) { var i = 0; var len = resources.length; var ret = new Promise(INTERNAL); function iterator() { if (i >= len) return ret._fulfill(); var maybePromise = castPreservingDisposable(resources[i++]); if (maybePromise instanceof Promise && maybePromise._isDisposable()) { try { maybePromise = tryConvertToPromise( maybePromise._getDisposer().tryDispose(inspection), resources.promise); } catch (e) { return thrower(e); } if (maybePromise instanceof Promise) { return maybePromise._then(iterator, thrower, null, null, null); } } iterator(); } iterator(); return ret; } function Disposer(data, promise, context) { this._data = data; this._promise = promise; this._context = context; } Disposer.prototype.data = function () { return this._data; }; Disposer.prototype.promise = function () { return this._promise; }; Disposer.prototype.resource = function () { if (this.promise().isFulfilled()) { return this.promise().value(); } return NULL; }; Disposer.prototype.tryDispose = function(inspection) { var resource = this.resource(); var context = this._context; if (context !== undefined) context._pushContext(); var ret = resource !== NULL ? this.doDispose(resource, inspection) : null; if (context !== undefined) context._popContext(); this._promise._unsetDisposable(); this._data = null; return ret; }; Disposer.isDisposer = function (d) { return (d != null && typeof d.resource === "function" && typeof d.tryDispose === "function"); }; function FunctionDisposer(fn, promise, context) { this.constructor$(fn, promise, context); } inherits(FunctionDisposer, Disposer); FunctionDisposer.prototype.doDispose = function (resource, inspection) { var fn = this.data(); return fn.call(resource, resource, inspection); }; function maybeUnwrapDisposer(value) { if (Disposer.isDisposer(value)) { this.resources[this.index]._setDisposable(value); return value.promise(); } return value; } function ResourceList(length) { this.length = length; this.promise = null; this[length-1] = null; } ResourceList.prototype._resultCancelled = function() { var len = this.length; for (var i = 0; i < len; ++i) { var item = this[i]; if (item instanceof Promise) { item.cancel(); } } }; Promise.using = function () { var len = arguments.length; if (len < 2) return apiRejection( "you must pass at least 2 arguments to Promise.using"); var fn = arguments[len - 1]; if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var input; var spreadArgs = true; if (len === 2 && Array.isArray(arguments[0])) { input = arguments[0]; len = input.length; spreadArgs = false; } else { input = arguments; len--; } var resources = new ResourceList(len); for (var i = 0; i < len; ++i) { var resource = input[i]; if (Disposer.isDisposer(resource)) { var disposer = resource; resource = resource.promise(); resource._setDisposable(disposer); } else { var maybePromise = tryConvertToPromise(resource); if (maybePromise instanceof Promise) { resource = maybePromise._then(maybeUnwrapDisposer, null, null, { resources: resources, index: i }, undefined); } } resources[i] = resource; } var reflectedResources = new Array(resources.length); for (var i = 0; i < reflectedResources.length; ++i) { reflectedResources[i] = Promise.resolve(resources[i]).reflect(); } var resultPromise = Promise.all(reflectedResources) .then(function(inspections) { for (var i = 0; i < inspections.length; ++i) { var inspection = inspections[i]; if (inspection.isRejected()) { errorObj.e = inspection.error(); return errorObj; } else if (!inspection.isFulfilled()) { resultPromise.cancel(); return; } inspections[i] = inspection.value(); } promise._pushContext(); fn = tryCatch(fn); var ret = spreadArgs ? fn.apply(undefined, inspections) : fn(inspections); var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, "Promise.using", promise); return ret; }); var promise = resultPromise.lastly(function() { var inspection = new Promise.PromiseInspection(resultPromise); return dispose(resources, inspection); }); resources.promise = promise; promise._setOnCancel(resources); return promise; }; Promise.prototype._setDisposable = function (disposer) { this._bitField = this._bitField | 131072; this._disposer = disposer; }; Promise.prototype._isDisposable = function () { return (this._bitField & 131072) > 0; }; Promise.prototype._getDisposer = function () { return this._disposer; }; Promise.prototype._unsetDisposable = function () { this._bitField = this._bitField & (~131072); this._disposer = undefined; }; Promise.prototype.disposer = function (fn) { if (typeof fn === "function") { return new FunctionDisposer(fn, this, createContext()); } throw new TypeError(); }; }; },{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ "use strict"; var es5 = _dereq_("./es5"); var canEvaluate = typeof navigator == "undefined"; var errorObj = {e: {}}; var tryCatchTarget; var globalObject = typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : this !== undefined ? this : null; function tryCatcher() { try { var target = tryCatchTarget; tryCatchTarget = null; return target.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { tryCatchTarget = fn; return tryCatcher; } var inherits = function(Child, Parent) { var hasProp = {}.hasOwnProperty; function T() { this.constructor = Child; this.constructor$ = Parent; for (var propertyName in Parent.prototype) { if (hasProp.call(Parent.prototype, propertyName) && propertyName.charAt(propertyName.length-1) !== "$" ) { this[propertyName + "$"] = Parent.prototype[propertyName]; } } } T.prototype = Parent.prototype; Child.prototype = new T(); return Child.prototype; }; function isPrimitive(val) { return val == null || val === true || val === false || typeof val === "string" || typeof val === "number"; } function isObject(value) { return typeof value === "function" || typeof value === "object" && value !== null; } function maybeWrapAsError(maybeError) { if (!isPrimitive(maybeError)) return maybeError; return new Error(safeToString(maybeError)); } function withAppended(target, appendee) { var len = target.length; var ret = new Array(len + 1); var i; for (i = 0; i < len; ++i) { ret[i] = target[i]; } ret[i] = appendee; return ret; } function getDataPropertyOrDefault(obj, key, defaultValue) { if (es5.isES5) { var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc != null) { return desc.get == null && desc.set == null ? desc.value : defaultValue; } } else { return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; } } function notEnumerableProp(obj, name, value) { if (isPrimitive(obj)) return obj; var descriptor = { value: value, configurable: true, enumerable: false, writable: true }; es5.defineProperty(obj, name, descriptor); return obj; } function thrower(r) { throw r; } var inheritedDataKeys = (function() { var excludedPrototypes = [ Array.prototype, Object.prototype, Function.prototype ]; var isExcludedProto = function(val) { for (var i = 0; i < excludedPrototypes.length; ++i) { if (excludedPrototypes[i] === val) { return true; } } return false; }; if (es5.isES5) { var getKeys = Object.getOwnPropertyNames; return function(obj) { var ret = []; var visitedKeys = Object.create(null); while (obj != null && !isExcludedProto(obj)) { var keys; try { keys = getKeys(obj); } catch (e) { return ret; } for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (visitedKeys[key]) continue; visitedKeys[key] = true; var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc != null && desc.get == null && desc.set == null) { ret.push(key); } } obj = es5.getPrototypeOf(obj); } return ret; }; } else { var hasProp = {}.hasOwnProperty; return function(obj) { if (isExcludedProto(obj)) return []; var ret = []; /*jshint forin:false */ enumeration: for (var key in obj) { if (hasProp.call(obj, key)) { ret.push(key); } else { for (var i = 0; i < excludedPrototypes.length; ++i) { if (hasProp.call(excludedPrototypes[i], key)) { continue enumeration; } } ret.push(key); } } return ret; }; } })(); var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; function isClass(fn) { try { if (typeof fn === "function") { var keys = es5.names(fn.prototype); var hasMethods = es5.isES5 && keys.length > 1; var hasMethodsOtherThanConstructor = keys.length > 0 && !(keys.length === 1 && keys[0] === "constructor"); var hasThisAssignmentAndStaticMethods = thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; if (hasMethods || hasMethodsOtherThanConstructor || hasThisAssignmentAndStaticMethods) { return true; } } return false; } catch (e) { return false; } } function toFastProperties(obj) { /*jshint -W027,-W055,-W031*/ function FakeConstructor() {} FakeConstructor.prototype = obj; var l = 8; while (l--) new FakeConstructor(); return obj; eval(obj); } var rident = /^[a-z$_][a-z$_0-9]*$/i; function isIdentifier(str) { return rident.test(str); } function filledRange(count, prefix, suffix) { var ret = new Array(count); for(var i = 0; i < count; ++i) { ret[i] = prefix + i + suffix; } return ret; } function safeToString(obj) { try { return obj + ""; } catch (e) { return "[no string representation]"; } } function isError(obj) { return obj instanceof Error || (obj !== null && typeof obj === "object" && typeof obj.message === "string" && typeof obj.name === "string"); } function markAsOriginatingFromRejection(e) { try { notEnumerableProp(e, "isOperational", true); } catch(ignore) {} } function originatesFromRejection(e) { if (e == null) return false; return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || e["isOperational"] === true); } function canAttachTrace(obj) { return isError(obj) && es5.propertyIsWritable(obj, "stack"); } var ensureErrorObject = (function() { if (!("stack" in new Error())) { return function(value) { if (canAttachTrace(value)) return value; try {throw new Error(safeToString(value));} catch(err) {return err;} }; } else { return function(value) { if (canAttachTrace(value)) return value; return new Error(safeToString(value)); }; } })(); function classString(obj) { return {}.toString.call(obj); } function copyDescriptors(from, to, filter) { var keys = es5.names(from); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (filter(key)) { try { es5.defineProperty(to, key, es5.getDescriptor(from, key)); } catch (ignore) {} } } } var asArray = function(v) { if (es5.isArray(v)) { return v; } return null; }; if (typeof Symbol !== "undefined" && Symbol.iterator) { var ArrayFrom = typeof Array.from === "function" ? function(v) { return Array.from(v); } : function(v) { var ret = []; var it = v[Symbol.iterator](); var itResult; while (!((itResult = it.next()).done)) { ret.push(itResult.value); } return ret; }; asArray = function(v) { if (es5.isArray(v)) { return v; } else if (v != null && typeof v[Symbol.iterator] === "function") { return ArrayFrom(v); } return null; }; } var isNode = typeof process !== "undefined" && classString(process).toLowerCase() === "[object process]"; var hasEnvVariables = typeof process !== "undefined" && typeof process.env !== "undefined"; function env(key) { return hasEnvVariables ? process.env[key] : undefined; } function getNativePromise() { if (typeof Promise === "function") { try { var promise = new Promise(function(){}); if ({}.toString.call(promise) === "[object Promise]") { return Promise; } } catch (e) {} } } function domainBind(self, cb) { return self.bind(cb); } var ret = { isClass: isClass, isIdentifier: isIdentifier, inheritedDataKeys: inheritedDataKeys, getDataPropertyOrDefault: getDataPropertyOrDefault, thrower: thrower, isArray: es5.isArray, asArray: asArray, notEnumerableProp: notEnumerableProp, isPrimitive: isPrimitive, isObject: isObject, isError: isError, canEvaluate: canEvaluate, errorObj: errorObj, tryCatch: tryCatch, inherits: inherits, withAppended: withAppended, maybeWrapAsError: maybeWrapAsError, toFastProperties: toFastProperties, filledRange: filledRange, toString: safeToString, canAttachTrace: canAttachTrace, ensureErrorObject: ensureErrorObject, originatesFromRejection: originatesFromRejection, markAsOriginatingFromRejection: markAsOriginatingFromRejection, classString: classString, copyDescriptors: copyDescriptors, hasDevTools: typeof chrome !== "undefined" && chrome && typeof chrome.loadTimes === "function", isNode: isNode, hasEnvVariables: hasEnvVariables, env: env, global: globalObject, getNativePromise: getNativePromise, domainBind: domainBind }; ret.isRecentNode = ret.isNode && (function() { var version = process.versions.node.split(".").map(Number); return (version[0] === 0 && version[1] > 10) || (version[0] > 0); })(); if (ret.isNode) ret.toFastProperties(process); try {throw new Error(); } catch (e) {ret.lastLineError = e;} module.exports = ret; },{"./es5":13}]},{},[4])(4) }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate) },{"_process":325,"timers":329}],109:[function(require,module,exports){ (function (global){(function (){ /** * Module dependencies. * @ignore */ // Test if we're in Node via presence of "global" not absence of "window" // to support hybrid environments like Electron if (typeof global !== 'undefined') { var Buffer = require('buffer').Buffer; // TODO just use global Buffer } var utils = require('./parser/utils'); /** * A class representation of the BSON Binary type. * * Sub types * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. * * @class * @param {Buffer} buffer a buffer object containing the binary data. * @param {Number} [subType] the option binary type. * @return {Binary} */ function Binary(buffer, subType) { if (!(this instanceof Binary)) return new Binary(buffer, subType); if ( buffer != null && !(typeof buffer === 'string') && !Buffer.isBuffer(buffer) && !(buffer instanceof Uint8Array) && !Array.isArray(buffer) ) { throw new Error('only String, Buffer, Uint8Array or Array accepted'); } this._bsontype = 'Binary'; if (buffer instanceof Number) { this.sub_type = buffer; this.position = 0; } else { this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; this.position = 0; } if (buffer != null && !(buffer instanceof Number)) { // Only accept Buffer, Uint8Array or Arrays if (typeof buffer === 'string') { // Different ways of writing the length of the string for the different types if (typeof Buffer !== 'undefined') { this.buffer = utils.toBuffer(buffer); } else if ( typeof Uint8Array !== 'undefined' || Object.prototype.toString.call(buffer) === '[object Array]' ) { this.buffer = writeStringToArray(buffer); } else { throw new Error('only String, Buffer, Uint8Array or Array accepted'); } } else { this.buffer = buffer; } this.position = buffer.length; } else { if (typeof Buffer !== 'undefined') { this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE); } else if (typeof Uint8Array !== 'undefined') { this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); } else { this.buffer = new Array(Binary.BUFFER_SIZE); } // Set position to start of buffer this.position = 0; } } /** * Updates this binary with byte_value. * * @method * @param {string} byte_value a single byte we wish to write. */ Binary.prototype.put = function put(byte_value) { // If it's a string and a has more than one character throw an error if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) throw new Error('only accepts single character String, Uint8Array or Array'); if ((typeof byte_value !== 'number' && byte_value < 0) || byte_value > 255) throw new Error('only accepts number in a valid unsigned byte range 0-255'); // Decode the byte value once var decoded_byte = null; if (typeof byte_value === 'string') { decoded_byte = byte_value.charCodeAt(0); } else if (byte_value['length'] != null) { decoded_byte = byte_value[0]; } else { decoded_byte = byte_value; } if (this.buffer.length > this.position) { this.buffer[this.position++] = decoded_byte; } else { if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { // Create additional overflow buffer var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length); // Combine the two buffers together this.buffer.copy(buffer, 0, 0, this.buffer.length); this.buffer = buffer; this.buffer[this.position++] = decoded_byte; } else { buffer = null; // Create a new buffer (typed or normal array) if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); } else { buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); } // We need to copy all the content to the new array for (var i = 0; i < this.buffer.length; i++) { buffer[i] = this.buffer[i]; } // Reassign the buffer this.buffer = buffer; // Write the byte this.buffer[this.position++] = decoded_byte; } } }; /** * Writes a buffer or string to the binary. * * @method * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. * @param {number} offset specify the binary of where to write the content. * @return {null} */ Binary.prototype.write = function write(string, offset) { offset = typeof offset === 'number' ? offset : this.position; // If the buffer is to small let's extend the buffer if (this.buffer.length < offset + string.length) { var buffer = null; // If we are in node.js if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { buffer = utils.allocBuffer(this.buffer.length + string.length); this.buffer.copy(buffer, 0, 0, this.buffer.length); } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { // Create a new buffer buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); // Copy the content for (var i = 0; i < this.position; i++) { buffer[i] = this.buffer[i]; } } // Assign the new buffer this.buffer = buffer; } if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { string.copy(this.buffer, offset, 0, string.length); this.position = offset + string.length > this.position ? offset + string.length : this.position; // offset = string.length } else if ( typeof Buffer !== 'undefined' && typeof string === 'string' && Buffer.isBuffer(this.buffer) ) { this.buffer.write(string, offset, 'binary'); this.position = offset + string.length > this.position ? offset + string.length : this.position; // offset = string.length; } else if ( Object.prototype.toString.call(string) === '[object Uint8Array]' || (Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') ) { for (i = 0; i < string.length; i++) { this.buffer[offset++] = string[i]; } this.position = offset > this.position ? offset : this.position; } else if (typeof string === 'string') { for (i = 0; i < string.length; i++) { this.buffer[offset++] = string.charCodeAt(i); } this.position = offset > this.position ? offset : this.position; } }; /** * Reads **length** bytes starting at **position**. * * @method * @param {number} position read from the given position in the Binary. * @param {number} length the number of bytes to read. * @return {Buffer} */ Binary.prototype.read = function read(position, length) { length = length && length > 0 ? length : this.position; // Let's return the data based on the type we have if (this.buffer['slice']) { return this.buffer.slice(position, position + length); } else { // Create a buffer to keep the result var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); for (var i = 0; i < length; i++) { buffer[i] = this.buffer[position++]; } } // Return the buffer return buffer; }; /** * Returns the value of this binary as a string. * * @method * @return {string} */ Binary.prototype.value = function value(asRaw) { asRaw = asRaw == null ? false : asRaw; // Optimize to serialize for the situation where the data == size of buffer if ( asRaw && typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length === this.position ) return this.buffer; // If it's a node.js buffer object if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); } else { if (asRaw) { // we support the slice command use it if (this.buffer['slice'] != null) { return this.buffer.slice(0, this.position); } else { // Create a new buffer to copy content to var newBuffer = Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); // Copy content for (var i = 0; i < this.position; i++) { newBuffer[i] = this.buffer[i]; } // Return the buffer return newBuffer; } } else { return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); } } }; /** * Length. * * @method * @return {number} the length of the binary. */ Binary.prototype.length = function length() { return this.position; }; /** * @ignore */ Binary.prototype.toJSON = function() { return this.buffer != null ? this.buffer.toString('base64') : ''; }; /** * @ignore */ Binary.prototype.toString = function(format) { return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; }; /** * Binary default subtype * @ignore */ var BSON_BINARY_SUBTYPE_DEFAULT = 0; /** * @ignore */ var writeStringToArray = function(data) { // Create a buffer var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); // Write the content to the buffer for (var i = 0; i < data.length; i++) { buffer[i] = data.charCodeAt(i); } // Write the string to the buffer return buffer; }; /** * Convert Array ot Uint8Array to Binary String * * @ignore */ var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { var result = ''; for (var i = startIndex; i < endIndex; i++) { result = result + String.fromCharCode(byteArray[i]); } return result; }; Binary.BUFFER_SIZE = 256; /** * Default BSON type * * @classconstant SUBTYPE_DEFAULT **/ Binary.SUBTYPE_DEFAULT = 0; /** * Function BSON type * * @classconstant SUBTYPE_DEFAULT **/ Binary.SUBTYPE_FUNCTION = 1; /** * Byte Array BSON type * * @classconstant SUBTYPE_DEFAULT **/ Binary.SUBTYPE_BYTE_ARRAY = 2; /** * OLD UUID BSON type * * @classconstant SUBTYPE_DEFAULT **/ Binary.SUBTYPE_UUID_OLD = 3; /** * UUID BSON type * * @classconstant SUBTYPE_DEFAULT **/ Binary.SUBTYPE_UUID = 4; /** * MD5 BSON type * * @classconstant SUBTYPE_DEFAULT **/ Binary.SUBTYPE_MD5 = 5; /** * User BSON type * * @classconstant SUBTYPE_DEFAULT **/ Binary.SUBTYPE_USER_DEFINED = 128; /** * Expose. */ module.exports = Binary; module.exports.Binary = Binary; }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./parser/utils":125,"buffer":129}],110:[function(require,module,exports){ 'use strict'; var Map = require('./map'), Long = require('./long'), Double = require('./double'), Timestamp = require('./timestamp'), ObjectID = require('./objectid'), BSONRegExp = require('./regexp'), Symbol = require('./symbol'), Int32 = require('./int_32'), Code = require('./code'), Decimal128 = require('./decimal128'), MinKey = require('./min_key'), MaxKey = require('./max_key'), DBRef = require('./db_ref'), Binary = require('./binary'); // Parts of the parser var deserialize = require('./parser/deserializer'), serializer = require('./parser/serializer'), calculateObjectSize = require('./parser/calculate_size'), utils = require('./parser/utils'); /** * @ignore * @api private */ // Default Max Size var MAXSIZE = 1024 * 1024 * 17; // Current Internal Temporary Serialization Buffer var buffer = utils.allocBuffer(MAXSIZE); var BSON = function() {}; /** * Serialize a Javascript object. * * @param {Object} object the Javascript object to serialize. * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. * @return {Buffer} returns the Buffer object containing the serialized object. * @api public */ BSON.prototype.serialize = function serialize(object, options) { options = options || {}; // Unpack the options var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; // Resize the internal serialization buffer if needed if (buffer.length < minInternalBufferSize) { buffer = utils.allocBuffer(minInternalBufferSize); } // Attempt to serialize var serializationIndex = serializer( buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, [] ); // Create the final buffer var finishedBuffer = utils.allocBuffer(serializationIndex); // Copy into the finished buffer buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); // Return the buffer return finishedBuffer; }; /** * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. * * @param {Object} object the Javascript object to serialize. * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. * @return {Number} returns the index pointing to the last written byte in the buffer. * @api public */ BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) { options = options || {}; // Unpack the options var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; var startIndex = typeof options.index === 'number' ? options.index : 0; // Attempt to serialize var serializationIndex = serializer( finalBuffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined ); // Return the index return serializationIndex - 1; }; /** * Deserialize data as BSON. * * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. * @return {Object} returns the deserialized Javascript Object. * @api public */ BSON.prototype.deserialize = function(buffer, options) { return deserialize(buffer, options); }; /** * Calculate the bson size for a passed in Javascript object. * * @param {Object} object the Javascript object to calculate the BSON byte size for. * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. * @return {Number} returns the number of bytes the BSON object will take up. * @api public */ BSON.prototype.calculateObjectSize = function(object, options) { options = options || {}; var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; return calculateObjectSize(object, serializeFunctions, ignoreUndefined); }; /** * Deserialize stream data as BSON documents. * * @param {Buffer} data the buffer containing the serialized set of BSON documents. * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. * @param {Number} numberOfDocuments number of documents to deserialize. * @param {Array} documents an array where to store the deserialized documents. * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. * @param {Object} [options] additional options used for the deserialization. * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. * @api public */ BSON.prototype.deserializeStream = function( data, startIndex, numberOfDocuments, documents, docStartIndex, options ) { options = options != null ? options : {}; var index = startIndex; // Loop over all documents for (var i = 0; i < numberOfDocuments; i++) { // Find size of the document var size = data[index] | (data[index + 1] << 8) | (data[index + 2] << 16) | (data[index + 3] << 24); // Update options with index options['index'] = index; // Parse the document at this point documents[docStartIndex + i] = this.deserialize(data, options); // Adjust index by the document size index = index + size; } // Return object containing end index of parsing and list of documents return index; }; /** * @ignore * @api private */ // BSON MAX VALUES BSON.BSON_INT32_MAX = 0x7fffffff; BSON.BSON_INT32_MIN = -0x80000000; BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; BSON.BSON_INT64_MIN = -Math.pow(2, 63); // JS MAX PRECISE VALUES BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. // Internal long versions // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. /** * Number BSON Type * * @classconstant BSON_DATA_NUMBER **/ BSON.BSON_DATA_NUMBER = 1; /** * String BSON Type * * @classconstant BSON_DATA_STRING **/ BSON.BSON_DATA_STRING = 2; /** * Object BSON Type * * @classconstant BSON_DATA_OBJECT **/ BSON.BSON_DATA_OBJECT = 3; /** * Array BSON Type * * @classconstant BSON_DATA_ARRAY **/ BSON.BSON_DATA_ARRAY = 4; /** * Binary BSON Type * * @classconstant BSON_DATA_BINARY **/ BSON.BSON_DATA_BINARY = 5; /** * ObjectID BSON Type * * @classconstant BSON_DATA_OID **/ BSON.BSON_DATA_OID = 7; /** * Boolean BSON Type * * @classconstant BSON_DATA_BOOLEAN **/ BSON.BSON_DATA_BOOLEAN = 8; /** * Date BSON Type * * @classconstant BSON_DATA_DATE **/ BSON.BSON_DATA_DATE = 9; /** * null BSON Type * * @classconstant BSON_DATA_NULL **/ BSON.BSON_DATA_NULL = 10; /** * RegExp BSON Type * * @classconstant BSON_DATA_REGEXP **/ BSON.BSON_DATA_REGEXP = 11; /** * Code BSON Type * * @classconstant BSON_DATA_CODE **/ BSON.BSON_DATA_CODE = 13; /** * Symbol BSON Type * * @classconstant BSON_DATA_SYMBOL **/ BSON.BSON_DATA_SYMBOL = 14; /** * Code with Scope BSON Type * * @classconstant BSON_DATA_CODE_W_SCOPE **/ BSON.BSON_DATA_CODE_W_SCOPE = 15; /** * 32 bit Integer BSON Type * * @classconstant BSON_DATA_INT **/ BSON.BSON_DATA_INT = 16; /** * Timestamp BSON Type * * @classconstant BSON_DATA_TIMESTAMP **/ BSON.BSON_DATA_TIMESTAMP = 17; /** * Long BSON Type * * @classconstant BSON_DATA_LONG **/ BSON.BSON_DATA_LONG = 18; /** * MinKey BSON Type * * @classconstant BSON_DATA_MIN_KEY **/ BSON.BSON_DATA_MIN_KEY = 0xff; /** * MaxKey BSON Type * * @classconstant BSON_DATA_MAX_KEY **/ BSON.BSON_DATA_MAX_KEY = 0x7f; /** * Binary Default Type * * @classconstant BSON_BINARY_SUBTYPE_DEFAULT **/ BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; /** * Binary Function Type * * @classconstant BSON_BINARY_SUBTYPE_FUNCTION **/ BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; /** * Binary Byte Array Type * * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY **/ BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; /** * Binary UUID Type * * @classconstant BSON_BINARY_SUBTYPE_UUID **/ BSON.BSON_BINARY_SUBTYPE_UUID = 3; /** * Binary MD5 Type * * @classconstant BSON_BINARY_SUBTYPE_MD5 **/ BSON.BSON_BINARY_SUBTYPE_MD5 = 4; /** * Binary User Defined Type * * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED **/ BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; // Return BSON module.exports = BSON; module.exports.Code = Code; module.exports.Map = Map; module.exports.Symbol = Symbol; module.exports.BSON = BSON; module.exports.DBRef = DBRef; module.exports.Binary = Binary; module.exports.ObjectID = ObjectID; module.exports.Long = Long; module.exports.Timestamp = Timestamp; module.exports.Double = Double; module.exports.Int32 = Int32; module.exports.MinKey = MinKey; module.exports.MaxKey = MaxKey; module.exports.BSONRegExp = BSONRegExp; module.exports.Decimal128 = Decimal128; },{"./binary":109,"./code":111,"./db_ref":112,"./decimal128":113,"./double":114,"./int_32":116,"./long":117,"./map":118,"./max_key":119,"./min_key":120,"./objectid":121,"./parser/calculate_size":122,"./parser/deserializer":123,"./parser/serializer":124,"./parser/utils":125,"./regexp":126,"./symbol":127,"./timestamp":128}],111:[function(require,module,exports){ /** * A class representation of the BSON Code type. * * @class * @param {(string|function)} code a string or function. * @param {Object} [scope] an optional scope for the function. * @return {Code} */ var Code = function Code(code, scope) { if (!(this instanceof Code)) return new Code(code, scope); this._bsontype = 'Code'; this.code = code; this.scope = scope; }; /** * @ignore */ Code.prototype.toJSON = function() { return { scope: this.scope, code: this.code }; }; module.exports = Code; module.exports.Code = Code; },{}],112:[function(require,module,exports){ /** * A class representation of the BSON DBRef type. * * @class * @param {string} namespace the collection name. * @param {ObjectID} oid the reference ObjectID. * @param {string} [db] optional db name, if omitted the reference is local to the current db. * @return {DBRef} */ function DBRef(namespace, oid, db) { if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); this._bsontype = 'DBRef'; this.namespace = namespace; this.oid = oid; this.db = db; } /** * @ignore * @api private */ DBRef.prototype.toJSON = function() { return { $ref: this.namespace, $id: this.oid, $db: this.db == null ? '' : this.db }; }; module.exports = DBRef; module.exports.DBRef = DBRef; },{}],113:[function(require,module,exports){ 'use strict'; var Long = require('./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+)?$/; var utils = require('./parser/utils'); // Detect if the value is a digit var isDigit = function(value) { return !isNaN(parseInt(value, 10)); }; // Divide two uint128 values var divideu128 = function(value) { var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); var _rem = Long.fromNumber(0); var i = 0; if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { return { quotient: value, rem: _rem }; } for (i = 0; i <= 3; i++) { // Adjust remainder to match value of next dividend _rem = _rem.shiftLeft(32); // Add the divided to _rem _rem = _rem.add(new Long(value.parts[i], 0)); value.parts[i] = _rem.div(DIVISOR).low_; _rem = _rem.modulo(DIVISOR); } return { quotient: value, rem: _rem }; }; // Multiply two Long values and return the 128 bit value var multiply64x2 = function(left, right) { if (!left && !right) { return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; } var leftHigh = left.shiftRightUnsigned(32); var leftLow = new Long(left.getLowBits(), 0); var rightHigh = right.shiftRightUnsigned(32); var rightLow = new Long(right.getLowBits(), 0); var productHigh = leftHigh.multiply(rightHigh); var productMid = leftHigh.multiply(rightLow); var productMid2 = leftLow.multiply(rightHigh); var productLow = leftLow.multiply(rightLow); productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); productMid = new Long(productMid.getLowBits(), 0) .add(productMid2) .add(productLow.shiftRightUnsigned(32)); productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); // Return the 128 bit result return { high: productHigh, low: productLow }; }; var lessThan = function(left, right) { // Make values unsigned var uhleft = left.high_ >>> 0; var uhright = right.high_ >>> 0; // Compare high bits first if (uhleft < uhright) { return true; } else if (uhleft === uhright) { var ulleft = left.low_ >>> 0; var ulright = right.low_ >>> 0; if (ulleft < ulright) return true; } return false; }; // var longtoHex = function(value) { // var buffer = utils.allocBuffer(8); // var index = 0; // // Encode the low 64 bits of the decimal // // Encode low bits // buffer[index++] = value.low_ & 0xff; // buffer[index++] = (value.low_ >> 8) & 0xff; // buffer[index++] = (value.low_ >> 16) & 0xff; // buffer[index++] = (value.low_ >> 24) & 0xff; // // Encode high bits // buffer[index++] = value.high_ & 0xff; // buffer[index++] = (value.high_ >> 8) & 0xff; // buffer[index++] = (value.high_ >> 16) & 0xff; // buffer[index++] = (value.high_ >> 24) & 0xff; // return buffer.reverse().toString('hex'); // }; // var int32toHex = function(value) { // var buffer = utils.allocBuffer(4); // var index = 0; // // Encode the low 64 bits of the decimal // // Encode low bits // buffer[index++] = value & 0xff; // buffer[index++] = (value >> 8) & 0xff; // buffer[index++] = (value >> 16) & 0xff; // buffer[index++] = (value >> 24) & 0xff; // return buffer.reverse().toString('hex'); // }; /** * A class representation of the BSON Decimal128 type. * * @class * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. * @return {Double} */ var Decimal128 = function(bytes) { this._bsontype = 'Decimal128'; this.bytes = bytes; }; /** * Create a Decimal128 instance from a string representation * * @method * @param {string} string a numeric string representation. * @return {Decimal128} returns a Decimal128 instance. */ Decimal128.fromString = function(string) { // Parse state tracking var isNegative = false; var sawRadix = false; var foundNonZero = false; // Total number of significant digits (no leading or trailing zero) var significantDigits = 0; // Total number of significand digits read var nDigitsRead = 0; // Total number of digits (no leading zeros) var nDigits = 0; // The number of the digits after radix var radixPosition = 0; // The index of the first non-zero in *str* var firstNonZero = 0; // Digits Array var digits = [0]; // The number of digits in digits var nDigitsStored = 0; // Insertion pointer for digits var digitsInsert = 0; // The index of the first non-zero digit var firstDigit = 0; // The index of the last digit var lastDigit = 0; // Exponent var exponent = 0; // loop index over array var i = 0; // The high 17 digits of the significand var significandHigh = [0, 0]; // The low 17 digits of the significand var significandLow = [0, 0]; // The biased exponent var biasedExponent = 0; // Read index var index = 0; // Trim the string string = string.trim(); // Naively prevent against REDOS attacks. // TODO: implementing a custom parsing for this, or refactoring the regex would yield // further gains. if (string.length >= 7000) { throw new Error('' + string + ' not a valid Decimal128 string'); } // Results var stringMatch = string.match(PARSE_STRING_REGEXP); var infMatch = string.match(PARSE_INF_REGEXP); var nanMatch = string.match(PARSE_NAN_REGEXP); // Validate the string if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) { throw new Error('' + string + ' not a valid Decimal128 string'); } // Check if we have an illegal exponent format if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { throw new Error('' + string + ' not a valid Decimal128 string'); } // Get the negative or positive sign if (string[index] === '+' || string[index] === '-') { isNegative = string[index++] === '-'; } // Check if user passed Infinity or NaN if (!isDigit(string[index]) && string[index] !== '.') { if (string[index] === 'i' || string[index] === 'I') { return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); } else if (string[index] === 'N') { return new Decimal128(utils.toBuffer(NAN_BUFFER)); } } // Read all the digits while (isDigit(string[index]) || string[index] === '.') { if (string[index] === '.') { if (sawRadix) { return new Decimal128(utils.toBuffer(NAN_BUFFER)); } sawRadix = true; index = index + 1; continue; } if (nDigitsStored < 34) { if (string[index] !== '0' || foundNonZero) { if (!foundNonZero) { firstNonZero = nDigitsRead; } foundNonZero = true; // Only store 34 digits digits[digitsInsert++] = parseInt(string[index], 10); nDigitsStored = nDigitsStored + 1; } } if (foundNonZero) { nDigits = nDigits + 1; } if (sawRadix) { radixPosition = radixPosition + 1; } nDigitsRead = nDigitsRead + 1; index = index + 1; } if (sawRadix && !nDigitsRead) { throw new Error('' + string + ' not a valid Decimal128 string'); } // Read exponent if exists if (string[index] === 'e' || string[index] === 'E') { // Read exponent digits var match = string.substr(++index).match(EXPONENT_REGEX); // No digits read if (!match || !match[2]) { return new Decimal128(utils.toBuffer(NAN_BUFFER)); } // Get exponent exponent = parseInt(match[0], 10); // Adjust the index index = index + match[0].length; } // Return not a number if (string[index]) { return new Decimal128(utils.toBuffer(NAN_BUFFER)); } // Done reading input // Find first non-zero digit in digits firstDigit = 0; if (!nDigitsStored) { firstDigit = 0; lastDigit = 0; digits[0] = 0; nDigits = 1; nDigitsStored = 1; significantDigits = 0; } else { lastDigit = nDigitsStored - 1; significantDigits = nDigits; if (exponent !== 0 && significantDigits !== 1) { while (string[firstNonZero + significantDigits - 1] === '0') { significantDigits = significantDigits - 1; } } } // Normalization of exponent // Correct exponent based on radix position, and shift significand as needed // to represent user input // Overflow prevention if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { exponent = EXPONENT_MIN; } else { exponent = exponent - radixPosition; } // Attempt to normalize the exponent while (exponent > EXPONENT_MAX) { // Shift exponent to significand and decrease lastDigit = lastDigit + 1; if (lastDigit - firstDigit > MAX_DIGITS) { // Check if we have a zero then just hard clamp, otherwise fail var digitsString = digits.join(''); if (digitsString.match(/^0+$/)) { exponent = EXPONENT_MAX; break; } else { return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); } } exponent = exponent - 1; } while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { // Shift last digit if (lastDigit === 0) { exponent = EXPONENT_MIN; significantDigits = 0; break; } if (nDigitsStored < nDigits) { // adjust to match digits not stored nDigits = nDigits - 1; } else { // adjust to round lastDigit = lastDigit - 1; } if (exponent < EXPONENT_MAX) { exponent = exponent + 1; } else { // Check if we have a zero then just hard clamp, otherwise fail digitsString = digits.join(''); if (digitsString.match(/^0+$/)) { exponent = EXPONENT_MAX; break; } else { return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); } } } // Round // We've normalized the exponent, but might still need to round. if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { var endOfString = nDigitsRead; // If we have seen a radix point, 'string' is 1 longer than we have // documented with ndigits_read, so inc the position of the first nonzero // digit and the position that digits are read to. if (sawRadix && exponent === EXPONENT_MIN) { firstNonZero = firstNonZero + 1; endOfString = endOfString + 1; } var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); var roundBit = 0; if (roundDigit >= 5) { roundBit = 1; if (roundDigit === 5) { roundBit = digits[lastDigit] % 2 === 1; for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { if (parseInt(string[i], 10)) { roundBit = 1; break; } } } } if (roundBit) { var dIdx = lastDigit; for (; dIdx >= 0; dIdx--) { if (++digits[dIdx] > 9) { digits[dIdx] = 0; // overflowed most significant digit if (dIdx === 0) { if (exponent < EXPONENT_MAX) { exponent = exponent + 1; digits[dIdx] = 1; } else { return new Decimal128( utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER) ); } } } else { break; } } } } // Encode significand // The high 17 digits of the significand significandHigh = Long.fromNumber(0); // The low 17 digits of the significand significandLow = Long.fromNumber(0); // read a zero if (significantDigits === 0) { significandHigh = Long.fromNumber(0); significandLow = Long.fromNumber(0); } else if (lastDigit - firstDigit < 17) { dIdx = firstDigit; significandLow = Long.fromNumber(digits[dIdx++]); significandHigh = new Long(0, 0); for (; dIdx <= lastDigit; dIdx++) { significandLow = significandLow.multiply(Long.fromNumber(10)); significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); } } else { dIdx = firstDigit; significandHigh = Long.fromNumber(digits[dIdx++]); for (; dIdx <= lastDigit - 17; dIdx++) { significandHigh = significandHigh.multiply(Long.fromNumber(10)); significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); } significandLow = Long.fromNumber(digits[dIdx++]); for (; dIdx <= lastDigit; dIdx++) { significandLow = significandLow.multiply(Long.fromNumber(10)); significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); } } var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); significand.low = significand.low.add(significandLow); if (lessThan(significand.low, significandLow)) { significand.high = significand.high.add(Long.fromNumber(1)); } // Biased exponent biasedExponent = exponent + EXPONENT_BIAS; var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; // Encode combination, exponent, and significand. if ( significand.high .shiftRightUnsigned(49) .and(Long.fromNumber(1)) .equals(Long.fromNumber) ) { // Encode '11' into bits 1 to 3 dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); dec.high = dec.high.or( Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) ); dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); } else { dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); } dec.low = significand.low; // Encode sign if (isNegative) { dec.high = dec.high.or(Long.fromString('9223372036854775808')); } // Encode into a buffer var buffer = utils.allocBuffer(16); index = 0; // Encode the low 64 bits of the decimal // Encode low bits buffer[index++] = dec.low.low_ & 0xff; buffer[index++] = (dec.low.low_ >> 8) & 0xff; buffer[index++] = (dec.low.low_ >> 16) & 0xff; buffer[index++] = (dec.low.low_ >> 24) & 0xff; // Encode high bits buffer[index++] = dec.low.high_ & 0xff; buffer[index++] = (dec.low.high_ >> 8) & 0xff; buffer[index++] = (dec.low.high_ >> 16) & 0xff; buffer[index++] = (dec.low.high_ >> 24) & 0xff; // Encode the high 64 bits of the decimal // Encode low bits buffer[index++] = dec.high.low_ & 0xff; buffer[index++] = (dec.high.low_ >> 8) & 0xff; buffer[index++] = (dec.high.low_ >> 16) & 0xff; buffer[index++] = (dec.high.low_ >> 24) & 0xff; // Encode high bits buffer[index++] = dec.high.high_ & 0xff; buffer[index++] = (dec.high.high_ >> 8) & 0xff; buffer[index++] = (dec.high.high_ >> 16) & 0xff; buffer[index++] = (dec.high.high_ >> 24) & 0xff; // Return the new Decimal128 return new Decimal128(buffer); }; // Extract least significant 5 bits var COMBINATION_MASK = 0x1f; // Extract least significant 14 bits var EXPONENT_MASK = 0x3fff; // Value of combination field for Inf var COMBINATION_INFINITY = 30; // Value of combination field for NaN var COMBINATION_NAN = 31; // Value of combination field for NaN // var COMBINATION_SNAN = 32; // decimal128 exponent bias EXPONENT_BIAS = 6176; /** * Create a string representation of the raw Decimal128 value * * @method * @return {string} returns a Decimal128 string representation. */ Decimal128.prototype.toString = function() { // Note: bits in this routine are referred to starting at 0, // from the sign bit, towards the coefficient. // bits 0 - 31 var high; // bits 32 - 63 var midh; // bits 64 - 95 var midl; // bits 96 - 127 var low; // bits 1 - 5 var combination; // decoded biased exponent (14 bits) var biased_exponent; // the number of significand digits var significand_digits = 0; // the base-10 digits in the significand var significand = new Array(36); for (var i = 0; i < significand.length; i++) significand[i] = 0; // read pointer into significand var index = 0; // unbiased exponent var exponent; // the exponent if scientific notation is used var scientific_exponent; // true if the number is zero var is_zero = false; // the most signifcant significand bits (50-46) var significand_msb; // temporary storage for significand decoding var significand128 = { parts: new Array(4) }; // indexing variables i; var j, k; // Output string var string = []; // Unpack index index = 0; // Buffer reference var buffer = this.bytes; // Unpack the low 64bits into a long low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); // Unpack the high 64bits into a long midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); // Unpack index index = 0; // Create the state of the decimal var dec = { low: new Long(low, midl), high: new Long(midh, high) }; if (dec.high.lessThan(Long.ZERO)) { string.push('-'); } // Decode combination field and exponent combination = (high >> 26) & COMBINATION_MASK; if (combination >> 3 === 3) { // Check for 'special' values if (combination === COMBINATION_INFINITY) { return string.join('') + 'Infinity'; } else if (combination === COMBINATION_NAN) { return 'NaN'; } else { biased_exponent = (high >> 15) & EXPONENT_MASK; significand_msb = 0x08 + ((high >> 14) & 0x01); } } else { significand_msb = (high >> 14) & 0x07; biased_exponent = (high >> 17) & EXPONENT_MASK; } exponent = biased_exponent - EXPONENT_BIAS; // Create string of significand digits // Convert the 114-bit binary number represented by // (significand_high, significand_low) to at most 34 decimal // digits through modulo and division. significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); significand128.parts[1] = midh; significand128.parts[2] = midl; significand128.parts[3] = low; if ( significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0 ) { is_zero = true; } else { for (k = 3; k >= 0; k--) { var least_digits = 0; // Peform the divide var result = divideu128(significand128); significand128 = result.quotient; least_digits = result.rem.low_; // We now have the 9 least significant digits (in base 2). // Convert and output to string. if (!least_digits) continue; for (j = 8; j >= 0; j--) { // significand[k * 9 + j] = Math.round(least_digits % 10); significand[k * 9 + j] = least_digits % 10; // least_digits = Math.round(least_digits / 10); least_digits = Math.floor(least_digits / 10); } } } // Output format options: // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd // Regular - ddd.ddd if (is_zero) { significand_digits = 1; significand[index] = 0; } else { significand_digits = 36; i = 0; while (!significand[index]) { i++; significand_digits = significand_digits - 1; index = index + 1; } } scientific_exponent = significand_digits - 1 + exponent; // The scientific exponent checks are dictated by the string conversion // specification and are somewhat arbitrary cutoffs. // // We must check exponent > 0, because if this is the case, the number // has trailing zeros. However, we *cannot* output these trailing zeros, // because doing so would change the precision of the value, and would // change stored data if the string converted number is round tripped. if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { // Scientific format string.push(significand[index++]); significand_digits = significand_digits - 1; if (significand_digits) { string.push('.'); } for (i = 0; i < significand_digits; i++) { string.push(significand[index++]); } // Exponent string.push('E'); if (scientific_exponent > 0) { string.push('+' + scientific_exponent); } else { string.push(scientific_exponent); } } else { // Regular format with no decimal place if (exponent >= 0) { for (i = 0; i < significand_digits; i++) { string.push(significand[index++]); } } else { var radix_position = significand_digits + exponent; // non-zero digits before radix if (radix_position > 0) { for (i = 0; i < radix_position; i++) { string.push(significand[index++]); } } else { string.push('0'); } string.push('.'); // add leading zeros after radix while (radix_position++ < 0) { string.push('0'); } for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { string.push(significand[index++]); } } } return string.join(''); }; Decimal128.prototype.toJSON = function() { return { $numberDecimal: this.toString() }; }; module.exports = Decimal128; module.exports.Decimal128 = Decimal128; },{"./long":117,"./parser/utils":125}],114:[function(require,module,exports){ /** * A class representation of the BSON Double type. * * @class * @param {number} value the number we want to represent as a double. * @return {Double} */ function Double(value) { if (!(this instanceof Double)) return new Double(value); this._bsontype = 'Double'; this.value = value; } /** * Access the number value. * * @method * @return {number} returns the wrapped double number. */ Double.prototype.valueOf = function() { return this.value; }; /** * @ignore */ Double.prototype.toJSON = function() { return this.value; }; module.exports = Double; module.exports.Double = Double; },{}],115:[function(require,module,exports){ // Copyright (c) 2008, Fair Oaks Labs, Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // // Modifications to writeIEEE754 to support negative zeroes made by Brian White var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { var e, m, bBE = endian === 'big', eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i = bBE ? 0 : nBytes - 1, d = bBE ? 1 : -1, s = buffer[offset + i]; i += d; e = s & ((1 << -nBits) - 1); s >>= -nBits; nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); m = e & ((1 << -nBits) - 1); e >>= -nBits; nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : (s ? -1 : 1) * Infinity; } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { var e, m, c, bBE = endian === 'big', eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, i = bBE ? nBytes - 1 : 0, d = bBE ? -1 : 1, s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); e = (e << mLen) | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); buffer[offset + i - d] |= s * 128; }; exports.readIEEE754 = readIEEE754; exports.writeIEEE754 = writeIEEE754; },{}],116:[function(require,module,exports){ /** * A class representation of a BSON Int32 type. * * @class * @param {number} value the number we want to represent as an int32. * @return {Int32} */ var Int32 = function(value) { if (!(this instanceof Int32)) return new Int32(value); this._bsontype = 'Int32'; this.value = value; }; /** * Access the number value. * * @method * @return {number} returns the wrapped int32 number. */ Int32.prototype.valueOf = function() { return this.value; }; /** * @ignore */ Int32.prototype.toJSON = function() { return this.value; }; module.exports = Int32; module.exports.Int32 = Int32; },{}],117:[function(require,module,exports){ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Copyright 2009 Google Inc. All Rights Reserved /** * Defines a Long class for representing a 64-bit two's-complement * integer value, which faithfully simulates the behavior of a Java "Long". This * implementation is derived from LongLib in GWT. * * Constructs a 64-bit two's-complement integer, given its low and high 32-bit * values as *signed* integers. See the from* functions below for more * convenient ways of constructing Longs. * * The internal representation of a Long is the two given signed, 32-bit values. * We use 32-bit pieces because these are the size of integers on which * Javascript performs bit-operations. For operations like addition and * multiplication, we split each number into 16-bit pieces, which can easily be * multiplied within Javascript's floating-point representation without overflow * or change in sign. * * In the algorithms below, we frequently reduce the negative case to the * positive case by negating the input(s) and then post-processing the result. * Note that we must ALWAYS check specially whether those values are MIN_VALUE * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as * a positive number, it overflows back into a negative). Not handling this * case would often result in infinite recursion. * * @class * @param {number} low the low (signed) 32 bits of the Long. * @param {number} high the high (signed) 32 bits of the Long. * @return {Long} */ function Long(low, high) { if (!(this instanceof Long)) return new Long(low, high); this._bsontype = 'Long'; /** * @type {number} * @ignore */ this.low_ = low | 0; // force into 32 signed bits. /** * @type {number} * @ignore */ this.high_ = high | 0; // force into 32 signed bits. } /** * Return the int value. * * @method * @return {number} the value, assuming it is a 32-bit integer. */ Long.prototype.toInt = function() { return this.low_; }; /** * Return the Number value. * * @method * @return {number} the closest floating-point representation to this value. */ Long.prototype.toNumber = function() { return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); }; /** * Return the JSON value. * * @method * @return {string} the JSON representation. */ Long.prototype.toJSON = function() { return this.toString(); }; /** * Return the String value. * * @method * @param {number} [opt_radix] the radix in which the text should be written. * @return {string} the textual representation of this value. */ Long.prototype.toString = function(opt_radix) { var radix = opt_radix || 10; if (radix < 2 || 36 < radix) { throw Error('radix out of range: ' + radix); } if (this.isZero()) { return '0'; } if (this.isNegative()) { if (this.equals(Long.MIN_VALUE)) { // We need to change the Long value before it can be negated, so we remove // the bottom-most digit in this base and then recurse to do the rest. var radixLong = Long.fromNumber(radix); var div = this.div(radixLong); var rem = div.multiply(radixLong).subtract(this); return div.toString(radix) + rem.toInt().toString(radix); } else { return '-' + this.negate().toString(radix); } } // Do several (6) digits each time through the loop, so as to // minimize the calls to the very expensive emulated div. var radixToPower = Long.fromNumber(Math.pow(radix, 6)); rem = this; var result = ''; while (!rem.isZero()) { var remDiv = rem.div(radixToPower); var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); var digits = intval.toString(radix); rem = remDiv; if (rem.isZero()) { return digits + result; } else { while (digits.length < 6) { digits = '0' + digits; } result = '' + digits + result; } } }; /** * Return the high 32-bits value. * * @method * @return {number} the high 32-bits as a signed value. */ Long.prototype.getHighBits = function() { return this.high_; }; /** * Return the low 32-bits value. * * @method * @return {number} the low 32-bits as a signed value. */ Long.prototype.getLowBits = function() { return this.low_; }; /** * Return the low unsigned 32-bits value. * * @method * @return {number} the low 32-bits as an unsigned value. */ Long.prototype.getLowBitsUnsigned = function() { return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; }; /** * Returns the number of bits needed to represent the absolute value of this Long. * * @method * @return {number} Returns the number of bits needed to represent the absolute value of this Long. */ Long.prototype.getNumBitsAbs = function() { if (this.isNegative()) { if (this.equals(Long.MIN_VALUE)) { return 64; } else { return this.negate().getNumBitsAbs(); } } else { var val = this.high_ !== 0 ? this.high_ : this.low_; for (var bit = 31; bit > 0; bit--) { if ((val & (1 << bit)) !== 0) { break; } } return this.high_ !== 0 ? bit + 33 : bit + 1; } }; /** * Return whether this value is zero. * * @method * @return {boolean} whether this value is zero. */ Long.prototype.isZero = function() { return this.high_ === 0 && this.low_ === 0; }; /** * Return whether this value is negative. * * @method * @return {boolean} whether this value is negative. */ Long.prototype.isNegative = function() { return this.high_ < 0; }; /** * Return whether this value is odd. * * @method * @return {boolean} whether this value is odd. */ Long.prototype.isOdd = function() { return (this.low_ & 1) === 1; }; /** * Return whether this Long equals the other * * @method * @param {Long} other Long to compare against. * @return {boolean} whether this Long equals the other */ Long.prototype.equals = function(other) { return this.high_ === other.high_ && this.low_ === other.low_; }; /** * Return whether this Long does not equal the other. * * @method * @param {Long} other Long to compare against. * @return {boolean} whether this Long does not equal the other. */ Long.prototype.notEquals = function(other) { return this.high_ !== other.high_ || this.low_ !== other.low_; }; /** * Return whether this Long is less than the other. * * @method * @param {Long} other Long to compare against. * @return {boolean} whether this Long is less than the other. */ Long.prototype.lessThan = function(other) { return this.compare(other) < 0; }; /** * Return whether this Long is less than or equal to the other. * * @method * @param {Long} other Long to compare against. * @return {boolean} whether this Long is less than or equal to the other. */ Long.prototype.lessThanOrEqual = function(other) { return this.compare(other) <= 0; }; /** * Return whether this Long is greater than the other. * * @method * @param {Long} other Long to compare against. * @return {boolean} whether this Long is greater than the other. */ Long.prototype.greaterThan = function(other) { return this.compare(other) > 0; }; /** * Return whether this Long is greater than or equal to the other. * * @method * @param {Long} other Long to compare against. * @return {boolean} whether this Long is greater than or equal to the other. */ Long.prototype.greaterThanOrEqual = function(other) { return this.compare(other) >= 0; }; /** * Compares this Long with the given one. * * @method * @param {Long} other Long to compare against. * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. */ Long.prototype.compare = function(other) { if (this.equals(other)) { return 0; } var thisNeg = this.isNegative(); var otherNeg = other.isNegative(); if (thisNeg && !otherNeg) { return -1; } if (!thisNeg && otherNeg) { return 1; } // at this point, the signs are the same, so subtraction will not overflow if (this.subtract(other).isNegative()) { return -1; } else { return 1; } }; /** * The negation of this value. * * @method * @return {Long} the negation of this value. */ Long.prototype.negate = function() { if (this.equals(Long.MIN_VALUE)) { return Long.MIN_VALUE; } else { return this.not().add(Long.ONE); } }; /** * Returns the sum of this and the given Long. * * @method * @param {Long} other Long to add to this one. * @return {Long} the sum of this and the given Long. */ Long.prototype.add = function(other) { // Divide each number into 4 chunks of 16 bits, and then sum the chunks. var a48 = this.high_ >>> 16; var a32 = this.high_ & 0xffff; var a16 = this.low_ >>> 16; var a00 = this.low_ & 0xffff; var b48 = other.high_ >>> 16; var b32 = other.high_ & 0xffff; var b16 = other.low_ >>> 16; var b00 = other.low_ & 0xffff; var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 + b00; c16 += c00 >>> 16; c00 &= 0xffff; c16 += a16 + b16; c32 += c16 >>> 16; c16 &= 0xffff; c32 += a32 + b32; c48 += c32 >>> 16; c32 &= 0xffff; c48 += a48 + b48; c48 &= 0xffff; return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); }; /** * Returns the difference of this and the given Long. * * @method * @param {Long} other Long to subtract from this. * @return {Long} the difference of this and the given Long. */ Long.prototype.subtract = function(other) { return this.add(other.negate()); }; /** * Returns the product of this and the given Long. * * @method * @param {Long} other Long to multiply with this. * @return {Long} the product of this and the other. */ Long.prototype.multiply = function(other) { if (this.isZero()) { return Long.ZERO; } else if (other.isZero()) { return Long.ZERO; } if (this.equals(Long.MIN_VALUE)) { return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; } else if (other.equals(Long.MIN_VALUE)) { return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; } if (this.isNegative()) { if (other.isNegative()) { return this.negate().multiply(other.negate()); } else { return this.negate() .multiply(other) .negate(); } } else if (other.isNegative()) { return this.multiply(other.negate()).negate(); } // If both Longs are small, use float multiplication if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { return Long.fromNumber(this.toNumber() * other.toNumber()); } // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. // We can skip products that would overflow. var a48 = this.high_ >>> 16; var a32 = this.high_ & 0xffff; var a16 = this.low_ >>> 16; var a00 = this.low_ & 0xffff; var b48 = other.high_ >>> 16; var b32 = other.high_ & 0xffff; var b16 = other.low_ >>> 16; var b00 = other.low_ & 0xffff; var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 * b00; c16 += c00 >>> 16; c00 &= 0xffff; c16 += a16 * b00; c32 += c16 >>> 16; c16 &= 0xffff; c16 += a00 * b16; c32 += c16 >>> 16; c16 &= 0xffff; c32 += a32 * b00; c48 += c32 >>> 16; c32 &= 0xffff; c32 += a16 * b16; c48 += c32 >>> 16; c32 &= 0xffff; c32 += a00 * b32; c48 += c32 >>> 16; c32 &= 0xffff; c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; c48 &= 0xffff; return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); }; /** * Returns this Long divided by the given one. * * @method * @param {Long} other Long by which to divide. * @return {Long} this Long divided by the given one. */ Long.prototype.div = function(other) { if (other.isZero()) { throw Error('division by zero'); } else if (this.isZero()) { return Long.ZERO; } if (this.equals(Long.MIN_VALUE)) { if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE } else if (other.equals(Long.MIN_VALUE)) { return Long.ONE; } else { // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. var halfThis = this.shiftRight(1); var approx = halfThis.div(other).shiftLeft(1); if (approx.equals(Long.ZERO)) { return other.isNegative() ? Long.ONE : Long.NEG_ONE; } else { var rem = this.subtract(other.multiply(approx)); var result = approx.add(rem.div(other)); return result; } } } else if (other.equals(Long.MIN_VALUE)) { return Long.ZERO; } if (this.isNegative()) { if (other.isNegative()) { return this.negate().div(other.negate()); } else { return this.negate() .div(other) .negate(); } } else if (other.isNegative()) { return this.div(other.negate()).negate(); } // Repeat the following until the remainder is less than other: find a // floating-point that approximates remainder / other *from below*, add this // into the result, and subtract it from the remainder. It is critical that // the approximate value is less than or equal to the real value so that the // remainder never becomes negative. var res = Long.ZERO; rem = this; while (rem.greaterThanOrEqual(other)) { // Approximate the result of division. This may be a little greater or // smaller than the actual value. approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); // We will tweak the approximate result by changing it in the 48-th digit or // the smallest non-fractional digit, whichever is larger. var log2 = Math.ceil(Math.log(approx) / Math.LN2); var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); // Decrease the approximation until it is smaller than the remainder. Note // that if it is too large, the product overflows and is negative. var approxRes = Long.fromNumber(approx); var approxRem = approxRes.multiply(other); while (approxRem.isNegative() || approxRem.greaterThan(rem)) { approx -= delta; approxRes = Long.fromNumber(approx); approxRem = approxRes.multiply(other); } // We know the answer can't be zero... and actually, zero would cause // infinite recursion since we would make no progress. if (approxRes.isZero()) { approxRes = Long.ONE; } res = res.add(approxRes); rem = rem.subtract(approxRem); } return res; }; /** * Returns this Long modulo the given one. * * @method * @param {Long} other Long by which to mod. * @return {Long} this Long modulo the given one. */ Long.prototype.modulo = function(other) { return this.subtract(this.div(other).multiply(other)); }; /** * The bitwise-NOT of this value. * * @method * @return {Long} the bitwise-NOT of this value. */ Long.prototype.not = function() { return Long.fromBits(~this.low_, ~this.high_); }; /** * Returns the bitwise-AND of this Long and the given one. * * @method * @param {Long} other the Long with which to AND. * @return {Long} the bitwise-AND of this and the other. */ Long.prototype.and = function(other) { return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); }; /** * Returns the bitwise-OR of this Long and the given one. * * @method * @param {Long} other the Long with which to OR. * @return {Long} the bitwise-OR of this and the other. */ Long.prototype.or = function(other) { return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); }; /** * Returns the bitwise-XOR of this Long and the given one. * * @method * @param {Long} other the Long with which to XOR. * @return {Long} the bitwise-XOR of this and the other. */ Long.prototype.xor = function(other) { return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); }; /** * Returns this Long with bits shifted to the left by the given amount. * * @method * @param {number} numBits the number of bits by which to shift. * @return {Long} this shifted to the left by the given amount. */ Long.prototype.shiftLeft = function(numBits) { numBits &= 63; if (numBits === 0) { return this; } else { var low = this.low_; if (numBits < 32) { var high = this.high_; return Long.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); } else { return Long.fromBits(0, low << (numBits - 32)); } } }; /** * Returns this Long with bits shifted to the right by the given amount. * * @method * @param {number} numBits the number of bits by which to shift. * @return {Long} this shifted to the right by the given amount. */ Long.prototype.shiftRight = function(numBits) { numBits &= 63; if (numBits === 0) { return this; } else { var high = this.high_; if (numBits < 32) { var low = this.low_; return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); } else { return Long.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); } } }; /** * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. * * @method * @param {number} numBits the number of bits by which to shift. * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. */ Long.prototype.shiftRightUnsigned = function(numBits) { numBits &= 63; if (numBits === 0) { return this; } else { var high = this.high_; if (numBits < 32) { var low = this.low_; return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); } else if (numBits === 32) { return Long.fromBits(high, 0); } else { return Long.fromBits(high >>> (numBits - 32), 0); } } }; /** * Returns a Long representing the given (32-bit) integer value. * * @method * @param {number} value the 32-bit integer in question. * @return {Long} the corresponding Long value. */ Long.fromInt = function(value) { if (-128 <= value && value < 128) { var cachedObj = Long.INT_CACHE_[value]; if (cachedObj) { return cachedObj; } } var obj = new Long(value | 0, value < 0 ? -1 : 0); if (-128 <= value && value < 128) { Long.INT_CACHE_[value] = obj; } return obj; }; /** * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. * * @method * @param {number} value the number in question. * @return {Long} the corresponding Long value. */ Long.fromNumber = function(value) { if (isNaN(value) || !isFinite(value)) { return Long.ZERO; } else if (value <= -Long.TWO_PWR_63_DBL_) { return Long.MIN_VALUE; } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { return Long.MAX_VALUE; } else if (value < 0) { return Long.fromNumber(-value).negate(); } else { return new Long((value % Long.TWO_PWR_32_DBL_) | 0, (value / Long.TWO_PWR_32_DBL_) | 0); } }; /** * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. * * @method * @param {number} lowBits the low 32-bits. * @param {number} highBits the high 32-bits. * @return {Long} the corresponding Long value. */ Long.fromBits = function(lowBits, highBits) { return new Long(lowBits, highBits); }; /** * Returns a Long representation of the given string, written using the given radix. * * @method * @param {string} str the textual representation of the Long. * @param {number} opt_radix the radix in which the text is written. * @return {Long} the corresponding Long value. */ Long.fromString = function(str, opt_radix) { if (str.length === 0) { throw Error('number format error: empty string'); } var radix = opt_radix || 10; if (radix < 2 || 36 < radix) { throw Error('radix out of range: ' + radix); } if (str.charAt(0) === '-') { return Long.fromString(str.substring(1), radix).negate(); } else if (str.indexOf('-') >= 0) { throw Error('number format error: interior "-" character: ' + str); } // Do several (8) digits each time through the loop, so as to // minimize the calls to the very expensive emulated div. var radixToPower = Long.fromNumber(Math.pow(radix, 8)); var result = Long.ZERO; for (var i = 0; i < str.length; i += 8) { var size = Math.min(8, str.length - i); var value = parseInt(str.substring(i, i + size), radix); if (size < 8) { var power = Long.fromNumber(Math.pow(radix, size)); result = result.multiply(power).add(Long.fromNumber(value)); } else { result = result.multiply(radixToPower); result = result.add(Long.fromNumber(value)); } } return result; }; // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the // from* methods on which they depend. /** * A cache of the Long representations of small integer values. * @type {Object} * @ignore */ Long.INT_CACHE_ = {}; // NOTE: the compiler should inline these constant values below and then remove // these variables, so there should be no runtime penalty for these. /** * Number used repeated below in calculations. This must appear before the * first call to any from* function below. * @type {number} * @ignore */ Long.TWO_PWR_16_DBL_ = 1 << 16; /** * @type {number} * @ignore */ Long.TWO_PWR_24_DBL_ = 1 << 24; /** * @type {number} * @ignore */ Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; /** * @type {number} * @ignore */ Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; /** * @type {number} * @ignore */ Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; /** * @type {number} * @ignore */ Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; /** * @type {number} * @ignore */ Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; /** @type {Long} */ Long.ZERO = Long.fromInt(0); /** @type {Long} */ Long.ONE = Long.fromInt(1); /** @type {Long} */ Long.NEG_ONE = Long.fromInt(-1); /** @type {Long} */ Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); /** @type {Long} */ Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); /** * @type {Long} * @ignore */ Long.TWO_PWR_24_ = Long.fromInt(1 << 24); /** * Expose. */ module.exports = Long; module.exports.Long = Long; },{}],118:[function(require,module,exports){ (function (global){(function (){ 'use strict'; // We have an ES6 Map available, return the native instance if (typeof global.Map !== 'undefined') { module.exports = global.Map; module.exports.Map = global.Map; } else { // We will return a polyfill var Map = function(array) { this._keys = []; this._values = {}; for (var i = 0; i < array.length; i++) { if (array[i] == null) continue; // skip null and undefined var entry = array[i]; var key = entry[0]; var value = entry[1]; // Add the key to the list of keys in order this._keys.push(key); // Add the key and value to the values dictionary with a point // to the location in the ordered keys list this._values[key] = { v: value, i: this._keys.length - 1 }; } }; Map.prototype.clear = function() { this._keys = []; this._values = {}; }; Map.prototype.delete = function(key) { var value = this._values[key]; if (value == null) return false; // Delete entry delete this._values[key]; // Remove the key from the ordered keys list this._keys.splice(value.i, 1); return true; }; Map.prototype.entries = function() { var self = this; var index = 0; return { next: function() { var key = self._keys[index++]; return { value: key !== undefined ? [key, self._values[key].v] : undefined, done: key !== undefined ? false : true }; } }; }; Map.prototype.forEach = function(callback, self) { self = self || this; for (var i = 0; i < this._keys.length; i++) { var key = this._keys[i]; // Call the forEach callback callback.call(self, this._values[key].v, key, self); } }; Map.prototype.get = function(key) { return this._values[key] ? this._values[key].v : undefined; }; Map.prototype.has = function(key) { return this._values[key] != null; }; Map.prototype.keys = function() { var self = this; var index = 0; return { next: function() { var key = self._keys[index++]; return { value: key !== undefined ? key : undefined, done: key !== undefined ? false : true }; } }; }; Map.prototype.set = function(key, value) { if (this._values[key]) { this._values[key].v = value; return this; } // Add the key to the list of keys in order this._keys.push(key); // Add the key and value to the values dictionary with a point // to the location in the ordered keys list this._values[key] = { v: value, i: this._keys.length - 1 }; return this; }; Map.prototype.values = function() { var self = this; var index = 0; return { next: function() { var key = self._keys[index++]; return { value: key !== undefined ? self._values[key].v : undefined, done: key !== undefined ? false : true }; } }; }; // Last ismaster Object.defineProperty(Map.prototype, 'size', { enumerable: true, get: function() { return this._keys.length; } }); module.exports = Map; module.exports.Map = Map; } }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],119:[function(require,module,exports){ /** * A class representation of the BSON MaxKey type. * * @class * @return {MaxKey} A MaxKey instance */ function MaxKey() { if (!(this instanceof MaxKey)) return new MaxKey(); this._bsontype = 'MaxKey'; } module.exports = MaxKey; module.exports.MaxKey = MaxKey; },{}],120:[function(require,module,exports){ /** * A class representation of the BSON MinKey type. * * @class * @return {MinKey} A MinKey instance */ function MinKey() { if (!(this instanceof MinKey)) return new MinKey(); this._bsontype = 'MinKey'; } module.exports = MinKey; module.exports.MinKey = MinKey; },{}],121:[function(require,module,exports){ (function (process,Buffer){(function (){ // Custom inspect property name / symbol. var inspect = 'inspect'; var utils = require('./parser/utils'); /** * Machine id. * * Create a random 3-byte value (i.e. unique for this * process). Other drivers use a md5 of the machine id here, but * that would mean an asyc call to gethostname, so we don't bother. * @ignore */ var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); // Regular expression that checks for hex value var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); // Check if buffer exists try { if (Buffer && Buffer.from) { var hasBufferType = true; inspect = require('util').inspect.custom || 'inspect'; } } catch (err) { hasBufferType = false; } /** * Create a new ObjectID instance * * @class * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. * @property {number} generationTime The generation time of this ObjectId instance * @return {ObjectID} instance of ObjectID. */ var ObjectID = function ObjectID(id) { // Duck-typing to support ObjectId from different npm packages if (id instanceof ObjectID) return id; if (!(this instanceof ObjectID)) return new ObjectID(id); this._bsontype = 'ObjectID'; // The most common usecase (blank id, new objectId instance) if (id == null || typeof id === 'number') { // Generate a new id this.id = this.generate(id); // If we are caching the hex string if (ObjectID.cacheHexString) this.__id = this.toString('hex'); // Return the object return; } // Check if the passed in id is valid var valid = ObjectID.isValid(id); // Throw an error if it's not a valid setup if (!valid && id != null) { throw new Error( 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' ); } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { return new ObjectID(utils.toBuffer(id, 'hex')); } else if (valid && typeof id === 'string' && id.length === 24) { return ObjectID.createFromHexString(id); } else if (id != null && id.length === 12) { // assume 12 byte string this.id = id; } else if (id != null && typeof id.toHexString === 'function') { // Duck-typing to support ObjectId from different npm packages return id; } else { throw new Error( 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' ); } if (ObjectID.cacheHexString) this.__id = this.toString('hex'); }; // Allow usage of ObjectId as well as ObjectID // var ObjectId = ObjectID; // Precomputed hex table enables speedy hex string conversion var hexTable = []; for (var i = 0; i < 256; i++) { hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); } /** * Return the ObjectID id as a 24 byte hex string representation * * @method * @return {string} return the 24 byte hex string representation. */ ObjectID.prototype.toHexString = function() { if (ObjectID.cacheHexString && this.__id) return this.__id; var hexString = ''; if (!this.id || !this.id.length) { throw new Error( 'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']' ); } if (this.id instanceof _Buffer) { hexString = convertToHex(this.id); if (ObjectID.cacheHexString) this.__id = hexString; return hexString; } for (var i = 0; i < this.id.length; i++) { hexString += hexTable[this.id.charCodeAt(i)]; } if (ObjectID.cacheHexString) this.__id = hexString; return hexString; }; /** * Update the ObjectID index used in generating new ObjectID's on the driver * * @method * @return {number} returns next index value. * @ignore */ ObjectID.prototype.get_inc = function() { return (ObjectID.index = (ObjectID.index + 1) % 0xffffff); }; /** * Update the ObjectID index used in generating new ObjectID's on the driver * * @method * @return {number} returns next index value. * @ignore */ ObjectID.prototype.getInc = function() { return this.get_inc(); }; /** * Generate a 12 byte id buffer used in ObjectID's * * @method * @param {number} [time] optional parameter allowing to pass in a second based timestamp. * @return {Buffer} return the 12 byte id buffer string. */ ObjectID.prototype.generate = function(time) { if ('number' !== typeof time) { time = ~~(Date.now() / 1000); } // Use pid var pid = (typeof process === 'undefined' || process.pid === 1 ? Math.floor(Math.random() * 100000) : process.pid) % 0xffff; var inc = this.get_inc(); // Buffer used var buffer = utils.allocBuffer(12); // Encode time buffer[3] = time & 0xff; buffer[2] = (time >> 8) & 0xff; buffer[1] = (time >> 16) & 0xff; buffer[0] = (time >> 24) & 0xff; // Encode machine buffer[6] = MACHINE_ID & 0xff; buffer[5] = (MACHINE_ID >> 8) & 0xff; buffer[4] = (MACHINE_ID >> 16) & 0xff; // Encode pid buffer[8] = pid & 0xff; buffer[7] = (pid >> 8) & 0xff; // Encode index buffer[11] = inc & 0xff; buffer[10] = (inc >> 8) & 0xff; buffer[9] = (inc >> 16) & 0xff; // Return the buffer return buffer; }; /** * Converts the id into a 24 byte hex string for printing * * @param {String} format The Buffer toString format parameter. * @return {String} return the 24 byte hex string representation. * @ignore */ ObjectID.prototype.toString = function(format) { // Is the id a buffer then use the buffer toString method to return the format if (this.id && this.id.copy) { return this.id.toString(typeof format === 'string' ? format : 'hex'); } // if(this.buffer ) return this.toHexString(); }; /** * Converts to a string representation of this Id. * * @return {String} return the 24 byte hex string representation. * @ignore */ ObjectID.prototype[inspect] = ObjectID.prototype.toString; /** * Converts to its JSON representation. * * @return {String} return the 24 byte hex string representation. * @ignore */ ObjectID.prototype.toJSON = function() { return this.toHexString(); }; /** * Compares the equality of this ObjectID with `otherID`. * * @method * @param {object} otherID ObjectID instance to compare against. * @return {boolean} the result of comparing two ObjectID's */ ObjectID.prototype.equals = function equals(otherId) { // var id; if (otherId instanceof ObjectID) { return this.toString() === otherId.toString(); } else if ( typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12 && this.id instanceof _Buffer ) { return otherId === this.id.toString('binary'); } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { return otherId.toLowerCase() === this.toHexString(); } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { return otherId === this.id; } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { return otherId.toHexString() === this.toHexString(); } else { return false; } }; /** * Returns the generation date (accurate up to the second) that this ID was generated. * * @method * @return {date} the generation date */ ObjectID.prototype.getTimestamp = function() { var timestamp = new Date(); var time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); timestamp.setTime(Math.floor(time) * 1000); return timestamp; }; /** * @ignore */ ObjectID.index = ~~(Math.random() * 0xffffff); /** * @ignore */ ObjectID.createPk = function createPk() { return new ObjectID(); }; /** * Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. * * @method * @param {number} time an integer number representing a number of seconds. * @return {ObjectID} return the created ObjectID */ ObjectID.createFromTime = function createFromTime(time) { var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); // Encode time into first 4 bytes buffer[3] = time & 0xff; buffer[2] = (time >> 8) & 0xff; buffer[1] = (time >> 16) & 0xff; buffer[0] = (time >> 24) & 0xff; // Return the new objectId return new ObjectID(buffer); }; // Lookup tables //var encodeLookup = '0123456789abcdef'.split(''); var decodeLookup = []; i = 0; while (i < 10) decodeLookup[0x30 + i] = i++; while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; var _Buffer = Buffer; var convertToHex = function(bytes) { return bytes.toString('hex'); }; /** * Creates an ObjectID from a hex string representation of an ObjectID. * * @method * @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. * @return {ObjectID} return the created ObjectID */ ObjectID.createFromHexString = function createFromHexString(string) { // Throw an error if it's not a valid setup if (typeof string === 'undefined' || (string != null && string.length !== 24)) { throw new Error( 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' ); } // Use Buffer.from method if available if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex')); // Calculate lengths var array = new _Buffer(12); var n = 0; var i = 0; while (i < 24) { array[n++] = (decodeLookup[string.charCodeAt(i++)] << 4) | decodeLookup[string.charCodeAt(i++)]; } return new ObjectID(array); }; /** * Checks if a value is a valid bson ObjectId * * @method * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. */ ObjectID.isValid = function isValid(id) { if (id == null) return false; if (typeof id === 'number') { return true; } if (typeof id === 'string') { return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); } if (id instanceof ObjectID) { return true; } if (id instanceof _Buffer) { return true; } // Duck-Typing detection of ObjectId like objects if ( typeof id.toHexString === 'function' && (id.id instanceof _Buffer || typeof id.id === 'string') ) { return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id)); } return false; }; /** * @ignore */ Object.defineProperty(ObjectID.prototype, 'generationTime', { enumerable: true, get: function() { return this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); }, set: function(value) { // Encode time into first 4 bytes this.id[3] = value & 0xff; this.id[2] = (value >> 8) & 0xff; this.id[1] = (value >> 16) & 0xff; this.id[0] = (value >> 24) & 0xff; } }); /** * Expose. */ module.exports = ObjectID; module.exports.ObjectID = ObjectID; module.exports.ObjectId = ObjectID; }).call(this)}).call(this,require('_process'),require("buffer").Buffer) },{"./parser/utils":125,"_process":325,"buffer":129,"util":332}],122:[function(require,module,exports){ (function (Buffer){(function (){ 'use strict'; var Long = require('../long').Long, Double = require('../double').Double, Timestamp = require('../timestamp').Timestamp, ObjectID = require('../objectid').ObjectID, Symbol = require('../symbol').Symbol, BSONRegExp = require('../regexp').BSONRegExp, Code = require('../code').Code, Decimal128 = require('../decimal128'), MinKey = require('../min_key').MinKey, MaxKey = require('../max_key').MaxKey, DBRef = require('../db_ref').DBRef, Binary = require('../binary').Binary; var normalizedFunctionString = require('./utils').normalizedFunctionString; // To ensure that 0.4 of node works correctly var isDate = function isDate(d) { return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; }; var calculateObjectSize = function calculateObjectSize( object, serializeFunctions, ignoreUndefined ) { var totalLength = 4 + 1; if (Array.isArray(object)) { for (var i = 0; i < object.length; i++) { totalLength += calculateElement( i.toString(), object[i], serializeFunctions, true, ignoreUndefined ); } } else { // If we have toBSON defined, override the current object if (object.toBSON) { object = object.toBSON(); } // Calculate size for (var key in object) { totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); } } return totalLength; }; /** * @ignore * @api private */ function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { // If we have toBSON defined, override the current object if (value && value.toBSON) { value = value.toBSON(); } switch (typeof value) { case 'string': return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; case 'number': if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); } else { return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); } } else { // 64 bit return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); } case 'undefined': if (isArray || !ignoreUndefined) return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; return 0; case 'boolean': return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); case 'object': if ( value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey' ) { return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); } else if (value instanceof Date || isDate(value)) { return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length ); } else if ( value instanceof Long || value instanceof Double || value instanceof Timestamp || value['_bsontype'] === 'Long' || value['_bsontype'] === 'Double' || value['_bsontype'] === 'Timestamp' ) { return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); } else if (value instanceof Code || value['_bsontype'] === 'Code') { // Calculate size depending on the availability of a scope if (value.scope != null && Object.keys(value.scope).length > 0) { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) ); } else { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 ); } } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { // Check what kind of subtype we have if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1 + 4) ); } else { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1) ); } } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1 ); } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { // Set up correct object for serialization var ordered_values = { $ref: value.namespace, $id: value.oid }; // Add db reference if it exists if (null != value.db) { ordered_values['$db'] = value.db; } return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) ); } else if ( value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' ) { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 ); } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + Buffer.byteLength(value.options, 'utf8') + 1 ); } else { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1 ); } case 'function': // WTF for 0.4.X where typeof /someregexp/ === 'function' if ( value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) === '[object RegExp]' ) { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 ); } else { if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) ); } else if (serializeFunctions) { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1 ); } } } return 0; } var BSON = {}; // BSON MAX VALUES BSON.BSON_INT32_MAX = 0x7fffffff; BSON.BSON_INT32_MIN = -0x80000000; // JS MAX PRECISE VALUES BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. module.exports = calculateObjectSize; }).call(this)}).call(this,require("buffer").Buffer) },{"../binary":109,"../code":111,"../db_ref":112,"../decimal128":113,"../double":114,"../long":117,"../max_key":119,"../min_key":120,"../objectid":121,"../regexp":126,"../symbol":127,"../timestamp":128,"./utils":125,"buffer":129}],123:[function(require,module,exports){ 'use strict'; var Long = require('../long').Long, Double = require('../double').Double, Timestamp = require('../timestamp').Timestamp, ObjectID = require('../objectid').ObjectID, Symbol = require('../symbol').Symbol, Code = require('../code').Code, MinKey = require('../min_key').MinKey, MaxKey = require('../max_key').MaxKey, Decimal128 = require('../decimal128'), Int32 = require('../int_32'), DBRef = require('../db_ref').DBRef, BSONRegExp = require('../regexp').BSONRegExp, Binary = require('../binary').Binary; var utils = require('./utils'); var deserialize = function(buffer, options, isArray) { options = options == null ? {} : options; var index = options && options.index ? options.index : 0; // Read the document size var size = buffer[index] | (buffer[index + 1] << 8) | (buffer[index + 2] << 16) | (buffer[index + 3] << 24); // Ensure buffer is valid size if (size < 5 || buffer.length < size || size + index > buffer.length) { throw new Error('corrupt bson message'); } // Illegal end value if (buffer[index + size - 1] !== 0) { throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); } // Start deserializtion return deserializeObject(buffer, index, options, isArray); }; var deserializeObject = function(buffer, index, options, isArray) { var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; if (!cacheFunctionsCrc32) var crc32 = null; var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; // Return raw bson buffer instead of parsing it var raw = options['raw'] == null ? false : options['raw']; // Return BSONRegExp objects instead of native regular expressions var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; // Controls the promotion of values vs wrapper classes var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; // Set the start index var startIndex = index; // Validate that we have at least 4 bytes of buffer if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); // Read the document size var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); // Ensure buffer is valid size if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); // Create holding object var object = isArray ? [] : {}; // Used for arrays to skip having to perform utf8 decoding var arrayIndex = 0; var done = false; // While we have more left data left keep parsing // while (buffer[index + 1] !== 0) { while (!done) { // Read the type var elementType = buffer[index++]; // If we get a zero it's the last byte, exit if (elementType === 0) break; // Get the start search index var i = index; // Locate the end of the c string while (buffer[i] !== 0x00 && i < buffer.length) { i++; } // If are at the end of the buffer there is a problem with the document if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); index = i + 1; if (elementType === BSON.BSON_DATA_STRING) { var stringSize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); if ( stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0 ) throw new Error('bad string length in bson'); object[name] = buffer.toString('utf8', index, index + stringSize - 1); index = index + stringSize; } else if (elementType === BSON.BSON_DATA_OID) { var oid = utils.allocBuffer(12); buffer.copy(oid, 0, index, index + 12); object[name] = new ObjectID(oid); index = index + 12; } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { object[name] = new Int32( buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24) ); } else if (elementType === BSON.BSON_DATA_INT) { object[name] = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { object[name] = new Double(buffer.readDoubleLE(index)); index = index + 8; } else if (elementType === BSON.BSON_DATA_NUMBER) { object[name] = buffer.readDoubleLE(index); index = index + 8; } else if (elementType === BSON.BSON_DATA_DATE) { var lowBits = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); var highBits = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); object[name] = new Date(new Long(lowBits, highBits).toNumber()); } else if (elementType === BSON.BSON_DATA_BOOLEAN) { if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); object[name] = buffer[index++] === 1; } else if (elementType === BSON.BSON_DATA_OBJECT) { var _index = index; var objectSize = buffer[index] | (buffer[index + 1] << 8) | (buffer[index + 2] << 16) | (buffer[index + 3] << 24); if (objectSize <= 0 || objectSize > buffer.length - index) throw new Error('bad embedded document length in bson'); // We have a raw value if (raw) { object[name] = buffer.slice(index, index + objectSize); } else { object[name] = deserializeObject(buffer, _index, options, false); } index = index + objectSize; } else if (elementType === BSON.BSON_DATA_ARRAY) { _index = index; objectSize = buffer[index] | (buffer[index + 1] << 8) | (buffer[index + 2] << 16) | (buffer[index + 3] << 24); var arrayOptions = options; // Stop index var stopIndex = index + objectSize; // All elements of array to be returned as raw bson if (fieldsAsRaw && fieldsAsRaw[name]) { arrayOptions = {}; for (var n in options) arrayOptions[n] = options[n]; arrayOptions['raw'] = true; } object[name] = deserializeObject(buffer, _index, arrayOptions, true); index = index + objectSize; if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); if (index !== stopIndex) throw new Error('corrupted array bson'); } else if (elementType === BSON.BSON_DATA_UNDEFINED) { object[name] = undefined; } else if (elementType === BSON.BSON_DATA_NULL) { object[name] = null; } else if (elementType === BSON.BSON_DATA_LONG) { // Unpack the low and high bits lowBits = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); highBits = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); var long = new Long(lowBits, highBits); // Promote the long if possible if (promoteLongs && promoteValues === true) { object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; } else { object[name] = long; } } else if (elementType === BSON.BSON_DATA_DECIMAL128) { // Buffer to contain the decimal bytes var bytes = utils.allocBuffer(16); // Copy the next 16 bytes into the bytes buffer buffer.copy(bytes, 0, index, index + 16); // Update index index = index + 16; // Assign the new Decimal128 value var decimal128 = new Decimal128(bytes); // If we have an alternative mapper use that object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; } else if (elementType === BSON.BSON_DATA_BINARY) { var binarySize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); var totalBinarySize = binarySize; var subType = buffer[index++]; // Did we have a negative binary size, throw if (binarySize < 0) throw new Error('Negative binary type element size found'); // Is the length longer than the document if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); // Decode as raw Buffer object if options specifies it if (buffer['slice'] != null) { // If we have subtype 2 skip the 4 bytes for the size if (subType === Binary.SUBTYPE_BYTE_ARRAY) { binarySize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); } if (promoteBuffers && promoteValues) { object[name] = buffer.slice(index, index + binarySize); } else { object[name] = new Binary(buffer.slice(index, index + binarySize), subType); } } else { var _buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); // If we have subtype 2 skip the 4 bytes for the size if (subType === Binary.SUBTYPE_BYTE_ARRAY) { binarySize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); } // Copy the data for (i = 0; i < binarySize; i++) { _buffer[i] = buffer[index + i]; } if (promoteBuffers && promoteValues) { object[name] = _buffer; } else { object[name] = new Binary(_buffer, subType); } } // Update the index index = index + binarySize; } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { // Get the start search index i = index; // Locate the end of the c string while (buffer[i] !== 0x00 && i < buffer.length) { i++; } // If are at the end of the buffer there is a problem with the document if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); // Return the C string var source = buffer.toString('utf8', index, i); // Create the regexp index = i + 1; // Get the start search index i = index; // Locate the end of the c string while (buffer[i] !== 0x00 && i < buffer.length) { i++; } // If are at the end of the buffer there is a problem with the document if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); // Return the C string var regExpOptions = buffer.toString('utf8', index, i); index = i + 1; // For each option add the corresponding one for javascript var optionsArray = new Array(regExpOptions.length); // Parse options for (i = 0; i < regExpOptions.length; i++) { switch (regExpOptions[i]) { case 'm': optionsArray[i] = 'm'; break; case 's': optionsArray[i] = 'g'; break; case 'i': optionsArray[i] = 'i'; break; } } object[name] = new RegExp(source, optionsArray.join('')); } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { // Get the start search index i = index; // Locate the end of the c string while (buffer[i] !== 0x00 && i < buffer.length) { i++; } // If are at the end of the buffer there is a problem with the document if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); // Return the C string source = buffer.toString('utf8', index, i); index = i + 1; // Get the start search index i = index; // Locate the end of the c string while (buffer[i] !== 0x00 && i < buffer.length) { i++; } // If are at the end of the buffer there is a problem with the document if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); // Return the C string regExpOptions = buffer.toString('utf8', index, i); index = i + 1; // Set the object object[name] = new BSONRegExp(source, regExpOptions); } else if (elementType === BSON.BSON_DATA_SYMBOL) { stringSize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); if ( stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0 ) throw new Error('bad string length in bson'); object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); index = index + stringSize; } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { lowBits = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); highBits = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); object[name] = new Timestamp(lowBits, highBits); } else if (elementType === BSON.BSON_DATA_MIN_KEY) { object[name] = new MinKey(); } else if (elementType === BSON.BSON_DATA_MAX_KEY) { object[name] = new MaxKey(); } else if (elementType === BSON.BSON_DATA_CODE) { stringSize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); if ( stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0 ) throw new Error('bad string length in bson'); var functionString = buffer.toString('utf8', index, index + stringSize - 1); // If we are evaluating the functions if (evalFunctions) { // If we have cache enabled let's look for the md5 of the function in the cache if (cacheFunctions) { var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; // Got to do this to avoid V8 deoptimizing the call due to finding eval object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); } else { object[name] = isolateEval(functionString); } } else { object[name] = new Code(functionString); } // Update parse index position index = index + stringSize; } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { var totalSize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); // Element cannot be shorter than totalSize + stringSize + documentSize + terminator if (totalSize < 4 + 4 + 4 + 1) { throw new Error('code_w_scope total size shorter minimum expected length'); } // Get the code string size stringSize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); // Check if we have a valid string if ( stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0 ) throw new Error('bad string length in bson'); // Javascript function functionString = buffer.toString('utf8', index, index + stringSize - 1); // Update parse index position index = index + stringSize; // Parse the element _index = index; // Decode the size of the object document objectSize = buffer[index] | (buffer[index + 1] << 8) | (buffer[index + 2] << 16) | (buffer[index + 3] << 24); // Decode the scope object var scopeObject = deserializeObject(buffer, _index, options, false); // Adjust the index index = index + objectSize; // Check if field length is to short if (totalSize < 4 + 4 + objectSize + stringSize) { throw new Error('code_w_scope total size is to short, truncating scope'); } // Check if totalSize field is to long if (totalSize > 4 + 4 + objectSize + stringSize) { throw new Error('code_w_scope total size is to long, clips outer document'); } // If we are evaluating the functions if (evalFunctions) { // If we have cache enabled let's look for the md5 of the function in the cache if (cacheFunctions) { hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; // Got to do this to avoid V8 deoptimizing the call due to finding eval object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); } else { object[name] = isolateEval(functionString); } object[name].scope = scopeObject; } else { object[name] = new Code(functionString, scopeObject); } } else if (elementType === BSON.BSON_DATA_DBPOINTER) { // Get the code string size stringSize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); // Check if we have a valid string if ( stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0 ) throw new Error('bad string length in bson'); // Namespace var namespace = buffer.toString('utf8', index, index + stringSize - 1); // Update parse index position index = index + stringSize; // Read the oid var oidBuffer = utils.allocBuffer(12); buffer.copy(oidBuffer, 0, index, index + 12); oid = new ObjectID(oidBuffer); // Update the index index = index + 12; // Split the namespace var parts = namespace.split('.'); var db = parts.shift(); var collection = parts.join('.'); // Upgrade to DBRef type object[name] = new DBRef(collection, oid, db); } else { throw new Error( 'Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '", are you using the latest BSON parser' ); } } // Check if the deserialization was against a valid array/object if (size !== index - startIndex) { if (isArray) throw new Error('corrupt array bson'); throw new Error('corrupt object bson'); } // Check if we have a db ref object if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); return object; }; /** * Ensure eval is isolated. * * @ignore * @api private */ var isolateEvalWithHash = function(functionCache, hash, functionString, object) { // Contains the value we are going to set var value = null; // Check for cache hit, eval if missing and return cached function if (functionCache[hash] == null) { eval('value = ' + functionString); functionCache[hash] = value; } // Set the object return functionCache[hash].bind(object); }; /** * Ensure eval is isolated. * * @ignore * @api private */ var isolateEval = function(functionString) { // Contains the value we are going to set var value = null; // Eval the function eval('value = ' + functionString); return value; }; var BSON = {}; /** * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 * * @ignore * @api private */ var functionCache = (BSON.functionCache = {}); /** * Number BSON Type * * @classconstant BSON_DATA_NUMBER **/ BSON.BSON_DATA_NUMBER = 1; /** * String BSON Type * * @classconstant BSON_DATA_STRING **/ BSON.BSON_DATA_STRING = 2; /** * Object BSON Type * * @classconstant BSON_DATA_OBJECT **/ BSON.BSON_DATA_OBJECT = 3; /** * Array BSON Type * * @classconstant BSON_DATA_ARRAY **/ BSON.BSON_DATA_ARRAY = 4; /** * Binary BSON Type * * @classconstant BSON_DATA_BINARY **/ BSON.BSON_DATA_BINARY = 5; /** * Binary BSON Type * * @classconstant BSON_DATA_UNDEFINED **/ BSON.BSON_DATA_UNDEFINED = 6; /** * ObjectID BSON Type * * @classconstant BSON_DATA_OID **/ BSON.BSON_DATA_OID = 7; /** * Boolean BSON Type * * @classconstant BSON_DATA_BOOLEAN **/ BSON.BSON_DATA_BOOLEAN = 8; /** * Date BSON Type * * @classconstant BSON_DATA_DATE **/ BSON.BSON_DATA_DATE = 9; /** * null BSON Type * * @classconstant BSON_DATA_NULL **/ BSON.BSON_DATA_NULL = 10; /** * RegExp BSON Type * * @classconstant BSON_DATA_REGEXP **/ BSON.BSON_DATA_REGEXP = 11; /** * Code BSON Type * * @classconstant BSON_DATA_DBPOINTER **/ BSON.BSON_DATA_DBPOINTER = 12; /** * Code BSON Type * * @classconstant BSON_DATA_CODE **/ BSON.BSON_DATA_CODE = 13; /** * Symbol BSON Type * * @classconstant BSON_DATA_SYMBOL **/ BSON.BSON_DATA_SYMBOL = 14; /** * Code with Scope BSON Type * * @classconstant BSON_DATA_CODE_W_SCOPE **/ BSON.BSON_DATA_CODE_W_SCOPE = 15; /** * 32 bit Integer BSON Type * * @classconstant BSON_DATA_INT **/ BSON.BSON_DATA_INT = 16; /** * Timestamp BSON Type * * @classconstant BSON_DATA_TIMESTAMP **/ BSON.BSON_DATA_TIMESTAMP = 17; /** * Long BSON Type * * @classconstant BSON_DATA_LONG **/ BSON.BSON_DATA_LONG = 18; /** * Long BSON Type * * @classconstant BSON_DATA_DECIMAL128 **/ BSON.BSON_DATA_DECIMAL128 = 19; /** * MinKey BSON Type * * @classconstant BSON_DATA_MIN_KEY **/ BSON.BSON_DATA_MIN_KEY = 0xff; /** * MaxKey BSON Type * * @classconstant BSON_DATA_MAX_KEY **/ BSON.BSON_DATA_MAX_KEY = 0x7f; /** * Binary Default Type * * @classconstant BSON_BINARY_SUBTYPE_DEFAULT **/ BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; /** * Binary Function Type * * @classconstant BSON_BINARY_SUBTYPE_FUNCTION **/ BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; /** * Binary Byte Array Type * * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY **/ BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; /** * Binary UUID Type * * @classconstant BSON_BINARY_SUBTYPE_UUID **/ BSON.BSON_BINARY_SUBTYPE_UUID = 3; /** * Binary MD5 Type * * @classconstant BSON_BINARY_SUBTYPE_MD5 **/ BSON.BSON_BINARY_SUBTYPE_MD5 = 4; /** * Binary User Defined Type * * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED **/ BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; // BSON MAX VALUES BSON.BSON_INT32_MAX = 0x7fffffff; BSON.BSON_INT32_MIN = -0x80000000; BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; BSON.BSON_INT64_MIN = -Math.pow(2, 63); // JS MAX PRECISE VALUES BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. // Internal long versions var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. module.exports = deserialize; },{"../binary":109,"../code":111,"../db_ref":112,"../decimal128":113,"../double":114,"../int_32":116,"../long":117,"../max_key":119,"../min_key":120,"../objectid":121,"../regexp":126,"../symbol":127,"../timestamp":128,"./utils":125}],124:[function(require,module,exports){ (function (Buffer){(function (){ 'use strict'; var writeIEEE754 = require('../float_parser').writeIEEE754, Long = require('../long').Long, Map = require('../map'), Binary = require('../binary').Binary; var normalizedFunctionString = require('./utils').normalizedFunctionString; // try { // var _Buffer = Uint8Array; // } catch (e) { // _Buffer = Buffer; // } var regexp = /\x00/; // eslint-disable-line no-control-regex var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; // To ensure that 0.4 of node works correctly var isDate = function isDate(d) { return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; }; var isRegExp = function isRegExp(d) { return Object.prototype.toString.call(d) === '[object RegExp]'; }; var serializeString = function(buffer, key, value, index, isArray) { // Encode String type buffer[index++] = BSON.BSON_DATA_STRING; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes + 1; buffer[index - 1] = 0; // Write the string var size = buffer.write(value, index + 4, 'utf8'); // Write the size of the string to buffer buffer[index + 3] = ((size + 1) >> 24) & 0xff; buffer[index + 2] = ((size + 1) >> 16) & 0xff; buffer[index + 1] = ((size + 1) >> 8) & 0xff; buffer[index] = (size + 1) & 0xff; // Update index index = index + 4 + size; // Write zero buffer[index++] = 0; return index; }; var serializeNumber = function(buffer, key, value, index, isArray) { // We have an integer value if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { // If the value fits in 32 bits encode as int, if it fits in a double // encode it as a double, otherwise long if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // Set int type 32 bits or less buffer[index++] = BSON.BSON_DATA_INT; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write the int value buffer[index++] = value & 0xff; buffer[index++] = (value >> 8) & 0xff; buffer[index++] = (value >> 16) & 0xff; buffer[index++] = (value >> 24) & 0xff; } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { // Encode as double buffer[index++] = BSON.BSON_DATA_NUMBER; // Number of written bytes numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write float writeIEEE754(buffer, value, index, 'little', 52, 8); // Ajust index index = index + 8; } else { // Set long type buffer[index++] = BSON.BSON_DATA_LONG; // Number of written bytes numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; var longVal = Long.fromNumber(value); var lowBits = longVal.getLowBits(); var highBits = longVal.getHighBits(); // Encode low bits buffer[index++] = lowBits & 0xff; buffer[index++] = (lowBits >> 8) & 0xff; buffer[index++] = (lowBits >> 16) & 0xff; buffer[index++] = (lowBits >> 24) & 0xff; // Encode high bits buffer[index++] = highBits & 0xff; buffer[index++] = (highBits >> 8) & 0xff; buffer[index++] = (highBits >> 16) & 0xff; buffer[index++] = (highBits >> 24) & 0xff; } } else { // Encode as double buffer[index++] = BSON.BSON_DATA_NUMBER; // Number of written bytes numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write float writeIEEE754(buffer, value, index, 'little', 52, 8); // Ajust index index = index + 8; } return index; }; var serializeNull = function(buffer, key, value, index, isArray) { // Set long type buffer[index++] = BSON.BSON_DATA_NULL; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; return index; }; var serializeBoolean = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_BOOLEAN; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Encode the boolean value buffer[index++] = value ? 1 : 0; return index; }; var serializeDate = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_DATE; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write the date var dateInMilis = Long.fromNumber(value.getTime()); var lowBits = dateInMilis.getLowBits(); var highBits = dateInMilis.getHighBits(); // Encode low bits buffer[index++] = lowBits & 0xff; buffer[index++] = (lowBits >> 8) & 0xff; buffer[index++] = (lowBits >> 16) & 0xff; buffer[index++] = (lowBits >> 24) & 0xff; // Encode high bits buffer[index++] = highBits & 0xff; buffer[index++] = (highBits >> 8) & 0xff; buffer[index++] = (highBits >> 16) & 0xff; buffer[index++] = (highBits >> 24) & 0xff; return index; }; var serializeRegExp = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_REGEXP; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; if (value.source && value.source.match(regexp) != null) { throw Error('value ' + value.source + ' must not contain null bytes'); } // Adjust the index index = index + buffer.write(value.source, index, 'utf8'); // Write zero buffer[index++] = 0x00; // Write the parameters if (value.global) buffer[index++] = 0x73; // s if (value.ignoreCase) buffer[index++] = 0x69; // i if (value.multiline) buffer[index++] = 0x6d; // m // Add ending zero buffer[index++] = 0x00; return index; }; var serializeBSONRegExp = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_REGEXP; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Check the pattern for 0 bytes if (value.pattern.match(regexp) != null) { // The BSON spec doesn't allow keys with null bytes because keys are // null-terminated. throw Error('pattern ' + value.pattern + ' must not contain null bytes'); } // Adjust the index index = index + buffer.write(value.pattern, index, 'utf8'); // Write zero buffer[index++] = 0x00; // Write the options index = index + buffer.write( value.options .split('') .sort() .join(''), index, 'utf8' ); // Add ending zero buffer[index++] = 0x00; return index; }; var serializeMinMax = function(buffer, key, value, index, isArray) { // Write the type of either min or max key if (value === null) { buffer[index++] = BSON.BSON_DATA_NULL; } else if (value._bsontype === 'MinKey') { buffer[index++] = BSON.BSON_DATA_MIN_KEY; } else { buffer[index++] = BSON.BSON_DATA_MAX_KEY; } // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; return index; }; var serializeObjectId = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_OID; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write the objectId into the shared buffer if (typeof value.id === 'string') { buffer.write(value.id, index, 'binary'); } else if (value.id && value.id.copy) { value.id.copy(buffer, index, 0, 12); } else { throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); } // Ajust index return index + 12; }; var serializeBuffer = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_BINARY; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Get size of the buffer (current write point) var size = value.length; // Write the size of the string to buffer buffer[index++] = size & 0xff; buffer[index++] = (size >> 8) & 0xff; buffer[index++] = (size >> 16) & 0xff; buffer[index++] = (size >> 24) & 0xff; // Write the default subtype buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; // Copy the content form the binary field to the buffer value.copy(buffer, index, 0, size); // Adjust the index index = index + size; return index; }; var serializeObject = function( buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path ) { for (var i = 0; i < path.length; i++) { if (path[i] === value) throw new Error('cyclic dependency detected'); } // Push value to stack path.push(value); // Write the type buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; var endIndex = serializeInto( buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path ); // Pop stack path.pop(); // Write size return endIndex; }; var serializeDecimal128 = function(buffer, key, value, index, isArray) { buffer[index++] = BSON.BSON_DATA_DECIMAL128; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write the data from the value value.bytes.copy(buffer, index, 0, 16); return index + 16; }; var serializeLong = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write the date var lowBits = value.getLowBits(); var highBits = value.getHighBits(); // Encode low bits buffer[index++] = lowBits & 0xff; buffer[index++] = (lowBits >> 8) & 0xff; buffer[index++] = (lowBits >> 16) & 0xff; buffer[index++] = (lowBits >> 24) & 0xff; // Encode high bits buffer[index++] = highBits & 0xff; buffer[index++] = (highBits >> 8) & 0xff; buffer[index++] = (highBits >> 16) & 0xff; buffer[index++] = (highBits >> 24) & 0xff; return index; }; var serializeInt32 = function(buffer, key, value, index, isArray) { // Set int type 32 bits or less buffer[index++] = BSON.BSON_DATA_INT; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write the int value buffer[index++] = value & 0xff; buffer[index++] = (value >> 8) & 0xff; buffer[index++] = (value >> 16) & 0xff; buffer[index++] = (value >> 24) & 0xff; return index; }; var serializeDouble = function(buffer, key, value, index, isArray) { // Encode as double buffer[index++] = BSON.BSON_DATA_NUMBER; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write float writeIEEE754(buffer, value, index, 'little', 52, 8); // Ajust index index = index + 8; return index; }; var serializeFunction = function(buffer, key, value, index, checkKeys, depth, isArray) { buffer[index++] = BSON.BSON_DATA_CODE; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Function string var functionString = normalizedFunctionString(value); // Write the string var size = buffer.write(functionString, index + 4, 'utf8') + 1; // Write the size of the string to buffer buffer[index] = size & 0xff; buffer[index + 1] = (size >> 8) & 0xff; buffer[index + 2] = (size >> 16) & 0xff; buffer[index + 3] = (size >> 24) & 0xff; // Update index index = index + 4 + size - 1; // Write zero buffer[index++] = 0; return index; }; var serializeCode = function( buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray ) { if (value.scope && typeof value.scope === 'object') { // Write the type buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Starting index var startIndex = index; // Serialize the function // Get the function string var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); // Index adjustment index = index + 4; // Write string into buffer var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; // Write the size of the string to buffer buffer[index] = codeSize & 0xff; buffer[index + 1] = (codeSize >> 8) & 0xff; buffer[index + 2] = (codeSize >> 16) & 0xff; buffer[index + 3] = (codeSize >> 24) & 0xff; // Write end 0 buffer[index + 4 + codeSize - 1] = 0; // Write the index = index + codeSize + 4; // // Serialize the scope value var endIndex = serializeInto( buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined ); index = endIndex - 1; // Writ the total var totalSize = endIndex - startIndex; // Write the total size of the object buffer[startIndex++] = totalSize & 0xff; buffer[startIndex++] = (totalSize >> 8) & 0xff; buffer[startIndex++] = (totalSize >> 16) & 0xff; buffer[startIndex++] = (totalSize >> 24) & 0xff; // Write trailing zero buffer[index++] = 0; } else { buffer[index++] = BSON.BSON_DATA_CODE; // Number of written bytes numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Function string functionString = value.code.toString(); // Write the string var size = buffer.write(functionString, index + 4, 'utf8') + 1; // Write the size of the string to buffer buffer[index] = size & 0xff; buffer[index + 1] = (size >> 8) & 0xff; buffer[index + 2] = (size >> 16) & 0xff; buffer[index + 3] = (size >> 24) & 0xff; // Update index index = index + 4 + size - 1; // Write zero buffer[index++] = 0; } return index; }; var serializeBinary = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_BINARY; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Extract the buffer var data = value.value(true); // Calculate size var size = value.position; // Add the deprecated 02 type 4 bytes of size to total if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; // Write the size of the string to buffer buffer[index++] = size & 0xff; buffer[index++] = (size >> 8) & 0xff; buffer[index++] = (size >> 16) & 0xff; buffer[index++] = (size >> 24) & 0xff; // Write the subtype to the buffer buffer[index++] = value.sub_type; // If we have binary type 2 the 4 first bytes are the size if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { size = size - 4; buffer[index++] = size & 0xff; buffer[index++] = (size >> 8) & 0xff; buffer[index++] = (size >> 16) & 0xff; buffer[index++] = (size >> 24) & 0xff; } // Write the data to the object data.copy(buffer, index, 0, value.position); // Adjust the index index = index + value.position; return index; }; var serializeSymbol = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_SYMBOL; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write the string var size = buffer.write(value.value, index + 4, 'utf8') + 1; // Write the size of the string to buffer buffer[index] = size & 0xff; buffer[index + 1] = (size >> 8) & 0xff; buffer[index + 2] = (size >> 16) & 0xff; buffer[index + 3] = (size >> 24) & 0xff; // Update index index = index + 4 + size - 1; // Write zero buffer[index++] = 0x00; return index; }; var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_OBJECT; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; var startIndex = index; var endIndex; // Serialize object if (null != value.db) { endIndex = serializeInto( buffer, { $ref: value.namespace, $id: value.oid, $db: value.db }, false, index, depth + 1, serializeFunctions ); } else { endIndex = serializeInto( buffer, { $ref: value.namespace, $id: value.oid }, false, index, depth + 1, serializeFunctions ); } // Calculate object size var size = endIndex - startIndex; // Write the size buffer[startIndex++] = size & 0xff; buffer[startIndex++] = (size >> 8) & 0xff; buffer[startIndex++] = (size >> 16) & 0xff; buffer[startIndex++] = (size >> 24) & 0xff; // Set index return endIndex; }; var serializeInto = function serializeInto( buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path ) { startingIndex = startingIndex || 0; path = path || []; // Push the object to the path path.push(object); // Start place to serialize into var index = startingIndex + 4; // var self = this; // Special case isArray if (Array.isArray(object)) { // Get object keys for (var i = 0; i < object.length; i++) { var key = '' + i; var value = object[i]; // Is there an override value if (value && value.toBSON) { if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); value = value.toBSON(); } var type = typeof value; if (type === 'string') { index = serializeString(buffer, key, value, index, true); } else if (type === 'number') { index = serializeNumber(buffer, key, value, index, true); } else if (type === 'boolean') { index = serializeBoolean(buffer, key, value, index, true); } else if (value instanceof Date || isDate(value)) { index = serializeDate(buffer, key, value, index, true); } else if (value === undefined) { index = serializeNull(buffer, key, value, index, true); } else if (value === null) { index = serializeNull(buffer, key, value, index, true); } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { index = serializeObjectId(buffer, key, value, index, true); } else if (Buffer.isBuffer(value)) { index = serializeBuffer(buffer, key, value, index, true); } else if (value instanceof RegExp || isRegExp(value)) { index = serializeRegExp(buffer, key, value, index, true); } else if (type === 'object' && value['_bsontype'] == null) { index = serializeObject( buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path ); } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { index = serializeDecimal128(buffer, key, value, index, true); } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { index = serializeLong(buffer, key, value, index, true); } else if (value['_bsontype'] === 'Double') { index = serializeDouble(buffer, key, value, index, true); } else if (typeof value === 'function' && serializeFunctions) { index = serializeFunction( buffer, key, value, index, checkKeys, depth, serializeFunctions, true ); } else if (value['_bsontype'] === 'Code') { index = serializeCode( buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true ); } else if (value['_bsontype'] === 'Binary') { index = serializeBinary(buffer, key, value, index, true); } else if (value['_bsontype'] === 'Symbol') { index = serializeSymbol(buffer, key, value, index, true); } else if (value['_bsontype'] === 'DBRef') { index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); } else if (value['_bsontype'] === 'BSONRegExp') { index = serializeBSONRegExp(buffer, key, value, index, true); } else if (value['_bsontype'] === 'Int32') { index = serializeInt32(buffer, key, value, index, true); } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { index = serializeMinMax(buffer, key, value, index, true); } else if (typeof value['_bsontype'] !== 'undefined') { throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); } } } else if (object instanceof Map) { var iterator = object.entries(); var done = false; while (!done) { // Unpack the next entry var entry = iterator.next(); done = entry.done; // Are we done, then skip and terminate if (done) continue; // Get the entry values key = entry.value[0]; value = entry.value[1]; // Check the type of the value type = typeof value; // Check the key and throw error if it's illegal if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { if (key.match(regexp) != null) { // The BSON spec doesn't allow keys with null bytes because keys are // null-terminated. throw Error('key ' + key + ' must not contain null bytes'); } if (checkKeys) { if ('$' === key[0]) { throw Error('key ' + key + " must not start with '$'"); } else if (~key.indexOf('.')) { throw Error('key ' + key + " must not contain '.'"); } } } if (type === 'string') { index = serializeString(buffer, key, value, index); } else if (type === 'number') { index = serializeNumber(buffer, key, value, index); } else if (type === 'boolean') { index = serializeBoolean(buffer, key, value, index); } else if (value instanceof Date || isDate(value)) { index = serializeDate(buffer, key, value, index); // } else if (value === undefined && ignoreUndefined === true) { } else if (value === null || (value === undefined && ignoreUndefined === false)) { index = serializeNull(buffer, key, value, index); } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { index = serializeObjectId(buffer, key, value, index); } else if (Buffer.isBuffer(value)) { index = serializeBuffer(buffer, key, value, index); } else if (value instanceof RegExp || isRegExp(value)) { index = serializeRegExp(buffer, key, value, index); } else if (type === 'object' && value['_bsontype'] == null) { index = serializeObject( buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path ); } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { index = serializeDecimal128(buffer, key, value, index); } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { index = serializeLong(buffer, key, value, index); } else if (value['_bsontype'] === 'Double') { index = serializeDouble(buffer, key, value, index); } else if (value['_bsontype'] === 'Code') { index = serializeCode( buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined ); } else if (typeof value === 'function' && serializeFunctions) { index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); } else if (value['_bsontype'] === 'Binary') { index = serializeBinary(buffer, key, value, index); } else if (value['_bsontype'] === 'Symbol') { index = serializeSymbol(buffer, key, value, index); } else if (value['_bsontype'] === 'DBRef') { index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); } else if (value['_bsontype'] === 'BSONRegExp') { index = serializeBSONRegExp(buffer, key, value, index); } else if (value['_bsontype'] === 'Int32') { index = serializeInt32(buffer, key, value, index); } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { index = serializeMinMax(buffer, key, value, index); } else if (typeof value['_bsontype'] !== 'undefined') { throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); } } } else { // Did we provide a custom serialization method if (object.toBSON) { if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); object = object.toBSON(); if (object != null && typeof object !== 'object') throw new Error('toBSON function did not return an object'); } // Iterate over all the keys for (key in object) { value = object[key]; // Is there an override value if (value && value.toBSON) { if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); value = value.toBSON(); } // Check the type of the value type = typeof value; // Check the key and throw error if it's illegal if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { if (key.match(regexp) != null) { // The BSON spec doesn't allow keys with null bytes because keys are // null-terminated. throw Error('key ' + key + ' must not contain null bytes'); } if (checkKeys) { if ('$' === key[0]) { throw Error('key ' + key + " must not start with '$'"); } else if (~key.indexOf('.')) { throw Error('key ' + key + " must not contain '.'"); } } } if (type === 'string') { index = serializeString(buffer, key, value, index); } else if (type === 'number') { index = serializeNumber(buffer, key, value, index); } else if (type === 'boolean') { index = serializeBoolean(buffer, key, value, index); } else if (value instanceof Date || isDate(value)) { index = serializeDate(buffer, key, value, index); } else if (value === undefined) { if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); } else if (value === null) { index = serializeNull(buffer, key, value, index); } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { index = serializeObjectId(buffer, key, value, index); } else if (Buffer.isBuffer(value)) { index = serializeBuffer(buffer, key, value, index); } else if (value instanceof RegExp || isRegExp(value)) { index = serializeRegExp(buffer, key, value, index); } else if (type === 'object' && value['_bsontype'] == null) { index = serializeObject( buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path ); } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { index = serializeDecimal128(buffer, key, value, index); } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { index = serializeLong(buffer, key, value, index); } else if (value['_bsontype'] === 'Double') { index = serializeDouble(buffer, key, value, index); } else if (value['_bsontype'] === 'Code') { index = serializeCode( buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined ); } else if (typeof value === 'function' && serializeFunctions) { index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); } else if (value['_bsontype'] === 'Binary') { index = serializeBinary(buffer, key, value, index); } else if (value['_bsontype'] === 'Symbol') { index = serializeSymbol(buffer, key, value, index); } else if (value['_bsontype'] === 'DBRef') { index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); } else if (value['_bsontype'] === 'BSONRegExp') { index = serializeBSONRegExp(buffer, key, value, index); } else if (value['_bsontype'] === 'Int32') { index = serializeInt32(buffer, key, value, index); } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { index = serializeMinMax(buffer, key, value, index); } else if (typeof value['_bsontype'] !== 'undefined') { throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); } } } // Remove the path path.pop(); // Final padding byte for object buffer[index++] = 0x00; // Final size var size = index - startingIndex; // Write the size of the object buffer[startingIndex++] = size & 0xff; buffer[startingIndex++] = (size >> 8) & 0xff; buffer[startingIndex++] = (size >> 16) & 0xff; buffer[startingIndex++] = (size >> 24) & 0xff; return index; }; var BSON = {}; /** * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 * * @ignore * @api private */ // var functionCache = (BSON.functionCache = {}); /** * Number BSON Type * * @classconstant BSON_DATA_NUMBER **/ BSON.BSON_DATA_NUMBER = 1; /** * String BSON Type * * @classconstant BSON_DATA_STRING **/ BSON.BSON_DATA_STRING = 2; /** * Object BSON Type * * @classconstant BSON_DATA_OBJECT **/ BSON.BSON_DATA_OBJECT = 3; /** * Array BSON Type * * @classconstant BSON_DATA_ARRAY **/ BSON.BSON_DATA_ARRAY = 4; /** * Binary BSON Type * * @classconstant BSON_DATA_BINARY **/ BSON.BSON_DATA_BINARY = 5; /** * ObjectID BSON Type, deprecated * * @classconstant BSON_DATA_UNDEFINED **/ BSON.BSON_DATA_UNDEFINED = 6; /** * ObjectID BSON Type * * @classconstant BSON_DATA_OID **/ BSON.BSON_DATA_OID = 7; /** * Boolean BSON Type * * @classconstant BSON_DATA_BOOLEAN **/ BSON.BSON_DATA_BOOLEAN = 8; /** * Date BSON Type * * @classconstant BSON_DATA_DATE **/ BSON.BSON_DATA_DATE = 9; /** * null BSON Type * * @classconstant BSON_DATA_NULL **/ BSON.BSON_DATA_NULL = 10; /** * RegExp BSON Type * * @classconstant BSON_DATA_REGEXP **/ BSON.BSON_DATA_REGEXP = 11; /** * Code BSON Type * * @classconstant BSON_DATA_CODE **/ BSON.BSON_DATA_CODE = 13; /** * Symbol BSON Type * * @classconstant BSON_DATA_SYMBOL **/ BSON.BSON_DATA_SYMBOL = 14; /** * Code with Scope BSON Type * * @classconstant BSON_DATA_CODE_W_SCOPE **/ BSON.BSON_DATA_CODE_W_SCOPE = 15; /** * 32 bit Integer BSON Type * * @classconstant BSON_DATA_INT **/ BSON.BSON_DATA_INT = 16; /** * Timestamp BSON Type * * @classconstant BSON_DATA_TIMESTAMP **/ BSON.BSON_DATA_TIMESTAMP = 17; /** * Long BSON Type * * @classconstant BSON_DATA_LONG **/ BSON.BSON_DATA_LONG = 18; /** * Long BSON Type * * @classconstant BSON_DATA_DECIMAL128 **/ BSON.BSON_DATA_DECIMAL128 = 19; /** * MinKey BSON Type * * @classconstant BSON_DATA_MIN_KEY **/ BSON.BSON_DATA_MIN_KEY = 0xff; /** * MaxKey BSON Type * * @classconstant BSON_DATA_MAX_KEY **/ BSON.BSON_DATA_MAX_KEY = 0x7f; /** * Binary Default Type * * @classconstant BSON_BINARY_SUBTYPE_DEFAULT **/ BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; /** * Binary Function Type * * @classconstant BSON_BINARY_SUBTYPE_FUNCTION **/ BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; /** * Binary Byte Array Type * * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY **/ BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; /** * Binary UUID Type * * @classconstant BSON_BINARY_SUBTYPE_UUID **/ BSON.BSON_BINARY_SUBTYPE_UUID = 3; /** * Binary MD5 Type * * @classconstant BSON_BINARY_SUBTYPE_MD5 **/ BSON.BSON_BINARY_SUBTYPE_MD5 = 4; /** * Binary User Defined Type * * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED **/ BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; // BSON MAX VALUES BSON.BSON_INT32_MAX = 0x7fffffff; BSON.BSON_INT32_MIN = -0x80000000; BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; BSON.BSON_INT64_MIN = -Math.pow(2, 63); // JS MAX PRECISE VALUES BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. // Internal long versions // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. module.exports = serializeInto; }).call(this)}).call(this,{"isBuffer":require("../../../../is-buffer/index.js")}) },{"../../../../is-buffer/index.js":179,"../binary":109,"../float_parser":115,"../long":117,"../map":118,"./utils":125}],125:[function(require,module,exports){ (function (Buffer){(function (){ 'use strict'; /** * Normalizes our expected stringified form of a function across versions of node * @param {Function} fn The function to stringify */ function normalizedFunctionString(fn) { return fn.toString().replace(/function *\(/, 'function ('); } function newBuffer(item, encoding) { return new Buffer(item, encoding); } function allocBuffer() { return Buffer.alloc.apply(Buffer, arguments); } function toBuffer() { return Buffer.from.apply(Buffer, arguments); } module.exports = { normalizedFunctionString: normalizedFunctionString, allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer, toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer }; }).call(this)}).call(this,require("buffer").Buffer) },{"buffer":129}],126:[function(require,module,exports){ /** * A class representation of the BSON RegExp type. * * @class * @return {BSONRegExp} A MinKey instance */ function BSONRegExp(pattern, options) { if (!(this instanceof BSONRegExp)) return new BSONRegExp(); // Execute this._bsontype = 'BSONRegExp'; this.pattern = pattern || ''; this.options = options || ''; // Validate options for (var i = 0; i < this.options.length; i++) { if ( !( this.options[i] === 'i' || this.options[i] === 'm' || this.options[i] === 'x' || this.options[i] === 'l' || this.options[i] === 's' || this.options[i] === 'u' ) ) { throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); } } } module.exports = BSONRegExp; module.exports.BSONRegExp = BSONRegExp; },{}],127:[function(require,module,exports){ (function (Buffer){(function (){ // Custom inspect property name / symbol. var inspect = Buffer ? require('util').inspect.custom || 'inspect' : 'inspect'; /** * A class representation of the BSON Symbol type. * * @class * @deprecated * @param {string} value the string representing the symbol. * @return {Symbol} */ function Symbol(value) { if (!(this instanceof Symbol)) return new Symbol(value); this._bsontype = 'Symbol'; this.value = value; } /** * Access the wrapped string value. * * @method * @return {String} returns the wrapped string. */ Symbol.prototype.valueOf = function() { return this.value; }; /** * @ignore */ Symbol.prototype.toString = function() { return this.value; }; /** * @ignore */ Symbol.prototype[inspect] = function() { return this.value; }; /** * @ignore */ Symbol.prototype.toJSON = function() { return this.value; }; module.exports = Symbol; module.exports.Symbol = Symbol; }).call(this)}).call(this,require("buffer").Buffer) },{"buffer":129,"util":332}],128:[function(require,module,exports){ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Copyright 2009 Google Inc. All Rights Reserved /** * This type is for INTERNAL use in MongoDB only and should not be used in applications. * The appropriate corresponding type is the JavaScript Date type. * * Defines a Timestamp class for representing a 64-bit two's-complement * integer value, which faithfully simulates the behavior of a Java "Timestamp". This * implementation is derived from TimestampLib in GWT. * * Constructs a 64-bit two's-complement integer, given its low and high 32-bit * values as *signed* integers. See the from* functions below for more * convenient ways of constructing Timestamps. * * The internal representation of a Timestamp is the two given signed, 32-bit values. * We use 32-bit pieces because these are the size of integers on which * Javascript performs bit-operations. For operations like addition and * multiplication, we split each number into 16-bit pieces, which can easily be * multiplied within Javascript's floating-point representation without overflow * or change in sign. * * In the algorithms below, we frequently reduce the negative case to the * positive case by negating the input(s) and then post-processing the result. * Note that we must ALWAYS check specially whether those values are MIN_VALUE * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as * a positive number, it overflows back into a negative). Not handling this * case would often result in infinite recursion. * * @class * @param {number} low the low (signed) 32 bits of the Timestamp. * @param {number} high the high (signed) 32 bits of the Timestamp. */ function Timestamp(low, high) { if (!(this instanceof Timestamp)) return new Timestamp(low, high); this._bsontype = 'Timestamp'; /** * @type {number} * @ignore */ this.low_ = low | 0; // force into 32 signed bits. /** * @type {number} * @ignore */ this.high_ = high | 0; // force into 32 signed bits. } /** * Return the int value. * * @return {number} the value, assuming it is a 32-bit integer. */ Timestamp.prototype.toInt = function() { return this.low_; }; /** * Return the Number value. * * @method * @return {number} the closest floating-point representation to this value. */ Timestamp.prototype.toNumber = function() { return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); }; /** * Return the JSON value. * * @method * @return {string} the JSON representation. */ Timestamp.prototype.toJSON = function() { return this.toString(); }; /** * Return the String value. * * @method * @param {number} [opt_radix] the radix in which the text should be written. * @return {string} the textual representation of this value. */ Timestamp.prototype.toString = function(opt_radix) { var radix = opt_radix || 10; if (radix < 2 || 36 < radix) { throw Error('radix out of range: ' + radix); } if (this.isZero()) { return '0'; } if (this.isNegative()) { if (this.equals(Timestamp.MIN_VALUE)) { // We need to change the Timestamp value before it can be negated, so we remove // the bottom-most digit in this base and then recurse to do the rest. var radixTimestamp = Timestamp.fromNumber(radix); var div = this.div(radixTimestamp); var rem = div.multiply(radixTimestamp).subtract(this); return div.toString(radix) + rem.toInt().toString(radix); } else { return '-' + this.negate().toString(radix); } } // Do several (6) digits each time through the loop, so as to // minimize the calls to the very expensive emulated div. var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); rem = this; var result = ''; while (!rem.isZero()) { var remDiv = rem.div(radixToPower); var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); var digits = intval.toString(radix); rem = remDiv; if (rem.isZero()) { return digits + result; } else { while (digits.length < 6) { digits = '0' + digits; } result = '' + digits + result; } } }; /** * Return the high 32-bits value. * * @method * @return {number} the high 32-bits as a signed value. */ Timestamp.prototype.getHighBits = function() { return this.high_; }; /** * Return the low 32-bits value. * * @method * @return {number} the low 32-bits as a signed value. */ Timestamp.prototype.getLowBits = function() { return this.low_; }; /** * Return the low unsigned 32-bits value. * * @method * @return {number} the low 32-bits as an unsigned value. */ Timestamp.prototype.getLowBitsUnsigned = function() { return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; }; /** * Returns the number of bits needed to represent the absolute value of this Timestamp. * * @method * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. */ Timestamp.prototype.getNumBitsAbs = function() { if (this.isNegative()) { if (this.equals(Timestamp.MIN_VALUE)) { return 64; } else { return this.negate().getNumBitsAbs(); } } else { var val = this.high_ !== 0 ? this.high_ : this.low_; for (var bit = 31; bit > 0; bit--) { if ((val & (1 << bit)) !== 0) { break; } } return this.high_ !== 0 ? bit + 33 : bit + 1; } }; /** * Return whether this value is zero. * * @method * @return {boolean} whether this value is zero. */ Timestamp.prototype.isZero = function() { return this.high_ === 0 && this.low_ === 0; }; /** * Return whether this value is negative. * * @method * @return {boolean} whether this value is negative. */ Timestamp.prototype.isNegative = function() { return this.high_ < 0; }; /** * Return whether this value is odd. * * @method * @return {boolean} whether this value is odd. */ Timestamp.prototype.isOdd = function() { return (this.low_ & 1) === 1; }; /** * Return whether this Timestamp equals the other * * @method * @param {Timestamp} other Timestamp to compare against. * @return {boolean} whether this Timestamp equals the other */ Timestamp.prototype.equals = function(other) { return this.high_ === other.high_ && this.low_ === other.low_; }; /** * Return whether this Timestamp does not equal the other. * * @method * @param {Timestamp} other Timestamp to compare against. * @return {boolean} whether this Timestamp does not equal the other. */ Timestamp.prototype.notEquals = function(other) { return this.high_ !== other.high_ || this.low_ !== other.low_; }; /** * Return whether this Timestamp is less than the other. * * @method * @param {Timestamp} other Timestamp to compare against. * @return {boolean} whether this Timestamp is less than the other. */ Timestamp.prototype.lessThan = function(other) { return this.compare(other) < 0; }; /** * Return whether this Timestamp is less than or equal to the other. * * @method * @param {Timestamp} other Timestamp to compare against. * @return {boolean} whether this Timestamp is less than or equal to the other. */ Timestamp.prototype.lessThanOrEqual = function(other) { return this.compare(other) <= 0; }; /** * Return whether this Timestamp is greater than the other. * * @method * @param {Timestamp} other Timestamp to compare against. * @return {boolean} whether this Timestamp is greater than the other. */ Timestamp.prototype.greaterThan = function(other) { return this.compare(other) > 0; }; /** * Return whether this Timestamp is greater than or equal to the other. * * @method * @param {Timestamp} other Timestamp to compare against. * @return {boolean} whether this Timestamp is greater than or equal to the other. */ Timestamp.prototype.greaterThanOrEqual = function(other) { return this.compare(other) >= 0; }; /** * Compares this Timestamp with the given one. * * @method * @param {Timestamp} other Timestamp to compare against. * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. */ Timestamp.prototype.compare = function(other) { if (this.equals(other)) { return 0; } var thisNeg = this.isNegative(); var otherNeg = other.isNegative(); if (thisNeg && !otherNeg) { return -1; } if (!thisNeg && otherNeg) { return 1; } // at this point, the signs are the same, so subtraction will not overflow if (this.subtract(other).isNegative()) { return -1; } else { return 1; } }; /** * The negation of this value. * * @method * @return {Timestamp} the negation of this value. */ Timestamp.prototype.negate = function() { if (this.equals(Timestamp.MIN_VALUE)) { return Timestamp.MIN_VALUE; } else { return this.not().add(Timestamp.ONE); } }; /** * Returns the sum of this and the given Timestamp. * * @method * @param {Timestamp} other Timestamp to add to this one. * @return {Timestamp} the sum of this and the given Timestamp. */ Timestamp.prototype.add = function(other) { // Divide each number into 4 chunks of 16 bits, and then sum the chunks. var a48 = this.high_ >>> 16; var a32 = this.high_ & 0xffff; var a16 = this.low_ >>> 16; var a00 = this.low_ & 0xffff; var b48 = other.high_ >>> 16; var b32 = other.high_ & 0xffff; var b16 = other.low_ >>> 16; var b00 = other.low_ & 0xffff; var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 + b00; c16 += c00 >>> 16; c00 &= 0xffff; c16 += a16 + b16; c32 += c16 >>> 16; c16 &= 0xffff; c32 += a32 + b32; c48 += c32 >>> 16; c32 &= 0xffff; c48 += a48 + b48; c48 &= 0xffff; return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); }; /** * Returns the difference of this and the given Timestamp. * * @method * @param {Timestamp} other Timestamp to subtract from this. * @return {Timestamp} the difference of this and the given Timestamp. */ Timestamp.prototype.subtract = function(other) { return this.add(other.negate()); }; /** * Returns the product of this and the given Timestamp. * * @method * @param {Timestamp} other Timestamp to multiply with this. * @return {Timestamp} the product of this and the other. */ Timestamp.prototype.multiply = function(other) { if (this.isZero()) { return Timestamp.ZERO; } else if (other.isZero()) { return Timestamp.ZERO; } if (this.equals(Timestamp.MIN_VALUE)) { return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; } else if (other.equals(Timestamp.MIN_VALUE)) { return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; } if (this.isNegative()) { if (other.isNegative()) { return this.negate().multiply(other.negate()); } else { return this.negate() .multiply(other) .negate(); } } else if (other.isNegative()) { return this.multiply(other.negate()).negate(); } // If both Timestamps are small, use float multiplication if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { return Timestamp.fromNumber(this.toNumber() * other.toNumber()); } // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. // We can skip products that would overflow. var a48 = this.high_ >>> 16; var a32 = this.high_ & 0xffff; var a16 = this.low_ >>> 16; var a00 = this.low_ & 0xffff; var b48 = other.high_ >>> 16; var b32 = other.high_ & 0xffff; var b16 = other.low_ >>> 16; var b00 = other.low_ & 0xffff; var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 * b00; c16 += c00 >>> 16; c00 &= 0xffff; c16 += a16 * b00; c32 += c16 >>> 16; c16 &= 0xffff; c16 += a00 * b16; c32 += c16 >>> 16; c16 &= 0xffff; c32 += a32 * b00; c48 += c32 >>> 16; c32 &= 0xffff; c32 += a16 * b16; c48 += c32 >>> 16; c32 &= 0xffff; c32 += a00 * b32; c48 += c32 >>> 16; c32 &= 0xffff; c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; c48 &= 0xffff; return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); }; /** * Returns this Timestamp divided by the given one. * * @method * @param {Timestamp} other Timestamp by which to divide. * @return {Timestamp} this Timestamp divided by the given one. */ Timestamp.prototype.div = function(other) { if (other.isZero()) { throw Error('division by zero'); } else if (this.isZero()) { return Timestamp.ZERO; } if (this.equals(Timestamp.MIN_VALUE)) { if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE } else if (other.equals(Timestamp.MIN_VALUE)) { return Timestamp.ONE; } else { // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. var halfThis = this.shiftRight(1); var approx = halfThis.div(other).shiftLeft(1); if (approx.equals(Timestamp.ZERO)) { return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; } else { var rem = this.subtract(other.multiply(approx)); var result = approx.add(rem.div(other)); return result; } } } else if (other.equals(Timestamp.MIN_VALUE)) { return Timestamp.ZERO; } if (this.isNegative()) { if (other.isNegative()) { return this.negate().div(other.negate()); } else { return this.negate() .div(other) .negate(); } } else if (other.isNegative()) { return this.div(other.negate()).negate(); } // Repeat the following until the remainder is less than other: find a // floating-point that approximates remainder / other *from below*, add this // into the result, and subtract it from the remainder. It is critical that // the approximate value is less than or equal to the real value so that the // remainder never becomes negative. var res = Timestamp.ZERO; rem = this; while (rem.greaterThanOrEqual(other)) { // Approximate the result of division. This may be a little greater or // smaller than the actual value. approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); // We will tweak the approximate result by changing it in the 48-th digit or // the smallest non-fractional digit, whichever is larger. var log2 = Math.ceil(Math.log(approx) / Math.LN2); var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); // Decrease the approximation until it is smaller than the remainder. Note // that if it is too large, the product overflows and is negative. var approxRes = Timestamp.fromNumber(approx); var approxRem = approxRes.multiply(other); while (approxRem.isNegative() || approxRem.greaterThan(rem)) { approx -= delta; approxRes = Timestamp.fromNumber(approx); approxRem = approxRes.multiply(other); } // We know the answer can't be zero... and actually, zero would cause // infinite recursion since we would make no progress. if (approxRes.isZero()) { approxRes = Timestamp.ONE; } res = res.add(approxRes); rem = rem.subtract(approxRem); } return res; }; /** * Returns this Timestamp modulo the given one. * * @method * @param {Timestamp} other Timestamp by which to mod. * @return {Timestamp} this Timestamp modulo the given one. */ Timestamp.prototype.modulo = function(other) { return this.subtract(this.div(other).multiply(other)); }; /** * The bitwise-NOT of this value. * * @method * @return {Timestamp} the bitwise-NOT of this value. */ Timestamp.prototype.not = function() { return Timestamp.fromBits(~this.low_, ~this.high_); }; /** * Returns the bitwise-AND of this Timestamp and the given one. * * @method * @param {Timestamp} other the Timestamp with which to AND. * @return {Timestamp} the bitwise-AND of this and the other. */ Timestamp.prototype.and = function(other) { return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); }; /** * Returns the bitwise-OR of this Timestamp and the given one. * * @method * @param {Timestamp} other the Timestamp with which to OR. * @return {Timestamp} the bitwise-OR of this and the other. */ Timestamp.prototype.or = function(other) { return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); }; /** * Returns the bitwise-XOR of this Timestamp and the given one. * * @method * @param {Timestamp} other the Timestamp with which to XOR. * @return {Timestamp} the bitwise-XOR of this and the other. */ Timestamp.prototype.xor = function(other) { return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); }; /** * Returns this Timestamp with bits shifted to the left by the given amount. * * @method * @param {number} numBits the number of bits by which to shift. * @return {Timestamp} this shifted to the left by the given amount. */ Timestamp.prototype.shiftLeft = function(numBits) { numBits &= 63; if (numBits === 0) { return this; } else { var low = this.low_; if (numBits < 32) { var high = this.high_; return Timestamp.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); } else { return Timestamp.fromBits(0, low << (numBits - 32)); } } }; /** * Returns this Timestamp with bits shifted to the right by the given amount. * * @method * @param {number} numBits the number of bits by which to shift. * @return {Timestamp} this shifted to the right by the given amount. */ Timestamp.prototype.shiftRight = function(numBits) { numBits &= 63; if (numBits === 0) { return this; } else { var high = this.high_; if (numBits < 32) { var low = this.low_; return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); } else { return Timestamp.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); } } }; /** * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. * * @method * @param {number} numBits the number of bits by which to shift. * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. */ Timestamp.prototype.shiftRightUnsigned = function(numBits) { numBits &= 63; if (numBits === 0) { return this; } else { var high = this.high_; if (numBits < 32) { var low = this.low_; return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); } else if (numBits === 32) { return Timestamp.fromBits(high, 0); } else { return Timestamp.fromBits(high >>> (numBits - 32), 0); } } }; /** * Returns a Timestamp representing the given (32-bit) integer value. * * @method * @param {number} value the 32-bit integer in question. * @return {Timestamp} the corresponding Timestamp value. */ Timestamp.fromInt = function(value) { if (-128 <= value && value < 128) { var cachedObj = Timestamp.INT_CACHE_[value]; if (cachedObj) { return cachedObj; } } var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); if (-128 <= value && value < 128) { Timestamp.INT_CACHE_[value] = obj; } return obj; }; /** * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. * * @method * @param {number} value the number in question. * @return {Timestamp} the corresponding Timestamp value. */ Timestamp.fromNumber = function(value) { if (isNaN(value) || !isFinite(value)) { return Timestamp.ZERO; } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { return Timestamp.MIN_VALUE; } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { return Timestamp.MAX_VALUE; } else if (value < 0) { return Timestamp.fromNumber(-value).negate(); } else { return new Timestamp( (value % Timestamp.TWO_PWR_32_DBL_) | 0, (value / Timestamp.TWO_PWR_32_DBL_) | 0 ); } }; /** * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. * * @method * @param {number} lowBits the low 32-bits. * @param {number} highBits the high 32-bits. * @return {Timestamp} the corresponding Timestamp value. */ Timestamp.fromBits = function(lowBits, highBits) { return new Timestamp(lowBits, highBits); }; /** * Returns a Timestamp representation of the given string, written using the given radix. * * @method * @param {string} str the textual representation of the Timestamp. * @param {number} opt_radix the radix in which the text is written. * @return {Timestamp} the corresponding Timestamp value. */ Timestamp.fromString = function(str, opt_radix) { if (str.length === 0) { throw Error('number format error: empty string'); } var radix = opt_radix || 10; if (radix < 2 || 36 < radix) { throw Error('radix out of range: ' + radix); } if (str.charAt(0) === '-') { return Timestamp.fromString(str.substring(1), radix).negate(); } else if (str.indexOf('-') >= 0) { throw Error('number format error: interior "-" character: ' + str); } // Do several (8) digits each time through the loop, so as to // minimize the calls to the very expensive emulated div. var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); var result = Timestamp.ZERO; for (var i = 0; i < str.length; i += 8) { var size = Math.min(8, str.length - i); var value = parseInt(str.substring(i, i + size), radix); if (size < 8) { var power = Timestamp.fromNumber(Math.pow(radix, size)); result = result.multiply(power).add(Timestamp.fromNumber(value)); } else { result = result.multiply(radixToPower); result = result.add(Timestamp.fromNumber(value)); } } return result; }; // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the // from* methods on which they depend. /** * A cache of the Timestamp representations of small integer values. * @type {Object} * @ignore */ Timestamp.INT_CACHE_ = {}; // NOTE: the compiler should inline these constant values below and then remove // these variables, so there should be no runtime penalty for these. /** * Number used repeated below in calculations. This must appear before the * first call to any from* function below. * @type {number} * @ignore */ Timestamp.TWO_PWR_16_DBL_ = 1 << 16; /** * @type {number} * @ignore */ Timestamp.TWO_PWR_24_DBL_ = 1 << 24; /** * @type {number} * @ignore */ Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; /** * @type {number} * @ignore */ Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; /** * @type {number} * @ignore */ Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; /** * @type {number} * @ignore */ Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; /** * @type {number} * @ignore */ Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; /** @type {Timestamp} */ Timestamp.ZERO = Timestamp.fromInt(0); /** @type {Timestamp} */ Timestamp.ONE = Timestamp.fromInt(1); /** @type {Timestamp} */ Timestamp.NEG_ONE = Timestamp.fromInt(-1); /** @type {Timestamp} */ Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); /** @type {Timestamp} */ Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); /** * @type {Timestamp} * @ignore */ Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); /** * Expose. */ module.exports = Timestamp; module.exports.Timestamp = Timestamp; },{}],129:[function(require,module,exports){ (function (Buffer){(function (){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') 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) arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } return arr.foo() === 42 } catch (e) { return false } } Object.defineProperty(Buffer.prototype, 'parent', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.buffer } }) Object.defineProperty(Buffer.prototype, 'offset', { enumerable: true, get: function () { 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) buf.__proto__ = 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) } // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 if (typeof Symbol !== 'undefined' && Symbol.species != null && Buffer[Symbol.species] === Buffer) { Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true, enumerable: false, writable: false }) } 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 fromArrayLike(value) } if (value == null) { throw 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 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 Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = 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 interpretted 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 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 buf.__proto__ = 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)) { buf = Buffer.from(buf) } if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } 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 coersion 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 '' } 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 latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, 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': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(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 += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; 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 newBuf.__proto__ = 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 = 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 = 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 = function readUInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } 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 = function readUInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (var i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } 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 } // 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 toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } 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 } }).call(this)}).call(this,require("buffer").Buffer) },{"base64-js":107,"buffer":129,"ieee754":178}],130:[function(require,module,exports){ "use strict"; 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 = require('./datatypes/datatypes'), Code = _require.Code, ValueSet = _require.ValueSet; var CodeService = /*#__PURE__*/function () { function CodeService() { var valueSetsJson = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, CodeService); this.valueSets = {}; for (var oid in valueSetsJson) { this.valueSets[oid] = {}; for (var version in valueSetsJson[oid]) { var codes = valueSetsJson[oid][version].map(function (code) { return new Code(code.code, code.system, code.version); }); this.valueSets[oid][version] = new ValueSet(oid, version, codes); } } } _createClass(CodeService, [{ key: "findValueSetsByOid", value: function findValueSetsByOid(oid) { return this.valueSets[oid] ? Object.values(this.valueSets[oid]) : []; } }, { key: "findValueSet", value: function findValueSet(oid, version) { if (version != null) { return this.valueSets[oid] != null ? this.valueSets[oid][version] : undefined; } else { var results = this.findValueSetsByOid(oid); if (results.length === 0) { return null; } else { return results.reduce(function (a, b) { if (a.version > b.version) { return a; } else { return b; } }); } } } }]); return CodeService; }(); module.exports.CodeService = CodeService; },{"./datatypes/datatypes":134}],131:[function(require,module,exports){ "use strict"; 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; 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 _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 DT = require('./datatypes/datatypes'); var Record = /*#__PURE__*/function () { function Record(json) { _classCallCheck(this, Record); this.json = json; this.id = this.json.id; } _createClass(Record, [{ key: "_is", value: function _is(typeSpecifier) { return this._typeHierarchy().some(function (t) { return t.type === typeSpecifier.type && t.name == typeSpecifier.name; }); } }, { key: "_typeHierarchy", value: function _typeHierarchy() { return [{ name: "{https://github.com/cqframework/cql-execution/simple}".concat(this.json.recordType), type: 'NamedTypeSpecifier' }, { name: '{https://github.com/cqframework/cql-execution/simple}Record', type: 'NamedTypeSpecifier' }, { name: '{urn:hl7-org:elm-types:r1}Any', type: 'NamedTypeSpecifier' }]; } }, { key: "_recursiveGet", value: function _recursiveGet(field) { if (field != null && field.indexOf('.') >= 0) { var _field$split = field.split('.', 2), _field$split2 = _slicedToArray(_field$split, 2), root = _field$split2[0], rest = _field$split2[1]; return new Record(this._recursiveGet(root))._recursiveGet(rest); } return this.json[field]; } }, { key: "get", value: function get(field) { // the model should return the correct type for the field. For this simple model example, // we just cheat and use the shape of the value to determine it. Real implementations should // have a more sophisticated approach var value = this._recursiveGet(field); if (typeof value === 'string' && /\d{4}-\d{2}-\d{2}(T[\d\-.]+)?/.test(value)) { return this.getDate(field); } if (value != null && _typeof(value) === 'object' && value.code != null && value.system != null) { return this.getCode(field); } if (value != null && _typeof(value) === 'object' && (value.low != null || value.high != null)) { return this.getInterval(field); } return value; } }, { key: "getId", value: function getId() { return this.id; } }, { key: "getDate", value: function getDate(field) { var val = this._recursiveGet(field); if (val != null) { return DT.DateTime.parse(val); } else { return null; } } }, { key: "getInterval", value: function getInterval(field) { var val = this._recursiveGet(field); if (val != null && _typeof(val) === 'object') { var low = val.low != null ? DT.DateTime.parse(val.low) : null; var high = val.high != null ? DT.DateTime.parse(val.high) : null; return new DT.Interval(low, high); } } }, { key: "getDateOrInterval", value: function getDateOrInterval(field) { var val = this._recursiveGet(field); if (val != null && _typeof(val) === 'object') { return this.getInterval(field); } else { return this.getDate(field); } } }, { key: "getCode", value: function getCode(field) { var val = this._recursiveGet(field); if (val != null && _typeof(val) === 'object') { return new DT.Code(val.code, val.system, val.version); } } }]); return Record; }(); var Patient = /*#__PURE__*/function (_Record) { _inherits(Patient, _Record); var _super = _createSuper(Patient); function Patient(json) { var _this; _classCallCheck(this, Patient); _this = _super.call(this, json); _this.name = json.name; _this.gender = json.gender; _this.birthDate = json.birthDate != null ? DT.DateTime.parse(json.birthDate) : undefined; _this.records = {}; (json.records || []).forEach(function (r) { if (_this.records[r.recordType] == null) { _this.records[r.recordType] = []; } _this.records[r.recordType].push(new Record(r)); }); return _this; } _createClass(Patient, [{ key: "findRecords", value: function findRecords(profile) { if (profile == null) { return []; } var recordType = profile.match(/(\{https:\/\/github\.com\/cqframework\/cql-execution\/simple\})?(.*)/)[2]; if (recordType === 'Patient') { return [this]; } else { return this.records[recordType] || []; } } }]); return Patient; }(Record); var PatientSource = /*#__PURE__*/function () { function PatientSource(patients) { _classCallCheck(this, PatientSource); this.patients = patients; this.nextPatient(); } _createClass(PatientSource, [{ key: "currentPatient", value: function currentPatient() { return this.current; } }, { key: "nextPatient", value: function nextPatient() { var currentJSON = this.patients.shift(); this.current = currentJSON ? new Patient(currentJSON) : undefined; return this.current; } }]); return PatientSource; }(); module.exports.Patient = Patient; module.exports.PatientSource = PatientSource; },{"./datatypes/datatypes":134}],132:[function(require,module,exports){ "use strict"; var library = require('./elm/library'); var expression = require('./elm/expression'); var repository = require('./runtime/repository'); var context = require('./runtime/context'); var exec = require('./runtime/executor'); var results = require('./runtime/results'); var datatypes = require('./datatypes/datatypes'); var patient = require('./cql-patient'); var codeservice = require('./cql-code-service'); // Library-related classes module.exports.Library = library.Library; module.exports.Repository = repository.Repository; module.exports.Expression = expression.Expression; // Execution-related classes module.exports.Context = context.Context; module.exports.Executor = exec.Executor; module.exports.PatientContext = context.PatientContext; module.exports.UnfilteredContext = context.UnfilteredContext; module.exports.Results = results.Results; // PatientSource-related classes module.exports.Patient = patient.Patient; module.exports.PatientSource = patient.PatientSource; // TerminologyService-related classes module.exports.CodeService = codeservice.CodeService; // DataType classes module.exports.Code = datatypes.Code; module.exports.CodeSystem = datatypes.CodeSystem; module.exports.Concept = datatypes.Concept; module.exports.Date = datatypes.Date; module.exports.DateTime = datatypes.DateTime; module.exports.Interval = datatypes.Interval; module.exports.Quantity = datatypes.Quantity; module.exports.Ratio = datatypes.Ratio; module.exports.ValueSet = datatypes.ValueSet; },{"./cql-code-service":130,"./cql-patient":131,"./datatypes/datatypes":134,"./elm/expression":150,"./elm/library":155,"./runtime/context":169,"./runtime/executor":170,"./runtime/repository":171,"./runtime/results":172}],133:[function(require,module,exports){ "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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); return Constructor; } var _require = require('../util/util'), typeIsArray = _require.typeIsArray; var Code = /*#__PURE__*/function () { function Code(code, system, version, display) { _classCallCheck(this, Code); this.code = code; this.system = system; this.version = version; this.display = display; } _createClass(Code, [{ key: "hasMatch", value: function hasMatch(code) { if (typeof code === 'string') { // the specific behavior for this is not in the specification. Matching codesystem behavior. return code === this.code; } else { return codesInList(toCodeList(code), [this]); } } }, { key: "isCode", get: function get() { return true; } }]); return Code; }(); var Concept = /*#__PURE__*/function () { function Concept(codes, display) { _classCallCheck(this, Concept); this.codes = codes || []; this.display = display; } _createClass(Concept, [{ key: "hasMatch", value: function hasMatch(code) { return codesInList(toCodeList(code), this.codes); } }, { key: "isConcept", get: function get() { return true; } }]); return Concept; }(); var ValueSet = /*#__PURE__*/function () { function ValueSet(oid, version, codes) { _classCallCheck(this, ValueSet); this.oid = oid; this.version = version; this.codes = codes || []; } _createClass(ValueSet, [{ key: "hasMatch", value: function hasMatch(code) { var codesList = toCodeList(code); // InValueSet String Overload if (codesList.length === 1 && typeof codesList[0] === 'string') { var matchFound = false; var multipleCodeSystemsExist = false; var _iterator = _createForOfIteratorHelper(this.codes), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var codeItem = _step.value; // Confirm all code systems match if (codeItem.system !== this.codes[0].system) { multipleCodeSystemsExist = true; } if (codeItem.code === codesList[0]) { matchFound = true; } if (multipleCodeSystemsExist && matchFound) { throw new Error('In (valueset) is ambiguous -- multiple codes with multiple code systems exist in value set.'); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return matchFound; } else { return codesInList(codesList, this.codes); } } }, { key: "isValueSet", get: function get() { return true; } }]); return ValueSet; }(); function toCodeList(c) { if (c == null) { return []; } else if (typeIsArray(c)) { var list = []; var _iterator2 = _createForOfIteratorHelper(c), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var c2 = _step2.value; list = list.concat(toCodeList(c2)); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return list; } else if (typeIsArray(c.codes)) { return c.codes; } else { return [c]; } } function codesInList(cl1, cl2) { // test each code in c1 against each code in c2 looking for a match return cl1.some(function (c1) { return cl2.some(function (c2) { // only the left argument (cl1) can contain strings. cl2 will only contain codes. if (typeof c1 === 'string') { // for "string in codesystem" this should compare the string to // the code's "code" field according to the specification. return c1 === c2.code; } else { return codesMatch(c1, c2); } }); }); } function codesMatch(code1, code2) { return code1.code === code2.code && code1.system === code2.system; } var CodeSystem = function CodeSystem(id, version) { _classCallCheck(this, CodeSystem); this.id = id; this.version = version; }; module.exports = { Code: Code, Concept: Concept, ValueSet: ValueSet, CodeSystem: CodeSystem }; },{"../util/util":176}],134:[function(require,module,exports){ "use strict"; var logic = require('./logic'); var clinical = require('./clinical'); var uncertainty = require('./uncertainty'); var datetime = require('./datetime'); var interval = require('./interval'); var quantity = require('./quantity'); var ratio = require('./ratio'); var libs = [logic, clinical, uncertainty, datetime, interval, quantity, ratio]; for (var _i = 0, _libs = libs; _i < _libs.length; _i++) { var lib = _libs[_i]; for (var _i2 = 0, _Object$keys = Object.keys(lib); _i2 < _Object$keys.length; _i2++) { var element = _Object$keys[_i2]; module.exports[element] = lib[element]; } } },{"./clinical":133,"./datetime":135,"./interval":137,"./logic":138,"./quantity":139,"./ratio":140,"./uncertainty":141}],135:[function(require,module,exports){ "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; } function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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 _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 _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 _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } 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" && Symbol.iterator in Object(iter)) 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 _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 = require('./uncertainty'), Uncertainty = _require.Uncertainty; var _require2 = require('../util/util'), jsDate = _require2.jsDate, normalizeMillisecondsField = _require2.normalizeMillisecondsField, normalizeMillisecondsFieldInString = _require2.normalizeMillisecondsFieldInString; var luxon = require('luxon'); // It's easiest and most performant to organize formats by length of the supported strings. // This way we can test strings only against the formats that have a chance of working. // NOTE: Formats use Luxon formats, documented here: https://moment.github.io/luxon/docs/manual/parsing.html#table-of-tokens var LENGTH_TO_DATE_FORMAT_MAP = function () { var ltdfMap = new Map(); ltdfMap.set(4, 'yyyy'); ltdfMap.set(7, 'yyyy-MM'); ltdfMap.set(10, 'yyyy-MM-dd'); return ltdfMap; }(); var LENGTH_TO_DATETIME_FORMATS_MAP = function () { var formats = { yyyy: '2012', 'yyyy-MM': '2012-01', 'yyyy-MM-dd': '2012-01-31', "yyyy-MM-dd'T''Z'": '2012-01-31TZ', "yyyy-MM-dd'T'ZZ": '2012-01-31T-04:00', "yyyy-MM-dd'T'HH": '2012-01-31T12', "yyyy-MM-dd'T'HH'Z'": '2012-01-31T12Z', "yyyy-MM-dd'T'HHZZ": '2012-01-31T12-04:00', "yyyy-MM-dd'T'HH:mm": '2012-01-31T12:30', "yyyy-MM-dd'T'HH:mm'Z'": '2012-01-31T12:30Z', "yyyy-MM-dd'T'HH:mmZZ": '2012-01-31T12:30-04:00', "yyyy-MM-dd'T'HH:mm:ss": '2012-01-31T12:30:59', "yyyy-MM-dd'T'HH:mm:ss'Z'": '2012-01-31T12:30:59Z', "yyyy-MM-dd'T'HH:mm:ssZZ": '2012-01-31T12:30:59-04:00', "yyyy-MM-dd'T'HH:mm:ss.SSS": '2012-01-31T12:30:59.000', "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'": '2012-01-31T12:30:59.000Z', "yyyy-MM-dd'T'HH:mm:ss.SSSZZ": '2012-01-31T12:30:59.000-04:00' }; var ltdtfMap = new Map(); Object.keys(formats).forEach(function (k) { var example = formats[k]; if (!ltdtfMap.has(example.length)) { ltdtfMap.set(example.length, [k]); } else { ltdtfMap.get(example.length).push(k); } }); return ltdtfMap; }(); function wholeLuxonDuration(duration, unit) { var value = duration.get(unit); return value >= 0 ? Math.floor(value) : Math.ceil(value); } function truncateLuxonDateTime(luxonDT, unit) { // Truncating by week (to the previous Sunday) requires different logic than the rest if (unit === DateTime.Unit.WEEK) { // Sunday is ISO weekday 7 if (luxonDT.weekday !== 7) { luxonDT = luxonDT.set({ weekday: 7 }).minus({ weeks: 1 }); } unit = DateTime.Unit.DAY; } return luxonDT.startOf(unit); } var DateTime = /*#__PURE__*/function () { _createClass(DateTime, null, [{ key: "parse", value: function parse(string) { if (string === null) { return null; } var matches = /(\d{4})(-(\d{2}))?(-(\d{2}))?(T((\d{2})(:(\d{2})(:(\d{2})(\.(\d+))?)?)?)?(Z|(([+-])(\d{2})(:?(\d{2}))?))?)?/.exec(string); if (matches == null) { return null; } var years = matches[1]; var months = matches[3]; var days = matches[5]; var hours = matches[8]; var minutes = matches[10]; var seconds = matches[12]; var milliseconds = matches[14]; if (milliseconds != null) { milliseconds = normalizeMillisecondsField(milliseconds); } if (milliseconds != null) { string = normalizeMillisecondsFieldInString(string, matches[14]); } if (!isValidDateTimeStringFormat(string)) { return null; } // convert the args to integers var args = [years, months, days, hours, minutes, seconds, milliseconds].map(function (arg) { return arg != null ? parseInt(arg) : arg; }); // convert timezone offset to decimal and add it to arguments if (matches[18] != null) { var num = parseInt(matches[18]) + (matches[20] != null ? parseInt(matches[20]) / 60 : 0); args.push(matches[17] === '+' ? num : num * -1); } else if (matches[15] === 'Z') { args.push(0); } return _construct(DateTime, _toConsumableArray(args)); } }, { key: "fromJSDate", value: function fromJSDate(date, timezoneOffset) { //This is from a JS Date, not a CQL Date if (date instanceof DateTime) { return date; } if (timezoneOffset != null) { date = new jsDate(date.getTime() + timezoneOffset * 60 * 60 * 1000); return new DateTime(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds(), timezoneOffset); } else { return new DateTime(date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()); } } }, { key: "fromLuxonDateTime", value: function fromLuxonDateTime(luxonDT) { if (luxonDT instanceof DateTime) { return luxonDT; } return new DateTime(luxonDT.year, luxonDT.month, luxonDT.day, luxonDT.hour, luxonDT.minute, luxonDT.second, luxonDT.millisecond, luxonDT.offset / 60); } }]); function DateTime() { var year = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var month = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var day = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var hour = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var minute = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; var second = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; var millisecond = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; var timezoneOffset = arguments.length > 7 ? arguments[7] : undefined; _classCallCheck(this, DateTime); // from the spec: If no timezone is specified, the timezone of the evaluation request timestamp is used. // NOTE: timezoneOffset will be explicitly null for the Time overload, whereas // it will be undefined if simply unspecified this.year = year; this.month = month; this.day = day; this.hour = hour; this.minute = minute; this.second = second; this.millisecond = millisecond; this.timezoneOffset = timezoneOffset; if (this.timezoneOffset === undefined) { this.timezoneOffset = new jsDate().getTimezoneOffset() / 60 * -1; } } _createClass(DateTime, [{ key: "copy", value: function copy() { return new DateTime(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond, this.timezoneOffset); } }, { key: "successor", value: function successor() { if (this.millisecond != null) { return this.add(1, DateTime.Unit.MILLISECOND); } else if (this.second != null) { return this.add(1, DateTime.Unit.SECOND); } else if (this.minute != null) { return this.add(1, DateTime.Unit.MINUTE); } else if (this.hour != null) { return this.add(1, DateTime.Unit.HOUR); } else if (this.day != null) { return this.add(1, DateTime.Unit.DAY); } else if (this.month != null) { return this.add(1, DateTime.Unit.MONTH); } else if (this.year != null) { return this.add(1, DateTime.Unit.YEAR); } } }, { key: "predecessor", value: function predecessor() { if (this.millisecond != null) { return this.add(-1, DateTime.Unit.MILLISECOND); } else if (this.second != null) { return this.add(-1, DateTime.Unit.SECOND); } else if (this.minute != null) { return this.add(-1, DateTime.Unit.MINUTE); } else if (this.hour != null) { return this.add(-1, DateTime.Unit.HOUR); } else if (this.day != null) { return this.add(-1, DateTime.Unit.DAY); } else if (this.month != null) { return this.add(-1, DateTime.Unit.MONTH); } else if (this.year != null) { return this.add(-1, DateTime.Unit.YEAR); } } }, { key: "convertToTimezoneOffset", value: function convertToTimezoneOffset() { var timezoneOffset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var shiftedLuxonDT = this.toLuxonDateTime().setZone(luxon.FixedOffsetZone.instance(timezoneOffset * 60)); var shiftedDT = DateTime.fromLuxonDateTime(shiftedLuxonDT); return shiftedDT.reducedPrecision(this.getPrecision()); } }, { key: "differenceBetween", value: function differenceBetween(other, unitField) { other = this._implicitlyConvert(other); if (other == null || !other.isDateTime) { return null; } // According to CQL spec: // * "Difference calculations are performed by truncating the datetime values at the next precision, // and then performing the corresponding duration calculation on the truncated values." // * "When difference is calculated for hours or finer units, timezone offsets should be normalized // prior to truncation to correctly consider real (actual elapsed) time. When difference is calculated // for days or coarser units, however, the time components (including timezone offset) should be truncated // without normalization to correctly reflect the difference in calendar days, months, and years." var a = this.toLuxonUncertainty(); var b = other.toLuxonUncertainty(); // If unit is days or above, reset all the DateTimes to UTC since TZ offset should not be considered; // Otherwise, we don't actually have to "normalize" to a common TZ because Luxon takes TZ into account. if ([DateTime.Unit.YEAR, DateTime.Unit.MONTH, DateTime.Unit.WEEK, DateTime.Unit.DAY].includes(unitField)) { a.low = a.low.toUTC(0, { keepLocalTime: true }); a.high = a.high.toUTC(0, { keepLocalTime: true }); b.low = b.low.toUTC(0, { keepLocalTime: true }); b.high = b.high.toUTC(0, { keepLocalTime: true }); } // Truncate all dates at precision below specified unit a.low = truncateLuxonDateTime(a.low, unitField); a.high = truncateLuxonDateTime(a.high, unitField); b.low = truncateLuxonDateTime(b.low, unitField); b.high = truncateLuxonDateTime(b.high, unitField); // Return the duration based on the normalize and truncated values return new Uncertainty(wholeLuxonDuration(b.low.diff(a.high, unitField), unitField), wholeLuxonDuration(b.high.diff(a.low, unitField), unitField)); } }, { key: "durationBetween", value: function durationBetween(other, unitField) { other = this._implicitlyConvert(other); if (other == null || !other.isDateTime) { return null; } var a = this.toLuxonUncertainty(); var b = other.toLuxonUncertainty(); return new Uncertainty(wholeLuxonDuration(b.low.diff(a.high, unitField), unitField), wholeLuxonDuration(b.high.diff(a.low, unitField), unitField)); } }, { key: "isUTC", value: function isUTC() { // A timezoneOffset of 0 indicates UTC time. return !this.timezoneOffset; } }, { key: "getPrecision", value: function getPrecision() { var result = null; if (this.year != null) { result = DateTime.Unit.YEAR; } else { return result; } if (this.month != null) { result = DateTime.Unit.MONTH; } else { return result; } if (this.day != null) { result = DateTime.Unit.DAY; } else { return result; } if (this.hour != null) { result = DateTime.Unit.HOUR; } else { return result; } if (this.minute != null) { result = DateTime.Unit.MINUTE; } else { return result; } if (this.second != null) { result = DateTime.Unit.SECOND; } else { return result; } if (this.millisecond != null) { result = DateTime.Unit.MILLISECOND; } return result; } }, { key: "toLuxonDateTime", value: function toLuxonDateTime() { var offsetMins = this.timezoneOffset != null ? this.timezoneOffset * 60 : new jsDate().getTimezoneOffset() * -1; return luxon.DateTime.fromObject({ year: this.year, month: this.month, day: this.day, hour: this.hour, minute: this.minute, second: this.second, millisecond: this.millisecond, zone: luxon.FixedOffsetZone.instance(offsetMins) }); } }, { key: "toLuxonUncertainty", value: function toLuxonUncertainty() { var low = this.toLuxonDateTime(); var high = low.endOf(this.getPrecision()); return new Uncertainty(low, high); } }, { key: "toJSDate", value: function toJSDate() { var ignoreTimezone = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var luxonDT = this.toLuxonDateTime(); // I don't know if anyone is using "ignoreTimezone" anymore (we aren't), but just in case if (ignoreTimezone) { var offset = new jsDate().getTimezoneOffset() * -1; luxonDT = luxonDT.setZone(luxon.FixedOffsetZone.instance(offset), { keepLocalTime: true }); } return luxonDT.toJSDate(); } }, { key: "toJSON", value: function toJSON() { return this.toString(); } }, { key: "_pad", value: function _pad(num) { return String('0' + num).slice(-2); } }, { key: "toString", value: function toString() { if (this.isTime()) { return this.toStringTime(); } else { return this.toStringDateTime(); } } }, { key: "toStringTime", value: function toStringTime() { var str = ''; if (this.hour != null) { str += this._pad(this.hour); if (this.minute != null) { str += ':' + this._pad(this.minute); if (this.second != null) { str += ':' + this._pad(this.second); if (this.millisecond != null) { str += '.' + String('00' + this.millisecond).slice(-3); } } } } return str; } }, { key: "toStringDateTime", value: function toStringDateTime() { var str = ''; if (this.year != null) { str += this.year; if (this.month != null) { str += '-' + this._pad(this.month); if (this.day != null) { str += '-' + this._pad(this.day); if (this.hour != null) { str += 'T' + this._pad(this.hour); if (this.minute != null) { str += ':' + this._pad(this.minute); if (this.second != null) { str += ':' + this._pad(this.second); if (this.millisecond != null) { str += '.' + String('00' + this.millisecond).slice(-3); } } } } } } } if (str.indexOf('T') !== -1 && this.timezoneOffset != null) { str += this.timezoneOffset < 0 ? '-' : '+'; var offsetHours = Math.floor(Math.abs(this.timezoneOffset)); str += this._pad(offsetHours); var offsetMin = (Math.abs(this.timezoneOffset) - offsetHours) * 60; str += ':' + this._pad(offsetMin); } return str; } }, { key: "getDateTime", value: function getDateTime() { return this; } }, { key: "getDate", value: function getDate() { return new _Date(this.year, this.month, this.day); } }, { key: "getTime", value: function getTime() { // Times no longer have timezoneOffets, so we must explicitly set it to null return new DateTime(0, 1, 1, this.hour, this.minute, this.second, this.millisecond, null); } }, { key: "isTime", value: function isTime() { return this.year === 0 && this.month === 1 && this.day === 1; } }, { key: "_implicitlyConvert", value: function _implicitlyConvert(other) { if (other != null && other.isDate) { return other.getDateTime(); } return other; } }, { key: "reducedPrecision", value: function reducedPrecision() { var unitField = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DateTime.Unit.MILLISECOND; var reduced = this.copy(); if (unitField !== DateTime.Unit.MILLISECOND) { var fieldIndex = DateTime.FIELDS.indexOf(unitField); var fieldsToRemove = DateTime.FIELDS.slice(fieldIndex + 1); var _iterator = _createForOfIteratorHelper(fieldsToRemove), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var field = _step.value; reduced[field] = null; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } return reduced; } }, { key: "isDateTime", get: function get() { return true; } }]); return DateTime; }(); DateTime.Unit = { YEAR: 'year', MONTH: 'month', WEEK: 'week', DAY: 'day', HOUR: 'hour', MINUTE: 'minute', SECOND: 'second', MILLISECOND: 'millisecond' }; DateTime.FIELDS = [DateTime.Unit.YEAR, DateTime.Unit.MONTH, DateTime.Unit.DAY, DateTime.Unit.HOUR, DateTime.Unit.MINUTE, DateTime.Unit.SECOND, DateTime.Unit.MILLISECOND]; var _Date = /*#__PURE__*/function () { _createClass(_Date, null, [{ key: "parse", value: function parse(string) { if (string === null) { return null; } var matches = /(\d{4})(-(\d{2}))?(-(\d{2}))?/.exec(string); if (matches == null) { return null; } var years = matches[1]; var months = matches[3]; var days = matches[5]; if (!isValidDateStringFormat(string)) { return null; } // convert args to integers var args = [years, months, days].map(function (arg) { return arg != null ? parseInt(arg) : arg; }); return _construct(_Date, _toConsumableArray(args)); } }]); function _Date() { var year = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var month = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var day = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; _classCallCheck(this, _Date); this.year = year; this.month = month; this.day = day; } _createClass(_Date, [{ key: "copy", value: function copy() { return new _Date(this.year, this.month, this.day); } }, { key: "successor", value: function successor() { if (this.day != null) { return this.add(1, _Date.Unit.DAY); } else if (this.month != null) { return this.add(1, _Date.Unit.MONTH); } else if (this.year != null) { return this.add(1, _Date.Unit.YEAR); } } }, { key: "predecessor", value: function predecessor() { if (this.day != null) { return this.add(-1, _Date.Unit.DAY); } else if (this.month != null) { return this.add(-1, _Date.Unit.MONTH); } else if (this.year != null) { return this.add(-1, _Date.Unit.YEAR); } } }, { key: "differenceBetween", value: function differenceBetween(other, unitField) { if (other != null && other.isDateTime) { return this.getDateTime().differenceBetween(other, unitField); } if (other == null || !other.isDate) { return null; } // According to CQL spec: // * "Difference calculations are performed by truncating the datetime values at the next precision, // and then performing the corresponding duration calculation on the truncated values." var a = this.toLuxonUncertainty(); var b = other.toLuxonUncertainty(); // Truncate all dates at precision below specified unit a.low = truncateLuxonDateTime(a.low, unitField); a.high = truncateLuxonDateTime(a.high, unitField); b.low = truncateLuxonDateTime(b.low, unitField); b.high = truncateLuxonDateTime(b.high, unitField); // Return the duration based on the normalize and truncated values return new Uncertainty(wholeLuxonDuration(b.low.diff(a.high, unitField), unitField), wholeLuxonDuration(b.high.diff(a.low, unitField), unitField)); } }, { key: "durationBetween", value: function durationBetween(other, unitField) { if (other != null && other.isDateTime) { return this.getDateTime().durationBetween(other, unitField); } if (other == null || !other.isDate) { return null; } var a = this.toLuxonUncertainty(); var b = other.toLuxonUncertainty(); return new Uncertainty(wholeLuxonDuration(b.low.diff(a.high, unitField), unitField), wholeLuxonDuration(b.high.diff(a.low, unitField), unitField)); } }, { key: "getPrecision", value: function getPrecision() { var result = null; if (this.year != null) { result = _Date.Unit.YEAR; } else { return result; } if (this.month != null) { result = _Date.Unit.MONTH; } else { return result; } if (this.day != null) { result = _Date.Unit.DAY; } else { return result; } return result; } }, { key: "toLuxonDateTime", value: function toLuxonDateTime() { return luxon.DateTime.fromObject({ year: this.year, month: this.month, day: this.day, zone: luxon.FixedOffsetZone.utcInstance }); } }, { key: "toLuxonUncertainty", value: function toLuxonUncertainty() { var low = this.toLuxonDateTime(); var high = low.endOf(this.getPrecision()).startOf('day'); // Date type is always at T00:00:00.0 return new Uncertainty(low, high); } }, { key: "toJSDate", value: function toJSDate() { var _ref = [this.year, this.month != null ? this.month - 1 : 0, this.day != null ? this.day : 1], y = _ref[0], mo = _ref[1], d = _ref[2]; return new jsDate(y, mo, d); } }, { key: "toJSON", value: function toJSON() { return this.toString(); } }, { key: "toString", value: function toString() { var str = ''; if (this.year != null) { str += this.year.toString(); if (this.month != null) { str += '-' + this.month.toString().padStart(2, '0'); if (this.day != null) { str += '-' + this.day.toString().padStart(2, '0'); } } } return str; } }, { key: "getDateTime", value: function getDateTime() { // from the spec: the result will be a DateTime with the time components set to zero, // except for the timezone offset, which will be set to the timezone offset of the evaluation // request timestamp. (this last part is acheived by just not passing in timezone offset) if (this.year != null && this.month != null && this.day != null) { return new DateTime(this.year, this.month, this.day, 0, 0, 0, 0); // from spec: no component may be specified at a precision below an unspecified precision. // For example, hour may be null, but if it is, minute, second, and millisecond must all be null as well. } else { return new DateTime(this.year, this.month, this.day); } } }, { key: "reducedPrecision", value: function reducedPrecision() { var unitField = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _Date.Unit.DAY; var reduced = this.copy(); if (unitField !== _Date.Unit.DAY) { var fieldIndex = _Date.FIELDS.indexOf(unitField); var fieldsToRemove = _Date.FIELDS.slice(fieldIndex + 1); var _iterator2 = _createForOfIteratorHelper(fieldsToRemove), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var field = _step2.value; reduced[field] = null; } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } return reduced; } }, { key: "isDate", get: function get() { return true; } }], [{ key: "fromJSDate", value: function fromJSDate(date) { if (date instanceof _Date) { return date; } return new _Date(date.getFullYear(), date.getMonth() + 1, date.getDate()); } }, { key: "fromLuxonDateTime", value: function fromLuxonDateTime(luxonDT) { if (luxonDT instanceof _Date) { return luxonDT; } return new _Date(luxonDT.year, luxonDT.month, luxonDT.day); } }]); return _Date; }(); var MIN_DATETIME_VALUE = DateTime.parse('0001-01-01T00:00:00.000'); var MAX_DATETIME_VALUE = DateTime.parse('9999-12-31T23:59:59.999'); var MIN_DATE_VALUE = _Date.parse('0001-01-01'); var MAX_DATE_VALUE = _Date.parse('9999-12-31'); var MIN_TIME_VALUE = DateTime.parse('0000-01-01T00:00:00.000').getTime(); var MAX_TIME_VALUE = DateTime.parse('0000-01-01T23:59:59.999').getTime(); _Date.Unit = { YEAR: 'year', MONTH: 'month', WEEK: 'week', DAY: 'day' }; _Date.FIELDS = [_Date.Unit.YEAR, _Date.Unit.MONTH, _Date.Unit.DAY]; // Shared Funtions For Date and DateTime DateTime.prototype.isPrecise = _Date.prototype.isPrecise = function () { var _this = this; return this.constructor.FIELDS.every(function (field) { return _this[field] != null; }); }; DateTime.prototype.isImprecise = _Date.prototype.isImprecise = function () { return !this.isPrecise(); }; // This function can take another Date-ish object, or a precision string (e.g. 'month') DateTime.prototype.isMorePrecise = _Date.prototype.isMorePrecise = function (other) { if (typeof other === 'string' && this.constructor.FIELDS.includes(other)) { if (this[other] == null) { return false; } } else { var _iterator3 = _createForOfIteratorHelper(this.constructor.FIELDS), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var field = _step3.value; if (other[field] != null && this[field] == null) { return false; } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } } return !this.isSamePrecision(other); }; // This function can take another Date-ish object, or a precision string (e.g. 'month') DateTime.prototype.isLessPrecise = _Date.prototype.isLessPrecise = function (other) { return !this.isSamePrecision(other) && !this.isMorePrecise(other); }; // This function can take another Date-ish object, or a precision string (e.g. 'month') DateTime.prototype.isSamePrecision = _Date.prototype.isSamePrecision = function (other) { if (typeof other === 'string' && this.constructor.FIELDS.includes(other)) { return other === this.getPrecision(); } var _iterator4 = _createForOfIteratorHelper(this.constructor.FIELDS), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var field = _step4.value; if (this[field] != null && other[field] == null) { return false; } if (this[field] == null && other[field] != null) { return false; } } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } return true; }; DateTime.prototype.equals = _Date.prototype.equals = function (other) { return compareWithDefaultResult(this, other, null); }; DateTime.prototype.equivalent = _Date.prototype.equivalent = function (other) { return compareWithDefaultResult(this, other, false); }; DateTime.prototype.sameAs = _Date.prototype.sameAs = function (other, precision) { if (!(other.isDate || other.isDateTime)) { return null; } else if (this.isDate && other.isDateTime) { return this.getDateTime().sameAs(other, precision); } else if (this.isDateTime && other.isDate) { other = other.getDateTime(); } if (precision != null && this.constructor.FIELDS.indexOf(precision) < 0) { throw new Error("Invalid precision: ".concat(precision)); } // make a copy of other in the correct timezone offset if they don't match. if (this.timezoneOffset !== other.timezoneOffset) { other = other.convertToTimezoneOffset(this.timezoneOffset); } var _iterator5 = _createForOfIteratorHelper(this.constructor.FIELDS), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var field = _step5.value; // if both have this precision defined if (this[field] != null && other[field] != null) { // if they are different then return with false if (this[field] !== other[field]) { return false; } // if both dont have this precision, return true of precision is not defined } else if (this[field] == null && other[field] == null) { if (precision == null) { return true; } else { // we havent met precision yet return null; } // otherwise they have inconclusive precision, return null } else { return null; } // if precision is defined and we have reached expected precision, we can leave the loop if (precision != null && precision === field) { break; } } // if we made it here, then all fields matched. } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } return true; }; DateTime.prototype.sameOrBefore = _Date.prototype.sameOrBefore = function (other, precision) { if (!(other.isDate || other.isDateTime)) { return null; } else if (this.isDate && other.isDateTime) { return this.getDateTime().sameOrBefore(other, precision); } else if (this.isDateTime && other.isDate) { other = other.getDateTime(); } if (precision != null && this.constructor.FIELDS.indexOf(precision) < 0) { throw new Error("Invalid precision: ".concat(precision)); } // make a copy of other in the correct timezone offset if they don't match. if (this.timezoneOffset !== other.timezoneOffset) { other = other.convertToTimezoneOffset(this.timezoneOffset); } var _iterator6 = _createForOfIteratorHelper(this.constructor.FIELDS), _step6; try { for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { var field = _step6.value; // if both have this precision defined if (this[field] != null && other[field] != null) { // if this value is less than the other return with true. this is before other if (this[field] < other[field]) { return true; // if this value is greater than the other return with false. this is after } else if (this[field] > other[field]) { return false; } // execution continues if the values are the same // if both dont have this precision, return true if precision is not defined } else if (this[field] == null && other[field] == null) { if (precision == null) { return true; } else { // we havent met precision yet return null; } // otherwise they have inconclusive precision, return null } else { return null; } // if precision is defined and we have reached expected precision, we can leave the loop if (precision != null && precision === field) { break; } } // if we made it here, then all fields matched and they are same } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } return true; }; DateTime.prototype.sameOrAfter = _Date.prototype.sameOrAfter = function (other, precision) { if (!(other.isDate || other.isDateTime)) { return null; } else if (this.isDate && other.isDateTime) { return this.getDateTime().sameOrAfter(other, precision); } else if (this.isDateTime && other.isDate) { other = other.getDateTime(); } if (precision != null && this.constructor.FIELDS.indexOf(precision) < 0) { throw new Error("Invalid precision: ".concat(precision)); } // make a copy of other in the correct timezone offset if they don't match. if (this.timezoneOffset !== other.timezoneOffset) { other = other.convertToTimezoneOffset(this.timezoneOffset); } var _iterator7 = _createForOfIteratorHelper(this.constructor.FIELDS), _step7; try { for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) { var field = _step7.value; // if both have this precision defined if (this[field] != null && other[field] != null) { // if this value is greater than the other return with true. this is after other if (this[field] > other[field]) { return true; // if this value is greater than the other return with false. this is before } else if (this[field] < other[field]) { return false; } // execution continues if the values are the same // if both dont have this precision, return true if precision is not defined } else if (this[field] == null && other[field] == null) { if (precision == null) { return true; } else { // we havent met precision yet return null; } // otherwise they have inconclusive precision, return null } else { return null; } // if precision is defined and we have reached expected precision, we can leave the loop if (precision != null && precision === field) { break; } } // if we made it here, then all fields matched and they are same } catch (err) { _iterator7.e(err); } finally { _iterator7.f(); } return true; }; DateTime.prototype.before = _Date.prototype.before = function (other, precision) { if (!(other.isDate || other.isDateTime)) { return null; } else if (this.isDate && other.isDateTime) { return this.getDateTime().before(other, precision); } else if (this.isDateTime && other.isDate) { other = other.getDateTime(); } if (precision != null && this.constructor.FIELDS.indexOf(precision) < 0) { throw new Error("Invalid precision: ".concat(precision)); } // make a copy of other in the correct timezone offset if they don't match. if (this.timezoneOffset !== other.timezoneOffset) { other = other.convertToTimezoneOffset(this.timezoneOffset); } var _iterator8 = _createForOfIteratorHelper(this.constructor.FIELDS), _step8; try { for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) { var field = _step8.value; // if both have this precision defined if (this[field] != null && other[field] != null) { // if this value is less than the other return with true. this is before other if (this[field] < other[field]) { return true; // if this value is greater than the other return with false. this is after } else if (this[field] > other[field]) { return false; } // execution continues if the values are the same // if both dont have this precision, return false if precision is not defined } else if (this[field] == null && other[field] == null) { if (precision == null) { return false; } else { // we havent met precision yet return null; } // otherwise they have inconclusive precision, return null } else { return null; } // if precision is defined and we have reached expected precision, we can leave the loop if (precision != null && precision === field) { break; } } // if we made it here, then all fields matched and they are same } catch (err) { _iterator8.e(err); } finally { _iterator8.f(); } return false; }; DateTime.prototype.after = _Date.prototype.after = function (other, precision) { if (!(other.isDate || other.isDateTime)) { return null; } else if (this.isDate && other.isDateTime) { return this.getDateTime().after(other, precision); } else if (this.isDateTime && other.isDate) { other = other.getDateTime(); } if (precision != null && this.constructor.FIELDS.indexOf(precision) < 0) { throw new Error("Invalid precision: ".concat(precision)); } // make a copy of other in the correct timezone offset if they don't match. if (this.timezoneOffset !== other.timezoneOffset) { other = other.convertToTimezoneOffset(this.timezoneOffset); } var _iterator9 = _createForOfIteratorHelper(this.constructor.FIELDS), _step9; try { for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) { var field = _step9.value; // if both have this precision defined if (this[field] != null && other[field] != null) { // if this value is greater than the other return with true. this is after other if (this[field] > other[field]) { return true; // if this value is greater than the other return with false. this is before } else if (this[field] < other[field]) { return false; } // execution continues if the values are the same // if both dont have this precision, return false if precision is not defined } else if (this[field] == null && other[field] == null) { if (precision == null) { return false; } else { // we havent met precision yet return null; } // otherwise they have inconclusive precision, return null } else { return null; } // if precision is defined and we have reached expected precision, we can leave the loop if (precision != null && precision === field) { break; } } // if we made it here, then all fields matched and they are same } catch (err) { _iterator9.e(err); } finally { _iterator9.f(); } return false; }; DateTime.prototype.add = _Date.prototype.add = function (offset, field) { if (offset === 0 || this.year == null) { return this.copy(); } // Use luxon to do the date math because it honors DST and it has the leap-year/end-of-month semantics we want. // NOTE: The luxonDateTime will contain default values where this[unit] is null, but we'll account for that. var luxonDateTime = this.toLuxonDateTime(); // From the spec: "The operation is performed by converting the time-based quantity to the most precise value // specified in the date/time (truncating any resulting decimal portion) and then adding it to the date/time value." // However, since you can't really convert days to months, if "this" is less precise than the field being added, we can // add to the earliest possible value of "this" or subtract from the latest possible value of "this" (depending on the // sign of the offset), and then null out the imprecise fields again after doing the calculation. Due to the way // luxonDateTime is constructed above, it is already at the earliest value, so only adjust if the offset is negative. var offsetIsMorePrecise = this[field] == null; //whether the quantity we are adding is more precise than "this". if (offsetIsMorePrecise && offset < 0) { luxonDateTime = luxonDateTime.endOf(this.getPrecision()); } // Now do the actual math and convert it back to a Date/DateTime w/ originally null fields nulled out again var luxonResult = luxonDateTime.plus(_defineProperty({}, field, offset)); var result = this.constructor.fromLuxonDateTime(luxonResult).reducedPrecision(this.getPrecision()); // Luxon never has a null offset, but sometimes "this" does, so reset to null if applicable if (this.isDateTime && this.timezoneOffset == null) { result.timezoneOffset = null; } // Can't use overflowsOrUnderflows from math.js due to circular dependencies when we require it if (result.after(MAX_DATETIME_VALUE || result.before(MIN_DATETIME_VALUE))) { return null; } else { return result; } }; DateTime.prototype.getFieldFloor = _Date.prototype.getFieldFloor = function (field) { switch (field) { case 'month': return 1; case 'day': return 1; case 'hour': return 0; case 'minute': return 0; case 'second': return 0; case 'millisecond': return 0; default: throw new Error('Tried to floor a field that has no floor value: ' + field); } }; DateTime.prototype.getFieldCieling = _Date.prototype.getFieldCieling = function (field) { switch (field) { case 'month': return 12; case 'day': return daysInMonth(this.year, this.month); case 'hour': return 23; case 'minute': return 59; case 'second': return 59; case 'millisecond': return 999; default: throw new Error('Tried to clieling a field that has no cieling value: ' + field); } }; function compareWithDefaultResult(a, b, defaultResult) { // return false there is a type mismatch if ((!a.isDate || !b.isDate) && (!a.isDateTime || !b.isDateTime)) { return false; } // make a copy of other in the correct timezone offset if they don't match. if (a.timezoneOffset !== b.timezoneOffset) { b = b.convertToTimezoneOffset(a.timezoneOffset); } var _iterator10 = _createForOfIteratorHelper(a.constructor.FIELDS), _step10; try { for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) { var field = _step10.value; // if both have this precision defined if (a[field] != null && b[field] != null) { // For the purposes of comparison, seconds and milliseconds are combined // as a single precision using a decimal, with decimal equality semantics if (field === 'second') { // NOTE: if millisecond is null it will calcualte like this anyway, but // if millisecond is undefined, using it will result in NaN calculations var aMillisecond = a['millisecond'] != null ? a['millisecond'] : 0; var aSecondAndMillisecond = a[field] + aMillisecond / 1000; var bMillisecond = b['millisecond'] != null ? b['millisecond'] : 0; var bSecondAndMillisecond = b[field] + bMillisecond / 1000; // second/millisecond is the most precise comparison, so we can directly return return aSecondAndMillisecond === bSecondAndMillisecond; } // if they are different then return with false if (a[field] !== b[field]) { return false; } // if both dont have this precision, return true } else if (a[field] == null && b[field] == null) { return true; // otherwise they have inconclusive precision, return defaultResult } else { return defaultResult; } } // if we made it here, then all fields matched. } catch (err) { _iterator10.e(err); } finally { _iterator10.f(); } return true; } function daysInMonth(year, month) { if (year == null || month == null) { throw new Error('daysInMonth requires year and month as arguments'); } // Month is 1-indexed here because of the 0 day return new jsDate(year, month, 0).getDate(); } function isValidDateStringFormat(string) { if (typeof string !== 'string') { return false; } var format = LENGTH_TO_DATE_FORMAT_MAP.get(string.length); if (format == null) { return false; } return luxon.DateTime.fromFormat(string, format).isValid; } function isValidDateTimeStringFormat(string) { if (typeof string !== 'string') { return false; } // Luxon doesn't support +hh offset, so change it to +hh:00 if (/T[\d:.]*[+-]\d{2}$/.test(string)) { string += ':00'; } var formats = LENGTH_TO_DATETIME_FORMATS_MAP.get(string.length); if (formats == null) { return false; } return formats.some(function (fmt) { return luxon.DateTime.fromFormat(string, fmt).isValid; }); } module.exports = { DateTime: DateTime, Date: _Date, MIN_DATETIME_VALUE: MIN_DATETIME_VALUE, MAX_DATETIME_VALUE: MAX_DATETIME_VALUE, MIN_DATE_VALUE: MIN_DATE_VALUE, MAX_DATE_VALUE: MAX_DATE_VALUE, MIN_TIME_VALUE: MIN_TIME_VALUE, MAX_TIME_VALUE: MAX_TIME_VALUE }; // Require MIN/MAX here because math.js requires this file, and when we make this file require // math.js before it exports DateTime and Date, it errors due to the circular dependency... // const { MAX_DATETIME_VALUE, MIN_DATETIME_VALUE } = require('../util/math'); },{"../util/util":176,"./uncertainty":141,"luxon":183}],136:[function(require,module,exports){ "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Exception = function Exception(message, wrapped) { _classCallCheck(this, Exception); this.message = message; this.wrapped = wrapped; }; module.exports = { Exception: Exception }; },{}],137:[function(require,module,exports){ "use strict"; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; 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 _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 = require('./uncertainty'), Uncertainty = _require.Uncertainty; var _require2 = require('../datatypes/quantity'), Quantity = _require2.Quantity, doSubtraction = _require2.doSubtraction; var _require3 = require('./logic'), ThreeValuedLogic = _require3.ThreeValuedLogic; var _require4 = require('../util/math'), successor = _require4.successor, predecessor = _require4.predecessor, maxValueForInstance = _require4.maxValueForInstance, minValueForInstance = _require4.minValueForInstance, maxValueForType = _require4.maxValueForType, minValueForType = _require4.minValueForType; var cmp = require('../util/comparison'); var Interval = /*#__PURE__*/function () { function Interval(low, high, lowClosed, highClosed, defaultPointType) { _classCallCheck(this, Interval); this.low = low; this.high = high; this.lowClosed = lowClosed != null ? lowClosed : true; this.highClosed = highClosed != null ? highClosed : true; // defaultPointType is used in the case that both endpoints are null this.defaultPointType = defaultPointType; } _createClass(Interval, [{ key: "copy", value: function copy() { var newLow = this.low; var newHigh = this.high; if (this.low != null && typeof this.low.copy === 'function') { newLow = this.low.copy(); } if (this.high != null && typeof this.high.copy === 'function') { newHigh = this.high.copy(); } return new Interval(newLow, newHigh, this.lowClosed, this.highClosed); } }, { key: "contains", value: function contains(item, precision) { // These first two checks ensure correct handling of edge case where an item equals the closed boundary if (this.lowClosed && this.low != null && cmp.equals(this.low, item)) { return true; } if (this.highClosed && this.high != null && cmp.equals(this.high, item)) { return true; } if (item != null && item.isInterval) { throw new Error('Argument to contains must be a point'); } var lowFn; if (this.lowClosed && this.low == null) { lowFn = function lowFn() { return true; }; } else if (this.lowClosed) { lowFn = cmp.lessThanOrEquals; } else { lowFn = cmp.lessThan; } var highFn; if (this.highClosed && this.high == null) { highFn = function highFn() { return true; }; } else if (this.highClosed) { highFn = cmp.greaterThanOrEquals; } else { highFn = cmp.greaterThan; } return ThreeValuedLogic.and(lowFn(this.low, item, precision), highFn(this.high, item, precision)); } }, { key: "properlyIncludes", value: function properlyIncludes(other, precision) { if (other == null || !other.isInterval) { throw new Error('Argument to properlyIncludes must be an interval'); } return ThreeValuedLogic.and(this.includes(other, precision), ThreeValuedLogic.not(other.includes(this, precision))); } }, { key: "includes", value: function includes(other, precision) { if (other == null || !other.isInterval) { return this.contains(other, precision); } var a = this.toClosed(); var b = other.toClosed(); return ThreeValuedLogic.and(cmp.lessThanOrEquals(a.low, b.low, precision), cmp.greaterThanOrEquals(a.high, b.high, precision)); } }, { key: "includedIn", value: function includedIn(other, precision) { // For the point overload, this operator is a synonym for the in operator if (other == null || !other.isInterval) { return this.contains(other, precision); } else { return other.includes(this); } } }, { key: "overlaps", value: function overlaps(item, precision) { var closed = this.toClosed(); var _ref = function () { if (item != null && item.isInterval) { var itemClosed = item.toClosed(); return [itemClosed.low, itemClosed.high]; } else { return [item, item]; } }(), _ref2 = _slicedToArray(_ref, 2), low = _ref2[0], high = _ref2[1]; return ThreeValuedLogic.and(cmp.lessThanOrEquals(closed.low, high, precision), cmp.greaterThanOrEquals(closed.high, low, precision)); } }, { key: "overlapsAfter", value: function overlapsAfter(item, precision) { var closed = this.toClosed(); var high = item != null && item.isInterval ? item.toClosed().high : item; return ThreeValuedLogic.and(cmp.lessThanOrEquals(closed.low, high, precision), cmp.greaterThan(closed.high, high, precision)); } }, { key: "overlapsBefore", value: function overlapsBefore(item, precision) { var closed = this.toClosed(); var low = item != null && item.isInterval ? item.toClosed().low : item; return ThreeValuedLogic.and(cmp.lessThan(closed.low, low, precision), cmp.greaterThanOrEquals(closed.high, low, precision)); } }, { key: "union", value: function union(other) { if (other == null || !other.isInterval) { throw new Error('Argument to union must be an interval'); } // Note that interval union is only defined if the arguments overlap or meet. if (this.overlaps(other) || this.meets(other)) { var _ref3 = [this.toClosed(), other.toClosed()], a = _ref3[0], b = _ref3[1]; var l, lc; if (cmp.lessThanOrEquals(a.low, b.low)) { var _ref4 = [this.low, this.lowClosed]; l = _ref4[0]; lc = _ref4[1]; } else if (cmp.greaterThanOrEquals(a.low, b.low)) { var _ref5 = [other.low, other.lowClosed]; l = _ref5[0]; lc = _ref5[1]; } else if (areNumeric(a.low, b.low)) { var _ref6 = [lowestNumericUncertainty(a.low, b.low), true]; l = _ref6[0]; lc = _ref6[1]; } else if (areDateTimes(a.low, b.low) && a.low.isMorePrecise(b.low)) { var _ref7 = [other.low, other.lowClosed]; l = _ref7[0]; lc = _ref7[1]; } else { var _ref8 = [this.low, this.lowClosed]; l = _ref8[0]; lc = _ref8[1]; } var h, hc; if (cmp.greaterThanOrEquals(a.high, b.high)) { var _ref9 = [this.high, this.highClosed]; h = _ref9[0]; hc = _ref9[1]; } else if (cmp.lessThanOrEquals(a.high, b.high)) { var _ref10 = [other.high, other.highClosed]; h = _ref10[0]; hc = _ref10[1]; } else if (areNumeric(a.high, b.high)) { var _ref11 = [highestNumericUncertainty(a.high, b.high), true]; h = _ref11[0]; hc = _ref11[1]; } else if (areDateTimes(a.high, b.high) && a.high.isMorePrecise(b.high)) { var _ref12 = [other.high, other.highClosed]; h = _ref12[0]; hc = _ref12[1]; } else { var _ref13 = [this.high, this.highClosed]; h = _ref13[0]; hc = _ref13[1]; } return new Interval(l, h, lc, hc); } else { return null; } } }, { key: "intersect", value: function intersect(other) { if (other == null || !other.isInterval) { throw new Error('Argument to union must be an interval'); } // Note that interval union is only defined if the arguments overlap. if (this.overlaps(other)) { var _ref14 = [this.toClosed(), other.toClosed()], a = _ref14[0], b = _ref14[1]; var l, lc; if (cmp.greaterThanOrEquals(a.low, b.low)) { var _ref15 = [this.low, this.lowClosed]; l = _ref15[0]; lc = _ref15[1]; } else if (cmp.lessThanOrEquals(a.low, b.low)) { var _ref16 = [other.low, other.lowClosed]; l = _ref16[0]; lc = _ref16[1]; } else if (areNumeric(a.low, b.low)) { var _ref17 = [highestNumericUncertainty(a.low, b.low), true]; l = _ref17[0]; lc = _ref17[1]; } else if (areDateTimes(a.low, b.low) && b.low.isMorePrecise(a.low)) { var _ref18 = [other.low, other.lowClosed]; l = _ref18[0]; lc = _ref18[1]; } else { var _ref19 = [this.low, this.lowClosed]; l = _ref19[0]; lc = _ref19[1]; } var h, hc; if (cmp.lessThanOrEquals(a.high, b.high)) { var _ref20 = [this.high, this.highClosed]; h = _ref20[0]; hc = _ref20[1]; } else if (cmp.greaterThanOrEquals(a.high, b.high)) { var _ref21 = [other.high, other.highClosed]; h = _ref21[0]; hc = _ref21[1]; } else if (areNumeric(a.high, b.high)) { var _ref22 = [lowestNumericUncertainty(a.high, b.high), true]; h = _ref22[0]; hc = _ref22[1]; } else if (areDateTimes(a.high, b.high) && b.high.isMorePrecise(a.high)) { var _ref23 = [other.high, other.highClosed]; h = _ref23[0]; hc = _ref23[1]; } else { var _ref24 = [this.high, this.highClosed]; h = _ref24[0]; hc = _ref24[1]; } return new Interval(l, h, lc, hc); } else { return null; } } }, { key: "except", value: function except(other) { if (other === null) { return null; } if (other == null || !other.isInterval) { throw new Error('Argument to except must be an interval'); } var ol = this.overlaps(other); if (ol === true) { var olb = this.overlapsBefore(other); var ola = this.overlapsAfter(other); if (olb === true && ola === false) { return new Interval(this.low, other.low, this.lowClosed, !other.lowClosed); } else if (ola === true && olb === false) { return new Interval(other.high, this.high, !other.highClosed, this.highClosed); } else { return null; } } else if (ol === false) { return this; } else { // ol is null return null; } } }, { key: "sameAs", value: function sameAs(other, precision) { // This large if and else if block handles the scenarios where there is an open ended null // If both lows or highs exists, it can be determined that intervals are not Same As if (this.low != null && other.low != null && this.high == null && other.high != null && !this.highClosed || this.low != null && other.low != null && this.high != null && other.high == null && !other.highClosed || this.low != null && other.low != null && this.high == null && other.high == null && !other.highClosed && !this.highClosed) { if (typeof this.low === 'number') { if (!(this.start() === other.start())) { return false; } } else { if (!this.start().sameAs(other.start(), precision)) { return false; } } } else if (this.low != null && other.low == null && this.high != null && other.high != null || this.low == null && other.low != null && this.high != null && other.high != null || this.low == null && other.low == null && this.high != null && other.high != null) { if (typeof this.high === 'number') { if (!(this.end() === other.end())) { return false; } } else { if (!this.end().sameAs(other.end(), precision)) { return false; } } } // Checks to see if any of the Intervals have a open, null boundary if (this.low == null && !this.lowClosed || this.high == null && !this.highClosed || other.low == null && !other.lowClosed || other.high == null && !other.highClosed) { return null; } // For the special cases where @ is Interval[null,null] if (this.lowClosed && this.low == null && this.highClosed && this.high == null) { return other.lowClosed && other.low == null && other.highClosed && other.high == null; } // For the special case where Interval[...] same as Interval[null,null] should return false. // This accounts for the inverse of the if statement above: where the second Interval is // [null,null] and not the first Interval. // The reason why this isn't caught below is due to how start() and end() work. // There is no way to tell the datatype for MIN and MAX if both boundaries are null. if (other.lowClosed && other.low == null && other.highClosed && other.high == null) { return false; } if (typeof this.low === 'number') { return this.start() === other.start() && this.end() === other.end(); } else { return this.start().sameAs(other.start(), precision) && this.end().sameAs(other.end(), precision); } } }, { key: "sameOrBefore", value: function sameOrBefore(other, precision) { if (this.end() == null || other == null || other.start() == null) { return null; } else { return cmp.lessThanOrEquals(this.end(), other.start(), precision); } } }, { key: "sameOrAfter", value: function sameOrAfter(other, precision) { if (this.start() == null || other == null || other.end() == null) { return null; } else { return cmp.greaterThanOrEquals(this.start(), other.end(), precision); } } }, { key: "equals", value: function equals(other) { if (other != null && other.isInterval) { var _ref25 = [this.toClosed(), other.toClosed()], a = _ref25[0], b = _ref25[1]; return ThreeValuedLogic.and(cmp.equals(a.low, b.low), cmp.equals(a.high, b.high)); } else { return false; } } }, { key: "after", value: function after(other, precision) { var closed = this.toClosed(); // Meets spec, but not 100% correct (e.g., (null, 5] after [6, 10] --> null) // Simple way to fix it: and w/ not overlaps if (other.toClosed) { return cmp.greaterThan(closed.low, other.toClosed().high, precision); } else { return cmp.greaterThan(closed.low, other, precision); } } }, { key: "before", value: function before(other, precision) { var closed = this.toClosed(); // Meets spec, but not 100% correct (e.g., (null, 5] after [6, 10] --> null) // Simple way to fix it: and w/ not overlaps if (other.toClosed) { return cmp.lessThan(closed.high, other.toClosed().low, precision); } else { return cmp.lessThan(closed.high, other, precision); } } }, { key: "meets", value: function meets(other, precision) { return ThreeValuedLogic.or(this.meetsBefore(other, precision), this.meetsAfter(other, precision)); } }, { key: "meetsAfter", value: function meetsAfter(other, precision) { try { if (precision != null && this.low != null && this.low.isDateTime) { return this.toClosed().low.sameAs(other.toClosed().high != null ? other.toClosed().high.add(1, precision) : null, precision); } else { return cmp.equals(this.toClosed().low, successor(other.toClosed().high)); } } catch (error) { return false; } } }, { key: "meetsBefore", value: function meetsBefore(other, precision) { try { if (precision != null && this.high != null && this.high.isDateTime) { return this.toClosed().high.sameAs(other.toClosed().low != null ? other.toClosed().low.add(-1, precision) : null, precision); } else { return cmp.equals(this.toClosed().high, predecessor(other.toClosed().low)); } } catch (error) { return false; } } }, { key: "start", value: function start() { if (this.low == null) { if (this.lowClosed) { return minValueForInstance(this.high); } else { return this.low; } } return this.toClosed().low; } }, { key: "end", value: function end() { if (this.high == null) { if (this.highClosed) { return maxValueForInstance(this.low); } else { return this.high; } } return this.toClosed().high; } }, { key: "starts", value: function starts(other, precision) { var startEqual; if (precision != null && this.low != null && this.low.isDateTime) { startEqual = this.low.sameAs(other.low, precision); } else { startEqual = cmp.equals(this.low, other.low); } var endLessThanOrEqual = cmp.lessThanOrEquals(this.high, other.high, precision); return startEqual && endLessThanOrEqual; } }, { key: "ends", value: function ends(other, precision) { var endEqual; var startGreaterThanOrEqual = cmp.greaterThanOrEquals(this.low, other.low, precision); if (precision != null && (this.low != null ? this.low.isDateTime : undefined)) { endEqual = this.high.sameAs(other.high, precision); } else { endEqual = cmp.equals(this.high, other.high); } return startGreaterThanOrEqual && endEqual; } }, { key: "width", value: function width() { if (this.low != null && (this.low.isDateTime || this.low.isDate) || this.high != null && (this.high.isDateTime || this.high.isDate)) { throw new Error('Width of Date, DateTime, and Time intervals is not supported'); } var closed = this.toClosed(); if (closed.low != null && closed.low.isUncertainty || closed.high != null && closed.high.isUncertainty) { return null; } else if (closed.low.isQuantity) { if (closed.low.unit !== closed.high.unit) { throw new Error('Cannot calculate width of Quantity Interval with different units'); } var lowValue = closed.low.value; var highValue = closed.high.value; var diff = Math.abs(highValue - lowValue); diff = Math.round(diff * Math.pow(10, 8)) / Math.pow(10, 8); return new Quantity(diff, closed.low.unit); } else { // TODO: Fix precision to 8 decimals in other places that return numbers var _diff = Math.abs(closed.high - closed.low); return Math.round(_diff * Math.pow(10, 8)) / Math.pow(10, 8); } } }, { key: "size", value: function size() { var pointSize = this.getPointSize(); if (this.low != null && (this.low.isDateTime || this.low.isDate) || this.high != null && (this.high.isDateTime || this.high.isDate)) { throw new Error('Size of Date, DateTime, and Time intervals is not supported'); } var closed = this.toClosed(); if (closed.low != null && closed.low.isUncertainty || closed.high != null && closed.high.isUncertainty) { return null; } else if (closed.low.isQuantity) { if (closed.low.unit !== closed.high.unit) { throw new Error('Cannot calculate size of Quantity Interval with different units'); } var lowValue = closed.low.value; var highValue = closed.high.value; var diff = Math.abs(highValue - lowValue) + pointSize.value; Math.round(diff * Math.pow(10, 8)) / Math.pow(10, 8); return new Quantity(diff, closed.low.unit); } else { var _diff2 = Math.abs(closed.high - closed.low) + pointSize.value; return Math.round(_diff2 * Math.pow(10, 8)) / Math.pow(10, 8); } } }, { key: "getPointSize", value: function getPointSize() { var pointSize; if (this.low != null) { if (this.low.isDateTime) { pointSize = new Quantity(1, this.low.getPrecision()); } else if (this.low.isQuantity) { pointSize = doSubtraction(successor(this.low), this.low); } else { pointSize = successor(this.low) - this.low; } } else if (this.high != null) { if (this.high.isDateTime) { pointSize = new Quantity(1, this.high.getPrecision()); } else if (this.high.isQuantity) { pointSize = doSubtraction(successor(this.high), this.high); } else { pointSize = successor(this.high) - this.high; } } else { throw new Error('Point type of intervals cannot be determined.'); } if (typeof pointSize === 'number') { pointSize = new Quantity(pointSize, '1'); } return pointSize; } }, { key: "toClosed", value: function toClosed() { // Calculate the closed flags. Despite the name of this function, if a boundary is null open, // we cannot close the boundary because that changes its meaning from "unknown" to "max/min value" var lowClosed = this.lowClosed || this.low != null; var highClosed = this.highClosed || this.high != null; if (this.pointType != null) { var low; if (this.lowClosed && this.low == null) { low = minValueForType(this.pointType); } else if (!this.lowClosed && this.low != null) { low = successor(this.low); } else { low = this.low; } var high; if (this.highClosed && this.high == null) { high = maxValueForType(this.pointType); } else if (!this.highClosed && this.high != null) { high = predecessor(this.high); } else { high = this.high; } if (low == null) { low = new Uncertainty(minValueForType(this.pointType), high); } if (high == null) { high = new Uncertainty(low, maxValueForType(this.pointType)); } return new Interval(low, high, lowClosed, highClosed); } else { return new Interval(this.low, this.high, lowClosed, highClosed); } } }, { key: "toString", value: function toString() { var start = this.lowClosed ? '[' : '('; var end = this.highClosed ? ']' : ')'; return start + this.low.toString() + ', ' + this.high.toString() + end; } }, { key: "isInterval", get: function get() { return true; } }, { key: "pointType", get: function get() { var pointType = null; var point = this.low != null ? this.low : this.high; if (point != null) { if (typeof point === 'number') { pointType = parseInt(point) === point ? '{urn:hl7-org:elm-types:r1}Integer' : '{urn:hl7-org:elm-types:r1}Decimal'; } else if (point.isTime && point.isTime()) { pointType = '{urn:hl7-org:elm-types:r1}Time'; } else if (point.isDate) { pointType = '{urn:hl7-org:elm-types:r1}Date'; } else if (point.isDateTime) { pointType = '{urn:hl7-org:elm-types:r1}DateTime'; } else if (point.isQuantity) { pointType = '{urn:hl7-org:elm-types:r1}Quantity'; } } if (pointType == null && this.defaultPointType != null) { pointType = this.defaultPointType; } return pointType; } }]); return Interval; }(); function areDateTimes(x, y) { return [x, y].every(function (z) { return z != null && z.isDateTime; }); } function areNumeric(x, y) { return [x, y].every(function (z) { return typeof z === 'number' || z != null && z.isUncertainty && typeof z.low === 'number'; }); } function lowestNumericUncertainty(x, y) { if (x == null || !x.isUncertainty) { x = new Uncertainty(x); } if (y == null || !y.isUncertainty) { y = new Uncertainty(y); } var low = x.low < y.low ? x.low : y.low; var high = x.high < y.high ? x.high : y.high; if (low !== high) { return new Uncertainty(low, high); } else { return low; } } function highestNumericUncertainty(x, y) { if (x == null || !x.isUncertainty) { x = new Uncertainty(x); } if (y == null || !y.isUncertainty) { y = new Uncertainty(y); } var low = x.low > y.low ? x.low : y.low; var high = x.high > y.high ? x.high : y.high; if (low !== high) { return new Uncertainty(low, high); } else { return low; } } module.exports = { Interval: Interval }; },{"../datatypes/quantity":139,"../util/comparison":173,"../util/math":174,"./logic":138,"./uncertainty":141}],138:[function(require,module,exports){ "use strict"; 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 ThreeValuedLogic = /*#__PURE__*/function () { function ThreeValuedLogic() { _classCallCheck(this, ThreeValuedLogic); } _createClass(ThreeValuedLogic, null, [{ key: "and", value: function and() { for (var _len = arguments.length, val = new Array(_len), _key = 0; _key < _len; _key++) { val[_key] = arguments[_key]; } if (val.includes(false)) { return false; } else if (val.includes(null)) { return null; } else { return true; } } }, { key: "or", value: function or() { for (var _len2 = arguments.length, val = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { val[_key2] = arguments[_key2]; } if (val.includes(true)) { return true; } else if (val.includes(null)) { return null; } else { return false; } } }, { key: "xor", value: function xor() { for (var _len3 = arguments.length, val = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { val[_key3] = arguments[_key3]; } if (val.includes(null)) { return null; } else { return val.reduce(function (a, b) { return (!a ^ !b) === 1; }); } } }, { key: "not", value: function not(val) { if (val != null) { return !val; } else { return null; } } }]); return ThreeValuedLogic; }(); module.exports = { ThreeValuedLogic: ThreeValuedLogic }; },{}],139:[function(require,module,exports){ "use strict"; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; 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 _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 = require('../util/math'), decimalAdjust = _require.decimalAdjust, isValidDecimal = _require.isValidDecimal, overflowsOrUnderflows = _require.overflowsOrUnderflows; var _require2 = require('../util/units'), checkUnit = _require2.checkUnit, _convertUnit = _require2.convertUnit, normalizeUnitsWhenPossible = _require2.normalizeUnitsWhenPossible, convertToCQLDateUnit = _require2.convertToCQLDateUnit, getProductOfUnits = _require2.getProductOfUnits, getQuotientOfUnits = _require2.getQuotientOfUnits; var Quantity = /*#__PURE__*/function () { function Quantity(value, unit) { _classCallCheck(this, Quantity); this.value = value; this.unit = unit; if (this.value == null || isNaN(this.value)) { throw new Error('Cannot create a quantity with an undefined value'); } else if (!isValidDecimal(this.value)) { throw new Error('Cannot create a quantity with an invalid decimal value'); } // Attempt to parse the unit with UCUM. If it fails, throw a friendly error. if (this.unit != null) { var validation = checkUnit(this.unit); if (!validation.valid) { throw new Error(validation.message); } } } _createClass(Quantity, [{ key: "clone", value: function clone() { return new Quantity(this.value, this.unit); } }, { key: "toString", value: function toString() { return "".concat(this.value, " '").concat(this.unit, "'"); } }, { key: "sameOrBefore", value: function sameOrBefore(other) { if (other != null && other.isQuantity) { var otherVal = _convertUnit(other.value, other.unit, this.unit); if (otherVal == null) { return null; } else { return this.value <= otherVal; } } } }, { key: "sameOrAfter", value: function sameOrAfter(other) { if (other != null && other.isQuantity) { var otherVal = _convertUnit(other.value, other.unit, this.unit); if (otherVal == null) { return null; } else { return this.value >= otherVal; } } } }, { key: "after", value: function after(other) { if (other != null && other.isQuantity) { var otherVal = _convertUnit(other.value, other.unit, this.unit); if (otherVal == null) { return null; } else { return this.value > otherVal; } } } }, { key: "before", value: function before(other) { if (other != null && other.isQuantity) { var otherVal = _convertUnit(other.value, other.unit, this.unit); if (otherVal == null) { return null; } else { return this.value < otherVal; } } } }, { key: "equals", value: function equals(other) { if (other != null && other.isQuantity) { if (!this.unit && other.unit || this.unit && !other.unit) { return false; } else if (!this.unit && !other.unit) { return this.value === other.value; } else { var otherVal = _convertUnit(other.value, other.unit, this.unit); if (otherVal == null) { return null; } else { return decimalAdjust('round', this.value, -8) === otherVal; } } } } }, { key: "convertUnit", value: function convertUnit(toUnit) { var value = _convertUnit(this.value, this.unit, toUnit); // Need to pass through constructor again to catch invalid units return new Quantity(value, toUnit); } }, { key: "dividedBy", value: function dividedBy(other) { if (other == null || other === 0 || other.value === 0) { return null; } else if (!other.isQuantity) { // convert it to a quantity w/ unit 1 other = new Quantity(other, '1'); } var _normalizeUnitsWhenPo = normalizeUnitsWhenPossible(this.value, this.unit, other.value, other.unit), _normalizeUnitsWhenPo2 = _slicedToArray(_normalizeUnitsWhenPo, 4), val1 = _normalizeUnitsWhenPo2[0], unit1 = _normalizeUnitsWhenPo2[1], val2 = _normalizeUnitsWhenPo2[2], unit2 = _normalizeUnitsWhenPo2[3]; var resultValue = val1 / val2; var resultUnit = getQuotientOfUnits(unit1, unit2); // Check for invalid unit or value if (resultUnit == null || overflowsOrUnderflows(resultValue)) { return null; } return new Quantity(decimalAdjust('round', resultValue, -8), resultUnit); } }, { key: "multiplyBy", value: function multiplyBy(other) { if (other == null) { return null; } else if (!other.isQuantity) { // convert it to a quantity w/ unit 1 other = new Quantity(other, '1'); } var _normalizeUnitsWhenPo3 = normalizeUnitsWhenPossible(this.value, this.unit, other.value, other.unit), _normalizeUnitsWhenPo4 = _slicedToArray(_normalizeUnitsWhenPo3, 4), val1 = _normalizeUnitsWhenPo4[0], unit1 = _normalizeUnitsWhenPo4[1], val2 = _normalizeUnitsWhenPo4[2], unit2 = _normalizeUnitsWhenPo4[3]; var resultValue = val1 * val2; var resultUnit = getProductOfUnits(unit1, unit2); // Check for invalid unit or value if (resultUnit == null || overflowsOrUnderflows(resultValue)) { return null; } return new Quantity(decimalAdjust('round', resultValue, -8), resultUnit); } }, { key: "isQuantity", get: function get() { return true; } }]); return Quantity; }(); function parseQuantity(str) { var components = /([+|-]?\d+\.?\d*)\s*('(.+)')?/.exec(str); if (components != null && components[1] != null) { var value = parseFloat(components[1]); if (!isValidDecimal(value)) { return null; } var unit; if (components[3] != null) { unit = components[3].trim(); } else { unit = ''; } return new Quantity(value, unit); } else { return null; } } function doScaledAddition(a, b, scaleForB) { if (a != null && a.isQuantity && b != null && b.isQuantity) { var _normalizeUnitsWhenPo5 = normalizeUnitsWhenPossible(a.value, a.unit, b.value * scaleForB, b.unit), _normalizeUnitsWhenPo6 = _slicedToArray(_normalizeUnitsWhenPo5, 4), val1 = _normalizeUnitsWhenPo6[0], unit1 = _normalizeUnitsWhenPo6[1], val2 = _normalizeUnitsWhenPo6[2], unit2 = _normalizeUnitsWhenPo6[3]; if (unit1 !== unit2) { // not compatible units, so we can't do addition return null; } var sum = val1 + val2; if (overflowsOrUnderflows(sum)) { return null; } return new Quantity(sum, unit1); } else if (a.copy && a.add) { // Date / DateTime require a CQL time unit var cqlUnitB = convertToCQLDateUnit(b.unit) || b.unit; return a.copy().add(b.value * scaleForB, cqlUnitB); } else { throw new Error('Unsupported argument types.'); } } function doAddition(a, b) { return doScaledAddition(a, b, 1); } function doSubtraction(a, b) { return doScaledAddition(a, b, -1); } function doDivision(a, b) { if (a != null && a.isQuantity) { return a.dividedBy(b); } } function doMultiplication(a, b) { if (a != null && a.isQuantity) { return a.multiplyBy(b); } else { return b.multiplyBy(a); } } module.exports = { Quantity: Quantity, parseQuantity: parseQuantity, doAddition: doAddition, doSubtraction: doSubtraction, doDivision: doDivision, doMultiplication: doMultiplication }; },{"../util/math":174,"../util/units":175}],140:[function(require,module,exports){ "use strict"; 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 Ratio = /*#__PURE__*/function () { function Ratio(numerator, denominator) { _classCallCheck(this, Ratio); this.numerator = numerator; this.denominator = denominator; if (this.numerator == null) { throw new Error('Cannot create a ratio with an undefined numerator'); } if (this.denominator == null) { throw new Error('Cannot create a ratio with an undefined denominator'); } } _createClass(Ratio, [{ key: "clone", value: function clone() { return new Ratio(this.numerator.clone(), this.denominator.clone()); } }, { key: "toString", value: function toString() { return "".concat(this.numerator.toString(), " : ").concat(this.denominator.toString()); } }, { key: "equals", value: function equals(other) { if (other != null && other.isRatio) { var divided_this = this.numerator.dividedBy(this.denominator); var divided_other = other.numerator.dividedBy(other.denominator); return divided_this.equals(divided_other); } else { return false; } } }, { key: "equivalent", value: function equivalent(other) { var equal = this.equals(other); return equal != null ? equal : false; } }, { key: "isRatio", get: function get() { return true; } }]); return Ratio; }(); module.exports = { Ratio: Ratio }; },{}],141:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); return Constructor; } var _require = require('./logic'), ThreeValuedLogic = _require.ThreeValuedLogic; var Uncertainty = /*#__PURE__*/function () { _createClass(Uncertainty, null, [{ key: "from", value: function from(obj) { if (obj != null && obj.isUncertainty) { return obj; } else { return new Uncertainty(obj); } } }]); function Uncertainty() { var low = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var high = arguments.length > 1 ? arguments[1] : undefined; _classCallCheck(this, Uncertainty); this.low = low; this.high = high; var gt = function gt(a, b) { if (_typeof(a) !== _typeof(b)) { // TODO: This should probably throw rather than return false. // Uncertainties with different types probably shouldn't be supported. return false; } if (typeof a.after === 'function') { return a.after(b); } else { return a > b; } }; var isNonEnumerable = function isNonEnumerable(val) { return val != null && (val.isCode || val.isConcept || val.isValueSet); }; if (typeof this.high === 'undefined') { this.high = this.low; } if (isNonEnumerable(this.low) || isNonEnumerable(this.high)) { this.low = this.high = null; } if (this.low != null && this.high != null && gt(this.low, this.high)) { var _ref = [this.high, this.low]; this.low = _ref[0]; this.high = _ref[1]; } } _createClass(Uncertainty, [{ key: "copy", value: function copy() { var newLow = this.low; var newHigh = this.high; if (typeof this.low.copy === 'function') { newLow = this.low.copy(); } if (typeof this.high.copy === 'function') { newHigh = this.high.copy(); } return new Uncertainty(newLow, newHigh); } }, { key: "isPoint", value: function isPoint() { // Note: Can't use normal equality, as that fails for Javascript dates // TODO: Fix after we don't need to support Javascript date uncertainties anymore var lte = function lte(a, b) { if (_typeof(a) !== _typeof(b)) { return false; } if (typeof a.sameOrBefore === 'function') { return a.sameOrBefore(b); } else { return a <= b; } }; var gte = function gte(a, b) { if (_typeof(a) !== _typeof(b)) { return false; } if (typeof a.sameOrBefore === 'function') { return a.sameOrAfter(b); } else { return a >= b; } }; return this.low != null && this.high != null && lte(this.low, this.high) && gte(this.low, this.high); } }, { key: "equals", value: function equals(other) { other = Uncertainty.from(other); return ThreeValuedLogic.not(ThreeValuedLogic.or(this.lessThan(other), this.greaterThan(other))); } }, { key: "lessThan", value: function lessThan(other) { var lt = function lt(a, b) { if (_typeof(a) !== _typeof(b)) { return false; } if (typeof a.before === 'function') { return a.before(b); } else { return a < b; } }; other = Uncertainty.from(other); var bestCase = this.low == null || other.high == null || lt(this.low, other.high); var worstCase = this.high != null && other.low != null && lt(this.high, other.low); if (bestCase === worstCase) { return bestCase; } else { return null; } } }, { key: "greaterThan", value: function greaterThan(other) { return Uncertainty.from(other).lessThan(this); } }, { key: "lessThanOrEquals", value: function lessThanOrEquals(other) { return ThreeValuedLogic.not(this.greaterThan(Uncertainty.from(other))); } }, { key: "greaterThanOrEquals", value: function greaterThanOrEquals(other) { return ThreeValuedLogic.not(this.lessThan(Uncertainty.from(other))); } }, { key: "isUncertainty", get: function get() { return true; } }]); return Uncertainty; }(); module.exports = { Uncertainty: Uncertainty }; },{"./logic":138}],142:[function(require,module,exports){ "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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 _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 _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var _require2 = require('../util/util'), typeIsArray = _require2.typeIsArray, allTrue = _require2.allTrue, anyTrue = _require2.anyTrue, removeNulls = _require2.removeNulls, numerical_sort = _require2.numerical_sort; var _require3 = require('./builder'), build = _require3.build; var _require4 = require('../datatypes/exception'), Exception = _require4.Exception; var _require5 = require('../util/comparison'), greaterThan = _require5.greaterThan, lessThan = _require5.lessThan; var _require6 = require('../datatypes/quantity'), Quantity = _require6.Quantity; var AggregateExpression = /*#__PURE__*/function (_Expression) { _inherits(AggregateExpression, _Expression); var _super = _createSuper(AggregateExpression); function AggregateExpression(json) { var _this; _classCallCheck(this, AggregateExpression); _this = _super.call(this, json); _this.source = build(json.source); return _this; } return AggregateExpression; }(Expression); var Count = /*#__PURE__*/function (_AggregateExpression) { _inherits(Count, _AggregateExpression); var _super2 = _createSuper(Count); function Count(json) { _classCallCheck(this, Count); return _super2.call(this, json); } _createClass(Count, [{ key: "exec", value: function exec(ctx) { var items = this.source.execute(ctx); if (typeIsArray(items)) { return removeNulls(items).length; } return 0; } }]); return Count; }(AggregateExpression); var Sum = /*#__PURE__*/function (_AggregateExpression2) { _inherits(Sum, _AggregateExpression2); var _super3 = _createSuper(Sum); function Sum(json) { _classCallCheck(this, Sum); return _super3.call(this, json); } _createClass(Sum, [{ key: "exec", value: function exec(ctx) { var items = this.source.execute(ctx); if (!typeIsArray(items)) { return null; } try { items = processQuantities(items); } catch (e) { return null; } if (items.length === 0) { return null; } if (hasOnlyQuantities(items)) { var values = getValuesFromQuantities(items); var sum = values.reduce(function (x, y) { return x + y; }); return new Quantity(sum, items[0].unit); } else { return items.reduce(function (x, y) { return x + y; }); } } }]); return Sum; }(AggregateExpression); var Min = /*#__PURE__*/function (_AggregateExpression3) { _inherits(Min, _AggregateExpression3); var _super4 = _createSuper(Min); function Min(json) { _classCallCheck(this, Min); return _super4.call(this, json); } _createClass(Min, [{ key: "exec", value: function exec(ctx) { var list = this.source.execute(ctx); if (list == null) { return null; } var listWithoutNulls = removeNulls(list); // Check for incompatible units and return null. We don't want to convert // the units for Min/Max, so we throw away the converted array if it succeeds try { processQuantities(list); } catch (e) { return null; } if (listWithoutNulls.length === 0) { return null; } // We assume the list is an array of all the same type. var minimum = listWithoutNulls[0]; var _iterator = _createForOfIteratorHelper(listWithoutNulls), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var element = _step.value; if (lessThan(element, minimum)) { minimum = element; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return minimum; } }]); return Min; }(AggregateExpression); var Max = /*#__PURE__*/function (_AggregateExpression4) { _inherits(Max, _AggregateExpression4); var _super5 = _createSuper(Max); function Max(json) { _classCallCheck(this, Max); return _super5.call(this, json); } _createClass(Max, [{ key: "exec", value: function exec(ctx) { var items = this.source.execute(ctx); if (items == null) { return null; } var listWithoutNulls = removeNulls(items); // Check for incompatible units and return null. We don't want to convert // the units for Min/Max, so we throw away the converted array if it succeeds try { processQuantities(items); } catch (e) { return null; } if (listWithoutNulls.length === 0) { return null; } // We assume the list is an array of all the same type. var maximum = listWithoutNulls[0]; var _iterator2 = _createForOfIteratorHelper(listWithoutNulls), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var element = _step2.value; if (greaterThan(element, maximum)) { maximum = element; } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return maximum; } }]); return Max; }(AggregateExpression); var Avg = /*#__PURE__*/function (_AggregateExpression5) { _inherits(Avg, _AggregateExpression5); var _super6 = _createSuper(Avg); function Avg(json) { _classCallCheck(this, Avg); return _super6.call(this, json); } _createClass(Avg, [{ key: "exec", value: function exec(ctx) { var items = this.source.execute(ctx); if (!typeIsArray(items)) { return null; } try { items = processQuantities(items); } catch (e) { return null; } if (items.length === 0) { return null; } if (hasOnlyQuantities(items)) { var values = getValuesFromQuantities(items); var sum = values.reduce(function (x, y) { return x + y; }); return new Quantity(sum / values.length, items[0].unit); } else { var _sum = items.reduce(function (x, y) { return x + y; }); return _sum / items.length; } } }]); return Avg; }(AggregateExpression); var Median = /*#__PURE__*/function (_AggregateExpression6) { _inherits(Median, _AggregateExpression6); var _super7 = _createSuper(Median); function Median(json) { _classCallCheck(this, Median); return _super7.call(this, json); } _createClass(Median, [{ key: "exec", value: function exec(ctx) { var items = this.source.execute(ctx); if (!typeIsArray(items)) { return null; } if (items.length === 0) { return null; } try { items = processQuantities(items); } catch (e) { return null; } if (!hasOnlyQuantities(items)) { return medianOfNumbers(items); } var values = getValuesFromQuantities(items); var median = medianOfNumbers(values); return new Quantity(median, items[0].unit); } }]); return Median; }(AggregateExpression); var Mode = /*#__PURE__*/function (_AggregateExpression7) { _inherits(Mode, _AggregateExpression7); var _super8 = _createSuper(Mode); function Mode(json) { _classCallCheck(this, Mode); return _super8.call(this, json); } _createClass(Mode, [{ key: "exec", value: function exec(ctx) { var items = this.source.execute(ctx); if (!typeIsArray(items)) { return null; } if (items.length === 0) { return null; } var filtered; try { filtered = processQuantities(items); } catch (e) { return null; } if (hasOnlyQuantities(filtered)) { var values = getValuesFromQuantities(filtered); var mode = this.mode(values); if (mode.length === 1) { mode = mode[0]; } return new Quantity(mode, items[0].unit); } else { var _mode = this.mode(filtered); if (_mode.length === 1) { return _mode[0]; } else { return _mode; } } } }, { key: "mode", value: function mode(arr) { var max = 0; var counts = {}; var results = []; var _iterator3 = _createForOfIteratorHelper(arr), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var elem = _step3.value; var cnt = counts[elem] = (counts[elem] != null ? counts[elem] : 0) + 1; if (cnt === max && !results.includes(elem)) { results.push(elem); } else if (cnt > max) { results = [elem]; max = cnt; } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return results; } }]); return Mode; }(AggregateExpression); var StdDev = /*#__PURE__*/function (_AggregateExpression8) { _inherits(StdDev, _AggregateExpression8); var _super9 = _createSuper(StdDev); // TODO: This should be a derived class of an abstract base class 'Statistic' // rather than the base class function StdDev(json) { var _this2; _classCallCheck(this, StdDev); _this2 = _super9.call(this, json); _this2.type = 'standard_deviation'; return _this2; } _createClass(StdDev, [{ key: "exec", value: function exec(ctx) { var items = this.source.execute(ctx); if (!typeIsArray(items)) { return null; } try { items = processQuantities(items); } catch (e) { return null; } if (items.length === 0) { return null; } if (hasOnlyQuantities(items)) { var values = getValuesFromQuantities(items); var stdDev = this.standardDeviation(values); return new Quantity(stdDev, items[0].unit); } else { return this.standardDeviation(items); } } }, { key: "standardDeviation", value: function standardDeviation(list) { var val = this.stats(list); if (val) { return val[this.type]; } } }, { key: "stats", value: function stats(list) { var sum = list.reduce(function (x, y) { return x + y; }); var mean = sum / list.length; var sumOfSquares = 0; var _iterator4 = _createForOfIteratorHelper(list), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var sq = _step4.value; sumOfSquares += Math.pow(sq - mean, 2); } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } var std_var = 1 / (list.length - 1) * sumOfSquares; var pop_var = 1 / list.length * sumOfSquares; var std_dev = Math.sqrt(std_var); var pop_dev = Math.sqrt(pop_var); return { standard_variance: std_var, population_variance: pop_var, standard_deviation: std_dev, population_deviation: pop_dev }; } }]); return StdDev; }(AggregateExpression); var Product = /*#__PURE__*/function (_AggregateExpression9) { _inherits(Product, _AggregateExpression9); var _super10 = _createSuper(Product); function Product(json) { _classCallCheck(this, Product); return _super10.call(this, json); } _createClass(Product, [{ key: "exec", value: function exec(ctx) { var items = this.source.execute(ctx); if (!typeIsArray(items)) { return null; } try { items = processQuantities(items); } catch (e) { return null; } if (items.length === 0) { return null; } if (hasOnlyQuantities(items)) { var values = getValuesFromQuantities(items); var product = values.reduce(function (x, y) { return x * y; }); // Units are not multiplied for the geometric product return new Quantity(product, items[0].unit); } else { return items.reduce(function (x, y) { return x * y; }); } } }]); return Product; }(AggregateExpression); var GeometricMean = /*#__PURE__*/function (_AggregateExpression10) { _inherits(GeometricMean, _AggregateExpression10); var _super11 = _createSuper(GeometricMean); function GeometricMean(json) { _classCallCheck(this, GeometricMean); return _super11.call(this, json); } _createClass(GeometricMean, [{ key: "exec", value: function exec(ctx) { var items = this.source.execute(ctx); if (!typeIsArray(items)) { return null; } try { items = processQuantities(items); } catch (e) { return null; } if (items.length === 0) { return null; } if (hasOnlyQuantities(items)) { var values = getValuesFromQuantities(items); var product = values.reduce(function (x, y) { return x * y; }); var geoMean = Math.pow(product, 1.0 / items.length); return new Quantity(geoMean, items[0].unit); } else { var _product = items.reduce(function (x, y) { return x * y; }); return Math.pow(_product, 1.0 / items.length); } } }]); return GeometricMean; }(AggregateExpression); var PopulationStdDev = /*#__PURE__*/function (_StdDev) { _inherits(PopulationStdDev, _StdDev); var _super12 = _createSuper(PopulationStdDev); function PopulationStdDev(json) { var _this3; _classCallCheck(this, PopulationStdDev); _this3 = _super12.call(this, json); _this3.type = 'population_deviation'; return _this3; } return PopulationStdDev; }(StdDev); var Variance = /*#__PURE__*/function (_StdDev2) { _inherits(Variance, _StdDev2); var _super13 = _createSuper(Variance); function Variance(json) { var _this4; _classCallCheck(this, Variance); _this4 = _super13.call(this, json); _this4.type = 'standard_variance'; return _this4; } return Variance; }(StdDev); var PopulationVariance = /*#__PURE__*/function (_StdDev3) { _inherits(PopulationVariance, _StdDev3); var _super14 = _createSuper(PopulationVariance); function PopulationVariance(json) { var _this5; _classCallCheck(this, PopulationVariance); _this5 = _super14.call(this, json); _this5.type = 'population_variance'; return _this5; } return PopulationVariance; }(StdDev); var AllTrue = /*#__PURE__*/function (_AggregateExpression11) { _inherits(AllTrue, _AggregateExpression11); var _super15 = _createSuper(AllTrue); function AllTrue(json) { _classCallCheck(this, AllTrue); return _super15.call(this, json); } _createClass(AllTrue, [{ key: "exec", value: function exec(ctx) { var items = this.source.execute(ctx); return allTrue(removeNulls(items)); } }]); return AllTrue; }(AggregateExpression); var AnyTrue = /*#__PURE__*/function (_AggregateExpression12) { _inherits(AnyTrue, _AggregateExpression12); var _super16 = _createSuper(AnyTrue); function AnyTrue(json) { _classCallCheck(this, AnyTrue); return _super16.call(this, json); } _createClass(AnyTrue, [{ key: "exec", value: function exec(ctx) { var items = this.source.execute(ctx); return anyTrue(items); } }]); return AnyTrue; }(AggregateExpression); function processQuantities(values) { var items = removeNulls(values); if (hasOnlyQuantities(items)) { return convertAllUnits(items); } else if (hasSomeQuantities(items)) { throw new Exception('Cannot perform aggregate operations on mixed values of Quantities and non Quantities'); } else { return items; } } function getValuesFromQuantities(quantities) { return quantities.map(function (quantity) { return quantity.value; }); } function hasOnlyQuantities(arr) { return arr.every(function (x) { return x.isQuantity; }); } function hasSomeQuantities(arr) { return arr.some(function (x) { return x.isQuantity; }); } function convertAllUnits(arr) { // convert all quantities in array to match the unit of the first item return arr.map(function (q) { return q.convertUnit(arr[0].unit); }); } function medianOfNumbers(numbers) { var items = numerical_sort(numbers, 'asc'); if (items.length % 2 === 1) { // Odd number of items return items[(items.length - 1) / 2]; } else { // Even number of items return (items[items.length / 2 - 1] + items[items.length / 2]) / 2; } } module.exports = { Count: Count, Sum: Sum, Min: Min, Max: Max, Avg: Avg, Median: Median, Mode: Mode, StdDev: StdDev, Product: Product, GeometricMean: GeometricMean, PopulationStdDev: PopulationStdDev, Variance: Variance, PopulationVariance: PopulationVariance, AllTrue: AllTrue, AnyTrue: AnyTrue }; },{"../datatypes/exception":136,"../datatypes/quantity":139,"../util/comparison":173,"../util/util":176,"./builder":144,"./expression":150}],143:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var _require2 = require('./builder'), build = _require2.build; var MathUtil = require('../util/math'); var _require3 = require('../datatypes/quantity'), Quantity = _require3.Quantity, doAddition = _require3.doAddition, doSubtraction = _require3.doSubtraction, doMultiplication = _require3.doMultiplication, doDivision = _require3.doDivision; var _require4 = require('../datatypes/uncertainty'), Uncertainty = _require4.Uncertainty; var Add = /*#__PURE__*/function (_Expression) { _inherits(Add, _Expression); var _super = _createSuper(Add); function Add(json) { _classCallCheck(this, Add); return _super.call(this, json); } _createClass(Add, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx); if (args == null || args.some(function (x) { return x == null; })) { return null; } var sum = args.reduce(function (x, y) { if (x.isUncertainty && !y.isUncertainty) { y = new Uncertainty(y, y); } else if (y.isUncertainty && !x.isUncertainty) { x = new Uncertainty(x, x); } if (x.isQuantity || x.isDateTime || x.isDate || x.isTime && x.isTime()) { return doAddition(x, y); } else if (x.isUncertainty && y.isUncertainty) { if (x.low.isQuantity || x.low.isDateTime || x.low.isDate || x.low.isTime && x.low.isTime()) { return new Uncertainty(doAddition(x.low, y.low), doAddition(x.high, y.high)); } else { return new Uncertainty(x.low + y.low, x.high + y.high); } } else { return x + y; } }); if (MathUtil.overflowsOrUnderflows(sum)) { return null; } return sum; } }]); return Add; }(Expression); var Subtract = /*#__PURE__*/function (_Expression2) { _inherits(Subtract, _Expression2); var _super2 = _createSuper(Subtract); function Subtract(json) { _classCallCheck(this, Subtract); return _super2.call(this, json); } _createClass(Subtract, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx); if (args == null || args.some(function (x) { return x == null; })) { return null; } var difference = args.reduce(function (x, y) { if (x.isUncertainty && !y.isUncertainty) { y = new Uncertainty(y, y); } else if (y.isUncertainty && !x.isUncertainty) { x = new Uncertainty(x, x); } if (x.isQuantity || x.isDateTime || x.isDate) { return doSubtraction(x, y); } else if (x.isUncertainty && y.isUncertainty) { if (x.low.isQuantity || x.low.isDateTime || x.low.isDate) { return new Uncertainty(doSubtraction(x.low, y.high), doSubtraction(x.high, y.low)); } else { return new Uncertainty(x.low - y.high, x.high - y.low); } } else { return x - y; } }); if (MathUtil.overflowsOrUnderflows(difference)) { return null; } return difference; } }]); return Subtract; }(Expression); var Multiply = /*#__PURE__*/function (_Expression3) { _inherits(Multiply, _Expression3); var _super3 = _createSuper(Multiply); function Multiply(json) { _classCallCheck(this, Multiply); return _super3.call(this, json); } _createClass(Multiply, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx); if (args == null || args.some(function (x) { return x == null; })) { return null; } var product = args.reduce(function (x, y) { if (x.isUncertainty && !y.isUncertainty) { y = new Uncertainty(y, y); } else if (y.isUncertainty && !x.isUncertainty) { x = new Uncertainty(x, x); } if (x.isQuantity || y.isQuantity) { return doMultiplication(x, y); } else if (x.isUncertainty && y.isUncertainty) { if (x.low.isQuantity) { return new Uncertainty(doMultiplication(x.low, y.low), doMultiplication(x.high, y.high)); } else { return new Uncertainty(x.low * y.low, x.high * y.high); } } else { return x * y; } }); if (MathUtil.overflowsOrUnderflows(product)) { return null; } return product; } }]); return Multiply; }(Expression); var Divide = /*#__PURE__*/function (_Expression4) { _inherits(Divide, _Expression4); var _super4 = _createSuper(Divide); function Divide(json) { _classCallCheck(this, Divide); return _super4.call(this, json); } _createClass(Divide, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx); if (args == null || args.some(function (x) { return x == null; })) { return null; } var quotient = args.reduce(function (x, y) { if (x.isUncertainty && !y.isUncertainty) { y = new Uncertainty(y, y); } else if (y.isUncertainty && !x.isUncertainty) { x = new Uncertainty(x, x); } if (x.isQuantity) { return doDivision(x, y); } else if (x.isUncertainty && y.isUncertainty) { if (x.low.isQuantity) { return new Uncertainty(doDivision(x.low, y.high), doDivision(x.high, y.low)); } else { return new Uncertainty(x.low / y.high, x.high / y.low); } } else { return x / y; } }); // Note, anything divided by 0 is Infinity in Javascript, which will be // considered as overflow by this check. if (MathUtil.overflowsOrUnderflows(quotient)) { return null; } return quotient; } }]); return Divide; }(Expression); var TruncatedDivide = /*#__PURE__*/function (_Expression5) { _inherits(TruncatedDivide, _Expression5); var _super5 = _createSuper(TruncatedDivide); function TruncatedDivide(json) { _classCallCheck(this, TruncatedDivide); return _super5.call(this, json); } _createClass(TruncatedDivide, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx); if (args == null || args.some(function (x) { return x == null; })) { return null; } var quotient = args.reduce(function (x, y) { return x / y; }); var truncatedQuotient = quotient >= 0 ? Math.floor(quotient) : Math.ceil(quotient); if (MathUtil.overflowsOrUnderflows(truncatedQuotient)) { return null; } return truncatedQuotient; } }]); return TruncatedDivide; }(Expression); var Modulo = /*#__PURE__*/function (_Expression6) { _inherits(Modulo, _Expression6); var _super6 = _createSuper(Modulo); function Modulo(json) { _classCallCheck(this, Modulo); return _super6.call(this, json); } _createClass(Modulo, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx); if (args == null || args.some(function (x) { return x == null; })) { return null; } var modulo = args.reduce(function (x, y) { return x % y; }); return MathUtil.decimalOrNull(modulo); } }]); return Modulo; }(Expression); var Ceiling = /*#__PURE__*/function (_Expression7) { _inherits(Ceiling, _Expression7); var _super7 = _createSuper(Ceiling); function Ceiling(json) { _classCallCheck(this, Ceiling); return _super7.call(this, json); } _createClass(Ceiling, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg == null) { return null; } return Math.ceil(arg); } }]); return Ceiling; }(Expression); var Floor = /*#__PURE__*/function (_Expression8) { _inherits(Floor, _Expression8); var _super8 = _createSuper(Floor); function Floor(json) { _classCallCheck(this, Floor); return _super8.call(this, json); } _createClass(Floor, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg == null) { return null; } return Math.floor(arg); } }]); return Floor; }(Expression); var Truncate = /*#__PURE__*/function (_Expression9) { _inherits(Truncate, _Expression9); var _super9 = _createSuper(Truncate); function Truncate(json) { _classCallCheck(this, Truncate); return _super9.call(this, json); } _createClass(Truncate, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg == null) { return null; } return arg >= 0 ? Math.floor(arg) : Math.ceil(arg); } }]); return Truncate; }(Expression); var Abs = /*#__PURE__*/function (_Expression10) { _inherits(Abs, _Expression10); var _super10 = _createSuper(Abs); function Abs(json) { _classCallCheck(this, Abs); return _super10.call(this, json); } _createClass(Abs, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg == null) { return null; } else if (arg.isQuantity) { return new Quantity(Math.abs(arg.value), arg.unit); } else { return Math.abs(arg); } } }]); return Abs; }(Expression); var Negate = /*#__PURE__*/function (_Expression11) { _inherits(Negate, _Expression11); var _super11 = _createSuper(Negate); function Negate(json) { _classCallCheck(this, Negate); return _super11.call(this, json); } _createClass(Negate, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg == null) { return null; } else if (arg.isQuantity) { return new Quantity(arg.value * -1, arg.unit); } else { return arg * -1; } } }]); return Negate; }(Expression); var Round = /*#__PURE__*/function (_Expression12) { _inherits(Round, _Expression12); var _super12 = _createSuper(Round); function Round(json) { var _this; _classCallCheck(this, Round); _this = _super12.call(this, json); _this.precision = build(json.precision); return _this; } _createClass(Round, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg == null) { return null; } var dec = this.precision != null ? this.precision.execute(ctx) : 0; return Math.round(arg * Math.pow(10, dec)) / Math.pow(10, dec); } }]); return Round; }(Expression); var Ln = /*#__PURE__*/function (_Expression13) { _inherits(Ln, _Expression13); var _super13 = _createSuper(Ln); function Ln(json) { _classCallCheck(this, Ln); return _super13.call(this, json); } _createClass(Ln, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg == null) { return null; } var ln = Math.log(arg); return MathUtil.decimalOrNull(ln); } }]); return Ln; }(Expression); var Exp = /*#__PURE__*/function (_Expression14) { _inherits(Exp, _Expression14); var _super14 = _createSuper(Exp); function Exp(json) { _classCallCheck(this, Exp); return _super14.call(this, json); } _createClass(Exp, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg == null) { return null; } var power = Math.exp(arg); if (MathUtil.overflowsOrUnderflows(power)) { return null; } return power; } }]); return Exp; }(Expression); var Log = /*#__PURE__*/function (_Expression15) { _inherits(Log, _Expression15); var _super15 = _createSuper(Log); function Log(json) { _classCallCheck(this, Log); return _super15.call(this, json); } _createClass(Log, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx); if (args == null || args.some(function (x) { return x == null; })) { return null; } var log = args.reduce(function (x, y) { return Math.log(x) / Math.log(y); }); return MathUtil.decimalOrNull(log); } }]); return Log; }(Expression); var Power = /*#__PURE__*/function (_Expression16) { _inherits(Power, _Expression16); var _super16 = _createSuper(Power); function Power(json) { _classCallCheck(this, Power); return _super16.call(this, json); } _createClass(Power, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx); if (args == null || args.some(function (x) { return x == null; })) { return null; } var power = args.reduce(function (x, y) { return Math.pow(x, y); }); if (MathUtil.overflowsOrUnderflows(power)) { return null; } return power; } }]); return Power; }(Expression); var MinValue = /*#__PURE__*/function (_Expression17) { _inherits(MinValue, _Expression17); var _super17 = _createSuper(MinValue); function MinValue(json) { var _this2; _classCallCheck(this, MinValue); _this2 = _super17.call(this, json); _this2.valueType = json.valueType; return _this2; } _createClass(MinValue, [{ key: "exec", value: function exec(ctx) { if (MinValue.MIN_VALUES[this.valueType]) { if (this.valueType === '{urn:hl7-org:elm-types:r1}DateTime') { var minDateTime = MinValue.MIN_VALUES[this.valueType].copy(); minDateTime.timezoneOffset = ctx.getTimezoneOffset(); return minDateTime; } else { return MinValue.MIN_VALUES[this.valueType]; } } else { throw new Error("Minimum not supported for ".concat(this.valueType)); } } }]); return MinValue; }(Expression); MinValue.MIN_VALUES = {}; MinValue.MIN_VALUES['{urn:hl7-org:elm-types:r1}Integer'] = MathUtil.MIN_INT_VALUE; MinValue.MIN_VALUES['{urn:hl7-org:elm-types:r1}Decimal'] = MathUtil.MIN_FLOAT_VALUE; MinValue.MIN_VALUES['{urn:hl7-org:elm-types:r1}DateTime'] = MathUtil.MIN_DATETIME_VALUE; MinValue.MIN_VALUES['{urn:hl7-org:elm-types:r1}Date'] = MathUtil.MIN_DATE_VALUE; MinValue.MIN_VALUES['{urn:hl7-org:elm-types:r1}Time'] = MathUtil.MIN_TIME_VALUE; var MaxValue = /*#__PURE__*/function (_Expression18) { _inherits(MaxValue, _Expression18); var _super18 = _createSuper(MaxValue); function MaxValue(json) { var _this3; _classCallCheck(this, MaxValue); _this3 = _super18.call(this, json); _this3.valueType = json.valueType; return _this3; } _createClass(MaxValue, [{ key: "exec", value: function exec(ctx) { if (MaxValue.MAX_VALUES[this.valueType] != null) { if (this.valueType === '{urn:hl7-org:elm-types:r1}DateTime') { var maxDateTime = MaxValue.MAX_VALUES[this.valueType].copy(); maxDateTime.timezoneOffset = ctx.getTimezoneOffset(); return maxDateTime; } else { return MaxValue.MAX_VALUES[this.valueType]; } } else { throw new Error("Maximum not supported for ".concat(this.valueType)); } } }]); return MaxValue; }(Expression); MaxValue.MAX_VALUES = {}; MaxValue.MAX_VALUES['{urn:hl7-org:elm-types:r1}Integer'] = MathUtil.MAX_INT_VALUE; MaxValue.MAX_VALUES['{urn:hl7-org:elm-types:r1}Decimal'] = MathUtil.MAX_FLOAT_VALUE; MaxValue.MAX_VALUES['{urn:hl7-org:elm-types:r1}DateTime'] = MathUtil.MAX_DATETIME_VALUE; MaxValue.MAX_VALUES['{urn:hl7-org:elm-types:r1}Date'] = MathUtil.MAX_DATE_VALUE; MaxValue.MAX_VALUES['{urn:hl7-org:elm-types:r1}Time'] = MathUtil.MAX_TIME_VALUE; var Successor = /*#__PURE__*/function (_Expression19) { _inherits(Successor, _Expression19); var _super19 = _createSuper(Successor); function Successor(json) { _classCallCheck(this, Successor); return _super19.call(this, json); } _createClass(Successor, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg == null) { null; } var successor = null; try { // MathUtil.successor throws on overflow, and the exception is used in // the logic for evaluating `meets`, so it can't be changed to just return null successor = MathUtil.successor(arg); } catch (e) { if (e instanceof MathUtil.OverFlowException) { return null; } } if (MathUtil.overflowsOrUnderflows(successor)) { return null; } return successor; } }]); return Successor; }(Expression); var Predecessor = /*#__PURE__*/function (_Expression20) { _inherits(Predecessor, _Expression20); var _super20 = _createSuper(Predecessor); function Predecessor(json) { _classCallCheck(this, Predecessor); return _super20.call(this, json); } _createClass(Predecessor, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg == null) { null; } var predecessor = null; try { // MathUtil.predecessor throws on underflow, and the exception is used in // the logic for evaluating `meets`, so it can't be changed to just return null predecessor = MathUtil.predecessor(arg); } catch (e) { if (e instanceof MathUtil.OverFlowException) { return null; } } if (MathUtil.overflowsOrUnderflows(predecessor)) { return null; } return predecessor; } }]); return Predecessor; }(Expression); module.exports = { Abs: Abs, Add: Add, Ceiling: Ceiling, Divide: Divide, Exp: Exp, Floor: Floor, Ln: Ln, Log: Log, MaxValue: MaxValue, MinValue: MinValue, Modulo: Modulo, Multiply: Multiply, Negate: Negate, Power: Power, Predecessor: Predecessor, Round: Round, Subtract: Subtract, Successor: Successor, Truncate: Truncate, TruncatedDivide: TruncatedDivide }; },{"../datatypes/quantity":139,"../datatypes/uncertainty":141,"../util/math":174,"./builder":144,"./expression":150}],144:[function(require,module,exports){ "use strict"; var E = require('./expressions'); var _require = require('../util/util'), typeIsArray = _require.typeIsArray; function build(json) { if (json == null) { return json; } if (typeIsArray(json)) { return json.map(function (child) { return build(child); }); } if (json.type === 'FunctionRef') { return new E.FunctionRef(json); } else if (json.type === 'Literal') { return E.Literal.from(json); } else if (functionExists(json.type)) { return constructByName(json.type, json); } else { return null; } } function functionExists(name) { return typeof E[name] === 'function'; } function constructByName(name, json) { return new E[name](json); } module.exports = { build: build }; },{"../util/util":176,"./expressions":151}],145:[function(require,module,exports){ "use strict"; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; 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) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var dt = require('../datatypes/datatypes'); var _require2 = require('./builder'), build = _require2.build; var ValueSetDef = /*#__PURE__*/function (_Expression) { _inherits(ValueSetDef, _Expression); var _super = _createSuper(ValueSetDef); function ValueSetDef(json) { var _this; _classCallCheck(this, ValueSetDef); _this = _super.call(this, json); _this.name = json.name; _this.id = json.id; _this.version = json.version; return _this; } //todo: code systems and versions _createClass(ValueSetDef, [{ key: "exec", value: function exec(ctx) { var valueset = ctx.codeService.findValueSet(this.id, this.version) || new dt.ValueSet(this.id, this.version); ctx.rootContext().set(this.name, valueset); return valueset; } }]); return ValueSetDef; }(Expression); var ValueSetRef = /*#__PURE__*/function (_Expression2) { _inherits(ValueSetRef, _Expression2); var _super2 = _createSuper(ValueSetRef); function ValueSetRef(json) { var _this2; _classCallCheck(this, ValueSetRef); _this2 = _super2.call(this, json); _this2.name = json.name; _this2.libraryName = json.libraryName; return _this2; } _createClass(ValueSetRef, [{ key: "exec", value: function exec(ctx) { // TODO: This calls the code service every time-- should be optimized var valueset = ctx.getValueSet(this.name, this.libraryName); if (valueset instanceof Expression) { valueset = valueset.execute(ctx); } return valueset; } }]); return ValueSetRef; }(Expression); var AnyInValueSet = /*#__PURE__*/function (_Expression3) { _inherits(AnyInValueSet, _Expression3); var _super3 = _createSuper(AnyInValueSet); function AnyInValueSet(json) { var _this3; _classCallCheck(this, AnyInValueSet); _this3 = _super3.call(this, json); _this3.codes = build(json.codes); _this3.valueset = new ValueSetRef(json.valueset); return _this3; } _createClass(AnyInValueSet, [{ key: "exec", value: function exec(ctx) { var valueset = this.valueset.execute(ctx); // If the value set reference cannot be resolved, a run-time error is thrown. if (valueset == null || !valueset.isValueSet) { throw new Error('ValueSet must be provided to InValueSet function'); } var codes = this.codes.exec(ctx); return codes != null && codes.some(function (code) { return valueset.hasMatch(code); }); } }]); return AnyInValueSet; }(Expression); var InValueSet = /*#__PURE__*/function (_Expression4) { _inherits(InValueSet, _Expression4); var _super4 = _createSuper(InValueSet); function InValueSet(json) { var _this4; _classCallCheck(this, InValueSet); _this4 = _super4.call(this, json); _this4.code = build(json.code); _this4.valueset = new ValueSetRef(json.valueset); return _this4; } _createClass(InValueSet, [{ key: "exec", value: function exec(ctx) { // If the code argument is null, the result is false if (this.code == null) { return false; } if (this.valueset == null) { throw new Error('ValueSet must be provided to InValueSet function'); } var code = this.code.execute(ctx); // spec indicates to return false if code is null, throw error if value set cannot be resolved if (code == null) { return false; } var valueset = this.valueset.execute(ctx); if (valueset == null || !valueset.isValueSet) { throw new Error('ValueSet must be provided to InValueSet function'); } // If there is a code and valueset return whether or not the valueset has the code return valueset.hasMatch(code); } }]); return InValueSet; }(Expression); var CodeSystemDef = /*#__PURE__*/function (_Expression5) { _inherits(CodeSystemDef, _Expression5); var _super5 = _createSuper(CodeSystemDef); function CodeSystemDef(json) { var _this5; _classCallCheck(this, CodeSystemDef); _this5 = _super5.call(this, json); _this5.name = json.name; _this5.id = json.id; _this5.version = json.version; return _this5; } _createClass(CodeSystemDef, [{ key: "exec", value: function exec(ctx) { return new dt.CodeSystem(this.id, this.version); } }]); return CodeSystemDef; }(Expression); var CodeDef = /*#__PURE__*/function (_Expression6) { _inherits(CodeDef, _Expression6); var _super6 = _createSuper(CodeDef); function CodeDef(json) { var _this6; _classCallCheck(this, CodeDef); _this6 = _super6.call(this, json); _this6.name = json.name; _this6.id = json.id; _this6.systemName = json.codeSystem.name; _this6.display = json.display; return _this6; } _createClass(CodeDef, [{ key: "exec", value: function exec(ctx) { var system = ctx.getCodeSystem(this.systemName).execute(ctx); return new dt.Code(this.id, system.id, system.version, this.display); } }]); return CodeDef; }(Expression); var CodeRef = /*#__PURE__*/function (_Expression7) { _inherits(CodeRef, _Expression7); var _super7 = _createSuper(CodeRef); function CodeRef(json) { var _this7; _classCallCheck(this, CodeRef); _this7 = _super7.call(this, json); _this7.name = json.name; _this7.library = json.libraryName; return _this7; } _createClass(CodeRef, [{ key: "exec", value: function exec(ctx) { ctx = this.library ? ctx.getLibraryContext(this.library) : ctx; var codeDef = ctx.getCode(this.name); return codeDef ? codeDef.execute(ctx) : undefined; } }]); return CodeRef; }(Expression); var Code = /*#__PURE__*/function (_Expression8) { _inherits(Code, _Expression8); var _super8 = _createSuper(Code); function Code(json) { var _this8; _classCallCheck(this, Code); _this8 = _super8.call(this, json); _this8.code = json.code; _this8.systemName = json.system.name; _this8.version = json.version; _this8.display = json.display; return _this8; } // Define a simple getter to allow type-checking of this class without instanceof // and in a way that survives minification (as opposed to checking constructor.name) _createClass(Code, [{ key: "exec", value: function exec(ctx) { var system = ctx.getCodeSystem(this.systemName) || {}; return new dt.Code(this.code, system.id, this.version, this.display); } }, { key: "isCode", get: function get() { return true; } }]); return Code; }(Expression); var ConceptDef = /*#__PURE__*/function (_Expression9) { _inherits(ConceptDef, _Expression9); var _super9 = _createSuper(ConceptDef); function ConceptDef(json) { var _this9; _classCallCheck(this, ConceptDef); _this9 = _super9.call(this, json); _this9.name = json.name; _this9.display = json.display; _this9.codes = json.code; return _this9; } _createClass(ConceptDef, [{ key: "exec", value: function exec(ctx) { var codes = this.codes.map(function (code) { var codeDef = ctx.getCode(code.name); return codeDef ? codeDef.execute(ctx) : undefined; }); return new dt.Concept(codes, this.display); } }]); return ConceptDef; }(Expression); var ConceptRef = /*#__PURE__*/function (_Expression10) { _inherits(ConceptRef, _Expression10); var _super10 = _createSuper(ConceptRef); function ConceptRef(json) { var _this10; _classCallCheck(this, ConceptRef); _this10 = _super10.call(this, json); _this10.name = json.name; return _this10; } _createClass(ConceptRef, [{ key: "exec", value: function exec(ctx) { var conceptDef = ctx.getConcept(this.name); return conceptDef ? conceptDef.execute(ctx) : undefined; } }]); return ConceptRef; }(Expression); var Concept = /*#__PURE__*/function (_Expression11) { _inherits(Concept, _Expression11); var _super11 = _createSuper(Concept); function Concept(json) { var _this11; _classCallCheck(this, Concept); _this11 = _super11.call(this, json); _this11.codes = json.code; _this11.display = json.display; return _this11; } // Define a simple getter to allow type-checking of this class without instanceof // and in a way that survives minification (as opposed to checking constructor.name) _createClass(Concept, [{ key: "toCode", value: function toCode(ctx, code) { var system = ctx.getCodeSystem(code.system.name) || {}; return new dt.Code(code.code, system.id, code.version, code.display); } }, { key: "exec", value: function exec(ctx) { var _this12 = this; var codes = this.codes.map(function (code) { return _this12.toCode(ctx, code); }); return new dt.Concept(codes, this.display); } }, { key: "isConcept", get: function get() { return true; } }]); return Concept; }(Expression); var CalculateAge = /*#__PURE__*/function (_Expression12) { _inherits(CalculateAge, _Expression12); var _super12 = _createSuper(CalculateAge); function CalculateAge(json) { var _this13; _classCallCheck(this, CalculateAge); _this13 = _super12.call(this, json); _this13.precision = json.precision; return _this13; } _createClass(CalculateAge, [{ key: "exec", value: function exec(ctx) { var date1 = this.execArgs(ctx); var date2 = dt.DateTime.fromJSDate(ctx.getExecutionDateTime()); var result = date1 != null ? date1.durationBetween(date2, this.precision.toLowerCase()) : undefined; if (result != null && result.isPoint()) { return result.low; } else { return result; } } }]); return CalculateAge; }(Expression); var CalculateAgeAt = /*#__PURE__*/function (_Expression13) { _inherits(CalculateAgeAt, _Expression13); var _super13 = _createSuper(CalculateAgeAt); function CalculateAgeAt(json) { var _this14; _classCallCheck(this, CalculateAgeAt); _this14 = _super13.call(this, json); _this14.precision = json.precision; return _this14; } _createClass(CalculateAgeAt, [{ key: "exec", value: function exec(ctx) { var _this$execArgs = this.execArgs(ctx), _this$execArgs2 = _slicedToArray(_this$execArgs, 2), date1 = _this$execArgs2[0], date2 = _this$execArgs2[1]; if (date1 != null && date2 != null) { // date1 is the birthdate, convert it to date if date2 is a date (to support ignoring time) if (date2.isDate && date1.isDateTime) { date1 = date1.getDate(); } var result = date1.durationBetween(date2, this.precision.toLowerCase()); if (result != null && result.isPoint()) { return result.low; } else { return result; } } return null; } }]); return CalculateAgeAt; }(Expression); module.exports = { AnyInValueSet: AnyInValueSet, CalculateAge: CalculateAge, CalculateAgeAt: CalculateAgeAt, Code: Code, CodeDef: CodeDef, CodeRef: CodeRef, CodeSystemDef: CodeSystemDef, Concept: Concept, ConceptDef: ConceptDef, ConceptRef: ConceptRef, InValueSet: InValueSet, ValueSetDef: ValueSetDef, ValueSetRef: ValueSetRef }; },{"../datatypes/datatypes":134,"./builder":144,"./expression":150}],146:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var _require2 = require('../datatypes/datatypes'), Uncertainty = _require2.Uncertainty; // Equal is completely handled by overloaded#Equal // NotEqual is completely handled by overloaded#Equal var Less = /*#__PURE__*/function (_Expression) { _inherits(Less, _Expression); var _super = _createSuper(Less); function Less(json) { _classCallCheck(this, Less); return _super.call(this, json); } _createClass(Less, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx).map(function (x) { return Uncertainty.from(x); }); if (args[0] == null || args[1] == null) { return null; } return args[0].lessThan(args[1]); } }]); return Less; }(Expression); var LessOrEqual = /*#__PURE__*/function (_Expression2) { _inherits(LessOrEqual, _Expression2); var _super2 = _createSuper(LessOrEqual); function LessOrEqual(json) { _classCallCheck(this, LessOrEqual); return _super2.call(this, json); } _createClass(LessOrEqual, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx).map(function (x) { return Uncertainty.from(x); }); if (args[0] == null || args[1] == null) { return null; } return args[0].lessThanOrEquals(args[1]); } }]); return LessOrEqual; }(Expression); var Greater = /*#__PURE__*/function (_Expression3) { _inherits(Greater, _Expression3); var _super3 = _createSuper(Greater); function Greater(json) { _classCallCheck(this, Greater); return _super3.call(this, json); } _createClass(Greater, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx).map(function (x) { return Uncertainty.from(x); }); if (args[0] == null || args[1] == null) { return null; } return args[0].greaterThan(args[1]); } }]); return Greater; }(Expression); var GreaterOrEqual = /*#__PURE__*/function (_Expression4) { _inherits(GreaterOrEqual, _Expression4); var _super4 = _createSuper(GreaterOrEqual); function GreaterOrEqual(json) { _classCallCheck(this, GreaterOrEqual); return _super4.call(this, json); } _createClass(GreaterOrEqual, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx).map(function (x) { return Uncertainty.from(x); }); if (args[0] == null || args[1] == null) { return null; } return args[0].greaterThanOrEquals(args[1]); } }]); return GreaterOrEqual; }(Expression); module.exports = { Greater: Greater, GreaterOrEqual: GreaterOrEqual, Less: Less, LessOrEqual: LessOrEqual }; },{"../datatypes/datatypes":134,"./expression":150}],147:[function(require,module,exports){ "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var _require2 = require('./builder'), build = _require2.build; var _require3 = require('../util/comparison'), equals = _require3.equals; // TODO: Spec lists "Conditional", but it's "If" in the XSD var If = /*#__PURE__*/function (_Expression) { _inherits(If, _Expression); var _super = _createSuper(If); function If(json) { var _this; _classCallCheck(this, If); _this = _super.call(this, json); _this.condition = build(json.condition); _this.th = build(json.then); _this.els = build(json.else); return _this; } _createClass(If, [{ key: "exec", value: function exec(ctx) { if (this.condition.execute(ctx)) { return this.th.execute(ctx); } else { return this.els.execute(ctx); } } }]); return If; }(Expression); var CaseItem = function CaseItem(json) { _classCallCheck(this, CaseItem); this.when = build(json.when); this.then = build(json.then); }; var Case = /*#__PURE__*/function (_Expression2) { _inherits(Case, _Expression2); var _super2 = _createSuper(Case); function Case(json) { var _this2; _classCallCheck(this, Case); _this2 = _super2.call(this, json); _this2.comparand = build(json.comparand); _this2.caseItems = json.caseItem.map(function (ci) { return new CaseItem(ci); }); _this2.els = build(json.else); return _this2; } _createClass(Case, [{ key: "exec", value: function exec(ctx) { if (this.comparand) { return this.exec_selected(ctx); } else { return this.exec_standard(ctx); } } }, { key: "exec_selected", value: function exec_selected(ctx) { var val = this.comparand.execute(ctx); var _iterator = _createForOfIteratorHelper(this.caseItems), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var ci = _step.value; if (equals(ci.when.execute(ctx), val)) { return ci.then.execute(ctx); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return this.els.execute(ctx); } }, { key: "exec_standard", value: function exec_standard(ctx) { var _iterator2 = _createForOfIteratorHelper(this.caseItems), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var ci = _step2.value; if (ci.when.execute(ctx)) { return ci.then.execute(ctx); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return this.els.execute(ctx); } }]); return Case; }(Expression); module.exports = { Case: Case, CaseItem: CaseItem, If: If }; },{"../util/comparison":173,"./builder":144,"./expression":150}],148:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } 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 _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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var _require2 = require('./builder'), build = _require2.build; var _require3 = require('./literal'), Literal = _require3.Literal; var DT = require('../datatypes/datatypes'); var DateTime = /*#__PURE__*/function (_Expression) { _inherits(DateTime, _Expression); var _super = _createSuper(DateTime); function DateTime(json) { var _this; _classCallCheck(this, DateTime); _this = _super.call(this, json); _this.json = json; return _this; } _createClass(DateTime, [{ key: "exec", value: function exec(ctx) { var _this2 = this; var _iterator = _createForOfIteratorHelper(DateTime.PROPERTIES), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var property = _step.value; // if json does not contain 'timezoneOffset' set it to the executionDateTime from the context if (this.json[property] != null) { this[property] = build(this.json[property]); } else if (property === 'timezoneOffset' && ctx.getTimezoneOffset() != null) { this[property] = Literal.from({ type: 'Literal', value: ctx.getTimezoneOffset(), valueType: '{urn:hl7-org:elm-types:r1}Integer' }); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } var args = DateTime.PROPERTIES.map(function (p) { return _this2[p] != null ? _this2[p].execute(ctx) : undefined; }); return _construct(DT.DateTime, _toConsumableArray(args)); } }]); return DateTime; }(Expression); DateTime.PROPERTIES = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond', 'timezoneOffset']; var _Date = /*#__PURE__*/function (_Expression2) { _inherits(_Date, _Expression2); var _super2 = _createSuper(_Date); function _Date(json) { var _this3; _classCallCheck(this, _Date); _this3 = _super2.call(this, json); _this3.json = json; return _this3; } _createClass(_Date, [{ key: "exec", value: function exec(ctx) { var _this4 = this; var _iterator2 = _createForOfIteratorHelper(_Date.PROPERTIES), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var property = _step2.value; if (this.json[property] != null) { this[property] = build(this.json[property]); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } var args = _Date.PROPERTIES.map(function (p) { return _this4[p] != null ? _this4[p].execute(ctx) : undefined; }); return _construct(DT.Date, _toConsumableArray(args)); } }]); return _Date; }(Expression); _Date.PROPERTIES = ['year', 'month', 'day']; var Time = /*#__PURE__*/function (_Expression3) { _inherits(Time, _Expression3); var _super3 = _createSuper(Time); function Time(json) { var _this5; _classCallCheck(this, Time); _this5 = _super3.call(this, json); var _iterator3 = _createForOfIteratorHelper(Time.PROPERTIES), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var property = _step3.value; if (json[property] != null) { _this5[property] = build(json[property]); } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return _this5; } _createClass(Time, [{ key: "exec", value: function exec(ctx) { var _this6 = this; var args = Time.PROPERTIES.map(function (p) { return _this6[p] != null ? _this6[p].execute(ctx) : undefined; }); return _construct(DT.DateTime, [0, 1, 1].concat(_toConsumableArray(args))).getTime(); } }]); return Time; }(Expression); Time.PROPERTIES = ['hour', 'minute', 'second', 'millisecond']; var Today = /*#__PURE__*/function (_Expression4) { _inherits(Today, _Expression4); var _super4 = _createSuper(Today); function Today(json) { _classCallCheck(this, Today); return _super4.call(this, json); } _createClass(Today, [{ key: "exec", value: function exec(ctx) { return ctx.getExecutionDateTime().getDate(); } }]); return Today; }(Expression); var Now = /*#__PURE__*/function (_Expression5) { _inherits(Now, _Expression5); var _super5 = _createSuper(Now); function Now(json) { _classCallCheck(this, Now); return _super5.call(this, json); } _createClass(Now, [{ key: "exec", value: function exec(ctx) { return ctx.getExecutionDateTime(); } }]); return Now; }(Expression); var TimeOfDay = /*#__PURE__*/function (_Expression6) { _inherits(TimeOfDay, _Expression6); var _super6 = _createSuper(TimeOfDay); function TimeOfDay(json) { _classCallCheck(this, TimeOfDay); return _super6.call(this, json); } _createClass(TimeOfDay, [{ key: "exec", value: function exec(ctx) { return ctx.getExecutionDateTime().getTime(); } }]); return TimeOfDay; }(Expression); var DateTimeComponentFrom = /*#__PURE__*/function (_Expression7) { _inherits(DateTimeComponentFrom, _Expression7); var _super7 = _createSuper(DateTimeComponentFrom); function DateTimeComponentFrom(json) { var _this7; _classCallCheck(this, DateTimeComponentFrom); _this7 = _super7.call(this, json); _this7.precision = json.precision; return _this7; } _createClass(DateTimeComponentFrom, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg != null) { return arg[this.precision.toLowerCase()]; } else { return null; } } }]); return DateTimeComponentFrom; }(Expression); var DateFrom = /*#__PURE__*/function (_Expression8) { _inherits(DateFrom, _Expression8); var _super8 = _createSuper(DateFrom); function DateFrom(json) { _classCallCheck(this, DateFrom); return _super8.call(this, json); } _createClass(DateFrom, [{ key: "exec", value: function exec(ctx) { var date = this.execArgs(ctx); if (date != null) { return date.getDate(); } else { return null; } } }]); return DateFrom; }(Expression); var TimeFrom = /*#__PURE__*/function (_Expression9) { _inherits(TimeFrom, _Expression9); var _super9 = _createSuper(TimeFrom); function TimeFrom(json) { _classCallCheck(this, TimeFrom); return _super9.call(this, json); } _createClass(TimeFrom, [{ key: "exec", value: function exec(ctx) { var date = this.execArgs(ctx); if (date != null) { return date.getTime(); } else { return null; } } }]); return TimeFrom; }(Expression); var TimezoneOffsetFrom = /*#__PURE__*/function (_Expression10) { _inherits(TimezoneOffsetFrom, _Expression10); var _super10 = _createSuper(TimezoneOffsetFrom); function TimezoneOffsetFrom(json) { _classCallCheck(this, TimezoneOffsetFrom); return _super10.call(this, json); } _createClass(TimezoneOffsetFrom, [{ key: "exec", value: function exec(ctx) { var date = this.execArgs(ctx); if (date != null) { return date.timezoneOffset; } else { return null; } } }]); return TimezoneOffsetFrom; }(Expression); // Delegated to by overloaded#After function doAfter(a, b, precision) { return a.after(b, precision); } // Delegated to by overloaded#Before function doBefore(a, b, precision) { return a.before(b, precision); } var DifferenceBetween = /*#__PURE__*/function (_Expression11) { _inherits(DifferenceBetween, _Expression11); var _super11 = _createSuper(DifferenceBetween); function DifferenceBetween(json) { var _this8; _classCallCheck(this, DifferenceBetween); _this8 = _super11.call(this, json); _this8.precision = json.precision; return _this8; } _createClass(DifferenceBetween, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx); // Check to make sure args exist and that they have differenceBetween functions so that they can be compared to one another if (args[0] == null || args[1] == null || typeof args[0].differenceBetween !== 'function' || typeof args[1].differenceBetween !== 'function') { return null; } var result = args[0].differenceBetween(args[1], this.precision != null ? this.precision.toLowerCase() : undefined); if (result != null && result.isPoint()) { return result.low; } else { return result; } } }]); return DifferenceBetween; }(Expression); var DurationBetween = /*#__PURE__*/function (_Expression12) { _inherits(DurationBetween, _Expression12); var _super12 = _createSuper(DurationBetween); function DurationBetween(json) { var _this9; _classCallCheck(this, DurationBetween); _this9 = _super12.call(this, json); _this9.precision = json.precision; return _this9; } _createClass(DurationBetween, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx); // Check to make sure args exist and that they have durationBetween functions so that they can be compared to one another if (args[0] == null || args[1] == null || typeof args[0].durationBetween !== 'function' || typeof args[1].durationBetween !== 'function') { return null; } var result = args[0].durationBetween(args[1], this.precision != null ? this.precision.toLowerCase() : undefined); if (result != null && result.isPoint()) { return result.low; } else { return result; } } }]); return DurationBetween; }(Expression); module.exports = { Date: _Date, DateFrom: DateFrom, DateTime: DateTime, DateTimeComponentFrom: DateTimeComponentFrom, DifferenceBetween: DifferenceBetween, DurationBetween: DurationBetween, Now: Now, Time: Time, TimeFrom: TimeFrom, TimeOfDay: TimeOfDay, TimezoneOffsetFrom: TimezoneOffsetFrom, Today: Today, doAfter: doAfter, doBefore: doBefore }; },{"../datatypes/datatypes":134,"./builder":144,"./expression":150,"./literal":157}],149:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), UnimplementedExpression = _require.UnimplementedExpression; var UsingDef = /*#__PURE__*/function (_UnimplementedExpress) { _inherits(UsingDef, _UnimplementedExpress); var _super = _createSuper(UsingDef); function UsingDef() { _classCallCheck(this, UsingDef); return _super.apply(this, arguments); } return UsingDef; }(UnimplementedExpression); var IncludeDef = /*#__PURE__*/function (_UnimplementedExpress2) { _inherits(IncludeDef, _UnimplementedExpress2); var _super2 = _createSuper(IncludeDef); function IncludeDef() { _classCallCheck(this, IncludeDef); return _super2.apply(this, arguments); } return IncludeDef; }(UnimplementedExpression); var VersionedIdentifier = /*#__PURE__*/function (_UnimplementedExpress3) { _inherits(VersionedIdentifier, _UnimplementedExpress3); var _super3 = _createSuper(VersionedIdentifier); function VersionedIdentifier() { _classCallCheck(this, VersionedIdentifier); return _super3.apply(this, arguments); } return VersionedIdentifier; }(UnimplementedExpression); module.exports = { UsingDef: UsingDef, IncludeDef: IncludeDef, VersionedIdentifier: VersionedIdentifier }; },{"./expression":150}],150:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 = require('./builder'), build = _require.build; var _require2 = require('../util/util'), typeIsArray = _require2.typeIsArray; var Expression = /*#__PURE__*/function () { function Expression(json) { _classCallCheck(this, Expression); if (json.operand != null) { var op = build(json.operand); if (typeIsArray(json.operand)) { this.args = op; } else { this.arg = op; } } if (json.localId != null) { this.localId = json.localId; } } _createClass(Expression, [{ key: "execute", value: function execute(ctx) { if (this.localId != null) { // Store the localId and result on the root context of this library var execValue = this.exec(ctx); ctx.rootContext().setLocalIdWithResult(this.localId, execValue); return execValue; } else { return this.exec(ctx); } } }, { key: "exec", value: function exec(ctx) { return this; } }, { key: "execArgs", value: function execArgs(ctx) { switch (false) { case this.args == null: return this.args.map(function (arg) { return arg.execute(ctx); }); case this.arg == null: return this.arg.execute(ctx); default: return null; } } }]); return Expression; }(); var UnimplementedExpression = /*#__PURE__*/function (_Expression) { _inherits(UnimplementedExpression, _Expression); var _super = _createSuper(UnimplementedExpression); function UnimplementedExpression(json) { var _this; _classCallCheck(this, UnimplementedExpression); _this = _super.call(this, json); _this.json = json; return _this; } _createClass(UnimplementedExpression, [{ key: "exec", value: function exec(ctx) { throw new Error("Unimplemented Expression: ".concat(this.json.type)); } }]); return UnimplementedExpression; }(Expression); module.exports = { Expression: Expression, UnimplementedExpression: UnimplementedExpression }; },{"../util/util":176,"./builder":144}],151:[function(require,module,exports){ "use strict"; var expression = require('./expression'); var aggregate = require('./aggregate'); var arithmetic = require('./arithmetic'); var clinical = require('./clinical'); var comparison = require('./comparison'); var conditional = require('./conditional'); var datetime = require('./datetime'); var declaration = require('./declaration'); var external = require('./external'); var instance = require('./instance'); var interval = require('./interval'); var list = require('./list'); var literal = require('./literal'); var logical = require('./logical'); var nullological = require('./nullological'); var parameters = require('./parameters'); var quantity = require('./quantity'); var query = require('./query'); var ratio = require('./ratio'); var reusable = require('./reusable'); var string = require('./string'); var structured = require('./structured'); var type = require('./type'); var overloaded = require('./overloaded'); var libs = [expression, aggregate, arithmetic, clinical, comparison, conditional, datetime, declaration, external, instance, interval, list, literal, logical, nullological, parameters, query, quantity, ratio, reusable, string, structured, type, overloaded]; for (var _i = 0, _libs = libs; _i < _libs.length; _i++) { var lib = _libs[_i]; for (var _i2 = 0, _Object$keys = Object.keys(lib); _i2 < _Object$keys.length; _i2++) { var element = _Object$keys[_i2]; module.exports[element] = lib[element]; } } },{"./aggregate":142,"./arithmetic":143,"./clinical":145,"./comparison":146,"./conditional":147,"./datetime":148,"./declaration":149,"./expression":150,"./external":152,"./instance":153,"./interval":154,"./list":156,"./literal":157,"./logical":158,"./nullological":159,"./overloaded":160,"./parameters":161,"./quantity":162,"./query":163,"./ratio":164,"./reusable":165,"./string":166,"./structured":167,"./type":168}],152:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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" && Symbol.iterator in Object(iter)) 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 _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 _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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var _require2 = require('./builder'), build = _require2.build; var _require3 = require('../util/util'), typeIsArray = _require3.typeIsArray; var Retrieve = /*#__PURE__*/function (_Expression) { _inherits(Retrieve, _Expression); var _super = _createSuper(Retrieve); function Retrieve(json) { var _this; _classCallCheck(this, Retrieve); _this = _super.call(this, json); _this.datatype = json.dataType; _this.templateId = json.templateId; _this.codeProperty = json.codeProperty; _this.codes = build(json.codes); _this.dateProperty = json.dateProperty; _this.dateRange = build(json.dateRange); return _this; } _createClass(Retrieve, [{ key: "exec", value: function exec(ctx) { var _this2 = this; var records = ctx.findRecords(this.templateId != null ? this.templateId : this.datatype); var codes = this.codes; if (this.codes && typeof this.codes.exec === 'function') { codes = this.codes.execute(ctx); if (codes == null) { return []; } } if (codes) { records = records.filter(function (r) { return _this2.recordMatchesCodesOrVS(r, codes); }); } // TODO: Added @dateProperty check due to previous fix in cql4browsers in cql_qdm_patient_api hash: ddbc57 if (this.dateRange && this.dateProperty) { var range = this.dateRange.execute(ctx); records = records.filter(function (r) { return range.includes(r.getDateOrInterval(_this2.dateProperty)); }); } if (Array.isArray(records)) { var _ctx$evaluatedRecords; (_ctx$evaluatedRecords = ctx.evaluatedRecords).push.apply(_ctx$evaluatedRecords, _toConsumableArray(records)); } else { ctx.evaluatedRecords.push(records); } return records; } }, { key: "recordMatchesCodesOrVS", value: function recordMatchesCodesOrVS(record, codes) { var _this3 = this; if (typeIsArray(codes)) { return codes.some(function (c) { return c.hasMatch(record.getCode(_this3.codeProperty)); }); } else { return codes.hasMatch(record.getCode(this.codeProperty)); } } }]); return Retrieve; }(Expression); module.exports = { Retrieve: Retrieve }; },{"../util/util":176,"./builder":144,"./expression":150}],153:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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 _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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 = require('./expression'), Expression = _require.Expression; var _require2 = require('./builder'), build = _require2.build; var _require3 = require('../datatypes/quantity'), Quantity = _require3.Quantity; var _require4 = require('../datatypes/datatypes'), Code = _require4.Code, Concept = _require4.Concept; var Element = /*#__PURE__*/function () { function Element(json) { _classCallCheck(this, Element); this.name = json.name; this.value = build(json.value); } _createClass(Element, [{ key: "exec", value: function exec(ctx) { return this.value != null ? this.value.execute(ctx) : undefined; } }]); return Element; }(); var Instance = /*#__PURE__*/function (_Expression) { _inherits(Instance, _Expression); var _super = _createSuper(Instance); function Instance(json) { var _this; _classCallCheck(this, Instance); _this = _super.call(this, json); _this.classType = json.classType; _this.element = json.element.map(function (child) { return new Element(child); }); return _this; } _createClass(Instance, [{ key: "exec", value: function exec(ctx) { var obj = {}; var _iterator = _createForOfIteratorHelper(this.element), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var el = _step.value; obj[el.name] = el.exec(ctx); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } switch (this.classType) { case '{urn:hl7-org:elm-types:r1}Quantity': return new Quantity(obj.value, obj.unit); case '{urn:hl7-org:elm-types:r1}Code': return new Code(obj.code, obj.system, obj.version, obj.display); case '{urn:hl7-org:elm-types:r1}Concept': return new Concept(obj.codes, obj.display); default: return obj; } } }]); return Instance; }(Expression); module.exports = { Instance: Instance }; },{"../datatypes/datatypes":134,"../datatypes/quantity":139,"./builder":144,"./expression":150}],154:[function(require,module,exports){ "use strict"; 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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(_e2) { throw _e2; }, 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 = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; 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) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var _require2 = require('./builder'), build = _require2.build; var _require3 = require('../datatypes/quantity'), Quantity = _require3.Quantity, doAddition = _require3.doAddition; var _require4 = require('../util/math'), successor = _require4.successor, predecessor = _require4.predecessor, MAX_DATETIME_VALUE = _require4.MAX_DATETIME_VALUE, MIN_DATETIME_VALUE = _require4.MIN_DATETIME_VALUE; var _require5 = require('../util/units'), convertUnit = _require5.convertUnit, compareUnits = _require5.compareUnits, convertToCQLDateUnit = _require5.convertToCQLDateUnit; var dtivl = require('../datatypes/interval'); var Interval = /*#__PURE__*/function (_Expression) { _inherits(Interval, _Expression); var _super = _createSuper(Interval); function Interval(json) { var _this; _classCallCheck(this, Interval); _this = _super.call(this, json); _this.lowClosed = json.lowClosed; _this.lowClosedExpression = build(json.lowClosedExpression); _this.highClosed = json.highClosed; _this.highClosedExpression = build(json.highClosedExpression); _this.low = build(json.low); _this.high = build(json.high); return _this; } // Define a simple getter to allow type-checking of this class without instanceof // and in a way that survives minification (as opposed to checking constructor.name) _createClass(Interval, [{ key: "exec", value: function exec(ctx) { var lowValue = this.low.execute(ctx); var highValue = this.high.execute(ctx); var lowClosed = this.lowClosed != null ? this.lowClosed : this.lowClosedExpression && this.lowClosedExpression.execute(ctx); var highClosed = this.highClosed != null ? this.highClosed : this.highClosedExpression && this.highClosedExpression.execute(ctx); var defaultPointType; if (lowValue == null && highValue == null) { // try to get the default point type from a cast if (this.low.asTypeSpecifier && this.low.asTypeSpecifier.type === 'NamedTypeSpecifier') { defaultPointType = this.low.asTypeSpecifier.name; } else if (this.high.asTypeSpecifier && this.high.asTypeSpecifier.type === 'NamedTypeSpecifier') { defaultPointType = this.high.asTypeSpecifier.name; } } return new dtivl.Interval(lowValue, highValue, lowClosed, highClosed, defaultPointType); } }, { key: "isInterval", get: function get() { return true; } }]); return Interval; }(Expression); // Equal is completely handled by overloaded#Equal // NotEqual is completely handled by overloaded#Equal // Delegated to by overloaded#Contains and overloaded#In function doContains(interval, item, precision) { return interval.contains(item, precision); } // Delegated to by overloaded#Includes and overloaded#IncludedIn function doIncludes(interval, subinterval, precision) { return interval.includes(subinterval, precision); } // Delegated to by overloaded#ProperIncludes and overloaded@ProperIncludedIn function doProperIncludes(interval, subinterval, precision) { return interval.properlyIncludes(subinterval, precision); } // Delegated to by overloaded#After function doAfter(a, b, precision) { return a.after(b, precision); } // Delegated to by overloaded#Before function doBefore(a, b, precision) { return a.before(b, precision); } var Meets = /*#__PURE__*/function (_Expression2) { _inherits(Meets, _Expression2); var _super2 = _createSuper(Meets); function Meets(json) { var _this2; _classCallCheck(this, Meets); _this2 = _super2.call(this, json); _this2.precision = json.precision != null ? json.precision.toLowerCase() : undefined; return _this2; } _createClass(Meets, [{ key: "exec", value: function exec(ctx) { var _this$execArgs = this.execArgs(ctx), _this$execArgs2 = _slicedToArray(_this$execArgs, 2), a = _this$execArgs2[0], b = _this$execArgs2[1]; if (a != null && b != null) { return a.meets(b, this.precision); } else { return null; } } }]); return Meets; }(Expression); var MeetsAfter = /*#__PURE__*/function (_Expression3) { _inherits(MeetsAfter, _Expression3); var _super3 = _createSuper(MeetsAfter); function MeetsAfter(json) { var _this3; _classCallCheck(this, MeetsAfter); _this3 = _super3.call(this, json); _this3.precision = json.precision != null ? json.precision.toLowerCase() : undefined; return _this3; } _createClass(MeetsAfter, [{ key: "exec", value: function exec(ctx) { var _this$execArgs3 = this.execArgs(ctx), _this$execArgs4 = _slicedToArray(_this$execArgs3, 2), a = _this$execArgs4[0], b = _this$execArgs4[1]; if (a != null && b != null) { return a.meetsAfter(b, this.precision); } else { return null; } } }]); return MeetsAfter; }(Expression); var MeetsBefore = /*#__PURE__*/function (_Expression4) { _inherits(MeetsBefore, _Expression4); var _super4 = _createSuper(MeetsBefore); function MeetsBefore(json) { var _this4; _classCallCheck(this, MeetsBefore); _this4 = _super4.call(this, json); _this4.precision = json.precision != null ? json.precision.toLowerCase() : undefined; return _this4; } _createClass(MeetsBefore, [{ key: "exec", value: function exec(ctx) { var _this$execArgs5 = this.execArgs(ctx), _this$execArgs6 = _slicedToArray(_this$execArgs5, 2), a = _this$execArgs6[0], b = _this$execArgs6[1]; if (a != null && b != null) { return a.meetsBefore(b, this.precision); } else { return null; } } }]); return MeetsBefore; }(Expression); var Overlaps = /*#__PURE__*/function (_Expression5) { _inherits(Overlaps, _Expression5); var _super5 = _createSuper(Overlaps); function Overlaps(json) { var _this5; _classCallCheck(this, Overlaps); _this5 = _super5.call(this, json); _this5.precision = json.precision != null ? json.precision.toLowerCase() : undefined; return _this5; } _createClass(Overlaps, [{ key: "exec", value: function exec(ctx) { var _this$execArgs7 = this.execArgs(ctx), _this$execArgs8 = _slicedToArray(_this$execArgs7, 2), a = _this$execArgs8[0], b = _this$execArgs8[1]; if (a != null && b != null) { return a.overlaps(b, this.precision); } else { return null; } } }]); return Overlaps; }(Expression); var OverlapsAfter = /*#__PURE__*/function (_Expression6) { _inherits(OverlapsAfter, _Expression6); var _super6 = _createSuper(OverlapsAfter); function OverlapsAfter(json) { var _this6; _classCallCheck(this, OverlapsAfter); _this6 = _super6.call(this, json); _this6.precision = json.precision != null ? json.precision.toLowerCase() : undefined; return _this6; } _createClass(OverlapsAfter, [{ key: "exec", value: function exec(ctx) { var _this$execArgs9 = this.execArgs(ctx), _this$execArgs10 = _slicedToArray(_this$execArgs9, 2), a = _this$execArgs10[0], b = _this$execArgs10[1]; if (a != null && b != null) { return a.overlapsAfter(b, this.precision); } else { return null; } } }]); return OverlapsAfter; }(Expression); var OverlapsBefore = /*#__PURE__*/function (_Expression7) { _inherits(OverlapsBefore, _Expression7); var _super7 = _createSuper(OverlapsBefore); function OverlapsBefore(json) { var _this7; _classCallCheck(this, OverlapsBefore); _this7 = _super7.call(this, json); _this7.precision = json.precision != null ? json.precision.toLowerCase() : undefined; return _this7; } _createClass(OverlapsBefore, [{ key: "exec", value: function exec(ctx) { var _this$execArgs11 = this.execArgs(ctx), _this$execArgs12 = _slicedToArray(_this$execArgs11, 2), a = _this$execArgs12[0], b = _this$execArgs12[1]; if (a != null && b != null) { return a.overlapsBefore(b, this.precision); } else { return null; } } }]); return OverlapsBefore; }(Expression); // Delegated to by overloaded#Union function doUnion(a, b) { return a.union(b); } // Delegated to by overloaded#Except function doExcept(a, b) { if (a != null && b != null) { return a.except(b); } else { return null; } } // Delegated to by overloaded#Intersect function doIntersect(a, b) { if (a != null && b != null) { return a.intersect(b); } else { return null; } } var Width = /*#__PURE__*/function (_Expression8) { _inherits(Width, _Expression8); var _super8 = _createSuper(Width); function Width(json) { _classCallCheck(this, Width); return _super8.call(this, json); } _createClass(Width, [{ key: "exec", value: function exec(ctx) { var interval = this.arg.execute(ctx); if (interval == null) { return null; } return interval.width(); } }]); return Width; }(Expression); var Size = /*#__PURE__*/function (_Expression9) { _inherits(Size, _Expression9); var _super9 = _createSuper(Size); function Size(json) { _classCallCheck(this, Size); return _super9.call(this, json); } _createClass(Size, [{ key: "exec", value: function exec(ctx) { var interval = this.arg.execute(ctx); if (interval == null) { return null; } return interval.size(); } }]); return Size; }(Expression); var Start = /*#__PURE__*/function (_Expression10) { _inherits(Start, _Expression10); var _super10 = _createSuper(Start); function Start(json) { _classCallCheck(this, Start); return _super10.call(this, json); } _createClass(Start, [{ key: "exec", value: function exec(ctx) { var interval = this.arg.execute(ctx); if (interval == null) { return null; } var start = interval.start(); // fix the timezoneOffset of minimum Datetime to match context offset if (start && start.isDateTime && start.equals(MIN_DATETIME_VALUE)) { start.timezoneOffset = ctx.getTimezoneOffset(); } return start; } }]); return Start; }(Expression); var End = /*#__PURE__*/function (_Expression11) { _inherits(End, _Expression11); var _super11 = _createSuper(End); function End(json) { _classCallCheck(this, End); return _super11.call(this, json); } _createClass(End, [{ key: "exec", value: function exec(ctx) { var interval = this.arg.execute(ctx); if (interval == null) { return null; } var end = interval.end(); // fix the timezoneOffset of maximum Datetime to match context offset if (end && end.isDateTime && end.equals(MAX_DATETIME_VALUE)) { end.timezoneOffset = ctx.getTimezoneOffset(); } return end; } }]); return End; }(Expression); var Starts = /*#__PURE__*/function (_Expression12) { _inherits(Starts, _Expression12); var _super12 = _createSuper(Starts); function Starts(json) { var _this8; _classCallCheck(this, Starts); _this8 = _super12.call(this, json); _this8.precision = json.precision != null ? json.precision.toLowerCase() : undefined; return _this8; } _createClass(Starts, [{ key: "exec", value: function exec(ctx) { var _this$execArgs13 = this.execArgs(ctx), _this$execArgs14 = _slicedToArray(_this$execArgs13, 2), a = _this$execArgs14[0], b = _this$execArgs14[1]; if (a != null && b != null) { return a.starts(b, this.precision); } else { return null; } } }]); return Starts; }(Expression); var Ends = /*#__PURE__*/function (_Expression13) { _inherits(Ends, _Expression13); var _super13 = _createSuper(Ends); function Ends(json) { var _this9; _classCallCheck(this, Ends); _this9 = _super13.call(this, json); _this9.precision = json.precision != null ? json.precision.toLowerCase() : undefined; return _this9; } _createClass(Ends, [{ key: "exec", value: function exec(ctx) { var _this$execArgs15 = this.execArgs(ctx), _this$execArgs16 = _slicedToArray(_this$execArgs15, 2), a = _this$execArgs16[0], b = _this$execArgs16[1]; if (a != null && b != null) { return a.ends(b, this.precision); } else { return null; } } }]); return Ends; }(Expression); function intervalListType(intervals) { // Returns one of null, 'time', 'date', 'datetime', 'quantity', 'integer', 'decimal' or 'mismatch' var type = null; var _iterator = _createForOfIteratorHelper(intervals), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var itvl = _step.value; if (itvl == null) { continue; } if (itvl.low == null && itvl.high == null) { //can't really determine type from this continue; } // if one end is null (but not both), the type can be determined from the other end var low = itvl.low != null ? itvl.low : itvl.high; var high = itvl.high != null ? itvl.high : itvl.low; if (low.isTime && low.isTime() && high.isTime && high.isTime()) { if (type == null) { type = 'time'; } else if (type === 'time') { continue; } else { return 'mismatch'; } // if an interval mixes date and datetime, type is datetime (for implicit conversion) } else if ((low.isDateTime || high.isDateTime) && (low.isDateTime || low.isDate) && (high.isDateTime || high.isDate)) { if (type == null || type === 'date') { type = 'datetime'; } else if (type === 'datetime') { continue; } else { return 'mismatch'; } } else if (low.isDate && high.isDate) { if (type == null) { type = 'date'; } else if (type === 'date' || type === 'datetime') { continue; } else { return 'mismatch'; } } else if (low.isQuantity && high.isQuantity) { if (type == null) { type = 'quantity'; } else if (type === 'quantity') { continue; } else { return 'mismatch'; } } else if (Number.isInteger(low) && Number.isInteger(high)) { if (type == null) { type = 'integer'; } else if (type === 'integer' || type === 'decimal') { continue; } else { return 'mismatch'; } } else if (typeof low === 'number' && typeof high === 'number') { if (type == null || type === 'integer') { type = 'decimal'; } else if (type === 'decimal') { continue; } else { return 'mismatch'; } //if we are here ends are mismatched } else { return 'mismatch'; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return type; } var Expand = /*#__PURE__*/function (_Expression14) { _inherits(Expand, _Expression14); var _super14 = _createSuper(Expand); function Expand(json) { _classCallCheck(this, Expand); return _super14.call(this, json); } _createClass(Expand, [{ key: "exec", value: function exec(ctx) { // expand(argument List>, per Quantity) List> var defaultPer, expandFunction; var _this$execArgs17 = this.execArgs(ctx), _this$execArgs18 = _slicedToArray(_this$execArgs17, 2), intervals = _this$execArgs18[0], per = _this$execArgs18[1]; var type = intervalListType(intervals); if (type === 'mismatch') { throw new Error('List of intervals contains mismatched types.'); } if (type == null) { return null; } // this step collapses overlaps, and also returns a clone of intervals so we can feel free to mutate intervals = collapseIntervals(intervals, per); if (intervals.length === 0) { return []; } if (['time', 'date', 'datetime'].includes(type)) { expandFunction = this.expandDTishInterval; defaultPer = function defaultPer(interval) { return new Quantity(1, interval.low.getPrecision()); }; } else if (['quantity'].includes(type)) { expandFunction = this.expandQuantityInterval; defaultPer = function defaultPer(interval) { return new Quantity(1, interval.low.unit); }; } else if (['integer', 'decimal'].includes(type)) { expandFunction = this.expandNumericInterval; defaultPer = function defaultPer(interval) { return new Quantity(1, '1'); }; } else { throw new Error('Interval list type not yet supported.'); } var results = []; var _iterator2 = _createForOfIteratorHelper(intervals), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var interval = _step2.value; if (interval == null) { continue; } // We do not support open ended intervals since result would likely be too long if (interval.low == null || interval.high == null) { return null; } if (type === 'datetime') { //support for implicitly converting dates to datetime interval.low = interval.low.getDateTime(); interval.high = interval.high.getDateTime(); } per = per != null ? per : defaultPer(interval); var items = expandFunction.call(this, interval, per); if (items === null) { return null; } results.push.apply(results, _toConsumableArray(items || [])); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return results; } }, { key: "expandDTishInterval", value: function expandDTishInterval(interval, per) { per.unit = convertToCQLDateUnit(per.unit); if (per.unit === 'week') { per.value *= 7; per.unit = 'day'; } // Precision Checks // return null if precision not applicable (e.g. gram, or minutes for dates) if (!interval.low.constructor.FIELDS.includes(per.unit)) { return null; } // open interval with null boundaries do not contribute to output // closed interval with null boundaries are not allowed for performance reasons if (interval.low == null || interval.high == null) { return null; } var low = interval.lowClosed ? interval.low : interval.low.successor(); var high = interval.highClosed ? interval.high : interval.high.predecessor(); if (low.after(high)) { return []; } if (interval.low.isLessPrecise(per.unit) || interval.high.isLessPrecise(per.unit)) { return []; } var current_low = low; var results = []; low = this.truncateToPrecision(low, per.unit); high = this.truncateToPrecision(high, per.unit); var current_high = current_low.add(per.value, per.unit).predecessor(); var intervalToAdd = new dtivl.Interval(current_low, current_high, true, true); while (intervalToAdd.high.sameOrBefore(high)) { results.push(intervalToAdd); current_low = current_low.add(per.value, per.unit); current_high = current_low.add(per.value, per.unit).predecessor(); intervalToAdd = new dtivl.Interval(current_low, current_high, true, true); } return results; } }, { key: "truncateToPrecision", value: function truncateToPrecision(value, unit) { // If interval boundaries are more precise than per quantity, truncate to // the precision specified by the per var shouldTruncate = false; var _iterator3 = _createForOfIteratorHelper(value.constructor.FIELDS), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var field = _step3.value; if (shouldTruncate) { value[field] = null; } if (field === unit) { // Start truncating after this unit shouldTruncate = true; } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return value; } }, { key: "expandQuantityInterval", value: function expandQuantityInterval(interval, per) { // we want to convert everything to the more precise of the interval.low or per var result_units; if (compareUnits(interval.low.unit, per.unit) > 0) { //interval.low.unit is 'bigger' aka les precise result_units = per.unit; } else { result_units = interval.low.unit; } var low_value = convertUnit(interval.low.value, interval.low.unit, result_units); var high_value = convertUnit(interval.high.value, interval.high.unit, result_units); var per_value = convertUnit(per.value, per.unit, result_units); // return null if unit conversion failed, must have mismatched units if (!(low_value != null && high_value != null && per_value != null)) { return null; } var results = this.makeNumericIntervalList(low_value, high_value, interval.lowClosed, interval.highClosed, per_value); var _iterator4 = _createForOfIteratorHelper(results), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var itvl = _step4.value; itvl.low = new Quantity(itvl.low, result_units); itvl.high = new Quantity(itvl.high, result_units); } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } return results; } }, { key: "expandNumericInterval", value: function expandNumericInterval(interval, per) { if (per.unit !== '1' && per.unit !== '') { return null; } return this.makeNumericIntervalList(interval.low, interval.high, interval.lowClosed, interval.highClosed, per.value); } }, { key: "makeNumericIntervalList", value: function makeNumericIntervalList(low, high, lowClosed, highClosed, perValue) { // If the per value is a Decimal (has a .), 8 decimal places are appropriate // Integers should have 0 Decimal places var perIsDecimal = perValue.toString().includes('.'); var decimalPrecision = perIsDecimal ? 8 : 0; low = lowClosed ? low : successor(low); high = highClosed ? high : predecessor(high); // If the interval boundaries are more precise than the per quantity, the // more precise values will be truncated to the precision specified by the // per quantity. low = truncateDecimal(low, decimalPrecision); high = truncateDecimal(high, decimalPrecision); if (low > high) { return []; } if (low == null || high == null) { return []; } var perUnitSize = perIsDecimal ? 0.00000001 : 1; if (low === high && Number.isInteger(low) && Number.isInteger(high) && !Number.isInteger(perValue)) { high = parseFloat((high + 1).toFixed(decimalPrecision)); } var current_low = low; var results = []; if (perValue > high - low + perUnitSize) { return []; } var current_high = parseFloat((current_low + perValue - perUnitSize).toFixed(decimalPrecision)); var intervalToAdd = new dtivl.Interval(current_low, current_high, true, true); while (intervalToAdd.high <= high) { results.push(intervalToAdd); current_low = parseFloat((current_low + perValue).toFixed(decimalPrecision)); current_high = parseFloat((current_low + perValue - perUnitSize).toFixed(decimalPrecision)); intervalToAdd = new dtivl.Interval(current_low, current_high, true, true); } return results; } }]); return Expand; }(Expression); var Collapse = /*#__PURE__*/function (_Expression15) { _inherits(Collapse, _Expression15); var _super15 = _createSuper(Collapse); function Collapse(json) { _classCallCheck(this, Collapse); return _super15.call(this, json); } _createClass(Collapse, [{ key: "exec", value: function exec(ctx) { // collapse(argument List>, per Quantity) List> var _this$execArgs19 = this.execArgs(ctx), _this$execArgs20 = _slicedToArray(_this$execArgs19, 2), intervals = _this$execArgs20[0], perWidth = _this$execArgs20[1]; return collapseIntervals(intervals, perWidth); } }]); return Collapse; }(Expression); function collapseIntervals(intervals, perWidth) { // Clone intervals so this function remains idempotent var intervalsClone = []; var _iterator5 = _createForOfIteratorHelper(intervals), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var interval = _step5.value; // The spec says to ignore null intervals if (interval != null) { intervalsClone.push(interval.copy()); } } // If the list is null, return null } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } if (intervals == null) { return null; } else if (intervalsClone.length <= 1) { return intervalsClone; } else { // If the per argument is null, the default unit interval for the point type // of the intervals involved will be used (i.e. the interval that has a // width equal to the result of the successor function for the point type). if (perWidth == null) { perWidth = intervalsClone[0].getPointSize(); } // sort intervalsClone by start intervalsClone.sort(function (a, b) { if (a.low && typeof a.low.before === 'function') { if (b.low != null && a.low.before(b.low)) { return -1; } if (b.low == null || a.low.after(b.low)) { return 1; } } else if (a.low != null && b.low != null) { if (a.low < b.low) { return -1; } if (a.low > b.low) { return 1; } } else if (a.low != null && b.low == null) { return 1; } else if (a.low == null && b.low != null) { return -1; } // if both lows are undefined, sort by high if (a.high && typeof a.high.before === 'function') { if (b.high == null || a.high.before(b.high)) { return -1; } if (a.high.after(b.high)) { return 1; } } else if (a.high != null && b.high != null) { if (a.high < b.high) { return -1; } if (a.high > b.high) { return 1; } } else if (a.high != null && b.high == null) { return -1; } else if (a.high == null && b.high != null) { return 1; } return 0; }); // collapse intervals as necessary var collapsedIntervals = []; var a = intervalsClone.shift(); var b = intervalsClone.shift(); while (b) { if (b.low && typeof b.low.durationBetween === 'function') { // handle DateTimes using durationBetween if (a.high != null ? a.high.sameOrAfter(b.low) : undefined) { // overlap if (b.high == null || b.high.after(a.high)) { a.high = b.high; } } else if ((a.high != null ? a.high.durationBetween(b.low, perWidth.unit).high : undefined) <= perWidth.value) { a.high = b.high; } else { collapsedIntervals.push(a); a = b; } } else if (b.low && typeof b.low.sameOrBefore === 'function') { if (a.high != null && b.low.sameOrBefore(doAddition(a.high, perWidth))) { if (b.high == null || b.high.after(a.high)) { a.high = b.high; } } else { collapsedIntervals.push(a); a = b; } } else { if (b.low - a.high <= perWidth.value) { if (b.high > a.high || b.high == null) { a.high = b.high; } } else { collapsedIntervals.push(a); a = b; } } b = intervalsClone.shift(); } collapsedIntervals.push(a); return collapsedIntervals; } } function truncateDecimal(decimal, decimalPlaces) { // like parseFloat().toFixed() but floor rather than round // Needed for when per precision is less than the interval input precision var re = new RegExp('^-?\\d+(?:.\\d{0,' + (decimalPlaces || -1) + '})?'); return parseFloat(decimal.toString().match(re)[0]); } module.exports = { Collapse: Collapse, End: End, Ends: Ends, Expand: Expand, Interval: Interval, Meets: Meets, MeetsAfter: MeetsAfter, MeetsBefore: MeetsBefore, Overlaps: Overlaps, OverlapsAfter: OverlapsAfter, OverlapsBefore: OverlapsBefore, Size: Size, Start: Start, Starts: Starts, Width: Width, doContains: doContains, doIncludes: doIncludes, doProperIncludes: doProperIncludes, doAfter: doAfter, doBefore: doBefore, doUnion: doUnion, doExcept: doExcept, doIntersect: doIntersect }; },{"../datatypes/interval":137,"../datatypes/quantity":139,"../util/math":174,"../util/units":175,"./builder":144,"./expression":150}],155:[function(require,module,exports){ "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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); return Constructor; } var Library = /*#__PURE__*/function () { function Library(json, libraryManager) { _classCallCheck(this, Library); this.source = json; // usings var usingDefs = json.library.usings && json.library.usings.def || []; this.usings = usingDefs.filter(function (u) { return u.localIdentifier !== 'System'; }).map(function (u) { return { name: u.localIdentifier, version: u.version }; }); // parameters var paramDefs = json.library.parameters && json.library.parameters.def || []; this.parameters = {}; var _iterator = _createForOfIteratorHelper(paramDefs), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var param = _step.value; this.parameters[param.name] = new ParameterDef(param); } // code systems } catch (err) { _iterator.e(err); } finally { _iterator.f(); } var csDefs = json.library.codeSystems && json.library.codeSystems.def || []; this.codesystems = {}; var _iterator2 = _createForOfIteratorHelper(csDefs), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var codesystem = _step2.value; this.codesystems[codesystem.name] = new CodeSystemDef(codesystem); } // value sets } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } var vsDefs = json.library.valueSets && json.library.valueSets.def || []; this.valuesets = {}; var _iterator3 = _createForOfIteratorHelper(vsDefs), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var valueset = _step3.value; this.valuesets[valueset.name] = new ValueSetDef(valueset); } // codes } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } var codeDefs = json.library.codes && json.library.codes.def || []; this.codes = {}; var _iterator4 = _createForOfIteratorHelper(codeDefs), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var code = _step4.value; this.codes[code.name] = new CodeDef(code); } // concepts } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } var conceptDefs = json.library.concepts && json.library.concepts.def || []; this.concepts = {}; var _iterator5 = _createForOfIteratorHelper(conceptDefs), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var concept = _step5.value; this.concepts[concept.name] = new ConceptDef(concept); } // expressions } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } var exprDefs = json.library.statements && json.library.statements.def || []; this.expressions = {}; this.functions = {}; var _iterator6 = _createForOfIteratorHelper(exprDefs), _step6; try { for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { var expr = _step6.value; if (expr.type === 'FunctionDef') { if (!this.functions[expr.name]) { this.functions[expr.name] = []; } this.functions[expr.name].push(new FunctionDef(expr)); } else { this.expressions[expr.name] = new ExpressionDef(expr); } } // includes } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } var inclDefs = json.library.includes && json.library.includes.def || []; this.includes = {}; var _iterator7 = _createForOfIteratorHelper(inclDefs), _step7; try { for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) { var incl = _step7.value; if (libraryManager) { this.includes[incl.localIdentifier] = libraryManager.resolve(incl.path, incl.version); } } } catch (err) { _iterator7.e(err); } finally { _iterator7.f(); } } _createClass(Library, [{ key: "getFunction", value: function getFunction(identifier) { return this.functions[identifier]; } }, { key: "get", value: function get(identifier) { return this.expressions[identifier] || this.includes[identifier] || this.getFunction(identifier); } }, { key: "getValueSet", value: function getValueSet(identifier, libraryName) { if (this.valuesets[identifier] != null) { return this.valuesets[identifier]; } return this.includes[libraryName] != null ? this.includes[libraryName].valuesets[identifier] : undefined; } }, { key: "getCodeSystem", value: function getCodeSystem(identifier) { return this.codesystems[identifier]; } }, { key: "getCode", value: function getCode(identifier) { return this.codes[identifier]; } }, { key: "getConcept", value: function getConcept(identifier) { return this.concepts[identifier]; } }, { key: "getParameter", value: function getParameter(name) { return this.parameters[name]; } }]); return Library; }(); // These requires are at the end of the file because having them first in the // file creates errors due to the order that the libraries are loaded. var _require = require('./expressions'), ExpressionDef = _require.ExpressionDef, FunctionDef = _require.FunctionDef, ParameterDef = _require.ParameterDef, ValueSetDef = _require.ValueSetDef, CodeSystemDef = _require.CodeSystemDef, CodeDef = _require.CodeDef, ConceptDef = _require.ConceptDef; module.exports = { Library: Library }; },{"./expressions":151}],156:[function(require,module,exports){ "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression, UnimplementedExpression = _require.UnimplementedExpression; var _require2 = require('./builder'), build = _require2.build; var _require3 = require('../util/util'), typeIsArray = _require3.typeIsArray; var _require4 = require('../util/comparison'), equals = _require4.equals; var List = /*#__PURE__*/function (_Expression) { _inherits(List, _Expression); var _super = _createSuper(List); function List(json) { var _this; _classCallCheck(this, List); _this = _super.call(this, json); _this.elements = build(json.element) || []; return _this; } _createClass(List, [{ key: "exec", value: function exec(ctx) { return this.elements.map(function (item) { return item.execute(ctx); }); } }, { key: "isList", get: function get() { return true; } }]); return List; }(Expression); var Exists = /*#__PURE__*/function (_Expression2) { _inherits(Exists, _Expression2); var _super2 = _createSuper(Exists); function Exists(json) { _classCallCheck(this, Exists); return _super2.call(this, json); } _createClass(Exists, [{ key: "exec", value: function exec(ctx) { var list = this.execArgs(ctx); // if list exists and has non empty length we need to make sure it isnt just full of nulls if (list) { return list.some(function (item) { return item != null; }); } return false; } }]); return Exists; }(Expression); // Equal is completely handled by overloaded#Equal // NotEqual is completely handled by overloaded#Equal // Delegated to by overloaded#Union function doUnion(a, b) { var distinct = doDistinct(a.concat(b)); return removeDuplicateNulls(distinct); } // Delegated to by overloaded#Except function doExcept(a, b) { var distinct = doDistinct(a); var setList = removeDuplicateNulls(distinct); return setList.filter(function (item) { return !doContains(b, item, true); }); } // Delegated to by overloaded#Intersect function doIntersect(a, b) { var distinct = doDistinct(a); var setList = removeDuplicateNulls(distinct); return setList.filter(function (item) { return doContains(b, item, true); }); } // ELM-only, not a product of CQL var Times = /*#__PURE__*/function (_UnimplementedExpress) { _inherits(Times, _UnimplementedExpress); var _super3 = _createSuper(Times); function Times() { _classCallCheck(this, Times); return _super3.apply(this, arguments); } return Times; }(UnimplementedExpression); // ELM-only, not a product of CQL var Filter = /*#__PURE__*/function (_UnimplementedExpress2) { _inherits(Filter, _UnimplementedExpress2); var _super4 = _createSuper(Filter); function Filter() { _classCallCheck(this, Filter); return _super4.apply(this, arguments); } return Filter; }(UnimplementedExpression); var SingletonFrom = /*#__PURE__*/function (_Expression3) { _inherits(SingletonFrom, _Expression3); var _super5 = _createSuper(SingletonFrom); function SingletonFrom(json) { _classCallCheck(this, SingletonFrom); return _super5.call(this, json); } _createClass(SingletonFrom, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg != null && arg.length > 1) { throw new Error("IllegalArgument: 'SingletonFrom' requires a 0 or 1 arg array"); } else if (arg != null && arg.length === 1) { return arg[0]; } else { return null; } } }]); return SingletonFrom; }(Expression); var ToList = /*#__PURE__*/function (_Expression4) { _inherits(ToList, _Expression4); var _super6 = _createSuper(ToList); function ToList(json) { _classCallCheck(this, ToList); return _super6.call(this, json); } _createClass(ToList, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg != null) { return [arg]; } else { return []; } } }]); return ToList; }(Expression); var IndexOf = /*#__PURE__*/function (_Expression5) { _inherits(IndexOf, _Expression5); var _super7 = _createSuper(IndexOf); function IndexOf(json) { var _this2; _classCallCheck(this, IndexOf); _this2 = _super7.call(this, json); _this2.source = build(json.source); _this2.element = build(json.element); return _this2; } _createClass(IndexOf, [{ key: "exec", value: function exec(ctx) { var index; var src = this.source.execute(ctx); var el = this.element.execute(ctx); if (src == null || el == null) { return null; } for (var i = 0; i < src.length; i++) { var itm = src[i]; if (equals(itm, el)) { index = i; break; } } if (index != null) { return index; } else { return -1; } } }]); return IndexOf; }(Expression); // Indexer is completely handled by overloaded#Indexer // Delegated to by overloaded#Contains and overloaded#In function doContains(container, item) { var nullEquivalence = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; return container.some(function (element) { return equals(element, item) || nullEquivalence && element == null && item == null; }); } // Delegated to by overloaded#Includes and overloaded@IncludedIn function doIncludes(list, sublist) { return sublist.every(function (x) { return doContains(list, x); }); } // Delegated to by overloaded#ProperIncludes and overloaded@ProperIncludedIn function doProperIncludes(list, sublist) { return list.length > sublist.length && doIncludes(list, sublist); } // ELM-only, not a product of CQL var ForEach = /*#__PURE__*/function (_UnimplementedExpress3) { _inherits(ForEach, _UnimplementedExpress3); var _super8 = _createSuper(ForEach); function ForEach() { _classCallCheck(this, ForEach); return _super8.apply(this, arguments); } return ForEach; }(UnimplementedExpression); var Flatten = /*#__PURE__*/function (_Expression6) { _inherits(Flatten, _Expression6); var _super9 = _createSuper(Flatten); function Flatten(json) { _classCallCheck(this, Flatten); return _super9.call(this, json); } _createClass(Flatten, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (typeIsArray(arg) && arg.every(function (x) { return typeIsArray(x); })) { return arg.reduce(function (x, y) { return x.concat(y); }, []); } else { return arg; } } }]); return Flatten; }(Expression); var Distinct = /*#__PURE__*/function (_Expression7) { _inherits(Distinct, _Expression7); var _super10 = _createSuper(Distinct); function Distinct(json) { _classCallCheck(this, Distinct); return _super10.call(this, json); } _createClass(Distinct, [{ key: "exec", value: function exec(ctx) { var result = this.execArgs(ctx); if (result == null) { return null; } return doDistinct(result); } }]); return Distinct; }(Expression); function doDistinct(list) { var distinct = []; list.forEach(function (item) { var isNew = distinct.every(function (seenItem) { return !equals(item, seenItem); }); if (isNew) { distinct.push(item); } }); return removeDuplicateNulls(distinct); } function removeDuplicateNulls(list) { // Remove duplicate null elements var firstNullFound = false; var setList = []; var _iterator = _createForOfIteratorHelper(list), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var item = _step.value; if (item !== null) { setList.push(item); } else if (item === null && !firstNullFound) { setList.push(item); firstNullFound = true; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return setList; } // ELM-only, not a product of CQL var Current = /*#__PURE__*/function (_UnimplementedExpress4) { _inherits(Current, _UnimplementedExpress4); var _super11 = _createSuper(Current); function Current() { _classCallCheck(this, Current); return _super11.apply(this, arguments); } return Current; }(UnimplementedExpression); var First = /*#__PURE__*/function (_Expression8) { _inherits(First, _Expression8); var _super12 = _createSuper(First); function First(json) { var _this3; _classCallCheck(this, First); _this3 = _super12.call(this, json); _this3.source = build(json.source); return _this3; } _createClass(First, [{ key: "exec", value: function exec(ctx) { var src = this.source.exec(ctx); if (src != null && typeIsArray(src) && src.length > 0) { return src[0]; } else { return null; } } }]); return First; }(Expression); var Last = /*#__PURE__*/function (_Expression9) { _inherits(Last, _Expression9); var _super13 = _createSuper(Last); function Last(json) { var _this4; _classCallCheck(this, Last); _this4 = _super13.call(this, json); _this4.source = build(json.source); return _this4; } _createClass(Last, [{ key: "exec", value: function exec(ctx) { var src = this.source.exec(ctx); if (src != null && typeIsArray(src) && src.length > 0) { return src[src.length - 1]; } else { return null; } } }]); return Last; }(Expression); var Slice = /*#__PURE__*/function (_Expression10) { _inherits(Slice, _Expression10); var _super14 = _createSuper(Slice); function Slice(json) { var _this5; _classCallCheck(this, Slice); _this5 = _super14.call(this, json); _this5.source = build(json.source); _this5.startIndex = build(json.startIndex); _this5.endIndex = build(json.endIndex); return _this5; } _createClass(Slice, [{ key: "exec", value: function exec(ctx) { var src = this.source.exec(ctx); if (src != null && typeIsArray(src)) { var startIndex = this.startIndex.exec(ctx); var endIndex = this.endIndex.exec(ctx); var start = startIndex != null ? startIndex : 0; var end = endIndex != null ? endIndex : src.length; if (src.length === 0 || start < 0 || end < 0 || end < start) { return []; } return src.slice(start, end); } return null; } }]); return Slice; }(Expression); // Length is completely handled by overloaded#Length module.exports = { Current: Current, Distinct: Distinct, Exists: Exists, Filter: Filter, First: First, Flatten: Flatten, ForEach: ForEach, IndexOf: IndexOf, Last: Last, List: List, SingletonFrom: SingletonFrom, Slice: Slice, Times: Times, ToList: ToList, doContains: doContains, doIncludes: doIncludes, doProperIncludes: doProperIncludes, doUnion: doUnion, doExcept: doExcept, doIntersect: doIntersect }; },{"../util/comparison":173,"../util/util":176,"./builder":144,"./expression":150}],157:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var Literal = /*#__PURE__*/function (_Expression) { _inherits(Literal, _Expression); var _super = _createSuper(Literal); _createClass(Literal, null, [{ key: "from", value: function from(json) { switch (json.valueType) { case '{urn:hl7-org:elm-types:r1}Boolean': return new BooleanLiteral(json); case '{urn:hl7-org:elm-types:r1}Integer': return new IntegerLiteral(json); case '{urn:hl7-org:elm-types:r1}Decimal': return new DecimalLiteral(json); case '{urn:hl7-org:elm-types:r1}String': return new StringLiteral(json); default: return new Literal(json); } } }]); function Literal(json) { var _this; _classCallCheck(this, Literal); _this = _super.call(this, json); _this.valueType = json.valueType; _this.value = json.value; return _this; } _createClass(Literal, [{ key: "exec", value: function exec(ctx) { return this.value; } }]); return Literal; }(Expression); // The following are not defined in ELM, but helpful for execution var BooleanLiteral = /*#__PURE__*/function (_Literal) { _inherits(BooleanLiteral, _Literal); var _super2 = _createSuper(BooleanLiteral); function BooleanLiteral(json) { var _this2; _classCallCheck(this, BooleanLiteral); _this2 = _super2.call(this, json); _this2.value = _this2.value === 'true'; return _this2; } // Define a simple getter to allow type-checking of this class without instanceof // and in a way that survives minification (as opposed to checking constructor.name) _createClass(BooleanLiteral, [{ key: "exec", value: function exec(ctx) { return this.value; } }, { key: "isBooleanLiteral", get: function get() { return true; } }]); return BooleanLiteral; }(Literal); var IntegerLiteral = /*#__PURE__*/function (_Literal2) { _inherits(IntegerLiteral, _Literal2); var _super3 = _createSuper(IntegerLiteral); function IntegerLiteral(json) { var _this3; _classCallCheck(this, IntegerLiteral); _this3 = _super3.call(this, json); _this3.value = parseInt(_this3.value, 10); return _this3; } // Define a simple getter to allow type-checking of this class without instanceof // and in a way that survives minification (as opposed to checking constructor.name) _createClass(IntegerLiteral, [{ key: "exec", value: function exec(ctx) { return this.value; } }, { key: "isIntegerLiteral", get: function get() { return true; } }]); return IntegerLiteral; }(Literal); var DecimalLiteral = /*#__PURE__*/function (_Literal3) { _inherits(DecimalLiteral, _Literal3); var _super4 = _createSuper(DecimalLiteral); function DecimalLiteral(json) { var _this4; _classCallCheck(this, DecimalLiteral); _this4 = _super4.call(this, json); _this4.value = parseFloat(_this4.value); return _this4; } // Define a simple getter to allow type-checking of this class without instanceof // and in a way that survives minification (as opposed to checking constructor.name) _createClass(DecimalLiteral, [{ key: "exec", value: function exec(ctx) { return this.value; } }, { key: "isDecimalLiteral", get: function get() { return true; } }]); return DecimalLiteral; }(Literal); var StringLiteral = /*#__PURE__*/function (_Literal4) { _inherits(StringLiteral, _Literal4); var _super5 = _createSuper(StringLiteral); function StringLiteral(json) { _classCallCheck(this, StringLiteral); return _super5.call(this, json); } // Define a simple getter to allow type-checking of this class without instanceof // and in a way that survives minification (as opposed to checking constructor.name) _createClass(StringLiteral, [{ key: "exec", value: function exec(ctx) { // TODO: Remove these replacements when CQL-to-ELM fixes bug: https://github.com/cqframework/clinical_quality_language/issues/82 return this.value.replace(/\\'/g, "'").replace(/\\"/g, '"'); } }, { key: "isStringLiteral", get: function get() { return true; } }]); return StringLiteral; }(Literal); module.exports = { BooleanLiteral: BooleanLiteral, DecimalLiteral: DecimalLiteral, IntegerLiteral: IntegerLiteral, Literal: Literal, StringLiteral: StringLiteral }; },{"./expression":150}],158:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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" && Symbol.iterator in Object(iter)) 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 _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 _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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var _require2 = require('../datatypes/datatypes'), ThreeValuedLogic = _require2.ThreeValuedLogic; var And = /*#__PURE__*/function (_Expression) { _inherits(And, _Expression); var _super = _createSuper(And); function And(json) { _classCallCheck(this, And); return _super.call(this, json); } _createClass(And, [{ key: "exec", value: function exec(ctx) { return ThreeValuedLogic.and.apply(ThreeValuedLogic, _toConsumableArray(this.execArgs(ctx))); } }]); return And; }(Expression); var Or = /*#__PURE__*/function (_Expression2) { _inherits(Or, _Expression2); var _super2 = _createSuper(Or); function Or(json) { _classCallCheck(this, Or); return _super2.call(this, json); } _createClass(Or, [{ key: "exec", value: function exec(ctx) { return ThreeValuedLogic.or.apply(ThreeValuedLogic, _toConsumableArray(this.execArgs(ctx))); } }]); return Or; }(Expression); var Not = /*#__PURE__*/function (_Expression3) { _inherits(Not, _Expression3); var _super3 = _createSuper(Not); function Not(json) { _classCallCheck(this, Not); return _super3.call(this, json); } _createClass(Not, [{ key: "exec", value: function exec(ctx) { return ThreeValuedLogic.not(this.execArgs(ctx)); } }]); return Not; }(Expression); var Xor = /*#__PURE__*/function (_Expression4) { _inherits(Xor, _Expression4); var _super4 = _createSuper(Xor); function Xor(json) { _classCallCheck(this, Xor); return _super4.call(this, json); } _createClass(Xor, [{ key: "exec", value: function exec(ctx) { return ThreeValuedLogic.xor.apply(ThreeValuedLogic, _toConsumableArray(this.execArgs(ctx))); } }]); return Xor; }(Expression); var IsTrue = /*#__PURE__*/function (_Expression5) { _inherits(IsTrue, _Expression5); var _super5 = _createSuper(IsTrue); function IsTrue(json) { _classCallCheck(this, IsTrue); return _super5.call(this, json); } _createClass(IsTrue, [{ key: "exec", value: function exec(ctx) { return true === this.execArgs(ctx); } }]); return IsTrue; }(Expression); var IsFalse = /*#__PURE__*/function (_Expression6) { _inherits(IsFalse, _Expression6); var _super6 = _createSuper(IsFalse); function IsFalse(json) { _classCallCheck(this, IsFalse); return _super6.call(this, json); } _createClass(IsFalse, [{ key: "exec", value: function exec(ctx) { return false === this.execArgs(ctx); } }]); return IsFalse; }(Expression); module.exports = { And: And, IsFalse: IsFalse, IsTrue: IsTrue, Not: Not, Or: Or, Xor: Xor }; },{"../datatypes/datatypes":134,"./expression":150}],159:[function(require,module,exports){ "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var Null = /*#__PURE__*/function (_Expression) { _inherits(Null, _Expression); var _super = _createSuper(Null); function Null(json) { _classCallCheck(this, Null); return _super.call(this, json); } _createClass(Null, [{ key: "exec", value: function exec(ctx) { return null; } }]); return Null; }(Expression); var IsNull = /*#__PURE__*/function (_Expression2) { _inherits(IsNull, _Expression2); var _super2 = _createSuper(IsNull); function IsNull(json) { _classCallCheck(this, IsNull); return _super2.call(this, json); } _createClass(IsNull, [{ key: "exec", value: function exec(ctx) { return this.execArgs(ctx) == null; } }]); return IsNull; }(Expression); var Coalesce = /*#__PURE__*/function (_Expression3) { _inherits(Coalesce, _Expression3); var _super3 = _createSuper(Coalesce); function Coalesce(json) { _classCallCheck(this, Coalesce); return _super3.call(this, json); } _createClass(Coalesce, [{ key: "exec", value: function exec(ctx) { var _iterator = _createForOfIteratorHelper(this.args), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var arg = _step.value; var result = arg.execute(ctx); // if a single arg that's a list, coalesce over the list if (this.args.length === 1 && Array.isArray(result)) { var item = result.find(function (item) { return item != null; }); if (item != null) { return item; } } else { if (result != null) { return result; } } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return null; } }]); return Coalesce; }(Expression); module.exports = { Coalesce: Coalesce, IsNull: IsNull, Null: Null }; },{"./expression":150}],160:[function(require,module,exports){ "use strict"; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; 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) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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" && Symbol.iterator in Object(iter)) 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 _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 _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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var _require2 = require('../datatypes/logic'), ThreeValuedLogic = _require2.ThreeValuedLogic; var _require3 = require('../datatypes/datetime'), DateTime = _require3.DateTime; var _require4 = require('../util/util'), typeIsArray = _require4.typeIsArray; var _require5 = require('../util/comparison'), equals = _require5.equals, equivalent = _require5.equivalent; var DT = require('./datetime'); var LIST = require('./list'); var IVL = require('./interval'); var Equal = /*#__PURE__*/function (_Expression) { _inherits(Equal, _Expression); var _super = _createSuper(Equal); function Equal(json) { _classCallCheck(this, Equal); return _super.call(this, json); } _createClass(Equal, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx); if (args[0] == null || args[1] == null) { return null; } return equals.apply(void 0, _toConsumableArray(args)); } }]); return Equal; }(Expression); var Equivalent = /*#__PURE__*/function (_Expression2) { _inherits(Equivalent, _Expression2); var _super2 = _createSuper(Equivalent); function Equivalent(json) { _classCallCheck(this, Equivalent); return _super2.call(this, json); } _createClass(Equivalent, [{ key: "exec", value: function exec(ctx) { var _this$execArgs = this.execArgs(ctx), _this$execArgs2 = _slicedToArray(_this$execArgs, 2), a = _this$execArgs2[0], b = _this$execArgs2[1]; if (a == null && b == null) { return true; } else if (a == null || b == null) { return false; } else { return equivalent(a, b); } } }]); return Equivalent; }(Expression); var NotEqual = /*#__PURE__*/function (_Expression3) { _inherits(NotEqual, _Expression3); var _super3 = _createSuper(NotEqual); function NotEqual(json) { _classCallCheck(this, NotEqual); return _super3.call(this, json); } _createClass(NotEqual, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx); if (args[0] == null || args[1] == null) { return null; } return ThreeValuedLogic.not(equals.apply(void 0, _toConsumableArray(this.execArgs(ctx)))); } }]); return NotEqual; }(Expression); var Union = /*#__PURE__*/function (_Expression4) { _inherits(Union, _Expression4); var _super4 = _createSuper(Union); function Union(json) { _classCallCheck(this, Union); return _super4.call(this, json); } _createClass(Union, [{ key: "exec", value: function exec(ctx) { var _this$execArgs3 = this.execArgs(ctx), _this$execArgs4 = _slicedToArray(_this$execArgs3, 2), a = _this$execArgs4[0], b = _this$execArgs4[1]; if (a == null || b == null) { return null; } var lib = typeIsArray(a) ? LIST : IVL; return lib.doUnion(a, b); } }]); return Union; }(Expression); var Except = /*#__PURE__*/function (_Expression5) { _inherits(Except, _Expression5); var _super5 = _createSuper(Except); function Except(json) { _classCallCheck(this, Except); return _super5.call(this, json); } _createClass(Except, [{ key: "exec", value: function exec(ctx) { var _this$execArgs5 = this.execArgs(ctx), _this$execArgs6 = _slicedToArray(_this$execArgs5, 2), a = _this$execArgs6[0], b = _this$execArgs6[1]; if (a == null) { return null; } if (b == null) { return typeIsArray(a) ? a : null; } var lib = typeIsArray(a) ? LIST : IVL; return lib.doExcept(a, b); } }]); return Except; }(Expression); var Intersect = /*#__PURE__*/function (_Expression6) { _inherits(Intersect, _Expression6); var _super6 = _createSuper(Intersect); function Intersect(json) { _classCallCheck(this, Intersect); return _super6.call(this, json); } _createClass(Intersect, [{ key: "exec", value: function exec(ctx) { var _this$execArgs7 = this.execArgs(ctx), _this$execArgs8 = _slicedToArray(_this$execArgs7, 2), a = _this$execArgs8[0], b = _this$execArgs8[1]; if (a == null || b == null) { return null; } var lib = typeIsArray(a) ? LIST : IVL; return lib.doIntersect(a, b); } }]); return Intersect; }(Expression); var Indexer = /*#__PURE__*/function (_Expression7) { _inherits(Indexer, _Expression7); var _super7 = _createSuper(Indexer); function Indexer(json) { _classCallCheck(this, Indexer); return _super7.call(this, json); } _createClass(Indexer, [{ key: "exec", value: function exec(ctx) { var _this$execArgs9 = this.execArgs(ctx), _this$execArgs10 = _slicedToArray(_this$execArgs9, 2), operand = _this$execArgs10[0], index = _this$execArgs10[1]; if (operand == null || index == null) { return null; } if (index < 0 || index >= operand.length) { return null; } return operand[index]; } }]); return Indexer; }(Expression); var In = /*#__PURE__*/function (_Expression8) { _inherits(In, _Expression8); var _super8 = _createSuper(In); function In(json) { var _this; _classCallCheck(this, In); _this = _super8.call(this, json); _this.precision = json.precision != null ? json.precision.toLowerCase() : undefined; return _this; } _createClass(In, [{ key: "exec", value: function exec(ctx) { var _this$execArgs11 = this.execArgs(ctx), _this$execArgs12 = _slicedToArray(_this$execArgs11, 2), item = _this$execArgs12[0], container = _this$execArgs12[1]; if (item == null) { return null; } if (container == null) { return false; } var lib = typeIsArray(container) ? LIST : IVL; return lib.doContains(container, item, this.precision); } }]); return In; }(Expression); var Contains = /*#__PURE__*/function (_Expression9) { _inherits(Contains, _Expression9); var _super9 = _createSuper(Contains); function Contains(json) { var _this2; _classCallCheck(this, Contains); _this2 = _super9.call(this, json); _this2.precision = json.precision != null ? json.precision.toLowerCase() : undefined; return _this2; } _createClass(Contains, [{ key: "exec", value: function exec(ctx) { var _this$execArgs13 = this.execArgs(ctx), _this$execArgs14 = _slicedToArray(_this$execArgs13, 2), container = _this$execArgs14[0], item = _this$execArgs14[1]; if (container == null) { return false; } if (item == null) { return null; } var lib = typeIsArray(container) ? LIST : IVL; return lib.doContains(container, item, this.precision); } }]); return Contains; }(Expression); var Includes = /*#__PURE__*/function (_Expression10) { _inherits(Includes, _Expression10); var _super10 = _createSuper(Includes); function Includes(json) { var _this3; _classCallCheck(this, Includes); _this3 = _super10.call(this, json); _this3.precision = json.precision != null ? json.precision.toLowerCase() : undefined; return _this3; } _createClass(Includes, [{ key: "exec", value: function exec(ctx) { var _this$execArgs15 = this.execArgs(ctx), _this$execArgs16 = _slicedToArray(_this$execArgs15, 2), container = _this$execArgs16[0], contained = _this$execArgs16[1]; if (container == null || contained == null) { return null; } var lib = typeIsArray(container) ? LIST : IVL; return lib.doIncludes(container, contained, this.precision); } }]); return Includes; }(Expression); var IncludedIn = /*#__PURE__*/function (_Expression11) { _inherits(IncludedIn, _Expression11); var _super11 = _createSuper(IncludedIn); function IncludedIn(json) { var _this4; _classCallCheck(this, IncludedIn); _this4 = _super11.call(this, json); _this4.precision = json.precision != null ? json.precision.toLowerCase() : undefined; return _this4; } _createClass(IncludedIn, [{ key: "exec", value: function exec(ctx) { var _this$execArgs17 = this.execArgs(ctx), _this$execArgs18 = _slicedToArray(_this$execArgs17, 2), contained = _this$execArgs18[0], container = _this$execArgs18[1]; if (container == null || contained == null) { return null; } var lib = typeIsArray(container) ? LIST : IVL; return lib.doIncludes(container, contained, this.precision); } }]); return IncludedIn; }(Expression); var ProperIncludes = /*#__PURE__*/function (_Expression12) { _inherits(ProperIncludes, _Expression12); var _super12 = _createSuper(ProperIncludes); function ProperIncludes(json) { var _this5; _classCallCheck(this, ProperIncludes); _this5 = _super12.call(this, json); _this5.precision = json.precision != null ? json.precision.toLowerCase() : undefined; return _this5; } _createClass(ProperIncludes, [{ key: "exec", value: function exec(ctx) { var _this$execArgs19 = this.execArgs(ctx), _this$execArgs20 = _slicedToArray(_this$execArgs19, 2), container = _this$execArgs20[0], contained = _this$execArgs20[1]; if (container == null || contained == null) { return null; } var lib = typeIsArray(container) ? LIST : IVL; return lib.doProperIncludes(container, contained, this.precision); } }]); return ProperIncludes; }(Expression); var ProperIncludedIn = /*#__PURE__*/function (_Expression13) { _inherits(ProperIncludedIn, _Expression13); var _super13 = _createSuper(ProperIncludedIn); function ProperIncludedIn(json) { var _this6; _classCallCheck(this, ProperIncludedIn); _this6 = _super13.call(this, json); _this6.precision = json.precision != null ? json.precision.toLowerCase() : undefined; return _this6; } _createClass(ProperIncludedIn, [{ key: "exec", value: function exec(ctx) { var _this$execArgs21 = this.execArgs(ctx), _this$execArgs22 = _slicedToArray(_this$execArgs21, 2), contained = _this$execArgs22[0], container = _this$execArgs22[1]; if (container == null || contained == null) { return null; } var lib = typeIsArray(container) ? LIST : IVL; return lib.doProperIncludes(container, contained, this.precision); } }]); return ProperIncludedIn; }(Expression); var Length = /*#__PURE__*/function (_Expression14) { _inherits(Length, _Expression14); var _super14 = _createSuper(Length); function Length(json) { _classCallCheck(this, Length); return _super14.call(this, json); } _createClass(Length, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg != null) { return arg.length; } else if (this.arg.asTypeSpecifier.type === 'ListTypeSpecifier') { return 0; } else { return null; } } }]); return Length; }(Expression); var After = /*#__PURE__*/function (_Expression15) { _inherits(After, _Expression15); var _super15 = _createSuper(After); function After(json) { var _this7; _classCallCheck(this, After); _this7 = _super15.call(this, json); _this7.precision = json.precision != null ? json.precision.toLowerCase() : undefined; return _this7; } _createClass(After, [{ key: "exec", value: function exec(ctx) { var _this$execArgs23 = this.execArgs(ctx), _this$execArgs24 = _slicedToArray(_this$execArgs23, 2), a = _this$execArgs24[0], b = _this$execArgs24[1]; if (a == null || b == null) { return null; } var lib = a instanceof DateTime ? DT : IVL; return lib.doAfter(a, b, this.precision); } }]); return After; }(Expression); var Before = /*#__PURE__*/function (_Expression16) { _inherits(Before, _Expression16); var _super16 = _createSuper(Before); function Before(json) { var _this8; _classCallCheck(this, Before); _this8 = _super16.call(this, json); _this8.precision = json.precision != null ? json.precision.toLowerCase() : undefined; return _this8; } _createClass(Before, [{ key: "exec", value: function exec(ctx) { var _this$execArgs25 = this.execArgs(ctx), _this$execArgs26 = _slicedToArray(_this$execArgs25, 2), a = _this$execArgs26[0], b = _this$execArgs26[1]; if (a == null || b == null) { return null; } var lib = a instanceof DateTime ? DT : IVL; return lib.doBefore(a, b, this.precision); } }]); return Before; }(Expression); var SameAs = /*#__PURE__*/function (_Expression17) { _inherits(SameAs, _Expression17); var _super17 = _createSuper(SameAs); function SameAs(json) { var _this9; _classCallCheck(this, SameAs); _this9 = _super17.call(this, json); _this9.precision = json.precision; return _this9; } _createClass(SameAs, [{ key: "exec", value: function exec(ctx) { var _this$execArgs27 = this.execArgs(ctx), _this$execArgs28 = _slicedToArray(_this$execArgs27, 2), a = _this$execArgs28[0], b = _this$execArgs28[1]; if (a != null && b != null) { return a.sameAs(b, this.precision != null ? this.precision.toLowerCase() : undefined); } else { return null; } } }]); return SameAs; }(Expression); var SameOrAfter = /*#__PURE__*/function (_Expression18) { _inherits(SameOrAfter, _Expression18); var _super18 = _createSuper(SameOrAfter); function SameOrAfter(json) { var _this10; _classCallCheck(this, SameOrAfter); _this10 = _super18.call(this, json); _this10.precision = json.precision; return _this10; } _createClass(SameOrAfter, [{ key: "exec", value: function exec(ctx) { var _this$execArgs29 = this.execArgs(ctx), _this$execArgs30 = _slicedToArray(_this$execArgs29, 2), d1 = _this$execArgs30[0], d2 = _this$execArgs30[1]; if (d1 != null && d2 != null) { return d1.sameOrAfter(d2, this.precision != null ? this.precision.toLowerCase() : undefined); } else { return null; } } }]); return SameOrAfter; }(Expression); var SameOrBefore = /*#__PURE__*/function (_Expression19) { _inherits(SameOrBefore, _Expression19); var _super19 = _createSuper(SameOrBefore); function SameOrBefore(json) { var _this11; _classCallCheck(this, SameOrBefore); _this11 = _super19.call(this, json); _this11.precision = json.precision; return _this11; } _createClass(SameOrBefore, [{ key: "exec", value: function exec(ctx) { var _this$execArgs31 = this.execArgs(ctx), _this$execArgs32 = _slicedToArray(_this$execArgs31, 2), d1 = _this$execArgs32[0], d2 = _this$execArgs32[1]; if (d1 != null && d2 != null) { return d1.sameOrBefore(d2, this.precision != null ? this.precision.toLowerCase() : undefined); } else { return null; } } }]); return SameOrBefore; }(Expression); module.exports = { After: After, Before: Before, Contains: Contains, Equal: Equal, Equivalent: Equivalent, Except: Except, In: In, IncludedIn: IncludedIn, Includes: Includes, Indexer: Indexer, Intersect: Intersect, Length: Length, NotEqual: NotEqual, ProperIncludedIn: ProperIncludedIn, ProperIncludes: ProperIncludes, SameAs: SameAs, SameOrAfter: SameOrAfter, SameOrBefore: SameOrBefore, Union: Union }; },{"../datatypes/datetime":135,"../datatypes/logic":138,"../util/comparison":173,"../util/util":176,"./datetime":148,"./expression":150,"./interval":154,"./list":156}],161:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var _require2 = require('./builder'), build = _require2.build; var ParameterDef = /*#__PURE__*/function (_Expression) { _inherits(ParameterDef, _Expression); var _super = _createSuper(ParameterDef); function ParameterDef(json) { var _this; _classCallCheck(this, ParameterDef); _this = _super.call(this, json); _this.name = json.name; _this.default = build(json.default); _this.parameterTypeSpecifier = json.parameterTypeSpecifier; return _this; } _createClass(ParameterDef, [{ key: "exec", value: function exec(ctx) { // If context parameters contains the name, return value. if (ctx && ctx.parameters[this.name] !== undefined) { return ctx.parameters[this.name]; // If the parent context contains the name, return that } else if (ctx.getParentParameter(this.name) !== undefined) { var parentParam = ctx.getParentParameter(this.name); return parentParam.default != null ? parentParam.default.execute(ctx) : parentParam; // If default type exists, execute the default type } else if (this.default != null) { this.default.execute(ctx); } } }]); return ParameterDef; }(Expression); var ParameterRef = /*#__PURE__*/function (_Expression2) { _inherits(ParameterRef, _Expression2); var _super2 = _createSuper(ParameterRef); function ParameterRef(json) { var _this2; _classCallCheck(this, ParameterRef); _this2 = _super2.call(this, json); _this2.name = json.name; _this2.library = json.libraryName; return _this2; } _createClass(ParameterRef, [{ key: "exec", value: function exec(ctx) { ctx = this.library ? ctx.getLibraryContext(this.library) : ctx; var param = ctx.getParameter(this.name); return param != null ? param.execute(ctx) : undefined; } }]); return ParameterRef; }(Expression); module.exports = { ParameterDef: ParameterDef, ParameterRef: ParameterRef }; },{"./builder":144,"./expression":150}],162:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var DT = require('../datatypes/datatypes'); // Unit conversation is currently implemented on for time duration comparison operations // TODO: Implement unit conversation for time duration mathematical operations var Quantity = /*#__PURE__*/function (_Expression) { _inherits(Quantity, _Expression); var _super = _createSuper(Quantity); function Quantity(json) { var _this; _classCallCheck(this, Quantity); _this = _super.call(this, json); _this.value = parseFloat(json.value); _this.unit = json.unit; return _this; } _createClass(Quantity, [{ key: "exec", value: function exec(ctx) { return new DT.Quantity(this.value, this.unit); } }]); return Quantity; }(Expression); module.exports = { Quantity: Quantity }; },{"../datatypes/datatypes":134,"./expression":150}],163:[function(require,module,exports){ "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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 _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } 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(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _require = require('./expression'), Expression = _require.Expression, UnimplementedExpression = _require.UnimplementedExpression; var _require2 = require('../runtime/context'), Context = _require2.Context; var _require3 = require('./builder'), build = _require3.build; var _require4 = require('../util/util'), typeIsArray = _require4.typeIsArray, allTrue = _require4.allTrue; var _require5 = require('../util/comparison'), equals = _require5.equals; var AliasedQuerySource = function AliasedQuerySource(json) { _classCallCheck(this, AliasedQuerySource); this.alias = json.alias; this.expression = build(json.expression); }; var LetClause = function LetClause(json) { _classCallCheck(this, LetClause); this.identifier = json.identifier; this.expression = build(json.expression); }; var With = /*#__PURE__*/function (_Expression) { _inherits(With, _Expression); var _super = _createSuper(With); function With(json) { var _this; _classCallCheck(this, With); _this = _super.call(this, json); _this.alias = json.alias; _this.expression = build(json.expression); _this.suchThat = build(json.suchThat); return _this; } _createClass(With, [{ key: "exec", value: function exec(ctx) { var _this2 = this; var records = this.expression.execute(ctx); if (!typeIsArray(records)) { records = [records]; } var returns = records.map(function (rec) { var childCtx = ctx.childContext(); childCtx.set(_this2.alias, rec); return _this2.suchThat.execute(childCtx); }); return returns.some(function (x) { return x; }); } }]); return With; }(Expression); var Without = /*#__PURE__*/function (_With) { _inherits(Without, _With); var _super2 = _createSuper(Without); function Without(json) { _classCallCheck(this, Without); return _super2.call(this, json); } _createClass(Without, [{ key: "exec", value: function exec(ctx) { return !_get(_getPrototypeOf(Without.prototype), "exec", this).call(this, ctx); } }]); return Without; }(With); // ELM-only, not a product of CQL var Sort = /*#__PURE__*/function (_UnimplementedExpress) { _inherits(Sort, _UnimplementedExpress); var _super3 = _createSuper(Sort); function Sort() { _classCallCheck(this, Sort); return _super3.apply(this, arguments); } return Sort; }(UnimplementedExpression); var ByDirection = /*#__PURE__*/function (_Expression2) { _inherits(ByDirection, _Expression2); var _super4 = _createSuper(ByDirection); function ByDirection(json) { var _this3; _classCallCheck(this, ByDirection); _this3 = _super4.call(this, json); _this3.direction = json.direction; _this3.low_order = _this3.direction === 'asc' ? -1 : 1; _this3.high_order = _this3.low_order * -1; return _this3; } _createClass(ByDirection, [{ key: "exec", value: function exec(ctx, a, b) { if (a === b) { return 0; } else if (a.isQuantity && b.isQuantity) { if (a.before(b)) { return this.low_order; } else { return this.high_order; } } else if (a < b) { return this.low_order; } else { return this.high_order; } } }]); return ByDirection; }(Expression); var ByExpression = /*#__PURE__*/function (_Expression3) { _inherits(ByExpression, _Expression3); var _super5 = _createSuper(ByExpression); function ByExpression(json) { var _this4; _classCallCheck(this, ByExpression); _this4 = _super5.call(this, json); _this4.expression = build(json.expression); _this4.direction = json.direction; _this4.low_order = _this4.direction === 'asc' ? -1 : 1; _this4.high_order = _this4.low_order * -1; return _this4; } _createClass(ByExpression, [{ key: "exec", value: function exec(ctx, a, b) { var sctx = ctx.childContext(a); var a_val = this.expression.execute(sctx); sctx = ctx.childContext(b); var b_val = this.expression.execute(sctx); if (a_val === b_val) { return 0; } else if (a_val.isQuantity && b_val.isQuantity) { if (a_val.before(b_val)) { return this.low_order; } else { return this.high_order; } } else if (a_val < b_val) { return this.low_order; } else { return this.high_order; } } }]); return ByExpression; }(Expression); var ByColumn = /*#__PURE__*/function (_ByExpression) { _inherits(ByColumn, _ByExpression); var _super6 = _createSuper(ByColumn); function ByColumn(json) { var _this5; _classCallCheck(this, ByColumn); _this5 = _super6.call(this, json); _this5.expression = build({ name: json.path, type: 'IdentifierRef' }); return _this5; } return ByColumn; }(ByExpression); var ReturnClause = function ReturnClause(json) { _classCallCheck(this, ReturnClause); this.expression = build(json.expression); this.distinct = json.distinct != null ? json.distinct : true; }; var SortClause = /*#__PURE__*/function () { function SortClause(json) { _classCallCheck(this, SortClause); this.by = build(json != null ? json.by : undefined); } _createClass(SortClause, [{ key: "sort", value: function sort(ctx, values) { var _this6 = this; if (this.by) { return values.sort(function (a, b) { var order = 0; var _iterator = _createForOfIteratorHelper(_this6.by), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var item = _step.value; // Do not use execute here because the value of the sort order is not important. order = item.exec(ctx, a, b); if (order !== 0) { break; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return order; }); } } }]); return SortClause; }(); var toDistinctList = function toDistinctList(xList) { var yList = []; xList.forEach(function (x) { if (!yList.some(function (y) { return equals(x, y); })) { yList.push(x); } }); return yList; }; var Query = /*#__PURE__*/function (_Expression4) { _inherits(Query, _Expression4); var _super7 = _createSuper(Query); function Query(json) { var _this7; _classCallCheck(this, Query); _this7 = _super7.call(this, json); _this7.sources = new MultiSource(json.source.map(function (s) { return new AliasedQuerySource(s); })); _this7.letClauses = json.let != null ? json.let.map(function (d) { return new LetClause(d); }) : []; _this7.relationship = json.relationship != null ? build(json.relationship) : []; _this7.where = build(json.where); _this7.returnClause = json.return != null ? new ReturnClause(json.return) : null; _this7.aliases = _this7.sources.aliases(); _this7.sortClause = json.sort != null ? new SortClause(json.sort) : null; return _this7; } _createClass(Query, [{ key: "exec", value: function exec(ctx) { var _this8 = this; var returnedValues = []; this.sources.forEach(ctx, function (rctx) { var _iterator2 = _createForOfIteratorHelper(_this8.letClauses), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var def = _step2.value; rctx.set(def.identifier, def.expression.execute(rctx)); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } var relations = _this8.relationship.map(function (rel) { var child_ctx = rctx.childContext(); return rel.execute(child_ctx); }); var passed = allTrue(relations) && (_this8.where ? _this8.where.execute(rctx) : true); if (passed) { if (_this8.returnClause != null) { var val = _this8.returnClause.expression.execute(rctx); returnedValues.push(val); } else { if (_this8.aliases.length === 1) { returnedValues.push(rctx.get(_this8.aliases[0])); } else { returnedValues.push(rctx.context_values); } } } }); var distinct = this.returnClause != null ? this.returnClause.distinct : true; if (distinct) { returnedValues = toDistinctList(returnedValues); } if (this.sortClause != null) { this.sortClause.sort(ctx, returnedValues); } if (this.sources.returnsList()) { return returnedValues; } else { return returnedValues[0]; } } }]); return Query; }(Expression); var AliasRef = /*#__PURE__*/function (_Expression5) { _inherits(AliasRef, _Expression5); var _super8 = _createSuper(AliasRef); function AliasRef(json) { var _this9; _classCallCheck(this, AliasRef); _this9 = _super8.call(this, json); _this9.name = json.name; return _this9; } _createClass(AliasRef, [{ key: "exec", value: function exec(ctx) { return ctx != null ? ctx.get(this.name) : undefined; } }]); return AliasRef; }(Expression); var QueryLetRef = /*#__PURE__*/function (_AliasRef) { _inherits(QueryLetRef, _AliasRef); var _super9 = _createSuper(QueryLetRef); function QueryLetRef(json) { _classCallCheck(this, QueryLetRef); return _super9.call(this, json); } return QueryLetRef; }(AliasRef); // The following is not defined by ELM but is helpful for execution var MultiSource = /*#__PURE__*/function () { function MultiSource(sources) { _classCallCheck(this, MultiSource); this.sources = sources; this.alias = this.sources[0].alias; this.expression = this.sources[0].expression; this.isList = true; if (this.sources.length > 1) { this.rest = new MultiSource(this.sources.slice(1)); } } _createClass(MultiSource, [{ key: "aliases", value: function aliases() { var a = [this.alias]; if (this.rest) { a = a.concat(this.rest.aliases()); } return a; } }, { key: "returnsList", value: function returnsList() { return this.isList || this.rest && this.rest.returnsList(); } }, { key: "forEach", value: function forEach(ctx, func) { var _this10 = this; var records = this.expression.execute(ctx); this.isList = typeIsArray(records); records = this.isList ? records : [records]; return records.map(function (rec) { var rctx = new Context(ctx); rctx.set(_this10.alias, rec); if (_this10.rest) { return _this10.rest.forEach(rctx, func); } else { return func(rctx); } }); } }]); return MultiSource; }(); module.exports = { AliasedQuerySource: AliasedQuerySource, AliasRef: AliasRef, ByColumn: ByColumn, ByDirection: ByDirection, ByExpression: ByExpression, LetClause: LetClause, Query: Query, QueryLetRef: QueryLetRef, ReturnClause: ReturnClause, Sort: Sort, SortClause: SortClause, With: With, Without: Without }; },{"../runtime/context":169,"../util/comparison":173,"../util/util":176,"./builder":144,"./expression":150}],164:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var _require2 = require('../datatypes/quantity'), Quantity = _require2.Quantity; var DT = require('../datatypes/datatypes'); var Ratio = /*#__PURE__*/function (_Expression) { _inherits(Ratio, _Expression); var _super = _createSuper(Ratio); function Ratio(json) { var _this; _classCallCheck(this, Ratio); _this = _super.call(this, json); if (json.numerator == null) { throw new Error('Cannot create a ratio with an undefined numerator value'); } else { _this.numerator = new Quantity(json.numerator.value, json.numerator.unit); } if (json.denominator == null) { throw new Error('Cannot create a ratio with an undefined denominator value'); } else { _this.denominator = new Quantity(json.denominator.value, json.denominator.unit); } return _this; } _createClass(Ratio, [{ key: "exec", value: function exec(ctx) { return new DT.Ratio(this.numerator, this.denominator); } }]); return Ratio; }(Expression); module.exports = { Ratio: Ratio }; },{"../datatypes/datatypes":134,"../datatypes/quantity":139,"./expression":150}],165:[function(require,module,exports){ "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var _require2 = require('./builder'), build = _require2.build; var ExpressionDef = /*#__PURE__*/function (_Expression) { _inherits(ExpressionDef, _Expression); var _super = _createSuper(ExpressionDef); function ExpressionDef(json) { var _this; _classCallCheck(this, ExpressionDef); _this = _super.call(this, json); _this.name = json.name; _this.context = json.context; _this.expression = build(json.expression); return _this; } _createClass(ExpressionDef, [{ key: "exec", value: function exec(ctx) { var value = this.expression != null ? this.expression.execute(ctx) : undefined; ctx.rootContext().set(this.name, value); return value; } }]); return ExpressionDef; }(Expression); var ExpressionRef = /*#__PURE__*/function (_Expression2) { _inherits(ExpressionRef, _Expression2); var _super2 = _createSuper(ExpressionRef); function ExpressionRef(json) { var _this2; _classCallCheck(this, ExpressionRef); _this2 = _super2.call(this, json); _this2.name = json.name; _this2.library = json.libraryName; return _this2; } _createClass(ExpressionRef, [{ key: "exec", value: function exec(ctx) { ctx = this.library ? ctx.getLibraryContext(this.library) : ctx; var value = ctx.get(this.name); if (value instanceof Expression) { value = value.execute(ctx); } return value; } }]); return ExpressionRef; }(Expression); var FunctionDef = /*#__PURE__*/function (_Expression3) { _inherits(FunctionDef, _Expression3); var _super3 = _createSuper(FunctionDef); function FunctionDef(json) { var _this3; _classCallCheck(this, FunctionDef); _this3 = _super3.call(this, json); _this3.name = json.name; _this3.expression = build(json.expression); _this3.parameters = json.operand; return _this3; } _createClass(FunctionDef, [{ key: "exec", value: function exec(ctx) { return this; } }]); return FunctionDef; }(Expression); var FunctionRef = /*#__PURE__*/function (_Expression4) { _inherits(FunctionRef, _Expression4); var _super4 = _createSuper(FunctionRef); function FunctionRef(json) { var _this4; _classCallCheck(this, FunctionRef); _this4 = _super4.call(this, json); _this4.name = json.name; _this4.library = json.libraryName; return _this4; } _createClass(FunctionRef, [{ key: "exec", value: function exec(ctx) { var functionDefs, child_ctx; if (this.library) { var lib = ctx.get(this.library); functionDefs = lib ? lib.getFunction(this.name) : undefined; var libCtx = ctx.getLibraryContext(this.library); child_ctx = libCtx ? libCtx.childContext() : undefined; } else { functionDefs = ctx.get(this.name); child_ctx = ctx.childContext(); } var args = this.execArgs(ctx); // Filter out functions w/ wrong number of arguments. functionDefs = functionDefs.filter(function (f) { return f.parameters.length === args.length; }); // If there is still > 1 matching function, filter by argument types if (functionDefs.length > 1) { functionDefs = functionDefs.filter(function (f) { var match = true; for (var i = 0; i < args.length && match; i++) { if (args[i] !== null) { var operandTypeSpecifier = f.parameters[i].operandTypeSpecifier; if (operandTypeSpecifier == null && f.parameters[i].operandType != null) { // convert it to a NamedTypedSpecifier operandTypeSpecifier = { name: f.parameters[i].operandType, type: 'NamedTypeSpecifier' }; } match = ctx.matchesTypeSpecifier(args[i], operandTypeSpecifier); } } return match; }); } // If there is still > 1 matching function, calculate a score based on quality of matches if (functionDefs.length > 1) {// TODO } if (functionDefs.length === 0) { throw new Error('no function with matching signature could be found'); } // By this point, we should have only one function, but until implementation is completed, // use the last one (no matter how many still remain) var functionDef = functionDefs[functionDefs.length - 1]; for (var i = 0; i < functionDef.parameters.length; i++) { child_ctx.set(functionDef.parameters[i].name, args[i]); } return functionDef.expression.execute(child_ctx); } }]); return FunctionRef; }(Expression); var OperandRef = /*#__PURE__*/function (_Expression5) { _inherits(OperandRef, _Expression5); var _super5 = _createSuper(OperandRef); function OperandRef(json) { var _this5; _classCallCheck(this, OperandRef); _this5 = _super5.call(this, json); _this5.name = json.name; return _this5; } _createClass(OperandRef, [{ key: "exec", value: function exec(ctx) { return ctx.get(this.name); } }]); return OperandRef; }(Expression); var IdentifierRef = /*#__PURE__*/function (_Expression6) { _inherits(IdentifierRef, _Expression6); var _super6 = _createSuper(IdentifierRef); function IdentifierRef(json) { var _this6; _classCallCheck(this, IdentifierRef); _this6 = _super6.call(this, json); _this6.name = json.name; _this6.library = json.libraryName; return _this6; } _createClass(IdentifierRef, [{ key: "exec", value: function exec(ctx) { // TODO: Technically, the ELM Translator should never output one of these // but this code is needed since it does, as a work-around to get queries // to work properly when sorting by a field in a tuple var lib = this.library ? ctx.get(this.library) : undefined; var val = lib ? lib.get(this.name) : ctx.get(this.name); if (val == null) { var parts = this.name.split('.'); val = ctx.get(parts[0]); if (val != null && parts.length > 1) { var curr_obj = val; var _iterator = _createForOfIteratorHelper(parts.slice(1)), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var part = _step.value; // _obj = curr_obj?[part] ? curr_obj?.get?(part) // curr_obj = if _obj instanceof Function then _obj.call(curr_obj) else _obj var _obj = void 0; if (curr_obj != null) { _obj = curr_obj[part]; if (_obj === undefined && typeof curr_obj.get === 'function') { _obj = curr_obj.get(part); } } curr_obj = _obj instanceof Function ? _obj.call(curr_obj) : _obj; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } val = curr_obj; } } if (val instanceof Function) { return val.call(ctx.context_values); } else { return val; } } }]); return IdentifierRef; }(Expression); module.exports = { ExpressionDef: ExpressionDef, ExpressionRef: ExpressionRef, FunctionDef: FunctionDef, FunctionRef: FunctionRef, IdentifierRef: IdentifierRef, OperandRef: OperandRef }; },{"./builder":144,"./expression":150}],166:[function(require,module,exports){ "use strict"; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; 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) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression; var _require2 = require('./builder'), build = _require2.build; var Concatenate = /*#__PURE__*/function (_Expression) { _inherits(Concatenate, _Expression); var _super = _createSuper(Concatenate); function Concatenate(json) { _classCallCheck(this, Concatenate); return _super.call(this, json); } _createClass(Concatenate, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx); if (args.some(function (x) { return x == null; })) { return null; } else { return args.reduce(function (x, y) { return x + y; }); } } }]); return Concatenate; }(Expression); var Combine = /*#__PURE__*/function (_Expression2) { _inherits(Combine, _Expression2); var _super2 = _createSuper(Combine); function Combine(json) { var _this; _classCallCheck(this, Combine); _this = _super2.call(this, json); _this.source = build(json.source); _this.separator = build(json.separator); return _this; } _createClass(Combine, [{ key: "exec", value: function exec(ctx) { var source = this.source.execute(ctx); var separator = this.separator != null ? this.separator.execute(ctx) : ''; if (source == null) { return null; } else { var filteredArray = source.filter(function (x) { return x != null; }); if (filteredArray.length === 0) { return null; } else { return filteredArray.join(separator); } } } }]); return Combine; }(Expression); var Split = /*#__PURE__*/function (_Expression3) { _inherits(Split, _Expression3); var _super3 = _createSuper(Split); function Split(json) { var _this2; _classCallCheck(this, Split); _this2 = _super3.call(this, json); _this2.stringToSplit = build(json.stringToSplit); _this2.separator = build(json.separator); return _this2; } _createClass(Split, [{ key: "exec", value: function exec(ctx) { var stringToSplit = this.stringToSplit.execute(ctx); var separator = this.separator.execute(ctx); if (stringToSplit && separator) { return stringToSplit.split(separator); } return stringToSplit ? [stringToSplit] : null; } }]); return Split; }(Expression); var SplitOnMatches = /*#__PURE__*/function (_Expression4) { _inherits(SplitOnMatches, _Expression4); var _super4 = _createSuper(SplitOnMatches); function SplitOnMatches(json) { var _this3; _classCallCheck(this, SplitOnMatches); _this3 = _super4.call(this, json); _this3.stringToSplit = build(json.stringToSplit); _this3.separatorPattern = build(json.separatorPattern); return _this3; } _createClass(SplitOnMatches, [{ key: "exec", value: function exec(ctx) { var stringToSplit = this.stringToSplit.execute(ctx); var separatorPattern = this.separatorPattern.execute(ctx); if (stringToSplit && separatorPattern) { return stringToSplit.split(new RegExp(separatorPattern)); } return stringToSplit ? [stringToSplit] : null; } }]); return SplitOnMatches; }(Expression); // Length is completely handled by overloaded#Length var Upper = /*#__PURE__*/function (_Expression5) { _inherits(Upper, _Expression5); var _super5 = _createSuper(Upper); function Upper(json) { _classCallCheck(this, Upper); return _super5.call(this, json); } _createClass(Upper, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg != null) { return arg.toUpperCase(); } else { return null; } } }]); return Upper; }(Expression); var Lower = /*#__PURE__*/function (_Expression6) { _inherits(Lower, _Expression6); var _super6 = _createSuper(Lower); function Lower(json) { _classCallCheck(this, Lower); return _super6.call(this, json); } _createClass(Lower, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg != null) { return arg.toLowerCase(); } else { return null; } } }]); return Lower; }(Expression); // Indexer is completely handled by overloaded#Indexer var PositionOf = /*#__PURE__*/function (_Expression7) { _inherits(PositionOf, _Expression7); var _super7 = _createSuper(PositionOf); function PositionOf(json) { var _this4; _classCallCheck(this, PositionOf); _this4 = _super7.call(this, json); _this4.pattern = build(json.pattern); _this4.string = build(json.string); return _this4; } _createClass(PositionOf, [{ key: "exec", value: function exec(ctx) { var pattern = this.pattern.execute(ctx); var string = this.string.execute(ctx); if (pattern == null || string == null) { return null; } else { return string.indexOf(pattern); } } }]); return PositionOf; }(Expression); var LastPositionOf = /*#__PURE__*/function (_Expression8) { _inherits(LastPositionOf, _Expression8); var _super8 = _createSuper(LastPositionOf); function LastPositionOf(json) { var _this5; _classCallCheck(this, LastPositionOf); _this5 = _super8.call(this, json); _this5.pattern = build(json.pattern); _this5.string = build(json.string); return _this5; } _createClass(LastPositionOf, [{ key: "exec", value: function exec(ctx) { var pattern = this.pattern.execute(ctx); var string = this.string.execute(ctx); if (pattern == null || string == null) { return null; } else { return string.lastIndexOf(pattern); } } }]); return LastPositionOf; }(Expression); var Matches = /*#__PURE__*/function (_Expression9) { _inherits(Matches, _Expression9); var _super9 = _createSuper(Matches); function Matches(json) { _classCallCheck(this, Matches); return _super9.call(this, json); } _createClass(Matches, [{ key: "exec", value: function exec(ctx) { var _this$execArgs = this.execArgs(ctx), _this$execArgs2 = _slicedToArray(_this$execArgs, 2), string = _this$execArgs2[0], pattern = _this$execArgs2[1]; if (string == null || pattern == null) { return null; } return new RegExp('^' + pattern + '$').test(string); } }]); return Matches; }(Expression); var Substring = /*#__PURE__*/function (_Expression10) { _inherits(Substring, _Expression10); var _super10 = _createSuper(Substring); function Substring(json) { var _this6; _classCallCheck(this, Substring); _this6 = _super10.call(this, json); _this6.stringToSub = build(json.stringToSub); _this6.startIndex = build(json.startIndex); _this6.length = build(json['length']); return _this6; } _createClass(Substring, [{ key: "exec", value: function exec(ctx) { var stringToSub = this.stringToSub.execute(ctx); var startIndex = this.startIndex.execute(ctx); var length = this.length != null ? this.length.execute(ctx) : null; // According to spec: If stringToSub or startIndex is null, or startIndex is out of range, the result is null. if (stringToSub == null || startIndex == null || startIndex < 0 || startIndex >= stringToSub.length) { return null; } else if (length != null) { return stringToSub.substr(startIndex, length); } else { return stringToSub.substr(startIndex); } } }]); return Substring; }(Expression); var StartsWith = /*#__PURE__*/function (_Expression11) { _inherits(StartsWith, _Expression11); var _super11 = _createSuper(StartsWith); function StartsWith(json) { _classCallCheck(this, StartsWith); return _super11.call(this, json); } _createClass(StartsWith, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx); if (args.some(function (x) { return x == null; })) { return null; } else { return args[0].slice(0, args[1].length) === args[1]; } } }]); return StartsWith; }(Expression); var EndsWith = /*#__PURE__*/function (_Expression12) { _inherits(EndsWith, _Expression12); var _super12 = _createSuper(EndsWith); function EndsWith(json) { _classCallCheck(this, EndsWith); return _super12.call(this, json); } _createClass(EndsWith, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx); if (args.some(function (x) { return x == null; })) { return null; } else { return args[1] === '' || args[0].slice(-args[1].length) === args[1]; } } }]); return EndsWith; }(Expression); var ReplaceMatches = /*#__PURE__*/function (_Expression13) { _inherits(ReplaceMatches, _Expression13); var _super13 = _createSuper(ReplaceMatches); function ReplaceMatches(json) { _classCallCheck(this, ReplaceMatches); return _super13.call(this, json); } _createClass(ReplaceMatches, [{ key: "exec", value: function exec(ctx) { var args = this.execArgs(ctx); if (args.some(function (x) { return x == null; })) { return null; } else { return args[0].replace(new RegExp(args[1], 'g'), args[2]); } } }]); return ReplaceMatches; }(Expression); module.exports = { Combine: Combine, Concatenate: Concatenate, EndsWith: EndsWith, LastPositionOf: LastPositionOf, Lower: Lower, Matches: Matches, PositionOf: PositionOf, ReplaceMatches: ReplaceMatches, Split: Split, SplitOnMatches: SplitOnMatches, StartsWith: StartsWith, Substring: Substring, Upper: Upper }; },{"./builder":144,"./expression":150}],167:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression, UnimplementedExpression = _require.UnimplementedExpression; var _require2 = require('./builder'), build = _require2.build; var Property = /*#__PURE__*/function (_Expression) { _inherits(Property, _Expression); var _super = _createSuper(Property); function Property(json) { var _this; _classCallCheck(this, Property); _this = _super.call(this, json); _this.scope = json.scope; _this.source = build(json.source); _this.path = json.path; return _this; } _createClass(Property, [{ key: "exec", value: function exec(ctx) { var obj = this.scope != null ? ctx.get(this.scope) : this.source; if (obj instanceof Expression) { obj = obj.execute(ctx); } var val = getPropertyFromObject(obj, this.path); if (val == null) { var parts = this.path.split('.'); var curr_obj = obj; var _iterator = _createForOfIteratorHelper(parts), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var part = _step.value; var _obj = getPropertyFromObject(curr_obj, part); curr_obj = _obj instanceof Function ? _obj.call(curr_obj) : _obj; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } val = curr_obj != null ? curr_obj : null; // convert undefined to null } if (val instanceof Function) { return val.call(obj); } else { return val; } } }]); return Property; }(Expression); function getPropertyFromObject(obj, path) { var val; if (obj != null) { val = obj[path]; if (val === undefined && typeof obj.get === 'function') { val = obj.get(path); } } return val; } var Tuple = /*#__PURE__*/function (_Expression2) { _inherits(Tuple, _Expression2); var _super2 = _createSuper(Tuple); function Tuple(json) { var _this2; _classCallCheck(this, Tuple); _this2 = _super2.call(this, json); var elements = json.element != null ? json.element : []; _this2.elements = elements.map(function (el) { return { name: el.name, value: build(el.value) }; }); return _this2; } _createClass(Tuple, [{ key: "exec", value: function exec(ctx) { var val = {}; var _iterator2 = _createForOfIteratorHelper(this.elements), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var el = _step2.value; val[el.name] = el.value != null ? el.value.execute(ctx) : undefined; } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return val; } }, { key: "isTuple", get: function get() { return true; } }]); return Tuple; }(Expression); var TupleElement = /*#__PURE__*/function (_UnimplementedExpress) { _inherits(TupleElement, _UnimplementedExpress); var _super3 = _createSuper(TupleElement); function TupleElement() { _classCallCheck(this, TupleElement); return _super3.apply(this, arguments); } return TupleElement; }(UnimplementedExpression); var TupleElementDefinition = /*#__PURE__*/function (_UnimplementedExpress2) { _inherits(TupleElementDefinition, _UnimplementedExpress2); var _super4 = _createSuper(TupleElementDefinition); function TupleElementDefinition() { _classCallCheck(this, TupleElementDefinition); return _super4.apply(this, arguments); } return TupleElementDefinition; }(UnimplementedExpression); module.exports = { Property: Property, Tuple: Tuple, TupleElement: TupleElement, TupleElementDefinition: TupleElementDefinition }; },{"./builder":144,"./expression":150}],168:[function(require,module,exports){ "use strict"; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; 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) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('./expression'), Expression = _require.Expression, UnimplementedExpression = _require.UnimplementedExpression; var _require2 = require('../datatypes/datetime'), DateTime = _require2.DateTime, _Date = _require2.Date; var _require3 = require('../datatypes/clinical'), Concept = _require3.Concept; var _require4 = require('../datatypes/quantity'), parseQuantity = _require4.parseQuantity; var _require5 = require('../util/math'), isValidDecimal = _require5.isValidDecimal, isValidInteger = _require5.isValidInteger, limitDecimalPrecision = _require5.limitDecimalPrecision; var _require6 = require('../util/util'), normalizeMillisecondsField = _require6.normalizeMillisecondsField; var _require7 = require('../datatypes/ratio'), Ratio = _require7.Ratio; var _require8 = require('../datatypes/uncertainty'), Uncertainty = _require8.Uncertainty; // TODO: Casting and Conversion needs unit tests! var As = /*#__PURE__*/function (_Expression) { _inherits(As, _Expression); var _super = _createSuper(As); function As(json) { var _this; _classCallCheck(this, As); _this = _super.call(this, json); if (json.asTypeSpecifier) { _this.asTypeSpecifier = json.asTypeSpecifier; } else if (json.asType) { // convert it to a NamedTypedSpecifier _this.asTypeSpecifier = { name: json.asType, type: 'NamedTypeSpecifier' }; } _this.strict = json.strict != null ? json.strict : false; return _this; } _createClass(As, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); // If it is null, return null if (arg == null) { return null; } if (ctx.matchesTypeSpecifier(arg, this.asTypeSpecifier)) { // TODO: request patient source to change type identification return arg; } else if (this.strict) { var argTypeString = specifierToString(guessSpecifierType(arg)); var asTypeString = specifierToString(this.asTypeSpecifier); throw new Error("Cannot cast ".concat(argTypeString, " as ").concat(asTypeString)); } else { return null; } } }]); return As; }(Expression); var ToBoolean = /*#__PURE__*/function (_Expression2) { _inherits(ToBoolean, _Expression2); var _super2 = _createSuper(ToBoolean); function ToBoolean(json) { _classCallCheck(this, ToBoolean); return _super2.call(this, json); } _createClass(ToBoolean, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg != null) { var strArg = arg.toString().toLowerCase(); if (['true', 't', 'yes', 'y', '1'].includes(strArg)) { return true; } else if (['false', 'f', 'no', 'n', '0'].includes(strArg)) { return false; } } return null; } }]); return ToBoolean; }(Expression); var ToConcept = /*#__PURE__*/function (_Expression3) { _inherits(ToConcept, _Expression3); var _super3 = _createSuper(ToConcept); function ToConcept(json) { _classCallCheck(this, ToConcept); return _super3.call(this, json); } _createClass(ToConcept, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg != null) { return new Concept([arg], arg.display); } else { return null; } } }]); return ToConcept; }(Expression); var ToDate = /*#__PURE__*/function (_Expression4) { _inherits(ToDate, _Expression4); var _super4 = _createSuper(ToDate); function ToDate(json) { _classCallCheck(this, ToDate); return _super4.call(this, json); } _createClass(ToDate, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg == null) { return null; } else if (arg.isDateTime) { return arg.getDate(); } else { return _Date.parse(arg.toString()); } } }]); return ToDate; }(Expression); var ToDateTime = /*#__PURE__*/function (_Expression5) { _inherits(ToDateTime, _Expression5); var _super5 = _createSuper(ToDateTime); function ToDateTime(json) { _classCallCheck(this, ToDateTime); return _super5.call(this, json); } _createClass(ToDateTime, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg == null) { return null; } else if (arg.isDate) { return arg.getDateTime(); } else { return DateTime.parse(arg.toString()); } } }]); return ToDateTime; }(Expression); var ToDecimal = /*#__PURE__*/function (_Expression6) { _inherits(ToDecimal, _Expression6); var _super6 = _createSuper(ToDecimal); function ToDecimal(json) { _classCallCheck(this, ToDecimal); return _super6.call(this, json); } _createClass(ToDecimal, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg != null) { if (arg.isUncertainty) { var low = limitDecimalPrecision(parseFloat(arg.low.toString())); var high = limitDecimalPrecision(parseFloat(arg.high.toString())); return new Uncertainty(low, high); } else { var decimal = limitDecimalPrecision(parseFloat(arg.toString())); if (isValidDecimal(decimal)) { return decimal; } } } return null; } }]); return ToDecimal; }(Expression); var ToInteger = /*#__PURE__*/function (_Expression7) { _inherits(ToInteger, _Expression7); var _super7 = _createSuper(ToInteger); function ToInteger(json) { _classCallCheck(this, ToInteger); return _super7.call(this, json); } _createClass(ToInteger, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg != null) { var integer = parseInt(arg.toString()); if (isValidInteger(integer)) { return integer; } } return null; } }]); return ToInteger; }(Expression); var ToQuantity = /*#__PURE__*/function (_Expression8) { _inherits(ToQuantity, _Expression8); var _super8 = _createSuper(ToQuantity); function ToQuantity(json) { _classCallCheck(this, ToQuantity); return _super8.call(this, json); } _createClass(ToQuantity, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg != null) { return parseQuantity(arg.toString()); } else { return null; } } }]); return ToQuantity; }(Expression); var ToRatio = /*#__PURE__*/function (_Expression9) { _inherits(ToRatio, _Expression9); var _super9 = _createSuper(ToRatio); function ToRatio(json) { _classCallCheck(this, ToRatio); return _super9.call(this, json); } _createClass(ToRatio, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg != null) { // Argument will be of form ':' var denominator, numerator; try { // String will be split into an array. Numerator will be at index 1, Denominator will be at index 4 var splitRatioString = arg.toString().match(/^(\d+(\.\d+)?\s*('.+')?)\s*:\s*(\d+(\.\d+)?\s*('.+')?)$/); if (splitRatioString == null) { return null; } numerator = parseQuantity(splitRatioString[1]); denominator = parseQuantity(splitRatioString[4]); } catch (error) { // If the input string is not formatted correctly, or cannot be // interpreted as a valid Quantity value, the result is null. return null; } // The value element of a Quantity must be present. if (numerator == null || denominator == null) { return null; } return new Ratio(numerator, denominator); } else { return null; } } }]); return ToRatio; }(Expression); var ToString = /*#__PURE__*/function (_Expression10) { _inherits(ToString, _Expression10); var _super10 = _createSuper(ToString); function ToString(json) { _classCallCheck(this, ToString); return _super10.call(this, json); } _createClass(ToString, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg != null) { return arg.toString(); } else { return null; } } }]); return ToString; }(Expression); var ToTime = /*#__PURE__*/function (_Expression11) { _inherits(ToTime, _Expression11); var _super11 = _createSuper(ToTime); function ToTime(json) { _classCallCheck(this, ToTime); return _super11.call(this, json); } _createClass(ToTime, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg != null) { var timeString = arg.toString(); // Return null if string doesn't represent a valid ISO-8601 Time // hh:mm:ss.fff or hh:mm:ss.fff var matches = /^T?((\d{2})(:(\d{2})(:(\d{2})(\.(\d+))?)?)?)?(Z|(([+-])(\d{2})(:?(\d{2}))?))?$/.exec(timeString); if (matches == null) { return null; } var hours = matches[2]; var minutes = matches[4]; var seconds = matches[6]; // Validate h/m/s if they exist, but allow null if (hours != null) { if (hours < 0 || hours > 23) { return null; } hours = parseInt(hours, 10); } if (minutes != null) { if (minutes < 0 || minutes > 59) { return null; } minutes = parseInt(minutes, 10); } if (seconds != null) { if (seconds < 0 || seconds > 59) { return null; } seconds = parseInt(seconds, 10); } var milliseconds = matches[8]; if (milliseconds != null) { milliseconds = parseInt(normalizeMillisecondsField(milliseconds)); } // Time is implemented as Datetime with year 0, month 1, day 1 and null timezoneOffset return new DateTime(0, 1, 1, hours, minutes, seconds, milliseconds, null); } else { return null; } } }]); return ToTime; }(Expression); var Convert = /*#__PURE__*/function (_Expression12) { _inherits(Convert, _Expression12); var _super12 = _createSuper(Convert); function Convert(json) { var _this2; _classCallCheck(this, Convert); _this2 = _super12.call(this, json); _this2.operand = json.operand; _this2.toType = json.toType; return _this2; } _createClass(Convert, [{ key: "exec", value: function exec(ctx) { switch (this.toType) { case '{urn:hl7-org:elm-types:r1}Boolean': return new ToBoolean({ type: 'ToBoolean', operand: this.operand }).execute(ctx); case '{urn:hl7-org:elm-types:r1}Concept': return new ToConcept({ type: 'ToConcept', operand: this.operand }).execute(ctx); case '{urn:hl7-org:elm-types:r1}Decimal': return new ToDecimal({ type: 'ToDecimal', operand: this.operand }).execute(ctx); case '{urn:hl7-org:elm-types:r1}Integer': return new ToInteger({ type: 'ToInteger', operand: this.operand }).execute(ctx); case '{urn:hl7-org:elm-types:r1}String': return new ToString({ type: 'ToString', operand: this.operand }).execute(ctx); case '{urn:hl7-org:elm-types:r1}Quantity': return new ToQuantity({ type: 'ToQuantity', operand: this.operand }).execute(ctx); case '{urn:hl7-org:elm-types:r1}DateTime': return new ToDateTime({ type: 'ToDateTime', operand: this.operand }).execute(ctx); case '{urn:hl7-org:elm-types:r1}Date': return new ToDate({ type: 'ToDate', operand: this.operand }).execute(ctx); case '{urn:hl7-org:elm-types:r1}Time': return new ToTime({ type: 'ToTime', operand: this.operand }).execute(ctx); default: return this.execArgs(ctx); } } }]); return Convert; }(Expression); var ConvertsToBoolean = /*#__PURE__*/function (_Expression13) { _inherits(ConvertsToBoolean, _Expression13); var _super13 = _createSuper(ConvertsToBoolean); function ConvertsToBoolean(json) { var _this3; _classCallCheck(this, ConvertsToBoolean); _this3 = _super13.call(this, json); _this3.operand = json.operand; return _this3; } _createClass(ConvertsToBoolean, [{ key: "exec", value: function exec(ctx) { var operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToBoolean, this.operand, ctx); } } }]); return ConvertsToBoolean; }(Expression); var ConvertsToDate = /*#__PURE__*/function (_Expression14) { _inherits(ConvertsToDate, _Expression14); var _super14 = _createSuper(ConvertsToDate); function ConvertsToDate(json) { var _this4; _classCallCheck(this, ConvertsToDate); _this4 = _super14.call(this, json); _this4.operand = json.operand; return _this4; } _createClass(ConvertsToDate, [{ key: "exec", value: function exec(ctx) { var operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToDate, this.operand, ctx); } } }]); return ConvertsToDate; }(Expression); var ConvertsToDateTime = /*#__PURE__*/function (_Expression15) { _inherits(ConvertsToDateTime, _Expression15); var _super15 = _createSuper(ConvertsToDateTime); function ConvertsToDateTime(json) { var _this5; _classCallCheck(this, ConvertsToDateTime); _this5 = _super15.call(this, json); _this5.operand = json.operand; return _this5; } _createClass(ConvertsToDateTime, [{ key: "exec", value: function exec(ctx) { var operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToDateTime, this.operand, ctx); } } }]); return ConvertsToDateTime; }(Expression); var ConvertsToDecimal = /*#__PURE__*/function (_Expression16) { _inherits(ConvertsToDecimal, _Expression16); var _super16 = _createSuper(ConvertsToDecimal); function ConvertsToDecimal(json) { var _this6; _classCallCheck(this, ConvertsToDecimal); _this6 = _super16.call(this, json); _this6.operand = json.operand; return _this6; } _createClass(ConvertsToDecimal, [{ key: "exec", value: function exec(ctx) { var operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToDecimal, this.operand, ctx); } } }]); return ConvertsToDecimal; }(Expression); var ConvertsToInteger = /*#__PURE__*/function (_Expression17) { _inherits(ConvertsToInteger, _Expression17); var _super17 = _createSuper(ConvertsToInteger); function ConvertsToInteger(json) { var _this7; _classCallCheck(this, ConvertsToInteger); _this7 = _super17.call(this, json); _this7.operand = json.operand; return _this7; } _createClass(ConvertsToInteger, [{ key: "exec", value: function exec(ctx) { var operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToInteger, this.operand, ctx); } } }]); return ConvertsToInteger; }(Expression); var ConvertsToQuantity = /*#__PURE__*/function (_Expression18) { _inherits(ConvertsToQuantity, _Expression18); var _super18 = _createSuper(ConvertsToQuantity); function ConvertsToQuantity(json) { var _this8; _classCallCheck(this, ConvertsToQuantity); _this8 = _super18.call(this, json); _this8.operand = json.operand; return _this8; } _createClass(ConvertsToQuantity, [{ key: "exec", value: function exec(ctx) { var operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToQuantity, this.operand, ctx); } } }]); return ConvertsToQuantity; }(Expression); var ConvertsToRatio = /*#__PURE__*/function (_Expression19) { _inherits(ConvertsToRatio, _Expression19); var _super19 = _createSuper(ConvertsToRatio); function ConvertsToRatio(json) { var _this9; _classCallCheck(this, ConvertsToRatio); _this9 = _super19.call(this, json); _this9.operand = json.operand; return _this9; } _createClass(ConvertsToRatio, [{ key: "exec", value: function exec(ctx) { var operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToRatio, this.operand, ctx); } } }]); return ConvertsToRatio; }(Expression); var ConvertsToString = /*#__PURE__*/function (_Expression20) { _inherits(ConvertsToString, _Expression20); var _super20 = _createSuper(ConvertsToString); function ConvertsToString(json) { var _this10; _classCallCheck(this, ConvertsToString); _this10 = _super20.call(this, json); _this10.operand = json.operand; return _this10; } _createClass(ConvertsToString, [{ key: "exec", value: function exec(ctx) { var operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToString, this.operand, ctx); } } }]); return ConvertsToString; }(Expression); var ConvertsToTime = /*#__PURE__*/function (_Expression21) { _inherits(ConvertsToTime, _Expression21); var _super21 = _createSuper(ConvertsToTime); function ConvertsToTime(json) { var _this11; _classCallCheck(this, ConvertsToTime); _this11 = _super21.call(this, json); _this11.operand = json.operand; return _this11; } _createClass(ConvertsToTime, [{ key: "exec", value: function exec(ctx) { var operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToTime, this.operand, ctx); } } }]); return ConvertsToTime; }(Expression); function canConvertToType(toFunction, operand, ctx) { try { var value = new toFunction({ type: toFunction.name, operand: operand }).execute(ctx); if (value != null) { return true; } else { return false; } } catch (error) { return false; } } var ConvertQuantity = /*#__PURE__*/function (_Expression22) { _inherits(ConvertQuantity, _Expression22); var _super22 = _createSuper(ConvertQuantity); function ConvertQuantity(json) { _classCallCheck(this, ConvertQuantity); return _super22.call(this, json); } _createClass(ConvertQuantity, [{ key: "exec", value: function exec(ctx) { var _this$execArgs = this.execArgs(ctx), _this$execArgs2 = _slicedToArray(_this$execArgs, 2), quantity = _this$execArgs2[0], newUnit = _this$execArgs2[1]; if (quantity != null && newUnit != null) { try { return quantity.convertUnit(newUnit); } catch (error) { // Cannot convert input to target unit, spec says to return null return null; } } } }]); return ConvertQuantity; }(Expression); var CanConvertQuantity = /*#__PURE__*/function (_Expression23) { _inherits(CanConvertQuantity, _Expression23); var _super23 = _createSuper(CanConvertQuantity); function CanConvertQuantity(json) { _classCallCheck(this, CanConvertQuantity); return _super23.call(this, json); } _createClass(CanConvertQuantity, [{ key: "exec", value: function exec(ctx) { var _this$execArgs3 = this.execArgs(ctx), _this$execArgs4 = _slicedToArray(_this$execArgs3, 2), quantity = _this$execArgs4[0], newUnit = _this$execArgs4[1]; if (quantity != null && newUnit != null) { try { quantity.convertUnit(newUnit); return true; } catch (error) { return false; } } return null; } }]); return CanConvertQuantity; }(Expression); var Is = /*#__PURE__*/function (_Expression24) { _inherits(Is, _Expression24); var _super24 = _createSuper(Is); function Is(json) { var _this12; _classCallCheck(this, Is); _this12 = _super24.call(this, json); if (json.isTypeSpecifier) { _this12.isTypeSpecifier = json.isTypeSpecifier; } else if (json.isType) { // Convert it to a NamedTypeSpecifier _this12.isTypeSpecifier = { name: json.isType, type: 'NamedTypeSpecifier' }; } return _this12; } _createClass(Is, [{ key: "exec", value: function exec(ctx) { var arg = this.execArgs(ctx); if (arg === null) { return false; } if (typeof arg._is !== 'function' && !isSystemType(this.isTypeSpecifier)) { // We need an _is implementation in order to check non System types throw new Error("Patient Source does not support Is operation for localId: ".concat(this.localId)); } return ctx.matchesTypeSpecifier(arg, this.isTypeSpecifier); } }]); return Is; }(Expression); function isSystemType(spec) { switch (spec.type) { case 'NamedTypeSpecifier': return spec.name.startsWith('{urn:hl7-org:elm-types:r1}'); case 'ListTypeSpecifier': return isSystemType(spec.elementType); case 'TupleTypeSpecifier': return spec.element.every(function (e) { return isSystemType(e.elementType); }); case 'IntervalTypeSpecifier': return isSystemType(spec.pointType); case 'ChoiceTypeSpecifier': return spec.choice.every(function (c) { return isSystemType(c); }); default: return false; } } function specifierToString(spec) { if (typeof spec === 'string') { return spec; } else if (spec == null || spec.type == null) { return ''; } switch (spec.type) { case 'NamedTypeSpecifier': return spec.name; case 'ListTypeSpecifier': return "List<".concat(specifierToString(spec.elementType), ">"); case 'TupleTypeSpecifier': return "Tuple<".concat(spec.element.map(function (e) { return "".concat(e.name, " ").concat(specifierToString(e.elementType)); }).join(', '), ">"); case 'IntervalTypeSpecifier': return "Interval<".concat(specifierToString(spec.pointType), ">"); case 'ChoiceTypeSpecifier': return "Choice<".concat(spec.choice.map(function (c) { return specifierToString(c); }).join(', '), ">"); default: return JSON.stringify(spec); } } function guessSpecifierType(val) { if (val == null) { return 'Null'; } var typeHierarchy = typeof val._typeHierarchy === 'function' && val._typeHierarchy(); if (typeHierarchy && typeHierarchy.length > 0) { return typeHierarchy[0]; } else if (typeof val === 'boolean') { return { type: 'NamedTypeSpecifier', name: '{urn:hl7-org:elm-types:r1}Boolean' }; } else if (typeof val === 'number' && Math.floor(val) === val) { // it could still be a decimal, but we have to just take our best guess! return { type: 'NamedTypeSpecifier', name: '{urn:hl7-org:elm-types:r1}Integer' }; } else if (typeof val === 'number') { return { type: 'NamedTypeSpecifier', name: '{urn:hl7-org:elm-types:r1}Decimal' }; } else if (typeof val === 'string') { return { type: 'NamedTypeSpecifier', name: '{urn:hl7-org:elm-types:r1}String' }; } else if (val.isConcept) { return { type: 'NamedTypeSpecifier', name: '{urn:hl7-org:elm-types:r1}Concept' }; } else if (val.isCode) { return { type: 'NamedTypeSpecifier', name: '{urn:hl7-org:elm-types:r1}Code' }; } else if (val.isDate) { return { type: 'NamedTypeSpecifier', name: '{urn:hl7-org:elm-types:r1}Date' }; } else if (val.isTime && val.isTime()) { return { type: 'NamedTypeSpecifier', name: '{urn:hl7-org:elm-types:r1}Time' }; } else if (val.isDateTime) { return { type: 'NamedTypeSpecifier', name: '{urn:hl7-org:elm-types:r1}DateTime' }; } else if (val.isQuantity) { return { type: 'NamedTypeSpecifier', name: '{urn:hl7-org:elm-types:r1}DateTime' }; } else if (Array.isArray(val)) { // Get unique types from the array (by converting to string and putting in a Set) var typesAsStrings = Array.from(new Set(val.map(function (v) { return JSON.stringify(guessSpecifierType(v)); }))); var types = typesAsStrings.map(function (ts) { return /^{/.test(ts) ? JSON.parse(ts) : ts; }); return { type: 'ListTypeSpecifier', elementType: types.length == 1 ? types[0] : { type: 'ChoiceTypeSpecifier', choice: types } }; } else if (val.isInterval) { return { type: 'IntervalTypeSpecifier', pointType: val.pointType }; } else if (_typeof(val) === 'object' && Object.keys(val).length > 0) { return { type: 'TupleTypeSpecifier', element: Object.keys(val).map(function (k) { return { name: k, elementType: guessSpecifierType(val[k]) }; }) }; } return 'Unknown'; } var IntervalTypeSpecifier = /*#__PURE__*/function (_UnimplementedExpress) { _inherits(IntervalTypeSpecifier, _UnimplementedExpress); var _super25 = _createSuper(IntervalTypeSpecifier); function IntervalTypeSpecifier() { _classCallCheck(this, IntervalTypeSpecifier); return _super25.apply(this, arguments); } return IntervalTypeSpecifier; }(UnimplementedExpression); var ListTypeSpecifier = /*#__PURE__*/function (_UnimplementedExpress2) { _inherits(ListTypeSpecifier, _UnimplementedExpress2); var _super26 = _createSuper(ListTypeSpecifier); function ListTypeSpecifier() { _classCallCheck(this, ListTypeSpecifier); return _super26.apply(this, arguments); } return ListTypeSpecifier; }(UnimplementedExpression); var NamedTypeSpecifier = /*#__PURE__*/function (_UnimplementedExpress3) { _inherits(NamedTypeSpecifier, _UnimplementedExpress3); var _super27 = _createSuper(NamedTypeSpecifier); function NamedTypeSpecifier() { _classCallCheck(this, NamedTypeSpecifier); return _super27.apply(this, arguments); } return NamedTypeSpecifier; }(UnimplementedExpression); var TupleTypeSpecifier = /*#__PURE__*/function (_UnimplementedExpress4) { _inherits(TupleTypeSpecifier, _UnimplementedExpress4); var _super28 = _createSuper(TupleTypeSpecifier); function TupleTypeSpecifier() { _classCallCheck(this, TupleTypeSpecifier); return _super28.apply(this, arguments); } return TupleTypeSpecifier; }(UnimplementedExpression); module.exports = { As: As, CanConvertQuantity: CanConvertQuantity, Convert: Convert, ConvertQuantity: ConvertQuantity, ConvertsToBoolean: ConvertsToBoolean, ConvertsToDate: ConvertsToDate, ConvertsToDateTime: ConvertsToDateTime, ConvertsToDecimal: ConvertsToDecimal, ConvertsToInteger: ConvertsToInteger, ConvertsToQuantity: ConvertsToQuantity, ConvertsToRatio: ConvertsToRatio, ConvertsToString: ConvertsToString, ConvertsToTime: ConvertsToTime, IntervalTypeSpecifier: IntervalTypeSpecifier, Is: Is, ListTypeSpecifier: ListTypeSpecifier, NamedTypeSpecifier: NamedTypeSpecifier, ToBoolean: ToBoolean, ToConcept: ToConcept, ToDate: ToDate, ToDateTime: ToDateTime, ToDecimal: ToDecimal, ToInteger: ToInteger, ToQuantity: ToQuantity, ToRatio: ToRatio, ToString: ToString, ToTime: ToTime, TupleTypeSpecifier: TupleTypeSpecifier }; },{"../datatypes/clinical":133,"../datatypes/datetime":135,"../datatypes/quantity":139,"../datatypes/ratio":140,"../datatypes/uncertainty":141,"../util/math":174,"../util/util":176,"./expression":150}],169:[function(require,module,exports){ "use strict"; 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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); return Constructor; } var _require = require('../datatypes/exception'), Exception = _require.Exception; var _require2 = require('../util/util'), typeIsArray = _require2.typeIsArray; var dt = require('../datatypes/datatypes'); var Context = /*#__PURE__*/function () { function Context(parent) { var _codeService = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var _parameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; _classCallCheck(this, Context); this.parent = parent; this._codeService = _codeService; this.context_values = {}; this.library_context = {}; this.localId_context = {}; this.evaluatedRecords = []; // TODO: If there is an issue with number of parameters look into cql4browsers fix: 387ea77538182833283af65e6341e7a05192304c this.checkParameters(_parameters); // not crazy about possibly throwing an error in a constructor, but... this._parameters = _parameters; } _createClass(Context, [{ key: "withParameters", value: function withParameters(params) { this.parameters = params || {}; return this; } }, { key: "withCodeService", value: function withCodeService(cs) { this.codeService = cs; return this; } }, { key: "rootContext", value: function rootContext() { if (this.parent) { return this.parent.rootContext(); } else { return this; } } }, { key: "findRecords", value: function findRecords(profile) { return this.parent && this.parent.findRecords(profile); } }, { key: "childContext", value: function childContext() { var context_values = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var ctx = new Context(this); ctx.context_values = context_values; return ctx; } }, { key: "getLibraryContext", value: function getLibraryContext(library) { return this.parent && this.parent.getLibraryContext(library); } }, { key: "getLocalIdContext", value: function getLocalIdContext(localId) { return this.parent && this.parent.getLocalIdContext(localId); } }, { key: "getParameter", value: function getParameter(name) { return this.parent && this.parent.getParameter(name); } }, { key: "getParentParameter", value: function getParentParameter(name) { if (this.parent) { if (this.parent.parameters[name] != null) { return this.parent.parameters[name]; } else { return this.parent.getParentParameter(name); } } } }, { key: "getTimezoneOffset", value: function getTimezoneOffset() { if (this.executionDateTime != null) { return this.executionDateTime.timezoneOffset; } else if (this.parent && this.parent.getTimezoneOffset != null) { return this.parent.getTimezoneOffset(); } else { throw new Exception('No Timezone Offset has been set'); } } }, { key: "getExecutionDateTime", value: function getExecutionDateTime() { if (this.executionDateTime != null) { return this.executionDateTime; } else if (this.parent && this.parent.getExecutionDateTime != null) { return this.parent.getExecutionDateTime(); } else { throw new Exception('No Execution DateTime has been set'); } } }, { key: "getValueSet", value: function getValueSet(name, library) { return this.parent && this.parent.getValueSet(name, library); } }, { key: "getCodeSystem", value: function getCodeSystem(name) { return this.parent && this.parent.getCodeSystem(name); } }, { key: "getCode", value: function getCode(name) { return this.parent && this.parent.getCode(name); } }, { key: "getConcept", value: function getConcept(name) { return this.parent && this.parent.getConcept(name); } }, { key: "get", value: function get(identifier) { // Check for undefined because if its null, we actually *do* want to return null (rather than // looking at parent), but if it's really undefined, *then* look at the parent if (typeof this.context_values[identifier] !== 'undefined') { return this.context_values[identifier]; } else if (identifier === '$this') { return this.context_values; } else { return this.parent != null && this.parent.get(identifier); } } }, { key: "set", value: function set(identifier, value) { this.context_values[identifier] = value; } }, { key: "setLocalIdWithResult", value: function setLocalIdWithResult(localId, value) { // Temporary fix. Real fix will be to return a list of all result values for a given localId. var ctx = this.localId_context[localId]; if (ctx === false || ctx === null || ctx === undefined || ctx.length === 0) { this.localId_context[localId] = value; } } }, { key: "getLocalIdResult", value: function getLocalIdResult(localId) { return this.localId_context[localId]; } // Returns an object of objects containing each library name // with the localIds and result values }, { key: "getAllLocalIds", value: function getAllLocalIds() { var localIdResults = {}; // Add the localIds and result values from the main library localIdResults[this.parent.source.library.identifier.id] = {}; localIdResults[this.parent.source.library.identifier.id] = this.localId_context; // Iterate over support libraries and store localIds for (var libName in this.library_context) { var lib = this.library_context[libName]; this.supportLibraryLocalIds(lib, localIdResults); } return localIdResults; } // Recursive function that will grab nested support library localId results }, { key: "supportLibraryLocalIds", value: function supportLibraryLocalIds(lib, localIdResults) { var _this = this; // Set library identifier name as the key and the object of localIds with their results as the value // if it already exists then we need to merge the results instead of overwriting if (localIdResults[lib.library.source.library.identifier.id] != null) { this.mergeLibraryLocalIdResults(localIdResults, lib.library.source.library.identifier.id, lib.localId_context); } else { localIdResults[lib.library.source.library.identifier.id] = lib.localId_context; } // Iterate over any support libraries in the current support library Object.values(lib.library_context).forEach(function (supportLib) { _this.supportLibraryLocalIds(supportLib, localIdResults); }); } // Merges the localId results for a library into the already collected results. The logic used for which result // to keep is the same as the logic used above in setLocalIdWithResult, "falsey" results are always replaced. }, { key: "mergeLibraryLocalIdResults", value: function mergeLibraryLocalIdResults(localIdResults, libraryId, libraryResults) { for (var localId in libraryResults) { var localIdResult = libraryResults[localId]; var existingResult = localIdResults[libraryId][localId]; // overwite this localid result if the existing result is "falsey". future work could track all results for each localid if (existingResult === false || existingResult === null || existingResult === undefined || existingResult.length === 0) { localIdResults[libraryId][localId] = localIdResult; } } } }, { key: "checkParameters", value: function checkParameters(params) { for (var pName in params) { var pVal = params[pName]; var pDef = this.getParameter(pName); if (pVal == null) { return; // Null can theoretically be any type } if (typeof pDef === 'undefined') { return; // This will happen if the parameter is declared in a different (included) library } else if (pDef.parameterTypeSpecifier != null && !this.matchesTypeSpecifier(pVal, pDef.parameterTypeSpecifier)) { throw new Error("Passed in parameter '".concat(pName, "' is wrong type")); } else if (pDef['default'] != null && !this.matchesInstanceType(pVal, pDef['default'])) { throw new Error("Passed in parameter '".concat(pName, "' is wrong type")); } } return true; } }, { key: "matchesTypeSpecifier", value: function matchesTypeSpecifier(val, spec) { switch (spec.type) { case 'NamedTypeSpecifier': return this.matchesNamedTypeSpecifier(val, spec); case 'ListTypeSpecifier': return this.matchesListTypeSpecifier(val, spec); case 'TupleTypeSpecifier': return this.matchesTupleTypeSpecifier(val, spec); case 'IntervalTypeSpecifier': return this.matchesIntervalTypeSpecifier(val, spec); case 'ChoiceTypeSpecifier': return this.matchesChoiceTypeSpecifier(val, spec); default: return true; // default to true when we don't know } } }, { key: "matchesListTypeSpecifier", value: function matchesListTypeSpecifier(val, spec) { var _this2 = this; return typeIsArray(val) && val.every(function (x) { return _this2.matchesTypeSpecifier(x, spec.elementType); }); } }, { key: "matchesTupleTypeSpecifier", value: function matchesTupleTypeSpecifier(val, spec) { var _this3 = this; // TODO: Spec is not clear about exactly how tuples should be matched return val != null && _typeof(val) === 'object' && !typeIsArray(val) && !val.isInterval && !val.isConcept && !val.isCode && !val.isDateTime && !val.isDate && !val.isQuantity && spec.element.every(function (x) { return typeof val[x.name] === 'undefined' || _this3.matchesTypeSpecifier(val[x.name], x.elementType); }); } }, { key: "matchesIntervalTypeSpecifier", value: function matchesIntervalTypeSpecifier(val, spec) { return val.isInterval && (val.low == null || this.matchesTypeSpecifier(val.low, spec.pointType)) && (val.high == null || this.matchesTypeSpecifier(val.high, spec.pointType)); } }, { key: "matchesChoiceTypeSpecifier", value: function matchesChoiceTypeSpecifier(val, spec) { var _this4 = this; return spec.choice.some(function (c) { return _this4.matchesTypeSpecifier(val, c); }); } }, { key: "matchesNamedTypeSpecifier", value: function matchesNamedTypeSpecifier(val, spec) { if (val == null) { return true; } switch (spec.name) { case '{urn:hl7-org:elm-types:r1}Boolean': return typeof val === 'boolean'; case '{urn:hl7-org:elm-types:r1}Decimal': return typeof val === 'number'; case '{urn:hl7-org:elm-types:r1}Integer': return typeof val === 'number' && Math.floor(val) === val; case '{urn:hl7-org:elm-types:r1}String': return typeof val === 'string'; case '{urn:hl7-org:elm-types:r1}Concept': return val && val.isConcept; case '{urn:hl7-org:elm-types:r1}Code': return val && val.isCode; case '{urn:hl7-org:elm-types:r1}DateTime': return val && val.isDateTime; case '{urn:hl7-org:elm-types:r1}Date': return val && val.isDate; case '{urn:hl7-org:elm-types:r1}Quantity': return val && val.isQuantity; case '{urn:hl7-org:elm-types:r1}Time': return val && val.isTime && val.isTime(); default: // Use the data model's implementation of _is, if it is available if (typeof val._is === 'function') { return val._is(spec); } // If the value is an array or interval, then we assume it cannot be cast to a // named type. Technically, this is not 100% true because a modelinfo can define // a named type whose base type is a list or interval. But none of our models // (FHIR, QDM, QICore) do that, so for those models, this approach will always be // correct. if (Array.isArray(val) || val.isInterval) { return false; } // Otherwise just default to true to match legacy behavior. // // NOTE: This is also where arbitrary tuples land because they will not have // an "is" function and we don't encode the type information into the runtime // objects so we can't easily determine their type. We can't reject them, // else things like `Encounter{ id: "1" } is Encounter` would return false. // So for now we allow false positives in order to avoid false negatives. return true; } } }, { key: "matchesInstanceType", value: function matchesInstanceType(val, inst) { if (inst.isBooleanLiteral) { return typeof val === 'boolean'; } else if (inst.isDecimalLiteral) { return typeof val === 'number'; } else if (inst.isIntegerLiteral) { return typeof val === 'number' && Math.floor(val) === val; } else if (inst.isStringLiteral) { return typeof val === 'string'; } else if (inst.isCode) { return val && val.isCode; } else if (inst.isConcept) { return val && val.isConcept; } else if (inst.isTime && inst.isTime()) { return val && val.isTime && val.isTime(); } else if (inst.isDate) { return val && val.isDate; } else if (inst.isDateTime) { return val && val.isDateTime; } else if (inst.isQuantity) { return val && val.isQuantity; } else if (inst.isList) { return this.matchesListInstanceType(val, inst); } else if (inst.isTuple) { return this.matchesTupleInstanceType(val, inst); } else if (inst.isInterval) { return this.matchesIntervalInstanceType(val, inst); } return true; // default to true when we don't know for sure } }, { key: "matchesListInstanceType", value: function matchesListInstanceType(val, list) { var _this5 = this; return typeIsArray(val) && val.every(function (x) { return _this5.matchesInstanceType(x, list.elements[0]); }); } }, { key: "matchesTupleInstanceType", value: function matchesTupleInstanceType(val, tpl) { var _this6 = this; return _typeof(val) === 'object' && !typeIsArray(val) && tpl.elements.every(function (x) { return typeof val[x.name] === 'undefined' || _this6.matchesInstanceType(val[x.name], x.value); }); } }, { key: "matchesIntervalInstanceType", value: function matchesIntervalInstanceType(val, ivl) { var pointType = ivl.low != null ? ivl.low : ivl.high; return val.isInterval && (val.low == null || this.matchesInstanceType(val.low, pointType)) && (val.high == null || this.matchesInstanceType(val.high, pointType)); } }, { key: "parameters", get: function get() { return this._parameters || this.parent && this.parent.parameters; }, set: function set(params) { this.checkParameters(params); this._parameters = params; } }, { key: "codeService", get: function get() { return this._codeService || this.parent && this.parent.codeService; }, set: function set(cs) { this._codeService = cs; } }]); return Context; }(); var PatientContext = /*#__PURE__*/function (_Context) { _inherits(PatientContext, _Context); var _super = _createSuper(PatientContext); function PatientContext(library, patient, codeService, parameters) { var _this7; var executionDateTime = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : dt.DateTime.fromJSDate(new Date()); _classCallCheck(this, PatientContext); _this7 = _super.call(this, library, codeService, parameters); _this7.library = library; _this7.patient = patient; _this7.executionDateTime = executionDateTime; return _this7; } _createClass(PatientContext, [{ key: "rootContext", value: function rootContext() { return this; } }, { key: "getLibraryContext", value: function getLibraryContext(library) { if (this.library_context[library] == null) { this.library_context[library] = new PatientContext(this.get(library), this.patient, this.codeService, this.parameters, this.executionDateTime); } return this.library_context[library]; } }, { key: "getLocalIdContext", value: function getLocalIdContext(localId) { if (this.localId_context[localId] == null) { this.localId_context[localId] = new PatientContext(this.get(localId), this.patient, this.codeService, this.parameters, this.executionDateTime); } return this.localId_context[localId]; } }, { key: "findRecords", value: function findRecords(profile) { return this.patient && this.patient.findRecords(profile); } }]); return PatientContext; }(Context); var UnfilteredContext = /*#__PURE__*/function (_Context2) { _inherits(UnfilteredContext, _Context2); var _super2 = _createSuper(UnfilteredContext); function UnfilteredContext(library, results, codeService, parameters) { var _this8; var executionDateTime = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : dt.DateTime.fromJSDate(new Date()); _classCallCheck(this, UnfilteredContext); _this8 = _super2.call(this, library, codeService, parameters); _this8.library = library; _this8.results = results; _this8.executionDateTime = executionDateTime; return _this8; } _createClass(UnfilteredContext, [{ key: "rootContext", value: function rootContext() { return this; } }, { key: "findRecords", value: function findRecords(template) { throw new Exception('Retreives are not currently supported in Unfiltered Context'); } }, { key: "getLibraryContext", value: function getLibraryContext(library) { throw new Exception('Library expressions are not currently supported in Unfiltered Context'); } }, { key: "get", value: function get(identifier) { //First check to see if the identifier is a unfiltered context expression that has already been cached if (this.context_values[identifier]) { return this.context_values[identifier]; } //if not look to see if the library has a unfiltered expression of that identifier if (this.library[identifier] && this.library[identifier].context === 'Unfiltered') { return this.library.expressions[identifier]; } //lastley attempt to gather all patient level results that have that identifier // should this compact null values before return ? return Object.values(this.results.patientResults).map(function (pr) { return pr[identifier]; }); } }]); return UnfilteredContext; }(Context); module.exports = { Context: Context, PatientContext: PatientContext, UnfilteredContext: UnfilteredContext }; },{"../datatypes/datatypes":134,"../datatypes/exception":136,"../util/util":176}],170:[function(require,module,exports){ "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; } 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 = require('./results'), Results = _require.Results; var _require2 = require('./context'), UnfilteredContext = _require2.UnfilteredContext, PatientContext = _require2.PatientContext; var Executor = /*#__PURE__*/function () { function Executor(library, codeService, parameters) { _classCallCheck(this, Executor); this.library = library; this.codeService = codeService; this.parameters = parameters; } _createClass(Executor, [{ key: "withLibrary", value: function withLibrary(lib) { this.library = lib; return this; } }, { key: "withParameters", value: function withParameters(params) { this.parameters = params != null ? params : {}; return this; } }, { key: "withCodeService", value: function withCodeService(cs) { this.codeService = cs; return this; } }, { key: "exec_expression", value: function exec_expression(expression, patientSource) { var r = new Results(); var expr = this.library.expressions[expression]; if (expr != null) { while (patientSource.currentPatient()) { var patient_ctx = new PatientContext(this.library, patientSource.currentPatient(), this.codeService, this.parameters); r.recordPatientResults(patient_ctx, _defineProperty({}, expression, expr.execute(patient_ctx))); patientSource.nextPatient(); } } return r; } }, { key: "exec", value: function exec(patientSource, executionDateTime) { var r = this.exec_patient_context(patientSource, executionDateTime); var unfilteredContext = new UnfilteredContext(this.library, r, this.codeService, this.parameters); var resultMap = {}; for (var key in this.library.expressions) { var expr = this.library.expressions[key]; if (expr.context === 'Unfiltered') { resultMap[key] = expr.exec(unfilteredContext); } } r.recordUnfilteredResults(resultMap); return r; } }, { key: "exec_patient_context", value: function exec_patient_context(patientSource, executionDateTime) { var r = new Results(); while (patientSource.currentPatient()) { var patient_ctx = new PatientContext(this.library, patientSource.currentPatient(), this.codeService, this.parameters, executionDateTime); var resultMap = {}; for (var key in this.library.expressions) { var expr = this.library.expressions[key]; if (expr.context === 'Patient') { resultMap[key] = expr.execute(patient_ctx); } } r.recordPatientResults(patient_ctx, resultMap); patientSource.nextPatient(); } return r; } }]); return Executor; }(); module.exports = { Executor: Executor }; },{"./context":169,"./results":172}],171:[function(require,module,exports){ "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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 = o[Symbol.iterator](); }, 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); return Constructor; } var _require = require('../elm/library'), Library = _require.Library; var Repository = /*#__PURE__*/function () { function Repository(data) { _classCallCheck(this, Repository); this.data = data; this.libraries = Array.from(Object.values(data)); } _createClass(Repository, [{ key: "resolve", value: function resolve(library, version) { var _iterator = _createForOfIteratorHelper(this.libraries), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var lib = _step.value; if (lib.library && lib.library.identifier) { var id = lib.library.identifier; if (id.id === library && id.version === version) { return new Library(lib, this); } } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } }]); return Repository; }(); module.exports = { Repository: Repository }; },{"../elm/library":155}],172:[function(require,module,exports){ "use strict"; 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" && Symbol.iterator in Object(iter)) 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 _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 Results = /*#__PURE__*/function () { function Results() { _classCallCheck(this, Results); this.patientResults = {}; this.unfilteredResults = {}; this.localIdPatientResultsMap = {}; this.patientEvaluatedRecords = {}; } // Expose an evaluatedRecords array for backwards compatibility _createClass(Results, [{ key: "recordPatientResults", value: function recordPatientResults(patient_ctx, resultMap) { var _this = this; var p = patient_ctx.patient; // NOTE: From now on prefer getId() over id() because some data models may have an id property // that is not a string (e.g., FHIR) -- so reserve getId() for the API (and expect a string // representation) but leave id() for data-model specific formats. var patientId = typeof p.getId === 'function' ? p.getId() : p.id(); // Record the results this.patientResults[patientId] = resultMap; // Record the local IDs this.localIdPatientResultsMap[patientId] = patient_ctx.getAllLocalIds(); // Record the evaluatedRecords, merging with an aggregated array across all libraries this.patientEvaluatedRecords[patientId] = _toConsumableArray(patient_ctx.evaluatedRecords); Object.values(patient_ctx.library_context).forEach(function (ctx) { var _this$patientEvaluate; (_this$patientEvaluate = _this.patientEvaluatedRecords[patientId]).push.apply(_this$patientEvaluate, _toConsumableArray(ctx.evaluatedRecords)); }); } }, { key: "recordUnfilteredResults", value: function recordUnfilteredResults(resultMap) { this.unfilteredResults = resultMap; } }, { key: "evaluatedRecords", get: function get() { var _ref; return (_ref = []).concat.apply(_ref, _toConsumableArray(Object.values(this.patientEvaluatedRecords))); } }]); return Results; }(); module.exports = { Results: Results }; },{}],173:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; 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; } var _require = require('../datatypes/uncertainty'), Uncertainty = _require.Uncertainty; function areNumbers(a, b) { return typeof a === 'number' && typeof b === 'number'; } function areStrings(a, b) { return typeof a === 'string' && typeof b === 'string'; } function areDateTimesOrQuantities(a, b) { return a && a.isDateTime && b && b.isDateTime || a && a.isDate && b && b.isDate || a && a.isQuantity && b && b.isQuantity; } function isUncertainty(x) { return x instanceof Uncertainty; } function lessThan(a, b, precision) { if (areNumbers(a, b) || areStrings(a, b)) { return a < b; } else if (areDateTimesOrQuantities(a, b)) { return a.before(b, precision); } else if (isUncertainty(a)) { return a.lessThan(b); } else if (isUncertainty(b)) { return Uncertainty.from(a).lessThan(b); } else { return null; } } function lessThanOrEquals(a, b, precision) { if (areNumbers(a, b) || areStrings(a, b)) { return a <= b; } else if (areDateTimesOrQuantities(a, b)) { return a.sameOrBefore(b, precision); } else if (isUncertainty(a)) { return a.lessThanOrEquals(b); } else if (isUncertainty(b)) { return Uncertainty.from(a).lessThanOrEquals(b); } else { return null; } } function greaterThan(a, b, precision) { if (areNumbers(a, b) || areStrings(a, b)) { return a > b; } else if (areDateTimesOrQuantities(a, b)) { return a.after(b, precision); } else if (isUncertainty(a)) { return a.greaterThan(b); } else if (isUncertainty(b)) { return Uncertainty.from(a).greaterThan(b); } else { return null; } } function greaterThanOrEquals(a, b, precision) { if (areNumbers(a, b) || areStrings(a, b)) { return a >= b; } else if (areDateTimesOrQuantities(a, b)) { return a.sameOrAfter(b, precision); } else if (isUncertainty(a)) { return a.greaterThanOrEquals(b); } else if (isUncertainty(b)) { return Uncertainty.from(a).greaterThanOrEquals(b); } else { return null; } } function equivalent(a, b) { if (a == null && b == null) { return true; } if (a == null || b == null) { return false; } if (isCode(a)) { return codesAreEquivalent(a, b); } // Quantity equivalence is the same as Quantity equality if (a.isQuantity) { return a.equals(b); } // Use overloaded 'equivalent' function if it is available if (typeof a.equivalent === 'function') { return a.equivalent(b); } var _getClassOfObjects = getClassOfObjects(a, b), _getClassOfObjects2 = _slicedToArray(_getClassOfObjects, 2), aClass = _getClassOfObjects2[0], bClass = _getClassOfObjects2[1]; switch (aClass) { case '[object Array]': return compareEveryItemInArrays(a, b, equivalent); case '[object Object]': return compareObjects(a, b, equivalent); case '[object String]': // Make sure b is also a string if (bClass === '[object String]') { // String equivalence is case- and locale insensitive a = a.replace(/\s/g, ' '); b = b.replace(/\s/g, ' '); return a.localeCompare(b, 'en', { sensitivity: 'base' }) === 0; } break; } return equals(a, b); } function isCode(object) { return object.hasMatch && typeof object.hasMatch === 'function'; } function codesAreEquivalent(code1, code2) { return code1.hasMatch(code2); } function getClassOfObjects(object1, object2) { return [object1, object2].map(function (obj) { return {}.toString.call(obj); }); } function compareEveryItemInArrays(array1, array2, comparisonFunction) { return array1.length === array2.length && array1.every(function (item, i) { return comparisonFunction(item, array2[i]); }); } function compareObjects(a, b, comparisonFunction) { if (!classesEqual(a, b)) { return false; } return deepCompareKeysAndValues(a, b, comparisonFunction); } function classesEqual(object1, object2) { return object2 instanceof object1.constructor && object1 instanceof object2.constructor; } function deepCompareKeysAndValues(a, b, comparisonFunction) { var finalComparisonResult; var aKeys = getKeysFromObject(a).sort(); var bKeys = getKeysFromObject(b).sort(); // Array.every() will only return true or false, so set a flag for if we should return null var shouldReturnNull = false; // Check if both arrays of keys are the same length and key names match if (aKeys.length === bKeys.length && aKeys.every(function (value, index) { return value === bKeys[index]; })) { finalComparisonResult = aKeys.every(function (key) { // if both are null we should return true to satisfy ignoring empty values in tuples if (a[key] == null && b[key] == null) { return true; } var comparisonResult = comparisonFunction(a[key], b[key]); if (comparisonResult === null) { shouldReturnNull = true; } return comparisonResult; }); } else { finalComparisonResult = false; } if (shouldReturnNull) { return null; } return finalComparisonResult; } function getKeysFromObject(object) { return Object.keys(object).filter(function (k) { return !isFunction(object[k]); }); } function isFunction(input) { return input instanceof Function || {}.toString.call(input) === '[object Function]'; } function equals(a, b) { // Handle null cases first: spec says if either is null, return null if (a == null || b == null) { return null; } // If one is a Quantity, use the Quantity equals function if (a && a.isQuantity) { return a.equals(b); } // If one is a Ratio, use the ratio equals function if (a && a.isRatio) { return a.equals(b); } // If one is an Uncertainty, convert the other to an Uncertainty if (a instanceof Uncertainty) { b = Uncertainty.from(b); } else if (b instanceof Uncertainty) { a = Uncertainty.from(a); } // Use overloaded 'equals' function if it is available if (typeof a.equals === 'function') { return a.equals(b); } // Return true of the objects are primitives and are strictly equal if (_typeof(a) === _typeof(b) && typeof a === 'string' || typeof a === 'number' || typeof a === 'boolean') { return a === b; } // Return false if they are instances of different classes var _getClassOfObjects3 = getClassOfObjects(a, b), _getClassOfObjects4 = _slicedToArray(_getClassOfObjects3, 2), aClass = _getClassOfObjects4[0], bClass = _getClassOfObjects4[1]; if (aClass !== bClass) { return false; } switch (aClass) { case '[object Date]': // Compare the ms since epoch return a.getTime() === b.getTime(); case '[object RegExp]': // Compare the components of the regular expression return ['source', 'global', 'ignoreCase', 'multiline'].every(function (p) { return a[p] === b[p]; }); case '[object Array]': if (a.indexOf(null) >= 0 || a.indexOf(undefined) >= 0 || b.indexOf(null) >= 0 || b.indexOf(undefined) >= 0) { return null; } return compareEveryItemInArrays(a, b, equals); case '[object Object]': return compareObjects(a, b, equals); case '[object Function]': return a.toString() === b.toString(); } // If we made it this far, we can't handle it return false; } module.exports = { lessThan: lessThan, lessThanOrEquals: lessThanOrEquals, greaterThan: greaterThan, greaterThanOrEquals: greaterThanOrEquals, equivalent: equivalent, equals: equals }; },{"../datatypes/uncertainty":141}],174:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } 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 } }); 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); } 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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var _require = require('../datatypes/exception'), Exception = _require.Exception; var _require2 = require('../datatypes/datetime'), MIN_DATETIME_VALUE = _require2.MIN_DATETIME_VALUE, MAX_DATETIME_VALUE = _require2.MAX_DATETIME_VALUE, MIN_DATE_VALUE = _require2.MIN_DATE_VALUE, MAX_DATE_VALUE = _require2.MAX_DATE_VALUE, MIN_TIME_VALUE = _require2.MIN_TIME_VALUE, MAX_TIME_VALUE = _require2.MAX_TIME_VALUE; var _require3 = require('../datatypes/uncertainty'), Uncertainty = _require3.Uncertainty; var MAX_INT_VALUE = Math.pow(2, 31) - 1; var MIN_INT_VALUE = Math.pow(-2, 31); var MAX_FLOAT_VALUE = 99999999999999999999.99999999; var MIN_FLOAT_VALUE = -99999999999999999999.99999999; var MIN_FLOAT_PRECISION_VALUE = Math.pow(10, -8); function overflowsOrUnderflows(value) { if (value == null) { return false; } if (value.isQuantity) { if (!isValidDecimal(value.value)) { return true; } } else if (value.isTime && value.isTime()) { if (value.after(MAX_TIME_VALUE)) { return true; } if (value.before(MIN_TIME_VALUE)) { return true; } } else if (value.isDateTime) { if (value.after(MAX_DATETIME_VALUE)) { return true; } if (value.before(MIN_DATETIME_VALUE)) { return true; } } else if (value.isDate) { if (value.after(MAX_DATE_VALUE)) { return true; } if (value.before(MIN_DATE_VALUE)) { return true; } } else if (Number.isInteger(value)) { if (!isValidInteger(value)) { return true; } } else if (value.isUncertainty) { return overflowsOrUnderflows(value.low) || overflowsOrUnderflows(value.high); } else { if (!isValidDecimal(value)) { return true; } } return false; } function isValidInteger(integer) { if (isNaN(integer)) { return false; } if (integer > MAX_INT_VALUE) { return false; } if (integer < MIN_INT_VALUE) { return false; } return true; } function isValidDecimal(decimal) { if (isNaN(decimal)) { return false; } if (decimal > MAX_FLOAT_VALUE) { return false; } if (decimal < MIN_FLOAT_VALUE) { return false; } return true; } function limitDecimalPrecision(decimal) { var decimalString = decimal.toString(); // For decimals so large that they are represented in scientific notation, javascript has already limited // the decimal to its own constraints, so we can't determine the original precision. Leave as-is unless // this becomes problematic, in which case we would need our own parseFloat. if (decimalString.indexOf('e') !== -1) { return decimal; } var splitDecimalString = decimalString.split('.'); var decimalPoints = splitDecimalString[1]; if (decimalPoints != null && decimalPoints.length > 8) { decimalString = splitDecimalString[0] + '.' + splitDecimalString[1].substring(0, 8); } return parseFloat(decimalString); } var OverFlowException = /*#__PURE__*/function (_Exception) { _inherits(OverFlowException, _Exception); var _super = _createSuper(OverFlowException); function OverFlowException() { _classCallCheck(this, OverFlowException); return _super.apply(this, arguments); } return OverFlowException; }(Exception); function successor(val) { if (typeof val === 'number') { if (parseInt(val) === val) { if (val >= MAX_INT_VALUE) { throw new OverFlowException(); } else { return val + 1; } } else { if (val >= MAX_FLOAT_VALUE) { throw new OverFlowException(); } else { return val + MIN_FLOAT_PRECISION_VALUE; } } } else if (val && val.isTime && val.isTime()) { if (val.sameAs(MAX_TIME_VALUE)) { throw new OverFlowException(); } else { return val.successor(); } } else if (val && val.isDateTime) { if (val.sameAs(MAX_DATETIME_VALUE)) { throw new OverFlowException(); } else { return val.successor(); } } else if (val && val.isDate) { if (val.sameAs(MAX_DATE_VALUE)) { throw new OverFlowException(); } else { return val.successor(); } } else if (val && val.isUncertainty) { // For uncertainties, if the high is the max val, don't increment it var high = function () { try { return successor(val.high); } catch (e) { return val.high; } }(); return new Uncertainty(successor(val.low), high); } else if (val && val.isQuantity) { var succ = val.clone(); succ.value = successor(val.value); return succ; } else if (val == null) { return null; } } function predecessor(val) { if (typeof val === 'number') { if (parseInt(val) === val) { if (val <= MIN_INT_VALUE) { throw new OverFlowException(); } else { return val - 1; } } else { if (val <= MIN_FLOAT_VALUE) { throw new OverFlowException(); } else { return val - MIN_FLOAT_PRECISION_VALUE; } } } else if (val && val.isTime && val.isTime()) { if (val.sameAs(MIN_TIME_VALUE)) { throw new OverFlowException(); } else { return val.predecessor(); } } else if (val && val.isDateTime) { if (val.sameAs(MIN_DATETIME_VALUE)) { throw new OverFlowException(); } else { return val.predecessor(); } } else if (val && val.isDate) { if (val.sameAs(MIN_DATE_VALUE)) { throw new OverFlowException(); } else { return val.predecessor(); } } else if (val && val.isUncertainty) { // For uncertainties, if the low is the min val, don't decrement it var low = function () { try { return predecessor(val.low); } catch (e) { return val.low; } }(); return new Uncertainty(low, predecessor(val.high)); } else if (val && val.isQuantity) { var pred = val.clone(); pred.value = predecessor(val.value); return pred; } else if (val == null) { return null; } } function maxValueForInstance(val) { if (typeof val === 'number') { if (parseInt(val) === val) { return MAX_INT_VALUE; } else { return MAX_FLOAT_VALUE; } } else if (val && val.isTime && val.isTime()) { return MAX_TIME_VALUE.copy(); } else if (val && val.isDateTime) { return MAX_DATETIME_VALUE.copy(); } else if (val && val.isDate) { return MAX_DATE_VALUE.copy(); } else if (val && val.isQuantity) { var val2 = val.clone(); val2.value = maxValueForInstance(val2.value); return val2; } else { return null; } } function maxValueForType(type, quantityInstance) { switch (type) { case '{urn:hl7-org:elm-types:r1}Integer': return MAX_INT_VALUE; case '{urn:hl7-org:elm-types:r1}Decimal': return MAX_FLOAT_VALUE; case '{urn:hl7-org:elm-types:r1}DateTime': return MAX_DATETIME_VALUE.copy(); case '{urn:hl7-org:elm-types:r1}Date': return MAX_DATE_VALUE.copy(); case '{urn:hl7-org:elm-types:r1}Time': return MAX_TIME_VALUE.copy(); case '{urn:hl7-org:elm-types:r1}Quantity': { if (quantityInstance == null) { // can't infer a quantity unit type from nothing] return null; } var maxQty = quantityInstance.clone(); maxQty.value = maxValueForInstance(maxQty.value); return maxQty; } } return null; } function minValueForInstance(val) { if (typeof val === 'number') { if (parseInt(val) === val) { return MIN_INT_VALUE; } else { return MIN_FLOAT_VALUE; } } else if (val && val.isTime && val.isTime()) { return MIN_TIME_VALUE.copy(); } else if (val && val.isDateTime) { return MIN_DATETIME_VALUE.copy(); } else if (val && val.isDate) { return MIN_DATE_VALUE.copy(); } else if (val && val.isQuantity) { var val2 = val.clone(); val2.value = minValueForInstance(val2.value); return val2; } else { return null; } } function minValueForType(type, quantityInstance) { switch (type) { case '{urn:hl7-org:elm-types:r1}Integer': return MIN_INT_VALUE; case '{urn:hl7-org:elm-types:r1}Decimal': return MIN_FLOAT_VALUE; case '{urn:hl7-org:elm-types:r1}DateTime': return MIN_DATETIME_VALUE.copy(); case '{urn:hl7-org:elm-types:r1}Date': return MIN_DATE_VALUE.copy(); case '{urn:hl7-org:elm-types:r1}Time': return MIN_TIME_VALUE.copy(); case '{urn:hl7-org:elm-types:r1}Quantity': { if (quantityInstance == null) { // can't infer a quantity unit type from nothing] return null; } var minQty = quantityInstance.clone(); minQty.value = minValueForInstance(minQty.value); return minQty; } } return null; } function decimalAdjust(type, value, exp) { //If the exp is undefined or zero... if (typeof exp === 'undefined' || +exp === 0) { return Math[type](value); } value = +value; exp = +exp; //If the value is not a number or the exp is not an integer... if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { return NaN; } //Shift value = value.toString().split('e'); var v = value[1] ? +value[1] - exp : -exp; value = Math[type](+(value[0] + 'e' + v)); //Shift back value = value.toString().split('e'); v = value[1] ? +value[1] + exp : exp; return +(value[0] + 'e' + v); } function decimalOrNull(value) { return isValidDecimal(value) ? value : null; } module.exports = { MAX_INT_VALUE: MAX_INT_VALUE, MIN_INT_VALUE: MIN_INT_VALUE, MAX_FLOAT_VALUE: MAX_FLOAT_VALUE, MIN_FLOAT_VALUE: MIN_FLOAT_VALUE, MIN_FLOAT_PRECISION_VALUE: MIN_FLOAT_PRECISION_VALUE, MIN_DATETIME_VALUE: MIN_DATETIME_VALUE, MAX_DATETIME_VALUE: MAX_DATETIME_VALUE, MIN_DATE_VALUE: MIN_DATE_VALUE, MAX_DATE_VALUE: MAX_DATE_VALUE, MIN_TIME_VALUE: MIN_TIME_VALUE, MAX_TIME_VALUE: MAX_TIME_VALUE, overflowsOrUnderflows: overflowsOrUnderflows, isValidInteger: isValidInteger, isValidDecimal: isValidDecimal, limitDecimalPrecision: limitDecimalPrecision, OverFlowException: OverFlowException, successor: successor, predecessor: predecessor, maxValueForInstance: maxValueForInstance, minValueForInstance: minValueForInstance, maxValueForType: maxValueForType, minValueForType: minValueForType, decimalAdjust: decimalAdjust, decimalOrNull: decimalOrNull }; },{"../datatypes/datetime":135,"../datatypes/exception":136,"../datatypes/uncertainty":141}],175:[function(require,module,exports){ "use strict"; 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; 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; } var ucum = require('@lhncbc/ucum-lhc'); var _require = require('./math'), decimalAdjust = _require.decimalAdjust; var utils = ucum.UcumLhcUtils.getInstance(); // Cache Map for unit validity results so we dont have to go to ucum-lhc for every check. var unitValidityCache = new Map(); function checkUnit(unit) { var allowEmptyUnits = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var allowCQLDateUnits = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; if (allowEmptyUnits) { unit = fixEmptyUnit(unit); } if (allowCQLDateUnits) { unit = fixCQLDateUnit(unit); } if (!unitValidityCache.has(unit)) { var result = utils.validateUnitString(unit, true); if (result.status === 'valid') { unitValidityCache.set(unit, { valid: true }); } else { var msg = "Invalid UCUM unit: '".concat(unit, "'."); if (result.ucumCode != null) { msg += " Did you mean '".concat(result.ucumCode, "'?"); } unitValidityCache.set(unit, { valid: false, message: msg }); } } return unitValidityCache.get(unit); } function convertUnit(fromVal, fromUnit, toUnit) { var adjustPrecision = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; var _map = [fromUnit, toUnit].map(fixUnit); var _map2 = _slicedToArray(_map, 2); fromUnit = _map2[0]; toUnit = _map2[1]; var result = utils.convertUnitTo(fixUnit(fromUnit), fromVal, fixUnit(toUnit)); if (result.status !== 'succeeded') { return; } return adjustPrecision ? decimalAdjust('round', result.toVal, -8) : result.toVal; } function normalizeUnitsWhenPossible(val1, unit1, val2, unit2) { // If both units are CQL date units, return CQL date units var useCQLDateUnits = CQL_TO_UCUM_DATE_UNITS[unit1] != null && CQL_TO_UCUM_DATE_UNITS[unit2] != null; var resultConverter = function resultConverter(unit) { return useCQLDateUnits ? convertToCQLDateUnit(unit) : unit; }; var _map3 = [unit1, unit2].map(fixUnit); var _map4 = _slicedToArray(_map3, 2); unit1 = _map4[0]; unit2 = _map4[1]; if (unit1 === unit2) { return [val1, unit1, val2, unit2]; } var baseUnit1 = getBaseUnitAndPower(unit1)[0]; var baseUnit2 = getBaseUnitAndPower(unit2)[0]; var _convertToBaseUnit = convertToBaseUnit(val2, unit2, baseUnit1), _convertToBaseUnit2 = _slicedToArray(_convertToBaseUnit, 2), newVal2 = _convertToBaseUnit2[0], newUnit2 = _convertToBaseUnit2[1]; if (newVal2 == null) { // it was not convertible, so just return the quantities as-is return [val1, resultConverter(unit1), val2, resultConverter(unit2)]; } // If the new val2 > old val2, return since we prefer conversion to smaller units if (newVal2 >= val2) { return [val1, resultConverter(unit1), newVal2, resultConverter(newUnit2)]; } // else it was a conversion to a larger unit, so go the other way around var _convertToBaseUnit3 = convertToBaseUnit(val1, unit1, baseUnit2), _convertToBaseUnit4 = _slicedToArray(_convertToBaseUnit3, 2), newVal1 = _convertToBaseUnit4[0], newUnit1 = _convertToBaseUnit4[1]; if (newVal1 == null) { // this should not happen since we established they are convertible, but just in case... return [val1, resultConverter(unit1), newVal2, resultConverter(newUnit2)]; } return [newVal1, resultConverter(newUnit1), val2, resultConverter(unit2)]; } function convertToCQLDateUnit(unit) { if (CQL_TO_UCUM_DATE_UNITS[unit]) { // it's already a CQL unit, so return it as-is, removing trailing 's' if necessary (e.g., years -> year) return unit.replace(/s$/, ''); } return UCUM_TO_CQL_DATE_UNITS[unit]; } function compareUnits(unit1, unit2) { try { var c = convertUnit(1, unit1, unit2); if (c > 1) { // unit1 is bigger (less precise) return 1; } else if (c < 1) { // unit1 is smaller return -1; } //units are the same return 0; } catch (e) { return null; } } function getProductOfUnits(unit1, unit2) { var _map5 = [unit1, unit2].map(fixEmptyUnit); var _map6 = _slicedToArray(_map5, 2); unit1 = _map6[0]; unit2 = _map6[1]; if (!checkUnit(unit1).valid || !checkUnit(unit2).valid) { return null; } // If either unit contains a divisor,combine the numerators and denominators, then divide if (unit1.indexOf('/') >= 0 || unit2.indexOf('/') >= 0) { // NOTE: We're not trying to get perfection on unit simplification, but doing what is reasonable var match1 = unit1.match(/([^/]*)(\/(.*))?/); var match2 = unit2.match(/([^/]*)(\/(.*))?/); // In the previous regexes, numerator is match[1], denominator is match[3] var newNum = getProductOfUnits(match1[1], match2[1]); var newDen = getProductOfUnits(match1[3], match2[3]); return getQuotientOfUnits(newNum, newDen); } // Get all the individual units being combined, accounting for multipliers (e.g., 'm.L'), // and then group like base units to combine powers (and remove '1's since they are no-ops) // e.g., 'm.L' * 'm' ==> { m: 2, L: 1}; 'm.L' * '1' ==> { m: 1, L: 1 }; '1' : '1' ==> { } var factorPowerMap = new Map(); var factors = [].concat(_toConsumableArray(unit1.split('.')), _toConsumableArray(unit2.split('.'))); factors.forEach(function (factor) { var _getBaseUnitAndPower = getBaseUnitAndPower(factor), _getBaseUnitAndPower2 = _slicedToArray(_getBaseUnitAndPower, 2), baseUnit = _getBaseUnitAndPower2[0], power = _getBaseUnitAndPower2[1]; if (baseUnit === '1' || power === 0) { // skip factors that are 1 since 1 * N is N. return; } var accumulatedPower = (factorPowerMap.get(baseUnit) || 0) + power; factorPowerMap.set(baseUnit, accumulatedPower); }); // Loop through the factor map, rebuilding each factor w/ combined power and join them all // back via the multiplier '.', treating a final '' (no non-1 units) as '1' // e.g., { m: 2, L: 1 } ==> 'm2.L' return fixUnit(Array.from(factorPowerMap.entries()).map(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), base = _ref2[0], power = _ref2[1]; return "".concat(base).concat(power > 1 ? power : ''); }).join('.')); } function getQuotientOfUnits(unit1, unit2) { var _map7 = [unit1, unit2].map(fixEmptyUnit); var _map8 = _slicedToArray(_map7, 2); unit1 = _map8[0]; unit2 = _map8[1]; if (!checkUnit(unit1).valid || !checkUnit(unit2).valid) { return null; } // Try to simplify division when neither unit contains a divisor itself if (unit1.indexOf('/') === -1 && unit2.indexOf('/') === -1) { // Get all the individual units in numerator and denominator accounting for multipliers // (e.g., 'm.L'), and then group like base units to combine powers, inversing denominator // powers since they are being divided. // e.g., 'm3.L' / 'm' ==> { m: 2, L: -1}; 'm.L' / '1' ==> { m: 1, L: 1 }; '1' / '1' ==> { 1: 0 } var factorPowerMap = new Map(); unit1.split('.').forEach(function (factor) { var _getBaseUnitAndPower3 = getBaseUnitAndPower(factor), _getBaseUnitAndPower4 = _slicedToArray(_getBaseUnitAndPower3, 2), baseUnit = _getBaseUnitAndPower4[0], power = _getBaseUnitAndPower4[1]; var accumulatedPower = (factorPowerMap.get(baseUnit) || 0) + power; factorPowerMap.set(baseUnit, accumulatedPower); }); unit2.split('.').forEach(function (factor) { var _getBaseUnitAndPower5 = getBaseUnitAndPower(factor), _getBaseUnitAndPower6 = _slicedToArray(_getBaseUnitAndPower5, 2), baseUnit = _getBaseUnitAndPower6[0], power = _getBaseUnitAndPower6[1]; var accumulatedPower = (factorPowerMap.get(baseUnit) || 0) - power; factorPowerMap.set(baseUnit, accumulatedPower); }); // Construct the numerator from factors with positive power, and denominator from factors // with negative power, filtering out base `1` and power 0 (which is also 1). // e.g. numerator: { m: 2, L: -2 } ==> 'm2'; { 1: 1, L: -1 } => '' // e.g. denominator: { m: 2, L: -2 } ==> 'L2'; { 1: 1, L: -1 } => 'L' var numerator = Array.from(factorPowerMap.entries()).filter(function (_ref3) { var _ref4 = _slicedToArray(_ref3, 2), base = _ref4[0], power = _ref4[1]; return base !== '1' && power > 0; }).map(function (_ref5) { var _ref6 = _slicedToArray(_ref5, 2), base = _ref6[0], power = _ref6[1]; return "".concat(base).concat(power > 1 ? power : ''); }).join('.'); var denominator = Array.from(factorPowerMap.entries()).filter(function (_ref7) { var _ref8 = _slicedToArray(_ref7, 2), base = _ref8[0], power = _ref8[1]; return base !== '1' && power < 0; }).map(function (_ref9) { var _ref10 = _slicedToArray(_ref9, 2), base = _ref10[0], power = _ref10[1]; return "".concat(base).concat(power < -1 ? power * -1 : ''); }).join('.'); // wrap the denominator in parentheses if necessary denominator = /[.]/.test(denominator) ? "(".concat(denominator, ")") : denominator; return fixUnit("".concat(numerator).concat(denominator !== '' ? '/' + denominator : '')); } // One of the units had a divisor, so don't try to be too smart; just construct it from the parts if (unit1 === unit2) { // e.g. 'm/g' / 'm/g' ==> '1' return '1'; } else if (unit2 === '1') { // e.g., 'm/g' / '1' ==> 'm/g/' return unit1; } else { // denominator is unit2, wrapped in parentheses if necessary var _denominator = /[./]/.test(unit2) ? "(".concat(unit2, ")") : unit2; if (unit1 === '1') { // e.g., '1' / 'm' ==> '/m'; '1' / 'm.g' ==> '/(m.g)' return "/".concat(_denominator); } // e.g., 'L' / 'm' ==> 'L/m'; 'L' / 'm.g' ==> 'L/(m.g)' return "".concat(unit1, "/").concat(_denominator); } } // UNEXPORTED FUNCTIONS function convertToBaseUnit(fromVal, fromUnit, toBaseUnit) { var fromPower = getBaseUnitAndPower(fromUnit)[1]; var toUnit = fromPower === 1 ? toBaseUnit : "".concat(toBaseUnit).concat(fromPower); var newVal = convertUnit(fromVal, fromUnit, toUnit); return newVal != null ? [newVal, toUnit] : []; } function getBaseUnitAndPower(unit) { // don't try to extract power from complex units (containing multipliers or divisors) if (/[./]/.test(unit)) { return [unit, 1]; } unit = fixUnit(unit); var _unit$match$slice = unit.match(/^(.*[^-\d])?([-]?\d*)$/).slice(1), _unit$match$slice2 = _slicedToArray(_unit$match$slice, 2), term = _unit$match$slice2[0], power = _unit$match$slice2[1]; if (term == null || term === '') { term = power; power = '1'; } else if (power == null || power === '') { power = '1'; } return [term, parseInt(power)]; } // The CQL specification says that dates are based on the Gregorian calendar, so CQL-based year and month // identifiers will be matched to the UCUM gregorian units. See http://unitsofmeasure.org/ucum.html#para-31 var CQL_TO_UCUM_DATE_UNITS = { years: 'a_g', year: 'a_g', months: 'mo_g', month: 'mo_g', weeks: 'wk', week: 'wk', days: 'd', day: 'd', hours: 'h', hour: 'h', minutes: 'min', minute: 'min', seconds: 's', second: 's', milliseconds: 'ms', millisecond: 'ms' }; var UCUM_TO_CQL_DATE_UNITS = { a: 'year', a_j: 'year', a_g: 'year', mo: 'month', mo_j: 'month', mo_g: 'month', wk: 'week', d: 'day', h: 'hour', min: 'minute', s: 'second', ms: 'millisecond' }; function fixEmptyUnit(unit) { if (unit == null || unit.trim && unit.trim() === '') { return '1'; } return unit; } function fixCQLDateUnit(unit) { return CQL_TO_UCUM_DATE_UNITS[unit] || unit; } function fixUnit(unit) { return fixCQLDateUnit(fixEmptyUnit(unit)); } module.exports = { checkUnit: checkUnit, convertUnit: convertUnit, normalizeUnitsWhenPossible: normalizeUnitsWhenPossible, convertToCQLDateUnit: convertToCQLDateUnit, compareUnits: compareUnits, getProductOfUnits: getProductOfUnits, getQuotientOfUnits: getQuotientOfUnits }; },{"./math":174,"@lhncbc/ucum-lhc":99}],176:[function(require,module,exports){ "use strict"; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; 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 removeNulls(things) { return things.filter(function (x) { return x != null; }); } function numerical_sort(things, direction) { return things.sort(function (a, b) { if (direction == null || direction === 'asc') { return a - b; } else { return b - a; } }); } function isNull(value) { return value === null; } var typeIsArray = Array.isArray || function (value) { return {}.toString.call(value) === '[object Array]'; }; function allTrue(things) { if (typeIsArray(things)) { return things.every(function (x) { return x; }); } else { return things; } } function anyTrue(things) { if (typeIsArray(things)) { return things.some(function (x) { return x; }); } else { return things; } } //The export below is to make it easier if js Date is overwritten with CQL Date var jsDate = Date; function normalizeMillisecondsFieldInString(string, msString) { // TODO: verify we are only removing numeral digits var timezoneField; msString = normalizeMillisecondsField(msString); var _string$split = string.split('.'), _string$split2 = _slicedToArray(_string$split, 2), beforeMs = _string$split2[0], msAndAfter = _string$split2[1]; var timezoneSeparator = getTimezoneSeparatorFromString(msAndAfter); if (timezoneSeparator) { timezoneField = msAndAfter != null ? msAndAfter.split(timezoneSeparator)[1] : undefined; } if (timezoneField == null) { timezoneField = ''; } return string = beforeMs + '.' + msString + timezoneSeparator + timezoneField; } function normalizeMillisecondsField(msString) { // fix up milliseconds by padding zeros and/or truncating (5 --> 500, 50 --> 500, 54321 --> 543, etc.) return msString = (msString + '00').substring(0, 3); } function getTimezoneSeparatorFromString(string) { if (string != null) { var matches = string.match(/-/); if (matches && matches.length === 1) { return '-'; } matches = string.match(/\+/); if (matches && matches.length === 1) { return '+'; } } return ''; } module.exports = { removeNulls: removeNulls, numerical_sort: numerical_sort, isNull: isNull, typeIsArray: typeIsArray, allTrue: allTrue, anyTrue: anyTrue, jsDate: jsDate, normalizeMillisecondsFieldInString: normalizeMillisecondsFieldInString, normalizeMillisecondsField: normalizeMillisecondsField, getTimezoneSeparatorFromString: getTimezoneSeparatorFromString }; },{}],177:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var objectCreate = Object.create || objectCreatePolyfill var objectKeys = Object.keys || objectKeysPolyfill var bind = Function.prototype.bind || functionBindPolyfill function EventEmitter() { if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) { this._events = objectCreate(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; 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; var hasDefineProperty; try { var o = {}; if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 }); hasDefineProperty = o.x === 0; } catch (err) { hasDefineProperty = false } if (hasDefineProperty) { Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function() { return defaultMaxListeners; }, set: function(arg) { // check whether the input is a positive number (whose value is zero or // greater and not a NaN). if (typeof arg !== 'number' || arg < 0 || arg !== arg) throw new TypeError('"defaultMaxListeners" must be a positive number'); defaultMaxListeners = arg; } }); } else { EventEmitter.defaultMaxListeners = defaultMaxListeners; } // 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 || isNaN(n)) throw new TypeError('"n" argument must be a positive number'); 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); }; // These standalone emit* functions are used to optimize calling of event // handlers for fast cases because emit() itself often has a variable number of // arguments and can be deoptimized because of that. These functions always have // the same number of arguments and thus do not get deoptimized, so the code // inside them can execute faster. function emitNone(handler, isFn, self) { if (isFn) handler.call(self); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self); } } function emitOne(handler, isFn, self, arg1) { if (isFn) handler.call(self, arg1); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1); } } function emitTwo(handler, isFn, self, arg1, arg2) { if (isFn) handler.call(self, arg1, arg2); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2); } } function emitThree(handler, isFn, self, arg1, arg2, arg3) { if (isFn) handler.call(self, arg1, arg2, arg3); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2, arg3); } } function emitMany(handler, isFn, self, args) { if (isFn) handler.apply(self, args); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].apply(self, args); } } EventEmitter.prototype.emit = function emit(type) { var er, handler, len, args, i, events; var doError = (type === 'error'); events = this._events; if (events) doError = (doError && events.error == null); else if (!doError) return false; // If there is no 'error' event listener then throw. if (doError) { if (arguments.length > 1) er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Unhandled "error" event. (' + er + ')'); err.context = er; throw err; } return false; } handler = events[type]; if (!handler) return false; var isFn = typeof handler === 'function'; len = arguments.length; switch (len) { // fast cases case 1: emitNone(handler, isFn, this); break; case 2: emitOne(handler, isFn, this, arguments[1]); break; case 3: emitTwo(handler, isFn, this, arguments[1], arguments[2]); break; case 4: emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); break; // slower default: args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; emitMany(handler, isFn, this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = target._events; if (!events) { events = target._events = objectCreate(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) { 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) { // 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]; } else { // If we've already got an array, just append. if (prepend) { existing.unshift(listener); } else { existing.push(listener); } } // Check for listener leak if (!existing.warned) { m = $getMaxListeners(target); if (m && m > 0 && existing.length > m) { existing.warned = true; 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; if (typeof console === 'object' && console.warn) { console.warn('%s: %s', w.name, w.message); } } } } 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; switch (arguments.length) { case 0: return this.listener.call(this.target); case 1: return this.listener.call(this.target, arguments[0]); case 2: return this.listener.call(this.target, arguments[0], arguments[1]); case 3: return this.listener.call(this.target, arguments[0], arguments[1], arguments[2]); default: var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) args[i] = arguments[i]; this.listener.apply(this.target, args); } } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; var wrapped = bind.call(onceWrapper, state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); 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; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = this._events; if (!events) return this; list = events[type]; if (!list) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = objectCreate(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) this.emit('removeListener', type, originalListener || listener); } return this; }; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; events = this._events; if (!events) return this; // not listening for removeListener, no need to emit if (!events.removeListener) { if (arguments.length === 0) { this._events = objectCreate(null); this._eventsCount = 0; } else if (events[type]) { if (--this._eventsCount === 0) this._events = objectCreate(null); else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = objectKeys(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 = objectCreate(null); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners) { // 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) return []; var evlistener = events[type]; if (!evlistener) 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) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; }; // About 1.5x faster than the two-arg version of Array#splice(). function spliceOne(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) list[i] = list[k]; list.pop(); } function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } 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 objectCreatePolyfill(proto) { var F = function() {}; F.prototype = proto; return new F; } function objectKeysPolyfill(obj) { var keys = []; for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) { keys.push(k); } return k; } function functionBindPolyfill(context) { var fn = this; return function () { return fn.apply(context, arguments); }; } },{}],178:[function(require,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 } },{}],179:[function(require,module,exports){ /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh * @license MIT */ // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually module.exports = function (obj) { return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) } function isBuffer (obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) } // For Node v0.10 support. Remove this eventually. function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } },{}],180:[function(require,module,exports){ 'use strict'; module.exports = Number.isFinite || function (value) { return !(typeof value !== 'number' || value !== value || value === Infinity || value === -Infinity); }; },{}],181:[function(require,module,exports){ // https://github.com/paulmillr/es6-shim // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isinteger var isFinite = require("is-finite"); module.exports = Number.isInteger || function(val) { return typeof val === "number" && isFinite(val) && Math.floor(val) === val; }; },{"is-finite":180}],182:[function(require,module,exports){ (function (process){(function (){ 'use strict'; function Kareem() { this._pres = new Map(); this._posts = new Map(); } Kareem.prototype.execPre = function(name, context, args, callback) { if (arguments.length === 3) { callback = args; args = []; } var pres = get(this._pres, name, []); var numPres = pres.length; var numAsyncPres = pres.numAsync || 0; var currentPre = 0; var asyncPresLeft = numAsyncPres; var done = false; var $args = args; if (!numPres) { return process.nextTick(function() { callback(null); }); } var next = function() { if (currentPre >= numPres) { return; } var pre = pres[currentPre]; if (pre.isAsync) { var args = [ decorateNextFn(_next), decorateNextFn(function(error) { if (error) { if (done) { return; } done = true; return callback(error); } if (--asyncPresLeft === 0 && currentPre >= numPres) { return callback(null); } }) ]; callMiddlewareFunction(pre.fn, context, args, args[0]); } else if (pre.fn.length > 0) { var args = [decorateNextFn(_next)]; var _args = arguments.length >= 2 ? arguments : [null].concat($args); for (var i = 1; i < _args.length; ++i) { args.push(_args[i]); } callMiddlewareFunction(pre.fn, context, args, args[0]); } else { let maybePromise = null; try { maybePromise = pre.fn.call(context); } catch (err) { if (err != null) { return callback(err); } } if (isPromise(maybePromise)) { maybePromise.then(() => _next(), err => _next(err)); } else { if (++currentPre >= numPres) { if (asyncPresLeft > 0) { // Leave parallel hooks to run return; } else { return process.nextTick(function() { callback(null); }); } } next(); } } }; next.apply(null, [null].concat(args)); function _next(error) { if (error) { if (done) { return; } done = true; return callback(error); } if (++currentPre >= numPres) { if (asyncPresLeft > 0) { // Leave parallel hooks to run return; } else { return callback(null); } } next.apply(context, arguments); } }; Kareem.prototype.execPreSync = function(name, context, args) { var pres = get(this._pres, name, []); var numPres = pres.length; 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 = get(this._posts, name, []); var numPosts = posts.length; var currentPost = 0; var firstError = null; if (options && options.error) { firstError = options.error; } if (!numPosts) { return process.nextTick(function() { callback.apply(null, [firstError].concat(args)); }); } var next = function() { var post = posts[currentPost].fn; var numArgs = 0; var argLength = args.length; var newArgs = []; for (var i = 0; i < argLength; ++i) { numArgs += args[i] && args[i]._kareemIgnore ? 0 : 1; if (!args[i] || !args[i]._kareemIgnore) { newArgs.push(args[i]); } } if (firstError) { if (post.length === numArgs + 2) { var _cb = decorateNextFn(function(error) { if (error) { firstError = error; } if (++currentPost >= numPosts) { return callback.call(null, firstError); } next(); }); callMiddlewareFunction(post, context, [firstError].concat(newArgs).concat([_cb]), _cb); } else { if (++currentPost >= numPosts) { return callback.call(null, firstError); } next(); } } else { const _cb = decorateNextFn(function(error) { if (error) { firstError = error; return next(); } 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([_cb]), _cb); } else { let error; let maybePromise; try { maybePromise = post.apply(context, newArgs); } catch (err) { error = err; firstError = err; } if (isPromise(maybePromise)) { return maybePromise.then(() => _cb(), err => _cb(err)); } if (++currentPost >= numPosts) { return callback.apply(null, [error].concat(args)); } next(error); } } }; next(); }; Kareem.prototype.execPostSync = function(name, context, args) { const posts = get(this._posts, name, []); const numPosts = posts.length; for (let i = 0; i < numPosts; ++i) { posts[i].fn.apply(context, args || []); } }; Kareem.prototype.createWrapperSync = function(name, fn) { var kareem = this; return function syncWrapper() { kareem.execPreSync(name, this, arguments); var toReturn = fn.apply(this, arguments); kareem.execPostSync(name, this, [toReturn]); return toReturn; }; } function _handleWrapError(instance, error, name, context, args, options, callback) { if (options.useErrorHandlers) { var _options = { error: error }; return instance.execPost(name, context, args, _options, function(error) { return typeof callback === 'function' && callback(error); }); } else { return typeof callback === 'function' ? callback(error) : undefined; } } Kareem.prototype.wrap = function(name, fn, context, args, options) { const lastArg = (args.length > 0 ? args[args.length - 1] : null); const argsWithoutCb = typeof lastArg === 'function' ? args.slice(0, args.length - 1) : args; const _this = this; options = options || {}; const checkForPromise = options.checkForPromise; this.execPre(name, context, args, function(error) { if (error) { const numCallbackParams = options.numCallbackParams || 0; const errorArgs = options.contextParameter ? [context] : []; for (var i = errorArgs.length; i < numCallbackParams; ++i) { errorArgs.push(null); } return _handleWrapError(_this, error, name, context, errorArgs, options, lastArg); } const end = (typeof lastArg === 'function' ? args.length - 1 : args.length); const numParameters = fn.length; const ret = fn.apply(context, args.slice(0, end).concat(_cb)); if (checkForPromise) { if (ret != null && typeof ret.then === 'function') { // Thenable, use it return ret.then( res => _cb(null, res), err => _cb(err) ); } // If `fn()` doesn't have a callback argument and doesn't return a // promise, assume it is sync if (numParameters < end + 1) { return _cb(null, ret); } } function _cb() { const args = arguments; const argsWithoutError = Array.prototype.slice.call(arguments, 1); if (options.nullResultByDefault && argsWithoutError.length === 0) { argsWithoutError.push(null); } if (arguments[0]) { // Assume error return _handleWrapError(_this, arguments[0], name, context, argsWithoutError, options, lastArg); } else { _this.execPost(name, context, argsWithoutError, function() { if (arguments[0]) { return typeof lastArg === 'function' ? lastArg(arguments[0]) : undefined; } return typeof lastArg === 'function' ? lastArg.apply(context, arguments) : undefined; }); } } }); }; Kareem.prototype.filter = function(fn) { const clone = this.clone(); const pres = Array.from(clone._pres.keys()); for (const name of pres) { const hooks = this._pres.get(name). map(h => Object.assign({}, h, { name: name })). filter(fn); if (hooks.length === 0) { clone._pres.delete(name); continue; } hooks.numAsync = hooks.filter(h => h.isAsync).length; clone._pres.set(name, hooks); } const posts = Array.from(clone._posts.keys()); for (const name of posts) { const hooks = this._posts.get(name). map(h => Object.assign({}, h, { name: name })). filter(fn); if (hooks.length === 0) { clone._posts.delete(name); continue; } clone._posts.set(name, hooks); } 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() { process.nextTick(() => fn.apply(this, arguments)); }; } return function() { var _context = context || this; var args = Array.prototype.slice.call(arguments); _this.wrap(name, fn, _context, args, options); }; }; Kareem.prototype.pre = function(name, isAsync, fn, error, unshift) { let options = {}; if (typeof isAsync === 'object' && isAsync != null) { options = isAsync; isAsync = options.isAsync; } else if (typeof arguments[1] !== 'boolean') { error = fn; fn = isAsync; isAsync = false; } const pres = get(this._pres, 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) { const hooks = get(this._posts, 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() { const n = new Kareem(); for (let key of this._pres.keys()) { const clone = this._pres.get(key).slice(); clone.numAsync = this._pres.get(key).numAsync; n._pres.set(key, clone); } for (let key of this._posts.keys()) { n._posts.set(key, this._posts.get(key).slice()); } return n; }; Kareem.prototype.merge = function(other, clone) { clone = arguments.length === 1 ? true : clone; var ret = clone ? this.clone() : this; for (let key of other._pres.keys()) { const sourcePres = get(ret._pres, key, []); const deduplicated = other._pres.get(key). // Deduplicate based on `fn` filter(p => sourcePres.map(_p => _p.fn).indexOf(p.fn) === -1); const combined = sourcePres.concat(deduplicated); combined.numAsync = sourcePres.numAsync || 0; combined.numAsync += deduplicated.filter(p => p.isAsync).length; ret._pres.set(key, combined); } for (let key of other._posts.keys()) { const sourcePosts = get(ret._posts, key, []); const deduplicated = other._posts.get(key). filter(p => sourcePosts.indexOf(p) === -1); ret._posts.set(key, sourcePosts.concat(deduplicated)); } return ret; }; function get(map, key, def) { if (map.has(key)) { return map.get(key); } return def; } function callMiddlewareFunction(fn, context, args, next) { let maybePromise; try { maybePromise = fn.apply(context, args); } catch (error) { return next(error); } if (isPromise(maybePromise)) { maybePromise.then(() => next(), err => next(err)); } } function isPromise(v) { return v != null && typeof v.then === 'function'; } function decorateNextFn(fn) { var called = false; var _this = this; return function() { // Ensure this function can only be called once if (called) { return; } called = true; // Make sure to clear the stack so try/catch doesn't catch errors // in subsequent middleware return process.nextTick(() => fn.apply(_this, arguments)); }; } module.exports = Kareem; }).call(this)}).call(this,require('_process')) },{"_process":325}],183:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); 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 _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } 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 _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 _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } 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(n); 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 _createForOfIteratorHelperLoose(o) { var i = 0; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } i = o[Symbol.iterator](); return i.next.bind(i); } // these aren't really private, but nor are they really useful to document /** * @private */ var LuxonError = /*#__PURE__*/function (_Error) { _inheritsLoose(LuxonError, _Error); function LuxonError() { return _Error.apply(this, arguments) || this; } return LuxonError; }( /*#__PURE__*/_wrapNativeSuper(Error)); /** * @private */ var InvalidDateTimeError = /*#__PURE__*/function (_LuxonError) { _inheritsLoose(InvalidDateTimeError, _LuxonError); function InvalidDateTimeError(reason) { return _LuxonError.call(this, "Invalid DateTime: " + reason.toMessage()) || this; } return InvalidDateTimeError; }(LuxonError); /** * @private */ var InvalidIntervalError = /*#__PURE__*/function (_LuxonError2) { _inheritsLoose(InvalidIntervalError, _LuxonError2); function InvalidIntervalError(reason) { return _LuxonError2.call(this, "Invalid Interval: " + reason.toMessage()) || this; } return InvalidIntervalError; }(LuxonError); /** * @private */ var InvalidDurationError = /*#__PURE__*/function (_LuxonError3) { _inheritsLoose(InvalidDurationError, _LuxonError3); function InvalidDurationError(reason) { return _LuxonError3.call(this, "Invalid Duration: " + reason.toMessage()) || this; } return InvalidDurationError; }(LuxonError); /** * @private */ var ConflictingSpecificationError = /*#__PURE__*/function (_LuxonError4) { _inheritsLoose(ConflictingSpecificationError, _LuxonError4); function ConflictingSpecificationError() { return _LuxonError4.apply(this, arguments) || this; } return ConflictingSpecificationError; }(LuxonError); /** * @private */ var InvalidUnitError = /*#__PURE__*/function (_LuxonError5) { _inheritsLoose(InvalidUnitError, _LuxonError5); function InvalidUnitError(unit) { return _LuxonError5.call(this, "Invalid unit " + unit) || this; } return InvalidUnitError; }(LuxonError); /** * @private */ var InvalidArgumentError = /*#__PURE__*/function (_LuxonError6) { _inheritsLoose(InvalidArgumentError, _LuxonError6); function InvalidArgumentError() { return _LuxonError6.apply(this, arguments) || this; } return InvalidArgumentError; }(LuxonError); /** * @private */ var ZoneIsAbstractError = /*#__PURE__*/function (_LuxonError7) { _inheritsLoose(ZoneIsAbstractError, _LuxonError7); function ZoneIsAbstractError() { return _LuxonError7.call(this, "Zone is an abstract class") || this; } return ZoneIsAbstractError; }(LuxonError); /** * @private */ var n = "numeric", s = "short", l = "long"; var DATE_SHORT = { year: n, month: n, day: n }; var DATE_MED = { year: n, month: s, day: n }; var DATE_MED_WITH_WEEKDAY = { year: n, month: s, day: n, weekday: s }; var DATE_FULL = { year: n, month: l, day: n }; var DATE_HUGE = { year: n, month: l, day: n, weekday: l }; var TIME_SIMPLE = { hour: n, minute: n }; var TIME_WITH_SECONDS = { hour: n, minute: n, second: n }; var TIME_WITH_SHORT_OFFSET = { hour: n, minute: n, second: n, timeZoneName: s }; var TIME_WITH_LONG_OFFSET = { hour: n, minute: n, second: n, timeZoneName: l }; var TIME_24_SIMPLE = { hour: n, minute: n, hour12: false }; /** * {@link toLocaleString}; format like '09:30:23', always 24-hour. */ var TIME_24_WITH_SECONDS = { hour: n, minute: n, second: n, hour12: false }; /** * {@link toLocaleString}; format like '09:30:23 EDT', always 24-hour. */ var TIME_24_WITH_SHORT_OFFSET = { hour: n, minute: n, second: n, hour12: false, timeZoneName: s }; /** * {@link toLocaleString}; format like '09:30:23 Eastern Daylight Time', always 24-hour. */ var TIME_24_WITH_LONG_OFFSET = { hour: n, minute: n, second: n, hour12: false, timeZoneName: l }; /** * {@link toLocaleString}; format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is. */ var DATETIME_SHORT = { year: n, month: n, day: n, hour: n, minute: n }; /** * {@link toLocaleString}; format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is. */ var DATETIME_SHORT_WITH_SECONDS = { year: n, month: n, day: n, hour: n, minute: n, second: n }; var DATETIME_MED = { year: n, month: s, day: n, hour: n, minute: n }; var DATETIME_MED_WITH_SECONDS = { year: n, month: s, day: n, hour: n, minute: n, second: n }; var DATETIME_MED_WITH_WEEKDAY = { year: n, month: s, day: n, weekday: s, hour: n, minute: n }; var DATETIME_FULL = { year: n, month: l, day: n, hour: n, minute: n, timeZoneName: s }; var DATETIME_FULL_WITH_SECONDS = { year: n, month: l, day: n, hour: n, minute: n, second: n, timeZoneName: s }; var DATETIME_HUGE = { year: n, month: l, day: n, weekday: l, hour: n, minute: n, timeZoneName: l }; var DATETIME_HUGE_WITH_SECONDS = { year: n, month: l, day: n, weekday: l, hour: n, minute: n, second: n, timeZoneName: l }; /* This is just a junk drawer, containing anything used across multiple classes. Because Luxon is small(ish), this should stay small and we won't worry about splitting it up into, say, parsingUtil.js and basicUtil.js and so on. But they are divided up by feature area. */ /** * @private */ // TYPES function isUndefined(o) { return typeof o === "undefined"; } function isNumber(o) { return typeof o === "number"; } function isInteger(o) { return typeof o === "number" && o % 1 === 0; } function isString(o) { return typeof o === "string"; } function isDate(o) { return Object.prototype.toString.call(o) === "[object Date]"; } // CAPABILITIES function hasIntl() { try { return typeof Intl !== "undefined" && Intl.DateTimeFormat; } catch (e) { return false; } } function hasFormatToParts() { return !isUndefined(Intl.DateTimeFormat.prototype.formatToParts); } function hasRelative() { try { return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat; } catch (e) { return false; } } // OBJECTS AND ARRAYS function maybeArray(thing) { return Array.isArray(thing) ? thing : [thing]; } function bestBy(arr, by, compare) { if (arr.length === 0) { return undefined; } return arr.reduce(function (best, next) { var pair = [by(next), next]; if (!best) { return pair; } else if (compare(best[0], pair[0]) === best[0]) { return best; } else { return pair; } }, null)[1]; } function pick(obj, keys) { return keys.reduce(function (a, k) { a[k] = obj[k]; return a; }, {}); } function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } // NUMBERS AND STRINGS function integerBetween(thing, bottom, top) { return isInteger(thing) && thing >= bottom && thing <= top; } // x % n but takes the sign of n instead of x function floorMod(x, n) { return x - n * Math.floor(x / n); } function padStart(input, n) { if (n === void 0) { n = 2; } var minus = input < 0 ? "-" : ""; var target = minus ? input * -1 : input; var result; if (target.toString().length < n) { result = ("0".repeat(n) + target).slice(-n); } else { result = target.toString(); } return "" + minus + result; } function parseInteger(string) { if (isUndefined(string) || string === null || string === "") { return undefined; } else { return parseInt(string, 10); } } function parseMillis(fraction) { // Return undefined (instead of 0) in these cases, where fraction is not set if (isUndefined(fraction) || fraction === null || fraction === "") { return undefined; } else { var f = parseFloat("0." + fraction) * 1000; return Math.floor(f); } } function roundTo(number, digits, towardZero) { if (towardZero === void 0) { towardZero = false; } var factor = Math.pow(10, digits), rounder = towardZero ? Math.trunc : Math.round; return rounder(number * factor) / factor; } // DATE BASICS function isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function daysInMonth(year, month) { var modMonth = floorMod(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12; if (modMonth === 2) { return isLeapYear(modYear) ? 29 : 28; } else { return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1]; } } // covert a calendar object to a local timestamp (epoch, but with the offset baked in) function objToLocalTS(obj) { var d = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond); // for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that if (obj.year < 100 && obj.year >= 0) { d = new Date(d); d.setUTCFullYear(d.getUTCFullYear() - 1900); } return +d; } function weeksInWeekYear(weekYear) { var p1 = (weekYear + Math.floor(weekYear / 4) - Math.floor(weekYear / 100) + Math.floor(weekYear / 400)) % 7, last = weekYear - 1, p2 = (last + Math.floor(last / 4) - Math.floor(last / 100) + Math.floor(last / 400)) % 7; return p1 === 4 || p2 === 3 ? 53 : 52; } function untruncateYear(year) { if (year > 99) { return year; } else return year > 60 ? 1900 + year : 2000 + year; } // PARSING function parseZoneInfo(ts, offsetFormat, locale, timeZone) { if (timeZone === void 0) { timeZone = null; } var date = new Date(ts), intlOpts = { hour12: false, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }; if (timeZone) { intlOpts.timeZone = timeZone; } var modified = Object.assign({ timeZoneName: offsetFormat }, intlOpts), intl = hasIntl(); if (intl && hasFormatToParts()) { var parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find(function (m) { return m.type.toLowerCase() === "timezonename"; }); return parsed ? parsed.value : null; } else if (intl) { // this probably doesn't work for all locales var without = new Intl.DateTimeFormat(locale, intlOpts).format(date), included = new Intl.DateTimeFormat(locale, modified).format(date), diffed = included.substring(without.length), trimmed = diffed.replace(/^[, \u200e]+/, ""); return trimmed; } else { return null; } } // signedOffset('-5', '30') -> -330 function signedOffset(offHourStr, offMinuteStr) { var offHour = parseInt(offHourStr, 10); // don't || this because we want to preserve -0 if (Number.isNaN(offHour)) { offHour = 0; } var offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin; return offHour * 60 + offMinSigned; } // COERCION function asNumber(value) { var numericValue = Number(value); if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue)) throw new InvalidArgumentError("Invalid unit value " + value); return numericValue; } function normalizeObject(obj, normalizer, nonUnitKeys) { var normalized = {}; for (var u in obj) { if (hasOwnProperty(obj, u)) { if (nonUnitKeys.indexOf(u) >= 0) continue; var v = obj[u]; if (v === undefined || v === null) continue; normalized[normalizer(u)] = asNumber(v); } } return normalized; } function formatOffset(offset, format) { var hours = Math.trunc(Math.abs(offset / 60)), minutes = Math.trunc(Math.abs(offset % 60)), sign = offset >= 0 ? "+" : "-"; switch (format) { case "short": return "" + sign + padStart(hours, 2) + ":" + padStart(minutes, 2); case "narrow": return "" + sign + hours + (minutes > 0 ? ":" + minutes : ""); case "techie": return "" + sign + padStart(hours, 2) + padStart(minutes, 2); default: throw new RangeError("Value format " + format + " is out of range for property format"); } } function timeObject(obj) { return pick(obj, ["hour", "minute", "second", "millisecond"]); } var ianaRegex = /[A-Za-z_+-]{1,256}(:?\/[A-Za-z_+-]{1,256}(\/[A-Za-z_+-]{1,256})?)?/; function stringify(obj) { return JSON.stringify(obj, Object.keys(obj).sort()); } /** * @private */ var monthsLong = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var monthsShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]; function months(length) { switch (length) { case "narrow": return monthsNarrow; case "short": return monthsShort; case "long": return monthsLong; case "numeric": return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]; case "2-digit": return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; default: return null; } } var weekdaysLong = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; var weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"]; function weekdays(length) { switch (length) { case "narrow": return weekdaysNarrow; case "short": return weekdaysShort; case "long": return weekdaysLong; case "numeric": return ["1", "2", "3", "4", "5", "6", "7"]; default: return null; } } var meridiems = ["AM", "PM"]; var erasLong = ["Before Christ", "Anno Domini"]; var erasShort = ["BC", "AD"]; var erasNarrow = ["B", "A"]; function eras(length) { switch (length) { case "narrow": return erasNarrow; case "short": return erasShort; case "long": return erasLong; default: return null; } } function meridiemForDateTime(dt) { return meridiems[dt.hour < 12 ? 0 : 1]; } function weekdayForDateTime(dt, length) { return weekdays(length)[dt.weekday - 1]; } function monthForDateTime(dt, length) { return months(length)[dt.month - 1]; } function eraForDateTime(dt, length) { return eras(length)[dt.year < 0 ? 0 : 1]; } function formatRelativeTime(unit, count, numeric, narrow) { if (numeric === void 0) { numeric = "always"; } if (narrow === void 0) { narrow = false; } var units = { years: ["year", "yr."], quarters: ["quarter", "qtr."], months: ["month", "mo."], weeks: ["week", "wk."], days: ["day", "day", "days"], hours: ["hour", "hr."], minutes: ["minute", "min."], seconds: ["second", "sec."] }; var lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1; if (numeric === "auto" && lastable) { var isDay = unit === "days"; switch (count) { case 1: return isDay ? "tomorrow" : "next " + units[unit][0]; case -1: return isDay ? "yesterday" : "last " + units[unit][0]; case 0: return isDay ? "today" : "this " + units[unit][0]; } } var isInPast = Object.is(count, -0) || count < 0, fmtValue = Math.abs(count), singular = fmtValue === 1, lilUnits = units[unit], fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit; return isInPast ? fmtValue + " " + fmtUnit + " ago" : "in " + fmtValue + " " + fmtUnit; } function formatString(knownFormat) { // these all have the offsets removed because we don't have access to them // without all the intl stuff this is backfilling var filtered = pick(knownFormat, ["weekday", "era", "year", "month", "day", "hour", "minute", "second", "timeZoneName", "hour12"]), key = stringify(filtered), dateTimeHuge = "EEEE, LLLL d, yyyy, h:mm a"; switch (key) { case stringify(DATE_SHORT): return "M/d/yyyy"; case stringify(DATE_MED): return "LLL d, yyyy"; case stringify(DATE_MED_WITH_WEEKDAY): return "EEE, LLL d, yyyy"; case stringify(DATE_FULL): return "LLLL d, yyyy"; case stringify(DATE_HUGE): return "EEEE, LLLL d, yyyy"; case stringify(TIME_SIMPLE): return "h:mm a"; case stringify(TIME_WITH_SECONDS): return "h:mm:ss a"; case stringify(TIME_WITH_SHORT_OFFSET): return "h:mm a"; case stringify(TIME_WITH_LONG_OFFSET): return "h:mm a"; case stringify(TIME_24_SIMPLE): return "HH:mm"; case stringify(TIME_24_WITH_SECONDS): return "HH:mm:ss"; case stringify(TIME_24_WITH_SHORT_OFFSET): return "HH:mm"; case stringify(TIME_24_WITH_LONG_OFFSET): return "HH:mm"; case stringify(DATETIME_SHORT): return "M/d/yyyy, h:mm a"; case stringify(DATETIME_MED): return "LLL d, yyyy, h:mm a"; case stringify(DATETIME_FULL): return "LLLL d, yyyy, h:mm a"; case stringify(DATETIME_HUGE): return dateTimeHuge; case stringify(DATETIME_SHORT_WITH_SECONDS): return "M/d/yyyy, h:mm:ss a"; case stringify(DATETIME_MED_WITH_SECONDS): return "LLL d, yyyy, h:mm:ss a"; case stringify(DATETIME_MED_WITH_WEEKDAY): return "EEE, d LLL yyyy, h:mm a"; case stringify(DATETIME_FULL_WITH_SECONDS): return "LLLL d, yyyy, h:mm:ss a"; case stringify(DATETIME_HUGE_WITH_SECONDS): return "EEEE, LLLL d, yyyy, h:mm:ss a"; default: return dateTimeHuge; } } function stringifyTokens(splits, tokenToString) { var s = ""; for (var _iterator = _createForOfIteratorHelperLoose(splits), _step; !(_step = _iterator()).done;) { var token = _step.value; if (token.literal) { s += token.val; } else { s += tokenToString(token.val); } } return s; } var _macroTokenToFormatOpts = { D: DATE_SHORT, DD: DATE_MED, DDD: DATE_FULL, DDDD: DATE_HUGE, t: TIME_SIMPLE, tt: TIME_WITH_SECONDS, ttt: TIME_WITH_SHORT_OFFSET, tttt: TIME_WITH_LONG_OFFSET, T: TIME_24_SIMPLE, TT: TIME_24_WITH_SECONDS, TTT: TIME_24_WITH_SHORT_OFFSET, TTTT: TIME_24_WITH_LONG_OFFSET, f: DATETIME_SHORT, ff: DATETIME_MED, fff: DATETIME_FULL, ffff: DATETIME_HUGE, F: DATETIME_SHORT_WITH_SECONDS, FF: DATETIME_MED_WITH_SECONDS, FFF: DATETIME_FULL_WITH_SECONDS, FFFF: DATETIME_HUGE_WITH_SECONDS }; /** * @private */ var Formatter = /*#__PURE__*/function () { Formatter.create = function create(locale, opts) { if (opts === void 0) { opts = {}; } return new Formatter(locale, opts); }; Formatter.parseFormat = function parseFormat(fmt) { var current = null, currentFull = "", bracketed = false; var splits = []; for (var i = 0; i < fmt.length; i++) { var c = fmt.charAt(i); if (c === "'") { if (currentFull.length > 0) { splits.push({ literal: bracketed, val: currentFull }); } current = null; currentFull = ""; bracketed = !bracketed; } else if (bracketed) { currentFull += c; } else if (c === current) { currentFull += c; } else { if (currentFull.length > 0) { splits.push({ literal: false, val: currentFull }); } currentFull = c; current = c; } } if (currentFull.length > 0) { splits.push({ literal: bracketed, val: currentFull }); } return splits; }; Formatter.macroTokenToFormatOpts = function macroTokenToFormatOpts(token) { return _macroTokenToFormatOpts[token]; }; function Formatter(locale, formatOpts) { this.opts = formatOpts; this.loc = locale; this.systemLoc = null; } var _proto = Formatter.prototype; _proto.formatWithSystemDefault = function formatWithSystemDefault(dt, opts) { if (this.systemLoc === null) { this.systemLoc = this.loc.redefaultToSystem(); } var df = this.systemLoc.dtFormatter(dt, Object.assign({}, this.opts, opts)); return df.format(); }; _proto.formatDateTime = function formatDateTime(dt, opts) { if (opts === void 0) { opts = {}; } var df = this.loc.dtFormatter(dt, Object.assign({}, this.opts, opts)); return df.format(); }; _proto.formatDateTimeParts = function formatDateTimeParts(dt, opts) { if (opts === void 0) { opts = {}; } var df = this.loc.dtFormatter(dt, Object.assign({}, this.opts, opts)); return df.formatToParts(); }; _proto.resolvedOptions = function resolvedOptions(dt, opts) { if (opts === void 0) { opts = {}; } var df = this.loc.dtFormatter(dt, Object.assign({}, this.opts, opts)); return df.resolvedOptions(); }; _proto.num = function num(n, p) { if (p === void 0) { p = 0; } // we get some perf out of doing this here, annoyingly if (this.opts.forceSimple) { return padStart(n, p); } var opts = Object.assign({}, this.opts); if (p > 0) { opts.padTo = p; } return this.loc.numberFormatter(opts).format(n); }; _proto.formatDateTimeFromString = function formatDateTimeFromString(dt, fmt) { var _this = this; var knownEnglish = this.loc.listingMode() === "en", useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory" && hasFormatToParts(), string = function string(opts, extract) { return _this.loc.extract(dt, opts, extract); }, formatOffset = function formatOffset(opts) { if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) { return "Z"; } return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : ""; }, meridiem = function meridiem() { return knownEnglish ? meridiemForDateTime(dt) : string({ hour: "numeric", hour12: true }, "dayperiod"); }, month = function month(length, standalone) { return knownEnglish ? monthForDateTime(dt, length) : string(standalone ? { month: length } : { month: length, day: "numeric" }, "month"); }, weekday = function weekday(length, standalone) { return knownEnglish ? weekdayForDateTime(dt, length) : string(standalone ? { weekday: length } : { weekday: length, month: "long", day: "numeric" }, "weekday"); }, maybeMacro = function maybeMacro(token) { var formatOpts = Formatter.macroTokenToFormatOpts(token); if (formatOpts) { return _this.formatWithSystemDefault(dt, formatOpts); } else { return token; } }, era = function era(length) { return knownEnglish ? eraForDateTime(dt, length) : string({ era: length }, "era"); }, tokenToString = function tokenToString(token) { // Where possible: http://cldr.unicode.org/translation/date-time-1/date-time#TOC-Standalone-vs.-Format-Styles switch (token) { // ms case "S": return _this.num(dt.millisecond); case "u": // falls through case "SSS": return _this.num(dt.millisecond, 3); // seconds case "s": return _this.num(dt.second); case "ss": return _this.num(dt.second, 2); // minutes case "m": return _this.num(dt.minute); case "mm": return _this.num(dt.minute, 2); // hours case "h": return _this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12); case "hh": return _this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2); case "H": return _this.num(dt.hour); case "HH": return _this.num(dt.hour, 2); // offset case "Z": // like +6 return formatOffset({ format: "narrow", allowZ: _this.opts.allowZ }); case "ZZ": // like +06:00 return formatOffset({ format: "short", allowZ: _this.opts.allowZ }); case "ZZZ": // like +0600 return formatOffset({ format: "techie", allowZ: _this.opts.allowZ }); case "ZZZZ": // like EST return dt.zone.offsetName(dt.ts, { format: "short", locale: _this.loc.locale }); case "ZZZZZ": // like Eastern Standard Time return dt.zone.offsetName(dt.ts, { format: "long", locale: _this.loc.locale }); // zone case "z": // like America/New_York return dt.zoneName; // meridiems case "a": return meridiem(); // dates case "d": return useDateTimeFormatter ? string({ day: "numeric" }, "day") : _this.num(dt.day); case "dd": return useDateTimeFormatter ? string({ day: "2-digit" }, "day") : _this.num(dt.day, 2); // weekdays - standalone case "c": // like 1 return _this.num(dt.weekday); case "ccc": // like 'Tues' return weekday("short", true); case "cccc": // like 'Tuesday' return weekday("long", true); case "ccccc": // like 'T' return weekday("narrow", true); // weekdays - format case "E": // like 1 return _this.num(dt.weekday); case "EEE": // like 'Tues' return weekday("short", false); case "EEEE": // like 'Tuesday' return weekday("long", false); case "EEEEE": // like 'T' return weekday("narrow", false); // months - standalone case "L": // like 1 return useDateTimeFormatter ? string({ month: "numeric", day: "numeric" }, "month") : _this.num(dt.month); case "LL": // like 01, doesn't seem to work return useDateTimeFormatter ? string({ month: "2-digit", day: "numeric" }, "month") : _this.num(dt.month, 2); case "LLL": // like Jan return month("short", true); case "LLLL": // like January return month("long", true); case "LLLLL": // like J return month("narrow", true); // months - format case "M": // like 1 return useDateTimeFormatter ? string({ month: "numeric" }, "month") : _this.num(dt.month); case "MM": // like 01 return useDateTimeFormatter ? string({ month: "2-digit" }, "month") : _this.num(dt.month, 2); case "MMM": // like Jan return month("short", false); case "MMMM": // like January return month("long", false); case "MMMMM": // like J return month("narrow", false); // years case "y": // like 2014 return useDateTimeFormatter ? string({ year: "numeric" }, "year") : _this.num(dt.year); case "yy": // like 14 return useDateTimeFormatter ? string({ year: "2-digit" }, "year") : _this.num(dt.year.toString().slice(-2), 2); case "yyyy": // like 0012 return useDateTimeFormatter ? string({ year: "numeric" }, "year") : _this.num(dt.year, 4); case "yyyyyy": // like 000012 return useDateTimeFormatter ? string({ year: "numeric" }, "year") : _this.num(dt.year, 6); // eras case "G": // like AD return era("short"); case "GG": // like Anno Domini return era("long"); case "GGGGG": return era("narrow"); case "kk": return _this.num(dt.weekYear.toString().slice(-2), 2); case "kkkk": return _this.num(dt.weekYear, 4); case "W": return _this.num(dt.weekNumber); case "WW": return _this.num(dt.weekNumber, 2); case "o": return _this.num(dt.ordinal); case "ooo": return _this.num(dt.ordinal, 3); case "q": // like 1 return _this.num(dt.quarter); case "qq": // like 01 return _this.num(dt.quarter, 2); case "X": return _this.num(Math.floor(dt.ts / 1000)); case "x": return _this.num(dt.ts); default: return maybeMacro(token); } }; return stringifyTokens(Formatter.parseFormat(fmt), tokenToString); }; _proto.formatDurationFromString = function formatDurationFromString(dur, fmt) { var _this2 = this; var tokenToField = function tokenToField(token) { switch (token[0]) { case "S": return "millisecond"; case "s": return "second"; case "m": return "minute"; case "h": return "hour"; case "d": return "day"; case "M": return "month"; case "y": return "year"; default: return null; } }, tokenToString = function tokenToString(lildur) { return function (token) { var mapped = tokenToField(token); if (mapped) { return _this2.num(lildur.get(mapped), token.length); } else { return token; } }; }, tokens = Formatter.parseFormat(fmt), realTokens = tokens.reduce(function (found, _ref) { var literal = _ref.literal, val = _ref.val; return literal ? found : found.concat(val); }, []), collapsed = dur.shiftTo.apply(dur, realTokens.map(tokenToField).filter(function (t) { return t; })); return stringifyTokens(tokens, tokenToString(collapsed)); }; return Formatter; }(); var Invalid = /*#__PURE__*/function () { function Invalid(reason, explanation) { this.reason = reason; this.explanation = explanation; } var _proto = Invalid.prototype; _proto.toMessage = function toMessage() { if (this.explanation) { return this.reason + ": " + this.explanation; } else { return this.reason; } }; return Invalid; }(); /** * @interface */ var Zone = /*#__PURE__*/function () { function Zone() {} var _proto = Zone.prototype; /** * Returns the offset's common name (such as EST) at the specified timestamp * @abstract * @param {number} ts - Epoch milliseconds for which to get the name * @param {Object} opts - Options to affect the format * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'. * @param {string} opts.locale - What locale to return the offset name in. * @return {string} */ _proto.offsetName = function offsetName(ts, opts) { throw new ZoneIsAbstractError(); } /** * Returns the offset's value as a string * @abstract * @param {number} ts - Epoch milliseconds for which to get the offset * @param {string} format - What style of offset to return. * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively * @return {string} */ ; _proto.formatOffset = function formatOffset(ts, format) { throw new ZoneIsAbstractError(); } /** * Return the offset in minutes for this zone at the specified timestamp. * @abstract * @param {number} ts - Epoch milliseconds for which to compute the offset * @return {number} */ ; _proto.offset = function offset(ts) { throw new ZoneIsAbstractError(); } /** * Return whether this Zone is equal to another zone * @abstract * @param {Zone} otherZone - the zone to compare * @return {boolean} */ ; _proto.equals = function equals(otherZone) { throw new ZoneIsAbstractError(); } /** * Return whether this Zone is valid. * @abstract * @type {boolean} */ ; _createClass(Zone, [{ key: "type", /** * The type of zone * @abstract * @type {string} */ get: function get() { throw new ZoneIsAbstractError(); } /** * The name of this zone. * @abstract * @type {string} */ }, { key: "name", get: function get() { throw new ZoneIsAbstractError(); } /** * Returns whether the offset is known to be fixed for the whole year. * @abstract * @type {boolean} */ }, { key: "universal", get: function get() { throw new ZoneIsAbstractError(); } }, { key: "isValid", get: function get() { throw new ZoneIsAbstractError(); } }]); return Zone; }(); var singleton = null; /** * Represents the local zone for this JavaScript environment. * @implements {Zone} */ var LocalZone = /*#__PURE__*/function (_Zone) { _inheritsLoose(LocalZone, _Zone); function LocalZone() { return _Zone.apply(this, arguments) || this; } var _proto = LocalZone.prototype; /** @override **/ _proto.offsetName = function offsetName(ts, _ref) { var format = _ref.format, locale = _ref.locale; return parseZoneInfo(ts, format, locale); } /** @override **/ ; _proto.formatOffset = function formatOffset$1(ts, format) { return formatOffset(this.offset(ts), format); } /** @override **/ ; _proto.offset = function offset(ts) { return -new Date(ts).getTimezoneOffset(); } /** @override **/ ; _proto.equals = function equals(otherZone) { return otherZone.type === "local"; } /** @override **/ ; _createClass(LocalZone, [{ key: "type", /** @override **/ get: function get() { return "local"; } /** @override **/ }, { key: "name", get: function get() { if (hasIntl()) { return new Intl.DateTimeFormat().resolvedOptions().timeZone; } else return "local"; } /** @override **/ }, { key: "universal", get: function get() { return false; } }, { key: "isValid", get: function get() { return true; } }], [{ key: "instance", /** * Get a singleton instance of the local zone * @return {LocalZone} */ get: function get() { if (singleton === null) { singleton = new LocalZone(); } return singleton; } }]); return LocalZone; }(Zone); var matchingRegex = RegExp("^" + ianaRegex.source + "$"); var dtfCache = {}; function makeDTF(zone) { if (!dtfCache[zone]) { dtfCache[zone] = new Intl.DateTimeFormat("en-US", { hour12: false, timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" }); } return dtfCache[zone]; } var typeToPos = { year: 0, month: 1, day: 2, hour: 3, minute: 4, second: 5 }; function hackyOffset(dtf, date) { var formatted = dtf.format(date).replace(/\u200E/g, ""), parsed = /(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(formatted), fMonth = parsed[1], fDay = parsed[2], fYear = parsed[3], fHour = parsed[4], fMinute = parsed[5], fSecond = parsed[6]; return [fYear, fMonth, fDay, fHour, fMinute, fSecond]; } function partsOffset(dtf, date) { var formatted = dtf.formatToParts(date), filled = []; for (var i = 0; i < formatted.length; i++) { var _formatted$i = formatted[i], type = _formatted$i.type, value = _formatted$i.value, pos = typeToPos[type]; if (!isUndefined(pos)) { filled[pos] = parseInt(value, 10); } } return filled; } var ianaZoneCache = {}; /** * A zone identified by an IANA identifier, like America/New_York * @implements {Zone} */ var IANAZone = /*#__PURE__*/function (_Zone) { _inheritsLoose(IANAZone, _Zone); /** * @param {string} name - Zone name * @return {IANAZone} */ IANAZone.create = function create(name) { if (!ianaZoneCache[name]) { ianaZoneCache[name] = new IANAZone(name); } return ianaZoneCache[name]; } /** * Reset local caches. Should only be necessary in testing scenarios. * @return {void} */ ; IANAZone.resetCache = function resetCache() { ianaZoneCache = {}; dtfCache = {}; } /** * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that. * @param {string} s - The string to check validity on * @example IANAZone.isValidSpecifier("America/New_York") //=> true * @example IANAZone.isValidSpecifier("Fantasia/Castle") //=> true * @example IANAZone.isValidSpecifier("Sport~~blorp") //=> false * @return {boolean} */ ; IANAZone.isValidSpecifier = function isValidSpecifier(s) { return !!(s && s.match(matchingRegex)); } /** * Returns whether the provided string identifies a real zone * @param {string} zone - The string to check * @example IANAZone.isValidZone("America/New_York") //=> true * @example IANAZone.isValidZone("Fantasia/Castle") //=> false * @example IANAZone.isValidZone("Sport~~blorp") //=> false * @return {boolean} */ ; IANAZone.isValidZone = function isValidZone(zone) { try { new Intl.DateTimeFormat("en-US", { timeZone: zone }).format(); return true; } catch (e) { return false; } } // Etc/GMT+8 -> -480 /** @ignore */ ; IANAZone.parseGMTOffset = function parseGMTOffset(specifier) { if (specifier) { var match = specifier.match(/^Etc\/GMT([+-]\d{1,2})$/i); if (match) { return -60 * parseInt(match[1]); } } return null; }; function IANAZone(name) { var _this; _this = _Zone.call(this) || this; /** @private **/ _this.zoneName = name; /** @private **/ _this.valid = IANAZone.isValidZone(name); return _this; } /** @override **/ var _proto = IANAZone.prototype; /** @override **/ _proto.offsetName = function offsetName(ts, _ref) { var format = _ref.format, locale = _ref.locale; return parseZoneInfo(ts, format, locale, this.name); } /** @override **/ ; _proto.formatOffset = function formatOffset$1(ts, format) { return formatOffset(this.offset(ts), format); } /** @override **/ ; _proto.offset = function offset(ts) { var date = new Date(ts), dtf = makeDTF(this.name), _ref2 = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date), year = _ref2[0], month = _ref2[1], day = _ref2[2], hour = _ref2[3], minute = _ref2[4], second = _ref2[5], adjustedHour = hour === 24 ? 0 : hour; var asUTC = objToLocalTS({ year: year, month: month, day: day, hour: adjustedHour, minute: minute, second: second, millisecond: 0 }); var asTS = +date; var over = asTS % 1000; asTS -= over >= 0 ? over : 1000 + over; return (asUTC - asTS) / (60 * 1000); } /** @override **/ ; _proto.equals = function equals(otherZone) { return otherZone.type === "iana" && otherZone.name === this.name; } /** @override **/ ; _createClass(IANAZone, [{ key: "type", get: function get() { return "iana"; } /** @override **/ }, { key: "name", get: function get() { return this.zoneName; } /** @override **/ }, { key: "universal", get: function get() { return false; } }, { key: "isValid", get: function get() { return this.valid; } }]); return IANAZone; }(Zone); var singleton$1 = null; /** * A zone with a fixed offset (meaning no DST) * @implements {Zone} */ var FixedOffsetZone = /*#__PURE__*/function (_Zone) { _inheritsLoose(FixedOffsetZone, _Zone); /** * Get an instance with a specified offset * @param {number} offset - The offset in minutes * @return {FixedOffsetZone} */ FixedOffsetZone.instance = function instance(offset) { return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset); } /** * Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6" * @param {string} s - The offset string to parse * @example FixedOffsetZone.parseSpecifier("UTC+6") * @example FixedOffsetZone.parseSpecifier("UTC+06") * @example FixedOffsetZone.parseSpecifier("UTC-6:00") * @return {FixedOffsetZone} */ ; FixedOffsetZone.parseSpecifier = function parseSpecifier(s) { if (s) { var r = s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i); if (r) { return new FixedOffsetZone(signedOffset(r[1], r[2])); } } return null; }; _createClass(FixedOffsetZone, null, [{ key: "utcInstance", /** * Get a singleton instance of UTC * @return {FixedOffsetZone} */ get: function get() { if (singleton$1 === null) { singleton$1 = new FixedOffsetZone(0); } return singleton$1; } }]); function FixedOffsetZone(offset) { var _this; _this = _Zone.call(this) || this; /** @private **/ _this.fixed = offset; return _this; } /** @override **/ var _proto = FixedOffsetZone.prototype; /** @override **/ _proto.offsetName = function offsetName() { return this.name; } /** @override **/ ; _proto.formatOffset = function formatOffset$1(ts, format) { return formatOffset(this.fixed, format); } /** @override **/ ; /** @override **/ _proto.offset = function offset() { return this.fixed; } /** @override **/ ; _proto.equals = function equals(otherZone) { return otherZone.type === "fixed" && otherZone.fixed === this.fixed; } /** @override **/ ; _createClass(FixedOffsetZone, [{ key: "type", get: function get() { return "fixed"; } /** @override **/ }, { key: "name", get: function get() { return this.fixed === 0 ? "UTC" : "UTC" + formatOffset(this.fixed, "narrow"); } }, { key: "universal", get: function get() { return true; } }, { key: "isValid", get: function get() { return true; } }]); return FixedOffsetZone; }(Zone); /** * A zone that failed to parse. You should never need to instantiate this. * @implements {Zone} */ var InvalidZone = /*#__PURE__*/function (_Zone) { _inheritsLoose(InvalidZone, _Zone); function InvalidZone(zoneName) { var _this; _this = _Zone.call(this) || this; /** @private */ _this.zoneName = zoneName; return _this; } /** @override **/ var _proto = InvalidZone.prototype; /** @override **/ _proto.offsetName = function offsetName() { return null; } /** @override **/ ; _proto.formatOffset = function formatOffset() { return ""; } /** @override **/ ; _proto.offset = function offset() { return NaN; } /** @override **/ ; _proto.equals = function equals() { return false; } /** @override **/ ; _createClass(InvalidZone, [{ key: "type", get: function get() { return "invalid"; } /** @override **/ }, { key: "name", get: function get() { return this.zoneName; } /** @override **/ }, { key: "universal", get: function get() { return false; } }, { key: "isValid", get: function get() { return false; } }]); return InvalidZone; }(Zone); /** * @private */ function normalizeZone(input, defaultZone) { var offset; if (isUndefined(input) || input === null) { return defaultZone; } else if (input instanceof Zone) { return input; } else if (isString(input)) { var lowered = input.toLowerCase(); if (lowered === "local") return defaultZone;else if (lowered === "utc" || lowered === "gmt") return FixedOffsetZone.utcInstance;else if ((offset = IANAZone.parseGMTOffset(input)) != null) { // handle Etc/GMT-4, which V8 chokes on return FixedOffsetZone.instance(offset); } else if (IANAZone.isValidSpecifier(lowered)) return IANAZone.create(input);else return FixedOffsetZone.parseSpecifier(lowered) || new InvalidZone(input); } else if (isNumber(input)) { return FixedOffsetZone.instance(input); } else if (typeof input === "object" && input.offset && typeof input.offset === "number") { // This is dumb, but the instanceof check above doesn't seem to really work // so we're duck checking it return input; } else { return new InvalidZone(input); } } var now = function now() { return Date.now(); }, defaultZone = null, // not setting this directly to LocalZone.instance bc loading order issues defaultLocale = null, defaultNumberingSystem = null, defaultOutputCalendar = null, throwOnInvalid = false; /** * Settings contains static getters and setters that control Luxon's overall behavior. Luxon is a simple library with few options, but the ones it does have live here. */ var Settings = /*#__PURE__*/function () { function Settings() {} /** * Reset Luxon's global caches. Should only be necessary in testing scenarios. * @return {void} */ Settings.resetCaches = function resetCaches() { Locale.resetCache(); IANAZone.resetCache(); }; _createClass(Settings, null, [{ key: "now", /** * Get the callback for returning the current timestamp. * @type {function} */ get: function get() { return now; } /** * Set the callback for returning the current timestamp. * The function should return a number, which will be interpreted as an Epoch millisecond count * @type {function} * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time */ , set: function set(n) { now = n; } /** * Get the default time zone to create DateTimes in. * @type {string} */ }, { key: "defaultZoneName", get: function get() { return Settings.defaultZone.name; } /** * Set the default time zone to create DateTimes in. Does not affect existing instances. * @type {string} */ , set: function set(z) { if (!z) { defaultZone = null; } else { defaultZone = normalizeZone(z); } } /** * Get the default time zone object to create DateTimes in. Does not affect existing instances. * @type {Zone} */ }, { key: "defaultZone", get: function get() { return defaultZone || LocalZone.instance; } /** * Get the default locale to create DateTimes with. Does not affect existing instances. * @type {string} */ }, { key: "defaultLocale", get: function get() { return defaultLocale; } /** * Set the default locale to create DateTimes with. Does not affect existing instances. * @type {string} */ , set: function set(locale) { defaultLocale = locale; } /** * Get the default numbering system to create DateTimes with. Does not affect existing instances. * @type {string} */ }, { key: "defaultNumberingSystem", get: function get() { return defaultNumberingSystem; } /** * Set the default numbering system to create DateTimes with. Does not affect existing instances. * @type {string} */ , set: function set(numberingSystem) { defaultNumberingSystem = numberingSystem; } /** * Get the default output calendar to create DateTimes with. Does not affect existing instances. * @type {string} */ }, { key: "defaultOutputCalendar", get: function get() { return defaultOutputCalendar; } /** * Set the default output calendar to create DateTimes with. Does not affect existing instances. * @type {string} */ , set: function set(outputCalendar) { defaultOutputCalendar = outputCalendar; } /** * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals * @type {boolean} */ }, { key: "throwOnInvalid", get: function get() { return throwOnInvalid; } /** * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals * @type {boolean} */ , set: function set(t) { throwOnInvalid = t; } }]); return Settings; }(); var intlDTCache = {}; function getCachedDTF(locString, opts) { if (opts === void 0) { opts = {}; } var key = JSON.stringify([locString, opts]); var dtf = intlDTCache[key]; if (!dtf) { dtf = new Intl.DateTimeFormat(locString, opts); intlDTCache[key] = dtf; } return dtf; } var intlNumCache = {}; function getCachedINF(locString, opts) { if (opts === void 0) { opts = {}; } var key = JSON.stringify([locString, opts]); var inf = intlNumCache[key]; if (!inf) { inf = new Intl.NumberFormat(locString, opts); intlNumCache[key] = inf; } return inf; } var intlRelCache = {}; function getCachedRTF(locString, opts) { if (opts === void 0) { opts = {}; } var _opts = opts, base = _opts.base, cacheKeyOpts = _objectWithoutPropertiesLoose(_opts, ["base"]); // exclude `base` from the options var key = JSON.stringify([locString, cacheKeyOpts]); var inf = intlRelCache[key]; if (!inf) { inf = new Intl.RelativeTimeFormat(locString, opts); intlRelCache[key] = inf; } return inf; } var sysLocaleCache = null; function systemLocale() { if (sysLocaleCache) { return sysLocaleCache; } else if (hasIntl()) { var computedSys = new Intl.DateTimeFormat().resolvedOptions().locale; // node sometimes defaults to "und". Override that because that is dumb sysLocaleCache = !computedSys || computedSys === "und" ? "en-US" : computedSys; return sysLocaleCache; } else { sysLocaleCache = "en-US"; return sysLocaleCache; } } function parseLocaleString(localeStr) { // I really want to avoid writing a BCP 47 parser // see, e.g. https://github.com/wooorm/bcp-47 // Instead, we'll do this: // a) if the string has no -u extensions, just leave it alone // b) if it does, use Intl to resolve everything // c) if Intl fails, try again without the -u var uIndex = localeStr.indexOf("-u-"); if (uIndex === -1) { return [localeStr]; } else { var options; var smaller = localeStr.substring(0, uIndex); try { options = getCachedDTF(localeStr).resolvedOptions(); } catch (e) { options = getCachedDTF(smaller).resolvedOptions(); } var _options = options, numberingSystem = _options.numberingSystem, calendar = _options.calendar; // return the smaller one so that we can append the calendar and numbering overrides to it return [smaller, numberingSystem, calendar]; } } function intlConfigString(localeStr, numberingSystem, outputCalendar) { if (hasIntl()) { if (outputCalendar || numberingSystem) { localeStr += "-u"; if (outputCalendar) { localeStr += "-ca-" + outputCalendar; } if (numberingSystem) { localeStr += "-nu-" + numberingSystem; } return localeStr; } else { return localeStr; } } else { return []; } } function mapMonths(f) { var ms = []; for (var i = 1; i <= 12; i++) { var dt = DateTime.utc(2016, i, 1); ms.push(f(dt)); } return ms; } function mapWeekdays(f) { var ms = []; for (var i = 1; i <= 7; i++) { var dt = DateTime.utc(2016, 11, 13 + i); ms.push(f(dt)); } return ms; } function listStuff(loc, length, defaultOK, englishFn, intlFn) { var mode = loc.listingMode(defaultOK); if (mode === "error") { return null; } else if (mode === "en") { return englishFn(length); } else { return intlFn(length); } } function supportsFastNumbers(loc) { if (loc.numberingSystem && loc.numberingSystem !== "latn") { return false; } else { return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || hasIntl() && new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === "latn"; } } /** * @private */ var PolyNumberFormatter = /*#__PURE__*/function () { function PolyNumberFormatter(intl, forceSimple, opts) { this.padTo = opts.padTo || 0; this.floor = opts.floor || false; if (!forceSimple && hasIntl()) { var intlOpts = { useGrouping: false }; if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo; this.inf = getCachedINF(intl, intlOpts); } } var _proto = PolyNumberFormatter.prototype; _proto.format = function format(i) { if (this.inf) { var fixed = this.floor ? Math.floor(i) : i; return this.inf.format(fixed); } else { // to match the browser's numberformatter defaults var _fixed = this.floor ? Math.floor(i) : roundTo(i, 3); return padStart(_fixed, this.padTo); } }; return PolyNumberFormatter; }(); /** * @private */ var PolyDateFormatter = /*#__PURE__*/function () { function PolyDateFormatter(dt, intl, opts) { this.opts = opts; this.hasIntl = hasIntl(); var z; if (dt.zone.universal && this.hasIntl) { // UTC-8 or Etc/UTC-8 are not part of tzdata, only Etc/GMT+8 and the like. // That is why fixed-offset TZ is set to that unless it is: // 1. Outside of the supported range Etc/GMT-14 to Etc/GMT+12. // 2. Not a whole hour, e.g. UTC+4:30. var gmtOffset = -1 * (dt.offset / 60); if (gmtOffset >= -14 && gmtOffset <= 12 && gmtOffset % 1 === 0) { z = gmtOffset >= 0 ? "Etc/GMT+" + gmtOffset : "Etc/GMT" + gmtOffset; this.dt = dt; } else { // Not all fixed-offset zones like Etc/+4:30 are present in tzdata. // So we have to make do. Two cases: // 1. The format options tell us to show the zone. We can't do that, so the best // we can do is format the date in UTC. // 2. The format options don't tell us to show the zone. Then we can adjust them // the time and tell the formatter to show it to us in UTC, so that the time is right // and the bad zone doesn't show up. z = "UTC"; if (opts.timeZoneName) { this.dt = dt; } else { this.dt = dt.offset === 0 ? dt : DateTime.fromMillis(dt.ts + dt.offset * 60 * 1000); } } } else if (dt.zone.type === "local") { this.dt = dt; } else { this.dt = dt; z = dt.zone.name; } if (this.hasIntl) { var intlOpts = Object.assign({}, this.opts); if (z) { intlOpts.timeZone = z; } this.dtf = getCachedDTF(intl, intlOpts); } } var _proto2 = PolyDateFormatter.prototype; _proto2.format = function format() { if (this.hasIntl) { return this.dtf.format(this.dt.toJSDate()); } else { var tokenFormat = formatString(this.opts), loc = Locale.create("en-US"); return Formatter.create(loc).formatDateTimeFromString(this.dt, tokenFormat); } }; _proto2.formatToParts = function formatToParts() { if (this.hasIntl && hasFormatToParts()) { return this.dtf.formatToParts(this.dt.toJSDate()); } else { // This is kind of a cop out. We actually could do this for English. However, we couldn't do it for intl strings // and IMO it's too weird to have an uncanny valley like that return []; } }; _proto2.resolvedOptions = function resolvedOptions() { if (this.hasIntl) { return this.dtf.resolvedOptions(); } else { return { locale: "en-US", numberingSystem: "latn", outputCalendar: "gregory" }; } }; return PolyDateFormatter; }(); /** * @private */ var PolyRelFormatter = /*#__PURE__*/function () { function PolyRelFormatter(intl, isEnglish, opts) { this.opts = Object.assign({ style: "long" }, opts); if (!isEnglish && hasRelative()) { this.rtf = getCachedRTF(intl, opts); } } var _proto3 = PolyRelFormatter.prototype; _proto3.format = function format(count, unit) { if (this.rtf) { return this.rtf.format(count, unit); } else { return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long"); } }; _proto3.formatToParts = function formatToParts(count, unit) { if (this.rtf) { return this.rtf.formatToParts(count, unit); } else { return []; } }; return PolyRelFormatter; }(); /** * @private */ var Locale = /*#__PURE__*/function () { Locale.fromOpts = function fromOpts(opts) { return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN); }; Locale.create = function create(locale, numberingSystem, outputCalendar, defaultToEN) { if (defaultToEN === void 0) { defaultToEN = false; } var specifiedLocale = locale || Settings.defaultLocale, // the system locale is useful for human readable strings but annoying for parsing/formatting known formats localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale()), numberingSystemR = numberingSystem || Settings.defaultNumberingSystem, outputCalendarR = outputCalendar || Settings.defaultOutputCalendar; return new Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale); }; Locale.resetCache = function resetCache() { sysLocaleCache = null; intlDTCache = {}; intlNumCache = {}; intlRelCache = {}; }; Locale.fromObject = function fromObject(_temp) { var _ref = _temp === void 0 ? {} : _temp, locale = _ref.locale, numberingSystem = _ref.numberingSystem, outputCalendar = _ref.outputCalendar; return Locale.create(locale, numberingSystem, outputCalendar); }; function Locale(locale, numbering, outputCalendar, specifiedLocale) { var _parseLocaleString = parseLocaleString(locale), parsedLocale = _parseLocaleString[0], parsedNumberingSystem = _parseLocaleString[1], parsedOutputCalendar = _parseLocaleString[2]; this.locale = parsedLocale; this.numberingSystem = numbering || parsedNumberingSystem || null; this.outputCalendar = outputCalendar || parsedOutputCalendar || null; this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar); this.weekdaysCache = { format: {}, standalone: {} }; this.monthsCache = { format: {}, standalone: {} }; this.meridiemCache = null; this.eraCache = {}; this.specifiedLocale = specifiedLocale; this.fastNumbersCached = null; } var _proto4 = Locale.prototype; _proto4.listingMode = function listingMode(defaultOK) { if (defaultOK === void 0) { defaultOK = true; } var intl = hasIntl(), hasFTP = intl && hasFormatToParts(), isActuallyEn = this.isEnglish(), hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory"); if (!hasFTP && !(isActuallyEn && hasNoWeirdness) && !defaultOK) { return "error"; } else if (!hasFTP || isActuallyEn && hasNoWeirdness) { return "en"; } else { return "intl"; } }; _proto4.clone = function clone(alts) { if (!alts || Object.getOwnPropertyNames(alts).length === 0) { return this; } else { return Locale.create(alts.locale || this.specifiedLocale, alts.numberingSystem || this.numberingSystem, alts.outputCalendar || this.outputCalendar, alts.defaultToEN || false); } }; _proto4.redefaultToEN = function redefaultToEN(alts) { if (alts === void 0) { alts = {}; } return this.clone(Object.assign({}, alts, { defaultToEN: true })); }; _proto4.redefaultToSystem = function redefaultToSystem(alts) { if (alts === void 0) { alts = {}; } return this.clone(Object.assign({}, alts, { defaultToEN: false })); }; _proto4.months = function months$1(length, format, defaultOK) { var _this = this; if (format === void 0) { format = false; } if (defaultOK === void 0) { defaultOK = true; } return listStuff(this, length, defaultOK, months, function () { var intl = format ? { month: length, day: "numeric" } : { month: length }, formatStr = format ? "format" : "standalone"; if (!_this.monthsCache[formatStr][length]) { _this.monthsCache[formatStr][length] = mapMonths(function (dt) { return _this.extract(dt, intl, "month"); }); } return _this.monthsCache[formatStr][length]; }); }; _proto4.weekdays = function weekdays$1(length, format, defaultOK) { var _this2 = this; if (format === void 0) { format = false; } if (defaultOK === void 0) { defaultOK = true; } return listStuff(this, length, defaultOK, weekdays, function () { var intl = format ? { weekday: length, year: "numeric", month: "long", day: "numeric" } : { weekday: length }, formatStr = format ? "format" : "standalone"; if (!_this2.weekdaysCache[formatStr][length]) { _this2.weekdaysCache[formatStr][length] = mapWeekdays(function (dt) { return _this2.extract(dt, intl, "weekday"); }); } return _this2.weekdaysCache[formatStr][length]; }); }; _proto4.meridiems = function meridiems$1(defaultOK) { var _this3 = this; if (defaultOK === void 0) { defaultOK = true; } return listStuff(this, undefined, defaultOK, function () { return meridiems; }, function () { // In theory there could be aribitrary day periods. We're gonna assume there are exactly two // for AM and PM. This is probably wrong, but it's makes parsing way easier. if (!_this3.meridiemCache) { var intl = { hour: "numeric", hour12: true }; _this3.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(function (dt) { return _this3.extract(dt, intl, "dayperiod"); }); } return _this3.meridiemCache; }); }; _proto4.eras = function eras$1(length, defaultOK) { var _this4 = this; if (defaultOK === void 0) { defaultOK = true; } return listStuff(this, length, defaultOK, eras, function () { var intl = { era: length }; // This is problematic. Different calendars are going to define eras totally differently. What I need is the minimum set of dates // to definitely enumerate them. if (!_this4.eraCache[length]) { _this4.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map(function (dt) { return _this4.extract(dt, intl, "era"); }); } return _this4.eraCache[length]; }); }; _proto4.extract = function extract(dt, intlOpts, field) { var df = this.dtFormatter(dt, intlOpts), results = df.formatToParts(), matching = results.find(function (m) { return m.type.toLowerCase() === field; }); return matching ? matching.value : null; }; _proto4.numberFormatter = function numberFormatter(opts) { if (opts === void 0) { opts = {}; } // this forcesimple option is never used (the only caller short-circuits on it, but it seems safer to leave) // (in contrast, the rest of the condition is used heavily) return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts); }; _proto4.dtFormatter = function dtFormatter(dt, intlOpts) { if (intlOpts === void 0) { intlOpts = {}; } return new PolyDateFormatter(dt, this.intl, intlOpts); }; _proto4.relFormatter = function relFormatter(opts) { if (opts === void 0) { opts = {}; } return new PolyRelFormatter(this.intl, this.isEnglish(), opts); }; _proto4.isEnglish = function isEnglish() { return this.locale === "en" || this.locale.toLowerCase() === "en-us" || hasIntl() && new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us"); }; _proto4.equals = function equals(other) { return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar; }; _createClass(Locale, [{ key: "fastNumbers", get: function get() { if (this.fastNumbersCached == null) { this.fastNumbersCached = supportsFastNumbers(this); } return this.fastNumbersCached; } }]); return Locale; }(); /* * This file handles parsing for well-specified formats. Here's how it works: * Two things go into parsing: a regex to match with and an extractor to take apart the groups in the match. * An extractor is just a function that takes a regex match array and returns a { year: ..., month: ... } object * parse() does the work of executing the regex and applying the extractor. It takes multiple regex/extractor pairs to try in sequence. * Extractors can take a "cursor" representing the offset in the match to look at. This makes it easy to combine extractors. * combineExtractors() does the work of combining them, keeping track of the cursor through multiple extractions. * Some extractions are super dumb and simpleParse and fromStrings help DRY them. */ function combineRegexes() { for (var _len = arguments.length, regexes = new Array(_len), _key = 0; _key < _len; _key++) { regexes[_key] = arguments[_key]; } var full = regexes.reduce(function (f, r) { return f + r.source; }, ""); return RegExp("^" + full + "$"); } function combineExtractors() { for (var _len2 = arguments.length, extractors = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { extractors[_key2] = arguments[_key2]; } return function (m) { return extractors.reduce(function (_ref, ex) { var mergedVals = _ref[0], mergedZone = _ref[1], cursor = _ref[2]; var _ex = ex(m, cursor), val = _ex[0], zone = _ex[1], next = _ex[2]; return [Object.assign(mergedVals, val), mergedZone || zone, next]; }, [{}, null, 1]).slice(0, 2); }; } function parse(s) { if (s == null) { return [null, null]; } for (var _len3 = arguments.length, patterns = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { patterns[_key3 - 1] = arguments[_key3]; } for (var _i = 0, _patterns = patterns; _i < _patterns.length; _i++) { var _patterns$_i = _patterns[_i], regex = _patterns$_i[0], extractor = _patterns$_i[1]; var m = regex.exec(s); if (m) { return extractor(m); } } return [null, null]; } function simpleParse() { for (var _len4 = arguments.length, keys = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { keys[_key4] = arguments[_key4]; } return function (match, cursor) { var ret = {}; var i; for (i = 0; i < keys.length; i++) { ret[keys[i]] = parseInteger(match[cursor + i]); } return [ret, null, cursor + i]; }; } // ISO and SQL parsing var offsetRegex = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/, isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/, isoTimeRegex = RegExp("" + isoTimeBaseRegex.source + offsetRegex.source + "?"), isoTimeExtensionRegex = RegExp("(?:T" + isoTimeRegex.source + ")?"), isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/, isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/, isoOrdinalRegex = /(\d{4})-?(\d{3})/, extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay"), extractISOOrdinalData = simpleParse("year", "ordinal"), sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/, // dumbed-down version of the ISO one sqlTimeRegex = RegExp(isoTimeBaseRegex.source + " ?(?:" + offsetRegex.source + "|(" + ianaRegex.source + "))?"), sqlTimeExtensionRegex = RegExp("(?: " + sqlTimeRegex.source + ")?"); function int(match, pos, fallback) { var m = match[pos]; return isUndefined(m) ? fallback : parseInteger(m); } function extractISOYmd(match, cursor) { var item = { year: int(match, cursor), month: int(match, cursor + 1, 1), day: int(match, cursor + 2, 1) }; return [item, null, cursor + 3]; } function extractISOTime(match, cursor) { var item = { hours: int(match, cursor, 0), minutes: int(match, cursor + 1, 0), seconds: int(match, cursor + 2, 0), milliseconds: parseMillis(match[cursor + 3]) }; return [item, null, cursor + 4]; } function extractISOOffset(match, cursor) { var local = !match[cursor] && !match[cursor + 1], fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]), zone = local ? null : FixedOffsetZone.instance(fullOffset); return [{}, zone, cursor + 3]; } function extractIANAZone(match, cursor) { var zone = match[cursor] ? IANAZone.create(match[cursor]) : null; return [{}, zone, cursor + 1]; } // ISO time parsing var isoTimeOnly = RegExp("^T?" + isoTimeBaseRegex.source + "$"); // ISO duration parsing var isoDuration = /^-?P(?:(?:(-?\d{1,9})Y)?(?:(-?\d{1,9})M)?(?:(-?\d{1,9})W)?(?:(-?\d{1,9})D)?(?:T(?:(-?\d{1,9})H)?(?:(-?\d{1,9})M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,9}))?S)?)?)$/; function extractISODuration(match) { var s = match[0], yearStr = match[1], monthStr = match[2], weekStr = match[3], dayStr = match[4], hourStr = match[5], minuteStr = match[6], secondStr = match[7], millisecondsStr = match[8]; var hasNegativePrefix = s[0] === "-"; var maybeNegate = function maybeNegate(num) { return num && hasNegativePrefix ? -num : num; }; return [{ years: maybeNegate(parseInteger(yearStr)), months: maybeNegate(parseInteger(monthStr)), weeks: maybeNegate(parseInteger(weekStr)), days: maybeNegate(parseInteger(dayStr)), hours: maybeNegate(parseInteger(hourStr)), minutes: maybeNegate(parseInteger(minuteStr)), seconds: maybeNegate(parseInteger(secondStr)), milliseconds: maybeNegate(parseMillis(millisecondsStr)) }]; } // These are a little braindead. EDT *should* tell us that we're in, say, America/New_York // and not just that we're in -240 *right now*. But since I don't think these are used that often // I'm just going to ignore that var obsOffsets = { GMT: 0, EDT: -4 * 60, EST: -5 * 60, CDT: -5 * 60, CST: -6 * 60, MDT: -6 * 60, MST: -7 * 60, PDT: -7 * 60, PST: -8 * 60 }; function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { var result = { year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr), month: monthsShort.indexOf(monthStr) + 1, day: parseInteger(dayStr), hour: parseInteger(hourStr), minute: parseInteger(minuteStr) }; if (secondStr) result.second = parseInteger(secondStr); if (weekdayStr) { result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1; } return result; } // RFC 2822/5322 var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/; function extractRFC2822(match) { var weekdayStr = match[1], dayStr = match[2], monthStr = match[3], yearStr = match[4], hourStr = match[5], minuteStr = match[6], secondStr = match[7], obsOffset = match[8], milOffset = match[9], offHourStr = match[10], offMinuteStr = match[11], result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); var offset; if (obsOffset) { offset = obsOffsets[obsOffset]; } else if (milOffset) { offset = 0; } else { offset = signedOffset(offHourStr, offMinuteStr); } return [result, new FixedOffsetZone(offset)]; } function preprocessRFC2822(s) { // Remove comments and folding whitespace and replace multiple-spaces with a single space return s.replace(/\([^)]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim(); } // http date var rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/, rfc850 = /^(Monday|Tuesday|Wedsday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/, ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/; function extractRFC1123Or850(match) { var weekdayStr = match[1], dayStr = match[2], monthStr = match[3], yearStr = match[4], hourStr = match[5], minuteStr = match[6], secondStr = match[7], result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); return [result, FixedOffsetZone.utcInstance]; } function extractASCII(match) { var weekdayStr = match[1], monthStr = match[2], dayStr = match[3], hourStr = match[4], minuteStr = match[5], secondStr = match[6], yearStr = match[7], result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); return [result, FixedOffsetZone.utcInstance]; } var isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex); var isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex); var isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex); var isoTimeCombinedRegex = combineRegexes(isoTimeRegex); var extractISOYmdTimeAndOffset = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset); var extractISOWeekTimeAndOffset = combineExtractors(extractISOWeekData, extractISOTime, extractISOOffset); var extractISOOrdinalDataAndTime = combineExtractors(extractISOOrdinalData, extractISOTime); var extractISOTimeAndOffset = combineExtractors(extractISOTime, extractISOOffset); /** * @private */ function parseISODate(s) { return parse(s, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDataAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset]); } function parseRFC2822Date(s) { return parse(preprocessRFC2822(s), [rfc2822, extractRFC2822]); } function parseHTTPDate(s) { return parse(s, [rfc1123, extractRFC1123Or850], [rfc850, extractRFC1123Or850], [ascii, extractASCII]); } function parseISODuration(s) { return parse(s, [isoDuration, extractISODuration]); } var extractISOTimeOnly = combineExtractors(extractISOTime); function parseISOTimeOnly(s) { return parse(s, [isoTimeOnly, extractISOTimeOnly]); } var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex); var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex); var extractISOYmdTimeOffsetAndIANAZone = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset, extractIANAZone); var extractISOTimeOffsetAndIANAZone = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone); function parseSQL(s) { return parse(s, [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeOffsetAndIANAZone], [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]); } var INVALID = "Invalid Duration"; // unit conversion constants var lowOrderMatrix = { weeks: { days: 7, hours: 7 * 24, minutes: 7 * 24 * 60, seconds: 7 * 24 * 60 * 60, milliseconds: 7 * 24 * 60 * 60 * 1000 }, days: { hours: 24, minutes: 24 * 60, seconds: 24 * 60 * 60, milliseconds: 24 * 60 * 60 * 1000 }, hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1000 }, minutes: { seconds: 60, milliseconds: 60 * 1000 }, seconds: { milliseconds: 1000 } }, casualMatrix = Object.assign({ years: { quarters: 4, months: 12, weeks: 52, days: 365, hours: 365 * 24, minutes: 365 * 24 * 60, seconds: 365 * 24 * 60 * 60, milliseconds: 365 * 24 * 60 * 60 * 1000 }, quarters: { months: 3, weeks: 13, days: 91, hours: 91 * 24, minutes: 91 * 24 * 60, seconds: 91 * 24 * 60 * 60, milliseconds: 91 * 24 * 60 * 60 * 1000 }, months: { weeks: 4, days: 30, hours: 30 * 24, minutes: 30 * 24 * 60, seconds: 30 * 24 * 60 * 60, milliseconds: 30 * 24 * 60 * 60 * 1000 } }, lowOrderMatrix), daysInYearAccurate = 146097.0 / 400, daysInMonthAccurate = 146097.0 / 4800, accurateMatrix = Object.assign({ years: { quarters: 4, months: 12, weeks: daysInYearAccurate / 7, days: daysInYearAccurate, hours: daysInYearAccurate * 24, minutes: daysInYearAccurate * 24 * 60, seconds: daysInYearAccurate * 24 * 60 * 60, milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000 }, quarters: { months: 3, weeks: daysInYearAccurate / 28, days: daysInYearAccurate / 4, hours: daysInYearAccurate * 24 / 4, minutes: daysInYearAccurate * 24 * 60 / 4, seconds: daysInYearAccurate * 24 * 60 * 60 / 4, milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000 / 4 }, months: { weeks: daysInMonthAccurate / 7, days: daysInMonthAccurate, hours: daysInMonthAccurate * 24, minutes: daysInMonthAccurate * 24 * 60, seconds: daysInMonthAccurate * 24 * 60 * 60, milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000 } }, lowOrderMatrix); // units ordered by size var orderedUnits = ["years", "quarters", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"]; var reverseUnits = orderedUnits.slice(0).reverse(); // clone really means "create another instance just like this one, but with these changes" function clone(dur, alts, clear) { if (clear === void 0) { clear = false; } // deep merge for vals var conf = { values: clear ? alts.values : Object.assign({}, dur.values, alts.values || {}), loc: dur.loc.clone(alts.loc), conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy }; return new Duration(conf); } function antiTrunc(n) { return n < 0 ? Math.floor(n) : Math.ceil(n); } // NB: mutates parameters function convert(matrix, fromMap, fromUnit, toMap, toUnit) { var conv = matrix[toUnit][fromUnit], raw = fromMap[fromUnit] / conv, sameSign = Math.sign(raw) === Math.sign(toMap[toUnit]), // ok, so this is wild, but see the matrix in the tests added = !sameSign && toMap[toUnit] !== 0 && Math.abs(raw) <= 1 ? antiTrunc(raw) : Math.trunc(raw); toMap[toUnit] += added; fromMap[fromUnit] -= added * conv; } // NB: mutates parameters function normalizeValues(matrix, vals) { reverseUnits.reduce(function (previous, current) { if (!isUndefined(vals[current])) { if (previous) { convert(matrix, vals, previous, vals, current); } return current; } else { return previous; } }, null); } /** * A Duration object represents a period of time, like "2 months" or "1 day, 1 hour". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime.plus} to add a Duration object to a DateTime, producing another DateTime. * * Here is a brief overview of commonly used methods and getters in Duration: * * * **Creation** To create a Duration, use {@link Duration.fromMillis}, {@link Duration.fromObject}, or {@link Duration.fromISO}. * * **Unit values** See the {@link Duration.years}, {@link Duration.months}, {@link Duration.weeks}, {@link Duration.days}, {@link Duration.hours}, {@link Duration.minutes}, {@link Duration.seconds}, {@link Duration.milliseconds} accessors. * * **Configuration** See {@link Duration.locale} and {@link Duration.numberingSystem} accessors. * * **Transformation** To create new Durations out of old ones use {@link Duration.plus}, {@link Duration.minus}, {@link Duration.normalize}, {@link Duration.set}, {@link Duration.reconfigure}, {@link Duration.shiftTo}, and {@link Duration.negate}. * * **Output** To convert the Duration into other representations, see {@link Duration.as}, {@link Duration.toISO}, {@link Duration.toFormat}, and {@link Duration.toJSON} * * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation. */ var Duration = /*#__PURE__*/function () { /** * @private */ function Duration(config) { var accurate = config.conversionAccuracy === "longterm" || false; /** * @access private */ this.values = config.values; /** * @access private */ this.loc = config.loc || Locale.create(); /** * @access private */ this.conversionAccuracy = accurate ? "longterm" : "casual"; /** * @access private */ this.invalid = config.invalid || null; /** * @access private */ this.matrix = accurate ? accurateMatrix : casualMatrix; /** * @access private */ this.isLuxonDuration = true; } /** * Create Duration from a number of milliseconds. * @param {number} count of milliseconds * @param {Object} opts - options for parsing * @param {string} [opts.locale='en-US'] - the locale to use * @param {string} opts.numberingSystem - the numbering system to use * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @return {Duration} */ Duration.fromMillis = function fromMillis(count, opts) { return Duration.fromObject(Object.assign({ milliseconds: count }, opts)); } /** * Create a Duration from a JavaScript object with keys like 'years' and 'hours. * If this object is empty then a zero milliseconds duration is returned. * @param {Object} obj - the object to create the DateTime from * @param {number} obj.years * @param {number} obj.quarters * @param {number} obj.months * @param {number} obj.weeks * @param {number} obj.days * @param {number} obj.hours * @param {number} obj.minutes * @param {number} obj.seconds * @param {number} obj.milliseconds * @param {string} [obj.locale='en-US'] - the locale to use * @param {string} obj.numberingSystem - the numbering system to use * @param {string} [obj.conversionAccuracy='casual'] - the conversion system to use * @return {Duration} */ ; Duration.fromObject = function fromObject(obj) { if (obj == null || typeof obj !== "object") { throw new InvalidArgumentError("Duration.fromObject: argument expected to be an object, got " + (obj === null ? "null" : typeof obj)); } return new Duration({ values: normalizeObject(obj, Duration.normalizeUnit, ["locale", "numberingSystem", "conversionAccuracy", "zone" // a bit of debt; it's super inconvenient internally not to be able to blindly pass this ]), loc: Locale.fromObject(obj), conversionAccuracy: obj.conversionAccuracy }); } /** * Create a Duration from an ISO 8601 duration string. * @param {string} text - text to parse * @param {Object} opts - options for parsing * @param {string} [opts.locale='en-US'] - the locale to use * @param {string} opts.numberingSystem - the numbering system to use * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @see https://en.wikipedia.org/wiki/ISO_8601#Durations * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 } * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 } * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 } * @return {Duration} */ ; Duration.fromISO = function fromISO(text, opts) { var _parseISODuration = parseISODuration(text), parsed = _parseISODuration[0]; if (parsed) { var obj = Object.assign(parsed, opts); return Duration.fromObject(obj); } else { return Duration.invalid("unparsable", "the input \"" + text + "\" can't be parsed as ISO 8601"); } } /** * Create a Duration from an ISO 8601 time string. * @param {string} text - text to parse * @param {Object} opts - options for parsing * @param {string} [opts.locale='en-US'] - the locale to use * @param {string} opts.numberingSystem - the numbering system to use * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @see https://en.wikipedia.org/wiki/ISO_8601#Times * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 } * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } * @return {Duration} */ ; Duration.fromISOTime = function fromISOTime(text, opts) { var _parseISOTimeOnly = parseISOTimeOnly(text), parsed = _parseISOTimeOnly[0]; if (parsed) { var obj = Object.assign(parsed, opts); return Duration.fromObject(obj); } else { return Duration.invalid("unparsable", "the input \"" + text + "\" can't be parsed as ISO 8601"); } } /** * Create an invalid Duration. * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information * @return {Duration} */ ; Duration.invalid = function invalid(reason, explanation) { if (explanation === void 0) { explanation = null; } if (!reason) { throw new InvalidArgumentError("need to specify a reason the Duration is invalid"); } var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); if (Settings.throwOnInvalid) { throw new InvalidDurationError(invalid); } else { return new Duration({ invalid: invalid }); } } /** * @private */ ; Duration.normalizeUnit = function normalizeUnit(unit) { var normalized = { year: "years", years: "years", quarter: "quarters", quarters: "quarters", month: "months", months: "months", week: "weeks", weeks: "weeks", day: "days", days: "days", hour: "hours", hours: "hours", minute: "minutes", minutes: "minutes", second: "seconds", seconds: "seconds", millisecond: "milliseconds", milliseconds: "milliseconds" }[unit ? unit.toLowerCase() : unit]; if (!normalized) throw new InvalidUnitError(unit); return normalized; } /** * Check if an object is a Duration. Works across context boundaries * @param {object} o * @return {boolean} */ ; Duration.isDuration = function isDuration(o) { return o && o.isLuxonDuration || false; } /** * Get the locale of a Duration, such 'en-GB' * @type {string} */ ; var _proto = Duration.prototype; /** * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens: * * `S` for milliseconds * * `s` for seconds * * `m` for minutes * * `h` for hours * * `d` for days * * `M` for months * * `y` for years * Notes: * * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits * * The duration will be converted to the set of units in the format string using {@link Duration.shiftTo} and the Durations's conversion accuracy setting. * @param {string} fmt - the format string * @param {Object} opts - options * @param {boolean} [opts.floor=true] - floor numerical values * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2" * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002" * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000" * @return {string} */ _proto.toFormat = function toFormat(fmt, opts) { if (opts === void 0) { opts = {}; } // reverse-compat since 1.2; we always round down now, never up, and we do it by default var fmtOpts = Object.assign({}, opts, { floor: opts.round !== false && opts.floor !== false }); return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID; } /** * Returns a JavaScript object with this Duration's values. * @param opts - options for generating the object * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 } * @return {Object} */ ; _proto.toObject = function toObject(opts) { if (opts === void 0) { opts = {}; } if (!this.isValid) return {}; var base = Object.assign({}, this.values); if (opts.includeConfig) { base.conversionAccuracy = this.conversionAccuracy; base.numberingSystem = this.loc.numberingSystem; base.locale = this.loc.locale; } return base; } /** * Returns an ISO 8601-compliant string representation of this Duration. * @see https://en.wikipedia.org/wiki/ISO_8601#Durations * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S' * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S' * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M' * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M' * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S' * @return {string} */ ; _proto.toISO = function toISO() { // we could use the formatter, but this is an easier way to get the minimum string if (!this.isValid) return null; var s = "P"; if (this.years !== 0) s += this.years + "Y"; if (this.months !== 0 || this.quarters !== 0) s += this.months + this.quarters * 3 + "M"; if (this.weeks !== 0) s += this.weeks + "W"; if (this.days !== 0) s += this.days + "D"; if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) s += "T"; if (this.hours !== 0) s += this.hours + "H"; if (this.minutes !== 0) s += this.minutes + "M"; if (this.seconds !== 0 || this.milliseconds !== 0) // this will handle "floating point madness" by removing extra decimal places // https://stackoverflow.com/questions/588004/is-floating-point-math-broken s += roundTo(this.seconds + this.milliseconds / 1000, 3) + "S"; if (s === "P") s += "T0S"; return s; } /** * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day. * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours. * @see https://en.wikipedia.org/wiki/ISO_8601#Times * @param {Object} opts - options * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 * @param {boolean} [opts.includePrefix=false] - include the `T` prefix * @param {string} [opts.format='extended'] - choose between the basic and extended format * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000' * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00' * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00' * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000' * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000' * @return {string} */ ; _proto.toISOTime = function toISOTime(opts) { if (opts === void 0) { opts = {}; } if (!this.isValid) return null; var millis = this.toMillis(); if (millis < 0 || millis >= 86400000) return null; opts = Object.assign({ suppressMilliseconds: false, suppressSeconds: false, includePrefix: false, format: "extended" }, opts); var value = this.shiftTo("hours", "minutes", "seconds", "milliseconds"); var fmt = opts.format === "basic" ? "hhmm" : "hh:mm"; if (!opts.suppressSeconds || value.seconds !== 0 || value.milliseconds !== 0) { fmt += opts.format === "basic" ? "ss" : ":ss"; if (!opts.suppressMilliseconds || value.milliseconds !== 0) { fmt += ".SSS"; } } var str = value.toFormat(fmt); if (opts.includePrefix) { str = "T" + str; } return str; } /** * Returns an ISO 8601 representation of this Duration appropriate for use in JSON. * @return {string} */ ; _proto.toJSON = function toJSON() { return this.toISO(); } /** * Returns an ISO 8601 representation of this Duration appropriate for use in debugging. * @return {string} */ ; _proto.toString = function toString() { return this.toISO(); } /** * Returns an milliseconds value of this Duration. * @return {number} */ ; _proto.toMillis = function toMillis() { return this.as("milliseconds"); } /** * Returns an milliseconds value of this Duration. Alias of {@link toMillis} * @return {number} */ ; _proto.valueOf = function valueOf() { return this.toMillis(); } /** * Make this Duration longer by the specified amount. Return a newly-constructed Duration. * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() * @return {Duration} */ ; _proto.plus = function plus(duration) { if (!this.isValid) return this; var dur = friendlyDuration(duration), result = {}; for (var _iterator = _createForOfIteratorHelperLoose(orderedUnits), _step; !(_step = _iterator()).done;) { var k = _step.value; if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) { result[k] = dur.get(k) + this.get(k); } } return clone(this, { values: result }, true); } /** * Make this Duration shorter by the specified amount. Return a newly-constructed Duration. * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() * @return {Duration} */ ; _proto.minus = function minus(duration) { if (!this.isValid) return this; var dur = friendlyDuration(duration); return this.plus(dur.negate()); } /** * Scale this Duration by the specified amount. Return a newly-constructed Duration. * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number. * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnit(x => x * 2) //=> { hours: 2, minutes: 60 } * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnit((x, u) => u === "hour" ? x * 2 : x) //=> { hours: 2, minutes: 30 } * @return {Duration} */ ; _proto.mapUnits = function mapUnits(fn) { if (!this.isValid) return this; var result = {}; for (var _i = 0, _Object$keys = Object.keys(this.values); _i < _Object$keys.length; _i++) { var k = _Object$keys[_i]; result[k] = asNumber(fn(this.values[k], k)); } return clone(this, { values: result }, true); } /** * Get the value of unit. * @param {string} unit - a unit such as 'minute' or 'day' * @example Duration.fromObject({years: 2, days: 3}).years //=> 2 * @example Duration.fromObject({years: 2, days: 3}).months //=> 0 * @example Duration.fromObject({years: 2, days: 3}).days //=> 3 * @return {number} */ ; _proto.get = function get(unit) { return this[Duration.normalizeUnit(unit)]; } /** * "Set" the values of specified units. Return a newly-constructed Duration. * @param {Object} values - a mapping of units to numbers * @example dur.set({ years: 2017 }) * @example dur.set({ hours: 8, minutes: 30 }) * @return {Duration} */ ; _proto.set = function set(values) { if (!this.isValid) return this; var mixed = Object.assign(this.values, normalizeObject(values, Duration.normalizeUnit, [])); return clone(this, { values: mixed }); } /** * "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration. * @example dur.reconfigure({ locale: 'en-GB' }) * @return {Duration} */ ; _proto.reconfigure = function reconfigure(_temp) { var _ref = _temp === void 0 ? {} : _temp, locale = _ref.locale, numberingSystem = _ref.numberingSystem, conversionAccuracy = _ref.conversionAccuracy; var loc = this.loc.clone({ locale: locale, numberingSystem: numberingSystem }), opts = { loc: loc }; if (conversionAccuracy) { opts.conversionAccuracy = conversionAccuracy; } return clone(this, opts); } /** * Return the length of the duration in the specified unit. * @param {string} unit - a unit such as 'minutes' or 'days' * @example Duration.fromObject({years: 1}).as('days') //=> 365 * @example Duration.fromObject({years: 1}).as('months') //=> 12 * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5 * @return {number} */ ; _proto.as = function as(unit) { return this.isValid ? this.shiftTo(unit).get(unit) : NaN; } /** * Reduce this Duration to its canonical representation in its current units. * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 } * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 } * @return {Duration} */ ; _proto.normalize = function normalize() { if (!this.isValid) return this; var vals = this.toObject(); normalizeValues(this.matrix, vals); return clone(this, { values: vals }, true); } /** * Convert this Duration into its representation in a different set of units. * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 } * @return {Duration} */ ; _proto.shiftTo = function shiftTo() { for (var _len = arguments.length, units = new Array(_len), _key = 0; _key < _len; _key++) { units[_key] = arguments[_key]; } if (!this.isValid) return this; if (units.length === 0) { return this; } units = units.map(function (u) { return Duration.normalizeUnit(u); }); var built = {}, accumulated = {}, vals = this.toObject(); var lastUnit; for (var _iterator2 = _createForOfIteratorHelperLoose(orderedUnits), _step2; !(_step2 = _iterator2()).done;) { var k = _step2.value; if (units.indexOf(k) >= 0) { lastUnit = k; var own = 0; // anything we haven't boiled down yet should get boiled to this unit for (var ak in accumulated) { own += this.matrix[ak][k] * accumulated[ak]; accumulated[ak] = 0; } // plus anything that's already in this unit if (isNumber(vals[k])) { own += vals[k]; } var i = Math.trunc(own); built[k] = i; accumulated[k] = own - i; // we'd like to absorb these fractions in another unit // plus anything further down the chain that should be rolled up in to this for (var down in vals) { if (orderedUnits.indexOf(down) > orderedUnits.indexOf(k)) { convert(this.matrix, vals, down, built, k); } } // otherwise, keep it in the wings to boil it later } else if (isNumber(vals[k])) { accumulated[k] = vals[k]; } } // anything leftover becomes the decimal for the last unit // lastUnit must be defined since units is not empty for (var key in accumulated) { if (accumulated[key] !== 0) { built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key]; } } return clone(this, { values: built }, true).normalize(); } /** * Return the negative of this Duration. * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 } * @return {Duration} */ ; _proto.negate = function negate() { if (!this.isValid) return this; var negated = {}; for (var _i2 = 0, _Object$keys2 = Object.keys(this.values); _i2 < _Object$keys2.length; _i2++) { var k = _Object$keys2[_i2]; negated[k] = -this.values[k]; } return clone(this, { values: negated }, true); } /** * Get the years. * @type {number} */ ; /** * Equality check * Two Durations are equal iff they have the same units and the same values for each unit. * @param {Duration} other * @return {boolean} */ _proto.equals = function equals(other) { if (!this.isValid || !other.isValid) { return false; } if (!this.loc.equals(other.loc)) { return false; } function eq(v1, v2) { // Consider 0 and undefined as equal if (v1 === undefined || v1 === 0) return v2 === undefined || v2 === 0; return v1 === v2; } for (var _iterator3 = _createForOfIteratorHelperLoose(orderedUnits), _step3; !(_step3 = _iterator3()).done;) { var u = _step3.value; if (!eq(this.values[u], other.values[u])) { return false; } } return true; }; _createClass(Duration, [{ key: "locale", get: function get() { return this.isValid ? this.loc.locale : null; } /** * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration * * @type {string} */ }, { key: "numberingSystem", get: function get() { return this.isValid ? this.loc.numberingSystem : null; } }, { key: "years", get: function get() { return this.isValid ? this.values.years || 0 : NaN; } /** * Get the quarters. * @type {number} */ }, { key: "quarters", get: function get() { return this.isValid ? this.values.quarters || 0 : NaN; } /** * Get the months. * @type {number} */ }, { key: "months", get: function get() { return this.isValid ? this.values.months || 0 : NaN; } /** * Get the weeks * @type {number} */ }, { key: "weeks", get: function get() { return this.isValid ? this.values.weeks || 0 : NaN; } /** * Get the days. * @type {number} */ }, { key: "days", get: function get() { return this.isValid ? this.values.days || 0 : NaN; } /** * Get the hours. * @type {number} */ }, { key: "hours", get: function get() { return this.isValid ? this.values.hours || 0 : NaN; } /** * Get the minutes. * @type {number} */ }, { key: "minutes", get: function get() { return this.isValid ? this.values.minutes || 0 : NaN; } /** * Get the seconds. * @return {number} */ }, { key: "seconds", get: function get() { return this.isValid ? this.values.seconds || 0 : NaN; } /** * Get the milliseconds. * @return {number} */ }, { key: "milliseconds", get: function get() { return this.isValid ? this.values.milliseconds || 0 : NaN; } /** * Returns whether the Duration is invalid. Invalid durations are returned by diff operations * on invalid DateTimes or Intervals. * @return {boolean} */ }, { key: "isValid", get: function get() { return this.invalid === null; } /** * Returns an error code if this Duration became invalid, or null if the Duration is valid * @return {string} */ }, { key: "invalidReason", get: function get() { return this.invalid ? this.invalid.reason : null; } /** * Returns an explanation of why this Duration became invalid, or null if the Duration is valid * @type {string} */ }, { key: "invalidExplanation", get: function get() { return this.invalid ? this.invalid.explanation : null; } }]); return Duration; }(); function friendlyDuration(durationish) { if (isNumber(durationish)) { return Duration.fromMillis(durationish); } else if (Duration.isDuration(durationish)) { return durationish; } else if (typeof durationish === "object") { return Duration.fromObject(durationish); } else { throw new InvalidArgumentError("Unknown duration argument " + durationish + " of type " + typeof durationish); } } var INVALID$1 = "Invalid Interval"; // checks if the start is equal to or before the end function validateStartEnd(start, end) { if (!start || !start.isValid) { return Interval.invalid("missing or invalid start"); } else if (!end || !end.isValid) { return Interval.invalid("missing or invalid end"); } else if (end < start) { return Interval.invalid("end before start", "The end of an interval must be after its start, but you had start=" + start.toISO() + " and end=" + end.toISO()); } else { return null; } } /** * An Interval object represents a half-open interval of time, where each endpoint is a {@link DateTime}. Conceptually, it's a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them. * * Here is a brief overview of the most commonly used methods and getters in Interval: * * * **Creation** To create an Interval, use {@link fromDateTimes}, {@link after}, {@link before}, or {@link fromISO}. * * **Accessors** Use {@link start} and {@link end} to get the start and end. * * **Interrogation** To analyze the Interval, use {@link count}, {@link length}, {@link hasSame}, {@link contains}, {@link isAfter}, or {@link isBefore}. * * **Transformation** To create other Intervals out of this one, use {@link set}, {@link splitAt}, {@link splitBy}, {@link divideEqually}, {@link merge}, {@link xor}, {@link union}, {@link intersection}, or {@link difference}. * * **Comparison** To compare this Interval to another one, use {@link equals}, {@link overlaps}, {@link abutsStart}, {@link abutsEnd}, {@link engulfs}. * * **Output** To convert the Interval into other representations, see {@link toString}, {@link toISO}, {@link toISODate}, {@link toISOTime}, {@link toFormat}, and {@link toDuration}. */ var Interval = /*#__PURE__*/function () { /** * @private */ function Interval(config) { /** * @access private */ this.s = config.start; /** * @access private */ this.e = config.end; /** * @access private */ this.invalid = config.invalid || null; /** * @access private */ this.isLuxonInterval = true; } /** * Create an invalid Interval. * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information * @return {Interval} */ Interval.invalid = function invalid(reason, explanation) { if (explanation === void 0) { explanation = null; } if (!reason) { throw new InvalidArgumentError("need to specify a reason the Interval is invalid"); } var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); if (Settings.throwOnInvalid) { throw new InvalidIntervalError(invalid); } else { return new Interval({ invalid: invalid }); } } /** * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end. * @param {DateTime|Date|Object} start * @param {DateTime|Date|Object} end * @return {Interval} */ ; Interval.fromDateTimes = function fromDateTimes(start, end) { var builtStart = friendlyDateTime(start), builtEnd = friendlyDateTime(end); var validateError = validateStartEnd(builtStart, builtEnd); if (validateError == null) { return new Interval({ start: builtStart, end: builtEnd }); } else { return validateError; } } /** * Create an Interval from a start DateTime and a Duration to extend to. * @param {DateTime|Date|Object} start * @param {Duration|Object|number} duration - the length of the Interval. * @return {Interval} */ ; Interval.after = function after(start, duration) { var dur = friendlyDuration(duration), dt = friendlyDateTime(start); return Interval.fromDateTimes(dt, dt.plus(dur)); } /** * Create an Interval from an end DateTime and a Duration to extend backwards to. * @param {DateTime|Date|Object} end * @param {Duration|Object|number} duration - the length of the Interval. * @return {Interval} */ ; Interval.before = function before(end, duration) { var dur = friendlyDuration(duration), dt = friendlyDateTime(end); return Interval.fromDateTimes(dt.minus(dur), dt); } /** * Create an Interval from an ISO 8601 string. * Accepts `/`, `/`, and `/` formats. * @param {string} text - the ISO string to parse * @param {Object} [opts] - options to pass {@link DateTime.fromISO} and optionally {@link Duration.fromISO} * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals * @return {Interval} */ ; Interval.fromISO = function fromISO(text, opts) { var _split = (text || "").split("/", 2), s = _split[0], e = _split[1]; if (s && e) { var start, startIsValid; try { start = DateTime.fromISO(s, opts); startIsValid = start.isValid; } catch (e) { startIsValid = false; } var end, endIsValid; try { end = DateTime.fromISO(e, opts); endIsValid = end.isValid; } catch (e) { endIsValid = false; } if (startIsValid && endIsValid) { return Interval.fromDateTimes(start, end); } if (startIsValid) { var dur = Duration.fromISO(e, opts); if (dur.isValid) { return Interval.after(start, dur); } } else if (endIsValid) { var _dur = Duration.fromISO(s, opts); if (_dur.isValid) { return Interval.before(end, _dur); } } } return Interval.invalid("unparsable", "the input \"" + text + "\" can't be parsed as ISO 8601"); } /** * Check if an object is an Interval. Works across context boundaries * @param {object} o * @return {boolean} */ ; Interval.isInterval = function isInterval(o) { return o && o.isLuxonInterval || false; } /** * Returns the start of the Interval * @type {DateTime} */ ; var _proto = Interval.prototype; /** * Returns the length of the Interval in the specified unit. * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in. * @return {number} */ _proto.length = function length(unit) { if (unit === void 0) { unit = "milliseconds"; } return this.isValid ? this.toDuration.apply(this, [unit]).get(unit) : NaN; } /** * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part. * Unlike {@link length} this counts sections of the calendar, not periods of time, e.g. specifying 'day' * asks 'what dates are included in this interval?', not 'how many days long is this interval?' * @param {string} [unit='milliseconds'] - the unit of time to count. * @return {number} */ ; _proto.count = function count(unit) { if (unit === void 0) { unit = "milliseconds"; } if (!this.isValid) return NaN; var start = this.start.startOf(unit), end = this.end.startOf(unit); return Math.floor(end.diff(start, unit).get(unit)) + 1; } /** * Returns whether this Interval's start and end are both in the same unit of time * @param {string} unit - the unit of time to check sameness on * @return {boolean} */ ; _proto.hasSame = function hasSame(unit) { return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false; } /** * Return whether this Interval has the same start and end DateTimes. * @return {boolean} */ ; _proto.isEmpty = function isEmpty() { return this.s.valueOf() === this.e.valueOf(); } /** * Return whether this Interval's start is after the specified DateTime. * @param {DateTime} dateTime * @return {boolean} */ ; _proto.isAfter = function isAfter(dateTime) { if (!this.isValid) return false; return this.s > dateTime; } /** * Return whether this Interval's end is before the specified DateTime. * @param {DateTime} dateTime * @return {boolean} */ ; _proto.isBefore = function isBefore(dateTime) { if (!this.isValid) return false; return this.e <= dateTime; } /** * Return whether this Interval contains the specified DateTime. * @param {DateTime} dateTime * @return {boolean} */ ; _proto.contains = function contains(dateTime) { if (!this.isValid) return false; return this.s <= dateTime && this.e > dateTime; } /** * "Sets" the start and/or end dates. Returns a newly-constructed Interval. * @param {Object} values - the values to set * @param {DateTime} values.start - the starting DateTime * @param {DateTime} values.end - the ending DateTime * @return {Interval} */ ; _proto.set = function set(_temp) { var _ref = _temp === void 0 ? {} : _temp, start = _ref.start, end = _ref.end; if (!this.isValid) return this; return Interval.fromDateTimes(start || this.s, end || this.e); } /** * Split this Interval at each of the specified DateTimes * @param {...[DateTime]} dateTimes - the unit of time to count. * @return {[Interval]} */ ; _proto.splitAt = function splitAt() { var _this = this; if (!this.isValid) return []; for (var _len = arguments.length, dateTimes = new Array(_len), _key = 0; _key < _len; _key++) { dateTimes[_key] = arguments[_key]; } var sorted = dateTimes.map(friendlyDateTime).filter(function (d) { return _this.contains(d); }).sort(), results = []; var s = this.s, i = 0; while (s < this.e) { var added = sorted[i] || this.e, next = +added > +this.e ? this.e : added; results.push(Interval.fromDateTimes(s, next)); s = next; i += 1; } return results; } /** * Split this Interval into smaller Intervals, each of the specified length. * Left over time is grouped into a smaller interval * @param {Duration|Object|number} duration - The length of each resulting interval. * @return {[Interval]} */ ; _proto.splitBy = function splitBy(duration) { var dur = friendlyDuration(duration); if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) { return []; } var s = this.s, added, next; var results = []; while (s < this.e) { added = s.plus(dur); next = +added > +this.e ? this.e : added; results.push(Interval.fromDateTimes(s, next)); s = next; } return results; } /** * Split this Interval into the specified number of smaller intervals. * @param {number} numberOfParts - The number of Intervals to divide the Interval into. * @return {[Interval]} */ ; _proto.divideEqually = function divideEqually(numberOfParts) { if (!this.isValid) return []; return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts); } /** * Return whether this Interval overlaps with the specified Interval * @param {Interval} other * @return {boolean} */ ; _proto.overlaps = function overlaps(other) { return this.e > other.s && this.s < other.e; } /** * Return whether this Interval's end is adjacent to the specified Interval's start. * @param {Interval} other * @return {boolean} */ ; _proto.abutsStart = function abutsStart(other) { if (!this.isValid) return false; return +this.e === +other.s; } /** * Return whether this Interval's start is adjacent to the specified Interval's end. * @param {Interval} other * @return {boolean} */ ; _proto.abutsEnd = function abutsEnd(other) { if (!this.isValid) return false; return +other.e === +this.s; } /** * Return whether this Interval engulfs the start and end of the specified Interval. * @param {Interval} other * @return {boolean} */ ; _proto.engulfs = function engulfs(other) { if (!this.isValid) return false; return this.s <= other.s && this.e >= other.e; } /** * Return whether this Interval has the same start and end as the specified Interval. * @param {Interval} other * @return {boolean} */ ; _proto.equals = function equals(other) { if (!this.isValid || !other.isValid) { return false; } return this.s.equals(other.s) && this.e.equals(other.e); } /** * Return an Interval representing the intersection of this Interval and the specified Interval. * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals. * Returns null if the intersection is empty, meaning, the intervals don't intersect. * @param {Interval} other * @return {Interval} */ ; _proto.intersection = function intersection(other) { if (!this.isValid) return this; var s = this.s > other.s ? this.s : other.s, e = this.e < other.e ? this.e : other.e; if (s > e) { return null; } else { return Interval.fromDateTimes(s, e); } } /** * Return an Interval representing the union of this Interval and the specified Interval. * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals. * @param {Interval} other * @return {Interval} */ ; _proto.union = function union(other) { if (!this.isValid) return this; var s = this.s < other.s ? this.s : other.s, e = this.e > other.e ? this.e : other.e; return Interval.fromDateTimes(s, e); } /** * Merge an array of Intervals into a equivalent minimal set of Intervals. * Combines overlapping and adjacent Intervals. * @param {[Interval]} intervals * @return {[Interval]} */ ; Interval.merge = function merge(intervals) { var _intervals$sort$reduc = intervals.sort(function (a, b) { return a.s - b.s; }).reduce(function (_ref2, item) { var sofar = _ref2[0], current = _ref2[1]; if (!current) { return [sofar, item]; } else if (current.overlaps(item) || current.abutsStart(item)) { return [sofar, current.union(item)]; } else { return [sofar.concat([current]), item]; } }, [[], null]), found = _intervals$sort$reduc[0], final = _intervals$sort$reduc[1]; if (final) { found.push(final); } return found; } /** * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals. * @param {[Interval]} intervals * @return {[Interval]} */ ; Interval.xor = function xor(intervals) { var _Array$prototype; var start = null, currentCount = 0; var results = [], ends = intervals.map(function (i) { return [{ time: i.s, type: "s" }, { time: i.e, type: "e" }]; }), flattened = (_Array$prototype = Array.prototype).concat.apply(_Array$prototype, ends), arr = flattened.sort(function (a, b) { return a.time - b.time; }); for (var _iterator = _createForOfIteratorHelperLoose(arr), _step; !(_step = _iterator()).done;) { var i = _step.value; currentCount += i.type === "s" ? 1 : -1; if (currentCount === 1) { start = i.time; } else { if (start && +start !== +i.time) { results.push(Interval.fromDateTimes(start, i.time)); } start = null; } } return Interval.merge(results); } /** * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals. * @param {...Interval} intervals * @return {[Interval]} */ ; _proto.difference = function difference() { var _this2 = this; for (var _len2 = arguments.length, intervals = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { intervals[_key2] = arguments[_key2]; } return Interval.xor([this].concat(intervals)).map(function (i) { return _this2.intersection(i); }).filter(function (i) { return i && !i.isEmpty(); }); } /** * Returns a string representation of this Interval appropriate for debugging. * @return {string} */ ; _proto.toString = function toString() { if (!this.isValid) return INVALID$1; return "[" + this.s.toISO() + " \u2013 " + this.e.toISO() + ")"; } /** * Returns an ISO 8601-compliant string representation of this Interval. * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals * @param {Object} opts - The same options as {@link DateTime.toISO} * @return {string} */ ; _proto.toISO = function toISO(opts) { if (!this.isValid) return INVALID$1; return this.s.toISO(opts) + "/" + this.e.toISO(opts); } /** * Returns an ISO 8601-compliant string representation of date of this Interval. * The time components are ignored. * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals * @return {string} */ ; _proto.toISODate = function toISODate() { if (!this.isValid) return INVALID$1; return this.s.toISODate() + "/" + this.e.toISODate(); } /** * Returns an ISO 8601-compliant string representation of time of this Interval. * The date components are ignored. * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals * @param {Object} opts - The same options as {@link DateTime.toISO} * @return {string} */ ; _proto.toISOTime = function toISOTime(opts) { if (!this.isValid) return INVALID$1; return this.s.toISOTime(opts) + "/" + this.e.toISOTime(opts); } /** * Returns a string representation of this Interval formatted according to the specified format string. * @param {string} dateFormat - the format string. This string formats the start and end time. See {@link DateTime.toFormat} for details. * @param {Object} opts - options * @param {string} [opts.separator = ' – '] - a separator to place between the start and end representations * @return {string} */ ; _proto.toFormat = function toFormat(dateFormat, _temp2) { var _ref3 = _temp2 === void 0 ? {} : _temp2, _ref3$separator = _ref3.separator, separator = _ref3$separator === void 0 ? " – " : _ref3$separator; if (!this.isValid) return INVALID$1; return "" + this.s.toFormat(dateFormat) + separator + this.e.toFormat(dateFormat); } /** * Return a Duration representing the time spanned by this interval. * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration. * @param {Object} opts - options that affect the creation of the Duration * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 } * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 } * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 } * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 } * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 } * @return {Duration} */ ; _proto.toDuration = function toDuration(unit, opts) { if (!this.isValid) { return Duration.invalid(this.invalidReason); } return this.e.diff(this.s, unit, opts); } /** * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes * @param {function} mapFn * @return {Interval} * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC()) * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 })) */ ; _proto.mapEndpoints = function mapEndpoints(mapFn) { return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e)); }; _createClass(Interval, [{ key: "start", get: function get() { return this.isValid ? this.s : null; } /** * Returns the end of the Interval * @type {DateTime} */ }, { key: "end", get: function get() { return this.isValid ? this.e : null; } /** * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'. * @type {boolean} */ }, { key: "isValid", get: function get() { return this.invalidReason === null; } /** * Returns an error code if this Interval is invalid, or null if the Interval is valid * @type {string} */ }, { key: "invalidReason", get: function get() { return this.invalid ? this.invalid.reason : null; } /** * Returns an explanation of why this Interval became invalid, or null if the Interval is valid * @type {string} */ }, { key: "invalidExplanation", get: function get() { return this.invalid ? this.invalid.explanation : null; } }]); return Interval; }(); /** * The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment. */ var Info = /*#__PURE__*/function () { function Info() {} /** * Return whether the specified zone contains a DST. * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone. * @return {boolean} */ Info.hasDST = function hasDST(zone) { if (zone === void 0) { zone = Settings.defaultZone; } var proto = DateTime.now().setZone(zone).set({ month: 12 }); return !zone.universal && proto.offset !== proto.set({ month: 6 }).offset; } /** * Return whether the specified zone is a valid IANA specifier. * @param {string} zone - Zone to check * @return {boolean} */ ; Info.isValidIANAZone = function isValidIANAZone(zone) { return IANAZone.isValidSpecifier(zone) && IANAZone.isValidZone(zone); } /** * Converts the input into a {@link Zone} instance. * * * If `input` is already a Zone instance, it is returned unchanged. * * If `input` is a string containing a valid time zone name, a Zone instance * with that name is returned. * * If `input` is a string that doesn't refer to a known time zone, a Zone * instance with {@link Zone.isValid} == false is returned. * * If `input is a number, a Zone instance with the specified fixed offset * in minutes is returned. * * If `input` is `null` or `undefined`, the default zone is returned. * @param {string|Zone|number} [input] - the value to be converted * @return {Zone} */ ; Info.normalizeZone = function normalizeZone$1(input) { return normalizeZone(input, Settings.defaultZone); } /** * Return an array of standalone month names. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @param {string} [opts.outputCalendar='gregory'] - the calendar * @example Info.months()[0] //=> 'January' * @example Info.months('short')[0] //=> 'Jan' * @example Info.months('numeric')[0] //=> '1' * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.' * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١' * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I' * @return {[string]} */ ; Info.months = function months(length, _temp) { if (length === void 0) { length = "long"; } var _ref = _temp === void 0 ? {} : _temp, _ref$locale = _ref.locale, locale = _ref$locale === void 0 ? null : _ref$locale, _ref$numberingSystem = _ref.numberingSystem, numberingSystem = _ref$numberingSystem === void 0 ? null : _ref$numberingSystem, _ref$outputCalendar = _ref.outputCalendar, outputCalendar = _ref$outputCalendar === void 0 ? "gregory" : _ref$outputCalendar; return Locale.create(locale, numberingSystem, outputCalendar).months(length); } /** * Return an array of format month names. * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that * changes the string. * See {@link months} * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @param {string} [opts.outputCalendar='gregory'] - the calendar * @return {[string]} */ ; Info.monthsFormat = function monthsFormat(length, _temp2) { if (length === void 0) { length = "long"; } var _ref2 = _temp2 === void 0 ? {} : _temp2, _ref2$locale = _ref2.locale, locale = _ref2$locale === void 0 ? null : _ref2$locale, _ref2$numberingSystem = _ref2.numberingSystem, numberingSystem = _ref2$numberingSystem === void 0 ? null : _ref2$numberingSystem, _ref2$outputCalendar = _ref2.outputCalendar, outputCalendar = _ref2$outputCalendar === void 0 ? "gregory" : _ref2$outputCalendar; return Locale.create(locale, numberingSystem, outputCalendar).months(length, true); } /** * Return an array of standalone week names. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long". * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @example Info.weekdays()[0] //=> 'Monday' * @example Info.weekdays('short')[0] //=> 'Mon' * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.' * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين' * @return {[string]} */ ; Info.weekdays = function weekdays(length, _temp3) { if (length === void 0) { length = "long"; } var _ref3 = _temp3 === void 0 ? {} : _temp3, _ref3$locale = _ref3.locale, locale = _ref3$locale === void 0 ? null : _ref3$locale, _ref3$numberingSystem = _ref3.numberingSystem, numberingSystem = _ref3$numberingSystem === void 0 ? null : _ref3$numberingSystem; return Locale.create(locale, numberingSystem, null).weekdays(length); } /** * Return an array of format week names. * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that * changes the string. * See {@link weekdays} * @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long". * @param {Object} opts - options * @param {string} [opts.locale=null] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @return {[string]} */ ; Info.weekdaysFormat = function weekdaysFormat(length, _temp4) { if (length === void 0) { length = "long"; } var _ref4 = _temp4 === void 0 ? {} : _temp4, _ref4$locale = _ref4.locale, locale = _ref4$locale === void 0 ? null : _ref4$locale, _ref4$numberingSystem = _ref4.numberingSystem, numberingSystem = _ref4$numberingSystem === void 0 ? null : _ref4$numberingSystem; return Locale.create(locale, numberingSystem, null).weekdays(length, true); } /** * Return an array of meridiems. * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @example Info.meridiems() //=> [ 'AM', 'PM' ] * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ] * @return {[string]} */ ; Info.meridiems = function meridiems(_temp5) { var _ref5 = _temp5 === void 0 ? {} : _temp5, _ref5$locale = _ref5.locale, locale = _ref5$locale === void 0 ? null : _ref5$locale; return Locale.create(locale).meridiems(); } /** * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian. * @param {string} [length='short'] - the length of the era representation, such as "short" or "long". * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @example Info.eras() //=> [ 'BC', 'AD' ] * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ] * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ] * @return {[string]} */ ; Info.eras = function eras(length, _temp6) { if (length === void 0) { length = "short"; } var _ref6 = _temp6 === void 0 ? {} : _temp6, _ref6$locale = _ref6.locale, locale = _ref6$locale === void 0 ? null : _ref6$locale; return Locale.create(locale, null, "gregory").eras(length); } /** * Return the set of available features in this environment. * Some features of Luxon are not available in all environments. For example, on older browsers, timezone support is not available. Use this function to figure out if that's the case. * Keys: * * `zones`: whether this environment supports IANA timezones * * `intlTokens`: whether this environment supports internationalized token-based formatting/parsing * * `intl`: whether this environment supports general internationalization * * `relative`: whether this environment supports relative time formatting * @example Info.features() //=> { intl: true, intlTokens: false, zones: true, relative: false } * @return {Object} */ ; Info.features = function features() { var intl = false, intlTokens = false, zones = false, relative = false; if (hasIntl()) { intl = true; intlTokens = hasFormatToParts(); relative = hasRelative(); try { zones = new Intl.DateTimeFormat("en", { timeZone: "America/New_York" }).resolvedOptions().timeZone === "America/New_York"; } catch (e) { zones = false; } } return { intl: intl, intlTokens: intlTokens, zones: zones, relative: relative }; }; return Info; }(); function dayDiff(earlier, later) { var utcDayStart = function utcDayStart(dt) { return dt.toUTC(0, { keepLocalTime: true }).startOf("day").valueOf(); }, ms = utcDayStart(later) - utcDayStart(earlier); return Math.floor(Duration.fromMillis(ms).as("days")); } function highOrderDiffs(cursor, later, units) { var differs = [["years", function (a, b) { return b.year - a.year; }], ["quarters", function (a, b) { return b.quarter - a.quarter; }], ["months", function (a, b) { return b.month - a.month + (b.year - a.year) * 12; }], ["weeks", function (a, b) { var days = dayDiff(a, b); return (days - days % 7) / 7; }], ["days", dayDiff]]; var results = {}; var lowestOrder, highWater; for (var _i = 0, _differs = differs; _i < _differs.length; _i++) { var _differs$_i = _differs[_i], unit = _differs$_i[0], differ = _differs$_i[1]; if (units.indexOf(unit) >= 0) { var _cursor$plus; lowestOrder = unit; var delta = differ(cursor, later); highWater = cursor.plus((_cursor$plus = {}, _cursor$plus[unit] = delta, _cursor$plus)); if (highWater > later) { var _cursor$plus2; cursor = cursor.plus((_cursor$plus2 = {}, _cursor$plus2[unit] = delta - 1, _cursor$plus2)); delta -= 1; } else { cursor = highWater; } results[unit] = delta; } } return [cursor, results, highWater, lowestOrder]; } function _diff (earlier, later, units, opts) { var _highOrderDiffs = highOrderDiffs(earlier, later, units), cursor = _highOrderDiffs[0], results = _highOrderDiffs[1], highWater = _highOrderDiffs[2], lowestOrder = _highOrderDiffs[3]; var remainingMillis = later - cursor; var lowerOrderUnits = units.filter(function (u) { return ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0; }); if (lowerOrderUnits.length === 0) { if (highWater < later) { var _cursor$plus3; highWater = cursor.plus((_cursor$plus3 = {}, _cursor$plus3[lowestOrder] = 1, _cursor$plus3)); } if (highWater !== cursor) { results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor); } } var duration = Duration.fromObject(Object.assign(results, opts)); if (lowerOrderUnits.length > 0) { var _Duration$fromMillis; return (_Duration$fromMillis = Duration.fromMillis(remainingMillis, opts)).shiftTo.apply(_Duration$fromMillis, lowerOrderUnits).plus(duration); } else { return duration; } } var numberingSystems = { arab: "[\u0660-\u0669]", arabext: "[\u06F0-\u06F9]", bali: "[\u1B50-\u1B59]", beng: "[\u09E6-\u09EF]", deva: "[\u0966-\u096F]", fullwide: "[\uFF10-\uFF19]", gujr: "[\u0AE6-\u0AEF]", hanidec: "[〇|一|二|三|四|五|六|七|八|九]", khmr: "[\u17E0-\u17E9]", knda: "[\u0CE6-\u0CEF]", laoo: "[\u0ED0-\u0ED9]", limb: "[\u1946-\u194F]", mlym: "[\u0D66-\u0D6F]", mong: "[\u1810-\u1819]", mymr: "[\u1040-\u1049]", orya: "[\u0B66-\u0B6F]", tamldec: "[\u0BE6-\u0BEF]", telu: "[\u0C66-\u0C6F]", thai: "[\u0E50-\u0E59]", tibt: "[\u0F20-\u0F29]", latn: "\\d" }; var numberingSystemsUTF16 = { arab: [1632, 1641], arabext: [1776, 1785], bali: [6992, 7001], beng: [2534, 2543], deva: [2406, 2415], fullwide: [65296, 65303], gujr: [2790, 2799], khmr: [6112, 6121], knda: [3302, 3311], laoo: [3792, 3801], limb: [6470, 6479], mlym: [3430, 3439], mong: [6160, 6169], mymr: [4160, 4169], orya: [2918, 2927], tamldec: [3046, 3055], telu: [3174, 3183], thai: [3664, 3673], tibt: [3872, 3881] }; // eslint-disable-next-line var hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split(""); function parseDigits(str) { var value = parseInt(str, 10); if (isNaN(value)) { value = ""; for (var i = 0; i < str.length; i++) { var code = str.charCodeAt(i); if (str[i].search(numberingSystems.hanidec) !== -1) { value += hanidecChars.indexOf(str[i]); } else { for (var key in numberingSystemsUTF16) { var _numberingSystemsUTF = numberingSystemsUTF16[key], min = _numberingSystemsUTF[0], max = _numberingSystemsUTF[1]; if (code >= min && code <= max) { value += code - min; } } } } return parseInt(value, 10); } else { return value; } } function digitRegex(_ref, append) { var numberingSystem = _ref.numberingSystem; if (append === void 0) { append = ""; } return new RegExp("" + numberingSystems[numberingSystem || "latn"] + append); } var MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support"; function intUnit(regex, post) { if (post === void 0) { post = function post(i) { return i; }; } return { regex: regex, deser: function deser(_ref) { var s = _ref[0]; return post(parseDigits(s)); } }; } var NBSP = String.fromCharCode(160); var spaceOrNBSP = "( |" + NBSP + ")"; var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g"); function fixListRegex(s) { // make dots optional and also make them literal // make space and non breakable space characters interchangeable return s.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP); } function stripInsensitivities(s) { return s.replace(/\./g, "") // ignore dots that were made optional .replace(spaceOrNBSPRegExp, " ") // interchange space and nbsp .toLowerCase(); } function oneOf(strings, startIndex) { if (strings === null) { return null; } else { return { regex: RegExp(strings.map(fixListRegex).join("|")), deser: function deser(_ref2) { var s = _ref2[0]; return strings.findIndex(function (i) { return stripInsensitivities(s) === stripInsensitivities(i); }) + startIndex; } }; } } function offset(regex, groups) { return { regex: regex, deser: function deser(_ref3) { var h = _ref3[1], m = _ref3[2]; return signedOffset(h, m); }, groups: groups }; } function simple(regex) { return { regex: regex, deser: function deser(_ref4) { var s = _ref4[0]; return s; } }; } function escapeToken(value) { // eslint-disable-next-line no-useless-escape return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); } function unitForToken(token, loc) { var one = digitRegex(loc), two = digitRegex(loc, "{2}"), three = digitRegex(loc, "{3}"), four = digitRegex(loc, "{4}"), six = digitRegex(loc, "{6}"), oneOrTwo = digitRegex(loc, "{1,2}"), oneToThree = digitRegex(loc, "{1,3}"), oneToSix = digitRegex(loc, "{1,6}"), oneToNine = digitRegex(loc, "{1,9}"), twoToFour = digitRegex(loc, "{2,4}"), fourToSix = digitRegex(loc, "{4,6}"), literal = function literal(t) { return { regex: RegExp(escapeToken(t.val)), deser: function deser(_ref5) { var s = _ref5[0]; return s; }, literal: true }; }, unitate = function unitate(t) { if (token.literal) { return literal(t); } switch (t.val) { // era case "G": return oneOf(loc.eras("short", false), 0); case "GG": return oneOf(loc.eras("long", false), 0); // years case "y": return intUnit(oneToSix); case "yy": return intUnit(twoToFour, untruncateYear); case "yyyy": return intUnit(four); case "yyyyy": return intUnit(fourToSix); case "yyyyyy": return intUnit(six); // months case "M": return intUnit(oneOrTwo); case "MM": return intUnit(two); case "MMM": return oneOf(loc.months("short", true, false), 1); case "MMMM": return oneOf(loc.months("long", true, false), 1); case "L": return intUnit(oneOrTwo); case "LL": return intUnit(two); case "LLL": return oneOf(loc.months("short", false, false), 1); case "LLLL": return oneOf(loc.months("long", false, false), 1); // dates case "d": return intUnit(oneOrTwo); case "dd": return intUnit(two); // ordinals case "o": return intUnit(oneToThree); case "ooo": return intUnit(three); // time case "HH": return intUnit(two); case "H": return intUnit(oneOrTwo); case "hh": return intUnit(two); case "h": return intUnit(oneOrTwo); case "mm": return intUnit(two); case "m": return intUnit(oneOrTwo); case "q": return intUnit(oneOrTwo); case "qq": return intUnit(two); case "s": return intUnit(oneOrTwo); case "ss": return intUnit(two); case "S": return intUnit(oneToThree); case "SSS": return intUnit(three); case "u": return simple(oneToNine); // meridiem case "a": return oneOf(loc.meridiems(), 0); // weekYear (k) case "kkkk": return intUnit(four); case "kk": return intUnit(twoToFour, untruncateYear); // weekNumber (W) case "W": return intUnit(oneOrTwo); case "WW": return intUnit(two); // weekdays case "E": case "c": return intUnit(one); case "EEE": return oneOf(loc.weekdays("short", false, false), 1); case "EEEE": return oneOf(loc.weekdays("long", false, false), 1); case "ccc": return oneOf(loc.weekdays("short", true, false), 1); case "cccc": return oneOf(loc.weekdays("long", true, false), 1); // offset/zone case "Z": case "ZZ": return offset(new RegExp("([+-]" + oneOrTwo.source + ")(?::(" + two.source + "))?"), 2); case "ZZZ": return offset(new RegExp("([+-]" + oneOrTwo.source + ")(" + two.source + ")?"), 2); // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing // because we don't have any way to figure out what they are case "z": return simple(/[a-z_+-/]{1,256}?/i); default: return literal(t); } }; var unit = unitate(token) || { invalidReason: MISSING_FTP }; unit.token = token; return unit; } var partTypeStyleToTokenVal = { year: { "2-digit": "yy", numeric: "yyyyy" }, month: { numeric: "M", "2-digit": "MM", short: "MMM", long: "MMMM" }, day: { numeric: "d", "2-digit": "dd" }, weekday: { short: "EEE", long: "EEEE" }, dayperiod: "a", dayPeriod: "a", hour: { numeric: "h", "2-digit": "hh" }, minute: { numeric: "m", "2-digit": "mm" }, second: { numeric: "s", "2-digit": "ss" } }; function tokenForPart(part, locale, formatOpts) { var type = part.type, value = part.value; if (type === "literal") { return { literal: true, val: value }; } var style = formatOpts[type]; var val = partTypeStyleToTokenVal[type]; if (typeof val === "object") { val = val[style]; } if (val) { return { literal: false, val: val }; } return undefined; } function buildRegex(units) { var re = units.map(function (u) { return u.regex; }).reduce(function (f, r) { return f + "(" + r.source + ")"; }, ""); return ["^" + re + "$", units]; } function match(input, regex, handlers) { var matches = input.match(regex); if (matches) { var all = {}; var matchIndex = 1; for (var i in handlers) { if (hasOwnProperty(handlers, i)) { var h = handlers[i], groups = h.groups ? h.groups + 1 : 1; if (!h.literal && h.token) { all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups)); } matchIndex += groups; } } return [matches, all]; } else { return [matches, {}]; } } function dateTimeFromMatches(matches) { var toField = function toField(token) { switch (token) { case "S": return "millisecond"; case "s": return "second"; case "m": return "minute"; case "h": case "H": return "hour"; case "d": return "day"; case "o": return "ordinal"; case "L": case "M": return "month"; case "y": return "year"; case "E": case "c": return "weekday"; case "W": return "weekNumber"; case "k": return "weekYear"; case "q": return "quarter"; default: return null; } }; var zone; if (!isUndefined(matches.Z)) { zone = new FixedOffsetZone(matches.Z); } else if (!isUndefined(matches.z)) { zone = IANAZone.create(matches.z); } else { zone = null; } if (!isUndefined(matches.q)) { matches.M = (matches.q - 1) * 3 + 1; } if (!isUndefined(matches.h)) { if (matches.h < 12 && matches.a === 1) { matches.h += 12; } else if (matches.h === 12 && matches.a === 0) { matches.h = 0; } } if (matches.G === 0 && matches.y) { matches.y = -matches.y; } if (!isUndefined(matches.u)) { matches.S = parseMillis(matches.u); } var vals = Object.keys(matches).reduce(function (r, k) { var f = toField(k); if (f) { r[f] = matches[k]; } return r; }, {}); return [vals, zone]; } var dummyDateTimeCache = null; function getDummyDateTime() { if (!dummyDateTimeCache) { dummyDateTimeCache = DateTime.fromMillis(1555555555555); } return dummyDateTimeCache; } function maybeExpandMacroToken(token, locale) { if (token.literal) { return token; } var formatOpts = Formatter.macroTokenToFormatOpts(token.val); if (!formatOpts) { return token; } var formatter = Formatter.create(locale, formatOpts); var parts = formatter.formatDateTimeParts(getDummyDateTime()); var tokens = parts.map(function (p) { return tokenForPart(p, locale, formatOpts); }); if (tokens.includes(undefined)) { return token; } return tokens; } function expandMacroTokens(tokens, locale) { var _Array$prototype; return (_Array$prototype = Array.prototype).concat.apply(_Array$prototype, tokens.map(function (t) { return maybeExpandMacroToken(t, locale); })); } /** * @private */ function explainFromTokens(locale, input, format) { var tokens = expandMacroTokens(Formatter.parseFormat(format), locale), units = tokens.map(function (t) { return unitForToken(t, locale); }), disqualifyingUnit = units.find(function (t) { return t.invalidReason; }); if (disqualifyingUnit) { return { input: input, tokens: tokens, invalidReason: disqualifyingUnit.invalidReason }; } else { var _buildRegex = buildRegex(units), regexString = _buildRegex[0], handlers = _buildRegex[1], regex = RegExp(regexString, "i"), _match = match(input, regex, handlers), rawMatches = _match[0], matches = _match[1], _ref6 = matches ? dateTimeFromMatches(matches) : [null, null], result = _ref6[0], zone = _ref6[1]; if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) { throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format"); } return { input: input, tokens: tokens, regex: regex, rawMatches: rawMatches, matches: matches, result: result, zone: zone }; } } function parseFromTokens(locale, input, format) { var _explainFromTokens = explainFromTokens(locale, input, format), result = _explainFromTokens.result, zone = _explainFromTokens.zone, invalidReason = _explainFromTokens.invalidReason; return [result, zone, invalidReason]; } var nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]; function unitOutOfRange(unit, value) { return new Invalid("unit out of range", "you specified " + value + " (of type " + typeof value + ") as a " + unit + ", which is invalid"); } function dayOfWeek(year, month, day) { var js = new Date(Date.UTC(year, month - 1, day)).getUTCDay(); return js === 0 ? 7 : js; } function computeOrdinal(year, month, day) { return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1]; } function uncomputeOrdinal(year, ordinal) { var table = isLeapYear(year) ? leapLadder : nonLeapLadder, month0 = table.findIndex(function (i) { return i < ordinal; }), day = ordinal - table[month0]; return { month: month0 + 1, day: day }; } /** * @private */ function gregorianToWeek(gregObj) { var year = gregObj.year, month = gregObj.month, day = gregObj.day, ordinal = computeOrdinal(year, month, day), weekday = dayOfWeek(year, month, day); var weekNumber = Math.floor((ordinal - weekday + 10) / 7), weekYear; if (weekNumber < 1) { weekYear = year - 1; weekNumber = weeksInWeekYear(weekYear); } else if (weekNumber > weeksInWeekYear(year)) { weekYear = year + 1; weekNumber = 1; } else { weekYear = year; } return Object.assign({ weekYear: weekYear, weekNumber: weekNumber, weekday: weekday }, timeObject(gregObj)); } function weekToGregorian(weekData) { var weekYear = weekData.weekYear, weekNumber = weekData.weekNumber, weekday = weekData.weekday, weekdayOfJan4 = dayOfWeek(weekYear, 1, 4), yearInDays = daysInYear(weekYear); var ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 3, year; if (ordinal < 1) { year = weekYear - 1; ordinal += daysInYear(year); } else if (ordinal > yearInDays) { year = weekYear + 1; ordinal -= daysInYear(weekYear); } else { year = weekYear; } var _uncomputeOrdinal = uncomputeOrdinal(year, ordinal), month = _uncomputeOrdinal.month, day = _uncomputeOrdinal.day; return Object.assign({ year: year, month: month, day: day }, timeObject(weekData)); } function gregorianToOrdinal(gregData) { var year = gregData.year, month = gregData.month, day = gregData.day, ordinal = computeOrdinal(year, month, day); return Object.assign({ year: year, ordinal: ordinal }, timeObject(gregData)); } function ordinalToGregorian(ordinalData) { var year = ordinalData.year, ordinal = ordinalData.ordinal, _uncomputeOrdinal2 = uncomputeOrdinal(year, ordinal), month = _uncomputeOrdinal2.month, day = _uncomputeOrdinal2.day; return Object.assign({ year: year, month: month, day: day }, timeObject(ordinalData)); } function hasInvalidWeekData(obj) { var validYear = isInteger(obj.weekYear), validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear)), validWeekday = integerBetween(obj.weekday, 1, 7); if (!validYear) { return unitOutOfRange("weekYear", obj.weekYear); } else if (!validWeek) { return unitOutOfRange("week", obj.week); } else if (!validWeekday) { return unitOutOfRange("weekday", obj.weekday); } else return false; } function hasInvalidOrdinalData(obj) { var validYear = isInteger(obj.year), validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year)); if (!validYear) { return unitOutOfRange("year", obj.year); } else if (!validOrdinal) { return unitOutOfRange("ordinal", obj.ordinal); } else return false; } function hasInvalidGregorianData(obj) { var validYear = isInteger(obj.year), validMonth = integerBetween(obj.month, 1, 12), validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month)); if (!validYear) { return unitOutOfRange("year", obj.year); } else if (!validMonth) { return unitOutOfRange("month", obj.month); } else if (!validDay) { return unitOutOfRange("day", obj.day); } else return false; } function hasInvalidTimeData(obj) { var hour = obj.hour, minute = obj.minute, second = obj.second, millisecond = obj.millisecond; var validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0, validMinute = integerBetween(minute, 0, 59), validSecond = integerBetween(second, 0, 59), validMillisecond = integerBetween(millisecond, 0, 999); if (!validHour) { return unitOutOfRange("hour", hour); } else if (!validMinute) { return unitOutOfRange("minute", minute); } else if (!validSecond) { return unitOutOfRange("second", second); } else if (!validMillisecond) { return unitOutOfRange("millisecond", millisecond); } else return false; } var INVALID$2 = "Invalid DateTime"; var MAX_DATE = 8.64e15; function unsupportedZone(zone) { return new Invalid("unsupported zone", "the zone \"" + zone.name + "\" is not supported"); } // we cache week data on the DT object and this intermediates the cache function possiblyCachedWeekData(dt) { if (dt.weekData === null) { dt.weekData = gregorianToWeek(dt.c); } return dt.weekData; } // clone really means, "make a new object with these modifications". all "setters" really use this // to create a new object while only changing some of the properties function clone$1(inst, alts) { var current = { ts: inst.ts, zone: inst.zone, c: inst.c, o: inst.o, loc: inst.loc, invalid: inst.invalid }; return new DateTime(Object.assign({}, current, alts, { old: current })); } // find the right offset a given local time. The o input is our guess, which determines which // offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST) function fixOffset(localTS, o, tz) { // Our UTC time is just a guess because our offset is just a guess var utcGuess = localTS - o * 60 * 1000; // Test whether the zone matches the offset for this ts var o2 = tz.offset(utcGuess); // If so, offset didn't change and we're done if (o === o2) { return [utcGuess, o]; } // If not, change the ts by the difference in the offset utcGuess -= (o2 - o) * 60 * 1000; // If that gives us the local time we want, we're done var o3 = tz.offset(utcGuess); if (o2 === o3) { return [utcGuess, o2]; } // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)]; } // convert an epoch timestamp into a calendar object with the given offset function tsToObj(ts, offset) { ts += offset * 60 * 1000; var d = new Date(ts); return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, day: d.getUTCDate(), hour: d.getUTCHours(), minute: d.getUTCMinutes(), second: d.getUTCSeconds(), millisecond: d.getUTCMilliseconds() }; } // convert a calendar object to a epoch timestamp function objToTS(obj, offset, zone) { return fixOffset(objToLocalTS(obj), offset, zone); } // create a new DT instance by adding a duration, adjusting for DSTs function adjustTime(inst, dur) { var oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c = Object.assign({}, inst.c, { year: year, month: month, day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7 }), millisToAdd = Duration.fromObject({ years: dur.years - Math.trunc(dur.years), quarters: dur.quarters - Math.trunc(dur.quarters), months: dur.months - Math.trunc(dur.months), weeks: dur.weeks - Math.trunc(dur.weeks), days: dur.days - Math.trunc(dur.days), hours: dur.hours, minutes: dur.minutes, seconds: dur.seconds, milliseconds: dur.milliseconds }).as("milliseconds"), localTS = objToLocalTS(c); var _fixOffset = fixOffset(localTS, oPre, inst.zone), ts = _fixOffset[0], o = _fixOffset[1]; if (millisToAdd !== 0) { ts += millisToAdd; // that could have changed the offset by going over a DST, but we want to keep the ts the same o = inst.zone.offset(ts); } return { ts: ts, o: o }; } // helper useful in turning the results of parsing into real dates // by handling the zone options function parseDataToDateTime(parsed, parsedZone, opts, format, text) { var setZone = opts.setZone, zone = opts.zone; if (parsed && Object.keys(parsed).length !== 0) { var interpretationZone = parsedZone || zone, inst = DateTime.fromObject(Object.assign(parsed, opts, { zone: interpretationZone, // setZone is a valid option in the calling methods, but not in fromObject setZone: undefined })); return setZone ? inst : inst.setZone(zone); } else { return DateTime.invalid(new Invalid("unparsable", "the input \"" + text + "\" can't be parsed as " + format)); } } // if you want to output a technical format (e.g. RFC 2822), this helper // helps handle the details function toTechFormat(dt, format, allowZ) { if (allowZ === void 0) { allowZ = true; } return dt.isValid ? Formatter.create(Locale.create("en-US"), { allowZ: allowZ, forceSimple: true }).formatDateTimeFromString(dt, format) : null; } // technical time formats (e.g. the time part of ISO 8601), take some options // and this commonizes their handling function toTechTimeFormat(dt, _ref) { var _ref$suppressSeconds = _ref.suppressSeconds, suppressSeconds = _ref$suppressSeconds === void 0 ? false : _ref$suppressSeconds, _ref$suppressMillisec = _ref.suppressMilliseconds, suppressMilliseconds = _ref$suppressMillisec === void 0 ? false : _ref$suppressMillisec, includeOffset = _ref.includeOffset, _ref$includePrefix = _ref.includePrefix, includePrefix = _ref$includePrefix === void 0 ? false : _ref$includePrefix, _ref$includeZone = _ref.includeZone, includeZone = _ref$includeZone === void 0 ? false : _ref$includeZone, _ref$spaceZone = _ref.spaceZone, spaceZone = _ref$spaceZone === void 0 ? false : _ref$spaceZone, _ref$format = _ref.format, format = _ref$format === void 0 ? "extended" : _ref$format; var fmt = format === "basic" ? "HHmm" : "HH:mm"; if (!suppressSeconds || dt.second !== 0 || dt.millisecond !== 0) { fmt += format === "basic" ? "ss" : ":ss"; if (!suppressMilliseconds || dt.millisecond !== 0) { fmt += ".SSS"; } } if ((includeZone || includeOffset) && spaceZone) { fmt += " "; } if (includeZone) { fmt += "z"; } else if (includeOffset) { fmt += format === "basic" ? "ZZZ" : "ZZ"; } var str = toTechFormat(dt, fmt); if (includePrefix) { str = "T" + str; } return str; } // defaults for unspecified units in the supported calendars var defaultUnitValues = { month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }, defaultWeekUnitValues = { weekNumber: 1, weekday: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }, defaultOrdinalUnitValues = { ordinal: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }; // Units in the supported calendars, sorted by bigness var orderedUnits$1 = ["year", "month", "day", "hour", "minute", "second", "millisecond"], orderedWeekUnits = ["weekYear", "weekNumber", "weekday", "hour", "minute", "second", "millisecond"], orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; // standardize case and plurality in units function normalizeUnit(unit) { var normalized = { year: "year", years: "year", month: "month", months: "month", day: "day", days: "day", hour: "hour", hours: "hour", minute: "minute", minutes: "minute", quarter: "quarter", quarters: "quarter", second: "second", seconds: "second", millisecond: "millisecond", milliseconds: "millisecond", weekday: "weekday", weekdays: "weekday", weeknumber: "weekNumber", weeksnumber: "weekNumber", weeknumbers: "weekNumber", weekyear: "weekYear", weekyears: "weekYear", ordinal: "ordinal" }[unit.toLowerCase()]; if (!normalized) throw new InvalidUnitError(unit); return normalized; } // this is a dumbed down version of fromObject() that runs about 60% faster // but doesn't do any validation, makes a bunch of assumptions about what units // are present, and so on. function quickDT(obj, zone) { // assume we have the higher-order units for (var _iterator = _createForOfIteratorHelperLoose(orderedUnits$1), _step; !(_step = _iterator()).done;) { var u = _step.value; if (isUndefined(obj[u])) { obj[u] = defaultUnitValues[u]; } } var invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj); if (invalid) { return DateTime.invalid(invalid); } var tsNow = Settings.now(), offsetProvis = zone.offset(tsNow), _objToTS = objToTS(obj, offsetProvis, zone), ts = _objToTS[0], o = _objToTS[1]; return new DateTime({ ts: ts, zone: zone, o: o }); } function diffRelative(start, end, opts) { var round = isUndefined(opts.round) ? true : opts.round, format = function format(c, unit) { c = roundTo(c, round || opts.calendary ? 0 : 2, true); var formatter = end.loc.clone(opts).relFormatter(opts); return formatter.format(c, unit); }, differ = function differ(unit) { if (opts.calendary) { if (!end.hasSame(start, unit)) { return end.startOf(unit).diff(start.startOf(unit), unit).get(unit); } else return 0; } else { return end.diff(start, unit).get(unit); } }; if (opts.unit) { return format(differ(opts.unit), opts.unit); } for (var _iterator2 = _createForOfIteratorHelperLoose(opts.units), _step2; !(_step2 = _iterator2()).done;) { var unit = _step2.value; var count = differ(unit); if (Math.abs(count) >= 1) { return format(count, unit); } } return format(0, opts.units[opts.units.length - 1]); } /** * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them. * * A DateTime comprises of: * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch. * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone). * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`. * * Here is a brief overview of the most commonly used functionality it provides: * * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link local}, {@link utc}, and (most flexibly) {@link fromObject}. To create one from a standard string format, use {@link fromISO}, {@link fromHTTP}, and {@link fromRFC2822}. To create one from a custom string format, use {@link fromFormat}. To create one from a native JS date, use {@link fromJSDate}. * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link toObject}), use the {@link year}, {@link month}, * {@link day}, {@link hour}, {@link minute}, {@link second}, {@link millisecond} accessors. * * **Week calendar**: For ISO week calendar attributes, see the {@link weekYear}, {@link weekNumber}, and {@link weekday} accessors. * * **Configuration** See the {@link locale} and {@link numberingSystem} accessors. * * **Transformation**: To transform the DateTime into other DateTimes, use {@link set}, {@link reconfigure}, {@link setZone}, {@link setLocale}, {@link plus}, {@link minus}, {@link endOf}, {@link startOf}, {@link toUTC}, and {@link toLocal}. * * **Output**: To convert the DateTime to other representations, use the {@link toRelative}, {@link toRelativeCalendar}, {@link toJSON}, {@link toISO}, {@link toHTTP}, {@link toObject}, {@link toRFC2822}, {@link toString}, {@link toLocaleString}, {@link toFormat}, {@link toMillis} and {@link toJSDate}. * * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation. */ var DateTime = /*#__PURE__*/function () { /** * @access private */ function DateTime(config) { var zone = config.zone || Settings.defaultZone; var invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null); /** * @access private */ this.ts = isUndefined(config.ts) ? Settings.now() : config.ts; var c = null, o = null; if (!invalid) { var unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); if (unchanged) { var _ref2 = [config.old.c, config.old.o]; c = _ref2[0]; o = _ref2[1]; } else { var ot = zone.offset(this.ts); c = tsToObj(this.ts, ot); invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null; c = invalid ? null : c; o = invalid ? null : ot; } } /** * @access private */ this._zone = zone; /** * @access private */ this.loc = config.loc || Locale.create(); /** * @access private */ this.invalid = invalid; /** * @access private */ this.weekData = null; /** * @access private */ this.c = c; /** * @access private */ this.o = o; /** * @access private */ this.isLuxonDateTime = true; } // CONSTRUCT /** * Create a DateTime for the current instant, in the system's time zone. * * Use Settings to override these default values if needed. * @example DateTime.now().toISO() //~> now in the ISO format * @return {DateTime} */ DateTime.now = function now() { return new DateTime({}); } /** * Create a local DateTime * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used * @param {number} [month=1] - The month, 1-indexed * @param {number} [day=1] - The day of the month, 1-indexed * @param {number} [hour=0] - The hour of the day, in 24-hour time * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59 * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59 * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999 * @example DateTime.local() //~> now * @example DateTime.local(2017) //~> 2017-01-01T00:00:00 * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00 * @example DateTime.local(2017, 3, 12) //~> 2017-03-12T00:00:00 * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00 * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00 * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10 * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765 * @return {DateTime} */ ; DateTime.local = function local(year, month, day, hour, minute, second, millisecond) { if (isUndefined(year)) { return new DateTime({}); } else { return quickDT({ year: year, month: month, day: day, hour: hour, minute: minute, second: second, millisecond: millisecond }, Settings.defaultZone); } } /** * Create a DateTime in UTC * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used * @param {number} [month=1] - The month, 1-indexed * @param {number} [day=1] - The day of the month * @param {number} [hour=0] - The hour of the day, in 24-hour time * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59 * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59 * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999 * @example DateTime.utc() //~> now * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765Z * @return {DateTime} */ ; DateTime.utc = function utc(year, month, day, hour, minute, second, millisecond) { if (isUndefined(year)) { return new DateTime({ ts: Settings.now(), zone: FixedOffsetZone.utcInstance }); } else { return quickDT({ year: year, month: month, day: day, hour: hour, minute: minute, second: second, millisecond: millisecond }, FixedOffsetZone.utcInstance); } } /** * Create a DateTime from a JavaScript Date object. Uses the default zone. * @param {Date} date - a JavaScript Date object * @param {Object} options - configuration options for the DateTime * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into * @return {DateTime} */ ; DateTime.fromJSDate = function fromJSDate(date, options) { if (options === void 0) { options = {}; } var ts = isDate(date) ? date.valueOf() : NaN; if (Number.isNaN(ts)) { return DateTime.invalid("invalid input"); } var zoneToUse = normalizeZone(options.zone, Settings.defaultZone); if (!zoneToUse.isValid) { return DateTime.invalid(unsupportedZone(zoneToUse)); } return new DateTime({ ts: ts, zone: zoneToUse, loc: Locale.fromObject(options) }); } /** * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone. * @param {number} milliseconds - a number of milliseconds since 1970 UTC * @param {Object} options - configuration options for the DateTime * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into * @param {string} [options.locale] - a locale to set on the resulting DateTime instance * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance * @return {DateTime} */ ; DateTime.fromMillis = function fromMillis(milliseconds, options) { if (options === void 0) { options = {}; } if (!isNumber(milliseconds)) { throw new InvalidArgumentError("fromMillis requires a numerical input, but received a " + typeof milliseconds + " with value " + milliseconds); } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) { // this isn't perfect because because we can still end up out of range because of additional shifting, but it's a start return DateTime.invalid("Timestamp out of range"); } else { return new DateTime({ ts: milliseconds, zone: normalizeZone(options.zone, Settings.defaultZone), loc: Locale.fromObject(options) }); } } /** * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone. * @param {number} seconds - a number of seconds since 1970 UTC * @param {Object} options - configuration options for the DateTime * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into * @param {string} [options.locale] - a locale to set on the resulting DateTime instance * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance * @return {DateTime} */ ; DateTime.fromSeconds = function fromSeconds(seconds, options) { if (options === void 0) { options = {}; } if (!isNumber(seconds)) { throw new InvalidArgumentError("fromSeconds requires a numerical input"); } else { return new DateTime({ ts: seconds * 1000, zone: normalizeZone(options.zone, Settings.defaultZone), loc: Locale.fromObject(options) }); } } /** * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults. * @param {Object} obj - the object to create the DateTime from * @param {number} obj.year - a year, such as 1987 * @param {number} obj.month - a month, 1-12 * @param {number} obj.day - a day of the month, 1-31, depending on the month * @param {number} obj.ordinal - day of the year, 1-365 or 366 * @param {number} obj.weekYear - an ISO week year * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday * @param {number} obj.hour - hour of the day, 0-23 * @param {number} obj.minute - minute of the hour, 0-59 * @param {number} obj.second - second of the minute, 0-59 * @param {number} obj.millisecond - millisecond of the second, 0-999 * @param {string|Zone} [obj.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone() * @param {string} [obj.locale='system's locale'] - a locale to set on the resulting DateTime instance * @param {string} obj.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} obj.numberingSystem - the numbering system to set on the resulting DateTime instance * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25' * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01' * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06 * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'utc' }), * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'local' }) * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'America/New_York' }) * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13' * @return {DateTime} */ ; DateTime.fromObject = function fromObject(obj) { var zoneToUse = normalizeZone(obj.zone, Settings.defaultZone); if (!zoneToUse.isValid) { return DateTime.invalid(unsupportedZone(zoneToUse)); } var tsNow = Settings.now(), offsetProvis = zoneToUse.offset(tsNow), normalized = normalizeObject(obj, normalizeUnit, ["zone", "locale", "outputCalendar", "numberingSystem"]), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber, loc = Locale.fromObject(obj); // cases: // just a weekday -> this week's instance of that weekday, no worries // (gregorian data or ordinal) + (weekYear or weekNumber) -> error // (gregorian month or day) + ordinal -> error // otherwise just use weeks or ordinals or gregorian, depending on what's specified if ((containsGregor || containsOrdinal) && definiteWeekDef) { throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals"); } if (containsGregorMD && containsOrdinal) { throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); } var useWeekData = definiteWeekDef || normalized.weekday && !containsGregor; // configure ourselves to deal with gregorian dates or week stuff var units, defaultValues, objNow = tsToObj(tsNow, offsetProvis); if (useWeekData) { units = orderedWeekUnits; defaultValues = defaultWeekUnitValues; objNow = gregorianToWeek(objNow); } else if (containsOrdinal) { units = orderedOrdinalUnits; defaultValues = defaultOrdinalUnitValues; objNow = gregorianToOrdinal(objNow); } else { units = orderedUnits$1; defaultValues = defaultUnitValues; } // set default values for missing stuff var foundFirst = false; for (var _iterator3 = _createForOfIteratorHelperLoose(units), _step3; !(_step3 = _iterator3()).done;) { var u = _step3.value; var v = normalized[u]; if (!isUndefined(v)) { foundFirst = true; } else if (foundFirst) { normalized[u] = defaultValues[u]; } else { normalized[u] = objNow[u]; } } // make sure the values we have are in range var higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid = higherOrderInvalid || hasInvalidTimeData(normalized); if (invalid) { return DateTime.invalid(invalid); } // compute the actual time var gregorian = useWeekData ? weekToGregorian(normalized) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, _objToTS2 = objToTS(gregorian, offsetProvis, zoneToUse), tsFinal = _objToTS2[0], offsetFinal = _objToTS2[1], inst = new DateTime({ ts: tsFinal, zone: zoneToUse, o: offsetFinal, loc: loc }); // gregorian data + weekday serves only to validate if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) { return DateTime.invalid("mismatched weekday", "you can't specify both a weekday of " + normalized.weekday + " and a date of " + inst.toISO()); } return inst; } /** * Create a DateTime from an ISO 8601 string * @param {string} text - the ISO string * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance * @example DateTime.fromISO('2016-05-25T09:08:34.123') * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00') * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true}) * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'}) * @example DateTime.fromISO('2016-W05-4') * @return {DateTime} */ ; DateTime.fromISO = function fromISO(text, opts) { if (opts === void 0) { opts = {}; } var _parseISODate = parseISODate(text), vals = _parseISODate[0], parsedZone = _parseISODate[1]; return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text); } /** * Create a DateTime from an RFC 2822 string * @param {string} text - the RFC 2822 string * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT') * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600') * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z') * @return {DateTime} */ ; DateTime.fromRFC2822 = function fromRFC2822(text, opts) { if (opts === void 0) { opts = {}; } var _parseRFC2822Date = parseRFC2822Date(text), vals = _parseRFC2822Date[0], parsedZone = _parseRFC2822Date[1]; return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text); } /** * Create a DateTime from an HTTP header date * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 * @param {string} text - the HTTP header date * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods. * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT') * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT') * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994') * @return {DateTime} */ ; DateTime.fromHTTP = function fromHTTP(text, opts) { if (opts === void 0) { opts = {}; } var _parseHTTPDate = parseHTTPDate(text), vals = _parseHTTPDate[0], parsedZone = _parseHTTPDate[1]; return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts); } /** * Create a DateTime from an input string and format string. * Defaults to en-US if no locale has been specified, regardless of the system's locale. * @see https://moment.github.io/luxon/docs/manual/parsing.html#table-of-tokens * @param {string} text - the string to parse * @param {string} fmt - the format the string is expected to be in (see the link below for the formats) * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @return {DateTime} */ ; DateTime.fromFormat = function fromFormat(text, fmt, opts) { if (opts === void 0) { opts = {}; } if (isUndefined(text) || isUndefined(fmt)) { throw new InvalidArgumentError("fromFormat requires an input string and a format"); } var _opts = opts, _opts$locale = _opts.locale, locale = _opts$locale === void 0 ? null : _opts$locale, _opts$numberingSystem = _opts.numberingSystem, numberingSystem = _opts$numberingSystem === void 0 ? null : _opts$numberingSystem, localeToUse = Locale.fromOpts({ locale: locale, numberingSystem: numberingSystem, defaultToEN: true }), _parseFromTokens = parseFromTokens(localeToUse, text, fmt), vals = _parseFromTokens[0], parsedZone = _parseFromTokens[1], invalid = _parseFromTokens[2]; if (invalid) { return DateTime.invalid(invalid); } else { return parseDataToDateTime(vals, parsedZone, opts, "format " + fmt, text); } } /** * @deprecated use fromFormat instead */ ; DateTime.fromString = function fromString(text, fmt, opts) { if (opts === void 0) { opts = {}; } return DateTime.fromFormat(text, fmt, opts); } /** * Create a DateTime from a SQL date, time, or datetime * Defaults to en-US if no locale has been specified, regardless of the system's locale * @param {string} text - the string to parse * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @example DateTime.fromSQL('2017-05-15') * @example DateTime.fromSQL('2017-05-15 09:12:34') * @example DateTime.fromSQL('2017-05-15 09:12:34.342') * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00') * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles') * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true }) * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' }) * @example DateTime.fromSQL('09:12:34.342') * @return {DateTime} */ ; DateTime.fromSQL = function fromSQL(text, opts) { if (opts === void 0) { opts = {}; } var _parseSQL = parseSQL(text), vals = _parseSQL[0], parsedZone = _parseSQL[1]; return parseDataToDateTime(vals, parsedZone, opts, "SQL", text); } /** * Create an invalid DateTime. * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information * @return {DateTime} */ ; DateTime.invalid = function invalid(reason, explanation) { if (explanation === void 0) { explanation = null; } if (!reason) { throw new InvalidArgumentError("need to specify a reason the DateTime is invalid"); } var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); if (Settings.throwOnInvalid) { throw new InvalidDateTimeError(invalid); } else { return new DateTime({ invalid: invalid }); } } /** * Check if an object is a DateTime. Works across context boundaries * @param {object} o * @return {boolean} */ ; DateTime.isDateTime = function isDateTime(o) { return o && o.isLuxonDateTime || false; } // INFO /** * Get the value of unit. * @param {string} unit - a unit such as 'minute' or 'day' * @example DateTime.local(2017, 7, 4).get('month'); //=> 7 * @example DateTime.local(2017, 7, 4).get('day'); //=> 4 * @return {number} */ ; var _proto = DateTime.prototype; _proto.get = function get(unit) { return this[unit]; } /** * Returns whether the DateTime is valid. Invalid DateTimes occur when: * * The DateTime was created from invalid calendar information, such as the 13th month or February 30 * * The DateTime was created by an operation on another invalid date * @type {boolean} */ ; /** * Returns the resolved Intl options for this DateTime. * This is useful in understanding the behavior of formatting methods * @param {Object} opts - the same options as toLocaleString * @return {Object} */ _proto.resolvedLocaleOpts = function resolvedLocaleOpts(opts) { if (opts === void 0) { opts = {}; } var _Formatter$create$res = Formatter.create(this.loc.clone(opts), opts).resolvedOptions(this), locale = _Formatter$create$res.locale, numberingSystem = _Formatter$create$res.numberingSystem, calendar = _Formatter$create$res.calendar; return { locale: locale, numberingSystem: numberingSystem, outputCalendar: calendar }; } // TRANSFORM /** * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime. * * Equivalent to {@link setZone}('utc') * @param {number} [offset=0] - optionally, an offset from UTC in minutes * @param {Object} [opts={}] - options to pass to `setZone()` * @return {DateTime} */ ; _proto.toUTC = function toUTC(offset, opts) { if (offset === void 0) { offset = 0; } if (opts === void 0) { opts = {}; } return this.setZone(FixedOffsetZone.instance(offset), opts); } /** * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime. * * Equivalent to `setZone('local')` * @return {DateTime} */ ; _proto.toLocal = function toLocal() { return this.setZone(Settings.defaultZone); } /** * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime. * * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link plus}. You may wish to use {@link toLocal} and {@link toUTC} which provide simple convenience wrappers for commonly used zones. * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link Zone} class. * @param {Object} opts - options * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this. * @return {DateTime} */ ; _proto.setZone = function setZone(zone, _temp) { var _ref3 = _temp === void 0 ? {} : _temp, _ref3$keepLocalTime = _ref3.keepLocalTime, keepLocalTime = _ref3$keepLocalTime === void 0 ? false : _ref3$keepLocalTime, _ref3$keepCalendarTim = _ref3.keepCalendarTime, keepCalendarTime = _ref3$keepCalendarTim === void 0 ? false : _ref3$keepCalendarTim; zone = normalizeZone(zone, Settings.defaultZone); if (zone.equals(this.zone)) { return this; } else if (!zone.isValid) { return DateTime.invalid(unsupportedZone(zone)); } else { var newTS = this.ts; if (keepLocalTime || keepCalendarTime) { var offsetGuess = zone.offset(this.ts); var asObj = this.toObject(); var _objToTS3 = objToTS(asObj, offsetGuess, zone); newTS = _objToTS3[0]; } return clone$1(this, { ts: newTS, zone: zone }); } } /** * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime. * @param {Object} properties - the properties to set * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' }) * @return {DateTime} */ ; _proto.reconfigure = function reconfigure(_temp2) { var _ref4 = _temp2 === void 0 ? {} : _temp2, locale = _ref4.locale, numberingSystem = _ref4.numberingSystem, outputCalendar = _ref4.outputCalendar; var loc = this.loc.clone({ locale: locale, numberingSystem: numberingSystem, outputCalendar: outputCalendar }); return clone$1(this, { loc: loc }); } /** * "Set" the locale. Returns a newly-constructed DateTime. * Just a convenient alias for reconfigure({ locale }) * @example DateTime.local(2017, 5, 25).setLocale('en-GB') * @return {DateTime} */ ; _proto.setLocale = function setLocale(locale) { return this.reconfigure({ locale: locale }); } /** * "Set" the values of specified units. Returns a newly-constructed DateTime. * You can only set units with this method; for "setting" metadata, see {@link reconfigure} and {@link setZone}. * @param {Object} values - a mapping of units to numbers * @example dt.set({ year: 2017 }) * @example dt.set({ hour: 8, minute: 30 }) * @example dt.set({ weekday: 5 }) * @example dt.set({ year: 2005, ordinal: 234 }) * @return {DateTime} */ ; _proto.set = function set(values) { if (!this.isValid) return this; var normalized = normalizeObject(values, normalizeUnit, []), settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday); var mixed; if (settingWeekStuff) { mixed = weekToGregorian(Object.assign(gregorianToWeek(this.c), normalized)); } else if (!isUndefined(normalized.ordinal)) { mixed = ordinalToGregorian(Object.assign(gregorianToOrdinal(this.c), normalized)); } else { mixed = Object.assign(this.toObject(), normalized); // if we didn't set the day but we ended up on an overflow date, // use the last day of the right month if (isUndefined(normalized.day)) { mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day); } } var _objToTS4 = objToTS(mixed, this.o, this.zone), ts = _objToTS4[0], o = _objToTS4[1]; return clone$1(this, { ts: ts, o: o }); } /** * Add a period of time to this DateTime and return the resulting DateTime * * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between. * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() * @example DateTime.now().plus(123) //~> in 123 milliseconds * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min * @return {DateTime} */ ; _proto.plus = function plus(duration) { if (!this.isValid) return this; var dur = friendlyDuration(duration); return clone$1(this, adjustTime(this, dur)); } /** * Subtract a period of time to this DateTime and return the resulting DateTime * See {@link plus} * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() @return {DateTime} */ ; _proto.minus = function minus(duration) { if (!this.isValid) return this; var dur = friendlyDuration(duration).negate(); return clone$1(this, adjustTime(this, dur)); } /** * "Set" this DateTime to the beginning of a unit of time. * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01' * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01' * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00' * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00' * @return {DateTime} */ ; _proto.startOf = function startOf(unit) { if (!this.isValid) return this; var o = {}, normalizedUnit = Duration.normalizeUnit(unit); switch (normalizedUnit) { case "years": o.month = 1; // falls through case "quarters": case "months": o.day = 1; // falls through case "weeks": case "days": o.hour = 0; // falls through case "hours": o.minute = 0; // falls through case "minutes": o.second = 0; // falls through case "seconds": o.millisecond = 0; break; // no default, invalid units throw in normalizeUnit() } if (normalizedUnit === "weeks") { o.weekday = 1; } if (normalizedUnit === "quarters") { var q = Math.ceil(this.month / 3); o.month = (q - 1) * 3 + 1; } return this.set(o); } /** * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00' * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00' * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00' * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00' * @return {DateTime} */ ; _proto.endOf = function endOf(unit) { var _this$plus; return this.isValid ? this.plus((_this$plus = {}, _this$plus[unit] = 1, _this$plus)).startOf(unit).minus(1) : this; } // OUTPUT /** * Returns a string representation of this DateTime formatted according to the specified format string. * **You may not want this.** See {@link toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens). * Defaults to en-US if no locale has been specified, regardless of the system's locale. * @see https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens * @param {string} fmt - the format string * @param {Object} opts - opts to override the configuration options * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22' * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22' * @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22' * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes' * @return {string} */ ; _proto.toFormat = function toFormat(fmt, opts) { if (opts === void 0) { opts = {}; } return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID$2; } /** * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`. * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation * of the DateTime in the assigned locale. * Defaults to the system's locale if no locale has been specified * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param opts {Object} - Intl.DateTimeFormat constructor options and configuration options * @example DateTime.now().toLocaleString(); //=> 4/20/2017 * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017' * @example DateTime.now().toLocaleString({ locale: 'en-gb' }); //=> '20/04/2017' * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017' * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM' * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM' * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20' * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM' * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hour12: false }); //=> '11:32' * @return {string} */ ; _proto.toLocaleString = function toLocaleString(opts) { if (opts === void 0) { opts = DATE_SHORT; } return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTime(this) : INVALID$2; } /** * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output. * Defaults to the system's locale if no locale has been specified * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`. * @example DateTime.now().toLocaleParts(); //=> [ * //=> { type: 'day', value: '25' }, * //=> { type: 'literal', value: '/' }, * //=> { type: 'month', value: '05' }, * //=> { type: 'literal', value: '/' }, * //=> { type: 'year', value: '1982' } * //=> ] */ ; _proto.toLocaleParts = function toLocaleParts(opts) { if (opts === void 0) { opts = {}; } return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : []; } /** * Returns an ISO 8601-compliant string representation of this DateTime * @param {Object} opts - options * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @param {string} [opts.format='extended'] - choose between the basic and extended format * @example DateTime.utc(1982, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z' * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00' * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335' * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400' * @return {string} */ ; _proto.toISO = function toISO(opts) { if (opts === void 0) { opts = {}; } if (!this.isValid) { return null; } return this.toISODate(opts) + "T" + this.toISOTime(opts); } /** * Returns an ISO 8601-compliant string representation of this DateTime's date component * @param {Object} opts - options * @param {string} [opts.format='extended'] - choose between the basic and extended format * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25' * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525' * @return {string} */ ; _proto.toISODate = function toISODate(_temp3) { var _ref5 = _temp3 === void 0 ? {} : _temp3, _ref5$format = _ref5.format, format = _ref5$format === void 0 ? "extended" : _ref5$format; var fmt = format === "basic" ? "yyyyMMdd" : "yyyy-MM-dd"; if (this.year > 9999) { fmt = "+" + fmt; } return toTechFormat(this, fmt); } /** * Returns an ISO 8601-compliant string representation of this DateTime's week date * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2' * @return {string} */ ; _proto.toISOWeekDate = function toISOWeekDate() { return toTechFormat(this, "kkkk-'W'WW-c"); } /** * Returns an ISO 8601-compliant string representation of this DateTime's time component * @param {Object} opts - options * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @param {boolean} [opts.includePrefix=false] - include the `T` prefix * @param {string} [opts.format='extended'] - choose between the basic and extended format * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z' * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z' * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z' * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z' * @return {string} */ ; _proto.toISOTime = function toISOTime(_temp4) { var _ref6 = _temp4 === void 0 ? {} : _temp4, _ref6$suppressMillise = _ref6.suppressMilliseconds, suppressMilliseconds = _ref6$suppressMillise === void 0 ? false : _ref6$suppressMillise, _ref6$suppressSeconds = _ref6.suppressSeconds, suppressSeconds = _ref6$suppressSeconds === void 0 ? false : _ref6$suppressSeconds, _ref6$includeOffset = _ref6.includeOffset, includeOffset = _ref6$includeOffset === void 0 ? true : _ref6$includeOffset, _ref6$includePrefix = _ref6.includePrefix, includePrefix = _ref6$includePrefix === void 0 ? false : _ref6$includePrefix, _ref6$format = _ref6.format, format = _ref6$format === void 0 ? "extended" : _ref6$format; return toTechTimeFormat(this, { suppressSeconds: suppressSeconds, suppressMilliseconds: suppressMilliseconds, includeOffset: includeOffset, includePrefix: includePrefix, format: format }); } /** * Returns an RFC 2822-compatible string representation of this DateTime, always in UTC * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000' * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400' * @return {string} */ ; _proto.toRFC2822 = function toRFC2822() { return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false); } /** * Returns a string representation of this DateTime appropriate for use in HTTP headers. * Specifically, the string conforms to RFC 1123. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT' * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT' * @return {string} */ ; _proto.toHTTP = function toHTTP() { return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'"); } /** * Returns a string representation of this DateTime appropriate for use in SQL Date * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13' * @return {string} */ ; _proto.toSQLDate = function toSQLDate() { return toTechFormat(this, "yyyy-MM-dd"); } /** * Returns a string representation of this DateTime appropriate for use in SQL Time * @param {Object} opts - options * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @example DateTime.utc().toSQL() //=> '05:15:16.345' * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00' * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345' * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York' * @return {string} */ ; _proto.toSQLTime = function toSQLTime(_temp5) { var _ref7 = _temp5 === void 0 ? {} : _temp5, _ref7$includeOffset = _ref7.includeOffset, includeOffset = _ref7$includeOffset === void 0 ? true : _ref7$includeOffset, _ref7$includeZone = _ref7.includeZone, includeZone = _ref7$includeZone === void 0 ? false : _ref7$includeZone; return toTechTimeFormat(this, { includeOffset: includeOffset, includeZone: includeZone, spaceZone: true }); } /** * Returns a string representation of this DateTime appropriate for use in SQL DateTime * @param {Object} opts - options * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z' * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00' * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000' * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York' * @return {string} */ ; _proto.toSQL = function toSQL(opts) { if (opts === void 0) { opts = {}; } if (!this.isValid) { return null; } return this.toSQLDate() + " " + this.toSQLTime(opts); } /** * Returns a string representation of this DateTime appropriate for debugging * @return {string} */ ; _proto.toString = function toString() { return this.isValid ? this.toISO() : INVALID$2; } /** * Returns the epoch milliseconds of this DateTime. Alias of {@link toMillis} * @return {number} */ ; _proto.valueOf = function valueOf() { return this.toMillis(); } /** * Returns the epoch milliseconds of this DateTime. * @return {number} */ ; _proto.toMillis = function toMillis() { return this.isValid ? this.ts : NaN; } /** * Returns the epoch seconds of this DateTime. * @return {number} */ ; _proto.toSeconds = function toSeconds() { return this.isValid ? this.ts / 1000 : NaN; } /** * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON. * @return {string} */ ; _proto.toJSON = function toJSON() { return this.toISO(); } /** * Returns a BSON serializable equivalent to this DateTime. * @return {Date} */ ; _proto.toBSON = function toBSON() { return this.toJSDate(); } /** * Returns a JavaScript object with this DateTime's year, month, day, and so on. * @param opts - options for generating the object * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 } * @return {Object} */ ; _proto.toObject = function toObject(opts) { if (opts === void 0) { opts = {}; } if (!this.isValid) return {}; var base = Object.assign({}, this.c); if (opts.includeConfig) { base.outputCalendar = this.outputCalendar; base.numberingSystem = this.loc.numberingSystem; base.locale = this.loc.locale; } return base; } /** * Returns a JavaScript Date equivalent to this DateTime. * @return {Date} */ ; _proto.toJSDate = function toJSDate() { return new Date(this.isValid ? this.ts : NaN); } // COMPARE /** * Return the difference between two DateTimes as a Duration. * @param {DateTime} otherDateTime - the DateTime to compare this one to * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration. * @param {Object} opts - options that affect the creation of the Duration * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @example * var i1 = DateTime.fromISO('1982-05-25T09:45'), * i2 = DateTime.fromISO('1983-10-14T10:30'); * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 } * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 } * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 } * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 } * @return {Duration} */ ; _proto.diff = function diff(otherDateTime, unit, opts) { if (unit === void 0) { unit = "milliseconds"; } if (opts === void 0) { opts = {}; } if (!this.isValid || !otherDateTime.isValid) { return Duration.invalid(this.invalid || otherDateTime.invalid, "created by diffing an invalid DateTime"); } var durOpts = Object.assign({ locale: this.locale, numberingSystem: this.numberingSystem }, opts); var units = maybeArray(unit).map(Duration.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = _diff(earlier, later, units, durOpts); return otherIsLater ? diffed.negate() : diffed; } /** * Return the difference between this DateTime and right now. * See {@link diff} * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration * @param {Object} opts - options that affect the creation of the Duration * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @return {Duration} */ ; _proto.diffNow = function diffNow(unit, opts) { if (unit === void 0) { unit = "milliseconds"; } if (opts === void 0) { opts = {}; } return this.diff(DateTime.now(), unit, opts); } /** * Return an Interval spanning between this DateTime and another DateTime * @param {DateTime} otherDateTime - the other end point of the Interval * @return {Interval} */ ; _proto.until = function until(otherDateTime) { return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this; } /** * Return whether this DateTime is in the same unit of time as another DateTime. * Higher-order units must also be identical for this function to return `true`. * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link setZone} to convert one of the dates if needed. * @param {DateTime} otherDateTime - the other DateTime * @param {string} unit - the unit of time to check sameness on * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day * @return {boolean} */ ; _proto.hasSame = function hasSame(otherDateTime, unit) { if (!this.isValid) return false; var inputMs = otherDateTime.valueOf(); var otherZoneDateTime = this.setZone(otherDateTime.zone, { keepLocalTime: true }); return otherZoneDateTime.startOf(unit) <= inputMs && inputMs <= otherZoneDateTime.endOf(unit); } /** * Equality check * Two DateTimes are equal iff they represent the same millisecond, have the same zone and location, and are both valid. * To compare just the millisecond values, use `+dt1 === +dt2`. * @param {DateTime} other - the other DateTime * @return {boolean} */ ; _proto.equals = function equals(other) { return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc); } /** * Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your * platform supports Intl.RelativeTimeFormat. Rounds down by default. * @param {Object} options - options that affect the output * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now. * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow" * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds" * @param {boolean} [options.round=true] - whether to round the numbers in the output. * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding. * @param {string} options.locale - override the locale of this DateTime * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this * @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day" * @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día" * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures" * @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago" * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago" * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago" */ ; _proto.toRelative = function toRelative(options) { if (options === void 0) { options = {}; } if (!this.isValid) return null; var base = options.base || DateTime.fromObject({ zone: this.zone }), padding = options.padding ? this < base ? -options.padding : options.padding : 0; return diffRelative(base, this.plus(padding), Object.assign(options, { numeric: "always", units: ["years", "months", "days", "hours", "minutes", "seconds"] })); } /** * Returns a string representation of this date relative to today, such as "yesterday" or "next month". * Only internationalizes on platforms that supports Intl.RelativeTimeFormat. * @param {Object} options - options that affect the output * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now. * @param {string} options.locale - override the locale of this DateTime * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days" * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow" * @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana" * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain" * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago" */ ; _proto.toRelativeCalendar = function toRelativeCalendar(options) { if (options === void 0) { options = {}; } if (!this.isValid) return null; return diffRelative(options.base || DateTime.fromObject({ zone: this.zone }), this, Object.assign(options, { numeric: "auto", units: ["years", "months", "days"], calendary: true })); } /** * Return the min of several date times * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum * @return {DateTime} the min DateTime, or undefined if called with no argument */ ; DateTime.min = function min() { for (var _len = arguments.length, dateTimes = new Array(_len), _key = 0; _key < _len; _key++) { dateTimes[_key] = arguments[_key]; } if (!dateTimes.every(DateTime.isDateTime)) { throw new InvalidArgumentError("min requires all arguments be DateTimes"); } return bestBy(dateTimes, function (i) { return i.valueOf(); }, Math.min); } /** * Return the max of several date times * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum * @return {DateTime} the max DateTime, or undefined if called with no argument */ ; DateTime.max = function max() { for (var _len2 = arguments.length, dateTimes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { dateTimes[_key2] = arguments[_key2]; } if (!dateTimes.every(DateTime.isDateTime)) { throw new InvalidArgumentError("max requires all arguments be DateTimes"); } return bestBy(dateTimes, function (i) { return i.valueOf(); }, Math.max); } // MISC /** * Explain how a string would be parsed by fromFormat() * @param {string} text - the string to parse * @param {string} fmt - the format the string is expected to be in (see description) * @param {Object} options - options taken by fromFormat() * @return {Object} */ ; DateTime.fromFormatExplain = function fromFormatExplain(text, fmt, options) { if (options === void 0) { options = {}; } var _options = options, _options$locale = _options.locale, locale = _options$locale === void 0 ? null : _options$locale, _options$numberingSys = _options.numberingSystem, numberingSystem = _options$numberingSys === void 0 ? null : _options$numberingSys, localeToUse = Locale.fromOpts({ locale: locale, numberingSystem: numberingSystem, defaultToEN: true }); return explainFromTokens(localeToUse, text, fmt); } /** * @deprecated use fromFormatExplain instead */ ; DateTime.fromStringExplain = function fromStringExplain(text, fmt, options) { if (options === void 0) { options = {}; } return DateTime.fromFormatExplain(text, fmt, options); } // FORMAT PRESETS /** * {@link toLocaleString} format like 10/14/1983 * @type {Object} */ ; _createClass(DateTime, [{ key: "isValid", get: function get() { return this.invalid === null; } /** * Returns an error code if this DateTime is invalid, or null if the DateTime is valid * @type {string} */ }, { key: "invalidReason", get: function get() { return this.invalid ? this.invalid.reason : null; } /** * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid * @type {string} */ }, { key: "invalidExplanation", get: function get() { return this.invalid ? this.invalid.explanation : null; } /** * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime * * @type {string} */ }, { key: "locale", get: function get() { return this.isValid ? this.loc.locale : null; } /** * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime * * @type {string} */ }, { key: "numberingSystem", get: function get() { return this.isValid ? this.loc.numberingSystem : null; } /** * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime * * @type {string} */ }, { key: "outputCalendar", get: function get() { return this.isValid ? this.loc.outputCalendar : null; } /** * Get the time zone associated with this DateTime. * @type {Zone} */ }, { key: "zone", get: function get() { return this._zone; } /** * Get the name of the time zone. * @type {string} */ }, { key: "zoneName", get: function get() { return this.isValid ? this.zone.name : null; } /** * Get the year * @example DateTime.local(2017, 5, 25).year //=> 2017 * @type {number} */ }, { key: "year", get: function get() { return this.isValid ? this.c.year : NaN; } /** * Get the quarter * @example DateTime.local(2017, 5, 25).quarter //=> 2 * @type {number} */ }, { key: "quarter", get: function get() { return this.isValid ? Math.ceil(this.c.month / 3) : NaN; } /** * Get the month (1-12). * @example DateTime.local(2017, 5, 25).month //=> 5 * @type {number} */ }, { key: "month", get: function get() { return this.isValid ? this.c.month : NaN; } /** * Get the day of the month (1-30ish). * @example DateTime.local(2017, 5, 25).day //=> 25 * @type {number} */ }, { key: "day", get: function get() { return this.isValid ? this.c.day : NaN; } /** * Get the hour of the day (0-23). * @example DateTime.local(2017, 5, 25, 9).hour //=> 9 * @type {number} */ }, { key: "hour", get: function get() { return this.isValid ? this.c.hour : NaN; } /** * Get the minute of the hour (0-59). * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30 * @type {number} */ }, { key: "minute", get: function get() { return this.isValid ? this.c.minute : NaN; } /** * Get the second of the minute (0-59). * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52 * @type {number} */ }, { key: "second", get: function get() { return this.isValid ? this.c.second : NaN; } /** * Get the millisecond of the second (0-999). * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654 * @type {number} */ }, { key: "millisecond", get: function get() { return this.isValid ? this.c.millisecond : NaN; } /** * Get the week year * @see https://en.wikipedia.org/wiki/ISO_week_date * @example DateTime.local(2014, 11, 31).weekYear //=> 2015 * @type {number} */ }, { key: "weekYear", get: function get() { return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN; } /** * Get the week number of the week year (1-52ish). * @see https://en.wikipedia.org/wiki/ISO_week_date * @example DateTime.local(2017, 5, 25).weekNumber //=> 21 * @type {number} */ }, { key: "weekNumber", get: function get() { return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN; } /** * Get the day of the week. * 1 is Monday and 7 is Sunday * @see https://en.wikipedia.org/wiki/ISO_week_date * @example DateTime.local(2014, 11, 31).weekday //=> 4 * @type {number} */ }, { key: "weekday", get: function get() { return this.isValid ? possiblyCachedWeekData(this).weekday : NaN; } /** * Get the ordinal (meaning the day of the year) * @example DateTime.local(2017, 5, 25).ordinal //=> 145 * @type {number|DateTime} */ }, { key: "ordinal", get: function get() { return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN; } /** * Get the human readable short month name, such as 'Oct'. * Defaults to the system's locale if no locale has been specified * @example DateTime.local(2017, 10, 30).monthShort //=> Oct * @type {string} */ }, { key: "monthShort", get: function get() { return this.isValid ? Info.months("short", { locale: this.locale })[this.month - 1] : null; } /** * Get the human readable long month name, such as 'October'. * Defaults to the system's locale if no locale has been specified * @example DateTime.local(2017, 10, 30).monthLong //=> October * @type {string} */ }, { key: "monthLong", get: function get() { return this.isValid ? Info.months("long", { locale: this.locale })[this.month - 1] : null; } /** * Get the human readable short weekday, such as 'Mon'. * Defaults to the system's locale if no locale has been specified * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon * @type {string} */ }, { key: "weekdayShort", get: function get() { return this.isValid ? Info.weekdays("short", { locale: this.locale })[this.weekday - 1] : null; } /** * Get the human readable long weekday, such as 'Monday'. * Defaults to the system's locale if no locale has been specified * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday * @type {string} */ }, { key: "weekdayLong", get: function get() { return this.isValid ? Info.weekdays("long", { locale: this.locale })[this.weekday - 1] : null; } /** * Get the UTC offset of this DateTime in minutes * @example DateTime.now().offset //=> -240 * @example DateTime.utc().offset //=> 0 * @type {number} */ }, { key: "offset", get: function get() { return this.isValid ? +this.o : NaN; } /** * Get the short human name for the zone's current offset, for example "EST" or "EDT". * Defaults to the system's locale if no locale has been specified * @type {string} */ }, { key: "offsetNameShort", get: function get() { if (this.isValid) { return this.zone.offsetName(this.ts, { format: "short", locale: this.locale }); } else { return null; } } /** * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time". * Defaults to the system's locale if no locale has been specified * @type {string} */ }, { key: "offsetNameLong", get: function get() { if (this.isValid) { return this.zone.offsetName(this.ts, { format: "long", locale: this.locale }); } else { return null; } } /** * Get whether this zone's offset ever changes, as in a DST. * @type {boolean} */ }, { key: "isOffsetFixed", get: function get() { return this.isValid ? this.zone.universal : null; } /** * Get whether the DateTime is in a DST. * @type {boolean} */ }, { key: "isInDST", get: function get() { if (this.isOffsetFixed) { return false; } else { return this.offset > this.set({ month: 1 }).offset || this.offset > this.set({ month: 5 }).offset; } } /** * Returns true if this DateTime is in a leap year, false otherwise * @example DateTime.local(2016).isInLeapYear //=> true * @example DateTime.local(2013).isInLeapYear //=> false * @type {boolean} */ }, { key: "isInLeapYear", get: function get() { return isLeapYear(this.year); } /** * Returns the number of days in this DateTime's month * @example DateTime.local(2016, 2).daysInMonth //=> 29 * @example DateTime.local(2016, 3).daysInMonth //=> 31 * @type {number} */ }, { key: "daysInMonth", get: function get() { return daysInMonth(this.year, this.month); } /** * Returns the number of days in this DateTime's year * @example DateTime.local(2016).daysInYear //=> 366 * @example DateTime.local(2013).daysInYear //=> 365 * @type {number} */ }, { key: "daysInYear", get: function get() { return this.isValid ? daysInYear(this.year) : NaN; } /** * Returns the number of weeks in this DateTime's year * @see https://en.wikipedia.org/wiki/ISO_week_date * @example DateTime.local(2004).weeksInWeekYear //=> 53 * @example DateTime.local(2013).weeksInWeekYear //=> 52 * @type {number} */ }, { key: "weeksInWeekYear", get: function get() { return this.isValid ? weeksInWeekYear(this.weekYear) : NaN; } }], [{ key: "DATE_SHORT", get: function get() { return DATE_SHORT; } /** * {@link toLocaleString} format like 'Oct 14, 1983' * @type {Object} */ }, { key: "DATE_MED", get: function get() { return DATE_MED; } /** * {@link toLocaleString} format like 'Fri, Oct 14, 1983' * @type {Object} */ }, { key: "DATE_MED_WITH_WEEKDAY", get: function get() { return DATE_MED_WITH_WEEKDAY; } /** * {@link toLocaleString} format like 'October 14, 1983' * @type {Object} */ }, { key: "DATE_FULL", get: function get() { return DATE_FULL; } /** * {@link toLocaleString} format like 'Tuesday, October 14, 1983' * @type {Object} */ }, { key: "DATE_HUGE", get: function get() { return DATE_HUGE; } /** * {@link toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "TIME_SIMPLE", get: function get() { return TIME_SIMPLE; } /** * {@link toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "TIME_WITH_SECONDS", get: function get() { return TIME_WITH_SECONDS; } /** * {@link toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "TIME_WITH_SHORT_OFFSET", get: function get() { return TIME_WITH_SHORT_OFFSET; } /** * {@link toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "TIME_WITH_LONG_OFFSET", get: function get() { return TIME_WITH_LONG_OFFSET; } /** * {@link toLocaleString} format like '09:30', always 24-hour. * @type {Object} */ }, { key: "TIME_24_SIMPLE", get: function get() { return TIME_24_SIMPLE; } /** * {@link toLocaleString} format like '09:30:23', always 24-hour. * @type {Object} */ }, { key: "TIME_24_WITH_SECONDS", get: function get() { return TIME_24_WITH_SECONDS; } /** * {@link toLocaleString} format like '09:30:23 EDT', always 24-hour. * @type {Object} */ }, { key: "TIME_24_WITH_SHORT_OFFSET", get: function get() { return TIME_24_WITH_SHORT_OFFSET; } /** * {@link toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour. * @type {Object} */ }, { key: "TIME_24_WITH_LONG_OFFSET", get: function get() { return TIME_24_WITH_LONG_OFFSET; } /** * {@link toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_SHORT", get: function get() { return DATETIME_SHORT; } /** * {@link toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_SHORT_WITH_SECONDS", get: function get() { return DATETIME_SHORT_WITH_SECONDS; } /** * {@link toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_MED", get: function get() { return DATETIME_MED; } /** * {@link toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_MED_WITH_SECONDS", get: function get() { return DATETIME_MED_WITH_SECONDS; } /** * {@link toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_MED_WITH_WEEKDAY", get: function get() { return DATETIME_MED_WITH_WEEKDAY; } /** * {@link toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_FULL", get: function get() { return DATETIME_FULL; } /** * {@link toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_FULL_WITH_SECONDS", get: function get() { return DATETIME_FULL_WITH_SECONDS; } /** * {@link toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_HUGE", get: function get() { return DATETIME_HUGE; } /** * {@link toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_HUGE_WITH_SECONDS", get: function get() { return DATETIME_HUGE_WITH_SECONDS; } }]); return DateTime; }(); function friendlyDateTime(dateTimeish) { if (DateTime.isDateTime(dateTimeish)) { return dateTimeish; } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) { return DateTime.fromJSDate(dateTimeish); } else if (dateTimeish && typeof dateTimeish === "object") { return DateTime.fromObject(dateTimeish); } else { throw new InvalidArgumentError("Unknown datetime argument: " + dateTimeish + ", of type " + typeof dateTimeish); } } var VERSION = "1.26.0"; exports.DateTime = DateTime; exports.Duration = Duration; exports.FixedOffsetZone = FixedOffsetZone; exports.IANAZone = IANAZone; exports.Info = Info; exports.Interval = Interval; exports.InvalidZone = InvalidZone; exports.LocalZone = LocalZone; exports.Settings = Settings; exports.VERSION = VERSION; exports.Zone = Zone; },{}],184:[function(require,module,exports){ /** * Export lib/mongoose * */ 'use strict'; module.exports = require('./lib/browser'); },{"./lib/browser":185}],185:[function(require,module,exports){ (function (Buffer){(function (){ /* eslint-env browser */ 'use strict'; require('./driver').set(require('./drivers/browser')); const DocumentProvider = require('./document_provider.js'); const PromiseProvider = require('./promise_provider'); DocumentProvider.setBrowser(true); /** * The Mongoose [Promise](#promise_Promise) constructor. * * @method Promise * @api public */ Object.defineProperty(exports, 'Promise', { get: function() { return PromiseProvider.get(); }, set: function(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 = require('./error/index'); /** * 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 = require('./schema'); /** * The various Mongoose Types. * * ####Example: * * const mongoose = require('mongoose'); * const array = mongoose.Types.Array; * * ####Types: * * - [ObjectId](#types-objectid-js) * - [Buffer](#types-buffer-js) * - [SubDocument](#types-embedded-js) * - [Array](#types-array-js) * - [DocumentArray](#types-documentarray-js) * * 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 = require('./types'); /** * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor * * @method VirtualType * @api public */ exports.VirtualType = require('./virtualtype'); /** * 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 = require('./schematype.js'); /** * Internal utils * * @property utils * @api private */ exports.utils = require('./utils.js'); /** * 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) { class Model extends exports.Document { constructor(obj, fields) { super(obj, schema, fields); } } Model.modelName = name; return Model; }; /*! * Module exports. */ if (typeof window !== 'undefined') { window.mongoose = module.exports; window.Buffer = Buffer; } }).call(this)}).call(this,require("buffer").Buffer) },{"./document_provider.js":195,"./driver":196,"./drivers/browser":200,"./error/index":204,"./promise_provider":272,"./schema":274,"./schematype.js":295,"./types":303,"./utils.js":307,"./virtualtype":308,"buffer":129}],186:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const NodeJSDocument = require('./document'); const EventEmitter = require('events').EventEmitter; const MongooseError = require('./error/index'); const Schema = require('./schema'); const ObjectId = require('./types/objectid'); const ValidationError = MongooseError.ValidationError; const applyHooks = require('./helpers/model/applyHooks'); const isObject = require('./helpers/isObject'); /** * Document constructor. * * @param {Object} obj the values to set * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter * @event `init`: Emitted on a document after it has was retrieved from the db and fully hydrated by Mongoose. * @event `save`: Emitted when the document is successfully saved * @api private */ function Document(obj, schema, fields, skipId, skipInit) { if (!(this instanceof Document)) { return new Document(obj, schema, fields, skipId, skipInit); } if (isObject(schema) && !schema.instanceOfSchema) { schema = new Schema(schema); } // When creating EmbeddedDocument, it already has the schema and he doesn't need the _id schema = this.schema || schema; // Generate ObjectId if it is missing, but it requires a scheme if (!this.schema && schema.options._id) { obj = obj || {}; if (obj._id === undefined) { obj._id = new ObjectId(); } } if (!schema) { throw new MongooseError.MissingSchemaError(); } this.$__setSchema(schema); NodeJSDocument.call(this, obj, fields, skipId, skipInit); applyHooks(this, schema, { decorateDoc: true }); // apply methods for (const m in schema.methods) { this[m] = schema.methods[m]; } // apply statics for (const s in schema.statics) { this[s] = schema.statics[s]; } } /*! * 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; },{"./document":194,"./error/index":204,"./helpers/isObject":234,"./helpers/model/applyHooks":236,"./schema":274,"./types/objectid":305,"events":177}],187:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const CastError = require('./error/cast'); const StrictModeError = require('./error/strict'); const Types = require('./schema/index'); const castTextSearch = require('./schema/operators/text'); const get = require('./helpers/get'); const getSchemaDiscriminatorByValue = require('./helpers/discriminator/getSchemaDiscriminatorByValue'); const isOperator = require('./helpers/query/isOperator'); const util = require('util'); const isObject = require('./helpers/isObject'); const isMongooseObject = require('./helpers/isMongooseObject'); const ALLOWED_GEOWITHIN_GEOJSON_TYPES = ['Polygon', 'MultiPolygon']; /** * Handles internal casting for query filters. * * @param {Schema} schema * @param {Object} obj Object to cast * @param {Object} options the query options * @param {Query} context passed to setters * @api private */ module.exports = function cast(schema, obj, options, context) { if (Array.isArray(obj)) { throw new Error('Query filter must be an object, got an array ', util.inspect(obj)); } if (obj == null) { return obj; } // bson 1.x has the unfortunate tendency to remove filters that have a top-level // `_bsontype` property. But we should still allow ObjectIds because // `Collection#find()` has a special case to support `find(objectid)`. // Should remove this when we upgrade to bson 4.x. See gh-8222, gh-8268 if (obj.hasOwnProperty('_bsontype') && obj._bsontype !== 'ObjectID') { delete obj._bsontype; } if (schema != null && schema.discriminators != null && obj[schema.options.discriminatorKey] != null) { schema = getSchemaDiscriminatorByValue(schema, obj[schema.options.discriminatorKey]) || schema; } const paths = Object.keys(obj); let i = paths.length; let _keys; let any$conditionals; let schematype; let nested; let path; let type; let 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 (let k = 0; k < val.length; ++k) { if (val[k] == null || typeof val[k] !== 'object') { throw new CastError('Object', val[k], path + '.' + k); } val[k] = cast(schema, val[k], options, context); } } else if (path === '$where') { type = typeof val; 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 === '$elemMatch') { val = cast(schema, val, options, context); } else if (path === '$text') { val = castTextSearch(val, path); } else { if (!schema) { // no casting for Mixed types continue; } schematype = schema.path(path); // Check for embedded discriminator paths if (!schematype) { const split = path.split('.'); let j = split.length; while (j--) { const pathFirstHalf = split.slice(0, j).join('.'); const pathLastHalf = split.slice(j).join('.'); const _schematype = schema.path(pathFirstHalf); const discriminatorKey = get(_schematype, 'schema.options.discriminatorKey'); // gh-6027: if we haven't found the schematype but this path is // underneath an embedded discriminator and the embedded discriminator // key is in the query, use the embedded discriminator schema if (_schematype != null && get(_schematype, 'schema.discriminators') != null && discriminatorKey != null && pathLastHalf !== discriminatorKey) { const discriminatorVal = get(obj, pathFirstHalf + '.' + discriminatorKey); if (discriminatorVal != null) { schematype = _schematype.schema.discriminators[discriminatorVal]. path(pathLastHalf); } } } } if (!schematype) { // Handle potential embedded array queries const split = path.split('.'); let j = split.length; let pathFirstHalf; let pathLastHalf; let remainingConds; // Find the part of the var path that is a path of the Schema while (j--) { pathFirstHalf = split.slice(0, j).join('.'); schematype = schema.path(pathFirstHalf); if (schematype) { break; } } // If a substring of the input path resolves to an actual real path... if (schematype) { // Apply the casting; similar code for $elemMatch in schema/array.js if (schematype.caster && schematype.caster.schema) { remainingConds = {}; pathLastHalf = split.slice(j).join('.'); remainingConds[pathLastHalf] = val; obj[path] = cast(schematype.caster.schema, remainingConds, options, context)[pathLastHalf]; } else { obj[path] = val; } continue; } if (isObject(val)) { // handle geo schemas that use object notation // { loc: { long: Number, lat: Number } let geo = ''; if (val.$near) { geo = '$near'; } else if (val.$nearSphere) { geo = '$nearSphere'; } else if (val.$within) { geo = '$within'; } else if (val.$geoIntersects) { geo = '$geoIntersects'; } else if (val.$geoWithin) { geo = '$geoWithin'; } if (geo) { const numbertype = new Types.Number('__QueryCasting__'); let 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') { const withinType = value.$center || value.$centerSphere || value.$box || value.$polygon; if (!withinType) { throw new Error('Bad $within parameter: ' + JSON.stringify(val)); } value = withinType; } else if (geo === '$near' && typeof value.type === 'string' && Array.isArray(value.coordinates)) { // geojson; cast the coordinates value = value.coordinates; } else if ((geo === '$near' || geo === '$nearSphere' || geo === '$geoIntersects') && value.$geometry && typeof value.$geometry.type === 'string' && Array.isArray(value.$geometry.coordinates)) { if (value.$maxDistance != null) { value.$maxDistance = numbertype.castForQueryWrapper({ val: value.$maxDistance, context: context }); } if (value.$minDistance != null) { value.$minDistance = numbertype.castForQueryWrapper({ val: value.$minDistance, context: context }); } if (isMongooseObject(value.$geometry)) { value.$geometry = value.$geometry.toObject({ transform: false, virtuals: false }); } value = value.$geometry.coordinates; } else if (geo === '$geoWithin') { if (value.$geometry) { if (isMongooseObject(value.$geometry)) { value.$geometry = value.$geometry.toObject({ virtuals: false }); } const geoWithinType = value.$geometry.type; if (ALLOWED_GEOWITHIN_GEOJSON_TYPES.indexOf(geoWithinType) === -1) { throw new Error('Invalid geoJSON type for $geoWithin "' + geoWithinType + '", must be "Polygon" or "MultiPolygon"'); } value = value.$geometry.coordinates; } else { value = value.$box || value.$polygon || value.$center || value.$centerSphere; if (isMongooseObject(value)) { value = value.toObject({ virtuals: false }); } } } _cast(value, numbertype, context); continue; } } if (schema.nested[path]) { continue; } if (options.upsert && options.strict) { if (options.strict === 'throw') { throw new StrictModeError(path); } throw new StrictModeError(path, 'Path "' + path + '" is not in ' + 'schema, strict mode is `true`, and upsert is `true`.'); } else if (options.strictQuery === 'throw') { throw new StrictModeError(path, 'Path "' + path + '" is not in ' + 'schema and strictQuery is \'throw\'.'); } else if (options.strictQuery) { delete obj[path]; } } else if (val == null) { continue; } else if (val.constructor.name === 'Object') { any$conditionals = Object.keys(val).some(isOperator); if (!any$conditionals) { obj[path] = schematype.castForQueryWrapper({ val: val, context: context }); } else { const ks = Object.keys(val); let $cond; let k = ks.length; while (k--) { $cond = ks[k]; nested = val[$cond]; if ($cond === '$not') { if (nested && schematype && !schematype.caster) { _keys = Object.keys(nested); if (_keys.length && isOperator(_keys[0])) { for (const key in nested) { nested[key] = schematype.castForQueryWrapper({ $conditional: key, val: nested[key], context: context }); } } else { val[$cond] = schematype.castForQueryWrapper({ $conditional: $cond, val: nested, context: context }); } continue; } cast(schematype.caster ? schematype.caster.schema : schema, nested, options, context); } else { val[$cond] = schematype.castForQueryWrapper({ $conditional: $cond, val: nested, context: context }); } } } } else if (Array.isArray(val) && ['Buffer', 'Array'].indexOf(schematype.instance) === -1) { const casted = []; const valuesArray = val; for (const _val of valuesArray) { casted.push(schematype.castForQueryWrapper({ val: _val, context: context })); } obj[path] = { $in: casted }; } else { obj[path] = schematype.castForQueryWrapper({ val: val, context: context }); } } } return obj; }; function _cast(val, numbertype, context) { if (Array.isArray(val)) { val.forEach(function(item, i) { if (Array.isArray(item) || isObject(item)) { return _cast(item, numbertype, context); } val[i] = numbertype.castForQueryWrapper({ val: item, context: context }); }); } else { const nearKeys = Object.keys(val); let nearLen = nearKeys.length; while (nearLen--) { const nkey = nearKeys[nearLen]; const item = val[nkey]; if (Array.isArray(item) || isObject(item)) { _cast(item, numbertype, context); val[nkey] = item; } else { val[nkey] = numbertype.castForQuery({ val: item, context: context }); } } } } },{"./error/cast":202,"./error/strict":214,"./helpers/discriminator/getSchemaDiscriminatorByValue":224,"./helpers/get":229,"./helpers/isMongooseObject":233,"./helpers/isObject":234,"./helpers/query/isOperator":243,"./schema/index":282,"./schema/operators/text":291,"util":332}],188:[function(require,module,exports){ 'use strict'; const CastError = require('../error/cast'); /*! * 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']); },{"../error/cast":202}],189:[function(require,module,exports){ 'use strict'; const assert = require('assert'); 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; } let date; assert.ok(typeof value !== 'boolean'); if (value instanceof Number || typeof value === 'number') { date = new Date(value); } else if (typeof value === 'string' && !isNaN(Number(value)) && (Number(value) >= 275761 || Number(value) < -271820)) { // string representation of milliseconds take this path date = new Date(Number(value)); } else if (typeof value.valueOf === 'function') { // support for moment.js. This is also the path strings will take because // strings have a `valueOf()` date = new Date(value.valueOf()); } else { // fallback date = new Date(value); } if (!isNaN(date.valueOf())) { return date; } assert.ok(false); }; },{"assert":103}],190:[function(require,module,exports){ (function (Buffer){(function (){ 'use strict'; const Decimal128Type = require('../types/decimal128'); const assert = require('assert'); 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); }; }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":179,"../types/decimal128":300,"assert":103}],191:[function(require,module,exports){ 'use strict'; const assert = require('assert'); /*! * Given a value, cast it to a number, or throw a `CastError` if the value * cannot be casted. `null` and `undefined` are considered valid. * * @param {Any} value * @param {String} [path] optional the path to set on the CastError * @return {Boolean|null|undefined} * @throws {Error} if `value` is not one of the allowed values * @api private */ module.exports = function castNumber(val) { if (val == null) { return val; } if (val === '') { return null; } 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); }; },{"assert":103}],192:[function(require,module,exports){ 'use strict'; const ObjectId = require('../driver').get().ObjectId; const assert = require('assert'); module.exports = function castObjectId(value) { if (value == null) { return value; } if (value instanceof ObjectId) { return value; } if (value._id) { if (value._id instanceof 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()); } assert.ok(false); }; },{"../driver":196,"assert":103}],193:[function(require,module,exports){ 'use strict'; const CastError = require('../error/cast'); /*! * 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); }; },{"../error/cast":202}],194:[function(require,module,exports){ (function (Buffer,process){(function (){ 'use strict'; /*! * Module dependencies. */ const EventEmitter = require('events').EventEmitter; const InternalCache = require('./internal'); const MongooseError = require('./error/index'); const MixedSchema = require('./schema/mixed'); const ObjectExpectedError = require('./error/objectExpected'); const ObjectParameterError = require('./error/objectParameter'); const ParallelValidateError = require('./error/parallelValidate'); const Schema = require('./schema'); const StrictModeError = require('./error/strict'); const ValidationError = require('./error/validation'); const ValidatorError = require('./error/validator'); const VirtualType = require('./virtualtype'); const promiseOrCallback = require('./helpers/promiseOrCallback'); const cleanModifiedSubpaths = require('./helpers/document/cleanModifiedSubpaths'); const compile = require('./helpers/document/compile').compile; const defineKey = require('./helpers/document/compile').defineKey; const flatten = require('./helpers/common').flatten; const get = require('./helpers/get'); const getEmbeddedDiscriminatorPath = require('./helpers/document/getEmbeddedDiscriminatorPath'); const handleSpreadDoc = require('./helpers/document/handleSpreadDoc'); const idGetter = require('./plugins/idGetter'); const isDefiningProjection = require('./helpers/projection/isDefiningProjection'); const isExclusive = require('./helpers/projection/isExclusive'); const inspect = require('util').inspect; const internalToObjectOptions = require('./options').internalToObjectOptions; const mpath = require('mpath'); const queryhelpers = require('./queryhelpers'); const utils = require('./utils'); const isPromise = require('./helpers/isPromise'); const clone = utils.clone; const deepEqual = utils.deepEqual; const isMongooseObject = utils.isMongooseObject; const arrayAtomicsBackupSymbol = Symbol('mongoose.Array#atomicsBackup'); const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol; const documentArrayParent = require('./helpers/symbols').documentArrayParent; const documentIsModified = require('./helpers/symbols').documentIsModified; const documentModifiedPaths = require('./helpers/symbols').documentModifiedPaths; const documentSchemaSymbol = require('./helpers/symbols').documentSchemaSymbol; const getSymbol = require('./helpers/symbols').getSymbol; const populateModelSymbol = require('./helpers/symbols').populateModelSymbol; const scopeSymbol = require('./helpers/symbols').scopeSymbol; let DocumentArray; let MongooseArray; let Embedded; const specialProperties = utils.specialProperties; /** * The core Mongoose document constructor. You should not call this directly, * the Mongoose [Model constructor](./api.html#Model) calls this for you. * * @param {Object} obj the values to set * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data * @param {Object} [options] various configuration options for the document * @param {Boolean} [options.defaults=true] if `false`, skip applying default values to this document. * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter * @event `init`: Emitted on a document after it has been retrieved from the db and fully hydrated by Mongoose. * @event `save`: Emitted when the document is successfully saved * @api private */ function Document(obj, fields, skipId, options) { if (typeof skipId === 'object' && skipId != null) { options = skipId; skipId = options.skipId; } options = Object.assign({}, options); const defaults = get(options, 'defaults', true); options.defaults = defaults; // Support `browserDocument.js` syntax if (this.schema == null) { const _schema = utils.isObject(fields) && !fields.instanceOfSchema ? new Schema(fields) : fields; this.$__setSchema(_schema); fields = skipId; skipId = options; options = arguments[4] || {}; } this.$__ = new InternalCache; this.$__.emitter = new EventEmitter(); this.isNew = 'isNew' in options ? options.isNew : true; this.errors = undefined; this.$__.$options = options || {}; this.$locals = {}; this.$op = null; if (obj != null && typeof obj !== 'object') { throw new ObjectParameterError(obj, 'obj', 'Document'); } const schema = this.schema; if (typeof fields === 'boolean' || fields === 'throw') { this.$__.strictMode = fields; fields = undefined; } else { this.$__.strictMode = schema.options.strict; this.$__.selected = fields; } const requiredPaths = schema.requiredPaths(true); for (const path of requiredPaths) { this.$__.activePaths.require(path); } this.$__.emitter.setMaxListeners(0); let exclude = null; // determine if this doc is a result of a query with // excluded fields if (utils.isPOJO(fields)) { exclude = isExclusive(fields); } const hasIncludedChildren = exclude === false && fields ? $__hasIncludedChildren(fields) : {}; 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, skipId, exclude, hasIncludedChildren, true, { isNew: this.isNew }); } } if (obj) { // Skip set hooks if (this.$__original_set) { this.$__original_set(obj, undefined, true); } else { this.$set(obj, undefined, true); } 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) { EventEmitter.prototype.once.call(this, 'init', () => { $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, { isNew: this.isNew }); }); } else if (defaults) { $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, { isNew: this.isNew }); } this.$__._id = this._id; if (!this.$__.strictMode && obj) { const _this = this; const keys = Object.keys(this._doc); keys.forEach(function(key) { if (!(key in schema.tree)) { defineKey(key, null, _this); } }); } applyQueue(this); } /*! * Document exposes the NodeJS event emitter API, so you can use * `on`, `once`, etc. */ utils.each( ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners', 'removeAllListeners', 'addListener'], function(emitterFn) { Document.prototype[emitterFn] = function() { return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments); }; }); Document.prototype.constructor = Document; for (const i in EventEmitter.prototype) { Document[i] = EventEmitter.prototype[i]; } /** * The document's schema. * * @api public * @property schema * @memberOf Document * @instance */ Document.prototype.schema; /** * Empty object that you can use for storing properties on the document. This * is handy for passing data to middleware without conflicting with Mongoose * internals. * * ####Example: * * schema.pre('save', function() { * // Mongoose will set `isNew` to `false` if `save()` succeeds * this.$locals.wasNew = this.isNew; * }); * * schema.post('save', function() { * // Prints true if `isNew` was set before `save()` * console.log(this.$locals.wasNew); * }); * * @api public * @property $locals * @memberOf Document * @instance */ Object.defineProperty(Document.prototype, '$locals', { configurable: false, enumerable: false, writable: true }); /** * Boolean flag specifying if the document is new. * * @api public * @property isNew * @memberOf Document * @instance */ Document.prototype.isNew; /** * The string version of this documents _id. * * ####Note: * * This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time. * * new Schema({ name: String }, { id: false }); * * @api public * @see Schema options /docs/guide.html#options * @property id * @memberOf Document * @instance */ Document.prototype.id; /** * Hash containing current validation errors. * * @api public * @property errors * @memberOf Document * @instance */ Document.prototype.errors; /** * A string containing the current operation that Mongoose is executing * on this document. May be `null`, `'save'`, `'validate'`, or `'remove'`. * * ####Example: * * const doc = new Model({ name: 'test' }); * doc.$op; // null * * const promise = doc.save(); * doc.$op; // 'save' * * await promise; * doc.$op; // null * * @api public * @property $op * @memberOf Document * @instance */ Document.prototype.$op; /*! * ignore */ function $__hasIncludedChildren(fields) { const hasIncludedChildren = {}; const keys = Object.keys(fields); for (const key of keys) { const parts = key.split('.'); const c = []; for (const part of parts) { c.push(part); hasIncludedChildren[c.join('.')] = 1; } } return hasIncludedChildren; } /*! * ignore */ function $__applyDefaults(doc, fields, skipId, exclude, hasIncludedChildren, isBeforeSetters, pathsToSkip) { const paths = Object.keys(doc.schema.paths); const plen = paths.length; for (let i = 0; i < plen; ++i) { let def; let curPath = ''; const p = paths[i]; if (p === '_id' && skipId) { continue; } const type = doc.schema.paths[p]; const path = p.indexOf('.') === -1 ? [p] : p.split('.'); const len = path.length; let included = false; let doc_ = doc._doc; for (let j = 0; j < len; ++j) { if (doc_ == null) { break; } const piece = path[j]; curPath += (!curPath.length ? '' : '.') + piece; if (exclude === true) { if (curPath in fields) { break; } } else if (exclude === false && fields && !included) { if (curPath in fields) { included = true; } else if (!hasIncludedChildren[curPath]) { break; } } 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]; } } } } /** * Builds the default doc structure * * @param {Object} obj * @param {Object} [fields] * @param {Boolean} [skipId] * @api private * @method $__buildDoc * @memberOf Document * @instance */ Document.prototype.$__buildDoc = function(obj, fields, skipId, exclude, hasIncludedChildren) { const doc = {}; const paths = Object.keys(this.schema.paths). // Don't build up any paths that are underneath a map, we don't know // what the keys will be filter(p => !p.includes('$*')); const plen = paths.length; let ii = 0; for (; ii < plen; ++ii) { const p = paths[ii]; if (p === '_id') { if (skipId) { continue; } if (obj && '_id' in obj) { continue; } } const path = p.split('.'); const len = path.length; const last = len - 1; let curPath = ''; let doc_ = doc; let included = false; for (let i = 0; i < len; ++i) { const piece = path[i]; curPath += (!curPath.length ? '' : '.') + piece; // 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 (i < 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; }; /*! * ignore */ Document.prototype.$__init = function(doc, opts) { this.isNew = false; this.$init = true; opts = opts || {}; // handle docs with populated paths // If doc._id is not null or undefined if (doc._id != null && opts.populated && opts.populated.length) { const id = String(doc._id); for (const item of opts.populated) { if (item.isVirtual) { this.populated(item.path, utils.getValue(item.path, doc), item); } else { this.populated(item.path, item._docs[id], item); } if (item._childDocs == null) { continue; } for (const child of item._childDocs) { if (child == null || child.$__ == null) { continue; } child.$__.parent = this; } } } init(this, doc, this._doc, opts); markArraySubdocsPopulated(this, opts.populated); this.emit('init', this); this.constructor.emit('init', this); this.$__._id = this._id; return this; }; /*! * If populating a path within a document array, make sure each * subdoc within the array knows its subpaths are populated. * * ####Example: * const doc = await Article.findOne().populate('comments.author'); * doc.comments[0].populated('author'); // Should be set */ function markArraySubdocsPopulated(doc, populated) { if (doc._id == null || populated == null || populated.length === 0) { return; } const id = String(doc._id); for (const item of populated) { if (item.isVirtual) { continue; } const path = item.path; const pieces = path.split('.'); for (let i = 0; i < pieces.length - 1; ++i) { const subpath = pieces.slice(0, i + 1).join('.'); const rest = pieces.slice(i + 1).join('.'); const val = doc.get(subpath); if (val == null) { continue; } if (val.isMongooseDocumentArray) { for (let j = 0; j < val.length; ++j) { val[j].populated(rest, item._docs[id] == null ? [] : item._docs[id][j], item); } break; } } } } /*! * 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 || ''; const keys = Object.keys(obj); const len = keys.length; let schema; let path; let i; let index = 0; while (index < len) { _init(index++); } function _init(index) { i = keys[index]; path = prefix + i; schema = self.schema.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 (self.schema.$isRootDiscriminator && !self.$__isSelected(path)) { return; } if (!schema && utils.isPOJO(obj[i])) { // assume nested object if (!doc[i]) { doc[i] = {}; } init(self, obj[i], doc[i], opts, path + '.'); } else if (!schema) { doc[i] = obj[i]; } else { if (obj[i] === null) { doc[i] = schema._castNullish(null); } else if (obj[i] !== undefined) { const intCache = obj[i].$__ || {}; const wasPopulated = intCache.wasPopulated || null; if (schema && !wasPopulated) { try { doc[i] = schema.cast(obj[i], self, true); } catch (e) { self.invalidate(e.path, new ValidatorError({ path: e.path, message: e.message, type: 'cast', value: e.value, reason: e })); } } else { doc[i] = obj[i]; } } // mark as hydrated if (!self.isModified(path)) { self.$__.activePaths.init(path); } } } } /** * Sends an update command with this document `_id` as the query selector. * * ####Example: * * weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback); * * ####Valid options: * * - same as in [Model.update](#model_Model.update) * * @see Model.update #model_Model.update * @param {Object} doc * @param {Object} options * @param {Function} callback * @return {Query} * @api public * @memberOf Document * @instance */ Document.prototype.update = function update() { const args = utils.args(arguments); args.unshift({ _id: this._id }); const query = this.constructor.update.apply(this.constructor, args); if (this.$session() != null) { if (!('session' in query.options)) { query.options.session = this.$session(); } } return query; }; /** * Sends an updateOne command with this document `_id` as the query selector. * * ####Example: * * weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback); * * ####Valid options: * * - same as in [Model.updateOne](#model_Model.updateOne) * * @see Model.updateOne #model_Model.updateOne * @param {Object} doc * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html). * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. * @param {Function} callback * @return {Query} * @api public * @memberOf Document * @instance */ Document.prototype.updateOne = function updateOne(doc, options, callback) { const query = this.constructor.updateOne({ _id: this._id }, doc, options); query._pre(cb => { this.constructor._middleware.execPre('updateOne', this, [this], cb); }); query._post(cb => { this.constructor._middleware.execPost('updateOne', this, [this], {}, cb); }); if (this.$session() != null) { if (!('session' in query.options)) { query.options.session = this.$session(); } } 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](#model_Model.replaceOne) * * @see Model.replaceOne #model_Model.replaceOne * @param {Object} doc * @param {Object} options * @param {Function} callback * @return {Query} * @api public * @memberOf Document * @instance */ Document.prototype.replaceOne = function replaceOne() { const args = utils.args(arguments); args.unshift({ _id: this._id }); return this.constructor.replaceOne.apply(this.constructor, args); }; /** * 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) { return this.$__.session; } this.$__.session = session; if (!this.ownerDocument) { const subdocs = this.$__getAllSubdocs(); for (const child of subdocs) { child.$session(session); } } return session; }; /** * Overwrite all values in this document with the values of `obj`, except * for immutable properties. Behaves similarly to `set()`, except for it * unsets all properties that aren't in `obj`. * * @param {Object} obj the object to overwrite this document with * @method overwrite * @name overwrite * @memberOf Document * @instance * @api public */ Document.prototype.overwrite = function overwrite(obj) { const keys = Array.from(new Set(Object.keys(this._doc).concat(Object.keys(obj)))); for (const key of keys) { if (key === '_id') { continue; } // Explicitly skip version key if (this.schema.options.versionKey && key === this.schema.options.versionKey) { continue; } if (this.schema.options.discriminatorKey && key === this.schema.options.discriminatorKey) { continue; } this.$set(key, obj[key]); } 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 * @method $set * @name $set * @memberOf Document * @instance * @api public */ Document.prototype.$set = function $set(path, val, type, options) { if (utils.isPOJO(type)) { options = type; type = undefined; } options = options || {}; const merge = options.merge; const adhoc = type && type !== true; const constructing = type === true; let adhocs; let keys; let i = 0; let pathtype; let key; let prefix; const strict = 'strict' in options ? options.strict : this.$__.strictMode; if (adhoc) { adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {}); adhocs[path] = this.schema.interpretAsType(path, type, this.schema.options); } if (path == null) { const _ = path; path = val; val = _; } else if (typeof path !== 'string') { // new Document({ key: val }) if (path instanceof Document) { if (path.$__isNested) { path = path.toObject(); } else { path = path._doc; } } if (path == null) { const _ = path; path = val; val = _; } prefix = val ? val + '.' : ''; keys = Object.keys(path); const len = keys.length; // `_skipMinimizeTopLevel` is because we may have deleted the top-level // nested key to ensure key order. const _skipMinimizeTopLevel = get(options, '_skipMinimizeTopLevel', false); if (len === 0 && _skipMinimizeTopLevel) { delete options._skipMinimizeTopLevel; if (val) { this.$set(val, {}); } return this; } for (let i = 0; i < len; ++i) { key = keys[i]; const pathName = prefix + key; pathtype = this.schema.pathType(pathName); // On initial set, delete any nested keys if we're going to overwrite // them to ensure we keep the user's key order. if (type === true && !prefix && path[key] != null && pathtype === 'nested' && this._doc[key] != null && Object.keys(this._doc[key]).length === 0) { delete this._doc[key]; // Make sure we set `{}` back even if we minimize re: gh-8565 options = Object.assign({}, options, { _skipMinimizeTopLevel: true }); } const someCondition = typeof path[key] === 'object' && !utils.isNativeObject(path[key]) && !utils.isMongooseType(path[key]) && path[key] != null && pathtype !== 'virtual' && pathtype !== 'real' && pathtype !== 'adhocOrUndefined' && !(this.$__path(pathName) instanceof MixedSchema) && !(this.schema.paths[pathName] && this.schema.paths[pathName].options && this.schema.paths[pathName].options.ref); if (someCondition) { this.$__.$setCalled.add(prefix + key); this.$set(path[key], prefix + key, constructing, options); } else if (strict) { // Don't overwrite defaults with undefined keys (gh-3981) (gh-9039) if (constructing && path[key] === void 0 && this.get(pathName) !== void 0) { continue; } if (pathtype === 'adhocOrUndefined') { pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true }); } if (pathtype === 'real' || pathtype === 'virtual') { // Check for setting single embedded schema to document (gh-3535) let p = path[key]; if (this.schema.paths[pathName] && this.schema.paths[pathName].$isSingleNested && path[key] instanceof Document) { p = p.toObject({ virtuals: false, transform: false }); } this.$set(prefix + key, p, constructing, options); } else if (pathtype === 'nested' && path[key] instanceof Document) { this.$set(prefix + key, path[key].toObject({ transform: false }), constructing, options); } else if (strict === 'throw') { if (pathtype === 'nested') { throw new ObjectExpectedError(key, path[key]); } else { throw new StrictModeError(key); } } } else if (path[key] !== void 0) { this.$set(prefix + key, path[key], constructing, options); } } return this; } else { this.$__.$setCalled.add(path); } let 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 (pathType === 'nested' && val) { if (typeof val === 'object' && val != null) { const hasPriorVal = this.$__.savedState != null && this.$__.savedState.hasOwnProperty(path); if (this.$__.savedState != null && !this.isNew && !this.$__.savedState.hasOwnProperty(path)) { const priorVal = this.$__getValue(path); this.$__.savedState[path] = priorVal; const keys = Object.keys(priorVal || {}); for (const key of keys) { this.$__.savedState[path + '.' + key] = priorVal[key]; } } if (!merge) { this.$__setValue(path, null); cleanModifiedSubpaths(this, path); } else { return this.$set(val, path, constructing); } const keys = Object.keys(val); this.$__setValue(path, {}); for (const key of keys) { this.$set(path + '.' + key, val[key], constructing); } if (hasPriorVal && utils.deepEqual(this.$__.savedState[path], val)) { this.unmarkModified(path); } else { this.markModified(path); } cleanModifiedSubpaths(this, path, { skipDocArrays: true }); return this; } this.invalidate(path, new MongooseError.CastError('Object', val, path)); return this; } let schema; const 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 let mixed; for (i = 0; i < parts.length; ++i) { const subpath = parts.slice(0, i + 1).join('.'); // If path is underneath a virtual, bypass everything and just set it. if (i + 1 < parts.length && this.schema.pathType(subpath) === 'virtual') { mpath.set(path, val, this); return this; } 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 let cur = this._doc; let curPath = ''; for (i = 0; i < parts.length - 1; ++i) { cur = cur[parts[i]]; curPath += (curPath.length > 0 ? '.' : '') + parts[i]; if (!cur) { this.$set(curPath, {}); // Hack re: gh-5800. If nested field is not selected, it probably exists // so `MongoError: cannot use the part (nested of nested.num) to // traverse the element ({nested: null})` is not likely. If user gets // that error, its their fault for now. We should reconsider disallowing // modifying not selected paths for 6.x if (!this.$__isSelected(curPath)) { this.unmarkModified(curPath); } cur = this.$__getValue(curPath); } } let 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 { for (i = 0; i < parts.length; ++i) { const subpath = parts.slice(0, i + 1).join('.'); if (this.get(subpath, null, { getters: false }) === null) { pathToMark = subpath; break; } } if (!pathToMark) { pathToMark = path; } } // if this doc is being constructed we should not trigger getters const priorVal = (() => { if (this.$__.$options.priorDoc != null) { return this.$__.$options.priorDoc.$__getValue(path); } if (constructing) { return void 0; } return this.$__getValue(path); })(); if (!schema) { this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); return this; } // If overwriting a subdocument path, make sure to clear out // any errors _before_ setting, so new errors that happen // get persisted. Re: #9080 if (schema.$isSingleNested || schema.$isMongooseArray) { _markValidSubpaths(this, path); } if (schema.$isSingleNested && val != null && merge) { if (val instanceof Document) { val = val.toObject({ virtuals: false, transform: false }); } const keys = Object.keys(val); for (const key of keys) { this.$set(path + '.' + key, val[key], constructing, options); } return this; } let shouldSet = true; try { // If the user is trying to set a ref path to a document with // the correct model name, treat it as populated const refMatches = (() => { if (schema.options == null) { return false; } if (!(val instanceof Document)) { return false; } const model = val.constructor; // Check ref const ref = schema.options.ref; if (ref != null && (ref === model.modelName || ref === model.baseModelName)) { return true; } // Check refPath const refPath = schema.options.refPath; if (refPath == null) { return false; } const modelName = val.get(refPath); return modelName === model.modelName || modelName === model.baseModelName; })(); let didPopulate = false; if (refMatches && val instanceof Document) { this.populated(path, val._id, { [populateModelSymbol]: val.constructor }); val.$__.wasPopulated = true; didPopulate = true; } let popOpts; if (schema.options && Array.isArray(schema.options[this.schema.options.typeKey]) && schema.options[this.schema.options.typeKey].length && schema.options[this.schema.options.typeKey][0].ref && _isManuallyPopulatedArray(val, schema.options[this.schema.options.typeKey][0].ref)) { if (this.ownerDocument) { popOpts = { [populateModelSymbol]: val[0].constructor }; this.ownerDocument().populated(this.$__fullPath(path), val.map(function(v) { return v._id; }), popOpts); } else { popOpts = { [populateModelSymbol]: val[0].constructor }; this.populated(path, val.map(function(v) { return v._id; }), popOpts); } for (const doc of val) { doc.$__.wasPopulated = true; } didPopulate = true; } if (this.schema.singleNestedPaths[path] == null) { // If this path is underneath a single nested schema, we'll call the setter // later in `$__set()` because we don't take `_doc` when we iterate through // a single nested doc. That's to make sure we get the correct context. // Otherwise we would double-call the setter, see gh-7196. val = schema.applySetters(val, this, false, priorVal); } if (schema.$isMongooseDocumentArray && Array.isArray(val) && val.length > 0 && val[0] != null && val[0].$__ != null && val[0].$__.populated != null) { const populatedPaths = Object.keys(val[0].$__.populated); for (const populatedPath of populatedPaths) { this.populated(path + '.' + populatedPath, val.map(v => v.populated(populatedPath)), val[0].$__.populated[populatedPath].options); } didPopulate = true; } if (!didPopulate && this.$__.populated) { // If this array partially contains populated documents, convert them // all to ObjectIds re: #8443 if (Array.isArray(val) && this.$__.populated[path]) { for (let i = 0; i < val.length; ++i) { if (val[i] instanceof Document) { val[i] = val[i]._id; } } } delete this.$__.populated[path]; } if (schema.$isSingleNested && val != null) { _checkImmutableSubpaths(val, schema, priorVal); } 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) { this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); if (this.$__.savedState != null) { if (!this.isNew && !this.$__.savedState.hasOwnProperty(path)) { this.$__.savedState[path] = priorVal; } else if (this.$__.savedState.hasOwnProperty(path) && utils.deepEqual(val, this.$__.savedState[path])) { this.unmarkModified(path); } } } 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; } for (const el of val) { if (!(el instanceof Document)) { return false; } const modelName = el.constructor.modelName; if (modelName == null) { return false; } if (el.constructor.modelName != ref && el.constructor.baseModelName != ref) { return false; } } return true; } /** * Sets the value of a path, or many paths. * * ####Example: * * // path, value * doc.set(path, value) * * // object * doc.set({ * path : value * , path2 : { * path : value * } * }) * * // on-the-fly cast to number * doc.set(path, value, Number) * * // on-the-fly cast to string * doc.set(path, value, String) * * // changing strict mode behavior * doc.set(path, value, { strict: false }); * * @param {String|Object} path path or object of key/vals to set * @param {Any} val the value to set * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes * @param {Object} [options] optionally specify options that modify the behavior of the set * @api public * @method set * @memberOf Document * @instance */ Document.prototype.set = Document.prototype.$set; /** * Determine if we should mark this change as modified. * * @return {Boolean} * @api private * @method $__shouldModify * @memberOf Document * @instance */ Document.prototype.$__shouldModify = function(pathToMark, path, constructing, parts, schema, val, priorVal) { if (this.isNew) { return true; } // Re: the note about gh-7196, `val` is the raw value without casting or // setters if the full path is under a single nested subdoc because we don't // want to double run setters. So don't set it as modified. See gh-7264. if (this.schema.singleNestedPaths[path] != null) { return false; } 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, constructing, parts, schema, val, priorVal) { Embedded = Embedded || require('./types/embedded'); const shouldModify = this.$__shouldModify(pathToMark, path, constructing, parts, schema, val, priorVal); const _this = this; if (shouldModify) { this.markModified(pathToMark); // handle directly setting arrays (gh-1126) MongooseArray || (MongooseArray = require('./types/array')); if (val && val.isMongooseArray) { val._registerAtomic('$set', val); // Update embedded document parent references (gh-5189) if (val.isMongooseDocumentArray) { val.forEach(function(item) { item && item.__parentArray && (item.__parentArray = val); }); } // Small hack for gh-1638: if we're overwriting the entire array, ignore // paths that were modified before the array overwrite this.$__.activePaths.forEach(function(modifiedPath) { if (modifiedPath.startsWith(path + '.')) { _this.$__.activePaths.ignore(modifiedPath); } }); } } let obj = this._doc; let i = 0; const l = parts.length; let cur = ''; for (; i < l; i++) { const next = i + 1; const last = next === l; cur += (cur ? '.' + parts[i] : parts[i]); if (specialProperties.has(parts[i])) { return; } if (last) { if (obj instanceof Map) { obj.set(parts[i], val); } else { obj[parts[i]] = val; } } else { if (utils.isPOJO(obj[parts[i]])) { obj = obj[parts[i]]; } else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) { obj = obj[parts[i]]; } else if (obj[parts[i]] && obj[parts[i]].$isSingleNested) { obj = obj[parts[i]]; } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) { obj = obj[parts[i]]; } else { obj[parts[i]] = obj[parts[i]] || {}; obj = obj[parts[i]]; } } } }; /** * 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) { let adhoc; options = options || {}; if (type) { adhoc = this.schema.interpretAsType(path, type, this.schema.options); } let schema = this.$__path(path); if (schema == null) { schema = this.schema.virtualpath(path); } if (schema instanceof MixedSchema) { const virtual = this.schema.virtualpath(path); if (virtual != null) { schema = virtual; } } const pieces = path.split('.'); let 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 (let i = 0, l = pieces.length; i < l; i++) { if (obj && obj._doc) { obj = obj._doc; } if (obj == null) { obj = void 0; } else if (obj instanceof Map) { obj = obj.get(pieces[i], { getters: false }); } else if (i === l - 1) { obj = utils.getValue(pieces[i], obj); } else { obj = obj[pieces[i]]; } } 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; /** * Returns the schematype for the given `path`. * * @param {String} path * @api private * @method $__path * @memberOf Document * @instance */ Document.prototype.$__path = function(path) { const adhocs = this.$__.adhocPaths; const adhocType = adhocs && adhocs.hasOwnProperty(path) ? adhocs[path] : null; 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](./schematypes.html#mixed) types._ * * ####Example: * * doc.mixed.type = 'changed'; * doc.markModified('mixed.type'); * doc.save() // changes to mixed.type are now persisted * * @param {String} path the path to mark modified * @param {Document} [scope] the scope to run validators with * @api public */ Document.prototype.markModified = function(path, scope) { this.$__.activePaths.modify(path); if (scope != null && !this.ownerDocument) { this.$__.pathsToScopes[path] = scope; } }; /** * Clears the modified state on the specified path. * * ####Example: * * doc.foo = 'bar'; * doc.unmarkModified('foo'); * doc.save(); // changes to foo will not be persisted * * @param {String} path the path to unmark modified * @api public */ Document.prototype.unmarkModified = function(path) { this.$__.activePaths.init(path); delete this.$__.pathsToScopes[path]; }; /** * 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) { const isEmptyOptions = { minimize: true, virtuals: false, getters: false, transform: false }; if (arguments.length > 0) { const v = this.get(path); if (v == null) { return true; } if (typeof v !== 'object') { return false; } if (utils.isPOJO(v)) { return _isEmpty(v); } return Object.keys(v.toObject(isEmptyOptions)).length === 0; } 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 (const key of Object.keys(v)) { if (!_isEmpty(v[key])) { return false; } } return true; } /** * Returns the list of paths that have been modified. * * @param {Object} [options] * @param {Boolean} [options.includeChildren=false] if true, returns children of modified paths as well. For example, if false, the list of modified paths for `doc.colors = { primary: 'blue' };` will **not** contain `colors.primary`. If true, `modifiedPaths()` will return an array that contains `colors.primary`. * @return {Array} * @api public */ Document.prototype.modifiedPaths = function(options) { options = options || {}; const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); const _this = this; return directModifiedPaths.reduce(function(list, path) { const parts = path.split('.'); list = list.concat(parts.reduce(function(chains, part, i) { return chains.concat(parts.slice(0, i).concat(part).join('.')); }, []).filter(function(chain) { return (list.indexOf(chain) === -1); })); if (!options.includeChildren) { return list; } let cur = _this.get(path); if (cur != null && typeof cur === 'object') { if (cur._doc) { cur = cur._doc; } if (Array.isArray(cur)) { const len = cur.length; for (let i = 0; i < len; ++i) { if (list.indexOf(path + '.' + i) === -1) { list.push(path + '.' + i); if (cur[i] != null && cur[i].$__) { const modified = cur[i].modifiedPaths(); for (const childPath of modified) { list.push(path + '.' + i + '.' + childPath); } } } } } else { Object.keys(cur). filter(function(key) { return list.indexOf(path + '.' + key) === -1; }). forEach(function(key) { list.push(path + '.' + key); }); } } return list; }, []); }; Document.prototype[documentModifiedPaths] = Document.prototype.modifiedPaths; /** * Returns true if any of the given paths is modified, else false. If no arguments, returns `true` if any path * in this document is modified. * * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified. * * ####Example * * doc.set('documents.0.title', 'changed'); * doc.isModified() // true * doc.isModified('documents') // true * doc.isModified('documents.0.title') // true * doc.isModified('documents otherProp') // true * doc.isDirectModified('documents') // false * * @param {String} [path] optional * @return {Boolean} * @api public */ Document.prototype.isModified = function(paths, modifiedPaths) { if (paths) { if (!Array.isArray(paths)) { paths = paths.split(' '); } const modified = modifiedPaths || this[documentModifiedPaths](); const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); const isModifiedChild = paths.some(function(path) { return !!~modified.indexOf(path); }); return isModifiedChild || paths.some(function(path) { return directModifiedPaths.some(function(mod) { return mod === path || path.startsWith(mod + '.'); }); }); } return this.$__.activePaths.some('modify'); }; 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) { if (path == null) { return this.$__.activePaths.some('default'); } if (typeof path === 'string' && path.indexOf(' ') === -1) { return this.$__.activePaths.states.default.hasOwnProperty(path); } let paths = path; if (!Array.isArray(paths)) { paths = paths.split(' '); } return paths.some(path => this.$__.activePaths.states.default.hasOwnProperty(path)); }; /** * Getter/setter, determines whether the document was removed or not. * * ####Example: * product.remove(function (err, product) { * product.$isDeleted(); // true * product.remove(); // no-op, doesn't send anything to the db * * product.$isDeleted(false); * product.$isDeleted(); // false * product.remove(); // will execute a remove against the db * }) * * @param {Boolean} [val] optional, overrides whether mongoose thinks the doc is deleted * @return {Boolean} whether mongoose thinks this doc is deleted. * @method $isDeleted * @memberOf Document * @instance * @api public */ Document.prototype.$isDeleted = function(val) { if (arguments.length === 0) { return !!this.$__.isDeleted; } this.$__.isDeleted = !!val; return this; }; /** * Returns true if `path` was directly set and modified, else false. * * ####Example * * doc.set('documents.0.title', 'changed'); * doc.isDirectModified('documents.0.title') // true * doc.isDirectModified('documents') // false * * @param {String|Array} path * @return {Boolean} * @api public */ Document.prototype.isDirectModified = function(path) { if (path == null) { return this.$__.activePaths.some('modify'); } if (typeof path === 'string' && path.indexOf(' ') === -1) { return this.$__.activePaths.states.modify.hasOwnProperty(path); } let paths = path; if (!Array.isArray(paths)) { paths = paths.split(' '); } return paths.some(path => this.$__.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) { if (path == null) { return this.$__.activePaths.some('init'); } if (typeof path === 'string' && path.indexOf(' ') === -1) { return this.$__.activePaths.states.init.hasOwnProperty(path); } let paths = path; if (!Array.isArray(paths)) { paths = paths.split(' '); } return paths.some(path => this.$__.activePaths.states.init.hasOwnProperty(path)); }; /** * Checks if `path` was selected in the source query which initialized this document. * * ####Example * * Thing.findOne().select('name').exec(function (err, doc) { * doc.isSelected('name') // true * doc.isSelected('age') // false * }) * * @param {String|Array} path * @return {Boolean} * @api public */ Document.prototype.isSelected = function isSelected(path) { 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(p => this.$__isSelected(p)); } const paths = Object.keys(this.$__.selected); let inclusive = null; if (paths.length === 1 && paths[0] === '_id') { // only _id was selected. return this.$__.selected._id === 0; } for (const cur of paths) { 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; } const pathDot = path + '.'; for (const cur of paths) { 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) { 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(p => this.isDirectSelected(p)); } const paths = Object.keys(this.$__.selected); let inclusive = null; if (paths.length === 1 && paths[0] === '_id') { // only _id was selected. return this.$__.selected._id === 0; } for (const cur of paths) { 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 {Function} [callback] optional callback called after validation completes, passing an error if one occurred * @return {Promise} Promise * @api public */ Document.prototype.validate = function(pathsToValidate, options, callback) { let parallelValidate; this.$op = 'validate'; if (this.ownerDocument != null) { // Skip parallel validate check for subdocuments } else if (this.$__.validating) { parallelValidate = new ParallelValidateError(this, { parentStack: options && options.parentStack, conflictStack: this.$__.validating.stack }); } else { this.$__.validating = new ParallelValidateError(this, { parentStack: options && options.parentStack }); } if (typeof pathsToValidate === 'function') { callback = pathsToValidate; options = null; pathsToValidate = null; } else if (typeof options === 'function') { callback = options; options = pathsToValidate; pathsToValidate = null; } return promiseOrCallback(callback, cb => { if (parallelValidate != null) { return cb(parallelValidate); } this.$__validate(pathsToValidate, options, (error) => { this.$op = null; cb(error); }); }, this.constructor.events); }; /*! * ignore */ function _evaluateRequiredFunctions(doc) { Object.keys(doc.$__.activePaths.states.require).forEach(path => { const p = doc.schema.path(path); if (p != null && typeof p.originalRequiredValue === 'function') { doc.$__.cachedRequired[path] = p.originalRequiredValue.call(doc, doc); } }); } /*! * ignore */ function _getPathsToValidate(doc) { const skipSchemaValidators = {}; _evaluateRequiredFunctions(doc); // only validate required fields when necessary let paths = new Set(Object.keys(doc.$__.activePaths.states.require).filter(function(path) { if (!doc.$__isSelected(path) && !doc.isModified(path)) { return false; } if (path in doc.$__.cachedRequired) { return doc.$__.cachedRequired[path]; } return true; })); Object.keys(doc.$__.activePaths.states.init).forEach(addToPaths); Object.keys(doc.$__.activePaths.states.modify).forEach(addToPaths); Object.keys(doc.$__.activePaths.states.default).forEach(addToPaths); function addToPaths(p) { paths.add(p); } const subdocs = doc.$__getAllSubdocs(); const modifiedPaths = doc.modifiedPaths(); for (const subdoc of subdocs) { if (subdoc.$basePath) { // Remove child paths for now, because we'll be validating the whole // subdoc for (const p of paths) { if (p === null || p.startsWith(subdoc.$basePath + '.')) { paths.delete(p); } } if (doc.isModified(subdoc.$basePath, modifiedPaths) && !doc.isDirectModified(subdoc.$basePath) && !doc.$isDefault(subdoc.$basePath)) { paths.add(subdoc.$basePath); skipSchemaValidators[subdoc.$basePath] = true; } } } // from here on we're not removing items from paths // gh-661: if a whole array is modified, make sure to run validation on all // the children as well for (const path of paths) { const _pathType = doc.schema.path(path); if (!_pathType || !_pathType.$isMongooseArray || // To avoid potential performance issues, skip doc arrays whose children // are not required. `getPositionalPathType()` may be slow, so avoid // it unless we have a case of #6364 (_pathType.$isMongooseDocumentArray && !get(_pathType, 'schemaOptions.required'))) { continue; } const val = doc.$__getValue(path); _pushNestedArrayPaths(val, paths, path); } function _pushNestedArrayPaths(val, paths, path) { if (val != null) { const numElements = val.length; for (let j = 0; j < numElements; ++j) { if (Array.isArray(val[j])) { _pushNestedArrayPaths(val[j], paths, path + '.' + j); } else { paths.add(path + '.' + j); } } } } const flattenOptions = { skipArrays: true }; for (const pathToCheck of paths) { if (doc.schema.nested[pathToCheck]) { let _v = doc.$__getValue(pathToCheck); if (isMongooseObject(_v)) { _v = _v.toObject({ transform: false }); } const flat = flatten(_v, pathToCheck, flattenOptions, doc.schema); Object.keys(flat).forEach(addToPaths); } } for (const path of paths) { // Single nested paths (paths embedded under single nested subdocs) will // be validated on their own when we call `validate()` on the subdoc itself. // Re: gh-8468 if (doc.schema.singleNestedPaths.hasOwnProperty(path)) { paths.delete(path); continue; } const _pathType = doc.schema.path(path); if (!_pathType || !_pathType.$isSchemaMap) { continue; } const val = doc.$__getValue(path); if (val == null) { continue; } for (const key of val.keys()) { paths.add(path + '.' + key); } } paths = Array.from(paths); return [paths, skipSchemaValidators]; } /*! * ignore */ Document.prototype.$__validate = function(pathsToValidate, options, callback) { if (typeof pathsToValidate === 'function') { callback = pathsToValidate; options = null; pathsToValidate = null; } else if (typeof options === 'function') { callback = options; options = null; } const hasValidateModifiedOnlyOption = options && (typeof options === 'object') && ('validateModifiedOnly' in options); let shouldValidateModifiedOnly; if (hasValidateModifiedOnlyOption) { shouldValidateModifiedOnly = !!options.validateModifiedOnly; } else { shouldValidateModifiedOnly = this.schema.options.validateModifiedOnly; } const _this = this; const _complete = () => { let validationError = this.$__.validationError; this.$__.validationError = undefined; if (shouldValidateModifiedOnly && validationError != null) { // Remove any validation errors that aren't from modified paths const errors = Object.keys(validationError.errors); for (const errPath of errors) { if (!this.isModified(errPath)) { delete validationError.errors[errPath]; } } if (Object.keys(validationError.errors).length === 0) { validationError = void 0; } } this.$__.cachedRequired = {}; this.emit('validate', _this); this.constructor.emit('validate', _this); this.$__.validating = null; if (validationError) { for (const key in validationError.errors) { // Make sure cast errors persist if (!this[documentArrayParent] && validationError.errors[key] instanceof MongooseError.CastError) { this.invalidate(key, validationError.errors[key]); } } return validationError; } }; // only validate required fields when necessary const pathDetails = _getPathsToValidate(this); let paths = shouldValidateModifiedOnly ? pathDetails[0].filter((path) => this.isModified(path)) : pathDetails[0]; const skipSchemaValidators = pathDetails[1]; if (Array.isArray(pathsToValidate)) { paths = _handlePathsToValidate(paths, pathsToValidate); } if (paths.length === 0) { return process.nextTick(function() { const error = _complete(); if (error) { return _this.schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) { callback(error); }); } callback(null, _this); }); } const validated = {}; let total = 0; const complete = function() { const error = _complete(); if (error) { return _this.schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) { callback(error); }); } callback(null, _this); }; const validatePath = function(path) { if (path == null || validated[path]) { return; } validated[path] = true; total++; process.nextTick(function() { const 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; } let val = _this.$__getValue(path); // If you `populate()` and get back a null value, required validators // shouldn't fail (gh-8018). We should always fall back to the populated // value. let pop; if (val == null && (pop = _this.populated(path))) { val = pop; } const scope = path in _this.$__.pathsToScopes ? _this.$__.pathsToScopes[path] : _this; const doValidateOptions = { skipSchemaValidators: skipSchemaValidators[path], path: path, validateModifiedOnly: shouldValidateModifiedOnly }; schemaType.doValidate(val, function(err) { if (err && (!schemaType.$isMongooseDocumentArray || err.$isArrayValidatorError)) { if (schemaType.$isSingleNested && err instanceof ValidationError && schemaType.schema.options.storeSubdocValidationError === false) { return --total || complete(); } _this.invalidate(path, err, undefined, true); } --total || complete(); }, scope, doValidateOptions); }); }; const numPaths = paths.length; for (let i = 0; i < numPaths; ++i) { validatePath(paths[i]); } }; /*! * ignore */ function _handlePathsToValidate(paths, pathsToValidate) { const _pathsToValidate = new Set(pathsToValidate); const parentPaths = new Map([]); for (const path of pathsToValidate) { if (path.indexOf('.') === -1) { continue; } const pieces = path.split('.'); let cur = pieces[0]; for (let i = 1; i < pieces.length; ++i) { // Since we skip subpaths under single nested subdocs to // avoid double validation, we need to add back the // single nested subpath if the user asked for it (gh-8626) parentPaths.set(cur, path); cur = cur + '.' + pieces[i]; } } const ret = []; for (const path of paths) { if (_pathsToValidate.has(path)) { ret.push(path); } else if (parentPaths.has(path)) { ret.push(parentPaths.get(path)); } } return ret; } /** * 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. * @return {ValidationError|undefined} ValidationError if there are errors during validation, or undefined if there is no error. * @api public */ Document.prototype.validateSync = function(pathsToValidate, options) { const _this = this; const hasValidateModifiedOnlyOption = options && (typeof options === 'object') && ('validateModifiedOnly' in options); let shouldValidateModifiedOnly; if (hasValidateModifiedOnlyOption) { shouldValidateModifiedOnly = !!options.validateModifiedOnly; } else { shouldValidateModifiedOnly = this.schema.options.validateModifiedOnly; } if (typeof pathsToValidate === 'string') { pathsToValidate = pathsToValidate.split(' '); } // only validate required fields when necessary const pathDetails = _getPathsToValidate(this); let paths = shouldValidateModifiedOnly ? pathDetails[0].filter((path) => this.isModified(path)) : pathDetails[0]; const skipSchemaValidators = pathDetails[1]; if (Array.isArray(pathsToValidate)) { paths = _handlePathsToValidate(paths, pathsToValidate); } const validating = {}; paths.forEach(function(path) { if (validating[path]) { return; } validating[path] = true; const p = _this.schema.path(path); if (!p) { return; } if (!_this.$isValid(path)) { return; } const val = _this.$__getValue(path); const err = p.doValidateSync(val, _this, { skipSchemaValidators: skipSchemaValidators[path], path: path, validateModifiedOnly: shouldValidateModifiedOnly }); if (err && (!p.$isMongooseDocumentArray || err.$isArrayValidatorError)) { if (p.$isSingleNested && err instanceof ValidationError && p.schema.options.storeSubdocValidationError === false) { return; } _this.invalidate(path, err, undefined, true); } }); const err = _this.$__.validationError; _this.$__.validationError = undefined; _this.emit('validate', _this); _this.constructor.emit('validate', _this); if (err) { for (const key in err.errors) { // Make sure cast errors persist if (err.errors[key] instanceof MongooseError.CastError) { _this.invalidate(key, err.errors[key]); } } } return err; }; /** * Marks a path as invalid, causing validation to fail. * * The `errorMsg` argument will become the message of the `ValidationError`. * * The `value` argument (if passed) will be available through the `ValidationError.value` property. * * doc.invalidate('size', 'must be less than 20', 14); * 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; } const keys = Object.keys(doc.$__.validationError.errors); for (const key of keys) { if (key.startsWith(path + '.')) { delete doc.$__.validationError.errors[key]; } } if (Object.keys(doc.$__.validationError.errors).length === 0) { doc.$__.validationError = null; } } /*! * ignore */ function _checkImmutableSubpaths(subdoc, schematype, priorVal) { const schema = schematype.schema; if (schema == null) { return; } for (const key of Object.keys(schema.paths)) { const path = schema.paths[key]; if (path.$immutableSetter == null) { continue; } const oldVal = priorVal == null ? void 0 : priorVal.$__getValue(key); // Calling immutableSetter with `oldVal` even though it expects `newVal` // is intentional. That's because `$immutableSetter` compares its param // to the current value. path.$immutableSetter.call(subdoc, oldVal); } } /** * Saves this document by inserting a new document into the database if [document.isNew](/docs/api.html#document_Document-isNew) is `true`, * or sends an [updateOne](/docs/api.html#document_Document-updateOne) operation **only** with the modifications to the database, it does not replace the whole document in the latter case. * * ####Example: * * product.sold = Date.now(); * product = await product.save(); * * If save is successful, the returned promise will fulfill with the document * saved. * * ####Example: * * const newProduct = await product.save(); * newProduct === product; // true * * @param {Object} [options] options optional options * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead. * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. * @param {Boolean} [options.validateModifiedOnly=false] If `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths. * @param {Number|String} [options.w] set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern). * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names) * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`. * @param {Function} [fn] optional callback * @method save * @memberOf Document * @instance * @throws {DocumentNotFoundError} if this [save updates an existing document](api.html#document_Document-isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating). * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise. * @api public * @see middleware http://mongoosejs.com/docs/middleware.html */ /** * Checks if a path is invalid * * @param {String|Array} path the field to check * @method $isValid * @memberOf Document * @instance * @api private */ Document.prototype.$isValid = function(path) { if (this.$__.validationError == null || Object.keys(this.$__.validationError.errors).length === 0) { return true; } if (path == null) { return false; } if (path.indexOf(' ') !== -1) { path = path.split(' '); } if (Array.isArray(path)) { return path.some(p => this.$__.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() { let _this = this; DocumentArray || (DocumentArray = require('./types/documentarray')); this.$__.activePaths .map('init', 'modify', function(i) { return _this.$__getValue(i); }) .filter(function(val) { return val && val instanceof Array && val.isMongooseDocumentArray && val.length; }) .forEach(function(array) { let i = array.length; while (i--) { const doc = array[i]; if (!doc) { continue; } doc.$__reset(); } _this.$__.activePaths.init(array.$path()); array[arrayAtomicsBackupSymbol] = array[arrayAtomicsSymbol]; array[arrayAtomicsSymbol] = {}; }); this.$__.activePaths. map('init', 'modify', function(i) { return _this.$__getValue(i); }). filter(function(val) { return val && val.$isSingleNested; }). forEach(function(doc) { doc.$__reset(); _this.$__.activePaths.init(doc.$basePath); }); // clear atomics this.$__dirty().forEach(function(dirt) { const 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; for (const dirt of this.$__dirty()) { const type = dirt.value; if (type && type[arrayAtomicsSymbol] && type[arrayAtomicsBackupSymbol]) { type[arrayAtomicsSymbol] = type[arrayAtomicsBackupSymbol]; } } for (const subdoc of this.$__getAllSubdocs()) { subdoc.$__undoReset(); } }; /** * Returns this documents dirty paths / vals. * * @api private * @method $__dirty * @memberOf Document * @instance */ Document.prototype.$__dirty = function() { const _this = this; let all = this.$__.activePaths.map('modify', function(path) { return { path: path, value: _this.$__getValue(path), schema: _this.$__path(path) }; }); // gh-2558: if we had to set a default and the value is not undefined, // we have to save as well all = all.concat(this.$__.activePaths.map('default', function(path) { if (path === '_id' || _this.$__getValue(path) == null) { return; } return { path: path, value: _this.$__getValue(path), schema: _this.$__path(path) }; })); // Sort dirty paths in a flat hierarchy. all.sort(function(a, b) { return (a.path < b.path ? -1 : (a.path > b.path ? 1 : 0)); }); // Ignore "foo.a" if "foo" is dirty already. const minimal = []; let lastPath; let top; all.forEach(function(item) { if (!item) { return; } if (lastPath == null || item.path.indexOf(lastPath) !== 0) { lastPath = item.path + '.'; minimal.push(item); top = item; } else if (top != null && top.value != null && top.value[arrayAtomicsSymbol] != null && top.value.hasAtomics()) { // special case for top level MongooseArrays // the `top` array itself and a sub path of `top` are being modified. // the only way to honor all of both modifications is through a $set // of entire array. top.value[arrayAtomicsSymbol] = {}; top.value[arrayAtomicsSymbol].$set = top.value; } }); top = lastPath = null; return minimal; }; /** * Assigns/compiles `schema` into this documents prototype. * * @param {Schema} schema * @api private * @method $__setSchema * @memberOf Document * @instance */ Document.prototype.$__setSchema = function(schema) { schema.plugin(idGetter, { deduplicate: true }); compile(schema.tree, this, undefined, schema.options); // Apply default getters if virtual doesn't have any (gh-6262) for (const key of Object.keys(schema.virtuals)) { schema.virtuals[key]._applyDefaultGetters(); } 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 = require('./types/documentarray')); // validate all document arrays. return this.$__.activePaths .map('init', 'modify', function(i) { return this.$__getValue(i); }.bind(this)) .filter(function(val) { return val && val instanceof Array && val.isMongooseDocumentArray && val.length; }).reduce(function(seed, array) { return seed.concat(array); }, []) .filter(function(doc) { return doc; }); }; /** * Get all subdocs (by bfs) * * @api private * @method $__getAllSubdocs * @memberOf Document * @instance */ Document.prototype.$__getAllSubdocs = function() { DocumentArray || (DocumentArray = require('./types/documentarray')); Embedded = Embedded || require('./types/embedded'); function docReducer(doc, seed, path) { let val = doc; if (path) { if (doc instanceof Document && doc[documentSchemaSymbol].paths[path]) { val = doc._doc[path]; } else { val = doc[path]; } } if (val instanceof Embedded) { seed.push(val); } else if (val instanceof Map) { seed = Array.from(val.keys()).reduce(function(seed, path) { return docReducer(val.get(path), seed, null); }, seed); } else if (val && val.$isSingleNested) { seed = Object.keys(val._doc).reduce(function(seed, path) { return docReducer(val._doc, seed, path); }, seed); seed.push(val); } else if (val && val.isMongooseDocumentArray) { val.forEach(function _docReduce(doc) { if (!doc || !doc._doc) { return; } seed = Object.keys(doc._doc).reduce(function(seed, path) { return docReducer(doc._doc, seed, path); }, seed); if (doc instanceof Embedded) { seed.push(doc); } }); } else if (val instanceof Document && val.$__isNested) { seed = Object.keys(val).reduce(function(seed, path) { return docReducer(val, seed, path); }, seed); } return seed; } const _this = this; const subDocs = Object.keys(this._doc).reduce(function(seed, path) { return docReducer(_this, seed, path); }, []); return subDocs; }; /*! * Runs queued functions */ function applyQueue(doc) { const q = doc.schema && doc.schema.callQueue; if (!q.length) { return; } for (const pair of q) { if (pair[0] !== 'pre' && pair[0] !== 'post' && pair[0] !== 'on') { doc[pair[0]].apply(doc, pair[1]); } } } /*! * 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) { let defaultOptions = { transform: true, flattenDecimals: true }; const path = json ? 'toJSON' : 'toObject'; const baseOptions = get(this, 'constructor.base.options.' + path, {}); const schemaOptions = get(this, 'schema.options', {}); // merge base default options with Schema's set default options if available. // `clone` is necessary here because `utils.options` directly modifies the second input. defaultOptions = utils.options(defaultOptions, clone(baseOptions)); defaultOptions = utils.options(defaultOptions, clone(schemaOptions[path] || {})); // If options do not exist or is not an object, set it to empty object options = utils.isPOJO(options) ? clone(options) : {}; options._calledWithOptions = options._calledWithOptions || clone(options); if (!('flattenMaps' in options)) { options.flattenMaps = defaultOptions.flattenMaps; } let _minimize; if (options._calledWithOptions.minimize != null) { _minimize = options.minimize; } else if (defaultOptions.minimize != null) { _minimize = defaultOptions.minimize; } else { _minimize = schemaOptions.minimize; } // The original options that will be passed to `clone()`. Important because // `clone()` will recursively call `$toObject()` on embedded docs, so we // need the original options the user passed in, plus `_isNested` and // `_parentOptions` for checking whether we need to depopulate. const cloneOptions = Object.assign(utils.clone(options), { _isNested: true, json: json, minimize: _minimize }); if (utils.hasUserDefinedProperty(options, 'getters')) { cloneOptions.getters = options.getters; } if (utils.hasUserDefinedProperty(options, 'virtuals')) { cloneOptions.virtuals = options.virtuals; } const depopulate = options.depopulate || get(options, '_parentOptions.depopulate', false); // _isNested will only be true if this is not the top level document, we // should never depopulate if (depopulate && options._isNested && this.$__.wasPopulated) { // populated paths that we set to a document return clone(this._id, cloneOptions); } // 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; const gettersOptions = Object.assign({}, cloneOptions); gettersOptions._skipSingleNestedGetters = false; // remember the root transform function // to save it from being overwritten by sub-transform functions const originalTransform = options.transform; let 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]; } let 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)) { const 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') { const 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](http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html) for proper storage. * * ####Options: * * - `getters` apply all getters (path and virtual getters), defaults to false * - `aliases` apply all aliases if `virtuals=true`, defaults to true * - `virtuals` apply virtual getters (can override `getters` option), defaults to false * - `minimize` remove empty objects, defaults to true * - `transform` a transform function to apply to the resulting document before returning * - `depopulate` depopulate any populated paths, replacing them with their original refs, defaults to false * - `versionKey` whether to include the version key, defaults to true * - `flattenMaps` convert Maps to POJOs. Useful if you want to JSON.stringify() the result of toObject(), defaults to false * - `useProjection` set to `true` to omit fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema. * * ####Getters/Virtuals * * Example of only applying path getters * * doc.toObject({ getters: true, virtuals: false }) * * Example of only applying virtual getters * * doc.toObject({ virtuals: true }) * * Example of applying both path and virtual getters * * doc.toObject({ getters: true }) * * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument. * * schema.set('toObject', { virtuals: true }) * * ####Transform * * We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function. * * Transform functions receive three arguments * * function (doc, ret, options) {} * * - `doc` The mongoose document which is being converted * - `ret` The plain object representation which has been converted * - `options` The options in use (either schema options or the options passed inline) * * ####Example * * // specify the transform schema option * if (!schema.options.toObject) schema.options.toObject = {}; * schema.options.toObject.transform = function (doc, ret, options) { * // remove the _id of every document before returning the result * delete ret._id; * return ret; * } * * // without the transformation in the schema * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } * * // with the transformation * doc.toObject(); // { name: 'Wreck-it Ralph' } * * With transformations we can do a lot more than remove properties. We can even return completely new customized objects: * * if (!schema.options.toObject) schema.options.toObject = {}; * schema.options.toObject.transform = function (doc, ret, options) { * return { movie: ret.name } * } * * // without the transformation in the schema * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } * * // with the transformation * doc.toObject(); // { movie: 'Wreck-it Ralph' } * * _Note: if a transform function returns `undefined`, the return value will be ignored._ * * Transformations may also be applied inline, overridding any transform set in the options: * * function xform (doc, ret, options) { * return { inline: ret.name, custom: true } * } * * // pass the transform as an inline option * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true } * * If you want to skip transformations, use `transform: false`: * * schema.options.toObject.hide = '_id'; * schema.options.toObject.transform = function (doc, ret, options) { * if (options.hide) { * options.hide.split(' ').forEach(function (prop) { * delete ret[prop]; * }); * } * return ret; * } * * const doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }); * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' } * doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' } * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' } * * If you pass a transform in `toObject()` options, Mongoose will apply the transform * to [subdocuments](/docs/subdocs.html) in addition to the top-level document. * Similarly, `transform: false` skips transforms for all subdocuments. * Note that this is behavior is different for transforms defined in the schema: * if you define a transform in `schema.options.toObject.transform`, that transform * will **not** apply to subdocuments. * * const memberSchema = new Schema({ name: String, email: String }); * const groupSchema = new Schema({ members: [memberSchema], name: String, email }); * const Group = mongoose.model('Group', groupSchema); * * const doc = new Group({ * name: 'Engineering', * email: 'dev@mongoosejs.io', * members: [{ name: 'Val', email: 'val@mongoosejs.io' }] * }); * * // Removes `email` from both top-level document **and** array elements * // { name: 'Engineering', members: [{ name: 'Val' }] } * doc.toObject({ transform: (doc, ret) => { delete ret.email; return ret; } }); * * Transforms, like all of these options, are also available for `toJSON`. See [this guide to `JSON.stringify()`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html) to learn why `toJSON()` and `toObject()` are separate functions. * * See [schema options](/docs/guide.html#toObject) for some more details. * * _During save, no custom options are applied to the document before being sent to the database._ * * @param {Object} [options] * @param {Boolean} [options.getters=false] if true, apply all getters, including virtuals * @param {Boolean} [options.virtuals=false] if true, apply virtuals, including aliases. Use `{ getters: true, virtuals: false }` to just apply getters, not virtuals * @param {Boolean} [options.aliases=true] if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`. * @param {Boolean} [options.minimize=true] if true, omit any empty objects from the output * @param {Function|null} [options.transform=null] if set, mongoose will call this function to allow you to transform the returned object * @param {Boolean} [options.depopulate=false] if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths. * @param {Boolean} [options.versionKey=true] if false, exclude the version key (`__v` by default) from the output * @param {Boolean} [options.flattenMaps=false] if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`. * @param {Boolean} [options.useProjection=false] - If true, omits fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema. * @return {Object} js object * @see mongodb.Binary http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html * @api public * @memberOf Document * @instance */ Document.prototype.toObject = function(options) { return this.$toObject(options); }; /*! * Minimizes an object, removing undefined values and empty objects * * @param {Object} object to minimize * @return {Object} */ function minimize(obj) { const keys = Object.keys(obj); let i = keys.length; let hasKeys; let key; let val; while (i--) { key = keys[i]; val = obj[key]; if (utils.isObject(val) && !Buffer.isBuffer(val)) { obj[key] = minimize(val); } 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) { const schema = self.schema; const paths = Object.keys(schema.virtuals); let i = paths.length; const numPaths = i; let path; let assignPath; let cur = self._doc; let v; const aliases = get(toObjectOptions, 'aliases', true); if (!cur) { return json; } options = options || {}; for (i = 0; i < numPaths; ++i) { path = paths[i]; // 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.substr(options.path.length + 1); } const parts = assignPath.split('.'); v = clone(self.get(path), options); if (v === void 0) { continue; } const plen = parts.length; cur = json; for (let j = 0; j < plen - 1; ++j) { cur[parts[j]] = cur[parts[j]] || {}; cur = cur[parts[j]]; } cur[parts[plen - 1]] = v; } return json; } /*! * Applies virtuals properties to `json`. * * @param {Document} self * @param {Object} json * @return {Object} `json` */ function applyGetters(self, json, options) { const schema = self.schema; const paths = Object.keys(schema.paths); let i = paths.length; let path; let cur = self._doc; let v; if (!cur) { return json; } while (i--) { path = paths[i]; const parts = path.split('.'); const plen = parts.length; const last = plen - 1; let branch = json; let part; cur = self._doc; if (!self.$__isSelected(path)) { continue; } for (let ii = 0; ii < plen; ++ii) { part = parts[ii]; v = cur[part]; if (ii === last) { const val = self.get(path); branch[part] = clone(val, options); } else if (v == null) { if (part in cur) { branch[part] = v; } break; } else { branch = branch[part] || (branch[part] = {}); } cur = v; } } return json; } /*! * Applies schema type transforms to `json`. * * @param {Document} self * @param {Object} json * @return {Object} `json` */ function applySchemaTypeTransforms(self, json) { const schema = self.schema; const paths = Object.keys(schema.paths || {}); const cur = self._doc; if (!cur) { return json; } for (const path of paths) { const schematype = schema.paths[path]; if (typeof schematype.options.transform === 'function') { const val = self.get(path); const transformedValue = schematype.options.transform.call(self, val); throwErrorIfPromise(path, transformedValue); utils.setValue(path, transformedValue, json); } else if (schematype.$embeddedSchemaType != null && typeof schematype.$embeddedSchemaType.options.transform === 'function') { const vals = [].concat(self.get(path)); const transform = schematype.$embeddedSchemaType.options.transform; for (let i = 0; i < vals.length; ++i) { const transformedValue = transform.call(self, vals[i]); vals[i] = transformedValue; throwErrorIfPromise(path, transformedValue); } json[path] = vals; } } 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) { const schema = self.schema; const paths = Object.keys(schema.paths || {}); const cur = self._doc; if (!cur) { return json; } let selected = self.$__.selected; if (selected === void 0) { selected = {}; queryhelpers.applyPaths(selected, schema); } if (selected == null || Object.keys(selected).length === 0) { return json; } for (const path of paths) { 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). * * This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument. * * schema.set('toJSON', { virtuals: true }) * * See [schema options](/docs/guide.html#toJSON) for details. * * @param {Object} options * @return {Object} * @see Document#toObject #document_Document-toObject * @see JSON.stringify() in JavaScript https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html * @api public * @memberOf Document * @instance */ Document.prototype.toJSON = function(options) { return this.$toObject(options, true); }; /** * If this document is a subdocument or populated document, returns the document's * parent. Returns `undefined` otherwise. * * @api public * @method parent * @memberOf Document * @instance */ Document.prototype.parent = function() { return this.$__.parent; }; /** * Alias for `parent()`. If this document is a subdocument or populated * document, returns the document's parent. Returns `undefined` otherwise. * * @api public * @method $parent * @memberOf Document * @instance */ Document.prototype.$parent = Document.prototype.parent; /** * Helper for console.log * * @api public * @method inspect * @memberOf Document * @instance */ Document.prototype.inspect = function(options) { const isPOJO = utils.isPOJO(options); let opts; if (isPOJO) { opts = options; opts.minimize = false; } const ret = this.toObject(opts); 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() { const 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; } const tid = this.$__getValue('_id'); const docid = doc.$__ != null ? doc.$__getValue('_id') : doc; if (!tid && !docid) { return deepEqual(this, doc); } return tid && tid.equals ? tid.equals(docid) : tid === docid; }; /** * Populates document references, executing the `callback` when complete. * If you want to use promises instead, use this function with * [`execPopulate()`](#document_Document-execPopulate) * * ####Example: * * doc * .populate('company') * .populate({ * path: 'notes', * match: /airline/, * select: 'text', * model: 'modelName' * options: opts * }, function (err, user) { * assert(doc._id === user._id) // the document itself is passed * }) * * // summary * doc.populate(path) // not executed * doc.populate(options); // not executed * doc.populate(path, callback) // executed * doc.populate(options, callback); // executed * doc.populate(callback); // executed * doc.populate(options).execPopulate() // executed, returns promise * * * ####NOTE: * * Population does not occur unless a `callback` is passed *or* you explicitly * call `execPopulate()`. * Passing the same path a second time will overwrite the previous path options. * See [Model.populate()](#model_Model.populate) for explaination of options. * * @see Model.populate #model_Model.populate * @see Document.execPopulate #document_Document-execPopulate * @param {String|Object} [path] The path to populate or an options object * @param {Function} [callback] When passed, population is invoked * @api public * @return {Document} this * @memberOf Document * @instance */ Document.prototype.populate = function populate() { if (arguments.length === 0) { return this; } const pop = this.$__.populate || (this.$__.populate = {}); const args = utils.args(arguments); let fn; if (typeof args[args.length - 1] === 'function') { fn = args.pop(); } // allow `doc.populate(callback)` if (args.length) { // use hash to remove duplicate paths const res = utils.populate.apply(null, args); for (const populateOptions of res) { pop[populateOptions.path] = populateOptions; } } if (fn) { const paths = utils.object.vals(pop); this.$__.populate = undefined; let topLevelModel = this.constructor; if (this.$__isNested) { topLevelModel = this.$__[scopeSymbol].constructor; const nestedPath = this.$__.nestedPath; paths.forEach(function(populateOptions) { populateOptions.path = nestedPath + '.' + populateOptions.path; }); } // Use `$session()` by default if the document has an associated session // See gh-6754 if (this.$session() != null) { const session = this.$session(); paths.forEach(path => { if (path.options == null) { path.options = { session: session }; return; } if (!('session' in path.options)) { path.options.session = session; } }); } topLevelModel.populate(this, paths, fn); } return this; }; /** * Explicitly executes population and returns a promise. Useful for promises integration. * * ####Example: * * const promise = doc. * populate('company'). * populate({ * path: 'notes', * match: /airline/, * select: 'text', * model: 'modelName' * options: opts * }). * execPopulate(); * * // summary * doc.execPopulate().then(resolve, reject); * * // you can also use doc.execPopulate(options) as a shorthand for * // doc.populate(options).execPopulate() * * * ####Example: * const promise = doc.execPopulate({ path: 'company', select: 'employees' }); * * // summary * promise.then(resolve,reject); * * @see Document.populate #document_Document-populate * @api public * @param {Function} [callback] optional callback. If specified, a promise will **not** be returned * @return {Promise} promise that resolves to the document when population is done * @memberOf Document * @instance */ Document.prototype.execPopulate = function(callback) { const isUsingShorthand = callback != null && typeof callback !== 'function'; if (isUsingShorthand) { return this.populate.apply(this, arguments).execPopulate(); } return promiseOrCallback(callback, cb => { this.populate(cb); }, this.constructor.events); }; /** * Gets _id(s) used during population of the given `path`. * * ####Example: * * Model.findOne().populate('author').exec(function (err, doc) { * console.log(doc.author.name) // Dr.Seuss * console.log(doc.populated('author')) // '5144cf8050f071d979c118a7' * }) * * If the path was not populated, returns `undefined`. * * @param {String} path * @return {Array|ObjectId|Number|Buffer|String|undefined} * @memberOf Document * @instance * @api public */ Document.prototype.populated = function(path, val, options) { // val and options are internal if (val === null || val === void 0) { if (!this.$__.populated) { return undefined; } const v = this.$__.populated[path]; if (v) { return v.value; } return undefined; } // internal if (val === true) { if (!this.$__.populated) { return undefined; } return this.$__.populated[path]; } this.$__.populated || (this.$__.populated = {}); this.$__.populated[path] = { value: val, options: options }; // If this was a nested populate, make sure each populated doc knows // about its populated children (gh-7685) const pieces = path.split('.'); for (let i = 0; i < pieces.length - 1; ++i) { const subpath = pieces.slice(0, i + 1).join('.'); const subdoc = this.get(subpath); if (subdoc != null && subdoc.$__ != null && this.populated(subpath)) { const rest = pieces.slice(i + 1).join('.'); subdoc.populated(rest, val, options); // No need to continue because the above recursion should take care of // marking the rest of the docs as populated break; } } return val; }; /** * 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 populated, this is a no-op. * * @param {String} path * @return {Document} this * @see Document.populate #document_Document-populate * @api public * @memberOf Document * @instance */ Document.prototype.depopulate = function(path) { if (typeof path === 'string') { path = path.split(' '); } let populatedIds; const virtualKeys = this.$$populatedVirtuals ? Object.keys(this.$$populatedVirtuals) : []; const populated = get(this, '$__.populated', {}); if (arguments.length === 0) { // Depopulate all for (const virtualKey of virtualKeys) { delete this.$$populatedVirtuals[virtualKey]; delete this._doc[virtualKey]; delete populated[virtualKey]; } const keys = Object.keys(populated); for (const key of keys) { populatedIds = this.populated(key); if (!populatedIds) { continue; } delete populated[key]; this.$set(key, populatedIds); } return this; } for (const singlePath of path) { populatedIds = this.populated(singlePath); delete populated[singlePath]; if (virtualKeys.indexOf(singlePath) !== -1) { delete this.$$populatedVirtuals[singlePath]; delete this._doc[singlePath]; } else if (populatedIds) { this.$set(singlePath, populatedIds); } } 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() { const delta = this.$__delta(); const changes = delta ? delta[1] : {}; return changes; }; /*! * Module exports. */ Document.ValidationError = ValidationError; module.exports = exports = Document; }).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")},require('_process')) },{"../../is-buffer/index.js":179,"./error/index":204,"./error/objectExpected":209,"./error/objectParameter":210,"./error/parallelValidate":213,"./error/strict":214,"./error/validation":215,"./error/validator":216,"./helpers/common":220,"./helpers/document/cleanModifiedSubpaths":225,"./helpers/document/compile":226,"./helpers/document/getEmbeddedDiscriminatorPath":227,"./helpers/document/handleSpreadDoc":228,"./helpers/get":229,"./helpers/isPromise":235,"./helpers/projection/isDefiningProjection":239,"./helpers/projection/isExclusive":240,"./helpers/promiseOrCallback":241,"./helpers/symbols":252,"./internal":256,"./options":257,"./plugins/idGetter":271,"./queryhelpers":273,"./schema":274,"./schema/mixed":284,"./types/array":297,"./types/documentarray":301,"./types/embedded":302,"./utils":307,"./virtualtype":308,"_process":325,"events":177,"mpath":310,"util":332}],195:[function(require,module,exports){ 'use strict'; /* eslint-env browser */ /*! * Module dependencies. */ const Document = require('./document.js'); const BrowserDocument = require('./browserDocument.js'); let 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; }; },{"./browserDocument.js":186,"./document.js":194}],196:[function(require,module,exports){ 'use strict'; /*! * ignore */ let driver = null; module.exports.get = function() { return driver; }; module.exports.set = function(v) { driver = v; }; },{}],197:[function(require,module,exports){ /*! * ignore */ 'use strict'; module.exports = function() {}; },{}],198:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const Binary = require('bson').Binary; /*! * Module exports. */ module.exports = exports = Binary; },{"bson":110}],199:[function(require,module,exports){ /*! * ignore */ 'use strict'; module.exports = require('bson').Decimal128; },{"bson":110}],200:[function(require,module,exports){ /*! * Module exports. */ 'use strict'; exports.Binary = require('./binary'); exports.Collection = function() { throw new Error('Cannot create a collection from browser library'); }; exports.Decimal128 = require('./decimal128'); exports.ObjectId = require('./objectid'); exports.ReadPreference = require('./ReadPreference'); },{"./ReadPreference":197,"./binary":198,"./decimal128":199,"./objectid":201}],201:[function(require,module,exports){ /*! * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId * @constructor NodeMongoDbObjectId * @see ObjectId */ 'use strict'; const ObjectId = require('bson').ObjectID; /*! * Getter for convenience with populate, see gh-6115 */ Object.defineProperty(ObjectId.prototype, '_id', { enumerable: false, configurable: true, get: function() { return this; } }); /*! * ignore */ module.exports = exports = ObjectId; },{"bson":110}],202:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const MongooseError = require('./mongooseError'); const get = require('../helpers/get'); const util = require('util'); /** * Casting Error constructor. * * @param {String} type * @param {String} value * @inherits MongooseError * @api private */ class CastError extends MongooseError { constructor(type, value, path, reason, schemaType) { // If no args, assume we'll `init()` later. if (arguments.length > 0) { const stringValue = getStringValue(value); const messageFormat = getMessageFormat(schemaType); const msg = formatMessage(null, type, stringValue, path, messageFormat); super(msg); this.init(type, value, path, reason, schemaType); } else { super(formatMessage()); } } /*! * ignore */ init(type, value, path, reason, schemaType) { this.stringValue = getStringValue(value); this.messageFormat = getMessageFormat(schemaType); this.kind = type; this.value = value; this.path = path; this.reason = reason; } /*! * ignore * @param {Readonly} other */ copy(other) { this.messageFormat = other.messageFormat; this.stringValue = other.stringValue; this.kind = other.kind; this.value = other.value; this.path = other.path; this.reason = other.reason; this.message = other.message; } /*! * ignore */ setModel(model) { this.model = model; this.message = formatMessage(model, this.kind, this.stringValue, this.path, this.messageFormat); } } Object.defineProperty(CastError.prototype, 'name', { value: 'CastError' }); function getStringValue(value) { let stringValue = util.inspect(value); stringValue = stringValue.replace(/^'|'$/g, '"'); if (!stringValue.startsWith('"')) { stringValue = '"' + stringValue + '"'; } return stringValue; } function getMessageFormat(schemaType) { const messageFormat = get(schemaType, 'options.cast', null); if (typeof messageFormat === 'string') { return messageFormat; } } /*! * ignore */ function formatMessage(model, kind, stringValue, path, messageFormat) { if (messageFormat != null) { let ret = messageFormat. replace('{KIND}', kind). replace('{VALUE}', stringValue). replace('{PATH}', path); if (model != null) { ret = ret.replace('{MODEL}', model.modelName); } return ret; } else { let ret = 'Cast to ' + kind + ' failed for value ' + stringValue + ' at path "' + path + '"'; if (model != null) { ret += ' for model "' + model.modelName + '"'; } return ret; } } /*! * exports */ module.exports = CastError; },{"../helpers/get":229,"./mongooseError":207,"util":332}],203:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); class DivergentArrayError extends MongooseError { /*! * DivergentArrayError constructor. * @param {Array} paths */ constructor(paths) { const msg = 'For your own good, using `document.save()` to update an array ' + 'which was selected using an $elemMatch projection OR ' + 'populated using skip, limit, query conditions, or exclusion of ' + 'the _id field when the operation results in a $pop or $set of ' + 'the entire array is not supported. The following ' + 'path(s) would have been modified unsafely:\n' + ' ' + paths.join('\n ') + '\n' + 'Use Model.update() to update these arrays instead.'; // TODO write up a docs page (FAQ) and link to it super(msg); } } Object.defineProperty(DivergentArrayError.prototype, 'name', { value: 'DivergentArrayError' }); /*! * exports */ module.exports = DivergentArrayError; },{"./":204}],204:[function(require,module,exports){ 'use strict'; /** * MongooseError constructor. MongooseError is the base class for all * Mongoose-specific errors. * * ####Example: * const Model = mongoose.model('Test', new Schema({ answer: Number })); * const doc = new Model({ answer: 'not a number' }); * const err = doc.validateSync(); * * err instanceof mongoose.Error; // true * * @constructor Error * @param {String} msg Error message * @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error */ const MongooseError = require('./mongooseError'); /** * 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 = require('./messages'); // 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 = require('./notFound'); /** * An instance of this error class will be returned when mongoose failed to * cast a value. * * @api public * @memberOf Error * @static CastError */ MongooseError.CastError = require('./cast'); /** * 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 = require('./validation'); /** * 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 = require('./validator'); /** * 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 = require('./version'); /** * 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 = require('./parallelSave'); /** * 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 = require('./overwriteModel'); /** * Thrown when you try to access a model that has not been registered yet * * @api public * @memberOf Error * @static MissingSchemaError */ MongooseError.MissingSchemaError = require('./missingSchema'); /** * 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 = require('./divergentArray'); /** * 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 = require('./strict'); },{"./cast":202,"./divergentArray":203,"./messages":205,"./missingSchema":206,"./mongooseError":207,"./notFound":208,"./overwriteModel":211,"./parallelSave":212,"./strict":214,"./validation":215,"./validator":216,"./version":217}],205:[function(require,module,exports){ /** * 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 */ 'use strict'; const msg = module.exports = exports = {}; msg.DocumentNotFoundError = null; msg.general = {}; msg.general.default = 'Validator failed for path `{PATH}` with value `{VALUE}`'; msg.general.required = 'Path `{PATH}` is required.'; msg.Number = {}; msg.Number.min = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).'; msg.Number.max = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).'; msg.Number.enum = '`{VALUE}` is not a valid enum value for path `{PATH}`.'; msg.Date = {}; msg.Date.min = 'Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN}).'; msg.Date.max = 'Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX}).'; msg.String = {}; msg.String.enum = '`{VALUE}` is not a valid enum value for path `{PATH}`.'; msg.String.match = 'Path `{PATH}` is invalid ({VALUE}).'; msg.String.minlength = 'Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).'; msg.String.maxlength = 'Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH}).'; },{}],206:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); class MissingSchemaError extends MongooseError { /*! * MissingSchema Error constructor. * @param {String} name */ constructor(name) { const msg = 'Schema hasn\'t been registered for model "' + name + '".\n' + 'Use mongoose.model(name, schema)'; super(msg); } } Object.defineProperty(MissingSchemaError.prototype, 'name', { value: 'MissingSchemaError' }); /*! * exports */ module.exports = MissingSchemaError; },{"./":204}],207:[function(require,module,exports){ 'use strict'; /*! * ignore */ class MongooseError extends Error { } Object.defineProperty(MongooseError.prototype, 'name', { value: 'MongooseError' }); module.exports = MongooseError; },{}],208:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const MongooseError = require('./'); const util = require('util'); class DocumentNotFoundError extends MongooseError { /*! * OverwriteModel Error constructor. */ constructor(filter, model, numAffected, result) { let msg; const messages = MongooseError.messages; if (messages.DocumentNotFoundError != null) { msg = typeof messages.DocumentNotFoundError === 'function' ? messages.DocumentNotFoundError(filter, model) : messages.DocumentNotFoundError; } else { msg = 'No document found for query "' + util.inspect(filter) + '" on model "' + model + '"'; } super(msg); this.result = result; this.numAffected = numAffected; this.filter = filter; // Backwards compat this.query = filter; } } Object.defineProperty(DocumentNotFoundError.prototype, 'name', { value: 'DocumentNotFoundError' }); /*! * exports */ module.exports = DocumentNotFoundError; },{"./":204,"util":332}],209:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); class ObjectExpectedError extends MongooseError { /** * Strict mode error constructor * * @param {string} type * @param {string} value * @api private */ constructor(path, val) { const typeDescription = Array.isArray(val) ? 'array' : 'primitive value'; super('Tried to set nested object field `' + path + `\` to ${typeDescription} \`` + val + '` and strict mode is set to throw.'); this.path = path; } } Object.defineProperty(ObjectExpectedError.prototype, 'name', { value: 'ObjectExpectedError' }); module.exports = ObjectExpectedError; },{"./":204}],210:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); class ObjectParameterError extends MongooseError { /** * Constructor for errors that happen when a parameter that's expected to be * an object isn't an object * * @param {Any} value * @param {String} paramName * @param {String} fnName * @api private */ constructor(value, paramName, fnName) { super('Parameter "' + paramName + '" to ' + fnName + '() must be an object, got ' + value.toString()); } } Object.defineProperty(ObjectParameterError.prototype, 'name', { value: 'ObjectParameterError' }); module.exports = ObjectParameterError; },{"./":204}],211:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); class OverwriteModelError extends MongooseError { /*! * OverwriteModel Error constructor. * @param {String} name */ constructor(name) { super('Cannot overwrite `' + name + '` model once compiled.'); } } Object.defineProperty(OverwriteModelError.prototype, 'name', { value: 'OverwriteModelError' }); /*! * exports */ module.exports = OverwriteModelError; },{"./":204}],212:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const MongooseError = require('./'); class ParallelSaveError extends MongooseError { /** * ParallelSave Error constructor. * * @param {Document} doc * @api private */ constructor(doc) { const msg = 'Can\'t save() the same doc multiple times in parallel. Document: '; super(msg + doc._id); } } Object.defineProperty(ParallelSaveError.prototype, 'name', { value: 'ParallelSaveError' }); /*! * exports */ module.exports = ParallelSaveError; },{"./":204}],213:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const MongooseError = require('./mongooseError'); class ParallelValidateError extends MongooseError { /** * ParallelValidate Error constructor. * * @param {Document} doc * @api private */ constructor(doc) { const msg = 'Can\'t validate() the same doc multiple times in parallel. Document: '; super(msg + doc._id); } } Object.defineProperty(ParallelValidateError.prototype, 'name', { value: 'ParallelValidateError' }); /*! * exports */ module.exports = ParallelValidateError; },{"./mongooseError":207}],214:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); class StrictModeError extends MongooseError { /** * Strict mode error constructor * * @param {String} path * @param {String} [msg] * @param {Boolean} [immutable] * @inherits MongooseError * @api private */ constructor(path, msg, immutable) { msg = msg || 'Field `' + path + '` is not in schema and strict ' + 'mode is set to throw.'; super(msg); this.isImmutableError = !!immutable; this.path = path; } } Object.defineProperty(StrictModeError.prototype, 'name', { value: 'StrictModeError' }); module.exports = StrictModeError; },{"./":204}],215:[function(require,module,exports){ /*! * Module requirements */ 'use strict'; const MongooseError = require('./mongooseError'); const util = require('util'); class ValidationError extends MongooseError { /** * Document Validation Error * * @api private * @param {Document} [instance] * @inherits MongooseError */ constructor(instance) { let _message; if (instance && instance.constructor.name === 'model') { _message = instance.constructor.modelName + ' validation failed'; } else { _message = 'Validation failed'; } super(_message); this.errors = {}; this._message = _message; if (instance) { instance.errors = this.errors; } } /** * Console.log helper */ toString() { return this.name + ': ' + _generateMessage(this); } /*! * inspect helper */ inspect() { return Object.assign(new Error(this.message), this); } /*! * add message */ addError(path, error) { this.errors[path] = error; this.message = this._message + ': ' + _generateMessage(this); } } 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() { return Object.assign({}, this, { name: this.name, message: this.message }); } }); Object.defineProperty(ValidationError.prototype, 'name', { value: 'ValidationError' }); /*! * ignore */ function _generateMessage(err) { const keys = Object.keys(err.errors || {}); const len = keys.length; const msgs = []; let key; for (let i = 0; i < len; ++i) { key = keys[i]; if (err === err.errors[key]) { continue; } msgs.push(key + ': ' + err.errors[key].message); } return msgs.join(', '); } /*! * Module exports */ module.exports = ValidationError; },{"./mongooseError":207,"util":332}],216:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); class ValidatorError extends MongooseError { /** * Schema validator error * * @param {Object} properties * @api private */ constructor(properties) { let msg = properties.message; if (!msg) { msg = MongooseError.messages.general.default; } const message = formatMessage(msg, properties); super(message); 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; } /*! * toString helper * TODO remove? This defaults to `${this.name}: ${this.message}` */ toString() { return this.message; } /*! * Ensure `name` and `message` show up in toJSON output re: gh-9296 */ toJSON() { return Object.assign({ name: this.name, message: this.message }, this); } } 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); } const propertyNames = Object.keys(properties); for (const propertyName of propertyNames) { if (propertyName === 'message') { continue; } msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]); } return msg; } /*! * exports */ module.exports = ValidatorError; },{"./":204}],217:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const MongooseError = require('./'); class VersionError extends MongooseError { /** * Version Error constructor. * * @param {Document} doc * @param {Number} currentVersion * @param {Array} modifiedPaths * @api private */ constructor(doc, currentVersion, modifiedPaths) { const modifiedPathsStr = modifiedPaths.join(', '); super('No matching document found for id "' + doc._id + '" version ' + currentVersion + ' modifiedPaths "' + modifiedPathsStr + '"'); this.version = currentVersion; this.modifiedPaths = modifiedPaths; } } Object.defineProperty(VersionError.prototype, 'name', { value: 'VersionError' }); /*! * exports */ module.exports = VersionError; },{"./":204}],218:[function(require,module,exports){ '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 }; } const res = arrayDepth(arr[0]); for (let i = 1; i < arr.length; ++i) { const _res = arrayDepth(arr[i]); if (_res.min < res.min) { res.min = _res.min; } if (_res.max > res.max) { res.max = _res.max; } res.containsNonArrayItem = res.containsNonArrayItem || _res.containsNonArrayItem; } res.min = res.min + 1; res.max = res.max + 1; return res; } },{}],219:[function(require,module,exports){ 'use strict'; const cloneRegExp = require('regexp-clone'); const Decimal = require('../types/decimal128'); const ObjectId = require('../types/objectid'); const specialProperties = require('./specialProperties'); const isMongooseObject = require('./isMongooseObject'); const getFunctionName = require('./getFunctionName'); const isBsonType = require('./isBsonType'); const isObject = require('./isObject'); const symbols = require('./symbols'); const utils = require('../utils'); /*! * Object clone with Mongoose natives support. * * If options.minimize is true, creates a minimal data object. Empty objects and undefined values will not be cloned. This makes the data payload sent to MongoDB as small as possible. * * Functions are never cloned. * * @param {Object} obj the object to clone * @param {Object} options * @param {Boolean} isArrayChild true if cloning immediately underneath an array. Special case for minimize. * @return {Object} the cloned object * @api private */ function clone(obj, options, isArrayChild) { if (obj == null) { return obj; } if (Array.isArray(obj)) { return cloneArray(obj, options); } if (isMongooseObject(obj)) { // Single nested subdocs should apply getters later in `applyGetters()` // when calling `toObject()`. See gh-7442, gh-8295 if (options && options._skipSingleNestedGetters && obj.$isSingleNested) { options = Object.assign({}, options, { getters: false }); } if (utils.isPOJO(obj) && obj.$__ != null && obj._doc != null) { return obj._doc; } if (options && options.json && typeof obj.toJSON === 'function') { return obj.toJSON(options); } return obj.toObject(options); } if (obj.constructor) { switch (getFunctionName(obj.constructor)) { case 'Object': return cloneObject(obj, options, isArrayChild); case 'Date': return new obj.constructor(+obj); case 'RegExp': return cloneRegExp(obj); default: // ignore break; } } if (obj instanceof ObjectId) { return new ObjectId(obj.id); } if (isBsonType(obj, 'Decimal128')) { if (options && options.flattenDecimals) { return obj.toJSON(); } return Decimal.fromString(obj.toString()); } if (!obj.constructor && isObject(obj)) { // object created with Object.create(null) return cloneObject(obj, options, isArrayChild); } if (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 (obj.valueOf != null) { return obj.valueOf(); } return cloneObject(obj, options, isArrayChild); } module.exports = clone; /*! * ignore */ function cloneObject(obj, options, isArrayChild) { const minimize = options && options.minimize; const ret = {}; let hasKeys; for (const k of Object.keys(obj)) { if (specialProperties.has(k)) { continue; } // Don't pass `isArrayChild` down const val = clone(obj[k], options); if (!minimize || (typeof val !== 'undefined')) { if (minimize === false && typeof val === 'undefined') { delete ret[k]; } else { hasKeys || (hasKeys = true); ret[k] = val; } } } return minimize && !isArrayChild ? hasKeys && ret : ret; } function cloneArray(arr, options) { const ret = []; for (const item of arr) { ret.push(clone(item, options, true)); } return ret; } },{"../types/decimal128":300,"../types/objectid":305,"../utils":307,"./getFunctionName":230,"./isBsonType":232,"./isMongooseObject":233,"./isObject":234,"./specialProperties":251,"./symbols":252,"regexp-clone":326}],220:[function(require,module,exports){ (function (Buffer){(function (){ 'use strict'; /*! * Module dependencies. */ const Binary = require('../driver').get().Binary; const Decimal128 = require('../types/decimal128'); const ObjectId = require('../types/objectid'); const isMongooseObject = require('./isMongooseObject'); exports.flatten = flatten; exports.modifiedPaths = modifiedPaths; /*! * ignore */ function flatten(update, path, options, schema) { let keys; if (update && isMongooseObject(update) && !Buffer.isBuffer(update)) { keys = Object.keys(update.toObject({ transform: false, virtuals: false })); } else { keys = Object.keys(update || {}); } const numKeys = keys.length; const result = {}; path = path ? path + '.' : ''; for (let i = 0; i < numKeys; ++i) { const key = keys[i]; const val = update[key]; result[path + key] = val; // Avoid going into mixed paths if schema is specified const keySchema = schema && schema.path && schema.path(path + key); const isNested = schema && schema.nested && schema.nested[path + key]; if (keySchema && keySchema.instance === 'Mixed') continue; if (shouldFlatten(val)) { if (options && options.skipArrays && Array.isArray(val)) { continue; } const flat = flatten(val, path + key, options, schema); for (const k in flat) { result[k] = flat[k]; } if (Array.isArray(val)) { result[path + key] = val; } } if (isNested) { const paths = Object.keys(schema.paths); for (const p of paths) { if (p.startsWith(path + key + '.') && !result.hasOwnProperty(p)) { result[p] = void 0; } } } } return result; } /*! * ignore */ function modifiedPaths(update, path, result) { const keys = Object.keys(update || {}); const numKeys = keys.length; result = result || {}; path = path ? path + '.' : ''; for (let i = 0; i < numKeys; ++i) { const key = keys[i]; let val = update[key]; result[path + key] = true; if (isMongooseObject(val) && !Buffer.isBuffer(val)) { val = val.toObject({ transform: false, virtuals: false }); } if (shouldFlatten(val)) { modifiedPaths(val, path + key, result); } } return result; } /*! * ignore */ function shouldFlatten(val) { return val && typeof val === 'object' && !(val instanceof Date) && !(val instanceof ObjectId) && (!Array.isArray(val) || val.length > 0) && !(val instanceof Buffer) && !(val instanceof Decimal128) && !(val instanceof Binary); } }).call(this)}).call(this,require("buffer").Buffer) },{"../driver":196,"../types/decimal128":300,"../types/objectid":305,"./isMongooseObject":233,"buffer":129}],221:[function(require,module,exports){ 'use strict'; module.exports = function checkEmbeddedDiscriminatorKeyProjection(userProjection, path, schema, selected, addedPaths) { const userProjectedInPath = Object.keys(userProjection). reduce((cur, key) => cur || key.startsWith(path + '.'), false); const _discriminatorKey = path + '.' + schema.options.discriminatorKey; if (!userProjectedInPath && addedPaths.length === 1 && addedPaths[0] === _discriminatorKey) { selected.splice(selected.indexOf(_discriminatorKey), 1); } }; },{}],222:[function(require,module,exports){ 'use strict'; const getDiscriminatorByValue = require('./getDiscriminatorByValue'); /*! * Find the correct constructor, taking into account discriminators */ module.exports = function getConstructor(Constructor, value) { const discriminatorKey = Constructor.schema.options.discriminatorKey; if (value != null && Constructor.discriminators && value[discriminatorKey] != null) { if (Constructor.discriminators[value[discriminatorKey]]) { Constructor = Constructor.discriminators[value[discriminatorKey]]; } else { const constructorByValue = getDiscriminatorByValue(Constructor, value[discriminatorKey]); if (constructorByValue) { Constructor = constructorByValue; } } } return Constructor; }; },{"./getDiscriminatorByValue":223}],223:[function(require,module,exports){ 'use strict'; /*! * returns discriminator by discriminatorMapping.value * * @param {Model} model * @param {string} value */ module.exports = function getDiscriminatorByValue(model, value) { let discriminator = null; if (!model.discriminators) { return discriminator; } for (const name in model.discriminators) { const it = model.discriminators[name]; if ( it.schema && it.schema.discriminatorMapping && it.schema.discriminatorMapping.value == value ) { discriminator = it; break; } } return discriminator; }; },{}],224:[function(require,module,exports){ 'use strict'; /*! * 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 (const key of Object.keys(schema.discriminators)) { const discriminatorSchema = schema.discriminators[key]; if (discriminatorSchema.discriminatorMapping == null) { continue; } if (discriminatorSchema.discriminatorMapping.value === value) { return discriminatorSchema; } } return null; }; },{}],225:[function(require,module,exports){ 'use strict'; /*! * ignore */ module.exports = function cleanModifiedSubpaths(doc, path, options) { options = options || {}; const skipDocArrays = options.skipDocArrays; let deleted = 0; if (!doc) { return deleted; } for (const modifiedPath of Object.keys(doc.$__.activePaths.states.modify)) { if (skipDocArrays) { const schemaType = doc.schema.path(modifiedPath); if (schemaType && schemaType.$isMongooseDocumentArray) { continue; } } if (modifiedPath.startsWith(path + '.')) { delete doc.$__.activePaths.states.modify[modifiedPath]; ++deleted; } } return deleted; }; },{}],226:[function(require,module,exports){ 'use strict'; const documentSchemaSymbol = require('../../helpers/symbols').documentSchemaSymbol; const get = require('../../helpers/get'); const internalToObjectOptions = require('../../options').internalToObjectOptions; const utils = require('../../utils'); let Document; const getSymbol = require('../../helpers/symbols').getSymbol; const scopeSymbol = require('../../helpers/symbols').scopeSymbol; /*! * exports */ exports.compile = compile; exports.defineKey = defineKey; /*! * Compiles schemas. */ function compile(tree, proto, prefix, options) { Document = Document || require('../../document'); const keys = Object.keys(tree); const len = keys.length; let limb; let key; for (let i = 0; i < len; ++i) { key = keys[i]; limb = tree[key]; const hasSubprops = utils.isPOJO(limb) && Object.keys(limb).length && (!limb[options.typeKey] || (options.typeKey === 'type' && limb.type.type)); const subprops = hasSubprops ? limb : null; defineKey(key, subprops, proto, prefix, keys, options); } } /*! * Defines the accessor named prop on the incoming prototype. */ function defineKey(prop, subprops, prototype, prefix, keys, options) { Document = Document || require('../../document'); const path = (prefix ? prefix + '.' : '') + prop; prefix = prefix || ''; if (subprops) { Object.defineProperty(prototype, prop, { enumerable: true, configurable: true, get: function() { const _this = this; if (!this.$__.getters) { this.$__.getters = {}; } if (!this.$__.getters[path]) { const nested = Object.create(Document.prototype, getOwnPropertyDescriptors(this)); // save scope for nested getters/setters if (!prefix) { nested.$__[scopeSymbol] = this; } nested.$__.nestedPath = path; 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() { return utils.clone(_this.get(path, null, { virtuals: get(this, 'schema.options.toObject.virtuals', null) })); } }); Object.defineProperty(nested, '$__get', { enumerable: false, configurable: true, writable: false, value: function() { return _this.get(path, null, { virtuals: get(this, 'schema.options.toObject.virtuals', null) }); } }); Object.defineProperty(nested, 'toJSON', { enumerable: false, configurable: true, writable: false, value: function() { return _this.get(path, null, { virtuals: get(_this, 'schema.options.toJSON.virtuals', null) }); } }); Object.defineProperty(nested, '$__isNested', { enumerable: false, configurable: true, writable: false, value: true }); const _isEmptyOptions = Object.freeze({ minimize: true, virtuals: false, getters: false, transform: false }); Object.defineProperty(nested, '$isEmpty', { enumerable: false, configurable: true, writable: false, value: function() { return Object.keys(this.get(path, null, _isEmptyOptions) || {}).length === 0; } }); 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(v) { if (v != null && v.$__isNested) { // Convert top-level to POJO, but leave subdocs hydrated so `$set` // can handle them. See gh-9293. v = v.$__get(); } else if (v instanceof Document && !v.$__isNested) { v = v.toObject(internalToObjectOptions); } const doc = this.$__[scopeSymbol] || this; doc.$set(path, v); } }); } else { Object.defineProperty(prototype, prop, { enumerable: true, configurable: true, get: function() { return this[getSymbol].call(this.$__[scopeSymbol] || this, path); }, set: function(v) { this.$set.call(this.$__[scopeSymbol] || this, path, v); } }); } } // gets descriptors for all properties of `object` // makes all properties non-enumerable to match previous behavior to #2211 function getOwnPropertyDescriptors(object) { const result = {}; Object.getOwnPropertyNames(object).forEach(function(key) { result[key] = Object.getOwnPropertyDescriptor(object, key); // Assume these are schema paths, ignore them re: #5470 if (result[key].get) { delete result[key]; return; } result[key].enumerable = [ 'isNew', '$__', 'errors', '_doc', '$locals', '$op', '__parentArray', '__index', '$isDocumentArrayElement' ].indexOf(key) === -1; }); return result; } },{"../../document":194,"../../helpers/get":229,"../../helpers/symbols":252,"../../options":257,"../../utils":307}],227:[function(require,module,exports){ 'use strict'; const get = require('../get'); /*! * Like `schema.path()`, except with a document, because impossible to * determine path type without knowing the embedded discriminator key. */ module.exports = function getEmbeddedDiscriminatorPath(doc, path, options) { options = options || {}; const typeOnly = options.typeOnly; const parts = path.split('.'); let schema = null; let type = 'adhocOrUndefined'; for (let i = 0; i < parts.length; ++i) { const subpath = parts.slice(0, i + 1).join('.'); schema = doc.schema.path(subpath); if (schema == null) { type = 'adhocOrUndefined'; continue; } if (schema.instance === 'Mixed') { return typeOnly ? 'real' : schema; } type = doc.schema.pathType(subpath); if ((schema.$isSingleNested || schema.$isMongooseDocumentArrayElement) && schema.schema.discriminators != null) { const discriminators = schema.schema.discriminators; const discriminatorKey = doc.get(subpath + '.' + get(schema, 'schema.options.discriminatorKey')); if (discriminatorKey == null || discriminators[discriminatorKey] == null) { continue; } const rest = parts.slice(i + 1).join('.'); return getEmbeddedDiscriminatorPath(doc.get(subpath), rest, options); } } // Are we getting the whole schema or just the type, 'real', 'nested', etc. return typeOnly ? type : schema; }; },{"../get":229}],228:[function(require,module,exports){ 'use strict'; const utils = require('../../utils'); /** * 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) { if (utils.isPOJO(v) && v.$__ != null && v._doc != null) { return v._doc; } return v; }; },{"../../utils":307}],229:[function(require,module,exports){ 'use strict'; /*! * Simplified lodash.get to work around the annoying null quirk. See: * https://github.com/lodash/lodash/issues/3659 */ module.exports = function get(obj, path, def) { const parts = path.split('.'); let rest = path; let cur = obj; for (const part of parts) { if (cur == null) { return def; } // `lib/cast.js` depends on being able to get dotted paths in updates, // like `{ $set: { 'a.b': 42 } }` if (cur[rest] != null) { return cur[rest]; } cur = getProperty(cur, part); rest = rest.substr(part.length + 1); } 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]; } },{}],230:[function(require,module,exports){ 'use strict'; module.exports = function(fn) { if (fn.name) { return fn.name; } return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1]; }; },{}],231:[function(require,module,exports){ (function (process){(function (){ /*! * 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 */ 'use strict'; module.exports = function immediate(cb) { return process.nextTick(cb); }; }).call(this)}).call(this,require('_process')) },{"_process":325}],232:[function(require,module,exports){ 'use strict'; const get = require('./get'); /*! * Get the bson type, if it exists */ function isBsonType(obj, typename) { return get(obj, '_bsontype', void 0) === typename; } module.exports = isBsonType; },{"./get":229}],233:[function(require,module,exports){ 'use strict'; /*! * 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) { if (v == null) { return false; } return v.$__ != null || // Document v.isMongooseArray || // Array or Document Array v.isMongooseBuffer || // Buffer v.$isMongooseMap; // Map }; },{}],234:[function(require,module,exports){ (function (Buffer){(function (){ 'use strict'; /*! * Determines if `arg` is an object. * * @param {Object|Array|String|Function|RegExp|any} arg * @api private * @return {Boolean} */ module.exports = function(arg) { if (Buffer.isBuffer(arg)) { return true; } return Object.prototype.toString.call(arg) === '[object Object]'; }; }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":179}],235:[function(require,module,exports){ 'use strict'; function isPromise(val) { return !!val && (typeof val === 'object' || typeof val === 'function') && typeof val.then === 'function'; } module.exports = isPromise; },{}],236:[function(require,module,exports){ 'use strict'; const symbols = require('../../schema/symbols'); const promiseOrCallback = require('../promiseOrCallback'); /*! * 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 || {}; const kareemOptions = { useErrorHandlers: true, numCallbackParams: 1, nullResultByDefault: true, contextParameter: true }; const objToDecorate = options.decorateDoc ? model : model.prototype; model.$appliedHooks = true; for (const key of Object.keys(schema.paths)) { const type = schema.paths[key]; let childModel = null; if (type.$isSingleNested) { childModel = type.caster; } else if (type.$isMongooseDocumentArray) { childModel = type.Constructor; } else { continue; } if (childModel.$appliedHooks) { continue; } applyHooks(childModel, type.schema, options); if (childModel.discriminators != null) { const keys = Object.keys(childModel.discriminators); for (const key of keys) { applyHooks(childModel.discriminators[key], childModel.discriminators[key].schema, options); } } } // Built-in hooks rely on hooking internal functions in order to support // promises and make it so that `doc.save.toString()` provides meaningful // information. const middleware = schema.s.hooks. filter(hook => { if (hook.name === 'updateOne' || hook.name === 'deleteOne') { return !!hook['document']; } if (hook.name === 'remove' || hook.name === 'init') { return hook['document'] == null || !!hook['document']; } if (hook.query != null || hook.document != null) { return hook.document !== false; } return true; }). filter(hook => { // If user has overwritten the method, don't apply built-in middleware if (schema.methods[hook.name]) { return !hook.fn[symbols.builtInMiddleware]; } return true; }); model._middleware = middleware; objToDecorate.$__originalValidate = objToDecorate.$__originalValidate || objToDecorate.$__validate; for (const method of ['save', 'validate', 'remove', 'deleteOne']) { const toWrap = method === 'validate' ? '$__originalValidate' : `$__${method}`; const wrapped = middleware. createWrapper(method, objToDecorate[toWrap], null, kareemOptions); objToDecorate[`$__${method}`] = wrapped; } objToDecorate.$__init = middleware. createWrapperSync('init', objToDecorate.$__init, null, kareemOptions); // Support hooks for custom methods const customMethods = Object.keys(schema.methods); const customMethodOptions = Object.assign({}, kareemOptions, { // Only use `checkForPromise` for custom methods, because mongoose // query thunks are not as consistent as I would like about returning // a nullish value rather than the query. If a query thunk returns // a query, `checkForPromise` causes infinite recursion checkForPromise: true }); for (const method of customMethods) { if (!middleware.hasHooks(method)) { // Don't wrap if there are no hooks for the custom method to avoid // surprises. Also, `createWrapper()` enforces consistent async, // so wrapping a sync method would break it. continue; } const originalMethod = objToDecorate[method]; objToDecorate[method] = function() { const args = Array.prototype.slice.call(arguments); const cb = args.slice(-1).pop(); const argsWithoutCallback = typeof cb === 'function' ? args.slice(0, args.length - 1) : args; return promiseOrCallback(cb, callback => { return this[`$__${method}`].apply(this, argsWithoutCallback.concat([callback])); }, model.events); }; objToDecorate[`$__${method}`] = middleware. createWrapper(method, originalMethod, null, customMethodOptions); } } },{"../../schema/symbols":294,"../promiseOrCallback":241}],237:[function(require,module,exports){ 'use strict'; const Mixed = require('../../schema/mixed'); const defineKey = require('../document/compile').defineKey; const get = require('../get'); const utils = require('../../utils'); const 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) { const applyPluginsToDiscriminators = get(model.base, 'options.applyPluginsToDiscriminators', false); // Even if `applyPluginsToDiscriminators` isn't set, we should still apply // global plugins to schemas embedded in the discriminator schema (gh-7370) model.base._applyPlugins(schema, { skipTopLevel: !applyPluginsToDiscriminators }); } const key = model.schema.options.discriminatorKey; const existingPath = model.schema.path(key); if (existingPath != null) { if (!utils.hasUserDefinedProperty(existingPath.options, 'select')) { existingPath.options.select = true; } existingPath.options.$skipDiscriminatorCheck = true; } else { const baseSchemaAddition = {}; baseSchemaAddition[key] = { default: void 0, select: true, $skipDiscriminatorCheck: true }; baseSchemaAddition[key][model.schema.options.typeKey] = String; model.schema.add(baseSchemaAddition); defineKey(key, null, model.prototype, null, [key], model.schema.options); } if (schema.path(key) && schema.path(key).options.$skipDiscriminatorCheck !== true) { throw new Error('Discriminator "' + name + '" cannot have field with name "' + key + '"'); } let value = name; if (typeof tiedValue == 'string' && tiedValue.length) { 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 const baseSchemaPaths = Object.keys(baseSchema.paths); const conflictingPaths = []; for (const path of baseSchemaPaths) { if (schema.nested[path]) { conflictingPaths.push(path); continue; } if (path.indexOf('.') === -1) { continue; } const sp = path.split('.').slice(0, -1); let cur = ''; for (const piece of sp) { cur += (cur.length ? '.' : '') + piece; if (schema.paths[cur] instanceof Mixed || schema.singleNestedPaths[cur] instanceof Mixed) { conflictingPaths.push(path); } } } utils.merge(schema, baseSchema, { isDiscriminatorSchemaMerge: true, omit: { discriminators: true, base: true }, omitNested: conflictingPaths.reduce((cur, path) => { cur['tree.' + path] = true; return cur; }, {}) }); // Clean up conflicting paths _after_ merging re: gh-6076 for (const conflictingPath of conflictingPaths) { delete schema.paths[conflictingPath]; } // Rebuild schema models because schemas may have been merged re: #7884 schema.childSchemas.forEach(obj => { obj.model.prototype.$__setSchema(obj.schema); }); const obj = {}; obj[key] = { default: value, select: true, set: function(newName) { if (newName === value) { return value; } throw new Error('Can\'t set discriminator key "' + key + '"'); }, $skipDiscriminatorCheck: true }; obj[key][schema.options.typeKey] = existingPath ? existingPath.instance : String; schema.add(obj); schema.discriminatorMapping = { key: key, value: value, isRoot: false }; if (baseSchema.options.collection) { schema.options.collection = baseSchema.options.collection; } const toJSON = schema.options.toJSON; const toObject = schema.options.toObject; const _id = schema.options._id; const id = schema.options.id; const keys = Object.keys(schema.options); schema.options.discriminatorKey = baseSchema.options.discriminatorKey; for (const _key of keys) { if (!CUSTOMIZABLE_DISCRIMINATOR_OPTIONS[_key]) { // Special case: compiling a model sets `pluralization = true` by default. Avoid throwing an error // for that case. See gh-9238 if (_key === 'pluralization' && schema.options[_key] == true && baseSchema.options[_key] == null) { continue; } if (!utils.deepEqual(schema.options[_key], baseSchema.options[_key])) { throw new Error('Can\'t customize discriminator option ' + _key + ' (can only modify ' + Object.keys(CUSTOMIZABLE_DISCRIMINATOR_OPTIONS).join(', ') + ')'); } } } schema.options = utils.clone(baseSchema.options); if (toJSON) schema.options.toJSON = toJSON; if (toObject) schema.options.toObject = toObject; if (typeof _id !== 'undefined') { schema.options._id = _id; } schema.options.id = id; schema.s.hooks = model.schema.s.hooks.merge(schema.s.hooks); 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]) { throw new Error('Discriminator with name "' + name + '" already exists'); } return schema; }; },{"../../schema/mixed":284,"../../utils":307,"../document/compile":226,"../get":229}],238:[function(require,module,exports){ 'use strict'; const MongooseError = require('../../error/mongooseError'); const util = require('util'); 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 })); } },{"../../error/mongooseError":207,"util":332}],239:[function(require,module,exports){ 'use strict'; /*! * ignore */ 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; }; },{}],240:[function(require,module,exports){ 'use strict'; const isDefiningProjection = require('./isDefiningProjection'); /*! * ignore */ module.exports = function isExclusive(projection) { const keys = Object.keys(projection); let ki = keys.length; let exclude = null; if (ki === 1 && keys[0] === '_id') { exclude = !!projection[keys[ki]]; } else { while (ki--) { // Does this projection explicitly define inclusion/exclusion? // Explicitly avoid `$meta` and `$slice` if (keys[ki] !== '_id' && isDefiningProjection(projection[keys[ki]])) { exclude = !projection[keys[ki]]; break; } } } return exclude; }; },{"./isDefiningProjection":239}],241:[function(require,module,exports){ (function (process){(function (){ 'use strict'; const PromiseProvider = require('../promise_provider'); const emittedSymbol = Symbol.for('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('error').length > 0 && !error[emittedSymbol]) { error[emittedSymbol] = true; ee.emit('error', error); } try { callback(error); } catch (error) { return process.nextTick(() => { throw error; }); } return; } callback.apply(this, arguments); }); } Promise = Promise || PromiseProvider.get(); return new Promise((resolve, reject) => { fn(function(error, res) { if (error != null) { if (ee != 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); }); }); }; }).call(this)}).call(this,require('_process')) },{"../promise_provider":272,"_process":325}],242:[function(require,module,exports){ 'use strict'; /*! * ignore */ module.exports = applyQueryMiddleware; /*! * ignore */ applyQueryMiddleware.middlewareFunctions = [ 'count', 'countDocuments', 'deleteMany', 'deleteOne', 'distinct', 'estimatedDocumentCount', 'find', 'findOne', 'findOneAndDelete', 'findOneAndRemove', 'findOneAndReplace', 'findOneAndUpdate', 'remove', 'replaceOne', 'update', 'updateMany', 'updateOne', 'validate' ]; /*! * Apply query middleware * * @param {Query} query constructor * @param {Model} model */ function applyQueryMiddleware(Query, model) { const kareemOptions = { useErrorHandlers: true, numCallbackParams: 1, nullResultByDefault: true }; const middleware = model.hooks.filter(hook => { const contexts = _getContexts(hook); if (hook.name === 'updateOne') { return contexts.query == null || !!contexts.query; } if (hook.name === 'deleteOne') { return !!contexts.query || Object.keys(contexts).length === 0; } if (hook.name === 'validate' || hook.name === 'remove') { return !!contexts.query; } if (hook.query != null || hook.document != null) { return !!hook.query; } return true; }); // `update()` thunk has a different name because `_update` was already taken Query.prototype._execUpdate = middleware.createWrapper('update', Query.prototype._execUpdate, null, kareemOptions); // `distinct()` thunk has a different name because `_distinct` was already taken Query.prototype.__distinct = middleware.createWrapper('distinct', Query.prototype.__distinct, null, kareemOptions); // `validate()` doesn't have a thunk because it doesn't execute a query. Query.prototype.validate = middleware.createWrapper('validate', Query.prototype.validate, null, kareemOptions); applyQueryMiddleware.middlewareFunctions. filter(v => v !== 'update' && v !== 'distinct' && v !== 'validate'). forEach(fn => { Query.prototype[`_${fn}`] = middleware.createWrapper(fn, Query.prototype[`_${fn}`], null, kareemOptions); }); } function _getContexts(hook) { const ret = {}; if (hook.hasOwnProperty('query')) { ret.query = hook.query; } if (hook.hasOwnProperty('document')) { ret.document = hook.document; } return ret; } },{}],243:[function(require,module,exports){ 'use strict'; const specialKeys = new Set([ '$ref', '$id', '$db' ]); module.exports = function isOperator(path) { return path.startsWith('$') && !specialKeys.has(path); }; },{}],244:[function(require,module,exports){ 'use strict'; module.exports = function addAutoId(schema) { const _obj = { _id: { auto: true } }; _obj._id[schema.options.typeKey] = 'ObjectId'; schema.add(_obj); }; },{}],245:[function(require,module,exports){ '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'); }; },{}],246:[function(require,module,exports){ 'use strict'; const get = require('../get'); const helperIsObject = require('../isObject'); /*! * Gather all indexes defined in the schema, including single nested, * document arrays, and embedded discriminators. */ module.exports = function getIndexes(schema) { let indexes = []; const schemaStack = new WeakMap(); const indexTypes = schema.constructor.indexTypes; const indexByName = new Map(); collectIndexes(schema); return indexes; function collectIndexes(schema, prefix, baseSchema) { // Ignore infinitely nested schemas, if we've already seen this schema // along this path there must be a cycle if (schemaStack.has(schema)) { return; } schemaStack.set(schema, true); prefix = prefix || ''; const keys = Object.keys(schema.paths); for (const key of keys) { const path = schema.paths[key]; if (baseSchema != null && baseSchema.paths[key]) { // If looking at an embedded discriminator schema, don't look at paths // that the continue; } if (path.$isMongooseDocumentArray || path.$isSingleNested) { if (get(path, 'options.excludeIndexes') !== true && get(path, 'schemaOptions.excludeIndexes') !== true && get(path, 'schema.options.excludeIndexes') !== true) { collectIndexes(path.schema, prefix + key + '.'); } if (path.schema.discriminators != null) { const discriminators = path.schema.discriminators; const discriminatorKeys = Object.keys(discriminators); for (const discriminatorKey of discriminatorKeys) { collectIndexes(discriminators[discriminatorKey], prefix + key + '.', path.schema); } } // Retained to minimize risk of backwards breaking changes due to // gh-6113 if (path.$isMongooseDocumentArray) { continue; } } const index = path._index || (path.caster && path.caster._index); if (index !== false && index !== null && index !== undefined) { const field = {}; const isObject = helperIsObject(index); const options = isObject ? index : {}; const type = typeof index === 'string' ? index : isObject ? index.type : false; if (type && indexTypes.indexOf(type) !== -1) { field[prefix + key] = type; } else if (options.text) { field[prefix + key] = 'text'; delete options.text; } else { const isDescendingIndex = Number(index) === -1; field[prefix + key] = isDescendingIndex ? -1 : 1; } delete options.type; if (!('background' in options)) { options.background = true; } if (schema.options.autoIndex != null) { options._autoIndex = schema.options.autoIndex; } const indexName = options && options.name; if (typeof indexName === 'string') { if (indexByName.has(indexName)) { Object.assign(indexByName.get(indexName), field); } else { indexes.push([field, options]); indexByName.set(indexName, field); } } else { indexes.push([field, options]); indexByName.set(indexName, field); } } } schemaStack.delete(schema); if (prefix) { fixSubIndexPaths(schema, prefix); } else { schema._indexes.forEach(function(index) { if (!('background' in index[1])) { index[1].background = true; } }); indexes = indexes.concat(schema._indexes); } } /*! * 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) { const subindexes = schema._indexes; const len = subindexes.length; for (let i = 0; i < len; ++i) { const indexObj = subindexes[i][0]; const indexOptions = subindexes[i][1]; const keys = Object.keys(indexObj); const klen = keys.length; const newindex = {}; // use forward iteration, order matters for (let j = 0; j < klen; ++j) { const key = keys[j]; newindex[prefix + key] = indexObj[key]; } const newIndexOptions = Object.assign({}, indexOptions); if (indexOptions != null && indexOptions.partialFilterExpression != null) { newIndexOptions.partialFilterExpression = {}; const partialFilterExpression = indexOptions.partialFilterExpression; for (const key of Object.keys(partialFilterExpression)) { newIndexOptions.partialFilterExpression[prefix + key] = partialFilterExpression[key]; } } indexes.push([newindex, newIndexOptions]); } } }; },{"../get":229,"../isObject":234}],247:[function(require,module,exports){ 'use strict'; const addAutoId = require('./addAutoId'); 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; }; },{"./addAutoId":244}],248:[function(require,module,exports){ '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]; } },{}],249:[function(require,module,exports){ 'use strict'; module.exports = function merge(s1, s2) { s1.add(s2.tree || {}); s1.callQueue = s1.callQueue.concat(s2.callQueue); s1.method(s2.methods); s1.static(s2.statics); for (const query in s2.query) { s1.query[query] = s2.query[query]; } for (const virtual in s2.virtuals) { s1.virtuals[virtual] = s2.virtuals[virtual].clone(); } s1.s.hooks.merge(s2.s.hooks, false); }; },{}],250:[function(require,module,exports){ 'use strict'; const StrictModeError = require('../../error/strict'); /*! * 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(fn => fn !== schematype.$immutableSetter); delete schematype.$immutableSetter; } }; function createImmutableSetter(path, immutable) { return function immutableSetter(v) { if (this == null || this.$__ == null) { return v; } if (this.isNew) { return v; } const _immutable = typeof immutable === 'function' ? immutable.call(this, this) : immutable; if (!_immutable) { return v; } const _value = this.$__getValue(path); if (this.$__.strictMode === 'throw' && v !== _value) { throw new StrictModeError(path, 'Path `' + path + '` is immutable ' + 'and strict mode is set to throw.', true); } return _value; }; } },{"../../error/strict":214}],251:[function(require,module,exports){ 'use strict'; module.exports = new Set(['__proto__', 'constructor', 'prototype']); },{}],252:[function(require,module,exports){ 'use strict'; exports.arrayAtomicsSymbol = Symbol('mongoose#Array#_atomics'); exports.arrayParentSymbol = Symbol('mongoose#Array#_parent'); exports.arrayPathSymbol = Symbol('mongoose#Array#_path'); exports.arraySchemaSymbol = Symbol('mongoose#Array#_schema'); exports.documentArrayParent = Symbol('mongoose:documentArrayParent'); exports.documentIsSelected = Symbol('mongoose#Document#isSelected'); exports.documentIsModified = Symbol('mongoose#Document#isModified'); exports.documentModifiedPaths = Symbol('mongoose#Document#modifiedPaths'); exports.documentSchemaSymbol = Symbol('mongoose#Document#schema'); exports.getSymbol = Symbol('mongoose#Document#get'); exports.modelSymbol = Symbol('mongoose#Model'); exports.objectIdSymbol = Symbol('mongoose#ObjectId'); exports.populateModelSymbol = Symbol('mongoose.PopulateOptions#Model'); exports.schemaTypeSymbol = Symbol('mongoose#schemaType'); exports.sessionNewDocuments = Symbol('mongoose:ClientSession#newDocuments'); exports.scopeSymbol = Symbol('mongoose#Document#scope'); exports.validatorErrorSymbol = Symbol('mongoose:validatorError'); },{}],253:[function(require,module,exports){ 'use strict'; const applyTimestampsToChildren = require('../update/applyTimestampsToChildren'); const applyTimestampsToUpdate = require('../update/applyTimestampsToUpdate'); const get = require('../get'); const handleTimestampOption = require('../schema/handleTimestampOption'); const symbols = require('../../schema/symbols'); module.exports = function setupTimestamps(schema, timestamps) { const childHasTimestamp = schema.childSchemas.find(withTimestamp); function withTimestamp(s) { const ts = s.schema.options.timestamps; return !!ts; } if (!timestamps && !childHasTimestamp) { return; } const createdAt = handleTimestampOption(timestamps, 'createdAt'); const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); const currentTime = timestamps != null && timestamps.hasOwnProperty('currentTime') ? timestamps.currentTime : null; const schemaAdditions = {}; schema.$timestamps = { createdAt: createdAt, updatedAt: updatedAt }; if (updatedAt && !schema.paths[updatedAt]) { schemaAdditions[updatedAt] = Date; } if (createdAt && !schema.paths[createdAt]) { schemaAdditions[createdAt] = Date; } schema.add(schemaAdditions); schema.pre('save', function(next) { const timestampOption = get(this, '$__.saveOptions.timestamps'); if (timestampOption === false) { return next(); } const skipUpdatedAt = timestampOption != null && timestampOption.updatedAt === false; const skipCreatedAt = timestampOption != null && timestampOption.createdAt === false; const defaultTimestamp = currentTime != null ? currentTime() : (this.ownerDocument ? this.ownerDocument() : this).constructor.base.now(); const auto_id = this._id && this._id.auto; if (!skipCreatedAt && createdAt && !this.get(createdAt) && this.$__isSelected(createdAt)) { this.$set(createdAt, auto_id ? this._id.getTimestamp() : defaultTimestamp); } if (!skipUpdatedAt && updatedAt && (this.isNew || this.isModified())) { let ts = defaultTimestamp; if (this.isNew) { if (createdAt != null) { ts = this.$__getValue(createdAt); } else if (auto_id) { ts = this._id.getTimestamp(); } } this.$set(updatedAt, ts); } next(); }); schema.methods.initializeTimestamps = function() { const ts = currentTime != null ? currentTime() : this.constructor.base.now(); if (createdAt && !this.get(createdAt)) { this.$set(createdAt, ts); } if (updatedAt && !this.get(updatedAt)) { this.$set(updatedAt, ts); } return this; }; _setTimestampsOnUpdate[symbols.builtInMiddleware] = true; const opts = { query: true, model: false }; schema.pre('findOneAndReplace', opts, _setTimestampsOnUpdate); schema.pre('findOneAndUpdate', opts, _setTimestampsOnUpdate); schema.pre('replaceOne', opts, _setTimestampsOnUpdate); schema.pre('update', opts, _setTimestampsOnUpdate); schema.pre('updateOne', opts, _setTimestampsOnUpdate); schema.pre('updateMany', opts, _setTimestampsOnUpdate); function _setTimestampsOnUpdate(next) { const now = currentTime != null ? currentTime() : this.model.base.now(); // Replacing with null update should still trigger timestamps if (this.op === 'findOneAndReplace' && this.getUpdate() == null) { this.setUpdate({}); } applyTimestampsToUpdate(now, createdAt, updatedAt, this.getUpdate(), this.options, this.schema); applyTimestampsToChildren(now, this.getUpdate(), this.model.schema); next(); } }; },{"../../schema/symbols":294,"../get":229,"../schema/handleTimestampOption":248,"../update/applyTimestampsToChildren":254,"../update/applyTimestampsToUpdate":255}],254:[function(require,module,exports){ 'use strict'; const cleanPositionalOperators = require('../schema/cleanPositionalOperators'); const handleTimestampOption = require('../schema/handleTimestampOption'); module.exports = applyTimestampsToChildren; /*! * ignore */ function applyTimestampsToChildren(now, update, schema) { if (update == null) { return; } const keys = Object.keys(update); const hasDollarKey = keys.some(key => key.startsWith('$')); if (hasDollarKey) { if (update.$push) { for (const key of Object.keys(update.$push)) { const $path = schema.path(key); if (update.$push[key] && $path && $path.$isMongooseDocumentArray && $path.schema.options.timestamps) { const timestamps = $path.schema.options.timestamps; const createdAt = handleTimestampOption(timestamps, 'createdAt'); const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); if (update.$push[key].$each) { update.$push[key].$each.forEach(function(subdoc) { if (updatedAt != null) { subdoc[updatedAt] = now; } if (createdAt != null) { subdoc[createdAt] = now; } }); } else { if (updatedAt != null) { update.$push[key][updatedAt] = now; } if (createdAt != null) { update.$push[key][createdAt] = now; } } } } } if (update.$set != null) { const keys = Object.keys(update.$set); for (const key of keys) { applyTimestampsToUpdateKey(schema, key, update.$set, now); } } } const updateKeys = Object.keys(update).filter(key => !key.startsWith('$')); for (const key of updateKeys) { applyTimestampsToUpdateKey(schema, key, update, now); } } function applyTimestampsToDocumentArray(arr, schematype, now) { const timestamps = schematype.schema.options.timestamps; if (!timestamps) { return; } const len = arr.length; const createdAt = handleTimestampOption(timestamps, 'createdAt'); const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); for (let i = 0; i < len; ++i) { if (updatedAt != null) { arr[i][updatedAt] = now; } if (createdAt != null) { arr[i][createdAt] = now; } applyTimestampsToChildren(now, arr[i], schematype.schema); } } function applyTimestampsToSingleNested(subdoc, schematype, now) { const timestamps = schematype.schema.options.timestamps; if (!timestamps) { return; } const createdAt = handleTimestampOption(timestamps, 'createdAt'); const 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 `$[.*]` const keyToSearch = cleanPositionalOperators(key); const path = schema.path(keyToSearch); if (!path) { return; } const parentSchemaTypes = []; const pieces = keyToSearch.split('.'); for (let i = pieces.length - 1; i > 0; --i) { const s = schema.path(pieces.slice(0, i).join('.')); if (s != null && (s.$isMongooseDocumentArray || s.$isSingleNested)) { parentSchemaTypes.push({ parentPath: key.split('.').slice(0, i).join('.'), parentSchemaType: s }); } } if (Array.isArray(update[key]) && path.$isMongooseDocumentArray) { applyTimestampsToDocumentArray(update[key], path, now); } else if (update[key] && path.$isSingleNested) { applyTimestampsToSingleNested(update[key], path, now); } else if (parentSchemaTypes.length > 0) { for (const item of parentSchemaTypes) { const parentPath = item.parentPath; const parentSchemaType = item.parentSchemaType; const timestamps = parentSchemaType.schema.options.timestamps; const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); if (!timestamps || updatedAt == null) { continue; } if (parentSchemaType.$isSingleNested) { // Single nested is easy update[parentPath + '.' + updatedAt] = now; } else if (parentSchemaType.$isMongooseDocumentArray) { let childPath = key.substr(parentPath.length + 1); if (/^\d+$/.test(childPath)) { update[parentPath + '.' + childPath][updatedAt] = now; continue; } const firstDot = childPath.indexOf('.'); childPath = firstDot !== -1 ? childPath.substr(0, firstDot) : childPath; update[parentPath + '.' + childPath + '.' + updatedAt] = now; } } } else if (path.schema != null && path.schema != schema && update[key]) { const timestamps = path.schema.options.timestamps; const createdAt = handleTimestampOption(timestamps, 'createdAt'); const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); if (!timestamps) { return; } if (updatedAt != null) { update[key][updatedAt] = now; } if (createdAt != null) { update[key][createdAt] = now; } } } },{"../schema/cleanPositionalOperators":245,"../schema/handleTimestampOption":248}],255:[function(require,module,exports){ 'use strict'; /*! * ignore */ const get = require('../get'); module.exports = applyTimestampsToUpdate; /*! * ignore */ function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, options) { const updates = currentUpdate; let _updates = updates; const overwrite = get(options, 'overwrite', false); const timestamps = get(options, 'timestamps', true); // Support skipping timestamps at the query level, see gh-6980 if (!timestamps || updates == null) { return currentUpdate; } const skipCreatedAt = timestamps != null && timestamps.createdAt === false; const skipUpdatedAt = timestamps != null && timestamps.updatedAt === false; if (overwrite) { if (currentUpdate && currentUpdate.$set) { currentUpdate = currentUpdate.$set; updates.$set = {}; _updates = updates.$set; } if (!skipUpdatedAt && updatedAt && !currentUpdate[updatedAt]) { _updates[updatedAt] = now; } if (!skipCreatedAt && createdAt && !currentUpdate[createdAt]) { _updates[createdAt] = now; } return updates; } currentUpdate = currentUpdate || {}; if (Array.isArray(updates)) { // Update with aggregation pipeline updates.push({ $set: { updatedAt: now } }); return updates; } updates.$set = updates.$set || {}; if (!skipUpdatedAt && updatedAt && (!currentUpdate.$currentDate || !currentUpdate.$currentDate[updatedAt])) { let timestampSet = false; if (updatedAt.indexOf('.') !== -1) { const pieces = updatedAt.split('.'); for (let i = 1; i < pieces.length; ++i) { const remnant = pieces.slice(-i).join('.'); const start = pieces.slice(0, -i).join('.'); if (currentUpdate[start] != null) { currentUpdate[start][remnant] = now; timestampSet = true; break; } else if (currentUpdate.$set && currentUpdate.$set[start]) { currentUpdate.$set[start][remnant] = now; timestampSet = true; break; } } } if (!timestampSet) { updates.$set[updatedAt] = now; } if (updates.hasOwnProperty(updatedAt)) { delete updates[updatedAt]; } } if (!skipCreatedAt && createdAt) { if (currentUpdate[createdAt]) { delete currentUpdate[createdAt]; } if (currentUpdate.$set && currentUpdate.$set[createdAt]) { delete currentUpdate.$set[createdAt]; } let timestampSet = false; if (createdAt.indexOf('.') !== -1) { const pieces = createdAt.split('.'); for (let i = 1; i < pieces.length; ++i) { const remnant = pieces.slice(-i).join('.'); const start = pieces.slice(0, -i).join('.'); if (currentUpdate[start] != null) { currentUpdate[start][remnant] = now; timestampSet = true; break; } else if (currentUpdate.$set && currentUpdate.$set[start]) { currentUpdate.$set[start][remnant] = now; timestampSet = true; break; } } } if (!timestampSet) { updates.$setOnInsert = updates.$setOnInsert || {}; updates.$setOnInsert[createdAt] = now; } } if (Object.keys(updates.$set).length === 0) { delete updates.$set; } return updates; } },{"../get":229}],256:[function(require,module,exports){ /*! * Dependencies */ 'use strict'; const StateMachine = require('./statemachine'); const ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default', 'ignore'); module.exports = exports = InternalCache; function InternalCache() { this.strictMode = undefined; this.selected = undefined; this.shardval = undefined; this.saveError = undefined; this.validationError = undefined; this.adhocPaths = undefined; this.removing = undefined; this.inserting = undefined; this.saving = undefined; this.version = undefined; this.getters = {}; this._id = undefined; this.populate = undefined; // what we want to populate in this doc this.populated = undefined;// the _ids that have been populated this.wasPopulated = false; // if this doc was the result of a population this.scope = undefined; this.activePaths = new ActiveRoster; this.pathsToScopes = {}; this.cachedRequired = {}; this.session = null; this.$setCalled = new Set(); // embedded docs this.ownerDocument = undefined; this.fullPath = undefined; } },{"./statemachine":296}],257:[function(require,module,exports){ 'use strict'; /*! * ignore */ exports.internalToObjectOptions = { transform: false, virtuals: false, getters: false, _skipDepopulateTopLevel: true, depopulate: true, flattenDecimals: false }; },{}],258:[function(require,module,exports){ 'use strict'; const clone = require('../helpers/clone'); class PopulateOptions { constructor(obj) { this._docs = {}; this._childDocs = []; if (obj == null) { return; } obj = clone(obj); Object.assign(this, obj); if (typeof obj.subPopulate === 'object') { this.populate = obj.subPopulate; } if (obj.perDocumentLimit != null && obj.limit != null) { throw new Error('Can not use `limit` and `perDocumentLimit` at the same time. Path: `' + obj.path + '`.'); } } } /** * The connection used to look up models by name. If not specified, Mongoose * will default to using the connection associated with the model in * `PopulateOptions#model`. * * @memberOf PopulateOptions * @property {Connection} connection * @api public */ module.exports = PopulateOptions; },{"../helpers/clone":219}],259:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on an Array schematype. * * ####Example: * * const schema = new Schema({ tags: [String] }); * schema.path('tags').options; // SchemaArrayOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaArrayOptions */ class SchemaArrayOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * 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, 'enum', opts); /*! * ignore */ module.exports = SchemaArrayOptions; },{"./SchemaTypeOptions":268,"./propertyOptions":270}],260:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on a Buffer schematype. * * ####Example: * * const schema = new Schema({ bitmap: Buffer }); * schema.path('bitmap').options; // SchemaBufferOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaBufferOptions */ class SchemaBufferOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * 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; },{"./SchemaTypeOptions":268,"./propertyOptions":270}],261:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on a Date schematype. * * ####Example: * * const schema = new Schema({ startedAt: Date }); * schema.path('startedAt').options; // SchemaDateOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaDateOptions */ class SchemaDateOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * If set, Mongoose adds a validator that checks that this path is after the * given `min`. * * @api public * @property min * @memberOf SchemaDateOptions * @type Date * @instance */ Object.defineProperty(SchemaDateOptions.prototype, 'min', opts); /** * If set, Mongoose adds a validator that checks that this path is before the * given `max`. * * @api public * @property max * @memberOf SchemaDateOptions * @type Date * @instance */ Object.defineProperty(SchemaDateOptions.prototype, 'max', opts); /** * If set, Mongoose creates a TTL index on this path. * * @api public * @property expires * @memberOf SchemaDateOptions * @type Date * @instance */ Object.defineProperty(SchemaDateOptions.prototype, 'expires', opts); /*! * ignore */ module.exports = SchemaDateOptions; },{"./SchemaTypeOptions":268,"./propertyOptions":270}],262:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on an Document Array schematype. * * ####Example: * * const schema = new Schema({ users: [{ name: string }] }); * schema.path('users').options; // SchemaDocumentArrayOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaDocumentOptions */ class SchemaDocumentArrayOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * 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; },{"./SchemaTypeOptions":268,"./propertyOptions":270}],263:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on a Map schematype. * * ####Example: * * const schema = new Schema({ socialMediaHandles: { type: Map, of: String } }); * schema.path('socialMediaHandles').options; // SchemaMapOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaMapOptions */ class SchemaMapOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * 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; },{"./SchemaTypeOptions":268,"./propertyOptions":270}],264:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on a Number schematype. * * ####Example: * * const schema = new Schema({ count: Number }); * schema.path('count').options; // SchemaNumberOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaNumberOptions */ class SchemaNumberOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * 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; },{"./SchemaTypeOptions":268,"./propertyOptions":270}],265:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on an ObjectId schematype. * * ####Example: * * const schema = new Schema({ testId: mongoose.ObjectId }); * schema.path('testId').options; // SchemaObjectIdOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaObjectIdOptions */ class SchemaObjectIdOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * 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; },{"./SchemaTypeOptions":268,"./propertyOptions":270}],266:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on a single nested schematype. * * ####Example: * * const schema = Schema({ child: Schema({ name: String }) }); * schema.path('child').options; // SchemaSingleNestedOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaSingleNestedOptions */ class SchemaSingleNestedOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * If set, overwrites the child schema's `_id` option. * * ####Example: * * const childSchema = Schema({ name: String }); * const parentSchema = Schema({ * child: { type: childSchema, _id: false } * }); * parentSchema.path('child').schema.options._id; // false * * @api public * @property of * @memberOf SchemaSingleNestedOptions * @type Function|string * @instance */ Object.defineProperty(SchemaSingleNestedOptions.prototype, '_id', opts); module.exports = SchemaSingleNestedOptions; },{"./SchemaTypeOptions":268,"./propertyOptions":270}],267:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on a string schematype. * * ####Example: * * const schema = new Schema({ name: String }); * schema.path('name').options; // SchemaStringOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaStringOptions */ class SchemaStringOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * Array of allowed values for this path * * @api public * @property enum * @memberOf SchemaStringOptions * @type Array * @instance */ Object.defineProperty(SchemaStringOptions.prototype, 'enum', opts); /** * Attach a validator that succeeds if the data string matches the given regular * expression, and fails otherwise. * * @api public * @property match * @memberOf SchemaStringOptions * @type RegExp * @instance */ Object.defineProperty(SchemaStringOptions.prototype, 'match', opts); /** * If truthy, Mongoose will add a custom setter that lowercases this string * using JavaScript's built-in `String#toLowerCase()`. * * @api public * @property lowercase * @memberOf SchemaStringOptions * @type Boolean * @instance */ Object.defineProperty(SchemaStringOptions.prototype, 'lowercase', opts); /** * If truthy, Mongoose will add a custom setter that removes leading and trailing * whitespace using JavaScript's built-in `String#trim()`. * * @api public * @property trim * @memberOf SchemaStringOptions * @type Boolean * @instance */ Object.defineProperty(SchemaStringOptions.prototype, 'trim', opts); /** * If truthy, Mongoose will add a custom setter that uppercases this string * using JavaScript's built-in `String#toUpperCase()`. * * @api public * @property uppercase * @memberOf SchemaStringOptions * @type Boolean * @instance */ Object.defineProperty(SchemaStringOptions.prototype, 'uppercase', opts); /** * If set, Mongoose will add a custom validator that ensures the given * string's `length` is at least the given number. * * Mongoose supports two different spellings for this option: `minLength` and `minlength`. * `minLength` is the recommended way to specify this option, but Mongoose also supports * `minlength` (lowercase "l"). * * @api public * @property minLength * @memberOf SchemaStringOptions * @type Number * @instance */ Object.defineProperty(SchemaStringOptions.prototype, 'minLength', opts); Object.defineProperty(SchemaStringOptions.prototype, 'minlength', opts); /** * If set, Mongoose will add a custom validator that ensures the given * string's `length` is at most the given number. * * Mongoose supports two different spellings for this option: `maxLength` and `maxlength`. * `maxLength` is the recommended way to specify this option, but Mongoose also supports * `maxlength` (lowercase "l"). * * @api public * @property maxLength * @memberOf SchemaStringOptions * @type Number * @instance */ Object.defineProperty(SchemaStringOptions.prototype, 'maxLength', opts); Object.defineProperty(SchemaStringOptions.prototype, 'maxlength', opts); /** * Sets default [populate options](/docs/populate.html#query-conditions). * * @api public * @property populate * @memberOf SchemaStringOptions * @type Object * @instance */ Object.defineProperty(SchemaStringOptions.prototype, 'populate', opts); /*! * ignore */ module.exports = SchemaStringOptions; },{"./SchemaTypeOptions":268,"./propertyOptions":270}],268:[function(require,module,exports){ 'use strict'; const clone = require('../helpers/clone'); /** * The options defined on a schematype. * * ####Example: * * const schema = new Schema({ name: String }); * schema.path('name').options instanceof mongoose.SchemaTypeOptions; // true * * @api public * @constructor SchemaTypeOptions */ class SchemaTypeOptions { constructor(obj) { if (obj == null) { return this; } Object.assign(this, clone(obj)); } } const opts = require('./propertyOptions'); /** * The type to cast this path to. * * @api public * @property type * @memberOf SchemaTypeOptions * @type Function|String|Object * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'type', opts); /** * Function or object describing how to validate this schematype. * * @api public * @property validate * @memberOf SchemaTypeOptions * @type Function|Object * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'validate', opts); /** * Allows overriding casting logic for this individual path. If a string, the * given string overwrites Mongoose's default cast error message. * * ####Example: * * const schema = new Schema({ * num: { * type: Number, * cast: '{VALUE} is not a valid number' * } * }); * * // Throws 'CastError: "bad" is not a valid number' * schema.path('num').cast('bad'); * * const Model = mongoose.model('Test', schema); * const doc = new Model({ num: 'fail' }); * const err = doc.validateSync(); * * err.errors['num']; // 'CastError: "fail" is not a valid number' * * @api public * @property cast * @memberOf SchemaTypeOptions * @type String * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'cast', opts); /** * If true, attach a required validator to this path, which ensures this path * path cannot be set to a nullish value. If a function, Mongoose calls the * function and only checks for nullish values if the function returns a truthy value. * * @api public * @property required * @memberOf SchemaTypeOptions * @type Function|Boolean * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'required', opts); /** * The default value for this path. If a function, Mongoose executes the function * and uses the return value as the default. * * @api public * @property default * @memberOf SchemaTypeOptions * @type Function|Any * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'default', opts); /** * The model that `populate()` should use if populating this path. * * @api public * @property ref * @memberOf SchemaTypeOptions * @type Function|String * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'ref', opts); /** * Whether to include or exclude this path by default when loading documents * using `find()`, `findOne()`, etc. * * @api public * @property select * @memberOf SchemaTypeOptions * @type Boolean|Number * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'select', opts); /** * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will * build an index on this path when the model is compiled. * * @api public * @property index * @memberOf SchemaTypeOptions * @type Boolean|Number|Object * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'index', opts); /** * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose * will build a unique index on this path when the * model is compiled. [The `unique` option is **not** a validator](/docs/validation.html#the-unique-option-is-not-a-validator). * * @api public * @property unique * @memberOf SchemaTypeOptions * @type Boolean|Number * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'unique', opts); /** * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will * disallow changes to this path once the document * is saved to the database for the first time. Read more about [immutability in Mongoose here](http://thecodebarbarian.com/whats-new-in-mongoose-5-6-immutable-properties.html). * * @api public * @property immutable * @memberOf SchemaTypeOptions * @type Function|Boolean * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'immutable', opts); /** * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will * build a sparse index on this path. * * @api public * @property sparse * @memberOf SchemaTypeOptions * @type Boolean|Number * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'sparse', opts); /** * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose * will build a text index on this path. * * @api public * @property text * @memberOf SchemaTypeOptions * @type Boolean|Number|Object * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'text', opts); /** * Define a transform function for this individual schema type. * Only called when calling `toJSON()` or `toObject()`. * * ####Example: * * const schema = Schema({ * myDate: { * type: Date, * transform: v => v.getFullYear() * } * }); * const Model = mongoose.model('Test', schema); * * const doc = new Model({ myDate: new Date('2019/06/01') }); * doc.myDate instanceof Date; // true * * const res = doc.toObject({ transform: true }); * res.myDate; // 2019 * * @api public * @property transform * @memberOf SchemaTypeOptions * @type Function * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'transform', opts); module.exports = SchemaTypeOptions; },{"../helpers/clone":219,"./propertyOptions":270}],269:[function(require,module,exports){ 'use strict'; const opts = require('./propertyOptions'); class VirtualOptions { constructor(obj) { 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; },{"./propertyOptions":270}],270:[function(require,module,exports){ 'use strict'; module.exports = Object.freeze({ enumerable: true, configurable: true, writable: true, value: void 0 }); },{}],271:[function(require,module,exports){ 'use strict'; /*! * ignore */ module.exports = function(schema) { // ensure the documents receive an id getter unless disabled const autoIdGetter = !schema.paths['id'] && (!schema.options.noVirtualId && schema.options.id); if (!autoIdGetter) { return; } schema.virtual('id').get(idGetter); }; /*! * Returns this documents _id cast to a string. */ function idGetter() { if (this._id != null) { return String(this._id); } return null; } },{}],272:[function(require,module,exports){ (function (global){(function (){ /*! * ignore */ 'use strict'; const assert = require('assert'); const mquery = require('mquery'); /** * Helper for multiplexing promise implementations * * @api private */ const 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 ${lib}`); store._promise = lib; mquery.Promise = lib; }; /*! * Use native promises by default */ store.set(global.Promise); module.exports = store; }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"assert":103,"mquery":317}],273:[function(require,module,exports){ 'use strict'; /*! * Module dependencies */ const checkEmbeddedDiscriminatorKeyProjection = require('./helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection'); const get = require('./helpers/get'); const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue'); const isDefiningProjection = require('./helpers/projection/isDefiningProjection'); const clone = require('./helpers/clone'); /*! * Prepare a set of path options for query population. * * @param {Query} query * @param {Object} options * @return {Array} */ exports.preparePopulationOptions = function preparePopulationOptions(query, options) { const _populate = query.options.populate; const pop = Object.keys(_populate).reduce((vals, key) => vals.concat([_populate[key]]), []); // lean options should trickle through all queries if (options.lean != null) { pop. filter(p => get(p, 'options.lean') == null). forEach(makeLean(options.lean)); } 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) { const _populate = query._mongooseOptions.populate; const pop = Object.keys(_populate).reduce((vals, key) => vals.concat([_populate[key]]), []); // lean options should trickle through all queries if (options.lean != null) { pop. filter(p => get(p, 'options.lean') == null). forEach(makeLean(options.lean)); } const session = get(query, 'options.session', null); if (session != null) { pop.forEach(path => { if (path.options == null) { path.options = { session: session }; return; } if (!('session' in path.options)) { path.options.session = session; } }); } const projection = query._fieldsForExec(); pop.forEach(p => { p._queryProjection = projection; }); 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) { model.hooks.execPreSync('createModel', doc); const discriminatorMapping = model.schema ? model.schema.discriminatorMapping : null; const key = discriminatorMapping && discriminatorMapping.isRoot ? discriminatorMapping.key : null; const value = doc[key]; if (key && value && model.discriminators) { const discriminator = model.discriminators[value] || getDiscriminatorByValue(model, value); if (discriminator) { const _fields = clone(userProvidedFields); exports.applyPaths(_fields, discriminator.schema); return new discriminator(undefined, _fields, true); } } return new model(undefined, fields, { skipId: true, isNew: false, willInit: true }); }; /*! * ignore */ exports.applyPaths = function applyPaths(fields, schema) { // determine if query is selecting or excluding fields let exclude; let keys; let keyIndex; if (fields) { keys = Object.keys(fields); keyIndex = keys.length; while (keyIndex--) { if (keys[keyIndex][0] === '+') { continue; } const 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 const selected = []; const excluded = []; const stack = []; analyzeSchema(schema); switch (exclude) { case true: for (const fieldName of excluded) { fields[fieldName] = 0; } break; case false: if (schema && schema.paths['_id'] && schema.paths['_id'].options && schema.paths['_id'].options.select === false) { fields._id = 0; } for (const fieldName of selected) { fields[fieldName] = fields[fieldName] || 1; } break; case undefined: if (fields == null) { break; } // Any leftover plus paths must in the schema, so delete them (gh-7017) for (const key of Object.keys(fields || {})) { if (key.startsWith('+')) { delete fields[key]; } } // user didn't specify fields, implies returning all fields. // only need to apply excluded fields and delete any plus paths for (const fieldName of excluded) { fields[fieldName] = 0; } break; } function analyzeSchema(schema, prefix) { prefix || (prefix = ''); // avoid recursion if (stack.indexOf(schema) !== -1) { return []; } stack.push(schema); const addedPaths = []; schema.eachPath(function(path, type) { if (prefix) path = prefix + '.' + path; const addedPath = analyzePath(path, type); if (addedPath != null) { addedPaths.push(addedPath); } // nested schemas if (type.schema) { const _addedPaths = analyzeSchema(type.schema, path); // Special case: if discriminator key is the only field that would // be projected in, remove it. if (exclude === false) { checkEmbeddedDiscriminatorKeyProjection(fields, path, type.schema, selected, _addedPaths); } } }); stack.pop(); return addedPaths; } function analyzePath(path, type) { const plusPath = '+' + path; const hasPlusPath = fields && plusPath in fields; if (hasPlusPath) { // forced inclusion delete fields[plusPath]; } if (typeof type.selected !== 'boolean') 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 const pieces = path.split('.'); let cur = ''; for (let i = 0; i < pieces.length; ++i) { cur += cur.length ? '.' + pieces[i] : pieces[i]; if (excluded.indexOf(cur) !== -1) { return; } } // Special case: if user has included a parent path of a discriminator key, // don't explicitly project in the discriminator key because that will // project out everything else under the parent path if (!exclude && get(type, 'options.$skipDiscriminatorCheck', false)) { let cur = ''; for (let i = 0; i < pieces.length; ++i) { cur += (cur.length === 0 ? '' : '.') + pieces[i]; const projection = get(fields, cur, false) || get(fields, cur + '.$', false); if (projection && typeof projection !== 'object') { return; } } } (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(path => typeof path === 'string' && path.startsWith(option.path + '.')). map(path => path.slice(option.path.length + 1)); } option.options.lean = val; }; } /*! * Handle the `WriteOpResult` from the server */ exports.handleDeleteWriteOpResult = function handleDeleteWriteOpResult(callback) { return function _handleDeleteWriteOpResult(error, res) { if (error) { return callback(error); } const mongooseResult = Object.assign({}, res.result); if (get(res, 'result.n', null) != null) { mongooseResult.deletedCount = res.result.n; } if (res.deletedCount != null) { mongooseResult.deletedCount = res.deletedCount; } return callback(null, mongooseResult); }; }; },{"./helpers/clone":219,"./helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection":221,"./helpers/discriminator/getDiscriminatorByValue":223,"./helpers/get":229,"./helpers/projection/isDefiningProjection":239}],274:[function(require,module,exports){ (function (Buffer){(function (){ 'use strict'; /*! * Module dependencies. */ const EventEmitter = require('events').EventEmitter; const Kareem = require('kareem'); const MongooseError = require('./error/mongooseError'); const SchemaType = require('./schematype'); const SchemaTypeOptions = require('./options/SchemaTypeOptions'); const VirtualOptions = require('./options/VirtualOptions'); const VirtualType = require('./virtualtype'); const addAutoId = require('./helpers/schema/addAutoId'); const arrayParentSymbol = require('./helpers/symbols').arrayParentSymbol; const get = require('./helpers/get'); const getIndexes = require('./helpers/schema/getIndexes'); const merge = require('./helpers/schema/merge'); const mpath = require('mpath'); const readPref = require('./driver').get().ReadPreference; const setupTimestamps = require('./helpers/timestamps/setupTimestamps'); const util = require('util'); const utils = require('./utils'); const validateRef = require('./helpers/populate/validateRef'); let MongooseTypes; const queryHooks = require('./helpers/query/applyQueryMiddleware'). middlewareFunctions; const documentHooks = require('./helpers/model/applyHooks').middlewareFunctions; const hookNames = queryHooks.concat(documentHooks). reduce((s, hook) => s.add(hook), new Set()); let id = 0; /** * Schema constructor. * * ####Example: * * const child = new Schema({ name: String }); * const schema = new Schema({ name: String, age: Number, children: [child] }); * const Tree = mongoose.model('Tree', schema); * * // setting schema options * new Schema({ name: String }, { _id: false, autoIndex: false }) * * ####Options: * * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option) * - [autoCreate](/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option) * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true * - [bufferTimeoutMS](/docs/guide.html#bufferTimeoutMS): number - defaults to 10000 (10 seconds). If `bufferCommands` is enabled, the amount of time Mongoose will wait for connectivity to be restablished before erroring out. * - [capped](/docs/guide.html#capped): bool - defaults to false * - [collection](/docs/guide.html#collection): string - no default * - [id](/docs/guide.html#id): bool - defaults to true * - [_id](/docs/guide.html#_id): bool - defaults to true * - [minimize](/docs/guide.html#minimize): bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true * - [read](/docs/guide.html#read): string * - [writeConcern](/docs/guide.html#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://docs.mongodb.com/manual/reference/write-concern/) * - [shardKey](/docs/guide.html#shardKey): object - defaults to `null` * - [strict](/docs/guide.html#strict): bool - defaults to true * - [strictQuery](/docs/guide.html#strictQuery): bool - defaults to false * - [toJSON](/docs/guide.html#toJSON) - object - no default * - [toObject](/docs/guide.html#toObject) - object - no default * - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type' * - [typePojoToMixed](/docs/guide.html#typePojoToMixed) - boolean - defaults to true. Determines whether a type set to a POJO becomes a Mixed path or a Subdocument * - [useNestedStrict](/docs/guide.html#useNestedStrict) - boolean - defaults to false * - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true` * - [versionKey](/docs/guide.html#versionKey): string or object - defaults to "__v" * - [optimisticConcurrency](/docs/guide.html#optimisticConcurrency): bool - defaults to false. Set to true to enable [optimistic concurrency](https://thecodebarbarian.com/whats-new-in-mongoose-5-10-optimistic-concurrency.html). * - [collation](/docs/guide.html#collation): object - defaults to null (which means use no collation) * - [selectPopulatedPaths](/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true` * - [skipVersioning](/docs/guide.html#skipVersioning): object - paths to exclude from versioning * - [timestamps](/docs/guide.html#timestamps): object or boolean - defaults to `false`. If true, Mongoose adds `createdAt` and `updatedAt` properties to your schema and manages those properties for you. * - [storeSubdocValidationError](/docs/guide.html#storeSubdocValidationError): boolean - Defaults to true. If false, Mongoose will wrap validation errors in single nested document subpaths into a single validation error on the single nested subdoc's path. * * ####Options for Nested Schemas: * - `excludeIndexes`: bool - defaults to `false`. If `true`, skip building indexes on this schema's paths. * * ####Note: * * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._ * * @param {Object|Schema|Array} [definition] Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas * @param {Object} [options] * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter * @event `init`: Emitted after the schema is compiled into a `Model`. * @api public */ function Schema(obj, options) { if (!(this instanceof Schema)) { return new Schema(obj, options); } this.obj = obj; this.paths = {}; this.aliases = {}; this.subpaths = {}; this.virtuals = {}; this.singleNestedPaths = {}; this.nested = {}; this.inherits = {}; this.callQueue = []; this._indexes = []; this.methods = {}; this.methodOptions = {}; this.statics = {}; this.tree = {}; this.query = {}; this.childSchemas = []; this.plugins = []; // For internal debugging. Do not use this to try to save a schema in MDB. this.$id = ++id; this.s = { hooks: new Kareem() }; this.options = this.defaultOptions(options); // build paths if (Array.isArray(obj)) { for (const definition of obj) { this.add(definition); } } else if (obj) { this.add(obj); } // check if _id's value is a subdocument (gh-2276) const _idSubDoc = obj && obj._id && utils.isObject(obj._id); // ensure the documents get an auto _id unless disabled const auto_id = !this.paths['_id'] && (!this.options.noId && 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); for (const path of paths) { const options = get(schema.paths[path], 'options'); if (options == null) { continue; } const prop = schema.paths[path].path; const 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)); } } /*! * 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 }); /** * The original object passed to the schema constructor * * ####Example: * * const schema = new Schema({ a: String }).add({ b: String }); * schema.obj; // { a: String } * * @api public * @property obj * @memberOf Schema * @instance */ Schema.prototype.obj; /** * The paths defined on this schema. The keys are the top-level paths * in this schema, and the values are instances of the SchemaType class. * * ####Example: * const schema = new Schema({ name: String }, { _id: false }); * schema.paths; // { name: SchemaString { ... } } * * schema.add({ age: Number }); * schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } } * * @api public * @property paths * @memberOf Schema * @instance */ Schema.prototype.paths; /** * Schema as a tree * * ####Example: * { * '_id' : ObjectId * , 'nested' : { * 'key' : String * } * } * * @api private * @property tree * @memberOf Schema * @instance */ Schema.prototype.tree; /** * Returns a deep copy of the schema * * ####Example: * * const schema = new Schema({ name: String }); * const clone = schema.clone(); * clone === schema; // false * clone.path('name'); // SchemaString { ... } * * @return {Schema} the cloned schema * @api public * @memberOf Schema * @instance */ Schema.prototype.clone = function() { const Constructor = this.base == null ? Schema : this.base.Schema; const s = new Constructor({}, this._userProvidedOptions); s.base = this.base; s.obj = this.obj; s.options = utils.clone(this.options); s.callQueue = this.callQueue.map(function(f) { return f; }); s.methods = utils.clone(this.methods); s.methodOptions = utils.clone(this.methodOptions); s.statics = utils.clone(this.statics); s.query = utils.clone(this.query); s.plugins = Array.prototype.slice.call(this.plugins); s._indexes = utils.clone(this._indexes); s.s.hooks = this.s.hooks.clone(); 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; if (this.discriminatorMapping != null) { s.discriminatorMapping = Object.assign({}, this.discriminatorMapping); } if (this.discriminators != null) { s.discriminators = Object.assign({}, this.discriminators); } s.aliases = Object.assign({}, this.aliases); // Bubble up `init` for backwards compat s.on('init', v => this.emit('init', v)); 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) { const newSchema = new Schema({}, options || this.options); if (!Array.isArray(paths)) { throw new MongooseError('Schema#pick() only accepts an array argument, ' + 'got "' + typeof paths + '"'); } for (const path of paths) { if (this.nested[path]) { newSchema.add({ [path]: get(this.tree, path) }); } else { const schematype = this.path(path); if (schematype == null) { throw new MongooseError('Path `' + path + '` is not in the schema'); } newSchema.add({ [path]: schematype }); } } return newSchema; }; /** * Returns default options for this schema, merged with `options`. * * @param {Object} options * @return {Object} * @api private */ Schema.prototype.defaultOptions = function(options) { if (options && options.safe === false) { options.safe = { w: 0 }; } if (options && options.safe && options.safe.w === 0) { // if you turn off safe writes, then versioning goes off as well options.versionKey = false; } this._userProvidedOptions = options == null ? {} : utils.clone(options); const baseOptions = get(this, 'base.options', {}); options = utils.options({ strict: 'strict' in baseOptions ? baseOptions.strict : true, strictQuery: 'strictQuery' in baseOptions ? baseOptions.strictQuery : false, bufferCommands: true, capped: false, // { size, max, autoIndexId } versionKey: '__v', optimisticConcurrency: false, discriminatorKey: '__t', minimize: true, autoIndex: null, shardKey: null, read: null, validateBeforeSave: true, // the following are only applied at construction time noId: false, // deprecated, use { _id: false } _id: true, noVirtualId: false, // deprecated, use { id: false } id: true, typeKey: 'type', typePojoToMixed: 'typePojoToMixed' in baseOptions ? baseOptions.typePojoToMixed : true }, utils.clone(options)); if (options.read) { options.read = readPref(options.read); } if (options.optimisticConcurrency && !options.versionKey) { throw new MongooseError('Must set `versionKey` if using `optimisticConcurrency`'); } return options; }; /** * 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 || ''; const keys = Object.keys(obj); for (const key of keys) { const fullPath = prefix + key; if (obj[key] == null) { throw new TypeError('Invalid value for schema path `' + fullPath + '`, got value "' + obj[key] + '"'); } // Retain `_id: false` but don't set it as a path, re: gh-8274. if (key === '_id' && obj[key] === false) { continue; } if (obj[key] instanceof VirtualType || get(obj[key], 'constructor.name', null) === 'VirtualType') { this.virtual(obj[key]); continue; } if (Array.isArray(obj[key]) && obj[key].length === 1 && obj[key][0] == null) { throw new TypeError('Invalid value for schema Array path `' + fullPath + '`, got value "' + obj[key][0] + '"'); } if (!(utils.isPOJO(obj[key]) || obj[key] instanceof SchemaTypeOptions)) { // Special-case: Non-options definitely a path so leaf at this node // Examples: Schema instances, SchemaType instances if (prefix) { this.nested[prefix.substr(0, prefix.length - 1)] = true; } this.path(prefix + key, obj[key]); } else if (Object.keys(obj[key]).length < 1) { // Special-case: {} always interpreted as Mixed path so leaf at this node if (prefix) { this.nested[prefix.substr(0, prefix.length - 1)] = true; } this.path(fullPath, obj[key]); // mixed type } else if (!obj[key][this.options.typeKey] || (this.options.typeKey === 'type' && obj[key].type.type)) { // Special-case: POJO with no bona-fide type key - interpret as tree of deep paths so recurse // nested object { last: { name: String }} this.nested[fullPath] = true; this.add(obj[key], fullPath + '.'); } else { // There IS a bona-fide type key that may also be a POJO if (!this.options.typePojoToMixed && utils.isPOJO(obj[key][this.options.typeKey])) { // If a POJO is the value of a type key, make it a subdocument if (prefix) { this.nested[prefix.substr(0, prefix.length - 1)] = true; } // Propage `typePojoToMixed` to implicitly created schemas const opts = { typePojoToMixed: false }; const _schema = new Schema(obj[key][this.options.typeKey], opts); const schemaWrappedPath = Object.assign({}, obj[key], { [this.options.typeKey]: _schema }); this.path(prefix + key, schemaWrappedPath); } else { // Either the type is non-POJO or we interpret it as Mixed anyway if (prefix) { this.nested[prefix.substr(0, prefix.length - 1)] = true; } this.path(prefix + key, obj[key]); } } } const addedKeys = Object.keys(obj). map(key => prefix ? prefix + key : key); aliasFields(this, addedKeys); return this; }; /** * Reserved document keys. * * Keys in this object are names that are rejected in schema declarations * because they conflict with Mongoose functionality. If you create a schema * using `new Schema()` with one of these property names, Mongoose will throw * an error. * * - _posts * - _pres * - collection * - emit * - errors * - get * - init * - isModified * - isNew * - listeners * - modelName * - on * - once * - populated * - prototype * - remove * - removeListener * - save * - schema * - toObject * - validate * * _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on. * * const schema = new Schema(..); * schema.methods.init = function () {} // potentially breaking */ Schema.reserved = Object.create(null); Schema.prototype.reserved = Schema.reserved; const reserved = Schema.reserved; // Core object reserved['prototype'] = // EventEmitter reserved.emit = reserved.listeners = reserved.on = reserved.removeListener = // document properties and functions reserved.collection = reserved.errors = reserved.get = reserved.init = reserved.isModified = reserved.isNew = reserved.populated = reserved.remove = reserved.save = reserved.schema = reserved.toObject = reserved.validate = 1; /** * Gets/sets schema paths. * * Sets a path (if arity 2) * Gets a path (if arity 1) * * ####Example * * schema.path('name') // returns a SchemaType * schema.path('name', Number) // changes the schemaType of `name` to Number * * @param {String} path * @param {Object} constructor * @api public */ Schema.prototype.path = function(path, obj) { // Convert to '.$' to check subpaths re: gh-6405 const cleanPath = _pathToPositionalSyntax(path); if (obj === undefined) { let schematype = _getPath(this, path, cleanPath); if (schematype != null) { return schematype; } // Look for maps const 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 const firstPieceOfPath = path.split('.')[0]; if (reserved[firstPieceOfPath]) { throw new Error('`' + firstPieceOfPath + '` may not be used as a schema pathname'); } if (typeof obj === 'object' && utils.hasUserDefinedProperty(obj, 'ref')) { validateRef(obj.ref, path); } // update the tree const subpaths = path.split(/\./); const last = subpaths.pop(); let branch = this.tree; let fullPath = ''; for (const sub of subpaths) { fullPath = fullPath += (fullPath.length > 0 ? '.' : '') + sub; if (!branch[sub]) { this.nested[fullPath] = true; branch[sub] = {}; } if (typeof branch[sub] !== 'object') { const msg = 'Cannot set nested path `' + path + '`. ' + 'Parent path `' + fullPath + '` already set to type ' + branch[sub].name + '.'; throw new Error(msg); } branch = branch[sub]; } branch[last] = utils.clone(obj); this.paths[path] = this.interpretAsType(path, obj, this.options); const schemaType = this.paths[path]; if (schemaType.$isSchemaMap) { // Maps can have arbitrary keys, so `$*` is internal shorthand for "any key" // The '$' is to imply this path should never be stored in MongoDB so we // can easily build a regexp out of this path, and '*' to imply "any key." const mapPath = path + '.$*'; let _mapType = { type: {} }; if (utils.hasUserDefinedProperty(obj, 'of')) { const isInlineSchema = utils.isPOJO(obj.of) && Object.keys(obj.of).length > 0 && !utils.hasUserDefinedProperty(obj.of, this.options.typeKey); _mapType = isInlineSchema ? new Schema(obj.of) : obj.of; } this.paths[mapPath] = this.interpretAsType(mapPath, _mapType, this.options); schemaType.$__schemaType = this.paths[mapPath]; } if (schemaType.$isSingleNested) { for (const key of Object.keys(schemaType.schema.paths)) { this.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key]; } for (const key of Object.keys(schemaType.schema.singleNestedPaths)) { this.singleNestedPaths[path + '.' + key] = schemaType.schema.singleNestedPaths[key]; } for (const key of Object.keys(schemaType.schema.subpaths)) { this.singleNestedPaths[path + '.' + key] = schemaType.schema.subpaths[key]; } for (const key of Object.keys(schemaType.schema.nested)) { this.singleNestedPaths[path + '.' + key] = 'nested'; } 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) { let arrayPath = path; let _schemaType = schemaType; const toAdd = []; while (_schemaType.$isMongooseArray) { arrayPath = arrayPath + '.$'; // Skip arrays of document arrays if (_schemaType.$isMongooseDocumentArray) { _schemaType.$embeddedSchemaType._arrayPath = arrayPath; _schemaType.$embeddedSchemaType._arrayParentPath = path; _schemaType = _schemaType.$embeddedSchemaType.clone(); } else { _schemaType.caster._arrayPath = arrayPath; _schemaType.caster._arrayParentPath = path; _schemaType = _schemaType.caster.clone(); } _schemaType.path = arrayPath; toAdd.push(_schemaType); } for (const _schemaType of toAdd) { this.subpaths[_schemaType.path] = _schemaType; } } if (schemaType.$isMongooseDocumentArray) { for (const key of Object.keys(schemaType.schema.paths)) { this.subpaths[path + '.' + key] = schemaType.schema.paths[key]; schemaType.schema.paths[key].$isUnderneathDocArray = true; } for (const key of Object.keys(schemaType.schema.subpaths)) { this.subpaths[path + '.' + key] = schemaType.schema.subpaths[key]; schemaType.schema.subpaths[key].$isUnderneathDocArray = true; } for (const key of Object.keys(schemaType.schema.singleNestedPaths)) { if (typeof schemaType.schema.singleNestedPaths[cleanPath] !== 'object') { continue; } this.subpaths[path + '.' + key] = schemaType.schema.singleNestedPaths[key]; schemaType.schema.singleNestedPaths[key].$isUnderneathDocArray = true; } } return this; }; /*! * ignore */ function gatherChildSchemas(schema) { const childSchemas = []; for (const path of Object.keys(schema.paths)) { const schematype = schema.paths[path]; if (schematype.$isMongooseDocumentArray || schematype.$isSingleNested) { childSchemas.push({ schema: schematype.schema, model: schematype.caster }); } } 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) { for (const _path of Object.keys(schema.paths)) { if (!_path.includes('.$*')) { continue; } const re = new RegExp('^' + _path.replace(/\.\$\*/g, '\\.[^.]+') + '$'); if (re.test(path)) { return schema.paths[_path]; } } 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; } const clone = obj.clone(); clone.path = path; return clone; } // If this schema has an associated Mongoose object, use the Mongoose object's // copy of SchemaTypes re: gh-7158 gh-6933 const MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types; if (!utils.isPOJO(obj) && !(obj instanceof SchemaTypeOptions)) { const constructorName = utils.getFunctionName(obj.constructor); if (constructorName !== 'Object') { const oldObj = obj; obj = {}; obj[options.typeKey] = oldObj; } } // Get the type making sure to allow keys named "type" // and default to mixed if not specified. // { type: { type: String, default: 'freshcut' } } let type = obj[options.typeKey] && (options.typeKey !== 'type' || !obj.type.type) ? obj[options.typeKey] : {}; let name; if (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` let cast = (type === Array || type === 'array') ? obj.cast || obj.of : type[0]; if (cast && cast.instanceOfSchema) { return new MongooseTypes.DocumentArray(path, cast, obj); } if (cast && cast[options.typeKey] && cast[options.typeKey].instanceOfSchema) { 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); } if (typeof cast === 'string') { cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)]; } else if (cast && (!cast[options.typeKey] || (options.typeKey === 'type' && cast.type.type)) && utils.isPOJO(cast)) { if (Object.keys(cast).length) { // The `minimize` and `typeKey` options propagate to child schemas // declared inline, like `{ arr: [{ val: { $type: String } }] }`. // See gh-3560 const childSchemaOptions = { minimize: options.minimize }; if (options.typeKey) { childSchemaOptions.typeKey = options.typeKey; } // propagate 'strict' option to child schema if (options.hasOwnProperty('strict')) { childSchemaOptions.strict = options.strict; } if (options.hasOwnProperty('typePojoToMixed')) { childSchemaOptions.typePojoToMixed = options.typePojoToMixed; } if (this._userProvidedOptions.hasOwnProperty('_id')) { childSchemaOptions._id = this._userProvidedOptions._id; } else if (Schema.Types.DocumentArray.defaultOptions && Schema.Types.DocumentArray.defaultOptions._id != null) { childSchemaOptions._id = Schema.Types.DocumentArray.defaultOptions._id; } const childSchema = new Schema(cast, childSchemaOptions); childSchema.$implicitlyCreated = true; return new MongooseTypes.DocumentArray(path, childSchema, obj); } else { // Special case: empty object becomes mixed return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj); } } if (cast) { type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type) ? cast[options.typeKey] : cast; name = typeof type === 'string' ? type : type.schemaName || utils.getFunctionName(type); if (!MongooseTypes.hasOwnProperty(name)) { throw new TypeError('Invalid schema configuration: ' + `\`${name}\` is not a valid type within the array \`${path}\`.` + 'See http://bit.ly/mongoose-schematypes for a list of valid schema types.'); } } return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options); } if (type && type.instanceOfSchema) { return new MongooseTypes.Embedded(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'; } if (MongooseTypes[name] == null) { throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` + `a valid type at path \`${path}\`. See ` + 'http://bit.ly/mongoose-schematypes for a list of valid schema types.'); } return new MongooseTypes[name](path, obj); }; /** * Iterates the schemas paths similar to Array#forEach. * * The callback is passed the pathname and the schemaType instance. * * ####Example: * * const userSchema = new Schema({ name: String, registeredAt: Date }); * userSchema.eachPath((pathname, schematype) => { * // Prints twice: * // name SchemaString { ... } * // registeredAt SchemaDate { ... } * console.log(pathname, schematype); * }); * * @param {Function} fn callback function * @return {Schema} this * @api public */ Schema.prototype.eachPath = function(fn) { const keys = Object.keys(this.paths); const len = keys.length; for (let 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; } const paths = Object.keys(this.paths); let i = paths.length; const ret = []; while (i--) { const path = paths[i]; if (this.paths[path].isRequired) { ret.push(path); } } this._requiredpaths = ret; return this._requiredpaths; }; /** * 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 const cleanPath = _pathToPositionalSyntax(path); if (this.paths.hasOwnProperty(path)) { return 'real'; } if (this.virtuals.hasOwnProperty(path)) { return 'virtual'; } if (this.nested.hasOwnProperty(path)) { return 'nested'; } if (this.subpaths.hasOwnProperty(cleanPath) || this.subpaths.hasOwnProperty(path)) { return 'real'; } const singleNestedPath = this.singleNestedPaths.hasOwnProperty(cleanPath) || this.singleNestedPaths.hasOwnProperty(path); if (singleNestedPath) { return singleNestedPath === 'nested' ? 'nested' : 'real'; } // Look for maps const 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) { const subpaths = path.split(/\./g); path = ''; for (let i = 0; i < subpaths.length; ++i) { path = i > 0 ? path + '.' + subpaths[i] : subpaths[i]; if (this.paths.hasOwnProperty(path) && this.paths[path] instanceof MongooseTypes.Mixed) { return this.paths[path]; } } 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) { const subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean); if (subpaths.length < 2) { return self.paths.hasOwnProperty(subpaths[0]) ? self.paths[subpaths[0]] : 'adhocOrUndefined'; } let val = self.path(subpaths[0]); let isNested = false; if (!val) { return 'adhocOrUndefined'; } const last = subpaths.length - 1; for (let i = 1; i < subpaths.length; ++i) { isNested = false; const 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; } const 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) { const remainingArgs = Array.prototype.slice.call(arguments, 1); for (const fn of hookNames) { if (name.test(fn)) { this.pre.apply(this, [fn].concat(remainingArgs)); } } return this; } if (Array.isArray(name)) { const remainingArgs = Array.prototype.slice.call(arguments, 1); for (const el of name) { this.pre.apply(this, [el].concat(remainingArgs)); } return this; } this.s.hooks.pre.apply(this.s.hooks, arguments); return this; }; /** * Defines a post hook for the document * * const schema = new Schema(..); * schema.post('save', function (doc) { * console.log('this fired after a document was saved'); * }); * * schema.post('find', function(docs) { * console.log('this fired after you ran a find query'); * }); * * schema.post(/Many$/, function(res) { * console.log('this fired after you ran `updateMany()` or `deleteMany()`); * }); * * const Model = mongoose.model('Model', schema); * * const m = new Model(..); * m.save(function(err) { * console.log('this fires after the `post` hook'); * }); * * m.find(function(err, docs) { * console.log('this fires after the post find hook'); * }); * * @param {String|RegExp} The method name or regular expression to match method name * @param {Object} [options] * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware. * @param {Function} fn callback * @see middleware http://mongoosejs.com/docs/middleware.html * @see kareem http://npmjs.org/package/kareem * @api public */ Schema.prototype.post = function(name) { if (name instanceof RegExp) { const remainingArgs = Array.prototype.slice.call(arguments, 1); for (const fn of hookNames) { if (name.test(fn)) { this.post.apply(this, [fn].concat(remainingArgs)); } } return this; } if (Array.isArray(name)) { const remainingArgs = Array.prototype.slice.call(arguments, 1); for (const el of name) { this.post.apply(this, [el].concat(remainingArgs)); } return this; } this.s.hooks.post.apply(this.s.hooks, arguments); return this; }; /** * 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) { for (const plugin of this.plugins) { if (plugin.fn === fn) { return this; } } } 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](./guide.html#methods) * * @param {String|Object} method name * @param {Function} [fn] * @api public */ Schema.prototype.method = function(name, fn, options) { if (typeof name !== 'string') { for (const i in name) { this.methods[i] = name[i]; this.methodOptions[i] = utils.clone(options); } } else { this.methods[name] = fn; this.methodOptions[name] = utils.clone(options); } return this; }; /** * Adds static "class" methods to Models compiled from this schema. * * ####Example * * const schema = new Schema(..); * // Equivalent to `schema.statics.findByName = function(name) {}`; * schema.static('findByName', function(name) { * return this.find({ name: name }); * }); * * const Drink = mongoose.model('Drink', schema); * await Drink.findByName('LaCroix'); * * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics. * * @param {String|Object} name * @param {Function} [fn] * @api public * @see Statics /docs/guide.html#statics */ Schema.prototype.static = function(name, fn) { if (typeof name !== 'string') { for (const i in name) { this.statics[i] = name[i]; } } else { this.statics[name] = fn; } return this; }; /** * Defines an index (most likely compound) for this schema. * * ####Example * * schema.index({ first: 1, last: -1 }) * * @param {Object} fields * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex) * @param {String} [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 'safe': setSafe(this.options, value); this._userProvidedOptions[key] = this.options[key]; break; case 'timestamps': this.setupTimestamp(value); this.options[key] = value; this._userProvidedOptions[key] = this.options[key]; break; case '_id': this.options[key] = value; this._userProvidedOptions[key] = this.options[key]; if (value && !this.paths['_id']) { addAutoId(this); } else if (!value && this.paths['_id'] != null && this.paths['_id'].auto) { this.remove('_id'); } break; default: this.options[key] = value; this._userProvidedOptions[key] = this.options[key]; break; } return this; }; /*! * ignore */ const safeDeprecationWarning = 'Mongoose: The `safe` option for schemas is ' + 'deprecated. Use the `writeConcern` option instead: ' + 'http://bit.ly/mongoose-write-concern'; const setSafe = util.deprecate(function setSafe(options, value) { options.safe = value === false ? { w: 0 } : value; }, safeDeprecationWarning); /** * Gets a schema option. * * ####Example: * * schema.get('strict'); // true * schema.set('strict', false); * schema.get('strict'); // false * * @param {String} key option name * @api public * @return {Any} the option's value */ Schema.prototype.get = function(key) { return this.options[key]; }; /** * The allowed index types * * @receiver Schema * @static indexTypes * @api public */ const indexTypes = '2d 2dsphere hashed text'.split(' '); Object.defineProperty(Schema, 'indexTypes', { get: function() { return indexTypes; }, set: function() { 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. * * ####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(); * * @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](populate.html#populate-virtuals). * @param {String|Function} [options.localField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information. * @param {String|Function} [options.foreignField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information. * @param {Boolean|Function} [options.justOne=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), will be a single doc or `null`. Otherwise, the populate virtual will be an array. * @param {Boolean} [options.count=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), this populate virtual will contain the number of documents rather than the documents themselves when you `populate()`. * @param {Function|null} [options.get=null] Adds a [getter](/docs/tutorials/getters-setters.html) to this virtual to transform the populated doc. * @return {VirtualType} */ Schema.prototype.virtual = function(name, options) { if (name instanceof VirtualType || (name != null && name.constructor.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)) { const _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); } }); const 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); } return virtual; } const virtuals = this.virtuals; const 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); // Workaround for gh-8198: if virtual is under document array, make a fake // virtual. See gh-8210 let cur = parts[0]; for (let i = 0; i < parts.length - 1; ++i) { if (this.paths[cur] != null && this.paths[cur].$isMongooseDocumentArray) { const remnant = parts.slice(i + 1).join('.'); const v = this.paths[cur].schema.virtual(remnant); v.get((v, virtual, doc) => { const parent = doc.__parentArray[arrayParentSymbol]; const path = cur + '.' + doc.__index + '.' + remnant; return parent.get(path); }); break; } cur += '.' + parts[i + 1]; } 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]) { const allKeys = Object.keys(this.paths). concat(Object.keys(this.nested)); for (const path of allKeys) { if (path.startsWith(name + '.')) { delete this.paths[path]; delete this.nested[path]; _deletePath(this, path); } } delete this.nested[name]; _deletePath(this, name); return; } delete this.paths[name]; _deletePath(this, name); }, this); } return this; }; /*! * ignore */ function _deletePath(schema, name) { const pieces = name.split('.'); const last = pieces.pop(); let branch = schema.tree; for (const piece of pieces) { branch = branch[piece]; } delete branch[last]; } /** * Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static), * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions) * to schema [virtuals](http://mongoosejs.com/docs/guide.html#virtuals), * [statics](http://mongoosejs.com/docs/guide.html#statics), and * [methods](http://mongoosejs.com/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)$/)) { return; } const method = Object.getOwnPropertyDescriptor(model, name); if (typeof method.value === 'function') { this.static(name, method.value); } }, this); } // Add methods and virtuals Object.getOwnPropertyNames(model.prototype).forEach(function(name) { if (name.match(/^(constructor)$/)) { return; } const method = Object.getOwnPropertyDescriptor(model.prototype, name); if (!virtualsOnly) { if (typeof method.value === 'function') { this.method(name, method.value); } } if (typeof method.get === 'function') { if (this.virtuals[name]) { this.virtuals[name].getters = []; } this.virtual(name).get(method.get); } if (typeof method.set === 'function') { if (this.virtuals[name]) { this.virtuals[name].setters = []; } this.virtual(name).set(method.set); } }, this); return this; }; /*! * ignore */ Schema.prototype._getSchema = function(path) { const _this = this; const pathschema = _this.path(path); const resultPath = []; if (pathschema) { pathschema.$fullPath = path; return pathschema; } function search(parts, schema) { let p = parts.length + 1; let foundschema; let trypath; while (p--) { trypath = parts.slice(0, p).join('.'); foundschema = schema.path(trypath); if (foundschema) { resultPath.push(trypath); if (foundschema.caster) { // array of Mixed? if (foundschema.caster instanceof MongooseTypes.Mixed) { foundschema.caster.$fullPath = resultPath.join('.'); return foundschema.caster; } // Now that we found the array, we need to check if there // are remaining document paths to look up for casting. // Also we need to handle array.$.path since schema.path // doesn't work for that. // If there is no foundschema.schema we are dealing with // a path like array.$ if (p !== parts.length) { if (foundschema.schema) { let ret; if (parts[p] === '$' || isArrayFilter(parts[p])) { if (p + 1 === parts.length) { // comments.$ return foundschema; } // comments.$.comments.$.title ret = search(parts.slice(p + 1), foundschema.schema); if (ret) { ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || !foundschema.schema.$isSingleNested; } return ret; } // this is the last path of the selector ret = search(parts.slice(p), foundschema.schema); if (ret) { ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || !foundschema.schema.$isSingleNested; } return ret; } } } else if (foundschema.$isSchemaMap) { if (p + 1 >= parts.length) { return foundschema.$__schemaType; } const ret = search(parts.slice(p + 1), foundschema.$__schemaType.schema); return ret; } foundschema.$fullPath = resultPath.join('.'); return foundschema; } } } // look for arrays const parts = path.split('.'); for (let i = 0; i < parts.length; ++i) { if (parts[i] === '$' || isArrayFilter(parts[i])) { // Re: gh-5628, because `schema.path()` doesn't take $ into account. parts[i] = '0'; } } return search(parts, _this); }; /*! * ignore */ Schema.prototype._getPathType = function(path) { const _this = this; const pathschema = _this.path(path); if (pathschema) { return 'real'; } function search(parts, schema) { let p = parts.length + 1, foundschema, trypath; while (p--) { trypath = parts.slice(0, p).join('.'); foundschema = schema.path(trypath); if (foundschema) { if (foundschema.caster) { // array of Mixed? if (foundschema.caster instanceof MongooseTypes.Mixed) { return { schema: foundschema, pathType: 'mixed' }; } // Now that we found the array, we need to check if there // are remaining document paths to look up for casting. // Also we need to handle array.$.path since schema.path // doesn't work for that. // If there is no foundschema.schema we are dealing with // a path like array.$ if (p !== parts.length && foundschema.schema) { if (parts[p] === '$' || isArrayFilter(parts[p])) { if (p === parts.length - 1) { return { schema: foundschema, pathType: 'nested' }; } // comments.$.comments.$.title return search(parts.slice(p + 1), foundschema.schema); } // this is the last path of the selector return search(parts.slice(p), foundschema.schema); } return { 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(']'); } /*! * 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](#schema-string-js) * - [Number](#schema-number-js) * - [Boolean](#schema-boolean-js) | Bool * - [Array](#schema-array-js) * - [Buffer](#schema-buffer-js) * - [Date](#schema-date-js) * - [ObjectId](#schema-objectid-js) | Oid * - [Mixed](#schema-mixed-js) * * 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 = require('./schema/index'); /*! * ignore */ exports.ObjectId = MongooseTypes.ObjectId; }).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) },{"../../is-buffer/index.js":179,"./driver":196,"./error/mongooseError":207,"./helpers/get":229,"./helpers/model/applyHooks":236,"./helpers/populate/validateRef":238,"./helpers/query/applyQueryMiddleware":242,"./helpers/schema/addAutoId":244,"./helpers/schema/getIndexes":246,"./helpers/schema/merge":249,"./helpers/symbols":252,"./helpers/timestamps/setupTimestamps":253,"./options/SchemaTypeOptions":268,"./options/VirtualOptions":269,"./schema/index":282,"./schematype":295,"./utils":307,"./virtualtype":308,"events":177,"kareem":182,"mpath":310,"util":332}],275:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const CastError = require('../error/cast'); const EventEmitter = require('events').EventEmitter; const ObjectExpectedError = require('../error/objectExpected'); const SchemaSingleNestedOptions = require('../options/SchemaSingleNestedOptions'); const SchemaType = require('../schematype'); const $exists = require('./operators/exists'); const castToNumber = require('./operators/helpers').castToNumber; const discriminator = require('../helpers/model/discriminator'); const geospatial = require('./operators/geospatial'); const get = require('../helpers/get'); const getConstructor = require('../helpers/discriminator/getConstructor'); const handleIdOption = require('../helpers/schema/handleIdOption'); const internalToObjectOptions = require('../options').internalToObjectOptions; let Subdocument; module.exports = SingleNestedPath; /** * Single nested subdocument SchemaType constructor. * * @param {Schema} schema * @param {String} key * @param {Object} options * @inherits SchemaType * @api public */ function SingleNestedPath(schema, path, options) { schema = handleIdOption(schema, options); this.caster = _createConstructor(schema); this.caster.path = path; this.caster.prototype.$basePath = path; this.schema = schema; this.$isSingleNested = true; SchemaType.call(this, path, options, 'Embedded'); } /*! * ignore */ SingleNestedPath.prototype = Object.create(SchemaType.prototype); SingleNestedPath.prototype.constructor = SingleNestedPath; SingleNestedPath.prototype.OptionsConstructor = SchemaSingleNestedOptions; /*! * ignore */ function _createConstructor(schema, baseClass) { // lazy load Subdocument || (Subdocument = require('../types/subdocument')); const _embedded = function SingleNested(value, path, parent) { const _this = this; this.$__parent = parent; Subdocument.apply(this, arguments); this.$session(this.ownerDocument().$session()); if (parent) { parent.on('save', function() { _this.emit('save', _this); _this.constructor.emit('save', _this); }); parent.on('isNew', function(val) { _this.isNew = val; _this.emit('isNew', val); _this.constructor.emit('isNew', val); }); } }; const proto = baseClass != null ? baseClass.prototype : Subdocument.prototype; _embedded.prototype = Object.create(proto); _embedded.prototype.$__setSchema(schema); _embedded.prototype.constructor = _embedded; _embedded.schema = schema; _embedded.$isSingleNested = true; _embedded.events = new EventEmitter(); _embedded.prototype.toBSON = function() { return this.toObject(internalToObjectOptions); }; // apply methods for (const i in schema.methods) { _embedded.prototype[i] = schema.methods[i]; } // apply statics for (const i in schema.statics) { _embedded[i] = schema.statics[i]; } for (const i in EventEmitter.prototype) { _embedded[i] = EventEmitter.prototype[i]; } 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 */ SingleNestedPath.prototype.$conditionalHandlers.$geoWithin = function handle$geoWithin(val) { return { $geometry: this.castForQuery(val.$geometry) }; }; /*! * ignore */ SingleNestedPath.prototype.$conditionalHandlers.$near = SingleNestedPath.prototype.$conditionalHandlers.$nearSphere = geospatial.cast$near; SingleNestedPath.prototype.$conditionalHandlers.$within = SingleNestedPath.prototype.$conditionalHandlers.$geoWithin = geospatial.cast$within; SingleNestedPath.prototype.$conditionalHandlers.$geoIntersects = geospatial.cast$geoIntersects; SingleNestedPath.prototype.$conditionalHandlers.$minDistance = castToNumber; SingleNestedPath.prototype.$conditionalHandlers.$maxDistance = castToNumber; SingleNestedPath.prototype.$conditionalHandlers.$exists = $exists; /** * Casts contents * * @param {Object} value * @api private */ SingleNestedPath.prototype.cast = function(val, doc, init, priorVal, options) { if (val && val.$isSingleNested && val.parent === doc) { return val; } if (val != null && (typeof val !== 'object' || Array.isArray(val))) { throw new ObjectExpectedError(this.path, val); } const Constructor = getConstructor(this.caster, val); let subdoc; // Only pull relevant selected paths and pull out the base path const parentSelected = get(doc, '$__.selected', {}); const path = this.path; const selected = Object.keys(parentSelected).reduce((obj, key) => { if (key.startsWith(path + '.')) { obj[key.substr(path.length + 1)] = parentSelected[key]; } return obj; }, {}); options = Object.assign({}, options, { priorDoc: priorVal }); if (init) { subdoc = new Constructor(void 0, selected, doc); subdoc.init(val); } else { if (Object.keys(val).length === 0) { return new Constructor({}, selected, doc, undefined, options); } return 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 */ SingleNestedPath.prototype.castForQuery = function($conditional, val, options) { let handler; if (arguments.length === 2) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error('Can\'t use ' + $conditional); } return handler.call(this, val); } val = $conditional; if (val == null) { return val; } if (this.options.runSetters) { val = this._applySetters(val); } const Constructor = getConstructor(this.caster, val); const overrideStrict = options != null && options.strict != null ? options.strict : void 0; try { val = new Constructor(val, overrideStrict); } catch (error) { // Make sure we always wrap in a CastError (gh-6803) if (!(error instanceof CastError)) { throw new CastError('Embedded', val, this.path, error, this); } throw error; } return val; }; /** * Async validation on this single nested doc. * * @api private */ SingleNestedPath.prototype.doValidate = function(value, fn, scope, options) { const Constructor = getConstructor(this.caster, value); if (options && options.skipSchemaValidators) { if (!(value instanceof Constructor)) { value = new Constructor(value, null, scope); } return value.validate(fn); } 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 */ SingleNestedPath.prototype.doValidateSync = function(value, scope, options) { if (!options || !options.skipSchemaValidators) { const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope); if (schemaTypeError) { return schemaTypeError; } } if (!value) { return; } return value.validateSync(); }; /** * Adds a discriminator to this single nested subdocument. * * ####Example: * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' }); * const schema = Schema({ shape: shapeSchema }); * * const singleNestedPath = parentSchema.path('shape'); * singleNestedPath.discriminator('Circle', Schema({ radius: Number })); * * @param {String} name * @param {Schema} schema fields to add to the schema for instances of this sub-class * @param {String} [value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model * @see discriminators /docs/discriminators.html * @api public */ SingleNestedPath.prototype.discriminator = function(name, schema, value) { schema = discriminator(this.caster, name, schema, value); this.caster.discriminators[name] = _createConstructor(schema, this.caster); return this.caster.discriminators[name]; }; /** * Sets a default option for all SingleNestedPath instances. * * ####Example: * * // Make all numbers have option `min` equal to 0. * mongoose.Schema.Embedded.set('required', true); * * @param {String} option - The option you'd like to set the value for * @param {*} value - value for option * @return {undefined} * @function set * @static * @api public */ SingleNestedPath.defaultOptions = {}; SingleNestedPath.set = SchemaType.set; /*! * ignore */ SingleNestedPath.prototype.clone = function() { const options = Object.assign({}, this.options); const schematype = new this.constructor(this.schema, this.path, options); schematype.validators = this.validators.slice(); if (this.requiredValidator !== undefined) { schematype.requiredValidator = this.requiredValidator; } schematype.caster.discriminators = Object.assign({}, this.caster.discriminators); return schematype; }; },{"../error/cast":202,"../error/objectExpected":209,"../helpers/discriminator/getConstructor":222,"../helpers/get":229,"../helpers/model/discriminator":237,"../helpers/schema/handleIdOption":247,"../options":257,"../options/SchemaSingleNestedOptions":266,"../schematype":295,"../types/subdocument":306,"./operators/exists":288,"./operators/geospatial":289,"./operators/helpers":290,"events":177}],276:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const $exists = require('./operators/exists'); const $type = require('./operators/type'); const MongooseError = require('../error/mongooseError'); const SchemaArrayOptions = require('../options/SchemaArrayOptions'); const SchemaType = require('../schematype'); const CastError = SchemaType.CastError; const Mixed = require('./mixed'); const arrayDepth = require('../helpers/arrayDepth'); const cast = require('../cast'); const get = require('../helpers/get'); const isOperator = require('../helpers/query/isOperator'); const util = require('util'); const utils = require('../utils'); const castToNumber = require('./operators/helpers').castToNumber; const geospatial = require('./operators/geospatial'); const getDiscriminatorByValue = require('../helpers/discriminator/getDiscriminatorByValue'); let MongooseArray; let EmbeddedDoc; const isNestedArraySymbol = Symbol('mongoose#isNestedArray'); /** * Array SchemaType constructor * * @param {String} key * @param {SchemaType} cast * @param {Object} options * @inherits SchemaType * @api public */ function SchemaArray(key, cast, options, schemaOptions) { // lazy load EmbeddedDoc || (EmbeddedDoc = require('../types').Embedded); let typeKey = 'type'; if (schemaOptions && schemaOptions.typeKey) { typeKey = schemaOptions.typeKey; } this.schemaOptions = schemaOptions; if (cast) { let castOptions = {}; if (utils.isPOJO(cast)) { if (cast[typeKey]) { // support { type: Woot } castOptions = utils.clone(cast); // do not alter user arguments delete castOptions[typeKey]; cast = cast[typeKey]; } else { cast = Mixed; } } if (cast === Object) { cast = Mixed; } // support { type: 'String' } const name = typeof cast === 'string' ? cast : utils.getFunctionName(cast); const Types = require('./index.js'); const 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) { this.caster = new caster(null, castOptions); } else { this.caster = caster; } this.$embeddedSchemaType = this.caster; if (!(this.caster instanceof EmbeddedDoc)) { this.caster.path = key; } } this.$isMongooseArray = true; SchemaType.call(this, key, options, 'Array'); let defaultArr; let fn; if (this.defaultValue != null) { defaultArr = this.defaultValue; fn = typeof defaultArr === 'function'; } if (!('defaultValue' in this) || this.defaultValue !== void 0) { const defaultFn = function() { let arr = []; if (fn) { arr = defaultArr.call(this); } else if (defaultArr != null) { arr = arr.concat(defaultArr); } // Leave it up to `cast()` to convert the array return arr; }; defaultFn.$runBeforeSetters = !fn; this.default(defaultFn); } } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ SchemaArray.schemaName = 'Array'; /** * Options for all arrays. * * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting. * * @static options * @api public */ SchemaArray.options = { castNonArrays: true }; 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 * @static * @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 * @static * @api public */ SchemaArray.checkRequired = SchemaType.checkRequired; /** * Check if the given value satisfies the `required` validator. * * @param {Any} value * @param {Document} doc * @return {Boolean} * @api public */ SchemaArray.prototype.checkRequired = function checkRequired(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { return !!value; } // `require('util').inherits()` does **not** copy static properties, and // plugins like mongoose-float use `inherits()` for pre-ES6. const _checkRequired = typeof this.constructor.checkRequired == 'function' ? this.constructor.checkRequired() : SchemaArray.checkRequired(); return _checkRequired(value); }; /** * 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() { let arr = this; while (true) { const instance = get(arr, 'caster.instance'); if (instance === 'Array') { arr = arr.caster; continue; } if (instance !== 'String' && instance !== 'Number') { throw new Error('`enum` can only be set on an array of strings or numbers ' + ', not ' + instance); } break; } let 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.populated(this.path)) { // means the object id was populated return value; } const ret = SchemaType.prototype.applyGetters.call(this, value, scope); if (Array.isArray(ret)) { const len = ret.length; for (let i = 0; i < len; ++i) { ret[i] = this.caster.applyGetters(ret[i], scope); } } return ret; }; SchemaArray.prototype._applySetters = function(value, scope, init, priorVal) { if (this.casterConstructor instanceof SchemaArray && SchemaArray.options.castNonArrays && !this[isNestedArraySymbol]) { // Check nesting levels and wrap in array if necessary let depth = 0; let arr = this; while (arr != null && arr instanceof SchemaArray && !arr.$isMongooseDocumentArray) { ++depth; arr = arr.casterConstructor; } // No need to wrap empty arrays if (value != null && value.length > 0) { const valueDepth = arrayDepth(value); if (valueDepth.min === valueDepth.max && valueDepth.max < depth && valueDepth.containsNonArrayItem) { for (let i = valueDepth.max; i < depth; ++i) { value = [value]; } } } } return 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 = require('../types').Array); let i; let l; if (Array.isArray(value)) { if (!value.length && doc) { const indexes = doc.schema.indexedPaths(); const arrayPath = this.path; for (i = 0, l = indexes.length; i < l; ++i) { const pathIndex = indexes[i][0][arrayPath]; if (pathIndex === '2dsphere' || pathIndex === '2d') { return; } } // Special case: if this index is on the parent of what looks like // GeoJSON, skip setting the default to empty array re: #1668, #3233 const arrayGeojsonPath = this.path.endsWith('.coordinates') ? this.path.substr(0, this.path.lastIndexOf('.')) : null; if (arrayGeojsonPath != null) { for (i = 0, l = indexes.length; i < l; ++i) { const pathIndex = indexes[i][0][arrayGeojsonPath]; if (pathIndex === '2dsphere') { return; } } } } if (!(value && value.isMongooseArray)) { value = MongooseArray(value, get(options, 'path', null) || this._arrayPath || this.path, doc, this); } else if (value && value.isMongooseArray) { // We need to create a new array, otherwise change tracking will // update the old doc (gh-4449) value = MongooseArray(value, get(options, 'path', null) || this._arrayPath || this.path, doc, this); } const isPopulated = doc != null && doc.$__ != null && doc.populated(this.path); if (isPopulated && init) { return value; } const caster = this.caster; if (caster && this.casterConstructor !== Mixed) { try { const len = value.length; for (i = 0; i < len; i++) { // Special case: number arrays disallow undefined. // Re: gh-840 // See commit 1298fe92d2c790a90594bd08199e45a4a09162a6 if (caster.instance === 'Number' && value[i] === void 0) { throw new MongooseError('Mongoose number arrays disallow storing undefined'); } const opts = {}; // Perf: creating `arrayPath` is expensive for large arrays. // We only need `arrayPath` if this is a nested array, so // skip if possible. if (caster.$isMongooseArray) { if (options != null && options.arrayPath != null) { opts.arrayPath = options.arrayPath + '.' + i; } else if (this.caster._arrayParentPath != null) { opts.arrayPath = this.caster._arrayParentPath + '.' + i; } } value[i] = caster.applySetters(value[i], doc, init, void 0, opts); } } catch (e) { // rethrow throw new CastError('[' + e.kind + ']', util.inspect(value), this.path + '.' + i, e, this); } } 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.discriminator = function(name, schema) { let arr = this; // eslint-disable-line consistent-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() { const options = Object.assign({}, this.options); const schematype = new this.constructor(this.path, this.caster, options, this.schemaOptions); schematype.validators = this.validators.slice(); if (this.requiredValidator !== undefined) { schematype.requiredValidator = this.requiredValidator; } return schematype; }; /** * Casts values for queries. * * @param {String} $conditional * @param {any} [value] * @api private */ SchemaArray.prototype.castForQuery = function($conditional, value) { let handler; let 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; let Constructor = this.casterConstructor; if (val && Constructor.discriminators && Constructor.schema && Constructor.schema.options && Constructor.schema.options.discriminatorKey) { if (typeof val[Constructor.schema.options.discriminatorKey] === 'string' && Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]) { Constructor = Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]; } else { const constructorByValue = getDiscriminatorByValue(Constructor, val[Constructor.schema.options.discriminatorKey]); if (constructorByValue) { Constructor = constructorByValue; } } } const proto = this.casterConstructor.prototype; let method = proto && (proto.castForQuery || proto.cast); if (!method && Constructor.castForQuery) { method = Constructor.castForQuery; } const caster = this.caster; if (Array.isArray(val)) { this.setters.reverse().forEach(setter => { val = setter.call(this, val, this); }); val = val.map(function(v) { if (utils.isObject(v) && v.$elemMatch) { return v; } if (method) { v = method.call(caster, v); return v; } if (v != null) { v = new Constructor(v); return v; } return v; }); } else if (method) { val = method.call(caster, val); } else if (val != null) { val = new Constructor(val); } } return val; }; function cast$all(val) { if (!Array.isArray(val)) { val = [val]; } val = val.map(function(v) { if (utils.isObject(v)) { const o = {}; o[this.path] = v; return cast(this.casterConstructor.schema, o)[this.path]; } return v; }, this); return this.castForQuery(val); } function cast$elemMatch(val) { const keys = Object.keys(val); const numKeys = keys.length; for (let i = 0; i < numKeys; ++i) { const key = keys[i]; const value = val[key]; if (isOperator(key) && value != null) { val[key] = this.castForQuery(key, value); } } // Is this an embedded discriminator and is the discriminator key set? // If so, use the discriminator schema. See gh-7449 const discriminatorKey = get(this, 'casterConstructor.schema.options.discriminatorKey'); const discriminators = get(this, 'casterConstructor.schema.discriminators', {}); if (discriminatorKey != null && val[discriminatorKey] != null && discriminators[val[discriminatorKey]] != null) { return cast(discriminators[val[discriminatorKey]], val); } return cast(this.casterConstructor.schema, val); } const 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'); } const ret = []; for (const obj of val) { ret.push(cast(this.casterConstructor.schema, obj)); } 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.$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; },{"../cast":187,"../error/mongooseError":207,"../helpers/arrayDepth":218,"../helpers/discriminator/getDiscriminatorByValue":223,"../helpers/get":229,"../helpers/query/isOperator":243,"../options/SchemaArrayOptions":259,"../schematype":295,"../types":303,"../utils":307,"./index.js":282,"./mixed":284,"./operators/exists":288,"./operators/geospatial":289,"./operators/helpers":290,"./operators/type":292,"util":332}],277:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const CastError = require('../error/cast'); const SchemaType = require('../schematype'); const castBoolean = require('../cast/boolean'); const utils = require('../utils'); /** * 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 = v => { if (v != null && typeof v !== 'boolean') { throw new Error(); } return v; }; /*! * ignore */ SchemaBoolean._checkRequired = v => v === true || v === false; /** * Override the function the required validator uses to check whether a boolean * passes the `required` check. * * @param {Function} fn * @return {Function} * @function checkRequired * @static * @api public */ SchemaBoolean.checkRequired = SchemaType.checkRequired; /** * Check if the given value satisfies a required validator. For a boolean * to satisfy a required validator, it must be strictly equal to true or to * false. * * @param {Any} value * @return {Boolean} * @api public */ SchemaBoolean.prototype.checkRequired = function(value) { return this.constructor._checkRequired(value); }; /** * Configure which values get casted to `true`. * * ####Example: * * const M = mongoose.model('Test', new Schema({ b: Boolean })); * new M({ b: 'affirmative' }).b; // undefined * mongoose.Schema.Boolean.convertToTrue.add('affirmative'); * new M({ b: 'affirmative' }).b; // true * * @property convertToTrue * @type Set * @api public */ Object.defineProperty(SchemaBoolean, 'convertToTrue', { get: () => castBoolean.convertToTrue, set: v => { castBoolean.convertToTrue = v; } }); /** * Configure which values get casted to `false`. * * ####Example: * * const M = mongoose.model('Test', new Schema({ b: Boolean })); * new M({ b: 'nay' }).b; // undefined * mongoose.Schema.Types.Boolean.convertToFalse.add('nay'); * new M({ b: 'nay' }).b; // false * * @property convertToFalse * @type Set * @api public */ Object.defineProperty(SchemaBoolean, 'convertToFalse', { get: () => castBoolean.convertToFalse, set: v => { castBoolean.convertToFalse = v; } }); /** * Casts to boolean * * @param {Object} value * @param {Object} model - this value is optional * @api private */ SchemaBoolean.prototype.cast = function(value) { let castBoolean; if (typeof this._castFunction === 'function') { castBoolean = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castBoolean = this.constructor.cast(); } else { castBoolean = SchemaBoolean.cast(); } 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) { let 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' && this.$$context != null && this.$$context._mongooseOptions != null && this.$$context._mongooseOptions.omitUndefined) { return v; } const castBoolean = typeof this.constructor.cast === 'function' ? this.constructor.cast() : SchemaBoolean.cast(); if (castBoolean == null) { return v; } if (castBoolean.convertToFalse instanceof Set && castBoolean.convertToFalse.has(v)) { return false; } if (castBoolean.convertToTrue instanceof Set && castBoolean.convertToTrue.has(v)) { return true; } return v; }; /*! * Module exports. */ module.exports = SchemaBoolean; },{"../cast/boolean":188,"../error/cast":202,"../schematype":295,"../utils":307}],278:[function(require,module,exports){ (function (Buffer){(function (){ /*! * Module dependencies. */ 'use strict'; const MongooseBuffer = require('../types/buffer'); const SchemaBufferOptions = require('../options/SchemaBufferOptions'); const SchemaType = require('../schematype'); const handleBitwiseOperator = require('./operators/bitwise'); const utils = require('../utils'); const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; const Binary = MongooseBuffer.Binary; const CastError = SchemaType.CastError; let Document; /** * Buffer SchemaType constructor * * @param {String} key * @param {Object} options * @inherits SchemaType * @api public */ function SchemaBuffer(key, options) { SchemaType.call(this, key, options, 'Buffer'); } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ SchemaBuffer.schemaName = 'Buffer'; SchemaBuffer.defaultOptions = {}; /*! * Inherits from SchemaType. */ SchemaBuffer.prototype = Object.create(SchemaType.prototype); SchemaBuffer.prototype.constructor = SchemaBuffer; SchemaBuffer.prototype.OptionsConstructor = SchemaBufferOptions; /*! * ignore */ SchemaBuffer._checkRequired = v => !!(v && v.length); /** * Sets a default option for all Buffer instances. * * ####Example: * * // Make all buffers have `required` of true by default. * mongoose.Schema.Buffer.set('required', true); * * const User = mongoose.model('User', new Schema({ test: Buffer })); * new User({ }).validateSync().errors.test.message; // Path `test` is required. * * @param {String} option - The option you'd like to set the value for * @param {*} value - value for option * @return {undefined} * @function set * @static * @api public */ SchemaBuffer.set = SchemaType.set; /** * Override the function the required validator uses to check whether a string * passes the `required` check. * * ####Example: * * // Allow empty strings to pass `required` check * mongoose.Schema.Types.String.checkRequired(v => v != null); * * const M = mongoose.model({ buf: { type: Buffer, required: true } }); * new M({ buf: Buffer.from('') }).validateSync(); // validation passes! * * @param {Function} fn * @return {Function} * @function checkRequired * @static * @api public */ SchemaBuffer.checkRequired = SchemaType.checkRequired; /** * Check if the given value satisfies a required validator. To satisfy a * required validator, a buffer must not be null or undefined and have * non-zero length. * * @param {Any} value * @param {Document} doc * @return {Boolean} * @api public */ SchemaBuffer.prototype.checkRequired = function(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { return !!value; } return this.constructor._checkRequired(value); }; /** * Casts contents * * @param {Object} value * @param {Document} doc document that triggers the casting * @param {Boolean} init * @api private */ SchemaBuffer.prototype.cast = function(value, doc, init) { let ret; if (SchemaType._isRef(this, value, doc, init)) { // wait! we may need to cast this to a document if (value === null || value === undefined) { return value; } // lazy load Document || (Document = require('./../document')); if (value instanceof Document) { value.$__.wasPopulated = true; return value; } // setting a populated path if (Buffer.isBuffer(value)) { return value; } else if (!utils.isObject(value)) { throw new CastError('Buffer', 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. const path = doc.$__fullPath(this.path); const owner = doc.ownerDocument ? doc.ownerDocument() : doc; const pop = owner.populated(path, true); ret = new pop.options[populateModelSymbol](value); ret.$__.wasPopulated = true; return ret; } // 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; } const type = typeof value; if ( type === 'string' || type === 'number' || Array.isArray(value) || (type === 'object' && value.type === 'Buffer' && Array.isArray(value.data)) // gh-6863 ) { if (type === 'number') { value = [value]; } ret = new MongooseBuffer(value, [this.path, doc]); if (this.options.subtype != null) { ret._subtype = this.options.subtype; } return ret; } 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](http://api.mongodb.com/python/current/api/bson/binary.html). * * ####Example: * * const s = new Schema({ uuid: { type: Buffer, subtype: 4 }); * const M = db.model('M', s); * const m = new M({ uuid: 'test string' }); * m.uuid._subtype; // 4 * * @param {Number} subtype the default subtype * @return {SchemaType} this * @api public */ SchemaBuffer.prototype.subtype = function(subtype) { this.options.subtype = subtype; return this; }; /*! * 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) { let handler; if (arguments.length === 2) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error('Can\'t use ' + $conditional + ' with Buffer.'); } return handler.call(this, val); } val = $conditional; const casted = this._castForQuery(val); return casted ? casted.toObject({ transform: false, virtuals: false }) : casted; }; /*! * Module exports. */ module.exports = SchemaBuffer; }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":179,"../helpers/symbols":252,"../options/SchemaBufferOptions":260,"../schematype":295,"../types/buffer":298,"../utils":307,"./../document":194,"./operators/bitwise":287}],279:[function(require,module,exports){ /*! * Module requirements. */ 'use strict'; const MongooseError = require('../error/index'); const SchemaDateOptions = require('../options/SchemaDateOptions'); const SchemaType = require('../schematype'); const castDate = require('../cast/date'); const utils = require('../utils'); const CastError = SchemaType.CastError; /** * Date SchemaType constructor. * * @param {String} key * @param {Object} options * @inherits SchemaType * @api public */ function SchemaDate(key, options) { SchemaType.call(this, key, options, 'Date'); } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ SchemaDate.schemaName = 'Date'; SchemaDate.defaultOptions = {}; /*! * Inherits from SchemaType. */ SchemaDate.prototype = Object.create(SchemaType.prototype); SchemaDate.prototype.constructor = SchemaDate; SchemaDate.prototype.OptionsConstructor = SchemaDateOptions; /*! * ignore */ SchemaDate._cast = castDate; /** * Sets a default option for all Date instances. * * ####Example: * * // Make all dates have `required` of true by default. * mongoose.Schema.Date.set('required', true); * * const User = mongoose.model('User', new Schema({ test: Date })); * new User({ }).validateSync().errors.test.message; // Path `test` is required. * * @param {String} option - The option you'd like to set the value for * @param {*} value - value for option * @return {undefined} * @function set * @static * @api public */ SchemaDate.set = SchemaType.set; /** * Get/set the function used to cast arbitrary values to dates. * * ####Example: * * // Mongoose converts empty string '' into `null` for date types. You * // can create a custom caster to disable it. * const original = mongoose.Schema.Types.Date.cast(); * mongoose.Schema.Types.Date.cast(v => { * assert.ok(v !== ''); * return original(v); * }); * * // Or disable casting entirely * mongoose.Schema.Types.Date.cast(false); * * @param {Function} caster * @return {Function} * @function get * @static * @api public */ SchemaDate.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; /*! * ignore */ SchemaDate._defaultCaster = 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 (!this._index || this._index.constructor.name !== 'Object') { this._index = {}; } this._index.expires = when; utils.expires(this._index); return this; }; /*! * ignore */ SchemaDate._checkRequired = v => v instanceof Date; /** * Override the function the required validator uses to check whether a string * passes the `required` check. * * ####Example: * * // Allow empty strings to pass `required` check * mongoose.Schema.Types.String.checkRequired(v => v != null); * * const M = mongoose.model({ str: { type: String, required: true } }); * new M({ str: '' }).validateSync(); // `null`, validation passes! * * @param {Function} fn * @return {Function} * @function checkRequired * @static * @api public */ SchemaDate.checkRequired = SchemaType.checkRequired; /** * Check if the given value satisfies a required validator. To satisfy * a required validator, the given value must be an instance of `Date`. * * @param {Any} value * @param {Document} doc * @return {Boolean} * @api public */ SchemaDate.prototype.checkRequired = function(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { return !!value; } // `require('util').inherits()` does **not** copy static properties, and // plugins like mongoose-float use `inherits()` for pre-ES6. const _checkRequired = typeof this.constructor.checkRequired == 'function' ? this.constructor.checkRequired() : SchemaDate.checkRequired(); return _checkRequired(value); }; /** * Sets a minimum date validator. * * ####Example: * * const s = new Schema({ d: { type: Date, min: Date('1970-01-01') }) * const M = db.model('M', s) * const m = new M({ d: Date('1969-12-31') }) * m.save(function (err) { * console.error(err) // validator error * m.d = Date('2014-12-08'); * m.save() // success * }) * * // custom error messages * // We can also use the special {MIN} token which will be replaced with the invalid value * const min = [Date('1970-01-01'), 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; * const schema = new Schema({ d: { type: Date, min: min }) * const M = mongoose.model('M', schema); * const s= new M({ d: Date('1969-12-31') }); * s.validate(function (err) { * console.log(String(err)) // ValidationError: The value of path `d` (1969-12-31) is before the limit (1970-01-01). * }) * * @param {Date} value minimum date * @param {String} [message] optional custom error message * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @api public */ SchemaDate.prototype.min = function(value, message) { if (this.minValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.minValidator; }, this); } if (value) { let msg = message || MongooseError.messages.Date.min; if (typeof msg === 'string') { msg = msg.replace(/{MIN}/, (value === Date.now ? 'Date.now()' : value.toString())); } const _this = this; this.validators.push({ validator: this.minValidator = function(val) { let _value = value; if (typeof value === 'function' && value !== Date.now) { _value = _value.call(this); } const min = (_value === Date.now ? _value() : _this.cast(_value)); return val === null || val.valueOf() >= min.valueOf(); }, message: msg, type: 'min', min: value }); } 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) { let msg = message || MongooseError.messages.Date.max; if (typeof msg === 'string') { msg = msg.replace(/{MAX}/, (value === Date.now ? 'Date.now()' : value.toString())); } const _this = this; this.validators.push({ validator: this.maxValidator = function(val) { let _value = value; if (typeof _value === 'function' && _value !== Date.now) { _value = _value.call(this); } const max = (_value === Date.now ? _value() : _this.cast(_value)); return val === null || val.valueOf() <= max.valueOf(); }, message: msg, type: 'max', max: value }); } return this; }; /** * Casts to date * * @param {Object} value to cast * @api private */ SchemaDate.prototype.cast = function(value) { let castDate; if (typeof this._castFunction === 'function') { castDate = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castDate = this.constructor.cast(); } else { castDate = SchemaDate.cast(); } 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); } const 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; },{"../cast/date":189,"../error/index":204,"../options/SchemaDateOptions":261,"../schematype":295,"../utils":307}],280:[function(require,module,exports){ (function (Buffer){(function (){ /*! * Module dependencies. */ 'use strict'; const SchemaType = require('../schematype'); const CastError = SchemaType.CastError; const Decimal128Type = require('../types/decimal128'); const castDecimal128 = require('../cast/decimal128'); const utils = require('../utils'); const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; let Document; /** * 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 = v => { if (v != null && !(v instanceof Decimal128Type)) { throw new Error(); } return v; }; /*! * ignore */ Decimal128._checkRequired = v => v instanceof Decimal128Type; /** * Override the function the required validator uses to check whether a string * passes the `required` check. * * @param {Function} fn * @return {Function} * @function checkRequired * @static * @api public */ Decimal128.checkRequired = SchemaType.checkRequired; /** * Check if the given value satisfies a required validator. * * @param {Any} value * @param {Document} doc * @return {Boolean} * @api public */ Decimal128.prototype.checkRequired = function checkRequired(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { return !!value; } // `require('util').inherits()` does **not** copy static properties, and // plugins like mongoose-float use `inherits()` for pre-ES6. const _checkRequired = typeof this.constructor.checkRequired == 'function' ? this.constructor.checkRequired() : Decimal128.checkRequired(); return _checkRequired(value); }; /** * 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)) { // wait! we may need to cast this to a document if (value === null || value === undefined) { return value; } // lazy load Document || (Document = require('./../document')); if (value instanceof Document) { value.$__.wasPopulated = true; return value; } // setting a populated path if (value instanceof Decimal128Type) { return value; } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { throw new CastError('Decimal128', 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. const path = doc.$__fullPath(this.path); const owner = doc.ownerDocument ? doc.ownerDocument() : doc; const pop = owner.populated(path, true); let ret = value; if (!doc.$__.populated || !doc.$__.populated[path] || !doc.$__.populated[path].options || !doc.$__.populated[path].options.options || !doc.$__.populated[path].options.options.lean) { ret = new pop.options[populateModelSymbol](value); ret.$__.wasPopulated = true; } return ret; } let castDecimal128; if (typeof this._castFunction === 'function') { castDecimal128 = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castDecimal128 = this.constructor.cast(); } else { castDecimal128 = Decimal128.cast(); } 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; }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":179,"../cast/decimal128":190,"../helpers/symbols":252,"../schematype":295,"../types/decimal128":300,"../utils":307,"./../document":194}],281:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const ArrayType = require('./array'); const CastError = require('../error/cast'); const EventEmitter = require('events').EventEmitter; const SchemaDocumentArrayOptions = require('../options/SchemaDocumentArrayOptions'); const SchemaType = require('../schematype'); const ValidationError = require('../error/validation'); const discriminator = require('../helpers/model/discriminator'); const get = require('../helpers/get'); const handleIdOption = require('../helpers/schema/handleIdOption'); const util = require('util'); const utils = require('../utils'); const getConstructor = require('../helpers/discriminator/getConstructor'); const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol; const documentArrayParent = require('../helpers/symbols').documentArrayParent; let MongooseDocumentArray; let Subdocument; /** * SubdocsArray SchemaType constructor * * @param {String} key * @param {Schema} schema * @param {Object} options * @inherits SchemaArray * @api public */ function DocumentArrayPath(key, schema, options, schemaOptions) { if (schemaOptions != null && schemaOptions._id != null) { schema = handleIdOption(schema, schemaOptions); } else if (options != null && options._id != null) { schema = handleIdOption(schema, options); } const EmbeddedDocument = _createConstructor(schema, options); EmbeddedDocument.prototype.$basePath = key; ArrayType.call(this, key, EmbeddedDocument, options); this.schema = schema; this.schemaOptions = schemaOptions || {}; this.$isMongooseDocumentArray = true; this.Constructor = EmbeddedDocument; EmbeddedDocument.base = schema.base; const fn = this.defaultValue; if (!('defaultValue' in this) || fn !== void 0) { this.default(function() { let arr = fn.call(this); if (!Array.isArray(arr)) { arr = [arr]; } // Leave it up to `cast()` to convert this to a documentarray return arr; }); } const parentSchemaType = this; this.$embeddedSchemaType = new SchemaType(key + '.$', { required: get(this, 'schemaOptions.required', false) }); this.$embeddedSchemaType.cast = function(value, doc, init) { return parentSchemaType.cast(value, doc, init)[0]; }; this.$embeddedSchemaType.$isMongooseDocumentArrayElement = true; this.$embeddedSchemaType.caster = this.Constructor; this.$embeddedSchemaType.schema = this.schema; } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ DocumentArrayPath.schemaName = 'DocumentArray'; /** * 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 = require('../types/embedded')); // compile an embedded document for this schema function EmbeddedDocument() { Subdocument.apply(this, arguments); this.$session(this.ownerDocument().$session()); } const proto = baseClass != null ? baseClass.prototype : Subdocument.prototype; EmbeddedDocument.prototype = Object.create(proto); EmbeddedDocument.prototype.$__setSchema(schema); EmbeddedDocument.schema = schema; EmbeddedDocument.prototype.constructor = EmbeddedDocument; EmbeddedDocument.$isArraySubdocument = true; EmbeddedDocument.events = new EventEmitter(); // apply methods for (const i in schema.methods) { EmbeddedDocument.prototype[i] = schema.methods[i]; } // apply statics for (const i in schema.statics) { EmbeddedDocument[i] = schema.statics[i]; } for (const i in EventEmitter.prototype) { EmbeddedDocument[i] = EventEmitter.prototype[i]; } EmbeddedDocument.options = options; return EmbeddedDocument; } /** * Adds a discriminator to this document array. * * ####Example: * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' }); * const schema = Schema({ shapes: [shapeSchema] }); * * const docArrayPath = parentSchema.path('shapes'); * docArrayPath.discriminator('Circle', Schema({ radius: Number })); * * @param {String} name * @param {Schema} schema fields to add to the schema for instances of this sub-class * @param {String} [value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. * @see discriminators /docs/discriminators.html * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model * @api public */ DocumentArrayPath.prototype.discriminator = function(name, schema, tiedValue) { if (typeof name === 'function') { name = utils.getFunctionName(name); } schema = discriminator(this.casterConstructor, name, schema, tiedValue); const EmbeddedDocument = _createConstructor(schema, null, this.casterConstructor); EmbeddedDocument.baseCasterConstructor = this.casterConstructor; 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 = require('../types/documentarray')); const _this = this; try { SchemaType.prototype.doValidate.call(this, array, cb, scope); } catch (err) { err.$isArrayValidatorError = true; return fn(err); } function cb(err) { if (err) { err.$isArrayValidatorError = true; return fn(err); } let count = array && array.length; let error; if (!count) { return fn(); } if (options && options.updateValidator) { return fn(); } if (!array.isMongooseDocumentArray) { 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; if (!(error instanceof ValidationError)) { error.$isArrayValidatorError = true; } } --count || fn(error); } for (let i = 0, len = count; i < len; ++i) { // sidestep sparse entries let 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)) { const 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) { const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope); if (schemaTypeError != null) { schemaTypeError.$isArrayValidatorError = true; return schemaTypeError; } const count = array && array.length; let 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 (let i = 0, len = count; i < len; ++i) { // sidestep sparse entries let 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)) { const Constructor = getConstructor(this.casterConstructor, array[i]); doc = array[i] = new Constructor(doc, array, undefined, undefined, i); } if (options != null && options.validateModifiedOnly && !doc.isModified()) { continue; } const subdocValidateError = doc.validateSync(); if (subdocValidateError && resultError == null) { resultError = subdocValidateError; } } return resultError; }; /*! * ignore */ DocumentArrayPath.prototype.getDefault = function(scope) { let ret = typeof this.defaultValue === 'function' ? this.defaultValue.call(scope) : this.defaultValue; if (ret == null) { return ret; } // lazy load MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray')); if (!Array.isArray(ret)) { ret = [ret]; } ret = new MongooseDocumentArray(ret, this.path, scope); for (let i = 0; i < ret.length; ++i) { const Constructor = getConstructor(this.casterConstructor, ret[i]); const _subdoc = new Constructor({}, ret, undefined, undefined, i); _subdoc.init(ret[i]); _subdoc.isNew = true; // 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; }; /** * 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 = require('../types/documentarray')); // 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; } let selected; let subdoc; const _opts = { transform: false, virtuals: false }; options = options || {}; if (!Array.isArray(value)) { if (!init && !DocumentArrayPath.options.castNonArrays) { throw new CastError('DocumentArray', util.inspect(value), this.path, null, this); } // gh-2442 mark whole array as modified if we're initializing a doc from // the db and the path isn't an array in the document if (!!doc && init) { doc.markModified(this.path); } return this.cast([value], doc, init, prev, options); } if (!(value && value.isMongooseDocumentArray) && !options.skipDocumentArrayCast) { value = new MongooseDocumentArray(value, this.path, doc); } else if (value && value.isMongooseDocumentArray) { // We need to create a new array, otherwise change tracking will // update the old doc (gh-4449) value = new MongooseDocumentArray(value, this.path, doc); } if (options.arrayPath != null) { value[arrayPathSymbol] = options.arrayPath; } const len = value.length; const initDocumentOptions = { skipId: true, willInit: true }; for (let i = 0; i < len; ++i) { if (!value[i]) { continue; } const Constructor = getConstructor(this.casterConstructor, value[i]); // Check if the document has a different schema (re gh-3701) if ((value[i].$__) && (!(value[i] instanceof Constructor) || value[i][documentArrayParent] !== doc)) { value[i] = value[i].toObject({ transform: false, // Special case: if different model, but same schema, apply virtuals // re: gh-7898 virtuals: value[i].schema === Constructor.schema }); } if (value[i] instanceof Subdocument) { // Might not have the correct index yet, so ensure it does. if (value[i].__index == null) { value[i].$setIndex(i); } } else if (value[i] != null) { if (init) { if (doc) { selected || (selected = scopePaths(this, doc.$__.selected, init)); } else { selected = true; } subdoc = new Constructor(null, value, initDocumentOptions, selected, i); value[i] = subdoc.init(value[i]); } else { if (prev && typeof prev.id === 'function') { subdoc = prev.id(value[i]._id); } if (prev && subdoc && utils.deepEqual(subdoc.toObject(_opts), value[i])) { // handle resetting doc with existing id and same data subdoc.set(value[i]); // if set() is hooked it will have no return value // see gh-746 value[i] = subdoc; } else { try { subdoc = new Constructor(value[i], value, undefined, undefined, i); // if set() is hooked it will have no return value // see gh-746 value[i] = subdoc; } catch (error) { const valueInErrorMessage = util.inspect(value[i]); throw new CastError('embedded', valueInErrorMessage, value[arrayPathSymbol], error, this); } } } } } return value; }; /*! * ignore */ DocumentArrayPath.prototype.clone = function() { const options = Object.assign({}, this.options); const schematype = new this.constructor(this.path, this.schema, options, this.schemaOptions); schematype.validators = this.validators.slice(); if (this.requiredValidator !== undefined) { schematype.requiredValidator = this.requiredValidator; } schematype.Constructor.discriminators = Object.assign({}, this.Constructor.discriminators); return schematype; }; /*! * 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; } const path = array.path + '.'; const keys = Object.keys(fields); let i = keys.length; const selected = {}; let hasKeys; let key; let sub; while (i--) { key = keys[i]; if (key.startsWith(path)) { sub = key.substring(path.length); if (sub === '$') { continue; } if (sub.startsWith('$.')) { sub = sub.substr(2); } hasKeys || (hasKeys = true); selected[sub] = fields[key]; } } 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; },{"../error/cast":202,"../error/validation":215,"../helpers/discriminator/getConstructor":222,"../helpers/get":229,"../helpers/model/discriminator":237,"../helpers/schema/handleIdOption":247,"../helpers/symbols":252,"../options/SchemaDocumentArrayOptions":262,"../schematype":295,"../types/documentarray":301,"../types/embedded":302,"../utils":307,"./array":276,"events":177,"util":332}],282:[function(require,module,exports){ /*! * Module exports. */ 'use strict'; exports.String = require('./string'); exports.Number = require('./number'); exports.Boolean = require('./boolean'); exports.DocumentArray = require('./documentarray'); exports.Embedded = require('./SingleNestedPath'); exports.Array = require('./array'); exports.Buffer = require('./buffer'); exports.Date = require('./date'); exports.ObjectId = require('./objectid'); exports.Mixed = require('./mixed'); exports.Decimal128 = exports.Decimal = require('./decimal128'); exports.Map = require('./map'); // alias exports.Oid = exports.ObjectId; exports.Object = exports.Mixed; exports.Bool = exports.Boolean; exports.ObjectID = exports.ObjectId; },{"./SingleNestedPath":275,"./array":276,"./boolean":277,"./buffer":278,"./date":279,"./decimal128":280,"./documentarray":281,"./map":283,"./mixed":284,"./number":285,"./objectid":286,"./string":293}],283:[function(require,module,exports){ (function (global){(function (){ 'use strict'; /*! * ignore */ const MongooseMap = require('../types/map'); const SchemaMapOptions = require('../options/SchemaMapOptions'); const SchemaType = require('../schematype'); /*! * ignore */ class Map extends SchemaType { constructor(key, options) { super(key, options, 'Map'); this.$isSchemaMap = true; } set(option, value) { return SchemaType.set(option, value); } cast(val, doc, init) { if (val instanceof MongooseMap) { return val; } const path = this.path; if (init) { const map = new MongooseMap({}, path, doc, this.$__schemaType); if (val instanceof global.Map) { for (const key of val.keys()) { let _val = val.get(key); if (_val == null) { _val = map.$__schemaType._castNullish(_val); } else { _val = map.$__schemaType.cast(_val, doc, true, null, { path: path + '.' + key }); } map.$init(key, _val); } } else { for (const key of Object.keys(val)) { let _val = val[key]; if (_val == null) { _val = map.$__schemaType._castNullish(_val); } else { _val = map.$__schemaType.cast(_val, doc, true, null, { path: path + '.' + key }); } map.$init(key, _val); } } return map; } return new MongooseMap(val, path, doc, this.$__schemaType); } clone() { const schematype = super.clone(); if (this.$__schemaType != null) { schematype.$__schemaType = this.$__schemaType.clone(); } return schematype; } } Map.prototype.OptionsConstructor = SchemaMapOptions; Map.defaultOptions = {}; module.exports = Map; }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../options/SchemaMapOptions":263,"../schematype":295,"../types/map":304}],284:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const SchemaType = require('../schematype'); const symbols = require('./symbols'); const isObject = require('../helpers/isObject'); /** * Mixed SchemaType constructor. * * @param {String} path * @param {Object} options * @inherits SchemaType * @api public */ function Mixed(path, options) { if (options && options.default) { const def = options.default; if (Array.isArray(def) && def.length === 0) { // make sure empty array defaults are handled options.default = Array; } else if (!options.shared && isObject(def) && Object.keys(def).length === 0) { // prevent odd "shared" objects between documents options.default = function() { return {}; }; } } 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) { 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; },{"../helpers/isObject":234,"../schematype":295,"./symbols":294}],285:[function(require,module,exports){ (function (Buffer){(function (){ 'use strict'; /*! * Module requirements. */ const MongooseError = require('../error/index'); const SchemaNumberOptions = require('../options/SchemaNumberOptions'); const SchemaType = require('../schematype'); const castNumber = require('../cast/number'); const handleBitwiseOperator = require('./operators/bitwise'); const utils = require('../utils'); const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; const CastError = SchemaType.CastError; let Document; /** * 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 = 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 = v => typeof v === 'number' || v instanceof Number; /** * Override the function the required validator uses to check whether a string * passes the `required` check. * * @param {Function} fn * @return {Function} * @function checkRequired * @static * @api public */ SchemaNumber.checkRequired = SchemaType.checkRequired; /** * Check if the given value satisfies a required validator. * * @param {Any} value * @param {Document} doc * @return {Boolean} * @api public */ SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { return !!value; } // `require('util').inherits()` does **not** copy static properties, and // plugins like mongoose-float use `inherits()` for pre-ES6. const _checkRequired = typeof this.constructor.checkRequired == 'function' ? this.constructor.checkRequired() : SchemaNumber.checkRequired(); return _checkRequired(value); }; /** * Sets a minimum number validator. * * ####Example: * * const s = new Schema({ n: { type: Number, min: 10 }) * const M = db.model('M', s) * const m = new M({ n: 9 }) * m.save(function (err) { * console.error(err) // validator error * m.n = 10; * m.save() // success * }) * * // custom error messages * // We can also use the special {MIN} token which will be replaced with the invalid value * const min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; * const schema = new Schema({ n: { type: Number, min: min }) * const M = mongoose.model('Measurement', schema); * const s= new M({ n: 4 }); * s.validate(function (err) { * console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10). * }) * * @param {Number} value minimum number * @param {String} [message] optional custom error message * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @api public */ SchemaNumber.prototype.min = function(value, message) { if (this.minValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.minValidator; }, this); } if (value !== null && value !== undefined) { let msg = message || MongooseError.messages.Number.min; msg = msg.replace(/{MIN}/, value); this.validators.push({ validator: this.minValidator = function(v) { return v == null || v >= value; }, message: msg, type: 'min', min: value }); } return this; }; /** * Sets a maximum number validator. * * ####Example: * * const s = new Schema({ n: { type: Number, max: 10 }) * const M = db.model('M', s) * const m = new M({ n: 11 }) * m.save(function (err) { * console.error(err) // validator error * m.n = 10; * m.save() // success * }) * * // custom error messages * // We can also use the special {MAX} token which will be replaced with the invalid value * const max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; * const schema = new Schema({ n: { type: Number, max: max }) * const M = mongoose.model('Measurement', schema); * const s= new M({ n: 4 }); * s.validate(function (err) { * console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10). * }) * * @param {Number} maximum number * @param {String} [message] optional custom error message * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @api public */ SchemaNumber.prototype.max = function(value, message) { if (this.maxValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.maxValidator; }, this); } if (value !== null && value !== undefined) { let msg = message || MongooseError.messages.Number.max; msg = msg.replace(/{MAX}/, value); this.validators.push({ validator: this.maxValidator = function(v) { return v == null || v <= value; }, message: msg, type: 'max', max: value }); } 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)) { if (utils.isObject(values)) { values = utils.object.vals(values); } else { values = Array.prototype.slice.call(arguments); } message = MongooseError.messages.Number.enum; } message = message == null ? MongooseError.messages.Number.enum : message; this.enumValidator = v => 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 (SchemaType._isRef(this, value, doc, init)) { // wait! we may need to cast this to a document if (value === null || value === undefined) { return value; } // lazy load Document || (Document = require('./../document')); if (value instanceof Document) { value.$__.wasPopulated = true; return value; } // setting a populated path if (typeof value === 'number') { return value; } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { throw new CastError('Number', 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. const path = doc.$__fullPath(this.path); const owner = doc.ownerDocument ? doc.ownerDocument() : doc; const pop = owner.populated(path, true); const ret = new pop.options[populateModelSymbol](value); ret.$__.wasPopulated = true; return ret; } const val = value && typeof value._id !== 'undefined' ? value._id : // documents value; let castNumber; if (typeof this._castFunction === 'function') { castNumber = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castNumber = this.constructor.cast(); } else { castNumber = SchemaNumber.cast(); } 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) { const _this = this; if (!Array.isArray(val)) { return [this.cast(val)]; } return val.map(function(m) { return _this.cast(m); }); } SchemaNumber.prototype.$conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { $bitsAllClear: handleBitwiseOperator, $bitsAnyClear: handleBitwiseOperator, $bitsAllSet: handleBitwiseOperator, $bitsAnySet: handleBitwiseOperator, $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle, $mod: handleArray }); /** * Casts contents for queries. * * @param {String} $conditional * @param {any} [value] * @api private */ SchemaNumber.prototype.castForQuery = function($conditional, val) { let handler; if (arguments.length === 2) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new CastError('number', val, this.path, null, this); } return handler.call(this, val); } val = this._castForQuery($conditional); return val; }; /*! * Module exports. */ module.exports = SchemaNumber; }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":179,"../cast/number":191,"../error/index":204,"../helpers/symbols":252,"../options/SchemaNumberOptions":264,"../schematype":295,"../utils":307,"./../document":194,"./operators/bitwise":287}],286:[function(require,module,exports){ (function (Buffer){(function (){ /*! * Module dependencies. */ 'use strict'; const SchemaObjectIdOptions = require('../options/SchemaObjectIdOptions'); const SchemaType = require('../schematype'); const castObjectId = require('../cast/objectid'); const oid = require('../types/objectid'); const utils = require('../utils'); const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; const CastError = SchemaType.CastError; let Document; /** * ObjectId SchemaType constructor. * * @param {String} key * @param {Object} options * @inherits SchemaType * @api public */ function ObjectId(key, options) { const isKeyHexStr = typeof key === 'string' && key.length === 24 && /^[a-f0-9]+$/i.test(key); const suppressWarning = options && options.suppressWarning; if ((isKeyHexStr || typeof key === 'undefined') && !suppressWarning) { console.warn('mongoose: To create a new ObjectId please try ' + '`Mongoose.Types.ObjectId` instead of using ' + '`Mongoose.Schema.ObjectId`. Set the `suppressWarning` option if ' + 'you\'re trying to create a hex char path in your schema.'); console.trace(); } SchemaType.call(this, key, options, 'ObjectID'); } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ ObjectId.schemaName = 'ObjectId'; ObjectId.defaultOptions = {}; /*! * Inherits from SchemaType. */ ObjectId.prototype = Object.create(SchemaType.prototype); ObjectId.prototype.constructor = ObjectId; ObjectId.prototype.OptionsConstructor = SchemaObjectIdOptions; /** * Attaches a getter for all ObjectId instances * * ####Example: * * // Always convert to string when getting an ObjectId * mongoose.ObjectId.get(v => v.toString()); * * const Model = mongoose.model('Test', new Schema({})); * typeof (new Model({})._id); // 'string' * * @param {Function} getter * @return {this} * @function get * @static * @api public */ ObjectId.get = SchemaType.get; /** * Sets a default option for all ObjectId instances. * * ####Example: * * // Make all object ids have option `required` equal to true. * mongoose.Schema.ObjectId.set('required', true); * * const Order = mongoose.model('Order', new Schema({ userId: ObjectId })); * new Order({ }).validateSync().errors.userId.message; // Path `userId` is required. * * @param {String} option - The option you'd like to set the value for * @param {*} value - value for option * @return {undefined} * @function set * @static * @api public */ ObjectId.set = SchemaType.set; /** * Adds an auto-generated ObjectId default if turnOn is true. * @param {Boolean} turnOn auto generated ObjectId defaults * @api public * @return {SchemaType} this */ ObjectId.prototype.auto = function(turnOn) { if (turnOn) { this.default(defaultId); this.set(resetId); } return this; }; /*! * ignore */ ObjectId._checkRequired = v => v instanceof oid; /*! * ignore */ ObjectId._cast = castObjectId; /** * Get/set the function used to cast arbitrary values to objectids. * * ####Example: * * // Make Mongoose only try to cast length 24 strings. By default, any 12 * // char string is a valid ObjectId. * const original = mongoose.ObjectId.cast(); * mongoose.ObjectId.cast(v => { * assert.ok(typeof v !== 'string' || v.length === 24); * return original(v); * }); * * // Or disable casting entirely * mongoose.ObjectId.cast(false); * * @param {Function} caster * @return {Function} * @function get * @static * @api public */ ObjectId.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; /*! * ignore */ ObjectId._defaultCaster = v => { if (!(v instanceof oid)) { 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. const _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 (SchemaType._isRef(this, value, doc, init)) { // wait! we may need to cast this to a document if (value === null || value === undefined) { return value; } // lazy load Document || (Document = require('./../document')); if (value instanceof Document) { value.$__.wasPopulated = true; return value; } // setting a populated path if (value instanceof oid) { return value; } else if ((value.constructor.name || '').toLowerCase() === 'objectid') { return new oid(value.toHexString()); } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { throw new CastError('ObjectId', 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. const path = doc.$__fullPath(this.path); const owner = doc.ownerDocument ? doc.ownerDocument() : doc; const pop = owner.populated(path, true); let ret = value; if (!doc.$__.populated || !doc.$__.populated[path] || !doc.$__.populated[path].options || !doc.$__.populated[path].options.options || !doc.$__.populated[path].options.options.lean) { ret = new pop.options[populateModelSymbol](value); ret.$__.wasPopulated = true; } return ret; } let castObjectId; if (typeof this._castFunction === 'function') { castObjectId = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castObjectId = this.constructor.cast(); } else { castObjectId = ObjectId.cast(); } 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 = require('./../document')); if (this instanceof Document) { if (v === void 0) { const _v = new oid; this.$__._id = _v; return _v; } this.$__._id = v; } return v; } /*! * Module exports. */ module.exports = ObjectId; }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":179,"../cast/objectid":192,"../helpers/symbols":252,"../options/SchemaObjectIdOptions":265,"../schematype":295,"../types/objectid":305,"../utils":307,"./../document":194}],287:[function(require,module,exports){ (function (Buffer){(function (){ /*! * Module requirements. */ 'use strict'; const CastError = require('../../error/cast'); /*! * ignore */ function handleBitwiseOperator(val) { const _this = this; if (Array.isArray(val)) { return val.map(function(v) { return _castNumber(_this.path, v); }); } else if (Buffer.isBuffer(val)) { return val; } // Assume trying to cast to number return _castNumber(_this.path, val); } /*! * ignore */ function _castNumber(path, num) { const v = Number(num); if (isNaN(v)) { throw new CastError('number', num, path); } return v; } module.exports = handleBitwiseOperator; }).call(this)}).call(this,{"isBuffer":require("../../../../is-buffer/index.js")}) },{"../../../../is-buffer/index.js":179,"../../error/cast":202}],288:[function(require,module,exports){ 'use strict'; const castBoolean = require('../../cast/boolean'); /*! * ignore */ module.exports = function(val) { const path = this != null ? this.path : null; return castBoolean(val, path); }; },{"../../cast/boolean":188}],289:[function(require,module,exports){ /*! * Module requirements. */ 'use strict'; const castArraysOfNumbers = require('./helpers').castArraysOfNumbers; const castToNumber = require('./helpers').castToNumber; /*! * ignore */ exports.cast$geoIntersects = cast$geoIntersects; exports.cast$near = cast$near; exports.cast$within = cast$within; function cast$near(val) { const SchemaArray = require('../array'); 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) { _castMinMaxDistance(this, val); if (val.$box || val.$polygon) { const type = val.$box ? '$box' : '$polygon'; val[type].forEach(arr => { if (!Array.isArray(arr)) { const msg = 'Invalid $within $box argument. ' + 'Expected an array, received ' + arr; throw new TypeError(msg); } arr.forEach((v, i) => { arr[i] = castToNumber.call(this, v); }); }); } else if (val.$center || val.$centerSphere) { const type = val.$center ? '$center' : '$centerSphere'; val[type].forEach((item, i) => { if (Array.isArray(item)) { item.forEach((v, j) => { item[j] = castToNumber.call(this, v); }); } else { val[type][i] = castToNumber.call(this, item); } }); } else if (val.$geometry) { cast$geometry(val, this); } return val; } function cast$geoIntersects(val) { const 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); } } },{"../array":276,"./helpers":290}],290:[function(require,module,exports){ 'use strict'; /*! * Module requirements. */ const SchemaNumber = require('../number'); /*! * @ignore */ exports.castToNumber = castToNumber; exports.castArraysOfNumbers = 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); } }); } },{"../number":285}],291:[function(require,module,exports){ 'use strict'; const CastError = require('../../error/cast'); const castBoolean = require('../../cast/boolean'); const castString = require('../../cast/string'); /*! * 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; }; },{"../../cast/boolean":188,"../../cast/string":193,"../../error/cast":202}],292:[function(require,module,exports){ 'use strict'; /*! * ignore */ module.exports = function(val) { if (Array.isArray(val)) { if (!val.every(v => typeof v === 'number' || typeof v === 'string')) { throw new Error('$type array values must be strings or numbers'); } 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; }; },{}],293:[function(require,module,exports){ (function (Buffer){(function (){ 'use strict'; /*! * Module dependencies. */ const SchemaType = require('../schematype'); const MongooseError = require('../error/index'); const SchemaStringOptions = require('../options/SchemaStringOptions'); const castString = require('../cast/string'); const utils = require('../utils'); const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; const CastError = SchemaType.CastError; let Document; /** * 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 = 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 = v => (v instanceof String || typeof v === 'string') && v.length; /** * Override the function the required validator uses to check whether a string * passes the `required` check. * * ####Example: * * // Allow empty strings to pass `required` check * mongoose.Schema.Types.String.checkRequired(v => v != null); * * const M = mongoose.model({ str: { type: String, required: true } }); * new M({ str: '' }).validateSync(); // `null`, validation passes! * * @param {Function} fn * @return {Function} * @function checkRequired * @static * @api public */ SchemaString.checkRequired = SchemaType.checkRequired; /** * Adds an enum validator * * ####Example: * * const states = ['opening', 'open', 'closing', 'closed'] * const s = new Schema({ state: { type: String, enum: states }}) * const M = db.model('M', s) * const m = new M({ state: 'invalid' }) * m.save(function (err) { * console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`. * m.state = 'open' * m.save(callback) // success * }) * * // or with custom error messages * const enum = { * values: ['opening', 'open', 'closing', 'closed'], * message: 'enum validator failed for path `{PATH}` with value `{VALUE}`' * } * const s = new Schema({ state: { type: String, enum: enum }) * const M = db.model('M', s) * const m = new M({ state: 'invalid' }) * m.save(function (err) { * console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid` * m.state = 'open' * m.save(callback) // success * }) * * @param {String|Object} [args...] enumeration values * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @api public */ SchemaString.prototype.enum = function() { if (this.enumValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.enumValidator; }, this); this.enumValidator = false; } if (arguments[0] === void 0 || arguments[0] === false) { return this; } let values; let 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; } for (const value of values) { if (value !== undefined) { this.enumValues.push(this.cast(value)); } } const vals = this.enumValues; this.enumValidator = function(v) { return undefined === v || ~vals.indexOf(v); }; this.validators.push({ validator: this.enumValidator, message: errorMessage, type: 'enum', enumValues: vals }); return this; }; /** * Adds a lowercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). * * ####Example: * * const s = new Schema({ email: { type: String, lowercase: true }}) * const M = db.model('M', s); * const m = new M({ email: 'SomeEmail@example.COM' }); * console.log(m.email) // someemail@example.com * M.find({ email: 'SomeEmail@example.com' }); // Queries by 'someemail@example.com' * * Note that `lowercase` does **not** affect regular expression queries: * * ####Example: * // Still queries for documents whose `email` matches the regular * // expression /SomeEmail/. Mongoose does **not** convert the RegExp * // to lowercase. * M.find({ email: /SomeEmail/ }); * * @api public * @return {SchemaType} this */ SchemaString.prototype.lowercase = function(shouldApply) { if (arguments.length > 0 && !shouldApply) { return this; } return this.set(function(v, self) { if (typeof v !== 'string') { v = self.cast(v); } if (v) { return v.toLowerCase(); } return v; }); }; /** * Adds an uppercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). * * ####Example: * * const s = new Schema({ caps: { type: String, uppercase: true }}) * const M = db.model('M', s); * const m = new M({ caps: 'an example' }); * console.log(m.caps) // AN EXAMPLE * M.find({ caps: 'an example' }) // Matches documents where caps = 'AN EXAMPLE' * * Note that `uppercase` does **not** affect regular expression queries: * * ####Example: * // Mongoose does **not** convert the RegExp to uppercase. * M.find({ email: /an example/ }); * * @api public * @return {SchemaType} this */ SchemaString.prototype.uppercase = function(shouldApply) { if (arguments.length > 0 && !shouldApply) { return this; } return this.set(function(v, self) { if (typeof v !== 'string') { v = self.cast(v); } if (v) { return v.toUpperCase(); } return v; }); }; /** * Adds a trim [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). * * The string value will be trimmed when set. * * ####Example: * * const s = new Schema({ name: { type: String, trim: true }}); * const M = db.model('M', s); * const string = ' some name '; * console.log(string.length); // 11 * const m = new M({ name: string }); * console.log(m.name.length); // 9 * * // Equivalent to `findOne({ name: string.trim() })` * M.findOne({ name: string }); * * Note that `trim` does **not** affect regular expression queries: * * ####Example: * // Mongoose does **not** trim whitespace from the RegExp. * M.find({ name: / some name / }); * * @api public * @return {SchemaType} this */ SchemaString.prototype.trim = function(shouldTrim) { if (arguments.length > 0 && !shouldTrim) { return this; } return this.set(function(v, self) { if (typeof v !== 'string') { v = self.cast(v); } if (v) { return v.trim(); } return v; }); }; /** * Sets a minimum length validator. * * ####Example: * * const schema = new Schema({ postalCode: { type: String, minlength: 5 }) * const Address = db.model('Address', schema) * const address = new Address({ postalCode: '9512' }) * address.save(function (err) { * console.error(err) // validator error * address.postalCode = '95125'; * address.save() // success * }) * * // custom error messages * // We can also use the special {MINLENGTH} token which will be replaced with the minimum allowed length * const minlength = [5, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).']; * const schema = new Schema({ postalCode: { type: String, minlength: minlength }) * const Address = mongoose.model('Address', schema); * const address = new Address({ postalCode: '9512' }); * address.validate(function (err) { * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5). * }) * * @param {Number} value minimum string length * @param {String} [message] optional custom error message * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @api public */ SchemaString.prototype.minlength = function(value, message) { if (this.minlengthValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.minlengthValidator; }, this); } if (value !== null && value !== undefined) { let msg = message || MongooseError.messages.String.minlength; msg = msg.replace(/{MINLENGTH}/, value); this.validators.push({ validator: this.minlengthValidator = function(v) { return v === null || v.length >= value; }, message: msg, type: 'minlength', minlength: value }); } return this; }; SchemaString.prototype.minLength = SchemaString.prototype.minlength; /** * Sets a maximum length validator. * * ####Example: * * const schema = new Schema({ postalCode: { type: String, maxlength: 9 }) * const Address = db.model('Address', schema) * const address = new Address({ postalCode: '9512512345' }) * address.save(function (err) { * console.error(err) // validator error * address.postalCode = '95125'; * address.save() // success * }) * * // custom error messages * // We can also use the special {MAXLENGTH} token which will be replaced with the maximum allowed length * const maxlength = [9, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).']; * const schema = new Schema({ postalCode: { type: String, maxlength: maxlength }) * const Address = mongoose.model('Address', schema); * const address = new Address({ postalCode: '9512512345' }); * address.validate(function (err) { * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (9). * }) * * @param {Number} value maximum string length * @param {String} [message] optional custom error message * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @api public */ SchemaString.prototype.maxlength = function(value, message) { if (this.maxlengthValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.maxlengthValidator; }, this); } if (value !== null && value !== undefined) { let msg = message || MongooseError.messages.String.maxlength; msg = msg.replace(/{MAXLENGTH}/, value); this.validators.push({ validator: this.maxlengthValidator = function(v) { return v === null || v.length <= value; }, message: msg, type: 'maxlength', maxlength: value }); } 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 const msg = message || MongooseError.messages.String.match; const matchValidator = function(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; const 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 (SchemaType._isRef(this, value, doc, true)) { return !!value; } // `require('util').inherits()` does **not** copy static properties, and // plugins like mongoose-float use `inherits()` for pre-ES6. const _checkRequired = typeof this.constructor.checkRequired == 'function' ? this.constructor.checkRequired() : SchemaString.checkRequired(); return _checkRequired(value); }; /** * Casts to String * * @api private */ SchemaString.prototype.cast = function(value, doc, init) { if (SchemaType._isRef(this, value, doc, init)) { // wait! we may need to cast this to a document if (value === null || value === undefined) { return value; } // lazy load Document || (Document = require('./../document')); if (value instanceof Document) { value.$__.wasPopulated = true; return value; } // setting a populated path if (typeof value === 'string') { return value; } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { throw new CastError('string', 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. const path = doc.$__fullPath(this.path); const owner = doc.ownerDocument ? doc.ownerDocument() : doc; const pop = owner.populated(path, true); const ret = new pop.options[populateModelSymbol](value); ret.$__.wasPopulated = true; return ret; } let castString; if (typeof this._castFunction === 'function') { castString = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castString = this.constructor.cast(); } else { castString = SchemaString.cast(); } try { return castString(value); } catch (error) { throw new CastError('string', value, this.path, null, this); } }; /*! * ignore */ function handleSingle(val) { return this.castForQuery(val); } function handleArray(val) { const _this = this; if (!Array.isArray(val)) { return [this.castForQuery(val)]; } return val.map(function(m) { return _this.castForQuery(m); }); } const $conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { $all: handleArray, $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle, $options: String, $regex: handleSingle, $not: handleSingle }); Object.defineProperty(SchemaString.prototype, '$conditionalHandlers', { configurable: false, enumerable: false, writable: false, value: Object.freeze($conditionalHandlers) }); /** * Casts contents for queries. * * @param {String} $conditional * @param {any} [val] * @api private */ SchemaString.prototype.castForQuery = function($conditional, val) { let handler; if (arguments.length === 2) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error('Can\'t use ' + $conditional + ' with String.'); } return handler.call(this, val); } val = $conditional; if (Object.prototype.toString.call(val) === '[object RegExp]') { return val; } return this._castForQuery(val); }; /*! * Module exports. */ module.exports = SchemaString; }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":179,"../cast/string":193,"../error/index":204,"../helpers/symbols":252,"../options/SchemaStringOptions":267,"../schematype":295,"../utils":307,"./../document":194}],294:[function(require,module,exports){ 'use strict'; exports.schemaMixedSymbol = Symbol.for('mongoose:schema_mixed'); exports.builtInMiddleware = Symbol.for('mongoose:built-in-middleware'); },{}],295:[function(require,module,exports){ (function (Buffer){(function (){ 'use strict'; /*! * Module dependencies. */ const MongooseError = require('./error/index'); const SchemaTypeOptions = require('./options/SchemaTypeOptions'); const $exists = require('./schema/operators/exists'); const $type = require('./schema/operators/type'); const get = require('./helpers/get'); const handleImmutable = require('./helpers/schematype/handleImmutable'); const immediate = require('./helpers/immediate'); const schemaTypeSymbol = require('./helpers/symbols').schemaTypeSymbol; const util = require('util'); const utils = require('./utils'); const validatorErrorSymbol = require('./helpers/symbols').validatorErrorSymbol; const documentIsModified = require('./helpers/symbols').documentIsModified; const CastError = MongooseError.CastError; const ValidatorError = MongooseError.ValidatorError; /** * SchemaType constructor. Do **not** instantiate `SchemaType` directly. * Mongoose converts your schema paths into SchemaTypes automatically. * * ####Example: * * const schema = new Schema({ name: String }); * schema.path('name') instanceof SchemaType; // true * * @param {String} path * @param {SchemaTypeOptions} [options] See [SchemaTypeOptions docs](/docs/api/schematypeoptions.html) * @param {String} [instance] * @api public */ function SchemaType(path, options, instance) { this[schemaTypeSymbol] = true; this.path = path; this.instance = instance; this.validators = []; this.getters = this.constructor.hasOwnProperty('getters') ? this.constructor.getters.slice() : []; this.setters = []; options = options || {}; const defaultOptions = this.constructor.defaultOptions || {}; const defaultOptionsKeys = Object.keys(defaultOptions); for (const option of defaultOptionsKeys) { if (defaultOptions.hasOwnProperty(option) && !options.hasOwnProperty(option)) { options[option] = defaultOptions[option]; } } if (options.select == null) { delete options.select; } const 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); } const keys = Object.keys(this.options); for (const prop of keys) { if (prop === 'cast') { this.castFunction(this.options[prop]); continue; } if (utils.hasUserDefinedProperty(this.options, prop) && typeof this[prop] === 'function') { // { unique: true, index: true } if (prop === 'index' && this._index) { if (options.index === false) { const index = this._index; if (typeof index === 'object' && index != null) { if (index.unique) { throw new Error('Path "' + this.path + '" may not have `index` ' + 'set to false and `unique` set to true'); } if (index.sparse) { throw new Error('Path "' + this.path + '" may not have `index` ' + 'set to false and `sparse` set to true'); } } this._index = false; } continue; } const val = options[prop]; // Special case so we don't screw up array defaults, see gh-5780 if (prop === 'default') { this.default(val); continue; } const opts = Array.isArray(val) ? val : [val]; this[prop].apply(this, opts); } } Object.defineProperty(this, '$$context', { enumerable: false, configurable: false, writable: true, value: null }); } /*! * ignore */ SchemaType.prototype.OptionsConstructor = SchemaTypeOptions; /** * Get/set the function used to cast arbitrary values to this type. * * ####Example: * * // Disallow `null` for numbers, and don't try to cast any values to * // numbers, so even strings like '123' will cause a CastError. * mongoose.Number.cast(function(v) { * assert.ok(v === undefined || typeof v === 'number'); * return v; * }); * * @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed * @return {Function} * @static * @receiver SchemaType * @function cast * @api public */ SchemaType.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = v => v; } this._cast = caster; return this._cast; }; /** * Get/set the function used to cast arbitrary values to this particular schematype instance. * Overrides `SchemaType.cast()`. * * ####Example: * * // Disallow `null` for numbers, and don't try to cast any values to * // numbers, so even strings like '123' will cause a CastError. * const number = new mongoose.Number('mypath', {}); * number.cast(function(v) { * assert.ok(v === undefined || typeof v === 'number'); * return v; * }); * * @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed * @return {Function} * @static * @receiver SchemaType * @function cast * @api public */ SchemaType.prototype.castFunction = function castFunction(caster) { if (arguments.length === 0) { return this._castFunction; } if (caster === false) { caster = this.constructor._defaultCaster || (v => v); } this._castFunction = caster; return this._castFunction; }; /** * 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 = utils.args(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._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._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._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: * * function capitalize (val) { * if (typeof val !== 'string') val = ''; * return val.charAt(0).toUpperCase() + val.substring(1); * } * * // defining within the schema * const s = new Schema({ name: { type: String, set: capitalize }}); * * // or with the SchemaType * const s = new Schema({ name: String }) * s.path('name').set(capitalize); * * Setters allow you to transform the data before it gets to the raw mongodb * document or query. * * Suppose you are implementing user registration for a website. Users provide * an email and password, which gets saved to mongodb. The email is a string * that you will want to normalize to lower case, in order to avoid one email * having more than one account -- e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM. * * You can set up email lower case normalization easily via a Mongoose setter. * * function toLower(v) { * return v.toLowerCase(); * } * * const UserSchema = new Schema({ * email: { type: String, set: toLower } * }); * * const User = db.model('User', UserSchema); * * const user = new User({email: 'AVENUE@Q.COM'}); * console.log(user.email); // 'avenue@q.com' * * // or * const user = new User(); * user.email = 'Avenue@Q.com'; * console.log(user.email); // 'avenue@q.com' * User.updateOne({ _id: _id }, { $set: { email: 'AVENUE@Q.COM' } }); // update to 'avenue@q.com' * * As you can see above, setters allow you to transform the data before it * stored in MongoDB, or before executing a query. * * _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._ * * new Schema({ email: { type: String, lowercase: true }}) * * Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema. * * function inspector (val, schematype) { * if (schematype.options.required) { * return schematype.path + ' is required'; * } else { * return val; * } * } * * const VirusSchema = new Schema({ * name: { type: String, required: true, set: inspector }, * taxonomy: { type: String, set: inspector } * }) * * const Virus = db.model('Virus', VirusSchema); * const v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' }); * * console.log(v.name); // name is required * console.log(v.taxonomy); // Parvovirinae * * You can also use setters to modify other properties on the document. If * you're setting a property `name` on a document, the setter will run with * `this` as the document. Be careful, in mongoose 5 setters will also run * when querying by `name` with `this` as the query. * * ```javascript * const nameSchema = new Schema({ name: String, keywords: [String] }); * nameSchema.path('name').set(function(v) { * // Need to check if `this` is a document, because in mongoose 5 * // setters will also run on queries, in which case `this` will be a * // mongoose query object. * if (this instanceof Document && v != null) { * this.keywords = v.split(' '); * } * return v; * }); * ``` * * @param {Function} fn * @return {SchemaType} this * @api public */ SchemaType.prototype.set = function(fn) { if (typeof fn !== 'function') { throw new TypeError('A setter must be a function.'); } this.setters.push(fn); return this; }; /** * Adds a getter to this schematype. * * ####Example: * * function dob (val) { * if (!val) return val; * return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear(); * } * * // defining within the schema * const s = new Schema({ born: { type: Date, get: dob }) * * // or by retreiving its SchemaType * const s = new Schema({ born: Date }) * s.path('born').get(dob) * * Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see. * * Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way: * * function obfuscate (cc) { * return '****-****-****-' + cc.slice(cc.length-4, cc.length); * } * * const AccountSchema = new Schema({ * creditCardNumber: { type: String, get: obfuscate } * }); * * const Account = db.model('Account', AccountSchema); * * Account.findById(id, function (err, found) { * console.log(found.creditCardNumber); // '****-****-****-1234' * }); * * Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema. * * function inspector (val, schematype) { * if (schematype.options.required) { * return schematype.path + ' is required'; * } else { * return schematype.path + ' is not'; * } * } * * const VirusSchema = new Schema({ * name: { type: String, required: true, get: inspector }, * taxonomy: { type: String, get: inspector } * }) * * const Virus = db.model('Virus', VirusSchema); * * Virus.findById(id, function (err, virus) { * console.log(virus.name); // name is required * console.log(virus.taxonomy); // taxonomy is not * }) * * @param {Function} fn * @return {SchemaType} this * @api public */ SchemaType.prototype.get = function(fn) { if (typeof fn !== 'function') { throw new TypeError('A getter must be a function.'); } this.getters.push(fn); return this; }; /** * Adds validator(s) for this document path. * * Validators always receive the value to validate as their first argument and * must return `Boolean`. Returning `false` or throwing an error means * validation failed. * * The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used. * * ####Examples: * * // make sure every value is equal to "something" * function validator (val) { * return val == 'something'; * } * new Schema({ name: { type: String, validate: validator }}); * * // with a custom error message * * const custom = [validator, 'Uh oh, {PATH} does not equal "something".'] * new Schema({ name: { type: String, validate: custom }}); * * // adding many validators at a time * * const many = [ * { validator: validator, msg: 'uh oh' } * , { validator: anotherValidator, msg: 'failed' } * ] * new Schema({ name: { type: String, validate: many }}); * * // or utilizing SchemaType methods directly: * * const schema = new Schema({ name: 'string' }); * schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`'); * * ####Error message templates: * * From the examples above, you may have noticed that error messages support * basic templating. There are a few other template keywords besides `{PATH}` * and `{VALUE}` too. To find out more, details are available * [here](#error_messages_MongooseError.messages). * * If Mongoose's built-in error message templating isn't enough, Mongoose * supports setting the `message` property to a function. * * schema.path('name').validate({ * validator: function() { return v.length > 5; }, * // `errors['name']` will be "name must have length 5, got 'foo'" * message: function(props) { * return `${props.path} must have length 5, got '${props.value}'`; * } * }); * * To bypass Mongoose's error messages and just copy the error message that * the validator throws, do this: * * schema.path('name').validate({ * validator: function() { throw new Error('Oops!'); }, * // `errors['name']` will be "Oops!" * message: function(props) { return props.reason.message; } * }); * * ####Asynchronous validation: * * Mongoose supports validators that return a promise. A validator that returns * a promise is called an _async validator_. Async validators run in * parallel, and `validate()` will wait until all async validators have settled. * * schema.path('name').validate({ * validator: function (value) { * return new Promise(function (resolve, reject) { * resolve(false); // validation failed * }); * } * }); * * You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs. * * Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate). * * If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along. * * const conn = mongoose.createConnection(..); * conn.on('error', handleError); * * const Product = conn.model('Product', yourSchema); * const dvd = new Product(..); * dvd.save(); // emits error on the `conn` above * * If you want to handle these errors at the Model level, add an `error` * listener to your Model as shown below. * * // registering an error listener on the Model lets us handle errors more locally * Product.on('error', handleError); * * @param {RegExp|Function|Object} obj validator function, or hash describing options * @param {Function} [obj.validator] validator function. If the validator function returns `undefined` or a truthy value, validation succeeds. If it returns [falsy](https://masteringjs.io/tutorials/fundamentals/falsy) (except `undefined`) or throws an error, validation fails. * @param {String|Function} [obj.message] optional error message. If function, should return the error message as a string * @param {Boolean} [obj.propsParameter=false] If true, Mongoose will pass the validator properties object (with the `validator` function, `message`, etc.) as the 2nd arg to the validator function. This is disabled by default because many validators [rely on positional args](https://github.com/chriso/validator.js#validators), so turning this on may cause unpredictable behavior in external validators. * @param {String|Function} [errorMsg] optional error message. If function, should return the error message as a string * @param {String} [type] optional validator type * @return {SchemaType} this * @api public */ SchemaType.prototype.validate = function(obj, message, type) { if (typeof obj === 'function' || obj && utils.getFunctionName(obj.constructor) === 'RegExp') { let properties; if (typeof message === 'function') { properties = { validator: obj, message: message }; properties.type = type || 'user defined'; } else if (message instanceof Object && !type) { properties = utils.clone(message); if (!properties.message) { properties.message = properties.msg; } properties.validator = obj; properties.type = properties.type || 'user defined'; } else { if (message == null) { message = MongooseError.messages.general.default; } if (!type) { type = 'user defined'; } properties = { message: message, type: type, validator: obj }; } if (properties.isAsync) { handleIsAsync(); } this.validators.push(properties); return this; } let i; let length; let arg; for (i = 0, length = arguments.length; i < length; i++) { arg = arguments[i]; if (!utils.isPOJO(arg)) { const msg = 'Invalid validator. Received (' + typeof arg + ') ' + arg + '. See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate'; throw new Error(msg); } this.validate(arg.validator, arg); } return this; }; /*! * ignore */ const handleIsAsync = util.deprecate(function handleIsAsync() {}, 'Mongoose: the `isAsync` option for custom validators is deprecated. Make ' + 'your async validators return a promise instead: ' + 'https://mongoosejs.com/docs/validation.html#async-custom-validators'); /** * Adds a required validator to this SchemaType. The validator gets added * to the front of this SchemaType's validators array using `unshift()`. * * ####Example: * * const s = new Schema({ born: { type: Date, required: true }) * * // or with custom error message * * const s = new Schema({ born: { type: Date, required: '{PATH} is required!' }) * * // or with a function * * const s = new Schema({ * userId: ObjectId, * username: { * type: String, * required: function() { return this.userId != null; } * } * }) * * // or with a function and a custom message * const s = new Schema({ * userId: ObjectId, * username: { * type: String, * required: [ * function() { return this.userId != null; }, * 'username is required if id is specified' * ] * } * }) * * // or through the path API * * s.path('name').required(true); * * // with custom error messaging * * s.path('name').required(true, 'grrr :( '); * * // or make a path conditionally required based on a function * const isOver18 = function() { return this.age >= 18; }; * s.path('voterRegistrationId').required(isOver18); * * The required validator uses the SchemaType's `checkRequired` function to * determine whether a given value satisfies the required validator. By default, * a value satisfies the required validator if `val != null` (that is, if * the value is not null nor undefined). However, most built-in mongoose schema * types override the default `checkRequired` function: * * @param {Boolean|Function|Object} required enable/disable the validator, or function that returns required boolean, or options object * @param {Boolean|Function} [options.isRequired] enable/disable the validator, or function that returns required boolean * @param {Function} [options.ErrorConstructor] custom error constructor. The constructor receives 1 parameter, an object containing the validator properties. * @param {String} [message] optional custom error message * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @see SchemaArray#checkRequired #schema_array_SchemaArray.checkRequired * @see SchemaBoolean#checkRequired #schema_boolean_SchemaBoolean-checkRequired * @see SchemaBuffer#checkRequired #schema_buffer_SchemaBuffer.schemaName * @see SchemaNumber#checkRequired #schema_number_SchemaNumber-min * @see SchemaObjectId#checkRequired #schema_objectid_ObjectId-auto * @see SchemaString#checkRequired #schema_string_SchemaString-checkRequired * @api public */ SchemaType.prototype.required = function(required, message) { let customOptions = {}; if (arguments.length > 0 && required == null) { this.validators = this.validators.filter(function(v) { return v.validator !== this.requiredValidator; }, this); this.isRequired = false; delete this.originalRequiredValue; return this; } 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; } const _this = this; this.isRequired = true; this.requiredValidator = function(v) { const cachedRequired = get(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) { const res = cachedRequired[_this.path] ? _this.checkRequired(v, this) : true; delete cachedRequired[_this.path]; return res; } else if (typeof required === 'function') { return required.apply(this) ? _this.checkRequired(v, this) : true; } return _this.checkRequired(v, this); }; this.originalRequiredValue = required; if (typeof required === 'string') { message = required; required = undefined; } const 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) { let ret = typeof this.defaultValue === 'function' ? this.defaultValue.call(scope) : this.defaultValue; if (ret !== null && ret !== undefined) { if (typeof ret === 'object' && (!this.options || !this.options.shared)) { ret = utils.clone(ret); } const casted = this.applySetters(ret, scope, init); if (casted && casted.$isSingleNested) { casted.$__parent = scope; } return casted; } return ret; }; /*! * Applies setters without casting * * @api private */ SchemaType.prototype._applySetters = function(value, scope, init) { let v = value; if (init) { return v; } const setters = this.setters; for (const setter of utils.clone(setters).reverse()) { v = setter.call(scope, v, this); } 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) { let v = this._applySetters(value, scope, init, priorVal, options); if (v == null) { return this._castNullish(v); } // do not cast until all setters are applied #665 v = this.cast(v, scope, init, priorVal, options); return v; }; /** * Applies getters to a value * * @param {Object} value * @param {Object} scope * @api private */ SchemaType.prototype.applyGetters = function(value, scope) { let v = value; const getters = this.getters; const len = getters.length; if (len === 0) { return v; } for (let 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) { let err = false; const path = this.path; // Avoid non-object `validators` const validators = this.validators. filter(v => v != null && typeof v === 'object'); let count = validators.length; if (!count) { return fn(null); } const _this = this; validators.forEach(function(v) { if (err) { return; } const validator = v.validator; let ok; const validatorProperties = utils.clone(v); validatorProperties.path = options && options.path ? options.path : path; validatorProperties.value = value; if (validator instanceof RegExp) { validate(validator.test(value), validatorProperties); return; } if (typeof validator !== 'function') { return; } if (value === undefined && validator !== _this.requiredValidator) { validate(true, validatorProperties); return; } if (validatorProperties.isAsync) { asyncValidate(validator, scope, value, validatorProperties, validate); return; } 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); } }); function validate(ok, validatorProperties) { if (err) { return; } if (ok === undefined || ok) { if (--count <= 0) { immediate(function() { fn(null); }); } } else { const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; err = new ErrorConstructor(validatorProperties); err[validatorErrorSymbol] = true; immediate(function() { fn(err); }); } } }; /*! * Handle async validators */ function asyncValidate(validator, scope, value, props, cb) { let called = false; const returnVal = validator.call(scope, value, function(ok, customMsg) { if (called) { return; } called = true; if (customMsg) { props.message = customMsg; } cb(ok, props); }); if (typeof returnVal === 'boolean') { called = true; cb(returnVal, props); } else if (returnVal && typeof returnVal.then === 'function') { // Promise returnVal.then( function(ok) { if (called) { return; } called = true; cb(ok, props); }, function(error) { if (called) { return; } called = true; props.reason = error; props.message = error.message; cb(false, props); }); } } /** * 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) { const path = this.path; const count = this.validators.length; if (!count) { return null; } let validators = this.validators; if (value === void 0) { if (this.validators.length > 0 && this.validators[0].type === 'required') { validators = [this.validators[0]]; } else { return null; } } let err = null; validators.forEach(function(v) { if (err) { return; } if (v == null || typeof v !== 'object') { return; } const validator = v.validator; const validatorProperties = utils.clone(v); validatorProperties.path = options && options.path ? options.path : path; validatorProperties.value = value; let ok; // Skip any explicit async validators. Validators that return a promise // will still run, but won't trigger any errors. if (validator.isAsync) { return; } if (validator instanceof RegExp) { validate(validator.test(value), validatorProperties); return; } if (typeof validator !== 'function') { return; } try { if (validatorProperties.propsParameter) { ok = validator.call(scope, value, validatorProperties); } else { ok = validator.call(scope, value); } } catch (error) { ok = false; validatorProperties.reason = error; } // Skip any validators that return a promise, we can't handle those // synchronously if (ok != null && typeof ok.then === 'function') { return; } validate(ok, validatorProperties); }); return err; function validate(ok, validatorProperties) { if (err) { return; } if (ok !== undefined && !ok) { const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; err = new ErrorConstructor(validatorProperties); err[validatorErrorSymbol] = true; } } }; /** * Determines if value is a valid Reference. * * @param {SchemaType} self * @param {Object} value * @param {Document} doc * @param {Boolean} init * @return {Boolean} * @api private */ SchemaType._isRef = function(self, value, doc, init) { // fast path let ref = init && self.options && (self.options.ref || self.options.refPath); if (!ref && doc && doc.$__ != null) { // checks for // - this populated with adhoc model and no ref was set in schema OR // - setting / pushing values after population const path = doc.$__fullPath(self.path); const owner = doc.ownerDocument ? doc.ownerDocument() : doc; ref = owner.populated(path) || doc.populated(self.path); } if (ref) { if (value == null) { return true; } if (!Buffer.isBuffer(value) && // buffers are objects too value._bsontype !== 'Binary' // raw binary value from the db && utils.isObject(value) // might have deselected _id in population query ) { return true; } } return false; }; /*! * ignore */ function handleSingle(val) { return this.castForQuery(val); } /*! * ignore */ function handleArray(val) { const _this = this; if (!Array.isArray(val)) { return [this.castForQuery(val)]; } return val.map(function(m) { return _this.castForQuery(m); }); } /*! * Just like handleArray, except also allows `[]` because surprisingly * `$in: [1, []]` works fine */ function handle$in(val) { const _this = this; if (!Array.isArray(val)) { return [this.castForQuery(val)]; } return val.map(function(m) { if (Array.isArray(m) && m.length === 0) { return m; } return _this.castForQuery(m); }); } /*! * 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) { const ret = this.castForQuery(params.$conditional, params.val); this.$$context = null; return ret; } if (params.$skipQueryCastForUpdate || params.$applySetters) { const ret = this._castForQuery(params.val); this.$$context = null; return ret; } const 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) { let handler; if (arguments.length === 2) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error('Can\'t use ' + $conditional); } return handler.call(this, val); } val = $conditional; return this._castForQuery(val); }; /*! * 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() { const options = Object.assign({}, this.options); const schematype = new this.constructor(this.path, options, this.instance); schematype.validators = this.validators.slice(); if (this.requiredValidator !== undefined) schematype.requiredValidator = this.requiredValidator; if (this.defaultValue !== undefined) schematype.defaultValue = this.defaultValue; if (this.$immutable !== undefined && this.options.immutable === undefined) { schematype.$immutable = this.$immutable; handleImmutable(schematype); } if (this._index !== undefined) schematype._index = this._index; if (this.selected !== undefined) schematype.selected = this.selected; if (this.isRequired !== undefined) schematype.isRequired = this.isRequired; if (this.originalRequiredValue !== undefined) schematype.originalRequiredValue = this.originalRequiredValue; schematype.getters = this.getters.slice(); schematype.setters = this.setters.slice(); return schematype; }; /*! * Module exports. */ module.exports = exports = SchemaType; exports.CastError = CastError; exports.ValidatorError = ValidatorError; }).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) },{"../../is-buffer/index.js":179,"./error/index":204,"./helpers/get":229,"./helpers/immediate":231,"./helpers/schematype/handleImmutable":250,"./helpers/symbols":252,"./options/SchemaTypeOptions":268,"./schema/operators/exists":288,"./schema/operators/type":292,"./utils":307,"util":332}],296:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const utils = require('./utils'); /*! * StateMachine represents a minimal `interface` for the * constructors it builds via StateMachine.ctor(...). * * @api private */ const StateMachine = module.exports = exports = function StateMachine() { }; /*! * StateMachine.ctor('state1', 'state2', ...) * A factory method for subclassing StateMachine. * The arguments are a list of states. For each state, * the constructor's prototype gets state transition * methods named after each state. These transition methods * place their path argument into the given state. * * @param {String} state * @param {String} [state] * @return {Function} subclass constructor * @private */ StateMachine.ctor = function() { const states = utils.args(arguments); const ctor = function() { StateMachine.apply(this, arguments); this.paths = {}; this.states = {}; this.stateNames = states; let i = states.length, state; while (i--) { state = states[i]; this.states[state] = {}; } }; 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) { const 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) { const keys = Object.keys(this.states[state]); let i = keys.length; let path; while (i--) { path = keys[i]; delete this.states[state][path]; delete this.paths[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() { const _this = this; const what = arguments.length ? arguments : this.stateNames; return Array.prototype.some.call(what, function(state) { return Object.keys(_this.states[state]).length; }); }; /*! * This function builds the functions that get assigned to `forEach` and `map`, * since both of those methods share a lot of the same logic. * * @param {String} iterMethod is either 'forEach' or 'map' * @return {Function} * @api private */ StateMachine.prototype._iter = function _iter(iterMethod) { return function() { const numArgs = arguments.length; let states = utils.args(arguments, 0, numArgs - 1); const callback = arguments[numArgs - 1]; if (!states.length) states = this.stateNames; const _this = this; const paths = states.reduce(function(paths, state) { return paths.concat(Object.keys(_this.states[state])); }, []); return paths[iterMethod](function(path, i, paths) { return callback(path, i, paths); }); }; }; /*! * 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); }; },{"./utils":307}],297:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const CoreMongooseArray = require('./core_array'); const Document = require('../document'); const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol; const arrayParentSymbol = require('../helpers/symbols').arrayParentSymbol; const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol; const arraySchemaSymbol = require('../helpers/symbols').arraySchemaSymbol; const _basePush = Array.prototype.push; /** * Mongoose Array constructor. * * ####NOTE: * * _Values always have to be passed to the constructor to initialize, otherwise `MongooseArray#push` will mark the array as modified._ * * @param {Array} values * @param {String} path * @param {Document} doc parent document * @api private * @inherits Array * @see http://bit.ly/f6CnZU */ function MongooseArray(values, path, doc, schematype) { const arr = new CoreMongooseArray(); arr[arrayAtomicsSymbol] = {}; if (Array.isArray(values)) { const len = values.length; for (let i = 0; i < len; ++i) { _basePush.call(arr, values[i]); } if (values[arrayAtomicsSymbol] != null) { arr[arrayAtomicsSymbol] = values[arrayAtomicsSymbol]; } } arr[arrayPathSymbol] = path; arr[arraySchemaSymbol] = void 0; // 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 && doc instanceof Document) { arr[arrayParentSymbol] = doc; arr[arraySchemaSymbol] = schematype || doc.schema.path(path); } return arr; } /*! * Module exports. */ module.exports = exports = MongooseArray; },{"../document":194,"../helpers/symbols":252,"./core_array":299}],298:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const Binary = require('../driver').get().Binary; const utils = require('../utils'); const Buffer = require('safe-buffer').Buffer; /** * Mongoose Buffer constructor. * * Values always have to be passed to the constructor to initialize. * * @param {Buffer} value * @param {String} encode * @param {Number} offset * @api private * @inherits Buffer * @see http://bit.ly/f6CnZU */ function MongooseBuffer(value, encode, offset) { const length = arguments.length; let val; if (length === 0 || arguments[0] === null || arguments[0] === undefined) { val = 0; } else { val = value; } let encoding; let path; let doc; if (Array.isArray(encode)) { // internal casting path = encode[0]; doc = encode[1]; } else { encoding = encode; } let buf; if (typeof val === 'number' || val instanceof Number) { buf = Buffer.alloc(val); } else { // string, array or object { type: 'Buffer', data: [...] } buf = Buffer.from(val, encoding, offset); } utils.decorate(buf, MongooseBuffer.mixin); buf.isMongooseBuffer = true; // make sure these internal props don't show up in Object.keys() buf[MongooseBuffer.pathSymbol] = path; buf[parentSymbol] = doc; buf._subtype = 0; return buf; } const pathSymbol = Symbol.for('mongoose#Buffer#_path'); const 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() { const parent = this[parentSymbol]; if (parent) { parent.markModified(this[MongooseBuffer.pathSymbol]); } return this; }, /** * Writes the buffer. * * @api public * @method write * @receiver MongooseBuffer */ write: function() { const written = Buffer.prototype.write.apply(this, arguments); if (written > 0) { this._markModified(); } return written; }, /** * Copies the buffer. * * ####Note: * * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this. * * @return {Number} The number of bytes copied. * @param {Buffer} target * @method copy * @receiver MongooseBuffer */ copy: function(target) { const ret = Buffer.prototype.copy.apply(this, arguments); if (target && target.isMongooseBuffer) { target._markModified(); } 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() { const 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 http://bsonspec.org/#/specification * @param {Hex} [subtype] * @return {Binary} * @api public * @method toObject * @receiver MongooseBuffer */ MongooseBuffer.mixin.toObject = function(options) { const subtype = typeof options === 'number' ? options : (this._subtype || 0); return new Binary(Buffer.from(this), subtype); }; /** * 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 (let 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 http://bsonspec.org/#/specification * @param {Hex} subtype * @api public * @method subtype * @receiver MongooseBuffer */ MongooseBuffer.mixin.subtype = function(subtype) { if (typeof subtype !== 'number') { throw new TypeError('Invalid subtype. Expected a number'); } if (this._subtype !== subtype) { this._markModified(); } this._subtype = subtype; }; /*! * Module exports. */ MongooseBuffer.Binary = Binary; module.exports = MongooseBuffer; },{"../driver":196,"../utils":307,"safe-buffer":327}],299:[function(require,module,exports){ (function (Buffer){(function (){ 'use strict'; const Document = require('../document'); const EmbeddedDocument = require('./embedded'); const MongooseError = require('../error/mongooseError'); const ObjectId = require('./objectid'); const cleanModifiedSubpaths = require('../helpers/document/cleanModifiedSubpaths'); const get = require('../helpers/get'); const internalToObjectOptions = require('../options').internalToObjectOptions; const utils = require('../utils'); const util = require('util'); const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol; const arrayParentSymbol = require('../helpers/symbols').arrayParentSymbol; const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol; const arraySchemaSymbol = require('../helpers/symbols').arraySchemaSymbol; const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; const slicedSymbol = Symbol('mongoose#Array#sliced'); const _basePush = Array.prototype.push; const validatorsSymbol = Symbol('mongoose#MongooseCoreArray#validators'); /*! * ignore */ class CoreMongooseArray extends Array { get isMongooseArray() { return true; } get validators() { return this[validatorsSymbol]; } set validators(v) { this[validatorsSymbol] = v; } /** * Depopulates stored atomic operation values as necessary for direct insertion to MongoDB. * * If no atomics exist, we return all array values after conversion. * * @return {Array} * @method $__getAtomics * @memberOf MongooseArray * @instance * @api private */ $__getAtomics() { const ret = []; const keys = Object.keys(this[arrayAtomicsSymbol] || {}); let i = keys.length; const opts = Object.assign({}, internalToObjectOptions, { _isNested: true }); if (i === 0) { ret[0] = ['$set', this.toObject(opts)]; return ret; } while (i--) { const op = keys[i]; let val = this[arrayAtomicsSymbol][op]; // the atomic values which are arrays are not MongooseArrays. we // need to convert their elements as if they were MongooseArrays // to handle populated arrays versus DocumentArrays properly. if (utils.isMongooseObject(val)) { val = val.toObject(opts); } else if (Array.isArray(val)) { val = this.toObject.call(val, opts); } else if (val != null && Array.isArray(val.$each)) { val.$each = this.toObject.call(val.$each, opts); } else if (val != null && typeof val.valueOf === 'function') { val = val.valueOf(); } if (op === '$addToSet') { val = { $each: val }; } ret.push([op, val]); } return ret; } /*! * ignore */ $atomics() { return this[arrayAtomicsSymbol]; } /*! * ignore */ $parent() { return this[arrayParentSymbol]; } /*! * ignore */ $path() { return this[arrayPathSymbol]; } /** * Atomically shifts the array at most one time per document `save()`. * * ####NOTE: * * _Calling this multiple times on an array before saving sends the same command as calling it once._ * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ * * doc.array = [1,2,3]; * * const shifted = doc.array.$shift(); * console.log(shifted); // 1 * console.log(doc.array); // [2,3] * * // no affect * shifted = doc.array.$shift(); * console.log(doc.array); // [2,3] * * doc.save(function (err) { * if (err) return handleError(err); * * // we saved, now $shift works again * shifted = doc.array.$shift(); * console.log(shifted ); // 2 * console.log(doc.array); // [3] * }) * * @api public * @memberOf MongooseArray * @instance * @method $shift * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop */ $shift() { this._registerAtomic('$pop', -1); this._markModified(); // only allow shifting once if (this._shifted) { return; } this._shifted = true; return [].shift.call(this); } /** * Pops the array atomically at most one time per document `save()`. * * #### NOTE: * * _Calling this mulitple times on an array before saving sends the same command as calling it once._ * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ * * doc.array = [1,2,3]; * * const popped = doc.array.$pop(); * console.log(popped); // 3 * console.log(doc.array); // [1,2] * * // no affect * popped = doc.array.$pop(); * console.log(doc.array); // [1,2] * * doc.save(function (err) { * if (err) return handleError(err); * * // we saved, now $pop works again * popped = doc.array.$pop(); * console.log(popped); // 2 * console.log(doc.array); // [1] * }) * * @api public * @method $pop * @memberOf MongooseArray * @instance * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop * @method $pop * @memberOf MongooseArray */ $pop() { this._registerAtomic('$pop', 1); this._markModified(); // only allow popping once if (this._popped) { return; } this._popped = true; return [].pop.call(this); } /*! * ignore */ $schema() { return this[arraySchemaSymbol]; } /** * Casts a member based on this arrays schema. * * @param {any} value * @return value the casted value * @method _cast * @api private * @memberOf MongooseArray */ _cast(value) { let populated = false; let Model; if (this[arrayParentSymbol]) { populated = this[arrayParentSymbol].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) || value instanceof ObjectId || !utils.isObject(value)) { value = { _id: value }; } // gh-2399 // we should cast model only when it's not a discriminator const isDisc = value.schema && value.schema.discriminatorMapping && value.schema.discriminatorMapping.key !== undefined; if (!isDisc) { value = new Model(value); } return this[arraySchemaSymbol].caster.applySetters(value, this[arrayParentSymbol], true); } return this[arraySchemaSymbol].caster.applySetters(value, this[arrayParentSymbol], false); } /** * Internal helper for .map() * * @api private * @return {Number} * @method _mapCast * @memberOf MongooseArray */ _mapCast(val, index) { return this._cast(val, this.length + index); } /** * Marks this array as modified. * * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments) * * @param {EmbeddedDocument} embeddedDoc the embedded doc that invoked this method on the Array * @param {String} embeddedPath the path which changed in the embeddedDoc * @method _markModified * @api private * @memberOf MongooseArray */ _markModified(elem) { const parent = this[arrayParentSymbol]; let dirtyPath; if (parent) { dirtyPath = this[arrayPathSymbol]; if (arguments.length) { dirtyPath = dirtyPath + '.' + elem; } if (dirtyPath != null && dirtyPath.endsWith('.$')) { return this; } 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(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; } const atomics = this[arrayAtomicsSymbol]; // reset pop/shift after save if (op === '$pop' && !('$pop' in atomics)) { const _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 (this[arrayAtomicsSymbol].$set || Object.keys(atomics).length && !(op in atomics)) { // a different op was previously registered. // save the entire thing. this[arrayAtomicsSymbol] = { $set: this }; return this; } let selector; if (op === '$pullAll' || op === '$addToSet') { atomics[op] || (atomics[op] = []); atomics[op] = atomics[op].concat(val); } else if (op === '$pullDocs') { const pullOp = atomics['$pull'] || (atomics['$pull'] = {}); if (val[0] instanceof EmbeddedDocument) { selector = pullOp['$or'] || (pullOp['$or'] = []); Array.prototype.push.apply(selector, val.map(function(v) { return v.toObject({ transform: false, virtuals: false }); })); } else { selector = pullOp['_id'] || (pullOp['_id'] = { $in: [] }); selector['$in'] = selector['$in'].concat(val); } } else if (op === '$push') { atomics.$push = atomics.$push || { $each: [] }; if (val != null && utils.hasUserDefinedProperty(val, '$each')) { atomics.$push = val; } else { atomics.$push.$each = atomics.$push.$each.concat(val); } } else { atomics[op] = val; } return this; } /** * Adds values to the array if not already present. * * ####Example: * * console.log(doc.array) // [2,3,4] * const added = doc.array.addToSet(4,5); * console.log(doc.array) // [2,3,4,5] * console.log(added) // [5] * * @param {any} [args...] * @return {Array} the values that were added * @memberOf MongooseArray * @api public * @method addToSet */ addToSet() { _checkManualPopulation(this, arguments); let values = [].map.call(arguments, this._mapCast, this); values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]); const added = []; let type = ''; if (values[0] instanceof EmbeddedDocument) { type = 'doc'; } else if (values[0] instanceof Date) { type = 'date'; } values.forEach(function(v) { let found; const val = +v; switch (type) { case 'doc': found = this.some(function(doc) { return doc.equals(v); }); break; case 'date': found = this.some(function(d) { return +d === val; }); break; default: found = ~this.indexOf(v); } if (!found) { [].push.call(this, v); this._registerAtomic('$addToSet', v); this._markModified(); [].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() { 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 * @return {Boolean} * @api public * @method includes * @memberOf MongooseArray */ includes(obj, fromIndex) { const ret = this.indexOf(obj, fromIndex); return ret !== -1; } /** * Return the index of `obj` or `-1` if not found. * * @param {Object} obj the item to look for * @return {Number} * @api public * @method indexOf * @memberOf MongooseArray */ indexOf(obj, fromIndex) { if (obj instanceof ObjectId) { obj = obj.toString(); } fromIndex = fromIndex == null ? 0 : fromIndex; const len = this.length; for (let i = fromIndex; i < len; ++i) { if (obj == this[i]) { return i; } } return -1; } /** * Helper for console.log * * @api public * @method inspect * @memberOf MongooseArray */ inspect() { return JSON.stringify(this); } /** * Pushes items to the array non-atomically. * * ####NOTE: * * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ * * @param {any} [args...] * @api public * @method nonAtomicPush * @memberOf MongooseArray */ nonAtomicPush() { const values = [].map.call(arguments, this._mapCast, this); const ret = [].push.apply(this, values); this._registerAtomic('$set', this); this._markModified(); return ret; } /** * Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking. * * ####Note: * * _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._ * * @see MongooseArray#$pop #types_array_MongooseArray-%24pop * @api public * @method pop * @memberOf MongooseArray */ pop() { const ret = [].pop.call(this); this._registerAtomic('$set', this); this._markModified(); return ret; } /** * Pulls items from the array atomically. Equality is determined by casting * the provided value to an embedded document and comparing using * [the `Document.equals()` function.](./api.html#document_Document-equals) * * ####Examples: * * doc.array.pull(ObjectId) * doc.array.pull({ _id: 'someId' }) * doc.array.pull(36) * doc.array.pull('tag 1', 'tag 2') * * To remove a document from a subdocument array we may pass an object with a matching `_id`. * * doc.subdocs.push({ _id: 4815162342 }) * doc.subdocs.pull({ _id: 4815162342 }) // removed * * Or we may passing the _id directly and let mongoose take care of it. * * doc.subdocs.push({ _id: 4815162342 }) * doc.subdocs.pull(4815162342); // works * * The first pull call will result in a atomic operation on the database, if pull is called repeatedly without saving the document, a $set operation is used on the complete array instead, overwriting possible changes that happened on the database in the meantime. * * @param {any} [args...] * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull * @api public * @method pull * @memberOf MongooseArray */ pull() { const values = [].map.call(arguments, this._cast, this); const cur = this[arrayParentSymbol].get(this[arrayPathSymbol]); let i = cur.length; let mem; while (i--) { mem = cur[i]; if (mem instanceof Document) { const some = values.some(function(v) { return mem.equals(v); }); if (some) { [].splice.call(cur, i, 1); } } else if (~cur.indexOf.call(values, mem)) { [].splice.call(cur, i, 1); } } if (values[0] instanceof EmbeddedDocument) { this._registerAtomic('$pullDocs', values.map(function(v) { return v.$__getValue('_id') || v; })); } else { this._registerAtomic('$pullAll', values); } this._markModified(); // Might have modified child paths and then pulled, like // `doc.children[1].name = 'test';` followed by // `doc.children.remove(doc.children[0]);`. In this case we fall back // to a `$set` on the whole array. See #3511 if (cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]) > 0) { this._registerAtomic('$set', this); } return this; } /** * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. * * ####Example: * * const schema = Schema({ nums: [Number] }); * const Model = mongoose.model('Test', schema); * * const doc = await Model.create({ nums: [3, 4] }); * doc.nums.push(5); // Add 5 to the end of the array * await doc.save(); * * // You can also pass an object with `$each` as the * // first parameter to use MongoDB's `$position` * doc.nums.push({ * $each: [1, 2], * $position: 0 * }); * doc.nums; // [1, 2, 3, 4, 5] * * @param {Object} [args...] * @api public * @method push * @memberOf MongooseArray */ push() { let values = arguments; let atomic = values; const isOverwrite = values[0] != null && utils.hasUserDefinedProperty(values[0], '$each'); if (isOverwrite) { atomic = values[0]; values = values[0].$each; } if (this[arraySchemaSymbol] == null) { return _basePush.apply(this, values); } _checkManualPopulation(this, values); const parent = this[arrayParentSymbol]; values = [].map.call(values, this._mapCast, this); values = this[arraySchemaSymbol].applySetters(values, parent, undefined, undefined, { skipDocumentArrayCast: true }); let ret; const atomics = this[arrayAtomicsSymbol]; if (isOverwrite) { atomic.$each = values; if (get(atomics, '$push.$each.length', 0) > 0 && atomics.$push.$position != atomics.$position) { throw new MongooseError('Cannot call `Array#push()` multiple times ' + 'with different `$position`'); } if (atomic.$position != null) { [].splice.apply(this, [atomic.$position, 0].concat(values)); ret = this.length; } else { ret = [].push.apply(this, values); } } else { if (get(atomics, '$push.$each.length', 0) > 0 && atomics.$push.$position != null) { throw new MongooseError('Cannot call `Array#push()` multiple times ' + 'with different `$position`'); } atomic = values; ret = [].push.apply(this, values); } this._registerAtomic('$push', atomic); this._markModified(); return ret; } /** * Alias of [pull](#mongoosearray_MongooseArray-pull) * * @see MongooseArray#pull #types_array_MongooseArray-pull * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull * @api public * @memberOf MongooseArray * @instance * @method remove */ remove() { return this.pull.apply(this, arguments); } /** * Sets the casted `val` at index `i` and marks the array modified. * * ####Example: * * // given documents based on the following * const Doc = mongoose.model('Doc', new Schema({ array: [Number] })); * * const doc = new Doc({ array: [2,3,4] }) * * console.log(doc.array) // [2,3,4] * * doc.array.set(1,"5"); * console.log(doc.array); // [2,5,4] // properly cast to number * doc.save() // the change is saved * * // VS not using array#set * doc.array[1] = "5"; * console.log(doc.array); // [2,"5",4] // no casting * doc.save() // change is not saved * * @return {Array} this * @api public * @method set * @memberOf MongooseArray */ set(i, val) { const value = this._cast(val, i); this[i] = value; this._markModified(i); return this; } /** * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. * * ####Example: * * doc.array = [2,3]; * const res = doc.array.shift(); * console.log(res) // 2 * console.log(doc.array) // [3] * * ####Note: * * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ * * @api public * @method shift * @memberOf MongooseArray */ shift() { const ret = [].shift.call(this); this._registerAtomic('$set', this); this._markModified(); return ret; } /** * Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking. * * ####NOTE: * * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ * * @api public * @method sort * @memberOf MongooseArray * @see https://masteringjs.io/tutorials/fundamentals/array-sort */ sort() { const ret = [].sort.apply(this, arguments); this._registerAtomic('$set', this); return ret; } /** * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. * * ####Note: * * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ * * @api public * @method splice * @memberOf MongooseArray * @see https://masteringjs.io/tutorials/fundamentals/array-splice */ splice() { let ret; _checkManualPopulation(this, Array.prototype.slice.call(arguments, 2)); if (arguments.length) { let vals; if (this[arraySchemaSymbol] == null) { vals = arguments; } else { vals = []; for (let i = 0; i < arguments.length; ++i) { vals[i] = i < 2 ? arguments[i] : this._cast(arguments[i], arguments[0] + (i - 2)); } } ret = [].splice.apply(this, vals); this._registerAtomic('$set', this); } return ret; } /*! * ignore */ slice() { const ret = super.slice.apply(this, arguments); ret[arrayParentSymbol] = this[arrayParentSymbol]; ret[arraySchemaSymbol] = this[arraySchemaSymbol]; ret[arrayAtomicsSymbol] = this[arrayAtomicsSymbol]; ret[arrayPathSymbol] = this[arrayPathSymbol]; ret[slicedSymbol] = true; return ret; } /*! * ignore */ filter() { const ret = super.filter.apply(this, arguments); ret[arrayParentSymbol] = this[arrayParentSymbol]; ret[arraySchemaSymbol] = this[arraySchemaSymbol]; ret[arrayAtomicsSymbol] = this[arrayAtomicsSymbol]; ret[arrayPathSymbol] = this[arrayPathSymbol]; return ret; } /*! * ignore */ toBSON() { return this.toObject(internalToObjectOptions); } /** * Returns a native js Array. * * @param {Object} options * @return {Array} * @api public * @method toObject * @memberOf MongooseArray */ toObject(options) { if (options && options.depopulate) { options = utils.clone(options); options._isNested = true; // Ensure return value is a vanilla array, because in Node.js 6+ `map()` // is smart enough to use the inherited array's constructor. return [].concat(this).map(function(doc) { return doc instanceof Document ? doc.toObject(options) : doc; }); } return [].concat(this); } /** * Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. * * ####Note: * * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwriting any changes that happen between when you retrieved the object and when you save it._ * * @api public * @method unshift * @memberOf MongooseArray */ unshift() { _checkManualPopulation(this, arguments); let values; if (this[arraySchemaSymbol] == null) { values = arguments; } else { values = [].map.call(arguments, this._cast, this); values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]); } [].unshift.apply(this, values); this._registerAtomic('$set', this); this._markModified(); return this.length; } } if (util.inspect.custom) { CoreMongooseArray.prototype[util.inspect.custom] = CoreMongooseArray.prototype.inspect; } /*! * ignore */ function _isAllSubdocs(docs, ref) { if (!ref) { return false; } for (const arg of docs) { if (arg == null) { return false; } const model = arg.constructor; if (!(arg instanceof Document) || (model.modelName !== ref && model.baseModelName !== ref)) { return false; } } return true; } /*! * ignore */ function _checkManualPopulation(arr, docs) { const ref = arr == null ? null : get(arr[arraySchemaSymbol], 'caster.options.ref', null); if (arr.length === 0 && docs.length > 0) { if (_isAllSubdocs(docs, ref)) { arr[arrayParentSymbol].populated(arr[arrayPathSymbol], [], { [populateModelSymbol]: docs[0].constructor }); } } } module.exports = CoreMongooseArray; }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":179,"../document":194,"../error/mongooseError":207,"../helpers/document/cleanModifiedSubpaths":225,"../helpers/get":229,"../helpers/symbols":252,"../options":257,"../utils":307,"./embedded":302,"./objectid":305,"util":332}],300:[function(require,module,exports){ /** * ObjectId type constructor * * ####Example * * const id = new mongoose.Types.ObjectId; * * @constructor ObjectId */ 'use strict'; module.exports = require('../driver').get().Decimal128; },{"../driver":196}],301:[function(require,module,exports){ (function (Buffer){(function (){ 'use strict'; /*! * Module dependencies. */ const CoreMongooseArray = require('./core_array'); const Document = require('../document'); const ObjectId = require('./objectid'); const castObjectId = require('../cast/objectid'); const getDiscriminatorByValue = require('../helpers/discriminator/getDiscriminatorByValue'); const internalToObjectOptions = require('../options').internalToObjectOptions; const util = require('util'); const utils = require('../utils'); const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol; const arrayParentSymbol = require('../helpers/symbols').arrayParentSymbol; const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol; const arraySchemaSymbol = require('../helpers/symbols').arraySchemaSymbol; const documentArrayParent = require('../helpers/symbols').documentArrayParent; const _basePush = Array.prototype.push; class CoreDocumentArray extends CoreMongooseArray { get isMongooseDocumentArray() { return true; } /*! * ignore */ toBSON() { return this.toObject(internalToObjectOptions); } /*! * ignore */ map() { const ret = super.map.apply(this, arguments); ret[arraySchemaSymbol] = null; ret[arrayPathSymbol] = null; ret[arrayParentSymbol] = null; return ret; } /** * Overrides MongooseArray#cast * * @method _cast * @api private * @receiver MongooseDocumentArray */ _cast(value, index) { if (this[arraySchemaSymbol] == null) { return value; } let Constructor = this[arraySchemaSymbol].casterConstructor; const isInstance = Constructor.$isMongooseDocumentArray ? value && value.isMongooseDocumentArray : value instanceof Constructor; if (isInstance || // Hack re: #5001, see #5005 (value && value.constructor && value.constructor.baseCasterConstructor === Constructor)) { if (!(value[documentArrayParent] && value.__parentArray)) { // value may have been created using array.create() value[documentArrayParent] = this[arrayParentSymbol]; value.__parentArray = this; } value.$setIndex(index); return value; } 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) || value instanceof 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 { const constructorByValue = getDiscriminatorByValue(Constructor, value[Constructor.schema.options.discriminatorKey]); if (constructorByValue) { Constructor = constructorByValue; } } } if (Constructor.$isMongooseDocumentArray) { return Constructor.cast(value, this, undefined, undefined, index); } return new Constructor(value, this, undefined, undefined, index); } /** * Searches array items for the first document with a matching _id. * * ####Example: * * const embeddedDoc = m.array.id(some_id); * * @return {EmbeddedDocument|null} the subdocument or null if not found. * @param {ObjectId|String|Number|Buffer} id * @TODO cast to the _id based on schema for proper comparison * @method id * @api public * @receiver MongooseDocumentArray */ id(id) { let casted; let sid; let _id; try { casted = castObjectId(id).toString(); } catch (e) { casted = null; } for (const val of this) { if (!val) { continue; } _id = val.get('_id'); if (_id === null || typeof _id === 'undefined') { continue; } else if (_id instanceof Document) { sid || (sid = String(id)); if (sid == _id._id) { return val; } } else if (!(id instanceof ObjectId) && !(_id instanceof ObjectId)) { if (id == _id || utils.deepEqual(id, _id)) { return val; } } else if (casted == _id) { return val; } } return null; } /** * Returns a native js Array of plain js objects * * ####NOTE: * * _Each sub-document is converted to a plain object by calling its `#toObject` method._ * * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion * @return {Array} * @method toObject * @api public * @receiver MongooseDocumentArray */ toObject(options) { // `[].concat` coerces the return value into a vanilla JS array, rather // than a Mongoose array. return [].concat(this.map(function(doc) { if (doc == null) { return null; } if (typeof doc.toObject !== 'function') { return doc; } return doc.toObject(options); })); } slice() { const arr = super.slice.apply(this, arguments); arr[arrayParentSymbol] = this[arrayParentSymbol]; arr[arrayPathSymbol] = this[arrayPathSymbol]; return arr; } /** * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. * * @param {Object} [args...] * @api public * @method push * @memberOf MongooseDocumentArray */ push() { const ret = super.push.apply(this, arguments); _updateParentPopulated(this); return ret; } /** * Pulls items from the array atomically. * * @param {Object} [args...] * @api public * @method pull * @memberOf MongooseDocumentArray */ pull() { const ret = super.pull.apply(this, arguments); _updateParentPopulated(this); return ret; } /** * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. */ shift() { const ret = super.shift.apply(this, arguments); _updateParentPopulated(this); return ret; } /** * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. */ splice() { const ret = super.splice.apply(this, arguments); _updateParentPopulated(this); return ret; } /** * Helper for console.log * * @method inspect * @api public * @receiver MongooseDocumentArray */ inspect() { return this.toObject(); } /** * Creates a subdocument casted to this schema. * * This is the same subdocument constructor used for casting. * * @param {Object} obj the value to cast to this arrays SubDocument schema * @method create * @api public * @receiver MongooseDocumentArray */ create(obj) { let Constructor = this[arraySchemaSymbol].casterConstructor; if (obj && Constructor.discriminators && Constructor.schema && Constructor.schema.options && Constructor.schema.options.discriminatorKey) { if (typeof obj[Constructor.schema.options.discriminatorKey] === 'string' && Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]) { Constructor = Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]; } else { const constructorByValue = getDiscriminatorByValue(Constructor, obj[Constructor.schema.options.discriminatorKey]); if (constructorByValue) { Constructor = constructorByValue; } } } return new Constructor(obj, this); } /*! * ignore */ notify(event) { const _this = this; return function notify(val, _arr) { _arr = _arr || _this; let i = _arr.length; while (i--) { if (_arr[i] == null) { continue; } switch (event) { // only swap for save event for now, we may change this to all event types later case 'save': val = _this[i]; break; default: // NO-OP break; } if (_arr[i].isMongooseArray) { notify(val, _arr[i]); } else if (_arr[i]) { _arr[i].emit(event, val); } } }; } _markModified(elem, embeddedPath) { const parent = this[arrayParentSymbol]; let dirtyPath; if (parent) { dirtyPath = this[arrayPathSymbol]; if (arguments.length) { if (embeddedPath != null) { // an embedded doc bubbled up the change const index = elem.__index; dirtyPath = dirtyPath + '.' + index + '.' + embeddedPath; } else { // directly set an index dirtyPath = dirtyPath + '.' + elem; } } if (dirtyPath != null && dirtyPath.endsWith('.$')) { return this; } parent.markModified(dirtyPath, arguments.length > 0 ? elem : parent); } return this; } } if (util.inspect.custom) { CoreDocumentArray.prototype[util.inspect.custom] = CoreDocumentArray.prototype.inspect; } /*! * 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) { const parent = arr[arrayParentSymbol]; if (!parent || parent.$__.populated == null) return; const populatedPaths = Object.keys(parent.$__.populated). filter(p => p.startsWith(arr[arrayPathSymbol] + '.')); for (const path of populatedPaths) { const remnant = path.slice((arr[arrayPathSymbol] + '.').length); if (!Array.isArray(parent.$__.populated[path].value)) { continue; } parent.$__.populated[path].value = arr.map(val => val.populated(remnant)); } } /** * DocumentArray constructor * * @param {Array} values * @param {String} path the path to this array * @param {Document} doc parent document * @api private * @return {MongooseDocumentArray} * @inherits MongooseArray * @see http://bit.ly/f6CnZU */ function MongooseDocumentArray(values, path, doc) { // TODO: replace this with `new CoreDocumentArray().concat()` when we remove // support for node 4.x and 5.x, see https://i.imgur.com/UAAHk4S.png const arr = new CoreDocumentArray(); arr[arrayAtomicsSymbol] = {}; arr[arraySchemaSymbol] = void 0; if (Array.isArray(values)) { if (values[arrayPathSymbol] === path && values[arrayParentSymbol] === doc) { arr[arrayAtomicsSymbol] = Object.assign({}, values[arrayAtomicsSymbol]); } values.forEach(v => { _basePush.call(arr, v); }); } arr[arrayPathSymbol] = path; // Because doc comes from the context of another function, doc === global // can happen if there was a null somewhere up the chain (see #3020 && #3034) // RB Jun 17, 2015 updated to check for presence of expected paths instead // to make more proof against unusual node environments if (doc && doc instanceof Document) { arr[arrayParentSymbol] = doc; arr[arraySchemaSymbol] = doc.schema.path(path); // `schema.path()` doesn't drill into nested arrays properly yet, see // gh-6398, gh-6602. This is a workaround because nested arrays are // always plain non-document arrays, so once you get to a document array // nesting is done. Matryoshka code. while (arr != null && arr[arraySchemaSymbol] != null && arr[arraySchemaSymbol].$isMongooseArray && !arr[arraySchemaSymbol].$isMongooseDocumentArray) { arr[arraySchemaSymbol] = arr[arraySchemaSymbol].casterConstructor; } } return arr; } /*! * Module exports. */ module.exports = MongooseDocumentArray; }).call(this)}).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":179,"../cast/objectid":192,"../document":194,"../helpers/discriminator/getDiscriminatorByValue":223,"../helpers/symbols":252,"../options":257,"../utils":307,"./core_array":299,"./objectid":305,"util":332}],302:[function(require,module,exports){ /* eslint no-func-assign: 1 */ /*! * Module dependencies. */ 'use strict'; const Document = require('../document_provider')(); const EventEmitter = require('events').EventEmitter; const ValidationError = require('../error/validation'); const immediate = require('../helpers/immediate'); const internalToObjectOptions = require('../options').internalToObjectOptions; const get = require('../helpers/get'); const promiseOrCallback = require('../helpers/promiseOrCallback'); const util = require('util'); const documentArrayParent = require('../helpers/symbols').documentArrayParent; const validatorErrorSymbol = require('../helpers/symbols').validatorErrorSymbol; /** * EmbeddedDocument constructor. * * @param {Object} obj js object returned from the db * @param {MongooseDocumentArray} parentArr the parent array of this document * @param {Boolean} skipId * @inherits Document * @api private */ function EmbeddedDocument(obj, parentArr, skipId, fields, index) { const options = {}; if (parentArr != null && parentArr.isMongooseDocumentArray) { this.__parentArray = parentArr; this[documentArrayParent] = parentArr.$parent(); } else { this.__parentArray = undefined; this[documentArrayParent] = undefined; } this.$setIndex(index); this.$isDocumentArrayElement = true; if (this[documentArrayParent] != null) { options.defaults = this[documentArrayParent].$__.$options.defaults; } Document.call(this, obj, fields, skipId, options); const _this = this; this.on('isNew', function(val) { _this.isNew = val; }); _this.on('save', function() { _this.constructor.emit('save', _this); }); } /*! * Inherit from Document */ EmbeddedDocument.prototype = Object.create(Document.prototype); EmbeddedDocument.prototype.constructor = EmbeddedDocument; for (const i in EventEmitter.prototype) { EmbeddedDocument[i] = EventEmitter.prototype[i]; } EmbeddedDocument.prototype.toBSON = function() { return this.toObject(internalToObjectOptions); }; /*! * ignore */ EmbeddedDocument.prototype.$setIndex = function(index) { this.__index = index; if (get(this, '$__.validationError', null) != null) { const keys = Object.keys(this.$__.validationError.errors); for (const key of keys) { this.invalidate(key, this.$__.validationError.errors[key]); } } }; /** * Marks the embedded doc modified. * * ####Example: * * const doc = blogpost.comments.id(hexstring); * doc.mixed.type = 'changed'; * doc.markModified('mixed.type'); * * @param {String} path the path which changed * @api public * @receiver EmbeddedDocument */ EmbeddedDocument.prototype.markModified = function(path) { this.$__.activePaths.modify(path); if (!this.__parentArray) { return; } const pathToCheck = this.__parentArray.$path() + '.0.' + path; if (this.isNew && this.ownerDocument().$__isSelected(pathToCheck)) { // Mark the WHOLE parent array as modified // if this is a new document (i.e., we are initializing // a document), this.__parentArray._markModified(); } else { this.__parentArray._markModified(this, path); } }; /*! * ignore */ EmbeddedDocument.prototype.populate = function() { throw new Error('Mongoose does not support calling populate() on nested ' + 'docs. Instead of `doc.arr[0].populate("path")`, use ' + '`doc.populate("arr.0.path")`'); }; /** * Used as a stub for [hooks.js](https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3) * * ####NOTE: * * _This is a no-op. Does not actually save the doc to the db._ * * @param {Function} [fn] * @return {Promise} resolved Promise * @api private */ EmbeddedDocument.prototype.save = function(options, fn) { if (typeof options === 'function') { fn = options; options = {}; } options = options || {}; if (!options.suppressWarning) { console.warn('mongoose: calling `save()` on a subdoc does **not** save ' + 'the document to MongoDB, it only runs save middleware. ' + 'Use `subdoc.save({ suppressWarning: true })` to hide this warning ' + 'if you\'re sure this behavior is right for your app.'); } return promiseOrCallback(fn, cb => { this.$__save(cb); }); }; /** * Used as a stub for middleware * * ####NOTE: * * _This is a no-op. Does not actually save the doc to the db._ * * @param {Function} [fn] * @method $__save * @api private */ EmbeddedDocument.prototype.$__save = function(fn) { return immediate(() => fn(null, this)); }; /*! * Registers remove event listeners for triggering * on subdocuments. * * @param {EmbeddedDocument} sub * @api private */ function registerRemoveListener(sub) { let 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); } /*! * no-op for hooks */ EmbeddedDocument.prototype.$__remove = function(cb) { if (cb == null) { return; } return cb(null, this); }; /** * Removes the subdocument from its parent array. * * @param {Object} [options] * @param {Function} [fn] * @api public */ EmbeddedDocument.prototype.remove = function(options, fn) { if (typeof options === 'function' && !fn) { fn = options; options = undefined; } if (!this.__parentArray || (options && options.noop)) { this.$__remove(fn); return this; } let _id; if (!this.willRemove) { _id = this._doc._id; if (!_id) { throw new Error('For your own good, Mongoose does not know ' + 'how to remove an EmbeddedDocument that has no _id'); } this.__parentArray.pull({ _id: _id }); this.willRemove = true; registerRemoveListener(this); } this.$__remove(fn); return this; }; /** * Override #update method of parent documents. * @api private */ EmbeddedDocument.prototype.update = function() { throw new Error('The #update method is not available on EmbeddedDocuments'); }; /** * Helper for console.log * * @api public */ EmbeddedDocument.prototype.inspect = function() { return this.toObject({ transform: false, virtuals: false, flattenDecimals: false }); }; if (util.inspect.custom) { /*! * Avoid Node deprecation warning DEP0079 */ EmbeddedDocument.prototype[util.inspect.custom] = EmbeddedDocument.prototype.inspect; } /** * Marks a path as invalid, causing validation to fail. * * @param {String} path the field to invalidate * @param {String|Error} err error which states the reason `path` was invalid * @return {Boolean} * @api public */ EmbeddedDocument.prototype.invalidate = function(path, err, val) { Document.prototype.invalidate.call(this, path, err, val); if (!this[documentArrayParent] || this.__index == null) { if (err[validatorErrorSymbol] || err instanceof ValidationError) { return this.ownerDocument().$__.validationError; } throw err; } const index = this.__index; const parentPath = this.__parentArray.$path(); const fullPath = [parentPath, index, path].join('.'); this[documentArrayParent].invalidate(fullPath, err, val); return this.ownerDocument().$__.validationError; }; /** * Marks a path as valid, removing existing validation errors. * * @param {String} path the field to mark as valid * @api private * @method $markValid * @receiver EmbeddedDocument */ EmbeddedDocument.prototype.$markValid = function(path) { if (!this[documentArrayParent]) { return; } const index = this.__index; if (typeof index !== 'undefined') { const parentPath = this.__parentArray.$path(); const fullPath = [parentPath, index, path].join('.'); this[documentArrayParent].$markValid(fullPath); } }; /*! * ignore */ EmbeddedDocument.prototype.$ignore = function(path) { Document.prototype.$ignore.call(this, path); if (!this[documentArrayParent]) { return; } const index = this.__index; if (typeof index !== 'undefined') { const parentPath = this.__parentArray.$path(); const fullPath = [parentPath, index, path].join('.'); this[documentArrayParent].$ignore(fullPath); } }; /** * Checks if a path is invalid * * @param {String} path the field to check * @api private * @method $isValid * @receiver EmbeddedDocument */ EmbeddedDocument.prototype.$isValid = function(path) { const index = this.__index; if (typeof index !== 'undefined' && this[documentArrayParent]) { return !this[documentArrayParent].$__.validationError || !this[documentArrayParent].$__.validationError.errors[this.$__fullPath(path)]; } return true; }; /** * Returns the top level document of this sub-document. * * @return {Document} */ EmbeddedDocument.prototype.ownerDocument = function() { if (this.$__.ownerDocument) { return this.$__.ownerDocument; } let parent = this[documentArrayParent]; if (!parent) { return this; } while (parent[documentArrayParent] || parent.$__parent) { parent = parent[documentArrayParent] || parent.$__parent; } this.$__.ownerDocument = parent; return this.$__.ownerDocument; }; /** * Returns the full path to this document. If optional `path` is passed, it is appended to the full path. * * @param {String} [path] * @return {String} * @api private * @method $__fullPath * @memberOf EmbeddedDocument * @instance */ EmbeddedDocument.prototype.$__fullPath = function(path) { if (!this.$__.fullPath) { let parent = this; // eslint-disable-line consistent-this if (!parent[documentArrayParent]) { return path; } const paths = []; while (parent[documentArrayParent] || parent.$__parent) { if (parent[documentArrayParent]) { paths.unshift(parent.__parentArray.$path()); } else { paths.unshift(parent.$basePath); } parent = parent[documentArrayParent] || parent.$__parent; } this.$__.fullPath = paths.join('.'); if (!this.$__.ownerDocument) { // optimization this.$__.ownerDocument = parent; } } return path ? this.$__.fullPath + '.' + path : this.$__.fullPath; }; /** * Returns this sub-documents parent document. * * @api public */ EmbeddedDocument.prototype.parent = function() { return this[documentArrayParent]; }; /** * Returns this sub-documents parent document. * * @api public */ EmbeddedDocument.prototype.$parent = EmbeddedDocument.prototype.parent; /** * Returns this sub-documents parent array. * * @api public */ EmbeddedDocument.prototype.parentArray = function() { return this.__parentArray; }; /*! * Module exports. */ module.exports = EmbeddedDocument; },{"../document_provider":195,"../error/validation":215,"../helpers/get":229,"../helpers/immediate":231,"../helpers/promiseOrCallback":241,"../helpers/symbols":252,"../options":257,"events":177,"util":332}],303:[function(require,module,exports){ /*! * Module exports. */ 'use strict'; exports.Array = require('./array'); exports.Buffer = require('./buffer'); exports.Document = // @deprecate exports.Embedded = require('./embedded'); exports.DocumentArray = require('./documentarray'); exports.Decimal128 = require('./decimal128'); exports.ObjectId = require('./objectid'); exports.Map = require('./map'); exports.Subdocument = require('./subdocument'); },{"./array":297,"./buffer":298,"./decimal128":300,"./documentarray":301,"./embedded":302,"./map":304,"./objectid":305,"./subdocument":306}],304:[function(require,module,exports){ 'use strict'; const Mixed = require('../schema/mixed'); const ObjectId = require('./objectid'); const deepEqual = require('../utils').deepEqual; const get = require('../helpers/get'); const handleSpreadDoc = require('../helpers/document/handleSpreadDoc'); const util = require('util'); const specialProperties = require('../helpers/specialProperties'); const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; /*! * ignore */ class MongooseMap extends Map { constructor(v, path, doc, schemaType) { if (v != null && v.constructor.name === 'Object') { v = Object.keys(v).reduce((arr, key) => arr.concat([[key, v[key]]]), []); } super(v); this.$__parent = doc != null && doc.$__ != null ? doc : null; this.$__path = path; this.$__schemaType = schemaType == null ? new Mixed(path) : schemaType; this.$__runDeferred(); } $init(key, value) { checkValidKey(key); super.set(key, value); if (value != null && value.$isSingleNested) { value.$basePath = this.$__path + '.' + key; } } $__set(key, value) { super.set(key, value); } get(key, options) { if (key instanceof ObjectId) { key = key.toString(); } options = options || {}; if (options.getters === false) { return super.get(key); } return this.$__schemaType.applyGetters(super.get(key), this.$__parent); } set(key, value) { if (key instanceof 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; } const fullPath = this.$__path + '.' + key; const populated = this.$__parent != null && this.$__parent.$__ ? this.$__parent.populated(fullPath) || this.$__parent.populated(this.$__path) : null; const priorVal = this.get(key); if (populated != null) { if (value.$__ == null) { value = new populated.options[populateModelSymbol](value); } value.$__.wasPopulated = true; } else { try { value = this.$__schemaType. applySetters(value, this.$__parent, false, this.get(key), { path: fullPath }); } catch (error) { if (this.$__parent != null && this.$__parent.$__ != null) { this.$__parent.invalidate(fullPath, error); return; } throw error; } } super.set(key, value); if (value != null && value.$isSingleNested) { value.$basePath = this.$__path + '.' + key; } const parent = this.$__parent; if (parent != null && parent.$__ != null && !deepEqual(value, priorVal)) { parent.markModified(this.$__path + '.' + key); } } clear() { super.clear(); const parent = this.$__parent; if (parent != null) { parent.markModified(this.$__path); } } delete(key) { if (key instanceof ObjectId) { key = key.toString(); } this.set(key, undefined); super.delete(key); } toBSON() { return new Map(this); } toObject(options) { if (get(options, 'flattenMaps')) { const ret = {}; const keys = this.keys(); for (const key of keys) { ret[key] = this.get(key); } return ret; } return new Map(this); } toJSON() { const ret = {}; const keys = this.keys(); for (const key of keys) { ret[key] = this.get(key); } return ret; } inspect() { return new Map(this); } $__runDeferred() { if (!this.$__deferred) { return; } for (const keyValueObject of this.$__deferred) { this.set(keyValueObject.key, keyValueObject.value); } this.$__deferred = null; } } if (util.inspect.custom) { Object.defineProperty(MongooseMap.prototype, util.inspect.custom, { enumerable: false, writable: false, configurable: false, value: MongooseMap.prototype.inspect }); } Object.defineProperty(MongooseMap.prototype, '$__set', { enumerable: false, writable: true, configurable: false }); Object.defineProperty(MongooseMap.prototype, '$__parent', { enumerable: false, writable: true, configurable: false }); Object.defineProperty(MongooseMap.prototype, '$__path', { enumerable: false, writable: true, configurable: false }); Object.defineProperty(MongooseMap.prototype, '$__schemaType', { enumerable: false, writable: true, configurable: false }); Object.defineProperty(MongooseMap.prototype, '$isMongooseMap', { enumerable: false, writable: false, configurable: false, value: true }); Object.defineProperty(MongooseMap.prototype, '$__deferredCalls', { enumerable: false, writable: false, configurable: false, value: true }); /*! * Since maps are stored as objects under the hood, keys must be strings * and can't contain any invalid characters */ function checkValidKey(key) { const keyType = typeof key; if (keyType !== 'string') { throw new TypeError(`Mongoose maps only support string keys, got ${keyType}`); } if (key.startsWith('$')) { throw new Error(`Mongoose maps do not support keys that start with "$", got "${key}"`); } if (key.includes('.')) { throw new Error(`Mongoose maps do not support keys that contain ".", got "${key}"`); } if (specialProperties.has(key)) { throw new Error(`Mongoose maps do not support reserved key name "${key}"`); } } module.exports = MongooseMap; },{"../helpers/document/handleSpreadDoc":228,"../helpers/get":229,"../helpers/specialProperties":251,"../helpers/symbols":252,"../schema/mixed":284,"../utils":307,"./objectid":305,"util":332}],305:[function(require,module,exports){ /** * ObjectId type constructor * * ####Example * * const id = new mongoose.Types.ObjectId; * * @constructor ObjectId */ 'use strict'; const ObjectId = require('../driver').get().ObjectId; const objectIdSymbol = require('../helpers/symbols').objectIdSymbol; /*! * Getter for convenience with populate, see gh-6115 */ Object.defineProperty(ObjectId.prototype, '_id', { enumerable: false, configurable: true, get: function() { return this; } }); ObjectId.prototype[objectIdSymbol] = true; module.exports = ObjectId; },{"../driver":196,"../helpers/symbols":252}],306:[function(require,module,exports){ 'use strict'; const Document = require('../document'); const immediate = require('../helpers/immediate'); const internalToObjectOptions = require('../options').internalToObjectOptions; const promiseOrCallback = require('../helpers/promiseOrCallback'); const documentArrayParent = require('../helpers/symbols').documentArrayParent; module.exports = Subdocument; /** * Subdocument constructor. * * @inherits Document * @api private */ function Subdocument(value, fields, parent, skipId, options) { this.$isSingleNested = true; if (options != null && options.path != null) { this.$basePath = options.path; } const hasPriorDoc = options != null && options.priorDoc; let initedPaths = null; if (hasPriorDoc) { this._doc = Object.assign({}, options.priorDoc._doc); delete this._doc[this.schema.options.discriminatorKey]; initedPaths = Object.keys(options.priorDoc._doc || {}). filter(key => key !== this.schema.options.discriminatorKey); } if (parent != null) { // If setting a nested path, should copy isNew from parent re: gh-7048 options = Object.assign({}, options, { isNew: parent.isNew, defaults: parent.$__.$options.defaults }); } Document.call(this, value, fields, skipId, options); if (hasPriorDoc) { for (const key of initedPaths) { if (!this.$__.activePaths.states.modify[key] && !this.$__.activePaths.states.default[key] && !this.$__.$setCalled.has(key)) { const schematype = this.schema.path(key); const def = schematype == null ? void 0 : schematype.getDefault(this); if (def === void 0) { delete this._doc[key]; } else { this._doc[key] = def; this.$__.activePaths.default(key); } } } delete options.priorDoc; delete this.$__.$options.priorDoc; } } Subdocument.prototype = Object.create(Document.prototype); 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) { if (typeof options === 'function') { fn = options; options = {}; } options = options || {}; if (!options.suppressWarning) { console.warn('mongoose: calling `save()` on a subdoc does **not** save ' + 'the document to MongoDB, it only runs save middleware. ' + 'Use `subdoc.save({ suppressWarning: true })` to hide this warning ' + 'if you\'re sure this behavior is right for your app.'); } return promiseOrCallback(fn, cb => { this.$__save(cb); }); }; /** * Used as a stub for middleware * * ####NOTE: * * _This is a no-op. Does not actually save the doc to the db._ * * @param {Function} [fn] * @method $__save * @api private */ Subdocument.prototype.$__save = function(fn) { return immediate(() => fn(null, this)); }; Subdocument.prototype.$isValid = function(path) { if (this.$__parent && this.$basePath) { return this.$__parent.$isValid([this.$basePath, path].join('.')); } return Document.prototype.$isValid.call(this, path); }; Subdocument.prototype.markModified = function(path) { Document.prototype.markModified.call(this, path); if (this.$__parent && this.$basePath) { if (this.$__parent.isDirectModified(this.$basePath)) { return; } this.$__parent.markModified([this.$basePath, path].join('.'), this); } }; Subdocument.prototype.isModified = function(paths, modifiedPaths) { if (this.$__parent && this.$basePath) { if (Array.isArray(paths) || typeof paths === 'string') { paths = (Array.isArray(paths) ? paths : paths.split(' ')); paths = paths.map(p => [this.$basePath, p].join('.')); return this.$__parent.isModified(paths, modifiedPaths); } return this.$__parent.isModified(this.$basePath); } 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); if (this.$__parent && this.$basePath) { this.$__parent.$markValid([this.$basePath, path].join('.')); } }; /*! * ignore */ Subdocument.prototype.invalidate = function(path, err, val) { // Hack: array subdocuments' validationError is equal to the owner doc's, // so validating an array subdoc gives the top-level doc back. Temporary // workaround for #5208 so we don't have circular errors. if (err !== this.ownerDocument().$__.validationError) { Document.prototype.invalidate.call(this, path, err, val); } if (this.$__parent && this.$basePath) { this.$__parent.invalidate([this.$basePath, path].join('.'), err, val); } else if (err.kind === 'cast' || err.name === 'CastError') { throw err; } return this.ownerDocument().$__.validationError; }; /*! * ignore */ Subdocument.prototype.$ignore = function(path) { Document.prototype.$ignore.call(this, path); if (this.$__parent && this.$basePath) { this.$__parent.$ignore([this.$basePath, path].join('.')); } }; /** * Returns the top level document of this sub-document. * * @return {Document} */ Subdocument.prototype.ownerDocument = function() { if (this.$__.ownerDocument) { return this.$__.ownerDocument; } let parent = this.$__parent; if (!parent) { return this; } while (parent.$__parent || parent[documentArrayParent]) { parent = parent.$__parent || parent[documentArrayParent]; } this.$__.ownerDocument = parent; return this.$__.ownerDocument; }; /** * Returns this sub-documents parent document. * * @api public */ Subdocument.prototype.parent = function() { return this.$__parent; }; /** * Returns this sub-documents parent document. * * @api public */ Subdocument.prototype.$parent = Subdocument.prototype.parent; /*! * no-op for hooks */ Subdocument.prototype.$__remove = function(cb) { return cb(null, this); }; /** * 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.$__parent.set(this.$basePath, null); } if (typeof callback === 'function') { callback(null); } }; /*! * 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")`'); }; /*! * Registers remove event listeners for triggering * on subdocuments. * * @param {Subdocument} sub * @api private */ function registerRemoveListener(sub) { let 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); } },{"../document":194,"../helpers/immediate":231,"../helpers/promiseOrCallback":241,"../helpers/symbols":252,"../options":257}],307:[function(require,module,exports){ (function (process){(function (){ 'use strict'; /*! * Module dependencies. */ const ms = require('ms'); const mpath = require('mpath'); const sliced = require('sliced'); const Buffer = require('safe-buffer').Buffer; const Decimal = require('./types/decimal128'); const ObjectId = require('./types/objectid'); const PopulateOptions = require('./options/PopulateOptions'); const clone = require('./helpers/clone'); const isObject = require('./helpers/isObject'); const isBsonType = require('./helpers/isBsonType'); const getFunctionName = require('./helpers/getFunctionName'); const isMongooseObject = require('./helpers/isMongooseObject'); const promiseOrCallback = require('./helpers/promiseOrCallback'); const specialProperties = require('./helpers/specialProperties'); let Document; exports.specialProperties = specialProperties; /*! * Produces a collection name from model `name`. By default, just returns * the model name * * @param {String} name a model name * @param {Function} pluralize function that pluralizes the collection name * @return {String} a collection name * @api private */ exports.toCollectionName = function(name, pluralize) { if (name === 'system.profile') { return name; } if (name === 'system.indexes') { return name; } if (typeof pluralize === 'function') { return pluralize(name); } return name; }; /*! * 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; } if (a == null || b == null) { return false; } if (a.prototype !== b.prototype) { return false; } if (a instanceof Map && b instanceof Map) { return deepEqual(Array.from(a.keys()), Array.from(b.keys())) && deepEqual(Array.from(a.values()), Array.from(b.values())); } // Handle MongooseNumbers if (a instanceof Number && b instanceof Number) { return a.valueOf() === b.valueOf(); } if (Buffer.isBuffer(a)) { return exports.buffer.areEqual(a, b); } if (Array.isArray(a) && Array.isArray(b)) { const len = a.length; if (len !== b.length) { return false; } for (let i = 0; i < len; ++i) { if (!deepEqual(a[i], b[i])) { return false; } } return true; } if (a.$__ != null) { a = a._doc; } else if (isMongooseObject(a)) { a = a.toObject(); } if (b.$__ != null) { b = b._doc; } else if (isMongooseObject(b)) { b = b.toObject(); } const ka = Object.keys(a); const kb = Object.keys(b); const kaLength = ka.length; // having the same number of owned properties (keys incorporates // hasOwnProperty) if (kaLength !== kb.length) { return false; } // the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); // ~~~cheap key test for (let 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 (const key of ka) { 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.omit = function omit(obj, keys) { if (keys == null) { return Object.assign({}, obj); } if (!Array.isArray(keys)) { keys = [keys]; } const ret = Object.assign({}, obj); for (const key of keys) { delete ret[key]; } 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) { const keys = Object.keys(defaults); let i = keys.length; let k; options = options || {}; while (i--) { k = keys[i]; if (!(k in options)) { options[k] = defaults[k]; } } return options; }; /*! * Generates a random string * * @api private */ exports.random = function() { return Math.random().toString().substr(3); }; /*! * 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 || {}; const keys = Object.keys(from); let i = 0; const len = keys.length; let key; path = path || ''; const omitNested = options.omitNested || {}; while (i < len) { key = keys[i++]; if (options.omit && options.omit[key]) { continue; } if (omitNested[path]) { continue; } if (specialProperties.has(key)) { continue; } if (to[key] == null) { to[key] = from[key]; } else if (exports.isObject(from[key])) { if (!exports.isObject(to[key])) { to[key] = {}; } if (from[key] != null) { // Skip merging schemas if we're creating a discriminator schema and // base schema has a given path as a single nested but discriminator schema // has the path as a document array, or vice versa (gh-9534) if (options.isDiscriminatorSchemaMerge && (from[key].$isSingleNested && to[key].$isMongooseDocumentArray) || (from[key].$isMongooseDocumentArray && to[key].$isSingleNested)) { continue; } else if (from[key].instanceOfSchema) { if (to[key].instanceOfSchema) { to[key].add(from[key].clone()); } else { to[key] = from[key].clone(); } continue; } else if (from[key] instanceof ObjectId) { to[key] = new ObjectId(from[key]); continue; } } merge(to[key], from[key], options, path ? path + '.' + key : key); } else if (options.overwrite) { to[key] = from[key]; } } }; /*! * Applies toObject recursively. * * @param {Document|Array|Object} obj * @return {Object} * @api private */ exports.toObject = function toObject(obj) { Document || (Document = require('./document')); let ret; if (obj == null) { return obj; } if (obj instanceof Document) { return obj.toObject(); } if (Array.isArray(obj)) { ret = []; for (const doc of obj) { ret.push(toObject(doc)); } return ret; } if (exports.isPOJO(obj)) { ret = {}; for (const k of Object.keys(obj)) { 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; } const proto = Object.getPrototypeOf(arg); // Prototype may be null if you used `Object.create(null)` // Checking `proto`'s constructor is safe because `getPrototypeOf()` // explicitly crosses the boundary from object data to object metadata return !proto || proto.constructor.name === 'Object'; }; /*! * Determines if `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) { const props = Object.keys(obj); for (const prop of props) { if (prop === key) { return true; } if (exports.isPOJO(obj[prop]) && exports.hasKey(obj[prop], key)) { return true; } } return false; }; /*! * A faster Array.prototype.slice.call(arguments) alternative * @api private */ exports.args = sliced; /*! * process.nextTick helper. * * Wraps `callback` in a try/catch + nextTick. * * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback. * * @param {Function} callback * @api private */ exports.tick = function tick(callback) { if (typeof callback !== 'function') { return; } return function() { try { callback.apply(this, arguments); } catch (err) { // only nextTick on err to get out of // the event loop and avoid state corruption. process.nextTick(function() { throw err; }); } }; }; /*! * Returns true if `v` is an object that can be serialized as a primitive in * MongoDB */ exports.isMongooseType = function(v) { return v instanceof ObjectId || v instanceof Decimal || 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; } let when; if (typeof object.expires !== 'string') { when = object.expires; } else { when = Math.round(ms(object.expires) / 1000); } object.expireAfterSeconds = when; 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 let obj = null; if (arguments.length === 1) { if (path instanceof PopulateOptions) { return [path]; } if (Array.isArray(path)) { const singles = makeSingles(path); return singles.map(o => exports.populate(o)[0]); } if (exports.isObject(path)) { obj = Object.assign({}, path); } else { obj = { path: path }; } } else if (typeof model === 'object') { obj = { path: path, select: select, match: model, options: match }; } else { obj = { path: path, select: select, model: model, match: match, options: options, populate: subPopulate, justOne: justOne, count: count }; } 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) { const ret = []; arr.forEach(function(obj) { if (/[\s]/.test(obj.path)) { const paths = obj.path.split(' '); paths.forEach(function(p) { const copy = Object.assign({}, obj); copy.path = p; ret.push(copy); }); } else { ret.push(obj); } }); return ret; } }; function _populateObj(obj) { if (Array.isArray(obj.populate)) { const ret = []; obj.populate.forEach(function(obj) { if (/[\s]/.test(obj.path)) { const copy = Object.assign({}, obj); const paths = copy.path.split(' '); paths.forEach(function(p) { copy.path = p; ret.push(exports.populate(copy)[0]); }); } else { ret.push(exports.populate(obj)[0]); } }); obj.populate = exports.populate(ret); } else if (obj.populate != null && typeof obj.populate === 'object') { obj.populate = exports.populate(obj.populate); } const ret = []; const paths = obj.path.split(' '); if (obj.options != null) { obj.options = exports.clone(obj.options); } for (const path of paths) { ret.push(new PopulateOptions(Object.assign({}, obj, { path: path }))); } return ret; } /*! * Return the value of `obj` at the given `path`. * * @param {String} path * @param {Object} obj */ 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) { const keys = Object.keys(o); let i = keys.length; const 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 */ const hop = Object.prototype.hasOwnProperty; exports.object.hasOwnProperty = function(obj, prop) { return hop.call(obj, prop); }; /*! * Determine if `val` is null or undefined * * @return {Boolean} */ 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 */ const _hasOwnProperty = Object.prototype.hasOwnProperty; exports.hasUserDefinedProperty = function(obj, key) { if (obj == null) { return false; } if (Array.isArray(key)) { for (const k of key) { if (exports.hasUserDefinedProperty(obj, k)) { return true; } } return false; } if (_hasOwnProperty.call(obj, key)) { return true; } if (typeof obj === 'object' && key in obj) { const v = obj[key]; return v !== Object.prototype[key] && v !== Array.prototype[key]; } return false; }; /*! * ignore */ const 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) { const primitives = {}; const ids = {}; const ret = []; for (const item of arr) { if (typeof item === 'number' || typeof item === 'string' || item == null) { if (primitives[item]) { continue; } ret.push(item); primitives[item] = true; } else if (item instanceof ObjectId) { if (ids[item.toString()]) { continue; } ret.push(item); ids[item.toString()] = true; } else { ret.push(item); } } 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 (let i = 0, len = a.length; i < len; ++i) { if (a[i] !== b[i]) { return false; } } return true; }; exports.getFunctionName = getFunctionName; /*! * Decorate buffers */ exports.decorate = function(destination, source) { for (const key in source) { if (specialProperties.has(key)) { continue; } destination[key] = source[key]; } }; /** * merges to with a copy of from * * @param {Object} to * @param {Object} fromObj * @api private */ exports.mergeClone = function(to, fromObj) { if (isMongooseObject(fromObj)) { fromObj = fromObj.toObject({ transform: false, virtuals: false, depopulate: true, getters: false, flattenDecimals: false }); } const keys = Object.keys(fromObj); const len = keys.length; let i = 0; let key; while (i < len) { key = keys[i++]; if (specialProperties.has(key)) { continue; } if (typeof to[key] === 'undefined') { to[key] = exports.clone(fromObj[key], { transform: false, virtuals: false, depopulate: true, getters: false, flattenDecimals: false }); } else { let val = fromObj[key]; if (val != null && val.valueOf && !(val instanceof Date)) { val = val.valueOf(); } if (exports.isObject(val)) { let obj = val; if (isMongooseObject(val) && !val.isMongooseBuffer) { obj = obj.toObject({ transform: false, virtuals: false, depopulate: true, getters: false, flattenDecimals: false }); } 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) { for (const item of arr) { fn(item); } }; /*! * ignore */ exports.getOption = function(name) { const sources = Array.prototype.slice.call(arguments, 1); for (const source of sources) { if (source[name] != null) { return source[name]; } } return null; }; /*! * ignore */ exports.noop = function() {}; }).call(this)}).call(this,require('_process')) },{"./document":194,"./helpers/clone":219,"./helpers/getFunctionName":230,"./helpers/isBsonType":232,"./helpers/isMongooseObject":233,"./helpers/isObject":234,"./helpers/promiseOrCallback":241,"./helpers/specialProperties":251,"./options/PopulateOptions":258,"./types/decimal128":300,"./types/objectid":305,"_process":325,"mpath":310,"ms":309,"safe-buffer":327,"sliced":328}],308:[function(require,module,exports){ 'use strict'; const utils = require('./utils'); /** * VirtualType constructor * * This is what mongoose uses to define virtual attributes via `Schema.prototype.virtual`. * * ####Example: * * const fullname = schema.virtual('fullname'); * fullname instanceof mongoose.VirtualType // true * * @param {Object} options * @param {string|function} [options.ref] if `ref` is not nullish, this becomes a [populated virtual](/docs/populate.html#populate-virtuals) * @param {string|function} [options.localField] the local field to populate on if this is a populated virtual. * @param {string|function} [options.foreignField] the foreign field to populate on if this is a populated virtual. * @param {boolean} [options.justOne=false] by default, a populated virtual is an array. If you set `justOne`, the populated virtual will be a single doc or `null`. * @param {boolean} [options.getters=false] if you set this to `true`, Mongoose will call any custom getters you defined on this virtual * @param {boolean} [options.count=false] if you set this to `true`, `populate()` will set this virtual to the number of populated documents, as opposed to the documents themselves, using [`Query#countDocuments()`](./api.html#query_Query-countDocuments) * @param {Object|Function} [options.match=null] add an extra match condition to `populate()` * @param {Number} [options.limit=null] add a default `limit` to the `populate()` query * @param {Number} [options.skip=null] add a default `skip` to the `populate()` query * @param {Number} [options.perDocumentLimit=null] For legacy reasons, `limit` with `populate()` may give incorrect results because it only executes a single query for every document being populated. If you set `perDocumentLimit`, Mongoose will ensure correct `limit` per document by executing a separate query for each document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })` will execute 2 additional queries if `.find()` returns 2 documents. * @param {Object} [options.options=null] Additional options like `limit` and `lean`. * @api public */ function VirtualType(options, name) { this.path = name; this.getters = []; this.setters = []; this.options = Object.assign({}, options); } /** * If no getters/getters, add a default * * @param {Function} fn * @return {VirtualType} this * @api private */ VirtualType.prototype._applyDefaultGetters = function() { if (this.getters.length > 0 || this.setters.length > 0) { return; } const path = this.path; const internalProperty = '$' + path; this.getters.push(function() { return this[internalProperty]; }); this.setters.push(function(v) { this[internalProperty] = v; }); }; /*! * ignore */ VirtualType.prototype.clone = function() { const 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]; } let v = value; for (let l = this.getters.length - 1; l >= 0; l--) { v = this.getters[l].call(doc, v, this, doc); } 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) { let v = value; for (let l = this.setters.length - 1; l >= 0; l--) { v = this.setters[l].call(doc, v, this, doc); } return v; }; /*! * exports */ module.exports = VirtualType; },{"./utils":307}],309:[function(require,module,exports){ /** * 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' : ''); } },{}],310:[function(require,module,exports){ 'use strict'; module.exports = exports = require('./lib'); },{"./lib":311}],311:[function(require,module,exports){ /* eslint strict:off */ /* eslint no-var: off */ /* eslint no-redeclare: off */ var stringToParts = require('./stringToParts'); // 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 (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 (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; } // 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) { // 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); } } }; /*! * 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; } },{"./stringToParts":312}],312:[function(require,module,exports){ 'use strict'; module.exports = function stringToParts(str) { const result = []; let curPropertyName = ''; let state = 'DEFAULT'; for (let i = 0; i < str.length; ++i) { // Fall back to treating as property name rather than bracket notation if // square brackets contains something other than a number. if (state === 'IN_SQUARE_BRACKETS' && !/\d/.test(str[i]) && str[i] !== ']') { state = 'DEFAULT'; curPropertyName = result[result.length - 1] + '[' + curPropertyName; result.splice(result.length - 1, 1); } 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; }; },{}],313:[function(require,module,exports){ 'use strict'; /** * methods a collection must implement */ var methods = [ 'find', 'findOne', 'update', 'updateMany', 'updateOne', 'replaceOne', 'remove', 'count', 'distinct', 'findAndModify', 'aggregate', 'findStream', 'deleteOne', 'deleteMany' ]; /** * 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'); }; } },{}],314:[function(require,module,exports){ 'use strict'; var env = require('../env'); if ('unknown' == env.type) { throw new Error('Unknown environment'); } module.exports = env.isNode ? require('./node') : env.isMongo ? require('./collection') : require('./collection'); },{"../env":316,"./collection":313,"./node":315}],315:[function(require,module,exports){ 'use strict'; /** * Module dependencies */ var Collection = require('./collection'); var utils = require('../utils'); function NodeCollection(col) { this.collection = col; this.collectionName = col.collectionName; } /** * inherit from collection base class */ utils.inherits(NodeCollection, Collection); /** * find(match, options, function(err, docs)) */ NodeCollection.prototype.find = function(match, options, cb) { this.collection.find(match, options, function(err, cursor) { if (err) return cb(err); try { cursor.toArray(cb); } catch (error) { cb(error); } }); }; /** * findOne(match, options, function(err, doc)) */ NodeCollection.prototype.findOne = function(match, options, cb) { this.collection.findOne(match, options, cb); }; /** * count(match, options, function(err, count)) */ NodeCollection.prototype.count = function(match, options, cb) { this.collection.count(match, options, cb); }; /** * distinct(prop, match, options, function(err, count)) */ NodeCollection.prototype.distinct = function(prop, match, options, cb) { this.collection.distinct(prop, match, options, cb); }; /** * update(match, update, options, function(err[, result])) */ NodeCollection.prototype.update = function(match, update, options, cb) { this.collection.update(match, update, options, cb); }; /** * update(match, update, options, function(err[, result])) */ NodeCollection.prototype.updateMany = function(match, update, options, cb) { this.collection.updateMany(match, update, options, cb); }; /** * update(match, update, options, function(err[, result])) */ NodeCollection.prototype.updateOne = function(match, update, options, cb) { this.collection.updateOne(match, update, options, cb); }; /** * replaceOne(match, update, options, function(err[, result])) */ NodeCollection.prototype.replaceOne = function(match, update, options, cb) { this.collection.replaceOne(match, update, options, cb); }; /** * deleteOne(match, options, function(err[, result]) */ NodeCollection.prototype.deleteOne = function(match, options, cb) { this.collection.deleteOne(match, options, cb); }; /** * deleteMany(match, options, function(err[, result]) */ NodeCollection.prototype.deleteMany = function(match, options, cb) { this.collection.deleteMany(match, options, cb); }; /** * remove(match, options, function(err[, result]) */ NodeCollection.prototype.remove = function(match, options, cb) { this.collection.remove(match, options, cb); }; /** * findAndModify(match, update, options, function(err, doc)) */ NodeCollection.prototype.findAndModify = function(match, update, options, cb) { var sort = Array.isArray(options.sort) ? options.sort : []; this.collection.findAndModify(match, sort, update, options, cb); }; /** * var stream = findStream(match, findOptions, streamOptions) */ NodeCollection.prototype.findStream = function(match, findOptions, streamOptions) { return this.collection.find(match, findOptions).stream(streamOptions); }; /** * var cursor = findCursor(match, findOptions) */ NodeCollection.prototype.findCursor = function(match, findOptions) { return this.collection.find(match, findOptions); }; /** * aggregation(operators..., function(err, doc)) * TODO */ /** * Expose */ module.exports = exports = NodeCollection; },{"../utils":319,"./collection":313}],316:[function(require,module,exports){ (function (process,global,Buffer){(function (){ 'use strict'; exports.isNode = 'undefined' != typeof process && 'object' == typeof module && 'object' == typeof global && 'function' == typeof Buffer && process.argv; exports.isMongo = !exports.isNode && 'function' == typeof printjson && 'function' == typeof ObjectId && 'function' == typeof rs && 'function' == typeof sh; exports.isBrowser = !exports.isNode && !exports.isMongo && 'undefined' != typeof window; exports.type = exports.isNode ? 'node' : exports.isMongo ? 'mongo' : exports.isBrowser ? 'browser' : 'unknown'; }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) },{"_process":325,"buffer":129}],317:[function(require,module,exports){ 'use strict'; /** * Dependencies */ var slice = require('sliced'); var assert = require('assert'); var util = require('util'); var utils = require('./utils'); var debug = require('debug')('mquery'); /* global Map */ /** * 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( ) { return $withinCmd == '$geoWithin'; }, set: function(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), method; for (var i = 0; i < methods.length; ++i) { method = methods[i]; // use methods if exist (safer option manipulation) if ('function' == typeof this[method]) { var args = utils.isArray(options[method]) ? options[method] : [options[method]]; this[method].apply(this, args); } else { this.options[method] = options[method]; } } 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 (!utils.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 (!utils.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 && !utils.isArray(arguments[1])) { this._ensurePath('mod'); val = slice(arguments); path = this._path; } else if (3 === arguments.length) { val = slice(arguments, 1); path = arguments[0]; } else { val = arguments[1]; path = arguments[0]; } 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', [],[],[]) path = arguments[0]; val = slice(arguments, 1); } else { // polygon([],[],[]) this._ensurePath('polygon'); path = this._path; val = slice(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 = slice(arguments); } else { path = arguments[0]; val = arguments[1]; } } else if (3 === arguments.length) { path = arguments[0]; val = slice(arguments, 1); } 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; return this._findAndModify('update', 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; return this._findAndModify('remove', callback); }; /** * _findAndModify * * @param {String} type - either "remove" or "update" * @param {Function} callback * @api private */ Query.prototype._findAndModify = function(type, callback) { assert.equal('function', typeof callback); var options = this._optionsForExec(); var fields; var doc; if ('remove' == type) { options.remove = true; } else { if (!('new' in options)) options.new = true; if (!('upsert' in options)) options.upsert = false; doc = this._updateForExec(); if (!doc) { if (options.upsert) { // still need to do the upsert to empty doc doc = { $set: {} }; } else { return this.findOne(callback); } } } fields = this._fieldsForExec(); if (fields != null) { if (this.$useProjection) { options.projection = this._fieldsForExec(); } else { options.fields = this._fieldsForExec(); } } var conds = this._conditions; debug('findAndModify', this._collection.collectionName, conds, doc, options); callback = this._wrapCallback('findAndModify', callback, { conditions: conds, doc: doc, options: options }); this._collection.findAndModify(conds, doc, options, utils.tick(callback)); return this; }; /** * 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 stream for the given find query. * * @throws Error if operation is not a find * @returns {Stream} Node 0.8 style */ Query.prototype.stream = function(streamOptions) { if ('find' != this.op) throw new Error('stream() is only available for find'); var conds = this._conditions; var options = this._optionsForExec(); if (this.$useProjection) { options.projection = this._fieldsForExec(); } else { options.fields = this._fieldsForExec(); } debug('stream', this._collection.collectionName, conds, options, streamOptions); return this._collection.findStream(conds, options, streamOptions); }; /** * 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), ops = utils.keys(update), i = ops.length, ret = {}; while (i--) { var op = ops[i]; if (this.options.overwrite) { ret[op] = update[op]; continue; } if ('$' !== op[0]) { // fix up $set sugar if (!ret.$set) { if (update.$set) { ret.$set = update.$set; } else { ret.$set = {}; } } ret.$set[op] = update[op]; ops.splice(i, 1); if (!~ops.indexOf('$set')) ops.push('$set'); } else if ('$set' === op) { if (!ret.$set) { ret[op] = update[op]; } } else { ret[op] = update[op]; } } 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 = require('./permissions'); 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 = require('./env'); Query.Collection = require('./collection'); Query.BaseCollection = require('./collection/collection'); Query.Promise = require('bluebird'); module.exports = exports = Query; // TODO // test utils },{"./collection":314,"./collection/collection":313,"./env":316,"./permissions":318,"./utils":319,"assert":103,"bluebird":108,"debug":320,"sliced":328,"util":332}],318:[function(require,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.comment = denied.distinct.maxScan = denied.distinct.snapshot = denied.distinct.hint = denied.distinct.tailable = true; // aggregation integration denied.findOneAndUpdate = denied.findOneAndRemove = function(self) { var keys = Object.keys(denied.findOneAndUpdate); var err; keys.every(function(option) { if (self.options[option]) { err = option; return false; } return true; }); return err; }; denied.findOneAndUpdate.limit = denied.findOneAndUpdate.skip = denied.findOneAndUpdate.batchSize = denied.findOneAndUpdate.maxScan = denied.findOneAndUpdate.snapshot = denied.findOneAndUpdate.hint = denied.findOneAndUpdate.tailable = denied.findOneAndUpdate.comment = true; denied.count = function(self) { if (self._fields && Object.keys(self._fields).length > 0) { return 'field selection and slice'; } var keys = Object.keys(denied.count); var err; keys.every(function(option) { if (self.options[option]) { err = option; return false; } return true; }); return err; }; denied.count.slice = denied.count.batchSize = denied.count.comment = denied.count.maxScan = denied.count.snapshot = denied.count.tailable = true; },{}],319:[function(require,module,exports){ (function (process,setImmediate){(function (){ 'use strict'; /*! * Module dependencies. */ var Buffer = require('safe-buffer').Buffer; var RegExpClone = require('regexp-clone'); 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 RegExpClone(obj); if ('Buffer' === obj.constructor.name) return exports.cloneBuffer(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; var ret = {}; var hasKeys; var val; for (const k of Object.keys(obj)) { // Not technically prototype pollution because this wouldn't merge properties // onto `Object.prototype`, but avoid properties like __proto__ as a precaution. if (specialProperties.indexOf(k) !== -1) { continue; } 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 = []; for (var i = 0, l = arr.length; 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), i = keys.length, key; while (i--) { key = keys[i]; if (specialProperties.indexOf(key) !== -1) { continue; } if ('undefined' === typeof to[key]) { to[key] = from[key]; } else { if (exports.isObject(from[key])) { merge(to[key], from[key]); } else { to[key] = from[key]; } } } }; /** * Same as merge but clones the assigned values. * * @param {Object} to * @param {Object} from * @api private */ exports.mergeClone = function mergeClone(to, from) { var keys = Object.keys(from), i = keys.length, key; while (i--) { key = keys[i]; if ('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); }; /** * Determines if `arg` is an array. * * @param {Object} * @return {Boolean} * @see nodejs utils */ exports.isArray = function(arg) { return Array.isArray(arg) || 'object' == typeof arg && '[object Array]' == exports.toString(arg); }; /** * 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 : process.nextTick; /** * Clones the contents of a buffer. * * @param {Buffer} buff * @return {Buffer} */ exports.cloneBuffer = function(buff) { var dupe = Buffer.alloc(buff.length); buff.copy(dupe, 0, 0, buff.length); return dupe; }; /** * 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]'; }; }).call(this)}).call(this,require('_process'),require("timers").setImmediate) },{"_process":325,"regexp-clone":326,"safe-buffer":322,"timers":329}],320:[function(require,module,exports){ (function (process){(function (){ /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = require('./debug'); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { return true; } // 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+)/)); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!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 ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { r = exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * 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 { return window.localStorage; } catch (e) {} } }).call(this)}).call(this,require('_process')) },{"./debug":321,"_process":325}],321:[function(require,module,exports){ /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = require('ms'); /** * Active `debug` instances. */ exports.instances = []; /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ exports.formatters = {}; /** * Select a color. * @param {String} namespace * @return {Number} * @api private */ function selectColor(namespace) { var hash = 0, i; for (i in namespace) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return exports.colors[Math.abs(hash) % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { var prevTime; function debug() { // disabled? if (!debug.enabled) return; var self = debug; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // turn the `arguments` into a proper Array var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // 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 match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting (colors, etc.) exports.formatArgs.call(self, args); var logFn = debug.log || exports.log || console.log.bind(console); logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = exports.enabled(namespace); debug.useColors = exports.useColors(); debug.color = selectColor(namespace); debug.destroy = destroy; // env-specific initialization logic for debug instances if ('function' === typeof exports.init) { exports.init(debug); } exports.instances.push(debug); return debug; } function destroy () { var index = exports.instances.indexOf(this); if (index !== -1) { exports.instances.splice(index, 1); return true; } else { return false; } } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); exports.names = []; exports.skips = []; var i; var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); var len = split.length; for (i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } for (i = 0; i < exports.instances.length; i++) { var instance = exports.instances[i]; instance.enabled = exports.enabled(instance.namespace); } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * 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, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } },{"ms":323}],322:[function(require,module,exports){ /* eslint-disable node/no-deprecated-api */ var buffer = require('buffer') 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) } },{"buffer":129}],323:[function(require,module,exports){ /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd'; } if (ms >= h) { return Math.round(ms / h) + 'h'; } if (ms >= m) { return Math.round(ms / m) + 'm'; } if (ms >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return; } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name; } return Math.ceil(ms / n) + ' ' + name + 's'; } },{}],324:[function(require,module,exports){ /* object-assign (c) Sindre Sorhus @license MIT */ 'use strict'; /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; },{}],325:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],326:[function(require,module,exports){ const toString = Object.prototype.toString; function isRegExp (o) { return 'object' == typeof o && '[object RegExp]' == toString.call(o); } module.exports = exports = function (regexp) { if (!isRegExp(regexp)) { throw new TypeError('Not a RegExp'); } const flags = []; if (regexp.global) flags.push('g'); if (regexp.multiline) flags.push('m'); if (regexp.ignoreCase) flags.push('i'); if (regexp.dotAll) flags.push('s'); if (regexp.unicode) flags.push('u'); if (regexp.sticky) flags.push('y'); const result = new RegExp(regexp.source, flags.join('')); if (typeof regexp.lastIndex === 'number') { result.lastIndex = regexp.lastIndex; } return result; } },{}],327:[function(require,module,exports){ /*! safe-buffer. MIT License. Feross Aboukhadijeh */ /* eslint-disable node/no-deprecated-api */ var buffer = require('buffer') 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) } },{"buffer":129}],328:[function(require,module,exports){ /** * An Array.prototype.slice.call(arguments) alternative * * @param {Object} args something with a length * @param {Number} slice * @param {Number} sliceEnd * @api public */ module.exports = function (args, slice, sliceEnd) { var ret = []; var len = args.length; if (0 === len) return ret; var start = slice < 0 ? Math.max(0, slice + len) : slice || 0; if (sliceEnd !== undefined) { len = sliceEnd < 0 ? sliceEnd + len : sliceEnd } while (len-- > start) { ret[len - start] = args[len]; } return ret; } },{}],329:[function(require,module,exports){ (function (setImmediate,clearImmediate){(function (){ var nextTick = require('process/browser.js').nextTick; var apply = Function.prototype.apply; var slice = Array.prototype.slice; var immediateIds = {}; var nextImmediateId = 0; // DOM APIs, for completeness exports.setTimeout = function() { return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); }; exports.setInterval = function() { return new Timeout(apply.call(setInterval, window, arguments), clearInterval); }; exports.clearTimeout = exports.clearInterval = function(timeout) { timeout.close(); }; function Timeout(id, clearFn) { this._id = id; this._clearFn = clearFn; } Timeout.prototype.unref = Timeout.prototype.ref = function() {}; Timeout.prototype.close = function() { this._clearFn.call(window, this._id); }; // Does not start the time, just sets up the members needed. exports.enroll = function(item, msecs) { clearTimeout(item._idleTimeoutId); item._idleTimeout = msecs; }; exports.unenroll = function(item) { clearTimeout(item._idleTimeoutId); item._idleTimeout = -1; }; exports._unrefActive = exports.active = function(item) { clearTimeout(item._idleTimeoutId); var msecs = item._idleTimeout; if (msecs >= 0) { item._idleTimeoutId = setTimeout(function onTimeout() { if (item._onTimeout) item._onTimeout(); }, msecs); } }; // That's not how node.js implements it but the exposed api is the same. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { var id = nextImmediateId++; var args = arguments.length < 2 ? false : slice.call(arguments, 1); immediateIds[id] = true; nextTick(function onNextTick() { if (immediateIds[id]) { // fn.call() is faster so we optimize for the common use-case // @see http://jsperf.com/call-apply-segu if (args) { fn.apply(null, args); } else { fn.call(null); } // Prevent ids from leaking exports.clearImmediate(id); } }); return id; }; exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { delete immediateIds[id]; }; }).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate) },{"process/browser.js":325,"timers":329}],330:[function(require,module,exports){ arguments[4][104][0].apply(exports,arguments) },{"dup":104}],331:[function(require,module,exports){ arguments[4][105][0].apply(exports,arguments) },{"dup":105}],332:[function(require,module,exports){ arguments[4][106][0].apply(exports,arguments) },{"./support/isBuffer":331,"_process":325,"dup":106,"inherits":330}]},{},[75]);