@medplum/app 3.3.0 → 3.3.1

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: `+E.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 Cl={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let gS=!1;function q6(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");Cl.Event=globalThis.Event,Cl.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},Cl.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function G6(e,t){if(!e)throw new Error(t)}function Zd(e){return new e.constructor(e.type,e)}const Ys={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let vS=!1;class fs extends Ap{constructor(t,n,r={}){gS||(q6(),gS=!0),super(),this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,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:s=Ys.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),s),G6(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(l=>{var u;return(u=this._ws)==null?void 0:u.send(l)}),this._messageQueue=[],this.onopen&&this.onopen(o),this.dispatchEvent(Zd(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(Zd(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(Zd(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(Zd(o))},this._url=t,this._protocols=n,this._options=r,this._options.startClosed&&(this._shouldReconnect=!1),this._options.binaryType?this._binaryType=this._options.binaryType:this._binaryType="blob",this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return fs.CONNECTING}get OPEN(){return fs.OPEN}get CLOSING(){return fs.CLOSING}get CLOSED(){return fs.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?fs.CLOSED:fs.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=Ys.maxEnqueuedMessages}=this._options;this._messageQueue.length<n&&(this._debug("enqueue",t),this._messageQueue.push(t))}}_debug(...t){this._options.debug&&this._debugLogger("RWS>",...t)}_getNextDelay(){const{reconnectionDelayGrowFactor:t=Ys.reconnectionDelayGrowFactor,minReconnectionDelay:n=Ys.minReconnectionDelay,maxReconnectionDelay:r=Ys.maxReconnectionDelay}=this._options;let o=0;return this._retryCount>0&&(o=n*Math.pow(t,this._retryCount-1),o>r&&(o=r)),this._debug("next delay",o),o}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=Ys.maxRetries,connectionTimeout:n=Ys.connectionTimeout}=this._options;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);return}this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),this._wait().then(()=>{if(this._closeCalled){this._connectLock=!1;return}!this._options.WebSocket&&typeof WebSocket>"u"&&!vS&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),vS=!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 Cl.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Cl.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new Cl.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 Q6=5e3;class Yg extends Ap{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 K6{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new Yg(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class Y6{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof LT))throw new dt(Qt("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new dt(Qt("Not a valid URL"))}const s=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 fs(o,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger});this.medplum=t,this.ws=s,this.masterSubEmitter=new Yg,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??Q6,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,o,s,l,u,d;try{const p=JSON.parse(n.data);if(p.type==="pong"){this.waitingForPong=!1;return}const h=p,m=(o=(r=h==null?void 0:h.entry)==null?void 0:r[0])==null?void 0:o.resource;if(m.type==="heartbeat"){(s=this.masterSubEmitter)==null||s.dispatchEvent({type:"heartbeat",payload:h});return}if(m.type==="handshake"){const x=ma(m.subscription),b={type:"connect",payload:{subscriptionId:x}};(l=this.masterSubEmitter)==null||l.dispatchEvent(b);const w=this.criteriaEntriesBySubscriptionId.get(x);if(!w){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}w.connecting=!1,w.emitter.dispatchEvent({...b});return}(u=this.masterSubEmitter)==null||u.dispatchEvent({type:"message",payload:h});const y=this.criteriaEntriesBySubscriptionId.get(ma(m.subscription));if(!y){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}y.emitter.dispatchEvent({type:"message",payload:h})}catch(p){console.error(p);const h={type:"error",payload:p};(d=this.masterSubEmitter)==null||d.dispatchEvent(h);for(const m of this.getAllCriteriaEmitters())m.dispatchEvent({...h})}}),t.addEventListener("error",()=>{var r;const n={type:"error",payload:new dt(uL(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 s of this.getAllCriteriaEmitters())s.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 l,u;let n=t==null?void 0:t.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${zt(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=(l=r==null?void 0:r.find(d=>d.name==="token"))==null?void 0:l.valueString,s=(u=r==null?void 0:r.find(d=>d.name==="websocket-url"))==null?void 0:u.valueUrl;if(!o)throw new dt(Qt("Failed to get token"));if(!s)throw new dt(Qt("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(bs(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 u;const{criteria:n,subscriptionProps:r,subscriptionId:o,token:s}=t;if(!this.criteriaEntries.has(n))return;const l=this.criteriaEntries.get(n);r?l.criteriaWithProps=l.criteriaWithProps.filter(d=>{const p=d.subscriptionProps;return!bs(r,p)}):l.bareCriteria=void 0,!l.bareCriteria&&l.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),(u=this.masterSubEmitter)==null||u._removeCriteria(n)),o&&this.criteriaEntriesBySubscriptionId.delete(o),s&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:s}}))}async subscribeToCriteria(t){if(!(this.ws.readyState!==WebSocket.OPEN||t.connecting)){t.connecting=!0;try{const[n,r]=await this.getTokenForCriteria(t);t.subscriptionId=n,t.token=r,this.criteriaEntriesBySubscriptionId.set(n,t),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:r}}))}catch(n){console.error(tt(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 K6(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 Yg(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const OT="3.3.0-0d59ebd14",X6=cn.FHIR_JSON+", */*; q=0.1",J6="https://api.medplum.com/",Z6=1e3,eF=6e4,tF=0,nF=3e5,rF="Binary/",yS={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]};class LT extends Ap{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)??oF(),this.storage=(t==null?void 0:t.storage)??new W6,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=dx((t==null?void 0:t.baseUrl)??J6),this.fhirBaseUrl=Bo(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=Bo(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=Bo(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=Bo(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),this.fhircastHubUrl=Bo(this.baseUrl,(t==null?void 0:t.fhircastHubUrl)??"fhircast/STU3"),this.clientId=(t==null?void 0:t.clientId)??"",this.clientSecret=(t==null?void 0:t.clientSecret)??"",this.defaultHeaders=(t==null?void 0:t.defaultHeaders)??{},this.onUnauthenticated=t==null?void 0:t.onUnauthenticated,this.refreshGracePeriod=(t==null?void 0:t.refreshGracePeriod)??nF,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?tF:eF),this.cacheTime>0?this.requestCache=new NT((t==null?void 0:t.resourceCacheSize)??Z6):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}getFhircastHubUrl(){return this.fhircastHubUrl}getDefaultHeaders(){return this.defaultHeaders}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=Bo(this.fhirBaseUrl,t);if(this.requestCache)for(const r of this.requestCache.keys())(r.endsWith(n)||r.includes(n+"?"))&&this.requestCache.delete(r)}get(t,n={}){t=t.toString();const r=this.getCacheEntry(t,n);if(r)return r.value;let o;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?o=new Promise((l,u)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:l,reject:u}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):o=this.request("GET",t,n);const s=new wo(o);return this.setCacheEntry(t,s),s}post(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("POST",t,o)}put(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("PUT",t,o)}patch(t,n,r={}){return t=t.toString(),this.setRequestBody(r,n),this.setRequestContentType(r,cn.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,s=!0){let l=o;s&&(l=await this.ensureCodeChallenge(o)),window.location.assign(this.getExternalAuthRedirectUri(t,n,r,l,s))}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,s=!0){const l=new URL(t);if(l.searchParams.set("response_type","code"),l.searchParams.set("client_id",n),l.searchParams.set("redirect_uri",r),l.searchParams.set("scope",o.scope??"openid profile email"),l.searchParams.set("state",JSON.stringify(o)),s){const{codeChallenge:u,codeChallengeMethod:d}=o;if(!d)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!u)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");l.searchParams.set("code_challenge_method",d),l.searchParams.set("code_challenge",u)}return l.toString()}fhirUrl(...t){return new URL(Bo(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=t$(n)),r}search(t,n,r){const o=this.fhirSearchUrl(t,n),s="search-"+o.toString(),l=this.getCacheEntry(s,r);if(l)return l.value;const u=this.getBundle(o,r);return this.setCacheEntry(s,u),u}searchOne(t,n,r){const o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();const s="searchOne-"+o.toString(),l=this.getCacheEntry(s,r);if(l)return l.value;const u=new wo(this.search(t,o.searchParams,r).then(d=>{var p,h;return(h=(p=d.entry)==null?void 0:p[0])==null?void 0:h.resource}));return this.setCacheEntry(s,u),u}searchResources(t,n,r){const s="searchResources-"+this.fhirSearchUrl(t,n).toString(),l=this.getCacheEntry(s,r);if(l)return l.value;const u=new wo(this.search(t,n,r).then(wS));return this.setCacheEntry(s,u),u}async*searchResourcePages(t,n,r){var s,l;let o=this.fhirSearchUrl(t,n);for(;o;){const u=new URL(o).searchParams,d=await this.search(t,u,r),p=(s=d.link)==null?void 0:s.find(h=>h.relation==="next");if(!((l=d.entry)!=null&&l.length)&&!p)break;yield wS(d),o=p!=null&&p.url?new URL(p.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,s;const r=(s=(o=this.requestCache)==null?void 0:o.get(this.fhirUrl(t,n).toString()))==null?void 0:s.value;return r!=null&&r.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return yS;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 wo(Promise.reject(new Error("Missing reference")));if(r==="system")return new wo(Promise.resolve(yS));const[o,s]=r.split("/");return!o||!s?new wo(Promise.reject(new Error("Invalid reference"))):this.readResource(o,s,n)}requestSchema(t){if(nT(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new wo((async()=>{const s=`{
101
+ */const Cl={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let gS=!1;function q6(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");Cl.Event=globalThis.Event,Cl.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},Cl.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function G6(e,t){if(!e)throw new Error(t)}function Zd(e){return new e.constructor(e.type,e)}const Ys={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let vS=!1;class fs extends Ap{constructor(t,n,r={}){gS||(q6(),gS=!0),super(),this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,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:s=Ys.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),s),G6(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(l=>{var u;return(u=this._ws)==null?void 0:u.send(l)}),this._messageQueue=[],this.onopen&&this.onopen(o),this.dispatchEvent(Zd(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(Zd(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(Zd(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(Zd(o))},this._url=t,this._protocols=n,this._options=r,this._options.startClosed&&(this._shouldReconnect=!1),this._options.binaryType?this._binaryType=this._options.binaryType:this._binaryType="blob",this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return fs.CONNECTING}get OPEN(){return fs.OPEN}get CLOSING(){return fs.CLOSING}get CLOSED(){return fs.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?fs.CLOSED:fs.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=Ys.maxEnqueuedMessages}=this._options;this._messageQueue.length<n&&(this._debug("enqueue",t),this._messageQueue.push(t))}}_debug(...t){this._options.debug&&this._debugLogger("RWS>",...t)}_getNextDelay(){const{reconnectionDelayGrowFactor:t=Ys.reconnectionDelayGrowFactor,minReconnectionDelay:n=Ys.minReconnectionDelay,maxReconnectionDelay:r=Ys.maxReconnectionDelay}=this._options;let o=0;return this._retryCount>0&&(o=n*Math.pow(t,this._retryCount-1),o>r&&(o=r)),this._debug("next delay",o),o}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=Ys.maxRetries,connectionTimeout:n=Ys.connectionTimeout}=this._options;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);return}this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),this._wait().then(()=>{if(this._closeCalled){this._connectLock=!1;return}!this._options.WebSocket&&typeof WebSocket>"u"&&!vS&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),vS=!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 Cl.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Cl.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new Cl.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 Q6=5e3;class Yg extends Ap{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 K6{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new Yg(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class Y6{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof LT))throw new dt(Qt("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new dt(Qt("Not a valid URL"))}const s=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 fs(o,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger});this.medplum=t,this.ws=s,this.masterSubEmitter=new Yg,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??Q6,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,o,s,l,u,d;try{const p=JSON.parse(n.data);if(p.type==="pong"){this.waitingForPong=!1;return}const h=p,m=(o=(r=h==null?void 0:h.entry)==null?void 0:r[0])==null?void 0:o.resource;if(m.type==="heartbeat"){(s=this.masterSubEmitter)==null||s.dispatchEvent({type:"heartbeat",payload:h});return}if(m.type==="handshake"){const x=ma(m.subscription),b={type:"connect",payload:{subscriptionId:x}};(l=this.masterSubEmitter)==null||l.dispatchEvent(b);const w=this.criteriaEntriesBySubscriptionId.get(x);if(!w){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}w.connecting=!1,w.emitter.dispatchEvent({...b});return}(u=this.masterSubEmitter)==null||u.dispatchEvent({type:"message",payload:h});const y=this.criteriaEntriesBySubscriptionId.get(ma(m.subscription));if(!y){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}y.emitter.dispatchEvent({type:"message",payload:h})}catch(p){console.error(p);const h={type:"error",payload:p};(d=this.masterSubEmitter)==null||d.dispatchEvent(h);for(const m of this.getAllCriteriaEmitters())m.dispatchEvent({...h})}}),t.addEventListener("error",()=>{var r;const n={type:"error",payload:new dt(uL(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 s of this.getAllCriteriaEmitters())s.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 l,u;let n=t==null?void 0:t.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${zt(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=(l=r==null?void 0:r.find(d=>d.name==="token"))==null?void 0:l.valueString,s=(u=r==null?void 0:r.find(d=>d.name==="websocket-url"))==null?void 0:u.valueUrl;if(!o)throw new dt(Qt("Failed to get token"));if(!s)throw new dt(Qt("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(bs(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 u;const{criteria:n,subscriptionProps:r,subscriptionId:o,token:s}=t;if(!this.criteriaEntries.has(n))return;const l=this.criteriaEntries.get(n);r?l.criteriaWithProps=l.criteriaWithProps.filter(d=>{const p=d.subscriptionProps;return!bs(r,p)}):l.bareCriteria=void 0,!l.bareCriteria&&l.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),(u=this.masterSubEmitter)==null||u._removeCriteria(n)),o&&this.criteriaEntriesBySubscriptionId.delete(o),s&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:s}}))}async subscribeToCriteria(t){if(!(this.ws.readyState!==WebSocket.OPEN||t.connecting)){t.connecting=!0;try{const[n,r]=await this.getTokenForCriteria(t);t.subscriptionId=n,t.token=r,this.criteriaEntriesBySubscriptionId.set(n,t),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:r}}))}catch(n){console.error(tt(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 K6(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 Yg(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const OT="3.3.1-9d4777e8d",X6=cn.FHIR_JSON+", */*; q=0.1",J6="https://api.medplum.com/",Z6=1e3,eF=6e4,tF=0,nF=3e5,rF="Binary/",yS={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]};class LT extends Ap{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)??oF(),this.storage=(t==null?void 0:t.storage)??new W6,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=dx((t==null?void 0:t.baseUrl)??J6),this.fhirBaseUrl=Bo(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=Bo(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=Bo(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=Bo(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),this.fhircastHubUrl=Bo(this.baseUrl,(t==null?void 0:t.fhircastHubUrl)??"fhircast/STU3"),this.clientId=(t==null?void 0:t.clientId)??"",this.clientSecret=(t==null?void 0:t.clientSecret)??"",this.defaultHeaders=(t==null?void 0:t.defaultHeaders)??{},this.onUnauthenticated=t==null?void 0:t.onUnauthenticated,this.refreshGracePeriod=(t==null?void 0:t.refreshGracePeriod)??nF,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?tF:eF),this.cacheTime>0?this.requestCache=new NT((t==null?void 0:t.resourceCacheSize)??Z6):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}getFhircastHubUrl(){return this.fhircastHubUrl}getDefaultHeaders(){return this.defaultHeaders}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=Bo(this.fhirBaseUrl,t);if(this.requestCache)for(const r of this.requestCache.keys())(r.endsWith(n)||r.includes(n+"?"))&&this.requestCache.delete(r)}get(t,n={}){t=t.toString();const r=this.getCacheEntry(t,n);if(r)return r.value;let o;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?o=new Promise((l,u)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:l,reject:u}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):o=this.request("GET",t,n);const s=new wo(o);return this.setCacheEntry(t,s),s}post(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("POST",t,o)}put(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("PUT",t,o)}patch(t,n,r={}){return t=t.toString(),this.setRequestBody(r,n),this.setRequestContentType(r,cn.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,s=!0){let l=o;s&&(l=await this.ensureCodeChallenge(o)),window.location.assign(this.getExternalAuthRedirectUri(t,n,r,l,s))}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,s=!0){const l=new URL(t);if(l.searchParams.set("response_type","code"),l.searchParams.set("client_id",n),l.searchParams.set("redirect_uri",r),l.searchParams.set("scope",o.scope??"openid profile email"),l.searchParams.set("state",JSON.stringify(o)),s){const{codeChallenge:u,codeChallengeMethod:d}=o;if(!d)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!u)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");l.searchParams.set("code_challenge_method",d),l.searchParams.set("code_challenge",u)}return l.toString()}fhirUrl(...t){return new URL(Bo(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=t$(n)),r}search(t,n,r){const o=this.fhirSearchUrl(t,n),s="search-"+o.toString(),l=this.getCacheEntry(s,r);if(l)return l.value;const u=this.getBundle(o,r);return this.setCacheEntry(s,u),u}searchOne(t,n,r){const o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();const s="searchOne-"+o.toString(),l=this.getCacheEntry(s,r);if(l)return l.value;const u=new wo(this.search(t,o.searchParams,r).then(d=>{var p,h;return(h=(p=d.entry)==null?void 0:p[0])==null?void 0:h.resource}));return this.setCacheEntry(s,u),u}searchResources(t,n,r){const s="searchResources-"+this.fhirSearchUrl(t,n).toString(),l=this.getCacheEntry(s,r);if(l)return l.value;const u=new wo(this.search(t,n,r).then(wS));return this.setCacheEntry(s,u),u}async*searchResourcePages(t,n,r){var s,l;let o=this.fhirSearchUrl(t,n);for(;o;){const u=new URL(o).searchParams,d=await this.search(t,u,r),p=(s=d.link)==null?void 0:s.find(h=>h.relation==="next");if(!((l=d.entry)!=null&&l.length)&&!p)break;yield wS(d),o=p!=null&&p.url?new URL(p.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,s;const r=(s=(o=this.requestCache)==null?void 0:o.get(this.fhirUrl(t,n).toString()))==null?void 0:s.value;return r!=null&&r.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return yS;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 wo(Promise.reject(new Error("Missing reference")));if(r==="system")return new wo(Promise.resolve(yS));const[o,s]=r.split("/");return!o||!s?new wo(Promise.reject(new Error("Invalid reference"))):this.readResource(o,s,n)}requestSchema(t){if(nT(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new wo((async()=>{const s=`{
102
102
  StructureDefinitionList(name: "${t}") {
103
103
  resourceType,
104
104
  name,
@@ -584,4 +584,4 @@ Error generating stack: `+E.message+`
584
584
  }
585
585
  ]
586
586
  }`,ZQ="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 eK(){const e=Pe(),{id:t}=Ft(),[n,r]=v.useState(),[o,s]=v.useState(),[l,u]=v.useState(JQ),[d,p]=v.useState(ZQ),[h,m]=v.useState(cn.FHIR_JSON),y=v.useRef(null),x=v.useRef(null),[b,w]=v.useState(!1);v.useEffect(()=>{e.readResource("Bot",t).then(async R=>{r(R),s(await tK(e,R))}).catch(R=>Ne({color:"red",message:tt(R),autoClose:!1}))},[e,t]);const j=v.useCallback(async()=>qc(y.current,{command:"getValue"}),[]),T=v.useCallback(async()=>qc(y.current,{command:"getOutput"}),[]),P=v.useCallback(async()=>h===cn.FHIR_JSON?JSON.parse(l):d,[h,l,d]),k=v.useCallback(async R=>{R.preventDefault(),R.stopPropagation(),w(!0);try{const M=await j(),A=await T(),$=await e.createAttachment(M,"index.ts","text/typescript"),z=await e.createAttachment(A,"index.js","text/typescript"),G=[{op:"add",path:"/sourceCode",value:$},{op:"add",path:"/executableCode",value:z}];await e.patchResource("Bot",t,G),Ne({color:"green",message:"Saved"})}catch(M){Ne({color:"red",message:tt(M),autoClose:!1})}finally{w(!1)}},[e,t,j,T]),C=v.useCallback(async R=>{R.preventDefault(),R.stopPropagation(),w(!0);try{await e.post(e.fhirUrl("Bot",t,"$deploy")),Ne({color:"green",message:"Deployed"})}catch(M){Ne({color:"red",message:tt(M),autoClose:!1})}finally{w(!1)}},[e,t]),_=v.useCallback(async R=>{R.preventDefault(),R.stopPropagation(),w(!0);try{const M=await P(),A=await e.post(e.fhirUrl("Bot",t,"$execute"),M,h);await qc(x.current,{command:"setValue",value:A}),Ne({color:"green",message:"Success"})}catch(M){Ne({color:"red",message:tt(M),autoClose:!1})}finally{w(!1)}},[e,t,P,h]);return!n||o===void 0?null:i.jsxs($r,{m:0,gutter:0,style:{overflow:"hidden"},children:[i.jsx($r.Col,{span:8,children:i.jsxs(fr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",mih:400,children:[i.jsx(XQ,{iframeRef:y,language:"typescript",module:"commonjs",testId:"code-frame",defaultValue:o,minHeight:"528px"}),i.jsxs(ye,{justify:"flex-end",gap:"xs",children:[i.jsx(Ee,{type:"button",onClick:k,loading:b,leftSection:i.jsx(QF,{size:"1rem"}),children:"Save"}),i.jsx(Ee,{type:"button",onClick:C,loading:b,leftSection:i.jsx(kx,{size:"1rem"}),children:"Deploy"}),i.jsx(Ee,{type:"button",onClick:_,loading:b,leftSection:i.jsx(l8,{size:"1rem"}),children:"Execute"})]})]})}),i.jsxs($r.Col,{span:4,children:[i.jsxs(fr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[i.jsx(dn,{data:[{label:"FHIR",value:cn.FHIR_JSON},{label:"HL7",value:cn.HL7_V2}],onChange:R=>m(R.currentTarget.value)}),h===cn.FHIR_JSON?i.jsx(ql,{value:l,onChange:R=>u(R),autosize:!0,minRows:15}):i.jsx("textarea",{className:KQ.hl7Input,value:d,onChange:R=>p(R.currentTarget.value),rows:15})]}),i.jsx(fr,{m:2,p:"xs",shadow:"md",children:i.jsx(YQ,{iframeRef:x,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function tK(e,t){var n,r,o;if((n=t.sourceCode)!=null&&n.url){const s=(o=(r=t.sourceCode.url)==null?void 0:r.split("/"))==null?void 0:o.find(dT);return(await e.download(e.fhirUrl("Binary",s))).text()}return t.code??""}function Ma(e){let t=e.meta;return t&&(t={...t,lastUpdated:void 0,versionId:void 0,author:void 0}),{...e,meta:t}}function nK(){const e=Pe(),{resourceType:t,id:n}=Ft(),r={reference:t+"/"+n},o=v.useCallback(s=>{e.updateResource(Ma(s)).then(()=>{Ne({color:"green",message:"Success"})}).catch(l=>{Ne({color:"red",message:tt(l),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return i.jsx(at,{children:i.jsx(OV,{value:r,onSubmit:o})});case"Questionnaire":return i.jsx(at,{children:i.jsx(SW,{questionnaire:r,onSubmit:o})});default:return null}}function rK(){const{resourceType:e,id:t}=Ft(),n=Ht({reference:e+"/"+t}),r=Tn();return n?i.jsx(at,{children:i.jsx(qW,{value:n,onStart:(o,s)=>r(`/forms/${ma(s)}`),onEdit:(o,s,l)=>r(`/${l.reference}}`)})}):null}function oK(){const e=Pe(),{resourceType:t,id:n}=Ft(),r=Tn();return i.jsxs(at,{children:[i.jsxs("p",{children:["Are you sure you want to delete this ",t,"?"]}),i.jsx(Ee,{color:"red",onClick:()=>{e.deleteResource(t,n).then(()=>r(`/${t}`)).catch(o=>Ne({color:"red",message:tt(o),autoClose:!1}))},children:"Delete"})]})}const iK="_selectProfileBtn_tbaz6_1",sK="_chevron_tbaz6_13",Bj={selectProfileBtn:iK,chevron:sK};function aK(){var d,p;const{resourceType:e,id:t}=Ft(),n=Ht({reference:e+"/"+t}),[r,o]=v.useState(),s=gu({onDropdownClose:()=>s.resetSelectedOption()}),l=v.useMemo(()=>{var h;if(bn((h=n==null?void 0:n.meta)==null?void 0:h.profile))return[i.jsx(lt.Option,{value:"",children:"None"},""),...n.meta.profile.map(m=>i.jsx(lt.Option,{value:m,children:m},m))]},[(d=n==null?void 0:n.meta)==null?void 0:d.profile]);if(v.useEffect(()=>{var h,m;((m=(h=n==null?void 0:n.meta)==null?void 0:h.profile)==null?void 0:m.length)===1&&o(n.meta.profile[0])},[(p=n==null?void 0:n.meta)==null?void 0:p.profile]),!n)return null;let u;return bn(l)&&(u=i.jsx(ye,{justify:"flex-end",children:i.jsxs(et,{align:"flex-end",gap:"xs",children:[i.jsxs(lt,{store:s,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:h=>{o(h),s.closeDropdown()},children:[i.jsx(lt.Target,{children:i.jsx(Qn,{onClick:()=>s.toggleDropdown(),children:i.jsxs(wy,{fw:"bold",fs:"sm",className:Bj.selectProfileBtn,children:[i.jsx("span",{children:"Pick profile"}),i.jsx(Ex,{stroke:1.5,className:Bj.chevron})]})})}),i.jsx(lt.Dropdown,{w:"max-content",children:i.jsx(lt.Options,{children:l})})]}),i.jsx(se,{children:r?i.jsxs(i.Fragment,{children:[i.jsx(_e,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),i.jsx(_e,{span:!0,size:"sm",children:r||"Nothing selected"})]}):i.jsx(_e,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),i.jsx(at,{children:i.jsxs(et,{gap:"xl",children:[u,i.jsx(Wx,{value:n,profileUrl:r})]})})}function lK(){const e=Pe(),{resourceType:t,id:n}=Ft(),[r,o]=v.useState(),[s,l]=v.useState(),u=Tn(),[d,p]=v.useState();v.useEffect(()=>{e.readResource(t,n).then(x=>{o(Br(x)),l(Br(x))}).catch(x=>{p(Wt(x)),Ne({color:"red",message:tt(x),autoClose:!1})})},[e,t,n]);const h=v.useCallback(x=>{p(void 0),e.updateResource(Ma(x)).then(()=>{u(`/${t}/${n}/details`),Ne({id:"succes",color:"green",message:"Success"})}).catch(b=>{p(Wt(b)),Ne({color:"red",message:tt(b),autoClose:!1})})},[e,t,n,u]),m=v.useCallback(x=>{p(void 0);const b=PP.createPatch(r,x);e.patchResource(t,n,b).then(()=>{u(`/${t}/${n}/details`),Ne({id:"succes",color:"green",message:"Success"})}).catch(w=>{p(Wt(w)),Ne({color:"red",message:tt(w),autoClose:!1})})},[e,t,n,r,u]),y=v.useCallback(()=>u(`/${t}/${n}/delete`),[u,t,n]);return s?i.jsx(at,{children:i.jsx(Mf,{defaultValue:s,onSubmit:h,onPatch:m,onDelete:y,outcome:d})}):null}function cK(){const{resourceType:e,id:t}=Ft(),n=Ht({reference:e+"/"+t});return n?i.jsx(at,{maw:600,children:n.resourceType==="Patient"?i.jsx(DV,{patient:n}):i.jsx(Ni,{icon:i.jsx(Ia,{size:16}),title:"Unsupported export type",color:"red",children:"This page is only supported for Patient resources"})}):null}function MR({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,o=Pe(),[s,l]=v.useState();return v.useEffect(()=>{o.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(u=>{l(u.filter(oB))}).catch(console.error)},[o,n,r]),i.jsx(It,{value:t==null?void 0:t.url,onChange:u=>{const d=s==null?void 0:s.find(p=>p.url===u);d&&n(d)},children:i.jsx(It.List,{children:s==null?void 0:s.map(u=>{var h,m;const d=(m=(h=e.meta)==null?void 0:h.profile)==null?void 0:m.includes(u.url),p=d?"This profile is present in this resource's meta.profile property.":"This profile is not included in this resource's meta.profile property.";return i.jsx(It.Tab,{value:u.url,title:p,rightSection:d&&i.jsx(nx,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:i.jsx(S8,{size:"90%"})}),children:u.title||u.name},u.url)})})})}function OR(e,t){const n=Pe(),r=Tn();return{defaultValue:{resourceType:e},handleSubmit:l=>{t&&t(void 0),n.createResource(l).then(u=>r("/"+u.resourceType+"/"+u.id)).catch(u=>{t&&t(Wt(u)),Ne({color:"red",message:tt(u),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function Cg(){const{resourceType:e}=Ft(),t=zi(),[n,r]=v.useState(),{defaultValue:o,handleSubmit:s}=OR(e,r),[l,u]=v.useState(),d=t.pathname.toLowerCase().endsWith("profiles"),p=v.useCallback(h=>{const m=Ma(h);l&&gT(m,l.url),s(m)},[l,s]);return d?i.jsx(at,{children:i.jsxs(et,{children:[i.jsx(MR,{resource:o,currentProfile:l,onChange:u}),l?i.jsx(Mf,{defaultValue:o,onSubmit:p,outcome:n,profileUrl:l.url},l.url):i.jsx(_e,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):i.jsx(at,{children:i.jsx(Mf,{defaultValue:o,onSubmit:s,outcome:n})})}function uK(){const e=Pe(),{resourceType:t,id:n}=Ft(),r=e.readHistory(t,n).read();return i.jsx(at,{children:i.jsx(vH,{history:r})})}function dK(){const{resourceType:e}=Ft(),[t,n]=v.useState(),{defaultValue:r,handleSubmit:o}=OR(e,n),s=v.useCallback(l=>{o(JSON.parse(l["new-resource"]))},[o]);return i.jsxs(at,{children:[t&&i.jsx(co,{outcome:t}),i.jsxs(mt,{onSubmit:s,children:[i.jsx(ql,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:Po(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),i.jsx(ye,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:i.jsx(Ee,{type:"submit",children:"OK"})})]})]})}function fK(){const e=Pe(),{resourceType:t,id:n}=Ft(),r=Ht({reference:t+"/"+n}),o=Tn(),[s,l]=v.useState(),u=v.useCallback(d=>{e.updateResource(Ma(JSON.parse(d.resource))).then(()=>{l(void 0),o(`/${t}/${n}/details`),Ne({color:"green",message:"Success"})}).catch(p=>{Ne({color:"red",message:tt(p),autoClose:!1})})},[e,t,n,o]);return r?i.jsxs(at,{children:[s&&i.jsx(co,{outcome:s}),i.jsxs(mt,{onSubmit:u,children:[i.jsx(ql,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:Po(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),i.jsx(ye,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:i.jsx(Ee,{type:"submit",children:"OK"})})]})]}):null}function pK(){const{resourceType:e,id:t}=Ft();return Ht({reference:e+"/"+t})?i.jsxs(at,{children:[i.jsxs(Ni,{icon:i.jsx(Ia,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",i.jsx("br",{}),i.jsx(Nt,{href:`/forms/${t}`,children:`/forms/${t}`})]}),i.jsx(eR,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function hK(){const e=Pe(),{resourceType:t,id:n}=Ft(),[r,o]=v.useState(),[s,l]=v.useState();return v.useEffect(()=>{e.readResource(t,n).then(u=>o(Br(u))).catch(u=>{Ne({color:"red",message:tt(u)})})},[e,t,n]),r?i.jsxs(at,{children:[i.jsxs($e,{order:2,children:["Available ",t," profiles"]}),i.jsx(et,{children:i.jsxs(i.Fragment,{children:[i.jsx(MR,{resource:r,currentProfile:s,onChange:l}),s?i.jsx(mK,{profile:s,resource:r,onResourceUpdated:u=>o(u)},s.url):i.jsx(_e,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const mK=({profile:e,resource:t,onResourceUpdated:n})=>{const r=Pe(),[o,s]=v.useState(),[l,u]=v.useState(()=>{var p,h;return(h=(p=t.meta)==null?void 0:p.profile)==null?void 0:h.includes(e.url)}),d=v.useCallback(p=>{s(void 0);const h=Ma(p);l?gT(h,e.url):n$(h,e.url),r.updateResource(h).then(m=>{n(m),Ne({color:"green",message:"Success"})}).catch(m=>{s(Wt(m)),Ne({color:"red",message:tt(m),autoClose:!1})})},[r,e.url,n,l]);return i.jsxs(et,{children:[i.jsx(ju,{size:"md",checked:l,label:`Conform resource to ${e.title}`,onChange:p=>u(p.currentTarget.checked),"data-testid":"profile-toggle"}),l?i.jsx(Mf,{profileUrl:e.url,defaultValue:t,onSubmit:d,outcome:o}):i.jsx("form",{noValidate:!0,onSubmit:p=>{p.preventDefault(),d(t)},children:i.jsx(ye,{justify:"flex-end",mt:"xl",children:i.jsx(Ee,{type:"submit",children:"OK"})})})]})},LR={"Create Only":"create","Update Only":"update","Delete Only":"delete","All Interactions":void 0},gK=Object.keys(LR);function vK(){const e=Pe(),{id:t}=Ft(),[n,r]=v.useState(),[o,s]=v.useState("create"),[l,u]=v.useState(0),d=e.searchResources("Subscription","status=active&_count=100").read().filter(h=>yK(h,t));function p(){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:zt(n)},...o?{extension:[{url:"https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction",valueCode:o}]}:void 0}).then(()=>{r(void 0),u(Date.now()),e.invalidateSearches("Subscription"),Ne({color:"green",message:"Success"})}).catch(h=>Ne({color:"red",message:tt(h),autoClose:!1}))}return i.jsxs(at,{children:[i.jsx($e,{children:"Bots"}),i.jsxs(et,{children:[d.length===0&&i.jsx("p",{children:"No bots found."}),d.map(h=>{var m;return i.jsxs("div",{children:[i.jsx("h3",{children:i.jsx(ec,{value:{reference:(m=h.channel)==null?void 0:m.endpoint},link:!0})}),i.jsxs("p",{children:["Criteria: ",h.criteria]})]},h.id)})]}),i.jsx(kn,{}),i.jsxs(et,{mt:10,children:[i.jsx(fu,{size:"lg",htmlFor:"bot",children:"Connect to bot"}),i.jsxs(ye,{children:[i.jsx(Na,{name:"bot",resourceType:"Bot",onChange:h=>r(h)}),i.jsx(Ee,{onClick:p,children:"Connect"})]}),i.jsx(ye,{children:i.jsx(dn,{name:"subscription-trigger-event",defaultValue:"Create Only",label:"Subscription Trigger Event",data:gK,onChange:h=>s(LR[h.target.value])})})]}),i.jsx("div",{style:{display:"none"},children:l})]})}function yK(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 xK(){const{id:e}=Ft(),t=Tn(),[n,r]=v.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:Se.EQUALS,value:"Questionnaire/"+e}],fields:["id","_lastUpdated"]});return i.jsx(at,{children:i.jsx(Ou,{search:n,onClick:o=>t(`/${o.resource.resourceType}/${o.resource.id}`),onChange:o=>r(o.definition),hideFilters:!0,hideToolbar:!0})})}function bK(){const e=Pe(),{resourceType:t,id:n}=Ft(),r=Ht({reference:t+"/"+n}),o=v.useCallback(s=>{e.updateResource(Ma(s)).then(()=>{Ne({color:"green",message:"Success"})}).catch(l=>{Ne({color:"red",message:tt(l),autoClose:!1})})},[e]);return r?i.jsx(at,{children:i.jsx($W,{onSubmit:o,definition:r})}):null}function wK(){const{resourceType:e,id:t}=Ft(),n=Ht({reference:e+"/"+t});return n?i.jsx(at,{children:e==="MeasureReport"?i.jsx(RV,{measureReport:n}):i.jsx(Vx,{value:n})}):null}const SK="_container_1ue98_1",jK="_entry_1ue98_14",CK="_active_1ue98_21",Eg={container:SK,entry:jK,active:CK};function EK(e){const t=Pe(),n=Ht(e.value),[r,o]=v.useState();return v.useEffect(()=>{if(!n)return;const s=i0(n);if(!s)return;const l="reference"in s?s.reference:zt(s);t.search("ServiceRequest","subject="+l).then(u=>{const p=(u.entry??[]).map(h=>h.resource);RP(p),p.reverse(),o(p)}).catch(u=>Ne({color:"red",message:tt(u),autoClose:!1}))},[t,n]),r?i.jsx("div",{"data-testid":"quick-service-requests",className:Eg.container,children:r.map(s=>{var l,u,d,p,h,m,y;return i.jsxs("div",{className:At(Eg.entry,{[Eg.active]:s.id===(n==null?void 0:n.id)}),children:[i.jsx("p",{children:i.jsx(xt,{to:s,children:kK(s)})}),((u=(l=s.category)==null?void 0:l[0])==null?void 0:u.text)&&i.jsx("p",{children:(d=s.category[0])==null?void 0:d.text}),((m=(h=(p=s.code)==null?void 0:p.coding)==null?void 0:h[0])==null?void 0:m.code)&&i.jsx("p",{children:(y=s.code.coding[0])==null?void 0:y.code}),i.jsx("p",{children:TK(s)})]},s.id)})}):null}function kK(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function TK(e){var t;return e.authoredOn?e.authoredOn.substring(0,10):(t=e.meta)!=null&&t.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const PK="_container_1l2dh_1",RK={container:PK};function _K(e){var o,s,l,u;const t=Ht(e.valueSet);if(!t)return null;const n=[""],r=(u=(l=(s=(o=t.compose)==null?void 0:o.include)==null?void 0:s[0])==null?void 0:l.concept)==null?void 0:u.map(d=>d.code);return r&&n.push(...r),e.defaultValue&&!n.includes(e.defaultValue)&&n.push(e.defaultValue),i.jsx("div",{className:RK.container,children:i.jsx(dn,{defaultValue:e.defaultValue,onChange:d=>e.onChange(d.currentTarget.value),data:n})})}function DK(e){var n,r;const t=Ht(e.specimen);return t?i.jsxs(pt,{children:[i.jsxs(pt.Entry,{children:[i.jsx(pt.Key,{children:"Type"}),i.jsx(pt.Value,{children:"Specimen"})]}),i.jsxs(pt.Entry,{children:[i.jsx(pt.Key,{children:"Collected"}),i.jsx(pt.Value,{children:pr((n=t.collection)==null?void 0:n.collectedDateTime)})]}),i.jsxs(pt.Entry,{children:[i.jsx(pt.Key,{children:"Specimen Age"}),i.jsx(pt.Value,{children:IK(t)})]}),(r=t.collection)!=null&&r.collectedDateTime&&t.receivedTime?i.jsxs(pt.Entry,{children:[i.jsx(pt.Key,{children:"Specimen Stability"}),i.jsx(pt.Value,{children:NK(t)})]}):i.jsx(i.Fragment,{})]}):null}function IK(e){var o;const t=(o=e.collection)==null?void 0:o.collectedDateTime;if(!t)return;const n=new Date(t);return $R(FR(n,new Date))}function NK(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 $R(FR(t,n))}function $R(e){return e.toString().padStart(3,"0")+"D"}function FR(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function AK(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"),e==="Patient"&&t.push("Export"),t}const MK=[];function OK(){var k,C,_,R,M,A,$;const e=Pe(),{resourceType:t,id:n}=Ft(),r={reference:t+"/"+n},o=Tn(),[s,l]=v.useState(),u=Ht(r,l),d=AK(t),[p,h]=v.useState(()=>{const z=window.location.pathname.split("/").pop();return z&&d.map(G=>G.toLowerCase()).includes(z)?z:d[0].toLowerCase()}),m=fn();async function y(){var q,Y;const G=(Y=(q=(await e.readHistory(t,n)).entry)==null?void 0:q.find(Q=>!!Q.resource))==null?void 0:Y.resource;G?x(G):Ne({color:"red",message:"No history to restore",autoClose:!1})}function x(z){e.updateResource(Ma(z)).then(()=>{l(void 0),Ne({color:"green",message:"Success"})}).catch(G=>{Ne({color:"red",message:tt(G),autoClose:!1})})}if(s)return dL(s)?i.jsxs(at,{children:[i.jsx($e,{children:"Deleted"}),i.jsx("p",{children:"The resource was deleted."}),i.jsx(Ee,{color:"red",onClick:y,children:"Restore"})]}):i.jsx(co,{outcome:s});function b(z){z||(z=d[0].toLowerCase()),h(z),o(`/${t}/${n}/${z}`)}function w(z){const G=u,q=G.orderDetail||[];q.length===0&&q.push({}),q[0].text!==z&&(q[0].text=z,x({...G,orderDetail:q}))}const j=u&&i0(u),T=u&&iQ(u),P=(_=(C=(k=e.getUserConfiguration())==null?void 0:k.option)==null?void 0:C.find(z=>z.id==="statusValueSet"))==null?void 0:_.valueString;return i.jsxs(i.Fragment,{children:[(u==null?void 0:u.resourceType)==="ServiceRequest"&&P&&i.jsx(_K,{valueSet:{reference:P},defaultValue:(M=(R=u.orderDetail)==null?void 0:R[0])==null?void 0:M.text,onChange:w},zt(u)+"-"+(($=(A=u.orderDetail)==null?void 0:A[0])==null?void 0:$.text)),u&&i.jsx(EK,{value:u}),u&&i.jsxs(fr,{children:[j&&i.jsx(_R,{patient:j}),T&&i.jsx(DK,{specimen:T}),t!=="Patient"&&i.jsx(DR,{resource:r}),i.jsx(so,{children:i.jsx(It,{value:p.toLowerCase(),onChange:b,children:i.jsx(It.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:d.map(z=>i.jsx(It.Tab,{value:z.toLowerCase(),children:MK.includes(z)?i.jsxs(ye,{gap:"xs",wrap:"nowrap",children:[z,i.jsx(vu,{color:m.primaryColor,size:"sm",children:"Beta"})]}):z},z))})})})]}),i.jsx(e0,{})]})}function Uj(){var T,P,k,C;const e=Tn(),{resourceType:t,id:n,versionId:r,tab:o}=Ft(),s=Pe(),[l,u]=v.useState(!0),[d,p]=v.useState(),[h,m]=v.useState();if(v.useEffect(()=>{m(void 0),u(!0),s.readHistory(t,n).then(_=>p(_)).then(()=>u(!1)).catch(_=>{m(_),u(!1)})},[s,t,n]),l)return i.jsx(oo,{});if(!d)return i.jsxs(at,{children:[i.jsx($e,{children:"Resource not found"}),i.jsx(xt,{to:`/${t}`,children:"Return to search page"})]});const y=d.entry??[],x=y.findIndex(_=>{var R,M;return((M=(R=_.resource)==null?void 0:R.meta)==null?void 0:M.versionId)===r});if(x===-1)return i.jsxs(at,{children:[i.jsx($e,{children:"Version not found"}),i.jsx(xt,{to:`/${t}/${n}`,children:"Return to resource"})]});const b=y[x].resource,w=x<y.length-1?y[x+1].resource:void 0,j="diff";return i.jsxs(It,{value:o||j,onChange:_=>e(`/${t}/${n}/_history/${r}/${_||j}`),children:[i.jsxs(fr,{children:[i.jsx(Iu,{fluid:!0,p:"md",children:i.jsx(_e,{children:`${t} ${n}`})}),i.jsxs(It.List,{children:[i.jsx(It.Tab,{value:"diff",children:"Diff"}),i.jsx(It.Tab,{value:"raw",children:"Raw"})]})]}),i.jsxs(at,{children:[h&&i.jsx("pre",{"data-testid":"error",children:JSON.stringify(h,void 0,2)}),i.jsx(It.Panel,{value:"diff",children:w?i.jsxs(i.Fragment,{children:[i.jsxs("ul",{children:[i.jsxs("li",{children:["Current: ",(T=b.meta)==null?void 0:T.versionId]}),i.jsxs("li",{children:["Previous:"," ",i.jsx(xt,{to:`/${t}/${n}/_history/${(P=w.meta)==null?void 0:P.versionId}`,children:(k=w.meta)==null?void 0:k.versionId})]})]}),i.jsx(pH,{original:w,revised:b})]}):i.jsxs(i.Fragment,{children:[i.jsxs("ul",{children:[i.jsxs("li",{children:["Current: ",(C=b.meta)==null?void 0:C.versionId]}),i.jsx("li",{children:"Previous: (none)"})]}),i.jsx("pre",{children:JSON.stringify(b,void 0,2)})]})}),i.jsx(It.Panel,{value:"raw",children:i.jsx("pre",{children:JSON.stringify(b,void 0,2)})})]})]})}function LK(){const{resourceType:e,id:t}=Ft(),n=Tn(),[r,o]=v.useState({resourceType:"Subscription",filters:[{code:"url",operator:Se.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return i.jsx(at,{children:i.jsx(vV,{search:r,onClick:s=>n(`/${s.resource.resourceType}/${s.resource.id}`),onChange:s=>o(s.definition),hideFilters:!0})})}function $K(e){const t=Pe(),{resource:n,opened:r,onClose:o}=e,[s,l]=v.useState(!1),[u,d]=v.useState(),[p,h]=v.useState(!1),m=v.useCallback(async()=>{if(n!=null&&n.id)try{await t.post(t.fhirUrl(n.resourceType,n.id,"$resend"),{subscription:s&&u?zt(u):void 0,verbose:p}),Ne({color:"green",message:"Done"}),o()}catch(y){Ne({color:"red",message:tt(y),autoClose:!1})}},[t,n,o,s,u,p]);return i.jsx(Mn,{opened:r,onClose:o,title:"Resend Subscriptions",children:i.jsx(mt,{onSubmit:m,children:i.jsxs(et,{children:[i.jsx(Kn,{label:"Choose subscription (all subscriptions by default)",onChange:y=>l(y.currentTarget.checked)}),s&&i.jsx(Na,{name:"subscription",resourceType:"Subscription",placeholder:"Subscription",onChange:d}),i.jsx(Kn,{label:"Verbose mode",onChange:y=>h(y.currentTarget.checked)}),i.jsx(ye,{justify:"flex-end",children:i.jsx(Ee,{type:"submit",children:"Resend"})})]})})})}function Vj(){const e=Pe(),t=Op(),{resourceType:n,id:r}=Ft(),o={reference:n+"/"+r},[s,l]=v.useState(),u=qf(!1);function d(P,k){return e.updateResource({...P,priority:k})}function p(P,k){d(P,"stat").then(k).catch(console.error)}function h(P,k){d(P,"routine").then(k).catch(console.error)}function m(P){t(`/${P.resourceType}/${P.id}`)}function y(P){t(`/${P.resourceType}/${P.id}/edit`)}function x(P){t(`/${P.resourceType}/${P.id}/delete`)}function b(P){l(P),u[1].open()}function w(P){var k;t(`/${P.resourceType}/${P.id}/_history/${(k=P.meta)==null?void 0:k.versionId}`)}function j(P,k){const C="aws-textract";Ne({id:C,title:"AWS Textract in Progress",message:"Extracting text... This may take a moment...",loading:!0,autoClose:!1}),e.post(e.fhirUrl(P.resourceType,P.id,"$aws-textract"),{}).then(()=>{k(),sa({id:C,title:"AWS Textract Successful",message:"Text successfully extracted.",color:"green",icon:i.jsx($i,{size:"1rem"}),loading:!1,withCloseButton:!0})}).catch(_=>sa({id:C,title:"AWS Textract Error",color:"red",message:tt(_),icon:i.jsx(ya,{size:"1rem"}),loading:!1,withCloseButton:!0}))}function T(P){var V;const{primaryResource:k,currentResource:C,reloadTimeline:_}=P,R=C.resourceType===k.resourceType&&C.id===k.id,M=C.resourceType==="Communication"&&C.priority!=="stat",A=C.resourceType==="Communication"&&C.priority==="stat",$=R,z=!R,G=!R,q=!R,Y=(V=e.getProjectMembership())==null?void 0:V.admin,Q=Y,ne=yQ()&&(C.resourceType==="DocumentReference"||C.resourceType==="Media");return i.jsxs(ve.Dropdown,{children:[i.jsx(ve.Label,{children:"Resource"}),M&&i.jsx(ve.Item,{leftSection:i.jsx(s8,{size:14}),onClick:()=>p(C,_),"aria-label":`Pin ${zt(C)}`,children:"Pin"}),A&&i.jsx(ve.Item,{leftSection:i.jsx(a8,{size:14}),onClick:()=>h(C,_),"aria-label":`Unpin ${zt(C)}`,children:"Unpin"}),z&&i.jsx(ve.Item,{leftSection:i.jsx(_S,{size:14}),onClick:()=>m(C),"aria-label":`Details ${zt(C)}`,children:"Details"}),$&&i.jsx(ve.Item,{leftSection:i.jsx(_S,{size:14}),onClick:()=>w(C),"aria-label":`Details ${zt(C)}`,children:"Details"}),G&&i.jsx(ve.Item,{leftSection:i.jsx(GT,{size:14}),onClick:()=>y(C),"aria-label":`Edit ${zt(C)}`,children:"Edit"}),Y&&i.jsxs(i.Fragment,{children:[i.jsx(ve.Divider,{}),i.jsx(ve.Label,{children:"Admin"}),Q&&i.jsx(ve.Item,{leftSection:i.jsx(f8,{size:14}),onClick:()=>b(C),"aria-label":`Resend Subscriptions ${zt(C)}`,children:"Resend Subscriptions"})]}),ne&&i.jsxs(i.Fragment,{children:[i.jsx(ve.Divider,{}),i.jsx(ve.Label,{children:"AWS AI"}),i.jsx(ve.Item,{leftSection:i.jsx(b8,{size:14}),onClick:()=>j(C,_),"aria-label":`AWS Textract ${zt(C)}`,children:"AWS Textract"})]}),q&&i.jsxs(i.Fragment,{children:[i.jsx(ve.Divider,{}),i.jsx(ve.Label,{children:"Danger zone"}),i.jsx(ve.Item,{color:"red",leftSection:i.jsx(Rx,{size:14}),onClick:()=>x(C),"aria-label":`Delete ${zt(C)}`,children:"Delete"})]})]})}return i.jsxs(i.Fragment,{children:[n==="Encounter"&&i.jsx(kU,{encounter:o,getMenu:T}),n==="Patient"&&i.jsx(NV,{patient:o,getMenu:T}),n==="ServiceRequest"&&i.jsx(bH,{serviceRequest:o,getMenu:T}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&i.jsx(EU,{resource:o,getMenu:T}),i.jsx($K,{resource:s,opened:u[0],onClose:u[1].close},`resend-subscriptions-${s==null?void 0:s.id}`)]})}function FK(e){const{opened:t,close:n,version:r,loadingStatus:o,handleStatus:s,handleUpgrade:l}=e,[u,d]=v.useState();return v.useEffect(()=>{t&&(u||bF("app-tools-page").then(d).catch(console.error),s())},[t,u,s]),u&&r&&!o?r==="unknown"?i.jsx("p",{children:"Unable to determine the current version of the agent. Check the network connectivity of the agent."}):r.startsWith(u)?i.jsxs("p",{children:["This agent is already on the latest version (",u,")."]}):i.jsxs(i.Fragment,{children:[i.jsxs("p",{children:["Are you sure you want to upgrade this agent from version ",r," to version ",u,"?"]}),i.jsx(Ee,{onClick:()=>{l(),n()},"aria-label":"Confirm upgrade",children:"Confirm Upgrade"})]}):i.jsx(oo,{})}function zK(){const e=Pe(),{id:t}=Ft(),n=v.useMemo(()=>({reference:"Agent/"+t}),[t]),[r,o]=v.useState(!1),[s,l]=v.useState(!1),[u,d]=v.useState(!1),[p,h]=v.useState(),[m,y]=v.useState(),[x,b]=v.useState(),[w,j]=v.useState(),[T,P]=v.useState(!1),[k,C]=v.useState(!1),[_,{open:R,close:M}]=qf(!1);v.useEffect(()=>{if(r||s||u||T){C(!0);return}C(!1)},[r,s,u,T]);const A=v.useCallback(()=>{o(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(Q=>{var ne,V,O,N,B,I;h((V=(ne=Q.parameter)==null?void 0:ne.find(F=>F.name==="status"))==null?void 0:V.valueCode),y((N=(O=Q.parameter)==null?void 0:O.find(F=>F.name==="version"))==null?void 0:N.valueString),b((I=(B=Q.parameter)==null?void 0:B.find(F=>F.name==="lastUpdated"))==null?void 0:I.valueInstant)}).catch(Q=>Y(tt(Q))).finally(()=>o(!1))},[e,t]),$=v.useCallback(Q=>{const ne=Q.host,V=Q.pingCount||1;ne&&(P(!0),e.pushToAgent(n,ne,`PING ${V}`,cn.PING,!0).then(O=>j(O)).catch(O=>Y(tt(O))).finally(()=>P(!1)))},[e,n]),z=v.useCallback(()=>{l(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(Q=>{q("Agent config reloaded successfully.")}).catch(Q=>Y(tt(Q))).finally(()=>l(!1))},[e,t]),G=v.useCallback(()=>{d(!0),e.get(e.fhirUrl("Agent",t,"$upgrade"),{cache:"reload"}).then(Q=>{q("Agent upgraded successfully.")}).catch(Q=>Y(tt(Q))).finally(()=>d(!1))},[e,t]);function q(Q){Ne({color:"green",title:"Success",icon:i.jsx($i,{size:"1rem"}),message:Q})}function Y(Q){Ne({color:"red",title:"Error",message:Q,autoClose:!1})}return i.jsxs(at,{children:[i.jsx(Mn,{opened:_,onClose:M,title:"Upgrade Agent",centered:!0,children:i.jsx(FK,{opened:_,close:M,version:m,loadingStatus:r,handleStatus:A,handleUpgrade:G})}),i.jsx($e,{order:1,children:"Agent Tools"}),i.jsxs("div",{style:{marginBottom:10},children:["Agent: ",i.jsx(ec,{value:n,link:!0})]}),i.jsx(kn,{my:"lg"}),i.jsx($e,{order:2,children:"Agent Status"}),i.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."}),i.jsx(Ee,{onClick:A,loading:r,disabled:k&&!r,children:"Get Status"}),!r&&p&&i.jsx(Ae,{children:i.jsxs(Ae.Tbody,{children:[i.jsxs(Ae.Tr,{children:[i.jsx(Ae.Td,{children:"Status"}),i.jsx(Ae.Td,{children:i.jsx(Ux,{status:p})})]}),i.jsxs(Ae.Tr,{children:[i.jsx(Ae.Td,{children:"Version"}),i.jsx(Ae.Td,{children:m})]}),i.jsxs(Ae.Tr,{children:[i.jsx(Ae.Td,{children:"Last Updated"}),i.jsx(Ae.Td,{children:pr(x,void 0,{timeZoneName:"longOffset"})})]})]})}),i.jsx(kn,{my:"lg"}),i.jsx($e,{order:2,children:"Reload Config"}),i.jsx("p",{children:"Reload the configuration of this agent, syncing it with the current version of the Agent resource on the Medplum server."}),i.jsx(Ee,{onClick:z,loading:s,disabled:k&&!s,"aria-label":"Reload config",children:"Reload Config"}),i.jsx(kn,{my:"lg"}),i.jsx($e,{order:2,children:"Upgrade Agent"}),i.jsx("p",{children:"Upgrade the version of this agent, to either the latest (default) or a specified version."}),i.jsx(Ee,{onClick:R,loading:u,disabled:k&&!u,"aria-label":"Upgrade agent",children:"Upgrade"}),i.jsx(kn,{my:"lg"}),i.jsx($e,{order:2,children:"Ping from Agent"}),i.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."}),i.jsx(mt,{onSubmit:$,children:i.jsxs(ye,{children:[i.jsx(Be,{id:"host",name:"host",placeholder:"ex. 127.0.0.1",label:"IP Address / Hostname",rightSection:i.jsx(Sn,{size:24,radius:"xl",variant:"filled",type:"submit","aria-label":"Ping",loading:T,disabled:k&&!T,children:i.jsx(h8,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),i.jsx(Fy,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!T&&w&&i.jsxs(i.Fragment,{children:[i.jsx($e,{order:5,mt:"sm",mb:0,children:"Last Ping"}),i.jsx("pre",{children:w})]})]})}function BK(){return i.jsx($q,{children:i.jsxs(Qe,{errorElement:i.jsx(ZG,{}),children:[i.jsx(Qe,{path:"/signin",element:i.jsx(CQ,{})}),i.jsx(Qe,{path:"/oauth",element:i.jsx(xQ,{})}),i.jsx(Qe,{path:"/resetpassword",element:i.jsx(wQ,{})}),i.jsx(Qe,{path:"/setpassword/:id/:secret",element:i.jsx(jQ,{})}),i.jsx(Qe,{path:"/register",element:i.jsx(bQ,{})}),i.jsx(Qe,{path:"/changepassword",element:i.jsx(YG,{})}),i.jsx(Qe,{path:"/security",element:i.jsx(SQ,{})}),i.jsx(Qe,{path:"/mfa",element:i.jsx(vQ,{})}),i.jsx(Qe,{path:"/batch",element:i.jsx(QG,{})}),i.jsx(Qe,{path:"/bulk/:resourceType",element:i.jsx(KG,{})}),i.jsx(Qe,{path:"/smart",element:i.jsx(EQ,{})}),i.jsx(Qe,{path:"/forms/:id",element:i.jsx(aQ,{})}),i.jsx(Qe,{path:"/admin/super",element:i.jsx($Q,{})}),i.jsx(Qe,{path:"/admin/config",element:i.jsx(AQ,{})}),i.jsxs(Qe,{path:"/admin",element:i.jsx(MQ,{}),children:[i.jsx(Qe,{path:"patients",element:i.jsx(NQ,{})}),i.jsx(Qe,{path:"bots/new",element:i.jsx(PQ,{})}),i.jsx(Qe,{path:"bots",element:i.jsx(kQ,{})}),i.jsx(Qe,{path:"clients/new",element:i.jsx(RQ,{})}),i.jsx(Qe,{path:"clients",element:i.jsx(TQ,{})}),i.jsx(Qe,{path:"details",element:i.jsx($j,{})}),i.jsx(Qe,{path:"invite",element:i.jsx(IQ,{})}),i.jsx(Qe,{path:"users",element:i.jsx(FQ,{})}),i.jsx(Qe,{path:"project",element:i.jsx($j,{})}),i.jsx(Qe,{path:"secrets",element:i.jsx(OQ,{})}),i.jsx(Qe,{path:"sites",element:i.jsx(LQ,{})}),i.jsx(Qe,{path:"members/:membershipId",element:i.jsx(DQ,{})})]}),i.jsx(Qe,{path:"/lab/assays",element:i.jsx(zQ,{})}),i.jsx(Qe,{path:"/lab/panels",element:i.jsx(BQ,{})}),i.jsx(Qe,{path:"/:resourceType/:id/_history/:versionId/:tab",element:i.jsx(Uj,{})}),i.jsx(Qe,{path:"/:resourceType/:id/_history/:versionId",element:i.jsx(Uj,{})}),i.jsxs(Qe,{path:"/:resourceType/new",element:i.jsx(JG,{}),children:[i.jsx(Qe,{index:!0,element:i.jsx(Cg,{})}),i.jsx(Qe,{path:"form",element:i.jsx(Cg,{})}),i.jsx(Qe,{path:"json",element:i.jsx(dK,{})}),i.jsx(Qe,{path:"profiles",element:i.jsx(Cg,{})})]}),i.jsxs(Qe,{path:"/:resourceType/:id",element:i.jsx(OK,{}),children:[i.jsx(Qe,{index:!0,element:i.jsx(Vj,{})}),i.jsx(Qe,{path:"apply",element:i.jsx(VQ,{})}),i.jsx(Qe,{path:"apps",element:i.jsx(WQ,{})}),i.jsx(Qe,{path:"event",element:i.jsx(qQ,{})}),i.jsx(Qe,{path:"blame",element:i.jsx(GQ,{})}),i.jsx(Qe,{path:"bots",element:i.jsx(vK,{})}),i.jsx(Qe,{path:"builder",element:i.jsx(nK,{})}),i.jsx(Qe,{path:"checklist",element:i.jsx(rK,{})}),i.jsx(Qe,{path:"delete",element:i.jsx(oK,{})}),i.jsx(Qe,{path:"details",element:i.jsx(aK,{})}),i.jsx(Qe,{path:"edit",element:i.jsx(lK,{})}),i.jsx(Qe,{path:"editor",element:i.jsx(eK,{})}),i.jsx(Qe,{path:"history",element:i.jsx(uK,{})}),i.jsx(Qe,{path:"json",element:i.jsx(fK,{})}),i.jsx(Qe,{path:"preview",element:i.jsx(pK,{})}),i.jsx(Qe,{path:"responses",element:i.jsx(xK,{})}),i.jsx(Qe,{path:"report",element:i.jsx(wK,{})}),i.jsx(Qe,{path:"ranges",element:i.jsx(bK,{})}),i.jsx(Qe,{path:"subscriptions",element:i.jsx(LK,{})}),i.jsx(Qe,{path:"timeline",element:i.jsx(Vj,{})}),i.jsx(Qe,{path:"tools",element:i.jsx(zK,{})}),i.jsx(Qe,{path:"profiles",element:i.jsx(hK,{})}),i.jsx(Qe,{path:"export",element:i.jsx(cK,{})})]}),i.jsx(Qe,{path:"/:resourceType",element:i.jsx(Lj,{})}),i.jsx(Qe,{path:"/",element:i.jsx(Lj,{})})]})})}function UK(){const e=Pe(),t=e.getUserConfiguration(),n=zi(),[r]=t0();return e.isLoading()?i.jsx(oo,{}):i.jsx(hz,{logo:i.jsx(Do,{size:24}),pathname:n.pathname,searchParams:r,version:OT,menus:VK(t),displayAddBookmark:!!(t!=null&&t.id),children:i.jsx(v.Suspense,{fallback:i.jsx(oo,{}),children:i.jsx(BK,{})})})}function VK(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(s=>({label:s.name,href:s.target,icon:WK(s.target)})))||[]}}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:i.jsx(t8,{})}]}),t}const Wj={Patient:v8,Practitioner:ZF,Organization:VF,ServiceRequest:u8,DiagnosticReport:p8,Questionnaire:JF,admin:zF,AccessPolicy:e8,Subscription:w8,batch:i8,Observation:o8};function WK(e){try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in Wj){const n=Wj[t];return i.jsx(n,{})}}catch{}return i.jsx(Tp,{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 HK(){const e=Fu(),t=new LT({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=Uq([{path:"*",element:i.jsx(UK,{})}]),o=l=>r.navigate(l);jH.createRoot(document.getElementById("root")).render(i.jsx(v.StrictMode,{children:i.jsx(wF,{medplum:t,navigate:o,children:i.jsxs(vC,{theme:n,children:[i.jsx(Oi,{position:"bottom-right"}),i.jsx(Xq,{router:r})]})})}))}HK().catch(console.error);
587
- //# sourceMappingURL=index-M3RO4kl5.js.map
587
+ //# sourceMappingURL=index-BJRa4_fn.js.map