@medplum/app 3.1.9 → 3.1.10

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.
@@ -90,7 +90,7 @@ Error generating stack: `+i.message+`
90
90
  allowNegative: `+i+`
91
91
  `),i=!1),Object.assign(Object.assign({},e),{allowNegative:i})}function e9(e){e=ZO(e),e.decimalSeparator,e.allowedDecimalSeparators,e.thousandsGroupStyle;var t=e.suffix,n=e.allowNegative,r=e.allowLeadingZeros,o=e.onKeyDown;o===void 0&&(o=hi);var i=e.onBlur;i===void 0&&(i=hi);var a=e.thousandSeparator,l=e.decimalScale,c=e.fixedDecimalScale,u=e.prefix;u===void 0&&(u="");var d=e.defaultValue,f=e.value,h=e.valueIsNumericString,m=e.onValueChange,g=PT(e,["decimalSeparator","allowedDecimalSeparators","thousandsGroupStyle","suffix","allowNegative","allowLeadingZeros","onKeyDown","onBlur","thousandSeparator","decimalScale","fixedDecimalScale","prefix","defaultValue","value","valueIsNumericString","onValueChange"]),v=th(e),S=v.decimalSeparator,y=v.allowedDecimalSeparators,b=function(A){return xb(A,e)},x=function(A,R){return XO(A,R,e)},w=_a(f)?d:f,j=h??YO(w,u,t);_a(f)?_a(d)||(j=j||typeof d=="number"):j=j||typeof f=="number";var E=function(A){return kT(A)?A:(typeof A=="number"&&(A=DT(A)),j&&typeof l=="number"?vb(A,l,!!c):A)},C=AT(E(f),E(d),!!j,b,x,m),T=C[0],_=T.numAsString,k=T.formattedValue,N=C[1],D=function(A){var R=A.target,P=A.key,$=R.selectionStart,B=R.selectionEnd,H=R.value;if(H===void 0&&(H=""),(P==="Backspace"||P==="Delete")&&B<u.length){A.preventDefault();return}if($!==B){o(A);return}P==="Backspace"&&H[0]==="-"&&$===u.length+1&&n&&Xi(R,1),l&&c&&(P==="Backspace"&&H[$-1]===S?(Xi(R,$-1),A.preventDefault()):P==="Delete"&&H[$]===S&&A.preventDefault()),y!=null&&y.includes(P)&&H[$]===S&&Xi(R,$+1);var Y=a===!0?",":a;P==="Backspace"&&H[$-1]===Y&&Xi(R,$-1),P==="Delete"&&H[$]===Y&&Xi(R,$+1),o(A)},M=function(A){var R=_;if(R.match(/\d/g)||(R=""),r||(R=$O(R)),c&&l&&(R=vb(R,l,c)),R!==_){var P=xb(R,e);N({formattedValue:P,value:R,floatValue:parseFloat(R)},{event:A,source:yc.event})}i(A)},I=function(A){return A===S?!0:xc(A)},L=function(A){var R=A.currentValue,P=A.lastValue,$=A.formattedValue,B=A.currentValueIndex,H=A.formattedValueIndex,Y=R[B],ie=$[H],Re=IT(P,R),se=Re.to;return B>=se.start&&B<se.end&&y&&y.includes(Y)&&ie===S?!0:Y===ie};return Object.assign(Object.assign({},g),{value:k,valueIsNumericString:!1,isValidInputCharacter:I,isCharacterSame:L,onValueChange:N,format:b,removeFormatting:x,getCaretBoundary:function(A){return JO(A,e)},onKeyDown:D,onBlur:M})}function t9(e){var t=e9(e);return on.createElement(GO,Object.assign({},t))}function bb({direction:e,style:t,...n}){return s.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:s.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 Um={root:"m_e2f5cd4e",controls:"m_95e17d22",control:"m_80b4b171"};const n9=/^(0\.0*|-0(\.0*)?)$/,r9=/^-?0\d+(\.\d+)?\.?$/;function o9(e){return(typeof e=="number"?e<Number.MAX_SAFE_INTEGER:!Number.isNaN(Number(e)))&&!Number.isNaN(e)}function wb(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 i9={step:1,clampBehavior:"blur",allowDecimal:!0,allowNegative:!0,withKeyboardEvents:!0,allowLeadingZeros:!0,trimLeadingZeroesOnBlur:!0,startValue:0},s9=(e,{size:t})=>({controls:{"--ni-chevron-size":De(t,"ni-chevron-size")}}),Oy=K((e,t)=>{const n=V("NumberInput",i9,e),{className:r,classNames:o,styles:i,unstyled:a,vars:l,onChange:c,onValueChange:u,value:d,defaultValue:f,max:h,min:m,step:g,hideControls:v,rightSection:S,isAllowed:y,clampBehavior:b,onBlur:x,allowDecimal:w,decimalScale:j,onKeyDown:E,onKeyDownCapture:C,handlersRef:T,startValue:_,disabled:k,rightSectionPointerEvents:N,allowNegative:D,readOnly:M,size:I,rightSectionWidth:L,stepHoldInterval:A,stepHoldDelay:R,allowLeadingZeros:P,withKeyboardEvents:$,trimLeadingZeroesOnBlur:B,...H}=n,Y=de({name:"NumberInput",classes:Um,props:n,classNames:o,styles:i,unstyled:a,vars:l,varsResolver:s9}),{resolvedClassNames:ie,resolvedStyles:Re}=Dc({classNames:o,styles:i,props:n}),[se,je]=mn({value:d,defaultValue:f,onChange:c}),ke=R!==void 0&&A!==void 0,oe=p.useRef(null),Be=p.useRef(null),ot=p.useRef(0),bt=(G,Se)=>{Se.source==="event"&&je(o9(G.floatValue)&&!n9.test(G.value)&&!(P&&r9.test(G.value))?G.floatValue:G.value),u==null||u(G,Se)},Qe=G=>{const Se=String(G).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);return Se?Math.max(0,(Se[1]?Se[1].length:0)-(Se[2]?+Se[2]:0)):0},Te=G=>{oe.current&&typeof G<"u"&&oe.current.setSelectionRange(G,G)},Pe=p.useRef();Pe.current=()=>{let G;const Se=Qe(se),We=Qe(g),it=Math.max(Se,We),ft=10**it;if(typeof se!="number"||Number.isNaN(se))G=Su(_,m,h);else if(h!==void 0){const Ut=(Math.round(se*ft)+Math.round(g*ft))/ft;G=Ut<=h?Ut:h}else G=(Math.round(se*ft)+Math.round(g*ft))/ft;const ln=G.toFixed(it);je(parseFloat(ln)),u==null||u({floatValue:parseFloat(ln),formattedValue:ln,value:ln},{source:"increment"}),setTimeout(()=>{var Ut;return Te((Ut=oe.current)==null?void 0:Ut.value.length)},0)};const nt=p.useRef();nt.current=()=>{let G;const Se=m!==void 0?m:D?Number.MIN_SAFE_INTEGER:0,We=Qe(se),it=Qe(g),ft=Math.max(We,it),ln=10**ft;if(typeof se!="number"||Number.isNaN(se))G=Su(_,Se,h);else{const Tn=(Math.round(se*ln)-Math.round(g*ln))/ln;G=Se!==void 0&&Tn<Se?Se:Tn}const Ut=G.toFixed(ft);je(parseFloat(Ut)),u==null||u({floatValue:parseFloat(Ut),formattedValue:Ut,value:Ut},{source:"decrement"}),setTimeout(()=>{var Tn;return Te((Tn=oe.current)==null?void 0:Tn.value.length)},0)};const Ue=G=>{E==null||E(G),!(M||!$)&&(G.key==="ArrowUp"&&(G.preventDefault(),Pe.current()),G.key==="ArrowDown"&&(G.preventDefault(),nt.current()))},ee=G=>{if(C==null||C(G),G.key==="Backspace"){const Se=oe.current;Se.selectionStart===0&&Se.selectionStart===Se.selectionEnd&&(G.preventDefault(),window.setTimeout(()=>Te(0),0))}};mf(T,{increment:Pe.current,decrement:nt.current});const ce=G=>{G?Pe.current():nt.current(),ot.current+=1},we=G=>{if(ce(G),ke){const Se=typeof A=="number"?A:A(ot.current);Be.current=window.setTimeout(()=>we(G),Se)}},He=(G,Se)=>{var We;G.preventDefault(),(We=oe.current)==null||We.focus(),ce(Se),ke&&(Be.current=window.setTimeout(()=>we(Se),R))},Z=()=>{Be.current&&window.clearTimeout(Be.current),Be.current=null,ot.current=0},le=s.jsxs("div",{...Y("controls"),children:[s.jsx(vn,{...Y("control"),tabIndex:-1,"aria-hidden":!0,disabled:k||typeof se=="number"&&h!==void 0&&se>=h,mod:{direction:"up"},onMouseDown:G=>G.preventDefault(),onPointerDown:G=>{He(G,!0)},onPointerUp:Z,onPointerLeave:Z,children:s.jsx(bb,{direction:"up"})}),s.jsx(vn,{...Y("control"),tabIndex:-1,"aria-hidden":!0,disabled:k||typeof se=="number"&&m!==void 0&&se<=m,mod:{direction:"down"},onMouseDown:G=>G.preventDefault(),onPointerDown:G=>{He(G,!1)},onPointerUp:Z,onPointerLeave:Z,children:s.jsx(bb,{direction:"down"})})]});return s.jsx(Jn,{component:t9,allowNegative:D,className:rt(Um.root,r),size:I,...H,readOnly:M,disabled:k,value:se,getInputRef:Kt(t,oe),onValueChange:bt,rightSection:v||M?S:S||le,classNames:ie,styles:Re,unstyled:a,__staticSelector:"NumberInput",decimalScale:w?j:0,onKeyDown:Ue,onKeyDownCapture:ee,rightSectionPointerEvents:N??(k?"none":void 0),rightSectionWidth:L??`var(--ni-right-section-width-${I||"sm"})`,allowLeadingZeros:P,onBlur:G=>{if(x==null||x(G),b==="blur"&&typeof se=="number"&&Su(se,m,h)!==se&&je(Su(se,m,h)),B&&typeof se=="string"){const Se=se.replace(/^0+/,""),We=parseFloat(Se);je(Number.isNaN(We)?Se:We)}},isAllowed:G=>b==="strict"?y?y(G)&&wb(G.floatValue,m,h):wb(G.floatValue,m,h):y?y(G):!0})});Oy.classes={...Jn.classes,...Um};Oy.displayName="@mantine/core/NumberInput";const[a9,nh]=$n("Pagination.Root component was not found in tree");var Wc={root:"m_4addd315",control:"m_326d024a",dots:"m_4ad7767d"};const l9={withPadding:!0},qc=K((e,t)=>{const n=V("PaginationControl",l9,e),{classNames:r,className:o,style:i,styles:a,vars:l,active:c,disabled:u,withPadding:d,mod:f,...h}=n,m=nh(),g=u||m.disabled;return s.jsx(vn,{ref:t,disabled:g,mod:[{active:c,disabled:g,"with-padding":d},f],...m.getStyles("control",{className:o,style:i,classNames:r,styles:a,active:!g}),...h})});qc.classes=Wc;qc.displayName="@mantine/core/PaginationControl";function Gc({style:e,children:t,path:n,...r}){return s.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:s.jsx("path",{d:n,fill:"currentColor"})})}const c9=e=>s.jsx(Gc,{...e,path:"M8.781 8l-3.3-3.3.943-.943L10.667 8l-4.243 4.243-.943-.943 3.3-3.3z"}),u9=e=>s.jsx(Gc,{...e,path:"M7.219 8l3.3 3.3-.943.943L5.333 8l4.243-4.243.943.943-3.3 3.3z"}),d9=e=>s.jsx(Gc,{...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"}),f9=e=>s.jsx(Gc,{...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"}),h9=e=>s.jsx(Gc,{...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"}),p9={icon:h9},rh=K((e,t)=>{const n=V("PaginationDots",p9,e),{classNames:r,className:o,style:i,styles:a,vars:l,icon:c,...u}=n,d=nh(),f=c;return s.jsx(W,{ref:t,...d.getStyles("dots",{className:o,style:i,styles:a,classNames:r}),...u,children:s.jsx(f,{style:{width:"calc(var(--pagination-control-size) / 1.8)",height:"calc(var(--pagination-control-size) / 1.8)"}})})});rh.classes=Wc;rh.displayName="@mantine/core/PaginationDots";function oh({icon:e,name:t,action:n,type:r}){const o={icon:e},i=p.forwardRef((a,l)=>{const{icon:c,...u}=V(t,o,a),d=c,f=nh(),h=r==="next"?f.active===f.total:f.active===1;return s.jsx(qc,{disabled:f.disabled||h,ref:l,onClick:f[n],withPadding:!1,...u,children:s.jsx(d,{className:"mantine-rotate-rtl",style:{width:"calc(var(--pagination-control-size) / 1.8)",height:"calc(var(--pagination-control-size) / 1.8)"}})})});return i.displayName=`@mantine/core/${t}`,i}const NT=oh({icon:c9,name:"PaginationNext",action:"onNext",type:"next"}),MT=oh({icon:u9,name:"PaginationPrevious",action:"onPrevious",type:"previous"}),OT=oh({icon:d9,name:"PaginationFirst",action:"onFirst",type:"previous"}),$T=oh({icon:f9,name:"PaginationLast",action:"onLast",type:"next"});function $y({dotsIcon:e}){const t=nh(),n=t.range.map((r,o)=>{var i;return r==="dots"?s.jsx(rh,{icon:e},o):s.jsx(qc,{active:r===t.active,"aria-current":r===t.active?"page":void 0,onClick:()=>t.onChange(r),disabled:t.disabled,...(i=t.getItemProps)==null?void 0:i.call(t,r),children:r},o)});return s.jsx(s.Fragment,{children:n})}$y.displayName="@mantine/core/PaginationItems";const m9={siblings:1,boundaries:1},g9=(e,{size:t,radius:n,color:r,autoContrast:o})=>({root:{"--pagination-control-radius":n===void 0?void 0:at(n),"--pagination-control-size":De(t,"pagination-control-size"),"--pagination-control-fz":sn(t),"--pagination-active-bg":r?st(r,e):void 0,"--pagination-active-color":Ts(o,e)?Bo({color:r,theme:e,autoContrast:o}):void 0}}),ih=K((e,t)=>{const n=V("PaginationRoot",m9,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,total:u,value:d,defaultValue:f,onChange:h,disabled:m,siblings:g,boundaries:v,color:S,radius:y,onNextPage:b,onPreviousPage:x,onFirstPage:w,onLastPage:j,getItemProps:E,autoContrast:C,...T}=n,_=de({name:"Pagination",classes:Wc,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:g9}),{range:k,setPage:N,next:D,previous:M,active:I,first:L,last:A}=U_({page:d,initialPage:f,onChange:h,total:u,siblings:g,boundaries:v}),R=tr(b,D),P=tr(x,M),$=tr(w,L),B=tr(j,A);return s.jsx(a9,{value:{total:u,range:k,active:I,disabled:m,getItemProps:E,onChange:N,onNext:R,onPrevious:P,onFirst:$,onLast:B,getStyles:_},children:s.jsx(W,{ref:t,..._("root"),...T})})});ih.classes=Wc;ih.displayName="@mantine/core/PaginationRoot";const v9={withControls:!0,siblings:1,boundaries:1,gap:8},Yr=K((e,t)=>{const n=V("Pagination",v9,e),{withEdges:r,withControls:o,getControlProps:i,nextIcon:a,previousIcon:l,lastIcon:c,firstIcon:u,dotsIcon:d,total:f,gap:h,...m}=n;return f<=0?null:s.jsx(ih,{ref:t,total:f,...m,children:s.jsxs(J,{gap:h,children:[r&&s.jsx(OT,{icon:u,...i==null?void 0:i("first")}),o&&s.jsx(MT,{icon:l,...i==null?void 0:i("previous")}),s.jsx($y,{dotsIcon:d}),o&&s.jsx(NT,{icon:a,...i==null?void 0:i("next")}),r&&s.jsx($T,{icon:c,...i==null?void 0:i("last")})]})})});Yr.classes=Wc;Yr.displayName="@mantine/core/Pagination";Yr.Root=ih;Yr.Control=qc;Yr.Dots=rh;Yr.First=OT;Yr.Last=$T;Yr.Next=NT;Yr.Previous=MT;Yr.Items=$y;const y9=({reveal:e})=>s.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:s.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 Hm={root:"m_f61ca620",input:"m_ccf8da4c",innerInput:"m_f2d85dd2",visibilityToggle:"m_b1072d44"};const x9={visibilityToggleIcon:y9},b9=(e,{size:t})=>({root:{"--psi-icon-size":De(t,"psi-icon-size"),"--psi-button-size":De(t,"psi-button-size")}}),Ur=K((e,t)=>{const n=V("PasswordInput",x9,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,required:u,error:d,leftSection:f,disabled:h,id:m,variant:g,inputContainer:v,description:S,label:y,size:b,errorProps:x,descriptionProps:w,labelProps:j,withAsterisk:E,inputWrapperOrder:C,wrapperProps:T,radius:_,rightSection:k,rightSectionWidth:N,rightSectionPointerEvents:D,leftSectionWidth:M,visible:I,defaultVisible:L,onVisibilityChange:A,visibilityToggleIcon:R,visibilityToggleButtonProps:P,rightSectionProps:$,leftSectionProps:B,leftSectionPointerEvents:H,withErrorStyles:Y,mod:ie,...Re}=n,se=Ln(m),[je,ke]=mn({value:I,defaultValue:L,finalValue:!1,onChange:A}),oe=()=>ke(!je),Be=de({name:"PasswordInput",classes:Hm,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:b9}),{resolvedClassNames:ot,resolvedStyles:bt}=Dc({classNames:r,styles:a,props:n}),{styleProps:Qe,rest:Te}=Vo(Re),Pe=R,nt=s.jsx(nn,{...Be("visibilityToggle"),disabled:h,radius:_,"aria-hidden":!P,tabIndex:-1,...P,variant:"subtle",color:"gray",unstyled:l,onMouseDown:Ue=>{var ee;Ue.preventDefault(),(ee=P==null?void 0:P.onMouseDown)==null||ee.call(P,Ue),oe()},onKeyDown:Ue=>{var ee;(ee=P==null?void 0:P.onKeyDown)==null||ee.call(P,Ue),Ue.key===" "&&(Ue.preventDefault(),oe())},children:s.jsx(Pe,{reveal:je})});return s.jsx(It.Wrapper,{required:u,id:se,label:y,error:d,description:S,size:b,classNames:ot,styles:bt,__staticSelector:"PasswordInput",errorProps:x,descriptionProps:w,unstyled:l,withAsterisk:E,inputWrapperOrder:C,inputContainer:v,variant:g,labelProps:{...j,htmlFor:se},mod:ie,...Be("root"),...Qe,...T,children:s.jsx(It,{component:"div",error:d,leftSection:f,size:b,classNames:{...ot,input:rt(Hm.input,ot.input)},styles:bt,radius:_,disabled:h,__staticSelector:"PasswordInput",rightSectionWidth:N,rightSection:k??nt,variant:g,unstyled:l,leftSectionWidth:M,rightSectionPointerEvents:D||"all",rightSectionProps:$,leftSectionProps:B,leftSectionPointerEvents:H,withAria:!1,withErrorStyles:Y,children:s.jsx("input",{required:u,"data-invalid":!!d||void 0,"data-with-left-section":!!f||void 0,...Be("innerInput"),disabled:h,id:se,ref:t,...Te,autoComplete:Te.autoComplete||"off",type:je?"text":"password"})})})});Ur.classes={...Jn.classes,...Hm};Ur.displayName="@mantine/core/PasswordInput";const[w9,LT]=Es(),[S9,j9]=Es();var FT={card:"m_9dc8ae12"};const C9={withBorder:!0},E9=(e,{radius:t})=>({card:{"--card-radius":at(t)}}),Ly=K((e,t)=>{const n=V("RadioCard",C9,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,checked:u,mod:d,withBorder:f,value:h,onClick:m,name:g,onKeyDown:v,...S}=n,y=de({name:"RadioCard",classes:FT,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:E9,rootSelector:"card"}),{dir:b}=ks(),x=LT(),w=typeof u=="boolean"?u:(x==null?void 0:x.value)===h||!1,j=g||(x==null?void 0:x.name),E=C=>{if(v==null||v(C),["ArrowDown","ArrowUp","ArrowLeft","ArrowRight"].includes(C.nativeEvent.code)){C.preventDefault();const T=Array.from(document.querySelectorAll(`[role="radio"][name="${j||"__mantine"}"]`)),_=T.findIndex(D=>D===C.target),k=_+1>=T.length?0:_+1,N=_-1<0?T.length-1:_-1;C.nativeEvent.code==="ArrowDown"&&(T[k].focus(),T[k].click()),C.nativeEvent.code==="ArrowUp"&&(T[N].focus(),T[N].click()),C.nativeEvent.code==="ArrowLeft"&&(T[b==="ltr"?N:k].focus(),T[b==="ltr"?N:k].click()),C.nativeEvent.code==="ArrowRight"&&(T[b==="ltr"?k:N].focus(),T[b==="ltr"?k:N].click())}};return s.jsx(S9,{value:{checked:w},children:s.jsx(vn,{ref:t,mod:[{"with-border":f,checked:w},d],...y("card"),...S,role:"radio","aria-checked":w,name:j,onClick:C=>{m==null||m(C),x==null||x.onChange(h||"")},onKeyDown:E})})});Ly.displayName="@mantine/core/RadioCard";Ly.classes=FT;const T9={},Fy=K((e,t)=>{const{value:n,defaultValue:r,onChange:o,size:i,wrapperProps:a,children:l,name:c,readOnly:u,...d}=V("RadioGroup",T9,e),f=Ln(c),[h,m]=mn({value:n,defaultValue:r,finalValue:"",onChange:o}),g=v=>!u&&m(typeof v=="string"?v:v.currentTarget.value);return s.jsx(w9,{value:{value:h,onChange:g,size:i,name:f},children:s.jsx(It.Wrapper,{size:i,ref:t,...a,...d,labelElement:"div",__staticSelector:"RadioGroup",children:s.jsx(fy,{role:"radiogroup",children:l})})})});Fy.classes=It.Wrapper.classes;Fy.displayName="@mantine/core/RadioGroup";function zT({size:e,style:t,...n}){return s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 5 5",style:{width:F(e),height:F(e),...t},"aria-hidden":!0,...n,children:s.jsx("circle",{cx:"2.5",cy:"2.5",r:"2.5",fill:"currentColor"})})}var BT={indicator:"m_717d7ff6",icon:"m_3e4da632","indicator--outline":"m_2980836c"};const P9={icon:zT},k9=(e,{radius:t,color:n,size:r,iconColor:o,variant:i,autoContrast:a})=>{const l=jr({color:n||e.primaryColor,theme:e}),c=l.isThemeColor&&l.shade===void 0?`var(--mantine-color-${l.color}-outline)`:l.color;return{indicator:{"--radio-size":De(r,"radio-size"),"--radio-radius":t===void 0?void 0:at(t),"--radio-color":i==="outline"?c:st(n,e),"--radio-icon-size":De(r,"radio-icon-size"),"--radio-icon-color":o?st(o,e):Ts(a,e)?Bo({color:n,theme:e,autoContrast:a}):void 0}}},zy=K((e,t)=>{const n=V("RadioIndicator",P9,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,icon:u,radius:d,color:f,iconColor:h,autoContrast:m,checked:g,mod:v,variant:S,disabled:y,...b}=n,x=u,w=de({name:"RadioIndicator",classes:BT,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:k9,rootSelector:"indicator"}),j=j9(),E=typeof g=="boolean"?g:(j==null?void 0:j.checked)||!1;return s.jsx(W,{ref:t,...w("indicator",{variant:S}),variant:S,mod:[{checked:E,disabled:y},v],...b,children:s.jsx(x,{...w("icon")})})});zy.displayName="@mantine/core/RadioIndicator";zy.classes=BT;var VT={root:"m_f3f1af94",inner:"m_89c4f5e4",icon:"m_f3ed6b2b",radio:"m_8a3dbb89","radio--outline":"m_1bfe9d39"};const R9={labelPosition:"right"},_9=(e,{size:t,radius:n,color:r,iconColor:o,variant:i,autoContrast:a})=>{const l=jr({color:r||e.primaryColor,theme:e}),c=l.isThemeColor&&l.shade===void 0?`var(--mantine-color-${l.color}-outline)`:l.color;return{root:{"--radio-size":De(t,"radio-size"),"--radio-radius":n===void 0?void 0:at(n),"--radio-color":i==="outline"?c:st(r,e),"--radio-icon-color":o?st(o,e):Ts(a,e)?Bo({color:r,theme:e,autoContrast:a}):void 0,"--radio-icon-size":De(t,"radio-icon-size")}}},ys=K((e,t)=>{const n=V("Radio",R9,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,id:u,size:d,label:f,labelPosition:h,description:m,error:g,radius:v,color:S,variant:y,disabled:b,wrapperProps:x,icon:w=zT,rootRef:j,iconColor:E,onChange:C,mod:T,..._}=n,k=de({name:"Radio",classes:VT,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:_9}),N=LT(),D=(N==null?void 0:N.size)??d,M=n.size?d:D,{styleProps:I,rest:L}=Vo(_),A=Ln(u),R=N?{checked:N.value===L.value,name:L.name??N.name,onChange:P=>{N.onChange(P),C==null||C(P)}}:{};return s.jsx(Vf,{...k("root"),__staticSelector:"Radio",__stylesApiProps:n,id:A,size:M,labelPosition:h,label:f,description:m,error:g,disabled:b,classNames:r,styles:a,unstyled:l,"data-checked":R.checked||void 0,variant:y,ref:j,mod:T,...I,...x,children:s.jsxs(W,{...k("inner"),mod:{"label-position":h},children:[s.jsx(W,{...k("radio",{focusable:!0,variant:y}),onChange:C,...L,...R,component:"input",mod:{error:!!g},ref:t,id:A,disabled:b,type:"radio"}),s.jsx(w,{...k("icon"),"aria-hidden":!0})]})})});ys.classes=VT;ys.displayName="@mantine/core/Radio";ys.Group=Fy;ys.Card=Ly;ys.Indicator=zy;const D9={duration:100,transition:"fade"};function I9(e,t){return{...D9,...t,...e}}function A9({offset:e,position:t}){const[n,r]=p.useState(!1),o=p.useRef(),{x:i,y:a,elements:l,refs:c,update:u,placement:d}=Uv({placement:t,middleware:[Fv({crossAxis:!0,padding:5,rootBoundary:"document"})]}),f=d.includes("right")?e:t.includes("left")?e*-1:0,h=d.includes("bottom")?e:t.includes("top")?e*-1:0,m=p.useCallback(({clientX:g,clientY:v})=>{c.setPositionReference({getBoundingClientRect(){return{width:0,height:0,x:g,y:v,left:g+f,top:v+h,right:g,bottom:v}}})},[l.reference]);return p.useEffect(()=>{if(c.floating.current){const g=o.current;g.addEventListener("mousemove",m);const v=ko(c.floating.current);return v.forEach(S=>{S.addEventListener("scroll",u)}),()=>{g.removeEventListener("mousemove",m),v.forEach(S=>{S.removeEventListener("scroll",u)})}}},[l.reference,c.floating.current,u,m,n]),{handleMouseMove:m,x:i,y:a,opened:n,setOpened:r,boundaryRef:o,floating:c.setFloating}}var sh={tooltip:"m_1b3c8819",arrow:"m_f898399f"};const N9={refProp:"ref",withinPortal:!0,offset:10,position:"right",zIndex:Qr("popover")},M9=(e,{radius:t,color:n})=>({tooltip:{"--tooltip-radius":t===void 0?void 0:at(t),"--tooltip-bg":n?st(n,e):void 0,"--tooltip-color":n?"var(--mantine-color-white)":void 0}}),By=K((e,t)=>{const n=V("TooltipFloating",N9,e),{children:r,refProp:o,withinPortal:i,style:a,className:l,classNames:c,styles:u,unstyled:d,radius:f,color:h,label:m,offset:g,position:v,multiline:S,zIndex:y,disabled:b,variant:x,vars:w,portalProps:j,...E}=n,C=At(),T=de({name:"TooltipFloating",props:n,classes:sh,className:l,style:a,classNames:c,styles:u,unstyled:d,rootSelector:"tooltip",vars:w,varsResolver:M9}),{handleMouseMove:_,x:k,y:N,opened:D,boundaryRef:M,floating:I,setOpened:L}=A9({offset:g,position:v});if(!zo(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 A=Kt(M,r.ref,t),R=$=>{var B,H;(H=(B=r.props).onMouseEnter)==null||H.call(B,$),_($),L(!0)},P=$=>{var B,H;(H=(B=r.props).onMouseLeave)==null||H.call(B,$),L(!1)};return s.jsxs(s.Fragment,{children:[s.jsx(Is,{...j,withinPortal:i,children:s.jsx(W,{...E,...T("tooltip",{style:{...BS(a,C),zIndex:y,display:!b&&D?"block":"none",top:(N&&Math.round(N))??"",left:(k&&Math.round(k))??""}}),variant:x,ref:I,mod:{multiline:S},children:m})}),p.cloneElement(r,{...r.props,[o]:A,onMouseEnter:R,onMouseLeave:P})]})});By.classes=sh;By.displayName="@mantine/core/TooltipFloating";const UT=p.createContext(!1),O9=UT.Provider,$9=()=>p.useContext(UT),L9={openDelay:0,closeDelay:0};function HT(e){const{openDelay:t,closeDelay:n,children:r}=V("TooltipGroup",L9,e);return s.jsx(O9,{value:!0,children:s.jsx(M4,{delay:{open:t,close:n},children:r})})}HT.displayName="@mantine/core/TooltipGroup";function F9(e){var E,C,T;const[t,n]=p.useState(!1),o=typeof e.opened=="boolean"?e.opened:t,i=$9(),a=Ln(),{delay:l,currentId:c,setCurrentId:u}=jE(),d=p.useCallback(_=>{n(_),_&&u(a)},[u,a]),{x:f,y:h,context:m,refs:g,update:v,placement:S,middlewareData:{arrow:{x:y,y:b}={}}}=Uv({strategy:e.strategy,placement:e.position,open:o,onOpenChange:d,middleware:[yE(e.offset),Fv({padding:8}),Fm(),xE({element:e.arrowRef,padding:e.arrowOffset}),...e.inline?[zm()]:[]]}),{getReferenceProps:x,getFloatingProps:w}=V4([N4(m,{enabled:(E=e.events)==null?void 0:E.hover,delay:i?l:{open:e.openDelay,close:e.closeDelay},mouseOnly:!((C=e.events)!=null&&C.touch)}),B4(m,{enabled:(T=e.events)==null?void 0:T.focus,visibleOnly:!0}),H4(m,{role:"tooltip"}),F4(m,{enabled:typeof e.opened>"u"}),O4(m,{id:a})]);_E({opened:o,position:e.position,positionDependencies:e.positionDependencies,floating:{refs:g,update:v}}),_o(()=>{var _;(_=e.onPositionChange)==null||_.call(e,S)},[S]);const j=o&&c&&c!==a;return{x:f,y:h,arrowX:y,arrowY:b,reference:g.setReference,floating:g.setFloating,getFloatingProps:w,getReferenceProps:x,isGroupPhase:j,opened:o,placement:S}}const Sb={position:"top",refProp:"ref",withinPortal:!0,inline:!1,arrowSize:4,arrowOffset:5,arrowRadius:0,arrowPosition:"side",offset:5,transitionProps:{duration:100,transition:"fade"},events:{hover:!0,focus:!1,touch:!1},zIndex:Qr("popover"),positionDependencies:[]},z9=(e,{radius:t,color:n})=>({tooltip:{"--tooltip-radius":t===void 0?void 0:at(t),"--tooltip-bg":n?st(n,e):void 0,"--tooltip-color":n?"var(--mantine-color-white)":void 0}}),Ms=K((e,t)=>{const n=V("Tooltip",Sb,e),{children:r,position:o,refProp:i,label:a,openDelay:l,closeDelay:c,onPositionChange:u,opened:d,withinPortal:f,radius:h,color:m,classNames:g,styles:v,unstyled:S,style:y,className:b,withArrow:x,arrowSize:w,arrowOffset:j,arrowRadius:E,arrowPosition:C,offset:T,transitionProps:_,multiline:k,events:N,zIndex:D,disabled:M,positionDependencies:I,onClick:L,onMouseEnter:A,onMouseLeave:R,inline:P,variant:$,keepMounted:B,vars:H,portalProps:Y,mod:ie,floatingStrategy:Re,...se}=V("Tooltip",Sb,n),{dir:je}=ks(),ke=p.useRef(null),oe=F9({position:CE(je,o),closeDelay:c,openDelay:l,onPositionChange:u,opened:d,events:N,arrowRef:ke,arrowOffset:j,offset:typeof T=="number"?T+(x?w/2:0):T,positionDependencies:[...I,r],inline:P,strategy:Re}),Be=de({name:"Tooltip",props:n,classes:sh,className:b,style:y,classNames:g,styles:v,unstyled:S,rootSelector:"tooltip",vars:H,varsResolver:z9});if(!zo(r))throw new Error("[@mantine/core] Tooltip component children should be an element or a component that accepts ref, fragments, strings, numbers and other primitive values are not supported");const ot=Kt(oe.reference,r.ref,t),bt=I9(_,{duration:100,transition:"fade"});return s.jsxs(s.Fragment,{children:[s.jsx(Is,{...Y,withinPortal:f,children:s.jsx(Wo,{...bt,keepMounted:B,mounted:!M&&!!oe.opened,duration:oe.isGroupPhase?10:bt.duration,children:Qe=>s.jsxs(W,{...se,variant:$,mod:[{multiline:k},ie],...oe.getFloatingProps({ref:oe.floating,className:Be("tooltip").className,style:{...Be("tooltip").style,...Qe,zIndex:D,top:oe.y??0,left:oe.x??0}}),children:[a,s.jsx(Hv,{ref:ke,arrowX:oe.arrowX,arrowY:oe.arrowY,visible:x,position:oe.placement,arrowSize:w,arrowOffset:j,arrowRadius:E,arrowPosition:C,...Be("arrow")})]})})}),p.cloneElement(r,oe.getReferenceProps({onClick:L,onMouseEnter:A,onMouseLeave:R,onMouseMove:n.onMouseMove,onPointerDown:n.onPointerDown,onPointerEnter:n.onPointerEnter,[i]:ot,className:rt(b,r.props.className),...r.props}))]})});Ms.classes=sh;Ms.displayName="@mantine/core/Tooltip";Ms.Floating=By;Ms.Group=HT;function B9({size:e,thickness:t,sum:n,value:r,root:o,offset:i}){const a=(e*.9-t*2)/2,l=Math.PI*a*2/100,c=o||r===void 0?`${(100-n)*l}, ${n*l}`:`${r*l}, ${(100-r)*l}`;return{strokeWidth:Number.isNaN(t)?12:t,cx:e/2||0,cy:e/2||0,r:a||0,transform:o?`scale(1, -1) translate(0, -${e})`:void 0,strokeDasharray:c,strokeDashoffset:o?0:i||0}}function WT({size:e,value:t,offset:n,sum:r,thickness:o,root:i,color:a,lineRoundCaps:l,tooltip:c,getStyles:u,display:d,...f}){const h=At();return s.jsx(Ms.Floating,{disabled:!c,label:c,children:s.jsx(W,{component:"circle",...f,...u("curve"),__vars:{"--curve-color":a?st(a,h):void 0},fill:"none",strokeLinecap:l?"round":"butt",...B9({sum:r,size:e,thickness:o,value:t,offset:n,root:i})})})}WT.displayName="@mantine/core/Curve";function V9({size:e,thickness:t,sections:n,renderRoundedLineCaps:r,rootColor:o}){const i=n.reduce((d,f)=>d+f.value,0),a=Math.PI*((e*.9-t*2)/2)*2;let l=a;const c=[],u=[];for(let d=0;d<n.length;d+=1)c.push({sum:i,offset:l,data:n[d],root:!1}),l-=n[d].value/100*a;if(c.push({sum:i,offset:l,data:{color:o},root:!0}),u.push({...c[c.length-1],lineRoundCaps:!1}),c.length>2){u.push({...c[0],lineRoundCaps:r}),u.push({...c[c.length-2],lineRoundCaps:r});for(let d=1;d<=c.length-3;d+=1)u.push({...c[d],lineRoundCaps:!1})}else u.push({...c[0],lineRoundCaps:r});return u}var qT={root:"m_b32e4812",svg:"m_d43b5134",curve:"m_b1ca1fbf",label:"m_b23f9dc4"};function U9(e,t){return Math.min(e||12,(t||120)/4)}const H9={size:120,thickness:12},W9=(e,{size:t,thickness:n})=>({root:{"--rp-size":F(t),"--rp-label-offset":F(n*2)}}),ah=K((e,t)=>{const n=V("RingProgress",H9,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,label:u,sections:d,size:f,thickness:h,roundCaps:m,rootColor:g,...v}=n,S=de({name:"RingProgress",classes:qT,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:W9}),y=U9(h,f),b=V9({size:f,thickness:y,sections:d,renderRoundedLineCaps:m,rootColor:g}).map(({data:x,sum:w,root:j,lineRoundCaps:E,offset:C},T)=>p.createElement(WT,{...x,key:T,size:f,thickness:y,sum:w,offset:C,color:x==null?void 0:x.color,root:j,lineRoundCaps:E,getStyles:S}));return s.jsxs(W,{...S("root"),size:f,ref:t,...v,children:[s.jsx("svg",{...S("svg"),children:b}),u&&s.jsx("div",{...S("label"),children:u})]})});ah.classes=qT;ah.displayName="@mantine/core/RingProgress";var GT={root:"m_cf365364",indicator:"m_9e182ccd",label:"m_1738fcb2",input:"m_1714d588",control:"m_69686b9b",innerLabel:"m_78882f40"};const q9={withItemsBorders:!0},G9=(e,{radius:t,color:n,transitionDuration:r,size:o,transitionTimingFunction:i})=>({root:{"--sc-radius":t===void 0?void 0:at(t),"--sc-color":n?st(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":i,"--sc-padding":De(o,"sc-padding"),"--sc-font-size":sn(o)}}),Vy=K((e,t)=>{var je,ke;const n=V("SegmentedControl",q9,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,data:u,value:d,defaultValue:f,onChange:h,size:m,name:g,disabled:v,readOnly:S,fullWidth:y,orientation:b,radius:x,color:w,transitionDuration:j,transitionTimingFunction:E,variant:C,autoContrast:T,withItemsBorders:_,mod:k,...N}=n,D=de({name:"SegmentedControl",props:n,classes:GT,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:G9}),M=At(),I=u.map(oe=>typeof oe=="string"?{label:oe,value:oe}:oe),L=q_(),[A,R]=p.useState(null),[P,$]=p.useState({}),B=(oe,Be)=>{P[Be]=oe,$(P)},[H,Y]=mn({value:d,defaultValue:f,finalValue:Array.isArray(u)?((je=I.find(oe=>!oe.disabled))==null?void 0:je.value)??((ke=u[0])==null?void 0:ke.value)??null:null,onChange:h}),ie=Ln(g),Re=I.map(oe=>p.createElement(W,{...D("control"),mod:{active:H===oe.value,orientation:b},key:oe.value},p.createElement("input",{...D("input"),disabled:v||oe.disabled,type:"radio",name:ie,value:oe.value,id:`${ie}-${oe.value}`,checked:H===oe.value,onChange:()=>!S&&Y(oe.value),"data-focus-ring":M.focusRing,key:`${oe.value}-input`}),p.createElement(W,{component:"label",...D("label"),mod:{active:H===oe.value&&!(v||oe.disabled),disabled:v||oe.disabled,"read-only":S},htmlFor:`${ie}-${oe.value}`,ref:Be=>B(Be,oe.value),__vars:{"--sc-label-color":w!==void 0?Bo({color:w,theme:M,autoContrast:T}):void 0},key:`${oe.value}-label`},s.jsx("span",{...D("innerLabel"),children:oe.label})))),se=Kt(t,oe=>R(oe));return u.length===0?null:s.jsxs(W,{...D("root"),variant:C,size:m,ref:se,mod:[{"full-width":y,orientation:b,initialized:L,"with-items-borders":_},k],...N,role:"radiogroup",children:[typeof H=="string"&&s.jsx(Kv,{target:P[H],parent:A,component:"span",transitionDuration:"var(--sc-transition-duration)",...D("indicator")}),Re]})});Vy.classes=GT;Vy.displayName="@mantine/core/SegmentedControl";function Q9({spacing:e,verticalSpacing:t,cols:n,selector:r}){var d;const o=At(),i=t===void 0?e:t,a=Ai({"--sg-spacing-x":qt(Fr(e)),"--sg-spacing-y":qt(Fr(i)),"--sg-cols":(d=Fr(n))==null?void 0:d.toString()}),l=gt(o.breakpoints).reduce((f,h)=>(f[h]||(f[h]={}),typeof e=="object"&&e[h]!==void 0&&(f[h]["--sg-spacing-x"]=qt(e[h])),typeof i=="object"&&i[h]!==void 0&&(f[h]["--sg-spacing-y"]=qt(i[h])),typeof n=="object"&&n[h]!==void 0&&(f[h]["--sg-cols"]=n[h]),f),{}),u=Yl(gt(l),o).filter(f=>gt(l[f.value]).length>0).map(f=>({query:`(min-width: ${o.breakpoints[f.value]})`,styles:l[f.value]}));return s.jsx(Ps,{styles:a,media:u,selector:r})}function Sp(e){return typeof e=="object"&&e!==null?gt(e):[]}function K9(e){return e.sort((t,n)=>Kl(t)-Kl(n))}function Y9({spacing:e,verticalSpacing:t,cols:n}){const r=Array.from(new Set([...Sp(e),...Sp(t),...Sp(n)]));return K9(r)}function X9({spacing:e,verticalSpacing:t,cols:n,selector:r}){var u;const o=t===void 0?e:t,i=Ai({"--sg-spacing-x":qt(Fr(e)),"--sg-spacing-y":qt(Fr(o)),"--sg-cols":(u=Fr(n))==null?void 0:u.toString()}),a=Y9({spacing:e,verticalSpacing:t,cols:n}),l=a.reduce((d,f)=>(d[f]||(d[f]={}),typeof e=="object"&&e[f]!==void 0&&(d[f]["--sg-spacing-x"]=qt(e[f])),typeof o=="object"&&o[f]!==void 0&&(d[f]["--sg-spacing-y"]=qt(o[f])),typeof n=="object"&&n[f]!==void 0&&(d[f]["--sg-cols"]=n[f]),d),{}),c=a.map(d=>({query:`simple-grid (min-width: ${d})`,styles:l[d]}));return s.jsx(Ps,{styles:i,container:c,selector:r})}var QT={container:"m_925c2d2c",root:"m_2415a157"};const J9={cols:1,spacing:"md",type:"media"},Uy=K((e,t)=>{const n=V("SimpleGrid",J9,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,cols:u,verticalSpacing:d,spacing:f,type:h,...m}=n,g=de({name:"SimpleGrid",classes:QT,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c}),v=Ic();return h==="container"?s.jsxs(s.Fragment,{children:[s.jsx(X9,{...n,selector:`.${v}`}),s.jsx("div",{...g("container"),children:s.jsx(W,{ref:t,...g("root",{className:v}),...m})})]}):s.jsxs(s.Fragment,{children:[s.jsx(Q9,{...n,selector:`.${v}`}),s.jsx(W,{ref:t,...g("root",{className:v}),...m})]})});Uy.classes=QT;Uy.displayName="@mantine/core/SimpleGrid";const Z9={},lh=K((e,t)=>{const{w:n,h:r,miw:o,mih:i,...a}=V("Space",Z9,e);return s.jsx(W,{ref:t,...a,w:n,miw:o??n,h:r,mih:i??r})});lh.displayName="@mantine/core/Space";var KT={root:"m_6d731127"};const e$={gap:"md",align:"stretch",justify:"flex-start"},t$=(e,{gap:t,align:n,justify:r})=>({root:{"--stack-gap":qt(t),"--stack-align":n,"--stack-justify":r}}),Ne=K((e,t)=>{const n=V("Stack",e$,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,align:u,justify:d,gap:f,variant:h,...m}=n,g=de({name:"Stack",props:n,classes:KT,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:t$});return s.jsx(W,{ref:t,...g("root"),variant:h,...m})});Ne.classes=KT;Ne.displayName="@mantine/core/Stack";const[n$,r$]=$n("Stepper component was not found in tree"),Gd=()=>null;Gd.displayName="@mantine/core/StepperCompleted";var Hy={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 Hu=(e,t)=>typeof e=="function"?s.jsx(e,{step:t||0}):e,o$={withIcon:!0,allowStepClick:!0,iconPosition:"left"},Wy=K((e,t)=>{const{classNames:n,className:r,style:o,styles:i,vars:a,step:l,state:c,color:u,icon:d,completedIcon:f,progressIcon:h,label:m,description:g,withIcon:v,iconSize:S,loading:y,allowStepClick:b,allowStepSelect:x,iconPosition:w,orientation:j,mod:E,...C}=V("StepperStep",o$,e),T=r$(),_=At(),k={classNames:n,styles:i},N=c==="stepCompleted"?null:c==="stepProgress"?h:d,D={"data-progress":c==="stepProgress"||void 0,"data-completed":c==="stepCompleted"||void 0};return s.jsxs(vn,{...T.getStyles("step",{className:r,style:o,variant:T.orientation,...k}),mod:[{"icon-position":w||T.iconPosition,"allow-click":b},E],ref:t,...D,...C,__vars:{"--step-color":u?st(u,_):void 0},tabIndex:b?0:-1,children:[v&&s.jsxs("span",{...T.getStyles("stepWrapper",k),children:[s.jsxs("span",{...T.getStyles("stepIcon",k),...D,children:[s.jsx(Wo,{mounted:c==="stepCompleted",transition:"pop",duration:200,children:M=>s.jsx("span",{...T.getStyles("stepCompletedIcon",{style:M,...k}),children:y?s.jsx(Kn,{color:"var(--mantine-color-white)",size:"calc(var(--stepper-icon-size) / 2)",...T.getStyles("stepLoader",k)}):Hu(f,l)||s.jsx(Uf,{size:"60%"})})}),c!=="stepCompleted"?y?s.jsx(Kn,{...T.getStyles("stepLoader",k),size:"calc(var(--stepper-icon-size) / 2)",color:u}):Hu(N||d,l):null]}),j==="vertical"&&s.jsx("span",{...T.getStyles("verticalSeparator",k),"data-active":c==="stepCompleted"||void 0})]}),(m||g)&&s.jsxs("span",{...T.getStyles("stepBody",k),"data-orientation":T.orientation,"data-icon-position":w||T.iconPosition,children:[m&&s.jsx("span",{...T.getStyles("stepLabel",k),children:Hu(m,l)}),g&&s.jsx("span",{...T.getStyles("stepDescription",k),children:Hu(g,l)})]})]})});Wy.classes=Hy;Wy.displayName="@mantine/core/StepperStep";const i$={orientation:"horizontal",iconPosition:"left",allowNextStepsSelect:!0,wrap:!0},s$=(e,{color:t,iconSize:n,size:r,contentPadding:o,radius:i,autoContrast:a})=>({root:{"--stepper-color":t?st(t,e):void 0,"--stepper-icon-color":Ts(a,e)?Bo({color:t,theme:e,autoContrast:a}):void 0,"--stepper-icon-size":n===void 0?De(r,"stepper-icon-size"):F(n),"--stepper-content-padding":qt(o),"--stepper-radius":i===void 0?void 0:at(i),"--stepper-fz":sn(r),"--stepper-spacing":qt(r)}}),Ha=K((e,t)=>{var P,$,B;const n=V("Stepper",i$,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,children:u,onStepClick:d,active:f,icon:h,completedIcon:m,progressIcon:g,color:v,iconSize:S,contentPadding:y,orientation:b,iconPosition:x,size:w,radius:j,allowNextStepsSelect:E,wrap:C,autoContrast:T,..._}=n,k=de({name:"Stepper",classes:Hy,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:s$}),N=p.Children.toArray(u),D=N.filter(H=>H.type!==Gd),M=N.find(H=>H.type===Gd),I=D.reduce((H,Y,ie)=>{const Re=f===ie?"stepProgress":f>ie?"stepCompleted":"stepInactive",je=typeof d!="function"?!1:typeof Y.props.allowStepSelect=="boolean"?Y.props.allowStepSelect:Re==="stepCompleted"||E;return H.push(p.cloneElement(Y,{icon:Y.props.icon||h||ie+1,key:ie,step:ie,state:Re,onClick:()=>je&&(d==null?void 0:d(ie)),allowStepClick:je,completedIcon:Y.props.completedIcon||m,progressIcon:Y.props.progressIcon||g,color:Y.props.color||v,iconSize:S,radius:j,iconPosition:Y.props.iconPosition||x,orientation:b,unstyled:l})),b==="horizontal"&&ie!==D.length-1&&H.push(p.createElement("div",{...k("separator"),"data-active":ie<f||void 0,"data-orientation":b,key:`separator-${ie}`})),H},[]),L=($=(P=D[f])==null?void 0:P.props)==null?void 0:$.children,A=(B=M==null?void 0:M.props)==null?void 0:B.children,R=f>D.length-1?A:L;return s.jsx(n$,{value:{getStyles:k,orientation:b,iconPosition:x},children:s.jsxs(W,{...k("root"),ref:t,size:w,..._,children:[s.jsx(W,{...k("steps"),mod:{orientation:b,"icon-position":x,wrap:C&&b!=="vertical"},children:I}),R&&s.jsx("div",{...k("content"),children:R})]})})});Ha.classes=Hy;Ha.displayName="@mantine/core/Stepper";Ha.Completed=Gd;Ha.Step=Wy;const YT=p.createContext(null),a$=YT.Provider,l$=()=>p.useContext(YT),c$={},qy=K((e,t)=>{const{value:n,defaultValue:r,onChange:o,size:i,wrapperProps:a,children:l,readOnly:c,...u}=V("SwitchGroup",c$,e),[d,f]=mn({value:n,defaultValue:r,finalValue:[],onChange:o}),h=m=>{const g=m.currentTarget.value;!c&&f(d.includes(g)?d.filter(v=>v!==g):[...d,g])};return s.jsx(a$,{value:{value:d,onChange:h,size:i},children:s.jsx(It.Wrapper,{size:i,ref:t,...a,...u,labelElement:"div",__staticSelector:"SwitchGroup",children:s.jsx(fy,{role:"group",children:l})})})});qy.classes=It.Wrapper.classes;qy.displayName="@mantine/core/SwitchGroup";var XT={root:"m_5f93f3bb",input:"m_926b4011",track:"m_9307d992",thumb:"m_93039a1d",trackLabel:"m_8277e082"};const u$={labelPosition:"right"},d$=(e,{radius:t,color:n,size:r})=>({root:{"--switch-radius":t===void 0?void 0:at(t),"--switch-height":De(r,"switch-height"),"--switch-width":De(r,"switch-width"),"--switch-thumb-size":De(r,"switch-thumb-size"),"--switch-label-font-size":De(r,"switch-label-font-size"),"--switch-track-label-padding":De(r,"switch-track-label-padding"),"--switch-color":n?st(n,e):void 0}}),Qc=K((e,t)=>{const n=V("Switch",u$,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,color:u,label:d,offLabel:f,onLabel:h,id:m,size:g,radius:v,wrapperProps:S,children:y,thumbIcon:b,checked:x,defaultChecked:w,onChange:j,labelPosition:E,description:C,error:T,disabled:_,variant:k,rootRef:N,mod:D,...M}=n,I=l$(),L=g||(I==null?void 0:I.size),A=de({name:"Switch",props:n,classes:XT,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:d$}),{styleProps:R,rest:P}=Vo(M),$=Ln(m),B=I?{checked:I.value.includes(P.value),onChange:I.onChange}:{},[H,Y]=mn({value:B.checked??x,defaultValue:w,finalValue:!1});return s.jsxs(Vf,{...A("root"),__staticSelector:"Switch",__stylesApiProps:n,id:$,size:L,labelPosition:E,label:d,description:C,error:T,disabled:_,bodyElement:"label",labelElement:"span",classNames:r,styles:a,unstyled:l,"data-checked":B.checked||void 0,variant:k,ref:N,mod:D,...R,...S,children:[s.jsx("input",{...P,disabled:_,checked:H,onChange:ie=>{var Re;I?(Re=B.onChange)==null||Re.call(B,ie):j==null||j(ie),Y(ie.currentTarget.checked)},id:$,ref:t,type:"checkbox",role:"switch",...A("input")}),s.jsxs(W,{"aria-hidden":"true",mod:{error:T,"label-position":E},...A("track"),children:[s.jsx(W,{component:"span",mod:"reduce-motion",...A("thumb"),children:b}),s.jsx("span",{...A("trackLabel"),children:H?h:f})]})]})});Qc.classes={...XT,...tT};Qc.displayName="@mantine/core/Switch";Qc.Group=qy;const[f$,h$]=$n("Table component was not found in the tree");var Kc={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 p$(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 Os(e,t){const n=`Table${e.charAt(0).toUpperCase()}${e.slice(1)}`,r=K((o,i)=>{const a=V(n,{},o),{classNames:l,className:c,style:u,styles:d,...f}=a,h=h$();return s.jsx(W,{component:e,ref:i,...p$(h,t),...h.getStyles(e,{className:c,classNames:l,style:u,styles:d,props:a}),...f})});return r.displayName=`@mantine/core/${n}`,r.classes=Kc,r}const Wm=Os("th",{columnBorder:!0}),JT=Os("td",{columnBorder:!0}),fd=Os("tr",{rowBorder:!0,striped:!0,highlightOnHover:!0}),ZT=Os("thead",{stickyHeader:!0}),eP=Os("tbody"),tP=Os("tfoot"),nP=Os("caption",{captionSide:!0});function Gy({data:e}){return s.jsxs(s.Fragment,{children:[e.caption&&s.jsx(nP,{children:e.caption}),e.head&&s.jsx(ZT,{children:s.jsx(fd,{children:e.head.map((t,n)=>s.jsx(Wm,{children:t},n))})}),e.body&&s.jsx(eP,{children:e.body.map((t,n)=>s.jsx(fd,{children:t.map((r,o)=>s.jsx(JT,{children:r},o))},n))}),e.foot&&s.jsx(tP,{children:s.jsx(fd,{children:e.foot.map((t,n)=>s.jsx(Wm,{children:t},n))})})]})}Gy.displayName="@mantine/core/TableDataRenderer";const m$={type:"scrollarea"},g$=(e,{minWidth:t,type:n})=>({scrollContainer:{"--table-min-width":F(t),"--table-overflow":n==="native"?"auto":void 0}}),Qy=K((e,t)=>{const n=V("TableScrollContainer",m$,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,children:u,minWidth:d,type:f,...h}=n,m=de({name:"TableScrollContainer",classes:Kc,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:g$,rootSelector:"scrollContainer"});return s.jsx(W,{component:f==="scrollarea"?kr:"div",...f==="scrollarea"?{offsetScrollbars:"x"}:{},ref:t,...m("scrollContainer"),...h,children:s.jsx("div",{...m("scrollContainerInner"),children:u})})});Qy.classes=Kc;Qy.displayName="@mantine/core/TableScrollContainer";const v$={withRowBorders:!0,verticalSpacing:7},y$=(e,{layout:t,captionSide:n,horizontalSpacing:r,verticalSpacing:o,borderColor:i,stripedColor:a,highlightOnHoverColor:l,striped:c,highlightOnHover:u,stickyHeaderOffset:d,stickyHeader:f})=>({table:{"--table-layout":t,"--table-caption-side":n,"--table-horizontal-spacing":qt(r),"--table-vertical-spacing":qt(o),"--table-border-color":i?st(i,e):void 0,"--table-striped-color":c&&a?st(a,e):void 0,"--table-highlight-on-hover-color":u&&l?st(l,e):void 0,"--table-sticky-header-offset":f?F(d):void 0}}),fe=K((e,t)=>{const n=V("Table",v$,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,horizontalSpacing:u,verticalSpacing:d,captionSide:f,stripedColor:h,highlightOnHoverColor:m,striped:g,highlightOnHover:v,withColumnBorders:S,withRowBorders:y,withTableBorder:b,borderColor:x,layout:w,variant:j,data:E,children:C,stickyHeader:T,stickyHeaderOffset:_,mod:k,...N}=n,D=de({name:"Table",props:n,className:o,style:i,classes:Kc,classNames:r,styles:a,unstyled:l,rootSelector:"table",vars:c,varsResolver:y$});return s.jsx(f$,{value:{getStyles:D,stickyHeader:T,striped:g===!0?"odd":g||void 0,highlightOnHover:v,withColumnBorders:S,withRowBorders:y,captionSide:f||"bottom"},children:s.jsx(W,{component:"table",variant:j,ref:t,mod:[{"data-with-table-border":b},k],...D("table"),...N,children:C||!!E&&s.jsx(Gy,{data:E})})})});fe.classes=Kc;fe.displayName="@mantine/core/Table";fe.Td=JT;fe.Th=Wm;fe.Tr=fd;fe.Thead=ZT;fe.Tbody=eP;fe.Tfoot=tP;fe.Caption=nP;fe.ScrollContainer=Qy;fe.DataRenderer=Gy;const[x$,Ky]=$n("Tabs component was not found in the tree");var Yc={root:"m_89d60db1","list--default":"m_576c9d4",list:"m_89d33d6d",panel:"m_b0c91715",tab:"m_4ec4dce6",tabSection:"m_fc420b1f","tab--default":"m_539e827b","list--outline":"m_6772fbd5","tab--outline":"m_b59ab47c","tab--pills":"m_c3381914"};const b$={},Yy=K((e,t)=>{const n=V("TabsList",b$,e),{children:r,className:o,grow:i,justify:a,classNames:l,styles:c,style:u,mod:d,...f}=n,h=Ky();return s.jsx(W,{...f,...h.getStyles("list",{className:o,style:u,classNames:l,styles:c,props:n,variant:h.variant}),ref:t,role:"tablist",variant:h.variant,mod:[{grow:i,orientation:h.orientation,placement:h.orientation==="vertical"&&h.placement,inverted:h.inverted},d],"aria-orientation":h.orientation,__vars:{"--tabs-justify":a},children:r})});Yy.classes=Yc;Yy.displayName="@mantine/core/TabsList";const w$={},Xy=K((e,t)=>{const n=V("TabsPanel",w$,e),{children:r,className:o,value:i,classNames:a,styles:l,style:c,mod:u,...d}=n,f=Ky(),h=f.value===i,m=f.keepMounted||n.keepMounted||h?r:null;return s.jsx(W,{...d,...f.getStyles("panel",{className:o,classNames:a,styles:l,style:[c,h?void 0:{display:"none"}],props:n}),ref:t,mod:[{orientation:f.orientation},u],role:"tabpanel",id:f.getPanelId(i),"aria-labelledby":f.getTabId(i),children:m})});Xy.classes=Yc;Xy.displayName="@mantine/core/TabsPanel";const S$={},Jy=K((e,t)=>{const n=V("TabsTab",S$,e),{className:r,children:o,rightSection:i,leftSection:a,value:l,onClick:c,onKeyDown:u,disabled:d,color:f,style:h,classNames:m,styles:g,vars:v,mod:S,...y}=n,b=At(),{dir:x}=ks(),w=Ky(),j=l===w.value,E=T=>{w.onChange(w.allowTabDeactivation&&l===w.value?null:l),c==null||c(T)},C={classNames:m,styles:g,props:n};return s.jsxs(vn,{...y,...w.getStyles("tab",{className:r,style:h,variant:w.variant,...C}),disabled:d,unstyled:w.unstyled,variant:w.variant,mod:[{active:j,disabled:d,orientation:w.orientation,inverted:w.inverted,placement:w.orientation==="vertical"&&w.placement},S],ref:t,role:"tab",id:w.getTabId(l),"aria-selected":j,tabIndex:j||w.value===null?0:-1,"aria-controls":w.getPanelId(l),onClick:E,__vars:{"--tabs-color":f?st(f,b):void 0},onKeyDown:CS({siblingSelector:'[role="tab"]',parentSelector:'[role="tablist"]',activateOnFocus:w.activateTabWithKeyboard,loop:w.loop,orientation:w.orientation||"horizontal",dir:x,onKeyDown:u}),children:[a&&s.jsx("span",{...w.getStyles("tabSection",C),"data-position":"left",children:a}),o&&s.jsx("span",{...w.getStyles("tabLabel",C),children:o}),i&&s.jsx("span",{...w.getStyles("tabSection",C),"data-position":"right",children:i})]})});Jy.classes=Yc;Jy.displayName="@mantine/core/TabsTab";const jb="Tabs.Tab or Tabs.Panel component was rendered with invalid value or without value",j$={keepMounted:!0,orientation:"horizontal",loop:!0,activateTabWithKeyboard:!0,allowTabDeactivation:!1,unstyled:!1,inverted:!1,variant:"default",placement:"left"},C$=(e,{radius:t,color:n,autoContrast:r})=>({root:{"--tabs-radius":at(t),"--tabs-color":st(n,e),"--tabs-text-color":Ts(r,e)?Bo({color:n,theme:e,autoContrast:r}):void 0}}),et=K((e,t)=>{const n=V("Tabs",j$,e),{defaultValue:r,value:o,onChange:i,orientation:a,children:l,loop:c,id:u,activateTabWithKeyboard:d,allowTabDeactivation:f,variant:h,color:m,radius:g,inverted:v,placement:S,keepMounted:y,classNames:b,styles:x,unstyled:w,className:j,style:E,vars:C,autoContrast:T,mod:_,...k}=n,N=Ln(u),[D,M]=mn({value:o,defaultValue:r,finalValue:null,onChange:i}),I=de({name:"Tabs",props:n,classes:Yc,className:j,style:E,classNames:b,styles:x,unstyled:w,vars:C,varsResolver:C$});return s.jsx(x$,{value:{placement:S,value:D,orientation:a,id:N,loop:c,activateTabWithKeyboard:d,getTabId:g0(`${N}-tab`,jb),getPanelId:g0(`${N}-panel`,jb),onChange:M,allowTabDeactivation:f,variant:h,color:m,radius:g,inverted:v,keepMounted:y,unstyled:w,getStyles:I},children:s.jsx(W,{ref:t,id:N,variant:h,mod:[{orientation:a,inverted:a==="horizontal"&&v,placement:a==="vertical"&&S},_],...I("root"),...k,children:l})})});et.classes=Yc;et.displayName="@mantine/core/Tabs";et.Tab=Jy;et.Panel=Xy;et.List=Yy;const E$={},me=K((e,t)=>{const n=V("TextInput",E$,e);return s.jsx(Jn,{component:"input",ref:t,...n,__staticSelector:"TextInput"})});me.classes=Jn.classes;me.displayName="@mantine/core/TextInput";var rP={root:"m_7341320d"};const T$={},P$=(e,{size:t,radius:n,variant:r,gradient:o,color:i,autoContrast:a})=>{const l=e.variantColorResolver({color:i||e.primaryColor,theme:e,gradient:o,variant:r||"filled",autoContrast:a});return{root:{"--ti-size":De(t,"ti-size"),"--ti-radius":n===void 0?void 0:at(n),"--ti-bg":i||r?l.background:void 0,"--ti-color":i||r?l.color:void 0,"--ti-bd":i||r?l.border:void 0}}},Zy=K((e,t)=>{const n=V("ThemeIcon",T$,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,autoContrast:u,...d}=n,f=de({name:"ThemeIcon",classes:rP,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:P$});return s.jsx(W,{ref:t,...f("root"),...d})});Zy.classes=rP;Zy.displayName="@mantine/core/ThemeIcon";const k$=["h1","h2","h3","h4","h5","h6"];function R$(e,t){const n=t!==void 0?t:`h${e}`;return k$.includes(n)?{fontSize:`var(--mantine-${n}-font-size)`,fontWeight:`var(--mantine-${n}-font-weight)`,lineHeight:`var(--mantine-${n}-line-height)`}:{fontSize:F(n),fontWeight:`var(--mantine-h${e}-font-weight)`,lineHeight:`var(--mantine-h${e}-line-height)`}}var oP={root:"m_8a5d1357"};const _$={order:1},D$=(e,{order:t,size:n,lineClamp:r,textWrap:o})=>{const i=R$(t,n);return{root:{"--title-fw":i.fontWeight,"--title-lh":i.lineHeight,"--title-fz":i.fontSize,"--title-line-clamp":typeof r=="number"?r.toString():void 0,"--title-text-wrap":o}}},pe=K((e,t)=>{const n=V("Title",_$,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,order:c,vars:u,size:d,variant:f,lineClamp:h,textWrap:m,mod:g,...v}=n,S=de({name:"Title",props:n,classes:oP,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:u,varsResolver:D$});return[1,2,3,4,5,6].includes(c)?s.jsx(W,{...S("root"),component:`h${c}`,variant:f,ref:t,mod:[{order:c,"data-line-clamp":typeof h=="number"},g],size:d,...v}):null});pe.classes=oP;pe.displayName="@mantine/core/Title";function I$(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(i=>i(t))},initialize(o){n||(t=o,n=!0)},subscribe(o){return r.add(o),()=>r.delete(o)}}}function A$(e){return p.useSyncExternalStore(e.subscribe,()=>e.getState(),()=>e.getState())}const N$=()=>I$({notifications:[],queue:[],limit:5}),$s=N$(),M$=(e=$s)=>A$(e);function sl(e,t){const n=e.getState(),r=t([...n.notifications,...n.queue]);e.setState({notifications:r.slice(0,n.limit),queue:r.slice(n.limit),limit:n.limit})}function ye(e,t=$s){const n=e.id||_g();return sl(t,r=>e.id&&r.some(o=>o.id===e.id)?r:[...r,{...e,id:n}]),n}function iP(e,t=$s){return sl(t,n=>n.filter(r=>{var o;return r.id===e?((o=r.onClose)==null||o.call(r,r),!1):!0})),e}function Ol(e,t=$s){return sl(t,n=>n.map(r=>r.id===e.id?{...r,...e}:r)),e.id}function O$(e=$s){sl(e,()=>[])}function $$(e=$s){sl(e,t=>t.slice(0,e.getState().limit))}const uo={show:ye,hide:iP,update:Ol,clean:O$,cleanQueue:$$,updateState:sl};function qm(e,t){return qm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},qm(e,t)}function sP(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,qm(e,t)}var aP={exports:{}},L$="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",F$=L$,z$=F$;function lP(){}function cP(){}cP.resetWarningCache=lP;var B$=function(){function e(r,o,i,a,l,c){if(c!==z$){var u=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 u.name="Invariant Violation",u}}e.isRequired=e;function t(){return e}var n={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:cP,resetWarningCache:lP};return n.PropTypes=n,n};aP.exports=B$();var V$=aP.exports;const pt=Sg(V$),Cb={disabled:!1},Qd=on.createContext(null);var U$=function(t){return t.scrollTop},$l="unmounted",Qi="exited",Ki="entering",ia="entered",Gm="exiting",Qo=function(e){sP(t,e);function t(r,o){var i;i=e.call(this,r,o)||this;var a=o,l=a&&!a.isMounting?r.enter:r.appear,c;return i.appearStatus=null,r.in?l?(c=Qi,i.appearStatus=Ki):c=ia:r.unmountOnExit||r.mountOnEnter?c=$l:c=Qi,i.state={status:c},i.nextCallback=null,i}t.getDerivedStateFromProps=function(o,i){var a=o.in;return a&&i.status===$l?{status:Qi}:null};var n=t.prototype;return n.componentDidMount=function(){this.updateStatus(!0,this.appearStatus)},n.componentDidUpdate=function(o){var i=null;if(o!==this.props){var a=this.state.status;this.props.in?a!==Ki&&a!==ia&&(i=Ki):(a===Ki||a===ia)&&(i=Gm)}this.updateStatus(!1,i)},n.componentWillUnmount=function(){this.cancelNextCallback()},n.getTimeouts=function(){var o=this.props.timeout,i,a,l;return i=a=l=o,o!=null&&typeof o!="number"&&(i=o.exit,a=o.enter,l=o.appear!==void 0?o.appear:a),{exit:i,enter:a,appear:l}},n.updateStatus=function(o,i){if(o===void 0&&(o=!1),i!==null)if(this.cancelNextCallback(),i===Ki){if(this.props.unmountOnExit||this.props.mountOnEnter){var a=this.props.nodeRef?this.props.nodeRef.current:ya.findDOMNode(this);a&&U$(a)}this.performEnter(o)}else this.performExit();else this.props.unmountOnExit&&this.state.status===Qi&&this.setState({status:$l})},n.performEnter=function(o){var i=this,a=this.props.enter,l=this.context?this.context.isMounting:o,c=this.props.nodeRef?[l]:[ya.findDOMNode(this),l],u=c[0],d=c[1],f=this.getTimeouts(),h=l?f.appear:f.enter;if(!o&&!a||Cb.disabled){this.safeSetState({status:ia},function(){i.props.onEntered(u)});return}this.props.onEnter(u,d),this.safeSetState({status:Ki},function(){i.props.onEntering(u,d),i.onTransitionEnd(h,function(){i.safeSetState({status:ia},function(){i.props.onEntered(u,d)})})})},n.performExit=function(){var o=this,i=this.props.exit,a=this.getTimeouts(),l=this.props.nodeRef?void 0:ya.findDOMNode(this);if(!i||Cb.disabled){this.safeSetState({status:Qi},function(){o.props.onExited(l)});return}this.props.onExit(l),this.safeSetState({status:Gm},function(){o.props.onExiting(l),o.onTransitionEnd(a.exit,function(){o.safeSetState({status:Qi},function(){o.props.onExited(l)})})})},n.cancelNextCallback=function(){this.nextCallback!==null&&(this.nextCallback.cancel(),this.nextCallback=null)},n.safeSetState=function(o,i){i=this.setNextCallback(i),this.setState(o,i)},n.setNextCallback=function(o){var i=this,a=!0;return this.nextCallback=function(l){a&&(a=!1,i.nextCallback=null,o(l))},this.nextCallback.cancel=function(){a=!1},this.nextCallback},n.onTransitionEnd=function(o,i){this.setNextCallback(i);var a=this.props.nodeRef?this.props.nodeRef.current:ya.findDOMNode(this),l=o==null&&!this.props.addEndListener;if(!a||l){setTimeout(this.nextCallback,0);return}if(this.props.addEndListener){var c=this.props.nodeRef?[this.nextCallback]:[a,this.nextCallback],u=c[0],d=c[1];this.props.addEndListener(u,d)}o!=null&&setTimeout(this.nextCallback,o)},n.render=function(){var o=this.state.status;if(o===$l)return null;var i=this.props,a=i.children;i.in,i.mountOnEnter,i.unmountOnExit,i.appear,i.enter,i.exit,i.timeout,i.addEndListener,i.onEnter,i.onEntering,i.onEntered,i.onExit,i.onExiting,i.onExited,i.nodeRef;var l=Sy(i,["children","in","mountOnEnter","unmountOnExit","appear","enter","exit","timeout","addEndListener","onEnter","onEntering","onEntered","onExit","onExiting","onExited","nodeRef"]);return on.createElement(Qd.Provider,{value:null},typeof a=="function"?a(o,l):on.cloneElement(on.Children.only(a),l))},t}(on.Component);Qo.contextType=Qd;Qo.propTypes={};function Zs(){}Qo.defaultProps={in:!1,mountOnEnter:!1,unmountOnExit:!1,appear:!1,enter:!0,exit:!0,onEnter:Zs,onEntering:Zs,onEntered:Zs,onExit:Zs,onExiting:Zs,onExited:Zs};Qo.UNMOUNTED=$l;Qo.EXITED=Qi;Qo.ENTERING=Ki;Qo.ENTERED=ia;Qo.EXITING=Gm;function H$(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function ex(e,t){var n=function(i){return t&&p.isValidElement(i)?t(i):i},r=Object.create(null);return e&&p.Children.map(e,function(o){return o}).forEach(function(o){r[o.key]=n(o)}),r}function W$(e,t){e=e||{},t=t||{};function n(d){return d in t?t[d]:e[d]}var r=Object.create(null),o=[];for(var i in e)i in t?o.length&&(r[i]=o,o=[]):o.push(i);var a,l={};for(var c in t){if(r[c])for(a=0;a<r[c].length;a++){var u=r[c][a];l[r[c][a]]=n(u)}l[c]=n(c)}for(a=0;a<o.length;a++)l[o[a]]=n(o[a]);return l}function rs(e,t,n){return n[t]!=null?n[t]:e.props[t]}function q$(e,t){return ex(e.children,function(n){return p.cloneElement(n,{onExited:t.bind(null,n),in:!0,appear:rs(n,"appear",e),enter:rs(n,"enter",e),exit:rs(n,"exit",e)})})}function G$(e,t,n){var r=ex(e.children),o=W$(t,r);return Object.keys(o).forEach(function(i){var a=o[i];if(p.isValidElement(a)){var l=i in t,c=i in r,u=t[i],d=p.isValidElement(u)&&!u.props.in;c&&(!l||d)?o[i]=p.cloneElement(a,{onExited:n.bind(null,a),in:!0,exit:rs(a,"exit",e),enter:rs(a,"enter",e)}):!c&&l&&!d?o[i]=p.cloneElement(a,{in:!1}):c&&l&&p.isValidElement(u)&&(o[i]=p.cloneElement(a,{onExited:n.bind(null,a),in:u.props.in,exit:rs(a,"exit",e),enter:rs(a,"enter",e)}))}}),o}var Q$=Object.values||function(e){return Object.keys(e).map(function(t){return e[t]})},K$={component:"div",childFactory:function(t){return t}},tx=function(e){sP(t,e);function t(r,o){var i;i=e.call(this,r,o)||this;var a=i.handleExited.bind(H$(i));return i.state={contextValue:{isMounting:!0},handleExited:a,firstRender:!0},i}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,i){var a=i.children,l=i.handleExited,c=i.firstRender;return{children:c?q$(o,l):G$(o,a,l),firstRender:!1}},n.handleExited=function(o,i){var a=ex(this.props.children);o.key in a||(o.props.onExited&&o.props.onExited(i),this.mounted&&this.setState(function(l){var c=qd({},l.children);return delete c[o.key],{children:c}}))},n.render=function(){var o=this.props,i=o.component,a=o.childFactory,l=Sy(o,["component","childFactory"]),c=this.state.contextValue,u=Q$(this.state.children).map(a);return delete l.appear,delete l.enter,delete l.exit,i===null?on.createElement(Qd.Provider,{value:c},u):on.createElement(Qd.Provider,{value:c},on.createElement(i,l,u))},t}(on.Component);tx.propTypes={};tx.defaultProps=K$;const Eb={left:"translateX(-100%)",right:"translateX(100%)","top-center":"translateY(-100%)","bottom-center":"translateY(100%)"},Y$={left:"translateX(0)",right:"translateX(0)","top-center":"translateY(0)","bottom-center":"translateY(0)"};function X$({state:e,maxHeight:t,position:n,transitionDuration:r}){const[o,i]=n.split("-"),a=i==="center"?`${o}-center`:i,l={opacity:0,maxHeight:t,transform:Eb[a],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"},c={opacity:1,transform:Y$[a]},u={opacity:0,maxHeight:0,transform:Eb[a]};return{...l,...{entering:c,entered:c,exiting:u,exited:u}[e]}}function J$(e,t){return typeof t=="number"?t:t===!1||e===!1?!1:e}const uP=p.forwardRef(({data:e,onHide:t,autoClose:n,...r},o)=>{const{autoClose:i,message:a,...l}=e,c=J$(n,e.autoClose),u=p.useRef(),d=()=>window.clearTimeout(u.current),f=()=>{t(e.id),d()},h=()=>{typeof c=="number"&&(u.current=window.setTimeout(f,c))};return p.useEffect(()=>{var m;(m=e.onOpen)==null||m.call(e,e)},[]),p.useEffect(()=>(h(),d),[c]),s.jsx(Ny,{...r,...l,onClose:f,ref:o,onMouseEnter:d,onMouseLeave:h,children:a})});uP.displayName="@mantine/notifications/NotificationContainer";var dP={root:"m_b37d9ac7",notification:"m_5ed0edd0"};const Z$=Qo,eL={position:"bottom-right",autoClose:4e3,transitionDuration:250,containerWidth:440,notificationMaxHeight:200,limit:5,zIndex:Qr("overlay"),store:$s,withinPortal:!0},tL=(e,{zIndex:t,position:n,containerWidth:r})=>{const[o,i]=n.split("-");return{root:{"--notifications-z-index":t==null?void 0:t.toString(),"--notifications-top":o==="top"?"var(--mantine-spacing-md)":void 0,"--notifications-bottom":o==="bottom"?"var(--mantine-spacing-md)":void 0,"--notifications-left":i==="left"?"var(--mantine-spacing-md)":i==="center"?"50%":void 0,"--notifications-right":i==="right"?"var(--mantine-spacing-md)":void 0,"--notifications-transform":i==="center"?"translateX(-50%)":void 0,"--notifications-container-width":F(r)}}},Ko=K((e,t)=>{const n=V("Notifications",eL,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,position:u,autoClose:d,transitionDuration:f,containerWidth:h,notificationMaxHeight:m,limit:g,zIndex:v,store:S,portalProps:y,withinPortal:b,...x}=n,w=At(),j=M$(S),E=F_(),C=Dg(),T=p.useRef({}),_=p.useRef(0),N=(w.respectReducedMotion?C:!1)?1:f,D=de({name:"Notifications",classes:dP,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:tL});p.useEffect(()=>{S==null||S.updateState(I=>({...I,limit:g||5}))},[g]),_o(()=>{j.notifications.length>_.current&&setTimeout(()=>E(),0),_.current=j.notifications.length},[j.notifications]);const M=j.notifications.map(({style:I,...L})=>s.jsx(Z$,{timeout:N,onEnter:()=>T.current[L.id].offsetHeight,nodeRef:{current:T.current[L.id]},children:A=>s.jsx(uP,{ref:R=>{T.current[L.id]=R},data:L,onHide:R=>iP(R,S),autoClose:d,...D("notification",{style:{...X$({state:A,position:u,transitionDuration:N,maxHeight:m}),...I}})})},L.id));return s.jsx(Is,{withinPortal:b,...y,children:s.jsx(W,{...D("root"),ref:t,...x,children:s.jsx(tx,{children:M})})})});Ko.classes=dP;Ko.displayName="@mantine/notifications/Notifications";Ko.show=uo.show;Ko.hide=uo.hide;Ko.update=uo.update;Ko.clean=uo.clean;Ko.cleanQueue=uo.cleanQueue;Ko.updateState=uo.updateState;class nL{constructor(t,n){this.operator=t,this.child=n}toString(){return`${this.operator}(${this.child.toString()})`}}class Xc{constructor(t,n,r){this.operator=t,this.left=n,this.right=r}toString(){return`${this.left.toString()} ${this.operator} ${this.right.toString()}`}}class rL{constructor(){this.prefixParselets={},this.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,i){const a=o.consumeAndParse(n);return r(i,a)}})}infixLeft(t,n,r){return this.registerInfix(t,{parse(o,i,a){const l=o.consumeAndParse(n);return r(i,a,l)},precedence:n})}construct(t){return new oL(t,this.prefixParselets,this.infixParselets)}}class oL{constructor(t,n,r){this.tokens=t,this.prefixParselets=n,this.infixParselets=r}hasMore(){return this.tokens.length>0}match(t){const n=this.peek();return(n==null?void 0:n.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 i=this.consume();o=this.getInfixParselet(i).parse(this,o,i)}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){var r,o;if(!this.tokens.length)throw Error("Cant consume unknown more tokens.");if(t&&((r=this.peek())==null?void 0:r.id)!==t){const i=this.peek();throw Error(`Expected ${t} but got "${i.id}" (${i.value}) at line ${i.line} column ${i.column}.`)}if(n&&((o=this.peek())==null?void 0:o.value)!==n){const i=this.peek();throw Error(`Expected "${n}" but got "${i.value}" at line ${i.line} column ${i.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]}}const iL="http://hl7.org",fP="ok",sL="created",aL="gone",lL="not-modified",cL="not-found",uL="forbidden",dL="accepted",fL={resourceType:"OperationOutcome",id:fP,issue:[{severity:"information",code:"informational",details:{text:"All OK"}}]},hL={resourceType:"OperationOutcome",id:cL,issue:[{severity:"error",code:"not-found",details:{text:"Not found"}}]},hP={resourceType:"OperationOutcome",id:uL,issue:[{severity:"error",code:"forbidden",details:{text:"Forbidden"}}]};function Ei(e,t){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"invalid",details:{text:e},...t?{expression:[t]}:void 0}]}}function Tt(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"structure",details:{text:e}}]}}function pL(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"exception",details:{text:"Internal server error"},diagnostics:e.toString()}]}}function ch(e){return typeof e=="object"&&e!==null&&e.resourceType==="OperationOutcome"}function pP(e){return e.id===fP||e.id===sL||e.id===lL||e.id===dL}function mL(e){return e.id===aL}class qe extends Error{constructor(t,n){super(mP(t)),this.outcome=t,this.cause=n}}function vt(e){return e instanceof qe?e.outcome:ch(e)?e:Ei(Me(e))}function Me(e){return e?typeof e=="string"?e:e instanceof Error?e.message:ch(e)?mP(e):typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:JSON.stringify(e):"Unknown error"}function mP(e){var n;const t=((n=e.issue)==null?void 0:n.map(gP))??[];return t.length>0?t.join("; "):"Unknown error"}function gP(e){var n,r;let t;return(n=e.details)!=null&&n.text?e.diagnostics?t=`${e.details.text} (${e.diagnostics})`:t=e.details.text:e.diagnostics?t=e.diagnostics:t="Unknown error",(r=e.expression)!=null&&r.length&&(t+=` (${e.expression.join(", ")})`),t}function gL(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 vL(e){const t=Object.create(null);for(const[n,r]of Object.entries(e))t[n]={name:n,elements:Object.fromEntries(Object.entries(r.elements).map(([o,i])=>[o,gL(o,i)])),constraints:[],innerTypes:[]};return t}const yL={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]}}},xL={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]}}},bL={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"}]}}},wL={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"}]}}},SL={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"}]}}},jL={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"}]}}},CL={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},coding:{max:9007199254740991,type:[{code:"Coding"}]},text:{type:[{code:"string"}]}}},EL={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"}]}}},TL={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},name:{type:[{code:"string"}]},telecom:{max:9007199254740991,type:[{code:"ContactPoint"}]}}},PL={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"}]}}},kL={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"}]}}},RL={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"}]}}},_L={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"}]}}},DL={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"}]}}},IL={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"]}]}}},AL={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"}]}}},NL={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"}]}}},ML={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"}]}}},OL={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"}]}}},$L={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"}]}}},LL={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"]}]}}},FL={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"}]}}},zL={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"}]},account:{type:[{code:"Reference"}]},compartment:{max:9007199254740991,type:[{code:"Reference"}]}}},BL={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},currency:{type:[{code:"code"}]}}},VL={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},status:{min:1,type:[{code:"code"}]},div:{min:1,type:[{code:"xhtml"}]}}},UL={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"]}]}}},HL={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},start:{type:[{code:"dateTime"}]},end:{type:[{code:"dateTime"}]}}},WL={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"}]}}},qL={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"}]}}},GL={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"}]}}},QL={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"}]}}},KL={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"]}]}}},YL={elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},numerator:{type:[{code:"Quantity"}]},denominator:{type:[{code:"Quantity"}]}}},XL={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"}]}}},JL={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"]}]}}},ZL={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"}]}}},e7={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"}]}}},t7={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"}]}}},n7={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"}]}}},r7={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"}]}}},o7={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"]}]}}},i7={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"}]}}},s7={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"}]}}},a7={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"}]}}},l7={Element:yL,BackboneElement:xL,Address:bL,Age:wL,Annotation:SL,Attachment:jL,CodeableConcept:CL,Coding:EL,ContactDetail:TL,ContactPoint:PL,Contributor:kL,Count:RL,DataRequirement:_L,Distance:DL,Dosage:IL,Duration:AL,ElementDefinition:NL,Expression:ML,Extension:OL,HumanName:$L,Identifier:LL,MarketingStatus:FL,Meta:zL,Money:BL,Narrative:VL,ParameterDefinition:UL,Period:HL,Population:WL,ProdCharacteristic:qL,ProductShelfLife:GL,Quantity:QL,Range:KL,Ratio:YL,Reference:XL,RelatedArtifact:JL,SampledData:ZL,Signature:e7,SubstanceAmount:t7,Timing:n7,TriggerDefinition:r7,UsageContext:o7,MoneyQuantity:i7,SimpleQuantity:s7,IdentityProvider:a7};function c7(e){return new u7(e).parse()}const vP=vL(l7),nx=Object.create(null),Tb=Object.create(null);function Qm(e){let t;return e?(t=Tb[e],t||(t=Tb[e]=Object.create(null))):t=vP,t}function Pb(e,t){var r;const n=Array.isArray(e)?e:((r=e.entry)==null?void 0:r.map(o=>o.resource))??[];for(const o of n)yP(o,t)}function yP(e,t){if(!(e!=null&&e.name))throw new Error("Failed loading StructureDefinition from bundle");if(e.resourceType!=="StructureDefinition")return;const n=c7(e),r=Qm(t);r[e.name]=n,t&&e.url===t&&(nx[t]=n);for(const o of n.innerTypes)o.parentType=n,r[o.name]=o}function xP(e){return!!vP[e]}function uh(e,t){let n=Qm(t)[e];return!n&&t&&(n=Qm()[e]),n}function bP(e,t){const n=uh(e,t);if(!n)throw new qe(Ei("Unknown data type: "+e));return n}function rx(e){return!!nx[e]}function Ls(e){return nx[e]}class u7{constructor(t){var n;if(!((n=t.snapshot)!=null&&n.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,title:t.title,type:t.type,url:t.url,kind:t.kind,description:h7(t),elements:{},constraints:this.parseElementDefinition(this.root).constraints,innerTypes:[],summaryProperties:new Set,mandatoryProperties:new Set},this.innerTypes=[]}parse(){var n,r,o,i,a;let t=this.next();for(;t;){if(t.sliceName)this.parseSliceStart(t);else if((n=t.id)!=null&&n.includes(":")){if((r=this.slicingContext)!=null&&r.current){const l=jp(t,this.slicingContext.path);this.slicingContext.current.elements[l]=this.parseElementDefinition(t)}}else{const l=this.parseElementDefinition(t);this.checkFieldEnter(t,l);let c=this.backboneContext;for(;c;){if((o=t.path)!=null&&o.startsWith(c.path+".")){c.type.elements[jp(t,c.path)]=l;break}c=c.parent}if(!c){const u=jp(t,this.root.path);t.isSummary&&((i=this.resourceSchema.summaryProperties)==null||i.add(u.replace("[x]",""))),l.min>0&&((a=this.resourceSchema.mandatoryProperties)==null||a.add(u.replace("[x]",""))),this.resourceSchema.elements[u]=l}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),t.slicing&&!this.slicingContext&&this.enterSlice(t,n)}enterInnerType(t){var n,r,o;for(;this.backboneContext&&!ea((n=this.backboneContext)==null?void 0:n.path,t.path);)this.innerTypes.push(this.backboneContext.type),this.backboneContext=this.backboneContext.parent;this.backboneContext={type:{name:Ob(t),title:t.label,description:t.definition,elements:{},constraints:this.parseElementDefinition(t).constraints,innerTypes:[]},path:t.path??"",parent:ea((r=this.backboneContext)==null?void 0:r.path,t.path)?this.backboneContext:(o=this.backboneContext)==null?void 0:o.parent}}enterSlice(t,n){var r,o,i,a;f7(t)&&!((r=this.peek())!=null&&r.sliceName)||(n.slicing={discriminator:(((o=t.slicing)==null?void 0:o.discriminator)??[]).map(l=>{if(l.type!=="value"&&l.type!=="pattern"&&l.type!=="type")throw new Error(`Unsupported slicing discriminator type: ${l.type}`);return{path:l.path,type:l.type}}),slices:[],ordered:((i=t.slicing)==null?void 0:i.ordered)??!1,rule:(a=t.slicing)==null?void 0:a.rules},this.slicingContext={field:n.slicing,path:t.path??""})}checkFieldExit(t=void 0){var n;if(this.backboneContext&&!ea(this.backboneContext.path,t==null?void 0:t.path))if(this.backboneContext.parent)do this.innerTypes.push(this.backboneContext.type),this.backboneContext=this.backboneContext.parent;while(this.backboneContext&&!ea(this.backboneContext.path,t==null?void 0:t.path));else this.innerTypes.push(this.backboneContext.type),this.backboneContext=void 0;this.slicingContext&&!ea(this.slicingContext.path,t==null?void 0:t.path)&&((n=this.slicingContext)!=null&&n.current&&this.slicingContext.field.slices.push(this.slicingContext.current),this.slicingContext=void 0)}next(){const t=this.peek();if(t)return this.index++,t}peek(){var n,r,o,i,a;const t=this.elements[this.index];if(t){if(this.elementIndex[t.path??""]=t,t.contentReference){const l=t.contentReference.slice(t.contentReference.indexOf("#")+1),c=this.elementIndex[l];return c?{...c,id:t.id,path:t.path,min:t.min??c.min,max:t.max??c.max,base:{path:((n=c.base)==null?void 0:n.path)??l,min:((r=t.base)==null?void 0:r.min)??((o=c.base)==null?void 0:o.min)??c.min,max:((i=t.base)==null?void 0:i.max)??((a=c.base)==null?void 0:a.max)??c.max},contentReference:t.contentReference,definition:t.definition}:void 0}return t}}isInnerType(t){var r;const n=this.peek();return!!(ea(t==null?void 0:t.path,n==null?void 0:n.path)&&((r=t.type)!=null&&r.some(o=>["BackboneElement","Element"].includes(o.code))))}parseSliceStart(t){if(!this.slicingContext)throw new Error(`Invalid slice start before discriminator: ${t.sliceName} (${t.id})`);this.slicingContext.current&&this.slicingContext.field.slices.push(this.slicingContext.current),this.slicingContext.current={...this.parseElementDefinition(t),name:t.sliceName??"",definition:t.definition,elements:{}}}parseElementDefinitionType(t){return(t.type??[]).map(n=>{var o;let r;return(n.code==="BackboneElement"||n.code==="Element")&&(r=Ob(t)),r||(r=(o=Jc(n,"http://hl7.org/fhir/StructureDefinition/structuredefinition-fhir-type"))==null?void 0:o.valueUrl),r||(r=n.code??""),{code:r,targetProfile:n.targetProfile,profile:n.profile}})}parseElementDefinition(t){var i,a;const n=kb(t.max),r=(i=t.base)!=null&&i.max?kb(t.base.max):n,o={type:"ElementDefinition",value:t};return{description:t.definition||"",path:t.path||((a=t.base)==null?void 0:a.path)||"",min:t.min??0,max:n,isArray:r>1,constraints:(t.constraint??[]).map(l=>({key:l.key??"",severity:l.severity??"error",expression:l.expression??"",description:l.human??""})),type:this.parseElementDefinitionType(t),fixed:Rb(pn(o,"fixed[x]")),pattern:Rb(pn(o,"pattern[x]")),binding:t.binding}}}function kb(e){return e==="*"?Number.POSITIVE_INFINITY:Number.parseInt(e,10)}function jp(e,t=""){return d7(e.path,t)}function d7(e,t){return e?t&&e.startsWith(t)?e.substring(t.length+1):e:""}function ea(e,t){return!e||!t?!1:t.startsWith(e+".")||t===e}function Rb(e){return Array.isArray(e)&&e.length>0?e[0]:Bt(e)?void 0:e}function f7(e){var n,r;const t=(n=e.slicing)==null?void 0:n.discriminator;return!!((r=e.type)!=null&&r.some(o=>o.code==="Extension")&&(t==null?void 0:t.length)===1&&t[0].type==="value"&&t[0].path==="url")}function h7(e){let t=e.description;return t!=null&&t.startsWith(`Base StructureDefinition for ${e.name} Type: `)&&(t=t.substring(`Base StructureDefinition for ${e.name} Type: `.length)),t}function p7(e,t,n){if(e===void 0)return[void 0];if(t==="$this")return[e];const r=n!=null&&n.withPath?m7:pn,[o,...i]=t.split(".");let a=[r(e,o,n)];for(const l of i){const c=[];for(const u of a)if(Array.isArray(u))for(const d of u)c.push(r(d,l,n));else(n!=null&&n.withPath&&u&&u.value!==void 0||!(n!=null&&n.withPath)&&u!==void 0)&&c.push(r(u,l,n));a=c}return a}function m7(e,t,n){const r=e.path;return g7(pn(e,t,n),r,t)}function g7(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,i)=>({...o,path:`${r}${n}[${i}]`})):{...e,path:`${r}${n}`}}const wP={base64Binary:/^([A-Za-z\d+/]{4})*([A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/,canonical:/^\S*$/,code:/^[^\s]+( [^\s]+)*$/,date:/^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2]\d|3[0-1]))?)?$/,dateTime:/^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2]\d|3[0-1])(T([01]\d|2[0-3])(:[0-5]\d:([0-5]\d|60)(\.\d{1,9})?)?)?)?(Z|[+-]((0\d|1[0-3]):[0-5]\d|14:00)?)?)?$/,id:/^[A-Za-z0-9\-.]{1,64}$/,instant:/^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])T([01]\d|2[0-3]):[0-5]\d:([0-5]\d|60)(\.\d{1,9})?(Z|[+-]((0\d|1[0-3]):[0-5]\d|14:00))$/,markdown:/^[\s\S]+$/,oid:/^urn:oid:[0-2](\.(0|[1-9]\d*))+$/,string:/^[\s\S]+$/,time:/^([01]\d|2[0-3]):[0-5]\d:([0-5]\d|60)(\.\d{1,9})?$/,uri:/^\S*$/,url:/^\S*$/,uuid:/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,xhtml:/.*/};function v7(e,t,n,r){var a;if(Array.isArray(e))return!1;let o;t.path==="$this"?o=n:o=(r??n.elements)[t.path];const i=n.type;switch(t.type){case"value":case"pattern":if(!e||!o)return!1;if(o.pattern)return ix(e,o.pattern);if(o.fixed)return xs(e,o.fixed);if(((a=o.binding)==null?void 0:a.strength)==="required"&&o.binding.valueSet)return!0;break;case"type":return!e||!(i!=null&&i.length)?!1:i.some(l=>l.code===e.type)}return!1}function Ce(e){return[{type:U.boolean,value:e}]}function po(e){return e==null?{type:"undefined",value:void 0}:Number.isSafeInteger(e)?{type:U.integer,value:e}:typeof e=="number"?{type:U.decimal,value:e}:typeof e=="boolean"?{type:U.boolean,value:e}:typeof e=="string"?{type:U.string,value:e}:Sr(e)?{type:U.Quantity,value:e}:Yo(e)?{type:e.resourceType,value:e}:{type:U.BackboneElement,value:e}}function gi(e){return e.length===0?!1:!!e[0].value}function $o(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 pn(e,t,n){if(!e.value)return;const r=zs(e.type,t,n==null?void 0:n.profileUrl);return r?SP(e,t,r):y7(e,t)}function SP(e,t,n){const r=e.value,o=n.type;if(!o||o.length===0)return;let i,a="undefined",l;if(n.path.endsWith("[x]")){const c=n.path.split(".").pop().replace("[x]","");for(const u of o){const d=c+Qt(u.code);if(i=r[d],l=r["_"+d],i!==void 0||l!==void 0){a=u.code;break}}}else console.assert(o.length===1,"Expected single type",n.path),i=r[t],a=o[0].code,l=r["_"+t];if(l)if(Array.isArray(i)){i=i.slice();for(let c=0;c<Math.max(i.length,l.length);c++)i[c]=Ab(i[c],l[c])}else i=Ab(i,l);if(!Bt(i))return(a==="Element"||a==="BackboneElement")&&(a=n.type[0].code),Array.isArray(i)?i.map(c=>_b(c,a)):_b(i,a)}function _b(e,t){return t==="Resource"&&Yo(e)&&(t=e.resourceType),{type:t,value:e}}function y7(e,t){const n=e.value;if(!n||typeof n!="object")return;let r;if(t in n)r=n[t];else for(const o in U){const i=t+Qt(o);if(i in n){r=n[i];break}}if(!Bt(r))return Array.isArray(r)?r.map(po):po(r)}function jP(e){const t=[];for(const n of e){let r=!1;for(const o of t)if(gi(TP(n,o))){r=!0;break}r||t.push(n)}return t}function CP(e){return Ce(!gi(e))}function EP(e,t){return e.length===0||t.length===0?[]:e.length!==t.length?Ce(!1):Ce(e.every((n,r)=>gi(TP(n,t[r]))))}function TP(e,t){var o,i;const n=(o=e.value)==null?void 0:o.valueOf(),r=(i=t.value)==null?void 0:i.valueOf();return typeof n=="number"&&typeof r=="number"?Ce(Math.abs(n-r)<1e-8):Sr(n)&&Sr(r)?Ce(RP(n,r)):Ce(typeof n=="object"&&typeof r=="object"?ox(e,t):n===r)}function PP(e,t){return e.length===0&&t.length===0?Ce(!0):e.length!==t.length?Ce(!1):(e.sort(Db),t.sort(Db),Ce(e.every((n,r)=>gi(x7(n,t[r])))))}function x7(e,t){const{type:n,value:r}=e,{type:o,value:i}=t,a=r==null?void 0:r.valueOf(),l=i==null?void 0:i.valueOf();return typeof a=="number"&&typeof l=="number"?Ce(Math.abs(a-l)<.01):Sr(a)&&Sr(l)?Ce(RP(a,l)):Ce(n==="Coding"&&o==="Coding"?typeof a!="object"||typeof l!="object"?!1:a.code===l.code&&a.system===l.system:typeof a=="object"&&typeof l=="object"?ox({...a,id:void 0},{...l,id:void 0}):typeof a=="string"&&typeof l=="string"?a.toLowerCase()===l.toLowerCase():a===l)}function Db(e,t){var o,i;const n=(o=e.value)==null?void 0:o.valueOf(),r=(i=t.value)==null?void 0:i.valueOf();return typeof n=="number"&&typeof r=="number"?n-r:typeof n=="string"&&typeof r=="string"?n.localeCompare(r):0}function kP(e,t){const{value:n}=e;if(n==null)return!1;switch(t){case"Boolean":return typeof n=="boolean";case"Decimal":case"Integer":return typeof n=="number";case"Date":return b7(n);case"DateTime":return Km(n);case"Time":return typeof n=="string"&&!!/^T\d/.exec(n);case"Period":return w7(n);case"Quantity":return Sr(n);default:return typeof n=="object"&&(n==null?void 0:n.resourceType)===t}}function b7(e){return typeof e=="string"&&!!wP.date.exec(e)}function Km(e){return typeof e=="string"&&!!wP.dateTime.exec(e)}function w7(e){return!!(e&&typeof e=="object"&&("start"in e&&Km(e.start)||"end"in e&&Km(e.end)))}function Sr(e){return!!(e&&typeof e=="object"&&"value"in e&&typeof e.value=="number")}function RP(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 ox(e,t){const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o],a=t[o];if(Ib(i)&&Ib(a)){if(!ox(i,a))return!1}else if(i!==a)return!1}return!0}function Ib(e){return e!==null&&typeof e=="object"}function Ab(e,t){if(t){if(typeof t!="object")throw new Error("Primitive extension must be an object");return S7(e??{},t)}return e}function S7(e,t){return delete t.__proto__,delete t.constructor,Object.assign(e,t)}function jt(e){const t=Ct(e),n=Lo(e);return n===t?{reference:t}:{reference:t,display:n}}function Ct(e){return Bs(e)?e.reference:`${e.resourceType}/${e.id}`}function dh(e){if(e)return Bs(e)?e.reference.split("/")[1]:e.id}function j7(e){return e.resourceType==="Patient"||e.resourceType==="Practitioner"||e.resourceType==="RelatedPerson"}function Lo(e){if(j7(e)){const t=C7(e);if(t)return t}if(e.resourceType==="Device"){const t=E7(e);if(t)return t}if(e.resourceType==="MedicationRequest"){const t=e.medicationCodeableConcept;if(t)return Di(t)}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]),M7(t))return Di(t);if(O7(t))return t.text}return Ct(e)}function C7(e){const t=e.name;if(t&&t.length>0)return Zc(t[0])}function E7(e){const t=e.deviceName;if(t&&t.length>0)return t[0].name}function T7(e){if(!("photo"in e))return;const t=e.photo;if(t)if(Array.isArray(t))for(const n of t){const r=Nb(n);if(r)return r}else return Nb(t)}function Nb(e){var t;if(e.url&&((t=e.contentType)!=null&&t.startsWith("image/")))return e.url}function _P(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(),i=n.getUTCMonth(),a=n.getUTCDate(),l=r.getUTCFullYear(),c=r.getUTCMonth(),u=r.getUTCDate();let d=l-o;(c<i||c===i&&u<a)&&d--;let f=l*12+c-(o*12+i);u<a&&f--;const h=Math.floor((r.getTime()-n.getTime())/(1e3*60*60*24));return{years:d,months:f,days:h}}function P7(e,t){const{years:n,months:r,days:o}=_P(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 Jc(e,...t){var r;let n=e;for(let o=0;o<t.length&&n;o++)n=(r=n==null?void 0:n.extension)==null?void 0:r.find(i=>i.url===t[o]);return n}function lr(e,t){return JSON.stringify(e,k7,t?2:void 0)}function k7(e,t){return!R7(e)&&Bt(t)?void 0:t}function R7(e){return!!/\d+$/.exec(e)}function Bt(e){if(e==null)return!0;const t=typeof e;return t==="string"||t==="object"?!Ot(e):!1}function Ot(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 xs(e,t,n){return e===t||Bt(e)&&Bt(t)?!0:Bt(e)||Bt(t)?!1:Array.isArray(e)&&Array.isArray(t)?_7(e,t):Array.isArray(e)||Array.isArray(t)?!1:Sn(e)&&Sn(t)?D7(e,t,n):(Sn(e)||Sn(t),!1)}function _7(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!xs(e[n],t[n]))return!1;return!0}function D7(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 i=e[o],a=t[o];if(!xs(i,a,o))return!1}return!0}function ix(e,t){return Bt(e)?!0:Bt(t)?!1:Array.isArray(e)&&Array.isArray(t)?I7(e,t):Array.isArray(e)||Array.isArray(t)?!1:Sn(e)&&Sn(t)?A7(e,t):Sn(e)||Sn(t)?!1:e===t}function I7(e,t){return t.every(n=>e.some(r=>ix(r,n)))}function A7(e,t){return Object.entries(t).every(([n,r])=>n in e&&ix(e[n],r))}function mo(e){return e===void 0?e:JSON.parse(JSON.stringify(e))}function DP(e){return!!/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/i.exec(e)}function Sn(e){return e!==null&&typeof e=="object"}function N7(e){return Sn(e)&&"code"in e&&typeof e.code=="string"}function M7(e){return Sn(e)&&"coding"in e&&Array.isArray(e.coding)&&e.coding.every(N7)}function O7(e){return Sn(e)&&"text"in e&&typeof e.text=="string"}const IP=[];for(let e=0;e<256;e++)IP.push(e.toString(16).padStart(2,"0"));function $7(e){const t=new Uint8Array(e),n=new Array(t.length);for(let r=0;r<t.length;r++)n[r]=IP[t[r]];return n.join("")}function L7(e){const t=new Uint8Array(e),n=[];for(let r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return window.btoa(n.join(""))}function Qt(e){return e?e.charAt(0).toUpperCase()+e.substring(1):""}function sx(e){return e.length>0&&e.startsWith(e[0].toUpperCase())}function bc(e,t){const n=e+".";if(t.startsWith(n))return t.slice(n.length)}function F7(e,t){var n,r;return(r=(n=e.coding)==null?void 0:n.find(o=>o.system===t))==null?void 0:r.code}function z7(e){if(e)return Array.isArray(e)?e:[e]}const Mb=e=>new Promise(t=>{setTimeout(t,e)});function Ym(e,t,n){const r=[];for(let o=0;o<n-1;o++){const i=e.indexOf(t);if(i<0)break;r.push(e.slice(0,i)),e=e.slice(i+t.length)}return r.push(e),r}function B7(e){let t,n=!1;return function(){return n||(t=e(),n=!0),t}}function Tl(e,t){return e?(e.push(t),e):[t]}function wc(e){return e.sort((t,n)=>t.localeCompare(n))}function AP(e){return e.endsWith("/")?e:e+"/"}function V7(e){return e.startsWith("/")?e.slice(1):e}function wo(e,t){return new URL(V7(t),AP(e.toString())).toString()}function U7(e,t){return wo(e,t).toString().replace("http://","ws://").replace("https://","wss://")}function H7(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 NP(e,t){var n,r;return(r=(n=e==null?void 0:e.meta)==null?void 0:n.profile)!=null&&r.includes(t)||(e.meta=e.meta??{},e.meta.profile=e.meta.profile??[],e.meta.profile.push(t)),e}function W7(e,t){var n,r;if((r=(n=e==null?void 0:e.meta)==null?void 0:n.profile)!=null&&r.includes(t)){const o=e.meta.profile.indexOf(t);e.meta.profile.splice(o,1)}return e}function q7(e,t){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!=null&&t.use)&&n.push("["+e.use+"]"),n.join(", ").trim()}function Zc(e,t){const n=[];if(e.prefix&&(t==null?void 0:t.prefix)!==!1&&n.push(...e.prefix),e.given&&n.push(...e.given),e.family&&n.push(e.family),e.suffix&&(t==null?void 0:t.suffix)!==!1&&n.push(...e.suffix),e.use&&(t!=null&&t.all||t!=null&&t.use)&&n.push("["+e.use+"]"),n.length===0){const r=jc(e.text);if(r)return r}return n.join(" ").trim()}function fh(e){return e instanceof Date&&!isNaN(e.getTime())}function G7(e,t,n){if(!e)return"";const r=new Date("2000-01-01T"+e+"Z");return fh(r)?r.toLocaleTimeString(t,n):""}function Mn(e,t,n){if(!e)return"";const r=new Date(e);return fh(r)?r.toLocaleString(t,n):""}function Q7(e,t,n){return!e||!e.start&&!e.end?"":Mn(e.start,t,n)+" - "+Mn(e.end,t,n)}const K7={s:"every second",min:"every minute",h:"hourly",d:"daily",wk:"weekly",mo:"monthly",a:"annually"},Y7={s:"second",min:"minute",h:"hour",d:"day",wk:"week",mo:"month",a:"year"},X7={s:"seconds",min:"minutes",h:"hours",d:"days",wk:"weeks",mo:"months",a:"years"};function MP(e){if(!e)return"";const t=[];return J7(t,e.repeat),e.event&&t.push(e.event.map(n=>Mn(n)).join(", ")),Qt(t.join(" ").trim())}function J7(e,t){if(!(t!=null&&t.periodUnit))return;const n=t.frequency??1,r=t.period??1,o=t.periodUnit;n===1&&r===1?e.push(K7[o]):(n===1?e.push("once"):e.push(n+" times"),r===1?e.push("per "+Y7[o]):e.push("per "+r+" "+X7[o])),t.dayOfWeek&&e.push("on "+t.dayOfWeek.map(Qt).join(", ")),t.timeOfDay&&e.push("at "+t.timeOfDay.map(i=>G7(i)).join(", "))}function Sc(e,t,n=!1){if(n&&t===void 0)throw new Error("Precision must be specified for exclusive ranges");const r=(e==null?void 0:e.low)&&{...e.low,comparator:void 0},o=(e==null?void 0:e.high)&&{...e.high,comparator:void 0};return(r==null?void 0:r.value)===void 0&&(o==null?void 0:o.value)===void 0?"":(r==null?void 0:r.value)!==void 0&&(o==null?void 0:o.value)===void 0?n&&t!==void 0?(r.value=t6(r.value,t),`> ${li(r)}`):`>= ${li(r)}`:(r==null?void 0:r.value)===void 0&&(o==null?void 0:o.value)!==void 0?n&&t!==void 0?(o.value=e6(o.value,t),`< ${li(o)}`):`<= ${li(o)}`:((r==null?void 0:r.unit)===(o==null?void 0:o.unit)&&(r==null||delete r.unit),`${li(r)} - ${li(o)}`)}function li(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[n.length-1]!==" "&&n.push(" "),n.push(e.unit)),n.join("").trim()}function Z7(e){return(e==null?void 0:e.value)===void 0?"":e.value.toLocaleString(void 0,{style:"currency",currency:e.currency??"USD",currencyDisplay:"narrowSymbol"})}function Di(e){if(!e)return"";const t=jc(e.text);return t||(e.coding?e.coding.map(n=>Fs(n)).join(", "):"")}function Fs(e){return jc(e==null?void 0:e.display)??jc(e==null?void 0:e.code)??""}function OP(e){if(!e)return"";const t=[];if(e.valueQuantity)t.push(li(e.valueQuantity));else if(e.valueCodeableConcept)t.push(Di(e.valueCodeableConcept));else{const n=jc(e.valueString);n&&t.push(n)}return"component"in e&&t.push(e.component.map(n=>OP(n)).join(" / ")),t.join(" / ").trim()}function jc(e){return typeof e=="string"?e:void 0}function e6(e,t,n=1){return($P(e)+n)*Math.pow(10,-t)}function t6(e,t,n=1){return($P(e)-n)*Math.pow(10,-t)}function $P(e,t){return e}const U={Address:"Address",Age:"Age",Annotation:"Annotation",Attachment:"Attachment",BackboneElement:"BackboneElement",CodeableConcept:"CodeableConcept",Coding:"Coding",ContactDetail:"ContactDetail",ContactPoint:"ContactPoint",Contributor:"Contributor",Count:"Count",DataRequirement:"DataRequirement",Distance:"Distance",Dosage:"Dosage",Duration:"Duration",Expression:"Expression",Extension:"Extension",HumanName:"HumanName",Identifier:"Identifier",MarketingStatus:"MarketingStatus",Meta:"Meta",Money:"Money",Narrative:"Narrative",ParameterDefinition:"ParameterDefinition",Period:"Period",Population:"Population",ProdCharacteristic:"ProdCharacteristic",ProductShelfLife:"ProductShelfLife",Quantity:"Quantity",Range:"Range",Ratio:"Ratio",Reference:"Reference",RelatedArtifact:"RelatedArtifact",SampledData:"SampledData",Signature:"Signature",SubstanceAmount:"SubstanceAmount",SystemString:"http://hl7.org/fhirpath/System.String",Timing:"Timing",TriggerDefinition:"TriggerDefinition",UsageContext:"UsageContext",base64Binary:"base64Binary",boolean:"boolean",canonical:"canonical",code:"code",date:"date",dateTime:"dateTime",decimal:"decimal",id:"id",instant:"instant",integer:"integer",markdown:"markdown",oid:"oid",positiveInt:"positiveInt",string:"string",time:"time",unsignedInt:"unsignedInt",uri:"uri",url:"url",uuid:"uuid"};function n6(e){for(const t of e.base??[]){let n=go.types[t];n||(n={searchParamsDetails:{}},go.types[t]=n),n.searchParams||(n.searchParams={_id:{base:[t],code:"_id",type:"token",expression:t+".id"},_lastUpdated:{base:[t],code:"_lastUpdated",type:"date",expression:t+".meta.lastUpdated"},_compartment:{base:[t],code:"_compartment",type:"reference",expression:t+".meta.compartment"},_profile:{base:[t],code:"_profile",type:"uri",expression:t+".meta.profile"},_security:{base:[t],code:"_security",type:"token",expression:t+".meta.security"},_source:{base:[t],code:"_source",type:"uri",expression:t+".meta.source"},_tag:{base:[t],code:"_tag",type:"token",expression:t+".meta.tag"}}),n.searchParams[e.code]=e}}function Ob(e){var n,r,o,i;const t=(r=(n=e.type)==null?void 0:n[0])==null?void 0:r.code;return t==="BackboneElement"||t==="Element"?r6((i=((o=e.base)==null?void 0:o.path)??e.path)==null?void 0:i.split(".")):t}function r6(e){return e.length===1?e[0]:e.map(Qt).join("")}function ax(e){var t;return(t=go.types[e])==null?void 0:t.searchParams}function o6(e,t){var n,r;return(r=(n=go.types[e])==null?void 0:n.searchParams)==null?void 0:r[t]}function bs(e){const t=e.replaceAll("[x]","").split(".").pop();return LP(t)}function LP(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(s6).join(" ").replace("_"," ").replace(/\s+/g," ")}const i6=new Set(["ID","IP","PKCE","JWKS","URI","URL","OMB","UDI"]);function s6(e){const t=e.toUpperCase();return e===t?e:i6.has(t)?t:t.charAt(0)+e.slice(1)}function zs(e,t,n){const r=uh(e,n);if(r)return a6(r.elements,t)}function a6(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 i=t.slice(0,r)+"[x]",a=e[i];if(a)return a}}}function Yo(e){return!!(e&&typeof e=="object"&&"resourceType"in e)}function Bs(e){return!!(e&&typeof e=="object"&&"reference"in e&&typeof e.reference=="string")}const go={types:{}};function hd(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 xo=()=>[],zn={empty:(e,t)=>Ce(t.length===0||t.every(n=>Bt(n.value))),hasValue:(e,t)=>Ce(t.length!==0),exists:(e,t,n)=>Ce(n?t.filter(r=>gi(n.eval(e,[r]))).length>0:t.length>0&&t.every(r=>!Bt(r.value))),all:(e,t,n)=>Ce(t.every(r=>gi(n.eval(e,[r])))),allTrue:(e,t)=>{for(const n of t)if(!n.value)return Ce(!1);return Ce(!0)},anyTrue:(e,t)=>{for(const n of t)if(n.value)return Ce(!0);return Ce(!1)},allFalse:(e,t)=>{for(const n of t)if(n.value)return Ce(!1);return Ce(!0)},anyFalse:(e,t)=>{for(const n of t)if(!n.value)return Ce(!0);return Ce(!1)},subsetOf:(e,t,n)=>{if(t.length===0)return Ce(!0);const r=n.eval(e,Hi(e));return r.length===0?Ce(!1):Ce(t.every(o=>r.some(i=>i.value===o.value)))},supersetOf:(e,t,n)=>{const r=n.eval(e,Hi(e));return r.length===0?Ce(!0):t.length===0?Ce(!1):Ce(r.every(o=>t.some(i=>i.value===o.value)))},count:(e,t)=>[{type:U.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)=>Ce(t.length===zn.distinct(e,t).length),where:(e,t,n)=>t.filter(r=>gi(n.eval(e,[r]))),select:(e,t,n)=>t.map(r=>n.eval(e,[r])).flat(),repeat:xo,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(t.length-1,t.length),tail:(e,t)=>t.length===0?[]:t.slice(1,t.length),skip:(e,t,n)=>{var o;const r=(o=n.eval(e,t)[0])==null?void 0:o.value;if(typeof r!="number")throw new Error("Expected a number for skip(num)");return r>=t.length?[]:r<=0?t:t.slice(r,t.length)},take:(e,t,n)=>{var o;const r=(o=n.eval(e,t)[0])==null?void 0:o.value;if(typeof r!="number")throw new Error("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,Hi(e)),o=[];for(const i of t)!o.some(a=>a.value===i.value)&&r.some(a=>a.value===i.value)&&o.push(i);return o},exclude:(e,t,n)=>{if(!n)return t;const r=n.eval(e,Hi(e)),o=[];for(const i of t)r.some(a=>a.value===i.value)||o.push(i);return o},union:(e,t,n)=>{if(!n)return t;const r=n.eval(e,Hi(e));return jP([...t,...r])},combine:(e,t,n)=>{if(!n)return t;const r=n.eval(e,Hi(e));return[...t,...r]},htmlChecks:(e,t,n)=>[po(!0)],iif:(e,t,n,r,o)=>{const i=n.eval(e,t);if(i.length>1||i.length===1&&typeof i[0].value!="boolean")throw new Error("Expected criterion to evaluate to a Boolean");return gi(i)?r.eval(e,t):o?o.eval(e,t):[]},toBoolean:(e,t)=>{if(t.length===0)return[];const[{value:n}]=oo(t,1);if(typeof n=="boolean")return[{type:U.boolean,value:n}];if(typeof n=="number"&&(n===0||n===1))return Ce(!!n);if(typeof n=="string"){const r=n.toLowerCase();if(["true","t","yes","y","1","1.0"].includes(r))return Ce(!0);if(["false","f","no","n","0","0.0"].includes(r))return Ce(!1)}return[]},convertsToBoolean:(e,t)=>t.length===0?[]:Ce(zn.toBoolean(e,t).length===1),toInteger:(e,t)=>{if(t.length===0)return[];const[{value:n}]=oo(t,1);return typeof n=="number"?[{type:U.integer,value:n}]:typeof n=="string"&&/^[+-]?\d+$/.exec(n)?[{type:U.integer,value:parseInt(n,10)}]:typeof n=="boolean"?[{type:U.integer,value:n?1:0}]:[]},convertsToInteger:(e,t)=>t.length===0?[]:Ce(zn.toInteger(e,t).length===1),toDate:(e,t)=>{if(t.length===0)return[];const[{value:n}]=oo(t,1);return typeof n=="string"&&/^\d{4}(-\d{2}(-\d{2})?)?/.exec(n)?[{type:U.date,value:hd(n)}]:[]},convertsToDate:(e,t)=>t.length===0?[]:Ce(zn.toDate(e,t).length===1),toDateTime:(e,t)=>{if(t.length===0)return[];const[{value:n}]=oo(t,1);return typeof n=="string"&&/^\d{4}(-\d{2}(-\d{2})?)?/.exec(n)?[{type:U.dateTime,value:hd(n)}]:[]},convertsToDateTime:(e,t)=>t.length===0?[]:Ce(zn.toDateTime(e,t).length===1),toDecimal:(e,t)=>{if(t.length===0)return[];const[{value:n}]=oo(t,1);return typeof n=="number"?[{type:U.decimal,value:n}]:typeof n=="string"&&/^-?\d{1,9}(\.\d{1,9})?$/.exec(n)?[{type:U.decimal,value:parseFloat(n)}]:typeof n=="boolean"?[{type:U.decimal,value:n?1:0}]:[]},convertsToDecimal:(e,t)=>t.length===0?[]:Ce(zn.toDecimal(e,t).length===1),toQuantity:(e,t)=>{if(t.length===0)return[];const[{value:n}]=oo(t,1);return Sr(n)?[{type:U.Quantity,value:n}]:typeof n=="number"?[{type:U.Quantity,value:{value:n,unit:"1"}}]:typeof n=="string"&&/^-?\d{1,9}(\.\d{1,9})?/.exec(n)?[{type:U.Quantity,value:{value:parseFloat(n),unit:"1"}}]:typeof n=="boolean"?[{type:U.Quantity,value:{value:n?1:0,unit:"1"}}]:[]},convertsToQuantity:(e,t)=>t.length===0?[]:Ce(zn.toQuantity(e,t).length===1),toString:(e,t)=>{if(t.length===0)return[];const[{value:n}]=oo(t,1);return n==null?[]:Sr(n)?[{type:U.string,value:`${n.value} '${n.unit}'`}]:[{type:U.string,value:n.toString()}]},convertsToString:(e,t)=>t.length===0?[]:Ce(zn.toString(e,t).length===1),toTime:(e,t)=>{if(t.length===0)return[];const[{value:n}]=oo(t,1);if(typeof n=="string"){const r=/^T?(\d{2}(:\d{2}(:\d{2})?)?)/.exec(n);if(r)return[{type:U.time,value:hd("T"+r[1])}]}return[]},convertsToTime:(e,t)=>t.length===0?[]:Ce(zn.toTime(e,t).length===1),indexOf:(e,t,n)=>hr((r,o)=>r.indexOf(o),e,t,n),substring:(e,t,n,r)=>hr((o,i,a)=>{const l=i,c=a?l+a:o.length;return l<0||l>=o.length?void 0:o.substring(l,c)},e,t,n,r),startsWith:(e,t,n)=>hr((r,o)=>r.startsWith(o),e,t,n),endsWith:(e,t,n)=>hr((r,o)=>r.endsWith(o),e,t,n),contains:(e,t,n)=>hr((r,o)=>r.includes(o),e,t,n),upper:(e,t)=>hr(n=>n.toUpperCase(),e,t),lower:(e,t)=>hr(n=>n.toLowerCase(),e,t),replace:(e,t,n,r)=>hr((o,i,a)=>o.replaceAll(i,a),e,t,n,r),matches:(e,t,n)=>hr((r,o)=>!!new RegExp(o).exec(r),e,t,n),replaceMatches:(e,t,n,r)=>hr((o,i,a)=>o.replaceAll(i,a),e,t,n,r),length:(e,t)=>hr(n=>n.length,e,t),toChars:(e,t)=>hr(n=>n?n.split(""):void 0,e,t),encode:xo,decode:xo,escape:xo,unescape:xo,trim:xo,split:xo,join:(e,t,n)=>{var o;const r=((o=n==null?void 0:n.eval(e,Hi(e))[0])==null?void 0:o.value)??"";if(typeof r!="string")throw new Error("Separator must be a string.");return[{type:U.string,value:t.map(i=>{var a;return((a=i.value)==null?void 0:a.toString())??""}).join(r)}]},abs:(e,t)=>to(Math.abs,e,t),ceiling:(e,t)=>to(Math.ceil,e,t),exp:(e,t)=>to(Math.exp,e,t),floor:(e,t)=>to(Math.floor,e,t),ln:(e,t)=>to(Math.log,e,t),log:(e,t,n)=>to((r,o)=>Math.log(r)/Math.log(o),e,t,n),power:(e,t,n)=>to(Math.pow,e,t,n),round:(e,t)=>to(Math.round,e,t),sqrt:(e,t)=>to(Math.sqrt,e,t),truncate:(e,t)=>to(n=>n|0,e,t),children:xo,descendants:xo,trace:(e,t,n)=>t,now:()=>[{type:U.dateTime,value:new Date().toISOString()}],timeOfDay:()=>[{type:U.time,value:new Date().toISOString().substring(11)}],today:()=>[{type:U.date,value:new Date().toISOString().substring(0,10)}],between:(e,t,n,r,o)=>{var u;const i=zn.toDateTime(e,n.eval(e,t));if(i.length===0)throw new Error("Invalid start date");const a=zn.toDateTime(e,r.eval(e,t));if(a.length===0)throw new Error("Invalid end date");const l=(u=o.eval(e,t)[0])==null?void 0:u.value;if(l!=="years"&&l!=="months"&&l!=="days")throw new Error("Invalid units");const c=_P(i[0].value,a[0].value);return[{type:U.Quantity,value:{value:c[l],unit:l}}]},is:(e,t,n)=>{let r="";return n instanceof lx?r=n.name:n instanceof ux&&(r=n.left.name+"."+n.right.name),r?t.map(o=>({type:U.boolean,value:kP(o,r)})):[]},not:(e,t)=>zn.toBoolean(e,t).map(n=>({type:U.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 i=r;if(i.resource)return po(i.resource);i.reference?o=i.reference:i.type&&i.identifier&&(o=`${i.type}?identifier=${i.identifier.system}|${i.identifier.value}`)}if(o!=null&&o.includes("?")){const[i]=o.split("?");return{type:i,value:{resourceType:i}}}if(o!=null&&o.includes("/")){const[i,a]=o.split("/");return{type:i,value:{resourceType:i,id:a}}}return{type:U.BackboneElement,value:void 0}}).filter(n=>!!n.value),as:(e,t)=>t,type:(e,t)=>t.map(({value:n})=>typeof n=="boolean"?{type:U.BackboneElement,value:{namespace:"System",name:"Boolean"}}:typeof n=="number"?{type:U.BackboneElement,value:{namespace:"System",name:"Integer"}}:Yo(n)?{type:U.BackboneElement,value:{namespace:"FHIR",name:n.resourceType}}:{type:U.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(i=>{var a;return{type:U.boolean,value:((a=i.value)==null?void 0:a.resourceType)===o}})}};function hr(e,t,n,...r){if(n.length===0)return[];const[{value:o}]=oo(n,1);if(typeof o!="string")throw new Error("String function cannot be called with non-string");const i=e(o,...r.map(a=>{var l;return(l=a==null?void 0:a.eval(t,n)[0])==null?void 0:l.value}));return i===void 0?[]:Array.isArray(i)?i.map(po):[po(i)]}function to(e,t,n,...r){if(n.length===0)return[];const[{value:o}]=oo(n,1),i=Sr(o),a=i?o.value:o;if(typeof a!="number")throw new Error("Math function cannot be called with non-number");const l=e(a,...r.map(d=>{var f;return(f=d.eval(t,n)[0])==null?void 0:f.value})),c=i?U.Quantity:n[0].type,u=i?{...o,value:l}:l;return[{type:c,value:u}]}function oo(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 Hi(e){var n;let t=e;for(;(n=t.parent)!=null&&n.variables.$this;)t=t.parent;return[t.variables.$this]}class l6{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 ta{constructor(t){this.value=t}eval(){return[this.value]}toString(){const t=this.value.value;return typeof t=="string"?`'${t}'`:t.toString()}}class lx{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==null?void 0: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 Yo(n)&&n.resourceType===this.name?t:pn(t,this.name)}toString(){return this.name}}class c6{eval(){return[]}toString(){return"{}"}}class u6 extends nL{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 cx extends Xc{constructor(t,n){super("as",t,n)}eval(t,n){return zn.ofType(t,this.left.eval(t,n),this.right)}}class Zn extends Xc{}class Ar extends Zn{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 i=r[0].value,a=o[0].value,l=Sr(i)?i.value:i,c=Sr(a)?a.value:a,u=this.impl(l,c);return typeof u=="boolean"?Ce(u):Sr(i)?[{type:U.Quantity,value:{...i,value:u}}]:[po(u)]}}class d6 extends Xc{constructor(t,n){super("&",t,n)}eval(t,n){const r=this.left.eval(t,n),o=this.right.eval(t,n),i=[...r,...o];return i.length>0&&i.every(a=>typeof a.value=="string")?[{type:U.string,value:i.map(a=>a.value).join("")}]:i}}class f6 extends Zn{constructor(t,n){super("contains",t,n)}eval(t,n){const r=this.left.eval(t,n),o=this.right.eval(t,n);return Ce(r.some(i=>i.value===o[0].value))}}class h6 extends Zn{constructor(t,n){super("in",t,n)}eval(t,n){const r=$o(this.left.eval(t,n)),o=this.right.eval(t,n);return r?Ce(o.some(i=>i.value===r.value)):[]}}class ux extends Xc{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 FP extends Xc{constructor(t,n){super("|",t,n)}eval(t,n){const r=this.left.eval(t,n),o=this.right.eval(t,n);return jP([...r,...o])}}class p6 extends Zn{constructor(t,n){super("=",t,n)}eval(t,n){const r=this.left.eval(t,n),o=this.right.eval(t,n);return EP(r,o)}}class m6 extends Zn{constructor(t,n){super("!=",t,n)}eval(t,n){const r=this.left.eval(t,n),o=this.right.eval(t,n);return CP(EP(r,o))}}class g6 extends Zn{constructor(t,n){super("~",t,n)}eval(t,n){const r=this.left.eval(t,n),o=this.right.eval(t,n);return PP(r,o)}}class v6 extends Zn{constructor(t,n){super("!~",t,n)}eval(t,n){const r=this.left.eval(t,n),o=this.right.eval(t,n);return CP(PP(r,o))}}class dx extends Zn{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 Ce(kP(r[0],o))}}class y6 extends Zn{constructor(t,n){super("and",t,n)}eval(t,n){const r=$o(this.left.eval(t,n),"boolean"),o=$o(this.right.eval(t,n),"boolean");return(r==null?void 0:r.value)===!0&&(o==null?void 0:o.value)===!0?Ce(!0):(r==null?void 0:r.value)===!1||(o==null?void 0:o.value)===!1?Ce(!1):[]}}class x6 extends Zn{constructor(t,n){super("or",t,n)}eval(t,n){const r=$o(this.left.eval(t,n),"boolean"),o=$o(this.right.eval(t,n),"boolean");return(r==null?void 0:r.value)===!1&&(o==null?void 0:o.value)===!1?Ce(!1):r!=null&&r.value||o!=null&&o.value?Ce(!0):[]}}class b6 extends Zn{constructor(t,n){super("xor",t,n)}eval(t,n){const r=$o(this.left.eval(t,n),"boolean"),o=$o(this.right.eval(t,n),"boolean");return!r||!o?[]:Ce(r.value!==o.value)}}class w6 extends Zn{constructor(t,n){super("implies",t,n)}eval(t,n){const r=$o(this.left.eval(t,n),"boolean"),o=$o(this.right.eval(t,n),"boolean");return(o==null?void 0:o.value)===!0||(r==null?void 0:r.value)===!1?Ce(!0):!r||!o?[]:Ce(!1)}}class fx{constructor(t,n){this.name=t,this.args=n}eval(t,n){const r=zn[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 hx{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 i=this.left.eval(t,n);return o in i?[i[o]]:[]}toString(){return`${this.left.toString()}[${this.expr.toString()}]`}}const S6=["year","years","month","months","week","weeks","day","days","hour","hours","minute","minutes","second","seconds","millisecond","milliseconds"];class j6{constructor(t,n,r,o){this.result=[],this.pos={index:0,line:1,column:0},this.markStack=[],this.str=t,this.keywords=n,this.operators=r,this.dateTimeLiterals=!!(o!=null&&o.dateTimeLiterals),this.symbolRegex=(o==null?void 0: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==='"'?this.consumeString(t):t==="`"?this.consumeBacktickSymbol():t==="@"?this.consumeDateTime():/\d/.exec(t)?this.consumeNumber():/\w/.exec(t)?this.consumeSymbol():(t==="$"||t==="%")&&/\w/.exec(n)?this.consumeSymbol():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()!==`
92
92
  `))}consumeString(t){this.advance();const n=this.buildToken("String",this.consumeWhile(()=>this.prev()==="\\"||this.curr()!==t));return this.advance(),n}consumeBacktickSymbol(){this.advance();const t=this.buildToken("Symbol",this.consumeWhile(()=>this.curr()!=="`"));return this.advance(),t}consumeDateTime(){this.advance();const t=this.pos.index;this.consumeWhile(()=>/[\d-]/.exec(this.curr()));let n=!1,r=!1;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()))));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()===" "&&C6(this.peekToken())&&(n="Quantity",this.consumeToken()),this.buildToken(n,this.str.substring(t,this.pos.index)))}consumeSymbol(){var n;const t=this.consumeWhile(()=>this.symbolRegex.exec(this.curr()));return((n=this.prevToken())==null?void 0:n.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]}prev(){return this.str[this.pos.index-1]??""}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()===`
93
- `?(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 C6(e){return!!(e&&(e.id==="String"||e.id==="Symbol"&&S6.includes(e.value)))}const E6=["true","false"],T6=["!=","!~","<=",">=","{}","->"];function P6(e){return new j6(e,E6,T6).tokenize()}const ct={FunctionCall:0,Dot:1,Indexer:2,UnaryAdd:3,UnarySubtract:3,Multiply:4,Divide:4,IntegerDivide:4,Modulo:4,Add:5,Subtract:5,Ampersand:5,Is:6,As:6,Union:7,GreaterThan:8,GreaterThanOrEquals:8,LessThan:8,LessThanOrEquals:8,Equals:9,Equivalent:9,NotEquals:9,NotEquivalent:9,In:10,Contains:10,And:11,Xor:12,Or:12,Implies:13,Arrow:100,Semicolon:200},k6={parse(e){var n;const t=e.consumeAndParse();if(!e.match(")"))throw new Error("Parse error: expected `)` got `"+((n=e.peek())==null?void 0:n.value)+"`");return t}},R6={parse(e,t){const n=e.consumeAndParse();if(!e.match("]"))throw new Error("Parse error: expected `]`");return new hx(t,n)},precedence:ct.Indexer},_6={parse(e,t){if(!(t instanceof lx))throw new Error("Unexpected parentheses");const n=[];for(;!e.match(")");)n.push(e.consumeAndParse()),e.match(",");return new fx(t.name,n)},precedence:ct.FunctionCall};function D6(e){const t=e.split(" "),n=parseFloat(t[0]);let r=t[1];return r!=null&&r.startsWith("'")&&r.endsWith("'")?r=r.substring(1,r.length-1):r="{"+r+"}",{value:n,unit:r}}function I6(){return new rL().registerPrefix("String",{parse:(e,t)=>new ta({type:U.string,value:t.value})}).registerPrefix("DateTime",{parse:(e,t)=>new ta({type:U.dateTime,value:hd(t.value)})}).registerPrefix("Quantity",{parse:(e,t)=>new ta({type:U.Quantity,value:D6(t.value)})}).registerPrefix("Number",{parse:(e,t)=>new ta({type:t.value.includes(".")?U.decimal:U.integer,value:parseFloat(t.value)})}).registerPrefix("true",{parse:()=>new ta({type:U.boolean,value:!0})}).registerPrefix("false",{parse:()=>new ta({type:U.boolean,value:!1})}).registerPrefix("Symbol",{parse:(e,t)=>new lx(t.value)}).registerPrefix("{}",{parse:()=>new c6}).registerPrefix("(",k6).registerInfix("[",R6).registerInfix("(",_6).prefix("+",ct.UnaryAdd,(e,t)=>new u6("+",t,n=>n)).prefix("-",ct.UnarySubtract,(e,t)=>new Ar("-",t,t,(n,r)=>-r)).infixLeft(".",ct.Dot,(e,t,n)=>new ux(e,n)).infixLeft("/",ct.Divide,(e,t,n)=>new Ar("/",e,n,(r,o)=>r/o)).infixLeft("*",ct.Multiply,(e,t,n)=>new Ar("*",e,n,(r,o)=>r*o)).infixLeft("+",ct.Add,(e,t,n)=>new Ar("+",e,n,(r,o)=>r+o)).infixLeft("-",ct.Subtract,(e,t,n)=>new Ar("-",e,n,(r,o)=>r-o)).infixLeft("|",ct.Union,(e,t,n)=>new FP(e,n)).infixLeft("=",ct.Equals,(e,t,n)=>new p6(e,n)).infixLeft("!=",ct.NotEquals,(e,t,n)=>new m6(e,n)).infixLeft("~",ct.Equivalent,(e,t,n)=>new g6(e,n)).infixLeft("!~",ct.NotEquivalent,(e,t,n)=>new v6(e,n)).infixLeft("<",ct.LessThan,(e,t,n)=>new Ar("<",e,n,(r,o)=>r<o)).infixLeft("<=",ct.LessThanOrEquals,(e,t,n)=>new Ar("<=",e,n,(r,o)=>r<=o)).infixLeft(">",ct.GreaterThan,(e,t,n)=>new Ar(">",e,n,(r,o)=>r>o)).infixLeft(">=",ct.GreaterThanOrEquals,(e,t,n)=>new Ar(">=",e,n,(r,o)=>r>=o)).infixLeft("&",ct.Ampersand,(e,t,n)=>new d6(e,n)).infixLeft("and",ct.And,(e,t,n)=>new y6(e,n)).infixLeft("as",ct.As,(e,t,n)=>new cx(e,n)).infixLeft("contains",ct.Contains,(e,t,n)=>new f6(e,n)).infixLeft("div",ct.Divide,(e,t,n)=>new Ar("div",e,n,(r,o)=>r/o|0)).infixLeft("in",ct.In,(e,t,n)=>new h6(e,n)).infixLeft("is",ct.Is,(e,t,n)=>new dx(e,n)).infixLeft("mod",ct.Modulo,(e,t,n)=>new Ar("mod",e,n,(r,o)=>r%o)).infixLeft("or",ct.Or,(e,t,n)=>new x6(e,n)).infixLeft("xor",ct.Xor,(e,t,n)=>new b6(e,n)).infixLeft("implies",ct.Implies,(e,t,n)=>new w6(e,n))}const A6=I6();function zP(e){return new l6(e,A6.construct(P6(e)).consumeAndParse())}function al(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]=po(n[r]))}return Cc(e,n).map(r=>r.value)}function Cc(e,t,n){const r=n??{};return zP(e).eval({variables:r},t).map(i=>{var a;return{type:i.type,value:(a=i.value)==null?void 0:a.valueOf()}})}var Co=(e=>(e.BOOLEAN="BOOLEAN",e.NUMBER="NUMBER",e.QUANTITY="QUANTITY",e.TEXT="TEXT",e.REFERENCE="REFERENCE",e.CANONICAL="CANONICAL",e.DATE="DATE",e.DATETIME="DATETIME",e.PERIOD="PERIOD",e.UUID="UUID",e))(Co||{});function ll(e,t){var r,o;let n=(o=(r=go.types[e])==null?void 0:r.searchParamsDetails)==null?void 0:o[t.code];return n||(n=M6(e,t)),n}function N6(e,t,n){let r=go.types[e];r||(r={},go.types[e]=r),r.searchParamsDetails||(r.searchParamsDetails={}),r.searchParamsDetails[t]=n}function M6(e,t){const n=t.code,r=L6(n),o=z6(e,t.expression),i={elementDefinitions:[],propertyTypes:new Set,array:!1};for(const l of o){const c=Gl(l),u=B7(()=>c.join("."));c.length===1&&c[0]instanceof Zn?i.propertyTypes.add("boolean"):u().endsWith("extension.value.code")||u().endsWith("extension.value.coding.code")?(i.array=!0,i.propertyTypes.add("code")):BP(i,Gl(l),e,1),u().endsWith("extension.valueDateTime")&&(i.array=!1)}const a={columnName:r,type:F6(t,i.propertyTypes),elementDefinitions:i.elementDefinitions,array:i.array};return N6(e,n,a),a}function BP(e,t,n,r){const o=t[r];if(o instanceof cx){e.propertyTypes.add(o.right.toString());return}if(o instanceof fx){O6(e,o);return}const i=o.toString(),a=zs(n,i);if(!a)throw new Error(`Element definition not found for ${n} ${i}`);let l=!1,c=r+1;if(c<t.length&&t[c]instanceof hx&&(l=!0,c++),a.isArray&&!l&&(e.array=!0),c>=t.length){e.elementDefinitions.push(a);for(const u of a.type)e.propertyTypes.add(u.code);return}for(const u of a.type){let d=u.code;$6(d)&&(d=a.type[0].code),BP(e,t,d,c)}}function O6(e,t){if(t.name==="as"){e.propertyTypes.add(t.args[0].toString());return}if(t.name==="resolve"){e.propertyTypes.add("string");return}if(t.name==="where"&&t.args[0]instanceof dx){e.propertyTypes.add(t.args[0].right.toString());return}throw new Error(`Unhandled FHIRPath function: ${t.name}`)}function $6(e){return e==="Element"||e==="BackboneElement"}function L6(e){return e.split("-").reduce((t,n,r)=>t+(r?Qt(n):n),"")}function F6(e,t){switch(e.type){case"date":return t.size===1&&t.has(U.date)?"DATE":"DATETIME";case"number":return"NUMBER";case"quantity":return"QUANTITY";case"reference":return t.has(U.canonical)?"CANONICAL":"REFERENCE";case"token":return t.size===1&&t.has(U.boolean)?"BOOLEAN":"TEXT";default:return"TEXT"}}function z6(e,t){const n=[],r=zP(t);return Xm(e,r.child,n),n}function Xm(e,t,n){t instanceof FP?(Xm(e,t.left,n),Xm(e,t.right,n)):t.toString().startsWith(e+".")&&n.push(t)}function Gl(e){if(e instanceof cx||e instanceof hx)return[Gl(e.left),e].flat();if(e instanceof Zn)return[e];if(e instanceof ux)return[Gl(e.left),Gl(e.right)].flat();if(e instanceof fx){if(e.name==="where"&&!(e.args[0]instanceof dx))return[];if(e.name==="last")return[]}return[e]}const hh=20;var te=(e=>(e.EQUALS="eq",e.NOT_EQUALS="ne",e.GREATER_THAN="gt",e.LESS_THAN="lt",e.GREATER_THAN_OR_EQUALS="ge",e.LESS_THAN_OR_EQUALS="le",e.STARTS_AFTER="sa",e.ENDS_BEFORE="eb",e.APPROXIMATELY="ap",e.CONTAINS="contains",e.EXACT="exact",e.TEXT="text",e.NOT="not",e.ABOVE="above",e.BELOW="below",e.IN="in",e.NOT_IN="not-in",e.OF_TYPE="of-type",e.MISSING="missing",e.PRESENT="present",e.IDENTIFIER="identifier",e.ITERATE="iterate",e))(te||{});const VP={contains:"contains",exact:"exact",above:"above",below:"below",text:"text",not:"not",in:"in","not-in":"not-in","of-type":"of-type",missing:"missing",identifier:"identifier",iterate:"iterate"},px={eq:"eq",ne:"ne",lt:"lt",le:"le",gt:"gt",ge:"ge",sa:"sa",eb:"eb",ap:"ap"};function UP(e,t){if(!e)throw new Error("Invalid search URL");let n="",r;if(typeof e=="string")if(e.includes("?")){const[a,l]=e.split("?");n=a,r=new URLSearchParams(l)}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 i=[];return r&&i.push(...r.entries()),B6(o,i)}function B6(e,t){const n={resourceType:e};for(const[r,o]of t)V6(n,r,o);return n}function V6(e,t,n){var a,l;let r,o;const i=t.indexOf(":");if(i>=0?(r=t.substring(0,i),o=t.substring(i+1)):(r=t,o=""),r!=="_"){if(r==="_has"||t.includes(".")){e.filters=Tl(e.filters,{code:t,operator:"eq",value:n});return}switch(r){case"_sort":U6(e,n);break;case"_count":e.count=parseInt(n,10);break;case"_offset":e.offset=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=$b(n);o==="iterate"&&(c.modifier="iterate"),e.include=Tl(e.include,c);break}case"_revinclude":{const c=$b(n);o==="iterate"&&(c.modifier="iterate"),e.revInclude=Tl(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=(l=(a=go.types[e.resourceType])==null?void 0:a.searchParams)==null?void 0:l[r];c?e.filters=Tl(e.filters,H6(c,o,n)):e.filters=Tl(e.filters,G6(r,o,n))}}}}function U6(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})}}function H6(e,t,n){if(t==="missing")return{code:e.code,operator:"missing",value:n};switch(e.type){case"number":case"date":case"quantity":return W6(e,n);case"reference":case"string":case"token":case"uri":return q6(e,t,n);default:throw new Error("Unrecognized search parameter type: "+e.type)}}function W6(e,t){const{operator:n,value:r}=Q6(t);return{code:e.code,operator:n,value:r}}function q6(e,t,n){return{code:e.code,operator:K6(t),value:n}}function G6(e,t,n){var o;let r="eq";if(t)r=t;else if(n.length>=2){const i=n.substring(0,2);i in px&&(n.length===2||(o=n.at(2))!=null&&o.match(/\d/))&&(r=i,n=n.substring(i.length))}return{code:e,operator:r,value:n}}function Q6(e){const t=e.substring(0,2),n=px[t];return n?{operator:n,value:e.substring(2)}:{operator:"eq",value:e}}function K6(e){return VP[e]??"eq"}function $b(e){const t=e.split(":");if(t.includes("*"))throw new qe(Ei("'*' is not supported as a value for search inclusion parameters"));if(t.length===1)throw new qe(Ei(`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 qe(Ei(`Invalid include value '${e}'`))}function xa(e){const t=[];return e.fields&&t.push("_fields="+e.fields.join(",")),e.filters&&e.filters.forEach(n=>t.push(Y6(n))),e.sortRules&&e.sortRules.length>0&&t.push(X6(e.sortRules)),e.offset!==void 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.include&&e.include.forEach(n=>t.push(Lb("_include",n))),e.revInclude&&e.revInclude.forEach(n=>t.push(Lb("_revinclude",n))),t.length===0?"":(wc(t),"?"+t.join("&"))}function Y6(e){const t=e.operator in VP?":"+e.operator:"",n=e.operator!=="eq"&&e.operator in px?e.operator:"";return`${e.code}${t}=${n}${encodeURIComponent(e.value)}`}function X6(e){return"_sort="+e.map(t=>t.descending?"-"+t.code:t.code).join(",")}function Lb(e,t){return e+(t.modifier?":"+t.modifier:"")+"="+t.resourceType+":"+t.searchParam+(t.targetType?":"+t.targetType:"")}function mx(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 J6(e,t){if(t.resourceType!==e.resourceType)return!1;if(t.filters){for(const n of t.filters)if(!Z6(e,t,n))return!1}return!0}function Z6(e,t,n){var o,i;const r=(i=(o=go.types[t.resourceType])==null?void 0:o.searchParams)==null?void 0:i[n.code];if(!r)return!1;if(n.operator===te.MISSING||n.operator===te.PRESENT)return eF(e,n,r);switch(r.type){case"reference":return tF(e,n,r);case"string":case"uri":return HP(e,n,r);case"token":return nF(e,n,r);case"date":return sF(e,n,r);default:return!1}}function eF(e,t,n){const o=al(n.expression,e).length>0;return(t.operator===te.MISSING&&t.value==="false"||t.operator===te.PRESENT&&t.value==="true")===o}function tF(e,t,n){const r=al(n.expression,e),o=ph(t.operator);if(t.value===""&&r.length===0)return t.operator===te.EQUALS;const i=r.map(a=>typeof a=="string"?a:a.reference);for(const a of mx(t.value)){let l=i.includes(a);if(!l&&t.code==="_compartment"&&(l=i.some(c=>c==null?void 0:c.endsWith("/"+a))),l)return!o}return o}function nF(e,t,n){return ll(e.resourceType,n).type===Co.BOOLEAN?rF(e,t,n):HP(e,t,n,!0)}function rF(e,t,n){const r=al(n.expression,e),o=t.value==="true",i=r.includes(o);return ph(t.operator)?!i:i}function HP(e,t,n,r){var u,d;const i=(d=(u=ll(e.resourceType,n).elementDefinitions)==null?void 0:u[0].type)==null?void 0:d[0].code,a=al(n.expression,e),l=mx(t.value),c=ph(t.operator);for(const f of a)for(const h of l){let m;if(i===U.Identifier?m=oF(f,t.operator,h):i===U.CodeableConcept?m=iF(f,t.operator,h):m=Jm(f,t.operator,h,r),m)return!c}return c}function Jm(e,t,n,r){if(r&&n.includes("|")){const[i,a]=n.split("|");return Jm(e,t,i,!1)&&(!a||Jm(e,t,a,!1))}let o="";return e&&(typeof e=="string"?o=e:typeof e=="object"&&(o=JSON.stringify(e))),o.toLowerCase().includes(n.toLowerCase())}function oF(e,t,n){var r,o,i;if(n.includes("|")){const[a,l]=n.split("|");return((r=e.system)==null?void 0:r.toLowerCase())===a.toLowerCase()&&((o=e.value)==null?void 0:o.toLowerCase())===l.toLowerCase()}return((i=e.value)==null?void 0:i.toLowerCase())===n.toLowerCase()}function iF(e,t,n){var r,o,i;if(n.includes("|")){const[a,l]=n.split("|");return((r=e.coding)==null?void 0:r.some(c=>{var u,d;return((u=c.system)==null?void 0:u.toLowerCase())===a.toLowerCase()&&((d=c.code)==null?void 0:d.toLowerCase())===l.toLowerCase()}))??!1}return((o=e.text)==null?void 0:o.toLowerCase())===n.toLowerCase()||(((i=e.coding)==null?void 0:i.some(a=>{var l;return((l=a.code)==null?void 0:l.toLowerCase())===n.toLowerCase()}))??!1)}function sF(e,t,n){const r=al(n.expression,e),o=mx(t.value),i=ph(t.operator);for(const a of r)for(const l of o)if(aF(a,t.operator,l))return!i;return i}function aF(e,t,n){switch(t){case te.STARTS_AFTER:case te.GREATER_THAN:return e>n;case te.GREATER_THAN_OR_EQUALS:return e>=n;case te.ENDS_BEFORE:case te.LESS_THAN:return e<n;case te.LESS_THAN_OR_EQUALS:return e<=n;case te.EQUALS:case te.NOT_EQUALS:return e===n;default:return!1}}function ph(e){return e===te.NOT_EQUALS||e===te.NOT}const lF={resourceType:"*"},cF=["DomainConfiguration","JsonWebKey","Login"],uF=["PasswordChangeRequest","UserSecurityRequest","Project","ProjectMembership","User"];var gx=(e=>(e.READ="read",e.VREAD="vread",e.UPDATE="update",e.PATCH="patch",e.DELETE="delete",e.HISTORY="history",e.HISTORY_INSTANCE="history-instance",e.HISTORY_TYPE="history-type",e.HISTORY_SYSTEM="history-system",e.CREATE="create",e.SEARCH="search",e.SEARCH_TYPE="search-type",e.SEARCH_SYSTEM="search-system",e.SEARCH_COMPARTMENT="search-compartment",e.CAPABILITIES="capabilities",e.TRANSACTION="transaction",e.BATCH="batch",e.OPERATION="operation",e))(gx||{});const dF=["read","vread","history","history-instance"];function fF(e,t){if(cF.includes(t))return!1;if(e.resource){for(const n of e.resource)if(qP(n.resourceType,t)&&!n.readonly)return!0}return!1}function WP(e,t,n){if(!n)return lF;if(n.resource){for(const r of n.resource)if(hF(e,t,r))return r}}function hF(e,t,n){var o,i;const r=e.resourceType;return!(!qP(n.resourceType,r)||n.readonly&&!dF.includes(t)||n.compartment&&!((i=(o=e.meta)==null?void 0:o.compartment)!=null&&i.find(a=>{var l;return a.reference===((l=n.compartment)==null?void 0:l.reference)}))||n.criteria&&!J6(e,UP(n.criteria)))}function qP(e,t){return e===t||e==="*"&&!uF.includes(t)}function pF(e){if(typeof window<"u")return window.atob(e);if(typeof Buffer<"u")return Buffer.from(e,"base64").toString("binary");throw new Error("Unable to decode base64")}function mF(e){if(typeof window<"u")return window.btoa(e);if(typeof Buffer<"u")return Buffer.from(e,"binary").toString("base64");throw new Error("Unable to encode base64")}function Fb(){const e=new Uint32Array(28);return crypto.getRandomValues(e),$7(e.buffer)}async function gF(e){return crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))}function GP(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function QP(e){var o,i,a;const t={};e=mo(e);for(const l of e.entry||[]){((o=l.resource)==null?void 0:o.meta)!==void 0&&(delete l.resource.meta.author,delete l.resource.meta.compartment,delete l.resource.meta.lastUpdated,delete l.resource.meta.project,delete l.resource.meta.versionId);const c=(i=l.resource)==null?void 0:i.id;c&&(t[c]=GP(),l.fullUrl="urn:uuid:"+t[c],(a=l.resource)==null||delete a.id)}const n=e.entry,r=JSON.stringify({resourceType:"Bundle",type:"transaction",entry:n==null?void 0:n.map(l=>({fullUrl:l.fullUrl,request:{method:"POST",url:l.resource.resourceType},resource:l.resource}))},(l,c)=>vF(l,c,t),2);return yF(JSON.parse(r))}function vF(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 yF(e){const t=bF(e),{sorted:n,cycles:r}=xF(t),o={};for(const a of e.entry||[])a.fullUrl&&(o[a.fullUrl]=a);const i=n.map(a=>o[a]);for(const a of r)for(const l of a){const c=o[l],u={...c,request:{...c.request,method:"PUT"}};i.push(u)}return{...e,entry:i}}function xF(e){const t=[],n={},r=[];for(const i of Object.keys(e))n[i]=0;function o(i,a){if(n[i]===2)return!0;if(n[i]===1){const c=a.lastIndexOf(i);return c!==-1&&r.push(a.slice(c)),!0}n[i]=1,a.push(i);let l=!1;for(const c of e[i])o(c,a)||(l=!0);return n[i]=2,a.pop(),t.unshift(i),!l}for(const i in e)n[i]===0&&o(i,[]);return{sorted:t,cycles:r}}function KP(e,t){for(const n in e)if(e[n]&&typeof e[n]=="object"){const r=e[n];if(Bs(r)){const o=r.reference;o.startsWith("urn:uuid:")&&t(o)}else KP(r,t)}}function bF(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&&KP(n.resource,o=>{t[o]&&t[o].push(r)})}return t}class YP{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 Jt={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",PNG:"image/png",SCIM_JSON:"application/scim+json",SVG:"image/svg+xml",TEXT:"text/plain",TYPESCRIPT:"text/typescript",PING:"x-application/ping"};class XP{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={}}}class vx{constructor(){this.emitter=new XP}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()}}const Zm={"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"},wF=["Patient","Encounter","ImagingStudy","DiagnosticReport","OperationOutcome","Bundle"],yx=["DiagnosticReport-update"];function SF(e){return yx.includes(e)}function jF(e){if(yx.includes(e))throw new qe(Tt(`'context.version' is required for '${e}'.`))}const CF={"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"},select:{resourceType:"*",isArray:!0}},"DiagnosticReport-update":{report:{resourceType:"DiagnosticReport"},patient:{resourceType:"Patient",optional:!0},study:{resourceType:"ImagingStudy",optional:!0},updates:{resourceType:"Bundle"}},syncerror:{operationoutcome:{resourceType:"OperationOutcome"}}};function EF(e){return wF.includes(e)}function JP(e){return!!e.endpoint}function zb(e){if(!xx(e))throw new qe(Tt("subscriptionRequest must be an object conforming to SubscriptionRequest type."));const{channelType:t,mode:n,topic:r,events:o}=e,i={"hub.channel.type":t,"hub.mode":n,"hub.topic":r,"hub.events":o.join(",")};return JP(e)&&(i.endpoint=e.endpoint),new URLSearchParams(i).toString()}function xx(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 i of o)if(!Zm[i])return!1;return!(JP(e)&&!(typeof e.endpoint=="string"&&e.endpoint.startsWith("ws")))}function Bb(e,t,n,r){if(typeof t!="object")throw new qe(Tt(`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 qe(Tt(`context[${n}] is invalid. Resource must contain a valid string ID.`));if(!t.resourceType)throw new qe(Tt(`context[${n}] is invalid. Resource must contain a resource type. No resource type found.`));const o=r.resourceType;if(o!=="*"){if(!EF(t.resourceType))throw new qe(Tt(`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 qe(Tt(`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.isArray)Bb(e,t.resource,n,r);else{const{resources:i}=t;if(!i)throw new qe(Tt(`context[${n}] is invalid. context[${n}] for the '${e}' with key '${String(t.key)}' should contain an array of resources on the key 'resources'.`));for(const a of i)Bb(e,a,n,r)}}function PF(e,t){const n=new Map,r=CF[e];for(let o=0;o<t.length;o++){const i=t[o].key;if(!r[i])throw new qe(Tt(`Key '${i}' not found for event '${e}'. Make sure to add only valid keys.`));TF(e,t[o],o,r[i],n)}for(const[o,i]of Object.entries(r)){if(!(i.optional||n.has(o)))throw new qe(Tt(`Missing required key '${o}' on context for '${e}' event.`));if(!i.manyAllowed&&(n.get(o)||0)>1)throw new qe(Tt(`${n.get(o)} context entries with key '${o}' found for the '${e}' event when schema only allows for 1.`))}}function Vb(e,t,n,r){if(!(e&&typeof e=="string"))throw new qe(Tt("Must provide a topic."));if(!Zm[t])throw new qe(Tt(`Must provide a valid FHIRcast event name. Supported events: ${Object.keys(Zm).join(", ")}`));if(typeof n!="object")throw new qe(Tt("context must be a context object or array of context objects."));if(yx.includes(t)&&!r)throw new qe(Tt(`The '${t}' event must contain a 'context.versionId'.`));const o=Array.isArray(n)?n:[n];return PF(t,o),{timestamp:new Date().toISOString(),id:GP(),event:{"hub.topic":e,"hub.event":t,context:o,...r?{"context.versionId":r}:{}}}}class kF extends vx{constructor(t){if(super(),this.subRequest=t,!t.endpoint)throw new qe(Tt("Subscription request should contain an endpoint."));if(!xx(t))throw new qe(Tt("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 i=o;i.event["hub.event"]!=="heartbeat"&&(this.dispatchEvent({type:"message",payload:i}),n.send(JSON.stringify({id:o==null?void 0:o.id,timestamp:new Date().toISOString()})))}),n.addEventListener("close",()=>{this.dispatchEvent({type:"disconnect"})})}),this.websocket=n}disconnect(){this.websocket.close()}}function RF(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=pF(t),r=Array.from(n).reduce((i,a)=>{const l=("00"+a.charCodeAt(0).toString(16)).slice(-2);return`${i}%${l}`},""),o=decodeURIComponent(r);return JSON.parse(o)}function _F(e){return e.split(".").length===3}function bx(e){const[t,n,r]=e.split(".");return RF(n)}function DF(e){try{return typeof bx(e).login_id=="string"}catch{return!1}}function IF(e){try{const n=bx(e).exp;return typeof n=="number"?n*1e3:void 0}catch{return}}class AF{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,Jt.TEXT)}async delete(t){await this.medplum.delete(`keyvalue/v1/${t}`)}}var ZP;ZP=Symbol.toStringTag;class Nr{constructor(t){this[ZP]="ReadablePromise",this.status="pending",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 NF{constructor(t){this.storage=t??(typeof localStorage<"u"?localStorage:new MF)}clear(){this.storage.clear()}getString(t){return this.storage.getItem(t)??void 0}setString(t,n){n?this.storage.setItem(t,n):this.storage.removeItem(t)}getObject(t){const n=this.getString(t);return n?JSON.parse(n):void 0}setObject(t,n){this.setString(t,n?lr(n):void 0)}}class MF{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]}}class OF extends vx{constructor(t){super(),this.bufferedAmount=-1/0,this.extensions="NOT_IMPLEMENTED",this.messageBuffer=[];const n=new WebSocket(t);n.addEventListener("open",()=>{if(this.messageBuffer.length){const r=this.messageBuffer;for(const o of r)n.send(o)}this.dispatchEvent(new Event("open"))}),n.addEventListener("error",r=>{this.dispatchEvent(r)}),n.addEventListener("message",r=>{this.dispatchEvent(r)}),n.addEventListener("close",r=>{this.dispatchEvent(r)}),this.ws=n}get readyState(){return this.ws.readyState}close(){this.ws.close()}send(t){if(this.ws.readyState!==WebSocket.OPEN){this.messageBuffer.push(t);return}try{this.ws.send(t)}catch(n){this.dispatchEvent(new ErrorEvent("error",{error:n,message:n.message})),this.messageBuffer.push(t)}}}class eg extends vx{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 $F{constructor(t,n){this.criteria=t,this.emitter=new eg(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}}class LF{constructor(t,n,r){if(!(t instanceof ek))throw new qe(Tt("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new qe(Tt("Not a valid URL"))}const i=r!=null&&r.RobustWebSocket?new r.RobustWebSocket(o):new OF(o);this.medplum=t,this.ws=i,this.masterSubEmitter=new eg,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.setupWebSocketListeners()}setupWebSocketListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,o,i,a,l;try{const c=JSON.parse(n.data),u=(o=(r=c==null?void 0:c.entry)==null?void 0:r[0])==null?void 0:o.resource;if(u.type==="heartbeat"){(i=this.masterSubEmitter)==null||i.dispatchEvent({type:"heartbeat",payload:c});return}(a=this.masterSubEmitter)==null||a.dispatchEvent({type:"message",payload:c});const d=this.criteriaEntriesBySubscriptionId.get(dh(u.subscription));if(!d){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}d.emitter.dispatchEvent({type:"message",payload:c})}catch(c){console.error(c);const u={type:"error",payload:c};(l=this.masterSubEmitter)==null||l.dispatchEvent(u);for(const d of this.getAllCriteriaEmitters())d.dispatchEvent(u)}}),t.addEventListener("error",()=>{var r;const n={type:"error",payload:new qe(pL(new Error("WebSocket error")))};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const o of this.getAllCriteriaEmitters())o.dispatchEvent(n)}),t.addEventListener("close",()=>{var r;const n={type:"close"};this.wsClosed&&((r=this.masterSubEmitter)==null||r.dispatchEvent(n));for(const o of this.getAllCriteriaEmitters())o.dispatchEvent(n)})}emitConnect(t){var r;const n={type:"connect",payload:{subscriptionId:t.subscriptionId}};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const o of this.getAllCriteriaEmitters())o.dispatchEvent(n)}emitError(t,n){var o;const r={type:"error",payload:n};(o=this.masterSubEmitter)==null||o.dispatchEvent(r),t.emitter.dispatchEvent(r)}maybeEmitDisconnect(t){var r;const{subscriptionId:n}=t;if(n){const o={type:"disconnect",payload:{subscriptionId:n}};(r=this.masterSubEmitter)==null||r.dispatchEvent(o),t.emitter.dispatchEvent(o)}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){var a,l;let n=t==null?void 0:t.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${Ct(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=(a=r==null?void 0:r.find(c=>c.name==="token"))==null?void 0:a.valueString,i=(l=r==null?void 0:r.find(c=>c.name==="websocket-url"))==null?void 0:l.valueUrl;if(!o)throw new qe(Tt("Failed to get token"));if(!i)throw new qe(Tt("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(xs(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){var l;const{criteria:n,subscriptionProps:r,subscriptionId:o,token:i}=t;if(!this.criteriaEntries.has(n))return;const a=this.criteriaEntries.get(n);r?a.criteriaWithProps=a.criteriaWithProps.filter(c=>{const u=c.subscriptionProps;return!xs(r,u)}):a.bareCriteria=void 0,!a.bareCriteria&&a.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),(l=this.masterSubEmitter)==null||l._removeCriteria(n)),o&&this.criteriaEntriesBySubscriptionId.delete(o),i&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:i}}))}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 $F(t,n);return this.addCriteriaEntry(o),this.getTokenForCriteria(o).then(([i,a])=>{o.subscriptionId=i,o.token=a,this.criteriaEntriesBySubscriptionId.set(i,o),this.emitConnect(o),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:a}}))}).catch(i=>{console.error(i.message),this.emitError(o,i),this.removeCriteriaEntry(o)}),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))}closeWebSocket(){this.wsClosed||(this.wsClosed=!0,this.ws.close())}getCriteriaCount(){return this.getAllCriteriaEmitters().length}getMasterEmitter(){return this.masterSubEmitter||(this.masterSubEmitter=new eg(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const FF="3.1.9-eb1d4ee09",zF=Jt.FHIR_JSON+", */*; q=0.1",BF="https://api.medplum.com/",VF=1e3,UF=6e4,HF=0,WF="Binary/",Ub={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]};class ek extends XP{constructor(t){if(super(),this.initComplete=!0,t!=null&&t.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=(t==null?void 0:t.fetch)??qF(),this.storage=(t==null?void 0:t.storage)??new NF,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=AP((t==null?void 0:t.baseUrl)??BF),this.fhirBaseUrl=wo(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=wo(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=wo(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=wo(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),this.clientId=(t==null?void 0:t.clientId)??"",this.clientSecret=(t==null?void 0:t.clientSecret)??"",this.onUnauthenticated=t==null?void 0:t.onUnauthenticated,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?HF:UF),this.cacheTime>0?this.requestCache=new YP((t==null?void 0:t.resourceCacheSize)??VF):this.requestCache=void 0,t!=null&&t.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t!=null&&t.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t!=null&&t.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve()):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t!=null&&t.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0}).catch(console.error)),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}clear(){this.storage.clear(),typeof window<"u"&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){var t;this.storage.setString("activeLogin",void 0),(t=this.requestCache)==null||t.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){var n;t=t.toString(),(n=this.requestCache)==null||n.delete(t)}invalidateAll(){var t;(t=this.requestCache)==null||t.clear()}invalidateSearches(t){const n=wo(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?o=new Promise((a,l)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:a,reject:l}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):o=this.request("GET",t,n);const i=new Nr(o);return this.setCacheEntry(t,i),i}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,Jt.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(window.location.search).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){window.location.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,o,i=!0){let a=o;i&&(a=await this.ensureCodeChallenge(o)),window.location.assign(this.getExternalAuthRedirectUri(t,n,r,a,i))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");const r=new URLSearchParams;return r.set("grant_type","urn:ietf:params:oauth:grant-type:token-exchange"),r.set("subject_token_type","urn:ietf:params:oauth:token-type:access_token"),r.set("client_id",n),r.set("subject_token",t),this.fetchTokens(r)}getExternalAuthRedirectUri(t,n,r,o,i=!0){const a=new URL(t);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",n),a.searchParams.set("redirect_uri",r),a.searchParams.set("scope",o.scope??"openid profile email"),a.searchParams.set("state",JSON.stringify(o)),i){const{codeChallenge:l,codeChallengeMethod:c}=o;if(!c)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!l)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");a.searchParams.set("code_challenge_method",c),a.searchParams.set("code_challenge",l)}return a.toString()}fhirUrl(...t){return new URL(wo(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=H7(n)),r}search(t,n,r){const o=this.fhirSearchUrl(t,n),i="search-"+o.toString(),a=this.getCacheEntry(i,r);if(a)return a.value;const l=new Nr((async()=>{const c=await this.get(o,r);if(c.entry)for(const u of c.entry)this.cacheResource(u.resource);return c})());return this.setCacheEntry(i,l),l}searchOne(t,n,r){const o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();const i="searchOne-"+o.toString(),a=this.getCacheEntry(i,r);if(a)return a.value;const l=new Nr(this.search(t,o.searchParams,r).then(c=>{var u,d;return(d=(u=c.entry)==null?void 0:u[0])==null?void 0:d.resource}));return this.setCacheEntry(i,l),l}searchResources(t,n,r){const i="searchResources-"+this.fhirSearchUrl(t,n).toString(),a=this.getCacheEntry(i,r);if(a)return a.value;const l=new Nr(this.search(t,n,r).then(Cp));return this.setCacheEntry(i,l),l}async*searchResourcePages(t,n,r){var i,a;let o=this.fhirSearchUrl(t,n);for(;o;){const l=new URL(o).searchParams,c=await this.search(t,l,r),u=(i=c.link)==null?void 0:i.find(d=>d.relation==="next");if(!((a=c.entry)!=null&&a.length)&&!u)break;yield Cp(c),o=u!=null&&u.url?new URL(u.url):void 0}}searchValueSet(t,n,r){return this.valueSetExpand({url:t,filter:n},r)}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){var o,i;const r=(i=(o=this.requestCache)==null?void 0:o.get(this.fhirUrl(t,n).toString()))==null?void 0:i.value;return r!=null&&r.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return Ub;const[r,o]=n.split("/");if(!(!r||!o))return this.getCached(r,o)}readResource(t,n,r){return this.get(this.fhirUrl(t,n),r)}readReference(t,n){const r=t.reference;if(!r)return new Nr(Promise.reject(new Error("Missing reference")));if(r==="system")return new Nr(Promise.resolve(Ub));const[o,i]=r.split("/");return!o||!i?new Nr(Promise.reject(new Error("Invalid reference"))):this.readResource(o,i,n)}requestSchema(t){if(xP(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Nr((async()=>{const i=`{
93
+ `?(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 C6(e){return!!(e&&(e.id==="String"||e.id==="Symbol"&&S6.includes(e.value)))}const E6=["true","false"],T6=["!=","!~","<=",">=","{}","->"];function P6(e){return new j6(e,E6,T6).tokenize()}const ct={FunctionCall:0,Dot:1,Indexer:2,UnaryAdd:3,UnarySubtract:3,Multiply:4,Divide:4,IntegerDivide:4,Modulo:4,Add:5,Subtract:5,Ampersand:5,Is:6,As:6,Union:7,GreaterThan:8,GreaterThanOrEquals:8,LessThan:8,LessThanOrEquals:8,Equals:9,Equivalent:9,NotEquals:9,NotEquivalent:9,In:10,Contains:10,And:11,Xor:12,Or:12,Implies:13,Arrow:100,Semicolon:200},k6={parse(e){var n;const t=e.consumeAndParse();if(!e.match(")"))throw new Error("Parse error: expected `)` got `"+((n=e.peek())==null?void 0:n.value)+"`");return t}},R6={parse(e,t){const n=e.consumeAndParse();if(!e.match("]"))throw new Error("Parse error: expected `]`");return new hx(t,n)},precedence:ct.Indexer},_6={parse(e,t){if(!(t instanceof lx))throw new Error("Unexpected parentheses");const n=[];for(;!e.match(")");)n.push(e.consumeAndParse()),e.match(",");return new fx(t.name,n)},precedence:ct.FunctionCall};function D6(e){const t=e.split(" "),n=parseFloat(t[0]);let r=t[1];return r!=null&&r.startsWith("'")&&r.endsWith("'")?r=r.substring(1,r.length-1):r="{"+r+"}",{value:n,unit:r}}function I6(){return new rL().registerPrefix("String",{parse:(e,t)=>new ta({type:U.string,value:t.value})}).registerPrefix("DateTime",{parse:(e,t)=>new ta({type:U.dateTime,value:hd(t.value)})}).registerPrefix("Quantity",{parse:(e,t)=>new ta({type:U.Quantity,value:D6(t.value)})}).registerPrefix("Number",{parse:(e,t)=>new ta({type:t.value.includes(".")?U.decimal:U.integer,value:parseFloat(t.value)})}).registerPrefix("true",{parse:()=>new ta({type:U.boolean,value:!0})}).registerPrefix("false",{parse:()=>new ta({type:U.boolean,value:!1})}).registerPrefix("Symbol",{parse:(e,t)=>new lx(t.value)}).registerPrefix("{}",{parse:()=>new c6}).registerPrefix("(",k6).registerInfix("[",R6).registerInfix("(",_6).prefix("+",ct.UnaryAdd,(e,t)=>new u6("+",t,n=>n)).prefix("-",ct.UnarySubtract,(e,t)=>new Ar("-",t,t,(n,r)=>-r)).infixLeft(".",ct.Dot,(e,t,n)=>new ux(e,n)).infixLeft("/",ct.Divide,(e,t,n)=>new Ar("/",e,n,(r,o)=>r/o)).infixLeft("*",ct.Multiply,(e,t,n)=>new Ar("*",e,n,(r,o)=>r*o)).infixLeft("+",ct.Add,(e,t,n)=>new Ar("+",e,n,(r,o)=>r+o)).infixLeft("-",ct.Subtract,(e,t,n)=>new Ar("-",e,n,(r,o)=>r-o)).infixLeft("|",ct.Union,(e,t,n)=>new FP(e,n)).infixLeft("=",ct.Equals,(e,t,n)=>new p6(e,n)).infixLeft("!=",ct.NotEquals,(e,t,n)=>new m6(e,n)).infixLeft("~",ct.Equivalent,(e,t,n)=>new g6(e,n)).infixLeft("!~",ct.NotEquivalent,(e,t,n)=>new v6(e,n)).infixLeft("<",ct.LessThan,(e,t,n)=>new Ar("<",e,n,(r,o)=>r<o)).infixLeft("<=",ct.LessThanOrEquals,(e,t,n)=>new Ar("<=",e,n,(r,o)=>r<=o)).infixLeft(">",ct.GreaterThan,(e,t,n)=>new Ar(">",e,n,(r,o)=>r>o)).infixLeft(">=",ct.GreaterThanOrEquals,(e,t,n)=>new Ar(">=",e,n,(r,o)=>r>=o)).infixLeft("&",ct.Ampersand,(e,t,n)=>new d6(e,n)).infixLeft("and",ct.And,(e,t,n)=>new y6(e,n)).infixLeft("as",ct.As,(e,t,n)=>new cx(e,n)).infixLeft("contains",ct.Contains,(e,t,n)=>new f6(e,n)).infixLeft("div",ct.Divide,(e,t,n)=>new Ar("div",e,n,(r,o)=>r/o|0)).infixLeft("in",ct.In,(e,t,n)=>new h6(e,n)).infixLeft("is",ct.Is,(e,t,n)=>new dx(e,n)).infixLeft("mod",ct.Modulo,(e,t,n)=>new Ar("mod",e,n,(r,o)=>r%o)).infixLeft("or",ct.Or,(e,t,n)=>new x6(e,n)).infixLeft("xor",ct.Xor,(e,t,n)=>new b6(e,n)).infixLeft("implies",ct.Implies,(e,t,n)=>new w6(e,n))}const A6=I6();function zP(e){return new l6(e,A6.construct(P6(e)).consumeAndParse())}function al(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]=po(n[r]))}return Cc(e,n).map(r=>r.value)}function Cc(e,t,n){const r=n??{};return zP(e).eval({variables:r},t).map(i=>{var a;return{type:i.type,value:(a=i.value)==null?void 0:a.valueOf()}})}var Co=(e=>(e.BOOLEAN="BOOLEAN",e.NUMBER="NUMBER",e.QUANTITY="QUANTITY",e.TEXT="TEXT",e.REFERENCE="REFERENCE",e.CANONICAL="CANONICAL",e.DATE="DATE",e.DATETIME="DATETIME",e.PERIOD="PERIOD",e.UUID="UUID",e))(Co||{});function ll(e,t){var r,o;let n=(o=(r=go.types[e])==null?void 0:r.searchParamsDetails)==null?void 0:o[t.code];return n||(n=M6(e,t)),n}function N6(e,t,n){let r=go.types[e];r||(r={},go.types[e]=r),r.searchParamsDetails||(r.searchParamsDetails={}),r.searchParamsDetails[t]=n}function M6(e,t){const n=t.code,r=L6(n),o=z6(e,t.expression),i={elementDefinitions:[],propertyTypes:new Set,array:!1};for(const l of o){const c=Gl(l),u=B7(()=>c.join("."));c.length===1&&c[0]instanceof Zn?i.propertyTypes.add("boolean"):u().endsWith("extension.value.code")||u().endsWith("extension.value.coding.code")?(i.array=!0,i.propertyTypes.add("code")):BP(i,Gl(l),e,1),u().endsWith("extension.valueDateTime")&&(i.array=!1)}const a={columnName:r,type:F6(t,i.propertyTypes),elementDefinitions:i.elementDefinitions,array:i.array};return N6(e,n,a),a}function BP(e,t,n,r){const o=t[r];if(o instanceof cx){e.propertyTypes.add(o.right.toString());return}if(o instanceof fx){O6(e,o);return}const i=o.toString(),a=zs(n,i);if(!a)throw new Error(`Element definition not found for ${n} ${i}`);let l=!1,c=r+1;if(c<t.length&&t[c]instanceof hx&&(l=!0,c++),a.isArray&&!l&&(e.array=!0),c>=t.length){e.elementDefinitions.push(a);for(const u of a.type)e.propertyTypes.add(u.code);return}for(const u of a.type){let d=u.code;$6(d)&&(d=a.type[0].code),BP(e,t,d,c)}}function O6(e,t){if(t.name==="as"){e.propertyTypes.add(t.args[0].toString());return}if(t.name==="resolve"){e.propertyTypes.add("string");return}if(t.name==="where"&&t.args[0]instanceof dx){e.propertyTypes.add(t.args[0].right.toString());return}throw new Error(`Unhandled FHIRPath function: ${t.name}`)}function $6(e){return e==="Element"||e==="BackboneElement"}function L6(e){return e.split("-").reduce((t,n,r)=>t+(r?Qt(n):n),"")}function F6(e,t){switch(e.type){case"date":return t.size===1&&t.has(U.date)?"DATE":"DATETIME";case"number":return"NUMBER";case"quantity":return"QUANTITY";case"reference":return t.has(U.canonical)?"CANONICAL":"REFERENCE";case"token":return t.size===1&&t.has(U.boolean)?"BOOLEAN":"TEXT";default:return"TEXT"}}function z6(e,t){const n=[],r=zP(t);return Xm(e,r.child,n),n}function Xm(e,t,n){t instanceof FP?(Xm(e,t.left,n),Xm(e,t.right,n)):t.toString().startsWith(e+".")&&n.push(t)}function Gl(e){if(e instanceof cx||e instanceof hx)return[Gl(e.left),e].flat();if(e instanceof Zn)return[e];if(e instanceof ux)return[Gl(e.left),Gl(e.right)].flat();if(e instanceof fx){if(e.name==="where"&&!(e.args[0]instanceof dx))return[];if(e.name==="last")return[]}return[e]}const hh=20;var te=(e=>(e.EQUALS="eq",e.NOT_EQUALS="ne",e.GREATER_THAN="gt",e.LESS_THAN="lt",e.GREATER_THAN_OR_EQUALS="ge",e.LESS_THAN_OR_EQUALS="le",e.STARTS_AFTER="sa",e.ENDS_BEFORE="eb",e.APPROXIMATELY="ap",e.CONTAINS="contains",e.EXACT="exact",e.TEXT="text",e.NOT="not",e.ABOVE="above",e.BELOW="below",e.IN="in",e.NOT_IN="not-in",e.OF_TYPE="of-type",e.MISSING="missing",e.PRESENT="present",e.IDENTIFIER="identifier",e.ITERATE="iterate",e))(te||{});const VP={contains:"contains",exact:"exact",above:"above",below:"below",text:"text",not:"not",in:"in","not-in":"not-in","of-type":"of-type",missing:"missing",identifier:"identifier",iterate:"iterate"},px={eq:"eq",ne:"ne",lt:"lt",le:"le",gt:"gt",ge:"ge",sa:"sa",eb:"eb",ap:"ap"};function UP(e,t){if(!e)throw new Error("Invalid search URL");let n="",r;if(typeof e=="string")if(e.includes("?")){const[a,l]=e.split("?");n=a,r=new URLSearchParams(l)}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 i=[];return r&&i.push(...r.entries()),B6(o,i)}function B6(e,t){const n={resourceType:e};for(const[r,o]of t)V6(n,r,o);return n}function V6(e,t,n){var a,l;let r,o;const i=t.indexOf(":");if(i>=0?(r=t.substring(0,i),o=t.substring(i+1)):(r=t,o=""),r!=="_"){if(r==="_has"||t.includes(".")){e.filters=Tl(e.filters,{code:t,operator:"eq",value:n});return}switch(r){case"_sort":U6(e,n);break;case"_count":e.count=parseInt(n,10);break;case"_offset":e.offset=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=$b(n);o==="iterate"&&(c.modifier="iterate"),e.include=Tl(e.include,c);break}case"_revinclude":{const c=$b(n);o==="iterate"&&(c.modifier="iterate"),e.revInclude=Tl(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=(l=(a=go.types[e.resourceType])==null?void 0:a.searchParams)==null?void 0:l[r];c?e.filters=Tl(e.filters,H6(c,o,n)):e.filters=Tl(e.filters,G6(r,o,n))}}}}function U6(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})}}function H6(e,t,n){if(t==="missing")return{code:e.code,operator:"missing",value:n};switch(e.type){case"number":case"date":case"quantity":return W6(e,n);case"reference":case"string":case"token":case"uri":return q6(e,t,n);default:throw new Error("Unrecognized search parameter type: "+e.type)}}function W6(e,t){const{operator:n,value:r}=Q6(t);return{code:e.code,operator:n,value:r}}function q6(e,t,n){return{code:e.code,operator:K6(t),value:n}}function G6(e,t,n){var o;let r="eq";if(t)r=t;else if(n.length>=2){const i=n.substring(0,2);i in px&&(n.length===2||(o=n.at(2))!=null&&o.match(/\d/))&&(r=i,n=n.substring(i.length))}return{code:e,operator:r,value:n}}function Q6(e){const t=e.substring(0,2),n=px[t];return n?{operator:n,value:e.substring(2)}:{operator:"eq",value:e}}function K6(e){return VP[e]??"eq"}function $b(e){const t=e.split(":");if(t.includes("*"))throw new qe(Ei("'*' is not supported as a value for search inclusion parameters"));if(t.length===1)throw new qe(Ei(`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 qe(Ei(`Invalid include value '${e}'`))}function xa(e){const t=[];return e.fields&&t.push("_fields="+e.fields.join(",")),e.filters&&e.filters.forEach(n=>t.push(Y6(n))),e.sortRules&&e.sortRules.length>0&&t.push(X6(e.sortRules)),e.offset!==void 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.include&&e.include.forEach(n=>t.push(Lb("_include",n))),e.revInclude&&e.revInclude.forEach(n=>t.push(Lb("_revinclude",n))),t.length===0?"":(wc(t),"?"+t.join("&"))}function Y6(e){const t=e.operator in VP?":"+e.operator:"",n=e.operator!=="eq"&&e.operator in px?e.operator:"";return`${e.code}${t}=${n}${encodeURIComponent(e.value)}`}function X6(e){return"_sort="+e.map(t=>t.descending?"-"+t.code:t.code).join(",")}function Lb(e,t){return e+(t.modifier?":"+t.modifier:"")+"="+t.resourceType+":"+t.searchParam+(t.targetType?":"+t.targetType:"")}function mx(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 J6(e,t){if(t.resourceType!==e.resourceType)return!1;if(t.filters){for(const n of t.filters)if(!Z6(e,t,n))return!1}return!0}function Z6(e,t,n){var o,i;const r=(i=(o=go.types[t.resourceType])==null?void 0:o.searchParams)==null?void 0:i[n.code];if(!r)return!1;if(n.operator===te.MISSING||n.operator===te.PRESENT)return eF(e,n,r);switch(r.type){case"reference":return tF(e,n,r);case"string":case"uri":return HP(e,n,r);case"token":return nF(e,n,r);case"date":return sF(e,n,r);default:return!1}}function eF(e,t,n){const o=al(n.expression,e).length>0;return(t.operator===te.MISSING&&t.value==="false"||t.operator===te.PRESENT&&t.value==="true")===o}function tF(e,t,n){const r=al(n.expression,e),o=ph(t.operator);if(t.value===""&&r.length===0)return t.operator===te.EQUALS;const i=r.map(a=>typeof a=="string"?a:a.reference);for(const a of mx(t.value)){let l=i.includes(a);if(!l&&t.code==="_compartment"&&(l=i.some(c=>c==null?void 0:c.endsWith("/"+a))),l)return!o}return o}function nF(e,t,n){return ll(e.resourceType,n).type===Co.BOOLEAN?rF(e,t,n):HP(e,t,n,!0)}function rF(e,t,n){const r=al(n.expression,e),o=t.value==="true",i=r.includes(o);return ph(t.operator)?!i:i}function HP(e,t,n,r){var u,d;const i=(d=(u=ll(e.resourceType,n).elementDefinitions)==null?void 0:u[0].type)==null?void 0:d[0].code,a=al(n.expression,e),l=mx(t.value),c=ph(t.operator);for(const f of a)for(const h of l){let m;if(i===U.Identifier?m=oF(f,t.operator,h):i===U.CodeableConcept?m=iF(f,t.operator,h):m=Jm(f,t.operator,h,r),m)return!c}return c}function Jm(e,t,n,r){if(r&&n.includes("|")){const[i,a]=n.split("|");return Jm(e,t,i,!1)&&(!a||Jm(e,t,a,!1))}let o="";return e&&(typeof e=="string"?o=e:typeof e=="object"&&(o=JSON.stringify(e))),o.toLowerCase().includes(n.toLowerCase())}function oF(e,t,n){var r,o,i;if(n.includes("|")){const[a,l]=n.split("|");return((r=e.system)==null?void 0:r.toLowerCase())===a.toLowerCase()&&((o=e.value)==null?void 0:o.toLowerCase())===l.toLowerCase()}return((i=e.value)==null?void 0:i.toLowerCase())===n.toLowerCase()}function iF(e,t,n){var r,o,i;if(n.includes("|")){const[a,l]=n.split("|");return((r=e.coding)==null?void 0:r.some(c=>{var u,d;return((u=c.system)==null?void 0:u.toLowerCase())===a.toLowerCase()&&((d=c.code)==null?void 0:d.toLowerCase())===l.toLowerCase()}))??!1}return((o=e.text)==null?void 0:o.toLowerCase())===n.toLowerCase()||(((i=e.coding)==null?void 0:i.some(a=>{var l;return((l=a.code)==null?void 0:l.toLowerCase())===n.toLowerCase()}))??!1)}function sF(e,t,n){const r=al(n.expression,e),o=mx(t.value),i=ph(t.operator);for(const a of r)for(const l of o)if(aF(a,t.operator,l))return!i;return i}function aF(e,t,n){switch(t){case te.STARTS_AFTER:case te.GREATER_THAN:return e>n;case te.GREATER_THAN_OR_EQUALS:return e>=n;case te.ENDS_BEFORE:case te.LESS_THAN:return e<n;case te.LESS_THAN_OR_EQUALS:return e<=n;case te.EQUALS:case te.NOT_EQUALS:return e===n;default:return!1}}function ph(e){return e===te.NOT_EQUALS||e===te.NOT}const lF={resourceType:"*"},cF=["DomainConfiguration","JsonWebKey","Login"],uF=["PasswordChangeRequest","UserSecurityRequest","Project","ProjectMembership","User"];var gx=(e=>(e.READ="read",e.VREAD="vread",e.UPDATE="update",e.PATCH="patch",e.DELETE="delete",e.HISTORY="history",e.HISTORY_INSTANCE="history-instance",e.HISTORY_TYPE="history-type",e.HISTORY_SYSTEM="history-system",e.CREATE="create",e.SEARCH="search",e.SEARCH_TYPE="search-type",e.SEARCH_SYSTEM="search-system",e.SEARCH_COMPARTMENT="search-compartment",e.CAPABILITIES="capabilities",e.TRANSACTION="transaction",e.BATCH="batch",e.OPERATION="operation",e))(gx||{});const dF=["read","vread","history","history-instance"];function fF(e,t){if(cF.includes(t))return!1;if(e.resource){for(const n of e.resource)if(qP(n.resourceType,t)&&!n.readonly)return!0}return!1}function WP(e,t,n){if(!n)return lF;if(n.resource){for(const r of n.resource)if(hF(e,t,r))return r}}function hF(e,t,n){var o,i;const r=e.resourceType;return!(!qP(n.resourceType,r)||n.readonly&&!dF.includes(t)||n.compartment&&!((i=(o=e.meta)==null?void 0:o.compartment)!=null&&i.find(a=>{var l;return a.reference===((l=n.compartment)==null?void 0:l.reference)}))||n.criteria&&!J6(e,UP(n.criteria)))}function qP(e,t){return e===t||e==="*"&&!uF.includes(t)}function pF(e){if(typeof window<"u")return window.atob(e);if(typeof Buffer<"u")return Buffer.from(e,"base64").toString("binary");throw new Error("Unable to decode base64")}function mF(e){if(typeof window<"u")return window.btoa(e);if(typeof Buffer<"u")return Buffer.from(e,"binary").toString("base64");throw new Error("Unable to encode base64")}function Fb(){const e=new Uint32Array(28);return crypto.getRandomValues(e),$7(e.buffer)}async function gF(e){return crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))}function GP(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function QP(e){var o,i,a;const t={};e=mo(e);for(const l of e.entry||[]){((o=l.resource)==null?void 0:o.meta)!==void 0&&(delete l.resource.meta.author,delete l.resource.meta.compartment,delete l.resource.meta.lastUpdated,delete l.resource.meta.project,delete l.resource.meta.versionId);const c=(i=l.resource)==null?void 0:i.id;c&&(t[c]=GP(),l.fullUrl="urn:uuid:"+t[c],(a=l.resource)==null||delete a.id)}const n=e.entry,r=JSON.stringify({resourceType:"Bundle",type:"transaction",entry:n==null?void 0:n.map(l=>({fullUrl:l.fullUrl,request:{method:"POST",url:l.resource.resourceType},resource:l.resource}))},(l,c)=>vF(l,c,t),2);return yF(JSON.parse(r))}function vF(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 yF(e){const t=bF(e),{sorted:n,cycles:r}=xF(t),o={};for(const a of e.entry||[])a.fullUrl&&(o[a.fullUrl]=a);const i=n.map(a=>o[a]);for(const a of r)for(const l of a){const c=o[l],u={...c,request:{...c.request,method:"PUT"}};i.push(u)}return{...e,entry:i}}function xF(e){const t=[],n={},r=[];for(const i of Object.keys(e))n[i]=0;function o(i,a){if(n[i]===2)return!0;if(n[i]===1){const c=a.lastIndexOf(i);return c!==-1&&r.push(a.slice(c)),!0}n[i]=1,a.push(i);let l=!1;for(const c of e[i])o(c,a)||(l=!0);return n[i]=2,a.pop(),t.unshift(i),!l}for(const i in e)n[i]===0&&o(i,[]);return{sorted:t,cycles:r}}function KP(e,t){for(const n in e)if(e[n]&&typeof e[n]=="object"){const r=e[n];if(Bs(r)){const o=r.reference;o.startsWith("urn:uuid:")&&t(o)}else KP(r,t)}}function bF(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&&KP(n.resource,o=>{t[o]&&t[o].push(r)})}return t}class YP{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 Jt={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",PNG:"image/png",SCIM_JSON:"application/scim+json",SVG:"image/svg+xml",TEXT:"text/plain",TYPESCRIPT:"text/typescript",PING:"x-application/ping"};class XP{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={}}}class vx{constructor(){this.emitter=new XP}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()}}const Zm={"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"},wF=["Patient","Encounter","ImagingStudy","DiagnosticReport","OperationOutcome","Bundle"],yx=["DiagnosticReport-update"];function SF(e){return yx.includes(e)}function jF(e){if(yx.includes(e))throw new qe(Tt(`'context.version' is required for '${e}'.`))}const CF={"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"},select:{resourceType:"*",isArray:!0}},"DiagnosticReport-update":{report:{resourceType:"DiagnosticReport"},patient:{resourceType:"Patient",optional:!0},study:{resourceType:"ImagingStudy",optional:!0},updates:{resourceType:"Bundle"}},syncerror:{operationoutcome:{resourceType:"OperationOutcome"}}};function EF(e){return wF.includes(e)}function JP(e){return!!e.endpoint}function zb(e){if(!xx(e))throw new qe(Tt("subscriptionRequest must be an object conforming to SubscriptionRequest type."));const{channelType:t,mode:n,topic:r,events:o}=e,i={"hub.channel.type":t,"hub.mode":n,"hub.topic":r,"hub.events":o.join(",")};return JP(e)&&(i.endpoint=e.endpoint),new URLSearchParams(i).toString()}function xx(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 i of o)if(!Zm[i])return!1;return!(JP(e)&&!(typeof e.endpoint=="string"&&e.endpoint.startsWith("ws")))}function Bb(e,t,n,r){if(typeof t!="object")throw new qe(Tt(`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 qe(Tt(`context[${n}] is invalid. Resource must contain a valid string ID.`));if(!t.resourceType)throw new qe(Tt(`context[${n}] is invalid. Resource must contain a resource type. No resource type found.`));const o=r.resourceType;if(o!=="*"){if(!EF(t.resourceType))throw new qe(Tt(`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 qe(Tt(`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.isArray)Bb(e,t.resource,n,r);else{const{resources:i}=t;if(!i)throw new qe(Tt(`context[${n}] is invalid. context[${n}] for the '${e}' with key '${String(t.key)}' should contain an array of resources on the key 'resources'.`));for(const a of i)Bb(e,a,n,r)}}function PF(e,t){const n=new Map,r=CF[e];for(let o=0;o<t.length;o++){const i=t[o].key;if(!r[i])throw new qe(Tt(`Key '${i}' not found for event '${e}'. Make sure to add only valid keys.`));TF(e,t[o],o,r[i],n)}for(const[o,i]of Object.entries(r)){if(!(i.optional||n.has(o)))throw new qe(Tt(`Missing required key '${o}' on context for '${e}' event.`));if(!i.manyAllowed&&(n.get(o)||0)>1)throw new qe(Tt(`${n.get(o)} context entries with key '${o}' found for the '${e}' event when schema only allows for 1.`))}}function Vb(e,t,n,r){if(!(e&&typeof e=="string"))throw new qe(Tt("Must provide a topic."));if(!Zm[t])throw new qe(Tt(`Must provide a valid FHIRcast event name. Supported events: ${Object.keys(Zm).join(", ")}`));if(typeof n!="object")throw new qe(Tt("context must be a context object or array of context objects."));if(yx.includes(t)&&!r)throw new qe(Tt(`The '${t}' event must contain a 'context.versionId'.`));const o=Array.isArray(n)?n:[n];return PF(t,o),{timestamp:new Date().toISOString(),id:GP(),event:{"hub.topic":e,"hub.event":t,context:o,...r?{"context.versionId":r}:{}}}}class kF extends vx{constructor(t){if(super(),this.subRequest=t,!t.endpoint)throw new qe(Tt("Subscription request should contain an endpoint."));if(!xx(t))throw new qe(Tt("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 i=o;i.event["hub.event"]!=="heartbeat"&&(this.dispatchEvent({type:"message",payload:i}),n.send(JSON.stringify({id:o==null?void 0:o.id,timestamp:new Date().toISOString()})))}),n.addEventListener("close",()=>{this.dispatchEvent({type:"disconnect"})})}),this.websocket=n}disconnect(){this.websocket.close()}}function RF(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=pF(t),r=Array.from(n).reduce((i,a)=>{const l=("00"+a.charCodeAt(0).toString(16)).slice(-2);return`${i}%${l}`},""),o=decodeURIComponent(r);return JSON.parse(o)}function _F(e){return e.split(".").length===3}function bx(e){const[t,n,r]=e.split(".");return RF(n)}function DF(e){try{return typeof bx(e).login_id=="string"}catch{return!1}}function IF(e){try{const n=bx(e).exp;return typeof n=="number"?n*1e3:void 0}catch{return}}class AF{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,Jt.TEXT)}async delete(t){await this.medplum.delete(`keyvalue/v1/${t}`)}}var ZP;ZP=Symbol.toStringTag;class Nr{constructor(t){this[ZP]="ReadablePromise",this.status="pending",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 NF{constructor(t){this.storage=t??(typeof localStorage<"u"?localStorage:new MF)}clear(){this.storage.clear()}getString(t){return this.storage.getItem(t)??void 0}setString(t,n){n?this.storage.setItem(t,n):this.storage.removeItem(t)}getObject(t){const n=this.getString(t);return n?JSON.parse(n):void 0}setObject(t,n){this.setString(t,n?lr(n):void 0)}}class MF{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]}}class OF extends vx{constructor(t){super(),this.bufferedAmount=-1/0,this.extensions="NOT_IMPLEMENTED",this.messageBuffer=[];const n=new WebSocket(t);n.addEventListener("open",()=>{if(this.messageBuffer.length){const r=this.messageBuffer;for(const o of r)n.send(o)}this.dispatchEvent(new Event("open"))}),n.addEventListener("error",r=>{this.dispatchEvent(r)}),n.addEventListener("message",r=>{this.dispatchEvent(r)}),n.addEventListener("close",r=>{this.dispatchEvent(r)}),this.ws=n}get readyState(){return this.ws.readyState}close(){this.ws.close()}send(t){if(this.ws.readyState!==WebSocket.OPEN){this.messageBuffer.push(t);return}try{this.ws.send(t)}catch(n){this.dispatchEvent(new ErrorEvent("error",{error:n,message:n.message})),this.messageBuffer.push(t)}}}class eg extends vx{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 $F{constructor(t,n){this.criteria=t,this.emitter=new eg(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}}class LF{constructor(t,n,r){if(!(t instanceof ek))throw new qe(Tt("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new qe(Tt("Not a valid URL"))}const i=r!=null&&r.RobustWebSocket?new r.RobustWebSocket(o):new OF(o);this.medplum=t,this.ws=i,this.masterSubEmitter=new eg,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.setupWebSocketListeners()}setupWebSocketListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,o,i,a,l;try{const c=JSON.parse(n.data),u=(o=(r=c==null?void 0:c.entry)==null?void 0:r[0])==null?void 0:o.resource;if(u.type==="heartbeat"){(i=this.masterSubEmitter)==null||i.dispatchEvent({type:"heartbeat",payload:c});return}(a=this.masterSubEmitter)==null||a.dispatchEvent({type:"message",payload:c});const d=this.criteriaEntriesBySubscriptionId.get(dh(u.subscription));if(!d){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}d.emitter.dispatchEvent({type:"message",payload:c})}catch(c){console.error(c);const u={type:"error",payload:c};(l=this.masterSubEmitter)==null||l.dispatchEvent(u);for(const d of this.getAllCriteriaEmitters())d.dispatchEvent(u)}}),t.addEventListener("error",()=>{var r;const n={type:"error",payload:new qe(pL(new Error("WebSocket error")))};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const o of this.getAllCriteriaEmitters())o.dispatchEvent(n)}),t.addEventListener("close",()=>{var r;const n={type:"close"};this.wsClosed&&((r=this.masterSubEmitter)==null||r.dispatchEvent(n));for(const o of this.getAllCriteriaEmitters())o.dispatchEvent(n)})}emitConnect(t){var r;const n={type:"connect",payload:{subscriptionId:t.subscriptionId}};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const o of this.getAllCriteriaEmitters())o.dispatchEvent(n)}emitError(t,n){var o;const r={type:"error",payload:n};(o=this.masterSubEmitter)==null||o.dispatchEvent(r),t.emitter.dispatchEvent(r)}maybeEmitDisconnect(t){var r;const{subscriptionId:n}=t;if(n){const o={type:"disconnect",payload:{subscriptionId:n}};(r=this.masterSubEmitter)==null||r.dispatchEvent(o),t.emitter.dispatchEvent(o)}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){var a,l;let n=t==null?void 0:t.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${Ct(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=(a=r==null?void 0:r.find(c=>c.name==="token"))==null?void 0:a.valueString,i=(l=r==null?void 0:r.find(c=>c.name==="websocket-url"))==null?void 0:l.valueUrl;if(!o)throw new qe(Tt("Failed to get token"));if(!i)throw new qe(Tt("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(xs(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){var l;const{criteria:n,subscriptionProps:r,subscriptionId:o,token:i}=t;if(!this.criteriaEntries.has(n))return;const a=this.criteriaEntries.get(n);r?a.criteriaWithProps=a.criteriaWithProps.filter(c=>{const u=c.subscriptionProps;return!xs(r,u)}):a.bareCriteria=void 0,!a.bareCriteria&&a.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),(l=this.masterSubEmitter)==null||l._removeCriteria(n)),o&&this.criteriaEntriesBySubscriptionId.delete(o),i&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:i}}))}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 $F(t,n);return this.addCriteriaEntry(o),this.getTokenForCriteria(o).then(([i,a])=>{o.subscriptionId=i,o.token=a,this.criteriaEntriesBySubscriptionId.set(i,o),this.emitConnect(o),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:a}}))}).catch(i=>{console.error(i.message),this.emitError(o,i),this.removeCriteriaEntry(o)}),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))}closeWebSocket(){this.wsClosed||(this.wsClosed=!0,this.ws.close())}getCriteriaCount(){return this.getAllCriteriaEmitters().length}getMasterEmitter(){return this.masterSubEmitter||(this.masterSubEmitter=new eg(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const FF="3.1.10-7ae504bff",zF=Jt.FHIR_JSON+", */*; q=0.1",BF="https://api.medplum.com/",VF=1e3,UF=6e4,HF=0,WF="Binary/",Ub={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]};class ek extends XP{constructor(t){if(super(),this.initComplete=!0,t!=null&&t.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=(t==null?void 0:t.fetch)??qF(),this.storage=(t==null?void 0:t.storage)??new NF,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=AP((t==null?void 0:t.baseUrl)??BF),this.fhirBaseUrl=wo(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=wo(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=wo(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=wo(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),this.clientId=(t==null?void 0:t.clientId)??"",this.clientSecret=(t==null?void 0:t.clientSecret)??"",this.onUnauthenticated=t==null?void 0:t.onUnauthenticated,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?HF:UF),this.cacheTime>0?this.requestCache=new YP((t==null?void 0:t.resourceCacheSize)??VF):this.requestCache=void 0,t!=null&&t.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t!=null&&t.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t!=null&&t.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve()):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t!=null&&t.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0}).catch(console.error)),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}clear(){this.storage.clear(),typeof window<"u"&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){var t;this.storage.setString("activeLogin",void 0),(t=this.requestCache)==null||t.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){var n;t=t.toString(),(n=this.requestCache)==null||n.delete(t)}invalidateAll(){var t;(t=this.requestCache)==null||t.clear()}invalidateSearches(t){const n=wo(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?o=new Promise((a,l)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:a,reject:l}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):o=this.request("GET",t,n);const i=new Nr(o);return this.setCacheEntry(t,i),i}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,Jt.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(window.location.search).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){window.location.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,o,i=!0){let a=o;i&&(a=await this.ensureCodeChallenge(o)),window.location.assign(this.getExternalAuthRedirectUri(t,n,r,a,i))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");const r=new URLSearchParams;return r.set("grant_type","urn:ietf:params:oauth:grant-type:token-exchange"),r.set("subject_token_type","urn:ietf:params:oauth:token-type:access_token"),r.set("client_id",n),r.set("subject_token",t),this.fetchTokens(r)}getExternalAuthRedirectUri(t,n,r,o,i=!0){const a=new URL(t);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",n),a.searchParams.set("redirect_uri",r),a.searchParams.set("scope",o.scope??"openid profile email"),a.searchParams.set("state",JSON.stringify(o)),i){const{codeChallenge:l,codeChallengeMethod:c}=o;if(!c)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!l)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");a.searchParams.set("code_challenge_method",c),a.searchParams.set("code_challenge",l)}return a.toString()}fhirUrl(...t){return new URL(wo(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=H7(n)),r}search(t,n,r){const o=this.fhirSearchUrl(t,n),i="search-"+o.toString(),a=this.getCacheEntry(i,r);if(a)return a.value;const l=new Nr((async()=>{const c=await this.get(o,r);if(c.entry)for(const u of c.entry)this.cacheResource(u.resource);return c})());return this.setCacheEntry(i,l),l}searchOne(t,n,r){const o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();const i="searchOne-"+o.toString(),a=this.getCacheEntry(i,r);if(a)return a.value;const l=new Nr(this.search(t,o.searchParams,r).then(c=>{var u,d;return(d=(u=c.entry)==null?void 0:u[0])==null?void 0:d.resource}));return this.setCacheEntry(i,l),l}searchResources(t,n,r){const i="searchResources-"+this.fhirSearchUrl(t,n).toString(),a=this.getCacheEntry(i,r);if(a)return a.value;const l=new Nr(this.search(t,n,r).then(Cp));return this.setCacheEntry(i,l),l}async*searchResourcePages(t,n,r){var i,a;let o=this.fhirSearchUrl(t,n);for(;o;){const l=new URL(o).searchParams,c=await this.search(t,l,r),u=(i=c.link)==null?void 0:i.find(d=>d.relation==="next");if(!((a=c.entry)!=null&&a.length)&&!u)break;yield Cp(c),o=u!=null&&u.url?new URL(u.url):void 0}}searchValueSet(t,n,r){return this.valueSetExpand({url:t,filter:n},r)}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){var o,i;const r=(i=(o=this.requestCache)==null?void 0:o.get(this.fhirUrl(t,n).toString()))==null?void 0:i.value;return r!=null&&r.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return Ub;const[r,o]=n.split("/");if(!(!r||!o))return this.getCached(r,o)}readResource(t,n,r){return this.get(this.fhirUrl(t,n),r)}readReference(t,n){const r=t.reference;if(!r)return new Nr(Promise.reject(new Error("Missing reference")));if(r==="system")return new Nr(Promise.resolve(Ub));const[o,i]=r.split("/");return!o||!i?new Nr(Promise.reject(new Error("Invalid reference"))):this.readResource(o,i,n)}requestSchema(t){if(xP(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Nr((async()=>{const i=`{
94
94
  StructureDefinitionList(name: "${t}") {
95
95
  resourceType,
96
96
  name,
@@ -513,7 +513,7 @@ Error generating stack: `+i.message+`
513
513
  }
514
514
  }
515
515
  }`.replace(/\s+/g," ")}function jz(e,t){const n=[];return e.data.Patients1&&n.push(...e.data.Patients1),e.data.Patients2&&n.push(...e.data.Patients2),e.data.ServiceRequestList&&n.push(...e.data.ServiceRequestList),Ez(Cz(n),t).slice(0,5)}function Cz(e){const t=new Set,n=[];for(const r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function Ez(e,t){return e.sort((n,r)=>tw(r,t)-tw(n,t))}function tw(e,t){let n=0;if(e.identifier)for(const r of e.identifier)n=Math.max(n,nw(r.value,t));if(e.resourceType==="Patient"&&e.name)for(const r of e.name)n=Math.max(n,nw(Zc(r),t));return n}function nw(e,t){if(!e)return 0;const n=e.toLowerCase().indexOf(t.toLowerCase());return n<0?0:100-n}function Tz(e){var o;const t=vh(),[n,r]=p.useState(!1);return s.jsx(Qn.Header,{p:8,style:{zIndex:101},children:s.jsxs(J,{justify:"space-between",children:[s.jsxs(J,{gap:"xs",children:[s.jsx(vn,{className:Wu.logoButton,onClick:e.navbarToggle,children:e.logo}),!e.headerSearchDisabled&&s.jsx(bz,{pathname:e.pathname,searchParams:e.searchParams})]}),s.jsxs(J,{gap:"lg",pr:"sm",children:[e.notifications,s.jsxs(ne,{width:260,shadow:"xl",position:"bottom-end",transitionProps:{transition:"pop-top-right"},opened:n,onClose:()=>r(!1),children:[s.jsx(ne.Target,{children:s.jsx(vn,{className:rt(Wu.user,{[Wu.userActive]:n}),onClick:()=>r(i=>!i),children:s.jsxs(J,{gap:7,children:[s.jsx(zi,{value:t,radius:"xl",size:24}),s.jsx(he,{size:"sm",className:Wu.userName,children:Zc((o=t==null?void 0:t.name)==null?void 0:o[0])}),s.jsx(ck,{size:12,stroke:1.5})]})})}),s.jsx(ne.Dropdown,{children:s.jsx(pz,{version:e.version})})]})]})]})})}function Pz(e){const t={};for(const n of Array.from(e.elements))n instanceof HTMLInputElement?kz(t,n):n instanceof HTMLTextAreaElement?t[n.name]=n.value:n instanceof HTMLSelectElement&&Rz(t,n);return t}function kz(e,t){t.disabled||(t.type==="checkbox"||t.type==="radio")&&!t.checked||(e[t.name]=t.value)}function Rz(e,t){e[t.name]=t.value}function Ke(e){return s.jsx("form",{style:e.style,"data-testid":e.testid,onSubmit:t=>{t.preventDefault();const n=Pz(t.target);e.onSubmit&&e.onSubmit(n)},children:e.children})}function _z(e){const t=ae(),n=t.getUserConfiguration();function r(o){var d,f;const{menuname:i,bookmarkname:a}=o,l=`${e.pathname}?${e.searchParams.toString()}`,c=mo(n),u=(d=c.menu)==null?void 0:d.find(({title:h})=>h===i);(f=u==null?void 0:u.link)==null||f.push({name:a,target:l}),t.updateResource(c).then(h=>{n.menu=h.menu,t.dispatchEvent({type:"change"}),ye({color:"green",message:"Success"}),e.onOk()}).catch(h=>{ye({color:"red",message:Me(h)})})}return s.jsx(En,{title:"Add Bookmark",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:e.onCancel,children:s.jsx(Ke,{onSubmit:r,children:s.jsxs(Ne,{children:[s.jsx(Dz,{config:n}),s.jsx(me,{label:"Bookmark Name",type:"text",name:"bookmarkname",placeholder:"Bookmark Name",withAsterisk:!0}),s.jsx(J,{justify:"flex-end",children:s.jsx(re,{mt:"sm",type:"submit",children:"OK"})})]})})})}function Dz(e){function t(r){var o;return(o=r==null?void 0:r.menu)==null?void 0:o.map(i=>i.title)}const n=t(e.config);return s.jsx(kt,{name:"menuname",defaultValue:n[0],label:"Select Menu Option",data:n,withAsterisk:!0})}function gk(e){return typeof e.code=="string"?e.code:JSON.stringify(e)}function Iz(e){return typeof e.display=="string"?e.display:gk(e)}function Az(e){return{value:gk(e),label:Iz(e),resource:e}}function Nz(e){return{code:e,display:e}}function Px(e){const t=ae(),{binding:n,creatable:r,clearable:o,expandParams:i,withHelpText:a,...l}=e,c=p.useCallback(async(u,d)=>{var g;if(!n)return[];const h=(g=(await t.valueSetExpand({...i,url:n,filter:u},{signal:d})).expansion)==null?void 0:g.contains,m=[];for(const v of h)v.code&&!m.some(S=>S.code===v.code)&&m.push(v);return m},[t,i,n]);return s.jsx(Tx,{...l,creatable:r??!0,clearable:o??!0,toOption:Az,loadOptions:c,onCreate:Nz,itemComponent:a?Mz:void 0})}const Mz=p.forwardRef(({label:e,resource:t,...n},r)=>s.jsx("div",{ref:r,...n,children:s.jsx(J,{wrap:"nowrap",children:s.jsxs("div",{children:[s.jsx(he,{children:e}),s.jsx(he,{size:"xs",c:"dimmed",children:`${t.system}#${t.code}`})]})})}));function vk(e){const{defaultValue:t,onChange:n,withHelpText:r,...o}=e,[i,a]=p.useState(t);function l(c){const u=c[0],d=$z(u);a(d),n&&n(d)}return s.jsx(Px,{defaultValue:Oz(i),onChange:l,withHelpText:r??!0,...o})}function Oz(e){return e?{code:e}:void 0}function $z(e){return e==null?void 0:e.code}function kx(e){const[t,n]=p.useState(e.defaultValue),r=e.onChange,o=p.useCallback(i=>{n(i),r&&r(i)},[r]);return s.jsx(vk,{disabled:e.disabled,"data-autofocus":e.autoFocus,"data-testid":e.testId,defaultValue:t,onChange:o,name:e.name,placeholder:e.placeholder,binding:"https://medplum.com/fhir/ValueSet/resource-types",creatable:!1,maxValues:e.maxValues??1,clearable:!1,withHelpText:!1})}const Lz="_menuTitle_9g6l5_1",Fz="_link_9g6l5_9",zz="_linkActive_9g6l5_38",og={menuTitle:Lz,link:Fz,linkActive:zz};function Bz(e){var l;const t=gh(),n=Hz(e.pathname,e.searchParams,e.menus),[r,o]=p.useState(!1);function i(c,u){c.stopPropagation(),c.preventDefault(),t(u),window.innerWidth<768&&e.closeNavbar()}function a(c){c&&t(`/${c}`)}return s.jsxs(s.Fragment,{children:[s.jsx(Qn.Navbar,{children:s.jsxs(kr,{p:"xs",children:[!e.resourceTypeSearchDisabled&&s.jsx(Qn.Section,{mb:"sm",children:s.jsx(kx,{name:"resourceType",placeholder:"Resource Type",maxValues:0,onChange:c=>a(c)},window.location.pathname)}),s.jsxs(Qn.Section,{grow:!0,children:[(l=e.menus)==null?void 0:l.map(c=>{var u;return s.jsxs(p.Fragment,{children:[s.jsx(he,{className:og.menuTitle,children:c.title}),(u=c.links)==null?void 0:u.map(d=>s.jsxs(Vz,{to:d.href,active:d.href===(n==null?void 0:n.href),onClick:f=>i(f,d.href),children:[s.jsx(Uz,{to:d.href,icon:d.icon}),s.jsx("span",{children:d.label})]},d.href))]},`menu-${c.title}`)}),e.displayAddBookmark&&s.jsx(re,{variant:"subtle",size:"xs",mt:"xl",leftSection:s.jsx(W8,{size:"0.75rem"}),onClick:()=>o(!0),children:"Add Bookmark"})]})]})}),e.pathname&&e.searchParams&&s.jsx(_z,{pathname:e.pathname,searchParams:e.searchParams,visible:r,onOk:()=>o(!1),onCancel:()=>o(!1)})]})}function Vz(e){return s.jsx(Ge,{onClick:e.onClick,to:e.to,className:rt(og.link,{[og.linkActive]:e.active}),children:e.children})}function Uz(e){return e.icon?e.icon:s.jsx(lh,{w:30})}function Hz(e,t,n){if(!e||!t||!n)return;let r,o=0;for(const i of n)if(i.links)for(const a of i.links){const l=Wz(e,t,a.href);l>o&&(o=l,r=a)}return r}function Wz(e,t,n){const r=new URL(n,"https://example.com");if(e!==r.pathname)return 0;const o=["_count","_offset"];for(const[a,l]of r.searchParams.entries())if(!o.includes(a)&&t.get(a)!==l)return 0;let i=1;for(const[a,l]of t.entries())o.includes(a)||r.searchParams.get(a)===l&&i++;return i}function qz(e){const[t,n]=p.useState(localStorage.navbarOpen==="true"),r=ae(),o=vh();p.useEffect(()=>{function c(){ye({color:"red",message:"No connection to server",autoClose:!1})}return r.addEventListener("offline",c),()=>r.removeEventListener("offline",c)},[r]);function i(c){localStorage.navbarOpen=c.toString(),n(c)}function a(){i(!1)}function l(){i(!t)}return r.isLoading()?s.jsx(qr,{}):s.jsxs(Qn,{header:{height:60},navbar:{width:250,breakpoint:"sm",collapsed:{desktop:!o||!t,mobile:!o||!t}},padding:0,children:[o&&s.jsx(Tz,{pathname:e.pathname,searchParams:e.searchParams,headerSearchDisabled:e.headerSearchDisabled,logo:e.logo,version:e.version,navbarToggle:l,notifications:e.notifications}),o&&t?s.jsx(Bz,{pathname:e.pathname,searchParams:e.searchParams,menus:e.menus,closeNavbar:a,displayAddBookmark:e.displayAddBookmark,resourceTypeSearchDisabled:e.resourceTypeSearchDisabled}):void 0,s.jsx(Qn.Main,{className:oz.main,children:s.jsx(pk,{children:s.jsx(p.Suspense,{fallback:s.jsx(qr,{}),children:e.children})})})]})}function ru(e){const{contentType:t,url:n,title:r}=e.value??{},o=ik(n);return o?s.jsxs("div",{"data-testid":"attachment-display",children:[(t==null?void 0:t.startsWith("image/"))&&s.jsx("img",{"data-testid":"attachment-image",style:{maxWidth:e.maxWidth},src:o,alt:r}),(t==null?void 0:t.startsWith("video/"))&&s.jsx("video",{"data-testid":"attachment-video",style:{maxWidth:e.maxWidth},controls:!0,children:s.jsx("source",{type:t,src:o})}),t==="application/pdf"&&s.jsx("div",{"data-testid":"attachment-pdf",style:{maxWidth:e.maxWidth,minHeight:400},children:s.jsx("iframe",{width:"100%",height:"400",src:o+"#navpanes=0",allowFullScreen:!0,frameBorder:0,seamless:!0})}),s.jsx("div",{"data-testid":"download-link",style:{padding:"2px 16px 16px 16px"},children:s.jsx(Ze,{href:n,"data-testid":"attachment-details",target:"_blank",rel:"noopener noreferrer",download:Gz(r),children:r||"Download"})})]}):null}function Gz(e){return e!=null&&e.includes(".")?e:void 0}const Qz="_root_17n8t_1",Kz="_compact_17n8t_25",rw={root:Qz,compact:Kz};function Rx(e){const{children:t,compact:n}=e;return s.jsx("dl",{className:rt(rw.root,{[rw.compact]:n}),children:t})}function Ro(e){return s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:e.term}),s.jsx("dd",{children:e.children})]})}function Yz(e){var r;const t=(r=e.values)==null?void 0:r.map((o,i)=>s.jsx("div",{children:s.jsx(ru,{value:o,maxWidth:e.maxWidth})},"attatchment-"+i));let n;if(e.includeDescriptionListEntry){if(e.property===void 0)throw new Error("props.property is required when includeDescriptionListEntry is true");if(!Ot(e.path))throw new Error("props.path is required when includeDescriptionListEntry is true");const o=e.path.split(".").pop();n=s.jsx(Ro,{term:bs(o),children:t})}else n=s.jsx(s.Fragment,{children:t});return n}function _x(e){const t=ae(),n=p.useRef(null);function r(a){var l;dt(a),(l=n.current)==null||l.click()}function o(a){dt(a);const l=a.target.files;l&&Array.from(l).forEach(i)}function i(a){!a||!a.name||(e.onUploadStart&&e.onUploadStart(),t.createAttachment({data:a,contentType:a.type||"application/octet-stream",filename:a.name,securityContext:e.securityContext,onProgress:e.onUploadProgress}).then(c=>e.onUpload(c)).catch(c=>{e.onUploadError&&e.onUploadError(vt(c))}))}return s.jsxs(s.Fragment,{children:[s.jsx("input",{disabled:e.disabled,type:"file","data-testid":"upload-file-input",style:{display:"none"},ref:n,onChange:a=>o(a)}),e.children({onClick:r,disabled:e.disabled})]})}function Xz(e){const[t,n]=p.useState(e.defaultValue??[]),r=p.useRef();r.current=t;function o(i){n(i),e.onChange&&e.onChange(i)}return s.jsxs("table",{style:{width:"100%"},children:[s.jsxs("colgroup",{children:[s.jsx("col",{width:"97%"}),s.jsx("col",{width:"3%"})]}),s.jsxs("tbody",{children:[t.map((i,a)=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx(ru,{value:i,maxWidth:200})}),s.jsx("td",{children:s.jsx(nn,{disabled:e.disabled,title:"Remove",variant:"subtle",size:"sm",color:"gray",onClick:l=>{dt(l);const c=t.slice();c.splice(a,1),o(c)},children:s.jsx(Xd,{})})})]},`${a}-${t.length}`)),s.jsxs("tr",{children:[s.jsx("td",{}),s.jsx("td",{children:s.jsx(_x,{disabled:e.disabled,onUpload:i=>{o([...r.current,i])},children:i=>s.jsx(nn,{...i,title:"Add",variant:"subtle",size:"sm",color:i.disabled?"gray":"green",children:s.jsx(Sx,{})})})})]})]})]})}function yk(e){const[t,n]=p.useState(e.defaultValue);function r(o){n(o),e.onChange&&e.onChange(o)}return t?s.jsxs(s.Fragment,{children:[s.jsx(ru,{value:t,maxWidth:200}),s.jsx(re,{disabled:e.disabled,onClick:o=>{dt(o),r(void 0)},children:"Remove"})]}):s.jsx(_x,{disabled:e.disabled,securityContext:e.securityContext,onUpload:r,children:o=>s.jsx(re,{...o,children:"Upload..."})})}function fo(e){return s.jsx(s.Fragment,{children:Di(e.value)})}function Jz(e){return s.jsx(s.Fragment,{children:Fs(e.value)})}function xk(e){const t=e.value;if(!t)return null;const n=[];return t.value&&n.push(t.value),(t.use||t.system)&&(n.push(" ["),t.use&&n.push(t.use),t.use&&t.system&&n.push(" "),t.system&&n.push(t.system),n.push("]")),s.jsx(s.Fragment,{children:n.join("").trim()})}function Zz(e){var n;const t=e.value;return t?s.jsxs(s.Fragment,{children:[t.name,t.name&&": ",(n=t.telecom)==null?void 0:n.map(r=>s.jsx(xk,{value:r},`telecom-${t.name}-${r.value}`))]}):null}function eB(e){var t,n;return s.jsxs("div",{children:[(t=e.value)==null?void 0:t.system,": ",(n=e.value)==null?void 0:n.value]})}function tB(e){return s.jsx(s.Fragment,{children:Z7(e.value)})}function Ec(e){return s.jsx(s.Fragment,{children:li(e.value)})}function Dx(e){return s.jsx(s.Fragment,{children:Sc(e.value)})}function nB(e){const t=e.value;return t?s.jsxs(s.Fragment,{children:[s.jsx(Ec,{value:t.numerator})," / ",s.jsx(Ec,{value:t.denominator})]}):null}function ef(e){if(!e.value)return null;const t=e.value.display||e.value.reference||lr(e.value);return e.link!==!1&&e.value.reference?s.jsx(Ge,{to:e.value,children:t}):s.jsx(s.Fragment,{children:t})}function bk(e,t,n,r){if(!Ot(n==null?void 0:n.slices))return[e];const o=new Array(t.length+1);for(let i=0;i<o.length;i++)o[i]=[];for(const i of e){const a=nk(i,t,n.discriminator,r);let l=a?t.findIndex(c=>c.name===a):-1;l===-1&&(l=t.length),o[l].push(i)}return o}async function wk({medplum:e,property:t}){return new Promise((n,r)=>{var l,c;if(!t.slicing){n([]);return}const o=[],i=[],a=[];for(const u of t.slicing.slices){if(!tk(u)){console.debug("Unsupported slice definition",u);continue}let d;Ot(u.elements)||(d=(c=(l=u.type[0])==null?void 0:l.profile)==null?void 0:c[0]),o.push(u),i.push(d),d?a.push(e.requestProfileSchema(d)):a.push(Promise.resolve([]))}Promise.all(a).then(()=>{for(let u=0;u<o.length;u++){const d=o[u],f=i[u];if(f){const h=Ls(f);d.typeSchema=h}}n(o)}).catch(r)})}function yh(e,t,n){return t!==void 0?s.jsx(e,{value:t,children:n}):n}function rB(e){var a,l;const{slice:t,property:n}=e,r=((a=t.typeSchema)==null?void 0:a.elements)??t.elements,o=p.useContext(yt),i=p.useMemo(()=>{var c;if(Ot(r))return Wa({parentContext:o,elements:r,path:e.path,profileUrl:(c=t.typeSchema)==null?void 0:c.url})},[o,e.path,(l=t.typeSchema)==null?void 0:l.url,r]);return yh(yt.Provider,i,s.jsx(s.Fragment,{children:e.value.map((c,u)=>s.jsx("div",{children:s.jsx(Gr,{property:n,path:e.path,arrayElement:!0,elementDefinitionType:t.type[0],propertyType:t.type[0].code,value:c,ignoreMissingValues:e.ignoreMissingValues,link:e.link})},`${u}-${e.value.length}`))}))}function oB(e){var g;const{property:t,propertyType:n}=e,r=ae(),o=p.useMemo(()=>Array.isArray(e.values)?e.values:[],[e.values]),[i,a]=p.useState(!0),[l,c]=p.useState([]),[u,d]=p.useState(()=>[o]),f=p.useContext(yt);if(p.useEffect(()=>{wk({medplum:r,property:t}).then(v=>{c(v);const S=bk(o,v,t.slicing,f.profileUrl);d(S),a(!1)}).catch(v=>{console.error(v),a(!1)})},[r,t,f.profileUrl,d,o]),i)return s.jsx("div",{children:"Loading..."});let h;if(((g=t.type[0])==null?void 0:g.code)!=="Extension"){const v=u[l.length],S=v.map((y,b)=>s.jsx("div",{children:s.jsx(Gr,{path:e.path,arrayElement:!0,property:t,propertyType:n,value:y,ignoreMissingValues:e.ignoreMissingValues,link:e.link})},`${b}-${v.length}`));if(e.includeDescriptionListEntry){if(!Ot(e.path))throw new Error("props.path is required when includeDescriptionListEntry is true");const y=e.path.split(".").pop();h=s.jsx(Ro,{term:bs(y),children:S})}else h=s.jsx(s.Fragment,{children:S})}return s.jsxs(s.Fragment,{children:[l.map((v,S)=>{if(!e.path)throw Error(`Displaying a resource property with slices of type ${e.propertyType} requires path`);let y=s.jsx(rB,{path:e.path,slice:v,property:t,value:u[S],ignoreMissingValues:e.ignoreMissingValues,link:e.link},v.name);return e.includeDescriptionListEntry&&(y=s.jsx(Ro,{term:bs(v.name),children:y},v.name)),y}),h]})}function ou(e,t,n){const r=pn(e,t,{profileUrl:n});return r?Array.isArray(r)?[r.map(o=>o.value),r[0].type]:[r.value,r.type]:[void 0,"undefined"]}function iB(e,t,n){const r=SP(e,t,n);return r?Array.isArray(r)?[r.map(o=>o.value),r[0].type]:[r.value,r.type]:[void 0,"undefined"]}function sB(e){const{elementDefinitionType:t}=e,n=ae(),r=p.useContext(yt),[o,i]=p.useState(bP("Extension")),a=p.useMemo(()=>{if(Ot(t==null?void 0:t.profile))return t.profile[0]},[t]),[l,c]=p.useState(a!==void 0);if(p.useEffect(()=>{a&&(c(!0),n.requestProfileSchema(a).then(()=>{const f=Ls(a);c(!1),f&&i(f)}).catch(f=>{c(!1),console.warn(f)}))},[n,a]),a&&(l||!rx(a)))return s.jsx("div",{children:"Loading..."});const u=o.elements["value[x]"];if((u==null?void 0:u.max)!==0){const[f,h]=ou({type:"Extension",value:e.value},"value[x]",a??r.profileUrl);return s.jsx(Gr,{propertyType:h,value:f})}return s.jsx(tf,{path:e.path,value:{type:o.name,value:e.value},compact:e.compact,ignoreMissingValues:e.ignoreMissingValues,link:e.link,profileUrl:a})}function Gr(e){var i;const{property:t,propertyType:n,value:r}=e;if((i=t==null?void 0:t.path)==null?void 0:i.endsWith(".id"))return s.jsxs(W,{component:"div",style:{display:"flex",gap:3,alignItems:"center"},children:[r,!Bt(r)&&s.jsx(xT,{value:r,timeout:2e3,children:({copied:a,copy:l})=>s.jsx(Ms,{label:a?"Copied":"Copy",withArrow:!0,position:"right",children:s.jsx(nn,{variant:"subtle",color:a?"teal":"gray",onClick:l,children:a?s.jsx(eu,{size:"1rem"}):s.jsx(uk,{size:"1rem"})})})})]});if(t&&(t.isArray||t.max>1)&&!e.arrayElement)return n===U.Attachment?s.jsx(Yz,{values:r,maxWidth:e.maxWidth,includeDescriptionListEntry:e.includeArrayDescriptionListEntry,property:t,path:e.path}):s.jsx(oB,{path:e.path,property:t,propertyType:n,values:r,includeDescriptionListEntry:e.includeArrayDescriptionListEntry,ignoreMissingValues:e.ignoreMissingValues,link:e.link});switch(n){case U.boolean:return s.jsx(s.Fragment,{children:r===void 0?"":(!!r).toString()});case U.SystemString:case U.string:return s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:r});case U.code:case U.date:case U.decimal:case U.id:case U.integer:case U.positiveInt:case U.unsignedInt:case U.uri:case U.url:return s.jsx(s.Fragment,{children:r});case U.canonical:return s.jsx(ef,{value:{reference:r},link:e.link});case U.dateTime:case U.instant:return s.jsx(s.Fragment,{children:Mn(r)});case U.markdown:return s.jsx("pre",{children:r});case U.Address:return s.jsx(l8,{value:r});case U.Annotation:return s.jsx(s.Fragment,{children:r==null?void 0:r.text});case U.Attachment:return s.jsx(ru,{value:r,maxWidth:e.maxWidth});case U.CodeableConcept:return s.jsx(fo,{value:r});case U.Coding:return s.jsx(Jz,{value:r});case U.ContactDetail:return s.jsx(Zz,{value:r});case U.ContactPoint:return s.jsx(xk,{value:r});case U.HumanName:return s.jsx(Ex,{value:r});case U.Identifier:return s.jsx(eB,{value:r});case U.Money:return s.jsx(tB,{value:r});case U.Period:return s.jsx(s.Fragment,{children:Q7(r)});case U.Quantity:case U.Duration:return s.jsx(Ec,{value:r});case U.Range:return s.jsx(Dx,{value:r});case U.Ratio:return s.jsx(nB,{value:r});case U.Reference:return s.jsx(ef,{value:r,link:e.link});case U.Timing:return s.jsx(s.Fragment,{children:MP(r)});case U.Dosage:case U.UsageContext:if(!e.path)throw Error(`Displaying property of type ${e.propertyType} requires path`);return s.jsx(tf,{path:e.path,value:{type:n,value:r},compact:!0,ignoreMissingValues:e.ignoreMissingValues});case U.Extension:if(!e.path)throw Error(`Displaying property of type ${e.propertyType} requires path`);return s.jsx(sB,{path:e.path,value:r,compact:!0,ignoreMissingValues:e.ignoreMissingValues,elementDefinitionType:e.elementDefinitionType});default:if(!t)throw Error(`Displaying property of type ${e.propertyType} requires element schema`);if(!e.path)throw Error(`Displaying property of type ${e.propertyType} requires path`);return s.jsx(tf,{path:e.path,value:{type:t.type[0].code,value:r},compact:!0,ignoreMissingValues:e.ignoreMissingValues})}}const Sk=["extension","modifierExtension"],aB=ak.filter(e=>!Sk.includes(e));function tf(e){const t=e.value,{value:n,type:r}=t,o=p.useContext(yt),i=e.profileUrl??(o==null?void 0:o.profileUrl),a=p.useMemo(()=>uh(r,i),[i,r]),l=p.useMemo(()=>{if(a)return Wa({parentContext:o,elements:a.elements,path:e.path,profileUrl:a.url,accessPolicyResource:e.accessPolicyResource})},[a,o,e.path,e.accessPolicyResource]);if(Bt(n))return null;if(!a)return s.jsxs("div",{children:[r," not implemented"]});if(typeof n=="object"&&"name"in n&&Object.keys(n).length===1&&typeof n.name=="string")return s.jsx("div",{children:n.name});const c=l??o;return yh(yt.Provider,l,s.jsx(Rx,{compact:e.compact,children:Object.entries(c.elements).map(([u,d])=>{var v;if(Sk.includes(u)&&Bt((v=d.slicing)==null?void 0:v.slices))return null;if(aB.includes(u))return null;if(lk.includes(u)&&d.path.split(".").length===2||u.includes("."))return null;const[f,h]=ou(t,u,c.profileUrl);if((e.ignoreMissingValues||d.max===0)&&Bt(f)||e.path.endsWith(".extension")&&(u==="url"||u==="id"))return null;const m=d.max>1||d.isArray,g=s.jsx(Gr,{property:d,propertyType:h,path:e.path+"."+u,value:f,ignoreMissingValues:e.ignoreMissingValues,includeArrayDescriptionListEntry:m,link:e.link},u);return m?g:s.jsx(Ro,{term:bs(u),children:g},u)})}))}const jk="Read Only";function Ck(e,t){return e?s.jsx(Ms.Floating,{label:e,children:t}):t}const lB="_dimmed_1pxw4_1",Ek={dimmed:lB};function Tk(e){const{debugMode:t}=p.useContext(yt);let n;return t&&e.fhirPath?n=`${e.title} - ${e.fhirPath}`:n=e.title,Ck(e!=null&&e.readonly?jk:void 0,s.jsxs(J,{wrap:"nowrap","data-testid":e.testId,children:[s.jsx("div",{children:e.children}),s.jsx("div",{children:s.jsx(It.Wrapper,{id:e.htmlFor,label:n,classNames:{label:e!=null&&e.readonly?Ek.dimmed:void 0},description:e.description,withAsterisk:e.withAsterisk,children:null})})]}))}function Xe(e,t){var n,r,o;return(o=(r=(n=e==null?void 0:e.issue)==null?void 0:n.filter(i=>{var a;return Pk((a=i.expression)==null?void 0:a[0],t)}))==null?void 0:r.map(i=>{var a;return(a=i.details)==null?void 0:a.text}))==null?void 0:o.join(`
516
- `)}function iu(e,t){var n;return(n=e==null?void 0:e.issue)==null?void 0:n.filter(r=>{var o;return Pk((o=r.expression)==null?void 0:o[0],t)})}const qu=/\[\d+\]/;function Pk(e,t){const n=typeof e=="string"&&qu.test(e),r=typeof t=="string"&&qu.test(t);if(n!==r&&(e=e==null?void 0:e.replace(qu,""),t=t==null?void 0:t.replace(qu,"")),e===t)return!0;if(!e||!t)return!1;const o=e.indexOf(".");if(o>=0&&e.substring(o+1)===t)return!0;const i=t.indexOf(".");return i>=0&&t.substring(i+1)===e}function mt(e){const{debugMode:t}=p.useContext(yt);let n;return t&&e.fhirPath?n=`${e.title} - ${e.fhirPath}`:n=e.title,Ck(e!=null&&e.readonly?jk:void 0,s.jsx(It.Wrapper,{id:e.htmlFor,label:n,classNames:{label:e!=null&&e.readonly?Ek.dimmed:void 0},description:e.description,withAsterisk:e.withAsterisk,error:Xe(e.outcome,e.errorExpression??e.htmlFor),"data-testid":e.testId,children:e.children}))}function kk(e,t,n,r,o){const i=r.type;if(i.length>1)for(const a of i){const l=t.replace("[x]",Qt(a.code));l in e&&delete e[l]}return e[n]=o,e}function cB(e){return!!e&&!Bt(e.url)&&!Bt(e.name)}function uB(e){const{defaultValue:t,onChange:n,withHelpText:r,outcome:o,path:i,valuePath:a,...l}=e,[c,u]=p.useState(t);function d(f){const h=fB(f);u(h),n&&n(h)}return s.jsx(Px,{defaultValue:c&&dB(c),onChange:d,withHelpText:r??!0,...l})}function dB(e){var t;return(t=e.coding)==null?void 0:t.map(n=>({system:n.system,code:n.code,display:n.display}))}function fB(e){if(e.length!==0)return{coding:e.map(t=>({system:t.system,code:t.code,display:t.display}))}}function Rk(e){const{defaultValue:t,onChange:n,withHelpText:r,...o}=e,[i,a]=p.useState(t);function l(c){const u=c[0],d=u&&pB(u);a(d),n&&n(d)}return s.jsx(Px,{defaultValue:i&&hB(i),maxValues:1,onChange:l,withHelpText:r??!0,...o})}function hB(e){return{system:e.system,code:e.code,display:e.display}}function pB(e){return{system:e.system,code:e.code,display:e.display}}function _k(e){const{path:t,outcome:n}=e,{elementsByPath:r,getExtendedProps:o}=p.useContext(yt),[i,a]=p.useState(e.defaultValue),l=p.useRef();l.current=i;const[c,u,d]=p.useMemo(()=>["system","use","value"].map(x=>r[t+"."+x]),[r,t]),[f,h,m]=p.useMemo(()=>["system","use","value"].map(x=>o(t+"."+x)),[o,t]);function g(x){x&&Object.keys(x).length===0&&(x=void 0),a(x),e.onChange&&e.onChange(x)}function v(x){const w={...l.current,system:x};x||delete w.system,g(w)}function S(x){const w={...l.current,use:x};x||delete w.use,g(w)}function y(x){const w={...l.current,value:x};x||delete w.value,g(w)}const b=e.valuePath??t;return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[s.jsx(kt,{disabled:e.disabled||(f==null?void 0:f.readonly),"data-testid":"system",defaultValue:i==null?void 0:i.system,required:((c==null?void 0:c.min)??0)>0,onChange:x=>v(x.currentTarget.value),data:["","email","phone","fax","pager","sms","other"],error:Xe(n,b+".system")}),s.jsx(kt,{disabled:e.disabled||(h==null?void 0:h.readonly),"data-testid":"use",defaultValue:i==null?void 0:i.use,required:((u==null?void 0:u.min)??0)>0,onChange:x=>S(x.currentTarget.value),data:["","home","work","temp","old","mobile"],error:Xe(n,b+".use")}),s.jsx(me,{disabled:e.disabled||(m==null?void 0:m.readonly),placeholder:"Value",defaultValue:i==null?void 0:i.value,required:((d==null?void 0:d.min)??0)>0,onChange:x=>y(x.currentTarget.value),error:Xe(n,b+".value")})]})}function mB(e){var d;const[t,n]=p.useState(e.defaultValue),r=p.useRef();r.current=t;const{getExtendedProps:o}=p.useContext(yt),[i,a]=p.useMemo(()=>["name","telecom"].map(f=>o(e.path+"."+f)),[o,e.path]);function l(f){n(f),e.onChange&&e.onChange(f)}function c(f){const h={...r.current,name:f};f||delete h.name,l(h)}function u(f){const h={...r.current,telecom:f&&[f]};f||delete h.telecom,l(h)}return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(me,{disabled:e.disabled||(i==null?void 0:i.readonly),"data-testid":e.name+"-name",name:e.name+"-name",placeholder:"Name",style:{width:180},defaultValue:t==null?void 0:t.name,onChange:f=>c(f.currentTarget.value)}),s.jsx(_k,{disabled:e.disabled||(a==null?void 0:a.readonly),name:e.name+"-telecom",path:e.path+".telecom",defaultValue:(d=t==null?void 0:t.telecom)==null?void 0:d[0],onChange:u,outcome:e.outcome})]})}function gB(e){if(!e)return"";const t=new Date(e);return fh(t)?t.toLocaleDateString("sv")+"T"+t.toLocaleTimeString("sv"):""}function Dk(e){if(!e)return"";const t=new Date(e);return fh(t)?t.toISOString():""}var vB={MEDPLUM_BASE_URL:"__MEDPLUM_BASE_URL__",MEDPLUM_CLIENT_ID:"__MEDPLUM_CLIENT_ID__",GOOGLE_CLIENT_ID:"__GOOGLE_CLIENT_ID__",RECAPTCHA_SITE_KEY:"__RECAPTCHA_SITE_KEY__",MEDPLUM_REGISTER_ENABLED:"__MEDPLUM_REGISTER_ENABLED__",MEDPLUM_VERSION:"3.1.9-eb1d4ee09",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function ws(e){return s.jsx(me,{id:e.name,name:e.name,label:e.label,"data-autofocus":e.autoFocus,"data-testid":e["data-testid"]??e.name,placeholder:e.placeholder,required:e.required,disabled:e.disabled,type:yB(),defaultValue:gB(e.defaultValue),autoFocus:e.autoFocus,error:Xe(e.outcome,e.name),onChange:t=>{if(e.onChange){const n=t.currentTarget.value;e.onChange(Dk(n))}}})}function yB(){return vB.NODE_ENV==="test"?"text":"datetime-local"}function xB(e){const{propertyType:t}=e,n=ae(),[r,o]=p.useState(),i=p.useMemo(()=>{if(Ot(t.profile))return t.profile[0]},[t]),[a,l]=p.useState(i!==void 0);return p.useEffect(()=>{i&&(l(!0),n.requestProfileSchema(i).then(()=>{const c=Ls(i);l(!1),o(c)}).catch(c=>{l(!1),console.warn(c)}))},[n,i]),i&&(a||!rx(i))?s.jsx("div",{children:"Loading..."}):s.jsx(Nx,{profileUrl:i,path:e.path,typeName:(r==null?void 0:r.name)??"Extension",defaultValue:e.defaultValue,onChange:e.onChange})}function bB(e){var b,x,w;const{outcome:t,path:n}=e,[r,o]=p.useState(e.defaultValue),{getExtendedProps:i}=p.useContext(yt),[a,l,c,u,d]=p.useMemo(()=>["use","prefix","given","family","suffix"].map(j=>i(e.path+"."+j)),[i,e.path]);function f(j){o(j),e.onChange&&e.onChange(j)}function h(j){f({...r,use:j||void 0})}function m(j){f({...r,prefix:j?j.split(" "):void 0})}function g(j){f({...r,given:j?j.split(" "):void 0})}function v(j){f({...r,family:j||void 0})}function S(j){f({...r,suffix:j?j.split(" "):void 0})}const y=e.valuePath??n;return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(kt,{disabled:e.disabled||(a==null?void 0:a.readonly),defaultValue:r==null?void 0:r.use,name:e.name+"-use","data-testid":"use",onChange:j=>h(j.currentTarget.value),data:["","temp","old","usual","official","nickname","anonymous","maiden"],error:Xe(t,y+".use")}),s.jsx(me,{disabled:e.disabled||(l==null?void 0:l.readonly),placeholder:"Prefix",name:e.name+"-prefix",defaultValue:(b=r==null?void 0:r.prefix)==null?void 0:b.join(" "),onChange:j=>m(j.currentTarget.value),error:Xe(t,y+".prefix")}),s.jsx(me,{disabled:e.disabled||(c==null?void 0:c.readonly),placeholder:"Given",name:e.name+"-given",defaultValue:(x=r==null?void 0:r.given)==null?void 0:x.join(" "),onChange:j=>g(j.currentTarget.value),error:Xe(t,y+".given")}),s.jsx(me,{disabled:e.disabled||(u==null?void 0:u.readonly),name:e.name+"-family",placeholder:"Family",defaultValue:r==null?void 0:r.family,onChange:j=>v(j.currentTarget.value),error:Xe(t,y+".family")}),s.jsx(me,{disabled:e.disabled||(d==null?void 0:d.readonly),placeholder:"Suffix",name:e.name+"-suffix",defaultValue:(w=r==null?void 0:r.suffix)==null?void 0:w.join(" "),onChange:j=>S(j.currentTarget.value),error:Xe(t,y+".suffix")})]})}function wB(e){const[t,n]=p.useState(e.defaultValue),{elementsByPath:r,getExtendedProps:o}=p.useContext(yt),[i,a]=p.useMemo(()=>["system","value"].map(f=>r[e.path+"."+f]),[r,e.path]),[l,c]=p.useMemo(()=>["system","value"].map(f=>o(e.path+"."+f)),[o,e.path]);function u(f){n(f),e.onChange&&e.onChange(f)}const d=e.valuePath??e.path;return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[s.jsx(me,{disabled:e.disabled||(l==null?void 0:l.readonly),placeholder:"System",required:((i==null?void 0:i.min)??0)>0,defaultValue:t==null?void 0:t.system,onChange:f=>u({...t,system:f.currentTarget.value}),error:Xe(e.outcome,d+".system")}),s.jsx(me,{disabled:e.disabled||(c==null?void 0:c.readonly),placeholder:"Value",required:((a==null?void 0:a.min)??0)>0,defaultValue:t==null?void 0:t.value,onChange:f=>u({...t,value:f.currentTarget.value}),error:Xe(e.outcome,d+".value")})]})}const SB=["USD","EUR","CAD","GBP","AUD"];function jB(e){var f;const{onChange:t}=e,[n,r]=p.useState(e.defaultValue),{getExtendedProps:o}=p.useContext(yt),[i,a]=p.useMemo(()=>["currency","value"].map(h=>o(e.path+"."+h)),[o,e.path]),l=p.useCallback(h=>{r(h),t&&t(h)},[t]),c=p.useCallback(h=>{l({...n,currency:h.currentTarget.value})},[n,l]),u=p.useCallback(h=>{l({...n,value:h.currentTarget.valueAsNumber})},[n,l]),d=s.jsx(kt,{disabled:e.disabled||(i==null?void 0:i.readonly),defaultValue:n==null?void 0:n.currency,data:SB,styles:{input:{fontWeight:500,borderTopLeftRadius:0,borderBottomLeftRadius:0,width:92}},onChange:c});return s.jsx(me,{disabled:e.disabled||(a==null?void 0:a.readonly),type:"number",name:e.name,label:e.label,placeholder:e.placeholder??"Value",defaultValue:((f=n==null?void 0:n.value)==null?void 0:f.toString())??"USD",leftSection:s.jsx(P8,{size:14}),rightSection:d,rightSectionWidth:92,onChange:u})}function CB(e){const[t,n]=p.useState(e.defaultValue),{getExtendedProps:r}=p.useContext(yt),[o,i]=p.useMemo(()=>["start","end"].map(l=>r(e.path+"."+l)),[r,e.path]);function a(l){n(l),e.onChange&&e.onChange(l)}return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(ws,{disabled:e.disabled||(o==null?void 0:o.readonly),name:e.name+".start",placeholder:"Start",defaultValue:t==null?void 0:t.start,onChange:l=>a({...t,start:l})}),s.jsx(ws,{disabled:e.disabled||(i==null?void 0:i.readonly),name:e.name+".end",placeholder:"End",defaultValue:t==null?void 0:t.end,onChange:l=>a({...t,end:l})})]})}function Ss(e){const[t,n]=p.useState(e.defaultValue),{getExtendedProps:r}=p.useContext(yt),[o,i,a]=p.useMemo(()=>["comparator","value","unit"].map(c=>r(e.path+"."+c)),[r,e.path]);function l(c){n(c),e.onChange&&e.onChange(c)}return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(kt,{disabled:e.disabled||(o==null?void 0:o.readonly),style:{width:80},"data-testid":e.name+"-comparator",defaultValue:t==null?void 0:t.comparator,data:["","<","<=",">=",">"],onChange:c=>l({...t,comparator:c.currentTarget.value})}),s.jsx(me,{disabled:e.disabled||(i==null?void 0:i.readonly),id:e.name,name:e.name,required:e.required,"data-autofocus":e.autoFocus,"data-testid":e.name+"-value",type:"number",placeholder:"Value",defaultValue:t==null?void 0:t.value,autoFocus:e.autoFocus,step:"any",onWheel:c=>{e.disableWheel&&c.currentTarget.blur()},onChange:c=>{l({...t,value:EB(c.currentTarget.value)})}}),s.jsx(me,{disabled:e.disabled||(a==null?void 0:a.readonly),placeholder:"Unit","data-testid":e.name+"-unit",defaultValue:t==null?void 0:t.unit,onChange:c=>l({...t,unit:c.currentTarget.value})})]})}function EB(e){if(e)return parseFloat(e)}function Ix(e){const[t,n]=p.useState(e.defaultValue),{getExtendedProps:r}=p.useContext(yt),[o,i]=p.useMemo(()=>["low","high"].map(l=>r(e.path+"."+l)),[r,e.path]);function a(l){n(l),e.onChange&&e.onChange(l)}return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(Ss,{path:e.path+".low",disabled:e.disabled||(o==null?void 0:o.readonly),name:e.name+"-low",defaultValue:t==null?void 0:t.low,onChange:l=>a({...t,low:l})}),s.jsx(Ss,{path:e.path+".high",disabled:e.disabled||(i==null?void 0:i.readonly),name:e.name+"-high",defaultValue:t==null?void 0:t.high,onChange:l=>a({...t,high:l})})]})}function TB(e){const[t,n]=p.useState(e.defaultValue),{getExtendedProps:r}=p.useContext(yt),[o,i]=p.useMemo(()=>["numerator","denominator"].map(l=>r(e.path+"."+l)),[r,e.path]);function a(l){n(l),e.onChange&&e.onChange(l)}return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(Ss,{path:e.path+".numerator",disabled:e.disabled||(o==null?void 0:o.readonly),name:e.name+"-numerator",defaultValue:t==null?void 0:t.numerator,onChange:l=>a({...t,numerator:l})}),s.jsx(Ss,{path:e.path+".denominator",disabled:e.disabled||(i==null?void 0:i.readonly),name:e.name+"-denominator",defaultValue:t==null?void 0:t.denominator,onChange:l=>a({...t,denominator:l})})]})}const PB={Device:"device-name",Observation:"code",User:"email:contains"},kB=["AccessPolicy","Account","ActivityDefinition","Bot","CapabilityStatement","CareTeam","ClientApplication","CodeSystem","CompartmentDefinition","ConceptMap","EffectEvidenceSynthesis","Endpoint","EventDefinition","Evidence","EvidenceVariable","ExampleScenario","GraphDefinition","Group","HealthcareService","ImplementationGuide","InsurancePlan","Library","Location","Measure","MedicinalProduct","MessageDefinition","NamingSystem","OperationDefinition","Organization","Patient","Person","PlanDefinition","Practitioner","Project","Questionnaire","RelatedPerson","ResearchDefinition","ResearchElementDefinition","RiskEvidenceSynthesis","SearchParameter","StructureDefinition","StructureMap","TerminologyCapabilities","TestScript","UserConfiguration","ValueSet"];function RB(e){return{value:Ct(e),label:Lo(e),resource:e}}function ul(e){const t=ae(),{resourceType:n,searchCriteria:r}=e,[o,i]=p.useState(),a=xt(e.defaultValue,i),l=e.onChange,c=p.useCallback(async(d,f)=>{const h=DB(n),m=new URLSearchParams({[h]:d??"",_count:"10",...r});return await t.searchResources(n,m,{signal:f})},[t,n,r]),u=p.useCallback(d=>{l&&l(d[0])},[l]);return Ot(e.defaultValue)&&!o&&!a?null:s.jsx(Tx,{disabled:e.disabled,name:e.name,required:e.required,itemComponent:_B,defaultValue:a,placeholder:e.placeholder,maxValues:1,toOption:RB,loadOptions:c,onChange:u,clearable:!0})}const _B=p.forwardRef(({label:e,resource:t,...n},r)=>s.jsx("div",{ref:r,...n,children:s.jsxs(J,{wrap:"nowrap",children:[s.jsx(zi,{value:t}),s.jsxs("div",{children:[s.jsx(he,{children:e}),s.jsx(he,{size:"xs",c:"dimmed",children:t.birthDate})]})]})}));function DB(e){return PB[e]??(kB.includes(e)?"name":"_id")}function xh(e){const{onChange:t}=e,n=ae(),[r,o]=p.useState(e.defaultValue),[i,a]=p.useState(()=>IB(e.targetTypes)),[l,c]=p.useState(()=>AB(e.defaultValue,i)),u=p.useRef(new YP),d=p.useMemo(()=>(l==null?void 0:l.type)==="profile"?{...e.searchCriteria,_profile:l.value}:e.searchCriteria,[e.searchCriteria,l]);p.useEffect(()=>{let m=!1;const g=i==null?void 0:i.map(v=>{if(!MB(v))return Promise.resolve(v);m=!0;const S=v.value,y=u.current.get(S);if(y)return y;const b=NB(n,v.value).then(w=>{const j={...v};return w?Ot(w.type)?(j.resourceType=w.type,j.name=w.name,j.title=w.title):(console.error(`StructureDefinition.type missing for ${v.value}`),j.error="StructureDefinition.type missing"):(console.error(`StructureDefinition not found for ${v.value}`),j.error="StructureDefinition not found"),j}).catch(w=>(console.error(w),{...v,error:w})),x=new Nr(b);return u.current.set(S,x),x});!g||!m||Promise.all(g).then(v=>{if(a(v),!l)return;const S=v.findIndex(y=>y.value===l.value||y.resourceType===l.resourceType);if(S===-1){console.debug(`defaultValue had unexpected resourceType: ${l.resourceType}`);return}c(v[S])}).catch(console.error)},[n,l,i]);const f=p.useCallback(m=>{const g=m?jt(m):void 0;o(g),t&&t(g)},[t]),h=p.useMemo(()=>i?i.map(m=>({value:m.value,label:m.type==="profile"?m.title??m.name??m.resourceType??m.value:m.value})):[],[i]);return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",children:[i&&i.length>1&&s.jsx(kt,{disabled:e.disabled,"data-autofocus":e.autoFocus,"data-testid":"reference-input-resource-type-select",defaultValue:l==null?void 0:l.resourceType,autoFocus:e.autoFocus,onChange:m=>{const g=m.currentTarget.value,v=i.find(S=>S.value===g);c(v)},data:h}),!i&&s.jsx(kx,{disabled:e.disabled,autoFocus:e.autoFocus,testId:"reference-input-resource-type-input",defaultValue:l==null?void 0:l.resourceType,onChange:m=>{c(m?{type:"resourceType",value:m,resourceType:m}:void 0)},name:e.name+"-resourceType",placeholder:"Resource Type"}),s.jsx(ul,{resourceType:l==null?void 0:l.resourceType,name:e.name+"-id",required:e.required,placeholder:e.placeholder,defaultValue:r,searchCriteria:d,onChange:f,disabled:e.disabled})]})}function IB(e){if(!e||e.length===0||e.length===1&&e[0]==="Resource")return;const t=[];for(const n of e)n.includes("/")?t.push({type:"profile",value:n}):t.push({type:"resourceType",value:n,resourceType:n});return t}function AB(e,t){var r;const n=(r=e==null?void 0:e.reference)==null?void 0:r.split("/")[0];if(n){const o=t==null?void 0:t.find(i=>i.resourceType===n);return o||{type:"resourceType",value:n,resourceType:n}}if(t&&t.length>0)return t[0]}async function NB(e,t){const n=Ls(t);if(n)return{type:n.type,name:n.name,title:n.title};const r=`{
516
+ `)}function iu(e,t){var n;return(n=e==null?void 0:e.issue)==null?void 0:n.filter(r=>{var o;return Pk((o=r.expression)==null?void 0:o[0],t)})}const qu=/\[\d+\]/;function Pk(e,t){const n=typeof e=="string"&&qu.test(e),r=typeof t=="string"&&qu.test(t);if(n!==r&&(e=e==null?void 0:e.replace(qu,""),t=t==null?void 0:t.replace(qu,"")),e===t)return!0;if(!e||!t)return!1;const o=e.indexOf(".");if(o>=0&&e.substring(o+1)===t)return!0;const i=t.indexOf(".");return i>=0&&t.substring(i+1)===e}function mt(e){const{debugMode:t}=p.useContext(yt);let n;return t&&e.fhirPath?n=`${e.title} - ${e.fhirPath}`:n=e.title,Ck(e!=null&&e.readonly?jk:void 0,s.jsx(It.Wrapper,{id:e.htmlFor,label:n,classNames:{label:e!=null&&e.readonly?Ek.dimmed:void 0},description:e.description,withAsterisk:e.withAsterisk,error:Xe(e.outcome,e.errorExpression??e.htmlFor),"data-testid":e.testId,children:e.children}))}function kk(e,t,n,r,o){const i=r.type;if(i.length>1)for(const a of i){const l=t.replace("[x]",Qt(a.code));l in e&&delete e[l]}return e[n]=o,e}function cB(e){return!!e&&!Bt(e.url)&&!Bt(e.name)}function uB(e){const{defaultValue:t,onChange:n,withHelpText:r,outcome:o,path:i,valuePath:a,...l}=e,[c,u]=p.useState(t);function d(f){const h=fB(f);u(h),n&&n(h)}return s.jsx(Px,{defaultValue:c&&dB(c),onChange:d,withHelpText:r??!0,...l})}function dB(e){var t;return(t=e.coding)==null?void 0:t.map(n=>({system:n.system,code:n.code,display:n.display}))}function fB(e){if(e.length!==0)return{coding:e.map(t=>({system:t.system,code:t.code,display:t.display}))}}function Rk(e){const{defaultValue:t,onChange:n,withHelpText:r,...o}=e,[i,a]=p.useState(t);function l(c){const u=c[0],d=u&&pB(u);a(d),n&&n(d)}return s.jsx(Px,{defaultValue:i&&hB(i),maxValues:1,onChange:l,withHelpText:r??!0,...o})}function hB(e){return{system:e.system,code:e.code,display:e.display}}function pB(e){return{system:e.system,code:e.code,display:e.display}}function _k(e){const{path:t,outcome:n}=e,{elementsByPath:r,getExtendedProps:o}=p.useContext(yt),[i,a]=p.useState(e.defaultValue),l=p.useRef();l.current=i;const[c,u,d]=p.useMemo(()=>["system","use","value"].map(x=>r[t+"."+x]),[r,t]),[f,h,m]=p.useMemo(()=>["system","use","value"].map(x=>o(t+"."+x)),[o,t]);function g(x){x&&Object.keys(x).length===0&&(x=void 0),a(x),e.onChange&&e.onChange(x)}function v(x){const w={...l.current,system:x};x||delete w.system,g(w)}function S(x){const w={...l.current,use:x};x||delete w.use,g(w)}function y(x){const w={...l.current,value:x};x||delete w.value,g(w)}const b=e.valuePath??t;return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[s.jsx(kt,{disabled:e.disabled||(f==null?void 0:f.readonly),"data-testid":"system",defaultValue:i==null?void 0:i.system,required:((c==null?void 0:c.min)??0)>0,onChange:x=>v(x.currentTarget.value),data:["","email","phone","fax","pager","sms","other"],error:Xe(n,b+".system")}),s.jsx(kt,{disabled:e.disabled||(h==null?void 0:h.readonly),"data-testid":"use",defaultValue:i==null?void 0:i.use,required:((u==null?void 0:u.min)??0)>0,onChange:x=>S(x.currentTarget.value),data:["","home","work","temp","old","mobile"],error:Xe(n,b+".use")}),s.jsx(me,{disabled:e.disabled||(m==null?void 0:m.readonly),placeholder:"Value",defaultValue:i==null?void 0:i.value,required:((d==null?void 0:d.min)??0)>0,onChange:x=>y(x.currentTarget.value),error:Xe(n,b+".value")})]})}function mB(e){var d;const[t,n]=p.useState(e.defaultValue),r=p.useRef();r.current=t;const{getExtendedProps:o}=p.useContext(yt),[i,a]=p.useMemo(()=>["name","telecom"].map(f=>o(e.path+"."+f)),[o,e.path]);function l(f){n(f),e.onChange&&e.onChange(f)}function c(f){const h={...r.current,name:f};f||delete h.name,l(h)}function u(f){const h={...r.current,telecom:f&&[f]};f||delete h.telecom,l(h)}return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(me,{disabled:e.disabled||(i==null?void 0:i.readonly),"data-testid":e.name+"-name",name:e.name+"-name",placeholder:"Name",style:{width:180},defaultValue:t==null?void 0:t.name,onChange:f=>c(f.currentTarget.value)}),s.jsx(_k,{disabled:e.disabled||(a==null?void 0:a.readonly),name:e.name+"-telecom",path:e.path+".telecom",defaultValue:(d=t==null?void 0:t.telecom)==null?void 0:d[0],onChange:u,outcome:e.outcome})]})}function gB(e){if(!e)return"";const t=new Date(e);return fh(t)?t.toLocaleDateString("sv")+"T"+t.toLocaleTimeString("sv"):""}function Dk(e){if(!e)return"";const t=new Date(e);return fh(t)?t.toISOString():""}var vB={MEDPLUM_BASE_URL:"__MEDPLUM_BASE_URL__",MEDPLUM_CLIENT_ID:"__MEDPLUM_CLIENT_ID__",GOOGLE_CLIENT_ID:"__GOOGLE_CLIENT_ID__",RECAPTCHA_SITE_KEY:"__RECAPTCHA_SITE_KEY__",MEDPLUM_REGISTER_ENABLED:"__MEDPLUM_REGISTER_ENABLED__",MEDPLUM_VERSION:"3.1.10-7ae504bff",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function ws(e){return s.jsx(me,{id:e.name,name:e.name,label:e.label,"data-autofocus":e.autoFocus,"data-testid":e["data-testid"]??e.name,placeholder:e.placeholder,required:e.required,disabled:e.disabled,type:yB(),defaultValue:gB(e.defaultValue),autoFocus:e.autoFocus,error:Xe(e.outcome,e.name),onChange:t=>{if(e.onChange){const n=t.currentTarget.value;e.onChange(Dk(n))}}})}function yB(){return vB.NODE_ENV==="test"?"text":"datetime-local"}function xB(e){const{propertyType:t}=e,n=ae(),[r,o]=p.useState(),i=p.useMemo(()=>{if(Ot(t.profile))return t.profile[0]},[t]),[a,l]=p.useState(i!==void 0);return p.useEffect(()=>{i&&(l(!0),n.requestProfileSchema(i).then(()=>{const c=Ls(i);l(!1),o(c)}).catch(c=>{l(!1),console.warn(c)}))},[n,i]),i&&(a||!rx(i))?s.jsx("div",{children:"Loading..."}):s.jsx(Nx,{profileUrl:i,path:e.path,typeName:(r==null?void 0:r.name)??"Extension",defaultValue:e.defaultValue,onChange:e.onChange})}function bB(e){var b,x,w;const{outcome:t,path:n}=e,[r,o]=p.useState(e.defaultValue),{getExtendedProps:i}=p.useContext(yt),[a,l,c,u,d]=p.useMemo(()=>["use","prefix","given","family","suffix"].map(j=>i(e.path+"."+j)),[i,e.path]);function f(j){o(j),e.onChange&&e.onChange(j)}function h(j){f({...r,use:j||void 0})}function m(j){f({...r,prefix:j?j.split(" "):void 0})}function g(j){f({...r,given:j?j.split(" "):void 0})}function v(j){f({...r,family:j||void 0})}function S(j){f({...r,suffix:j?j.split(" "):void 0})}const y=e.valuePath??n;return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(kt,{disabled:e.disabled||(a==null?void 0:a.readonly),defaultValue:r==null?void 0:r.use,name:e.name+"-use","data-testid":"use",onChange:j=>h(j.currentTarget.value),data:["","temp","old","usual","official","nickname","anonymous","maiden"],error:Xe(t,y+".use")}),s.jsx(me,{disabled:e.disabled||(l==null?void 0:l.readonly),placeholder:"Prefix",name:e.name+"-prefix",defaultValue:(b=r==null?void 0:r.prefix)==null?void 0:b.join(" "),onChange:j=>m(j.currentTarget.value),error:Xe(t,y+".prefix")}),s.jsx(me,{disabled:e.disabled||(c==null?void 0:c.readonly),placeholder:"Given",name:e.name+"-given",defaultValue:(x=r==null?void 0:r.given)==null?void 0:x.join(" "),onChange:j=>g(j.currentTarget.value),error:Xe(t,y+".given")}),s.jsx(me,{disabled:e.disabled||(u==null?void 0:u.readonly),name:e.name+"-family",placeholder:"Family",defaultValue:r==null?void 0:r.family,onChange:j=>v(j.currentTarget.value),error:Xe(t,y+".family")}),s.jsx(me,{disabled:e.disabled||(d==null?void 0:d.readonly),placeholder:"Suffix",name:e.name+"-suffix",defaultValue:(w=r==null?void 0:r.suffix)==null?void 0:w.join(" "),onChange:j=>S(j.currentTarget.value),error:Xe(t,y+".suffix")})]})}function wB(e){const[t,n]=p.useState(e.defaultValue),{elementsByPath:r,getExtendedProps:o}=p.useContext(yt),[i,a]=p.useMemo(()=>["system","value"].map(f=>r[e.path+"."+f]),[r,e.path]),[l,c]=p.useMemo(()=>["system","value"].map(f=>o(e.path+"."+f)),[o,e.path]);function u(f){n(f),e.onChange&&e.onChange(f)}const d=e.valuePath??e.path;return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[s.jsx(me,{disabled:e.disabled||(l==null?void 0:l.readonly),placeholder:"System",required:((i==null?void 0:i.min)??0)>0,defaultValue:t==null?void 0:t.system,onChange:f=>u({...t,system:f.currentTarget.value}),error:Xe(e.outcome,d+".system")}),s.jsx(me,{disabled:e.disabled||(c==null?void 0:c.readonly),placeholder:"Value",required:((a==null?void 0:a.min)??0)>0,defaultValue:t==null?void 0:t.value,onChange:f=>u({...t,value:f.currentTarget.value}),error:Xe(e.outcome,d+".value")})]})}const SB=["USD","EUR","CAD","GBP","AUD"];function jB(e){var f;const{onChange:t}=e,[n,r]=p.useState(e.defaultValue),{getExtendedProps:o}=p.useContext(yt),[i,a]=p.useMemo(()=>["currency","value"].map(h=>o(e.path+"."+h)),[o,e.path]),l=p.useCallback(h=>{r(h),t&&t(h)},[t]),c=p.useCallback(h=>{l({...n,currency:h.currentTarget.value})},[n,l]),u=p.useCallback(h=>{l({...n,value:h.currentTarget.valueAsNumber})},[n,l]),d=s.jsx(kt,{disabled:e.disabled||(i==null?void 0:i.readonly),defaultValue:n==null?void 0:n.currency,data:SB,styles:{input:{fontWeight:500,borderTopLeftRadius:0,borderBottomLeftRadius:0,width:92}},onChange:c});return s.jsx(me,{disabled:e.disabled||(a==null?void 0:a.readonly),type:"number",name:e.name,label:e.label,placeholder:e.placeholder??"Value",defaultValue:((f=n==null?void 0:n.value)==null?void 0:f.toString())??"USD",leftSection:s.jsx(P8,{size:14}),rightSection:d,rightSectionWidth:92,onChange:u})}function CB(e){const[t,n]=p.useState(e.defaultValue),{getExtendedProps:r}=p.useContext(yt),[o,i]=p.useMemo(()=>["start","end"].map(l=>r(e.path+"."+l)),[r,e.path]);function a(l){n(l),e.onChange&&e.onChange(l)}return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(ws,{disabled:e.disabled||(o==null?void 0:o.readonly),name:e.name+".start",placeholder:"Start",defaultValue:t==null?void 0:t.start,onChange:l=>a({...t,start:l})}),s.jsx(ws,{disabled:e.disabled||(i==null?void 0:i.readonly),name:e.name+".end",placeholder:"End",defaultValue:t==null?void 0:t.end,onChange:l=>a({...t,end:l})})]})}function Ss(e){const[t,n]=p.useState(e.defaultValue),{getExtendedProps:r}=p.useContext(yt),[o,i,a]=p.useMemo(()=>["comparator","value","unit"].map(c=>r(e.path+"."+c)),[r,e.path]);function l(c){n(c),e.onChange&&e.onChange(c)}return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(kt,{disabled:e.disabled||(o==null?void 0:o.readonly),style:{width:80},"data-testid":e.name+"-comparator",defaultValue:t==null?void 0:t.comparator,data:["","<","<=",">=",">"],onChange:c=>l({...t,comparator:c.currentTarget.value})}),s.jsx(me,{disabled:e.disabled||(i==null?void 0:i.readonly),id:e.name,name:e.name,required:e.required,"data-autofocus":e.autoFocus,"data-testid":e.name+"-value",type:"number",placeholder:"Value",defaultValue:t==null?void 0:t.value,autoFocus:e.autoFocus,step:"any",onWheel:c=>{e.disableWheel&&c.currentTarget.blur()},onChange:c=>{l({...t,value:EB(c.currentTarget.value)})}}),s.jsx(me,{disabled:e.disabled||(a==null?void 0:a.readonly),placeholder:"Unit","data-testid":e.name+"-unit",defaultValue:t==null?void 0:t.unit,onChange:c=>l({...t,unit:c.currentTarget.value})})]})}function EB(e){if(e)return parseFloat(e)}function Ix(e){const[t,n]=p.useState(e.defaultValue),{getExtendedProps:r}=p.useContext(yt),[o,i]=p.useMemo(()=>["low","high"].map(l=>r(e.path+"."+l)),[r,e.path]);function a(l){n(l),e.onChange&&e.onChange(l)}return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(Ss,{path:e.path+".low",disabled:e.disabled||(o==null?void 0:o.readonly),name:e.name+"-low",defaultValue:t==null?void 0:t.low,onChange:l=>a({...t,low:l})}),s.jsx(Ss,{path:e.path+".high",disabled:e.disabled||(i==null?void 0:i.readonly),name:e.name+"-high",defaultValue:t==null?void 0:t.high,onChange:l=>a({...t,high:l})})]})}function TB(e){const[t,n]=p.useState(e.defaultValue),{getExtendedProps:r}=p.useContext(yt),[o,i]=p.useMemo(()=>["numerator","denominator"].map(l=>r(e.path+"."+l)),[r,e.path]);function a(l){n(l),e.onChange&&e.onChange(l)}return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(Ss,{path:e.path+".numerator",disabled:e.disabled||(o==null?void 0:o.readonly),name:e.name+"-numerator",defaultValue:t==null?void 0:t.numerator,onChange:l=>a({...t,numerator:l})}),s.jsx(Ss,{path:e.path+".denominator",disabled:e.disabled||(i==null?void 0:i.readonly),name:e.name+"-denominator",defaultValue:t==null?void 0:t.denominator,onChange:l=>a({...t,denominator:l})})]})}const PB={Device:"device-name",Observation:"code",User:"email:contains"},kB=["AccessPolicy","Account","ActivityDefinition","Bot","CapabilityStatement","CareTeam","ClientApplication","CodeSystem","CompartmentDefinition","ConceptMap","EffectEvidenceSynthesis","Endpoint","EventDefinition","Evidence","EvidenceVariable","ExampleScenario","GraphDefinition","Group","HealthcareService","ImplementationGuide","InsurancePlan","Library","Location","Measure","MedicinalProduct","MessageDefinition","NamingSystem","OperationDefinition","Organization","Patient","Person","PlanDefinition","Practitioner","Project","Questionnaire","RelatedPerson","ResearchDefinition","ResearchElementDefinition","RiskEvidenceSynthesis","SearchParameter","StructureDefinition","StructureMap","TerminologyCapabilities","TestScript","UserConfiguration","ValueSet"];function RB(e){return{value:Ct(e),label:Lo(e),resource:e}}function ul(e){const t=ae(),{resourceType:n,searchCriteria:r}=e,[o,i]=p.useState(),a=xt(e.defaultValue,i),l=e.onChange,c=p.useCallback(async(d,f)=>{const h=DB(n),m=new URLSearchParams({[h]:d??"",_count:"10",...r});return await t.searchResources(n,m,{signal:f})},[t,n,r]),u=p.useCallback(d=>{l&&l(d[0])},[l]);return Ot(e.defaultValue)&&!o&&!a?null:s.jsx(Tx,{disabled:e.disabled,name:e.name,required:e.required,itemComponent:_B,defaultValue:a,placeholder:e.placeholder,maxValues:1,toOption:RB,loadOptions:c,onChange:u,clearable:!0})}const _B=p.forwardRef(({label:e,resource:t,...n},r)=>s.jsx("div",{ref:r,...n,children:s.jsxs(J,{wrap:"nowrap",children:[s.jsx(zi,{value:t}),s.jsxs("div",{children:[s.jsx(he,{children:e}),s.jsx(he,{size:"xs",c:"dimmed",children:t.birthDate})]})]})}));function DB(e){return PB[e]??(kB.includes(e)?"name":"_id")}function xh(e){const{onChange:t}=e,n=ae(),[r,o]=p.useState(e.defaultValue),[i,a]=p.useState(()=>IB(e.targetTypes)),[l,c]=p.useState(()=>AB(e.defaultValue,i)),u=p.useRef(new YP),d=p.useMemo(()=>(l==null?void 0:l.type)==="profile"?{...e.searchCriteria,_profile:l.value}:e.searchCriteria,[e.searchCriteria,l]);p.useEffect(()=>{let m=!1;const g=i==null?void 0:i.map(v=>{if(!MB(v))return Promise.resolve(v);m=!0;const S=v.value,y=u.current.get(S);if(y)return y;const b=NB(n,v.value).then(w=>{const j={...v};return w?Ot(w.type)?(j.resourceType=w.type,j.name=w.name,j.title=w.title):(console.error(`StructureDefinition.type missing for ${v.value}`),j.error="StructureDefinition.type missing"):(console.error(`StructureDefinition not found for ${v.value}`),j.error="StructureDefinition not found"),j}).catch(w=>(console.error(w),{...v,error:w})),x=new Nr(b);return u.current.set(S,x),x});!g||!m||Promise.all(g).then(v=>{if(a(v),!l)return;const S=v.findIndex(y=>y.value===l.value||y.resourceType===l.resourceType);if(S===-1){console.debug(`defaultValue had unexpected resourceType: ${l.resourceType}`);return}c(v[S])}).catch(console.error)},[n,l,i]);const f=p.useCallback(m=>{const g=m?jt(m):void 0;o(g),t&&t(g)},[t]),h=p.useMemo(()=>i?i.map(m=>({value:m.value,label:m.type==="profile"?m.title??m.name??m.resourceType??m.value:m.value})):[],[i]);return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",children:[i&&i.length>1&&s.jsx(kt,{disabled:e.disabled,"data-autofocus":e.autoFocus,"data-testid":"reference-input-resource-type-select",defaultValue:l==null?void 0:l.resourceType,autoFocus:e.autoFocus,onChange:m=>{const g=m.currentTarget.value,v=i.find(S=>S.value===g);c(v)},data:h}),!i&&s.jsx(kx,{disabled:e.disabled,autoFocus:e.autoFocus,testId:"reference-input-resource-type-input",defaultValue:l==null?void 0:l.resourceType,onChange:m=>{c(m?{type:"resourceType",value:m,resourceType:m}:void 0)},name:e.name+"-resourceType",placeholder:"Resource Type"}),s.jsx(ul,{resourceType:l==null?void 0:l.resourceType,name:e.name+"-id",required:e.required,placeholder:e.placeholder,defaultValue:r,searchCriteria:d,onChange:f,disabled:e.disabled})]})}function IB(e){if(!e||e.length===0||e.length===1&&e[0]==="Resource")return;const t=[];for(const n of e)n.includes("/")?t.push({type:"profile",value:n}):t.push({type:"resourceType",value:n,resourceType:n});return t}function AB(e,t){var r;const n=(r=e==null?void 0:e.reference)==null?void 0:r.split("/")[0];if(n){const o=t==null?void 0:t.find(i=>i.resourceType===n);return o||{type:"resourceType",value:n,resourceType:n}}if(t&&t.length>0)return t[0]}async function NB(e,t){const n=Ls(t);if(n)return{type:n.type,name:n.name,title:n.title};const r=`{
517
517
  StructureDefinitionList(url: "${t}", _sort: "_lastUpdated", _count: 1) {
518
518
  type,
519
519
  name,
@@ -521,7 +521,7 @@ Error generating stack: `+i.message+`
521
521
  }
522
522
  }`.replace(/\s+/g," ");return(await e.graphql(r)).data.StructureDefinitionList[0]}function MB(e){return e.type==="profile"&&!(e!=null&&e.error)&&Bt(e.resourceType)}const OB="_indented_ldk1d_1",Ik={indented:OB};function Ak({propertyDisplayName:e,onClick:t,testId:n}){const r=e?`Add ${e}`:"Add";return e?s.jsx(re,{title:r,size:"sm",color:"green.6",variant:"subtle","data-testid":n,leftSection:s.jsx(Jd,{size:"1.25rem"}),onClick:t,children:r}):s.jsx(nn,{title:r,color:"green.6","data-testid":n,onClick:t,children:s.jsx(Jd,{size:"1.25rem"})})}function Nk({propertyDisplayName:e,onClick:t,testId:n}){return s.jsx(nn,{title:e?`Remove ${e}`:"Remove",color:"red.5","data-testid":n,variant:"subtle",onClick:t,children:s.jsx(Xd,{size:"1.25rem"})})}function $B(e){var m,g;const{slice:t,property:n}=e,[r,o]=p.useState(e.defaultValue),i=((m=t.typeSchema)==null?void 0:m.elements)??t.elements,a=p.useContext(yt),l=p.useMemo(()=>{var v;if(Ot(i))return Wa({parentContext:a,elements:i,path:e.path,profileUrl:(v=t.typeSchema)==null?void 0:v.url})},[a,e.path,(g=t.typeSchema)==null?void 0:g.url,i]);function c(v){o(v),e.onChange&&e.onChange(v)}const u=t.min>0,d=Bt(t.elements),f=LP(t.name),h=e.property.readonly&&r.length===0;return yh(yt.Provider,l,s.jsx(mt,{title:f,description:t.definition,withAsterisk:u,fhirPath:`${n.path}:${t.name}`,testId:e.testId,readonly:e.property.readonly,children:h?s.jsx(he,{c:"dimmed",children:"(empty)"}):s.jsxs(Ne,{className:d?Ik.indented:void 0,children:[r.map((v,S)=>s.jsxs(J,{wrap:"nowrap",children:[s.jsx("div",{style:{flexGrow:1},"data-testid":e.testId&&`${e.testId}-elements-${S}`,children:s.jsx(Ax,{elementDefinitionType:t.type[0],name:t.name,defaultValue:v,onChange:y=>{const b=[...r];b[S]=y,c(b)},outcome:e.outcome,min:t.min,max:t.max,binding:t.binding,path:e.path,valuePath:void 0,readOnly:e.property.readonly})}),!e.property.readonly&&r.length>t.min&&s.jsx(Nk,{propertyDisplayName:f,testId:e.testId&&`${e.testId}-remove-${S}`,onClick:y=>{dt(y);const b=[...r];b.splice(S,1),c(b)}})]},`${S}-${r.length}`)),!e.property.readonly&&r.length<t.max&&s.jsx(J,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:s.jsx(Ak,{propertyDisplayName:f,onClick:v=>{dt(v);const S=[...r,void 0];c(S)},testId:e.testId&&`${e.testId}-add`})})]})}))}function LB(e,t,n){return t===void 0?e:n===void 0?t:`${t}[${n}]`}function FB(e){var b;const{property:t}=e,n=ae(),[r,o]=p.useState(!0),[i,a]=p.useState([]),[l]=p.useState(()=>Array.isArray(e.defaultValue)?e.defaultValue:[]),[c,u]=p.useState(()=>[l]),d=p.useContext(yt),f=(b=t.type[0])==null?void 0:b.code;p.useEffect(()=>{wk({medplum:n,property:t}).then(x=>{a(x);const w=bk(l,x,t.slicing,d.profileUrl);zB(w,x),u(w),o(!1)}).catch(x=>{console.error(x),o(!1)})},[n,t,l,d.profileUrl,u]);function h(x,w){const j=[...c];if(j[w]=x,u(j),e.onChange){const E=j.flat().filter(C=>C!==void 0);e.onChange(E)}}if(r)return s.jsx("div",{children:"Loading..."});const m=i.length,g=c[m],v=!(e.hideNonSliceValues??(f==="Extension"&&i.length>0)),S=bs(t.path),y=e.property.readonly&&i.length===0&&l.length===0;return s.jsxs(Ne,{className:e.indent?Ik.indented:void 0,children:[y&&s.jsx(he,{c:"dimmed",children:"(empty)"}),i.map((x,w)=>s.jsx($B,{slice:x,path:e.path,valuePath:e.valuePath,property:t,defaultValue:c[w],onChange:j=>{h(j,w)},testId:`slice-${x.name}`},x.name)),v&&g.map((x,w)=>s.jsxs(J,{wrap:"nowrap",style:{flexGrow:1},children:[s.jsx("div",{style:{flexGrow:1},children:s.jsx(dl,{arrayElement:!0,property:e.property,name:e.name+"."+w,path:e.path,valuePath:LB(e.path,e.valuePath,w),defaultValue:x,onChange:j=>{const E=[...g];E[w]=j,h(E,m)},defaultPropertyType:void 0,outcome:e.outcome})}),!e.property.readonly&&s.jsx(Nk,{propertyDisplayName:S,testId:`nonsliced-remove-${w}`,onClick:j=>{dt(j);const E=[...g];E.splice(w,1),h(E,m)}})]},`${w}-${g.length}`)),!e.property.readonly&&v&&c.flat().length<t.max&&s.jsx(J,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:s.jsx(Ak,{propertyDisplayName:S,onClick:x=>{dt(x);const w=[...g];w.push(void 0),h(w,m)},testId:"nonsliced-add"})})]})}function zB(e,t){for(let n=0;n<t.length;n++){const r=t[n],o=e[n];for(;o.length<r.min;)o.push(void 0)}}function BB(e){const[t,n]=p.useState(!1),r=TS(),o=p.useRef(null),i={...e.styles};return t||(i.input||(i.input={}),i.input.WebkitTextSecurity="disc"),s.jsxs(ms,{gap:"xs",children:[s.jsx(Ns,{...e,styles:{...i,root:{...i.root??{},flexGrow:1}},ref:o,autosize:!0,minRows:1,onFocus:()=>n(!0),onBlur:()=>n(!1)}),s.jsx(nn,{title:"Copy secret",onClick:()=>{var a;r.copy((a=o.current)==null?void 0:a.value),ye({color:"green",message:"Copied"})},children:s.jsx(uk,{})})]})}const VB=["sun","mon","tue","wed","thu","fri","sat"];function UB(e){const[t,n]=p.useState(e.defaultValue),[r,o]=p.useState(!e.disabled&&(e.defaultModalOpen??!1)),i=p.useRef();return i.current=t,s.jsxs(s.Fragment,{children:[s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx("span",{children:MP(i.current)||"No repeat"}),s.jsx(re,{disabled:e.disabled,onClick:()=>o(!0),children:"Edit"})]}),!e.disabled&&s.jsx(HB,{path:e.path,visible:r,defaultValue:i.current,onOk:a=>{e.onChange&&e.onChange(a),n(a),o(!1)},onCancel:()=>o(!1)})]})}const ow={repeat:{period:1,periodUnit:"d"}};function HB(e){const[t,n]=p.useState(e.defaultValue||ow),{getExtendedProps:r}=p.useContext(yt),[o,i,a,l,c]=p.useMemo(()=>["event","repeat","repeat.period","repeat.periodUnit","repeat.dayOfWeek"].map(v=>r(e.path+"."+v)),[r,e.path]),u=p.useRef();u.current=t;function d(v){n({...u.current,event:[v]})}function f(v){n({...u.current,repeat:v})}function h(v){var S;f({...(S=u.current)==null?void 0:S.repeat,period:v})}function m(v){var S;f({...(S=u.current)==null?void 0:S.repeat,periodUnit:v})}function g(v){var S;f({...(S=u.current)==null?void 0:S.repeat,dayOfWeek:v})}return s.jsx(En,{title:"Timing",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:()=>e.onCancel(),children:s.jsxs(Ne,{children:[s.jsx(mt,{title:"Starts on",htmlFor:"timing-dialog-start",children:s.jsx(ws,{disabled:o==null?void 0:o.readonly,name:"timing-dialog-start",onChange:v=>d(v)})}),s.jsx(Qc,{disabled:i==null?void 0:i.readonly,label:"Repeat",checked:!!t.repeat,onChange:v=>f(v.currentTarget.checked?ow.repeat:void 0)}),t.repeat&&s.jsxs(s.Fragment,{children:[s.jsx(mt,{title:"Repeat every",htmlFor:"timing-dialog-period",children:s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",children:[s.jsx(me,{disabled:a==null?void 0:a.readonly,type:"number",step:1,id:"timing-dialog-period",name:"timing-dialog-period",defaultValue:t.repeat.period||1,onChange:v=>h(parseInt(v.currentTarget.value,10)||1)}),s.jsx(kt,{disabled:l==null?void 0:l.readonly,id:"timing-dialog-periodUnit",name:"timing-dialog-periodUnit",defaultValue:t.repeat.periodUnit,onChange:v=>m(v.currentTarget.value),data:[{label:"second",value:"s"},{label:"minute",value:"min"},{label:"hour",value:"h"},{label:"day",value:"d"},{label:"week",value:"wk"},{label:"month",value:"mo"},{label:"year",value:"a"}]})]})}),t.repeat.periodUnit==="wk"&&s.jsx(mt,{title:"Repeat on",children:s.jsx(vc.Group,{multiple:!0,onChange:g,children:s.jsx(J,{justify:"space-between",mt:"md",gap:"xs",children:VB.map(v=>s.jsx(vc,{value:v,size:"xs",radius:"xl",disabled:c==null?void 0:c.readonly,children:v.charAt(0).toUpperCase()},v))})})})]}),s.jsx(J,{justify:"flex-end",children:s.jsx(re,{onClick:()=>e.onOk(t),children:"OK"})})]})})}function dl(e){var l;const{property:t,name:n,onChange:r,defaultValue:o}=e,i=e.defaultPropertyType&&e.defaultPropertyType!=="undefined"?e.defaultPropertyType:t.type[0].code,a=t.type;if((t.isArray||t.max>1)&&!e.arrayElement){if(i===U.Attachment)return s.jsx(Xz,{name:n,defaultValue:o,onChange:r,disabled:t.readonly});const c=((l=a[0])==null?void 0:l.code)!==U.Extension;return s.jsx(FB,{property:t,name:n,path:e.path,valuePath:e.valuePath,defaultValue:o,indent:c,onChange:r,outcome:e.outcome})}else return a.length>1?s.jsx(WB,{elementDefinitionTypes:a,...e}):s.jsx(Ax,{name:n,defaultValue:o,onChange:c=>{if(e.onChange){const u=e.name.replace("[x]",Qt(a[0].code));e.onChange(c,u)}},outcome:e.outcome,elementDefinitionType:a[0],min:t.min,max:t.min,binding:t.binding,path:e.path,valuePath:e.valuePath,readOnly:t.readonly})}function WB(e){const t=e.elementDefinitionTypes;let n;e.defaultPropertyType&&(n=t.find(i=>i.code===e.defaultPropertyType)),n||(n=t[0]);const[r,o]=p.useState(n);return s.jsxs(J,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[s.jsx(kt,{disabled:e.property.readonly,style:{width:"200px"},defaultValue:r.code,"data-testid":e.name&&e.name+"-selector",onChange:i=>{o(t.find(a=>a.code===i.currentTarget.value))},data:t.map(i=>({value:i.code,label:i.code}))}),s.jsx(Ax,{name:e.name,defaultValue:e.defaultValue,outcome:e.outcome,elementDefinitionType:r,onChange:i=>{e.onChange&&e.onChange(i,e.name.replace("[x]",Qt(r.code)))},min:e.property.min,max:e.property.max,binding:e.property.binding,path:e.property.path,valuePath:e.valuePath,readOnly:e.property.readonly})]})}function Ax(e){const{name:t,onChange:n,outcome:r,binding:o,path:i,valuePath:a,readOnly:l}=e,c=e.min!==void 0&&e.min>0,u=e.elementDefinitionType.code,d=p.useContext(yt),f=p.useMemo(()=>{if(!sx(u)||!Bt(e.defaultValue))return e.defaultValue;const g=Object.create(null);if(d.path===e.path)Gb(g,d.elements);else{const v=bc(d.path,e.path);if(v===void 0)return e.defaultValue;Gb(g,d.elements,v)}return Ot(g)?g:e.defaultValue},[u,d.path,d.elements,e.path,e.defaultValue]);if(!u)return s.jsx("div",{children:"Property type not specified "});function h(){return{name:t,defaultValue:f,onChange:n,outcome:r,path:i,valuePath:a,disabled:l}}function m(){const g=Xe(e.outcome,a??i);return{id:t,name:t,"data-testid":t,defaultValue:f,required:c,error:g,disabled:l}}switch(u){case U.SystemString:case U.canonical:case U.string:case U.time:case U.uri:case U.url:return e.path==="Project.secret.value[x]"?s.jsx(BB,{...m(),onChange:g=>{e.onChange&&e.onChange(g.currentTarget.value)}}):s.jsx(me,{...m(),onChange:g=>{n&&n(g.currentTarget.value)}});case U.date:return s.jsx(me,{...m(),type:"date",onChange:g=>{n&&n(g.currentTarget.value)}});case U.dateTime:case U.instant:return s.jsx(ws,{...m(),onChange:n,outcome:r});case U.decimal:case U.integer:case U.positiveInt:case U.unsignedInt:return s.jsx(me,{...m(),type:"number",step:u===U.decimal?"any":"1",onChange:g=>{if(n){const v=g.currentTarget.valueAsNumber;n(Number.isNaN(v)?void 0:v)}}});case U.code:return s.jsx(vk,{...m(),error:void 0,onChange:n,binding:o==null?void 0:o.valueSet});case U.boolean:return s.jsx(Xn,{...m(),defaultChecked:!!f,onChange:g=>{n&&n(g.currentTarget.checked)}});case U.base64Binary:case U.markdown:return s.jsx(Ns,{...m(),spellCheck:u!==U.base64Binary,onChange:g=>{n&&n(g.currentTarget.value)}});case U.Address:return s.jsx(d8,{...h()});case U.Annotation:return s.jsx(f8,{...h()});case U.Attachment:return s.jsx(yk,{...h()});case U.CodeableConcept:return s.jsx(uB,{binding:o==null?void 0:o.valueSet,...h()});case U.Coding:return s.jsx(Rk,{binding:o==null?void 0:o.valueSet,...h()});case U.ContactDetail:return s.jsx(mB,{...h()});case U.ContactPoint:return s.jsx(_k,{...h()});case U.Extension:return s.jsx(xB,{...h(),propertyType:e.elementDefinitionType});case U.HumanName:return s.jsx(bB,{...h()});case U.Identifier:return s.jsx(wB,{...h()});case U.Money:return s.jsx(jB,{...h()});case U.Period:return s.jsx(CB,{...h()});case U.Duration:case U.Quantity:return s.jsx(Ss,{...h()});case U.Range:return s.jsx(Ix,{...h()});case U.Ratio:return s.jsx(TB,{...h()});case U.Reference:return s.jsx(xh,{...h(),targetTypes:GB(e.elementDefinitionType)});case U.Timing:return s.jsx(UB,{...h()});case U.Dosage:case U.UsageContext:default:return s.jsx(Nx,{...h(),typeName:u})}}const qB=[`${iL}/fhir/StructureDefinition/`,"https://medplum.com/fhir/StructureDefinition/"];function GB(e){var t;return(t=e==null?void 0:e.targetProfile)==null?void 0:t.map(n=>{const r=qB.find(o=>n.startsWith(o));return r?n.slice(r.length):n})}function QB(e){const[t,n]=p.useState(e.defaultValue??{}),r=p.useContext(yt),o=p.useMemo(()=>u8(r.elements),[r.elements]);function i(l){n(l),e.onChange&&e.onChange(l)}const a={type:e.type,value:t};return s.jsx(Ne,{style:{flexGrow:1},"data-testid":e.testId,children:o.map(([l,c])=>{const[u,d]=iB(a,l,c),f=c.min!==void 0&&c.min>0,h=e.valuePath?e.valuePath+"."+l:void 0,m=s.jsx(dl,{property:c,name:l,path:e.path+"."+l,valuePath:h,defaultValue:u,defaultPropertyType:d,onChange:(g,v)=>{i(kk({...t},l,v??l,c,g))},outcome:e.outcome},l);return e.type==="Extension"||wx.includes(l)?m:c.type.length===1&&c.type[0].code==="boolean"?s.jsx(Tk,{title:bs(l),description:c.description,htmlFor:l,fhirPath:c.path,withAsterisk:f,readonly:c.readonly,children:m},l):s.jsx(mt,{title:bs(l),description:c.description,withAsterisk:f,htmlFor:l,outcome:e.outcome,fhirPath:c.path,errorExpression:h,readonly:c.readonly,children:m},l)})})}function Nx(e){const[t]=p.useState(()=>e.defaultValue??{}),n=p.useContext(yt),r=e.profileUrl??(n==null?void 0:n.profileUrl),o=p.useMemo(()=>uh(e.typeName,r),[e.typeName,r]),i=(o==null?void 0:o.type)??e.typeName,a=p.useMemo(()=>{if(o)return Wa({parentContext:n,elements:o.elements,path:e.path,profileUrl:o.url,accessPolicyResource:e.accessPolicyResource})},[o,n,e.path,e.accessPolicyResource]);return o?yh(yt.Provider,a,s.jsx(QB,{path:e.path,valuePath:e.valuePath,type:i,defaultValue:t,onChange:e.onChange,outcome:e.outcome})):s.jsxs("div",{children:[i," not implemented"]})}const KB="_root_1vii2_1",YB={root:KB};function su(e){const{children:t,...n}=e;return s.jsx(xy,{className:YB.root,...n,children:t})}const XB="_noteBody_10swh_1",JB="_noteCite_10swh_5",ZB="_noteRoot_10swh_10",iw={noteBody:XB,noteCite:JB,noteRoot:ZB};function Mk({value:e}){return e?s.jsx(Ne,{justify:"flex-start",gap:"xs",children:e.map(t=>{var n;return t.text&&s.jsx(gy,{classNames:{cite:iw.noteCite,root:iw.noteRoot},cite:((n=t.authorReference)==null?void 0:n.display)||t.authorString,icon:null,children:t.text},`note-${t.text}`)})}):null}function fl(e){const{value:t,link:n,...r}=e,[o,i]=p.useState(),a=xt(t,i);let l;if(o&&!pP(o))l=`[${Me(o)}]`;else if(a)l=Lo(a);else return null;return n?s.jsx(Ge,{to:t,...r,children:l}):s.jsx(he,{component:"span",...r,children:l})}function Da(e){return s.jsxs(J,{gap:"xs",children:[s.jsx(zi,{size:24,radius:12,value:e.value,link:e.link}),s.jsx(fl,{value:e.value,link:e.link})]})}const eV={draft:"blue",active:"blue","on-hold":"yellow",revoked:"red",completed:"green","entered-in-error":"red",unknown:"gray",retired:"gray",registered:"blue",preliminary:"blue",final:"green",amended:"yellow",corrected:"yellow",cancelled:"red",requested:"blue",received:"blue",accepted:"blue",rejected:"red",ready:"blue","in-progress":"blue",failed:"red",proposed:"blue",pending:"blue",booked:"blue",arrived:"blue",fulfilled:"green",noshow:"red","checked-in":"blue",waitlist:"gray",routine:"gray",urgent:"red",asap:"red",stat:"red","not-done":"red",connected:"green",disconnected:"red"};function Mx(e){return s.jsx(Uc,{color:eV[e.status],children:e.status})}const tV="_table_pe9td_1",nV="_criticalRow_pe9td_12",rV="_noteBody_pe9td_23",oV="_noteCite_pe9td_27",iV="_noteRoot_pe9td_32",Ok={table:tV,criticalRow:nV,noteBody:rV,noteCite:oV,noteRoot:iV};Ox.defaultProps={hideObservationNotes:!1,hideSpecimenInfo:!1};function Ox(e){var a;const t=ae(),n=xt(e.value),[r,o]=p.useState();if(p.useEffect(()=>{n!=null&&n.specimen&&Promise.allSettled(n.specimen.map(l=>t.readReference(l))).then(l=>l.filter(c=>c.status==="fulfilled").map(c=>c.value)).then(o).catch(console.error)},[t,n]),!n)return null;const i=(r==null?void 0:r.flatMap(l=>l.note||[]))||[];if(n.presentedForm&&n.presentedForm.length>0){const l=n.presentedForm[0];(a=l.contentType)!=null&&a.startsWith("text/plain")&&l.data&&i.push({text:window.atob(l.data)})}return s.jsxs(Ne,{children:[s.jsx(pe,{children:"Diagnostic Report"}),s.jsx(sV,{value:n}),r&&!e.hideSpecimenInfo&&aV(r),n.result&&s.jsx(lV,{hideObservationNotes:e.hideObservationNotes,value:n.result}),i.length>0&&s.jsx(Mk,{value:i})]})}function sV({value:e}){var t,n;return s.jsxs(J,{mt:"md",gap:30,children:[e.subject&&s.jsxs("div",{children:[s.jsx(he,{size:"xs",tt:"uppercase",c:"dimmed",children:"Subject"}),s.jsx(Da,{value:e.subject,link:!0})]}),(t=e.resultsInterpreter)==null?void 0:t.map(r=>s.jsxs("div",{children:[s.jsx(he,{size:"xs",tt:"uppercase",c:"dimmed",children:"Interpreter"}),s.jsx(Da,{value:r,link:!0})]},r.reference)),(n=e.performer)==null?void 0:n.map(r=>s.jsxs("div",{children:[s.jsx(he,{size:"xs",tt:"uppercase",c:"dimmed",children:"Performer"}),s.jsx(Da,{value:r,link:!0})]},r.reference)),e.issued&&s.jsxs("div",{children:[s.jsx(he,{size:"xs",tt:"uppercase",c:"dimmed",children:"Issued"}),s.jsx(he,{children:Mn(e.issued)})]}),e.status&&s.jsxs("div",{children:[s.jsx(he,{size:"xs",tt:"uppercase",c:"dimmed",children:"Status"}),s.jsx(he,{children:Qt(e.status)})]})]})}function aV(e){return s.jsxs(Ne,{gap:"xs",children:[s.jsx(pe,{order:2,size:"h6",children:"Specimens"}),s.jsx(An,{type:"ordered",children:e==null?void 0:e.map(t=>{var n;return s.jsx(An.Item,{ml:"sm",children:s.jsxs(J,{gap:20,children:[s.jsxs(J,{gap:5,children:[s.jsx(he,{fw:500,children:"Collected:"})," ",Mn((n=t.collection)==null?void 0:n.collectedDateTime)]}),s.jsxs(J,{gap:5,children:[s.jsx(he,{fw:500,children:"Received:"})," ",Mn(t.receivedTime)]})]})},`specimen-${t.id}`)})})]})}function lV(e){return s.jsxs("table",{className:Ok.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Test"}),s.jsx("th",{children:"Value"}),s.jsx("th",{children:"Reference Range"}),s.jsx("th",{children:"Interpretation"}),s.jsx("th",{children:"Category"}),s.jsx("th",{children:"Performer"}),s.jsx("th",{children:"Status"})]})}),s.jsx("tbody",{children:s.jsx($k,{value:e.value,ancestorIds:e.ancestorIds,hideObservationNotes:e.hideObservationNotes})})]})}function $k(e){var t;return s.jsx(s.Fragment,{children:(t=e.value)==null?void 0:t.map(n=>s.jsx(cV,{value:n,ancestorIds:e.ancestorIds,hideObservationNotes:e.hideObservationNotes},`obs-${Bs(n)?n.reference:n.id}`))})}function cV(e){var o,i;const t=xt(e.value);if(!t||(o=e.ancestorIds)!=null&&o.includes(t.id))return null;const n=!e.hideObservationNotes&&t.note,r=fV(t);return s.jsxs(s.Fragment,{children:[s.jsxs("tr",{className:rt({[Ok.criticalRow]:r}),children:[s.jsx("td",{rowSpan:n?2:1,children:s.jsx(Ge,{to:t,children:s.jsx(fo,{value:t.code})})}),s.jsx("td",{children:s.jsx(uV,{value:t})}),s.jsx("td",{children:s.jsx(dV,{value:t.referenceRange})}),s.jsx("td",{children:t.interpretation&&t.interpretation.length>0&&s.jsx(fo,{value:t.interpretation[0]})}),s.jsx("td",{children:t.category&&t.category.length>0&&s.jsx(s.Fragment,{children:t.category.map(a=>s.jsx("div",{children:s.jsx(fo,{value:a})},`category-${Di(a)}`))})}),s.jsx("td",{children:(i=t.performer)==null?void 0:i.map(a=>s.jsx(ef,{value:a},a.reference))}),s.jsx("td",{children:t.status&&s.jsx(Mx,{status:t.status})})]}),t.hasMember&&s.jsx($k,{value:t.hasMember,ancestorIds:e.ancestorIds?[...e.ancestorIds,t.id]:[t.id],hideObservationNotes:e.hideObservationNotes}),n&&s.jsx("tr",{children:s.jsx("td",{colSpan:6,children:s.jsx(Mk,{value:t.note})})})]})}function uV(e){const t=e.value;return s.jsx(s.Fragment,{children:OP(t)})}function dV(e){const t=e.value&&e.value.length>0&&e.value[0];return t?t.text?s.jsx(s.Fragment,{children:t.text}):s.jsx(Dx,{value:t}):null}function fV(e){var n,r,o,i;const t=(i=(o=(r=(n=e.interpretation)==null?void 0:n[0])==null?void 0:r.coding)==null?void 0:o[0])==null?void 0:i.code;return t==="AA"||t==="LL"||t==="HH"||t==="A"}const hV="_paper_1igaj_1",pV="_fill_1igaj_20",sw={paper:hV,fill:pV};function $x(e){const{width:t,fill:n,className:r,children:o,...i}=e,a=t?{maxWidth:t}:void 0;return s.jsx(qn,{className:rt(sw.paper,n&&sw.fill,r),style:a,shadow:"sm",radius:"sm",withBorder:!0,...i,children:o})}var Lk={},au={};Object.defineProperty(au,"__esModule",{value:!0});au.Pointer=void 0;function mV(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function gV(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var vV=function(){function e(t){t===void 0&&(t=[""]),this.tokens=t}return e.fromJSON=function(t){var n=t.split("/").map(mV);if(n[0]!=="")throw new Error("Invalid JSON Pointer: ".concat(t));return new e(n)},e.prototype.toString=function(){return this.tokens.map(gV).join("/")},e.prototype.evaluate=function(t){for(var n=null,r="",o=t,i=1,a=this.tokens.length;i<a;i++)n=o,r=this.tokens[i],!(r=="__proto__"||r=="constructor"||r=="prototype")&&(o=(n||{})[r]);return{parent:n,key:r,value:o}},e.prototype.get=function(t){return this.evaluate(t).value},e.prototype.set=function(t,n){var r=this.evaluate(t);r.parent&&(r.parent[r.key]=n)},e.prototype.push=function(t){this.tokens.push(t)},e.prototype.add=function(t){var n=this.tokens.concat(String(t));return new e(n)},e}();au.Pointer=vV;var Ft={},Lx={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.clone=e.objectType=e.hasOwnProperty=void 0,e.hasOwnProperty=Object.prototype.hasOwnProperty;function t(o){return o===void 0?"undefined":o===null?"null":Array.isArray(o)?"array":typeof o}e.objectType=t;function n(o){return o!=null&&typeof o=="object"}function r(o){if(!n(o))return o;if(o.constructor==Array){for(var i=o.length,a=new Array(i),l=0;l<i;l++)a[l]=r(o[l]);return a}if(o.constructor==Date){var c=new Date(+o);return c}var u={};for(var d in o)e.hasOwnProperty.call(o,d)&&(u[d]=r(o[d]));return u}e.clone=r})(Lx);var In={};Object.defineProperty(In,"__esModule",{value:!0});In.diffAny=In.diffObjects=In.diffArrays=In.intersection=In.subtract=In.isDestructive=void 0;var Tc=Lx;function yV(e){var t=e.op;return t==="remove"||t==="replace"||t==="copy"||t==="move"}In.isDestructive=yV;function ig(e,t){var n={};for(var r in e)Tc.hasOwnProperty.call(e,r)&&e[r]!==void 0&&(n[r]=1);for(var o in t)Tc.hasOwnProperty.call(t,o)&&t[o]!==void 0&&delete n[o];return Object.keys(n)}In.subtract=ig;function Fk(e){for(var t=e.length,n={},r=0;r<t;r++){var o=e[r];for(var i in o)Tc.hasOwnProperty.call(o,i)&&o[i]!==void 0&&(n[i]=(n[i]||0)+1)}for(var i in n)n[i]<t&&delete n[i];return Object.keys(n)}In.intersection=Fk;function xV(e){return e.op==="add"}function bV(e){return e.op==="remove"}function Tp(e,t){return{operations:e.operations.concat(t),cost:e.cost+1}}function zk(e,t,n,r){r===void 0&&(r=bh);var o={"0,0":{operations:[],cost:0}};function i(d,f){var h="".concat(d,",").concat(f),m=o[h];if(m===void 0){if(d>0&&f>0&&!r(e[d-1],t[f-1],n.add(String(d-1))).length)m=i(d-1,f-1);else{var g=[];if(d>0){var v=i(d-1,f),S={op:"remove",index:d-1};g.push(Tp(v,S))}if(f>0){var y=i(d,f-1),b={op:"add",index:d-1,value:t[f-1]};g.push(Tp(y,b))}if(d>0&&f>0){var x=i(d-1,f-1),w={op:"replace",index:d-1,original:e[d-1],value:t[f-1]};g.push(Tp(x,w))}var j=g.sort(function(E,C){return E.cost-C.cost})[0];m=j}o[h]=m}return m}var a=isNaN(e.length)||e.length<=0?0:e.length,l=isNaN(t.length)||t.length<=0?0:t.length,c=i(a,l).operations,u=c.reduce(function(d,f){var h=d[0],m=d[1];if(xV(f)){var g=f.index+1+m,v=g<a+m?String(g):"-",S={op:f.op,path:n.add(v).toString(),value:f.value};return[h.concat(S),m+1]}else if(bV(f)){var S={op:f.op,path:n.add(String(f.index+m)).toString()};return[h.concat(S),m-1]}else{var y=n.add(String(f.index+m)),b=r(f.original,f.value,y);return[h.concat.apply(h,b),m]}},[[],0])[0];return u}In.diffArrays=zk;function Bk(e,t,n,r){r===void 0&&(r=bh);var o=[];return ig(e,t).forEach(function(i){o.push({op:"remove",path:n.add(i).toString()})}),ig(t,e).forEach(function(i){o.push({op:"add",path:n.add(i).toString(),value:t[i]})}),Fk([e,t]).forEach(function(i){o.push.apply(o,r(e[i],t[i],n.add(i)))}),o}In.diffObjects=Bk;function bh(e,t,n,r){if(r===void 0&&(r=bh),e===t)return[];var o=(0,Tc.objectType)(e),i=(0,Tc.objectType)(t);return o=="array"&&i=="array"?zk(e,t,n,r):o=="object"&&i=="object"?Bk(e,t,n,r):[{op:"replace",path:n.toString(),value:t}]}In.diffAny=bh;var Fx=a0&&a0.__extends||function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(r[i]=o[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}();Object.defineProperty(Ft,"__esModule",{value:!0});Ft.apply=Ft.InvalidOperationError=Ft.test=Ft.copy=Ft.move=Ft.replace=Ft.remove=Ft.add=Ft.TestError=Ft.MissingError=void 0;var Fo=au,zx=Lx,wV=In,ho=function(e){Fx(t,e);function t(n){var r=e.call(this,"Value required at path: ".concat(n))||this;return r.path=n,r.name="MissingError",r}return t}(Error);Ft.MissingError=ho;var Vk=function(e){Fx(t,e);function t(n,r){var o=e.call(this,"Test failed: ".concat(n," != ").concat(r))||this;return o.actual=n,o.expected=r,o.name="TestError",o}return t}(Error);Ft.TestError=Vk;function Bx(e,t,n){if(Array.isArray(e))if(t=="-")e.push(n);else{var r=parseInt(t,10);e.splice(r,0,n)}else e[t]=n}function Uk(e,t){if(Array.isArray(e)){var n=parseInt(t,10);e.splice(n,1)}else delete e[t]}function Hk(e,t){var n=Fo.Pointer.fromJSON(t.path).evaluate(e);return n.parent===void 0?new ho(t.path):(Bx(n.parent,n.key,(0,zx.clone)(t.value)),null)}Ft.add=Hk;function Wk(e,t){var n=Fo.Pointer.fromJSON(t.path).evaluate(e);return n.value===void 0?new ho(t.path):(Uk(n.parent,n.key),null)}Ft.remove=Wk;function qk(e,t){var n=Fo.Pointer.fromJSON(t.path).evaluate(e);if(n.parent===null)return new ho(t.path);if(Array.isArray(n.parent)){if(parseInt(n.key,10)>=n.parent.length)return new ho(t.path)}else if(n.value===void 0)return new ho(t.path);return n.parent[n.key]=(0,zx.clone)(t.value),null}Ft.replace=qk;function Gk(e,t){var n=Fo.Pointer.fromJSON(t.from).evaluate(e);if(n.value===void 0)return new ho(t.from);var r=Fo.Pointer.fromJSON(t.path).evaluate(e);return r.parent===void 0?new ho(t.path):(Uk(n.parent,n.key),Bx(r.parent,r.key,n.value),null)}Ft.move=Gk;function Qk(e,t){var n=Fo.Pointer.fromJSON(t.from).evaluate(e);if(n.value===void 0)return new ho(t.from);var r=Fo.Pointer.fromJSON(t.path).evaluate(e);return r.parent===void 0?new ho(t.path):(Bx(r.parent,r.key,(0,zx.clone)(n.value)),null)}Ft.copy=Qk;function Kk(e,t){var n=Fo.Pointer.fromJSON(t.path).evaluate(e);return(0,wV.diffAny)(n.value,t.value,new Fo.Pointer).length?new Vk(n.value,t.value):null}Ft.test=Kk;var Yk=function(e){Fx(t,e);function t(n){var r=e.call(this,"Invalid operation: ".concat(n.op))||this;return r.operation=n,r.name="InvalidOperationError",r}return t}(Error);Ft.InvalidOperationError=Yk;function SV(e,t){switch(t.op){case"add":return Hk(e,t);case"remove":return Wk(e,t);case"replace":return qk(e,t);case"move":return Gk(e,t);case"copy":return Qk(e,t);case"test":return Kk(e,t)}return new Yk(t)}Ft.apply=SV;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createTests=e.createPatch=e.applyPatch=e.Pointer=void 0;var t=au;Object.defineProperty(e,"Pointer",{enumerable:!0,get:function(){return t.Pointer}});var n=Ft,r=In;function o(u,d){return d.map(function(f){return(0,n.apply)(u,f)})}e.applyPatch=o;function i(u){function d(f,h,m){var g=u(f,h,m);return Array.isArray(g)?g:(0,r.diffAny)(f,h,m,d)}return d}function a(u,d,f){var h=new t.Pointer;return(f?i(f):r.diffAny)(u,d,h)}e.createPatch=a;function l(u,d){var f=t.Pointer.fromJSON(d).evaluate(u);if(f!==void 0)return{op:"test",path:d,value:f.value}}function c(u,d){var f=new Array;return d.filter(r.isDestructive).forEach(function(h){var m=l(u,h.path);if(m&&f.push(m),"from"in h){var g=l(u,h.from);g&&f.push(g)}}),f}e.createTests=c})(Lk);const jV="_root_w6lfx_1",CV="_removed_w6lfx_16",EV="_added_w6lfx_21",Pp={root:jV,removed:CV,added:EV};function TV(e){const t=ae(),{original:n,revised:r}=e,[o,i]=p.useState(!1);p.useEffect(()=>{t.requestSchema(e.original.resourceType).then(()=>i(!0)).catch(console.log)},[t,e.original.resourceType]);const a=p.useMemo(()=>{if(!o)return null;const l=[po(n)],c=[po(r)],u=[],d=PV(Lk.createPatch(n,r));for(const f of d){const h=f.path,m=kV(h),g=RV(n.resourceType,m),v=f.op==="add"?void 0:Cc(m,l),S=f.op==="remove"?void 0:Cc(m,c);u.push({key:`op-${f.op}-${f.path}`,name:`${Qt(f.op)} ${m}`,path:(g==null?void 0:g.path)??n.resourceType+"."+m,property:g,originalValue:aw(g,v),revisedValue:aw(g,S)})}return u},[o,n,r]);return a?s.jsxs(fe,{className:Pp.root,children:[s.jsx(fe.Thead,{children:s.jsxs(fe.Tr,{children:[s.jsx(fe.Th,{}),s.jsx(fe.Th,{children:"Before"}),s.jsx(fe.Th,{children:"After"})]})}),s.jsx(fe.Tbody,{children:a.map(l=>s.jsxs(fe.Tr,{children:[s.jsx(fe.Td,{children:l.name}),s.jsx(fe.Td,{className:Pp.removed,children:l.originalValue&&s.jsx(Gr,{path:l.path,property:l.property,propertyType:l.originalValue.type,value:l.originalValue.value,ignoreMissingValues:!0})}),s.jsx(fe.Td,{className:Pp.added,children:l.revisedValue&&s.jsx(Gr,{path:l.path,property:l.property,propertyType:l.revisedValue.type,value:l.revisedValue.value,ignoreMissingValues:!0})})]},l.key))})]}):null}function PV(e){const t=[];for(const n of e){const{op:r,path:o}=n;if(o.startsWith("/meta/author")||o.startsWith("/meta/compartment")||o.startsWith("/meta/lastUpdated")||o.startsWith("/meta/versionId"))continue;const i=e.filter(l=>l.op===r&&l.path===o).length,a={op:r,path:o};i>1&&(r==="add"||r==="remove")&&/\/[0-9-]+$/.test(o)&&(a.op="replace",a.path=o.replace(/\/[^/]+$/,"")),t.some(l=>l.op===a.op&&l.path===a.path)||t.push(a)}return t}function kV(e){const t=e.split("/").filter(Boolean);let n="";for(let r=0;r<t.length;r++){const o=t[r];o==="-"?n+=".last()":/^\d+$/.test(o)?n+=`[${o}]`:(r>0&&(n+="."),n+=o)}return n.endsWith(".url")&&(n=n.replace(/\.url$/,"")),n}function RV(e,t){var r;const n=ll(e,{resourceType:"SearchParameter",base:[e],code:e+"."+t,expression:e+"."+t});return(r=n==null?void 0:n.elementDefinitions)==null?void 0:r[0]}function aw(e,t){return t&&{type:Array.isArray(t)?t[0].type:t.type,value:_V(t,!!(e!=null&&e.isArray))}}function _V(e,t){const n=z7(e).flatMap(r=>r.value);return t?n:n[0]}function Vx(e){const{profileUrl:t}=e,n=ae(),r=n.getAccessPolicy(),o=xt(e.value),[i,a]=p.useState();p.useEffect(()=>{if(o)if(t)n.requestProfileSchema(t,{expandProfile:!0}).then(()=>{const c=Ls(t);c?a(c.name):console.error(`Schema not found for ${t}`)}).catch(c=>{console.error("Error in requestProfileSchema",c)});else{const c=o.resourceType;n.requestSchema(c).then(()=>{a(c)}).catch(console.error)}},[n,t,o]);const l=p.useMemo(()=>o&&WP(o,gx.READ,r),[r,o]);return!i||!o?null:s.jsx(tf,{path:o.resourceType,value:{type:i,value:e.forceUseInput?e.value:o},profileUrl:t,ignoreMissingValues:e.ignoreMissingValues,accessPolicyResource:l})}const DV="_item_5q6yx_1",IV="_itemPadding_5q6yx_5",lw={item:DV,itemPadding:IV};function AV(e){return s.jsx(su,{children:e.children})}function js(e){var c,u;const{resource:t,profile:n,padding:r,popupMenuItems:o,...i}=e,a=n??((c=t.meta)==null?void 0:c.author),l=e.dateTime??((u=t.meta)==null?void 0:u.lastUpdated);return s.jsxs($x,{"data-testid":"timeline-item",fill:!0,...i,children:[s.jsxs(J,{justify:"space-between",gap:8,mx:"xs",my:"sm",children:[s.jsx(zi,{value:a,link:!0,size:"md"}),s.jsxs("div",{style:{flex:1},children:[s.jsx(he,{size:"sm",children:s.jsx(fl,{c:"dark",fw:500,value:a,link:!0})}),s.jsxs(he,{size:"xs",children:[s.jsx(Ge,{c:"dimmed",to:e.resource,children:Mn(l)}),s.jsx(he,{component:"span",c:"dimmed",mx:8,children:"·"}),s.jsx(Ge,{c:"dimmed",to:e.resource,children:e.resource.resourceType})]})]}),o&&s.jsxs(ne,{position:"bottom-end",shadow:"md",width:200,children:[s.jsx(ne.Target,{children:s.jsx(nn,{color:"gray",variant:"subtle",radius:"xl","aria-label":`Actions for ${Ct(e.resource)}`,children:s.jsx(R8,{})})}),o]})]}),s.jsx(pk,{children:s.jsx("div",{className:rt(lw.item,{[lw.itemPadding]:r}),children:e.children})})]})}function Xk(e,t){e.sort((n,r)=>{const o=cw(n,t),i=cw(r,t);return o>i?1:o<i?-1:uw(n,t)-uw(r,t)})}function cw(e,t){if(!Jk(e,t)){const n=e.priority;if(typeof n=="string")return{stat:4,asap:3,urgent:2}[n]??0}return 0}function uw(e,t){var r;if(!Jk(e,t)){if(e.resourceType==="Communication"&&e.sent)return new Date(e.sent).getTime();if((e.resourceType==="DiagnosticReport"||e.resourceType==="Media"||e.resourceType==="Observation")&&e.issued)return new Date(e.issued).getTime();if(e.resourceType==="DocumentReference"&&e.date)return new Date(e.date).getTime()}const n=(r=e.meta)==null?void 0:r.lastUpdated;return n?new Date(n).getTime():0}function Jk(e,t){return!!t&&e.resourceType===t.resourceType&&e.id===t.id}const NV="_pinnedComment_5uxzi_2",MV={pinnedComment:NV};function wh(e){const t=ae(),n=gh(),r=t.getProfile(),o=p.useRef(null),i=xt(e.value),[a,l]=p.useState(),[c,u]=p.useState([]),d=e.loadTimelineResources,f=p.useRef(c);f.current=c;const h=p.useCallback(D=>{Xk(D,i),D.reverse(),u(D)},[i]),m=p.useCallback(D=>{const M=[];for(const I of D){if(I.status!=="fulfilled")continue;const L=I.value;if(L.type==="history"&&l(L),L.entry)for(const A of L.entry)M.push(A.resource)}h(M)},[h]),g=p.useCallback(D=>h([...f.current,D]),[h]),v=p.useCallback(()=>{var I;let D,M;"resourceType"in e.value?(D=e.value.resourceType,M=e.value.id):[D,M]=(I=e.value.reference)==null?void 0:I.split("/"),d(t,D,M).then(m).catch(console.error)},[t,e.value,d,m]);p.useEffect(()=>v(),[v]);function S(D){!i||!e.createCommunication||t.createResource(e.createCommunication(i,r,D)).then(M=>g(M)).catch(console.error)}function y(D){!i||!e.createMedia||t.createResource(e.createMedia(i,r,D)).then(M=>g(M)).then(()=>Ol({id:"upload-notification",color:"teal",title:"Upload complete",message:"",icon:s.jsx(eu,{size:16}),autoClose:2e3})).catch(M=>Ol({id:"upload-notification",color:"red",title:"Upload error",message:Me(M),icon:s.jsx(Jb,{size:16}),autoClose:2e3}))}function b(D,M){return t.updateResource({...D,priority:M})}function x(D){b(D,"stat").then(v).catch(console.error)}function w(D){b(D,"routine").then(v).catch(console.error)}function j(D){n(`/${D.resourceType}/${D.id}`)}function E(D){n(`/${D.resourceType}/${D.id}/edit`)}function C(D){n(`/${D.resourceType}/${D.id}/delete`)}function T(D){var M;n(`/${D.resourceType}/${D.id}/_history/${(M=D.meta)==null?void 0:M.versionId}`)}function _(){ye({id:"upload-notification",loading:!0,title:"Initializing upload...",message:"Please wait...",autoClose:!1,withCloseButton:!1})}function k(D){Ol({id:"upload-notification",loading:!0,title:"Uploading...",message:VV(D),autoClose:!1,withCloseButton:!1})}function N(D){Ol({id:"upload-notification",color:"red",title:"Upload error",message:Me(D),icon:s.jsx(Jb,{size:16}),autoClose:2e3})}return i?s.jsxs(AV,{children:[e.createCommunication&&s.jsx($x,{children:s.jsx(Ke,{testid:"timeline-form",onSubmit:D=>{S(D.text);const M=o.current;M&&(M.value="",M.focus())},children:s.jsxs(J,{gap:"xs",wrap:"nowrap",style:{width:"100%"},children:[s.jsx(zi,{value:r}),s.jsx(me,{name:"text",ref:o,placeholder:"Add comment",style:{width:"100%",maxWidth:300}}),s.jsx(nn,{type:"submit",radius:"xl",color:"blue",variant:"filled",children:s.jsx(F8,{size:16})}),s.jsx(_x,{securityContext:jt(i),onUpload:y,onUploadStart:_,onUploadProgress:k,onUploadError:N,children:D=>s.jsx(nn,{...D,radius:"xl",color:"blue",variant:"filled",children:s.jsx(Sx,{size:16})})})]})})}),c.map(D=>{var I;if(!D)return null;const M=`${D.resourceType}/${D.id}/${(I=D.meta)==null?void 0:I.versionId}`;if(D.resourceType===i.resourceType&&D.id===i.id)return s.jsx(OV,{history:a,resource:D,onDetails:T},M);switch(D.resourceType){case"AuditEvent":return s.jsx(zV,{resource:D,onDetails:j},M);case"Communication":return s.jsx(LV,{resource:D,onPin:D.priority!=="stat"?x:void 0,onUnpin:D.priority==="stat"?w:void 0,onDetails:j,onEdit:E,onDelete:C},M);case"DiagnosticReport":return s.jsx(BV,{resource:D,onDetails:j,onEdit:E,onDelete:C},M);case"Media":return s.jsx(FV,{resource:D,onDetails:j,onEdit:E,onDelete:C},M);default:return s.jsx(js,{resource:D,padding:!0,children:s.jsx(Vx,{value:D,ignoreMissingValues:!0})},M)}})]}):s.jsx(fn,{style:{width:"100%",height:"100%"},children:s.jsx(Kn,{})})}function Ga(e){return s.jsxs(ne.Dropdown,{children:[s.jsx(ne.Label,{children:"Resource"}),e.onPin&&s.jsx(ne.Item,{leftSection:s.jsx(V8,{size:14}),onClick:()=>e.onPin(e.resource),"aria-label":`Pin ${Ct(e.resource)}`,children:"Pin"}),e.onUnpin&&s.jsx(ne.Item,{leftSection:s.jsx(U8,{size:14}),onClick:()=>e.onUnpin(e.resource),"aria-label":`Unpin ${Ct(e.resource)}`,children:"Unpin"}),e.onDetails&&s.jsx(ne.Item,{leftSection:s.jsx(M8,{size:14}),onClick:()=>e.onDetails(e.resource),"aria-label":`Details ${Ct(e.resource)}`,children:"Details"}),e.onEdit&&s.jsx(ne.Item,{leftSection:s.jsx(_8,{size:14}),onClick:()=>e.onEdit(e.resource),"aria-label":`Edit ${Ct(e.resource)}`,children:"Edit"}),e.onDelete&&s.jsxs(s.Fragment,{children:[s.jsx(ne.Divider,{}),s.jsx(ne.Label,{children:"Danger zone"}),s.jsx(ne.Item,{color:"red",leftSection:s.jsx(hk,{size:14}),onClick:()=>e.onDelete(e.resource),"aria-label":`Delete ${Ct(e.resource)}`,children:"Delete"})]})]})}function OV(e){const t=$V(e.history,e.resource);return t?s.jsx(js,{resource:e.resource,padding:!0,popupMenuItems:s.jsx(Ga,{...e}),children:s.jsx(TV,{original:t,revised:e.resource})}):s.jsxs(js,{resource:e.resource,padding:!0,popupMenuItems:s.jsx(Ga,{...e}),children:[s.jsx("h3",{children:"Created"}),s.jsx(Vx,{value:e.resource,ignoreMissingValues:!0,forceUseInput:!0})]})}function $V(e,t){const n=e.entry,r=n.findIndex(o=>{var i,a,l;return((a=(i=o.resource)==null?void 0:i.meta)==null?void 0:a.versionId)===((l=t.meta)==null?void 0:l.versionId)});if(!(r>=n.length-1))return n[r+1].resource}function LV(e){var r,o;const n=!e.resource.priority||e.resource.priority==="routine"?void 0:MV.pinnedComment;return s.jsx(js,{resource:e.resource,profile:e.resource.sender,dateTime:e.resource.sent,padding:!0,className:n,popupMenuItems:s.jsx(Ga,{...e}),children:s.jsx("p",{children:(o=(r=e.resource.payload)==null?void 0:r[0])==null?void 0:o.contentString})})}function FV(e){var r;const t=(r=e.resource.content)==null?void 0:r.contentType,n=t&&!t.startsWith("image/")&&!t.startsWith("video/")&&t!=="application/pdf";return s.jsx(js,{resource:e.resource,padding:!!n,popupMenuItems:s.jsx(Ga,{...e}),children:s.jsx(ru,{value:e.resource.content})})}function zV(e){return s.jsx(js,{resource:e.resource,padding:!0,popupMenuItems:s.jsx(Ga,{...e}),children:s.jsx(kr,{children:s.jsx("pre",{children:e.resource.outcomeDesc})})})}function BV(e){return s.jsx(js,{resource:e.resource,padding:!0,popupMenuItems:s.jsx(Ga,{...e}),children:s.jsx(Ox,{value:e.resource})})}function VV(e){if(e.lengthComputable){const t=100*e.loaded/e.total;return`Uploaded: ${kp(e.loaded)} / ${kp(e.total)} ${t.toFixed(2)}%`}return`Uploaded: ${kp(e.loaded)}`}function kp(e){if(e===0)return"0.00 B";const t=Math.floor(Math.log(e)/Math.log(1024));return(e/Math.pow(1024,t)).toFixed(2)+" "+" KMGTP".charAt(t)+"B"}function UV(e){return s.jsx(wh,{value:e.resource,loadTimelineResources:async(t,n,r)=>{const o=`${n}/${r}`;return Promise.allSettled([t.readHistory(n,r),t.search("Task",{_filter:`based-on eq ${o} or focus eq ${o} or subject eq ${o}`,_count:100})])}})}function Ie(e){const{children:t,...n}=e;return s.jsx(su,{children:s.jsx($x,{...n,children:t})})}function HV(e){return s.jsx(wh,{value:e.encounter,loadTimelineResources:async(t,n,r)=>Promise.allSettled([t.readHistory("Encounter",r),t.search("Communication","encounter=Encounter/"+r),t.search("Media","encounter=Encounter/"+r)]),createCommunication:(t,n,r)=>({resourceType:"Communication",status:"completed",encounter:jt(t),subject:t.subject,sender:jt(n),sent:new Date().toISOString(),payload:[{contentString:r}]}),createMedia:(t,n,r)=>({resourceType:"Media",status:"completed",encounter:jt(t),subject:t.subject,operator:jt(n),issued:new Date().toISOString(),content:r})})}function WV(e){let t;try{t=al(e.path,e.resource)}catch(n){return console.warn("FhirPathDisplay:",n),null}if(t.length>1)throw new Error(`Component "path" for "FhirPathDisplay" must resolve to a single element. Received ${t.length} elements [${JSON.stringify(t,null,2)}]`);return s.jsx(Gr,{value:t[0]||"",propertyType:e.propertyType})}function qV(e){return s.jsxs(En,{title:"Export",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:e.onCancel,children:[s.jsxs(W,{display:"flex",style:{justifyContent:"space-between"},children:[e.exportCsv&&s.jsx(dw,{text:"CSV",exportLogic:e.exportCsv,onCancel:e.onCancel}),e.exportTransactionBundle&&s.jsx(dw,{text:"Transaction Bundle",exportLogic:e.exportTransactionBundle,onCancel:e.onCancel})]}),s.jsx(he,{style:{marginTop:"10px",marginLeft:"2px"},children:"Limited to 1000 records"})]})}function dw(e){return s.jsx(re,{onClick:()=>{e.exportLogic(),e.onCancel()},children:`Export as ${e.text}`})}const GV={string:[te.EQUALS,te.NOT,te.CONTAINS,te.EXACT],fulltext:[te.EQUALS,te.NOT,te.CONTAINS,te.EXACT],token:[te.EQUALS,te.NOT],reference:[te.EQUALS,te.NOT],numeric:[te.EQUALS,te.NOT_EQUALS,te.GREATER_THAN,te.LESS_THAN,te.GREATER_THAN_OR_EQUALS,te.LESS_THAN_OR_EQUALS],quantity:[te.EQUALS,te.NOT_EQUALS,te.GREATER_THAN,te.LESS_THAN,te.GREATER_THAN_OR_EQUALS,te.LESS_THAN_OR_EQUALS],date:[te.EQUALS,te.NOT_EQUALS,te.GREATER_THAN,te.LESS_THAN,te.GREATER_THAN_OR_EQUALS,te.LESS_THAN_OR_EQUALS,te.STARTS_AFTER,te.ENDS_BEFORE,te.APPROXIMATELY],datetime:[te.EQUALS,te.NOT_EQUALS,te.GREATER_THAN,te.LESS_THAN,te.GREATER_THAN_OR_EQUALS,te.LESS_THAN_OR_EQUALS,te.STARTS_AFTER,te.ENDS_BEFORE,te.APPROXIMATELY]},QV={eq:"equals",ne:"not equals",gt:"greater than",lt:"less than",ge:"greater than or equals",le:"less than or equals",sa:"starts after",eb:"ends before",ap:"approximately",contains:"contains",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"};function Ux(e,t){return{...e,filters:t,offset:0,name:void 0}}function Zk(e,t){return Ux(e,(e.filters??[]).filter(n=>n.code!==t))}function Sh(e,t,n,r,o){const i=[];return e.filters&&i.push(...e.filters),i.push({code:t,operator:n,value:r??""}),Ux(e,i)}function KV(e,t){if(!e.filters)return e;const n=[...e.filters];return n.splice(t,1),{...e,filters:n,name:void 0}}function YV(e,t){return Hx(e,t,-1)}function XV(e,t){return Hx(e,t,0)}function JV(e,t){return Hx(e,t,1)}function Hx(e,t,n){const r=new Date;r.setDate(r.getDate()+n),r.setHours(0,0,0,0);const o=new Date(r.getTime());return o.setDate(o.getDate()+1),o.setTime(o.getTime()-1),qx(e,t,r,o)}function ZV(e,t){return Wx(e,t,-1)}function eU(e,t){return Wx(e,t,0)}function tU(e,t){return Wx(e,t,1)}function Wx(e,t,n){const r=new Date;r.setMonth(r.getMonth()+n),r.setDate(1),r.setHours(0,0,0,0);const o=new Date(r.getTime());return o.setMonth(o.getMonth()+1),o.setDate(1),o.setHours(0,0,0,0),o.setTime(o.getTime()-1),qx(e,t,r,o)}function nU(e,t){const n=new Date;return n.setMonth(0),n.setDate(1),n.setHours(0,0,0,0),qx(e,t,n,new Date)}function qx(e,t,n,r){return e=Zk(e,t),e=fw(e,t,te.GREATER_THAN_OR_EQUALS,n),e=fw(e,t,te.LESS_THAN_OR_EQUALS,r),e}function fw(e,t,n,r){return Sh(e,t,n,r.toISOString())}function hw(e,t,n=!0){return Sh(e,t,te.MISSING,n.toString())}function rU(e,t){return e.offset===t?e:{...e,offset:t,name:void 0}}function oU(e,t){const n=e.count??hh,r=(t-1)*n;return rU(e,r)}function iU(e,t,n){return t===sU(e)&&n!==void 0&&n===aU(e)?e:{...e,sortRules:[{code:t,descending:!!n}],name:void 0}}function sU(e){const t=e.sortRules;if(!t||t.length===0)return;const n=t[0].code;return n.startsWith("-")?n.substr(1):n}function aU(e){const t=e.sortRules;return!t||t.length===0?!1:!!t[0].descending}function lU(e){return GV[e.type]}function Gx(e){return QV[e]??""}function Ii(e){let t=e;return t.includes(".")&&(t=t.split(".").pop()),t==="versionId"?"Version ID":(t=t.replace("[x]",""),t=t.replace(/([A-Z])/g," $1"),t=t.replace(/[-_]/g," "),t=t.replace(/\s+/g," "),t=t.trim(),t.toLowerCase()==="id"?"ID":t.split(/\s/).map(Qt).join(" "))}function cU(e,t){var r,o;const n=t.name;return n==="id"?e.id:n==="meta.versionId"?(r=e.meta)==null?void 0:r.versionId:n==="_lastUpdated"?Mn((o=e.meta)==null?void 0:o.lastUpdated):t.elementDefinition&&`${e.resourceType}.${t.name}`===t.elementDefinition.path?uU(e,t.elementDefinition):t.searchParams&&t.searchParams.length===1&&t.name===t.searchParams[0].code?dU(e,t.searchParams[0]):null}function uU(e,t){var i,a,l;const n=((l=(a=(i=t.path)==null?void 0:i.split("."))==null?void 0:a.pop())==null?void 0:l.replaceAll("[x]",""))??"",[r,o]=ou({type:e.resourceType,value:e},n);return r?s.jsx(Gr,{path:t.path,property:t,propertyType:o,value:r,maxWidth:200,ignoreMissingValues:!0,link:!1}):null}function dU(e,t){const n=Cc(t.expression,[{type:e.resourceType,value:e}]);return!n||n.length===0?null:s.jsx(s.Fragment,{children:n.map((r,o)=>s.jsx(Gr,{propertyType:r.type,value:r.value,maxWidth:200,ignoreMissingValues:!0,link:!1},`${o}-${n.length}`))})}function fU(e){const t=p.useRef(!1),[n,r]=p.useState({search:JSON.parse(lr(e.search))}),[o,i]=p.useState(!1);p.useEffect(()=>{r({search:e.search})},[e.search]);const a=p.useMemo(()=>{if(!e.visible)return[];const c=e.search.resourceType,u=bP(c),d=ax(c);return wc(hU(u,d)).map(f=>({value:f,label:Ii(f)}))},[e.visible,e.search.resourceType]);if(!e.visible)return null;function l(c){r({search:{...n.search,fields:c}})}return s.jsx(En,{title:"Fields",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:()=>{e.onCancel()},size:"auto",withOverlay:!0,closeOnClickOutside:!1,overlayProps:{onMouseDownCapture:()=>{t.current=o},onClick:()=>{t.current||e.onCancel(),t.current=!1},children:s.jsx("div",{"data-testid":"overlay-child"})},children:s.jsxs(Ne,{children:[s.jsx(eh,{style:{width:550},placeholder:"Select fields to display",data:a,value:n.search.fields??[],onChange:l,onDropdownOpen:()=>i(!0),onDropdownClose:()=>i(!1),maxDropdownHeight:"250px",clearButtonProps:{"aria-label":"Clear selection"},clearable:!0,searchable:!0}),s.jsx(J,{justify:"flex-end",children:s.jsx(re,{onClick:()=>e.onOk(n.search),children:"OK"})})]})})}function hU(e,t){const n=[],r=new Set,o=new Set;for(const i of Object.keys(e.elements))n.push(i),r.add(i.toLowerCase()),o.add(Ii(i));if(t)for(const i of Object.keys(t)){const a=Ii(i);!r.has(i)&&!o.has(a)&&(n.push(i),r.add(i),o.add(a))}return n}function eR(e){var o;const{resourceType:t,filter:n}=e,r=(o=go.types[t].searchParams)==null?void 0:o[n.code];if(r){if(r.type==="reference"&&(n.operator===te.EQUALS||n.operator===te.NOT_EQUALS))return s.jsx(fl,{value:{reference:n.value}});const i=ll(t,r);if(n.code==="_lastUpdated"||i.type===Co.DATETIME)return s.jsx(s.Fragment,{children:Mn(n.value)})}return s.jsx(s.Fragment,{children:n.value})}function tR(e){const t=ll(e.resourceType,e.searchParam),n="filter-value";switch(t.type){case Co.REFERENCE:return s.jsx(xh,{name:n,defaultValue:e.defaultValue?{reference:e.defaultValue}:void 0,targetTypes:e.searchParam.target,autoFocus:e.autoFocus,onChange:r=>{r?e.onChange(r.reference):e.onChange("")}});case Co.BOOLEAN:return s.jsx(Xn,{name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultChecked:e.defaultValue==="true",autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.checked.toString())});case Co.DATE:return s.jsx(me,{type:"date",name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value)});case Co.DATETIME:return s.jsx(ws,{name:n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:e.onChange});case Co.NUMBER:return s.jsx(me,{type:"number",name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value)});case Co.QUANTITY:return s.jsx(Ss,{name:n,path:"",defaultValue:pU(e.defaultValue),autoFocus:e.autoFocus,onChange:r=>{r?e.onChange(`${r.value}`):e.onChange("")}});default:return s.jsx(me,{name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value),placeholder:"Search value"})}}function pU(e){if(e){const[t,n,r]=e.split("|");if(t)return{value:parseFloat(t),system:n,unit:r}}}function mU(e){const[t,n]=p.useState(JSON.parse(lr(e.search))),[r,o]=p.useState(-1),i=p.useRef(t);i.current=t,p.useEffect(()=>{n(JSON.parse(lr(e.search)))},[e.search]);function a(d){n(Sh(i.current,d.code,d.operator,d.value))}if(!e.visible)return null;const l=e.search.resourceType,c=ax(l)??{},u=t.filters||[];return s.jsxs(En,{title:"Filters",closeButtonProps:{"aria-label":"Close"},size:900,opened:e.visible,onClose:e.onCancel,children:[s.jsx("div",{children:s.jsxs("table",{children:[s.jsxs("colgroup",{children:[s.jsx("col",{style:{width:200}}),s.jsx("col",{style:{width:200}}),s.jsx("col",{style:{width:380}}),s.jsx("col",{style:{width:120}})]}),s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Field"}),s.jsx("th",{children:"Operation"}),s.jsx("th",{children:"Value"}),s.jsx("th",{children:"Actions"})]})}),s.jsxs("tbody",{children:[u.map((d,f)=>f===r?s.jsx(pw,{resourceType:l,searchParams:c,defaultValue:d,okText:"Save",onOk:h=>{const m=[...u];m[f]=h,n(Ux(i.current,m)),o(-1)},onCancel:()=>o(-1)},`filter-${d.code}-${d.operator}-${d.value}-input`):s.jsx(gU,{resourceType:l,filter:d,onEdit:()=>o(f),onDelete:()=>n(KV(i.current,f))},`filter-${d.code}-${d.operator}-${d.value}-display`)),s.jsx(pw,{resourceType:l,searchParams:c,okText:"Add",onOk:a})]})]})}),s.jsx(J,{justify:"flex-end",mt:"xl",children:s.jsx(re,{onClick:()=>e.onOk(i.current),children:"OK"})})]})}function gU(e){const{filter:t}=e;return s.jsxs("tr",{children:[s.jsx("td",{children:Ii(t.code)}),s.jsx("td",{children:Gx(t.operator)}),s.jsx("td",{children:s.jsx(eR,{resourceType:e.resourceType,filter:t})}),s.jsxs("td",{children:[s.jsx(re,{size:"compact-md",variant:"outline",onClick:e.onEdit,children:"Edit"}),s.jsx(re,{size:"compact-md",variant:"outline",onClick:e.onDelete,children:"Delete"})]})]})}function pw(e){const[t,n]=p.useState(e.defaultValue??{}),r=p.useRef(t);r.current=t;function o(u){n({...r.current,code:u})}function i(u){n({...r.current,operator:u})}function a(u){n({...r.current,value:u})}const l=e.searchParams[t.code],c=l&&lU(l);return s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx(kt,{"data-testid":"filter-field",defaultValue:r.current.code,onChange:u=>o(u.currentTarget.value),data:["",...Object.keys(e.searchParams).map(u=>({value:u,label:Ii(u)}))]})}),s.jsx("td",{children:c&&s.jsx(kt,{"data-testid":"filter-operation",defaultValue:t.operator,onChange:u=>i(u.currentTarget.value),data:["",...c.map(u=>({value:u,label:Gx(u)}))]})}),s.jsx("td",{children:l&&t.operator&&s.jsx(tR,{resourceType:e.resourceType,searchParam:l,defaultValue:t.value,onChange:a})}),s.jsxs("td",{children:[t.code&&t.operator&&s.jsx(re,{size:"compact-md",variant:"outline",onClick:()=>{e.onOk(r.current),n({})},children:e.okText}),e.onCancel&&s.jsx(re,{size:"compact-md",variant:"outline",onClick:e.onCancel,children:"Cancel"})]})]})}function vU(e){const[t,n]=p.useState(e.defaultValue??"");if(!e.visible||!e.searchParam||!e.filter)return null;function r(){e.onOk({...e.filter,value:t})}return s.jsx(En,{title:e.title,size:"xl",opened:e.visible,onClose:e.onCancel,children:s.jsx(Ke,{onSubmit:r,children:s.jsxs(or,{children:[s.jsx(or.Col,{span:10,children:s.jsx(tR,{resourceType:e.resourceType,searchParam:e.searchParam,defaultValue:t,autoFocus:!0,onChange:n})}),s.jsx(or.Col,{span:2,children:s.jsx(re,{onClick:r,fullWidth:!0,children:"OK"})})]})})})}function yU(e){if(!e.searchParams)return null;function t(i,a){o(iU(e.search,i.code,a))}function n(i){o(Zk(e.search,i.code))}function r(i,a){e.onPrompt(i,{code:i.code,operator:a,value:""})}function o(i){e.onChange(i)}return e.searchParams.length===1?s.jsx(xU,{search:e.search,searchParam:e.searchParams[0],onSort:t,onPrompt:r,onChange:o,onClear:n}):s.jsx(ne.Dropdown,{children:e.searchParams.map(i=>s.jsx(ne.Item,{children:Ii(i.code)},i.code))})}function xU(e){switch(e.searchParam.type){case"date":return s.jsx(bU,{...e});case"number":case"quantity":return s.jsx(wU,{...e});case"reference":return s.jsx(SU,{...e});case"string":return s.jsx(jU,{...e});case"token":case"uri":return s.jsx(CU,{...e});default:return s.jsxs(s.Fragment,{children:["Unknown search param type: ",e.searchParam.type]})}}function bU(e){const{searchParam:t}=e,n=t.code;return s.jsxs(ne.Dropdown,{children:[s.jsx(ne.Item,{leftSection:s.jsx(jx,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort Oldest to Newest"}),s.jsx(ne.Item,{leftSection:s.jsx(Cx,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Newest to Oldest"}),s.jsx(ne.Divider,{}),s.jsx(ne.Item,{leftSection:s.jsx(nu,{size:14}),onClick:()=>e.onPrompt(t,te.EQUALS),children:"Equals..."}),s.jsx(ne.Item,{leftSection:s.jsx(tu,{size:14}),onClick:()=>e.onPrompt(t,te.NOT_EQUALS),children:"Does not equal..."}),s.jsx(ne.Divider,{}),s.jsx(ne.Item,{leftSection:s.jsx(fk,{size:14}),onClick:()=>e.onPrompt(t,te.ENDS_BEFORE),children:"Before..."}),s.jsx(ne.Item,{leftSection:s.jsx(dk,{size:14}),onClick:()=>e.onPrompt(t,te.STARTS_AFTER),children:"After..."}),s.jsx(ne.Item,{leftSection:s.jsx(b8,{size:14}),onClick:()=>e.onPrompt(t,te.EQUALS),children:"Between..."}),s.jsx(ne.Divider,{}),s.jsx(ne.Item,{leftSection:s.jsx(Wi,{size:14}),onClick:()=>e.onChange(JV(e.search,n)),children:"Tomorrow"}),s.jsx(ne.Item,{leftSection:s.jsx(Wi,{size:14}),onClick:()=>e.onChange(XV(e.search,n)),children:"Today"}),s.jsx(ne.Item,{leftSection:s.jsx(Wi,{size:14}),onClick:()=>e.onChange(YV(e.search,n)),children:"Yesterday"}),s.jsx(ne.Divider,{}),s.jsx(ne.Item,{leftSection:s.jsx(Wi,{size:14}),onClick:()=>e.onChange(tU(e.search,n)),children:"Next Month"}),s.jsx(ne.Item,{leftSection:s.jsx(Wi,{size:14}),onClick:()=>e.onChange(eU(e.search,n)),children:"This Month"}),s.jsx(ne.Item,{leftSection:s.jsx(Wi,{size:14}),onClick:()=>e.onChange(ZV(e.search,n)),children:"Last Month"}),s.jsx(ne.Divider,{}),s.jsx(ne.Item,{leftSection:s.jsx(Wi,{size:14}),onClick:()=>e.onChange(nU(e.search,n)),children:"Year to date"}),s.jsx(lu,{...e})]})}function wU(e){const{searchParam:t}=e;return s.jsxs(ne.Dropdown,{children:[s.jsx(ne.Item,{leftSection:s.jsx(jx,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort Smallest to Largest"}),s.jsx(ne.Item,{leftSection:s.jsx(Cx,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Largest to Smallest"}),s.jsx(ne.Divider,{}),s.jsx(ne.Item,{leftSection:s.jsx(nu,{size:14}),onClick:()=>e.onPrompt(t,te.EQUALS),children:"Equals..."}),s.jsx(ne.Item,{leftSection:s.jsx(tu,{size:14}),onClick:()=>e.onPrompt(t,te.NOT_EQUALS),children:"Does not equal..."}),s.jsx(ne.Divider,{}),s.jsx(ne.Item,{leftSection:s.jsx(dk,{size:14}),onClick:()=>e.onPrompt(t,te.GREATER_THAN),children:"Greater than..."}),s.jsx(ne.Item,{leftSection:s.jsx(rg,{size:14}),onClick:()=>e.onPrompt(t,te.GREATER_THAN_OR_EQUALS),children:"Greater than or equal to..."}),s.jsx(ne.Item,{leftSection:s.jsx(fk,{size:14}),onClick:()=>e.onPrompt(t,te.LESS_THAN),children:"Less than..."}),s.jsx(ne.Item,{leftSection:s.jsx(rg,{size:14}),onClick:()=>e.onPrompt(t,te.LESS_THAN_OR_EQUALS),children:"Less than or equal to..."}),s.jsx(lu,{...e})]})}function SU(e){const{searchParam:t}=e;return s.jsxs(ne.Dropdown,{children:[s.jsx(ne.Item,{leftSection:s.jsx(nu,{size:14}),onClick:()=>e.onPrompt(t,te.EQUALS),children:"Equals..."}),s.jsx(ne.Item,{leftSection:s.jsx(tu,{size:14}),onClick:()=>e.onPrompt(t,te.NOT),children:"Does not equal..."}),s.jsx(lu,{...e})]})}function jU(e){const{searchParam:t}=e;return s.jsxs(ne.Dropdown,{children:[s.jsx(ne.Item,{leftSection:s.jsx(jx,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort A to Z"}),s.jsx(ne.Item,{leftSection:s.jsx(Cx,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Z to A"}),s.jsx(ne.Divider,{}),s.jsx(ne.Item,{leftSection:s.jsx(nu,{size:14}),onClick:()=>e.onPrompt(t,te.EQUALS),children:"Equals..."}),s.jsx(ne.Item,{leftSection:s.jsx(tu,{size:14}),onClick:()=>e.onPrompt(t,te.NOT),children:"Does not equal..."}),s.jsx(ne.Divider,{}),s.jsx(ne.Item,{leftSection:s.jsx(j8,{size:14}),onClick:()=>e.onPrompt(t,te.CONTAINS),children:"Contains..."}),s.jsx(ne.Item,{leftSection:s.jsx(S8,{size:14}),onClick:()=>e.onPrompt(t,te.EQUALS),children:"Does not contain..."}),s.jsx(lu,{...e})]})}function CU(e){const{searchParam:t}=e;return s.jsxs(ne.Dropdown,{children:[s.jsx(ne.Item,{leftSection:s.jsx(nu,{size:14}),onClick:()=>e.onPrompt(t,te.EQUALS),children:"Equals..."}),s.jsx(ne.Item,{leftSection:s.jsx(tu,{size:14}),onClick:()=>e.onPrompt(t,te.NOT),children:"Does not equal..."}),s.jsx(lu,{...e})]})}function lu(e){const{searchParam:t}=e,n=t.code;return s.jsxs(s.Fragment,{children:[s.jsx(ne.Divider,{}),s.jsx(ne.Item,{leftSection:s.jsx(y8,{size:14}),onClick:()=>e.onChange(hw(e.search,n)),children:"Missing"}),s.jsx(ne.Item,{leftSection:s.jsx(v8,{size:14}),onClick:()=>e.onChange(hw(e.search,n,!1)),children:"Not missing"}),s.jsx(ne.Divider,{}),s.jsx(ne.Item,{leftSection:s.jsx(Zd,{size:14}),onClick:()=>e.onClear(t),children:"Clear filters"})]})}const EU="_root_vlout_1",TU="_table_vlout_8",PU="_tr_vlout_12",kU="_th_vlout_18",RU="_control_vlout_22",_U="_icon_vlout_31",Pl={root:EU,table:TU,tr:PU,th:kU,control:RU,icon:_U};function DU(e){const t=e.resourceType,n=[];for(const r of e.fields||["id","_lastUpdated"])n.push(IU(t,r));return n}function IU(e,t){var o;if(t==="_lastUpdated")return{name:"_lastUpdated",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_lastUpdated",name:"_lastUpdated",type:"date",expression:"Resource.meta.lastUpdated"}]};if(t==="meta.versionId")return{name:"meta.versionId",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_versionId",name:"_versionId",type:"token",expression:"Resource.meta.versionId"}]};const n=zs(e,t),r=o6(e,t.toLowerCase());if(n&&r)return{name:t,elementDefinition:n,searchParams:[r]};if(n){const i=ax(e);let a;if(i){const l=new RegExp(`${e}\\.${t.replaceAll("[x]","")}([^\\w-]|$)`);a=Object.values(i).filter(c=>!!c.expression&&l.test(c==null?void 0:c.expression)),a.length===0&&(a=void 0)}return{name:t,elementDefinition:n,searchParams:a}}if(r){const i=ll(e,r);return{name:t,elementDefinition:(o=i.elementDefinitions)==null?void 0:o[0],searchParams:[r]}}return{name:t}}class AU extends Event{constructor(t){super("change"),this.definition=t}}class NU extends Event{constructor(t){super("load"),this.response=t}}class nf extends Event{constructor(t,n){super("click"),this.resource=t,this.browserEvent=n}}function MU(e){var I,L,A;const t=ae(),[n,r]=p.useState(),[o,i]=p.useState(),{search:a,onLoad:l}=e,[c,u]=p.useState({selected:{},fieldEditorVisible:!1,filterEditorVisible:!1,exportDialogVisible:!1,filterDialogVisible:!1}),d=p.useRef(c);d.current=c;const f=a.total??"accurate",h=p.useCallback(R=>{i(void 0),t.search(a.resourceType,xa({...a,total:f,fields:void 0}),R).then(P=>{u({...d.current,searchResponse:P}),l&&l(new NU(P))}).catch(P=>{u({...d.current,searchResponse:void 0}),i(P)})},[t,a,f,l]),m=p.useCallback(()=>{u({...d.current,searchResponse:void 0}),h({cache:"reload"})},[h]);p.useEffect(()=>{h()},[h]);function g(R,P){R.stopPropagation();const B=R.target.checked,H={...d.current.selected};B?H[P]=!0:delete H[P],u({...d.current,selected:H})}function v(R){R.stopPropagation();const $=R.target.checked,B={},H=d.current.searchResponse;$&&(H!=null&&H.entry)&&H.entry.forEach(Y=>{var ie;(ie=Y.resource)!=null&&ie.id&&(B[Y.resource.id]=!0)}),u({...d.current,selected:B})}function S(){var P,$;const R=d.current;if(!((P=R.searchResponse)!=null&&P.entry)||R.searchResponse.entry.length===0)return!1;for(const B of R.searchResponse.entry)if(($=B.resource)!=null&&$.id&&!R.selected[B.resource.id])return!1;return!0}function y(R){e.onChange&&e.onChange(new AU(R))}function b(R,P){if(mk(R.target)||R.button===2)return;dt(R);const $=R.button===1||R.ctrlKey||R.metaKey;!$&&e.onClick&&e.onClick(new nf(P,R)),$&&e.onAuxClick&&e.onAuxClick(new nf(P,R))}function x(){return!!(e.onExport??e.onExportCsv??e.onExportTransactionBundle)}if(p.useEffect(()=>{r(e.search.resourceType),t.requestSchema(e.search.resourceType).catch(console.error).finally(()=>r(void 0))},[t,e.search.resourceType]),!xP(e.search.resourceType)||n===e.search.resourceType)return s.jsx(fn,{style:{width:"100%",height:"100%"},children:s.jsx(Kn,{})});const w=e.checkboxesEnabled,j=DU(a),E=a.resourceType,C=c.searchResponse,T=C==null?void 0:C.entry,_=T==null?void 0:T.map(R=>R.resource),k="subtle",N="gray",D=16,M=window.innerWidth<768;return s.jsxs("div",{className:Pl.root,"data-testid":"search-control",children:[!e.hideToolbar&&s.jsxs(J,{justify:"space-between",mb:"xl",children:[s.jsxs(J,{gap:2,children:[s.jsx(re,{size:"compact-md",variant:k,color:N,leftSection:s.jsx(T8,{size:D}),onClick:()=>u({...d.current,fieldEditorVisible:!0}),children:"Fields"}),s.jsx(re,{size:"compact-md",variant:k,color:N,leftSection:s.jsx(I8,{size:D}),onClick:()=>u({...d.current,filterEditorVisible:!0}),children:"Filters"}),e.onNew&&s.jsx(re,{size:"compact-md",variant:k,color:N,leftSection:s.jsx(D8,{size:D}),onClick:e.onNew,children:"New..."}),!M&&x()&&s.jsx(re,{size:"compact-md",variant:k,color:N,leftSection:s.jsx(ez,{size:D}),onClick:e.onExport?e.onExport:()=>u({...d.current,exportDialogVisible:!0}),children:"Export..."}),!M&&e.onDelete&&s.jsx(re,{size:"compact-md",variant:k,color:N,leftSection:s.jsx(hk,{size:D}),onClick:()=>e.onDelete(Object.keys(c.selected)),children:"Delete..."}),!M&&e.onBulk&&s.jsx(re,{size:"compact-md",variant:k,color:N,leftSection:s.jsx(x8,{size:D}),onClick:()=>e.onBulk(Object.keys(c.selected)),children:"Bulk..."})]}),s.jsxs(J,{gap:2,children:[C&&s.jsxs(he,{size:"xs",c:"dimmed","data-testid":"count-display",children:[nR(a,C).toLocaleString(),"-",FU(a,C).toLocaleString(),C.total!==void 0&&` of ${a.total==="estimate"?"~":""}${(I=C.total)==null?void 0:I.toLocaleString()}`]}),s.jsx(nn,{variant:k,color:N,title:"Refresh",onClick:m,children:s.jsx(G8,{size:D})})]})]}),s.jsxs(fe,{className:Pl.table,children:[s.jsxs(fe.Thead,{children:[s.jsxs(fe.Tr,{children:[w&&s.jsx(fe.Th,{children:s.jsx("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:S(),onChange:R=>v(R)})}),j.map(R=>s.jsx(fe.Th,{children:s.jsxs(ne,{shadow:"md",width:240,position:"bottom-end",children:[s.jsx(ne.Target,{children:s.jsx(vn,{className:Pl.control,p:2,children:s.jsxs(J,{justify:"space-between",wrap:"nowrap",children:[s.jsx(he,{fw:500,children:Ii(R.name)}),s.jsx(fn,{className:Pl.icon,children:s.jsx(p8,{size:14,stroke:1.5})})]})})}),s.jsx(yU,{search:e.search,searchParams:R.searchParams,onPrompt:(P,$)=>{u({...d.current,filterDialogVisible:!0,filterDialogSearchParam:P,filterDialogFilter:$})},onChange:P=>{y(P)}})]})},R.name))]}),!e.hideFilters&&s.jsxs(fe.Tr,{children:[w&&s.jsx(fe.Th,{}),j.map(R=>s.jsx(fe.Th,{children:R.searchParams&&s.jsx(OU,{resourceType:E,searchParams:R.searchParams,filters:e.search.filters})},R.name))]})]}),s.jsx(fe.Tbody,{children:_==null?void 0:_.map(R=>R&&s.jsxs(fe.Tr,{className:Pl.tr,"data-testid":"search-control-row",onClick:P=>b(P,R),onAuxClick:P=>b(P,R),children:[w&&s.jsx(fe.Td,{children:s.jsx("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${R.id}`,checked:!!c.selected[R.id],onChange:P=>g(P,R.id)})}),j.map(P=>s.jsx(fe.Td,{children:cU(R,P)},P.name))]},R.id))})]}),(_==null?void 0:_.length)===0&&s.jsx(su,{children:s.jsx(fn,{style:{height:150},children:s.jsx(he,{size:"xl",c:"dimmed",children:"No results"})})}),C&&s.jsx(fn,{m:"md",p:"md",children:s.jsx(Yr,{value:$U(a),total:LU(a,C),onChange:R=>y(oU(a,R)),getControlProps:R=>{switch(R){case"previous":return{"aria-label":"Previous page"};case"next":return{"aria-label":"Next page"};default:return{}}}})}),o&&s.jsx("div",{"data-testid":"search-error",children:s.jsx("pre",{style:{textAlign:"left"},children:JSON.stringify(o,void 0,2)})}),s.jsx(fU,{search:e.search,visible:d.current.fieldEditorVisible,onOk:R=>{y(R),u({...d.current,fieldEditorVisible:!1})},onCancel:()=>{u({...d.current,fieldEditorVisible:!1})}}),s.jsx(mU,{search:e.search,visible:d.current.filterEditorVisible,onOk:R=>{y(R),u({...d.current,filterEditorVisible:!1})},onCancel:()=>{u({...d.current,filterEditorVisible:!1})}}),s.jsx(qV,{visible:d.current.exportDialogVisible,exportCsv:e.onExportCsv,exportTransactionBundle:e.onExportTransactionBundle,onCancel:()=>{u({...d.current,exportDialogVisible:!1})}}),s.jsx(vU,{visible:d.current.filterDialogVisible,title:(L=c.filterDialogSearchParam)!=null&&L.code?Ii(c.filterDialogSearchParam.code):"",resourceType:E,searchParam:c.filterDialogSearchParam,filter:c.filterDialogFilter,defaultValue:"",onOk:R=>{y(Sh(e.search,R.code,R.operator,R.value)),u({...d.current,filterDialogVisible:!1})},onCancel:()=>{u({...d.current,filterDialogVisible:!1})}},(A=c.filterDialogSearchParam)==null?void 0:A.code)]})}const cu=p.memo(MU);function OU(e){const t=(e.filters??[]).filter(n=>e.searchParams.find(r=>r.code===n.code));return t.length===0?s.jsx("span",{children:"no filters"}):s.jsx(s.Fragment,{children:t.map(n=>s.jsxs("div",{children:[Gx(n.operator)," ",s.jsx(eR,{resourceType:e.resourceType,filter:n})]},`filter-${n.code}-${n.operator}-${n.value}`))})}function $U(e){return Math.floor((e.offset??0)/(e.count??hh))+1}function LU(e,t){const n=e.count??hh,r=rR(e,t);return Math.ceil(r/n)}function nR(e,t){return Math.min(rR(e,t),(e.offset??0)+1)}function FU(e,t){var n;return Math.max(nR(e,t)+(((n=t.entry)==null?void 0:n.length)??0)-1,0)}function rR(e,t){var r,o;let n=t.total;return n===void 0&&(n=(e.offset??0)+(((r=t.entry)==null?void 0:r.length)??0)+((o=t.link)!=null&&o.some(i=>i.relation==="next")?1:0)),n}function zU(e){const t=ae(),[n,r]=p.useState(!1),[o,i]=p.useState(),{query:a,fields:l}=e,[c,u]=p.useState(),[d,f]=p.useState({}),h=p.useRef();h.current=c;const m=p.useRef({});m.current=d,p.useEffect(()=>{i(void 0),t.graphql(a).then(u).catch(x=>i(vt(x)))},[t,a]);function g(x,w){x.stopPropagation();const E=x.target.checked,C={...m.current};E?C[w]=!0:delete C[w],f(C)}function v(x){var T;x.stopPropagation();const j=x.target.checked,E={},C=(T=h.current)==null?void 0:T.data.ResourceList;j&&C&&C.forEach(_=>{_.id&&(E[_.id]=!0)}),f(E)}function S(){var w;const x=(w=h.current)==null?void 0:w.data.ResourceList;if(!x||x.length===0)return!1;for(const j of x)if(j.id&&!m.current[j.id])return!1;return!0}function y(x,w){mk(x.target)||(dt(x),x.button!==1&&e.onClick&&e.onClick(new nf(w,x)),x.button===1&&e.onAuxClick&&e.onAuxClick(new nf(w,x)))}if(p.useEffect(()=>{t.requestSchema(e.resourceType).then(()=>r(!0)).catch(console.log)},[t,e.resourceType]),!n)return s.jsx(Kn,{});const b=e.checkboxesEnabled;return s.jsxs("div",{onContextMenu:x=>dt(x),"data-testid":"search-control",children:[s.jsxs(fe,{children:[s.jsx(fe.Thead,{children:s.jsxs(fe.Tr,{children:[b&&s.jsx(fe.Th,{children:s.jsx("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:S(),onChange:x=>v(x)})}),l.map(x=>s.jsx(fe.Th,{children:x.name},x.name))]})}),s.jsx(fe.Tbody,{children:c==null?void 0:c.data.ResourceList.map(x=>x&&s.jsxs(fe.Tr,{"data-testid":"search-control-row",onClick:w=>y(w,x),onAuxClick:w=>y(w,x),children:[b&&s.jsx(fe.Td,{children:s.jsx("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${x.id}`,checked:!!d[x.id],onChange:w=>g(w,x.id)})}),l.map(w=>s.jsx(fe.Td,{children:s.jsx(WV,{propertyType:w.propertyType,path:w.fhirPath,resource:x})},w.name))]},x.id))})]}),(c==null?void 0:c.data.ResourceList.length)===0&&s.jsx("div",{"data-testid":"empty-search",children:"No results"}),o&&s.jsx("div",{"data-testid":"search-error",children:s.jsx("pre",{style:{textAlign:"left"},children:JSON.stringify(o,void 0,2)})}),e.onBulk&&s.jsx(re,{onClick:()=>e.onBulk(Object.keys(m.current)),children:"Bulk..."})]})}const BU=p.memo(zU);function Xr(e){return s.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 491 491",style:{width:e.size,height:e.size},children:[s.jsx("title",{children:"Medplum Logo"}),s.jsx("path",{fill:e.fill??"#ad7136",d:"M282 67c6-16 16-29 29-40L289 0c-22 17-37 41-43 68l17 23 19-24z"}),s.jsx("path",{fill:e.fill??"#946af9",d:"M311 63c-17 0-33 4-48 11-16-7-32-11-49-11-87 0-158 96-158 214s71 214 158 214c17 0 33-4 49-11 15 7 31 11 48 11 87 0 158-96 158-214S398 63 311 63z"}),s.jsx("path",{fill:e.fill??"#7857c5",d:"M231 489l-17 2c-87 0-158-96-158-214S127 63 214 63l17 1c-39 12-70 102-70 213s31 201 70 212z"}),s.jsx("path",{fill:e.fill??"#40bc26",d:"M207 220a176 176 0 01-177 43A176 176 0 01251 43l1 5c17 59 2 125-45 172z"}),s.jsx("path",{fill:e.fill??"#33961e",d:"M252 48A421 421 0 0057 270l-27-7A176 176 0 01251 43l1 5z"})]})}function VU(e){const{group:t}=e;return s.jsx(qn,{withBorder:!0,radius:"md",p:"xs",display:"flex",style:{alignItems:"center",justifyContent:"center"},children:s.jsxs(J,{children:[t.measureScore&&s.jsx(WU,{group:t}),!t.measureScore&&s.jsx(HU,{group:t})]})})}function UU(e){const{measure:t}=e;return s.jsxs(s.Fragment,{children:[s.jsx(he,{fz:"md",fw:500,mb:8,children:t.title}),s.jsx(he,{fz:"xs",c:"dimmed",mb:8,children:t.subtitle})]})}function HU(e){const{group:t}=e,n=t.population,r=n==null?void 0:n.find(c=>Di(c.code)==="numerator"),o=n==null?void 0:n.find(c=>Di(c.code)==="denominator"),i=r==null?void 0:r.count,a=o==null?void 0:o.count;if(a===0)return s.jsxs(W,{children:[s.jsx(pe,{order:3,children:"Not Applicable"}),s.jsx(he,{children:`Denominator: ${a}`})]});if(i===void 0||a===void 0)return s.jsxs(W,{children:[s.jsx(pe,{order:3,children:"Insufficient Data"}),s.jsx(he,{children:`Numerator: ${i}`}),s.jsx(he,{children:`Denominator: ${a}`})]});const l=i/a*100;return s.jsx(ah,{size:120,thickness:12,roundCaps:!0,sections:[{value:l,color:oR(l)}],label:s.jsx(ms,{justify:"center",children:s.jsxs(he,{fw:700,fz:18,children:[i," / ",a]})})})}function WU(e){var r,o,i;const{group:t}=e,n=((r=t.measureScore)==null?void 0:r.unit)??((o=t.measureScore)==null?void 0:o.code);return s.jsx(s.Fragment,{children:n==="%"?s.jsx(ah,{size:120,thickness:12,roundCaps:!0,sections:[{value:qU(t),color:oR(((i=t==null?void 0:t.measureScore)==null?void 0:i.value)??0)}],label:s.jsx(ms,{justify:"center",children:s.jsx(he,{fw:700,fz:18,children:s.jsx(Ec,{value:t.measureScore})})})}):s.jsx(ms,{h:120,align:"center",children:s.jsx(pe,{order:3,children:s.jsx(Ec,{value:t.measureScore})})})})}function qU(e){var r,o;const t=(r=e.measureScore)==null?void 0:r.value,n=(o=e.measureScore)==null?void 0:o.unit;return t?t<=1&&n==="%"?t*100:t:0}function oR(e){return e<=33?"red":e<=67?"yellow":"green"}function GU(e){var r;const t=xt(e.measureReport),[n]=a8("Measure",{url:t==null?void 0:t.measure});return t?s.jsxs(W,{children:[n&&s.jsx(UU,{measure:n}),s.jsx(Uy,{cols:{base:3,sm:1},spacing:{base:"md",sm:"sm"},children:(r=t.group)==null?void 0:r.map((o,i)=>s.jsx(VU,{group:o},o.id??i))})]}):null}function Jr(e){var n;const t=((n=e.outcome)==null?void 0:n.issue)||e.issues;return!t||t.length===0?null:s.jsx(Li,{icon:s.jsx(cl,{size:16}),color:"red",children:t.map(r=>{var o;return s.jsx("div",{"data-testid":"text-field-error",children:gP(r)},(o=r.details)==null?void 0:o.text)})})}function QU(e){const t=p.useCallback((n,r,o)=>{const i=`${r}/${o}`,a=100;return Promise.allSettled([n.readHistory("Patient",o),n.search("Communication",{subject:i,_count:a}),n.search("Device",{patient:i,_count:a}),n.search("DeviceRequest",{patient:i,_count:a}),n.search("DiagnosticReport",{subject:i,_count:a}),n.search("Media",{subject:i,_count:a}),n.search("ServiceRequest",{subject:i,_count:a}),n.search("Task",{subject:i,_count:a})])},[]);return s.jsx(wh,{value:e.patient,loadTimelineResources:t,createCommunication:(n,r,o)=>({resourceType:"Communication",status:"completed",subject:jt(n),sender:jt(r),sent:new Date().toISOString(),payload:[{contentString:o}]}),createMedia:(n,r,o)=>({resourceType:"Media",status:"completed",subject:jt(n),operator:jt(r),issued:new Date().toISOString(),content:o})})}const KU="_section_14dzq_2",YU="_hovering_14dzq_11",XU="_editing_14dzq_15",JU="_bottomActions_14dzq_20",ba={section:KU,hovering:YU,editing:XU,bottomActions:JU};function ZU(e){const t=ae(),n=xt(e.value),[r,o]=p.useState(!1),[i,a]=p.useState(),[l,c]=p.useState(),[u,d]=p.useState();function f(){c(void 0)}function h(){a(void 0)}const m=p.useRef();if(m.current=u,p.useEffect(()=>{t.requestSchema("PlanDefinition").then(()=>o(!0)).catch(console.log)},[t]),p.useEffect(()=>(d(iH(n??{resourceType:"PlanDefinition",status:"active"})),document.addEventListener("mouseover",f),document.addEventListener("click",h),()=>{document.removeEventListener("mouseover",f),document.removeEventListener("click",h)}),[n]),!r||!u)return null;function g(v,S){d({...m.current,[v]:S})}return s.jsx("div",{children:s.jsxs(Ke,{testid:"questionnaire-form",onSubmit:()=>e.onSubmit(u),children:[s.jsx(me,{label:"Plan Title",defaultValue:u.title,onChange:v=>g("title",v.currentTarget.value)}),s.jsx(iR,{actions:u.action||[],selectedKey:i,setSelectedKey:a,hoverKey:l,setHoverKey:c,onChange:v=>g("action",v)}),s.jsx(re,{type:"submit",children:"Save"})]})})}function iR(e){const t=p.useRef();t.current=e.actions;function n(i){e.onChange(t.current.map(a=>a.id===i.id?i:a))}function r(i){e.onChange([...t.current,i]),e.setSelectedKey(i.id)}function o(i){e.onChange(t.current.filter(a=>a!==i))}return s.jsxs("div",{className:ba.section,children:[e.actions.map(i=>s.jsx("div",{children:s.jsx(eH,{action:i,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,setHoverKey:e.setHoverKey,onChange:n,onRemove:()=>o(i)})},i.id)),s.jsx("div",{className:ba.bottomActions,children:s.jsx(Ze,{href:"#",onClick:i=>{dt(i),r({id:aR()})},children:"Add action"})})]})}function eH(e){const{action:t}=e,n=oH(t),r=e.selectedKey===e.action.id,o=e.hoverKey===e.action.id;function i(c){c.stopPropagation(),e.setSelectedKey(e.action.id)}function a(c){dt(c),e.setHoverKey(e.action.id)}const l=rt(ba.section,{[ba.editing]:r,[ba.hovering]:o&&!r});return s.jsxs("div",{"data-testid":t.id,className:l,onClick:i,onMouseOver:a,onFocus:a,children:[r?s.jsx(nH,{action:t,actionType:n,onChange:e.onChange,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,setHoverKey:e.setHoverKey,onRemove:e.onRemove}):s.jsx(tH,{action:t,actionType:n}),s.jsx("div",{className:ba.bottomActions,children:s.jsx(Ze,{href:"#",onClick:c=>{c.preventDefault(),e.onRemove()},children:"Remove"})})]})}const sg={path:"PlanDefinition.action.timing[x]",min:0,max:1,description:"",isArray:!1,constraints:[],type:["dateTime","Period","Range","Timing"].map(e=>({code:e}))};function tH(e){const{action:t,actionType:n}=e,[r,o]=sR(t);return s.jsxs("div",{children:[s.jsxs("div",{children:[t.title||"Untitled"," ",n&&`(${n})`]}),t.definitionCanonical&&s.jsx("div",{children:s.jsx(ef,{value:{reference:t.definitionCanonical}})}),r&&s.jsx("div",{children:s.jsx(Gr,{property:sg,propertyType:o,value:r})})]})}function nH(e){const{action:t}=e,[n,r]=p.useState(e.actionType);function o(i,a){e.onChange({...t,[i]:a})}return s.jsxs(Ne,{gap:"xl",children:[s.jsx(me,{name:`actionTitle-${t.id}`,label:"Title",defaultValue:t.title,onChange:i=>o("title",i.currentTarget.value)}),s.jsx(me,{name:`actionDescription-${t.id}`,label:"Description",defaultValue:t.description,onChange:i=>o("description",i.currentTarget.value)}),s.jsx(kt,{label:"Type of Action",description:"The type of the action to be performed.",name:`actionType-${t.id}`,defaultValue:n,onChange:i=>r(i.currentTarget.value),data:["","appointment","lab","questionnaire","task"]}),t.action&&t.action.length>0&&s.jsx(iR,{actions:t.action,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,setHoverKey:e.setHoverKey,onChange:i=>o("action",i)}),(()=>{switch(n){case"appointment":return s.jsx(Gu,{title:"Appointment",description:"The subject must schedule an appointment from the schedule.",resourceType:"Schedule",action:t,onChange:e.onChange});case"lab":return s.jsx(Gu,{title:"Lab",description:"The subject must complete the following lab panel.",resourceType:"ActivityDefinition",action:t,onChange:e.onChange});case"questionnaire":return s.jsx(Gu,{title:"Questionnaire",description:"The subject must complete the selected questionnaire.",resourceType:"Questionnaire",action:t,onChange:e.onChange});case"task":return s.jsx(Gu,{title:"Task",description:"The subject must complete the following task.",resourceType:"ActivityDefinition",action:t,onChange:e.onChange});default:return null}})(),s.jsx(mt,{title:"Timing",description:"When the action should take place.",children:s.jsx(rH,{name:"timing-"+t.id,action:t,onChange:e.onChange})})]})}function Gu(e){const{id:t,definitionCanonical:n}=e.action,r=n!=null&&n.startsWith(e.resourceType+"/")?{reference:n}:void 0;return s.jsx(ul,{name:t,resourceType:e.resourceType,defaultValue:r,loadOnFocus:!0,onChange:o=>{o?e.onChange({...e.action,definitionCanonical:Ct(o)}):e.onChange({...e.action,definitionCanonical:void 0})}})}function rH(e){const t=e.action,n="timing",[r,o]=sR(t);return s.jsx(dl,{property:sg,name:"timing[x]",path:"PlanDefinition.timing[x]",defaultValue:r,defaultPropertyType:o,onChange:(i,a)=>{e.onChange(kk(t,n,a??n,sg,i))},outcome:void 0})}function oH(e){var t,n,r;if((t=e.definitionCanonical)!=null&&t.startsWith("Schedule"))return"appointment";if((n=e.definitionCanonical)!=null&&n.startsWith("Questionnaire/"))return"questionnaire";if((r=e.definitionCanonical)!=null&&r.startsWith("ActivityDefinition/"))return"task"}function sR(e){return ou({type:"PlanDefinitionAction",value:e},"timing")}let Rp=1;function aR(e){if(e){if(e.startsWith("id-")){const t=parseInt(e.substring(3),10);isNaN(t)||(Rp=Math.max(Rp,t+1))}return e}return"id-"+Rp++}function iH(e){return{...e,action:lR(e.action)}}function lR(e){if(e)return e.map(t=>({...t,id:aR(t.id),action:lR(t.action)}))}var wt=(e=>(e.group="group",e.display="display",e.question="question",e.boolean="boolean",e.decimal="decimal",e.integer="integer",e.date="date",e.dateTime="dateTime",e.time="time",e.string="string",e.text="text",e.url="url",e.choice="choice",e.openChoice="open-choice",e.attachment="attachment",e.reference="reference",e.quantity="quantity",e))(wt||{});function sH(e){return e.type==="choice"||e.type==="open-choice"}function aH(e,t){if(!e.enableWhen)return!0;const n=e.enableBehavior??"any";for(const r of e.enableWhen){const o=cR(t,r.question);if(r.operator==="exists"&&!r.answerBoolean&&!(o!=null&&o.length)){if(n==="any")return!0;continue}const{anyMatch:i,allMatch:a}=uH(r,o,n);if(n==="any"&&i)return!0;if(n==="all"&&!a)return!1}return n!=="any"}function lH(e,t,n){return e.map(r=>{var a;const o=(a=n.answerOption)==null?void 0:a.find(l=>Fs(l.valueCoding)===r||l[t]===r),i=pn({type:"QuestionnaireItemAnswerOption",value:o},"value");return{[t]:i==null?void 0:i.value}})}function cR(e,t){if(e)for(const n of e){if(n.linkId===t)return n.answer;if(n.item){const r=cR(n.item,t);if(r)return r}}}function cH(e,t,n){if(n==="exists")return!!e===t.value;if(e){const r=n==="="||n==="!="?n==null?void 0:n.replace("=","~"):n,[{value:o}]=Cc(`%actualAnswer ${r} %expectedAnswer`,[e],{"%actualAnswer":e,"%expectedAnswer":t});return o}else return!1}function uH(e,t,n){const r=t||[],o=pn({type:"QuestionnaireItemEnableWhen",value:e},"answer[x]");let i=!1,a=!0;for(const l of r){const c=pn({type:"QuestionnaireResponseItemAnswer",value:l},"value[x]"),{operator:u}=e;if(cH(c,o,u)?i=!0:a=!1,n==="any"&&i)break}return{anyMatch:i,allMatch:a}}function uR(e){var n,r;const t=Jc(e,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource");if(t){if(t.valueCode!==void 0)return[t.valueCode];if(t.valueCodeableConcept)return(r=(n=t.valueCodeableConcept)==null?void 0:n.coding)==null?void 0:r.map(o=>o.code)}}function _p(e,t){var o;const n=mo(e);let r=Jc(n,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource");return!t||t.length===0?(r&&(n.extension=(o=n.extension)==null?void 0:o.filter(i=>i!==r)),n):(r||(n.extension||(n.extension=[]),r={url:"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource"},n.extension.push(r)),t.length===1?(r.valueCode=t[0],delete r.valueCodeableConcept):(r.valueCodeableConcept={coding:t.map(i=>({code:i}))},delete r.valueCode),n)}function dH(e,t,n){const r=Jc(e,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceFilter");if(!(r!=null&&r.valueString))return;let o=r.valueString;t!=null&&t.reference&&(o=o.replaceAll("$subj",t.reference)),n!=null&&n.reference&&(o=o.replaceAll("$encounter",n.reference));const i={},a=o.split("&");for(const l of a){const[c,u]=Ym(l,"=",2);i[c]=u}return i}function fH(e){return{resourceType:"QuestionnaireResponse",questionnaire:Ct(e),item:dR(e.item),status:"in-progress"}}function dR(e){return(e==null?void 0:e.map(fR))??[]}function fR(e){var t;return{id:pH(),linkId:e.linkId,text:e.text,item:dR(e.item),answer:((t=e.initial)==null?void 0:t.map(mH))??[]}}let hH=1;function pH(){return"id-"+hH++}function mH(e){return{...e}}function gH(e){return e.value.display||e.value.reference||lr(e.value)}function vH(e){var n,r,o,i;const t=(n=e==null?void 0:e.item)==null?void 0:n[0];if(t){const a=Jc(t,"http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl");if(((i=(o=(r=a==null?void 0:a.valueCodeableConcept)==null?void 0:r.coding)==null?void 0:o[0])==null?void 0:i.code)==="page")return e.item.length}return 1}const hR=p.createContext({});function ag(e){const t=p.useContext(hR),n=e.item,r=e.response;function o(u){var f,h,m,g;let d;Array.isArray(u)?d=u:e.index>=(((h=(f=e.response)==null?void 0:f.answer)==null?void 0:h.length)??0)?d=(((m=e.response)==null?void 0:m.answer)??[]).concat([u]):d=(((g=e.response)==null?void 0:g.answer)??[]).map((S,y)=>y===e.index?u:S)??[],e.onChange({id:r==null?void 0:r.id,linkId:r==null?void 0:r.linkId,text:n.text,answer:d})}const i=n.type;if(!i)return null;const a=n.linkId;if(!a)return null;const l=n.initial&&n.initial.length>0?n.initial[0]:void 0,c=Qx(r,e.index)??pn({type:"QuestionnaireItemInitial",value:l},"value");switch(i){case wt.display:return s.jsx("p",{children:e.item.text},e.item.linkId);case wt.boolean:return s.jsx(Tk,{title:e.item.text,htmlFor:e.item.linkId,children:s.jsx(Xn,{id:e.item.linkId,name:e.item.linkId,defaultChecked:c==null?void 0:c.value,onChange:u=>o({valueBoolean:u.currentTarget.checked})})},e.item.linkId);case wt.decimal:return s.jsx(me,{type:"number",step:"any",id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueDecimal:u.currentTarget.valueAsNumber})});case wt.integer:return s.jsx(me,{type:"number",step:1,id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueInteger:u.currentTarget.valueAsNumber})});case wt.date:return s.jsx(me,{type:"date",id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueDate:u.currentTarget.value})});case wt.dateTime:return s.jsx(ws,{name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueDateTime:u})});case wt.time:return s.jsx(me,{type:"time",id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueTime:u.currentTarget.value})});case wt.string:case wt.url:return s.jsx(me,{id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueString:u.currentTarget.value})});case wt.text:return s.jsx(Ns,{id:a,name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueString:u.currentTarget.value})});case wt.attachment:return s.jsx(J,{py:4,children:s.jsx(yk,{path:"",name:a,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueAttachment:u})})});case wt.reference:return s.jsx(xh,{name:a,required:n.required,targetTypes:uR(n),searchCriteria:dH(n,t.subject,t.encounter),defaultValue:c==null?void 0:c.value,onChange:u=>o({valueReference:u})});case wt.quantity:return s.jsx(Ss,{path:"",name:a,required:n.required,defaultValue:c==null?void 0:c.value,onChange:u=>o({valueQuantity:u}),disableWheel:!0});case wt.choice:case wt.openChoice:return jH(n)&&!n.answerValueSet?s.jsx(yH,{name:a,item:n,initial:l,response:r,onChangeAnswer:u=>o(u)}):s.jsx(xH,{name:a,item:n,initial:l,response:r,onChangeAnswer:u=>o(u)});default:return null}}function yH(e){var c;const{name:t,item:n,initial:r,response:o}=e;if(!((c=n.answerOption)!=null&&c.length))return s.jsx(pR,{});const i=pn({type:"QuestionnaireItemInitial",value:r},"value"),a=[""];for(const u of n.answerOption){const d=pn({type:"QuestionnaireItemAnswerOption",value:u},"value");a.push(mw(d))}const l=Qx(o)??i;if(n.repeats){const{propertyName:u,data:d}=CH(e.item),f=wH(o);return s.jsx(eh,{data:d,placeholder:"Select items",searchable:!0,defaultValue:f||[mw(i)],onChange:h=>{const m=lH(h,u,n);e.onChangeAnswer(m)}})}return s.jsx(kt,{id:t,name:t,onChange:u=>{const d=u.currentTarget.selectedIndex;if(d===0){e.onChangeAnswer({});return}const f=n.answerOption[d-1],h=pn({type:"QuestionnaireItemAnswerOption",value:f},"value"),m="value"+Qt(h.type);e.onChangeAnswer({[m]:h.value})},defaultValue:Fs(l==null?void 0:l.value)||(l==null?void 0:l.value),data:a})}function xH(e){var a;const{name:t,item:n,initial:r,onChangeAnswer:o,response:i}=e;return!((a=n.answerOption)!=null&&a.length)&&!n.answerValueSet?s.jsx(pR,{}):n.answerValueSet?s.jsx(Rk,{path:"",name:t,binding:n.answerValueSet,onChange:l=>o({valueCoding:l}),creatable:n.type===wt.openChoice}):s.jsx(bH,{name:(i==null?void 0:i.id)??t,item:n,initial:r,response:i,onChangeAnswer:o})}function bH(e){const{name:t,item:n,initial:r,onChangeAnswer:o,response:i}=e,a=zs("QuestionnaireItemAnswerOption","value[x]"),l=pn({type:"QuestionnaireItemInitial",value:r},"value"),c=[];let u;if(n.answerOption)for(let h=0;h<n.answerOption.length;h++){const m=n.answerOption[h],g=`${t}-option-${h}`,v=pn({type:"QuestionnaireItemAnswerOption",value:m},"value");v!=null&&v.value&&(l&&lr(v)===lr(l)&&(u=g),c.push([g,v]))}const d=Qx(i),f=SH(c,d);return s.jsx(ys.Group,{name:t,value:f??u,onChange:h=>{const m=c.find(g=>g[0]===h);if(m){const g=m[1],v="value"+Qt(g.type);o({[v]:g.value})}},children:c.map(([h,m])=>s.jsx(ys,{id:h,value:h,py:4,label:s.jsx(Gr,{property:a,propertyType:m.type,value:m.value})},h))})}function pR(){return s.jsx(me,{disabled:!0,placeholder:"No Answers Defined"})}function mR(e){return pn({type:"QuestionnaireItemAnswer",value:e},"value")}function Qx(e,t=0){const n=e.answer;return mR((n==null?void 0:n[t])??{})}function wH(e){const t=e.answer;return t?t.map(r=>mR(r)).map(r=>Fs(r==null?void 0:r.value)||(r==null?void 0:r.value)):[]}function SH(e,t){var n;return(n=e.find(r=>xs(r[1].value,t==null?void 0:t.value)))==null?void 0:n[0]}function mw(e){if(e)return e.type==="CodeableConcept"?Di(e.value):e.type==="Coding"?Fs(e.value):e.type==="Reference"?gH(e):e.value.toString()}function jH(e){var t;return!!((t=e.extension)!=null&&t.some(n=>{var r,o,i;return n.url==="http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl"&&((i=(o=(r=n.valueCodeableConcept)==null?void 0:r.coding)==null?void 0:o[0])==null?void 0:i.code)==="drop-down"}))}function CH(e){var i;if(((i=e.answerOption)==null?void 0:i.length)===0)return{propertyName:"",data:[]};const t=e.answerOption[0],n=pn({type:"QuestionnaireItemAnswerOption",value:t},"value"),r="value"+Qt(n.type),o=(e.answerOption??[]).map(a=>({value:gw(a,r),label:gw(a,r)}));return{propertyName:r,data:o}}function gw(e,t){var n;return Fs(e.valueCoding)||((n=e[t])==null?void 0:n.toString())}const EH="_section_cpwxo_1",TH="_hovering_cpwxo_10",PH="_editing_cpwxo_14",kH="_questionBody_cpwxo_19",RH="_topActions_cpwxo_23",_H="_bottomActions_cpwxo_32",DH="_movementActions_cpwxo_43",IH="_movementIcons_cpwxo_55",AH="_columnAlignment_cpwxo_59",NH="_linkIdInput_cpwxo_64",MH="_typeSelect_cpwxo_69",pr={section:EH,hovering:TH,editing:PH,questionBody:kH,topActions:RH,bottomActions:_H,movementActions:DH,movementIcons:IH,columnAlignment:AH,linkIdInput:NH,typeSelect:MH};function OH(e){const t=ae(),n=xt(e.questionnaire),[r,o]=p.useState(!1),[i,a]=p.useState(),[l,c]=p.useState(),[u,d]=p.useState();function f(){d(void 0)}function h(){c(void 0)}p.useEffect(()=>{t.requestSchema("Questionnaire").then(()=>o(!0)).catch(console.log)},[t]),p.useEffect(()=>(a(zH(n??{resourceType:"Questionnaire",status:"active"})),document.addEventListener("mouseover",f),document.addEventListener("click",h),()=>{document.removeEventListener("mouseover",f),document.removeEventListener("click",h)}),[n]);const m=(g,v)=>{a(g),e.autoSave&&!v&&e.onSubmit&&e.onSubmit(g)};return!r||!i?null:s.jsx("div",{children:s.jsxs(Ke,{testid:"questionnaire-form",onSubmit:()=>e.onSubmit(i),children:[s.jsx(gR,{item:i,selectedKey:l,setSelectedKey:c,hoverKey:u,setHoverKey:d,onChange:m}),s.jsx(re,{type:"submit",children:"Save"})]})})}function gR(e){var x;const t=e.item,n=e.item,r=Yo(e.item),o=r||n.type===wt.group,i=n.linkId??"[untitled]",a=e.selectedKey===e.item.id,l=e.hoverKey===e.item.id,c=p.useRef();c.current=e.item;function u(w){dt(w),e.setSelectedKey(e.item.id)}function d(w){dt(w),e.setHoverKey(e.item.id)}function f(w){var E;const j=c.current;e.onChange({...j,item:(E=j.item)==null?void 0:E.map(C=>C.id===w.id?w:C)})}function h(w,j){e.onChange({...e.item,item:[...e.item.item??[],w]},j)}function m(w){var j;e.onChange({...e.item,item:(j=e.item.item)==null?void 0:j.filter(E=>E!==w)})}function g(w,j){e.onChange({...c.current,[w]:j})}function v(w){e.onChange({...e.item,...w})}function S(w){var j;e.onChange({...e.item,item:(j=e.item.item)==null?void 0:j.map(E=>E===w?{...E,repeats:!E.repeats}:E)})}function y(w,j){const E=UH(e.item.item,w,j);e.onChange({...e.item,item:E})}const b=rt(pr.section,{[pr.editing]:a,[pr.hovering]:l&&!a});return s.jsxs("div",{"data-testid":n.linkId,className:b,onClick:u,onMouseOver:d,onFocus:d,children:[s.jsx("div",{className:pr.questionBody,children:a?s.jsxs(s.Fragment,{children:[r&&s.jsx(me,{size:"xl",defaultValue:t.title,onBlur:w=>g("title",w.currentTarget.value)}),!r&&s.jsx(Ns,{autosize:!0,minRows:2,defaultValue:n.text,onBlur:w=>g("text",w.currentTarget.value)}),n.type==="reference"&&s.jsx(FH,{item:n,onChange:v}),sH(n)&&s.jsx($H,{item:n,onChange:w=>v(w)})]}):s.jsxs(s.Fragment,{children:[t.title&&s.jsx(pe,{children:t.title}),n.text&&s.jsx("div",{children:n.text}),!o&&s.jsx(ag,{item:n,index:0,onChange:()=>{},response:{linkId:n.linkId}})]})}),(x=n.item)==null?void 0:x.map((w,j)=>s.jsx("div",{children:s.jsx(gR,{item:w,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,isFirst:j===0,isLast:j===(e.item.item??[]).length-1,setHoverKey:e.setHoverKey,onChange:f,onRemove:()=>m(w),onRepeatable:S,onMoveUp:()=>y(j,-1),onMoveDown:()=>y(j,1)})},w.id)),!o&&s.jsx("div",{className:pr.topActions,children:a?s.jsxs(s.Fragment,{children:[s.jsx(me,{size:"xs",className:pr.linkIdInput,defaultValue:n.linkId,onBlur:w=>g("linkId",w.currentTarget.value)}),!o&&s.jsx(kt,{size:"xs",className:pr.typeSelect,defaultValue:n.type,onChange:w=>g("type",w.currentTarget.value),data:[{value:"display",label:"Display"},{value:"boolean",label:"Boolean"},{value:"decimal",label:"Decimal"},{value:"integer",label:"Integer"},{value:"date",label:"Date"},{value:"dateTime",label:"Date/Time"},{value:"time",label:"Time"},{value:"string",label:"String"},{value:"text",label:"Text"},{value:"url",label:"URL"},{value:"choice",label:"Choice"},{value:"open-choice",label:"Open Choice"},{value:"attachment",label:"Attachment"},{value:"reference",label:"Reference"},{value:"quantity",label:"Quantity"}]})]}):s.jsx("div",{children:i})}),!r&&s.jsx(W,{className:pr.movementActions,children:s.jsxs(W,{className:pr.columnAlignment,children:[!e.isFirst&&s.jsx(Ze,{href:"#",onClick:w=>{w.preventDefault(),e.onMoveUp&&e.onMoveUp()},children:s.jsx(g8,{"data-testid":"up-button",size:15,className:pr.movementIcons})}),!e.isLast&&s.jsx(Ze,{href:"#",onClick:w=>{w.preventDefault(),e.onMoveDown&&e.onMoveDown()},children:s.jsx(m8,{"data-testid":"down-button",size:15,className:pr.movementIcons})})]})}),s.jsxs("div",{className:pr.bottomActions,children:[o&&s.jsxs(s.Fragment,{children:[s.jsx(Ze,{href:"#",onClick:w=>{w.preventDefault(),h({id:Cs(),linkId:ug("q"),type:"string",text:"Question"})},children:"Add item"}),s.jsx(Ze,{href:"#",onClick:w=>{w.preventDefault(),h({id:Cs(),linkId:ug("g"),type:"group",text:"Group"},!0)},children:"Add group"})]}),r&&s.jsx(Ze,{href:"#",onClick:w=>{w.preventDefault(),h(VH(),!0)},children:"Add Page"}),a&&!r&&s.jsxs(s.Fragment,{children:[s.jsx(Ze,{href:"#",onClick:w=>{w.preventDefault(),e.onRepeatable&&e.onRepeatable(n)},children:n.repeats?"Remove Repeatable":"Make Repeatable"}),s.jsx(Ze,{href:"#",onClick:w=>{w.preventDefault(),e.onRemove&&e.onRemove()},children:"Remove"})]})]})]})}function $H(e){const t=zs("QuestionnaireItemAnswerOption","value[x]"),n=e.item.answerOption??[];return s.jsxs("div",{children:[e.item.answerValueSet!==void 0?s.jsx(me,{placeholder:"Enter Value Set",defaultValue:e.item.answerValueSet,onChange:r=>e.onChange({...e.item,answerValueSet:r.target.value})}):s.jsx(LH,{options:n,property:t,item:e.item,onChange:e.onChange}),s.jsxs(W,{display:"flex",children:[s.jsx(Ze,{href:"#",onClick:r=>{dt(r),e.onChange({...e.item,answerValueSet:void 0,answerOption:[...n,{id:Cs()}]})},children:"Add choice"}),s.jsx(lh,{w:"lg"}),s.jsx(Ze,{href:"#",onClick:r=>{dt(r),e.onChange({...e.item,answerOption:[],answerValueSet:""})},children:"Add value set"})]})]})}function LH(e){return s.jsx("div",{children:e.options.map(t=>{const[n,r]=ou({type:"QuestionnaireItemAnswerOption",value:t},"value");return s.jsxs("div",{style:{display:"flex",flexDirection:"row",justifyContent:"space-between",alignItems:"center",width:"80%"},children:[s.jsx("div",{children:s.jsx(dl,{name:"value[x]",path:"Questionnaire.answerOption.value[x]",property:e.property,defaultPropertyType:r,defaultValue:n,onChange:(o,i)=>{const a=[...e.options],l=a.findIndex(c=>c.id===t.id);a[l]={id:t.id,[i]:o},e.onChange({...e.item,answerOption:a})},outcome:void 0},t.id)}),s.jsx("div",{children:s.jsx(Ze,{href:"#",onClick:o=>{dt(o),e.onChange({...e.item,answerOption:e.options.filter(i=>i.id!==t.id)})},children:"Remove"})})]},t.id)})})}function FH(e){const t=uR(e.item)??[];return s.jsxs(s.Fragment,{children:[t.map((n,r)=>s.jsxs(J,{children:[s.jsx(kx,{name:"resourceType",placeholder:"Resource Type",defaultValue:n,onChange:o=>{e.onChange(_p(e.item,t.map(i=>i===n?o:i)))}}),s.jsx(Ze,{href:"#",onClick:o=>{dt(o),e.onChange(_p(e.item,t.filter(i=>i!==n)))},children:"Remove"})]},`${n}-${r}`)),s.jsx(Ze,{href:"#",onClick:n=>{dt(n),e.onChange(_p(e.item,[...t,""]))},children:"Add Resource Type"})]})}let lg=1,cg=1;function ug(e){return e+lg++}function Cs(){return"id-"+cg++}function zH(e){return{...e,id:e.id||Cs(),item:vR(e.item)}}function vR(e){if(e)return e.forEach(t=>{var n,r;(n=t.id)!=null&&n.match(/^id-\d+$/)&&(cg=Math.max(cg,parseInt(t.id.substring(3),10)+1)),(r=t.linkId)!=null&&r.match(/^q\d+$/)&&(lg=Math.max(lg,parseInt(t.linkId.substring(1),10)+1))}),e.map(t=>({...t,id:t.id||Cs(),item:vR(t.item),answerOption:BH(t.answerOption)}))}function BH(e){if(e)return e.map(t=>({...t,id:t.id||Cs()}))}function VH(){return{id:Cs(),linkId:ug("s"),type:"group",text:"New Page",extension:[{url:"http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl",valueCodeableConcept:{coding:[{system:"http://hl7.org/fhir/questionnaire-item-control",code:"page"}]}}]}}function UH(e,t,n){const r=e??[],o=t+n;if(o<0||o>=r.length)return r;const i=[...r];return[i[t],i[o]]=[i[o],i[t]],i}function yR(e){const{item:t,response:n,onChange:r}=e,[o,i]=p.useState(HH(t,n??{linkId:t.linkId}));if(!e.checkForQuestionEnabled(t)||!n)return null;if(t.type===wt.display)return s.jsx("p",{children:t.text},t.linkId);const a=(t==null?void 0:t.repeats)&&t.type!==wt.choice&&t.type!==wt.openChoice;return t.type===wt.boolean?s.jsx(ag,{item:t,response:n,onChange:l=>r([l]),index:0},t.linkId):s.jsxs(mt,{htmlFor:e.item.linkId,title:e.item.text,withAsterisk:e.item.required,children:[[...Array(o)].map((l,c)=>s.jsx(ag,{item:t,response:n,onChange:u=>r([u]),index:c},`${t.linkId}-${c}`)),a&&s.jsx(Ze,{onClick:()=>i(l=>l+1),children:"Add Item"})]},e.item.linkId)}function HH(e,t){if(e.type===wt.choice||e.type===wt.openChoice)return 1;const n=t.answer;return n!=null&&n.length?n.length:1}function xR(e){const[t,n]=p.useState(e.response);if(t.length===0)return null;function r(i,a){const l=t.map((c,u)=>u===a?i[0]:c);n(l),e.onChange(l)}function o(){const i=fR(e.item);n([...t,i])}return s.jsxs(s.Fragment,{children:[t.map((i,a)=>s.jsx(bR,{item:e.item,response:i,checkForQuestionEnabled:e.checkForQuestionEnabled,onChange:l=>r(l,a)},i.id)),e.item.repeats&&s.jsx(Ze,{onClick:o,children:`Add Group: ${e.item.text}`})]})}function bR(e){var i;const{response:t,checkForQuestionEnabled:n,onChange:r}=e;function o(a){var d;const l=(d=t.item)==null?void 0:d.map(f=>a.find(m=>m.id===f.id)??f),c=l==null?void 0:l.concat(a.slice(1)),u={...t,item:c};r([u])}return e.checkForQuestionEnabled(e.item)?s.jsxs("div",{children:[e.item.text&&s.jsx(pe,{order:3,mb:"md",children:e.item.text}),s.jsx(Ne,{children:(i=e.item.item)==null?void 0:i.map(a=>{var l,c,u;return a.type===wt.group?a.repeats?s.jsx(xR,{item:a,response:((l=t.item)==null?void 0:l.filter(d=>d.linkId===a.linkId))??[],checkForQuestionEnabled:n,onChange:o},a.linkId):s.jsx(bR,{item:a,checkForQuestionEnabled:n,response:((c=t.item)==null?void 0:c.find(d=>d.linkId===a.linkId))??{linkId:a.linkId},onChange:o},a.linkId):s.jsx(yR,{item:a,response:(u=t.item)==null?void 0:u.find(d=>d.linkId===a.linkId),onChange:o,checkForQuestionEnabled:n},a.linkId)})})]},e.item.linkId):null}function WH(e){const{items:t,response:n,activePage:r,onChange:o,nextStep:i,prevStep:a,numberOfPages:l,renderPages:c,submitButtonText:u,checkForQuestionEnabled:d}=e,f=t.map(h=>{var v;const m=((v=n==null?void 0:n.item)==null?void 0:v.filter(S=>S.linkId===h.linkId))??[],g=h.type===wt.group?s.jsx(xR,{item:h,response:m,onChange:o,checkForQuestionEnabled:d},h.linkId):s.jsx(yR,{item:h,response:m==null?void 0:m[0],onChange:o,checkForQuestionEnabled:d},h.linkId);return c?s.jsx(Ha.Step,{label:h.text,children:g},h.linkId):g});return s.jsxs(s.Fragment,{children:[c&&s.jsx(Ha,{active:r??0,allowNextStepsSelect:!1,p:6,children:f}),!c&&s.jsx(Ne,{children:f}),s.jsx(qH,{activePage:r??0,numberOfPages:l,nextStep:i,prevStep:a,submitButtonText:u})]})}function qH(e){const t=e.activePage>0,n=e.activePage<e.numberOfPages-1,r=e.activePage===e.numberOfPages-1;return s.jsxs(J,{justify:"flex-end",mt:"xl",gap:"xs",children:[t&&s.jsx(re,{onClick:e.prevStep,children:"Back"}),n&&s.jsx(re,{onClick:o=>{o.currentTarget.closest("form").reportValidity()&&e.nextStep()},children:"Next"}),r&&s.jsx(re,{type:"submit",children:e.submitButtonText??"Submit"})]})}function wR(e){const t=ae(),n=t.getProfile(),[r,o]=p.useState(!1),i=xt(e.questionnaire),[a,l]=p.useState(),[c,u]=p.useState(0);p.useEffect(()=>{t.requestSchema("Questionnaire").then(()=>t.requestSchema("QuestionnaireResponse")).then(()=>o(!0)).catch(console.log)},[t]),p.useEffect(()=>{l(i?fH(i):void 0)},[i]);function d(v){const S=(a==null?void 0:a.item)??[],b={resourceType:"QuestionnaireResponse",status:"in-progress",item:SR(S,Array.isArray(v)?v:[v])};l(b)}function f(v){return aH(v,(a==null?void 0:a.item)??[])}if(!r||!i||!a)return null;const h=vH(i),m=()=>u(v=>v+1),g=()=>u(v=>v-1);return s.jsx(hR.Provider,{value:{subject:e.subject,encounter:e.encounter},children:s.jsxs(Ke,{testid:"questionnaire-form",onSubmit:()=>{e.onSubmit&&a&&e.onSubmit({...a,questionnaire:Ct(i),subject:e.subject,source:jt(n),authored:new Date().toISOString(),status:"completed"})},children:[i.title&&s.jsx(pe,{children:i.title}),s.jsx(WH,{items:i.item??[],response:a,onChange:d,renderPages:h>1,activePage:c,numberOfPages:h,submitButtonText:e.submitButtonText,checkForQuestionEnabled:f,nextStep:m,prevStep:g})]})})}function GH(e,t){const n=SR(e.item??[],t.item??[]);return{...t,item:n.length>0?n:void 0,answer:t.answer&&t.answer.length>0?t.answer:e.answer}}function SR(e,t){const n=[],r=new Set;for(const o of e){const i=o.id,a=t.find(l=>l.id===i);a?(n.push(GH(o,a)),r.add(a.id)):n.push(o)}for(const o of t)r.has(o.id)||n.push(o);return n}const QH="_section_4m5it_1",KH={section:QH},YH=["gender","age","gestationalAge","context","appliesTo","category"],XH={definition:{resourceType:"ObservationDefinition",code:{text:""}},onSubmit:()=>{}};function JH(e){e=Object.assign(XH,e);const t=e.definition,[n,r]=p.useState([]),[o,i]=p.useState(1),[a,l]=p.useState(1);return p.useEffect(()=>{const g=tW(t,l);r(nW(g.qualifiedInterval||[],i))},[t]),s.jsxs(Ke,{testid:"reference-range-editor",onSubmit:c,children:[s.jsx(Ne,{children:n.map(g=>{var v;return s.jsx(ZH,{unit:oW((v=t.quantitativeDetails)==null?void 0:v.unit),onChange:f,onAdd:h,onRemove:m,onRemoveGroup:d,intervalGroup:g},`group-${g.id}`)})}),s.jsx(nn,{title:"Add Group",variant:"subtle",size:"sm",onClick:g=>{dt(g),u({id:`group-id-${o}`,filters:{},intervals:[]}),i(v=>v+1)},children:s.jsx(Jd,{})}),s.jsx(J,{justify:"flex-end",children:s.jsx(re,{type:"submit",children:"Save"})})]});function c(){const g=n.flatMap(v=>v.intervals).filter(v=>!iW(v));e.onSubmit({...t,qualifiedInterval:g})}function u(g){r(v=>[...v,g])}function d(g){r(v=>v.filter(S=>S.id!==g.id))}function f(g,v){r(S=>{S=[...S];const y=S.find(x=>x.id===g),b=y==null?void 0:y.intervals.findIndex(x=>x.id===v.id);return b!==void 0&&(y!=null&&y.intervals[b])&&(y.intervals[b]=v),S})}function h(g,v){v.id===void 0&&(v.id=`id-${a}`,l(S=>S+1)),r(S=>{S=[...S];const y=S.findIndex(b=>b.id===g);if(y!==-1){const b={...S[y]};v={...v,...b.filters},b.intervals=[...b.intervals,v],S[y]=b}return S})}function m(g,v){r(S=>{S=[...S];const y=S.find(b=>b.id===g);return y&&(y.intervals=y.intervals.filter(b=>b.id!==v.id)),S})}}function ZH(e){const{intervalGroup:t,unit:n}=e;return s.jsx(su,{"data-testid":t.id,className:KH.section,children:s.jsxs(Ne,{gap:"lg",children:[s.jsx(J,{justify:"flex-end",children:s.jsx(nn,{title:"Remove Group",variant:"subtle","data-testid":`remove-group-button-${t.id}`,size:"sm",onClick:r=>{dt(r),e.onRemoveGroup(t)},children:s.jsx(Xd,{})},`remove-group-button-${t.id}`)}),s.jsx(eW,{intervalGroup:t,onChange:e.onChange}),s.jsx(Zt,{}),t.intervals.map(r=>s.jsxs(Ne,{gap:"xs",children:[s.jsxs(J,{children:[s.jsx(me,{"data-testid":`condition-${r.id}`,defaultValue:r.condition,label:"Condition: ",size:"sm",onChange:o=>{dt(o),e.onChange(t.id,{...r,condition:o.currentTarget.value.trim()})}},`condition-${r.id}`),s.jsx(nn,{title:"Remove Interval",variant:"subtle",size:"sm","data-testid":`remove-interval-${r.id}`,onClick:o=>{dt(o),e.onRemove(t.id,r)},children:s.jsx(Xd,{})},`remove-interval-${r.id}`)]}),s.jsx(Ix,{path:"",onChange:o=>{e.onChange(t.id,{...r,range:o})},name:`range-${r.id}`,defaultValue:r.range},`range-${r.id}`)]},`interval-${r.id}`)),s.jsx(nn,{title:"Add Interval",variant:"subtle",size:"sm",onClick:r=>{dt(r),e.onAdd(t.id,{range:{low:{unit:n},high:{unit:n}}})},children:s.jsx(Jd,{})})]})})}function eW(e){var r,o;const{intervalGroup:t,onChange:n}=e;t.filters.age||(t.filters.age={});for(const i of["low","high"])(r=t.filters.age[i])!=null&&r.unit||(t.filters.age[i]={...t.filters.age[i],unit:"years",system:"http://unitsofmeasure.org"});return s.jsxs(Ne,{style:{maxWidth:"50%"},children:[s.jsx(J,{children:s.jsx(kt,{data:["","male","female"],label:"Gender:",defaultValue:t.filters.gender||"",onChange:i=>{for(const a of t.intervals){let l=i.currentTarget.value;l===""&&(l=void 0),n(t.id,{...a,gender:l})}}})}),s.jsxs(J,{gap:"xs",children:[s.jsx(he,{component:"label",htmlFor:`div-age-${t.id}`,children:"Age:"}),s.jsx("div",{id:`div-age-${t.id}`,children:s.jsx(Ix,{path:"",name:`age-${t.id}`,defaultValue:t.filters.age,onChange:i=>{for(const a of t.intervals)n(t.id,{...a,age:i})}},`age-${t.id}`)})]}),s.jsx(kt,{data:["","pre-puberty","follicular","midcycle","luteal","postmenopausal"],label:"Endocrine:",defaultValue:((o=t.filters.context)==null?void 0:o.text)||"",onChange:i=>{for(const a of t.intervals){let l=i.currentTarget.value;l===""?(l=void 0,n(t.id,{...a,context:void 0})):n(t.id,{...a,context:{text:l,coding:[{code:l,system:"http://terminology.hl7.org/CodeSystem/referencerange-meaning"}]}})}}}),s.jsx(kt,{data:["","reference","critical","absolute"],label:"Category: ",defaultValue:t.filters.category,onChange:i=>{for(const a of t.intervals){const l=i.currentTarget.value;l===""?n(t.id,{...a,category:void 0}):n(t.id,{...a,category:l})}}})]})}function tW(e,t){const n=e.qualifiedInterval||[];let r=Math.max(...n.map(o=>{var a;const i=parseInt(((a=o.id)==null?void 0:a.substring(3))||"",10);return isNaN(i)?Number.NEGATIVE_INFINITY:i}))+1;return Number.isFinite(r)||(r=1),e={...e,qualifiedInterval:n.map(o=>({...o,id:o.id||`id-${r++}`}))},t(r),e}function nW(e,t){let n=1;const r={};for(const o of e){const i=rW(o);i in r||(r[i]={id:`group-id-${n++}`,filters:Object.fromEntries(YH.map(a=>[a,o[a]])),intervals:[]}),r[i].intervals.push(o)}return t(n),Object.values(r)}function rW(e){var n,r;return[`gender=${e.gender}`,`age=${Sc(e.age)}`,`gestationalAge=${Sc(e.gestationalAge)}`,`context=${(n=e.context)==null?void 0:n.text}`,`appliesTo=${(r=e.appliesTo)==null?void 0:r.map(o=>o.text).join("+")}`,`category=${e.category}`].join(":")}function oW(e){return e&&(F7(e,"http://unitsofmeasure.org")||e.text)}function iW(e){var t,n,r,o;return((n=(t=e.range)==null?void 0:t.low)==null?void 0:n.value)===void 0&&((o=(r=e.range)==null?void 0:r.high)==null?void 0:o.value)===void 0}function sW(e){var u;const t=ae(),n=xt(e.value),[r,o]=p.useState(!1),[i,a]=p.useState();if(p.useEffect(()=>{n&&!r&&(t.executeBatch(l(n)).then(a).catch(console.log),o(!0))},[t,n,r]),!n||!i)return null;return s.jsx(or,{children:(u=n.action)==null?void 0:u.map((d,f)=>{var v,S,y,b,x,w;const h=d.resource&&c(d.resource),m=(S=(v=h==null?void 0:h.input)==null?void 0:v[0])==null?void 0:S.valueReference,g=(b=(y=h==null?void 0:h.output)==null?void 0:y[0])==null?void 0:b.valueReference;return s.jsxs(p.Fragment,{children:[s.jsx(or.Col,{span:1,p:"md",children:(h==null?void 0:h.status)==="completed"?s.jsx(E8,{}):s.jsx(X8,{color:"gray"})}),s.jsxs(or.Col,{span:9,p:"xs",children:[s.jsx(he,{fw:500,children:d.title}),d.description&&s.jsx("div",{children:d.description}),s.jsxs("div",{children:["Last edited by ",s.jsx(fl,{value:(x=h==null?void 0:h.meta)==null?void 0:x.author})," on ",Mn((w=h==null?void 0:h.meta)==null?void 0:w.lastUpdated)]}),s.jsxs("div",{children:["Status: ",s.jsx(Mx,{status:(h==null?void 0:h.status)||"unknown"})]})]}),s.jsxs(or.Col,{span:2,p:"md",children:[m&&!g&&s.jsx(re,{onClick:()=>e.onStart(h,m),children:"Start"}),m&&g&&s.jsx(re,{onClick:()=>e.onEdit(h,m,g),children:"Edit"})]})]},`action-${f}`)})});function l(d){var h;const f=[];if(d.action)for(const m of d.action)(h=m.resource)!=null&&h.reference&&f.push({request:{method:"GET",url:m.resource.reference}});return{resourceType:"Bundle",type:"batch",entry:f}}function c(d){for(const f of i==null?void 0:i.entry)if(f.resource&&d.reference===Ct(f.resource))return f.resource}}function jR(e,t){const n=aW(e,t);return lW(n,e,t)}function aW(e,t){const n=e.length,r=t.length,o=n+r+1,i=1+2*o,a=i/2|0,l=new Array(i);l[a+1]={i:0,j:-1,prev:void 0,snake:!0};for(let c=0;c<o;c++){for(let u=-c;u<=c;u+=2){const d=a+u,f=d+1,h=d-1,m=l[f],g=l[h];let v,S=0;u===-c||u!==c&&g.i<m.i?(S=m.i,v=m):(S=g.i+1,v=g),l[h]=void 0;let y=S-u,b={i:S,j:y,prev:cW(v),snake:!1};for(;S<n&&y<r&&e[S]===t[y];)S++,y++;if(S>b.i&&(b={i:S,j:y,prev:b,snake:!0}),l[d]=b,S>=n&&y>=r)return l[d]}l[a+c-1]=void 0}}function lW(e,t,n){const r=[];let o=e;for(o.snake&&(o=o.prev);o!=null&&o.prev&&o.prev.j>=0;){const i=o.i,a=o.j;o=o.prev;const l=o.i,c=o.j,u={position:l,lines:t.slice(l,i)},d={position:c,lines:n.slice(c,a)};let f;u.lines.length===0&&d.lines.length>0?f="insert":u.lines.length>0&&d.lines.length===0?f="delete":f="change",r.push({original:u,revised:d,type:f}),o.snake&&(o=o.prev)}return r}function cW(e){return e&&!e.snake&&e.prev?e.prev:e}function uW(e){const t=e.entry.filter(r=>!!r.resource).map(r=>{var o;return{meta:(o=r.resource)==null?void 0:o.meta,lines:lr(r.resource,!0).match(/[^\r\n]+/g)}}).sort((r,o)=>r.meta.lastUpdated.localeCompare(o.meta.lastUpdated)),n=t[0].lines.map(r=>({id:t[0].meta.versionId,meta:t[0].meta,value:r,span:1}));return dW(n,t),fW(n),n}function dW(e,t){for(let n=1;n<t.length;n++){const r=jR(t[n-1].lines,t[n].lines);for(const o of r){const i=o.original.position,a=o.original.lines,l=o.revised.lines;if((o.type==="delete"||o.type==="change")&&e.splice(i,a.length),o.type==="insert"||o.type==="change")for(let c=0;c<o.revised.lines.length;c++)e.splice(i+c,0,{id:t[n].meta.versionId,meta:t[n].meta,value:l[c],span:1})}}}function fW(e){let t=0;for(;t<e.length;){let n=t;for(;n<e.length&&e[n].id===e[t].id;)e[n].span=-1,n++;e[t].span=n-t,t=n}}const hW="_container_1oj0p_1",pW="_root_1oj0p_5",mW="_startRow_1oj0p_20",gW="_normalRow_1oj0p_24",vW="_author_1oj0p_28",yW="_dateTime_1oj0p_32",xW="_lineNumber_1oj0p_37",bW="_line_1oj0p_37",wW="_pre_1oj0p_52",bo={container:hW,root:pW,startRow:mW,normalRow:gW,author:vW,dateTime:yW,lineNumber:xW,line:bW,pre:wW};function SW(e,t){return`/${e.resourceType}/${e.id}/_history/${t}`}function jW(e){const t=Math.floor((Date.now()-Date.parse(e))/1e3),n=Math.floor(t/31536e3);if(n>0)return na(n,"year");const r=Math.floor(t/2592e3);if(r>0)return na(r,"month");const o=Math.floor(t/86400);if(o>0)return na(o,"day");const i=Math.floor(t/3600);if(i>0)return na(i,"hour");const a=Math.floor(t/60);return a>0?na(a,"minute"):na(t,"second")}function na(e,t){return`${e} ${e===1?t:t+"s"} ago`}function CW(e){var a,l;const t=ae(),[n,r]=p.useState(e.history);if(p.useEffect(()=>{!e.history&&e.resourceType&&e.id&&t.readHistory(e.resourceType,e.id).then(r).catch(console.log)},[t,e.history,e.resourceType,e.id]),!n)return s.jsx("div",{children:"Loading..."});const o=(l=(a=n.entry)==null?void 0:a[0])==null?void 0:l.resource;if(!o)return null;const i=uW(n);return s.jsx("div",{className:bo.container,children:s.jsx("table",{className:bo.root,children:s.jsx("tbody",{children:i.map((c,u)=>s.jsxs("tr",{className:c.span>0?bo.startRow:bo.normalRow,children:[c.span>0&&s.jsxs(s.Fragment,{children:[s.jsx("td",{className:bo.author,rowSpan:c.span,children:s.jsx(Da,{value:c.meta.author,link:!0})}),s.jsx("td",{className:bo.dateTime,rowSpan:c.span,children:s.jsx(Ge,{to:SW(o,c.meta.versionId),children:jW(c.meta.lastUpdated)})})]}),s.jsx("td",{className:bo.lineNumber,children:u+1}),s.jsx("td",{className:bo.line,children:s.jsx("pre",{className:bo.pre,children:c.value})})]},"row-"+u))})})})}const EW="_removed_mgz0k_2",TW="_added_mgz0k_7",vw={removed:EW,added:TW};function PW(e){let t=e.original,n=e.revised;e.ignoreMeta&&(t={...t,meta:void 0},n={...n,meta:void 0});const r=lr(t,!0).match(/[^\r\n]+/g),o=lr(n,!0).match(/[^\r\n]+/g),i=jR(r,o);return s.jsx("pre",{style:{color:"gray"},children:i.map((a,l)=>s.jsx(kW,{delta:a},"delta"+l))})}function kW(e){return s.jsxs(s.Fragment,{children:["...",s.jsx("br",{}),e.delta.original.lines.length>0&&s.jsx("div",{className:vw.removed,children:e.delta.original.lines.join(`
523
523
  `)}),e.delta.revised.lines.length>0&&s.jsx("div",{className:vw.added,children:e.delta.revised.lines.join(`
524
- `)}),"...",s.jsx("br",{})]})}function rf(e){const{outcome:t}=e,n=ae(),r=xt(e.defaultValue),[o,i]=p.useState(),[a,l]=p.useState(),c=n.getAccessPolicy();p.useEffect(()=>{if(r)if(e.profileUrl){const f=e.profileUrl;n.requestProfileSchema(e.profileUrl,{expandProfile:!0}).then(()=>{const h=Ls(f);if(h){i(h.name);const m=n8(r,h);l(m)}else console.error(`Schema not found for ${f}`)}).catch(h=>{console.error("Error in requestProfileSchema",h)})}else{const f=e.schemaName??(r==null?void 0:r.resourceType);n.requestSchema(f).then(()=>{l(r),i(f)}).catch(console.log)}},[n,r,e.schemaName,e.profileUrl]);const u=p.useMemo(()=>r&&WP(r,gx.READ,c),[c,r]),d=p.useMemo(()=>n.isSuperAdmin()||!c||!Ot(a==null?void 0:a.resourceType)?!0:fF(c,a==null?void 0:a.resourceType),[n,c,a==null?void 0:a.resourceType]);return!o||!a?s.jsx("div",{children:"Loading..."}):d?s.jsxs("form",{noValidate:!0,autoComplete:"off",onSubmit:f=>{f.preventDefault(),e.onSubmit&&e.onSubmit(a)},children:[s.jsxs(Ne,{mb:"xl",children:[s.jsx(mt,{title:"Resource Type",htmlFor:"resourceType",outcome:t,children:s.jsx(me,{name:"resourceType",defaultValue:a.resourceType,disabled:!0})}),s.jsx(mt,{title:"ID",htmlFor:"id",outcome:t,children:s.jsx(me,{name:"id",defaultValue:a.id,disabled:!0})})]}),s.jsx(Nx,{path:a.resourceType,valuePath:a.resourceType,typeName:o,defaultValue:a,outcome:t,onChange:l,profileUrl:e.profileUrl,accessPolicyResource:u}),s.jsxs(J,{justify:"flex-end",mt:"xl",children:[s.jsx(re,{type:"submit",children:"OK"}),e.onDelete&&s.jsx(re,{variant:"outline",color:"red",type:"button",onClick:()=>{e.onDelete(a)},children:"Delete"})]})]}):s.jsxs(Li,{color:"red",title:"Permission denied",icon:s.jsx(cl,{}),children:["Your access level prevents you from editing and creating ",a.resourceType," resources."]})}function RW(e){var o;const t=ae(),[n,r]=p.useState(e.history);return p.useEffect(()=>{!e.history&&e.resourceType&&e.id&&t.readHistory(e.resourceType,e.id).then(r).catch(console.log)},[t,e.history,e.resourceType,e.id]),n?s.jsxs(fe,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[s.jsx(fe.Thead,{children:s.jsxs(fe.Tr,{children:[s.jsx(fe.Th,{children:"Author"}),s.jsx(fe.Th,{children:"Date"}),s.jsx(fe.Th,{children:"Version"})]})}),s.jsx(fe.Tbody,{children:(o=n.entry)==null?void 0:o.map((i,a)=>s.jsx(_W,{entry:i},"entry-"+a))})]}):s.jsx("div",{children:"Loading..."})}function _W(e){var r,o,i;const{response:t,resource:n}=e.entry;return n?s.jsxs(fe.Tr,{children:[s.jsx(fe.Td,{children:s.jsx(Da,{value:(r=n.meta)==null?void 0:r.author,link:!0})}),s.jsx(fe.Td,{children:Mn((o=n.meta)==null?void 0:o.lastUpdated)}),s.jsx(fe.Td,{children:s.jsx(Ge,{to:DW(n),children:(i=n.meta)==null?void 0:i.versionId})})]}):s.jsx(fe.Tr,{children:s.jsx(fe.Td,{colSpan:3,children:Me(t==null?void 0:t.outcome)})})}function DW(e){var t;return`/${e.resourceType}/${e.id}/_history/${(t=e.meta)==null?void 0:t.versionId}`}function IW(e){return s.jsx(wh,{value:e.serviceRequest,loadTimelineResources:async(t,n,r)=>{const o=`${n}/${r}`,i=100;return Promise.allSettled([t.readHistory("ServiceRequest",r),t.search("Communication",{"based-on":o,_count:i}),t.search("DiagnosticReport",{"based-on":o,_count:i}),t.search("Media",{"based-on":o,_count:i}),t.search("DocumentReference",{related:o,_count:i}),t.search("Task",{_filter:`based-on eq ${o} or focus eq ${o} or subject eq ${o}`,_count:i})])},createCommunication:(t,n,r)=>({resourceType:"Communication",status:"completed",basedOn:[jt(t)],subject:t.subject,sender:jt(n),sent:new Date().toISOString(),payload:[{contentString:r}]}),createMedia:(t,n,r)=>({resourceType:"Media",status:"completed",basedOn:[jt(t)],subject:t.subject,operator:jt(n),issued:new Date().toISOString(),content:r})})}function AW(e){const t=ae(),{client:n,patient:r,encounter:o,children:i,...a}=e;function l(){t.createResource({resourceType:"SmartAppLaunch",patient:r,encounter:o}).then(c=>{const u=new URL(n.launchUri);u.searchParams.set("iss",t.getBaseUrl()+"fhir/R4"),u.searchParams.set("launch",c.id),window.location.assign(u.toString())}).catch(c=>ye({color:"red",message:Me(c),autoClose:!1}))}return s.jsx(Ze,{onClick:()=>l(),...a,children:i})}function CR(e){const t=ae(),[n,r]=p.useState();return s.jsxs(Ke,{onSubmit:async o=>{try{e.handleAuthResponse(await t.startNewProject({login:e.login,projectName:o.projectName}))}catch(i){r(vt(i))}},children:[s.jsxs(fn,{style:{flexDirection:"column"},children:[s.jsx(Xr,{size:32}),s.jsx(pe,{children:"Create project"})]}),s.jsxs(Ne,{gap:"xl",children:[s.jsx(me,{name:"projectName",label:"Project Name",placeholder:"My Project",required:!0,autoFocus:!0,error:Xe(n,"firstName")}),s.jsxs(he,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",s.jsx(Ze,{href:"https://www.medplum.com/privacy",children:"Privacy Policy"})," and ",s.jsx(Ze,{href:"https://www.medplum.com/terms",children:"Terms of Service"}),"."]})]}),s.jsx(J,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(re,{type:"submit",children:"Create project"})})]})}function ER(e,t){const n=document.getElementsByTagName("head")[0],r=document.createElement("script");r.async=!0,r.src=e,r.onload=t??null,n.appendChild(r)}function TR(e){const t=ae(),{googleClientId:n,handleGoogleCredential:r}=e,o=p.useRef(null),[i,a]=p.useState(typeof google<"u"),[l,c]=p.useState(!1),[u,d]=p.useState(!1);return p.useEffect(()=>{if(typeof google>"u"){ER("https://accounts.google.com/gsi/client",()=>a(!0));return}l||(google.accounts.id.initialize({client_id:n,callback:r}),c(!0)),o.current&&!u&&(google.accounts.id.renderButton(o.current,{}),d(!0))},[t,n,l,i,o,u,r]),n?s.jsx("div",{ref:o}):null}var NW={MEDPLUM_BASE_URL:"__MEDPLUM_BASE_URL__",MEDPLUM_CLIENT_ID:"__MEDPLUM_CLIENT_ID__",GOOGLE_CLIENT_ID:"__GOOGLE_CLIENT_ID__",RECAPTCHA_SITE_KEY:"__RECAPTCHA_SITE_KEY__",MEDPLUM_REGISTER_ENABLED:"__MEDPLUM_REGISTER_ENABLED__",MEDPLUM_VERSION:"3.1.9-eb1d4ee09",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function PR(e){var t;if(e)return e;if(typeof window<"u"){const n=window.location.protocol+"//"+window.location.host;if((((t=NW.GOOGLE_AUTH_ORIGINS)==null?void 0:t.split(","))??[]).includes(n))return"__GOOGLE_CLIENT_ID__"}}function kR(e){typeof grecaptcha>"u"&&ER("https://www.google.com/recaptcha/api.js?render="+e)}function RR(e){return new Promise((t,n)=>{grecaptcha.ready(async()=>{try{t(await grecaptcha.execute(e,{action:"submit"}))}catch(r){n(r)}})})}function MW(e){const t=PR(e.googleClientId),n=e.recaptchaSiteKey,r=ae(),[o,i]=p.useState(),a=iu(o,void 0);return p.useEffect(()=>{n&&kR(n)},[n]),s.jsxs(Ke,{onSubmit:async l=>{try{let c="";n&&(c=await RR(n)),e.handleAuthResponse(await r.startNewUser({projectId:e.projectId,clientId:e.clientId,firstName:l.firstName,lastName:l.lastName,email:l.email,password:l.password,remember:l.remember==="true",recaptchaSiteKey:n,recaptchaToken:c}))}catch(c){i(vt(c))}},children:[s.jsx(fn,{style:{flexDirection:"column"},children:e.children}),s.jsx(Jr,{issues:a}),t&&s.jsxs(s.Fragment,{children:[s.jsx(J,{justify:"center",p:"xl",style:{height:70},children:s.jsx(TR,{googleClientId:t,handleGoogleCredential:async l=>{try{e.handleAuthResponse(await r.startGoogleLogin({googleClientId:l.clientId,googleCredential:l.credential,projectId:e.projectId,createUser:!0}))}catch(c){i(vt(c))}}})}),s.jsx(Zt,{label:"or",labelPosition:"center",my:"lg"})]}),s.jsxs(Ne,{gap:"xl",children:[s.jsx(me,{name:"firstName",type:"text",label:"First name",placeholder:"First name",required:!0,autoFocus:!0,error:Xe(o,"firstName")}),s.jsx(me,{name:"lastName",type:"text",label:"Last name",placeholder:"Last name",required:!0,error:Xe(o,"lastName")}),s.jsx(me,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,error:Xe(o,"email")}),s.jsx(Ur,{name:"password",label:"Password",autoComplete:"off",required:!0,error:Xe(o,"password")}),s.jsxs(he,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",s.jsx(Ze,{href:"https://www.medplum.com/privacy",children:"Privacy Policy"})," and ",s.jsx(Ze,{href:"https://www.medplum.com/terms",children:"Terms of Service"}),"."]}),s.jsxs(he,{c:"dimmed",size:"xs",children:["This site is protected by reCAPTCHA and the Google"," ",s.jsx(Ze,{href:"https://policies.google.com/privacy",children:"Privacy Policy"})," and ",s.jsx(Ze,{href:"https://policies.google.com/terms",children:"Terms of Service"})," apply."]})]}),s.jsxs(J,{justify:"space-between",mt:"xl",wrap:"nowrap",children:[s.jsx(Xn,{name:"remember",label:"Remember me",size:"xs"}),s.jsx(re,{type:"submit",children:"Create account"})]})]})}function OW(e){const{type:t,projectId:n,clientId:r,googleClientId:o,recaptchaSiteKey:i,onSuccess:a}=e,l=ae(),[c,u]=p.useState(),[d,f]=p.useState();p.useEffect(()=>{t==="patient"&&c&&l.startNewPatient({login:c,projectId:n}).then(m=>l.processCode(m.code)).then(()=>a()).catch(m=>f(vt(m)))},[l,t,n,c,a]);function h(m){m.code?l.processCode(m.code).then(()=>a()).catch(console.log):m.login&&u(m.login)}return s.jsxs(Ie,{width:450,children:[d&&s.jsx("pre",{children:JSON.stringify(d,null,2)}),!c&&s.jsx(MW,{projectId:n,clientId:r,googleClientId:o,recaptchaSiteKey:i,handleAuthResponse:h,children:e.children}),c&&t==="project"&&s.jsx(CR,{login:c,handleAuthResponse:h})]})}function $W(e){const[t,n]=p.useState();return t?s.jsx(FW,{email:t,...e}):s.jsx(LW,{setEmail:n,...e})}function LW(e){const{setEmail:t,onRegister:n,handleAuthResponse:r,children:o,disableEmailAuth:i,...a}=e,l=ae(),c=!e.disableGoogleAuth&&PR(e.googleClientId),[u,d]=p.useState(),f=iu(u,void 0),h=p.useCallback(async v=>{if(!v.authorizeUrl)return!1;const S=JSON.stringify({...await l.ensureCodeChallenge(a),domain:v.domain}),y=new URL(v.authorizeUrl);return y.searchParams.set("state",S),window.location.assign(y.toString()),!0},[l,a]),m=p.useCallback(async v=>{const S=await l.post("auth/method",{email:v.email});await h(S)||t(v.email)},[l,h,t]),g=p.useCallback(async v=>{try{const S=await l.startGoogleLogin({...a,googleCredential:v.credential});await h(S)||r(S)}catch(S){d(vt(S))}},[l,a,h,r]);return s.jsxs(Ke,{onSubmit:m,children:[s.jsx(fn,{style:{flexDirection:"column"},children:o}),s.jsx(Jr,{issues:f}),c&&s.jsxs(s.Fragment,{children:[s.jsx(J,{justify:"center",p:"xl",style:{height:70},children:s.jsx(TR,{googleClientId:c,handleGoogleCredential:g})}),!i&&s.jsx(Zt,{label:"or",labelPosition:"center",my:"lg"})]}),!i&&s.jsx(me,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,autoFocus:!0,error:Xe(u,"email")}),s.jsxs(J,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[s.jsx("div",{children:n&&s.jsx(Ze,{component:"button",type:"button",color:"dimmed",onClick:n,size:"xs",children:"Register"})}),!i&&s.jsx(re,{type:"submit",children:"Next"})]})]})}function FW(e){const{onForgotPassword:t,handleAuthResponse:n,children:r,...o}=e,i=ae(),[a,l]=p.useState(),c=iu(a,void 0),u=p.useCallback(d=>{i.startLogin({...o,password:d.password,remember:d.remember==="on"}).then(n).catch(f=>l(vt(f)))},[i,o,n]);return s.jsxs(Ke,{onSubmit:u,children:[s.jsx(fn,{style:{flexDirection:"column"},children:r}),s.jsx(Jr,{issues:c}),s.jsx(Ne,{gap:"xl",children:s.jsx(Ur,{name:"password",label:"Password",autoComplete:"off",required:!0,autoFocus:!0,error:Xe(a,"password")})}),s.jsxs(J,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[t&&s.jsx(Ze,{component:"button",type:"button",c:"dimmed",onClick:t,size:"xs",children:"Forgot password"}),s.jsx(Xn,{id:"remember",name:"remember",label:"Remember me",size:"xs",style:{lineHeight:1}}),s.jsx(re,{type:"submit",children:"Sign in"})]})]})}function zW(e){const t=ae(),n=Vc(),[r,o]=p.useState(""),[i,a]=p.useState();function l(f){var h;return!!((h=f==null?void 0:f.toLowerCase())!=null&&h.includes(r.toLowerCase()))}function c(f){var h,m;return l((h=f.profile)==null?void 0:h.display)||l((m=f.project)==null?void 0:m.display)}function u(f){t.post("auth/profile",{login:e.login,profile:f}).then(e.handleAuthResponse).catch(h=>a(vt(h)))}const d=e.memberships.filter(c).slice(0,10).map(f=>s.jsx(Ae.Option,{value:f.id,children:s.jsx(BW,{...f})},f.id));return s.jsxs(Ne,{children:[s.jsxs(ms,{gap:"md",mb:"md",justify:"center",align:"center",direction:"column",wrap:"nowrap",children:[s.jsx(Xr,{size:32}),s.jsx(pe,{order:3,children:"Choose profile"})]}),s.jsx(Jr,{outcome:i}),s.jsxs(Ae,{store:n,onOptionSubmit:u,children:[s.jsx(Ae.EventsTarget,{children:s.jsx(me,{placeholder:"Search",value:r,onChange:f=>{o(f.currentTarget.value),n.updateSelectedOptionIndex()}})}),s.jsx("div",{children:s.jsx(Ae.Options,{children:d.length>0?d:s.jsx(Ae.Empty,{children:"Nothing found..."})})})]})]})}function BW(e){var t,n;return s.jsxs(J,{children:[s.jsx(gs,{radius:"xl"}),s.jsxs("div",{children:[s.jsx(he,{fz:"sm",fw:500,children:(t=e.profile)==null?void 0:t.display}),s.jsx(he,{fz:"xs",opacity:.6,children:(n=e.project)==null?void 0:n.display})]})]})}function VW(e){const t=ae();return s.jsx(Ke,{onSubmit:n=>{t.post("auth/scope",{login:e.login,scope:Object.keys(n).join(" ")}).then(e.handleAuthResponse).catch(console.log)},children:s.jsxs(Ne,{children:[s.jsxs(fn,{style:{flexDirection:"column"},children:[s.jsx(Xr,{size:32}),s.jsx(pe,{children:"Choose scope"})]}),s.jsx(Ne,{children:(e.scope??"openid").split(" ").map(n=>s.jsx(Xn,{id:n,name:n,label:n,defaultChecked:!0},n))}),s.jsx(J,{justify:"flex-end",mt:"xl",children:s.jsx(re,{type:"submit",children:"Set scope"})})]})})}function UW(e){const t=ae(),[n,r]=p.useState();return s.jsx(Ke,{onSubmit:o=>{r(void 0),t.post("auth/mfa/verify",{login:e.login,token:o.token}).then(e.handleAuthResponse).catch(i=>r(Me(i)))},children:s.jsxs(Ne,{children:[s.jsxs(fn,{style:{flexDirection:"column"},children:[s.jsx(Xr,{size:32}),s.jsx(pe,{children:"Enter MFA code"})]}),n&&s.jsx(Li,{icon:s.jsx(cl,{size:16}),title:"Error",color:"red",children:n}),s.jsx(Ne,{children:s.jsx(me,{name:"token",label:"MFA code",required:!0,autoFocus:!0})}),s.jsx(J,{justify:"flex-end",mt:"xl",children:s.jsx(re,{type:"submit",children:"Submit code"})})]})})}function _R(e){const{login:t,chooseScopes:n,onSuccess:r,onForgotPassword:o,onRegister:i,onCode:a,...l}=e,c=ae(),[u,d]=p.useState(),f=p.useRef(!1),[h,m]=p.useState(!1),[g,v]=p.useState(),S=p.useCallback(x=>{a?a(x):c.processCode(x).then(()=>{r&&r()}).catch(w=>ye({color:"red",message:Me(w)}))},[c,a,r]),y=p.useCallback(x=>{m(!!x.mfaRequired),x.login&&d(x.login),x.memberships&&v(x.memberships),x.code&&(n?v(void 0):S(x.code))},[n,S]),b=p.useCallback(x=>{S(x.code)},[S]);return p.useEffect(()=>{t&&!f.current&&!u&&(f.current=!0,c.get("auth/login/"+t).then(y).catch(x=>ye({color:"red",message:Me(x)})))},[c,t,f,u,y]),s.jsx(Ie,{width:450,px:"sm",py:"md",children:u?h?s.jsx(UW,{login:u,handleAuthResponse:y}):g?s.jsx(zW,{login:u,memberships:g,handleAuthResponse:y}):e.projectId==="new"?s.jsx(CR,{login:u,handleAuthResponse:y}):e.chooseScopes?s.jsx(VW,{login:u,scope:e.scope,handleAuthResponse:b}):s.jsx("div",{children:"Success"}):s.jsx($W,{onForgotPassword:o,onRegister:i,handleAuthResponse:y,disableGoogleAuth:e.disableGoogleAuth,disableEmailAuth:e.disableEmailAuth,...l,children:e.children})})}var DR,yw=$c;DR=yw.createRoot,yw.hydrateRoot;/**
524
+ `)}),"...",s.jsx("br",{})]})}function rf(e){const{outcome:t}=e,n=ae(),r=xt(e.defaultValue),[o,i]=p.useState(),[a,l]=p.useState(),c=n.getAccessPolicy();p.useEffect(()=>{if(r)if(e.profileUrl){const f=e.profileUrl;n.requestProfileSchema(e.profileUrl,{expandProfile:!0}).then(()=>{const h=Ls(f);if(h){i(h.name);const m=n8(r,h);l(m)}else console.error(`Schema not found for ${f}`)}).catch(h=>{console.error("Error in requestProfileSchema",h)})}else{const f=e.schemaName??(r==null?void 0:r.resourceType);n.requestSchema(f).then(()=>{l(r),i(f)}).catch(console.log)}},[n,r,e.schemaName,e.profileUrl]);const u=p.useMemo(()=>r&&WP(r,gx.READ,c),[c,r]),d=p.useMemo(()=>n.isSuperAdmin()||!c||!Ot(a==null?void 0:a.resourceType)?!0:fF(c,a==null?void 0:a.resourceType),[n,c,a==null?void 0:a.resourceType]);return!o||!a?s.jsx("div",{children:"Loading..."}):d?s.jsxs("form",{noValidate:!0,autoComplete:"off",onSubmit:f=>{f.preventDefault(),e.onSubmit&&e.onSubmit(a)},children:[s.jsxs(Ne,{mb:"xl",children:[s.jsx(mt,{title:"Resource Type",htmlFor:"resourceType",outcome:t,children:s.jsx(me,{name:"resourceType",defaultValue:a.resourceType,disabled:!0})}),s.jsx(mt,{title:"ID",htmlFor:"id",outcome:t,children:s.jsx(me,{name:"id",defaultValue:a.id,disabled:!0})})]}),s.jsx(Nx,{path:a.resourceType,valuePath:a.resourceType,typeName:o,defaultValue:a,outcome:t,onChange:l,profileUrl:e.profileUrl,accessPolicyResource:u}),s.jsxs(J,{justify:"flex-end",mt:"xl",children:[s.jsx(re,{type:"submit",children:"OK"}),e.onDelete&&s.jsx(re,{variant:"outline",color:"red",type:"button",onClick:()=>{e.onDelete(a)},children:"Delete"})]})]}):s.jsxs(Li,{color:"red",title:"Permission denied",icon:s.jsx(cl,{}),children:["Your access level prevents you from editing and creating ",a.resourceType," resources."]})}function RW(e){var o;const t=ae(),[n,r]=p.useState(e.history);return p.useEffect(()=>{!e.history&&e.resourceType&&e.id&&t.readHistory(e.resourceType,e.id).then(r).catch(console.log)},[t,e.history,e.resourceType,e.id]),n?s.jsxs(fe,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[s.jsx(fe.Thead,{children:s.jsxs(fe.Tr,{children:[s.jsx(fe.Th,{children:"Author"}),s.jsx(fe.Th,{children:"Date"}),s.jsx(fe.Th,{children:"Version"})]})}),s.jsx(fe.Tbody,{children:(o=n.entry)==null?void 0:o.map((i,a)=>s.jsx(_W,{entry:i},"entry-"+a))})]}):s.jsx("div",{children:"Loading..."})}function _W(e){var r,o,i;const{response:t,resource:n}=e.entry;return n?s.jsxs(fe.Tr,{children:[s.jsx(fe.Td,{children:s.jsx(Da,{value:(r=n.meta)==null?void 0:r.author,link:!0})}),s.jsx(fe.Td,{children:Mn((o=n.meta)==null?void 0:o.lastUpdated)}),s.jsx(fe.Td,{children:s.jsx(Ge,{to:DW(n),children:(i=n.meta)==null?void 0:i.versionId})})]}):s.jsx(fe.Tr,{children:s.jsx(fe.Td,{colSpan:3,children:Me(t==null?void 0:t.outcome)})})}function DW(e){var t;return`/${e.resourceType}/${e.id}/_history/${(t=e.meta)==null?void 0:t.versionId}`}function IW(e){return s.jsx(wh,{value:e.serviceRequest,loadTimelineResources:async(t,n,r)=>{const o=`${n}/${r}`,i=100;return Promise.allSettled([t.readHistory("ServiceRequest",r),t.search("Communication",{"based-on":o,_count:i}),t.search("DiagnosticReport",{"based-on":o,_count:i}),t.search("Media",{"based-on":o,_count:i}),t.search("DocumentReference",{related:o,_count:i}),t.search("Task",{_filter:`based-on eq ${o} or focus eq ${o} or subject eq ${o}`,_count:i})])},createCommunication:(t,n,r)=>({resourceType:"Communication",status:"completed",basedOn:[jt(t)],subject:t.subject,sender:jt(n),sent:new Date().toISOString(),payload:[{contentString:r}]}),createMedia:(t,n,r)=>({resourceType:"Media",status:"completed",basedOn:[jt(t)],subject:t.subject,operator:jt(n),issued:new Date().toISOString(),content:r})})}function AW(e){const t=ae(),{client:n,patient:r,encounter:o,children:i,...a}=e;function l(){t.createResource({resourceType:"SmartAppLaunch",patient:r,encounter:o}).then(c=>{const u=new URL(n.launchUri);u.searchParams.set("iss",t.getBaseUrl()+"fhir/R4"),u.searchParams.set("launch",c.id),window.location.assign(u.toString())}).catch(c=>ye({color:"red",message:Me(c),autoClose:!1}))}return s.jsx(Ze,{onClick:()=>l(),...a,children:i})}function CR(e){const t=ae(),[n,r]=p.useState();return s.jsxs(Ke,{onSubmit:async o=>{try{e.handleAuthResponse(await t.startNewProject({login:e.login,projectName:o.projectName}))}catch(i){r(vt(i))}},children:[s.jsxs(fn,{style:{flexDirection:"column"},children:[s.jsx(Xr,{size:32}),s.jsx(pe,{children:"Create project"})]}),s.jsxs(Ne,{gap:"xl",children:[s.jsx(me,{name:"projectName",label:"Project Name",placeholder:"My Project",required:!0,autoFocus:!0,error:Xe(n,"firstName")}),s.jsxs(he,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",s.jsx(Ze,{href:"https://www.medplum.com/privacy",children:"Privacy Policy"})," and ",s.jsx(Ze,{href:"https://www.medplum.com/terms",children:"Terms of Service"}),"."]})]}),s.jsx(J,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(re,{type:"submit",children:"Create project"})})]})}function ER(e,t){const n=document.getElementsByTagName("head")[0],r=document.createElement("script");r.async=!0,r.src=e,r.onload=t??null,n.appendChild(r)}function TR(e){const t=ae(),{googleClientId:n,handleGoogleCredential:r}=e,o=p.useRef(null),[i,a]=p.useState(typeof google<"u"),[l,c]=p.useState(!1),[u,d]=p.useState(!1);return p.useEffect(()=>{if(typeof google>"u"){ER("https://accounts.google.com/gsi/client",()=>a(!0));return}l||(google.accounts.id.initialize({client_id:n,callback:r}),c(!0)),o.current&&!u&&(google.accounts.id.renderButton(o.current,{}),d(!0))},[t,n,l,i,o,u,r]),n?s.jsx("div",{ref:o}):null}var NW={MEDPLUM_BASE_URL:"__MEDPLUM_BASE_URL__",MEDPLUM_CLIENT_ID:"__MEDPLUM_CLIENT_ID__",GOOGLE_CLIENT_ID:"__GOOGLE_CLIENT_ID__",RECAPTCHA_SITE_KEY:"__RECAPTCHA_SITE_KEY__",MEDPLUM_REGISTER_ENABLED:"__MEDPLUM_REGISTER_ENABLED__",MEDPLUM_VERSION:"3.1.10-7ae504bff",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function PR(e){var t;if(e)return e;if(typeof window<"u"){const n=window.location.protocol+"//"+window.location.host;if((((t=NW.GOOGLE_AUTH_ORIGINS)==null?void 0:t.split(","))??[]).includes(n))return"__GOOGLE_CLIENT_ID__"}}function kR(e){typeof grecaptcha>"u"&&ER("https://www.google.com/recaptcha/api.js?render="+e)}function RR(e){return new Promise((t,n)=>{grecaptcha.ready(async()=>{try{t(await grecaptcha.execute(e,{action:"submit"}))}catch(r){n(r)}})})}function MW(e){const t=PR(e.googleClientId),n=e.recaptchaSiteKey,r=ae(),[o,i]=p.useState(),a=iu(o,void 0);return p.useEffect(()=>{n&&kR(n)},[n]),s.jsxs(Ke,{onSubmit:async l=>{try{let c="";n&&(c=await RR(n)),e.handleAuthResponse(await r.startNewUser({projectId:e.projectId,clientId:e.clientId,firstName:l.firstName,lastName:l.lastName,email:l.email,password:l.password,remember:l.remember==="true",recaptchaSiteKey:n,recaptchaToken:c}))}catch(c){i(vt(c))}},children:[s.jsx(fn,{style:{flexDirection:"column"},children:e.children}),s.jsx(Jr,{issues:a}),t&&s.jsxs(s.Fragment,{children:[s.jsx(J,{justify:"center",p:"xl",style:{height:70},children:s.jsx(TR,{googleClientId:t,handleGoogleCredential:async l=>{try{e.handleAuthResponse(await r.startGoogleLogin({googleClientId:l.clientId,googleCredential:l.credential,projectId:e.projectId,createUser:!0}))}catch(c){i(vt(c))}}})}),s.jsx(Zt,{label:"or",labelPosition:"center",my:"lg"})]}),s.jsxs(Ne,{gap:"xl",children:[s.jsx(me,{name:"firstName",type:"text",label:"First name",placeholder:"First name",required:!0,autoFocus:!0,error:Xe(o,"firstName")}),s.jsx(me,{name:"lastName",type:"text",label:"Last name",placeholder:"Last name",required:!0,error:Xe(o,"lastName")}),s.jsx(me,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,error:Xe(o,"email")}),s.jsx(Ur,{name:"password",label:"Password",autoComplete:"off",required:!0,error:Xe(o,"password")}),s.jsxs(he,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",s.jsx(Ze,{href:"https://www.medplum.com/privacy",children:"Privacy Policy"})," and ",s.jsx(Ze,{href:"https://www.medplum.com/terms",children:"Terms of Service"}),"."]}),s.jsxs(he,{c:"dimmed",size:"xs",children:["This site is protected by reCAPTCHA and the Google"," ",s.jsx(Ze,{href:"https://policies.google.com/privacy",children:"Privacy Policy"})," and ",s.jsx(Ze,{href:"https://policies.google.com/terms",children:"Terms of Service"})," apply."]})]}),s.jsxs(J,{justify:"space-between",mt:"xl",wrap:"nowrap",children:[s.jsx(Xn,{name:"remember",label:"Remember me",size:"xs"}),s.jsx(re,{type:"submit",children:"Create account"})]})]})}function OW(e){const{type:t,projectId:n,clientId:r,googleClientId:o,recaptchaSiteKey:i,onSuccess:a}=e,l=ae(),[c,u]=p.useState(),[d,f]=p.useState();p.useEffect(()=>{t==="patient"&&c&&l.startNewPatient({login:c,projectId:n}).then(m=>l.processCode(m.code)).then(()=>a()).catch(m=>f(vt(m)))},[l,t,n,c,a]);function h(m){m.code?l.processCode(m.code).then(()=>a()).catch(console.log):m.login&&u(m.login)}return s.jsxs(Ie,{width:450,children:[d&&s.jsx("pre",{children:JSON.stringify(d,null,2)}),!c&&s.jsx(MW,{projectId:n,clientId:r,googleClientId:o,recaptchaSiteKey:i,handleAuthResponse:h,children:e.children}),c&&t==="project"&&s.jsx(CR,{login:c,handleAuthResponse:h})]})}function $W(e){const[t,n]=p.useState();return t?s.jsx(FW,{email:t,...e}):s.jsx(LW,{setEmail:n,...e})}function LW(e){const{setEmail:t,onRegister:n,handleAuthResponse:r,children:o,disableEmailAuth:i,...a}=e,l=ae(),c=!e.disableGoogleAuth&&PR(e.googleClientId),[u,d]=p.useState(),f=iu(u,void 0),h=p.useCallback(async v=>{if(!v.authorizeUrl)return!1;const S=JSON.stringify({...await l.ensureCodeChallenge(a),domain:v.domain}),y=new URL(v.authorizeUrl);return y.searchParams.set("state",S),window.location.assign(y.toString()),!0},[l,a]),m=p.useCallback(async v=>{const S=await l.post("auth/method",{email:v.email});await h(S)||t(v.email)},[l,h,t]),g=p.useCallback(async v=>{try{const S=await l.startGoogleLogin({...a,googleCredential:v.credential});await h(S)||r(S)}catch(S){d(vt(S))}},[l,a,h,r]);return s.jsxs(Ke,{onSubmit:m,children:[s.jsx(fn,{style:{flexDirection:"column"},children:o}),s.jsx(Jr,{issues:f}),c&&s.jsxs(s.Fragment,{children:[s.jsx(J,{justify:"center",p:"xl",style:{height:70},children:s.jsx(TR,{googleClientId:c,handleGoogleCredential:g})}),!i&&s.jsx(Zt,{label:"or",labelPosition:"center",my:"lg"})]}),!i&&s.jsx(me,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,autoFocus:!0,error:Xe(u,"email")}),s.jsxs(J,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[s.jsx("div",{children:n&&s.jsx(Ze,{component:"button",type:"button",color:"dimmed",onClick:n,size:"xs",children:"Register"})}),!i&&s.jsx(re,{type:"submit",children:"Next"})]})]})}function FW(e){const{onForgotPassword:t,handleAuthResponse:n,children:r,...o}=e,i=ae(),[a,l]=p.useState(),c=iu(a,void 0),u=p.useCallback(d=>{i.startLogin({...o,password:d.password,remember:d.remember==="on"}).then(n).catch(f=>l(vt(f)))},[i,o,n]);return s.jsxs(Ke,{onSubmit:u,children:[s.jsx(fn,{style:{flexDirection:"column"},children:r}),s.jsx(Jr,{issues:c}),s.jsx(Ne,{gap:"xl",children:s.jsx(Ur,{name:"password",label:"Password",autoComplete:"off",required:!0,autoFocus:!0,error:Xe(a,"password")})}),s.jsxs(J,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[t&&s.jsx(Ze,{component:"button",type:"button",c:"dimmed",onClick:t,size:"xs",children:"Forgot password"}),s.jsx(Xn,{id:"remember",name:"remember",label:"Remember me",size:"xs",style:{lineHeight:1}}),s.jsx(re,{type:"submit",children:"Sign in"})]})]})}function zW(e){const t=ae(),n=Vc(),[r,o]=p.useState(""),[i,a]=p.useState();function l(f){var h;return!!((h=f==null?void 0:f.toLowerCase())!=null&&h.includes(r.toLowerCase()))}function c(f){var h,m;return l((h=f.profile)==null?void 0:h.display)||l((m=f.project)==null?void 0:m.display)}function u(f){t.post("auth/profile",{login:e.login,profile:f}).then(e.handleAuthResponse).catch(h=>a(vt(h)))}const d=e.memberships.filter(c).slice(0,10).map(f=>s.jsx(Ae.Option,{value:f.id,children:s.jsx(BW,{...f})},f.id));return s.jsxs(Ne,{children:[s.jsxs(ms,{gap:"md",mb:"md",justify:"center",align:"center",direction:"column",wrap:"nowrap",children:[s.jsx(Xr,{size:32}),s.jsx(pe,{order:3,children:"Choose profile"})]}),s.jsx(Jr,{outcome:i}),s.jsxs(Ae,{store:n,onOptionSubmit:u,children:[s.jsx(Ae.EventsTarget,{children:s.jsx(me,{placeholder:"Search",value:r,onChange:f=>{o(f.currentTarget.value),n.updateSelectedOptionIndex()}})}),s.jsx("div",{children:s.jsx(Ae.Options,{children:d.length>0?d:s.jsx(Ae.Empty,{children:"Nothing found..."})})})]})]})}function BW(e){var t,n;return s.jsxs(J,{children:[s.jsx(gs,{radius:"xl"}),s.jsxs("div",{children:[s.jsx(he,{fz:"sm",fw:500,children:(t=e.profile)==null?void 0:t.display}),s.jsx(he,{fz:"xs",opacity:.6,children:(n=e.project)==null?void 0:n.display})]})]})}function VW(e){const t=ae();return s.jsx(Ke,{onSubmit:n=>{t.post("auth/scope",{login:e.login,scope:Object.keys(n).join(" ")}).then(e.handleAuthResponse).catch(console.log)},children:s.jsxs(Ne,{children:[s.jsxs(fn,{style:{flexDirection:"column"},children:[s.jsx(Xr,{size:32}),s.jsx(pe,{children:"Choose scope"})]}),s.jsx(Ne,{children:(e.scope??"openid").split(" ").map(n=>s.jsx(Xn,{id:n,name:n,label:n,defaultChecked:!0},n))}),s.jsx(J,{justify:"flex-end",mt:"xl",children:s.jsx(re,{type:"submit",children:"Set scope"})})]})})}function UW(e){const t=ae(),[n,r]=p.useState();return s.jsx(Ke,{onSubmit:o=>{r(void 0),t.post("auth/mfa/verify",{login:e.login,token:o.token}).then(e.handleAuthResponse).catch(i=>r(Me(i)))},children:s.jsxs(Ne,{children:[s.jsxs(fn,{style:{flexDirection:"column"},children:[s.jsx(Xr,{size:32}),s.jsx(pe,{children:"Enter MFA code"})]}),n&&s.jsx(Li,{icon:s.jsx(cl,{size:16}),title:"Error",color:"red",children:n}),s.jsx(Ne,{children:s.jsx(me,{name:"token",label:"MFA code",required:!0,autoFocus:!0})}),s.jsx(J,{justify:"flex-end",mt:"xl",children:s.jsx(re,{type:"submit",children:"Submit code"})})]})})}function _R(e){const{login:t,chooseScopes:n,onSuccess:r,onForgotPassword:o,onRegister:i,onCode:a,...l}=e,c=ae(),[u,d]=p.useState(),f=p.useRef(!1),[h,m]=p.useState(!1),[g,v]=p.useState(),S=p.useCallback(x=>{a?a(x):c.processCode(x).then(()=>{r&&r()}).catch(w=>ye({color:"red",message:Me(w)}))},[c,a,r]),y=p.useCallback(x=>{m(!!x.mfaRequired),x.login&&d(x.login),x.memberships&&v(x.memberships),x.code&&(n?v(void 0):S(x.code))},[n,S]),b=p.useCallback(x=>{S(x.code)},[S]);return p.useEffect(()=>{t&&!f.current&&!u&&(f.current=!0,c.get("auth/login/"+t).then(y).catch(x=>ye({color:"red",message:Me(x)})))},[c,t,f,u,y]),s.jsx(Ie,{width:450,px:"sm",py:"md",children:u?h?s.jsx(UW,{login:u,handleAuthResponse:y}):g?s.jsx(zW,{login:u,memberships:g,handleAuthResponse:y}):e.projectId==="new"?s.jsx(CR,{login:u,handleAuthResponse:y}):e.chooseScopes?s.jsx(VW,{login:u,scope:e.scope,handleAuthResponse:b}):s.jsx("div",{children:"Success"}):s.jsx($W,{onForgotPassword:o,onRegister:i,handleAuthResponse:y,disableGoogleAuth:e.disableGoogleAuth,disableEmailAuth:e.disableEmailAuth,...l,children:e.children})})}var DR,yw=$c;DR=yw.createRoot,yw.hydrateRoot;/**
525
525
  * @remix-run/router v1.16.1
526
526
  *
527
527
  * Copyright (c) Remix Software Inc.
@@ -560,4 +560,4 @@ Error generating stack: `+i.message+`
560
560
  }
561
561
  ]
562
562
  }`,pK="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 mK(){const e=ae(),{id:t}=lt(),[n,r]=p.useState(),[o,i]=p.useState(),[a,l]=p.useState(hK),[c,u]=p.useState(pK),[d,f]=p.useState(Jt.FHIR_JSON),h=p.useRef(null),m=p.useRef(null),[g,v]=p.useState(!1);p.useEffect(()=>{e.readResource("Bot",t).then(async E=>{r(E),i(await gK(e,E))}).catch(E=>ye({color:"red",message:Me(E),autoClose:!1}))},[e,t]);const S=p.useCallback(()=>pd(h.current,{command:"getValue"}),[]),y=p.useCallback(()=>pd(h.current,{command:"getOutput"}),[]),b=p.useCallback(async()=>d===Jt.FHIR_JSON?JSON.parse(a):c,[d,a,c]),x=p.useCallback(async E=>{E.preventDefault(),E.stopPropagation(),v(!0);try{const C=await S(),T=await e.createAttachment(C,"index.ts","text/typescript"),_=[];n!=null&&n.sourceCode?_.push({op:"replace",path:"/sourceCode",value:T}):_.push({op:"add",path:"/sourceCode",value:T}),await e.patchResource("Bot",t,_),ye({color:"green",message:"Saved"})}catch(C){ye({color:"red",message:Me(C),autoClose:!1})}finally{v(!1)}},[e,t,n,S]),w=p.useCallback(async E=>{E.preventDefault(),E.stopPropagation(),v(!0);try{const C=await y();await e.post(e.fhirUrl("Bot",t,"$deploy"),{code:C}),ye({color:"green",message:"Deployed"})}catch(C){ye({color:"red",message:Me(C),autoClose:!1})}finally{v(!1)}},[e,t,y]),j=p.useCallback(async E=>{E.preventDefault(),E.stopPropagation(),v(!0);try{const C=await b(),T=await e.post(e.fhirUrl("Bot",t,"$execute"),C,d);await pd(m.current,{command:"setValue",value:T}),ye({color:"green",message:"Success"})}catch(C){ye({color:"red",message:Me(C),autoClose:!1})}finally{v(!1)}},[e,t,b,d]);return!n||o===void 0?null:s.jsxs(or,{m:0,gutter:0,style:{overflow:"hidden"},children:[s.jsx(or.Col,{span:8,children:s.jsxs(qn,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",mih:400,children:[s.jsx(fK,{iframeRef:h,language:"typescript",module:"commonjs",testId:"code-frame",defaultValue:o,minHeight:"528px"}),s.jsxs(J,{justify:"flex-end",gap:"xs",children:[s.jsx(re,{type:"button",onClick:x,loading:g,leftSection:s.jsx(k8,{size:"1rem"}),children:"Save"}),s.jsx(re,{type:"button",onClick:w,loading:g,leftSection:s.jsx(Sx,{size:"1rem"}),children:"Deploy"}),s.jsx(re,{type:"button",onClick:j,loading:g,leftSection:s.jsx(H8,{size:"1rem"}),children:"Execute"})]})]})}),s.jsxs(or.Col,{span:4,children:[s.jsxs(qn,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[s.jsx(kt,{data:[{label:"FHIR",value:Jt.FHIR_JSON},{label:"HL7",value:Jt.HL7_V2}],onChange:E=>f(E.currentTarget.value)}),d===Jt.FHIR_JSON?s.jsx(rl,{value:a,onChange:E=>l(E),autosize:!0,minRows:15}):s.jsx("textarea",{className:uK.hl7Input,value:c,onChange:E=>u(E.currentTarget.value),rows:15})]}),s.jsx(qn,{m:2,p:"xs",shadow:"md",children:s.jsx(dK,{iframeRef:m,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function gK(e,t){var n,r,o;if((n=t.sourceCode)!=null&&n.url){const i=(o=(r=t.sourceCode.url)==null?void 0:r.split("/"))==null?void 0:o.find(DP);return(await e.download(e.fhirUrl("Binary",i))).text()}return t.code??""}function Vs(e){let t=e.meta;return t&&(t={...t,lastUpdated:void 0,versionId:void 0,author:void 0}),{...e,meta:t}}function vK(){const e=ae(),{resourceType:t,id:n}=lt(),r={reference:t+"/"+n},o=p.useCallback(i=>{e.updateResource(Vs(i)).then(()=>{ye({color:"green",message:"Success"})}).catch(a=>{ye({color:"red",message:Me(a),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return s.jsx(Ie,{children:s.jsx(ZU,{value:r,onSubmit:o})});case"Questionnaire":return s.jsx(Ie,{children:s.jsx(OH,{questionnaire:r,onSubmit:o})});default:return null}}function yK(){const{resourceType:e,id:t}=lt(),n=xt({reference:e+"/"+t}),r=Vt();return n?s.jsx(Ie,{children:s.jsx(sW,{value:n,onStart:(o,i)=>r(`/forms/${dh(i)}`),onEdit:(o,i,a)=>r(`/${a.reference}}`)})}):null}function xK(){const e=ae(),{resourceType:t,id:n}=lt(),r=Vt();return s.jsxs(Ie,{children:[s.jsxs("p",{children:["Are you sure you want to delete this ",t,"?"]}),s.jsx(re,{color:"red",onClick:()=>{e.deleteResource(t,n).then(()=>r(`/${t}`)).catch(o=>ye({color:"red",message:Me(o),autoClose:!1}))},children:"Delete"})]})}const bK="_selectProfileBtn_tbaz6_1",wK="_chevron_tbaz6_13",Zw={selectProfileBtn:bK,chevron:wK};function SK(){var c,u;const{resourceType:e,id:t}=lt(),n=xt({reference:e+"/"+t}),[r,o]=p.useState(),i=Vc({onDropdownClose:()=>i.resetSelectedOption()}),a=p.useMemo(()=>{var d;if(Ot((d=n==null?void 0:n.meta)==null?void 0:d.profile))return[s.jsx(Ae.Option,{value:"",children:"None"},""),...n.meta.profile.map(f=>s.jsx(Ae.Option,{value:f,children:f},f))]},[(c=n==null?void 0:n.meta)==null?void 0:c.profile]);if(p.useEffect(()=>{var d,f;((f=(d=n==null?void 0:n.meta)==null?void 0:d.profile)==null?void 0:f.length)===1&&o(n.meta.profile[0])},[(u=n==null?void 0:n.meta)==null?void 0:u.profile]),!n)return null;let l;return Ot(a)&&(l=s.jsx(J,{justify:"flex-end",children:s.jsxs(Ne,{align:"flex-end",gap:"xs",children:[s.jsxs(Ae,{store:i,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:d=>{o(d),i.closeDropdown()},children:[s.jsx(Ae.Target,{children:s.jsx(vn,{onClick:()=>i.toggleDropdown(),children:s.jsxs(yy,{fw:"bold",fs:"sm",className:Zw.selectProfileBtn,children:[s.jsx("span",{children:"Pick profile"}),s.jsx(ck,{stroke:1.5,className:Zw.chevron})]})})}),s.jsx(Ae.Dropdown,{w:"max-content",children:s.jsx(Ae.Options,{children:a})})]}),s.jsx(W,{children:r?s.jsxs(s.Fragment,{children:[s.jsx(he,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),s.jsx(he,{span:!0,size:"sm",children:r||"Nothing selected"})]}):s.jsx(he,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),s.jsx(Ie,{children:s.jsxs(Ne,{gap:"xl",children:[l,s.jsx(Vx,{value:n,profileUrl:r})]})})}function jK(){const e=ae(),{resourceType:t,id:n}=lt(),[r,o]=p.useState(),i=Vt(),[a,l]=p.useState();p.useEffect(()=>{e.readResource(t,n).then(d=>o(mo(d))).catch(d=>{l(vt(d)),ye({color:"red",message:Me(d),autoClose:!1})})},[e,t,n]);const c=p.useCallback(d=>{l(void 0),e.updateResource(Vs(d)).then(()=>{i(`/${t}/${n}/details`),ye({color:"green",message:"Success"})}).catch(f=>{l(vt(f)),ye({color:"red",message:Me(f),autoClose:!1})})},[e,t,n,i]),u=p.useCallback(()=>i(`/${t}/${n}/delete`),[i,t,n]);return r?s.jsx(Ie,{children:s.jsx(rf,{defaultValue:r,onSubmit:c,onDelete:u,outcome:a})}):null}function c2({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,o=ae(),[i,a]=p.useState();return p.useEffect(()=>{o.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(l=>{a(l.filter(cB))}).catch(console.error)},[o,n,r]),s.jsx(et,{value:t==null?void 0:t.url,onChange:l=>{const c=i==null?void 0:i.find(u=>u.url===l);c&&n(c)},children:s.jsx(et.List,{children:i==null?void 0:i.map(l=>{var d,f;const c=(f=(d=e.meta)==null?void 0:d.profile)==null?void 0:f.includes(l.url),u=c?"This profile is present in this resource's meta.profile property.":"This profile is not included in this resource's meta.profile property.";return s.jsx(et.Tab,{value:l.url,title:u,rightSection:c&&s.jsx(Zy,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:s.jsx(nz,{size:"90%"})}),children:l.title||l.name},l.url)})})})}function u2(e,t){const n=ae(),r=Vt();return{defaultValue:{resourceType:e},handleSubmit:a=>{t&&t(void 0),n.createResource(a).then(l=>r("/"+l.resourceType+"/"+l.id)).catch(l=>{t&&t(vt(l)),ye({color:"red",message:Me(l),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function Op(){const{resourceType:e}=lt(),t=Jo(),[n,r]=p.useState(),{defaultValue:o,handleSubmit:i}=u2(e,r),[a,l]=p.useState(),c=t.pathname.toLowerCase().endsWith("profiles"),u=p.useCallback(d=>{const f=Vs(d);a&&NP(f,a.url),i(f)},[a,i]);return c?s.jsx(Ie,{children:s.jsxs(Ne,{children:[s.jsx(c2,{resource:o,currentProfile:a,onChange:l}),a?s.jsx(rf,{defaultValue:o,onSubmit:u,outcome:n,profileUrl:a.url},a.url):s.jsx(he,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):s.jsx(Ie,{children:s.jsx(rf,{defaultValue:o,onSubmit:i,outcome:n})})}function CK(){const e=ae(),{resourceType:t,id:n}=lt(),r=e.readHistory(t,n).read();return s.jsx(Ie,{children:s.jsx(RW,{history:r})})}function EK(){const{resourceType:e}=lt(),[t,n]=p.useState(),{defaultValue:r,handleSubmit:o}=u2(e,n),i=p.useCallback(a=>{o(JSON.parse(a["new-resource"]))},[o]);return s.jsxs(Ie,{children:[t&&s.jsx(Jr,{outcome:t}),s.jsxs(Ke,{onSubmit:i,children:[s.jsx(rl,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:lr(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),s.jsx(J,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(re,{type:"submit",children:"OK"})})]})]})}function TK(){const e=ae(),{resourceType:t,id:n}=lt(),r=xt({reference:t+"/"+n}),o=Vt(),[i,a]=p.useState(),l=p.useCallback(c=>{e.updateResource(Vs(JSON.parse(c.resource))).then(()=>{a(void 0),o(`/${t}/${n}/details`),ye({color:"green",message:"Success"})}).catch(u=>{ye({color:"red",message:Me(u),autoClose:!1})})},[e,t,n,o]);return r?s.jsxs(Ie,{children:[i&&s.jsx(Jr,{outcome:i}),s.jsxs(Ke,{onSubmit:l,children:[s.jsx(rl,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:lr(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),s.jsx(J,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(re,{type:"submit",children:"OK"})})]})]}):null}function PK(){const{resourceType:e,id:t}=lt();return xt({reference:e+"/"+t})?s.jsxs(Ie,{children:[s.jsxs(Li,{icon:s.jsx(cl,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",s.jsx("br",{}),s.jsx(Ze,{href:`/forms/${t}`,children:`/forms/${t}`})]}),s.jsx(wR,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function kK(){const e=ae(),{resourceType:t,id:n}=lt(),[r,o]=p.useState(),[i,a]=p.useState();return p.useEffect(()=>{e.readResource(t,n).then(l=>o(mo(l))).catch(l=>{ye({color:"red",message:Me(l)})})},[e,t,n]),r?s.jsxs(Ie,{children:[s.jsxs(pe,{order:2,children:["Available ",t," profiles"]}),s.jsx(Ne,{children:s.jsxs(s.Fragment,{children:[s.jsx(c2,{resource:r,currentProfile:i,onChange:a}),i?s.jsx(RK,{profile:i,resource:r,onResourceUpdated:l=>o(l)},i.url):s.jsx(he,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const RK=({profile:e,resource:t,onResourceUpdated:n})=>{const r=ae(),[o,i]=p.useState(),[a,l]=p.useState(()=>{var u,d;return(d=(u=t.meta)==null?void 0:u.profile)==null?void 0:d.includes(e.url)}),c=p.useCallback(u=>{i(void 0);const d=Vs(u);a?NP(d,e.url):W7(d,e.url),r.updateResource(d).then(f=>{n(f),ye({color:"green",message:"Success"})}).catch(f=>{i(vt(f)),ye({color:"red",message:Me(f),autoClose:!1})})},[r,e.url,n,a]);return s.jsxs(Ne,{children:[s.jsx(Qc,{size:"md",checked:a,label:`Conform resource to ${e.title}`,onChange:u=>l(u.currentTarget.checked),"data-testid":"profile-toggle"}),a?s.jsx(rf,{profileUrl:e.url,defaultValue:t,onSubmit:c,outcome:o}):s.jsx("form",{noValidate:!0,onSubmit:u=>{u.preventDefault(),c(t)},children:s.jsx(J,{justify:"flex-end",mt:"xl",children:s.jsx(re,{type:"submit",children:"OK"})})})]})};function _K(){const e=ae(),{id:t}=lt(),[n,r]=p.useState(),[o,i]=p.useState(0),a=e.searchResources("Subscription","status=active&_count=100").read().filter(c=>DK(c,t));function l(){n&&e.createResource({resourceType:"Subscription",status:"active",reason:`Connect bot ${n.name} to questionnaire responses`,criteria:"QuestionnaireResponse?questionnaire=Questionnaire/"+t,channel:{type:"rest-hook",endpoint:Ct(n)}}).then(()=>{r(void 0),i(Date.now()),e.invalidateSearches("Subscription"),ye({color:"green",message:"Success"})}).catch(c=>ye({color:"red",message:Me(c),autoClose:!1}))}return s.jsxs(Ie,{children:[s.jsx(pe,{children:"Bots"}),a.length===0&&s.jsx("p",{children:"No bots found."}),a.map(c=>{var u;return s.jsxs("div",{children:[s.jsx("h3",{children:s.jsx(fl,{value:{reference:(u=c.channel)==null?void 0:u.endpoint},link:!0})}),s.jsxs("p",{children:["Criteria: ",c.criteria]})]},c.id)}),s.jsx("hr",{}),s.jsx(pe,{children:"Connect to bot"}),s.jsxs(J,{children:[s.jsx(ul,{name:"bot",resourceType:"Bot",onChange:c=>r(c)}),s.jsx(re,{onClick:l,children:"Connect"})]}),s.jsx("div",{style:{display:"none"},children:o})]})}function DK(e,t){var o;const n=e.criteria||"",r=((o=e.channel)==null?void 0:o.endpoint)||"";return n.startsWith("QuestionnaireResponse?")&&n.includes(t)&&r.startsWith("Bot/")}function IK(){const{id:e}=lt(),t=Vt(),[n,r]=p.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:te.EQUALS,value:"Questionnaire/"+e}],fields:["id","_lastUpdated"]});return s.jsx(Ie,{children:s.jsx(cu,{search:n,onClick:o=>t(`/${o.resource.resourceType}/${o.resource.id}`),onChange:o=>r(o.definition),hideFilters:!0,hideToolbar:!0})})}function AK(){const e=ae(),{resourceType:t,id:n}=lt(),r=xt({reference:t+"/"+n}),o=p.useCallback(i=>{e.updateResource(Vs(i)).then(()=>{ye({color:"green",message:"Success"})}).catch(a=>{ye({color:"red",message:Me(a),autoClose:!1})})},[e]);return r?s.jsx(Ie,{children:s.jsx(JH,{onSubmit:o,definition:r})}):null}function NK(){const{resourceType:e,id:t}=lt(),n=xt({reference:e+"/"+t});return n?s.jsx(Ie,{children:e==="MeasureReport"?s.jsx(GU,{measureReport:n}):s.jsx(Ox,{value:n})}):null}const MK="_container_1ue98_1",OK="_entry_1ue98_14",$K="_active_1ue98_21",$p={container:MK,entry:OK,active:$K};function LK(e){const t=ae(),n=xt(e.value),[r,o]=p.useState();return p.useEffect(()=>{if(!n)return;const i=o0(n);if(!i)return;const a="reference"in i?i.reference:Ct(i);t.search("ServiceRequest","subject="+a).then(l=>{const u=l.entry.map(d=>d.resource);Xk(u),u.reverse(),o(u)}).catch(l=>ye({color:"red",message:Me(l),autoClose:!1}))},[t,n]),r?s.jsx("div",{"data-testid":"quick-service-requests",className:$p.container,children:r.map(i=>{var a,l,c,u,d,f,h;return s.jsxs("div",{className:rt($p.entry,{[$p.active]:i.id===(n==null?void 0:n.id)}),children:[s.jsx("p",{children:s.jsx(Ge,{to:i,children:FK(i)})}),((l=(a=i.category)==null?void 0:a[0])==null?void 0:l.text)&&s.jsx("p",{children:(c=i.category[0])==null?void 0:c.text}),((f=(d=(u=i.code)==null?void 0:u.coding)==null?void 0:d[0])==null?void 0:f.code)&&s.jsx("p",{children:(h=i.code.coding[0])==null?void 0:h.code}),s.jsx("p",{children:zK(i)})]},i.id)})}):null}function FK(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function zK(e){var t;return e.authoredOn?e.authoredOn.substring(0,10):(t=e.meta)!=null&&t.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const BK="_container_1l2dh_1",VK={container:BK};function UK(e){var o,i,a,l;const t=xt(e.valueSet);if(!t)return null;const n=[""],r=(l=(a=(i=(o=t.compose)==null?void 0:o.include)==null?void 0:i[0])==null?void 0:a.concept)==null?void 0:l.map(c=>c.code);return r&&n.push(...r),e.defaultValue&&!n.includes(e.defaultValue)&&n.push(e.defaultValue),s.jsx("div",{className:VK.container,children:s.jsx(kt,{defaultValue:e.defaultValue,onChange:c=>e.onChange(c.currentTarget.value),data:n})})}function HK(e){var n,r;const t=xt(e.specimen);return t?s.jsxs(Fe,{children:[s.jsxs(Fe.Entry,{children:[s.jsx(Fe.Key,{children:"Type"}),s.jsx(Fe.Value,{children:"Specimen"})]}),s.jsxs(Fe.Entry,{children:[s.jsx(Fe.Key,{children:"Collected"}),s.jsx(Fe.Value,{children:Mn((n=t.collection)==null?void 0:n.collectedDateTime)})]}),s.jsxs(Fe.Entry,{children:[s.jsx(Fe.Key,{children:"Specimen Age"}),s.jsx(Fe.Value,{children:WK(t)})]}),(r=t.collection)!=null&&r.collectedDateTime&&t.receivedTime?s.jsxs(Fe.Entry,{children:[s.jsx(Fe.Key,{children:"Specimen Stability"}),s.jsx(Fe.Value,{children:qK(t)})]}):s.jsx(s.Fragment,{})]}):null}function WK(e){var o;const t=(o=e.collection)==null?void 0:o.collectedDateTime;if(!t)return;const n=new Date(t);return d2(f2(n,new Date))}function qK(e){var r;if(!((r=e.collection)!=null&&r.collectedDateTime)||!e.receivedTime)return;const t=new Date(e.collection.collectedDateTime),n=new Date(e.receivedTime);return d2(f2(t,n))}function d2(e){return e.toString().padStart(3,"0")+"D"}function f2(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function GK(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==="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"),t}const QK=["Profiles"];function KK(){var x,w,j,E,C,T,_;const e=ae(),{resourceType:t,id:n}=lt(),r={reference:t+"/"+n},o=Vt(),[i,a]=p.useState(),l=xt(r,a),c=GK(t),[u,d]=p.useState(()=>{const k=window.location.pathname.split("/").pop();return k&&c.map(N=>N.toLowerCase()).includes(k)?k:c[0].toLowerCase()}),f=At();async function h(){var D,M;const N=(M=(D=(await e.readHistory(t,n)).entry)==null?void 0:D.find(I=>!!I.resource))==null?void 0:M.resource;N?m(N):ye({color:"red",message:"No history to restore",autoClose:!1})}function m(k){e.updateResource(Vs(k)).then(()=>{a(void 0),ye({color:"green",message:"Success"})}).catch(N=>{ye({color:"red",message:Me(N),autoClose:!1})})}if(i)return mL(i)?s.jsxs(Ie,{children:[s.jsx(pe,{children:"Deleted"}),s.jsx("p",{children:"The resource was deleted."}),s.jsx(re,{color:"red",onClick:h,children:"Restore"})]}):s.jsx(Jr,{outcome:i});function g(k){k||(k=c[0].toLowerCase()),d(k),o(`/${t}/${n}/${k}`)}function v(k){const N=l,D=N.orderDetail||[];D.length===0&&D.push({}),D[0].text!==k&&(D[0].text=k,m({...N,orderDetail:D}))}const S=l&&o0(l),y=l&&wQ(l),b=(j=(w=(x=e.getUserConfiguration())==null?void 0:x.option)==null?void 0:w.find(k=>k.id==="statusValueSet"))==null?void 0:j.valueString;return s.jsxs(s.Fragment,{children:[(l==null?void 0:l.resourceType)==="ServiceRequest"&&b&&s.jsx(UK,{valueSet:{reference:b},defaultValue:(C=(E=l.orderDetail)==null?void 0:E[0])==null?void 0:C.text,onChange:v},Ct(l)+"-"+((_=(T=l.orderDetail)==null?void 0:T[0])==null?void 0:_.text)),l&&s.jsx(LK,{value:l}),l&&s.jsxs(qn,{children:[S&&s.jsx(i2,{patient:S}),y&&s.jsx(HK,{specimen:y}),t!=="Patient"&&s.jsx(s2,{resource:r}),s.jsx(kr,{children:s.jsx(et,{value:u.toLowerCase(),onChange:g,children:s.jsx(et.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:c.map(k=>s.jsx(et.Tab,{value:k.toLowerCase(),children:QK.includes(k)?s.jsxs(J,{gap:"xs",wrap:"nowrap",children:[k,s.jsx(Uc,{color:f.primaryColor,size:"sm",children:"Beta"})]}):k},k))})})})]}),s.jsx(Zx,{})]})}function eS(){var y,b,x,w;const e=Vt(),{resourceType:t,id:n,versionId:r,tab:o}=lt(),i=ae(),[a,l]=p.useState(!0),[c,u]=p.useState(),[d,f]=p.useState();if(p.useEffect(()=>{f(void 0),l(!0),i.readHistory(t,n).then(j=>u(j)).then(()=>l(!1)).catch(j=>{f(j),l(!1)})},[i,t,n]),a)return s.jsx(qr,{});if(!c)return s.jsxs(Ie,{children:[s.jsx(pe,{children:"Resource not found"}),s.jsx(Ge,{to:`/${t}`,children:"Return to search page"})]});const h=c.entry,m=h.findIndex(j=>{var E,C;return((C=(E=j.resource)==null?void 0:E.meta)==null?void 0:C.versionId)===r});if(m===-1)return s.jsxs(Ie,{children:[s.jsx(pe,{children:"Version not found"}),s.jsx(Ge,{to:`/${t}/${n}`,children:"Return to resource"})]});const g=h[m].resource,v=m<h.length-1?h[m+1].resource:void 0,S="diff";return s.jsxs(et,{value:o||S,onChange:j=>e(`/${t}/${n}/_history/${r}/${j||S}`),children:[s.jsxs(qn,{children:[s.jsx(su,{fluid:!0,p:"md",children:s.jsx(he,{children:`${t} ${n}`})}),s.jsxs(et.List,{children:[s.jsx(et.Tab,{value:"diff",children:"Diff"}),s.jsx(et.Tab,{value:"raw",children:"Raw"})]})]}),s.jsxs(Ie,{children:[d&&s.jsx("pre",{"data-testid":"error",children:JSON.stringify(d,void 0,2)}),s.jsx(et.Panel,{value:"diff",children:v?s.jsxs(s.Fragment,{children:[s.jsxs("ul",{children:[s.jsxs("li",{children:["Current: ",(y=g.meta)==null?void 0:y.versionId]}),s.jsxs("li",{children:["Previous:"," ",s.jsx(Ge,{to:`/${t}/${n}/_history/${(b=v.meta)==null?void 0:b.versionId}`,children:(x=v.meta)==null?void 0:x.versionId})]})]}),s.jsx(PW,{original:v,revised:g})]}):s.jsxs(s.Fragment,{children:[s.jsxs("ul",{children:[s.jsxs("li",{children:["Current: ",(w=g.meta)==null?void 0:w.versionId]}),s.jsx("li",{children:"Previous: (none)"})]}),s.jsx("pre",{children:JSON.stringify(g,void 0,2)})]})}),s.jsx(et.Panel,{value:"raw",children:s.jsx("pre",{children:JSON.stringify(g,void 0,2)})})]})]})}function YK(){const{resourceType:e,id:t}=lt(),n=Vt(),[r,o]=p.useState({resourceType:"Subscription",filters:[{code:"url",operator:te.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return s.jsx(Ie,{children:s.jsx(cu,{search:r,onClick:i=>n(`/${i.resource.resourceType}/${i.resource.id}`),onChange:i=>o(i.definition),hideFilters:!0})})}function tS(){const{resourceType:e,id:t}=lt(),n={reference:e+"/"+t};switch(e){case"Encounter":return s.jsx(HV,{encounter:n});case"Patient":return s.jsx(QU,{patient:n});case"ServiceRequest":return s.jsx(IW,{serviceRequest:n});default:return s.jsx(UV,{resource:n})}}function XK(){const e=ae(),{id:t}=lt(),n=p.useMemo(()=>({reference:"Agent/"+t}),[t]),[r,o]=p.useState(!1),[i,a]=p.useState(!1),[l,c]=p.useState(!1),[u,d]=p.useState(),[f,h]=p.useState(),[m,g]=p.useState(),[v,S]=p.useState(),[y,b]=p.useState(!1),[x,w]=p.useState(!1);p.useEffect(()=>{if(r||i||l||y){w(!0);return}w(!1)},[r,i,l,y]);const j=p.useCallback(()=>{o(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(N=>{var D,M,I,L,A,R;d((M=(D=N.parameter)==null?void 0:D.find(P=>P.name==="status"))==null?void 0:M.valueCode),h((L=(I=N.parameter)==null?void 0:I.find(P=>P.name==="version"))==null?void 0:L.valueString),g((R=(A=N.parameter)==null?void 0:A.find(P=>P.name==="lastUpdated"))==null?void 0:R.valueInstant)}).catch(N=>k(Me(N))).finally(()=>o(!1))},[e,t]),E=p.useCallback(N=>{const D=N.host,M=N.pingCount||1;D&&(b(!0),e.pushToAgent(n,D,`PING ${M}`,Jt.PING,!0).then(I=>S(I)).catch(I=>k(Me(I))).finally(()=>b(!1)))},[e,n]),C=p.useCallback(()=>{a(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(N=>{_("Agent config reloaded successfully.")}).catch(N=>k(Me(N))).finally(()=>a(!1))},[e,t]),T=p.useCallback(()=>{c(!0),e.get(e.fhirUrl("Agent",t,"$upgrade"),{cache:"reload"}).then(N=>{_("Agent upgraded successfully.")}).catch(N=>k(Me(N))).finally(()=>c(!1))},[e,t]);function _(N){ye({color:"green",title:"Success",icon:s.jsx(eu,{size:"1rem"}),message:N})}function k(N){ye({color:"red",title:"Error",message:N,autoClose:!1})}return s.jsxs(Ie,{children:[s.jsx(pe,{order:1,children:"Agent Tools"}),s.jsxs("div",{style:{marginBottom:10},children:["Agent: ",s.jsx(fl,{value:n,link:!0})]}),s.jsx(Zt,{my:"lg"}),s.jsx(pe,{order:2,children:"Agent Status"}),s.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."}),s.jsx(re,{onClick:j,loading:r,disabled:x&&!r,children:"Get Status"}),!r&&u&&s.jsx(fe,{children:s.jsxs(fe.Tbody,{children:[s.jsxs(fe.Tr,{children:[s.jsx(fe.Td,{children:"Status"}),s.jsx(fe.Td,{children:s.jsx(Mx,{status:u})})]}),s.jsxs(fe.Tr,{children:[s.jsx(fe.Td,{children:"Version"}),s.jsx(fe.Td,{children:f})]}),s.jsxs(fe.Tr,{children:[s.jsx(fe.Td,{children:"Last Updated"}),s.jsx(fe.Td,{children:Mn(m,void 0,{timeZoneName:"longOffset"})})]})]})}),s.jsx(Zt,{my:"lg"}),s.jsx(pe,{order:2,children:"Reload Config"}),s.jsx("p",{children:"Reload the configuration of this agent, syncing it with the current version of the Agent resource on the Medplum server."}),s.jsx(re,{onClick:C,loading:i,disabled:x&&!i,"aria-label":"Reload config",children:"Reload Config"}),s.jsx(Zt,{my:"lg"}),s.jsx(pe,{order:2,children:"Upgrade Agent"}),s.jsx("p",{children:"Upgrade the version of this agent, to either the latest (default) or a specified version."}),s.jsx(re,{onClick:T,loading:l,disabled:x&&!l,"aria-label":"Upgrade agent",children:"Upgrade"}),s.jsx(Zt,{my:"lg"}),s.jsx(pe,{order:2,children:"Ping from Agent"}),s.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."}),s.jsx(Ke,{onSubmit:E,children:s.jsxs(J,{children:[s.jsx(me,{id:"host",name:"host",placeholder:"ex. 127.0.0.1",label:"IP Address / Hostname",rightSection:s.jsx(nn,{size:24,radius:"xl",variant:"filled",type:"submit","aria-label":"Ping",loading:y,disabled:x&&!y,children:s.jsx(K8,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),s.jsx(Oy,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!y&&v&&s.jsxs(s.Fragment,{children:[s.jsx(pe,{order:5,mt:"sm",mb:0,children:"Last Ping"}),s.jsx("pre",{children:v})]})]})}function JK(){return s.jsx(tG,{children:s.jsxs(xe,{errorElement:s.jsx(mQ,{}),children:[s.jsx(xe,{path:"/signin",element:s.jsx(FQ,{})}),s.jsx(xe,{path:"/oauth",element:s.jsx(NQ,{})}),s.jsx(xe,{path:"/resetpassword",element:s.jsx(OQ,{})}),s.jsx(xe,{path:"/setpassword/:id/:secret",element:s.jsx(LQ,{})}),s.jsx(xe,{path:"/register",element:s.jsx(MQ,{})}),s.jsx(xe,{path:"/changepassword",element:s.jsx(fQ,{})}),s.jsx(xe,{path:"/security",element:s.jsx($Q,{})}),s.jsx(xe,{path:"/mfa",element:s.jsx(AQ,{})}),s.jsx(xe,{path:"/batch",element:s.jsx(uQ,{})}),s.jsx(xe,{path:"/bulk/:resourceType",element:s.jsx(dQ,{})}),s.jsx(xe,{path:"/smart",element:s.jsx(zQ,{})}),s.jsx(xe,{path:"/forms/:id",element:s.jsx(jQ,{})}),s.jsx(xe,{path:"/admin/super",element:s.jsx(ZQ,{})}),s.jsx(xe,{path:"/admin/config",element:s.jsx(KQ,{})}),s.jsxs(xe,{path:"/admin",element:s.jsx(YQ,{}),children:[s.jsx(xe,{path:"patients",element:s.jsx(QQ,{})}),s.jsx(xe,{path:"bots/new",element:s.jsx(UQ,{})}),s.jsx(xe,{path:"bots",element:s.jsx(BQ,{})}),s.jsx(xe,{path:"clients/new",element:s.jsx(HQ,{})}),s.jsx(xe,{path:"clients",element:s.jsx(VQ,{})}),s.jsx(xe,{path:"details",element:s.jsx(Yw,{})}),s.jsx(xe,{path:"invite",element:s.jsx(GQ,{})}),s.jsx(xe,{path:"users",element:s.jsx(eK,{})}),s.jsx(xe,{path:"project",element:s.jsx(Yw,{})}),s.jsx(xe,{path:"secrets",element:s.jsx(XQ,{})}),s.jsx(xe,{path:"sites",element:s.jsx(JQ,{})}),s.jsx(xe,{path:"members/:membershipId",element:s.jsx(qQ,{})})]}),s.jsx(xe,{path:"/lab/assays",element:s.jsx(tK,{})}),s.jsx(xe,{path:"/lab/panels",element:s.jsx(nK,{})}),s.jsx(xe,{path:"/:resourceType/:id/_history/:versionId/:tab",element:s.jsx(eS,{})}),s.jsx(xe,{path:"/:resourceType/:id/_history/:versionId",element:s.jsx(eS,{})}),s.jsxs(xe,{path:"/:resourceType/new",element:s.jsx(pQ,{}),children:[s.jsx(xe,{index:!0,element:s.jsx(Op,{})}),s.jsx(xe,{path:"form",element:s.jsx(Op,{})}),s.jsx(xe,{path:"json",element:s.jsx(EK,{})}),s.jsx(xe,{path:"profiles",element:s.jsx(Op,{})})]}),s.jsxs(xe,{path:"/:resourceType/:id",element:s.jsx(KK,{}),children:[s.jsx(xe,{index:!0,element:s.jsx(tS,{})}),s.jsx(xe,{path:"apply",element:s.jsx(oK,{})}),s.jsx(xe,{path:"apps",element:s.jsx(iK,{})}),s.jsx(xe,{path:"event",element:s.jsx(aK,{})}),s.jsx(xe,{path:"blame",element:s.jsx(lK,{})}),s.jsx(xe,{path:"bots",element:s.jsx(_K,{})}),s.jsx(xe,{path:"builder",element:s.jsx(vK,{})}),s.jsx(xe,{path:"checklist",element:s.jsx(yK,{})}),s.jsx(xe,{path:"delete",element:s.jsx(xK,{})}),s.jsx(xe,{path:"details",element:s.jsx(SK,{})}),s.jsx(xe,{path:"edit",element:s.jsx(jK,{})}),s.jsx(xe,{path:"editor",element:s.jsx(mK,{})}),s.jsx(xe,{path:"history",element:s.jsx(CK,{})}),s.jsx(xe,{path:"json",element:s.jsx(TK,{})}),s.jsx(xe,{path:"preview",element:s.jsx(PK,{})}),s.jsx(xe,{path:"responses",element:s.jsx(IK,{})}),s.jsx(xe,{path:"report",element:s.jsx(NK,{})}),s.jsx(xe,{path:"ranges",element:s.jsx(AK,{})}),s.jsx(xe,{path:"subscriptions",element:s.jsx(YK,{})}),s.jsx(xe,{path:"timeline",element:s.jsx(tS,{})}),s.jsx(xe,{path:"tools",element:s.jsx(XK,{})}),s.jsx(xe,{path:"profiles",element:s.jsx(kK,{})})]}),s.jsx(xe,{path:"/:resourceType",element:s.jsx(Kw,{})}),s.jsx(xe,{path:"/",element:s.jsx(Kw,{})})]})})}function ZK(){const e=ae(),t=e.getUserConfiguration(),n=Jo(),[r]=e0();return e.isLoading()?s.jsx(qr,{}):s.jsx(qz,{logo:s.jsx(Xr,{size:24}),pathname:n.pathname,searchParams:r,version:FF,menus:eY(t),displayAddBookmark:!!(t!=null&&t.id),children:s.jsx(p.Suspense,{fallback:s.jsx(qr,{}),children:s.jsx(JK,{})})})}function eY(e){var n;const t=((n=e==null?void 0:e.menu)==null?void 0:n.map(r=>{var o;return{title:r.title,links:((o=r.link)==null?void 0:o.map(i=>({label:i.name,href:i.target,icon:tY(i.target)})))||[]}}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:s.jsx($8,{})}]}),t}const nS={Patient:J8,Practitioner:N8,Organization:C8,ServiceRequest:q8,DiagnosticReport:Q8,Questionnaire:A8,admin:w8,AccessPolicy:O8,Subscription:tz,batch:B8,Observation:z8};function tY(e){try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in nS){const n=nS[t];return s.jsx(n,{})}}catch{}return s.jsx(lh,{w:30})}"serviceWorker"in navigator&&window.addEventListener("load",()=>{navigator.serviceWorker.getRegistrations().then(e=>Promise.all(e.map(t=>t.unregister()))).catch(e=>console.error("SW registration failed: ",e))});async function nY(){const e=hu(),t=new ek({baseUrl:e.baseUrl,clientId:e.clientId,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=iG([{path:"*",element:s.jsx(ZK,{})}]),o=a=>r.navigate(a);DR(document.getElementById("root")).render(s.jsx(p.StrictMode,{children:s.jsx(i8,{medplum:t,navigate:o,children:s.jsxs(FS,{theme:n,children:[s.jsx(Ko,{position:"bottom-right"}),s.jsx(pG,{router:r})]})})}))}nY().catch(console.error);
563
- //# sourceMappingURL=index-Bp8s7x5Q.js.map
563
+ //# sourceMappingURL=index-Sp7REiKx.js.map