PageSourceSearch

https://www.medplum.com/assets/js/fe97b83a.88d748f4.js

js medplum.com collected 2026-10-02 07:39:08 UTC 164,234 bytes, 41 lines download raw bytes

1"use strict";(self.webpackChunk_medplum_docs=self.webpackChunk_medplum_docs||[]).push([["1463"],{30334(e,t,i){i.r(t),i.d(t,{metadata:()=>n,default:()=>y,frontMatter:()=>f,contentTitle:()=>h,toc:()=>p,assets:()=>u});var n=JSON.parse('{"id":"api/fhir/resources/paymentreconciliation","title":"PaymentReconciliation","description":"This resource provides the details including amount of a payment and allocates the payment items being paid.","source":"@site/docs/api/fhir/resources/paymentreconciliation.mdx","sourceDirName":"api/fhir/resources","slug":"/api/fhir/resources/paymentreconciliation","permalink":"/docs/api/fhir/resources/paymentreconciliation","draft":false,"unlisted":false,"editUrl":"https://github.com/medplum/medplum/blob/main/packages/docs/docs/api/fhir/resources/paymentreconciliation.mdx","tags":[],"version":"current","lastUpdatedAt":1705358635000,"sidebarPosition":104,"frontMatter":{"title":"PaymentReconciliation","sidebar_position":104},"sidebar":"docsSidebar","previous":{"title":"PaymentNotice","permalink":"/docs/api/fhir/resources/paymentnotice"},"next":{"title":"Person","permalink":"/docs/api/fhir/resources/person"}}'),r=i(31085),o=i(71184),s=i(81093),a=i(80660),c=i(62874),d=JSON.parse('{"qo":[{"name":"PaymentReconciliation","depth":0,"types":[{"datatype":""}],"path":"PaymentReconciliation","min":0,"max":"*","short":"PaymentReconciliation resource","definition":"This resource provides the details including amount of a payment and allocates the payment items being paid.","comment":"","inherited":false},{"name":"id","depth":1,"types":[{"datatype":"string"}],"path":"PaymentReconciliation.id","min":0,"max":"1","short":"Logical id of this artifact","definition":"The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes.","comment":"The only time that a resource does not have an id is when it is being submitted to the server using a create operation.","inherited":true,"base":"Resource"},{"name":"meta","depth":1,"types":[{"datatype":"Meta","documentLocation":"datatype"}],"path":"PaymentReconciliation.meta","min":0,"max":"1","short":"Metadata about the resource","definition":"The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content might not always be associated with version changes to the resource.","comment":"","inherited":true,"base":"Resource"},{"name":"implicitRules","depth":1,"types":[{"datatype":"uri"}],"path":"PaymentReconciliation.implicitRules","min":0,"max":"1","short":"A set of rules under which this content was created","definition":"A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content. Often, this is a reference to an implementation guide that defines the special rules along with other profiles etc.","comment":"Asserting this rule set restricts the content to be only understood by a limited set of trading partners. This inherently limits the usefulness of the data in the long term. However, the existing health eco-system is highly fractured, and not yet ready to define, collect, and exchange data in a generally computable sense. Wherever possible, implementers and/or specification writers should avoid using this element. Often, when used, the URL is a reference to an implementation guide that defines these special rules as part of it\'s narrative along with other profiles, value sets, etc.","inherited":true,"base":"Resource"},{"name":"language","depth":1,"types":[{"datatype":"code"}],"path":"PaymentReconciliation.language","min":0,"max":"1","short":"Language of the resource content","definition":"The base language in which the resource is written.","comment":"Language is provided to support indexing and accessibility (typically, services such as text to speech use the language tag). The html language tag in the narrative applies  to the narrative. The language tag on the resource may be used to specify the language of other presentations generated from the data in the resource. Not all the content has to be in the base language. The Resource.language should not be assumed to apply to the narrative automatically. If a language is specified, it should it also be specified on the div element in the html (see rules in HTML5 for information about the relationship between xml:lang and the html lang attribute).","inherited":true,"base":"Resource"},{"name":"text","depth":1,"types":[{"datatype":"Narrative","documentLocation":"datatype"}],"path":"PaymentReconciliation.text","min":0,"max":"1","short":"Text summary of the resource, for human interpretation","definition":"A human-readable narrative that contains a summary of the resource and can be used to represent the content of the resource to a human. The narrative need not encode all the structured data, but is required to contain sufficient detail to make it \\"clinically safe\\" for a human to just read the narrative. Resource definitions may define what content should be represented in the narrative to ensure clinical safety.","comment":"Contained resources do not have narrative. Resources that are not contained SHOULD have a narrative. In some cases, a resource may only have text with little or no additional discrete data (as long as all minOccurs=1 elements are satisfied).  This may be necessary for data from legacy systems where information is captured as a \\"text blob\\" or where text is additionally entered raw or narrated and encoded information is added later.","inherited":true,"base":"DomainResource"},{"name":"contained","depth":1,"types":[{"datatype":"Resource"}],"path":"PaymentReconciliation.contained","min":0,"max":"*","short":"Contained, inline Resources","definition":"The
1se resources do not have an independent existence apart from the resource that contains them - they cannot be identified independently, and nor can they have their own independent transaction scope.","comment":"This should never be done when the content can be identified properly, as once identification is lost, it is extremely difficult (and context dependent) to restore it again. Contained resources may have profiles and tags In their meta elements, but SHALL NOT have security labels.","inherited":true,"base":"DomainResource"},{"name":"extension","depth":1,"types":[{"datatype":"Extension","documentLocation":"datatype"}],"path":"PaymentReconciliation.extension","min":0,"max":"*","short":"Additional content defined by implementations","definition":"May be used to represent additional information that is not part of the basic definition of the resource. To make the use of extensions safe and manageable, there is a strict set of governance  applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension.","comment":"There can be no stigma associated with the use of extensions by any application, project, or standard - regardless of the institution or jurisdiction that uses or defines the extensions.  The use of extensions is what allows the FHIR specification to retain a core level of simplicity for everyone.","inherited":true,"base":"DomainResource"},{"name":"modifierExtension","depth":1,"types":[{"datatype":"Extension","documentLocation":"datatype"}],"path":"PaymentReconciliation.modifierExtension","min":0,"max":"*","short":"Extensions that cannot be ignored","definition":"May be used to represent additional information that is not part of the basic definition of the resource and that modifies the understanding of the element that contains it and/or the understanding of the containing element\'s descendants. Usually modifier elements provide negation or qualification. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions.\\n\\nModifier extensions SHALL NOT change the meaning of any elements on Resource or DomainResource (including cannot change the meaning of modifierExtension itself).","comment":"There can be no stigma associated with the use of extensions by any application, project, or standard - regardless of the institution or jurisdiction that uses or defines the extensions.  The use of extensions is what allows the FHIR specification to retain a core level of simplicity for everyone.","inherited":true,"base":"DomainResource"},{"name":"identifier","depth":1,"types":[{"datatype":"Identifier","documentLocation":"datatype"}],"path":"PaymentReconciliation.identifier","min":0,"max":"*","short":"Business Identifier for a payment reconciliation","definition":"A unique identifier assigned to this payment reconciliation.","comment":"","inherited":false},{"name":"status","depth":1,"types":[{"datatype":"code"}],"path":"PaymentReconciliation.status","min":1,"max":"1","short":"active | cancelled | draft | entered-in-error","definition":"The status of the resource instance.","comment":"This element is labeled as a modifier because the status contains codes that mark the resource as not currently valid.","inherited":false},{"name":"period","depth":1,"types":[{"datatype":"Period","documentLocation":"datatype"}],"path":"PaymentReconciliation.period","min":0,"max":"1","short":"Period covered","definition":"The period of time for which payments have been gathered into this bulk payment for settlement.","comment":"","inherited":false},{"name":"created","depth":1,"types":[{"datatype":"dateTime"}],"path":"PaymentReconciliation.created","min":1,"max":"1","short":"Creation date","definition":"The date when the resource was created.","comment":"","inherited":false},{"name":"paymentIssuer","depth":1,"types":[{"datatype":"Reference","documentLocation":"datatype"}],"referenceTypes":[{"datatype":"Organization","documentLocation":"resource"}],"path":"PaymentReconciliation.paymentIssuer","min":0,"max":"1","short":"Party generating payment","definition":"The party who generated the payment.","comment":"This party is also responsible for the reconciliation.","inherited":false},{"name":"request","depth":1,"types":[{"datatype":"Reference","documentLocation":"datatype"}],"referenceTypes":[{"datatype":"Task","documentLocation":"resource"}],"path":"PaymentReconciliation.request","min":0,"max":"1","short":"Reference to requesting resource","definition":"Original request resource reference.","comment":"","inherited":false},{"name":"requestor","depth":1,"types":[{"datatype":"Reference","documentLocation":"datatype"}],"referenceTypes":[{"datatype":"Practitioner","documentLocation":"resource"},{"datatype":"PractitionerRole","documentLocation":"resource"},{"datatype":"Organization","documentLocation":"resource"}],"path":"PaymentReconciliation.requestor","min":0,"max":"1","short":"Responsible practitioner","definition":"The practitioner who is responsible for the services rendered to the patient.","comment":"","inherited":false},{"name":"outcome","depth":1,"types":[{"datatype":"code"}],"path":"PaymentReconciliation.outcome","min":0,"max":"1","short":"queued | complete | error | partial","definition":"The outcome of a request for a reconciliation.","comment":"The resource may be used to indicate that: the request has been held (queued) for processing; that it has been processed and errors found (error); that no errors were found and that some of the adjudication has been undertaken (partial) or that all of the adjudication has been undertaken (complete).","inherited":false},{"name":"disposition","depth":1,"types":[{"datatype":"string"}],"path":"PaymentReconciliation.disposition","min":0,"max":"1","short":"Disposition message","definition":"A human readable description of the status of the request for the reconciliation.","comment":"","inherited":false},{"name":"paymentDate","depth":1,"types":[{"datatype":"date"}],"path":"PaymentReconciliation.paymentDate","min":1,"max":"1","short":"When payment issued","definition":"The date of payment as indicated on the financial instrument.","comment":"","inherited":false},{"name":"paymentAmount","depth":1,"types":[{"datatype":"Money","documentLocation":"datatype"}],"path":"PaymentReconciliation.paymentAmount","min":1,"max":"1","short":"Total amount of Payment","definition":"Total payment amount as indicated on the financial instrument.","comment":"","inherited":false},{"name":"paymentIdentifier","depth":1,"types":[{"datatype":"Identifier","documentLocation":"datatype"}],"path":"PaymentReconciliation.paymentIdentifier","min":0,"max":"1","short":"Business identifier for the payment","definition":"Issuer\'s unique identifier for the payment instrument.","comment":"For example: EFT number or check number.","inherited":false},{"name":"detail","depth":1,"types":[{"datatype":"BackboneElement"}],"path":"PaymentReconciliation.detail","min":0,"max":"*","short":"Settlement particulars","definition":"Distribution of the payment amount for a previously acknowledged payable.","comment":"","inherited":false},{"name":"id","depth":2,"types":[{"datatype":"string"}],"path":"PaymentReconciliation.detail.id","min":0,"max":"1","short":"Unique id for inter-element referencing","definition":"Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces.","comment":"","inherited":true,"base":"Element"},{"name":"extension","depth":2,"types":[{"datatype":"Extension","documentLocation":"datatype"}],"path":"PaymentReconciliation.detail.extension","min":0,"max":"*","short":"Additional content defined by implementations","definition":"May be used to represent additional information that is not part of the basic definition of the element. To make the use of extensions safe and manageable, there is a strict set of governance  applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension.","comment":"There can be no stigma associated with the use of extensions by any application, project, or standard - regardless of the institution or jurisdiction that uses or defines the extensions.  The use of extensions is what allows the FHIR specification to retain a core level of simplicity for everyone.","inherited":true,"base":"Element"},{"name":"modifierExtension","depth":2,"types":[{"datatype":"Extension","documentLocation":"datatype"}],"path":"PaymentReconciliation.detail.modifierExtension","min":0,"max":"*","short":"Extensions that cannot be ignored even if unrecognized","definition":"May be used to represent additional information that is not part of the basic definition of the element and that modifies the understanding of the element in which it is contained and/or the understanding of the containing element\'s descendants. Usually modifier elements provide negation or qualification. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions.\\n\\nModifier extensions SHALL NOT change the meaning of any elements on Resource or DomainResource (including cannot change the meaning of modifierExtension itself).","comment":"There can be no stigma associated with the use of extensions by any application, project, or standard - regardless of the institution or jurisdiction that uses or defines the extensions.  The use of extensions is what allows the FHIR specification to retain a core level of simplicity for everyone.","inherited":true,"base":"BackboneElement"},{"name":"identifier","depth":2,"types":[{"datatype":"Identifier","documentLocation":"datatype"}],"path":"PaymentReconciliation.detail.identifier","min":0,"max":"1","short":"Business identifier of the payment detail","definition":"Unique identifier for the current payment item for the referenced payable.","comment":"","inherited":false},{"name":"predecessor","depth":2,"types":[{"datatype":"Identifier","documentLocation":"datatype"}],"path":"PaymentReconciliation.detail.predecessor","min":0,"max":"1","short":"Business identifier of the prior payment detail","definition":"Unique identifier for the prior payment item for the referenced payable.","comment":"","inherited":false},{"name":"type","depth":2,"types":[{"datatype":"CodeableConcept","documentLocation":"datatype"}],"path":"PaymentReconciliation.detail.type","min":1,"max":"1","short":"Category of payment","definition":"Code to indicate the nature of the payment.","comment":"For example: payment, adjustment, funds advance, etc.","inherited":false},{"name":"request","depth":2,"types":[{"datatype":"Reference","documentLocation":"datatype"}],"referenceTypes":[{"datatype":"Resource"}],"path":"PaymentReconciliation.detail.request","min":0,"max":"1","short":"Request giving rise to the payment","definition":"A resource, such as a Claim, the evaluation of which could lead to payment.","comment":"","inherited":false},{"name":"submitter","depth":2,"types":[{"datatype":"Reference","documentLocation":"datatype"}],"referenceTypes":[{"datatype":"Practitioner","documentLocation":"resource"},{"datatype":"PractitionerRole","documentLocation":"resource"},{"datatype":"Organization","documentLocation":"resource"}],"path":"PaymentReconciliation.detail.submitter","min":0,"max":"1","short":"Submitter of the request","definition":"The party which submitted the claim or financial transaction.","comment":"","inherited":false},{"name":"response","depth":2,"types":[{"datatype":"Reference","documentLocation":"datatype"}],"referenceTypes":[{"datatype":"Resource"}],"path":"PaymentReconciliation.detail.response","min":0,"max":"1","short":"Response committing to a payment","definition":"A resource, such as a ClaimResponse, which contains a commitment to payment.","comment":"","inherited":false},{"name":"date","depth":2,"types":[{"datatype":"date"}],"path":"PaymentReconciliation.detail.date","min":0,"max":"1","short":"Date of commitment to pay","definition":"The date from the response resource containing a commitment to pay.","comment":"","inherited":false},{"name":"responsible","depth":2,"types":[{"datatype":"Reference","documentLocation":"datatype"}],"referenceTypes":[{"datatype":"PractitionerRole","documentLocation":"resource"}],"path":"PaymentReconciliation.detail.responsible","min":0,"max":"1","short":"Contact for the response","definition":"A reference to the individual who is responsible for inquiries regarding the response and its payment.","comment":"","inherited":false},{"name":"payee","depth":2,"types":[{"datatype":"Reference","documentLocation":"datatype"}],"referenceTypes":[{"datatype":"Practitioner","documentLocation":"resource"},{"datatype":"PractitionerRole","documentLocation":"resource"},{"datatype":"Organization","documentLocation":"resource"}],"path":"PaymentReconciliation.detail.payee","min":0,"max":"1","short":"Recipient of the payment","definition":"The party which is receiving the payment.","comment":"","inherited":false},{"name":"amount","depth":2,"types":[{"datatype":"Money","documentLocation":"datatype"}],"path":"PaymentReconciliation.detail.amount","min":0,"max":"1","short":"Amount allocated to this payable","definition":"The monetary amount allocated from the total payment to the payable.","comment":"","inherited":false},{"name":"formCode","depth":1,"types":[{"datatype":"CodeableConcept","documentLocation":"datatype"}],"path":"PaymentReconciliation.formCode","min":0,"max":"1","short":"Printed form identifier","definition":"A code for the form to be used for printing the content.","comment":"May be needed to identify specific jurisdictional forms.","inherited":false},{"name":"processNote","depth":1,"types":[{"datatype":"BackboneElement"}],"path":"PaymentReconciliation.processNote","min":0,"max":"*","short":"Note concerning processing","definition":"A note that describes or explains the processing in a human readable form.","comment":"","inherited":false},{"name":"id","depth":2,"types":[{"datatype":"string"}],"path":"PaymentReconciliation.processNote.id","min":0,"max":"1","short":"Unique id for inter-element referencing","definition":"Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces.","comment":"","inherited":true,"base":"Element"},{"name":"extension","depth":2,"types":[{"datatype":"Extension","documentLocation":"datatype"}],"path":"PaymentReconciliation.processNote.extension","min":0,"max":"*","short":"Additional content defined by implementations","definition":"May be used to represent additional information that is not part of the basic definition of the element. To make the use of extensions safe and manageable, there is a strict set of governance  applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension.","comment":"There can be no stigma associated with the use of extensions by any application, project, or standard - regardless of the institution or jurisdiction that uses or defines the extensions.  The use of extensions is what allows the FHIR specification to retain a core level of simplicity for everyone.","inherited":true,"base":"Element"},{"name":"modifierExtension","depth":2,"types":[{"datatype":"Extension","documentLocation":"datatype"}],"path":"PaymentReconciliation.processNote.modifierExtension","min":0,"max":"*","short":"Extensions that cannot be ignored even if unrecognized","definition":"May be used to represent additional information that is not part of the basic definition of the element and that modifies the understanding of the element in which it is contained and/or th
1e understanding of the containing element\'s descendants. Usually modifier elements provide negation or qualification. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions.\\n\\nModifier extensions SHALL NOT change the meaning of any elements on Resource or DomainResource (including cannot change the meaning of modifierExtension itself).","comment":"There can be no stigma associated with the use of extensions by any application, project, or standard - regardless of the institution or jurisdiction that uses or defines the extensions.  The use of extensions is what allows the FHIR specification to retain a core level of simplicity for everyone.","inherited":true,"base":"BackboneElement"},{"name":"type","depth":2,"types":[{"datatype":"code"}],"path":"PaymentReconciliation.processNote.type","min":0,"max":"1","short":"display | print | printoper","definition":"The business purpose of the note text.","comment":"","inherited":false},{"name":"text","depth":2,"types":[{"datatype":"string"}],"path":"PaymentReconciliation.processNote.text","min":0,"max":"1","short":"Note explanatory text","definition":"The explanation or description associated with the processing.","comment":"","inherited":false}],"hG":[{"name":"created","type":"date","description":"The creation date","expression":"PaymentReconciliation.created"},{"name":"disposition","type":"string","description":"The contents of the disposition message","expression":"PaymentReconciliation.disposition"},{"name":"identifier","type":"token","description":"The business identifier of the ExplanationOfBenefit","expression":"PaymentReconciliation.identifier"},{"name":"outcome","type":"token","description":"The processing outcome","expression":"PaymentReconciliation.outcome"},{"name":"payment-issuer","type":"reference","description":"The organization which generated this resource","expression":"PaymentReconciliation.paymentIssuer"},{"name":"request","type":"reference","description":"The reference to the claim","expression":"PaymentReconciliation.request"},{"name":"requestor","type":"reference","description":"The reference to the provider who submitted the claim","expression":"PaymentReconciliation.requestor"},{"name":"status","type":"token","description":"The status of the payment reconciliation","expression":"PaymentReconciliation.status"}]}'),l=i(67022);let f={title:"PaymentReconciliation",sidebar_position:104},h="PaymentReconciliation",u={},p=[{value:"Elements",id:"elements",level:2},{value:"Search Parameters",id:"search-parameters",level:2},{value:"Inherited Elements",id:"inherited-elements",level:2}];function m(e){let t={h1:"h1",h2:"h2",header:"header",p:"p",...(0,o.R)(),...e.components};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(t.header,{children:(0,r.jsx)(t.h1,{id:"paymentreconciliation",children:"PaymentReconciliation"})}),"\n",(0,r.jsx)(t.p,{children:"This resource provides the details including amount of a payment and allocates the payment items being paid."}),"\n",(0,r.jsxs)(a.A,{queryString:"section",children:[(0,r.jsxs)(c.A,{value:"schema",label:"Schema",default:!0,children:[(0,r.jsx)(t.h2,{id:"elements",children:"Elements"}),(0,r.jsx)(l.A,{properties:d.qo.filter(e=>!(e.inherited&&e.base.includes("Resource")))}),(0,r.jsx)(t.h2,{id:"search-parameters",children:"Search Parameters"}),(0,r.jsx)(l.b,{searchParams:d.hG}),(0,r.jsx)(t.h2,{id:"inherited-elements",children:"Inherited Elements"}),(0,r.jsx)(l.A,{properties:d.qo.filter(e=>e.inherited&&e.base.includes("Resource"))})]}),(0,r.jsx)(c.A,{value:"usage",label:"Usage",children:(0,r.jsxs)("div",{children:[" ",(0,r.jsx)("a",{name:"scope"})," ",(0,r.jsxs)("p",{children:[" The ",(0,r.jsx)(s.A,{to:"/docs/api/fhir/resources/paymentreconciliation",children:"PaymentReconciliation"})," resource provides the bulk payment details  associated with a payment by the payor for receivable amounts, such as for goods and services rendered by a provider to patients  covered by insurance plans offered by that payor. These are the payment reconciliation details which may align to the individual payment amounts indicated on discrete ",(0,r.jsx)("a",{href:"/docs/api/fhir/resources/claimresponse",children:"ClaimResponses"})," or ",(0,r.jsx)("a",{href:"/docs/api/fhir/resources/invoice",children:"Invoices"})," for example. "]})," ",(0,r.jsxs)("p",{children:[" Bulk payments need to provide a means to associate the amounts paid against specific ",(0,r.jsx)(s.A,{to:"/docs/api/fhir/resources/claim",children:"Claims"}),", ",(0,r.jsx)(s.A,{to:"/docs/api/fhir/resources/invoice",children:"Invoices"}),",  and other financial exchanges and adjustments, to the bulk payment itself in order to reconcile  accounts receivable. "]})," ",(0,r.jsx)("p",{children:"    "})," ",(0,r.jsxs)("p",{children:["The ",(0,r.jsx)(s.A,{to:"/docs/api/fhir/resources/paymentreconciliation",children:"PaymentReconciliation"}),' resource is a "event" resource from a FHIR workflow perspective - see ',(0,r.jsx)("a",{href:"https://www.hl7.org/fhir/workflow.html#event",children:"Workflow Event."})]}
1)," ",(0,r.jsxs)("h3",{class:"self-link-parent",children:[" Additional Information ",(0,r.jsx)("a",{href:"https://www.hl7.org/fhir/paymentreconciliation.html#13.9.1.1",title:"link to here",class:"self-link"})]})," ",(0,r.jsx)("p",{children:" Additional information regarding electronic payment notice content and usage may be found at: "})," ",(0,r.jsxs)("ul",{children:[" ",(0,r.jsxs)("li",{children:[(0,r.jsx)("a",{href:"https://www.hl7.org/fhir/financial-module.html#resource-status",children:"Financial Resource Status Lifecycle"}),": how .status is used in the financial resources."]})," "]})," "]})}),(0,r.jsx)(c.A,{value:"relationships",label:"Relationships",children:(0,r.jsxs)("div",{children:[" ",(0,r.jsxs)("p",{children:[" The ",(0,r.jsx)(s.A,{to:"/docs/api/fhir/resources/paymentreconciliation",children:"PaymentReconciliation"})," resource serves to correlate a payment amount to the adjudicated claim amounts appearing on one or more ",(0,r.jsx)("a",{href:"/docs/api/fhir/resources/claimresponse",children:"ClaimResponses"}),". ",(0,r.jsx)(s.A,{to:"/docs/api/fhir/resources/paymentreconciliation",children:"PaymentReconciliation"})," provides the bulk payment details  associated with a payment by the payor for goods and services rendered by a provider to patients  covered by insurance plans offered by that payor. "]})," ",(0,r.jsxs)("p",{children:[" The ",(0,r.jsx)("a",{href:"/docs/api/fhir/resources/paymentnotice",children:"PaymentNotice"})," resource is used to indicate that a payment has, or is about to occur. The resource is used commonly when tracking of payment occurences is required for regulatory or business purposes.  "]})," ",(0,r.jsxs)("p",{children:[" The ",(0,r.jsx)("a",{href:"/docs/api/fhir/resources/claimresponse",children:"ClaimResponse"})," resource is an insurer's adjudication and/or authorization of a set of healthcare-related goods and services for a patient against the patient's insurance coverages and does not indicate that payment has occured. "]})," ",(0,r.jsxs)("p",{children:[" For reporting out to patients or transferring data to patient centered applications, such as patient health Record (PHR) application, the ",(0,r.jsx)("a",{href:"/docs/api/fhir/resources/explanationofbenefit",children:"ExplanationOfBenefit"}),"  should be used instead. "]})," ",(0,r.jsxs)("p",{children:[" ",(0,r.jsx)("b",{children:"The eClaim domain includes a number of related resources"})," "]})," ",(0,r.jsxs)("table",{border:"1",cellpadding:"1",cellspacing:"2",frame:"box",children:[" ",(0,r.jsxs)("tbody",{children:[(0,r.jsxs)("tr",{children:[" ",(0,r.jsx)("td",{children:"PaymentReconciliation"})," ",(0,r.jsx)("td",{children:"Provides the bulk payment details  associated with a payment by the payor for goods and services rendered by a provider to patients  covered by insurance plans offered by that payor."})," "]})," ",(0,r.jsxs)("tr",{children:[" ",(0,r.jsx)("td",{children:(0,r.jsx)("a",{href:"/docs/api/fhir/resources/claimresponse",children:"ClaimResponse"})})," ",(0,r.jsxs)("td",{children:["A payor's adjudication and/or authorization response to the suite of services provided in a ",(0,r.jsx)(s.A,{to:"/docs/api/fhir/resources/claim",children:"Claim"}),". Typically the ",(0,r.jsx)(s.A,{to:"/docs/api/fhir/resources/claimresponse",children:"ClaimResponse"})," references the ",(0,r.jsx)(s.A,{to:"/docs/api/fhir/resources/claim",children:"Claim"})," but does not duplicate the clinical or financial information provided in the claim."]})," "]})," ",(0,r.jsxs)("tr",{children:[" ",(0,r.jsx)("td",{children:(0,r.jsx)("a",{href:"/docs/api/fhir/resources/explanationofbenefit",children:"ExplanationOfBenefit"})})," ",(0,r.jsxs)("td",{children:["This resource combines the information from the ",(0,r.jsx)(s.A,{to:"/docs/api/fhir/resources/claim",children:"Claim"})," and the ",(0,r.jsx)(s.A,{to:"/docs/api/fhir/resources/claimresponse",children:"ClaimResponse"}),", stripping out any provider or payor proprietary information, into a unified information model  suitable for use for: patient reporting; transferring information to a ",(0,r.jsx)(s.A,{to:"/docs/api/fhir/resources/patient",children:"Patient"})," Health Record system; and, supporting complete claim and adjudication information exchange  with regulatory and analytics organizations and other parts of the provider's organization. "]})," "]})," ",(0,r.jsxs)("tr",{children:[" ",(0,r.jsx)("td",{children:(0,r.jsx)("a",{href:"/docs/api/fhir/resources/paymentnotice",children:"PaymentNotice"})})," ",(0,r.jsx)("td",{children:"An indication that a payment has occured, is about to occur, or has been cancelled."})," "]})," "]})]})," "]})}),(0,r.jsx)(c.A,{value:"referencedBy",label:"Referenced By",children:(0,r.jsx)("ul",{children:(0,r.jsx)("li",{children:(0,r.jsx)("a",{href:"/docs/api/fhir/resources/paymentnotice",children:"PaymentNotice"})})})})]})]})}function y(e={}){let{wrapper:t}={...(0,o.R)(),...e.components};return t?(0,r.jsx)(t,{...e,children:(0,r.jsx)(m,{...e})}):m(e)}},67022(e,t,i){i.d(t,{A:()=>s,b:()=>a});var n=i(31085),r=i(39372),o=i(58586);function s(e){let{properties:t}=e;return t=t.filter(e=>e.depth>0),(0,n.jsxs)("table",{children:[(0,n.jsx)("thead",{children:(0,n.jsxs)("tr",{children:[(0,n.jsx)("th",{children:"Name"}),(0,n.jsx)("th",{children:"Required"}),(0,n.jsx)("th",{children:"Type"}),(0,n.jsx)("th",{children:"Description"})]})}),(0,n.jsx)("tbody",{children:t.map(e=>{var t;return(0,n.jsxs)("tr",{children:[(0,n.jsxs)("td",{className:"propertyNameColumn_lWqY",children:[e.depth>1?(0,n.jsx)("span",{className:"indentation_g2Dh",style:{marginLeft:`calc(${e.depth-1} * 1.5rem)`}}):"",(0,n.jsx)("span",{style:e.name.length>20?{fontSize:"calc(0.85 * 14px)"}:{},children:e.name})]}),(0,n.jsx)("td",{className:"required_B8Qh",children:e.min>0?"\u2713":""}),(0,n.jsxs)("td",{children:["BackboneElement"===(t=e).types[0].datatype?(0,n.jsx)(n.Fragment,{children:(0,r.ayp)(t.path.split("."))}):(0,n.jsx)("span",{style:{whiteSpace:"pre-wrap"},children:t.types.map(e=>{var i;let r;return"Reference"===e.datatype?(r=(i=t.referenceTypes||[]).length>2,(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{children:"Reference<"}),i.map((e,t)=>(0,n.jsxs)(n.Fragment,{children:[c(e,`${0===t&&r?"\n  ":""}${e.datatype}`),(0,n.jsx)("span",{children:t<i.length-1?i&&r?"\n |  ":" | ":r?"\n":""},`reference-separator-${e.datatype}`)]})),(0,n.jsx)("span",{children:">"})]})):c(e)}).map((e,i,r)=>(0,n.jsxs)("span",{className:"propertyTypeColumn_ysv_",children:[e,i<r.length-1?", ":""]},`${t.path}-type-${i}`))},`row-${t.path}`),"*"===e.max?"[]":""]}),(0,n.jsxs)("td",{children:[(0,n.jsx)("p",{children:e.short}),(0,n.jsxs)("details",{open:!1,children:[(0,n.jsx)("summary",{children:"Details"}),(0,n.jsx)(d,{content:e.definition}),(0,n.jsx)(d,{content:e.comment})]})]})]},e.path)})})]})}function a(e){let t=e.searchParams;return t&&0!==t.length?(0,n.jsxs)("table",{children:[(0,n.jsx)("thead",{children:(0,n.jsxs)("tr",{children:[(0,n.jsx)("th",{children:"Name"}),(0,n.jsx)("th",{children:"Type"}),(0,n.jsx)("th",{children:"Description"}),(0,n.jsx)("th",{children:"Expression"})]})}),(0,n.jsx)("tbody",{children:t.map(e=>(0,n.jsxs)("tr",{children:[(0,n.jsx)("td",{children:e.name}),(0,n.jsx)("td",{children:e.type}),(0,n.jsx)("td",{children:e.description}),(0,n.jsx)("td",{children:e.expression})]},e.name))})]}):(0,n.jsx)("em",{children:"None"})}function c(e,t){var i;return(t=t||e.datatype,e.documentLocation)?(0,n.jsx)("a",{href:`../${("medplum"!==(i=e.documentLocation)&&i.endsWith("e")?`${i}s`:i).toLowerCase()}/${e.datatype.toLowerCase()}`,children:t},e.datatype):(0,n.jsx)(n.Fragment,{children:t})}function d({content:e}){if(!e)return null;let t=(0,o.xI)(e,{async:!1});return(0,n.jsx)("div",{dangerouslySetInnerHTML:{__html:t}})}},39372(e,t,i){i.d(t,{Go6:()=>ec,H4N:()=>f,Pzm:()=>h,RZV:()=>ey,UtL:()=>eT,ayp:()=>eR,cME:()=>tc,kAL:()=>ei,qKc:()=>s,ypx:()=>u});var n,r=Object.defineProperty,o=(e,t,i)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?r(e,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[n]=i}
1,s=class{constructor(e=10){o(this,"max"),o(this,"cache"),this.max=e,this.cache=new Map}clear(){this.cache.clear()}get(e){let 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}},a=class{constructor(e,t){o(this,"operator"),o(this,"child"),this.operator=e,this.child=t}toString(){return`${this.operator}(${this.child.toString()})`}},c=class{constructor(e,t,i){o(this,"operator"),o(this,"left"),o(this,"right"),this.operator=e,this.left=t,this.right=i}toString(){return`(${this.left.toString()} ${this.operator} ${this.right.toString()})`}},d=class{constructor(){o(this,"prefixParselets",{}),o(this,"infixParselets",{})}registerInfix(e,t){return this.infixParselets[e]=t,this}registerPrefix(e,t){return this.prefixParselets[e]=t,this}prefix(e,t,i){return this.registerPrefix(e,{parse:(e,n)=>i(n,e.consumeAndParse(t))})}infixLeft(e,t,i){return this.registerInfix(e,{parse:(e,n,r)=>i(n,r,e.consumeAndParse(t)),precedence:t})}construct(e){return new l(e,this.prefixParselets,this.infixParselets)}},l=class{constructor(e,t,i){o(this,"tokens"),o(this,"prefixParselets"),o(this,"infixParselets"),this.tokens=e,this.prefixParselets=t,this.infixParselets=i}hasMore(){return this.tokens.length>0}match(e){return this.peek()?.id===e&&(this.consume(),!0)}consumeAndParse(e=1/0){let t=this.consume(),i=this.prefixParselets[t.id];if(!i)throw Error(`Parse error at "${t.value}" (line ${t.line}, column ${t.column}). No matching prefix parselet.`);let n=i.parse(this,t);for(;e>this.getPrecedence();){let e=this.consume();n=this.getInfixParselet(e).parse(this,n,e)}return n}getPrecedence(){let e=this.peek();if(!e)return 1/0;let 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){let t=this.peek();throw Error(`Expected ${e} but got "${t.id}" (${t.value}) at line ${t.line} column ${t.column}.`)}if(t&&this.peek()?.value!==t){let 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]}},f="http://unitsofmeasure.org",h="http://snomed.info/sct",u="http://hl7.org",p={resourceType:"OperationOutcome",id:"not-found",issue:[{severity:"error",code:"not-found",details:{text:"Not found"}}]},m={resourceType:"OperationOutcome",id:"unauthorized",issue:[{severity:"error",code:"login",details:{text:"Unauthorized"}}]},y={...m,issue:[...m.issue,{severity:"error",code:"expired",details:{text:"Token expired"}}]},g={...m,issue:[...m.issue,{severity:"error",code:"invalid",details:{text:"Token not issued for this audience"}}]};function x(e,t){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"invalid",details:{text:e},...t?{expression:function(e){if(void 0!==e)return Array.isArray(e)?e:[e]}(t)}:void 0}]}}function v(e,t,i,n){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:i??"structure",details:{text:e},...t?{expression:t}:void 0,...n?{diagnostics:n}:void 0}]}}function b(e){return"object"==typeof e&&null!==e&&"OperationOutcome"===e.resourceType}var w=class extends null{constructor(e,t){super(S(e),t),o(this,"outcome"),this.name="OperationOutcomeError",this.outcome=e}};function E(e){return e instanceof w?e.outcome:b(e)?e:x(T(e))}function T(e){return e?"string"==typeof e?e:e&&"object"==typeof e&&(e instanceof Error||"u">typeof DOMException&&e instanceof DOMException||"[object Error]"===Object.prototype.toString.call(e))?e.message:b(e)?S(e):"object"==typeof e&&"code"in e&&"string"==typeof e.code?e.code:JSON.stringify(e):"Unknown error"}function S(e){let t=e.issue?.map(C)??[];return t.length>0?t.join("; "):"Unknown error"}function C(e){let t;return t=e.details?.text?e.diagnostics?`${e.details.text} (${e.diagnostics})`:e.details.text:e.diagnostics?e.diagnostics:"Unknown error",e.expression?.length&&(t+=` (${e.expression.join(", ")})`),t}var R=function(e){let t=Object.create(null);
1for(let[i,n]of Object.entries(e))t[i]={name:i,type:i,path:i,elements:Object.fromEntries(Object.entries(n.elements).map(([e,t])=>[e,function(e,t){let i=t.max&&t.max===Number.MAX_SAFE_INTEGER?1/0:t.max;return{path:e,description:"",type:t.type??[],min:t.min??0,max:i??1,isArray:!!i&&i>1,constraints:[]}}(e,t)])),constraints:[],innerTypes:[]};return t}({Element:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]}}},BackboneElement:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},modifierExtension:{max:0x1fffffffffffff,type:[{code:"Extension"}]}}},Address:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},type:{type:[{code:"code"}]},text:{type:[{code:"string"}]},line:{max:0x1fffffffffffff,type:[{code:"string"}]},city:{type:[{code:"string"}]},district:{type:[{code:"string"}]},state:{type:[{code:"string"}]},postalCode:{type:[{code:"string"}]},country:{type:[{code:"string"}]},period:{type:[{code:"Period"}]}}},Age:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Annotation:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},"author[x]":{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Organization"]},{code:"string"}]},time:{type:[{code:"dateTime"}]},text:{min:1,type:[{code:"markdown"}]}}},Attachment:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},contentType:{type:[{code:"code"}]},language:{type:[{code:"code"}]},data:{type:[{code:"base64Binary"}]},url:{type:[{code:"url"}]},size:{type:[{code:"unsignedInt"}]},hash:{type:[{code:"base64Binary"}]},title:{type:[{code:"string"}]},creation:{type:[{code:"dateTime"}]}}},CodeableConcept:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},coding:{max:0x1fffffffffffff,type:[{code:"Coding"}]},text:{type:[{code:"string"}]}}},Coding:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},system:{type:[{code:"uri"}]},version:{type:[{code:"string"}]},code:{type:[{code:"code"}]},display:{type:[{code:"string"}]},userSelected:{type:[{code:"boolean"}]}}},ContactDetail:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},name:{type:[{code:"string"}]},telecom:{max:0x1fffffffffffff,type:[{code:"ContactPoint"}]}}},ContactPoint:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},system:{type:[{code:"code"}]},value:{type:[{code:"string"}]},use:{type:[{code:"code"}]},rank:{type:[{code:"positiveInt"}]},period:{type:[{code:"Period"}]}}},Contributor:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},name:{min:1,type:[{code:"string"}]},contact:{max:0x1fffffffffffff,type:[{code:"ContactDetail"}]}}},Count:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},DataRequirement:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},profile:{max:0x1fffffffffffff,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:0x1fffffffffffff,type:[{code:"string"}]},codeFilter:{max:0x1fffffffffffff,type:[{code:"DataRequirementCodeFilter"}]},dateFilter:{max:0x1fffffffffffff,type:[{code:"DataRequirementDateFilter"}]},limit:{type:[{code:"positiveInt"}]},sort:{max:0x1fffffffffffff,type:[{code:"DataRequirementSort"}]}}},DataRequirementCodeFilter:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},valueSet:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/ValueSet"]}]},code:{max:0x1fffffffffffff,type:[{code:"Coding"}]}}},DataRequirementDateFilter:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},"value[x]":{type:[{code:"dateTime"},{code:"Period"},{code:"Duration"}]}}},DataRequirementSort:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},direction:{min:1,type:[{code:"code"}]}}},Distance:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Dosage:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},modifierExtension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},sequence:{type:[{code:"integer"}]},text:{type:[{code:"string"}]},additionalInstruction:{max:0x1fffffffffffff,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:0x1fffffffffffff,type:[{code:"DosageDoseAndRate"}]},maxDosePerPeriod:{type:[{code:"Ratio"}]},maxDosePerAdministration:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},maxDosePerLifetime:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},DosageDoseAndRate:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},type:{type:[{code:"CodeableConcept"}]},"dose[x]":{type:[{code:"Range"},{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},"rate[x]":{type:[{code:"Ratio"},{code:"Range"},{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},Duration:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},ElementDefinition:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},modifierExtension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},representation:{max:0x1fffffffffffff,type:[{code:"code"}]},sliceName:{type:[{code:"string"}]},sliceIsConstraining:{type:[{code:"boolean"}]},label:{type:[{code:"string"}]},code:{max:0x1fffffffffffff,type:[{code:"Coding"}]},slicing:{type:[{code:"ElementDefinitionSlicing"}]},short:{type:[{code:"string"}]},definition:{type:[{code:"markdown"}]},comment:{type:[{code:"markdown"}]},requirements:{type:[{code:"markdown"}]},alias:{max:0x1fffffffffffff,type:[{code:"string"}]},min:{type:[{code:"unsignedInt"}]},max:{type:[{code:"string"}]},base:{type:[{code:"ElementDefinitionBase"}]},contentReference:{type:[{code:"uri"}]},type:{max:0x1fffffffffffff,type:[{code:"ElementDefinitionType"}]},"defaultValue[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},meaningWhenMissing:{type:[{code:"markdown"}]},orderMeaning:{type:[{code:"string"}]},"fixed[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},"pattern[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},example:{max:0x1fffffffffffff,type:[{code:"ElementDefinitionExample"}]},"minValue[x]":{type:[{code:"date"},{code:"dateTime"},{code:"instant"},{code:"time"},{code:"decimal"},{code:"integer"},{code:"positiveInt"},{code:"unsignedInt"},{code:"Quantity"}]},"maxValue[x]":{type:[{code:"date"},{code:"dateTime"},{code:"instant"},{code:"time"},{code:"decimal"},{code:"integer"},{code:"positiveInt"},{code:"unsignedInt"},{code:"Quantity"}]},maxLength:{type:[{code:"integer"}]},condition:{max:0x1fffffffffffff,type:[{code:"id"}]},constraint:{max:0x1fffffffffffff,type:[{code:"ElementDefinitionConstraint"}]},mustSupport:{type:[{code:"boolean"}]},isModifier:{type:[{code:"boolean"}]},isModifierReason:{type:[{code:"string"}]},isSummary:{type:[{code:"boolean"}]},binding:{type:[{code:"ElementDefinitionBinding"}]},mapping:{max:0x1fffffffffffff,type:[{code:"ElementDefinitionMapping"}]}}},ElementDefinitionSlicingDiscriminator:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},path:{min:1,type:[{code:"string"}]}}},ElementDefinitionSlicing:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},discriminator:{max:0x1fffffffffffff,type:[{code:"ElementDefinitionSlicingDiscriminator"}]},description:{type:[{code:"string"}]},ordered:{type:[{code:"boolean"}]},rules:{min:1,type:[{code:"code"}]}}},ElementDefinitionBase:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},min:{min:1,type:[{code:"unsignedInt"}]},max:{min:1,type:[{code:"string"}]}}},ElementDefinitionType:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},code:{min:1,type:[{code:"uri"}]},profile:{max:0x1fffffffffffff,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},targetProfile:{max:0x1fffffffffffff,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},aggregation:{max:0x1fffffffffffff,type:[{code:"code"}]},versioning:{type:[{code:"code"}]}}},ElementDefinitionExample:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},label:{min:1,type:[{code:"string"}]},"value[x]":{min:1,type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]}}},ElementDefinitionConstraint:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},key:{min:1,type:[{code:"id"}]},requirements:{type:[{code:"string"}]},severity:{min:1,type:[{code:"code"}]},human:{min:1,type:[{code:"string"}]},expression:{type:[{code:"string"}]},xpath:{type:[{code:"string"}]},source:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]}}},ElementDefinitionBinding:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},strength:{min:1,type:[{code:"code"}]},description:{type:[{code:"string"}]},valueSet:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/ValueSet"]}]}}},ElementDefinitionMapping:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},identity:{min:1,type:[{code:"id"}]},language:{type:[{code:"code"}]},map:{min:1,type:[{code:"string"}]},comment:{type:[{code:"string"}]}}},Expression:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},description:{type:[{code:"string"}]},name:{type:[{code:"id"}]},language:{min:1,type:[{code:"code"}]},expression:{type:[{code:"string"}]},reference:{type:[{code:"uri"}]}}},Extension:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},url:{min:1,type:[{code:"uri"}]},"value[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"
1},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]}}},HumanName:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},text:{type:[{code:"string"}]},family:{type:[{code:"string"}]},given:{max:0x1fffffffffffff,type:[{code:"string"}]},prefix:{max:0x1fffffffffffff,type:[{code:"string"}]},suffix:{max:0x1fffffffffffff,type:[{code:"string"}]},period:{type:[{code:"Period"}]}}},Identifier:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},type:{type:[{code:"CodeableConcept"}]},system:{type:[{code:"uri"}]},value:{type:[{code:"string"}]},period:{type:[{code:"Period"}]},assigner:{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Organization"]}]}}},MarketingStatus:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},modifierExtension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},country:{min:1,type:[{code:"CodeableConcept"}]},jurisdiction:{type:[{code:"CodeableConcept"}]},status:{min:1,type:[{code:"CodeableConcept"}]},dateRange:{min:1,type:[{code:"Period"}]},restoreDate:{type:[{code:"dateTime"}]}}},Meta:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},versionId:{type:[{code:"id"}]},lastUpdated:{type:[{code:"instant"}]},source:{type:[{code:"uri"}]},profile:{max:0x1fffffffffffff,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]},security:{max:0x1fffffffffffff,type:[{code:"Coding"}]},tag:{max:0x1fffffffffffff,type:[{code:"Coding"}]},project:{type:[{code:"uri"}]},author:{type:[{code:"Reference"}]},onBehalfOf:{type:[{code:"Reference"}]},account:{type:[{code:"Reference"}]},accounts:{max:0x1fffffffffffff,type:[{code:"Reference"}]},compartment:{max:0x1fffffffffffff,type:[{code:"Reference"}]},deleted:{type:[{code:"boolean"}]}}},Money:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},currency:{type:[{code:"code"}]}}},Narrative:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},status:{min:1,type:[{code:"code"}]},div:{min:1,type:[{code:"xhtml"}]}}},ParameterDefinition:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},name:{type:[{code:"code"}]},use:{min:1,type:[{code:"code"}]},min:{type:[{code:"integer"}]},max:{type:[{code:"string"}]},documentation:{type:[{code:"string"}]},type:{min:1,type:[{code:"code"}]},profile:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]}}},Period:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},start:{type:[{code:"dateTime"}]},end:{type:[{code:"dateTime"}]}}},Population:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},modifierExtension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},"age[x]":{type:[{code:"Range"},{code:"CodeableConcept"}]},gender:{type:[{code:"CodeableConcept"}]},race:{type:[{code:"CodeableConcept"}]},physiologicalCondition:{type:[{code:"CodeableConcept"}]}}},ProdCharacteristic:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},modifierExtension:{max:0x1fffffffffffff,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:0x1fffffffffffff,type:[{code:"string"}]},imprint:{max:0x1fffffffffffff,type:[{code:"string"}]},image:{max:0x1fffffffffffff,type:[{code:"Attachment"}]},scoring:{type:[{code:"CodeableConcept"}]}}},ProductShelfLife:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},modifierExtension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},identifier:{type:[{code:"Identifier"}]},type:{min:1,type:[{code:"CodeableConcept"}]},period:{min:1,type:[{code:"Quantity"}]},specialPrecautionsForStorage:{max:0x1fffffffffffff,type:[{code:"CodeableConcept"}]}}},Quantity:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Range:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},low:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},high:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},Ratio:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},numerator:{type:[{code:"Quantity"}]},denominator:{type:[{code:"Quantity"}]}}},Reference:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},reference:{type:[{code:"string"}]},type:{type:[{code:"uri"}]},identifier:{type:[{code:"Identifier"}]},display:{type:[{code:"string"}]}}},RelatedArtifact:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},label:{type:[{code:"string"}]},display:{type:[{code:"string"}]},citation:{type:[{code:"markdown"}]},url:{type:[{code:"url"}]},document:{type:[{code:"Attachment"}]},resource:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/Resource"]}]}}},SampledData:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},origin:{min:1,type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},period:{min:1,type:[{code:"decimal"}]},factor:{type:[{code:"decimal"}]},lowerLimit:{type:[{code:"decimal"}]},upperLimit:{type:[{code:"decimal"}]},dimensions:{min:1,type:[{code:"positiveInt"}]},data:{type:[{code:"string"}]}}},Signature:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},type:{min:1,max:0x1fffffffffffff,type:[{code:"Coding"}]},when:{min:1,type:[{code:"instant"}]},who:{min:1,type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/PractitionerRole","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/Device","http://hl7.org/fhir/StructureDefinition/Organization"]}]},onBehalfOf:{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/PractitionerRole","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/Device","http://hl7.org/fhir/StructureDefinition/Organization"]}]},targetFormat:{type:[{code:"code"}]},sigFormat:{type:[{code:"code"}]},data:{type:[{code:"base64Binary"}]}}},SubstanceAmount:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},modifierExtension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},"amount[x]":{type:[{code:"Quantity"},{code:"Range"},{code:"string"}]},amountType:{type:[{code:"CodeableConcept"}]},amountText:{type:[{code:"string"}]},referenceRange:{type:[{code:"SubstanceAmountReferenceRange"}]}}},SubstanceAmountReferenceRange:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},lowLimit:{type:[{code:"Quantity"}]}
1,highLimit:{type:[{code:"Quantity"}]}}},Timing:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},modifierExtension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},event:{max:0x1fffffffffffff,type:[{code:"dateTime"}]},repeat:{type:[{code:"TimingRepeat"}]},code:{type:[{code:"CodeableConcept"}]}}},TimingRepeat:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,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:0x1fffffffffffff,type:[{code:"code"}]},timeOfDay:{max:0x1fffffffffffff,type:[{code:"time"}]},when:{max:0x1fffffffffffff,type:[{code:"code"}]},offset:{type:[{code:"unsignedInt"}]}}},TriggerDefinition:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,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:0x1fffffffffffff,type:[{code:"DataRequirement"}]},condition:{type:[{code:"Expression"}]}}},UsageContext:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},code:{min:1,type:[{code:"Coding"}]},"value[x]":{min:1,type:[{code:"CodeableConcept"},{code:"Quantity"},{code:"Range"},{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/PlanDefinition","http://hl7.org/fhir/StructureDefinition/ResearchStudy","http://hl7.org/fhir/StructureDefinition/InsurancePlan","http://hl7.org/fhir/StructureDefinition/HealthcareService","http://hl7.org/fhir/StructureDefinition/Group","http://hl7.org/fhir/StructureDefinition/Location","http://hl7.org/fhir/StructureDefinition/Organization"]}]}}},MoneyQuantity:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},SimpleQuantity:{elements:{id:{type:[{code:"string"}]},extension:{max:0x1fffffffffffff,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{max:0,type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},IdentityProvider:{elements:{issuer:{type:[{code:"string"}]},audience:{type:[{code:"string"}]},jwksUrl:{type:[{code:"string"}]},authorizeUrl:{type:[{code:"string"}]},tokenUrl:{type:[{code:"string"}]},tokenAuthMethod:{type:[{code:"code"}]},userInfoUrl:{type:[{code:"string"}]},userInfoMode:{type:[{code:"code"}]},userInfoApiKey:{type:[{code:"string"}]},clientId:{type:[{code:"string"}]},clientSecret:{type:[{code:"string"}]},usePkce:{type:[{code:"boolean"}]},useSubject:{type:[{code:"boolean"}]},identitySource:{type:[{code:"code"}]},identityMappingMode:{type:[{code:"code"}]}}}}),P=Object.create(null),k=Object.create(null);function D(e){let t;return(t=k[e])||(t=k[e]=Object.create(null)),t}function A(e){let t=(Array.isArray(e)?e:e.entry?.map(e=>e.resource)??[]).filter(e=>e?.resourceType==="StructureDefinition");for(let e of(function(e){for(let t of Array.isArray(e)?e:e.entry?.map(e=>e.resource)??[])t?.resourceType==="StructureDefinition"&&"resource"===t.kind&&eS(t.type)}(t),t))_(e)}function _(e){if(!e?.name)throw Error("Failed loading StructureDefinition from bundle");if("StructureDefinition"!==e.resourceType)return;let t=new L(e).parse(),i=null[e.url],n,r;for(let o of(i?(n=R,r=i):(n=e.url===`http://hl7.org/fhir/StructureDefinition/${e.type}`||e.url===`https://medplum.com/fhir/StructureDefinition/${e.type}`||e.type?.startsWith("http://")||e.type?.startsWith("https://")?R:D(e.url),r=e.type),n[r]=t,t.innerTypes))o.parentType=t,n[o.name]=o;P[e.url]=t}var L=class{constructor(e){var t;let i;if(o(this,"root"),o(this,"elements"),o(this,"elementIndex"),o(this,"index"),o(this,"resourceSchema"),o(this,"slicingContext"),o(this,"innerTypes"),o(this,"backboneContext"),!e.snapshot?.element||0===e.snapshot.element.length)throw Error(`No snapshot defined for StructureDefinition '${e.name}'`);this.root=e.snapshot.element[0],this.elements=e.snapshot.element.slice(1),this.elementIndex=Object.create(null),this.index=0,this.resourceSchema={name:e.name,path:this.root.path,title:e.title,type:e.type,url:e.url,ver
1sion:e.version,kind:e.kind,description:(i=(t=e).description,i?.startsWith(`Base StructureDefinition for ${t.name} Type: `)&&(i=i.substring(`Base StructureDefinition for ${t.name} Type: `.length)),i),elements:{},constraints:this.parseElementDefinition(this.root).constraints,innerTypes:[],summaryProperties:new Set,mandatoryProperties:new Set},this.innerTypes=[]}parse(){let e=this.next();for(;e;){if(e.sliceName)this.parseSliceStart(e);else if(e.id?.includes(":")){if(this.slicingContext?.current){let t=I(e,this.slicingContext.path);this.slicingContext.current.elements[t]=this.parseElementDefinition(e)}}else{let t=this.parseElementDefinition(e);this.checkFieldEnter(e,t);let i=this.backboneContext;for(;i;){if(e.path?.startsWith(i.path+".")){i.type.elements[I(e,i.path)]=t;break}i=i.parent}if(!i){let i=I(e,this.root.path);e.isSummary&&this.resourceSchema.summaryProperties?.add(i.replace("[x]","")),t.min>0&&this.resourceSchema.mandatoryProperties?.add(i.replace("[x]","")),this.resourceSchema.elements[i]=t}this.checkFieldExit(e)}e=this.next()}return this.checkFieldExit(),this.innerTypes.length>0&&(this.resourceSchema.innerTypes=this.innerTypes),this.resourceSchema}checkFieldEnter(e,t){this.isInnerType(e)&&this.enterInnerType(e),this.slicingContext&&!U(this.slicingContext.path,e?.path)&&(this.slicingContext=void 0),e.slicing&&!this.slicingContext&&this.enterSlice(e,t)}enterInnerType(e){for(;this.backboneContext&&!U(this.backboneContext?.path,e.path);)this.innerTypes.push(this.backboneContext.type),this.backboneContext=this.backboneContext.parent;let t=eC(e);this.backboneContext={type:{name:t,type:t,path:e.path,title:e.label,description:e.definition,elements:{},constraints:this.parseElementDefinition(e).constraints,innerTypes:[]},path:e.path,parent:U(this.backboneContext?.path,e.path)?this.backboneContext:this.backboneContext?.parent}}enterSlice(e,t){var i;let n;i=e,n=i.slicing?.discriminator,i.type?.some(e=>"Extension"===e.code)&&n?.length===1&&"value"===n[0].type&&"url"===n[0].path&&!this.peek()?.sliceName||(t.slicing={discriminator:(e.slicing?.discriminator??[]).map(e=>{if("value"!==e.type&&"pattern"!==e.type&&"type"!==e.type)throw Error(`Unsupported slicing discriminator type: ${e.type}`);return{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){if(this.backboneContext&&!U(this.backboneContext.path,e?.path))if(this.backboneContext.parent)do this.innerTypes.push(this.backboneContext.type),this.backboneContext=this.backboneContext.parent;while(this.backboneContext&&!U(this.backboneContext.path,e?.path))else this.innerTypes.push(this.backboneContext.type),this.backboneContext=void 0}next(){let e=this.peek();if(e)return this.index++,e}peek(){let e=this.elements[this.index];if(e){if(this.elementIndex[e.path??""]=e,e.contentReference){let t=e.contentReference.slice(e.contentReference.indexOf("#")+1),i=this.elementIndex[t];return i?{...i,id:e.id,path:e.path,min:e.min??i.min,max:e.max??i.max,base:{path:i.base?.path??t,min:e.base?.min??i.base?.min??i.min,max:e.base?.max??i.base?.max??i.max},contentReference:e.contentReference,definition:e.definition}:void 0}return e}}isInnerType(e){let t=this.peek();return!!(U(e?.path,t?.path)&&e.type?.some(e=>["BackboneElement","Element"].includes(e.code)))}parseSliceStart(e){if(!this.slicingContext)throw Error(`Invalid slice start before discriminator: ${e.sliceName} (${e.id})`);this.slicingContext.current={...this.parseElementDefinition(e),name:e.sliceName??"",definition:e.definition,elements:{}},this.slicingContext.field.slices.push(this.slicingContext.current)}parseElementDefinitionType(e){return(e.type??[]).map(t=>{let i;return("BackboneElement"===t.code||"Element"===t.code)&&(i=eC(e)),i||(i=eo(t,"http://hl7.org/fhir/StructureDefinition/structuredefinition-fhir-type")?.valueUrl),i||(i=t.code??""),{code:i,targetProfile:t.targetProfile,profile:t.profile}})}parseElementDefinition(e){let t=j(e.max),i=e.base?.max?j(e.base.max):t,n={type:"ElementDefinition",value:e};return{description:e.definition||"",path:e.path||e.base?.path||"",min:e.min??0,max:t,isArray:i>1,constraints:(e.constraint??[]).map(e=>({key:e.key??"",severity:e.severity??"error",expression:e.expression??"",description:e.human??""})),type:this.parseElementDefinitionType(e),fixed:O(F(n,"fixed[x]")),pattern:O(F(n,"pattern[x]")),binding:e.binding}}};function j(e){return"*"===e?1/0:Number.parseInt(e,10)}function I(e,t=""){var i,n;return i=e.path,n=t,i?n&&i.startsWith(n)?i.substring(n.length+1):i:""}function U(e,t){return!!e&&!!t&&(t.startsWith(e+".")||t===e)}function O(e){return Array.isArray(e)&&e.length>0?e[0]:es(e)?void 0:e}new s(1e3);var M=/^(\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]))?)?$/,q=/^(\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)?)?)?$/;function N(e){return[{type:eT.boolean,value:e}]}function $(e){return null==e?{type:"undefined",value:void 0}:Number.isSafeInteger(e)?{type:eT.integer,value:e}:"number"==typeof e?{type:eT.decimal,value:e}:"boolean"==typeof e?{type:eT.boolean,value:e}:"string"==typeof e?{type:eT.string,value:e}:X(e)?{type:eT.Quantity,value:e}:ek(e)?{type:e.resourceType,value:e}:ef(e)?{type:eT.CodeableConcept,value:e}:el(e)?{type:eT.Coding,value:e}:{type:eT.BackboneElement,value:e}}function B(e){return 0!==e.length&&!!e[0].value}function W(e,t){if(0!==e.length){if(1===e.length&&(!t||e[0].type===t))return e[0];{let i=t?` of type ${t}`:"";throw Error(`Expected singleton${i}, but found ${JSON.stringify(e)}`)}}}function F(e,t,i){if(!e.value)return;let n=function(e,t,i){let n=function(e,t){if(t){let i=D(t)[e];if(i)return i}return R[e]}(e,i);if(n)return function(e,t){let i=e[t]??e[t+"[x]"];if(i)return i;for(let i=0;i<t.length;i++){let n=t[i];if(n>="A"&&n<="Z"){let n=e[t.slice(0,i)+"[x]"];if(n)return n}}}(n.elements,t)}(e.type,t,i?.profileUrl);return n?function(e,t){let i=e.value,n=t.type;if(!n||0===n.length)return;let r,o="undefined",s,a=t.path.lastIndexOf("."),c=t.path.substring(a+1),d=c,l=!1;for(let e of(c.endsWith("[x]")&&(d=c.substring(0,c.length-3),l=!0),n)){let t=d;if(l&&(t+=ep(e.code)),r=i[t],s=i["_"+t],void 0!==r||void 0!==s){o=e.code;break}}if(s)if(Array.isArray(r)){r=r.slice();for(let e=0;e<Math.max(r.length,s.length);e++)r[e]=et(r[e],s[e])}else if(!r&&Array.isArray(s)){r=s.slice();for(let e=0;e<s.length;e++)r[e]=et(void 0,s[e])}else r=et(r,s);if(!es(r))return("Element"===o||"BackboneElement"===o)&&(o=t.type[0].code),Array.isArray(r)?r.map(e=>H(e,o)):H(r,o)}(e,n):function(e,t){let i,n=e.value;if(n&&"object"==typeof n){if(t in n){let e=n[t];i=Array.isArray(e)?e.map($):$(e)}else{let e=t.endsWith("[x]")?t.substring(0,t.length-3):t;for(let t of Object.values(eT)){let r=e+ep(t);if(r in n){let e=n[r];i=Array.isArray(e)?e.map(e=>({type:t,value:e})):{type:t,value:e};break}}}if(Array.isArray(i)){if(0===i.length||es(i[0]))return}else if(es(i))return;return i}}(e,t)}function H(e,t){return"Resource"===t&&ek(e)&&(t=e.resourceType),{type:t,value:e}}function Q(e){let t=[];for(let i of e){let e=!1;for(let n of t)if(B(z(i,n))){e=!0;break}e||t.push(i)}return t}function z(e,t){let i=e.value?.valueOf(),n=t.value?.valueOf();return"number"==typeof i&&"number"==typeof n?N(1e-8>Math.abs(i-n)):X(i)&&X(n)?N(Y(i,n)):N("object"==typeof i&&"object"==typeof n?Z(e,t):i===n)}function J(e,t){return 0===e.length&&0===t.length?N(!0):e.length!==t.length?N(!1):(e.sort(G),t.sort(G),N(e.every((e,i)=>B(function(e,t){let{type:i,value:n}=e,{type:r,value:o}=t,s=n?.valueOf(),a=o?.valueOf();return"number"==typeof s&&"number"==typeof a?N(.01>Math.abs(s-a)):X(s)&&X(a)?N(Y(s,a)):N("Coding"===i&&"Coding"===r?"object"==typeof s&&"object"==typeof a&&s.c
1ode===a.code&&s.system===a.system:"object"==typeof s&&"object"==typeof a?Z({...s,id:void 0},{...a,id:void 0}):"string"==typeof s&&"string"==typeof a?s.toLowerCase()===a.toLowerCase():s===a)}(e,t[i])))))}function G(e,t){let i=e.value?.valueOf(),n=t.value?.valueOf();return"number"==typeof i&&"number"==typeof n?i-n:"string"==typeof i&&"string"==typeof n?i.localeCompare(n):0}function V(e,t){var i,n;let{value:r}=e;if(null==r)return!1;let o=t;switch(o.startsWith("System.")&&(o=o.substring(7)),o.startsWith("FHIR.")&&(o=o.substring(5)),o){case"Boolean":return"boolean"==typeof r;case"Decimal":case"Integer":return"number"==typeof r;case"Date":return"string"==typeof(i=r)&&!!M.exec(i);case"DateTime":return K(r);case"Time":return"string"==typeof r&&!!/^T\d/.exec(r);case"Period":return!!((n=r)&&"object"==typeof n&&("start"in n&&K(n.start)||"end"in n&&K(n.end)));case"Quantity":return X(r);default:return e.type===o||"object"==typeof r&&r?.resourceType===o}}function K(e){return"string"==typeof e&&!!q.exec(e)}function X(e){return!!(e&&"object"==typeof e&&"value"in e&&"number"==typeof e.value)}function Y(e,t){return .01>Math.abs(e.value-t.value)&&(e.unit===t.unit||e.code===t.code||e.unit===t.code||e.code===t.unit)}function Z(e,t){let i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(let n of i){let i=e[n],r=t[n];if(ee(i)&&ee(r)){if(!Z(i,r))return!1}else if(i!==r)return!1}return!0}function ee(e){return null!==e&&"object"==typeof e}function et(e,t){if(t){var i,n;if("object"!=typeof t)throw Error("Primitive extension must be an object");return i=e??{},n=t,delete n.__proto__,delete n.constructor,Object.assign(i,n)}return e}function ei(e){let t=en(e)??"undefined/undefined",i=function(e){if("Patient"===e.resourceType||"Practitioner"===e.resourceType||"RelatedPerson"===e.resourceType){let t=function(e){let t=e.name;if(t&&t.length>0){var i=t[0];if(!i)return"";let e=[];if(i.prefix&&!0&&e.push(...i.prefix),i.given&&e.push(...i.given),i.family&&e.push(i.family),i.suffix&&!0&&e.push(...i.suffix),i.use,0===e.length){let e=eE(i.text);if(e)return e}return e.join(" ").trim()}}(e);if(t)return t}if("Appointment"===e.resourceType&&e.serviceType?.[0])return ew(e.serviceType[0]);if("Device"===e.resourceType){let t=function(e){let t=e.deviceName;if(t&&t.length>0)return t[0].name}(e);if(t)return t}if("DocumentReference"===e.resourceType){if(e.description)return e.description;if(e.type)return ew(e.type)}if("MedicationRequest"===e.resourceType&&e.medicationCodeableConcept||"MedicationStatement"===e.resourceType&&e.medicationCodeableConcept)return ew(e.medicationCodeableConcept);if("Slot"===e.resourceType&&(e.start||e.end))return`${eb(e.start)} - ${eb(e.end)}`;if("Subscription"===e.resourceType&&e.criteria)return e.criteria;if("User"===e.resourceType&&e.email)return e.email;if("name"in e&&e.name&&"string"==typeof e.name)return e.name;if("code"in e&&e.code){var t;let i=e.code;if(Array.isArray(i)&&(i=i[0]),ef(i))return ew(i);if(ed(t=i)&&"text"in t&&"string"==typeof t.text)return i.text}return en(e)??""}(e);return i===t?{reference:t}:{reference:t,display:i}}function en(e){return eD(e)?e.reference:ek(e,void 0)&&"id"in e&&"string"==typeof e.id?`${e.resourceType}/${e.id}`:void 0}function er(e){if(e)return eD(e)?e.reference.split("/")[1]:e.id}function eo(e,...t){let i=e;for(let e=0;e<t.length&&i;e++)i=i?.extension?.find(i=>i.url===t[e]);return i}function es(e){if(null==e)return!0;let t=typeof e;return("string"===t||"object"===t)&&!function(e){if(null==e)return!1;let t=typeof e;return"string"===t&&""!==e||"object"===t&&("length"in e&&e.length>0||Object.keys(e).length>0)}(e)}function ea(e,t,i){return!!(e===t||es(e)&&es(t))||!(es(e)||es(t))&&(Array.isArray(e)&&Array.isArray(t)?function(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!ea(e[i],t[i]))return!1;return!0}(e,t):!(Array.isArray(e)||Array.isArray(t))&&(ed(e)&&ed(t)?function(e,t,i){let n=new Set;for(let t of Object.keys(e))n.add(t);for(let e of Object.keys(t))n.add(e);for(let r of("meta"===i&&(n.delete("versionId"),n.delete("lastUpdated"),n.delete("author")),n))if(!ea(e[r],t[r],r))return!1;return!0}(e,t,i):(ed(e)||ed(t),!1)))}function ec(e){return void 0===e?e:JSON.parse(JSON.stringify(e))}function ed(e){return null!==e&&"object"==typeof e}function el(e){return ed(e)&&"code"in e&&"string"==typeof e.code}function ef(e){return ed(e)&&"coding"in e&&Array.isArray(e.coding)&&e.coding.every(el)}var eh=[];for(let e=0;e<256;e++)eh.push(e.toString(16).padStart(2,"0"));function eu(e){return ArrayBuffer.isView(e)?e.buffer:e}function ep(e){return e?e.charAt(0).toUpperCase()+e.substring(1):""}var em=(e,t)=>
1new Promise((i,n)=>{t?.signal?.throwIfAborted();let r=setTimeout(i,e);t?.signal?.addEventListener("abort",()=>{clearTimeout(r),n(t.signal?.reason)},{once:!0})});function ey(e){let t,i=!1;return function(){return i||(t=e(),i=!0),t}}function eg(e){return e.endsWith("/")?e:e+"/"}function ex(e,t){return new URL(t.startsWith("/")?t.slice(1):t,eg(e.toString())).toString()}var ev=Object.freeze([]);function eb(e,t,i){if(!e)return"";let n=new Date(e);return n instanceof Date&&!Number.isNaN(n.getTime())?n.toLocaleString(t,i):""}function ew(e){return e?eE(e.text)||(e.coding?e.coding.map(e=>(function(e){let t=eE(e?.display);if(t){let e=void 0;return`${t}${e?" ("+e+")":""}`}return eE(e?.code)??""})(e)).join(", "):""):""}function eE(e){return"string"==typeof e?e:void 0}var eT={Address:"Address",Age:"Age",Annotation:"Annotation",Attachment:"Attachment",BackboneElement:"BackboneElement",CodeableConcept:"CodeableConcept",Coding:"Coding",ContactDetail:"ContactDetail",ContactPoint:"ContactPoint",Contributor:"Contributor",Count:"Count",DataRequirement:"DataRequirement",Distance:"Distance",Dosage:"Dosage",Duration:"Duration",Element:"Element",ElementDefinition:"ElementDefinition",Expression:"Expression",Extension:"Extension",HumanName:"HumanName",Identifier:"Identifier",MarketingStatus:"MarketingStatus",Meta:"Meta",Money:"Money",MoneyQuantity:"MoneyQuantity",Narrative:"Narrative",ParameterDefinition:"ParameterDefinition",Period:"Period",Population:"Population",ProdCharacteristic:"ProdCharacteristic",ProductShelfLife:"ProductShelfLife",Quantity:"Quantity",Range:"Range",Ratio:"Ratio",Reference:"Reference",RelatedArtifact:"RelatedArtifact",SampledData:"SampledData",Signature:"Signature",SimpleQuantity:"SimpleQuantity",SubstanceAmount:"SubstanceAmount",SystemString:"http://hl7.org/fhirpath/System.String",Timing:"Timing",TriggerDefinition:"TriggerDefinition",UsageContext:"UsageContext",base64Binary:"base64Binary",boolean:"boolean",canonical:"canonical",code:"code",date:"date",dateTime:"dateTime",decimal:"decimal",id:"id",instant:"instant",integer:"integer",markdown:"markdown",oid:"oid",positiveInt:"positiveInt",string:"string",time:"time",unsignedInt:"unsignedInt",uri:"uri",url:"url",uuid:"uuid",xhtml:"xhtml"};function eS(e){let t,i=eA.types[e];return i||(i={searchParamsDetails:{}},eA.types[e]=i),i.searchParams||"Binary"===e||(i.searchParams={_id:{base:[e],code:"_id",type:"token",expression:e+".id"},_lastUpdated:{base:[e],code:"_lastUpdated",type:"date",expression:e+".meta.lastUpdated"}
1,_compartment:{base:[e],code:"_compartment",type:"reference",expression:e+".meta.compartment",get target(){return t??=Object.values(R).filter(eP).map(e=>e.name)}},_profile:{base:[e],code:"_profile",type:"uri",expression:e+".meta.profile"},_security:{base:[e],code:"_security",type:"token",expression:e+".meta.security"},_source:{base:[e],code:"_source",type:"uri",expression:e+".meta.source"},_tag:{base:[e],code:"_tag",type:"token",expression:e+".meta.tag"},_project:{base:[e],code:"_project",type:"token",expression:e+".meta.project"}}),i}function eC(e){let t=e.type?.[0]?.code;return"BackboneElement"===t||"Element"===t?eR((e.base?.path??e.path)?.split(".")):t}function eR(e){return 1===e.length?e[0]:e.map(ep).join("")}function eP(e){return"resource"===e.kind&&"Resource"!==e.name&&"DomainResource"!==e.name}function ek(e,t){return!(!e||"object"!=typeof e||!("resourceType"in e)||t&&e.resourceType!==t)}function eD(e,t){return!!e&&"object"==typeof e&&"reference"in e&&"string"==typeof e.reference&&(!t||null!==e.reference.match(RegExp(`^${t}(/|\\?)`)))}var eA=null;function e_(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{return e}}var eL=()=>[];function ej(e){return e instanceof e$?e.name:e instanceof eV&&e.left instanceof e$&&e.right instanceof e$?e.left.name+"."+e.right.name:""}var eI={empty:(e,t)=>N(t.every(e=>es(e.value))),hasValue:(e,t)=>N(0!==t.length),exists:(e,t,i)=>i?N(t.some(t=>B(i.eval(e,[t])))):N(t.length>0&&t.every(e=>!es(e.value))),all:(e,t,i)=>N(t.every(t=>B(i.eval(e,[t])))),allTrue:(e,t)=>{for(let e of t)if(!e.value)return N(!1);return N(!0)},anyTrue:(e,t)=>{for(let e of t)if(e.value)return N(!0);return N(!1)},allFalse:(e,t)=>{for(let e of t)if(e.value)return N(!1);return N(!0)},anyFalse:(e,t)=>{for(let e of t)if(!e.value)return N(!0);return N(!1)},subsetOf:(e,t,i)=>{if(0===t.length)return N(!0);let n=i.eval(e,eq(e));return 0===n.length?N(!1):N(t.every(e=>n.some(t=>t.value===e.value)))},supersetOf:(e,t,i)=>{let n=i.eval(e,eq(e));return 0===n.length?N(!0):0===t.length?N(!1):N(n.every(e=>t.some(t=>t.value===e.value)))},count:(e,t)=>[{type:eT.integer,value:t.length}],distinct:(e,t)=>
1{let i=[];for(let e of t)i.some(t=>t.value===e.value)||i.push(e);return i},isDistinct:(e,t)=>N(t.length===eI.distinct(e,t).length),where:(e,t,i)=>t.filter(t=>B(i.eval(e,[t]))),select:(e,t,i)=>t.flatMap(t=>i.eval({parent:e,variables:{$this:t}},[t])),repeat:eL,ofType:(e,t,i)=>{let n=ej(i);return n?t.filter(e=>V(e,n)):[]},single:(e,t)=>{if(t.length>1)throw 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(-1,t.length),tail:(e,t)=>0===t.length?[]:t.slice(1,t.length),skip:(e,t,i)=>{let n=i.eval(e,t)[0]?.value;if("number"!=typeof n)throw TypeError("Expected a number for skip(num)");return n>=t.length?[]:n<=0?t:t.slice(n,t.length)},take:(e,t,i)=>{let n=i.eval(e,t)[0]?.value;if("number"!=typeof n)throw TypeError("Expected a number for take(num)");return n<=0?[]:t.slice(0,n)},intersect:(e,t,i)=>{if(!i)return t;let n=i.eval(e,eq(e)),r=[];for(let e of t)!r.some(t=>t.value===e.value)&&n.some(t=>t.value===e.value)&&r.push(e);return r},exclude:(e,t,i)=>{if(!i)return t;let n=i.eval(e,eq(e)),r=[];for(let e of t)n.some(t=>t.value===e.value)||r.push(e);return r},union:(e,t,i)=>i?Q([...t,...i.eval(e,eq(e))]):t,combine:(e,t,i)=>i?[...t,...i.eval(e,eq(e))]:t,htmlChecks:(e,t,i)=>[$(!0)],iif:(e,t,i,n,r)=>{let o=i.eval(e,t);if(o.length>1||1===o.length&&"boolean"!=typeof o[0].value)throw Error("Expected criterion to evaluate to a Boolean");return B(o)?n.eval(e,t):r?r.eval(e,t):[]},toBoolean:(e,t)=>{if(0===t.length)return[];let[{value:i}]=eM(t,1);if("boolean"==typeof i)return[{type:eT.boolean,value:i}];if("number"==typeof i&&(0===i||1===i))return N(!!i);if("string"==typeof i){let e=i.toLowerCase();if(["true","t","yes","y","1","1.0"].includes(e))return N(!0);if(["false","f","no","n","0","0.0"].includes(e))return N(!1)}return[]},convertsToBoolean:(e,t)=>0===t.length?[]:N(1===eI.toBoolean(e,t).length),toInteger:(e,t)=>{if(0===t.length)return[];let[{value:i}]=eM(t,1);return"number"==typeof i?[{type:eT.integer,value:i}]:"string"==typeof i&&/^[+-]?\d+$/.exec(i)?[{type:eT.integer,value:Number.parseInt(i,10)}]:"boolean"==typeof i?[{type:eT.integer,value:+!!i}]:[]},convertsToInteger:(e,t)=>0===t.length?[]:N(1===eI.toInteger(e,t).length),toDate:(e,t)=>{if(0===t.length)return[];let[{value:i}]=eM(t,1);return"string"==typeof i&&/^\d{4}(-\d{2}(-\d{2})?)?/.exec(i)?[{type:eT.date,value:e_(i)}]:[]},convertsToDate:(e,t)=>0===t.length?[]:N(1===eI.toDate(e,t).length),toDateTime:(e,t)=>{if(0===t.length)return[];let[{value:i}]=eM(t,1);return"string"==typeof i&&/^\d{4}(-\d{2}(-\d{2})?)?/.exec(i)?[{type:eT.dateTime,value:e_(i)}]:[]},convertsToDateTime:(e,t)=>0===t.length?[]:N(1===eI.toDateTime(e,t).length),toDecimal:(e,t)=>{if(0===t.length)return[];let[{value:i}]=eM(t,1);return"number"==typeof i?[{type:eT.decimal,value:i}]:"string"==typeof i&&/^-?\d{1,9}(\.\d{1,9})?$/.exec(i)?[{type:eT.decimal,value:Number.parseFloat(i)}]:"boolean"==typeof i?[{type:eT.decimal,value:+!!i}]:[]},convertsToDecimal:(e,t)=>0===t.length?[]:N(1===eI.toDecimal(e,t).length),toQuantity:(e,t)=>{if(0===t.length)return[];let[{value:i}]=eM(t,1);return X(i)?[{type:eT.Quantity,value:i}]:"number"==typeof i?[{type:eT.Quantity,value:{value:i,unit:"1"}}]:"string"==typeof i&&/^-?\d{1,9}(\.\d{1,9})?/.exec(i)?[{type:eT.Quantity,value:{value:Number.parseFloat(i),unit:"1"}}]:"boolean"==typeof i?[{type:eT.Quantity,value:{value:+!!i,unit:"1"}}]:[]},convertsToQuantity:(e,t)=>0===t.length?[]:N(1===eI.toQuantity(e,t).length),toString:(e,t)=>{if(0===t.length)return[];let[{value:i}]=eM(t,1);return null==i?[]:X(i)?[{type:eT.string,value:`${i.value} '${i.unit}'`}]:[{type:eT.string,value:i.toString()}]},convertsToString:(e,t)=>0===t.length?[]:N(1===eI.toString(e,t).length),toTime:(e,t)=>{if(0===t.length)return[];let[{value:i}]=eM(t,1);if("string"==typeof i){let e=/^T?(\d{2}(:\d{2}(:\d{2})?)?)/.exec(i);if(e)return[{type:eT.time,value:e_("T"+e[1])}]}return[]},convertsToTime:(e,t)=>0===t.length?[]:N(1===eI.toTime(e,t).length),indexOf:(e,t,i)=>eU((e,t)=>e.indexOf(t),e,t,i),substring:(e,t,i,n)=>eU((e,t,i)=>{let n=i?t+i:e.length;return t<0||t>=e.length?void 0:e.substring(t,n)},e,t,i,n),startsWith:(e,t,i)=>eU((e,t)=>e.startsWith(t),e,t,i),endsWith:(e,t,i)=>eU((e,t)=>e.endsWith(t),e,t,i),contains:(e,t,i)=>eU((e,t)=>e.includes(t),e,t,i),upper:(e,t)=>eU(e=>e.toUpperCase(),e,t),lower:(e,t)=>eU(e=>e.toLowerCase(),e,t),replace:(e,t,i,n)=>eU((e,t,i)=>e.replaceAll(t,i),e,t,i,n),matches:(e,t,i)=>eU((e,t)=>!!new RegExp(t).exec(e),e,t,i),replaceMatches:(e,t,i,n)=>eU((e,t,i)=>e.replaceAll(RegExp(t,"g"),i.replaceAll(/\$\{(\w+)\}/g,"$<$1>")),e,t,i,n),length:(e,t)=>eU(e=>e.length,e,t),toChars:(e,t)=>eU(e=>e?e.split(""):void 0,e,t),encode:eL,decode:eL,escape:eL,unescape:eL,trim:eL,split:eL,join:(e,t,i)=>{let n=i?.eval(e,eq(e))[0]?.value??"";if("string"!=typeof n)throw TypeError("Separator must be a string.");return[{type:eT.string,value:t.map(e=>e.value?.toString()??"").join(n)}]},abs:(e,t)=>eO(Math.abs,e,t),ceiling:(e,t)=>
1eO(Math.ceil,e,t),exp:(e,t)=>eO(Math.exp,e,t),floor:(e,t)=>eO(Math.floor,e,t),ln:(e,t)=>eO(Math.log,e,t),log:(e,t,i)=>eO((e,t)=>Math.log(e)/Math.log(t),e,t,i),power:(e,t,i)=>eO(Math.pow,e,t,i),round:(e,t,...i)=>eO((e,t=0)=>{if("number"!=typeof t||t<0)throw Error("Invalid precision provided to round()");let i=Math.pow(10,t);return Math.round(e*i)/i},e,t,...i),sqrt:(e,t)=>eO(Math.sqrt,e,t),truncate:(e,t)=>eO(e=>Math.trunc(e),e,t),children:eL,descendants:eL,trace:(e,t,i)=>t,now:()=>[{type:eT.dateTime,value:new Date().toISOString()}],timeOfDay:()=>[{type:eT.time,value:new Date().toISOString().substring(11)}],today:()=>[{type:eT.date,value:new Date().toISOString().substring(0,10)}],between:(e,t,i,n,r)=>{var o,s;let a,c,d,l,f,h,u,p,m,y,g=eI.toDateTime(e,i.eval(e,t));if(0===g.length)throw Error("Invalid start date");let x=eI.toDateTime(e,n.eval(e,t));if(0===x.length)throw Error("Invalid end date");let v=r.eval(e,t)[0]?.value;if("years"!==v&&"months"!==v&&"days"!==v)throw Error("Invalid units");let b=(o=g[0].value,s=x[0].value,(a=new Date(o)).setUTCHours(0,0,0,0),(c=s?new Date(s):new Date).setUTCHours(0,0,0,0),d=a.getUTCFullYear(),l=a.getUTCMonth(),f=a.getUTCDate(),h=c.getUTCFullYear(),u=c.getUTCMonth(),p=c.getUTCDate(),m=h-d,(u<l||u===l&&p<f)&&m--,y=12*h+u-(12*d+l),p<f&&y--,{years:m,months:y,days:Math.floor((c.getTime()-a.getTime())/864e5)});return[{type:eT.Quantity,value:{value:b[v],unit:v}}]},is:(e,t,i)=>{let n=ej(i);return n?t.map(e=>({type:eT.boolean,value:V(e,n)})):[]},not:(e,t)=>eI.toBoolean(e,t).map(e=>({type:eT.boolean,value:!e.value})),resolve:(e,t)=>t.map(e=>{let t=e.value,i;if("string"==typeof t)i=t;else if("object"==typeof t){if(t.resource)return $(t.resource);t.reference?i=t.reference:t.type&&t.identifier&&(i=`${t.type}?identifier=${t.identifier.system}|${t.identifier.value}`)}if(i?.includes("?")){let[e]=i.split("?");return{type:e,value:{resourceType:e}}}if(i?.includes("/")){let[e,t]=i.split("/");return{type:e,value:{resourceType:e,id:t}}}return{type:eT.BackboneElement,value:void 0}}).filter(e=>!!e.value),as:(e,t,i)=>{let n=ej(i);if(!n)throw Error(`Expected a valid type identifier as the right operand of 'as', but found ${i.toString()}`);let r=W(t);return r&&V(r,n)?[r]:[]},type:(e,t)=>t.map(({value:e})=>"boolean"==typeof e?{type:eT.BackboneElement,value:{namespace:"System",name:"Boolean"}}:"number"==typeof e?{type:eT.BackboneElement,value:{namespace:"System",name:"Integer"}}:ek(e)?{type:eT.BackboneElement,value:{namespace:"FHIR",name:e.resourceType}}:{type:eT.BackboneElement,value:null}),conformsTo:(e,t,i)=>{let n=i.eval(e,t)[0].value;if(!n.startsWith("http://hl7.org/fhir/StructureDefinition/"))throw Error("Expected a StructureDefinition URL");let r=n.replace("http://hl7.org/fhir/StructureDefinition/","");return t.map(e=>({type:eT.boolean,value:e.value?.resourceType===r}))},getResourceKey:(e,t)=>{let i=t[0]?.value;return i?.id?[{type:eT.id,value:i.id}]:[]},getReferenceKey:(e,t,i)=>{let n=t[0]?.value;if(!n?.reference)return[];let r="";return i instanceof e$&&(r=i.name),r&&!n.reference.startsWith(r+"/")?[]:[{type:eT.id,value:er(n)}]},extension:(e,t,i)=>{let n=i.eval(e,t)[0].value,r=t?.[0]?.value;if(r){let e=eo(r,n);if(e)return[{type:eT.Extension,value:e}]}return[]}};function eU(e,t,i,...n){if(0===i.length)return[];let[{value:r}]=eM(i,1);if("string"!=typeof r)throw TypeError("String function cannot be called with non-string");let o=e(r,...n.map(e=>e?.eval(t,i)[0]?.value));return void 0===o?[]:Array.isArray(o)?o.map($):[$(o)]}function eO(e,t,i,...n){if(0===i.length)return[];let[{value:r}]=eM(i,1),o=X(r),s=o?r.value:r;if("number"!=typeof s)throw TypeError("Math function cannot be called with non-number");let a=e(s,...n.map(e=>e.eval(t,i)[0]?.value));return[{type:o?eT.Quantity:i[0].type,value:o?{...r,value:a}:a}]}function eM(e,t){if(e.length!==t)throw Error(`Expected ${t} arguments`);for(let t of e)if(null==t)throw Error("Expected non-null argument");return e}function eq(e){let t=e;for(;t.parent?.variables.$this;)t=t.parent;return[t.variables.$this]}var eN=class{constructor(e){o(this,"value"),this.value=e}eval(){return[this.value]}toString(){let e=this.value.value;return"string"==typeof e?`'${e}'`:e.toString()}},e$=class{constructor(e){o(this,"name"),this.name=e}eval(e,t){if("$this"===this.name)return t;let i=this.getVariable(e);if(i)return[i];if(this.name.startsWith("%"))throw Error(`Undefined variable ${this.name}`);return t.flatMap(e=>this.evalValue(e)).filter(e=>e?.value!==void 0)}getVariable(e){let t=e.variables[this.name];return void 0!==t?t:e.parent?this.getVariable(e.parent):void 0}evalValue(e){let t=e.value;if(!(!t||"object"!=typeof t)){var i,n,r,o;let s,a;return ek(t,this.name)?("path"in e||(e.path=t.resourceType),e):(i=this.name,s=e.path,n=F(e,i,void 0),r=s,o=i,a=r?r+".":"",void 0===n?{type:"undefined",value:void 0,path:`${a}${o}`}:Array.isArray(n)?n.map((e,t)=>({...e,path:`${a}${o}[${t}]`})):{...n,path:`${a}${o}`})}}toString(){return this.name}},eB=class{eval(){return[]}toString(){return"{}"}},eW=class extends a{constructor(e,t,i){super(e,t),o(this,"impl"),this.impl=i}eval(e,t){return this.impl(this.child.eval(e,t))}toString(){return this.operator+this.child.toString()}},eF=class extends c{constructor(e,t){super("as",e,t)}eval(e,t){return eI.as(e,this.left.eval(e,t),this.right)}},eH=class extends c{constructor(e,t,i,n){super(e,t,i),o(this,"impl"),this.impl=n}eval(e,t){let i=this.left.eval(e,t),n=this.right.eval(e,t);if(i.length<1||n.length<1)return[];let r=W(i)?.value,o=W(n)?.value,s=X(r)?r.value:r,a=X(o)?o.value:o,c=this.impl(s,a);return"boolean"==typeof c?N(c):X(r)?[{type:eT.Quantity,value:{...r,value:c}}]:[$(c)]}},eQ=Object.freeze({type:"string",value:""}),ez=class extends c{constructor(e,t){super("&",e,t)}eval(e,t){let i=W(this.left.eval(e,t))??eQ,n=W(this.right.eval(e,t))??eQ;if("string"!=typeof i.value)throw Error(`Expected string operand for &, but got ${i.type}`);if("string"!=typeof n.value)throw Error(`Expected string operand for &, but got ${n.type}`);return[{type:eT.string,value:i.value+n.value}]}},eJ=class extends c{constructor(e,t){super("contains",e,t)}eval(e,t){let i=this.left.eval(e,t),n=this.right.eval(e,t);return N(i.some(e=>e.value===n[0].value))}},eG=class extends c{constructor(e,t){super("in",e,t)}eval(e,t){let i=W(this.left.eval(e,t)),n=this.right.eval(e,t);return i?N(n.some(e=>z(i,e)[0].value)):[]}},eV=class extends c{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()}`}},eK=class extends c{constructor(e,t){super("|",e,t)}eval(e,t){return Q([...this.left.eval(e,t),...this.right.eval(e,t)])}},eX=class extends c{constructor(e,t){super("=",e,t)}eval(e,t){let i=this.left.eval(e,t),n=this.right.eval(e,t);return 0===i.length||0===n.length?[]:i.length!==n.length?N(!1):N(i.every((e,t)=>B(z(e,n[t]))))}},eY=class extends c{constructor(e,t){super("!=",e,t)}eval(e,t){let i=this.left.eval(e,t),n=this.right.eval(e,t);return 0===i.length||0===n.length?[]:i.length!==n.length?N(!0):N(i.some((e,t)=>!B(z(e,n[t]))))}},eZ=class extends c{constructor(e,t){super("~",e,t)}eval(e,t){return J(this.left.eval(e,t),this.right.eval(e,t))}},e0=class extends c{constructor(e,t){super("!~",e,t)}eval(e,t){return N(!B(J(this.left.eval(e,t),this.right.eval(e,t))))}},e1=class extends c{constructor(e,t){super("is",e,t)}eval(e,t){let i=this.left.eval(e,t);if(1!==i.length)return[];let n=ej(this.right);return n?N(V(i[0],n)):[]}},e2=class extends c{constructor(e,t){super("and",e,t)}eval(e,t){let i=W(this.left.eval(e,t),"boolean"),n=W(this.right.eval(e,t),"boolean");return i?.value===!0&&n?.value===!0?N(!0):i?.value===!1||n?.value===!1?N(!1):[]}},e7=class extends c{constructor(e,t){super("or",e,t)}eval(e,t){let i=W(this.left.eval(e,t),"boolean"),n=W(this.right.eval(e,t),"boolean");return i?.value===!1&&n?.value===!1?N(!1):i?.value||n?.value?N(!0):[]}},e3=class extends c{constructor(e,t){super("xor",e,t)}eval(e,t){let i=W(this.left.eval(e,t),"boolean"),n=W(this.right.eval(e,t),"boolean");return i&&n?N(i.value!==n.value):[]}},e4=class extends c{constructor(e,t){super("implies",e,t)}eval(e,t){let i=W(this.left.eval(e,t),"boolean"),n=W(this.right.eval(e,t),"boolean");return n?.value===!0||i?.value===!1?N(!0):i&&n?N(!1):[]}},e6=class{constructor(e,t){o(this,"name"),o(this,"args"),this.name=e,this.args=t}eval(e,t){let i=eI[this.name];if(!i)throw Error("Unrecognized function: "+this.name);return i(e,t,...this.args)}toString(){return`${this.name}(${this.args.map(e=>e.toString()).join(", ")})`}}
1,e8=class{constructor(e,t){o(this,"left"),o(this,"expr"),this.left=e,this.expr=t}eval(e,t){let i=this.expr.eval(e,t);if(1!==i.length)return[];let n=i[0].value;if("number"!=typeof n)throw Error("Invalid indexer expression: should return integer}");let r=this.left.eval(e,t);return n in r?[r[n]]:[]}toString(){return`${this.left.toString()}[${this.expr.toString()}]`}},e5=["!=","!~","<=",">=","{}","->"],e9={parse(e){let t=e.consumeAndParse();if(!e.match(")"))throw Error("Parse error: expected `)` got `"+e.peek()?.value+"`");return t}},te={parse(e,t){let i=e.consumeAndParse();if(!e.match("]"))throw Error("Parse error: expected `]`");return new e8(t,i)},precedence:2},tt={parse(e,t){if(!(t instanceof e$))throw Error("Unexpected parentheses");let i=[];for(;!e.match(")");)i.push(e.consumeAndParse()),e.match(",");return new e6(t.name,i)},precedence:0};function ti(){return new d().registerPrefix("String",{parse:(e,t)=>new eN({type:eT.string,value:t.value})}).registerPrefix("DateTime",{parse:(e,t)=>new eN({type:eT.dateTime,value:e_(t.value)})}).registerPrefix("Quantity",{parse:(e,t)=>{let i,n,r;return new eN({type:eT.Quantity,value:(n=Number.parseFloat((i=t.value.split(" "))[0]),r=i[1],{value:n,unit:r=r?.startsWith("'")&&r.endsWith("'")?r.substring(1,r.length-1):"{"+r+"}"})})}}).registerPrefix("Number",{parse:(e,t)=>new eN({type:t.value.includes(".")?eT.decimal:eT.integer,value:Number.parseFloat(t.value)})}).registerPrefix("true",{parse:()=>new eN({type:eT.boolean,value:!0})}).registerPrefix("false",{parse:()=>new eN({type:eT.boolean,value:!1})}).registerPrefix("Symbol",{parse:(e,t)=>new e$(t.value)}).registerPrefix("{}",{parse:()=>new eB}).registerPrefix("(",e9).registerInfix("[",te).registerInfix("(",tt).prefix("+",3,(e,t)=>new eW("+",t,e=>e)).prefix("-",3,(e,t)=>new eH("-",t,t,(e,t)=>-t)).infixLeft(".",1,(e,t,i)=>new eV(e,i)).infixLeft("/",4,(e,t,i)=>new eH("/",e,i,(e,t)=>e/t)).infixLeft("*",4,(e,t,i)=>new eH("*",e,i,(e,t)=>e*t)).infixLeft("+",5,(e,t,i)=>new eH("+",e,i,(e,t)=>e+t)).infixLeft("-",5,(e,t,i)=>new eH("-",e,i,(e,t)=>e-t)).infixLeft("|",7,(e,t,i)=>new eK(e,i)).infixLeft("=",9,(e,t,i)=>new eX(e,i)).infixLeft("!=",9,(e,t,i)=>new eY(e,i)).infixLeft("~",9,(e,t,i)=>new eZ(e,i)).infixLeft("!~",9,(e,t,i)=>new e0(e,i)).infixLeft("<",8,(e,t,i)=>new eH("<",e,i,(e,t)=>e<t)).infixLeft("<=",8,(e,t,i)=>new eH("<=",e,i,(e,t)=>e<=t)).infixLeft(">",8,(e,t,i)=>new eH(">",e,i,(e,t)=>e>t)).infixLeft(">=",8,(e,t,i)=>new eH(">=",e,i,(e,t)=>e>=t)).infixLeft("&",5,(e,t,i)=>new ez(e,i)).infixLeft("and",11,(e,t,i)=>new e2(e,i)).infixLeft("as",6,(e,t,i)=>new eF(e,i)).infixLeft("contains",10,(e,t,i)=>new eJ(e,i)).infixLeft("div",4,(e,t,i)=>new eH("div",e,i,(e,t)=>Math.trunc(e/t))).infixLeft("in",10,(e,t,i)=>new eG(e,i)).infixLeft("is",6,(e,t,i)=>new e1(e,i)).infixLeft("mod",4,(e,t,i)=>new eH("mod",e,i,(e,t)=>e%t)).infixLeft("or",12,(e,t,i)=>new e7(e,i)).infixLeft("xor",12,(e,t,i)=>new e3(e,i)).infixLeft("implies",13,(e,t,i)=>new e4(e,i))}ti();new s(1e3);function tn(){return"u">typeof window}function tr(){return"u">typeof Buffer?Buffer:void 0}function to(e){if(tn()){let t=new window.TextEncoder().encode(e),i=String.fromCodePoint.apply(null,t);return window.btoa(i)}let t=tr();if(t)return t.from(e,"utf8").toString("base64");throw Error("Unable to encode base64")}function ts(){let e=new Uint32Array(28);return crypto.getRandomValues(e),function(e){let t=new Uint8Array(eu(e)),i=Array(t.length);for(let e=0;e<t.length;e++)i[e]=eh[t[e]];return i.join("")}(e.buffer)}async function ta(e){return crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))}var tc={CSS:"text/css",DICOM:"application/dicom",DICOM_JSON:"application/dicom+json",EVENT_STREAM:"text/event-stream",FAVICON:"image/vnd.microsoft.icon",FHIR_JSON:"application/fhir+json",FORM_URL_ENCODED:"application/x-www-form-urlencoded",HL7_V2:"x-application/hl7-v2+er7",HTML:"text/html",JAVASCRIPT:"text/javascript",JOSE:"application/jose",JSON:"application/json",JSON_PATCH:"application/json-patch+json",JWT:"application/jwt",LINKSET_JSON:"application/linkset+json",MULTIPART_FORM_DATA:"multipart/form-data",PNG:"image/png",SCIM_JSON:"application/scim+json",SVG:"image/svg+xml",TEXT:"text/plain",TYPESCRIPT:"text/typescript",PING:"x-application/ping",XML:"text/xml",CDA_XML:"application/cda+xml",OCTET_STREAM:"application/octet-stream"},td={Event:"u">typeof globalThis.Event?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0},tl=null;function tf(){}function th(e){return e instanceof td.CloseEvent?new td.CloseEvent(e.code,e.reason,void 0):e instanceof td.ErrorEvent?new td.ErrorEvent(e.error??Error(e.message),void 0):new e.constructor(e.type,e)}var tu=null,tp=class e extends null{constructor(e,t,i={}){tl||(function(){if(typeof globalThis.Event>"u")throw Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");
1td.Event=globalThis.Event,td.ErrorEvent=class extends Event{constructor(e,t){super("error",t),o(this,"message"),o(this,"error"),this.message=e.message,this.error=e}},td.CloseEvent=class extends Event{constructor(e=1e3,t="",i){super("close",i),o(this,"code"),o(this,"reason"),o(this,"wasClean",!0),this.code=e,this.reason=t}}}(),tl=!0),super(),o(this,"_ws"),o(this,"_retryCount",-1),o(this,"_uptimeTimeout"),o(this,"_connectTimeout"),o(this,"_shouldReconnect",!0),o(this,"_connectLock",!1),o(this,"_binaryType"),o(this,"_closeCalled",!1),o(this,"_messageQueue",[]),o(this,"_debugLogger",console.log.bind(console)),o(this,"_url"),o(this,"_protocols"),o(this,"_options"),o(this,"onclose",null),o(this,"onerror",null),o(this,"onmessage",null),o(this,"onopen",null),o(this,"_handleOpen",e=>{this._debug("open event");let{minUptime:t=null.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),t),function(e,t){if(!e)throw Error(t)}(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(e=>this._ws?.send(e)),this._messageQueue=[],this.onopen&&this.onopen(e),this.dispatchEvent(th(e))}),o(this,"_handleMessage",e=>{this._debug("message event"),this.onmessage&&this.onmessage(e),this.dispatchEvent(th(e))}),o(this,"_handleError",e=>{let t=e.error instanceof Error?new td.ErrorEvent(e.error,this):new td.ErrorEvent(Error(e.message||"WebSocket error"),this);this._debug("error event",t.message),this._disconnect(void 0,"TIMEOUT"===t.message?"timeout":void 0),this.onerror&&this.onerror(t),this._debug("exec error listeners"),this.dispatchEvent(th(t)),this._connect()}),o(this,"_handleClose",e=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(e),this.dispatchEvent(th(e))}),this._url=e,this._protocols=t,this._options=i,this._options.startClosed&&(this._shouldReconnect=!1),this._options.binaryType?this._binaryType=this._options.binaryType:this._binaryType="blob",this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return e.CONNECTING}get OPEN(){return e.OPEN}get CLOSING(){return e.CLOSING}get CLOSED(){return e.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((e,t)=>("string"==typeof t?e+=t.length:t instanceof Blob?e+=t.size:e+=t.byteLength,e),0)+(this._ws?.bufferedAmount??0)}get extensions(){return this._ws?.extensions??""}get protocol(){return this._ws?.protocol??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?e.CLOSED:e.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}close(e=1e3,t){(this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws)?this._ws.readyState===this.CLOSED?this._debug("close: already closed"):this._ws.close(e,t):this._debug("close enqueued: no ws instance")}reconnect(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED&&this._disconnect(e,t),this._connect()}send(e){if(this._ws?.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{let{maxEnqueuedMessages:t=null.maxEnqueuedMessages}=this._options;this._messageQueue.length<t&&(this._debug("enqueue",e),this._messageQueue.push(e))}}_debug(...e){this._options.debug&&this._debugLogger("RWS>",...e)}_getNextDelay(){let{reconnectionDelayGrowFactor:e=null.reconnectionDelayGrowFactor,minReconnectionDelay:t=null.minReconnectionDelay,maxReconnectionDelay:i=null.maxReconnectionDelay}=this._options,n=0;return this._retryCount>0&&(n=t*Math.pow(e,this._retryCount-1))>i&&(n=i),this._debug("next delay",n),n}_wait(){return new Promise(e=>{setTimeout(e,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;
1let{maxRetries:e=null.maxRetries,connectionTimeout:t=null.connectionTimeout}=this._options;if(this._retryCount>=e){this._connectLock=!1,this._debug("max retries reached",this._retryCount,">=",e);return}this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),this._wait().then(()=>{if(this._closeCalled){this._connectLock=!1;return}!this._options.WebSocket&&typeof WebSocket>"u"&&!tu&&(console.error("\u203C\uFE0F No WebSocket implementation available. You should define options.WebSocket."),tu=!0);let e=this._options.WebSocket||WebSocket;this._debug("connect",{url:this._url,protocols:this._protocols}),this._ws=this._protocols?new e(this._url,this._protocols):new e(this._url),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),t)}).catch(e=>{this._connectLock=!1,this._handleError(new td.ErrorEvent(Error(e.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new td.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(e=1e3,t){if(this._clearTimeouts(),!this._ws)return;let i=this._ws;this._removeListeners(),i.addEventListener("error",tf);try{i.close(e,t),this._handleClose(new td.CloseEvent(e,t,this))}catch{}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_removeListeners(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}},tm={"Patient-open":{patient:{resourceType:"Patient"},encounter:{resourceType:"Encounter",optional:!0}},"Patient-close":{patient:{resourceType:"Patient"},encounter:{resourceType:"Encounter",optional:!0}},"ImagingStudy-open":{study:{resourceType:"ImagingStudy"},encounter:{resourceType:"Encounter",optional:!0},patient:{resourceType:"Patient",optional:!0}},"ImagingStudy-close":{study:{resourceType:"ImagingStudy"},encounter:{resourceType:"Encounter",optional:!0},patient:{resourceType:"Patient",optional:!0}},"Encounter-open":{encounter:{resourceType:"Encounter"},patient:{resourceType:"Patient"}},"Encounter-close":{encounter:{resourceType:"Encounter"},patient:{resourceType:"Patient"}},"DiagnosticReport-open":{report:{resourceType:"DiagnosticReport"},encounter:{resourceType:"Encounter",optional:!0},study:{resourceType:"ImagingStudy",optional:!0,manyAllowed:!0},patient:{resourceType:"Patient"}},"DiagnosticReport-close":{report:{resourceType:"DiagnosticReport"},encounter:{resourceType:"Encounter",optional:!0},study:{resourceType:"ImagingStudy",optional:!0,manyAllowed:!0},patient:{resourceType:"Patient"}},"DiagnosticReport-select":{report:{resourceType:"DiagnosticReport",reference:!0},patient:{resourceType:"Patient",optional:!0,reference:!0},select:{resourceType:"*",reference:!0,manyAllowed:!0}},"DiagnosticReport-update":{report:{resourceType:"DiagnosticReport",reference:!0},patient:{resourceType:"Patient",optional:!0,reference:!0},updates:{resourceType:"Bundle"}},syncerror:{operationoutcome:{resourceType:"OperationOutcome"}}};function ty(e){return!!e.endpoint}function tg(e){if(!tx(e))throw new w(v("subscriptionRequest must be an object conforming to SubscriptionRequest type."));let{channelType:t,mode:i,topic:n,events:r}=e,o={"hub.channel.type":t,"hub.mode":i,"hub.topic":n};return"subscribe"===i&&(o["hub.events"]=r.join(",")),ty(e)&&(o["hub.channel.endpoint"]=e.endpoint),new URLSearchParams(o).toString()}function tx(e){if("object"!=typeof e)return!1;let{channelType:t,mode:i,topic:n,events:r}=e;if(!(t&&i&&n&&r)||"string"!=typeof n||"object"!=typeof r||!Array.isArray(r)||r.length<1||"websocket"!==t||"subscribe"!==i&&"unsubscribe"!==i)return!1;for(let e of r)if(!null[e])return!1;return!(ty(e)&&!("string"==typeof e.endpoint&&e.endpoint.startsWith("ws")))}function tv(e,t,i,n){if(!(e&&"string"==typeof e))throw new w(v("Must provide a topic."));if(!null[t])throw new w(v(`Must provide a valid FHIRcast event name. Supported events: ${Ob
1ject.keys(null).join(", ")}`));if("object"!=typeof i)throw new w(v("context must be a context object or array of context objects."));if(null.includes(t)&&!n)throw new w(v(`The '${t}' event must contain a 'context.versionId'.`));let r=Array.isArray(i)?i:[i];return function(e,t){let i=new Map,n=tm[e];for(let r=0;r<t.length;r++){let o=t[r].key;if(!n[o])throw new w(v(`Key '${o}' not found for event '${e}'. Make sure to add only valid keys.`));!function(e,t,i,n,r){if(r.set(t.key,(r.get(t.key)??0)+1),n.reference){if(!eD(t.reference))throw new w(v(`context[${i}] is invalid. Expected key '${t.key}' to be a reference.`))}else{var o,s=t.resource;if("object"!=typeof s)throw new w(v(`context[${i}] is invalid. Context must contain a single valid FHIR resource! Resource is not an object.`));if(!(s.id&&"string"==typeof s.id))throw new w(v(`context[${i}] is invalid. Resource must contain a valid string ID.`));if(!s.resourceType)throw new w(v(`context[${i}] is invalid. Resource must contain a resource type. No resource type found.`));let r=n.resourceType;if("*"!==r){if(o=s.resourceType,!null.includes(o))throw new w(v(`context[${i}
1] is invalid. Resource must contain a valid FHIRcast resource type. Resource type is not a known resource type.`));if(r&&s.resourceType!==r)throw new w(v(`context[${i}] is invalid. context[${i}] for the '${e}' event should contain resource of type ${r}.`))}}}(e,t[r],r,n[o],i)}for(let[t,r]of Object.entries(n)){if(!(r.optional||i.has(t)))throw new w(v(`Missing required key '${t}' on context for '${e}' event.`));if(!r.manyAllowed&&(i.get(t)??0)>1)throw new w(v(`${i.get(t)} context entries with key '${t}' found for the '${e}' event when schema only allows for 1.`))}}(t,r),{timestamp:new Date().toISOString(),id:"u">typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replaceAll(/[xy]/g,e=>{let t=Math.trunc(16*Math.random());return("x"===e?t:3&t|8).toString(16)}),event:{"hub.topic":e,"hub.event":t,context:r,...n?{"context.versionId":n}:{}}}}var tb=class extends null{constructor(e,t){if(super(),o(this,"subRequest"),o(this,"websocket"),this.subRequest=e,!e.endpoint)throw new w(v("Subscription request should contain an endpoint."));if(!tx(e))throw new w(v("Subscription request failed validation."));let{ReconnectingWebSocket:i=tp,...n}=t??{},r=new i(e.endpoint,void 0,n);r.addEventListener("open",()=>{this.dispatchEvent({type:"connect"})}),r.addEventListener("message",e=>{let t=JSON.parse(e.data);if(!t.event){"denied"===t["hub.mode"]&&this.disconnect();return}"heartbeat"!==t.event["hub.event"]&&(this.dispatchEvent({type:"message",payload:t}),r.send(JSON.stringify({id:t?.id,timestamp:new Date().toISOString()})))}),r.addEventListener("close",()=>{this.dispatchEvent({type:"disconnect"})}),this.websocket=r}disconnect(){this.websocket.close()}};function tw(e){let[t,i,n]=e.split(".");return JSON.parse(function(e){var t=(e=e.padEnd(e.length+(4-e.length%4)%4,"=")).replaceAll("-","+").replaceAll("_","/");if(tn()){let e=window.atob(t),i=Uint8Array.from(e,e=>e.codePointAt(0));return new window.TextDecoder().decode(i)}let i=tr();if(i)return i.from(t,"base64").toString("utf-8");throw Error("Unable to decode base64")}(i))}var tE=class{constructor(e){o(this,"medplum"),this.medplum=e}
1async get(e){return this.medplum.get(`keyvalue/v1/${e}`)}async set(e,t){await this.medplum.put(`keyvalue/v1/${e}`,t,tc.TEXT)}async delete(e){await this.medplum.delete(`keyvalue/v1/${e}`)}};n=Symbol.toStringTag;var tT=class{constructor(e){o(this,n,"ReadablePromise"),o(this,"suspender"),o(this,"status","pending"),o(this,"response"),o(this,"error"),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)}},tS=class{constructor(e,t=""){o(this,"storage"),o(this,"prefix",""),this.storage=e??globalThis.localStorage??new tC,this.prefix=t}makeKey(e){return this.prefix+e}clear(){if(this.storage===globalThis.localStorage&&this.prefix)for(let e=this.storage.length-1;e>=0;e--){let t=this.storage.key(e);t?.startsWith(this.prefix)&&this.storage.removeItem(t)}else this.storage.clear()}getString(e){return this.storage.getItem(this.makeKey(e))??void 0}setString(e,t){t?this.storage.setItem(this.makeKey(e),t):this.storage.removeItem(this.makeKey(e))}getObject(e){let t=this.getString(e);return t?JSON.parse(t):void 0}setObject(e,t){this.setString(e,t?JSON.stringify(function e(t){if(null!=t&&""!==t)return"object"==typeof t?Array.isArray(t)?function(t){let i=t.length;if(0===i)return;let n,r=0;for(let o=0;o<i;o++){let i=t[o],s=e(i);s===i||n||(n=Array.from(t)),void 0===s?n&&(n[o]=null):(n&&(n[o]=s),r++)}if(0!==r)return n??t}(t):function(t){let i,n=0;for(let r in t){let o=t[r],s=e(o);s===o||i||(i={...t}),void 0===s?i&&delete i[r]:(i&&(i[r]=s),n++)}if(0!==n)return i??t}(t):t}(t),null,void 0)??"":void 0)}},tC=class{constructor(){o(this,"data"),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]}},tR=[WebSocket.CLOSING,WebSocket.CLOSED],tP=class extends null{constructor(...e){super(),o(this,"criteria"),this.criteria=new Set(e)}getCriteria(){return this.criteria}_addCriteria(e){this.criteria.add(e)}_removeCriteria(e){this.criteria.delete(e)}},tk=class{constructor(e,t){o(this,"criteria"),o(this,"emitter"),o(this,"refCount"),o(this,"subscriptionProps"),o(this,"subscriptionId"),o(this,"token"),o(this,"tokenExpiry"),o(this,"state","idle"),o(this,"generation",0),o(this,"lastUnrefTime"),this.criteria=e,this.emitter=new tP(e),this.refCount=1,this.subscriptionProps=t?{...t}:void 0}nextGeneration(){return++this.generation}},tD=class{constructor(e,t,i){let n;if(o(this,"medplum"),o(this,"ws"),o(this,"masterSubEmitter"),o(this,"criteriaEntries"),o(this,"criteriaEntriesBySubscriptionId"),o(this,"wsClosed"),o(this,"pingTimer"),o(this,"tokenRefreshTimer"),o(this,"pingIntervalMs"),o(this,"waitingForPong",!1),o(this,"currentProfile"),!(e instanceof tL))throw new w(v("First arg of constructor should be a `MedplumClient`"));try{n=new URL(t).toString()}catch{throw new w(v("Not a valid URL"))}let r=i?.ReconnectingWebSocket?new i.ReconnectingWebSocket(n,void 0,{debug:i?.debug,debugLogger:i?.debugLogger}):new tp(n,void 0,{debug:i?.debug,debugLogger:i?.debugLogger});this.medplum=e,this.ws=r,this.masterSubEmitter=new tP,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=i?.pingIntervalMs??5e3,this.currentProfile=e.getProfile(),this.setupListeners()}setupListeners(){let e=this.ws;e.addEventListener("message",e=>{try{let t=JSON.parse(e.data);if("pong"===t.type){this.waitingForPong=!1;return}let i=t?.entry?.[0]?.resource;if(!i)return void console.warn("Received WebSocket message without a SubscriptionStatus resource; ignoring",t);if("heartbeat"===i.type)return void this.masterSubEmitter?.dispatchEvent({type:"heartbeat",payload:t});if("handshake"===i.type){let e=er(i.subscription),t={type:"connect",payload:{subscriptionId:e}};this.masterSubEmitter?.dispatchEvent(t);let n=this.criteriaEntriesBySubscriptionId.get(e);if(!n)return void console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");("connecting"===n.state||"refreshing"===n.state)&&(n.state="active"),n.emitter.dispatchEvent({...t});return}this.masterSubEmitter?.dispatchEvent({type:"message",payload:t});let n=this.criteriaEntriesBySubscriptionId.get(er(i.subscription));if(!n)return void console.warn("Received notification for criteria the SubscriptionManager is not listening for");n.emitter.dispatchEvent({type:"message",payload:t})}catch(t){console.error(t);let e={type:"error",payload:t};for(let t of(this.masterSubEmitter?.dispatchEvent(e),this.getAllCriteriaEmitters()))t.dispatchEvent({...e})}}),e.addEventListener("error",e=>{let t={type:"error",payload:new w({resourceType:"OperationOutcome",issue:[{severity:"error",code:"exception",details:{text:"WebSocket connection closed due to an error"},diagnostics:e.error?T(e.error):e.message}]})};for(let e of(this.masterSubEmitter?.dispatchEvent(t),this.getAllCriteriaEmitters()))e.dispatchEvent({...t})}),e.addEventListener("close",()=>{let e={type:"close"};for(let t of(this.masterSubEmitter?.dispatchEvent(e),this.getAllCriteriaEmitters()))t.dispatchEvent({...e});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.tokenRefreshTimer&&(clearInterval(this.tokenRefreshTimer),this.tokenRefreshTimer=void 0),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),this.masterSubEmitter?.removeAllListeners())}),e.addEventListener("open",()=>{let t={type:"open"};for(let e of(this.masterSubEmitter?.dispatchEvent(t),this.getAllCriteriaEmitters()))e.dispatchEvent({...t});this.refreshAllSubscriptions().catch(console.error),this.pingTimer??=setInterval(()=>{this.waitingForPong?(this.waitingForPong=!1,e.reconnect()):(e.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0),this.gcUnrefEntries()},this.pingIntervalMs),this.tokenRefreshTimer??=setInterval(()=>{this.checkTokenExpirations(),this.gcUnrefEntries()},6e4)}),this.medplum.addEventListener("change",()=>{let e=this.medplum.getProfile();this.currentProfile&&void 0===e?this.ws.close():e&&this.currentProfile?.id!==e.id&&this.ws.reconnect(),this.currentProfile=e})}sendBind(e){this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:e}}))}sendUnbind(e){this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:e}}))}emitError(e,t){let i={type:"error",payload:t};this.masterSubEmitter?.dispatchEvent(i),e.emitter.dispatchEvent({...i})}maybeEmitDisconnect(e){let{subscriptionId:t}=e;if(t){let i={type:"disconnect",payload:{subscriptionId:t}};this.masterSubEmitter?.dispatchEvent(i),e.emitter.dispatchEvent({...i})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}isStale(e,t){return this.isEntryGettingRemoved(e)||e.generation!==t}maybeGetCriteriaEntry(e,t){let i=this.criteriaEntries.get(e);if(i){if(!t)return i.bareCriteria;for(let e of i.criteriaWithProps)if(ea(t,e.subscriptionProps))return e}}getAllCriteriaEmitters(){let e=[];for(let t of this.criteriaEntries.values())for(let i of tA(t))i.refCount>0&&e.push(i.emitter);return e}addCriteriaEntry(e){let{criteria:t,subscriptionProps:i}=e,n;this.criteriaEntries.has(t)?n=this.criteriaEntries.get(t):(n={criteriaWithProps:[]},this.criteriaEntries.set(t,n)),i?n.criteriaWithProps.push(e):n.bareCriteria=e}removeCriteriaEntry(e){e.state="removed",e.generation++;let{criteria:t,subscriptionProps:i,subscriptionId:n,token:r}=e;if(!this.criteriaEntries.has(t))return;let o=this.criteriaEntries.get(t);i?o.criteriaWithProps=o.criteriaWithProps.filter(e=>!ea(i,e.subscriptionProps)):o.bareCriteria=void 0,o.bareCriteria||0!==o.criteriaWithProps.length||(this.criteriaEntries.delete(t),this.masterSubEmitter?._removeCriteria(t)),n&&this.criteriaEntriesBySubscriptionId.delete(n),r&&this.sendUnbind(r)}async subscribeToCriteria(e){this.wsClosed&&await this.reconnectIfNeeded(),this.ws.readyState===WebSocket.OPEN&&this.medplum.getProfile()&&"idle"===e.state&&(e.state="connecting",await this.rebindCriteriaEntry(e))}async refreshAllSubscriptions(){this.criteriaEntriesBySubscriptionId.clear();let e=[],t=[];for(let i of this.criteriaEntries.values())for(let n of tA(i))0===n.refCount?t.push(n):e.push(n);for(let e of t)this.removeCriteriaEntry(e);for(let t of e)t.token&&this.sendUnbind(t.token),t.token=void 0,t.tokenExpiry=void 0,t.subscriptionId=void 0,t.state="idle",t.generation++,await this.subscribeToCriteria(t)}async rebindCriteriaEntry(e){let t=e.nextGeneration();try{if(!e.subscriptionId){let i=await this.medplum.createResource({...e.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${en(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:e.criteria});if(e.subscriptionId??=i.id,this.isStale(e,t))return}let{parameter:i}=await this.medplum.get(`fhir/R4/Subscription/${e.subscriptionId}/$get-ws-binding-token`,{cache:"no-cache"}),n=i?.find(e=>"token"===e.name)?.valueString,r=i?.find(e=>"websocket-url"===e.name)?.valueUrl,o=i?.find(e=>"expiration"===e.name)?.valueDateTime;if(!n)throw new w(v("Failed to get token"));if(!r)throw new w(v("Failed to get URL from $get-ws-binding-token"));if(!o)throw new w(v("Failed to get expiration from $get-ws-binding-token"));if(this.isStale(e,t))return;e.token=n,e.tokenExpiry=new Date(o).getTime(),this.criteriaEntriesBySubscriptionId.set(e.subscriptionId,e),this.sendBind(n)}catch(i){console.error(T(i)),e.generation!==t||this.isEntryGettingRemoved(e)||(e.state="refreshing"===e.state?"active":"idle"),this.emitError(e,i)}}checkTokenExpirations(){if(!this.medplum.getProfile())return;let e=Date.now();for(let t of this.criteriaEntries.values())for(let i of tA(t))0===i.refCount||!i.tokenExpiry||i.tokenExpiry-e<=3e5&&"active"===i.state&&this.ws.readyState===WebSocket.OPEN&&(i.state="refreshing",this.rebindCriteriaEntry(i).catch(e=>{this.masterSubEmitter?.dispatchEvent({type:"error",payload:e})}))}addCriteria(e,t){this.masterSubEmitter&&this.masterSubEmitter._addCriteria(e);let i=this.maybeGetCriteriaEntry(e,t);if(i)return 0===i.refCount&&(i.lastUnrefTime=void 0,i.generation++,"active"!==i.state&&(i.state=i.token?"active":"idle")),i.refCount+=1,"idle"===i.state&&this.subscribeToCriteria(i).catch(console.error),i.emitter;let n=new tk(e,t);return this.addCriteriaEntry(n),this.subscribeToCriteria(n).catch(console.error),n.emitter}removeCriteria(e,t){let i=this.maybeGetCriteriaEntry(e,t);!i||this.isEntryGettingRemoved(i)?console.warn("Criteria not known to `SubscriptionManager`. Possibly called remove too many times."):(i.refCount-=1,0===i.refCount&&(i.lastUnrefTime=Date.now(),i.generation++))}gcUnrefEntries(){let e=Date.now(),t=[];for(let i of this.criteriaEntries.values())for(let n of tA(i))0===n.refCount&&void 0!==n.lastUnrefTime&&e-n.lastUnrefTime>=1e4&&t.push(n);for(let e of t)this.maybeEmitDisconnect(e),this.removeCriteriaEntry(e);t.length>0&&0===this.criteriaEntries.size&&this.closeWebSocket()}isEntryGettingRemoved(e){return 0===e.refCount||"removed"===e.state}getWebSocket(){return this.ws}closeWebSocket(){if(!this.wsClosed){if(this.ws.readyState===WebSocket.OPEN)for(let e of this.criteriaEntries.values())for(let t of tA(e))t.token&&this.sendUnbind(t.token);this.wsClosed=!0,this.ws.close()}}reconnectWebSocket(){this.ws.reconnect(),this.wsClosed=!1}
1getCriteriaCount(){return this.getAllCriteriaEmitters().length}getMasterEmitter(){return this.masterSubEmitter||(this.masterSubEmitter=new tP(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}async reconnectIfNeeded(){tR.includes(this.getWebSocket().readyState)&&await new Promise(e=>{let t=()=>{this.getWebSocket().removeEventListener("open",t),e()};this.getWebSocket().addEventListener("open",t),this.reconnectWebSocket()})}};function tA(e){return e.bareCriteria?[e.bareCriteria,...e.criteriaWithProps]:e.criteriaWithProps}new s(1e3);var t_=tc.FHIR_JSON+", */*; q=0.1",tL=class extends null{constructor(e){if(super(),o(this,"options"),o(this,"fetch"),o(this,"createPdfImpl"),o(this,"storage"),o(this,"requestCache"),o(this,"cacheTime"),o(this,"baseUrl"),o(this,"fhirBaseUrl"),o(this,"authorizeUrl"),o(this,"tokenUrl"),o(this,"logoutUrl"),o(this,"fhircastHubUrl"),o(this,"cdsServicesUrl"),o(this,"defaultHeaders"),o(this,"onUnauthenticated"),o(this,"autoBatchTime"),o(this,"autoBatchQueue"),o(this,"maxRetries"),o(this,"maxRetryTime"),o(this,"refreshGracePeriod"),o(this,"subscriptionManager"),o(this,"medplumServer"),o(this,"clientId"),o(this,"clientSecret"),o(this,"credentialsInHeader"),o(this,"autoBatchTimerId"),o(this,"accessToken"),o(this,"accessTokenExpires"),o(this,"refreshToken"),o(this,"refreshPromise"),o(this,"profilePromise"),o(this,"sessionDetails"),o(this,"currentRateLimits"),o(this,"basicAuth"),o(this,"initPromise"),o(this,"initComplete",!0),o(this,"keyValueClient"),o(this,"logLevel"),e?.baseUrl&&!e.baseUrl.startsWith("http"))throw Error("Base URL must start with http or https");this.options=e??{},this.fetch=e?.fetch??function(){if(!globalThis.fetch)throw Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}(),this.storage=e?.storage??new tS(void 0,e?.storagePrefix),this.createPdfImpl=e?.createPdf,this.baseUrl=eg(e?.baseUrl??"https://api.medplum.com/"),this.fhirBaseUrl=ex(this.baseUrl,e?.fhirUrlPath??"fhir/R4"),this.authorizeUrl=ex(this.baseUrl,e?.authorizeUrl??"oauth2/authorize"),this.tokenUrl=ex(this.baseUrl,e?.tokenUrl??"oauth2/token"),this.logoutUrl=ex(this.baseUrl,e?.logoutUrl??"oauth2/logout"),this.fhircastHubUrl=ex(this.baseUrl,e?.fhircastHubUrl??"fhircast/STU3"),this.cdsServicesUrl=ex(this.baseUrl,e?.cdsServicesUrl??"cds-services"),this.clientId=e?.clientId??"",this.clientSecret=e?.clientSecret??"",this.credentialsInHeader=e?.authCredentialsMethod==="header",this.defaultHeaders=e?.defaultHeaders??{},this.onUnauthenticated=e?.onUnauthenticated,this.refreshGracePeriod=e?.refreshGracePeriod??3e5,this.logLevel=this.initializeLogLevel(e),this.maxRetries=e?.maxRetries??2,this.maxRetryTime=e?.maxRetryTime??2e3,this.cacheTime=e?.cacheTime??6e4*!!tn(),this.cacheTime>0?this.requestCache=new s(e?.resourceCacheSize??1e3):this.requestCache=void 0,e?.autoBatchTime?(this.autoBatchTime=e.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),e?.accessToken&&this.setAccessToken(e.accessToken),void 0===this.storage.getInitPromise?(e?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve(),this.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{e?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(e=>{console.error(e),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:e}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}initializeLogLevel(e){return e?.logLevel?e.logLevel:e?.verbose!==void 0&&e.verbose?"verbose":"none"}async attemptResumeActiveLogin(){let e=this.getActiveLogin();e&&(this.setAccessToken(e.accessToken,e.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}getFhircastHubUrl(){return this.fhircastHubUrl}getCdsServicesUrl(){return this.cdsServicesUrl}getDefaultHeaders(){return this.defaultHeaders}clear(){this.storage.clear(),this.clearActiveLogin()}clearActiveLogin(){this.storage.setString("activeLogin",void 0),this.requestCache?.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.refreshPromise=void 0,this.accessTokenExpires=void 0,this.sessionDetail
1s=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(e){e=e.toString(),this.requestCache?.delete(e)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(e){let t=ex(this.fhirBaseUrl,e);for(let e of this.requestCache?.keys()??ev)(e.endsWith(t)||e.includes(t+"?"))&&this.requestCache?.delete(e)}notifyResourceModified(e){"delete"!==e.operation&&e.resource?this.cacheResource(e.resource,void 0):e.id&&this.deleteCacheEntry(this.fhirUrl(e.resourceType,e.id).toString()),this.invalidateSearches(e.resourceType),this.dispatchResourceModified(e)}get(e,t={}){let i;e=e.toString();let n=this.getCacheEntry(e,t);if(n)return n.value;e.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!t.disableAutoBatch?i=new Promise((i,n)=>{this.autoBatchQueue.push({method:"GET",url:e.replace(this.fhirBaseUrl,""),options:t,resolve:i,reject:n}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):(t.method="GET",i=this.request(e,t));let r=new tT(i);return this.setCacheEntry(e,r,t),r}post(e,t,i,n={}){return e=e.toString(),this.setRequestBody(n,t),i&&this.setRequestContentType(n,i),this.invalidateUrl(e),n.method="POST",this.request(e,n)}put(e,t,i,n={}){return e=e.toString(),this.setRequestBody(n,t),i&&this.setRequestContentType(n,i),this.invalidateUrl(e),n.method="PUT",this.request(e,n)}patch(e,t,i={}){return e=e.toString(),this.setRequestBody(i,t),this.setRequestContentType(i,tc.JSON_PATCH),this.invalidateUrl(e),i.method="PATCH",this.request(e,i)}delete(e,t={}){return e=e.toString(),this.invalidateUrl(e),t.method="DELETE",this.request(e,t)}async startNewUser(e,t){let{codeChallengeMethod:i,codeChallenge:n}=await this.startPkce();return this.post("auth/newuser",{...e,clientId:e.clientId??this.clientId,codeChallengeMethod:i,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){let t=new URLSearchParams(null.getSearch()).get("code");return t?this.processCode(t):void await this.requestAuthorization(e)}signOutWithRedirect(){null.assign(this.logoutUrl)}async signInWithExternalAuth(e,t,i,n,r=!0){let o=n;r&&(o=await this.ensureCodeChallenge(n)),null.assign(this.getExternalAuthRedirectUri(e,t,i,o,r))}async exchangeExternalAccessToken(e,t,i){if(!(t=t??this.clientId))throw Error("MedplumClient is missing clientId");let n={grant_type:null.TokenExchange,subject_token_type:null.AccessToken,client_id:t,subject_token:e};return i&&(n.membership_id=i),this.fetchTokens(n)}getExternalAuthRedirectUri(e,t,i,n,r=!0){let o=new URL(e);if(o.searchParams.set("response_type","code"),o.searchParams.set("client_id",t),o.searchParams.set("redirect_uri",i),o.searchParams.set("scope",n.scope??"openid profile email"),o.searchParams.set("state",JSON.stringify(n)),r){let{codeChallenge:e,codeChallengeMethod:t}=n;if(!t)throw Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!e)throw Error("`LoginRequest` for external auth must include a `codeChallenge`.");o.searchParams.set("code_challenge_method",t),o.searchParams.set("code_challenge",e)}return o.toString()}fhirUrl(...e){return new URL(ex(this.fhirBaseUrl,e.join("/")))}fhirSearchUrl(e,t){var i;let n=this.fhirUrl(e);return t&&("object"!=typeof(i=t)||Array.isArray(i)||i instanceof URLSearchParams||(i=Object.fromEntries(Object.entries(i).filter(e=>void 0!==e[1]))),n.search=new URLSearchParams(i).toString()),n}search(e,t,i){let n=this.fhirSearchUrl(e,t),r="search-"+n.toString(),o=this.getCacheEntry(r,i);if(o)return o.value;let s=this.getBundle(n,i);return this.setCacheEntry(r,s,i),s}searchOne(e,t,i){let n=this.fhirSearchUrl(e,t);n.searchParams.set("_count","1"),n.searchParams.sort();let r="searchOne-"+n.toString(),o=this.getCacheEntry(r,i);if(o)return o.value;let s=new tT(this.search(e,n.searchParams,i).then(e=>e.entry?.[0]?.resource));return this.setCacheEntry(r,s,i),s}searchResources(e,t,i){let n="searchResources-"+this.fhirSearchUrl(e,t).toString(),r=this.getCacheEntry(n,i);if(r)return r.value;let o=new tT(this.search(e,t,i).then(tI));return this.setCacheEntry(n,o,i),o}async *searchResourcePages(e,t,i){let n=this.fhirSearchUrl(e,t);for(;n;){let t=new URL(n).searchParams;t.has("_count")||t.set("_count","1000");let r=await this.search(e,t,i),o=r.link?.find(e=>"next"===e.relation);if(!r.entry?.length&&!o)break;yield tI(r),n=o?.url?new URL(o.url):void 0}}valueSetExpand(e,t){let i=this.fhirUrl("ValueSet","$expand");return i.search=new URLSearchParams(e).toString(),this.get(i.toString(),t)}getCached(e,t){let i=this.requestCache?.get(this.fhirUrl(e,t).toString())?.value;return i?.isOk()?i.read():void 0}getCachedReference(e){let t=e.reference;if(!t)return;if("system"===t)return null;let[i,n]=t.split("/");if(!(!i||!n))return this.getCached(i,n)}readResource(e,t,i){if(!t)throw Error('The "id" parameter cannot be null, undefined, or an empty string.');return this.get(this.fhirUrl(e,t),i)}readReference(e,t){let i=e.reference;if(!i)return new tT(Promise.reject(Error("Missing reference")));if("system"===i)return new tT(Promise.resolve(null));let[n,r]=i.split("/");return n&&r?this.readResource(n,r,t):new tT(Promise.reject(Error("Invalid reference")))}readCanonical(e,t,i){return Array.isArray(e)?this.searchOne("",{_type:e.join(","),url:t},i):this.searchOne(e,"url="+t,i)}requestSchema(e,t){if(R[e])return Promise.resolve();let i=e+"-requestSchema",n=this.getCacheEntry(i,void 0);if(n)return n.value;let r=new tT((async()=>{let t=`{
2      StructureDefinitionList(_filter: "name eq ${e}") {
3        resourceType,
4        name,
5        kind,
6        description,
7        type,
8        url,
9        snapshot {
10          element {
11            id,
12            path,
13            definition,
14            min,
15            max,
16            base {
17              path,
18              min,
19              max
20            },
21            contentReference,
22            type {
23              code,
24              profile,
25              targetProfile
26            },
27            binding {
28              strength,
29              valueSet
30            }
31          }
32        }
33      }
34      SearchParameterList(base: "${e}
34", _count: 100) {
35        base,
36        code,
37        type,
38        expression,
39        target
40      }
41    }`.replaceAll(/\s+/g," "),i=await this.graphql(t);for(let e of(A(i.data.StructureDefinitionList),i.data.SearchParameterList))for(let t of e.base??ev){let i=eS(t);i.searchParams||(i.searchParams={}),i.searchParams[e.code]=e}})());return this.setCacheEntry(i,r,t),r}requestProfileSchema(e,t){if(!t?.expandProfile&&P[e])return Promise.resolve();let i=e+"-requestSchema"+(t?.expandProfile?"-nested":""),n=this.getCacheEntry(i,void 0);if(n)return n.value;let r=new tT((async()=>{if(t?.expandProfile){let t=this.fhirUrl("StructureDefinition","$expand-profile");t.search=new URLSearchParams({url:e}).toString(),A(await this.post(t.toString(),{}))}else{let t=await this.searchOne("StructureDefinition",{url:e,_sort:"-_lastUpdated"});if(!t)return void console.warn(`No StructureDefinition found for ${e}!`);_(t)}})());return this.setCacheEntry(i,r,t),r}readHistory(e,t,i,n){let r=this.fhirUrl(e,t,"_history");return i?.count&&r.searchParams.set("_count",i.count.toString()),i?.offset&&r.searchParams.set("_offset",i.offset.toString()),this.get(r.toString(),n)}readVersion(e,t,i,n){return this.get(this.fhirUrl(e,t,"_history",i),n)}readPatientEverything(e,t){return this.getBundle(this.fhirUrl("Patient",e,"$everything"),t)}readPatientSummary(e,t){return this.getBundle(this.fhirUrl("Patient",e,"$summary"),t)}async createResource(e,t){if(!e.resourceType)throw Error("Missing resourceType");this.invalidateSearches(e.resourceType);let i=await this.post(this.fhirUrl(e.resourceType),e,void 0,t);return this.dispatchResourceModified({resourceType:e.resourceType,operation:"create",id:i?.id,resource:i}),i}async createResourceIfNoneExist(e,t,i={}){let n=this.fhirUrl(e.resourceType);this.setRequestHeader(i,"If-None-Exist",t);let r=await this.post(n,e,void 0,i);return this.cacheResource(r,i),this.invalidateUrl(this.fhirUrl(e.resourceType,e.id,"_history")),this.invalidateSearches(e.resourceType),this.dispatchResourceModified({resourceType:e.resourceType,operation:"create",id:r?.id,resource:r}),r}async upsertResource(e,t,i){let n=this.fhirSearchUrl(e.resourceType,t),r=await this.put(n,e,void 0,i),o=void 0!==r;return r||(r=e),this.cacheResource(r,i),this.invalidateUrl(this.fhirUrl(e.resourceType,e.id,"_history")),this.invalidateSearches(e.resourceType),o&&this.dispatchResourceModified({resourceType:e.resourceType,operation:"update",id:r.id,resource:r}),r}async createAttachment(e,t,i,n,r){let o=tU(e,t,i,n);if(o.contentType===tc.XML){let e=o.data,t;(t=e instanceof Blob?await new Promise((t,i)=>{let n=new FileReader;n.onload=()=>{n.result?t(n.result):i(Error("Failed to load file"))},n.readAsText(e,"utf-8")}):ArrayBuffer.isView(e)?new TextDecoder().decode(e):e).includes("<ClinicalDocument")&&t.includes("urn:hl7-org:v3")&&(o={...o,contentType:tc.CDA_XML})}let s=r??("object"==typeof t?t:{}),a=await this.createBinary(o,s);return{contentType:o.contentType,url:a.url,title:o.filename}}createBinary(e,t,i,n,r){let o=tU(e,t,i,n),s=r??("object"==typeof t?t:{}),{data:a,contentType:c,filename:d,securityContext:l,onProgress:f}=o,h=this.fhirUrl("Binary");return d&&h.searchParams.set("_filename",d),l?.reference&&this.setRequestHeader(s,"X-Security-Context",l.reference),f?this.uploadwithProgress(h,a,c,f,s):this.post(h,a,c,s)}uploadwithProgress(e,t,i,n,r){return new Promise((o,s)=>{let a=new XMLHttpRequest,c=()=>a.abort();r?.signal?.addEventListener("abort",c);let d=e=>{r?.signal?.removeEventListener("abort",c),e instanceof Error?s(e):o(e)};if(a.responseType="json",a.onabort=()=>d(new DOMException("Request aborted","AbortError")),a.onerror=()=>d(Error("Request error")),n&&(a.upload.onprogress=e=>n(e),a.upload.onload=e=>n(e)),a.onload=()=>{a.status>=200&&a.status<300?d(a.response):d(new w(E(a.response||a.statusText)))},a.open("POST",e),a.withCredentials=!0,a.setRequestHeader("Authorization","Bearer "+this.accessToken),a.setRequestHeader("Cache-Control","no-cache, no-store, max-age=0"),a.setRequestHeader("Content-Type",i),!1!==this.options.extendedMode&&a.setRequestHeader("X-Medplum","extended"),r?.headers)for(let[e,t]of Object.entries(r.headers))a.setRequestHeader(e,t);a.send(t)})}async createPdf(e,t,i,n){if(!this.createPdfImpl)throw Error("PDF creation not enabled");let r=function(e,t,i,n){return ed(e)&&"docDefinition"in e?e:{docDefinition:e,filename:t,tableLayouts:i,fonts:n}}(e,t,i,n),o="object"==typeof t?t:{},{docDefinition:s,tableLayouts:a,fonts:c,...d}=r,l=await this.createPdfImpl(s,a,c),f={...d,data:l,contentType:"application/pdf"};return this.createBinary(f,o)}createComment(e,t,i){let n=this.getProfile(),r,o;return"Encounter"===e.resourceType&&(r=ei(e),o=e.subject),"ServiceRequest"===e.resourceType&&(r=e.encounter,o=e.subject),"Patient"===e.resourceType&&(o=ei(e)),this.createResource({resourceType:"Communication",status:"completed",basedOn:[ei(e)],encounter:r,subject:o,sender:n?ei(n):void 0,sent:new Date().toISOString(),payload:[{contentString:t}]},i)}async updateResource(e,t){if(!e.resourceType)throw Error("Missing resourceType");if(!e.id)throw Error("Missing id");let i=await this.put(this.fhirUrl(e.resourceType,e.id),e,void 0,t),n=void 0!==i;
41return i||(i=e),this.cacheResource(i,t),this.invalidateUrl(this.fhirUrl(e.resourceType,e.id,"_history")),this.invalidateSearches(e.resourceType),n&&this.dispatchResourceModified({resourceType:e.resourceType,operation:"update",id:i.id,resource:i}),i}async patchResource(e,t,i,n){let r=await this.patch(this.fhirUrl(e,t),i,n);return this.cacheResource(r,n),this.invalidateUrl(this.fhirUrl(e,t,"_history")),this.invalidateSearches(e),this.dispatchResourceModified({resourceType:e,operation:"patch",id:t,resource:r}),r}async deleteResource(e,t,i){this.deleteCacheEntry(this.fhirUrl(e,t).toString()),this.invalidateSearches(e);let n=await this.delete(this.fhirUrl(e,t),i);return this.dispatchResourceModified({resourceType:e,operation:"delete",id:t}),n}validateResource(e,t){return this.post(this.fhirUrl(e.resourceType,"$validate"),e,void 0,t)}executeBot(e,t,i,n){let r;return"string"==typeof e?r=this.fhirUrl("Bot",e,"$execute"):(r=this.fhirUrl("Bot","$execute")).searchParams.set("identifier",e.system+"|"+e.value),this.post(r,t,i,n)}executeBatch(e,t){return this.post(this.fhirBaseUrl,e,void 0,t)}sendEmail(e,t){return this.post("email/v1/send",e,tc.JSON,t)}graphql(e,t,i,n){return this.post(this.fhirUrl("$graphql"),{query:e,operationName:t,variables:i},tc.JSON,n)}readResourceGraph(e,t,i,n){return this.get(`${this.fhirUrl(e,t)}/$graph?graph=${i}`,n)}pushToAgent(e,t,i,n,r,o){let{waitTimeout:s,returnAck:a,...c}=o??{};return this.post(this.fhirUrl("Agent",er(e),"$push"),{destination:"string"==typeof t?t:en(t),body:i,contentType:n,waitForResponse:r,...void 0!==s?{waitTimeout:s}:void 0,...void 0!==a?{returnAck:a}:void 0},tc.FHIR_JSON,c)}getCdsServices(e){return this.get(this.cdsServicesUrl,e)}callCdsService(e,t,i){return this.post(ex(this.cdsServicesUrl,e),t,tc.JSON,i)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(e){this.sessionDetails?.profile&&en(this.sessionDetails.profile)===e.profile?.reference||this.clearActiveLogin(),this.setAccessToken(e.accessToken,e.refreshToken),this.storage.setObject("activeLogin",e),this.addLogin(e),this.refreshPromise=void 0,await this.refreshProfile()}getAccessToken(){return this.accessToken}isAuthenticated(e){return void 0!==this.accessTokenExpires&&Date.now()<this.accessTokenExpires-(e??this.refreshGracePeriod)}setAccessToken(e,t){this.accessToken=e,this.refreshToken=t,this.accessTokenExpires=function(e){try{let t=tw(e).exp;return"number"==typeof t?1e3*t:void 0}catch{return}}(e),this.medplumServer=function(e){try{return"string"==typeof tw(e).login_id}catch{return!1}}(e)}getLogins(){return this.storage.getObject("logins")??[]}addLogin(e){let t=this.getLogins().filter(t=>t.profile?.reference!==e.profile?.reference);t.push(e),this.storage.setObject("logins",t)}async refreshProfile(){if(this.medplumServer)return this.profilePromise=new Promise((e,t)=>{this.get("auth/me",{cache:"no-cache"}).then(t=>{this.profilePromise=void 0;let i=this.sessionDetails?.profile?.id!==t.profile.id;this.sessionDetails=t,this.syncStoredLoginProject(),i&&this.dispatchEvent({type:"change"}),e(t.profile),this.dispatchEvent({type:"profileRefreshed"})}).catch(t)}),this.dispatchEvent({type:"profileRefreshing"}),this.profilePromise}syncStoredLoginProject(){let e=this.getActiveLogin(),t=this.sessionDetails?.project?.name;if(!e||!t||e.project.display===t)return;let i={...e,project:{...e.project,display:t}};this.storage.setObject("activeLogin",i),this.addLogin(i)}isLoading(){return!this.isInitialized||!!this.profilePromise&&!this.sessionDetails?.profile}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?this.profilePromise:this.sessionDetails?this.sessionDetails.profile:this.refreshProfile()}getUserConfiguration(){return this.sessionDetails?.config}getAccessPolicy(){return this.sessionDetails?.accessPolicy}async download(e,t={}){return(await this.downloadResponse(e,t)).blob()}async downloadResponse(e,t={}){this.refreshPromise&&await this.refreshPromise;let i=e.toString();i.startsWith("Binary/")&&(e=this.fhirUrl(i));let n=t.headers;return n||(t.headers=n={}),n.Accept||(n.Accept="*/*"),this.addFetchOptionsDefaults(t,e.toString()),this.fetchWithRetry(e.toString(),t)}async createMedia(e,t){let{additionalFields:i,...n}=e,r=await this.createResource({resourceType:"Media",status:"preparation",content:{contentType:e.contentType},...i});n.securityContext||(n.securityContext=ei(r));let o=await this.createAttachment(n,t);return this.updateResource({...r,status:"completed",content:o})}async uploadMedia(e,t,i,n,r){return this.createMedia({data:e,contentType:t,filename:i,additionalFields:n},r)}async createDocumentReference(e,t){let{additionalFields:i,...n}=e,r=await this.createResource({resourceType:"DocumentReference",status:"current",content:[{attachment:{contentType:e.contentType}}],...i});n.securityContext||(n.securityContext=ei(r));let o=await this.createAttachment(n,t);return this.updateResource({...r,content:[{attachment:o}]})}async bulkExport(e="",t,i,n){let r=e&&`${e}/`,o=this.fhirUrl(`${r}$export`);return t&&o.searchParams.set("_type",t),i&&o.searchParams.set("_since",i),this.startAsyncRequest(o.toString(),n)}
41async startAsyncRequest(e,t={}){return this.addFetchOptionsDefaults(t,e),t.headers.Prefer="respond-async",t.method="POST",this.request(e,t)}async wrappedFetch(e,t){return await this.refreshIfExpired(),this.addFetchOptionsDefaults(t,e),this.fetchWithRetry(e,t)}get keyValue(){return this.keyValueClient||(this.keyValueClient=new tE(this)),this.keyValueClient}getBundle(e,t){return new tT((async()=>{let i=await this.get(e,t);for(let e of i.entry??ev)this.cacheResource(e.resource,t);return i})())}isCacheEnabled(e){return!!this.requestCache&&!this.getRequestHeader(e,"x-medplum-on-behalf-of")}getCacheEntry(e,t){if(!this.isCacheEnabled(t)||t?.cache==="no-cache"||t?.cache==="reload")return;let i=this.requestCache.get(e);if(!(!i||i.requestTime+this.cacheTime<Date.now()))return i}setCacheEntry(e,t,i){this.isCacheEnabled(i)&&(this.requestCache.set(e,{requestTime:Date.now(),value:t}),i?.signal&&i.signal.addEventListener("abort",()=>{this.requestCache.delete(e)}))}cacheResource(e,t){e?.id&&!e.meta?.tag?.some(e=>"SUBSETTED"===e.code)&&this.setCacheEntry(this.fhirUrl(e.resourceType,e.id).toString(),new tT(Promise.resolve(e)),t)}deleteCacheEntry(e){this.requestCache&&this.requestCache.delete(e)}dispatchResourceModified(e){this.listenerCount("resourceModified")>0&&this.dispatchEvent({type:"resourceModified",payload:e})}async request(e,t={},i={}){let n=await this.wrappedFetch(e,t);if(401===n.status)return this.handleUnauthenticated(e,t,i);if(204===n.status||304===n.status)return;let r=n.headers.get("content-type")?.includes("json");if(404===n.status&&!r)throw new w(p);let o=await this.parseBody(n,r);if(200===n.status&&t.followRedirectOnOk||201===n.status&&t.followRedirectOnCreated){let e=await tj(n,o);if(e)return this.request(e,{...t,method:"GET",body:void 0})}if(202===n.status&&t.pollStatusOnAccepted){let e=await tj(n,o)??i.statusUrl;if(e)return this.pollStatus(e,t,i)}if(n.status>=400)throw new w(E(o));return o}async parseBody(e,t){let i;if("0"!==e.headers.get("content-length")){if(t)try{i=await e.json()}catch(t){throw console.error("Error parsing response",e.status,t),t}else i=await e.text();return i}}async fetchWithRetry(e,t){e.startsWith("http")||(e=ex(this.baseUrl,e));let i=t?.maxRetries??this.maxRetries;for(let r=0;r<=i;r++)try{var n;"none"!==this.logLevel&&this.logRequest(e,t);let o=await this.fetch(e,t);if("none"!==this.logLevel&&this.logResponse(o),this.setCurrentRateLimit(o),r>=i||(n=o,429!==n.status&&!(n.status>=500)))return o;let s=this.getRetryDelay(r),a=t.maxRetryTime??this.maxRetryTime;if(s>a)return o;await em(s,{signal:t.signal})}catch(e){if("Failed to fetch"===e.message&&0===r&&this.dispatchEvent({type:"offline"}),"AbortError"===e.name||r===i)throw e}throw Error("Unreachable")}logRequest(e,t){if(console.log(`> ${t.method} ${e}`),"verbose"===this.logLevel&&t.headers){let e=t.headers;for(let t of Object.keys(e).sort((e,t)=>e.localeCompare(t)))console.log(`> ${t}: ${e[t]}`)}}logResponse(e){console.log(`< ${e.status} ${e.statusText}`),"verbose"===this.logLevel&&e.headers&&e.headers.forEach((e,t)=>console.log(`< ${t}: ${e}`))}setCurrentRateLimit(e){if(!e?.headers||"function"!=typeof e.headers.get)return;let t=e.headers.get("ratelimit");t&&(this.currentRateLimits=t)}rateLimitStatus(){if(!this.currentRateLimits)return[];let e=this.currentRateLimits;return e.split(",").map(t=>{let i=t.split(";").map(e=>e.trim());if(3!==i.length)throw Error("Could not parse RateLimit header: "+e);let n=i[0].substring(1,i[0].length-1),r=i.find(e=>e.startsWith("r="))?.substring(2),o=r?Number.parseInt(r,10):NaN,s=i.find(e=>e.startsWith("t="))?.substring(2),a=s?Number.parseInt(s,10):NaN;if(!n||Number.isNaN(o)||Number.isNaN(a))throw Error("Could not parse RateLimit header: "+e);return{name:n,remainingUnits:o,secondsUntilReset:a,resetsAfter:Math.ceil((Date.now()+1e3*a)/1e3)}})}getRetryDelay(e){let t=this.rateLimitStatus(),i=500*Math.pow(1.5,e);for(let e of t)e.remainingUnits||(i=Math.max(i,1e3*e.secondsUntilReset));return i}async pollStatus(e,t,i){let n={...t,method:"GET",body:void 0,redirect:"follow"};if(void 0===i.pollCount)t.headers&&"object"==typeof t.headers&&"Prefer"in t.headers&&(n.headers={...t.headers},delete n.headers.Prefer),i.statusUrl=e,i.pollCount=1;else{let e=t.pollStatusPeriod??1e3;await em(e,{signal:t.signal}),i.pollCount++}return this.request(e,n,i)}async executeAutoBatch(){if(void 0===this.autoBatchQueue)return;let e=[...this.autoBatchQueue];if(this.autoBatchQueue.length=0,this.autoBatchTimerId=void 0,1===e.length){let t=e[0];try{t.options.method=t.method,t.resolve(await this.request(ex(this.fhirBaseUrl,t.url),t.options))}catch(e){t.reject(new w(E(e)))}return}let 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}))},i=await this.post(this.fhirBaseUrl,t);for(let t=0;t<e.length;t++){var n;let r=e[t],o=i.entry?.[t];o?.response?.outcome&&"ok"!==(n=o.response.outcome).id&&"created"!==n.id&&"not-modified"!==n.id&&"accepted"!==n.id?r.reject(new w(o.response.outcome)):r.resolve(o?.resource)}}isInternalUrl(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return!0;try{let t=new URL(e);return e.startsWith(this.baseUrl)||e.startsWith(this.fhirBaseUrl)||t.origin===new URL(this.baseUrl).origin&&eg(t.pathname).startsWith(eg(new URL(this.baseUrl).pathname))}catch{return!1}}addFetchOptionsDefaults(e,t){Object.entries(this.defaultHeaders).forEac
41h(([t,i])=>{this.setRequestHeader(e,t,i)}),this.setRequestHeader(e,"Accept",t_,!0),!1!==this.options.extendedMode&&this.setRequestHeader(e,"X-Medplum","extended"),e.body&&this.setRequestHeader(e,"Content-Type",tc.FHIR_JSON,!0),this.isInternalUrl(t)&&(this.accessToken?this.setRequestHeader(e,"Authorization","Bearer "+this.accessToken):this.basicAuth&&this.setRequestHeader(e,"Authorization","Basic "+this.basicAuth),e.credentials||(e.credentials="include"))}setRequestContentType(e,t){this.setRequestHeader(e,"Content-Type",t)}getRequestHeader(e,t){let i=e?.headers;if(i){if(Array.isArray(i)){let e=i.find(([e])=>e.toLowerCase()===t.toLowerCase());return e?e[1]:void 0}if(i instanceof Headers)return i.get(t)??void 0;if(ed(i))return i[t]??void 0}}setRequestHeader(e,t,i,n=!1){let r=e.headers;r?Array.isArray(r)?n&&r.some(([e])=>e.toLowerCase()===t.toLowerCase())||r.push([t,i]):r instanceof Headers?n&&r.has(t)||r.set(t,i):!ed(r)||n&&r[t]||(r[t]=i):e.headers={[t]:i}}setRequestBody(e,t){"string"==typeof t||"u">typeof Blob&&(t instanceof Blob||t?.constructor.name==="Blob")||"u">typeof File&&(t instanceof File||t?.constructor.name==="File")||"u">typeof Uint8Array&&(t instanceof Uint8Array||t?.constructor.name==="Uint8Array")?e.body=t:"object"==typeof t&&null!==t&&("function"==typeof t.getReader||"function"==typeof t.pipe&&"function"==typeof t.on)?(e.body=t,e.duplex="half"):t&&(e.body=JSON.stringify(t))}async handleUnauthenticated(e,t,i){let n=i.authAttempt??0,r=n+1<2?this.refresh(void 0,!0):void 0;if(r)return await r,this.request(e,t,{...i,authAttempt:n+1});throw this.clear(),this.onUnauthenticated?.(),new w(m)}async startPkce(){let e=ts();this.storage.setString("pkceState",e);let t=ts().slice(0,128);this.storage.setString("codeVerifier",t);try{let e=await ta(t);return{codeChallengeMethod:"S256",codeChallenge:(function(e){let t=new Uint8Array(eu(e)),i=Array(t.length);for(let e=0;e<t.length;e++)i[e]=String.fromCodePoint(t[e]);return window.btoa(i.join(""))})(e).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}}catch(e){return console.warn("Failed to hash code verifier. Falling back to 'plain' code challenge method",e),{codeChallengeMethod:"plain",codeChallenge:t}}}async requestAuthorization(e){let t=await this.ensureCodeChallenge(e??{}),i=new URL(this.authorizeUrl);i.searchParams.set("response_type","code"),i.searchParams.set("state",this.storage.getString("pkceState")),i.searchParams.set("client_id",t.clientId??this.clientId),i.searchParams.set("redirect_uri",t.redirectUri??null.getOrigin()),i.searchParams.set("code_challenge_method",t.codeChallengeMethod),i.searchParams.set("code_challenge",t.codeChallenge),i.searchParams.set("scope",t.scope??"openid profile"),null.assign(i.toString())}processCode(e,t){let i={grant_type:null.AuthorizationCode,code:e,client_id:t?.clientId??this.clientId??"",redirect_uri:t?.redirectUri??null.getOrigin()},n=this.storage.getString("codeVerifier");return n&&(i.code_verifier=n),this.fetchTokens(i)}refreshIfExpired(e){return this.refreshPromise||void 0===this.accessTokenExpires||this.isAuthenticated(e)||this.refresh(e),this.refreshPromise??Promise.resolve()}refresh(e,t=!1){return this.refreshPromise?this.refreshPromise:this.refreshToken||this.clientId&&this.clientSecret?(this.refreshPromise=this.runRefreshWithLock(e,t),this.refreshPromise):void 0}async runRefreshWithLock(e,t=!1){let i=()=>{let i=this.accessToken,n=this.getActiveLogin();n?.accessToken&&n.accessToken!==this.accessToken&&this.setAccessToken(n.accessToken,n.refreshToken);let r=this.accessToken!==i;return this.isAuthenticated(e)&&(!t||r)?Promise.resolve(this.getProfile()):this.refreshToken?this.fetchTokens({grant_type:null.RefreshToken,client_id:this.clientId??"",refresh_token:this.refreshToken}):this.clientId&&this.clientSecret?this.startClientLogin(this.clientId,this.clientSecret):Promise.resolve(void 0)},n="u">typeof navigator?navigator.locks:void 0;if(!n?.request)return i();let r=`medplum-refresh:${this.storage.makeKey("activeLogin")}`;return n.request(r,i)}async startClientLogin(e,t){return this.clientId=e,this.clientSecret=t,this.fetchTokens({grant_type:null.ClientCredentials,client_id:e,client_secret:t})}
41async startJwtBearerLogin(e,t,i){return this.clientId=e,this.fetchTokens({grant_type:null.JwtBearer,client_id:e,assertion:t,scope:i})}async startJwtAssertionLogin(e){return this.fetchTokens({grant_type:null.ClientCredentials,client_assertion_type:null.JwtBearer,client_assertion:e})}setBasicAuth(e,t){this.clientId=e,this.clientSecret=t,this.basicAuth=to(e+":"+t)}setLogLevel(e){this.logLevel=e,this.options.verbose="verbose"===e}getLogLevel(){return this.logLevel}setVerbose(e){this.logLevel=e?"verbose":"none",this.options.verbose=e}async fhircastSubscribe(e,t){if("string"!=typeof e||""===e)throw new w(v("Invalid topic provided. Topic must be a valid string."));if(!("object"==typeof t&&Array.isArray(t)&&t.length>0))throw new w(v("Invalid events provided. Events must be an array of event names containing at least one event."));let i={channelType:"websocket",mode:"subscribe",topic:e,events:t},n=(await this.post(this.fhircastHubUrl,tg(i),tc.FORM_URL_ENCODED))["hub.channel.endpoint"];if(!n)throw Error("Invalid response!");return i.endpoint=n,i}async fhircastUnsubscribe(e){if(!tx(e))throw new w(v("Invalid topic or subscriptionRequest. SubscriptionRequest must be an object."));if(!(e.endpoint&&"string"==typeof e.endpoint&&e.endpoint.startsWith("ws")))throw new w(v("Provided subscription request must have an endpoint in order to unsubscribe."));e.mode="unsubscribe",await this.post(this.fhircastHubUrl,tg(e),tc.FORM_URL_ENCODED)}fhircastConnect(e,t){return new tb(e,t)}async fhircastPublish(e,t,i,n){return null.includes(t)?this.post(this.fhircastHubUrl,tv(e,t,i,n),tc.JSON):(function(e){if(null.includes(e))throw new w(v(`'context.version' is required for '${e}'.`))}(t),this.post(this.fhircastHubUrl,tv(e,t,i),tc.JSON))}async fhircastGetContext(e){return this.get(`${this.fhircastHubUrl}/${e}`,{cache:"no-cache"})}async invite(e,t){return this.post("admin/projects/"+e+"/invite",t)}async handleTokenError(e){try{let t=await e.json();throw b(t)?new w(t):t.error_description?new w(x(t.error_description)):Error(JSON.stringify(t))}catch(e){throw e instanceof w?(e.message=`Failed to fetch tokens: ${e.message}`,e):new w(x("Failed to fetch tokens"),{cause:e})}}async fetchTokens(e){let t=new URLSearchParams(e),i={...this.defaultHeaders,"Content-Type":tc.FORM_URL_ENCODED};this.basicAuth&&(i.Authorization=`Basic ${this.basicAuth}`),this.credentialsInHeader&&(t.delete("client_id"),t.delete("client_secret"),!this.basicAuth&&e.client_id&&e.client_secret&&(i.Authorization=`Basic ${to(e.client_id+":"+e.client_secret)}`));let n={method:"POST",headers:i,body:t.toString(),credentials:"include"},r;try{r=await this.fetchWithRetry(this.tokenUrl,n)}catch(e){throw this.refreshPromise=void 0,e}r.ok||(this.clearActiveLogin(),this.onUnauthenticated?.(),await this.handleTokenError(r));let o=await r.json();return await this.verifyTokens(o),this.getProfile()}async verifyTokens(e){let t=e.access_token;if(3===t.split(".").length){let e=tw(t);if(Date.now()>=1e3*e.exp)throw this.clearActiveLogin(),new w(y);if(e.cid){if(e.cid!==this.clientId)throw this.clearActiveLogin(),new w(g)}else if(this.clientId&&e.client_id!==this.clientId)throw this.clearActiveLogin(),new w(g)}return this.setActiveLogin({accessToken:t,refreshToken:e.refresh_token,project:e.project,profile:e.profile})}checkSessionDetailsMatchLogin(e){return!this.sessionDetails||!e||(e.profile?.reference?.endsWith(this.sessionDetails.profile.id)??!1)}setupStorageListener(){try{window.addEventListener("storage",e=>{if(null===e.key)null.reload();else if(e.key===this.storage.makeKey("activeLogin")){let t=e.oldValue?JSON.parse(e.oldValue):void 0,i=e.newValue?JSON.parse(e.newValue):void 0;t?.profile.reference===i?.profile.reference&&this.checkSessionDetailsMatchLogin(i)?i?this.setAccessToken(i.accessToken,i.refreshToken):this.clear():null.reload()}})}catch{}}getSubscriptionManager(){return this.subscriptionManager||(this.subscriptionManager=new tD(this,ex(this.baseUrl,"/ws/subscriptions-r4").toString().replace("http://","ws://").replace("https://","wss://"))),this.subscriptionManager}subscribeToCriteria(e,t){return this.getSubscriptionManager().addCriteria(e,t)}unsubscribeFromCriteria(e,t){this.subscriptionManager&&this.subscriptionManager.removeCriteria(e,t)}
41getMasterSubscriptionEmitter(){return this.getSubscriptionManager().getMasterEmitter()}};async function tj(e,t){let i=e.headers.get("content-location");if(i)return i;let n=e.headers.get("location");return n||(b(t)&&t.issue?.[0]?.diagnostics?t.issue[0].diagnostics:void 0)}function tI(e){return Object.assign(e.entry?.map(e=>e.resource)??[],{bundle:e})}function tU(e,t,i,n){return ed(e)&&"data"in e&&"contentType"in e?e:{data:e,filename:t,contentType:i,onProgress:n}}[...e5],ti().registerInfix("->",{precedence:100}).registerInfix(";",{precedence:200}),Object.prototype.hasOwnProperty,Object.freeze({implicitArrayCreation:!0})," ".repeat(2),[...e5],ti(),new WeakMap}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.