@medplum/app 4.3.15 → 4.4.0

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.
@@ -84,7 +84,7 @@ function bO(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&
84
84
  *
85
85
  * Copy of "partysocket" from Partykit team, a fork of the original "Reconnecting WebSocket"
86
86
  * https://github.com/partykit/partykit/blob/main/packages/partysocket
87
- */const hc={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let PE=!1;function hV(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");hc.Event=globalThis.Event,hc.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},hc.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function pV(e,t){if(!e)throw new Error(t)}function ph(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};let kE=!1;class Ba extends um{constructor(t,n,r={}){PE||(hV(),PE=!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=Rs.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),s),pV(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(c=>this._ws?.send(c)),this._messageQueue=[],this.onopen&&this.onopen(o),this.dispatchEvent(ph(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(ph(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(ph(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(ph(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 Ba.CONNECTING}get OPEN(){return Ba.OPEN}get CLOSING(){return Ba.CLOSING}get CLOSED(){return Ba.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((n,r)=>(typeof r=="string"?n+=r.length:r instanceof Blob?n+=r.size:n+=r.byteLength,n),0)+(this._ws?.bufferedAmount??0)}get extensions(){return this._ws?.extensions??""}get protocol(){return this._ws?.protocol??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?Ba.CLOSED:Ba.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"&&!kE&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),kE=!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 hc.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new hc.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new hc.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 mV=5e3;class Jy extends um{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 gV{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new Jy(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class vV{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof eA))throw new dt(gn("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new dt(gn("Not a valid URL"))}const s=r?.ReconnectingWebSocket?new r.ReconnectingWebSocket(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger}):new Ba(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger});this.medplum=t,this.ws=s,this.masterSubEmitter=new Jy,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=r?.pingIntervalMs??mV,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{try{const r=JSON.parse(n.data);if(r.type==="pong"){this.waitingForPong=!1;return}const o=r,s=o?.entry?.[0]?.resource;if(s.type==="heartbeat"){this.masterSubEmitter?.dispatchEvent({type:"heartbeat",payload:o});return}if(s.type==="handshake"){const d=Hs(s.subscription),f={type:"connect",payload:{subscriptionId:d}};this.masterSubEmitter?.dispatchEvent(f);const p=this.criteriaEntriesBySubscriptionId.get(d);if(!p){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}p.connecting=!1,p.emitter.dispatchEvent({...f});return}this.masterSubEmitter?.dispatchEvent({type:"message",payload:o});const c=this.criteriaEntriesBySubscriptionId.get(Hs(s.subscription));if(!c){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}c.emitter.dispatchEvent({type:"message",payload:o})}catch(r){console.error(r);const o={type:"error",payload:r};this.masterSubEmitter?.dispatchEvent(o);for(const s of this.getAllCriteriaEmitters())s.dispatchEvent({...o})}}),t.addEventListener("error",()=>{const n={type:"error",payload:new dt(Rz(new Error("WebSocket error")))};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n})}),t.addEventListener("close",()=>{const n={type:"close"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),this.masterSubEmitter?.removeAllListeners())}),t.addEventListener("open",()=>{const n={type:"open"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.refreshAllSubscriptions().catch(console.error),this.pingTimer||(this.pingTimer=setInterval(()=>{if(this.waitingForPong){this.waitingForPong=!1,t.reconnect();return}t.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0},this.pingIntervalMs))}),this.medplum.addEventListener("change",()=>{const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&this.currentProfile?.id!==n.id&&this.ws.reconnect(),this.currentProfile=n})}emitError(t,n){const r={type:"error",payload:n};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){const{subscriptionId:n}=t;if(n){const r={type:"disconnect",payload:{subscriptionId:n}};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){let n=t?.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${At(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:t.criteria})).id);const{parameter:r}=await this.medplum.get(`fhir/R4/Subscription/${n}/$get-ws-binding-token`),o=r?.find(c=>c.name==="token")?.valueString,s=r?.find(c=>c.name==="websocket-url")?.valueUrl;if(!o)throw new dt(gn("Failed to get token"));if(!s)throw new dt(gn("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(co(n,o.subscriptionProps))return o}}getAllCriteriaEmitters(){const t=[];for(const n of this.criteriaEntries.values()){n.bareCriteria&&t.push(n.bareCriteria.emitter);for(const r of n.criteriaWithProps)t.push(r.emitter)}return t}addCriteriaEntry(t){const{criteria:n,subscriptionProps:r}=t;let o;this.criteriaEntries.has(n)?o=this.criteriaEntries.get(n):(o={criteriaWithProps:[]},this.criteriaEntries.set(n,o)),r?o.criteriaWithProps.push(t):o.bareCriteria=t}removeCriteriaEntry(t){const{criteria:n,subscriptionProps:r,subscriptionId:o,token:s}=t;if(!this.criteriaEntries.has(n))return;const c=this.criteriaEntries.get(n);r?c.criteriaWithProps=c.criteriaWithProps.filter(d=>{const f=d.subscriptionProps;return!co(r,f)}):c.bareCriteria=void 0,!c.bareCriteria&&c.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),this.masterSubEmitter?._removeCriteria(n)),o&&this.criteriaEntriesBySubscriptionId.delete(o),s&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:s}}))}async subscribeToCriteria(t){if(!(this.ws.readyState!==WebSocket.OPEN||t.connecting)){t.connecting=!0;try{const[n,r]=await this.getTokenForCriteria(t);t.subscriptionId=n,t.token=r,this.criteriaEntriesBySubscriptionId.set(n,t),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:r}}))}catch(n){console.error(Ge(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 gV(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 Jy(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const JD="4.3.15-eb4780adc",yV=un.FHIR_JSON+", */*; q=0.1",xV="https://api.medplum.com/",bV=1e3,SV=6e4,wV=0,jV=3e5,CV="Binary/",NE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},oc={ClientCredentials:"client_credentials",AuthorizationCode:"authorization_code",RefreshToken:"refresh_token",JwtBearer:"urn:ietf:params:oauth:grant-type:jwt-bearer",TokenExchange:"urn:ietf:params:oauth:grant-type:token-exchange"},EV={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},TV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class eA extends um{constructor(t){if(super(),this.initComplete=!0,t?.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=t?.fetch??RV(),this.storage=t?.storage??new dV,this.createPdfImpl=t?.createPdf,this.baseUrl=db(t?.baseUrl??xV),this.fhirBaseUrl=Zi(this.baseUrl,t?.fhirUrlPath??"fhir/R4"),this.authorizeUrl=Zi(this.baseUrl,t?.authorizeUrl??"oauth2/authorize"),this.tokenUrl=Zi(this.baseUrl,t?.tokenUrl??"oauth2/token"),this.logoutUrl=Zi(this.baseUrl,t?.logoutUrl??"oauth2/logout"),this.fhircastHubUrl=Zi(this.baseUrl,t?.fhircastHubUrl??"fhircast/STU3"),this.clientId=t?.clientId??"",this.clientSecret=t?.clientSecret??"",this.credentialsInHeader=t?.authCredentialsMethod==="header",this.defaultHeaders=t?.defaultHeaders??{},this.onUnauthenticated=t?.onUnauthenticated,this.refreshGracePeriod=t?.refreshGracePeriod??jV,this.cacheTime=t?.cacheTime??(typeof window>"u"?wV:SV),this.cacheTime>0?this.requestCache=new dD(t?.resourceCacheSize??bV):this.requestCache=void 0,t?.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t?.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve(),this.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}async attemptResumeActiveLogin(){const t=this.getActiveLogin();t&&(this.setAccessToken(t.accessToken,t.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}getFhircastHubUrl(){return this.fhircastHubUrl}getDefaultHeaders(){return this.defaultHeaders}clear(){this.storage.clear(),typeof window<"u"&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){this.storage.setString("activeLogin",void 0),this.requestCache?.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.refreshPromise=void 0,this.accessTokenExpires=void 0,this.sessionDetails=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(t){t=t.toString(),this.requestCache?.delete(t)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(t){const n=Zi(this.fhirBaseUrl,t);if(this.requestCache)for(const r of this.requestCache.keys())(r.endsWith(n)||r.includes(n+"?"))&&this.requestCache.delete(r)}get(t,n={}){t=t.toString();const r=this.getCacheEntry(t,n);if(r)return r.value;let o;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?o=new Promise((c,d)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:c,reject:d}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):o=this.request("GET",t,n);const s=new Ai(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,un.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 c=o;s&&(c=await this.ensureCodeChallenge(o)),window.location.assign(this.getExternalAuthRedirectUri(t,n,r,c,s))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");return this.fetchTokens({grant_type:oc.TokenExchange,subject_token_type:EV.AccessToken,client_id:n,subject_token:t})}getExternalAuthRedirectUri(t,n,r,o,s=!0){const c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",n),c.searchParams.set("redirect_uri",r),c.searchParams.set("scope",o.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(o)),s){const{codeChallenge:d,codeChallengeMethod:f}=o;if(!f)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!d)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");c.searchParams.set("code_challenge_method",f),c.searchParams.set("code_challenge",d)}return c.toString()}fhirUrl(...t){return new URL(Zi(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=yU(n)),r}search(t,n,r){const o=this.fhirSearchUrl(t,n),s="search-"+o.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=this.getBundle(o,r);return this.setCacheEntry(s,d),d}searchOne(t,n,r){const o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();const s="searchOne-"+o.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=new Ai(this.search(t,o.searchParams,r).then(f=>f.entry?.[0]?.resource));return this.setCacheEntry(s,d),d}searchResources(t,n,r){const s="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=new Ai(this.search(t,n,r).then(LE));return this.setCacheEntry(s,d),d}async*searchResourcePages(t,n,r){let o=this.fhirSearchUrl(t,n);for(;o;){const s=new URL(o).searchParams;s.has("_count")||s.set("_count","1000");const c=await this.search(t,s,r),d=c.link?.find(f=>f.relation==="next");if(!c.entry?.length&&!d)break;yield LE(c),o=d?.url?new URL(d.url):void 0}}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){const r=this.requestCache?.get(this.fhirUrl(t,n).toString())?.value;return r?.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return NE;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 Ai(Promise.reject(new Error("Missing reference")));if(r==="system")return new Ai(Promise.resolve(NE));const[o,s]=r.split("/");return!o||!s?new Ai(Promise.reject(new Error("Invalid reference"))):this.readResource(o,s,n)}requestSchema(t){if(yD(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Ai((async()=>{const s=`{
87
+ */const hc={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let PE=!1;function hV(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");hc.Event=globalThis.Event,hc.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},hc.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function pV(e,t){if(!e)throw new Error(t)}function ph(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};let kE=!1;class Ba extends um{constructor(t,n,r={}){PE||(hV(),PE=!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=Rs.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),s),pV(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(c=>this._ws?.send(c)),this._messageQueue=[],this.onopen&&this.onopen(o),this.dispatchEvent(ph(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(ph(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(ph(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(ph(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 Ba.CONNECTING}get OPEN(){return Ba.OPEN}get CLOSING(){return Ba.CLOSING}get CLOSED(){return Ba.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((n,r)=>(typeof r=="string"?n+=r.length:r instanceof Blob?n+=r.size:n+=r.byteLength,n),0)+(this._ws?.bufferedAmount??0)}get extensions(){return this._ws?.extensions??""}get protocol(){return this._ws?.protocol??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?Ba.CLOSED:Ba.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"&&!kE&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),kE=!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 hc.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new hc.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new hc.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 mV=5e3;class Jy extends um{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 gV{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new Jy(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class vV{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof eA))throw new dt(gn("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new dt(gn("Not a valid URL"))}const s=r?.ReconnectingWebSocket?new r.ReconnectingWebSocket(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger}):new Ba(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger});this.medplum=t,this.ws=s,this.masterSubEmitter=new Jy,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=r?.pingIntervalMs??mV,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{try{const r=JSON.parse(n.data);if(r.type==="pong"){this.waitingForPong=!1;return}const o=r,s=o?.entry?.[0]?.resource;if(s.type==="heartbeat"){this.masterSubEmitter?.dispatchEvent({type:"heartbeat",payload:o});return}if(s.type==="handshake"){const d=Hs(s.subscription),f={type:"connect",payload:{subscriptionId:d}};this.masterSubEmitter?.dispatchEvent(f);const p=this.criteriaEntriesBySubscriptionId.get(d);if(!p){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}p.connecting=!1,p.emitter.dispatchEvent({...f});return}this.masterSubEmitter?.dispatchEvent({type:"message",payload:o});const c=this.criteriaEntriesBySubscriptionId.get(Hs(s.subscription));if(!c){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}c.emitter.dispatchEvent({type:"message",payload:o})}catch(r){console.error(r);const o={type:"error",payload:r};this.masterSubEmitter?.dispatchEvent(o);for(const s of this.getAllCriteriaEmitters())s.dispatchEvent({...o})}}),t.addEventListener("error",()=>{const n={type:"error",payload:new dt(Rz(new Error("WebSocket error")))};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n})}),t.addEventListener("close",()=>{const n={type:"close"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),this.masterSubEmitter?.removeAllListeners())}),t.addEventListener("open",()=>{const n={type:"open"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.refreshAllSubscriptions().catch(console.error),this.pingTimer||(this.pingTimer=setInterval(()=>{if(this.waitingForPong){this.waitingForPong=!1,t.reconnect();return}t.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0},this.pingIntervalMs))}),this.medplum.addEventListener("change",()=>{const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&this.currentProfile?.id!==n.id&&this.ws.reconnect(),this.currentProfile=n})}emitError(t,n){const r={type:"error",payload:n};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){const{subscriptionId:n}=t;if(n){const r={type:"disconnect",payload:{subscriptionId:n}};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){let n=t?.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${At(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:t.criteria})).id);const{parameter:r}=await this.medplum.get(`fhir/R4/Subscription/${n}/$get-ws-binding-token`),o=r?.find(c=>c.name==="token")?.valueString,s=r?.find(c=>c.name==="websocket-url")?.valueUrl;if(!o)throw new dt(gn("Failed to get token"));if(!s)throw new dt(gn("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(co(n,o.subscriptionProps))return o}}getAllCriteriaEmitters(){const t=[];for(const n of this.criteriaEntries.values()){n.bareCriteria&&t.push(n.bareCriteria.emitter);for(const r of n.criteriaWithProps)t.push(r.emitter)}return t}addCriteriaEntry(t){const{criteria:n,subscriptionProps:r}=t;let o;this.criteriaEntries.has(n)?o=this.criteriaEntries.get(n):(o={criteriaWithProps:[]},this.criteriaEntries.set(n,o)),r?o.criteriaWithProps.push(t):o.bareCriteria=t}removeCriteriaEntry(t){const{criteria:n,subscriptionProps:r,subscriptionId:o,token:s}=t;if(!this.criteriaEntries.has(n))return;const c=this.criteriaEntries.get(n);r?c.criteriaWithProps=c.criteriaWithProps.filter(d=>{const f=d.subscriptionProps;return!co(r,f)}):c.bareCriteria=void 0,!c.bareCriteria&&c.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),this.masterSubEmitter?._removeCriteria(n)),o&&this.criteriaEntriesBySubscriptionId.delete(o),s&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:s}}))}async subscribeToCriteria(t){if(!(this.ws.readyState!==WebSocket.OPEN||t.connecting)){t.connecting=!0;try{const[n,r]=await this.getTokenForCriteria(t);t.subscriptionId=n,t.token=r,this.criteriaEntriesBySubscriptionId.set(n,t),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:r}}))}catch(n){console.error(Ge(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 gV(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 Jy(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const JD="4.4.0-1ce85f8ea",yV=un.FHIR_JSON+", */*; q=0.1",xV="https://api.medplum.com/",bV=1e3,SV=6e4,wV=0,jV=3e5,CV="Binary/",NE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},oc={ClientCredentials:"client_credentials",AuthorizationCode:"authorization_code",RefreshToken:"refresh_token",JwtBearer:"urn:ietf:params:oauth:grant-type:jwt-bearer",TokenExchange:"urn:ietf:params:oauth:grant-type:token-exchange"},EV={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},TV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class eA extends um{constructor(t){if(super(),this.initComplete=!0,t?.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=t?.fetch??RV(),this.storage=t?.storage??new dV,this.createPdfImpl=t?.createPdf,this.baseUrl=db(t?.baseUrl??xV),this.fhirBaseUrl=Zi(this.baseUrl,t?.fhirUrlPath??"fhir/R4"),this.authorizeUrl=Zi(this.baseUrl,t?.authorizeUrl??"oauth2/authorize"),this.tokenUrl=Zi(this.baseUrl,t?.tokenUrl??"oauth2/token"),this.logoutUrl=Zi(this.baseUrl,t?.logoutUrl??"oauth2/logout"),this.fhircastHubUrl=Zi(this.baseUrl,t?.fhircastHubUrl??"fhircast/STU3"),this.clientId=t?.clientId??"",this.clientSecret=t?.clientSecret??"",this.credentialsInHeader=t?.authCredentialsMethod==="header",this.defaultHeaders=t?.defaultHeaders??{},this.onUnauthenticated=t?.onUnauthenticated,this.refreshGracePeriod=t?.refreshGracePeriod??jV,this.cacheTime=t?.cacheTime??(typeof window>"u"?wV:SV),this.cacheTime>0?this.requestCache=new dD(t?.resourceCacheSize??bV):this.requestCache=void 0,t?.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t?.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve(),this.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}async attemptResumeActiveLogin(){const t=this.getActiveLogin();t&&(this.setAccessToken(t.accessToken,t.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}getFhircastHubUrl(){return this.fhircastHubUrl}getDefaultHeaders(){return this.defaultHeaders}clear(){this.storage.clear(),typeof window<"u"&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){this.storage.setString("activeLogin",void 0),this.requestCache?.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.refreshPromise=void 0,this.accessTokenExpires=void 0,this.sessionDetails=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(t){t=t.toString(),this.requestCache?.delete(t)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(t){const n=Zi(this.fhirBaseUrl,t);if(this.requestCache)for(const r of this.requestCache.keys())(r.endsWith(n)||r.includes(n+"?"))&&this.requestCache.delete(r)}get(t,n={}){t=t.toString();const r=this.getCacheEntry(t,n);if(r)return r.value;let o;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?o=new Promise((c,d)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:c,reject:d}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):o=this.request("GET",t,n);const s=new Ai(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,un.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 c=o;s&&(c=await this.ensureCodeChallenge(o)),window.location.assign(this.getExternalAuthRedirectUri(t,n,r,c,s))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");return this.fetchTokens({grant_type:oc.TokenExchange,subject_token_type:EV.AccessToken,client_id:n,subject_token:t})}getExternalAuthRedirectUri(t,n,r,o,s=!0){const c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",n),c.searchParams.set("redirect_uri",r),c.searchParams.set("scope",o.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(o)),s){const{codeChallenge:d,codeChallengeMethod:f}=o;if(!f)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!d)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");c.searchParams.set("code_challenge_method",f),c.searchParams.set("code_challenge",d)}return c.toString()}fhirUrl(...t){return new URL(Zi(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=yU(n)),r}search(t,n,r){const o=this.fhirSearchUrl(t,n),s="search-"+o.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=this.getBundle(o,r);return this.setCacheEntry(s,d),d}searchOne(t,n,r){const o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();const s="searchOne-"+o.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=new Ai(this.search(t,o.searchParams,r).then(f=>f.entry?.[0]?.resource));return this.setCacheEntry(s,d),d}searchResources(t,n,r){const s="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=new Ai(this.search(t,n,r).then(LE));return this.setCacheEntry(s,d),d}async*searchResourcePages(t,n,r){let o=this.fhirSearchUrl(t,n);for(;o;){const s=new URL(o).searchParams;s.has("_count")||s.set("_count","1000");const c=await this.search(t,s,r),d=c.link?.find(f=>f.relation==="next");if(!c.entry?.length&&!d)break;yield LE(c),o=d?.url?new URL(d.url):void 0}}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){const r=this.requestCache?.get(this.fhirUrl(t,n).toString())?.value;return r?.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return NE;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 Ai(Promise.reject(new Error("Missing reference")));if(r==="system")return new Ai(Promise.resolve(NE));const[o,s]=r.split("/");return!o||!s?new Ai(Promise.reject(new Error("Invalid reference"))):this.readResource(o,s,n)}requestSchema(t){if(yD(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Ai((async()=>{const s=`{
88
88
  StructureDefinitionList(_filter: "name eq ${t}") {
89
89
  resourceType,
90
90
  name,
@@ -604,4 +604,4 @@ Please change the parent <Route path="${E}"> to <Route path="${E==="/"?"*":`${E}
604
604
  }
605
605
  ]
606
606
  }`,lne="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 cne(){const e=De(),{id:t}=Bt(),[n,r]=v.useState(),[o,s]=v.useState(),[c,d]=v.useState(sne),[f,p]=v.useState(lne),[m,g]=v.useState(un.FHIR_JSON),x=v.useRef(null),b=v.useRef(null),[S,j]=v.useState(!1);v.useEffect(()=>{e.readResource("Bot",t).then(async A=>{r(A),s(await une(e,A))}).catch(A=>Ne({color:"red",message:Ge(A),autoClose:!1}))},[e,t]);const C=v.useCallback(async()=>Xu(x.current,{command:"getValue"}),[]),R=v.useCallback(async()=>Xu(x.current,{command:"getOutput"}),[]),E=v.useCallback(async()=>m===un.FHIR_JSON?JSON.parse(c):f,[m,c,f]),T=v.useCallback(async A=>{A.preventDefault(),A.stopPropagation(),j(!0);try{const k=await C(),L=await R(),z=await e.createAttachment({data:k,filename:"index.ts",contentType:"text/typescript"}),B=await e.createAttachment({data:L,filename:"index.js",contentType:"text/typescript"}),Z=[{op:"add",path:"/sourceCode",value:z},{op:"add",path:"/executableCode",value:B}];await e.patchResource("Bot",t,Z),Ne({color:"green",message:"Saved"})}catch(k){Ne({color:"red",message:Ge(k),autoClose:!1})}finally{j(!1)}},[e,t,C,R]),_=v.useCallback(async A=>{A.preventDefault(),A.stopPropagation(),j(!0);try{await e.post(e.fhirUrl("Bot",t,"$deploy")),Ne({color:"green",message:"Deployed"})}catch(k){Ne({color:"red",message:Ge(k),autoClose:!1})}finally{j(!1)}},[e,t]),P=v.useCallback(async A=>{A.preventDefault(),A.stopPropagation(),j(!0);try{const k=await E(),L=await e.post(e.fhirUrl("Bot",t,"$execute"),k,m);await Xu(b.current,{command:"setValue",value:L}),Ne({color:"green",message:"Success"})}catch(k){Ne({color:"red",message:Ge(k),autoClose:!1})}finally{j(!1)}},[e,t,E,m]);return!n||o===void 0?null:a.jsxs(ar,{m:0,gutter:0,style:{overflow:"hidden"},children:[a.jsx(ar.Col,{span:8,children:a.jsxs(yr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",mih:400,children:[a.jsx(ane,{iframeRef:x,language:"typescript",module:"commonjs",testId:"code-frame",defaultValue:o,minHeight:"528px"}),a.jsxs(ge,{justify:"flex-end",gap:"xs",children:[a.jsx(ke,{type:"button",onClick:T,loading:S,leftSection:a.jsx(xq,{size:"1rem"}),children:"Save"}),a.jsx(ke,{type:"button",onClick:_,loading:S,leftSection:a.jsx(_b,{size:"1rem"}),children:"Deploy"}),a.jsx(ke,{type:"button",onClick:P,loading:S,leftSection:a.jsx(aH,{size:"1rem"}),children:"Execute"})]})]})}),a.jsxs(ar.Col,{span:4,children:[a.jsxs(yr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[a.jsx(sn,{data:[{label:"FHIR",value:un.FHIR_JSON},{label:"HL7",value:un.HL7_V2}],onChange:A=>g(A.currentTarget.value)}),m===un.FHIR_JSON?a.jsx(Lc,{value:c,onChange:A=>d(A),autosize:!0,minRows:15}):a.jsx("textarea",{className:ine.hl7Input,value:f,onChange:A=>p(A.currentTarget.value),rows:15})]}),a.jsx(yr,{m:2,p:"xs",shadow:"md",children:a.jsx(one,{iframeRef:b,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function une(e,t){if(t.sourceCode?.url){const n=t.sourceCode.url?.split("/")?.find(PD);return(await e.download(e.fhirUrl("Binary",n))).text()}return t.code??""}function pl(e){let t=e.meta;return t&&(t={...t,lastUpdated:void 0,versionId:void 0,author:void 0}),{...e,meta:t}}function dne(){const e=De(),{resourceType:t,id:n}=Bt(),r={reference:t+"/"+n},o=v.useCallback(s=>{e.updateResource(pl(s)).then(()=>{Ne({color:"green",message:"Success"})}).catch(c=>{Ne({color:"red",message:Ge(c),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return a.jsx(lt,{children:a.jsx(sK,{value:r,onSubmit:o})});case"Questionnaire":return a.jsx(lt,{children:a.jsx(MK,{questionnaire:r,onSubmit:o})});default:return null}}function fne(){const{resourceType:e,id:t}=Bt(),n=Gt({reference:e+"/"+t}),r=wn();return n?a.jsx(lt,{children:a.jsx(cX,{value:n,onStart:(o,s)=>r(`/forms/${Hs(s)}`)?.catch(console.error),onEdit:(o,s,c)=>r(`/${c.reference}}`)?.catch(console.error)})}):null}function hne(){const e=De(),{resourceType:t,id:n}=Bt(),r=wn();return a.jsxs(lt,{children:[a.jsxs("p",{children:["Are you sure you want to delete this ",t,"?"]}),a.jsx(ke,{color:"red",onClick:()=>{e.deleteResource(t,n).then(()=>r(`/${t}`)?.catch(console.error)).catch(o=>Ne({color:"red",message:Ge(o),autoClose:!1}))},children:"Delete"})]})}const pne="_selectProfileBtn_tbaz6_1",mne="_chevron_tbaz6_13",aR={selectProfileBtn:pne,chevron:mne};function gne(){const{resourceType:e,id:t}=Bt(),n=Gt({reference:e+"/"+t}),[r,o]=v.useState(),s=il({onDropdownClose:()=>s.resetSelectedOption()}),c=v.useMemo(()=>{if(Tn(n?.meta?.profile))return[a.jsx(We.Option,{value:"",children:"None"},""),...n.meta.profile.map(f=>a.jsx(We.Option,{value:f,children:f},f))]},[n?.meta?.profile]);if(v.useEffect(()=>{n?.meta?.profile?.length===1&&o(n.meta.profile[0])},[n?.meta?.profile]),!n)return null;let d;return Tn(c)&&(d=a.jsx(ge,{justify:"flex-end",children:a.jsxs($e,{align:"flex-end",gap:"xs",children:[a.jsxs(We,{store:s,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:f=>{o(f),s.closeDropdown()},children:[a.jsx(We.Target,{children:a.jsx(er,{onClick:()=>s.toggleDropdown(),children:a.jsxs(Cd,{fw:"bold",fs:"sm",className:aR.selectProfileBtn,children:[a.jsx("span",{children:"Pick profile"}),a.jsx(Rb,{stroke:1.5,className:aR.chevron})]})})}),a.jsx(We.Dropdown,{w:"max-content",children:a.jsx(We.Options,{children:c})})]}),a.jsx(ce,{children:r?a.jsxs(a.Fragment,{children:[a.jsx(_e,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),a.jsx(_e,{span:!0,size:"sm",children:r||"Nothing selected"})]}):a.jsx(_e,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),a.jsx(lt,{children:a.jsxs($e,{gap:"xl",children:[d,a.jsx(qb,{value:n,profileUrl:r})]})})}function vne(){const e=De(),{resourceType:t,id:n}=Bt(),[r,o]=v.useState(),[s,c]=v.useState(),d=wn(),[f,p]=v.useState();v.useEffect(()=>{e.readResource(t,n).then(b=>{o(Kr(b)),c(Kr(b))}).catch(b=>{p(Ht(b)),Ne({color:"red",message:Ge(b),autoClose:!1})})},[e,t,n]);const m=v.useCallback(b=>{p(void 0),e.updateResource(pl(b)).then(()=>{d(`/${t}/${n}/details`)?.catch(console.error),Ne({id:"succes",color:"green",message:"Success"})}).catch(S=>{p(Ht(S)),Ne({color:"red",message:Ge(S),autoClose:!1})})},[e,t,n,d]),g=v.useCallback(b=>{p(void 0);const S=JA.createPatch(r,b);e.patchResource(t,n,S).then(()=>{d(`/${t}/${n}/details`)?.catch(console.error),Ne({id:"succes",color:"green",message:"Success"})}).catch(j=>{p(Ht(j)),Ne({color:"red",message:Ge(j),autoClose:!1})})},[e,t,n,r,d]),x=v.useCallback(()=>d(`/${t}/${n}/delete`)?.catch(console.error),[d,t,n]);return s?a.jsx(lt,{children:a.jsx(up,{defaultValue:s,onSubmit:m,onPatch:g,onDelete:x,outcome:f})}):null}function yne(){const{resourceType:e,id:t}=Bt(),n=Gt({reference:e+"/"+t});return n?a.jsx(lt,{maw:700,children:n.resourceType==="Patient"?a.jsx(tK,{patient:n}):a.jsx(oa,{icon:a.jsx(ll,{size:16}),title:"Unsupported export type",color:"red",children:"This page is only supported for Patient resources"})}):null}function uk({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,o=De(),[s,c]=v.useState();return v.useEffect(()=>{o.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(d=>{c(d.filter(wW))}).catch(console.error)},[o,n,r]),a.jsx(_t,{value:t?.url,onChange:d=>{const f=s?.find(p=>p.url===d);f&&n(f)},children:a.jsx(_t.List,{children:s?.map(d=>{const f=e.meta?.profile?.includes(d.url),p=f?"This profile is present in this resource's meta.profile property.":"This profile is not included in this resource's meta.profile property.";return a.jsx(_t.Tab,{value:d.url,title:p,rightSection:f&&a.jsx(rb,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:a.jsx($H,{size:"90%"})}),children:d.title||d.name},d.url)})})})}function dk(e,t){const n=De(),r=wn();return{defaultValue:{resourceType:e},handleSubmit:c=>{t&&t(void 0),n.createResource(c).then(d=>r("/"+d.resourceType+"/"+d.id)).catch(d=>{t&&t(Ht(d)),Ne({color:"red",message:Ge(d),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function Dy(){const{resourceType:e}=Bt(),t=Lr(),[n,r]=v.useState(),{defaultValue:o,handleSubmit:s}=dk(e,r),[c,d]=v.useState(),f=t.pathname.toLowerCase().endsWith("profiles"),p=v.useCallback(m=>{const g=pl(m);c&&LD(g,c.url),s(g)},[c,s]);return f?a.jsx(lt,{children:a.jsxs($e,{children:[a.jsx(uk,{resource:o,currentProfile:c,onChange:d}),c?a.jsx(up,{defaultValue:o,onSubmit:p,outcome:n,profileUrl:c.url},c.url):a.jsx(_e,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):a.jsx(lt,{children:a.jsx(up,{defaultValue:o,onSubmit:s,outcome:n})})}function sR(){const e=De(),{resourceType:t,id:n}=Bt(),r=e.readHistory(t,n).read();return a.jsx(lt,{children:a.jsx(OX,{history:r})})}function xne(){const{resourceType:e}=Bt(),[t,n]=v.useState(),{defaultValue:r,handleSubmit:o}=dk(e,n),s=v.useCallback(c=>{o(JSON.parse(c["new-resource"]))},[o]);return a.jsxs(lt,{children:[t&&a.jsx(dr,{outcome:t}),a.jsxs(ut,{onSubmit:s,children:[a.jsx(Lc,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:Ii(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),a.jsx(ge,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:a.jsx(ke,{type:"submit",children:"OK"})})]})]})}function bne(){const e=De(),{resourceType:t,id:n}=Bt(),r=Gt({reference:t+"/"+n}),o=wn(),[s,c]=v.useState(),d=v.useCallback(f=>{e.updateResource(pl(JSON.parse(f.resource))).then(()=>{c(void 0),o(`/${t}/${n}/details`)?.catch(console.error),Ne({color:"green",message:"Success"})}).catch(p=>{Ne({color:"red",message:Ge(p),autoClose:!1})})},[e,t,n,o]);return r?a.jsxs(lt,{children:[s&&a.jsx(dr,{outcome:s}),a.jsxs(ut,{onSubmit:d,children:[a.jsx(Lc,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:Ii(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),a.jsx(ge,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:a.jsx(ke,{type:"submit",children:"OK"})})]})]}):null}function Sne(){const{resourceType:e,id:t}=Bt();return Gt({reference:e+"/"+t})?a.jsxs(lt,{children:[a.jsxs(oa,{icon:a.jsx(ll,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",a.jsx("br",{}),a.jsx(Pt,{href:`/forms/${t}`,children:`/forms/${t}`})]}),a.jsx(xP,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function wne(){const e=De(),{resourceType:t,id:n}=Bt(),[r,o]=v.useState(),[s,c]=v.useState();return v.useEffect(()=>{e.readResource(t,n).then(d=>o(Kr(d))).catch(d=>{Ne({color:"red",message:Ge(d)})})},[e,t,n]),r?a.jsxs(lt,{children:[a.jsxs(Oe,{order:2,children:["Available ",t," profiles"]}),a.jsx($e,{children:a.jsxs(a.Fragment,{children:[a.jsx(uk,{resource:r,currentProfile:s,onChange:c}),s?a.jsx(jne,{profile:s,resource:r,onResourceUpdated:d=>o(d)},s.url):a.jsx(_e,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const jne=({profile:e,resource:t,onResourceUpdated:n})=>{const r=De(),[o,s]=v.useState(),[c,d]=v.useState(()=>t.meta?.profile?.includes(e.url)),f=v.useCallback(p=>{s(void 0);const m=pl(p);c?LD(m,e.url):xU(m,e.url),r.updateResource(m).then(g=>{n(g),Ne({color:"green",message:"Success"})}).catch(g=>{s(Ht(g)),Ne({color:"red",message:Ge(g),autoClose:!1})})},[r,e.url,n,c]);return a.jsxs($e,{children:[a.jsx(Pd,{size:"md",checked:c,label:`Conform resource to ${e.title}`,onChange:p=>d(p.currentTarget.checked),"data-testid":"profile-toggle"}),c?a.jsx(up,{profileUrl:e.url,defaultValue:t,onSubmit:f,outcome:o}):a.jsx("form",{noValidate:!0,onSubmit:p=>{p.preventDefault(),f(t)},children:a.jsx(ge,{justify:"flex-end",mt:"xl",children:a.jsx(ke,{type:"submit",children:"OK"})})})]})},fk={"Create Only":"create","Update Only":"update","Delete Only":"delete","All Interactions":void 0},Cne=Object.keys(fk);function Ene(){const e=De(),{id:t}=Bt(),n=Gt({reference:`Questionnaire/${t}`}),[r,o]=v.useState(),[s,c]=v.useState("create"),[d,f]=v.useState(0),p=e.searchResources("Subscription","status=active&_count=100").read().filter(g=>Tne(g,n));function m(){r&&n&&e.createResource({resourceType:"Subscription",status:"active",reason:`Connect bot ${r.name} to questionnaire responses`,criteria:`QuestionnaireResponse?questionnaire=${n.url?`${n.url},${At(n)}`:At(n)}`,channel:{type:"rest-hook",endpoint:At(r)},...s?{extension:[{url:"https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction",valueCode:s}]}:void 0}).then(()=>{o(void 0),f(Date.now()),e.invalidateSearches("Subscription"),Ne({color:"green",message:"Success"})}).catch(g=>Ne({color:"red",message:Ge(g),autoClose:!1}))}return a.jsxs(lt,{children:[a.jsx(Oe,{children:"Bots"}),a.jsxs($e,{children:[p.length===0&&a.jsx("p",{children:"No bots found."}),p.map(g=>a.jsxs("div",{children:[a.jsx("h3",{children:a.jsx(dl,{value:{reference:g.channel?.endpoint},link:!0})}),a.jsxs("p",{children:["Criteria: ",g.criteria]})]},g.id))]}),a.jsx(pn,{}),a.jsxs($e,{mt:10,children:[a.jsx(yd,{size:"lg",htmlFor:"bot",children:"Connect to bot"}),a.jsxs(ge,{children:[a.jsx(ul,{name:"bot",resourceType:"Bot",onChange:g=>o(g)}),a.jsx(ke,{onClick:m,children:"Connect"})]}),a.jsx(ge,{children:a.jsx(sn,{name:"subscription-trigger-event",defaultValue:"Create Only",label:"Subscription Trigger Event",data:Cne,onChange:g=>c(fk[g.target.value])})})]}),a.jsx("div",{style:{display:"none"},children:d})]})}function Tne(e,t){if(!t)return!1;const n=e.criteria||"",r=e.channel?.endpoint||"";return n.startsWith("QuestionnaireResponse?")&&r.startsWith("Bot/")&&(n.includes(At(t))||(t.url?n.includes(t.url):!1))}function Rne(){const{id:e}=Bt(),t=wn(),r=De().readReference({reference:`Questionnaire/${e}`}).read(),[o,s]=v.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:ue.EQUALS,value:r.url?`${r.url},Questionnaire/${e}`:`Questionnaire/${e}`}],fields:["id","_lastUpdated"]});return a.jsx(lt,{children:a.jsx(qc,{search:o,onClick:c=>t(`/${c.resource.resourceType}/${c.resource.id}`)?.catch(console.error),onChange:c=>s(c.definition),hideFilters:!0,hideToolbar:!0})})}function _ne(){const e=De(),{resourceType:t,id:n}=Bt(),r=Gt({reference:t+"/"+n}),o=v.useCallback(s=>{e.updateResource(pl(s)).then(()=>{Ne({color:"green",message:"Success"})}).catch(c=>{Ne({color:"red",message:Ge(c),autoClose:!1})})},[e]);return r?a.jsx(lt,{children:a.jsx(tX,{onSubmit:o,definition:r})}):null}function Dne(){const{resourceType:e,id:t}=Bt(),n=Gt({reference:e+"/"+t});return n?a.jsx(lt,{children:e==="MeasureReport"?a.jsx(JY,{measureReport:n}):a.jsx(Fb,{value:n})}):null}const Ane="_container_1ue98_1",Pne="_entry_1ue98_14",kne="_active_1ue98_21",Ay={container:Ane,entry:Pne,active:kne};function Nne(e){const t=De(),n=Gt(e.value),[r,o]=v.useState();return v.useEffect(()=>{if(!n)return;const s=lS(n);if(!s)return;const c="reference"in s?s.reference:At(s);t.search("ServiceRequest","subject="+c).then(d=>{const p=(d.entry??[]).map(m=>m.resource);eP(p),p.reverse(),o(p)}).catch(d=>Ne({color:"red",message:Ge(d),autoClose:!1}))},[t,n]),r?a.jsx("div",{"data-testid":"quick-service-requests",className:Ay.container,children:r.map(s=>a.jsxs("div",{className:It(Ay.entry,{[Ay.active]:s.id===n?.id}),children:[a.jsx("p",{children:a.jsx(vt,{to:s,children:One(s)})}),s.category?.[0]?.text&&a.jsx("p",{children:s.category[0]?.text}),s.code?.coding?.[0]?.code&&a.jsx("p",{children:s.code.coding[0]?.code}),a.jsx("p",{children:Mne(s)})]},s.id))}):null}function One(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function Mne(e){return e.authoredOn?e.authoredOn.substring(0,10):e.meta?.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const Lne="_container_1l2dh_1",Ine={container:Lne};function $ne(e){const t=Gt(e.valueSet);if(!t)return null;const n=[""],r=t.compose?.include?.[0]?.concept?.map(o=>o.code);return r&&n.push(...r),e.defaultValue&&!n.includes(e.defaultValue)&&n.push(e.defaultValue),a.jsx("div",{className:Ine.container,children:a.jsx(sn,{defaultValue:e.defaultValue,onChange:o=>e.onChange(o.currentTarget.value),data:n})})}function zne(e){const t=Gt(e.specimen);return t?a.jsxs(ht,{children:[a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Type"}),a.jsx(ht.Value,{children:"Specimen"})]}),a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Collected"}),a.jsx(ht.Value,{children:lr(t.collection?.collectedDateTime)})]}),a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Specimen Age"}),a.jsx(ht.Value,{children:Une(t)})]}),t.collection?.collectedDateTime&&t.receivedTime?a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Specimen Stability"}),a.jsx(ht.Value,{children:Bne(t)})]}):a.jsx(a.Fragment,{})]}):null}function Une(e){const t=e.collection?.collectedDateTime;if(!t)return;const n=new Date(t);return hk(pk(n,new Date))}function Bne(e){if(!e.collection?.collectedDateTime||!e.receivedTime)return;const t=new Date(e.collection.collectedDateTime),n=new Date(e.receivedTime);return hk(pk(t,n))}function hk(e){return e.toString().padStart(3,"0")+"D"}function pk(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function Vne(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}function Fne(){const e=De(),{resourceType:t,id:n}=Bt(),r={reference:t+"/"+n},o=wn(),[s,c]=v.useState(),d=Gt(r,c),f=Vne(t),[p,m]=v.useState(()=>{const E=window.location.pathname.split("/").pop();return E&&f.map(T=>T.toLowerCase()).includes(E)?E:f[0].toLowerCase()});async function g(){const T=(await e.readHistory(t,n)).entry?.find(_=>!!_.resource)?.resource;T?x(T):Ne({color:"red",message:"No history to restore",autoClose:!1})}function x(E){e.updateResource(pl(E)).then(()=>{c(void 0),Ne({color:"green",message:"Success"})}).catch(T=>{Ne({color:"red",message:Ge(T),autoClose:!1})})}if(s)return Dz(s)?a.jsxs(lt,{children:[a.jsx(Oe,{children:"Deleted"}),a.jsx("p",{children:"The resource was deleted."}),a.jsx(ke,{color:"red",onClick:g,children:"Restore"})]}):a.jsx(dr,{outcome:s});function b(E){E||(E=f[0].toLowerCase()),m(E),o(`/${t}/${n}/${E}`)?.catch(console.error)}function S(E){const T=d,_=T.orderDetail||[];_.length===0&&_.push({}),_[0].text!==E&&(_[0].text=E,x({...T,orderDetail:_}))}const j=d&&lS(d),C=d&&nee(d),R=e.getUserConfiguration()?.option?.find(E=>E.id==="statusValueSet")?.valueString;return a.jsxs(a.Fragment,{children:[d?.resourceType==="ServiceRequest"&&R&&a.jsx($ne,{valueSet:{reference:R},defaultValue:d.orderDetail?.[0]?.text,onChange:S},At(d)+"-"+d.orderDetail?.[0]?.text),d&&a.jsx(Nne,{value:d}),d&&a.jsxs(yr,{children:[j&&a.jsx(cP,{patient:j}),C&&a.jsx(zne,{specimen:C}),t!=="Patient"&&a.jsx(ak,{resource:r}),a.jsx(Zr,{children:a.jsx(_t,{value:p.toLowerCase(),onChange:b,children:a.jsx(_t.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:f.map(E=>a.jsx(_t.Tab,{value:E.toLowerCase(),children:E},E))})})})]}),a.jsx(iS,{})]})}function jh(){const e=wn(),{resourceType:t,id:n,versionId:r,tab:o}=Bt(),s=De(),[c,d]=v.useState(!0),[f,p]=v.useState(),[m,g]=v.useState();if(v.useEffect(()=>{g(void 0),d(!0),s.readHistory(t,n).then(T=>p(T)).then(()=>d(!1)).catch(T=>{g(T),d(!1)})},[s,t,n]),c)return a.jsx(yi,{});const x=f?.entry??[],b=x.findIndex(T=>T.resource?.meta?.versionId===r);if(b===-1)return a.jsxs(lt,{children:[a.jsx(Oe,{children:"Version not found"}),a.jsx(vt,{to:`/${t}/${n}`,children:"Return to resource"})]});const S=x[b].resource,j=b<x.length-1?x[b+1].resource:void 0,C="diff",R=o||C,E=x.length-b;return a.jsx(Ed,{maw:1200,children:a.jsx(cl,{children:a.jsxs($e,{gap:"lg",children:[m&&a.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)}),a.jsxs(tm,{cols:2,mb:"lg",children:[a.jsx(ji,{total:x.length,value:E,getControlProps:oP,onChange:T=>e(`/${t}/${n}/_history/${x[x.length-T]?.resource?.meta?.versionId}/${R}`)?.catch(console.error)}),a.jsx(ge,{justify:"right",children:a.jsx(Ad,{data:[{value:"diff",label:"Diff"},{value:"raw",label:"Raw"}],value:R,onChange:T=>e(`/${t}/${n}/_history/${r}/${T||C}`)?.catch(console.error)})})]}),a.jsx(ce,{mb:"lg",children:a.jsxs(vm,{compact:!0,children:[a.jsx(mi,{term:"Version ID",children:S.meta?.versionId}),a.jsx(mi,{term:"Author",children:a.jsx(pc,{value:S.meta?.author,link:!0},S.meta?.author?.reference)}),a.jsx(mi,{term:"Date/Time",children:lr(S.meta?.lastUpdated)})]})}),R==="diff"&&a.jsx(AX,{original:j??{resourceType:t,id:n},revised:S}),R==="raw"&&a.jsx("pre",{style:{fontSize:"9pt"},children:JSON.stringify(S,void 0,2)})]})})})}function qne(){const{resourceType:e,id:t}=Bt(),n=wn(),[r,o]=v.useState({resourceType:"Subscription",filters:[{code:"url",operator:ue.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return a.jsx(lt,{children:a.jsx(IY,{search:r,onClick:s=>n(`/${s.resource.resourceType}/${s.resource.id}`)?.catch(console.error),onChange:s=>o(s.definition),hideFilters:!0})})}function Hne(e){const t=De(),{resource:n,opened:r,onClose:o}=e,[s,c]=v.useState(!1),[d,f]=v.useState(),[p,m]=v.useState(!1),g=v.useCallback(async()=>{if(n?.id)try{await t.post(t.fhirUrl(n.resourceType,n.id,"$resend"),{subscription:s&&d?At(d):void 0,verbose:p}),Ne({color:"green",message:"Done"}),o()}catch(x){Ne({color:"red",message:Ge(x),autoClose:!1})}},[t,n,o,s,d,p]);return a.jsx(In,{opened:r,onClose:o,title:"Resend Subscriptions",children:a.jsx(ut,{onSubmit:g,children:a.jsxs($e,{children:[a.jsx(Dn,{label:"Choose subscription (all subscriptions by default)",onChange:x=>c(x.currentTarget.checked)}),s&&a.jsx(ul,{name:"subscription",resourceType:"Subscription",placeholder:"Subscription",onChange:f}),a.jsx(Dn,{label:"Verbose mode",onChange:x=>m(x.currentTarget.checked)}),a.jsx(ge,{justify:"flex-end",children:a.jsx(ke,{type:"submit",children:"Resend"})})]})})})}function lR(){const e=De(),t=hm(),{resourceType:n,id:r}=Bt(),o={reference:n+"/"+r},[s,c]=v.useState(),d=md(!1);function f(E,T){return e.updateResource({...E,priority:T})}function p(E,T){f(E,"stat").then(T).catch(console.error)}function m(E,T){f(E,"routine").then(T).catch(console.error)}function g(E){t(`/${E.resourceType}/${E.id}`)}function x(E){t(`/${E.resourceType}/${E.id}/edit`)}function b(E){t(`/${E.resourceType}/${E.id}/delete`)}function S(E){c(E),d[1].open()}function j(E){t(`/${E.resourceType}/${E.id}/_history/${E.meta?.versionId}`)}function C(E,T){const _="aws-textract";Ne({id:_,title:"AWS Textract in Progress",message:"Extracting text... This may take a moment...",loading:!0,autoClose:!1}),e.post(e.fhirUrl(E.resourceType,E.id,"$aws-textract"),{}).then(()=>{T(),Ms({id:_,title:"AWS Textract Successful",message:"Text successfully extracted.",color:"green",icon:a.jsx(vo,{size:"1rem"}),loading:!1,withCloseButton:!0})}).catch(P=>Ms({id:_,title:"AWS Textract Error",color:"red",message:Ge(P),icon:a.jsx(Ys,{size:"1rem"}),loading:!1,withCloseButton:!0}))}function R(E){const{primaryResource:T,currentResource:_,reloadTimeline:P}=E,A=_.resourceType===T.resourceType&&_.id===T.id,k=_.resourceType==="Communication"&&_.priority!=="stat",L=_.resourceType==="Communication"&&_.priority==="stat",z=A,B=!A,Z=!A,K=!A,Y=e.getProjectMembership()?.admin,H=Y,W=Wte()&&(_.resourceType==="DocumentReference"||_.resourceType==="Media");return a.jsxs(Ce.Dropdown,{children:[a.jsx(Ce.Label,{children:"Resource"}),k&&a.jsx(Ce.Item,{leftSection:a.jsx(nH,{size:14}),onClick:()=>p(_,P),"aria-label":`Pin ${At(_)}`,children:"Pin"}),L&&a.jsx(Ce.Item,{leftSection:a.jsx(iH,{size:14}),onClick:()=>m(_,P),"aria-label":`Unpin ${At(_)}`,children:"Unpin"}),B&&a.jsx(Ce.Item,{leftSection:a.jsx(GE,{size:14}),onClick:()=>g(_),"aria-label":`Details ${At(_)}`,children:"Details"}),z&&a.jsx(Ce.Item,{leftSection:a.jsx(GE,{size:14}),onClick:()=>j(_),"aria-label":`Details ${At(_)}`,children:"Details"}),Z&&a.jsx(Ce.Item,{leftSection:a.jsx(vA,{size:14}),onClick:()=>x(_),"aria-label":`Edit ${At(_)}`,children:"Edit"}),Y&&a.jsxs(a.Fragment,{children:[a.jsx(Ce.Divider,{}),a.jsx(Ce.Label,{children:"Admin"}),H&&a.jsx(Ce.Item,{leftSection:a.jsx(fH,{size:14}),onClick:()=>S(_),"aria-label":`Resend Subscriptions ${At(_)}`,children:"Resend Subscriptions"})]}),W&&a.jsxs(a.Fragment,{children:[a.jsx(Ce.Divider,{}),a.jsx(Ce.Label,{children:"AWS AI"}),a.jsx(Ce.Item,{leftSection:a.jsx(PH,{size:14}),onClick:()=>C(_,P),"aria-label":`AWS Textract ${At(_)}`,children:"AWS Textract"})]}),K&&a.jsxs(a.Fragment,{children:[a.jsx(Ce.Divider,{}),a.jsx(Ce.Label,{children:"Danger zone"}),a.jsx(Ce.Item,{color:"red",leftSection:a.jsx(mm,{size:14}),onClick:()=>b(_),"aria-label":`Delete ${At(_)}`,children:"Delete"})]})]})}return a.jsxs(a.Fragment,{children:[n==="Encounter"&&a.jsx(HQ,{encounter:o,getMenu:R}),n==="Patient"&&a.jsx(iK,{patient:o,getMenu:R}),n==="ServiceRequest"&&a.jsx(IX,{serviceRequest:o,getMenu:R}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&a.jsx(qQ,{resource:o,getMenu:R}),a.jsx(Hne,{resource:s,opened:d[0],onClose:d[1].close},`resend-subscriptions-${s?.id}`)]})}function Gne(e){const{opened:t,close:n,version:r,loadingStatus:o,handleStatus:s,handleUpgrade:c}=e,[d,f]=v.useState(),[p,m]=v.useState(!1);return v.useEffect(()=>{t&&(d||XV("app-tools-page").then(f).catch(console.error),s())},[t,d,s]),d&&r&&!o?r==="unknown"?a.jsx("p",{children:"Unable to determine the current version of the agent. Check the network connectivity of the agent."}):r.startsWith(d)?a.jsxs("p",{children:["This agent is already on the latest version (",d,")."]}):a.jsxs(a.Fragment,{children:[a.jsxs("p",{children:["Are you sure you want to upgrade this agent from version ",r," to version ",d,"?"]}),a.jsxs(ge,{children:[a.jsx(ke,{onClick:()=>{c(p),n()},"aria-label":"Confirm upgrade",children:"Confirm Upgrade"}),a.jsx(Dn,{label:"Force",onChange:g=>m(g.currentTarget.checked)})]})]}):a.jsx(yi,{})}function Wne(){const e=De(),{id:t}=Bt(),n=v.useMemo(()=>({reference:"Agent/"+t}),[t]),[r,o]=v.useState(!1),[s,c]=v.useState(!1),[d,f]=v.useState(!1),[p,m]=v.useState(!1),[g,x]=v.useState(),[b,S]=v.useState(),[j,C]=v.useState(),[R,E]=v.useState(),[T,_]=v.useState(!1),[P,A]=v.useState(!1),[k,L]=v.useState(),[z,{open:B,close:Z}]=md(!1);v.useEffect(()=>{if(r||s||d||T){A(!0);return}A(!1)},[r,s,d,T]);const K=v.useCallback(()=>{o(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(q=>{x(q.parameter?.find(N=>N.name==="status")?.valueCode),S(q.parameter?.find(N=>N.name==="version")?.valueString),C(q.parameter?.find(N=>N.name==="lastUpdated")?.valueInstant)}).catch(q=>$(Ge(q))).finally(()=>o(!1))},[e,t]),Y=v.useCallback(q=>{const N=q.host,F=q.pingCount||1;N&&(_(!0),e.pushToAgent(n,N,`PING ${F}`,un.PING,!0).then(J=>E(J)).catch(J=>$(Ge(J))).finally(()=>_(!1)))},[e,n]),H=v.useCallback(()=>{c(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(q=>{I("Agent config reloaded successfully.")}).catch(q=>$(Ge(q))).finally(()=>c(!1))},[e,t]),W=v.useCallback(q=>{f(!0),e.get(e.fhirUrl("Agent",t,"$upgrade",`?force=${q}`),{cache:"reload"}).then(N=>{I("Agent upgraded successfully.")}).catch(N=>$(Ge(N))).finally(()=>f(!1))},[e,t]),M=v.useCallback(q=>{m(!0);const N=q.logLimit||20;e.get(e.fhirUrl("Agent",t,`$fetch-logs${N!==void 0?`?limit=${N}`:""}`),{cache:"reload"}).then(F=>{const J=F?.parameter?.find(ae=>ae.name==="logs");J&&L(J?.valueString)}).catch(F=>$(Ge(F))).finally(()=>m(!1))},[e,t]);function I(q){Ne({color:"green",title:"Success",icon:a.jsx(vo,{size:"1rem"}),message:q})}function $(q){Ne({color:"red",title:"Error",message:q,autoClose:!1})}return a.jsxs(lt,{children:[a.jsx(In,{opened:z,onClose:Z,title:"Upgrade Agent",centered:!0,children:a.jsx(Gne,{opened:z,close:Z,version:b,loadingStatus:r,handleStatus:K,handleUpgrade:W})}),a.jsx(Oe,{order:1,children:"Agent Tools"}),a.jsxs("div",{style:{marginBottom:10},children:["Agent: ",a.jsx(dl,{value:n,link:!0})]}),a.jsx(pn,{my:"lg"}),a.jsx(Oe,{order:2,children:"Agent Status"}),a.jsx("p",{children:"Retrieve the status of the agent. This tests whether the agent is connected to the Medplum server, and the last time it was able to communicate."}),a.jsx(ke,{onClick:K,loading:r,disabled:P&&!r,children:"Get Status"}),!r&&g&&a.jsx(de,{children:a.jsxs(de.Tbody,{children:[a.jsxs(de.Tr,{children:[a.jsx(de.Td,{children:"Status"}),a.jsx(de.Td,{children:a.jsx(bm,{status:g})})]}),a.jsxs(de.Tr,{children:[a.jsx(de.Td,{children:"Version"}),a.jsx(de.Td,{children:b})]}),a.jsxs(de.Tr,{children:[a.jsx(de.Td,{children:"Last Updated"}),a.jsx(de.Td,{children:lr(j,void 0,{timeZoneName:"longOffset"})})]})]})}),a.jsx(pn,{my:"lg"}),a.jsx(Oe,{order:2,children:"Reload Config"}),a.jsx("p",{children:"Reload the configuration of this agent, syncing it with the current version of the Agent resource on the Medplum server."}),a.jsx(ke,{onClick:H,loading:s,disabled:P&&!s,"aria-label":"Reload config",children:"Reload Config"}),a.jsx(pn,{my:"lg"}),a.jsx(Oe,{order:2,children:"Upgrade Agent"}),a.jsx("p",{children:"Upgrade the version of this agent, to either the latest (default) or a specified version."}),a.jsx(ke,{onClick:B,loading:d,disabled:P&&!d,"aria-label":"Upgrade agent",children:"Upgrade"}),a.jsx(pn,{my:"lg"}),a.jsxs(ut,{onSubmit:M,children:[a.jsx(Oe,{order:2,children:"Fetch Logs"}),a.jsx("p",{children:"Fetch logs from the agent."}),k?.length?a.jsx(Cd,{block:!0,mb:15,children:k}):null,a.jsxs(ge,{children:[a.jsx(wc,{w:100,id:"logLimit",name:"logLimit",placeholder:"20",label:"Log Limit"}),a.jsx(ke,{mt:22,loading:p,disabled:P&&!p,"aria-label":"Fetch logs",type:"submit",children:"Fetch Logs"})]})]}),a.jsx(pn,{my:"lg"}),a.jsx(Oe,{order:2,children:"Ping from Agent"}),a.jsx("p",{children:"Send a ping command from the agent to a valid IP address or hostname. Use this tool to troubleshoot local network connectivity."}),a.jsx(ut,{onSubmit:Y,children:a.jsxs(ge,{children:[a.jsx(Ue,{id:"host",name:"host",placeholder:"ex. 127.0.0.1",label:"IP Address / Hostname",rightSection:a.jsx(bn,{size:24,radius:"xl",variant:"filled",type:"submit","aria-label":"Ping",loading:T,disabled:P&&!T,children:a.jsx(gH,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),a.jsx(wc,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!T&&R&&a.jsxs(a.Fragment,{children:[a.jsx(Oe,{order:5,mt:"sm",mb:0,children:"Last Ping"}),a.jsx("pre",{children:R})]})]})}function Qne(){const e=wn(),t=De(),[n,r]=v.useState();v.useEffect(()=>{t.get("auth/me",{cache:"no-cache"}).then(r).catch(s=>Ne({color:"red",message:Ge(s),autoClose:!1}))},[t]);function o(s){t.post("auth/revoke",{loginId:s}).then(()=>t.get("auth/me",{cache:"no-cache"})).then(r).then(()=>Ne({color:"green",message:"Login revoked"})).catch(c=>Ne({color:"red",message:Ge(c),autoClose:!1}))}return n?a.jsxs(a.Fragment,{children:[a.jsxs(lt,{children:[a.jsx(Oe,{children:"Security"}),a.jsxs(vm,{children:[a.jsx(mi,{term:"ID",children:a.jsx(Pt,{href:`/${At(n.profile)}`,children:n.profile.id})}),a.jsx(mi,{term:"Resource Type",children:n.profile.resourceType}),a.jsx(mi,{term:"Name",children:Bc(n.profile.name?.[0])})]})]}),a.jsxs(lt,{children:[a.jsx(Oe,{children:"Sessions"}),a.jsxs(de,{children:[a.jsx("thead",{children:a.jsxs("tr",{children:[a.jsx("th",{children:"OS"}),a.jsx("th",{children:"Browser"}),a.jsx("th",{children:"IP Address"}),a.jsx("th",{children:"Auth Method"}),a.jsx("th",{children:"Last Updated"}),a.jsx("th",{})]})}),a.jsx("tbody",{children:n.security.sessions.map(s=>a.jsxs("tr",{children:[a.jsx("td",{children:s.os}),a.jsx("td",{children:s.browser}),a.jsx("td",{children:s.remoteAddress}),a.jsx("td",{children:s.authMethod}),a.jsx("td",{children:lr(s.lastUpdated)}),a.jsx("td",{children:a.jsx(Pt,{href:"#",onClick:()=>o(s.id),children:"Revoke"})})]},s.id))})]})]}),a.jsxs(lt,{children:[a.jsx(Oe,{children:"Password"}),a.jsx(ke,{onClick:()=>e("/changepassword")?.catch(console.error),children:"Change password"})]}),a.jsxs(lt,{children:[a.jsx(Oe,{children:"Multi Factor Auth"}),a.jsxs("p",{children:["Enrolled: ",n.security.mfaEnrolled.toString()]}),!n.security.mfaEnrolled&&a.jsx(ke,{onClick:()=>e("/mfa")?.catch(console.error),children:"Enroll"})]})]}):null}function Yne(){const{id:e,secret:t}=Bt(),n=De(),[r,o]=v.useState(),[s,c]=v.useState(!1),d=Fc(r,void 0);return a.jsxs(lt,{width:450,children:[a.jsx(dr,{issues:d}),a.jsxs(ut,{onSubmit:f=>{if(f.password!==f.confirmPassword){o(io("Passwords do not match","confirmPassword"));return}o(void 0);const p={id:e,secret:t,password:f.password};n.post("auth/setpassword",p).then(()=>c(!0)).catch(m=>o(Ht(m)))},children:[a.jsxs(Jn,{style:{flexDirection:"column"},children:[a.jsx(Ci,{size:32}),a.jsx(Oe,{children:"Set password"})]}),!s&&a.jsxs($e,{children:[a.jsx(Oi,{name:"password",label:"New password",required:!0,error:kt(r,"password")}),a.jsx(Oi,{name:"confirmPassword",label:"Confirm new password",required:!0,error:kt(r,"confirmPassword")}),a.jsx(ge,{justify:"flex-end",mt:"xl",children:a.jsx(ke,{type:"submit",children:"Set password"})})]}),s&&a.jsxs("div",{"data-testid":"success",children:["Password set. You can now ",a.jsx(vt,{to:"/signin",children:"sign in"}),"."]})]})]})}function Kne(){const e=pm(),t=wn(),[n]=sS(),r=Wd(),o=v.useCallback(()=>{const s=n.get("next");t(s?.startsWith("/")?s:"/")?.catch(console.error)},[n,t]);return v.useEffect(()=>{e&&n.has("next")&&o()},[e,n,o]),a.jsxs(LA,{onSuccess:()=>o(),onForgotPassword:()=>t("/resetpassword")?.catch(console.error),onRegister:lk()?()=>t("/register")?.catch(console.error):void 0,googleClientId:r.googleClientId,login:n.get("login")||void 0,projectId:n.get("project")||void 0,children:[a.jsx(Ci,{size:32}),a.jsx(Oe,{children:"Sign in to Medplum"}),n.get("project")==="new"&&a.jsx("div",{children:"Sign in again to create a new project"})]})}function Xne(){const e=wn(),t=Lr(),[n,r]=v.useState(),[o,s]=v.useState(),[c,d]=v.useState();return v.useEffect(()=>{const f=Object.fromEntries(new URLSearchParams(t.search).entries());r(f.resourceType),s(f.query),d(JSON.parse(f.fields))},[t]),!n||!o||!c?null:a.jsx(FY,{resourceType:n,checkboxesEnabled:!0,query:o,fields:c,onClick:f=>e(`/${n}/${f.resource.id}`)?.catch(console.error),onAuxClick:f=>window.open(`/${n}/${f.resource.id}`,"_blank"),onBulk:f=>{e(`/bulk/${n}?ids=${f.join(",")}`)?.catch(console.error)}})}function Zne(){const{id:e,secret:t}=Bt(),n=De(),[r,o]=v.useState(),[s,c]=v.useState(!1),d=Fc(r,void 0);return a.jsxs(lt,{width:450,children:[a.jsx(dr,{issues:d}),a.jsxs(ut,{onSubmit:()=>{o(void 0);const f={id:e,secret:t};n.post("auth/verifyemail",f).then(()=>c(!0)).catch(p=>o(Ht(p)))},children:[a.jsxs(Jn,{style:{flexDirection:"column"},children:[a.jsx(Ci,{size:32}),a.jsx(Oe,{children:"Email address verification required"})]}),!s&&a.jsxs($e,{children:[a.jsx("p",{children:"In order to sign in, click the button below to verify your ability to receive email at the address this link was sent to."}),a.jsx(ge,{justify:"flex-end",mt:"xl",children:a.jsx(ke,{type:"submit",children:"Verify email"})})]}),s&&a.jsxs("div",{"data-testid":"success",children:["Email verified. You can now ",a.jsx(vt,{to:"/signin",children:"sign in"}),"."]})]})]})}function Jne(){return a.jsx(bJ,{children:a.jsxs(Ie,{errorElement:a.jsx(kte,{}),children:[a.jsx(Ie,{path:"/signin",element:a.jsx(Kne,{})}),a.jsx(Ie,{path:"/oauth",element:a.jsx(Qte,{})}),a.jsx(Ie,{path:"/resetpassword",element:a.jsx(Kte,{})}),a.jsx(Ie,{path:"/setpassword/:id/:secret",element:a.jsx(Yne,{})}),a.jsx(Ie,{path:"/verifyemail/:id/:secret",element:a.jsx(Zne,{})}),a.jsx(Ie,{path:"/register",element:a.jsx(Yte,{})}),a.jsx(Ie,{path:"/changepassword",element:a.jsx(Dte,{})}),a.jsx(Ie,{path:"/security",element:a.jsx(Qne,{})}),a.jsx(Ie,{path:"/mfa",element:a.jsx(Hte,{})}),a.jsx(Ie,{path:"/batch",element:a.jsx(Rte,{})}),a.jsx(Ie,{path:"/bulk/:resourceType",element:a.jsx(_te,{})}),a.jsx(Ie,{path:"/smart",element:a.jsx(Xne,{})}),a.jsx(Ie,{path:"/forms/:id",element:a.jsx(Nte,{})}),a.jsx(Ie,{path:"/admin/super",element:a.jsx(Dee,{})}),a.jsx(Ie,{path:"/admin/super/asyncjob",element:a.jsx(jee,{})}),a.jsx(Ie,{path:"/admin/super/db",element:a.jsx(pee,{})}),a.jsx(Ie,{path:"/admin/config",element:a.jsx(xee,{})}),a.jsxs(Ie,{path:"/admin",element:a.jsx(bee,{}),children:[a.jsx(Ie,{path:"patients",element:a.jsx(yee,{})}),a.jsx(Ie,{path:"bots/new",element:a.jsx(oee,{})}),a.jsx(Ie,{path:"bots",element:a.jsx(ree,{})}),a.jsx(Ie,{path:"clients/new",element:a.jsx(aee,{})}),a.jsx(Ie,{path:"clients",element:a.jsx(iee,{})}),a.jsx(Ie,{path:"details",element:a.jsx(qT,{})}),a.jsx(Ie,{path:"invite",element:a.jsx(vee,{})}),a.jsx(Ie,{path:"users",element:a.jsx(kee,{})}),a.jsx(Ie,{path:"project",element:a.jsx(qT,{})}),a.jsx(Ie,{path:"secrets",element:a.jsx(See,{})}),a.jsx(Ie,{path:"sites",element:a.jsx(wee,{})}),a.jsx(Ie,{path:"members/:membershipId",element:a.jsx(gee,{})})]}),a.jsx(Ie,{path:"/lab/assays",element:a.jsx(Fte,{})}),a.jsx(Ie,{path:"/lab/panels",element:a.jsx(qte,{})}),a.jsxs(Ie,{path:"/:resourceType/new",element:a.jsx(Pte,{}),children:[a.jsx(Ie,{index:!0,element:a.jsx(Dy,{})}),a.jsx(Ie,{path:"form",element:a.jsx(Dy,{})}),a.jsx(Ie,{path:"json",element:a.jsx(xne,{})}),a.jsx(Ie,{path:"profiles",element:a.jsx(Dy,{})})]}),a.jsxs(Ie,{path:"/:resourceType/:id",element:a.jsx(Fne,{}),children:[a.jsx(Ie,{index:!0,element:a.jsx(lR,{})}),a.jsx(Ie,{path:"apply",element:a.jsx(Zte,{})}),a.jsx(Ie,{path:"apps",element:a.jsx(Jte,{})}),a.jsx(Ie,{path:"event",element:a.jsx(tne,{})}),a.jsx(Ie,{path:"blame",element:a.jsx(nne,{})}),a.jsx(Ie,{path:"bots",element:a.jsx(Ene,{})}),a.jsx(Ie,{path:"builder",element:a.jsx(dne,{})}),a.jsx(Ie,{path:"checklist",element:a.jsx(fne,{})}),a.jsx(Ie,{path:"delete",element:a.jsx(hne,{})}),a.jsx(Ie,{path:"details",element:a.jsx(gne,{})}),a.jsx(Ie,{path:"edit",element:a.jsx(vne,{})}),a.jsx(Ie,{path:"editor",element:a.jsx(cne,{})}),a.jsxs(Ie,{path:"history",children:[a.jsx(Ie,{index:!0,element:a.jsx(sR,{})}),a.jsx(Ie,{path:":versionId/:tab",element:a.jsx(jh,{})}),a.jsx(Ie,{path:":versionId",element:a.jsx(jh,{})})]}),a.jsxs(Ie,{path:"_history",children:[a.jsx(Ie,{index:!0,element:a.jsx(sR,{})}),a.jsx(Ie,{path:":versionId/:tab",element:a.jsx(jh,{})}),a.jsx(Ie,{path:":versionId",element:a.jsx(jh,{})})]}),a.jsx(Ie,{path:"json",element:a.jsx(bne,{})}),a.jsx(Ie,{path:"preview",element:a.jsx(Sne,{})}),a.jsx(Ie,{path:"responses",element:a.jsx(Rne,{})}),a.jsx(Ie,{path:"report",element:a.jsx(Dne,{})}),a.jsx(Ie,{path:"ranges",element:a.jsx(_ne,{})}),a.jsx(Ie,{path:"subscriptions",element:a.jsx(qne,{})}),a.jsx(Ie,{path:"timeline",element:a.jsx(lR,{})}),a.jsx(Ie,{path:"tools",element:a.jsx(Wne,{})}),a.jsx(Ie,{path:"profiles",element:a.jsx(wne,{})}),a.jsx(Ie,{path:"export",element:a.jsx(yne,{})})]}),a.jsx(Ie,{path:"/:resourceType",element:a.jsx(iR,{})}),a.jsx(Ie,{path:"/",element:a.jsx(iR,{})})]})})}function ere(){const e=De(),t=e.getUserConfiguration(),n=Lr(),[r]=sS();return e.isLoading()?a.jsx(yi,{}):a.jsx(AG,{logo:a.jsx(Ci,{size:24}),pathname:n.pathname,searchParams:r,version:JD,menus:tre(t),displayAddBookmark:!!t?.id,children:a.jsx(v.Suspense,{fallback:a.jsx(yi,{}),children:a.jsx(Jne,{})})})}function tre(e){const t=e?.menu?.map(n=>({title:n.title,links:n.link?.map(r=>({label:r.name,href:r.target,icon:nre(r.target)}))||[]}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:a.jsx(Vq,{})}]}),t}const cR={Patient:EH,Practitioner:Iq,Organization:eq,ServiceRequest:cH,DiagnosticReport:pH,Questionnaire:Mq,admin:QF,AccessPolicy:Uq,Subscription:MH,batch:eH,Observation:Kq};function nre(e){if(e.includes("admin/super/db"))return a.jsx(vq,{});try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in cR){const n=cR[t];return a.jsx(n,{})}}catch{}return a.jsx(nm,{w:30})}async function rre(){const e=Wd(),t=new eA({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=qJ([{path:"*",element:a.jsx(ere,{})}]),o=c=>r.navigate(c);FX.createRoot(document.getElementById("root")).render(a.jsx(v.StrictMode,{children:a.jsx(ZV,{medplum:t,navigate:o,children:a.jsxs(OR,{theme:n,children:[a.jsx(la,{position:"bottom-right"}),a.jsx(gJ,{router:r})]})})}))}rre().catch(console.error);
607
- //# sourceMappingURL=index-R1Ol1I71.js.map
607
+ //# sourceMappingURL=index-DoATk7Yv.js.map