@medplum/app 4.3.7 → 4.3.8
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.
|
@@ -83,7 +83,7 @@ function g4(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&
|
|
|
83
83
|
*
|
|
84
84
|
* Copy of "partysocket" from Partykit team, a fork of the original "Reconnecting WebSocket"
|
|
85
85
|
* https://github.com/partykit/partykit/blob/main/packages/partysocket
|
|
86
|
-
*/const lc={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let EE=!1;function lV(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");lc.Event=globalThis.Event,lc.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},lc.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function cV(e,t){if(!e)throw new Error(t)}function ah(e){return new e.constructor(e.type,e)}const Ss={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let TE=!1;class Lo extends em{constructor(t,n,r={}){EE||(lV(),EE=!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=i=>{this._debug("open event");const{minUptime:o=Ss.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),o),cV(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(c=>{var u;return(u=this._ws)==null?void 0:u.send(c)}),this._messageQueue=[],this.onopen&&this.onopen(i),this.dispatchEvent(ah(i))},this._handleMessage=i=>{this._debug("message event"),this.onmessage&&this.onmessage(i),this.dispatchEvent(ah(i))},this._handleError=i=>{this._debug("error event",i.message),this._disconnect(void 0,i.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(i),this._debug("exec error listeners"),this.dispatchEvent(ah(i)),this._connect()},this._handleClose=i=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(i),this.dispatchEvent(ah(i))},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 Lo.CONNECTING}get OPEN(){return Lo.OPEN}get CLOSING(){return Lo.CLOSING}get CLOSED(){return Lo.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,i)=>(typeof i=="string"?r+=i.length:i instanceof Blob?r+=i.size:r+=i.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?Lo.CLOSED:Lo.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=Ss.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=Ss.reconnectionDelayGrowFactor,minReconnectionDelay:n=Ss.minReconnectionDelay,maxReconnectionDelay:r=Ss.maxReconnectionDelay}=this._options;let i=0;return this._retryCount>0&&(i=n*Math.pow(t,this._retryCount-1),i>r&&(i=r)),this._debug("next delay",i),i}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=Ss.maxRetries,connectionTimeout:n=Ss.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"&&!TE&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),TE=!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 lc.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new lc.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new lc.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 uV=5e3;class Vy extends em{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 dV{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new Vy(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class fV{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof XD))throw new ft(yn("First arg of constructor should be a `MedplumClient`"));let i;try{i=new URL(n).toString()}catch{throw new ft(yn("Not a valid URL"))}const o=r!=null&&r.ReconnectingWebSocket?new r.ReconnectingWebSocket(i,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger}):new Lo(i,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger});this.medplum=t,this.ws=o,this.masterSubEmitter=new Vy,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??uV,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,i,o,c,u,f;try{const h=JSON.parse(n.data);if(h.type==="pong"){this.waitingForPong=!1;return}const m=h,g=(i=(r=m==null?void 0:m.entry)==null?void 0:r[0])==null?void 0:i.resource;if(g.type==="heartbeat"){(o=this.masterSubEmitter)==null||o.dispatchEvent({type:"heartbeat",payload:m});return}if(g.type==="handshake"){const b=Vs(g.subscription),S={type:"connect",payload:{subscriptionId:b}};(c=this.masterSubEmitter)==null||c.dispatchEvent(S);const j=this.criteriaEntriesBySubscriptionId.get(b);if(!j){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}j.connecting=!1,j.emitter.dispatchEvent({...S});return}(u=this.masterSubEmitter)==null||u.dispatchEvent({type:"message",payload:m});const y=this.criteriaEntriesBySubscriptionId.get(Vs(g.subscription));if(!y){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}y.emitter.dispatchEvent({type:"message",payload:m})}catch(h){console.error(h);const m={type:"error",payload:h};(f=this.masterSubEmitter)==null||f.dispatchEvent(m);for(const g of this.getAllCriteriaEmitters())g.dispatchEvent({...m})}}),t.addEventListener("error",()=>{var r;const n={type:"error",payload:new ft(jz(new Error("WebSocket error")))};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const i of this.getAllCriteriaEmitters())i.dispatchEvent({...n})}),t.addEventListener("close",()=>{var r,i;const n={type:"close"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const o of this.getAllCriteriaEmitters())o.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),(i=this.masterSubEmitter)==null||i.removeAllListeners())}),t.addEventListener("open",()=>{var r;const n={type:"open"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const i of this.getAllCriteriaEmitters())i.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 i;const r={type:"error",payload:n};(i=this.masterSubEmitter)==null||i.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){var r;const{subscriptionId:n}=t;if(n){const i={type:"disconnect",payload:{subscriptionId:n}};(r=this.masterSubEmitter)==null||r.dispatchEvent(i),t.emitter.dispatchEvent({...i})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){var c,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 ${Mt(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`),i=(c=r==null?void 0:r.find(f=>f.name==="token"))==null?void 0:c.valueString,o=(u=r==null?void 0:r.find(f=>f.name==="websocket-url"))==null?void 0:u.valueUrl;if(!i)throw new ft(yn("Failed to get token"));if(!o)throw new ft(yn("Failed to get URL from $get-ws-binding-token"));return[n,i]}maybeGetCriteriaEntry(t,n){const r=this.criteriaEntries.get(t);if(r){if(!n)return r.bareCriteria;for(const i of r.criteriaWithProps)if(sa(n,i.subscriptionProps))return i}}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 i;this.criteriaEntries.has(n)?i=this.criteriaEntries.get(n):(i={criteriaWithProps:[]},this.criteriaEntries.set(n,i)),r?i.criteriaWithProps.push(t):i.bareCriteria=t}removeCriteriaEntry(t){var u;const{criteria:n,subscriptionProps:r,subscriptionId:i,token:o}=t;if(!this.criteriaEntries.has(n))return;const c=this.criteriaEntries.get(n);r?c.criteriaWithProps=c.criteriaWithProps.filter(f=>{const h=f.subscriptionProps;return!sa(r,h)}):c.bareCriteria=void 0,!c.bareCriteria&&c.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),(u=this.masterSubEmitter)==null||u._removeCriteria(n)),i&&this.criteriaEntriesBySubscriptionId.delete(i),o&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:o}}))}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(Ke(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 i=new dV(t,n);return this.addCriteriaEntry(i),this.subscribeToCriteria(i).catch(console.error),i.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 Vy(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const YD="4.3.7-da76410e3",hV=fn.FHIR_JSON+", */*; q=0.1",pV="https://api.medplum.com/",mV=1e3,gV=6e4,vV=0,yV=3e5,xV="Binary/",RE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},ec={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"},bV={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},SV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class XD extends em{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)??wV(),this.storage=(t==null?void 0:t.storage)??new oV,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=ab((t==null?void 0:t.baseUrl)??pV),this.fhirBaseUrl=Ki(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=Ki(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=Ki(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=Ki(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),this.fhircastHubUrl=Ki(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)??yV,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?vV:gV),this.cacheTime>0?this.requestCache=new sD((t==null?void 0:t.resourceCacheSize)??mV):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=Ki(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 i;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?i=new Promise((c,u)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:c,reject:u}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):i=this.request("GET",t,n);const o=new Ri(i);return this.setCacheEntry(t,o),o}post(t,n,r,i={}){return t=t.toString(),this.setRequestBody(i,n),r&&this.setRequestContentType(i,r),this.invalidateUrl(t),this.request("POST",t,i)}put(t,n,r,i={}){return t=t.toString(),this.setRequestBody(i,n),r&&this.setRequestContentType(i,r),this.invalidateUrl(t),this.request("PUT",t,i)}patch(t,n,r={}){return t=t.toString(),this.setRequestBody(r,n),this.setRequestContentType(r,fn.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:i}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:r,codeChallenge:i},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,i,o=!0){let c=i;o&&(c=await this.ensureCodeChallenge(i)),window.location.assign(this.getExternalAuthRedirectUri(t,n,r,c,o))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");return this.fetchTokens({grant_type:ec.TokenExchange,subject_token_type:bV.AccessToken,client_id:n,subject_token:t})}getExternalAuthRedirectUri(t,n,r,i,o=!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",i.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(i)),o){const{codeChallenge:u,codeChallengeMethod:f}=i;if(!f)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!u)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");c.searchParams.set("code_challenge_method",f),c.searchParams.set("code_challenge",u)}return c.toString()}fhirUrl(...t){return new URL(Ki(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=pU(n)),r}search(t,n,r){const i=this.fhirSearchUrl(t,n),o="search-"+i.toString(),c=this.getCacheEntry(o,r);if(c)return c.value;const u=this.getBundle(i,r);return this.setCacheEntry(o,u),u}searchOne(t,n,r){const i=this.fhirSearchUrl(t,n);i.searchParams.set("_count","1"),i.searchParams.sort();const o="searchOne-"+i.toString(),c=this.getCacheEntry(o,r);if(c)return c.value;const u=new Ri(this.search(t,i.searchParams,r).then(f=>{var h,m;return(m=(h=f.entry)==null?void 0:h[0])==null?void 0:m.resource}));return this.setCacheEntry(o,u),u}searchResources(t,n,r){const o="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(o,r);if(c)return c.value;const u=new Ri(this.search(t,n,r).then(AE));return this.setCacheEntry(o,u),u}async*searchResourcePages(t,n,r){var o,c;let i=this.fhirSearchUrl(t,n);for(;i;){const u=new URL(i).searchParams;u.has("_count")||u.set("_count","1000");const f=await this.search(t,u,r),h=(o=f.link)==null?void 0:o.find(m=>m.relation==="next");if(!((c=f.entry)!=null&&c.length)&&!h)break;yield AE(f),i=h!=null&&h.url?new URL(h.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 i,o;const r=(o=(i=this.requestCache)==null?void 0:i.get(this.fhirUrl(t,n).toString()))==null?void 0:o.value;return r!=null&&r.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return RE;const[r,i]=n.split("/");if(!(!r||!i))return this.getCached(r,i)}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 Ri(Promise.reject(new Error("Missing reference")));if(r==="system")return new Ri(Promise.resolve(RE));const[i,o]=r.split("/");return!i||!o?new Ri(Promise.reject(new Error("Invalid reference"))):this.readResource(i,o,n)}requestSchema(t){if(pD(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const i=new Ri((async()=>{const o=`{
|
|
86
|
+
*/const lc={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let EE=!1;function lV(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");lc.Event=globalThis.Event,lc.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},lc.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function cV(e,t){if(!e)throw new Error(t)}function ah(e){return new e.constructor(e.type,e)}const Ss={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let TE=!1;class Lo extends em{constructor(t,n,r={}){EE||(lV(),EE=!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=i=>{this._debug("open event");const{minUptime:o=Ss.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),o),cV(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(c=>{var u;return(u=this._ws)==null?void 0:u.send(c)}),this._messageQueue=[],this.onopen&&this.onopen(i),this.dispatchEvent(ah(i))},this._handleMessage=i=>{this._debug("message event"),this.onmessage&&this.onmessage(i),this.dispatchEvent(ah(i))},this._handleError=i=>{this._debug("error event",i.message),this._disconnect(void 0,i.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(i),this._debug("exec error listeners"),this.dispatchEvent(ah(i)),this._connect()},this._handleClose=i=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(i),this.dispatchEvent(ah(i))},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 Lo.CONNECTING}get OPEN(){return Lo.OPEN}get CLOSING(){return Lo.CLOSING}get CLOSED(){return Lo.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,i)=>(typeof i=="string"?r+=i.length:i instanceof Blob?r+=i.size:r+=i.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?Lo.CLOSED:Lo.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=Ss.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=Ss.reconnectionDelayGrowFactor,minReconnectionDelay:n=Ss.minReconnectionDelay,maxReconnectionDelay:r=Ss.maxReconnectionDelay}=this._options;let i=0;return this._retryCount>0&&(i=n*Math.pow(t,this._retryCount-1),i>r&&(i=r)),this._debug("next delay",i),i}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=Ss.maxRetries,connectionTimeout:n=Ss.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"&&!TE&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),TE=!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 lc.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new lc.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new lc.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 uV=5e3;class Vy extends em{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 dV{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new Vy(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class fV{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof XD))throw new ft(yn("First arg of constructor should be a `MedplumClient`"));let i;try{i=new URL(n).toString()}catch{throw new ft(yn("Not a valid URL"))}const o=r!=null&&r.ReconnectingWebSocket?new r.ReconnectingWebSocket(i,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger}):new Lo(i,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger});this.medplum=t,this.ws=o,this.masterSubEmitter=new Vy,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??uV,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,i,o,c,u,f;try{const h=JSON.parse(n.data);if(h.type==="pong"){this.waitingForPong=!1;return}const m=h,g=(i=(r=m==null?void 0:m.entry)==null?void 0:r[0])==null?void 0:i.resource;if(g.type==="heartbeat"){(o=this.masterSubEmitter)==null||o.dispatchEvent({type:"heartbeat",payload:m});return}if(g.type==="handshake"){const b=Vs(g.subscription),S={type:"connect",payload:{subscriptionId:b}};(c=this.masterSubEmitter)==null||c.dispatchEvent(S);const j=this.criteriaEntriesBySubscriptionId.get(b);if(!j){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}j.connecting=!1,j.emitter.dispatchEvent({...S});return}(u=this.masterSubEmitter)==null||u.dispatchEvent({type:"message",payload:m});const y=this.criteriaEntriesBySubscriptionId.get(Vs(g.subscription));if(!y){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}y.emitter.dispatchEvent({type:"message",payload:m})}catch(h){console.error(h);const m={type:"error",payload:h};(f=this.masterSubEmitter)==null||f.dispatchEvent(m);for(const g of this.getAllCriteriaEmitters())g.dispatchEvent({...m})}}),t.addEventListener("error",()=>{var r;const n={type:"error",payload:new ft(jz(new Error("WebSocket error")))};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const i of this.getAllCriteriaEmitters())i.dispatchEvent({...n})}),t.addEventListener("close",()=>{var r,i;const n={type:"close"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const o of this.getAllCriteriaEmitters())o.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),(i=this.masterSubEmitter)==null||i.removeAllListeners())}),t.addEventListener("open",()=>{var r;const n={type:"open"};(r=this.masterSubEmitter)==null||r.dispatchEvent(n);for(const i of this.getAllCriteriaEmitters())i.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 i;const r={type:"error",payload:n};(i=this.masterSubEmitter)==null||i.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){var r;const{subscriptionId:n}=t;if(n){const i={type:"disconnect",payload:{subscriptionId:n}};(r=this.masterSubEmitter)==null||r.dispatchEvent(i),t.emitter.dispatchEvent({...i})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){var c,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 ${Mt(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`),i=(c=r==null?void 0:r.find(f=>f.name==="token"))==null?void 0:c.valueString,o=(u=r==null?void 0:r.find(f=>f.name==="websocket-url"))==null?void 0:u.valueUrl;if(!i)throw new ft(yn("Failed to get token"));if(!o)throw new ft(yn("Failed to get URL from $get-ws-binding-token"));return[n,i]}maybeGetCriteriaEntry(t,n){const r=this.criteriaEntries.get(t);if(r){if(!n)return r.bareCriteria;for(const i of r.criteriaWithProps)if(sa(n,i.subscriptionProps))return i}}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 i;this.criteriaEntries.has(n)?i=this.criteriaEntries.get(n):(i={criteriaWithProps:[]},this.criteriaEntries.set(n,i)),r?i.criteriaWithProps.push(t):i.bareCriteria=t}removeCriteriaEntry(t){var u;const{criteria:n,subscriptionProps:r,subscriptionId:i,token:o}=t;if(!this.criteriaEntries.has(n))return;const c=this.criteriaEntries.get(n);r?c.criteriaWithProps=c.criteriaWithProps.filter(f=>{const h=f.subscriptionProps;return!sa(r,h)}):c.bareCriteria=void 0,!c.bareCriteria&&c.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),(u=this.masterSubEmitter)==null||u._removeCriteria(n)),i&&this.criteriaEntriesBySubscriptionId.delete(i),o&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:o}}))}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(Ke(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 i=new dV(t,n);return this.addCriteriaEntry(i),this.subscribeToCriteria(i).catch(console.error),i.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 Vy(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const YD="4.3.8-f9656648f",hV=fn.FHIR_JSON+", */*; q=0.1",pV="https://api.medplum.com/",mV=1e3,gV=6e4,vV=0,yV=3e5,xV="Binary/",RE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},ec={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"},bV={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},SV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class XD extends em{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)??wV(),this.storage=(t==null?void 0:t.storage)??new oV,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=ab((t==null?void 0:t.baseUrl)??pV),this.fhirBaseUrl=Ki(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=Ki(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=Ki(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=Ki(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),this.fhircastHubUrl=Ki(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)??yV,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?vV:gV),this.cacheTime>0?this.requestCache=new sD((t==null?void 0:t.resourceCacheSize)??mV):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=Ki(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 i;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?i=new Promise((c,u)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:c,reject:u}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):i=this.request("GET",t,n);const o=new Ri(i);return this.setCacheEntry(t,o),o}post(t,n,r,i={}){return t=t.toString(),this.setRequestBody(i,n),r&&this.setRequestContentType(i,r),this.invalidateUrl(t),this.request("POST",t,i)}put(t,n,r,i={}){return t=t.toString(),this.setRequestBody(i,n),r&&this.setRequestContentType(i,r),this.invalidateUrl(t),this.request("PUT",t,i)}patch(t,n,r={}){return t=t.toString(),this.setRequestBody(r,n),this.setRequestContentType(r,fn.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:i}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:r,codeChallenge:i},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,i,o=!0){let c=i;o&&(c=await this.ensureCodeChallenge(i)),window.location.assign(this.getExternalAuthRedirectUri(t,n,r,c,o))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");return this.fetchTokens({grant_type:ec.TokenExchange,subject_token_type:bV.AccessToken,client_id:n,subject_token:t})}getExternalAuthRedirectUri(t,n,r,i,o=!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",i.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(i)),o){const{codeChallenge:u,codeChallengeMethod:f}=i;if(!f)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!u)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");c.searchParams.set("code_challenge_method",f),c.searchParams.set("code_challenge",u)}return c.toString()}fhirUrl(...t){return new URL(Ki(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=pU(n)),r}search(t,n,r){const i=this.fhirSearchUrl(t,n),o="search-"+i.toString(),c=this.getCacheEntry(o,r);if(c)return c.value;const u=this.getBundle(i,r);return this.setCacheEntry(o,u),u}searchOne(t,n,r){const i=this.fhirSearchUrl(t,n);i.searchParams.set("_count","1"),i.searchParams.sort();const o="searchOne-"+i.toString(),c=this.getCacheEntry(o,r);if(c)return c.value;const u=new Ri(this.search(t,i.searchParams,r).then(f=>{var h,m;return(m=(h=f.entry)==null?void 0:h[0])==null?void 0:m.resource}));return this.setCacheEntry(o,u),u}searchResources(t,n,r){const o="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(o,r);if(c)return c.value;const u=new Ri(this.search(t,n,r).then(AE));return this.setCacheEntry(o,u),u}async*searchResourcePages(t,n,r){var o,c;let i=this.fhirSearchUrl(t,n);for(;i;){const u=new URL(i).searchParams;u.has("_count")||u.set("_count","1000");const f=await this.search(t,u,r),h=(o=f.link)==null?void 0:o.find(m=>m.relation==="next");if(!((c=f.entry)!=null&&c.length)&&!h)break;yield AE(f),i=h!=null&&h.url?new URL(h.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 i,o;const r=(o=(i=this.requestCache)==null?void 0:i.get(this.fhirUrl(t,n).toString()))==null?void 0:o.value;return r!=null&&r.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return RE;const[r,i]=n.split("/");if(!(!r||!i))return this.getCached(r,i)}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 Ri(Promise.reject(new Error("Missing reference")));if(r==="system")return new Ri(Promise.resolve(RE));const[i,o]=r.split("/");return!i||!o?new Ri(Promise.reject(new Error("Invalid reference"))):this.readResource(i,o,n)}requestSchema(t){if(pD(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const i=new Ri((async()=>{const o=`{
|
|
87
87
|
StructureDefinitionList(_filter: "name eq ${t}") {
|
|
88
88
|
resourceType,
|
|
89
89
|
name,
|
|
@@ -586,4 +586,4 @@ Please change the parent <Route path="${_}"> to <Route path="${_==="/"?"*":`${_}
|
|
|
586
586
|
}
|
|
587
587
|
]
|
|
588
588
|
}`,$te="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 zte(){const e=Ae(),{id:t}=Ht(),[n,r]=v.useState(),[i,o]=v.useState(),[c,u]=v.useState(Ite),[f,h]=v.useState($te),[m,g]=v.useState(fn.FHIR_JSON),y=v.useRef(null),b=v.useRef(null),[S,j]=v.useState(!1);v.useEffect(()=>{e.readResource("Bot",t).then(async k=>{r(k),o(await Ute(e,k))}).catch(k=>Oe({color:"red",message:Ke(k),autoClose:!1}))},[e,t]);const C=v.useCallback(async()=>qu(y.current,{command:"getValue"}),[]),T=v.useCallback(async()=>qu(y.current,{command:"getOutput"}),[]),_=v.useCallback(async()=>m===fn.FHIR_JSON?JSON.parse(c):f,[m,c,f]),E=v.useCallback(async k=>{k.preventDefault(),k.stopPropagation(),j(!0);try{const M=await C(),L=await T(),z=await e.createAttachment({data:M,filename:"index.ts",contentType:"text/typescript"}),F=await e.createAttachment({data:L,filename:"index.js",contentType:"text/typescript"}),Y=[{op:"add",path:"/sourceCode",value:z},{op:"add",path:"/executableCode",value:F}];await e.patchResource("Bot",t,Y),Oe({color:"green",message:"Saved"})}catch(M){Oe({color:"red",message:Ke(M),autoClose:!1})}finally{j(!1)}},[e,t,C,T]),R=v.useCallback(async k=>{k.preventDefault(),k.stopPropagation(),j(!0);try{await e.post(e.fhirUrl("Bot",t,"$deploy")),Oe({color:"green",message:"Deployed"})}catch(M){Oe({color:"red",message:Ke(M),autoClose:!1})}finally{j(!1)}},[e,t]),D=v.useCallback(async k=>{k.preventDefault(),k.stopPropagation(),j(!0);try{const M=await _(),L=await e.post(e.fhirUrl("Bot",t,"$execute"),M,m);await qu(b.current,{command:"setValue",value:L}),Oe({color:"green",message:"Success"})}catch(M){Oe({color:"red",message:Ke(M),autoClose:!1})}finally{j(!1)}},[e,t,_,m]);return!n||i===void 0?null:s.jsxs(or,{m:0,gutter:0,style:{overflow:"hidden"},children:[s.jsx(or.Col,{span:8,children:s.jsxs(lr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",mih:400,children:[s.jsx(Lte,{iframeRef:y,language:"typescript",module:"commonjs",testId:"code-frame",defaultValue:i,minHeight:"528px"}),s.jsxs(je,{justify:"flex-end",gap:"xs",children:[s.jsx(Pe,{type:"button",onClick:E,loading:S,leftSection:s.jsx(fH,{size:"1rem"}),children:"Save"}),s.jsx(Pe,{type:"button",onClick:R,loading:S,leftSection:s.jsx(wb,{size:"1rem"}),children:"Deploy"}),s.jsx(Pe,{type:"button",onClick:D,loading:S,leftSection:s.jsx(YH,{size:"1rem"}),children:"Execute"})]})]})}),s.jsxs(or.Col,{span:4,children:[s.jsxs(lr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[s.jsx(sn,{data:[{label:"FHIR",value:fn.FHIR_JSON},{label:"HL7",value:fn.HL7_V2}],onChange:k=>g(k.currentTarget.value)}),m===fn.FHIR_JSON?s.jsx(Ac,{value:c,onChange:k=>u(k),autosize:!0,minRows:15}):s.jsx("textarea",{className:Ote.hl7Input,value:f,onChange:k=>h(k.currentTarget.value),rows:15})]}),s.jsx(lr,{m:2,p:"xs",shadow:"md",children:s.jsx(Mte,{iframeRef:b,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function Ute(e,t){var n,r,i;if((n=t.sourceCode)!=null&&n.url){const o=(i=(r=t.sourceCode.url)==null?void 0:r.split("/"))==null?void 0:i.find(RD);return(await e.download(e.fhirUrl("Binary",o))).text()}return t.code??""}function cl(e){let t=e.meta;return t&&(t={...t,lastUpdated:void 0,versionId:void 0,author:void 0}),{...e,meta:t}}function Bte(){const e=Ae(),{resourceType:t,id:n}=Ht(),r={reference:t+"/"+n},i=v.useCallback(o=>{e.updateResource(cl(o)).then(()=>{Oe({color:"green",message:"Success"})}).catch(c=>{Oe({color:"red",message:Ke(c),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return s.jsx(st,{children:s.jsx(YY,{value:r,onSubmit:i})});case"Questionnaire":return s.jsx(st,{children:s.jsx(jX,{questionnaire:r,onSubmit:i})});default:return null}}function Vte(){const{resourceType:e,id:t}=Ht(),n=Wt({reference:e+"/"+t}),r=Sn();return n?s.jsx(st,{children:s.jsx(YX,{value:n,onStart:(i,o)=>{var c;return(c=r(`/forms/${Vs(o)}`))==null?void 0:c.catch(console.error)},onEdit:(i,o,c)=>{var u;return(u=r(`/${c.reference}}`))==null?void 0:u.catch(console.error)}})}):null}function Fte(){const e=Ae(),{resourceType:t,id:n}=Ht(),r=Sn();return s.jsxs(st,{children:[s.jsxs("p",{children:["Are you sure you want to delete this ",t,"?"]}),s.jsx(Pe,{color:"red",onClick:()=>{e.deleteResource(t,n).then(()=>{var i;return(i=r(`/${t}`))==null?void 0:i.catch(console.error)}).catch(i=>Oe({color:"red",message:Ke(i),autoClose:!1}))},children:"Delete"})]})}const Hte="_selectProfileBtn_tbaz6_1",qte="_chevron_tbaz6_13",tR={selectProfileBtn:Hte,chevron:qte};function Gte(){var f,h;const{resourceType:e,id:t}=Ht(),n=Wt({reference:e+"/"+t}),[r,i]=v.useState(),o=gd({onDropdownClose:()=>o.resetSelectedOption()}),c=v.useMemo(()=>{var m;if(Tn((m=n==null?void 0:n.meta)==null?void 0:m.profile))return[s.jsx(ct.Option,{value:"",children:"None"},""),...n.meta.profile.map(g=>s.jsx(ct.Option,{value:g,children:g},g))]},[(f=n==null?void 0:n.meta)==null?void 0:f.profile]);if(v.useEffect(()=>{var m,g;((g=(m=n==null?void 0:n.meta)==null?void 0:m.profile)==null?void 0:g.length)===1&&i(n.meta.profile[0])},[(h=n==null?void 0:n.meta)==null?void 0:h.profile]),!n)return null;let u;return Tn(c)&&(u=s.jsx(je,{justify:"flex-end",children:s.jsxs(qe,{align:"flex-end",gap:"xs",children:[s.jsxs(ct,{store:o,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:m=>{i(m),o.closeDropdown()},children:[s.jsx(ct.Target,{children:s.jsx(tr,{onClick:()=>o.toggleDropdown(),children:s.jsxs(g0,{fw:"bold",fs:"sm",className:tR.selectProfileBtn,children:[s.jsx("span",{children:"Pick profile"}),s.jsx(Sb,{stroke:1.5,className:tR.chevron})]})})}),s.jsx(ct.Dropdown,{w:"max-content",children:s.jsx(ct.Options,{children:c})})]}),s.jsx(ce,{children:r?s.jsxs(s.Fragment,{children:[s.jsx(_e,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),s.jsx(_e,{span:!0,size:"sm",children:r||"Nothing selected"})]}):s.jsx(_e,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),s.jsx(st,{children:s.jsxs(qe,{gap:"xl",children:[u,s.jsx($b,{value:n,profileUrl:r})]})})}function Wte(){const e=Ae(),{resourceType:t,id:n}=Ht(),[r,i]=v.useState(),[o,c]=v.useState(),u=Sn(),[f,h]=v.useState();v.useEffect(()=>{e.readResource(t,n).then(b=>{i(Wr(b)),c(Wr(b))}).catch(b=>{h(Kt(b)),Oe({color:"red",message:Ke(b),autoClose:!1})})},[e,t,n]);const m=v.useCallback(b=>{h(void 0),e.updateResource(cl(b)).then(()=>{var S;(S=u(`/${t}/${n}/details`))==null||S.catch(console.error),Oe({id:"succes",color:"green",message:"Success"})}).catch(S=>{h(Kt(S)),Oe({color:"red",message:Ke(S),autoClose:!1})})},[e,t,n,u]),g=v.useCallback(b=>{h(void 0);const S=KA.createPatch(r,b);e.patchResource(t,n,S).then(()=>{var j;(j=u(`/${t}/${n}/details`))==null||j.catch(console.error),Oe({id:"succes",color:"green",message:"Success"})}).catch(j=>{h(Kt(j)),Oe({color:"red",message:Ke(j),autoClose:!1})})},[e,t,n,r,u]),y=v.useCallback(()=>{var b;return(b=u(`/${t}/${n}/delete`))==null?void 0:b.catch(console.error)},[u,t,n]);return o?s.jsx(st,{children:s.jsx(Zh,{defaultValue:o,onSubmit:m,onPatch:g,onDelete:y,outcome:f})}):null}function Qte(){const{resourceType:e,id:t}=Ht(),n=Wt({reference:e+"/"+t});return n?s.jsx(st,{maw:700,children:n.resourceType==="Patient"?s.jsx(FY,{patient:n}):s.jsx(Za,{icon:s.jsx(al,{size:16}),title:"Unsupported export type",color:"red",children:"This page is only supported for Patient resources"})}):null}function oP({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,i=Ae(),[o,c]=v.useState();return v.useEffect(()=>{i.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(u=>{c(u.filter(uW))}).catch(console.error)},[i,n,r]),s.jsx(Rt,{value:t==null?void 0:t.url,onChange:u=>{const f=o==null?void 0:o.find(h=>h.url===u);f&&n(f)},children:s.jsx(Rt.List,{children:o==null?void 0:o.map(u=>{var m,g;const f=(g=(m=e.meta)==null?void 0:m.profile)==null?void 0:g.includes(u.url),h=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 s.jsx(Rt.Tab,{value:u.url,title:h,rightSection:f&&s.jsx(X0,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:s.jsx(Rq,{size:"90%"})}),children:u.title||u.name},u.url)})})})}function sP(e,t){const n=Ae(),r=Sn();return{defaultValue:{resourceType:e},handleSubmit:c=>{t&&t(void 0),n.createResource(c).then(u=>r("/"+u.resourceType+"/"+u.id)).catch(u=>{t&&t(Kt(u)),Oe({color:"red",message:Ke(u),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function yy(){const{resourceType:e}=Ht(),t=Or(),[n,r]=v.useState(),{defaultValue:i,handleSubmit:o}=sP(e,r),[c,u]=v.useState(),f=t.pathname.toLowerCase().endsWith("profiles"),h=v.useCallback(m=>{const g=cl(m);c&&PD(g,c.url),o(g)},[c,o]);return f?s.jsx(st,{children:s.jsxs(qe,{children:[s.jsx(oP,{resource:i,currentProfile:c,onChange:u}),c?s.jsx(Zh,{defaultValue:i,onSubmit:h,outcome:n,profileUrl:c.url},c.url):s.jsx(_e,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):s.jsx(st,{children:s.jsx(Zh,{defaultValue:i,onSubmit:o,outcome:n})})}function Yte(){const e=Ae(),{resourceType:t,id:n}=Ht(),r=e.readHistory(t,n).read();return s.jsx(st,{children:s.jsx(bK,{history:r})})}function Xte(){const{resourceType:e}=Ht(),[t,n]=v.useState(),{defaultValue:r,handleSubmit:i}=sP(e,n),o=v.useCallback(c=>{i(JSON.parse(c["new-resource"]))},[i]);return s.jsxs(st,{children:[t&&s.jsx(Xr,{outcome:t}),s.jsxs(mt,{onSubmit:o,children:[s.jsx(Ac,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:Oi(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),s.jsx(je,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(Pe,{type:"submit",children:"OK"})})]})]})}function Kte(){const e=Ae(),{resourceType:t,id:n}=Ht(),r=Wt({reference:t+"/"+n}),i=Sn(),[o,c]=v.useState(),u=v.useCallback(f=>{e.updateResource(cl(JSON.parse(f.resource))).then(()=>{var h;c(void 0),(h=i(`/${t}/${n}/details`))==null||h.catch(console.error),Oe({color:"green",message:"Success"})}).catch(h=>{Oe({color:"red",message:Ke(h),autoClose:!1})})},[e,t,n,i]);return r?s.jsxs(st,{children:[o&&s.jsx(Xr,{outcome:o}),s.jsxs(mt,{onSubmit:u,children:[s.jsx(Ac,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:Oi(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),s.jsx(je,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:s.jsx(Pe,{type:"submit",children:"OK"})})]})]}):null}function Zte(){const{resourceType:e,id:t}=Ht();return Wt({reference:e+"/"+t})?s.jsxs(st,{children:[s.jsxs(Za,{icon:s.jsx(al,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",s.jsx("br",{}),s.jsx(Pt,{href:`/forms/${t}`,children:`/forms/${t}`})]}),s.jsx(mk,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function Jte(){const e=Ae(),{resourceType:t,id:n}=Ht(),[r,i]=v.useState(),[o,c]=v.useState();return v.useEffect(()=>{e.readResource(t,n).then(u=>i(Wr(u))).catch(u=>{Oe({color:"red",message:Ke(u)})})},[e,t,n]),r?s.jsxs(st,{children:[s.jsxs(Ie,{order:2,children:["Available ",t," profiles"]}),s.jsx(qe,{children:s.jsxs(s.Fragment,{children:[s.jsx(oP,{resource:r,currentProfile:o,onChange:c}),o?s.jsx(ene,{profile:o,resource:r,onResourceUpdated:u=>i(u)},o.url):s.jsx(_e,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const ene=({profile:e,resource:t,onResourceUpdated:n})=>{const r=Ae(),[i,o]=v.useState(),[c,u]=v.useState(()=>{var h,m;return(m=(h=t.meta)==null?void 0:h.profile)==null?void 0:m.includes(e.url)}),f=v.useCallback(h=>{o(void 0);const m=cl(h);c?PD(m,e.url):mU(m,e.url),r.updateResource(m).then(g=>{n(g),Oe({color:"green",message:"Success"})}).catch(g=>{o(Kt(g)),Oe({color:"red",message:Ke(g),autoClose:!1})})},[r,e.url,n,c]);return s.jsxs(qe,{children:[s.jsx(Sd,{size:"md",checked:c,label:`Conform resource to ${e.title}`,onChange:h=>u(h.currentTarget.checked),"data-testid":"profile-toggle"}),c?s.jsx(Zh,{profileUrl:e.url,defaultValue:t,onSubmit:f,outcome:i}):s.jsx("form",{noValidate:!0,onSubmit:h=>{h.preventDefault(),f(t)},children:s.jsx(je,{justify:"flex-end",mt:"xl",children:s.jsx(Pe,{type:"submit",children:"OK"})})})]})},lP={"Create Only":"create","Update Only":"update","Delete Only":"delete","All Interactions":void 0},tne=Object.keys(lP);function nne(){const e=Ae(),{id:t}=Ht(),n=Wt({reference:`Questionnaire/${t}`}),[r,i]=v.useState(),[o,c]=v.useState("create"),[u,f]=v.useState(0),h=e.searchResources("Subscription","status=active&_count=100").read().filter(g=>rne(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},${Mt(n)}`:Mt(n)}`,channel:{type:"rest-hook",endpoint:Mt(r)},...o?{extension:[{url:"https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction",valueCode:o}]}:void 0}).then(()=>{i(void 0),f(Date.now()),e.invalidateSearches("Subscription"),Oe({color:"green",message:"Success"})}).catch(g=>Oe({color:"red",message:Ke(g),autoClose:!1}))}return s.jsxs(st,{children:[s.jsx(Ie,{children:"Bots"}),s.jsxs(qe,{children:[h.length===0&&s.jsx("p",{children:"No bots found."}),h.map(g=>{var y;return s.jsxs("div",{children:[s.jsx("h3",{children:s.jsx(Ic,{value:{reference:(y=g.channel)==null?void 0:y.endpoint},link:!0})}),s.jsxs("p",{children:["Criteria: ",g.criteria]})]},g.id)})]}),s.jsx(Cn,{}),s.jsxs(qe,{mt:10,children:[s.jsx(fd,{size:"lg",htmlFor:"bot",children:"Connect to bot"}),s.jsxs(je,{children:[s.jsx(ol,{name:"bot",resourceType:"Bot",onChange:g=>i(g)}),s.jsx(Pe,{onClick:m,children:"Connect"})]}),s.jsx(je,{children:s.jsx(sn,{name:"subscription-trigger-event",defaultValue:"Create Only",label:"Subscription Trigger Event",data:tne,onChange:g=>c(lP[g.target.value])})})]}),s.jsx("div",{style:{display:"none"},children:u})]})}function rne(e,t){var i;if(!t)return!1;const n=e.criteria||"",r=((i=e.channel)==null?void 0:i.endpoint)||"";return n.startsWith("QuestionnaireResponse?")&&r.startsWith("Bot/")&&(n.includes(Mt(t))||(t.url?n.includes(t.url):!1))}function ine(){const{id:e}=Ht(),t=Sn(),r=Ae().readReference({reference:`Questionnaire/${e}`}).read(),[i,o]=v.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:ue.EQUALS,value:r.url?`${r.url},Questionnaire/${e}`:`Questionnaire/${e}`}],fields:["id","_lastUpdated"]});return s.jsx(st,{children:s.jsx($c,{search:i,onClick:c=>{var u;return(u=t(`/${c.resource.resourceType}/${c.resource.id}`))==null?void 0:u.catch(console.error)},onChange:c=>o(c.definition),hideFilters:!0,hideToolbar:!0})})}function ane(){const e=Ae(),{resourceType:t,id:n}=Ht(),r=Wt({reference:t+"/"+n}),i=v.useCallback(o=>{e.updateResource(cl(o)).then(()=>{Oe({color:"green",message:"Success"})}).catch(c=>{Oe({color:"red",message:Ke(c),autoClose:!1})})},[e]);return r?s.jsx(st,{children:s.jsx(BX,{onSubmit:i,definition:r})}):null}function one(){const{resourceType:e,id:t}=Ht(),n=Wt({reference:e+"/"+t});return n?s.jsx(st,{children:e==="MeasureReport"?s.jsx(BY,{measureReport:n}):s.jsx(Ib,{value:n})}):null}const sne="_container_1ue98_1",lne="_entry_1ue98_14",cne="_active_1ue98_21",xy={container:sne,entry:lne,active:cne};function une(e){const t=Ae(),n=Wt(e.value),[r,i]=v.useState();return v.useEffect(()=>{if(!n)return;const o=o1(n);if(!o)return;const c="reference"in o?o.reference:Mt(o);t.search("ServiceRequest","subject="+c).then(u=>{const h=(u.entry??[]).map(m=>m.resource);ZA(h),h.reverse(),i(h)}).catch(u=>Oe({color:"red",message:Ke(u),autoClose:!1}))},[t,n]),r?s.jsx("div",{"data-testid":"quick-service-requests",className:xy.container,children:r.map(o=>{var c,u,f,h,m,g,y;return s.jsxs("div",{className:zt(xy.entry,{[xy.active]:o.id===(n==null?void 0:n.id)}),children:[s.jsx("p",{children:s.jsx(gt,{to:o,children:dne(o)})}),((u=(c=o.category)==null?void 0:c[0])==null?void 0:u.text)&&s.jsx("p",{children:(f=o.category[0])==null?void 0:f.text}),((g=(m=(h=o.code)==null?void 0:h.coding)==null?void 0:m[0])==null?void 0:g.code)&&s.jsx("p",{children:(y=o.code.coding[0])==null?void 0:y.code}),s.jsx("p",{children:fne(o)})]},o.id)})}):null}function dne(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function fne(e){var t;return e.authoredOn?e.authoredOn.substring(0,10):(t=e.meta)!=null&&t.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const hne="_container_1l2dh_1",pne={container:hne};function mne(e){var i,o,c,u;const t=Wt(e.valueSet);if(!t)return null;const n=[""],r=(u=(c=(o=(i=t.compose)==null?void 0:i.include)==null?void 0:o[0])==null?void 0:c.concept)==null?void 0:u.map(f=>f.code);return r&&n.push(...r),e.defaultValue&&!n.includes(e.defaultValue)&&n.push(e.defaultValue),s.jsx("div",{className:pne.container,children:s.jsx(sn,{defaultValue:e.defaultValue,onChange:f=>e.onChange(f.currentTarget.value),data:n})})}function gne(e){var n,r;const t=Wt(e.specimen);return t?s.jsxs(pt,{children:[s.jsxs(pt.Entry,{children:[s.jsx(pt.Key,{children:"Type"}),s.jsx(pt.Value,{children:"Specimen"})]}),s.jsxs(pt.Entry,{children:[s.jsx(pt.Key,{children:"Collected"}),s.jsx(pt.Value,{children:gr((n=t.collection)==null?void 0:n.collectedDateTime)})]}),s.jsxs(pt.Entry,{children:[s.jsx(pt.Key,{children:"Specimen Age"}),s.jsx(pt.Value,{children:vne(t)})]}),(r=t.collection)!=null&&r.collectedDateTime&&t.receivedTime?s.jsxs(pt.Entry,{children:[s.jsx(pt.Key,{children:"Specimen Stability"}),s.jsx(pt.Value,{children:yne(t)})]}):s.jsx(s.Fragment,{})]}):null}function vne(e){var i;const t=(i=e.collection)==null?void 0:i.collectedDateTime;if(!t)return;const n=new Date(t);return cP(uP(n,new Date))}function yne(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 cP(uP(t,n))}function cP(e){return e.toString().padStart(3,"0")+"D"}function uP(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function xne(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 bne(){var _,E,R,D,k,M,L;const e=Ae(),{resourceType:t,id:n}=Ht(),r={reference:t+"/"+n},i=Sn(),[o,c]=v.useState(),u=Wt(r,c),f=xne(t),[h,m]=v.useState(()=>{const z=window.location.pathname.split("/").pop();return z&&f.map(F=>F.toLowerCase()).includes(z)?z:f[0].toLowerCase()});async function g(){var Y,W;const F=(W=(Y=(await e.readHistory(t,n)).entry)==null?void 0:Y.find(J=>!!J.resource))==null?void 0:W.resource;F?y(F):Oe({color:"red",message:"No history to restore",autoClose:!1})}function y(z){e.updateResource(cl(z)).then(()=>{c(void 0),Oe({color:"green",message:"Success"})}).catch(F=>{Oe({color:"red",message:Ke(F),autoClose:!1})})}if(o)return Ez(o)?s.jsxs(st,{children:[s.jsx(Ie,{children:"Deleted"}),s.jsx("p",{children:"The resource was deleted."}),s.jsx(Pe,{color:"red",onClick:g,children:"Restore"})]}):s.jsx(Xr,{outcome:o});function b(z){var F;z||(z=f[0].toLowerCase()),m(z),(F=i(`/${t}/${n}/${z}`))==null||F.catch(console.error)}function S(z){const F=u,Y=F.orderDetail||[];Y.length===0&&Y.push({}),Y[0].text!==z&&(Y[0].text=z,y({...F,orderDetail:Y}))}const j=u&&o1(u),C=u&&$ee(u),T=(R=(E=(_=e.getUserConfiguration())==null?void 0:_.option)==null?void 0:E.find(z=>z.id==="statusValueSet"))==null?void 0:R.valueString;return s.jsxs(s.Fragment,{children:[(u==null?void 0:u.resourceType)==="ServiceRequest"&&T&&s.jsx(mne,{valueSet:{reference:T},defaultValue:(k=(D=u.orderDetail)==null?void 0:D[0])==null?void 0:k.text,onChange:S},Mt(u)+"-"+((L=(M=u.orderDetail)==null?void 0:M[0])==null?void 0:L.text)),u&&s.jsx(une,{value:u}),u&&s.jsxs(lr,{children:[j&&s.jsx(ok,{patient:j}),C&&s.jsx(gne,{specimen:C}),t!=="Patient"&&s.jsx(Jk,{resource:r}),s.jsx(Yr,{children:s.jsx(Rt,{value:h.toLowerCase(),onChange:b,children:s.jsx(Rt.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:f.map(z=>s.jsx(Rt.Tab,{value:z.toLowerCase(),children:z},z))})})})]}),s.jsx(Jb,{})]})}function nR(){var T,_,E,R;const e=Sn(),{resourceType:t,id:n,versionId:r,tab:i}=Ht(),o=Ae(),[c,u]=v.useState(!0),[f,h]=v.useState(),[m,g]=v.useState();if(v.useEffect(()=>{g(void 0),u(!0),o.readHistory(t,n).then(D=>h(D)).then(()=>u(!1)).catch(D=>{g(D),u(!1)})},[o,t,n]),c)return s.jsx(gi,{});if(!f)return s.jsxs(st,{children:[s.jsx(Ie,{children:"Resource not found"}),s.jsx(gt,{to:`/${t}`,children:"Return to search page"})]});const y=f.entry??[],b=y.findIndex(D=>{var k,M;return((M=(k=D.resource)==null?void 0:k.meta)==null?void 0:M.versionId)===r});if(b===-1)return s.jsxs(st,{children:[s.jsx(Ie,{children:"Version not found"}),s.jsx(gt,{to:`/${t}/${n}`,children:"Return to resource"})]});const S=y[b].resource,j=b<y.length-1?y[b+1].resource:void 0,C="diff";return s.jsxs(Rt,{value:i||C,onChange:D=>{var k;return(k=e(`/${t}/${n}/_history/${r}/${D||C}`))==null?void 0:k.catch(console.error)},children:[s.jsxs(lr,{children:[s.jsx(Lc,{fluid:!0,p:"md",children:s.jsx(_e,{children:`${t} ${n}`})}),s.jsxs(Rt.List,{children:[s.jsx(Rt.Tab,{value:"diff",children:"Diff"}),s.jsx(Rt.Tab,{value:"raw",children:"Raw"})]})]}),s.jsxs(st,{children:[m&&s.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)}),s.jsx(Rt.Panel,{value:"diff",children:j?s.jsxs(s.Fragment,{children:[s.jsxs("ul",{children:[s.jsxs("li",{children:["Current: ",(T=S.meta)==null?void 0:T.versionId]}),s.jsxs("li",{children:["Previous:"," ",s.jsx(gt,{to:`/${t}/${n}/_history/${(_=j.meta)==null?void 0:_.versionId}`,children:(E=j.meta)==null?void 0:E.versionId})]})]}),s.jsx(gK,{original:j,revised:S})]}):s.jsxs(s.Fragment,{children:[s.jsxs("ul",{children:[s.jsxs("li",{children:["Current: ",(R=S.meta)==null?void 0:R.versionId]}),s.jsx("li",{children:"Previous: (none)"})]}),s.jsx("pre",{children:JSON.stringify(S,void 0,2)})]})}),s.jsx(Rt.Panel,{value:"raw",children:s.jsx("pre",{children:JSON.stringify(S,void 0,2)})})]})]})}function Sne(){const{resourceType:e,id:t}=Ht(),n=Sn(),[r,i]=v.useState({resourceType:"Subscription",filters:[{code:"url",operator:ue.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return s.jsx(st,{children:s.jsx(EY,{search:r,onClick:o=>{var c;return(c=n(`/${o.resource.resourceType}/${o.resource.id}`))==null?void 0:c.catch(console.error)},onChange:o=>i(o.definition),hideFilters:!0})})}function wne(e){const t=Ae(),{resource:n,opened:r,onClose:i}=e,[o,c]=v.useState(!1),[u,f]=v.useState(),[h,m]=v.useState(!1),g=v.useCallback(async()=>{if(n!=null&&n.id)try{await t.post(t.fhirUrl(n.resourceType,n.id,"$resend"),{subscription:o&&u?Mt(u):void 0,verbose:h}),Oe({color:"green",message:"Done"}),i()}catch(y){Oe({color:"red",message:Ke(y),autoClose:!1})}},[t,n,i,o,u,h]);return s.jsx(Vn,{opened:r,onClose:i,title:"Resend Subscriptions",children:s.jsx(mt,{onSubmit:g,children:s.jsxs(qe,{children:[s.jsx(Un,{label:"Choose subscription (all subscriptions by default)",onChange:y=>c(y.currentTarget.checked)}),o&&s.jsx(ol,{name:"subscription",resourceType:"Subscription",placeholder:"Subscription",onChange:f}),s.jsx(Un,{label:"Verbose mode",onChange:y=>m(y.currentTarget.checked)}),s.jsx(je,{justify:"flex-end",children:s.jsx(Pe,{type:"submit",children:"Resend"})})]})})})}function rR(){const e=Ae(),t=rm(),{resourceType:n,id:r}=Ht(),i={reference:n+"/"+r},[o,c]=v.useState(),u=lp(!1);function f(_,E){return e.updateResource({..._,priority:E})}function h(_,E){f(_,"stat").then(E).catch(console.error)}function m(_,E){f(_,"routine").then(E).catch(console.error)}function g(_){t(`/${_.resourceType}/${_.id}`)}function y(_){t(`/${_.resourceType}/${_.id}/edit`)}function b(_){t(`/${_.resourceType}/${_.id}/delete`)}function S(_){c(_),u[1].open()}function j(_){var E;t(`/${_.resourceType}/${_.id}/_history/${(E=_.meta)==null?void 0:E.versionId}`)}function C(_,E){const R="aws-textract";Oe({id:R,title:"AWS Textract in Progress",message:"Extracting text... This may take a moment...",loading:!0,autoClose:!1}),e.post(e.fhirUrl(_.resourceType,_.id,"$aws-textract"),{}).then(()=>{E(),As({id:R,title:"AWS Textract Successful",message:"Text successfully extracted.",color:"green",icon:s.jsx(ro,{size:"1rem"}),loading:!1,withCloseButton:!0})}).catch(D=>As({id:R,title:"AWS Textract Error",color:"red",message:Ke(D),icon:s.jsx(Gs,{size:"1rem"}),loading:!1,withCloseButton:!0}))}function T(_){var P;const{primaryResource:E,currentResource:R,reloadTimeline:D}=_,k=R.resourceType===E.resourceType&&R.id===E.id,M=R.resourceType==="Communication"&&R.priority!=="stat",L=R.resourceType==="Communication"&&R.priority==="stat",z=k,F=!k,Y=!k,W=!k,J=(P=e.getProjectMembership())==null?void 0:P.admin,G=J,X=Xee()&&(R.resourceType==="DocumentReference"||R.resourceType==="Media");return s.jsxs(Ce.Dropdown,{children:[s.jsx(Ce.Label,{children:"Resource"}),M&&s.jsx(Ce.Item,{leftSection:s.jsx(qH,{size:14}),onClick:()=>h(R,D),"aria-label":`Pin ${Mt(R)}`,children:"Pin"}),L&&s.jsx(Ce.Item,{leftSection:s.jsx(WH,{size:14}),onClick:()=>m(R,D),"aria-label":`Unpin ${Mt(R)}`,children:"Unpin"}),F&&s.jsx(Ce.Item,{leftSection:s.jsx(UE,{size:14}),onClick:()=>g(R),"aria-label":`Details ${Mt(R)}`,children:"Details"}),z&&s.jsx(Ce.Item,{leftSection:s.jsx(UE,{size:14}),onClick:()=>j(R),"aria-label":`Details ${Mt(R)}`,children:"Details"}),Y&&s.jsx(Ce.Item,{leftSection:s.jsx(pA,{size:14}),onClick:()=>y(R),"aria-label":`Edit ${Mt(R)}`,children:"Edit"}),J&&s.jsxs(s.Fragment,{children:[s.jsx(Ce.Divider,{}),s.jsx(Ce.Label,{children:"Admin"}),G&&s.jsx(Ce.Item,{leftSection:s.jsx(tq,{size:14}),onClick:()=>S(R),"aria-label":`Resend Subscriptions ${Mt(R)}`,children:"Resend Subscriptions"})]}),X&&s.jsxs(s.Fragment,{children:[s.jsx(Ce.Divider,{}),s.jsx(Ce.Label,{children:"AWS AI"}),s.jsx(Ce.Item,{leftSection:s.jsx(bq,{size:14}),onClick:()=>C(R,D),"aria-label":`AWS Textract ${Mt(R)}`,children:"AWS Textract"})]}),W&&s.jsxs(s.Fragment,{children:[s.jsx(Ce.Divider,{}),s.jsx(Ce.Label,{children:"Danger zone"}),s.jsx(Ce.Item,{color:"red",leftSection:s.jsx(am,{size:14}),onClick:()=>b(R),"aria-label":`Delete ${Mt(R)}`,children:"Delete"})]})]})}return s.jsxs(s.Fragment,{children:[n==="Encounter"&&s.jsx(NQ,{encounter:i,getMenu:T}),n==="Patient"&&s.jsx(GY,{patient:i,getMenu:T}),n==="ServiceRequest"&&s.jsx(jK,{serviceRequest:i,getMenu:T}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&s.jsx(PQ,{resource:i,getMenu:T}),s.jsx(wne,{resource:o,opened:u[0],onClose:u[1].close},`resend-subscriptions-${o==null?void 0:o.id}`)]})}function jne(e){const{opened:t,close:n,version:r,loadingStatus:i,handleStatus:o,handleUpgrade:c}=e,[u,f]=v.useState(),[h,m]=v.useState(!1);return v.useEffect(()=>{t&&(u||GV("app-tools-page").then(f).catch(console.error),o())},[t,u,o]),u&&r&&!i?r==="unknown"?s.jsx("p",{children:"Unable to determine the current version of the agent. Check the network connectivity of the agent."}):r.startsWith(u)?s.jsxs("p",{children:["This agent is already on the latest version (",u,")."]}):s.jsxs(s.Fragment,{children:[s.jsxs("p",{children:["Are you sure you want to upgrade this agent from version ",r," to version ",u,"?"]}),s.jsxs(je,{children:[s.jsx(Pe,{onClick:()=>{c(h),n()},"aria-label":"Confirm upgrade",children:"Confirm Upgrade"}),s.jsx(Un,{label:"Force",onChange:g=>m(g.currentTarget.checked)})]})]}):s.jsx(gi,{})}function Cne(){const e=Ae(),{id:t}=Ht(),n=v.useMemo(()=>({reference:"Agent/"+t}),[t]),[r,i]=v.useState(!1),[o,c]=v.useState(!1),[u,f]=v.useState(!1),[h,m]=v.useState(),[g,y]=v.useState(),[b,S]=v.useState(),[j,C]=v.useState(),[T,_]=v.useState(!1),[E,R]=v.useState(!1),[D,{open:k,close:M}]=lp(!1);v.useEffect(()=>{if(r||o||u||T){R(!0);return}R(!1)},[r,o,u,T]);const L=v.useCallback(()=>{i(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(G=>{var X,P,I,$,H,O;m((P=(X=G.parameter)==null?void 0:X.find(U=>U.name==="status"))==null?void 0:P.valueCode),y(($=(I=G.parameter)==null?void 0:I.find(U=>U.name==="version"))==null?void 0:$.valueString),S((O=(H=G.parameter)==null?void 0:H.find(U=>U.name==="lastUpdated"))==null?void 0:O.valueInstant)}).catch(G=>J(Ke(G))).finally(()=>i(!1))},[e,t]),z=v.useCallback(G=>{const X=G.host,P=G.pingCount||1;X&&(_(!0),e.pushToAgent(n,X,`PING ${P}`,fn.PING,!0).then(I=>C(I)).catch(I=>J(Ke(I))).finally(()=>_(!1)))},[e,n]),F=v.useCallback(()=>{c(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(G=>{W("Agent config reloaded successfully.")}).catch(G=>J(Ke(G))).finally(()=>c(!1))},[e,t]),Y=v.useCallback(G=>{f(!0),e.get(e.fhirUrl("Agent",t,"$upgrade",`?force=${G}`),{cache:"reload"}).then(X=>{W("Agent upgraded successfully.")}).catch(X=>J(Ke(X))).finally(()=>f(!1))},[e,t]);function W(G){Oe({color:"green",title:"Success",icon:s.jsx(ro,{size:"1rem"}),message:G})}function J(G){Oe({color:"red",title:"Error",message:G,autoClose:!1})}return s.jsxs(st,{children:[s.jsx(Vn,{opened:D,onClose:M,title:"Upgrade Agent",centered:!0,children:s.jsx(jne,{opened:D,close:M,version:g,loadingStatus:r,handleStatus:L,handleUpgrade:Y})}),s.jsx(Ie,{order:1,children:"Agent Tools"}),s.jsxs("div",{style:{marginBottom:10},children:["Agent: ",s.jsx(Ic,{value:n,link:!0})]}),s.jsx(Cn,{my:"lg"}),s.jsx(Ie,{order:2,children:"Agent Status"}),s.jsx("p",{children:"Retrieve the status of the agent. This tests whether the agent is connected to the Medplum server, and the last time it was able to communicate."}),s.jsx(Pe,{onClick:L,loading:r,disabled:E&&!r,children:"Get Status"}),!r&&h&&s.jsx(ye,{children:s.jsxs(ye.Tbody,{children:[s.jsxs(ye.Tr,{children:[s.jsx(ye.Td,{children:"Status"}),s.jsx(ye.Td,{children:s.jsx(um,{status:h})})]}),s.jsxs(ye.Tr,{children:[s.jsx(ye.Td,{children:"Version"}),s.jsx(ye.Td,{children:g})]}),s.jsxs(ye.Tr,{children:[s.jsx(ye.Td,{children:"Last Updated"}),s.jsx(ye.Td,{children:gr(b,void 0,{timeZoneName:"longOffset"})})]})]})}),s.jsx(Cn,{my:"lg"}),s.jsx(Ie,{order:2,children:"Reload Config"}),s.jsx("p",{children:"Reload the configuration of this agent, syncing it with the current version of the Agent resource on the Medplum server."}),s.jsx(Pe,{onClick:F,loading:o,disabled:E&&!o,"aria-label":"Reload config",children:"Reload Config"}),s.jsx(Cn,{my:"lg"}),s.jsx(Ie,{order:2,children:"Upgrade Agent"}),s.jsx("p",{children:"Upgrade the version of this agent, to either the latest (default) or a specified version."}),s.jsx(Pe,{onClick:k,loading:u,disabled:E&&!u,"aria-label":"Upgrade agent",children:"Upgrade"}),s.jsx(Cn,{my:"lg"}),s.jsx(Ie,{order:2,children:"Ping from Agent"}),s.jsx("p",{children:"Send a ping command from the agent to a valid IP address or hostname. Use this tool to troubleshoot local network connectivity."}),s.jsx(mt,{onSubmit:z,children:s.jsxs(je,{children:[s.jsx($e,{id:"host",name:"host",placeholder:"ex. 127.0.0.1",label:"IP Address / Hostname",rightSection:s.jsx(An,{size:24,radius:"xl",variant:"filled",type:"submit","aria-label":"Ping",loading:T,disabled:E&&!T,children:s.jsx(aq,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),s.jsx($p,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!T&&j&&s.jsxs(s.Fragment,{children:[s.jsx(Ie,{order:5,mt:"sm",mb:0,children:"Last Ping"}),s.jsx("pre",{children:j})]})]})}function Ene(){return s.jsx(nJ,{children:s.jsxs(Ve,{errorElement:s.jsx(Iee,{}),children:[s.jsx(Ve,{path:"/signin",element:s.jsx(nte,{})}),s.jsx(Ve,{path:"/oauth",element:s.jsx(Kee,{})}),s.jsx(Ve,{path:"/resetpassword",element:s.jsx(Jee,{})}),s.jsx(Ve,{path:"/setpassword/:id/:secret",element:s.jsx(tte,{})}),s.jsx(Ve,{path:"/register",element:s.jsx(Zee,{})}),s.jsx(Ve,{path:"/changepassword",element:s.jsx(Oee,{})}),s.jsx(Ve,{path:"/security",element:s.jsx(ete,{})}),s.jsx(Ve,{path:"/mfa",element:s.jsx(Yee,{})}),s.jsx(Ve,{path:"/batch",element:s.jsx(Pee,{})}),s.jsx(Ve,{path:"/bulk/:resourceType",element:s.jsx(Nee,{})}),s.jsx(Ve,{path:"/smart",element:s.jsx(rte,{})}),s.jsx(Ve,{path:"/forms/:id",element:s.jsx(zee,{})}),s.jsx(Ve,{path:"/admin/super",element:s.jsx(wte,{})}),s.jsx(Ve,{path:"/admin/super/asyncjob",element:s.jsx(gte,{})}),s.jsx(Ve,{path:"/admin/config",element:s.jsx(fte,{})}),s.jsxs(Ve,{path:"/admin",element:s.jsx(hte,{}),children:[s.jsx(Ve,{path:"patients",element:s.jsx(dte,{})}),s.jsx(Ve,{path:"bots/new",element:s.jsx(ote,{})}),s.jsx(Ve,{path:"bots",element:s.jsx(ite,{})}),s.jsx(Ve,{path:"clients/new",element:s.jsx(ste,{})}),s.jsx(Ve,{path:"clients",element:s.jsx(ate,{})}),s.jsx(Ve,{path:"details",element:s.jsx(XT,{})}),s.jsx(Ve,{path:"invite",element:s.jsx(ute,{})}),s.jsx(Ve,{path:"users",element:s.jsx(Cte,{})}),s.jsx(Ve,{path:"project",element:s.jsx(XT,{})}),s.jsx(Ve,{path:"secrets",element:s.jsx(pte,{})}),s.jsx(Ve,{path:"sites",element:s.jsx(mte,{})}),s.jsx(Ve,{path:"members/:membershipId",element:s.jsx(cte,{})})]}),s.jsx(Ve,{path:"/lab/assays",element:s.jsx(Ete,{})}),s.jsx(Ve,{path:"/lab/panels",element:s.jsx(Tte,{})}),s.jsx(Ve,{path:"/:resourceType/:id/_history/:versionId/:tab",element:s.jsx(nR,{})}),s.jsx(Ve,{path:"/:resourceType/:id/_history/:versionId",element:s.jsx(nR,{})}),s.jsxs(Ve,{path:"/:resourceType/new",element:s.jsx(Lee,{}),children:[s.jsx(Ve,{index:!0,element:s.jsx(yy,{})}),s.jsx(Ve,{path:"form",element:s.jsx(yy,{})}),s.jsx(Ve,{path:"json",element:s.jsx(Xte,{})}),s.jsx(Ve,{path:"profiles",element:s.jsx(yy,{})})]}),s.jsxs(Ve,{path:"/:resourceType/:id",element:s.jsx(bne,{}),children:[s.jsx(Ve,{index:!0,element:s.jsx(rR,{})}),s.jsx(Ve,{path:"apply",element:s.jsx(_te,{})}),s.jsx(Ve,{path:"apps",element:s.jsx(Dte,{})}),s.jsx(Ve,{path:"event",element:s.jsx(kte,{})}),s.jsx(Ve,{path:"blame",element:s.jsx(Pte,{})}),s.jsx(Ve,{path:"bots",element:s.jsx(nne,{})}),s.jsx(Ve,{path:"builder",element:s.jsx(Bte,{})}),s.jsx(Ve,{path:"checklist",element:s.jsx(Vte,{})}),s.jsx(Ve,{path:"delete",element:s.jsx(Fte,{})}),s.jsx(Ve,{path:"details",element:s.jsx(Gte,{})}),s.jsx(Ve,{path:"edit",element:s.jsx(Wte,{})}),s.jsx(Ve,{path:"editor",element:s.jsx(zte,{})}),s.jsx(Ve,{path:"history",element:s.jsx(Yte,{})}),s.jsx(Ve,{path:"json",element:s.jsx(Kte,{})}),s.jsx(Ve,{path:"preview",element:s.jsx(Zte,{})}),s.jsx(Ve,{path:"responses",element:s.jsx(ine,{})}),s.jsx(Ve,{path:"report",element:s.jsx(one,{})}),s.jsx(Ve,{path:"ranges",element:s.jsx(ane,{})}),s.jsx(Ve,{path:"subscriptions",element:s.jsx(Sne,{})}),s.jsx(Ve,{path:"timeline",element:s.jsx(rR,{})}),s.jsx(Ve,{path:"tools",element:s.jsx(Cne,{})}),s.jsx(Ve,{path:"profiles",element:s.jsx(Jte,{})}),s.jsx(Ve,{path:"export",element:s.jsx(Qte,{})})]}),s.jsx(Ve,{path:"/:resourceType",element:s.jsx(YT,{})}),s.jsx(Ve,{path:"/",element:s.jsx(YT,{})})]})})}function Tne(){const e=Ae(),t=e.getUserConfiguration(),n=Or(),[r]=n1();return e.isLoading()?s.jsx(gi,{}):s.jsx(xG,{logo:s.jsx(zi,{size:24}),pathname:n.pathname,searchParams:r,version:YD,menus:Rne(t),displayAddBookmark:!!(t!=null&&t.id),children:s.jsx(v.Suspense,{fallback:s.jsx(gi,{}),children:s.jsx(Ene,{})})})}function Rne(e){var n;const t=((n=e==null?void 0:e.menu)==null?void 0:n.map(r=>{var i;return{title:r.title,links:((i=r.link)==null?void 0:i.map(o=>({label:o.name,href:o.target,icon:_ne(o.target)})))||[]}}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:s.jsx(kH,{})}]}),t}const iR={Patient:pq,Practitioner:TH,Organization:YF,ServiceRequest:ZH,DiagnosticReport:rq,Questionnaire:CH,admin:FF,AccessPolicy:DH,Subscription:Cq,batch:FH,Observation:zH};function _ne(e){try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in iR){const n=iR[t];return s.jsx(n,{})}}catch{}return s.jsx(Gp,{w:30})}async function Dne(){const e=$d(),t=new XD({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=TJ([{path:"*",element:s.jsx(Tne,{})}]),i=c=>r.navigate(c);DK.createRoot(document.getElementById("root")).render(s.jsx(v.StrictMode,{children:s.jsx(WV,{medplum:t,navigate:i,children:s.jsxs(DR,{theme:n,children:[s.jsx(to,{position:"bottom-right"}),s.jsx(ZZ,{router:r})]})})}))}Dne().catch(console.error);
|
|
589
|
-
//# sourceMappingURL=index-
|
|
589
|
+
//# sourceMappingURL=index-BMbYVdkq.js.map
|