@medplum/app 3.2.14 → 3.2.16
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.
|
@@ -98,7 +98,7 @@ Error generating stack: `+i.message+`
|
|
|
98
98
|
*
|
|
99
99
|
* Copy of "partysocket" from Partykit team, a fork of the original "Reconnecting WebSocket"
|
|
100
100
|
* https://github.com/partykit/partykit/blob/main/packages/partysocket
|
|
101
|
-
*/const Wa={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let yw=!1;function j8(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");Wa.Event=globalThis.Event,Wa.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},Wa.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function C8(e,t){if(!e)throw new Error(t)}function ud(e){return new e.constructor(e.type,e)}const rs={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1};let xw=!1;class xi extends Uh{constructor(t,n,r={}){yw||(j8(),yw=!0),super(),this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this._debugLogger=console.log.bind(console),this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=o=>{this._debug("open event");const{minUptime:i=rs.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),i),C8(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(a=>{var l;return(l=this._ws)==null?void 0:l.send(a)}),this._messageQueue=[],this.onopen&&this.onopen(o),this.dispatchEvent(ud(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(ud(o))},this._handleError=o=>{this._debug("error event",o.message),this._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(o),this._debug("exec error listeners"),this.dispatchEvent(ud(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(ud(o))},this._url=t,this._protocols=n,this._options=r,this._options.startClosed&&(this._shouldReconnect=!1),this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return xi.CONNECTING}get OPEN(){return xi.OPEN}get CLOSING(){return xi.CLOSING}get CLOSED(){return xi.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){var n;return this._messageQueue.reduce((r,o)=>(typeof o=="string"?r+=o.length:o instanceof Blob?r+=o.size:r+=o.byteLength,r),0)+(((n=this._ws)==null?void 0:n.bufferedAmount)??0)}get extensions(){var t;return((t=this._ws)==null?void 0:t.extensions)??""}get protocol(){var t;return((t=this._ws)==null?void 0:t.protocol)??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?xi.CLOSED:xi.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}close(t=1e3,n){if(this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(t,n)}reconnect(t,n){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(t,n),this._connect())}send(t){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",t),this._ws.send(t);else{const{maxEnqueuedMessages:n=rs.maxEnqueuedMessages}=this._options;this._messageQueue.length<n&&(this._debug("enqueue",t),this._messageQueue.push(t))}}_debug(...t){this._options.debug&&this._debugLogger("RWS>",...t)}_getNextDelay(){const{reconnectionDelayGrowFactor:t=rs.reconnectionDelayGrowFactor,minReconnectionDelay:n=rs.minReconnectionDelay,maxReconnectionDelay:r=rs.maxReconnectionDelay}=this._options;let o=0;return this._retryCount>0&&(o=n*Math.pow(t,this._retryCount-1),o>r&&(o=r)),this._debug("next delay",o),o}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=rs.maxRetries,connectionTimeout:n=rs.connectionTimeout}=this._options;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);return}this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),this._wait().then(()=>{if(this._closeCalled){this._connectLock=!1;return}!this._options.WebSocket&&typeof WebSocket>"u"&&!xw&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),xw=!0);const r=this._options.WebSocket||WebSocket;this._debug("connect",{url:this._url,protocols:this._protocols}),this._ws=this._protocols?new r(this._url,this._protocols):new r(this._url),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),n)}).catch(r=>{this._connectLock=!1,this._handleError(new Wa.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Wa.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new Wa.CloseEvent(t,n,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_removeListeners(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}}const E8=5e3;class Dg extends Uh{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 T8{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new Dg(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class P8{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof _k))throw new Be(_t("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new Be(_t("Not a valid URL"))}const i=r!=null&&r.ReconnectingWebSocket?new r.ReconnectingWebSocket(o,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger}):new xi(o,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger});this.medplum=t,this.ws=i,this.masterSubEmitter=new Dg,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??E8,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,o,i,a,l,c;try{const u=JSON.parse(n.data);if(u.type==="pong"){this.waitingForPong=!1;return}const d=u,f=(o=(r=d==null?void 0:d.entry)==null?void 0:r[0])==null?void 0:o.resource;if(f.type==="heartbeat"){(i=this.masterSubEmitter)==null||i.dispatchEvent({type:"heartbeat",payload:d});return}if(f.type==="handshake"){const m=il(f.subscription),g={type:"connect",payload:{subscriptionId:m}};(a=this.masterSubEmitter)==null||a.dispatchEvent(g);const v=this.criteriaEntriesBySubscriptionId.get(m);if(!v){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}v.connecting=!1,v.emitter.dispatchEvent({...g});return}(l=this.masterSubEmitter)==null||l.dispatchEvent({type:"message",payload:d});const h=this.criteriaEntriesBySubscriptionId.get(il(f.subscription));if(!h){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}h.emitter.dispatchEvent({type:"message",payload:d})}catch(u){console.error(u);const d={type:"error",payload:u};(c=this.masterSubEmitter)==null||c.dispatchEvent(d);for(const f of this.getAllCriteriaEmitters())f.dispatchEvent({...d})}}),t.addEventListener("error",()=>{var r;const n={type:"error",payload:new Be(Y$(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,o;const n={type:"close"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const i of this.getAllCriteriaEmitters())i.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),(o=this.masterSubEmitter)==null||o.removeAllListeners())}),t.addEventListener("open",()=>{var r;const n={type:"open"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const o of this.getAllCriteriaEmitters())o.dispatchEvent({...n});this.refreshAllSubscriptions().catch(console.error),this.pingTimer||(this.pingTimer=setInterval(()=>{if(this.waitingForPong){this.waitingForPong=!1,t.reconnect();return}t.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0},this.pingIntervalMs))}),this.medplum.addEventListener("change",()=>{var r;const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&((r=this.currentProfile)==null?void 0:r.id)!==n.id&&this.ws.reconnect(),this.currentProfile=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 ${rt(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 Be(_t("Failed to get token"));if(!i)throw new Be(_t("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(Ui(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!Ui(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.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:i}}))}async subscribeToCriteria(t){if(!(this.ws.readyState!==WebSocket.OPEN||t.connecting)){t.connecting=!0;try{const[n,r]=await this.getTokenForCriteria(t);t.subscriptionId=n,t.token=r,this.criteriaEntriesBySubscriptionId.set(n,t),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:r}}))}catch(n){console.error(Ae(n)),this.emitError(t,n),this.removeCriteriaEntry(t)}}}async refreshAllSubscriptions(){this.criteriaEntriesBySubscriptionId.clear();for(const t of this.criteriaEntries.values())for(const n of[...t.bareCriteria?[t.bareCriteria]:[],...t.criteriaWithProps])n.clearAttachedSubscription(),await this.subscribeToCriteria(n)}addCriteria(t,n){this.masterSubEmitter&&this.masterSubEmitter._addCriteria(t);const r=this.maybeGetCriteriaEntry(t,n);if(r)return r.refCount+=1,r.emitter;const o=new T8(t,n);return this.addCriteriaEntry(o),this.subscribeToCriteria(o).catch(console.error),o.emitter}removeCriteria(t,n){const r=this.maybeGetCriteriaEntry(t,n);if(!r){console.warn("Criteria not known to `SubscriptionManager`. Possibly called remove too many times.");return}r.refCount-=1,!(r.refCount>0)&&(this.maybeEmitDisconnect(r),this.removeCriteriaEntry(r))}getWebSocket(){return this.ws}closeWebSocket(){this.wsClosed||(this.wsClosed=!0,this.ws.close())}reconnectWebSocket(){this.ws.reconnect(),this.wsClosed=!1}getCriteriaCount(){return this.getAllCriteriaEmitters().length}getMasterEmitter(){return this.masterSubEmitter||(this.masterSubEmitter=new Dg(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const k8="3.2.14-2f87100e5",R8=rn.FHIR_JSON+", */*; q=0.1",_8="https://api.medplum.com/",D8=1e3,I8=6e4,A8=0,N8=3e5,M8="Binary/",bw={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]};class _k extends Uh{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)??O8(),this.storage=(t==null?void 0:t.storage)??new w8,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=uk((t==null?void 0:t.baseUrl)??_8),this.fhirBaseUrl=Po(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=Po(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=Po(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=Po(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.refreshGracePeriod=(t==null?void 0:t.refreshGracePeriod)??N8,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?A8:I8),this.cacheTime>0?this.requestCache=new Pk((t==null?void 0:t.resourceCacheSize)??D8):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.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t!=null&&t.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}async attemptResumeActiveLogin(){const t=this.getActiveLogin();t&&(this.setAccessToken(t.accessToken,t.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}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=Po(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 Or(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,rn.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(Po(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=_6(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 Or((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 Or(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 Or(this.search(t,n,r).then(jw));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 jw(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 bw;const[r,o]=n.split("/");if(!(!r||!o))return this.getCached(r,o)}readResource(t,n,r){if(!n)throw new Error('The "id" parameter cannot be null, undefined, or an empty string.');return this.get(this.fhirUrl(t,n),r)}readReference(t,n){const r=t.reference;if(!r)return new Or(Promise.reject(new Error("Missing reference")));if(r==="system")return new Or(Promise.resolve(bw));const[o,i]=r.split("/");return!o||!i?new Or(Promise.reject(new Error("Invalid reference"))):this.readResource(o,i,n)}requestSchema(t){if(ZP(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Or((async()=>{const i=`{
|
|
101
|
+
*/const Wa={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let yw=!1;function j8(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");Wa.Event=globalThis.Event,Wa.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},Wa.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function C8(e,t){if(!e)throw new Error(t)}function ud(e){return new e.constructor(e.type,e)}const rs={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1};let xw=!1;class xi extends Uh{constructor(t,n,r={}){yw||(j8(),yw=!0),super(),this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this._debugLogger=console.log.bind(console),this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=o=>{this._debug("open event");const{minUptime:i=rs.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),i),C8(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(a=>{var l;return(l=this._ws)==null?void 0:l.send(a)}),this._messageQueue=[],this.onopen&&this.onopen(o),this.dispatchEvent(ud(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(ud(o))},this._handleError=o=>{this._debug("error event",o.message),this._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(o),this._debug("exec error listeners"),this.dispatchEvent(ud(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(ud(o))},this._url=t,this._protocols=n,this._options=r,this._options.startClosed&&(this._shouldReconnect=!1),this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return xi.CONNECTING}get OPEN(){return xi.OPEN}get CLOSING(){return xi.CLOSING}get CLOSED(){return xi.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){var n;return this._messageQueue.reduce((r,o)=>(typeof o=="string"?r+=o.length:o instanceof Blob?r+=o.size:r+=o.byteLength,r),0)+(((n=this._ws)==null?void 0:n.bufferedAmount)??0)}get extensions(){var t;return((t=this._ws)==null?void 0:t.extensions)??""}get protocol(){var t;return((t=this._ws)==null?void 0:t.protocol)??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?xi.CLOSED:xi.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}close(t=1e3,n){if(this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(t,n)}reconnect(t,n){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(t,n),this._connect())}send(t){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",t),this._ws.send(t);else{const{maxEnqueuedMessages:n=rs.maxEnqueuedMessages}=this._options;this._messageQueue.length<n&&(this._debug("enqueue",t),this._messageQueue.push(t))}}_debug(...t){this._options.debug&&this._debugLogger("RWS>",...t)}_getNextDelay(){const{reconnectionDelayGrowFactor:t=rs.reconnectionDelayGrowFactor,minReconnectionDelay:n=rs.minReconnectionDelay,maxReconnectionDelay:r=rs.maxReconnectionDelay}=this._options;let o=0;return this._retryCount>0&&(o=n*Math.pow(t,this._retryCount-1),o>r&&(o=r)),this._debug("next delay",o),o}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=rs.maxRetries,connectionTimeout:n=rs.connectionTimeout}=this._options;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);return}this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),this._wait().then(()=>{if(this._closeCalled){this._connectLock=!1;return}!this._options.WebSocket&&typeof WebSocket>"u"&&!xw&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),xw=!0);const r=this._options.WebSocket||WebSocket;this._debug("connect",{url:this._url,protocols:this._protocols}),this._ws=this._protocols?new r(this._url,this._protocols):new r(this._url),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),n)}).catch(r=>{this._connectLock=!1,this._handleError(new Wa.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Wa.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new Wa.CloseEvent(t,n,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_removeListeners(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}}const E8=5e3;class Dg extends Uh{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 T8{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new Dg(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class P8{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof _k))throw new Be(_t("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new Be(_t("Not a valid URL"))}const i=r!=null&&r.ReconnectingWebSocket?new r.ReconnectingWebSocket(o,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger}):new xi(o,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger});this.medplum=t,this.ws=i,this.masterSubEmitter=new Dg,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??E8,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,o,i,a,l,c;try{const u=JSON.parse(n.data);if(u.type==="pong"){this.waitingForPong=!1;return}const d=u,f=(o=(r=d==null?void 0:d.entry)==null?void 0:r[0])==null?void 0:o.resource;if(f.type==="heartbeat"){(i=this.masterSubEmitter)==null||i.dispatchEvent({type:"heartbeat",payload:d});return}if(f.type==="handshake"){const m=il(f.subscription),g={type:"connect",payload:{subscriptionId:m}};(a=this.masterSubEmitter)==null||a.dispatchEvent(g);const v=this.criteriaEntriesBySubscriptionId.get(m);if(!v){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}v.connecting=!1,v.emitter.dispatchEvent({...g});return}(l=this.masterSubEmitter)==null||l.dispatchEvent({type:"message",payload:d});const h=this.criteriaEntriesBySubscriptionId.get(il(f.subscription));if(!h){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}h.emitter.dispatchEvent({type:"message",payload:d})}catch(u){console.error(u);const d={type:"error",payload:u};(c=this.masterSubEmitter)==null||c.dispatchEvent(d);for(const f of this.getAllCriteriaEmitters())f.dispatchEvent({...d})}}),t.addEventListener("error",()=>{var r;const n={type:"error",payload:new Be(Y$(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,o;const n={type:"close"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const i of this.getAllCriteriaEmitters())i.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),(o=this.masterSubEmitter)==null||o.removeAllListeners())}),t.addEventListener("open",()=>{var r;const n={type:"open"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const o of this.getAllCriteriaEmitters())o.dispatchEvent({...n});this.refreshAllSubscriptions().catch(console.error),this.pingTimer||(this.pingTimer=setInterval(()=>{if(this.waitingForPong){this.waitingForPong=!1,t.reconnect();return}t.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0},this.pingIntervalMs))}),this.medplum.addEventListener("change",()=>{var r;const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&((r=this.currentProfile)==null?void 0:r.id)!==n.id&&this.ws.reconnect(),this.currentProfile=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 ${rt(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 Be(_t("Failed to get token"));if(!i)throw new Be(_t("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(Ui(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!Ui(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.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:i}}))}async subscribeToCriteria(t){if(!(this.ws.readyState!==WebSocket.OPEN||t.connecting)){t.connecting=!0;try{const[n,r]=await this.getTokenForCriteria(t);t.subscriptionId=n,t.token=r,this.criteriaEntriesBySubscriptionId.set(n,t),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:r}}))}catch(n){console.error(Ae(n)),this.emitError(t,n),this.removeCriteriaEntry(t)}}}async refreshAllSubscriptions(){this.criteriaEntriesBySubscriptionId.clear();for(const t of this.criteriaEntries.values())for(const n of[...t.bareCriteria?[t.bareCriteria]:[],...t.criteriaWithProps])n.clearAttachedSubscription(),await this.subscribeToCriteria(n)}addCriteria(t,n){this.masterSubEmitter&&this.masterSubEmitter._addCriteria(t);const r=this.maybeGetCriteriaEntry(t,n);if(r)return r.refCount+=1,r.emitter;const o=new T8(t,n);return this.addCriteriaEntry(o),this.subscribeToCriteria(o).catch(console.error),o.emitter}removeCriteria(t,n){const r=this.maybeGetCriteriaEntry(t,n);if(!r){console.warn("Criteria not known to `SubscriptionManager`. Possibly called remove too many times.");return}r.refCount-=1,!(r.refCount>0)&&(this.maybeEmitDisconnect(r),this.removeCriteriaEntry(r))}getWebSocket(){return this.ws}closeWebSocket(){this.wsClosed||(this.wsClosed=!0,this.ws.close())}reconnectWebSocket(){this.ws.reconnect(),this.wsClosed=!1}getCriteriaCount(){return this.getAllCriteriaEmitters().length}getMasterEmitter(){return this.masterSubEmitter||(this.masterSubEmitter=new Dg(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const k8="3.2.16-a2ededb30",R8=rn.FHIR_JSON+", */*; q=0.1",_8="https://api.medplum.com/",D8=1e3,I8=6e4,A8=0,N8=3e5,M8="Binary/",bw={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]};class _k extends Uh{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)??O8(),this.storage=(t==null?void 0:t.storage)??new w8,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=uk((t==null?void 0:t.baseUrl)??_8),this.fhirBaseUrl=Po(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=Po(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=Po(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=Po(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.refreshGracePeriod=(t==null?void 0:t.refreshGracePeriod)??N8,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?A8:I8),this.cacheTime>0?this.requestCache=new Pk((t==null?void 0:t.resourceCacheSize)??D8):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.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t!=null&&t.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}async attemptResumeActiveLogin(){const t=this.getActiveLogin();t&&(this.setAccessToken(t.accessToken,t.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}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=Po(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 Or(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,rn.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(Po(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=_6(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 Or((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 Or(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 Or(this.search(t,n,r).then(jw));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 jw(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 bw;const[r,o]=n.split("/");if(!(!r||!o))return this.getCached(r,o)}readResource(t,n,r){if(!n)throw new Error('The "id" parameter cannot be null, undefined, or an empty string.');return this.get(this.fhirUrl(t,n),r)}readReference(t,n){const r=t.reference;if(!r)return new Or(Promise.reject(new Error("Missing reference")));if(r==="system")return new Or(Promise.resolve(bw));const[o,i]=r.split("/");return!o||!i?new Or(Promise.reject(new Error("Invalid reference"))):this.readResource(o,i,n)}requestSchema(t){if(ZP(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Or((async()=>{const i=`{
|
|
102
102
|
StructureDefinitionList(name: "${t}") {
|
|
103
103
|
resourceType,
|
|
104
104
|
name,
|
|
@@ -138,7 +138,7 @@ Error generating stack: `+i.message+`
|
|
|
138
138
|
expression,
|
|
139
139
|
target
|
|
140
140
|
}
|
|
141
|
-
}`.replace(/\s+/g," "),a=await this.graphql(i);nw(a.data.StructureDefinitionList);for(const l of a.data.SearchParameterList)U6(l)})());return this.setCacheEntry(n,o),o}requestProfileSchema(t,n){if(!(n!=null&&n.expandProfile)&&Ix(t))return Promise.resolve();const r=t+"-requestSchema"+(n!=null&&n.expandProfile?"-nested":""),o=this.getCacheEntry(r,void 0);if(o)return o.value;const i=new Or((async()=>{if(n!=null&&n.expandProfile){const a=this.fhirUrl("StructureDefinition","$expand-profile");a.search=new URLSearchParams({url:t}).toString();const l=await this.post(a.toString(),{});nw(l)}else{const a=await this.searchOne("StructureDefinition",{url:t,_sort:"-_lastUpdated"});if(!a){console.warn(`No StructureDefinition found for ${t}!`);return}JP(a)}})());return this.setCacheEntry(r,i),i}readHistory(t,n,r){return this.get(this.fhirUrl(t,n,"_history"),r)}readVersion(t,n,r,o){return this.get(this.fhirUrl(t,n,"_history",r),o)}readPatientEverything(t,n){return this.get(this.fhirUrl("Patient",t,"$everything"),n)}createResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");return this.invalidateSearches(t.resourceType),this.post(this.fhirUrl(t.resourceType),t,void 0,n)}async createResourceIfNoneExist(t,n,r){return await this.searchOne(t.resourceType,n,r)??this.createResource(t,r)}async upsertResource(t,n,r){const o=this.fhirSearchUrl(t.resourceType,n);let i=await this.put(o,t,void 0,r);return i||(i=t),this.cacheResource(i),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),i}async createAttachment(t,n,r,o,i){const a=Cw(t,n,r,o),l=i??(typeof n=="object"?n:{}),c=await this.createBinary(a,l);return{contentType:a.contentType,url:c.url,title:a.filename}}createBinary(t,n,r,o,i){const a=Cw(t,n,r,o),l=i??(typeof n=="object"?n:{}),{data:c,contentType:u,filename:d,securityContext:f,onProgress:h}=a,m=this.fhirUrl("Binary");return d&&m.searchParams.set("_filename",d),f!=null&&f.reference&&this.setRequestHeader(l,"X-Security-Context",f.reference),h?this.uploadwithProgress(m,c,u,h,l):this.post(m,c,u,l)}uploadwithProgress(t,n,r,o,i){return new Promise((a,l)=>{var f;const c=new XMLHttpRequest,u=()=>c.abort();(f=i==null?void 0:i.signal)==null||f.addEventListener("abort",u);const d=h=>{var m;(m=i==null?void 0:i.signal)==null||m.removeEventListener("abort",u),h instanceof Error?l(h):a(h)};if(c.responseType="json",c.onabort=()=>d(new DOMException("Request aborted","AbortError")),c.onerror=()=>d(new Error("Request error")),o&&(c.upload.onprogress=h=>o(h),c.upload.onload=h=>o(h)),c.onload=()=>{c.status>=200&&c.status<300?d(c.response):d(new Be(ft(c.response||c.statusText)))},c.open("POST",t),c.withCredentials=!0,c.setRequestHeader("Authorization","Bearer "+this.accessToken),c.setRequestHeader("Cache-Control","no-cache, no-store, max-age=0"),c.setRequestHeader("Content-Type",r),c.setRequestHeader("X-Medplum","extended"),i!=null&&i.headers){const h=i.headers;for(const[m,g]of Object.entries(h))c.setRequestHeader(m,g)}c.send(n)})}async createPdf(t,n,r,o){if(!this.createPdfImpl)throw new Error("PDF creation not enabled");const i=F8(t,n,r,o),a=typeof n=="object"?n:{},{docDefinition:l,tableLayouts:c,fonts:u,...d}=i,f=await this.createPdfImpl(l,c,u),h={...d,data:f,contentType:"application/pdf"};return this.createBinary(h,a)}createComment(t,n,r){const o=this.getProfile();let i,a;return t.resourceType==="Encounter"&&(i=Tt(t),a=t.subject),t.resourceType==="ServiceRequest"&&(i=t.encounter,a=t.subject),t.resourceType==="Patient"&&(a=Tt(t)),this.createResource({resourceType:"Communication",status:"completed",basedOn:[Tt(t)],encounter:i,subject:a,sender:o?Tt(o):void 0,sent:new Date().toISOString(),payload:[{contentString:n}]},r)}async updateResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");if(!t.id)throw new Error("Missing id");let r=await this.put(this.fhirUrl(t.resourceType,t.id),t,void 0,n);return r||(r=t),this.cacheResource(r),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),r}async patchResource(t,n,r,o){const i=await this.patch(this.fhirUrl(t,n),r,o);return this.cacheResource(i),this.invalidateUrl(this.fhirUrl(t,n,"_history")),this.invalidateSearches(t),i}deleteResource(t,n,r){return this.deleteCacheEntry(this.fhirUrl(t,n).toString()),this.invalidateSearches(t),this.delete(this.fhirUrl(t,n),r)}validateResource(t,n){return this.post(this.fhirUrl(t.resourceType,"$validate"),t,void 0,n)}executeBot(t,n,r,o){let i;if(typeof t=="string"){const a=t;i=this.fhirUrl("Bot",a,"$execute")}else{const a=t;i=this.fhirUrl("Bot","$execute"),i.searchParams.set("identifier",a.system+"|"+a.value)}return this.post(i,n,r,o)}executeBatch(t,n){return this.post(this.fhirBaseUrl,t,void 0,n)}sendEmail(t,n){return this.post("email/v1/send",t,rn.JSON,n)}graphql(t,n,r,o){return this.post(this.fhirUrl("$graphql"),{query:t,operationName:n,variables:r},rn.JSON,o)}readResourceGraph(t,n,r,o){return this.get(`${this.fhirUrl(t,n)}/$graph?graph=${r}`,o)}pushToAgent(t,n,r,o,i,a){return this.post(this.fhirUrl("Agent",il(t),"$push"),{destination:typeof n=="string"?n:rt(n),body:r,contentType:o,waitForResponse:i},rn.FHIR_JSON,a)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(t){var n,r;(!((n=this.sessionDetails)!=null&&n.profile)||rt(this.sessionDetails.profile)!==((r=t.profile)==null?void 0:r.reference))&&this.clearActiveLogin(),this.setAccessToken(t.accessToken,t.refreshToken),this.storage.setObject("activeLogin",t),this.addLogin(t),this.refreshPromise=void 0,await this.refreshProfile()}getAccessToken(){return this.accessToken}setAccessToken(t,n){this.accessToken=t,this.refreshToken=n,this.accessTokenExpires=x8(t),this.medplumServer=y8(t)}getLogins(){return this.storage.getObject("logins")??[]}addLogin(t){const n=this.getLogins().filter(r=>{var o,i;return((o=r.profile)==null?void 0:o.reference)!==((i=t.profile)==null?void 0:i.reference)});n.push(t),this.storage.setObject("logins",n)}async refreshProfile(){return this.medplumServer?(this.profilePromise=new Promise((t,n)=>{this.get("auth/me",{cache:"no-cache"}).then(r=>{var i,a;this.profilePromise=void 0;const o=((a=(i=this.sessionDetails)==null?void 0:i.profile)==null?void 0:a.id)!==r.profile.id;this.sessionDetails=r,o&&this.dispatchEvent({type:"change"}),t(r.profile),this.dispatchEvent({type:"profileRefreshed"})}).catch(n)}),this.dispatchEvent({type:"profileRefreshing"}),this.profilePromise):Promise.resolve(void 0)}isLoading(){var t;return!this.isInitialized||!!this.profilePromise&&!((t=this.sessionDetails)!=null&&t.profile)}isSuperAdmin(){var t;return!!((t=this.sessionDetails)!=null&&t.project.superAdmin)}isProjectAdmin(){var t;return!!((t=this.sessionDetails)!=null&&t.membership.admin)}getProject(){var t;return(t=this.sessionDetails)==null?void 0:t.project}getProjectMembership(){var t;return(t=this.sessionDetails)==null?void 0:t.membership}getProfile(){var t;return(t=this.sessionDetails)==null?void 0:t.profile}async getProfileAsync(){return this.profilePromise?this.profilePromise:this.sessionDetails?this.sessionDetails.profile:this.refreshProfile()}getUserConfiguration(){var t;return(t=this.sessionDetails)==null?void 0:t.config}getAccessPolicy(){var t;return(t=this.sessionDetails)==null?void 0:t.accessPolicy}async download(t,n={}){this.refreshPromise&&await this.refreshPromise;const r=t.toString();r.startsWith(M8)&&(t=this.fhirUrl(r));let o=n.headers;return o||(o={},n.headers=o),o.Accept||(o.Accept="*/*"),this.addFetchOptionsDefaults(n),(await this.fetchWithRetry(t.toString(),n)).blob()}async createMedia(t,n){const{additionalFields:r,...o}=t,i=await this.createResource({resourceType:"Media",status:"preparation",content:{contentType:t.contentType},...r});o.securityContext||(o.securityContext=Tt(i));const a=await this.createAttachment(o,n);return this.updateResource({...i,status:"completed",content:a})}async uploadMedia(t,n,r,o,i){return this.createMedia({data:t,contentType:n,filename:r,additionalFields:o},i)}async bulkExport(t="",n,r,o){const i=t&&`${t}/`,a=this.fhirUrl(`${i}$export`);return n&&a.searchParams.set("_type",n),r&&a.searchParams.set("_since",r),this.startAsyncRequest(a.toString(),o)}async startAsyncRequest(t,n={}){this.addFetchOptionsDefaults(n);const r=n.headers;return r.Prefer="respond-async",this.request("POST",t,n)}get keyValue(){return this.keyValueClient||(this.keyValueClient=new b8(this)),this.keyValueClient}getCacheEntry(t,n){if(!this.requestCache||(n==null?void 0:n.cache)==="no-cache"||(n==null?void 0:n.cache)==="reload")return;const r=this.requestCache.get(t);if(!(!r||r.requestTime+this.cacheTime<Date.now()))return r}setCacheEntry(t,n){this.requestCache&&this.requestCache.set(t,{requestTime:Date.now(),value:n})}cacheResource(t){var n,r;t!=null&&t.id&&!((r=(n=t.meta)==null?void 0:n.tag)!=null&&r.some(o=>o.code==="SUBSETTED"))&&this.setCacheEntry(this.fhirUrl(t.resourceType,t.id).toString(),new Or(Promise.resolve(t)))}deleteCacheEntry(t){this.requestCache&&this.requestCache.delete(t)}async request(t,n,r={},o={}){await this.refreshIfExpired(),r.method=t,this.addFetchOptionsDefaults(r);const i=await this.fetchWithRetry(n,r);if(i.status===401)return this.handleUnauthenticated(t,n,r);if(i.status===204||i.status===304)return;const a=i.headers.get("content-type"),l=a==null?void 0:a.includes("json");if(i.status===404&&!l)throw new Be(Q$);const c=await this.parseBody(i,l);if(i.status===200&&r.followRedirectOnOk||i.status===201&&r.followRedirectOnCreated){const u=await Sw(i,c);if(u)return this.request("GET",u,{...r,body:void 0})}if(i.status===202&&r.pollStatusOnAccepted){const d=await Sw(i,c)??o.statusUrl;if(d)return this.pollStatus(d,r,o)}if(i.status>=400)throw new Be(ft(c));return c}async parseBody(t,n){let r;if(n)try{r=await t.json()}catch(o){throw console.error("Error parsing response",t.status,o),o}else r=await t.text();return r}async fetchWithRetry(t,n){t.startsWith("http")||(t=Po(this.baseUrl,t));const r=(n==null?void 0:n.maxRetries)??2,o=200;for(let i=0;i<=r;i++){try{this.options.verbose&&this.logRequest(t,n);const a=await this.fetch(t,n);if(this.options.verbose&&this.logResponse(a),a.status<500||i===r)return a}catch(a){if(a.message==="Failed to fetch"&&i===0&&this.dispatchEvent({type:"offline"}),a.name==="AbortError"||i===r)throw a}await uw(o)}throw new Error("Unreachable")}logRequest(t,n){if(console.log(`> ${n.method} ${t}`),n.headers){const r=n.headers;for(const o of Oc(Object.keys(r)))console.log(`> ${o}: ${r[o]}`)}}logResponse(t){console.log(`< ${t.status} ${t.statusText}`),t.headers&&t.headers.forEach((n,r)=>console.log(`< ${r}: ${n}`))}async pollStatus(t,n,r){const o={...n,method:"GET",body:void 0,redirect:"follow"};if(r.pollCount===void 0)n.headers&&typeof n.headers=="object"&&"Prefer"in n.headers&&(o.headers={...n.headers},delete o.headers.Prefer),r.statusUrl=t,r.pollCount=1;else{const i=n.pollStatusPeriod??1e3;await uw(i),r.pollCount++}return this.request("GET",t,o,r)}async executeAutoBatch(){var o,i;const t=[...this.autoBatchQueue];if(this.autoBatchQueue.length=0,this.autoBatchTimerId=void 0,t.length===1){const a=t[0];try{a.resolve(await this.request(a.method,Po(this.fhirBaseUrl,a.url),a.options))}catch(l){a.reject(new Be(ft(l)))}return}const n={resourceType:"Bundle",type:"batch",entry:t.map(a=>({request:{method:a.method,url:a.url},resource:a.options.body?JSON.parse(a.options.body):void 0}))},r=await this.post(this.fhirBaseUrl,n);for(let a=0;a<t.length;a++){const l=t[a],c=(o=r.entry)==null?void 0:o[a];(i=c==null?void 0:c.response)!=null&&i.outcome&&!QP(c.response.outcome)?l.reject(new Be(c.response.outcome)):l.resolve(c==null?void 0:c.resource)}}addFetchOptionsDefaults(t){this.setRequestHeader(t,"X-Medplum","extended"),this.setRequestHeader(t,"Accept",R8,!0),t.body&&this.setRequestHeader(t,"Content-Type",rn.FHIR_JSON,!0),this.accessToken?this.setRequestHeader(t,"Authorization","Bearer "+this.accessToken):this.basicAuth&&this.setRequestHeader(t,"Authorization","Basic "+this.basicAuth),t.cache||(t.cache="no-cache"),t.credentials||(t.credentials="include")}setRequestContentType(t,n){this.setRequestHeader(t,"Content-Type",n)}setRequestHeader(t,n,r,o=!1){t.headers||(t.headers={});const i=t.headers;o&&i[n]||(i[n]=r)}setRequestBody(t,n){typeof n=="string"||typeof Blob<"u"&&(n instanceof Blob||n.constructor.name==="Blob")||typeof File<"u"&&(n instanceof File||n.constructor.name==="File")||typeof Uint8Array<"u"&&(n instanceof Uint8Array||n.constructor.name==="Uint8Array")?t.body=n:n&&(t.body=JSON.stringify(n))}handleUnauthenticated(t,n,r){return this.refresh()?this.request(t,n,r):(this.clear(),this.onUnauthenticated&&this.onUnauthenticated(),Promise.reject(new Be(Nc)))}async startPkce(){const t=pw();sessionStorage.setItem("pkceState",t);const n=pw().slice(0,128);sessionStorage.setItem("codeVerifier",n);const r=await n8(n),o=C6(r).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return sessionStorage.setItem("codeChallenge",o),{codeChallengeMethod:"S256",codeChallenge:o}}async requestAuthorization(t){const n=await this.ensureCodeChallenge(t??{}),r=new URL(this.authorizeUrl);r.searchParams.set("response_type","code"),r.searchParams.set("state",sessionStorage.getItem("pkceState")),r.searchParams.set("client_id",n.clientId??this.clientId),r.searchParams.set("redirect_uri",n.redirectUri??ww()),r.searchParams.set("code_challenge_method",n.codeChallengeMethod),r.searchParams.set("code_challenge",n.codeChallenge),r.searchParams.set("scope",n.scope??"openid profile"),window.location.assign(r.toString())}processCode(t,n){const r=new URLSearchParams;if(r.set("grant_type","authorization_code"),r.set("code",t),r.set("client_id",(n==null?void 0:n.clientId)??this.clientId),r.set("redirect_uri",(n==null?void 0:n.redirectUri)??ww()),typeof sessionStorage<"u"){const o=sessionStorage.getItem("codeVerifier");o&&r.set("code_verifier",o)}return this.fetchTokens(r)}refreshIfExpired(t){return t===void 0&&(t=this.refreshGracePeriod),!this.refreshPromise&&this.accessTokenExpires!==void 0&&Date.now()>this.accessTokenExpires-t&&this.refresh(),this.refreshPromise??Promise.resolve()}refresh(){if(this.refreshPromise)return this.refreshPromise;if(this.refreshToken){const t=new URLSearchParams;return t.set("grant_type","refresh_token"),t.set("client_id",this.clientId),t.set("refresh_token",this.refreshToken),this.refreshPromise=this.fetchTokens(t),this.refreshPromise}if(this.clientId&&this.clientSecret)return this.refreshPromise=this.startClientLogin(this.clientId,this.clientSecret),this.refreshPromise}async startClientLogin(t,n){this.clientId=t,this.clientSecret=n;const r=new URLSearchParams;return r.set("grant_type","client_credentials"),r.set("client_id",t),r.set("client_secret",n),this.fetchTokens(r)}async startJwtBearerLogin(t,n,r){this.clientId=t;const o=new URLSearchParams;return o.set("grant_type","urn:ietf:params:oauth:grant-type:jwt-bearer"),o.set("client_id",t),o.set("assertion",n),o.set("scope",r),this.fetchTokens(o)}async startJwtAssertionLogin(t){const n=new URLSearchParams;return n.append("grant_type","client_credentials"),n.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),n.append("client_assertion",t),this.fetchTokens(n)}setBasicAuth(t,n){this.clientId=t,this.clientSecret=n,this.basicAuth=t8(t+":"+n)}async fhircastSubscribe(t,n){if(!(typeof t=="string"&&t!==""))throw new Be(_t("Invalid topic provided. Topic must be a valid string."));if(!(typeof n=="object"&&Array.isArray(n)&&n.length>0))throw new Be(_t("Invalid events provided. Events must be an array of event names containing at least one event."));const r={channelType:"websocket",mode:"subscribe",topic:t,events:n},i=(await this.post("/fhircast/STU3",mw(r),rn.FORM_URL_ENCODED))["hub.channel.endpoint"];if(!i)throw new Error("Invalid response!");return r.endpoint=i,r}async fhircastUnsubscribe(t){if(!Gx(t))throw new Be(_t("Invalid topic or subscriptionRequest. SubscriptionRequest must be an object."));if(!(t.endpoint&&typeof t.endpoint=="string"&&t.endpoint.startsWith("ws")))throw new Be(_t("Provided subscription request must have an endpoint in order to unsubscribe."));t.mode="unsubscribe",await this.post("/fhircast/STU3",mw(t),rn.FORM_URL_ENCODED)}fhircastConnect(t){return new m8(t)}async fhircastPublish(t,n,r,o){return c8(n)?this.post(`/fhircast/STU3/${t}`,vw(t,n,r,o),rn.JSON):(u8(n),this.post(`/fhircast/STU3/${t}`,vw(t,n,r),rn.JSON))}async fhircastGetContext(t){return this.get(`/fhircast/STU3/${t}`)}async invite(t,n){return this.post("admin/projects/"+t+"/invite",n)}async fetchTokens(t){const n={method:"POST",headers:{"Content-Type":rn.FORM_URL_ENCODED},body:t.toString(),credentials:"include"},r=n.headers;this.basicAuth&&(r.Authorization=`Basic ${this.basicAuth}`);let o;try{o=await this.fetchWithRetry(this.tokenUrl,n)}catch(a){throw this.refreshPromise=void 0,a}if(!o.ok){this.clearActiveLogin();try{const a=await o.json();throw new Be(Oi(a.error_description))}catch(a){throw new Be(Oi("Failed to fetch tokens"),a)}}const i=await o.json();return await this.verifyTokens(i),this.getProfile()}async verifyTokens(t){const n=t.access_token;if(v8(n)){const r=Qx(n);if(Date.now()>=r.exp*1e3)throw this.clearActiveLogin(),new Be(K$);if(r.cid){if(r.cid!==this.clientId)throw this.clearActiveLogin(),new Be(ew)}else if(this.clientId&&r.client_id!==this.clientId)throw this.clearActiveLogin(),new Be(ew)}return this.setActiveLogin({accessToken:n,refreshToken:t.refresh_token,project:t.project,profile:t.profile})}setupStorageListener(){try{window.addEventListener("storage",t=>{if(t.key===null)window.location.reload();else if(t.key==="activeLogin"){const n=t.oldValue?JSON.parse(t.oldValue):void 0,r=t.newValue?JSON.parse(t.newValue):void 0;(n==null?void 0:n.profile.reference)!==(r==null?void 0:r.profile.reference)&&window.location.reload()}})}catch{}}getSubscriptionManager(){return this.subscriptionManager||(this.subscriptionManager=new P8(this,R6(this.baseUrl,"/ws/subscriptions-r4"))),this.subscriptionManager}subscribeToCriteria(t,n){return this.getSubscriptionManager().addCriteria(t,n)}unsubscribeFromCriteria(t,n){this.subscriptionManager&&(this.subscriptionManager.removeCriteria(t,n),this.subscriptionManager.getCriteriaCount()===0&&this.subscriptionManager.closeWebSocket())}getMasterSubscriptionEmitter(){return this.getSubscriptionManager().getMasterEmitter()}}function O8(){if(!globalThis.fetch)throw new Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}function ww(){return typeof window>"u"?"":window.location.protocol+"//"+window.location.host+"/"}async function Sw(e,t){var o,i;const n=e.headers.get("content-location");if(n)return n;const r=e.headers.get("location");if(r)return r;if(Lh(t)&&((i=(o=t.issue)==null?void 0:o[0])!=null&&i.diagnostics))return t.issue[0].diagnostics}function jw(e){var n;const t=((n=e.entry)==null?void 0:n.map(r=>r.resource))??[];return Object.assign(t,{bundle:e})}function L8(e){return Rn(e)&&"data"in e&&"contentType"in e}function Cw(e,t,n,r){return L8(e)?e:{data:e,filename:t,contentType:n,onProgress:r}}function $8(e){return Rn(e)&&"docDefinition"in e}function F8(e,t,n,r){return $8(e)?e:{docDefinition:e,filename:t,tableLayouts:n,fonts:r}}function sl({parentContext:e,path:t,elements:n,profileUrl:r,debugMode:o,accessPolicyResource:i}){if(t===(e==null?void 0:e.path))return;o??(o=(e==null?void 0:e.debugMode)??!1),i??(i=e==null?void 0:e.accessPolicyResource);let a=z8(t,n,e,!!o);const l=Pg(t,".",2)[1];a=B8(a,i,l),a=U8(a,i,l);const c=Object.create(null);for(const[d,f]of Object.entries(a))c[t+"."+d]=f;let u;if(e&&!e.isDefaultContext)u=e.getExtendedProps;else{const d=Object.create(null);u=f=>{const h=Pg(f,".",2)[1];if(h){if(!d[h]){const m=wf(h,i==null?void 0:i.hiddenFields);d[h]={hidden:m,readonly:m||wf(h,i==null?void 0:i.readonlyFields)}}return d[h]}}}return{path:t,elements:a,elementsByPath:c,profileUrl:r??(e==null?void 0:e.profileUrl),debugMode:o,getExtendedProps:u,accessPolicyResource:i}}function z8(e,t,n,r){const o=Object.create(null);if(n)for(const[a,l]of Object.entries(n.elementsByPath)){const c=Mc(e,a);c!==void 0&&(o[c]=l)}let i=!1;if(t)for(const[a,l]of Object.entries(t))a in o||(o[a]=l,i=!0);return r&&console.assert(i,"Unnecessary ElementsContext; not using any newly provided elements"),o}function B8(e,t,n){var o;if(!((o=t==null?void 0:t.hiddenFields)!=null&&o.length))return e;const r=n?n+".":"";return Object.fromEntries(Object.entries(e).filter(([i])=>!wf(r+i,t.hiddenFields)))}function U8(e,t,n){var i;if(!((i=t==null?void 0:t.readonlyFields)!=null&&i.length))return e;const r=Object.create(null),o=n?n+".":"";for(const[a,l]of Object.entries(e))wf(o+a,t.readonlyFields)?r[a]={...l,readonly:!0}:r[a]=l;return r}function wf(e,t){if(!(t!=null&&t.length))return!1;const n=e.split(".");for(let r=1;r<=n.length;r++){const o=n.slice(0,r).join(".");if(t.includes(o))return!0}return!1}function Dk(e){return e.type!==void 0&&e.type.length>0}function V8(e,t,n,r){var i;const o=X7(e,t.path,{profileUrl:r});if(o){const a=((i=n.typeSchema)==null?void 0:i.elements)??n.elements;return o.some(l=>e6(l,t,n,a))??!1}return console.assert(!1,"getNestedProperty[%s] in isDiscriminatorComponentMatch missed",t.path),!1}function Ik(e,t,n,r){var o,i;if(e)for(const a of t){const l={value:e,type:((o=a.typeSchema)==null?void 0:o.type)??((i=a.type)==null?void 0:i[0].code)};if(n.every(c=>{var u;return V8(l,c,a,((u=a.typeSchema)==null?void 0:u.url)??r)}))return a.name}}class W8{constructor(t,n,r){if(t.type===void 0)throw new Error("schema must include a type");this.rootSchema=t;const o=sl({parentContext:void 0,path:this.rootSchema.type,elements:r??this.rootSchema.elements,profileUrl:this.rootSchema.name===this.rootSchema.type?void 0:this.rootSchema.url});if(o===void 0)throw new Error("Could not create root elements context");this.elementsContextStack=[o],this.visitor=n}get elementsContext(){return this.elementsContextStack[this.elementsContextStack.length-1]}crawlElement(t,n,r){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema);const o=Object.fromEntries(Object.entries(this.elementsContext.elements).filter(([i])=>i.startsWith(n)));this.crawlElementsImpl(o,r),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlSlice(t,n,r){const o=this.prepareSlices(r.slices,r);if(!$t(o.slices))throw new Error(`cannot crawl slice ${n.name} since it has no type information`);this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.sliceAllowList=[n],this.crawlSliceImpl(o.slices[0],n.path,o),this.sliceAllowList=void 0,this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlResource(){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.crawlElementsImpl(this.rootSchema.elements,this.rootSchema.type),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlElementsImpl(t,n){const r=H8(t);for(const o of r)this.crawlElementNode(o,n)}crawlElementNode(t,n){var o,i;const r=n+"."+t.key;this.visitor.onEnterElement&&this.visitor.onEnterElement(r,t.element,this.elementsContext);for(const a of t.children)this.crawlElementNode(a,n);$t((i=(o=t.element)==null?void 0:o.slicing)==null?void 0:i.slices)&&this.crawlSlicingImpl(t.element.slicing,r),this.visitor.onExitElement&&this.visitor.onExitElement(r,t.element,this.elementsContext)}prepareSlices(t,n){var i,a;const r=[];for(const l of t){if(!Dk(l))continue;const c=(a=(i=l.type.find(u=>$t(u.profile)))==null?void 0:i.profile)==null?void 0:a[0];if($t(c)){const u=wl(c);u&&(l.typeSchema=u)}r.push(l)}return{...n,slices:r}}crawlSlicingImpl(t,n){const r=this.prepareSlices(t.slices,t);for(const o of r.slices)(this.sliceAllowList===void 0||this.sliceAllowList.includes(o))&&this.crawlSliceImpl(o,n,r)}crawlSliceImpl(t,n,r){const o=t.typeSchema;o&&this.visitor.onEnterSchema&&this.visitor.onEnterSchema(o),this.visitor.onEnterSlice&&this.visitor.onEnterSlice(n,t,r);let i;const a=(o==null?void 0:o.elements)??t.elements;$t(a)&&(i=sl({path:n,parentContext:this.elementsContext,elements:a})),i&&this.elementsContextStack.push(i),this.crawlElementsImpl(a,n),i&&this.elementsContextStack.pop(),this.visitor.onExitSlice&&this.visitor.onExitSlice(n,t,r),o&&this.visitor.onExitSchema&&this.visitor.onExitSchema(o)}}function H8(e){const t=[];function n(i,a){return a.startsWith(i+".")}function r(i,a){for(const l of i.children)if(n(l.key,a.key)){r(l,a);return}i.children.push(a)}const o=Object.entries(e);o.sort((i,a)=>i[0].localeCompare(a[0]));for(const[i,a]of o){const l={key:i,element:a,children:[]};let c=!1;for(const u of t)if(n(u.key,i)){r(u,l),c=!0;break}c||t.push(l)}return t}const em="__sliceName";function q8(e,t){const n=new G8(e,e.resourceType,"resource");return new W8(t,n).crawlResource(),n.getDefaultValue()}function Ew(e,t,n){for(const[r,o]of Object.entries(t)){if(n===void 0||n===r){Sf(e,r,o,t);continue}const i=Mc(n,r);i!==void 0&&Sf(e,i,o,t)}return e}class G8{constructor(t,n,r){this.schemaStack=[],this.valueStack=[],this.rootValue=Kr(t),this.valueStack.splice(0,this.valueStack.length,{type:r,path:n,values:[this.rootValue]})}get schema(){return this.schemaStack[this.schemaStack.length-1]}get value(){return this.valueStack[this.valueStack.length-1]}onEnterSchema(t){this.schemaStack.push(t)}onExitSchema(){this.schemaStack.pop()}onEnterElement(t,n,r){const o=this.value.values,i=this.value.path,a=Mc(i,t);if(a===void 0)throw new Error(`Expected ${t} to be prefixed by ${i}`);const l=[];for(const c of o){if(c===void 0)continue;const u=Array.isArray(c)?c:[c];for(const d of u){Q8(d,a,n,r.elements),Sf(d,a,n,r.elements);const f=Ag(d,a,n,r.elements);f!==void 0&&l.push(f)}}this.valueStack.push({type:"element",path:t,values:l})}onExitElement(t,n,r){if(!this.valueStack.pop())throw new Error("Expected value context to exist when exiting element");const i=Mc(this.value.path,t);if(i===void 0)throw new Error(`Expected ${t} to be prefixed by ${this.value.path}`);for(const a of this.value.values){const l=Ag(a,i,n,r.elements);if(Array.isArray(l))for(let c=l.length-1;c>=0;c--){const u=l[c];$t(u)||l.splice(c,1)}qt(l)&&Ig(a,void 0,i,n)}}onEnterSlice(t,n,r){const o=this.value.values,i=[];for(const a of o){if(a===void 0)continue;if(!Array.isArray(a))throw new Error("Expected array value for sliced element");const l=this.getMatchingSliceValues(a,n,r);i.push(l)}this.valueStack.push({type:"slice",path:t,values:i})}getMatchingSliceValues(t,n,r){const o=[];for(const i of t)(i[em]??Ik(i,[n],r.discriminator,this.schema.url))===n.name&&o.push(i);for(let i=o.length;i<n.min;i++)if(Ox(n.type[0].code)){const a=Object.create(null);o.push(a),t.push(a)}return o}onExitSlice(){const t=this.valueStack.pop();if(!t)throw new Error("Expected value context to exist in onExitSlice");for(const n of t.values)for(let r=n.length-1;r>=0;r--){const o=n[r];em in o&&delete o[em]}}getDefaultValue(){return this.rootValue}}function Q8(e,t,n,r){const o=Ag(e,t,n,r);n.min>0&&o===void 0&&Ox(n.type[0].code)&&(n.isArray?Ig(e,[Object.create(null)],t,n):Ig(e,Object.create(null),t,n))}function Ig(e,t,n,r){if(n.includes("."))throw new Error("key cannot be nested");let o=n;if(n.includes("[x]")){const i=r.type[0].code;o=n.replace("[x]",tn(i))}t===void 0?delete e[o]:e[o]=t}function Ag(e,t,n,r){const o=t.split(".");let i=e,a;for(let l=0;l<o.length;l++){let c=o[l];if(c.includes("[x]")){const d=r[o.slice(0,l+1).join(".")].type[0].code;c=c.replace("[x]",tn(d))}if(l===o.length-1){Array.isArray(i)?a=i.map(u=>u[c]):a=i[c];continue}if(Array.isArray(i))i=i.map(u=>u[c]);else if(Rn(i)){if(i[c]===void 0)return;i=i[c]}else return}return a}function Sf(e,t,n,r){if(!(n.fixed||n.pattern))return e;if(Array.isArray(e))return e.map(l=>Sf(l,t,n,r));e==null&&(e=Object.create(null));const o=e,i=t.split(".");let a=o;for(let l=0;l<i.length;l++){let c=i[l];if(c.includes("[x]")){const d=r[i.slice(0,l+1).join(".")].type[0].code;c=c.replace("[x]",tn(d))}if(l===i.length-1){const u=Array.isArray(a)?a:[a];for(const d of u)n.fixed?d[c]??(d[c]=n.fixed.value):n.pattern&&(d[c]=Ak(d[c],n.pattern.value))}else{if(!(c in a)){const u=i.slice(0,l+1).join(".");a[c]=r[u].isArray?[Object.create(null)]:Object.create(null)}a=a[c]}}return o}function Ak(e,t){if(Array.isArray(t)&&(Array.isArray(e)||e===void 0))return((e==null?void 0:e.length)??0)>0?e:Kr(t);if(Rn(t)&&(Rn(e)&&!Array.isArray(e)||e===void 0)){const n=Kr(e)??Object.create(null);for(const r of Object.keys(t))n[r]=Ak(n[r],t[r]);return n}return e}const Nk=p.createContext(void 0);function Vh(){return p.useContext(Nk)}function le(){return Vh().medplum}function Wh(){return Vh().navigate}function Hh(){return Vh().profile}const Tw=["change","storageInitialized","storageInitFailed","profileRefreshing","profileRefreshed"];function K8(e){const t=e.medplum,n=e.navigate??Y8,[r,o]=p.useState({profile:t.getProfile(),loading:t.isLoading()});p.useEffect(()=>{function a(){o(l=>({...l,profile:t.getProfile(),loading:t.isLoading()}))}for(const l of Tw)t.addEventListener(l,a);return()=>{for(const l of Tw)t.removeEventListener(l,a)}},[t]);const i=p.useMemo(()=>({...r,medplum:t,navigate:n}),[r,t,n]);return s.jsx(Nk.Provider,{value:i,children:e.children})}function Y8(e){window.location.assign(e)}const Pw=new Map,Mk=e=>p.useMemo(()=>{if(!e)return;const t=e.split("?")[0];if(!t)return e;let n;try{n=new URLSearchParams(new URL(e).search)}catch{return e}if(!n.has("Key-Pair-Id")||!n.has("Signature"))return e;const r=n.get("Expires");if(!r||r.length>13)return e;const o=Pw.get(t);if(o){const a=new URLSearchParams(new URL(o).search).get("Expires");if(a&&parseInt(a,10)*1e3-5e3>Date.now())return o}return Pw.set(t,e),e},[e]);function St(e,t){const n=le(),[r,o]=p.useState(()=>kw(n,e)),i=p.useCallback(a=>{Ui(a,r)||o(a)},[r]);return p.useEffect(()=>{let a=!0;const l=kw(n,e);return!l&&Xs(e)?n.readReference(e).then(c=>{a&&i(c)}).catch(c=>{a&&(i(void 0),t&&t(ft(c)))}):i(l),()=>a=!1},[n,e,i,t]),r}function kw(e,t){if(t){if(ri(t))return t;if(Xs(t))return e.getCachedReference(t)}}function X8(e,t){return Ok("searchOne",e,t)}function al(e,t){return Ok("searchResources",e,t)}function Ok(e,t,n){const r=le(),[o,i]=p.useState(),[a,l]=p.useState(!0),[c,u]=p.useState(),[d,f]=p.useState();return p.useEffect(()=>{const h=r.fhirSearchUrl(t,n).toString();h!==o&&(i(h),r[e](t,n).then(m=>{l(!1),u(m),f(G$)}).catch(m=>{l(!1),u(void 0),f(ft(m))}))},[r,e,t,n,o]),[c,a,d]}function J8(e){const t=e.value;return t?s.jsx(s.Fragment,{children:I6(t)}):null}const Lk=["meta","implicitRules","contained","extension","modifierExtension"],$k=["language","text"],wt=p.createContext({path:"",profileUrl:void 0,elements:Object.create(null),elementsByPath:Object.create(null),getExtendedProps:()=>({readonly:!1,hidden:!1}),accessPolicyResource:void 0,debugMode:!1,isDefaultContext:!0});wt.displayName="ElementsContext";const Kx=["extension","modifierExtension"],Z8=["id",...Lk].filter(e=>!Kx.includes(e));function ez(e){return Object.entries(e).filter(([n,r])=>{var o;return!$t(r.type)||r.max===0||r.path.toLowerCase().endsWith("extension.url")&&r.fixed||Kx.includes(n)&&!$t((o=r.slicing)==null?void 0:o.slices)||Z8.includes(n)?!1:!($k.includes(n)&&r.path.split(".").length===2||n.includes("."))})}function Rw(e,t){return e.line&&e.line.length>t?e.line[t]:""}function _w(e,t,n){const r=e.line||[];for(;r.length<=t;)r.push("");return r[t]=n,{...e,line:r}}function tz(e){const[t,n]=p.useState(e.defaultValue||{}),r=p.useRef();r.current=t;const{getExtendedProps:o}=p.useContext(wt),[i,a,l,c,u,d,f]=p.useMemo(()=>["use","type","line1","line2","city","state","postalCode"].map(x=>o(e.path+"."+x)),[o,e.path]);function h(x){n(x),e.onChange&&e.onChange(x)}function m(x){h({...r.current,use:x})}function g(x){h({...r.current,type:x})}function v(x){h(_w(r.current||{},0,x))}function S(x){h(_w(r.current||{},1,x))}function b(x){h({...r.current,city:x})}function w(x){h({...r.current,state:x})}function y(x){h({...r.current,postalCode:x})}return s.jsxs(te,{gap:"xs",wrap:"nowrap",grow:!0,children:[s.jsx(It,{disabled:e.disabled||(i==null?void 0:i.readonly),"data-testid":"address-use",defaultValue:t.use,onChange:x=>m(x.currentTarget.value),data:["","home","work","temp","old","billing"]}),s.jsx(It,{disabled:e.disabled||(a==null?void 0:a.readonly),"data-testid":"address-type",defaultValue:t.type,onChange:x=>g(x.currentTarget.value),data:["","postal","physical","both"]}),s.jsx(ye,{disabled:e.disabled||(l==null?void 0:l.readonly),placeholder:"Line 1",defaultValue:Rw(t,0),onChange:x=>v(x.currentTarget.value)}),s.jsx(ye,{disabled:e.disabled||(c==null?void 0:c.readonly),placeholder:"Line 2",defaultValue:Rw(t,1),onChange:x=>S(x.currentTarget.value)}),s.jsx(ye,{disabled:e.disabled||(u==null?void 0:u.readonly),placeholder:"City",defaultValue:t.city,onChange:x=>b(x.currentTarget.value)}),s.jsx(ye,{disabled:e.disabled||(d==null?void 0:d.readonly),placeholder:"State",defaultValue:t.state,onChange:x=>w(x.currentTarget.value)}),s.jsx(ye,{disabled:e.disabled||(f==null?void 0:f.readonly),placeholder:"Postal Code",defaultValue:t.postalCode,onChange:x=>y(x.currentTarget.value)})]})}function nz(e){const t=Hh(),[n,r]=p.useState(e.defaultValue||{});function o(i){const a=i?{text:i,authorReference:t&&Tt(t),time:new Date().toISOString()}:{};r(a),e.onChange&&e.onChange(a)}return s.jsx(ye,{disabled:e.disabled,name:e.name,placeholder:"Annotation text",defaultValue:n.text,onChange:i=>o(i.currentTarget.value)})}/**
|
|
141
|
+
}`.replace(/\s+/g," "),a=await this.graphql(i);nw(a.data.StructureDefinitionList);for(const l of a.data.SearchParameterList)U6(l)})());return this.setCacheEntry(n,o),o}requestProfileSchema(t,n){if(!(n!=null&&n.expandProfile)&&Ix(t))return Promise.resolve();const r=t+"-requestSchema"+(n!=null&&n.expandProfile?"-nested":""),o=this.getCacheEntry(r,void 0);if(o)return o.value;const i=new Or((async()=>{if(n!=null&&n.expandProfile){const a=this.fhirUrl("StructureDefinition","$expand-profile");a.search=new URLSearchParams({url:t}).toString();const l=await this.post(a.toString(),{});nw(l)}else{const a=await this.searchOne("StructureDefinition",{url:t,_sort:"-_lastUpdated"});if(!a){console.warn(`No StructureDefinition found for ${t}!`);return}JP(a)}})());return this.setCacheEntry(r,i),i}readHistory(t,n,r){return this.get(this.fhirUrl(t,n,"_history"),r)}readVersion(t,n,r,o){return this.get(this.fhirUrl(t,n,"_history",r),o)}readPatientEverything(t,n){return this.get(this.fhirUrl("Patient",t,"$everything"),n)}createResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");return this.invalidateSearches(t.resourceType),this.post(this.fhirUrl(t.resourceType),t,void 0,n)}async createResourceIfNoneExist(t,n,r){return await this.searchOne(t.resourceType,n,r)??this.createResource(t,r)}async upsertResource(t,n,r){const o=this.fhirSearchUrl(t.resourceType,n);let i=await this.put(o,t,void 0,r);return i||(i=t),this.cacheResource(i),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),i}async createAttachment(t,n,r,o,i){const a=Cw(t,n,r,o),l=i??(typeof n=="object"?n:{}),c=await this.createBinary(a,l);return{contentType:a.contentType,url:c.url,title:a.filename}}createBinary(t,n,r,o,i){const a=Cw(t,n,r,o),l=i??(typeof n=="object"?n:{}),{data:c,contentType:u,filename:d,securityContext:f,onProgress:h}=a,m=this.fhirUrl("Binary");return d&&m.searchParams.set("_filename",d),f!=null&&f.reference&&this.setRequestHeader(l,"X-Security-Context",f.reference),h?this.uploadwithProgress(m,c,u,h,l):this.post(m,c,u,l)}uploadwithProgress(t,n,r,o,i){return new Promise((a,l)=>{var f;const c=new XMLHttpRequest,u=()=>c.abort();(f=i==null?void 0:i.signal)==null||f.addEventListener("abort",u);const d=h=>{var m;(m=i==null?void 0:i.signal)==null||m.removeEventListener("abort",u),h instanceof Error?l(h):a(h)};if(c.responseType="json",c.onabort=()=>d(new DOMException("Request aborted","AbortError")),c.onerror=()=>d(new Error("Request error")),o&&(c.upload.onprogress=h=>o(h),c.upload.onload=h=>o(h)),c.onload=()=>{c.status>=200&&c.status<300?d(c.response):d(new Be(ft(c.response||c.statusText)))},c.open("POST",t),c.withCredentials=!0,c.setRequestHeader("Authorization","Bearer "+this.accessToken),c.setRequestHeader("Cache-Control","no-cache, no-store, max-age=0"),c.setRequestHeader("Content-Type",r),c.setRequestHeader("X-Medplum","extended"),i!=null&&i.headers){const h=i.headers;for(const[m,g]of Object.entries(h))c.setRequestHeader(m,g)}c.send(n)})}async createPdf(t,n,r,o){if(!this.createPdfImpl)throw new Error("PDF creation not enabled");const i=F8(t,n,r,o),a=typeof n=="object"?n:{},{docDefinition:l,tableLayouts:c,fonts:u,...d}=i,f=await this.createPdfImpl(l,c,u),h={...d,data:f,contentType:"application/pdf"};return this.createBinary(h,a)}createComment(t,n,r){const o=this.getProfile();let i,a;return t.resourceType==="Encounter"&&(i=Tt(t),a=t.subject),t.resourceType==="ServiceRequest"&&(i=t.encounter,a=t.subject),t.resourceType==="Patient"&&(a=Tt(t)),this.createResource({resourceType:"Communication",status:"completed",basedOn:[Tt(t)],encounter:i,subject:a,sender:o?Tt(o):void 0,sent:new Date().toISOString(),payload:[{contentString:n}]},r)}async updateResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");if(!t.id)throw new Error("Missing id");let r=await this.put(this.fhirUrl(t.resourceType,t.id),t,void 0,n);return r||(r=t),this.cacheResource(r),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),r}async patchResource(t,n,r,o){const i=await this.patch(this.fhirUrl(t,n),r,o);return this.cacheResource(i),this.invalidateUrl(this.fhirUrl(t,n,"_history")),this.invalidateSearches(t),i}deleteResource(t,n,r){return this.deleteCacheEntry(this.fhirUrl(t,n).toString()),this.invalidateSearches(t),this.delete(this.fhirUrl(t,n),r)}validateResource(t,n){return this.post(this.fhirUrl(t.resourceType,"$validate"),t,void 0,n)}executeBot(t,n,r,o){let i;if(typeof t=="string"){const a=t;i=this.fhirUrl("Bot",a,"$execute")}else{const a=t;i=this.fhirUrl("Bot","$execute"),i.searchParams.set("identifier",a.system+"|"+a.value)}return this.post(i,n,r,o)}executeBatch(t,n){return this.post(this.fhirBaseUrl,t,void 0,n)}sendEmail(t,n){return this.post("email/v1/send",t,rn.JSON,n)}graphql(t,n,r,o){return this.post(this.fhirUrl("$graphql"),{query:t,operationName:n,variables:r},rn.JSON,o)}readResourceGraph(t,n,r,o){return this.get(`${this.fhirUrl(t,n)}/$graph?graph=${r}`,o)}pushToAgent(t,n,r,o,i,a){return this.post(this.fhirUrl("Agent",il(t),"$push"),{destination:typeof n=="string"?n:rt(n),body:r,contentType:o,waitForResponse:i},rn.FHIR_JSON,a)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(t){var n,r;(!((n=this.sessionDetails)!=null&&n.profile)||rt(this.sessionDetails.profile)!==((r=t.profile)==null?void 0:r.reference))&&this.clearActiveLogin(),this.setAccessToken(t.accessToken,t.refreshToken),this.storage.setObject("activeLogin",t),this.addLogin(t),this.refreshPromise=void 0,await this.refreshProfile()}getAccessToken(){return this.accessToken}setAccessToken(t,n){this.accessToken=t,this.refreshToken=n,this.accessTokenExpires=x8(t),this.medplumServer=y8(t)}getLogins(){return this.storage.getObject("logins")??[]}addLogin(t){const n=this.getLogins().filter(r=>{var o,i;return((o=r.profile)==null?void 0:o.reference)!==((i=t.profile)==null?void 0:i.reference)});n.push(t),this.storage.setObject("logins",n)}async refreshProfile(){return this.medplumServer?(this.profilePromise=new Promise((t,n)=>{this.get("auth/me",{cache:"no-cache"}).then(r=>{var i,a;this.profilePromise=void 0;const o=((a=(i=this.sessionDetails)==null?void 0:i.profile)==null?void 0:a.id)!==r.profile.id;this.sessionDetails=r,o&&this.dispatchEvent({type:"change"}),t(r.profile),this.dispatchEvent({type:"profileRefreshed"})}).catch(n)}),this.dispatchEvent({type:"profileRefreshing"}),this.profilePromise):Promise.resolve(void 0)}isLoading(){var t;return!this.isInitialized||!!this.profilePromise&&!((t=this.sessionDetails)!=null&&t.profile)}isSuperAdmin(){var t;return!!((t=this.sessionDetails)!=null&&t.project.superAdmin)}isProjectAdmin(){var t;return!!((t=this.sessionDetails)!=null&&t.membership.admin)}getProject(){var t;return(t=this.sessionDetails)==null?void 0:t.project}getProjectMembership(){var t;return(t=this.sessionDetails)==null?void 0:t.membership}getProfile(){var t;return(t=this.sessionDetails)==null?void 0:t.profile}async getProfileAsync(){return this.profilePromise?this.profilePromise:this.sessionDetails?this.sessionDetails.profile:this.refreshProfile()}getUserConfiguration(){var t;return(t=this.sessionDetails)==null?void 0:t.config}getAccessPolicy(){var t;return(t=this.sessionDetails)==null?void 0:t.accessPolicy}async download(t,n={}){this.refreshPromise&&await this.refreshPromise;const r=t.toString();r.startsWith(M8)&&(t=this.fhirUrl(r));let o=n.headers;return o||(o={},n.headers=o),o.Accept||(o.Accept="*/*"),this.addFetchOptionsDefaults(n),(await this.fetchWithRetry(t.toString(),n)).blob()}async createMedia(t,n){const{additionalFields:r,...o}=t,i=await this.createResource({resourceType:"Media",status:"preparation",content:{contentType:t.contentType},...r});o.securityContext||(o.securityContext=Tt(i));const a=await this.createAttachment(o,n);return this.updateResource({...i,status:"completed",content:a})}async uploadMedia(t,n,r,o,i){return this.createMedia({data:t,contentType:n,filename:r,additionalFields:o},i)}async bulkExport(t="",n,r,o){const i=t&&`${t}/`,a=this.fhirUrl(`${i}$export`);return n&&a.searchParams.set("_type",n),r&&a.searchParams.set("_since",r),this.startAsyncRequest(a.toString(),o)}async startAsyncRequest(t,n={}){this.addFetchOptionsDefaults(n);const r=n.headers;return r.Prefer="respond-async",this.request("POST",t,n)}get keyValue(){return this.keyValueClient||(this.keyValueClient=new b8(this)),this.keyValueClient}getCacheEntry(t,n){if(!this.requestCache||(n==null?void 0:n.cache)==="no-cache"||(n==null?void 0:n.cache)==="reload")return;const r=this.requestCache.get(t);if(!(!r||r.requestTime+this.cacheTime<Date.now()))return r}setCacheEntry(t,n){this.requestCache&&this.requestCache.set(t,{requestTime:Date.now(),value:n})}cacheResource(t){var n,r;t!=null&&t.id&&!((r=(n=t.meta)==null?void 0:n.tag)!=null&&r.some(o=>o.code==="SUBSETTED"))&&this.setCacheEntry(this.fhirUrl(t.resourceType,t.id).toString(),new Or(Promise.resolve(t)))}deleteCacheEntry(t){this.requestCache&&this.requestCache.delete(t)}async request(t,n,r={},o={}){await this.refreshIfExpired(),r.method=t,this.addFetchOptionsDefaults(r);const i=await this.fetchWithRetry(n,r);if(i.status===401)return this.handleUnauthenticated(t,n,r);if(i.status===204||i.status===304)return;const a=i.headers.get("content-type"),l=a==null?void 0:a.includes("json");if(i.status===404&&!l)throw new Be(Q$);const c=await this.parseBody(i,l);if(i.status===200&&r.followRedirectOnOk||i.status===201&&r.followRedirectOnCreated){const u=await Sw(i,c);if(u)return this.request("GET",u,{...r,body:void 0})}if(i.status===202&&r.pollStatusOnAccepted){const d=await Sw(i,c)??o.statusUrl;if(d)return this.pollStatus(d,r,o)}if(i.status>=400)throw new Be(ft(c));return c}async parseBody(t,n){let r;if(n)try{r=await t.json()}catch(o){throw console.error("Error parsing response",t.status,o),o}else r=await t.text();return r}async fetchWithRetry(t,n){t.startsWith("http")||(t=Po(this.baseUrl,t));const r=(n==null?void 0:n.maxRetries)??2,o=200;for(let i=0;i<=r;i++){try{this.options.verbose&&this.logRequest(t,n);const a=await this.fetch(t,n);if(this.options.verbose&&this.logResponse(a),a.status<500||i===r)return a}catch(a){if(a.message==="Failed to fetch"&&i===0&&this.dispatchEvent({type:"offline"}),a.name==="AbortError"||i===r)throw a}await uw(o)}throw new Error("Unreachable")}logRequest(t,n){if(console.log(`> ${n.method} ${t}`),n.headers){const r=n.headers;for(const o of Oc(Object.keys(r)))console.log(`> ${o}: ${r[o]}`)}}logResponse(t){console.log(`< ${t.status} ${t.statusText}`),t.headers&&t.headers.forEach((n,r)=>console.log(`< ${r}: ${n}`))}async pollStatus(t,n,r){const o={...n,method:"GET",body:void 0,redirect:"follow"};if(r.pollCount===void 0)n.headers&&typeof n.headers=="object"&&"Prefer"in n.headers&&(o.headers={...n.headers},delete o.headers.Prefer),r.statusUrl=t,r.pollCount=1;else{const i=n.pollStatusPeriod??1e3;await uw(i),r.pollCount++}return this.request("GET",t,o,r)}async executeAutoBatch(){var o,i;const t=[...this.autoBatchQueue];if(this.autoBatchQueue.length=0,this.autoBatchTimerId=void 0,t.length===1){const a=t[0];try{a.resolve(await this.request(a.method,Po(this.fhirBaseUrl,a.url),a.options))}catch(l){a.reject(new Be(ft(l)))}return}const n={resourceType:"Bundle",type:"batch",entry:t.map(a=>({request:{method:a.method,url:a.url},resource:a.options.body?JSON.parse(a.options.body):void 0}))},r=await this.post(this.fhirBaseUrl,n);for(let a=0;a<t.length;a++){const l=t[a],c=(o=r.entry)==null?void 0:o[a];(i=c==null?void 0:c.response)!=null&&i.outcome&&!QP(c.response.outcome)?l.reject(new Be(c.response.outcome)):l.resolve(c==null?void 0:c.resource)}}addFetchOptionsDefaults(t){this.setRequestHeader(t,"X-Medplum","extended"),this.setRequestHeader(t,"Accept",R8,!0),t.body&&this.setRequestHeader(t,"Content-Type",rn.FHIR_JSON,!0),this.accessToken?this.setRequestHeader(t,"Authorization","Bearer "+this.accessToken):this.basicAuth&&this.setRequestHeader(t,"Authorization","Basic "+this.basicAuth),t.cache||(t.cache="no-cache"),t.credentials||(t.credentials="include")}setRequestContentType(t,n){this.setRequestHeader(t,"Content-Type",n)}setRequestHeader(t,n,r,o=!1){t.headers||(t.headers={});const i=t.headers;o&&i[n]||(i[n]=r)}setRequestBody(t,n){typeof n=="string"||typeof Blob<"u"&&(n instanceof Blob||n.constructor.name==="Blob")||typeof File<"u"&&(n instanceof File||n.constructor.name==="File")||typeof Uint8Array<"u"&&(n instanceof Uint8Array||n.constructor.name==="Uint8Array")?t.body=n:n&&(t.body=JSON.stringify(n))}handleUnauthenticated(t,n,r){return this.refresh()?this.request(t,n,r):(this.clear(),this.onUnauthenticated&&this.onUnauthenticated(),Promise.reject(new Be(Nc)))}async startPkce(){const t=pw();sessionStorage.setItem("pkceState",t);const n=pw().slice(0,128);sessionStorage.setItem("codeVerifier",n);const r=await n8(n),o=C6(r).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return sessionStorage.setItem("codeChallenge",o),{codeChallengeMethod:"S256",codeChallenge:o}}async requestAuthorization(t){const n=await this.ensureCodeChallenge(t??{}),r=new URL(this.authorizeUrl);r.searchParams.set("response_type","code"),r.searchParams.set("state",sessionStorage.getItem("pkceState")),r.searchParams.set("client_id",n.clientId??this.clientId),r.searchParams.set("redirect_uri",n.redirectUri??ww()),r.searchParams.set("code_challenge_method",n.codeChallengeMethod),r.searchParams.set("code_challenge",n.codeChallenge),r.searchParams.set("scope",n.scope??"openid profile"),window.location.assign(r.toString())}processCode(t,n){const r=new URLSearchParams;if(r.set("grant_type","authorization_code"),r.set("code",t),r.set("client_id",(n==null?void 0:n.clientId)??this.clientId),r.set("redirect_uri",(n==null?void 0:n.redirectUri)??ww()),typeof sessionStorage<"u"){const o=sessionStorage.getItem("codeVerifier");o&&r.set("code_verifier",o)}return this.fetchTokens(r)}refreshIfExpired(t){return t===void 0&&(t=this.refreshGracePeriod),!this.refreshPromise&&this.accessTokenExpires!==void 0&&Date.now()>this.accessTokenExpires-t&&this.refresh(),this.refreshPromise??Promise.resolve()}refresh(){if(this.refreshPromise)return this.refreshPromise;if(this.refreshToken){const t=new URLSearchParams;return t.set("grant_type","refresh_token"),t.set("client_id",this.clientId),t.set("refresh_token",this.refreshToken),this.refreshPromise=this.fetchTokens(t),this.refreshPromise}if(this.clientId&&this.clientSecret)return this.refreshPromise=this.startClientLogin(this.clientId,this.clientSecret),this.refreshPromise}async startClientLogin(t,n){this.clientId=t,this.clientSecret=n;const r=new URLSearchParams;return r.set("grant_type","client_credentials"),r.set("client_id",t),r.set("client_secret",n),this.fetchTokens(r)}async startJwtBearerLogin(t,n,r){this.clientId=t;const o=new URLSearchParams;return o.set("grant_type","urn:ietf:params:oauth:grant-type:jwt-bearer"),o.set("client_id",t),o.set("assertion",n),o.set("scope",r),this.fetchTokens(o)}async startJwtAssertionLogin(t){const n=new URLSearchParams;return n.append("grant_type","client_credentials"),n.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),n.append("client_assertion",t),this.fetchTokens(n)}setBasicAuth(t,n){this.clientId=t,this.clientSecret=n,this.basicAuth=t8(t+":"+n)}async fhircastSubscribe(t,n){if(!(typeof t=="string"&&t!==""))throw new Be(_t("Invalid topic provided. Topic must be a valid string."));if(!(typeof n=="object"&&Array.isArray(n)&&n.length>0))throw new Be(_t("Invalid events provided. Events must be an array of event names containing at least one event."));const r={channelType:"websocket",mode:"subscribe",topic:t,events:n},i=(await this.post("/fhircast/STU3",mw(r),rn.FORM_URL_ENCODED))["hub.channel.endpoint"];if(!i)throw new Error("Invalid response!");return r.endpoint=i,r}async fhircastUnsubscribe(t){if(!Gx(t))throw new Be(_t("Invalid topic or subscriptionRequest. SubscriptionRequest must be an object."));if(!(t.endpoint&&typeof t.endpoint=="string"&&t.endpoint.startsWith("ws")))throw new Be(_t("Provided subscription request must have an endpoint in order to unsubscribe."));t.mode="unsubscribe",await this.post("/fhircast/STU3",mw(t),rn.FORM_URL_ENCODED)}fhircastConnect(t){return new m8(t)}async fhircastPublish(t,n,r,o){return c8(n)?this.post(`/fhircast/STU3/${t}`,vw(t,n,r,o),rn.JSON):(u8(n),this.post(`/fhircast/STU3/${t}`,vw(t,n,r),rn.JSON))}async fhircastGetContext(t){return this.get(`/fhircast/STU3/${t}`)}async invite(t,n){return this.post("admin/projects/"+t+"/invite",n)}async fetchTokens(t){const n={method:"POST",headers:{"Content-Type":rn.FORM_URL_ENCODED},body:t.toString(),credentials:"include"},r=n.headers;this.basicAuth&&(r.Authorization=`Basic ${this.basicAuth}`);let o;try{o=await this.fetchWithRetry(this.tokenUrl,n)}catch(a){throw this.refreshPromise=void 0,a}if(!o.ok){this.clearActiveLogin();try{const a=await o.json();throw new Be(Oi(a.error_description))}catch(a){throw new Be(Oi("Failed to fetch tokens"),a)}}const i=await o.json();return await this.verifyTokens(i),this.getProfile()}async verifyTokens(t){const n=t.access_token;if(v8(n)){const r=Qx(n);if(Date.now()>=r.exp*1e3)throw this.clearActiveLogin(),new Be(K$);if(r.cid){if(r.cid!==this.clientId)throw this.clearActiveLogin(),new Be(ew)}else if(this.clientId&&r.client_id!==this.clientId)throw this.clearActiveLogin(),new Be(ew)}return this.setActiveLogin({accessToken:n,refreshToken:t.refresh_token,project:t.project,profile:t.profile})}checkSessionDetailsMatchLogin(t){var n,r;return this.sessionDetails&&t?((r=(n=t.profile)==null?void 0:n.reference)==null?void 0:r.endsWith(this.sessionDetails.profile.id))??!1:!0}setupStorageListener(){try{window.addEventListener("storage",t=>{if(t.key===null)window.location.reload();else if(t.key==="activeLogin"){const n=t.oldValue?JSON.parse(t.oldValue):void 0,r=t.newValue?JSON.parse(t.newValue):void 0;(n==null?void 0:n.profile.reference)!==(r==null?void 0:r.profile.reference)||!this.checkSessionDetailsMatchLogin(r)?window.location.reload():r?this.setAccessToken(r.accessToken,r.refreshToken):this.clear()}})}catch{}}getSubscriptionManager(){return this.subscriptionManager||(this.subscriptionManager=new P8(this,R6(this.baseUrl,"/ws/subscriptions-r4"))),this.subscriptionManager}subscribeToCriteria(t,n){return this.getSubscriptionManager().addCriteria(t,n)}unsubscribeFromCriteria(t,n){this.subscriptionManager&&(this.subscriptionManager.removeCriteria(t,n),this.subscriptionManager.getCriteriaCount()===0&&this.subscriptionManager.closeWebSocket())}getMasterSubscriptionEmitter(){return this.getSubscriptionManager().getMasterEmitter()}}function O8(){if(!globalThis.fetch)throw new Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}function ww(){return typeof window>"u"?"":window.location.protocol+"//"+window.location.host+"/"}async function Sw(e,t){var o,i;const n=e.headers.get("content-location");if(n)return n;const r=e.headers.get("location");if(r)return r;if(Lh(t)&&((i=(o=t.issue)==null?void 0:o[0])!=null&&i.diagnostics))return t.issue[0].diagnostics}function jw(e){var n;const t=((n=e.entry)==null?void 0:n.map(r=>r.resource))??[];return Object.assign(t,{bundle:e})}function L8(e){return Rn(e)&&"data"in e&&"contentType"in e}function Cw(e,t,n,r){return L8(e)?e:{data:e,filename:t,contentType:n,onProgress:r}}function $8(e){return Rn(e)&&"docDefinition"in e}function F8(e,t,n,r){return $8(e)?e:{docDefinition:e,filename:t,tableLayouts:n,fonts:r}}function sl({parentContext:e,path:t,elements:n,profileUrl:r,debugMode:o,accessPolicyResource:i}){if(t===(e==null?void 0:e.path))return;o??(o=(e==null?void 0:e.debugMode)??!1),i??(i=e==null?void 0:e.accessPolicyResource);let a=z8(t,n,e,!!o);const l=Pg(t,".",2)[1];a=B8(a,i,l),a=U8(a,i,l);const c=Object.create(null);for(const[d,f]of Object.entries(a))c[t+"."+d]=f;let u;if(e&&!e.isDefaultContext)u=e.getExtendedProps;else{const d=Object.create(null);u=f=>{const h=Pg(f,".",2)[1];if(h){if(!d[h]){const m=wf(h,i==null?void 0:i.hiddenFields);d[h]={hidden:m,readonly:m||wf(h,i==null?void 0:i.readonlyFields)}}return d[h]}}}return{path:t,elements:a,elementsByPath:c,profileUrl:r??(e==null?void 0:e.profileUrl),debugMode:o,getExtendedProps:u,accessPolicyResource:i}}function z8(e,t,n,r){const o=Object.create(null);if(n)for(const[a,l]of Object.entries(n.elementsByPath)){const c=Mc(e,a);c!==void 0&&(o[c]=l)}let i=!1;if(t)for(const[a,l]of Object.entries(t))a in o||(o[a]=l,i=!0);return r&&console.assert(i,"Unnecessary ElementsContext; not using any newly provided elements"),o}function B8(e,t,n){var o;if(!((o=t==null?void 0:t.hiddenFields)!=null&&o.length))return e;const r=n?n+".":"";return Object.fromEntries(Object.entries(e).filter(([i])=>!wf(r+i,t.hiddenFields)))}function U8(e,t,n){var i;if(!((i=t==null?void 0:t.readonlyFields)!=null&&i.length))return e;const r=Object.create(null),o=n?n+".":"";for(const[a,l]of Object.entries(e))wf(o+a,t.readonlyFields)?r[a]={...l,readonly:!0}:r[a]=l;return r}function wf(e,t){if(!(t!=null&&t.length))return!1;const n=e.split(".");for(let r=1;r<=n.length;r++){const o=n.slice(0,r).join(".");if(t.includes(o))return!0}return!1}function Dk(e){return e.type!==void 0&&e.type.length>0}function V8(e,t,n,r){var i;const o=X7(e,t.path,{profileUrl:r});if(o){const a=((i=n.typeSchema)==null?void 0:i.elements)??n.elements;return o.some(l=>e6(l,t,n,a))??!1}return console.assert(!1,"getNestedProperty[%s] in isDiscriminatorComponentMatch missed",t.path),!1}function Ik(e,t,n,r){var o,i;if(e)for(const a of t){const l={value:e,type:((o=a.typeSchema)==null?void 0:o.type)??((i=a.type)==null?void 0:i[0].code)};if(n.every(c=>{var u;return V8(l,c,a,((u=a.typeSchema)==null?void 0:u.url)??r)}))return a.name}}class W8{constructor(t,n,r){if(t.type===void 0)throw new Error("schema must include a type");this.rootSchema=t;const o=sl({parentContext:void 0,path:this.rootSchema.type,elements:r??this.rootSchema.elements,profileUrl:this.rootSchema.name===this.rootSchema.type?void 0:this.rootSchema.url});if(o===void 0)throw new Error("Could not create root elements context");this.elementsContextStack=[o],this.visitor=n}get elementsContext(){return this.elementsContextStack[this.elementsContextStack.length-1]}crawlElement(t,n,r){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema);const o=Object.fromEntries(Object.entries(this.elementsContext.elements).filter(([i])=>i.startsWith(n)));this.crawlElementsImpl(o,r),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlSlice(t,n,r){const o=this.prepareSlices(r.slices,r);if(!$t(o.slices))throw new Error(`cannot crawl slice ${n.name} since it has no type information`);this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.sliceAllowList=[n],this.crawlSliceImpl(o.slices[0],n.path,o),this.sliceAllowList=void 0,this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlResource(){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.crawlElementsImpl(this.rootSchema.elements,this.rootSchema.type),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlElementsImpl(t,n){const r=H8(t);for(const o of r)this.crawlElementNode(o,n)}crawlElementNode(t,n){var o,i;const r=n+"."+t.key;this.visitor.onEnterElement&&this.visitor.onEnterElement(r,t.element,this.elementsContext);for(const a of t.children)this.crawlElementNode(a,n);$t((i=(o=t.element)==null?void 0:o.slicing)==null?void 0:i.slices)&&this.crawlSlicingImpl(t.element.slicing,r),this.visitor.onExitElement&&this.visitor.onExitElement(r,t.element,this.elementsContext)}prepareSlices(t,n){var i,a;const r=[];for(const l of t){if(!Dk(l))continue;const c=(a=(i=l.type.find(u=>$t(u.profile)))==null?void 0:i.profile)==null?void 0:a[0];if($t(c)){const u=wl(c);u&&(l.typeSchema=u)}r.push(l)}return{...n,slices:r}}crawlSlicingImpl(t,n){const r=this.prepareSlices(t.slices,t);for(const o of r.slices)(this.sliceAllowList===void 0||this.sliceAllowList.includes(o))&&this.crawlSliceImpl(o,n,r)}crawlSliceImpl(t,n,r){const o=t.typeSchema;o&&this.visitor.onEnterSchema&&this.visitor.onEnterSchema(o),this.visitor.onEnterSlice&&this.visitor.onEnterSlice(n,t,r);let i;const a=(o==null?void 0:o.elements)??t.elements;$t(a)&&(i=sl({path:n,parentContext:this.elementsContext,elements:a})),i&&this.elementsContextStack.push(i),this.crawlElementsImpl(a,n),i&&this.elementsContextStack.pop(),this.visitor.onExitSlice&&this.visitor.onExitSlice(n,t,r),o&&this.visitor.onExitSchema&&this.visitor.onExitSchema(o)}}function H8(e){const t=[];function n(i,a){return a.startsWith(i+".")}function r(i,a){for(const l of i.children)if(n(l.key,a.key)){r(l,a);return}i.children.push(a)}const o=Object.entries(e);o.sort((i,a)=>i[0].localeCompare(a[0]));for(const[i,a]of o){const l={key:i,element:a,children:[]};let c=!1;for(const u of t)if(n(u.key,i)){r(u,l),c=!0;break}c||t.push(l)}return t}const em="__sliceName";function q8(e,t){const n=new G8(e,e.resourceType,"resource");return new W8(t,n).crawlResource(),n.getDefaultValue()}function Ew(e,t,n){for(const[r,o]of Object.entries(t)){if(n===void 0||n===r){Sf(e,r,o,t);continue}const i=Mc(n,r);i!==void 0&&Sf(e,i,o,t)}return e}class G8{constructor(t,n,r){this.schemaStack=[],this.valueStack=[],this.rootValue=Kr(t),this.valueStack.splice(0,this.valueStack.length,{type:r,path:n,values:[this.rootValue]})}get schema(){return this.schemaStack[this.schemaStack.length-1]}get value(){return this.valueStack[this.valueStack.length-1]}onEnterSchema(t){this.schemaStack.push(t)}onExitSchema(){this.schemaStack.pop()}onEnterElement(t,n,r){const o=this.value.values,i=this.value.path,a=Mc(i,t);if(a===void 0)throw new Error(`Expected ${t} to be prefixed by ${i}`);const l=[];for(const c of o){if(c===void 0)continue;const u=Array.isArray(c)?c:[c];for(const d of u){Q8(d,a,n,r.elements),Sf(d,a,n,r.elements);const f=Ag(d,a,n,r.elements);f!==void 0&&l.push(f)}}this.valueStack.push({type:"element",path:t,values:l})}onExitElement(t,n,r){if(!this.valueStack.pop())throw new Error("Expected value context to exist when exiting element");const i=Mc(this.value.path,t);if(i===void 0)throw new Error(`Expected ${t} to be prefixed by ${this.value.path}`);for(const a of this.value.values){const l=Ag(a,i,n,r.elements);if(Array.isArray(l))for(let c=l.length-1;c>=0;c--){const u=l[c];$t(u)||l.splice(c,1)}qt(l)&&Ig(a,void 0,i,n)}}onEnterSlice(t,n,r){const o=this.value.values,i=[];for(const a of o){if(a===void 0)continue;if(!Array.isArray(a))throw new Error("Expected array value for sliced element");const l=this.getMatchingSliceValues(a,n,r);i.push(l)}this.valueStack.push({type:"slice",path:t,values:i})}getMatchingSliceValues(t,n,r){const o=[];for(const i of t)(i[em]??Ik(i,[n],r.discriminator,this.schema.url))===n.name&&o.push(i);for(let i=o.length;i<n.min;i++)if(Ox(n.type[0].code)){const a=Object.create(null);o.push(a),t.push(a)}return o}onExitSlice(){const t=this.valueStack.pop();if(!t)throw new Error("Expected value context to exist in onExitSlice");for(const n of t.values)for(let r=n.length-1;r>=0;r--){const o=n[r];em in o&&delete o[em]}}getDefaultValue(){return this.rootValue}}function Q8(e,t,n,r){const o=Ag(e,t,n,r);n.min>0&&o===void 0&&Ox(n.type[0].code)&&(n.isArray?Ig(e,[Object.create(null)],t,n):Ig(e,Object.create(null),t,n))}function Ig(e,t,n,r){if(n.includes("."))throw new Error("key cannot be nested");let o=n;if(n.includes("[x]")){const i=r.type[0].code;o=n.replace("[x]",tn(i))}t===void 0?delete e[o]:e[o]=t}function Ag(e,t,n,r){const o=t.split(".");let i=e,a;for(let l=0;l<o.length;l++){let c=o[l];if(c.includes("[x]")){const d=r[o.slice(0,l+1).join(".")].type[0].code;c=c.replace("[x]",tn(d))}if(l===o.length-1){Array.isArray(i)?a=i.map(u=>u[c]):a=i[c];continue}if(Array.isArray(i))i=i.map(u=>u[c]);else if(Rn(i)){if(i[c]===void 0)return;i=i[c]}else return}return a}function Sf(e,t,n,r){if(!(n.fixed||n.pattern))return e;if(Array.isArray(e))return e.map(l=>Sf(l,t,n,r));e==null&&(e=Object.create(null));const o=e,i=t.split(".");let a=o;for(let l=0;l<i.length;l++){let c=i[l];if(c.includes("[x]")){const d=r[i.slice(0,l+1).join(".")].type[0].code;c=c.replace("[x]",tn(d))}if(l===i.length-1){const u=Array.isArray(a)?a:[a];for(const d of u)n.fixed?d[c]??(d[c]=n.fixed.value):n.pattern&&(d[c]=Ak(d[c],n.pattern.value))}else{if(!(c in a)){const u=i.slice(0,l+1).join(".");a[c]=r[u].isArray?[Object.create(null)]:Object.create(null)}a=a[c]}}return o}function Ak(e,t){if(Array.isArray(t)&&(Array.isArray(e)||e===void 0))return((e==null?void 0:e.length)??0)>0?e:Kr(t);if(Rn(t)&&(Rn(e)&&!Array.isArray(e)||e===void 0)){const n=Kr(e)??Object.create(null);for(const r of Object.keys(t))n[r]=Ak(n[r],t[r]);return n}return e}const Nk=p.createContext(void 0);function Vh(){return p.useContext(Nk)}function le(){return Vh().medplum}function Wh(){return Vh().navigate}function Hh(){return Vh().profile}const Tw=["change","storageInitialized","storageInitFailed","profileRefreshing","profileRefreshed"];function K8(e){const t=e.medplum,n=e.navigate??Y8,[r,o]=p.useState({profile:t.getProfile(),loading:t.isLoading()});p.useEffect(()=>{function a(){o(l=>({...l,profile:t.getProfile(),loading:t.isLoading()}))}for(const l of Tw)t.addEventListener(l,a);return()=>{for(const l of Tw)t.removeEventListener(l,a)}},[t]);const i=p.useMemo(()=>({...r,medplum:t,navigate:n}),[r,t,n]);return s.jsx(Nk.Provider,{value:i,children:e.children})}function Y8(e){window.location.assign(e)}const Pw=new Map,Mk=e=>p.useMemo(()=>{if(!e)return;const t=e.split("?")[0];if(!t)return e;let n;try{n=new URLSearchParams(new URL(e).search)}catch{return e}if(!n.has("Key-Pair-Id")||!n.has("Signature"))return e;const r=n.get("Expires");if(!r||r.length>13)return e;const o=Pw.get(t);if(o){const a=new URLSearchParams(new URL(o).search).get("Expires");if(a&&parseInt(a,10)*1e3-5e3>Date.now())return o}return Pw.set(t,e),e},[e]);function St(e,t){const n=le(),[r,o]=p.useState(()=>kw(n,e)),i=p.useCallback(a=>{Ui(a,r)||o(a)},[r]);return p.useEffect(()=>{let a=!0;const l=kw(n,e);return!l&&Xs(e)?n.readReference(e).then(c=>{a&&i(c)}).catch(c=>{a&&(i(void 0),t&&t(ft(c)))}):i(l),()=>a=!1},[n,e,i,t]),r}function kw(e,t){if(t){if(ri(t))return t;if(Xs(t))return e.getCachedReference(t)}}function X8(e,t){return Ok("searchOne",e,t)}function al(e,t){return Ok("searchResources",e,t)}function Ok(e,t,n){const r=le(),[o,i]=p.useState(),[a,l]=p.useState(!0),[c,u]=p.useState(),[d,f]=p.useState();return p.useEffect(()=>{const h=r.fhirSearchUrl(t,n).toString();h!==o&&(i(h),r[e](t,n).then(m=>{l(!1),u(m),f(G$)}).catch(m=>{l(!1),u(void 0),f(ft(m))}))},[r,e,t,n,o]),[c,a,d]}function J8(e){const t=e.value;return t?s.jsx(s.Fragment,{children:I6(t)}):null}const Lk=["meta","implicitRules","contained","extension","modifierExtension"],$k=["language","text"],wt=p.createContext({path:"",profileUrl:void 0,elements:Object.create(null),elementsByPath:Object.create(null),getExtendedProps:()=>({readonly:!1,hidden:!1}),accessPolicyResource:void 0,debugMode:!1,isDefaultContext:!0});wt.displayName="ElementsContext";const Kx=["extension","modifierExtension"],Z8=["id",...Lk].filter(e=>!Kx.includes(e));function ez(e){return Object.entries(e).filter(([n,r])=>{var o;return!$t(r.type)||r.max===0||r.path.toLowerCase().endsWith("extension.url")&&r.fixed||Kx.includes(n)&&!$t((o=r.slicing)==null?void 0:o.slices)||Z8.includes(n)?!1:!($k.includes(n)&&r.path.split(".").length===2||n.includes("."))})}function Rw(e,t){return e.line&&e.line.length>t?e.line[t]:""}function _w(e,t,n){const r=e.line||[];for(;r.length<=t;)r.push("");return r[t]=n,{...e,line:r}}function tz(e){const[t,n]=p.useState(e.defaultValue||{}),r=p.useRef();r.current=t;const{getExtendedProps:o}=p.useContext(wt),[i,a,l,c,u,d,f]=p.useMemo(()=>["use","type","line1","line2","city","state","postalCode"].map(x=>o(e.path+"."+x)),[o,e.path]);function h(x){n(x),e.onChange&&e.onChange(x)}function m(x){h({...r.current,use:x})}function g(x){h({...r.current,type:x})}function v(x){h(_w(r.current||{},0,x))}function S(x){h(_w(r.current||{},1,x))}function b(x){h({...r.current,city:x})}function w(x){h({...r.current,state:x})}function y(x){h({...r.current,postalCode:x})}return s.jsxs(te,{gap:"xs",wrap:"nowrap",grow:!0,children:[s.jsx(It,{disabled:e.disabled||(i==null?void 0:i.readonly),"data-testid":"address-use",defaultValue:t.use,onChange:x=>m(x.currentTarget.value),data:["","home","work","temp","old","billing"]}),s.jsx(It,{disabled:e.disabled||(a==null?void 0:a.readonly),"data-testid":"address-type",defaultValue:t.type,onChange:x=>g(x.currentTarget.value),data:["","postal","physical","both"]}),s.jsx(ye,{disabled:e.disabled||(l==null?void 0:l.readonly),placeholder:"Line 1",defaultValue:Rw(t,0),onChange:x=>v(x.currentTarget.value)}),s.jsx(ye,{disabled:e.disabled||(c==null?void 0:c.readonly),placeholder:"Line 2",defaultValue:Rw(t,1),onChange:x=>S(x.currentTarget.value)}),s.jsx(ye,{disabled:e.disabled||(u==null?void 0:u.readonly),placeholder:"City",defaultValue:t.city,onChange:x=>b(x.currentTarget.value)}),s.jsx(ye,{disabled:e.disabled||(d==null?void 0:d.readonly),placeholder:"State",defaultValue:t.state,onChange:x=>w(x.currentTarget.value)}),s.jsx(ye,{disabled:e.disabled||(f==null?void 0:f.readonly),placeholder:"Postal Code",defaultValue:t.postalCode,onChange:x=>y(x.currentTarget.value)})]})}function nz(e){const t=Hh(),[n,r]=p.useState(e.defaultValue||{});function o(i){const a=i?{text:i,authorReference:t&&Tt(t),time:new Date().toISOString()}:{};r(a),e.onChange&&e.onChange(a)}return s.jsx(ye,{disabled:e.disabled,name:e.name,placeholder:"Annotation text",defaultValue:n.text,onChange:i=>o(i.currentTarget.value)})}/**
|
|
142
142
|
* @license @tabler/icons-react v3.17.0 - MIT
|
|
143
143
|
*
|
|
144
144
|
* This source code is licensed under the MIT license.
|
|
@@ -569,7 +569,7 @@ Error generating stack: `+i.message+`
|
|
|
569
569
|
* LICENSE.md file in the root directory of this source tree.
|
|
570
570
|
*
|
|
571
571
|
* @license MIT
|
|
572
|
-
*/function If(){return If=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},If.apply(this,arguments)}function Hg(e){return e===void 0&&(e=""),new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(o=>[n,o]):[[n,r]])},[]))}function ZG(e,t){let n=Hg(e);return t&&t.forEach((r,o)=>{n.has(o)||t.getAll(o).forEach(i=>{n.append(o,i)})}),n}const eQ="6";try{window.__reactRouterVersion=eQ}catch{}function tQ(e,t){return fG({basename:void 0,future:If({},void 0,{v7_prependBasename:!0}),history:Oq({window:void 0}),hydrationData:nQ(),routes:e,mapRouteProperties:JG,unstable_dataStrategy:void 0,unstable_patchRoutesOnNavigation:void 0,window:void 0}).initialize()}function nQ(){var e;let t=(e=window)==null?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=If({},t,{errors:rQ(t.errors)})),t}function rQ(e){if(!e)return null;let t=Object.entries(e),n={};for(let[r,o]of t)if(o&&o.__type==="RouteErrorResponse")n[r]=new _f(o.status,o.statusText,o.data,o.internal===!0);else if(o&&o.__type==="Error"){if(o.__subType){let i=window[o.__subType];if(typeof i=="function")try{let a=new i(o.message);a.stack="",n[r]=a}catch{}}if(n[r]==null){let i=new Error(o.message);i.stack="",n[r]=i}}else n[r]=o;return n}const oQ=p.createContext({isTransitioning:!1}),iQ=p.createContext(new Map),sQ="startTransition",vS=QS[sQ],aQ="flushSync",yS=ON[aQ];function lQ(e){vS?vS(e):e()}function Hl(e){yS?yS(e):e()}class cQ{constructor(){this.status="pending",this.promise=new Promise((t,n)=>{this.resolve=r=>{this.status==="pending"&&(this.status="resolved",t(r))},this.reject=r=>{this.status==="pending"&&(this.status="rejected",n(r))}})}}function uQ(e){let{fallbackElement:t,router:n,future:r}=e,[o,i]=p.useState(n.state),[a,l]=p.useState(),[c,u]=p.useState({isTransitioning:!1}),[d,f]=p.useState(),[h,m]=p.useState(),[g,v]=p.useState(),S=p.useRef(new Map),{v7_startTransition:b}=r||{},w=p.useCallback(j=>{b?lQ(j):j()},[b]),y=p.useCallback((j,R)=>{let{deletedFetchers:k,unstable_flushSync:I,unstable_viewTransitionOpts:O}=R;k.forEach(L=>S.current.delete(L)),j.fetchers.forEach((L,B)=>{L.data!==void 0&&S.current.set(B,L.data)});let F=n.window==null||n.window.document==null||typeof n.window.document.startViewTransition!="function";if(!O||F){I?Hl(()=>i(j)):w(()=>i(j));return}if(I){Hl(()=>{h&&(d&&d.resolve(),h.skipTransition()),u({isTransitioning:!0,flushSync:!0,currentLocation:O.currentLocation,nextLocation:O.nextLocation})});let L=n.window.document.startViewTransition(()=>{Hl(()=>i(j))});L.finished.finally(()=>{Hl(()=>{f(void 0),m(void 0),l(void 0),u({isTransitioning:!1})})}),Hl(()=>m(L));return}h?(d&&d.resolve(),h.skipTransition(),v({state:j,currentLocation:O.currentLocation,nextLocation:O.nextLocation})):(l(j),u({isTransitioning:!0,flushSync:!1,currentLocation:O.currentLocation,nextLocation:O.nextLocation}))},[n.window,h,d,S,w]);p.useLayoutEffect(()=>n.subscribe(y),[n,y]),p.useEffect(()=>{c.isTransitioning&&!c.flushSync&&f(new cQ)},[c]),p.useEffect(()=>{if(d&&a&&n.window){let j=a,R=d.promise,k=n.window.document.startViewTransition(async()=>{w(()=>i(j)),await R});k.finished.finally(()=>{f(void 0),m(void 0),l(void 0),u({isTransitioning:!1})}),m(k)}},[w,a,d,n.window]),p.useEffect(()=>{d&&a&&o.location.key===a.location.key&&d.resolve()},[d,h,o.location,a]),p.useEffect(()=>{!c.isTransitioning&&g&&(l(g.state),u({isTransitioning:!0,flushSync:!1,currentLocation:g.currentLocation,nextLocation:g.nextLocation}),v(void 0))},[c.isTransitioning,g]),p.useEffect(()=>{},[]);let x=p.useMemo(()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:j=>n.navigate(j),push:(j,R,k)=>n.navigate(j,{state:R,preventScrollReset:k==null?void 0:k.preventScrollReset}),replace:(j,R,k)=>n.navigate(j,{replace:!0,state:R,preventScrollReset:k==null?void 0:k.preventScrollReset})}),[n]),C=n.basename||"/",E=p.useMemo(()=>({router:n,navigator:x,static:!1,basename:C}),[n,x,C]),T=p.useMemo(()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath}),[n.future.v7_relativeSplatPath]);return p.createElement(p.Fragment,null,p.createElement(Jh.Provider,{value:E},p.createElement(v2.Provider,{value:o},p.createElement(iQ.Provider,{value:S.current},p.createElement(oQ.Provider,{value:c},p.createElement(YG,{basename:C,location:o.location,navigationType:o.historyAction,navigator:x,future:T},o.initialized||n.future.v7_partialHydration?p.createElement(dQ,{routes:n.routes,future:n.future,state:o}):t))))),null)}const dQ=p.memo(fQ);function fQ(e){let{routes:t,future:n,state:r}=e;return b2(t,void 0,r,n)}var xS;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(xS||(xS={}));var bS;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(bS||(bS={}));function _0(e){let t=p.useRef(Hg(e)),n=p.useRef(!1),r=ii(),o=p.useMemo(()=>ZG(r.search,n.current?null:t.current),[r.search]),i=Gt(),a=p.useCallback((l,c)=>{const u=Hg(typeof l=="function"?l(o):l);n.current=!0,i("?"+u,c)},[i,o]);return[o,a]}const hQ=new Map([["aac","audio/aac"],["abw","application/x-abiword"],["arc","application/x-freearc"],["avif","image/avif"],["avi","video/x-msvideo"],["azw","application/vnd.amazon.ebook"],["bin","application/octet-stream"],["bmp","image/bmp"],["bz","application/x-bzip"],["bz2","application/x-bzip2"],["cda","application/x-cdf"],["csh","application/x-csh"],["css","text/css"],["csv","text/csv"],["doc","application/msword"],["docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],["eot","application/vnd.ms-fontobject"],["epub","application/epub+zip"],["gz","application/gzip"],["gif","image/gif"],["heic","image/heic"],["heif","image/heif"],["htm","text/html"],["html","text/html"],["ico","image/vnd.microsoft.icon"],["ics","text/calendar"],["jar","application/java-archive"],["jpeg","image/jpeg"],["jpg","image/jpeg"],["js","text/javascript"],["json","application/json"],["jsonld","application/ld+json"],["mid","audio/midi"],["midi","audio/midi"],["mjs","text/javascript"],["mp3","audio/mpeg"],["mp4","video/mp4"],["mpeg","video/mpeg"],["mpkg","application/vnd.apple.installer+xml"],["odp","application/vnd.oasis.opendocument.presentation"],["ods","application/vnd.oasis.opendocument.spreadsheet"],["odt","application/vnd.oasis.opendocument.text"],["oga","audio/ogg"],["ogv","video/ogg"],["ogx","application/ogg"],["opus","audio/opus"],["otf","font/otf"],["png","image/png"],["pdf","application/pdf"],["php","application/x-httpd-php"],["ppt","application/vnd.ms-powerpoint"],["pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],["rar","application/vnd.rar"],["rtf","application/rtf"],["sh","application/x-sh"],["svg","image/svg+xml"],["swf","application/x-shockwave-flash"],["tar","application/x-tar"],["tif","image/tiff"],["tiff","image/tiff"],["ts","video/mp2t"],["ttf","font/ttf"],["txt","text/plain"],["vsd","application/vnd.visio"],["wav","audio/wav"],["weba","audio/webm"],["webm","video/webm"],["webp","image/webp"],["woff","font/woff"],["woff2","font/woff2"],["xhtml","application/xhtml+xml"],["xls","application/vnd.ms-excel"],["xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],["xml","application/xml"],["xul","application/vnd.mozilla.xul+xml"],["zip","application/zip"],["7z","application/x-7z-compressed"],["mkv","video/x-matroska"],["mov","video/quicktime"],["msg","application/vnd.ms-outlook"]]);function Tu(e,t){const n=pQ(e);if(typeof n.path!="string"){const{webkitRelativePath:r}=e;Object.defineProperty(n,"path",{value:typeof t=="string"?t:typeof r=="string"&&r.length>0?r:e.name,writable:!1,configurable:!1,enumerable:!0})}return n}function pQ(e){const{name:t}=e;if(t&&t.lastIndexOf(".")!==-1&&!e.type){const r=t.split(".").pop().toLowerCase(),o=hQ.get(r);o&&Object.defineProperty(e,"type",{value:o,writable:!1,configurable:!1,enumerable:!0})}return e}var kl=(e,t,n)=>new Promise((r,o)=>{var i=c=>{try{l(n.next(c))}catch(u){o(u)}},a=c=>{try{l(n.throw(c))}catch(u){o(u)}},l=c=>c.done?r(c.value):Promise.resolve(c.value).then(i,a);l((n=n.apply(e,t)).next())});const mQ=[".DS_Store","Thumbs.db"];function gQ(e){return kl(this,null,function*(){return Af(e)&&vQ(e.dataTransfer)?wQ(e.dataTransfer,e.type):yQ(e)?xQ(e):Array.isArray(e)&&e.every(t=>"getFile"in t&&typeof t.getFile=="function")?bQ(e):[]})}function vQ(e){return Af(e)}function yQ(e){return Af(e)&&Af(e.target)}function Af(e){return typeof e=="object"&&e!==null}function xQ(e){return qg(e.target.files).map(t=>Tu(t))}function bQ(e){return kl(this,null,function*(){return(yield Promise.all(e.map(n=>n.getFile()))).map(n=>Tu(n))})}function wQ(e,t){return kl(this,null,function*(){if(e.items){const n=qg(e.items).filter(o=>o.kind==="file");if(t!=="drop")return n;const r=yield Promise.all(n.map(SQ));return wS(j2(r))}return wS(qg(e.files).map(n=>Tu(n)))})}function wS(e){return e.filter(t=>mQ.indexOf(t.name)===-1)}function qg(e){if(e===null)return[];const t=[];for(let n=0;n<e.length;n++){const r=e[n];t.push(r)}return t}function SQ(e){if(typeof e.webkitGetAsEntry!="function")return SS(e);const t=e.webkitGetAsEntry();return t&&t.isDirectory?C2(t):SS(e)}function j2(e){return e.reduce((t,n)=>[...t,...Array.isArray(n)?j2(n):[n]],[])}function SS(e){const t=e.getAsFile();if(!t)return Promise.reject(`${e} is not a File`);const n=Tu(t);return Promise.resolve(n)}function jQ(e){return kl(this,null,function*(){return e.isDirectory?C2(e):CQ(e)})}function C2(e){const t=e.createReader();return new Promise((n,r)=>{const o=[];function i(){t.readEntries(a=>kl(this,null,function*(){if(a.length){const l=Promise.all(a.map(jQ));o.push(l),i()}else try{const l=yield Promise.all(o);n(l)}catch(l){r(l)}}),a=>{r(a)})}i()})}function CQ(e){return kl(this,null,function*(){return new Promise((t,n)=>{e.file(r=>{const o=Tu(r,e.fullPath);t(o)},r=>{n(r)})})})}function EQ(e,t){if(e&&t){const n=Array.isArray(t)?t:t.split(","),r=e.name||"",o=(e.type||"").toLowerCase(),i=o.replace(/\/.*$/,"");return n.some(a=>{const l=a.trim().toLowerCase();return l.charAt(0)==="."?r.toLowerCase().endsWith(l):l.endsWith("/*")?i===l.replace(/\/.*$/,""):o===l})}return!0}var TQ=Object.defineProperty,PQ=Object.defineProperties,kQ=Object.getOwnPropertyDescriptors,jS=Object.getOwnPropertySymbols,RQ=Object.prototype.hasOwnProperty,_Q=Object.prototype.propertyIsEnumerable,CS=(e,t,n)=>t in e?TQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,DQ=(e,t)=>{for(var n in t||(t={}))RQ.call(t,n)&&CS(e,n,t[n]);if(jS)for(var n of jS(t))_Q.call(t,n)&&CS(e,n,t[n]);return e},IQ=(e,t)=>PQ(e,kQ(t));const AQ="file-invalid-type",NQ="file-too-large",MQ="file-too-small",OQ="too-many-files",LQ=e=>{e=Array.isArray(e)&&e.length===1?e[0]:e;const t=Array.isArray(e)?`one of ${e.join(", ")}`:e;return{code:AQ,message:`File type must be ${t}`}},ES=e=>({code:NQ,message:`File is larger than ${e} ${e===1?"byte":"bytes"}`}),TS=e=>({code:MQ,message:`File is smaller than ${e} ${e===1?"byte":"bytes"}`}),$Q={code:OQ,message:"Too many files"};function E2(e,t){const n=e.type==="application/x-moz-file"||EQ(e,t);return[n,n?null:LQ(t)]}function T2(e,t,n){if(fs(e.size))if(fs(t)&&fs(n)){if(e.size>n)return[!1,ES(n)];if(e.size<t)return[!1,TS(t)]}else{if(fs(t)&&e.size<t)return[!1,TS(t)];if(fs(n)&&e.size>n)return[!1,ES(n)]}return[!0,null]}function fs(e){return e!=null}function FQ({files:e,accept:t,minSize:n,maxSize:r,multiple:o,maxFiles:i,validator:a}){return!o&&e.length>1||o&&i>=1&&e.length>i?!1:e.every(l=>{const[c]=E2(l,t),[u]=T2(l,n,r),d=a?a(l):null;return c&&u&&!d})}function Nf(e){return typeof e.isPropagationStopped=="function"?e.isPropagationStopped():typeof e.cancelBubble<"u"?e.cancelBubble:!1}function md(e){return e.dataTransfer?Array.prototype.some.call(e.dataTransfer.types,t=>t==="Files"||t==="application/x-moz-file"):!!e.target&&!!e.target.files}function PS(e){e.preventDefault()}function zQ(e){return e.indexOf("MSIE")!==-1||e.indexOf("Trident/")!==-1}function BQ(e){return e.indexOf("Edge/")!==-1}function UQ(e=window.navigator.userAgent){return zQ(e)||BQ(e)}function io(...e){return(t,...n)=>e.some(r=>(!Nf(t)&&r&&r(t,...n),Nf(t)))}function VQ(){return"showOpenFilePicker"in window}function WQ(e){return fs(e)?[{description:"Files",accept:Object.entries(e).filter(([n,r])=>{let o=!0;return P2(n)||(console.warn(`Skipped "${n}" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.`),o=!1),(!Array.isArray(r)||!r.every(k2))&&(console.warn(`Skipped "${n}" because an invalid file extension was provided.`),o=!1),o}).reduce((n,[r,o])=>IQ(DQ({},n),{[r]:o}),{})}]:e}function HQ(e){if(fs(e))return Object.entries(e).reduce((t,[n,r])=>[...t,n,...r],[]).filter(t=>P2(t)||k2(t)).join(",")}function qQ(e){return e instanceof DOMException&&(e.name==="AbortError"||e.code===e.ABORT_ERR)}function GQ(e){return e instanceof DOMException&&(e.name==="SecurityError"||e.code===e.SECURITY_ERR)}function P2(e){return e==="audio/*"||e==="video/*"||e==="image/*"||e==="text/*"||/\w+\/[-+.\w]+/g.test(e)}function k2(e){return/^.*\.[\w]+$/.test(e)}var QQ=Object.defineProperty,KQ=Object.defineProperties,YQ=Object.getOwnPropertyDescriptors,Mf=Object.getOwnPropertySymbols,R2=Object.prototype.hasOwnProperty,_2=Object.prototype.propertyIsEnumerable,kS=(e,t,n)=>t in e?QQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,On=(e,t)=>{for(var n in t||(t={}))R2.call(t,n)&&kS(e,n,t[n]);if(Mf)for(var n of Mf(t))_2.call(t,n)&&kS(e,n,t[n]);return e},bi=(e,t)=>KQ(e,YQ(t)),Of=(e,t)=>{var n={};for(var r in e)R2.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Mf)for(var r of Mf(e))t.indexOf(r)<0&&_2.call(e,r)&&(n[r]=e[r]);return n};const D0=p.forwardRef((e,t)=>{var n=e,{children:r}=n,o=Of(n,["children"]);const i=I2(o),{open:a}=i,l=Of(i,["open"]);return p.useImperativeHandle(t,()=>({open:a}),[a]),fn.createElement(p.Fragment,null,r(bi(On({},l),{open:a})))});D0.displayName="Dropzone";const D2={disabled:!1,getFilesFromEvent:gQ,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!0,autoFocus:!1};D0.defaultProps=D2;D0.propTypes={children:vt.func,accept:vt.objectOf(vt.arrayOf(vt.string)),multiple:vt.bool,preventDropOnDocument:vt.bool,noClick:vt.bool,noKeyboard:vt.bool,noDrag:vt.bool,noDragEventsBubbling:vt.bool,minSize:vt.number,maxSize:vt.number,maxFiles:vt.number,disabled:vt.bool,getFilesFromEvent:vt.func,onFileDialogCancel:vt.func,onFileDialogOpen:vt.func,useFsAccessApi:vt.bool,autoFocus:vt.bool,onDragEnter:vt.func,onDragLeave:vt.func,onDragOver:vt.func,onDrop:vt.func,onDropAccepted:vt.func,onDropRejected:vt.func,onError:vt.func,validator:vt.func};const Gg={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function I2(e={}){const{accept:t,disabled:n,getFilesFromEvent:r,maxSize:o,minSize:i,multiple:a,maxFiles:l,onDragEnter:c,onDragLeave:u,onDragOver:d,onDrop:f,onDropAccepted:h,onDropRejected:m,onFileDialogCancel:g,onFileDialogOpen:v,useFsAccessApi:S,autoFocus:b,preventDropOnDocument:w,noClick:y,noKeyboard:x,noDrag:C,noDragEventsBubbling:E,onError:T,validator:j}=On(On({},D2),e),R=p.useMemo(()=>HQ(t),[t]),k=p.useMemo(()=>WQ(t),[t]),I=p.useMemo(()=>typeof v=="function"?v:RS,[v]),O=p.useMemo(()=>typeof g=="function"?g:RS,[g]),F=p.useRef(null),L=p.useRef(null),[B,D]=p.useReducer(XQ,Gg),{isFocused:_,isFileDialogActive:P}=B,N=p.useRef(typeof window<"u"&&window.isSecureContext&&S&&VQ()),$=()=>{!N.current&&P&&setTimeout(()=>{if(L.current){const{files:J}=L.current;J.length||(D({type:"closeDialog"}),O())}},300)};p.useEffect(()=>(window.addEventListener("focus",$,!1),()=>{window.removeEventListener("focus",$,!1)}),[L,P,O,N]);const H=p.useRef([]),X=J=>{F.current&&F.current.contains(J.target)||(J.preventDefault(),H.current=[])};p.useEffect(()=>(w&&(document.addEventListener("dragover",PS,!1),document.addEventListener("drop",X,!1)),()=>{w&&(document.removeEventListener("dragover",PS),document.removeEventListener("drop",X))}),[F,w]),p.useEffect(()=>(!n&&b&&F.current&&F.current.focus(),()=>{}),[F,b,n]);const ce=p.useCallback(J=>{T?T(J):console.error(J)},[T]),Ie=p.useCallback(J=>{J.preventDefault(),J.persist(),oe(J),H.current=[...H.current,J.target],md(J)&&Promise.resolve(r(J)).then(ie=>{if(Nf(J)&&!E)return;const G=ie.length,Ce=G>0&&FQ({files:ie,accept:R,minSize:i,maxSize:o,multiple:a,maxFiles:l,validator:j}),He=G>0&&!Ce;D({isDragAccept:Ce,isDragReject:He,isDragActive:!0,type:"setDraggedFiles"}),c&&c(J)}).catch(ie=>ce(ie))},[r,c,ce,E,R,i,o,a,l,j]),ue=p.useCallback(J=>{J.preventDefault(),J.persist(),oe(J);const ie=md(J);if(ie&&J.dataTransfer)try{J.dataTransfer.dropEffect="copy"}catch{}return ie&&d&&d(J),!1},[d,E]),xe=p.useCallback(J=>{J.preventDefault(),J.persist(),oe(J);const ie=H.current.filter(Ce=>F.current&&F.current.contains(Ce)),G=ie.indexOf(J.target);G!==-1&&ie.splice(G,1),H.current=ie,!(ie.length>0)&&(D({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),md(J)&&u&&u(J))},[F,u,E]),_e=p.useCallback((J,ie)=>{const G=[],Ce=[];J.forEach(He=>{const[lt,gt]=E2(He,R),[mn,Xt]=T2(He,i,o),Bt=j?j(He):null;if(lt&&mn&&!Bt)G.push(He);else{let an=[gt,Xt];Bt&&(an=an.concat(Bt)),Ce.push({file:He,errors:an.filter(si=>si)})}}),(!a&&G.length>1||a&&l>=1&&G.length>l)&&(G.forEach(He=>{Ce.push({file:He,errors:[$Q]})}),G.splice(0)),D({acceptedFiles:G,fileRejections:Ce,type:"setFiles"}),f&&f(G,Ce,ie),Ce.length>0&&m&&m(Ce,ie),G.length>0&&h&&h(G,ie)},[D,a,R,i,o,l,f,h,m,j]),de=p.useCallback(J=>{J.preventDefault(),J.persist(),oe(J),H.current=[],md(J)&&Promise.resolve(r(J)).then(ie=>{Nf(J)&&!E||_e(ie,J)}).catch(ie=>ce(ie)),D({type:"reset"})},[r,_e,ce,E]),Oe=p.useCallback(()=>{if(N.current){D({type:"openDialog"}),I();const J={multiple:a,types:k};window.showOpenFilePicker(J).then(ie=>r(ie)).then(ie=>{_e(ie,null),D({type:"closeDialog"})}).catch(ie=>{qQ(ie)?(O(ie),D({type:"closeDialog"})):GQ(ie)?(N.current=!1,L.current?(L.current.value=null,L.current.click()):ce(new Error("Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no <input> was provided."))):ce(ie)});return}L.current&&(D({type:"openDialog"}),I(),L.current.value=null,L.current.click())},[D,I,O,S,_e,ce,k,a]),Ye=p.useCallback(J=>{!F.current||!F.current.isEqualNode(J.target)||(J.key===" "||J.key==="Enter"||J.keyCode===32||J.keyCode===13)&&(J.preventDefault(),Oe())},[F,Oe]),jt=p.useCallback(()=>{D({type:"focus"})},[]),mt=p.useCallback(()=>{D({type:"blur"})},[]),at=p.useCallback(()=>{y||(UQ()?setTimeout(Oe,0):Oe())},[y,Oe]),Re=J=>n?null:J,et=J=>x?null:Re(J),ht=J=>C?null:Re(J),oe=J=>{E&&J.stopPropagation()},Q=p.useMemo(()=>(J={})=>{var ie=J,{refKey:G="ref",role:Ce,onKeyDown:He,onFocus:lt,onBlur:gt,onClick:mn,onDragEnter:Xt,onDragOver:Bt,onDragLeave:an,onDrop:si}=ie,ai=Of(ie,["refKey","role","onKeyDown","onFocus","onBlur","onClick","onDragEnter","onDragOver","onDragLeave","onDrop"]);return On(On({onKeyDown:et(io(He,Ye)),onFocus:et(io(lt,jt)),onBlur:et(io(gt,mt)),onClick:Re(io(mn,at)),onDragEnter:ht(io(Xt,Ie)),onDragOver:ht(io(Bt,ue)),onDragLeave:ht(io(an,xe)),onDrop:ht(io(si,de)),role:typeof Ce=="string"&&Ce!==""?Ce:"presentation",[G]:F},!n&&!x?{tabIndex:0}:{}),ai)},[F,Ye,jt,mt,at,Ie,ue,xe,de,x,C,n]),fe=p.useCallback(J=>{J.stopPropagation()},[]),Pe=p.useMemo(()=>(J={})=>{var ie=J,{refKey:G="ref",onChange:Ce,onClick:He}=ie,lt=Of(ie,["refKey","onChange","onClick"]);const gt={accept:R,multiple:a,type:"file",style:{display:"none"},onChange:Re(io(Ce,de)),onClick:Re(io(He,fe)),tabIndex:-1,[G]:L};return On(On({},gt),lt)},[L,t,a,de,n]);return bi(On({},B),{isFocused:_&&!n,getRootProps:Q,getInputProps:Pe,rootRef:F,inputRef:L,open:Re(Oe)})}function XQ(e,t){switch(t.type){case"focus":return bi(On({},e),{isFocused:!0});case"blur":return bi(On({},e),{isFocused:!1});case"openDialog":return bi(On({},Gg),{isFileDialogActive:!0});case"closeDialog":return bi(On({},e),{isFileDialogActive:!1});case"setDraggedFiles":return bi(On({},e),{isDragActive:t.isDragActive,isDragAccept:t.isDragAccept,isDragReject:t.isDragReject});case"setFiles":return bi(On({},e),{acceptedFiles:t.acceptedFiles,fileRejections:t.fileRejections});case"reset":return On({},Gg);default:return e}}function RS(){}const[JQ,ZQ]=Un("Dropzone component was not found in tree");function I0(e){const t=n=>{const{children:r,...o}=V(`Dropzone${G0(e)}`,{},n),i=ZQ(),a=Qo(r)?r:s.jsx("span",{children:r});return i[e]?p.cloneElement(a,o):null};return t.displayName=`@mantine/dropzone/${G0(e)}`,t}const eK=I0("accept"),tK=I0("reject"),nK=I0("idle");var Hc={root:"m_d46a4834",inner:"m_b85f7144",fullScreen:"m_96f6e9ad",dropzone:"m_7946116d"};const rK={loading:!1,multiple:!0,maxSize:1/0,autoFocus:!1,activateOnClick:!0,activateOnDrag:!0,dragEventsBubbling:!0,activateOnKeyboard:!0,useFsAccessApi:!0,variant:"light",rejectColor:"red"},oK=(e,{radius:t,variant:n,acceptColor:r,rejectColor:o})=>{const i=e.variantColorResolver({color:r||e.primaryColor,theme:e,variant:n}),a=e.variantColorResolver({color:o||"red",theme:e,variant:n});return{root:{"--dropzone-radius":it(t),"--dropzone-accept-color":i.color,"--dropzone-accept-bg":i.background,"--dropzone-reject-color":a.color,"--dropzone-reject-bg":a.background}}},es=Y((e,t)=>{const n=V("Dropzone",rK,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,radius:u,disabled:d,loading:f,multiple:h,maxSize:m,accept:g,children:v,onDropAny:S,onDrop:b,onReject:w,openRef:y,name:x,maxFiles:C,autoFocus:E,activateOnClick:T,activateOnDrag:j,dragEventsBubbling:R,activateOnKeyboard:k,onDragEnter:I,onDragLeave:O,onDragOver:F,onFileDialogCancel:L,onFileDialogOpen:B,preventDropOnDocument:D,useFsAccessApi:_,getFilesFromEvent:P,validator:N,rejectColor:$,acceptColor:H,enablePointerEvents:X,loaderProps:ce,inputProps:Ie,mod:ue,...xe}=n,_e=he({name:"Dropzone",classes:Hc,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:oK}),{getRootProps:de,getInputProps:Oe,isDragAccept:Ye,isDragReject:jt,open:mt}=I2({onDrop:S,onDropAccepted:b,onDropRejected:w,disabled:d||f,accept:Array.isArray(g)?g.reduce((Re,et)=>({...Re,[et]:[]}),{}):g,multiple:h,maxSize:m,maxFiles:C,autoFocus:E,noClick:!T,noDrag:!j,noDragEventsBubbling:!R,noKeyboard:!k,onDragEnter:I,onDragLeave:O,onDragOver:F,onFileDialogCancel:L,onFileDialogOpen:B,preventDropOnDocument:D,useFsAccessApi:_,validator:N,...P?{getFilesFromEvent:P}:null});Bf(y,mt);const at=!Ye&&!jt;return s.jsx(JQ,{value:{accept:Ye,reject:jt,idle:at},children:s.jsxs(q,{...de(),..._e("root",{focusable:!0}),...xe,mod:[{accept:Ye,reject:jt,idle:at,loading:f,"activate-on-click":T},ue],children:[s.jsx(ex,{visible:f,overlayProps:{radius:u},unstyled:l,loaderProps:ce}),s.jsx("input",{...Oe(Ie),name:x}),s.jsx("div",{..._e("inner"),ref:t,"data-enable-pointer-events":X||void 0,children:v})]})})});es.classes=Hc;es.displayName="@mantine/dropzone/Dropzone";es.Accept=eK;es.Idle=nK;es.Reject=tK;const iK={loading:!1,maxSize:1/0,activateOnClick:!1,activateOnDrag:!0,dragEventsBubbling:!0,activateOnKeyboard:!0,active:!0,zIndex:Jr("max"),withinPortal:!0},A0=Y((e,t)=>{const n=V("DropzoneFullScreen",iK,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,active:u,onDrop:d,onReject:f,zIndex:h,withinPortal:m,portalProps:g,...v}=n,S=he({name:"DropzoneFullScreen",classes:Hc,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,rootSelector:"fullScreen"}),{resolvedClassNames:b,resolvedStyles:w}=Gc({classNames:r,styles:a,props:n}),[y,x]=p.useState(0),[C,{open:E,close:T}]=av(!1),j=k=>{var I;(I=k.dataTransfer)!=null&&I.types.includes("Files")&&(x(O=>O+1),E())},R=()=>{x(k=>k-1)};return p.useEffect(()=>{y===0&&T()},[y]),p.useEffect(()=>{if(u)return document.addEventListener("dragenter",j,!1),document.addEventListener("dragleave",R,!1),()=>{document.removeEventListener("dragenter",j,!1),document.removeEventListener("dragleave",R,!1)}},[u]),s.jsx(Vs,{...g,withinPortal:m,children:s.jsx(q,{...S("fullScreen",{style:{opacity:C?1:0,pointerEvents:C?"all":"none",zIndex:h}}),ref:t,children:s.jsx(es,{...v,classNames:b,styles:w,unstyled:l,className:Hc.dropzone,onDrop:k=>{d==null||d(k),T(),x(0)},onReject:k=>{f==null||f(k),T(),x(0)}})})})});A0.classes=Hc;A0.displayName="@mantine/dropzone/DropzoneFullScreen";es.FullScreen=A0;const gd=es,sK='{"resourceType": "Bundle"}';function cm({id:e,title:t,message:n,color:r,icon:o,withCloseButton:i=!1,method:a="show",loading:l}){po[a]({id:e,loading:l,title:t,message:n,color:r,icon:o,withCloseButton:i,autoClose:!1})}function aK(){const e=At(),t=le(),[n,r]=p.useState({}),o=p.useCallback(async(l,c)=>{const u="batch-upload";cm({id:u,title:"Batch Upload in Progress",message:"Your batch data is being uploaded. This may take a moment...",method:"show",loading:!0});try{r({});let d=JSON.parse(l);d.type!=="batch"&&d.type!=="transaction"&&(d=Ek(d));const f=await t.executeBatch(d);r(h=>({...h,[c]:f})),cm({id:u,title:"Batch Upload Successful",message:"Your batch data was successfully uploaded.",color:"green",method:"update",icon:s.jsx(Js,{size:"1rem"}),withCloseButton:!0})}catch(d){cm({id:u,title:"Batch Upload Failed",color:"red",message:Ae(d),method:"update",icon:s.jsx(Ef,{size:"1rem"}),withCloseButton:!0})}},[t]),i=p.useCallback(async l=>{for(const c of l){const u=new FileReader;u.onload=d=>{var f;return o((f=d.target)==null?void 0:f.result,c.name)},u.readAsText(c)}},[o]),a=p.useCallback(async l=>{await o(l.input,"JSON Data")},[o]);return s.jsxs(Me,{children:[s.jsx(ve,{children:"Batch Create"}),s.jsxs("p",{children:["Use this page to create, read, or update multiple resources. For more details, see ",s.jsx("a",{href:"https://www.hl7.org/fhir/http.html#transaction",children:"FHIR Batch and Transaction"}),"."]}),Object.keys(n).length===0&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{children:"Input"}),s.jsxs(Je,{defaultValue:"upload",children:[s.jsxs(Je.List,{children:[s.jsx(Je.Tab,{value:"upload",children:"File Upload"}),s.jsx(Je.Tab,{value:"json",children:"JSON"})]}),s.jsx(Je.Panel,{value:"upload",pt:"xs",children:s.jsx(gd,{onDrop:i,accept:["application/json"],children:s.jsxs(te,{justify:"center",gap:"xl",style:{minHeight:220,pointerEvents:"none"},children:[s.jsx(gd.Accept,{children:s.jsx(Aw,{size:50,stroke:1.5,color:e.colors[e.primaryColor][5]})}),s.jsx(gd.Reject,{children:s.jsx(Ef,{size:50,stroke:1.5,color:e.colors.red[5]})}),s.jsx(gd.Idle,{children:s.jsx(Aw,{size:50,stroke:1.5})}),s.jsxs("div",{children:[s.jsx(me,{size:"xl",inline:!0,children:"Drag files here or click to select files"}),s.jsx(me,{size:"sm",color:"dimmed",inline:!0,mt:7,children:"Attach as many files as you like"})]})]})})}),s.jsx(Je.Panel,{value:"json",pt:"xs",children:s.jsxs(qe,{onSubmit:a,children:[s.jsx(vl,{"data-testid":"batch-input",name:"input",autosize:!0,minRows:20,defaultValue:sK,deserialize:JSON.parse}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(ae,{type:"submit",children:"Submit"})})]})})]})]}),Object.keys(n).length>0&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{children:"Output"}),s.jsxs(Je,{defaultValue:Object.keys(n)[0],children:[s.jsx(Je.List,{children:Object.keys(n).map(l=>s.jsx(Je.Tab,{value:l,children:l},l))}),Object.keys(n).map(l=>s.jsx(Je.Panel,{value:l,children:s.jsx("pre",{style:{border:"1px solid #888"},children:JSON.stringify(n[l],void 0,2)})},l))]}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(ae,{onClick:()=>r({}),children:"Start over"})})]})]})}function lK(){const{resourceType:e}=st(),n=(Object.fromEntries(new URLSearchParams(location.search).entries()).ids||"").split(",").filter(o=>!!o),[r]=al("Questionnaire",`subject-type=${e}`);return r?r.length===0?s.jsxs(Me,{children:[s.jsxs(ve,{children:["No apps for ",e]}),s.jsx(We,{to:`/${e}`,children:"Return to search page"})]}):s.jsx(Me,{children:s.jsx("div",{children:r.map(o=>s.jsxs("div",{children:[s.jsx("h3",{children:s.jsx(We,{to:`/forms/${o.id}?subject=`+n.map(i=>`${e}/${i}`).join(","),children:o.name})}),s.jsx("p",{children:o.description})]},o.id))})}):s.jsx(Yr,{})}function cK(){const e=le(),[t,n]=p.useState(),[r,o]=p.useState(!1);return s.jsx(Me,{width:450,children:s.jsxs(qe,{onSubmit:i=>{n(void 0),e.post("auth/changepassword",i).then(()=>o(!0)).catch(a=>n(ft(a)))},children:[s.jsxs(vn,{style:{flexDirection:"column"},children:[s.jsx(to,{size:32}),s.jsx(ve,{children:"Change password"})]}),!r&&s.jsxs($e,{gap:"xl",mt:"xl",children:[s.jsx(Hr,{name:"oldPassword",label:"Old password",required:!0,autoFocus:!0,error:Qe(t,"oldPassword")}),s.jsx(Hr,{name:"newPassword",label:"New password",required:!0,error:Qe(t,"newPassword")}),s.jsx(Hr,{name:"confirmPassword",label:"Confirm new password",required:!0,error:Qe(t,"confirmPassword")}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(ae,{type:"submit",children:"Change password"})})]}),r&&s.jsx("div",{"data-testid":"success",children:"Password changed successfully"})]})})}const Qg=["Form","JSON","Profiles"],uK=["Profiles"],um=Qg[0].toLowerCase();function dK(){const e=Gt(),t=At(),{resourceType:n}=st(),[r,o]=p.useState(()=>{const a=window.location.pathname.split("/").pop();return a&&Qg.map(l=>l.toLowerCase()).includes(a)?a:um});function i(a){a||(a=um),o(a),e(`/${n}/new/${a}`)}return s.jsxs(s.Fragment,{children:[s.jsxs(Xn,{children:[s.jsxs(me,{p:"md",fw:500,children:["New ",n]}),s.jsx(_r,{children:s.jsx(Je,{defaultValue:um,value:r,onChange:i,children:s.jsx(Je.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:Qg.map(a=>s.jsx(Je.Tab,{value:a.toLowerCase(),px:"md",children:uK.includes(a)?s.jsxs(te,{gap:"xs",wrap:"nowrap",children:[a,s.jsx(iu,{color:t.primaryColor,size:"sm",children:"Beta"})]}):a},a))})})})]}),s.jsx(R0,{})]})}function fK(){return s.jsx(Me,{children:s.jsxs($e,{children:[s.jsx(ve,{order:1,children:"Unexpected Error"}),s.jsx(me,{children:"We're sorry, something went wrong."}),s.jsxs(me,{children:["Please contact ",s.jsx(Ke,{href:"mailto:support@medplum.com",children:"support"})," for assistance."]})]})})}const hK="_root_1fbwr_1",pK="_entry_1fbwr_8",mK="_key_1fbwr_13",gK="_value_1fbwr_20",np={root:hK,entry:pK,key:mK,value:gK};function ze(e){return s.jsx(_r,{children:s.jsx("div",{className:np.root,children:e.children})})}ze.Entry=function(t){return s.jsx("div",{className:np.entry,children:t.children})};ze.Key=function(t){return s.jsx("div",{className:np.key,children:t.children})};ze.Value=function(t){return s.jsx("div",{className:np.value,children:t.children})};function vK(e){if(e.gender==="male")return"blue";if(e.gender==="female")return"pink"}function A2(e){var n,r;const t=St(e.patient);return t?s.jsxs(ze,{children:[s.jsx(Ji,{value:t,size:"lg",color:vK(t)}),s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Name"}),s.jsx(ze.Value,{children:s.jsx(We,{to:t,fw:500,children:t.name?s.jsx(t0,{value:t.name[0],options:{use:!1}}):"[blank]"})})]}),t.birthDate&&s.jsxs(s.Fragment,{children:[s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"DoB"}),s.jsx(ze.Value,{children:t.birthDate})]}),s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Age"}),s.jsx(ze.Value,{children:h6(t.birthDate)})]})]}),t.gender&&s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Gender"}),s.jsx(ze.Value,{children:t.gender})]}),t.address&&s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"State"}),s.jsx(ze.Value,{children:(n=t.address[0])==null?void 0:n.state})]}),(r=t.identifier)==null?void 0:r.map(o=>s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:o==null?void 0:o.system}),s.jsx(ze.Value,{children:o==null?void 0:o.value})]},`${o==null?void 0:o.system}-${o==null?void 0:o.value}`))]}):null}function N2(e){const t=St(e.resource);if(!t)return null;const n=[{key:"Type",value:s.jsx(We,{to:`/${t.resourceType}`,children:t.resourceType})}];function r(a,l){a&&l&&n.push({key:a,value:l})}function o(a){a&&r(a.system,a.value)}function i(a,l){Array.isArray(l)?l.forEach(c=>i(a,c)):typeof l=="string"?r(a,l):l&&(Array.isArray(l.coding)?r(a,l.coding.map(c=>c.display||c.code).join(", ")):r(a,l.text))}if("name"in t){const a=qo(t);a!==rt(t)&&r("Name",a)}return"category"in t&&i("Category",t.category),t.resourceType!=="Bot"&&"code"in t&&i("Code",t.code),"identifier"in t&&(Array.isArray(t.identifier)?t.identifier.forEach(o):o(t.identifier)),n.length===1&&n.push({key:"ID",value:t.id}),s.jsx(ze,{children:n.map(a=>s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:a.key}),s.jsx(ze.Value,{children:a.value})]},`${a.key}-${a.value}`))})}function N0(e){if(e.resourceType==="Patient")return e;if(e.resourceType==="DiagnosticReport"||e.resourceType==="Encounter"||e.resourceType==="Observation"||e.resourceType==="ServiceRequest")return e.subject}function yK(e){var t;if(e.resourceType==="Specimen")return e;if(e.resourceType==="Observation")return e.specimen;if(e.resourceType==="DiagnosticReport"||e.resourceType==="ServiceRequest")return(t=e.specimen)==null?void 0:t[0]}function Ld(e,t){return new Promise((n,r)=>{var i;const o=new MessageChannel;o.port1.onmessage=({data:a})=>{o.port1.close(),a.error?r(a.error):n(a.result)},(i=e.contentWindow)==null||i.postMessage(t,"https://codeeditor.medplum.com",[o.port2])})}function ts(e){var t;return il((t=e.getActiveLogin())==null?void 0:t.project)}function xK(e,t){const n=new Blob([e],{type:rn.JSON}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r;const i=new Date().toISOString().replace(/\D/g,"");o.download=`${i}.json`,document.body.appendChild(o),o.click(),URL.revokeObjectURL(r)}function bK(){const{id:e}=st(),t=ii(),r=Object.fromEntries(new URLSearchParams(t.search).entries()).subject,o=le(),[i,a]=p.useState(!0),[l,c]=p.useState(),[u,d]=p.useState(),[f,h]=p.useState(),[m,g]=p.useState(),[v,S]=p.useState();if(p.useEffect(()=>{const y={resourceType:"Bundle",type:"batch",entry:[{request:{method:"GET",url:`Questionnaire/${e}`}}]};if(r){const x=r.split(",").filter(C=>!!C);x.length===1&&y.entry.push({request:{method:"GET",url:x[0]}}),d(x)}o.executeBatch(y).then(x=>{var C,E,T,j,R,k,I,O;((T=(E=(C=x.entry)==null?void 0:C[0])==null?void 0:E.response)==null?void 0:T.status)!=="200"?g((k=(R=(j=x.entry)==null?void 0:j[0])==null?void 0:R.response)==null?void 0:k.outcome):(c((I=x.entry[0])==null?void 0:I.resource),h((O=x.entry[1])==null?void 0:O.resource)),a(!1)}).catch(x=>{g(x),a(!1)})},[o,e,r]),m)return s.jsx(Me,{children:s.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)})});if(v)return s.jsxs(Me,{children:[s.jsx(ve,{children:l==null?void 0:l.title}),s.jsx("p",{children:"Your response has been recorded."}),s.jsxs("ul",{children:[v.length===1&&s.jsx("li",{children:s.jsx(We,{to:v[0],children:"Review your answers"})}),v.length>1&&s.jsxs("li",{children:["Review your answers:",s.jsx("ul",{children:v.map(y=>s.jsx("li",{children:s.jsx(We,{to:y,children:rt(y)})},y.id))})]}),f&&s.jsx("li",{children:s.jsxs(We,{to:f,children:["Back to ",qo(f)]})}),s.jsx("li",{children:s.jsx(We,{to:"/",children:"Go back home"})})]})]});if(i||!l)return s.jsx(Yr,{});const b=f&&N0(f);return s.jsxs(s.Fragment,{children:[s.jsxs(Xn,{shadow:"xs",radius:0,children:[b&&s.jsx(A2,{patient:b}),f&&f.resourceType!=="Patient"&&s.jsx(N2,{resource:f}),s.jsx(q,{px:"xl",py:"md",children:s.jsxs(me,{children:[qo(l),u&&u.length>1&&s.jsxs(s.Fragment,{children:[" (for ",u.length," resources)"]})]})})]}),s.jsx(Me,{children:s.jsx(KR,{questionnaire:l,subject:f&&Tt(f),onSubmit:w})})]});async function w(y){const x=[];if(!u||u.length===0)x.push(await o.createResource(y));else for(const C of u)x.push(await o.createResource({...y,subject:{reference:C}}));S(x)}}const wK="_paper_unw9o_1",SK={paper:wK},jK={Bot:"/admin/bots/new",ClientApplication:"/admin/clients/new"};function M2(e,t){const n=e.resourceType||CK(t),r=e.fields??EK(n),o=e.filters??(e.resourceType?void 0:TK(n)),i=e.sortRules??PK(n),a=e.offset??0,l=e.count??zh;return{...e,resourceType:n,fields:r,filters:o,sortRules:i,offset:a,count:l}}function CK(e){var t,n;return localStorage.getItem("defaultResourceType")??((n=(t=e==null?void 0:e.option)==null?void 0:t.find(r=>r.id==="defaultResourceType"))==null?void 0:n.valueString)??"Patient"}function EK(e){const t=M0(e);if(t!=null&&t.fields)return t.fields;const n=["id","_lastUpdated"];switch(e){case"Patient":n.push("name","birthDate","gender");break;case"AccessPolicy":case"Bot":case"ClientApplication":case"Practitioner":case"Project":case"Organization":case"Questionnaire":case"UserConfiguration":n.push("name");break;case"CodeSystem":case"ValueSet":n.push("name","title","status");break;case"Condition":n.push("subject","code","clinicalStatus");break;case"Device":n.push("manufacturer","deviceName","patient");break;case"DeviceDefinition":n.push("manufacturer[x]","deviceName");break;case"DeviceRequest":n.push("code[x]","subject");break;case"DiagnosticReport":case"Observation":n.push("subject","code","status");break;case"Encounter":n.push("subject");break;case"ServiceRequest":n.push("subject","code","status","orderDetail");break;case"Subscription":n.push("criteria");break;case"User":n.push("email");break}return n}function TK(e){var t;return(t=M0(e))==null?void 0:t.filters}function PK(e){const t=M0(e);return t!=null&&t.sortRules?t.sortRules:[{code:"_lastUpdated",descending:!0}]}function M0(e){const t=localStorage.getItem(e+"-defaultSearch");return t?JSON.parse(t):void 0}function kK(e){localStorage.setItem("defaultResourceType",e.resourceType),localStorage.setItem(e.resourceType+"-defaultSearch",JSON.stringify(e))}async function RK(e,t){const n={resourceType:e.resourceType,count:1e3,offset:0,filters:e.filters},r=M2(n,t.getUserConfiguration()),o=await t.search(r.resourceType,Ia({...r,total:"accurate",fields:void 0}));return Ek(o)}function _S(){const e=le(),t=Gt(),n=ii(),[r,o]=p.useState();return p.useEffect(()=>{const i=bk(n.pathname+n.search),a=M2(i,e.getUserConfiguration());n.pathname===`/${a.resourceType}`&&n.search===Ia(a)?(kK(a),o(a)):t(`/${a.resourceType}${Ia(a)}`)},[e,t,n]),!(r!=null&&r.resourceType)||!r.fields||r.fields.length===0?s.jsx(Yr,{}):s.jsx(Xn,{shadow:"xs",m:"md",p:"xs",className:SK.paper,children:s.jsx(ju,{checkboxesEnabled:!0,search:r,onClick:i=>t(`/${i.resource.resourceType}/${i.resource.id}`),onAuxClick:i=>window.open(`/${i.resource.resourceType}/${i.resource.id}`,"_blank"),onChange:i=>{t(`/${r.resourceType}${Ia(i.definition)}`)},onNew:()=>{t(jK[r.resourceType]??`/${r.resourceType}/new`)},onExportCsv:()=>{const i=e.fhirUrl(r.resourceType,"$csv")+Ia(r);e.download(i).then(a=>{window.open(window.URL.createObjectURL(a),"_blank")}).catch(a=>ge({color:"red",message:Ae(a),autoClose:!1}))},onExportTransactionBundle:async()=>{RK(r,e).then(i=>xK(JSON.stringify(i,void 0,2))).catch(i=>ge({color:"red",message:Ae(i),autoClose:!1}))},onDelete:i=>{window.confirm("Are you sure you want to delete these resources?")&&(e.invalidateSearches(r.resourceType),e.executeBatch({resourceType:"Bundle",type:"batch",entry:i.map(a=>({request:{method:"DELETE",url:`${r.resourceType}/${a}`}}))}).then(()=>o({...r})).catch(a=>ge({color:"red",message:Ae(a),autoClose:!1})))},onBulk:i=>{t(`/bulk/${r.resourceType}?ids=${i.join(",")}`)}})})}function _K(){const e=le(),[t,n]=p.useState(),[r,o]=p.useState(void 0);p.useEffect(()=>{e.get("auth/mfa/status").then(l=>{n(l.enrollQrCode),o(l.enrolled)}).catch(l=>ge({color:"red",message:Ae(l),autoClose:!1}))},[e]);const i=p.useCallback(l=>{e.post("auth/mfa/enroll",l).then(()=>{o(!0),ge({color:"green",message:"Success"})}).catch(c=>ge({color:"red",message:Ae(c),autoClose:!1}))},[e]),a=p.useCallback(()=>{e.post("auth/mfa/disable",{}).catch(console.log)},[e]);return r===void 0?null:r?s.jsx(Me,{children:s.jsxs(te,{children:[s.jsx(ve,{children:"MFA is enabled"}),s.jsx(ae,{onClick:a,children:"Disable MFA"})]})}):s.jsx(Me,{width:400,children:s.jsxs(qe,{onSubmit:i,children:[s.jsx(ve,{children:"Multi Factor Auth Setup"}),s.jsx(vn,{children:s.jsx("img",{src:t})}),s.jsx(ye,{name:"token",label:"Code"}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(ae,{type:"submit",children:"Enroll"})})]})})}const dm={BASE_URL:"/",DEV:!1,GOOGLE_CLIENT_ID:"__GOOGLE_CLIENT_ID__",MEDPLUM_BASE_URL:"__MEDPLUM_BASE_URL__",MEDPLUM_CLIENT_ID:"__MEDPLUM_CLIENT_ID__",MEDPLUM_REGISTER_ENABLED:"__MEDPLUM_REGISTER_ENABLED__",MEDPLUM_VERSION:"3.2.14-2f87100e5",MODE:"production",PROD:!0,RECAPTCHA_SITE_KEY:"__RECAPTCHA_SITE_KEY__",SSR:!1},Kg={baseUrl:"__MEDPLUM_BASE_URL__",clientId:"__MEDPLUM_CLIENT_ID__",googleClientId:"__GOOGLE_CLIENT_ID__",recaptchaSiteKey:"__RECAPTCHA_SITE_KEY__",registerEnabled:"__MEDPLUM_REGISTER_ENABLED__",awsTextractEnabled:dm==null?void 0:dm.MEDPLUM_AWS_TEXTRACT_ENABLED};function Pu(){return Kg}function O2(){return L2("registerEnabled")}function DK(){return L2("awsTextractEnabled")}function L2(e){try{return Kg[e]!==!1&&Kg[e]!=="false"}catch{return!0}}function IK(){const e=Gt(),[t]=_0(),n=t.get("client_id");if(!n)return null;const r=t.get("scope")||"openid";function o(i){const a=new URL(t.get("redirect_uri"));for(const l of["scope","state","nonce"])t.has(l)&&a.searchParams.set(l,t.get(l));a.searchParams.set("code",i),window.location.assign(a.toString())}return s.jsxs(o2,{onCode:o,onForgotPassword:()=>e("/resetpassword"),onRegister:()=>e("/register"),googleClientId:Pu().googleClientId,clientId:n||void 0,redirectUri:t.get("redirect_uri")||void 0,scope:r,nonce:t.get("nonce")||void 0,launch:t.get("launch")||void 0,codeChallenge:t.get("code_challenge")||void 0,codeChallengeMethod:t.get("code_challenge_method")||void 0,chooseScopes:r!=="openid",children:[s.jsx(to,{size:32}),s.jsx(ve,{children:"Sign in to Medplum"})]})}function AK(){const e=le(),t=Gt(),n=Pu();return p.useEffect(()=>{e.getProfile()&&t("/signin?project=new")},[e,t]),O2()?s.jsxs(kq,{type:"project",projectId:"new",onSuccess:()=>t("/"),googleClientId:n.googleClientId,recaptchaSiteKey:n.recaptchaSiteKey,children:[s.jsx(to,{size:32}),s.jsx(ve,{children:"Create a new account"})]}):s.jsx(Me,{width:450,children:s.jsx(Yi,{icon:s.jsx(El,{size:16}),title:"New projects disabled",color:"red",children:"New projects are disabled on this server."})})}function NK(){const e=Gt(),t=le(),[n,r]=p.useState(),[o,i]=p.useState(!1),a=Pu().recaptchaSiteKey;return p.useEffect(()=>{a&&n2(a)},[a]),s.jsx(Me,{width:450,children:s.jsxs(qe,{onSubmit:async l=>{let c="";a&&(c=await r2(a)),t.post("auth/resetpassword",{...l,recaptchaToken:c}).then(()=>i(!0)).catch(u=>r(ft(u)))},children:[s.jsxs($e,{gap:"lg",mb:"xl",align:"center",children:[s.jsx(to,{size:32}),s.jsx(ve,{children:"Medplum Password Reset"})]}),s.jsxs($e,{gap:"xl",children:[s.jsx(Ar,{issues:xu(n,void 0)}),!o&&s.jsxs(s.Fragment,{children:[s.jsx(ye,{name:"email",type:"email",label:"Email",required:!0,autoFocus:!0,error:Qe(n,"email")}),s.jsxs(te,{justify:"space-between",mt:"xl",wrap:"nowrap",children:[s.jsx(Ke,{component:"button",type:"button",color:"dimmed",onClick:()=>e("/register"),size:"xs",children:"Register"}),s.jsx(ae,{type:"submit",children:"Reset password"})]})]}),o&&s.jsx("div",{children:"If the account exists on our system, a password reset email will be sent."})]})]})})}function MK(){var i;const e=Gt(),t=le(),[n,r]=p.useState();p.useEffect(()=>{t.get("auth/me",{cache:"no-cache"}).then(r).catch(a=>ge({color:"red",message:Ae(a),autoClose:!1}))},[t]);function o(a){t.post("auth/revoke",{loginId:a}).then(()=>t.get("auth/me",{cache:"no-cache"})).then(r).then(()=>ge({color:"green",message:"Login revoked"})).catch(l=>ge({color:"red",message:Ae(l),autoClose:!1}))}return n?s.jsxs(s.Fragment,{children:[s.jsxs(Me,{children:[s.jsx(ve,{children:"Security"}),s.jsxs(i0,{children:[s.jsx(Oo,{term:"ID",children:s.jsx(Ke,{href:`/${rt(n.profile)}`,children:n.profile.id})}),s.jsx(Oo,{term:"Resource Type",children:n.profile.resourceType}),s.jsx(Oo,{term:"Name",children:pu((i=n.profile.name)==null?void 0:i[0])})]})]}),s.jsxs(Me,{children:[s.jsx(ve,{children:"Sessions"}),s.jsxs(pe,{children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"OS"}),s.jsx("th",{children:"Browser"}),s.jsx("th",{children:"IP Address"}),s.jsx("th",{children:"Auth Method"}),s.jsx("th",{children:"Last Updated"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:n.security.sessions.map(a=>s.jsxs("tr",{children:[s.jsx("td",{children:a.os}),s.jsx("td",{children:a.browser}),s.jsx("td",{children:a.remoteAddress}),s.jsx("td",{children:a.authMethod}),s.jsx("td",{children:zn(a.lastUpdated)}),s.jsx("td",{children:s.jsx(Ke,{href:"#",onClick:()=>o(a.id),children:"Revoke"})})]},a.id))})]})]}),s.jsxs(Me,{children:[s.jsx(ve,{children:"Password"}),s.jsx(ae,{onClick:()=>e("/changepassword"),children:"Change password"})]}),s.jsxs(Me,{children:[s.jsx(ve,{children:"Multi Factor Auth"}),s.jsxs("p",{children:["Enrolled: ",n.security.mfaEnrolled.toString()]}),!n.security.mfaEnrolled&&s.jsx(ae,{onClick:()=>e("/mfa"),children:"Enroll"})]})]}):null}function OK(){const{id:e,secret:t}=st(),n=le(),[r,o]=p.useState(),[i,a]=p.useState(!1),l=xu(r,void 0);return s.jsxs(Me,{width:450,children:[s.jsx(Ar,{issues:l}),s.jsxs(qe,{onSubmit:c=>{if(c.password!==c.confirmPassword){o(Oi("Passwords do not match","confirmPassword"));return}o(void 0);const u={id:e,secret:t,password:c.password};n.post("auth/setpassword",u).then(()=>a(!0)).catch(d=>o(ft(d)))},children:[s.jsxs(vn,{style:{flexDirection:"column"},children:[s.jsx(to,{size:32}),s.jsx(ve,{children:"Set password"})]}),!i&&s.jsxs($e,{children:[s.jsx(Hr,{name:"password",label:"New password",required:!0,error:Qe(r,"password")}),s.jsx(Hr,{name:"confirmPassword",label:"Confirm new password",required:!0,error:Qe(r,"confirmPassword")}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(ae,{type:"submit",children:"Set password"})})]}),i&&s.jsxs("div",{"data-testid":"success",children:["Password set. You can now ",s.jsx(We,{to:"/signin",children:"sign in"}),"."]})]})]})}function LK(){const e=Hh(),t=Gt(),[n]=_0(),r=Pu(),o=p.useCallback(()=>{const i=n.get("next");t(i!=null&&i.startsWith("/")?i:"/")},[n,t]);return p.useEffect(()=>{e&&n.has("next")&&o()},[e,n,o]),s.jsxs(o2,{onSuccess:()=>o(),onForgotPassword:()=>t("/resetpassword"),onRegister:O2()?()=>t("/register"):void 0,googleClientId:r.googleClientId,login:n.get("login")||void 0,projectId:n.get("project")||void 0,children:[s.jsx(to,{size:32}),s.jsx(ve,{children:"Sign in to Medplum"}),n.get("project")==="new"&&s.jsx("div",{children:"Sign in again to create a new project"})]})}function $K(){const e=Gt(),t=ii(),[n,r]=p.useState(),[o,i]=p.useState(),[a,l]=p.useState();return p.useEffect(()=>{const c=Object.fromEntries(new URLSearchParams(t.search).entries());r(c.resourceType),i(c.query),l(JSON.parse(c.fields))},[t]),!n||!o||!a?null:s.jsx(IW,{resourceType:n,checkboxesEnabled:!0,query:o,fields:a,onClick:c=>e(`/${n}/${c.resource.id}`),onAuxClick:c=>window.open(`/${n}/${c.resource.id}`,"_blank"),onBulk:c=>{e(`/bulk/${n}?ids=${c.join(",")}`)}})}function rp(e){const t=le(),n=ts(t),r=Gt(),[o,i]=p.useState({resourceType:"ProjectMembership",filters:[{code:"project",operator:re.EQUALS,value:"Project/"+n},{code:"profile-type",operator:re.EQUALS,value:e.resourceType}],fields:e.fields,count:100});return s.jsx(ju,{search:o,onClick:a=>r(`/admin/members/${a.resource.id}`),onChange:a=>i(a.definition),hideFilters:!0,hideToolbar:!0})}function FK(){return s.jsxs(s.Fragment,{children:[s.jsx(ve,{children:"Bots"}),s.jsx(rp,{resourceType:"Bot",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(te,{justify:"flex-end",children:s.jsx(We,{to:"/admin/bots/new",children:"Create new bot"})})]})}function zK(){return s.jsxs(s.Fragment,{children:[s.jsx(ve,{children:"Clients"}),s.jsx(rp,{resourceType:"ClientApplication",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(te,{justify:"flex-end",children:s.jsx(We,{to:"/admin/clients/new",children:"Create new client"})})]})}function op(e){return s.jsx(Zs,{resourceType:"AccessPolicy",name:"accessPolicy",defaultValue:e.defaultValue,placeholder:"Access Policy",onChange:t=>{ri(t)?e.onChange(Tt(t)):e.onChange(void 0)}})}function BK(){const e=le(),t=ts(e),[n,r]=p.useState(""),[o,i]=p.useState(""),[a,l]=p.useState(),[c,u]=p.useState(),[d,f]=p.useState(void 0);return s.jsxs(s.Fragment,{children:[s.jsx(ve,{children:"Create new Bot"}),s.jsxs(qe,{onSubmit:()=>{const h={name:n,description:o,accessPolicy:a};e.post("admin/projects/"+t+"/bot",h).then(m=>{e.invalidateSearches("Bot"),e.invalidateSearches("ProjectMembership"),f(m),ge({color:"green",message:"Bot created"})}).catch(m=>{ge({color:"red",message:Ae(m),autoClose:!1}),u(ft(m))})},children:[!d&&s.jsxs($e,{children:[s.jsx(yt,{title:"Name",htmlFor:"name",outcome:c,children:s.jsx(ye,{id:"name",name:"name",required:!0,autoFocus:!0,onChange:h=>r(h.currentTarget.value),error:Qe(c,"name")})}),s.jsx(yt,{title:"Description",htmlFor:"description",outcome:c,children:s.jsx(ye,{id:"description",name:"description",onChange:h=>i(h.currentTarget.value),error:Qe(c,"description")})}),s.jsx(yt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:c,children:s.jsx(op,{name:"accessPolicy",onChange:l})}),s.jsx(te,{justify:"flex-end",children:s.jsx(ae,{type:"submit",children:"Create Bot"})})]}),d&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(me,{children:"Bot created"}),s.jsxs($n,{children:[s.jsx($n.Item,{children:s.jsx(We,{to:d,children:"Go to new bot"})}),s.jsx($n.Item,{children:s.jsx(We,{to:"/admin/bots",children:"Back to bots list"})})]})]})]})]})}function UK(){const e=le(),t=ts(e),[n,r]=p.useState(""),[o,i]=p.useState(""),[a,l]=p.useState(""),[c,u]=p.useState(),[d,f]=p.useState(),[h,m]=p.useState(void 0);return s.jsxs(s.Fragment,{children:[s.jsx(ve,{children:"Create new Client"}),s.jsxs(qe,{onSubmit:()=>{const g={name:n,description:o,redirectUri:a,accessPolicy:c};e.post("admin/projects/"+t+"/client",g).then(v=>{e.invalidateSearches("ClientApplication"),e.invalidateSearches("ProjectMembership"),m(v),ge({color:"green",message:"Client created"})}).catch(v=>{ge({color:"red",message:Ae(v),autoClose:!1}),f(ft(v))})},children:[!h&&s.jsxs($e,{children:[s.jsx(yt,{title:"Name",htmlFor:"name",outcome:d,children:s.jsx(ye,{id:"name",name:"name",required:!0,autoFocus:!0,onChange:g=>r(g.currentTarget.value),error:Qe(d,"name")})}),s.jsx(yt,{title:"Description",htmlFor:"description",outcome:d,children:s.jsx(ye,{id:"description",name:"description",onChange:g=>i(g.currentTarget.value),error:Qe(d,"description")})}),s.jsx(yt,{title:"Redirect URI",htmlFor:"redirectUri",outcome:d,children:s.jsx(ye,{id:"redirectUri",name:"redirectUri",onChange:g=>l(g.currentTarget.value),error:Qe(d,"redirectUri")})}),s.jsx(yt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:d,children:s.jsx(op,{name:"accessPolicy",onChange:u})}),s.jsx(te,{justify:"flex-end",children:s.jsx(ae,{type:"submit",children:"Create Client"})})]}),h&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(me,{children:"Client created"}),s.jsxs($n,{children:[s.jsx($n.Item,{children:s.jsx(We,{to:h,children:"Go to new client"})}),s.jsx($n.Item,{children:s.jsx(We,{to:"/admin/clients",children:"Back to clients list"})})]})]})]})]})}function VK(e){return s.jsx(Zs,{resourceType:"UserConfiguration",name:"userConfiguration",defaultValue:e.defaultValue,placeholder:"User Configuration",onChange:t=>{ri(t)?e.onChange(Tt(t)):e.onChange(void 0)}})}function WK(){const{membershipId:e}=st(),t=le(),n=ts(t),r=Gt(),o=t.get(`admin/projects/${n}/members/${e}`).read(),[i,a]=p.useState(o.accessPolicy),[l,c]=p.useState(o.userConfiguration),[u,d]=p.useState(o.admin),[f,h]=p.useState(),[m,g]=p.useState(!1);function v(){window.confirm("Are you sure?")&&t.delete(`admin/projects/${n}/members/${e}`).then(()=>t.get(`admin/projects/${n}`,{cache:"no-cache"})).then(()=>r("/admin/project")).catch(S=>h(ft(S)))}return s.jsxs(s.Fragment,{children:[s.jsx(ve,{children:"Edit membership"}),s.jsx("h3",{children:s.jsx(Ha,{value:o.profile,link:!0})}),s.jsxs(qe,{onSubmit:()=>{const S={...o,accessPolicy:i,userConfiguration:l,admin:u};t.post(`admin/projects/${n}/members/${e}`,S).then(()=>g(!0)).catch(b=>h(ft(b)))},children:[!m&&s.jsxs($e,{children:[s.jsx(yt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:f,children:s.jsx(op,{name:"accessPolicy",defaultValue:i,onChange:a})}),s.jsx(yt,{title:"User Configuration",htmlFor:"userConfiguration",outcome:f,children:s.jsx(VK,{name:"userConfiguration",defaultValue:l,onChange:c})}),s.jsx(yt,{title:"Admin",htmlFor:"admin",outcome:f,children:s.jsx(Dn,{id:"admin",name:"admin",defaultChecked:u,onChange:S=>d(S.currentTarget.checked)})}),s.jsxs(te,{justify:"flex-end",mt:"xl",children:[s.jsx(ae,{type:"submit",children:"Save"}),s.jsx(ae,{type:"button",color:"red",variant:"outline",onClick:v,children:"Remove user"})]})]}),m&&s.jsxs("div",{"data-testid":"success",children:[s.jsx("p",{children:"User updated"}),s.jsx("pre",{children:JSON.stringify(f,void 0,2)}),s.jsxs("p",{children:["Click ",s.jsx(We,{to:"/admin/project",children:"here"})," to return to the project admin page."]})]})]})]})}function HK(){const e=le(),[t,n]=p.useState(e.getProject()),[r,o]=p.useState(),[i,a]=p.useState(),[l,c]=p.useState(!1),[u,d]=p.useState(void 0),f=p.useCallback(h=>{const m={resourceType:h.resourceType,firstName:h.firstName,lastName:h.lastName,email:h.email,sendEmail:h.sendEmail==="on",accessPolicy:r,admin:h.isAdmin==="on"};e.invite(t==null?void 0:t.id,m).then(g=>{e.invalidateSearches("Patient"),e.invalidateSearches("Practitioner"),e.invalidateSearches("ProjectMembership"),Lh(g)?a(g):d(g),c(m.sendEmail??!1),ge({color:"green",message:"Invite success"})}).catch(g=>{ge({color:"red",message:Ae(g),autoClose:!1}),a(ft(g))})},[e,t,r]);return s.jsxs(qe,{onSubmit:f,children:[!u&&!i&&s.jsxs($e,{children:[s.jsx(ve,{children:"Invite new member"}),e.isSuperAdmin()&&s.jsx(yt,{title:"Project",htmlFor:"project",outcome:i,children:s.jsx(Zs,{resourceType:"Project",name:"project",defaultValue:t,onChange:n})}),s.jsx(It,{name:"resourceType",label:"Role",defaultValue:"Practitioner",data:["Practitioner","Patient","RelatedPerson"],error:Qe(i,"resourceType")}),s.jsx(ye,{name:"firstName",label:"First Name",required:!0,autoFocus:!0,error:Qe(i,"firstName")}),s.jsx(ye,{name:"lastName",label:"Last Name",required:!0,error:Qe(i,"lastName")}),s.jsx(ye,{name:"email",type:"email",label:"Email",required:!0,error:Qe(i,"email")}),s.jsx(yt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:i,children:s.jsx(op,{name:"accessPolicy",onChange:o})}),s.jsx(Dn,{name:"sendEmail",label:"Send email",defaultChecked:!0}),s.jsx(Dn,{name:"isAdmin",label:"Admin"}),s.jsx(te,{justify:"flex-end",children:s.jsx(ae,{type:"submit",children:"Invite"})})]}),i&&s.jsxs("div",{"data-testid":"success",children:[s.jsx("p",{children:"User created, email couldn't be sent"}),s.jsx("p",{children:"Could not send email. Make sure you have AWS SES set up."}),s.jsxs("p",{children:["Click ",s.jsx(We,{to:"/admin/project",children:"here"})," to return to the project admin page."]})]}),u&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(me,{children:"User created"}),l&&s.jsx(me,{children:"Email sent"}),s.jsxs($n,{children:[s.jsx($n.Item,{children:s.jsx(We,{to:u,children:"Go to new membership"})}),s.jsx($n.Item,{children:s.jsx(We,{to:u.profile,children:"Go to new profile"})}),s.jsx($n.Item,{children:s.jsx(We,{to:"/admin/users",children:"Back to users list"})})]})]})]})}function qK(){return s.jsxs(s.Fragment,{children:[s.jsx(ve,{children:"Patients"}),s.jsx(rp,{resourceType:"Patient",fields:["user","profile","_lastUpdated"]}),s.jsx(te,{justify:"flex-end",children:s.jsx(We,{to:"/admin/invite",children:"Invite new patient"})})]})}function GK(){const e=le();if(!e.isLoading()&&!e.isProjectAdmin())return s.jsx(Ar,{outcome:GP});function t(n){e.post("admin/projects/setpassword",n).then(()=>ge({color:"green",message:"Done"})).catch(r=>ge({color:"red",message:Ae(r),autoClose:!1}))}return s.jsxs(Me,{width:600,children:[s.jsx(ve,{order:1,children:"Project Admin"}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Force Set Password"}),s.jsx(me,{children:"Sets the password for the specified user in this project."}),s.jsx(me,{children:"This action can only be performed by project administrators. Passwords can only be set for users scoped in this project."}),s.jsx(qe,{onSubmit:t,children:s.jsxs($e,{children:[s.jsx(ye,{name:"email",label:"Email",required:!0}),s.jsx(Hr,{name:"password",label:"Password",required:!0}),s.jsx(ae,{type:"submit",children:"Force Set Password"})]})})]})}function DS(){const e=le(),t=ts(e),n=e.get(`admin/projects/${t}`).read();return s.jsxs(s.Fragment,{children:[s.jsx(ve,{children:"Details"}),s.jsxs(i0,{children:[s.jsx(Oo,{term:"ID",children:n.project.id}),s.jsx(Oo,{term:"Name",children:n.project.name})]})]})}const IS=["Details","Users","Patients","Clients","Bots","Secrets","Sites"];function QK(){const e=Gt(),n=ii().pathname.replace("/admin/","")||IS[0],r=le(),o=ts(r),i=p.useMemo(()=>r.get("admin/projects/"+o).read(),[r,o]);function a(l){e(`/admin/${l}`)}return s.jsxs(s.Fragment,{children:[s.jsxs(Xn,{children:[s.jsx(ze,{children:s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Project"}),s.jsx(ze.Value,{children:i.project.name})]})}),s.jsx(_r,{children:s.jsx(Je,{value:n.toLowerCase(),onChange:a,children:s.jsx(Je.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:IS.map(l=>s.jsx(Je.Tab,{value:l.toLowerCase(),children:l},l))})})})]}),s.jsx(Me,{children:s.jsx(R0,{})})]})}function KK(){const e=le(),t=ts(e),n=e.get(`admin/projects/${t}`).read(),[r,o]=p.useState(!1),[i,a]=p.useState();return p.useEffect(()=>{e.requestSchema("Project").then(()=>o(!0)).catch(console.log)},[e]),p.useEffect(()=>{n&&a(Kr(n.project.secret||[]))},[e,n]),!r||!i?s.jsx("div",{children:"Loading..."}):s.jsxs("form",{noValidate:!0,autoComplete:"off",onSubmit:l=>{l.preventDefault(),e.post(`admin/projects/${t}/secrets`,i).then(()=>e.get(`admin/projects/${t}`,{cache:"reload"})).then(()=>ge({color:"green",message:"Saved"})).catch(console.log)},children:[s.jsx(ve,{children:"Project Secrets"}),s.jsx("p",{children:"Use project secrets to store sensitive information such as API keys or other access credentials."}),s.jsx(Tl,{property:Ys("Project","secret"),name:"secret",path:"Project.secret",defaultValue:i,onChange:a,outcome:void 0}),s.jsx(ae,{type:"submit",children:"Save"})]})}function YK(){const e=le(),t=ts(e),n=e.get(`admin/projects/${t}`).read(),[r,o]=p.useState(!1),[i,a]=p.useState();return p.useEffect(()=>{e.requestSchema("Project").then(()=>o(!0)).catch(console.log)},[e]),p.useEffect(()=>{n&&a(Kr(n.project.site||[]))},[e,n]),!r||!i?s.jsx("div",{children:"Loading..."}):s.jsxs("form",{noValidate:!0,autoComplete:"off",onSubmit:l=>{l.preventDefault(),e.post(`admin/projects/${t}/sites`,i).then(()=>e.get(`admin/projects/${t}`,{cache:"reload"})).then(()=>ge({color:"green",message:"Saved"})).catch(c=>{var d,f,h,m;const u=ft(c);ge({color:"red",message:`Error ${(f=(d=u.issue)==null?void 0:d[0].details)==null?void 0:f.text} ${(m=(h=u.issue)==null?void 0:h[0].expression)==null?void 0:m[0]}`,autoClose:!1})})},children:[s.jsx(ve,{children:"Project Sites"}),s.jsx("p",{children:"Use project sites configure your project on a separate domain."}),s.jsx(Tl,{property:Ys("Project","site"),name:"site",path:"Project.site",defaultValue:i,onChange:a,outcome:void 0}),s.jsx(ae,{type:"submit",children:"Save"})]})}function XK(){const e=le(),[t,{open:n,close:r}]=av(!1),[o,i]=p.useState(""),[a,l]=p.useState();if(!e.isLoading()&&!e.isSuperAdmin())return s.jsx(Ar,{outcome:GP});function c(){vd(e,"Rebuilding Structure Definitions","admin/super/structuredefinitions")}function u(){vd(e,"Rebuilding Search Parameters","admin/super/searchparameters")}function d(){vd(e,"Rebuilding Value Sets","admin/super/valuesets")}function f(S){vd(e,"Reindexing Resources","admin/super/reindex",S)}function h(S){e.post("admin/super/removebotidjobsfromqueue",S).then(()=>ge({color:"green",message:"Done"})).catch(b=>ge({color:"red",message:Ae(b),autoClose:!1}))}function m(S){e.post("admin/super/purge",{...S,before:sR(S.before)}).then(()=>ge({color:"green",message:"Done"})).catch(b=>ge({color:"red",message:Ae(b),autoClose:!1}))}function g(S){e.post("admin/super/setpassword",S).then(()=>ge({color:"green",message:"Done"})).catch(b=>ge({color:"red",message:Ae(b),autoClose:!1}))}function v(){e.post("fhir/R4/$db-stats",{}).then(S=>{var b,w;i("Database Stats"),l(s.jsx("pre",{children:(w=(b=S.parameter)==null?void 0:b.find(y=>y.name==="tableString"))==null?void 0:w.valueString})),n()}).catch(S=>ge({color:"red",message:Ae(S),autoClose:!1}))}return s.jsxs(Me,{width:600,children:[s.jsx(ve,{order:1,children:"Super Admin"}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Structure Definitions"}),s.jsx("p",{children:"StructureDefinition resources contain the metadata about resource types. They are provided with the FHIR specification. Medplum also includes some custom StructureDefinition resources for internal data types. Press this button to update the database StructureDefinitions from the FHIR specification."}),s.jsx(qe,{children:s.jsx(ae,{onClick:c,children:"Rebuild StructureDefinitions"})}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Search Parameters"}),s.jsx("p",{children:"SearchParameter resources contain the metadata about filters and sorting. They are provided with the FHIR specification. Medplum also includes some custom SearchParameter resources for internal data types. Press this button to update the database SearchParameters from the FHIR specification."}),s.jsx(qe,{children:s.jsx(ae,{onClick:u,children:"Rebuild SearchParameters"})}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Value Sets"}),s.jsx("p",{children:"ValueSet resources enum values for a wide variety of use cases. Press this button to update the database ValueSets from the FHIR specification."}),s.jsx(qe,{children:s.jsx(ae,{onClick:d,children:"Rebuild ValueSets"})}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Reindex Resources"}),s.jsx("p",{children:"When Medplum changes how resources are indexed, the system may require a reindex for old resources to be indexed properly."}),s.jsx(qe,{onSubmit:f,children:s.jsxs($e,{children:[s.jsx(yt,{title:"Resource Type",htmlFor:"resourceType",children:s.jsx(ye,{id:"resourceType",name:"resourceType",placeholder:"Reindex Resource Type"})}),s.jsx(yt,{title:"Search Filter",htmlFor:"filter",children:s.jsx(ye,{id:"filter",name:"filter",placeholder:"e.g. name=Sam&birthdate=lt2000-01-01"})}),s.jsx(ae,{type:"submit",children:"Reindex"})]})}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Purge Resources"}),s.jsx("p",{children:"As system generated resources accumulate, the system may require a purge to remove old resources."}),s.jsx(qe,{onSubmit:m,children:s.jsxs($e,{children:[s.jsx(yt,{title:"Purge Resource Type",htmlFor:"purgeResourceType",children:s.jsx(It,{id:"purgeResourceType",name:"resourceType",data:["","AuditEvent","Login"]})}),s.jsx(yt,{title:"Purge Before",htmlFor:"before",children:s.jsx(As,{name:"before",placeholder:"Before Date"})}),s.jsx(ae,{type:"submit",children:"Purge"})]})}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Remove Bot ID Jobs from Queue"}),s.jsx("p",{children:"Remove all queued jobs for a Bot ID"}),s.jsx(qe,{onSubmit:h,children:s.jsxs($e,{children:[s.jsx(yt,{title:"Bot ID",children:s.jsx(ye,{name:"botId",placeholder:"Bot Id"})}),s.jsx(ae,{type:"submit",children:"Remove Jobs by Bot ID"})]})}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Force Set Password"}),s.jsx("p",{children:'Note that this applies to all projects for the user. Therefore, this should only be used in extreme circumstances. Always prefer to use the "Forgot Password" flow first.'}),s.jsx(qe,{onSubmit:g,children:s.jsxs($e,{children:[s.jsx(ye,{name:"email",label:"Email",required:!0}),s.jsx(Hr,{name:"password",label:"Password",required:!0}),s.jsx(ye,{name:"projectId",label:"Project ID"}),s.jsx(ae,{type:"submit",children:"Force Set Password"})]})}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Database Stats"}),s.jsx("p",{children:"Query current table statistics from the database."}),s.jsx(qe,{onSubmit:v,children:s.jsx(ae,{type:"submit",children:"Get Database Stats"})}),s.jsx(jn,{opened:t,onClose:r,title:o,centered:!0,children:a})]})}function vd(e,t,n,r){po.show({id:n,loading:!0,title:t,message:"Running...",autoClose:!1,withCloseButton:!1});const o={method:"POST",pollStatusOnAccepted:!0};r&&(o.body=JSON.stringify(r)),e.startAsyncRequest(n,o).then(()=>{po.update({id:n,color:"green",title:t,message:"Done",icon:s.jsx(Js,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})}).catch(i=>{po.update({id:n,color:"red",title:t,message:Ae(i),icon:s.jsx(Ef,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})})}function JK(){return s.jsxs(s.Fragment,{children:[s.jsx(ve,{children:"Users"}),s.jsx(rp,{resourceType:"Practitioner",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(te,{justify:"flex-end",children:s.jsx(We,{to:"/admin/invite",children:"Invite new user"})})]})}function ZK(){const[e]=al("ObservationDefinition","_count=100");return e?s.jsxs(pe,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Category"}),s.jsx("th",{children:"Code"}),s.jsx("th",{children:"Method"}),s.jsx("th",{children:"Unit"}),s.jsx("th",{children:"Precision"}),s.jsx("th",{children:"Ranges"})]})}),s.jsx("tbody",{children:e.map(t=>{var n,r,o,i;return s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx(mo,{value:(n=t.category)==null?void 0:n[0]})}),s.jsx("td",{children:s.jsx(mo,{value:t.code})}),s.jsx("td",{children:s.jsx(mo,{value:t.method})}),s.jsx("td",{children:(o=(r=t.quantitativeDetails)==null?void 0:r.unit)==null?void 0:o.text}),s.jsx("td",{children:(i=t.quantitativeDetails)==null?void 0:i.decimalPrecision}),s.jsx("td",{children:s.jsx(Yg,{ranges:t.qualifiedInterval})})]},t.id)})})]}):s.jsx(Yr,{})}function Yg(e){const{ranges:t}=e;if(!t)return null;const n=AS(t.map(o=>o.gender));if(n.length>1)return Oc(n),s.jsx(s.Fragment,{children:n.map(o=>{var i;return s.jsxs(p.Fragment,{children:[s.jsx("div",{children:s.jsx("strong",{children:tn(o)})}),s.jsx(Yg,{ranges:(i=e.ranges)==null?void 0:i.filter(a=>a.gender===o)})]},o)})});const r=AS(t.map(o=>o.age&&Lc(o.age)));return r.length>1?(Oc(r),s.jsx(s.Fragment,{children:r.map(o=>{var i;return s.jsxs(p.Fragment,{children:[s.jsx("div",{children:s.jsx("strong",{children:tn(o)})}),s.jsx(Yg,{ranges:(i=e.ranges)==null?void 0:i.filter(a=>Lc(a.age)===o)})]},o)})})):s.jsx(s.Fragment,{children:t.map(o=>s.jsx("table",{children:s.jsx("tbody",{children:s.jsxs("tr",{children:[s.jsx("td",{children:o.condition}),s.jsx("td",{children:s.jsx(a0,{value:o.range})})]})})},`range-${o.condition}`))})}function AS(e){return[...new Set(e.filter(t=>!!t))]}function eY(){const[e]=al("ActivityDefinition","_count=100"),[t]=al("ObservationDefinition","_count=100");return!e||!t?s.jsx(Yr,{}):s.jsxs(pe,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Category"}),s.jsx("th",{children:"Assay"}),e.map(n=>s.jsx("th",{children:n.name},n.id))]})}),s.jsx("tbody",{children:t.map(n=>{var r;return s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx(mo,{value:(r=n.category)==null?void 0:r[0]})}),s.jsx("td",{children:s.jsx(mo,{value:n.code})}),e.map(o=>{var i;return s.jsx("td",{children:(i=o.observationResultRequirement)!=null&&i.find(a=>{var l;return(l=a.reference)==null?void 0:l.includes(n.id)})?"✅":""},o.id)})]},n.id)})})]})}function tY(e){var a;const t=le(),[n,r]=p.useState(),[o,i]=p.useState();return o?s.jsxs(s.Fragment,{children:[s.jsx("p",{children:"Request group created successfully."}),s.jsxs("ul",{children:[s.jsxs("li",{children:["Go to the"," ",s.jsx(We,{to:o,suffix:"checklist",children:"Request Group"})]}),s.jsxs("li",{children:["Back to the ",s.jsx(We,{to:e.planDefinition,children:"Plan Definition"})]})]})]}):s.jsx(qe,{onSubmit:()=>{t.post(t.fhirUrl("PlanDefinition",e.planDefinition.id,"$apply"),{resourceType:"Parameters",parameter:[{name:"subject",valueString:n==null?void 0:n.reference}]}).then(i).catch(console.log)},children:s.jsxs($e,{children:[s.jsxs(ve,{children:['Start "',e.planDefinition.title,'"']}),s.jsxs(me,{children:["Use the ",s.jsx("strong",{children:"Apply"})," operation to create a group of tasks for a workflow."]}),s.jsx(me,{children:"The following tasks will be created:"}),s.jsx("ul",{children:(a=e.planDefinition.action)==null?void 0:a.map((l,c)=>{var u;return s.jsxs("li",{children:[((u=l.definitionCanonical)==null?void 0:u.startsWith("Questionnaire/"))&&"Questionnaire request: ",l.title&&s.jsx(s.Fragment,{children:l.title}),l.code&&s.jsx(mo,{value:l.code[0]})]},`action-${c}`)})}),s.jsx(yt,{title:"Subject",children:s.jsx(Gh,{name:"subject",targetTypes:["Patient","Practitioner"],defaultValue:n,onChange:r})}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(ae,{type:"submit",children:"Go"})})]})})}function nY(){const{resourceType:e,id:t}=st(),n=St({reference:e+"/"+t});return n?s.jsx(Me,{children:s.jsx(tY,{planDefinition:n})}):null}function rY(){const{resourceType:e,id:t}=st(),n=St({reference:e+"/"+t}),[r,o]=al("Questionnaire","subject-type="+e),[i,a]=al("ClientApplication",{_count:1e3});if(!n||o||a)return s.jsx(Yr,{});const l=i==null?void 0:i.filter(d=>oY(e)&&!!d.launchUri);if((!r||r.length===0)&&(!l||l.length===0))return s.jsxs(Me,{children:[s.jsx(ve,{children:"Apps"}),s.jsxs("p",{children:["No apps found. Contact your administrator or ",s.jsx("a",{href:"mailto:support@medplum.com",children:"Medplum Support"})," to add automation here."]})]});let c,u;return n.resourceType==="Patient"?c=Tt(n):n.resourceType==="Encounter"&&(c=n.subject,u=Tt(n)),s.jsxs(Me,{children:[r==null?void 0:r.map(d=>s.jsxs("div",{children:[s.jsx(ve,{order:3,children:s.jsx(We,{to:`/forms/${d.id}?subject=${rt(n)}`,children:d.title||d.name})}),s.jsx(me,{children:d.description})]},d.id)),l==null?void 0:l.map(d=>s.jsxs("div",{children:[s.jsx(ve,{order:3,children:s.jsx(Tq,{client:d,patient:c,encounter:u,children:d.name})}),s.jsx(me,{children:d.description})]},d.id))]})}function oY(e){return e==="Patient"||e==="Encounter"}function iY(){const{resourceType:e,id:t}=st(),n=Gt(),[r,o]=p.useState({resourceType:"AuditEvent",filters:[{code:"entity",operator:re.EQUALS,value:`${e}/${t}`}],fields:["id","outcome","outcomeDesc","_lastUpdated"],sortRules:[{code:"-_lastUpdated"}],count:20});return s.jsx(Me,{children:s.jsx(ju,{search:r,onClick:i=>n(`/${i.resource.resourceType}/${i.resource.id}`),onChange:i=>o(i.definition),hideFilters:!0})})}function sY(){const e=le(),{resourceType:t,id:n}=st(),r=e.readHistory(t,n).read();return s.jsx(Me,{children:s.jsx(mq,{history:r})})}const aY="_hl7Input_k5xm3_1",lY={hl7Input:aY};function cY(e){return s.jsx("iframe",{frameBorder:"0",src:"https://codeeditor.medplum.com/bot-runner.html",className:e.className,ref:e.iframeRef,"data-testid":e.testId,style:{width:"100%",height:"100%",minHeight:e.minHeight}})}function uY(e){const t=e.defaultValue,n=new URL(`https://codeeditor.medplum.com/${e.language}-editor.html`);return e.module&&n.searchParams.set("module",e.module),s.jsx("iframe",{frameBorder:"0",src:n.toString(),style:{width:"100%",height:"100%",minHeight:e.minHeight},ref:e.iframeRef,"data-testid":e.testId,onLoad:r=>{Ld(r.currentTarget,{command:"setValue",value:t}).catch(console.error)}})}const dY=`{
|
|
572
|
+
*/function If(){return If=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},If.apply(this,arguments)}function Hg(e){return e===void 0&&(e=""),new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(o=>[n,o]):[[n,r]])},[]))}function ZG(e,t){let n=Hg(e);return t&&t.forEach((r,o)=>{n.has(o)||t.getAll(o).forEach(i=>{n.append(o,i)})}),n}const eQ="6";try{window.__reactRouterVersion=eQ}catch{}function tQ(e,t){return fG({basename:void 0,future:If({},void 0,{v7_prependBasename:!0}),history:Oq({window:void 0}),hydrationData:nQ(),routes:e,mapRouteProperties:JG,unstable_dataStrategy:void 0,unstable_patchRoutesOnNavigation:void 0,window:void 0}).initialize()}function nQ(){var e;let t=(e=window)==null?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=If({},t,{errors:rQ(t.errors)})),t}function rQ(e){if(!e)return null;let t=Object.entries(e),n={};for(let[r,o]of t)if(o&&o.__type==="RouteErrorResponse")n[r]=new _f(o.status,o.statusText,o.data,o.internal===!0);else if(o&&o.__type==="Error"){if(o.__subType){let i=window[o.__subType];if(typeof i=="function")try{let a=new i(o.message);a.stack="",n[r]=a}catch{}}if(n[r]==null){let i=new Error(o.message);i.stack="",n[r]=i}}else n[r]=o;return n}const oQ=p.createContext({isTransitioning:!1}),iQ=p.createContext(new Map),sQ="startTransition",vS=QS[sQ],aQ="flushSync",yS=ON[aQ];function lQ(e){vS?vS(e):e()}function Hl(e){yS?yS(e):e()}class cQ{constructor(){this.status="pending",this.promise=new Promise((t,n)=>{this.resolve=r=>{this.status==="pending"&&(this.status="resolved",t(r))},this.reject=r=>{this.status==="pending"&&(this.status="rejected",n(r))}})}}function uQ(e){let{fallbackElement:t,router:n,future:r}=e,[o,i]=p.useState(n.state),[a,l]=p.useState(),[c,u]=p.useState({isTransitioning:!1}),[d,f]=p.useState(),[h,m]=p.useState(),[g,v]=p.useState(),S=p.useRef(new Map),{v7_startTransition:b}=r||{},w=p.useCallback(j=>{b?lQ(j):j()},[b]),y=p.useCallback((j,R)=>{let{deletedFetchers:k,unstable_flushSync:I,unstable_viewTransitionOpts:O}=R;k.forEach(L=>S.current.delete(L)),j.fetchers.forEach((L,B)=>{L.data!==void 0&&S.current.set(B,L.data)});let F=n.window==null||n.window.document==null||typeof n.window.document.startViewTransition!="function";if(!O||F){I?Hl(()=>i(j)):w(()=>i(j));return}if(I){Hl(()=>{h&&(d&&d.resolve(),h.skipTransition()),u({isTransitioning:!0,flushSync:!0,currentLocation:O.currentLocation,nextLocation:O.nextLocation})});let L=n.window.document.startViewTransition(()=>{Hl(()=>i(j))});L.finished.finally(()=>{Hl(()=>{f(void 0),m(void 0),l(void 0),u({isTransitioning:!1})})}),Hl(()=>m(L));return}h?(d&&d.resolve(),h.skipTransition(),v({state:j,currentLocation:O.currentLocation,nextLocation:O.nextLocation})):(l(j),u({isTransitioning:!0,flushSync:!1,currentLocation:O.currentLocation,nextLocation:O.nextLocation}))},[n.window,h,d,S,w]);p.useLayoutEffect(()=>n.subscribe(y),[n,y]),p.useEffect(()=>{c.isTransitioning&&!c.flushSync&&f(new cQ)},[c]),p.useEffect(()=>{if(d&&a&&n.window){let j=a,R=d.promise,k=n.window.document.startViewTransition(async()=>{w(()=>i(j)),await R});k.finished.finally(()=>{f(void 0),m(void 0),l(void 0),u({isTransitioning:!1})}),m(k)}},[w,a,d,n.window]),p.useEffect(()=>{d&&a&&o.location.key===a.location.key&&d.resolve()},[d,h,o.location,a]),p.useEffect(()=>{!c.isTransitioning&&g&&(l(g.state),u({isTransitioning:!0,flushSync:!1,currentLocation:g.currentLocation,nextLocation:g.nextLocation}),v(void 0))},[c.isTransitioning,g]),p.useEffect(()=>{},[]);let x=p.useMemo(()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:j=>n.navigate(j),push:(j,R,k)=>n.navigate(j,{state:R,preventScrollReset:k==null?void 0:k.preventScrollReset}),replace:(j,R,k)=>n.navigate(j,{replace:!0,state:R,preventScrollReset:k==null?void 0:k.preventScrollReset})}),[n]),C=n.basename||"/",E=p.useMemo(()=>({router:n,navigator:x,static:!1,basename:C}),[n,x,C]),T=p.useMemo(()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath}),[n.future.v7_relativeSplatPath]);return p.createElement(p.Fragment,null,p.createElement(Jh.Provider,{value:E},p.createElement(v2.Provider,{value:o},p.createElement(iQ.Provider,{value:S.current},p.createElement(oQ.Provider,{value:c},p.createElement(YG,{basename:C,location:o.location,navigationType:o.historyAction,navigator:x,future:T},o.initialized||n.future.v7_partialHydration?p.createElement(dQ,{routes:n.routes,future:n.future,state:o}):t))))),null)}const dQ=p.memo(fQ);function fQ(e){let{routes:t,future:n,state:r}=e;return b2(t,void 0,r,n)}var xS;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(xS||(xS={}));var bS;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(bS||(bS={}));function _0(e){let t=p.useRef(Hg(e)),n=p.useRef(!1),r=ii(),o=p.useMemo(()=>ZG(r.search,n.current?null:t.current),[r.search]),i=Gt(),a=p.useCallback((l,c)=>{const u=Hg(typeof l=="function"?l(o):l);n.current=!0,i("?"+u,c)},[i,o]);return[o,a]}const hQ=new Map([["aac","audio/aac"],["abw","application/x-abiword"],["arc","application/x-freearc"],["avif","image/avif"],["avi","video/x-msvideo"],["azw","application/vnd.amazon.ebook"],["bin","application/octet-stream"],["bmp","image/bmp"],["bz","application/x-bzip"],["bz2","application/x-bzip2"],["cda","application/x-cdf"],["csh","application/x-csh"],["css","text/css"],["csv","text/csv"],["doc","application/msword"],["docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],["eot","application/vnd.ms-fontobject"],["epub","application/epub+zip"],["gz","application/gzip"],["gif","image/gif"],["heic","image/heic"],["heif","image/heif"],["htm","text/html"],["html","text/html"],["ico","image/vnd.microsoft.icon"],["ics","text/calendar"],["jar","application/java-archive"],["jpeg","image/jpeg"],["jpg","image/jpeg"],["js","text/javascript"],["json","application/json"],["jsonld","application/ld+json"],["mid","audio/midi"],["midi","audio/midi"],["mjs","text/javascript"],["mp3","audio/mpeg"],["mp4","video/mp4"],["mpeg","video/mpeg"],["mpkg","application/vnd.apple.installer+xml"],["odp","application/vnd.oasis.opendocument.presentation"],["ods","application/vnd.oasis.opendocument.spreadsheet"],["odt","application/vnd.oasis.opendocument.text"],["oga","audio/ogg"],["ogv","video/ogg"],["ogx","application/ogg"],["opus","audio/opus"],["otf","font/otf"],["png","image/png"],["pdf","application/pdf"],["php","application/x-httpd-php"],["ppt","application/vnd.ms-powerpoint"],["pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],["rar","application/vnd.rar"],["rtf","application/rtf"],["sh","application/x-sh"],["svg","image/svg+xml"],["swf","application/x-shockwave-flash"],["tar","application/x-tar"],["tif","image/tiff"],["tiff","image/tiff"],["ts","video/mp2t"],["ttf","font/ttf"],["txt","text/plain"],["vsd","application/vnd.visio"],["wav","audio/wav"],["weba","audio/webm"],["webm","video/webm"],["webp","image/webp"],["woff","font/woff"],["woff2","font/woff2"],["xhtml","application/xhtml+xml"],["xls","application/vnd.ms-excel"],["xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],["xml","application/xml"],["xul","application/vnd.mozilla.xul+xml"],["zip","application/zip"],["7z","application/x-7z-compressed"],["mkv","video/x-matroska"],["mov","video/quicktime"],["msg","application/vnd.ms-outlook"]]);function Tu(e,t){const n=pQ(e);if(typeof n.path!="string"){const{webkitRelativePath:r}=e;Object.defineProperty(n,"path",{value:typeof t=="string"?t:typeof r=="string"&&r.length>0?r:e.name,writable:!1,configurable:!1,enumerable:!0})}return n}function pQ(e){const{name:t}=e;if(t&&t.lastIndexOf(".")!==-1&&!e.type){const r=t.split(".").pop().toLowerCase(),o=hQ.get(r);o&&Object.defineProperty(e,"type",{value:o,writable:!1,configurable:!1,enumerable:!0})}return e}var kl=(e,t,n)=>new Promise((r,o)=>{var i=c=>{try{l(n.next(c))}catch(u){o(u)}},a=c=>{try{l(n.throw(c))}catch(u){o(u)}},l=c=>c.done?r(c.value):Promise.resolve(c.value).then(i,a);l((n=n.apply(e,t)).next())});const mQ=[".DS_Store","Thumbs.db"];function gQ(e){return kl(this,null,function*(){return Af(e)&&vQ(e.dataTransfer)?wQ(e.dataTransfer,e.type):yQ(e)?xQ(e):Array.isArray(e)&&e.every(t=>"getFile"in t&&typeof t.getFile=="function")?bQ(e):[]})}function vQ(e){return Af(e)}function yQ(e){return Af(e)&&Af(e.target)}function Af(e){return typeof e=="object"&&e!==null}function xQ(e){return qg(e.target.files).map(t=>Tu(t))}function bQ(e){return kl(this,null,function*(){return(yield Promise.all(e.map(n=>n.getFile()))).map(n=>Tu(n))})}function wQ(e,t){return kl(this,null,function*(){if(e.items){const n=qg(e.items).filter(o=>o.kind==="file");if(t!=="drop")return n;const r=yield Promise.all(n.map(SQ));return wS(j2(r))}return wS(qg(e.files).map(n=>Tu(n)))})}function wS(e){return e.filter(t=>mQ.indexOf(t.name)===-1)}function qg(e){if(e===null)return[];const t=[];for(let n=0;n<e.length;n++){const r=e[n];t.push(r)}return t}function SQ(e){if(typeof e.webkitGetAsEntry!="function")return SS(e);const t=e.webkitGetAsEntry();return t&&t.isDirectory?C2(t):SS(e)}function j2(e){return e.reduce((t,n)=>[...t,...Array.isArray(n)?j2(n):[n]],[])}function SS(e){const t=e.getAsFile();if(!t)return Promise.reject(`${e} is not a File`);const n=Tu(t);return Promise.resolve(n)}function jQ(e){return kl(this,null,function*(){return e.isDirectory?C2(e):CQ(e)})}function C2(e){const t=e.createReader();return new Promise((n,r)=>{const o=[];function i(){t.readEntries(a=>kl(this,null,function*(){if(a.length){const l=Promise.all(a.map(jQ));o.push(l),i()}else try{const l=yield Promise.all(o);n(l)}catch(l){r(l)}}),a=>{r(a)})}i()})}function CQ(e){return kl(this,null,function*(){return new Promise((t,n)=>{e.file(r=>{const o=Tu(r,e.fullPath);t(o)},r=>{n(r)})})})}function EQ(e,t){if(e&&t){const n=Array.isArray(t)?t:t.split(","),r=e.name||"",o=(e.type||"").toLowerCase(),i=o.replace(/\/.*$/,"");return n.some(a=>{const l=a.trim().toLowerCase();return l.charAt(0)==="."?r.toLowerCase().endsWith(l):l.endsWith("/*")?i===l.replace(/\/.*$/,""):o===l})}return!0}var TQ=Object.defineProperty,PQ=Object.defineProperties,kQ=Object.getOwnPropertyDescriptors,jS=Object.getOwnPropertySymbols,RQ=Object.prototype.hasOwnProperty,_Q=Object.prototype.propertyIsEnumerable,CS=(e,t,n)=>t in e?TQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,DQ=(e,t)=>{for(var n in t||(t={}))RQ.call(t,n)&&CS(e,n,t[n]);if(jS)for(var n of jS(t))_Q.call(t,n)&&CS(e,n,t[n]);return e},IQ=(e,t)=>PQ(e,kQ(t));const AQ="file-invalid-type",NQ="file-too-large",MQ="file-too-small",OQ="too-many-files",LQ=e=>{e=Array.isArray(e)&&e.length===1?e[0]:e;const t=Array.isArray(e)?`one of ${e.join(", ")}`:e;return{code:AQ,message:`File type must be ${t}`}},ES=e=>({code:NQ,message:`File is larger than ${e} ${e===1?"byte":"bytes"}`}),TS=e=>({code:MQ,message:`File is smaller than ${e} ${e===1?"byte":"bytes"}`}),$Q={code:OQ,message:"Too many files"};function E2(e,t){const n=e.type==="application/x-moz-file"||EQ(e,t);return[n,n?null:LQ(t)]}function T2(e,t,n){if(fs(e.size))if(fs(t)&&fs(n)){if(e.size>n)return[!1,ES(n)];if(e.size<t)return[!1,TS(t)]}else{if(fs(t)&&e.size<t)return[!1,TS(t)];if(fs(n)&&e.size>n)return[!1,ES(n)]}return[!0,null]}function fs(e){return e!=null}function FQ({files:e,accept:t,minSize:n,maxSize:r,multiple:o,maxFiles:i,validator:a}){return!o&&e.length>1||o&&i>=1&&e.length>i?!1:e.every(l=>{const[c]=E2(l,t),[u]=T2(l,n,r),d=a?a(l):null;return c&&u&&!d})}function Nf(e){return typeof e.isPropagationStopped=="function"?e.isPropagationStopped():typeof e.cancelBubble<"u"?e.cancelBubble:!1}function md(e){return e.dataTransfer?Array.prototype.some.call(e.dataTransfer.types,t=>t==="Files"||t==="application/x-moz-file"):!!e.target&&!!e.target.files}function PS(e){e.preventDefault()}function zQ(e){return e.indexOf("MSIE")!==-1||e.indexOf("Trident/")!==-1}function BQ(e){return e.indexOf("Edge/")!==-1}function UQ(e=window.navigator.userAgent){return zQ(e)||BQ(e)}function io(...e){return(t,...n)=>e.some(r=>(!Nf(t)&&r&&r(t,...n),Nf(t)))}function VQ(){return"showOpenFilePicker"in window}function WQ(e){return fs(e)?[{description:"Files",accept:Object.entries(e).filter(([n,r])=>{let o=!0;return P2(n)||(console.warn(`Skipped "${n}" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.`),o=!1),(!Array.isArray(r)||!r.every(k2))&&(console.warn(`Skipped "${n}" because an invalid file extension was provided.`),o=!1),o}).reduce((n,[r,o])=>IQ(DQ({},n),{[r]:o}),{})}]:e}function HQ(e){if(fs(e))return Object.entries(e).reduce((t,[n,r])=>[...t,n,...r],[]).filter(t=>P2(t)||k2(t)).join(",")}function qQ(e){return e instanceof DOMException&&(e.name==="AbortError"||e.code===e.ABORT_ERR)}function GQ(e){return e instanceof DOMException&&(e.name==="SecurityError"||e.code===e.SECURITY_ERR)}function P2(e){return e==="audio/*"||e==="video/*"||e==="image/*"||e==="text/*"||/\w+\/[-+.\w]+/g.test(e)}function k2(e){return/^.*\.[\w]+$/.test(e)}var QQ=Object.defineProperty,KQ=Object.defineProperties,YQ=Object.getOwnPropertyDescriptors,Mf=Object.getOwnPropertySymbols,R2=Object.prototype.hasOwnProperty,_2=Object.prototype.propertyIsEnumerable,kS=(e,t,n)=>t in e?QQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,On=(e,t)=>{for(var n in t||(t={}))R2.call(t,n)&&kS(e,n,t[n]);if(Mf)for(var n of Mf(t))_2.call(t,n)&&kS(e,n,t[n]);return e},bi=(e,t)=>KQ(e,YQ(t)),Of=(e,t)=>{var n={};for(var r in e)R2.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Mf)for(var r of Mf(e))t.indexOf(r)<0&&_2.call(e,r)&&(n[r]=e[r]);return n};const D0=p.forwardRef((e,t)=>{var n=e,{children:r}=n,o=Of(n,["children"]);const i=I2(o),{open:a}=i,l=Of(i,["open"]);return p.useImperativeHandle(t,()=>({open:a}),[a]),fn.createElement(p.Fragment,null,r(bi(On({},l),{open:a})))});D0.displayName="Dropzone";const D2={disabled:!1,getFilesFromEvent:gQ,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!0,autoFocus:!1};D0.defaultProps=D2;D0.propTypes={children:vt.func,accept:vt.objectOf(vt.arrayOf(vt.string)),multiple:vt.bool,preventDropOnDocument:vt.bool,noClick:vt.bool,noKeyboard:vt.bool,noDrag:vt.bool,noDragEventsBubbling:vt.bool,minSize:vt.number,maxSize:vt.number,maxFiles:vt.number,disabled:vt.bool,getFilesFromEvent:vt.func,onFileDialogCancel:vt.func,onFileDialogOpen:vt.func,useFsAccessApi:vt.bool,autoFocus:vt.bool,onDragEnter:vt.func,onDragLeave:vt.func,onDragOver:vt.func,onDrop:vt.func,onDropAccepted:vt.func,onDropRejected:vt.func,onError:vt.func,validator:vt.func};const Gg={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function I2(e={}){const{accept:t,disabled:n,getFilesFromEvent:r,maxSize:o,minSize:i,multiple:a,maxFiles:l,onDragEnter:c,onDragLeave:u,onDragOver:d,onDrop:f,onDropAccepted:h,onDropRejected:m,onFileDialogCancel:g,onFileDialogOpen:v,useFsAccessApi:S,autoFocus:b,preventDropOnDocument:w,noClick:y,noKeyboard:x,noDrag:C,noDragEventsBubbling:E,onError:T,validator:j}=On(On({},D2),e),R=p.useMemo(()=>HQ(t),[t]),k=p.useMemo(()=>WQ(t),[t]),I=p.useMemo(()=>typeof v=="function"?v:RS,[v]),O=p.useMemo(()=>typeof g=="function"?g:RS,[g]),F=p.useRef(null),L=p.useRef(null),[B,D]=p.useReducer(XQ,Gg),{isFocused:_,isFileDialogActive:P}=B,N=p.useRef(typeof window<"u"&&window.isSecureContext&&S&&VQ()),$=()=>{!N.current&&P&&setTimeout(()=>{if(L.current){const{files:J}=L.current;J.length||(D({type:"closeDialog"}),O())}},300)};p.useEffect(()=>(window.addEventListener("focus",$,!1),()=>{window.removeEventListener("focus",$,!1)}),[L,P,O,N]);const H=p.useRef([]),X=J=>{F.current&&F.current.contains(J.target)||(J.preventDefault(),H.current=[])};p.useEffect(()=>(w&&(document.addEventListener("dragover",PS,!1),document.addEventListener("drop",X,!1)),()=>{w&&(document.removeEventListener("dragover",PS),document.removeEventListener("drop",X))}),[F,w]),p.useEffect(()=>(!n&&b&&F.current&&F.current.focus(),()=>{}),[F,b,n]);const ce=p.useCallback(J=>{T?T(J):console.error(J)},[T]),Ie=p.useCallback(J=>{J.preventDefault(),J.persist(),oe(J),H.current=[...H.current,J.target],md(J)&&Promise.resolve(r(J)).then(ie=>{if(Nf(J)&&!E)return;const G=ie.length,Ce=G>0&&FQ({files:ie,accept:R,minSize:i,maxSize:o,multiple:a,maxFiles:l,validator:j}),He=G>0&&!Ce;D({isDragAccept:Ce,isDragReject:He,isDragActive:!0,type:"setDraggedFiles"}),c&&c(J)}).catch(ie=>ce(ie))},[r,c,ce,E,R,i,o,a,l,j]),ue=p.useCallback(J=>{J.preventDefault(),J.persist(),oe(J);const ie=md(J);if(ie&&J.dataTransfer)try{J.dataTransfer.dropEffect="copy"}catch{}return ie&&d&&d(J),!1},[d,E]),xe=p.useCallback(J=>{J.preventDefault(),J.persist(),oe(J);const ie=H.current.filter(Ce=>F.current&&F.current.contains(Ce)),G=ie.indexOf(J.target);G!==-1&&ie.splice(G,1),H.current=ie,!(ie.length>0)&&(D({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),md(J)&&u&&u(J))},[F,u,E]),_e=p.useCallback((J,ie)=>{const G=[],Ce=[];J.forEach(He=>{const[lt,gt]=E2(He,R),[mn,Xt]=T2(He,i,o),Bt=j?j(He):null;if(lt&&mn&&!Bt)G.push(He);else{let an=[gt,Xt];Bt&&(an=an.concat(Bt)),Ce.push({file:He,errors:an.filter(si=>si)})}}),(!a&&G.length>1||a&&l>=1&&G.length>l)&&(G.forEach(He=>{Ce.push({file:He,errors:[$Q]})}),G.splice(0)),D({acceptedFiles:G,fileRejections:Ce,type:"setFiles"}),f&&f(G,Ce,ie),Ce.length>0&&m&&m(Ce,ie),G.length>0&&h&&h(G,ie)},[D,a,R,i,o,l,f,h,m,j]),de=p.useCallback(J=>{J.preventDefault(),J.persist(),oe(J),H.current=[],md(J)&&Promise.resolve(r(J)).then(ie=>{Nf(J)&&!E||_e(ie,J)}).catch(ie=>ce(ie)),D({type:"reset"})},[r,_e,ce,E]),Oe=p.useCallback(()=>{if(N.current){D({type:"openDialog"}),I();const J={multiple:a,types:k};window.showOpenFilePicker(J).then(ie=>r(ie)).then(ie=>{_e(ie,null),D({type:"closeDialog"})}).catch(ie=>{qQ(ie)?(O(ie),D({type:"closeDialog"})):GQ(ie)?(N.current=!1,L.current?(L.current.value=null,L.current.click()):ce(new Error("Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no <input> was provided."))):ce(ie)});return}L.current&&(D({type:"openDialog"}),I(),L.current.value=null,L.current.click())},[D,I,O,S,_e,ce,k,a]),Ye=p.useCallback(J=>{!F.current||!F.current.isEqualNode(J.target)||(J.key===" "||J.key==="Enter"||J.keyCode===32||J.keyCode===13)&&(J.preventDefault(),Oe())},[F,Oe]),jt=p.useCallback(()=>{D({type:"focus"})},[]),mt=p.useCallback(()=>{D({type:"blur"})},[]),at=p.useCallback(()=>{y||(UQ()?setTimeout(Oe,0):Oe())},[y,Oe]),Re=J=>n?null:J,et=J=>x?null:Re(J),ht=J=>C?null:Re(J),oe=J=>{E&&J.stopPropagation()},Q=p.useMemo(()=>(J={})=>{var ie=J,{refKey:G="ref",role:Ce,onKeyDown:He,onFocus:lt,onBlur:gt,onClick:mn,onDragEnter:Xt,onDragOver:Bt,onDragLeave:an,onDrop:si}=ie,ai=Of(ie,["refKey","role","onKeyDown","onFocus","onBlur","onClick","onDragEnter","onDragOver","onDragLeave","onDrop"]);return On(On({onKeyDown:et(io(He,Ye)),onFocus:et(io(lt,jt)),onBlur:et(io(gt,mt)),onClick:Re(io(mn,at)),onDragEnter:ht(io(Xt,Ie)),onDragOver:ht(io(Bt,ue)),onDragLeave:ht(io(an,xe)),onDrop:ht(io(si,de)),role:typeof Ce=="string"&&Ce!==""?Ce:"presentation",[G]:F},!n&&!x?{tabIndex:0}:{}),ai)},[F,Ye,jt,mt,at,Ie,ue,xe,de,x,C,n]),fe=p.useCallback(J=>{J.stopPropagation()},[]),Pe=p.useMemo(()=>(J={})=>{var ie=J,{refKey:G="ref",onChange:Ce,onClick:He}=ie,lt=Of(ie,["refKey","onChange","onClick"]);const gt={accept:R,multiple:a,type:"file",style:{display:"none"},onChange:Re(io(Ce,de)),onClick:Re(io(He,fe)),tabIndex:-1,[G]:L};return On(On({},gt),lt)},[L,t,a,de,n]);return bi(On({},B),{isFocused:_&&!n,getRootProps:Q,getInputProps:Pe,rootRef:F,inputRef:L,open:Re(Oe)})}function XQ(e,t){switch(t.type){case"focus":return bi(On({},e),{isFocused:!0});case"blur":return bi(On({},e),{isFocused:!1});case"openDialog":return bi(On({},Gg),{isFileDialogActive:!0});case"closeDialog":return bi(On({},e),{isFileDialogActive:!1});case"setDraggedFiles":return bi(On({},e),{isDragActive:t.isDragActive,isDragAccept:t.isDragAccept,isDragReject:t.isDragReject});case"setFiles":return bi(On({},e),{acceptedFiles:t.acceptedFiles,fileRejections:t.fileRejections});case"reset":return On({},Gg);default:return e}}function RS(){}const[JQ,ZQ]=Un("Dropzone component was not found in tree");function I0(e){const t=n=>{const{children:r,...o}=V(`Dropzone${G0(e)}`,{},n),i=ZQ(),a=Qo(r)?r:s.jsx("span",{children:r});return i[e]?p.cloneElement(a,o):null};return t.displayName=`@mantine/dropzone/${G0(e)}`,t}const eK=I0("accept"),tK=I0("reject"),nK=I0("idle");var Hc={root:"m_d46a4834",inner:"m_b85f7144",fullScreen:"m_96f6e9ad",dropzone:"m_7946116d"};const rK={loading:!1,multiple:!0,maxSize:1/0,autoFocus:!1,activateOnClick:!0,activateOnDrag:!0,dragEventsBubbling:!0,activateOnKeyboard:!0,useFsAccessApi:!0,variant:"light",rejectColor:"red"},oK=(e,{radius:t,variant:n,acceptColor:r,rejectColor:o})=>{const i=e.variantColorResolver({color:r||e.primaryColor,theme:e,variant:n}),a=e.variantColorResolver({color:o||"red",theme:e,variant:n});return{root:{"--dropzone-radius":it(t),"--dropzone-accept-color":i.color,"--dropzone-accept-bg":i.background,"--dropzone-reject-color":a.color,"--dropzone-reject-bg":a.background}}},es=Y((e,t)=>{const n=V("Dropzone",rK,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,radius:u,disabled:d,loading:f,multiple:h,maxSize:m,accept:g,children:v,onDropAny:S,onDrop:b,onReject:w,openRef:y,name:x,maxFiles:C,autoFocus:E,activateOnClick:T,activateOnDrag:j,dragEventsBubbling:R,activateOnKeyboard:k,onDragEnter:I,onDragLeave:O,onDragOver:F,onFileDialogCancel:L,onFileDialogOpen:B,preventDropOnDocument:D,useFsAccessApi:_,getFilesFromEvent:P,validator:N,rejectColor:$,acceptColor:H,enablePointerEvents:X,loaderProps:ce,inputProps:Ie,mod:ue,...xe}=n,_e=he({name:"Dropzone",classes:Hc,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,vars:c,varsResolver:oK}),{getRootProps:de,getInputProps:Oe,isDragAccept:Ye,isDragReject:jt,open:mt}=I2({onDrop:S,onDropAccepted:b,onDropRejected:w,disabled:d||f,accept:Array.isArray(g)?g.reduce((Re,et)=>({...Re,[et]:[]}),{}):g,multiple:h,maxSize:m,maxFiles:C,autoFocus:E,noClick:!T,noDrag:!j,noDragEventsBubbling:!R,noKeyboard:!k,onDragEnter:I,onDragLeave:O,onDragOver:F,onFileDialogCancel:L,onFileDialogOpen:B,preventDropOnDocument:D,useFsAccessApi:_,validator:N,...P?{getFilesFromEvent:P}:null});Bf(y,mt);const at=!Ye&&!jt;return s.jsx(JQ,{value:{accept:Ye,reject:jt,idle:at},children:s.jsxs(q,{...de(),..._e("root",{focusable:!0}),...xe,mod:[{accept:Ye,reject:jt,idle:at,loading:f,"activate-on-click":T},ue],children:[s.jsx(ex,{visible:f,overlayProps:{radius:u},unstyled:l,loaderProps:ce}),s.jsx("input",{...Oe(Ie),name:x}),s.jsx("div",{..._e("inner"),ref:t,"data-enable-pointer-events":X||void 0,children:v})]})})});es.classes=Hc;es.displayName="@mantine/dropzone/Dropzone";es.Accept=eK;es.Idle=nK;es.Reject=tK;const iK={loading:!1,maxSize:1/0,activateOnClick:!1,activateOnDrag:!0,dragEventsBubbling:!0,activateOnKeyboard:!0,active:!0,zIndex:Jr("max"),withinPortal:!0},A0=Y((e,t)=>{const n=V("DropzoneFullScreen",iK,e),{classNames:r,className:o,style:i,styles:a,unstyled:l,vars:c,active:u,onDrop:d,onReject:f,zIndex:h,withinPortal:m,portalProps:g,...v}=n,S=he({name:"DropzoneFullScreen",classes:Hc,props:n,className:o,style:i,classNames:r,styles:a,unstyled:l,rootSelector:"fullScreen"}),{resolvedClassNames:b,resolvedStyles:w}=Gc({classNames:r,styles:a,props:n}),[y,x]=p.useState(0),[C,{open:E,close:T}]=av(!1),j=k=>{var I;(I=k.dataTransfer)!=null&&I.types.includes("Files")&&(x(O=>O+1),E())},R=()=>{x(k=>k-1)};return p.useEffect(()=>{y===0&&T()},[y]),p.useEffect(()=>{if(u)return document.addEventListener("dragenter",j,!1),document.addEventListener("dragleave",R,!1),()=>{document.removeEventListener("dragenter",j,!1),document.removeEventListener("dragleave",R,!1)}},[u]),s.jsx(Vs,{...g,withinPortal:m,children:s.jsx(q,{...S("fullScreen",{style:{opacity:C?1:0,pointerEvents:C?"all":"none",zIndex:h}}),ref:t,children:s.jsx(es,{...v,classNames:b,styles:w,unstyled:l,className:Hc.dropzone,onDrop:k=>{d==null||d(k),T(),x(0)},onReject:k=>{f==null||f(k),T(),x(0)}})})})});A0.classes=Hc;A0.displayName="@mantine/dropzone/DropzoneFullScreen";es.FullScreen=A0;const gd=es,sK='{"resourceType": "Bundle"}';function cm({id:e,title:t,message:n,color:r,icon:o,withCloseButton:i=!1,method:a="show",loading:l}){po[a]({id:e,loading:l,title:t,message:n,color:r,icon:o,withCloseButton:i,autoClose:!1})}function aK(){const e=At(),t=le(),[n,r]=p.useState({}),o=p.useCallback(async(l,c)=>{const u="batch-upload";cm({id:u,title:"Batch Upload in Progress",message:"Your batch data is being uploaded. This may take a moment...",method:"show",loading:!0});try{r({});let d=JSON.parse(l);d.type!=="batch"&&d.type!=="transaction"&&(d=Ek(d));const f=await t.executeBatch(d);r(h=>({...h,[c]:f})),cm({id:u,title:"Batch Upload Successful",message:"Your batch data was successfully uploaded.",color:"green",method:"update",icon:s.jsx(Js,{size:"1rem"}),withCloseButton:!0})}catch(d){cm({id:u,title:"Batch Upload Failed",color:"red",message:Ae(d),method:"update",icon:s.jsx(Ef,{size:"1rem"}),withCloseButton:!0})}},[t]),i=p.useCallback(async l=>{for(const c of l){const u=new FileReader;u.onload=d=>{var f;return o((f=d.target)==null?void 0:f.result,c.name)},u.readAsText(c)}},[o]),a=p.useCallback(async l=>{await o(l.input,"JSON Data")},[o]);return s.jsxs(Me,{children:[s.jsx(ve,{children:"Batch Create"}),s.jsxs("p",{children:["Use this page to create, read, or update multiple resources. For more details, see ",s.jsx("a",{href:"https://www.hl7.org/fhir/http.html#transaction",children:"FHIR Batch and Transaction"}),"."]}),Object.keys(n).length===0&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{children:"Input"}),s.jsxs(Je,{defaultValue:"upload",children:[s.jsxs(Je.List,{children:[s.jsx(Je.Tab,{value:"upload",children:"File Upload"}),s.jsx(Je.Tab,{value:"json",children:"JSON"})]}),s.jsx(Je.Panel,{value:"upload",pt:"xs",children:s.jsx(gd,{onDrop:i,accept:["application/json"],children:s.jsxs(te,{justify:"center",gap:"xl",style:{minHeight:220,pointerEvents:"none"},children:[s.jsx(gd.Accept,{children:s.jsx(Aw,{size:50,stroke:1.5,color:e.colors[e.primaryColor][5]})}),s.jsx(gd.Reject,{children:s.jsx(Ef,{size:50,stroke:1.5,color:e.colors.red[5]})}),s.jsx(gd.Idle,{children:s.jsx(Aw,{size:50,stroke:1.5})}),s.jsxs("div",{children:[s.jsx(me,{size:"xl",inline:!0,children:"Drag files here or click to select files"}),s.jsx(me,{size:"sm",color:"dimmed",inline:!0,mt:7,children:"Attach as many files as you like"})]})]})})}),s.jsx(Je.Panel,{value:"json",pt:"xs",children:s.jsxs(qe,{onSubmit:a,children:[s.jsx(vl,{"data-testid":"batch-input",name:"input",autosize:!0,minRows:20,defaultValue:sK,deserialize:JSON.parse}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(ae,{type:"submit",children:"Submit"})})]})})]})]}),Object.keys(n).length>0&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{children:"Output"}),s.jsxs(Je,{defaultValue:Object.keys(n)[0],children:[s.jsx(Je.List,{children:Object.keys(n).map(l=>s.jsx(Je.Tab,{value:l,children:l},l))}),Object.keys(n).map(l=>s.jsx(Je.Panel,{value:l,children:s.jsx("pre",{style:{border:"1px solid #888"},children:JSON.stringify(n[l],void 0,2)})},l))]}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(ae,{onClick:()=>r({}),children:"Start over"})})]})]})}function lK(){const{resourceType:e}=st(),n=(Object.fromEntries(new URLSearchParams(location.search).entries()).ids||"").split(",").filter(o=>!!o),[r]=al("Questionnaire",`subject-type=${e}`);return r?r.length===0?s.jsxs(Me,{children:[s.jsxs(ve,{children:["No apps for ",e]}),s.jsx(We,{to:`/${e}`,children:"Return to search page"})]}):s.jsx(Me,{children:s.jsx("div",{children:r.map(o=>s.jsxs("div",{children:[s.jsx("h3",{children:s.jsx(We,{to:`/forms/${o.id}?subject=`+n.map(i=>`${e}/${i}`).join(","),children:o.name})}),s.jsx("p",{children:o.description})]},o.id))})}):s.jsx(Yr,{})}function cK(){const e=le(),[t,n]=p.useState(),[r,o]=p.useState(!1);return s.jsx(Me,{width:450,children:s.jsxs(qe,{onSubmit:i=>{n(void 0),e.post("auth/changepassword",i).then(()=>o(!0)).catch(a=>n(ft(a)))},children:[s.jsxs(vn,{style:{flexDirection:"column"},children:[s.jsx(to,{size:32}),s.jsx(ve,{children:"Change password"})]}),!r&&s.jsxs($e,{gap:"xl",mt:"xl",children:[s.jsx(Hr,{name:"oldPassword",label:"Old password",required:!0,autoFocus:!0,error:Qe(t,"oldPassword")}),s.jsx(Hr,{name:"newPassword",label:"New password",required:!0,error:Qe(t,"newPassword")}),s.jsx(Hr,{name:"confirmPassword",label:"Confirm new password",required:!0,error:Qe(t,"confirmPassword")}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(ae,{type:"submit",children:"Change password"})})]}),r&&s.jsx("div",{"data-testid":"success",children:"Password changed successfully"})]})})}const Qg=["Form","JSON","Profiles"],uK=["Profiles"],um=Qg[0].toLowerCase();function dK(){const e=Gt(),t=At(),{resourceType:n}=st(),[r,o]=p.useState(()=>{const a=window.location.pathname.split("/").pop();return a&&Qg.map(l=>l.toLowerCase()).includes(a)?a:um});function i(a){a||(a=um),o(a),e(`/${n}/new/${a}`)}return s.jsxs(s.Fragment,{children:[s.jsxs(Xn,{children:[s.jsxs(me,{p:"md",fw:500,children:["New ",n]}),s.jsx(_r,{children:s.jsx(Je,{defaultValue:um,value:r,onChange:i,children:s.jsx(Je.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:Qg.map(a=>s.jsx(Je.Tab,{value:a.toLowerCase(),px:"md",children:uK.includes(a)?s.jsxs(te,{gap:"xs",wrap:"nowrap",children:[a,s.jsx(iu,{color:t.primaryColor,size:"sm",children:"Beta"})]}):a},a))})})})]}),s.jsx(R0,{})]})}function fK(){return s.jsx(Me,{children:s.jsxs($e,{children:[s.jsx(ve,{order:1,children:"Unexpected Error"}),s.jsx(me,{children:"We're sorry, something went wrong."}),s.jsxs(me,{children:["Please contact ",s.jsx(Ke,{href:"mailto:support@medplum.com",children:"support"})," for assistance."]})]})})}const hK="_root_1fbwr_1",pK="_entry_1fbwr_8",mK="_key_1fbwr_13",gK="_value_1fbwr_20",np={root:hK,entry:pK,key:mK,value:gK};function ze(e){return s.jsx(_r,{children:s.jsx("div",{className:np.root,children:e.children})})}ze.Entry=function(t){return s.jsx("div",{className:np.entry,children:t.children})};ze.Key=function(t){return s.jsx("div",{className:np.key,children:t.children})};ze.Value=function(t){return s.jsx("div",{className:np.value,children:t.children})};function vK(e){if(e.gender==="male")return"blue";if(e.gender==="female")return"pink"}function A2(e){var n,r;const t=St(e.patient);return t?s.jsxs(ze,{children:[s.jsx(Ji,{value:t,size:"lg",color:vK(t)}),s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Name"}),s.jsx(ze.Value,{children:s.jsx(We,{to:t,fw:500,children:t.name?s.jsx(t0,{value:t.name[0],options:{use:!1}}):"[blank]"})})]}),t.birthDate&&s.jsxs(s.Fragment,{children:[s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"DoB"}),s.jsx(ze.Value,{children:t.birthDate})]}),s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Age"}),s.jsx(ze.Value,{children:h6(t.birthDate)})]})]}),t.gender&&s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Gender"}),s.jsx(ze.Value,{children:t.gender})]}),t.address&&s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"State"}),s.jsx(ze.Value,{children:(n=t.address[0])==null?void 0:n.state})]}),(r=t.identifier)==null?void 0:r.map(o=>s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:o==null?void 0:o.system}),s.jsx(ze.Value,{children:o==null?void 0:o.value})]},`${o==null?void 0:o.system}-${o==null?void 0:o.value}`))]}):null}function N2(e){const t=St(e.resource);if(!t)return null;const n=[{key:"Type",value:s.jsx(We,{to:`/${t.resourceType}`,children:t.resourceType})}];function r(a,l){a&&l&&n.push({key:a,value:l})}function o(a){a&&r(a.system,a.value)}function i(a,l){Array.isArray(l)?l.forEach(c=>i(a,c)):typeof l=="string"?r(a,l):l&&(Array.isArray(l.coding)?r(a,l.coding.map(c=>c.display||c.code).join(", ")):r(a,l.text))}if("name"in t){const a=qo(t);a!==rt(t)&&r("Name",a)}return"category"in t&&i("Category",t.category),t.resourceType!=="Bot"&&"code"in t&&i("Code",t.code),"identifier"in t&&(Array.isArray(t.identifier)?t.identifier.forEach(o):o(t.identifier)),n.length===1&&n.push({key:"ID",value:t.id}),s.jsx(ze,{children:n.map(a=>s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:a.key}),s.jsx(ze.Value,{children:a.value})]},`${a.key}-${a.value}`))})}function N0(e){if(e.resourceType==="Patient")return e;if(e.resourceType==="DiagnosticReport"||e.resourceType==="Encounter"||e.resourceType==="Observation"||e.resourceType==="ServiceRequest")return e.subject}function yK(e){var t;if(e.resourceType==="Specimen")return e;if(e.resourceType==="Observation")return e.specimen;if(e.resourceType==="DiagnosticReport"||e.resourceType==="ServiceRequest")return(t=e.specimen)==null?void 0:t[0]}function Ld(e,t){return new Promise((n,r)=>{var i;const o=new MessageChannel;o.port1.onmessage=({data:a})=>{o.port1.close(),a.error?r(a.error):n(a.result)},(i=e.contentWindow)==null||i.postMessage(t,"https://codeeditor.medplum.com",[o.port2])})}function ts(e){var t;return il((t=e.getActiveLogin())==null?void 0:t.project)}function xK(e,t){const n=new Blob([e],{type:rn.JSON}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r;const i=new Date().toISOString().replace(/\D/g,"");o.download=`${i}.json`,document.body.appendChild(o),o.click(),URL.revokeObjectURL(r)}function bK(){const{id:e}=st(),t=ii(),r=Object.fromEntries(new URLSearchParams(t.search).entries()).subject,o=le(),[i,a]=p.useState(!0),[l,c]=p.useState(),[u,d]=p.useState(),[f,h]=p.useState(),[m,g]=p.useState(),[v,S]=p.useState();if(p.useEffect(()=>{const y={resourceType:"Bundle",type:"batch",entry:[{request:{method:"GET",url:`Questionnaire/${e}`}}]};if(r){const x=r.split(",").filter(C=>!!C);x.length===1&&y.entry.push({request:{method:"GET",url:x[0]}}),d(x)}o.executeBatch(y).then(x=>{var C,E,T,j,R,k,I,O;((T=(E=(C=x.entry)==null?void 0:C[0])==null?void 0:E.response)==null?void 0:T.status)!=="200"?g((k=(R=(j=x.entry)==null?void 0:j[0])==null?void 0:R.response)==null?void 0:k.outcome):(c((I=x.entry[0])==null?void 0:I.resource),h((O=x.entry[1])==null?void 0:O.resource)),a(!1)}).catch(x=>{g(x),a(!1)})},[o,e,r]),m)return s.jsx(Me,{children:s.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)})});if(v)return s.jsxs(Me,{children:[s.jsx(ve,{children:l==null?void 0:l.title}),s.jsx("p",{children:"Your response has been recorded."}),s.jsxs("ul",{children:[v.length===1&&s.jsx("li",{children:s.jsx(We,{to:v[0],children:"Review your answers"})}),v.length>1&&s.jsxs("li",{children:["Review your answers:",s.jsx("ul",{children:v.map(y=>s.jsx("li",{children:s.jsx(We,{to:y,children:rt(y)})},y.id))})]}),f&&s.jsx("li",{children:s.jsxs(We,{to:f,children:["Back to ",qo(f)]})}),s.jsx("li",{children:s.jsx(We,{to:"/",children:"Go back home"})})]})]});if(i||!l)return s.jsx(Yr,{});const b=f&&N0(f);return s.jsxs(s.Fragment,{children:[s.jsxs(Xn,{shadow:"xs",radius:0,children:[b&&s.jsx(A2,{patient:b}),f&&f.resourceType!=="Patient"&&s.jsx(N2,{resource:f}),s.jsx(q,{px:"xl",py:"md",children:s.jsxs(me,{children:[qo(l),u&&u.length>1&&s.jsxs(s.Fragment,{children:[" (for ",u.length," resources)"]})]})})]}),s.jsx(Me,{children:s.jsx(KR,{questionnaire:l,subject:f&&Tt(f),onSubmit:w})})]});async function w(y){const x=[];if(!u||u.length===0)x.push(await o.createResource(y));else for(const C of u)x.push(await o.createResource({...y,subject:{reference:C}}));S(x)}}const wK="_paper_unw9o_1",SK={paper:wK},jK={Bot:"/admin/bots/new",ClientApplication:"/admin/clients/new"};function M2(e,t){const n=e.resourceType||CK(t),r=e.fields??EK(n),o=e.filters??(e.resourceType?void 0:TK(n)),i=e.sortRules??PK(n),a=e.offset??0,l=e.count??zh;return{...e,resourceType:n,fields:r,filters:o,sortRules:i,offset:a,count:l}}function CK(e){var t,n;return localStorage.getItem("defaultResourceType")??((n=(t=e==null?void 0:e.option)==null?void 0:t.find(r=>r.id==="defaultResourceType"))==null?void 0:n.valueString)??"Patient"}function EK(e){const t=M0(e);if(t!=null&&t.fields)return t.fields;const n=["id","_lastUpdated"];switch(e){case"Patient":n.push("name","birthDate","gender");break;case"AccessPolicy":case"Bot":case"ClientApplication":case"Practitioner":case"Project":case"Organization":case"Questionnaire":case"UserConfiguration":n.push("name");break;case"CodeSystem":case"ValueSet":n.push("name","title","status");break;case"Condition":n.push("subject","code","clinicalStatus");break;case"Device":n.push("manufacturer","deviceName","patient");break;case"DeviceDefinition":n.push("manufacturer[x]","deviceName");break;case"DeviceRequest":n.push("code[x]","subject");break;case"DiagnosticReport":case"Observation":n.push("subject","code","status");break;case"Encounter":n.push("subject");break;case"ServiceRequest":n.push("subject","code","status","orderDetail");break;case"Subscription":n.push("criteria");break;case"User":n.push("email");break}return n}function TK(e){var t;return(t=M0(e))==null?void 0:t.filters}function PK(e){const t=M0(e);return t!=null&&t.sortRules?t.sortRules:[{code:"_lastUpdated",descending:!0}]}function M0(e){const t=localStorage.getItem(e+"-defaultSearch");return t?JSON.parse(t):void 0}function kK(e){localStorage.setItem("defaultResourceType",e.resourceType),localStorage.setItem(e.resourceType+"-defaultSearch",JSON.stringify(e))}async function RK(e,t){const n={resourceType:e.resourceType,count:1e3,offset:0,filters:e.filters},r=M2(n,t.getUserConfiguration()),o=await t.search(r.resourceType,Ia({...r,total:"accurate",fields:void 0}));return Ek(o)}function _S(){const e=le(),t=Gt(),n=ii(),[r,o]=p.useState();return p.useEffect(()=>{const i=bk(n.pathname+n.search),a=M2(i,e.getUserConfiguration());n.pathname===`/${a.resourceType}`&&n.search===Ia(a)?(kK(a),o(a)):t(`/${a.resourceType}${Ia(a)}`)},[e,t,n]),!(r!=null&&r.resourceType)||!r.fields||r.fields.length===0?s.jsx(Yr,{}):s.jsx(Xn,{shadow:"xs",m:"md",p:"xs",className:SK.paper,children:s.jsx(ju,{checkboxesEnabled:!0,search:r,onClick:i=>t(`/${i.resource.resourceType}/${i.resource.id}`),onAuxClick:i=>window.open(`/${i.resource.resourceType}/${i.resource.id}`,"_blank"),onChange:i=>{t(`/${r.resourceType}${Ia(i.definition)}`)},onNew:()=>{t(jK[r.resourceType]??`/${r.resourceType}/new`)},onExportCsv:()=>{const i=e.fhirUrl(r.resourceType,"$csv")+Ia(r);e.download(i).then(a=>{window.open(window.URL.createObjectURL(a),"_blank")}).catch(a=>ge({color:"red",message:Ae(a),autoClose:!1}))},onExportTransactionBundle:async()=>{RK(r,e).then(i=>xK(JSON.stringify(i,void 0,2))).catch(i=>ge({color:"red",message:Ae(i),autoClose:!1}))},onDelete:i=>{window.confirm("Are you sure you want to delete these resources?")&&(e.invalidateSearches(r.resourceType),e.executeBatch({resourceType:"Bundle",type:"batch",entry:i.map(a=>({request:{method:"DELETE",url:`${r.resourceType}/${a}`}}))}).then(()=>o({...r})).catch(a=>ge({color:"red",message:Ae(a),autoClose:!1})))},onBulk:i=>{t(`/bulk/${r.resourceType}?ids=${i.join(",")}`)}})})}function _K(){const e=le(),[t,n]=p.useState(),[r,o]=p.useState(void 0);p.useEffect(()=>{e.get("auth/mfa/status").then(l=>{n(l.enrollQrCode),o(l.enrolled)}).catch(l=>ge({color:"red",message:Ae(l),autoClose:!1}))},[e]);const i=p.useCallback(l=>{e.post("auth/mfa/enroll",l).then(()=>{o(!0),ge({color:"green",message:"Success"})}).catch(c=>ge({color:"red",message:Ae(c),autoClose:!1}))},[e]),a=p.useCallback(()=>{e.post("auth/mfa/disable",{}).catch(console.log)},[e]);return r===void 0?null:r?s.jsx(Me,{children:s.jsxs(te,{children:[s.jsx(ve,{children:"MFA is enabled"}),s.jsx(ae,{onClick:a,children:"Disable MFA"})]})}):s.jsx(Me,{width:400,children:s.jsxs(qe,{onSubmit:i,children:[s.jsx(ve,{children:"Multi Factor Auth Setup"}),s.jsx(vn,{children:s.jsx("img",{src:t})}),s.jsx(ye,{name:"token",label:"Code"}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(ae,{type:"submit",children:"Enroll"})})]})})}const dm={BASE_URL:"/",DEV:!1,GOOGLE_CLIENT_ID:"__GOOGLE_CLIENT_ID__",MEDPLUM_BASE_URL:"__MEDPLUM_BASE_URL__",MEDPLUM_CLIENT_ID:"__MEDPLUM_CLIENT_ID__",MEDPLUM_REGISTER_ENABLED:"__MEDPLUM_REGISTER_ENABLED__",MEDPLUM_VERSION:"3.2.16-a2ededb30",MODE:"production",PROD:!0,RECAPTCHA_SITE_KEY:"__RECAPTCHA_SITE_KEY__",SSR:!1},Kg={baseUrl:"__MEDPLUM_BASE_URL__",clientId:"__MEDPLUM_CLIENT_ID__",googleClientId:"__GOOGLE_CLIENT_ID__",recaptchaSiteKey:"__RECAPTCHA_SITE_KEY__",registerEnabled:"__MEDPLUM_REGISTER_ENABLED__",awsTextractEnabled:dm==null?void 0:dm.MEDPLUM_AWS_TEXTRACT_ENABLED};function Pu(){return Kg}function O2(){return L2("registerEnabled")}function DK(){return L2("awsTextractEnabled")}function L2(e){try{return Kg[e]!==!1&&Kg[e]!=="false"}catch{return!0}}function IK(){const e=Gt(),[t]=_0(),n=t.get("client_id");if(!n)return null;const r=t.get("scope")||"openid";function o(i){const a=new URL(t.get("redirect_uri"));for(const l of["scope","state","nonce"])t.has(l)&&a.searchParams.set(l,t.get(l));a.searchParams.set("code",i),window.location.assign(a.toString())}return s.jsxs(o2,{onCode:o,onForgotPassword:()=>e("/resetpassword"),onRegister:()=>e("/register"),googleClientId:Pu().googleClientId,clientId:n||void 0,redirectUri:t.get("redirect_uri")||void 0,scope:r,nonce:t.get("nonce")||void 0,launch:t.get("launch")||void 0,codeChallenge:t.get("code_challenge")||void 0,codeChallengeMethod:t.get("code_challenge_method")||void 0,chooseScopes:r!=="openid",children:[s.jsx(to,{size:32}),s.jsx(ve,{children:"Sign in to Medplum"})]})}function AK(){const e=le(),t=Gt(),n=Pu();return p.useEffect(()=>{e.getProfile()&&t("/signin?project=new")},[e,t]),O2()?s.jsxs(kq,{type:"project",projectId:"new",onSuccess:()=>t("/"),googleClientId:n.googleClientId,recaptchaSiteKey:n.recaptchaSiteKey,children:[s.jsx(to,{size:32}),s.jsx(ve,{children:"Create a new account"})]}):s.jsx(Me,{width:450,children:s.jsx(Yi,{icon:s.jsx(El,{size:16}),title:"New projects disabled",color:"red",children:"New projects are disabled on this server."})})}function NK(){const e=Gt(),t=le(),[n,r]=p.useState(),[o,i]=p.useState(!1),a=Pu().recaptchaSiteKey;return p.useEffect(()=>{a&&n2(a)},[a]),s.jsx(Me,{width:450,children:s.jsxs(qe,{onSubmit:async l=>{let c="";a&&(c=await r2(a)),t.post("auth/resetpassword",{...l,recaptchaToken:c}).then(()=>i(!0)).catch(u=>r(ft(u)))},children:[s.jsxs($e,{gap:"lg",mb:"xl",align:"center",children:[s.jsx(to,{size:32}),s.jsx(ve,{children:"Medplum Password Reset"})]}),s.jsxs($e,{gap:"xl",children:[s.jsx(Ar,{issues:xu(n,void 0)}),!o&&s.jsxs(s.Fragment,{children:[s.jsx(ye,{name:"email",type:"email",label:"Email",required:!0,autoFocus:!0,error:Qe(n,"email")}),s.jsxs(te,{justify:"space-between",mt:"xl",wrap:"nowrap",children:[s.jsx(Ke,{component:"button",type:"button",color:"dimmed",onClick:()=>e("/register"),size:"xs",children:"Register"}),s.jsx(ae,{type:"submit",children:"Reset password"})]})]}),o&&s.jsx("div",{children:"If the account exists on our system, a password reset email will be sent."})]})]})})}function MK(){var i;const e=Gt(),t=le(),[n,r]=p.useState();p.useEffect(()=>{t.get("auth/me",{cache:"no-cache"}).then(r).catch(a=>ge({color:"red",message:Ae(a),autoClose:!1}))},[t]);function o(a){t.post("auth/revoke",{loginId:a}).then(()=>t.get("auth/me",{cache:"no-cache"})).then(r).then(()=>ge({color:"green",message:"Login revoked"})).catch(l=>ge({color:"red",message:Ae(l),autoClose:!1}))}return n?s.jsxs(s.Fragment,{children:[s.jsxs(Me,{children:[s.jsx(ve,{children:"Security"}),s.jsxs(i0,{children:[s.jsx(Oo,{term:"ID",children:s.jsx(Ke,{href:`/${rt(n.profile)}`,children:n.profile.id})}),s.jsx(Oo,{term:"Resource Type",children:n.profile.resourceType}),s.jsx(Oo,{term:"Name",children:pu((i=n.profile.name)==null?void 0:i[0])})]})]}),s.jsxs(Me,{children:[s.jsx(ve,{children:"Sessions"}),s.jsxs(pe,{children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"OS"}),s.jsx("th",{children:"Browser"}),s.jsx("th",{children:"IP Address"}),s.jsx("th",{children:"Auth Method"}),s.jsx("th",{children:"Last Updated"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:n.security.sessions.map(a=>s.jsxs("tr",{children:[s.jsx("td",{children:a.os}),s.jsx("td",{children:a.browser}),s.jsx("td",{children:a.remoteAddress}),s.jsx("td",{children:a.authMethod}),s.jsx("td",{children:zn(a.lastUpdated)}),s.jsx("td",{children:s.jsx(Ke,{href:"#",onClick:()=>o(a.id),children:"Revoke"})})]},a.id))})]})]}),s.jsxs(Me,{children:[s.jsx(ve,{children:"Password"}),s.jsx(ae,{onClick:()=>e("/changepassword"),children:"Change password"})]}),s.jsxs(Me,{children:[s.jsx(ve,{children:"Multi Factor Auth"}),s.jsxs("p",{children:["Enrolled: ",n.security.mfaEnrolled.toString()]}),!n.security.mfaEnrolled&&s.jsx(ae,{onClick:()=>e("/mfa"),children:"Enroll"})]})]}):null}function OK(){const{id:e,secret:t}=st(),n=le(),[r,o]=p.useState(),[i,a]=p.useState(!1),l=xu(r,void 0);return s.jsxs(Me,{width:450,children:[s.jsx(Ar,{issues:l}),s.jsxs(qe,{onSubmit:c=>{if(c.password!==c.confirmPassword){o(Oi("Passwords do not match","confirmPassword"));return}o(void 0);const u={id:e,secret:t,password:c.password};n.post("auth/setpassword",u).then(()=>a(!0)).catch(d=>o(ft(d)))},children:[s.jsxs(vn,{style:{flexDirection:"column"},children:[s.jsx(to,{size:32}),s.jsx(ve,{children:"Set password"})]}),!i&&s.jsxs($e,{children:[s.jsx(Hr,{name:"password",label:"New password",required:!0,error:Qe(r,"password")}),s.jsx(Hr,{name:"confirmPassword",label:"Confirm new password",required:!0,error:Qe(r,"confirmPassword")}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(ae,{type:"submit",children:"Set password"})})]}),i&&s.jsxs("div",{"data-testid":"success",children:["Password set. You can now ",s.jsx(We,{to:"/signin",children:"sign in"}),"."]})]})]})}function LK(){const e=Hh(),t=Gt(),[n]=_0(),r=Pu(),o=p.useCallback(()=>{const i=n.get("next");t(i!=null&&i.startsWith("/")?i:"/")},[n,t]);return p.useEffect(()=>{e&&n.has("next")&&o()},[e,n,o]),s.jsxs(o2,{onSuccess:()=>o(),onForgotPassword:()=>t("/resetpassword"),onRegister:O2()?()=>t("/register"):void 0,googleClientId:r.googleClientId,login:n.get("login")||void 0,projectId:n.get("project")||void 0,children:[s.jsx(to,{size:32}),s.jsx(ve,{children:"Sign in to Medplum"}),n.get("project")==="new"&&s.jsx("div",{children:"Sign in again to create a new project"})]})}function $K(){const e=Gt(),t=ii(),[n,r]=p.useState(),[o,i]=p.useState(),[a,l]=p.useState();return p.useEffect(()=>{const c=Object.fromEntries(new URLSearchParams(t.search).entries());r(c.resourceType),i(c.query),l(JSON.parse(c.fields))},[t]),!n||!o||!a?null:s.jsx(IW,{resourceType:n,checkboxesEnabled:!0,query:o,fields:a,onClick:c=>e(`/${n}/${c.resource.id}`),onAuxClick:c=>window.open(`/${n}/${c.resource.id}`,"_blank"),onBulk:c=>{e(`/bulk/${n}?ids=${c.join(",")}`)}})}function rp(e){const t=le(),n=ts(t),r=Gt(),[o,i]=p.useState({resourceType:"ProjectMembership",filters:[{code:"project",operator:re.EQUALS,value:"Project/"+n},{code:"profile-type",operator:re.EQUALS,value:e.resourceType}],fields:e.fields,count:100});return s.jsx(ju,{search:o,onClick:a=>r(`/admin/members/${a.resource.id}`),onChange:a=>i(a.definition),hideFilters:!0,hideToolbar:!0})}function FK(){return s.jsxs(s.Fragment,{children:[s.jsx(ve,{children:"Bots"}),s.jsx(rp,{resourceType:"Bot",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(te,{justify:"flex-end",children:s.jsx(We,{to:"/admin/bots/new",children:"Create new bot"})})]})}function zK(){return s.jsxs(s.Fragment,{children:[s.jsx(ve,{children:"Clients"}),s.jsx(rp,{resourceType:"ClientApplication",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(te,{justify:"flex-end",children:s.jsx(We,{to:"/admin/clients/new",children:"Create new client"})})]})}function op(e){return s.jsx(Zs,{resourceType:"AccessPolicy",name:"accessPolicy",defaultValue:e.defaultValue,placeholder:"Access Policy",onChange:t=>{ri(t)?e.onChange(Tt(t)):e.onChange(void 0)}})}function BK(){const e=le(),t=ts(e),[n,r]=p.useState(""),[o,i]=p.useState(""),[a,l]=p.useState(),[c,u]=p.useState(),[d,f]=p.useState(void 0);return s.jsxs(s.Fragment,{children:[s.jsx(ve,{children:"Create new Bot"}),s.jsxs(qe,{onSubmit:()=>{const h={name:n,description:o,accessPolicy:a};e.post("admin/projects/"+t+"/bot",h).then(m=>{e.invalidateSearches("Bot"),e.invalidateSearches("ProjectMembership"),f(m),ge({color:"green",message:"Bot created"})}).catch(m=>{ge({color:"red",message:Ae(m),autoClose:!1}),u(ft(m))})},children:[!d&&s.jsxs($e,{children:[s.jsx(yt,{title:"Name",htmlFor:"name",outcome:c,children:s.jsx(ye,{id:"name",name:"name",required:!0,autoFocus:!0,onChange:h=>r(h.currentTarget.value),error:Qe(c,"name")})}),s.jsx(yt,{title:"Description",htmlFor:"description",outcome:c,children:s.jsx(ye,{id:"description",name:"description",onChange:h=>i(h.currentTarget.value),error:Qe(c,"description")})}),s.jsx(yt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:c,children:s.jsx(op,{name:"accessPolicy",onChange:l})}),s.jsx(te,{justify:"flex-end",children:s.jsx(ae,{type:"submit",children:"Create Bot"})})]}),d&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(me,{children:"Bot created"}),s.jsxs($n,{children:[s.jsx($n.Item,{children:s.jsx(We,{to:d,children:"Go to new bot"})}),s.jsx($n.Item,{children:s.jsx(We,{to:"/admin/bots",children:"Back to bots list"})})]})]})]})]})}function UK(){const e=le(),t=ts(e),[n,r]=p.useState(""),[o,i]=p.useState(""),[a,l]=p.useState(""),[c,u]=p.useState(),[d,f]=p.useState(),[h,m]=p.useState(void 0);return s.jsxs(s.Fragment,{children:[s.jsx(ve,{children:"Create new Client"}),s.jsxs(qe,{onSubmit:()=>{const g={name:n,description:o,redirectUri:a,accessPolicy:c};e.post("admin/projects/"+t+"/client",g).then(v=>{e.invalidateSearches("ClientApplication"),e.invalidateSearches("ProjectMembership"),m(v),ge({color:"green",message:"Client created"})}).catch(v=>{ge({color:"red",message:Ae(v),autoClose:!1}),f(ft(v))})},children:[!h&&s.jsxs($e,{children:[s.jsx(yt,{title:"Name",htmlFor:"name",outcome:d,children:s.jsx(ye,{id:"name",name:"name",required:!0,autoFocus:!0,onChange:g=>r(g.currentTarget.value),error:Qe(d,"name")})}),s.jsx(yt,{title:"Description",htmlFor:"description",outcome:d,children:s.jsx(ye,{id:"description",name:"description",onChange:g=>i(g.currentTarget.value),error:Qe(d,"description")})}),s.jsx(yt,{title:"Redirect URI",htmlFor:"redirectUri",outcome:d,children:s.jsx(ye,{id:"redirectUri",name:"redirectUri",onChange:g=>l(g.currentTarget.value),error:Qe(d,"redirectUri")})}),s.jsx(yt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:d,children:s.jsx(op,{name:"accessPolicy",onChange:u})}),s.jsx(te,{justify:"flex-end",children:s.jsx(ae,{type:"submit",children:"Create Client"})})]}),h&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(me,{children:"Client created"}),s.jsxs($n,{children:[s.jsx($n.Item,{children:s.jsx(We,{to:h,children:"Go to new client"})}),s.jsx($n.Item,{children:s.jsx(We,{to:"/admin/clients",children:"Back to clients list"})})]})]})]})]})}function VK(e){return s.jsx(Zs,{resourceType:"UserConfiguration",name:"userConfiguration",defaultValue:e.defaultValue,placeholder:"User Configuration",onChange:t=>{ri(t)?e.onChange(Tt(t)):e.onChange(void 0)}})}function WK(){const{membershipId:e}=st(),t=le(),n=ts(t),r=Gt(),o=t.get(`admin/projects/${n}/members/${e}`).read(),[i,a]=p.useState(o.accessPolicy),[l,c]=p.useState(o.userConfiguration),[u,d]=p.useState(o.admin),[f,h]=p.useState(),[m,g]=p.useState(!1);function v(){window.confirm("Are you sure?")&&t.delete(`admin/projects/${n}/members/${e}`).then(()=>t.get(`admin/projects/${n}`,{cache:"no-cache"})).then(()=>r("/admin/project")).catch(S=>h(ft(S)))}return s.jsxs(s.Fragment,{children:[s.jsx(ve,{children:"Edit membership"}),s.jsx("h3",{children:s.jsx(Ha,{value:o.profile,link:!0})}),s.jsxs(qe,{onSubmit:()=>{const S={...o,accessPolicy:i,userConfiguration:l,admin:u};t.post(`admin/projects/${n}/members/${e}`,S).then(()=>g(!0)).catch(b=>h(ft(b)))},children:[!m&&s.jsxs($e,{children:[s.jsx(yt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:f,children:s.jsx(op,{name:"accessPolicy",defaultValue:i,onChange:a})}),s.jsx(yt,{title:"User Configuration",htmlFor:"userConfiguration",outcome:f,children:s.jsx(VK,{name:"userConfiguration",defaultValue:l,onChange:c})}),s.jsx(yt,{title:"Admin",htmlFor:"admin",outcome:f,children:s.jsx(Dn,{id:"admin",name:"admin",defaultChecked:u,onChange:S=>d(S.currentTarget.checked)})}),s.jsxs(te,{justify:"flex-end",mt:"xl",children:[s.jsx(ae,{type:"submit",children:"Save"}),s.jsx(ae,{type:"button",color:"red",variant:"outline",onClick:v,children:"Remove user"})]})]}),m&&s.jsxs("div",{"data-testid":"success",children:[s.jsx("p",{children:"User updated"}),s.jsx("pre",{children:JSON.stringify(f,void 0,2)}),s.jsxs("p",{children:["Click ",s.jsx(We,{to:"/admin/project",children:"here"})," to return to the project admin page."]})]})]})]})}function HK(){const e=le(),[t,n]=p.useState(e.getProject()),[r,o]=p.useState(),[i,a]=p.useState(),[l,c]=p.useState(!1),[u,d]=p.useState(void 0),f=p.useCallback(h=>{const m={resourceType:h.resourceType,firstName:h.firstName,lastName:h.lastName,email:h.email,sendEmail:h.sendEmail==="on",accessPolicy:r,admin:h.isAdmin==="on"};e.invite(t==null?void 0:t.id,m).then(g=>{e.invalidateSearches("Patient"),e.invalidateSearches("Practitioner"),e.invalidateSearches("ProjectMembership"),Lh(g)?a(g):d(g),c(m.sendEmail??!1),ge({color:"green",message:"Invite success"})}).catch(g=>{ge({color:"red",message:Ae(g),autoClose:!1}),a(ft(g))})},[e,t,r]);return s.jsxs(qe,{onSubmit:f,children:[!u&&!i&&s.jsxs($e,{children:[s.jsx(ve,{children:"Invite new member"}),e.isSuperAdmin()&&s.jsx(yt,{title:"Project",htmlFor:"project",outcome:i,children:s.jsx(Zs,{resourceType:"Project",name:"project",defaultValue:t,onChange:n})}),s.jsx(It,{name:"resourceType",label:"Role",defaultValue:"Practitioner",data:["Practitioner","Patient","RelatedPerson"],error:Qe(i,"resourceType")}),s.jsx(ye,{name:"firstName",label:"First Name",required:!0,autoFocus:!0,error:Qe(i,"firstName")}),s.jsx(ye,{name:"lastName",label:"Last Name",required:!0,error:Qe(i,"lastName")}),s.jsx(ye,{name:"email",type:"email",label:"Email",required:!0,error:Qe(i,"email")}),s.jsx(yt,{title:"Access Policy",htmlFor:"accessPolicy",outcome:i,children:s.jsx(op,{name:"accessPolicy",onChange:o})}),s.jsx(Dn,{name:"sendEmail",label:"Send email",defaultChecked:!0}),s.jsx(Dn,{name:"isAdmin",label:"Admin"}),s.jsx(te,{justify:"flex-end",children:s.jsx(ae,{type:"submit",children:"Invite"})})]}),i&&s.jsxs("div",{"data-testid":"success",children:[s.jsx("p",{children:"User created, email couldn't be sent"}),s.jsx("p",{children:"Could not send email. Make sure you have AWS SES set up."}),s.jsxs("p",{children:["Click ",s.jsx(We,{to:"/admin/project",children:"here"})," to return to the project admin page."]})]}),u&&s.jsxs("div",{"data-testid":"success",children:[s.jsx(me,{children:"User created"}),l&&s.jsx(me,{children:"Email sent"}),s.jsxs($n,{children:[s.jsx($n.Item,{children:s.jsx(We,{to:u,children:"Go to new membership"})}),s.jsx($n.Item,{children:s.jsx(We,{to:u.profile,children:"Go to new profile"})}),s.jsx($n.Item,{children:s.jsx(We,{to:"/admin/users",children:"Back to users list"})})]})]})]})}function qK(){return s.jsxs(s.Fragment,{children:[s.jsx(ve,{children:"Patients"}),s.jsx(rp,{resourceType:"Patient",fields:["user","profile","_lastUpdated"]}),s.jsx(te,{justify:"flex-end",children:s.jsx(We,{to:"/admin/invite",children:"Invite new patient"})})]})}function GK(){const e=le();if(!e.isLoading()&&!e.isProjectAdmin())return s.jsx(Ar,{outcome:GP});function t(n){e.post("admin/projects/setpassword",n).then(()=>ge({color:"green",message:"Done"})).catch(r=>ge({color:"red",message:Ae(r),autoClose:!1}))}return s.jsxs(Me,{width:600,children:[s.jsx(ve,{order:1,children:"Project Admin"}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Force Set Password"}),s.jsx(me,{children:"Sets the password for the specified user in this project."}),s.jsx(me,{children:"This action can only be performed by project administrators. Passwords can only be set for users scoped in this project."}),s.jsx(qe,{onSubmit:t,children:s.jsxs($e,{children:[s.jsx(ye,{name:"email",label:"Email",required:!0}),s.jsx(Hr,{name:"password",label:"Password",required:!0}),s.jsx(ae,{type:"submit",children:"Force Set Password"})]})})]})}function DS(){const e=le(),t=ts(e),n=e.get(`admin/projects/${t}`).read();return s.jsxs(s.Fragment,{children:[s.jsx(ve,{children:"Details"}),s.jsxs(i0,{children:[s.jsx(Oo,{term:"ID",children:n.project.id}),s.jsx(Oo,{term:"Name",children:n.project.name})]})]})}const IS=["Details","Users","Patients","Clients","Bots","Secrets","Sites"];function QK(){const e=Gt(),n=ii().pathname.replace("/admin/","")||IS[0],r=le(),o=ts(r),i=p.useMemo(()=>r.get("admin/projects/"+o).read(),[r,o]);function a(l){e(`/admin/${l}`)}return s.jsxs(s.Fragment,{children:[s.jsxs(Xn,{children:[s.jsx(ze,{children:s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Project"}),s.jsx(ze.Value,{children:i.project.name})]})}),s.jsx(_r,{children:s.jsx(Je,{value:n.toLowerCase(),onChange:a,children:s.jsx(Je.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:IS.map(l=>s.jsx(Je.Tab,{value:l.toLowerCase(),children:l},l))})})})]}),s.jsx(Me,{children:s.jsx(R0,{})})]})}function KK(){const e=le(),t=ts(e),n=e.get(`admin/projects/${t}`).read(),[r,o]=p.useState(!1),[i,a]=p.useState();return p.useEffect(()=>{e.requestSchema("Project").then(()=>o(!0)).catch(console.log)},[e]),p.useEffect(()=>{n&&a(Kr(n.project.secret||[]))},[e,n]),!r||!i?s.jsx("div",{children:"Loading..."}):s.jsxs("form",{noValidate:!0,autoComplete:"off",onSubmit:l=>{l.preventDefault(),e.post(`admin/projects/${t}/secrets`,i).then(()=>e.get(`admin/projects/${t}`,{cache:"reload"})).then(()=>ge({color:"green",message:"Saved"})).catch(console.log)},children:[s.jsx(ve,{children:"Project Secrets"}),s.jsx("p",{children:"Use project secrets to store sensitive information such as API keys or other access credentials."}),s.jsx(Tl,{property:Ys("Project","secret"),name:"secret",path:"Project.secret",defaultValue:i,onChange:a,outcome:void 0}),s.jsx(ae,{type:"submit",children:"Save"})]})}function YK(){const e=le(),t=ts(e),n=e.get(`admin/projects/${t}`).read(),[r,o]=p.useState(!1),[i,a]=p.useState();return p.useEffect(()=>{e.requestSchema("Project").then(()=>o(!0)).catch(console.log)},[e]),p.useEffect(()=>{n&&a(Kr(n.project.site||[]))},[e,n]),!r||!i?s.jsx("div",{children:"Loading..."}):s.jsxs("form",{noValidate:!0,autoComplete:"off",onSubmit:l=>{l.preventDefault(),e.post(`admin/projects/${t}/sites`,i).then(()=>e.get(`admin/projects/${t}`,{cache:"reload"})).then(()=>ge({color:"green",message:"Saved"})).catch(c=>{var d,f,h,m;const u=ft(c);ge({color:"red",message:`Error ${(f=(d=u.issue)==null?void 0:d[0].details)==null?void 0:f.text} ${(m=(h=u.issue)==null?void 0:h[0].expression)==null?void 0:m[0]}`,autoClose:!1})})},children:[s.jsx(ve,{children:"Project Sites"}),s.jsx("p",{children:"Use project sites configure your project on a separate domain."}),s.jsx(Tl,{property:Ys("Project","site"),name:"site",path:"Project.site",defaultValue:i,onChange:a,outcome:void 0}),s.jsx(ae,{type:"submit",children:"Save"})]})}function XK(){const e=le(),[t,{open:n,close:r}]=av(!1),[o,i]=p.useState(""),[a,l]=p.useState();if(!e.isLoading()&&!e.isSuperAdmin())return s.jsx(Ar,{outcome:GP});function c(){vd(e,"Rebuilding Structure Definitions","admin/super/structuredefinitions")}function u(){vd(e,"Rebuilding Search Parameters","admin/super/searchparameters")}function d(){vd(e,"Rebuilding Value Sets","admin/super/valuesets")}function f(S){vd(e,"Reindexing Resources","admin/super/reindex",S)}function h(S){e.post("admin/super/removebotidjobsfromqueue",S).then(()=>ge({color:"green",message:"Done"})).catch(b=>ge({color:"red",message:Ae(b),autoClose:!1}))}function m(S){e.post("admin/super/purge",{...S,before:sR(S.before)}).then(()=>ge({color:"green",message:"Done"})).catch(b=>ge({color:"red",message:Ae(b),autoClose:!1}))}function g(S){e.post("admin/super/setpassword",S).then(()=>ge({color:"green",message:"Done"})).catch(b=>ge({color:"red",message:Ae(b),autoClose:!1}))}function v(){e.post("fhir/R4/$db-stats",{}).then(S=>{var b,w;i("Database Stats"),l(s.jsx("pre",{children:(w=(b=S.parameter)==null?void 0:b.find(y=>y.name==="tableString"))==null?void 0:w.valueString})),n()}).catch(S=>ge({color:"red",message:Ae(S),autoClose:!1}))}return s.jsxs(Me,{width:600,children:[s.jsx(ve,{order:1,children:"Super Admin"}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Structure Definitions"}),s.jsx("p",{children:"StructureDefinition resources contain the metadata about resource types. They are provided with the FHIR specification. Medplum also includes some custom StructureDefinition resources for internal data types. Press this button to update the database StructureDefinitions from the FHIR specification."}),s.jsx(qe,{children:s.jsx(ae,{onClick:c,children:"Rebuild StructureDefinitions"})}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Search Parameters"}),s.jsx("p",{children:"SearchParameter resources contain the metadata about filters and sorting. They are provided with the FHIR specification. Medplum also includes some custom SearchParameter resources for internal data types. Press this button to update the database SearchParameters from the FHIR specification."}),s.jsx(qe,{children:s.jsx(ae,{onClick:u,children:"Rebuild SearchParameters"})}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Value Sets"}),s.jsx("p",{children:"ValueSet resources enum values for a wide variety of use cases. Press this button to update the database ValueSets from the FHIR specification."}),s.jsx(qe,{children:s.jsx(ae,{onClick:d,children:"Rebuild ValueSets"})}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Reindex Resources"}),s.jsx("p",{children:"When Medplum changes how resources are indexed, the system may require a reindex for old resources to be indexed properly."}),s.jsx(qe,{onSubmit:f,children:s.jsxs($e,{children:[s.jsx(yt,{title:"Resource Type",htmlFor:"resourceType",children:s.jsx(ye,{id:"resourceType",name:"resourceType",placeholder:"Reindex Resource Type"})}),s.jsx(yt,{title:"Search Filter",htmlFor:"filter",children:s.jsx(ye,{id:"filter",name:"filter",placeholder:"e.g. name=Sam&birthdate=lt2000-01-01"})}),s.jsx(ae,{type:"submit",children:"Reindex"})]})}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Purge Resources"}),s.jsx("p",{children:"As system generated resources accumulate, the system may require a purge to remove old resources."}),s.jsx(qe,{onSubmit:m,children:s.jsxs($e,{children:[s.jsx(yt,{title:"Purge Resource Type",htmlFor:"purgeResourceType",children:s.jsx(It,{id:"purgeResourceType",name:"resourceType",data:["","AuditEvent","Login"]})}),s.jsx(yt,{title:"Purge Before",htmlFor:"before",children:s.jsx(As,{name:"before",placeholder:"Before Date"})}),s.jsx(ae,{type:"submit",children:"Purge"})]})}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Remove Bot ID Jobs from Queue"}),s.jsx("p",{children:"Remove all queued jobs for a Bot ID"}),s.jsx(qe,{onSubmit:h,children:s.jsxs($e,{children:[s.jsx(yt,{title:"Bot ID",children:s.jsx(ye,{name:"botId",placeholder:"Bot Id"})}),s.jsx(ae,{type:"submit",children:"Remove Jobs by Bot ID"})]})}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Force Set Password"}),s.jsx("p",{children:'Note that this applies to all projects for the user. Therefore, this should only be used in extreme circumstances. Always prefer to use the "Forgot Password" flow first.'}),s.jsx(qe,{onSubmit:g,children:s.jsxs($e,{children:[s.jsx(ye,{name:"email",label:"Email",required:!0}),s.jsx(Hr,{name:"password",label:"Password",required:!0}),s.jsx(ye,{name:"projectId",label:"Project ID"}),s.jsx(ae,{type:"submit",children:"Force Set Password"})]})}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{order:2,children:"Database Stats"}),s.jsx("p",{children:"Query current table statistics from the database."}),s.jsx(qe,{onSubmit:v,children:s.jsx(ae,{type:"submit",children:"Get Database Stats"})}),s.jsx(jn,{opened:t,onClose:r,title:o,centered:!0,children:a})]})}function vd(e,t,n,r){po.show({id:n,loading:!0,title:t,message:"Running...",autoClose:!1,withCloseButton:!1});const o={method:"POST",pollStatusOnAccepted:!0};r&&(o.body=JSON.stringify(r)),e.startAsyncRequest(n,o).then(()=>{po.update({id:n,color:"green",title:t,message:"Done",icon:s.jsx(Js,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})}).catch(i=>{po.update({id:n,color:"red",title:t,message:Ae(i),icon:s.jsx(Ef,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})})}function JK(){return s.jsxs(s.Fragment,{children:[s.jsx(ve,{children:"Users"}),s.jsx(rp,{resourceType:"Practitioner",fields:["user","profile","admin","_lastUpdated"]}),s.jsx(te,{justify:"flex-end",children:s.jsx(We,{to:"/admin/invite",children:"Invite new user"})})]})}function ZK(){const[e]=al("ObservationDefinition","_count=100");return e?s.jsxs(pe,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Category"}),s.jsx("th",{children:"Code"}),s.jsx("th",{children:"Method"}),s.jsx("th",{children:"Unit"}),s.jsx("th",{children:"Precision"}),s.jsx("th",{children:"Ranges"})]})}),s.jsx("tbody",{children:e.map(t=>{var n,r,o,i;return s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx(mo,{value:(n=t.category)==null?void 0:n[0]})}),s.jsx("td",{children:s.jsx(mo,{value:t.code})}),s.jsx("td",{children:s.jsx(mo,{value:t.method})}),s.jsx("td",{children:(o=(r=t.quantitativeDetails)==null?void 0:r.unit)==null?void 0:o.text}),s.jsx("td",{children:(i=t.quantitativeDetails)==null?void 0:i.decimalPrecision}),s.jsx("td",{children:s.jsx(Yg,{ranges:t.qualifiedInterval})})]},t.id)})})]}):s.jsx(Yr,{})}function Yg(e){const{ranges:t}=e;if(!t)return null;const n=AS(t.map(o=>o.gender));if(n.length>1)return Oc(n),s.jsx(s.Fragment,{children:n.map(o=>{var i;return s.jsxs(p.Fragment,{children:[s.jsx("div",{children:s.jsx("strong",{children:tn(o)})}),s.jsx(Yg,{ranges:(i=e.ranges)==null?void 0:i.filter(a=>a.gender===o)})]},o)})});const r=AS(t.map(o=>o.age&&Lc(o.age)));return r.length>1?(Oc(r),s.jsx(s.Fragment,{children:r.map(o=>{var i;return s.jsxs(p.Fragment,{children:[s.jsx("div",{children:s.jsx("strong",{children:tn(o)})}),s.jsx(Yg,{ranges:(i=e.ranges)==null?void 0:i.filter(a=>Lc(a.age)===o)})]},o)})})):s.jsx(s.Fragment,{children:t.map(o=>s.jsx("table",{children:s.jsx("tbody",{children:s.jsxs("tr",{children:[s.jsx("td",{children:o.condition}),s.jsx("td",{children:s.jsx(a0,{value:o.range})})]})})},`range-${o.condition}`))})}function AS(e){return[...new Set(e.filter(t=>!!t))]}function eY(){const[e]=al("ActivityDefinition","_count=100"),[t]=al("ObservationDefinition","_count=100");return!e||!t?s.jsx(Yr,{}):s.jsxs(pe,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Category"}),s.jsx("th",{children:"Assay"}),e.map(n=>s.jsx("th",{children:n.name},n.id))]})}),s.jsx("tbody",{children:t.map(n=>{var r;return s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx(mo,{value:(r=n.category)==null?void 0:r[0]})}),s.jsx("td",{children:s.jsx(mo,{value:n.code})}),e.map(o=>{var i;return s.jsx("td",{children:(i=o.observationResultRequirement)!=null&&i.find(a=>{var l;return(l=a.reference)==null?void 0:l.includes(n.id)})?"✅":""},o.id)})]},n.id)})})]})}function tY(e){var a;const t=le(),[n,r]=p.useState(),[o,i]=p.useState();return o?s.jsxs(s.Fragment,{children:[s.jsx("p",{children:"Request group created successfully."}),s.jsxs("ul",{children:[s.jsxs("li",{children:["Go to the"," ",s.jsx(We,{to:o,suffix:"checklist",children:"Request Group"})]}),s.jsxs("li",{children:["Back to the ",s.jsx(We,{to:e.planDefinition,children:"Plan Definition"})]})]})]}):s.jsx(qe,{onSubmit:()=>{t.post(t.fhirUrl("PlanDefinition",e.planDefinition.id,"$apply"),{resourceType:"Parameters",parameter:[{name:"subject",valueString:n==null?void 0:n.reference}]}).then(i).catch(console.log)},children:s.jsxs($e,{children:[s.jsxs(ve,{children:['Start "',e.planDefinition.title,'"']}),s.jsxs(me,{children:["Use the ",s.jsx("strong",{children:"Apply"})," operation to create a group of tasks for a workflow."]}),s.jsx(me,{children:"The following tasks will be created:"}),s.jsx("ul",{children:(a=e.planDefinition.action)==null?void 0:a.map((l,c)=>{var u;return s.jsxs("li",{children:[((u=l.definitionCanonical)==null?void 0:u.startsWith("Questionnaire/"))&&"Questionnaire request: ",l.title&&s.jsx(s.Fragment,{children:l.title}),l.code&&s.jsx(mo,{value:l.code[0]})]},`action-${c}`)})}),s.jsx(yt,{title:"Subject",children:s.jsx(Gh,{name:"subject",targetTypes:["Patient","Practitioner"],defaultValue:n,onChange:r})}),s.jsx(te,{justify:"flex-end",mt:"xl",children:s.jsx(ae,{type:"submit",children:"Go"})})]})})}function nY(){const{resourceType:e,id:t}=st(),n=St({reference:e+"/"+t});return n?s.jsx(Me,{children:s.jsx(tY,{planDefinition:n})}):null}function rY(){const{resourceType:e,id:t}=st(),n=St({reference:e+"/"+t}),[r,o]=al("Questionnaire","subject-type="+e),[i,a]=al("ClientApplication",{_count:1e3});if(!n||o||a)return s.jsx(Yr,{});const l=i==null?void 0:i.filter(d=>oY(e)&&!!d.launchUri);if((!r||r.length===0)&&(!l||l.length===0))return s.jsxs(Me,{children:[s.jsx(ve,{children:"Apps"}),s.jsxs("p",{children:["No apps found. Contact your administrator or ",s.jsx("a",{href:"mailto:support@medplum.com",children:"Medplum Support"})," to add automation here."]})]});let c,u;return n.resourceType==="Patient"?c=Tt(n):n.resourceType==="Encounter"&&(c=n.subject,u=Tt(n)),s.jsxs(Me,{children:[r==null?void 0:r.map(d=>s.jsxs("div",{children:[s.jsx(ve,{order:3,children:s.jsx(We,{to:`/forms/${d.id}?subject=${rt(n)}`,children:d.title||d.name})}),s.jsx(me,{children:d.description})]},d.id)),l==null?void 0:l.map(d=>s.jsxs("div",{children:[s.jsx(ve,{order:3,children:s.jsx(Tq,{client:d,patient:c,encounter:u,children:d.name})}),s.jsx(me,{children:d.description})]},d.id))]})}function oY(e){return e==="Patient"||e==="Encounter"}function iY(){const{resourceType:e,id:t}=st(),n=Gt(),[r,o]=p.useState({resourceType:"AuditEvent",filters:[{code:"entity",operator:re.EQUALS,value:`${e}/${t}`}],fields:["id","outcome","outcomeDesc","_lastUpdated"],sortRules:[{code:"-_lastUpdated"}],count:20});return s.jsx(Me,{children:s.jsx(ju,{search:r,onClick:i=>n(`/${i.resource.resourceType}/${i.resource.id}`),onChange:i=>o(i.definition),hideFilters:!0})})}function sY(){const e=le(),{resourceType:t,id:n}=st(),r=e.readHistory(t,n).read();return s.jsx(Me,{children:s.jsx(mq,{history:r})})}const aY="_hl7Input_k5xm3_1",lY={hl7Input:aY};function cY(e){return s.jsx("iframe",{frameBorder:"0",src:"https://codeeditor.medplum.com/bot-runner.html",className:e.className,ref:e.iframeRef,"data-testid":e.testId,style:{width:"100%",height:"100%",minHeight:e.minHeight}})}function uY(e){const t=e.defaultValue,n=new URL(`https://codeeditor.medplum.com/${e.language}-editor.html`);return e.module&&n.searchParams.set("module",e.module),s.jsx("iframe",{frameBorder:"0",src:n.toString(),style:{width:"100%",height:"100%",minHeight:e.minHeight},ref:e.iframeRef,"data-testid":e.testId,onLoad:r=>{Ld(r.currentTarget,{command:"setValue",value:t}).catch(console.error)}})}const dY=`{
|
|
573
573
|
"resourceType": "Patient",
|
|
574
574
|
"name": [
|
|
575
575
|
{
|
|
@@ -580,4 +580,4 @@ Error generating stack: `+i.message+`
|
|
|
580
580
|
}
|
|
581
581
|
]
|
|
582
582
|
}`,fY="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 hY(){const e=le(),{id:t}=st(),[n,r]=p.useState(),[o,i]=p.useState(),[a,l]=p.useState(dY),[c,u]=p.useState(fY),[d,f]=p.useState(rn.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 pY(e,E))}).catch(E=>ge({color:"red",message:Ae(E),autoClose:!1}))},[e,t]);const S=p.useCallback(()=>Ld(h.current,{command:"getValue"}),[]),b=p.useCallback(()=>Ld(h.current,{command:"getOutput"}),[]),w=p.useCallback(async()=>d===rn.FHIR_JSON?JSON.parse(a):c,[d,a,c]),y=p.useCallback(async E=>{E.preventDefault(),E.stopPropagation(),v(!0);try{const T=await S(),j=await e.createAttachment(T,"index.ts","text/typescript"),R=[];n!=null&&n.sourceCode?R.push({op:"replace",path:"/sourceCode",value:j}):R.push({op:"add",path:"/sourceCode",value:j}),await e.patchResource("Bot",t,R),ge({color:"green",message:"Saved"})}catch(T){ge({color:"red",message:Ae(T),autoClose:!1})}finally{v(!1)}},[e,t,n,S]),x=p.useCallback(async E=>{E.preventDefault(),E.stopPropagation(),v(!0);try{const T=await b();await e.post(e.fhirUrl("Bot",t,"$deploy"),{code:T}),ge({color:"green",message:"Deployed"})}catch(T){ge({color:"red",message:Ae(T),autoClose:!1})}finally{v(!1)}},[e,t,b]),C=p.useCallback(async E=>{E.preventDefault(),E.stopPropagation(),v(!0);try{const T=await w(),j=await e.post(e.fhirUrl("Bot",t,"$execute"),T,d);await Ld(m.current,{command:"setValue",value:j}),ge({color:"green",message:"Success"})}catch(T){ge({color:"red",message:Ae(T),autoClose:!1})}finally{v(!1)}},[e,t,w,d]);return!n||o===void 0?null:s.jsxs(cr,{m:0,gutter:0,style:{overflow:"hidden"},children:[s.jsx(cr.Col,{span:8,children:s.jsxs(Xn,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",mih:400,children:[s.jsx(uY,{iframeRef:h,language:"typescript",module:"commonjs",testId:"code-frame",defaultValue:o,minHeight:"528px"}),s.jsxs(te,{justify:"flex-end",gap:"xs",children:[s.jsx(ae,{type:"button",onClick:y,loading:g,leftSection:s.jsx(yz,{size:"1rem"}),children:"Save"}),s.jsx(ae,{type:"button",onClick:x,loading:g,leftSection:s.jsx(Xx,{size:"1rem"}),children:"Deploy"}),s.jsx(ae,{type:"button",onClick:C,loading:g,leftSection:s.jsx(Iz,{size:"1rem"}),children:"Execute"})]})]})}),s.jsxs(cr.Col,{span:4,children:[s.jsxs(Xn,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[s.jsx(It,{data:[{label:"FHIR",value:rn.FHIR_JSON},{label:"HL7",value:rn.HL7_V2}],onChange:E=>f(E.currentTarget.value)}),d===rn.FHIR_JSON?s.jsx(vl,{value:a,onChange:E=>l(E),autosize:!0,minRows:15}):s.jsx("textarea",{className:lY.hl7Input,value:c,onChange:E=>u(E.currentTarget.value),rows:15})]}),s.jsx(Xn,{m:2,p:"xs",shadow:"md",children:s.jsx(cY,{iframeRef:m,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function pY(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(lk);return(await e.download(e.fhirUrl("Binary",i))).text()}return t.code??""}function ea(e){let t=e.meta;return t&&(t={...t,lastUpdated:void 0,versionId:void 0,author:void 0}),{...e,meta:t}}function mY(){const e=le(),{resourceType:t,id:n}=st(),r={reference:t+"/"+n},o=p.useCallback(i=>{e.updateResource(ea(i)).then(()=>{ge({color:"green",message:"Success"})}).catch(a=>{ge({color:"red",message:Ae(a),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return s.jsx(Me,{children:s.jsx(WW,{value:r,onSubmit:o})});case"Questionnaire":return s.jsx(Me,{children:s.jsx(PH,{questionnaire:r,onSubmit:o})});default:return null}}function gY(){const{resourceType:e,id:t}=st(),n=St({reference:e+"/"+t}),r=Gt();return n?s.jsx(Me,{children:s.jsx(XH,{value:n,onStart:(o,i)=>r(`/forms/${il(i)}`),onEdit:(o,i,a)=>r(`/${a.reference}}`)})}):null}function vY(){const e=le(),{resourceType:t,id:n}=st(),r=Gt();return s.jsxs(Me,{children:[s.jsxs("p",{children:["Are you sure you want to delete this ",t,"?"]}),s.jsx(ae,{color:"red",onClick:()=>{e.deleteResource(t,n).then(()=>r(`/${t}`)).catch(o=>ge({color:"red",message:Ae(o),autoClose:!1}))},children:"Delete"})]})}const yY="_selectProfileBtn_tbaz6_1",xY="_chevron_tbaz6_13",NS={selectProfileBtn:yY,chevron:xY};function bY(){var c,u;const{resourceType:e,id:t}=st(),n=St({reference:e+"/"+t}),[r,o]=p.useState(),i=ou({onDropdownClose:()=>i.resetSelectedOption()}),a=p.useMemo(()=>{var d;if($t((d=n==null?void 0:n.meta)==null?void 0:d.profile))return[s.jsx(Le.Option,{value:"",children:"None"},""),...n.meta.profile.map(f=>s.jsx(Le.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 $t(a)&&(l=s.jsx(te,{justify:"flex-end",children:s.jsxs($e,{align:"flex-end",gap:"xs",children:[s.jsxs(Le,{store:i,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:d=>{o(d),i.closeDropdown()},children:[s.jsx(Le.Target,{children:s.jsx(Sn,{onClick:()=>i.toggleDropdown(),children:s.jsxs(Gy,{fw:"bold",fs:"sm",className:NS.selectProfileBtn,children:[s.jsx("span",{children:"Pick profile"}),s.jsx(Yx,{stroke:1.5,className:NS.chevron})]})})}),s.jsx(Le.Dropdown,{w:"max-content",children:s.jsx(Le.Options,{children:a})})]}),s.jsx(q,{children:r?s.jsxs(s.Fragment,{children:[s.jsx(me,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),s.jsx(me,{span:!0,size:"sm",children:r||"Nothing selected"})]}):s.jsx(me,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),s.jsx(Me,{children:s.jsxs($e,{gap:"xl",children:[l,s.jsx(x0,{value:n,profileUrl:r})]})})}function wY(){const e=le(),{resourceType:t,id:n}=st(),[r,o]=p.useState(),[i,a]=p.useState(),l=Gt(),[c,u]=p.useState();p.useEffect(()=>{e.readResource(t,n).then(m=>{o(Kr(m)),a(Kr(m))}).catch(m=>{u(ft(m)),ge({color:"red",message:Ae(m),autoClose:!1})})},[e,t,n]);const d=p.useCallback(m=>{u(void 0),e.updateResource(ea(m)).then(()=>{l(`/${t}/${n}/details`),ge({id:"succes",color:"green",message:"Success"})}).catch(g=>{u(ft(g)),ge({color:"red",message:Ae(g),autoClose:!1})})},[e,t,n,l]),f=p.useCallback(m=>{u(void 0);const g=p0.createPatch(r,m);e.patchResource(t,n,g).then(()=>{l(`/${t}/${n}/details`),ge({id:"succes",color:"green",message:"Success"})}).catch(v=>{u(ft(v)),ge({color:"red",message:Ae(v),autoClose:!1})})},[e,t,n,r,l]),h=p.useCallback(()=>l(`/${t}/${n}/delete`),[l,t,n]);return i?s.jsx(Me,{children:s.jsx(Rf,{defaultValue:i,onSubmit:d,onPatch:f,onDelete:h,outcome:c})}):null}function $2({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,o=le(),[i,a]=p.useState();return p.useEffect(()=>{o.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(l=>{a(l.filter(tU))}).catch(console.error)},[o,n,r]),s.jsx(Je,{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(Je.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(Je.Tab,{value:l.url,title:u,rightSection:c&&s.jsx(Rx,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:s.jsx(qz,{size:"90%"})}),children:l.title||l.name},l.url)})})})}function F2(e,t){const n=le(),r=Gt();return{defaultValue:{resourceType:e},handleSubmit:a=>{t&&t(void 0),n.createResource(a).then(l=>r("/"+l.resourceType+"/"+l.id)).catch(l=>{t&&t(ft(l)),ge({color:"red",message:Ae(l),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function fm(){const{resourceType:e}=st(),t=ii(),[n,r]=p.useState(),{defaultValue:o,handleSubmit:i}=F2(e,r),[a,l]=p.useState(),c=t.pathname.toLowerCase().endsWith("profiles"),u=p.useCallback(d=>{const f=ea(d);a&&dk(f,a.url),i(f)},[a,i]);return c?s.jsx(Me,{children:s.jsxs($e,{children:[s.jsx($2,{resource:o,currentProfile:a,onChange:l}),a?s.jsx(Rf,{defaultValue:o,onSubmit:u,outcome:n,profileUrl:a.url},a.url):s.jsx(me,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):s.jsx(Me,{children:s.jsx(Rf,{defaultValue:o,onSubmit:i,outcome:n})})}function SY(){const e=le(),{resourceType:t,id:n}=st(),r=e.readHistory(t,n).read();return s.jsx(Me,{children:s.jsx(Sq,{history:r})})}function jY(){const{resourceType:e}=st(),[t,n]=p.useState(),{defaultValue:r,handleSubmit:o}=F2(e,n),i=p.useCallback(a=>{o(JSON.parse(a["new-resource"]))},[o]);return s.jsxs(Me,{children:[t&&s.jsx(Ar,{outcome:t}),s.jsxs(qe,{onSubmit:i,children:[s.jsx(vl,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:hr(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(ae,{type:"submit",children:"OK"})})]})]})}function CY(){const e=le(),{resourceType:t,id:n}=st(),r=St({reference:t+"/"+n}),o=Gt(),[i,a]=p.useState(),l=p.useCallback(c=>{e.updateResource(ea(JSON.parse(c.resource))).then(()=>{a(void 0),o(`/${t}/${n}/details`),ge({color:"green",message:"Success"})}).catch(u=>{ge({color:"red",message:Ae(u),autoClose:!1})})},[e,t,n,o]);return r?s.jsxs(Me,{children:[i&&s.jsx(Ar,{outcome:i}),s.jsxs(qe,{onSubmit:l,children:[s.jsx(vl,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:hr(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),s.jsx(te,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(ae,{type:"submit",children:"OK"})})]})]}):null}function EY(){const{resourceType:e,id:t}=st();return St({reference:e+"/"+t})?s.jsxs(Me,{children:[s.jsxs(Yi,{icon:s.jsx(El,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",s.jsx("br",{}),s.jsx(Ke,{href:`/forms/${t}`,children:`/forms/${t}`})]}),s.jsx(KR,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function TY(){const e=le(),{resourceType:t,id:n}=st(),[r,o]=p.useState(),[i,a]=p.useState();return p.useEffect(()=>{e.readResource(t,n).then(l=>o(Kr(l))).catch(l=>{ge({color:"red",message:Ae(l)})})},[e,t,n]),r?s.jsxs(Me,{children:[s.jsxs(ve,{order:2,children:["Available ",t," profiles"]}),s.jsx($e,{children:s.jsxs(s.Fragment,{children:[s.jsx($2,{resource:r,currentProfile:i,onChange:a}),i?s.jsx(PY,{profile:i,resource:r,onResourceUpdated:l=>o(l)},i.url):s.jsx(me,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const PY=({profile:e,resource:t,onResourceUpdated:n})=>{const r=le(),[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=ea(u);a?dk(d,e.url):D6(d,e.url),r.updateResource(d).then(f=>{n(f),ge({color:"green",message:"Success"})}).catch(f=>{i(ft(f)),ge({color:"red",message:Ae(f),autoClose:!1})})},[r,e.url,n,a]);return s.jsxs($e,{children:[s.jsx(uu,{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(te,{justify:"flex-end",mt:"xl",children:s.jsx(ae,{type:"submit",children:"OK"})})})]})};function kY(){const e=le(),{id:t}=st(),[n,r]=p.useState(),[o,i]=p.useState(0),a=e.searchResources("Subscription","status=active&_count=100").read().filter(c=>RY(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:rt(n)}}).then(()=>{r(void 0),i(Date.now()),e.invalidateSearches("Subscription"),ge({color:"green",message:"Success"})}).catch(c=>ge({color:"red",message:Ae(c),autoClose:!1}))}return s.jsxs(Me,{children:[s.jsx(ve,{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(Pl,{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(ve,{children:"Connect to bot"}),s.jsxs(te,{children:[s.jsx(Zs,{name:"bot",resourceType:"Bot",onChange:c=>r(c)}),s.jsx(ae,{onClick:l,children:"Connect"})]}),s.jsx("div",{style:{display:"none"},children:o})]})}function RY(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 _Y(){const{id:e}=st(),t=Gt(),[n,r]=p.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:re.EQUALS,value:"Questionnaire/"+e}],fields:["id","_lastUpdated"]});return s.jsx(Me,{children:s.jsx(ju,{search:n,onClick:o=>t(`/${o.resource.resourceType}/${o.resource.id}`),onChange:o=>r(o.definition),hideFilters:!0,hideToolbar:!0})})}function DY(){const e=le(),{resourceType:t,id:n}=st(),r=St({reference:t+"/"+n}),o=p.useCallback(i=>{e.updateResource(ea(i)).then(()=>{ge({color:"green",message:"Success"})}).catch(a=>{ge({color:"red",message:Ae(a),autoClose:!1})})},[e]);return r?s.jsx(Me,{children:s.jsx(VH,{onSubmit:o,definition:r})}):null}function IY(){const{resourceType:e,id:t}=st(),n=St({reference:e+"/"+t});return n?s.jsx(Me,{children:e==="MeasureReport"?s.jsx($W,{measureReport:n}):s.jsx(f0,{value:n})}):null}const AY="_container_1ue98_1",NY="_entry_1ue98_14",MY="_active_1ue98_21",hm={container:AY,entry:NY,active:MY};function OY(e){const t=le(),n=St(e.value),[r,o]=p.useState();return p.useEffect(()=>{if(!n)return;const i=N0(n);if(!i)return;const a="reference"in i?i.reference:rt(i);t.search("ServiceRequest","subject="+a).then(l=>{const u=l.entry.map(d=>d.resource);ER(u),u.reverse(),o(u)}).catch(l=>ge({color:"red",message:Ae(l),autoClose:!1}))},[t,n]),r?s.jsx("div",{"data-testid":"quick-service-requests",className:hm.container,children:r.map(i=>{var a,l,c,u,d,f,h;return s.jsxs("div",{className:tt(hm.entry,{[hm.active]:i.id===(n==null?void 0:n.id)}),children:[s.jsx("p",{children:s.jsx(We,{to:i,children:LY(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:$Y(i)})]},i.id)})}):null}function LY(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function $Y(e){var t;return e.authoredOn?e.authoredOn.substring(0,10):(t=e.meta)!=null&&t.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const FY="_container_1l2dh_1",zY={container:FY};function BY(e){var o,i,a,l;const t=St(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:zY.container,children:s.jsx(It,{defaultValue:e.defaultValue,onChange:c=>e.onChange(c.currentTarget.value),data:n})})}function UY(e){var n,r;const t=St(e.specimen);return t?s.jsxs(ze,{children:[s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Type"}),s.jsx(ze.Value,{children:"Specimen"})]}),s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Collected"}),s.jsx(ze.Value,{children:zn((n=t.collection)==null?void 0:n.collectedDateTime)})]}),s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Specimen Age"}),s.jsx(ze.Value,{children:VY(t)})]}),(r=t.collection)!=null&&r.collectedDateTime&&t.receivedTime?s.jsxs(ze.Entry,{children:[s.jsx(ze.Key,{children:"Specimen Stability"}),s.jsx(ze.Value,{children:WY(t)})]}):s.jsx(s.Fragment,{})]}):null}function VY(e){var o;const t=(o=e.collection)==null?void 0:o.collectedDateTime;if(!t)return;const n=new Date(t);return z2(B2(n,new Date))}function WY(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 z2(B2(t,n))}function z2(e){return e.toString().padStart(3,"0")+"D"}function B2(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function HY(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 qY=[];function GY(){var y,x,C,E,T,j,R;const e=le(),{resourceType:t,id:n}=st(),r={reference:t+"/"+n},o=Gt(),[i,a]=p.useState(),l=St(r,a),c=HY(t),[u,d]=p.useState(()=>{const k=window.location.pathname.split("/").pop();return k&&c.map(I=>I.toLowerCase()).includes(k)?k:c[0].toLowerCase()}),f=At();async function h(){var O,F;const I=(F=(O=(await e.readHistory(t,n)).entry)==null?void 0:O.find(L=>!!L.resource))==null?void 0:F.resource;I?m(I):ge({color:"red",message:"No history to restore",autoClose:!1})}function m(k){e.updateResource(ea(k)).then(()=>{a(void 0),ge({color:"green",message:"Success"})}).catch(I=>{ge({color:"red",message:Ae(I),autoClose:!1})})}if(i)return X$(i)?s.jsxs(Me,{children:[s.jsx(ve,{children:"Deleted"}),s.jsx("p",{children:"The resource was deleted."}),s.jsx(ae,{color:"red",onClick:h,children:"Restore"})]}):s.jsx(Ar,{outcome:i});function g(k){k||(k=c[0].toLowerCase()),d(k),o(`/${t}/${n}/${k}`)}function v(k){const I=l,O=I.orderDetail||[];O.length===0&&O.push({}),O[0].text!==k&&(O[0].text=k,m({...I,orderDetail:O}))}const S=l&&N0(l),b=l&&yK(l),w=(C=(x=(y=e.getUserConfiguration())==null?void 0:y.option)==null?void 0:x.find(k=>k.id==="statusValueSet"))==null?void 0:C.valueString;return s.jsxs(s.Fragment,{children:[(l==null?void 0:l.resourceType)==="ServiceRequest"&&w&&s.jsx(BY,{valueSet:{reference:w},defaultValue:(T=(E=l.orderDetail)==null?void 0:E[0])==null?void 0:T.text,onChange:v},rt(l)+"-"+((R=(j=l.orderDetail)==null?void 0:j[0])==null?void 0:R.text)),l&&s.jsx(OY,{value:l}),l&&s.jsxs(Xn,{children:[S&&s.jsx(A2,{patient:S}),b&&s.jsx(UY,{specimen:b}),t!=="Patient"&&s.jsx(N2,{resource:r}),s.jsx(_r,{children:s.jsx(Je,{value:u.toLowerCase(),onChange:g,children:s.jsx(Je.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:c.map(k=>s.jsx(Je.Tab,{value:k.toLowerCase(),children:qY.includes(k)?s.jsxs(te,{gap:"xs",wrap:"nowrap",children:[k,s.jsx(iu,{color:f.primaryColor,size:"sm",children:"Beta"})]}):k},k))})})})]}),s.jsx(R0,{})]})}function MS(){var b,w,y,x;const e=Gt(),{resourceType:t,id:n,versionId:r,tab:o}=st(),i=le(),[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(C=>u(C)).then(()=>l(!1)).catch(C=>{f(C),l(!1)})},[i,t,n]),a)return s.jsx(Yr,{});if(!c)return s.jsxs(Me,{children:[s.jsx(ve,{children:"Resource not found"}),s.jsx(We,{to:`/${t}`,children:"Return to search page"})]});const h=c.entry,m=h.findIndex(C=>{var E,T;return((T=(E=C.resource)==null?void 0:E.meta)==null?void 0:T.versionId)===r});if(m===-1)return s.jsxs(Me,{children:[s.jsx(ve,{children:"Version not found"}),s.jsx(We,{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(Je,{value:o||S,onChange:C=>e(`/${t}/${n}/_history/${r}/${C||S}`),children:[s.jsxs(Xn,{children:[s.jsx(bu,{fluid:!0,p:"md",children:s.jsx(me,{children:`${t} ${n}`})}),s.jsxs(Je.List,{children:[s.jsx(Je.Tab,{value:"diff",children:"Diff"}),s.jsx(Je.Tab,{value:"raw",children:"Raw"})]})]}),s.jsxs(Me,{children:[d&&s.jsx("pre",{"data-testid":"error",children:JSON.stringify(d,void 0,2)}),s.jsx(Je.Panel,{value:"diff",children:v?s.jsxs(s.Fragment,{children:[s.jsxs("ul",{children:[s.jsxs("li",{children:["Current: ",(b=g.meta)==null?void 0:b.versionId]}),s.jsxs("li",{children:["Previous:"," ",s.jsx(We,{to:`/${t}/${n}/_history/${(w=v.meta)==null?void 0:w.versionId}`,children:(y=v.meta)==null?void 0:y.versionId})]})]}),s.jsx(yq,{original:v,revised:g})]}):s.jsxs(s.Fragment,{children:[s.jsxs("ul",{children:[s.jsxs("li",{children:["Current: ",(x=g.meta)==null?void 0:x.versionId]}),s.jsx("li",{children:"Previous: (none)"})]}),s.jsx("pre",{children:JSON.stringify(g,void 0,2)})]})}),s.jsx(Je.Panel,{value:"raw",children:s.jsx("pre",{children:JSON.stringify(g,void 0,2)})})]})]})}function QY(){const{resourceType:e,id:t}=st(),n=Gt(),[r,o]=p.useState({resourceType:"Subscription",filters:[{code:"url",operator:re.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return s.jsx(Me,{children:s.jsx(TW,{search:r,onClick:i=>n(`/${i.resource.resourceType}/${i.resource.id}`),onChange:i=>o(i.definition),hideFilters:!0})})}function KY(e){const t=le(),{resource:n,opened:r,onClose:o}=e,[i,a]=p.useState(!1),[l,c]=p.useState(),[u,d]=p.useState(!1),f=p.useCallback(async()=>{if(n!=null&&n.id)try{await t.post(t.fhirUrl(n.resourceType,n.id,"$resend"),{subscription:i&&l?rt(l):void 0,verbose:u}),ge({color:"green",message:"Done"}),o()}catch(h){ge({color:"red",message:Ae(h),autoClose:!1})}},[t,n,o,i,l,u]);return s.jsx(jn,{opened:r,onClose:o,title:"Resend Subscriptions",children:s.jsx(qe,{onSubmit:f,children:s.jsxs($e,{children:[s.jsx(Dn,{label:"Choose subscription (all subscriptions by default)",onChange:h=>a(h.currentTarget.checked)}),i&&s.jsx(Zs,{name:"subscription",resourceType:"Subscription",placeholder:"Subscription",onChange:c}),s.jsx(Dn,{label:"Verbose mode",onChange:h=>d(h.currentTarget.checked)}),s.jsx(te,{justify:"flex-end",children:s.jsx(ae,{type:"submit",children:"Resend"})})]})})})}function OS(){const e=le(),t=Wh(),{resourceType:n,id:r}=st(),o={reference:n+"/"+r},[i,a]=p.useState(),l=av(!1);function c(w,y){return e.updateResource({...w,priority:y})}function u(w,y){c(w,"stat").then(y).catch(console.error)}function d(w,y){c(w,"routine").then(y).catch(console.error)}function f(w){t(`/${w.resourceType}/${w.id}`)}function h(w){t(`/${w.resourceType}/${w.id}/edit`)}function m(w){t(`/${w.resourceType}/${w.id}/delete`)}function g(w){a(w),l[1].open()}function v(w){var y;t(`/${w.resourceType}/${w.id}/_history/${(y=w.meta)==null?void 0:y.versionId}`)}function S(w,y){e.post(e.fhirUrl(w.resourceType,w.id,"$aws-textract"),{}).then(y).catch(console.error)}function b(w){var D;const{primaryResource:y,currentResource:x,reloadTimeline:C}=w,E=x.resourceType===y.resourceType&&x.id===y.id,T=x.resourceType==="Communication"&&x.priority!=="stat",j=x.resourceType==="Communication"&&x.priority==="stat",R=E,k=!E,I=!E,O=!E,F=(D=e.getProjectMembership())==null?void 0:D.admin,L=F,B=DK()&&(x.resourceType==="DocumentReference"||x.resourceType==="Media");return s.jsxs(Z.Dropdown,{children:[s.jsx(Z.Label,{children:"Resource"}),T&&s.jsx(Z.Item,{leftSection:s.jsx(_z,{size:14}),onClick:()=>u(x,C),"aria-label":`Pin ${rt(x)}`,children:"Pin"}),j&&s.jsx(Z.Item,{leftSection:s.jsx(Dz,{size:14}),onClick:()=>d(x,C),"aria-label":`Unpin ${rt(x)}`,children:"Unpin"}),k&&s.jsx(Z.Item,{leftSection:s.jsx(Iw,{size:14}),onClick:()=>f(x),"aria-label":`Details ${rt(x)}`,children:"Details"}),R&&s.jsx(Z.Item,{leftSection:s.jsx(Iw,{size:14}),onClick:()=>v(x),"aria-label":`Details ${rt(x)}`,children:"Details"}),I&&s.jsx(Z.Item,{leftSection:s.jsx(zk,{size:14}),onClick:()=>h(x),"aria-label":`Edit ${rt(x)}`,children:"Edit"}),F&&s.jsxs(s.Fragment,{children:[s.jsx(Z.Divider,{}),s.jsx(Z.Label,{children:"Admin"}),L&&s.jsx(Z.Item,{leftSection:s.jsx(Oz,{size:14}),onClick:()=>g(x),"aria-label":`Resend Subscriptions ${rt(x)}`,children:"Resend Subscriptions"})]}),B&&s.jsxs(s.Fragment,{children:[s.jsx(Z.Divider,{}),s.jsx(Z.Label,{children:"AWS AI"}),s.jsx(Z.Item,{leftSection:s.jsx(Wz,{size:14}),onClick:()=>S(x,C),"aria-label":`AWS Textract ${rt(x)}`,children:"AWS Textract"})]}),O&&s.jsxs(s.Fragment,{children:[s.jsx(Z.Divider,{}),s.jsx(Z.Label,{children:"Danger zone"}),s.jsx(Z.Item,{color:"red",leftSection:s.jsx(e0,{size:14}),onClick:()=>m(x),"aria-label":`Delete ${rt(x)}`,children:"Delete"})]})]})}return s.jsxs(s.Fragment,{children:[n==="Encounter"&&s.jsx(MV,{encounter:o,getMenu:b}),n==="Patient"&&s.jsx(FW,{patient:o,getMenu:b}),n==="ServiceRequest"&&s.jsx(Eq,{serviceRequest:o,getMenu:b}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&s.jsx(NV,{resource:o,getMenu:b}),s.jsx(KY,{resource:i,opened:l[0],onClose:l[1].close},`resend-subscriptions-${i==null?void 0:i.id}`)]})}function YY(){const e=le(),{id:t}=st(),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(),[b,w]=p.useState(!1),[y,x]=p.useState(!1);p.useEffect(()=>{if(r||i||l||b){x(!0);return}x(!1)},[r,i,l,b]);const C=p.useCallback(()=>{o(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(I=>{var O,F,L,B,D,_;d((F=(O=I.parameter)==null?void 0:O.find(P=>P.name==="status"))==null?void 0:F.valueCode),h((B=(L=I.parameter)==null?void 0:L.find(P=>P.name==="version"))==null?void 0:B.valueString),g((_=(D=I.parameter)==null?void 0:D.find(P=>P.name==="lastUpdated"))==null?void 0:_.valueInstant)}).catch(I=>k(Ae(I))).finally(()=>o(!1))},[e,t]),E=p.useCallback(I=>{const O=I.host,F=I.pingCount||1;O&&(w(!0),e.pushToAgent(n,O,`PING ${F}`,rn.PING,!0).then(L=>S(L)).catch(L=>k(Ae(L))).finally(()=>w(!1)))},[e,n]),T=p.useCallback(()=>{a(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(I=>{R("Agent config reloaded successfully.")}).catch(I=>k(Ae(I))).finally(()=>a(!1))},[e,t]),j=p.useCallback(()=>{c(!0),e.get(e.fhirUrl("Agent",t,"$upgrade"),{cache:"reload"}).then(I=>{R("Agent upgraded successfully.")}).catch(I=>k(Ae(I))).finally(()=>c(!1))},[e,t]);function R(I){ge({color:"green",title:"Success",icon:s.jsx(Js,{size:"1rem"}),message:I})}function k(I){ge({color:"red",title:"Error",message:I,autoClose:!1})}return s.jsxs(Me,{children:[s.jsx(ve,{order:1,children:"Agent Tools"}),s.jsxs("div",{style:{marginBottom:10},children:["Agent: ",s.jsx(Pl,{value:n,link:!0})]}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{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(ae,{onClick:C,loading:r,disabled:y&&!r,children:"Get Status"}),!r&&u&&s.jsx(pe,{children:s.jsxs(pe.Tbody,{children:[s.jsxs(pe.Tr,{children:[s.jsx(pe.Td,{children:"Status"}),s.jsx(pe.Td,{children:s.jsx(d0,{status:u})})]}),s.jsxs(pe.Tr,{children:[s.jsx(pe.Td,{children:"Version"}),s.jsx(pe.Td,{children:f})]}),s.jsxs(pe.Tr,{children:[s.jsx(pe.Td,{children:"Last Updated"}),s.jsx(pe.Td,{children:zn(m,void 0,{timeZoneName:"longOffset"})})]})]})}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{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(ae,{onClick:T,loading:i,disabled:y&&!i,"aria-label":"Reload config",children:"Reload Config"}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{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(ae,{onClick:j,loading:l,disabled:y&&!l,"aria-label":"Upgrade agent",children:"Upgrade"}),s.jsx(dn,{my:"lg"}),s.jsx(ve,{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(qe,{onSubmit:E,children:s.jsxs(te,{children:[s.jsx(ye,{id:"host",name:"host",placeholder:"ex. 127.0.0.1",label:"IP Address / Hostname",rightSection:s.jsx(en,{size:24,radius:"xl",variant:"filled",type:"submit","aria-label":"Ping",loading:b,disabled:y&&!b,children:s.jsx($z,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),s.jsx(dx,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!b&&v&&s.jsxs(s.Fragment,{children:[s.jsx(ve,{order:5,mt:"sm",mb:0,children:"Last Ping"}),s.jsx("pre",{children:v})]})]})}function XY(){return s.jsx(XG,{children:s.jsxs(Se,{errorElement:s.jsx(fK,{}),children:[s.jsx(Se,{path:"/signin",element:s.jsx(LK,{})}),s.jsx(Se,{path:"/oauth",element:s.jsx(IK,{})}),s.jsx(Se,{path:"/resetpassword",element:s.jsx(NK,{})}),s.jsx(Se,{path:"/setpassword/:id/:secret",element:s.jsx(OK,{})}),s.jsx(Se,{path:"/register",element:s.jsx(AK,{})}),s.jsx(Se,{path:"/changepassword",element:s.jsx(cK,{})}),s.jsx(Se,{path:"/security",element:s.jsx(MK,{})}),s.jsx(Se,{path:"/mfa",element:s.jsx(_K,{})}),s.jsx(Se,{path:"/batch",element:s.jsx(aK,{})}),s.jsx(Se,{path:"/bulk/:resourceType",element:s.jsx(lK,{})}),s.jsx(Se,{path:"/smart",element:s.jsx($K,{})}),s.jsx(Se,{path:"/forms/:id",element:s.jsx(bK,{})}),s.jsx(Se,{path:"/admin/super",element:s.jsx(XK,{})}),s.jsx(Se,{path:"/admin/config",element:s.jsx(GK,{})}),s.jsxs(Se,{path:"/admin",element:s.jsx(QK,{}),children:[s.jsx(Se,{path:"patients",element:s.jsx(qK,{})}),s.jsx(Se,{path:"bots/new",element:s.jsx(BK,{})}),s.jsx(Se,{path:"bots",element:s.jsx(FK,{})}),s.jsx(Se,{path:"clients/new",element:s.jsx(UK,{})}),s.jsx(Se,{path:"clients",element:s.jsx(zK,{})}),s.jsx(Se,{path:"details",element:s.jsx(DS,{})}),s.jsx(Se,{path:"invite",element:s.jsx(HK,{})}),s.jsx(Se,{path:"users",element:s.jsx(JK,{})}),s.jsx(Se,{path:"project",element:s.jsx(DS,{})}),s.jsx(Se,{path:"secrets",element:s.jsx(KK,{})}),s.jsx(Se,{path:"sites",element:s.jsx(YK,{})}),s.jsx(Se,{path:"members/:membershipId",element:s.jsx(WK,{})})]}),s.jsx(Se,{path:"/lab/assays",element:s.jsx(ZK,{})}),s.jsx(Se,{path:"/lab/panels",element:s.jsx(eY,{})}),s.jsx(Se,{path:"/:resourceType/:id/_history/:versionId/:tab",element:s.jsx(MS,{})}),s.jsx(Se,{path:"/:resourceType/:id/_history/:versionId",element:s.jsx(MS,{})}),s.jsxs(Se,{path:"/:resourceType/new",element:s.jsx(dK,{}),children:[s.jsx(Se,{index:!0,element:s.jsx(fm,{})}),s.jsx(Se,{path:"form",element:s.jsx(fm,{})}),s.jsx(Se,{path:"json",element:s.jsx(jY,{})}),s.jsx(Se,{path:"profiles",element:s.jsx(fm,{})})]}),s.jsxs(Se,{path:"/:resourceType/:id",element:s.jsx(GY,{}),children:[s.jsx(Se,{index:!0,element:s.jsx(OS,{})}),s.jsx(Se,{path:"apply",element:s.jsx(nY,{})}),s.jsx(Se,{path:"apps",element:s.jsx(rY,{})}),s.jsx(Se,{path:"event",element:s.jsx(iY,{})}),s.jsx(Se,{path:"blame",element:s.jsx(sY,{})}),s.jsx(Se,{path:"bots",element:s.jsx(kY,{})}),s.jsx(Se,{path:"builder",element:s.jsx(mY,{})}),s.jsx(Se,{path:"checklist",element:s.jsx(gY,{})}),s.jsx(Se,{path:"delete",element:s.jsx(vY,{})}),s.jsx(Se,{path:"details",element:s.jsx(bY,{})}),s.jsx(Se,{path:"edit",element:s.jsx(wY,{})}),s.jsx(Se,{path:"editor",element:s.jsx(hY,{})}),s.jsx(Se,{path:"history",element:s.jsx(SY,{})}),s.jsx(Se,{path:"json",element:s.jsx(CY,{})}),s.jsx(Se,{path:"preview",element:s.jsx(EY,{})}),s.jsx(Se,{path:"responses",element:s.jsx(_Y,{})}),s.jsx(Se,{path:"report",element:s.jsx(IY,{})}),s.jsx(Se,{path:"ranges",element:s.jsx(DY,{})}),s.jsx(Se,{path:"subscriptions",element:s.jsx(QY,{})}),s.jsx(Se,{path:"timeline",element:s.jsx(OS,{})}),s.jsx(Se,{path:"tools",element:s.jsx(YY,{})}),s.jsx(Se,{path:"profiles",element:s.jsx(TY,{})})]}),s.jsx(Se,{path:"/:resourceType",element:s.jsx(_S,{})}),s.jsx(Se,{path:"/",element:s.jsx(_S,{})})]})})}function JY(){const e=le(),t=e.getUserConfiguration(),n=ii(),[r]=_0();return e.isLoading()?s.jsx(Yr,{}):s.jsx($B,{logo:s.jsx(to,{size:24}),pathname:n.pathname,searchParams:r,version:k8,menus:ZY(t),displayAddBookmark:!!(t!=null&&t.id),children:s.jsx(p.Suspense,{fallback:s.jsx(Yr,{}),children:s.jsx(XY,{})})})}function ZY(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:eX(i.target)})))||[]}}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:s.jsx(Ez,{})}]}),t}const LS={Patient:Bz,Practitioner:jz,Organization:pz,ServiceRequest:Nz,DiagnosticReport:Lz,Questionnaire:Sz,admin:dz,AccessPolicy:Cz,Subscription:Hz,batch:Rz,Observation:kz};function eX(e){try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in LS){const n=LS[t];return s.jsx(n,{})}}catch{}return s.jsx(Oh,{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 tX(){const e=Pu(),t=new _k({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=tQ([{path:"*",element:s.jsx(JY,{})}]),o=a=>r.navigate(a);i2(document.getElementById("root")).render(s.jsx(p.StrictMode,{children:s.jsx(K8,{medplum:t,navigate:o,children:s.jsxs(xj,{theme:n,children:[s.jsx(ni,{position:"bottom-right"}),s.jsx(uQ,{router:r})]})})}))}tX().catch(console.error);
|
|
583
|
-
//# sourceMappingURL=index-
|
|
583
|
+
//# sourceMappingURL=index-DiO5UUQN.js.map
|