@medplum/app 5.0.6 → 5.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -56,7 +56,7 @@ ${d}`}function wa({color:e,theme:t,autoContrast:n}){return(typeof n=="boolean"?n
|
|
|
56
56
|
`),s=!1),Object.assign(Object.assign({},e),{allowNegative:s})}function pz(e){e=hz(e),e.decimalSeparator,e.allowedDecimalSeparators,e.thousandsGroupStyle;var t=e.suffix,n=e.allowNegative,r=e.allowLeadingZeros,o=e.onKeyDown;o===void 0&&(o=us);var s=e.onBlur;s===void 0&&(s=us);var c=e.thousandSeparator,d=e.decimalScale,f=e.fixedDecimalScale,p=e.prefix;p===void 0&&(p="");var m=e.defaultValue,g=e.value,y=e.valueIsNumericString,b=e.onValueChange,S=GA(e,["decimalSeparator","allowedDecimalSeparators","thousandsGroupStyle","suffix","allowNegative","allowLeadingZeros","onKeyDown","onBlur","thousandSeparator","decimalScale","fixedDecimalScale","prefix","defaultValue","value","valueIsNumericString","onValueChange"]),j=Am(e),C=j.decimalSeparator,R=j.allowedDecimalSeparators,E=function(M){return uT(M,e)},T=function(M,L){return dz(M,L,e)},_=Mc(g)?m:g,k=y??uz(_,p,t);Mc(g)?Mc(m)||(k=k||typeof m=="number"):k=k||typeof g=="number";var I=function(M){return QA(M)?M:(typeof M=="number"&&(M=KA(M)),k&&typeof d=="number"?lT(M,d,!!f):M)},A=JA(I(g),I(m),!!k,E,T,b),P=A[0],z=P.numAsString,B=P.formattedValue,Y=A[1],J=function(M){var L=M.target,U=M.key,V=L.selectionStart,K=L.selectionEnd,O=L.value;if(O===void 0&&(O=""),(U==="Backspace"||U==="Delete")&&K<p.length){M.preventDefault();return}if(V!==K){o(M);return}U==="Backspace"&&O[0]==="-"&&V===p.length+1&&n&&Zs(L,1),d&&f&&(U==="Backspace"&&O[V-1]===C?(Zs(L,V-1),M.preventDefault()):U==="Delete"&&O[V]===C&&M.preventDefault()),R?.includes(U)&&O[V]===C&&Zs(L,V+1);var F=c===!0?",":c;U==="Backspace"&&O[V-1]===F&&Zs(L,V-1),U==="Delete"&&O[V]===F&&Zs(L,V+1),o(M)},Z=function(M){var L=z;if(L.match(/\d/g)||(L=""),r||(L=X6(L)),f&&d&&(L=lT(L,d,f)),L!==z){var U=uT(L,e);Y({formattedValue:U,value:L,floatValue:parseFloat(L)},{event:M,source:_d.event})}s(M)},$=function(M){return M===C?!0:Ad(M)},Q=function(M){var L=M.currentValue,U=M.lastValue,V=M.formattedValue,K=M.currentValueIndex,O=M.formattedValueIndex,F=L[K],ae=V[O],ue=XA(U,L),be=ue.to,we=function(Ce){return T(Ce).indexOf(".")+p.length};return g===0&&f&&d&&L[be.start]===C&&we(L)<K&&we(V)>O?!1:K>=be.start&&K<be.end&&R&&R.includes(F)&&ae===C?!0:F===ae};return Object.assign(Object.assign({},S),{value:B,valueIsNumericString:!1,isValidInputCharacter:$,isCharacterSame:Q,onValueChange:Y,format:E,removeFormatting:T,getCaretBoundary:function(M){return fz(M,e)},onKeyDown:J,onBlur:Z})}function mz(e){var t=pz(e);return Mn.createElement(sz,Object.assign({},t))}function dT({direction:e,style:t,...n}){return a.jsx("svg",{style:{width:"var(--ni-chevron-size)",height:"var(--ni-chevron-size)",transform:e==="up"?"rotate(180deg)":void 0,...t},viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n,children:a.jsx("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:"currentColor",fillRule:"evenodd",clipRule:"evenodd"})})}var Lx={root:"m_e2f5cd4e",controls:"m_95e17d22",control:"m_80b4b171"};const gz=/^(0\.0*|-0(\.0*)?)$/,vz=/^-?0\d+(\.\d+)?\.?$/,yz=/\.\d*0$/;function Ix(e){return typeof e=="string"&&e!==""&&!Number.isNaN(Number(e))}function Fy(e){return typeof e=="number"?e<Number.MAX_SAFE_INTEGER:e===""||Ix(e)&&Number(e)<Number.MAX_SAFE_INTEGER}function xz(e){return e.toString().replace(".","").length}function bz(e,t){return(typeof e=="number"?e<Number.MAX_SAFE_INTEGER:!Number.isNaN(Number(e)))&&!Number.isNaN(e)&&xz(t)<14&&t!==""}function fT(e,t,n){if(e===void 0)return!0;const r=t===void 0||e>=t,o=n===void 0||e<=n;return r&&o}const Sz={step:1,clampBehavior:"blur",allowDecimal:!0,allowNegative:!0,withKeyboardEvents:!0,allowLeadingZeros:!0,trimLeadingZeroesOnBlur:!0,startValue:0,allowedDecimalSeparators:[".",","]},wz=(e,{size:t})=>({controls:{"--ni-chevron-size":it(t,"ni-chevron-size")}});function jz(e,t,n){const r=e.toString().replace(/^0+(?=\d)/,""),o=parseFloat(r);return Number.isNaN(o)?r:o>Number.MAX_SAFE_INTEGER?t!==void 0?t:r:vd(o,n,t)}const Hc=ge((e,t)=>{const n=ie("NumberInput",Sz,e),{className:r,classNames:o,styles:s,unstyled:c,vars:d,onChange:f,onValueChange:p,value:m,defaultValue:g,max:y,min:b,step:S,hideControls:j,rightSection:C,isAllowed:R,clampBehavior:E,onBlur:T,allowDecimal:_,decimalScale:k,onKeyDown:I,onKeyDownCapture:A,handlersRef:P,startValue:z,disabled:B,rightSectionPointerEvents:Y,allowNegative:J,readOnly:Z,size:$,rightSectionWidth:Q,stepHoldInterval:M,stepHoldDelay:L,allowLeadingZeros:U,withKeyboardEvents:V,trimLeadingZeroesOnBlur:K,allowedDecimalSeparators:O,attributes:F,...ae}=n,ue=Le({name:"NumberInput",classes:Lx,props:n,classNames:o,styles:s,unstyled:c,attributes:F,vars:d,varsResolver:wz}),{resolvedClassNames:be,resolvedStyles:we}=Cl({classNames:o,styles:s,props:n}),[Ce,nt]=rr({value:m,defaultValue:g,finalValue:"",onChange:f}),De=L!==void 0&&M!==void 0,ft=v.useRef(null),ot=v.useRef(null),ht=v.useRef(0),st=(je,Ae)=>{Ae.source==="event"&&nt(bz(je.floatValue,je.value)&&!gz.test(je.value)&&!(U&&vz.test(je.value))&&!yz.test(je.value)?je.floatValue:je.value),p?.(je,Ae)},yt=je=>{const Ae=String(je).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);return Ae?Math.max(0,(Ae[1]?Ae[1].length:0)-(Ae[2]?+Ae[2]:0)):0},mt=je=>{ft.current&&typeof je<"u"&&ft.current.setSelectionRange(je,je)},It=v.useRef(xp);It.current=()=>{if(!Fy(Ce))return;let je;const Ae=yt(Ce),_t=yt(S),Zn=Math.max(Ae,_t),vn=10**Zn;if(!Ix(Ce)&&(typeof Ce!="number"||Number.isNaN(Ce)))je=vd(z,b,y);else if(y!==void 0){const yn=(Math.round(Number(Ce)*vn)+Math.round(S*vn))/vn;je=yn<=y?yn:y}else je=(Math.round(Number(Ce)*vn)+Math.round(S*vn))/vn;const Pn=je.toFixed(Zn);nt(parseFloat(Pn)),p?.({floatValue:parseFloat(Pn),formattedValue:Pn,value:Pn},{source:"increment"}),setTimeout(()=>mt(ft.current?.value.length),0)};const Te=v.useRef(xp);Te.current=()=>{if(!Fy(Ce))return;let je;const Ae=b!==void 0?b:J?Number.MIN_SAFE_INTEGER:0,_t=yt(Ce),Zn=yt(S),vn=Math.max(_t,Zn),Pn=10**vn;if(!Ix(Ce)&&typeof Ce!="number"||Number.isNaN(Ce))je=vd(z,Ae,y);else{const En=(Math.round(Number(Ce)*Pn)-Math.round(S*Pn))/Pn;je=Ae!==void 0&&En<Ae?Ae:En}const yn=je.toFixed(vn);nt(parseFloat(yn)),p?.({floatValue:parseFloat(yn),formattedValue:yn,value:yn},{source:"decrement"}),setTimeout(()=>mt(ft.current?.value.length),0)};const Re=je=>{I?.(je),!(Z||!V)&&(je.key==="ArrowUp"&&(je.preventDefault(),It.current?.()),je.key==="ArrowDown"&&(je.preventDefault(),Te.current?.()))},Ie=je=>{if(A?.(je),je.key==="Backspace"){const Ae=ft.current;Ae&&Ae.selectionStart===0&&Ae.selectionStart===Ae.selectionEnd&&(je.preventDefault(),window.setTimeout(()=>mt(0),0))}},Oe=je=>{let Ae=Ce;E==="blur"&&typeof Ae=="number"&&(Ae=vd(Ae,b,y)),K&&typeof Ae=="string"&&yt(Ae)<15&&(Ae=jz(Ae,y,b)),Ce!==Ae&&nt(Ae),T?.(je)};wd(P,{increment:It.current,decrement:Te.current});const ct=je=>{je?It.current?.():Te.current?.(),ht.current+=1},tt=je=>{if(ct(je),De){const Ae=typeof M=="number"?M:M(ht.current);ot.current=window.setTimeout(()=>tt(je),Ae)}},lt=(je,Ae)=>{je.preventDefault(),ft.current?.focus(),ct(Ae),De&&(ot.current=window.setTimeout(()=>tt(Ae),L))},pe=()=>{ot.current&&window.clearTimeout(ot.current),ot.current=null,ht.current=0},qe=a.jsxs("div",{...ue("controls"),children:[a.jsx(An,{...ue("control"),tabIndex:-1,"aria-hidden":!0,disabled:B||typeof Ce=="number"&&y!==void 0&&Ce>=y,mod:{direction:"up"},onMouseDown:je=>je.preventDefault(),onPointerDown:je=>{lt(je,!0)},onPointerUp:pe,onPointerLeave:pe,children:a.jsx(dT,{direction:"up"})}),a.jsx(An,{...ue("control"),tabIndex:-1,"aria-hidden":!0,disabled:B||typeof Ce=="number"&&b!==void 0&&Ce<=b,mod:{direction:"down"},onMouseDown:je=>je.preventDefault(),onPointerDown:je=>{lt(je,!1)},onPointerUp:pe,onPointerLeave:pe,children:a.jsx(dT,{direction:"down"})})]});return a.jsx($r,{component:mz,allowNegative:J,className:Ut(Lx.root,r),size:$,inputMode:"decimal",...ae,readOnly:Z,disabled:B,value:Ce,getInputRef:Bn(t,ft),onValueChange:st,rightSection:j||Z||!Fy(Ce)?C:C||qe,classNames:be,styles:we,unstyled:c,__staticSelector:"NumberInput",decimalScale:_?k:0,onKeyDown:Re,onKeyDownCapture:Ie,rightSectionPointerEvents:Y??(B?"none":void 0),rightSectionWidth:Q??`var(--ni-right-section-width-${$||"sm"})`,allowLeadingZeros:U,allowedDecimalSeparators:O,onBlur:Oe,attributes:F,isAllowed:je=>E==="strict"?R?R(je)&&fT(je.floatValue,b,y):fT(je.floatValue,b,y):R?R(je):!0})});Hc.classes={...$r.classes,...Lx};Hc.displayName="@mantine/core/NumberInput";const[Cz,Dm]=jr("Pagination.Root component was not found in tree");var ef={root:"m_4addd315",control:"m_326d024a",dots:"m_4ad7767d"};const Ez={withPadding:!0},tf=ge((e,t)=>{const n=ie("PaginationControl",Ez,e),{classNames:r,className:o,style:s,styles:c,vars:d,active:f,disabled:p,withPadding:m,mod:g,...y}=n,b=Dm(),S=p||b.disabled;return a.jsx(An,{ref:t,disabled:S,mod:[{active:f,disabled:S,"with-padding":m},g],...b.getStyles("control",{className:o,style:s,classNames:r,styles:c,active:!S}),...y})});tf.classes=ef;tf.displayName="@mantine/core/PaginationControl";function nf({style:e,children:t,path:n,...r}){return a.jsx("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",style:{width:"calc(var(--pagination-control-size) / 1.8)",height:"calc(var(--pagination-control-size) / 1.8)",...e},...r,children:a.jsx("path",{d:n,fill:"currentColor"})})}const Tz=e=>a.jsx(nf,{...e,path:"M8.781 8l-3.3-3.3.943-.943L10.667 8l-4.243 4.243-.943-.943 3.3-3.3z"}),Rz=e=>a.jsx(nf,{...e,path:"M7.219 8l3.3 3.3-.943.943L5.333 8l4.243-4.243.943.943-3.3 3.3z"}),_z=e=>a.jsx(nf,{...e,path:"M6.85355 3.85355C7.04882 3.65829 7.04882 3.34171 6.85355 3.14645C6.65829 2.95118 6.34171 2.95118 6.14645 3.14645L2.14645 7.14645C1.95118 7.34171 1.95118 7.65829 2.14645 7.85355L6.14645 11.8536C6.34171 12.0488 6.65829 12.0488 6.85355 11.8536C7.04882 11.6583 7.04882 11.3417 6.85355 11.1464L3.20711 7.5L6.85355 3.85355ZM12.8536 3.85355C13.0488 3.65829 13.0488 3.34171 12.8536 3.14645C12.6583 2.95118 12.3417 2.95118 12.1464 3.14645L8.14645 7.14645C7.95118 7.34171 7.95118 7.65829 8.14645 7.85355L12.1464 11.8536C12.3417 12.0488 12.6583 12.0488 12.8536 11.8536C13.0488 11.6583 13.0488 11.3417 12.8536 11.1464L9.20711 7.5L12.8536 3.85355Z"}),Az=e=>a.jsx(nf,{...e,path:"M2.14645 11.1464C1.95118 11.3417 1.95118 11.6583 2.14645 11.8536C2.34171 12.0488 2.65829 12.0488 2.85355 11.8536L6.85355 7.85355C7.04882 7.65829 7.04882 7.34171 6.85355 7.14645L2.85355 3.14645C2.65829 2.95118 2.34171 2.95118 2.14645 3.14645C1.95118 3.34171 1.95118 3.65829 2.14645 3.85355L5.79289 7.5L2.14645 11.1464ZM8.14645 11.1464C7.95118 11.3417 7.95118 11.6583 8.14645 11.8536C8.34171 12.0488 8.65829 12.0488 8.85355 11.8536L12.8536 7.85355C13.0488 7.65829 13.0488 7.34171 12.8536 7.14645L8.85355 3.14645C8.65829 2.95118 8.34171 2.95118 8.14645 3.14645C7.95118 3.34171 7.95118 3.65829 8.14645 3.85355L11.7929 7.5L8.14645 11.1464Z"}),Dz=e=>a.jsx(nf,{...e,path:"M2 8c0-.733.6-1.333 1.333-1.333.734 0 1.334.6 1.334 1.333s-.6 1.333-1.334 1.333C2.6 9.333 2 8.733 2 8zm9.333 0c0-.733.6-1.333 1.334-1.333C13.4 6.667 14 7.267 14 8s-.6 1.333-1.333 1.333c-.734 0-1.334-.6-1.334-1.333zM6.667 8c0-.733.6-1.333 1.333-1.333s1.333.6 1.333 1.333S8.733 9.333 8 9.333 6.667 8.733 6.667 8z"}),kz={icon:Dz},km=ge((e,t)=>{const n=ie("PaginationDots",kz,e),{classNames:r,className:o,style:s,styles:c,vars:d,icon:f,...p}=n,m=Dm();return a.jsx(ce,{ref:t,...m.getStyles("dots",{className:o,style:s,styles:c,classNames:r}),...p,children:a.jsx(f,{style:{width:"calc(var(--pagination-control-size) / 1.8)",height:"calc(var(--pagination-control-size) / 1.8)"}})})});km.classes=ef;km.displayName="@mantine/core/PaginationDots";function Pm({icon:e,name:t,action:n,type:r}){const o={icon:e},s=v.forwardRef((c,d)=>{const{icon:f,...p}=ie(t,o,c),m=Dm(),g=r==="next"?m.active===m.total:m.active===1;return a.jsx(tf,{disabled:m.disabled||g,ref:d,onClick:m[n],withPadding:!1,...p,children:a.jsx(f,{className:"mantine-rotate-rtl",style:{width:"calc(var(--pagination-control-size) / 1.8)",height:"calc(var(--pagination-control-size) / 1.8)"}})})});return s.displayName=`@mantine/core/${t}`,s}const ZA=Pm({icon:Tz,name:"PaginationNext",action:"onNext",type:"next"}),eD=Pm({icon:Rz,name:"PaginationPrevious",action:"onPrevious",type:"previous"}),tD=Pm({icon:_z,name:"PaginationFirst",action:"onFirst",type:"previous"}),nD=Pm({icon:Az,name:"PaginationLast",action:"onLast",type:"next"});function I0({dotsIcon:e}){const t=Dm(),n=t.range.map((r,o)=>r==="dots"?a.jsx(km,{icon:e},o):a.jsx(tf,{active:r===t.active,"aria-current":r===t.active?"page":void 0,onClick:()=>t.onChange(r),disabled:t.disabled,...t.getItemProps?.(r),children:t.getItemProps?.(r)?.children??r},o));return a.jsx(a.Fragment,{children:n})}I0.displayName="@mantine/core/PaginationItems";const Pz={siblings:1,boundaries:1},Nz=(e,{size:t,radius:n,color:r,autoContrast:o})=>({root:{"--pagination-control-radius":n===void 0?void 0:Ft(n),"--pagination-control-size":it(t,"pagination-control-size"),"--pagination-control-fz":Qn(t),"--pagination-active-bg":r?Wt(r,e):void 0,"--pagination-active-color":El(o,e)?wa({color:r,theme:e,autoContrast:o}):void 0}}),Nm=ge((e,t)=>{const n=ie("PaginationRoot",Pz,e),{classNames:r,className:o,style:s,styles:c,unstyled:d,vars:f,total:p,value:m,defaultValue:g,onChange:y,disabled:b,siblings:S,boundaries:j,color:C,radius:R,onNextPage:E,onPreviousPage:T,onFirstPage:_,onLastPage:k,getItemProps:I,autoContrast:A,attributes:P,...z}=n,B=Le({name:"Pagination",classes:ef,props:n,className:o,style:s,classNames:r,styles:c,unstyled:d,attributes:P,vars:f,varsResolver:Nz}),{range:Y,setPage:J,next:Z,previous:$,active:Q,first:M,last:L}=l4({page:m,initialPage:g,onChange:y,total:p,siblings:S,boundaries:j}),U=ar(E,Z),V=ar(T,$),K=ar(_,M),O=ar(k,L);return a.jsx(Cz,{value:{total:p,range:Y,active:Q,disabled:b,getItemProps:I,onChange:J,onNext:U,onPrevious:V,onFirst:K,onLast:O,getStyles:B},children:a.jsx(ce,{ref:t,...B("root"),...z})})});Nm.classes=ef;Nm.displayName="@mantine/core/PaginationRoot";const Oz={withControls:!0,withPages:!0,siblings:1,boundaries:1,gap:8},zi=ge((e,t)=>{const n=ie("Pagination",Oz,e),{withEdges:r,withControls:o,getControlProps:s,nextIcon:c,previousIcon:d,lastIcon:f,firstIcon:p,dotsIcon:m,total:g,gap:y,hideWithOnePage:b,withPages:S,...j}=n;return g<=0||b&&g===1?null:a.jsx(Nm,{ref:t,total:g,...j,children:a.jsxs(ye,{gap:y,children:[r&&a.jsx(tD,{icon:p,...s?.("first")}),o&&a.jsx(eD,{icon:d,...s?.("previous")}),S&&a.jsx(I0,{dotsIcon:m}),o&&a.jsx(ZA,{icon:c,...s?.("next")}),r&&a.jsx(nD,{icon:f,...s?.("last")})]})})});zi.classes=ef;zi.displayName="@mantine/core/Pagination";zi.Root=Nm;zi.Control=tf;zi.Dots=km;zi.First=tD;zi.Last=nD;zi.Next=ZA;zi.Previous=eD;zi.Items=I0;const Mz=({reveal:e})=>a.jsx("svg",{viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{width:"var(--psi-icon-size)",height:"var(--psi-icon-size)"},children:a.jsx("path",{d:e?"M13.3536 2.35355C13.5488 2.15829 13.5488 1.84171 13.3536 1.64645C13.1583 1.45118 12.8417 1.45118 12.6464 1.64645L10.6828 3.61012C9.70652 3.21671 8.63759 3 7.5 3C4.30786 3 1.65639 4.70638 0.0760002 7.23501C-0.0253338 7.39715 -0.0253334 7.60288 0.0760014 7.76501C0.902945 9.08812 2.02314 10.1861 3.36061 10.9323L1.64645 12.6464C1.45118 12.8417 1.45118 13.1583 1.64645 13.3536C1.84171 13.5488 2.15829 13.5488 2.35355 13.3536L4.31723 11.3899C5.29348 11.7833 6.36241 12 7.5 12C10.6921 12 13.3436 10.2936 14.924 7.76501C15.0253 7.60288 15.0253 7.39715 14.924 7.23501C14.0971 5.9119 12.9769 4.81391 11.6394 4.06771L13.3536 2.35355ZM9.90428 4.38861C9.15332 4.1361 8.34759 4 7.5 4C4.80285 4 2.52952 5.37816 1.09622 7.50001C1.87284 8.6497 2.89609 9.58106 4.09974 10.1931L9.90428 4.38861ZM5.09572 10.6114L10.9003 4.80685C12.1039 5.41894 13.1272 6.35031 13.9038 7.50001C12.4705 9.62183 10.1971 11 7.5 11C6.65241 11 5.84668 10.8639 5.09572 10.6114Z":"M7.5 11C4.80285 11 2.52952 9.62184 1.09622 7.50001C2.52952 5.37816 4.80285 4 7.5 4C10.1971 4 12.4705 5.37816 13.9038 7.50001C12.4705 9.62183 10.1971 11 7.5 11ZM7.5 3C4.30786 3 1.65639 4.70638 0.0760002 7.23501C-0.0253338 7.39715 -0.0253334 7.60288 0.0760014 7.76501C1.65639 10.2936 4.30786 12 7.5 12C10.6921 12 13.3436 10.2936 14.924 7.76501C15.0253 7.60288 15.0253 7.39715 14.924 7.23501C13.3436 4.70638 10.6921 3 7.5 3ZM7.5 9.5C8.60457 9.5 9.5 8.60457 9.5 7.5C9.5 6.39543 8.60457 5.5 7.5 5.5C6.39543 5.5 5.5 6.39543 5.5 7.5C5.5 8.60457 6.39543 9.5 7.5 9.5Z",fill:"currentColor",fillRule:"evenodd",clipRule:"evenodd"})});var zx={root:"m_f61ca620",input:"m_ccf8da4c",innerInput:"m_f2d85dd2",visibilityToggle:"m_b1072d44"};const Lz={visibilityToggleIcon:Mz},Iz=(e,{size:t})=>({root:{"--psi-icon-size":it(t,"psi-icon-size"),"--psi-button-size":it(t,"psi-button-size")}}),Ki=ge((e,t)=>{const n=ie("PasswordInput",Lz,e),{classNames:r,className:o,style:s,styles:c,unstyled:d,vars:f,required:p,error:m,leftSection:g,disabled:y,id:b,variant:S,inputContainer:j,description:C,label:R,size:E,errorProps:T,descriptionProps:_,labelProps:k,withAsterisk:I,inputWrapperOrder:A,wrapperProps:P,radius:z,rightSection:B,rightSectionWidth:Y,rightSectionPointerEvents:J,leftSectionWidth:Z,visible:$,defaultVisible:Q,onVisibilityChange:M,visibilityToggleIcon:L,visibilityToggleButtonProps:U,rightSectionProps:V,leftSectionProps:K,leftSectionPointerEvents:O,withErrorStyles:F,mod:ae,attributes:ue,...be}=n,we=mr(b),[Ce,nt]=rr({value:$,defaultValue:Q,finalValue:!1,onChange:M}),De=()=>nt(!Ce),ft=Le({name:"PasswordInput",classes:zx,props:n,className:o,style:s,classNames:r,styles:c,unstyled:d,attributes:ue,vars:f,varsResolver:Iz}),{resolvedClassNames:ot,resolvedStyles:ht}=Cl({classNames:r,styles:c,props:n}),{styleProps:st,rest:yt}=ja(be),mt=T?.id||`${we}-error`,It=_?.id||`${we}-description`,Ie=`${!!m&&typeof m!="boolean"?mt:""} ${!!C?It:""}`,Oe=Ie.trim().length>0?Ie.trim():void 0,ct=a.jsx(Dn,{...ft("visibilityToggle"),disabled:y,radius:z,"aria-hidden":!U,"aria-pressed":Ce,tabIndex:-1,...U,variant:U?.variant??"subtle",color:"gray",unstyled:d,onTouchEnd:tt=>{tt.preventDefault(),U?.onTouchEnd?.(tt),De()},onMouseDown:tt=>{tt.preventDefault(),U?.onMouseDown?.(tt),De()},onKeyDown:tt=>{U?.onKeyDown?.(tt),tt.key===" "&&(tt.preventDefault(),De())},children:a.jsx(L,{reveal:Ce})});return a.jsx(hn.Wrapper,{required:p,id:we,label:R,error:m,description:C,size:E,classNames:ot,styles:ht,__staticSelector:"PasswordInput",unstyled:d,withAsterisk:I,inputWrapperOrder:A,inputContainer:j,variant:S,labelProps:{...k,htmlFor:we},descriptionProps:{..._,id:It},errorProps:{...T,id:mt},mod:ae,attributes:ue,...ft("root"),...st,...P,children:a.jsx(hn,{component:"div",error:m,leftSection:g,size:E,classNames:{...ot,input:Ut(zx.input,ot.input)},styles:ht,radius:z,disabled:y,__staticSelector:"PasswordInput",rightSectionWidth:Y,rightSection:B??ct,variant:S,unstyled:d,leftSectionWidth:Z,rightSectionPointerEvents:J||"all",rightSectionProps:V,leftSectionProps:K,leftSectionPointerEvents:O,withAria:!1,withErrorStyles:F,attributes:ue,children:a.jsx("input",{required:p,"data-invalid":!!m||void 0,"data-with-left-section":!!g||void 0,...ft("innerInput"),disabled:y,id:we,ref:t,...yt,"aria-describedby":Oe,autoComplete:yt.autoComplete||"off",type:Ce?"text":"password"})})})});Ki.classes={...$r.classes,...zx};Ki.displayName="@mantine/core/PasswordInput";const[zz,rD]=Io(),[$z,Uz]=Io();var iD={card:"m_9dc8ae12"};const Bz={withBorder:!0},Vz=(e,{radius:t})=>({card:{"--card-radius":Ft(t)}}),z0=ge((e,t)=>{const n=ie("RadioCard",Bz,e),{classNames:r,className:o,style:s,styles:c,unstyled:d,vars:f,checked:p,mod:m,withBorder:g,value:y,onClick:b,name:S,onKeyDown:j,attributes:C,...R}=n,E=Le({name:"RadioCard",classes:iD,props:n,className:o,style:s,classNames:r,styles:c,unstyled:d,attributes:C,vars:f,varsResolver:Vz,rootSelector:"card"}),{dir:T}=ws(),_=rD(),k=typeof p=="boolean"?p:_?.value===y||!1,I=S||_?.name,A=P=>{if(j?.(P),["ArrowDown","ArrowUp","ArrowLeft","ArrowRight"].includes(P.nativeEvent.code)){P.preventDefault();const z=Array.from(document.querySelectorAll(`[role="radio"][name="${I||"__mantine"}"]`)),B=z.findIndex(Z=>Z===P.target),Y=B+1>=z.length?0:B+1,J=B-1<0?z.length-1:B-1;P.nativeEvent.code==="ArrowDown"&&(z[Y].focus(),z[Y].click()),P.nativeEvent.code==="ArrowUp"&&(z[J].focus(),z[J].click()),P.nativeEvent.code==="ArrowLeft"&&(z[T==="ltr"?J:Y].focus(),z[T==="ltr"?J:Y].click()),P.nativeEvent.code==="ArrowRight"&&(z[T==="ltr"?Y:J].focus(),z[T==="ltr"?Y:J].click())}};return a.jsx($z,{value:{checked:k},children:a.jsx(An,{ref:t,mod:[{"with-border":g,checked:k},m],...E("card"),...R,role:"radio","aria-checked":k,name:I,onClick:P=>{b?.(P),_?.onChange(y||"")},onKeyDown:A})})});z0.displayName="@mantine/core/RadioCard";z0.classes=iD;const $0=ge((e,t)=>{const{value:n,defaultValue:r,onChange:o,size:s,wrapperProps:c,children:d,name:f,readOnly:p,disabled:m,...g}=ie("RadioGroup",null,e),y=mr(f),[b,S]=rr({value:n,defaultValue:r,finalValue:"",onChange:o}),j=C=>!p&&S(typeof C=="string"?C:C.currentTarget.value);return a.jsx(zz,{value:{value:b,onChange:j,size:s,name:y,disabled:m},children:a.jsx(hn.Wrapper,{size:s,ref:t,...c,...g,labelElement:"div",__staticSelector:"RadioGroup",children:a.jsx(c0,{role:"radiogroup",children:d})})})});$0.classes=hn.Wrapper.classes;$0.displayName="@mantine/core/RadioGroup";function oD({size:e,style:t,...n}){return a.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 5 5",style:{width:le(e),height:le(e),...t},"aria-hidden":!0,...n,children:a.jsx("circle",{cx:"2.5",cy:"2.5",r:"2.5",fill:"currentColor"})})}var aD={indicator:"m_717d7ff6",icon:"m_3e4da632","indicator--outline":"m_2980836c"};const Fz={icon:oD},Hz=(e,{radius:t,color:n,size:r,iconColor:o,variant:s,autoContrast:c})=>{const d=Xr({color:n||e.primaryColor,theme:e}),f=d.isThemeColor&&d.shade===void 0?`var(--mantine-color-${d.color}-outline)`:d.color;return{indicator:{"--radio-size":it(r,"radio-size"),"--radio-radius":t===void 0?void 0:Ft(t),"--radio-color":s==="outline"?f:Wt(n,e),"--radio-icon-size":it(r,"radio-icon-size"),"--radio-icon-color":o?Wt(o,e):El(c,e)?wa({color:n,theme:e,autoContrast:c}):void 0}}},U0=ge((e,t)=>{const n=ie("RadioIndicator",Fz,e),{classNames:r,className:o,style:s,styles:c,unstyled:d,vars:f,icon:p,radius:m,color:g,iconColor:y,autoContrast:b,checked:S,mod:j,variant:C,disabled:R,attributes:E,...T}=n,_=Le({name:"RadioIndicator",classes:aD,props:n,className:o,style:s,classNames:r,styles:c,unstyled:d,attributes:E,vars:f,varsResolver:Hz,rootSelector:"indicator"}),k=Uz(),I=typeof S=="boolean"?S:k?.checked||!1;return a.jsx(ce,{ref:t,..._("indicator",{variant:C}),variant:C,mod:[{checked:I,disabled:R},j],...T,children:a.jsx(p,{..._("icon")})})});U0.displayName="@mantine/core/RadioIndicator";U0.classes=aD;var sD={root:"m_f3f1af94",inner:"m_89c4f5e4",icon:"m_f3ed6b2b",radio:"m_8a3dbb89","radio--outline":"m_1bfe9d39"};const qz={labelPosition:"right"},Gz=(e,{size:t,radius:n,color:r,iconColor:o,variant:s,autoContrast:c})=>{const d=Xr({color:r||e.primaryColor,theme:e}),f=d.isThemeColor&&d.shade===void 0?`var(--mantine-color-${d.color}-outline)`:d.color;return{root:{"--radio-size":it(t,"radio-size"),"--radio-radius":n===void 0?void 0:Ft(n),"--radio-color":s==="outline"?f:Wt(r,e),"--radio-icon-color":o?Wt(o,e):El(c,e)?wa({color:r,theme:e,autoContrast:c}):void 0,"--radio-icon-size":it(t,"radio-icon-size")}}},vr=ge((e,t)=>{const n=ie("Radio",qz,e),{classNames:r,className:o,style:s,styles:c,unstyled:d,vars:f,id:p,size:m,label:g,labelPosition:y,description:b,error:S,radius:j,color:C,variant:R,disabled:E,wrapperProps:T,icon:_=oD,rootRef:k,iconColor:I,onChange:A,mod:P,attributes:z,checked:B,...Y}=n,J=Le({name:"Radio",classes:sD,props:n,className:o,style:s,classNames:r,styles:c,unstyled:d,attributes:z,vars:f,varsResolver:Gz}),Z=rD(),$=Z?.size??m,Q=n.size?m:$,{styleProps:M,rest:L}=ja(Y),U=mr(p),V=Z?Z.value===L.value:void 0,K={checked:V??B,name:Z?.name??L.name,onChange:O=>{Z?.onChange(O),A?.(O)},disabled:Z?.disabled??E};return a.jsx(mm,{...J("root"),__staticSelector:"Radio",__stylesApiProps:n,id:U,size:Q,labelPosition:y,label:g,description:b,error:S,disabled:K.disabled,classNames:r,styles:c,unstyled:d,"data-checked":(V??B)||void 0,variant:R,ref:k,mod:P,...M,...T,children:a.jsxs(ce,{...J("inner"),mod:{"label-position":y},children:[a.jsx(ce,{...J("radio",{focusable:!0,variant:R}),...L,...K,component:"input",mod:{error:!!S},ref:t,id:U,type:"radio"}),a.jsx(_,{...J("icon"),"aria-hidden":!0})]})})});vr.classes=sD;vr.displayName="@mantine/core/Radio";vr.Group=$0;vr.Card=z0;vr.Indicator=U0;const Qz={duration:100,transition:"fade"};function hT(e,t){return{...Qz,...t,...e}}function Wz({offset:e,position:t,defaultOpened:n}){const[r,o]=v.useState(n),s=v.useRef(null),{x:c,y:d,elements:f,refs:p,update:m,placement:g}=zb({placement:t,middleware:[Ob({crossAxis:!0,padding:5,rootBoundary:"document"})]}),y=g.includes("right")?e:t.includes("left")?e*-1:0,b=g.includes("bottom")?e:t.includes("top")?e*-1:0,S=v.useCallback(({clientX:j,clientY:C})=>{p.setPositionReference({getBoundingClientRect(){return{width:0,height:0,x:j,y:C,left:j+y,top:C+b,right:j,bottom:C}}})},[f.reference]);return v.useEffect(()=>{if(p.floating.current){const j=s.current;j.addEventListener("mousemove",S);const C=ma(p.floating.current);return C.forEach(R=>{R.addEventListener("scroll",m)}),()=>{j.removeEventListener("mousemove",S),C.forEach(R=>{R.removeEventListener("scroll",m)})}}},[f.reference,p.floating.current,m,S,r]),{handleMouseMove:S,x:c,y:d,opened:r,setOpened:o,boundaryRef:s,floating:p.setFloating}}var Om={tooltip:"m_1b3c8819",arrow:"m_f898399f"};const Yz={refProp:"ref",withinPortal:!0,offset:10,position:"right",zIndex:zr("popover")},Kz=(e,{radius:t,color:n})=>({tooltip:{"--tooltip-radius":t===void 0?void 0:Ft(t),"--tooltip-bg":n?Wt(n,e):void 0,"--tooltip-color":n?"var(--mantine-color-white)":void 0}}),B0=ge((e,t)=>{const n=ie("TooltipFloating",Yz,e),{children:r,refProp:o,withinPortal:s,style:c,className:d,classNames:f,styles:p,unstyled:m,radius:g,color:y,label:b,offset:S,position:j,multiline:C,zIndex:R,disabled:E,defaultOpened:T,variant:_,vars:k,portalProps:I,attributes:A,...P}=n,z=gn(),B=Le({name:"TooltipFloating",props:n,classes:Om,className:d,style:c,classNames:f,styles:p,unstyled:m,attributes:A,rootSelector:"tooltip",vars:k,varsResolver:Kz}),{handleMouseMove:Y,x:J,y:Z,opened:$,boundaryRef:Q,floating:M,setOpened:L}=Wz({offset:S,position:j,defaultOpened:T});if(!Lo(r))throw new Error("[@mantine/core] Tooltip.Floating component children should be an element or a component that accepts ref, fragments, strings, numbers and other primitive values are not supported");const U=Bn(Q,em(r),t),V=r.props,K=F=>{V.onMouseEnter?.(F),Y(F),L(!0)},O=F=>{V.onMouseLeave?.(F),L(!1)};return a.jsxs(a.Fragment,{children:[a.jsx(va,{...I,withinPortal:s,children:a.jsx(ce,{...P,...B("tooltip",{style:{...J2(c,z),zIndex:R,display:!E&&$?"block":"none",top:(Z&&Math.round(Z))??"",left:(J&&Math.round(J))??""}}),variant:_,ref:M,mod:{multiline:C},children:b})}),v.cloneElement(r,{...V,[o]:U,onMouseEnter:K,onMouseLeave:O})]})});B0.classes=Om;B0.displayName="@mantine/core/TooltipFloating";const lD=v.createContext(!1),Xz=lD.Provider,Jz=()=>v.useContext(lD),Zz={openDelay:0,closeDelay:0};function V0(e){const{openDelay:t,closeDelay:n,children:r}=ie("TooltipGroup",Zz,e);return a.jsx(Xz,{value:!0,children:a.jsx(hL,{delay:{open:t,close:n},children:r})})}V0.displayName="@mantine/core/TooltipGroup";V0.extend=e=>e;function e$(e){if(e===void 0)return{shift:!0,flip:!0};const t={...e};return e.shift===void 0&&(t.shift=!0),e.flip===void 0&&(t.flip=!0),t}function t$(e){const t=e$(e.middlewares),n=[m_(e.offset)];return t.shift&&n.push(Ob(typeof t.shift=="boolean"?{padding:8}:{padding:8,...t.shift})),t.flip&&n.push(typeof t.flip=="boolean"?Cp():Cp(t.flip)),n.push(g_({element:e.arrowRef,padding:e.arrowOffset})),t.inline?n.push(typeof t.inline=="boolean"?yd():yd(t.inline)):e.inline&&n.push(yd()),n}function n$(e){const[t,n]=v.useState(e.defaultOpened),o=typeof e.opened=="boolean"?e.opened:t,s=Jz(),c=mr(),d=v.useCallback(k=>{n(k),k&&R(c)},[c]),{x:f,y:p,context:m,refs:g,placement:y,middlewareData:{arrow:{x:b,y:S}={}}}=zb({strategy:e.strategy,placement:e.position,open:o,onOpenChange:d,middleware:t$(e),whileElementsMounted:kx}),{delay:j,currentId:C,setCurrentId:R}=pL(m,{id:c}),{getReferenceProps:E,getFloatingProps:T}=bL([dL(m,{enabled:e.events?.hover,delay:s?j:{open:e.openDelay,close:e.closeDelay},mouseOnly:!e.events?.touch}),xL(m,{enabled:e.events?.focus,visibleOnly:!0}),wL(m,{role:"tooltip"}),vL(m,{enabled:typeof e.opened>"u"})]);gs(()=>{e.onPositionChange?.(y)},[y]);const _=o&&C&&C!==c;return{x:f,y:p,arrowX:b,arrowY:S,reference:g.setReference,floating:g.setFloating,getFloatingProps:T,getReferenceProps:E,isGroupPhase:_,opened:o,placement:y}}const pT={position:"top",refProp:"ref",withinPortal:!0,arrowSize:4,arrowOffset:5,arrowRadius:0,arrowPosition:"side",offset:5,transitionProps:{duration:100,transition:"fade"},events:{hover:!0,focus:!1,touch:!1},zIndex:zr("popover"),positionDependencies:[],middlewares:{flip:!0,shift:!0,inline:!1}},r$=(e,{radius:t,color:n,variant:r,autoContrast:o})=>{const s=e.variantColorResolver({theme:e,color:n||e.primaryColor,autoContrast:o,variant:r||"filled"});return{tooltip:{"--tooltip-radius":t===void 0?void 0:Ft(t),"--tooltip-bg":n?s.background:void 0,"--tooltip-color":n?s.color:void 0}}},to=ge((e,t)=>{const n=ie("Tooltip",pT,e),{children:r,position:o,refProp:s,label:c,openDelay:d,closeDelay:f,onPositionChange:p,opened:m,defaultOpened:g,withinPortal:y,radius:b,color:S,classNames:j,styles:C,unstyled:R,style:E,className:T,withArrow:_,arrowSize:k,arrowOffset:I,arrowRadius:A,arrowPosition:P,offset:z,transitionProps:B,multiline:Y,events:J,zIndex:Z,disabled:$,positionDependencies:Q,onClick:M,onMouseEnter:L,onMouseLeave:U,inline:V,variant:K,keepMounted:O,vars:F,portalProps:ae,mod:ue,floatingStrategy:be,middlewares:we,autoContrast:Ce,attributes:nt,target:De,...ft}=ie("Tooltip",pT,n),{dir:ot}=ws(),ht=v.useRef(null),st=n$({position:M_(ot,o),closeDelay:f,openDelay:d,onPositionChange:p,opened:m,defaultOpened:g,events:J,arrowRef:ht,arrowOffset:I,offset:typeof z=="number"?z+(_?k/2:0):z,positionDependencies:[...Q,De??r],inline:V,strategy:be,middlewares:we});v.useEffect(()=>{const Ie=De instanceof HTMLElement?De:typeof De=="string"?document.querySelector(De):De?.current||null;Ie&&st.reference(Ie)},[De,st]);const yt=Le({name:"Tooltip",props:n,classes:Om,className:T,style:E,classNames:j,styles:C,unstyled:R,attributes:nt,rootSelector:"tooltip",vars:F,varsResolver:r$});if(!De&&!Lo(r))return null;if(De){const Ie=hT(B,{duration:100,transition:"fade"});return a.jsx(a.Fragment,{children:a.jsx(va,{...ae,withinPortal:y,children:a.jsx(Zi,{...Ie,keepMounted:O,mounted:!$&&!!st.opened,duration:st.isGroupPhase?10:Ie.duration,children:Oe=>a.jsxs(ce,{...ft,"data-fixed":be==="fixed"||void 0,variant:K,mod:[{multiline:Y},ue],...st.getFloatingProps({ref:st.floating,className:yt("tooltip").className,style:{...yt("tooltip").style,...Oe,zIndex:Z,top:st.y??0,left:st.x??0}}),children:[c,a.jsx(Ep,{ref:ht,arrowX:st.arrowX,arrowY:st.arrowY,visible:_,position:st.placement,arrowSize:k,arrowOffset:I,arrowRadius:A,arrowPosition:P,...yt("arrow")})]})})})})}const mt=r,It=mt.props,Te=Bn(st.reference,em(mt),t),Re=hT(B,{duration:100,transition:"fade"});return a.jsxs(a.Fragment,{children:[a.jsx(va,{...ae,withinPortal:y,children:a.jsx(Zi,{...Re,keepMounted:O,mounted:!$&&!!st.opened,duration:st.isGroupPhase?10:Re.duration,children:Ie=>a.jsxs(ce,{...ft,"data-fixed":be==="fixed"||void 0,variant:K,mod:[{multiline:Y},ue],...st.getFloatingProps({ref:st.floating,className:yt("tooltip").className,style:{...yt("tooltip").style,...Ie,zIndex:Z,top:st.y??0,left:st.x??0}}),children:[c,a.jsx(Ep,{ref:ht,arrowX:st.arrowX,arrowY:st.arrowY,visible:_,position:st.placement,arrowSize:k,arrowOffset:I,arrowRadius:A,arrowPosition:P,...yt("arrow")})]})})}),v.cloneElement(mt,st.getReferenceProps({onClick:M,onMouseEnter:L,onMouseLeave:U,onMouseMove:n.onMouseMove,onPointerDown:n.onPointerDown,onPointerEnter:n.onPointerEnter,className:Ut(T,It.className),...It,[s]:Te}))]})});to.classes=Om;to.displayName="@mantine/core/Tooltip";to.Floating=B0;to.Group=V0;function i$({size:e,thickness:t,sum:n,value:r,root:o,offset:s}){const c=(e*.9-t*2)/2,d=Math.PI*c*2/100,f=o||r===void 0?`${(100-n)*d}, ${n*d}`:`${r*d}, ${(100-r)*d}`;return{strokeWidth:Number.isNaN(t)?12:t,cx:e/2||0,cy:e/2||0,r:c||0,transform:o?`scale(1, -1) translate(0, -${e})`:void 0,strokeDasharray:f,strokeDashoffset:o?0:s||0}}function cD({size:e,value:t,offset:n,sum:r,thickness:o,root:s,color:c,lineRoundCaps:d,tooltip:f,getStyles:p,display:m,...g}){const y=gn();return a.jsx(to.Floating,{disabled:!f,label:f,children:a.jsx(ce,{component:"circle",...g,...p("curve"),__vars:{"--curve-color":c?Wt(c,y):void 0},fill:"none",strokeLinecap:d?"round":"butt",...i$({sum:r,size:e,thickness:o,value:t,offset:n,root:s})})})}cD.displayName="@mantine/core/Curve";function o$({size:e,thickness:t,sections:n,renderRoundedLineCaps:r,rootColor:o}){const s=n.reduce((m,g)=>m+g.value,0),c=Math.PI*((e*.9-t*2)/2)*2;let d=c;const f=[],p=[];for(let m=0;m<n.length;m+=1)f.push({sum:s,offset:d,data:n[m],root:!1}),d-=n[m].value/100*c;if(f.push({sum:s,offset:d,data:{color:o},root:!0}),p.push({...f[f.length-1],lineRoundCaps:!1}),f.length>2){p.push({...f[0],lineRoundCaps:r}),p.push({...f[f.length-2],lineRoundCaps:r});for(let m=1;m<=f.length-3;m+=1)p.push({...f[m],lineRoundCaps:!1})}else p.push({...f[0],lineRoundCaps:r});return p}var uD={root:"m_b32e4812",svg:"m_d43b5134",curve:"m_b1ca1fbf",label:"m_b23f9dc4"};function a$(e,t){return Math.min(e||12,(t||120)/4)}const s$={size:120,thickness:12},l$=(e,{size:t,thickness:n,transitionDuration:r})=>({root:{"--rp-size":le(t),"--rp-label-offset":le(n*2),"--rp-transition-duration":r?`${r}ms`:void 0}}),Mm=ge((e,t)=>{const n=ie("RingProgress",s$,e),{classNames:r,className:o,style:s,styles:c,unstyled:d,vars:f,label:p,sections:m,size:g,thickness:y,roundCaps:b,rootColor:S,transitionDuration:j,attributes:C,...R}=n,E=Le({name:"RingProgress",classes:uD,props:n,className:o,style:s,classNames:r,styles:c,unstyled:d,attributes:C,vars:f,varsResolver:l$}),T=a$(y,g),_=o$({size:g,thickness:T,sections:m,renderRoundedLineCaps:b,rootColor:S}).map(({data:k,sum:I,root:A,lineRoundCaps:P,offset:z},B)=>v.createElement(cD,{...k,key:B,size:g,thickness:T,sum:I,offset:z,color:k?.color,root:A,lineRoundCaps:P,getStyles:E}));return a.jsxs(ce,{...E("root"),size:g,ref:t,...R,children:[a.jsx("svg",{...E("svg"),children:_}),p&&a.jsx("div",{...E("label"),children:p})]})});Mm.classes=uD;Mm.displayName="@mantine/core/RingProgress";var dD={root:"m_cf365364",indicator:"m_9e182ccd",label:"m_1738fcb2",input:"m_1714d588",control:"m_69686b9b",innerLabel:"m_78882f40"};const c$={withItemsBorders:!0},u$=(e,{radius:t,color:n,transitionDuration:r,size:o,transitionTimingFunction:s})=>({root:{"--sc-radius":t===void 0?void 0:Ft(t),"--sc-color":n?Wt(n,e):void 0,"--sc-shadow":n?void 0:"var(--mantine-shadow-xs)","--sc-transition-duration":r===void 0?void 0:`${r}ms`,"--sc-transition-timing-function":s,"--sc-padding":it(o,"sc-padding"),"--sc-font-size":Qn(o)}}),qc=ge((e,t)=>{const n=ie("SegmentedControl",c$,e),{classNames:r,className:o,style:s,styles:c,unstyled:d,vars:f,data:p,value:m,defaultValue:g,onChange:y,size:b,name:S,disabled:j,readOnly:C,fullWidth:R,orientation:E,radius:T,color:_,transitionDuration:k,transitionTimingFunction:I,variant:A,autoContrast:P,withItemsBorders:z,mod:B,attributes:Y,...J}=n,Z=Le({name:"SegmentedControl",props:n,classes:dD,className:o,style:s,classNames:r,styles:c,unstyled:d,attributes:Y,vars:f,varsResolver:u$}),$=gn(),Q=p.map(De=>typeof De=="string"?{label:De,value:De}:De),M=b4(),[L,U]=v.useState(bp()),[V,K]=v.useState(null),[O,F]=v.useState({}),ae=(De,ft)=>{O[ft]=De,F(O)},[ue,be]=rr({value:m,defaultValue:g,finalValue:Array.isArray(p)?Q.find(De=>!De.disabled)?.value??p[0]?.value??null:null,onChange:y}),we=mr(S),Ce=Q.map(De=>v.createElement(ce,{...Z("control"),mod:{active:ue===De.value,orientation:E},key:De.value},v.createElement("input",{...Z("input"),disabled:j||De.disabled,type:"radio",name:we,value:De.value,id:`${we}-${De.value}`,checked:ue===De.value,onChange:()=>!C&&be(De.value),"data-focus-ring":$.focusRing,key:`${De.value}-input`}),v.createElement(ce,{component:"label",...Z("label"),mod:{active:ue===De.value&&!(j||De.disabled),disabled:j||De.disabled,"read-only":C},htmlFor:`${we}-${De.value}`,ref:ft=>ae(ft,De.value),__vars:{"--sc-label-color":_!==void 0?wa({color:_,theme:$,autoContrast:P}):void 0},key:`${De.value}-label`},a.jsx("span",{...Z("innerLabel"),children:De.label})))),nt=Bn(t,De=>K(De));return d4(()=>{U(bp())},[p.length]),p.length===0?null:a.jsxs(ce,{...Z("root"),variant:A,size:b,ref:nt,mod:[{"full-width":R,orientation:E,initialized:M,"with-items-borders":z},B],...J,role:"radiogroup","data-disabled":j,children:[typeof ue=="string"&&a.jsx(Gb,{target:O[ue],parent:V,component:"span",transitionDuration:"var(--sc-transition-duration)",...Z("indicator")},L),Ce]})});qc.classes=dD;qc.displayName="@mantine/core/SegmentedControl";function d$({spacing:e,verticalSpacing:t,cols:n,selector:r}){const o=gn(),s=t===void 0?e:t,c=Ss({"--sg-spacing-x":Gn(Qi(e)),"--sg-spacing-y":Gn(Qi(s)),"--sg-cols":Qi(n)?.toString()}),d=dn(o.breakpoints).reduce((m,g)=>(m[g]||(m[g]={}),typeof e=="object"&&e[g]!==void 0&&(m[g]["--sg-spacing-x"]=Gn(e[g])),typeof s=="object"&&s[g]!==void 0&&(m[g]["--sg-spacing-y"]=Gn(s[g])),typeof n=="object"&&n[g]!==void 0&&(m[g]["--sg-cols"]=n[g]),m),{}),p=Sd(dn(d),o.breakpoints).filter(m=>dn(d[m.value]).length>0).map(m=>({query:`(min-width: ${o.breakpoints[m.value]})`,styles:d[m.value]}));return a.jsx(Tl,{styles:c,media:p,selector:r})}function Hy(e){return typeof e=="object"&&e!==null?dn(e):[]}function f$(e){return e.sort((t,n)=>bd(t)-bd(n))}function h$({spacing:e,verticalSpacing:t,cols:n}){const r=Array.from(new Set([...Hy(e),...Hy(t),...Hy(n)]));return f$(r)}function p$({spacing:e,verticalSpacing:t,cols:n,selector:r}){const o=t===void 0?e:t,s=Ss({"--sg-spacing-x":Gn(Qi(e)),"--sg-spacing-y":Gn(Qi(o)),"--sg-cols":Qi(n)?.toString()}),c=h$({spacing:e,verticalSpacing:t,cols:n}),d=c.reduce((p,m)=>(p[m]||(p[m]={}),typeof e=="object"&&e[m]!==void 0&&(p[m]["--sg-spacing-x"]=Gn(e[m])),typeof o=="object"&&o[m]!==void 0&&(p[m]["--sg-spacing-y"]=Gn(o[m])),typeof n=="object"&&n[m]!==void 0&&(p[m]["--sg-cols"]=n[m]),p),{}),f=c.map(p=>({query:`simple-grid (min-width: ${p})`,styles:d[p]}));return a.jsx(Tl,{styles:s,container:f,selector:r})}var fD={container:"m_925c2d2c",root:"m_2415a157"};const m$={cols:1,spacing:"md",type:"media"},Lm=ge((e,t)=>{const n=ie("SimpleGrid",m$,e),{classNames:r,className:o,style:s,styles:c,unstyled:d,vars:f,cols:p,verticalSpacing:m,spacing:g,type:y,attributes:b,...S}=n,j=Le({name:"SimpleGrid",classes:fD,props:n,className:o,style:s,classNames:r,styles:c,unstyled:d,attributes:b,vars:f}),C=Hd();return y==="container"?a.jsxs(a.Fragment,{children:[a.jsx(p$,{...n,selector:`.${C}`}),a.jsx("div",{...j("container"),children:a.jsx(ce,{ref:t,...j("root",{className:C}),...S})})]}):a.jsxs(a.Fragment,{children:[a.jsx(d$,{...n,selector:`.${C}`}),a.jsx(ce,{ref:t,...j("root",{className:C}),...S})]})});Lm.classes=fD;Lm.displayName="@mantine/core/SimpleGrid";const Im=ge((e,t)=>{const{w:n,h:r,miw:o,mih:s,...c}=ie("Space",null,e);return a.jsx(ce,{ref:t,...c,w:n,miw:o??n,h:r,mih:s??r})});Im.displayName="@mantine/core/Space";var hD={root:"m_6d731127"};const g$={gap:"md",align:"stretch",justify:"flex-start"},v$=(e,{gap:t,align:n,justify:r})=>({root:{"--stack-gap":Gn(t),"--stack-align":n,"--stack-justify":r}}),Ue=ge((e,t)=>{const n=ie("Stack",g$,e),{classNames:r,className:o,style:s,styles:c,unstyled:d,vars:f,align:p,justify:m,gap:g,variant:y,attributes:b,...S}=n,j=Le({name:"Stack",props:n,classes:hD,className:o,style:s,classNames:r,styles:c,unstyled:d,attributes:b,vars:f,varsResolver:v$});return a.jsx(ce,{ref:t,...j("root"),variant:y,...S})});Ue.classes=hD;Ue.displayName="@mantine/core/Stack";const[y$,x$]=jr("Stepper component was not found in tree"),Rp=()=>null;Rp.displayName="@mantine/core/StepperCompleted";var F0={root:"m_cbb4ea7e",steps:"m_aaf89d0b",separator:"m_2a371ac9",content:"m_78da155d",step:"m_cbb57068","step--horizontal":"m_f56b1e2c","step--vertical":"m_833edb7e",verticalSeparator:"m_6496b3f3",stepWrapper:"m_818e70b",stepIcon:"m_1959ad01",stepCompletedIcon:"m_a79331dc",stepBody:"m_1956aa2a",stepLabel:"m_12051f6c",stepDescription:"m_164eea74"};const Gh=(e,t)=>typeof e=="function"?a.jsx(e,{step:t||0}):e,b$={withIcon:!0,allowStepClick:!0,iconPosition:"left"},H0=ge((e,t)=>{const{classNames:n,className:r,style:o,styles:s,vars:c,step:d,state:f,color:p,icon:m,completedIcon:g,progressIcon:y,label:b,description:S,withIcon:j,iconSize:C,loading:R,allowStepClick:E,allowStepSelect:T,iconPosition:_,orientation:k,mod:I,...A}=ie("StepperStep",b$,e),P=x$(),z=gn(),B={classNames:n,styles:s},Y=f==="stepCompleted"?null:f==="stepProgress"?y:m,J={"data-progress":f==="stepProgress"||void 0,"data-completed":f==="stepCompleted"||void 0};return a.jsxs(An,{...P.getStyles("step",{className:r,style:o,variant:P.orientation,...B}),mod:[{"icon-position":_||P.iconPosition,"allow-click":E},I],ref:t,...J,...A,__vars:{"--step-color":p?Wt(p,z):void 0},tabIndex:E?0:-1,children:[j&&a.jsxs("span",{...P.getStyles("stepWrapper",B),children:[a.jsxs("span",{...P.getStyles("stepIcon",B),...J,children:[a.jsx(Zi,{mounted:f==="stepCompleted",transition:"pop",duration:200,children:Z=>a.jsx("span",{...P.getStyles("stepCompletedIcon",{style:Z,...B}),children:R?a.jsx(Ir,{color:"var(--mantine-color-white)",size:"calc(var(--stepper-icon-size) / 2)",...P.getStyles("stepLoader",B)}):Gh(g,d)||a.jsx(Xd,{size:"60%"})})}),f!=="stepCompleted"?R?a.jsx(Ir,{...P.getStyles("stepLoader",B),size:"calc(var(--stepper-icon-size) / 2)",color:p}):Gh(Y||m,d):null]}),k==="vertical"&&a.jsx("span",{...P.getStyles("verticalSeparator",B),"data-active":f==="stepCompleted"||void 0})]}),(b||S)&&a.jsxs("span",{...P.getStyles("stepBody",B),"data-orientation":P.orientation,"data-icon-position":_||P.iconPosition,children:[b&&a.jsx("span",{...P.getStyles("stepLabel",B),children:Gh(b,d)}),S&&a.jsx("span",{...P.getStyles("stepDescription",B),children:Gh(S,d)})]})]})});H0.classes=F0;H0.displayName="@mantine/core/StepperStep";const S$={orientation:"horizontal",iconPosition:"left",allowNextStepsSelect:!0,wrap:!0},w$=(e,{color:t,iconSize:n,size:r,contentPadding:o,radius:s,autoContrast:c})=>({root:{"--stepper-color":t?Wt(t,e):void 0,"--stepper-icon-color":El(c,e)?wa({color:t,theme:e,autoContrast:c}):void 0,"--stepper-icon-size":n===void 0?it(r,"stepper-icon-size"):le(n),"--stepper-content-padding":Gn(o),"--stepper-radius":s===void 0?void 0:Ft(s),"--stepper-fz":Qn(r),"--stepper-spacing":Gn(r)}}),Gc=ge((e,t)=>{const n=ie("Stepper",S$,e),{classNames:r,className:o,style:s,styles:c,unstyled:d,vars:f,children:p,onStepClick:m,active:g,icon:y,completedIcon:b,progressIcon:S,color:j,iconSize:C,contentPadding:R,orientation:E,iconPosition:T,size:_,radius:k,allowNextStepsSelect:I,wrap:A,autoContrast:P,attributes:z,...B}=n,Y=Le({name:"Stepper",classes:F0,props:n,className:o,style:s,classNames:r,styles:c,unstyled:d,attributes:z,vars:f,varsResolver:w$}),J=v.Children.toArray(p),Z=J.filter(V=>V.type!==Rp),$=J.find(V=>V.type===Rp),Q=Z.reduce((V,K,O)=>{const F=g===O?"stepProgress":g>O?"stepCompleted":"stepInactive",ue=typeof m!="function"?!1:typeof K.props.allowStepSelect=="boolean"?K.props.allowStepSelect:F==="stepCompleted"||I;return V.push(v.cloneElement(K,{icon:K.props.icon||y||O+1,key:O,step:O,state:F,onClick:()=>ue&&m?.(O),allowStepClick:ue,completedIcon:K.props.completedIcon||b,progressIcon:K.props.progressIcon||S,color:K.props.color||j,iconSize:C,iconPosition:K.props.iconPosition||T,orientation:E})),E==="horizontal"&&O!==Z.length-1&&V.push(v.createElement("div",{...Y("separator"),"data-active":O<g||void 0,"data-orientation":E,key:`separator-${O}`})),V},[]),M=Z[g]?.props?.children,L=$?.props?.children,U=g>Z.length-1?L:M;return a.jsx(y$,{value:{getStyles:Y,orientation:E,iconPosition:T},children:a.jsxs(ce,{...Y("root"),ref:t,size:_,...B,children:[a.jsx(ce,{...Y("steps"),mod:{orientation:E,"icon-position":T,wrap:A&&E!=="vertical"},children:Q}),U&&a.jsx("div",{...Y("content"),children:U})]})})});Gc.classes=F0;Gc.displayName="@mantine/core/Stepper";Gc.Completed=Rp;Gc.Step=H0;const pD=v.createContext(null),j$=pD.Provider,C$=()=>v.useContext(pD),q0=ge((e,t)=>{const{value:n,defaultValue:r,onChange:o,size:s,wrapperProps:c,children:d,readOnly:f,disabled:p,...m}=ie("SwitchGroup",null,e),[g,y]=rr({value:n,defaultValue:r,finalValue:[],onChange:o}),b=S=>{const j=S.currentTarget.value;!f&&y(g.includes(j)?g.filter(C=>C!==j):[...g,j])};return a.jsx(j$,{value:{value:g,onChange:b,size:s,disabled:p},children:a.jsx(hn.Wrapper,{size:s,ref:t,...c,...m,labelElement:"div",__staticSelector:"SwitchGroup",children:a.jsx(c0,{role:"group",children:d})})})});q0.classes=hn.Wrapper.classes;q0.displayName="@mantine/core/SwitchGroup";var mD={root:"m_5f93f3bb",input:"m_926b4011",track:"m_9307d992",thumb:"m_93039a1d",trackLabel:"m_8277e082"};const E$={labelPosition:"right",withThumbIndicator:!0},T$=(e,{radius:t,color:n,size:r})=>({root:{"--switch-radius":t===void 0?void 0:Ft(t),"--switch-height":it(r,"switch-height"),"--switch-width":it(r,"switch-width"),"--switch-thumb-size":it(r,"switch-thumb-size"),"--switch-label-font-size":it(r,"switch-label-font-size"),"--switch-track-label-padding":it(r,"switch-track-label-padding"),"--switch-color":n?Wt(n,e):void 0}}),rf=ge((e,t)=>{const n=ie("Switch",E$,e),{classNames:r,className:o,style:s,styles:c,unstyled:d,vars:f,color:p,label:m,offLabel:g,onLabel:y,id:b,size:S,radius:j,wrapperProps:C,thumbIcon:R,checked:E,defaultChecked:T,onChange:_,labelPosition:k,description:I,error:A,disabled:P,variant:z,rootRef:B,mod:Y,withThumbIndicator:J,attributes:Z,...$}=n,Q=C$(),M=S||Q?.size,L=Le({name:"Switch",props:n,classes:mD,className:o,style:s,classNames:r,styles:c,unstyled:d,attributes:Z,vars:f,varsResolver:T$}),{styleProps:U,rest:V}=ja($),K=mr(b),O={checked:Q?.value.includes(V.value)??E,onChange:ue=>{Q?.onChange(ue),_?.(ue)},disabled:Q?.disabled??P},[F,ae]=rr({value:O.checked??E,defaultValue:T,finalValue:!1});return a.jsxs(mm,{...L("root"),__staticSelector:"Switch",__stylesApiProps:n,id:K,size:M,labelPosition:k,label:m,description:I,error:A,disabled:O.disabled,bodyElement:"label",labelElement:"span",classNames:r,styles:c,unstyled:d,"data-checked":O.checked,variant:z,ref:B,mod:Y,...U,...C,children:[a.jsx("input",{...V,...O,checked:F,"data-checked":O.checked,onChange:ue=>{O.onChange?.(ue),ae(ue.currentTarget.checked)},id:K,ref:t,type:"checkbox",role:"switch",...L("input")}),a.jsxs(ce,{"aria-hidden":"true",component:"span",mod:{error:A,"label-position":k,"without-labels":!y&&!g},...L("track"),children:[a.jsx(ce,{component:"span",mod:{"reduce-motion":!0,"with-thumb-indicator":J&&!R},...L("thumb"),children:R}),a.jsx("span",{...L("trackLabel"),children:F?y:g})]})]})});rf.classes={...mD,...xA};rf.displayName="@mantine/core/Switch";rf.Group=q0;const[R$,_$]=jr("Table component was not found in the tree");var of={table:"m_b23fa0ef",th:"m_4e7aa4f3",tr:"m_4e7aa4fd",td:"m_4e7aa4ef",tbody:"m_b2404537",thead:"m_b242d975",caption:"m_9e5a3ac7",scrollContainer:"m_a100c15",scrollContainerInner:"m_62259741"};function A$(e,t){if(!t)return;const n={};return t.columnBorder&&e.withColumnBorders&&(n["data-with-column-border"]=!0),t.rowBorder&&e.withRowBorders&&(n["data-with-row-border"]=!0),t.striped&&e.striped&&(n["data-striped"]=e.striped),t.highlightOnHover&&e.highlightOnHover&&(n["data-hover"]=!0),t.captionSide&&e.captionSide&&(n["data-side"]=e.captionSide),t.stickyHeader&&e.stickyHeader&&(n["data-sticky"]=!0),n}function Al(e,t){const n=`Table${e.charAt(0).toUpperCase()}${e.slice(1)}`,r=ge((o,s)=>{const c=ie(n,{},o),{classNames:d,className:f,style:p,styles:m,...g}=c,y=_$();return a.jsx(ce,{component:e,ref:s,...A$(y,t),...y.getStyles(e,{className:f,classNames:d,style:p,styles:m,props:c}),...g})});return r.displayName=`@mantine/core/${n}`,r.classes=of,r}const $x=Al("th",{columnBorder:!0}),gD=Al("td",{columnBorder:!0}),up=Al("tr",{rowBorder:!0,striped:!0,highlightOnHover:!0}),vD=Al("thead",{stickyHeader:!0}),yD=Al("tbody"),xD=Al("tfoot"),bD=Al("caption",{captionSide:!0});function G0({data:e}){return a.jsxs(a.Fragment,{children:[e.caption&&a.jsx(bD,{children:e.caption}),e.head&&a.jsx(vD,{children:a.jsx(up,{children:e.head.map((t,n)=>a.jsx($x,{children:t},n))})}),e.body&&a.jsx(yD,{children:e.body.map((t,n)=>a.jsx(up,{children:t.map((r,o)=>a.jsx(gD,{children:r},o))},n))}),e.foot&&a.jsx(xD,{children:a.jsx(up,{children:e.foot.map((t,n)=>a.jsx($x,{children:t},n))})})]})}G0.displayName="@mantine/core/TableDataRenderer";const D$={type:"scrollarea"},k$=(e,{minWidth:t,maxHeight:n,type:r})=>({scrollContainer:{"--table-min-width":le(t),"--table-max-height":le(n),"--table-overflow":r==="native"?"auto":void 0}}),Q0=ge((e,t)=>{const n=ie("TableScrollContainer",D$,e),{classNames:r,className:o,style:s,styles:c,unstyled:d,vars:f,children:p,minWidth:m,maxHeight:g,type:y,scrollAreaProps:b,attributes:S,...j}=n,C=Le({name:"TableScrollContainer",classes:of,props:n,className:o,style:s,classNames:r,styles:c,unstyled:d,attributes:S,vars:f,varsResolver:k$,rootSelector:"scrollContainer"});return a.jsx(ce,{component:y==="scrollarea"?Jr:"div",...y==="scrollarea"?g?{offsetScrollbars:"xy",...b}:{offsetScrollbars:"x",...b}:{},ref:t,...C("scrollContainer"),...j,children:a.jsx("div",{...C("scrollContainerInner"),children:p})})});Q0.classes=of;Q0.displayName="@mantine/core/TableScrollContainer";const P$={withRowBorders:!0,verticalSpacing:7},N$=(e,{layout:t,captionSide:n,horizontalSpacing:r,verticalSpacing:o,borderColor:s,stripedColor:c,highlightOnHoverColor:d,striped:f,highlightOnHover:p,stickyHeaderOffset:m,stickyHeader:g})=>({table:{"--table-layout":t,"--table-caption-side":n,"--table-horizontal-spacing":Gn(r),"--table-vertical-spacing":Gn(o),"--table-border-color":s?Wt(s,e):void 0,"--table-striped-color":f&&c?Wt(c,e):void 0,"--table-highlight-on-hover-color":p&&d?Wt(d,e):void 0,"--table-sticky-header-offset":g?le(m):void 0}}),de=ge((e,t)=>{const n=ie("Table",P$,e),{classNames:r,className:o,style:s,styles:c,unstyled:d,vars:f,horizontalSpacing:p,verticalSpacing:m,captionSide:g,stripedColor:y,highlightOnHoverColor:b,striped:S,highlightOnHover:j,withColumnBorders:C,withRowBorders:R,withTableBorder:E,borderColor:T,layout:_,variant:k,data:I,children:A,stickyHeader:P,stickyHeaderOffset:z,mod:B,tabularNums:Y,attributes:J,...Z}=n,$=Le({name:"Table",props:n,className:o,style:s,classes:of,classNames:r,styles:c,unstyled:d,attributes:J,rootSelector:"table",vars:f,varsResolver:N$});return a.jsx(R$,{value:{getStyles:$,stickyHeader:P,striped:S===!0?"odd":S||void 0,highlightOnHover:j,withColumnBorders:C,withRowBorders:R,captionSide:g||"bottom"},children:a.jsx(ce,{component:"table",variant:k,ref:t,mod:[{"data-with-table-border":E,"data-tabular-nums":Y},B],...$("table"),...Z,children:A||!!I&&a.jsx(G0,{data:I})})})});de.classes=of;de.displayName="@mantine/core/Table";de.Td=gD;de.Th=$x;de.Tr=up;de.Thead=vD;de.Tbody=yD;de.Tfoot=xD;de.Caption=bD;de.ScrollContainer=Q0;de.DataRenderer=G0;const[O$,W0]=jr("Tabs component was not found in the tree");var af={root:"m_89d60db1","list--default":"m_576c9d4",list:"m_89d33d6d",tab:"m_4ec4dce6",panel:"m_b0c91715",tabSection:"m_fc420b1f",tabLabel:"m_42bbd1ae","tab--default":"m_539e827b","list--outline":"m_6772fbd5","tab--outline":"m_b59ab47c","tab--pills":"m_c3381914"};const Y0=ge((e,t)=>{const n=ie("TabsList",null,e),{children:r,className:o,grow:s,justify:c,classNames:d,styles:f,style:p,mod:m,...g}=n,y=W0();return a.jsx(ce,{...g,...y.getStyles("list",{className:o,style:p,classNames:d,styles:f,props:n,variant:y.variant}),ref:t,role:"tablist",variant:y.variant,mod:[{grow:s,orientation:y.orientation,placement:y.orientation==="vertical"&&y.placement,inverted:y.inverted},m],"aria-orientation":y.orientation,__vars:{"--tabs-justify":c},children:r})});Y0.classes=af;Y0.displayName="@mantine/core/TabsList";const K0=ge((e,t)=>{const n=ie("TabsPanel",null,e),{children:r,className:o,value:s,classNames:c,styles:d,style:f,mod:p,keepMounted:m,...g}=n,y=W0(),b=y.value===s,S=y.keepMounted||m||b?r:null;return a.jsx(ce,{...y.getStyles("panel",{className:o,classNames:c,styles:d,style:[f,b?void 0:{display:"none"}],props:n}),ref:t,mod:[{orientation:y.orientation},p],role:"tabpanel",id:y.getPanelId(s),"aria-labelledby":y.getTabId(s),...g,children:S})});K0.classes=af;K0.displayName="@mantine/core/TabsPanel";const X0=ge((e,t)=>{const n=ie("TabsTab",null,e),{className:r,children:o,rightSection:s,leftSection:c,value:d,onClick:f,onKeyDown:p,disabled:m,color:g,style:y,classNames:b,styles:S,vars:j,mod:C,tabIndex:R,...E}=n,T=gn(),{dir:_}=ws(),k=W0(),I=d===k.value,A=z=>{k.onChange(k.allowTabDeactivation&&d===k.value?null:d),f?.(z)},P={classNames:b,styles:S,props:n};return a.jsxs(An,{...k.getStyles("tab",{className:r,style:y,variant:k.variant,...P}),disabled:m,unstyled:k.unstyled,variant:k.variant,mod:[{active:I,disabled:m,orientation:k.orientation,inverted:k.inverted,placement:k.orientation==="vertical"&&k.placement},C],ref:t,role:"tab",id:k.getTabId(d),"aria-selected":I,tabIndex:R!==void 0?R:I||k.value===null?0:-1,"aria-controls":k.getPanelId(d),onClick:A,__vars:{"--tabs-color":g?Wt(g,T):void 0},onKeyDown:yb({siblingSelector:'[role="tab"]',parentSelector:'[role="tablist"]',activateOnFocus:k.activateTabWithKeyboard,loop:k.loop,orientation:k.orientation||"horizontal",dir:_,onKeyDown:p}),...E,children:[c&&a.jsx("span",{...k.getStyles("tabSection",P),"data-position":"left",children:c}),o&&a.jsx("span",{...k.getStyles("tabLabel",P),children:o}),s&&a.jsx("span",{...k.getStyles("tabSection",P),"data-position":"right",children:s})]})});X0.classes=af;X0.displayName="@mantine/core/TabsTab";const mT="Tabs.Tab or Tabs.Panel component was rendered with invalid value or without value",M$={keepMounted:!0,orientation:"horizontal",loop:!0,activateTabWithKeyboard:!0,variant:"default",placement:"left"},L$=(e,{radius:t,color:n,autoContrast:r})=>({root:{"--tabs-radius":Ft(t),"--tabs-color":Wt(n,e),"--tabs-text-color":El(r,e)?wa({color:n,theme:e,autoContrast:r}):void 0}}),Pt=ge((e,t)=>{const n=ie("Tabs",M$,e),{defaultValue:r,value:o,onChange:s,orientation:c,children:d,loop:f,id:p,activateTabWithKeyboard:m,allowTabDeactivation:g,variant:y,color:b,radius:S,inverted:j,placement:C,keepMounted:R,classNames:E,styles:T,unstyled:_,className:k,style:I,vars:A,autoContrast:P,mod:z,attributes:B,...Y}=n,J=mr(p),[Z,$]=rr({value:o,defaultValue:r,finalValue:null,onChange:s}),Q=Le({name:"Tabs",props:n,classes:af,className:k,style:I,classNames:E,styles:T,unstyled:_,attributes:B,vars:A,varsResolver:L$});return a.jsx(O$,{value:{placement:C,value:Z,orientation:c,id:J,loop:f,activateTabWithKeyboard:m,getTabId:lE(`${J}-tab`,mT),getPanelId:lE(`${J}-panel`,mT),onChange:$,allowTabDeactivation:g,variant:y,color:b,radius:S,inverted:j,keepMounted:R,unstyled:_,getStyles:Q},children:a.jsx(ce,{ref:t,id:J,variant:y,mod:[{orientation:c,inverted:c==="horizontal"&&j,placement:c==="vertical"&&C},z],...Q("root"),...Y,children:d})})});Pt.classes=af;Pt.displayName="@mantine/core/Tabs";Pt.Tab=X0;Pt.Panel=K0;Pt.List=Y0;const He=ge((e,t)=>{const n=ie("TextInput",null,e);return a.jsx($r,{component:"input",ref:t,...n,__staticSelector:"TextInput"})});He.classes=$r.classes;He.displayName="@mantine/core/TextInput";var SD={root:"m_7341320d"};const I$=(e,{size:t,radius:n,variant:r,gradient:o,color:s,autoContrast:c})=>{const d=e.variantColorResolver({color:s||e.primaryColor,theme:e,gradient:o,variant:r||"filled",autoContrast:c});return{root:{"--ti-size":it(t,"ti-size"),"--ti-radius":n===void 0?void 0:Ft(n),"--ti-bg":s||r?d.background:void 0,"--ti-color":s||r?d.color:void 0,"--ti-bd":s||r?d.border:void 0}}},J0=ge((e,t)=>{const n=ie("ThemeIcon",null,e),{classNames:r,className:o,style:s,styles:c,unstyled:d,vars:f,autoContrast:p,attributes:m,...g}=n,y=Le({name:"ThemeIcon",classes:SD,props:n,className:o,style:s,classNames:r,styles:c,unstyled:d,attributes:m,vars:f,varsResolver:I$});return a.jsx(ce,{ref:t,...y("root"),...g})});J0.classes=SD;J0.displayName="@mantine/core/ThemeIcon";const z$=["h1","h2","h3","h4","h5","h6"],$$=["xs","sm","md","lg","xl"];function U$(e,t){const n=t!==void 0?t:`h${e}`;return z$.includes(n)?{fontSize:`var(--mantine-${n}-font-size)`,fontWeight:`var(--mantine-${n}-font-weight)`,lineHeight:`var(--mantine-${n}-line-height)`}:$$.includes(n)?{fontSize:`var(--mantine-font-size-${n})`,fontWeight:`var(--mantine-h${e}-font-weight)`,lineHeight:`var(--mantine-h${e}-line-height)`}:{fontSize:le(n),fontWeight:`var(--mantine-h${e}-font-weight)`,lineHeight:`var(--mantine-h${e}-line-height)`}}var wD={root:"m_8a5d1357"};const B$={order:1},V$=(e,{order:t,size:n,lineClamp:r,textWrap:o})=>{const s=U$(t||1,n);return{root:{"--title-fw":s.fontWeight,"--title-lh":s.lineHeight,"--title-fz":s.fontSize,"--title-line-clamp":typeof r=="number"?r.toString():void 0,"--title-text-wrap":o}}},ze=ge((e,t)=>{const n=ie("Title",B$,e),{classNames:r,className:o,style:s,styles:c,unstyled:d,order:f,vars:p,size:m,variant:g,lineClamp:y,textWrap:b,mod:S,attributes:j,...C}=n,R=Le({name:"Title",props:n,classes:wD,className:o,style:s,classNames:r,styles:c,unstyled:d,attributes:j,vars:p,varsResolver:V$});return[1,2,3,4,5,6].includes(f)?a.jsx(ce,{...R("root"),component:`h${f}`,variant:g,ref:t,mod:[{order:f,"data-line-clamp":typeof y=="number"},S],size:m,...C}):null});ze.classes=wD;ze.displayName="@mantine/core/Title";function jD(e){let t=e,n=!1;const r=new Set;return{getState(){return t},updateState(o){t=typeof o=="function"?o(t):o},setState(o){this.updateState(o),r.forEach(s=>s(t))},initialize(o){n||(t=o,n=!0)},subscribe(o){return r.add(o),()=>r.delete(o)}}}function CD(e){return v.useSyncExternalStore(e.subscribe,()=>e.getState(),()=>e.getState())}function F$(e,t,n){const r=[],o=[],s={};for(const c of e){const d=c.position||t;s[d]=s[d]||0,s[d]+=1,s[d]<=n?o.push(c):r.push(c)}return{notifications:o,queue:r}}const H$=()=>jD({notifications:[],queue:[],defaultPosition:"bottom-right",limit:5}),Dl=H$(),q$=(e=Dl)=>CD(e);function cu(e,t){const n=e.getState(),r=t([...n.notifications,...n.queue]),o=F$(r,n.defaultPosition,n.limit);e.setState({notifications:o.notifications,queue:o.queue,limit:n.limit,defaultPosition:n.defaultPosition})}function Ne(e,t=Dl){const n=e.id||bp();return cu(t,r=>e.id&&r.some(o=>o.id===e.id)?r:[...r,{...e,id:n}]),n}function ED(e,t=Dl){return cu(t,n=>n.filter(r=>r.id===e?(r.onClose?.(r),!1):!0)),e}function rl(e,t=Dl){return cu(t,n=>n.map(r=>r.id===e.id?{...r,...e}:r)),e.id}function G$(e=Dl){cu(e,()=>[])}function Q$(e=Dl){cu(e,t=>t.slice(0,e.getState().limit))}const Di={show:Ne,hide:ED,update:rl,clean:G$,cleanQueue:Q$,updateState:cu};function Ux(e,t){return Ux=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},Ux(e,t)}function TD(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,Ux(e,t)}var qy={exports:{}},Gy,gT;function W$(){if(gT)return Gy;gT=1;var e="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";return Gy=e,Gy}var Qy,vT;function Y$(){if(vT)return Qy;vT=1;var e=W$();function t(){}function n(){}return n.resetWarningCache=t,Qy=function(){function r(c,d,f,p,m,g){if(g!==e){var y=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw y.name="Invariant Violation",y}}r.isRequired=r;function o(){return r}var s={array:r,bigint:r,bool:r,func:r,number:r,object:r,string:r,symbol:r,any:r,arrayOf:o,element:r,elementType:r,instanceOf:o,node:r,objectOf:o,oneOf:o,oneOfType:o,shape:o,exact:o,checkPropTypes:n,resetWarningCache:t};return s.PropTypes=s,s},Qy}var yT;function K$(){return yT||(yT=1,qy.exports=Y$()()),qy.exports}var X$=K$();const un=Xp(X$),xT={disabled:!1},_p=Mn.createContext(null);var J$=function(t){return t.scrollTop},pd="unmounted",Ks="exited",Xs="entering",Dc="entered",Bx="exiting",Ta=(function(e){TD(t,e);function t(r,o){var s;s=e.call(this,r,o)||this;var c=o,d=c&&!c.isMounting?r.enter:r.appear,f;return s.appearStatus=null,r.in?d?(f=Ks,s.appearStatus=Xs):f=Dc:r.unmountOnExit||r.mountOnEnter?f=pd:f=Ks,s.state={status:f},s.nextCallback=null,s}t.getDerivedStateFromProps=function(o,s){var c=o.in;return c&&s.status===pd?{status:Ks}:null};var n=t.prototype;return n.componentDidMount=function(){this.updateStatus(!0,this.appearStatus)},n.componentDidUpdate=function(o){var s=null;if(o!==this.props){var c=this.state.status;this.props.in?c!==Xs&&c!==Dc&&(s=Xs):(c===Xs||c===Dc)&&(s=Bx)}this.updateStatus(!1,s)},n.componentWillUnmount=function(){this.cancelNextCallback()},n.getTimeouts=function(){var o=this.props.timeout,s,c,d;return s=c=d=o,o!=null&&typeof o!="number"&&(s=o.exit,c=o.enter,d=o.appear!==void 0?o.appear:c),{exit:s,enter:c,appear:d}},n.updateStatus=function(o,s){if(o===void 0&&(o=!1),s!==null)if(this.cancelNextCallback(),s===Xs){if(this.props.unmountOnExit||this.props.mountOnEnter){var c=this.props.nodeRef?this.props.nodeRef.current:hd.findDOMNode(this);c&&J$(c)}this.performEnter(o)}else this.performExit();else this.props.unmountOnExit&&this.state.status===Ks&&this.setState({status:pd})},n.performEnter=function(o){var s=this,c=this.props.enter,d=this.context?this.context.isMounting:o,f=this.props.nodeRef?[d]:[hd.findDOMNode(this),d],p=f[0],m=f[1],g=this.getTimeouts(),y=d?g.appear:g.enter;if(!o&&!c||xT.disabled){this.safeSetState({status:Dc},function(){s.props.onEntered(p)});return}this.props.onEnter(p,m),this.safeSetState({status:Xs},function(){s.props.onEntering(p,m),s.onTransitionEnd(y,function(){s.safeSetState({status:Dc},function(){s.props.onEntered(p,m)})})})},n.performExit=function(){var o=this,s=this.props.exit,c=this.getTimeouts(),d=this.props.nodeRef?void 0:hd.findDOMNode(this);if(!s||xT.disabled){this.safeSetState({status:Ks},function(){o.props.onExited(d)});return}this.props.onExit(d),this.safeSetState({status:Bx},function(){o.props.onExiting(d),o.onTransitionEnd(c.exit,function(){o.safeSetState({status:Ks},function(){o.props.onExited(d)})})})},n.cancelNextCallback=function(){this.nextCallback!==null&&(this.nextCallback.cancel(),this.nextCallback=null)},n.safeSetState=function(o,s){s=this.setNextCallback(s),this.setState(o,s)},n.setNextCallback=function(o){var s=this,c=!0;return this.nextCallback=function(d){c&&(c=!1,s.nextCallback=null,o(d))},this.nextCallback.cancel=function(){c=!1},this.nextCallback},n.onTransitionEnd=function(o,s){this.setNextCallback(s);var c=this.props.nodeRef?this.props.nodeRef.current:hd.findDOMNode(this),d=o==null&&!this.props.addEndListener;if(!c||d){setTimeout(this.nextCallback,0);return}if(this.props.addEndListener){var f=this.props.nodeRef?[this.nextCallback]:[c,this.nextCallback],p=f[0],m=f[1];this.props.addEndListener(p,m)}o!=null&&setTimeout(this.nextCallback,o)},n.render=function(){var o=this.state.status;if(o===pd)return null;var s=this.props,c=s.children;s.in,s.mountOnEnter,s.unmountOnExit,s.appear,s.enter,s.exit,s.timeout,s.addEndListener,s.onEnter,s.onEntering,s.onEntered,s.onExit,s.onExiting,s.onExited,s.nodeRef;var d=S0(s,["children","in","mountOnEnter","unmountOnExit","appear","enter","exit","timeout","addEndListener","onEnter","onEntering","onEntered","onExit","onExiting","onExited","nodeRef"]);return Mn.createElement(_p.Provider,{value:null},typeof c=="function"?c(o,d):Mn.cloneElement(Mn.Children.only(c),d))},t})(Mn.Component);Ta.contextType=_p;Ta.propTypes={};function wc(){}Ta.defaultProps={in:!1,mountOnEnter:!1,unmountOnExit:!1,appear:!1,enter:!0,exit:!0,onEnter:wc,onEntering:wc,onEntered:wc,onExit:wc,onExiting:wc,onExited:wc};Ta.UNMOUNTED=pd;Ta.EXITED=Ks;Ta.ENTERING=Xs;Ta.ENTERED=Dc;Ta.EXITING=Bx;function Z$(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Z0(e,t){var n=function(s){return t&&v.isValidElement(s)?t(s):s},r=Object.create(null);return e&&v.Children.map(e,function(o){return o}).forEach(function(o){r[o.key]=n(o)}),r}function e8(e,t){e=e||{},t=t||{};function n(m){return m in t?t[m]:e[m]}var r=Object.create(null),o=[];for(var s in e)s in t?o.length&&(r[s]=o,o=[]):o.push(s);var c,d={};for(var f in t){if(r[f])for(c=0;c<r[f].length;c++){var p=r[f][c];d[r[f][c]]=n(p)}d[f]=n(f)}for(c=0;c<o.length;c++)d[o[c]]=n(o[c]);return d}function il(e,t,n){return n[t]!=null?n[t]:e.props[t]}function t8(e,t){return Z0(e.children,function(n){return v.cloneElement(n,{onExited:t.bind(null,n),in:!0,appear:il(n,"appear",e),enter:il(n,"enter",e),exit:il(n,"exit",e)})})}function n8(e,t,n){var r=Z0(e.children),o=e8(t,r);return Object.keys(o).forEach(function(s){var c=o[s];if(v.isValidElement(c)){var d=s in t,f=s in r,p=t[s],m=v.isValidElement(p)&&!p.props.in;f&&(!d||m)?o[s]=v.cloneElement(c,{onExited:n.bind(null,c),in:!0,exit:il(c,"exit",e),enter:il(c,"enter",e)}):!f&&d&&!m?o[s]=v.cloneElement(c,{in:!1}):f&&d&&v.isValidElement(p)&&(o[s]=v.cloneElement(c,{onExited:n.bind(null,c),in:p.props.in,exit:il(c,"exit",e),enter:il(c,"enter",e)}))}}),o}var r8=Object.values||function(e){return Object.keys(e).map(function(t){return e[t]})},i8={component:"div",childFactory:function(t){return t}},ls=(function(e){TD(t,e);function t(r,o){var s;s=e.call(this,r,o)||this;var c=s.handleExited.bind(Z$(s));return s.state={contextValue:{isMounting:!0},handleExited:c,firstRender:!0},s}var n=t.prototype;return n.componentDidMount=function(){this.mounted=!0,this.setState({contextValue:{isMounting:!1}})},n.componentWillUnmount=function(){this.mounted=!1},t.getDerivedStateFromProps=function(o,s){var c=s.children,d=s.handleExited,f=s.firstRender;return{children:f?t8(o,d):n8(o,c,d),firstRender:!1}},n.handleExited=function(o,s){var c=Z0(this.props.children);o.key in c||(o.props.onExited&&o.props.onExited(s),this.mounted&&this.setState(function(d){var f=Tp({},d.children);return delete f[o.key],{children:f}}))},n.render=function(){var o=this.props,s=o.component,c=o.childFactory,d=S0(o,["component","childFactory"]),f=this.state.contextValue,p=r8(this.state.children).map(c);return delete d.appear,delete d.enter,delete d.exit,s===null?Mn.createElement(_p.Provider,{value:f},p):Mn.createElement(_p.Provider,{value:f},Mn.createElement(s,d,p))},t})(Mn.Component);ls.propTypes={};ls.defaultProps=i8;const RD=["bottom-center","bottom-left","bottom-right","top-center","top-left","top-right"];function o8(e,t){return e.reduce((n,r)=>(n[r.position||t].push(r),n),RD.reduce((n,r)=>(n[r]=[],n),{}))}const bT={left:"translateX(-100%)",right:"translateX(100%)","top-center":"translateY(-100%)","bottom-center":"translateY(100%)"},a8={left:"translateX(0)",right:"translateX(0)","top-center":"translateY(0)","bottom-center":"translateY(0)"};function s8({state:e,maxHeight:t,position:n,transitionDuration:r}){const[o,s]=n.split("-"),c=s==="center"?`${o}-center`:s,d={opacity:0,maxHeight:t,transform:bT[c],transitionDuration:`${r}ms, ${r}ms, ${r}ms`,transitionTimingFunction:"cubic-bezier(.51,.3,0,1.21), cubic-bezier(.51,.3,0,1.21), linear",transitionProperty:"opacity, transform, max-height"},f={opacity:1,transform:a8[c]},p={opacity:0,maxHeight:0,transform:bT[c]};return{...d,...{entering:f,entered:f,exiting:p,exited:p}[e]}}function l8(e,t){return typeof t=="number"?t:t===!1||e===!1?!1:e}const _D=v.forwardRef(({data:e,onHide:t,autoClose:n,...r},o)=>{const{autoClose:s,message:c,...d}=e,f=l8(n,e.autoClose),p=v.useRef(-1),m=()=>window.clearTimeout(p.current),g=()=>{t(e.id),m()},y=()=>{typeof f=="number"&&(p.current=window.setTimeout(g,f))};return v.useEffect(()=>{e.onOpen?.(e)},[]),v.useEffect(()=>(y(),m),[f]),a.jsx(M0,{...r,...d,onClose:g,ref:o,onMouseEnter:m,onMouseLeave:y,children:c})});_D.displayName="@mantine/notifications/NotificationContainer";var AD={root:"m_b37d9ac7",notification:"m_5ed0edd0"};const c8=Ta,u8={position:"bottom-right",autoClose:4e3,transitionDuration:250,containerWidth:440,notificationMaxHeight:200,limit:5,zIndex:zr("overlay"),store:Dl,withinPortal:!0},d8=(e,{zIndex:t,containerWidth:n})=>({root:{"--notifications-z-index":t?.toString(),"--notifications-container-width":le(n)}}),Ra=ge((e,t)=>{const n=ie("Notifications",u8,e),{classNames:r,className:o,style:s,styles:c,unstyled:d,vars:f,position:p,autoClose:m,transitionDuration:g,containerWidth:y,notificationMaxHeight:b,limit:S,zIndex:j,store:C,portalProps:R,withinPortal:E,...T}=n,_=gn(),k=q$(C),I=i4(),A=Sb(),P=v.useRef({}),z=v.useRef(0),Y=(_.respectReducedMotion?A:!1)?1:g,J=Le({name:"Notifications",classes:AD,props:n,className:o,style:s,classNames:r,styles:c,unstyled:d,vars:f,varsResolver:d8});v.useEffect(()=>{C?.updateState(Q=>({...Q,limit:S||5,defaultPosition:p}))},[S,p]),gs(()=>{k.notifications.length>z.current&&setTimeout(()=>I(),0),z.current=k.notifications.length},[k.notifications]);const Z=o8(k.notifications,p),$=RD.reduce((Q,M)=>(Q[M]=Z[M].map(({style:L,...U})=>a.jsx(c8,{timeout:Y,onEnter:()=>P.current[U.id].offsetHeight,nodeRef:{current:P.current[U.id]},children:V=>a.jsx(_D,{ref:K=>{K&&(P.current[U.id]=K)},data:U,onHide:K=>ED(K,C),autoClose:m,...J("notification",{style:{...s8({state:V,position:M,transitionDuration:Y,maxHeight:b}),...L}})})},U.id)),Q),{});return a.jsxs(va,{withinPortal:E,...R,children:[a.jsx(ce,{...J("root"),"data-position":"top-center",ref:t,...T,children:a.jsx(ls,{children:$["top-center"]})}),a.jsx(ce,{...J("root"),"data-position":"top-left",...T,children:a.jsx(ls,{children:$["top-left"]})}),a.jsx(ce,{...J("root",{className:dl.classNames.fullWidth}),"data-position":"top-right",...T,children:a.jsx(ls,{children:$["top-right"]})}),a.jsx(ce,{...J("root",{className:dl.classNames.fullWidth}),"data-position":"bottom-right",...T,children:a.jsx(ls,{children:$["bottom-right"]})}),a.jsx(ce,{...J("root"),"data-position":"bottom-left",...T,children:a.jsx(ls,{children:$["bottom-left"]})}),a.jsx(ce,{...J("root"),"data-position":"bottom-center",...T,children:a.jsx(ls,{children:$["bottom-center"]})})]})});Ra.classes=AD;Ra.displayName="@mantine/notifications/Notifications";Ra.show=Di.show;Ra.hide=Di.hide;Ra.update=Di.update;Ra.clean=Di.clean;Ra.cleanQueue=Di.cleanQueue;Ra.updateState=Di.updateState;class f8{operator;child;constructor(t,n){this.operator=t,this.child=n}toString(){return`${this.operator}(${this.child.toString()})`}}class sf{operator;left;right;constructor(t,n,r){this.operator=t,this.left=n,this.right=r}toString(){return`(${this.left.toString()} ${this.operator} ${this.right.toString()})`}}class h8{prefixParselets={};infixParselets={};registerInfix(t,n){return this.infixParselets[t]=n,this}registerPrefix(t,n){return this.prefixParselets[t]=n,this}prefix(t,n,r){return this.registerPrefix(t,{parse(o,s){const c=o.consumeAndParse(n);return r(s,c)}})}infixLeft(t,n,r){return this.registerInfix(t,{parse(o,s,c){const d=o.consumeAndParse(n);return r(s,c,d)},precedence:n})}construct(t){return new p8(t,this.prefixParselets,this.infixParselets)}}class p8{tokens;prefixParselets;infixParselets;constructor(t,n,r){this.tokens=t,this.prefixParselets=n,this.infixParselets=r}hasMore(){return this.tokens.length>0}match(t){return this.peek()?.id!==t?!1:(this.consume(),!0)}consumeAndParse(t=1/0){const n=this.consume(),r=this.prefixParselets[n.id];if(!r)throw Error(`Parse error at "${n.value}" (line ${n.line}, column ${n.column}). No matching prefix parselet.`);let o=r.parse(this,n);for(;t>this.getPrecedence();){const s=this.consume();o=this.getInfixParselet(s).parse(this,o,s)}return o}getPrecedence(){const t=this.peek();if(!t)return 1/0;const n=this.getInfixParselet(t);return n?n.precedence:1/0}consume(t,n){if(!this.tokens.length)throw Error("Cant consume unknown more tokens.");if(t&&this.peek()?.id!==t){const r=this.peek();throw Error(`Expected ${t} but got "${r.id}" (${r.value}) at line ${r.line} column ${r.column}.`)}if(n&&this.peek()?.value!==n){const r=this.peek();throw Error(`Expected "${n}" but got "${r.value}" at line ${r.line} column ${r.column}.`)}return this.tokens.shift()}peek(){return this.tokens.length>0?this.tokens[0]:void 0}removeComments(){this.tokens=this.tokens.filter(t=>t.id!=="Comment")}getInfixParselet(t){return this.infixParselets[t.id==="Symbol"?t.value:t.id]}}class DD{max;cache;constructor(t=10){this.max=t,this.cache=new Map}clear(){this.cache.clear()}get(t){const n=this.cache.get(t);return n&&(this.cache.delete(t),this.cache.set(t,n)),n}set(t,n){this.cache.has(t)?this.cache.delete(t):this.cache.size>=this.max&&this.cache.delete(this.first()),this.cache.set(t,n)}delete(t){this.cache.delete(t)}keys(){return this.cache.keys()}first(){return this.cache.keys().next().value}}const io="http://hl7.org",kD="ok",m8="created",g8="gone",v8="not-modified",y8="not-found",x8="unauthorized",b8="forbidden",S8="accepted",w8={resourceType:"OperationOutcome",id:kD,issue:[{severity:"information",code:"informational",details:{text:"All OK"}}]},j8={resourceType:"OperationOutcome",id:y8,issue:[{severity:"error",code:"not-found",details:{text:"Not found"}}]},Dd={resourceType:"OperationOutcome",id:x8,issue:[{severity:"error",code:"login",details:{text:"Unauthorized"}}]},C8={...Dd,issue:[...Dd.issue,{severity:"error",code:"expired",details:{text:"Token expired"}}]},ST={...Dd,issue:[...Dd.issue,{severity:"error",code:"invalid",details:{text:"Token not issued for this audience"}}]},lf={resourceType:"OperationOutcome",id:b8,issue:[{severity:"error",code:"forbidden",details:{text:"Forbidden"}}]};function Eo(e,t){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"invalid",details:{text:e},...t?{expression:[t]}:void 0}]}}function jn(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"structure",details:{text:e}}]}}function E8(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"exception",details:{text:"Internal server error"},diagnostics:e.toString()}]}}function T8(e){return!e||typeof e!="object"?!1:e instanceof Error||typeof DOMException<"u"&&e instanceof DOMException?!0:Object.prototype.toString.call(e)==="[object Error]"}function zm(e){return typeof e=="object"&&e!==null&&e.resourceType==="OperationOutcome"}function PD(e){return e.id===kD||e.id===m8||e.id===v8||e.id===S8}function R8(e){return e.id===g8}class vt extends Error{outcome;constructor(t,n){super(ND(t),n),this.name="OperationOutcomeError",this.outcome=t}}function Yt(e){return e instanceof vt?e.outcome:zm(e)?e:Eo(Qe(e))}function Qe(e){return e?typeof e=="string"?e:T8(e)?e.message:zm(e)?ND(e):typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:JSON.stringify(e):"Unknown error"}function ND(e){const t=e.issue?.map(OD)??[];return t.length>0?t.join("; "):"Unknown error"}function OD(e){let t;return e.details?.text?e.diagnostics?t=`${e.details.text} (${e.diagnostics})`:t=e.details.text:e.diagnostics?t=e.diagnostics:t="Unknown error",e.expression?.length&&(t+=` (${e.expression.join(", ")})`),t}function _8(e,t){const n=t.max&&t.max===Number.MAX_SAFE_INTEGER?Number.POSITIVE_INFINITY:t.max;return{path:e,description:"",type:t.type??[],min:t.min??0,max:n??1,isArray:!!n&&n>1,constraints:[]}}function A8(e){const t=Object.create(null);for(const[n,r]of Object.entries(e))t[n]={name:n,type:n,path:n,elements:Object.fromEntries(Object.entries(r.elements).map(([o,s])=>[o,_8(o,s)])),constraints:[],innerTypes:[]};return t}const D8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]}}},k8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]}}},P8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},type:{type:[{code:"code"}]},text:{type:[{code:"string"}]},line:{max:9007199254740991,type:[{code:"string"}]},city:{type:[{code:"string"}]},district:{type:[{code:"string"}]},state:{type:[{code:"string"}]},postalCode:{type:[{code:"string"}]},country:{type:[{code:"string"}]},period:{type:[{code:"Period"}]}}},N8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},O8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},"author[x]":{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Organization"]},{code:"string"}]},time:{type:[{code:"dateTime"}]},text:{min:1,type:[{code:"markdown"}]}}},M8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},contentType:{type:[{code:"code"}]},language:{type:[{code:"code"}]},data:{type:[{code:"base64Binary"}]},url:{type:[{code:"url"}]},size:{type:[{code:"unsignedInt"}]},hash:{type:[{code:"base64Binary"}]},title:{type:[{code:"string"}]},creation:{type:[{code:"dateTime"}]}}},L8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},coding:{max:9007199254740991,type:[{code:"Coding"}]},text:{type:[{code:"string"}]}}},I8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},system:{type:[{code:"uri"}]},version:{type:[{code:"string"}]},code:{type:[{code:"code"}]},display:{type:[{code:"string"}]},userSelected:{type:[{code:"boolean"}]}}},z8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},name:{type:[{code:"string"}]},telecom:{max:9007199254740991,type:[{code:"ContactPoint"}]}}},$8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},system:{type:[{code:"code"}]},value:{type:[{code:"string"}]},use:{type:[{code:"code"}]},rank:{type:[{code:"positiveInt"}]},period:{type:[{code:"Period"}]}}},U8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},name:{min:1,type:[{code:"string"}]},contact:{max:9007199254740991,type:[{code:"ContactDetail"}]}}},B8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},V8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},profile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]},"subject[x]":{type:[{code:"CodeableConcept"},{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Group"]}]},mustSupport:{max:9007199254740991,type:[{code:"string"}]},codeFilter:{max:9007199254740991,type:[{code:"DataRequirementCodeFilter"}]},dateFilter:{max:9007199254740991,type:[{code:"DataRequirementDateFilter"}]},limit:{type:[{code:"positiveInt"}]},sort:{max:9007199254740991,type:[{code:"DataRequirementSort"}]}}},F8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},valueSet:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/ValueSet"]}]},code:{max:9007199254740991,type:[{code:"Coding"}]}}},H8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},"value[x]":{type:[{code:"dateTime"},{code:"Period"},{code:"Duration"}]}}},q8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},direction:{min:1,type:[{code:"code"}]}}},G8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Q8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},sequence:{type:[{code:"integer"}]},text:{type:[{code:"string"}]},additionalInstruction:{max:9007199254740991,type:[{code:"CodeableConcept"}]},patientInstruction:{type:[{code:"string"}]},timing:{type:[{code:"Timing"}]},"asNeeded[x]":{type:[{code:"boolean"},{code:"CodeableConcept"}]},site:{type:[{code:"CodeableConcept"}]},route:{type:[{code:"CodeableConcept"}]},method:{type:[{code:"CodeableConcept"}]},doseAndRate:{max:9007199254740991,type:[{code:"DosageDoseAndRate"}]},maxDosePerPeriod:{type:[{code:"Ratio"}]},maxDosePerAdministration:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},maxDosePerLifetime:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},W8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{type:[{code:"CodeableConcept"}]},"dose[x]":{type:[{code:"Range"},{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},"rate[x]":{type:[{code:"Ratio"},{code:"Range"},{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},Y8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},K8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},representation:{max:9007199254740991,type:[{code:"code"}]},sliceName:{type:[{code:"string"}]},sliceIsConstraining:{type:[{code:"boolean"}]},label:{type:[{code:"string"}]},code:{max:9007199254740991,type:[{code:"Coding"}]},slicing:{type:[{code:"ElementDefinitionSlicing"}]},short:{type:[{code:"string"}]},definition:{type:[{code:"markdown"}]},comment:{type:[{code:"markdown"}]},requirements:{type:[{code:"markdown"}]},alias:{max:9007199254740991,type:[{code:"string"}]},min:{type:[{code:"unsignedInt"}]},max:{type:[{code:"string"}]},base:{type:[{code:"ElementDefinitionBase"}]},contentReference:{type:[{code:"uri"}]},type:{max:9007199254740991,type:[{code:"ElementDefinitionType"}]},"defaultValue[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},meaningWhenMissing:{type:[{code:"markdown"}]},orderMeaning:{type:[{code:"string"}]},"fixed[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},"pattern[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},example:{max:9007199254740991,type:[{code:"ElementDefinitionExample"}]},"minValue[x]":{type:[{code:"date"},{code:"dateTime"},{code:"instant"},{code:"time"},{code:"decimal"},{code:"integer"},{code:"positiveInt"},{code:"unsignedInt"},{code:"Quantity"}]},"maxValue[x]":{type:[{code:"date"},{code:"dateTime"},{code:"instant"},{code:"time"},{code:"decimal"},{code:"integer"},{code:"positiveInt"},{code:"unsignedInt"},{code:"Quantity"}]},maxLength:{type:[{code:"integer"}]},condition:{max:9007199254740991,type:[{code:"id"}]},constraint:{max:9007199254740991,type:[{code:"ElementDefinitionConstraint"}]},mustSupport:{type:[{code:"boolean"}]},isModifier:{type:[{code:"boolean"}]},isModifierReason:{type:[{code:"string"}]},isSummary:{type:[{code:"boolean"}]},binding:{type:[{code:"ElementDefinitionBinding"}]},mapping:{max:9007199254740991,type:[{code:"ElementDefinitionMapping"}]}}},X8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},path:{min:1,type:[{code:"string"}]}}},J8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},discriminator:{max:9007199254740991,type:[{code:"ElementDefinitionSlicingDiscriminator"}]},description:{type:[{code:"string"}]},ordered:{type:[{code:"boolean"}]},rules:{min:1,type:[{code:"code"}]}}},Z8={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},min:{min:1,type:[{code:"unsignedInt"}]},max:{min:1,type:[{code:"string"}]}}},eU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},code:{min:1,type:[{code:"uri"}]},profile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},targetProfile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},aggregation:{max:9007199254740991,type:[{code:"code"}]},versioning:{type:[{code:"code"}]}}},tU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},label:{min:1,type:[{code:"string"}]},"value[x]":{min:1,type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]}}},nU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},key:{min:1,type:[{code:"id"}]},requirements:{type:[{code:"string"}]},severity:{min:1,type:[{code:"code"}]},human:{min:1,type:[{code:"string"}]},expression:{type:[{code:"string"}]},xpath:{type:[{code:"string"}]},source:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]}}},rU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},strength:{min:1,type:[{code:"code"}]},description:{type:[{code:"string"}]},valueSet:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/ValueSet"]}]}}},iU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},identity:{min:1,type:[{code:"id"}]},language:{type:[{code:"code"}]},map:{min:1,type:[{code:"string"}]},comment:{type:[{code:"string"}]}}},oU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},description:{type:[{code:"string"}]},name:{type:[{code:"id"}]},language:{min:1,type:[{code:"code"}]},expression:{type:[{code:"string"}]},reference:{type:[{code:"uri"}]}}},aU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},url:{min:1,type:[{code:"uri"}]},"value[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]}}},sU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},text:{type:[{code:"string"}]},family:{type:[{code:"string"}]},given:{max:9007199254740991,type:[{code:"string"}]},prefix:{max:9007199254740991,type:[{code:"string"}]},suffix:{max:9007199254740991,type:[{code:"string"}]},period:{type:[{code:"Period"}]}}},lU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},type:{type:[{code:"CodeableConcept"}]},system:{type:[{code:"uri"}]},value:{type:[{code:"string"}]},period:{type:[{code:"Period"}]},assigner:{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Organization"]}]}}},cU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},country:{min:1,type:[{code:"CodeableConcept"}]},jurisdiction:{type:[{code:"CodeableConcept"}]},status:{min:1,type:[{code:"CodeableConcept"}]},dateRange:{min:1,type:[{code:"Period"}]},restoreDate:{type:[{code:"dateTime"}]}}},uU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},versionId:{type:[{code:"id"}]},lastUpdated:{type:[{code:"instant"}]},source:{type:[{code:"uri"}]},profile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]},security:{max:9007199254740991,type:[{code:"Coding"}]},tag:{max:9007199254740991,type:[{code:"Coding"}]},project:{type:[{code:"uri"}]},author:{type:[{code:"Reference"}]},onBehalfOf:{type:[{code:"Reference"}]},account:{type:[{code:"Reference"}]},accounts:{max:9007199254740991,type:[{code:"Reference"}]},compartment:{max:9007199254740991,type:[{code:"Reference"}]}}},dU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},currency:{type:[{code:"code"}]}}},fU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},status:{min:1,type:[{code:"code"}]},div:{min:1,type:[{code:"xhtml"}]}}},hU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},name:{type:[{code:"code"}]},use:{min:1,type:[{code:"code"}]},min:{type:[{code:"integer"}]},max:{type:[{code:"string"}]},documentation:{type:[{code:"string"}]},type:{min:1,type:[{code:"code"}]},profile:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]}}},pU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},start:{type:[{code:"dateTime"}]},end:{type:[{code:"dateTime"}]}}},mU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},"age[x]":{type:[{code:"Range"},{code:"CodeableConcept"}]},gender:{type:[{code:"CodeableConcept"}]},race:{type:[{code:"CodeableConcept"}]},physiologicalCondition:{type:[{code:"CodeableConcept"}]}}},gU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},height:{type:[{code:"Quantity"}]},width:{type:[{code:"Quantity"}]},depth:{type:[{code:"Quantity"}]},weight:{type:[{code:"Quantity"}]},nominalVolume:{type:[{code:"Quantity"}]},externalDiameter:{type:[{code:"Quantity"}]},shape:{type:[{code:"string"}]},color:{max:9007199254740991,type:[{code:"string"}]},imprint:{max:9007199254740991,type:[{code:"string"}]},image:{max:9007199254740991,type:[{code:"Attachment"}]},scoring:{type:[{code:"CodeableConcept"}]}}},vU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},identifier:{type:[{code:"Identifier"}]},type:{min:1,type:[{code:"CodeableConcept"}]},period:{min:1,type:[{code:"Quantity"}]},specialPrecautionsForStorage:{max:9007199254740991,type:[{code:"CodeableConcept"}]}}},yU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},xU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},low:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},high:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},bU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},numerator:{type:[{code:"Quantity"}]},denominator:{type:[{code:"Quantity"}]}}},SU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},reference:{type:[{code:"string"}]},type:{type:[{code:"uri"}]},identifier:{type:[{code:"Identifier"}]},display:{type:[{code:"string"}]}}},wU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},label:{type:[{code:"string"}]},display:{type:[{code:"string"}]},citation:{type:[{code:"markdown"}]},url:{type:[{code:"url"}]},document:{type:[{code:"Attachment"}]},resource:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/Resource"]}]}}},jU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},origin:{min:1,type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},period:{min:1,type:[{code:"decimal"}]},factor:{type:[{code:"decimal"}]},lowerLimit:{type:[{code:"decimal"}]},upperLimit:{type:[{code:"decimal"}]},dimensions:{min:1,type:[{code:"positiveInt"}]},data:{type:[{code:"string"}]}}},CU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,max:9007199254740991,type:[{code:"Coding"}]},when:{min:1,type:[{code:"instant"}]},who:{min:1,type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/PractitionerRole","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/Device","http://hl7.org/fhir/StructureDefinition/Organization"]}]},onBehalfOf:{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/PractitionerRole","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/Device","http://hl7.org/fhir/StructureDefinition/Organization"]}]},targetFormat:{type:[{code:"code"}]},sigFormat:{type:[{code:"code"}]},data:{type:[{code:"base64Binary"}]}}},EU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},"amount[x]":{type:[{code:"Quantity"},{code:"Range"},{code:"string"}]},amountType:{type:[{code:"CodeableConcept"}]},amountText:{type:[{code:"string"}]},referenceRange:{type:[{code:"SubstanceAmountReferenceRange"}]}}},TU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},lowLimit:{type:[{code:"Quantity"}]},highLimit:{type:[{code:"Quantity"}]}}},RU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},event:{max:9007199254740991,type:[{code:"dateTime"}]},repeat:{type:[{code:"TimingRepeat"}]},code:{type:[{code:"CodeableConcept"}]}}},_U={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},"bounds[x]":{type:[{code:"Duration"},{code:"Range"},{code:"Period"}]},count:{type:[{code:"positiveInt"}]},countMax:{type:[{code:"positiveInt"}]},duration:{type:[{code:"decimal"}]},durationMax:{type:[{code:"decimal"}]},durationUnit:{type:[{code:"code"}]},frequency:{type:[{code:"positiveInt"}]},frequencyMax:{type:[{code:"positiveInt"}]},period:{type:[{code:"decimal"}]},periodMax:{type:[{code:"decimal"}]},periodUnit:{type:[{code:"code"}]},dayOfWeek:{max:9007199254740991,type:[{code:"code"}]},timeOfDay:{max:9007199254740991,type:[{code:"time"}]},when:{max:9007199254740991,type:[{code:"code"}]},offset:{type:[{code:"unsignedInt"}]}}},AU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},name:{type:[{code:"string"}]},"timing[x]":{type:[{code:"Timing"},{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Schedule"]},{code:"date"},{code:"dateTime"}]},data:{max:9007199254740991,type:[{code:"DataRequirement"}]},condition:{type:[{code:"Expression"}]}}},DU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},code:{min:1,type:[{code:"Coding"}]},"value[x]":{min:1,type:[{code:"CodeableConcept"},{code:"Quantity"},{code:"Range"},{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/PlanDefinition","http://hl7.org/fhir/StructureDefinition/ResearchStudy","http://hl7.org/fhir/StructureDefinition/InsurancePlan","http://hl7.org/fhir/StructureDefinition/HealthcareService","http://hl7.org/fhir/StructureDefinition/Group","http://hl7.org/fhir/StructureDefinition/Location","http://hl7.org/fhir/StructureDefinition/Organization"]}]}}},kU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},PU={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{max:0,type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},NU={elements:{authorizeUrl:{min:1,type:[{code:"string"}]},tokenUrl:{min:1,type:[{code:"string"}]},tokenAuthMethod:{type:[{code:"code"}]},userInfoUrl:{min:1,type:[{code:"string"}]},clientId:{min:1,type:[{code:"string"}]},clientSecret:{min:1,type:[{code:"string"}]},usePkce:{type:[{code:"boolean"}]},useSubject:{type:[{code:"boolean"}]}}},OU={Element:D8,BackboneElement:k8,Address:P8,Age:N8,Annotation:O8,Attachment:M8,CodeableConcept:L8,Coding:I8,ContactDetail:z8,ContactPoint:$8,Contributor:U8,Count:B8,DataRequirement:V8,DataRequirementCodeFilter:F8,DataRequirementDateFilter:H8,DataRequirementSort:q8,Distance:G8,Dosage:Q8,DosageDoseAndRate:W8,Duration:Y8,ElementDefinition:K8,ElementDefinitionSlicingDiscriminator:X8,ElementDefinitionSlicing:J8,ElementDefinitionBase:Z8,ElementDefinitionType:eU,ElementDefinitionExample:tU,ElementDefinitionConstraint:nU,ElementDefinitionBinding:rU,ElementDefinitionMapping:iU,Expression:oU,Extension:aU,HumanName:sU,Identifier:lU,MarketingStatus:cU,Meta:uU,Money:dU,Narrative:fU,ParameterDefinition:hU,Period:pU,Population:mU,ProdCharacteristic:gU,ProductShelfLife:vU,Quantity:yU,Range:xU,Ratio:bU,Reference:SU,RelatedArtifact:wU,SampledData:jU,Signature:CU,SubstanceAmount:EU,SubstanceAmountReferenceRange:TU,Timing:RU,TimingRepeat:_U,TriggerDefinition:AU,UsageContext:DU,MoneyQuantity:kU,SimpleQuantity:PU,IdentityProvider:NU};function MU(e){return new IU(e).parse()}const Ap=A8(OU),eS=Object.create(null),wT=Object.create(null),LU={"http://hl7.org/fhir/StructureDefinition/MoneyQuantity":"MoneyQuantity","http://hl7.org/fhir/StructureDefinition/SimpleQuantity":"SimpleQuantity","http://hl7.org/fhir/uv/sql-on-fhir/StructureDefinition/ViewDefinition":"ViewDefinition"};function MD(e){let t;return t=wT[e],t||(t=wT[e]=Object.create(null)),t}function jT(e){const n=(Array.isArray(e)?e:e.entry?.map(r=>r.resource)??[]).filter(r=>r?.resourceType==="StructureDefinition");TB(n);for(const r of n)LD(r)}function LD(e){if(!e?.name)throw new Error("Failed loading StructureDefinition from bundle");if(e.resourceType!=="StructureDefinition")return;const t=MU(e),n=LU[e.url];let r,o;n?(r=Ap,o=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=Ap,o=e.type):(r=MD(e.url),o=e.type),r[o]=t;for(const s of t.innerTypes)s.parentType=t,r[s.name]=s;eS[e.url]=t}function ID(e){return!!Ap[e]}function $m(e,t){if(t){const n=MD(t)[e];if(n)return n}return Ap[e]}function zD(e,t){const n=$m(e,t);if(!n)throw new vt(Eo("Unknown data type: "+e));return n}function tS(e){return!!eS[e]}function uu(e){return eS[e]}class IU{root;elements;elementIndex;index;resourceSchema;slicingContext;innerTypes;backboneContext;constructor(t){if(!t.snapshot?.element||t.snapshot.element.length===0)throw new Error(`No snapshot defined for StructureDefinition '${t.name}'`);this.root=t.snapshot.element[0],this.elements=t.snapshot.element.slice(1),this.elementIndex=Object.create(null),this.index=0,this.resourceSchema={name:t.name,path:this.root.path,title:t.title,type:t.type,url:t.url,version:t.version,kind:t.kind,description:UU(t),elements:{},constraints:this.parseElementDefinition(this.root).constraints,innerTypes:[],summaryProperties:new Set,mandatoryProperties:new Set},this.innerTypes=[]}parse(){let t=this.next();for(;t;){if(t.sliceName)this.parseSliceStart(t);else if(t.id?.includes(":")){if(this.slicingContext?.current){const n=Wy(t,this.slicingContext.path);this.slicingContext.current.elements[n]=this.parseElementDefinition(t)}}else{const n=this.parseElementDefinition(t);this.checkFieldEnter(t,n);let r=this.backboneContext;for(;r;){if(t.path?.startsWith(r.path+".")){r.type.elements[Wy(t,r.path)]=n;break}r=r.parent}if(!r){const o=Wy(t,this.root.path);t.isSummary&&this.resourceSchema.summaryProperties?.add(o.replace("[x]","")),n.min>0&&this.resourceSchema.mandatoryProperties?.add(o.replace("[x]","")),this.resourceSchema.elements[o]=n}this.checkFieldExit(t)}t=this.next()}return this.checkFieldExit(),this.innerTypes.length>0&&(this.resourceSchema.innerTypes=this.innerTypes),this.resourceSchema}checkFieldEnter(t,n){this.isInnerType(t)&&this.enterInnerType(t),this.slicingContext&&!jc(this.slicingContext.path,t?.path)&&(this.slicingContext=void 0),t.slicing&&!this.slicingContext&&this.enterSlice(t,n)}enterInnerType(t){for(;this.backboneContext&&!jc(this.backboneContext?.path,t.path);)this.innerTypes.push(this.backboneContext.type),this.backboneContext=this.backboneContext.parent;const n=kT(t);this.backboneContext={type:{name:n,type:n,path:t.path,title:t.label,description:t.definition,elements:{},constraints:this.parseElementDefinition(t).constraints,innerTypes:[]},path:t.path,parent:jc(this.backboneContext?.path,t.path)?this.backboneContext:this.backboneContext?.parent}}enterSlice(t,n){$U(t)&&!this.peek()?.sliceName||(n.slicing={discriminator:(t.slicing?.discriminator??[]).map(r=>{if(r.type!=="value"&&r.type!=="pattern"&&r.type!=="type")throw new Error(`Unsupported slicing discriminator type: ${r.type}`);return{path:r.path,type:r.type}}),slices:[],ordered:t.slicing?.ordered??!1,rule:t.slicing?.rules},this.slicingContext={field:n.slicing,path:t.path??""})}checkFieldExit(t=void 0){if(this.backboneContext&&!jc(this.backboneContext.path,t?.path))if(this.backboneContext.parent)do this.innerTypes.push(this.backboneContext.type),this.backboneContext=this.backboneContext.parent;while(this.backboneContext&&!jc(this.backboneContext.path,t?.path));else this.innerTypes.push(this.backboneContext.type),this.backboneContext=void 0}next(){const t=this.peek();if(t)return this.index++,t}peek(){const t=this.elements[this.index];if(t){if(this.elementIndex[t.path??""]=t,t.contentReference){const n=t.contentReference.slice(t.contentReference.indexOf("#")+1),r=this.elementIndex[n];return r?{...r,id:t.id,path:t.path,min:t.min??r.min,max:t.max??r.max,base:{path:r.base?.path??n,min:t.base?.min??r.base?.min??r.min,max:t.base?.max??r.base?.max??r.max},contentReference:t.contentReference,definition:t.definition}:void 0}return t}}isInnerType(t){const n=this.peek();return!!(jc(t?.path,n?.path)&&t.type?.some(r=>["BackboneElement","Element"].includes(r.code)))}parseSliceStart(t){if(!this.slicingContext)throw new Error(`Invalid slice start before discriminator: ${t.sliceName} (${t.id})`);this.slicingContext.current={...this.parseElementDefinition(t),name:t.sliceName??"",definition:t.definition,elements:{}},this.slicingContext.field.slices.push(this.slicingContext.current)}parseElementDefinitionType(t){return(t.type??[]).map(n=>{let r;return(n.code==="BackboneElement"||n.code==="Element")&&(r=kT(t)),r||(r=Uo(n,"http://hl7.org/fhir/StructureDefinition/structuredefinition-fhir-type")?.valueUrl),r||(r=n.code??""),{code:r,targetProfile:n.targetProfile,profile:n.profile}})}parseElementDefinition(t){const n=CT(t.max),r=t.base?.max?CT(t.base.max):n,o={type:"ElementDefinition",value:t};return{description:t.definition||"",path:t.path||t.base?.path||"",min:t.min??0,max:n,isArray:r>1,constraints:(t.constraint??[]).map(s=>({key:s.key??"",severity:s.severity??"error",expression:s.expression??"",description:s.human??""})),type:this.parseElementDefinitionType(t),fixed:ET(kd(o,"fixed[x]")),pattern:ET(kd(o,"pattern[x]")),binding:t.binding}}}function CT(e){return e==="*"?Number.POSITIVE_INFINITY:Number.parseInt(e,10)}function Wy(e,t=""){return zU(e.path,t)}function zU(e,t){return e?t&&e.startsWith(t)?e.substring(t.length+1):e:""}function jc(e,t){return!e||!t?!1:t.startsWith(e+".")||t===e}function ET(e){return Array.isArray(e)&&e.length>0?e[0]:Cn(e)?void 0:e}function $U(e){const t=e.slicing?.discriminator;return!!(e.type?.some(n=>n.code==="Extension")&&t?.length===1&&t[0].type==="value"&&t[0].path==="url")}function UU(e){let t=e.description;return t?.startsWith(`Base StructureDefinition for ${e.name} Type: `)&&(t=t.substring(`Base StructureDefinition for ${e.name} Type: `.length)),t}function BU(e,t,n){if(e===void 0)return[void 0];if(t==="$this")return[e];const r=n?.withPath?$D:kd,[o,...s]=t.split(".");let c=[r(e,o,n)];for(const d of s){const f=[];for(const p of c)if(Array.isArray(p))for(const m of p)f.push(r(m,d,n));else(n?.withPath&&p?.value!==void 0||!n?.withPath&&p!==void 0)&&f.push(r(p,d,n));c=f}return c}function $D(e,t,n){const r=e.path;return VU(kd(e,t,n),r,t)}function VU(e,t,n){const r=t?t+".":"";return e===void 0?{type:"undefined",value:void 0,path:`${r}${n}`}:Array.isArray(e)?e.map((o,s)=>({...o,path:`${r}${n}[${s}]`})):{...e,path:`${r}${n}`}}const UD={date:/^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2]\d|3[0-1]))?)?$/,dateTime:/^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2]\d|3[0-1])(T([01]\d|2[0-3])(:[0-5]\d:([0-5]\d|60)(\.\d{1,9})?)?)?)?(Z|[+-]((0\d|1[0-3]):[0-5]\d|14:00)?)?)?$/};function FU(e,t,n,r){if(Array.isArray(e))return!1;let o;t.path==="$this"?o=n:o=(r??n.elements)[t.path];const s=n.type;switch(t.type){case"value":case"pattern":if(!e||!o)return!1;if(o.pattern)return iS(e,o.pattern);if(o.fixed)return ko(e,o.fixed);if(o.binding?.strength==="required"&&o.binding.valueSet)return!0;break;case"type":return!e||!s?.length?!1:s.some(c=>c.code===e.type)}return!1}function Ze(e){return[{type:ne.boolean,value:e}]}function fi(e){return e==null?{type:"undefined",value:void 0}:Number.isSafeInteger(e)?{type:ne.integer,value:e}:typeof e=="number"?{type:ne.decimal,value:e}:typeof e=="boolean"?{type:ne.boolean,value:e}:typeof e=="string"?{type:ne.string,value:e}:ki(e)?{type:ne.Quantity,value:e}:Bo(e)?{type:e.resourceType,value:e}:JD(e)?{type:ne.CodeableConcept,value:e}:XD(e)?{type:ne.Coding,value:e}:{type:ne.BackboneElement,value:e}}function wo(e){return e.length===0?!1:!!e[0].value}function xa(e,t){if(e.length!==0){if(e.length===1&&(!t||e[0].type===t))return e[0];throw new Error(`Expected singleton of type ${t}, but found ${JSON.stringify(e)}`)}}function kd(e,t,n){if(!e.value)return;const r=_s(e.type,t,n?.profileUrl);return r?BD(e,t,r):cf(e,t)}function BD(e,t,n){const r=e.value,o=n.type;if(!o||o.length===0)return;let s,c="undefined",d;const f=n.path.lastIndexOf("."),p=n.path.substring(f+1);for(const m of o){const g=p.replace("[x]",Wn(m.code));if(s=r[g],d=r["_"+g],s!==void 0||d!==void 0){c=m.code;break}}if(d)if(Array.isArray(s)){s=s.slice();for(let m=0;m<Math.max(s.length,d.length);m++)s[m]=Yy(s[m],d[m])}else if(!s&&Array.isArray(d)){s=d.slice();for(let m=0;m<d.length;m++)s[m]=Yy(void 0,d[m])}else s=Yy(s,d);if(!Cn(s))return(c==="Element"||c==="BackboneElement")&&(c=n.type[0].code),Array.isArray(s)?s.map(m=>TT(m,c)):TT(s,c)}function TT(e,t){return t==="Resource"&&Bo(e)&&(t=e.resourceType),{type:t,value:e}}function cf(e,t){const n=e.value;if(!n||typeof n!="object")return;let r;if(t in n){const o=n[t];Array.isArray(o)?r=o.map(fi):r=fi(o)}else{const o=t.endsWith("[x]")?t.substring(0,t.length-3):t;for(const s of Object.values(ne)){const c=o+Wn(s);if(c in n){const d=n[c];Array.isArray(d)?r=d.map(f=>({type:s,value:f})):r={type:s,value:d};break}}}if(Array.isArray(r)){if(r.length===0||Cn(r[0]))return}else if(Cn(r))return;return r}function VD(e){const t=[];for(const n of e){let r=!1;for(const o of t)if(wo(Um(n,o))){r=!0;break}r||t.push(n)}return t}function HU(e){return Ze(!wo(e))}function qU(e,t){return e.length===0||t.length===0?[]:e.length!==t.length?Ze(!1):Ze(e.every((n,r)=>wo(Um(n,t[r]))))}function GU(e,t){return e.length===0||t.length===0?[]:e.length!==t.length?Ze(!0):Ze(e.some((n,r)=>!wo(Um(n,t[r]))))}function Um(e,t){const n=e.value?.valueOf(),r=t.value?.valueOf();return typeof n=="number"&&typeof r=="number"?Ze(Math.abs(n-r)<1e-8):ki(n)&&ki(r)?Ze(WD(n,r)):Ze(typeof n=="object"&&typeof r=="object"?nS(e,t):n===r)}function FD(e,t){return e.length===0&&t.length===0?Ze(!0):e.length!==t.length?Ze(!1):(e.sort(RT),t.sort(RT),Ze(e.every((n,r)=>wo(QU(n,t[r])))))}function QU(e,t){const{type:n,value:r}=e,{type:o,value:s}=t,c=r?.valueOf(),d=s?.valueOf();return typeof c=="number"&&typeof d=="number"?Ze(Math.abs(c-d)<.01):ki(c)&&ki(d)?Ze(WD(c,d)):Ze(n==="Coding"&&o==="Coding"?typeof c!="object"||typeof d!="object"?!1:c.code===d.code&&c.system===d.system:typeof c=="object"&&typeof d=="object"?nS({...c,id:void 0},{...d,id:void 0}):typeof c=="string"&&typeof d=="string"?c.toLowerCase()===d.toLowerCase():c===d)}function RT(e,t){const n=e.value?.valueOf(),r=t.value?.valueOf();return typeof n=="number"&&typeof r=="number"?n-r:typeof n=="string"&&typeof r=="string"?n.localeCompare(r):0}function HD(e,t){const{value:n}=e;if(n==null)return!1;let r=t;switch(r.startsWith("System.")&&(r=r.substring(7)),r.startsWith("FHIR.")&&(r=r.substring(5)),r){case"Boolean":return typeof n=="boolean";case"Decimal":case"Integer":return typeof n=="number";case"Date":return qD(n);case"DateTime":return Pd(n);case"Time":return typeof n=="string"&&!!/^T\d/.exec(n);case"Period":return GD(n);case"Quantity":return ki(n);default:return e.type===r||typeof n=="object"&&n?.resourceType===r}}function qD(e){return typeof e=="string"&&!!UD.date.exec(e)}function Pd(e){return typeof e=="string"&&!!UD.dateTime.exec(e)}function GD(e){return!!(e&&typeof e=="object"&&("start"in e&&Pd(e.start)||"end"in e&&Pd(e.end)))}function QD(e){if(e){if(qD(e)||Pd(e))return{start:Qh(e,"0000-01-01T00:00:00.000"),end:Qh(e,"xxxx-12-31T23:59:59.999")};if(GD(e))return{start:e.start?Qh(e.start,"0000-01-01T00:00:00.000"):void 0,end:e.end?Qh(e.end,"xxxx-12-31T23:59:59.999"):void 0}}}function Qh(e,t){let n="Z";const r=Math.max(e.indexOf("+",10),e.indexOf("-",10));r>-1?(n=e.substring(r),e=e.substring(0,r)):e.endsWith("Z")&&(e=e.substring(0,e.length-1));const o=e+t.substring(e.length)+n;return new Date(o).toISOString()}function ki(e){return!!(e&&typeof e=="object"&&"value"in e&&typeof e.value=="number")}function WD(e,t){return Math.abs(e.value-t.value)<.01&&(e.unit===t.unit||e.code===t.code||e.unit===t.code||e.code===t.unit)}function nS(e,t){const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const s=e[o],c=t[o];if(_T(s)&&_T(c)){if(!nS(s,c))return!1}else if(s!==c)return!1}return!0}function _T(e){return e!==null&&typeof e=="object"}function Yy(e,t){if(t){if(typeof t!="object")throw new Error("Primitive extension must be an object");return WU(e??{},t)}return e}function WU(e,t){return delete t.__proto__,delete t.constructor,Object.assign(e,t)}function YD(e,t){return Bo(e,t)&&"id"in e&&typeof e.id=="string"}function Qt(e){const t=Ot(e)??"undefined/undefined",n=ba(e);return n===t?{reference:t}:{reference:t,display:n}}function Ot(e){if(_a(e))return e.reference;if(YD(e))return`${e.resourceType}/${e.id}`}function pl(e){if(e)return _a(e)?e.reference.split("/")[1]:e.id}function YU(e){return e.resourceType==="Patient"||e.resourceType==="Practitioner"||e.resourceType==="RelatedPerson"}function ba(e){if(YU(e)){const t=KU(e);if(t)return t}if(e.resourceType==="Device"){const t=XU(e);if(t)return t}if(e.resourceType==="MedicationRequest"&&e.medicationCodeableConcept)return xs(e.medicationCodeableConcept);if(e.resourceType==="Subscription"&&e.criteria)return e.criteria;if(e.resourceType==="User"&&e.email)return e.email;if("name"in e&&e.name&&typeof e.name=="string")return e.name;if("code"in e&&e.code){let t=e.code;if(Array.isArray(t)&&(t=t[0]),JD(t))return xs(t);if(lB(t))return t.text}return Ot(e)??""}function KU(e){const t=e.name;if(t&&t.length>0)return Rs(t[0])}function XU(e){const t=e.deviceName;if(t&&t.length>0)return t[0].name}function JU(e){if(!("photo"in e))return;const t=e.photo;if(t)if(Array.isArray(t))for(const n of t){const r=AT(n);if(r)return r}else return AT(t)}function AT(e){if(e.url&&e.contentType?.startsWith("image/"))return e.url}function KD(e,t){const n=new Date(e);n.setUTCHours(0,0,0,0);const r=t?new Date(t):new Date;r.setUTCHours(0,0,0,0);const o=n.getUTCFullYear(),s=n.getUTCMonth(),c=n.getUTCDate(),d=r.getUTCFullYear(),f=r.getUTCMonth(),p=r.getUTCDate();let m=d-o;(f<s||f===s&&p<c)&&m--;let g=d*12+f-(o*12+s);p<c&&g--;const y=Math.floor((r.getTime()-n.getTime())/(1e3*60*60*24));return{years:m,months:g,days:y}}function ZU(e,t){const{years:n,months:r,days:o}=KD(e,t);return n>=2?n.toString().padStart(3,"0")+"Y":r>=1?r.toString().padStart(3,"0")+"M":o.toString().padStart(3,"0")+"D"}function Uo(e,...t){let n=e;for(let r=0;r<t.length&&n;r++)n=n?.extension?.find(o=>o.url===t[r]);return n}function no(e,t){const n=rS(e);return JSON.stringify(n,null,t?2:void 0)??""}function rS(e){if(!(e==null||e===""))return typeof e=="object"?Array.isArray(e)?eB(e):tB(e):e}function eB(e){const t=e.length;if(t===0)return;let n,r=0;for(let o=0;o<t;o++){const s=e[o],c=rS(s);c!==s&&!n&&(n=Array.from(e)),c===void 0?n&&(n[o]=null):(n&&(n[o]=c),r++)}if(r!==0)return n??e}function tB(e){let t,n=0;for(const r in e){const o=e[r],s=rS(o);s!==o&&!t&&(t={...e}),s===void 0?t&&delete t[r]:(t&&(t[r]=s),n++)}if(n!==0)return t??e}function Cn(e){if(e==null)return!0;const t=typeof e;return t==="string"||t==="object"?!Ln(e):!1}function Ln(e){if(e==null)return!1;const t=typeof e;return t==="string"&&e!==""||t==="object"&&("length"in e&&e.length>0||Object.keys(e).length>0)}function nB(e){if(!e)return;let t=e.length-1;for(;t>=0&&Cn(e[t]);)t--;return t>=0?e.slice(0,t+1):void 0}function ko(e,t,n){return e===t||Cn(e)&&Cn(t)?!0:Cn(e)||Cn(t)?!1:Array.isArray(e)&&Array.isArray(t)?rB(e,t):Array.isArray(e)||Array.isArray(t)?!1:pr(e)&&pr(t)?iB(e,t,n):(pr(e)||pr(t),!1)}function rB(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!ko(e[n],t[n]))return!1;return!0}function iB(e,t,n){const r=new Set;Object.keys(e).forEach(o=>r.add(o)),Object.keys(t).forEach(o=>r.add(o)),n==="meta"&&(r.delete("versionId"),r.delete("lastUpdated"),r.delete("author"));for(const o of r){const s=e[o],c=t[o];if(!ko(s,c,o))return!1}return!0}function iS(e,t){return Cn(e)?!0:Cn(t)?!1:Array.isArray(e)&&Array.isArray(t)?oB(e,t):Array.isArray(e)||Array.isArray(t)?!1:pr(e)&&pr(t)?aB(e,t):pr(e)||pr(t)?!1:e===t}function oB(e,t){return t.every(n=>e.some(r=>iS(r,n)))}function aB(e,t){return Object.entries(t).every(([n,r])=>n in e&&iS(e[n],r))}function hi(e){return e===void 0?e:JSON.parse(JSON.stringify(e))}function oS(e){return/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i.test(e)}function pr(e){return e!==null&&typeof e=="object"}function sB(e){return typeof e=="string"}function XD(e){return pr(e)&&"code"in e&&typeof e.code=="string"}function JD(e){return pr(e)&&"coding"in e&&Array.isArray(e.coding)&&e.coding.every(XD)}function lB(e){return pr(e)&&"text"in e&&typeof e.text=="string"}const ZD=[];for(let e=0;e<256;e++)ZD.push(e.toString(16).padStart(2,"0"));function cB(e){const t=ek(e),n=new Uint8Array(t),r=new Array(n.length);for(let o=0;o<n.length;o++)r[o]=ZD[n[o]];return r.join("")}function uB(e){const t=ek(e),n=new Uint8Array(t),r=new Array(n.length);for(let o=0;o<n.length;o++)r[o]=String.fromCharCode(n[o]);return window.btoa(r.join(""))}function ek(e){return ArrayBuffer.isView(e)?e.buffer:e}function Wn(e){return e?e.charAt(0).toUpperCase()+e.substring(1):""}function aS(e){return e.length>0&&e.startsWith(e[0].toUpperCase())}function ol(e,t){const n=e+".";if(t.startsWith(n))return t.slice(n.length)}function dB(e,t){return e.coding?.find(n=>n.system===t)?.code}function fB(e){if(e!==void 0)return Array.isArray(e)?e:[e]}const DT=e=>new Promise(t=>{setTimeout(t,e)});function Vx(e,t,n){const r=[];for(let o=0;o<n-1;o++){const s=e.indexOf(t);if(s<0)break;r.push(e.slice(0,s)),e=e.slice(s+t.length)}return r.push(e),r}function hB(e){let t,n=!1;return function(){return n||(t=e(),n=!0),t}}function sd(e,t){return e?(e.push(t),e):[t]}function Qc(e){return e.sort((t,n)=>t.localeCompare(n))}function sS(e){return e.endsWith("/")?e:e+"/"}function pB(e){return e.startsWith("/")?e.slice(1):e}function vo(e,t){return new URL(pB(t),sS(e.toString())).toString()}function mB(e,t){return vo(e,t).toString().replace("http://","ws://").replace("https://","wss://")}function gB(e){return typeof e=="object"&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&(e=Object.fromEntries(Object.entries(e).filter(t=>t[1]!==void 0))),new URLSearchParams(e).toString()}function tk(e,t){return e?.meta?.profile?.includes(t)||(e.meta=e.meta??{},e.meta.profile=e.meta.profile??[],e.meta.profile.push(t)),e}function vB(e,t){if(e?.meta?.profile?.includes(t)){const n=e.meta.profile.indexOf(t);e.meta.profile.splice(n,1)}return e}function ml(e){if(!e)return"";switch(e.type){case"Address":return nk(e.value);case"CodeableConcept":return xs(e.value);case"Coding":return uf(e.value);case"ContactPoint":return e.value.value;case"HumanName":return Rs(e.value);case"Quantity":return al(e.value);case"Reference":return yB(e.value);default:return e.value?.toString()??""}}function yB(e){return e?e.display??e.reference??no(e):""}function nk(e,t){if(!e)return"";const n=[];if(e.line&&n.push(...e.line),e.city||e.state||e.postalCode){const r=[];e.city&&r.push(e.city),e.state&&r.push(e.state),e.postalCode&&r.push(e.postalCode),n.push(r.join(", "))}return e.use&&t?.use,n.join(", ").trim()}function Rs(e,t){if(!e)return"";const n=[];if(e.prefix&&t?.prefix!==!1&&n.push(...e.prefix),e.given&&n.push(...e.given),e.family&&n.push(e.family),e.suffix&&t?.suffix!==!1&&n.push(...e.suffix),e.use&&(t?.all||t?.use)&&n.push("["+e.use+"]"),n.length===0){const r=Od(e.text);if(r)return r}return n.join(" ").trim()}function Bm(e){return e instanceof Date&&!Number.isNaN(e.getTime())}function xB(e,t,n){if(!e)return"";const r=new Date("2000-01-01T"+e+"Z");return Bm(r)?r.toLocaleTimeString(t,n):""}function wr(e,t,n){if(!e)return"";const r=new Date(e);return Bm(r)?r.toLocaleString(t,n):""}function bB(e,t,n){return!e||!e.start&&!e.end?"":wr(e.start,t,n)+" - "+wr(e.end,t,n)}const SB={s:"every second",min:"every minute",h:"hourly",d:"daily",wk:"weekly",mo:"monthly",a:"annually"},wB={s:"second",min:"minute",h:"hour",d:"day",wk:"week",mo:"month",a:"year"},jB={s:"seconds",min:"minutes",h:"hours",d:"days",wk:"weeks",mo:"months",a:"years"};function rk(e){if(!e)return"";const t=[];return CB(t,e.repeat),e.event&&t.push(e.event.map(n=>wr(n)).join(", ")),Wn(t.join(" ").trim())}function CB(e,t){if(!t?.periodUnit)return;const n=t.frequency??1,r=t.period??1,o=t.periodUnit;n===1&&r===1?e.push(SB[o]):(n===1?e.push("once"):e.push(n+" times"),r===1?e.push("per "+wB[o]):e.push("per "+r+" "+jB[o])),t.dayOfWeek&&e.push("on "+t.dayOfWeek.map(Wn).join(", ")),t.timeOfDay&&e.push("at "+t.timeOfDay.map(s=>xB(s)).join(", "))}function Nd(e,t,n=!1){if(n&&t===void 0)throw new Error("Precision must be specified for exclusive ranges");const r=e?.low&&{...e.low,comparator:void 0},o=e?.high&&{...e.high,comparator:void 0};return r?.value===void 0&&o?.value===void 0?"":r?.value!==void 0&&o?.value===void 0?`>= ${al(r)}`:r?.value===void 0&&o?.value!==void 0?`<= ${al(o)}`:(r?.unit===o?.unit&&delete r?.unit,`${al(r)} - ${al(o)}`)}function al(e,t){if(!e)return"";const n=[];return e.comparator&&(n.push(e.comparator),n.push(" ")),e.value!==void 0&&n.push(e.value),e.unit&&(e.unit!=="%"&&n.at(-1)!==" "&&n.push(" "),n.push(e.unit)),n.join("").trim()}function EB(e){return e?.value===void 0?"":e.value.toLocaleString(void 0,{style:"currency",currency:e.currency??"USD",currencyDisplay:"narrowSymbol"})}function xs(e){if(!e)return"";const t=Od(e.text);return t||(e.coding?e.coding.map(n=>uf(n)).join(", "):"")}function uf(e,t){const n=Od(e?.display);return n?`${n}`:Od(e?.code)??""}function ik(e){if(!e)return"";const t=[];if(e.valueQuantity)t.push(al(e.valueQuantity));else if(e.valueCodeableConcept)t.push(xs(e.valueCodeableConcept));else{const n=Od(e.valueString);n&&t.push(n)}return"component"in e&&t.push(e.component.map(n=>ik(n)).join(" / ")),t.join(" / ").trim()}function Od(e){return typeof e=="string"?e:void 0}const ne={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 TB(e){const t=Array.isArray(e)?e:e.entry?.map(n=>n.resource)??[];for(const n of t)n?.resourceType==="StructureDefinition"&&n.kind==="resource"&&ok(n.type)}function ok(e){let t=Po.types[e];return t||(t={searchParamsDetails:{}},Po.types[e]=t),!t.searchParams&&e!=="Binary"&&(t.searchParams={_id:{base:[e],code:"_id",type:"token",expression:e+".id"},_lastUpdated:{base:[e],code:"_lastUpdated",type:"date",expression:e+".meta.lastUpdated"},_compartment:{base:[e],code:"_compartment",type:"reference",expression:e+".meta.compartment"},_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"}}),t}function RB(e){for(const t of e.base??[]){const n=ok(t);n.searchParams||(n.searchParams={}),n.searchParams[e.code]=e}}function kT(e){const t=e.type?.[0]?.code;return t==="BackboneElement"||t==="Element"?_B((e.base?.path??e.path)?.split(".")):t}function _B(e){return e.length===1?e[0]:e.map(Wn).join("")}function lS(e){return Po.types[e]?.searchParams}function AB(e,t){return Po.types[e]?.searchParams?.[t]}function gl(e){const t=e.replaceAll("[x]","").split(".").pop();return ak(t)}function ak(e){let t;return e.length<100?t=e.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+/g)??[]:t=e.split(/(?=[A-Z])/),t.map(kB).join(" ").replace("_"," ").replaceAll(/\s+/g," ")}const DB=new Set(["CDS","ID","IP","PKCE","JWKS","URI","URL","OMB","UDI"]);function kB(e){const t=e.toUpperCase();return e===t?e:DB.has(t)?t:t.charAt(0)+e.slice(1)}function _s(e,t,n){const r=$m(e,n);if(r)return PB(r.elements,t)}function PB(e,t){const n=e[t]??e[t+"[x]"];if(n)return n;for(let r=0;r<t.length;r++){const o=t[r];if(o>="A"&&o<="Z"){const s=t.slice(0,r)+"[x]",c=e[s];if(c)return c}}}function Bo(e,t){return!(!e||typeof e!="object"||!("resourceType"in e)||t&&e.resourceType!==t)}function _a(e,t){return!!(e&&typeof e=="object"&&"reference"in e&&typeof e.reference=="string")}const Po={types:{}};function dp(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}}const ua=()=>[],Yr={empty:(e,t)=>Ze(t.every(n=>Cn(n.value))),hasValue:(e,t)=>Ze(t.length!==0),exists:(e,t,n)=>Ze(n?t.some(r=>wo(n.eval(e,[r]))):t.length>0&&t.every(r=>!Cn(r.value))),all:(e,t,n)=>Ze(t.every(r=>wo(n.eval(e,[r])))),allTrue:(e,t)=>{for(const n of t)if(!n.value)return Ze(!1);return Ze(!0)},anyTrue:(e,t)=>{for(const n of t)if(n.value)return Ze(!0);return Ze(!1)},allFalse:(e,t)=>{for(const n of t)if(n.value)return Ze(!1);return Ze(!0)},anyFalse:(e,t)=>{for(const n of t)if(!n.value)return Ze(!0);return Ze(!1)},subsetOf:(e,t,n)=>{if(t.length===0)return Ze(!0);const r=n.eval(e,Ws(e));return r.length===0?Ze(!1):Ze(t.every(o=>r.some(s=>s.value===o.value)))},supersetOf:(e,t,n)=>{const r=n.eval(e,Ws(e));return r.length===0?Ze(!0):t.length===0?Ze(!1):Ze(r.every(o=>t.some(s=>s.value===o.value)))},count:(e,t)=>[{type:ne.integer,value:t.length}],distinct:(e,t)=>{const n=[];for(const r of t)n.some(o=>o.value===r.value)||n.push(r);return n},isDistinct:(e,t)=>Ze(t.length===Yr.distinct(e,t).length),where:(e,t,n)=>t.filter(r=>wo(n.eval(e,[r]))),select:(e,t,n)=>t.flatMap(r=>n.eval({parent:e,variables:{$this:r}},[r])),repeat:ua,ofType:(e,t,n)=>t.filter(r=>r.type===n.name),single:(e,t)=>{if(t.length>1)throw new Error("Expected input length one for single()");return t.length===0?[]:t.slice(0,1)},first:(e,t)=>t.length===0?[]:t.slice(0,1),last:(e,t)=>t.length===0?[]:t.slice(-1,t.length),tail:(e,t)=>t.length===0?[]:t.slice(1,t.length),skip:(e,t,n)=>{const r=n.eval(e,t)[0]?.value;if(typeof r!="number")throw new TypeError("Expected a number for skip(num)");return r>=t.length?[]:r<=0?t:t.slice(r,t.length)},take:(e,t,n)=>{const r=n.eval(e,t)[0]?.value;if(typeof r!="number")throw new TypeError("Expected a number for take(num)");return r>=t.length?t:r<=0?[]:t.slice(0,r)},intersect:(e,t,n)=>{if(!n)return t;const r=n.eval(e,Ws(e)),o=[];for(const s of t)!o.some(c=>c.value===s.value)&&r.some(c=>c.value===s.value)&&o.push(s);return o},exclude:(e,t,n)=>{if(!n)return t;const r=n.eval(e,Ws(e)),o=[];for(const s of t)r.some(c=>c.value===s.value)||o.push(s);return o},union:(e,t,n)=>{if(!n)return t;const r=n.eval(e,Ws(e));return VD([...t,...r])},combine:(e,t,n)=>{if(!n)return t;const r=n.eval(e,Ws(e));return[...t,...r]},htmlChecks:(e,t,n)=>[fi(!0)],iif:(e,t,n,r,o)=>{const s=n.eval(e,t);if(s.length>1||s.length===1&&typeof s[0].value!="boolean")throw new Error("Expected criterion to evaluate to a Boolean");return wo(s)?r.eval(e,t):o?o.eval(e,t):[]},toBoolean:(e,t)=>{if(t.length===0)return[];const[{value:n}]=yo(t,1);if(typeof n=="boolean")return[{type:ne.boolean,value:n}];if(typeof n=="number"&&(n===0||n===1))return Ze(!!n);if(typeof n=="string"){const r=n.toLowerCase();if(["true","t","yes","y","1","1.0"].includes(r))return Ze(!0);if(["false","f","no","n","0","0.0"].includes(r))return Ze(!1)}return[]},convertsToBoolean:(e,t)=>t.length===0?[]:Ze(Yr.toBoolean(e,t).length===1),toInteger:(e,t)=>{if(t.length===0)return[];const[{value:n}]=yo(t,1);return typeof n=="number"?[{type:ne.integer,value:n}]:typeof n=="string"&&/^[+-]?\d+$/.exec(n)?[{type:ne.integer,value:Number.parseInt(n,10)}]:typeof n=="boolean"?[{type:ne.integer,value:n?1:0}]:[]},convertsToInteger:(e,t)=>t.length===0?[]:Ze(Yr.toInteger(e,t).length===1),toDate:(e,t)=>{if(t.length===0)return[];const[{value:n}]=yo(t,1);return typeof n=="string"&&/^\d{4}(-\d{2}(-\d{2})?)?/.exec(n)?[{type:ne.date,value:dp(n)}]:[]},convertsToDate:(e,t)=>t.length===0?[]:Ze(Yr.toDate(e,t).length===1),toDateTime:(e,t)=>{if(t.length===0)return[];const[{value:n}]=yo(t,1);return typeof n=="string"&&/^\d{4}(-\d{2}(-\d{2})?)?/.exec(n)?[{type:ne.dateTime,value:dp(n)}]:[]},convertsToDateTime:(e,t)=>t.length===0?[]:Ze(Yr.toDateTime(e,t).length===1),toDecimal:(e,t)=>{if(t.length===0)return[];const[{value:n}]=yo(t,1);return typeof n=="number"?[{type:ne.decimal,value:n}]:typeof n=="string"&&/^-?\d{1,9}(\.\d{1,9})?$/.exec(n)?[{type:ne.decimal,value:Number.parseFloat(n)}]:typeof n=="boolean"?[{type:ne.decimal,value:n?1:0}]:[]},convertsToDecimal:(e,t)=>t.length===0?[]:Ze(Yr.toDecimal(e,t).length===1),toQuantity:(e,t)=>{if(t.length===0)return[];const[{value:n}]=yo(t,1);return ki(n)?[{type:ne.Quantity,value:n}]:typeof n=="number"?[{type:ne.Quantity,value:{value:n,unit:"1"}}]:typeof n=="string"&&/^-?\d{1,9}(\.\d{1,9})?/.exec(n)?[{type:ne.Quantity,value:{value:Number.parseFloat(n),unit:"1"}}]:typeof n=="boolean"?[{type:ne.Quantity,value:{value:n?1:0,unit:"1"}}]:[]},convertsToQuantity:(e,t)=>t.length===0?[]:Ze(Yr.toQuantity(e,t).length===1),toString:(e,t)=>{if(t.length===0)return[];const[{value:n}]=yo(t,1);return n==null?[]:ki(n)?[{type:ne.string,value:`${n.value} '${n.unit}'`}]:[{type:ne.string,value:n.toString()}]},convertsToString:(e,t)=>t.length===0?[]:Ze(Yr.toString(e,t).length===1),toTime:(e,t)=>{if(t.length===0)return[];const[{value:n}]=yo(t,1);if(typeof n=="string"){const r=/^T?(\d{2}(:\d{2}(:\d{2})?)?)/.exec(n);if(r)return[{type:ne.time,value:dp("T"+r[1])}]}return[]},convertsToTime:(e,t)=>t.length===0?[]:Ze(Yr.toTime(e,t).length===1),indexOf:(e,t,n)=>Ti((r,o)=>r.indexOf(o),e,t,n),substring:(e,t,n,r)=>Ti((o,s,c)=>{const d=s,f=c?d+c:o.length;return d<0||d>=o.length?void 0:o.substring(d,f)},e,t,n,r),startsWith:(e,t,n)=>Ti((r,o)=>r.startsWith(o),e,t,n),endsWith:(e,t,n)=>Ti((r,o)=>r.endsWith(o),e,t,n),contains:(e,t,n)=>Ti((r,o)=>r.includes(o),e,t,n),upper:(e,t)=>Ti(n=>n.toUpperCase(),e,t),lower:(e,t)=>Ti(n=>n.toLowerCase(),e,t),replace:(e,t,n,r)=>Ti((o,s,c)=>o.replaceAll(s,c),e,t,n,r),matches:(e,t,n)=>Ti((r,o)=>!!new RegExp(o).exec(r),e,t,n),replaceMatches:(e,t,n,r)=>Ti((o,s,c)=>o.replaceAll(new RegExp(s,"g"),c.replaceAll(/\$\{(\w+)\}/g,"$<$1>")),e,t,n,r),length:(e,t)=>Ti(n=>n.length,e,t),toChars:(e,t)=>Ti(n=>n?n.split(""):void 0,e,t),encode:ua,decode:ua,escape:ua,unescape:ua,trim:ua,split:ua,join:(e,t,n)=>{const r=n?.eval(e,Ws(e))[0]?.value??"";if(typeof r!="string")throw new TypeError("Separator must be a string.");return[{type:ne.string,value:t.map(o=>o.value?.toString()??"").join(r)}]},abs:(e,t)=>mo(Math.abs,e,t),ceiling:(e,t)=>mo(Math.ceil,e,t),exp:(e,t)=>mo(Math.exp,e,t),floor:(e,t)=>mo(Math.floor,e,t),ln:(e,t)=>mo(Math.log,e,t),log:(e,t,n)=>mo((r,o)=>Math.log(r)/Math.log(o),e,t,n),power:(e,t,n)=>mo(Math.pow,e,t,n),round:(e,t,...n)=>mo((r,o=0)=>{if(typeof o!="number"||o<0)throw new Error("Invalid precision provided to round()");const s=Math.pow(10,o);return Math.round(r*s)/s},e,t,...n),sqrt:(e,t)=>mo(Math.sqrt,e,t),truncate:(e,t)=>mo(n=>Math.trunc(n),e,t),children:ua,descendants:ua,trace:(e,t,n)=>t,now:()=>[{type:ne.dateTime,value:new Date().toISOString()}],timeOfDay:()=>[{type:ne.time,value:new Date().toISOString().substring(11)}],today:()=>[{type:ne.date,value:new Date().toISOString().substring(0,10)}],between:(e,t,n,r,o)=>{const s=Yr.toDateTime(e,n.eval(e,t));if(s.length===0)throw new Error("Invalid start date");const c=Yr.toDateTime(e,r.eval(e,t));if(c.length===0)throw new Error("Invalid end date");const d=o.eval(e,t)[0]?.value;if(d!=="years"&&d!=="months"&&d!=="days")throw new Error("Invalid units");const f=KD(s[0].value,c[0].value);return[{type:ne.Quantity,value:{value:f[d],unit:d}}]},is:(e,t,n)=>{let r="";return n instanceof Md?r=n.name:n instanceof Vm&&(r=n.left.name+"."+n.right.name),r?t.map(o=>({type:ne.boolean,value:HD(o,r)})):[]},not:(e,t)=>Yr.toBoolean(e,t).map(n=>({type:ne.boolean,value:!n.value})),resolve:(e,t)=>t.map(n=>{const r=n.value;let o;if(typeof r=="string")o=r;else if(typeof r=="object"){const s=r;if(s.resource)return fi(s.resource);s.reference?o=s.reference:s.type&&s.identifier&&(o=`${s.type}?identifier=${s.identifier.system}|${s.identifier.value}`)}if(o?.includes("?")){const[s]=o.split("?");return{type:s,value:{resourceType:s}}}if(o?.includes("/")){const[s,c]=o.split("/");return{type:s,value:{resourceType:s,id:c}}}return{type:ne.BackboneElement,value:void 0}}).filter(n=>!!n.value),as:(e,t)=>t,type:(e,t)=>t.map(({value:n})=>typeof n=="boolean"?{type:ne.BackboneElement,value:{namespace:"System",name:"Boolean"}}:typeof n=="number"?{type:ne.BackboneElement,value:{namespace:"System",name:"Integer"}}:Bo(n)?{type:ne.BackboneElement,value:{namespace:"FHIR",name:n.resourceType}}:{type:ne.BackboneElement,value:null}),conformsTo:(e,t,n)=>{const r=n.eval(e,t)[0].value;if(!r.startsWith("http://hl7.org/fhir/StructureDefinition/"))throw new Error("Expected a StructureDefinition URL");const o=r.replace("http://hl7.org/fhir/StructureDefinition/","");return t.map(s=>({type:ne.boolean,value:s.value?.resourceType===o}))},getResourceKey:(e,t)=>{const n=t[0].value;return n?.id?[{type:ne.id,value:n.id}]:[]},getReferenceKey:(e,t,n)=>{const r=t[0].value;if(!r?.reference)return[];let o="";return n instanceof Md&&(o=n.name),o&&!r.reference.startsWith(o+"/")?[]:[{type:ne.id,value:pl(r)}]},extension:(e,t,n)=>{const r=n.eval(e,t)[0].value,o=t?.[0]?.value;if(o){const s=Uo(o,r);if(s)return[{type:ne.Extension,value:s}]}return[]}};function Ti(e,t,n,...r){if(n.length===0)return[];const[{value:o}]=yo(n,1);if(typeof o!="string")throw new TypeError("String function cannot be called with non-string");const s=r.map(d=>d?.eval(t,n)[0]?.value),c=e(o,...s);return c===void 0?[]:Array.isArray(c)?c.map(fi):[fi(c)]}function mo(e,t,n,...r){if(n.length===0)return[];const[{value:o}]=yo(n,1),s=ki(o),c=s?o.value:o;if(typeof c!="number")throw new TypeError("Math function cannot be called with non-number");const d=e(c,...r.map(m=>m.eval(t,n)[0]?.value)),f=s?ne.Quantity:n[0].type,p=s?{...o,value:d}:d;return[{type:f,value:p}]}function yo(e,t){if(e.length!==t)throw new Error(`Expected ${t} arguments`);for(const n of e)if(n==null)throw new Error("Expected non-null argument");return e}function Ws(e){let t=e;for(;t.parent?.variables.$this;)t=t.parent;return[t.variables.$this]}class cS{original;child;constructor(t,n){this.original=t,this.child=n}eval(t,n){try{if(n.length>0){const r=[];for(const o of n)r.push(this.child.eval({parent:t,variables:{$this:o}},[o]));return r.flat()}else return this.child.eval(t,[])}catch(r){throw new Error(`FhirPathError on "${this.original}": ${r}`,{cause:r})}}toString(){return this.child.toString()}}class Cc{value;constructor(t){this.value=t}eval(){return[this.value]}toString(){const t=this.value.value;return typeof t=="string"?`'${t}'`:t.toString()}}class Md{name;constructor(t){this.name=t}eval(t,n){if(this.name==="$this")return n;const r=this.getVariable(t);if(r)return[r];if(this.name.startsWith("%"))throw new Error(`Undefined variable ${this.name}`);return n.flatMap(o=>this.evalValue(o)).filter(o=>o?.value!==void 0)}getVariable(t){const n=t.variables[this.name];if(n!==void 0)return n;if(t.parent)return this.getVariable(t.parent)}evalValue(t){const n=t.value;if(!(!n||typeof n!="object"))return Bo(n,this.name)?t:$D(t,this.name)}toString(){return this.name}}class NB{eval(){return[]}toString(){return"{}"}}class OB extends f8{impl;constructor(t,n,r){super(t,n),this.impl=r}eval(t,n){return this.impl(this.child.eval(t,n))}toString(){return this.operator+this.child.toString()}}class Dp extends sf{constructor(t,n){super("as",t,n)}eval(t,n){return Yr.ofType(t,this.left.eval(t,n),this.right)}}class ei extends sf{}class qi extends ei{impl;constructor(t,n,r,o){super(t,n,r),this.impl=o}eval(t,n){const r=this.left.eval(t,n);if(r.length!==1)return[];const o=this.right.eval(t,n);if(o.length!==1)return[];const s=r[0].value,c=o[0].value,d=ki(s)?s.value:s,f=ki(c)?c.value:c,p=this.impl(d,f);return typeof p=="boolean"?Ze(p):ki(s)?[{type:ne.Quantity,value:{...s,value:p}}]:[fi(p)]}}class MB extends sf{constructor(t,n){super("&",t,n)}eval(t,n){const r=this.left.eval(t,n),o=this.right.eval(t,n),s=[...r,...o];return s.length>0&&s.every(c=>typeof c.value=="string")?[{type:ne.string,value:s.map(c=>c.value).join("")}]:s}}class LB extends ei{constructor(t,n){super("contains",t,n)}eval(t,n){const r=this.left.eval(t,n),o=this.right.eval(t,n);return Ze(r.some(s=>s.value===o[0].value))}}class IB extends ei{constructor(t,n){super("in",t,n)}eval(t,n){const r=xa(this.left.eval(t,n)),o=this.right.eval(t,n);return r?Ze(o.some(s=>Um(r,s)[0].value)):[]}}class Vm extends sf{constructor(t,n){super(".",t,n)}eval(t,n){return this.right.eval(t,this.left.eval(t,n))}toString(){return`${this.left.toString()}.${this.right.toString()}`}}class uS extends sf{constructor(t,n){super("|",t,n)}eval(t,n){const r=this.left.eval(t,n),o=this.right.eval(t,n);return VD([...r,...o])}}class zB extends ei{constructor(t,n){super("=",t,n)}eval(t,n){const r=this.left.eval(t,n),o=this.right.eval(t,n);return qU(r,o)}}class $B extends ei{constructor(t,n){super("!=",t,n)}eval(t,n){const r=this.left.eval(t,n),o=this.right.eval(t,n);return GU(r,o)}}class UB extends ei{constructor(t,n){super("~",t,n)}eval(t,n){const r=this.left.eval(t,n),o=this.right.eval(t,n);return FD(r,o)}}class BB extends ei{constructor(t,n){super("!~",t,n)}eval(t,n){const r=this.left.eval(t,n),o=this.right.eval(t,n);return HU(FD(r,o))}}class dS extends ei{constructor(t,n){super("is",t,n)}eval(t,n){const r=this.left.eval(t,n);if(r.length!==1)return[];const o=this.right.name;return Ze(HD(r[0],o))}}class VB extends ei{constructor(t,n){super("and",t,n)}eval(t,n){const r=xa(this.left.eval(t,n),"boolean"),o=xa(this.right.eval(t,n),"boolean");return r?.value===!0&&o?.value===!0?Ze(!0):r?.value===!1||o?.value===!1?Ze(!1):[]}}class FB extends ei{constructor(t,n){super("or",t,n)}eval(t,n){const r=xa(this.left.eval(t,n),"boolean"),o=xa(this.right.eval(t,n),"boolean");return r?.value===!1&&o?.value===!1?Ze(!1):r?.value||o?.value?Ze(!0):[]}}class HB extends ei{constructor(t,n){super("xor",t,n)}eval(t,n){const r=xa(this.left.eval(t,n),"boolean"),o=xa(this.right.eval(t,n),"boolean");return!r||!o?[]:Ze(r.value!==o.value)}}class qB extends ei{constructor(t,n){super("implies",t,n)}eval(t,n){const r=xa(this.left.eval(t,n),"boolean"),o=xa(this.right.eval(t,n),"boolean");return o?.value===!0||r?.value===!1?Ze(!0):!r||!o?[]:Ze(!1)}}class fS{name;args;constructor(t,n){this.name=t,this.args=n}eval(t,n){const r=Yr[this.name];if(!r)throw new Error("Unrecognized function: "+this.name);return r(t,n,...this.args)}toString(){return`${this.name}(${this.args.map(t=>t.toString()).join(", ")})`}}class hS{left;expr;constructor(t,n){this.left=t,this.expr=n}eval(t,n){const r=this.expr.eval(t,n);if(r.length!==1)return[];const o=r[0].value;if(typeof o!="number")throw new Error("Invalid indexer expression: should return integer}");const s=this.left.eval(t,n);return o in s?[s[o]]:[]}toString(){return`${this.left.toString()}[${this.expr.toString()}]`}}const GB=["year","years","month","months","week","weeks","day","days","hour","hours","minute","minutes","second","seconds","millisecond","milliseconds"],QB={"'":"'",'"':'"',"`":"`",r:"\r",n:`
|
|
57
57
|
`,t:" ",f:"\f","\\":"\\"};class WB{str;keywords;operators;dateTimeLiterals;symbolRegex;result=[];pos={index:0,line:1,column:0};markStack=[];constructor(t,n,r,o){this.str=t,this.keywords=n,this.operators=r,this.dateTimeLiterals=!!o?.dateTimeLiterals,this.symbolRegex=o?.symbolRegex??/[$\w%]/}tokenize(){for(;this.pos.index<this.str.length;){const t=this.consumeToken();t&&this.result.push(t)}return this.result}prevToken(){return this.result.slice(-1)[0]}peekToken(){this.mark();const t=this.consumeToken();return this.reset(),t}consumeToken(){this.consumeWhitespace();const t=this.curr();if(!t)return;this.mark();const n=this.peek();return t==="/"&&n==="*"?this.consumeMultiLineComment():t==="/"&&n==="/"?this.consumeSingleLineComment():t==="'"||t==='"'||t==="`"?this.consumeString(t):t==="@"?this.consumeDateTime():/\d/.exec(t)?this.consumeNumber():/\w/.exec(t)?this.consumeSymbol():(t==="$"||t==="%")&&/\w/.exec(n)?this.consumeSymbol():(t==="$"||t==="%")&&(n==="'"||n==='"'||n==="`")?this.consumeQuotedSymbol(n):this.consumeOperator()}consumeWhitespace(){this.consumeWhile(()=>/\s/.exec(this.curr()))}consumeMultiLineComment(){const t=this.pos.index;return this.consumeWhile(()=>this.curr()!=="*"||this.peek()!=="/"),this.advance(),this.advance(),this.buildToken("Comment",this.str.substring(t,this.pos.index))}consumeSingleLineComment(){return this.buildToken("Comment",this.consumeWhile(()=>this.curr()!==`
|
|
58
58
|
`))}consumeString(t){this.advance();let n="",r;for(;r=this.consumeChar(t);)n+=r;const o=this.buildToken(t==="`"?"Symbol":"String",n);return this.advance(),o}consumeChar(t){const n=this.curr();if(n==="\\"){this.advance();const r=this.curr(),o=QB[r];if(o!==void 0)return this.advance(),o;if(r==="u"){this.advance();const s=/^[0-9a-fA-F]{4}$/.exec(this.str.substring(this.pos.index,this.pos.index+4))?.[0];return s?(this.advance(),this.advance(),this.advance(),this.advance(),String.fromCodePoint(Number.parseInt(s,16))):"u"}return this.consumeChar(t)}return n===t||!n?"":(this.advance(),n)}consumeQuotedSymbol(t){this.mark();const n=this.pos.index;this.advance(),this.consumeString(t);const r=this.str.substring(n,this.pos.index);return this.buildToken("Symbol",r)}consumeDateTime(){this.advance();const t=this.pos.index;this.consumeWhile(()=>/[\d-]/.exec(this.curr()));let n=!1,r=!1;if(this.curr()==="T"&&(n=!0,this.advance(),this.consumeWhile(()=>/[\d:]/.exec(this.curr())),this.curr()==="."&&/\d/.exec(this.peek())&&(this.advance(),this.consumeWhile(()=>/\d/.exec(this.curr()))),this.curr()==="Z"?(r=!0,this.advance()):(this.curr()==="+"||this.curr()==="-")&&(r=!0,this.advance(),this.consumeWhile(()=>/[\d:]/.exec(this.curr())))),this.pos.index===t)throw new Error("Invalid DateTime literal");let o=this.str.substring(t,this.pos.index);return o.endsWith("T")?o=o.substring(0,o.length-1):!o.startsWith("T")&&n&&!r&&(o+="Z"),this.buildToken("DateTime",o)}consumeNumber(){const t=this.pos.index;let n="Number";return this.consumeWhile(()=>/\d/.exec(this.curr())),this.curr()==="."&&/\d/.exec(this.peek())&&(this.advance(),this.consumeWhile(()=>/\d/.exec(this.curr()))),this.curr()==="-"&&this.dateTimeLiterals?(this.pos.index=t-1,this.consumeDateTime()):(this.curr()===" "&&YB(this.peekToken())&&(n="Quantity",this.consumeToken()),this.buildToken(n,this.str.substring(t,this.pos.index)))}consumeSymbol(){const t=this.consumeWhile(()=>this.symbolRegex.exec(this.curr()));return this.prevToken()?.value!=="."&&this.keywords.includes(t)?this.buildToken(t,t):this.buildToken("Symbol",t)}consumeOperator(){const t=this.curr(),n=this.peek(),r=t+n;return this.operators.includes(r)?(this.advance(),this.advance(),this.buildToken(r,r)):(this.advance(),this.buildToken(t,t))}consumeWhile(t){const n=this.pos.index;for(;this.pos.index<this.str.length&&t();)this.advance();return this.str.substring(n,this.pos.index)}curr(){return this.str[this.pos.index]}peek(){return this.str[this.pos.index+1]??""}mark(){this.markStack.push({...this.pos})}reset(){const t=this.markStack.pop();if(!t)throw new Error("No mark to reset to");this.pos.index=t.index,this.pos.line=t.line,this.pos.column=t.column}advance(){this.pos.index++,this.curr()===`
|
|
59
|
-
`?(this.pos.line++,this.pos.column=0):this.pos.column++}buildToken(t,n){const r=this.markStack.pop();if(!r)throw new Error("No mark for token");return{id:t,value:n,...r}}}function YB(e){return!!(e&&(e.id==="String"||e.id==="Symbol"&&GB.includes(e.value)))}const KB=["true","false"],XB=["!=","!~","<=",">=","{}","->"];function JB(e){return new WB(e,KB,XB).tokenize()}const tn={FunctionCall:0,Dot:1,Indexer:2,UnaryAdd:3,UnarySubtract:3,Multiply:4,Divide:4,Modulo:4,Add:5,Subtract:5,Ampersand:5,Is:6,As:6,Union:7,GreaterThan:8,GreaterThanOrEquals:8,LessThan:8,LessThanOrEquals:8,Equals:9,Equivalent:9,NotEquals:9,NotEquivalent:9,In:10,Contains:10,And:11,Xor:12,Or:12,Implies:13},ZB={parse(e){const t=e.consumeAndParse();if(!e.match(")"))throw new Error("Parse error: expected `)` got `"+e.peek()?.value+"`");return t}},eV={parse(e,t){const n=e.consumeAndParse();if(!e.match("]"))throw new Error("Parse error: expected `]`");return new hS(t,n)},precedence:tn.Indexer},tV={parse(e,t){if(!(t instanceof Md))throw new Error("Unexpected parentheses");const n=[];for(;!e.match(")");)n.push(e.consumeAndParse()),e.match(",");return new fS(t.name,n)},precedence:tn.FunctionCall};function nV(e){const t=e.split(" "),n=Number.parseFloat(t[0]);let r=t[1];return r?.startsWith("'")&&r.endsWith("'")?r=r.substring(1,r.length-1):r="{"+r+"}",{value:n,unit:r}}function rV(){return new h8().registerPrefix("String",{parse:(e,t)=>new Cc({type:ne.string,value:t.value})}).registerPrefix("DateTime",{parse:(e,t)=>new Cc({type:ne.dateTime,value:dp(t.value)})}).registerPrefix("Quantity",{parse:(e,t)=>new Cc({type:ne.Quantity,value:nV(t.value)})}).registerPrefix("Number",{parse:(e,t)=>new Cc({type:t.value.includes(".")?ne.decimal:ne.integer,value:Number.parseFloat(t.value)})}).registerPrefix("true",{parse:()=>new Cc({type:ne.boolean,value:!0})}).registerPrefix("false",{parse:()=>new Cc({type:ne.boolean,value:!1})}).registerPrefix("Symbol",{parse:(e,t)=>new Md(t.value)}).registerPrefix("{}",{parse:()=>new NB}).registerPrefix("(",ZB).registerInfix("[",eV).registerInfix("(",tV).prefix("+",tn.UnaryAdd,(e,t)=>new OB("+",t,n=>n)).prefix("-",tn.UnarySubtract,(e,t)=>new qi("-",t,t,(n,r)=>-r)).infixLeft(".",tn.Dot,(e,t,n)=>new Vm(e,n)).infixLeft("/",tn.Divide,(e,t,n)=>new qi("/",e,n,(r,o)=>r/o)).infixLeft("*",tn.Multiply,(e,t,n)=>new qi("*",e,n,(r,o)=>r*o)).infixLeft("+",tn.Add,(e,t,n)=>new qi("+",e,n,(r,o)=>r+o)).infixLeft("-",tn.Subtract,(e,t,n)=>new qi("-",e,n,(r,o)=>r-o)).infixLeft("|",tn.Union,(e,t,n)=>new uS(e,n)).infixLeft("=",tn.Equals,(e,t,n)=>new zB(e,n)).infixLeft("!=",tn.NotEquals,(e,t,n)=>new $B(e,n)).infixLeft("~",tn.Equivalent,(e,t,n)=>new UB(e,n)).infixLeft("!~",tn.NotEquivalent,(e,t,n)=>new BB(e,n)).infixLeft("<",tn.LessThan,(e,t,n)=>new qi("<",e,n,(r,o)=>r<o)).infixLeft("<=",tn.LessThanOrEquals,(e,t,n)=>new qi("<=",e,n,(r,o)=>r<=o)).infixLeft(">",tn.GreaterThan,(e,t,n)=>new qi(">",e,n,(r,o)=>r>o)).infixLeft(">=",tn.GreaterThanOrEquals,(e,t,n)=>new qi(">=",e,n,(r,o)=>r>=o)).infixLeft("&",tn.Ampersand,(e,t,n)=>new MB(e,n)).infixLeft("and",tn.And,(e,t,n)=>new VB(e,n)).infixLeft("as",tn.As,(e,t,n)=>new Dp(e,n)).infixLeft("contains",tn.Contains,(e,t,n)=>new LB(e,n)).infixLeft("div",tn.Divide,(e,t,n)=>new qi("div",e,n,(r,o)=>Math.trunc(r/o))).infixLeft("in",tn.In,(e,t,n)=>new IB(e,n)).infixLeft("is",tn.Is,(e,t,n)=>new dS(e,n)).infixLeft("mod",tn.Modulo,(e,t,n)=>new qi("mod",e,n,(r,o)=>r%o)).infixLeft("or",tn.Or,(e,t,n)=>new FB(e,n)).infixLeft("xor",tn.Xor,(e,t,n)=>new HB(e,n)).infixLeft("implies",tn.Implies,(e,t,n)=>new qB(e,n))}const iV=rV();function pS(e){return new cS(e,iV.construct(JB(e)).consumeAndParse())}function oV(e,t){const n=Array.isArray(t)?t:[t];for(let r=0;r<n.length;r++){const o=n[r];typeof o=="object"&&"type"in o&&"value"in o||(n[r]=fi(n[r]))}return bs(e,n).map(r=>r.value)}function bs(e,t,n={},r=void 0){let o;if(typeof e=="string"){const s=r?.get(e);o=s??pS(e),r&&!s&&r.set(e,o)}else o=e;return o.eval({variables:n},t).map(s=>{const c={type:s.type,value:s.value?.valueOf()};return"path"in s&&(c.path=s.path),c})}function aV(e){const t=[];for(const n of e){const r=QD(n.value);r&&t.push(r)}return t}function sV(e){const t=new Set;for(const n of e){const r=ml(n);r&&t.add(r)}return Array.from(t)}function lV(e){const t=new Set;for(const n of e){const{value:r}=n;r&&(sB(r)?t.add(r):_a(r)?t.add(r.reference):YD(r)?t.add(Ot(r)):typeof r.identifier=="object"&&t.add(`identifier:${r.identifier.system}|${r.identifier.value}`))}return Array.from(t)}function cV(e,t={}){const n=[];for(const r of e)uV(t,n,r);return n}function uV(e,t,n){const{type:r,value:o}=n;switch(r){case ne.Identifier:dV(t,e,o);break;case ne.CodeableConcept:fV(t,e,o);break;case ne.Coding:sk(t,e,o);break;case ne.ContactPoint:hV(t,e,o);break;default:vl(t,e,void 0,o?.toString())}}function dV(e,t,n){n?.type?.text&&vl(e,t,t.textSearchSystem,n.type.text),vl(e,t,n?.system,n?.value)}function fV(e,t,n){if(n?.text&&vl(e,t,t.textSearchSystem,n.text),n?.coding)for(const r of n.coding)sk(e,t,r)}function sk(e,t,n){n&&(n.display&&vl(e,t,t.textSearchSystem,n.display),vl(e,t,n.system,n.code))}function hV(e,t,n){n&&vl(e,t,n.system,n.value?.toLocaleLowerCase())}function vl(e,t,n,r){(n||r)&&!e.some(o=>o.system===n&&o.value===r)&&e.push({system:n,value:r&&t.caseInsensitive?r.toLocaleLowerCase():r})}const Fm=20,he={EQUALS:"eq",NOT_EQUALS:"ne",GREATER_THAN:"gt",LESS_THAN:"lt",GREATER_THAN_OR_EQUALS:"ge",LESS_THAN_OR_EQUALS:"le",STARTS_AFTER:"sa",ENDS_BEFORE:"eb",APPROXIMATELY:"ap",CONTAINS:"contains",STARTS_WITH:"sw",EXACT:"exact",TEXT:"text",NOT:"not",ABOVE:"above",BELOW:"below",IN:"in",NOT_IN:"not-in",OF_TYPE:"of-type",MISSING:"missing",PRESENT:"present",IDENTIFIER:"identifier",ITERATE:"iterate"},lk={contains:he.CONTAINS,exact:he.EXACT,above:he.ABOVE,below:he.BELOW,text:he.TEXT,not:he.NOT,in:he.IN,"not-in":he.NOT_IN,"of-type":he.OF_TYPE,missing:he.MISSING,identifier:he.IDENTIFIER,iterate:he.ITERATE},mS={eq:he.EQUALS,ne:he.NOT_EQUALS,lt:he.LESS_THAN,le:he.LESS_THAN_OR_EQUALS,gt:he.GREATER_THAN,ge:he.GREATER_THAN_OR_EQUALS,sa:he.STARTS_AFTER,eb:he.ENDS_BEFORE,ap:he.APPROXIMATELY,sw:he.STARTS_WITH};function ck(e,t){if(!e)throw new Error("Invalid search URL");let n="",r;if(typeof e=="string")if(e.includes("?")){const[c,d]=e.split("?");n=c,r=new URLSearchParams(d)}else n=e;else typeof e=="object"&&(n=e.pathname,r=e.searchParams);let o;n.includes("/")?o=n.split("/").filter(Boolean).pop():o=n;const s=[];return r&&s.push(...r.entries()),pV(o,s)}function pV(e,t){const n={resourceType:e};for(const[r,o]of t)mV(n,r,o);return n}function mV(e,t,n){let r,o;const s=t.indexOf(":");if(s>=0?(r=t.substring(0,s),o=t.substring(s+1)):(r=t,o=""),r!=="_"){if(r==="_has"||t.includes(".")){e.filters=sd(e.filters,{code:t,operator:he.EQUALS,value:n});return}switch(r){case"_sort":gV(e,n);break;case"_cursor":e.cursor=n;break;case"_count":e.count=Number.parseInt(n,10);break;case"_offset":e.offset=Number.parseInt(n,10);break;case"_total":e.total=n;break;case"_summary":n==="count"?(e.total="accurate",e.count=0):(n==="true"||n==="data"||n==="text")&&(e.summary=n);break;case"_include":{const c=PT(n);o==="iterate"&&(c.modifier=he.ITERATE),e.include=sd(e.include,c);break}case"_revinclude":{const c=PT(n);o==="iterate"&&(c.modifier=he.ITERATE),e.revInclude=sd(e.revInclude,c);break}case"_fields":case"_elements":e.fields=n.split(",");break;case"_type":e.types=n.split(",");break;case"_format":e.format=n;break;case"_pretty":e.pretty=n==="true";break;default:{const c=Po.types[e.resourceType]?.searchParams?.[r];c?e.filters=sd(e.filters,yV(c,o,n)):e.filters=sd(e.filters,xV(r,o,n))}}}}function gV(e,t){for(const n of t.split(",")){let r,o=!1;n.startsWith("-")?(r=n.substring(1),o=!0):r=n,e.sortRules||(e.sortRules=[]),e.sortRules.push({code:r,descending:o})}}const vV=[he.MISSING,he.PRESENT];function yV(e,t,n){if(vV.includes(t))return{code:e.code,operator:t,value:n};switch(e.type){case"number":case"date":case"quantity":{const{operator:r,value:o}=bV(n,t||he.EQUALS);if(!NT(e,o))throw new vt(Eo(`Invalid format for ${e.type} search parameter: ${o}`));return{code:e.code,operator:r,value:o}}case"reference":case"string":case"token":case"uri":if(!NT(e,n))throw new vt(Eo(`Invalid format for ${e.type} search parameter: ${n}`));return{code:e.code,operator:SV(t),value:n};default:throw new Error("Unrecognized search parameter type: "+e.type)}}function xV(e,t,n){let r=he.EQUALS;if(t)r=t;else if(n.length>=2){const o=n.substring(0,2);o in mS&&(n.length===2||n.at(2)?.match(/\d/))&&(r=o,n=n.substring(o.length))}return{code:e,operator:r,value:n}}function bV(e,t){const n=e.substring(0,2),r=mS[n];return r?{operator:r,value:e.substring(2)}:{operator:t,value:e}}function SV(e){return lk[e]??he.EQUALS}function PT(e){const t=e.split(":");if(t.includes("*"))throw new vt(Eo("'*' is not supported as a value for search inclusion parameters"));if(t.length===1)throw new vt(Eo(`Invalid include value '${e}': must be of the form ResourceType:search-parameter`));if(t.length===2)return{resourceType:t[0],searchParam:t[1]};if(t.length===3)return{resourceType:t[0],searchParam:t[1],targetType:t[2]};throw new vt(Eo(`Invalid include value '${e}'`))}function NT(e,t){switch(e.type){case"date":return Pd(t);default:return!0}}function ps(e){const t=[];return e.fields&&t.push("_fields="+e.fields.join(",")),e.filters&&e.filters.forEach(n=>t.push(wV(n))),e.sortRules&&e.sortRules.length>0&&t.push(jV(e.sortRules)),e.cursor!==void 0&&t.push("_cursor="+encodeURIComponent(e.cursor)),e.offset!==void 0&&e.offset!==0&&t.push("_offset="+e.offset),e.count!==void 0&&t.push("_count="+e.count),e.total!==void 0&&t.push("_total="+e.total),e.types&&e.types.length>0&&t.push("_type="+e.types.join(",")),e.include&&e.include.forEach(n=>t.push(OT("_include",n))),e.revInclude&&e.revInclude.forEach(n=>t.push(OT("_revinclude",n))),t.length===0?"":(Qc(t),"?"+t.join("&"))}function wV(e){const t=e.operator in lk?":"+e.operator:"",n=e.operator!==he.EQUALS&&e.operator in mS?e.operator:"";return`${e.code}${t}=${n}${encodeURIComponent(e.value)}`}function jV(e){return"_sort="+e.map(t=>t.descending?"-"+t.code:t.code).join(",")}function OT(e,t){return e+(t.modifier?":"+t.modifier:"")+"="+t.resourceType+":"+t.searchParam+(t.targetType?":"+t.targetType:"")}function Hm(e){const t=[];let n="",r=!1;for(const o of e)r?(n+=o,r=!1):o==="\\"?r=!0:o===","?(t.push(n),n=""):n+=o;return t.push(n),t}function CV(e,t){if(t.resourceType!==e.resourceType)return!1;if(t.filters){for(const n of t.filters)if(!EV(e,t,n))return!1}return!0}function EV(e,t,n){const r=Po.types[t.resourceType]?.searchParams?.[n.code];if(!r)return!1;const o=bs(r.expression,[fi(e)]);if(n.operator===he.MISSING||n.operator===he.PRESENT)return TV(o,n);switch(r.type){case"reference":return RV(o,n);case"string":case"uri":return DV(o,n);case"token":return _V(o,n);case"date":return PV(o,n);default:return!1}}function TV(e,t){const n=e.length>0;return(t.operator===he.MISSING&&t.value==="false"||t.operator===he.PRESENT&&t.value==="true")===n}function RV(e,t){const n=qm(t.operator);if(t.value===""&&e.length===0)return t.operator===he.EQUALS;const r=lV(e);for(const o of Hm(t.value)){let s=r.includes(o);if(!s&&t.code==="_compartment"&&(s=r.some(c=>c?.endsWith("/"+o))),s)return!n}return n}function _V(e,t){const n=cV(e),r=Hm(t.value),o=qm(t.operator);for(const s of n)for(const c of r)if(AV(s,c))return!o;return o}function AV(e,t){if(t.includes("|")){const[n,r]=t.split("|").map(o=>o.toLowerCase());return!n&&!r?!1:n?e.system?.toLowerCase()===n&&(!r||e.value?.toLowerCase()===r):!e.system&&e.value?.toLowerCase()===r}return e.value?.toLowerCase()===t.toLowerCase()}function DV(e,t){const n=sV(e),r=Hm(t.value),o=qm(t.operator);for(const s of n)for(const c of r)if(kV(s,c))return!o;return o}function kV(e,t){return e.toLowerCase().includes(t.toLowerCase())}function PV(e,t){const n=aV(e),r=Hm(t.value),o=qm(t.operator);for(const s of n)for(const c of r)if(NV(s,t.operator,c))return!o;return o}function NV(e,t,n){if(!e)return!1;const r=QD(n);if(!r)return!1;const o=e.start??"0000",s=e.end??"9999",c=r.start,d=r.end;switch(t){case he.APPROXIMATELY:case he.EQUALS:case he.NOT_EQUALS:return o<d&&s>c;case he.LESS_THAN:return o<c;case he.GREATER_THAN:return s>d;case he.LESS_THAN_OR_EQUALS:return o<=d;case he.GREATER_THAN_OR_EQUALS:return s>=c;case he.STARTS_AFTER:return o>d;case he.ENDS_BEFORE:return s<c;default:return!1}}function qm(e){return e===he.NOT_EQUALS||e===he.NOT}const OV={resourceType:"*"},MV=["DomainConfiguration","JsonWebKey","Login"],LV=["UserSecurityRequest","Project","ProjectMembership","User"],sl={READ:"read",VREAD:"vread",UPDATE:"update",HISTORY:"history",SEARCH:"search"},IV=[sl.READ,sl.VREAD,sl.HISTORY,sl.SEARCH];function zV(e,t){return MV.includes(t)?!1:$V(e,sl.UPDATE,t)}function $V(e,t,n){return!!e.resource?.some(r=>dk(r,n,t))}function uk(e,t,n){return n?n.resource?.find(r=>UV(e,t,r)):OV}function UV(e,t,n){const r=e.resourceType;return dk(n,r,t)?r==="Binary"?!0:!(n.compartment&&!e.meta?.compartment?.some(o=>o.reference===n.compartment?.reference)||n.criteria&&!CV(e,ck(n.criteria))):!1}function dk(e,t,n){return e.resourceType!==t&&(e.resourceType!=="*"||LV.includes(t))?!1:e.interaction?e.interaction.includes(n):!e.readonly||IV.includes(n)}function xo(){return typeof window<"u"}function fk(){return typeof Buffer<"u"?Buffer:void 0}const nr={assign(e){xo()&&globalThis.location.assign(e)},reload(){xo()&&globalThis.location.reload()},getSearch(){return xo()?globalThis.location.search:""},getPathname(){return xo()?globalThis.location.pathname:""},getLocation(){return xo()?globalThis.location.toString():""},getOrigin(){return xo()?globalThis.location.protocol+"//"+globalThis.location.host+"/":""}};function BV(e){if(xo()){const n=window.atob(e),r=Uint8Array.from(n,o=>o.charCodeAt(0));return new window.TextDecoder().decode(r)}const t=fk();if(t)return t.from(e,"base64").toString("utf-8");throw new Error("Unable to decode base64")}function MT(e){if(xo()){const n=new window.TextEncoder().encode(e),r=String.fromCharCode.apply(null,n);return window.btoa(r)}const t=fk();if(t)return t.from(e,"utf8").toString("base64");throw new Error("Unable to encode base64")}function VV(e){e=e.padEnd(e.length+(4-e.length%4)%4,"=");const t=e.replaceAll("-","+").replaceAll("_","/");return BV(t)}function LT(){const e=new Uint32Array(28);return crypto.getRandomValues(e),cB(e.buffer)}async function FV(e){return crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))}function hk(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replaceAll(/[xy]/g,e=>{const t=Math.trunc(Math.random()*16);return(e==="x"?t:t&3|8).toString(16)})}function pk(e){const t={};e=hi(e);for(const o of e.entry||[]){const s=o.resource;if(!s)continue;s.meta!==void 0&&(delete s.meta.author,delete s.meta.compartment,delete s.meta.lastUpdated,delete s.meta.project,delete s.meta.versionId,Object.keys(s.meta).length===0&&delete s.meta);const c=s?.id;c&&(t[c]=hk(),o.fullUrl="urn:uuid:"+t[c],delete o.resource?.id)}const n=e.entry,r=JSON.stringify({resourceType:"Bundle",type:"transaction",entry:n?.map(o=>({fullUrl:o.fullUrl,request:{method:"POST",url:o.resource?.resourceType},resource:o.resource}))},(o,s)=>HV(o,s,t),2);return qV(JSON.parse(r))}function HV(e,t,n){if(e==="reference"&&typeof t=="string"){let r;if(t.includes("/")?r=t.split("/")[1]:t.startsWith("urn:uuid:")?r=t.slice(9):t.startsWith("#")&&(r=t.slice(1)),r){const o=n[r];if(o)return"urn:uuid:"+o}}return t}function qV(e){const t=QV(e),{sorted:n,cycles:r}=GV(t),o={},s=[];for(const d of e.entry??[])d.fullUrl?o[d.fullUrl]=d:s.push(d);const c=n.map(d=>o[d]);for(const d of r)for(const f of d){const p=o[f],m={...p,request:{...p.request,method:"PUT"}};c.push(m)}return c.push(...s),{...e,entry:c}}const Ec={NotVisited:"NotVisited",Visiting:"Visiting",Visited:"Visited"};function GV(e){const t=[],n={},r=[];for(const s of Object.keys(e))n[s]=Ec.NotVisited;function o(s,c){if(n[s]===Ec.Visited)return!0;if(n[s]===Ec.Visiting){const f=c.lastIndexOf(s);return f!==-1&&r.push(c.slice(f)),!0}n[s]=Ec.Visiting,c.push(s);let d=!1;for(const f of e[s])o(f,c)||(d=!0);return n[s]=Ec.Visited,c.pop(),t.unshift(s),!d}for(const s in e)n[s]===Ec.NotVisited&&o(s,[]);return{sorted:t,cycles:r}}function mk(e,t){for(const n in e)if(e[n]&&typeof e[n]=="object"){const r=e[n];if(_a(r)){const o=r.reference;o.startsWith("urn:uuid:")&&t(o)}else mk(r,t)}}function QV(e){const t={};for(const n of e.entry||[])n.fullUrl&&(t[n.fullUrl]=[]);for(const n of e.entry||[]){const r=n.fullUrl;n.resource&&mk(n.resource,o=>{t[o]&&t[o].push(r)})}return t}const nn={CSS:"text/css",DICOM:"application/dicom",FAVICON:"image/vnd.microsoft.icon",FHIR_JSON:"application/fhir+json",FORM_URL_ENCODED:"application/x-www-form-urlencoded",HL7_V2:"x-application/hl7-v2+er7",HTML:"text/html",JAVASCRIPT:"text/javascript",JSON:"application/json",JSON_PATCH:"application/json-patch+json",JWT:"application/jwt",MULTIPART_FORM_DATA:"multipart/form-data",PNG:"image/png",SCIM_JSON:"application/scim+json",SVG:"image/svg+xml",TEXT:"text/plain",TYPESCRIPT:"text/typescript",PING:"x-application/ping",XML:"text/xml",CDA_XML:"application/cda+xml",OCTET_STREAM:"application/octet-stream"};let WV=class{listeners;constructor(){this.listeners={}}addEventListener(t,n){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(n)}removeEventListener(t,n){const r=this.listeners[t];if(r){for(let o=0;o<r.length;o++)if(r[o]===n){r.splice(o,1);return}}}dispatchEvent(t){const n=this.listeners[t.type];if(n)for(const r of n)r.call(this,t);return!t.defaultPrevented}removeAllListeners(){this.listeners={}}listenerCount(t){return this.listeners[t]?.length??0}};class Gm{emitter=new WV;dispatchEvent(t){this.emitter.dispatchEvent(t)}addEventListener(t,n){this.emitter.addEventListener(t,n)}removeEventListener(t,n){this.emitter.removeEventListener(t,n)}removeAllListeners(){this.emitter.removeAllListeners()}listenerCount(t){return this.emitter.listenerCount(t)}}const Fx={"Patient-open":"Patient-open","Patient-close":"Patient-close","ImagingStudy-open":"ImagingStudy-open","ImagingStudy-close":"ImagingStudy-close","Encounter-open":"Encounter-open","Encounter-close":"Encounter-close","DiagnosticReport-open":"DiagnosticReport-open","DiagnosticReport-close":"DiagnosticReport-close","DiagnosticReport-select":"DiagnosticReport-select","DiagnosticReport-update":"DiagnosticReport-update",syncerror:"syncerror"},YV=["Patient","Encounter","ImagingStudy","DiagnosticReport","OperationOutcome","Bundle"],gS=["DiagnosticReport-update"];function KV(e){return gS.includes(e)}function XV(e){if(gS.includes(e))throw new vt(jn(`'context.version' is required for '${e}'.`))}const JV={"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 ZV(e){return YV.includes(e)}function gk(e){return!!e.endpoint}function IT(e){if(!vS(e))throw new vt(jn("subscriptionRequest must be an object conforming to SubscriptionRequest type."));const{channelType:t,mode:n,topic:r,events:o}=e,s={"hub.channel.type":t,"hub.mode":n,"hub.topic":r,"hub.events":o.join(",")};return gk(e)&&(s.endpoint=e.endpoint),new URLSearchParams(s).toString()}function vS(e){if(typeof e!="object")return!1;const{channelType:t,mode:n,topic:r,events:o}=e;if(!(t&&n&&r&&o)||typeof r!="string"||typeof o!="object"||!Array.isArray(o)||o.length<1||t!=="websocket"||n!=="subscribe"&&n!=="unsubscribe")return!1;for(const s of o)if(!Fx[s])return!1;return!(gk(e)&&!(typeof e.endpoint=="string"&&e.endpoint.startsWith("ws")))}function eF(e,t,n,r){if(typeof t!="object")throw new vt(jn(`context[${n}] is invalid. Context must contain a single valid FHIR resource! Resource is not an object.`));if(!(t.id&&typeof t.id=="string"))throw new vt(jn(`context[${n}] is invalid. Resource must contain a valid string ID.`));if(!t.resourceType)throw new vt(jn(`context[${n}] is invalid. Resource must contain a resource type. No resource type found.`));const o=r.resourceType;if(o!=="*"){if(!ZV(t.resourceType))throw new vt(jn(`context[${n}] is invalid. Resource must contain a valid FHIRcast resource type. Resource type is not a known resource type.`));if(o&&t.resourceType!==o)throw new vt(jn(`context[${n}] is invalid. context[${n}] for the '${e}' event should contain resource of type ${o}.`))}}function tF(e,t,n,r,o){if(o.set(t.key,(o.get(t.key)??0)+1),r.reference){if(!_a(t.reference))throw new vt(jn(`context[${n}] is invalid. Expected key '${t.key}' to be a reference.`))}else eF(e,t.resource,n,r)}function nF(e,t){const n=new Map,r=JV[e];for(let o=0;o<t.length;o++){const s=t[o].key;if(!r[s])throw new vt(jn(`Key '${s}' not found for event '${e}'. Make sure to add only valid keys.`));tF(e,t[o],o,r[s],n)}for(const[o,s]of Object.entries(r)){if(!(s.optional||n.has(o)))throw new vt(jn(`Missing required key '${o}' on context for '${e}' event.`));if(!s.manyAllowed&&(n.get(o)??0)>1)throw new vt(jn(`${n.get(o)} context entries with key '${o}' found for the '${e}' event when schema only allows for 1.`))}}function zT(e,t,n,r){if(!(e&&typeof e=="string"))throw new vt(jn("Must provide a topic."));if(!Fx[t])throw new vt(jn(`Must provide a valid FHIRcast event name. Supported events: ${Object.keys(Fx).join(", ")}`));if(typeof n!="object")throw new vt(jn("context must be a context object or array of context objects."));if(gS.includes(t)&&!r)throw new vt(jn(`The '${t}' event must contain a 'context.versionId'.`));const o=Array.isArray(n)?n:[n];return nF(t,o),{timestamp:new Date().toISOString(),id:hk(),event:{"hub.topic":e,"hub.event":t,context:o,...r?{"context.versionId":r}:{}}}}class rF extends Gm{subRequest;websocket;constructor(t){if(super(),this.subRequest=t,!t.endpoint)throw new vt(jn("Subscription request should contain an endpoint."));if(!vS(t))throw new vt(jn("Subscription request failed validation."));const n=new WebSocket(t.endpoint);n.addEventListener("open",()=>{this.dispatchEvent({type:"connect"}),n.addEventListener("message",r=>{const o=JSON.parse(r.data);if(o["hub.topic"])return;const s=o;s.event["hub.event"]!=="heartbeat"&&(this.dispatchEvent({type:"message",payload:s}),n.send(JSON.stringify({id:o?.id,timestamp:new Date().toISOString()})))}),n.addEventListener("close",()=>{this.dispatchEvent({type:"disconnect"})})}),this.websocket=n}disconnect(){this.websocket.close()}}function iF(e){return JSON.parse(VV(e))}function oF(e){return e.split(".").length===3}function yS(e){const[t,n,r]=e.split(".");return iF(n)}function aF(e){try{return typeof yS(e).login_id=="string"}catch{return!1}}function sF(e){try{const n=yS(e).exp;return typeof n=="number"?n*1e3:void 0}catch{return}}class lF{medplum;constructor(t){this.medplum=t}async get(t){return this.medplum.get(`keyvalue/v1/${t}`)}async set(t,n){await this.medplum.put(`keyvalue/v1/${t}`,n,nn.TEXT)}async delete(t){await this.medplum.delete(`keyvalue/v1/${t}`)}}class Gi{[Symbol.toStringTag]="ReadablePromise";suspender;status="pending";response;error;constructor(t){this.suspender=t.then(n=>(this.status="success",this.response=n,n),n=>{throw this.status="error",this.error=n,n})}isPending(){return this.status==="pending"}isOk(){return this.status==="success"}read(){switch(this.status){case"pending":throw this.suspender;case"error":throw this.error;default:return this.response}}then(t,n){return this.suspender.then(t,n)}catch(t){return this.suspender.catch(t)}finally(t){return this.suspender.finally(t)}}class cF{storage;prefix="";constructor(t,n=""){this.storage=t??globalThis.localStorage??new uF,this.prefix=n}makeKey(t){return this.prefix+t}clear(){this.storage===globalThis.localStorage&&this.prefix?Object.keys(this.storage).filter(t=>t.startsWith(this.prefix)).forEach(t=>{this.storage.removeItem(t)}):this.storage.clear()}getString(t){return this.storage.getItem(this.makeKey(t))??void 0}setString(t,n){n?this.storage.setItem(this.makeKey(t),n):this.storage.removeItem(this.makeKey(t))}getObject(t){const n=this.getString(t);return n?JSON.parse(n):void 0}setObject(t,n){this.setString(t,n?no(n):void 0)}}class uF{data;constructor(){this.data=new Map}get length(){return this.data.size}clear(){this.data.clear()}getItem(t){return this.data.get(t)??null}setItem(t,n){n?this.data.set(t,n):this.data.delete(t)}removeItem(t){this.data.delete(t)}key(t){return Array.from(this.data.keys())[t]}}const Lc={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let $T=!1;function dF(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");Lc.Event=globalThis.Event,Lc.ErrorEvent=class extends Event{message;error;constructor(t,n){super("error",n),this.message=t.message,this.error=t}},Lc.CloseEvent=class extends Event{code;reason;wasClean=!0;constructor(t=1e3,n="",r){super("close",r),this.code=t,this.reason=n}}}function fF(e,t){if(!e)throw new Error(t)}function Wh(e){return new e.constructor(e.type,e)}const Ys={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let UT=!1;class cs extends Gm{_ws;_retryCount=-1;_uptimeTimeout;_connectTimeout;_shouldReconnect=!0;_connectLock=!1;_binaryType;_closeCalled=!1;_messageQueue=[];_debugLogger=console.log.bind(console);_url;_protocols;_options;constructor(t,n,r={}){$T||(dF(),$T=!0),super(),this._url=t,this._protocols=n,this._options=r,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 cs.CONNECTING}get OPEN(){return cs.OPEN}get CLOSING(){return cs.CLOSING}get CLOSED(){return cs.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((n,r)=>(typeof r=="string"?n+=r.length:r instanceof Blob?n+=r.size:n+=r.byteLength,n),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?cs.CLOSED:cs.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}onclose=null;onerror=null;onmessage=null;onopen=null;close(t=1e3,n){if(this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(t,n)}reconnect(t,n){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(t,n),this._connect())}send(t){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",t),this._ws.send(t);else{const{maxEnqueuedMessages:n=Ys.maxEnqueuedMessages}=this._options;this._messageQueue.length<n&&(this._debug("enqueue",t),this._messageQueue.push(t))}}_debug(...t){this._options.debug&&this._debugLogger("RWS>",...t)}_getNextDelay(){const{reconnectionDelayGrowFactor:t=Ys.reconnectionDelayGrowFactor,minReconnectionDelay:n=Ys.minReconnectionDelay,maxReconnectionDelay:r=Ys.maxReconnectionDelay}=this._options;let o=0;return this._retryCount>0&&(o=n*Math.pow(t,this._retryCount-1),o>r&&(o=r)),this._debug("next delay",o),o}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=Ys.maxRetries,connectionTimeout:n=Ys.connectionTimeout}=this._options;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);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"&&!UT&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),UT=!0);const r=this._options.WebSocket||WebSocket;this._debug("connect",{url:this._url,protocols:this._protocols}),this._ws=this._protocols?new r(this._url,this._protocols):new r(this._url),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),n)}).catch(r=>{this._connectLock=!1,this._handleError(new Lc.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Lc.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new Lc.CloseEvent(t,n,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_handleOpen=t=>{this._debug("open event");const{minUptime:n=Ys.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),n),fF(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(r=>this._ws?.send(r)),this._messageQueue=[],this.onopen&&this.onopen(t),this.dispatchEvent(Wh(t))};_handleMessage=t=>{this._debug("message event"),this.onmessage&&this.onmessage(t),this.dispatchEvent(Wh(t))};_handleError=t=>{this._debug("error event",t.message),this._disconnect(void 0,t.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(t),this._debug("exec error listeners"),this.dispatchEvent(Wh(t)),this._connect()};_handleClose=t=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(t),this.dispatchEvent(Wh(t))};_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)}}const hF=5e3;class Hx extends Gm{criteria;constructor(...t){super(),this.criteria=new Set(t)}getCriteria(){return this.criteria}_addCriteria(t){this.criteria.add(t)}_removeCriteria(t){this.criteria.delete(t)}}class pF{criteria;emitter;refCount;subscriptionProps;subscriptionId;token;connecting=!1;constructor(t,n){this.criteria=t,this.emitter=new Hx(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class mF{medplum;ws;masterSubEmitter;criteriaEntries;criteriaEntriesBySubscriptionId;wsClosed;pingTimer=void 0;pingIntervalMs;waitingForPong=!1;currentProfile;constructor(t,n,r){if(!(t instanceof yk))throw new vt(jn("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new vt(jn("Not a valid URL"))}const s=r?.ReconnectingWebSocket?new r.ReconnectingWebSocket(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger}):new cs(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger});this.medplum=t,this.ws=s,this.masterSubEmitter=new Hx,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=r?.pingIntervalMs??hF,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{try{const r=JSON.parse(n.data);if(r.type==="pong"){this.waitingForPong=!1;return}const o=r,s=o?.entry?.[0]?.resource;if(s.type==="heartbeat"){this.masterSubEmitter?.dispatchEvent({type:"heartbeat",payload:o});return}if(s.type==="handshake"){const d=pl(s.subscription),f={type:"connect",payload:{subscriptionId:d}};this.masterSubEmitter?.dispatchEvent(f);const p=this.criteriaEntriesBySubscriptionId.get(d);if(!p){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}p.connecting=!1,p.emitter.dispatchEvent({...f});return}this.masterSubEmitter?.dispatchEvent({type:"message",payload:o});const c=this.criteriaEntriesBySubscriptionId.get(pl(s.subscription));if(!c){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}c.emitter.dispatchEvent({type:"message",payload:o})}catch(r){console.error(r);const o={type:"error",payload:r};this.masterSubEmitter?.dispatchEvent(o);for(const s of this.getAllCriteriaEmitters())s.dispatchEvent({...o})}}),t.addEventListener("error",()=>{const n={type:"error",payload:new vt(E8(new Error("WebSocket error")))};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n})}),t.addEventListener("close",()=>{const n={type:"close"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),this.masterSubEmitter?.removeAllListeners())}),t.addEventListener("open",()=>{const n={type:"open"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.refreshAllSubscriptions().catch(console.error),this.pingTimer||(this.pingTimer=setInterval(()=>{if(this.waitingForPong){this.waitingForPong=!1,t.reconnect();return}t.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0},this.pingIntervalMs))}),this.medplum.addEventListener("change",()=>{const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&this.currentProfile?.id!==n.id&&this.ws.reconnect(),this.currentProfile=n})}emitError(t,n){const r={type:"error",payload:n};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){const{subscriptionId:n}=t;if(n){const r={type:"disconnect",payload:{subscriptionId:n}};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){let n=t?.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${Ot(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:t.criteria})).id);const{parameter:r}=await this.medplum.get(`fhir/R4/Subscription/${n}/$get-ws-binding-token`),o=r?.find(c=>c.name==="token")?.valueString,s=r?.find(c=>c.name==="websocket-url")?.valueUrl;if(!o)throw new vt(jn("Failed to get token"));if(!s)throw new vt(jn("Failed to get URL from $get-ws-binding-token"));return[n,o]}maybeGetCriteriaEntry(t,n){const r=this.criteriaEntries.get(t);if(r){if(!n)return r.bareCriteria;for(const o of r.criteriaWithProps)if(ko(n,o.subscriptionProps))return o}}getAllCriteriaEmitters(){const t=[];for(const n of this.criteriaEntries.values()){n.bareCriteria&&t.push(n.bareCriteria.emitter);for(const r of n.criteriaWithProps)t.push(r.emitter)}return t}addCriteriaEntry(t){const{criteria:n,subscriptionProps:r}=t;let o;this.criteriaEntries.has(n)?o=this.criteriaEntries.get(n):(o={criteriaWithProps:[]},this.criteriaEntries.set(n,o)),r?o.criteriaWithProps.push(t):o.bareCriteria=t}removeCriteriaEntry(t){const{criteria:n,subscriptionProps:r,subscriptionId:o,token:s}=t;if(!this.criteriaEntries.has(n))return;const c=this.criteriaEntries.get(n);r?c.criteriaWithProps=c.criteriaWithProps.filter(d=>{const f=d.subscriptionProps;return!ko(r,f)}):c.bareCriteria=void 0,!c.bareCriteria&&c.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),this.masterSubEmitter?._removeCriteria(n)),o&&this.criteriaEntriesBySubscriptionId.delete(o),s&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:s}}))}async subscribeToCriteria(t){if(!(this.ws.readyState!==WebSocket.OPEN||t.connecting)){t.connecting=!0;try{const[n,r]=await this.getTokenForCriteria(t);t.subscriptionId=n,t.token=r,this.criteriaEntriesBySubscriptionId.set(n,t),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:r}}))}catch(n){console.error(Qe(n)),this.emitError(t,n),this.removeCriteriaEntry(t)}}}async refreshAllSubscriptions(){this.criteriaEntriesBySubscriptionId.clear();for(const t of this.criteriaEntries.values())for(const n of[...t.bareCriteria?[t.bareCriteria]:[],...t.criteriaWithProps])n.clearAttachedSubscription(),await this.subscribeToCriteria(n)}addCriteria(t,n){this.masterSubEmitter&&this.masterSubEmitter._addCriteria(t);const r=this.maybeGetCriteriaEntry(t,n);if(r)return r.refCount+=1,r.emitter;const o=new pF(t,n);return this.addCriteriaEntry(o),this.subscribeToCriteria(o).catch(console.error),o.emitter}removeCriteria(t,n){const r=this.maybeGetCriteriaEntry(t,n);if(!r){console.warn("Criteria not known to `SubscriptionManager`. Possibly called remove too many times.");return}r.refCount-=1,!(r.refCount>0)&&(this.maybeEmitDisconnect(r),this.removeCriteriaEntry(r))}getWebSocket(){return this.ws}closeWebSocket(){this.wsClosed||(this.wsClosed=!0,this.ws.close())}reconnectWebSocket(){this.ws.reconnect(),this.wsClosed=!1}getCriteriaCount(){return this.getAllCriteriaEmitters().length}getMasterEmitter(){return this.masterSubEmitter||(this.masterSubEmitter=new Hx(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const vk="5.0.6-697ed2e",gF=nn.FHIR_JSON+", */*; q=0.1",vF="https://api.medplum.com/",yF=1e3,xF=6e4,bF=0,SF=3e5,wF="Binary/",BT={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},Tc={ClientCredentials:"client_credentials",AuthorizationCode:"authorization_code",RefreshToken:"refresh_token",JwtBearer:"urn:ietf:params:oauth:grant-type:jwt-bearer",TokenExchange:"urn:ietf:params:oauth:grant-type:token-exchange"},jF={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},CF={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class yk extends Gm{options;fetch;createPdfImpl;storage;requestCache;cacheTime;baseUrl;fhirBaseUrl;authorizeUrl;tokenUrl;logoutUrl;fhircastHubUrl;defaultHeaders;onUnauthenticated;autoBatchTime;autoBatchQueue;refreshGracePeriod;subscriptionManager;medplumServer;clientId;clientSecret;credentialsInHeader;autoBatchTimerId;accessToken;accessTokenExpires;refreshToken;refreshPromise;profilePromise;sessionDetails;currentRateLimits;basicAuth;initPromise;initComplete=!0;keyValueClient;constructor(t){if(super(),t?.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=t?.fetch??EF(),this.storage=t?.storage??new cF(void 0,t?.storagePrefix),this.createPdfImpl=t?.createPdf,this.baseUrl=sS(t?.baseUrl??vF),this.fhirBaseUrl=vo(this.baseUrl,t?.fhirUrlPath??"fhir/R4"),this.authorizeUrl=vo(this.baseUrl,t?.authorizeUrl??"oauth2/authorize"),this.tokenUrl=vo(this.baseUrl,t?.tokenUrl??"oauth2/token"),this.logoutUrl=vo(this.baseUrl,t?.logoutUrl??"oauth2/logout"),this.fhircastHubUrl=vo(this.baseUrl,t?.fhircastHubUrl??"fhircast/STU3"),this.clientId=t?.clientId??"",this.clientSecret=t?.clientSecret??"",this.credentialsInHeader=t?.authCredentialsMethod==="header",this.defaultHeaders=t?.defaultHeaders??{},this.onUnauthenticated=t?.onUnauthenticated,this.refreshGracePeriod=t?.refreshGracePeriod??SF,this.cacheTime=t?.cacheTime??(xo()?xF:bF),this.cacheTime>0?this.requestCache=new DD(t?.resourceCacheSize??yF):this.requestCache=void 0,t?.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t?.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t?.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(()=>{t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}async attemptResumeActiveLogin(){const t=this.getActiveLogin();t&&(this.setAccessToken(t.accessToken,t.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}getFhircastHubUrl(){return this.fhircastHubUrl}getDefaultHeaders(){return this.defaultHeaders}clear(){this.storage.clear(),xo()&&sessionStorage.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.sessionDetails=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(t){t=t.toString(),this.requestCache?.delete(t)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(t){const n=vo(this.fhirBaseUrl,t);if(this.requestCache)for(const r of this.requestCache.keys())(r.endsWith(n)||r.includes(n+"?"))&&this.requestCache.delete(r)}get(t,n={}){t=t.toString();const r=this.getCacheEntry(t,n);if(r)return r.value;let o;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?o=new Promise((c,d)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:c,reject:d}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):o=this.request("GET",t,n);const s=new Gi(o);return this.setCacheEntry(t,s),s}post(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("POST",t,o)}put(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("PUT",t,o)}patch(t,n,r={}){return t=t.toString(),this.setRequestBody(r,n),this.setRequestContentType(r,nn.JSON_PATCH),this.invalidateUrl(t),this.request("PATCH",t,r)}delete(t,n){return t=t.toString(),this.invalidateUrl(t),this.request("DELETE",t,n)}async startNewUser(t,n){const{codeChallengeMethod:r,codeChallenge:o}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:r,codeChallenge:o},void 0,n)}async startNewProject(t,n){return this.post("auth/newproject",t,void 0,n)}async startNewPatient(t,n){return this.post("auth/newpatient",t,void 0,n)}async startLogin(t,n){return this.post("auth/login",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async startGoogleLogin(t,n){return this.post("auth/google",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async ensureCodeChallenge(t){return t.codeChallenge?t:{...t,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(t){const r=new URLSearchParams(nr.getSearch()).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){nr.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,o,s=!0){let c=o;s&&(c=await this.ensureCodeChallenge(o)),nr.assign(this.getExternalAuthRedirectUri(t,n,r,c,s))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");return this.fetchTokens({grant_type:Tc.TokenExchange,subject_token_type:jF.AccessToken,client_id:n,subject_token:t})}getExternalAuthRedirectUri(t,n,r,o,s=!0){const c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",n),c.searchParams.set("redirect_uri",r),c.searchParams.set("scope",o.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(o)),s){const{codeChallenge:d,codeChallengeMethod:f}=o;if(!f)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!d)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");c.searchParams.set("code_challenge_method",f),c.searchParams.set("code_challenge",d)}return c.toString()}fhirUrl(...t){return new URL(vo(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=gB(n)),r}search(t,n,r){const o=this.fhirSearchUrl(t,n),s="search-"+o.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=this.getBundle(o,r);return this.setCacheEntry(s,d),d}searchOne(t,n,r){const o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();const s="searchOne-"+o.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=new Gi(this.search(t,o.searchParams,r).then(f=>f.entry?.[0]?.resource));return this.setCacheEntry(s,d),d}searchResources(t,n,r){const s="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=new Gi(this.search(t,n,r).then(FT));return this.setCacheEntry(s,d),d}async*searchResourcePages(t,n,r){let o=this.fhirSearchUrl(t,n);for(;o;){const s=new URL(o).searchParams;s.has("_count")||s.set("_count","1000");const c=await this.search(t,s,r),d=c.link?.find(f=>f.relation==="next");if(!c.entry?.length&&!d)break;yield FT(c),o=d?.url?new URL(d.url):void 0}}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){const r=this.requestCache?.get(this.fhirUrl(t,n).toString())?.value;return r?.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return BT;const[r,o]=n.split("/");if(!(!r||!o))return this.getCached(r,o)}readResource(t,n,r){if(!n)throw new Error('The "id" parameter cannot be null, undefined, or an empty string.');return this.get(this.fhirUrl(t,n),r)}readReference(t,n){const r=t.reference;if(!r)return new Gi(Promise.reject(new Error("Missing reference")));if(r==="system")return new Gi(Promise.resolve(BT));const[o,s]=r.split("/");return!o||!s?new Gi(Promise.reject(new Error("Invalid reference"))):this.readResource(o,s,n)}requestSchema(t){if(ID(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Gi((async()=>{const s=`{
|
|
59
|
+
`?(this.pos.line++,this.pos.column=0):this.pos.column++}buildToken(t,n){const r=this.markStack.pop();if(!r)throw new Error("No mark for token");return{id:t,value:n,...r}}}function YB(e){return!!(e&&(e.id==="String"||e.id==="Symbol"&&GB.includes(e.value)))}const KB=["true","false"],XB=["!=","!~","<=",">=","{}","->"];function JB(e){return new WB(e,KB,XB).tokenize()}const tn={FunctionCall:0,Dot:1,Indexer:2,UnaryAdd:3,UnarySubtract:3,Multiply:4,Divide:4,Modulo:4,Add:5,Subtract:5,Ampersand:5,Is:6,As:6,Union:7,GreaterThan:8,GreaterThanOrEquals:8,LessThan:8,LessThanOrEquals:8,Equals:9,Equivalent:9,NotEquals:9,NotEquivalent:9,In:10,Contains:10,And:11,Xor:12,Or:12,Implies:13},ZB={parse(e){const t=e.consumeAndParse();if(!e.match(")"))throw new Error("Parse error: expected `)` got `"+e.peek()?.value+"`");return t}},eV={parse(e,t){const n=e.consumeAndParse();if(!e.match("]"))throw new Error("Parse error: expected `]`");return new hS(t,n)},precedence:tn.Indexer},tV={parse(e,t){if(!(t instanceof Md))throw new Error("Unexpected parentheses");const n=[];for(;!e.match(")");)n.push(e.consumeAndParse()),e.match(",");return new fS(t.name,n)},precedence:tn.FunctionCall};function nV(e){const t=e.split(" "),n=Number.parseFloat(t[0]);let r=t[1];return r?.startsWith("'")&&r.endsWith("'")?r=r.substring(1,r.length-1):r="{"+r+"}",{value:n,unit:r}}function rV(){return new h8().registerPrefix("String",{parse:(e,t)=>new Cc({type:ne.string,value:t.value})}).registerPrefix("DateTime",{parse:(e,t)=>new Cc({type:ne.dateTime,value:dp(t.value)})}).registerPrefix("Quantity",{parse:(e,t)=>new Cc({type:ne.Quantity,value:nV(t.value)})}).registerPrefix("Number",{parse:(e,t)=>new Cc({type:t.value.includes(".")?ne.decimal:ne.integer,value:Number.parseFloat(t.value)})}).registerPrefix("true",{parse:()=>new Cc({type:ne.boolean,value:!0})}).registerPrefix("false",{parse:()=>new Cc({type:ne.boolean,value:!1})}).registerPrefix("Symbol",{parse:(e,t)=>new Md(t.value)}).registerPrefix("{}",{parse:()=>new NB}).registerPrefix("(",ZB).registerInfix("[",eV).registerInfix("(",tV).prefix("+",tn.UnaryAdd,(e,t)=>new OB("+",t,n=>n)).prefix("-",tn.UnarySubtract,(e,t)=>new qi("-",t,t,(n,r)=>-r)).infixLeft(".",tn.Dot,(e,t,n)=>new Vm(e,n)).infixLeft("/",tn.Divide,(e,t,n)=>new qi("/",e,n,(r,o)=>r/o)).infixLeft("*",tn.Multiply,(e,t,n)=>new qi("*",e,n,(r,o)=>r*o)).infixLeft("+",tn.Add,(e,t,n)=>new qi("+",e,n,(r,o)=>r+o)).infixLeft("-",tn.Subtract,(e,t,n)=>new qi("-",e,n,(r,o)=>r-o)).infixLeft("|",tn.Union,(e,t,n)=>new uS(e,n)).infixLeft("=",tn.Equals,(e,t,n)=>new zB(e,n)).infixLeft("!=",tn.NotEquals,(e,t,n)=>new $B(e,n)).infixLeft("~",tn.Equivalent,(e,t,n)=>new UB(e,n)).infixLeft("!~",tn.NotEquivalent,(e,t,n)=>new BB(e,n)).infixLeft("<",tn.LessThan,(e,t,n)=>new qi("<",e,n,(r,o)=>r<o)).infixLeft("<=",tn.LessThanOrEquals,(e,t,n)=>new qi("<=",e,n,(r,o)=>r<=o)).infixLeft(">",tn.GreaterThan,(e,t,n)=>new qi(">",e,n,(r,o)=>r>o)).infixLeft(">=",tn.GreaterThanOrEquals,(e,t,n)=>new qi(">=",e,n,(r,o)=>r>=o)).infixLeft("&",tn.Ampersand,(e,t,n)=>new MB(e,n)).infixLeft("and",tn.And,(e,t,n)=>new VB(e,n)).infixLeft("as",tn.As,(e,t,n)=>new Dp(e,n)).infixLeft("contains",tn.Contains,(e,t,n)=>new LB(e,n)).infixLeft("div",tn.Divide,(e,t,n)=>new qi("div",e,n,(r,o)=>Math.trunc(r/o))).infixLeft("in",tn.In,(e,t,n)=>new IB(e,n)).infixLeft("is",tn.Is,(e,t,n)=>new dS(e,n)).infixLeft("mod",tn.Modulo,(e,t,n)=>new qi("mod",e,n,(r,o)=>r%o)).infixLeft("or",tn.Or,(e,t,n)=>new FB(e,n)).infixLeft("xor",tn.Xor,(e,t,n)=>new HB(e,n)).infixLeft("implies",tn.Implies,(e,t,n)=>new qB(e,n))}const iV=rV();function pS(e){return new cS(e,iV.construct(JB(e)).consumeAndParse())}function oV(e,t){const n=Array.isArray(t)?t:[t];for(let r=0;r<n.length;r++){const o=n[r];typeof o=="object"&&"type"in o&&"value"in o||(n[r]=fi(n[r]))}return bs(e,n).map(r=>r.value)}function bs(e,t,n={},r=void 0){let o;if(typeof e=="string"){const s=r?.get(e);o=s??pS(e),r&&!s&&r.set(e,o)}else o=e;return o.eval({variables:n},t).map(s=>{const c={type:s.type,value:s.value?.valueOf()};return"path"in s&&(c.path=s.path),c})}function aV(e){const t=[];for(const n of e){const r=QD(n.value);r&&t.push(r)}return t}function sV(e){const t=new Set;for(const n of e){const r=ml(n);r&&t.add(r)}return Array.from(t)}function lV(e){const t=new Set;for(const n of e){const{value:r}=n;r&&(sB(r)?t.add(r):_a(r)?t.add(r.reference):YD(r)?t.add(Ot(r)):typeof r.identifier=="object"&&t.add(`identifier:${r.identifier.system}|${r.identifier.value}`))}return Array.from(t)}function cV(e,t={}){const n=[];for(const r of e)uV(t,n,r);return n}function uV(e,t,n){const{type:r,value:o}=n;switch(r){case ne.Identifier:dV(t,e,o);break;case ne.CodeableConcept:fV(t,e,o);break;case ne.Coding:sk(t,e,o);break;case ne.ContactPoint:hV(t,e,o);break;default:vl(t,e,void 0,o?.toString())}}function dV(e,t,n){n?.type?.text&&vl(e,t,t.textSearchSystem,n.type.text),vl(e,t,n?.system,n?.value)}function fV(e,t,n){if(n?.text&&vl(e,t,t.textSearchSystem,n.text),n?.coding)for(const r of n.coding)sk(e,t,r)}function sk(e,t,n){n&&(n.display&&vl(e,t,t.textSearchSystem,n.display),vl(e,t,n.system,n.code))}function hV(e,t,n){n&&vl(e,t,n.system,n.value?.toLocaleLowerCase())}function vl(e,t,n,r){(n||r)&&!e.some(o=>o.system===n&&o.value===r)&&e.push({system:n,value:r&&t.caseInsensitive?r.toLocaleLowerCase():r})}const Fm=20,he={EQUALS:"eq",NOT_EQUALS:"ne",GREATER_THAN:"gt",LESS_THAN:"lt",GREATER_THAN_OR_EQUALS:"ge",LESS_THAN_OR_EQUALS:"le",STARTS_AFTER:"sa",ENDS_BEFORE:"eb",APPROXIMATELY:"ap",CONTAINS:"contains",STARTS_WITH:"sw",EXACT:"exact",TEXT:"text",NOT:"not",ABOVE:"above",BELOW:"below",IN:"in",NOT_IN:"not-in",OF_TYPE:"of-type",MISSING:"missing",PRESENT:"present",IDENTIFIER:"identifier",ITERATE:"iterate"},lk={contains:he.CONTAINS,exact:he.EXACT,above:he.ABOVE,below:he.BELOW,text:he.TEXT,not:he.NOT,in:he.IN,"not-in":he.NOT_IN,"of-type":he.OF_TYPE,missing:he.MISSING,identifier:he.IDENTIFIER,iterate:he.ITERATE},mS={eq:he.EQUALS,ne:he.NOT_EQUALS,lt:he.LESS_THAN,le:he.LESS_THAN_OR_EQUALS,gt:he.GREATER_THAN,ge:he.GREATER_THAN_OR_EQUALS,sa:he.STARTS_AFTER,eb:he.ENDS_BEFORE,ap:he.APPROXIMATELY,sw:he.STARTS_WITH};function ck(e,t){if(!e)throw new Error("Invalid search URL");let n="",r;if(typeof e=="string")if(e.includes("?")){const[c,d]=e.split("?");n=c,r=new URLSearchParams(d)}else n=e;else typeof e=="object"&&(n=e.pathname,r=e.searchParams);let o;n.includes("/")?o=n.split("/").filter(Boolean).pop():o=n;const s=[];return r&&s.push(...r.entries()),pV(o,s)}function pV(e,t){const n={resourceType:e};for(const[r,o]of t)mV(n,r,o);return n}function mV(e,t,n){let r,o;const s=t.indexOf(":");if(s>=0?(r=t.substring(0,s),o=t.substring(s+1)):(r=t,o=""),r!=="_"){if(r==="_has"||t.includes(".")){e.filters=sd(e.filters,{code:t,operator:he.EQUALS,value:n});return}switch(r){case"_sort":gV(e,n);break;case"_cursor":e.cursor=n;break;case"_count":e.count=Number.parseInt(n,10);break;case"_offset":e.offset=Number.parseInt(n,10);break;case"_total":e.total=n;break;case"_summary":n==="count"?(e.total="accurate",e.count=0):(n==="true"||n==="data"||n==="text")&&(e.summary=n);break;case"_include":{const c=PT(n);o==="iterate"&&(c.modifier=he.ITERATE),e.include=sd(e.include,c);break}case"_revinclude":{const c=PT(n);o==="iterate"&&(c.modifier=he.ITERATE),e.revInclude=sd(e.revInclude,c);break}case"_fields":case"_elements":e.fields=n.split(",");break;case"_type":e.types=n.split(",");break;case"_format":e.format=n;break;case"_pretty":e.pretty=n==="true";break;default:{const c=Po.types[e.resourceType]?.searchParams?.[r];c?e.filters=sd(e.filters,yV(c,o,n)):e.filters=sd(e.filters,xV(r,o,n))}}}}function gV(e,t){for(const n of t.split(",")){let r,o=!1;n.startsWith("-")?(r=n.substring(1),o=!0):r=n,e.sortRules||(e.sortRules=[]),e.sortRules.push({code:r,descending:o})}}const vV=[he.MISSING,he.PRESENT];function yV(e,t,n){if(vV.includes(t))return{code:e.code,operator:t,value:n};switch(e.type){case"number":case"date":case"quantity":{const{operator:r,value:o}=bV(n,t||he.EQUALS);if(!NT(e,o))throw new vt(Eo(`Invalid format for ${e.type} search parameter: ${o}`));return{code:e.code,operator:r,value:o}}case"reference":case"string":case"token":case"uri":if(!NT(e,n))throw new vt(Eo(`Invalid format for ${e.type} search parameter: ${n}`));return{code:e.code,operator:SV(t),value:n};default:throw new Error("Unrecognized search parameter type: "+e.type)}}function xV(e,t,n){let r=he.EQUALS;if(t)r=t;else if(n.length>=2){const o=n.substring(0,2);o in mS&&(n.length===2||n.at(2)?.match(/\d/))&&(r=o,n=n.substring(o.length))}return{code:e,operator:r,value:n}}function bV(e,t){const n=e.substring(0,2),r=mS[n];return r?{operator:r,value:e.substring(2)}:{operator:t,value:e}}function SV(e){return lk[e]??he.EQUALS}function PT(e){const t=e.split(":");if(t.includes("*"))throw new vt(Eo("'*' is not supported as a value for search inclusion parameters"));if(t.length===1)throw new vt(Eo(`Invalid include value '${e}': must be of the form ResourceType:search-parameter`));if(t.length===2)return{resourceType:t[0],searchParam:t[1]};if(t.length===3)return{resourceType:t[0],searchParam:t[1],targetType:t[2]};throw new vt(Eo(`Invalid include value '${e}'`))}function NT(e,t){switch(e.type){case"date":return Pd(t);default:return!0}}function ps(e){const t=[];return e.fields&&t.push("_fields="+e.fields.join(",")),e.filters&&e.filters.forEach(n=>t.push(wV(n))),e.sortRules&&e.sortRules.length>0&&t.push(jV(e.sortRules)),e.cursor!==void 0&&t.push("_cursor="+encodeURIComponent(e.cursor)),e.offset!==void 0&&e.offset!==0&&t.push("_offset="+e.offset),e.count!==void 0&&t.push("_count="+e.count),e.total!==void 0&&t.push("_total="+e.total),e.types&&e.types.length>0&&t.push("_type="+e.types.join(",")),e.include&&e.include.forEach(n=>t.push(OT("_include",n))),e.revInclude&&e.revInclude.forEach(n=>t.push(OT("_revinclude",n))),t.length===0?"":(Qc(t),"?"+t.join("&"))}function wV(e){const t=e.operator in lk?":"+e.operator:"",n=e.operator!==he.EQUALS&&e.operator in mS?e.operator:"";return`${e.code}${t}=${n}${encodeURIComponent(e.value)}`}function jV(e){return"_sort="+e.map(t=>t.descending?"-"+t.code:t.code).join(",")}function OT(e,t){return e+(t.modifier?":"+t.modifier:"")+"="+t.resourceType+":"+t.searchParam+(t.targetType?":"+t.targetType:"")}function Hm(e){const t=[];let n="",r=!1;for(const o of e)r?(n+=o,r=!1):o==="\\"?r=!0:o===","?(t.push(n),n=""):n+=o;return t.push(n),t}function CV(e,t){if(t.resourceType!==e.resourceType)return!1;if(t.filters){for(const n of t.filters)if(!EV(e,t,n))return!1}return!0}function EV(e,t,n){const r=Po.types[t.resourceType]?.searchParams?.[n.code];if(!r)return!1;const o=bs(r.expression,[fi(e)]);if(n.operator===he.MISSING||n.operator===he.PRESENT)return TV(o,n);switch(r.type){case"reference":return RV(o,n);case"string":case"uri":return DV(o,n);case"token":return _V(o,n);case"date":return PV(o,n);default:return!1}}function TV(e,t){const n=e.length>0;return(t.operator===he.MISSING&&t.value==="false"||t.operator===he.PRESENT&&t.value==="true")===n}function RV(e,t){const n=qm(t.operator);if(t.value===""&&e.length===0)return t.operator===he.EQUALS;const r=lV(e);for(const o of Hm(t.value)){let s=r.includes(o);if(!s&&t.code==="_compartment"&&(s=r.some(c=>c?.endsWith("/"+o))),s)return!n}return n}function _V(e,t){const n=cV(e),r=Hm(t.value),o=qm(t.operator);for(const s of n)for(const c of r)if(AV(s,c))return!o;return o}function AV(e,t){if(t.includes("|")){const[n,r]=t.split("|").map(o=>o.toLowerCase());return!n&&!r?!1:n?e.system?.toLowerCase()===n&&(!r||e.value?.toLowerCase()===r):!e.system&&e.value?.toLowerCase()===r}return e.value?.toLowerCase()===t.toLowerCase()}function DV(e,t){const n=sV(e),r=Hm(t.value),o=qm(t.operator);for(const s of n)for(const c of r)if(kV(s,c))return!o;return o}function kV(e,t){return e.toLowerCase().includes(t.toLowerCase())}function PV(e,t){const n=aV(e),r=Hm(t.value),o=qm(t.operator);for(const s of n)for(const c of r)if(NV(s,t.operator,c))return!o;return o}function NV(e,t,n){if(!e)return!1;const r=QD(n);if(!r)return!1;const o=e.start??"0000",s=e.end??"9999",c=r.start,d=r.end;switch(t){case he.APPROXIMATELY:case he.EQUALS:case he.NOT_EQUALS:return o<d&&s>c;case he.LESS_THAN:return o<c;case he.GREATER_THAN:return s>d;case he.LESS_THAN_OR_EQUALS:return o<=d;case he.GREATER_THAN_OR_EQUALS:return s>=c;case he.STARTS_AFTER:return o>d;case he.ENDS_BEFORE:return s<c;default:return!1}}function qm(e){return e===he.NOT_EQUALS||e===he.NOT}const OV={resourceType:"*"},MV=["DomainConfiguration","JsonWebKey","Login"],LV=["UserSecurityRequest","Project","ProjectMembership","User"],sl={READ:"read",VREAD:"vread",UPDATE:"update",HISTORY:"history",SEARCH:"search"},IV=[sl.READ,sl.VREAD,sl.HISTORY,sl.SEARCH];function zV(e,t){return MV.includes(t)?!1:$V(e,sl.UPDATE,t)}function $V(e,t,n){return!!e.resource?.some(r=>dk(r,n,t))}function uk(e,t,n){return n?n.resource?.find(r=>UV(e,t,r)):OV}function UV(e,t,n){const r=e.resourceType;return dk(n,r,t)?r==="Binary"?!0:!(n.compartment&&!e.meta?.compartment?.some(o=>o.reference===n.compartment?.reference)||n.criteria&&!CV(e,ck(n.criteria))):!1}function dk(e,t,n){return e.resourceType!==t&&(e.resourceType!=="*"||LV.includes(t))?!1:e.interaction?e.interaction.includes(n):!e.readonly||IV.includes(n)}function xo(){return typeof window<"u"}function fk(){return typeof Buffer<"u"?Buffer:void 0}const nr={assign(e){xo()&&globalThis.location.assign(e)},reload(){xo()&&globalThis.location.reload()},getSearch(){return xo()?globalThis.location.search:""},getPathname(){return xo()?globalThis.location.pathname:""},getLocation(){return xo()?globalThis.location.toString():""},getOrigin(){return xo()?globalThis.location.protocol+"//"+globalThis.location.host+"/":""}};function BV(e){if(xo()){const n=window.atob(e),r=Uint8Array.from(n,o=>o.charCodeAt(0));return new window.TextDecoder().decode(r)}const t=fk();if(t)return t.from(e,"base64").toString("utf-8");throw new Error("Unable to decode base64")}function MT(e){if(xo()){const n=new window.TextEncoder().encode(e),r=String.fromCharCode.apply(null,n);return window.btoa(r)}const t=fk();if(t)return t.from(e,"utf8").toString("base64");throw new Error("Unable to encode base64")}function VV(e){e=e.padEnd(e.length+(4-e.length%4)%4,"=");const t=e.replaceAll("-","+").replaceAll("_","/");return BV(t)}function LT(){const e=new Uint32Array(28);return crypto.getRandomValues(e),cB(e.buffer)}async function FV(e){return crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))}function hk(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replaceAll(/[xy]/g,e=>{const t=Math.trunc(Math.random()*16);return(e==="x"?t:t&3|8).toString(16)})}function pk(e){const t={};e=hi(e);for(const o of e.entry||[]){const s=o.resource;if(!s)continue;s.meta!==void 0&&(delete s.meta.author,delete s.meta.compartment,delete s.meta.lastUpdated,delete s.meta.project,delete s.meta.versionId,Object.keys(s.meta).length===0&&delete s.meta);const c=s?.id;c&&(t[c]=hk(),o.fullUrl="urn:uuid:"+t[c],delete o.resource?.id)}const n=e.entry,r=JSON.stringify({resourceType:"Bundle",type:"transaction",entry:n?.map(o=>({fullUrl:o.fullUrl,request:{method:"POST",url:o.resource?.resourceType},resource:o.resource}))},(o,s)=>HV(o,s,t),2);return qV(JSON.parse(r))}function HV(e,t,n){if(e==="reference"&&typeof t=="string"){let r;if(t.includes("/")?r=t.split("/")[1]:t.startsWith("urn:uuid:")?r=t.slice(9):t.startsWith("#")&&(r=t.slice(1)),r){const o=n[r];if(o)return"urn:uuid:"+o}}return t}function qV(e){const t=QV(e),{sorted:n,cycles:r}=GV(t),o={},s=[];for(const d of e.entry??[])d.fullUrl?o[d.fullUrl]=d:s.push(d);const c=n.map(d=>o[d]);for(const d of r)for(const f of d){const p=o[f],m={...p,request:{...p.request,method:"PUT"}};c.push(m)}return c.push(...s),{...e,entry:c}}const Ec={NotVisited:"NotVisited",Visiting:"Visiting",Visited:"Visited"};function GV(e){const t=[],n={},r=[];for(const s of Object.keys(e))n[s]=Ec.NotVisited;function o(s,c){if(n[s]===Ec.Visited)return!0;if(n[s]===Ec.Visiting){const f=c.lastIndexOf(s);return f!==-1&&r.push(c.slice(f)),!0}n[s]=Ec.Visiting,c.push(s);let d=!1;for(const f of e[s])o(f,c)||(d=!0);return n[s]=Ec.Visited,c.pop(),t.unshift(s),!d}for(const s in e)n[s]===Ec.NotVisited&&o(s,[]);return{sorted:t,cycles:r}}function mk(e,t){for(const n in e)if(e[n]&&typeof e[n]=="object"){const r=e[n];if(_a(r)){const o=r.reference;o.startsWith("urn:uuid:")&&t(o)}else mk(r,t)}}function QV(e){const t={};for(const n of e.entry||[])n.fullUrl&&(t[n.fullUrl]=[]);for(const n of e.entry||[]){const r=n.fullUrl;n.resource&&mk(n.resource,o=>{t[o]&&t[o].push(r)})}return t}const nn={CSS:"text/css",DICOM:"application/dicom",FAVICON:"image/vnd.microsoft.icon",FHIR_JSON:"application/fhir+json",FORM_URL_ENCODED:"application/x-www-form-urlencoded",HL7_V2:"x-application/hl7-v2+er7",HTML:"text/html",JAVASCRIPT:"text/javascript",JSON:"application/json",JSON_PATCH:"application/json-patch+json",JWT:"application/jwt",MULTIPART_FORM_DATA:"multipart/form-data",PNG:"image/png",SCIM_JSON:"application/scim+json",SVG:"image/svg+xml",TEXT:"text/plain",TYPESCRIPT:"text/typescript",PING:"x-application/ping",XML:"text/xml",CDA_XML:"application/cda+xml",OCTET_STREAM:"application/octet-stream"};let WV=class{listeners;constructor(){this.listeners={}}addEventListener(t,n){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(n)}removeEventListener(t,n){const r=this.listeners[t];if(r){for(let o=0;o<r.length;o++)if(r[o]===n){r.splice(o,1);return}}}dispatchEvent(t){const n=this.listeners[t.type];if(n)for(const r of n)r.call(this,t);return!t.defaultPrevented}removeAllListeners(){this.listeners={}}listenerCount(t){return this.listeners[t]?.length??0}};class Gm{emitter=new WV;dispatchEvent(t){this.emitter.dispatchEvent(t)}addEventListener(t,n){this.emitter.addEventListener(t,n)}removeEventListener(t,n){this.emitter.removeEventListener(t,n)}removeAllListeners(){this.emitter.removeAllListeners()}listenerCount(t){return this.emitter.listenerCount(t)}}const Fx={"Patient-open":"Patient-open","Patient-close":"Patient-close","ImagingStudy-open":"ImagingStudy-open","ImagingStudy-close":"ImagingStudy-close","Encounter-open":"Encounter-open","Encounter-close":"Encounter-close","DiagnosticReport-open":"DiagnosticReport-open","DiagnosticReport-close":"DiagnosticReport-close","DiagnosticReport-select":"DiagnosticReport-select","DiagnosticReport-update":"DiagnosticReport-update",syncerror:"syncerror"},YV=["Patient","Encounter","ImagingStudy","DiagnosticReport","OperationOutcome","Bundle"],gS=["DiagnosticReport-update"];function KV(e){return gS.includes(e)}function XV(e){if(gS.includes(e))throw new vt(jn(`'context.version' is required for '${e}'.`))}const JV={"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 ZV(e){return YV.includes(e)}function gk(e){return!!e.endpoint}function IT(e){if(!vS(e))throw new vt(jn("subscriptionRequest must be an object conforming to SubscriptionRequest type."));const{channelType:t,mode:n,topic:r,events:o}=e,s={"hub.channel.type":t,"hub.mode":n,"hub.topic":r,"hub.events":o.join(",")};return gk(e)&&(s.endpoint=e.endpoint),new URLSearchParams(s).toString()}function vS(e){if(typeof e!="object")return!1;const{channelType:t,mode:n,topic:r,events:o}=e;if(!(t&&n&&r&&o)||typeof r!="string"||typeof o!="object"||!Array.isArray(o)||o.length<1||t!=="websocket"||n!=="subscribe"&&n!=="unsubscribe")return!1;for(const s of o)if(!Fx[s])return!1;return!(gk(e)&&!(typeof e.endpoint=="string"&&e.endpoint.startsWith("ws")))}function eF(e,t,n,r){if(typeof t!="object")throw new vt(jn(`context[${n}] is invalid. Context must contain a single valid FHIR resource! Resource is not an object.`));if(!(t.id&&typeof t.id=="string"))throw new vt(jn(`context[${n}] is invalid. Resource must contain a valid string ID.`));if(!t.resourceType)throw new vt(jn(`context[${n}] is invalid. Resource must contain a resource type. No resource type found.`));const o=r.resourceType;if(o!=="*"){if(!ZV(t.resourceType))throw new vt(jn(`context[${n}] is invalid. Resource must contain a valid FHIRcast resource type. Resource type is not a known resource type.`));if(o&&t.resourceType!==o)throw new vt(jn(`context[${n}] is invalid. context[${n}] for the '${e}' event should contain resource of type ${o}.`))}}function tF(e,t,n,r,o){if(o.set(t.key,(o.get(t.key)??0)+1),r.reference){if(!_a(t.reference))throw new vt(jn(`context[${n}] is invalid. Expected key '${t.key}' to be a reference.`))}else eF(e,t.resource,n,r)}function nF(e,t){const n=new Map,r=JV[e];for(let o=0;o<t.length;o++){const s=t[o].key;if(!r[s])throw new vt(jn(`Key '${s}' not found for event '${e}'. Make sure to add only valid keys.`));tF(e,t[o],o,r[s],n)}for(const[o,s]of Object.entries(r)){if(!(s.optional||n.has(o)))throw new vt(jn(`Missing required key '${o}' on context for '${e}' event.`));if(!s.manyAllowed&&(n.get(o)??0)>1)throw new vt(jn(`${n.get(o)} context entries with key '${o}' found for the '${e}' event when schema only allows for 1.`))}}function zT(e,t,n,r){if(!(e&&typeof e=="string"))throw new vt(jn("Must provide a topic."));if(!Fx[t])throw new vt(jn(`Must provide a valid FHIRcast event name. Supported events: ${Object.keys(Fx).join(", ")}`));if(typeof n!="object")throw new vt(jn("context must be a context object or array of context objects."));if(gS.includes(t)&&!r)throw new vt(jn(`The '${t}' event must contain a 'context.versionId'.`));const o=Array.isArray(n)?n:[n];return nF(t,o),{timestamp:new Date().toISOString(),id:hk(),event:{"hub.topic":e,"hub.event":t,context:o,...r?{"context.versionId":r}:{}}}}class rF extends Gm{subRequest;websocket;constructor(t){if(super(),this.subRequest=t,!t.endpoint)throw new vt(jn("Subscription request should contain an endpoint."));if(!vS(t))throw new vt(jn("Subscription request failed validation."));const n=new WebSocket(t.endpoint);n.addEventListener("open",()=>{this.dispatchEvent({type:"connect"}),n.addEventListener("message",r=>{const o=JSON.parse(r.data);if(o["hub.topic"])return;const s=o;s.event["hub.event"]!=="heartbeat"&&(this.dispatchEvent({type:"message",payload:s}),n.send(JSON.stringify({id:o?.id,timestamp:new Date().toISOString()})))}),n.addEventListener("close",()=>{this.dispatchEvent({type:"disconnect"})})}),this.websocket=n}disconnect(){this.websocket.close()}}function iF(e){return JSON.parse(VV(e))}function oF(e){return e.split(".").length===3}function yS(e){const[t,n,r]=e.split(".");return iF(n)}function aF(e){try{return typeof yS(e).login_id=="string"}catch{return!1}}function sF(e){try{const n=yS(e).exp;return typeof n=="number"?n*1e3:void 0}catch{return}}class lF{medplum;constructor(t){this.medplum=t}async get(t){return this.medplum.get(`keyvalue/v1/${t}`)}async set(t,n){await this.medplum.put(`keyvalue/v1/${t}`,n,nn.TEXT)}async delete(t){await this.medplum.delete(`keyvalue/v1/${t}`)}}class Gi{[Symbol.toStringTag]="ReadablePromise";suspender;status="pending";response;error;constructor(t){this.suspender=t.then(n=>(this.status="success",this.response=n,n),n=>{throw this.status="error",this.error=n,n})}isPending(){return this.status==="pending"}isOk(){return this.status==="success"}read(){switch(this.status){case"pending":throw this.suspender;case"error":throw this.error;default:return this.response}}then(t,n){return this.suspender.then(t,n)}catch(t){return this.suspender.catch(t)}finally(t){return this.suspender.finally(t)}}class cF{storage;prefix="";constructor(t,n=""){this.storage=t??globalThis.localStorage??new uF,this.prefix=n}makeKey(t){return this.prefix+t}clear(){this.storage===globalThis.localStorage&&this.prefix?Object.keys(this.storage).filter(t=>t.startsWith(this.prefix)).forEach(t=>{this.storage.removeItem(t)}):this.storage.clear()}getString(t){return this.storage.getItem(this.makeKey(t))??void 0}setString(t,n){n?this.storage.setItem(this.makeKey(t),n):this.storage.removeItem(this.makeKey(t))}getObject(t){const n=this.getString(t);return n?JSON.parse(n):void 0}setObject(t,n){this.setString(t,n?no(n):void 0)}}class uF{data;constructor(){this.data=new Map}get length(){return this.data.size}clear(){this.data.clear()}getItem(t){return this.data.get(t)??null}setItem(t,n){n?this.data.set(t,n):this.data.delete(t)}removeItem(t){this.data.delete(t)}key(t){return Array.from(this.data.keys())[t]}}const Lc={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let $T=!1;function dF(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");Lc.Event=globalThis.Event,Lc.ErrorEvent=class extends Event{message;error;constructor(t,n){super("error",n),this.message=t.message,this.error=t}},Lc.CloseEvent=class extends Event{code;reason;wasClean=!0;constructor(t=1e3,n="",r){super("close",r),this.code=t,this.reason=n}}}function fF(e,t){if(!e)throw new Error(t)}function Wh(e){return new e.constructor(e.type,e)}const Ys={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let UT=!1;class cs extends Gm{_ws;_retryCount=-1;_uptimeTimeout;_connectTimeout;_shouldReconnect=!0;_connectLock=!1;_binaryType;_closeCalled=!1;_messageQueue=[];_debugLogger=console.log.bind(console);_url;_protocols;_options;constructor(t,n,r={}){$T||(dF(),$T=!0),super(),this._url=t,this._protocols=n,this._options=r,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 cs.CONNECTING}get OPEN(){return cs.OPEN}get CLOSING(){return cs.CLOSING}get CLOSED(){return cs.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((n,r)=>(typeof r=="string"?n+=r.length:r instanceof Blob?n+=r.size:n+=r.byteLength,n),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?cs.CLOSED:cs.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}onclose=null;onerror=null;onmessage=null;onopen=null;close(t=1e3,n){if(this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(t,n)}reconnect(t,n){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(t,n),this._connect())}send(t){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",t),this._ws.send(t);else{const{maxEnqueuedMessages:n=Ys.maxEnqueuedMessages}=this._options;this._messageQueue.length<n&&(this._debug("enqueue",t),this._messageQueue.push(t))}}_debug(...t){this._options.debug&&this._debugLogger("RWS>",...t)}_getNextDelay(){const{reconnectionDelayGrowFactor:t=Ys.reconnectionDelayGrowFactor,minReconnectionDelay:n=Ys.minReconnectionDelay,maxReconnectionDelay:r=Ys.maxReconnectionDelay}=this._options;let o=0;return this._retryCount>0&&(o=n*Math.pow(t,this._retryCount-1),o>r&&(o=r)),this._debug("next delay",o),o}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=Ys.maxRetries,connectionTimeout:n=Ys.connectionTimeout}=this._options;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);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"&&!UT&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),UT=!0);const r=this._options.WebSocket||WebSocket;this._debug("connect",{url:this._url,protocols:this._protocols}),this._ws=this._protocols?new r(this._url,this._protocols):new r(this._url),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),n)}).catch(r=>{this._connectLock=!1,this._handleError(new Lc.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Lc.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new Lc.CloseEvent(t,n,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_handleOpen=t=>{this._debug("open event");const{minUptime:n=Ys.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),n),fF(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(r=>this._ws?.send(r)),this._messageQueue=[],this.onopen&&this.onopen(t),this.dispatchEvent(Wh(t))};_handleMessage=t=>{this._debug("message event"),this.onmessage&&this.onmessage(t),this.dispatchEvent(Wh(t))};_handleError=t=>{this._debug("error event",t.message),this._disconnect(void 0,t.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(t),this._debug("exec error listeners"),this.dispatchEvent(Wh(t)),this._connect()};_handleClose=t=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(t),this.dispatchEvent(Wh(t))};_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)}}const hF=5e3;class Hx extends Gm{criteria;constructor(...t){super(),this.criteria=new Set(t)}getCriteria(){return this.criteria}_addCriteria(t){this.criteria.add(t)}_removeCriteria(t){this.criteria.delete(t)}}class pF{criteria;emitter;refCount;subscriptionProps;subscriptionId;token;connecting=!1;constructor(t,n){this.criteria=t,this.emitter=new Hx(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class mF{medplum;ws;masterSubEmitter;criteriaEntries;criteriaEntriesBySubscriptionId;wsClosed;pingTimer=void 0;pingIntervalMs;waitingForPong=!1;currentProfile;constructor(t,n,r){if(!(t instanceof yk))throw new vt(jn("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new vt(jn("Not a valid URL"))}const s=r?.ReconnectingWebSocket?new r.ReconnectingWebSocket(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger}):new cs(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger});this.medplum=t,this.ws=s,this.masterSubEmitter=new Hx,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=r?.pingIntervalMs??hF,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{try{const r=JSON.parse(n.data);if(r.type==="pong"){this.waitingForPong=!1;return}const o=r,s=o?.entry?.[0]?.resource;if(s.type==="heartbeat"){this.masterSubEmitter?.dispatchEvent({type:"heartbeat",payload:o});return}if(s.type==="handshake"){const d=pl(s.subscription),f={type:"connect",payload:{subscriptionId:d}};this.masterSubEmitter?.dispatchEvent(f);const p=this.criteriaEntriesBySubscriptionId.get(d);if(!p){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}p.connecting=!1,p.emitter.dispatchEvent({...f});return}this.masterSubEmitter?.dispatchEvent({type:"message",payload:o});const c=this.criteriaEntriesBySubscriptionId.get(pl(s.subscription));if(!c){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}c.emitter.dispatchEvent({type:"message",payload:o})}catch(r){console.error(r);const o={type:"error",payload:r};this.masterSubEmitter?.dispatchEvent(o);for(const s of this.getAllCriteriaEmitters())s.dispatchEvent({...o})}}),t.addEventListener("error",()=>{const n={type:"error",payload:new vt(E8(new Error("WebSocket error")))};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n})}),t.addEventListener("close",()=>{const n={type:"close"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),this.masterSubEmitter?.removeAllListeners())}),t.addEventListener("open",()=>{const n={type:"open"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.refreshAllSubscriptions().catch(console.error),this.pingTimer||(this.pingTimer=setInterval(()=>{if(this.waitingForPong){this.waitingForPong=!1,t.reconnect();return}t.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0},this.pingIntervalMs))}),this.medplum.addEventListener("change",()=>{const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&this.currentProfile?.id!==n.id&&this.ws.reconnect(),this.currentProfile=n})}emitError(t,n){const r={type:"error",payload:n};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){const{subscriptionId:n}=t;if(n){const r={type:"disconnect",payload:{subscriptionId:n}};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){let n=t?.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${Ot(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:t.criteria})).id);const{parameter:r}=await this.medplum.get(`fhir/R4/Subscription/${n}/$get-ws-binding-token`),o=r?.find(c=>c.name==="token")?.valueString,s=r?.find(c=>c.name==="websocket-url")?.valueUrl;if(!o)throw new vt(jn("Failed to get token"));if(!s)throw new vt(jn("Failed to get URL from $get-ws-binding-token"));return[n,o]}maybeGetCriteriaEntry(t,n){const r=this.criteriaEntries.get(t);if(r){if(!n)return r.bareCriteria;for(const o of r.criteriaWithProps)if(ko(n,o.subscriptionProps))return o}}getAllCriteriaEmitters(){const t=[];for(const n of this.criteriaEntries.values()){n.bareCriteria&&t.push(n.bareCriteria.emitter);for(const r of n.criteriaWithProps)t.push(r.emitter)}return t}addCriteriaEntry(t){const{criteria:n,subscriptionProps:r}=t;let o;this.criteriaEntries.has(n)?o=this.criteriaEntries.get(n):(o={criteriaWithProps:[]},this.criteriaEntries.set(n,o)),r?o.criteriaWithProps.push(t):o.bareCriteria=t}removeCriteriaEntry(t){const{criteria:n,subscriptionProps:r,subscriptionId:o,token:s}=t;if(!this.criteriaEntries.has(n))return;const c=this.criteriaEntries.get(n);r?c.criteriaWithProps=c.criteriaWithProps.filter(d=>{const f=d.subscriptionProps;return!ko(r,f)}):c.bareCriteria=void 0,!c.bareCriteria&&c.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),this.masterSubEmitter?._removeCriteria(n)),o&&this.criteriaEntriesBySubscriptionId.delete(o),s&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:s}}))}async subscribeToCriteria(t){if(!(this.ws.readyState!==WebSocket.OPEN||t.connecting)){t.connecting=!0;try{const[n,r]=await this.getTokenForCriteria(t);t.subscriptionId=n,t.token=r,this.criteriaEntriesBySubscriptionId.set(n,t),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:r}}))}catch(n){console.error(Qe(n)),this.emitError(t,n),this.removeCriteriaEntry(t)}}}async refreshAllSubscriptions(){this.criteriaEntriesBySubscriptionId.clear();for(const t of this.criteriaEntries.values())for(const n of[...t.bareCriteria?[t.bareCriteria]:[],...t.criteriaWithProps])n.clearAttachedSubscription(),await this.subscribeToCriteria(n)}addCriteria(t,n){this.masterSubEmitter&&this.masterSubEmitter._addCriteria(t);const r=this.maybeGetCriteriaEntry(t,n);if(r)return r.refCount+=1,r.emitter;const o=new pF(t,n);return this.addCriteriaEntry(o),this.subscribeToCriteria(o).catch(console.error),o.emitter}removeCriteria(t,n){const r=this.maybeGetCriteriaEntry(t,n);if(!r){console.warn("Criteria not known to `SubscriptionManager`. Possibly called remove too many times.");return}r.refCount-=1,!(r.refCount>0)&&(this.maybeEmitDisconnect(r),this.removeCriteriaEntry(r))}getWebSocket(){return this.ws}closeWebSocket(){this.wsClosed||(this.wsClosed=!0,this.ws.close())}reconnectWebSocket(){this.ws.reconnect(),this.wsClosed=!1}getCriteriaCount(){return this.getAllCriteriaEmitters().length}getMasterEmitter(){return this.masterSubEmitter||(this.masterSubEmitter=new Hx(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const vk="5.0.7-0dd9d93",gF=nn.FHIR_JSON+", */*; q=0.1",vF="https://api.medplum.com/",yF=1e3,xF=6e4,bF=0,SF=3e5,wF="Binary/",BT={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},Tc={ClientCredentials:"client_credentials",AuthorizationCode:"authorization_code",RefreshToken:"refresh_token",JwtBearer:"urn:ietf:params:oauth:grant-type:jwt-bearer",TokenExchange:"urn:ietf:params:oauth:grant-type:token-exchange"},jF={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},CF={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class yk extends Gm{options;fetch;createPdfImpl;storage;requestCache;cacheTime;baseUrl;fhirBaseUrl;authorizeUrl;tokenUrl;logoutUrl;fhircastHubUrl;defaultHeaders;onUnauthenticated;autoBatchTime;autoBatchQueue;refreshGracePeriod;subscriptionManager;medplumServer;clientId;clientSecret;credentialsInHeader;autoBatchTimerId;accessToken;accessTokenExpires;refreshToken;refreshPromise;profilePromise;sessionDetails;currentRateLimits;basicAuth;initPromise;initComplete=!0;keyValueClient;constructor(t){if(super(),t?.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=t?.fetch??EF(),this.storage=t?.storage??new cF(void 0,t?.storagePrefix),this.createPdfImpl=t?.createPdf,this.baseUrl=sS(t?.baseUrl??vF),this.fhirBaseUrl=vo(this.baseUrl,t?.fhirUrlPath??"fhir/R4"),this.authorizeUrl=vo(this.baseUrl,t?.authorizeUrl??"oauth2/authorize"),this.tokenUrl=vo(this.baseUrl,t?.tokenUrl??"oauth2/token"),this.logoutUrl=vo(this.baseUrl,t?.logoutUrl??"oauth2/logout"),this.fhircastHubUrl=vo(this.baseUrl,t?.fhircastHubUrl??"fhircast/STU3"),this.clientId=t?.clientId??"",this.clientSecret=t?.clientSecret??"",this.credentialsInHeader=t?.authCredentialsMethod==="header",this.defaultHeaders=t?.defaultHeaders??{},this.onUnauthenticated=t?.onUnauthenticated,this.refreshGracePeriod=t?.refreshGracePeriod??SF,this.cacheTime=t?.cacheTime??(xo()?xF:bF),this.cacheTime>0?this.requestCache=new DD(t?.resourceCacheSize??yF):this.requestCache=void 0,t?.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t?.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t?.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(()=>{t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}async attemptResumeActiveLogin(){const t=this.getActiveLogin();t&&(this.setAccessToken(t.accessToken,t.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}getFhircastHubUrl(){return this.fhircastHubUrl}getDefaultHeaders(){return this.defaultHeaders}clear(){this.storage.clear(),xo()&&sessionStorage.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.sessionDetails=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(t){t=t.toString(),this.requestCache?.delete(t)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(t){const n=vo(this.fhirBaseUrl,t);if(this.requestCache)for(const r of this.requestCache.keys())(r.endsWith(n)||r.includes(n+"?"))&&this.requestCache.delete(r)}get(t,n={}){t=t.toString();const r=this.getCacheEntry(t,n);if(r)return r.value;let o;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?o=new Promise((c,d)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:c,reject:d}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):o=this.request("GET",t,n);const s=new Gi(o);return this.setCacheEntry(t,s),s}post(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("POST",t,o)}put(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("PUT",t,o)}patch(t,n,r={}){return t=t.toString(),this.setRequestBody(r,n),this.setRequestContentType(r,nn.JSON_PATCH),this.invalidateUrl(t),this.request("PATCH",t,r)}delete(t,n){return t=t.toString(),this.invalidateUrl(t),this.request("DELETE",t,n)}async startNewUser(t,n){const{codeChallengeMethod:r,codeChallenge:o}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:r,codeChallenge:o},void 0,n)}async startNewProject(t,n){return this.post("auth/newproject",t,void 0,n)}async startNewPatient(t,n){return this.post("auth/newpatient",t,void 0,n)}async startLogin(t,n){return this.post("auth/login",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async startGoogleLogin(t,n){return this.post("auth/google",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async ensureCodeChallenge(t){return t.codeChallenge?t:{...t,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(t){const r=new URLSearchParams(nr.getSearch()).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){nr.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,o,s=!0){let c=o;s&&(c=await this.ensureCodeChallenge(o)),nr.assign(this.getExternalAuthRedirectUri(t,n,r,c,s))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");return this.fetchTokens({grant_type:Tc.TokenExchange,subject_token_type:jF.AccessToken,client_id:n,subject_token:t})}getExternalAuthRedirectUri(t,n,r,o,s=!0){const c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",n),c.searchParams.set("redirect_uri",r),c.searchParams.set("scope",o.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(o)),s){const{codeChallenge:d,codeChallengeMethod:f}=o;if(!f)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!d)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");c.searchParams.set("code_challenge_method",f),c.searchParams.set("code_challenge",d)}return c.toString()}fhirUrl(...t){return new URL(vo(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=gB(n)),r}search(t,n,r){const o=this.fhirSearchUrl(t,n),s="search-"+o.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=this.getBundle(o,r);return this.setCacheEntry(s,d),d}searchOne(t,n,r){const o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();const s="searchOne-"+o.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=new Gi(this.search(t,o.searchParams,r).then(f=>f.entry?.[0]?.resource));return this.setCacheEntry(s,d),d}searchResources(t,n,r){const s="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=new Gi(this.search(t,n,r).then(FT));return this.setCacheEntry(s,d),d}async*searchResourcePages(t,n,r){let o=this.fhirSearchUrl(t,n);for(;o;){const s=new URL(o).searchParams;s.has("_count")||s.set("_count","1000");const c=await this.search(t,s,r),d=c.link?.find(f=>f.relation==="next");if(!c.entry?.length&&!d)break;yield FT(c),o=d?.url?new URL(d.url):void 0}}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){const r=this.requestCache?.get(this.fhirUrl(t,n).toString())?.value;return r?.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return BT;const[r,o]=n.split("/");if(!(!r||!o))return this.getCached(r,o)}readResource(t,n,r){if(!n)throw new Error('The "id" parameter cannot be null, undefined, or an empty string.');return this.get(this.fhirUrl(t,n),r)}readReference(t,n){const r=t.reference;if(!r)return new Gi(Promise.reject(new Error("Missing reference")));if(r==="system")return new Gi(Promise.resolve(BT));const[o,s]=r.split("/");return!o||!s?new Gi(Promise.reject(new Error("Invalid reference"))):this.readResource(o,s,n)}requestSchema(t){if(ID(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Gi((async()=>{const s=`{
|
|
60
60
|
StructureDefinitionList(_filter: "name eq ${t}") {
|
|
61
61
|
resourceType,
|
|
62
62
|
name,
|
|
@@ -260,4 +260,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
260
260
|
}
|
|
261
261
|
]
|
|
262
262
|
}`,Kre="MSH|^~\\&|ADT1|MCM|LABADT|MCM|198808181126|SECURITY|ADT|MSG00001|P|2.1\rPID|||PATID1234^5^M11||JONES^WILLIAM^A^III||19610615|M-||C|1200 N ELM STREET^^GREENSBORO^NC^27401-1020|GL|(919)379-1212|(919)271-3434||S||PATID12345001^2^M10|123456789|987654^NC\rNK1|1|JONES^BARBARA^K|SPO|||||20011105\rPV1|1|I|2000^2012^01||||004777^LEBAUER^SIDNEY^J.|||SUR||-||1|A0-";function Xre(){const e=_e(),{id:t}=Ht(),[n,r]=v.useState(),[o,s]=v.useState(),[c,d]=v.useState(),[f,p]=v.useState(Yre),[m,g]=v.useState(Kre),[y,b]=v.useState(nn.FHIR_JSON),S=v.useRef(null),j=v.useRef(null),[C,R]=v.useState(!1);v.useEffect(()=>{e.readResource("Bot",t).then(async P=>{r(P),s(P.runtimeVersion==="vmcontext"?"commonjs":"esnext"),d(await Jre(e,P))}).catch(P=>Ne({color:"red",message:Qe(P),autoClose:!1}))},[e,t]);const E=v.useCallback(async()=>xd(S.current,{command:"getValue"}),[]),T=v.useCallback(async()=>xd(S.current,{command:"getOutput"}),[]),_=v.useCallback(async()=>y===nn.FHIR_JSON?JSON.parse(f):m,[y,f,m]),k=v.useCallback(async P=>{P.preventDefault(),P.stopPropagation(),R(!0);try{const z=await E(),B=await T(),Y=await e.createAttachment({data:z,filename:"index.ts",contentType:nn.TYPESCRIPT}),J=await e.createAttachment({data:B,filename:o==="commonjs"?"index.cjs":"index.mjs",contentType:nn.JAVASCRIPT}),Z=[{op:"add",path:"/sourceCode",value:Y},{op:"add",path:"/executableCode",value:J}];await e.patchResource("Bot",t,Z),Ne({color:"green",message:"Saved"})}catch(z){Ne({color:"red",message:Qe(z),autoClose:!1})}finally{R(!1)}},[e,t,o,E,T]),I=v.useCallback(async P=>{P.preventDefault(),P.stopPropagation(),R(!0);try{await e.post(e.fhirUrl("Bot",t,"$deploy")),Ne({color:"green",message:"Deployed"})}catch(z){Ne({color:"red",message:Qe(z),autoClose:!1})}finally{R(!1)}},[e,t]),A=v.useCallback(async P=>{P.preventDefault(),P.stopPropagation(),R(!0);try{const z=await _(),B=await e.post(e.fhirUrl("Bot",t,"$execute"),z,y);await xd(j.current,{command:"setValue",value:B}),Ne({color:"green",message:"Success"})}catch(z){Ne({color:"red",message:Qe(z),autoClose:!1})}finally{R(!1)}},[e,t,_,y]);return!n||c===void 0?null:a.jsxs(Sr,{m:0,gutter:0,style:{overflow:"hidden"},children:[a.jsx(Sr.Col,{span:8,children:a.jsxs(Or,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",mih:400,children:[a.jsx(Wre,{iframeRef:S,language:"typescript",module:o,testId:"code-frame",defaultValue:c,minHeight:"528px"}),a.jsxs(ye,{justify:"flex-end",gap:"xs",children:[a.jsx(Pe,{type:"button",onClick:k,loading:C,leftSection:a.jsx(yq,{size:"1rem"}),children:"Save"}),a.jsx(Pe,{type:"button",onClick:I,loading:C,leftSection:a.jsx(CS,{size:"1rem"}),children:"Deploy"}),a.jsx(Pe,{type:"button",onClick:A,loading:C,leftSection:a.jsx(sG,{size:"1rem"}),children:"Execute"})]})]})}),a.jsxs(Sr.Col,{span:4,children:[a.jsxs(Or,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[a.jsx(fn,{data:[{label:"FHIR",value:nn.FHIR_JSON},{label:"HL7",value:nn.HL7_V2}],onChange:P=>b(P.currentTarget.value)}),y===nn.FHIR_JSON?a.jsx(au,{value:f,onChange:P=>p(P),autosize:!0,minRows:15}):a.jsx("textarea",{className:Gre.hl7Input,value:m,onChange:P=>g(P.currentTarget.value),rows:15})]}),a.jsx(Or,{m:2,p:"xs",shadow:"md",children:a.jsx(Qre,{iframeRef:j,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function Jre(e,t){if(t.sourceCode?.url){const n=t.sourceCode.url?.split("/")?.find(oS);return(await e.download(e.fhirUrl("Binary",n))).text()}return t.code??""}function Ml(e){let t=e.meta;return t&&(t={...t,lastUpdated:void 0,versionId:void 0,author:void 0}),{...e,meta:t}}function Zre(){const e=_e(),{resourceType:t,id:n}=Ht(),r={reference:t+"/"+n},o=v.useCallback(s=>{e.updateResource(Ml(s)).then(()=>{Ne({color:"green",message:"Success"})}).catch(c=>{Ne({color:"red",message:Qe(c),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return a.jsx(dt,{children:a.jsx(OX,{value:r,onSubmit:o})});case"Questionnaire":return a.jsx(dt,{children:a.jsx(lJ,{questionnaire:r,onSubmit:o})});default:return null}}function eie(){const{resourceType:e,id:t}=Ht(),n=Kt({reference:e+"/"+t}),r=kn();return n?a.jsx(dt,{children:a.jsx(LJ,{value:n,onStart:(o,s)=>r(`/forms/${pl(s)}`)?.catch(console.error),onEdit:(o,s,c)=>r(`/${c.reference}}`)?.catch(console.error)})}):null}function tie(){const e=_e(),{resourceType:t,id:n}=Ht(),r=kn();return a.jsxs(dt,{children:[a.jsxs("p",{children:["Are you sure you want to delete this ",t,"?"]}),a.jsx(Pe,{color:"red",onClick:()=>{e.deleteResource(t,n).then(()=>r(`/${t}`)?.catch(console.error)).catch(o=>Ne({color:"red",message:Qe(o),autoClose:!1}))},children:"Delete"})]})}const nie="_selectProfileBtn_tbaz6_1",rie="_chevron_tbaz6_13",j2={selectProfileBtn:nie,chevron:rie};function iie(){const{resourceType:e,id:t}=Ht(),n=Kt({reference:e+"/"+t}),[r,o]=v.useState(),s=Rl({onDropdownClose:()=>s.resetSelectedOption()}),c=v.useMemo(()=>{if(Ln(n?.meta?.profile))return[a.jsx(Xe.Option,{value:"",children:"None"},""),...n.meta.profile.map(f=>a.jsx(Xe.Option,{value:f,children:f},f))]},[n?.meta?.profile]);if(v.useEffect(()=>{n?.meta?.profile?.length===1&&o(n.meta.profile[0])},[n?.meta?.profile]),!n)return null;let d;return Ln(c)&&(d=a.jsx(ye,{justify:"flex-end",children:a.jsxs(Ue,{align:"flex-end",gap:"xs",children:[a.jsxs(Xe,{store:s,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:f=>{o(f),s.closeDropdown()},children:[a.jsx(Xe.Target,{children:a.jsx(An,{onClick:()=>s.toggleDropdown(),children:a.jsxs(Jd,{fw:"bold",fs:"sm",className:j2.selectProfileBtn,children:[a.jsx("span",{children:"Pick profile"}),a.jsx(jS,{stroke:1.5,className:j2.chevron})]})})}),a.jsx(Xe.Dropdown,{w:"max-content",children:a.jsx(Xe.Options,{children:c})})]}),a.jsx(ce,{children:r?a.jsxs(a.Fragment,{children:[a.jsx(Ee,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),a.jsx(Ee,{span:!0,size:"sm",children:r||"Nothing selected"})]}):a.jsx(Ee,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),a.jsx(dt,{children:a.jsxs(Ue,{gap:"xl",children:[d,a.jsx(FS,{value:n,profileUrl:r})]})})}function oie(){const e=_e(),{resourceType:t,id:n}=Ht(),[r,o]=v.useState(),[s,c]=v.useState(),d=kn(),[f,p]=v.useState();v.useEffect(()=>{e.readResource(t,n).then(b=>{o(hi(b)),c(hi(b))}).catch(b=>{p(Yt(b)),Ne({color:"red",message:Qe(b),autoClose:!1})})},[e,t,n]);const m=v.useCallback(b=>{p(void 0),e.updateResource(Ml(b)).then(()=>{d(`/${t}/${n}/details`)?.catch(console.error),Ne({id:"succes",color:"green",message:"Success"})}).catch(S=>{p(Yt(S)),Ne({color:"red",message:Qe(S),autoClose:!1})})},[e,t,n,d]),g=v.useCallback(b=>{p(void 0);const S=EP.createPatch(r,b);e.patchResource(t,n,S).then(()=>{d(`/${t}/${n}/details`)?.catch(console.error),Ne({id:"succes",color:"green",message:"Success"})}).catch(j=>{p(Yt(j)),Ne({color:"red",message:Qe(j),autoClose:!1})})},[e,t,n,r,d]),y=v.useCallback(()=>d(`/${t}/${n}/delete`)?.catch(console.error),[d,t,n]);return s?a.jsx(dt,{children:a.jsx(Hp,{defaultValue:s,onSubmit:m,onPatch:g,onDelete:y,outcome:f})}):null}function aie(){const{resourceType:e,id:t}=Ht(),n=Kt({reference:e+"/"+t});return n?a.jsx(dt,{maw:700,children:n.resourceType==="Patient"?a.jsx(_X,{patient:n}):a.jsx($o,{icon:a.jsx(As,{size:16}),title:"Unsupported export type",color:"red",children:"This page is only supported for Patient resources"})}):null}function zN({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,o=_e(),[s,c]=v.useState();return v.useEffect(()=>{o.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(d=>{c(d.filter(WW))}).catch(console.error)},[o,n,r]),a.jsx(Pt,{value:t?.url,onChange:d=>{const f=s?.find(p=>p.url===d);f&&n(f)},children:a.jsx(Pt.List,{children:s?.map(d=>{const f=e.meta?.profile?.includes(d.url),p=f?"This profile is present in this resource's meta.profile property.":"This profile is not included in this resource's meta.profile property.";return a.jsx(Pt.Tab,{value:d.url,title:p,rightSection:f&&a.jsx(J0,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:a.jsx(zG,{size:"90%"})}),children:d.title||d.name},d.url)})})})}function $N(e,t){const n=_e(),r=kn();return{defaultValue:{resourceType:e},handleSubmit:c=>{t&&t(void 0),n.createResource(c).then(d=>r("/"+d.resourceType+"/"+d.id)).catch(d=>{t&&t(Yt(d)),Ne({color:"red",message:Qe(d),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function xx(){const{resourceType:e}=Ht(),t=ti(),[n,r]=v.useState(),{defaultValue:o,handleSubmit:s}=$N(e,r),[c,d]=v.useState(),f=t.pathname.toLowerCase().endsWith("profiles"),p=v.useCallback(m=>{const g=Ml(m);c&&tk(g,c.url),s(g)},[c,s]);return f?a.jsx(dt,{children:a.jsxs(Ue,{children:[a.jsx(zN,{resource:o,currentProfile:c,onChange:d}),c?a.jsx(Hp,{defaultValue:o,onSubmit:p,outcome:n,profileUrl:c.url},c.url):a.jsx(Ee,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):a.jsx(dt,{children:a.jsx(Hp,{defaultValue:o,onSubmit:s,outcome:n})})}function C2(){const e=_e(),{resourceType:t,id:n}=Ht(),r=e.readHistory(t,n).read();return a.jsx(dt,{children:a.jsx(sZ,{history:r})})}function sie(){const{resourceType:e}=Ht(),[t,n]=v.useState(),{defaultValue:r,handleSubmit:o}=$N(e,n),s=v.useCallback(c=>{o(JSON.parse(c["new-resource"]))},[o]);return a.jsxs(dt,{children:[t&&a.jsx(Er,{outcome:t}),a.jsxs(pt,{onSubmit:s,children:[a.jsx(au,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:no(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),a.jsx(ye,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:a.jsx(Pe,{type:"submit",children:"OK"})})]})]})}function lie(){const e=_e(),{resourceType:t,id:n}=Ht(),r=Kt({reference:t+"/"+n}),o=kn(),[s,c]=v.useState(),d=v.useCallback(f=>{e.updateResource(Ml(JSON.parse(f.resource))).then(()=>{c(void 0),o(`/${t}/${n}/details`)?.catch(console.error),Ne({color:"green",message:"Success"})}).catch(p=>{Ne({color:"red",message:Qe(p),autoClose:!1})})},[e,t,n,o]);return r?a.jsxs(dt,{children:[s&&a.jsx(Er,{outcome:s}),a.jsxs(pt,{onSubmit:d,children:[a.jsx(au,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:no(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),a.jsx(ye,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:a.jsx(Pe,{type:"submit",children:"OK"})})]})]}):null}function cie(e){const{resourceType:t,id:n}=e;return a.jsxs(dt,{children:[a.jsxs($o,{icon:a.jsx(As,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",a.jsx("br",{}),a.jsx(Mt,{href:`/forms/${n}`,children:`/forms/${n}`})]}),a.jsx(qP,{questionnaire:{reference:t+"/"+n},onSubmit:()=>alert("You submitted the preview")})]})}const uie="_propertyTable_1xts4_1",die="_propertiesTitle_1xts4_17",UN={propertyTable:uie,propertiesTitle:die};function fie(e){return e.valueCode||e.valueString||(e.valueBoolean===void 0?void 0:String(e.valueBoolean))||(e.valueInteger===void 0?void 0:String(e.valueInteger))||(e.valueDecimal===void 0?void 0:String(e.valueDecimal))||e.valueDate||e.valueDateTime||"N/A"}function hie(e){const{properties:t}=e,n=t.map(r=>{let o="",s="",c="";return r.part?.forEach(d=>{d.name==="code"?o=d.valueCode||"":d.name==="description"?s=d.valueString||"":d.name==="value"&&(c=fie(d))}),{code:o,description:s,value:c}});return a.jsxs(de,{className:UN.propertyTable,children:[a.jsx(de.Thead,{children:a.jsxs(de.Tr,{children:[a.jsx(de.Th,{children:"Code"}),a.jsx(de.Th,{children:"Description"}),a.jsx(de.Th,{children:"Value"})]})}),a.jsx(de.Tbody,{children:n.map((r,o)=>a.jsxs(de.Tr,{children:[a.jsx(de.Td,{children:r.code}),a.jsx(de.Td,{children:r.description}),a.jsx(de.Td,{children:r.value})]},`property-${o}`))})]})}function pie(e){const{valueSet:t}=e,n=_e(),r=t.url,[o,s]=v.useState(),[c,d]=v.useState(),[f,p]=v.useState(!1),[m,g]=v.useState(),y=v.useCallback(async j=>{if(s(j),d(void 0),g(void 0),!j?.code||!j?.system){p(!1);return}p(!0);try{const C=new URLSearchParams({system:j.system,code:j.code}),R=n.fhirUrl("CodeSystem","$lookup")+"?"+C.toString(),E=await n.get(R);d(E)}catch(C){g(C instanceof Error?C:new Error(String(C)))}finally{p(!1)}},[n]),b=v.useMemo(()=>c?.parameter?.filter(j=>j.name==="property"&&j.part)??[],[c]),S=b.length>0;return a.jsx(dt,{children:a.jsxs(Ue,{gap:"xl",children:[a.jsx(gf,{binding:r,placeholder:"Select a value from the ValueSet",onChange:j=>y(j[0]),defaultValue:o,maxValues:1}),o?a.jsxs(Ue,{gap:"md",children:[a.jsxs(yf,{children:[a.jsx(Lr,{term:"Code",children:o.code}),o.system&&a.jsx(Lr,{term:"System",children:o.system}),o.display&&a.jsx(Lr,{term:"Display",children:o.display})]}),f&&a.jsxs(ye,{gap:"xs",children:[a.jsx(Ir,{size:"sm"}),a.jsx(Ee,{size:"sm",c:"dimmed",children:"Loading properties..."})]}),!f&&m&&a.jsxs($o,{icon:a.jsx(As,{size:16}),title:"Lookup Failed",color:"red",children:["Failed to retrieve code information: ",Qe(m)]}),!f&&!m&&S&&a.jsx(AS,{children:a.jsxs(Ue,{gap:"xs",mt:"lg",children:[a.jsx(Ee,{fw:500,size:"sm",c:"dimmed",className:UN.propertiesTitle,children:"Properties"}),a.jsx(hie,{properties:b})]})})]}):null]})})}function mie(){const{resourceType:e,id:t}=Ht(),n=Kt({reference:e+"/"+t});return n?n.resourceType==="Questionnaire"?a.jsx(cie,{resourceType:e,id:t}):n.resourceType==="ValueSet"?a.jsx(pie,{valueSet:n}):null:null}function gie(){const e=_e(),{resourceType:t,id:n}=Ht(),[r,o]=v.useState(),[s,c]=v.useState();return v.useEffect(()=>{e.readResource(t,n).then(d=>o(hi(d))).catch(d=>{Ne({color:"red",message:Qe(d)})})},[e,t,n]),r?a.jsxs(dt,{children:[a.jsxs(ze,{order:2,children:["Available ",t," profiles"]}),a.jsx(Ue,{children:a.jsxs(a.Fragment,{children:[a.jsx(zN,{resource:r,currentProfile:s,onChange:c}),s?a.jsx(vie,{profile:s,resource:r,onResourceUpdated:d=>o(d)},s.url):a.jsx(Ee,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const vie=({profile:e,resource:t,onResourceUpdated:n})=>{const r=_e(),[o,s]=v.useState(),[c,d]=v.useState(()=>t.meta?.profile?.includes(e.url)),f=v.useCallback(p=>{s(void 0);const m=Ml(p);c?tk(m,e.url):vB(m,e.url),r.updateResource(m).then(g=>{n(g),Ne({color:"green",message:"Success"})}).catch(g=>{s(Yt(g)),Ne({color:"red",message:Qe(g),autoClose:!1})})},[r,e.url,n,c]);return a.jsxs(Ue,{children:[a.jsx(rf,{size:"md",checked:c,label:`Conform resource to ${e.title}`,onChange:p=>d(p.currentTarget.checked),"data-testid":"profile-toggle"}),c?a.jsx(Hp,{profileUrl:e.url,defaultValue:t,onSubmit:f,outcome:o}):a.jsx("form",{noValidate:!0,onSubmit:p=>{p.preventDefault(),f(t)},children:a.jsx(ye,{justify:"flex-end",mt:"xl",children:a.jsx(Pe,{type:"submit",children:"OK"})})})]})},BN={"Create Only":"create","Update Only":"update","Delete Only":"delete","All Interactions":void 0},yie=Object.keys(BN);function xie(){const e=_e(),{id:t}=Ht(),n=Kt({reference:`Questionnaire/${t}`}),[r,o]=v.useState(),[s,c]=v.useState("create"),[d,f]=v.useState(0),p=e.searchResources("Subscription","status=active&_count=100").read().filter(g=>bie(g,n));function m(){r&&n&&e.createResource({resourceType:"Subscription",status:"active",reason:`Connect bot ${r.name} to questionnaire responses`,criteria:`QuestionnaireResponse?questionnaire=${n.url?`${n.url},${Ot(n)}`:Ot(n)}`,channel:{type:"rest-hook",endpoint:Ot(r)},...s?{extension:[{url:"https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction",valueCode:s}]}:void 0}).then(()=>{o(void 0),f(Date.now()),e.invalidateSearches("Subscription"),Ne({color:"green",message:"Success"})}).catch(g=>Ne({color:"red",message:Qe(g),autoClose:!1}))}return a.jsxs(dt,{children:[a.jsx(ze,{children:"Bots"}),a.jsxs(Ue,{children:[p.length===0&&a.jsx("p",{children:"No bots found."}),p.map(g=>a.jsxs("div",{children:[a.jsx("h3",{children:a.jsx(Nl,{value:{reference:g.channel?.endpoint},link:!0})}),a.jsxs("p",{children:["Criteria: ",g.criteria]})]},g.id))]}),a.jsx(_n,{}),a.jsxs(Ue,{mt:10,children:[a.jsx(Gd,{size:"lg",htmlFor:"bot",children:"Connect to bot"}),a.jsxs(ye,{children:[a.jsx(Pl,{name:"bot",resourceType:"Bot",onChange:g=>o(g)}),a.jsx(Pe,{onClick:m,children:"Connect"})]}),a.jsx(ye,{children:a.jsx(fn,{name:"subscription-trigger-event",defaultValue:"Create Only",label:"Subscription Trigger Event",data:yie,onChange:g=>c(BN[g.target.value])})})]}),a.jsx("div",{style:{display:"none"},children:d})]})}function bie(e,t){if(!t)return!1;const n=e.criteria||"",r=e.channel?.endpoint||"";return n.startsWith("QuestionnaireResponse?")&&r.startsWith("Bot/")&&(n.includes(Ot(t))||(t.url?n.includes(t.url):!1))}function Sie(){const{id:e}=Ht(),t=kn(),r=_e().readReference({reference:`Questionnaire/${e}`}).read(),[o,s]=v.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:he.EQUALS,value:r.url?`${r.url},Questionnaire/${e}`:`Questionnaire/${e}`}],fields:["id","_lastUpdated"]});return a.jsx(dt,{children:a.jsx(pu,{search:o,onClick:c=>t(`/${c.resource.resourceType}/${c.resource.id}`)?.catch(console.error),onChange:c=>s(c.definition),hideFilters:!0,hideToolbar:!0})})}function wie(){const e=_e(),{resourceType:t,id:n}=Ht(),r=Kt({reference:t+"/"+n}),o=v.useCallback(s=>{e.updateResource(Ml(s)).then(()=>{Ne({color:"green",message:"Success"})}).catch(c=>{Ne({color:"red",message:Qe(c),autoClose:!1})})},[e]);return r?a.jsx(dt,{children:a.jsx(_J,{onSubmit:o,definition:r})}):null}function jie(){const{resourceType:e,id:t}=Ht(),n=Kt({reference:e+"/"+t});return n?a.jsx(dt,{children:e==="MeasureReport"?a.jsx(TX,{measureReport:n}):a.jsx(VS,{value:n})}):null}const Cie="_container_1ue98_1",Eie="_entry_1ue98_14",Tie="_active_1ue98_21",bx={container:Cie,entry:Eie,active:Tie};function Rie(e){const t=_e(),n=Kt(e.value),[r,o]=v.useState();return v.useEffect(()=>{if(!n)return;const s=l1(n);if(!s)return;const c="reference"in s?s.reference:Ot(s);t.search("ServiceRequest","subject="+c).then(d=>{const p=(d.entry??[]).map(m=>m.resource);TP(p),p.reverse(),o(p)}).catch(d=>Ne({color:"red",message:Qe(d),autoClose:!1}))},[t,n]),r?a.jsx("div",{"data-testid":"quick-service-requests",className:bx.container,children:r.map(s=>a.jsxs("div",{className:Ut(bx.entry,{[bx.active]:s.id===n?.id}),children:[a.jsx("p",{children:a.jsx(jt,{to:s,children:_ie(s)})}),s.category?.[0]?.text&&a.jsx("p",{children:s.category[0]?.text}),s.code?.coding?.[0]?.code&&a.jsx("p",{children:s.code.coding[0]?.code}),a.jsx("p",{children:Aie(s)})]},s.id))}):null}function _ie(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function Aie(e){return e.authoredOn?e.authoredOn.substring(0,10):e.meta?.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const Die="_container_1l2dh_1",kie={container:Die};function Pie(e){const t=Kt(e.valueSet);if(!t)return null;const n=[""],r=t.compose?.include?.[0]?.concept?.map(o=>o.code);return r&&n.push(...r),e.defaultValue&&!n.includes(e.defaultValue)&&n.push(e.defaultValue),a.jsx("div",{className:kie.container,children:a.jsx(fn,{defaultValue:e.defaultValue,onChange:o=>e.onChange(o.currentTarget.value),data:n})})}function Nie(e){const t=Kt(e.specimen);return t?a.jsxs(xt,{children:[a.jsxs(xt.Entry,{children:[a.jsx(xt.Key,{children:"Type"}),a.jsx(xt.Value,{children:"Specimen"})]}),a.jsxs(xt.Entry,{children:[a.jsx(xt.Key,{children:"Collected"}),a.jsx(xt.Value,{children:wr(t.collection?.collectedDateTime)})]}),a.jsxs(xt.Entry,{children:[a.jsx(xt.Key,{children:"Specimen Age"}),a.jsx(xt.Value,{children:Oie(t)})]}),t.collection?.collectedDateTime&&t.receivedTime?a.jsxs(xt.Entry,{children:[a.jsx(xt.Key,{children:"Specimen Stability"}),a.jsx(xt.Value,{children:Mie(t)})]}):a.jsx(a.Fragment,{})]}):null}function Oie(e){const t=e.collection?.collectedDateTime;if(!t)return;const n=new Date(t);return VN(FN(n,new Date))}function Mie(e){if(!e.collection?.collectedDateTime||!e.receivedTime)return;const t=new Date(e.collection.collectedDateTime),n=new Date(e.receivedTime);return VN(FN(t,n))}function VN(e){return e.toString().padStart(3,"0")+"D"}function FN(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function Lie(e){const t=["Timeline"];return e==="Bot"&&t.push("Editor","Subscriptions"),e==="PlanDefinition"&&t.push("Apply","Builder"),e==="Questionnaire"&&t.push("Preview","Builder","Bots","Responses"),e==="ValueSet"&&t.push("Preview"),(e==="DiagnosticReport"||e==="MeasureReport")&&t.push("Report"),e==="RequestGroup"&&t.push("Checklist"),e==="ObservationDefinition"&&t.push("Ranges"),e==="Agent"&&t.push("Tools"),t.push("Details","Edit","Event","History","Blame","JSON","Apps","Profiles"),e==="Patient"&&t.push("Export"),t}function Iie(){const e=_e(),{resourceType:t,id:n}=Ht(),r={reference:t+"/"+n},o=kn(),[s,c]=v.useState(),d=Kt(r,c),f=Lie(t),[p,m]=v.useState(()=>{const E=window.location.pathname.split("/").pop();return E&&f.map(T=>T.toLowerCase()).includes(E)?E:f[0].toLowerCase()});async function g(){const T=(await e.readHistory(t,n)).entry?.find(_=>!!_.resource)?.resource;T?y(T):Ne({color:"red",message:"No history to restore",autoClose:!1})}function y(E){e.updateResource(Ml(E)).then(()=>{c(void 0),Ne({color:"green",message:"Success"})}).catch(T=>{Ne({color:"red",message:Qe(T),autoClose:!1})})}if(s)return R8(s)?a.jsxs(dt,{children:[a.jsx(ze,{children:"Deleted"}),a.jsx("p",{children:"The resource was deleted."}),a.jsx(Pe,{color:"red",onClick:g,children:"Restore"})]}):a.jsx(Er,{outcome:s});function b(E){E||(E=f[0].toLowerCase()),m(E),o(`/${t}/${n}/${E}`)?.catch(console.error)}function S(E){const T=d,_=T.orderDetail||[];_.length===0&&_.push({}),_[0].text!==E&&(_[0].text=E,y({...T,orderDetail:_}))}const j=d&&l1(d),C=d&&Ote(d),R=e.getUserConfiguration()?.option?.find(E=>E.id==="statusValueSet")?.valueString;return a.jsxs(a.Fragment,{children:[d?.resourceType==="ServiceRequest"&&R&&a.jsx(Pie,{valueSet:{reference:R},defaultValue:d.orderDetail?.[0]?.text,onChange:S},Ot(d)+"-"+d.orderDetail?.[0]?.text),d&&a.jsx(Rie,{value:d}),d&&a.jsxs(Or,{children:[j&&a.jsx(MP,{patient:j}),C&&a.jsx(Nie,{specimen:C}),t!=="Patient"&&a.jsx(ON,{resource:r}),a.jsx(Jr,{children:a.jsx(Pt,{value:p.toLowerCase(),onChange:b,children:a.jsx(Pt.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:f.map(E=>a.jsx(Pt.Tab,{value:E.toLowerCase(),children:E},E))})})})]}),a.jsx(i1,{})]})}function rp(){const e=kn(),{resourceType:t,id:n,versionId:r,tab:o}=Ht(),s=_e(),[c,d]=v.useState(!0),[f,p]=v.useState(),[m,g]=v.useState();if(v.useEffect(()=>{g(void 0),d(!0),s.readHistory(t,n).then(T=>p(T)).then(()=>d(!1)).catch(T=>{g(T),d(!1)})},[s,t,n]),c)return a.jsx(Ni,{});const y=f?.entry??[],b=y.findIndex(T=>T.resource?.meta?.versionId===r);if(b===-1)return a.jsxs(dt,{children:[a.jsx(ze,{children:"Version not found"}),a.jsx(jt,{to:`/${t}/${n}`,children:"Return to resource"})]});const S=y[b].resource,j=b<y.length-1?y[b+1].resource:void 0,C="diff",R=o||C,E=y.length-b;return a.jsx(Zd,{maw:1200,children:a.jsx(kl,{children:a.jsxs(Ue,{gap:"lg",children:[m&&a.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)}),a.jsxs(Lm,{cols:2,mb:"lg",children:[a.jsx(zi,{total:y.length,value:E,getControlProps:kP,onChange:T=>e(`/${t}/${n}/_history/${y[y.length-T]?.resource?.meta?.versionId}/${R}`)?.catch(console.error)}),a.jsx(ye,{justify:"right",children:a.jsx(qc,{data:[{value:"diff",label:"Diff"},{value:"raw",label:"Raw"}],value:R,onChange:T=>e(`/${t}/${n}/_history/${r}/${T||C}`)?.catch(console.error)})})]}),a.jsx(ce,{mb:"lg",children:a.jsxs(yf,{compact:!0,children:[a.jsx(Lr,{term:"Version ID",children:S.meta?.versionId}),a.jsx(Lr,{term:"Author",children:a.jsx(Ic,{value:S.meta?.author,link:!0},S.meta?.author?.reference)}),a.jsx(Lr,{term:"Date/Time",children:wr(S.meta?.lastUpdated)})]})}),R==="diff"&&a.jsx(rZ,{original:j??{resourceType:t,id:n},revised:S}),R==="raw"&&a.jsx("pre",{style:{fontSize:"9pt"},children:JSON.stringify(S,void 0,2)})]})})})}function zie(){const{resourceType:e,id:t}=Ht(),n=kn(),[r,o]=v.useState({resourceType:"Subscription",filters:[{code:"url",operator:he.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return a.jsx(dt,{children:a.jsx(pu,{search:r,onClick:s=>n(`/${s.resource.resourceType}/${s.resource.id}`)?.catch(console.error),onChange:s=>o(s.definition),hideFilters:!0})})}function $ie(e){const t=_e(),{resource:n,opened:r,onClose:o}=e,[s,c]=v.useState(!1),[d,f]=v.useState(),[p,m]=v.useState(!1),g=v.useCallback(async()=>{if(n?.id)try{await t.post(t.fhirUrl(n.resourceType,n.id,"$resend"),{subscription:s&&d?Ot(d):void 0,verbose:p}),Ne({color:"green",message:"Done"}),o()}catch(y){Ne({color:"red",message:Qe(y),autoClose:!1})}},[t,n,o,s,d,p]);return a.jsx(Vn,{opened:r,onClose:o,title:"Resend Subscriptions",children:a.jsx(pt,{onSubmit:g,children:a.jsxs(Ue,{children:[a.jsx($n,{label:"Choose subscription (all subscriptions by default)",onChange:y=>c(y.currentTarget.checked)}),s&&a.jsx(Pl,{name:"subscription",resourceType:"Subscription",placeholder:"Subscription",onChange:f}),a.jsx($n,{label:"Verbose mode",onChange:y=>m(y.currentTarget.checked)}),a.jsx(ye,{justify:"flex-end",children:a.jsx(Pe,{type:"submit",children:"Resend"})})]})})})}function E2(){const e=_e(),t=df(),{resourceType:n,id:r}=Ht(),o={reference:n+"/"+r},[s,c]=v.useState(),d=Zc(!1);function f(E,T){return e.updateResource({...E,priority:T})}function p(E,T){f(E,"stat").then(T).catch(console.error)}function m(E,T){f(E,"routine").then(T).catch(console.error)}function g(E){t(`/${E.resourceType}/${E.id}`)}function y(E){t(`/${E.resourceType}/${E.id}/edit`)}function b(E){t(`/${E.resourceType}/${E.id}/delete`)}function S(E){c(E),d[1].open()}function j(E){t(`/${E.resourceType}/${E.id}/_history/${E.meta?.versionId}`)}function C(E,T){const _="aws-textract";Ne({id:_,title:"AWS Textract in Progress",message:"Extracting text... This may take a moment...",loading:!0,autoClose:!1}),e.post(e.fhirUrl(E.resourceType,E.id,"$aws-textract"),{}).then(()=>{T(),rl({id:_,title:"AWS Textract Successful",message:"Text successfully extracted.",color:"green",icon:a.jsx(Vo,{size:"1rem"}),loading:!1,withCloseButton:!0})}).catch(k=>rl({id:_,title:"AWS Textract Error",color:"red",message:Qe(k),icon:a.jsx(yl,{size:"1rem"}),loading:!1,withCloseButton:!0}))}function R(E){const{primaryResource:T,currentResource:_,reloadTimeline:k}=E,I=_.resourceType===T.resourceType&&_.id===T.id,A=_.resourceType==="Communication"&&_.priority!=="stat",P=_.resourceType==="Communication"&&_.priority==="stat",z=I,B=!I,Y=!I,J=!I,Z=e.getProjectMembership()?.admin,$=Z,Q=Mre()&&(_.resourceType==="DocumentReference"||_.resourceType==="Media");return a.jsxs(xe.Dropdown,{children:[a.jsx(xe.Label,{children:"Resource"}),A&&a.jsx(xe.Item,{leftSection:a.jsx(rG,{size:14}),onClick:()=>p(_,k),"aria-label":`Pin ${Ot(_)}`,children:"Pin"}),P&&a.jsx(xe.Item,{leftSection:a.jsx(oG,{size:14}),onClick:()=>m(_,k),"aria-label":`Unpin ${Ot(_)}`,children:"Unpin"}),B&&a.jsx(xe.Item,{leftSection:a.jsx(eR,{size:14}),onClick:()=>g(_),"aria-label":`Details ${Ot(_)}`,children:"Details"}),z&&a.jsx(xe.Item,{leftSection:a.jsx(eR,{size:14}),onClick:()=>j(_),"aria-label":`Details ${Ot(_)}`,children:"Details"}),Y&&a.jsx(xe.Item,{leftSection:a.jsx(Mk,{size:14}),onClick:()=>y(_),"aria-label":`Edit ${Ot(_)}`,children:"Edit"}),Z&&a.jsxs(a.Fragment,{children:[a.jsx(xe.Divider,{}),a.jsx(xe.Label,{children:"Admin"}),$&&a.jsx(xe.Item,{leftSection:a.jsx(hG,{size:14}),onClick:()=>S(_),"aria-label":`Resend Subscriptions ${Ot(_)}`,children:"Resend Subscriptions"})]}),Q&&a.jsxs(a.Fragment,{children:[a.jsx(xe.Divider,{}),a.jsx(xe.Label,{children:"AWS AI"}),a.jsx(xe.Item,{leftSection:a.jsx(kG,{size:14}),onClick:()=>C(_,k),"aria-label":`AWS Textract ${Ot(_)}`,children:"AWS Textract"})]}),J&&a.jsxs(a.Fragment,{children:[a.jsx(xe.Divider,{}),a.jsx(xe.Label,{children:"Danger zone"}),a.jsx(xe.Item,{color:"red",leftSection:a.jsx(Ym,{size:14}),onClick:()=>b(_),"aria-label":`Delete ${Ot(_)}`,children:"Delete"})]})]})}return a.jsxs(a.Fragment,{children:[n==="Encounter"&&a.jsx(xK,{encounter:o,getMenu:R}),n==="Patient"&&a.jsx(kX,{patient:o,getMenu:R}),n==="ServiceRequest"&&a.jsx(uZ,{serviceRequest:o,getMenu:R}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&a.jsx(yK,{resource:o,getMenu:R}),a.jsx($ie,{resource:s,opened:d[0],onClose:d[1].close},`resend-subscriptions-${s?.id}`)]})}function Uie(e){const{opened:t,close:n,version:r,loadingStatus:o,handleStatus:s,handleUpgrade:c}=e,[d,f]=v.useState(),[p,m]=v.useState(!1);return v.useEffect(()=>{t&&(d||KF("app-tools-page").then(f).catch(console.error),s())},[t,d,s]),d&&r&&!o?r==="unknown"?a.jsx("p",{children:"Unable to determine the current version of the agent. Check the network connectivity of the agent."}):r.startsWith(d)?a.jsxs("p",{children:["This agent is already on the latest version (",d,")."]}):a.jsxs(a.Fragment,{children:[a.jsxs("p",{children:["Are you sure you want to upgrade this agent from version ",r," to version ",d,"?"]}),a.jsxs(ye,{children:[a.jsx(Pe,{onClick:()=>{c(p),n()},"aria-label":"Confirm upgrade",children:"Confirm Upgrade"}),a.jsx($n,{label:"Force",onChange:g=>m(g.currentTarget.checked)})]})]}):a.jsx(Ni,{})}function Bie(){const e=_e(),{id:t}=Ht(),n=v.useMemo(()=>({reference:"Agent/"+t}),[t]),[r,o]=v.useState(!1),[s,c]=v.useState(!1),[d,f]=v.useState(!1),[p,m]=v.useState(!1),[g,y]=v.useState(),[b,S]=v.useState(),[j,C]=v.useState(),[R,E]=v.useState(),[T,_]=v.useState(!1),[k,I]=v.useState(!1),[A,P]=v.useState(),[z,{open:B,close:Y}]=Zc(!1);v.useEffect(()=>{if(r||s||d||T){I(!0);return}I(!1)},[r,s,d,T]);const J=v.useCallback(()=>{o(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(V=>{y(V.parameter?.find(K=>K.name==="status")?.valueCode),S(V.parameter?.find(K=>K.name==="version")?.valueString),C(V.parameter?.find(K=>K.name==="lastUpdated")?.valueInstant)}).catch(V=>U(Qe(V))).finally(()=>o(!1))},[e,t]),Z=v.useCallback(V=>{const K=V.host,O=V.pingCount||1;K&&(_(!0),e.pushToAgent(n,K,`PING ${O}`,nn.PING,!0).then(F=>E(F)).catch(F=>U(Qe(F))).finally(()=>_(!1)))},[e,n]),$=v.useCallback(()=>{c(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(V=>{L("Agent config reloaded successfully.")}).catch(V=>U(Qe(V))).finally(()=>c(!1))},[e,t]),Q=v.useCallback(V=>{f(!0);const K=e.fhirUrl("Agent",t,"$upgrade");K.searchParams.set("force",String(V)),e.get(K,{cache:"reload"}).then(O=>{L("Agent upgraded successfully.")}).catch(O=>U(Qe(O))).finally(()=>f(!1))},[e,t]),M=v.useCallback(V=>{m(!0);const K=V.logLimit||20;e.get(e.fhirUrl("Agent",t,`$fetch-logs${K!==void 0?`?limit=${K}`:""}`),{cache:"reload"}).then(O=>{const F=O?.parameter?.find(ae=>ae.name==="logs");F&&P(F?.valueString)}).catch(O=>U(Qe(O))).finally(()=>m(!1))},[e,t]);function L(V){Ne({color:"green",title:"Success",icon:a.jsx(Vo,{size:"1rem"}),message:V})}function U(V){Ne({color:"red",title:"Error",message:V,autoClose:!1})}return a.jsxs(dt,{children:[a.jsx(Vn,{opened:z,onClose:Y,title:"Upgrade Agent",centered:!0,children:a.jsx(Uie,{opened:z,close:Y,version:b,loadingStatus:r,handleStatus:J,handleUpgrade:Q})}),a.jsx(ze,{order:1,children:"Agent Tools"}),a.jsxs("div",{style:{marginBottom:10},children:["Agent: ",a.jsx(Nl,{value:n,link:!0})]}),a.jsx(_n,{my:"lg"}),a.jsx(ze,{order:2,children:"Agent Status"}),a.jsx("p",{children:"Retrieve the status of the agent. This tests whether the agent is connected to the Medplum server, and the last time it was able to communicate."}),a.jsx(Pe,{onClick:J,loading:r,disabled:k&&!r,children:"Get Status"}),!r&&g&&a.jsx(de,{children:a.jsxs(de.Tbody,{children:[a.jsxs(de.Tr,{children:[a.jsx(de.Td,{children:"Status"}),a.jsx(de.Td,{children:a.jsx(ig,{status:g})})]}),a.jsxs(de.Tr,{children:[a.jsx(de.Td,{children:"Version"}),a.jsx(de.Td,{children:b})]}),a.jsxs(de.Tr,{children:[a.jsx(de.Td,{children:"Last Updated"}),a.jsx(de.Td,{children:wr(j,void 0,{timeZoneName:"longOffset"})})]})]})}),a.jsx(_n,{my:"lg"}),a.jsx(ze,{order:2,children:"Reload Config"}),a.jsx("p",{children:"Reload the configuration of this agent, syncing it with the current version of the Agent resource on the Medplum server."}),a.jsx(Pe,{onClick:$,loading:s,disabled:k&&!s,"aria-label":"Reload config",children:"Reload Config"}),a.jsx(_n,{my:"lg"}),a.jsx(ze,{order:2,children:"Upgrade Agent"}),a.jsx("p",{children:"Upgrade the version of this agent, to either the latest (default) or a specified version."}),a.jsx(Pe,{onClick:B,loading:d,disabled:k&&!d,"aria-label":"Upgrade agent",children:"Upgrade"}),a.jsx(_n,{my:"lg"}),a.jsxs(pt,{onSubmit:M,children:[a.jsx(ze,{order:2,children:"Fetch Logs"}),a.jsx("p",{children:"Fetch logs from the agent."}),A?.length?a.jsx(Jd,{block:!0,mb:15,children:A}):null,a.jsxs(ye,{children:[a.jsx(Hc,{w:100,id:"logLimit",name:"logLimit",placeholder:"20",label:"Log Limit"}),a.jsx(Pe,{mt:22,loading:p,disabled:k&&!p,"aria-label":"Fetch logs",type:"submit",children:"Fetch Logs"})]})]}),a.jsx(_n,{my:"lg"}),a.jsx(ze,{order:2,children:"Ping from Agent"}),a.jsx("p",{children:"Send a ping command from the agent to a valid IP address or hostname. Use this tool to troubleshoot local network connectivity."}),a.jsx(pt,{onSubmit:Z,children:a.jsxs(ye,{children:[a.jsx(He,{id:"host",name:"host",placeholder:"ex. 127.0.0.1",label:"IP Address / Hostname",rightSection:a.jsx(Dn,{size:24,radius:"xl",variant:"filled",type:"submit","aria-label":"Ping",loading:T,disabled:k&&!T,children:a.jsx(vG,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),a.jsx(Hc,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!T&&R&&a.jsxs(a.Fragment,{children:[a.jsx(ze,{order:5,mt:"sm",mb:0,children:"Last Ping"}),a.jsx("pre",{children:R})]})]})}function Vie(){const e=kn(),t=_e(),[n,r]=v.useState();v.useEffect(()=>{t.get("auth/me",{cache:"no-cache"}).then(r).catch(s=>Ne({color:"red",message:Qe(s),autoClose:!1}))},[t]);function o(s){t.post("auth/revoke",{loginId:s}).then(()=>t.get("auth/me",{cache:"no-cache"})).then(r).then(()=>Ne({color:"green",message:"Login revoked"})).catch(c=>Ne({color:"red",message:Qe(c),autoClose:!1}))}return n?a.jsxs(a.Fragment,{children:[a.jsxs(dt,{children:[a.jsx(ze,{children:"Security"}),a.jsxs(yf,{children:[a.jsx(Lr,{term:"ID",children:a.jsx(Mt,{href:`/${Ot(n.profile)}`,children:n.profile.id})}),a.jsx(Lr,{term:"Resource Type",children:n.profile.resourceType}),a.jsx(Lr,{term:"Name",children:Rs(n.profile.name?.[0])})]})]}),a.jsxs(dt,{children:[a.jsx(ze,{children:"Sessions"}),a.jsxs(de,{children:[a.jsx("thead",{children:a.jsxs("tr",{children:[a.jsx("th",{children:"OS"}),a.jsx("th",{children:"Browser"}),a.jsx("th",{children:"IP Address"}),a.jsx("th",{children:"Auth Method"}),a.jsx("th",{children:"Last Updated"}),a.jsx("th",{})]})}),a.jsx("tbody",{children:n.security.sessions.map(s=>a.jsxs("tr",{children:[a.jsx("td",{children:s.os}),a.jsx("td",{children:s.browser}),a.jsx("td",{children:s.remoteAddress}),a.jsx("td",{children:s.authMethod}),a.jsx("td",{children:wr(s.lastUpdated)}),a.jsx("td",{children:a.jsx(Mt,{href:"#",onClick:()=>o(s.id),children:"Revoke"})})]},s.id))})]})]}),a.jsxs(dt,{children:[a.jsx(ze,{children:"Password"}),a.jsx(Pe,{onClick:()=>e("/changepassword")?.catch(console.error),children:"Change password"})]}),a.jsxs(dt,{children:[a.jsx(ze,{children:"Multi Factor Auth"}),a.jsxs("p",{children:["Enrolled: ",n.security.mfaEnrolled.toString()]}),!n.security.mfaEnrolled&&a.jsx(Pe,{onClick:()=>e("/mfa")?.catch(console.error),children:"Enroll"})]})]}):null}function Fie(){const{id:e,secret:t}=Ht(),n=_e(),[r,o]=v.useState(),[s,c]=v.useState(!1),d=hu(r,void 0);return a.jsxs(dt,{width:450,children:[a.jsx(Er,{issues:d}),a.jsxs(pt,{onSubmit:f=>{if(f.password!==f.confirmPassword){o(Eo("Passwords do not match","confirmPassword"));return}o(void 0);const p={id:e,secret:t,password:f.password};n.post("auth/setpassword",p).then(()=>c(!0)).catch(m=>o(Yt(m)))},children:[a.jsxs(hr,{style:{flexDirection:"column"},children:[a.jsx($i,{size:32}),a.jsx(ze,{children:"Set password"})]}),!s&&a.jsxs(Ue,{children:[a.jsx(Ki,{name:"password",label:"New password",required:!0,error:Lt(r,"password")}),a.jsx(Ki,{name:"confirmPassword",label:"Confirm new password",required:!0,error:Lt(r,"confirmPassword")}),a.jsx(ye,{justify:"flex-end",mt:"xl",children:a.jsx(Pe,{type:"submit",children:"Set password"})})]}),s&&a.jsxs("div",{"data-testid":"success",children:["Password set. You can now ",a.jsx(jt,{to:"/signin",children:"sign in"}),"."]})]})]})}function Hie(){const e=ff(),t=kn(),[n]=s1(),r=Ef(),o=v.useCallback(()=>{const s=n.get("next");t(s?.startsWith("/")?s:"/")?.catch(console.error)},[n,t]);return v.useEffect(()=>{e&&n.has("next")&&o()},[e,n,o]),a.jsxs(lP,{onSuccess:()=>o(),onForgotPassword:()=>t("/resetpassword")?.catch(console.error),onRegister:LN()?()=>t("/register")?.catch(console.error):void 0,googleClientId:r.googleClientId,login:n.get("login")||void 0,projectId:n.get("project")||void 0,children:[a.jsx($i,{size:32}),a.jsxs(ze,{children:["Sign in to ",Fk()]}),n.get("project")==="new"&&a.jsx("div",{children:"Sign in again to create a new project"})]})}function qie(){const e=kn(),t=ti(),[n,r]=v.useState(),[o,s]=v.useState(),[c,d]=v.useState();return v.useEffect(()=>{const f=Object.fromEntries(new URLSearchParams(t.search).entries());r(f.resourceType),s(f.query),d(JSON.parse(f.fields))},[t]),!n||!o||!c?null:a.jsx(gX,{resourceType:n,checkboxesEnabled:!0,query:o,fields:c,onClick:f=>e(`/${n}/${f.resource.id}`)?.catch(console.error),onAuxClick:f=>window.open(`/${n}/${f.resource.id}`,"_blank"),onBulk:f=>{e(`/bulk/${n}?ids=${f.join(",")}`)?.catch(console.error)}})}function Gie(){const{id:e,secret:t}=Ht(),n=_e(),[r,o]=v.useState(),[s,c]=v.useState(!1),d=hu(r,void 0);return a.jsxs(dt,{width:450,children:[a.jsx(Er,{issues:d}),a.jsxs(pt,{onSubmit:()=>{o(void 0);const f={id:e,secret:t};n.post("auth/verifyemail",f).then(()=>c(!0)).catch(p=>o(Yt(p)))},children:[a.jsxs(hr,{style:{flexDirection:"column"},children:[a.jsx($i,{size:32}),a.jsx(ze,{children:"Email address verification required"})]}),!s&&a.jsxs(Ue,{children:[a.jsx("p",{children:"In order to sign in, click the button below to verify your ability to receive email at the address this link was sent to."}),a.jsx(ye,{justify:"flex-end",mt:"xl",children:a.jsx(Pe,{type:"submit",children:"Verify email"})})]}),s&&a.jsxs("div",{"data-testid":"success",children:["Email verified. You can now ",a.jsx(jt,{to:"/signin",children:"sign in"}),"."]})]})]})}function Qie(){return a.jsx(Jee,{children:a.jsxs($e,{errorElement:a.jsx(bre,{}),children:[a.jsx($e,{path:"/signin",element:a.jsx(Hie,{})}),a.jsx($e,{path:"/oauth",element:a.jsx(Lre,{})}),a.jsx($e,{path:"/resetpassword",element:a.jsx(zre,{})}),a.jsx($e,{path:"/setpassword/:id/:secret",element:a.jsx(Fie,{})}),a.jsx($e,{path:"/verifyemail/:id/:secret",element:a.jsx(Gie,{})}),a.jsx($e,{path:"/register",element:a.jsx(Ire,{})}),a.jsx($e,{path:"/changepassword",element:a.jsx(vre,{})}),a.jsx($e,{path:"/security",element:a.jsx(Vie,{})}),a.jsx($e,{path:"/mfa",element:a.jsx(Nre,{})}),a.jsx($e,{path:"/batch",element:a.jsx(mre,{})}),a.jsx($e,{path:"/bulk/:resourceType",element:a.jsx(gre,{})}),a.jsx($e,{path:"/smart",element:a.jsx(qie,{})}),a.jsx($e,{path:"/forms/:id",element:a.jsx(Sre,{})}),a.jsx($e,{path:"/admin/super",element:a.jsx(sne,{})}),a.jsx($e,{path:"/admin/super/asyncjob",element:a.jsx(tne,{})}),a.jsx($e,{path:"/admin/super/db",element:a.jsx(Gte,{})}),a.jsx($e,{path:"/admin/config",element:a.jsx(Xte,{})}),a.jsxs($e,{path:"/admin",element:a.jsx(Jte,{}),children:[a.jsx($e,{path:"patients",element:a.jsx(Kte,{})}),a.jsx($e,{path:"bots/new",element:a.jsx(Ite,{})}),a.jsx($e,{path:"bots",element:a.jsx(Mte,{})}),a.jsx($e,{path:"clients/new",element:a.jsx(zte,{})}),a.jsx($e,{path:"clients",element:a.jsx(Lte,{})}),a.jsx($e,{path:"details",element:a.jsx(o2,{})}),a.jsx($e,{path:"invite",element:a.jsx(Yte,{})}),a.jsx($e,{path:"users",element:a.jsx(une,{})}),a.jsx($e,{path:"project",element:a.jsx(o2,{})}),a.jsx($e,{path:"secrets",element:a.jsx(Zte,{})}),a.jsx($e,{path:"sites",element:a.jsx(ene,{})}),a.jsx($e,{path:"members/:membershipId",element:a.jsx(Wte,{})})]}),a.jsx($e,{path:"/lab/assays",element:a.jsx(kre,{})}),a.jsx($e,{path:"/lab/panels",element:a.jsx(Pre,{})}),a.jsxs($e,{path:"/:resourceType/new",element:a.jsx(xre,{}),children:[a.jsx($e,{index:!0,element:a.jsx(xx,{})}),a.jsx($e,{path:"form",element:a.jsx(xx,{})}),a.jsx($e,{path:"json",element:a.jsx(sie,{})}),a.jsx($e,{path:"profiles",element:a.jsx(xx,{})})]}),a.jsxs($e,{path:"/:resourceType/:id",element:a.jsx(Iie,{}),children:[a.jsx($e,{index:!0,element:a.jsx(E2,{})}),a.jsx($e,{path:"apply",element:a.jsx(Ure,{})}),a.jsx($e,{path:"apps",element:a.jsx(Bre,{})}),a.jsx($e,{path:"event",element:a.jsx(Fre,{})}),a.jsx($e,{path:"blame",element:a.jsx(Hre,{})}),a.jsx($e,{path:"bots",element:a.jsx(xie,{})}),a.jsx($e,{path:"builder",element:a.jsx(Zre,{})}),a.jsx($e,{path:"checklist",element:a.jsx(eie,{})}),a.jsx($e,{path:"delete",element:a.jsx(tie,{})}),a.jsx($e,{path:"details",element:a.jsx(iie,{})}),a.jsx($e,{path:"edit",element:a.jsx(oie,{})}),a.jsx($e,{path:"editor",element:a.jsx(Xre,{})}),a.jsxs($e,{path:"history",children:[a.jsx($e,{index:!0,element:a.jsx(C2,{})}),a.jsx($e,{path:":versionId/:tab",element:a.jsx(rp,{})}),a.jsx($e,{path:":versionId",element:a.jsx(rp,{})})]}),a.jsxs($e,{path:"_history",children:[a.jsx($e,{index:!0,element:a.jsx(C2,{})}),a.jsx($e,{path:":versionId/:tab",element:a.jsx(rp,{})}),a.jsx($e,{path:":versionId",element:a.jsx(rp,{})})]}),a.jsx($e,{path:"json",element:a.jsx(lie,{})}),a.jsx($e,{path:"preview",element:a.jsx(mie,{})}),a.jsx($e,{path:"responses",element:a.jsx(Sie,{})}),a.jsx($e,{path:"report",element:a.jsx(jie,{})}),a.jsx($e,{path:"ranges",element:a.jsx(wie,{})}),a.jsx($e,{path:"subscriptions",element:a.jsx(zie,{})}),a.jsx($e,{path:"timeline",element:a.jsx(E2,{})}),a.jsx($e,{path:"tools",element:a.jsx(Bie,{})}),a.jsx($e,{path:"profiles",element:a.jsx(gie,{})}),a.jsx($e,{path:"export",element:a.jsx(aie,{})})]}),a.jsx($e,{path:"/:resourceType",element:a.jsx(S2,{})}),a.jsx($e,{path:"/",element:a.jsx(S2,{})})]})})}function Wie(){const e=_e(),t=e.getUserConfiguration(),n=ti(),[r]=s1();return e.isLoading()?a.jsx(Ni,{}):a.jsx(ZQ,{logo:a.jsx($i,{size:24}),pathname:n.pathname,searchParams:r,version:vk,menus:Yie(t),displayAddBookmark:!!t?.id,children:a.jsx(v.Suspense,{fallback:a.jsx(Ni,{}),children:a.jsx(Qie,{})})})}function Yie(e){const t=e?.menu?.map(n=>({title:n.title,links:n.link?.map(r=>({label:r.name,href:r.target,icon:Kie(r.target)}))||[]}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:a.jsx(Fq,{})}]}),t}const T2={Patient:EG,Practitioner:Lq,Organization:ZH,ServiceRequest:uG,DiagnosticReport:mG,Questionnaire:Oq,admin:QH,AccessPolicy:Bq,Subscription:MG,batch:tG,Observation:Xq};function Kie(e){if(e.includes("admin/super/db"))return a.jsx(gq,{});try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in T2){const n=T2[t];return a.jsx(n,{})}}catch{}return a.jsx(Im,{w:20})}async function Xie(){const e=Ef(),t=new yk({baseUrl:e.baseUrl,clientId:e.clientId,storagePrefix:"@medplum:",cacheTime:6e4,autoBatchTime:100,onUnauthenticated:()=>{window.location.pathname!=="/signin"&&window.location.pathname!=="/oauth"&&(window.location.href="/signin?next="+encodeURIComponent(window.location.pathname+window.location.search))}}),n={headings:{sizes:{h1:{fontSize:"1.125rem",fontWeight:"500",lineHeight:"2.0"}}},fontSizes:{xs:"0.6875rem",sm:"0.875rem",md:"0.875rem",lg:"1.0rem",xl:"1.125rem"}},r=wte([{path:"*",element:a.jsx(Wie,{})}]),o=c=>r.navigate(c);gZ.createRoot(document.getElementById("root")).render(a.jsx(v.StrictMode,{children:a.jsx(XF,{medplum:t,navigate:o,children:a.jsxs(K2,{theme:n,children:[a.jsx(Ra,{position:"bottom-right"}),a.jsx(Wee,{router:r})]})})}))}Xie().catch(console.error);
|
|
263
|
-
//# sourceMappingURL=index-
|
|
263
|
+
//# sourceMappingURL=index-CjxNlO-J.js.map
|