@medplum/core 2.0.23 → 2.0.24
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.
- package/dist/cjs/index.cjs +14080 -13352
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.min.cjs +1 -1
- package/dist/esm/access.mjs +142 -0
- package/dist/esm/access.mjs.map +1 -0
- package/dist/esm/bundle.mjs +3 -3
- package/dist/esm/bundle.mjs.map +1 -1
- package/dist/esm/client.mjs +49 -25
- package/dist/esm/client.mjs.map +1 -1
- package/dist/esm/fhirlexer/parse.mjs.map +1 -1
- package/dist/esm/fhirmapper/parse.mjs +1 -1
- package/dist/esm/fhirmapper/parse.mjs.map +1 -1
- package/dist/esm/fhirpath/functions.mjs +2 -2
- package/dist/esm/fhirpath/functions.mjs.map +1 -1
- package/dist/esm/fhirpath/parse.mjs +2 -1
- package/dist/esm/fhirpath/parse.mjs.map +1 -1
- package/dist/esm/fhirpath/utils.mjs +4 -5
- package/dist/esm/fhirpath/utils.mjs.map +1 -1
- package/dist/esm/format.mjs +1 -1
- package/dist/esm/format.mjs.map +1 -1
- package/dist/esm/hl7.mjs +6 -6
- package/dist/esm/hl7.mjs.map +1 -1
- package/dist/esm/index.min.mjs +1 -1
- package/dist/esm/index.mjs +5 -2
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/outcomes.mjs +38 -14
- package/dist/esm/outcomes.mjs.map +1 -1
- package/dist/esm/readablepromise.mjs +1 -1
- package/dist/esm/readablepromise.mjs.map +1 -1
- package/dist/esm/schema.mjs +1 -1
- package/dist/esm/schema.mjs.map +1 -1
- package/dist/esm/search/details.mjs +14 -16
- package/dist/esm/search/details.mjs.map +1 -1
- package/dist/esm/search/match.mjs +7 -5
- package/dist/esm/search/match.mjs.map +1 -1
- package/dist/esm/search/search.mjs +14 -5
- package/dist/esm/search/search.mjs.map +1 -1
- package/dist/esm/types.mjs +1 -1
- package/dist/esm/types.mjs.map +1 -1
- package/dist/esm/typeschema/types.mjs +278 -0
- package/dist/esm/typeschema/types.mjs.map +1 -0
- package/dist/esm/typeschema/validation.mjs +262 -0
- package/dist/esm/typeschema/validation.mjs.map +1 -0
- package/dist/esm/utils.mjs +3 -3
- package/dist/esm/utils.mjs.map +1 -1
- package/dist/types/access.d.ts +48 -0
- package/dist/types/client.d.ts +15 -20
- package/dist/types/fhirlexer/parse.d.ts +5 -4
- package/dist/types/fhirpath/functions.d.ts +1 -3
- package/dist/types/index.d.ts +3 -0
- package/dist/types/outcomes.d.ts +3 -1
- package/dist/types/search/search.d.ts +7 -0
- package/dist/types/typeschema/types.d.ts +5 -2
- package/dist/types/typeschema/validation.d.ts +2 -0
- package/package.json +1 -1
package/dist/cjs/index.min.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).medplum=e.medplum||{},e.medplum.core={}))}(this,(function(e){"use strict";function t(e){if("undefined"!=typeof window)return window.atob(e);if("undefined"!=typeof Buffer)return Buffer.from(e,"base64").toString("binary");throw new Error("Unable to decode base64")}function r(e){if("undefined"!=typeof window)return window.btoa(e);if("undefined"!=typeof Buffer)return Buffer.from(e,"binary").toString("base64");throw new Error("Unable to encode base64")}function n(e,t){return"reference"===e&&"string"==typeof t&&t.includes("/")?"urn:uuid:"+t.split("/")[1]:t}class i{constructor(e=10){this.max=e,this.cache=new Map}clear(){this.cache.clear()}get(e){const t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){this.cache.has(e)?this.cache.delete(e):this.cache.size>=this.max&&this.cache.delete(this.first()),this.cache.set(e,t)}delete(e){this.cache.delete(e)}keys(){return this.cache.keys()}first(){return this.cache.keys().next().value}}function o(e,t){const r=[];return e.prefix&&!1!==t?.prefix&&r.push(...e.prefix),e.given&&r.push(...e.given),e.family&&r.push(e.family),e.suffix&&!1!==t?.suffix&&r.push(...e.suffix),e.use&&(t?.all||t?.use)&&r.push("["+e.use+"]"),r.join(" ").trim()}function s(e){return e instanceof Date&&!isNaN(e.getTime())}function a(e,t,r){if(!e)return"";const n=new Date("2000-01-01T"+e+"Z");return s(n)?n.toLocaleTimeString(t,r):""}function c(e,t,r){if(!e)return"";const n=new Date(e);return s(n)?n.toLocaleString(t,r):""}const u={s:"every second",min:"every minute",h:"hourly",d:"daily",wk:"weekly",mo:"monthly",a:"annually"},p={s:"second",min:"minute",h:"hour",d:"day",wk:"week",mo:"month",a:"year"},d={s:"seconds",min:"minutes",h:"hours",d:"days",wk:"weeks",mo:"months",a:"years"};function l(e,t){if(!e)return"";const r=[];return e.comparator&&(r.push(e.comparator),r.push(" ")),void 0!==e.value&&(void 0!==t?r.push(e.value.toFixed(t)):r.push(e.value)),e.unit&&("%"!==e.unit&&" "!==r[r.length-1]&&r.push(" "),r.push(e.unit)),r.join("").trim()}function h(e){return e?e.text?e.text:e.coding?e.coding.map((e=>f(e))).join(", "):"":""}function f(e){return e?.display||e?.code||""}function y(e,t){return void 0===t?e:Math.round(e*Math.pow(10,t))}function m(e){const t=g(e),r=x(e);return r===t?{reference:t}:{reference:t,display:r}}function g(e){return e.resourceType+"/"+e.id}function v(e){return"Patient"===e.resourceType||"Practitioner"===e.resourceType||"RelatedPerson"===e.resourceType}function x(e){if(v(e)){const t=function(e){const t=e.name;if(t&&t.length>0)return o(t[0]);return}(e);if(t)return t}if("Device"===e.resourceType){const t=function(e){const t=e.deviceName;if(t&&t.length>0)return t[0].name;return}(e);if(t)return t}return"Observation"===e.resourceType&&"code"in e&&e.code?.text?e.code.text:"User"===e.resourceType&&e.email?e.email:"name"in e&&e.name&&"string"==typeof e.name?e.name:g(e)}function T(e){if(e.url&&e.contentType&&e.contentType.startsWith("image/"))return e.url}function S(e,t){const r=new Date(e);r.setUTCHours(0,0,0,0);const n=t?new Date(t):new Date;n.setUTCHours(0,0,0,0);const i=r.getUTCFullYear(),o=r.getUTCMonth(),s=r.getUTCDate(),a=n.getUTCFullYear(),c=n.getUTCMonth(),u=n.getUTCDate();let p=a-i;(c<o||c===o&&u<s)&&p--;let d=12*a+c-(12*i+o);u<s&&d--;return{years:p,months:d,days:Math.floor((n.getTime()-r.getTime())/864e5)}}function b(e,t){if(e)for(const r of e)r.linkId&&r.answer&&r.answer.length>0&&(t[r.linkId]=r.answer[0]),b(r.item,t)}function w(e,...t){let r=e;for(let e=0;e<t.length&&r;e++)r=r?.extension?.find((r=>r.url===t[e]));return r?.valueString}function E(e,t){return JSON.stringify(e,P,t?2:void 0)}function P(e,t){return!function(e){return!!e.match(/\d+$/)}(e)&&A(t)?void 0:t}function A(e){if(null==e)return!0;const t=typeof e;return"string"===t&&""===e||"object"===t&&0===Object.keys(e).length}function k(e,t,r){return e===t||(!(!A(e)||!A(t))||!A(e)&&!A(t)&&(Array.isArray(e)&&Array.isArray(t)?function(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!k(e[r],t[r]))return!1;return!0}(e,t):!Array.isArray(e)&&!Array.isArray(t)&&(C(e)&&C(t)?function(e,t,r){const n=new Set;Object.keys(e).forEach((e=>n.add(e))),Object.keys(t).forEach((e=>n.add(e))),"meta"===r&&(n.delete("versionId"),n.delete("lastUpdated"),n.delete("author"));for(const r of n){if(!k(e[r],t[r],r))return!1}return!0}(e,t,r):(C(e)||C(t),!1))))}function C(e){return null!==e&&"object"==typeof e}function R(e){return e.every((e=>"string"==typeof e))}const D=[];for(let e=0;e<256;e++)D.push(e.toString(16).padStart(2,"0"));function O(e){const t=new Uint8Array(e),r=new Array(t.length);for(let e=0;e<t.length;e++)r[e]=D[t[e]];return r.join("")}function I(e){const t=new Uint8Array(e),r=[];for(let e=0;e<t.length;e++)r[e]=String.fromCharCode(t[e]);return window.btoa(r.join(""))}function U(e){return e.charAt(0).toUpperCase()+e.substring(1)}function L(e){return e===e.toLowerCase()&&e!==e.toUpperCase()}function N(e,t){return e?.coding?.find((e=>e.system===t))?.code}function M(e,t){return function(e,t){return!e.gender||e.gender===t.gender}(e,t)&&function(e,t){return!e.age||_(S(t.birthDate).years,e.age)}(e,t)}function _(e,t,r){return(void 0===t.low?.value||j(e,t.low.value,r))&&(void 0===t.high?.value||B(e,t.high.value,r))}function B(e,t,r){return q(e,r)<=q(t,r)}function j(e,t,r){return q(e,r)>=q(t,r)}function q(e,t){return void 0===t?e:Math.round(e*Math.pow(10,t))}function $(){const e=new Uint32Array(28);return crypto.getRandomValues(e),O(e.buffer)}class Q{constructor(){this.listeners={}}addEventListener(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)}removeEventListeneer(e,t){const r=this.listeners[e];if(r)for(let e=0;e<r.length;e++)if(r[e]===t)return void r.splice(e,1)}dispatchEvent(e){const t=this.listeners[e.type];return t&&t.forEach((t=>t.call(this,e))),!e.defaultPrevented}}function F(e){const[r,n,i]=e.split(".");return function(e){const r=t(e.replace(/-/g,"+").replace(/_/g,"/")),n=Array.from(r).reduce(((e,t)=>`${e}%${("00"+t.charCodeAt(0).toString(16)).slice(-2)}`),""),i=decodeURIComponent(n);return JSON.parse(i)}(n)}const H="ok",W="created",z="gone",G="not-modified",V="not-found",J="unauthorized",X="forbidden",Y="too-many-requests",K={resourceType:"OperationOutcome",id:H,issue:[{severity:"information",code:"informational",details:{text:"All OK"}}]},Z={resourceType:"OperationOutcome",id:W,issue:[{severity:"information",code:"informational",details:{text:"Created"}}]},ee={resourceType:"OperationOutcome",id:G,issue:[{severity:"information",code:"informational",details:{text:"Not Modified"}}]},te={resourceType:"OperationOutcome",id:V,issue:[{severity:"error",code:"not-found",details:{text:"Not found"}}]},re={resourceType:"OperationOutcome",id:J,issue:[{severity:"error",code:"login",details:{text:"Unauthorized"}}]},ne={resourceType:"OperationOutcome",id:X,issue:[{severity:"error",code:"forbidden",details:{text:"Forbidden"}}]},ie={resourceType:"OperationOutcome",id:z,issue:[{severity:"error",code:"deleted",details:{text:"Gone"}}]},oe={resourceType:"OperationOutcome",id:Y,issue:[{severity:"error",code:"throttled",details:{text:"Too Many Requests"}}]},se={resourceType:"OperationOutcome",id:"accepted",issue:[{severity:"information",code:"informational",details:{text:"Accepted"}}]};function ae(e,t){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"invalid",details:{text:e},expression:t?[t]:void 0}]}}function ce(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"structure",details:{text:e}}]}}function ue(e){return"object"==typeof e&&null!==e&&"OperationOutcome"===e.resourceType}function pe(e){return e.id===H||e.id===W||e.id===G}class de extends Error{constructor(e,t){super(fe(e)),this.outcome=e,this.cause=t}}function le(e){return e instanceof de?e.outcome:ue(e)?e:ae(he(e))}function he(e){return e?"string"==typeof e?e:e instanceof Error?e.message:ue(e)?fe(e):JSON.stringify(e):"Unknown error"}function fe(e){const t=e.issue?.map(ye)??[];return t.length>0?t.join("; "):"Unknown error"}function ye(e){let t=e.details?.text??e.diagnostics??"Unknown error";return e.expression?.length&&(t+=` (${e.expression.join(", ")})`),t}var me;class ge{constructor(e){this[me]="ReadablePromise",this.status="pending",this.suspender=e.then((e=>(this.status="success",this.response=e,e)),(e=>{throw this.status="error",this.error=e,e}))}isPending(){return"pending"===this.status}isOk(){return"success"===this.status}read(){switch(this.status){case"pending":throw this.suspender;case"error":throw this.error;default:return this.response}}then(e,t){return this.suspender.then(e,t)}catch(e){return this.suspender.catch(e)}finally(e){return this.suspender.finally(e)}}me=Symbol.toStringTag;class ve{constructor(){this.storage="undefined"!=typeof localStorage?localStorage:new xe}clear(){this.storage.clear()}getString(e){return this.storage.getItem(e)||void 0}setString(e,t){t?this.storage.setItem(e,t):this.storage.removeItem(e)}getObject(e){const t=this.getString(e);return t?JSON.parse(t):void 0}setObject(e,t){this.setString(e,t?E(t):void 0)}}class xe{constructor(){this.data=new Map}get length(){return this.data.size}clear(){this.data.clear()}getItem(e){return this.data.get(e)??null}setItem(e,t){t?this.data.set(e,t):this.data.delete(e)}removeItem(e){this.data.delete(e)}key(e){return Array.from(this.data.keys())[e]}}var Te,Se={types:{Element:{display:"Element",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]}}},BackboneElement:{display:"BackboneElement",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]}}},Address:{display:"Address",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},use:{type:[{code:"code"}]},type:{type:[{code:"code"}]},text:{type:[{code:"string"}]},line:{max:"*",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:{display:"Age",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Annotation:{display:"Annotation",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Attachment",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"CodeableConcept",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},coding:{max:"*",type:[{code:"Coding"}]},text:{type:[{code:"string"}]}}},Coding:{display:"Coding",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},system:{type:[{code:"uri"}]},version:{type:[{code:"string"}]},code:{type:[{code:"code"}]},display:{type:[{code:"string"}]},userSelected:{type:[{code:"boolean"}]}}},ContactDetail:{display:"ContactDetail",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},name:{type:[{code:"string"}]},telecom:{max:"*",type:[{code:"ContactPoint"}]}}},ContactPoint:{display:"ContactPoint",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},system:{type:[{code:"code"}]},value:{type:[{code:"string"}]},use:{type:[{code:"code"}]},rank:{type:[{code:"positiveInt"}]},period:{type:[{code:"Period"}]}}},Contributor:{display:"Contributor",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},name:{min:1,type:[{code:"string"}]},contact:{max:"*",type:[{code:"ContactDetail"}]}}},Count:{display:"Count",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},DataRequirement:{display:"DataRequirement",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},profile:{max:"*",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:"*",type:[{code:"string"}]},codeFilter:{max:"*",type:[{code:"Element"}]},dateFilter:{max:"*",type:[{code:"Element"}]},limit:{type:[{code:"positiveInt"}]},sort:{max:"*",type:[{code:"Element"}]}}},DataRequirementCodeFilter:{display:"DataRequirementCodeFilter",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},valueSet:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/ValueSet"]}]},code:{max:"*",type:[{code:"Coding"}]}}},DataRequirementDateFilter:{display:"DataRequirementDateFilter",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},"value[x]":{type:[{code:"dateTime"},{code:"Period"},{code:"Duration"}]}}},DataRequirementSort:{display:"DataRequirementSort",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},direction:{min:1,type:[{code:"code"}]}}},Distance:{display:"Distance",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Dosage:{display:"Dosage",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},sequence:{type:[{code:"integer"}]},text:{type:[{code:"string"}]},additionalInstruction:{max:"*",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:"*",type:[{code:"Element"}]},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:{display:"DosageDoseAndRate",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Duration",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},ElementDefinition:{display:"ElementDefinition",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},representation:{max:"*",type:[{code:"code"}]},sliceName:{type:[{code:"string"}]},sliceIsConstraining:{type:[{code:"boolean"}]},label:{type:[{code:"string"}]},code:{max:"*",type:[{code:"Coding"}]},slicing:{type:[{code:"Element"}]},short:{type:[{code:"string"}]},definition:{type:[{code:"markdown"}]},comment:{type:[{code:"markdown"}]},requirements:{type:[{code:"markdown"}]},alias:{max:"*",type:[{code:"string"}]},min:{type:[{code:"unsignedInt"}]},max:{type:[{code:"string"}]},base:{type:[{code:"Element"}]},contentReference:{type:[{code:"uri"}]},type:{max:"*",type:[{code:"Element"}]},"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:"*",type:[{code:"Element"}]},"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:"*",type:[{code:"id"}]},constraint:{max:"*",type:[{code:"Element"}]},mustSupport:{type:[{code:"boolean"}]},isModifier:{type:[{code:"boolean"}]},isModifierReason:{type:[{code:"string"}]},isSummary:{type:[{code:"boolean"}]},binding:{type:[{code:"Element"}]},mapping:{max:"*",type:[{code:"Element"}]}}},ElementDefinitionSlicing:{display:"ElementDefinitionSlicing",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},discriminator:{max:"*",type:[{code:"Element"}]},description:{type:[{code:"string"}]},ordered:{type:[{code:"boolean"}]},rules:{min:1,type:[{code:"code"}]}}},ElementDefinitionSlicingDiscriminator:{display:"ElementDefinitionSlicingDiscriminator",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},path:{min:1,type:[{code:"string"}]}}},ElementDefinitionBase:{display:"ElementDefinitionBase",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},min:{min:1,type:[{code:"unsignedInt"}]},max:{min:1,type:[{code:"string"}]}}},ElementDefinitionType:{display:"ElementDefinitionType",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},code:{min:1,type:[{code:"uri"}]},profile:{max:"*",type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},targetProfile:{max:"*",type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},aggregation:{max:"*",type:[{code:"code"}]},versioning:{type:[{code:"code"}]}}},ElementDefinitionExample:{display:"ElementDefinitionExample",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"ElementDefinitionConstraint",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"ElementDefinitionBinding",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"ElementDefinitionMapping",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},identity:{min:1,type:[{code:"id"}]},language:{type:[{code:"code"}]},map:{min:1,type:[{code:"string"}]},comment:{type:[{code:"string"}]}}},Expression:{display:"Expression",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Extension",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},url:{min:1,type:[{code:"string"}]},"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:{display:"HumanName",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},use:{type:[{code:"code"}]},text:{type:[{code:"string"}]},family:{type:[{code:"string"}]},given:{max:"*",type:[{code:"string"}]},prefix:{max:"*",type:[{code:"string"}]},suffix:{max:"*",type:[{code:"string"}]},period:{type:[{code:"Period"}]}}},Identifier:{display:"Identifier",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"MarketingStatus",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",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:{display:"Meta",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},versionId:{type:[{code:"id"}]},lastUpdated:{type:[{code:"instant"}]},source:{type:[{code:"uri"}]},profile:{max:"*",type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]},security:{max:"*",type:[{code:"Coding"}]},tag:{max:"*",type:[{code:"Coding"}]},project:{type:[{code:"uri"}]},author:{type:[{code:"Reference"}]},account:{type:[{code:"Reference"}]},compartment:{max:"*",type:[{code:"Reference"}]}}},Money:{display:"Money",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},currency:{type:[{code:"code"}]}}},Narrative:{display:"Narrative",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},status:{min:1,type:[{code:"code"}]},div:{min:1,type:[{code:"xhtml"}]}}},ParameterDefinition:{display:"ParameterDefinition",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Period",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},start:{type:[{code:"dateTime"}]},end:{type:[{code:"dateTime"}]}}},Population:{display:"Population",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},"age[x]":{type:[{code:"Range"},{code:"CodeableConcept"}]},gender:{type:[{code:"CodeableConcept"}]},race:{type:[{code:"CodeableConcept"}]},physiologicalCondition:{type:[{code:"CodeableConcept"}]}}},ProdCharacteristic:{display:"ProdCharacteristic",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",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:"*",type:[{code:"string"}]},imprint:{max:"*",type:[{code:"string"}]},image:{max:"*",type:[{code:"Attachment"}]},scoring:{type:[{code:"CodeableConcept"}]}}},ProductShelfLife:{display:"ProductShelfLife",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},identifier:{type:[{code:"Identifier"}]},type:{min:1,type:[{code:"CodeableConcept"}]},period:{min:1,type:[{code:"Quantity"}]},specialPrecautionsForStorage:{max:"*",type:[{code:"CodeableConcept"}]}}},Quantity:{display:"Quantity",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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"}]}}},Range:{display:"Range",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Ratio",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},numerator:{type:[{code:"Quantity"}]},denominator:{type:[{code:"Quantity"}]}}},Reference:{display:"Reference",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},reference:{type:[{code:"string"}]},type:{type:[{code:"uri"}]},identifier:{type:[{code:"Identifier"}]},display:{type:[{code:"string"}]}}},RelatedArtifact:{display:"RelatedArtifact",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"SampledData",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Signature",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},type:{min:1,max:"*",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:{display:"SubstanceAmount",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},"amount[x]":{type:[{code:"Quantity"},{code:"Range"},{code:"string"}]},amountType:{type:[{code:"CodeableConcept"}]},amountText:{type:[{code:"string"}]},referenceRange:{type:[{code:"Element"}]}}},SubstanceAmountReferenceRange:{display:"SubstanceAmountReferenceRange",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},lowLimit:{type:[{code:"Quantity"}]},highLimit:{type:[{code:"Quantity"}]}}},Timing:{display:"Timing",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},event:{max:"*",type:[{code:"dateTime"}]},repeat:{type:[{code:"Element"}]},code:{type:[{code:"CodeableConcept"}]}}},TimingRepeat:{display:"TimingRepeat",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:"*",type:[{code:"code"}]},timeOfDay:{max:"*",type:[{code:"time"}]},when:{max:"*",type:[{code:"code"}]},offset:{type:[{code:"unsignedInt"}]}}},TriggerDefinition:{display:"TriggerDefinition",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:"*",type:[{code:"DataRequirement"}]},condition:{type:[{code:"Expression"}]}}},UsageContext:{display:"UsageContext",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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"]}]}}},MetadataResource:{display:"MetadataResource",properties:{id:{type:[{code:"string"}]},meta:{type:[{code:"Meta"}]},implicitRules:{type:[{code:"uri"}]},language:{type:[{code:"code"}]},text:{type:[{code:"Narrative"}]},contained:{max:"*",type:[{code:"Resource"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},url:{type:[{code:"uri"}]},version:{type:[{code:"string"}]},name:{type:[{code:"string"}]},title:{type:[{code:"string"}]},status:{min:1,type:[{code:"code"}]},experimental:{type:[{code:"boolean"}]},date:{type:[{code:"dateTime"}]},publisher:{type:[{code:"string"}]},contact:{max:"*",type:[{code:"ContactDetail"}]},description:{type:[{code:"markdown"}]},useContext:{max:"*",type:[{code:"UsageContext"}]},jurisdiction:{max:"*",type:[{code:"CodeableConcept"}]}}},IdentityProvider:{display:"IdentityProvider",properties:{authorizeUrl:{min:1,type:[{code:"string"}]},tokenUrl:{min:1,type:[{code:"string"}]},userInfoUrl:{min:1,type:[{code:"string"}]},clientId:{min:1,type:[{code:"string"}]},clientSecret:{min:1,type:[{code:"string"}]},useSubject:{type:[{code:"boolean"}]}}}}};function be(e){if(!e.name)return;const t=e.snapshot?.element;t&&(t.forEach((t=>function(e,t){const r=t.path,n=t.type?.[0]?.code;if(void 0!==n&&"Element"!==n&&"BackboneElement"!==n)return;const i=r.split(".");i[0]=e.name;const o=Ee(i);let s=De.types[o];s||(De.types[o]=s={});s.parentType=s.parentType||Ee(i.slice(0,i.length-1)),s.display=s.display||o,s.structureDefinition=s.structureDefinition||e,s.elementDefinition=s.elementDefinition||t,s.description=s.description||t.definition,s.properties=s.properties||{}}(e,t))),t.forEach((t=>function(e,t){const r=t.path,n=r.split(".");if(1===n.length)return;n[0]=e.name;const i=Ee(n.slice(0,n.length-1)),o=De.types[i];if(!o)return;const s=n[n.length-1];o.properties[s]=t}(e,t))))}function we(e){if(e.base)for(const t of e.base){const r=De.types[t];r&&(r.searchParams||(r.searchParams={_id:{base:[t],code:"_id",type:"token",expression:t+".id"},_lastUpdated:{base:[t],code:"_lastUpdated",type:"date",expression:t+".meta.lastUpdated"},_compartment:{base:[t],code:"_compartment",type:"reference",expression:t+".meta.compartment"},_profile:{base:[t],code:"_profile",type:"uri",expression:t+".meta.profile"},_security:{base:[t],code:"_security",type:"token",expression:t+".meta.security"},_source:{base:[t],code:"_source",type:"uri",expression:t+".meta.source"},_tag:{base:[t],code:"_tag",type:"token",expression:t+".meta.tag"}}),r.searchParams[e.code]=e)}}function Ee(e){return 1===e.length?e[0]:e.map(U).join("")}function Pe(e){const t=e.structureDefinition;return t&&t.name===e.elementDefinition?.path&&"resource"===t.kind&&!t.abstract}e.PropertyType=void 0,(Te=e.PropertyType||(e.PropertyType={})).Address="Address",Te.Age="Age",Te.Annotation="Annotation",Te.Attachment="Attachment",Te.BackboneElement="BackboneElement",Te.CodeableConcept="CodeableConcept",Te.Coding="Coding",Te.ContactDetail="ContactDetail",Te.ContactPoint="ContactPoint",Te.Contributor="Contributor",Te.Count="Count",Te.DataRequirement="DataRequirement",Te.Distance="Distance",Te.Dosage="Dosage",Te.Duration="Duration",Te.Expression="Expression",Te.Extension="Extension",Te.HumanName="HumanName",Te.Identifier="Identifier",Te.MarketingStatus="MarketingStatus",Te.Meta="Meta",Te.Money="Money",Te.Narrative="Narrative",Te.ParameterDefinition="ParameterDefinition",Te.Period="Period",Te.Population="Population",Te.ProdCharacteristic="ProdCharacteristic",Te.ProductShelfLife="ProductShelfLife",Te.Quantity="Quantity",Te.Range="Range",Te.Ratio="Ratio",Te.Reference="Reference",Te.RelatedArtifact="RelatedArtifact",Te.SampledData="SampledData",Te.Signature="Signature",Te.SubstanceAmount="SubstanceAmount",Te.SystemString="http://hl7.org/fhirpath/System.String",Te.Timing="Timing",Te.TriggerDefinition="TriggerDefinition",Te.UsageContext="UsageContext",Te.base64Binary="base64Binary",Te.boolean="boolean",Te.canonical="canonical",Te.code="code",Te.date="date",Te.dateTime="dateTime",Te.decimal="decimal",Te.id="id",Te.instant="instant",Te.integer="integer",Te.markdown="markdown",Te.oid="oid",Te.positiveInt="positiveInt",Te.string="string",Te.time="time",Te.unsignedInt="unsignedInt",Te.uri="uri",Te.url="url",Te.uuid="uuid";const Ae=new Set(["ID","IP","PKCE","JWKS","URI","URL"]);function ke(e){const t=e.toUpperCase();return Ae.has(t)?t:t.charAt(0)+e.slice(1)}function Ce(e,t){const r=De.types[e];if(!r)return;const n=r.properties[t]??r.properties[t+"[x]"];if(n){if(n.contentReference){const e=n.contentReference.substring(1).split("."),t=e.pop();return Ce(Ee(e),t)}return n}}function Re(e){return!(!e||"object"!=typeof e||!("resourceType"in e))}const De=Se,Oe="application/fhir+json",Ie={resourceType:"Device",id:"system",deviceName:[{name:"System"}]};var Ue,Le;e.OAuthGrantType=void 0,(Ue=e.OAuthGrantType||(e.OAuthGrantType={})).ClientCredentials="client_credentials",Ue.AuthorizationCode="authorization_code",Ue.RefreshToken="refresh_token",Ue.TokenExchange="urn:ietf:params:oauth:grant-type:token-exchange",e.OAuthTokenType=void 0,(Le=e.OAuthTokenType||(e.OAuthTokenType={})).AccessToken="urn:ietf:params:oauth:token-type:access_token",Le.RefreshToken="urn:ietf:params:oauth:token-type:refresh_token",Le.IdToken="urn:ietf:params:oauth:token-type:id_token",Le.Saml1Token="urn:ietf:params:oauth:token-type:saml1",Le.Saml2Token="urn:ietf:params:oauth:token-type:saml2";function Ne(){return"undefined"==typeof window?"":window.location.protocol+"//"+window.location.host+"/"}function Me(e){return e?e.endsWith("/")?e:e+"/":e}class _e{constructor(e,t){this.operator=e,this.child=t}toString(){return`${this.operator}(${this.child.toString()})`}}class Be{constructor(e,t,r){this.operator=e,this.left=t,this.right=r}toString(){return`${this.left.toString()} ${this.operator} ${this.right.toString()}`}}class je{constructor(){this.prefixParselets={},this.infixParselets={}}registerInfix(e,t){return this.infixParselets[e]=t,this}registerPrefix(e,t){return this.prefixParselets[e]=t,this}prefix(e,t,r){return this.registerPrefix(e,{parse(e,n){const i=e.consumeAndParse(t);return r(n,i)}})}infixLeft(e,t,r){return this.registerInfix(e,{parse(e,n,i){const o=e.consumeAndParse(t);return r(n,i,o)},precedence:t})}construct(e){return new qe(e,this.prefixParselets,this.infixParselets)}}class qe{constructor(e,t,r){this.tokens=e,this.prefixParselets=t,this.infixParselets=r}hasMore(){return this.tokens.length>0}match(e){const t=this.peek();return t?.id===e&&(this.consume(),!0)}consumeAndParse(e=1/0){const t=this.consume(),r=this.prefixParselets[t.id];if(!r)throw Error(`Parse error at "${t.value}" (line ${t.line}, column ${t.column}). No matching prefix parselet.`);let n=r.parse(this,t);for(;e>this.getPrecedence();){const e=this.consume();n=this.getInfixParselet(e).parse(this,n,e)}return n}getPrecedence(){const e=this.peek();if(!e)return 1/0;const t=this.getInfixParselet(e);return t?t.precedence:1/0}consume(e,t){if(!this.tokens.length)throw Error("Cant consume unknown more tokens.");if(e&&this.peek()?.id!==e){const t=this.peek();throw Error(`Expected ${e} but got "${t.id}" at line ${t.line} column ${t.column}.`)}if(t&&this.peek()?.value!==t){const e=this.peek();throw Error(`Expected "${t}" but got "${e.value}" at line ${e.line} column ${e.column}.`)}return this.tokens.shift()}peek(){return this.tokens.length>0?this.tokens[0]:void 0}removeComments(){this.tokens=this.tokens.filter((e=>"Comment"!==e.id))}getInfixParselet(e){return this.infixParselets["Symbol"===e.id?e.value:e.id]}}const $e=["year","years","month","months","week","weeks","day","days","hour","hours","minute","minutes","second","seconds","millisecond","milliseconds"];class Qe{constructor(e,t,r,n){this.result=[],this.pos={index:0,line:1,column:0},this.markStack=[],this.str=e,this.keywords=t,this.operators=r,this.dateTimeLiterals=!!n?.dateTimeLiterals,this.symbolRegex=n?.symbolRegex??/[$\w%]/}tokenize(){for(;this.pos.index<this.str.length;){const e=this.consumeToken();e&&this.result.push(e)}return this.result}prevToken(){return this.result.slice(-1)[0]}peekToken(){this.mark();const e=this.consumeToken();return this.reset(),e}consumeToken(){this.consumeWhitespace();const e=this.curr();if(!e)return;this.mark();const t=this.peek();return"/"===e&&"*"===t?this.consumeMultiLineComment():"/"===e&&"/"===t?this.consumeSingleLineComment():"'"===e||'"'===e?this.consumeString(e):"`"===e?this.consumeBacktickSymbol():"@"===e?this.consumeDateTime():e.match(/\d/)?this.consumeNumber():e.match(/\w/)?this.consumeSymbol():"$"!==e&&"%"!==e||!t.match(/\w/)?this.consumeOperator():this.consumeSymbol()}consumeWhitespace(){this.consumeWhile((()=>this.curr().match(/\s/)))}consumeMultiLineComment(){const e=this.pos.index;return this.consumeWhile((()=>"*"!==this.curr()||"/"!==this.peek())),this.advance(),this.advance(),this.buildToken("Comment",this.str.substring(e,this.pos.index))}consumeSingleLineComment(){return this.buildToken("Comment",this.consumeWhile((()=>"\n"!==this.curr())))}consumeString(e){this.advance();const t=this.buildToken("String",this.consumeWhile((()=>"\\"===this.prev()||this.curr()!==e)));return this.advance(),t}consumeBacktickSymbol(){this.advance();const e=this.buildToken("Symbol",this.consumeWhile((()=>"`"!==this.curr())));return this.advance(),e}consumeDateTime(){this.advance();const e=this.pos.index;return this.consumeWhile((()=>this.curr().match(/[\d-]/))),"T"===this.curr()&&(this.advance(),this.consumeWhile((()=>this.curr().match(/[\d:]/))),"."===this.curr()&&this.peek().match(/\d/)&&(this.advance(),this.consumeWhile((()=>this.curr().match(/\d/)))),"Z"===this.curr()?this.advance():"+"!==this.curr()&&"-"!==this.curr()||(this.advance(),this.consumeWhile((()=>this.curr().match(/[\d:]/))))),this.buildToken("DateTime",this.str.substring(e,this.pos.index))}consumeNumber(){const e=this.pos.index;let t="Number";return this.consumeWhile((()=>this.curr().match(/\d/))),"."===this.curr()&&this.peek().match(/\d/)&&(this.advance(),this.consumeWhile((()=>this.curr().match(/\d/)))),"-"===this.curr()&&this.dateTimeLiterals?(this.pos.index=e-1,this.consumeDateTime()):(" "===this.curr()&&function(e){if(e){if("String"===e.id)return!0;if("Symbol"===e.id&&$e.includes(e.value))return!0}return!1}(this.peekToken())&&(t="Quantity",this.consumeToken()),this.buildToken(t,this.str.substring(e,this.pos.index)))}consumeSymbol(){const e=this.consumeWhile((()=>this.curr().match(this.symbolRegex)));return"."!==this.prevToken()?.value&&this.keywords.includes(e)?this.buildToken(e,e):this.buildToken("Symbol",e)}consumeOperator(){const e=this.curr(),t=e+this.peek();return this.operators.includes(t)?(this.advance(),this.advance(),this.buildToken(t,t)):(this.advance(),this.buildToken(e,e))}consumeWhile(e){const t=this.pos.index;for(;this.pos.index<this.str.length&&e();)this.advance();return this.str.substring(t,this.pos.index)}curr(){return this.str[this.pos.index]}prev(){return this.str[this.pos.index-1]??""}peek(){return this.str[this.pos.index+1]??""}mark(){this.markStack.push({...this.pos})}reset(){const e=this.markStack.pop();if(!e)throw new Error("No mark to reset to");this.pos.index=e.index,this.pos.line=e.line,this.pos.column=e.column}advance(){this.pos.index++,"\n"===this.curr()?(this.pos.line++,this.pos.column=0):this.pos.column++}buildToken(e,t){const r=this.markStack.pop();if(!r)throw new Error("No mark for token");return{id:e,value:t,...r}}}function Fe(e){if(e.startsWith("T"))return e+"T00:00:00.000Z".substring(e.length);if(e.length<=10)return e;try{return new Date(e).toISOString()}catch(t){return e}}function He(t){return[{type:e.PropertyType.boolean,value:t}]}function We(t){return null==t?{type:"undefined",value:void 0}:Number.isSafeInteger(t)?{type:e.PropertyType.integer,value:t}:"number"==typeof t?{type:e.PropertyType.decimal,value:t}:"boolean"==typeof t?{type:e.PropertyType.boolean,value:t}:"string"==typeof t?{type:e.PropertyType.string,value:t}:it(t)?{type:e.PropertyType.Quantity,value:t}:Re(t)?{type:t.resourceType,value:t}:{type:e.PropertyType.BackboneElement,value:t}}function ze(e){return 0!==e.length&&!!e[0].value}function Ge(t,r){if(!t?.value)return;const n=Ce(t.type,r);if(n){const e=function(e,t,r){const n=r.type;if(!n||0===n.length)return;let i,o="undefined";if(1===n.length)i=e.value[t],o=n[0].code;else for(const r of n){const n=t.replace("[x]","")+U(r.code);if(n in e.value){i=e.value[n],o=r.code;break}}if(A(i))return;"Element"!==o&&"BackboneElement"!==o||(o=Ee(r.path?.split(".")));return Array.isArray(i)?i.map((e=>Ve(e,o))):Ve(i,o)}(t,r,n);if(e)return e}return function(t,r){const n=t.value;if(!n||"object"!=typeof n)return;let i;if(r in n)i=n[r];else for(const t in e.PropertyType){const e=r+U(t);if(e in n){i=n[e];break}}if(A(i))return;return Array.isArray(i)?i.map(We):We(i)}(t,r)}function Ve(e,t){return"Resource"===t&&Re(e)&&(t=e.resourceType),{type:t,value:e}}function Je(e){const t=[];for(const r of e){let e=!1;for(const n of t)if(ze(Ke(r,n))){e=!0;break}e||t.push(r)}return t}function Xe(e){return He(!ze(e))}function Ye(e,t){return 0===e.length||0===t.length?[]:e.length!==t.length?He(!1):He(e.every(((e,r)=>ze(Ke(e,t[r])))))}function Ke(e,t){const r=e.value,n=t.value;return"number"==typeof r&&"number"==typeof n?He(Math.abs(r-n)<1e-8):it(r)&&it(n)?He(ot(r,n)):He("object"==typeof r&&"object"==typeof n?st(e,t):r===n)}function Ze(e,t){return 0===e.length&&0===t.length?He(!0):e.length!==t.length?He(!1):(e.sort(tt),t.sort(tt),He(e.every(((e,r)=>ze(et(e,t[r]))))))}function et(e,t){const r=e.value,n=t.value;return"number"==typeof r&&"number"==typeof n?He(Math.abs(r-n)<.01):it(r)&&it(n)?He(ot(r,n)):He("object"==typeof r&&"object"==typeof n?st(r,n):"string"==typeof r&&"string"==typeof n?r.toLowerCase()===n.toLowerCase():r===n)}function tt(e,t){const r=e.value,n=t.value;return"number"==typeof r&&"number"==typeof n?r-n:"string"==typeof r&&"string"==typeof n?r.localeCompare(n):0}function rt(e,t){const{value:r}=e;if(null==r)return!1;switch(t){case"Boolean":return"boolean"==typeof r;case"Decimal":case"Integer":return"number"==typeof r;case"Date":return"string"==typeof r&&!!r.match(/^\d{4}(-\d{2}(-\d{2})?)?/);case"DateTime":return"string"==typeof r&&!!r.match(/^\d{4}(-\d{2}(-\d{2})?)?T/);case"Time":return"string"==typeof r&&!!r.match(/^T\d/);case"Period":return nt(r);case"Quantity":return it(r);default:return"object"==typeof r&&r?.resourceType===t}}function nt(e){return!(!e||"object"!=typeof e||!("start"in e))}function it(e){return!(!e||"object"!=typeof e||!("value"in e)||"number"!=typeof e.value)}function ot(e,t){return Math.abs(e.value-t.value)<.01&&(e.unit===t.unit||e.code===t.code||e.unit===t.code||e.code===t.unit)}function st(e,t){const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(const n of r){const r=e[n],i=t[n];if(at(r)&&at(i)){if(!st(r,i))return!1}else if(r!==i)return!1}return!0}function at(e){return null!==e&&"object"==typeof e}const ct=()=>[],ut={empty:(e,t)=>He(0===t.length),exists:(e,t,r)=>He(r?t.filter((t=>ze(r.eval(e,[t])))).length>0:t.length>0),all:(e,t,r)=>He(t.every((t=>ze(r.eval(e,[t]))))),allTrue:(e,t)=>{for(const e of t)if(!e.value)return He(!1);return He(!0)},anyTrue:(e,t)=>{for(const e of t)if(e.value)return He(!0);return He(!1)},allFalse:(e,t)=>{for(const e of t)if(e.value)return He(!1);return He(!0)},anyFalse:(e,t)=>{for(const e of t)if(!e.value)return He(!0);return He(!1)},subsetOf:ct,supersetOf:ct,count:(t,r)=>[{type:e.PropertyType.integer,value:r.length}],distinct:(e,t)=>{const r=[];for(const e of t)r.some((t=>t.value===e.value))||r.push(e);return r},isDistinct:(e,t)=>He(t.length===ut.distinct(e,t).length),where:(e,t,r)=>t.filter((t=>ze(r.eval(e,[t])))),select:(e,t,r)=>t.map((t=>r.eval(e,[t]))).flat(),repeat:ct,ofType:(e,t,r)=>t.filter((e=>e.type===r.name)),single:(e,t)=>{if(t.length>1)throw new Error("Expected input length one for single()");return 0===t.length?[]:t.slice(0,1)},first:(e,t)=>0===t.length?[]:t.slice(0,1),last:(e,t)=>0===t.length?[]:t.slice(t.length-1,t.length),tail:(e,t)=>0===t.length?[]:t.slice(1,t.length),skip:(e,t,r)=>{const n=r.eval(e,t)[0]?.value;if("number"!=typeof n)throw new Error("Expected a number for skip(num)");return n>=t.length?[]:n<=0?t:t.slice(n,t.length)},take:(e,t,r)=>{const n=r.eval(e,t)[0]?.value;if("number"!=typeof n)throw new Error("Expected a number for take(num)");return n>=t.length?t:n<=0?[]:t.slice(0,n)},intersect:(e,t,r)=>{if(!r)return t;const n=r.eval(e,t),i=[];for(const e of t)!i.some((t=>t.value===e.value))&&n.some((t=>t.value===e.value))&&i.push(e);return i},exclude:(e,t,r)=>{if(!r)return t;const n=r.eval(e,t),i=[];for(const e of t)n.some((t=>t.value===e.value))||i.push(e);return i},union:(e,t,r)=>{if(!r)return t;const n=r.eval(e,t);return Je([...t,...n])},combine:(e,t,r)=>{if(!r)return t;const n=r.eval(e,t);return[...t,...n]},iif:(e,t,r,n,i)=>{const o=r.eval(e,t);if(o.length>1||1===o.length&&"boolean"!=typeof o[0].value)throw new Error("Expected criterion to evaluate to a Boolean");return ze(o)?n.eval(e,t):i?i.eval(e,t):[]},toBoolean:(t,r)=>{if(0===r.length)return[];const[{value:n}]=lt(r,1);if("boolean"==typeof n)return[{type:e.PropertyType.boolean,value:n}];if("number"==typeof n&&(0===n||1===n))return He(!!n);if("string"==typeof n){const e=n.toLowerCase();if(["true","t","yes","y","1","1.0"].includes(e))return He(!0);if(["false","f","no","n","0","0.0"].includes(e))return He(!1)}return[]},convertsToBoolean:(e,t)=>0===t.length?[]:He(1===ut.toBoolean(e,t).length),toInteger:(t,r)=>{if(0===r.length)return[];const[{value:n}]=lt(r,1);return"number"==typeof n?[{type:e.PropertyType.integer,value:n}]:"string"==typeof n&&n.match(/^[+-]?\d+$/)?[{type:e.PropertyType.integer,value:parseInt(n,10)}]:"boolean"==typeof n?[{type:e.PropertyType.integer,value:n?1:0}]:[]},convertsToInteger:(e,t)=>0===t.length?[]:He(1===ut.toInteger(e,t).length),toDate:(t,r)=>{if(0===r.length)return[];const[{value:n}]=lt(r,1);return"string"==typeof n&&n.match(/^\d{4}(-\d{2}(-\d{2})?)?/)?[{type:e.PropertyType.date,value:Fe(n)}]:[]},convertsToDate:(e,t)=>0===t.length?[]:He(1===ut.toDate(e,t).length),toDateTime:(t,r)=>{if(0===r.length)return[];const[{value:n}]=lt(r,1);return"string"==typeof n&&n.match(/^\d{4}(-\d{2}(-\d{2})?)?/)?[{type:e.PropertyType.dateTime,value:Fe(n)}]:[]},convertsToDateTime:(e,t)=>0===t.length?[]:He(1===ut.toDateTime(e,t).length),toDecimal:(t,r)=>{if(0===r.length)return[];const[{value:n}]=lt(r,1);return"number"==typeof n?[{type:e.PropertyType.decimal,value:n}]:"string"==typeof n&&n.match(/^-?\d{1,9}(\.\d{1,9})?$/)?[{type:e.PropertyType.decimal,value:parseFloat(n)}]:"boolean"==typeof n?[{type:e.PropertyType.decimal,value:n?1:0}]:[]},convertsToDecimal:(e,t)=>0===t.length?[]:He(1===ut.toDecimal(e,t).length),toQuantity:(t,r)=>{if(0===r.length)return[];const[{value:n}]=lt(r,1);return it(n)?[{type:e.PropertyType.Quantity,value:n}]:"number"==typeof n?[{type:e.PropertyType.Quantity,value:{value:n,unit:"1"}}]:"string"==typeof n&&n.match(/^-?\d{1,9}(\.\d{1,9})?/)?[{type:e.PropertyType.Quantity,value:{value:parseFloat(n),unit:"1"}}]:"boolean"==typeof n?[{type:e.PropertyType.Quantity,value:{value:n?1:0,unit:"1"}}]:[]},convertsToQuantity:(e,t)=>0===t.length?[]:He(1===ut.toQuantity(e,t).length),toString:(t,r)=>{if(0===r.length)return[];const[{value:n}]=lt(r,1);return null==n?[]:it(n)?[{type:e.PropertyType.string,value:`${n.value} '${n.unit}'`}]:[{type:e.PropertyType.string,value:n.toString()}]},convertsToString:(e,t)=>0===t.length?[]:He(1===ut.toString(e,t).length),toTime:(t,r)=>{if(0===r.length)return[];const[{value:n}]=lt(r,1);if("string"==typeof n){const t=n.match(/^T?(\d{2}(:\d{2}(:\d{2})?)?)/);if(t)return[{type:e.PropertyType.time,value:Fe("T"+t[1])}]}return[]},convertsToTime:(e,t)=>0===t.length?[]:He(1===ut.toTime(e,t).length),indexOf:(e,t,r)=>pt(((e,t)=>e.indexOf(t)),e,t,r),substring:(e,t,r,n)=>pt(((e,t,r)=>{const n=t,i=r?n+r:e.length;return n<0||n>=e.length?void 0:e.substring(n,i)}),e,t,r,n),startsWith:(e,t,r)=>pt(((e,t)=>e.startsWith(t)),e,t,r),endsWith:(e,t,r)=>pt(((e,t)=>e.endsWith(t)),e,t,r),contains:(e,t,r)=>pt(((e,t)=>e.includes(t)),e,t,r),upper:(e,t)=>pt((e=>e.toUpperCase()),e,t),lower:(e,t)=>pt((e=>e.toLowerCase()),e,t),replace:(e,t,r,n)=>pt(((e,t,r)=>e.replaceAll(t,r)),e,t,r,n),matches:(e,t,r)=>pt(((e,t)=>!!e.match(t)),e,t,r),replaceMatches:(e,t,r,n)=>pt(((e,t,r)=>e.replaceAll(t,r)),e,t,r,n),length:(e,t)=>pt((e=>e.length),e,t),toChars:(e,t)=>pt((e=>e?e.split(""):void 0),e,t),abs:(e,t)=>dt(Math.abs,e,t),ceiling:(e,t)=>dt(Math.ceil,e,t),exp:(e,t)=>dt(Math.exp,e,t),floor:(e,t)=>dt(Math.floor,e,t),ln:(e,t)=>dt(Math.log,e,t),log:(e,t,r)=>dt(((e,t)=>Math.log(e)/Math.log(t)),e,t,r),power:(e,t,r)=>dt(Math.pow,e,t,r),round:(e,t)=>dt(Math.round,e,t),sqrt:(e,t)=>dt(Math.sqrt,e,t),truncate:(e,t)=>dt((e=>0|e),e,t),children:ct,descendants:ct,trace:(e,t,r)=>(console.log("trace",t,r),t),now:()=>[{type:e.PropertyType.dateTime,value:(new Date).toISOString()}],timeOfDay:()=>[{type:e.PropertyType.time,value:(new Date).toISOString().substring(11)}],today:()=>[{type:e.PropertyType.date,value:(new Date).toISOString().substring(0,10)}],between:(t,r,n,i,o)=>{const s=ut.toDateTime(t,n.eval(t,r));if(0===s.length)throw new Error("Invalid start date");const a=ut.toDateTime(t,i.eval(t,r));if(0===a.length)throw new Error("Invalid end date");const c=o.eval(t,r)[0]?.value;if("years"!==c&&"months"!==c&&"days"!==c)throw new Error("Invalid units");const u=S(s[0].value,a[0].value);return[{type:e.PropertyType.Quantity,value:{value:u[c],unit:c}}]},is:(t,r,n)=>{let i="";return n instanceof yt?i=n.name:n instanceof wt&&(i=n.left.name+"."+n.right.name),i?r.map((t=>({type:e.PropertyType.boolean,value:rt(t,i)}))):[]},not:(t,r)=>ut.toBoolean(t,r).map((t=>({type:e.PropertyType.boolean,value:!t.value}))),resolve:(t,r)=>r.map((t=>{const r=t.value;let n;if("string"==typeof r)n=r;else if("object"==typeof r){const e=r;if(e.resource)return We(e.resource);e.reference?n=e.reference:e.type&&e.identifier&&(n=`${e.type}?identifier=${e.identifier.system}|${e.identifier.value}`)}if(n?.includes("?")){const[e]=n.split("?");return{type:e,value:{resourceType:e}}}if(n?.includes("/")){const[e,t]=n.split("/");return{type:e,value:{resourceType:e,id:t}}}return{type:e.PropertyType.BackboneElement,value:void 0}})).filter((e=>!!e.value)),as:(e,t)=>t,type:(t,r)=>r.map((({value:t})=>"boolean"==typeof t?{type:e.PropertyType.BackboneElement,value:{namespace:"System",name:"Boolean"}}:"number"==typeof t?{type:e.PropertyType.BackboneElement,value:{namespace:"System",name:"Integer"}}:Re(t)?{type:e.PropertyType.BackboneElement,value:{namespace:"FHIR",name:t.resourceType}}:{type:e.PropertyType.BackboneElement,value:null})),conformsTo:(t,r,n)=>{const i=n.eval(t,r)[0].value;if(!i.startsWith("http://hl7.org/fhir/StructureDefinition/"))throw new Error("Expected a StructureDefinition URL");const o=i.replace("http://hl7.org/fhir/StructureDefinition/","");return r.map((t=>({type:e.PropertyType.boolean,value:t.value?.resourceType===o})))}};function pt(e,t,r,...n){if(0===r.length)return[];const[{value:i}]=lt(r,1);if("string"!=typeof i)throw new Error("String function cannot be called with non-string");const o=e(i,...n.map((e=>e&&e.eval(t,r)?.[0]?.value)));return void 0===o?[]:Array.isArray(o)?o.map(We):[We(o)]}function dt(t,r,n,...i){if(0===n.length)return[];const[{value:o}]=lt(n,1),s=it(o),a=s?o.value:o;if("number"!=typeof a)throw new Error("Math function cannot be called with non-number");const c=t(a,...i.map((e=>e.eval(r,n)?.[0]?.value)));return[{type:s?e.PropertyType.Quantity:n[0].type,value:s?{...o,value:c}:c}]}function lt(e,t){if(e.length!==t)throw new Error(`Expected ${t} arguments`);for(const t of e)if(null==t)throw new Error("Expected non-null argument");return e}class ht{constructor(e,t){this.original=e,this.child=t}eval(e,t){try{return t.length>0?t.map((t=>this.child.eval(e,[t]))).flat():this.child.eval(e,[])}catch(e){throw new Error(`FhirPathError on "${this.original}": ${e}`)}}toString(){return this.child.toString()}}class ft{constructor(e){this.value=e}eval(){return[this.value]}toString(){const e=this.value.value;return"string"==typeof e?`'${e}'`:e.toString()}}class yt{constructor(e){this.name=e}eval(e,t){if("$this"===this.name)return t;if(this.name.startsWith("%")){const t=e.variables[this.name.slice(1)];if(!t)throw new Error(`Undefined variable ${this.name}`);return[t]}return t.flatMap((e=>this.evalValue(e))).filter((e=>void 0!==e?.value))}evalValue(e){const t=e.value;if(t&&"object"==typeof t)return Re(t)&&t.resourceType===this.name?e:Ge(e,this.name)}toString(){return this.name}}class mt{eval(){return[]}toString(){return"{}"}}class gt extends _e{constructor(e,t,r){super(e,t),this.impl=r}eval(e,t){return this.impl(this.child.eval(e,t))}toString(){return this.child.toString()}}class vt extends Be{constructor(e,t){super("as",e,t)}eval(e,t){return ut.ofType(e,this.left.eval(e,t),this.right)}}class xt extends Be{constructor(e,t,r,n){super(e,t,r),this.impl=n}eval(t,r){const n=this.left.eval(t,r);if(1!==n.length)return[];const i=this.right.eval(t,r);if(1!==i.length)return[];const o=n[0].value,s=i[0].value,a=it(o)?o.value:o,c=it(s)?s.value:s,u=this.impl(a,c);return"boolean"==typeof u?He(u):it(o)?[{type:e.PropertyType.Quantity,value:{...o,value:u}}]:[We(u)]}}class Tt extends Be{constructor(e,t){super("&",e,t)}eval(t,r){const n=[...this.left.eval(t,r),...this.right.eval(t,r)];return n.length>0&&n.every((e=>"string"==typeof e.value))?[{type:e.PropertyType.string,value:n.map((e=>e.value)).join("")}]:n}}class St extends Be{constructor(e,t){super("contains",e,t)}eval(e,t){const r=this.left.eval(e,t),n=this.right.eval(e,t);return He(r.some((e=>e.value===n[0].value)))}}class bt extends Be{constructor(e,t){super("in",e,t)}eval(e,t){const r=this.left.eval(e,t);return He(this.right.eval(e,t).some((e=>e.value===r[0].value)))}}class wt extends Be{constructor(e,t){super(".",e,t)}eval(e,t){return this.right.eval(e,this.left.eval(e,t))}toString(){return`${this.left.toString()}.${this.right.toString()}`}}class Et extends Be{constructor(e,t){super("|",e,t)}eval(e,t){return Je([...this.left.eval(e,t),...this.right.eval(e,t)])}}class Pt extends Be{constructor(e,t){super("=",e,t)}eval(e,t){return Ye(this.left.eval(e,t),this.right.eval(e,t))}}class At extends Be{constructor(e,t){super("!=",e,t)}eval(e,t){return Xe(Ye(this.left.eval(e,t),this.right.eval(e,t)))}}class kt extends Be{constructor(e,t){super("~",e,t)}eval(e,t){return Ze(this.left.eval(e,t),this.right.eval(e,t))}}class Ct extends Be{constructor(e,t){super("!~",e,t)}eval(e,t){return Xe(Ze(this.left.eval(e,t),this.right.eval(e,t)))}}class Rt extends Be{constructor(e,t){super("is",e,t)}eval(e,t){const r=this.left.eval(e,t);if(1!==r.length)return[];const n=this.right.name;return He(rt(r[0],n))}}class Dt extends Be{constructor(e,t){super("and",e,t)}eval(e,t){const r=this.left.eval(e,t),n=this.right.eval(e,t);return!0===r[0]?.value&&!0===n[0]?.value?He(!0):!1===r[0]?.value||!1===n[0]?.value?He(!1):[]}}class Ot extends Be{constructor(e,t){super("or",e,t)}eval(e,t){const r=this.left.eval(e,t);if(ze(r))return r;const n=this.right.eval(e,t);return ze(n)?n:[]}}class It extends Be{constructor(e,t){super("xor",e,t)}eval(e,t){const r=this.left.eval(e,t),n=this.right.eval(e,t);if(0===r.length&&0===n.length)return[];const i=0===r.length?null:r[0].value,o=0===n.length?null:n[0].value;return!0===i&&!0!==o||!0!==i&&!0===o?He(!0):!0===i&&!0===o||!1===i&&!1===o?He(!1):[]}}class Ut{constructor(e,t){this.name=e,this.args=t}eval(e,t){const r=ut[this.name];if(!r)throw new Error("Unrecognized function: "+this.name);return r(e,t,...this.args)}toString(){return`${this.name}(${this.args.map((e=>e.toString())).join(", ")})`}}class Lt{constructor(e,t){this.left=e,this.expr=t}eval(e,t){const r=this.expr.eval(e,t);if(1!==r.length)return[];const n=r[0].value;if("number"!=typeof n)throw new Error("Invalid indexer expression: should return integer}");const i=this.left.eval(e,t);return n in i?[i[n]]:[]}toString(){return`${this.left.toString()}[${this.expr.toString()}]`}}const Nt=["true","false"],Mt=["!=","!~","<=",">=","{}","->"];function _t(e){return new Qe(e,Nt,Mt).tokenize()}const Bt={parse(e){const t=e.consumeAndParse();if(!e.match(")"))throw new Error("Parse error: expected `)` got `"+e.peek()?.value+"`");return t}},jt={parse(e,t){const r=e.consumeAndParse();if(!e.match("]"))throw new Error("Parse error: expected `]`");return new Lt(t,r)},precedence:2},qt={parse(e,t){if(!(t instanceof yt))throw new Error("Unexpected parentheses");const r=[];for(;!e.match(")");)r.push(e.consumeAndParse()),e.match(",");return new Ut(t.name,r)},precedence:0};function $t(e){const t=e.split(" "),r=parseFloat(t[0]);let n=t[1];return n=n&&n.startsWith("'")&&n.endsWith("'")?n.substring(1,n.length-1):"{"+n+"}",{value:r,unit:n}}function Qt(){return(new je).registerPrefix("String",{parse:(t,r)=>new ft({type:e.PropertyType.string,value:r.value})}).registerPrefix("DateTime",{parse:(t,r)=>new ft({type:e.PropertyType.dateTime,value:Fe(r.value)})}).registerPrefix("Quantity",{parse:(t,r)=>new ft({type:e.PropertyType.Quantity,value:$t(r.value)})}).registerPrefix("Number",{parse:(t,r)=>new ft({type:e.PropertyType.decimal,value:parseFloat(r.value)})}).registerPrefix("true",{parse:()=>new ft({type:e.PropertyType.boolean,value:!0})}).registerPrefix("false",{parse:()=>new ft({type:e.PropertyType.boolean,value:!1})}).registerPrefix("Symbol",{parse:(e,t)=>new yt(t.value)}).registerPrefix("{}",{parse:()=>new mt}).registerPrefix("(",Bt).registerInfix("[",jt).registerInfix("(",qt).prefix("+",3,((e,t)=>new gt("+",t,(e=>e)))).prefix("-",3,((e,t)=>new xt("-",t,t,((e,t)=>-t)))).infixLeft(".",1,((e,t,r)=>new wt(e,r))).infixLeft("/",4,((e,t,r)=>new xt("/",e,r,((e,t)=>e/t)))).infixLeft("*",4,((e,t,r)=>new xt("*",e,r,((e,t)=>e*t)))).infixLeft("+",5,((e,t,r)=>new xt("+",e,r,((e,t)=>e+t)))).infixLeft("-",5,((e,t,r)=>new xt("-",e,r,((e,t)=>e-t)))).infixLeft("|",7,((e,t,r)=>new Et(e,r))).infixLeft("=",9,((e,t,r)=>new Pt(e,r))).infixLeft("!=",9,((e,t,r)=>new At(e,r))).infixLeft("~",9,((e,t,r)=>new kt(e,r))).infixLeft("!~",9,((e,t,r)=>new Ct(e,r))).infixLeft("<",8,((e,t,r)=>new xt("<",e,r,((e,t)=>e<t)))).infixLeft("<=",8,((e,t,r)=>new xt("<=",e,r,((e,t)=>e<=t)))).infixLeft(">",8,((e,t,r)=>new xt(">",e,r,((e,t)=>e>t)))).infixLeft(">=",8,((e,t,r)=>new xt(">=",e,r,((e,t)=>e>=t)))).infixLeft("&",5,((e,t,r)=>new Tt(e,r))).infixLeft("and",6,((e,t,r)=>new Dt(e,r))).infixLeft("as",6,((e,t,r)=>new vt(e,r))).infixLeft("contains",6,((e,t,r)=>new St(e,r))).infixLeft("div",6,((e,t,r)=>new xt("div",e,r,((e,t)=>e/t|0)))).infixLeft("in",6,((e,t,r)=>new bt(e,r))).infixLeft("is",6,((e,t,r)=>new Rt(e,r))).infixLeft("mod",6,((e,t,r)=>new xt("mod",e,r,((e,t)=>e%t)))).infixLeft("or",6,((e,t,r)=>new Ot(e,r))).infixLeft("xor",6,((e,t,r)=>new It(e,r)))}const Ft=Qt();function Ht(e){return new ht(e,Ft.construct(_t(e)).consumeAndParse())}function Wt(e,t){const r=Array.isArray(t)?t:[t];for(let e=0;e<r.length;e++){const t=r[e];"object"==typeof t&&"type"in t&&"value"in t||(r[e]=We(r[e]))}return zt(e,r).map((e=>e.value))}function zt(e,t,r){const n=r||{};return Ht(e).eval({variables:n},t)}const Gt=[...Mt,"->","<<",">>"];class Vt{constructor(e){this.parser=e,this.structureMap={resourceType:"StructureMap"}}parse(){for(this.parser.consume("Symbol","map"),this.structureMap.url=this.parser.consume("String").value,this.parser.consume("="),this.structureMap.name=this.parser.consume().value;this.parser.hasMore();){const e=this.parser.peek()?.value;switch(e){case"uses":this.parseUses();break;case"imports":this.parseImport();break;case"group":this.parseGroup();break;case"conceptmap":this.parseConceptMap();break;default:throw new Error(`Unexpected token: ${e}`)}}return this.structureMap}parseUses(){this.parser.consume("Symbol","uses");const e={};e.url=this.parser.consume("String").value,"alias"===this.parser.peek()?.value&&(this.parser.consume("Symbol","alias"),e.alias=this.parser.consume("Symbol").value),this.parser.consume("Symbol","as"),e.mode=this.parser.consume().value,this.structureMap.structure||(this.structureMap.structure=[]),this.structureMap.structure.push(e)}parseImport(){this.parser.consume("Symbol","imports"),this.structureMap.import||(this.structureMap.import=[]),this.structureMap.import.push(this.parser.consume("String").value)}parseGroup(){const e={};this.parser.consume("Symbol","group"),e.name=this.parser.consume("Symbol").value,e.input=this.parseParameters(),"extends"===this.parser.peek()?.value&&(this.parser.consume("Symbol","extends"),e.extends=this.parser.consume("Symbol").value),"<<"===this.parser.peek()?.value?(this.parser.consume("<<"),e.typeMode=this.parser.consume().value,"+"===this.parser.peek()?.value&&(this.parser.consume("+"),e.typeMode="type-and-types"),this.parser.consume(">>")):e.typeMode="none",e.rule=this.parseRules(),this.structureMap.group||(this.structureMap.group=[]),this.structureMap.group.push(e)}parseParameters(){const e=[];for(this.parser.consume("(");this.parser.hasMore()&&")"!==this.parser.peek()?.value;)e.push(this.parseParameter()),","===this.parser.peek()?.value&&this.parser.consume(",");return this.parser.consume(")"),e}parseParameter(){const e={};return e.mode=this.parser.consume().value,e.name=this.parser.consume("Symbol").value,":"===this.parser.peek()?.value&&(this.parser.consume(":"),e.type=this.parser.consume("Symbol").value),e}parseRules(){const e=[];for(this.parser.consume("{");this.parser.hasMore()&&"}"!==this.parser.peek()?.value;)e.push(this.parseRule());return this.parser.consume("}"),e}parseRule(){const e={source:this.parseRuleSources()};return"->"===this.parser.peek()?.value&&(this.parser.consume("->"),e.target=this.parseRuleTargets()),"then"===this.parser.peek()?.value&&(this.parser.consume("Symbol","then"),"{"===this.parser.peek()?.id?e.rule=this.parseRules():e.dependent=this.parseRuleDependents()),"String"===this.parser.peek()?.id?e.name=this.parser.consume().value:e.name=e.source?.[0]?.element,this.parser.consume(";"),e}parseRuleSources(){const e=[this.parseRuleSource()];for(;this.parser.hasMore()&&","===this.parser.peek()?.value;)this.parser.consume(","),e.push(this.parseRuleSource());return e}parseRuleSource(){const e={},t=this.parseRuleContext();if(t.includes(".")){const r=t.split(".");e.context=r[0],e.element=r[1]}else e.context=t;if(this.parser.hasMore()&&":"===this.parser.peek()?.value&&(this.parser.consume(":"),e.type=this.parser.consume().value),this.parser.hasMore()&&"default"===this.parser.peek()?.value&&(this.parser.consume("default"),this.parser.consumeAndParse()),"first"!==this.parser.peek()?.value&&"not_first"!==this.parser.peek()?.value&&"last"!==this.parser.peek()?.value&&"not_last"!==this.parser.peek()?.value&&"only_one"!==this.parser.peek()?.value||(e.listMode=this.parser.consume().value),"as"===this.parser.peek()?.value&&(this.parser.consume("Symbol","as"),e.variable=this.parser.consume().value),"where"===this.parser.peek()?.value){this.parser.consume("Symbol","where");const t=this.parser.consumeAndParse(100);e.condition=t.toString()}if("check"===this.parser.peek()?.value){this.parser.consume("Symbol","check");const t=this.parser.consumeAndParse(100);e.check=t.toString()}return e}parseRuleTargets(){const e=[this.parseRuleTarget()];for(;this.parser.hasMore()&&","===this.parser.peek()?.value;)this.parser.consume(","),e.push(this.parseRuleTarget());return e}parseRuleTarget(){const e={},t=this.parseRuleContext();if(t.includes(".")){const r=t.split(".");e.contextType="variable",e.context=r[0],e.element=r[1]}else e.context=t;return"="===this.parser.peek()?.value&&(this.parser.consume("="),this.parseRuleTargetTransform(e)),"as"===this.parser.peek()?.value&&(this.parser.consume("Symbol","as"),e.variable=this.parser.consume().value),"first"!==this.parser.peek()?.value&&"share"!==this.parser.peek()?.value&&"last"!==this.parser.peek()?.value&&"collate"!==this.parser.peek()?.value||(e.listMode=[this.parser.consume().value]),e}parseRuleTargetTransform(e){e.transform="copy";const t=this.parser.consumeAndParse(6);if(t instanceof yt)this.parseRuleTargetSymbol(e,t);else if(t instanceof Ut)this.parseRuleTargetFunction(e,t);else{if(!(t instanceof ft))throw new Error(`Unexpected FHIRPath: ${t}`);this.parseRuleTargetLiteral(e,t)}}parseRuleTargetSymbol(e,t){e.parameter=[{valueId:t.name}]}parseRuleTargetFunction(e,t){const r=t.name;switch(r){case"create":e.parameter=[{valueString:(t.args?.[0]).value.value}];break;case"translate":e.parameter=[{}];break;default:throw new Error("Unknown target function: "+r)}}parseRuleTargetLiteral(e,t){switch(t.value.type){case"boolean":e.parameter=[{valueBoolean:t.value.value}];break;case"decimal":e.parameter=[{valueDecimal:t.value.value}];break;case"string":e.parameter=[{valueString:t.value.value}];break;default:throw new Error("Unknown target literal type: "+t.value.type)}}parseRuleContext(){let e=this.parser.consume().value;for(;"."===this.parser.peek()?.value;)this.parser.consume("."),e+="."+this.parser.consume().value;return e}parseRuleDependents(){const e=this.parser.consumeAndParse(100);return[{name:e.name,variable:e.args.map((e=>e.name))}]}parseConceptMap(){for(;"}"!==this.parser.peek()?.value;)this.parser.consume();this.parser.consume("}")}}const Jt=Qt().registerInfix("->",{precedence:100}).registerInfix(";",{precedence:200});var Xt;e.Operator=void 0,(Xt=e.Operator||(e.Operator={})).EQUALS="eq",Xt.NOT_EQUALS="ne",Xt.GREATER_THAN="gt",Xt.LESS_THAN="lt",Xt.GREATER_THAN_OR_EQUALS="ge",Xt.LESS_THAN_OR_EQUALS="le",Xt.STARTS_AFTER="sa",Xt.ENDS_BEFORE="eb",Xt.APPROXIMATELY="ap",Xt.CONTAINS="contains",Xt.EXACT="exact",Xt.TEXT="text",Xt.NOT="not",Xt.ABOVE="above",Xt.BELOW="below",Xt.IN="in",Xt.NOT_IN="not-in",Xt.OF_TYPE="of-type",Xt.MISSING="missing",Xt.IDENTIFIER="identifier",Xt.ITERATE="iterate";const Yt={contains:e.Operator.CONTAINS,exact:e.Operator.EXACT,above:e.Operator.ABOVE,below:e.Operator.BELOW,text:e.Operator.TEXT,not:e.Operator.NOT,in:e.Operator.IN,"not-in":e.Operator.NOT_IN,"of-type":e.Operator.OF_TYPE,missing:e.Operator.MISSING,identifier:e.Operator.IDENTIFIER,iterate:e.Operator.ITERATE},Kt={eq:e.Operator.EQUALS,ne:e.Operator.NOT_EQUALS,lt:e.Operator.LESS_THAN,le:e.Operator.LESS_THAN_OR_EQUALS,gt:e.Operator.GREATER_THAN,ge:e.Operator.GREATER_THAN_OR_EQUALS,sa:e.Operator.STARTS_AFTER,eb:e.Operator.ENDS_BEFORE,ap:e.Operator.APPROXIMATELY};function Zt(e){return er(e.pathname.split("/").filter(Boolean).pop(),e.searchParams.entries())}function er(e,t){const r={resourceType:e};for(const[e,n]of t)tr(r,e,n);return r}function tr(t,r,n){let i,o;const s=r.indexOf(":");switch(s>=0?(i=r.substring(0,s),o=r.substring(s+1)):(i=r,o=""),i){case"_sort":!function(e,t){for(const r of t.split(",")){let t,n=!1;r.startsWith("-")?(t=r.substring(1),n=!0):t=r,e.sortRules||(e.sortRules=[]),e.sortRules.push({code:t,descending:n})}}(t,n);break;case"_count":t.count=parseInt(n);break;case"_offset":t.offset=parseInt(n);break;case"_total":t.total=n;break;case"_summary":t.total="accurate",t.count=0;break;case"_include":{const r=ir(n);"iterate"===o&&(r.modifier=e.Operator.ITERATE),t.include?t.include.push(r):t.include=[r];break}case"_revinclude":{const r=ir(n);"iterate"===o&&(r.modifier=e.Operator.ITERATE),t.revInclude?t.revInclude.push(r):t.revInclude=[r];break}case"_fields":t.fields=n.split(",");break;default:{const r=De.types[t.resourceType]?.searchParams?.[i];r?function(t,r,n,i){if("missing"===n)return void or(t,{code:r.code,operator:e.Operator.MISSING,value:i});switch(r.type){case"number":case"date":!function(e,t,r){const{operator:n,value:i}=rr(r);or(e,{code:t.code,operator:n,value:i})}(t,r,i);break;case"reference":case"string":case"token":case"uri":!function(e,t,r,n){or(e,{code:t.code,operator:nr(r),value:n})}(t,r,n,i);break;case"quantity":!function(e,t,r){const[n,i,o]=r.split("|"),{operator:s,value:a}=rr(n);or(e,{code:t.code,operator:s,value:a,unitSystem:i,unitCode:o})}(t,r,i)}}(t,r,o,n):function(t,r,n,i){let o=e.Operator.EQUALS;if(n)o=n;else if(i.length>=2){const e=i.substring(0,2);e in Kt&&(2===i.length||i.at(2)?.match(/\d/))&&(o=e,i=i.substring(e.length))}or(t,{code:r,operator:o,value:i})}(t,i,o,n)}}}function rr(t){const r=t.substring(0,2),n=Kt[r];return n?{operator:n,value:t.substring(2)}:{operator:e.Operator.EQUALS,value:t}}function nr(t){return Yt[t]||e.Operator.EQUALS}function ir(e){const t=e.split(":");if(t.forEach((e=>{if("*"===e)throw new de(ae("'*' is not supported as a value for search inclusion parameters"))})),1===t.length)throw new de(ae(`Invalid include value '${e}': must be of the form ResourceType:search-parameter`));if(2===t.length)return{resourceType:t[0],searchParam:t[1]};if(3===t.length)return{resourceType:t[0],searchParam:t[1],targetType:t[2]};throw new de(ae(`Invalid include value '${e}'`))}function or(e,t){e.filters?e.filters.push(t):e.filters=[t]}const sr=[...Mt,"eq","ne","co"];class ar{constructor(e,t,r){this.path=e,this.operator=t,this.value=r}}class cr{constructor(e){this.child=e}}class ur{constructor(e,t,r){this.keyword=e,this.left=t,this.right=r}}const pr={eq:e.Operator.EQUALS,ne:e.Operator.NOT_EQUALS,co:e.Operator.CONTAINS,sw:void 0,ew:void 0,gt:e.Operator.GREATER_THAN,lt:e.Operator.LESS_THAN,ge:e.Operator.GREATER_THAN_OR_EQUALS,le:e.Operator.LESS_THAN_OR_EQUALS,ap:e.Operator.APPROXIMATELY,sa:e.Operator.STARTS_AFTER,eb:e.Operator.ENDS_BEFORE,pr:e.Operator.MISSING,po:void 0,ss:void 0,sb:void 0,in:e.Operator.IN,ni:e.Operator.NOT_IN,re:void 0,identifier:e.Operator.IDENTIFIER};class dr{constructor(e){this.parser=e}parse(){let e;"("===this.parser.peek()?.value?(this.parser.consume("("),e=this.parse(),this.parser.consume(")")):"not"===this.parser.peek()?.value?(this.parser.consume("Symbol","not"),this.parser.consume("("),e=new cr(this.parse()),this.parser.consume(")")):e=new ar(this.parser.consume("Symbol").value,function(e){const t=pr[e];if(!t)throw new de(ae("Invalid operator: "+e));return t}(this.parser.consume("Symbol").value),this.parser.consume().value);const t=this.parser.peek()?.value;return"and"===t||"or"===t?(this.parser.consume("Symbol",t),new ur(t,e,this.parse())):e}}const lr=Qt();class hr{constructor(e="\r",t="|",r="^",n="~",i="\\",o="&"){this.segmentSeparator=e,this.fieldSeparator=t,this.componentSeparator=r,this.repetitionSeparator=n,this.escapeCharacter=i,this.subcomponentSeparator=o}getMsh2(){return this.fieldSeparator+this.componentSeparator+this.repetitionSeparator+this.escapeCharacter+this.subcomponentSeparator}}class fr{constructor(e,t=new hr){this.context=t,this.segments=e}get(e){return"number"==typeof e?this.segments[e]:this.segments.find((t=>t.name===e))}getAll(e){return this.segments.filter((t=>t.name===e))}toString(){return this.segments.map((e=>e.toString())).join(this.context.segmentSeparator)}buildAck(){const e=new Date,t=this.get("MSH"),r=t?.get(2)?.toString()||"",n=t?.get(3)?.toString()||"",i=t?.get(4)?.toString()||"",o=t?.get(5)?.toString()||"",s=t?.get(9)?.toString()||"",a=t?.get(12)?.toString()||"2.5.1";return new fr([new yr(["MSH",this.context.getMsh2(),i,o,r,n,e.toISOString(),"","ACK",e.getTime().toString(),"P",a],this.context),new yr(["MSA","AA",s,"OK"],this.context)])}static parse(e){if(!e.startsWith("MSH")){const e=new Error("Invalid HL7 message");throw e.type="entity.parse.failed",e}const t=new hr("\r",e.charAt(3),e.charAt(4),e.charAt(5),e.charAt(6),e.charAt(7));return new fr(e.split(/[\r\n]+/).map((e=>yr.parse(e,t))),t)}}class yr{constructor(e,t=new hr){this.context=t,R(e)?this.fields=e.map((e=>mr.parse(e))):this.fields=e,this.name=this.fields[0].components[0][0]}get(e){return this.fields[e]}toString(){return this.fields.map((e=>e.toString())).join(this.context.fieldSeparator)}static parse(e,t=new hr){return new yr(e.split(t.fieldSeparator).map((e=>mr.parse(e,t))),t)}}class mr{constructor(e,t=new hr){this.context=t,this.components=e}get(e,t,r=0){let n=this.components[r][e]||"";return void 0!==t&&(n=n.split(this.context.subcomponentSeparator)[t]||""),n}toString(){return this.components.map((e=>e.join(this.context.componentSeparator))).join(this.context.repetitionSeparator)}static parse(e,t=new hr){return new mr(e.split(t.repetitionSeparator).map((e=>e.split(t.componentSeparator))),t)}}function gr(e){return e.toString().padStart(2,"0")}const vr={base64Binary:"string",boolean:"boolean",canonical:"string",code:"string",date:"string",dateTime:"string",decimal:"number",id:"string",instant:"string",integer:"number",markdown:"string",oid:"string",positiveInt:"number",string:"string",time:"string",unsignedInt:"number",uri:"string",url:"string",uuid:"string",xhtml:"string","http://hl7.org/fhirpath/System.String":"string"},xr=new Set(["resourceType","id","meta","implicitRules","language","text","contained","extension","modifierExtension"]);function Tr(e){const t=De.types[e];return t&&t.structureDefinition.id===e&&"resource"===t.structureDefinition.kind}class Sr{constructor(e){this.issues=[],this.root=e}validate(){const e=this.root;if(!e)throw new de(ce("Resource is null"));const t=e.resourceType;if(!t)throw new de(ce("Missing resource type"));if(br(e,"",this.issues),this.validateObject(We(e),t),this.issues.length>0)throw new de({resourceType:"OperationOutcome",issue:this.issues})}validateObject(e,t){const r=De.types[e.type];if(!r)throw new de(ce("Unknown type: "+e.type));const n=r.properties;this.checkProperties(t,n,e),this.checkAdditionalProperties(t,e,n)}checkProperties(e,t,r){for(const[n,i]of Object.entries(t))this.checkProperty(e+"."+n,i,r)}checkProperty(e,t,r){const n=Ge(r,e.split(".").pop());if(A(n))void 0!==t.min&&t.min>0&&this.issues.push(wr(e,"Missing required property"));else if("*"===t.max){if(!Array.isArray(n))return void this.issues.push(wr(e,"Expected array for property"));for(const r of n)this.checkPropertyValue(e,t,r)}else{if(Array.isArray(n))return void this.issues.push(wr(e,"Expected single value for property"));this.checkPropertyValue(e,t,n)}}checkPropertyValue(e,t,r){null!==r.value&&(L(r.type.charAt(0))?this.validatePrimitiveType(t,r):this.validateObject(r,e))}validatePrimitiveType(e,t){const{type:r,value:n}=t;if(null===n)return;const i=vr[t.type];typeof n===i?"string"===i?this.validateString(e,r,n):"number"===i&&this.validateNumber(e,r,n):this.createIssue(e,"Invalid type for "+r)}validateString(e,t,r){if(!r.trim())return void this.createIssue(e,"Invalid empty string");const n=De.types[t]?.properties?.value;if(n?.type){const i=w(n.type[0],"http://hl7.org/fhir/StructureDefinition/regex");i&&(r.match(new RegExp(i))||this.createIssue(e,"Invalid "+t+" format"))}}validateNumber(t,r,n){var i;!isNaN(n)&&isFinite(n)?((i=r)!==e.PropertyType.integer&&i!==e.PropertyType.positiveInt&&i!==e.PropertyType.unsignedInt||Number.isInteger(n)||this.createIssue(t,"Number is not an integer"),r===e.PropertyType.positiveInt&&n<=0&&this.createIssue(t,"Number is less than or equal to zero"),r===e.PropertyType.unsignedInt&&n<0&&this.createIssue(t,"Number is negative")):this.createIssue(t,"Invalid "+r+" value")}checkAdditionalProperties(e,t,r){const n=t.value;for(const i of Object.keys(n))this.checkAdditionalProperty(e,i,t,r)}checkAdditionalProperty(e,t,r,n){if(!(xr.has(t)||t in n||function(e,t,r){for(const n of Object.keys(r)){if(!n.endsWith("[x]"))continue;const r=n.replace("[x]","");if(!e.startsWith(r))continue;let i=Ge(t,n);if(i&&(Array.isArray(i)&&(i=i[0]),i&&e===r+U(i.type)))return!0}return!1}(t,r,n)||this.checkPrimitiveElement(e,t,r))){const r=`${e}.${t}`;this.issues.push(wr(r,`Invalid additional property "${r}"`))}}checkPrimitiveElement(e,t,r){if(!t.startsWith("_"))return!1;return t.slice(1)in r.value&&(this.validateObject({type:"Element",value:r.value[t]},e),!0)}createIssue(e,t){this.issues.push(wr(e.path,t))}}function br(e,t,r){null===e?r.push(wr(t,"Invalid null value")):Array.isArray(e)?function(e,t,r){for(let n=0;n<e.length;n++)void 0===e[n]?r.push(wr(`${t}[${n}]`,"Invalid undefined value")):br(e[n],`${t}[${n}]`,r)}(e,t,r):"object"==typeof e&&function(e,t,r){for(const[n,i]of Object.entries(e))br(i,`${t}${t?".":""}${n}`,r)}(e,t,r)}function wr(e,t){return{severity:"error",code:"structure",details:{text:t},expression:[e]}}var Er;function Pr(t,r){let n=De.types[t]?.searchParamsDetails?.[r.code];return n||(n=function(t,r){const n=r.code,i=function(e){return e.split("-").reduce(((e,t,r)=>e+(r?U(t):t)),"")}(n),o=kr(t,r.expression)?.split(".");if(!o)return{columnName:i,type:e.SearchParameterType.TEXT};let s,a,c=t,u=!1;for(let e=1;e<o.length;e++){let n=o[e],i=!1;const p=/\[\d+\]$/.exec(n);if(p&&(n=n.substring(0,n.length-p[0].length),i=!0),s=Ce(c,n),!s)throw new Error(`Element definition not found for ${t} ${r.code}`);"0"===s.max||"1"===s.max||i||(u=!0),a=s.type?.[0].code,e<o.length-1&&(c=Ar(a)?Ee(s.path?.split(".")):a)}const p=function(t,r){let n=e.SearchParameterType.TEXT;switch(t.type){case"date":n=r===e.PropertyType.date?e.SearchParameterType.DATE:e.SearchParameterType.DATETIME;break;case"number":n=e.SearchParameterType.NUMBER;break;case"quantity":n=e.SearchParameterType.QUANTITY;break;case"reference":n=r===e.PropertyType.canonical?e.SearchParameterType.CANONICAL:e.SearchParameterType.REFERENCE;break;case"token":"boolean"===r&&(n=e.SearchParameterType.BOOLEAN)}return n}(r,a),d={columnName:i,type:p,elementDefinition:s,array:u};return function(e,t,r){const n=De.types[e];n.searchParamsDetails||(n.searchParamsDetails={});n.searchParamsDetails[t]=r}(t,n,d),d}(t,r)),n}function Ar(e){return"Element"===e||"BackboneElement"===e}function kr(e,t){const r=t.split(" | ");for(const t of r){if((n=t).includes(" as Period")||n.includes(" as SampledDate"))continue;const r=Cr(t);if(r.startsWith(e+"."))return r}var n}function Cr(e){let t=e.trim();t.startsWith("(")&&t.endsWith(")")&&(t=t.substring(1,t.length-1));const r=[" != "," as ",".as(",".exists(",".resolve(",".where("];for(const e of r)t.includes(e)&&(t=t.substring(0,t.indexOf(e)));return t}function Rr(t,r,n){const i=De.types[r.resourceType]?.searchParams?.[n.code];switch(i?.type){case"reference":return function(t,r,n){const i=Wt(n.expression,t),o=Ur(r.operator);if(""===r.value&&0===i.length)return r.operator===e.Operator.EQUALS;const s=i.map((e=>"string"==typeof e?e:e.reference));for(const e of r.value.split(",")){let t=s.includes(e);if(t||"_compartment"!==r.code||(t=s.some((t=>t?.endsWith("/"+e)))),t)return!o}return o}(t,n,i);case"string":case"uri":return Dr(t,n,i);case"token":return function(t,r,n){const i=Pr(t.resourceType,n);return i.type===e.SearchParameterType.BOOLEAN?function(e,t,r){const n=Wt(r.expression,e),i="true"===t.value,o=n.includes(i);return Ur(t.operator)?!o:o}(t,r,n):Dr(t,r,n,!0)}(t,n,i);case"date":return function(e,t,r){const n=Wt(r.expression,e),i=t.value.split(","),o=Ur(t.operator);for(const e of n)for(const r of i){if(Ir(e,t.operator,r))return!o}return o}(t,n,i)}return!1}function Dr(e,t,r,n){const i=Wt(r.expression,e),o=t.value.split(","),s=Ur(t.operator);for(const e of i)for(const r of o){if(Or(e,t.operator,r,n))return!s}return s}function Or(e,t,r,n){if(n&&r.includes("|")){const[n,i]=r.split("|");return Or(e,t,n,!1)&&(!i||Or(e,t,i,!1))}let i="";return e&&("string"==typeof e?i=e:"object"==typeof e&&(i=JSON.stringify(e))),i.toLowerCase().includes(r.toLowerCase())}function Ir(t,r,n){switch(r){case e.Operator.STARTS_AFTER:case e.Operator.GREATER_THAN:return t>n;case e.Operator.GREATER_THAN_OR_EQUALS:return t>=n;case e.Operator.ENDS_BEFORE:case e.Operator.LESS_THAN:return t<n;case e.Operator.LESS_THAN_OR_EQUALS:return t<=n;case e.Operator.EQUALS:case e.Operator.NOT_EQUALS:return t===n}return!1}function Ur(t){return t===e.Operator.NOT_EQUALS||t===e.Operator.NOT}e.SearchParameterType=void 0,(Er=e.SearchParameterType||(e.SearchParameterType={})).BOOLEAN="BOOLEAN",Er.NUMBER="NUMBER",Er.QUANTITY="QUANTITY",Er.TEXT="TEXT",Er.REFERENCE="REFERENCE",Er.CANONICAL="CANONICAL",Er.DATE="DATE",Er.DATETIME="DATETIME",Er.PERIOD="PERIOD",Er.UUID="UUID",e.AndAtom=Dt,e.ArithemticOperatorAtom=xt,e.AsAtom=vt,e.ClientStorage=ve,e.ConcatAtom=Tt,e.ContainsAtom=St,e.DEFAULT_SEARCH_COUNT=20,e.DotAtom=wt,e.EmptySetAtom=mt,e.EqualsAtom=Pt,e.EquivalentAtom=kt,e.FHIRPATH_KEYWORDS=Nt,e.FHIRPATH_OPERATORS=Mt,e.FhirFilterComparison=ar,e.FhirFilterConnective=ur,e.FhirFilterNegation=cr,e.FhirPathAtom=ht,e.FhirSchemaValidator=Sr,e.FunctionAtom=Ut,e.Hl7Context=hr,e.Hl7Field=mr,e.Hl7Message=fr,e.Hl7Segment=yr,e.InAtom=bt,e.IndexerAtom=Lt,e.InfixOperatorAtom=Be,e.IsAtom=Rt,e.LRUCache=i,e.LiteralAtom=ft,e.MEDPLUM_VERSION="2.0.23-b244eeae",e.MedplumClient=class extends Q{constructor(e){if(super(),e?.baseUrl&&!e.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.fetch=e?.fetch||function(){if(!globalThis.fetch)throw new Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}(),this.storage=e?.storage||new ve,this.createPdfImpl=e?.createPdf,this.baseUrl=Me(e?.baseUrl)||"https://api.medplum.com/",this.fhirBaseUrl=this.baseUrl+(Me(e?.fhirUrlPath)||"fhir/R4/"),this.clientId=e?.clientId||"",this.authorizeUrl=e?.authorizeUrl||this.baseUrl+"oauth2/authorize",this.tokenUrl=e?.tokenUrl||this.baseUrl+"oauth2/token",this.logoutUrl=e?.logoutUrl||this.baseUrl+"oauth2/logout",this.onUnauthenticated=e?.onUnauthenticated,this.cacheTime=e?.cacheTime??6e4,this.cacheTime>0?this.requestCache=new i(e?.resourceCacheSize??1e3):this.requestCache=void 0,e?.autoBatchTime?(this.autoBatchTime=e?.autoBatchTime??0,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0);const t=this.getActiveLogin();t&&(this.accessToken=t.accessToken,this.refreshToken=t.refreshToken,this.refreshProfile().catch(console.log)),this.setupStorageListener()}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}clear(){this.storage.clear(),this.clearActiveLogin()}clearActiveLogin(){this.basicAuth||(this.storage.setString("activeLogin",void 0),this.requestCache?.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.sessionDetails=void 0,this.dispatchEvent({type:"change"}))}invalidateUrl(e){e=e.toString(),this.requestCache?.delete(e)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(e){const t=this.fhirBaseUrl+e;if(this.requestCache)for(const e of this.requestCache.keys())(e.endsWith(t)||e.includes(t+"?"))&&this.requestCache.delete(e)}get(e,t={}){e=e.toString();const r=this.getCacheEntry(e,t);if(r)return r.value;let n;n=e.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue?new Promise(((r,n)=>{this.autoBatchQueue.push({method:"GET",url:e.replace(this.fhirBaseUrl,""),options:t,resolve:r,reject:n}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout((()=>this.executeAutoBatch()),this.autoBatchTime))})):this.request("GET",e,t);const i=new ge(n);return this.setCacheEntry(e,i),i}post(e,t,r,n={}){return e=e.toString(),t&&this.setRequestBody(n,t),r&&this.setRequestContentType(n,r),this.invalidateUrl(e),this.request("POST",e,n)}put(e,t,r,n={}){return e=e.toString(),t&&this.setRequestBody(n,t),r&&this.setRequestContentType(n,r),this.invalidateUrl(e),this.request("PUT",e,n)}patch(e,t,r={}){return e=e.toString(),this.setRequestBody(r,t),this.setRequestContentType(r,"application/json-patch+json"),this.invalidateUrl(e),this.request("PATCH",e,r)}delete(e,t){return e=e.toString(),this.invalidateUrl(e),this.request("DELETE",e,t)}async startNewUser(e,t){const{codeChallengeMethod:r,codeChallenge:n}=await this.startPkce();return this.post("auth/newuser",{...e,codeChallengeMethod:r,codeChallenge:n},void 0,t)}async startNewProject(e,t){return this.post("auth/newproject",e,void 0,t)}async startNewPatient(e,t){return this.post("auth/newpatient",e,void 0,t)}async startLogin(e,t){return this.post("auth/login",{...await this.ensureCodeChallenge(e),clientId:e.clientId??this.clientId,scope:e.scope},void 0,t)}async startGoogleLogin(e,t){return this.post("auth/google",{...await this.ensureCodeChallenge(e),clientId:e.clientId??this.clientId,scope:e.scope},void 0,t)}async ensureCodeChallenge(e){return e.codeChallenge?e:{...e,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(e){const t=new URLSearchParams(window.location.search).get("code");return t?this.processCode(t):void await this.requestAuthorization(e)}signOutWithRedirect(){window.location.assign(this.logoutUrl)}async signInWithExternalAuth(e,t,r,n){const i=await this.ensureCodeChallenge(n);window.location.assign(this.getExternalAuthRedirectUri(e,t,r,i))}async exchangeExternalAccessToken(t,r){if(!(r=r||this.clientId))throw new Error("MedplumClient is missing clientId");const n=new URLSearchParams;return n.set("grant_type",e.OAuthGrantType.TokenExchange),n.set("subject_token_type",e.OAuthTokenType.AccessToken),n.set("client_id",r),n.set("subject_token",t),this.fetchTokens(n)}getExternalAuthRedirectUri(e,t,r,n){const i=new URL(e);return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t),i.searchParams.set("redirect_uri",r),i.searchParams.set("scope","openid profile email"),i.searchParams.set("state",JSON.stringify(n)),i.toString()}fhirUrl(...e){return new URL(this.fhirBaseUrl+e.join("/"))}fhirSearchUrl(e,t){const r=this.fhirUrl(e);return t&&(r.search=new URLSearchParams(t).toString()),r}search(e,t,r){const n=this.fhirSearchUrl(e,t),i=n.toString()+"-search",o=this.getCacheEntry(i,r);if(o)return o.value;const s=new ge((async()=>{const e=await this.get(n,r);if(e.entry)for(const t of e.entry)this.cacheResource(t.resource);return e})());return this.setCacheEntry(i,s),s}searchOne(e,t,r){const n=this.fhirSearchUrl(e,t);n.searchParams.set("_count","1"),n.searchParams.sort();const i=n.toString()+"-searchOne",o=this.getCacheEntry(i,r);if(o)return o.value;const s=new ge(this.search(e,n.searchParams,r).then((e=>e.entry?.[0]?.resource)));return this.setCacheEntry(i,s),s}searchResources(e,t,r){const n=this.fhirSearchUrl(e,t).toString()+"-searchResources",i=this.getCacheEntry(n,r);if(i)return i.value;const o=new ge(this.search(e,t,r).then((e=>e.entry?.map((e=>e.resource))??[])));return this.setCacheEntry(n,o),o}async*searchResourcePages(e,t,r){let n=this.fhirSearchUrl(e,t);for(;n;){const t=new URL(n).searchParams,i=await this.search(e,t,r),o=i?.link?.find((e=>"next"===e.relation));if(!i?.entry?.length&&!o)break;yield i?.entry?.map((e=>e.resource))??[],n=o?.url?new URL(o?.url):void 0}}searchValueSet(e,t,r){const n=this.fhirUrl("ValueSet","$expand");return n.searchParams.set("url",e),n.searchParams.set("filter",t),this.get(n.toString(),r)}getCached(e,t){const r=this.requestCache?.get(this.fhirUrl(e,t).toString())?.value;return r&&r.isOk()?r.read():void 0}getCachedReference(e){const t=e.reference;if(!t)return;if("system"===t)return Ie;const[r,n]=t.split("/");return r&&n?this.getCached(r,n):void 0}readResource(e,t,r){return this.get(this.fhirUrl(e,t),r)}readReference(e,t){const r=e?.reference;if(!r)return new ge(Promise.reject(new Error("Missing reference")));if("system"===r)return new ge(Promise.resolve(Ie));const[n,i]=r.split("/");return n&&i?this.readResource(n,i,t):new ge(Promise.reject(new Error("Invalid reference")))}getSchema(){return De}requestSchema(e){if(e in De.types)return Promise.resolve(De);const t=e+"-requestSchema",r=this.getCacheEntry(t,void 0);if(r)return r.value;const n=new ge((async()=>{const t=`{\n StructureDefinitionList(name: "${e}") {\n name,\n description,\n snapshot {\n element {\n id,\n path,\n min,\n max,\n type {\n code,\n targetProfile\n },\n binding {\n valueSet\n },\n definition\n }\n }\n }\n SearchParameterList(base: "${e}", _count: 100) {\n base,\n code,\n type,\n expression,\n target\n }\n }`.replace(/\s+/g," "),r=await this.graphql(t);for(const e of r.data.StructureDefinitionList)be(e);for(const e of r.data.SearchParameterList)we(e);return De})());return this.setCacheEntry(t,n),n}readHistory(e,t,r){return this.get(this.fhirUrl(e,t,"_history"),r)}readVersion(e,t,r,n){return this.get(this.fhirUrl(e,t,"_history",r),n)}readPatientEverything(e,t){return this.get(this.fhirUrl("Patient",e,"$everything"),t)}createResource(e,t){if(!e.resourceType)throw new Error("Missing resourceType");return this.invalidateSearches(e.resourceType),this.post(this.fhirUrl(e.resourceType),e,void 0,t)}async createResourceIfNoneExist(e,t,r){return await this.searchOne(e.resourceType,t,r)??this.createResource(e,r)}createBinary(e,t,r,n){const i=this.fhirUrl("Binary");return t&&i.searchParams.set("_filename",t),n?this.uploadwithProgress(i,e,r,n):this.post(i,e,r)}uploadwithProgress(e,t,r,n){return new Promise(((i,o)=>{const s=new XMLHttpRequest;s.responseType="json",s.onabort=()=>o(new Error("Request aborted")),s.onerror=()=>o(new Error("Request error")),n&&(s.upload.onprogress=e=>n(e),s.upload.onload=e=>n(e)),s.onload=()=>{s.status>=200&&s.status<300?i(s.response):o(new Error(s.statusText))},s.open("POST",e),s.withCredentials=!0,s.setRequestHeader("Authorization","Bearer "+this.accessToken),s.setRequestHeader("Cache-Control","no-cache, no-store, max-age=0"),s.setRequestHeader("Content-Type",r),s.setRequestHeader("X-Medplum","extended"),s.send(t)}))}async createPdf(e,t,r,n){if(!this.createPdfImpl)throw new Error("PDF creation not enabled");const i=await this.createPdfImpl(e,r,n);return this.createBinary(i,t,"application/pdf")}createComment(e,t,r){const n=this.getProfile();let i,o;return"Encounter"===e.resourceType&&(i=m(e),o=e.subject),"ServiceRequest"===e.resourceType&&(i=e.encounter,o=e.subject),"Patient"===e.resourceType&&(o=m(e)),this.createResource({resourceType:"Communication",basedOn:[m(e)],encounter:i,subject:o,sender:n?m(n):void 0,sent:(new Date).toISOString(),payload:[{contentString:t}]},r)}async updateResource(e,t){if(!e.resourceType)throw new Error("Missing resourceType");if(!e.id)throw new Error("Missing id");this.invalidateSearches(e.resourceType);let r=await this.put(this.fhirUrl(e.resourceType,e.id),e,void 0,t);return r||(r=e),this.cacheResource(r),r}patchResource(e,t,r,n){return this.invalidateSearches(e),this.patch(this.fhirUrl(e,t),r,n)}deleteResource(e,t,r){return this.deleteCacheEntry(this.fhirUrl(e,t).toString()),this.invalidateSearches(e),this.delete(this.fhirUrl(e,t),r)}validateResource(e,t){return this.post(this.fhirUrl(e.resourceType,"$validate"),e,void 0,t)}executeBot(e,t,r,n){let i;if("string"==typeof e){const t=e;i=this.fhirUrl("Bot",t,"$execute")}else{const t=e;i=this.fhirUrl("Bot","$execute")+`?identifier=${t.system}|${t.value}`}return this.post(i,t,r,n)}executeBatch(e,t){return this.post(this.fhirBaseUrl.slice(0,-1),e,void 0,t)}sendEmail(e,t){return this.post("email/v1/send",e,"application/json",t)}graphql(e,t,r,n){return this.post(this.fhirUrl("$graphql"),{query:e,operationName:t,variables:r},"application/json",n)}readResourceGraph(e,t,r,n){return this.get(`${this.fhirUrl(e,t)}/$graph?graph=${r}`,n)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(e){this.clearActiveLogin(),this.accessToken=e.accessToken,this.basicAuth||(this.refreshToken=e.refreshToken,this.storage.setObject("activeLogin",e),this.addLogin(e),this.refreshPromise=void 0,await this.refreshProfile())}getAccessToken(){return this.accessToken}setAccessToken(e){this.accessToken=e,this.refreshToken=void 0,this.sessionDetails=void 0}getLogins(){return this.storage.getObject("logins")??[]}addLogin(e){const t=this.getLogins().filter((t=>t.profile?.reference!==e.profile?.reference));t.push(e),this.storage.setObject("logins",t)}async refreshProfile(){return this.profilePromise=new Promise(((e,t)=>{this.basicAuth||this.get("auth/me").then((t=>{this.profilePromise=void 0,this.sessionDetails=t,this.dispatchEvent({type:"change"}),e(t.profile)})).catch(t)})),this.profilePromise}isLoading(){return!!this.profilePromise}isSuperAdmin(){return!!this.sessionDetails?.project?.superAdmin}isProjectAdmin(){return!!this.sessionDetails?.membership?.admin}getProject(){return this.sessionDetails?.project}getProjectMembership(){return this.sessionDetails?.membership}getProfile(){return this.sessionDetails?.profile}async getProfileAsync(){return this.profilePromise&&await this.profilePromise,this.getProfile()}getUserConfiguration(){return this.sessionDetails?.config}getAccessPolicy(){return this.sessionDetails?.accessPolicy}async download(e,t={}){this.refreshPromise&&await this.refreshPromise,this.addFetchOptionsDefaults(t);return(await this.fetch(e.toString(),t)).blob()}async uploadMedia(e,t,r,n,i){const o=await this.createBinary(e,r,t);return this.createResource({...n,resourceType:"Media",content:{contentType:t,url:"Binary/"+o.id,title:r}},i)}async bulkExport(e="",t,r,n={}){const i=e?`${e}/`:e,o=this.fhirUrl(`${i}$export`);t&&o.searchParams.set("_type",t),r&&o.searchParams.set("_since",r),this.addFetchOptionsDefaults(n);n.headers.Prefer="respond-async";const s=await this.fetchWithRetry(o.toString(),n);if(202===s.status){const e=s.headers.get("content-location");if(e)return await this.pollStatus(e)}return await this.parseResponse(s,"POST",o.toString())}getCacheEntry(e,t){if(!this.requestCache||"no-cache"===t?.cache||"reload"===t?.cache)return;const r=this.requestCache.get(e);return!r||r.requestTime+this.cacheTime<Date.now()?void 0:r}setCacheEntry(e,t){this.requestCache&&this.requestCache.set(e,{requestTime:Date.now(),value:t})}cacheResource(e){e?.id&&this.setCacheEntry(this.fhirUrl(e.resourceType,e.id).toString(),new ge(Promise.resolve(e)))}deleteCacheEntry(e){this.requestCache&&this.requestCache.delete(e)}async request(e,t,r={}){this.refreshPromise&&await this.refreshPromise,t.startsWith("http")||(t=this.baseUrl+t),r.method=e,this.addFetchOptionsDefaults(r);const n=await this.fetchWithRetry(t,r);return await this.parseResponse(n,e,t,r)}async parseResponse(e,t,r,n={}){if(401===e.status)return this.handleUnauthenticated(t,r,n);if(204===e.status||304===e.status)return;if(404===e.status){const t=e.headers.get("content-type");if(!t?.includes("application/fhir+json"))throw new de(te)}let i;try{i=await e.json()}catch(t){throw console.error("Error parsing response",e.status,t),t}if(e.status>=400)throw new de(le(i));return i}async fetchWithRetry(e,t){let r;for(let n=0;n<3;n++){try{if(r=await this.fetch(e,t),r.status<500)return r}catch(e){this.retryCatch(n,3,e)}await new Promise((e=>setTimeout(e,200)))}return r}async pollStatus(e){let t,r=!0;for(;r;){const n={};this.addFetchOptionsDefaults(n);const i=await this.fetchWithRetry(e,n);202!==i.status&&(r=!1,t=i),await new Promise((e=>setTimeout(e,200)))}return await this.parseResponse(t,"POST",e)}async executeAutoBatch(){const e=[...this.autoBatchQueue];if(this.autoBatchQueue.length=0,this.autoBatchTimerId=void 0,1===e.length){const t=e[0];try{t.resolve(await this.request(t.method,this.fhirBaseUrl+t.url,t.options))}catch(e){t.reject(new de(le(e)))}return}const t={resourceType:"Bundle",type:"batch",entry:e.map((e=>({request:{method:e.method,url:e.url},resource:e.options.body?JSON.parse(e.options.body):void 0})))},r=await this.post(this.fhirBaseUrl.slice(0,-1),t);for(let t=0;t<e.length;t++){const n=e[t],i=r.entry?.[t];i?.response?.outcome&&!pe(i.response.outcome)?n.reject(new de(i.response.outcome)):n.resolve(i?.resource)}}addFetchOptionsDefaults(e){let t=e.headers;t||(t={},e.headers=t),t.Accept=Oe,t["X-Medplum"]="extended",e.body&&!t["Content-Type"]&&(t["Content-Type"]=Oe),this.accessToken?t.Authorization="Bearer "+this.accessToken:this.basicAuth&&(t.Authorization="Basic "+this.basicAuth),e.cache||(e.cache="no-cache"),e.credentials||(e.credentials="include")}setRequestContentType(e,t){e.headers||(e.headers={});e.headers["Content-Type"]=t}setRequestBody(e,t){"string"==typeof t||"undefined"!=typeof Blob&&t instanceof Blob||"undefined"!=typeof File&&t instanceof File||"undefined"!=typeof Uint8Array&&t instanceof Uint8Array?e.body=t:t&&(e.body=JSON.stringify(t))}handleUnauthenticated(e,t,r){return this.refresh()?this.request(e,t,r):(this.clearActiveLogin(),this.onUnauthenticated&&this.onUnauthenticated(),Promise.reject(new Error("Unauthenticated")))}async startPkce(){const e=$();sessionStorage.setItem("pkceState",e);const t=$();sessionStorage.setItem("codeVerifier",t);const r=I(await async function(e){return crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e))}(t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return sessionStorage.setItem("codeChallenge",r),{codeChallengeMethod:"S256",codeChallenge:r}}async requestAuthorization(e){const t=await this.ensureCodeChallenge(e||{}),r=new URL(this.authorizeUrl);r.searchParams.set("response_type","code"),r.searchParams.set("state",sessionStorage.getItem("pkceState")),r.searchParams.set("client_id",t.clientId||this.clientId),r.searchParams.set("redirect_uri",t.redirectUri||Ne()),r.searchParams.set("code_challenge_method",t.codeChallengeMethod),r.searchParams.set("code_challenge",t.codeChallenge),r.searchParams.set("scope",t.scope||"openid profile"),window.location.assign(r.toString())}processCode(t,r){const n=new URLSearchParams;if(n.set("grant_type",e.OAuthGrantType.AuthorizationCode),n.set("code",t),n.set("client_id",r?.clientId||this.clientId),n.set("redirect_uri",r?.redirectUri||Ne()),"undefined"!=typeof sessionStorage){const e=sessionStorage.getItem("codeVerifier");e&&n.set("code_verifier",e)}return this.fetchTokens(n)}refresh(){if(this.refreshPromise)return this.refreshPromise;if(this.refreshToken){const t=new URLSearchParams;return t.set("grant_type",e.OAuthGrantType.RefreshToken),t.set("client_id",this.clientId),t.set("refresh_token",this.refreshToken),this.refreshPromise=this.fetchTokens(t),this.refreshPromise}return this.clientId&&this.clientSecret?(this.refreshPromise=this.startClientLogin(this.clientId,this.clientSecret),this.refreshPromise):void 0}async startClientLogin(t,r){this.clientId=t,this.clientSecret=r;const n=new URLSearchParams;return n.set("grant_type",e.OAuthGrantType.ClientCredentials),n.set("client_id",t),n.set("client_secret",r),this.fetchTokens(n)}setBasicAuth(e,t){this.clientId=e,this.clientSecret=t,this.basicAuth=r(e+":"+t)}async invite(e,t){return this.post("admin/projects/"+e+"/invite",t)}async fetchTokens(e){const t={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e,credentials:"include"},r=t.headers;this.basicAuth&&(r.Authorization=`Basic ${this.basicAuth}`);const n=await this.fetch(this.tokenUrl,t);if(!n.ok){this.clearActiveLogin();try{const e=await n.json();throw new de(ae(e.error_description))}catch(e){throw new de(ae("Failed to fetch tokens"),e)}}const i=await n.json();return await this.verifyTokens(i),this.getProfile()}async verifyTokens(e){const t=e.access_token,r=F(t);if(Date.now()>=1e3*r.exp)throw this.clearActiveLogin(),new Error("Token expired");if(r.cid){if(r.cid!==this.clientId)throw this.clearActiveLogin(),new Error("Token was not issued for this audience")}else if(this.clientId&&r.client_id!==this.clientId)throw this.clearActiveLogin(),new Error("Token was not issued for this audience");return this.setActiveLogin({accessToken:t,refreshToken:e.refresh_token,project:e.project,profile:e.profile})}setupStorageListener(){try{window.addEventListener("storage",(e=>{null!==e.key&&"activeLogin"!==e.key||window.location.reload()}))}catch(e){}}retryCatch(e,t,r){if("Failed to fetch"===r.message&&1===e&&this.dispatchEvent({type:"offline"}),e>=t-1)throw r}},e.MemoryStorage=xe,e.NotEqualsAtom=At,e.NotEquivalentAtom=Ct,e.OperationOutcomeError=de,e.OrAtom=Ot,e.Parser=qe,e.ParserBuilder=je,e.PrefixOperatorAtom=_e,e.ReadablePromise=ge,e.SymbolAtom=yt,e.Tokenizer=Qe,e.UnaryOperatorAtom=gt,e.UnionAtom=Et,e.XorAtom=It,e.accepted=se,e.allOk=K,e.arrayBufferToBase64=I,e.arrayBufferToHex=O,e.assertOk=function(e,t){if(!pe(e)||void 0===t)throw new de(e)},e.badRequest=ae,e.booleanToTypedValue=He,e.buildTypeName=Ee,e.calculateAge=S,e.calculateAgeString=function(e,t){const{years:r,months:n,days:i}=S(e,t);return r>=2?r.toString().padStart(3,"0")+"Y":n>=1?n.toString().padStart(3,"0")+"M":i.toString().padStart(3,"0")+"D"},e.capitalize=U,e.checkForNull=br,e.convertToTransactionBundle=function(e){for(const t of e.entry||[])delete t?.resource?.meta,t.fullUrl="urn:uuid:"+t?.resource?.id,delete t?.resource?.id;const t=e.entry,r=JSON.stringify({resourceType:"Bundle",type:"transaction",entry:t?.map((e=>({fullUrl:e.fullUrl,request:{method:"POST",url:e.resource.resourceType},resource:e.resource})))},n,2);return JSON.parse(r)},e.createReference=m,e.createStructureIssue=wr,e.created=Z,e.decodeBase64=t,e.deepClone=function(e){return JSON.parse(JSON.stringify(e))},e.deepEquals=k,e.encodeBase64=r,e.evalFhirPath=Wt,e.evalFhirPathTyped=zt,e.fhirPathArrayEquals=Ye,e.fhirPathArrayEquivalent=Ze,e.fhirPathEquals=Ke,e.fhirPathEquivalent=et,e.fhirPathIs=rt,e.fhirPathNot=Xe,e.findObservationInterval=function(e,t,r,n){return e.qualifiedInterval?.find((i=>M(i,t)&&function(e,t,r){return!!e.range&&_(t,e.range,r)}(i,r,e.quantitativeDetails?.decimalPrecision)&&(void 0===n||i.category===n)))},e.findObservationReferenceRange=function(e,t,r){return e.qualifiedInterval?.find((e=>M(e,t)&&r.includes(e.condition)))},e.findResourceByCode=function(e,t,r){return e.find((e=>"string"==typeof t?N(e.code||{},r)===t:N(e.code||{},r)===N(t,r)))},e.forbidden=ne,e.formatAddress=function(e,t){const r=[];if(e.line&&r.push(...e.line),e.city||e.state||e.postalCode){const t=[];e.city&&t.push(e.city),e.state&&t.push(e.state),e.postalCode&&t.push(e.postalCode),r.push(t.join(", "))}return e.use&&(t?.all||t?.use)&&r.push("["+e.use+"]"),r.join(t?.lineSeparator||", ").trim()},e.formatCodeableConcept=h,e.formatCoding=f,e.formatDate=function(e,t,r){if(!e)return"";const n=new Date(e);return s(n)?(n.setUTCHours(0,0,0,0),n.toLocaleDateString(t,{timeZone:"UTC",...r})):""},e.formatDateTime=c,e.formatFamilyName=function(e){return e.family||""},e.formatGivenName=function(e){const t=[];return e.given&&t.push(...e.given),t.join(" ").trim()},e.formatHumanName=o,e.formatMoney=function(e){return void 0===e?.value?"":e.value.toLocaleString(void 0,{style:"currency",currency:e.currency||"USD",currencyDisplay:"narrowSymbol"})},e.formatObservationValue=function e(t){return t?"component"in t?t.component.map((t=>e(t))).join(" / "):t?.valueQuantity?l(t.valueQuantity):t.valueCodeableConcept?h(t.valueCodeableConcept):t.valueString?t.valueString:"":""},e.formatPeriod=function(e,t,r){return e&&(e.start||e.end)?c(e.start,t,r)+" - "+c(e.end,t,r):""},e.formatQuantity=l,e.formatRange=function(e,t,r=!1){if(r&&void 0===t)throw new Error("Precision must be specified for exclusive ranges");const n=e?.low&&{...e.low,comparator:void 0},i=e?.high&&{...e.high,comparator:void 0};return void 0===n?.value&&void 0===i?.value?"":void 0!==n?.value&&void 0===i?.value?r&&void 0!==t?(n.value=function(e,t,r=1){return(y(e,t)-r)*Math.pow(10,-t)}(n.value,t),`> ${l(n,t)}`):`>= ${l(n,t)}`:void 0===n?.value&&void 0!==i?.value?r&&void 0!==t?(i.value=function(e,t,r=1){return(y(e,t)+r)*Math.pow(10,-t)}(i.value,t),`< ${l(i,t)}`):`<= ${l(i,t)}`:(n?.unit===i?.unit&&delete n?.unit,`${l(n,t)} - ${l(i,t)}`)},e.formatSearchQuery=function(t){const r=[];return t.fields&&r.push("_fields="+t.fields.join(",")),t.filters&&t.filters.forEach((t=>r.push(function(t){const r=t.operator in Yt?":"+t.operator:"",n=t.operator!==e.Operator.EQUALS&&t.operator in Kt?t.operator:"";return`${t.code}${r}=${n}${encodeURIComponent(t.value)}`}(t)))),t.sortRules&&t.sortRules.length>0&&r.push("_sort="+t.sortRules.map((e=>e.descending?"-"+e.code:e.code)).join(",")),void 0!==t.offset&&r.push("_offset="+t.offset),void 0!==t.count&&r.push("_count="+t.count),void 0!==t.total&&r.push("_total="+t.total),0===r.length?"":(r.sort(),"?"+r.join("&"))},e.formatTime=a,e.formatTiming=function(e){if(!e)return"";const t=[];if(e.repeat?.periodUnit){const r=e.repeat.frequency||1,n=e.repeat.period||1,i=e.repeat.periodUnit;1===r&&1===n?t.push(u[i]):(1===r?t.push("once"):t.push(r+" times"),1===n?t.push("per "+p[i]):t.push("per "+n+" "+d[i])),e.repeat.dayOfWeek&&t.push("on "+e.repeat.dayOfWeek.map(U).join(", ")),e.repeat.timeOfDay&&t.push("at "+e.repeat.timeOfDay.map((e=>a(e))).join(", "))}return e.event&&t.push(e.event.map((e=>c(e))).join(", ")),U(t.join(" ").trim())},e.getCodeBySystem=N,e.getDateProperty=function(e){return e?new Date(e):void 0},e.getDisplayString=x,e.getElementDefinition=Ce,e.getElementDefinitionTypeName=function(e){const t=e.type?.[0]?.code;return"BackboneElement"===t||"Element"===t?Ee(e.path?.split(".")):t},e.getExpressionForResourceType=kr,e.getExtension=function(e,...t){let r=e;for(let e=0;e<t.length&&r;e++)r=r?.extension?.find((r=>r.url===t[e]));return r},e.getExtensionValue=w,e.getIdentifier=function(e,t){const r=e.identifier;if(!r)return;const n=Array.isArray(r)?r:[r];for(const e of n)if(e.system===t)return e.value},e.getImageSrc=function(e){if(!("photo"in e))return;const t=e.photo;if(t){if(!Array.isArray(t))return T(t);for(const e of t){const t=T(e);if(t)return t}}},e.getPropertyDisplayName=function(e){return e.replaceAll("[x]","").split(".").pop().split(/(?=[A-Z])/).map(ke).join(" ").replace("_"," ").replace(/\s+/g," ")},e.getQuestionnaireAnswers=function(e){const t={};return b(e.item,t),t},e.getReferenceString=g,e.getResourceTypeSchema=function(e){return De.types[e]},e.getResourceTypes=function(){const e=[];for(const[t,r]of Object.entries(De.types))Pe(r)&&e.push(t);return e},e.getSearchParameterDetails=Pr,e.getSearchParameters=function(e){return De.types[e].searchParams},e.getStatus=function(e){return e.id===H?200:e.id===W?201:e.id===G?304:e.id===J?401:e.id===X?403:e.id===V?404:e.id===z?410:e.id===Y?429:400},e.getTypedPropertyValue=Ge,e.globalSchema=De,e.gone=ie,e.indexSearchParameter=we,e.indexSearchParameterBundle=function(e){for(const t of e.entry){const e=t.resource;"SearchParameter"===e.resourceType&&we(e)}},e.indexStructureDefinition=be,e.indexStructureDefinitionBundle=function(e){for(const t of e.entry){const e=t.resource;"StructureDefinition"===e.resourceType&&be(e)}},e.initFhirPathParserBuilder=Qt,e.isEmpty=A,e.isGone=function(e){return e.id===z},e.isLowerCase=L,e.isNotFound=function(e){return e.id===V},e.isObject=C,e.isOk=pe,e.isOperationOutcome=ue,e.isPeriod=nt,e.isProfileResource=v,e.isQuantity=it,e.isQuantityEquivalent=ot,e.isReference=function(e){return!(!e||"object"!=typeof e||!("reference"in e))},e.isResource=Re,e.isResourceType=Tr,e.isResourceTypeSchema=Pe,e.isStringArray=R,e.isUUID=function(e){return!!e.match(/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/i)},e.isValidDate=s,e.matchesRange=_,e.matchesSearchRequest=function(e,t){if(t.resourceType!==e.resourceType)return!1;if(t.filters)for(const r of t.filters)if(!Rr(e,t,r))return!1;return!0},e.normalizeErrorString=he,e.normalizeOperationOutcome=le,e.notFound=te,e.notModified=ee,e.operationOutcomeIssueToString=ye,e.operationOutcomeToString=fe,e.parseFhirPath=Ht,e.parseFilterParameter=function(e){const t=lr.construct(new Qe(e,Nt,sr,{dateTimeLiterals:!0,symbolRegex:/[^\s\])]/}).tokenize());return t.removeComments(),new dr(t).parse()},e.parseHl7Date=function(e,t){if(!e)return;t={seconds:!0,tzOffset:"Z",...t};const r=Number.parseInt(e.substring(0,4)),n=Number.parseInt(e.substring(4,6)),i=Number.parseInt(e.substring(6,8)),o=Number.parseInt(e.substring(8,10)),s=Number.parseInt(e.substring(10,12)),a=t.seconds?Number.parseInt(e.substring(12,14)):0;return`${gr(r)}-${gr(n)}-${gr(i)}T${gr(o)}:${gr(s)}:${gr(a)}.000${t.tzOffset}`},e.parseJWTPayload=F,e.parseMappingLanguage=function(e){const t=Jt.construct(new Qe(e,Nt,Gt).tokenize());return t.removeComments(),new Vt(t).parse()},e.parseSearchDefinition=function(e){return Zt(new URL(e,"https://example.com/"))},e.parseSearchRequest=function(e,t){const r=[];for(const[e,n]of Object.entries(t))if(Array.isArray(n))for(let t=0;t<n.length;t++)r.push([e,n[t]]);else r.push([e,n||""]);return er(e,r)},e.parseSearchUrl=Zt,e.preciseEquals=function(e,t,r){return q(e,r)===q(t,r)},e.preciseGreaterThan=function(e,t,r){return q(e,r)>q(t,r)},e.preciseGreaterThanOrEquals=j,e.preciseLessThan=function(e,t,r){return q(e,r)<q(t,r)},e.preciseLessThanOrEquals=B,e.preciseRound=function(e,t){return parseFloat(e.toFixed(t))},e.removeDuplicates=Je,e.resolveId=function(e){return e?.reference?.split("/")[1]},e.setCodeBySystem=function(e,t,r){e.coding||(e.coding=[]);const n=e.coding?.find((e=>e.system===t));n?n.code=r:e.coding?.push({system:t,code:r})},e.streamToBuffer=function(e){const t=[];return new Promise(((r,n)=>{e.on("data",(e=>t.push(Buffer.from(e)))),e.on("error",(t=>{e.destroy(),n(t)})),e.on("end",(()=>{r(Buffer.concat(t))})),e.on("close",(()=>{e.destroy()}))}))},e.stringify=E,e.toJsBoolean=ze,e.toTypedValue=We,e.tokenize=_t,e.tooManyRequests=oe,e.unauthorized=re,e.validateResource=function(e){new Sr(e).validate()},e.validateResourceType=function(e){if(!e)throw new de(ce("Resource type is null"));if(!Tr(e))throw new de(ce("Unknown resource type"))},e.validationError=ce}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).medplum=e.medplum||{},e.medplum.core={}))}(this,(function(e){"use strict";var t={types:{Element:{display:"Element",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]}}},BackboneElement:{display:"BackboneElement",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]}}},Address:{display:"Address",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},use:{type:[{code:"code"}]},type:{type:[{code:"code"}]},text:{type:[{code:"string"}]},line:{max:"*",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:{display:"Age",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Annotation:{display:"Annotation",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Attachment",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"CodeableConcept",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},coding:{max:"*",type:[{code:"Coding"}]},text:{type:[{code:"string"}]}}},Coding:{display:"Coding",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},system:{type:[{code:"uri"}]},version:{type:[{code:"string"}]},code:{type:[{code:"code"}]},display:{type:[{code:"string"}]},userSelected:{type:[{code:"boolean"}]}}},ContactDetail:{display:"ContactDetail",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},name:{type:[{code:"string"}]},telecom:{max:"*",type:[{code:"ContactPoint"}]}}},ContactPoint:{display:"ContactPoint",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},system:{type:[{code:"code"}]},value:{type:[{code:"string"}]},use:{type:[{code:"code"}]},rank:{type:[{code:"positiveInt"}]},period:{type:[{code:"Period"}]}}},Contributor:{display:"Contributor",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},name:{min:1,type:[{code:"string"}]},contact:{max:"*",type:[{code:"ContactDetail"}]}}},Count:{display:"Count",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},DataRequirement:{display:"DataRequirement",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},profile:{max:"*",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:"*",type:[{code:"string"}]},codeFilter:{max:"*",type:[{code:"Element"}]},dateFilter:{max:"*",type:[{code:"Element"}]},limit:{type:[{code:"positiveInt"}]},sort:{max:"*",type:[{code:"Element"}]}}},DataRequirementCodeFilter:{display:"DataRequirementCodeFilter",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},valueSet:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/ValueSet"]}]},code:{max:"*",type:[{code:"Coding"}]}}},DataRequirementDateFilter:{display:"DataRequirementDateFilter",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},"value[x]":{type:[{code:"dateTime"},{code:"Period"},{code:"Duration"}]}}},DataRequirementSort:{display:"DataRequirementSort",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},direction:{min:1,type:[{code:"code"}]}}},Distance:{display:"Distance",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Dosage:{display:"Dosage",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},sequence:{type:[{code:"integer"}]},text:{type:[{code:"string"}]},additionalInstruction:{max:"*",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:"*",type:[{code:"Element"}]},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:{display:"DosageDoseAndRate",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Duration",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},ElementDefinition:{display:"ElementDefinition",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},representation:{max:"*",type:[{code:"code"}]},sliceName:{type:[{code:"string"}]},sliceIsConstraining:{type:[{code:"boolean"}]},label:{type:[{code:"string"}]},code:{max:"*",type:[{code:"Coding"}]},slicing:{type:[{code:"Element"}]},short:{type:[{code:"string"}]},definition:{type:[{code:"markdown"}]},comment:{type:[{code:"markdown"}]},requirements:{type:[{code:"markdown"}]},alias:{max:"*",type:[{code:"string"}]},min:{type:[{code:"unsignedInt"}]},max:{type:[{code:"string"}]},base:{type:[{code:"Element"}]},contentReference:{type:[{code:"uri"}]},type:{max:"*",type:[{code:"Element"}]},"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:"*",type:[{code:"Element"}]},"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:"*",type:[{code:"id"}]},constraint:{max:"*",type:[{code:"Element"}]},mustSupport:{type:[{code:"boolean"}]},isModifier:{type:[{code:"boolean"}]},isModifierReason:{type:[{code:"string"}]},isSummary:{type:[{code:"boolean"}]},binding:{type:[{code:"Element"}]},mapping:{max:"*",type:[{code:"Element"}]}}},ElementDefinitionSlicing:{display:"ElementDefinitionSlicing",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},discriminator:{max:"*",type:[{code:"Element"}]},description:{type:[{code:"string"}]},ordered:{type:[{code:"boolean"}]},rules:{min:1,type:[{code:"code"}]}}},ElementDefinitionSlicingDiscriminator:{display:"ElementDefinitionSlicingDiscriminator",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},path:{min:1,type:[{code:"string"}]}}},ElementDefinitionBase:{display:"ElementDefinitionBase",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},min:{min:1,type:[{code:"unsignedInt"}]},max:{min:1,type:[{code:"string"}]}}},ElementDefinitionType:{display:"ElementDefinitionType",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},code:{min:1,type:[{code:"uri"}]},profile:{max:"*",type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},targetProfile:{max:"*",type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},aggregation:{max:"*",type:[{code:"code"}]},versioning:{type:[{code:"code"}]}}},ElementDefinitionExample:{display:"ElementDefinitionExample",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"ElementDefinitionConstraint",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"ElementDefinitionBinding",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"ElementDefinitionMapping",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},identity:{min:1,type:[{code:"id"}]},language:{type:[{code:"code"}]},map:{min:1,type:[{code:"string"}]},comment:{type:[{code:"string"}]}}},Expression:{display:"Expression",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Extension",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},url:{min:1,type:[{code:"string"}]},"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:{display:"HumanName",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},use:{type:[{code:"code"}]},text:{type:[{code:"string"}]},family:{type:[{code:"string"}]},given:{max:"*",type:[{code:"string"}]},prefix:{max:"*",type:[{code:"string"}]},suffix:{max:"*",type:[{code:"string"}]},period:{type:[{code:"Period"}]}}},Identifier:{display:"Identifier",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"MarketingStatus",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",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:{display:"Meta",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},versionId:{type:[{code:"id"}]},lastUpdated:{type:[{code:"instant"}]},source:{type:[{code:"uri"}]},profile:{max:"*",type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]},security:{max:"*",type:[{code:"Coding"}]},tag:{max:"*",type:[{code:"Coding"}]},project:{type:[{code:"uri"}]},author:{type:[{code:"Reference"}]},account:{type:[{code:"Reference"}]},compartment:{max:"*",type:[{code:"Reference"}]}}},Money:{display:"Money",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},currency:{type:[{code:"code"}]}}},Narrative:{display:"Narrative",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},status:{min:1,type:[{code:"code"}]},div:{min:1,type:[{code:"xhtml"}]}}},ParameterDefinition:{display:"ParameterDefinition",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Period",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},start:{type:[{code:"dateTime"}]},end:{type:[{code:"dateTime"}]}}},Population:{display:"Population",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},"age[x]":{type:[{code:"Range"},{code:"CodeableConcept"}]},gender:{type:[{code:"CodeableConcept"}]},race:{type:[{code:"CodeableConcept"}]},physiologicalCondition:{type:[{code:"CodeableConcept"}]}}},ProdCharacteristic:{display:"ProdCharacteristic",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",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:"*",type:[{code:"string"}]},imprint:{max:"*",type:[{code:"string"}]},image:{max:"*",type:[{code:"Attachment"}]},scoring:{type:[{code:"CodeableConcept"}]}}},ProductShelfLife:{display:"ProductShelfLife",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},identifier:{type:[{code:"Identifier"}]},type:{min:1,type:[{code:"CodeableConcept"}]},period:{min:1,type:[{code:"Quantity"}]},specialPrecautionsForStorage:{max:"*",type:[{code:"CodeableConcept"}]}}},Quantity:{display:"Quantity",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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"}]}}},Range:{display:"Range",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Ratio",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},numerator:{type:[{code:"Quantity"}]},denominator:{type:[{code:"Quantity"}]}}},Reference:{display:"Reference",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},reference:{type:[{code:"string"}]},type:{type:[{code:"uri"}]},identifier:{type:[{code:"Identifier"}]},display:{type:[{code:"string"}]}}},RelatedArtifact:{display:"RelatedArtifact",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"SampledData",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Signature",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},type:{min:1,max:"*",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:{display:"SubstanceAmount",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},"amount[x]":{type:[{code:"Quantity"},{code:"Range"},{code:"string"}]},amountType:{type:[{code:"CodeableConcept"}]},amountText:{type:[{code:"string"}]},referenceRange:{type:[{code:"Element"}]}}},SubstanceAmountReferenceRange:{display:"SubstanceAmountReferenceRange",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},lowLimit:{type:[{code:"Quantity"}]},highLimit:{type:[{code:"Quantity"}]}}},Timing:{display:"Timing",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},event:{max:"*",type:[{code:"dateTime"}]},repeat:{type:[{code:"Element"}]},code:{type:[{code:"CodeableConcept"}]}}},TimingRepeat:{display:"TimingRepeat",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:"*",type:[{code:"code"}]},timeOfDay:{max:"*",type:[{code:"time"}]},when:{max:"*",type:[{code:"code"}]},offset:{type:[{code:"unsignedInt"}]}}},TriggerDefinition:{display:"TriggerDefinition",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:"*",type:[{code:"DataRequirement"}]},condition:{type:[{code:"Expression"}]}}},UsageContext:{display:"UsageContext",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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"]}]}}},MetadataResource:{display:"MetadataResource",properties:{id:{type:[{code:"string"}]},meta:{type:[{code:"Meta"}]},implicitRules:{type:[{code:"uri"}]},language:{type:[{code:"code"}]},text:{type:[{code:"Narrative"}]},contained:{max:"*",type:[{code:"Resource"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},url:{type:[{code:"uri"}]},version:{type:[{code:"string"}]},name:{type:[{code:"string"}]},title:{type:[{code:"string"}]},status:{min:1,type:[{code:"code"}]},experimental:{type:[{code:"boolean"}]},date:{type:[{code:"dateTime"}]},publisher:{type:[{code:"string"}]},contact:{max:"*",type:[{code:"ContactDetail"}]},description:{type:[{code:"markdown"}]},useContext:{max:"*",type:[{code:"UsageContext"}]},jurisdiction:{max:"*",type:[{code:"CodeableConcept"}]}}},IdentityProvider:{display:"IdentityProvider",properties:{authorizeUrl:{min:1,type:[{code:"string"}]},tokenUrl:{min:1,type:[{code:"string"}]},userInfoUrl:{min:1,type:[{code:"string"}]},clientId:{min:1,type:[{code:"string"}]},clientSecret:{min:1,type:[{code:"string"}]},useSubject:{type:[{code:"boolean"}]}}}}};function r(e,t){const r=[];return e.prefix&&!1!==t?.prefix&&r.push(...e.prefix),e.given&&r.push(...e.given),e.family&&r.push(e.family),e.suffix&&!1!==t?.suffix&&r.push(...e.suffix),e.use&&(t?.all||t?.use)&&r.push("["+e.use+"]"),r.join(" ").trim()}function n(e){return e instanceof Date&&!isNaN(e.getTime())}function i(e,t,r){if(!e)return"";const i=new Date("2000-01-01T"+e+"Z");return n(i)?i.toLocaleTimeString(t,r):""}function o(e,t,r){if(!e)return"";const i=new Date(e);return n(i)?i.toLocaleString(t,r):""}const s={s:"every second",min:"every minute",h:"hourly",d:"daily",wk:"weekly",mo:"monthly",a:"annually"},a={s:"second",min:"minute",h:"hour",d:"day",wk:"week",mo:"month",a:"year"},c={s:"seconds",min:"minutes",h:"hours",d:"days",wk:"weeks",mo:"months",a:"years"};function u(e,t){if(!e)return"";const r=[];return e.comparator&&(r.push(e.comparator),r.push(" ")),void 0!==e.value&&(void 0!==t?r.push(e.value.toFixed(t)):r.push(e.value)),e.unit&&("%"!==e.unit&&" "!==r[r.length-1]&&r.push(" "),r.push(e.unit)),r.join("").trim()}function p(e){return e?e.text?e.text:e.coding?e.coding.map((e=>d(e))).join(", "):"":""}function d(e){return e?.display||e?.code||""}function l(e,t){return void 0===t?e:Math.round(e*Math.pow(10,t))}function h(e){const t=f(e),r=m(e);return r===t?{reference:t}:{reference:t,display:r}}function f(e){return e.resourceType+"/"+e.id}function y(e){return"Patient"===e.resourceType||"Practitioner"===e.resourceType||"RelatedPerson"===e.resourceType}function m(e){if(y(e)){const t=function(e){const t=e.name;if(t&&t.length>0)return r(t[0]);return}(e);if(t)return t}if("Device"===e.resourceType){const t=function(e){const t=e.deviceName;if(t&&t.length>0)return t[0].name;return}(e);if(t)return t}return"Observation"===e.resourceType&&"code"in e&&e.code?.text?e.code.text:"User"===e.resourceType&&e.email?e.email:"name"in e&&e.name&&"string"==typeof e.name?e.name:f(e)}function g(e){if(e.url&&e.contentType&&e.contentType.startsWith("image/"))return e.url}function v(e,t){const r=new Date(e);r.setUTCHours(0,0,0,0);const n=t?new Date(t):new Date;n.setUTCHours(0,0,0,0);const i=r.getUTCFullYear(),o=r.getUTCMonth(),s=r.getUTCDate(),a=n.getUTCFullYear(),c=n.getUTCMonth(),u=n.getUTCDate();let p=a-i;(c<o||c===o&&u<s)&&p--;let d=12*a+c-(12*i+o);u<s&&d--;return{years:p,months:d,days:Math.floor((n.getTime()-r.getTime())/864e5)}}function x(e,t){if(e)for(const r of e)r.linkId&&r.answer&&r.answer.length>0&&(t[r.linkId]=r.answer[0]),x(r.item,t)}function T(e,...t){let r=e;for(let e=0;e<t.length&&r;e++)r=r?.extension?.find((r=>r.url===t[e]));return r?.valueString}function b(e,t){return JSON.stringify(e,S,t?2:void 0)}function S(e,t){return!function(e){return!!e.match(/\d+$/)}(e)&&w(t)?void 0:t}function w(e){if(null==e)return!0;const t=typeof e;return"string"===t&&""===e||"object"===t&&0===Object.keys(e).length}function E(e,t,r){return e===t||(!(!w(e)||!w(t))||!w(e)&&!w(t)&&(Array.isArray(e)&&Array.isArray(t)?function(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!E(e[r],t[r]))return!1;return!0}(e,t):!Array.isArray(e)&&!Array.isArray(t)&&(P(e)&&P(t)?function(e,t,r){const n=new Set;Object.keys(e).forEach((e=>n.add(e))),Object.keys(t).forEach((e=>n.add(e))),"meta"===r&&(n.delete("versionId"),n.delete("lastUpdated"),n.delete("author"));for(const r of n){if(!E(e[r],t[r],r))return!1}return!0}(e,t,r):(P(e)||P(t),!1))))}function P(e){return null!==e&&"object"==typeof e}function k(e){return e.every((e=>"string"==typeof e))}const C=[];for(let e=0;e<256;e++)C.push(e.toString(16).padStart(2,"0"));function A(e){const t=new Uint8Array(e),r=new Array(t.length);for(let e=0;e<t.length;e++)r[e]=C[t[e]];return r.join("")}function R(e){const t=new Uint8Array(e),r=[];for(let e=0;e<t.length;e++)r[e]=String.fromCharCode(t[e]);return window.btoa(r.join(""))}function D(e){return e.charAt(0).toUpperCase()+e.substring(1)}function O(e){return e===e.toLowerCase()&&e!==e.toUpperCase()}function I(e,t){return e.coding?.find((e=>e.system===t))?.code}function U(e,t){return function(e,t){return!e.gender||e.gender===t.gender}(e,t)&&function(e,t){return!e.age||N(v(t.birthDate).years,e.age)}(e,t)}function N(e,t,r){return(void 0===t.low?.value||M(e,t.low.value,r))&&(void 0===t.high?.value||L(e,t.high.value,r))}function L(e,t,r){return _(e,r)<=_(t,r)}function M(e,t,r){return _(e,r)>=_(t,r)}function _(e,t){return void 0===t?e:Math.round(e*Math.pow(10,t))}var B;function j(e){if(!e.name)return;const t=e.snapshot?.element;t&&(t.forEach((t=>function(e,t){const r=t.path,n=t.type?.[0]?.code;if(void 0!==n&&"Element"!==n&&"BackboneElement"!==n)return;const i=r.split(".");i[0]=e.name;const o=q(i);let s=G.types[o];s||(G.types[o]=s={});s.parentType=s.parentType||q(i.slice(0,i.length-1)),s.display=s.display||o,s.structureDefinition=s.structureDefinition||e,s.elementDefinition=s.elementDefinition||t,s.description=s.description||t.definition,s.properties=s.properties||{}}(e,t))),t.forEach((t=>function(e,t){const r=t.path,n=r.split(".");if(1===n.length)return;n[0]=e.name;const i=q(n.slice(0,n.length-1)),o=G.types[i];if(!o)return;const s=n[n.length-1];o.properties[s]=t}(e,t))))}function $(e){if(e.base)for(const t of e.base){const r=G.types[t];r&&(r.searchParams||(r.searchParams={_id:{base:[t],code:"_id",type:"token",expression:t+".id"},_lastUpdated:{base:[t],code:"_lastUpdated",type:"date",expression:t+".meta.lastUpdated"},_compartment:{base:[t],code:"_compartment",type:"reference",expression:t+".meta.compartment"},_profile:{base:[t],code:"_profile",type:"uri",expression:t+".meta.profile"},_security:{base:[t],code:"_security",type:"token",expression:t+".meta.security"},_source:{base:[t],code:"_source",type:"uri",expression:t+".meta.source"},_tag:{base:[t],code:"_tag",type:"token",expression:t+".meta.tag"}}),r.searchParams[e.code]=e)}}function q(e){return 1===e.length?e[0]:e.map(D).join("")}function F(e){const t=e.structureDefinition;return t&&t.name===e.elementDefinition.path&&"resource"===t.kind&&!t.abstract}e.PropertyType=void 0,(B=e.PropertyType||(e.PropertyType={})).Address="Address",B.Age="Age",B.Annotation="Annotation",B.Attachment="Attachment",B.BackboneElement="BackboneElement",B.CodeableConcept="CodeableConcept",B.Coding="Coding",B.ContactDetail="ContactDetail",B.ContactPoint="ContactPoint",B.Contributor="Contributor",B.Count="Count",B.DataRequirement="DataRequirement",B.Distance="Distance",B.Dosage="Dosage",B.Duration="Duration",B.Expression="Expression",B.Extension="Extension",B.HumanName="HumanName",B.Identifier="Identifier",B.MarketingStatus="MarketingStatus",B.Meta="Meta",B.Money="Money",B.Narrative="Narrative",B.ParameterDefinition="ParameterDefinition",B.Period="Period",B.Population="Population",B.ProdCharacteristic="ProdCharacteristic",B.ProductShelfLife="ProductShelfLife",B.Quantity="Quantity",B.Range="Range",B.Ratio="Ratio",B.Reference="Reference",B.RelatedArtifact="RelatedArtifact",B.SampledData="SampledData",B.Signature="Signature",B.SubstanceAmount="SubstanceAmount",B.SystemString="http://hl7.org/fhirpath/System.String",B.Timing="Timing",B.TriggerDefinition="TriggerDefinition",B.UsageContext="UsageContext",B.base64Binary="base64Binary",B.boolean="boolean",B.canonical="canonical",B.code="code",B.date="date",B.dateTime="dateTime",B.decimal="decimal",B.id="id",B.instant="instant",B.integer="integer",B.markdown="markdown",B.oid="oid",B.positiveInt="positiveInt",B.string="string",B.time="time",B.unsignedInt="unsignedInt",B.uri="uri",B.url="url",B.uuid="uuid";const Q=new Set(["ID","IP","PKCE","JWKS","URI","URL"]);function W(e){const t=e.toUpperCase();return Q.has(t)?t:t.charAt(0)+e.slice(1)}function H(e,t){const r=G.types[e];if(!r)return;const n=r.properties[t]??r.properties[t+"[x]"];if(n){if(n.contentReference){const e=n.contentReference.substring(1).split("."),t=e.pop();return H(q(e),t)}return n}}function z(e){return!(!e||"object"!=typeof e||!("resourceType"in e))}const G=t,V="ok",J="created",X="gone",Y="not-modified",Z="not-found",K="unauthorized",ee="forbidden",te="too-many-requests",re="accepted",ne={resourceType:"OperationOutcome",id:V,issue:[{severity:"information",code:"informational",details:{text:"All OK"}}]},ie={resourceType:"OperationOutcome",id:J,issue:[{severity:"information",code:"informational",details:{text:"Created"}}]},oe={resourceType:"OperationOutcome",id:Y,issue:[{severity:"information",code:"informational",details:{text:"Not Modified"}}]},se={resourceType:"OperationOutcome",id:Z,issue:[{severity:"error",code:"not-found",details:{text:"Not found"}}]},ae={resourceType:"OperationOutcome",id:K,issue:[{severity:"error",code:"login",details:{text:"Unauthorized"}}]},ce={resourceType:"OperationOutcome",id:ee,issue:[{severity:"error",code:"forbidden",details:{text:"Forbidden"}}]},ue={resourceType:"OperationOutcome",id:X,issue:[{severity:"error",code:"deleted",details:{text:"Gone"}}]},pe={resourceType:"OperationOutcome",id:te,issue:[{severity:"error",code:"throttled",details:{text:"Too Many Requests"}}]};function de(e,t){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"invalid",details:{text:e},expression:t?[t]:void 0}]}}function le(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"structure",details:{text:e}}]}}function he(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"exception",details:{text:"Internal server error"},diagnostics:e.toString()}]}}function fe(e){return"object"==typeof e&&null!==e&&"OperationOutcome"===e.resourceType}function ye(e){return e.id===V||e.id===J||e.id===Y||e.id===re}class me extends Error{constructor(e,t){super(xe(e)),this.outcome=e,this.cause=t}}function ge(e){return e instanceof me?e.outcome:fe(e)?e:de(ve(e))}function ve(e){return e?"string"==typeof e?e:e instanceof Error?e.message:fe(e)?xe(e):JSON.stringify(e):"Unknown error"}function xe(e){const t=e.issue?.map(Te)??[];return t.length>0?t.join("; "):"Unknown error"}function Te(e){let t=e.details?.text??e.diagnostics??"Unknown error";return e.expression?.length&&(t+=` (${e.expression.join(", ")})`),t}var be;e.Operator=void 0,(be=e.Operator||(e.Operator={})).EQUALS="eq",be.NOT_EQUALS="ne",be.GREATER_THAN="gt",be.LESS_THAN="lt",be.GREATER_THAN_OR_EQUALS="ge",be.LESS_THAN_OR_EQUALS="le",be.STARTS_AFTER="sa",be.ENDS_BEFORE="eb",be.APPROXIMATELY="ap",be.CONTAINS="contains",be.EXACT="exact",be.TEXT="text",be.NOT="not",be.ABOVE="above",be.BELOW="below",be.IN="in",be.NOT_IN="not-in",be.OF_TYPE="of-type",be.MISSING="missing",be.IDENTIFIER="identifier",be.ITERATE="iterate";const Se={contains:e.Operator.CONTAINS,exact:e.Operator.EXACT,above:e.Operator.ABOVE,below:e.Operator.BELOW,text:e.Operator.TEXT,not:e.Operator.NOT,in:e.Operator.IN,"not-in":e.Operator.NOT_IN,"of-type":e.Operator.OF_TYPE,missing:e.Operator.MISSING,identifier:e.Operator.IDENTIFIER,iterate:e.Operator.ITERATE},we={eq:e.Operator.EQUALS,ne:e.Operator.NOT_EQUALS,lt:e.Operator.LESS_THAN,le:e.Operator.LESS_THAN_OR_EQUALS,gt:e.Operator.GREATER_THAN,ge:e.Operator.GREATER_THAN_OR_EQUALS,sa:e.Operator.STARTS_AFTER,eb:e.Operator.ENDS_BEFORE,ap:e.Operator.APPROXIMATELY};function Ee(e){return ke(e.pathname.split("/").filter(Boolean).pop(),e.searchParams.entries())}function Pe(e){return Ee(new URL(e,"https://api.medplum.com/"))}function ke(e,t){const r={resourceType:e};for(const[e,n]of t)Ce(r,e,n);return r}function Ce(t,r,n){let i,o;const s=r.indexOf(":");switch(s>=0?(i=r.substring(0,s),o=r.substring(s+1)):(i=r,o=""),i){case"_sort":!function(e,t){for(const r of t.split(",")){let t,n=!1;r.startsWith("-")?(t=r.substring(1),n=!0):t=r,e.sortRules||(e.sortRules=[]),e.sortRules.push({code:t,descending:n})}}(t,n);break;case"_count":t.count=parseInt(n,10);break;case"_offset":t.offset=parseInt(n,10);break;case"_total":t.total=n;break;case"_summary":t.total="accurate",t.count=0;break;case"_include":{const r=De(n);"iterate"===o&&(r.modifier=e.Operator.ITERATE),t.include?t.include.push(r):t.include=[r];break}case"_revinclude":{const r=De(n);"iterate"===o&&(r.modifier=e.Operator.ITERATE),t.revInclude?t.revInclude.push(r):t.revInclude=[r];break}case"_fields":t.fields=n.split(",");break;default:{const r=G.types[t.resourceType]?.searchParams?.[i];r?function(t,r,n,i){if("missing"===n)return void Oe(t,{code:r.code,operator:e.Operator.MISSING,value:i});switch(r.type){case"number":case"date":!function(e,t,r){const{operator:n,value:i}=Ae(r);Oe(e,{code:t.code,operator:n,value:i})}(t,r,i);break;case"reference":case"string":case"token":case"uri":!function(e,t,r,n){Oe(e,{code:t.code,operator:Re(r),value:n})}(t,r,n,i);break;case"quantity":!function(e,t,r){const[n,i,o]=r.split("|"),{operator:s,value:a}=Ae(n);Oe(e,{code:t.code,operator:s,value:a,unitSystem:i,unitCode:o})}(t,r,i)}}(t,r,o,n):function(t,r,n,i){let o=e.Operator.EQUALS;if(n)o=n;else if(i.length>=2){const e=i.substring(0,2);e in we&&(2===i.length||i.at(2)?.match(/\d/))&&(o=e,i=i.substring(e.length))}Oe(t,{code:r,operator:o,value:i})}(t,i,o,n)}}}function Ae(t){const r=t.substring(0,2),n=we[r];return n?{operator:n,value:t.substring(2)}:{operator:e.Operator.EQUALS,value:t}}function Re(t){return Se[t]||e.Operator.EQUALS}function De(e){const t=e.split(":");if(t.forEach((e=>{if("*"===e)throw new me(de("'*' is not supported as a value for search inclusion parameters"))})),1===t.length)throw new me(de(`Invalid include value '${e}': must be of the form ResourceType:search-parameter`));if(2===t.length)return{resourceType:t[0],searchParam:t[1]};if(3===t.length)return{resourceType:t[0],searchParam:t[1],targetType:t[2]};throw new me(de(`Invalid include value '${e}'`))}function Oe(e,t){e.filters?e.filters.push(t):e.filters=[t]}class Ie{constructor(e,t){this.operator=e,this.child=t}toString(){return`${this.operator}(${this.child.toString()})`}}class Ue{constructor(e,t,r){this.operator=e,this.left=t,this.right=r}toString(){return`${this.left.toString()} ${this.operator} ${this.right.toString()}`}}class Ne{constructor(){this.prefixParselets={},this.infixParselets={}}registerInfix(e,t){return this.infixParselets[e]=t,this}registerPrefix(e,t){return this.prefixParselets[e]=t,this}prefix(e,t,r){return this.registerPrefix(e,{parse(e,n){const i=e.consumeAndParse(t);return r(n,i)}})}infixLeft(e,t,r){return this.registerInfix(e,{parse(e,n,i){const o=e.consumeAndParse(t);return r(n,i,o)},precedence:t})}construct(e){return new Le(e,this.prefixParselets,this.infixParselets)}}class Le{constructor(e,t,r){this.tokens=e,this.prefixParselets=t,this.infixParselets=r}hasMore(){return this.tokens.length>0}match(e){const t=this.peek();return t?.id===e&&(this.consume(),!0)}consumeAndParse(e=1/0){const t=this.consume(),r=this.prefixParselets[t.id];if(!r)throw Error(`Parse error at "${t.value}" (line ${t.line}, column ${t.column}). No matching prefix parselet.`);let n=r.parse(this,t);for(;e>this.getPrecedence();){const e=this.consume();n=this.getInfixParselet(e).parse(this,n,e)}return n}getPrecedence(){const e=this.peek();if(!e)return 1/0;const t=this.getInfixParselet(e);return t?t.precedence:1/0}consume(e,t){if(!this.tokens.length)throw Error("Cant consume unknown more tokens.");if(e&&this.peek()?.id!==e){const t=this.peek();throw Error(`Expected ${e} but got "${t.id}" at line ${t.line} column ${t.column}.`)}if(t&&this.peek()?.value!==t){const e=this.peek();throw Error(`Expected "${t}" but got "${e.value}" at line ${e.line} column ${e.column}.`)}return this.tokens.shift()}peek(){return this.tokens.length>0?this.tokens[0]:void 0}removeComments(){this.tokens=this.tokens.filter((e=>"Comment"!==e.id))}getInfixParselet(e){return this.infixParselets["Symbol"===e.id?e.value:e.id]}}const Me=["year","years","month","months","week","weeks","day","days","hour","hours","minute","minutes","second","seconds","millisecond","milliseconds"];class _e{constructor(e,t,r,n){this.result=[],this.pos={index:0,line:1,column:0},this.markStack=[],this.str=e,this.keywords=t,this.operators=r,this.dateTimeLiterals=!!n?.dateTimeLiterals,this.symbolRegex=n?.symbolRegex??/[$\w%]/}tokenize(){for(;this.pos.index<this.str.length;){const e=this.consumeToken();e&&this.result.push(e)}return this.result}prevToken(){return this.result.slice(-1)[0]}peekToken(){this.mark();const e=this.consumeToken();return this.reset(),e}consumeToken(){this.consumeWhitespace();const e=this.curr();if(!e)return;this.mark();const t=this.peek();return"/"===e&&"*"===t?this.consumeMultiLineComment():"/"===e&&"/"===t?this.consumeSingleLineComment():"'"===e||'"'===e?this.consumeString(e):"`"===e?this.consumeBacktickSymbol():"@"===e?this.consumeDateTime():e.match(/\d/)?this.consumeNumber():e.match(/\w/)?this.consumeSymbol():"$"!==e&&"%"!==e||!t.match(/\w/)?this.consumeOperator():this.consumeSymbol()}consumeWhitespace(){this.consumeWhile((()=>this.curr().match(/\s/)))}consumeMultiLineComment(){const e=this.pos.index;return this.consumeWhile((()=>"*"!==this.curr()||"/"!==this.peek())),this.advance(),this.advance(),this.buildToken("Comment",this.str.substring(e,this.pos.index))}consumeSingleLineComment(){return this.buildToken("Comment",this.consumeWhile((()=>"\n"!==this.curr())))}consumeString(e){this.advance();const t=this.buildToken("String",this.consumeWhile((()=>"\\"===this.prev()||this.curr()!==e)));return this.advance(),t}consumeBacktickSymbol(){this.advance();const e=this.buildToken("Symbol",this.consumeWhile((()=>"`"!==this.curr())));return this.advance(),e}consumeDateTime(){this.advance();const e=this.pos.index;return this.consumeWhile((()=>this.curr().match(/[\d-]/))),"T"===this.curr()&&(this.advance(),this.consumeWhile((()=>this.curr().match(/[\d:]/))),"."===this.curr()&&this.peek().match(/\d/)&&(this.advance(),this.consumeWhile((()=>this.curr().match(/\d/)))),"Z"===this.curr()?this.advance():"+"!==this.curr()&&"-"!==this.curr()||(this.advance(),this.consumeWhile((()=>this.curr().match(/[\d:]/))))),this.buildToken("DateTime",this.str.substring(e,this.pos.index))}consumeNumber(){const e=this.pos.index;let t="Number";return this.consumeWhile((()=>this.curr().match(/\d/))),"."===this.curr()&&this.peek().match(/\d/)&&(this.advance(),this.consumeWhile((()=>this.curr().match(/\d/)))),"-"===this.curr()&&this.dateTimeLiterals?(this.pos.index=e-1,this.consumeDateTime()):(" "===this.curr()&&function(e){if(e){if("String"===e.id)return!0;if("Symbol"===e.id&&Me.includes(e.value))return!0}return!1}(this.peekToken())&&(t="Quantity",this.consumeToken()),this.buildToken(t,this.str.substring(e,this.pos.index)))}consumeSymbol(){const e=this.consumeWhile((()=>this.curr().match(this.symbolRegex)));return"."!==this.prevToken()?.value&&this.keywords.includes(e)?this.buildToken(e,e):this.buildToken("Symbol",e)}consumeOperator(){const e=this.curr(),t=e+this.peek();return this.operators.includes(t)?(this.advance(),this.advance(),this.buildToken(t,t)):(this.advance(),this.buildToken(e,e))}consumeWhile(e){const t=this.pos.index;for(;this.pos.index<this.str.length&&e();)this.advance();return this.str.substring(t,this.pos.index)}curr(){return this.str[this.pos.index]}prev(){return this.str[this.pos.index-1]??""}peek(){return this.str[this.pos.index+1]??""}mark(){this.markStack.push({...this.pos})}reset(){const e=this.markStack.pop();if(!e)throw new Error("No mark to reset to");this.pos.index=e.index,this.pos.line=e.line,this.pos.column=e.column}advance(){this.pos.index++,"\n"===this.curr()?(this.pos.line++,this.pos.column=0):this.pos.column++}buildToken(e,t){const r=this.markStack.pop();if(!r)throw new Error("No mark for token");return{id:e,value:t,...r}}}function Be(e){if(e.startsWith("T"))return e+"T00:00:00.000Z".substring(e.length);if(e.length<=10)return e;try{return new Date(e).toISOString()}catch(t){return e}}function je(t){return[{type:e.PropertyType.boolean,value:t}]}function $e(t){return null==t?{type:"undefined",value:void 0}:Number.isSafeInteger(t)?{type:e.PropertyType.integer,value:t}:"number"==typeof t?{type:e.PropertyType.decimal,value:t}:"boolean"==typeof t?{type:e.PropertyType.boolean,value:t}:"string"==typeof t?{type:e.PropertyType.string,value:t}:Ke(t)?{type:e.PropertyType.Quantity,value:t}:z(t)?{type:t.resourceType,value:t}:{type:e.PropertyType.BackboneElement,value:t}}function qe(e){return 0!==e.length&&!!e[0].value}function Fe(t,r){if(!t.value)return;const n=H(t.type,r);if(n){const e=function(e,t,r){const n=r.type;if(!n||0===n.length)return;let i,o="undefined";if(1===n.length)i=e.value[t],o=n[0].code;else for(const r of n){const n=t.replace("[x]","")+D(r.code);if(n in e.value){i=e.value[n],o=r.code;break}}if(w(i))return;"Element"!==o&&"BackboneElement"!==o||(o=q(r.path?.split(".")));return Array.isArray(i)?i.map((e=>Qe(e,o))):Qe(i,o)}(t,r,n);if(e)return e}return function(t,r){const n=t.value;if(!n||"object"!=typeof n)return;let i;if(r in n)i=n[r];else for(const t in e.PropertyType){const e=r+D(t);if(e in n){i=n[e];break}}if(w(i))return;return Array.isArray(i)?i.map($e):$e(i)}(t,r)}function Qe(e,t){return"Resource"===t&&z(e)&&(t=e.resourceType),{type:t,value:e}}function We(e){const t=[];for(const r of e){let e=!1;for(const n of t)if(qe(Ge(r,n))){e=!0;break}e||t.push(r)}return t}function He(e){return je(!qe(e))}function ze(e,t){return 0===e.length||0===t.length?[]:e.length!==t.length?je(!1):je(e.every(((e,r)=>qe(Ge(e,t[r])))))}function Ge(e,t){const r=e.value,n=t.value;return"number"==typeof r&&"number"==typeof n?je(Math.abs(r-n)<1e-8):Ke(r)&&Ke(n)?je(et(r,n)):je("object"==typeof r&&"object"==typeof n?tt(e,t):r===n)}function Ve(e,t){return 0===e.length&&0===t.length?je(!0):e.length!==t.length?je(!1):(e.sort(Xe),t.sort(Xe),je(e.every(((e,r)=>qe(Je(e,t[r]))))))}function Je(e,t){const r=e.value,n=t.value;return"number"==typeof r&&"number"==typeof n?je(Math.abs(r-n)<.01):Ke(r)&&Ke(n)?je(et(r,n)):je("object"==typeof r&&"object"==typeof n?tt(r,n):"string"==typeof r&&"string"==typeof n?r.toLowerCase()===n.toLowerCase():r===n)}function Xe(e,t){const r=e.value,n=t.value;return"number"==typeof r&&"number"==typeof n?r-n:"string"==typeof r&&"string"==typeof n?r.localeCompare(n):0}function Ye(e,t){const{value:r}=e;if(null==r)return!1;switch(t){case"Boolean":return"boolean"==typeof r;case"Decimal":case"Integer":return"number"==typeof r;case"Date":return"string"==typeof r&&!!r.match(/^\d{4}(-\d{2}(-\d{2})?)?/);case"DateTime":return"string"==typeof r&&!!r.match(/^\d{4}(-\d{2}(-\d{2})?)?T/);case"Time":return"string"==typeof r&&!!r.match(/^T\d/);case"Period":return Ze(r);case"Quantity":return Ke(r);default:return"object"==typeof r&&r?.resourceType===t}}function Ze(e){return!(!e||"object"!=typeof e||!("start"in e))}function Ke(e){return!(!e||"object"!=typeof e||!("value"in e)||"number"!=typeof e.value)}function et(e,t){return Math.abs(e.value-t.value)<.01&&(e.unit===t.unit||e.code===t.code||e.unit===t.code||e.code===t.unit)}function tt(e,t){const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(const n of r){const r=e[n],i=t[n];if(rt(r)&&rt(i)){if(!tt(r,i))return!1}else if(r!==i)return!1}return!0}function rt(e){return null!==e&&"object"==typeof e}const nt=()=>[],it={empty:(e,t)=>je(0===t.length),exists:(e,t,r)=>je(r?t.filter((t=>qe(r.eval(e,[t])))).length>0:t.length>0),all:(e,t,r)=>je(t.every((t=>qe(r.eval(e,[t]))))),allTrue:(e,t)=>{for(const e of t)if(!e.value)return je(!1);return je(!0)},anyTrue:(e,t)=>{for(const e of t)if(e.value)return je(!0);return je(!1)},allFalse:(e,t)=>{for(const e of t)if(e.value)return je(!1);return je(!0)},anyFalse:(e,t)=>{for(const e of t)if(!e.value)return je(!0);return je(!1)},subsetOf:nt,supersetOf:nt,count:(t,r)=>[{type:e.PropertyType.integer,value:r.length}],distinct:(e,t)=>{const r=[];for(const e of t)r.some((t=>t.value===e.value))||r.push(e);return r},isDistinct:(e,t)=>je(t.length===it.distinct(e,t).length),where:(e,t,r)=>t.filter((t=>qe(r.eval(e,[t])))),select:(e,t,r)=>t.map((t=>r.eval(e,[t]))).flat(),repeat:nt,ofType:(e,t,r)=>t.filter((e=>e.type===r.name)),single:(e,t)=>{if(t.length>1)throw new Error("Expected input length one for single()");return 0===t.length?[]:t.slice(0,1)},first:(e,t)=>0===t.length?[]:t.slice(0,1),last:(e,t)=>0===t.length?[]:t.slice(t.length-1,t.length),tail:(e,t)=>0===t.length?[]:t.slice(1,t.length),skip:(e,t,r)=>{const n=r.eval(e,t)[0]?.value;if("number"!=typeof n)throw new Error("Expected a number for skip(num)");return n>=t.length?[]:n<=0?t:t.slice(n,t.length)},take:(e,t,r)=>{const n=r.eval(e,t)[0]?.value;if("number"!=typeof n)throw new Error("Expected a number for take(num)");return n>=t.length?t:n<=0?[]:t.slice(0,n)},intersect:(e,t,r)=>{if(!r)return t;const n=r.eval(e,t),i=[];for(const e of t)!i.some((t=>t.value===e.value))&&n.some((t=>t.value===e.value))&&i.push(e);return i},exclude:(e,t,r)=>{if(!r)return t;const n=r.eval(e,t),i=[];for(const e of t)n.some((t=>t.value===e.value))||i.push(e);return i},union:(e,t,r)=>{if(!r)return t;const n=r.eval(e,t);return We([...t,...n])},combine:(e,t,r)=>{if(!r)return t;const n=r.eval(e,t);return[...t,...n]},iif:(e,t,r,n,i)=>{const o=r.eval(e,t);if(o.length>1||1===o.length&&"boolean"!=typeof o[0].value)throw new Error("Expected criterion to evaluate to a Boolean");return qe(o)?n.eval(e,t):i?i.eval(e,t):[]},toBoolean:(t,r)=>{if(0===r.length)return[];const[{value:n}]=at(r,1);if("boolean"==typeof n)return[{type:e.PropertyType.boolean,value:n}];if("number"==typeof n&&(0===n||1===n))return je(!!n);if("string"==typeof n){const e=n.toLowerCase();if(["true","t","yes","y","1","1.0"].includes(e))return je(!0);if(["false","f","no","n","0","0.0"].includes(e))return je(!1)}return[]},convertsToBoolean:(e,t)=>0===t.length?[]:je(1===it.toBoolean(e,t).length),toInteger:(t,r)=>{if(0===r.length)return[];const[{value:n}]=at(r,1);return"number"==typeof n?[{type:e.PropertyType.integer,value:n}]:"string"==typeof n&&n.match(/^[+-]?\d+$/)?[{type:e.PropertyType.integer,value:parseInt(n,10)}]:"boolean"==typeof n?[{type:e.PropertyType.integer,value:n?1:0}]:[]},convertsToInteger:(e,t)=>0===t.length?[]:je(1===it.toInteger(e,t).length),toDate:(t,r)=>{if(0===r.length)return[];const[{value:n}]=at(r,1);return"string"==typeof n&&n.match(/^\d{4}(-\d{2}(-\d{2})?)?/)?[{type:e.PropertyType.date,value:Be(n)}]:[]},convertsToDate:(e,t)=>0===t.length?[]:je(1===it.toDate(e,t).length),toDateTime:(t,r)=>{if(0===r.length)return[];const[{value:n}]=at(r,1);return"string"==typeof n&&n.match(/^\d{4}(-\d{2}(-\d{2})?)?/)?[{type:e.PropertyType.dateTime,value:Be(n)}]:[]},convertsToDateTime:(e,t)=>0===t.length?[]:je(1===it.toDateTime(e,t).length),toDecimal:(t,r)=>{if(0===r.length)return[];const[{value:n}]=at(r,1);return"number"==typeof n?[{type:e.PropertyType.decimal,value:n}]:"string"==typeof n&&n.match(/^-?\d{1,9}(\.\d{1,9})?$/)?[{type:e.PropertyType.decimal,value:parseFloat(n)}]:"boolean"==typeof n?[{type:e.PropertyType.decimal,value:n?1:0}]:[]},convertsToDecimal:(e,t)=>0===t.length?[]:je(1===it.toDecimal(e,t).length),toQuantity:(t,r)=>{if(0===r.length)return[];const[{value:n}]=at(r,1);return Ke(n)?[{type:e.PropertyType.Quantity,value:n}]:"number"==typeof n?[{type:e.PropertyType.Quantity,value:{value:n,unit:"1"}}]:"string"==typeof n&&n.match(/^-?\d{1,9}(\.\d{1,9})?/)?[{type:e.PropertyType.Quantity,value:{value:parseFloat(n),unit:"1"}}]:"boolean"==typeof n?[{type:e.PropertyType.Quantity,value:{value:n?1:0,unit:"1"}}]:[]},convertsToQuantity:(e,t)=>0===t.length?[]:je(1===it.toQuantity(e,t).length),toString:(t,r)=>{if(0===r.length)return[];const[{value:n}]=at(r,1);return null==n?[]:Ke(n)?[{type:e.PropertyType.string,value:`${n.value} '${n.unit}'`}]:[{type:e.PropertyType.string,value:n.toString()}]},convertsToString:(e,t)=>0===t.length?[]:je(1===it.toString(e,t).length),toTime:(t,r)=>{if(0===r.length)return[];const[{value:n}]=at(r,1);if("string"==typeof n){const t=n.match(/^T?(\d{2}(:\d{2}(:\d{2})?)?)/);if(t)return[{type:e.PropertyType.time,value:Be("T"+t[1])}]}return[]},convertsToTime:(e,t)=>0===t.length?[]:je(1===it.toTime(e,t).length),indexOf:(e,t,r)=>ot(((e,t)=>e.indexOf(t)),e,t,r),substring:(e,t,r,n)=>ot(((e,t,r)=>{const n=t,i=r?n+r:e.length;return n<0||n>=e.length?void 0:e.substring(n,i)}),e,t,r,n),startsWith:(e,t,r)=>ot(((e,t)=>e.startsWith(t)),e,t,r),endsWith:(e,t,r)=>ot(((e,t)=>e.endsWith(t)),e,t,r),contains:(e,t,r)=>ot(((e,t)=>e.includes(t)),e,t,r),upper:(e,t)=>ot((e=>e.toUpperCase()),e,t),lower:(e,t)=>ot((e=>e.toLowerCase()),e,t),replace:(e,t,r,n)=>ot(((e,t,r)=>e.replaceAll(t,r)),e,t,r,n),matches:(e,t,r)=>ot(((e,t)=>!!e.match(t)),e,t,r),replaceMatches:(e,t,r,n)=>ot(((e,t,r)=>e.replaceAll(t,r)),e,t,r,n),length:(e,t)=>ot((e=>e.length),e,t),toChars:(e,t)=>ot((e=>e?e.split(""):void 0),e,t),abs:(e,t)=>st(Math.abs,e,t),ceiling:(e,t)=>st(Math.ceil,e,t),exp:(e,t)=>st(Math.exp,e,t),floor:(e,t)=>st(Math.floor,e,t),ln:(e,t)=>st(Math.log,e,t),log:(e,t,r)=>st(((e,t)=>Math.log(e)/Math.log(t)),e,t,r),power:(e,t,r)=>st(Math.pow,e,t,r),round:(e,t)=>st(Math.round,e,t),sqrt:(e,t)=>st(Math.sqrt,e,t),truncate:(e,t)=>st((e=>0|e),e,t),children:nt,descendants:nt,trace:(e,t,r)=>(console.log("trace",t,r),t),now:()=>[{type:e.PropertyType.dateTime,value:(new Date).toISOString()}],timeOfDay:()=>[{type:e.PropertyType.time,value:(new Date).toISOString().substring(11)}],today:()=>[{type:e.PropertyType.date,value:(new Date).toISOString().substring(0,10)}],between:(t,r,n,i,o)=>{const s=it.toDateTime(t,n.eval(t,r));if(0===s.length)throw new Error("Invalid start date");const a=it.toDateTime(t,i.eval(t,r));if(0===a.length)throw new Error("Invalid end date");const c=o.eval(t,r)[0]?.value;if("years"!==c&&"months"!==c&&"days"!==c)throw new Error("Invalid units");const u=v(s[0].value,a[0].value);return[{type:e.PropertyType.Quantity,value:{value:u[c],unit:c}}]},is:(t,r,n)=>{let i="";return n instanceof pt?i=n.name:n instanceof vt&&(i=n.left.name+"."+n.right.name),i?r.map((t=>({type:e.PropertyType.boolean,value:Ye(t,i)}))):[]},not:(t,r)=>it.toBoolean(t,r).map((t=>({type:e.PropertyType.boolean,value:!t.value}))),resolve:(t,r)=>r.map((t=>{const r=t.value;let n;if("string"==typeof r)n=r;else if("object"==typeof r){const e=r;if(e.resource)return $e(e.resource);e.reference?n=e.reference:e.type&&e.identifier&&(n=`${e.type}?identifier=${e.identifier.system}|${e.identifier.value}`)}if(n?.includes("?")){const[e]=n.split("?");return{type:e,value:{resourceType:e}}}if(n?.includes("/")){const[e,t]=n.split("/");return{type:e,value:{resourceType:e,id:t}}}return{type:e.PropertyType.BackboneElement,value:void 0}})).filter((e=>!!e.value)),as:(e,t)=>t,type:(t,r)=>r.map((({value:t})=>"boolean"==typeof t?{type:e.PropertyType.BackboneElement,value:{namespace:"System",name:"Boolean"}}:"number"==typeof t?{type:e.PropertyType.BackboneElement,value:{namespace:"System",name:"Integer"}}:z(t)?{type:e.PropertyType.BackboneElement,value:{namespace:"FHIR",name:t.resourceType}}:{type:e.PropertyType.BackboneElement,value:null})),conformsTo:(t,r,n)=>{const i=n.eval(t,r)[0].value;if(!i.startsWith("http://hl7.org/fhir/StructureDefinition/"))throw new Error("Expected a StructureDefinition URL");const o=i.replace("http://hl7.org/fhir/StructureDefinition/","");return r.map((t=>({type:e.PropertyType.boolean,value:t.value?.resourceType===o})))}};function ot(e,t,r,...n){if(0===r.length)return[];const[{value:i}]=at(r,1);if("string"!=typeof i)throw new Error("String function cannot be called with non-string");const o=e(i,...n.map((e=>e?.eval(t,r)[0]?.value)));return void 0===o?[]:Array.isArray(o)?o.map($e):[$e(o)]}function st(t,r,n,...i){if(0===n.length)return[];const[{value:o}]=at(n,1),s=Ke(o),a=s?o.value:o;if("number"!=typeof a)throw new Error("Math function cannot be called with non-number");const c=t(a,...i.map((e=>e.eval(r,n)[0]?.value)));return[{type:s?e.PropertyType.Quantity:n[0].type,value:s?{...o,value:c}:c}]}function at(e,t){if(e.length!==t)throw new Error(`Expected ${t} arguments`);for(const t of e)if(null==t)throw new Error("Expected non-null argument");return e}class ct{constructor(e,t){this.original=e,this.child=t}eval(e,t){try{return t.length>0?t.map((t=>this.child.eval(e,[t]))).flat():this.child.eval(e,[])}catch(e){throw new Error(`FhirPathError on "${this.original}": ${e}`)}}toString(){return this.child.toString()}}class ut{constructor(e){this.value=e}eval(){return[this.value]}toString(){const e=this.value.value;return"string"==typeof e?`'${e}'`:e.toString()}}class pt{constructor(e){this.name=e}eval(e,t){if("$this"===this.name)return t;if(this.name.startsWith("%")){const t=e.variables[this.name.slice(1)];if(!t)throw new Error(`Undefined variable ${this.name}`);return[t]}return t.flatMap((e=>this.evalValue(e))).filter((e=>void 0!==e?.value))}evalValue(e){const t=e.value;if(t&&"object"==typeof t)return z(t)&&t.resourceType===this.name?e:Fe(e,this.name)}toString(){return this.name}}class dt{eval(){return[]}toString(){return"{}"}}class lt extends Ie{constructor(e,t,r){super(e,t),this.impl=r}eval(e,t){return this.impl(this.child.eval(e,t))}toString(){return this.child.toString()}}class ht extends Ue{constructor(e,t){super("as",e,t)}eval(e,t){return it.ofType(e,this.left.eval(e,t),this.right)}}class ft extends Ue{constructor(e,t,r,n){super(e,t,r),this.impl=n}eval(t,r){const n=this.left.eval(t,r);if(1!==n.length)return[];const i=this.right.eval(t,r);if(1!==i.length)return[];const o=n[0].value,s=i[0].value,a=Ke(o)?o.value:o,c=Ke(s)?s.value:s,u=this.impl(a,c);return"boolean"==typeof u?je(u):Ke(o)?[{type:e.PropertyType.Quantity,value:{...o,value:u}}]:[$e(u)]}}class yt extends Ue{constructor(e,t){super("&",e,t)}eval(t,r){const n=[...this.left.eval(t,r),...this.right.eval(t,r)];return n.length>0&&n.every((e=>"string"==typeof e.value))?[{type:e.PropertyType.string,value:n.map((e=>e.value)).join("")}]:n}}class mt extends Ue{constructor(e,t){super("contains",e,t)}eval(e,t){const r=this.left.eval(e,t),n=this.right.eval(e,t);return je(r.some((e=>e.value===n[0].value)))}}class gt extends Ue{constructor(e,t){super("in",e,t)}eval(e,t){const r=this.left.eval(e,t);return je(this.right.eval(e,t).some((e=>e.value===r[0].value)))}}class vt extends Ue{constructor(e,t){super(".",e,t)}eval(e,t){return this.right.eval(e,this.left.eval(e,t))}toString(){return`${this.left.toString()}.${this.right.toString()}`}}class xt extends Ue{constructor(e,t){super("|",e,t)}eval(e,t){return We([...this.left.eval(e,t),...this.right.eval(e,t)])}}class Tt extends Ue{constructor(e,t){super("=",e,t)}eval(e,t){return ze(this.left.eval(e,t),this.right.eval(e,t))}}class bt extends Ue{constructor(e,t){super("!=",e,t)}eval(e,t){return He(ze(this.left.eval(e,t),this.right.eval(e,t)))}}class St extends Ue{constructor(e,t){super("~",e,t)}eval(e,t){return Ve(this.left.eval(e,t),this.right.eval(e,t))}}class wt extends Ue{constructor(e,t){super("!~",e,t)}eval(e,t){return He(Ve(this.left.eval(e,t),this.right.eval(e,t)))}}class Et extends Ue{constructor(e,t){super("is",e,t)}eval(e,t){const r=this.left.eval(e,t);if(1!==r.length)return[];const n=this.right.name;return je(Ye(r[0],n))}}class Pt extends Ue{constructor(e,t){super("and",e,t)}eval(e,t){const r=this.left.eval(e,t),n=this.right.eval(e,t);return!0===r[0]?.value&&!0===n[0]?.value?je(!0):!1===r[0]?.value||!1===n[0]?.value?je(!1):[]}}class kt extends Ue{constructor(e,t){super("or",e,t)}eval(e,t){const r=this.left.eval(e,t);if(qe(r))return r;const n=this.right.eval(e,t);return qe(n)?n:[]}}class Ct extends Ue{constructor(e,t){super("xor",e,t)}eval(e,t){const r=this.left.eval(e,t),n=this.right.eval(e,t);if(0===r.length&&0===n.length)return[];const i=0===r.length?null:r[0].value,o=0===n.length?null:n[0].value;return!0===i&&!0!==o||!0!==i&&!0===o?je(!0):!0===i&&!0===o||!1===i&&!1===o?je(!1):[]}}class At{constructor(e,t){this.name=e,this.args=t}eval(e,t){const r=it[this.name];if(!r)throw new Error("Unrecognized function: "+this.name);return r(e,t,...this.args)}toString(){return`${this.name}(${this.args.map((e=>e.toString())).join(", ")})`}}class Rt{constructor(e,t){this.left=e,this.expr=t}eval(e,t){const r=this.expr.eval(e,t);if(1!==r.length)return[];const n=r[0].value;if("number"!=typeof n)throw new Error("Invalid indexer expression: should return integer}");const i=this.left.eval(e,t);return n in i?[i[n]]:[]}toString(){return`${this.left.toString()}[${this.expr.toString()}]`}}const Dt=["true","false"],Ot=["!=","!~","<=",">=","{}","->"];function It(e){return new _e(e,Dt,Ot).tokenize()}const Ut={parse(e){const t=e.consumeAndParse();if(!e.match(")"))throw new Error("Parse error: expected `)` got `"+e.peek()?.value+"`");return t}},Nt={parse(e,t){const r=e.consumeAndParse();if(!e.match("]"))throw new Error("Parse error: expected `]`");return new Rt(t,r)},precedence:2},Lt={parse(e,t){if(!(t instanceof pt))throw new Error("Unexpected parentheses");const r=[];for(;!e.match(")");)r.push(e.consumeAndParse()),e.match(",");return new At(t.name,r)},precedence:0};function Mt(e){const t=e.split(" "),r=parseFloat(t[0]);let n=t[1];return n=n?.startsWith("'")&&n.endsWith("'")?n.substring(1,n.length-1):"{"+n+"}",{value:r,unit:n}}function _t(){return(new Ne).registerPrefix("String",{parse:(t,r)=>new ut({type:e.PropertyType.string,value:r.value})}).registerPrefix("DateTime",{parse:(t,r)=>new ut({type:e.PropertyType.dateTime,value:Be(r.value)})}).registerPrefix("Quantity",{parse:(t,r)=>new ut({type:e.PropertyType.Quantity,value:Mt(r.value)})}).registerPrefix("Number",{parse:(t,r)=>new ut({type:e.PropertyType.decimal,value:parseFloat(r.value)})}).registerPrefix("true",{parse:()=>new ut({type:e.PropertyType.boolean,value:!0})}).registerPrefix("false",{parse:()=>new ut({type:e.PropertyType.boolean,value:!1})}).registerPrefix("Symbol",{parse:(e,t)=>new pt(t.value)}).registerPrefix("{}",{parse:()=>new dt}).registerPrefix("(",Ut).registerInfix("[",Nt).registerInfix("(",Lt).prefix("+",3,((e,t)=>new lt("+",t,(e=>e)))).prefix("-",3,((e,t)=>new ft("-",t,t,((e,t)=>-t)))).infixLeft(".",1,((e,t,r)=>new vt(e,r))).infixLeft("/",4,((e,t,r)=>new ft("/",e,r,((e,t)=>e/t)))).infixLeft("*",4,((e,t,r)=>new ft("*",e,r,((e,t)=>e*t)))).infixLeft("+",5,((e,t,r)=>new ft("+",e,r,((e,t)=>e+t)))).infixLeft("-",5,((e,t,r)=>new ft("-",e,r,((e,t)=>e-t)))).infixLeft("|",7,((e,t,r)=>new xt(e,r))).infixLeft("=",9,((e,t,r)=>new Tt(e,r))).infixLeft("!=",9,((e,t,r)=>new bt(e,r))).infixLeft("~",9,((e,t,r)=>new St(e,r))).infixLeft("!~",9,((e,t,r)=>new wt(e,r))).infixLeft("<",8,((e,t,r)=>new ft("<",e,r,((e,t)=>e<t)))).infixLeft("<=",8,((e,t,r)=>new ft("<=",e,r,((e,t)=>e<=t)))).infixLeft(">",8,((e,t,r)=>new ft(">",e,r,((e,t)=>e>t)))).infixLeft(">=",8,((e,t,r)=>new ft(">=",e,r,((e,t)=>e>=t)))).infixLeft("&",5,((e,t,r)=>new yt(e,r))).infixLeft("and",6,((e,t,r)=>new Pt(e,r))).infixLeft("as",6,((e,t,r)=>new ht(e,r))).infixLeft("contains",6,((e,t,r)=>new mt(e,r))).infixLeft("div",6,((e,t,r)=>new ft("div",e,r,((e,t)=>e/t|0)))).infixLeft("in",6,((e,t,r)=>new gt(e,r))).infixLeft("is",6,((e,t,r)=>new Et(e,r))).infixLeft("mod",6,((e,t,r)=>new ft("mod",e,r,((e,t)=>e%t)))).infixLeft("or",6,((e,t,r)=>new kt(e,r))).infixLeft("xor",6,((e,t,r)=>new Ct(e,r)))}const Bt=_t();function jt(e){return new ct(e,Bt.construct(It(e)).consumeAndParse())}function $t(e,t){const r=Array.isArray(t)?t:[t];for(let e=0;e<r.length;e++){const t=r[e];"object"==typeof t&&"type"in t&&"value"in t||(r[e]=$e(r[e]))}return qt(e,r).map((e=>e.value))}function qt(e,t,r){const n=r||{};return jt(e).eval({variables:n},t)}var Ft;function Qt(t,r){let n=G.types[t].searchParamsDetails?.[r.code];return n||(n=function(t,r){const n=r.code,i=function(e){return e.split("-").reduce(((e,t,r)=>e+(r?D(t):t)),"")}(n),o=Ht(t,r.expression)?.split(".");if(!o)return{columnName:i,type:e.SearchParameterType.TEXT};let s,a,c=t,u=!1;for(let e=1;e<o.length;e++){let n=o[e],i=!1;const p=/\[\d+\]$/.exec(n);if(p&&(n=n.substring(0,n.length-p[0].length),i=!0),s=H(c,n),!s)throw new Error(`Element definition not found for ${t} ${r.code}`);"0"===s.max||"1"===s.max||i||(u=!0),a=s.type?.[0].code,e<o.length-1&&(c=Wt(a)?q(s.path?.split(".")):a)}const p=function(t,r){switch(t.type){case"date":return r===e.PropertyType.date?e.SearchParameterType.DATE:e.SearchParameterType.DATETIME;case"number":return e.SearchParameterType.NUMBER;case"quantity":return e.SearchParameterType.QUANTITY;case"reference":return r===e.PropertyType.canonical?e.SearchParameterType.CANONICAL:e.SearchParameterType.REFERENCE;case"token":return r===e.PropertyType.boolean?e.SearchParameterType.BOOLEAN:e.SearchParameterType.TEXT;default:return e.SearchParameterType.TEXT}}(r,a),d={columnName:i,type:p,elementDefinition:s,array:u};return function(e,t,r){const n=G.types[e];n.searchParamsDetails||(n.searchParamsDetails={});n.searchParamsDetails[t]=r}(t,n,d),d}(t,r)),n}function Wt(e){return"Element"===e||"BackboneElement"===e}function Ht(e,t){const r=t.split(" | ");for(const t of r){if((n=t).includes(" as Period")||n.includes(" as SampledDate"))continue;const r=zt(t);if(r.startsWith(e+"."))return r}var n}function zt(e){let t=e.trim();t.startsWith("(")&&t.endsWith(")")&&(t=t.substring(1,t.length-1));const r=[" != "," as ",".as(",".exists(",".resolve(",".where("];for(const e of r)t.includes(e)&&(t=t.substring(0,t.indexOf(e)));return t}function Gt(e,t){if(t.resourceType!==e.resourceType)return!1;if(t.filters)for(const r of t.filters)if(!Vt(e,t,r))return!1;return!0}function Vt(t,r,n){const i=G.types[r.resourceType].searchParams?.[n.code];switch(i?.type){case"reference":return function(t,r,n){const i=$t(n.expression,t),o=Zt(r.operator);if(""===r.value&&0===i.length)return r.operator===e.Operator.EQUALS;const s=i.map((e=>"string"==typeof e?e:e.reference));for(const e of r.value.split(",")){let t=s.includes(e);if(t||"_compartment"!==r.code||(t=s.some((t=>t?.endsWith("/"+e)))),t)return!o}return o}(t,n,i);case"string":case"uri":return Jt(t,n,i);case"token":return function(t,r,n){const i=Qt(t.resourceType,n);return i.type===e.SearchParameterType.BOOLEAN?function(e,t,r){const n=$t(r.expression,e),i="true"===t.value,o=n.includes(i);return Zt(t.operator)?!o:o}(t,r,n):Jt(t,r,n,!0)}(t,n,i);case"date":return function(e,t,r){const n=$t(r.expression,e),i=t.value.split(","),o=Zt(t.operator);for(const e of n)for(const r of i){if(Yt(e,t.operator,r))return!o}return o}(t,n,i);default:return!1}}function Jt(e,t,r,n){const i=$t(r.expression,e),o=t.value.split(","),s=Zt(t.operator);for(const e of i)for(const r of o){if(Xt(e,t.operator,r,n))return!s}return s}function Xt(e,t,r,n){if(n&&r.includes("|")){const[n,i]=r.split("|");return Xt(e,t,n,!1)&&(!i||Xt(e,t,i,!1))}let i="";return e&&("string"==typeof e?i=e:"object"==typeof e&&(i=JSON.stringify(e))),i.toLowerCase().includes(r.toLowerCase())}function Yt(t,r,n){switch(r){case e.Operator.STARTS_AFTER:case e.Operator.GREATER_THAN:return t>n;case e.Operator.GREATER_THAN_OR_EQUALS:return t>=n;case e.Operator.ENDS_BEFORE:case e.Operator.LESS_THAN:return t<n;case e.Operator.LESS_THAN_OR_EQUALS:return t<=n;case e.Operator.EQUALS:case e.Operator.NOT_EQUALS:return t===n;default:return!1}}function Zt(t){return t===e.Operator.NOT_EQUALS||t===e.Operator.NOT}e.SearchParameterType=void 0,(Ft=e.SearchParameterType||(e.SearchParameterType={})).BOOLEAN="BOOLEAN",Ft.NUMBER="NUMBER",Ft.QUANTITY="QUANTITY",Ft.TEXT="TEXT",Ft.REFERENCE="REFERENCE",Ft.CANONICAL="CANONICAL",Ft.DATE="DATE",Ft.DATETIME="DATETIME",Ft.PERIOD="PERIOD",Ft.UUID="UUID";const Kt=["CapabilityStatement","CompartmentDefinition","ImplementationGuide","OperationDefinition","SearchParameter","StructureDefinition"],er=["DomainConfiguration","JsonWebKey","Login","User"],tr=["PasswordChangeRequest","Project","ProjectMembership"];function rr(e,t){if(er.includes(t))return!1;if(Kt.includes(t))return!1;if(e.resource)for(const r of e.resource)if(or(r.resourceType,t)&&!r.readonly)return!0;return!1}function nr(e,t,r){if(e.resource)for(const n of e.resource)if(ir(t,n,r))return!0;return!1}function ir(e,t,r){const n=e.resourceType;return!!or(t.resourceType,n)&&(!(!r&&t.readonly)&&(!(t.compartment&&!e.meta?.compartment?.find((e=>e.reference===t.compartment?.reference)))&&!(t.criteria&&!Gt(e,Pe(t.criteria)))))}function or(e,t){return e===t||"*"===e&&!tr.includes(t)}function sr(e){if("undefined"!=typeof window)return window.atob(e);if("undefined"!=typeof Buffer)return Buffer.from(e,"base64").toString("binary");throw new Error("Unable to decode base64")}function ar(e){if("undefined"!=typeof window)return window.btoa(e);if("undefined"!=typeof Buffer)return Buffer.from(e,"binary").toString("base64");throw new Error("Unable to encode base64")}function cr(e,t){return"reference"===e&&"string"==typeof t&&t.includes("/")?"urn:uuid:"+t.split("/")[1]:t}class ur{constructor(e=10){this.max=e,this.cache=new Map}clear(){this.cache.clear()}get(e){const t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){this.cache.has(e)?this.cache.delete(e):this.cache.size>=this.max&&this.cache.delete(this.first()),this.cache.set(e,t)}delete(e){this.cache.delete(e)}keys(){return this.cache.keys()}first(){return this.cache.keys().next().value}}function pr(){const e=new Uint32Array(28);return crypto.getRandomValues(e),A(e.buffer)}class dr{constructor(){this.listeners={}}addEventListener(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)}removeEventListeneer(e,t){const r=this.listeners[e];if(r)for(let e=0;e<r.length;e++)if(r[e]===t)return void r.splice(e,1)}dispatchEvent(e){const t=this.listeners[e.type];return t&&t.forEach((t=>t.call(this,e))),!e.defaultPrevented}}function lr(e){const[t,r,n]=e.split(".");return function(e){const t=sr(e.replace(/-/g,"+").replace(/_/g,"/")),r=Array.from(t).reduce(((e,t)=>`${e}%${("00"+t.charCodeAt(0).toString(16)).slice(-2)}`),""),n=decodeURIComponent(r);return JSON.parse(n)}(r)}var hr;class fr{constructor(e){this[hr]="ReadablePromise",this.status="pending",this.suspender=e.then((e=>(this.status="success",this.response=e,e)),(e=>{throw this.status="error",this.error=e,e}))}isPending(){return"pending"===this.status}isOk(){return"success"===this.status}read(){switch(this.status){case"pending":throw this.suspender;case"error":throw this.error;default:return this.response}}then(e,t){return this.suspender.then(e,t)}catch(e){return this.suspender.catch(e)}finally(e){return this.suspender.finally(e)}}hr=Symbol.toStringTag;class yr{constructor(){this.storage="undefined"!=typeof localStorage?localStorage:new mr}clear(){this.storage.clear()}getString(e){return this.storage.getItem(e)||void 0}setString(e,t){t?this.storage.setItem(e,t):this.storage.removeItem(e)}getObject(e){const t=this.getString(e);return t?JSON.parse(t):void 0}setObject(e,t){this.setString(e,t?b(t):void 0)}}class mr{constructor(){this.data=new Map}get length(){return this.data.size}clear(){this.data.clear()}getItem(e){return this.data.get(e)??null}setItem(e,t){t?this.data.set(e,t):this.data.delete(e)}removeItem(e){this.data.delete(e)}key(e){return Array.from(this.data.keys())[e]}}const gr="application/fhir+json",vr={resourceType:"Device",id:"system",deviceName:[{name:"System"}]};var xr,Tr;e.OAuthGrantType=void 0,(xr=e.OAuthGrantType||(e.OAuthGrantType={})).ClientCredentials="client_credentials",xr.AuthorizationCode="authorization_code",xr.RefreshToken="refresh_token",xr.TokenExchange="urn:ietf:params:oauth:grant-type:token-exchange",e.OAuthTokenType=void 0,(Tr=e.OAuthTokenType||(e.OAuthTokenType={})).AccessToken="urn:ietf:params:oauth:token-type:access_token",Tr.RefreshToken="urn:ietf:params:oauth:token-type:refresh_token",Tr.IdToken="urn:ietf:params:oauth:token-type:id_token",Tr.Saml1Token="urn:ietf:params:oauth:token-type:saml1",Tr.Saml2Token="urn:ietf:params:oauth:token-type:saml2";function br(){return"undefined"==typeof window?"":window.location.protocol+"//"+window.location.host+"/"}function Sr(e){return e?e.endsWith("/")?e:e+"/":e}const wr=[...Ot,"->","<<",">>"];class Er{constructor(e){this.parser=e,this.structureMap={resourceType:"StructureMap"}}parse(){for(this.parser.consume("Symbol","map"),this.structureMap.url=this.parser.consume("String").value,this.parser.consume("="),this.structureMap.name=this.parser.consume().value;this.parser.hasMore();){const e=this.parser.peek()?.value;switch(e){case"uses":this.parseUses();break;case"imports":this.parseImport();break;case"group":this.parseGroup();break;case"conceptmap":this.parseConceptMap();break;default:throw new Error(`Unexpected token: ${e}`)}}return this.structureMap}parseUses(){this.parser.consume("Symbol","uses");const e={};e.url=this.parser.consume("String").value,"alias"===this.parser.peek()?.value&&(this.parser.consume("Symbol","alias"),e.alias=this.parser.consume("Symbol").value),this.parser.consume("Symbol","as"),e.mode=this.parser.consume().value,this.structureMap.structure||(this.structureMap.structure=[]),this.structureMap.structure.push(e)}parseImport(){this.parser.consume("Symbol","imports"),this.structureMap.import||(this.structureMap.import=[]),this.structureMap.import.push(this.parser.consume("String").value)}parseGroup(){const e={};this.parser.consume("Symbol","group"),e.name=this.parser.consume("Symbol").value,e.input=this.parseParameters(),"extends"===this.parser.peek()?.value&&(this.parser.consume("Symbol","extends"),e.extends=this.parser.consume("Symbol").value),"<<"===this.parser.peek()?.value?(this.parser.consume("<<"),e.typeMode=this.parser.consume().value,"+"===this.parser.peek()?.value&&(this.parser.consume("+"),e.typeMode="type-and-types"),this.parser.consume(">>")):e.typeMode="none",e.rule=this.parseRules(),this.structureMap.group||(this.structureMap.group=[]),this.structureMap.group.push(e)}parseParameters(){const e=[];for(this.parser.consume("(");this.parser.hasMore()&&")"!==this.parser.peek()?.value;)e.push(this.parseParameter()),","===this.parser.peek()?.value&&this.parser.consume(",");return this.parser.consume(")"),e}parseParameter(){const e={};return e.mode=this.parser.consume().value,e.name=this.parser.consume("Symbol").value,":"===this.parser.peek()?.value&&(this.parser.consume(":"),e.type=this.parser.consume("Symbol").value),e}parseRules(){const e=[];for(this.parser.consume("{");this.parser.hasMore()&&"}"!==this.parser.peek()?.value;)e.push(this.parseRule());return this.parser.consume("}"),e}parseRule(){const e={source:this.parseRuleSources()};return"->"===this.parser.peek()?.value&&(this.parser.consume("->"),e.target=this.parseRuleTargets()),"then"===this.parser.peek()?.value&&(this.parser.consume("Symbol","then"),"{"===this.parser.peek()?.id?e.rule=this.parseRules():e.dependent=this.parseRuleDependents()),"String"===this.parser.peek()?.id?e.name=this.parser.consume().value:e.name=e.source?.[0]?.element,this.parser.consume(";"),e}parseRuleSources(){const e=[this.parseRuleSource()];for(;this.parser.hasMore()&&","===this.parser.peek()?.value;)this.parser.consume(","),e.push(this.parseRuleSource());return e}parseRuleSource(){const e={},t=this.parseRuleContext();if(t.includes(".")){const r=t.split(".");e.context=r[0],e.element=r[1]}else e.context=t;if(this.parser.hasMore()&&":"===this.parser.peek()?.value&&(this.parser.consume(":"),e.type=this.parser.consume().value),this.parser.hasMore()&&"default"===this.parser.peek()?.value&&(this.parser.consume("default"),this.parser.consumeAndParse()),"first"!==this.parser.peek()?.value&&"not_first"!==this.parser.peek()?.value&&"last"!==this.parser.peek()?.value&&"not_last"!==this.parser.peek()?.value&&"only_one"!==this.parser.peek()?.value||(e.listMode=this.parser.consume().value),"as"===this.parser.peek()?.value&&(this.parser.consume("Symbol","as"),e.variable=this.parser.consume().value),"where"===this.parser.peek()?.value){this.parser.consume("Symbol","where");const t=this.parser.consumeAndParse(100);e.condition=t.toString()}if("check"===this.parser.peek()?.value){this.parser.consume("Symbol","check");const t=this.parser.consumeAndParse(100);e.check=t.toString()}return e}parseRuleTargets(){const e=[this.parseRuleTarget()];for(;this.parser.hasMore()&&","===this.parser.peek()?.value;)this.parser.consume(","),e.push(this.parseRuleTarget());return e}parseRuleTarget(){const e={},t=this.parseRuleContext();if(t.includes(".")){const r=t.split(".");e.contextType="variable",e.context=r[0],e.element=r[1]}else e.context=t;return"="===this.parser.peek()?.value&&(this.parser.consume("="),this.parseRuleTargetTransform(e)),"as"===this.parser.peek()?.value&&(this.parser.consume("Symbol","as"),e.variable=this.parser.consume().value),"first"!==this.parser.peek()?.value&&"share"!==this.parser.peek()?.value&&"last"!==this.parser.peek()?.value&&"collate"!==this.parser.peek()?.value||(e.listMode=[this.parser.consume().value]),e}parseRuleTargetTransform(e){e.transform="copy";const t=this.parser.consumeAndParse(6);if(t instanceof pt)this.parseRuleTargetSymbol(e,t);else if(t instanceof At)this.parseRuleTargetFunction(e,t);else{if(!(t instanceof ut))throw new Error(`Unexpected FHIRPath: ${t}`);this.parseRuleTargetLiteral(e,t)}}parseRuleTargetSymbol(e,t){e.parameter=[{valueId:t.name}]}parseRuleTargetFunction(e,t){const r=t.name;switch(r){case"create":e.parameter=[{valueString:t.args[0].value.value}];break;case"translate":e.parameter=[{}];break;default:throw new Error("Unknown target function: "+r)}}parseRuleTargetLiteral(e,t){switch(t.value.type){case"boolean":e.parameter=[{valueBoolean:t.value.value}];break;case"decimal":e.parameter=[{valueDecimal:t.value.value}];break;case"string":e.parameter=[{valueString:t.value.value}];break;default:throw new Error("Unknown target literal type: "+t.value.type)}}parseRuleContext(){let e=this.parser.consume().value;for(;"."===this.parser.peek()?.value;)this.parser.consume("."),e+="."+this.parser.consume().value;return e}parseRuleDependents(){const e=this.parser.consumeAndParse(100);return[{name:e.name,variable:e.args.map((e=>e.name))}]}parseConceptMap(){for(;"}"!==this.parser.peek()?.value;)this.parser.consume();this.parser.consume("}")}}const Pr=_t().registerInfix("->",{precedence:100}).registerInfix(";",{precedence:200});const kr=[...Ot,"eq","ne","co"];class Cr{constructor(e,t,r){this.path=e,this.operator=t,this.value=r}}class Ar{constructor(e){this.child=e}}class Rr{constructor(e,t,r){this.keyword=e,this.left=t,this.right=r}}const Dr={eq:e.Operator.EQUALS,ne:e.Operator.NOT_EQUALS,co:e.Operator.CONTAINS,sw:void 0,ew:void 0,gt:e.Operator.GREATER_THAN,lt:e.Operator.LESS_THAN,ge:e.Operator.GREATER_THAN_OR_EQUALS,le:e.Operator.LESS_THAN_OR_EQUALS,ap:e.Operator.APPROXIMATELY,sa:e.Operator.STARTS_AFTER,eb:e.Operator.ENDS_BEFORE,pr:e.Operator.MISSING,po:void 0,ss:void 0,sb:void 0,in:e.Operator.IN,ni:e.Operator.NOT_IN,re:void 0,identifier:e.Operator.IDENTIFIER};class Or{constructor(e){this.parser=e}parse(){let e;"("===this.parser.peek()?.value?(this.parser.consume("("),e=this.parse(),this.parser.consume(")")):"not"===this.parser.peek()?.value?(this.parser.consume("Symbol","not"),this.parser.consume("("),e=new Ar(this.parse()),this.parser.consume(")")):e=new Cr(this.parser.consume("Symbol").value,function(e){const t=Dr[e];if(!t)throw new me(de("Invalid operator: "+e));return t}(this.parser.consume("Symbol").value),this.parser.consume().value);const t=this.parser.peek()?.value;return"and"===t||"or"===t?(this.parser.consume("Symbol",t),new Rr(t,e,this.parse())):e}}const Ir=_t();class Ur{constructor(e="\r",t="|",r="^",n="~",i="\\",o="&"){this.segmentSeparator=e,this.fieldSeparator=t,this.componentSeparator=r,this.repetitionSeparator=n,this.escapeCharacter=i,this.subcomponentSeparator=o}getMsh2(){return this.fieldSeparator+this.componentSeparator+this.repetitionSeparator+this.escapeCharacter+this.subcomponentSeparator}}class Nr{constructor(e,t=new Ur){this.context=t,this.segments=e}get(e){return"number"==typeof e?this.segments[e]:this.segments.find((t=>t.name===e))}getAll(e){return this.segments.filter((t=>t.name===e))}toString(){return this.segments.map((e=>e.toString())).join(this.context.segmentSeparator)}buildAck(){const e=new Date,t=this.get("MSH"),r=t?.get(2)?.toString()||"",n=t?.get(3)?.toString()||"",i=t?.get(4)?.toString()||"",o=t?.get(5)?.toString()||"",s=t?.get(9)?.toString()||"",a=t?.get(12)?.toString()||"2.5.1";return new Nr([new Lr(["MSH",this.context.getMsh2(),i,o,r,n,e.toISOString(),"","ACK",e.getTime().toString(),"P",a],this.context),new Lr(["MSA","AA",s,"OK"],this.context)])}static parse(e){if(!e.startsWith("MSH")){const e=new Error("Invalid HL7 message");throw e.type="entity.parse.failed",e}const t=new Ur("\r",e.charAt(3),e.charAt(4),e.charAt(5),e.charAt(6),e.charAt(7));return new Nr(e.split(/[\r\n]+/).map((e=>Lr.parse(e,t))),t)}}class Lr{constructor(e,t=new Ur){this.context=t,k(e)?this.fields=e.map((e=>Mr.parse(e))):this.fields=e,this.name=this.fields[0].components[0][0]}get(e){return this.fields[e]}toString(){return this.fields.map((e=>e.toString())).join(this.context.fieldSeparator)}static parse(e,t=new Ur){return new Lr(e.split(t.fieldSeparator).map((e=>Mr.parse(e,t))),t)}}class Mr{constructor(e,t=new Ur){this.context=t,this.components=e}get(e,t,r=0){let n=this.components[r][e]||"";return void 0!==t&&(n=n.split(this.context.subcomponentSeparator)[t]||""),n}toString(){return this.components.map((e=>e.join(this.context.componentSeparator))).join(this.context.repetitionSeparator)}static parse(e,t=new Ur){return new Mr(e.split(t.repetitionSeparator).map((e=>e.split(t.componentSeparator))),t)}}function _r(e){return e.toString().padStart(2,"0")}const Br={base64Binary:"string",boolean:"boolean",canonical:"string",code:"string",date:"string",dateTime:"string",decimal:"number",id:"string",instant:"string",integer:"number",markdown:"string",oid:"string",positiveInt:"number",string:"string",time:"string",unsignedInt:"number",uri:"string",url:"string",uuid:"string",xhtml:"string","http://hl7.org/fhirpath/System.String":"string"},jr=new Set(["resourceType","id","meta","implicitRules","language","text","contained","extension","modifierExtension"]);function $r(e){const t=G.types[e];return t&&t.structureDefinition.id===e&&"resource"===t.structureDefinition.kind}class qr{constructor(e){this.issues=[],this.root=e}validate(){const e=this.root;if(!e)throw new me(le("Resource is null"));const t=e.resourceType;if(!t)throw new me(le("Missing resource type"));if(Fr(e,"",this.issues),this.validateObject($e(e),t),this.issues.length>0)throw new me({resourceType:"OperationOutcome",issue:this.issues})}validateObject(e,t){const r=G.types[e.type];if(!r)throw new me(le("Unknown type: "+e.type));const n=r.properties;this.checkProperties(t,n,e),this.checkAdditionalProperties(t,e,n)}checkProperties(e,t,r){for(const[n,i]of Object.entries(t))this.checkProperty(e+"."+n,i,r)}checkProperty(e,t,r){const n=Fe(r,e.split(".").pop());if(w(n))void 0!==t.min&&t.min>0&&this.issues.push(Qr(e,"Missing required property"));else if("*"===t.max){if(!Array.isArray(n))return void this.issues.push(Qr(e,"Expected array for property"));for(const r of n)this.checkPropertyValue(e,t,r)}else{if(Array.isArray(n))return void this.issues.push(Qr(e,"Expected single value for property"));this.checkPropertyValue(e,t,n)}}checkPropertyValue(e,t,r){null!==r.value&&(O(r.type.charAt(0))?this.validatePrimitiveType(t,r):this.validateObject(r,e))}validatePrimitiveType(e,t){const{type:r,value:n}=t;if(null===n)return;const i=Br[t.type];typeof n===i?"string"===i?this.validateString(e,r,n):"number"===i&&this.validateNumber(e,r,n):this.createIssue(e,"Invalid type for "+r)}validateString(e,t,r){if(!r.trim())return void this.createIssue(e,"Invalid empty string");const n=G.types[t]?.properties.value;if(n?.type){const i=T(n.type[0],"http://hl7.org/fhir/StructureDefinition/regex");i&&(r.match(new RegExp(i))||this.createIssue(e,"Invalid "+t+" format"))}}validateNumber(t,r,n){var i;!isNaN(n)&&isFinite(n)?((i=r)!==e.PropertyType.integer&&i!==e.PropertyType.positiveInt&&i!==e.PropertyType.unsignedInt||Number.isInteger(n)||this.createIssue(t,"Number is not an integer"),r===e.PropertyType.positiveInt&&n<=0&&this.createIssue(t,"Number is less than or equal to zero"),r===e.PropertyType.unsignedInt&&n<0&&this.createIssue(t,"Number is negative")):this.createIssue(t,"Invalid "+r+" value")}checkAdditionalProperties(e,t,r){const n=t.value;for(const i of Object.keys(n))this.checkAdditionalProperty(e,i,t,r)}checkAdditionalProperty(e,t,r,n){if(!(jr.has(t)||t in n||function(e,t,r){for(const n of Object.keys(r)){if(!n.endsWith("[x]"))continue;const r=n.replace("[x]","");if(!e.startsWith(r))continue;let i=Fe(t,n);if(i&&(Array.isArray(i)&&(i=i[0]),i&&e===r+D(i.type)))return!0}return!1}(t,r,n)||this.checkPrimitiveElement(e,t,r))){const r=`${e}.${t}`;this.issues.push(Qr(r,`Invalid additional property "${r}"`))}}checkPrimitiveElement(e,t,r){if(!t.startsWith("_"))return!1;return t.slice(1)in r.value&&(this.validateObject({type:"Element",value:r.value[t]},e),!0)}createIssue(e,t){this.issues.push(Qr(e.path,t))}}function Fr(e,t,r){null===e?r.push(Qr(t,"Invalid null value")):Array.isArray(e)?function(e,t,r){for(let n=0;n<e.length;n++)void 0===e[n]?r.push(Qr(`${t}[${n}]`,"Invalid undefined value")):Fr(e[n],`${t}[${n}]`,r)}(e,t,r):"object"==typeof e&&function(e,t,r){for(const[n,i]of Object.entries(e))Fr(i,`${t}${t?".":""}${n}`,r)}(e,t,r)}function Qr(e,t){return{severity:"error",code:"structure",details:{text:t},expression:[e]}}function Wr(e){return new Gr(e).parse()}const Hr=Object.create(null);function zr(e){const t=Hr[e];if(!t)throw new me(he(Error("Unknown data type: "+e)));return t}class Gr{constructor(e){if(!e.snapshot?.element||0===e.snapshot.element.length)throw new Error(`No snapshot defined for StructureDefinition '${e.name}'`);const t=e.snapshot.element[0];this.elements=e.snapshot.element.slice(1),this.elementIndex=Object.create(null),this.index=0,this.resourceSchema={name:e.type,fields:{},constraints:this.parseFieldDefinition(t).constraints,innerTypes:[]},this.innerTypes=[]}parse(){let e=this.next();for(;e;){if(e.sliceName)this.parseSliceStart(e);else if(e.id?.includes(":")){if(this.slicingContext?.current){const t=Jr(e,this.slicingContext.path);this.slicingContext.current.fields[t]=this.parseFieldDefinition(e)}}else{const t=this.parseFieldDefinition(e);this.checkFieldEnter(e,t),this.backboneContext&&e.path?.startsWith(this.backboneContext.path+".")?this.backboneContext.type.fields[Jr(e,this.backboneContext.path)]=t:this.backboneContext?.parent&&e.path?.startsWith(this.backboneContext.parent.path+".")?this.backboneContext.parent.type.fields[Jr(e,this.backboneContext.parent.path)]=t:this.resourceSchema.fields[Jr(e,this.resourceSchema.name)]=t,this.checkFieldExit(e)}e=this.next()}return this.checkFieldExit(),this.innerTypes.length>0&&(this.resourceSchema.innerTypes=this.innerTypes),this.resourceSchema}checkFieldEnter(e,t){if(this.isInnerType(e)){for(;this.backboneContext&&!Xr(this.backboneContext?.path,e.path);)this.innerTypes.push(this.backboneContext.type),this.backboneContext=this.backboneContext.parent;this.backboneContext={type:{name:Yr(e.path?.split(".")??[]),fields:{},constraints:this.parseFieldDefinition(e).constraints,innerTypes:[]},path:e.path??"",parent:Xr(this.backboneContext?.path,e.path)?this.backboneContext:this.backboneContext?.parent}}e.slicing&&!this.slicingContext&&(t.slicing={discriminator:(e.slicing?.discriminator??[]).map((e=>({path:e.path,type:e.type}))),slices:[],ordered:e.slicing?.ordered??!1,rule:e.slicing?.rules},this.slicingContext={field:t.slicing,path:e.path??""})}checkFieldExit(e=void 0){if(this.backboneContext&&!Xr(this.backboneContext.path,e?.path))if(this.backboneContext.parent)do{this.innerTypes.push(this.backboneContext.type),this.backboneContext=this.backboneContext.parent}while(this.backboneContext&&!Xr(this.backboneContext.path,e?.path));else this.innerTypes.push(this.backboneContext.type),delete this.backboneContext;this.slicingContext&&!Xr(this.slicingContext.path,e?.path)&&(this.slicingContext?.current&&this.slicingContext.field.slices.push(this.slicingContext.current),delete this.slicingContext)}next(){const e=this.peek();if(e)return this.index++,e}peek(){const e=this.elements[this.index];if(e){if(this.elementIndex[e.path??""]=e,e.contentReference){const t=this.elementIndex[e.contentReference.slice(e.contentReference.indexOf("#")+1)];if(!t)return;return{...t,id:e.id,path:e.path}}return e}}isInnerType(e){const t=this.peek();return!(!Xr(e?.path,t?.path)||!e.type?.some((e=>["BackboneElement","Element"].includes(e.code))))}parseSliceStart(e){if(!this.slicingContext)throw new Error("Invalid slice start before discriminator");this.slicingContext.current&&this.slicingContext.field.slices.push(this.slicingContext.current),this.slicingContext.current={name:e.sliceName??"",fields:{},min:e.min??0,max:"*"===e.max?Number.POSITIVE_INFINITY:Number.parseInt(e.max,10)}}parseFieldDefinition(e){const t=Vr(e.max),r=e.base?.max?Vr(e.base.max):t,n={type:"ElementDefinition",value:e};return{min:e.min??0,max:t,isArray:r>1,constraints:(e.constraint??[]).map((e=>({key:e.key??"",severity:e.severity??"error",expression:e.expression??"",description:e.human??""}))),type:(e.type??[]).map((t=>({code:["BackboneElement","Element"].includes(t.code)?Yr(e.base?.path?.split(".")??[]):t.code??"",targetProfile:t.targetProfile??[]}))),fixed:Zr(Fe(n,"fixed")),pattern:Zr(Fe(n,"pattern")),binding:"required"===e.binding?.strength?e.binding.valueSet:void 0}}}function Vr(e){return"*"===e?Number.POSITIVE_INFINITY:Number.parseInt(e,10)}function Jr(e,t=""){return function(e,t){if(!e)return"";if(t&&e.startsWith(t))return e.substring(t.length+1);return e}(e.path,t)}function Xr(e,t){return!(!e||!t)&&(t.startsWith(e+".")||t===e)}function Yr(e){return 1===e.length?e[0]:e.map(D).join("")}function Zr(e){return Array.isArray(e)&&e.length>0?e[0]:w(e)?void 0:e}const Kr={base64Binary:"string",boolean:"boolean",canonical:"string",code:"string",date:"string",dateTime:"string",decimal:"number",id:"string",instant:"string",integer:"number",markdown:"string",oid:"string",positiveInt:"number",string:"string",time:"string",unsignedInt:"number",uri:"string",url:"string",uuid:"string",xhtml:"string","http://hl7.org/fhirpath/System.String":"string"},en={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:/^[\s\S]+$/,oid:/^urn:oid:[0-2](\.(0|[1-9]\d*))+$/,string:/^[\s\S]+$/,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:/.*/};class tn{constructor(e,t){this.issues=[],this.schema=t?Wr(t):zr(e)}validate(e){if(!e)throw new me(le("Resource is null"));const t=e.resourceType;if(!t)throw new me(le("Missing resource type"));this.validateObject({type:t,value:e},this.schema,t);const r=this.issues;if(this.issues=[],r.length>0)throw new me({resourceType:"OperationOutcome",issue:r})}validateObject(e,t,r){for(const[n,i]of Object.entries(t.fields))this.checkProperty(e,n,t,r+"."+n);this.checkAdditionalProperties(e,t.fields,r)}checkProperty(e,t,r,n){const i=function(e,t){const[r,...n]=t.split(".");let i=[Fe(e,r)];for(const e of n){const t=[];for(const r of i)if(void 0!==r)if(Array.isArray(r))for(const n of r)t.push(Fe(n,e));else t.push(Fe(r,e));i=t}return i}(e,t),o=r.fields[t];if(!o)throw new Error(`Missing element validation schema for ${t}`);for(const e of i){if(w(e))return void(o.min>0&&this.issues.push(Qr(n,"Missing required property")));let t;if(o.isArray){if(!Array.isArray(e))return void this.issues.push(Qr(n,"Expected array of values"));t=e}else{if(Array.isArray(e))return void this.issues.push(Qr(n,"Expected single value"));t=[e]}for(const e of t)this.checkPropertyValue(e,n)}}checkPropertyValue(e,t){if(O(e.type.charAt(0)))this.validatePrimitiveType(e,t);else{const r=zr(e.type);this.validateObject(e,r,t)}}checkAdditionalProperties(e,t,r){const n=e.value;for(const i of Object.keys(n))"resourceType"!==i&&(i in t||rn(e,i,t)||this.isPrimitiveExtension(e,i,r)||this.issues.push(Qr(`${r}.${i}`,`Invalid additional property "${i}"`)))}isPrimitiveExtension(e,t,r){return!!t.startsWith("_")&&(this.validateObject({type:"Element",value:e.value[t]},zr("Element"),r),!0)}validatePrimitiveType(e,t){const{type:r,value:n}=e,i=Kr[r];typeof n===i?"string"===i?this.validateString(n,r,t):"number"===i&&this.validateNumber(n,r,t):this.issues.push(Qr(t,`Invalid JSON type at ${t}: expected ${i}, but got ${typeof n}`))}validateString(e,t,r){if(!e.trim())return void this.issues.push(Qr(r,"String must contain non-whitespace content"));const n=en[t];n&&!n.exec(e)&&this.issues.push(Qr(r,"Invalid "+t+" format"))}validateNumber(t,r,n){var i;isNaN(t)||!isFinite(t)?this.issues.push(Qr(n,"Invalid numeric value")):(i=r)!==e.PropertyType.integer&&i!==e.PropertyType.positiveInt&&i!==e.PropertyType.unsignedInt||Number.isInteger(t)?r===e.PropertyType.positiveInt&&t<=0?this.issues.push(Qr(n,"Expected number to be positive")):r===e.PropertyType.unsignedInt&&t<0&&this.issues.push(Qr(n,"Expected number to be non-negative")):this.issues.push(Qr(n,"Expected number to be an integer"))}}function rn(e,t,r){const n=t.split(/(?=[A-Z])/g);let i="";for(const t of n){if(i+=t,!r[i+"[x]"])continue;return!!Fe(e,i)}return!1}e.AndAtom=Pt,e.ArithemticOperatorAtom=ft,e.AsAtom=ht,e.ClientStorage=yr,e.ConcatAtom=yt,e.ContainsAtom=mt,e.DEFAULT_SEARCH_COUNT=20,e.DotAtom=vt,e.EmptySetAtom=dt,e.EqualsAtom=Tt,e.EquivalentAtom=St,e.FHIRPATH_KEYWORDS=Dt,e.FHIRPATH_OPERATORS=Ot,e.FhirFilterComparison=Cr,e.FhirFilterConnective=Rr,e.FhirFilterNegation=Ar,e.FhirPathAtom=ct,e.FhirSchemaValidator=qr,e.FunctionAtom=At,e.Hl7Context=Ur,e.Hl7Field=Mr,e.Hl7Message=Nr,e.Hl7Segment=Lr,e.InAtom=gt,e.IndexerAtom=Rt,e.InfixOperatorAtom=Ue,e.IsAtom=Et,e.LRUCache=ur,e.LiteralAtom=ut,e.MEDPLUM_VERSION="2.0.24-8a2dc16",e.MedplumClient=class extends dr{constructor(e){if(super(),e?.baseUrl&&!e.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.fetch=e?.fetch??function(){if(!globalThis.fetch)throw new Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}(),this.storage=e?.storage||new yr,this.createPdfImpl=e?.createPdf,this.baseUrl=Sr(e?.baseUrl)||"https://api.medplum.com/",this.fhirBaseUrl=this.baseUrl+(Sr(e?.fhirUrlPath)||"fhir/R4/"),this.clientId=e?.clientId||"",this.authorizeUrl=e?.authorizeUrl||this.baseUrl+"oauth2/authorize",this.tokenUrl=e?.tokenUrl||this.baseUrl+"oauth2/token",this.logoutUrl=e?.logoutUrl||this.baseUrl+"oauth2/logout",this.onUnauthenticated=e?.onUnauthenticated,this.cacheTime=e?.cacheTime??6e4,this.cacheTime>0?this.requestCache=new ur(e?.resourceCacheSize??1e3):this.requestCache=void 0,e?.autoBatchTime?(this.autoBatchTime=e.autoBatchTime??0,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0);const t=this.getActiveLogin();t&&(this.accessToken=t.accessToken,this.refreshToken=t.refreshToken,this.refreshProfile().catch(console.log)),this.setupStorageListener()}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}clear(){this.storage.clear(),this.clearActiveLogin()}clearActiveLogin(){this.basicAuth||(this.storage.setString("activeLogin",void 0),this.requestCache?.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.sessionDetails=void 0,this.dispatchEvent({type:"change"}))}invalidateUrl(e){e=e.toString(),this.requestCache?.delete(e)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(e){const t=this.fhirBaseUrl+e;if(this.requestCache)for(const e of this.requestCache.keys())(e.endsWith(t)||e.includes(t+"?"))&&this.requestCache.delete(e)}get(e,t={}){e=e.toString();const r=this.getCacheEntry(e,t);if(r)return r.value;let n;n=e.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue?new Promise(((r,n)=>{this.autoBatchQueue.push({method:"GET",url:e.replace(this.fhirBaseUrl,""),options:t,resolve:r,reject:n}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout((()=>this.executeAutoBatch()),this.autoBatchTime))})):this.request("GET",e,t);const i=new fr(n);return this.setCacheEntry(e,i),i}post(e,t,r,n={}){return e=e.toString(),t&&this.setRequestBody(n,t),r&&this.setRequestContentType(n,r),this.invalidateUrl(e),this.request("POST",e,n)}put(e,t,r,n={}){return e=e.toString(),t&&this.setRequestBody(n,t),r&&this.setRequestContentType(n,r),this.invalidateUrl(e),this.request("PUT",e,n)}patch(e,t,r={}){return e=e.toString(),this.setRequestBody(r,t),this.setRequestContentType(r,"application/json-patch+json"),this.invalidateUrl(e),this.request("PATCH",e,r)}delete(e,t){return e=e.toString(),this.invalidateUrl(e),this.request("DELETE",e,t)}async startNewUser(e,t){const{codeChallengeMethod:r,codeChallenge:n}=await this.startPkce();return this.post("auth/newuser",{...e,codeChallengeMethod:r,codeChallenge:n},void 0,t)}async startNewProject(e,t){return this.post("auth/newproject",e,void 0,t)}async startNewPatient(e,t){return this.post("auth/newpatient",e,void 0,t)}async startLogin(e,t){return this.post("auth/login",{...await this.ensureCodeChallenge(e),clientId:e.clientId??this.clientId,scope:e.scope},void 0,t)}async startGoogleLogin(e,t){return this.post("auth/google",{...await this.ensureCodeChallenge(e),clientId:e.clientId??this.clientId,scope:e.scope},void 0,t)}async ensureCodeChallenge(e){return e.codeChallenge?e:{...e,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(e){const t=new URLSearchParams(window.location.search).get("code");return t?this.processCode(t):void await this.requestAuthorization(e)}signOutWithRedirect(){window.location.assign(this.logoutUrl)}async signInWithExternalAuth(e,t,r,n){const i=await this.ensureCodeChallenge(n);window.location.assign(this.getExternalAuthRedirectUri(e,t,r,i))}async exchangeExternalAccessToken(t,r){if(!(r=r||this.clientId))throw new Error("MedplumClient is missing clientId");const n=new URLSearchParams;return n.set("grant_type",e.OAuthGrantType.TokenExchange),n.set("subject_token_type",e.OAuthTokenType.AccessToken),n.set("client_id",r),n.set("subject_token",t),this.fetchTokens(n)}getExternalAuthRedirectUri(e,t,r,n){const i=new URL(e);return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t),i.searchParams.set("redirect_uri",r),i.searchParams.set("scope","openid profile email"),i.searchParams.set("state",JSON.stringify(n)),i.toString()}fhirUrl(...e){return new URL(this.fhirBaseUrl+e.join("/"))}fhirSearchUrl(e,t){const r=this.fhirUrl(e);return t&&(r.search=new URLSearchParams(t).toString()),r}search(e,t,r){const n=this.fhirSearchUrl(e,t),i=n.toString()+"-search",o=this.getCacheEntry(i,r);if(o)return o.value;const s=new fr((async()=>{const e=await this.get(n,r);if(e.entry)for(const t of e.entry)this.cacheResource(t.resource);return e})());return this.setCacheEntry(i,s),s}searchOne(e,t,r){const n=this.fhirSearchUrl(e,t);n.searchParams.set("_count","1"),n.searchParams.sort();const i=n.toString()+"-searchOne",o=this.getCacheEntry(i,r);if(o)return o.value;const s=new fr(this.search(e,n.searchParams,r).then((e=>e.entry?.[0]?.resource)));return this.setCacheEntry(i,s),s}searchResources(e,t,r){const n=this.fhirSearchUrl(e,t).toString()+"-searchResources",i=this.getCacheEntry(n,r);if(i)return i.value;const o=new fr(this.search(e,t,r).then((e=>e.entry?.map((e=>e.resource))??[])));return this.setCacheEntry(n,o),o}async*searchResourcePages(e,t,r){let n=this.fhirSearchUrl(e,t);for(;n;){const t=new URL(n).searchParams,i=await this.search(e,t,r),o=i.link?.find((e=>"next"===e.relation));if(!i.entry?.length&&!o)break;yield i.entry?.map((e=>e.resource))??[],n=o?.url?new URL(o.url):void 0}}searchValueSet(e,t,r){const n=this.fhirUrl("ValueSet","$expand");return n.searchParams.set("url",e),n.searchParams.set("filter",t),this.get(n.toString(),r)}getCached(e,t){const r=this.requestCache?.get(this.fhirUrl(e,t).toString())?.value;return r?.isOk()?r.read():void 0}getCachedReference(e){const t=e.reference;if(!t)return;if("system"===t)return vr;const[r,n]=t.split("/");return r&&n?this.getCached(r,n):void 0}readResource(e,t,r){return this.get(this.fhirUrl(e,t),r)}readReference(e,t){const r=e.reference;if(!r)return new fr(Promise.reject(new Error("Missing reference")));if("system"===r)return new fr(Promise.resolve(vr));const[n,i]=r.split("/");return n&&i?this.readResource(n,i,t):new fr(Promise.reject(new Error("Invalid reference")))}getSchema(){return G}requestSchema(e){if(e in G.types)return Promise.resolve(G);const t=e+"-requestSchema",r=this.getCacheEntry(t,void 0);if(r)return r.value;const n=new fr((async()=>{const t=`{\n StructureDefinitionList(name: "${e}") {\n name,\n description,\n snapshot {\n element {\n id,\n path,\n min,\n max,\n type {\n code,\n targetProfile\n },\n binding {\n valueSet\n },\n definition\n }\n }\n }\n SearchParameterList(base: "${e}", _count: 100) {\n base,\n code,\n type,\n expression,\n target\n }\n }`.replace(/\s+/g," "),r=await this.graphql(t);for(const e of r.data.StructureDefinitionList)j(e);for(const e of r.data.SearchParameterList)$(e);return G})());return this.setCacheEntry(t,n),n}readHistory(e,t,r){return this.get(this.fhirUrl(e,t,"_history"),r)}readVersion(e,t,r,n){return this.get(this.fhirUrl(e,t,"_history",r),n)}readPatientEverything(e,t){return this.get(this.fhirUrl("Patient",e,"$everything"),t)}createResource(e,t){if(!e.resourceType)throw new Error("Missing resourceType");return this.invalidateSearches(e.resourceType),this.post(this.fhirUrl(e.resourceType),e,void 0,t)}async createResourceIfNoneExist(e,t,r){return await this.searchOne(e.resourceType,t,r)??this.createResource(e,r)}createBinary(e,t,r,n){const i=this.fhirUrl("Binary");return t&&i.searchParams.set("_filename",t),n?this.uploadwithProgress(i,e,r,n):this.post(i,e,r)}uploadwithProgress(e,t,r,n){return new Promise(((i,o)=>{const s=new XMLHttpRequest;s.responseType="json",s.onabort=()=>o(new Error("Request aborted")),s.onerror=()=>o(new Error("Request error")),n&&(s.upload.onprogress=e=>n(e),s.upload.onload=e=>n(e)),s.onload=()=>{s.status>=200&&s.status<300?i(s.response):o(new Error(s.statusText))},s.open("POST",e),s.withCredentials=!0,s.setRequestHeader("Authorization","Bearer "+this.accessToken),s.setRequestHeader("Cache-Control","no-cache, no-store, max-age=0"),s.setRequestHeader("Content-Type",r),s.setRequestHeader("X-Medplum","extended"),s.send(t)}))}async createPdf(e,t,r,n){if(!this.createPdfImpl)throw new Error("PDF creation not enabled");const i=await this.createPdfImpl(e,r,n);return this.createBinary(i,t,"application/pdf")}createComment(e,t,r){const n=this.getProfile();let i,o;return"Encounter"===e.resourceType&&(i=h(e),o=e.subject),"ServiceRequest"===e.resourceType&&(i=e.encounter,o=e.subject),"Patient"===e.resourceType&&(o=h(e)),this.createResource({resourceType:"Communication",basedOn:[h(e)],encounter:i,subject:o,sender:n?h(n):void 0,sent:(new Date).toISOString(),payload:[{contentString:t}]},r)}async updateResource(e,t){if(!e.resourceType)throw new Error("Missing resourceType");if(!e.id)throw new Error("Missing id");this.invalidateSearches(e.resourceType);let r=await this.put(this.fhirUrl(e.resourceType,e.id),e,void 0,t);return r||(r=e),this.cacheResource(r),r}patchResource(e,t,r,n){return this.invalidateSearches(e),this.patch(this.fhirUrl(e,t),r,n)}deleteResource(e,t,r){return this.deleteCacheEntry(this.fhirUrl(e,t).toString()),this.invalidateSearches(e),this.delete(this.fhirUrl(e,t),r)}validateResource(e,t){return this.post(this.fhirUrl(e.resourceType,"$validate"),e,void 0,t)}executeBot(e,t,r,n){let i;if("string"==typeof e){const t=e;i=this.fhirUrl("Bot",t,"$execute")}else{const t=e;i=this.fhirUrl("Bot","$execute")+`?identifier=${t.system}|${t.value}`}return this.post(i,t,r,n)}executeBatch(e,t){return this.post(this.fhirBaseUrl.slice(0,-1),e,void 0,t)}sendEmail(e,t){return this.post("email/v1/send",e,"application/json",t)}graphql(e,t,r,n){return this.post(this.fhirUrl("$graphql"),{query:e,operationName:t,variables:r},"application/json",n)}readResourceGraph(e,t,r,n){return this.get(`${this.fhirUrl(e,t)}/$graph?graph=${r}`,n)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(e){this.clearActiveLogin(),this.accessToken=e.accessToken,this.basicAuth||(this.refreshToken=e.refreshToken,this.storage.setObject("activeLogin",e),this.addLogin(e),this.refreshPromise=void 0,await this.refreshProfile())}getAccessToken(){return this.accessToken}setAccessToken(e){this.accessToken=e,this.refreshToken=void 0,this.sessionDetails=void 0}getLogins(){return this.storage.getObject("logins")??[]}addLogin(e){const t=this.getLogins().filter((t=>t.profile?.reference!==e.profile?.reference));t.push(e),this.storage.setObject("logins",t)}async refreshProfile(){return this.profilePromise=new Promise(((e,t)=>{this.basicAuth||this.get("auth/me").then((t=>{this.profilePromise=void 0,this.sessionDetails=t,this.dispatchEvent({type:"change"}),e(t.profile)})).catch(t)})),this.profilePromise}isLoading(){return!!this.profilePromise}isSuperAdmin(){return!!this.sessionDetails?.project.superAdmin}isProjectAdmin(){return!!this.sessionDetails?.membership.admin}getProject(){return this.sessionDetails?.project}getProjectMembership(){return this.sessionDetails?.membership}getProfile(){return this.sessionDetails?.profile}async getProfileAsync(){return this.profilePromise&&await this.profilePromise,this.getProfile()}getUserConfiguration(){return this.sessionDetails?.config}getAccessPolicy(){return this.sessionDetails?.accessPolicy}async download(e,t={}){this.refreshPromise&&await this.refreshPromise,this.addFetchOptionsDefaults(t);return(await this.fetch(e.toString(),t)).blob()}async uploadMedia(e,t,r,n,i){const o=await this.createBinary(e,r,t);return this.createResource({...n,resourceType:"Media",content:{contentType:t,url:"Binary/"+o.id,title:r}},i)}async bulkExport(e="",t,r,n){const i=e?`${e}/`:e,o=this.fhirUrl(`${i}$export`);return t&&o.searchParams.set("_type",t),r&&o.searchParams.set("_since",r),this.startAsyncRequest(o.toString(),n)}async startAsyncRequest(e,t={}){this.addFetchOptionsDefaults(t);t.headers.Prefer="respond-async";const r=await this.fetchWithRetry(e,t);if(202===r.status){const e=r.headers.get("content-location");if(e)return this.pollStatus(e);const t=await r.json();if(fe(t)&&t.issue?.[0]?.diagnostics)return this.pollStatus(t.issue[0].diagnostics)}return this.parseResponse(r,"POST",e)}getCacheEntry(e,t){if(!this.requestCache||"no-cache"===t?.cache||"reload"===t?.cache)return;const r=this.requestCache.get(e);return!r||r.requestTime+this.cacheTime<Date.now()?void 0:r}setCacheEntry(e,t){this.requestCache&&this.requestCache.set(e,{requestTime:Date.now(),value:t})}cacheResource(e){e?.id&&this.setCacheEntry(this.fhirUrl(e.resourceType,e.id).toString(),new fr(Promise.resolve(e)))}deleteCacheEntry(e){this.requestCache&&this.requestCache.delete(e)}async request(e,t,r={}){this.refreshPromise&&await this.refreshPromise,r.method=e,this.addFetchOptionsDefaults(r);const n=await this.fetchWithRetry(t,r);return this.parseResponse(n,e,t,r)}async parseResponse(e,t,r,n={}){if(401===e.status)return this.handleUnauthenticated(t,r,n);if(204===e.status||304===e.status)return;if(404===e.status){const t=e.headers.get("content-type");if(!t?.includes("application/fhir+json"))throw new me(se)}let i;try{i=await e.json()}catch(t){throw console.error("Error parsing response",e.status,t),t}if(e.status>=400)throw new me(ge(i));return i}async fetchWithRetry(e,t){e.startsWith("http")||(e=this.baseUrl+e);let r;for(let n=0;n<3;n++){try{if(r=await this.fetch(e,t),r.status<500)return r}catch(e){this.retryCatch(n,3,e)}await new Promise((e=>{setTimeout(e,200)}))}return r}async pollStatus(e){let t,r=!0;for(;r;){const n={};this.addFetchOptionsDefaults(n);const i=await this.fetchWithRetry(e,n);202!==i.status&&(r=!1,t=i),await new Promise((e=>{setTimeout(e,2e3)}))}return this.parseResponse(t,"POST",e)}async executeAutoBatch(){const e=[...this.autoBatchQueue];if(this.autoBatchQueue.length=0,this.autoBatchTimerId=void 0,1===e.length){const t=e[0];try{t.resolve(await this.request(t.method,this.fhirBaseUrl+t.url,t.options))}catch(e){t.reject(new me(ge(e)))}return}const t={resourceType:"Bundle",type:"batch",entry:e.map((e=>({request:{method:e.method,url:e.url},resource:e.options.body?JSON.parse(e.options.body):void 0})))},r=await this.post(this.fhirBaseUrl.slice(0,-1),t);for(let t=0;t<e.length;t++){const n=e[t],i=r.entry?.[t];i?.response?.outcome&&!ye(i.response.outcome)?n.reject(new me(i.response.outcome)):n.resolve(i?.resource)}}addFetchOptionsDefaults(e){let t=e.headers;t||(t={},e.headers=t),t.Accept=gr,t["X-Medplum"]="extended",e.body&&!t["Content-Type"]&&(t["Content-Type"]=gr),this.accessToken?t.Authorization="Bearer "+this.accessToken:this.basicAuth&&(t.Authorization="Basic "+this.basicAuth),e.cache||(e.cache="no-cache"),e.credentials||(e.credentials="include")}setRequestContentType(e,t){e.headers||(e.headers={});e.headers["Content-Type"]=t}setRequestBody(e,t){"string"==typeof t||"undefined"!=typeof Blob&&t instanceof Blob||"undefined"!=typeof File&&t instanceof File||"undefined"!=typeof Uint8Array&&t instanceof Uint8Array?e.body=t:t&&(e.body=JSON.stringify(t))}handleUnauthenticated(e,t,r){return this.refresh()?this.request(e,t,r):(this.clearActiveLogin(),this.onUnauthenticated&&this.onUnauthenticated(),Promise.reject(new Error("Unauthenticated")))}async startPkce(){const e=pr();sessionStorage.setItem("pkceState",e);const t=pr();sessionStorage.setItem("codeVerifier",t);const r=R(await async function(e){return crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e))}(t)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return sessionStorage.setItem("codeChallenge",r),{codeChallengeMethod:"S256",codeChallenge:r}}async requestAuthorization(e){const t=await this.ensureCodeChallenge(e||{}),r=new URL(this.authorizeUrl);r.searchParams.set("response_type","code"),r.searchParams.set("state",sessionStorage.getItem("pkceState")),r.searchParams.set("client_id",t.clientId||this.clientId),r.searchParams.set("redirect_uri",t.redirectUri||br()),r.searchParams.set("code_challenge_method",t.codeChallengeMethod),r.searchParams.set("code_challenge",t.codeChallenge),r.searchParams.set("scope",t.scope||"openid profile"),window.location.assign(r.toString())}processCode(t,r){const n=new URLSearchParams;if(n.set("grant_type",e.OAuthGrantType.AuthorizationCode),n.set("code",t),n.set("client_id",r?.clientId||this.clientId),n.set("redirect_uri",r?.redirectUri||br()),"undefined"!=typeof sessionStorage){const e=sessionStorage.getItem("codeVerifier");e&&n.set("code_verifier",e)}return this.fetchTokens(n)}refresh(){if(this.refreshPromise)return this.refreshPromise;if(this.refreshToken){const t=new URLSearchParams;return t.set("grant_type",e.OAuthGrantType.RefreshToken),t.set("client_id",this.clientId),t.set("refresh_token",this.refreshToken),this.refreshPromise=this.fetchTokens(t),this.refreshPromise}return this.clientId&&this.clientSecret?(this.refreshPromise=this.startClientLogin(this.clientId,this.clientSecret),this.refreshPromise):void 0}async startClientLogin(t,r){this.clientId=t,this.clientSecret=r;const n=new URLSearchParams;return n.set("grant_type",e.OAuthGrantType.ClientCredentials),n.set("client_id",t),n.set("client_secret",r),this.fetchTokens(n)}setBasicAuth(e,t){this.clientId=e,this.clientSecret=t,this.basicAuth=ar(e+":"+t)}async invite(e,t){return this.post("admin/projects/"+e+"/invite",t)}async fetchTokens(e){const t={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e,credentials:"include"},r=t.headers;this.basicAuth&&(r.Authorization=`Basic ${this.basicAuth}`);const n=await this.fetch(this.tokenUrl,t);if(!n.ok){this.clearActiveLogin();try{const e=await n.json();throw new me(de(e.error_description))}catch(e){throw new me(de("Failed to fetch tokens"),e)}}const i=await n.json();return await this.verifyTokens(i),this.getProfile()}async verifyTokens(e){const t=e.access_token,r=lr(t);if(Date.now()>=1e3*r.exp)throw this.clearActiveLogin(),new Error("Token expired");if(r.cid){if(r.cid!==this.clientId)throw this.clearActiveLogin(),new Error("Token was not issued for this audience")}else if(this.clientId&&r.client_id!==this.clientId)throw this.clearActiveLogin(),new Error("Token was not issued for this audience");return this.setActiveLogin({accessToken:t,refreshToken:e.refresh_token,project:e.project,profile:e.profile})}setupStorageListener(){try{window.addEventListener("storage",(e=>{null!==e.key&&"activeLogin"!==e.key||window.location.reload()}))}catch(e){}}retryCatch(e,t,r){if("Failed to fetch"===r.message&&1===e&&this.dispatchEvent({type:"offline"}),e>=t-1)throw r}},e.MemoryStorage=mr,e.NotEqualsAtom=bt,e.NotEquivalentAtom=wt,e.OperationOutcomeError=me,e.OrAtom=kt,e.Parser=Le,e.ParserBuilder=Ne,e.PrefixOperatorAtom=Ie,e.ReadablePromise=fr,e.SymbolAtom=pt,e.Tokenizer=_e,e.UnaryOperatorAtom=lt,e.UnionAtom=xt,e.XorAtom=Ct,e.accepted=function(e){return{resourceType:"OperationOutcome",id:re,issue:[{severity:"information",code:"informational",details:{text:"Accepted"},diagnostics:e}]}},e.allOk=ne,e.arrayBufferToBase64=R,e.arrayBufferToHex=A,e.assertOk=function(e,t){if(!ye(e)||void 0===t)throw new me(e)},e.badRequest=de,e.booleanToTypedValue=je,e.buildTypeName=q,e.calculateAge=v,e.calculateAgeString=function(e,t){const{years:r,months:n,days:i}=v(e,t);return r>=2?r.toString().padStart(3,"0")+"Y":n>=1?n.toString().padStart(3,"0")+"M":i.toString().padStart(3,"0")+"D"},e.canReadResourceType=function(e,t){if(e.resource)for(const r of e.resource)if(or(r.resourceType,t))return!0;return!1},e.canWriteResource=function(e,t){return!!rr(e,t.resourceType)&&nr(e,t,!1)},e.canWriteResourceType=rr,e.capitalize=D,e.checkForNull=Fr,e.convertToTransactionBundle=function(e){for(const t of e.entry||[])delete t.resource?.meta,t.fullUrl="urn:uuid:"+t.resource?.id,delete t.resource?.id;const t=e.entry,r=JSON.stringify({resourceType:"Bundle",type:"transaction",entry:t?.map((e=>({fullUrl:e.fullUrl,request:{method:"POST",url:e.resource.resourceType},resource:e.resource})))},cr,2);return JSON.parse(r)},e.createReference=h,e.createStructureIssue=Qr,e.created=ie,e.decodeBase64=sr,e.deepClone=function(e){return JSON.parse(JSON.stringify(e))},e.deepEquals=E,e.encodeBase64=ar,e.evalFhirPath=$t,e.evalFhirPathTyped=qt,e.experimentalValidateResource=function(e,t){return new tn(e.resourceType,t).validate(e)},e.fhirPathArrayEquals=ze,e.fhirPathArrayEquivalent=Ve,e.fhirPathEquals=Ge,e.fhirPathEquivalent=Je,e.fhirPathIs=Ye,e.fhirPathNot=He,e.findObservationInterval=function(e,t,r,n){return e.qualifiedInterval?.find((i=>U(i,t)&&function(e,t,r){return!!e.range&&N(t,e.range,r)}(i,r,e.quantitativeDetails?.decimalPrecision)&&(void 0===n||i.category===n)))},e.findObservationReferenceRange=function(e,t,r){return e.qualifiedInterval?.find((e=>U(e,t)&&r.includes(e.condition)))},e.findResourceByCode=function(e,t,r){return e.find((e=>"string"==typeof t?I(e.code||{},r)===t:I(e.code||{},r)===I(t,r)))},e.forbidden=ce,e.formatAddress=function(e,t){const r=[];if(e.line&&r.push(...e.line),e.city||e.state||e.postalCode){const t=[];e.city&&t.push(e.city),e.state&&t.push(e.state),e.postalCode&&t.push(e.postalCode),r.push(t.join(", "))}return e.use&&(t?.all||t?.use)&&r.push("["+e.use+"]"),r.join(t?.lineSeparator||", ").trim()},e.formatCodeableConcept=p,e.formatCoding=d,e.formatDate=function(e,t,r){if(!e)return"";const i=new Date(e);return n(i)?(i.setUTCHours(0,0,0,0),i.toLocaleDateString(t,{timeZone:"UTC",...r})):""},e.formatDateTime=o,e.formatFamilyName=function(e){return e.family||""},e.formatGivenName=function(e){const t=[];return e.given&&t.push(...e.given),t.join(" ").trim()},e.formatHumanName=r,e.formatMoney=function(e){return void 0===e?.value?"":e.value.toLocaleString(void 0,{style:"currency",currency:e.currency||"USD",currencyDisplay:"narrowSymbol"})},e.formatObservationValue=function e(t){return t?"component"in t?t.component.map((t=>e(t))).join(" / "):t.valueQuantity?u(t.valueQuantity):t.valueCodeableConcept?p(t.valueCodeableConcept):t.valueString?t.valueString:"":""},e.formatPeriod=function(e,t,r){return e&&(e.start||e.end)?o(e.start,t,r)+" - "+o(e.end,t,r):""},e.formatQuantity=u,e.formatRange=function(e,t,r=!1){if(r&&void 0===t)throw new Error("Precision must be specified for exclusive ranges");const n=e?.low&&{...e.low,comparator:void 0},i=e?.high&&{...e.high,comparator:void 0};return void 0===n?.value&&void 0===i?.value?"":void 0!==n?.value&&void 0===i?.value?r&&void 0!==t?(n.value=function(e,t,r=1){return(l(e,t)-r)*Math.pow(10,-t)}(n.value,t),`> ${u(n,t)}`):`>= ${u(n,t)}`:void 0===n?.value&&void 0!==i?.value?r&&void 0!==t?(i.value=function(e,t,r=1){return(l(e,t)+r)*Math.pow(10,-t)}(i.value,t),`< ${u(i,t)}`):`<= ${u(i,t)}`:(n?.unit===i?.unit&&delete n?.unit,`${u(n,t)} - ${u(i,t)}`)},e.formatSearchQuery=function(t){const r=[];return t.fields&&r.push("_fields="+t.fields.join(",")),t.filters&&t.filters.forEach((t=>r.push(function(t){const r=t.operator in Se?":"+t.operator:"",n=t.operator!==e.Operator.EQUALS&&t.operator in we?t.operator:"";return`${t.code}${r}=${n}${encodeURIComponent(t.value)}`}(t)))),t.sortRules&&t.sortRules.length>0&&r.push("_sort="+t.sortRules.map((e=>e.descending?"-"+e.code:e.code)).join(",")),void 0!==t.offset&&r.push("_offset="+t.offset),void 0!==t.count&&r.push("_count="+t.count),void 0!==t.total&&r.push("_total="+t.total),0===r.length?"":(r.sort(),"?"+r.join("&"))},e.formatTime=i,e.formatTiming=function(e){if(!e)return"";const t=[];if(e.repeat?.periodUnit){const r=e.repeat.frequency||1,n=e.repeat.period||1,o=e.repeat.periodUnit;1===r&&1===n?t.push(s[o]):(1===r?t.push("once"):t.push(r+" times"),1===n?t.push("per "+a[o]):t.push("per "+n+" "+c[o])),e.repeat.dayOfWeek&&t.push("on "+e.repeat.dayOfWeek.map(D).join(", ")),e.repeat.timeOfDay&&t.push("at "+e.repeat.timeOfDay.map((e=>i(e))).join(", "))}return e.event&&t.push(e.event.map((e=>o(e))).join(", ")),D(t.join(" ").trim())},e.getCodeBySystem=I,e.getDateProperty=function(e){return e?new Date(e):void 0},e.getDisplayString=m,e.getElementDefinition=H,e.getElementDefinitionTypeName=function(e){const t=e.type?.[0]?.code;return"BackboneElement"===t||"Element"===t?q(e.path?.split(".")):t},e.getExpressionForResourceType=Ht,e.getExtension=function(e,...t){let r=e;for(let e=0;e<t.length&&r;e++)r=r?.extension?.find((r=>r.url===t[e]));return r},e.getExtensionValue=T,e.getIdentifier=function(e,t){const r=e.identifier;if(!r)return;const n=Array.isArray(r)?r:[r];for(const e of n)if(e.system===t)return e.value},e.getImageSrc=function(e){if(!("photo"in e))return;const t=e.photo;if(t){if(!Array.isArray(t))return g(t);for(const e of t){const t=g(e);if(t)return t}}},e.getPropertyDisplayName=function(e){return e.replaceAll("[x]","").split(".").pop().split(/(?=[A-Z])/).map(W).join(" ").replace("_"," ").replace(/\s+/g," ")},e.getQuestionnaireAnswers=function(e){const t={};return x(e.item,t),t},e.getReferenceString=f,e.getResourceTypeSchema=function(e){return G.types[e]},e.getResourceTypes=function(){const e=[];for(const[t,r]of Object.entries(G.types))F(r)&&e.push(t);return e},e.getSearchParameterDetails=Qt,e.getSearchParameters=function(e){return G.types[e].searchParams},e.getStatus=function(e){return e.id===V?200:e.id===J?201:e.id===re?202:e.id===Y?304:e.id===K?401:e.id===ee?403:e.id===Z?404:e.id===X?410:e.id===te?429:400},e.getTypedPropertyValue=Fe,e.globalSchema=G,e.gone=ue,e.indexSearchParameter=$,e.indexSearchParameterBundle=function(e){for(const t of e.entry){const e=t.resource;"SearchParameter"===e.resourceType&&$(e)}},e.indexStructureDefinition=j,e.indexStructureDefinitionBundle=function(e){for(const t of e.entry){const e=t.resource;"StructureDefinition"===e.resourceType&&j(e)}},e.initFhirPathParserBuilder=_t,e.isAccepted=function(e){return e.id===re},e.isEmpty=w,e.isGone=function(e){return e.id===X},e.isLowerCase=O,e.isNotFound=function(e){return e.id===Z},e.isObject=P,e.isOk=ye,e.isOperationOutcome=fe,e.isPeriod=Ze,e.isProfileResource=y,e.isQuantity=Ke,e.isQuantityEquivalent=et,e.isReference=function(e){return!(!e||"object"!=typeof e||!("reference"in e))},e.isResource=z,e.isResourceType=$r,e.isResourceTypeSchema=F,e.isStringArray=k,e.isUUID=function(e){return!!e.match(/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/i)},e.isValidDate=n,e.loadDataTypes=function(e){for(const{resource:t}of e.entry??[]){if(!t?.name)throw new Error("Failed loading StructureDefinition from bundle");if("StructureDefinition"!==t.resourceType)continue;const e=Wr(t);Hr[t.name]=e;for(const t of e.innerTypes)Hr[t.name]=t}},e.matchesAccessPolicy=nr,e.matchesRange=N,e.matchesSearchRequest=Gt,e.normalizeErrorString=ve,e.normalizeOperationOutcome=ge,e.notFound=se,e.notModified=oe,e.operationOutcomeIssueToString=Te,e.operationOutcomeToString=xe,e.parseCriteriaAsSearchRequest=Pe,e.parseFhirPath=jt,e.parseFilterParameter=function(e){const t=Ir.construct(new _e(e,Dt,kr,{dateTimeLiterals:!0,symbolRegex:/[^\s\])]/}).tokenize());return t.removeComments(),new Or(t).parse()},e.parseHl7Date=function(e,t){if(!e)return;t={seconds:!0,tzOffset:"Z",...t};const r=Number.parseInt(e.substring(0,4),10),n=Number.parseInt(e.substring(4,6),10),i=Number.parseInt(e.substring(6,8),10),o=Number.parseInt(e.substring(8,10),10),s=Number.parseInt(e.substring(10,12),10),a=t.seconds?Number.parseInt(e.substring(12,14),10):0;return`${_r(r)}-${_r(n)}-${_r(i)}T${_r(o)}:${_r(s)}:${_r(a)}.000${t.tzOffset}`},e.parseJWTPayload=lr,e.parseMappingLanguage=function(e){const t=Pr.construct(new _e(e,Dt,wr).tokenize());return t.removeComments(),new Er(t).parse()},e.parseSearchDefinition=function(e){return Ee(new URL(e,"https://example.com/"))},e.parseSearchRequest=function(e,t){const r=[];for(const[e,n]of Object.entries(t))if(Array.isArray(n))for(const t of n)r.push([e,t]);else r.push([e,n||""]);return ke(e,r)},e.parseSearchUrl=Ee,e.preciseEquals=function(e,t,r){return _(e,r)===_(t,r)},e.preciseGreaterThan=function(e,t,r){return _(e,r)>_(t,r)},e.preciseGreaterThanOrEquals=M,e.preciseLessThan=function(e,t,r){return _(e,r)<_(t,r)},e.preciseLessThanOrEquals=L,e.preciseRound=function(e,t){return parseFloat(e.toFixed(t))},e.projectAdminResourceTypes=tr,e.protectedResourceTypes=er,e.publicResourceTypes=Kt,e.removeDuplicates=We,e.resolveId=function(e){return e?.reference?.split("/")[1]},e.serverError=he,e.setCodeBySystem=function(e,t,r){e.coding||(e.coding=[]);const n=e.coding.find((e=>e.system===t));n?n.code=r:e.coding.push({system:t,code:r})},e.streamToBuffer=function(e){const t=[];return new Promise(((r,n)=>{e.on("data",(e=>t.push(Buffer.from(e)))),e.on("error",(t=>{e.destroy(),n(t)})),e.on("end",(()=>{r(Buffer.concat(t))})),e.on("close",(()=>{e.destroy()}))}))},e.stringify=b,e.toJsBoolean=qe,e.toTypedValue=$e,e.tokenize=It,e.tooManyRequests=pe,e.unauthorized=ae,e.validateResource=function(e){new qr(e).validate()},e.validateResourceType=function(e){if(!e)throw new me(le("Resource type is null"));if(!$r(e))throw new me(le("Unknown resource type"))},e.validationError=le}));
|