@medplum/app 4.3.4 → 4.3.5
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 g3(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 oc={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let RE=!1;function lV(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");oc.Event=globalThis.Event,oc.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},oc.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 _E=!1;class Io extends tm{constructor(t,n,r={}){RE||(lV(),RE=!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 Io.CONNECTING}get OPEN(){return Io.OPEN}get CLOSING(){return Io.CLOSING}get CLOSED(){return Io.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?Io.CLOSED:Io.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"&&!_E&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),_E=!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 oc.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new oc.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new oc.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 Fy extends tm{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 Fy(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 KD))throw new dt(yn("First arg of constructor should be a `MedplumClient`"));let i;try{i=new URL(n).toString()}catch{throw new dt(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 Io(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 Fy,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 w=this.criteriaEntriesBySubscriptionId.get(b);if(!w){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}w.connecting=!1,w.emitter.dispatchEvent({...S});return}(u=this.masterSubEmitter)==null||u.dispatchEvent({type:"message",payload:m});const v=this.criteriaEntriesBySubscriptionId.get(Vs(g.subscription));if(!v){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}v.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 dt(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 ${zt(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:t.criteria})).id);const{parameter:r}=await this.medplum.get(`fhir/R4/Subscription/${n}/$get-ws-binding-token`),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 dt(yn("Failed to get token"));if(!o)throw new dt(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(la(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!la(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(Ye(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 Fy(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const XD="4.3.4-0636480b8",hV=hn.FHIR_JSON+", */*; q=0.1",pV="https://api.medplum.com/",mV=1e3,gV=6e4,vV=0,yV=3e5,xV="Binary/",DE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},Zl={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 KD extends tm{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=ob((t==null?void 0:t.baseUrl)??pV),this.fhirBaseUrl=Zi(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=Zi(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=Zi(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=Zi(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),this.fhircastHubUrl=Zi(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 uD((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=Zi(this.fhirBaseUrl,t);if(this.requestCache)for(const r of this.requestCache.keys())(r.endsWith(n)||r.includes(n+"?"))&&this.requestCache.delete(r)}get(t,n={}){t=t.toString();const r=this.getCacheEntry(t,n);if(r)return r.value;let 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 Di(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,hn.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:Zl.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(Zi(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=gU(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 Di(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 Di(this.search(t,n,r).then(PE));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 PE(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 DE;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 Di(Promise.reject(new Error("Missing reference")));if(r==="system")return new Di(Promise.resolve(DE));const[i,o]=r.split("/");return!i||!o?new Di(Promise.reject(new Error("Invalid reference"))):this.readResource(i,o,n)}requestSchema(t){if(vD(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const i=new Di((async()=>{const o=`{
|
|
86
|
+
*/const oc={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let RE=!1;function lV(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");oc.Event=globalThis.Event,oc.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},oc.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 _E=!1;class Io extends tm{constructor(t,n,r={}){RE||(lV(),RE=!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 Io.CONNECTING}get OPEN(){return Io.OPEN}get CLOSING(){return Io.CLOSING}get CLOSED(){return Io.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?Io.CLOSED:Io.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"&&!_E&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),_E=!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 oc.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new oc.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new oc.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 Fy extends tm{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 Fy(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 KD))throw new dt(yn("First arg of constructor should be a `MedplumClient`"));let i;try{i=new URL(n).toString()}catch{throw new dt(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 Io(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 Fy,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 w=this.criteriaEntriesBySubscriptionId.get(b);if(!w){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}w.connecting=!1,w.emitter.dispatchEvent({...S});return}(u=this.masterSubEmitter)==null||u.dispatchEvent({type:"message",payload:m});const v=this.criteriaEntriesBySubscriptionId.get(Vs(g.subscription));if(!v){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}v.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 dt(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 ${zt(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:t.criteria})).id);const{parameter:r}=await this.medplum.get(`fhir/R4/Subscription/${n}/$get-ws-binding-token`),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 dt(yn("Failed to get token"));if(!o)throw new dt(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(la(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!la(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(Ye(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 Fy(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const XD="4.3.5-be2f2f517",hV=hn.FHIR_JSON+", */*; q=0.1",pV="https://api.medplum.com/",mV=1e3,gV=6e4,vV=0,yV=3e5,xV="Binary/",DE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},Zl={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 KD extends tm{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=ob((t==null?void 0:t.baseUrl)??pV),this.fhirBaseUrl=Zi(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=Zi(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=Zi(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=Zi(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),this.fhircastHubUrl=Zi(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 uD((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=Zi(this.fhirBaseUrl,t);if(this.requestCache)for(const r of this.requestCache.keys())(r.endsWith(n)||r.includes(n+"?"))&&this.requestCache.delete(r)}get(t,n={}){t=t.toString();const r=this.getCacheEntry(t,n);if(r)return r.value;let 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 Di(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,hn.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:Zl.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(Zi(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=gU(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 Di(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 Di(this.search(t,n,r).then(PE));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 PE(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 DE;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 Di(Promise.reject(new Error("Missing reference")));if(r==="system")return new Di(Promise.resolve(DE));const[i,o]=r.split("/");return!i||!o?new Di(Promise.reject(new Error("Invalid reference"))):this.readResource(i,o,n)}requestSchema(t){if(vD(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const i=new Di((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
|
}`,xee="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 bee(){const e=Ae(),{id:t}=qt(),[n,r]=y.useState(),[i,o]=y.useState(),[c,u]=y.useState(yee),[f,h]=y.useState(xee),[m,g]=y.useState(hn.FHIR_JSON),v=y.useRef(null),b=y.useRef(null),[S,w]=y.useState(!1);y.useEffect(()=>{e.readResource("Bot",t).then(async k=>{r(k),o(await See(e,k))}).catch(k=>Oe({color:"red",message:Ye(k),autoClose:!1}))},[e,t]);const C=y.useCallback(async()=>Xu(v.current,{command:"getValue"}),[]),E=y.useCallback(async()=>Xu(v.current,{command:"getOutput"}),[]),_=y.useCallback(async()=>m===hn.FHIR_JSON?JSON.parse(c):f,[m,c,f]),T=y.useCallback(async k=>{k.preventDefault(),k.stopPropagation(),w(!0);try{const M=await C(),I=await E(),z=await e.createAttachment({data:M,filename:"index.ts",contentType:"text/typescript"}),V=await e.createAttachment({data:I,filename:"index.js",contentType:"text/typescript"}),Y=[{op:"add",path:"/sourceCode",value:z},{op:"add",path:"/executableCode",value:V}];await e.patchResource("Bot",t,Y),Oe({color:"green",message:"Saved"})}catch(M){Oe({color:"red",message:Ye(M),autoClose:!1})}finally{w(!1)}},[e,t,C,E]),R=y.useCallback(async k=>{k.preventDefault(),k.stopPropagation(),w(!0);try{await e.post(e.fhirUrl("Bot",t,"$deploy")),Oe({color:"green",message:"Deployed"})}catch(M){Oe({color:"red",message:Ye(M),autoClose:!1})}finally{w(!1)}},[e,t]),D=y.useCallback(async k=>{k.preventDefault(),k.stopPropagation(),w(!0);try{const M=await _(),I=await e.post(e.fhirUrl("Bot",t,"$execute"),M,m);await Xu(b.current,{command:"setValue",value:I}),Oe({color:"green",message:"Success"})}catch(M){Oe({color:"red",message:Ye(M),autoClose:!1})}finally{w(!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(vee,{iframeRef:v,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:T,loading:S,leftSection:s.jsx(MF,{size:"1rem"}),children:"Save"}),s.jsx(Pe,{type:"button",onClick:R,loading:S,leftSection:s.jsx(Cb,{size:"1rem"}),children:"Deploy"}),s.jsx(Pe,{type:"button",onClick:D,loading:S,leftSection:s.jsx(XF,{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(ln,{data:[{label:"FHIR",value:hn.FHIR_JSON},{label:"HL7",value:hn.HL7_V2}],onChange:k=>g(k.currentTarget.value)}),m===hn.FHIR_JSON?s.jsx(Dc,{value:c,onChange:k=>u(k),autosize:!0,minRows:15}):s.jsx("textarea",{className:mee.hl7Input,value:f,onChange:k=>h(k.currentTarget.value),rows:15})]}),s.jsx(lr,{m:2,p:"xs",shadow:"md",children:s.jsx(gee,{iframeRef:b,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function See(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 ll(e){let t=e.meta;return t&&(t={...t,lastUpdated:void 0,versionId:void 0,author:void 0}),{...e,meta:t}}function wee(){const e=Ae(),{resourceType:t,id:n}=qt(),r={reference:t+"/"+n},i=y.useCallback(o=>{e.updateResource(ll(o)).then(()=>{Oe({color:"green",message:"Success"})}).catch(c=>{Oe({color:"red",message:Ye(c),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return s.jsx(ot,{children:s.jsx(AQ,{value:r,onSubmit:i})});case"Questionnaire":return s.jsx(ot,{children:s.jsx(iY,{questionnaire:r,onSubmit:i})});default:return null}}function jee(){const{resourceType:e,id:t}=qt(),n=Wt({reference:e+"/"+t}),r=wn();return n?s.jsx(ot,{children:s.jsx(AY,{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 Cee(){const e=Ae(),{resourceType:t,id:n}=qt(),r=wn();return s.jsxs(ot,{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:Ye(i),autoClose:!1}))},children:"Delete"})]})}const Eee="_selectProfileBtn_tbaz6_1",Tee="_chevron_tbaz6_13",iR={selectProfileBtn:Eee,chevron:Tee};function Ree(){var f,h;const{resourceType:e,id:t}=qt(),n=Wt({reference:e+"/"+t}),[r,i]=y.useState(),o=xd({onDropdownClose:()=>o.resetSelectedOption()}),c=y.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(y.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(v0,{fw:"bold",fs:"sm",className:iR.selectProfileBtn,children:[s.jsx("span",{children:"Pick profile"}),s.jsx(jb,{stroke:1.5,className:iR.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(ot,{children:s.jsxs(qe,{gap:"xl",children:[u,s.jsx(Ub,{value:n,profileUrl:r})]})})}function _ee(){const e=Ae(),{resourceType:t,id:n}=qt(),[r,i]=y.useState(),[o,c]=y.useState(),u=wn(),[f,h]=y.useState();y.useEffect(()=>{e.readResource(t,n).then(b=>{i(Wr(b)),c(Wr(b))}).catch(b=>{h(Zt(b)),Oe({color:"red",message:Ye(b),autoClose:!1})})},[e,t,n]);const m=y.useCallback(b=>{h(void 0),e.updateResource(ll(b)).then(()=>{var S;(S=u(`/${t}/${n}/details`))==null||S.catch(console.error),Oe({id:"succes",color:"green",message:"Success"})}).catch(S=>{h(Zt(S)),Oe({color:"red",message:Ye(S),autoClose:!1})})},[e,t,n,u]),g=y.useCallback(b=>{h(void 0);const S=KA.createPatch(r,b);e.patchResource(t,n,S).then(()=>{var w;(w=u(`/${t}/${n}/details`))==null||w.catch(console.error),Oe({id:"succes",color:"green",message:"Success"})}).catch(w=>{h(Zt(w)),Oe({color:"red",message:Ye(w),autoClose:!1})})},[e,t,n,r,u]),v=y.useCallback(()=>{var b;return(b=u(`/${t}/${n}/delete`))==null?void 0:b.catch(console.error)},[u,t,n]);return o?s.jsx(ot,{children:s.jsx(Jh,{defaultValue:o,onSubmit:m,onPatch:g,onDelete:v,outcome:f})}):null}function Dee(){const{resourceType:e,id:t}=qt(),n=Wt({reference:e+"/"+t});return n?s.jsx(ot,{maw:700,children:n.resourceType==="Patient"?s.jsx(CQ,{patient:n}):s.jsx(Ka,{icon:s.jsx(il,{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]=y.useState();return y.useEffect(()=>{i.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(u=>{c(u.filter(qq))}).catch(console.error)},[i,n,r]),s.jsx(Tt,{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(Tt.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(Tt.Tab,{value:u.url,title:h,rightSection:f&&s.jsx(K0,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:s.jsx(lH,{size:"90%"})}),children:u.title||u.name},u.url)})})})}function sP(e,t){const n=Ae(),r=wn();return{defaultValue:{resourceType:e},handleSubmit:c=>{t&&t(void 0),n.createResource(c).then(u=>r("/"+u.resourceType+"/"+u.id)).catch(u=>{t&&t(Zt(u)),Oe({color:"red",message:Ye(u),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function yy(){const{resourceType:e}=qt(),t=Mr(),[n,r]=y.useState(),{defaultValue:i,handleSubmit:o}=sP(e,r),[c,u]=y.useState(),f=t.pathname.toLowerCase().endsWith("profiles"),h=y.useCallback(m=>{const g=ll(m);c&&PD(g,c.url),o(g)},[c,o]);return f?s.jsx(ot,{children:s.jsxs(qe,{children:[s.jsx(oP,{resource:i,currentProfile:c,onChange:u}),c?s.jsx(Jh,{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(ot,{children:s.jsx(Jh,{defaultValue:i,onSubmit:o,outcome:n})})}function Aee(){const e=Ae(),{resourceType:t,id:n}=qt(),r=e.readHistory(t,n).read();return s.jsx(ot,{children:s.jsx(tX,{history:r})})}function kee(){const{resourceType:e}=qt(),[t,n]=y.useState(),{defaultValue:r,handleSubmit:i}=sP(e,n),o=y.useCallback(c=>{i(JSON.parse(c["new-resource"]))},[i]);return s.jsxs(ot,{children:[t&&s.jsx(Xr,{outcome:t}),s.jsxs(pt,{onSubmit:o,children:[s.jsx(Dc,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:Ii(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 Pee(){const e=Ae(),{resourceType:t,id:n}=qt(),r=Wt({reference:t+"/"+n}),i=wn(),[o,c]=y.useState(),u=y.useCallback(f=>{e.updateResource(ll(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:Ye(h),autoClose:!1})})},[e,t,n,i]);return r?s.jsxs(ot,{children:[o&&s.jsx(Xr,{outcome:o}),s.jsxs(pt,{onSubmit:u,children:[s.jsx(Dc,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:Ii(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 Nee(){const{resourceType:e,id:t}=qt();return Wt({reference:e+"/"+t})?s.jsxs(ot,{children:[s.jsxs(Ka,{icon:s.jsx(il,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",s.jsx("br",{}),s.jsx(Nt,{href:`/forms/${t}`,children:`/forms/${t}`})]}),s.jsx(mk,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function Oee(){const e=Ae(),{resourceType:t,id:n}=qt(),[r,i]=y.useState(),[o,c]=y.useState();return y.useEffect(()=>{e.readResource(t,n).then(u=>i(Wr(u))).catch(u=>{Oe({color:"red",message:Ye(u)})})},[e,t,n]),r?s.jsxs(ot,{children:[s.jsxs(Le,{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(Mee,{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 Mee=({profile:e,resource:t,onResourceUpdated:n})=>{const r=Ae(),[i,o]=y.useState(),[c,u]=y.useState(()=>{var h,m;return(m=(h=t.meta)==null?void 0:h.profile)==null?void 0:m.includes(e.url)}),f=y.useCallback(h=>{o(void 0);const m=ll(h);c?PD(m,e.url):vU(m,e.url),r.updateResource(m).then(g=>{n(g),Oe({color:"green",message:"Success"})}).catch(g=>{o(Zt(g)),Oe({color:"red",message:Ye(g),autoClose:!1})})},[r,e.url,n,c]);return s.jsxs(qe,{children:[s.jsx(Cd,{size:"md",checked:c,label:`Conform resource to ${e.title}`,onChange:h=>u(h.currentTarget.checked),"data-testid":"profile-toggle"}),c?s.jsx(Jh,{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},Iee=Object.keys(lP);function Lee(){const e=Ae(),{id:t}=qt(),n=Wt({reference:`Questionnaire/${t}`}),[r,i]=y.useState(),[o,c]=y.useState("create"),[u,f]=y.useState(0),h=e.searchResources("Subscription","status=active&_count=100").read().filter(g=>$ee(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},${zt(n)}`:zt(n)}`,channel:{type:"rest-hook",endpoint:zt(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:Ye(g),autoClose:!1}))}return s.jsxs(ot,{children:[s.jsx(Le,{children:"Bots"}),s.jsxs(qe,{children:[h.length===0&&s.jsx("p",{children:"No bots found."}),h.map(g=>{var v;return s.jsxs("div",{children:[s.jsx("h3",{children:s.jsx($c,{value:{reference:(v=g.channel)==null?void 0:v.endpoint},link:!0})}),s.jsxs("p",{children:["Criteria: ",g.criteria]})]},g.id)})]}),s.jsx(Cn,{}),s.jsxs(qe,{mt:10,children:[s.jsx(md,{size:"lg",htmlFor:"bot",children:"Connect to bot"}),s.jsxs(je,{children:[s.jsx(al,{name:"bot",resourceType:"Bot",onChange:g=>i(g)}),s.jsx(Pe,{onClick:m,children:"Connect"})]}),s.jsx(je,{children:s.jsx(ln,{name:"subscription-trigger-event",defaultValue:"Create Only",label:"Subscription Trigger Event",data:Iee,onChange:g=>c(lP[g.target.value])})})]}),s.jsx("div",{style:{display:"none"},children:u})]})}function $ee(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(zt(t))||(t.url?n.includes(t.url):!1))}function zee(){const{id:e}=qt(),t=wn(),r=Ae().readReference({reference:`Questionnaire/${e}`}).read(),[i,o]=y.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:ue.EQUALS,value:r.url?`${r.url},Questionnaire/${e}`:`Questionnaire/${e}`}],fields:["id","_lastUpdated"]});return s.jsx(ot,{children:s.jsx(zc,{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 Uee(){const e=Ae(),{resourceType:t,id:n}=qt(),r=Wt({reference:t+"/"+n}),i=y.useCallback(o=>{e.updateResource(ll(o)).then(()=>{Oe({color:"green",message:"Success"})}).catch(c=>{Oe({color:"red",message:Ye(c),autoClose:!1})})},[e]);return r?s.jsx(ot,{children:s.jsx(wY,{onSubmit:i,definition:r})}):null}function Bee(){const{resourceType:e,id:t}=qt(),n=Wt({reference:e+"/"+t});return n?s.jsx(ot,{children:e==="MeasureReport"?s.jsx(wQ,{measureReport:n}):s.jsx(zb,{value:n})}):null}const Vee="_container_1ue98_1",Fee="_entry_1ue98_14",Hee="_active_1ue98_21",xy={container:Vee,entry:Fee,active:Hee};function qee(e){const t=Ae(),n=Wt(e.value),[r,i]=y.useState();return y.useEffect(()=>{if(!n)return;const o=l1(n);if(!o)return;const c="reference"in o?o.reference:zt(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:Ye(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,v;return s.jsxs("div",{className:Ut(xy.entry,{[xy.active]:o.id===(n==null?void 0:n.id)}),children:[s.jsx("p",{children:s.jsx(mt,{to:o,children:Gee(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:(v=o.code.coding[0])==null?void 0:v.code}),s.jsx("p",{children:Wee(o)})]},o.id)})}):null}function Gee(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function Wee(e){var t;return e.authoredOn?e.authoredOn.substring(0,10):(t=e.meta)!=null&&t.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const Qee="_container_1l2dh_1",Yee={container:Qee};function Xee(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:Yee.container,children:s.jsx(ln,{defaultValue:e.defaultValue,onChange:f=>e.onChange(f.currentTarget.value),data:n})})}function Kee(e){var n,r;const t=Wt(e.specimen);return t?s.jsxs(ht,{children:[s.jsxs(ht.Entry,{children:[s.jsx(ht.Key,{children:"Type"}),s.jsx(ht.Value,{children:"Specimen"})]}),s.jsxs(ht.Entry,{children:[s.jsx(ht.Key,{children:"Collected"}),s.jsx(ht.Value,{children:gr((n=t.collection)==null?void 0:n.collectedDateTime)})]}),s.jsxs(ht.Entry,{children:[s.jsx(ht.Key,{children:"Specimen Age"}),s.jsx(ht.Value,{children:Zee(t)})]}),(r=t.collection)!=null&&r.collectedDateTime&&t.receivedTime?s.jsxs(ht.Entry,{children:[s.jsx(ht.Key,{children:"Specimen Stability"}),s.jsx(ht.Value,{children:Jee(t)})]}):s.jsx(s.Fragment,{})]}):null}function Zee(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 Jee(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 ete(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 tte(){var _,T,R,D,k,M,I;const e=Ae(),{resourceType:t,id:n}=qt(),r={reference:t+"/"+n},i=wn(),[o,c]=y.useState(),u=Wt(r,c),f=ete(t),[h,m]=y.useState(()=>{const z=window.location.pathname.split("/").pop();return z&&f.map(V=>V.toLowerCase()).includes(z)?z:f[0].toLowerCase()});async function g(){var Y,W;const V=(W=(Y=(await e.readHistory(t,n)).entry)==null?void 0:Y.find(J=>!!J.resource))==null?void 0:W.resource;V?v(V):Oe({color:"red",message:"No history to restore",autoClose:!1})}function v(z){e.updateResource(ll(z)).then(()=>{c(void 0),Oe({color:"green",message:"Success"})}).catch(V=>{Oe({color:"red",message:Ye(V),autoClose:!1})})}if(o)return Ez(o)?s.jsxs(ot,{children:[s.jsx(Le,{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 V;z||(z=f[0].toLowerCase()),m(z),(V=i(`/${t}/${n}/${z}`))==null||V.catch(console.error)}function S(z){const V=u,Y=V.orderDetail||[];Y.length===0&&Y.push({}),Y[0].text!==z&&(Y[0].text=z,v({...V,orderDetail:Y}))}const w=u&&l1(u),C=u&&xJ(u),E=(R=(T=(_=e.getUserConfiguration())==null?void 0:_.option)==null?void 0:T.find(z=>z.id==="statusValueSet"))==null?void 0:R.valueString;return s.jsxs(s.Fragment,{children:[(u==null?void 0:u.resourceType)==="ServiceRequest"&&E&&s.jsx(Xee,{valueSet:{reference:E},defaultValue:(k=(D=u.orderDetail)==null?void 0:D[0])==null?void 0:k.text,onChange:S},zt(u)+"-"+((I=(M=u.orderDetail)==null?void 0:M[0])==null?void 0:I.text)),u&&s.jsx(qee,{value:u}),u&&s.jsxs(lr,{children:[w&&s.jsx(ok,{patient:w}),C&&s.jsx(Kee,{specimen:C}),t!=="Patient"&&s.jsx(Jk,{resource:r}),s.jsx(Yr,{children:s.jsx(Tt,{value:h.toLowerCase(),onChange:b,children:s.jsx(Tt.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:f.map(z=>s.jsx(Tt.Tab,{value:z.toLowerCase(),children:z},z))})})})]}),s.jsx(t1,{})]})}function aR(){var E,_,T,R;const e=wn(),{resourceType:t,id:n,versionId:r,tab:i}=qt(),o=Ae(),[c,u]=y.useState(!0),[f,h]=y.useState(),[m,g]=y.useState();if(y.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(ot,{children:[s.jsx(Le,{children:"Resource not found"}),s.jsx(mt,{to:`/${t}`,children:"Return to search page"})]});const v=f.entry??[],b=v.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(ot,{children:[s.jsx(Le,{children:"Version not found"}),s.jsx(mt,{to:`/${t}/${n}`,children:"Return to resource"})]});const S=v[b].resource,w=b<v.length-1?v[b+1].resource:void 0,C="diff";return s.jsxs(Tt,{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(Tt.List,{children:[s.jsx(Tt.Tab,{value:"diff",children:"Diff"}),s.jsx(Tt.Tab,{value:"raw",children:"Raw"})]})]}),s.jsxs(ot,{children:[m&&s.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)}),s.jsx(Tt.Panel,{value:"diff",children:w?s.jsxs(s.Fragment,{children:[s.jsxs("ul",{children:[s.jsxs("li",{children:["Current: ",(E=S.meta)==null?void 0:E.versionId]}),s.jsxs("li",{children:["Previous:"," ",s.jsx(mt,{to:`/${t}/${n}/_history/${(_=w.meta)==null?void 0:_.versionId}`,children:(T=w.meta)==null?void 0:T.versionId})]})]}),s.jsx(KY,{original:w,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(Tt.Panel,{value:"raw",children:s.jsx("pre",{children:JSON.stringify(S,void 0,2)})})]})]})}function nte(){const{resourceType:e,id:t}=qt(),n=wn(),[r,i]=y.useState({resourceType:"Subscription",filters:[{code:"url",operator:ue.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return s.jsx(ot,{children:s.jsx(oQ,{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 rte(e){const t=Ae(),{resource:n,opened:r,onClose:i}=e,[o,c]=y.useState(!1),[u,f]=y.useState(),[h,m]=y.useState(!1),g=y.useCallback(async()=>{if(n!=null&&n.id)try{await t.post(t.fhirUrl(n.resourceType,n.id,"$resend"),{subscription:o&&u?zt(u):void 0,verbose:h}),Oe({color:"green",message:"Done"}),i()}catch(v){Oe({color:"red",message:Ye(v),autoClose:!1})}},[t,n,i,o,u,h]);return s.jsx(Bn,{opened:r,onClose:i,title:"Resend Subscriptions",children:s.jsx(pt,{onSubmit:g,children:s.jsxs(qe,{children:[s.jsx(zn,{label:"Choose subscription (all subscriptions by default)",onChange:v=>c(v.currentTarget.checked)}),o&&s.jsx(al,{name:"subscription",resourceType:"Subscription",placeholder:"Subscription",onChange:f}),s.jsx(zn,{label:"Verbose mode",onChange:v=>m(v.currentTarget.checked)}),s.jsx(je,{justify:"flex-end",children:s.jsx(Pe,{type:"submit",children:"Resend"})})]})})})}function oR(){const e=Ae(),t=rm(),{resourceType:n,id:r}=qt(),i={reference:n+"/"+r},[o,c]=y.useState(),u=up(!1);function f(_,T){return e.updateResource({..._,priority:T})}function h(_,T){f(_,"stat").then(T).catch(console.error)}function m(_,T){f(_,"routine").then(T).catch(console.error)}function g(_){t(`/${_.resourceType}/${_.id}`)}function v(_){t(`/${_.resourceType}/${_.id}/edit`)}function b(_){t(`/${_.resourceType}/${_.id}/delete`)}function S(_){c(_),u[1].open()}function w(_){var T;t(`/${_.resourceType}/${_.id}/_history/${(T=_.meta)==null?void 0:T.versionId}`)}function C(_,T){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(()=>{T(),As({id:R,title:"AWS Textract Successful",message:"Text successfully extracted.",color:"green",icon:s.jsx(to,{size:"1rem"}),loading:!1,withCloseButton:!0})}).catch(D=>As({id:R,title:"AWS Textract Error",color:"red",message:Ye(D),icon:s.jsx(qs,{size:"1rem"}),loading:!1,withCloseButton:!0}))}function E(_){var P;const{primaryResource:T,currentResource:R,reloadTimeline:D}=_,k=R.resourceType===T.resourceType&&R.id===T.id,M=R.resourceType==="Communication"&&R.priority!=="stat",I=R.resourceType==="Communication"&&R.priority==="stat",z=k,V=!k,Y=!k,W=!k,J=(P=e.getProjectMembership())==null?void 0:P.admin,G=J,X=kJ()&&(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(QF,{size:14}),onClick:()=>h(R,D),"aria-label":`Pin ${zt(R)}`,children:"Pin"}),I&&s.jsx(Ce.Item,{leftSection:s.jsx(YF,{size:14}),onClick:()=>m(R,D),"aria-label":`Unpin ${zt(R)}`,children:"Unpin"}),V&&s.jsx(Ce.Item,{leftSection:s.jsx(VE,{size:14}),onClick:()=>g(R),"aria-label":`Details ${zt(R)}`,children:"Details"}),z&&s.jsx(Ce.Item,{leftSection:s.jsx(VE,{size:14}),onClick:()=>w(R),"aria-label":`Details ${zt(R)}`,children:"Details"}),Y&&s.jsx(Ce.Item,{leftSection:s.jsx(pA,{size:14}),onClick:()=>v(R),"aria-label":`Edit ${zt(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(ZF,{size:14}),onClick:()=>S(R),"aria-label":`Resend Subscriptions ${zt(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(oH,{size:14}),onClick:()=>C(R,D),"aria-label":`AWS Textract ${zt(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 ${zt(R)}`,children:"Delete"})]})]})}return s.jsxs(s.Fragment,{children:[n==="Encounter"&&s.jsx(pW,{encounter:i,getMenu:E}),n==="Patient"&&s.jsx(RQ,{patient:i,getMenu:E}),n==="ServiceRequest"&&s.jsx(iX,{serviceRequest:i,getMenu:E}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&s.jsx(hW,{resource:i,getMenu:E}),s.jsx(rte,{resource:o,opened:u[0],onClose:u[1].close},`resend-subscriptions-${o==null?void 0:o.id}`)]})}function ite(e){const{opened:t,close:n,version:r,loadingStatus:i,handleStatus:o,handleUpgrade:c}=e,[u,f]=y.useState(),[h,m]=y.useState(!1);return y.useEffect(()=>{t&&(u||zV("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(zn,{label:"Force",onChange:g=>m(g.currentTarget.checked)})]})]}):s.jsx(gi,{})}function ate(){const e=Ae(),{id:t}=qt(),n=y.useMemo(()=>({reference:"Agent/"+t}),[t]),[r,i]=y.useState(!1),[o,c]=y.useState(!1),[u,f]=y.useState(!1),[h,m]=y.useState(),[g,v]=y.useState(),[b,S]=y.useState(),[w,C]=y.useState(),[E,_]=y.useState(!1),[T,R]=y.useState(!1),[D,{open:k,close:M}]=up(!1);y.useEffect(()=>{if(r||o||u||E){R(!0);return}R(!1)},[r,o,u,E]);const I=y.useCallback(()=>{i(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(G=>{var X,P,L,$,H,O;m((P=(X=G.parameter)==null?void 0:X.find(U=>U.name==="status"))==null?void 0:P.valueCode),v(($=(L=G.parameter)==null?void 0:L.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(Ye(G))).finally(()=>i(!1))},[e,t]),z=y.useCallback(G=>{const X=G.host,P=G.pingCount||1;X&&(_(!0),e.pushToAgent(n,X,`PING ${P}`,hn.PING,!0).then(L=>C(L)).catch(L=>J(Ye(L))).finally(()=>_(!1)))},[e,n]),V=y.useCallback(()=>{c(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(G=>{W("Agent config reloaded successfully.")}).catch(G=>J(Ye(G))).finally(()=>c(!1))},[e,t]),Y=y.useCallback(G=>{f(!0),e.get(e.fhirUrl("Agent",t,"$upgrade",`?force=${G}`),{cache:"reload"}).then(X=>{W("Agent upgraded successfully.")}).catch(X=>J(Ye(X))).finally(()=>f(!1))},[e,t]);function W(G){Oe({color:"green",title:"Success",icon:s.jsx(to,{size:"1rem"}),message:G})}function J(G){Oe({color:"red",title:"Error",message:G,autoClose:!1})}return s.jsxs(ot,{children:[s.jsx(Bn,{opened:D,onClose:M,title:"Upgrade Agent",centered:!0,children:s.jsx(ite,{opened:D,close:M,version:g,loadingStatus:r,handleStatus:I,handleUpgrade:Y})}),s.jsx(Le,{order:1,children:"Agent Tools"}),s.jsxs("div",{style:{marginBottom:10},children:["Agent: ",s.jsx($c,{value:n,link:!0})]}),s.jsx(Cn,{my:"lg"}),s.jsx(Le,{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:I,loading:r,disabled:T&&!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(Le,{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:V,loading:o,disabled:T&&!o,"aria-label":"Reload config",children:"Reload Config"}),s.jsx(Cn,{my:"lg"}),s.jsx(Le,{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:T&&!u,"aria-label":"Upgrade agent",children:"Upgrade"}),s.jsx(Cn,{my:"lg"}),s.jsx(Le,{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(pt,{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:E,disabled:T&&!E,children:s.jsx(eH,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),s.jsx(Up,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!E&&w&&s.jsxs(s.Fragment,{children:[s.jsx(Le,{order:5,mt:"sm",mb:0,children:"Last Ping"}),s.jsx("pre",{children:w})]})]})}function ote(){return s.jsx(IK,{children:s.jsxs(Fe,{errorElement:s.jsx(yJ,{}),children:[s.jsx(Fe,{path:"/signin",element:s.jsx(LJ,{})}),s.jsx(Fe,{path:"/oauth",element:s.jsx(PJ,{})}),s.jsx(Fe,{path:"/resetpassword",element:s.jsx(OJ,{})}),s.jsx(Fe,{path:"/setpassword/:id/:secret",element:s.jsx(IJ,{})}),s.jsx(Fe,{path:"/register",element:s.jsx(NJ,{})}),s.jsx(Fe,{path:"/changepassword",element:s.jsx(mJ,{})}),s.jsx(Fe,{path:"/security",element:s.jsx(MJ,{})}),s.jsx(Fe,{path:"/mfa",element:s.jsx(AJ,{})}),s.jsx(Fe,{path:"/batch",element:s.jsx(hJ,{})}),s.jsx(Fe,{path:"/bulk/:resourceType",element:s.jsx(pJ,{})}),s.jsx(Fe,{path:"/smart",element:s.jsx($J,{})}),s.jsx(Fe,{path:"/forms/:id",element:s.jsx(bJ,{})}),s.jsx(Fe,{path:"/admin/super",element:s.jsx(ree,{})}),s.jsx(Fe,{path:"/admin/super/asyncjob",element:s.jsx(KJ,{})}),s.jsx(Fe,{path:"/admin/config",element:s.jsx(WJ,{})}),s.jsxs(Fe,{path:"/admin",element:s.jsx(QJ,{}),children:[s.jsx(Fe,{path:"patients",element:s.jsx(GJ,{})}),s.jsx(Fe,{path:"bots/new",element:s.jsx(BJ,{})}),s.jsx(Fe,{path:"bots",element:s.jsx(zJ,{})}),s.jsx(Fe,{path:"clients/new",element:s.jsx(VJ,{})}),s.jsx(Fe,{path:"clients",element:s.jsx(UJ,{})}),s.jsx(Fe,{path:"details",element:s.jsx(JT,{})}),s.jsx(Fe,{path:"invite",element:s.jsx(qJ,{})}),s.jsx(Fe,{path:"users",element:s.jsx(aee,{})}),s.jsx(Fe,{path:"project",element:s.jsx(JT,{})}),s.jsx(Fe,{path:"secrets",element:s.jsx(YJ,{})}),s.jsx(Fe,{path:"sites",element:s.jsx(XJ,{})}),s.jsx(Fe,{path:"members/:membershipId",element:s.jsx(HJ,{})})]}),s.jsx(Fe,{path:"/lab/assays",element:s.jsx(oee,{})}),s.jsx(Fe,{path:"/lab/panels",element:s.jsx(see,{})}),s.jsx(Fe,{path:"/:resourceType/:id/_history/:versionId/:tab",element:s.jsx(aR,{})}),s.jsx(Fe,{path:"/:resourceType/:id/_history/:versionId",element:s.jsx(aR,{})}),s.jsxs(Fe,{path:"/:resourceType/new",element:s.jsx(vJ,{}),children:[s.jsx(Fe,{index:!0,element:s.jsx(yy,{})}),s.jsx(Fe,{path:"form",element:s.jsx(yy,{})}),s.jsx(Fe,{path:"json",element:s.jsx(kee,{})}),s.jsx(Fe,{path:"profiles",element:s.jsx(yy,{})})]}),s.jsxs(Fe,{path:"/:resourceType/:id",element:s.jsx(tte,{}),children:[s.jsx(Fe,{index:!0,element:s.jsx(oR,{})}),s.jsx(Fe,{path:"apply",element:s.jsx(cee,{})}),s.jsx(Fe,{path:"apps",element:s.jsx(uee,{})}),s.jsx(Fe,{path:"event",element:s.jsx(fee,{})}),s.jsx(Fe,{path:"blame",element:s.jsx(hee,{})}),s.jsx(Fe,{path:"bots",element:s.jsx(Lee,{})}),s.jsx(Fe,{path:"builder",element:s.jsx(wee,{})}),s.jsx(Fe,{path:"checklist",element:s.jsx(jee,{})}),s.jsx(Fe,{path:"delete",element:s.jsx(Cee,{})}),s.jsx(Fe,{path:"details",element:s.jsx(Ree,{})}),s.jsx(Fe,{path:"edit",element:s.jsx(_ee,{})}),s.jsx(Fe,{path:"editor",element:s.jsx(bee,{})}),s.jsx(Fe,{path:"history",element:s.jsx(Aee,{})}),s.jsx(Fe,{path:"json",element:s.jsx(Pee,{})}),s.jsx(Fe,{path:"preview",element:s.jsx(Nee,{})}),s.jsx(Fe,{path:"responses",element:s.jsx(zee,{})}),s.jsx(Fe,{path:"report",element:s.jsx(Bee,{})}),s.jsx(Fe,{path:"ranges",element:s.jsx(Uee,{})}),s.jsx(Fe,{path:"subscriptions",element:s.jsx(nte,{})}),s.jsx(Fe,{path:"timeline",element:s.jsx(oR,{})}),s.jsx(Fe,{path:"tools",element:s.jsx(ate,{})}),s.jsx(Fe,{path:"profiles",element:s.jsx(Oee,{})}),s.jsx(Fe,{path:"export",element:s.jsx(Dee,{})})]}),s.jsx(Fe,{path:"/:resourceType",element:s.jsx(ZT,{})}),s.jsx(Fe,{path:"/",element:s.jsx(ZT,{})})]})})}function ste(){const e=Ae(),t=e.getUserConfiguration(),n=Mr(),[r]=i1();return e.isLoading()?s.jsx(gi,{}):s.jsx(eq,{logo:s.jsx(Bi,{size:24}),pathname:n.pathname,searchParams:r,version:XD,menus:lte(t),displayAddBookmark:!!(t!=null&&t.id),children:s.jsx(y.Suspense,{fallback:s.jsx(gi,{}),children:s.jsx(ote,{})})})}function lte(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:cte(o.target)})))||[]}}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:s.jsx(VF,{})}]}),t}const sR={Patient:rH,Practitioner:UF,Organization:AF,ServiceRequest:KF,DiagnosticReport:JF,Questionnaire:zF,admin:RF,AccessPolicy:BF,Subscription:sH,batch:WF,Observation:qF};function cte(e){try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in sR){const n=sR[t];return s.jsx(n,{})}}catch{}return s.jsx(Qp,{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 ute(){const e=Bd(),t=new KD({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=sZ([{path:"*",element:s.jsx(ste,{})}]),i=c=>r.navigate(c);uX.createRoot(document.getElementById("root")).render(s.jsx(y.StrictMode,{children:s.jsx(UV,{medplum:t,navigate:i,children:s.jsxs(PR,{theme:n,children:[s.jsx(eo,{position:"bottom-right"}),s.jsx(PK,{router:r})]})})}))}ute().catch(console.error);
|
|
589
|
-
//# sourceMappingURL=index-
|
|
589
|
+
//# sourceMappingURL=index-8LS3BIwK.js.map
|