@medplum/ccda 4.3.6 → 4.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- var Kn=class{constructor(i,e){this.operator=i,this.child=e}toString(){return`${this.operator}(${this.child.toString()})`}},W=class{constructor(i,e,t){this.operator=i,this.left=e,this.right=t}toString(){return`(${this.left.toString()} ${this.operator} ${this.right.toString()})`}},er=class{constructor(){this.prefixParselets={},this.infixParselets={}}registerInfix(i,e){return this.infixParselets[i]=e,this}registerPrefix(i,e){return this.prefixParselets[i]=e,this}prefix(i,e,t){return this.registerPrefix(i,{parse(n,r){let o=n.consumeAndParse(e);return t(r,o)}})}infixLeft(i,e,t){return this.registerInfix(i,{parse(n,r,o){let s=n.consumeAndParse(e);return t(r,o,s)},precedence:e})}construct(i){return new tr(i,this.prefixParselets,this.infixParselets)}},tr=class{constructor(i,e,t){this.tokens=i,this.prefixParselets=e,this.infixParselets=t}hasMore(){return this.tokens.length>0}match(i){return this.peek()?.id!==i?!1:(this.consume(),!0)}consumeAndParse(i=1/0){let e=this.consume(),t=this.prefixParselets[e.id];if(!t)throw Error(`Parse error at "${e.value}" (line ${e.line}, column ${e.column}). No matching prefix parselet.`);let n=t.parse(this,e);for(;i>this.getPrecedence();){let r=this.consume();n=this.getInfixParselet(r).parse(this,n,r)}return n}getPrecedence(){let i=this.peek();if(!i)return 1/0;let e=this.getInfixParselet(i);return e?e.precedence:1/0}consume(i,e){if(!this.tokens.length)throw Error("Cant consume unknown more tokens.");if(i&&this.peek()?.id!==i){let t=this.peek();throw Error(`Expected ${i} but got "${t.id}" (${t.value}) at line ${t.line} column ${t.column}.`)}if(e&&this.peek()?.value!==e){let t=this.peek();throw Error(`Expected "${e}" but got "${t.value}" at line ${t.line} column ${t.column}.`)}return this.tokens.shift()}peek(){return this.tokens.length>0?this.tokens[0]:void 0}removeComments(){this.tokens=this.tokens.filter(i=>i.id!=="Comment")}getInfixParselet(i){return this.infixParselets[i.id==="Symbol"?i.value:i.id]}},ir=class{constructor(i=10){this.max=i,this.cache=new Map}clear(){this.cache.clear()}get(i){let e=this.cache.get(i);return e&&(this.cache.delete(i),this.cache.set(i,e)),e}set(i,e){this.cache.has(i)?this.cache.delete(i):this.cache.size>=this.max&&this.cache.delete(this.first()),this.cache.set(i,e)}delete(i){this.cache.delete(i)}keys(){return this.cache.keys()}first(){return this.cache.keys().next().value}},nt="http://unitsofmeasure.org",ge="http://loinc.org",rt="http://snomed.info/sct",Yt="http://www.nlm.nih.gov/research/umls/rxnorm",Ht="http://www.ama-assn.org/go/cpt";var $t="http://hl7.org/fhir/sid/ndc",_="http://hl7.org",T="http://terminology.hl7.org";var nr="unauthorized";var ye={resourceType:"OperationOutcome",id:nr,issue:[{severity:"error",code:"login",details:{text:"Unauthorized"}}]},Ho={...ye,issue:[...ye.issue,{severity:"error",code:"expired",details:{text:"Token expired"}}]},$o={...ye,issue:[...ye.issue,{severity:"error",code:"invalid",details:{text:"Token not issued for this audience"}}]};function rr(i,e){let t=e.max&&e.max===Number.MAX_SAFE_INTEGER?Number.POSITIVE_INFINITY:e.max;return{path:i,description:"",type:e.type??[],min:e.min??0,max:t??1,isArray:!!t&&t>1,constraints:[]}}function or(i){let e=Object.create(null);for(let[t,n]of Object.entries(i))e[t]={name:t,type:t,path:t,elements:Object.fromEntries(Object.entries(n.elements).map(([r,o])=>[r,rr(r,o)])),constraints:[],innerTypes:[]};return e}var sr={Element:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]}}},BackboneElement:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]}}},Address:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},type:{type:[{code:"code"}]},text:{type:[{code:"string"}]},line:{max:9007199254740991,type:[{code:"string"}]},city:{type:[{code:"string"}]},district:{type:[{code:"string"}]},state:{type:[{code:"string"}]},postalCode:{type:[{code:"string"}]},country:{type:[{code:"string"}]},period:{type:[{code:"Period"}]}}},Age:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Annotation:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},"author[x]":{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Organization"]},{code:"string"}]},time:{type:[{code:"dateTime"}]},text:{min:1,type:[{code:"markdown"}]}}},Attachment:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},contentType:{type:[{code:"code"}]},language:{type:[{code:"code"}]},data:{type:[{code:"base64Binary"}]},url:{type:[{code:"url"}]},size:{type:[{code:"unsignedInt"}]},hash:{type:[{code:"base64Binary"}]},title:{type:[{code:"string"}]},creation:{type:[{code:"dateTime"}]}}},CodeableConcept:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},coding:{max:9007199254740991,type:[{code:"Coding"}]},text:{type:[{code:"string"}]}}},Coding:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},system:{type:[{code:"uri"}]},version:{type:[{code:"string"}]},code:{type:[{code:"code"}]},display:{type:[{code:"string"}]},userSelected:{type:[{code:"boolean"}]}}},ContactDetail:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},name:{type:[{code:"string"}]},telecom:{max:9007199254740991,type:[{code:"ContactPoint"}]}}},ContactPoint:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},system:{type:[{code:"code"}]},value:{type:[{code:"string"}]},use:{type:[{code:"code"}]},rank:{type:[{code:"positiveInt"}]},period:{type:[{code:"Period"}]}}},Contributor:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},name:{min:1,type:[{code:"string"}]},contact:{max:9007199254740991,type:[{code:"ContactDetail"}]}}},Count:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},DataRequirement:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},profile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]},"subject[x]":{type:[{code:"CodeableConcept"},{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Group"]}]},mustSupport:{max:9007199254740991,type:[{code:"string"}]},codeFilter:{max:9007199254740991,type:[{code:"DataRequirementCodeFilter"}]},dateFilter:{max:9007199254740991,type:[{code:"DataRequirementDateFilter"}]},limit:{type:[{code:"positiveInt"}]},sort:{max:9007199254740991,type:[{code:"DataRequirementSort"}]}}},DataRequirementCodeFilter:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},valueSet:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/ValueSet"]}]},code:{max:9007199254740991,type:[{code:"Coding"}]}}},DataRequirementDateFilter:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},"value[x]":{type:[{code:"dateTime"},{code:"Period"},{code:"Duration"}]}}},DataRequirementSort:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},direction:{min:1,type:[{code:"code"}]}}},Distance:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Dosage:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},sequence:{type:[{code:"integer"}]},text:{type:[{code:"string"}]},additionalInstruction:{max:9007199254740991,type:[{code:"CodeableConcept"}]},patientInstruction:{type:[{code:"string"}]},timing:{type:[{code:"Timing"}]},"asNeeded[x]":{type:[{code:"boolean"},{code:"CodeableConcept"}]},site:{type:[{code:"CodeableConcept"}]},route:{type:[{code:"CodeableConcept"}]},method:{type:[{code:"CodeableConcept"}]},doseAndRate:{max:9007199254740991,type:[{code:"DosageDoseAndRate"}]},maxDosePerPeriod:{type:[{code:"Ratio"}]},maxDosePerAdministration:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},maxDosePerLifetime:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},DosageDoseAndRate:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{type:[{code:"CodeableConcept"}]},"dose[x]":{type:[{code:"Range"},{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},"rate[x]":{type:[{code:"Ratio"},{code:"Range"},{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},Duration:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},ElementDefinition:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},representation:{max:9007199254740991,type:[{code:"code"}]},sliceName:{type:[{code:"string"}]},sliceIsConstraining:{type:[{code:"boolean"}]},label:{type:[{code:"string"}]},code:{max:9007199254740991,type:[{code:"Coding"}]},slicing:{type:[{code:"ElementDefinitionSlicing"}]},short:{type:[{code:"string"}]},definition:{type:[{code:"markdown"}]},comment:{type:[{code:"markdown"}]},requirements:{type:[{code:"markdown"}]},alias:{max:9007199254740991,type:[{code:"string"}]},min:{type:[{code:"unsignedInt"}]},max:{type:[{code:"string"}]},base:{type:[{code:"ElementDefinitionBase"}]},contentReference:{type:[{code:"uri"}]},type:{max:9007199254740991,type:[{code:"ElementDefinitionType"}]},"defaultValue[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},meaningWhenMissing:{type:[{code:"markdown"}]},orderMeaning:{type:[{code:"string"}]},"fixed[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},"pattern[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},example:{max:9007199254740991,type:[{code:"ElementDefinitionExample"}]},"minValue[x]":{type:[{code:"date"},{code:"dateTime"},{code:"instant"},{code:"time"},{code:"decimal"},{code:"integer"},{code:"positiveInt"},{code:"unsignedInt"},{code:"Quantity"}]},"maxValue[x]":{type:[{code:"date"},{code:"dateTime"},{code:"instant"},{code:"time"},{code:"decimal"},{code:"integer"},{code:"positiveInt"},{code:"unsignedInt"},{code:"Quantity"}]},maxLength:{type:[{code:"integer"}]},condition:{max:9007199254740991,type:[{code:"id"}]},constraint:{max:9007199254740991,type:[{code:"ElementDefinitionConstraint"}]},mustSupport:{type:[{code:"boolean"}]},isModifier:{type:[{code:"boolean"}]},isModifierReason:{type:[{code:"string"}]},isSummary:{type:[{code:"boolean"}]},binding:{type:[{code:"ElementDefinitionBinding"}]},mapping:{max:9007199254740991,type:[{code:"ElementDefinitionMapping"}]}}},ElementDefinitionSlicingDiscriminator:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},path:{min:1,type:[{code:"string"}]}}},ElementDefinitionSlicing:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},discriminator:{max:9007199254740991,type:[{code:"ElementDefinitionSlicingDiscriminator"}]},description:{type:[{code:"string"}]},ordered:{type:[{code:"boolean"}]},rules:{min:1,type:[{code:"code"}]}}},ElementDefinitionBase:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},min:{min:1,type:[{code:"unsignedInt"}]},max:{min:1,type:[{code:"string"}]}}},ElementDefinitionType:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},code:{min:1,type:[{code:"uri"}]},profile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},targetProfile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},aggregation:{max:9007199254740991,type:[{code:"code"}]},versioning:{type:[{code:"code"}]}}},ElementDefinitionExample:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},label:{min:1,type:[{code:"string"}]},"value[x]":{min:1,type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]}}},ElementDefinitionConstraint:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},key:{min:1,type:[{code:"id"}]},requirements:{type:[{code:"string"}]},severity:{min:1,type:[{code:"code"}]},human:{min:1,type:[{code:"string"}]},expression:{type:[{code:"string"}]},xpath:{type:[{code:"string"}]},source:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]}}},ElementDefinitionBinding:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},strength:{min:1,type:[{code:"code"}]},description:{type:[{code:"string"}]},valueSet:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/ValueSet"]}]}}},ElementDefinitionMapping:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},identity:{min:1,type:[{code:"id"}]},language:{type:[{code:"code"}]},map:{min:1,type:[{code:"string"}]},comment:{type:[{code:"string"}]}}},Expression:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},description:{type:[{code:"string"}]},name:{type:[{code:"id"}]},language:{min:1,type:[{code:"code"}]},expression:{type:[{code:"string"}]},reference:{type:[{code:"uri"}]}}},Extension:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},url:{min:1,type:[{code:"uri"}]},"value[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]}}},HumanName:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},text:{type:[{code:"string"}]},family:{type:[{code:"string"}]},given:{max:9007199254740991,type:[{code:"string"}]},prefix:{max:9007199254740991,type:[{code:"string"}]},suffix:{max:9007199254740991,type:[{code:"string"}]},period:{type:[{code:"Period"}]}}},Identifier:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},type:{type:[{code:"CodeableConcept"}]},system:{type:[{code:"uri"}]},value:{type:[{code:"string"}]},period:{type:[{code:"Period"}]},assigner:{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Organization"]}]}}},MarketingStatus:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},country:{min:1,type:[{code:"CodeableConcept"}]},jurisdiction:{type:[{code:"CodeableConcept"}]},status:{min:1,type:[{code:"CodeableConcept"}]},dateRange:{min:1,type:[{code:"Period"}]},restoreDate:{type:[{code:"dateTime"}]}}},Meta:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},versionId:{type:[{code:"id"}]},lastUpdated:{type:[{code:"instant"}]},source:{type:[{code:"uri"}]},profile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]},security:{max:9007199254740991,type:[{code:"Coding"}]},tag:{max:9007199254740991,type:[{code:"Coding"}]},project:{type:[{code:"uri"}]},author:{type:[{code:"Reference"}]},onBehalfOf:{type:[{code:"Reference"}]},account:{type:[{code:"Reference"}]},accounts:{max:9007199254740991,type:[{code:"Reference"}]},compartment:{max:9007199254740991,type:[{code:"Reference"}]}}},Money:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},currency:{type:[{code:"code"}]}}},Narrative:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},status:{min:1,type:[{code:"code"}]},div:{min:1,type:[{code:"xhtml"}]}}},ParameterDefinition:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},name:{type:[{code:"code"}]},use:{min:1,type:[{code:"code"}]},min:{type:[{code:"integer"}]},max:{type:[{code:"string"}]},documentation:{type:[{code:"string"}]},type:{min:1,type:[{code:"code"}]},profile:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]}}},Period:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},start:{type:[{code:"dateTime"}]},end:{type:[{code:"dateTime"}]}}},Population:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},"age[x]":{type:[{code:"Range"},{code:"CodeableConcept"}]},gender:{type:[{code:"CodeableConcept"}]},race:{type:[{code:"CodeableConcept"}]},physiologicalCondition:{type:[{code:"CodeableConcept"}]}}},ProdCharacteristic:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},height:{type:[{code:"Quantity"}]},width:{type:[{code:"Quantity"}]},depth:{type:[{code:"Quantity"}]},weight:{type:[{code:"Quantity"}]},nominalVolume:{type:[{code:"Quantity"}]},externalDiameter:{type:[{code:"Quantity"}]},shape:{type:[{code:"string"}]},color:{max:9007199254740991,type:[{code:"string"}]},imprint:{max:9007199254740991,type:[{code:"string"}]},image:{max:9007199254740991,type:[{code:"Attachment"}]},scoring:{type:[{code:"CodeableConcept"}]}}},ProductShelfLife:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},identifier:{type:[{code:"Identifier"}]},type:{min:1,type:[{code:"CodeableConcept"}]},period:{min:1,type:[{code:"Quantity"}]},specialPrecautionsForStorage:{max:9007199254740991,type:[{code:"CodeableConcept"}]}}},Quantity:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Range:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},low:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},high:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},Ratio:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},numerator:{type:[{code:"Quantity"}]},denominator:{type:[{code:"Quantity"}]}}},Reference:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},reference:{type:[{code:"string"}]},type:{type:[{code:"uri"}]},identifier:{type:[{code:"Identifier"}]},display:{type:[{code:"string"}]}}},RelatedArtifact:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},label:{type:[{code:"string"}]},display:{type:[{code:"string"}]},citation:{type:[{code:"markdown"}]},url:{type:[{code:"url"}]},document:{type:[{code:"Attachment"}]},resource:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/Resource"]}]}}},SampledData:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},origin:{min:1,type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},period:{min:1,type:[{code:"decimal"}]},factor:{type:[{code:"decimal"}]},lowerLimit:{type:[{code:"decimal"}]},upperLimit:{type:[{code:"decimal"}]},dimensions:{min:1,type:[{code:"positiveInt"}]},data:{type:[{code:"string"}]}}},Signature:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,max:9007199254740991,type:[{code:"Coding"}]},when:{min:1,type:[{code:"instant"}]},who:{min:1,type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/PractitionerRole","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/Device","http://hl7.org/fhir/StructureDefinition/Organization"]}]},onBehalfOf:{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/PractitionerRole","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/Device","http://hl7.org/fhir/StructureDefinition/Organization"]}]},targetFormat:{type:[{code:"code"}]},sigFormat:{type:[{code:"code"}]},data:{type:[{code:"base64Binary"}]}}},SubstanceAmount:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},"amount[x]":{type:[{code:"Quantity"},{code:"Range"},{code:"string"}]},amountType:{type:[{code:"CodeableConcept"}]},amountText:{type:[{code:"string"}]},referenceRange:{type:[{code:"SubstanceAmountReferenceRange"}]}}},SubstanceAmountReferenceRange:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},lowLimit:{type:[{code:"Quantity"}]},highLimit:{type:[{code:"Quantity"}]}}},Timing:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},event:{max:9007199254740991,type:[{code:"dateTime"}]},repeat:{type:[{code:"TimingRepeat"}]},code:{type:[{code:"CodeableConcept"}]}}},TimingRepeat:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},"bounds[x]":{type:[{code:"Duration"},{code:"Range"},{code:"Period"}]},count:{type:[{code:"positiveInt"}]},countMax:{type:[{code:"positiveInt"}]},duration:{type:[{code:"decimal"}]},durationMax:{type:[{code:"decimal"}]},durationUnit:{type:[{code:"code"}]},frequency:{type:[{code:"positiveInt"}]},frequencyMax:{type:[{code:"positiveInt"}]},period:{type:[{code:"decimal"}]},periodMax:{type:[{code:"decimal"}]},periodUnit:{type:[{code:"code"}]},dayOfWeek:{max:9007199254740991,type:[{code:"code"}]},timeOfDay:{max:9007199254740991,type:[{code:"time"}]},when:{max:9007199254740991,type:[{code:"code"}]},offset:{type:[{code:"unsignedInt"}]}}},TriggerDefinition:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},name:{type:[{code:"string"}]},"timing[x]":{type:[{code:"Timing"},{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Schedule"]},{code:"date"},{code:"dateTime"}]},data:{max:9007199254740991,type:[{code:"DataRequirement"}]},condition:{type:[{code:"Expression"}]}}},UsageContext:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},code:{min:1,type:[{code:"Coding"}]},"value[x]":{min:1,type:[{code:"CodeableConcept"},{code:"Quantity"},{code:"Range"},{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/PlanDefinition","http://hl7.org/fhir/StructureDefinition/ResearchStudy","http://hl7.org/fhir/StructureDefinition/InsurancePlan","http://hl7.org/fhir/StructureDefinition/HealthcareService","http://hl7.org/fhir/StructureDefinition/Group","http://hl7.org/fhir/StructureDefinition/Location","http://hl7.org/fhir/StructureDefinition/Organization"]}]}}},MoneyQuantity:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},SimpleQuantity:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{max:0,type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},IdentityProvider:{elements:{authorizeUrl:{min:1,type:[{code:"string"}]},tokenUrl:{min:1,type:[{code:"string"}]},tokenAuthMethod:{type:[{code:"code"}]},userInfoUrl:{min:1,type:[{code:"string"}]},clientId:{min:1,type:[{code:"string"}]},clientSecret:{min:1,type:[{code:"string"}]},usePkce:{type:[{code:"boolean"}]},useSubject:{type:[{code:"boolean"}]}}}};var ar=or(sr);var Mt=Object.create(null);function cr(i){let e;return e=Mt[i],e||(e=Mt[i]=Object.create(null)),e}function ur(i,e){if(e){let t=cr(e)[i];if(t)return t}return ar[i]}var jo=new ir(1e3);var jt={base64Binary:/^([A-Za-z\d+/]{4})*([A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/,canonical:/^\S*$/,code:/^[^\s]+( [^\s]+)*$/,date:/^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2]\d|3[0-1]))?)?$/,dateTime:/^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2]\d|3[0-1])(T([01]\d|2[0-3])(:[0-5]\d:([0-5]\d|60)(\.\d{1,9})?)?)?)?(Z|[+-]((0\d|1[0-3]):[0-5]\d|14:00)?)?)?$/,id:/^[A-Za-z0-9\-.]{1,64}$/,instant:/^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])T([01]\d|2[0-3]):[0-5]\d:([0-5]\d|60)(\.\d{1,9})?(Z|[+-]((0\d|1[0-3]):[0-5]\d|14:00))$/,markdown:/^[\r\n\t\u0020-\uFFFF]+$/,oid:/^urn:oid:[0-2](\.(0|[1-9]\d*))+$/,string:/^[\r\n\t\u0020-\uFFFF]+$/,time:/^([01]\d|2[0-3]):[0-5]\d:([0-5]\d|60)(\.\d{1,9})?$/,uri:/^\S*$/,url:/^\S*$/,uuid:/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,xhtml:/.*/};function c(i){return[{type:u.boolean,value:i}]}function M(i){return i==null?{type:"undefined",value:void 0}:Number.isSafeInteger(i)?{type:u.integer,value:i}:typeof i=="number"?{type:u.decimal,value:i}:typeof i=="boolean"?{type:u.boolean,value:i}:typeof i=="string"?{type:u.string,value:i}:g(i)?{type:u.Quantity,value:i}:z(i)?{type:i.resourceType,value:i}:Jt(i)?{type:u.CodeableConcept,value:i}:Xt(i)?{type:u.Coding,value:i}:{type:u.BackboneElement,value:i}}function P(i){return i.length===0?!1:!!i[0].value}function b(i,e){if(i.length!==0){if(i.length===1&&(!e||i[0].type===e))return i[0];throw new Error(`Expected singleton of type ${e}, but found ${JSON.stringify(i)}`)}}function dr(i,e,t){if(!i.value)return;let n=br(i.type,e,t?.profileUrl);return n?lr(i,e,n):pr(i,e)}function lr(i,e,t){let n=i.value,r=t.type;if(!r||r.length===0)return;let o,s="undefined",a,h=t.path.lastIndexOf("."),S=t.path.substring(h+1);for(let E of r){let $=S.replace("[x]",Q(E.code));if(o=n[$],a=n["_"+$],o!==void 0||a!==void 0){s=E.code;break}}if(a)if(Array.isArray(o)){o=o.slice();for(let E=0;E<Math.max(o.length,a.length);E++)o[E]=kt(o[E],a[E])}else o=kt(o,a);if(!q(o))return(s==="Element"||s==="BackboneElement")&&(s=t.type[0].code),Array.isArray(o)?o.map(E=>wt(E,s)):wt(o,s)}function wt(i,e){return e==="Resource"&&z(i)&&(e=i.resourceType),{type:e,value:i}}function pr(i,e){let t=i.value;if(!t||typeof t!="object")return;let n;if(e in t){let r=t[e];Array.isArray(r)?n=r.map(M):n=M(r)}else{let r=e.endsWith("[x]")?e.substring(0,e.length-3):e;for(let o of Object.values(u)){let s=r+Q(o);if(s in t){let a=t[s];Array.isArray(a)?n=a.map(h=>({type:o,value:h})):n={type:o,value:a};break}}}if(Array.isArray(n)){if(n.length===0||q(n[0]))return}else if(q(n))return;return n}function qt(i){let e=[];for(let t of i){let n=!1;for(let r of e)if(P(Ae(t,r))){n=!0;break}n||e.push(t)}return e}function hr(i){return c(!P(i))}function fr(i,e){return i.length===0||e.length===0?[]:i.length!==e.length?c(!1):c(i.every((t,n)=>P(Ae(t,e[n]))))}function _r(i,e){return i.length===0||e.length===0?[]:i.length!==e.length?c(!0):c(i.some((t,n)=>!P(Ae(t,e[n]))))}function Ae(i,e){let t=i.value?.valueOf(),n=e.value?.valueOf();return typeof t=="number"&&typeof n=="number"?c(Math.abs(t-n)<1e-8):g(t)&&g(n)?c(zt(t,n)):c(typeof t=="object"&&typeof n=="object"?ot(i,e):t===n)}function Wt(i,e){return i.length===0&&e.length===0?c(!0):i.length!==e.length?c(!1):(i.sort(Bt),e.sort(Bt),c(i.every((t,n)=>P(mr(t,e[n])))))}function mr(i,e){let{type:t,value:n}=i,{type:r,value:o}=e,s=n?.valueOf(),a=o?.valueOf();return typeof s=="number"&&typeof a=="number"?c(Math.abs(s-a)<.01):g(s)&&g(a)?c(zt(s,a)):c(t==="Coding"&&r==="Coding"?typeof s!="object"||typeof a!="object"?!1:s.code===a.code&&s.system===a.system:typeof s=="object"&&typeof a=="object"?ot({...s,id:void 0},{...a,id:void 0}):typeof s=="string"&&typeof a=="string"?s.toLowerCase()===a.toLowerCase():s===a)}function Bt(i,e){let t=i.value?.valueOf(),n=e.value?.valueOf();return typeof t=="number"&&typeof n=="number"?t-n:typeof t=="string"&&typeof n=="string"?t.localeCompare(n):0}function Qt(i,e){let{value:t}=i;if(t==null)return!1;let n=e;switch(n.startsWith("System.")&&(n=n.substring(7)),n.startsWith("FHIR.")&&(n=n.substring(5)),n){case"Boolean":return typeof t=="boolean";case"Decimal":case"Integer":return typeof t=="number";case"Date":return Er(t);case"DateTime":return it(t);case"Time":return typeof t=="string"&&!!/^T\d/.exec(t);case"Period":return Ir(t);case"Quantity":return g(t);default:return i.type===n||typeof t=="object"&&t?.resourceType===n}}function Er(i){return typeof i=="string"&&!!jt.date.exec(i)}function it(i){return typeof i=="string"&&!!jt.dateTime.exec(i)}function Ir(i){return!!(i&&typeof i=="object"&&("start"in i&&it(i.start)||"end"in i&&it(i.end)))}function g(i){return!!(i&&typeof i=="object"&&"value"in i&&typeof i.value=="number")}function zt(i,e){return Math.abs(i.value-e.value)<.01&&(i.unit===e.unit||i.code===e.code||i.unit===e.code||i.code===e.unit)}function ot(i,e){let t=Object.keys(i),n=Object.keys(e);if(t.length!==n.length)return!1;for(let r of t){let o=i[r],s=e[r];if(Ft(o)&&Ft(s)){if(!ot(o,s))return!1}else if(o!==s)return!1}return!0}function Ft(i){return i!==null&&typeof i=="object"}function kt(i,e){if(e){if(typeof e!="object")throw new Error("Primitive extension must be an object");return Tr(i??{},e)}return i}function Tr(i,e){return delete e.__proto__,delete e.constructor,Object.assign(i,e)}function Or(i,e){return z(i,e)&&"id"in i&&typeof i.id=="string"}function f(i){let e=Zt(i)??"undefined/undefined",t=Cr(i);return t===e?{reference:e}:{reference:e,display:t}}function Zt(i){if(Kt(i))return i.reference;if(Or(i))return`${i.resourceType}/${i.id}`}function Sr(i){if(i)return Kt(i)?i.reference.split("/")[1]:i.id}function yr(i){return i.resourceType==="Patient"||i.resourceType==="Practitioner"||i.resourceType==="RelatedPerson"}function Cr(i){if(yr(i)){let e=gr(i);if(e)return e}if(i.resourceType==="Device"){let e=Ar(i);if(e)return e}if(i.resourceType==="MedicationRequest"&&i.medicationCodeableConcept)return Gt(i.medicationCodeableConcept);if(i.resourceType==="Subscription"&&i.criteria)return i.criteria;if(i.resourceType==="User"&&i.email)return i.email;if("name"in i&&i.name&&typeof i.name=="string")return i.name;if("code"in i&&i.code){let e=i.code;if(Array.isArray(e)&&(e=e[0]),Jt(e))return Gt(e);if(Dr(e))return e.text}return Zt(i)??""}function gr(i){let e=i.name;if(e&&e.length>0)return xr(e[0])}function Ar(i){let e=i.deviceName;if(e&&e.length>0)return e[0].name}function Nr(i,e){let t=new Date(i);t.setUTCHours(0,0,0,0);let n=e?new Date(e):new Date;n.setUTCHours(0,0,0,0);let r=t.getUTCFullYear(),o=t.getUTCMonth(),s=t.getUTCDate(),a=n.getUTCFullYear(),h=n.getUTCMonth(),S=n.getUTCDate(),E=a-r;(h<o||h===o&&S<s)&&E--;let $=a*12+h-(r*12+o);S<s&&$--;let Jn=Math.floor((n.getTime()-t.getTime())/(1e3*60*60*24));return{years:E,months:$,days:Jn}}function Ne(i,...e){let t=i;for(let n=0;n<e.length&&t;n++)t=t?.extension?.find(r=>r.url===e[n]);return t}function q(i){if(i==null)return!0;let e=typeof i;return e==="string"||e==="object"?!Rr(i):!1}function Rr(i){if(i==null)return!1;let e=typeof i;return e==="string"&&i!==""||e==="object"&&("length"in i&&i.length>0||Object.keys(i).length>0)}function st(i){return/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i.test(i)}function at(i){return i!==null&&typeof i=="object"}function Xt(i){return at(i)&&"code"in i&&typeof i.code=="string"}function Jt(i){return at(i)&&"coding"in i&&Array.isArray(i.coding)&&i.coding.every(Xt)}function Dr(i){return at(i)&&"text"in i&&typeof i.text=="string"}var vr=[];for(let i=0;i<256;i++)vr.push(i.toString(16).padStart(2,"0"));function Q(i){return i?i.charAt(0).toUpperCase()+i.substring(1):""}function xr(i,e){if(!i)return"";let t=[];if(i.prefix&&e?.prefix!==!1&&t.push(...i.prefix),i.given&&t.push(...i.given),i.family&&t.push(i.family),i.suffix&&e?.suffix!==!1&&t.push(...i.suffix),i.use&&(e?.all||e?.use)&&t.push("["+i.use+"]"),t.length===0){let n=j(i.text);if(n)return n}return t.join(" ").trim()}function Gt(i){return i?j(i.text)||(i.coding?i.coding.map(t=>Pr(t)).join(", "):""):""}function Pr(i,e){let t=j(i?.display);if(t){let n=e?j(i?.code):void 0;return`${t}${n?" ("+n+")":""}`}return j(i?.code)??""}function j(i){return typeof i=="string"?i:void 0}var u={Address:"Address",Age:"Age",Annotation:"Annotation",Attachment:"Attachment",BackboneElement:"BackboneElement",CodeableConcept:"CodeableConcept",Coding:"Coding",ContactDetail:"ContactDetail",ContactPoint:"ContactPoint",Contributor:"Contributor",Count:"Count",DataRequirement:"DataRequirement",Distance:"Distance",Dosage:"Dosage",Duration:"Duration",Expression:"Expression",Extension:"Extension",HumanName:"HumanName",Identifier:"Identifier",MarketingStatus:"MarketingStatus",Meta:"Meta",Money:"Money",Narrative:"Narrative",ParameterDefinition:"ParameterDefinition",Period:"Period",Population:"Population",ProdCharacteristic:"ProdCharacteristic",ProductShelfLife:"ProductShelfLife",Quantity:"Quantity",Range:"Range",Ratio:"Ratio",Reference:"Reference",RelatedArtifact:"RelatedArtifact",SampledData:"SampledData",Signature:"Signature",SubstanceAmount:"SubstanceAmount",SystemString:"http://hl7.org/fhirpath/System.String",Timing:"Timing",TriggerDefinition:"TriggerDefinition",UsageContext:"UsageContext",base64Binary:"base64Binary",boolean:"boolean",canonical:"canonical",code:"code",date:"date",dateTime:"dateTime",decimal:"decimal",id:"id",instant:"instant",integer:"integer",markdown:"markdown",oid:"oid",positiveInt:"positiveInt",string:"string",time:"time",unsignedInt:"unsignedInt",uri:"uri",url:"url",uuid:"uuid"};function br(i,e,t){let n=ur(i,t);if(n)return Lr(n.elements,e)}function Lr(i,e){let t=i[e]??i[e+"[x]"];if(t)return t;for(let n=0;n<e.length;n++){let r=e[n];if(r>="A"&&r<="Z"){let o=e.slice(0,n)+"[x]",s=i[o];if(s)return s}}}function z(i,e){return!(!i||typeof i!="object"||!("resourceType"in i)||e&&i.resourceType!==e)}function Kt(i){return!!(i&&typeof i=="object"&&"reference"in i&&typeof i.reference=="string")}function Se(i){if(i.startsWith("T"))return i+"T00:00:00.000Z".substring(i.length);if(i.length<=10)return i;try{return new Date(i).toISOString()}catch{return i}}var x=()=>[],y={empty:(i,e)=>c(e.length===0||e.every(t=>q(t.value))),hasValue:(i,e)=>c(e.length!==0),exists:(i,e,t)=>c(t?e.filter(n=>P(t.eval(i,[n]))).length>0:e.length>0&&e.every(n=>!q(n.value))),all:(i,e,t)=>c(e.every(n=>P(t.eval(i,[n])))),allTrue:(i,e)=>{for(let t of e)if(!t.value)return c(!1);return c(!0)},anyTrue:(i,e)=>{for(let t of e)if(t.value)return c(!0);return c(!1)},allFalse:(i,e)=>{for(let t of e)if(t.value)return c(!1);return c(!0)},anyFalse:(i,e)=>{for(let t of e)if(!t.value)return c(!0);return c(!1)},subsetOf:(i,e,t)=>{if(e.length===0)return c(!0);let n=t.eval(i,V(i));return n.length===0?c(!1):c(e.every(r=>n.some(o=>o.value===r.value)))},supersetOf:(i,e,t)=>{let n=t.eval(i,V(i));return n.length===0?c(!0):e.length===0?c(!1):c(n.every(r=>e.some(o=>o.value===r.value)))},count:(i,e)=>[{type:u.integer,value:e.length}],distinct:(i,e)=>{let t=[];for(let n of e)t.some(r=>r.value===n.value)||t.push(n);return t},isDistinct:(i,e)=>c(e.length===y.distinct(i,e).length),where:(i,e,t)=>e.filter(n=>P(t.eval(i,[n]))),select:(i,e,t)=>e.map(n=>t.eval({parent:i,variables:{$this:n}},[n])).flat(),repeat:x,ofType:(i,e,t)=>e.filter(n=>n.type===t.name),single:(i,e)=>{if(e.length>1)throw new Error("Expected input length one for single()");return e.length===0?[]:e.slice(0,1)},first:(i,e)=>e.length===0?[]:e.slice(0,1),last:(i,e)=>e.length===0?[]:e.slice(e.length-1,e.length),tail:(i,e)=>e.length===0?[]:e.slice(1,e.length),skip:(i,e,t)=>{let n=t.eval(i,e)[0]?.value;if(typeof n!="number")throw new Error("Expected a number for skip(num)");return n>=e.length?[]:n<=0?e:e.slice(n,e.length)},take:(i,e,t)=>{let n=t.eval(i,e)[0]?.value;if(typeof n!="number")throw new Error("Expected a number for take(num)");return n>=e.length?e:n<=0?[]:e.slice(0,n)},intersect:(i,e,t)=>{if(!t)return e;let n=t.eval(i,V(i)),r=[];for(let o of e)!r.some(s=>s.value===o.value)&&n.some(s=>s.value===o.value)&&r.push(o);return r},exclude:(i,e,t)=>{if(!t)return e;let n=t.eval(i,V(i)),r=[];for(let o of e)n.some(s=>s.value===o.value)||r.push(o);return r},union:(i,e,t)=>{if(!t)return e;let n=t.eval(i,V(i));return qt([...e,...n])},combine:(i,e,t)=>{if(!t)return e;let n=t.eval(i,V(i));return[...e,...n]},htmlChecks:(i,e,t)=>[M(!0)],iif:(i,e,t,n,r)=>{let o=t.eval(i,e);if(o.length>1||o.length===1&&typeof o[0].value!="boolean")throw new Error("Expected criterion to evaluate to a Boolean");return P(o)?n.eval(i,e):r?r.eval(i,e):[]},toBoolean:(i,e)=>{if(e.length===0)return[];let[{value:t}]=v(e,1);if(typeof t=="boolean")return[{type:u.boolean,value:t}];if(typeof t=="number"&&(t===0||t===1))return c(!!t);if(typeof t=="string"){let n=t.toLowerCase();if(["true","t","yes","y","1","1.0"].includes(n))return c(!0);if(["false","f","no","n","0","0.0"].includes(n))return c(!1)}return[]},convertsToBoolean:(i,e)=>e.length===0?[]:c(y.toBoolean(i,e).length===1),toInteger:(i,e)=>{if(e.length===0)return[];let[{value:t}]=v(e,1);return typeof t=="number"?[{type:u.integer,value:t}]:typeof t=="string"&&/^[+-]?\d+$/.exec(t)?[{type:u.integer,value:parseInt(t,10)}]:typeof t=="boolean"?[{type:u.integer,value:t?1:0}]:[]},convertsToInteger:(i,e)=>e.length===0?[]:c(y.toInteger(i,e).length===1),toDate:(i,e)=>{if(e.length===0)return[];let[{value:t}]=v(e,1);return typeof t=="string"&&/^\d{4}(-\d{2}(-\d{2})?)?/.exec(t)?[{type:u.date,value:Se(t)}]:[]},convertsToDate:(i,e)=>e.length===0?[]:c(y.toDate(i,e).length===1),toDateTime:(i,e)=>{if(e.length===0)return[];let[{value:t}]=v(e,1);return typeof t=="string"&&/^\d{4}(-\d{2}(-\d{2})?)?/.exec(t)?[{type:u.dateTime,value:Se(t)}]:[]},convertsToDateTime:(i,e)=>e.length===0?[]:c(y.toDateTime(i,e).length===1),toDecimal:(i,e)=>{if(e.length===0)return[];let[{value:t}]=v(e,1);return typeof t=="number"?[{type:u.decimal,value:t}]:typeof t=="string"&&/^-?\d{1,9}(\.\d{1,9})?$/.exec(t)?[{type:u.decimal,value:parseFloat(t)}]:typeof t=="boolean"?[{type:u.decimal,value:t?1:0}]:[]},convertsToDecimal:(i,e)=>e.length===0?[]:c(y.toDecimal(i,e).length===1),toQuantity:(i,e)=>{if(e.length===0)return[];let[{value:t}]=v(e,1);return g(t)?[{type:u.Quantity,value:t}]:typeof t=="number"?[{type:u.Quantity,value:{value:t,unit:"1"}}]:typeof t=="string"&&/^-?\d{1,9}(\.\d{1,9})?/.exec(t)?[{type:u.Quantity,value:{value:parseFloat(t),unit:"1"}}]:typeof t=="boolean"?[{type:u.Quantity,value:{value:t?1:0,unit:"1"}}]:[]},convertsToQuantity:(i,e)=>e.length===0?[]:c(y.toQuantity(i,e).length===1),toString:(i,e)=>{if(e.length===0)return[];let[{value:t}]=v(e,1);return t==null?[]:g(t)?[{type:u.string,value:`${t.value} '${t.unit}'`}]:[{type:u.string,value:t.toString()}]},convertsToString:(i,e)=>e.length===0?[]:c(y.toString(i,e).length===1),toTime:(i,e)=>{if(e.length===0)return[];let[{value:t}]=v(e,1);if(typeof t=="string"){let n=/^T?(\d{2}(:\d{2}(:\d{2})?)?)/.exec(t);if(n)return[{type:u.time,value:Se("T"+n[1])}]}return[]},convertsToTime:(i,e)=>e.length===0?[]:c(y.toTime(i,e).length===1),indexOf:(i,e,t)=>C((n,r)=>n.indexOf(r),i,e,t),substring:(i,e,t,n)=>C((r,o,s)=>{let a=o,h=s?a+s:r.length;return a<0||a>=r.length?void 0:r.substring(a,h)},i,e,t,n),startsWith:(i,e,t)=>C((n,r)=>n.startsWith(r),i,e,t),endsWith:(i,e,t)=>C((n,r)=>n.endsWith(r),i,e,t),contains:(i,e,t)=>C((n,r)=>n.includes(r),i,e,t),upper:(i,e)=>C(t=>t.toUpperCase(),i,e),lower:(i,e)=>C(t=>t.toLowerCase(),i,e),replace:(i,e,t,n)=>C((r,o,s)=>r.replaceAll(o,s),i,e,t,n),matches:(i,e,t)=>C((n,r)=>!!new RegExp(r).exec(n),i,e,t),replaceMatches:(i,e,t,n)=>C((r,o,s)=>r.replaceAll(new RegExp(o,"g"),s),i,e,t,n),length:(i,e)=>C(t=>t.length,i,e),toChars:(i,e)=>C(t=>t?t.split(""):void 0,i,e),encode:x,decode:x,escape:x,unescape:x,trim:x,split:x,join:(i,e,t)=>{let n=t?.eval(i,V(i))[0]?.value??"";if(typeof n!="string")throw new Error("Separator must be a string.");return[{type:u.string,value:e.map(r=>r.value?.toString()??"").join(n)}]},abs:(i,e)=>D(Math.abs,i,e),ceiling:(i,e)=>D(Math.ceil,i,e),exp:(i,e)=>D(Math.exp,i,e),floor:(i,e)=>D(Math.floor,i,e),ln:(i,e)=>D(Math.log,i,e),log:(i,e,t)=>D((n,r)=>Math.log(n)/Math.log(r),i,e,t),power:(i,e,t)=>D(Math.pow,i,e,t),round:(i,e)=>D(Math.round,i,e),sqrt:(i,e)=>D(Math.sqrt,i,e),truncate:(i,e)=>D(t=>t|0,i,e),children:x,descendants:x,trace:(i,e,t)=>e,now:()=>[{type:u.dateTime,value:new Date().toISOString()}],timeOfDay:()=>[{type:u.time,value:new Date().toISOString().substring(11)}],today:()=>[{type:u.date,value:new Date().toISOString().substring(0,10)}],between:(i,e,t,n,r)=>{let o=y.toDateTime(i,t.eval(i,e));if(o.length===0)throw new Error("Invalid start date");let s=y.toDateTime(i,n.eval(i,e));if(s.length===0)throw new Error("Invalid end date");let a=r.eval(i,e)[0]?.value;if(a!=="years"&&a!=="months"&&a!=="days")throw new Error("Invalid units");let h=Nr(o[0].value,s[0].value);return[{type:u.Quantity,value:{value:h[a],unit:a}}]},is:(i,e,t)=>{let n="";return t instanceof Ce?n=t.name:t instanceof ei&&(n=t.left.name+"."+t.right.name),n?e.map(r=>({type:u.boolean,value:Qt(r,n)})):[]},not:(i,e)=>y.toBoolean(i,e).map(t=>({type:u.boolean,value:!t.value})),resolve:(i,e)=>e.map(t=>{let n=t.value,r;if(typeof n=="string")r=n;else if(typeof n=="object"){let o=n;if(o.resource)return M(o.resource);o.reference?r=o.reference:o.type&&o.identifier&&(r=`${o.type}?identifier=${o.identifier.system}|${o.identifier.value}`)}if(r?.includes("?")){let[o]=r.split("?");return{type:o,value:{resourceType:o}}}if(r?.includes("/")){let[o,s]=r.split("/");return{type:o,value:{resourceType:o,id:s}}}return{type:u.BackboneElement,value:void 0}}).filter(t=>!!t.value),as:(i,e)=>e,type:(i,e)=>e.map(({value:t})=>typeof t=="boolean"?{type:u.BackboneElement,value:{namespace:"System",name:"Boolean"}}:typeof t=="number"?{type:u.BackboneElement,value:{namespace:"System",name:"Integer"}}:z(t)?{type:u.BackboneElement,value:{namespace:"FHIR",name:t.resourceType}}:{type:u.BackboneElement,value:null}),conformsTo:(i,e,t)=>{let n=t.eval(i,e)[0].value;if(!n.startsWith("http://hl7.org/fhir/StructureDefinition/"))throw new Error("Expected a StructureDefinition URL");let r=n.replace("http://hl7.org/fhir/StructureDefinition/","");return e.map(o=>({type:u.boolean,value:o.value?.resourceType===r}))},getResourceKey:(i,e)=>{let t=e[0].value;return t?.id?[{type:u.id,value:t.id}]:[]},getReferenceKey:(i,e,t)=>{let n=e[0].value;if(!n?.reference)return[];let r="";return t instanceof Ce&&(r=t.name),r&&!n.reference.startsWith(r+"/")?[]:[{type:u.id,value:Sr(n)}]},extension:(i,e,t)=>{let n=t.eval(i,e)[0].value,r=e?.[0]?.value;if(r){let o=Ne(r,n);if(o)return[{type:u.Extension,value:o}]}return[]}};function C(i,e,t,...n){if(t.length===0)return[];let[{value:r}]=v(t,1);if(typeof r!="string")throw new Error("String function cannot be called with non-string");let o=i(r,...n.map(s=>s?.eval(e,t)[0]?.value));return o===void 0?[]:Array.isArray(o)?o.map(M):[M(o)]}function D(i,e,t,...n){if(t.length===0)return[];let[{value:r}]=v(t,1),o=g(r),s=o?r.value:r;if(typeof s!="number")throw new Error("Math function cannot be called with non-number");let a=i(s,...n.map(E=>E.eval(e,t)[0]?.value)),h=o?u.Quantity:t[0].type,S=o?{...r,value:a}:a;return[{type:h,value:S}]}function v(i,e){if(i.length!==e)throw new Error(`Expected ${e} arguments`);for(let t of i)if(t==null)throw new Error("Expected non-null argument");return i}function V(i){let e=i;for(;e.parent?.variables.$this;)e=e.parent;return[e.variables.$this]}var G=class{constructor(i){this.value=i}eval(){return[this.value]}toString(){let i=this.value.value;return typeof i=="string"?`'${i}'`:i.toString()}},Ce=class{constructor(i){this.name=i}eval(i,e){if(this.name==="$this")return e;let t=this.getVariable(i);if(t)return[t];if(this.name.startsWith("%"))throw new Error(`Undefined variable ${this.name}`);return e.flatMap(n=>this.evalValue(n)).filter(n=>n?.value!==void 0)}getVariable(i){let e=i.variables[this.name];if(e!==void 0)return e;if(i.parent)return this.getVariable(i.parent)}evalValue(i){let e=i.value;if(!(!e||typeof e!="object"))return z(e,this.name)?i:dr(i,this.name)}toString(){return this.name}},Ur=class{eval(){return[]}toString(){return"{}"}},Vr=class extends Kn{constructor(i,e,t){super(i,e),this.impl=t}eval(i,e){return this.impl(this.child.eval(i,e))}toString(){return this.operator+this.child.toString()}},Mr=class extends W{constructor(i,e){super("as",i,e)}eval(i,e){return y.ofType(i,this.left.eval(i,e),this.right)}},A=class extends W{},R=class extends A{constructor(i,e,t,n){super(i,e,t),this.impl=n}eval(i,e){let t=this.left.eval(i,e);if(t.length!==1)return[];let n=this.right.eval(i,e);if(n.length!==1)return[];let r=t[0].value,o=n[0].value,s=g(r)?r.value:r,a=g(o)?o.value:o,h=this.impl(s,a);return typeof h=="boolean"?c(h):g(r)?[{type:u.Quantity,value:{...r,value:h}}]:[M(h)]}},wr=class extends W{constructor(i,e){super("&",i,e)}eval(i,e){let t=this.left.eval(i,e),n=this.right.eval(i,e),r=[...t,...n];return r.length>0&&r.every(o=>typeof o.value=="string")?[{type:u.string,value:r.map(o=>o.value).join("")}]:r}},Br=class extends A{constructor(i,e){super("contains",i,e)}eval(i,e){let t=this.left.eval(i,e),n=this.right.eval(i,e);return c(t.some(r=>r.value===n[0].value))}},Fr=class extends A{constructor(i,e){super("in",i,e)}eval(i,e){let t=b(this.left.eval(i,e)),n=this.right.eval(i,e);return t?c(n.some(r=>Ae(t,r)[0].value)):[]}},ei=class extends W{constructor(i,e){super(".",i,e)}eval(i,e){return this.right.eval(i,this.left.eval(i,e))}toString(){return`${this.left.toString()}.${this.right.toString()}`}},kr=class extends W{constructor(i,e){super("|",i,e)}eval(i,e){let t=this.left.eval(i,e),n=this.right.eval(i,e);return qt([...t,...n])}},Gr=class extends A{constructor(i,e){super("=",i,e)}eval(i,e){let t=this.left.eval(i,e),n=this.right.eval(i,e);return fr(t,n)}},Yr=class extends A{constructor(i,e){super("!=",i,e)}eval(i,e){let t=this.left.eval(i,e),n=this.right.eval(i,e);return _r(t,n)}},Hr=class extends A{constructor(i,e){super("~",i,e)}eval(i,e){let t=this.left.eval(i,e),n=this.right.eval(i,e);return Wt(t,n)}},$r=class extends A{constructor(i,e){super("!~",i,e)}eval(i,e){let t=this.left.eval(i,e),n=this.right.eval(i,e);return hr(Wt(t,n))}},jr=class extends A{constructor(i,e){super("is",i,e)}eval(i,e){let t=this.left.eval(i,e);if(t.length!==1)return[];let n=this.right.name;return c(Qt(t[0],n))}},qr=class extends A{constructor(i,e){super("and",i,e)}eval(i,e){let t=b(this.left.eval(i,e),"boolean"),n=b(this.right.eval(i,e),"boolean");return t?.value===!0&&n?.value===!0?c(!0):t?.value===!1||n?.value===!1?c(!1):[]}},Wr=class extends A{constructor(i,e){super("or",i,e)}eval(i,e){let t=b(this.left.eval(i,e),"boolean"),n=b(this.right.eval(i,e),"boolean");return t?.value===!1&&n?.value===!1?c(!1):t?.value||n?.value?c(!0):[]}},Qr=class extends A{constructor(i,e){super("xor",i,e)}eval(i,e){let t=b(this.left.eval(i,e),"boolean"),n=b(this.right.eval(i,e),"boolean");return!t||!n?[]:c(t.value!==n.value)}},zr=class extends A{constructor(i,e){super("implies",i,e)}eval(i,e){let t=b(this.left.eval(i,e),"boolean"),n=b(this.right.eval(i,e),"boolean");return n?.value===!0||t?.value===!1?c(!0):!t||!n?[]:c(!1)}},Zr=class{constructor(i,e){this.name=i,this.args=e}eval(i,e){let t=y[this.name];if(!t)throw new Error("Unrecognized function: "+this.name);return t(i,e,...this.args)}toString(){return`${this.name}(${this.args.map(i=>i.toString()).join(", ")})`}},Xr=class{constructor(i,e){this.left=i,this.expr=e}eval(i,e){let t=this.expr.eval(i,e);if(t.length!==1)return[];let n=t[0].value;if(typeof n!="number")throw new Error("Invalid indexer expression: should return integer}");let r=this.left.eval(i,e);return n in r?[r[n]]:[]}toString(){return`${this.left.toString()}[${this.expr.toString()}]`}};var ti=["!=","!~","<=",">=","{}","->"];var l={FunctionCall:0,Dot:1,Indexer:2,UnaryAdd:3,UnarySubtract:3,Multiply:4,Divide:4,IntegerDivide:4,Modulo:4,Add:5,Subtract:5,Ampersand:5,Is:6,As:6,Union:7,GreaterThan:8,GreaterThanOrEquals:8,LessThan:8,LessThanOrEquals:8,Equals:9,Equivalent:9,NotEquals:9,NotEquivalent:9,In:10,Contains:10,And:11,Xor:12,Or:12,Implies:13,Arrow:100,Semicolon:200},Jr={parse(i){let e=i.consumeAndParse();if(!i.match(")"))throw new Error("Parse error: expected `)` got `"+i.peek()?.value+"`");return e}},Kr={parse(i,e){let t=i.consumeAndParse();if(!i.match("]"))throw new Error("Parse error: expected `]`");return new Xr(e,t)},precedence:l.Indexer},eo={parse(i,e){if(!(e instanceof Ce))throw new Error("Unexpected parentheses");let t=[];for(;!i.match(")");)t.push(i.consumeAndParse()),i.match(",");return new Zr(e.name,t)},precedence:l.FunctionCall};function to(i){let e=i.split(" "),t=parseFloat(e[0]),n=e[1];return n?.startsWith("'")&&n.endsWith("'")?n=n.substring(1,n.length-1):n="{"+n+"}",{value:t,unit:n}}function ct(){return new er().registerPrefix("String",{parse:(i,e)=>new G({type:u.string,value:e.value})}).registerPrefix("DateTime",{parse:(i,e)=>new G({type:u.dateTime,value:Se(e.value)})}).registerPrefix("Quantity",{parse:(i,e)=>new G({type:u.Quantity,value:to(e.value)})}).registerPrefix("Number",{parse:(i,e)=>new G({type:e.value.includes(".")?u.decimal:u.integer,value:parseFloat(e.value)})}).registerPrefix("true",{parse:()=>new G({type:u.boolean,value:!0})}).registerPrefix("false",{parse:()=>new G({type:u.boolean,value:!1})}).registerPrefix("Symbol",{parse:(i,e)=>new Ce(e.value)}).registerPrefix("{}",{parse:()=>new Ur}).registerPrefix("(",Jr).registerInfix("[",Kr).registerInfix("(",eo).prefix("+",l.UnaryAdd,(i,e)=>new Vr("+",e,t=>t)).prefix("-",l.UnarySubtract,(i,e)=>new R("-",e,e,(t,n)=>-n)).infixLeft(".",l.Dot,(i,e,t)=>new ei(i,t)).infixLeft("/",l.Divide,(i,e,t)=>new R("/",i,t,(n,r)=>n/r)).infixLeft("*",l.Multiply,(i,e,t)=>new R("*",i,t,(n,r)=>n*r)).infixLeft("+",l.Add,(i,e,t)=>new R("+",i,t,(n,r)=>n+r)).infixLeft("-",l.Subtract,(i,e,t)=>new R("-",i,t,(n,r)=>n-r)).infixLeft("|",l.Union,(i,e,t)=>new kr(i,t)).infixLeft("=",l.Equals,(i,e,t)=>new Gr(i,t)).infixLeft("!=",l.NotEquals,(i,e,t)=>new Yr(i,t)).infixLeft("~",l.Equivalent,(i,e,t)=>new Hr(i,t)).infixLeft("!~",l.NotEquivalent,(i,e,t)=>new $r(i,t)).infixLeft("<",l.LessThan,(i,e,t)=>new R("<",i,t,(n,r)=>n<r)).infixLeft("<=",l.LessThanOrEquals,(i,e,t)=>new R("<=",i,t,(n,r)=>n<=r)).infixLeft(">",l.GreaterThan,(i,e,t)=>new R(">",i,t,(n,r)=>n>r)).infixLeft(">=",l.GreaterThanOrEquals,(i,e,t)=>new R(">=",i,t,(n,r)=>n>=r)).infixLeft("&",l.Ampersand,(i,e,t)=>new wr(i,t)).infixLeft("and",l.And,(i,e,t)=>new qr(i,t)).infixLeft("as",l.As,(i,e,t)=>new Mr(i,t)).infixLeft("contains",l.Contains,(i,e,t)=>new Br(i,t)).infixLeft("div",l.Divide,(i,e,t)=>new R("div",i,t,(n,r)=>n/r|0)).infixLeft("in",l.In,(i,e,t)=>new Fr(i,t)).infixLeft("is",l.Is,(i,e,t)=>new jr(i,t)).infixLeft("mod",l.Modulo,(i,e,t)=>new R("mod",i,t,(n,r)=>n%r)).infixLeft("or",l.Or,(i,e,t)=>new Wr(i,t)).infixLeft("xor",l.Xor,(i,e,t)=>new Qr(i,t)).infixLeft("implies",l.Implies,(i,e,t)=>new zr(i,t))}var qo=ct();var d={EQUALS:"eq",NOT_EQUALS:"ne",GREATER_THAN:"gt",LESS_THAN:"lt",GREATER_THAN_OR_EQUALS:"ge",LESS_THAN_OR_EQUALS:"le",STARTS_AFTER:"sa",ENDS_BEFORE:"eb",APPROXIMATELY:"ap",CONTAINS:"contains",STARTS_WITH:"sw",EXACT:"exact",TEXT:"text",NOT:"not",ABOVE:"above",BELOW:"below",IN:"in",NOT_IN:"not-in",OF_TYPE:"of-type",MISSING:"missing",PRESENT:"present",IDENTIFIER:"identifier",ITERATE:"iterate"},Wo={contains:d.CONTAINS,exact:d.EXACT,above:d.ABOVE,below:d.BELOW,text:d.TEXT,not:d.NOT,in:d.IN,"not-in":d.NOT_IN,"of-type":d.OF_TYPE,missing:d.MISSING,identifier:d.IDENTIFIER,iterate:d.ITERATE},Qo={eq:d.EQUALS,ne:d.NOT_EQUALS,lt:d.LESS_THAN,le:d.LESS_THAN_OR_EQUALS,gt:d.GREATER_THAN,ge:d.GREATER_THAN_OR_EQUALS,sa:d.STARTS_AFTER,eb:d.ENDS_BEFORE,ap:d.APPROXIMATELY,sw:d.STARTS_WITH};var zo=[d.MISSING,d.PRESENT];var Oe={READ:"read",VREAD:"vread",UPDATE:"update",DELETE:"delete",HISTORY:"history",CREATE:"create",SEARCH:"search"},Zo=[Oe.READ,Oe.VREAD,Oe.HISTORY,Oe.SEARCH];function Re(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}var io={CSS:"text/css",DICOM:"application/dicom",FAVICON:"image/vnd.microsoft.icon",FHIR_JSON:"application/fhir+json",FORM_URL_ENCODED:"application/x-www-form-urlencoded",HL7_V2:"x-application/hl7-v2+er7",HTML:"text/html",JAVASCRIPT:"text/javascript",JSON:"application/json",JSON_PATCH:"application/json-patch+json",JWT:"application/jwt",MULTIPART_FORM_DATA:"multipart/form-data",PNG:"image/png",SCIM_JSON:"application/scim+json",SVG:"image/svg+xml",TEXT:"text/plain",TYPESCRIPT:"text/typescript",PING:"x-application/ping",XML:"text/xml",CDA_XML:"application/cda+xml"};var no;no=Symbol.toStringTag;var Xo={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};var Jo={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1};var Ko=io.FHIR_JSON+", */*; q=0.1";var es=[...ti,"->","<<",">>","=="];var ts=ct().registerInfix("->",{precedence:l.Arrow}).registerInfix(";",{precedence:l.Semicolon});var is=" ".repeat(2);var ns=[...ti,"eq","ne","co"];var rs={eq:d.EXACT,ne:d.NOT_EQUALS,co:d.CONTAINS,sw:d.STARTS_WITH,ew:void 0,gt:d.GREATER_THAN,lt:d.LESS_THAN,ge:d.GREATER_THAN_OR_EQUALS,le:d.LESS_THAN_OR_EQUALS,ap:d.APPROXIMATELY,sa:d.STARTS_AFTER,eb:d.ENDS_BEFORE,pr:d.PRESENT,po:void 0,ss:void 0,sb:void 0,in:d.IN,ni:d.NOT_IN,re:d.EQUALS,identifier:d.IDENTIFIER};var os=ct();function ut(i){if(!i)return;let e=i.substring(0,4),t="01",n="01";return i.length>=8&&(t=i.substring(4,6),n=i.substring(6,8)),`${e}-${t}-${n}`}function m(i){if(!i)return;let e=i.substring(0,4),t="01",n="01",r="00",o="00",s="00",a="Z";return i.length>=8&&(t=i.substring(4,6),n=i.substring(6,8)),i.length>=12&&(r=i.substring(8,10),o=i.substring(10,12)),i.length>=14&&(s=i.substring(12,14)),i.length>14&&(a=i.substring(14),a==="+0000"&&(a="Z")),`${e}-${t}-${n}T${r}:${o}:${s}${a}`}function w(i){if(i)return i.substring(0,10).replace(/-/g,"")}function O(i){if(!i)return;let[e,t]=i.split("T"),n=e.replaceAll("-",""),r=(t??"").replaceAll(/\.\d+/g,"").replaceAll(/:/g,"").replaceAll(/Z/g,"+0000");return`${n}${r}`}var B="1.3.6.1.4.1.19376.1.5.3.1.3.1";var ii="2.16.840.1.113883.1.3";var ni="2.16.840.1.113883.2.20.5.1",ri="2.16.840.1.113883.3.26.1.1";var oi="2.16.840.1.113883.4.1",si="2.16.840.1.113883.4.3",ai="2.16.840.1.113883.4.6",ci="2.16.840.1.113883.4.9",De="2.16.840.1.113883.5.1",ve="2.16.840.1.113883.5.4",dt="2.16.840.1.113883.5.6",lt="2.16.840.1.113883.5.25",N="2.16.840.1.113883.6.1",ui="2.16.840.1.113883.6.12",di="2.16.840.1.113883.6.24",li="2.16.840.1.113883.6.69",pi="2.16.840.1.113883.6.88",L="2.16.840.1.113883.6.96",hi="2.16.840.1.113883.6.101",fi="2.16.840.1.113883.6.209",xe="2.16.840.1.113883.6.238",_i="2.16.840.1.113883.6.345";var mi="2.16.840.1.113883.10.20.15.3.8";var Z="2.16.840.1.113883.10.20.22.1.1";var pt="2.16.840.1.113883.10.20.22.1.2";var ht="2.16.840.1.113883.10.20.22.1.14";var Pe="2.16.840.1.113883.10.20.22.2.1.1";var X="2.16.840.1.113883.10.20.22.2.2",J="2.16.840.1.113883.10.20.22.2.2.1";var ft="2.16.840.1.113883.10.20.22.2.3.1";var Ei="2.16.840.1.113883.10.20.22.2.4.1";var Ii="2.16.840.1.113883.10.20.22.2.5",K="2.16.840.1.113883.10.20.22.2.5.1",Ti="2.16.840.1.113883.10.20.22.2.5.1 .2",Oi="2.16.840.1.113883.10.20.22.2.5.2",Si="2.16.840.1.113883.10.20.22.2.6",ee="2.16.840.1.113883.10.20.22.2.6.1",yi="2.16.840.1.113883.10.20.22.2.6.1.2",Ci="2.16.840.1.113883.10.20.22.2.6.2";var Y="2.16.840.1.113883.10.20.22.2.7.1";var be="2.16.840.1.113883.10.20.22.2.8";var U="2.16.840.1.113883.10.20.22.2.10";var _t="2.16.840.1.113883.10.20.22.2.17";var Le="2.16.840.1.113883.10.20.22.2.18";var gi="2.16.840.1.113883.10.20.22.2.22.1";var Ai="2.16.840.1.113883.10.20.22.2.23";var Ni="2.16.840.1.113883.10.20.22.2.56";var Ue="2.16.840.1.113883.10.20.22.2.58";var te="2.16.840.1.113883.10.20.22.2.60";var Ve="2.16.840.1.113883.10.20.22.2.65";var Me="2.16.840.1.113883.10.20.22.2.500",ie="2.16.840.1.113883.10.20.22.4.1",Ri="2.16.840.1.113883.10.20.22.4.1.2",ne="2.16.840.1.113883.10.20.22.4.2",Di="2.16.840.1.113883.10.20.22.4.2.2",mt="2.16.840.1.113883.10.20.22.4.3";var F="2.16.840.1.113883.10.20.22.4.4",vi="2.16.840.1.113883.10.20.22.4.4.2";var Et="2.16.840.1.113883.10.20.22.4.7";var It="2.16.840.1.113883.10.20.22.4.8";var Tt="2.16.840.1.113883.10.20.22.4.9";var re="2.16.840.1.113883.10.20.22.4.12";var oe="2.16.840.1.113883.10.20.22.4.13";var se="2.16.840.1.113883.10.20.22.4.14";var Ot="2.16.840.1.113883.10.20.22.4.16";var xi="2.16.840.1.113883.10.20.22.4.20";var St="2.16.840.1.113883.10.20.22.4.23";var ae="2.16.840.1.113883.10.20.22.4.26",Pi="2.16.840.1.113883.10.20.22.4.26.2",ce="2.16.840.1.113883.10.20.22.4.27",bi="2.16.840.1.113883.10.20.22.4.27.2";var yt="2.16.840.1.113883.10.20.22.4.30";var Ct="2.16.840.1.113883.10.20.22.4.32";var Li="2.16.840.1.113883.10.20.22.4.37",Ui="2.16.840.1.113883.10.20.22.4.38",Vi="2.16.840.1.113883.10.20.22.4.38.1";var gt="2.16.840.1.113883.10.20.22.4.44";var ue="2.16.840.1.113883.10.20.22.4.49";var At="2.16.840.1.113883.10.20.22.4.52";var Nt="2.16.840.1.113883.10.20.22.4.54";var Mi="2.16.840.1.113883.10.20.22.4.66";var wi="2.16.840.1.113883.10.20.22.4.67";var Bi="2.16.840.1.113883.10.20.22.4.69",Fi="2.16.840.1.113883.10.20.22.4.70";var ki="2.16.840.1.113883.10.20.22.4.74";var Gi="2.16.840.1.113883.10.20.22.4.75";var de="2.16.840.1.113883.10.20.22.4.78",Yi="2.16.840.1.113883.10.20.22.4.78.2";var le="2.16.840.1.113883.10.20.22.4.85";var Hi="2.16.840.1.113883.10.20.22.4.86";var $i="2.16.840.1.113883.10.20.22.4.114";var ji="2.16.840.1.113883.10.20.22.4.119";var we="2.16.840.1.113883.10.20.22.4.121";var qi="2.16.840.1.113883.10.20.22.4.130";var Rt="2.16.840.1.113883.10.20.22.4.132",Wi="2.16.840.1.113883.10.20.22.4.133";var Qi="2.16.840.1.113883.10.20.22.4.140";var Be="2.16.840.1.113883.10.20.22.4.147",pe="2.16.840.1.113883.10.20.22.4.200",zi="2.16.840.1.113883.10.20.22.4.201",Zi="2.16.840.1.113883.10.20.22.4.202";var Xi="2.16.840.1.113883.10.20.22.4.244";var Ji="2.16.840.1.113883.10.20.22.4.250";var Ki="2.16.840.1.113883.10.20.22.4.406",en="2.16.840.1.113883.10.20.22.4.407";var tn="2.16.840.1.113883.10.20.22.4.416";var Dt="2.16.840.1.113883.10.20.22.4.500",nn="2.16.840.1.113883.10.20.22.4.501";var rn="2.16.840.1.113883.10.20.22.4.503",on="2.16.840.1.113883.10.20.22.4.504";var sn="2.16.840.1.113883.10.20.22.4.506",Fe="2.16.840.1.113883.10.20.22.4.507",an="2.16.840.1.113883.10.20.22.4.508";var cn="2.16.840.1.113883.10.20.22.4.512";var vt="2.16.840.1.113883.12.292",xt="2.16.840.1.113883.3.3719";var I=class{constructor(e,t,n,r){this.systemName=e,this.ccdaSystemOid=t,this.fhirSystemUrl=n,this.entries=r,this.ccdaToFhirMap={},this.fhirToCcdaMap={};for(let o of r)this.ccdaToFhirMap[o.ccdaValue]||(this.ccdaToFhirMap[o.ccdaValue]=o),this.fhirToCcdaMap[o.fhirValue]||(this.fhirToCcdaMap[o.fhirValue]=o)}getEntryByFhir(e){return this.fhirToCcdaMap[e]}getEntryByCcda(e){return this.ccdaToFhirMap[e]}mapCcdaToFhir(e){return this.ccdaToFhirMap[e]?.fhirValue}mapCcdaToFhirWithDefault(e,t){return e?this.mapCcdaToFhir(e)??t:t}mapFhirToCcdaWithDefault(e,t){return e?this.mapFhirToCcda(e)??t:t}mapCcdaToFhirCodeableConcept(e){let t=this.ccdaToFhirMap[e];if(t)return{coding:[{system:this.fhirSystemUrl,code:t.fhirValue,display:t.displayName}],text:t.displayName}}mapFhirToCcda(e){if(e)return this.fhirToCcdaMap[e]?.ccdaValue}mapFhirToCcdaCode(e){if(!e)return;let t=this.fhirToCcdaMap[e];if(t)return{"@_code":t.ccdaValue,"@_displayName":t.displayName,"@_codeSystem":this.ccdaSystemOid,"@_codeSystemName":Qe.getEntryByCcda(this.ccdaSystemOid)?.displayName}}},k="http:",ro=`${_}/fhir/administrative-gender`,Pt=`${T}/CodeSystem/condition-clinical`,dn=`${T}/CodeSystem/condition-verification`,Fs=`${T}/CodeSystem/v3-LanguageAbilityMode`,ks=`${T}/CodeSystem/v3-LanguageAbilityProficiency`,Gs=`${T}/CodeSystem/v3-Race`,ln=`${T}/CodeSystem/condition-category`,bt=`${T}/CodeSystem/condition-ver-status`,ke=`${T}/CodeSystem/allergyintolerance-clinical`,Lt=`${T}/CodeSystem/allergyintolerance-verification`,pn=`${T}/CodeSystem/v3-ActCode`,hn=`${T}/CodeSystem/v3-ParticipationType`,fn=`${T}/CodeSystem/diagnosis-role`,oo=`${T}/CodeSystem/v3-Confidentiality`,so=`${T}/CodeSystem/observation-category`,ao=`${_}/fhir/ValueSet/address-use`,co=`${_}/fhir/ValueSet/name-use`,uo=`${_}/fhir/ValueSet/administrative-gender`,lo=`${_}/fhir/ValueSet/contactentity-use`,po=`${_}/fhir/ValueSet/medicationrequest-status`,Ys=`${_}/fhir/StructureDefinition/language-mode`,Hs=`${_}/fhir/StructureDefinition/language-proficiency`,$s=`${_}/fhir/us/core/StructureDefinition/us-core-patient`,he=`${_}/fhir/us/core/StructureDefinition/us-core-race`,Ge=`${_}/fhir/us/core/StructureDefinition/us-core-ethnicity`,_n=`${_}/fhir/us/core/StructureDefinition/us-core-condition`,mn=`${_}/fhir/us/core/StructureDefinition/us-core-medicationrequest`,js=`${_}/cda/template`,ho=`${k}//ncithesaurus-stage.nci.nih.gov`,fo=`${_}/fhir/sid/us-ssn`,_o=`${_}/fhir/sid/us-dln`,mo=`${_}/fhir/sid/us-npi`,Eo=`${k}//fdasis.nlm.nih.gov`,Io=`${k}//nucc.org/provider-taxonomy`,To=`${k}//va.gov/terminology/medrt`,Oo=`${k}//hl7.org/fhir/ndfrt`,So=`${k}//nucc.org/cvx`,yo=`${_}/fhir/sid/cvx`,En=`${k}//www.w3.org/2001/XMLSchema-instance`,Ye="https://medplum.com/fhir/StructureDefinition/ccda-narrative-reference",In="48765-2",Tn="11369-6",On="10160-0",He="11450-4",Sn="30954-2",yn="29762-2",Cn="8716-3",gn="47519-4",$e="18776-5",je="51848-0",An="46264-8",fe="61146-7",_e="75310-3",Nn="46240-8",me="42349-1",Rn="57133-1",Dn="10190-7",vn="85847-2",xn="48768-6",qe="11488-4",qs="34109-9",Ws="60591-5",We="34133-9",Pn="76662-6",bn="75323-6",Ln="58144-7",Un="72166-2",Vn="11367-0",Mn="46098-0",wn="76689-9",Qe=new I("System","","",[{ccdaValue:ni,fhirValue:"https://fhir.infoway-inforoute.ca/CodeSystem/pCLOCD",displayName:"pan-Canadian LOINC Observation Code Database (pCLOCD)"},{ccdaValue:ri,fhirValue:ho,displayName:"NCI Thesaurus"},{ccdaValue:oi,fhirValue:fo,displayName:"SSN"},{ccdaValue:si,fhirValue:_o,displayName:"DLN"},{ccdaValue:ai,fhirValue:mo,displayName:"NPI"},{ccdaValue:ci,fhirValue:Eo,displayName:"Unique Ingredient Identifier (UNII)"},{ccdaValue:N,fhirValue:ge,displayName:"LOINC"},{ccdaValue:ui,fhirValue:Ht,displayName:"Current Procedural Terminology (CPT)"},{ccdaValue:di,fhirValue:"urn:iso:std:iso:11073:10101",displayName:"Medical Device Communications (MDC)"},{ccdaValue:li,fhirValue:$t,displayName:"National Drug Code (NDC)"},{ccdaValue:pi,fhirValue:Yt,displayName:"RxNorm"},{ccdaValue:L,fhirValue:rt,displayName:"SNOMED CT"},{ccdaValue:hi,fhirValue:Io,displayName:"NUCC Health Care Provider Taxonomy"},{ccdaValue:_i,fhirValue:To,displayName:"Medication Reference Terminology (MED-RT)"},{ccdaValue:fi,fhirValue:Oo,displayName:"National Drug File Reference Terminology (NDF-RT)"},{ccdaValue:vt,fhirValue:So,displayName:"CVX"},{ccdaValue:lt,fhirValue:"Confidentiality",displayName:"Confidentiality"},{ccdaValue:De,fhirValue:ro,displayName:"Administrative Sex"},{ccdaValue:vt,fhirValue:yo,displayName:"Vaccine Administered Code Set (CVX)"}]);function Ee(i){if(i)return Qe.mapCcdaToFhir(i)??`urn:oid:${i}`}function Bn(i){if(i)return i.startsWith("urn:oid:")?i.replace("urn:oid:",""):Qe.mapFhirToCcda(i)}function p(i){if(!i?.coding)return;let e=un(i.coding[0]);if(i.coding.length>1){e.translation=[];for(let t=1;t<i.coding.length;t++)e.translation.push(un(i.coding[t]))}return e}function un(i){let e=i?.system?Qe.getEntryByFhir(i.system):void 0,t=e?.ccdaValue,n=e?.displayName,r=i.system?.startsWith("urn:oid:")?i.system.replace("urn:oid:",""):void 0;return{"@_code":i.code,"@_displayName":i.display,"@_codeSystem":t??r,"@_codeSystemName":n}}function H(i){let e=p(i);if(e)return{"@_xsi:type":"CD",...e}}var Fn=new I("Confidentiality",lt,oo,[{ccdaValue:"U",fhirValue:"U",displayName:"unrestricted"},{ccdaValue:"L",fhirValue:"L",displayName:"low"},{ccdaValue:"M",fhirValue:"M",displayName:"moderate"},{ccdaValue:"N",fhirValue:"N",displayName:"normal"},{ccdaValue:"R",fhirValue:"R",displayName:"restricted"},{ccdaValue:"V",fhirValue:"V",displayName:"very restricted"}]),ze=new I("HumanNameUse","",co,[{ccdaValue:"C",fhirValue:"usual",displayName:"Common/Called by"},{ccdaValue:"L",fhirValue:"official",displayName:"Legal"},{ccdaValue:"TEMP",fhirValue:"temp",displayName:"Temporary"},{ccdaValue:"P",fhirValue:"nickname",displayName:"Nickname"},{ccdaValue:"ANON",fhirValue:"anonymous",displayName:"Anonymous"},{ccdaValue:"L",fhirValue:"maiden",displayName:"Maiden"},{ccdaValue:"L",fhirValue:"old",displayName:"Old"}]),kn=new I("Gender","",uo,[{ccdaValue:"F",fhirValue:"female",displayName:"Female"},{ccdaValue:"M",fhirValue:"male",displayName:"Male"},{ccdaValue:"UN",fhirValue:"unknown",displayName:"Unknown"},{ccdaValue:"UN",fhirValue:"other",displayName:"Other"}]),Ze=new I("AddressUse","",ao,[{ccdaValue:"HP",fhirValue:"home",displayName:"Home"},{ccdaValue:"WP",fhirValue:"work",displayName:"Work"}]),Xe=new I("TelecomUse","",lo,[{ccdaValue:"WP",fhirValue:"work",displayName:"Work"},{ccdaValue:"HP",fhirValue:"home",displayName:"Home"},{ccdaValue:"MC",fhirValue:"mobile",displayName:"Mobile"}]),Je=new I("AllergyStatus","",Lt,[{ccdaValue:"unconfirmed",fhirValue:"unconfirmed",displayName:"Unconfirmed"},{ccdaValue:"provisional",fhirValue:"provisional",displayName:"Provisional"},{ccdaValue:"differential",fhirValue:"differential",displayName:"Differential"},{ccdaValue:"confirmed",fhirValue:"confirmed",displayName:"Confirmed"},{ccdaValue:"refuted",fhirValue:"refuted",displayName:"Refuted"},{ccdaValue:"entered-in-error",fhirValue:"entered-in-error",displayName:"Entered in Error"},{ccdaValue:"unknown",fhirValue:"unknown",displayName:"Unknown"}]),Gn=new I("AllergyCategory",L,ke,[{ccdaValue:"414285001",fhirValue:"food",displayName:"Allergy to food (finding)"},{ccdaValue:"419511003",fhirValue:"medication",displayName:"Propensity to adverse reactions to drug (finding)"},{ccdaValue:"426232007",fhirValue:"environment",displayName:"Environmental allergy (finding)"},{ccdaValue:"418038007",fhirValue:"biologic",displayName:"Propensity to adverse reactions to substance (finding)"}]),Ke=new I("AllergySeverity",rt,ke,[{ccdaValue:"255604002",fhirValue:"mild",displayName:"Mild"},{ccdaValue:"6736007",fhirValue:"moderate",displayName:"Moderate"},{ccdaValue:"24484000",fhirValue:"severe",displayName:"Severe"}]),Ie=new I("ProblemStatus","",bt,[{ccdaValue:"active",fhirValue:"active",displayName:"Active"},{ccdaValue:"inactive",fhirValue:"inactive",displayName:"Inactive"},{ccdaValue:"resolved",fhirValue:"inactive",displayName:"Resolved"},{ccdaValue:"remission",fhirValue:"inactive",displayName:"In Remission"},{ccdaValue:"relapse",fhirValue:"active",displayName:"Relapse"},{ccdaValue:"resolved relapse",fhirValue:"inactive",displayName:"Resolved Relapse"},{ccdaValue:"aborted",fhirValue:"aborted",displayName:"Aborted"}]),et=new I("ImmunizationStatus","","",[{ccdaValue:"completed",fhirValue:"completed",displayName:"Completed"},{ccdaValue:"nullified",fhirValue:"entered-in-error",displayName:"Nullified"},{ccdaValue:"aborted",fhirValue:"not-done",displayName:"Aborted"},{ccdaValue:"cancelled",fhirValue:"not-done",displayName:"Cancelled"},{ccdaValue:"obsolete",fhirValue:"not-done",displayName:"Obsolete"}]),Yn=new I("EncounterStatus","","",[{ccdaValue:"active",fhirValue:"in-progress",displayName:"In Progress"},{ccdaValue:"completed",fhirValue:"finished",displayName:"Finished"},{ccdaValue:"aborted",fhirValue:"cancelled",displayName:"Cancelled"},{ccdaValue:"cancelled",fhirValue:"cancelled",displayName:"Cancelled"},{ccdaValue:"unknown",fhirValue:"unknown",displayName:"Unknown"}]),Hn=new I("ProcedureStatus","","",[{ccdaValue:"completed",fhirValue:"completed",displayName:"Completed"},{ccdaValue:"aborted",fhirValue:"stopped",displayName:"Stopped"},{ccdaValue:"cancelled",fhirValue:"not-done",displayName:"Not Done"},{ccdaValue:"new",fhirValue:"not-done",displayName:"Draft"},{ccdaValue:"unknown",fhirValue:"unknown",displayName:"Unknown"}]),tt=new I("MedicationStatus","",po,[{ccdaValue:"active",fhirValue:"active",displayName:"Active"},{ccdaValue:"completed",fhirValue:"completed",displayName:"Completed"},{ccdaValue:"aborted",fhirValue:"stopped",displayName:"Stopped"},{ccdaValue:"cancelled",fhirValue:"cancelled",displayName:"Cancelled"},{ccdaValue:"aborted",fhirValue:"entered-in-error",displayName:"Entered in Error"},{ccdaValue:"active",fhirValue:"draft",displayName:"Draft"},{ccdaValue:"cancelled",fhirValue:"unknown",displayName:"Unknown"},{ccdaValue:"nullified",fhirValue:"cancelled",displayName:"Nullified"},{ccdaValue:"obsolete",fhirValue:"cancelled",displayName:"Obsolete"}]),$n=new I("ObservationCategory","",so,[{ccdaValue:Ui,fhirValue:"social-history",displayName:"Social History"},{ccdaValue:Vi,fhirValue:"social-history",displayName:"Social History V2"},{ccdaValue:de,fhirValue:"social-history",displayName:"Smoking Status"},{ccdaValue:Yi,fhirValue:"social-history",displayName:"Current Smoking Status"},{ccdaValue:le,fhirValue:"social-history",displayName:"Tobacco Use"},{ccdaValue:rn,fhirValue:"social-history",displayName:"Basic Occupation"},{ccdaValue:on,fhirValue:"social-history",displayName:"Basic Industry"},{ccdaValue:nn,fhirValue:"social-history",displayName:"Sexual Orientation"},{ccdaValue:Fe,fhirValue:"social-history",displayName:"Sex Observation"},{ccdaValue:pe,fhirValue:"social-history",displayName:"Gender Identity"},{ccdaValue:zi,fhirValue:"social-history",displayName:"Gender Identity V2"},{ccdaValue:mi,fhirValue:"social-history",displayName:"Pregnancy Status"},{ccdaValue:sn,fhirValue:"social-history",displayName:"Tribal Affiliation"},{ccdaValue:ce,fhirValue:"vital-signs",displayName:"Vital Signs Observation"},{ccdaValue:bi,fhirValue:"vital-signs",displayName:"Vital Signs Observation V2"},{ccdaValue:ae,fhirValue:"vital-signs",displayName:"Vital Signs Organizer"},{ccdaValue:Pi,fhirValue:"vital-signs",displayName:"Vital Signs Organizer V2"},{ccdaValue:cn,fhirValue:"vital-signs",displayName:"Average Blood Pressure Organizer"},{ccdaValue:ne,fhirValue:"laboratory",displayName:"Result Observation"},{ccdaValue:Di,fhirValue:"laboratory",displayName:"Result Observation V2"},{ccdaValue:Ki,fhirValue:"laboratory",displayName:"Laboratory Battery (ID)"},{ccdaValue:en,fhirValue:"laboratory",displayName:"Laboratory Observation (ID)"},{ccdaValue:tn,fhirValue:"laboratory",displayName:"Laboratory Result Organizer (ID)"},{ccdaValue:ie,fhirValue:"laboratory",displayName:"Result Organizer"},{ccdaValue:Ri,fhirValue:"laboratory",displayName:"Result Organizer V2"},{ccdaValue:Bi,fhirValue:"survey",displayName:"Assessment Scale Observation"},{ccdaValue:Hi,fhirValue:"survey",displayName:"Assessment Scale Supporting Observation"},{ccdaValue:ki,fhirValue:"survey",displayName:"Cognitive Status Result Observation"},{ccdaValue:Gi,fhirValue:"survey",displayName:"Cognitive Status Result Organizer"},{ccdaValue:wi,fhirValue:"survey",displayName:"Functional Status Result Observation"},{ccdaValue:Mi,fhirValue:"survey",displayName:"Functional Status Result Organizer"},{ccdaValue:oe,fhirValue:"exam",displayName:"Procedure Activity Observation"},{ccdaValue:F,fhirValue:"exam",displayName:"Problem Observation"},{ccdaValue:vi,fhirValue:"exam",displayName:"Problem Observation V2"},{ccdaValue:Fi,fhirValue:"exam",displayName:"Pressure Ulcer Observation"},{ccdaValue:$i,fhirValue:"exam",displayName:"Wound Observation"},{ccdaValue:Wi,fhirValue:"exam",displayName:"Wound Measurements Observation"},{ccdaValue:Y,fhirValue:"exam",displayName:"Procedure Section"},{ccdaValue:an,fhirValue:"therapy",displayName:"Medication Adherence"},{ccdaValue:qi,fhirValue:"therapy",displayName:"Nutrition Recommendations"},{ccdaValue:Xi,fhirValue:"therapy",displayName:"Diet Statement (Nutrition)"},{ccdaValue:Ji,fhirValue:"therapy",displayName:"Monitoring, Evaluation and Outcome (Nutrition)"}]);import{XMLBuilder as jn,XMLParser as qn}from"fast-xml-parser";var Co=["ClinicalDocument.recordTarget",".id",".templateId",".name",".addr",".telecom",".streetAddressLine",".author",".effectiveTime","name.given","name.suffix","name.prefix","patient.raceCode","patient.sdtc:raceCode","patient.ethnicGroupCode","patient.languageCommunication","component.structuredBody.component","component.structuredBody.component.section","component.section","component.observation","component.act","code.translation","section.entry","entry.act","entry.organizer","entry.substanceAdministration","entry.observation","entry.encounter","entry.procedure","encounter.performer","encounter.participant","encounter.entryRelationship","entryRelationship.observation","entryRelationship.substanceAdministration","entryRelationship.act","organizer.component","substanceAdministration.consumable.manufacturedProduct","substanceAdministration.entryRelationship","substanceAdministration.performer","act.entryRelationship","act.performer","observation.participant","observation.entryRelationship","observation.referenceRange","consumable.manufacturedProduct","manufacturedProduct.manufacturedMaterial","manufacturedProduct.manufacturerOrganization","manufacturedProduct.manufacturedLabeledDrug","manufacturedMaterial.code","manufacturedMaterial.lotNumberText"];function Xs(i){return new qn({ignoreAttributes:!1,attributeNamePrefix:"@_",parseAttributeValue:!1,parseTagValue:!1,isArray:(n,r,o,s)=>Co.some(a=>r.endsWith(a))}).parse(i).ClinicalDocument}function Js(i){return new jn({ignoreAttributes:!1,attributeNamePrefix:"@_",format:!0,suppressBooleanAttributes:!1,suppressEmptyNode:!0}).build({"?xml":{"@_version":"1.0","@_encoding":"UTF-8"},"?xml-stylesheet":{"@_type":"text/xsl","@_href":"CDA.xsl"},ClinicalDocument:{"@_xmlns":"urn:hl7-org:v3","@_xmlns:xsi":En,"@_xmlns:voc":"urn:hl7-org:v3/voc","@_xmlns:sdtc":"urn:hl7-org:sdtc",...i}})}function Wn(i){return new qn({ignoreAttributes:!1,attributeNamePrefix:"@_",parseAttributeValue:!1,parseTagValue:!1}).parse(i)}function Qn(i){return i?typeof i=="string"?i:new jn({ignoreAttributes:!1,attributeNamePrefix:"@_",format:!1,suppressBooleanAttributes:!1,suppressEmptyNode:!0}).build(i).split(`
2
- `).map(n=>n.trim()).join(""):""}function oa(i,e){return new Ut(i,e).convert()}var Ut=class{constructor(e,t){this.resources=[];this.ccda=e,this.options=t}convert(){return this.processHeader(),{resourceType:"Bundle",type:"document",entry:[{resource:this.createComposition()},...this.patient?[{resource:this.patient}]:[],...this.resources.map(t=>({resource:t}))]}}processHeader(){let e=this.ccda.recordTarget?.[0]?.patientRole;e&&(this.patient=this.createPatient(e))}createPatient(e){let t=e.patient,n=[];return t.raceCode&&t.raceCode.length>0&&!t.raceCode[0]["@_nullFlavor"]&&n.push({url:he,extension:t.raceCode.map(r=>({url:"ombCategory",valueCoding:this.mapCodeToCoding(r)}))}),t.ethnicGroupCode&&t.ethnicGroupCode.length>0&&!t.ethnicGroupCode[0]["@_nullFlavor"]&&n.push({url:Ge,extension:t.ethnicGroupCode.map(r=>({url:"ombCategory",valueCoding:this.mapCodeToCoding(r)}))}),{resourceType:"Patient",id:this.mapId(e.id),identifier:this.mapIdentifiers(e.id),name:this.mapCcdaNameArrayFhirHumanNameArray(t.name),gender:this.mapGenderCode(t.administrativeGenderCode?.["@_code"]),birthDate:ut(t.birthTime?.["@_value"]),address:this.mapAddresses(e.addr),telecom:this.mapTelecom(e.telecom),extension:n.length>0?n:void 0}}mapId(e){let t=e?.find(n=>!n["@_extension"]&&n["@_root"]&&st(n["@_root"]));return t?t["@_root"]:Re()}mapIdentifiers(e){if(!e)return;let t=[];for(let n of e)!n["@_extension"]&&n["@_root"]&&st(n["@_root"])||t.push({system:Ee(n["@_root"]),value:n["@_extension"]});return t}mapCcdaNameArrayFhirHumanNameArray(e){return e?.map(t=>this.mapCcdaNameToFhirHumanName(t)).filter(Boolean)}mapCcdaNameToFhirHumanName(e){if(!e)return;let t={},n=e["@_use"]?ze.mapCcdaToFhir(e["@_use"]):void 0;return n&&(t.use=n),e.prefix&&(t.prefix=e.prefix.map(Te)?.filter(Boolean)),e.family&&(t.family=Te(e.family)),e.given&&(t.given=e.given.map(Te)?.filter(Boolean)),e.suffix&&(t.suffix=e.suffix.map(Te)?.filter(Boolean)),t}mapAddresses(e){if(!(!e||e.length===0||e.every(t=>t["@_nullFlavor"]==="UNK")))return e?.map(t=>({"@_use":t["@_use"]?Ze.mapCcdaToFhir(t["@_use"]):void 0,line:t.streetAddressLine,city:t.city,state:t.state,postalCode:t.postalCode,country:t.country}))}mapTelecom(e){if(!(!e||e.length===0||e.every(t=>t["@_nullFlavor"]==="UNK")))return e?.map(t=>({"@_use":t["@_use"]?Xe.mapCcdaToFhir(t["@_use"]):void 0,system:this.getTelecomSystem(t["@_value"]),value:this.getTelecomValue(t["@_value"])}))}createComposition(){let e=this.ccda.component?.structuredBody?.component||[],t=[];for(let n of e)for(let r of n.section){let o=this.processSection(r);t.push({title:r.title,code:this.mapCode(r.code),text:{status:"generated",div:`<div xmlns="http://www.w3.org/1999/xhtml">${Qn(r.text)}</div>`},entry:o.map(f)}),this.resources.push(...o)}return{resourceType:"Composition",id:this.mapId(this.ccda.id),language:this.ccda.languageCode?.["@_code"],status:"final",type:this.ccda.code?this.mapCode(this.ccda.code):{coding:[{system:ge,code:We}]},confidentiality:this.ccda.confidentialityCode?.["@_code"],author:this.ccda.author?.[0]?[this.mapAuthorToReference(this.ccda.author?.[0])]:[{display:"Medplum"}],custodian:this.mapCustodianToReference(this.ccda.custodian),event:this.mapDocumentationOfToEvent(this.ccda.documentationOf),date:m(this.ccda.effectiveTime?.[0]?.["@_value"])??new Date().toISOString(),title:this.ccda.title??"Medical Summary",section:t}}processSection(e){let t=[];if(e.entry)for(let n of e.entry)this.processEntry(e,n,t);return t}processEntry(e,t,n){for(let r of t.act??[]){let o=this.processAct(e,r);o&&n.push(o)}for(let r of t.substanceAdministration??[]){let o=this.processSubstanceAdministration(e,r);o&&n.push(o)}for(let r of t.organizer??[])n.push(this.processOrganizer(e,r));for(let r of t.observation??[])n.push(this.processObservation(e,r));for(let r of t.encounter??[])n.push(this.processEncounter(e,r));for(let r of t.procedure??[])n.push(this.processProcedure(e,r))}processAct(e,t){let n=e.templateId[0]["@_root"];switch(n){case ee:case Si:case yi:case Ci:return this.processAllergyIntoleranceAct(t);case K:case Ii:case Ti:case Oi:return this.processConditionAct(t);case U:return this.processCarePlanAct(t);case Ue:return this.processConditionAct(t);case Y:return this.processProcedureAct(t);case B:return;case Ve:return;case Le:return;default:if(this.options?.ignoreUnsupportedSections)return;throw new Error("Unhandled act templateId: "+n)}}processAllergyIntoleranceAct(e){let t=e.entryRelationship?.find(s=>s["@_typeCode"]==="SUBJ")?.observation?.[0];if(!t)return;let n={resourceType:"AllergyIntolerance",id:this.mapId(e.id),clinicalStatus:this.createClinicalStatus(e),verificationStatus:this.createVerificationStatus(),type:"allergy",category:["food"],patient:f(this.patient),recorder:this.mapAuthorToReference(e.author?.[0]),recordedDate:this.mapEffectiveTimeToDateTime(e.effectiveTime?.[0]),onsetDateTime:this.mapEffectiveTimeToDateTime(t.effectiveTime?.[0])};t.value?.["@_code"]==="414285001"&&(n.category=["food"]),n.extension=this.mapTextReference(t.text);let r=t.participant?.[0]?.participantRole?.playingEntity?.code;r&&(n.code=this.mapCode(r),n.code&&r.originalText?.reference?.["@_value"]&&(n.code.extension=this.mapTextReference(r.originalText)));let o=t.entryRelationship?.find(s=>s["@_typeCode"]==="MFST")?.observation;return o&&(n.reaction=o.map(s=>this.processReaction(s))),n.asserter=this.mapAuthorToReference(t.author?.[0]),n}processConditionAct(e){let t=e.entryRelationship?.find(r=>r["@_typeCode"]==="SUBJ")?.observation?.[0];if(!t)return;let n={resourceType:"Condition",id:this.mapId(e.id),identifier:this.concatArrays(this.mapIdentifiers(e.id),this.mapIdentifiers(t.id)),meta:{profile:[_n]},clinicalStatus:{coding:[{system:Pt,code:Ie.mapCcdaToFhirWithDefault(e.statusCode?.["@_code"],"active")}]},verificationStatus:{coding:[{system:dn,code:"confirmed"}]},category:[{coding:[{system:ln,code:"problem-list-item",display:"Problem List Item"}]}],code:this.mapCode(t.value),subject:f(this.patient),onsetDateTime:m(t.effectiveTime?.[0]?.low?.["@_value"]),abatementDateTime:m(t.effectiveTime?.[0]?.high?.["@_value"]),recordedDate:this.mapEffectiveTimeToDateTime(e.effectiveTime?.[0]),recorder:this.mapAuthorToReference(t.author?.[0]),asserter:this.mapAuthorToReference(t.author?.[0])};return n.extension=this.mapTextReference(t.text),n}processCarePlanAct(e){return{resourceType:"CarePlan",id:this.mapId(e.id),identifier:this.mapIdentifiers(e.id),status:"completed",intent:"plan",title:"CARE PLAN",category:e.code?[this.mapCode(e.code)]:void 0,subject:f(this.patient),description:Te(e.text)}}processProcedureAct(e){return{resourceType:"Procedure",id:this.mapId(e.id),identifier:this.mapIdentifiers(e.id),status:"completed",code:this.mapCode(e.code),subject:f(this.patient),performedDateTime:m(e.effectiveTime?.[0]?.["@_value"]),recorder:this.mapAuthorToReference(e.author?.[0]),asserter:this.mapAuthorToReference(e.author?.[0]),extension:this.mapTextReference(e.text)}}processSubstanceAdministration(e,t){let n=e.templateId[0]["@_root"];switch(n){case Pe:case U:return this.processMedicationSubstanceAdministration(t);case X:case J:return this.processImmunizationSubstanceAdministration(t);default:if(this.options?.ignoreUnsupportedSections)return;throw new Error("Unhandled substance administration templateId: "+n)}}processMedicationSubstanceAdministration(e){let t=this.mapId(e.id),n=e.consumable?.manufacturedProduct?.[0]?.manufacturedMaterial?.[0]?.code?.[0],r=e.routeCode,o=e.doseQuantity,s=e.consumable?.manufacturedProduct?.[0]?.manufacturerOrganization?.[0],a=e.entryRelationship?.find(E=>E.substanceAdministration?.[0]?.templateId?.[0]?.["@_root"]===Be)?.substanceAdministration?.[0],h,S;return s?h={resourceType:"Medication",id:"med-"+t,code:this.mapCode(n),extension:this.mapTextReference(n?.originalText),manufacturer:s?{identifier:{value:s.id?.[0]?.["@_root"]},display:s.name?.[0]}:void 0}:S={...this.mapCode(n),extension:this.mapTextReference(n?.originalText)},{resourceType:"MedicationRequest",id:t,contained:h?[h]:void 0,meta:{profile:[mn]},extension:this.mapTextReference(e.text),status:tt.mapCcdaToFhirWithDefault(e.statusCode?.["@_code"],"active"),intent:"order",medicationReference:h?{reference:"#med-"+t}:void 0,medicationCodeableConcept:S,subject:f(this.patient),authoredOn:m(e.author?.[0]?.time?.["@_value"]),dispenseRequest:e.effectiveTime?.[0]?{validityPeriod:{start:m(e.effectiveTime?.[0]?.low?.["@_value"]),end:m(e.effectiveTime?.[0]?.high?.["@_value"])}}:void 0,dosageInstruction:[{text:typeof e.text=="string"?e.text:void 0,extension:this.mapTextReference(a?.text),route:r?this.mapCode(r):void 0,timing:{repeat:e.effectiveTime?.[1]?.period?{period:Number(e.effectiveTime?.[1]?.period["@_value"]),periodUnit:e.effectiveTime?.[1]?.period["@_unit"]}:void 0},doseAndRate:o?[{doseQuantity:{system:nt,value:Number(o["@_value"]),code:"[IU]",unit:"[IU]"}}]:void 0}]}}processImmunizationSubstanceAdministration(e){let t=e.consumable;if(!t)return;let n={resourceType:"Immunization",id:this.mapId(e.id),identifier:this.mapIdentifiers(e.id),status:et.mapCcdaToFhirWithDefault(e.statusCode?.["@_code"],"completed"),vaccineCode:this.mapCode(t.manufacturedProduct?.[0]?.manufacturedMaterial?.[0]?.code?.[0]),patient:f(this.patient),occurrenceDateTime:m(e.effectiveTime?.[0]?.["@_value"]),lotNumber:t.manufacturedProduct?.[0]?.manufacturedMaterial?.[0]?.lotNumberText?.[0]};return e.performer&&(n.performer=this.mapCcdaPerformerArrayToImmunizationPerformerArray(e.performer)),n.extension=this.mapTextReference(e.text),e.consumable?.manufacturedProduct?.[0]?.manufacturerOrganization?.[0]&&(n.manufacturer={display:e.consumable?.manufacturedProduct?.[0]?.manufacturerOrganization?.[0]?.name?.[0]}),n}processReaction(e){let t={id:this.mapId(e.id),manifestation:[this.mapCode(e.value)],onset:m(e.effectiveTime?.[0]?.low?.["@_value"])};return this.processSeverity(e,t),t.manifestation&&t.manifestation.length>0&&e.text?.reference?.["@_value"]&&(t.manifestation[0].extension=this.mapTextReference(e.text)),t}processSeverity(e,t){let n=e.entryRelationship?.find(o=>o["@_typeCode"]==="SUBJ")?.observation?.[0];if(!n)return;let r=n.value?.["@_code"];r&&(t.severity=Ke.mapCcdaToFhir(r)),t.extension=this.mapTextReference(n.text)}mapEffectiveTimeToDateTime(e){if(e?.["@_value"])return m(e["@_value"]);if(e?.low?.["@_value"])return m(e.low["@_value"])}mapEffectiveTimeToPeriod(e){if(!e?.["@_value"]&&(e?.low||e?.high))return{start:m(e?.low?.["@_value"]),end:m(e?.high?.["@_value"])}}mapGenderCode(e){return e?{F:"female",M:"male",UN:"unknown"}[e]:void 0}getTelecomSystem(e){if(e)return e.startsWith("tel:")?"phone":e.startsWith("mailto:")?"email":"other"}getTelecomValue(e){if(e)return e.replace(/^(tel:|mailto:)/,"")}mapCode(e){if(!e)return;let t={coding:[{system:Ee(e["@_codeSystem"]),code:e["@_code"],display:e["@_displayName"]}],text:e["@_displayName"]};if(e.translation)for(let n of e.translation)t.coding.push({system:Ee(n["@_codeSystem"]),code:n["@_code"],display:n["@_displayName"]});return t}mapCodeToCoding(e){if(e)return{system:Ee(e["@_codeSystem"]),code:e["@_code"],display:e["@_displayName"]}}createClinicalStatus(e){return{coding:[{system:ke,code:Je.mapCcdaToFhirWithDefault(e.statusCode?.["@_code"],"active")}]}}createVerificationStatus(){return{coding:[{system:Lt,code:"confirmed"}]}}mapAuthorToReference(e){if(!e)return;let t={resourceType:"Practitioner",id:this.mapId(e.assignedAuthor?.id),identifier:this.mapIdentifiers(e.assignedAuthor?.id),name:this.mapCcdaNameArrayFhirHumanNameArray(e.assignedAuthor?.assignedPerson?.name),address:this.mapAddresses(e.assignedAuthor?.addr),telecom:this.mapTelecom(e.assignedAuthor?.telecom),qualification:e.assignedAuthor?.code?[this.mapCode(e.assignedAuthor?.code)]:void 0};return this.resources.push(t),f(t)}mapAssignedEntityToReference(e){if(!e)return;let t=e.assignedPerson,n=e.representedOrganization,r={resourceType:"Practitioner",id:this.mapId(e?.id),identifier:this.mapIdentifiers(e?.id),name:this.mapCcdaNameArrayFhirHumanNameArray(t?.name),address:this.mapAddresses(e?.addr),telecom:this.mapTelecom(e?.telecom)};this.resources.push(r);let o={resourceType:"Organization",id:this.mapId(e?.id),identifier:this.mapIdentifiers(n?.id),name:n?.name?.[0],address:this.mapAddresses(n?.addr)};this.resources.push(o);let s={resourceType:"PractitionerRole",id:this.mapId(e?.id),practitioner:f(r),organization:f(o)};return this.resources.push(s),f(s)}mapCustodianToReference(e){if(!e)return;let t={resourceType:"Organization",id:this.mapId(e.assignedCustodian.representedCustodianOrganization.id),identifier:this.mapIdentifiers(e.assignedCustodian.representedCustodianOrganization.id),name:e.assignedCustodian.representedCustodianOrganization.name?.[0],address:this.mapAddresses(e.assignedCustodian.representedCustodianOrganization.addr),telecom:this.mapTelecom(e.assignedCustodian.representedCustodianOrganization.telecom)};return this.resources.push(t),f(t)}mapDocumentationOfToEvent(e){if(!e)return;let t=e.serviceEvent;if(t)return[{code:t.code?[this.mapCode(t.code)]:void 0,period:this.mapEffectiveTimeToPeriod(t.effectiveTime?.[0])}]}concatArrays(e,t){return e?t?[...e,...t]:e:t}mapCcdaPerformerArrayToImmunizationPerformerArray(e){let t=[];for(let n of e){let r=n.assignedEntity,o=this.mapAssignedEntityToReference(r);o&&t.push({actor:o})}return t}processOrganizer(e,t){return e.templateId[0]["@_root"]===Me?this.processCareTeamOrganizer(t):this.processVitalsOrganizer(t)}processCareTeamOrganizer(e){let t=[];if(e.component)for(let r of e.component){let o=this.processCareTeamMember(r);o&&t.push(o)}return{resourceType:"CareTeam",id:this.mapId(e.id),identifier:this.mapIdentifiers(e.id),participant:t.length>0?t:void 0}}processCareTeamMember(e){let t=e.act?.[0];if(!t)return;let n=t.performer?.[0];if(n)return{role:n.functionCode?[this.mapCode(n.functionCode)]:void 0,member:this.mapAssignedEntityToReference(n.assignedEntity),period:this.mapEffectiveTimeToPeriod(t.effectiveTime?.[0])}}processVitalsOrganizer(e){let t={resourceType:"Observation",id:this.mapId(e.id),identifier:this.mapIdentifiers(e.id),status:"final",category:this.mapObservationTemplateIdToObservationCategory(e.templateId),code:this.mapCode(e.code),subject:f(this.patient)};if(e.effectiveTime?.[0]?.["@_value"]&&(t.effectiveDateTime=m(e.effectiveTime?.[0]?.["@_value"])),e.component){let n=[];for(let r of e.component)n.push(...this.processVitalsComponent(r));n.length>0&&(t.hasMember=n)}return t}processVitalsComponent(e){let t=[];if(e.observation)for(let n of e.observation){let r=this.processVitalsObservation(n);t.push(f(r)),this.resources.push(r)}return t}processObservation(e,t){let n=t.templateId[0]["@_root"];if(n===te||n===we)return this.processGoalObservation(t);switch(e.templateId[0]["@_root"]){case U:case te:return this.processGoalObservation(t);default:return this.processVitalsObservation(t)}}processGoalObservation(e){let t={resourceType:"Goal",id:this.mapId(e.id),identifier:this.mapIdentifiers(e.id),lifecycleStatus:this.mapGoalLifecycleStatus(e),description:this.mapCode(e.code),subject:f(this.patient),startDate:ut(e.effectiveTime?.[0]?.["@_value"])};return t.target=e.entryRelationship?.map(n=>({measure:this.mapCode(n.act?.[0]?.code),detailCodeableConcept:this.mapCode(n.act?.[0]?.code),dueDate:m(n.act?.[0]?.effectiveTime?.[0]?.low?.["@_value"])})),t.extension=this.mapTextReference(e.text),t}mapGoalLifecycleStatus(e){return{active:"active",completed:"completed",cancelled:"cancelled",aborted:"cancelled"}[e.statusCode["@_code"]??"active"]}processVitalsObservation(e){let t={resourceType:"Observation",id:this.mapId(e.id),identifier:this.mapIdentifiers(e.id),status:"final",category:this.mapObservationTemplateIdToObservationCategory(e.templateId),code:this.mapCode(e.code),subject:f(this.patient),referenceRange:this.mapReferenceRangeArray(e.referenceRange),performer:e.author?.map(n=>this.mapAuthorToReference(n)).filter(Boolean)};if(e.value?.["@_xsi:type"])switch(e.value["@_xsi:type"]){case"PQ":case"CO":t.valueQuantity={value:e.value["@_value"]?parseFloat(e.value["@_value"]):void 0,unit:e.value["@_unit"],system:nt,code:e.value["@_unit"]};break;case"CD":case"CE":t.valueCodeableConcept=this.mapCode(e.value);break;case"ST":t.valueString=e.value["#text"]??"";break;default:console.warn(`Unhandled observation value type: ${e.value["@_xsi:type"]}`)}return e.effectiveTime?.[0]?.["@_value"]&&(t.effectiveDateTime=m(e.effectiveTime?.[0]?.["@_value"])),t.extension=this.mapTextReference(e.text),t}mapObservationTemplateIdToObservationCategory(e){if(!e)return;let t=new Set,n=[];for(let r of e){let o=$n.mapCcdaToFhirCodeableConcept(r["@_root"]);o?.coding?.[0]?.code&&!t.has(o.coding[0].code)&&(t.add(o.coding[0].code),n.push(o))}return Array.from(n.values())}mapReferenceRangeArray(e){if(!(!e||e.length===0))return e.map(t=>this.mapReferenceRange(t)).filter(Boolean)}mapReferenceRange(e){if(!e)return;let t=e.observationRange;if(!t)return;let n={};return n.extension=this.mapTextReference(t.text),n}processEncounter(e,t){let n={resourceType:"Encounter",id:this.mapId(t.id),identifier:this.mapIdentifiers(t.id),status:Yn.mapCcdaToFhirWithDefault(t.statusCode?.["@_code"],"unknown"),class:{system:pn,code:t.code?.["@_code"]??"AMB",display:t.code?.["@_displayName"]??"Ambulatory"},type:t.code?[this.mapCode(t.code)]:void 0,subject:f(this.patient),period:this.mapEffectiveTimeToPeriod(t.effectiveTime?.[0])};if(t.performer&&(n.participant=t.performer.map(r=>({type:[{coding:[{system:hn,code:r["@_typeCode"]??"PPRF",display:"Primary Performer"}]}],individual:this.mapAssignedEntityToReference(r.assignedEntity)}))),t.entryRelationship){let r=t.entryRelationship.filter(o=>o["@_typeCode"]==="RSON").map(o=>{let s=o.observation?.[0];if(!s)return;let a={resourceType:"Condition",id:this.mapId(s.id),identifier:this.mapIdentifiers(s.id),clinicalStatus:{coding:[{system:Pt,code:"active"}]},verificationStatus:{coding:[{system:bt,code:"confirmed"}]},code:this.mapCode(s.value),subject:f(this.patient),onsetDateTime:m(s.effectiveTime?.[0]?.low?.["@_value"])};return this.resources.push(a),{condition:f(a),use:{coding:[{system:fn,code:"AD",display:"Admission diagnosis"}]}}}).filter(Boolean);r.length>0&&(n.diagnosis=r)}return n.extension=this.mapTextReference(t.text),n}processProcedure(e,t){return{resourceType:"Procedure",id:this.mapId(t.id),identifier:this.mapIdentifiers(t.id),status:Hn.mapCcdaToFhirWithDefault(t.statusCode?.["@_code"],"completed"),code:this.mapCode(t.code),subject:f(this.patient),performedPeriod:this.mapEffectiveTimeToPeriod(t.effectiveTime?.[0]),bodySite:t.targetSiteCode?[this.mapCode(t.targetSiteCode)]:void 0,extension:this.mapTextReference(t.text)}}mapTextReference(e){if(!(!e||typeof e!="object")&&e?.reference?.["@_value"])return[{url:Ye,valueString:e.reference?.["@_value"]}]}};function Te(i){if(i){if(typeof i=="string")return i;if(typeof i=="object"&&"#text"in i)return i["#text"]}}var zn=[{"@_root":Z,"@_extension":"2015-08-01"},{"@_root":Z},{"@_root":pt,"@_extension":"2015-08-01"},{"@_root":pt}],Zn=[{"@_root":Z,"@_extension":"2015-08-01"},{"@_root":Z},{"@_root":ht,"@_extension":"2015-08-01"},{"@_root":ht}],go=[{"@_root":ee,"@_extension":"2015-08-01"},{"@_root":ee}],Ao=[{"@_root":Pe,"@_extension":"2014-06-09"}],No=[{"@_root":K,"@_extension":"2015-08-01"},{"@_root":K}],Ro=[{"@_root":X},{"@_root":X,"@_extension":"2015-08-01"},{"@_root":J},{"@_root":J,"@_extension":"2015-08-01"}],Do=[{"@_root":Ei,"@_extension":"2015-08-01"}],vo=[{"@_root":_t},{"@_root":_t,"@_extension":"2015-08-01"}],xo=[{"@_root":Y,"@_extension":"2014-06-09"}],ua=[{"@_root":U,"@_extension":"2014-06-09"}],da=[{"@_root":ft,"@_extension":"2015-08-01"}],Po=[{"@_root":ft,"@_extension":"2015-08-01"}],bo=[{"@_root":Ai,"@_extension":"2015-08-01"}],Lo=[{"@_root":be}],Uo=[{"@_root":U},{"@_root":U,"@_extension":"2014-06-09"}],Vo=[{"@_root":gi,"@_extension":"2015-08-01"}],Mo=[{"@_root":te}],wo=[{"@_root":Ue,"@_extension":"2015-08-01"}],Bo=[{"@_root":B,"@_extension":"2014-06-09"}],Fo=[{"@_root":Ni,"@_extension":"2015-08-01"}],ko=[{"@_root":Ve,"@_extension":"2016-11-01"}],Go=[{"@_root":Me,"@_extension":"2022-06-01"}],Yo=[{"@_root":Le,"@_extension":"2015-08-01"}],Xn=Object.fromEntries([[In,go],[On,Ao],[He,No],[Tn,Ro],[Cn,Do],[yn,vo],[gn,xo],[Sn,Po],[je,Lo],[$e,Uo],[Nn,Vo],[fe,Mo],[_e,wo],[me,Bo],[Dn,Fo],[qe,ko],[vn,Go],[xn,Yo],[An,bo]]);function Ia(i,e){return new Vt(i,e).convert()}var Vt=class{constructor(e,t){this.bundle=e,this.options=t;let n=this.findResource("Composition");if(!n)throw new Error("Composition not found");let r=this.findResource("Patient");if(!r)throw new Error("Patient not found");this.composition=n,this.patient=r}convert(){let e=this.createSections(),t=this.composition.section?.find(o=>o.code?.coding?.[0]?.code===me)?.entry?.find(o=>o.reference?.startsWith("ServiceRequest/")),n,r;return this.options?.type==="referral"?(n=Zn,r={"@_code":Rn,"@_displayName":"Referral Note","@_codeSystem":N,"@_codeSystemName":"LOINC"}):(n=zn,r={"@_code":We,"@_displayName":"Summarization of Episode Note","@_codeSystem":N,"@_codeSystemName":"LOINC"}),{realmCode:{"@_code":"US"},typeId:{"@_root":ii,"@_extension":"POCD_HD000040"},templateId:n,id:this.mapIdentifiers(this.composition.id,void 0),code:r,title:this.composition.title,effectiveTime:this.mapEffectiveTime(this.composition.date,void 0),confidentialityCode:this.composition.confidentiality?Fn.mapFhirToCcdaCode(this.composition.confidentiality):void 0,languageCode:{"@_code":this.composition.language??"en-US"},recordTarget:this.createRecordTarget(),author:this.mapAuthor(this.composition.author?.[0],this.composition.date,!0),custodian:this.mapCustodian(this.composition.custodian),informationRecipient:this.mapRecipient(t),documentationOf:this.mapDocumentationOf(this.composition.event),component:e.length>0?{structuredBody:{component:e.map(o=>({section:[o]}))}}:void 0}}findResource(e){return this.bundle.entry?.find(t=>t.resource?.resourceType===e)?.resource}findResourceByReference(e){if(!e?.reference)return;let[t,n]=e.reference.split("/");if(!(!t||!n))return this.bundle.entry?.find(r=>r.resource?.resourceType===t&&r.resource?.id===n)?.resource}findResourcesByReferences(e){return e?e.map(t=>this.findResourceByReference(t)).filter(t=>!!t):[]}createRecordTarget(){if(!this.patient)throw new Error("Patient not found");return[{patientRole:{id:this.mapIdentifiers(this.patient.id,this.patient.identifier),addr:this.mapFhirAddressArrayToCcdaAddressArray(this.patient.address),telecom:this.mapTelecom(this.patient.telecom),patient:this.mapPatient(this.patient)}}]}mapPatient(e){return{name:this.mapNames(e.name),administrativeGenderCode:this.mapGender(e.gender),birthTime:this.mapBirthDate(e.birthDate),raceCode:this.mapRace(e),"sdtc:raceCode":this.mapDetailedRace(e),ethnicGroupCode:this.mapEthnicity(e.extension),languageCommunication:this.mapLanguageCommunication(e.communication)}}mapNames(e){return e?.map(t=>({"@_use":t.use?ze.mapFhirToCcdaWithDefault(t.use,"L"):void 0,prefix:t.prefix,family:t.family,given:t.given,suffix:t.suffix}))}mapGender(e){if(e)return{"@_code":kn.mapFhirToCcda(e),"@_displayName":e?Q(e):"Unknown","@_codeSystem":De,"@_codeSystemName":"AdministrativeGender"}}mapBirthDate(e){if(e)return{"@_value":e.replace(/-/g,"")}}mapFhirAddressArrayToCcdaAddressArray(e){return!e||e.length===0?[{"@_nullFlavor":"UNK"}]:e.map(t=>this.mapFhirAddressToCcdaAddress(t)).filter(Boolean)}mapFhirAddressToCcdaAddress(e){return e?{"@_use":e.use?Ze.mapFhirToCcda(e.use):void 0,streetAddressLine:e.line||[],city:e.city,state:e.state,postalCode:e.postalCode,country:e.country}:void 0}mapRace(e){let t=Ne(e,he,"ombCategory")?.valueCoding;return t?[{"@_code":t.code,"@_displayName":t.display,"@_codeSystem":xe,"@_codeSystemName":"CDC Race and Ethnicity"}]:[{"@_nullFlavor":"UNK"}]}mapDetailedRace(e){let t=Ne(e,he,"detailed")?.valueCoding;if(t)return[{"@_code":t.code,"@_displayName":t.display,"@_codeSystem":xe,"@_codeSystemName":"CDC Race and Ethnicity"}]}mapEthnicity(e){let n=e?.find(r=>r.url===Ge)?.extension?.find(r=>r.url==="ombCategory")?.valueCoding;return n?[{"@_code":n.code,"@_displayName":n.display,"@_codeSystem":xe,"@_codeSystemName":"CDC Race and Ethnicity"}]:[{"@_nullFlavor":"UNK"}]}mapLanguageCommunication(e){if(e?.length)return[{languageCode:{"@_code":e[0].language?.coding?.[0]?.code}}]}createSections(){let e=[];if(this.composition.section)for(let t of this.composition.section)e.push(this.createSection(t));return e}createSection(e){let t=e.code?.coding?.[0]?.code;if(!t)throw new Error(`Missing section code: ${JSON.stringify(e.code)}`);let n=Xn[t];if(!n)throw new Error(`Unknown section code: ${t}`);let r=this.findResourcesByReferences(e.entry);return t===je&&r.length===1&&r[0].resourceType==="ClinicalImpression"?this.createClinicalImpressionSection(e,r[0]):t===me&&r.length===1&&r[0].resourceType==="ServiceRequest"?this.createReasonForReferralSection(e,r[0]):{templateId:n,code:p(e.code),title:e.title,text:this.mapFhirTextDivToCcdaSectionText(e.text),entry:r.map(o=>this.createEntry(e,o)).filter(Boolean),"@_nullFlavor":r.length===0?"NI":void 0}}createEntry(e,t){switch(t.resourceType){case"AllergyIntolerance":return this.createAllergyEntry(t);case"CarePlan":return this.createPlanOfTreatmentCarePlanEntry(t);case"CareTeam":return this.createCareTeamEntry(t);case"ClinicalImpression":return this.createClinicalImpressionEntry(t);case"Condition":return this.createConditionEntry(e,t);case"DeviceUseStatement":return this.createDeviceUseStatementEntry(t);case"DiagnosticReport":return this.createDiagnosticReportEntry(t);case"Encounter":return this.createEncounterEntry(t);case"Goal":return this.createGoalEntry(e,t);case"Immunization":return this.createImmunizationEntry(t);case"MedicationRequest":return this.createMedicationEntry(t);case"Procedure":return this.createHistoryOfProceduresEntry(t);case"Observation":return this.createObservationEntry(t);case"ServiceRequest":return this.createPlanOfTreatmentServiceRequestEntry(t);default:return}}mapFhirTextDivToCcdaSectionText(e){if(!e)return;let t=Wn(e.div)?.div;return t?.["@_xmlns"]&&delete t["@_xmlns"],t}createAllergyEntry(e){let t=e.reaction?.[0];return{act:[{"@_classCode":"ACT","@_moodCode":"EVN",templateId:[{"@_root":yt},{"@_root":yt,"@_extension":"2015-08-01"}],id:this.mapIdentifiers(e.id,e.identifier),code:{"@_code":"CONC","@_codeSystem":dt},statusCode:{"@_code":Je.mapFhirToCcdaWithDefault(e.clinicalStatus?.coding?.[0]?.code,"active")},effectiveTime:this.mapEffectivePeriod(e.recordedDate,void 0),author:this.mapAuthor(e.recorder,e.recordedDate),text:this.createTextFromExtensions(e.extension),entryRelationship:[{"@_typeCode":"SUBJ",observation:[{"@_classCode":"OBS","@_moodCode":"EVN",templateId:[{"@_root":Et},{"@_root":Et,"@_extension":"2014-06-09"}],id:this.mapIdentifiers(e.id,e.identifier),code:{"@_code":"ASSERTION","@_codeSystem":ve},text:this.createTextFromExtensions(e.extension),statusCode:{"@_code":"completed"},effectiveTime:this.mapEffectivePeriod(e.onsetPeriod?.start??e.onsetDateTime,e.onsetPeriod?.end,!0),value:this.mapAllergyCategory(e.category),author:this.mapAuthor(e.asserter,e.recordedDate),participant:[{"@_typeCode":"CSM",participantRole:{"@_classCode":"MANU",playingEntity:{"@_classCode":"MMAT",code:e.code?.coding?.[0]?.code==="716186003"?{"@_nullFlavor":"NA"}:{...p(e.code),originalText:e.code?.extension?{reference:this.getNarrativeReference(e.code?.extension)}:void 0}}}}],entryRelationship:t?[{"@_typeCode":"MFST","@_inversionInd":"true",observation:[{"@_classCode":"OBS","@_moodCode":"EVN",templateId:[{"@_root":Tt},{"@_root":Tt,"@_extension":"2014-06-09"}],id:this.mapIdentifiers(t.id,void 0),code:{"@_code":"ASSERTION","@_codeSystem":ve},statusCode:{"@_code":"completed"},effectiveTime:this.mapEffectiveDate(e.onsetDateTime,e.onsetPeriod),value:H(t.manifestation?.[0]),text:this.createTextFromExtensions(t.manifestation?.[0]?.extension),entryRelationship:[{"@_typeCode":"SUBJ","@_inversionInd":"true",observation:[{"@_classCode":"OBS","@_moodCode":"EVN",templateId:[{"@_root":It},{"@_root":It,"@_extension":"2014-06-09"}],code:{"@_code":"SEV","@_codeSystem":ve,"@_codeSystemName":"ActCode"},statusCode:{"@_code":"completed"},value:{"@_xsi:type":"CD","@_code":Ke.mapFhirToCcdaWithDefault(t.severity,"M"),"@_displayName":t.severity?Q(t.severity):void 0,"@_codeSystem":L,"@_codeSystemName":"SNOMED CT"},text:this.createTextFromExtensions(t.extension)}]}]}]}]:[]}]}]}]}}mapAllergyCategory(e){let t=Gn.mapFhirToCcdaCode(e?.[0]);return t||(t={"@_code":"419199007","@_displayName":"Allergy to substance (disorder)","@_codeSystem":L,"@_codeSystemName":"SNOMED CT"}),{"@_xsi:type":"CD",...t}}mapAuthor(e,t,n){if(!e)return;let r=this.findResourceByReference(e);if(!r)return;let o;if(r.resourceType==="Organization"?o=r:r.resourceType==="PractitionerRole"&&(o=this.findResourceByReference(r.organization),r=this.findResourceByReference(r.practitioner)),!r)return;let s;"address"in r&&(s=r.address);let a;"telecom"in r&&(a=r.telecom);let h;"qualification"in r&&(h=r.qualification?.[0]);let S;return["Patient","Practitioner","RelatedPerson"].includes(r.resourceType)&&(S=r.name),[{templateId:[{"@_root":ji}],time:t?{"@_value":O(t)}:void 0,assignedAuthor:{id:this.mapIdentifiers(r.id,r.identifier),addr:this.mapFhirAddressArrayToCcdaAddressArray(s),telecom:this.mapTelecom(a),code:p(h),assignedPerson:S?{name:this.mapNames(S)}:void 0,assignedAuthoringDevice:!S&&n?{manufacturerModelName:"Medplum",softwareName:"Medplum"}:void 0,representedOrganization:o?.name?{name:[o.name]}:void 0}}]}mapCustodian(e){if(!e)return;let t=this.findResourceByReference(e);if(t)return{assignedCustodian:{representedCustodianOrganization:{id:this.mapIdentifiers(t.id,t.identifier),name:t.name?[t.name]:void 0,telecom:this.mapTelecom(t.telecom),addr:this.mapFhirAddressArrayToCcdaAddressArray(t.address)}}}}mapRecipient(e){if(!e)return;let t=this.findResourceByReference(e);if(!t)return;let n=t.performer;if(!n||n.length===0)return;let r=this.findResourceByReference(n[0]);if(!(!r||r.resourceType!=="Practitioner"))return{intendedRecipient:{informationRecipient:{name:this.mapNames(r.name)}}}}mapDocumentationOf(e){if(!e||e.length===0)return;let t=e[0];if(!(!t||!t.code&&!t.period))return{serviceEvent:{"@_classCode":"PCPR",code:p(t.code?.[0]),effectiveTime:this.mapEffectiveDate(void 0,t.period)}}}createMedicationEntry(e){let t=e.contained?.find(s=>s.resourceType==="Medication"),n=t?.code||e.medicationCodeableConcept,r=t?.manufacturer,o=[];if(e.dispenseRequest?.validityPeriod){let s=this.mapEffectiveDate(void 0,e.dispenseRequest.validityPeriod);s&&o.push(...s)}return e.dosageInstruction?.[0]?.timing?.repeat?.period&&o.push({"@_xsi:type":"PIVL_TS","@_institutionSpecified":"true","@_operator":"A",period:{"@_value":e.dosageInstruction[0].timing.repeat.period.toString(),"@_unit":e.dosageInstruction[0].timing.repeat.periodUnit}}),{substanceAdministration:[{"@_classCode":"SBADM","@_moodCode":"EVN",templateId:[{"@_root":Ot,"@_extension":"2014-06-09"},{"@_root":Ot}],id:[{"@_root":e.id||crypto.randomUUID()}],text:this.createTextFromExtensions(e.extension),statusCode:{"@_code":tt.mapFhirToCcdaWithDefault(e.status,"active")},effectiveTime:o,routeCode:this.mapMedicationRoute(e.dosageInstruction?.[0]?.route),doseQuantity:this.mapDoseQuantity(e.dosageInstruction?.[0]?.doseAndRate?.[0]),consumable:{"@_typeCode":"CSM",manufacturedProduct:[{"@_classCode":"MANU",templateId:[{"@_root":St,"@_extension":"2014-06-09"},{"@_root":St}],manufacturedMaterial:[{code:[{...p(n),originalText:this.createTextFromExtensions(t?.extension)}]}],manufacturerOrganization:r?[{id:this.mapIdentifiers(r.id,r.identifier?[r.identifier]:void 0),name:[r.display]}]:void 0}]},author:this.mapAuthor(e.requester,e.authoredOn),entryRelationship:e.dosageInstruction?.filter(s=>!!s.extension)?.map(s=>({"@_typeCode":"COMP",substanceAdministration:[{"@_classCode":"SBADM","@_moodCode":"EVN",templateId:[{"@_root":Be}],code:{"@_code":Pn,"@_codeSystem":N,"@_codeSystemName":"LOINC","@_displayName":"Medication Instructions"},text:this.createTextFromExtensions(s.extension),consumable:{manufacturedProduct:[{manufacturedLabeledDrug:[{"@_nullFlavor":"NA"}]}]}}]}))}]}}mapMedicationRoute(e){if(e)return p(e)}mapDoseQuantity(e){if(e?.doseQuantity)return{"@_value":e.doseQuantity.value?.toString(),"@_unit":e.doseQuantity.unit}}mapTelecom(e){return!e||e.length===0?[{"@_nullFlavor":"UNK"}]:e?.map(t=>({"@_use":t.use?Xe.mapFhirToCcda(t.use):void 0,"@_value":`${this.mapTelecomSystemToPrefix(t.system)}${t.value}`}))}mapTelecomSystemToPrefix(e){return e==="email"?"mailto:":e==="phone"?"tel:":e==="fax"?"fax:":""}mapIdentifiers(e,t){let n=[];if(e&&n.push({"@_root":e}),t)for(let r of t){let o=Bn(r.system);o&&n.push({"@_root":o,"@_extension":r.value})}return n}getNarrativeReference(e){let t=e?.find(n=>n.url===Ye)?.valueString;return t?{"@_value":t}:void 0}createTextFromExtensions(e){let t=this.getNarrativeReference(e);return t?{reference:t}:void 0}createConditionEntry(e,t){let n=e.code?.coding?.[0]?.code;if(n===He)return this.createProblemEntry(t);if(n===_e)return this.createHealthConcernEntry(t)}createProblemEntry(e){return{act:[{"@_classCode":"ACT","@_moodCode":"EVN",templateId:[{"@_root":mt},{"@_root":mt,"@_extension":"2015-08-01"}],id:this.mapIdentifiers(e.id,void 0),code:{"@_code":"CONC","@_codeSystem":dt},statusCode:{"@_code":Ie.mapFhirToCcdaWithDefault(e.clinicalStatus?.coding?.[0]?.code,"active")},effectiveTime:this.mapEffectivePeriod(e.recordedDate,void 0),entryRelationship:[{"@_typeCode":"SUBJ",observation:[{"@_classCode":"OBS","@_moodCode":"EVN",templateId:[{"@_root":F},{"@_root":F,"@_extension":"2015-08-01"}],id:e.identifier?this.mapIdentifiers(void 0,e.identifier):[{"@_root":Re()}],text:this.createTextFromExtensions(e.extension),code:{"@_code":"55607006","@_codeSystem":L,"@_codeSystemName":"SNOMED CT","@_displayName":"Problem",translation:[{"@_code":bn,"@_codeSystem":N,"@_codeSystemName":"LOINC","@_displayName":"Condition"}]},statusCode:{"@_code":"completed"},effectiveTime:[{low:e.onsetDateTime?{"@_value":w(e.onsetDateTime)}:void 0,high:e.abatementDateTime?{"@_value":O(e.abatementDateTime)}:void 0}],value:H(e.code),author:this.mapAuthor(e.asserter,e.recordedDate)}]}]}]}}createHealthConcernEntry(e){return{act:[{"@_classCode":"ACT","@_moodCode":"EVN",templateId:[{"@_root":Rt,"@_extension":"2015-08-01"},{"@_root":Rt,"@_extension":"2022-06-01"}],id:this.mapIdentifiers(e.id,void 0),code:{"@_code":_e,"@_codeSystem":N,"@_codeSystemName":"LOINC","@_displayName":"Health Concern"},statusCode:{"@_code":Ie.mapFhirToCcdaWithDefault(e.clinicalStatus?.coding?.[0]?.code,"active")},effectiveTime:this.mapEffectivePeriod(e.recordedDate,void 0)}]}}createImmunizationEntry(e){let t=e?.manufacturer,n={substanceAdministration:[{"@_classCode":"SBADM","@_moodCode":"EVN","@_negationInd":"false",templateId:[{"@_root":At},{"@_root":At,"@_extension":"2015-08-01"}],id:this.mapIdentifiers(e.id,e.identifier),text:this.createTextFromExtensions(e.extension),statusCode:{"@_code":et.mapFhirToCcdaWithDefault(e.status,"completed")},effectiveTime:[{"@_value":w(e.occurrenceDateTime)}],consumable:{manufacturedProduct:[{"@_classCode":"MANU",templateId:[{"@_root":Nt},{"@_root":Nt,"@_extension":"2014-06-09"}],manufacturedMaterial:[{code:[p(e.vaccineCode)],lotNumberText:e.lotNumber?[e.lotNumber]:void 0}],manufacturerOrganization:t?[{id:this.mapIdentifiers(t.id,t.identifier?[t.identifier]:void 0),name:[t.display]}]:void 0}]}}]};return e.performer&&(n.substanceAdministration[0].performer=e.performer.map(r=>this.mapImmunizationPerformerToCcdaPerformer(r)).filter(Boolean)),n}mapImmunizationPerformerToCcdaPerformer(e){if(!e)return;let t=this.findResourceByReference(e.actor);if(!t)return;let n,r;return t.resourceType==="PractitionerRole"?(n=this.findResourceByReference(t.practitioner),r=this.findResourceByReference(t.organization)):t.resourceType==="Practitioner"?n=t:t.resourceType==="Organization"&&(r=t),{assignedEntity:{id:this.mapIdentifiers(t.id,t.identifier),addr:this.mapFhirAddressArrayToCcdaAddressArray(n?.address),telecom:this.mapTelecom(t.telecom),assignedPerson:n?{id:this.mapIdentifiers(n.id,n.identifier),name:this.mapNames(n.name)}:void 0,representedOrganization:r?{id:this.mapIdentifiers(r.id,r.identifier),name:r.name?[r.name]:void 0,addr:this.mapFhirAddressArrayToCcdaAddressArray(r.address),telecom:this.mapTelecom(r.telecom)}:void 0}}}createObservationEntry(e){return e.hasMember?{organizer:[this.createVitalSignsOrganizer(e)]}:{observation:[this.createVitalSignObservation(e)]}}createPlanOfTreatmentCarePlanEntry(e){if(e.status==="completed")return{act:[{"@_classCode":"ACT","@_moodCode":"INT",templateId:[{"@_root":xi}],id:this.mapIdentifiers(e.id,e.identifier),code:H(e.category?.[0]),text:e.description?{"#text":e.description}:this.createTextFromExtensions(e.extension),statusCode:{"@_code":e.status}}]}}createGoalEntry(e,t){let n=e.code?.coding?.[0]?.code,r;if(n===$e)r=[{"@_root":gt}];else if(n===fe)r=[{"@_root":we}];else return;let o;if(n===fe)o={"@_code":Ln,"@_codeSystem":N,"@_codeSystemName":"LOINC","@_displayName":"Resident's overall goal established during assessment process"};else if(t.description)o=p(t.description);else return;return{observation:[{"@_classCode":"OBS","@_moodCode":"GOL",templateId:r,id:this.mapIdentifiers(t.id,t.identifier),code:o,statusCode:{"@_code":this.mapPlanOfTreatmentStatus(t.lifecycleStatus)},effectiveTime:[{"@_value":O(t.startDate)}],value:t.description?.text?{"@_xsi:type":"ST","#text":t.description.text}:void 0,text:this.createTextFromExtensions(t.extension),entryRelationship:t.target?.map(s=>({"@_typeCode":"RSON","@_inversionInd":"true",act:[{"@_classCode":"ACT","@_moodCode":"EVN",templateId:[{"@_root":re},{"@_root":re,"@_extension":"2014-06-09"}],code:p(s.measure),statusCode:{"@_code":"completed"},effectiveTime:[{"@_value":O(t.startDate)}]}]}))}]}}mapPlanOfTreatmentStatus(e){switch(e){case"achieved":return"completed";case"cancelled":return"cancelled";default:return"active"}}createVitalSignsOrganizer(e){let t=[];if(e.hasMember)for(let r of e.hasMember){let o=this.findResourceByReference(r);if(!(!o||o.resourceType!=="Observation"))if(o.component)for(let s of o.component)t.push({observation:[this.createVitalSignComponentObservation(o,s)]});else t.push({observation:[this.createVitalSignObservation(o)]})}return{"@_classCode":"CLUSTER","@_moodCode":"EVN",templateId:[{"@_root":ae},{"@_root":ae,"@_extension":"2015-08-01"}],id:this.mapIdentifiers(e.id,e.identifier),code:p(e.code),statusCode:{"@_code":"completed"},effectiveTime:[{"@_value":O(e.effectiveDateTime)}],component:t}}createVitalSignObservation(e){return{"@_classCode":"OBS","@_moodCode":"EVN",templateId:this.mapObservationTemplateId(e),id:this.mapIdentifiers(e.id,e.identifier),code:p(e.code),statusCode:{"@_code":"completed"},effectiveTime:[{"@_value":O(e.effectiveDateTime)}],value:this.mapObservationValue(e),referenceRange:this.mapReferenceRangeArray(e.referenceRange),text:this.createTextFromExtensions(e.extension),author:this.mapAuthor(e.performer?.[0],e.effectiveDateTime)}}createVitalSignComponentObservation(e,t){return{"@_classCode":"OBS","@_moodCode":"EVN",templateId:this.mapObservationTemplateId(e),id:this.mapIdentifiers(e.id,e.identifier),code:p(t.code),statusCode:{"@_code":"completed"},effectiveTime:[{"@_value":O(e.effectiveDateTime)}],value:this.mapObservationValue(t),referenceRange:this.mapReferenceRangeArray(t.referenceRange),text:this.createTextFromExtensions(t.extension),author:this.mapAuthor(e.performer?.[0],e.effectiveDateTime)}}mapObservationTemplateId(e){let t=e.code?.coding?.[0]?.code,n=e.category?.[0]?.coding?.[0]?.code;return t===Un?[{"@_root":de},{"@_root":de,"@_extension":"2014-06-09"}]:t===Vn?[{"@_root":le},{"@_root":le,"@_extension":"2014-06-09"}]:t===Mn?[{"@_root":Fe,"@_extension":"2023-06-28"}]:t===wn?[{"@_root":pe},{"@_root":pe,"@_extension":"2016-06-01"}]:n==="exam"?[{"@_root":oe},{"@_root":oe,"@_extension":"2014-06-09"}]:n==="laboratory"?[{"@_root":ne},{"@_root":ne,"@_extension":"2015-08-01"}]:[{"@_root":ce},{"@_root":ce,"@_extension":"2014-06-09"}]}mapObservationValue(e){if(e.valueQuantity)return{"@_xsi:type":"PQ","@_unit":e.valueQuantity.unit,"@_value":e.valueQuantity.value?.toString()};if(e.valueCodeableConcept)return H(e.valueCodeableConcept);if(e.valueString)return{"@_xsi:type":"ST","#text":e.valueString}}mapReferenceRangeArray(e){if(!(!e||e.length===0))return e.map(t=>this.mapReferenceRange(t)).filter(Boolean)}mapReferenceRange(e){if(!e)return;let t=this.getNarrativeReference(e.extension);return t?{observationRange:{text:{reference:t},value:{"@_xsi:type":"ED",reference:t}}}:{observationRange:{text:this.createTextFromExtensions(e.extension)}}}createHistoryOfProceduresEntry(e){if(e.resourceType==="Procedure"){let t=["183948003","409063005","311331002","61310001","183945009","309814009","278373008","410606002","183933003","24642003","225338006","128939004"],n=e.code?.coding?.[0]?.code;return n&&t.includes(n)?{act:[{"@_classCode":"ACT","@_moodCode":"EVN",templateId:[{"@_root":re},{"@_root":re,"@_extension":"2014-06-09"}],id:this.mapIdentifiers(e.id,e.identifier),code:p(e.code),statusCode:{"@_code":"completed"},effectiveTime:this.mapEffectiveTime(e.performedDateTime,e.performedPeriod),text:this.createTextFromExtensions(e.extension)}]}:{procedure:[{"@_classCode":"PROC","@_moodCode":"EVN",templateId:[{"@_root":se},{"@_root":se,"@_extension":"2014-06-09"}],id:this.mapIdentifiers(e.id,e.identifier),code:p(e.code),statusCode:{"@_code":"completed"},effectiveTime:this.mapEffectiveTime(e.performedDateTime,e.performedPeriod),text:this.createTextFromExtensions(e.extension),targetSiteCode:p(e.bodySite?.[0]),participant:[this.mapLocationToParticipant(e.location)].filter(Boolean)}]}}if(e.resourceType==="Observation")return{observation:[{"@_classCode":"OBS","@_moodCode":"EVN",templateId:this.mapObservationTemplateId(e),id:this.mapIdentifiers(e.id,e.identifier),code:p(e.code),value:this.mapObservationValue(e),statusCode:{"@_code":"completed"},effectiveTime:this.mapEffectiveTime(e.effectiveDateTime,e.effectivePeriod),text:this.createTextFromExtensions(e.extension)}]};throw new Error(`Unknown history of procedures resource type: ${e.resourceType}`)}mapLocationToParticipant(e){if(!e)return;let t=this.findResourceByReference(e);if(t)return{"@_typeCode":"LOC",participantRole:{"@_classCode":"SDLOC",templateId:[{"@_root":Ct}],id:this.mapIdentifiers(t.id,t.identifier),code:p(t.type?.[0]),addr:t.address?this.mapFhirAddressArrayToCcdaAddressArray([t.address]):void 0,telecom:this.mapTelecom(t.telecom),playingEntity:{"@_classCode":"PLC",name:t.name?[t.name]:void 0}}}}mapEffectiveTime(e,t){if(t)return[{low:{"@_value":O(t.start)},high:{"@_value":O(t.end)}}];if(e)return[{"@_value":O(e)}]}mapEffectiveDate(e,t){if(t)return[{"@_xsi:type":"IVL_TS",low:t.start?{"@_value":w(t.start)}:void 0,high:t.end?{"@_value":w(t.end)}:void 0}];if(e)return[{"@_value":w(e)}]}mapEffectivePeriod(e,t,n=!1){if(!e&&!t)return;let r={};return e?r.low={"@_value":O(e)}:n&&(r.low={"@_nullFlavor":"NI"}),t?r.high={"@_value":O(t)}:n&&(r.high={"@_nullFlavor":"NI"}),[r]}createEncounterEntry(e){return{encounter:[{"@_classCode":"ENC","@_moodCode":"EVN",templateId:[{"@_root":ue},{"@_root":ue,"@_extension":"2015-08-01"}],id:this.mapIdentifiers(e.id,e.identifier),code:p(e.type?.[0]),text:this.createTextFromExtensions(e.extension),effectiveTime:this.mapEffectiveTime(void 0,e.period),participant:e.participant?.map(t=>({"@_typeCode":"LOC",participantRole:{"@_classCode":"SDLOC",templateId:[{"@_root":Ct}],code:p(t.type?.[0])}})),entryRelationship:e.diagnosis?.map(t=>this.createEncounterDiagnosis(t)).filter(Boolean)}]}}createEncounterDiagnosis(e){let t=this.findResourceByReference(e.condition);if(!(!t||t.resourceType!=="Condition"))return{"@_typeCode":"REFR",act:[{"@_classCode":"ACT","@_moodCode":"EVN",templateId:[{"@_root":ue,"@_extension":"2015-08-01"},{"@_root":ue}],code:{"@_code":"29308-4","@_displayName":"Diagnosis","@_codeSystem":N,"@_codeSystemName":"LOINC"},entryRelationship:[{"@_typeCode":"SUBJ",observation:[{"@_classCode":"OBS","@_moodCode":"EVN",templateId:[{"@_root":F,"@_extension":"2015-08-01"},{"@_root":F}],id:this.mapIdentifiers(t.id,t.identifier),code:{"@_code":"282291009","@_displayName":"Diagnosis interpretation","@_codeSystem":L,"@_codeSystemName":"SNOMED CT",translation:[{"@_code":"29308-4","@_displayName":"Diagnosis","@_codeSystem":N,"@_codeSystemName":"LOINC"}]},statusCode:{"@_code":"completed"},effectiveTime:this.mapEffectivePeriod(t.onsetDateTime,t.abatementDateTime),value:H(t.code)}]}]}]}}createCareTeamEntry(e){return{organizer:[{"@_classCode":"CLUSTER","@_moodCode":"EVN",templateId:[{"@_root":Dt,"@_extension":"2022-07-01"},{"@_root":Dt,"@_extension":"2022-06-01"}],id:this.mapIdentifiers(e.id,e.identifier),component:e.participant?.map(t=>({"@_typeCode":"PRF",role:t.role}))}]}}createClinicalImpressionSection(e,t){return{templateId:[{"@_root":be}],code:p(e.code),title:e.title,text:t.summary,author:this.mapAuthor(t.assessor,t.date)}}createPlanOfTreatmentServiceRequestEntry(e){return{observation:[{"@_classCode":"OBS","@_moodCode":"RQO",templateId:[{"@_root":gt}],id:this.mapIdentifiers(e.id,e.identifier),code:p(e.code),statusCode:{"@_code":this.mapPlanOfTreatmentStatus(e.status)},effectiveTime:[{"@_value":O(e.occurrenceDateTime)}],text:this.createTextFromExtensions(e.extension)}]}}createDiagnosticReportEntry(e){let t=[];if(e.result)for(let n of e.result){let r=this.findResourceByReference(n);!r||r.resourceType!=="Observation"||t.push({observation:[this.createVitalSignObservation(r)]})}return{organizer:[{"@_classCode":"CLUSTER","@_moodCode":"EVN",templateId:[{"@_root":ie},{"@_root":ie,"@_extension":"2015-08-01"}],id:this.mapIdentifiers(e.id,e.identifier),code:p(e.code),statusCode:{"@_code":"completed"},component:t}]}}createDeviceUseStatementEntry(e){let t=this.findResourceByReference(e.device);if(!t)return;let n=[],r=this.mapIdentifiers(t.id,t.identifier);return r&&n.push(...r),t.udiCarrier?.[0]?.deviceIdentifier&&n.push({"@_root":xt,"@_extension":t.udiCarrier[0].carrierHRF,"@_assigningAuthorityName":"FDA"}),{procedure:[{"@_classCode":"PROC","@_moodCode":"EVN",templateId:[{"@_root":se,"@_extension":"2014-06-09"},{"@_root":se}],id:this.mapIdentifiers(e.id,e.identifier),code:{"@_code":"360030002","@_codeSystem":L,"@_codeSystemName":"SNOMED CT","@_displayName":"Application of medical device"},statusCode:{"@_code":"completed"},participant:[{"@_typeCode":"DEV",participantRole:{"@_classCode":"MANU",templateId:[{"@_root":Li}],id:n,playingDevice:{"@_classCode":"DEV",code:p(t.type)},scopingEntity:{id:[{"@_root":xt}]}}}]}]}}createClinicalImpressionEntry(e){return{act:[{"@_classCode":"ACT","@_moodCode":"EVN",templateId:[{"@_root":Zi,"@_extension":"2016-11-01"}],id:this.mapIdentifiers(e.id,e.identifier),code:p(e.code)??{"@_code":qe,"@_codeSystem":N,"@_codeSystemName":"LOINC","@_displayName":"Note"},text:e.summary?{"#text":e.summary}:this.createTextFromExtensions(e.extension),statusCode:{"@_code":"completed"},effectiveTime:[{"@_value":w(e.date)}],author:this.mapAuthor(e.assessor,e.date)}]}}createReasonForReferralSection(e,t){return{templateId:[{"@_root":B,"@_extension":"2014-06-09"},{"@_root":B}],code:p(e.code),title:e.title,text:t.note?.[0]?.text,entry:[{act:[{"@_classCode":"PCPR","@_moodCode":"INT",templateId:[{"@_root":Qi}],id:this.mapIdentifiers(t.id,t.identifier),code:p(t.code),statusCode:{"@_code":"active"},effectiveTime:[{"@_value":O(t.occurrenceDateTime)}],priorityCode:{"@_code":"A","@_codeSystem":"2.16.840.1.113883.5.7","@_codeSystemName":"ActPriority","@_displayName":"ASAP"},author:this.mapAuthor(t.requester,t.occurrenceDateTime)}]}]}}};export{pn as ACT_CODE_SYSTEM,Ze as ADDRESS_USE_MAPPER,ao as ADDRESS_USE_VALUE_SET,ro as ADMINISTRATIVE_GENDER_CODE_SYSTEM,uo as ADMINISTRATIVE_GENDER_VALUE_SET,go as ALLERGIES_SECTION_TEMPLATE_IDS,Gn as ALLERGY_CATEGORY_MAPPER,ke as ALLERGY_CLINICAL_CODE_SYSTEM,Ke as ALLERGY_SEVERITY_MAPPER,Je as ALLERGY_STATUS_MAPPER,Lt as ALLERGY_VERIFICATION_CODE_SYSTEM,Lo as ASSESSMENTS_SECTION_TEMPLATE_IDS,Go as CARE_TEAM_SECTION_TEMPLATE_IDS,Ye as CCDA_NARRATIVE_REFERENCE_URL,js as CCDA_TEMPLATE_CODE_SYSTEM,zn as CCDA_TEMPLATE_IDS,Pt as CLINICAL_CONDITION_CODE_SYSTEM,ua as CLINICAL_NOTES_SECTION_TEMPLATE_IDS,ln as CONDITION_CATEGORY_CODE_SYSTEM,dn as CONDITION_VERIFICATION_CODE_SYSTEM,bt as CONDITION_VER_STATUS_CODE_SYSTEM,oo as CONFIDENTIALITY_CODE_SYSTEM,Fn as CONFIDENTIALITY_MAPPER,lo as CONTACT_ENTITY_USE_VALUE_SET,So as CVX_URL,bo as DEVICES_SECTION_TEMPLATE_IDS,fn as DIAGNOSIS_ROLE_CODE_SYSTEM,Vo as ENCOUNTERS_SECTION_TEMPLATE_IDS,Yn as ENCOUNTER_STATUS_MAPPER,I as EnumMapper,yo as FHIR_CVX_URL,kn as GENDER_MAPPER,Mo as GOALS_SECTION_TEMPLATE_IDS,wo as HEALTH_CONCERNS_SECTION_TEMPLATE_IDS,k as HTTP,ze as HUMAN_NAME_USE_MAPPER,Ro as IMMUNIZATIONS_SECTION_TEMPLATE_IDS,et as IMMUNIZATION_STATUS_MAPPER,Yo as INSURANCE_SECTION_TEMPLATE_IDS,da as LAB_TESTS_SECTION_TEMPLATE_IDS,Fs as LANGUAGE_MODE_CODE_SYSTEM,Ys as LANGUAGE_MODE_URL,ks as LANGUAGE_PROFICIENCY_CODE_SYSTEM,Hs as LANGUAGE_PROFICIENCY_URL,Mn as LOINC_ADMINISTRATIVE_SEX,In as LOINC_ALLERGIES_SECTION,je as LOINC_ASSESSMENTS_SECTION,wn as LOINC_BIRTH_SEX,vn as LOINC_CARE_TEAM_SECTION,bn as LOINC_CONDITION,An as LOINC_DEVICES_SECTION,Nn as LOINC_ENCOUNTERS_SECTION,fe as LOINC_GOALS_SECTION,_e as LOINC_HEALTH_CONCERNS_SECTION,Vn as LOINC_HISTORY_OF_TOBACCO_USE,Tn as LOINC_IMMUNIZATIONS_SECTION,xn as LOINC_INSURANCE_SECTION,On as LOINC_MEDICATIONS_SECTION,Pn as LOINC_MEDICATION_INSTRUCTIONS,Dn as LOINC_MENTAL_STATUS_SECTION,qe as LOINC_NOTES_SECTION,qs as LOINC_NOTE_DOCUMENT,Ln as LOINC_OVERALL_GOAL,Ws as LOINC_PATIENT_SUMMARY_DOCUMENT,$e as LOINC_PLAN_OF_TREATMENT_SECTION,He as LOINC_PROBLEMS_SECTION,gn as LOINC_PROCEDURES_SECTION,me as LOINC_REASON_FOR_REFERRAL_SECTION,Rn as LOINC_REFERRAL_NOTE,Sn as LOINC_RESULTS_SECTION,yn as LOINC_SOCIAL_HISTORY_SECTION,We as LOINC_SUMMARY_OF_EPISODE_NOTE,Un as LOINC_TOBACCO_SMOKING_STATUS,Xn as LOINC_TO_TEMPLATE_IDS,Cn as LOINC_VITAL_SIGNS_SECTION,Ao as MEDICATIONS_SECTION_TEMPLATE_IDS,po as MEDICATION_REQUEST_STATUS_VALUE_SET,tt as MEDICATION_STATUS_MAPPER,Fo as MENTAL_STATUS_SECTION_TEMPLATE_IDS,co as NAME_USE_VALUE_SET,ho as NCI_THESAURUS_URL,Oo as NDFRT_URL,Io as NUCC_TAXONOMY_URL,so as OBSERVATION_CATEGORY_CODE_SYSTEM,$n as OBSERVATION_CATEGORY_MAPPER,hn as PARTICIPATION_CODE_SYSTEM,ko as PATIENT_NOTES_SECTION_TEMPLATE_IDS,Uo as PLAN_OF_TREATMENT_SECTION_TEMPLATE_IDS,No as PROBLEMS_SECTION_TEMPLATE_IDS,Ie as PROBLEM_STATUS_MAPPER,xo as PROCEDURES_SECTION_TEMPLATE_IDS,Hn as PROCEDURE_STATUS_MAPPER,Gs as RACE_CODE_SYSTEM,Bo as REASON_FOR_REFERRAL_SECTION_TEMPLATE_IDS,Zn as REFERRAL_TEMPLATE_IDS,Po as RESULTS_SECTION_TEMPLATE_IDS,vo as SOCIAL_HISTORY_SECTION_TEMPLATE_IDS,Qe as SYSTEM_MAPPER,Xe as TELECOM_USE_MAPPER,Eo as UNII_URL,_n as US_CORE_CONDITION_URL,Ge as US_CORE_ETHNICITY_URL,mn as US_CORE_MEDICATION_REQUEST_URL,$s as US_CORE_PATIENT_URL,he as US_CORE_RACE_URL,_o as US_DRIVER_LICENSE_URL,mo as US_NPI_URL,fo as US_SSN_URL,To as VA_MEDRT_URL,Do as VITAL_SIGNS_SECTION_TEMPLATE_IDS,En as XSI_URL,oa as convertCcdaToFhir,Js as convertCcdaToXml,Ia as convertFhirToCcda,Qn as convertToCompactXml,Xs as convertXmlToCcda,Ee as mapCcdaSystemToFhir,ut as mapCcdaToFhirDate,m as mapCcdaToFhirDateTime,p as mapCodeableConceptToCcdaCode,H as mapCodeableConceptToCcdaValue,un as mapCodingToCcdaCode,Bn as mapFhirSystemToCcda,w as mapFhirToCcdaDate,O as mapFhirToCcdaDateTime,Wn as parseXml};
1
+ var Kn=class{constructor(i,e){this.operator=i,this.child=e}toString(){return`${this.operator}(${this.child.toString()})`}},W=class{constructor(i,e,t){this.operator=i,this.left=e,this.right=t}toString(){return`(${this.left.toString()} ${this.operator} ${this.right.toString()})`}},er=class{constructor(){this.prefixParselets={},this.infixParselets={}}registerInfix(i,e){return this.infixParselets[i]=e,this}registerPrefix(i,e){return this.prefixParselets[i]=e,this}prefix(i,e,t){return this.registerPrefix(i,{parse(n,r){let o=n.consumeAndParse(e);return t(r,o)}})}infixLeft(i,e,t){return this.registerInfix(i,{parse(n,r,o){let s=n.consumeAndParse(e);return t(r,o,s)},precedence:e})}construct(i){return new tr(i,this.prefixParselets,this.infixParselets)}},tr=class{constructor(i,e,t){this.tokens=i,this.prefixParselets=e,this.infixParselets=t}hasMore(){return this.tokens.length>0}match(i){return this.peek()?.id!==i?!1:(this.consume(),!0)}consumeAndParse(i=1/0){let e=this.consume(),t=this.prefixParselets[e.id];if(!t)throw Error(`Parse error at "${e.value}" (line ${e.line}, column ${e.column}). No matching prefix parselet.`);let n=t.parse(this,e);for(;i>this.getPrecedence();){let r=this.consume();n=this.getInfixParselet(r).parse(this,n,r)}return n}getPrecedence(){let i=this.peek();if(!i)return 1/0;let e=this.getInfixParselet(i);return e?e.precedence:1/0}consume(i,e){if(!this.tokens.length)throw Error("Cant consume unknown more tokens.");if(i&&this.peek()?.id!==i){let t=this.peek();throw Error(`Expected ${i} but got "${t.id}" (${t.value}) at line ${t.line} column ${t.column}.`)}if(e&&this.peek()?.value!==e){let t=this.peek();throw Error(`Expected "${e}" but got "${t.value}" at line ${t.line} column ${t.column}.`)}return this.tokens.shift()}peek(){return this.tokens.length>0?this.tokens[0]:void 0}removeComments(){this.tokens=this.tokens.filter(i=>i.id!=="Comment")}getInfixParselet(i){return this.infixParselets[i.id==="Symbol"?i.value:i.id]}},ir=class{constructor(i=10){this.max=i,this.cache=new Map}clear(){this.cache.clear()}get(i){let e=this.cache.get(i);return e&&(this.cache.delete(i),this.cache.set(i,e)),e}set(i,e){this.cache.has(i)?this.cache.delete(i):this.cache.size>=this.max&&this.cache.delete(this.first()),this.cache.set(i,e)}delete(i){this.cache.delete(i)}keys(){return this.cache.keys()}first(){return this.cache.keys().next().value}},nt="http://unitsofmeasure.org",ge="http://loinc.org",rt="http://snomed.info/sct",Yt="http://www.nlm.nih.gov/research/umls/rxnorm",Ht="http://www.ama-assn.org/go/cpt";var $t="http://hl7.org/fhir/sid/ndc",_="http://hl7.org",T="http://terminology.hl7.org";var nr="unauthorized";var ye={resourceType:"OperationOutcome",id:nr,issue:[{severity:"error",code:"login",details:{text:"Unauthorized"}}]},Ho={...ye,issue:[...ye.issue,{severity:"error",code:"expired",details:{text:"Token expired"}}]},$o={...ye,issue:[...ye.issue,{severity:"error",code:"invalid",details:{text:"Token not issued for this audience"}}]};function rr(i,e){let t=e.max&&e.max===Number.MAX_SAFE_INTEGER?Number.POSITIVE_INFINITY:e.max;return{path:i,description:"",type:e.type??[],min:e.min??0,max:t??1,isArray:!!t&&t>1,constraints:[]}}function or(i){let e=Object.create(null);for(let[t,n]of Object.entries(i))e[t]={name:t,type:t,path:t,elements:Object.fromEntries(Object.entries(n.elements).map(([r,o])=>[r,rr(r,o)])),constraints:[],innerTypes:[]};return e}var sr={Element:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]}}},BackboneElement:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]}}},Address:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},type:{type:[{code:"code"}]},text:{type:[{code:"string"}]},line:{max:9007199254740991,type:[{code:"string"}]},city:{type:[{code:"string"}]},district:{type:[{code:"string"}]},state:{type:[{code:"string"}]},postalCode:{type:[{code:"string"}]},country:{type:[{code:"string"}]},period:{type:[{code:"Period"}]}}},Age:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Annotation:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},"author[x]":{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Organization"]},{code:"string"}]},time:{type:[{code:"dateTime"}]},text:{min:1,type:[{code:"markdown"}]}}},Attachment:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},contentType:{type:[{code:"code"}]},language:{type:[{code:"code"}]},data:{type:[{code:"base64Binary"}]},url:{type:[{code:"url"}]},size:{type:[{code:"unsignedInt"}]},hash:{type:[{code:"base64Binary"}]},title:{type:[{code:"string"}]},creation:{type:[{code:"dateTime"}]}}},CodeableConcept:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},coding:{max:9007199254740991,type:[{code:"Coding"}]},text:{type:[{code:"string"}]}}},Coding:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},system:{type:[{code:"uri"}]},version:{type:[{code:"string"}]},code:{type:[{code:"code"}]},display:{type:[{code:"string"}]},userSelected:{type:[{code:"boolean"}]}}},ContactDetail:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},name:{type:[{code:"string"}]},telecom:{max:9007199254740991,type:[{code:"ContactPoint"}]}}},ContactPoint:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},system:{type:[{code:"code"}]},value:{type:[{code:"string"}]},use:{type:[{code:"code"}]},rank:{type:[{code:"positiveInt"}]},period:{type:[{code:"Period"}]}}},Contributor:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},name:{min:1,type:[{code:"string"}]},contact:{max:9007199254740991,type:[{code:"ContactDetail"}]}}},Count:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},DataRequirement:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},profile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]},"subject[x]":{type:[{code:"CodeableConcept"},{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Group"]}]},mustSupport:{max:9007199254740991,type:[{code:"string"}]},codeFilter:{max:9007199254740991,type:[{code:"DataRequirementCodeFilter"}]},dateFilter:{max:9007199254740991,type:[{code:"DataRequirementDateFilter"}]},limit:{type:[{code:"positiveInt"}]},sort:{max:9007199254740991,type:[{code:"DataRequirementSort"}]}}},DataRequirementCodeFilter:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},valueSet:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/ValueSet"]}]},code:{max:9007199254740991,type:[{code:"Coding"}]}}},DataRequirementDateFilter:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},"value[x]":{type:[{code:"dateTime"},{code:"Period"},{code:"Duration"}]}}},DataRequirementSort:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},direction:{min:1,type:[{code:"code"}]}}},Distance:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Dosage:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},sequence:{type:[{code:"integer"}]},text:{type:[{code:"string"}]},additionalInstruction:{max:9007199254740991,type:[{code:"CodeableConcept"}]},patientInstruction:{type:[{code:"string"}]},timing:{type:[{code:"Timing"}]},"asNeeded[x]":{type:[{code:"boolean"},{code:"CodeableConcept"}]},site:{type:[{code:"CodeableConcept"}]},route:{type:[{code:"CodeableConcept"}]},method:{type:[{code:"CodeableConcept"}]},doseAndRate:{max:9007199254740991,type:[{code:"DosageDoseAndRate"}]},maxDosePerPeriod:{type:[{code:"Ratio"}]},maxDosePerAdministration:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},maxDosePerLifetime:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},DosageDoseAndRate:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{type:[{code:"CodeableConcept"}]},"dose[x]":{type:[{code:"Range"},{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},"rate[x]":{type:[{code:"Ratio"},{code:"Range"},{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},Duration:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},ElementDefinition:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},representation:{max:9007199254740991,type:[{code:"code"}]},sliceName:{type:[{code:"string"}]},sliceIsConstraining:{type:[{code:"boolean"}]},label:{type:[{code:"string"}]},code:{max:9007199254740991,type:[{code:"Coding"}]},slicing:{type:[{code:"ElementDefinitionSlicing"}]},short:{type:[{code:"string"}]},definition:{type:[{code:"markdown"}]},comment:{type:[{code:"markdown"}]},requirements:{type:[{code:"markdown"}]},alias:{max:9007199254740991,type:[{code:"string"}]},min:{type:[{code:"unsignedInt"}]},max:{type:[{code:"string"}]},base:{type:[{code:"ElementDefinitionBase"}]},contentReference:{type:[{code:"uri"}]},type:{max:9007199254740991,type:[{code:"ElementDefinitionType"}]},"defaultValue[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},meaningWhenMissing:{type:[{code:"markdown"}]},orderMeaning:{type:[{code:"string"}]},"fixed[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},"pattern[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},example:{max:9007199254740991,type:[{code:"ElementDefinitionExample"}]},"minValue[x]":{type:[{code:"date"},{code:"dateTime"},{code:"instant"},{code:"time"},{code:"decimal"},{code:"integer"},{code:"positiveInt"},{code:"unsignedInt"},{code:"Quantity"}]},"maxValue[x]":{type:[{code:"date"},{code:"dateTime"},{code:"instant"},{code:"time"},{code:"decimal"},{code:"integer"},{code:"positiveInt"},{code:"unsignedInt"},{code:"Quantity"}]},maxLength:{type:[{code:"integer"}]},condition:{max:9007199254740991,type:[{code:"id"}]},constraint:{max:9007199254740991,type:[{code:"ElementDefinitionConstraint"}]},mustSupport:{type:[{code:"boolean"}]},isModifier:{type:[{code:"boolean"}]},isModifierReason:{type:[{code:"string"}]},isSummary:{type:[{code:"boolean"}]},binding:{type:[{code:"ElementDefinitionBinding"}]},mapping:{max:9007199254740991,type:[{code:"ElementDefinitionMapping"}]}}},ElementDefinitionSlicingDiscriminator:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},path:{min:1,type:[{code:"string"}]}}},ElementDefinitionSlicing:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},discriminator:{max:9007199254740991,type:[{code:"ElementDefinitionSlicingDiscriminator"}]},description:{type:[{code:"string"}]},ordered:{type:[{code:"boolean"}]},rules:{min:1,type:[{code:"code"}]}}},ElementDefinitionBase:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},min:{min:1,type:[{code:"unsignedInt"}]},max:{min:1,type:[{code:"string"}]}}},ElementDefinitionType:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},code:{min:1,type:[{code:"uri"}]},profile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},targetProfile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},aggregation:{max:9007199254740991,type:[{code:"code"}]},versioning:{type:[{code:"code"}]}}},ElementDefinitionExample:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},label:{min:1,type:[{code:"string"}]},"value[x]":{min:1,type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]}}},ElementDefinitionConstraint:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},key:{min:1,type:[{code:"id"}]},requirements:{type:[{code:"string"}]},severity:{min:1,type:[{code:"code"}]},human:{min:1,type:[{code:"string"}]},expression:{type:[{code:"string"}]},xpath:{type:[{code:"string"}]},source:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]}}},ElementDefinitionBinding:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},strength:{min:1,type:[{code:"code"}]},description:{type:[{code:"string"}]},valueSet:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/ValueSet"]}]}}},ElementDefinitionMapping:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},identity:{min:1,type:[{code:"id"}]},language:{type:[{code:"code"}]},map:{min:1,type:[{code:"string"}]},comment:{type:[{code:"string"}]}}},Expression:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},description:{type:[{code:"string"}]},name:{type:[{code:"id"}]},language:{min:1,type:[{code:"code"}]},expression:{type:[{code:"string"}]},reference:{type:[{code:"uri"}]}}},Extension:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},url:{min:1,type:[{code:"uri"}]},"value[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]}}},HumanName:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},text:{type:[{code:"string"}]},family:{type:[{code:"string"}]},given:{max:9007199254740991,type:[{code:"string"}]},prefix:{max:9007199254740991,type:[{code:"string"}]},suffix:{max:9007199254740991,type:[{code:"string"}]},period:{type:[{code:"Period"}]}}},Identifier:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},type:{type:[{code:"CodeableConcept"}]},system:{type:[{code:"uri"}]},value:{type:[{code:"string"}]},period:{type:[{code:"Period"}]},assigner:{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Organization"]}]}}},MarketingStatus:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},country:{min:1,type:[{code:"CodeableConcept"}]},jurisdiction:{type:[{code:"CodeableConcept"}]},status:{min:1,type:[{code:"CodeableConcept"}]},dateRange:{min:1,type:[{code:"Period"}]},restoreDate:{type:[{code:"dateTime"}]}}},Meta:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},versionId:{type:[{code:"id"}]},lastUpdated:{type:[{code:"instant"}]},source:{type:[{code:"uri"}]},profile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]},security:{max:9007199254740991,type:[{code:"Coding"}]},tag:{max:9007199254740991,type:[{code:"Coding"}]},project:{type:[{code:"uri"}]},author:{type:[{code:"Reference"}]},onBehalfOf:{type:[{code:"Reference"}]},account:{type:[{code:"Reference"}]},accounts:{max:9007199254740991,type:[{code:"Reference"}]},compartment:{max:9007199254740991,type:[{code:"Reference"}]}}},Money:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},currency:{type:[{code:"code"}]}}},Narrative:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},status:{min:1,type:[{code:"code"}]},div:{min:1,type:[{code:"xhtml"}]}}},ParameterDefinition:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},name:{type:[{code:"code"}]},use:{min:1,type:[{code:"code"}]},min:{type:[{code:"integer"}]},max:{type:[{code:"string"}]},documentation:{type:[{code:"string"}]},type:{min:1,type:[{code:"code"}]},profile:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]}}},Period:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},start:{type:[{code:"dateTime"}]},end:{type:[{code:"dateTime"}]}}},Population:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},"age[x]":{type:[{code:"Range"},{code:"CodeableConcept"}]},gender:{type:[{code:"CodeableConcept"}]},race:{type:[{code:"CodeableConcept"}]},physiologicalCondition:{type:[{code:"CodeableConcept"}]}}},ProdCharacteristic:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},height:{type:[{code:"Quantity"}]},width:{type:[{code:"Quantity"}]},depth:{type:[{code:"Quantity"}]},weight:{type:[{code:"Quantity"}]},nominalVolume:{type:[{code:"Quantity"}]},externalDiameter:{type:[{code:"Quantity"}]},shape:{type:[{code:"string"}]},color:{max:9007199254740991,type:[{code:"string"}]},imprint:{max:9007199254740991,type:[{code:"string"}]},image:{max:9007199254740991,type:[{code:"Attachment"}]},scoring:{type:[{code:"CodeableConcept"}]}}},ProductShelfLife:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},identifier:{type:[{code:"Identifier"}]},type:{min:1,type:[{code:"CodeableConcept"}]},period:{min:1,type:[{code:"Quantity"}]},specialPrecautionsForStorage:{max:9007199254740991,type:[{code:"CodeableConcept"}]}}},Quantity:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Range:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},low:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},high:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},Ratio:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},numerator:{type:[{code:"Quantity"}]},denominator:{type:[{code:"Quantity"}]}}},Reference:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},reference:{type:[{code:"string"}]},type:{type:[{code:"uri"}]},identifier:{type:[{code:"Identifier"}]},display:{type:[{code:"string"}]}}},RelatedArtifact:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},label:{type:[{code:"string"}]},display:{type:[{code:"string"}]},citation:{type:[{code:"markdown"}]},url:{type:[{code:"url"}]},document:{type:[{code:"Attachment"}]},resource:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/Resource"]}]}}},SampledData:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},origin:{min:1,type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},period:{min:1,type:[{code:"decimal"}]},factor:{type:[{code:"decimal"}]},lowerLimit:{type:[{code:"decimal"}]},upperLimit:{type:[{code:"decimal"}]},dimensions:{min:1,type:[{code:"positiveInt"}]},data:{type:[{code:"string"}]}}},Signature:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,max:9007199254740991,type:[{code:"Coding"}]},when:{min:1,type:[{code:"instant"}]},who:{min:1,type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/PractitionerRole","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/Device","http://hl7.org/fhir/StructureDefinition/Organization"]}]},onBehalfOf:{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/PractitionerRole","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/Device","http://hl7.org/fhir/StructureDefinition/Organization"]}]},targetFormat:{type:[{code:"code"}]},sigFormat:{type:[{code:"code"}]},data:{type:[{code:"base64Binary"}]}}},SubstanceAmount:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},"amount[x]":{type:[{code:"Quantity"},{code:"Range"},{code:"string"}]},amountType:{type:[{code:"CodeableConcept"}]},amountText:{type:[{code:"string"}]},referenceRange:{type:[{code:"SubstanceAmountReferenceRange"}]}}},SubstanceAmountReferenceRange:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},lowLimit:{type:[{code:"Quantity"}]},highLimit:{type:[{code:"Quantity"}]}}},Timing:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},event:{max:9007199254740991,type:[{code:"dateTime"}]},repeat:{type:[{code:"TimingRepeat"}]},code:{type:[{code:"CodeableConcept"}]}}},TimingRepeat:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},"bounds[x]":{type:[{code:"Duration"},{code:"Range"},{code:"Period"}]},count:{type:[{code:"positiveInt"}]},countMax:{type:[{code:"positiveInt"}]},duration:{type:[{code:"decimal"}]},durationMax:{type:[{code:"decimal"}]},durationUnit:{type:[{code:"code"}]},frequency:{type:[{code:"positiveInt"}]},frequencyMax:{type:[{code:"positiveInt"}]},period:{type:[{code:"decimal"}]},periodMax:{type:[{code:"decimal"}]},periodUnit:{type:[{code:"code"}]},dayOfWeek:{max:9007199254740991,type:[{code:"code"}]},timeOfDay:{max:9007199254740991,type:[{code:"time"}]},when:{max:9007199254740991,type:[{code:"code"}]},offset:{type:[{code:"unsignedInt"}]}}},TriggerDefinition:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},name:{type:[{code:"string"}]},"timing[x]":{type:[{code:"Timing"},{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Schedule"]},{code:"date"},{code:"dateTime"}]},data:{max:9007199254740991,type:[{code:"DataRequirement"}]},condition:{type:[{code:"Expression"}]}}},UsageContext:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},code:{min:1,type:[{code:"Coding"}]},"value[x]":{min:1,type:[{code:"CodeableConcept"},{code:"Quantity"},{code:"Range"},{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/PlanDefinition","http://hl7.org/fhir/StructureDefinition/ResearchStudy","http://hl7.org/fhir/StructureDefinition/InsurancePlan","http://hl7.org/fhir/StructureDefinition/HealthcareService","http://hl7.org/fhir/StructureDefinition/Group","http://hl7.org/fhir/StructureDefinition/Location","http://hl7.org/fhir/StructureDefinition/Organization"]}]}}},MoneyQuantity:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},SimpleQuantity:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{max:0,type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},IdentityProvider:{elements:{authorizeUrl:{min:1,type:[{code:"string"}]},tokenUrl:{min:1,type:[{code:"string"}]},tokenAuthMethod:{type:[{code:"code"}]},userInfoUrl:{min:1,type:[{code:"string"}]},clientId:{min:1,type:[{code:"string"}]},clientSecret:{min:1,type:[{code:"string"}]},usePkce:{type:[{code:"boolean"}]},useSubject:{type:[{code:"boolean"}]}}}};var ar=or(sr);var Mt=Object.create(null);function cr(i){let e;return e=Mt[i],e||(e=Mt[i]=Object.create(null)),e}function ur(i,e){if(e){let t=cr(e)[i];if(t)return t}return ar[i]}var jo=new ir(1e3);var jt={base64Binary:/^([A-Za-z\d+/]{4})*([A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/,canonical:/^\S*$/,code:/^[^\s]+( [^\s]+)*$/,date:/^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2]\d|3[0-1]))?)?$/,dateTime:/^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2]\d|3[0-1])(T([01]\d|2[0-3])(:[0-5]\d:([0-5]\d|60)(\.\d{1,9})?)?)?)?(Z|[+-]((0\d|1[0-3]):[0-5]\d|14:00)?)?)?$/,id:/^[A-Za-z0-9\-.]{1,64}$/,instant:/^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])T([01]\d|2[0-3]):[0-5]\d:([0-5]\d|60)(\.\d{1,9})?(Z|[+-]((0\d|1[0-3]):[0-5]\d|14:00))$/,markdown:/^[\r\n\t\u0020-\uFFFF]+$/,oid:/^urn:oid:[0-2](\.(0|[1-9]\d*))+$/,string:/^[\r\n\t\u0020-\uFFFF]+$/,time:/^([01]\d|2[0-3]):[0-5]\d:([0-5]\d|60)(\.\d{1,9})?$/,uri:/^\S*$/,url:/^\S*$/,uuid:/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,xhtml:/.*/};function c(i){return[{type:u.boolean,value:i}]}function M(i){return i==null?{type:"undefined",value:void 0}:Number.isSafeInteger(i)?{type:u.integer,value:i}:typeof i=="number"?{type:u.decimal,value:i}:typeof i=="boolean"?{type:u.boolean,value:i}:typeof i=="string"?{type:u.string,value:i}:g(i)?{type:u.Quantity,value:i}:z(i)?{type:i.resourceType,value:i}:Jt(i)?{type:u.CodeableConcept,value:i}:Xt(i)?{type:u.Coding,value:i}:{type:u.BackboneElement,value:i}}function P(i){return i.length===0?!1:!!i[0].value}function b(i,e){if(i.length!==0){if(i.length===1&&(!e||i[0].type===e))return i[0];throw new Error(`Expected singleton of type ${e}, but found ${JSON.stringify(i)}`)}}function dr(i,e,t){if(!i.value)return;let n=br(i.type,e,t?.profileUrl);return n?lr(i,e,n):pr(i,e)}function lr(i,e,t){let n=i.value,r=t.type;if(!r||r.length===0)return;let o,s="undefined",a,h=t.path.lastIndexOf("."),S=t.path.substring(h+1);for(let E of r){let $=S.replace("[x]",Q(E.code));if(o=n[$],a=n["_"+$],o!==void 0||a!==void 0){s=E.code;break}}if(a)if(Array.isArray(o)){o=o.slice();for(let E=0;E<Math.max(o.length,a.length);E++)o[E]=Ft(o[E],a[E])}else o=Ft(o,a);if(!q(o))return(s==="Element"||s==="BackboneElement")&&(s=t.type[0].code),Array.isArray(o)?o.map(E=>wt(E,s)):wt(o,s)}function wt(i,e){return e==="Resource"&&z(i)&&(e=i.resourceType),{type:e,value:i}}function pr(i,e){let t=i.value;if(!t||typeof t!="object")return;let n;if(e in t){let r=t[e];Array.isArray(r)?n=r.map(M):n=M(r)}else{let r=e.endsWith("[x]")?e.substring(0,e.length-3):e;for(let o of Object.values(u)){let s=r+Q(o);if(s in t){let a=t[s];Array.isArray(a)?n=a.map(h=>({type:o,value:h})):n={type:o,value:a};break}}}if(Array.isArray(n)){if(n.length===0||q(n[0]))return}else if(q(n))return;return n}function qt(i){let e=[];for(let t of i){let n=!1;for(let r of e)if(P(Ae(t,r))){n=!0;break}n||e.push(t)}return e}function hr(i){return c(!P(i))}function fr(i,e){return i.length===0||e.length===0?[]:i.length!==e.length?c(!1):c(i.every((t,n)=>P(Ae(t,e[n]))))}function _r(i,e){return i.length===0||e.length===0?[]:i.length!==e.length?c(!0):c(i.some((t,n)=>!P(Ae(t,e[n]))))}function Ae(i,e){let t=i.value?.valueOf(),n=e.value?.valueOf();return typeof t=="number"&&typeof n=="number"?c(Math.abs(t-n)<1e-8):g(t)&&g(n)?c(zt(t,n)):c(typeof t=="object"&&typeof n=="object"?ot(i,e):t===n)}function Wt(i,e){return i.length===0&&e.length===0?c(!0):i.length!==e.length?c(!1):(i.sort(Bt),e.sort(Bt),c(i.every((t,n)=>P(mr(t,e[n])))))}function mr(i,e){let{type:t,value:n}=i,{type:r,value:o}=e,s=n?.valueOf(),a=o?.valueOf();return typeof s=="number"&&typeof a=="number"?c(Math.abs(s-a)<.01):g(s)&&g(a)?c(zt(s,a)):c(t==="Coding"&&r==="Coding"?typeof s!="object"||typeof a!="object"?!1:s.code===a.code&&s.system===a.system:typeof s=="object"&&typeof a=="object"?ot({...s,id:void 0},{...a,id:void 0}):typeof s=="string"&&typeof a=="string"?s.toLowerCase()===a.toLowerCase():s===a)}function Bt(i,e){let t=i.value?.valueOf(),n=e.value?.valueOf();return typeof t=="number"&&typeof n=="number"?t-n:typeof t=="string"&&typeof n=="string"?t.localeCompare(n):0}function Qt(i,e){let{value:t}=i;if(t==null)return!1;let n=e;switch(n.startsWith("System.")&&(n=n.substring(7)),n.startsWith("FHIR.")&&(n=n.substring(5)),n){case"Boolean":return typeof t=="boolean";case"Decimal":case"Integer":return typeof t=="number";case"Date":return Er(t);case"DateTime":return it(t);case"Time":return typeof t=="string"&&!!/^T\d/.exec(t);case"Period":return Ir(t);case"Quantity":return g(t);default:return i.type===n||typeof t=="object"&&t?.resourceType===n}}function Er(i){return typeof i=="string"&&!!jt.date.exec(i)}function it(i){return typeof i=="string"&&!!jt.dateTime.exec(i)}function Ir(i){return!!(i&&typeof i=="object"&&("start"in i&&it(i.start)||"end"in i&&it(i.end)))}function g(i){return!!(i&&typeof i=="object"&&"value"in i&&typeof i.value=="number")}function zt(i,e){return Math.abs(i.value-e.value)<.01&&(i.unit===e.unit||i.code===e.code||i.unit===e.code||i.code===e.unit)}function ot(i,e){let t=Object.keys(i),n=Object.keys(e);if(t.length!==n.length)return!1;for(let r of t){let o=i[r],s=e[r];if(kt(o)&&kt(s)){if(!ot(o,s))return!1}else if(o!==s)return!1}return!0}function kt(i){return i!==null&&typeof i=="object"}function Ft(i,e){if(e){if(typeof e!="object")throw new Error("Primitive extension must be an object");return Tr(i??{},e)}return i}function Tr(i,e){return delete e.__proto__,delete e.constructor,Object.assign(i,e)}function Or(i,e){return z(i,e)&&"id"in i&&typeof i.id=="string"}function f(i){let e=Zt(i)??"undefined/undefined",t=Cr(i);return t===e?{reference:e}:{reference:e,display:t}}function Zt(i){if(Kt(i))return i.reference;if(Or(i))return`${i.resourceType}/${i.id}`}function Sr(i){if(i)return Kt(i)?i.reference.split("/")[1]:i.id}function yr(i){return i.resourceType==="Patient"||i.resourceType==="Practitioner"||i.resourceType==="RelatedPerson"}function Cr(i){if(yr(i)){let e=gr(i);if(e)return e}if(i.resourceType==="Device"){let e=Ar(i);if(e)return e}if(i.resourceType==="MedicationRequest"&&i.medicationCodeableConcept)return Gt(i.medicationCodeableConcept);if(i.resourceType==="Subscription"&&i.criteria)return i.criteria;if(i.resourceType==="User"&&i.email)return i.email;if("name"in i&&i.name&&typeof i.name=="string")return i.name;if("code"in i&&i.code){let e=i.code;if(Array.isArray(e)&&(e=e[0]),Jt(e))return Gt(e);if(Dr(e))return e.text}return Zt(i)??""}function gr(i){let e=i.name;if(e&&e.length>0)return xr(e[0])}function Ar(i){let e=i.deviceName;if(e&&e.length>0)return e[0].name}function Nr(i,e){let t=new Date(i);t.setUTCHours(0,0,0,0);let n=e?new Date(e):new Date;n.setUTCHours(0,0,0,0);let r=t.getUTCFullYear(),o=t.getUTCMonth(),s=t.getUTCDate(),a=n.getUTCFullYear(),h=n.getUTCMonth(),S=n.getUTCDate(),E=a-r;(h<o||h===o&&S<s)&&E--;let $=a*12+h-(r*12+o);S<s&&$--;let Jn=Math.floor((n.getTime()-t.getTime())/(1e3*60*60*24));return{years:E,months:$,days:Jn}}function Ne(i,...e){let t=i;for(let n=0;n<e.length&&t;n++)t=t?.extension?.find(r=>r.url===e[n]);return t}function q(i){if(i==null)return!0;let e=typeof i;return e==="string"||e==="object"?!Rr(i):!1}function Rr(i){if(i==null)return!1;let e=typeof i;return e==="string"&&i!==""||e==="object"&&("length"in i&&i.length>0||Object.keys(i).length>0)}function st(i){return/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i.test(i)}function at(i){return i!==null&&typeof i=="object"}function Xt(i){return at(i)&&"code"in i&&typeof i.code=="string"}function Jt(i){return at(i)&&"coding"in i&&Array.isArray(i.coding)&&i.coding.every(Xt)}function Dr(i){return at(i)&&"text"in i&&typeof i.text=="string"}var vr=[];for(let i=0;i<256;i++)vr.push(i.toString(16).padStart(2,"0"));function Q(i){return i?i.charAt(0).toUpperCase()+i.substring(1):""}function xr(i,e){if(!i)return"";let t=[];if(i.prefix&&e?.prefix!==!1&&t.push(...i.prefix),i.given&&t.push(...i.given),i.family&&t.push(i.family),i.suffix&&e?.suffix!==!1&&t.push(...i.suffix),i.use&&(e?.all||e?.use)&&t.push("["+i.use+"]"),t.length===0){let n=j(i.text);if(n)return n}return t.join(" ").trim()}function Gt(i){return i?j(i.text)||(i.coding?i.coding.map(t=>Pr(t)).join(", "):""):""}function Pr(i,e){let t=j(i?.display);if(t){let n=e?j(i?.code):void 0;return`${t}${n?" ("+n+")":""}`}return j(i?.code)??""}function j(i){return typeof i=="string"?i:void 0}var u={Address:"Address",Age:"Age",Annotation:"Annotation",Attachment:"Attachment",BackboneElement:"BackboneElement",CodeableConcept:"CodeableConcept",Coding:"Coding",ContactDetail:"ContactDetail",ContactPoint:"ContactPoint",Contributor:"Contributor",Count:"Count",DataRequirement:"DataRequirement",Distance:"Distance",Dosage:"Dosage",Duration:"Duration",Expression:"Expression",Extension:"Extension",HumanName:"HumanName",Identifier:"Identifier",MarketingStatus:"MarketingStatus",Meta:"Meta",Money:"Money",Narrative:"Narrative",ParameterDefinition:"ParameterDefinition",Period:"Period",Population:"Population",ProdCharacteristic:"ProdCharacteristic",ProductShelfLife:"ProductShelfLife",Quantity:"Quantity",Range:"Range",Ratio:"Ratio",Reference:"Reference",RelatedArtifact:"RelatedArtifact",SampledData:"SampledData",Signature:"Signature",SubstanceAmount:"SubstanceAmount",SystemString:"http://hl7.org/fhirpath/System.String",Timing:"Timing",TriggerDefinition:"TriggerDefinition",UsageContext:"UsageContext",base64Binary:"base64Binary",boolean:"boolean",canonical:"canonical",code:"code",date:"date",dateTime:"dateTime",decimal:"decimal",id:"id",instant:"instant",integer:"integer",markdown:"markdown",oid:"oid",positiveInt:"positiveInt",string:"string",time:"time",unsignedInt:"unsignedInt",uri:"uri",url:"url",uuid:"uuid"};function br(i,e,t){let n=ur(i,t);if(n)return Lr(n.elements,e)}function Lr(i,e){let t=i[e]??i[e+"[x]"];if(t)return t;for(let n=0;n<e.length;n++){let r=e[n];if(r>="A"&&r<="Z"){let o=e.slice(0,n)+"[x]",s=i[o];if(s)return s}}}function z(i,e){return!(!i||typeof i!="object"||!("resourceType"in i)||e&&i.resourceType!==e)}function Kt(i){return!!(i&&typeof i=="object"&&"reference"in i&&typeof i.reference=="string")}function Se(i){if(i.startsWith("T"))return i+"T00:00:00.000Z".substring(i.length);if(i.length<=10)return i;try{return new Date(i).toISOString()}catch{return i}}var x=()=>[],y={empty:(i,e)=>c(e.length===0||e.every(t=>q(t.value))),hasValue:(i,e)=>c(e.length!==0),exists:(i,e,t)=>c(t?e.filter(n=>P(t.eval(i,[n]))).length>0:e.length>0&&e.every(n=>!q(n.value))),all:(i,e,t)=>c(e.every(n=>P(t.eval(i,[n])))),allTrue:(i,e)=>{for(let t of e)if(!t.value)return c(!1);return c(!0)},anyTrue:(i,e)=>{for(let t of e)if(t.value)return c(!0);return c(!1)},allFalse:(i,e)=>{for(let t of e)if(t.value)return c(!1);return c(!0)},anyFalse:(i,e)=>{for(let t of e)if(!t.value)return c(!0);return c(!1)},subsetOf:(i,e,t)=>{if(e.length===0)return c(!0);let n=t.eval(i,V(i));return n.length===0?c(!1):c(e.every(r=>n.some(o=>o.value===r.value)))},supersetOf:(i,e,t)=>{let n=t.eval(i,V(i));return n.length===0?c(!0):e.length===0?c(!1):c(n.every(r=>e.some(o=>o.value===r.value)))},count:(i,e)=>[{type:u.integer,value:e.length}],distinct:(i,e)=>{let t=[];for(let n of e)t.some(r=>r.value===n.value)||t.push(n);return t},isDistinct:(i,e)=>c(e.length===y.distinct(i,e).length),where:(i,e,t)=>e.filter(n=>P(t.eval(i,[n]))),select:(i,e,t)=>e.map(n=>t.eval({parent:i,variables:{$this:n}},[n])).flat(),repeat:x,ofType:(i,e,t)=>e.filter(n=>n.type===t.name),single:(i,e)=>{if(e.length>1)throw new Error("Expected input length one for single()");return e.length===0?[]:e.slice(0,1)},first:(i,e)=>e.length===0?[]:e.slice(0,1),last:(i,e)=>e.length===0?[]:e.slice(e.length-1,e.length),tail:(i,e)=>e.length===0?[]:e.slice(1,e.length),skip:(i,e,t)=>{let n=t.eval(i,e)[0]?.value;if(typeof n!="number")throw new Error("Expected a number for skip(num)");return n>=e.length?[]:n<=0?e:e.slice(n,e.length)},take:(i,e,t)=>{let n=t.eval(i,e)[0]?.value;if(typeof n!="number")throw new Error("Expected a number for take(num)");return n>=e.length?e:n<=0?[]:e.slice(0,n)},intersect:(i,e,t)=>{if(!t)return e;let n=t.eval(i,V(i)),r=[];for(let o of e)!r.some(s=>s.value===o.value)&&n.some(s=>s.value===o.value)&&r.push(o);return r},exclude:(i,e,t)=>{if(!t)return e;let n=t.eval(i,V(i)),r=[];for(let o of e)n.some(s=>s.value===o.value)||r.push(o);return r},union:(i,e,t)=>{if(!t)return e;let n=t.eval(i,V(i));return qt([...e,...n])},combine:(i,e,t)=>{if(!t)return e;let n=t.eval(i,V(i));return[...e,...n]},htmlChecks:(i,e,t)=>[M(!0)],iif:(i,e,t,n,r)=>{let o=t.eval(i,e);if(o.length>1||o.length===1&&typeof o[0].value!="boolean")throw new Error("Expected criterion to evaluate to a Boolean");return P(o)?n.eval(i,e):r?r.eval(i,e):[]},toBoolean:(i,e)=>{if(e.length===0)return[];let[{value:t}]=v(e,1);if(typeof t=="boolean")return[{type:u.boolean,value:t}];if(typeof t=="number"&&(t===0||t===1))return c(!!t);if(typeof t=="string"){let n=t.toLowerCase();if(["true","t","yes","y","1","1.0"].includes(n))return c(!0);if(["false","f","no","n","0","0.0"].includes(n))return c(!1)}return[]},convertsToBoolean:(i,e)=>e.length===0?[]:c(y.toBoolean(i,e).length===1),toInteger:(i,e)=>{if(e.length===0)return[];let[{value:t}]=v(e,1);return typeof t=="number"?[{type:u.integer,value:t}]:typeof t=="string"&&/^[+-]?\d+$/.exec(t)?[{type:u.integer,value:parseInt(t,10)}]:typeof t=="boolean"?[{type:u.integer,value:t?1:0}]:[]},convertsToInteger:(i,e)=>e.length===0?[]:c(y.toInteger(i,e).length===1),toDate:(i,e)=>{if(e.length===0)return[];let[{value:t}]=v(e,1);return typeof t=="string"&&/^\d{4}(-\d{2}(-\d{2})?)?/.exec(t)?[{type:u.date,value:Se(t)}]:[]},convertsToDate:(i,e)=>e.length===0?[]:c(y.toDate(i,e).length===1),toDateTime:(i,e)=>{if(e.length===0)return[];let[{value:t}]=v(e,1);return typeof t=="string"&&/^\d{4}(-\d{2}(-\d{2})?)?/.exec(t)?[{type:u.dateTime,value:Se(t)}]:[]},convertsToDateTime:(i,e)=>e.length===0?[]:c(y.toDateTime(i,e).length===1),toDecimal:(i,e)=>{if(e.length===0)return[];let[{value:t}]=v(e,1);return typeof t=="number"?[{type:u.decimal,value:t}]:typeof t=="string"&&/^-?\d{1,9}(\.\d{1,9})?$/.exec(t)?[{type:u.decimal,value:parseFloat(t)}]:typeof t=="boolean"?[{type:u.decimal,value:t?1:0}]:[]},convertsToDecimal:(i,e)=>e.length===0?[]:c(y.toDecimal(i,e).length===1),toQuantity:(i,e)=>{if(e.length===0)return[];let[{value:t}]=v(e,1);return g(t)?[{type:u.Quantity,value:t}]:typeof t=="number"?[{type:u.Quantity,value:{value:t,unit:"1"}}]:typeof t=="string"&&/^-?\d{1,9}(\.\d{1,9})?/.exec(t)?[{type:u.Quantity,value:{value:parseFloat(t),unit:"1"}}]:typeof t=="boolean"?[{type:u.Quantity,value:{value:t?1:0,unit:"1"}}]:[]},convertsToQuantity:(i,e)=>e.length===0?[]:c(y.toQuantity(i,e).length===1),toString:(i,e)=>{if(e.length===0)return[];let[{value:t}]=v(e,1);return t==null?[]:g(t)?[{type:u.string,value:`${t.value} '${t.unit}'`}]:[{type:u.string,value:t.toString()}]},convertsToString:(i,e)=>e.length===0?[]:c(y.toString(i,e).length===1),toTime:(i,e)=>{if(e.length===0)return[];let[{value:t}]=v(e,1);if(typeof t=="string"){let n=/^T?(\d{2}(:\d{2}(:\d{2})?)?)/.exec(t);if(n)return[{type:u.time,value:Se("T"+n[1])}]}return[]},convertsToTime:(i,e)=>e.length===0?[]:c(y.toTime(i,e).length===1),indexOf:(i,e,t)=>C((n,r)=>n.indexOf(r),i,e,t),substring:(i,e,t,n)=>C((r,o,s)=>{let a=o,h=s?a+s:r.length;return a<0||a>=r.length?void 0:r.substring(a,h)},i,e,t,n),startsWith:(i,e,t)=>C((n,r)=>n.startsWith(r),i,e,t),endsWith:(i,e,t)=>C((n,r)=>n.endsWith(r),i,e,t),contains:(i,e,t)=>C((n,r)=>n.includes(r),i,e,t),upper:(i,e)=>C(t=>t.toUpperCase(),i,e),lower:(i,e)=>C(t=>t.toLowerCase(),i,e),replace:(i,e,t,n)=>C((r,o,s)=>r.replaceAll(o,s),i,e,t,n),matches:(i,e,t)=>C((n,r)=>!!new RegExp(r).exec(n),i,e,t),replaceMatches:(i,e,t,n)=>C((r,o,s)=>r.replaceAll(new RegExp(o,"g"),s),i,e,t,n),length:(i,e)=>C(t=>t.length,i,e),toChars:(i,e)=>C(t=>t?t.split(""):void 0,i,e),encode:x,decode:x,escape:x,unescape:x,trim:x,split:x,join:(i,e,t)=>{let n=t?.eval(i,V(i))[0]?.value??"";if(typeof n!="string")throw new Error("Separator must be a string.");return[{type:u.string,value:e.map(r=>r.value?.toString()??"").join(n)}]},abs:(i,e)=>D(Math.abs,i,e),ceiling:(i,e)=>D(Math.ceil,i,e),exp:(i,e)=>D(Math.exp,i,e),floor:(i,e)=>D(Math.floor,i,e),ln:(i,e)=>D(Math.log,i,e),log:(i,e,t)=>D((n,r)=>Math.log(n)/Math.log(r),i,e,t),power:(i,e,t)=>D(Math.pow,i,e,t),round:(i,e)=>D(Math.round,i,e),sqrt:(i,e)=>D(Math.sqrt,i,e),truncate:(i,e)=>D(t=>t|0,i,e),children:x,descendants:x,trace:(i,e,t)=>e,now:()=>[{type:u.dateTime,value:new Date().toISOString()}],timeOfDay:()=>[{type:u.time,value:new Date().toISOString().substring(11)}],today:()=>[{type:u.date,value:new Date().toISOString().substring(0,10)}],between:(i,e,t,n,r)=>{let o=y.toDateTime(i,t.eval(i,e));if(o.length===0)throw new Error("Invalid start date");let s=y.toDateTime(i,n.eval(i,e));if(s.length===0)throw new Error("Invalid end date");let a=r.eval(i,e)[0]?.value;if(a!=="years"&&a!=="months"&&a!=="days")throw new Error("Invalid units");let h=Nr(o[0].value,s[0].value);return[{type:u.Quantity,value:{value:h[a],unit:a}}]},is:(i,e,t)=>{let n="";return t instanceof Ce?n=t.name:t instanceof ei&&(n=t.left.name+"."+t.right.name),n?e.map(r=>({type:u.boolean,value:Qt(r,n)})):[]},not:(i,e)=>y.toBoolean(i,e).map(t=>({type:u.boolean,value:!t.value})),resolve:(i,e)=>e.map(t=>{let n=t.value,r;if(typeof n=="string")r=n;else if(typeof n=="object"){let o=n;if(o.resource)return M(o.resource);o.reference?r=o.reference:o.type&&o.identifier&&(r=`${o.type}?identifier=${o.identifier.system}|${o.identifier.value}`)}if(r?.includes("?")){let[o]=r.split("?");return{type:o,value:{resourceType:o}}}if(r?.includes("/")){let[o,s]=r.split("/");return{type:o,value:{resourceType:o,id:s}}}return{type:u.BackboneElement,value:void 0}}).filter(t=>!!t.value),as:(i,e)=>e,type:(i,e)=>e.map(({value:t})=>typeof t=="boolean"?{type:u.BackboneElement,value:{namespace:"System",name:"Boolean"}}:typeof t=="number"?{type:u.BackboneElement,value:{namespace:"System",name:"Integer"}}:z(t)?{type:u.BackboneElement,value:{namespace:"FHIR",name:t.resourceType}}:{type:u.BackboneElement,value:null}),conformsTo:(i,e,t)=>{let n=t.eval(i,e)[0].value;if(!n.startsWith("http://hl7.org/fhir/StructureDefinition/"))throw new Error("Expected a StructureDefinition URL");let r=n.replace("http://hl7.org/fhir/StructureDefinition/","");return e.map(o=>({type:u.boolean,value:o.value?.resourceType===r}))},getResourceKey:(i,e)=>{let t=e[0].value;return t?.id?[{type:u.id,value:t.id}]:[]},getReferenceKey:(i,e,t)=>{let n=e[0].value;if(!n?.reference)return[];let r="";return t instanceof Ce&&(r=t.name),r&&!n.reference.startsWith(r+"/")?[]:[{type:u.id,value:Sr(n)}]},extension:(i,e,t)=>{let n=t.eval(i,e)[0].value,r=e?.[0]?.value;if(r){let o=Ne(r,n);if(o)return[{type:u.Extension,value:o}]}return[]}};function C(i,e,t,...n){if(t.length===0)return[];let[{value:r}]=v(t,1);if(typeof r!="string")throw new Error("String function cannot be called with non-string");let o=i(r,...n.map(s=>s?.eval(e,t)[0]?.value));return o===void 0?[]:Array.isArray(o)?o.map(M):[M(o)]}function D(i,e,t,...n){if(t.length===0)return[];let[{value:r}]=v(t,1),o=g(r),s=o?r.value:r;if(typeof s!="number")throw new Error("Math function cannot be called with non-number");let a=i(s,...n.map(E=>E.eval(e,t)[0]?.value)),h=o?u.Quantity:t[0].type,S=o?{...r,value:a}:a;return[{type:h,value:S}]}function v(i,e){if(i.length!==e)throw new Error(`Expected ${e} arguments`);for(let t of i)if(t==null)throw new Error("Expected non-null argument");return i}function V(i){let e=i;for(;e.parent?.variables.$this;)e=e.parent;return[e.variables.$this]}var G=class{constructor(i){this.value=i}eval(){return[this.value]}toString(){let i=this.value.value;return typeof i=="string"?`'${i}'`:i.toString()}},Ce=class{constructor(i){this.name=i}eval(i,e){if(this.name==="$this")return e;let t=this.getVariable(i);if(t)return[t];if(this.name.startsWith("%"))throw new Error(`Undefined variable ${this.name}`);return e.flatMap(n=>this.evalValue(n)).filter(n=>n?.value!==void 0)}getVariable(i){let e=i.variables[this.name];if(e!==void 0)return e;if(i.parent)return this.getVariable(i.parent)}evalValue(i){let e=i.value;if(!(!e||typeof e!="object"))return z(e,this.name)?i:dr(i,this.name)}toString(){return this.name}},Ur=class{eval(){return[]}toString(){return"{}"}},Vr=class extends Kn{constructor(i,e,t){super(i,e),this.impl=t}eval(i,e){return this.impl(this.child.eval(i,e))}toString(){return this.operator+this.child.toString()}},Mr=class extends W{constructor(i,e){super("as",i,e)}eval(i,e){return y.ofType(i,this.left.eval(i,e),this.right)}},A=class extends W{},R=class extends A{constructor(i,e,t,n){super(i,e,t),this.impl=n}eval(i,e){let t=this.left.eval(i,e);if(t.length!==1)return[];let n=this.right.eval(i,e);if(n.length!==1)return[];let r=t[0].value,o=n[0].value,s=g(r)?r.value:r,a=g(o)?o.value:o,h=this.impl(s,a);return typeof h=="boolean"?c(h):g(r)?[{type:u.Quantity,value:{...r,value:h}}]:[M(h)]}},wr=class extends W{constructor(i,e){super("&",i,e)}eval(i,e){let t=this.left.eval(i,e),n=this.right.eval(i,e),r=[...t,...n];return r.length>0&&r.every(o=>typeof o.value=="string")?[{type:u.string,value:r.map(o=>o.value).join("")}]:r}},Br=class extends A{constructor(i,e){super("contains",i,e)}eval(i,e){let t=this.left.eval(i,e),n=this.right.eval(i,e);return c(t.some(r=>r.value===n[0].value))}},kr=class extends A{constructor(i,e){super("in",i,e)}eval(i,e){let t=b(this.left.eval(i,e)),n=this.right.eval(i,e);return t?c(n.some(r=>Ae(t,r)[0].value)):[]}},ei=class extends W{constructor(i,e){super(".",i,e)}eval(i,e){return this.right.eval(i,this.left.eval(i,e))}toString(){return`${this.left.toString()}.${this.right.toString()}`}},Fr=class extends W{constructor(i,e){super("|",i,e)}eval(i,e){let t=this.left.eval(i,e),n=this.right.eval(i,e);return qt([...t,...n])}},Gr=class extends A{constructor(i,e){super("=",i,e)}eval(i,e){let t=this.left.eval(i,e),n=this.right.eval(i,e);return fr(t,n)}},Yr=class extends A{constructor(i,e){super("!=",i,e)}eval(i,e){let t=this.left.eval(i,e),n=this.right.eval(i,e);return _r(t,n)}},Hr=class extends A{constructor(i,e){super("~",i,e)}eval(i,e){let t=this.left.eval(i,e),n=this.right.eval(i,e);return Wt(t,n)}},$r=class extends A{constructor(i,e){super("!~",i,e)}eval(i,e){let t=this.left.eval(i,e),n=this.right.eval(i,e);return hr(Wt(t,n))}},jr=class extends A{constructor(i,e){super("is",i,e)}eval(i,e){let t=this.left.eval(i,e);if(t.length!==1)return[];let n=this.right.name;return c(Qt(t[0],n))}},qr=class extends A{constructor(i,e){super("and",i,e)}eval(i,e){let t=b(this.left.eval(i,e),"boolean"),n=b(this.right.eval(i,e),"boolean");return t?.value===!0&&n?.value===!0?c(!0):t?.value===!1||n?.value===!1?c(!1):[]}},Wr=class extends A{constructor(i,e){super("or",i,e)}eval(i,e){let t=b(this.left.eval(i,e),"boolean"),n=b(this.right.eval(i,e),"boolean");return t?.value===!1&&n?.value===!1?c(!1):t?.value||n?.value?c(!0):[]}},Qr=class extends A{constructor(i,e){super("xor",i,e)}eval(i,e){let t=b(this.left.eval(i,e),"boolean"),n=b(this.right.eval(i,e),"boolean");return!t||!n?[]:c(t.value!==n.value)}},zr=class extends A{constructor(i,e){super("implies",i,e)}eval(i,e){let t=b(this.left.eval(i,e),"boolean"),n=b(this.right.eval(i,e),"boolean");return n?.value===!0||t?.value===!1?c(!0):!t||!n?[]:c(!1)}},Zr=class{constructor(i,e){this.name=i,this.args=e}eval(i,e){let t=y[this.name];if(!t)throw new Error("Unrecognized function: "+this.name);return t(i,e,...this.args)}toString(){return`${this.name}(${this.args.map(i=>i.toString()).join(", ")})`}},Xr=class{constructor(i,e){this.left=i,this.expr=e}eval(i,e){let t=this.expr.eval(i,e);if(t.length!==1)return[];let n=t[0].value;if(typeof n!="number")throw new Error("Invalid indexer expression: should return integer}");let r=this.left.eval(i,e);return n in r?[r[n]]:[]}toString(){return`${this.left.toString()}[${this.expr.toString()}]`}};var ti=["!=","!~","<=",">=","{}","->"];var l={FunctionCall:0,Dot:1,Indexer:2,UnaryAdd:3,UnarySubtract:3,Multiply:4,Divide:4,IntegerDivide:4,Modulo:4,Add:5,Subtract:5,Ampersand:5,Is:6,As:6,Union:7,GreaterThan:8,GreaterThanOrEquals:8,LessThan:8,LessThanOrEquals:8,Equals:9,Equivalent:9,NotEquals:9,NotEquivalent:9,In:10,Contains:10,And:11,Xor:12,Or:12,Implies:13,Arrow:100,Semicolon:200},Jr={parse(i){let e=i.consumeAndParse();if(!i.match(")"))throw new Error("Parse error: expected `)` got `"+i.peek()?.value+"`");return e}},Kr={parse(i,e){let t=i.consumeAndParse();if(!i.match("]"))throw new Error("Parse error: expected `]`");return new Xr(e,t)},precedence:l.Indexer},eo={parse(i,e){if(!(e instanceof Ce))throw new Error("Unexpected parentheses");let t=[];for(;!i.match(")");)t.push(i.consumeAndParse()),i.match(",");return new Zr(e.name,t)},precedence:l.FunctionCall};function to(i){let e=i.split(" "),t=parseFloat(e[0]),n=e[1];return n?.startsWith("'")&&n.endsWith("'")?n=n.substring(1,n.length-1):n="{"+n+"}",{value:t,unit:n}}function ct(){return new er().registerPrefix("String",{parse:(i,e)=>new G({type:u.string,value:e.value})}).registerPrefix("DateTime",{parse:(i,e)=>new G({type:u.dateTime,value:Se(e.value)})}).registerPrefix("Quantity",{parse:(i,e)=>new G({type:u.Quantity,value:to(e.value)})}).registerPrefix("Number",{parse:(i,e)=>new G({type:e.value.includes(".")?u.decimal:u.integer,value:parseFloat(e.value)})}).registerPrefix("true",{parse:()=>new G({type:u.boolean,value:!0})}).registerPrefix("false",{parse:()=>new G({type:u.boolean,value:!1})}).registerPrefix("Symbol",{parse:(i,e)=>new Ce(e.value)}).registerPrefix("{}",{parse:()=>new Ur}).registerPrefix("(",Jr).registerInfix("[",Kr).registerInfix("(",eo).prefix("+",l.UnaryAdd,(i,e)=>new Vr("+",e,t=>t)).prefix("-",l.UnarySubtract,(i,e)=>new R("-",e,e,(t,n)=>-n)).infixLeft(".",l.Dot,(i,e,t)=>new ei(i,t)).infixLeft("/",l.Divide,(i,e,t)=>new R("/",i,t,(n,r)=>n/r)).infixLeft("*",l.Multiply,(i,e,t)=>new R("*",i,t,(n,r)=>n*r)).infixLeft("+",l.Add,(i,e,t)=>new R("+",i,t,(n,r)=>n+r)).infixLeft("-",l.Subtract,(i,e,t)=>new R("-",i,t,(n,r)=>n-r)).infixLeft("|",l.Union,(i,e,t)=>new Fr(i,t)).infixLeft("=",l.Equals,(i,e,t)=>new Gr(i,t)).infixLeft("!=",l.NotEquals,(i,e,t)=>new Yr(i,t)).infixLeft("~",l.Equivalent,(i,e,t)=>new Hr(i,t)).infixLeft("!~",l.NotEquivalent,(i,e,t)=>new $r(i,t)).infixLeft("<",l.LessThan,(i,e,t)=>new R("<",i,t,(n,r)=>n<r)).infixLeft("<=",l.LessThanOrEquals,(i,e,t)=>new R("<=",i,t,(n,r)=>n<=r)).infixLeft(">",l.GreaterThan,(i,e,t)=>new R(">",i,t,(n,r)=>n>r)).infixLeft(">=",l.GreaterThanOrEquals,(i,e,t)=>new R(">=",i,t,(n,r)=>n>=r)).infixLeft("&",l.Ampersand,(i,e,t)=>new wr(i,t)).infixLeft("and",l.And,(i,e,t)=>new qr(i,t)).infixLeft("as",l.As,(i,e,t)=>new Mr(i,t)).infixLeft("contains",l.Contains,(i,e,t)=>new Br(i,t)).infixLeft("div",l.Divide,(i,e,t)=>new R("div",i,t,(n,r)=>n/r|0)).infixLeft("in",l.In,(i,e,t)=>new kr(i,t)).infixLeft("is",l.Is,(i,e,t)=>new jr(i,t)).infixLeft("mod",l.Modulo,(i,e,t)=>new R("mod",i,t,(n,r)=>n%r)).infixLeft("or",l.Or,(i,e,t)=>new Wr(i,t)).infixLeft("xor",l.Xor,(i,e,t)=>new Qr(i,t)).infixLeft("implies",l.Implies,(i,e,t)=>new zr(i,t))}var qo=ct();var d={EQUALS:"eq",NOT_EQUALS:"ne",GREATER_THAN:"gt",LESS_THAN:"lt",GREATER_THAN_OR_EQUALS:"ge",LESS_THAN_OR_EQUALS:"le",STARTS_AFTER:"sa",ENDS_BEFORE:"eb",APPROXIMATELY:"ap",CONTAINS:"contains",STARTS_WITH:"sw",EXACT:"exact",TEXT:"text",NOT:"not",ABOVE:"above",BELOW:"below",IN:"in",NOT_IN:"not-in",OF_TYPE:"of-type",MISSING:"missing",PRESENT:"present",IDENTIFIER:"identifier",ITERATE:"iterate"},Wo={contains:d.CONTAINS,exact:d.EXACT,above:d.ABOVE,below:d.BELOW,text:d.TEXT,not:d.NOT,in:d.IN,"not-in":d.NOT_IN,"of-type":d.OF_TYPE,missing:d.MISSING,identifier:d.IDENTIFIER,iterate:d.ITERATE},Qo={eq:d.EQUALS,ne:d.NOT_EQUALS,lt:d.LESS_THAN,le:d.LESS_THAN_OR_EQUALS,gt:d.GREATER_THAN,ge:d.GREATER_THAN_OR_EQUALS,sa:d.STARTS_AFTER,eb:d.ENDS_BEFORE,ap:d.APPROXIMATELY,sw:d.STARTS_WITH};var zo=[d.MISSING,d.PRESENT];var Oe={READ:"read",VREAD:"vread",UPDATE:"update",DELETE:"delete",HISTORY:"history",CREATE:"create",SEARCH:"search"},Zo=[Oe.READ,Oe.VREAD,Oe.HISTORY,Oe.SEARCH];function Re(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}var io={CSS:"text/css",DICOM:"application/dicom",FAVICON:"image/vnd.microsoft.icon",FHIR_JSON:"application/fhir+json",FORM_URL_ENCODED:"application/x-www-form-urlencoded",HL7_V2:"x-application/hl7-v2+er7",HTML:"text/html",JAVASCRIPT:"text/javascript",JSON:"application/json",JSON_PATCH:"application/json-patch+json",JWT:"application/jwt",MULTIPART_FORM_DATA:"multipart/form-data",PNG:"image/png",SCIM_JSON:"application/scim+json",SVG:"image/svg+xml",TEXT:"text/plain",TYPESCRIPT:"text/typescript",PING:"x-application/ping",XML:"text/xml",CDA_XML:"application/cda+xml"};var no;no=Symbol.toStringTag;var Xo={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};var Jo={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1};var Ko=io.FHIR_JSON+", */*; q=0.1";var es=[...ti,"->","<<",">>","=="];var ts=ct().registerInfix("->",{precedence:l.Arrow}).registerInfix(";",{precedence:l.Semicolon});var is=" ".repeat(2);var ns=[...ti,"eq","ne","co"];var rs={eq:d.EXACT,ne:d.NOT_EQUALS,co:d.CONTAINS,sw:d.STARTS_WITH,ew:void 0,gt:d.GREATER_THAN,lt:d.LESS_THAN,ge:d.GREATER_THAN_OR_EQUALS,le:d.LESS_THAN_OR_EQUALS,ap:d.APPROXIMATELY,sa:d.STARTS_AFTER,eb:d.ENDS_BEFORE,pr:d.PRESENT,po:void 0,ss:void 0,sb:void 0,in:d.IN,ni:d.NOT_IN,re:d.EQUALS,identifier:d.IDENTIFIER};var os=ct();function ut(i){if(!i)return;let e=i.substring(0,4),t="01",n="01";return i.length>=8&&(t=i.substring(4,6),n=i.substring(6,8)),`${e}-${t}-${n}`}function m(i){if(!i)return;let e=i.substring(0,4),t="01",n="01",r="00",o="00",s="00",a="Z";return i.length>=8&&(t=i.substring(4,6),n=i.substring(6,8)),i.length>=12&&(r=i.substring(8,10),o=i.substring(10,12)),i.length>=14&&(s=i.substring(12,14)),i.length>14&&(a=i.substring(14),a==="+0000"&&(a="Z")),`${e}-${t}-${n}T${r}:${o}:${s}${a}`}function w(i){if(i)return i.substring(0,10).replace(/-/g,"")}function O(i){if(!i)return;let[e,t]=i.split("T"),n=e.replaceAll("-",""),r=(t??"").replaceAll(/\.\d+/g,"").replaceAll(/:/g,"").replaceAll(/Z/g,"+0000");return`${n}${r}`}var B="1.3.6.1.4.1.19376.1.5.3.1.3.1";var ii="2.16.840.1.113883.1.3";var ni="2.16.840.1.113883.2.20.5.1",ri="2.16.840.1.113883.3.26.1.1";var oi="2.16.840.1.113883.4.1",si="2.16.840.1.113883.4.3",ai="2.16.840.1.113883.4.6",ci="2.16.840.1.113883.4.9",De="2.16.840.1.113883.5.1",ve="2.16.840.1.113883.5.4",dt="2.16.840.1.113883.5.6",lt="2.16.840.1.113883.5.25",N="2.16.840.1.113883.6.1",ui="2.16.840.1.113883.6.12",di="2.16.840.1.113883.6.24",li="2.16.840.1.113883.6.69",pi="2.16.840.1.113883.6.88",L="2.16.840.1.113883.6.96",hi="2.16.840.1.113883.6.101",fi="2.16.840.1.113883.6.209",xe="2.16.840.1.113883.6.238",_i="2.16.840.1.113883.6.345";var mi="2.16.840.1.113883.10.20.15.3.8";var Z="2.16.840.1.113883.10.20.22.1.1";var pt="2.16.840.1.113883.10.20.22.1.2";var ht="2.16.840.1.113883.10.20.22.1.14";var Pe="2.16.840.1.113883.10.20.22.2.1.1";var X="2.16.840.1.113883.10.20.22.2.2",J="2.16.840.1.113883.10.20.22.2.2.1";var ft="2.16.840.1.113883.10.20.22.2.3.1";var Ei="2.16.840.1.113883.10.20.22.2.4.1";var Ii="2.16.840.1.113883.10.20.22.2.5",K="2.16.840.1.113883.10.20.22.2.5.1",Ti="2.16.840.1.113883.10.20.22.2.5.1 .2",Oi="2.16.840.1.113883.10.20.22.2.5.2",Si="2.16.840.1.113883.10.20.22.2.6",ee="2.16.840.1.113883.10.20.22.2.6.1",yi="2.16.840.1.113883.10.20.22.2.6.1.2",Ci="2.16.840.1.113883.10.20.22.2.6.2";var Y="2.16.840.1.113883.10.20.22.2.7.1";var be="2.16.840.1.113883.10.20.22.2.8";var U="2.16.840.1.113883.10.20.22.2.10";var _t="2.16.840.1.113883.10.20.22.2.17";var Le="2.16.840.1.113883.10.20.22.2.18";var gi="2.16.840.1.113883.10.20.22.2.22.1";var Ai="2.16.840.1.113883.10.20.22.2.23";var Ni="2.16.840.1.113883.10.20.22.2.56";var Ue="2.16.840.1.113883.10.20.22.2.58";var te="2.16.840.1.113883.10.20.22.2.60";var Ve="2.16.840.1.113883.10.20.22.2.65";var Me="2.16.840.1.113883.10.20.22.2.500",ie="2.16.840.1.113883.10.20.22.4.1",Ri="2.16.840.1.113883.10.20.22.4.1.2",ne="2.16.840.1.113883.10.20.22.4.2",Di="2.16.840.1.113883.10.20.22.4.2.2",mt="2.16.840.1.113883.10.20.22.4.3";var k="2.16.840.1.113883.10.20.22.4.4",vi="2.16.840.1.113883.10.20.22.4.4.2";var Et="2.16.840.1.113883.10.20.22.4.7";var It="2.16.840.1.113883.10.20.22.4.8";var Tt="2.16.840.1.113883.10.20.22.4.9";var re="2.16.840.1.113883.10.20.22.4.12";var oe="2.16.840.1.113883.10.20.22.4.13";var se="2.16.840.1.113883.10.20.22.4.14";var Ot="2.16.840.1.113883.10.20.22.4.16";var xi="2.16.840.1.113883.10.20.22.4.20";var St="2.16.840.1.113883.10.20.22.4.23";var ae="2.16.840.1.113883.10.20.22.4.26",Pi="2.16.840.1.113883.10.20.22.4.26.2",ce="2.16.840.1.113883.10.20.22.4.27",bi="2.16.840.1.113883.10.20.22.4.27.2";var yt="2.16.840.1.113883.10.20.22.4.30";var Ct="2.16.840.1.113883.10.20.22.4.32";var Li="2.16.840.1.113883.10.20.22.4.37",Ui="2.16.840.1.113883.10.20.22.4.38",Vi="2.16.840.1.113883.10.20.22.4.38.1";var gt="2.16.840.1.113883.10.20.22.4.44";var ue="2.16.840.1.113883.10.20.22.4.49";var At="2.16.840.1.113883.10.20.22.4.52";var Nt="2.16.840.1.113883.10.20.22.4.54";var Mi="2.16.840.1.113883.10.20.22.4.66";var wi="2.16.840.1.113883.10.20.22.4.67";var Bi="2.16.840.1.113883.10.20.22.4.69",ki="2.16.840.1.113883.10.20.22.4.70";var Fi="2.16.840.1.113883.10.20.22.4.74";var Gi="2.16.840.1.113883.10.20.22.4.75";var de="2.16.840.1.113883.10.20.22.4.78",Yi="2.16.840.1.113883.10.20.22.4.78.2";var le="2.16.840.1.113883.10.20.22.4.85";var Hi="2.16.840.1.113883.10.20.22.4.86";var $i="2.16.840.1.113883.10.20.22.4.114";var ji="2.16.840.1.113883.10.20.22.4.119";var we="2.16.840.1.113883.10.20.22.4.121";var qi="2.16.840.1.113883.10.20.22.4.130";var Rt="2.16.840.1.113883.10.20.22.4.132",Wi="2.16.840.1.113883.10.20.22.4.133";var Qi="2.16.840.1.113883.10.20.22.4.140";var Be="2.16.840.1.113883.10.20.22.4.147",pe="2.16.840.1.113883.10.20.22.4.200",zi="2.16.840.1.113883.10.20.22.4.201",Zi="2.16.840.1.113883.10.20.22.4.202";var Xi="2.16.840.1.113883.10.20.22.4.244";var Ji="2.16.840.1.113883.10.20.22.4.250";var Ki="2.16.840.1.113883.10.20.22.4.406",en="2.16.840.1.113883.10.20.22.4.407";var tn="2.16.840.1.113883.10.20.22.4.416";var Dt="2.16.840.1.113883.10.20.22.4.500",nn="2.16.840.1.113883.10.20.22.4.501";var rn="2.16.840.1.113883.10.20.22.4.503",on="2.16.840.1.113883.10.20.22.4.504";var sn="2.16.840.1.113883.10.20.22.4.506",ke="2.16.840.1.113883.10.20.22.4.507",an="2.16.840.1.113883.10.20.22.4.508";var cn="2.16.840.1.113883.10.20.22.4.512";var vt="2.16.840.1.113883.12.292",xt="2.16.840.1.113883.3.3719";var I=class{constructor(e,t,n,r){this.systemName=e,this.ccdaSystemOid=t,this.fhirSystemUrl=n,this.entries=r,this.ccdaToFhirMap={},this.fhirToCcdaMap={};for(let o of r)this.ccdaToFhirMap[o.ccdaValue]||(this.ccdaToFhirMap[o.ccdaValue]=o),this.fhirToCcdaMap[o.fhirValue]||(this.fhirToCcdaMap[o.fhirValue]=o)}getEntryByFhir(e){return this.fhirToCcdaMap[e]}getEntryByCcda(e){return this.ccdaToFhirMap[e]}mapCcdaToFhir(e){return this.ccdaToFhirMap[e]?.fhirValue}mapCcdaToFhirWithDefault(e,t){return e?this.mapCcdaToFhir(e)??t:t}mapFhirToCcdaWithDefault(e,t){return e?this.mapFhirToCcda(e)??t:t}mapCcdaToFhirCodeableConcept(e){let t=this.ccdaToFhirMap[e];if(t)return{coding:[{system:this.fhirSystemUrl,code:t.fhirValue,display:t.displayName}],text:t.displayName}}mapFhirToCcda(e){if(e)return this.fhirToCcdaMap[e]?.ccdaValue}mapFhirToCcdaCode(e){if(!e)return;let t=this.fhirToCcdaMap[e];if(t)return{"@_code":t.ccdaValue,"@_displayName":t.displayName,"@_codeSystem":this.ccdaSystemOid,"@_codeSystemName":Qe.getEntryByCcda(this.ccdaSystemOid)?.displayName}}},F="http:",ro=`${_}/fhir/administrative-gender`,Pt=`${T}/CodeSystem/condition-clinical`,dn=`${T}/CodeSystem/condition-verification`,ks=`${T}/CodeSystem/v3-LanguageAbilityMode`,Fs=`${T}/CodeSystem/v3-LanguageAbilityProficiency`,Gs=`${T}/CodeSystem/v3-Race`,ln=`${T}/CodeSystem/condition-category`,bt=`${T}/CodeSystem/condition-ver-status`,Fe=`${T}/CodeSystem/allergyintolerance-clinical`,Lt=`${T}/CodeSystem/allergyintolerance-verification`,pn=`${T}/CodeSystem/v3-ActCode`,hn=`${T}/CodeSystem/v3-ParticipationType`,fn=`${T}/CodeSystem/diagnosis-role`,oo=`${T}/CodeSystem/v3-Confidentiality`,so=`${T}/CodeSystem/observation-category`,ao=`${_}/fhir/ValueSet/address-use`,co=`${_}/fhir/ValueSet/name-use`,uo=`${_}/fhir/ValueSet/administrative-gender`,lo=`${_}/fhir/ValueSet/contactentity-use`,po=`${_}/fhir/ValueSet/medicationrequest-status`,Ys=`${_}/fhir/StructureDefinition/language-mode`,Hs=`${_}/fhir/StructureDefinition/language-proficiency`,$s=`${_}/fhir/us/core/StructureDefinition/us-core-patient`,he=`${_}/fhir/us/core/StructureDefinition/us-core-race`,Ge=`${_}/fhir/us/core/StructureDefinition/us-core-ethnicity`,_n=`${_}/fhir/us/core/StructureDefinition/us-core-condition`,mn=`${_}/fhir/us/core/StructureDefinition/us-core-medicationrequest`,js=`${_}/cda/template`,ho=`${F}//ncithesaurus-stage.nci.nih.gov`,fo=`${_}/fhir/sid/us-ssn`,_o=`${_}/fhir/sid/us-dln`,mo=`${_}/fhir/sid/us-npi`,Eo=`${F}//fdasis.nlm.nih.gov`,Io=`${F}//nucc.org/provider-taxonomy`,To=`${F}//va.gov/terminology/medrt`,Oo=`${F}//hl7.org/fhir/ndfrt`,So=`${F}//nucc.org/cvx`,yo=`${_}/fhir/sid/cvx`,En=`${F}//www.w3.org/2001/XMLSchema-instance`,Ye="https://medplum.com/fhir/StructureDefinition/ccda-narrative-reference",In="48765-2",Tn="11369-6",On="10160-0",He="11450-4",Sn="30954-2",yn="29762-2",Cn="8716-3",gn="47519-4",$e="18776-5",je="51848-0",An="46264-8",fe="61146-7",_e="75310-3",Nn="46240-8",me="42349-1",Rn="57133-1",Dn="10190-7",vn="85847-2",xn="48768-6",qe="11488-4",qs="34109-9",Ws="60591-5",We="34133-9",Pn="76662-6",bn="75323-6",Ln="58144-7",Un="72166-2",Vn="11367-0",Mn="46098-0",wn="76689-9",Qe=new I("System","","",[{ccdaValue:ni,fhirValue:"https://fhir.infoway-inforoute.ca/CodeSystem/pCLOCD",displayName:"pan-Canadian LOINC Observation Code Database (pCLOCD)"},{ccdaValue:ri,fhirValue:ho,displayName:"NCI Thesaurus"},{ccdaValue:oi,fhirValue:fo,displayName:"SSN"},{ccdaValue:si,fhirValue:_o,displayName:"DLN"},{ccdaValue:ai,fhirValue:mo,displayName:"NPI"},{ccdaValue:ci,fhirValue:Eo,displayName:"Unique Ingredient Identifier (UNII)"},{ccdaValue:N,fhirValue:ge,displayName:"LOINC"},{ccdaValue:ui,fhirValue:Ht,displayName:"Current Procedural Terminology (CPT)"},{ccdaValue:di,fhirValue:"urn:iso:std:iso:11073:10101",displayName:"Medical Device Communications (MDC)"},{ccdaValue:li,fhirValue:$t,displayName:"National Drug Code (NDC)"},{ccdaValue:pi,fhirValue:Yt,displayName:"RxNorm"},{ccdaValue:L,fhirValue:rt,displayName:"SNOMED CT"},{ccdaValue:hi,fhirValue:Io,displayName:"NUCC Health Care Provider Taxonomy"},{ccdaValue:_i,fhirValue:To,displayName:"Medication Reference Terminology (MED-RT)"},{ccdaValue:fi,fhirValue:Oo,displayName:"National Drug File Reference Terminology (NDF-RT)"},{ccdaValue:vt,fhirValue:So,displayName:"CVX"},{ccdaValue:lt,fhirValue:"Confidentiality",displayName:"Confidentiality"},{ccdaValue:De,fhirValue:ro,displayName:"Administrative Sex"},{ccdaValue:vt,fhirValue:yo,displayName:"Vaccine Administered Code Set (CVX)"}]);function Ee(i){if(i)return Qe.mapCcdaToFhir(i)??`urn:oid:${i}`}function Bn(i){if(i)return i.startsWith("urn:oid:")?i.replace("urn:oid:",""):Qe.mapFhirToCcda(i)}function p(i){if(!i?.coding)return;let e=un(i.coding[0]);if(i.coding.length>1){e.translation=[];for(let t=1;t<i.coding.length;t++)e.translation.push(un(i.coding[t]))}return e}function un(i){let e=i?.system?Qe.getEntryByFhir(i.system):void 0,t=e?.ccdaValue,n=e?.displayName,r=i.system?.startsWith("urn:oid:")?i.system.replace("urn:oid:",""):void 0;return{"@_code":i.code,"@_displayName":i.display,"@_codeSystem":t??r,"@_codeSystemName":n}}function H(i){let e=p(i);if(e)return{"@_xsi:type":"CD",...e}}var kn=new I("Confidentiality",lt,oo,[{ccdaValue:"U",fhirValue:"U",displayName:"unrestricted"},{ccdaValue:"L",fhirValue:"L",displayName:"low"},{ccdaValue:"M",fhirValue:"M",displayName:"moderate"},{ccdaValue:"N",fhirValue:"N",displayName:"normal"},{ccdaValue:"R",fhirValue:"R",displayName:"restricted"},{ccdaValue:"V",fhirValue:"V",displayName:"very restricted"}]),ze=new I("HumanNameUse","",co,[{ccdaValue:"C",fhirValue:"usual",displayName:"Common/Called by"},{ccdaValue:"L",fhirValue:"official",displayName:"Legal"},{ccdaValue:"TEMP",fhirValue:"temp",displayName:"Temporary"},{ccdaValue:"P",fhirValue:"nickname",displayName:"Nickname"},{ccdaValue:"ANON",fhirValue:"anonymous",displayName:"Anonymous"},{ccdaValue:"L",fhirValue:"maiden",displayName:"Maiden"},{ccdaValue:"L",fhirValue:"old",displayName:"Old"}]),Fn=new I("Gender","",uo,[{ccdaValue:"F",fhirValue:"female",displayName:"Female"},{ccdaValue:"M",fhirValue:"male",displayName:"Male"},{ccdaValue:"UN",fhirValue:"unknown",displayName:"Unknown"},{ccdaValue:"UN",fhirValue:"other",displayName:"Other"}]),Ze=new I("AddressUse","",ao,[{ccdaValue:"HP",fhirValue:"home",displayName:"Home"},{ccdaValue:"WP",fhirValue:"work",displayName:"Work"}]),Xe=new I("TelecomUse","",lo,[{ccdaValue:"WP",fhirValue:"work",displayName:"Work"},{ccdaValue:"HP",fhirValue:"home",displayName:"Home"},{ccdaValue:"MC",fhirValue:"mobile",displayName:"Mobile"}]),Je=new I("AllergyStatus","",Lt,[{ccdaValue:"unconfirmed",fhirValue:"unconfirmed",displayName:"Unconfirmed"},{ccdaValue:"provisional",fhirValue:"provisional",displayName:"Provisional"},{ccdaValue:"differential",fhirValue:"differential",displayName:"Differential"},{ccdaValue:"confirmed",fhirValue:"confirmed",displayName:"Confirmed"},{ccdaValue:"refuted",fhirValue:"refuted",displayName:"Refuted"},{ccdaValue:"entered-in-error",fhirValue:"entered-in-error",displayName:"Entered in Error"},{ccdaValue:"unknown",fhirValue:"unknown",displayName:"Unknown"}]),Gn=new I("AllergyCategory",L,Fe,[{ccdaValue:"414285001",fhirValue:"food",displayName:"Allergy to food (finding)"},{ccdaValue:"419511003",fhirValue:"medication",displayName:"Propensity to adverse reactions to drug (finding)"},{ccdaValue:"426232007",fhirValue:"environment",displayName:"Environmental allergy (finding)"},{ccdaValue:"418038007",fhirValue:"biologic",displayName:"Propensity to adverse reactions to substance (finding)"}]),Ke=new I("AllergySeverity",rt,Fe,[{ccdaValue:"255604002",fhirValue:"mild",displayName:"Mild"},{ccdaValue:"6736007",fhirValue:"moderate",displayName:"Moderate"},{ccdaValue:"24484000",fhirValue:"severe",displayName:"Severe"}]),Ie=new I("ProblemStatus","",bt,[{ccdaValue:"active",fhirValue:"active",displayName:"Active"},{ccdaValue:"inactive",fhirValue:"inactive",displayName:"Inactive"},{ccdaValue:"resolved",fhirValue:"inactive",displayName:"Resolved"},{ccdaValue:"remission",fhirValue:"inactive",displayName:"In Remission"},{ccdaValue:"relapse",fhirValue:"active",displayName:"Relapse"},{ccdaValue:"resolved relapse",fhirValue:"inactive",displayName:"Resolved Relapse"},{ccdaValue:"aborted",fhirValue:"aborted",displayName:"Aborted"}]),et=new I("ImmunizationStatus","","",[{ccdaValue:"completed",fhirValue:"completed",displayName:"Completed"},{ccdaValue:"nullified",fhirValue:"entered-in-error",displayName:"Nullified"},{ccdaValue:"aborted",fhirValue:"not-done",displayName:"Aborted"},{ccdaValue:"cancelled",fhirValue:"not-done",displayName:"Cancelled"},{ccdaValue:"obsolete",fhirValue:"not-done",displayName:"Obsolete"}]),Yn=new I("EncounterStatus","","",[{ccdaValue:"active",fhirValue:"in-progress",displayName:"In Progress"},{ccdaValue:"completed",fhirValue:"finished",displayName:"Finished"},{ccdaValue:"aborted",fhirValue:"cancelled",displayName:"Cancelled"},{ccdaValue:"cancelled",fhirValue:"cancelled",displayName:"Cancelled"},{ccdaValue:"unknown",fhirValue:"unknown",displayName:"Unknown"}]),Hn=new I("ProcedureStatus","","",[{ccdaValue:"completed",fhirValue:"completed",displayName:"Completed"},{ccdaValue:"aborted",fhirValue:"stopped",displayName:"Stopped"},{ccdaValue:"cancelled",fhirValue:"not-done",displayName:"Not Done"},{ccdaValue:"new",fhirValue:"not-done",displayName:"Draft"},{ccdaValue:"unknown",fhirValue:"unknown",displayName:"Unknown"}]),tt=new I("MedicationStatus","",po,[{ccdaValue:"active",fhirValue:"active",displayName:"Active"},{ccdaValue:"completed",fhirValue:"completed",displayName:"Completed"},{ccdaValue:"aborted",fhirValue:"stopped",displayName:"Stopped"},{ccdaValue:"cancelled",fhirValue:"cancelled",displayName:"Cancelled"},{ccdaValue:"aborted",fhirValue:"entered-in-error",displayName:"Entered in Error"},{ccdaValue:"active",fhirValue:"draft",displayName:"Draft"},{ccdaValue:"cancelled",fhirValue:"unknown",displayName:"Unknown"},{ccdaValue:"nullified",fhirValue:"cancelled",displayName:"Nullified"},{ccdaValue:"obsolete",fhirValue:"cancelled",displayName:"Obsolete"}]),$n=new I("ObservationCategory","",so,[{ccdaValue:Ui,fhirValue:"social-history",displayName:"Social History"},{ccdaValue:Vi,fhirValue:"social-history",displayName:"Social History V2"},{ccdaValue:de,fhirValue:"social-history",displayName:"Smoking Status"},{ccdaValue:Yi,fhirValue:"social-history",displayName:"Current Smoking Status"},{ccdaValue:le,fhirValue:"social-history",displayName:"Tobacco Use"},{ccdaValue:rn,fhirValue:"social-history",displayName:"Basic Occupation"},{ccdaValue:on,fhirValue:"social-history",displayName:"Basic Industry"},{ccdaValue:nn,fhirValue:"social-history",displayName:"Sexual Orientation"},{ccdaValue:ke,fhirValue:"social-history",displayName:"Sex Observation"},{ccdaValue:pe,fhirValue:"social-history",displayName:"Gender Identity"},{ccdaValue:zi,fhirValue:"social-history",displayName:"Gender Identity V2"},{ccdaValue:mi,fhirValue:"social-history",displayName:"Pregnancy Status"},{ccdaValue:sn,fhirValue:"social-history",displayName:"Tribal Affiliation"},{ccdaValue:ce,fhirValue:"vital-signs",displayName:"Vital Signs Observation"},{ccdaValue:bi,fhirValue:"vital-signs",displayName:"Vital Signs Observation V2"},{ccdaValue:ae,fhirValue:"vital-signs",displayName:"Vital Signs Organizer"},{ccdaValue:Pi,fhirValue:"vital-signs",displayName:"Vital Signs Organizer V2"},{ccdaValue:cn,fhirValue:"vital-signs",displayName:"Average Blood Pressure Organizer"},{ccdaValue:ne,fhirValue:"laboratory",displayName:"Result Observation"},{ccdaValue:Di,fhirValue:"laboratory",displayName:"Result Observation V2"},{ccdaValue:Ki,fhirValue:"laboratory",displayName:"Laboratory Battery (ID)"},{ccdaValue:en,fhirValue:"laboratory",displayName:"Laboratory Observation (ID)"},{ccdaValue:tn,fhirValue:"laboratory",displayName:"Laboratory Result Organizer (ID)"},{ccdaValue:ie,fhirValue:"laboratory",displayName:"Result Organizer"},{ccdaValue:Ri,fhirValue:"laboratory",displayName:"Result Organizer V2"},{ccdaValue:Bi,fhirValue:"survey",displayName:"Assessment Scale Observation"},{ccdaValue:Hi,fhirValue:"survey",displayName:"Assessment Scale Supporting Observation"},{ccdaValue:Fi,fhirValue:"survey",displayName:"Cognitive Status Result Observation"},{ccdaValue:Gi,fhirValue:"survey",displayName:"Cognitive Status Result Organizer"},{ccdaValue:wi,fhirValue:"survey",displayName:"Functional Status Result Observation"},{ccdaValue:Mi,fhirValue:"survey",displayName:"Functional Status Result Organizer"},{ccdaValue:oe,fhirValue:"exam",displayName:"Procedure Activity Observation"},{ccdaValue:k,fhirValue:"exam",displayName:"Problem Observation"},{ccdaValue:vi,fhirValue:"exam",displayName:"Problem Observation V2"},{ccdaValue:ki,fhirValue:"exam",displayName:"Pressure Ulcer Observation"},{ccdaValue:$i,fhirValue:"exam",displayName:"Wound Observation"},{ccdaValue:Wi,fhirValue:"exam",displayName:"Wound Measurements Observation"},{ccdaValue:Y,fhirValue:"exam",displayName:"Procedure Section"},{ccdaValue:an,fhirValue:"therapy",displayName:"Medication Adherence"},{ccdaValue:qi,fhirValue:"therapy",displayName:"Nutrition Recommendations"},{ccdaValue:Xi,fhirValue:"therapy",displayName:"Diet Statement (Nutrition)"},{ccdaValue:Ji,fhirValue:"therapy",displayName:"Monitoring, Evaluation and Outcome (Nutrition)"}]);import{XMLBuilder as jn,XMLParser as qn}from"fast-xml-parser";var Co=["ClinicalDocument.recordTarget",".id",".templateId",".name",".addr",".telecom",".streetAddressLine",".author",".effectiveTime","name.given","name.suffix","name.prefix","patient.raceCode","patient.sdtc:raceCode","patient.ethnicGroupCode","patient.languageCommunication","component.structuredBody.component","component.structuredBody.component.section","component.section","component.observation","component.act","code.translation","section.entry","entry.act","entry.organizer","entry.substanceAdministration","entry.observation","entry.encounter","entry.procedure","encounter.performer","encounter.participant","encounter.entryRelationship","entryRelationship.observation","entryRelationship.substanceAdministration","entryRelationship.act","organizer.component","substanceAdministration.consumable.manufacturedProduct","substanceAdministration.entryRelationship","substanceAdministration.performer","act.entryRelationship","act.performer","observation.participant","observation.entryRelationship","observation.referenceRange","consumable.manufacturedProduct","manufacturedProduct.manufacturedMaterial","manufacturedProduct.manufacturerOrganization","manufacturedProduct.manufacturedLabeledDrug","manufacturedMaterial.code","manufacturedMaterial.lotNumberText"];function Xs(i){return new qn({ignoreAttributes:!1,attributeNamePrefix:"@_",parseAttributeValue:!1,parseTagValue:!1,isArray:(n,r,o,s)=>Co.some(a=>r.endsWith(a))}).parse(i).ClinicalDocument}function Js(i){return new jn({ignoreAttributes:!1,attributeNamePrefix:"@_",format:!0,suppressBooleanAttributes:!1,suppressEmptyNode:!0}).build({"?xml":{"@_version":"1.0","@_encoding":"UTF-8"},"?xml-stylesheet":{"@_type":"text/xsl","@_href":"CDA.xsl"},ClinicalDocument:{"@_xmlns":"urn:hl7-org:v3","@_xmlns:xsi":En,"@_xmlns:voc":"urn:hl7-org:v3/voc","@_xmlns:sdtc":"urn:hl7-org:sdtc",...i}})}function Wn(i){return new qn({ignoreAttributes:!1,attributeNamePrefix:"@_",parseAttributeValue:!1,parseTagValue:!1}).parse(i)}function Qn(i){return i?typeof i=="string"?i:new jn({ignoreAttributes:!1,attributeNamePrefix:"@_",format:!1,suppressBooleanAttributes:!1,suppressEmptyNode:!0}).build(i).split(`
2
+ `).map(n=>n.trim()).join(""):""}function oa(i,e){return new Ut(i,e).convert()}var Ut=class{constructor(e,t){this.resources=[];this.ccda=e,this.options=t}convert(){return this.processHeader(),{resourceType:"Bundle",type:"document",entry:[{resource:this.createComposition()},...this.patient?[{resource:this.patient}]:[],...this.resources.map(t=>({resource:t}))]}}processHeader(){let e=this.ccda.recordTarget?.[0]?.patientRole;e&&(this.patient=this.createPatient(e))}createPatient(e){let t=e.patient,n=[];return t.raceCode&&t.raceCode.length>0&&!t.raceCode[0]["@_nullFlavor"]&&n.push({url:he,extension:t.raceCode.map(r=>({url:"ombCategory",valueCoding:this.mapCodeToCoding(r)}))}),t.ethnicGroupCode&&t.ethnicGroupCode.length>0&&!t.ethnicGroupCode[0]["@_nullFlavor"]&&n.push({url:Ge,extension:t.ethnicGroupCode.map(r=>({url:"ombCategory",valueCoding:this.mapCodeToCoding(r)}))}),{resourceType:"Patient",id:this.mapId(e.id),identifier:this.mapIdentifiers(e.id),name:this.mapCcdaNameArrayFhirHumanNameArray(t.name),gender:this.mapGenderCode(t.administrativeGenderCode?.["@_code"]),birthDate:ut(t.birthTime?.["@_value"]),address:this.mapAddresses(e.addr),telecom:this.mapTelecom(e.telecom),extension:n.length>0?n:void 0}}mapId(e){let t=e?.find(n=>!n["@_extension"]&&n["@_root"]&&st(n["@_root"]));return t?t["@_root"]:Re()}mapIdentifiers(e){if(!e)return;let t=[];for(let n of e)!n["@_extension"]&&n["@_root"]&&st(n["@_root"])||t.push({system:Ee(n["@_root"]),value:n["@_extension"]});return t}mapCcdaNameArrayFhirHumanNameArray(e){return e?.map(t=>this.mapCcdaNameToFhirHumanName(t)).filter(Boolean)}mapCcdaNameToFhirHumanName(e){if(!e)return;let t={},n=e["@_use"]?ze.mapCcdaToFhir(e["@_use"]):void 0;return n&&(t.use=n),e.prefix&&(t.prefix=e.prefix.map(Te)?.filter(Boolean)),e.family&&(t.family=Te(e.family)),e.given&&(t.given=e.given.map(Te)?.filter(Boolean)),e.suffix&&(t.suffix=e.suffix.map(Te)?.filter(Boolean)),t}mapAddresses(e){if(!(!e||e.length===0||e.every(t=>t["@_nullFlavor"]==="UNK")))return e?.map(t=>({"@_use":t["@_use"]?Ze.mapCcdaToFhir(t["@_use"]):void 0,line:t.streetAddressLine,city:t.city,state:t.state,postalCode:t.postalCode,country:t.country}))}mapTelecom(e){if(!(!e||e.length===0||e.every(t=>t["@_nullFlavor"]==="UNK")))return e?.map(t=>({"@_use":t["@_use"]?Xe.mapCcdaToFhir(t["@_use"]):void 0,system:this.getTelecomSystem(t["@_value"]),value:this.getTelecomValue(t["@_value"])}))}createComposition(){let e=this.ccda.component?.structuredBody?.component||[],t=[];for(let n of e)for(let r of n.section){let o=this.processSection(r);t.push({title:r.title,code:this.mapCode(r.code),text:{status:"generated",div:`<div xmlns="http://www.w3.org/1999/xhtml">${Qn(r.text)}</div>`},entry:o.map(f)}),this.resources.push(...o)}return{resourceType:"Composition",id:this.mapId(this.ccda.id),language:this.ccda.languageCode?.["@_code"],status:"final",type:this.ccda.code?this.mapCode(this.ccda.code):{coding:[{system:ge,code:We}]},confidentiality:this.ccda.confidentialityCode?.["@_code"],author:this.ccda.author?.[0]?[this.mapAuthorToReference(this.ccda.author?.[0])]:[{display:"Medplum"}],custodian:this.mapCustodianToReference(this.ccda.custodian),event:this.mapDocumentationOfToEvent(this.ccda.documentationOf),date:m(this.ccda.effectiveTime?.[0]?.["@_value"])??new Date().toISOString(),title:this.ccda.title??"Medical Summary",section:t}}processSection(e){let t=[];if(e.entry)for(let n of e.entry)this.processEntry(e,n,t);return t}processEntry(e,t,n){for(let r of t.act??[]){let o=this.processAct(e,r);o&&n.push(o)}for(let r of t.substanceAdministration??[]){let o=this.processSubstanceAdministration(e,r);o&&n.push(o)}for(let r of t.organizer??[])n.push(this.processOrganizer(e,r));for(let r of t.observation??[])n.push(this.processObservation(e,r));for(let r of t.encounter??[])n.push(this.processEncounter(e,r));for(let r of t.procedure??[])n.push(this.processProcedure(e,r))}processAct(e,t){let n=e.templateId[0]["@_root"];switch(n){case ee:case Si:case yi:case Ci:return this.processAllergyIntoleranceAct(t);case K:case Ii:case Ti:case Oi:return this.processConditionAct(t);case U:return this.processCarePlanAct(t);case Ue:return this.processConditionAct(t);case Y:return this.processProcedureAct(t);case B:return;case Ve:return;case Le:return;default:if(this.options?.ignoreUnsupportedSections)return;throw new Error("Unhandled act templateId: "+n)}}processAllergyIntoleranceAct(e){let t=e.entryRelationship?.find(s=>s["@_typeCode"]==="SUBJ")?.observation?.[0];if(!t)return;let n={resourceType:"AllergyIntolerance",id:this.mapId(e.id),clinicalStatus:this.createClinicalStatus(e),verificationStatus:this.createVerificationStatus(),type:"allergy",category:["food"],patient:f(this.patient),recorder:this.mapAuthorToReference(e.author?.[0]),recordedDate:this.mapEffectiveTimeToDateTime(e.effectiveTime?.[0]),onsetDateTime:this.mapEffectiveTimeToDateTime(t.effectiveTime?.[0])};t.value?.["@_code"]==="414285001"&&(n.category=["food"]),n.extension=this.mapTextReference(t.text);let r=t.participant?.[0]?.participantRole?.playingEntity?.code;r&&(n.code=this.mapCode(r),n.code&&r.originalText?.reference?.["@_value"]&&(n.code.extension=this.mapTextReference(r.originalText)));let o=t.entryRelationship?.find(s=>s["@_typeCode"]==="MFST")?.observation;return o&&(n.reaction=o.map(s=>this.processReaction(s))),n.asserter=this.mapAuthorToReference(t.author?.[0]),n}processConditionAct(e){let t=e.entryRelationship?.find(r=>r["@_typeCode"]==="SUBJ")?.observation?.[0];if(!t)return;let n={resourceType:"Condition",id:this.mapId(e.id),identifier:this.concatArrays(this.mapIdentifiers(e.id),this.mapIdentifiers(t.id)),meta:{profile:[_n]},clinicalStatus:{coding:[{system:Pt,code:Ie.mapCcdaToFhirWithDefault(e.statusCode?.["@_code"],"active")}]},verificationStatus:{coding:[{system:dn,code:"confirmed"}]},category:[{coding:[{system:ln,code:"problem-list-item",display:"Problem List Item"}]}],code:this.mapCode(t.value),subject:f(this.patient),onsetDateTime:m(t.effectiveTime?.[0]?.low?.["@_value"]),abatementDateTime:m(t.effectiveTime?.[0]?.high?.["@_value"]),recordedDate:this.mapEffectiveTimeToDateTime(e.effectiveTime?.[0]),recorder:this.mapAuthorToReference(t.author?.[0]),asserter:this.mapAuthorToReference(t.author?.[0])};return n.extension=this.mapTextReference(t.text),n}processCarePlanAct(e){return{resourceType:"CarePlan",id:this.mapId(e.id),identifier:this.mapIdentifiers(e.id),status:"completed",intent:"plan",title:"CARE PLAN",category:e.code?[this.mapCode(e.code)]:void 0,subject:f(this.patient),description:Te(e.text)}}processProcedureAct(e){return{resourceType:"Procedure",id:this.mapId(e.id),identifier:this.mapIdentifiers(e.id),status:"completed",code:this.mapCode(e.code),subject:f(this.patient),performedDateTime:m(e.effectiveTime?.[0]?.["@_value"]),recorder:this.mapAuthorToReference(e.author?.[0]),asserter:this.mapAuthorToReference(e.author?.[0]),extension:this.mapTextReference(e.text)}}processSubstanceAdministration(e,t){let n=e.templateId[0]["@_root"];switch(n){case Pe:case U:return this.processMedicationSubstanceAdministration(t);case X:case J:return this.processImmunizationSubstanceAdministration(t);default:if(this.options?.ignoreUnsupportedSections)return;throw new Error("Unhandled substance administration templateId: "+n)}}processMedicationSubstanceAdministration(e){let t=this.mapId(e.id),n=e.consumable?.manufacturedProduct?.[0]?.manufacturedMaterial?.[0]?.code?.[0],r=e.routeCode,o=e.doseQuantity,s=e.consumable?.manufacturedProduct?.[0]?.manufacturerOrganization?.[0],a=e.entryRelationship?.find(E=>E.substanceAdministration?.[0]?.templateId?.[0]?.["@_root"]===Be)?.substanceAdministration?.[0],h,S;return s?h={resourceType:"Medication",id:"med-"+t,code:this.mapCode(n),extension:this.mapTextReference(n?.originalText),manufacturer:s?{identifier:{value:s.id?.[0]?.["@_root"]},display:s.name?.[0]}:void 0}:S={...this.mapCode(n),extension:this.mapTextReference(n?.originalText)},{resourceType:"MedicationRequest",id:t,contained:h?[h]:void 0,meta:{profile:[mn]},extension:this.mapTextReference(e.text),status:tt.mapCcdaToFhirWithDefault(e.statusCode?.["@_code"],"active"),intent:"order",medicationReference:h?{reference:"#med-"+t}:void 0,medicationCodeableConcept:S,subject:f(this.patient),authoredOn:m(e.author?.[0]?.time?.["@_value"]),dispenseRequest:e.effectiveTime?.[0]?{validityPeriod:{start:m(e.effectiveTime?.[0]?.low?.["@_value"]),end:m(e.effectiveTime?.[0]?.high?.["@_value"])}}:void 0,dosageInstruction:[{text:typeof e.text=="string"?e.text:void 0,extension:this.mapTextReference(a?.text),route:r?this.mapCode(r):void 0,timing:{repeat:e.effectiveTime?.[1]?.period?{period:Number(e.effectiveTime?.[1]?.period["@_value"]),periodUnit:e.effectiveTime?.[1]?.period["@_unit"]}:void 0},doseAndRate:o?[{doseQuantity:{system:nt,value:Number(o["@_value"]),code:"[IU]",unit:"[IU]"}}]:void 0}]}}processImmunizationSubstanceAdministration(e){let t=e.consumable;if(!t)return;let n={resourceType:"Immunization",id:this.mapId(e.id),identifier:this.mapIdentifiers(e.id),status:et.mapCcdaToFhirWithDefault(e.statusCode?.["@_code"],"completed"),vaccineCode:this.mapCode(t.manufacturedProduct?.[0]?.manufacturedMaterial?.[0]?.code?.[0]),patient:f(this.patient),occurrenceDateTime:m(e.effectiveTime?.[0]?.["@_value"]),lotNumber:t.manufacturedProduct?.[0]?.manufacturedMaterial?.[0]?.lotNumberText?.[0]};return e.performer&&(n.performer=this.mapCcdaPerformerArrayToImmunizationPerformerArray(e.performer)),n.extension=this.mapTextReference(e.text),e.consumable?.manufacturedProduct?.[0]?.manufacturerOrganization?.[0]&&(n.manufacturer={display:e.consumable?.manufacturedProduct?.[0]?.manufacturerOrganization?.[0]?.name?.[0]}),n}processReaction(e){let t={id:this.mapId(e.id),manifestation:[this.mapCode(e.value)],onset:m(e.effectiveTime?.[0]?.low?.["@_value"])};return this.processSeverity(e,t),t.manifestation&&t.manifestation.length>0&&e.text?.reference?.["@_value"]&&(t.manifestation[0].extension=this.mapTextReference(e.text)),t}processSeverity(e,t){let n=e.entryRelationship?.find(o=>o["@_typeCode"]==="SUBJ")?.observation?.[0];if(!n)return;let r=n.value?.["@_code"];r&&(t.severity=Ke.mapCcdaToFhir(r)),t.extension=this.mapTextReference(n.text)}mapEffectiveTimeToDateTime(e){if(e?.["@_value"])return m(e["@_value"]);if(e?.low?.["@_value"])return m(e.low["@_value"])}mapEffectiveTimeToPeriod(e){if(!e?.["@_value"]&&(e?.low||e?.high))return{start:m(e?.low?.["@_value"]),end:m(e?.high?.["@_value"])}}mapGenderCode(e){return e?{F:"female",M:"male",UN:"unknown"}[e]:void 0}getTelecomSystem(e){if(e)return e.startsWith("tel:")?"phone":e.startsWith("mailto:")?"email":"other"}getTelecomValue(e){if(e)return e.replace(/^(tel:|mailto:)/,"")}mapCode(e){if(!e)return;let t={coding:[{system:Ee(e["@_codeSystem"]),code:e["@_code"],display:e["@_displayName"]}],text:e["@_displayName"]};if(e.translation)for(let n of e.translation)t.coding.push({system:Ee(n["@_codeSystem"]),code:n["@_code"],display:n["@_displayName"]});return t}mapCodeToCoding(e){if(e)return{system:Ee(e["@_codeSystem"]),code:e["@_code"],display:e["@_displayName"]}}createClinicalStatus(e){return{coding:[{system:Fe,code:Je.mapCcdaToFhirWithDefault(e.statusCode?.["@_code"],"active")}]}}createVerificationStatus(){return{coding:[{system:Lt,code:"confirmed"}]}}mapAuthorToReference(e){if(!e)return;let t={resourceType:"Practitioner",id:this.mapId(e.assignedAuthor?.id),identifier:this.mapIdentifiers(e.assignedAuthor?.id),name:this.mapCcdaNameArrayFhirHumanNameArray(e.assignedAuthor?.assignedPerson?.name),address:this.mapAddresses(e.assignedAuthor?.addr),telecom:this.mapTelecom(e.assignedAuthor?.telecom),qualification:e.assignedAuthor?.code?[this.mapCode(e.assignedAuthor?.code)]:void 0};return this.resources.push(t),f(t)}mapAssignedEntityToReference(e){if(!e)return;let t=e.assignedPerson,n=e.representedOrganization,r={resourceType:"Practitioner",id:this.mapId(e?.id),identifier:this.mapIdentifiers(e?.id),name:this.mapCcdaNameArrayFhirHumanNameArray(t?.name),address:this.mapAddresses(e?.addr),telecom:this.mapTelecom(e?.telecom)};this.resources.push(r);let o={resourceType:"Organization",id:this.mapId(e?.id),identifier:this.mapIdentifiers(n?.id),name:n?.name?.[0],address:this.mapAddresses(n?.addr)};this.resources.push(o);let s={resourceType:"PractitionerRole",id:this.mapId(e?.id),practitioner:f(r),organization:f(o)};return this.resources.push(s),f(s)}mapCustodianToReference(e){if(!e)return;let t={resourceType:"Organization",id:this.mapId(e.assignedCustodian.representedCustodianOrganization.id),identifier:this.mapIdentifiers(e.assignedCustodian.representedCustodianOrganization.id),name:e.assignedCustodian.representedCustodianOrganization.name?.[0],address:this.mapAddresses(e.assignedCustodian.representedCustodianOrganization.addr),telecom:this.mapTelecom(e.assignedCustodian.representedCustodianOrganization.telecom)};return this.resources.push(t),f(t)}mapDocumentationOfToEvent(e){if(!e)return;let t=e.serviceEvent;if(t)return[{code:t.code?[this.mapCode(t.code)]:void 0,period:this.mapEffectiveTimeToPeriod(t.effectiveTime?.[0])}]}concatArrays(e,t){return e?t?[...e,...t]:e:t}mapCcdaPerformerArrayToImmunizationPerformerArray(e){let t=[];for(let n of e){let r=n.assignedEntity,o=this.mapAssignedEntityToReference(r);o&&t.push({actor:o})}return t}processOrganizer(e,t){return e.templateId[0]["@_root"]===Me?this.processCareTeamOrganizer(t):this.processVitalsOrganizer(t)}processCareTeamOrganizer(e){let t=[];if(e.component)for(let r of e.component){let o=this.processCareTeamMember(r);o&&t.push(o)}return{resourceType:"CareTeam",id:this.mapId(e.id),identifier:this.mapIdentifiers(e.id),participant:t.length>0?t:void 0}}processCareTeamMember(e){let t=e.act?.[0];if(!t)return;let n=t.performer?.[0];if(n)return{role:n.functionCode?[this.mapCode(n.functionCode)]:void 0,member:this.mapAssignedEntityToReference(n.assignedEntity),period:this.mapEffectiveTimeToPeriod(t.effectiveTime?.[0])}}processVitalsOrganizer(e){let t={resourceType:"Observation",id:this.mapId(e.id),identifier:this.mapIdentifiers(e.id),status:"final",category:this.mapObservationTemplateIdToObservationCategory(e.templateId),code:this.mapCode(e.code),subject:f(this.patient)};if(e.effectiveTime?.[0]?.["@_value"]&&(t.effectiveDateTime=m(e.effectiveTime?.[0]?.["@_value"])),e.component){let n=[];for(let r of e.component)n.push(...this.processVitalsComponent(r));n.length>0&&(t.hasMember=n)}return t}processVitalsComponent(e){let t=[];if(e.observation)for(let n of e.observation){let r=this.processVitalsObservation(n);t.push(f(r)),this.resources.push(r)}return t}processObservation(e,t){let n=t.templateId[0]["@_root"];if(n===te||n===we)return this.processGoalObservation(t);switch(e.templateId[0]["@_root"]){case U:case te:return this.processGoalObservation(t);default:return this.processVitalsObservation(t)}}processGoalObservation(e){let t={resourceType:"Goal",id:this.mapId(e.id),identifier:this.mapIdentifiers(e.id),lifecycleStatus:this.mapGoalLifecycleStatus(e),description:this.mapCode(e.code),subject:f(this.patient),startDate:ut(e.effectiveTime?.[0]?.["@_value"])};return t.target=e.entryRelationship?.map(n=>({measure:this.mapCode(n.act?.[0]?.code),detailCodeableConcept:this.mapCode(n.act?.[0]?.code),dueDate:m(n.act?.[0]?.effectiveTime?.[0]?.low?.["@_value"])})),t.extension=this.mapTextReference(e.text),t}mapGoalLifecycleStatus(e){return{active:"active",completed:"completed",cancelled:"cancelled",aborted:"cancelled"}[e.statusCode["@_code"]??"active"]}processVitalsObservation(e){let t={resourceType:"Observation",id:this.mapId(e.id),identifier:this.mapIdentifiers(e.id),status:"final",category:this.mapObservationTemplateIdToObservationCategory(e.templateId),code:this.mapCode(e.code),subject:f(this.patient),referenceRange:this.mapReferenceRangeArray(e.referenceRange),performer:e.author?.map(n=>this.mapAuthorToReference(n)).filter(Boolean)};if(e.value?.["@_xsi:type"])switch(e.value["@_xsi:type"]){case"PQ":case"CO":t.valueQuantity={value:e.value["@_value"]?parseFloat(e.value["@_value"]):void 0,unit:e.value["@_unit"],system:nt,code:e.value["@_unit"]};break;case"CD":case"CE":t.valueCodeableConcept=this.mapCode(e.value);break;case"ST":t.valueString=e.value["#text"]??"";break;default:console.warn(`Unhandled observation value type: ${e.value["@_xsi:type"]}`)}return e.effectiveTime?.[0]?.["@_value"]&&(t.effectiveDateTime=m(e.effectiveTime?.[0]?.["@_value"])),t.extension=this.mapTextReference(e.text),t}mapObservationTemplateIdToObservationCategory(e){if(!e)return;let t=new Set,n=[];for(let r of e){let o=$n.mapCcdaToFhirCodeableConcept(r["@_root"]);o?.coding?.[0]?.code&&!t.has(o.coding[0].code)&&(t.add(o.coding[0].code),n.push(o))}return Array.from(n.values())}mapReferenceRangeArray(e){if(!(!e||e.length===0))return e.map(t=>this.mapReferenceRange(t)).filter(Boolean)}mapReferenceRange(e){if(!e)return;let t=e.observationRange;if(!t)return;let n={};return n.extension=this.mapTextReference(t.text),n}processEncounter(e,t){let n={resourceType:"Encounter",id:this.mapId(t.id),identifier:this.mapIdentifiers(t.id),status:Yn.mapCcdaToFhirWithDefault(t.statusCode?.["@_code"],"unknown"),class:{system:pn,code:t.code?.["@_code"]??"AMB",display:t.code?.["@_displayName"]??"Ambulatory"},type:t.code?[this.mapCode(t.code)]:void 0,subject:f(this.patient),period:this.mapEffectiveTimeToPeriod(t.effectiveTime?.[0])};if(t.performer&&(n.participant=t.performer.map(r=>({type:[{coding:[{system:hn,code:r["@_typeCode"]??"PPRF",display:"Primary Performer"}]}],individual:this.mapAssignedEntityToReference(r.assignedEntity)}))),t.entryRelationship){let r=t.entryRelationship.filter(o=>o["@_typeCode"]==="RSON").map(o=>{let s=o.observation?.[0];if(!s)return;let a={resourceType:"Condition",id:this.mapId(s.id),identifier:this.mapIdentifiers(s.id),clinicalStatus:{coding:[{system:Pt,code:"active"}]},verificationStatus:{coding:[{system:bt,code:"confirmed"}]},code:this.mapCode(s.value),subject:f(this.patient),onsetDateTime:m(s.effectiveTime?.[0]?.low?.["@_value"])};return this.resources.push(a),{condition:f(a),use:{coding:[{system:fn,code:"AD",display:"Admission diagnosis"}]}}}).filter(Boolean);r.length>0&&(n.diagnosis=r)}return n.extension=this.mapTextReference(t.text),n}processProcedure(e,t){return{resourceType:"Procedure",id:this.mapId(t.id),identifier:this.mapIdentifiers(t.id),status:Hn.mapCcdaToFhirWithDefault(t.statusCode?.["@_code"],"completed"),code:this.mapCode(t.code),subject:f(this.patient),performedPeriod:this.mapEffectiveTimeToPeriod(t.effectiveTime?.[0]),bodySite:t.targetSiteCode?[this.mapCode(t.targetSiteCode)]:void 0,extension:this.mapTextReference(t.text)}}mapTextReference(e){if(!(!e||typeof e!="object")&&e?.reference?.["@_value"])return[{url:Ye,valueString:e.reference?.["@_value"]}]}};function Te(i){if(i){if(typeof i=="string")return i;if(typeof i=="object"&&"#text"in i)return i["#text"]}}var zn=[{"@_root":Z,"@_extension":"2015-08-01"},{"@_root":Z},{"@_root":pt,"@_extension":"2015-08-01"},{"@_root":pt}],Zn=[{"@_root":Z,"@_extension":"2015-08-01"},{"@_root":Z},{"@_root":ht,"@_extension":"2015-08-01"},{"@_root":ht}],go=[{"@_root":ee,"@_extension":"2015-08-01"},{"@_root":ee}],Ao=[{"@_root":Pe,"@_extension":"2014-06-09"}],No=[{"@_root":K,"@_extension":"2015-08-01"},{"@_root":K}],Ro=[{"@_root":X},{"@_root":X,"@_extension":"2015-08-01"},{"@_root":J},{"@_root":J,"@_extension":"2015-08-01"}],Do=[{"@_root":Ei,"@_extension":"2015-08-01"}],vo=[{"@_root":_t},{"@_root":_t,"@_extension":"2015-08-01"}],xo=[{"@_root":Y,"@_extension":"2014-06-09"}],ua=[{"@_root":U,"@_extension":"2014-06-09"}],da=[{"@_root":ft,"@_extension":"2015-08-01"}],Po=[{"@_root":ft,"@_extension":"2015-08-01"}],bo=[{"@_root":Ai,"@_extension":"2015-08-01"}],Lo=[{"@_root":be}],Uo=[{"@_root":U},{"@_root":U,"@_extension":"2014-06-09"}],Vo=[{"@_root":gi,"@_extension":"2015-08-01"}],Mo=[{"@_root":te}],wo=[{"@_root":Ue,"@_extension":"2015-08-01"}],Bo=[{"@_root":B,"@_extension":"2014-06-09"}],ko=[{"@_root":Ni,"@_extension":"2015-08-01"}],Fo=[{"@_root":Ve,"@_extension":"2016-11-01"}],Go=[{"@_root":Me,"@_extension":"2022-06-01"}],Yo=[{"@_root":Le,"@_extension":"2015-08-01"}],Xn=Object.fromEntries([[In,go],[On,Ao],[He,No],[Tn,Ro],[Cn,Do],[yn,vo],[gn,xo],[Sn,Po],[je,Lo],[$e,Uo],[Nn,Vo],[fe,Mo],[_e,wo],[me,Bo],[Dn,ko],[qe,Fo],[vn,Go],[xn,Yo],[An,bo]]);function Ia(i,e){return new Vt(i,e).convert()}var Vt=class{constructor(e,t){this.bundle=e,this.options=t;let n=this.findResource("Composition");if(!n)throw new Error("Composition not found");let r=this.findResource("Patient");if(!r)throw new Error("Patient not found");this.composition=n,this.patient=r}convert(){let e=this.createSections(),t=this.composition.section?.find(o=>o.code?.coding?.[0]?.code===me)?.entry?.find(o=>o.reference?.startsWith("ServiceRequest/")),n,r;return this.options?.type==="referral"?(n=Zn,r={"@_code":Rn,"@_displayName":"Referral Note","@_codeSystem":N,"@_codeSystemName":"LOINC"}):(n=zn,r={"@_code":We,"@_displayName":"Summarization of Episode Note","@_codeSystem":N,"@_codeSystemName":"LOINC"}),{realmCode:{"@_code":"US"},typeId:{"@_root":ii,"@_extension":"POCD_HD000040"},templateId:n,id:this.mapIdentifiers(this.composition.id,void 0),code:r,title:this.composition.title,effectiveTime:this.mapEffectiveTime(this.composition.date,void 0),confidentialityCode:this.composition.confidentiality?kn.mapFhirToCcdaCode(this.composition.confidentiality):void 0,languageCode:{"@_code":this.composition.language??"en-US"},recordTarget:this.createRecordTarget(),author:this.mapAuthor(this.composition.author?.[0],this.composition.date,!0),custodian:this.mapCustodian(this.composition.custodian),informationRecipient:this.mapRecipient(t),documentationOf:this.mapDocumentationOf(this.composition.event),component:e.length>0?{structuredBody:{component:e.map(o=>({section:[o]}))}}:void 0}}findResource(e){return this.bundle.entry?.find(t=>t.resource?.resourceType===e)?.resource}findResourceByReference(e){if(!e?.reference)return;let[t,n]=e.reference.split("/");if(!(!t||!n))return this.bundle.entry?.find(r=>r.resource?.resourceType===t&&r.resource?.id===n)?.resource}findResourcesByReferences(e){return e?e.map(t=>this.findResourceByReference(t)).filter(t=>!!t):[]}createRecordTarget(){if(!this.patient)throw new Error("Patient not found");return[{patientRole:{id:this.mapIdentifiers(this.patient.id,this.patient.identifier),addr:this.mapFhirAddressArrayToCcdaAddressArray(this.patient.address),telecom:this.mapTelecom(this.patient.telecom),patient:this.mapPatient(this.patient)}}]}mapPatient(e){return{name:this.mapNames(e.name),administrativeGenderCode:this.mapGender(e.gender),birthTime:this.mapBirthDate(e.birthDate),raceCode:this.mapRace(e),"sdtc:raceCode":this.mapDetailedRace(e),ethnicGroupCode:this.mapEthnicity(e.extension),languageCommunication:this.mapLanguageCommunication(e.communication)}}mapNames(e){return e?.map(t=>({"@_use":t.use?ze.mapFhirToCcdaWithDefault(t.use,"L"):void 0,prefix:t.prefix,family:t.family,given:t.given,suffix:t.suffix}))}mapGender(e){if(e)return{"@_code":Fn.mapFhirToCcda(e),"@_displayName":e?Q(e):"Unknown","@_codeSystem":De,"@_codeSystemName":"AdministrativeGender"}}mapBirthDate(e){if(e)return{"@_value":e.replace(/-/g,"")}}mapFhirAddressArrayToCcdaAddressArray(e){return!e||e.length===0?[{"@_nullFlavor":"UNK"}]:e.map(t=>this.mapFhirAddressToCcdaAddress(t)).filter(Boolean)}mapFhirAddressToCcdaAddress(e){return e?{"@_use":e.use?Ze.mapFhirToCcda(e.use):void 0,streetAddressLine:e.line||[],city:e.city,state:e.state,postalCode:e.postalCode,country:e.country}:void 0}mapRace(e){let t=Ne(e,he,"ombCategory")?.valueCoding;return t?[{"@_code":t.code,"@_displayName":t.display,"@_codeSystem":xe,"@_codeSystemName":"CDC Race and Ethnicity"}]:[{"@_nullFlavor":"UNK"}]}mapDetailedRace(e){let t=Ne(e,he,"detailed")?.valueCoding;if(t)return[{"@_code":t.code,"@_displayName":t.display,"@_codeSystem":xe,"@_codeSystemName":"CDC Race and Ethnicity"}]}mapEthnicity(e){let n=e?.find(r=>r.url===Ge)?.extension?.find(r=>r.url==="ombCategory")?.valueCoding;return n?[{"@_code":n.code,"@_displayName":n.display,"@_codeSystem":xe,"@_codeSystemName":"CDC Race and Ethnicity"}]:[{"@_nullFlavor":"UNK"}]}mapLanguageCommunication(e){if(e?.length)return[{languageCode:{"@_code":e[0].language?.coding?.[0]?.code}}]}createSections(){let e=[];if(this.composition.section)for(let t of this.composition.section)e.push(this.createSection(t));return e}createSection(e){let t=e.code?.coding?.[0]?.code;if(!t)throw new Error(`Missing section code: ${JSON.stringify(e.code)}`);let n=Xn[t];if(!n)throw new Error(`Unknown section code: ${t}`);let r=this.findResourcesByReferences(e.entry);return t===je&&r.length===1&&r[0].resourceType==="ClinicalImpression"?this.createClinicalImpressionSection(e,r[0]):t===me&&r.length===1&&r[0].resourceType==="ServiceRequest"?this.createReasonForReferralSection(e,r[0]):{templateId:n,code:p(e.code),title:e.title,text:this.mapFhirTextDivToCcdaSectionText(e.text),entry:r.map(o=>this.createEntry(e,o)).filter(Boolean),"@_nullFlavor":r.length===0?"NI":void 0}}createEntry(e,t){switch(t.resourceType){case"AllergyIntolerance":return this.createAllergyEntry(t);case"CarePlan":return this.createPlanOfTreatmentCarePlanEntry(t);case"CareTeam":return this.createCareTeamEntry(t);case"ClinicalImpression":return this.createClinicalImpressionEntry(t);case"Condition":return this.createConditionEntry(e,t);case"DeviceUseStatement":return this.createDeviceUseStatementEntry(t);case"DiagnosticReport":return this.createDiagnosticReportEntry(t);case"Encounter":return this.createEncounterEntry(t);case"Goal":return this.createGoalEntry(e,t);case"Immunization":return this.createImmunizationEntry(t);case"MedicationRequest":return this.createMedicationEntry(t);case"Procedure":return this.createHistoryOfProceduresEntry(t);case"Observation":return this.createObservationEntry(t);case"ServiceRequest":return this.createPlanOfTreatmentServiceRequestEntry(t);default:return}}mapFhirTextDivToCcdaSectionText(e){if(!e)return;let t=Wn(e.div)?.div;return t?.["@_xmlns"]&&delete t["@_xmlns"],t}createAllergyEntry(e){let t=e.reaction?.[0];return{act:[{"@_classCode":"ACT","@_moodCode":"EVN",templateId:[{"@_root":yt},{"@_root":yt,"@_extension":"2015-08-01"}],id:this.mapIdentifiers(e.id,e.identifier),code:{"@_code":"CONC","@_codeSystem":dt},statusCode:{"@_code":Je.mapFhirToCcdaWithDefault(e.clinicalStatus?.coding?.[0]?.code,"active")},effectiveTime:this.mapEffectivePeriod(e.recordedDate,void 0),author:this.mapAuthor(e.recorder,e.recordedDate),text:this.createTextFromExtensions(e.extension),entryRelationship:[{"@_typeCode":"SUBJ",observation:[{"@_classCode":"OBS","@_moodCode":"EVN",templateId:[{"@_root":Et},{"@_root":Et,"@_extension":"2014-06-09"}],id:this.mapIdentifiers(e.id,e.identifier),code:{"@_code":"ASSERTION","@_codeSystem":ve},text:this.createTextFromExtensions(e.extension),statusCode:{"@_code":"completed"},effectiveTime:this.mapEffectivePeriod(e.onsetPeriod?.start??e.onsetDateTime,e.onsetPeriod?.end,!0),value:this.mapAllergyCategory(e.category),author:this.mapAuthor(e.asserter,e.recordedDate),participant:[{"@_typeCode":"CSM",participantRole:{"@_classCode":"MANU",playingEntity:{"@_classCode":"MMAT",code:e.code?.coding?.[0]?.code==="716186003"?{"@_nullFlavor":"NA"}:{...p(e.code),originalText:e.code?.extension?{reference:this.getNarrativeReference(e.code?.extension)}:void 0}}}}],entryRelationship:t?[{"@_typeCode":"MFST","@_inversionInd":"true",observation:[{"@_classCode":"OBS","@_moodCode":"EVN",templateId:[{"@_root":Tt},{"@_root":Tt,"@_extension":"2014-06-09"}],id:this.mapIdentifiers(t.id,void 0),code:{"@_code":"ASSERTION","@_codeSystem":ve},statusCode:{"@_code":"completed"},effectiveTime:this.mapEffectiveDate(e.onsetDateTime,e.onsetPeriod),value:H(t.manifestation?.[0]),text:this.createTextFromExtensions(t.manifestation?.[0]?.extension),entryRelationship:[{"@_typeCode":"SUBJ","@_inversionInd":"true",observation:[{"@_classCode":"OBS","@_moodCode":"EVN",templateId:[{"@_root":It},{"@_root":It,"@_extension":"2014-06-09"}],code:{"@_code":"SEV","@_codeSystem":ve,"@_codeSystemName":"ActCode"},statusCode:{"@_code":"completed"},value:{"@_xsi:type":"CD","@_code":Ke.mapFhirToCcdaWithDefault(t.severity,"M"),"@_displayName":t.severity?Q(t.severity):void 0,"@_codeSystem":L,"@_codeSystemName":"SNOMED CT"},text:this.createTextFromExtensions(t.extension)}]}]}]}]:[]}]}]}]}}mapAllergyCategory(e){let t=Gn.mapFhirToCcdaCode(e?.[0]);return t||(t={"@_code":"419199007","@_displayName":"Allergy to substance (disorder)","@_codeSystem":L,"@_codeSystemName":"SNOMED CT"}),{"@_xsi:type":"CD",...t}}mapAuthor(e,t,n){if(!e)return;let r=this.findResourceByReference(e);if(!r)return;let o;if(r.resourceType==="Organization"?o=r:r.resourceType==="PractitionerRole"&&(o=this.findResourceByReference(r.organization),r=this.findResourceByReference(r.practitioner)),!r)return;let s;"address"in r&&(s=r.address);let a;"telecom"in r&&(a=r.telecom);let h;"qualification"in r&&(h=r.qualification?.[0]);let S;return["Patient","Practitioner","RelatedPerson"].includes(r.resourceType)&&(S=r.name),[{templateId:[{"@_root":ji}],time:t?{"@_value":O(t)}:void 0,assignedAuthor:{id:this.mapIdentifiers(r.id,r.identifier),addr:this.mapFhirAddressArrayToCcdaAddressArray(s),telecom:this.mapTelecom(a),code:p(h),assignedPerson:S?{name:this.mapNames(S)}:void 0,assignedAuthoringDevice:!S&&n?{manufacturerModelName:"Medplum",softwareName:"Medplum"}:void 0,representedOrganization:o?.name?{name:[o.name]}:void 0}}]}mapCustodian(e){if(!e)return;let t=this.findResourceByReference(e);if(t)return{assignedCustodian:{representedCustodianOrganization:{id:this.mapIdentifiers(t.id,t.identifier),name:t.name?[t.name]:void 0,telecom:this.mapTelecom(t.telecom),addr:this.mapFhirAddressArrayToCcdaAddressArray(t.address)}}}}mapRecipient(e){if(!e)return;let t=this.findResourceByReference(e);if(!t)return;let n=t.performer;if(!n||n.length===0)return;let r=this.findResourceByReference(n[0]);if(!(!r||r.resourceType!=="Practitioner"))return{intendedRecipient:{informationRecipient:{name:this.mapNames(r.name)}}}}mapDocumentationOf(e){if(!e||e.length===0)return;let t=e[0];if(!(!t||!t.code&&!t.period))return{serviceEvent:{"@_classCode":"PCPR",code:p(t.code?.[0]),effectiveTime:this.mapEffectiveDate(void 0,t.period)}}}createMedicationEntry(e){let t=e.contained?.find(s=>s.resourceType==="Medication"),n=t?.code||e.medicationCodeableConcept,r=t?.manufacturer,o=[];if(e.dispenseRequest?.validityPeriod){let s=this.mapEffectiveDate(void 0,e.dispenseRequest.validityPeriod);s&&o.push(...s)}return e.dosageInstruction?.[0]?.timing?.repeat?.period&&o.push({"@_xsi:type":"PIVL_TS","@_institutionSpecified":"true","@_operator":"A",period:{"@_value":e.dosageInstruction[0].timing.repeat.period.toString(),"@_unit":e.dosageInstruction[0].timing.repeat.periodUnit}}),{substanceAdministration:[{"@_classCode":"SBADM","@_moodCode":"EVN",templateId:[{"@_root":Ot,"@_extension":"2014-06-09"},{"@_root":Ot}],id:[{"@_root":e.id||crypto.randomUUID()}],text:this.createTextFromExtensions(e.extension),statusCode:{"@_code":tt.mapFhirToCcdaWithDefault(e.status,"active")},effectiveTime:o,routeCode:this.mapMedicationRoute(e.dosageInstruction?.[0]?.route),doseQuantity:this.mapDoseQuantity(e.dosageInstruction?.[0]?.doseAndRate?.[0]),consumable:{"@_typeCode":"CSM",manufacturedProduct:[{"@_classCode":"MANU",templateId:[{"@_root":St,"@_extension":"2014-06-09"},{"@_root":St}],manufacturedMaterial:[{code:[{...p(n),originalText:this.createTextFromExtensions(t?.extension)}]}],manufacturerOrganization:r?[{id:this.mapIdentifiers(r.id,r.identifier?[r.identifier]:void 0),name:[r.display]}]:void 0}]},author:this.mapAuthor(e.requester,e.authoredOn),entryRelationship:e.dosageInstruction?.filter(s=>!!s.extension)?.map(s=>({"@_typeCode":"COMP",substanceAdministration:[{"@_classCode":"SBADM","@_moodCode":"EVN",templateId:[{"@_root":Be}],code:{"@_code":Pn,"@_codeSystem":N,"@_codeSystemName":"LOINC","@_displayName":"Medication Instructions"},text:this.createTextFromExtensions(s.extension),consumable:{manufacturedProduct:[{manufacturedLabeledDrug:[{"@_nullFlavor":"NA"}]}]}}]}))}]}}mapMedicationRoute(e){if(e)return p(e)}mapDoseQuantity(e){if(e?.doseQuantity)return{"@_value":e.doseQuantity.value?.toString(),"@_unit":e.doseQuantity.unit}}mapTelecom(e){return!e||e.length===0?[{"@_nullFlavor":"UNK"}]:e?.map(t=>({"@_use":t.use?Xe.mapFhirToCcda(t.use):void 0,"@_value":`${this.mapTelecomSystemToPrefix(t.system)}${t.value}`}))}mapTelecomSystemToPrefix(e){return e==="email"?"mailto:":e==="phone"?"tel:":e==="fax"?"fax:":""}mapIdentifiers(e,t){let n=[];if(e&&n.push({"@_root":e}),t)for(let r of t){let o=Bn(r.system);o&&n.push({"@_root":o,"@_extension":r.value})}return n}getNarrativeReference(e){let t=e?.find(n=>n.url===Ye)?.valueString;return t?{"@_value":t}:void 0}createTextFromExtensions(e){let t=this.getNarrativeReference(e);return t?{reference:t}:void 0}createConditionEntry(e,t){let n=e.code?.coding?.[0]?.code;if(n===He)return this.createProblemEntry(t);if(n===_e)return this.createHealthConcernEntry(t)}createProblemEntry(e){return{act:[{"@_classCode":"ACT","@_moodCode":"EVN",templateId:[{"@_root":mt},{"@_root":mt,"@_extension":"2015-08-01"}],id:this.mapIdentifiers(e.id,void 0),code:{"@_code":"CONC","@_codeSystem":dt},statusCode:{"@_code":Ie.mapFhirToCcdaWithDefault(e.clinicalStatus?.coding?.[0]?.code,"active")},effectiveTime:this.mapEffectivePeriod(e.recordedDate,void 0),entryRelationship:[{"@_typeCode":"SUBJ",observation:[{"@_classCode":"OBS","@_moodCode":"EVN",templateId:[{"@_root":k},{"@_root":k,"@_extension":"2015-08-01"}],id:e.identifier?this.mapIdentifiers(void 0,e.identifier):[{"@_root":Re()}],text:this.createTextFromExtensions(e.extension),code:{"@_code":"55607006","@_codeSystem":L,"@_codeSystemName":"SNOMED CT","@_displayName":"Problem",translation:[{"@_code":bn,"@_codeSystem":N,"@_codeSystemName":"LOINC","@_displayName":"Condition"}]},statusCode:{"@_code":"completed"},effectiveTime:[{low:e.onsetDateTime?{"@_value":w(e.onsetDateTime)}:void 0,high:e.abatementDateTime?{"@_value":O(e.abatementDateTime)}:void 0}],value:H(e.code),author:this.mapAuthor(e.asserter,e.recordedDate)}]}]}]}}createHealthConcernEntry(e){return{act:[{"@_classCode":"ACT","@_moodCode":"EVN",templateId:[{"@_root":Rt,"@_extension":"2015-08-01"},{"@_root":Rt,"@_extension":"2022-06-01"}],id:this.mapIdentifiers(e.id,void 0),code:{"@_code":_e,"@_codeSystem":N,"@_codeSystemName":"LOINC","@_displayName":"Health Concern"},statusCode:{"@_code":Ie.mapFhirToCcdaWithDefault(e.clinicalStatus?.coding?.[0]?.code,"active")},effectiveTime:this.mapEffectivePeriod(e.recordedDate,void 0)}]}}createImmunizationEntry(e){let t=e?.manufacturer,n={substanceAdministration:[{"@_classCode":"SBADM","@_moodCode":"EVN","@_negationInd":"false",templateId:[{"@_root":At},{"@_root":At,"@_extension":"2015-08-01"}],id:this.mapIdentifiers(e.id,e.identifier),text:this.createTextFromExtensions(e.extension),statusCode:{"@_code":et.mapFhirToCcdaWithDefault(e.status,"completed")},effectiveTime:[{"@_value":w(e.occurrenceDateTime)}],consumable:{manufacturedProduct:[{"@_classCode":"MANU",templateId:[{"@_root":Nt},{"@_root":Nt,"@_extension":"2014-06-09"}],manufacturedMaterial:[{code:[p(e.vaccineCode)],lotNumberText:e.lotNumber?[e.lotNumber]:void 0}],manufacturerOrganization:t?[{id:this.mapIdentifiers(t.id,t.identifier?[t.identifier]:void 0),name:[t.display]}]:void 0}]}}]};return e.performer&&(n.substanceAdministration[0].performer=e.performer.map(r=>this.mapImmunizationPerformerToCcdaPerformer(r)).filter(Boolean)),n}mapImmunizationPerformerToCcdaPerformer(e){if(!e)return;let t=this.findResourceByReference(e.actor);if(!t)return;let n,r;return t.resourceType==="PractitionerRole"?(n=this.findResourceByReference(t.practitioner),r=this.findResourceByReference(t.organization)):t.resourceType==="Practitioner"?n=t:t.resourceType==="Organization"&&(r=t),{assignedEntity:{id:this.mapIdentifiers(t.id,t.identifier),addr:this.mapFhirAddressArrayToCcdaAddressArray(n?.address),telecom:this.mapTelecom(t.telecom),assignedPerson:n?{id:this.mapIdentifiers(n.id,n.identifier),name:this.mapNames(n.name)}:void 0,representedOrganization:r?{id:this.mapIdentifiers(r.id,r.identifier),name:r.name?[r.name]:void 0,addr:this.mapFhirAddressArrayToCcdaAddressArray(r.address),telecom:this.mapTelecom(r.telecom)}:void 0}}}createObservationEntry(e){return e.hasMember?{organizer:[this.createVitalSignsOrganizer(e)]}:{observation:[this.createVitalSignObservation(e)]}}createPlanOfTreatmentCarePlanEntry(e){if(e.status==="completed")return{act:[{"@_classCode":"ACT","@_moodCode":"INT",templateId:[{"@_root":xi}],id:this.mapIdentifiers(e.id,e.identifier),code:H(e.category?.[0]),text:e.description?{"#text":e.description}:this.createTextFromExtensions(e.extension),statusCode:{"@_code":e.status}}]}}createGoalEntry(e,t){let n=e.code?.coding?.[0]?.code,r;if(n===$e)r=[{"@_root":gt}];else if(n===fe)r=[{"@_root":we}];else return;let o;if(n===fe)o={"@_code":Ln,"@_codeSystem":N,"@_codeSystemName":"LOINC","@_displayName":"Resident's overall goal established during assessment process"};else if(t.description)o=p(t.description);else return;return{observation:[{"@_classCode":"OBS","@_moodCode":"GOL",templateId:r,id:this.mapIdentifiers(t.id,t.identifier),code:o,statusCode:{"@_code":this.mapPlanOfTreatmentStatus(t.lifecycleStatus)},effectiveTime:[{"@_value":O(t.startDate)}],value:t.description?.text?{"@_xsi:type":"ST","#text":t.description.text}:void 0,text:this.createTextFromExtensions(t.extension),entryRelationship:t.target?.map(s=>({"@_typeCode":"RSON","@_inversionInd":"true",act:[{"@_classCode":"ACT","@_moodCode":"EVN",templateId:[{"@_root":re},{"@_root":re,"@_extension":"2014-06-09"}],code:p(s.measure),statusCode:{"@_code":"completed"},effectiveTime:[{"@_value":O(t.startDate)}]}]}))}]}}mapPlanOfTreatmentStatus(e){switch(e){case"achieved":return"completed";case"cancelled":return"cancelled";default:return"active"}}createVitalSignsOrganizer(e){let t=[];if(e.hasMember)for(let r of e.hasMember){let o=this.findResourceByReference(r);if(!(!o||o.resourceType!=="Observation"))if(o.component)for(let s of o.component)t.push({observation:[this.createVitalSignComponentObservation(o,s)]});else t.push({observation:[this.createVitalSignObservation(o)]})}return{"@_classCode":"CLUSTER","@_moodCode":"EVN",templateId:[{"@_root":ae},{"@_root":ae,"@_extension":"2015-08-01"}],id:this.mapIdentifiers(e.id,e.identifier),code:p(e.code),statusCode:{"@_code":"completed"},effectiveTime:[{"@_value":O(e.effectiveDateTime)}],component:t}}createVitalSignObservation(e){return{"@_classCode":"OBS","@_moodCode":"EVN",templateId:this.mapObservationTemplateId(e),id:this.mapIdentifiers(e.id,e.identifier),code:p(e.code),statusCode:{"@_code":"completed"},effectiveTime:[{"@_value":O(e.effectiveDateTime)}],value:this.mapObservationValue(e),referenceRange:this.mapReferenceRangeArray(e.referenceRange),text:this.createTextFromExtensions(e.extension),author:this.mapAuthor(e.performer?.[0],e.effectiveDateTime)}}createVitalSignComponentObservation(e,t){return{"@_classCode":"OBS","@_moodCode":"EVN",templateId:this.mapObservationTemplateId(e),id:this.mapIdentifiers(e.id,e.identifier),code:p(t.code),statusCode:{"@_code":"completed"},effectiveTime:[{"@_value":O(e.effectiveDateTime)}],value:this.mapObservationValue(t),referenceRange:this.mapReferenceRangeArray(t.referenceRange),text:this.createTextFromExtensions(t.extension),author:this.mapAuthor(e.performer?.[0],e.effectiveDateTime)}}mapObservationTemplateId(e){let t=e.code?.coding?.[0]?.code,n=e.category?.[0]?.coding?.[0]?.code;return t===Un?[{"@_root":de},{"@_root":de,"@_extension":"2014-06-09"}]:t===Vn?[{"@_root":le},{"@_root":le,"@_extension":"2014-06-09"}]:t===Mn?[{"@_root":ke,"@_extension":"2023-06-28"}]:t===wn?[{"@_root":pe},{"@_root":pe,"@_extension":"2016-06-01"}]:n==="exam"?[{"@_root":oe},{"@_root":oe,"@_extension":"2014-06-09"}]:n==="laboratory"?[{"@_root":ne},{"@_root":ne,"@_extension":"2015-08-01"}]:[{"@_root":ce},{"@_root":ce,"@_extension":"2014-06-09"}]}mapObservationValue(e){if(e.valueQuantity)return{"@_xsi:type":"PQ","@_unit":e.valueQuantity.unit,"@_value":e.valueQuantity.value?.toString()};if(e.valueCodeableConcept)return H(e.valueCodeableConcept);if(e.valueString)return{"@_xsi:type":"ST","#text":e.valueString}}mapReferenceRangeArray(e){if(!(!e||e.length===0))return e.map(t=>this.mapReferenceRange(t)).filter(Boolean)}mapReferenceRange(e){if(!e)return;let t=this.getNarrativeReference(e.extension);return t?{observationRange:{text:{reference:t},value:{"@_xsi:type":"ED",reference:t}}}:{observationRange:{text:this.createTextFromExtensions(e.extension)}}}createHistoryOfProceduresEntry(e){if(e.resourceType==="Procedure"){let t=["183948003","409063005","311331002","61310001","183945009","309814009","278373008","410606002","183933003","24642003","225338006","128939004"],n=e.code?.coding?.[0]?.code;return n&&t.includes(n)?{act:[{"@_classCode":"ACT","@_moodCode":"EVN",templateId:[{"@_root":re},{"@_root":re,"@_extension":"2014-06-09"}],id:this.mapIdentifiers(e.id,e.identifier),code:p(e.code),statusCode:{"@_code":"completed"},effectiveTime:this.mapEffectiveTime(e.performedDateTime,e.performedPeriod),text:this.createTextFromExtensions(e.extension)}]}:{procedure:[{"@_classCode":"PROC","@_moodCode":"EVN",templateId:[{"@_root":se},{"@_root":se,"@_extension":"2014-06-09"}],id:this.mapIdentifiers(e.id,e.identifier),code:p(e.code),statusCode:{"@_code":"completed"},effectiveTime:this.mapEffectiveTime(e.performedDateTime,e.performedPeriod),text:this.createTextFromExtensions(e.extension),targetSiteCode:p(e.bodySite?.[0]),participant:[this.mapLocationToParticipant(e.location)].filter(Boolean)}]}}if(e.resourceType==="Observation")return{observation:[{"@_classCode":"OBS","@_moodCode":"EVN",templateId:this.mapObservationTemplateId(e),id:this.mapIdentifiers(e.id,e.identifier),code:p(e.code),value:this.mapObservationValue(e),statusCode:{"@_code":"completed"},effectiveTime:this.mapEffectiveTime(e.effectiveDateTime,e.effectivePeriod),text:this.createTextFromExtensions(e.extension)}]};throw new Error(`Unknown history of procedures resource type: ${e.resourceType}`)}mapLocationToParticipant(e){if(!e)return;let t=this.findResourceByReference(e);if(t)return{"@_typeCode":"LOC",participantRole:{"@_classCode":"SDLOC",templateId:[{"@_root":Ct}],id:this.mapIdentifiers(t.id,t.identifier),code:p(t.type?.[0]),addr:t.address?this.mapFhirAddressArrayToCcdaAddressArray([t.address]):void 0,telecom:this.mapTelecom(t.telecom),playingEntity:{"@_classCode":"PLC",name:t.name?[t.name]:void 0}}}}mapEffectiveTime(e,t){if(t)return[{low:{"@_value":O(t.start)},high:{"@_value":O(t.end)}}];if(e)return[{"@_value":O(e)}]}mapEffectiveDate(e,t){if(t)return[{"@_xsi:type":"IVL_TS",low:t.start?{"@_value":w(t.start)}:void 0,high:t.end?{"@_value":w(t.end)}:void 0}];if(e)return[{"@_value":w(e)}]}mapEffectivePeriod(e,t,n=!1){if(!e&&!t)return;let r={};return e?r.low={"@_value":O(e)}:n&&(r.low={"@_nullFlavor":"NI"}),t?r.high={"@_value":O(t)}:n&&(r.high={"@_nullFlavor":"NI"}),[r]}createEncounterEntry(e){return{encounter:[{"@_classCode":"ENC","@_moodCode":"EVN",templateId:[{"@_root":ue},{"@_root":ue,"@_extension":"2015-08-01"}],id:this.mapIdentifiers(e.id,e.identifier),code:p(e.type?.[0]),text:this.createTextFromExtensions(e.extension),effectiveTime:this.mapEffectiveTime(void 0,e.period),participant:e.participant?.map(t=>({"@_typeCode":"LOC",participantRole:{"@_classCode":"SDLOC",templateId:[{"@_root":Ct}],code:p(t.type?.[0])}})),entryRelationship:e.diagnosis?.map(t=>this.createEncounterDiagnosis(t)).filter(Boolean)}]}}createEncounterDiagnosis(e){let t=this.findResourceByReference(e.condition);if(!(!t||t.resourceType!=="Condition"))return{"@_typeCode":"REFR",act:[{"@_classCode":"ACT","@_moodCode":"EVN",templateId:[{"@_root":ue,"@_extension":"2015-08-01"},{"@_root":ue}],code:{"@_code":"29308-4","@_displayName":"Diagnosis","@_codeSystem":N,"@_codeSystemName":"LOINC"},entryRelationship:[{"@_typeCode":"SUBJ",observation:[{"@_classCode":"OBS","@_moodCode":"EVN",templateId:[{"@_root":k,"@_extension":"2015-08-01"},{"@_root":k}],id:this.mapIdentifiers(t.id,t.identifier),code:{"@_code":"282291009","@_displayName":"Diagnosis interpretation","@_codeSystem":L,"@_codeSystemName":"SNOMED CT",translation:[{"@_code":"29308-4","@_displayName":"Diagnosis","@_codeSystem":N,"@_codeSystemName":"LOINC"}]},statusCode:{"@_code":"completed"},effectiveTime:this.mapEffectivePeriod(t.onsetDateTime,t.abatementDateTime),value:H(t.code)}]}]}]}}createCareTeamEntry(e){return{organizer:[{"@_classCode":"CLUSTER","@_moodCode":"EVN",templateId:[{"@_root":Dt,"@_extension":"2022-07-01"},{"@_root":Dt,"@_extension":"2022-06-01"}],id:this.mapIdentifiers(e.id,e.identifier),component:e.participant?.map(t=>({"@_typeCode":"PRF",role:t.role}))}]}}createClinicalImpressionSection(e,t){return{templateId:[{"@_root":be}],code:p(e.code),title:e.title,text:t.summary,author:this.mapAuthor(t.assessor,t.date)}}createPlanOfTreatmentServiceRequestEntry(e){return{observation:[{"@_classCode":"OBS","@_moodCode":"RQO",templateId:[{"@_root":gt}],id:this.mapIdentifiers(e.id,e.identifier),code:p(e.code),statusCode:{"@_code":this.mapPlanOfTreatmentStatus(e.status)},effectiveTime:[{"@_value":O(e.occurrenceDateTime)}],text:this.createTextFromExtensions(e.extension)}]}}createDiagnosticReportEntry(e){let t=[];if(e.result)for(let n of e.result){let r=this.findResourceByReference(n);!r||r.resourceType!=="Observation"||t.push({observation:[this.createVitalSignObservation(r)]})}return{organizer:[{"@_classCode":"CLUSTER","@_moodCode":"EVN",templateId:[{"@_root":ie},{"@_root":ie,"@_extension":"2015-08-01"}],id:this.mapIdentifiers(e.id,e.identifier),code:p(e.code),statusCode:{"@_code":"completed"},component:t}]}}createDeviceUseStatementEntry(e){let t=this.findResourceByReference(e.device);if(!t)return;let n=[],r=this.mapIdentifiers(t.id,t.identifier);return r&&n.push(...r),t.udiCarrier?.[0]?.deviceIdentifier&&n.push({"@_root":xt,"@_extension":t.udiCarrier[0].carrierHRF,"@_assigningAuthorityName":"FDA"}),{procedure:[{"@_classCode":"PROC","@_moodCode":"EVN",templateId:[{"@_root":se,"@_extension":"2014-06-09"},{"@_root":se}],id:this.mapIdentifiers(e.id,e.identifier),code:{"@_code":"360030002","@_codeSystem":L,"@_codeSystemName":"SNOMED CT","@_displayName":"Application of medical device"},statusCode:{"@_code":"completed"},participant:[{"@_typeCode":"DEV",participantRole:{"@_classCode":"MANU",templateId:[{"@_root":Li}],id:n,playingDevice:{"@_classCode":"DEV",code:p(t.type)},scopingEntity:{id:[{"@_root":xt}]}}}]}]}}createClinicalImpressionEntry(e){return{act:[{"@_classCode":"ACT","@_moodCode":"EVN",templateId:[{"@_root":Zi,"@_extension":"2016-11-01"}],id:this.mapIdentifiers(e.id,e.identifier),code:p(e.code)??{"@_code":qe,"@_codeSystem":N,"@_codeSystemName":"LOINC","@_displayName":"Note"},text:e.summary?{"#text":e.summary}:this.createTextFromExtensions(e.extension),statusCode:{"@_code":"completed"},effectiveTime:[{"@_value":w(e.date)}],author:this.mapAuthor(e.assessor,e.date)}]}}createReasonForReferralSection(e,t){return{templateId:[{"@_root":B,"@_extension":"2014-06-09"},{"@_root":B}],code:p(e.code),title:e.title,text:t.note?.[0]?.text,entry:[{act:[{"@_classCode":"PCPR","@_moodCode":"INT",templateId:[{"@_root":Qi}],id:this.mapIdentifiers(t.id,t.identifier),code:p(t.code),statusCode:{"@_code":"active"},effectiveTime:[{"@_value":O(t.occurrenceDateTime)}],priorityCode:{"@_code":"A","@_codeSystem":"2.16.840.1.113883.5.7","@_codeSystemName":"ActPriority","@_displayName":"ASAP"},author:this.mapAuthor(t.requester,t.occurrenceDateTime)}]}]}}};export{pn as ACT_CODE_SYSTEM,Ze as ADDRESS_USE_MAPPER,ao as ADDRESS_USE_VALUE_SET,ro as ADMINISTRATIVE_GENDER_CODE_SYSTEM,uo as ADMINISTRATIVE_GENDER_VALUE_SET,go as ALLERGIES_SECTION_TEMPLATE_IDS,Gn as ALLERGY_CATEGORY_MAPPER,Fe as ALLERGY_CLINICAL_CODE_SYSTEM,Ke as ALLERGY_SEVERITY_MAPPER,Je as ALLERGY_STATUS_MAPPER,Lt as ALLERGY_VERIFICATION_CODE_SYSTEM,Lo as ASSESSMENTS_SECTION_TEMPLATE_IDS,Go as CARE_TEAM_SECTION_TEMPLATE_IDS,Ye as CCDA_NARRATIVE_REFERENCE_URL,js as CCDA_TEMPLATE_CODE_SYSTEM,zn as CCDA_TEMPLATE_IDS,Pt as CLINICAL_CONDITION_CODE_SYSTEM,ua as CLINICAL_NOTES_SECTION_TEMPLATE_IDS,ln as CONDITION_CATEGORY_CODE_SYSTEM,dn as CONDITION_VERIFICATION_CODE_SYSTEM,bt as CONDITION_VER_STATUS_CODE_SYSTEM,oo as CONFIDENTIALITY_CODE_SYSTEM,kn as CONFIDENTIALITY_MAPPER,lo as CONTACT_ENTITY_USE_VALUE_SET,So as CVX_URL,bo as DEVICES_SECTION_TEMPLATE_IDS,fn as DIAGNOSIS_ROLE_CODE_SYSTEM,Vo as ENCOUNTERS_SECTION_TEMPLATE_IDS,Yn as ENCOUNTER_STATUS_MAPPER,I as EnumMapper,yo as FHIR_CVX_URL,Fn as GENDER_MAPPER,Mo as GOALS_SECTION_TEMPLATE_IDS,wo as HEALTH_CONCERNS_SECTION_TEMPLATE_IDS,F as HTTP,ze as HUMAN_NAME_USE_MAPPER,Ro as IMMUNIZATIONS_SECTION_TEMPLATE_IDS,et as IMMUNIZATION_STATUS_MAPPER,Yo as INSURANCE_SECTION_TEMPLATE_IDS,da as LAB_TESTS_SECTION_TEMPLATE_IDS,ks as LANGUAGE_MODE_CODE_SYSTEM,Ys as LANGUAGE_MODE_URL,Fs as LANGUAGE_PROFICIENCY_CODE_SYSTEM,Hs as LANGUAGE_PROFICIENCY_URL,Mn as LOINC_ADMINISTRATIVE_SEX,In as LOINC_ALLERGIES_SECTION,je as LOINC_ASSESSMENTS_SECTION,wn as LOINC_BIRTH_SEX,vn as LOINC_CARE_TEAM_SECTION,bn as LOINC_CONDITION,An as LOINC_DEVICES_SECTION,Nn as LOINC_ENCOUNTERS_SECTION,fe as LOINC_GOALS_SECTION,_e as LOINC_HEALTH_CONCERNS_SECTION,Vn as LOINC_HISTORY_OF_TOBACCO_USE,Tn as LOINC_IMMUNIZATIONS_SECTION,xn as LOINC_INSURANCE_SECTION,On as LOINC_MEDICATIONS_SECTION,Pn as LOINC_MEDICATION_INSTRUCTIONS,Dn as LOINC_MENTAL_STATUS_SECTION,qe as LOINC_NOTES_SECTION,qs as LOINC_NOTE_DOCUMENT,Ln as LOINC_OVERALL_GOAL,Ws as LOINC_PATIENT_SUMMARY_DOCUMENT,$e as LOINC_PLAN_OF_TREATMENT_SECTION,He as LOINC_PROBLEMS_SECTION,gn as LOINC_PROCEDURES_SECTION,me as LOINC_REASON_FOR_REFERRAL_SECTION,Rn as LOINC_REFERRAL_NOTE,Sn as LOINC_RESULTS_SECTION,yn as LOINC_SOCIAL_HISTORY_SECTION,We as LOINC_SUMMARY_OF_EPISODE_NOTE,Un as LOINC_TOBACCO_SMOKING_STATUS,Xn as LOINC_TO_TEMPLATE_IDS,Cn as LOINC_VITAL_SIGNS_SECTION,Ao as MEDICATIONS_SECTION_TEMPLATE_IDS,po as MEDICATION_REQUEST_STATUS_VALUE_SET,tt as MEDICATION_STATUS_MAPPER,ko as MENTAL_STATUS_SECTION_TEMPLATE_IDS,co as NAME_USE_VALUE_SET,ho as NCI_THESAURUS_URL,Oo as NDFRT_URL,Io as NUCC_TAXONOMY_URL,so as OBSERVATION_CATEGORY_CODE_SYSTEM,$n as OBSERVATION_CATEGORY_MAPPER,hn as PARTICIPATION_CODE_SYSTEM,Fo as PATIENT_NOTES_SECTION_TEMPLATE_IDS,Uo as PLAN_OF_TREATMENT_SECTION_TEMPLATE_IDS,No as PROBLEMS_SECTION_TEMPLATE_IDS,Ie as PROBLEM_STATUS_MAPPER,xo as PROCEDURES_SECTION_TEMPLATE_IDS,Hn as PROCEDURE_STATUS_MAPPER,Gs as RACE_CODE_SYSTEM,Bo as REASON_FOR_REFERRAL_SECTION_TEMPLATE_IDS,Zn as REFERRAL_TEMPLATE_IDS,Po as RESULTS_SECTION_TEMPLATE_IDS,vo as SOCIAL_HISTORY_SECTION_TEMPLATE_IDS,Qe as SYSTEM_MAPPER,Xe as TELECOM_USE_MAPPER,Eo as UNII_URL,_n as US_CORE_CONDITION_URL,Ge as US_CORE_ETHNICITY_URL,mn as US_CORE_MEDICATION_REQUEST_URL,$s as US_CORE_PATIENT_URL,he as US_CORE_RACE_URL,_o as US_DRIVER_LICENSE_URL,mo as US_NPI_URL,fo as US_SSN_URL,To as VA_MEDRT_URL,Do as VITAL_SIGNS_SECTION_TEMPLATE_IDS,En as XSI_URL,oa as convertCcdaToFhir,Js as convertCcdaToXml,Ia as convertFhirToCcda,Qn as convertToCompactXml,Xs as convertXmlToCcda,Ee as mapCcdaSystemToFhir,ut as mapCcdaToFhirDate,m as mapCcdaToFhirDateTime,p as mapCodeableConceptToCcdaCode,H as mapCodeableConceptToCcdaValue,un as mapCodingToCcdaCode,Bn as mapFhirSystemToCcda,w as mapFhirToCcdaDate,O as mapFhirToCcdaDateTime,Wn as parseXml};
3
3
  /*!
4
4
  * Reconnecting WebSocket
5
5
  * by Pedro Ladaria <pedro.ladaria@gmail.com>