@medplum/app 4.1.1 → 4.1.2
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: `+k.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 LS=!1;function R6(){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 _6(e,t){if(!e)throw new Error(t)}function sf(e){return new e.constructor(e.type,e)}const Ws={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let $S=!1;class us extends Gp{constructor(t,n,r={}){LS||(R6(),LS=!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=Ws.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),s),_6(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(sf(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(sf(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(sf(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(sf(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 us.CONNECTING}get OPEN(){return us.OPEN}get CLOSING(){return us.CLOSING}get CLOSED(){return us.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?us.CLOSED:us.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=Ws.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=Ws.reconnectionDelayGrowFactor,minReconnectionDelay:n=Ws.minReconnectionDelay,maxReconnectionDelay:r=Ws.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=Ws.maxRetries,connectionTimeout:n=Ws.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"&&!$S&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),$S=!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 D6=5e3;class iv extends Gp{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 I6{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new iv(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class A6{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof rP))throw new ft(fn("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new ft(fn("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 us(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 iv,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??D6,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=ca(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 v=this.criteriaEntriesBySubscriptionId.get(ca(m.subscription));if(!v){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}v.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 ft(G5(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 ${Dt(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 ft(fn("Failed to get token"));if(!s)throw new ft(fn("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(vs(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!vs(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 I6(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 iv(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const nP="4.1.1-9084a85f3",N6=nn.FHIR_JSON+", */*; q=0.1",O6="https://api.medplum.com/",M6=1e3,L6=6e4,$6=0,F6=3e5,z6="Binary/",FS={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},pl={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"},V6={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},B6={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class rP extends Gp{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)??U6(),this.storage=(t==null?void 0:t.storage)??new T6,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=bx((t==null?void 0:t.baseUrl)??O6),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.credentialsInHeader=(t==null?void 0:t.authCredentialsMethod)==="header",this.defaultHeaders=(t==null?void 0:t.defaultHeaders)??{},this.onUnauthenticated=t==null?void 0:t.onUnauthenticated,this.refreshGracePeriod=(t==null?void 0:t.refreshGracePeriod)??F6,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?$6:L6),this.cacheTime>0?this.requestCache=new ET((t==null?void 0:t.resourceCacheSize)??M6):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,nn.JSON_PATCH),this.invalidateUrl(t),this.request("PATCH",t,r)}delete(t,n){return t=t.toString(),this.invalidateUrl(t),this.request("DELETE",t,n)}async startNewUser(t,n){const{codeChallengeMethod:r,codeChallenge:o}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:r,codeChallenge:o},void 0,n)}async startNewProject(t,n){return this.post("auth/newproject",t,void 0,n)}async startNewPatient(t,n){return this.post("auth/newpatient",t,void 0,n)}async startLogin(t,n){return this.post("auth/login",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async startGoogleLogin(t,n){return this.post("auth/google",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async ensureCodeChallenge(t){return t.codeChallenge?t:{...t,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(t){const r=new URLSearchParams(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");return this.fetchTokens({grant_type:pl.TokenExchange,subject_token_type:V6.AccessToken,client_id:n,subject_token:t})}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=F7(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(BS));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 BS(d),o=p!=null&&p.url?new URL(p.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){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 FS;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(FS));const[o,s]=r.split("/");return!o||!s?new wo(Promise.reject(new Error("Invalid reference"))):this.readResource(o,s,n)}requestSchema(t){if(jT(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 LS=!1;function R6(){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 _6(e,t){if(!e)throw new Error(t)}function sf(e){return new e.constructor(e.type,e)}const Ws={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let $S=!1;class us extends Gp{constructor(t,n,r={}){LS||(R6(),LS=!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=Ws.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),s),_6(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(sf(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(sf(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(sf(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(sf(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 us.CONNECTING}get OPEN(){return us.OPEN}get CLOSING(){return us.CLOSING}get CLOSED(){return us.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?us.CLOSED:us.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=Ws.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=Ws.reconnectionDelayGrowFactor,minReconnectionDelay:n=Ws.minReconnectionDelay,maxReconnectionDelay:r=Ws.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=Ws.maxRetries,connectionTimeout:n=Ws.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"&&!$S&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),$S=!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 D6=5e3;class iv extends Gp{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 I6{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new iv(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class A6{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof rP))throw new ft(fn("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new ft(fn("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 us(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 iv,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??D6,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=ca(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 v=this.criteriaEntriesBySubscriptionId.get(ca(m.subscription));if(!v){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}v.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 ft(G5(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 ${Dt(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 ft(fn("Failed to get token"));if(!s)throw new ft(fn("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(vs(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!vs(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 I6(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 iv(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const nP="4.1.2-7f5a095ee",N6=nn.FHIR_JSON+", */*; q=0.1",O6="https://api.medplum.com/",M6=1e3,L6=6e4,$6=0,F6=3e5,z6="Binary/",FS={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},pl={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"},V6={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},B6={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class rP extends Gp{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)??U6(),this.storage=(t==null?void 0:t.storage)??new T6,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=bx((t==null?void 0:t.baseUrl)??O6),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.credentialsInHeader=(t==null?void 0:t.authCredentialsMethod)==="header",this.defaultHeaders=(t==null?void 0:t.defaultHeaders)??{},this.onUnauthenticated=t==null?void 0:t.onUnauthenticated,this.refreshGracePeriod=(t==null?void 0:t.refreshGracePeriod)??F6,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?$6:L6),this.cacheTime>0?this.requestCache=new ET((t==null?void 0:t.resourceCacheSize)??M6):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,nn.JSON_PATCH),this.invalidateUrl(t),this.request("PATCH",t,r)}delete(t,n){return t=t.toString(),this.invalidateUrl(t),this.request("DELETE",t,n)}async startNewUser(t,n){const{codeChallengeMethod:r,codeChallenge:o}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:r,codeChallenge:o},void 0,n)}async startNewProject(t,n){return this.post("auth/newproject",t,void 0,n)}async startNewPatient(t,n){return this.post("auth/newpatient",t,void 0,n)}async startLogin(t,n){return this.post("auth/login",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async startGoogleLogin(t,n){return this.post("auth/google",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async ensureCodeChallenge(t){return t.codeChallenge?t:{...t,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(t){const r=new URLSearchParams(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");return this.fetchTokens({grant_type:pl.TokenExchange,subject_token_type:V6.AccessToken,client_id:n,subject_token:t})}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=F7(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(BS));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 BS(d),o=p!=null&&p.url?new URL(p.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){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 FS;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(FS));const[o,s]=r.split("/");return!o||!s?new wo(Promise.reject(new Error("Invalid reference"))):this.readResource(o,s,n)}requestSchema(t){if(jT(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,
|
|
@@ -569,4 +569,4 @@ Please change the parent <Route path="${E}"> to <Route path="${E==="/"?"*":`${E}
|
|
|
569
569
|
}
|
|
570
570
|
]
|
|
571
571
|
}`,gY="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 vY(){const e=Te(),{id:t}=$t(),[n,r]=g.useState(),[o,s]=g.useState(),[l,u]=g.useState(mY),[d,p]=g.useState(gY),[h,m]=g.useState(nn.FHIR_JSON),v=g.useRef(null),x=g.useRef(null),[b,w]=g.useState(!1);g.useEffect(()=>{e.readResource("Bot",t).then(async D=>{r(D),s(await yY(e,D))}).catch(D=>De({color:"red",message:tt(D),autoClose:!1}))},[e,t]);const j=g.useCallback(async()=>Yc(v.current,{command:"getValue"}),[]),T=g.useCallback(async()=>Yc(v.current,{command:"getOutput"}),[]),R=g.useCallback(async()=>h===nn.FHIR_JSON?JSON.parse(l):d,[h,l,d]),E=g.useCallback(async D=>{D.preventDefault(),D.stopPropagation(),w(!0);try{const A=await j(),O=await T(),L=await e.createAttachment({data:A,filename:"index.ts",contentType:"text/typescript"}),V=await e.createAttachment({data:O,filename:"index.js",contentType:"text/typescript"}),q=[{op:"add",path:"/sourceCode",value:L},{op:"add",path:"/executableCode",value:V}];await e.patchResource("Bot",t,q),De({color:"green",message:"Saved"})}catch(A){De({color:"red",message:tt(A),autoClose:!1})}finally{w(!1)}},[e,t,j,T]),C=g.useCallback(async D=>{D.preventDefault(),D.stopPropagation(),w(!0);try{await e.post(e.fhirUrl("Bot",t,"$deploy")),De({color:"green",message:"Deployed"})}catch(A){De({color:"red",message:tt(A),autoClose:!1})}finally{w(!1)}},[e,t]),P=g.useCallback(async D=>{D.preventDefault(),D.stopPropagation(),w(!0);try{const A=await R(),O=await e.post(e.fhirUrl("Bot",t,"$execute"),A,h);await Yc(x.current,{command:"setValue",value:O}),De({color:"green",message:"Success"})}catch(A){De({color:"red",message:tt(A),autoClose:!1})}finally{w(!1)}},[e,t,R,h]);return!n||o===void 0?null:i.jsxs(Fr,{m:0,gutter:0,style:{overflow:"hidden"},children:[i.jsx(Fr.Col,{span:8,children:i.jsxs(cr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",mih:400,children:[i.jsx(hY,{iframeRef:v,language:"typescript",module:"commonjs",testId:"code-frame",defaultValue:o,minHeight:"528px"}),i.jsxs(xe,{justify:"flex-end",gap:"xs",children:[i.jsx(Oe,{type:"button",onClick:E,loading:b,leftSection:i.jsx(Az,{size:"1rem"}),children:"Save"}),i.jsx(Oe,{type:"button",onClick:C,loading:b,leftSection:i.jsx(Ox,{size:"1rem"}),children:"Deploy"}),i.jsx(Oe,{type:"button",onClick:P,loading:b,leftSection:i.jsx(Gz,{size:"1rem"}),children:"Execute"})]})]})}),i.jsxs(Fr.Col,{span:4,children:[i.jsxs(cr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[i.jsx(Jt,{data:[{label:"FHIR",value:nn.FHIR_JSON},{label:"HL7",value:nn.HL7_V2}],onChange:D=>m(D.currentTarget.value)}),h===nn.FHIR_JSON?i.jsx(Hl,{value:l,onChange:D=>u(D),autosize:!0,minRows:15}):i.jsx("textarea",{className:fY.hl7Input,value:d,onChange:D=>p(D.currentTarget.value),rows:15})]}),i.jsx(cr,{m:2,p:"xs",shadow:"md",children:i.jsx(pY,{iframeRef:x,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function yY(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(AT);return(await e.download(e.fhirUrl("Binary",s))).text()}return t.code??""}function _a(e){let t=e.meta;return t&&(t={...t,lastUpdated:void 0,versionId:void 0,author:void 0}),{...e,meta:t}}function xY(){const e=Te(),{resourceType:t,id:n}=$t(),r={reference:t+"/"+n},o=g.useCallback(s=>{e.updateResource(_a(s)).then(()=>{De({color:"green",message:"Success"})}).catch(l=>{De({color:"red",message:tt(l),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return i.jsx(lt,{children:i.jsx(TW,{value:r,onSubmit:o})});case"Questionnaire":return i.jsx(lt,{children:i.jsx(dH,{questionnaire:r,onSubmit:o})});default:return null}}function bY(){const{resourceType:e,id:t}=$t(),n=Vt({reference:e+"/"+t}),r=Sn();return n?i.jsx(lt,{children:i.jsx(MH,{value:n,onStart:(o,s)=>{var l;return(l=r(`/forms/${ca(s)}`))==null?void 0:l.catch(console.error)},onEdit:(o,s,l)=>{var u;return(u=r(`/${l.reference}}`))==null?void 0:u.catch(console.error)}})}):null}function wY(){const e=Te(),{resourceType:t,id:n}=$t(),r=Sn();return i.jsxs(lt,{children:[i.jsxs("p",{children:["Are you sure you want to delete this ",t,"?"]}),i.jsx(Oe,{color:"red",onClick:()=>{e.deleteResource(t,n).then(()=>{var o;return(o=r(`/${t}`))==null?void 0:o.catch(console.error)}).catch(o=>De({color:"red",message:tt(o),autoClose:!1}))},children:"Delete"})]})}const SY="_selectProfileBtn_tbaz6_1",jY="_chevron_tbaz6_13",dC={selectProfileBtn:SY,chevron:jY};function CY(){var d,p;const{resourceType:e,id:t}=$t(),n=Vt({reference:e+"/"+t}),[r,o]=g.useState(),s=bu({onDropdownClose:()=>s.resetSelectedOption()}),l=g.useMemo(()=>{var h;if(bn((h=n==null?void 0:n.meta)==null?void 0:h.profile))return[i.jsx(ut.Option,{value:"",children:"None"},""),...n.meta.profile.map(m=>i.jsx(ut.Option,{value:m,children:m},m))]},[(d=n==null?void 0:n.meta)==null?void 0:d.profile]);if(g.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(xe,{justify:"flex-end",children:i.jsxs(et,{align:"flex-end",gap:"xs",children:[i.jsxs(ut,{store:s,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:h=>{o(h),s.closeDropdown()},children:[i.jsx(ut.Target,{children:i.jsx(Kn,{onClick:()=>s.toggleDropdown(),children:i.jsxs(Dy,{fw:"bold",fs:"sm",className:dC.selectProfileBtn,children:[i.jsx("span",{children:"Pick profile"}),i.jsx(Nx,{stroke:1.5,className:dC.chevron})]})})}),i.jsx(ut.Dropdown,{w:"max-content",children:i.jsx(ut.Options,{children:l})})]}),i.jsx(se,{children:r?i.jsxs(i.Fragment,{children:[i.jsx(Pe,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),i.jsx(Pe,{span:!0,size:"sm",children:r||"Nothing selected"})]}):i.jsx(Pe,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),i.jsx(lt,{children:i.jsxs(et,{gap:"xl",children:[u,i.jsx(t0,{value:n,profileUrl:r})]})})}function EY(){const e=Te(),{resourceType:t,id:n}=$t(),[r,o]=g.useState(),[s,l]=g.useState(),u=Sn(),[d,p]=g.useState();g.useEffect(()=>{e.readResource(t,n).then(x=>{o(Br(x)),l(Br(x))}).catch(x=>{p(Gt(x)),De({color:"red",message:tt(x),autoClose:!1})})},[e,t,n]);const h=g.useCallback(x=>{p(void 0),e.updateResource(_a(x)).then(()=>{var b;(b=u(`/${t}/${n}/details`))==null||b.catch(console.error),De({id:"succes",color:"green",message:"Success"})}).catch(b=>{p(Gt(b)),De({color:"red",message:tt(b),autoClose:!1})})},[e,t,n,u]),m=g.useCallback(x=>{p(void 0);const b=KP.createPatch(r,x);e.patchResource(t,n,b).then(()=>{var w;(w=u(`/${t}/${n}/details`))==null||w.catch(console.error),De({id:"succes",color:"green",message:"Success"})}).catch(w=>{p(Gt(w)),De({color:"red",message:tt(w),autoClose:!1})})},[e,t,n,r,u]),v=g.useCallback(()=>{var x;return(x=u(`/${t}/${n}/delete`))==null?void 0:x.catch(console.error)},[u,t,n]);return s?i.jsx(lt,{children:i.jsx(Gf,{defaultValue:s,onSubmit:h,onPatch:m,onDelete:v,outcome:d})}):null}function kY(){const{resourceType:e,id:t}=$t(),n=Vt({reference:e+"/"+t});return n?i.jsx(lt,{maw:700,children:n.resourceType==="Patient"?i.jsx(wW,{patient:n}):i.jsx(Ni,{icon:i.jsx(ka,{size:16}),title:"Unsupported export type",color:"red",children:"This page is only supported for Patient resources"})}):null}function l2({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,o=Te(),[s,l]=g.useState();return g.useEffect(()=>{o.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(u=>{l(u.filter(WV))}).catch(console.error)},[o,n,r]),i.jsx(_t,{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(_t.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(_t.Tab,{value:u.url,title:p,rightSection:d&&i.jsx(fx,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:i.jsx(a8,{size:"90%"})}),children:u.title||u.name},u.url)})})})}function c2(e,t){const n=Te(),r=Sn();return{defaultValue:{resourceType:e},handleSubmit:l=>{t&&t(void 0),n.createResource(l).then(u=>r("/"+u.resourceType+"/"+u.id)).catch(u=>{t&&t(Gt(u)),De({color:"red",message:tt(u),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function Ng(){const{resourceType:e}=$t(),t=Rr(),[n,r]=g.useState(),{defaultValue:o,handleSubmit:s}=c2(e,r),[l,u]=g.useState(),d=t.pathname.toLowerCase().endsWith("profiles"),p=g.useCallback(h=>{const m=_a(h);l&&$T(m,l.url),s(m)},[l,s]);return d?i.jsx(lt,{children:i.jsxs(et,{children:[i.jsx(l2,{resource:o,currentProfile:l,onChange:u}),l?i.jsx(Gf,{defaultValue:o,onSubmit:p,outcome:n,profileUrl:l.url},l.url):i.jsx(Pe,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):i.jsx(lt,{children:i.jsx(Gf,{defaultValue:o,onSubmit:s,outcome:n})})}function TY(){const e=Te(),{resourceType:t,id:n}=$t(),r=e.readHistory(t,n).read();return i.jsx(lt,{children:i.jsx(aq,{history:r})})}function PY(){const{resourceType:e}=$t(),[t,n]=g.useState(),{defaultValue:r,handleSubmit:o}=c2(e,n),s=g.useCallback(l=>{o(JSON.parse(l["new-resource"]))},[o]);return i.jsxs(lt,{children:[t&&i.jsx(po,{outcome:t}),i.jsxs(mt,{onSubmit:s,children:[i.jsx(Hl,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:Po(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),i.jsx(xe,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:i.jsx(Oe,{type:"submit",children:"OK"})})]})]})}function RY(){const e=Te(),{resourceType:t,id:n}=$t(),r=Vt({reference:t+"/"+n}),o=Sn(),[s,l]=g.useState(),u=g.useCallback(d=>{e.updateResource(_a(JSON.parse(d.resource))).then(()=>{var p;l(void 0),(p=o(`/${t}/${n}/details`))==null||p.catch(console.error),De({color:"green",message:"Success"})}).catch(p=>{De({color:"red",message:tt(p),autoClose:!1})})},[e,t,n,o]);return r?i.jsxs(lt,{children:[s&&i.jsx(po,{outcome:s}),i.jsxs(mt,{onSubmit:u,children:[i.jsx(Hl,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:Po(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),i.jsx(xe,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:i.jsx(Oe,{type:"submit",children:"OK"})})]})]}):null}function _Y(){const{resourceType:e,id:t}=$t();return Vt({reference:e+"/"+t})?i.jsxs(lt,{children:[i.jsxs(Ni,{icon:i.jsx(ka,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",i.jsx("br",{}),i.jsx(Et,{href:`/forms/${t}`,children:`/forms/${t}`})]}),i.jsx(bR,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function DY(){const e=Te(),{resourceType:t,id:n}=$t(),[r,o]=g.useState(),[s,l]=g.useState();return g.useEffect(()=>{e.readResource(t,n).then(u=>o(Br(u))).catch(u=>{De({color:"red",message:tt(u)})})},[e,t,n]),r?i.jsxs(lt,{children:[i.jsxs(Fe,{order:2,children:["Available ",t," profiles"]}),i.jsx(et,{children:i.jsxs(i.Fragment,{children:[i.jsx(l2,{resource:r,currentProfile:s,onChange:l}),s?i.jsx(IY,{profile:s,resource:r,onResourceUpdated:u=>o(u)},s.url):i.jsx(Pe,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const IY=({profile:e,resource:t,onResourceUpdated:n})=>{const r=Te(),[o,s]=g.useState(),[l,u]=g.useState(()=>{var p,h;return(h=(p=t.meta)==null?void 0:p.profile)==null?void 0:h.includes(e.url)}),d=g.useCallback(p=>{s(void 0);const h=_a(p);l?$T(h,e.url):z7(h,e.url),r.updateResource(h).then(m=>{n(m),De({color:"green",message:"Success"})}).catch(m=>{s(Gt(m)),De({color:"red",message:tt(m),autoClose:!1})})},[r,e.url,n,l]);return i.jsxs(et,{children:[i.jsx(ku,{size:"md",checked:l,label:`Conform resource to ${e.title}`,onChange:p=>u(p.currentTarget.checked),"data-testid":"profile-toggle"}),l?i.jsx(Gf,{profileUrl:e.url,defaultValue:t,onSubmit:d,outcome:o}):i.jsx("form",{noValidate:!0,onSubmit:p=>{p.preventDefault(),d(t)},children:i.jsx(xe,{justify:"flex-end",mt:"xl",children:i.jsx(Oe,{type:"submit",children:"OK"})})})]})},u2={"Create Only":"create","Update Only":"update","Delete Only":"delete","All Interactions":void 0},AY=Object.keys(u2);function NY(){const e=Te(),{id:t}=$t(),n=Vt({reference:`Questionnaire/${t}`}),[r,o]=g.useState(),[s,l]=g.useState("create"),[u,d]=g.useState(0),p=e.searchResources("Subscription","status=active&_count=100").read().filter(m=>OY(m,n));function h(){r&&n&&e.createResource({resourceType:"Subscription",status:"active",reason:`Connect bot ${r.name} to questionnaire responses`,criteria:`QuestionnaireResponse?questionnaire=${n.url?`${n.url},${Dt(n)}`:Dt(n)}`,channel:{type:"rest-hook",endpoint:Dt(r)},...s?{extension:[{url:"https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction",valueCode:s}]}:void 0}).then(()=>{o(void 0),d(Date.now()),e.invalidateSearches("Subscription"),De({color:"green",message:"Success"})}).catch(m=>De({color:"red",message:tt(m),autoClose:!1}))}return i.jsxs(lt,{children:[i.jsx(Fe,{children:"Bots"}),i.jsxs(et,{children:[p.length===0&&i.jsx("p",{children:"No bots found."}),p.map(m=>{var v;return i.jsxs("div",{children:[i.jsx("h3",{children:i.jsx(Zl,{value:{reference:(v=m.channel)==null?void 0:v.endpoint},link:!0})}),i.jsxs("p",{children:["Criteria: ",m.criteria]})]},m.id)})]}),i.jsx(yn,{}),i.jsxs(et,{mt:10,children:[i.jsx(gu,{size:"lg",htmlFor:"bot",children:"Connect to bot"}),i.jsxs(xe,{children:[i.jsx(Ta,{name:"bot",resourceType:"Bot",onChange:m=>o(m)}),i.jsx(Oe,{onClick:h,children:"Connect"})]}),i.jsx(xe,{children:i.jsx(Jt,{name:"subscription-trigger-event",defaultValue:"Create Only",label:"Subscription Trigger Event",data:AY,onChange:m=>l(u2[m.target.value])})})]}),i.jsx("div",{style:{display:"none"},children:u})]})}function OY(e,t){var o;if(!t)return!1;const n=e.criteria||"",r=((o=e.channel)==null?void 0:o.endpoint)||"";return n.startsWith("QuestionnaireResponse?")&&r.startsWith("Bot/")&&(n.includes(Dt(t))||(t.url?n.includes(t.url):!1))}function MY(){const{id:e}=$t(),t=Sn(),r=Te().readReference({reference:`Questionnaire/${e}`}).read(),[o,s]=g.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:le.EQUALS,value:r.url?`${r.url},Questionnaire/${e}`:`Questionnaire/${e}`}],fields:["id","_lastUpdated"]});return i.jsx(lt,{children:i.jsx(zu,{search:o,onClick:l=>{var u;return(u=t(`/${l.resource.resourceType}/${l.resource.id}`))==null?void 0:u.catch(console.error)},onChange:l=>s(l.definition),hideFilters:!0,hideToolbar:!0})})}function LY(){const e=Te(),{resourceType:t,id:n}=$t(),r=Vt({reference:t+"/"+n}),o=g.useCallback(s=>{e.updateResource(_a(s)).then(()=>{De({color:"green",message:"Success"})}).catch(l=>{De({color:"red",message:tt(l),autoClose:!1})})},[e]);return r?i.jsx(lt,{children:i.jsx(PH,{onSubmit:o,definition:r})}):null}function $Y(){const{resourceType:e,id:t}=$t(),n=Vt({reference:e+"/"+t});return n?i.jsx(lt,{children:e==="MeasureReport"?i.jsx(xW,{measureReport:n}):i.jsx(e0,{value:n})}):null}const FY="_container_1ue98_1",zY="_entry_1ue98_14",VY="_active_1ue98_21",Og={container:FY,entry:zY,active:VY};function BY(e){const t=Te(),n=Vt(e.value),[r,o]=g.useState();return g.useEffect(()=>{if(!n)return;const s=E0(n);if(!s)return;const l="reference"in s?s.reference:Dt(s);t.search("ServiceRequest","subject="+l).then(u=>{const p=(u.entry??[]).map(h=>h.resource);YP(p),p.reverse(),o(p)}).catch(u=>De({color:"red",message:tt(u),autoClose:!1}))},[t,n]),r?i.jsx("div",{"data-testid":"quick-service-requests",className:Og.container,children:r.map(s=>{var l,u,d,p,h,m,v;return i.jsxs("div",{className:At(Og.entry,{[Og.active]:s.id===(n==null?void 0:n.id)}),children:[i.jsx("p",{children:i.jsx(xt,{to:s,children:UY(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:(v=s.code.coding[0])==null?void 0:v.code}),i.jsx("p",{children:WY(s)})]},s.id)})}):null}function UY(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function WY(e){var t;return e.authoredOn?e.authoredOn.substring(0,10):(t=e.meta)!=null&&t.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const HY="_container_1l2dh_1",qY={container:HY};function GY(e){var o,s,l,u;const t=Vt(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:qY.container,children:i.jsx(Jt,{defaultValue:e.defaultValue,onChange:d=>e.onChange(d.currentTarget.value),data:n})})}function QY(e){var n,r;const t=Vt(e.specimen);return t?i.jsxs(ht,{children:[i.jsxs(ht.Entry,{children:[i.jsx(ht.Key,{children:"Type"}),i.jsx(ht.Value,{children:"Specimen"})]}),i.jsxs(ht.Entry,{children:[i.jsx(ht.Key,{children:"Collected"}),i.jsx(ht.Value,{children:ur((n=t.collection)==null?void 0:n.collectedDateTime)})]}),i.jsxs(ht.Entry,{children:[i.jsx(ht.Key,{children:"Specimen Age"}),i.jsx(ht.Value,{children:KY(t)})]}),(r=t.collection)!=null&&r.collectedDateTime&&t.receivedTime?i.jsxs(ht.Entry,{children:[i.jsx(ht.Key,{children:"Specimen Stability"}),i.jsx(ht.Value,{children:YY(t)})]}):i.jsx(i.Fragment,{})]}):null}function KY(e){var o;const t=(o=e.collection)==null?void 0:o.collectedDateTime;if(!t)return;const n=new Date(t);return d2(f2(n,new Date))}function YY(e){var r;if(!((r=e.collection)!=null&&r.collectedDateTime)||!e.receivedTime)return;const t=new Date(e.collection.collectedDateTime),n=new Date(e.receivedTime);return d2(f2(t,n))}function d2(e){return e.toString().padStart(3,"0")+"D"}function f2(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function XY(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 JY(){var R,E,C,P,D,A,O;const e=Te(),{resourceType:t,id:n}=$t(),r={reference:t+"/"+n},o=Sn(),[s,l]=g.useState(),u=Vt(r,l),d=XY(t),[p,h]=g.useState(()=>{const L=window.location.pathname.split("/").pop();return L&&d.map(V=>V.toLowerCase()).includes(L)?L:d[0].toLowerCase()});async function m(){var q,G;const V=(G=(q=(await e.readHistory(t,n)).entry)==null?void 0:q.find(Q=>!!Q.resource))==null?void 0:G.resource;V?v(V):De({color:"red",message:"No history to restore",autoClose:!1})}function v(L){e.updateResource(_a(L)).then(()=>{l(void 0),De({color:"green",message:"Success"})}).catch(V=>{De({color:"red",message:tt(V),autoClose:!1})})}if(s)return Q5(s)?i.jsxs(lt,{children:[i.jsx(Fe,{children:"Deleted"}),i.jsx("p",{children:"The resource was deleted."}),i.jsx(Oe,{color:"red",onClick:m,children:"Restore"})]}):i.jsx(po,{outcome:s});function x(L){var V;L||(L=d[0].toLowerCase()),h(L),(V=o(`/${t}/${n}/${L}`))==null||V.catch(console.error)}function b(L){const V=u,q=V.orderDetail||[];q.length===0&&q.push({}),q[0].text!==L&&(q[0].text=L,v({...V,orderDetail:q}))}const w=u&&E0(u),j=u&&SK(u),T=(C=(E=(R=e.getUserConfiguration())==null?void 0:R.option)==null?void 0:E.find(L=>L.id==="statusValueSet"))==null?void 0:C.valueString;return i.jsxs(i.Fragment,{children:[(u==null?void 0:u.resourceType)==="ServiceRequest"&&T&&i.jsx(GY,{valueSet:{reference:T},defaultValue:(D=(P=u.orderDetail)==null?void 0:P[0])==null?void 0:D.text,onChange:b},Dt(u)+"-"+((O=(A=u.orderDetail)==null?void 0:A[0])==null?void 0:O.text)),u&&i.jsx(BY,{value:u}),u&&i.jsxs(cr,{children:[w&&i.jsx(oR,{patient:w}),j&&i.jsx(QY,{specimen:j}),t!=="Patient"&&i.jsx(o2,{resource:r}),i.jsx(co,{children:i.jsx(_t,{value:p.toLowerCase(),onChange:x,children:i.jsx(_t.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:d.map(L=>i.jsx(_t.Tab,{value:L.toLowerCase(),children:L},L))})})})]}),i.jsx(y0,{})]})}function fC(){var T,R,E,C;const e=Sn(),{resourceType:t,id:n,versionId:r,tab:o}=$t(),s=Te(),[l,u]=g.useState(!0),[d,p]=g.useState(),[h,m]=g.useState();if(g.useEffect(()=>{m(void 0),u(!0),s.readHistory(t,n).then(P=>p(P)).then(()=>u(!1)).catch(P=>{m(P),u(!1)})},[s,t,n]),l)return i.jsx(so,{});if(!d)return i.jsxs(lt,{children:[i.jsx(Fe,{children:"Resource not found"}),i.jsx(xt,{to:`/${t}`,children:"Return to search page"})]});const v=d.entry??[],x=v.findIndex(P=>{var D,A;return((A=(D=P.resource)==null?void 0:D.meta)==null?void 0:A.versionId)===r});if(x===-1)return i.jsxs(lt,{children:[i.jsx(Fe,{children:"Version not found"}),i.jsx(xt,{to:`/${t}/${n}`,children:"Return to resource"})]});const b=v[x].resource,w=x<v.length-1?v[x+1].resource:void 0,j="diff";return i.jsxs(_t,{value:o||j,onChange:P=>{var D;return(D=e(`/${t}/${n}/_history/${r}/${P||j}`))==null?void 0:D.catch(console.error)},children:[i.jsxs(cr,{children:[i.jsx(Ou,{fluid:!0,p:"md",children:i.jsx(Pe,{children:`${t} ${n}`})}),i.jsxs(_t.List,{children:[i.jsx(_t.Tab,{value:"diff",children:"Diff"}),i.jsx(_t.Tab,{value:"raw",children:"Raw"})]})]}),i.jsxs(lt,{children:[h&&i.jsx("pre",{"data-testid":"error",children:JSON.stringify(h,void 0,2)}),i.jsx(_t.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/${(R=w.meta)==null?void 0:R.versionId}`,children:(E=w.meta)==null?void 0:E.versionId})]})]}),i.jsx(rq,{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(_t.Panel,{value:"raw",children:i.jsx("pre",{children:JSON.stringify(b,void 0,2)})})]})]})}function ZY(){const{resourceType:e,id:t}=$t(),n=Sn(),[r,o]=g.useState({resourceType:"Subscription",filters:[{code:"url",operator:le.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return i.jsx(lt,{children:i.jsx(rW,{search:r,onClick:s=>{var l;return(l=n(`/${s.resource.resourceType}/${s.resource.id}`))==null?void 0:l.catch(console.error)},onChange:s=>o(s.definition),hideFilters:!0})})}function eX(e){const t=Te(),{resource:n,opened:r,onClose:o}=e,[s,l]=g.useState(!1),[u,d]=g.useState(),[p,h]=g.useState(!1),m=g.useCallback(async()=>{if(n!=null&&n.id)try{await t.post(t.fhirUrl(n.resourceType,n.id,"$resend"),{subscription:s&&u?Dt(u):void 0,verbose:p}),De({color:"green",message:"Done"}),o()}catch(v){De({color:"red",message:tt(v),autoClose:!1})}},[t,n,o,s,u,p]);return i.jsx(Nn,{opened:r,onClose:o,title:"Resend Subscriptions",children:i.jsx(mt,{onSubmit:m,children:i.jsxs(et,{children:[i.jsx(Bn,{label:"Choose subscription (all subscriptions by default)",onChange:v=>l(v.currentTarget.checked)}),s&&i.jsx(Ta,{name:"subscription",resourceType:"Subscription",placeholder:"Subscription",onChange:d}),i.jsx(Bn,{label:"Verbose mode",onChange:v=>h(v.currentTarget.checked)}),i.jsx(xe,{justify:"flex-end",children:i.jsx(Oe,{type:"submit",children:"Resend"})})]})})})}function pC(){const e=Te(),t=Kp(),{resourceType:n,id:r}=$t(),o={reference:n+"/"+r},[s,l]=g.useState(),u=rp(!1);function d(R,E){return e.updateResource({...R,priority:E})}function p(R,E){d(R,"stat").then(E).catch(console.error)}function h(R,E){d(R,"routine").then(E).catch(console.error)}function m(R){t(`/${R.resourceType}/${R.id}`)}function v(R){t(`/${R.resourceType}/${R.id}/edit`)}function x(R){t(`/${R.resourceType}/${R.id}/delete`)}function b(R){l(R),u[1].open()}function w(R){var E;t(`/${R.resourceType}/${R.id}/_history/${(E=R.meta)==null?void 0:E.versionId}`)}function j(R,E){const C="aws-textract";De({id:C,title:"AWS Textract in Progress",message:"Extracting text... This may take a moment...",loading:!0,autoClose:!1}),e.post(e.fhirUrl(R.resourceType,R.id,"$aws-textract"),{}).then(()=>{E(),Zs({id:C,title:"AWS Textract Successful",message:"Text successfully extracted.",color:"green",icon:i.jsx($i,{size:"1rem"}),loading:!1,withCloseButton:!0})}).catch(P=>Zs({id:C,title:"AWS Textract Error",color:"red",message:tt(P),icon:i.jsx(fa,{size:"1rem"}),loading:!1,withCloseButton:!0}))}function T(R){var B;const{primaryResource:E,currentResource:C,reloadTimeline:P}=R,D=C.resourceType===E.resourceType&&C.id===E.id,A=C.resourceType==="Communication"&&C.priority!=="stat",O=C.resourceType==="Communication"&&C.priority==="stat",L=D,V=!D,q=!D,G=!D,Q=(B=e.getProjectMembership())==null?void 0:B.admin,Y=Q,X=NK()&&(C.resourceType==="DocumentReference"||C.resourceType==="Media");return i.jsxs(ve.Dropdown,{children:[i.jsx(ve.Label,{children:"Resource"}),A&&i.jsx(ve.Item,{leftSection:i.jsx(Hz,{size:14}),onClick:()=>p(C,P),"aria-label":`Pin ${Dt(C)}`,children:"Pin"}),O&&i.jsx(ve.Item,{leftSection:i.jsx(qz,{size:14}),onClick:()=>h(C,P),"aria-label":`Unpin ${Dt(C)}`,children:"Unpin"}),V&&i.jsx(ve.Item,{leftSection:i.jsx(XS,{size:14}),onClick:()=>m(C),"aria-label":`Details ${Dt(C)}`,children:"Details"}),L&&i.jsx(ve.Item,{leftSection:i.jsx(XS,{size:14}),onClick:()=>w(C),"aria-label":`Details ${Dt(C)}`,children:"Details"}),q&&i.jsx(ve.Item,{leftSection:i.jsx(pP,{size:14}),onClick:()=>v(C),"aria-label":`Edit ${Dt(C)}`,children:"Edit"}),Q&&i.jsxs(i.Fragment,{children:[i.jsx(ve.Divider,{}),i.jsx(ve.Label,{children:"Admin"}),Y&&i.jsx(ve.Item,{leftSection:i.jsx(Xz,{size:14}),onClick:()=>b(C),"aria-label":`Resend Subscriptions ${Dt(C)}`,children:"Resend Subscriptions"})]}),X&&i.jsxs(i.Fragment,{children:[i.jsx(ve.Divider,{}),i.jsx(ve.Label,{children:"AWS AI"}),i.jsx(ve.Item,{leftSection:i.jsx(i8,{size:14}),onClick:()=>j(C,P),"aria-label":`AWS Textract ${Dt(C)}`,children:"AWS Textract"})]}),G&&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($x,{size:14}),onClick:()=>x(C),"aria-label":`Delete ${Dt(C)}`,children:"Delete"})]})]})}return i.jsxs(i.Fragment,{children:[n==="Encounter"&&i.jsx(fU,{encounter:o,getMenu:T}),n==="Patient"&&i.jsx(CW,{patient:o,getMenu:T}),n==="ServiceRequest"&&i.jsx(uq,{serviceRequest:o,getMenu:T}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&i.jsx(dU,{resource:o,getMenu:T}),i.jsx(eX,{resource:s,opened:u[0],onClose:u[1].close},`resend-subscriptions-${s==null?void 0:s.id}`)]})}function tX(e){const{opened:t,close:n,version:r,loadingStatus:o,handleStatus:s,handleUpgrade:l}=e,[u,d]=g.useState();return g.useEffect(()=>{t&&(u||iz("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(Oe,{onClick:()=>{l(),n()},"aria-label":"Confirm upgrade",children:"Confirm Upgrade"})]}):i.jsx(so,{})}function nX(){const e=Te(),{id:t}=$t(),n=g.useMemo(()=>({reference:"Agent/"+t}),[t]),[r,o]=g.useState(!1),[s,l]=g.useState(!1),[u,d]=g.useState(!1),[p,h]=g.useState(),[m,v]=g.useState(),[x,b]=g.useState(),[w,j]=g.useState(),[T,R]=g.useState(!1),[E,C]=g.useState(!1),[P,{open:D,close:A}]=rp(!1);g.useEffect(()=>{if(r||s||u||T){C(!0);return}C(!1)},[r,s,u,T]);const O=g.useCallback(()=>{o(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(Y=>{var X,B,M,N,F,I;h((B=(X=Y.parameter)==null?void 0:X.find(z=>z.name==="status"))==null?void 0:B.valueCode),v((N=(M=Y.parameter)==null?void 0:M.find(z=>z.name==="version"))==null?void 0:N.valueString),b((I=(F=Y.parameter)==null?void 0:F.find(z=>z.name==="lastUpdated"))==null?void 0:I.valueInstant)}).catch(Y=>Q(tt(Y))).finally(()=>o(!1))},[e,t]),L=g.useCallback(Y=>{const X=Y.host,B=Y.pingCount||1;X&&(R(!0),e.pushToAgent(n,X,`PING ${B}`,nn.PING,!0).then(M=>j(M)).catch(M=>Q(tt(M))).finally(()=>R(!1)))},[e,n]),V=g.useCallback(()=>{l(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(Y=>{G("Agent config reloaded successfully.")}).catch(Y=>Q(tt(Y))).finally(()=>l(!1))},[e,t]),q=g.useCallback(()=>{d(!0),e.get(e.fhirUrl("Agent",t,"$upgrade"),{cache:"reload"}).then(Y=>{G("Agent upgraded successfully.")}).catch(Y=>Q(tt(Y))).finally(()=>d(!1))},[e,t]);function G(Y){De({color:"green",title:"Success",icon:i.jsx($i,{size:"1rem"}),message:Y})}function Q(Y){De({color:"red",title:"Error",message:Y,autoClose:!1})}return i.jsxs(lt,{children:[i.jsx(Nn,{opened:P,onClose:A,title:"Upgrade Agent",centered:!0,children:i.jsx(tX,{opened:P,close:A,version:m,loadingStatus:r,handleStatus:O,handleUpgrade:q})}),i.jsx(Fe,{order:1,children:"Agent Tools"}),i.jsxs("div",{style:{marginBottom:10},children:["Agent: ",i.jsx(Zl,{value:n,link:!0})]}),i.jsx(yn,{my:"lg"}),i.jsx(Fe,{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(Oe,{onClick:O,loading:r,disabled:E&&!r,children:"Get Status"}),!r&&p&&i.jsx(Me,{children:i.jsxs(Me.Tbody,{children:[i.jsxs(Me.Tr,{children:[i.jsx(Me.Td,{children:"Status"}),i.jsx(Me.Td,{children:i.jsx(Zx,{status:p})})]}),i.jsxs(Me.Tr,{children:[i.jsx(Me.Td,{children:"Version"}),i.jsx(Me.Td,{children:m})]}),i.jsxs(Me.Tr,{children:[i.jsx(Me.Td,{children:"Last Updated"}),i.jsx(Me.Td,{children:ur(x,void 0,{timeZoneName:"longOffset"})})]})]})}),i.jsx(yn,{my:"lg"}),i.jsx(Fe,{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(Oe,{onClick:V,loading:s,disabled:E&&!s,"aria-label":"Reload config",children:"Reload Config"}),i.jsx(yn,{my:"lg"}),i.jsx(Fe,{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(Oe,{onClick:D,loading:u,disabled:E&&!u,"aria-label":"Upgrade agent",children:"Upgrade"}),i.jsx(yn,{my:"lg"}),i.jsx(Fe,{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:L,children:i.jsxs(xe,{children:[i.jsx(Ve,{id:"host",name:"host",placeholder:"ex. 127.0.0.1",label:"IP Address / Hostname",rightSection:i.jsx(En,{size:24,radius:"xl",variant:"filled",type:"submit","aria-label":"Ping",loading:T,disabled:E&&!T,children:i.jsx(Zz,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),i.jsx(Dp,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!T&&w&&i.jsxs(i.Fragment,{children:[i.jsx(Fe,{order:5,mt:"sm",mb:0,children:"Last Ping"}),i.jsx("pre",{children:w})]})]})}function rX(){return i.jsx(zG,{children:i.jsxs(Qe,{errorElement:i.jsx(wK,{}),children:[i.jsx(Qe,{path:"/signin",element:i.jsx(zK,{})}),i.jsx(Qe,{path:"/oauth",element:i.jsx(OK,{})}),i.jsx(Qe,{path:"/resetpassword",element:i.jsx(LK,{})}),i.jsx(Qe,{path:"/setpassword/:id/:secret",element:i.jsx(FK,{})}),i.jsx(Qe,{path:"/register",element:i.jsx(MK,{})}),i.jsx(Qe,{path:"/changepassword",element:i.jsx(yK,{})}),i.jsx(Qe,{path:"/security",element:i.jsx($K,{})}),i.jsx(Qe,{path:"/mfa",element:i.jsx(AK,{})}),i.jsx(Qe,{path:"/batch",element:i.jsx(gK,{})}),i.jsx(Qe,{path:"/bulk/:resourceType",element:i.jsx(vK,{})}),i.jsx(Qe,{path:"/smart",element:i.jsx(VK,{})}),i.jsx(Qe,{path:"/forms/:id",element:i.jsx(jK,{})}),i.jsx(Qe,{path:"/admin/super",element:i.jsx(eY,{})}),i.jsx(Qe,{path:"/admin/config",element:i.jsx(YK,{})}),i.jsxs(Qe,{path:"/admin",element:i.jsx(XK,{}),children:[i.jsx(Qe,{path:"patients",element:i.jsx(KK,{})}),i.jsx(Qe,{path:"bots/new",element:i.jsx(WK,{})}),i.jsx(Qe,{path:"bots",element:i.jsx(BK,{})}),i.jsx(Qe,{path:"clients/new",element:i.jsx(HK,{})}),i.jsx(Qe,{path:"clients",element:i.jsx(UK,{})}),i.jsx(Qe,{path:"details",element:i.jsx(lC,{})}),i.jsx(Qe,{path:"invite",element:i.jsx(QK,{})}),i.jsx(Qe,{path:"users",element:i.jsx(nY,{})}),i.jsx(Qe,{path:"project",element:i.jsx(lC,{})}),i.jsx(Qe,{path:"secrets",element:i.jsx(JK,{})}),i.jsx(Qe,{path:"sites",element:i.jsx(ZK,{})}),i.jsx(Qe,{path:"members/:membershipId",element:i.jsx(GK,{})})]}),i.jsx(Qe,{path:"/lab/assays",element:i.jsx(rY,{})}),i.jsx(Qe,{path:"/lab/panels",element:i.jsx(oY,{})}),i.jsx(Qe,{path:"/:resourceType/:id/_history/:versionId/:tab",element:i.jsx(fC,{})}),i.jsx(Qe,{path:"/:resourceType/:id/_history/:versionId",element:i.jsx(fC,{})}),i.jsxs(Qe,{path:"/:resourceType/new",element:i.jsx(bK,{}),children:[i.jsx(Qe,{index:!0,element:i.jsx(Ng,{})}),i.jsx(Qe,{path:"form",element:i.jsx(Ng,{})}),i.jsx(Qe,{path:"json",element:i.jsx(PY,{})}),i.jsx(Qe,{path:"profiles",element:i.jsx(Ng,{})})]}),i.jsxs(Qe,{path:"/:resourceType/:id",element:i.jsx(JY,{}),children:[i.jsx(Qe,{index:!0,element:i.jsx(pC,{})}),i.jsx(Qe,{path:"apply",element:i.jsx(sY,{})}),i.jsx(Qe,{path:"apps",element:i.jsx(aY,{})}),i.jsx(Qe,{path:"event",element:i.jsx(cY,{})}),i.jsx(Qe,{path:"blame",element:i.jsx(uY,{})}),i.jsx(Qe,{path:"bots",element:i.jsx(NY,{})}),i.jsx(Qe,{path:"builder",element:i.jsx(xY,{})}),i.jsx(Qe,{path:"checklist",element:i.jsx(bY,{})}),i.jsx(Qe,{path:"delete",element:i.jsx(wY,{})}),i.jsx(Qe,{path:"details",element:i.jsx(CY,{})}),i.jsx(Qe,{path:"edit",element:i.jsx(EY,{})}),i.jsx(Qe,{path:"editor",element:i.jsx(vY,{})}),i.jsx(Qe,{path:"history",element:i.jsx(TY,{})}),i.jsx(Qe,{path:"json",element:i.jsx(RY,{})}),i.jsx(Qe,{path:"preview",element:i.jsx(_Y,{})}),i.jsx(Qe,{path:"responses",element:i.jsx(MY,{})}),i.jsx(Qe,{path:"report",element:i.jsx($Y,{})}),i.jsx(Qe,{path:"ranges",element:i.jsx(LY,{})}),i.jsx(Qe,{path:"subscriptions",element:i.jsx(ZY,{})}),i.jsx(Qe,{path:"timeline",element:i.jsx(pC,{})}),i.jsx(Qe,{path:"tools",element:i.jsx(nX,{})}),i.jsx(Qe,{path:"profiles",element:i.jsx(DY,{})}),i.jsx(Qe,{path:"export",element:i.jsx(kY,{})})]}),i.jsx(Qe,{path:"/:resourceType",element:i.jsx(aC,{})}),i.jsx(Qe,{path:"/",element:i.jsx(aC,{})})]})})}function oX(){const e=Te(),t=e.getUserConfiguration(),n=Rr(),[r]=w0();return e.isLoading()?i.jsx(so,{}):i.jsx(Z8,{logo:i.jsx(Do,{size:24}),pathname:n.pathname,searchParams:r,version:nP,menus:iX(t),displayAddBookmark:!!(t!=null&&t.id),children:i.jsx(g.Suspense,{fallback:i.jsx(so,{}),children:i.jsx(rX,{})})})}function iX(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:sX(s.target)})))||[]}}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:i.jsx(zz,{})}]}),t}const hC={Patient:n8,Practitioner:$z,Organization:Pz,ServiceRequest:Kz,DiagnosticReport:Jz,Questionnaire:Lz,admin:Ez,AccessPolicy:Fz,Subscription:s8,batch:Wz,Observation:Uz};function sX(e){try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in hC){const n=hC[t];return i.jsx(n,{})}}catch{}return i.jsx(Fp,{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 aX(){const e=Hu(),t=new rP({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(oX,{})}]),o=l=>r.navigate(l);pq.createRoot(document.getElementById("root")).render(i.jsx(g.StrictMode,{children:i.jsx(sz,{medplum:t,navigate:o,children:i.jsxs(FC,{theme:n,children:[i.jsx(Li,{position:"bottom-right"}),i.jsx(MG,{router:r})]})})}))}aX().catch(console.error);
|
|
572
|
-
//# sourceMappingURL=index-
|
|
572
|
+
//# sourceMappingURL=index-CeLG6otA.js.map
|