@medplum/app 4.3.2 → 4.3.3
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 p3(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 ac={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let SE=!1;function oV(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");ac.Event=globalThis.Event,ac.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},ac.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function sV(e,t){if(!e)throw new Error(t)}function ah(e){return new e.constructor(e.type,e)}const bs={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let wE=!1;class Mo extends Xp{constructor(t,n,r={}){SE||(oV(),SE=!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:s=bs.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),s),sV(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 Mo.CONNECTING}get OPEN(){return Mo.OPEN}get CLOSING(){return Mo.CLOSING}get CLOSED(){return Mo.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?Mo.CLOSED:Mo.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=bs.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=bs.reconnectionDelayGrowFactor,minReconnectionDelay:n=bs.minReconnectionDelay,maxReconnectionDelay:r=bs.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=bs.maxRetries,connectionTimeout:n=bs.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"&&!wE&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),wE=!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 ac.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new ac.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new ac.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 lV=5e3;class zy extends Xp{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 cV{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new zy(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class uV{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof GA))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 s=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 Mo(i,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger});this.medplum=t,this.ws=s,this.masterSubEmitter=new zy,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??lV,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,i,s,c,u,f;try{const p=JSON.parse(n.data);if(p.type==="pong"){this.waitingForPong=!1;return}const m=p,g=(i=(r=m==null?void 0:m.entry)==null?void 0:r[0])==null?void 0:i.resource;if(g.type==="heartbeat"){(s=this.masterSubEmitter)==null||s.dispatchEvent({type:"heartbeat",payload:m});return}if(g.type==="handshake"){const b=Bs(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(Bs(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(p){console.error(p);const m={type:"error",payload:p};(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(S8(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 s of this.getAllCriteriaEmitters())s.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),(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,s=(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(!s)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(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:s}=t;if(!this.criteriaEntries.has(n))return;const c=this.criteriaEntries.get(n);r?c.criteriaWithProps=c.criteriaWithProps.filter(f=>{const p=f.subscriptionProps;return!sa(r,p)}):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),s&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:s}}))}async subscribeToCriteria(t){if(!(this.ws.readyState!==WebSocket.OPEN||t.connecting)){t.connecting=!0;try{const[n,r]=await this.getTokenForCriteria(t);t.subscriptionId=n,t.token=r,this.criteriaEntriesBySubscriptionId.set(n,t),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:r}}))}catch(n){console.error(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 cV(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 zy(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const qA="4.3.2-31f7dcd0a",dV=hn.FHIR_JSON+", */*; q=0.1",fV="https://api.medplum.com/",hV=1e3,pV=6e4,mV=0,gV=3e5,vV="Binary/",jE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},Xl={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"},yV={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},xV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class GA extends Xp{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)??bV(),this.storage=(t==null?void 0:t.storage)??new iV,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=eb((t==null?void 0:t.baseUrl)??fV),this.fhirBaseUrl=Xi(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=Xi(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=Xi(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=Xi(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),this.fhircastHubUrl=Xi(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)??gV,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?mV:pV),this.cacheTime>0?this.requestCache=new aA((t==null?void 0:t.resourceCacheSize)??hV):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=Xi(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 s=new Ai(i);return this.setCacheEntry(t,s),s}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,s=!0){let c=i;s&&(c=await this.ensureCodeChallenge(i)),window.location.assign(this.getExternalAuthRedirectUri(t,n,r,c,s))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");return this.fetchTokens({grant_type:Xl.TokenExchange,subject_token_type:yV.AccessToken,client_id:n,subject_token:t})}getExternalAuthRedirectUri(t,n,r,i,s=!0){const c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",n),c.searchParams.set("redirect_uri",r),c.searchParams.set("scope",i.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(i)),s){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(Xi(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),s="search-"+i.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=this.getBundle(i,r);return this.setCacheEntry(s,u),u}searchOne(t,n,r){const i=this.fhirSearchUrl(t,n);i.searchParams.set("_count","1"),i.searchParams.sort();const s="searchOne-"+i.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=new Ai(this.search(t,i.searchParams,r).then(f=>{var p,m;return(m=(p=f.entry)==null?void 0:p[0])==null?void 0:m.resource}));return this.setCacheEntry(s,u),u}searchResources(t,n,r){const s="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=new Ai(this.search(t,n,r).then(TE));return this.setCacheEntry(s,u),u}async*searchResourcePages(t,n,r){var s,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),p=(s=f.link)==null?void 0:s.find(m=>m.relation==="next");if(!((c=f.entry)!=null&&c.length)&&!p)break;yield TE(f),i=p!=null&&p.url?new URL(p.url):void 0}}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){var i,s;const r=(s=(i=this.requestCache)==null?void 0:i.get(this.fhirUrl(t,n).toString()))==null?void 0:s.value;return r!=null&&r.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return jE;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 Ai(Promise.reject(new Error("Missing reference")));if(r==="system")return new Ai(Promise.resolve(jE));const[i,s]=r.split("/");return!i||!s?new Ai(Promise.reject(new Error("Invalid reference"))):this.readResource(i,s,n)}requestSchema(t){if(fA(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const i=new Ai((async()=>{const s=`{
|
|
86
|
+
*/const ac={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let SE=!1;function oV(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");ac.Event=globalThis.Event,ac.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},ac.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function sV(e,t){if(!e)throw new Error(t)}function ah(e){return new e.constructor(e.type,e)}const bs={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let wE=!1;class Mo extends Xp{constructor(t,n,r={}){SE||(oV(),SE=!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:s=bs.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),s),sV(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 Mo.CONNECTING}get OPEN(){return Mo.OPEN}get CLOSING(){return Mo.CLOSING}get CLOSED(){return Mo.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?Mo.CLOSED:Mo.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=bs.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=bs.reconnectionDelayGrowFactor,minReconnectionDelay:n=bs.minReconnectionDelay,maxReconnectionDelay:r=bs.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=bs.maxRetries,connectionTimeout:n=bs.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"&&!wE&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),wE=!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 ac.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new ac.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new ac.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 lV=5e3;class zy extends Xp{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 cV{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new zy(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class uV{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof GA))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 s=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 Mo(i,void 0,{debug:r==null?void 0:r.debug,debugLogger:r==null?void 0:r.debugLogger});this.medplum=t,this.ws=s,this.masterSubEmitter=new zy,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=(r==null?void 0:r.pingIntervalMs)??lV,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{var r,i,s,c,u,f;try{const p=JSON.parse(n.data);if(p.type==="pong"){this.waitingForPong=!1;return}const m=p,g=(i=(r=m==null?void 0:m.entry)==null?void 0:r[0])==null?void 0:i.resource;if(g.type==="heartbeat"){(s=this.masterSubEmitter)==null||s.dispatchEvent({type:"heartbeat",payload:m});return}if(g.type==="handshake"){const b=Bs(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(Bs(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(p){console.error(p);const m={type:"error",payload:p};(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(S8(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 s of this.getAllCriteriaEmitters())s.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),(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,s=(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(!s)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(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:s}=t;if(!this.criteriaEntries.has(n))return;const c=this.criteriaEntries.get(n);r?c.criteriaWithProps=c.criteriaWithProps.filter(f=>{const p=f.subscriptionProps;return!sa(r,p)}):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),s&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:s}}))}async subscribeToCriteria(t){if(!(this.ws.readyState!==WebSocket.OPEN||t.connecting)){t.connecting=!0;try{const[n,r]=await this.getTokenForCriteria(t);t.subscriptionId=n,t.token=r,this.criteriaEntriesBySubscriptionId.set(n,t),this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:r}}))}catch(n){console.error(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 cV(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 zy(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const qA="4.3.3-ded292ba7",dV=hn.FHIR_JSON+", */*; q=0.1",fV="https://api.medplum.com/",hV=1e3,pV=6e4,mV=0,gV=3e5,vV="Binary/",jE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},Xl={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"},yV={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},xV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class GA extends Xp{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)??bV(),this.storage=(t==null?void 0:t.storage)??new iV,this.createPdfImpl=t==null?void 0:t.createPdf,this.baseUrl=eb((t==null?void 0:t.baseUrl)??fV),this.fhirBaseUrl=Xi(this.baseUrl,(t==null?void 0:t.fhirUrlPath)??"fhir/R4"),this.authorizeUrl=Xi(this.baseUrl,(t==null?void 0:t.authorizeUrl)??"oauth2/authorize"),this.tokenUrl=Xi(this.baseUrl,(t==null?void 0:t.tokenUrl)??"oauth2/token"),this.logoutUrl=Xi(this.baseUrl,(t==null?void 0:t.logoutUrl)??"oauth2/logout"),this.fhircastHubUrl=Xi(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)??gV,this.cacheTime=(t==null?void 0:t.cacheTime)??(typeof window>"u"?mV:pV),this.cacheTime>0?this.requestCache=new aA((t==null?void 0:t.resourceCacheSize)??hV):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=Xi(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 s=new Ai(i);return this.setCacheEntry(t,s),s}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,s=!0){let c=i;s&&(c=await this.ensureCodeChallenge(i)),window.location.assign(this.getExternalAuthRedirectUri(t,n,r,c,s))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");return this.fetchTokens({grant_type:Xl.TokenExchange,subject_token_type:yV.AccessToken,client_id:n,subject_token:t})}getExternalAuthRedirectUri(t,n,r,i,s=!0){const c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",n),c.searchParams.set("redirect_uri",r),c.searchParams.set("scope",i.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(i)),s){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(Xi(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),s="search-"+i.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=this.getBundle(i,r);return this.setCacheEntry(s,u),u}searchOne(t,n,r){const i=this.fhirSearchUrl(t,n);i.searchParams.set("_count","1"),i.searchParams.sort();const s="searchOne-"+i.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=new Ai(this.search(t,i.searchParams,r).then(f=>{var p,m;return(m=(p=f.entry)==null?void 0:p[0])==null?void 0:m.resource}));return this.setCacheEntry(s,u),u}searchResources(t,n,r){const s="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const u=new Ai(this.search(t,n,r).then(TE));return this.setCacheEntry(s,u),u}async*searchResourcePages(t,n,r){var s,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),p=(s=f.link)==null?void 0:s.find(m=>m.relation==="next");if(!((c=f.entry)!=null&&c.length)&&!p)break;yield TE(f),i=p!=null&&p.url?new URL(p.url):void 0}}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){var i,s;const r=(s=(i=this.requestCache)==null?void 0:i.get(this.fhirUrl(t,n).toString()))==null?void 0:s.value;return r!=null&&r.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return jE;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 Ai(Promise.reject(new Error("Missing reference")));if(r==="system")return new Ai(Promise.resolve(jE));const[i,s]=r.split("/");return!i||!s?new Ai(Promise.reject(new Error("Invalid reference"))):this.readResource(i,s,n)}requestSchema(t){if(fA(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const i=new Ai((async()=>{const s=`{
|
|
87
87
|
StructureDefinitionList(_filter: "name eq ${t}") {
|
|
88
88
|
resourceType,
|
|
89
89
|
name,
|
|
@@ -583,4 +583,4 @@ Please change the parent <Route path="${D}"> to <Route path="${D==="/"?"*":`${D}
|
|
|
583
583
|
}
|
|
584
584
|
]
|
|
585
585
|
}`,see="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 lee(){const e=_e(),{id:t}=qt(),[n,r]=v.useState(),[i,s]=v.useState(),[c,u]=v.useState(oee),[f,p]=v.useState(see),[m,g]=v.useState(hn.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),s(await cee(e,k))}).catch(k=>Oe({color:"red",message:Ye(k),autoClose:!1}))},[e,t]);const C=v.useCallback(async()=>Yu(y.current,{command:"getValue"}),[]),T=v.useCallback(async()=>Yu(y.current,{command:"getOutput"}),[]),D=v.useCallback(async()=>m===hn.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(),I=await T(),$=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:$},{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{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:Ye(M),autoClose:!1})}finally{j(!1)}},[e,t]),A=v.useCallback(async k=>{k.preventDefault(),k.stopPropagation(),j(!0);try{const M=await D(),I=await e.post(e.fhirUrl("Bot",t,"$execute"),M,m);await Yu(b.current,{command:"setValue",value:I}),Oe({color:"green",message:"Success"})}catch(M){Oe({color:"red",message:Ye(M),autoClose:!1})}finally{j(!1)}},[e,t,D,m]);return!n||i===void 0?null:o.jsxs(or,{m:0,gutter:0,style:{overflow:"hidden"},children:[o.jsx(or.Col,{span:8,children:o.jsxs(mr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",mih:400,children:[o.jsx(aee,{iframeRef:y,language:"typescript",module:"commonjs",testId:"code-frame",defaultValue:i,minHeight:"528px"}),o.jsxs(je,{justify:"flex-end",gap:"xs",children:[o.jsx(Ne,{type:"button",onClick:E,loading:S,leftSection:o.jsx(dF,{size:"1rem"}),children:"Save"}),o.jsx(Ne,{type:"button",onClick:R,loading:S,leftSection:o.jsx(mb,{size:"1rem"}),children:"Deploy"}),o.jsx(Ne,{type:"button",onClick:A,loading:S,leftSection:o.jsx(TF,{size:"1rem"}),children:"Execute"})]})]})}),o.jsxs(or.Col,{span:4,children:[o.jsxs(mr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[o.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?o.jsx(Dc,{value:c,onChange:k=>u(k),autosize:!0,minRows:15}):o.jsx("textarea",{className:ree.hl7Input,value:f,onChange:k=>p(k.currentTarget.value),rows:15})]}),o.jsx(mr,{m:2,p:"xs",shadow:"md",children:o.jsx(iee,{iframeRef:b,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function cee(e,t){var n,r,i;if((n=t.sourceCode)!=null&&n.url){const s=(i=(r=t.sourceCode.url)==null?void 0:r.split("/"))==null?void 0:i.find(wA);return(await e.download(e.fhirUrl("Binary",s))).text()}return t.code??""}function sl(e){let t=e.meta;return t&&(t={...t,lastUpdated:void 0,versionId:void 0,author:void 0}),{...e,meta:t}}function uee(){const e=_e(),{resourceType:t,id:n}=qt(),r={reference:t+"/"+n},i=v.useCallback(s=>{e.updateResource(sl(s)).then(()=>{Oe({color:"green",message:"Success"})}).catch(c=>{Oe({color:"red",message:Ye(c),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return o.jsx(ot,{children:o.jsx(oW,{value:r,onSubmit:i})});case"Questionnaire":return o.jsx(ot,{children:o.jsx(QW,{questionnaire:r,onSubmit:i})});default:return null}}function dee(){const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t}),r=wn();return n?o.jsx(ot,{children:o.jsx(yY,{value:n,onStart:(i,s)=>{var c;return(c=r(`/forms/${Bs(s)}`))==null?void 0:c.catch(console.error)},onEdit:(i,s,c)=>{var u;return(u=r(`/${c.reference}}`))==null?void 0:u.catch(console.error)}})}):null}function fee(){const e=_e(),{resourceType:t,id:n}=qt(),r=wn();return o.jsxs(ot,{children:[o.jsxs("p",{children:["Are you sure you want to delete this ",t,"?"]}),o.jsx(Ne,{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 hee="_selectProfileBtn_tbaz6_1",pee="_chevron_tbaz6_13",JT={selectProfileBtn:hee,chevron:pee};function mee(){var f,p;const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t}),[r,i]=v.useState(),s=yd({onDropdownClose:()=>s.resetSelectedOption()}),c=v.useMemo(()=>{var m;if(Tn((m=n==null?void 0:n.meta)==null?void 0:m.profile))return[o.jsx(ct.Option,{value:"",children:"None"},""),...n.meta.profile.map(g=>o.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])},[(p=n==null?void 0:n.meta)==null?void 0:p.profile]),!n)return null;let u;return Tn(c)&&(u=o.jsx(je,{justify:"flex-end",children:o.jsxs(Ge,{align:"flex-end",gap:"xs",children:[o.jsxs(ct,{store:s,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:m=>{i(m),s.closeDropdown()},children:[o.jsx(ct.Target,{children:o.jsx(tr,{onClick:()=>s.toggleDropdown(),children:o.jsxs(d0,{fw:"bold",fs:"sm",className:JT.selectProfileBtn,children:[o.jsx("span",{children:"Pick profile"}),o.jsx(pb,{stroke:1.5,className:JT.chevron})]})})}),o.jsx(ct.Dropdown,{w:"max-content",children:o.jsx(ct.Options,{children:c})})]}),o.jsx(ce,{children:r?o.jsxs(o.Fragment,{children:[o.jsx(Ae,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),o.jsx(Ae,{span:!0,size:"sm",children:r||"Nothing selected"})]}):o.jsx(Ae,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),o.jsx(ot,{children:o.jsxs(Ge,{gap:"xl",children:[u,o.jsx(Pb,{value:n,profileUrl:r})]})})}function gee(){const e=_e(),{resourceType:t,id:n}=qt(),[r,i]=v.useState(),[s,c]=v.useState(),u=wn(),[f,p]=v.useState();v.useEffect(()=>{e.readResource(t,n).then(b=>{i(Qr(b)),c(Qr(b))}).catch(b=>{p(Zt(b)),Oe({color:"red",message:Ye(b),autoClose:!1})})},[e,t,n]);const m=v.useCallback(b=>{p(void 0),e.updateResource(sl(b)).then(()=>{var S;(S=u(`/${t}/${n}/details`))==null||S.catch(console.error),Oe({id:"succes",color:"green",message:"Success"})}).catch(S=>{p(Zt(S)),Oe({color:"red",message:Ye(S),autoClose:!1})})},[e,t,n,u]),g=v.useCallback(b=>{p(void 0);const S=$_.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=>{p(Zt(j)),Oe({color:"red",message:Ye(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 s?o.jsx(ot,{children:o.jsx(Yh,{defaultValue:s,onSubmit:m,onPatch:g,onDelete:y,outcome:f})}):null}function vee(){const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t});return n?o.jsx(ot,{maw:700,children:n.resourceType==="Patient"?o.jsx(eW,{patient:n}):o.jsx(Ya,{icon:o.jsx(rl,{size:16}),title:"Unsupported export type",color:"red",children:"This page is only supported for Patient resources"})}):null}function i4({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,i=_e(),[s,c]=v.useState();return v.useEffect(()=>{i.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(u=>{c(u.filter(Sq))}).catch(console.error)},[i,n,r]),o.jsx(Et,{value:t==null?void 0:t.url,onChange:u=>{const f=s==null?void 0:s.find(p=>p.url===u);f&&n(f)},children:o.jsx(Et.List,{children:s==null?void 0:s.map(u=>{var m,g;const f=(g=(m=e.meta)==null?void 0:m.profile)==null?void 0:g.includes(u.url),p=f?"This profile is present in this resource's meta.profile property.":"This profile is not included in this resource's meta.profile property.";return o.jsx(Et.Tab,{value:u.url,title:p,rightSection:f&&o.jsx(q0,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:o.jsx(zF,{size:"90%"})}),children:u.title||u.name},u.url)})})})}function a4(e,t){const n=_e(),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 hy(){const{resourceType:e}=qt(),t=Mr(),[n,r]=v.useState(),{defaultValue:i,handleSubmit:s}=a4(e,r),[c,u]=v.useState(),f=t.pathname.toLowerCase().endsWith("profiles"),p=v.useCallback(m=>{const g=sl(m);c&&RA(g,c.url),s(g)},[c,s]);return f?o.jsx(ot,{children:o.jsxs(Ge,{children:[o.jsx(i4,{resource:i,currentProfile:c,onChange:u}),c?o.jsx(Yh,{defaultValue:i,onSubmit:p,outcome:n,profileUrl:c.url},c.url):o.jsx(Ae,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):o.jsx(ot,{children:o.jsx(Yh,{defaultValue:i,onSubmit:s,outcome:n})})}function yee(){const e=_e(),{resourceType:t,id:n}=qt(),r=e.readHistory(t,n).read();return o.jsx(ot,{children:o.jsx(FY,{history:r})})}function xee(){const{resourceType:e}=qt(),[t,n]=v.useState(),{defaultValue:r,handleSubmit:i}=a4(e,n),s=v.useCallback(c=>{i(JSON.parse(c["new-resource"]))},[i]);return o.jsxs(ot,{children:[t&&o.jsx(Kr,{outcome:t}),o.jsxs(pt,{onSubmit:s,children:[o.jsx(Dc,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:Ii(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),o.jsx(je,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:o.jsx(Ne,{type:"submit",children:"OK"})})]})]})}function bee(){const e=_e(),{resourceType:t,id:n}=qt(),r=Qt({reference:t+"/"+n}),i=wn(),[s,c]=v.useState(),u=v.useCallback(f=>{e.updateResource(sl(JSON.parse(f.resource))).then(()=>{var p;c(void 0),(p=i(`/${t}/${n}/details`))==null||p.catch(console.error),Oe({color:"green",message:"Success"})}).catch(p=>{Oe({color:"red",message:Ye(p),autoClose:!1})})},[e,t,n,i]);return r?o.jsxs(ot,{children:[s&&o.jsx(Kr,{outcome:s}),o.jsxs(pt,{onSubmit:u,children:[o.jsx(Dc,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:Ii(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),o.jsx(je,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:o.jsx(Ne,{type:"submit",children:"OK"})})]})]}):null}function See(){const{resourceType:e,id:t}=qt();return Qt({reference:e+"/"+t})?o.jsxs(ot,{children:[o.jsxs(Ya,{icon:o.jsx(rl,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",o.jsx("br",{}),o.jsx(Nt,{href:`/forms/${t}`,children:`/forms/${t}`})]}),o.jsx(dk,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function wee(){const e=_e(),{resourceType:t,id:n}=qt(),[r,i]=v.useState(),[s,c]=v.useState();return v.useEffect(()=>{e.readResource(t,n).then(u=>i(Qr(u))).catch(u=>{Oe({color:"red",message:Ye(u)})})},[e,t,n]),r?o.jsxs(ot,{children:[o.jsxs(Le,{order:2,children:["Available ",t," profiles"]}),o.jsx(Ge,{children:o.jsxs(o.Fragment,{children:[o.jsx(i4,{resource:r,currentProfile:s,onChange:c}),s?o.jsx(jee,{profile:s,resource:r,onResourceUpdated:u=>i(u)},s.url):o.jsx(Ae,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const jee=({profile:e,resource:t,onResourceUpdated:n})=>{const r=_e(),[i,s]=v.useState(),[c,u]=v.useState(()=>{var p,m;return(m=(p=t.meta)==null?void 0:p.profile)==null?void 0:m.includes(e.url)}),f=v.useCallback(p=>{s(void 0);const m=sl(p);c?RA(m,e.url):mU(m,e.url),r.updateResource(m).then(g=>{n(g),Oe({color:"green",message:"Success"})}).catch(g=>{s(Zt(g)),Oe({color:"red",message:Ye(g),autoClose:!1})})},[r,e.url,n,c]);return o.jsxs(Ge,{children:[o.jsx(jd,{size:"md",checked:c,label:`Conform resource to ${e.title}`,onChange:p=>u(p.currentTarget.checked),"data-testid":"profile-toggle"}),c?o.jsx(Yh,{profileUrl:e.url,defaultValue:t,onSubmit:f,outcome:i}):o.jsx("form",{noValidate:!0,onSubmit:p=>{p.preventDefault(),f(t)},children:o.jsx(je,{justify:"flex-end",mt:"xl",children:o.jsx(Ne,{type:"submit",children:"OK"})})})]})},o4={"Create Only":"create","Update Only":"update","Delete Only":"delete","All Interactions":void 0},Cee=Object.keys(o4);function Eee(){const e=_e(),{id:t}=qt(),n=Qt({reference:`Questionnaire/${t}`}),[r,i]=v.useState(),[s,c]=v.useState("create"),[u,f]=v.useState(0),p=e.searchResources("Subscription","status=active&_count=100").read().filter(g=>Tee(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)},...s?{extension:[{url:"https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction",valueCode:s}]}: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 o.jsxs(ot,{children:[o.jsx(Le,{children:"Bots"}),o.jsxs(Ge,{children:[p.length===0&&o.jsx("p",{children:"No bots found."}),p.map(g=>{var y;return o.jsxs("div",{children:[o.jsx("h3",{children:o.jsx(Lc,{value:{reference:(y=g.channel)==null?void 0:y.endpoint},link:!0})}),o.jsxs("p",{children:["Criteria: ",g.criteria]})]},g.id)})]}),o.jsx(Cn,{}),o.jsxs(Ge,{mt:10,children:[o.jsx(pd,{size:"lg",htmlFor:"bot",children:"Connect to bot"}),o.jsxs(je,{children:[o.jsx(il,{name:"bot",resourceType:"Bot",onChange:g=>i(g)}),o.jsx(Ne,{onClick:m,children:"Connect"})]}),o.jsx(je,{children:o.jsx(ln,{name:"subscription-trigger-event",defaultValue:"Create Only",label:"Subscription Trigger Event",data:Cee,onChange:g=>c(o4[g.target.value])})})]}),o.jsx("div",{style:{display:"none"},children:u})]})}function Tee(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 Ree(){const{id:e}=qt(),t=wn(),r=_e().readReference({reference:`Questionnaire/${e}`}).read(),[i,s]=v.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:ue.EQUALS,value:r.url?`${r.url},Questionnaire/${e}`:`Questionnaire/${e}`}],fields:["id","_lastUpdated"]});return o.jsx(ot,{children:o.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=>s(c.definition),hideFilters:!0,hideToolbar:!0})})}function Dee(){const e=_e(),{resourceType:t,id:n}=qt(),r=Qt({reference:t+"/"+n}),i=v.useCallback(s=>{e.updateResource(sl(s)).then(()=>{Oe({color:"green",message:"Success"})}).catch(c=>{Oe({color:"red",message:Ye(c),autoClose:!1})})},[e]);return r?o.jsx(ot,{children:o.jsx(uY,{onSubmit:i,definition:r})}):null}function Aee(){const{resourceType:e,id:t}=qt(),n=Qt({reference:e+"/"+t});return n?o.jsx(ot,{children:e==="MeasureReport"?o.jsx(ZQ,{measureReport:n}):o.jsx(kb,{value:n})}):null}const _ee="_container_1ue98_1",kee="_entry_1ue98_14",Pee="_active_1ue98_21",py={container:_ee,entry:kee,active:Pee};function Nee(e){const t=_e(),n=Qt(e.value),[r,i]=v.useState();return v.useEffect(()=>{if(!n)return;const s=n1(n);if(!s)return;const c="reference"in s?s.reference:zt(s);t.search("ServiceRequest","subject="+c).then(u=>{const p=(u.entry??[]).map(m=>m.resource);U_(p),p.reverse(),i(p)}).catch(u=>Oe({color:"red",message:Ye(u),autoClose:!1}))},[t,n]),r?o.jsx("div",{"data-testid":"quick-service-requests",className:py.container,children:r.map(s=>{var c,u,f,p,m,g,y;return o.jsxs("div",{className:Ut(py.entry,{[py.active]:s.id===(n==null?void 0:n.id)}),children:[o.jsx("p",{children:o.jsx(mt,{to:s,children:Oee(s)})}),((u=(c=s.category)==null?void 0:c[0])==null?void 0:u.text)&&o.jsx("p",{children:(f=s.category[0])==null?void 0:f.text}),((g=(m=(p=s.code)==null?void 0:p.coding)==null?void 0:m[0])==null?void 0:g.code)&&o.jsx("p",{children:(y=s.code.coding[0])==null?void 0:y.code}),o.jsx("p",{children:Mee(s)})]},s.id)})}):null}function Oee(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function Mee(e){var t;return e.authoredOn?e.authoredOn.substring(0,10):(t=e.meta)!=null&&t.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const Iee="_container_1l2dh_1",Lee={container:Iee};function zee(e){var i,s,c,u;const t=Qt(e.valueSet);if(!t)return null;const n=[""],r=(u=(c=(s=(i=t.compose)==null?void 0:i.include)==null?void 0:s[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),o.jsx("div",{className:Lee.container,children:o.jsx(ln,{defaultValue:e.defaultValue,onChange:f=>e.onChange(f.currentTarget.value),data:n})})}function $ee(e){var n,r;const t=Qt(e.specimen);return t?o.jsxs(ht,{children:[o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Type"}),o.jsx(ht.Value,{children:"Specimen"})]}),o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Collected"}),o.jsx(ht.Value,{children:gr((n=t.collection)==null?void 0:n.collectedDateTime)})]}),o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Specimen Age"}),o.jsx(ht.Value,{children:Uee(t)})]}),(r=t.collection)!=null&&r.collectedDateTime&&t.receivedTime?o.jsxs(ht.Entry,{children:[o.jsx(ht.Key,{children:"Specimen Stability"}),o.jsx(ht.Value,{children:Bee(t)})]}):o.jsx(o.Fragment,{})]}):null}function Uee(e){var i;const t=(i=e.collection)==null?void 0:i.collectedDateTime;if(!t)return;const n=new Date(t);return s4(l4(n,new Date))}function Bee(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 s4(l4(t,n))}function s4(e){return e.toString().padStart(3,"0")+"D"}function l4(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function Vee(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 Fee(){var D,E,R,A,k,M,I;const e=_e(),{resourceType:t,id:n}=qt(),r={reference:t+"/"+n},i=wn(),[s,c]=v.useState(),u=Qt(r,c),f=Vee(t),[p,m]=v.useState(()=>{const $=window.location.pathname.split("/").pop();return $&&f.map(V=>V.toLowerCase()).includes($)?$:f[0].toLowerCase()});async function g(){var Y,Q;const V=(Q=(Y=(await e.readHistory(t,n)).entry)==null?void 0:Y.find(J=>!!J.resource))==null?void 0:Q.resource;V?y(V):Oe({color:"red",message:"No history to restore",autoClose:!1})}function y($){e.updateResource(sl($)).then(()=>{c(void 0),Oe({color:"green",message:"Success"})}).catch(V=>{Oe({color:"red",message:Ye(V),autoClose:!1})})}if(s)return j8(s)?o.jsxs(ot,{children:[o.jsx(Le,{children:"Deleted"}),o.jsx("p",{children:"The resource was deleted."}),o.jsx(Ne,{color:"red",onClick:g,children:"Restore"})]}):o.jsx(Kr,{outcome:s});function b($){var V;$||($=f[0].toLowerCase()),m($),(V=i(`/${t}/${n}/${$}`))==null||V.catch(console.error)}function S($){const V=u,Y=V.orderDetail||[];Y.length===0&&Y.push({}),Y[0].text!==$&&(Y[0].text=$,y({...V,orderDetail:Y}))}const j=u&&n1(u),C=u&&sJ(u),T=(R=(E=(D=e.getUserConfiguration())==null?void 0:D.option)==null?void 0:E.find($=>$.id==="statusValueSet"))==null?void 0:R.valueString;return o.jsxs(o.Fragment,{children:[(u==null?void 0:u.resourceType)==="ServiceRequest"&&T&&o.jsx(zee,{valueSet:{reference:T},defaultValue:(k=(A=u.orderDetail)==null?void 0:A[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&&o.jsx(Nee,{value:u}),u&&o.jsxs(mr,{children:[j&&o.jsx(W_,{patient:j}),C&&o.jsx($ee,{specimen:C}),t!=="Patient"&&o.jsx(Xk,{resource:r}),o.jsx(Yr,{children:o.jsx(Et,{value:p.toLowerCase(),onChange:b,children:o.jsx(Et.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:f.map($=>o.jsx(Et.Tab,{value:$.toLowerCase(),children:$},$))})})})]}),o.jsx(Yb,{})]})}function eR(){var T,D,E,R;const e=wn(),{resourceType:t,id:n,versionId:r,tab:i}=qt(),s=_e(),[c,u]=v.useState(!0),[f,p]=v.useState(),[m,g]=v.useState();if(v.useEffect(()=>{g(void 0),u(!0),s.readHistory(t,n).then(A=>p(A)).then(()=>u(!1)).catch(A=>{g(A),u(!1)})},[s,t,n]),c)return o.jsx(gi,{});if(!f)return o.jsxs(ot,{children:[o.jsx(Le,{children:"Resource not found"}),o.jsx(mt,{to:`/${t}`,children:"Return to search page"})]});const y=f.entry??[],b=y.findIndex(A=>{var k,M;return((M=(k=A.resource)==null?void 0:k.meta)==null?void 0:M.versionId)===r});if(b===-1)return o.jsxs(ot,{children:[o.jsx(Le,{children:"Version not found"}),o.jsx(mt,{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 o.jsxs(Et,{value:i||C,onChange:A=>{var k;return(k=e(`/${t}/${n}/_history/${r}/${A||C}`))==null?void 0:k.catch(console.error)},children:[o.jsxs(mr,{children:[o.jsx(Ic,{fluid:!0,p:"md",children:o.jsx(Ae,{children:`${t} ${n}`})}),o.jsxs(Et.List,{children:[o.jsx(Et.Tab,{value:"diff",children:"Diff"}),o.jsx(Et.Tab,{value:"raw",children:"Raw"})]})]}),o.jsxs(ot,{children:[m&&o.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)}),o.jsx(Et.Panel,{value:"diff",children:j?o.jsxs(o.Fragment,{children:[o.jsxs("ul",{children:[o.jsxs("li",{children:["Current: ",(T=S.meta)==null?void 0:T.versionId]}),o.jsxs("li",{children:["Previous:"," ",o.jsx(mt,{to:`/${t}/${n}/_history/${(D=j.meta)==null?void 0:D.versionId}`,children:(E=j.meta)==null?void 0:E.versionId})]})]}),o.jsx($Y,{original:j,revised:S})]}):o.jsxs(o.Fragment,{children:[o.jsxs("ul",{children:[o.jsxs("li",{children:["Current: ",(R=S.meta)==null?void 0:R.versionId]}),o.jsx("li",{children:"Previous: (none)"})]}),o.jsx("pre",{children:JSON.stringify(S,void 0,2)})]})}),o.jsx(Et.Panel,{value:"raw",children:o.jsx("pre",{children:JSON.stringify(S,void 0,2)})})]})]})}function Hee(){const{resourceType:e,id:t}=qt(),n=wn(),[r,i]=v.useState({resourceType:"Subscription",filters:[{code:"url",operator:ue.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return o.jsx(ot,{children:o.jsx(IQ,{search:r,onClick:s=>{var c;return(c=n(`/${s.resource.resourceType}/${s.resource.id}`))==null?void 0:c.catch(console.error)},onChange:s=>i(s.definition),hideFilters:!0})})}function qee(e){const t=_e(),{resource:n,opened:r,onClose:i}=e,[s,c]=v.useState(!1),[u,f]=v.useState(),[p,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:s&&u?zt(u):void 0,verbose:p}),Oe({color:"green",message:"Done"}),i()}catch(y){Oe({color:"red",message:Ye(y),autoClose:!1})}},[t,n,i,s,u,p]);return o.jsx(Un,{opened:r,onClose:i,title:"Resend Subscriptions",children:o.jsx(pt,{onSubmit:g,children:o.jsxs(Ge,{children:[o.jsx(zn,{label:"Choose subscription (all subscriptions by default)",onChange:y=>c(y.currentTarget.checked)}),s&&o.jsx(il,{name:"subscription",resourceType:"Subscription",placeholder:"Subscription",onChange:f}),o.jsx(zn,{label:"Verbose mode",onChange:y=>m(y.currentTarget.checked)}),o.jsx(je,{justify:"flex-end",children:o.jsx(Ne,{type:"submit",children:"Resend"})})]})})})}function tR(){const e=_e(),t=Jp(),{resourceType:n,id:r}=qt(),i={reference:n+"/"+r},[s,c]=v.useState(),u=op(!1);function f(D,E){return e.updateResource({...D,priority:E})}function p(D,E){f(D,"stat").then(E).catch(console.error)}function m(D,E){f(D,"routine").then(E).catch(console.error)}function g(D){t(`/${D.resourceType}/${D.id}`)}function y(D){t(`/${D.resourceType}/${D.id}/edit`)}function b(D){t(`/${D.resourceType}/${D.id}/delete`)}function S(D){c(D),u[1].open()}function j(D){var E;t(`/${D.resourceType}/${D.id}/_history/${(E=D.meta)==null?void 0:E.versionId}`)}function C(D,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(D.resourceType,D.id,"$aws-textract"),{}).then(()=>{E(),As({id:R,title:"AWS Textract Successful",message:"Text successfully extracted.",color:"green",icon:o.jsx(eo,{size:"1rem"}),loading:!1,withCloseButton:!0})}).catch(A=>As({id:R,title:"AWS Textract Error",color:"red",message:Ye(A),icon:o.jsx(Hs,{size:"1rem"}),loading:!1,withCloseButton:!0}))}function T(D){var P;const{primaryResource:E,currentResource:R,reloadTimeline:A}=D,k=R.resourceType===E.resourceType&&R.id===E.id,M=R.resourceType==="Communication"&&R.priority!=="stat",I=R.resourceType==="Communication"&&R.priority==="stat",$=k,V=!k,Y=!k,Q=!k,J=(P=e.getProjectMembership())==null?void 0:P.admin,G=J,K=xJ()&&(R.resourceType==="DocumentReference"||R.resourceType==="Media");return o.jsxs(Ce.Dropdown,{children:[o.jsx(Ce.Label,{children:"Resource"}),M&&o.jsx(Ce.Item,{leftSection:o.jsx(CF,{size:14}),onClick:()=>p(R,A),"aria-label":`Pin ${zt(R)}`,children:"Pin"}),I&&o.jsx(Ce.Item,{leftSection:o.jsx(EF,{size:14}),onClick:()=>m(R,A),"aria-label":`Unpin ${zt(R)}`,children:"Unpin"}),V&&o.jsx(Ce.Item,{leftSection:o.jsx(ME,{size:14}),onClick:()=>g(R),"aria-label":`Details ${zt(R)}`,children:"Details"}),$&&o.jsx(Ce.Item,{leftSection:o.jsx(ME,{size:14}),onClick:()=>j(R),"aria-label":`Details ${zt(R)}`,children:"Details"}),Y&&o.jsx(Ce.Item,{leftSection:o.jsx(n_,{size:14}),onClick:()=>y(R),"aria-label":`Edit ${zt(R)}`,children:"Edit"}),J&&o.jsxs(o.Fragment,{children:[o.jsx(Ce.Divider,{}),o.jsx(Ce.Label,{children:"Admin"}),G&&o.jsx(Ce.Item,{leftSection:o.jsx(DF,{size:14}),onClick:()=>S(R),"aria-label":`Resend Subscriptions ${zt(R)}`,children:"Resend Subscriptions"})]}),K&&o.jsxs(o.Fragment,{children:[o.jsx(Ce.Divider,{}),o.jsx(Ce.Label,{children:"AWS AI"}),o.jsx(Ce.Item,{leftSection:o.jsx(IF,{size:14}),onClick:()=>C(R,A),"aria-label":`AWS Textract ${zt(R)}`,children:"AWS Textract"})]}),Q&&o.jsxs(o.Fragment,{children:[o.jsx(Ce.Divider,{}),o.jsx(Ce.Label,{children:"Danger zone"}),o.jsx(Ce.Item,{color:"red",leftSection:o.jsx(yb,{size:14}),onClick:()=>b(R),"aria-label":`Delete ${zt(R)}`,children:"Delete"})]})]})}return o.jsxs(o.Fragment,{children:[n==="Encounter"&&o.jsx(HG,{encounter:i,getMenu:T}),n==="Patient"&&o.jsx(rW,{patient:i,getMenu:T}),n==="ServiceRequest"&&o.jsx(GY,{serviceRequest:i,getMenu:T}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&o.jsx(FG,{resource:i,getMenu:T}),o.jsx(qee,{resource:s,opened:u[0],onClose:u[1].close},`resend-subscriptions-${s==null?void 0:s.id}`)]})}function Gee(e){const{opened:t,close:n,version:r,loadingStatus:i,handleStatus:s,handleUpgrade:c}=e,[u,f]=v.useState(),[p,m]=v.useState(!1);return v.useEffect(()=>{t&&(u||LV("app-tools-page").then(f).catch(console.error),s())},[t,u,s]),u&&r&&!i?r==="unknown"?o.jsx("p",{children:"Unable to determine the current version of the agent. Check the network connectivity of the agent."}):r.startsWith(u)?o.jsxs("p",{children:["This agent is already on the latest version (",u,")."]}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{children:["Are you sure you want to upgrade this agent from version ",r," to version ",u,"?"]}),o.jsxs(je,{children:[o.jsx(Ne,{onClick:()=>{c(p),n()},"aria-label":"Confirm upgrade",children:"Confirm Upgrade"}),o.jsx(zn,{label:"Force",onChange:g=>m(g.currentTarget.checked)})]})]}):o.jsx(gi,{})}function Qee(){const e=_e(),{id:t}=qt(),n=v.useMemo(()=>({reference:"Agent/"+t}),[t]),[r,i]=v.useState(!1),[s,c]=v.useState(!1),[u,f]=v.useState(!1),[p,m]=v.useState(),[g,y]=v.useState(),[b,S]=v.useState(),[j,C]=v.useState(),[T,D]=v.useState(!1),[E,R]=v.useState(!1),[A,{open:k,close:M}]=op(!1);v.useEffect(()=>{if(r||s||u||T){R(!0);return}R(!1)},[r,s,u,T]);const I=v.useCallback(()=>{i(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(G=>{var K,P,L,z,H,O;m((P=(K=G.parameter)==null?void 0:K.find(U=>U.name==="status"))==null?void 0:P.valueCode),y((z=(L=G.parameter)==null?void 0:L.find(U=>U.name==="version"))==null?void 0:z.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]),$=v.useCallback(G=>{const K=G.host,P=G.pingCount||1;K&&(D(!0),e.pushToAgent(n,K,`PING ${P}`,hn.PING,!0).then(L=>C(L)).catch(L=>J(Ye(L))).finally(()=>D(!1)))},[e,n]),V=v.useCallback(()=>{c(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(G=>{Q("Agent config reloaded successfully.")}).catch(G=>J(Ye(G))).finally(()=>c(!1))},[e,t]),Y=v.useCallback(G=>{f(!0),e.get(e.fhirUrl("Agent",t,"$upgrade",`?force=${G}`),{cache:"reload"}).then(K=>{Q("Agent upgraded successfully.")}).catch(K=>J(Ye(K))).finally(()=>f(!1))},[e,t]);function Q(G){Oe({color:"green",title:"Success",icon:o.jsx(eo,{size:"1rem"}),message:G})}function J(G){Oe({color:"red",title:"Error",message:G,autoClose:!1})}return o.jsxs(ot,{children:[o.jsx(Un,{opened:A,onClose:M,title:"Upgrade Agent",centered:!0,children:o.jsx(Gee,{opened:A,close:M,version:g,loadingStatus:r,handleStatus:I,handleUpgrade:Y})}),o.jsx(Le,{order:1,children:"Agent Tools"}),o.jsxs("div",{style:{marginBottom:10},children:["Agent: ",o.jsx(Lc,{value:n,link:!0})]}),o.jsx(Cn,{my:"lg"}),o.jsx(Le,{order:2,children:"Agent Status"}),o.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."}),o.jsx(Ne,{onClick:I,loading:r,disabled:E&&!r,children:"Get Status"}),!r&&p&&o.jsx(ye,{children:o.jsxs(ye.Tbody,{children:[o.jsxs(ye.Tr,{children:[o.jsx(ye.Td,{children:"Status"}),o.jsx(ye.Td,{children:o.jsx(am,{status:p})})]}),o.jsxs(ye.Tr,{children:[o.jsx(ye.Td,{children:"Version"}),o.jsx(ye.Td,{children:g})]}),o.jsxs(ye.Tr,{children:[o.jsx(ye.Td,{children:"Last Updated"}),o.jsx(ye.Td,{children:gr(b,void 0,{timeZoneName:"longOffset"})})]})]})}),o.jsx(Cn,{my:"lg"}),o.jsx(Le,{order:2,children:"Reload Config"}),o.jsx("p",{children:"Reload the configuration of this agent, syncing it with the current version of the Agent resource on the Medplum server."}),o.jsx(Ne,{onClick:V,loading:s,disabled:E&&!s,"aria-label":"Reload config",children:"Reload Config"}),o.jsx(Cn,{my:"lg"}),o.jsx(Le,{order:2,children:"Upgrade Agent"}),o.jsx("p",{children:"Upgrade the version of this agent, to either the latest (default) or a specified version."}),o.jsx(Ne,{onClick:k,loading:u,disabled:E&&!u,"aria-label":"Upgrade agent",children:"Upgrade"}),o.jsx(Cn,{my:"lg"}),o.jsx(Le,{order:2,children:"Ping from Agent"}),o.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."}),o.jsx(pt,{onSubmit:$,children:o.jsxs(je,{children:[o.jsx(ze,{id:"host",name:"host",placeholder:"ex. 127.0.0.1",label:"IP Address / Hostname",rightSection:o.jsx(_n,{size:24,radius:"xl",variant:"filled",type:"submit","aria-label":"Ping",loading:T,disabled:E&&!T,children:o.jsx(_F,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),o.jsx(Ip,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!T&&j&&o.jsxs(o.Fragment,{children:[o.jsx(Le,{order:5,mt:"sm",mb:0,children:"Last Ping"}),o.jsx("pre",{children:j})]})]})}function Wee(){return o.jsx(CX,{children:o.jsxs(Fe,{errorElement:o.jsx(oJ,{}),children:[o.jsx(Fe,{path:"/signin",element:o.jsx(EJ,{})}),o.jsx(Fe,{path:"/oauth",element:o.jsx(bJ,{})}),o.jsx(Fe,{path:"/resetpassword",element:o.jsx(wJ,{})}),o.jsx(Fe,{path:"/setpassword/:id/:secret",element:o.jsx(CJ,{})}),o.jsx(Fe,{path:"/register",element:o.jsx(SJ,{})}),o.jsx(Fe,{path:"/changepassword",element:o.jsx(rJ,{})}),o.jsx(Fe,{path:"/security",element:o.jsx(jJ,{})}),o.jsx(Fe,{path:"/mfa",element:o.jsx(yJ,{})}),o.jsx(Fe,{path:"/batch",element:o.jsx(tJ,{})}),o.jsx(Fe,{path:"/bulk/:resourceType",element:o.jsx(nJ,{})}),o.jsx(Fe,{path:"/smart",element:o.jsx(TJ,{})}),o.jsx(Fe,{path:"/forms/:id",element:o.jsx(lJ,{})}),o.jsx(Fe,{path:"/admin/super",element:o.jsx(qJ,{})}),o.jsx(Fe,{path:"/admin/super/asyncjob",element:o.jsx($J,{})}),o.jsx(Fe,{path:"/admin/config",element:o.jsx(MJ,{})}),o.jsxs(Fe,{path:"/admin",element:o.jsx(IJ,{}),children:[o.jsx(Fe,{path:"patients",element:o.jsx(OJ,{})}),o.jsx(Fe,{path:"bots/new",element:o.jsx(AJ,{})}),o.jsx(Fe,{path:"bots",element:o.jsx(RJ,{})}),o.jsx(Fe,{path:"clients/new",element:o.jsx(_J,{})}),o.jsx(Fe,{path:"clients",element:o.jsx(DJ,{})}),o.jsx(Fe,{path:"details",element:o.jsx(WT,{})}),o.jsx(Fe,{path:"invite",element:o.jsx(NJ,{})}),o.jsx(Fe,{path:"users",element:o.jsx(QJ,{})}),o.jsx(Fe,{path:"project",element:o.jsx(WT,{})}),o.jsx(Fe,{path:"secrets",element:o.jsx(LJ,{})}),o.jsx(Fe,{path:"sites",element:o.jsx(zJ,{})}),o.jsx(Fe,{path:"members/:membershipId",element:o.jsx(PJ,{})})]}),o.jsx(Fe,{path:"/lab/assays",element:o.jsx(WJ,{})}),o.jsx(Fe,{path:"/lab/panels",element:o.jsx(YJ,{})}),o.jsx(Fe,{path:"/:resourceType/:id/_history/:versionId/:tab",element:o.jsx(eR,{})}),o.jsx(Fe,{path:"/:resourceType/:id/_history/:versionId",element:o.jsx(eR,{})}),o.jsxs(Fe,{path:"/:resourceType/new",element:o.jsx(aJ,{}),children:[o.jsx(Fe,{index:!0,element:o.jsx(hy,{})}),o.jsx(Fe,{path:"form",element:o.jsx(hy,{})}),o.jsx(Fe,{path:"json",element:o.jsx(xee,{})}),o.jsx(Fe,{path:"profiles",element:o.jsx(hy,{})})]}),o.jsxs(Fe,{path:"/:resourceType/:id",element:o.jsx(Fee,{}),children:[o.jsx(Fe,{index:!0,element:o.jsx(tR,{})}),o.jsx(Fe,{path:"apply",element:o.jsx(XJ,{})}),o.jsx(Fe,{path:"apps",element:o.jsx(ZJ,{})}),o.jsx(Fe,{path:"event",element:o.jsx(eee,{})}),o.jsx(Fe,{path:"blame",element:o.jsx(tee,{})}),o.jsx(Fe,{path:"bots",element:o.jsx(Eee,{})}),o.jsx(Fe,{path:"builder",element:o.jsx(uee,{})}),o.jsx(Fe,{path:"checklist",element:o.jsx(dee,{})}),o.jsx(Fe,{path:"delete",element:o.jsx(fee,{})}),o.jsx(Fe,{path:"details",element:o.jsx(mee,{})}),o.jsx(Fe,{path:"edit",element:o.jsx(gee,{})}),o.jsx(Fe,{path:"editor",element:o.jsx(lee,{})}),o.jsx(Fe,{path:"history",element:o.jsx(yee,{})}),o.jsx(Fe,{path:"json",element:o.jsx(bee,{})}),o.jsx(Fe,{path:"preview",element:o.jsx(See,{})}),o.jsx(Fe,{path:"responses",element:o.jsx(Ree,{})}),o.jsx(Fe,{path:"report",element:o.jsx(Aee,{})}),o.jsx(Fe,{path:"ranges",element:o.jsx(Dee,{})}),o.jsx(Fe,{path:"subscriptions",element:o.jsx(Hee,{})}),o.jsx(Fe,{path:"timeline",element:o.jsx(tR,{})}),o.jsx(Fe,{path:"tools",element:o.jsx(Qee,{})}),o.jsx(Fe,{path:"profiles",element:o.jsx(wee,{})}),o.jsx(Fe,{path:"export",element:o.jsx(vee,{})})]}),o.jsx(Fe,{path:"/:resourceType",element:o.jsx(QT,{})}),o.jsx(Fe,{path:"/",element:o.jsx(QT,{})})]})})}function Yee(){const e=_e(),t=e.getUserConfiguration(),n=Mr(),[r]=Zb();return e.isLoading()?o.jsx(gi,{}):o.jsx(_H,{logo:o.jsx(Ui,{size:24}),pathname:n.pathname,searchParams:r,version:qA,menus:Kee(t),displayAddBookmark:!!(t!=null&&t.id),children:o.jsx(v.Suspense,{fallback:o.jsx(gi,{}),children:o.jsx(Wee,{})})})}function Kee(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(s=>({label:s.name,href:s.target,icon:Xee(s.target)})))||[]}}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:o.jsx(yF,{})}]}),t}const nR={Patient:NF,Practitioner:gF,Organization:oF,ServiceRequest:RF,DiagnosticReport:AF,Questionnaire:mF,admin:rF,AccessPolicy:vF,Subscription:LF,batch:jF,Observation:SF};function Xee(e){try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in nR){const n=nR[t];return o.jsx(n,{})}}catch{}return o.jsx(Hp,{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 Zee(){const e=Bd(),t=new GA({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=YX([{path:"*",element:o.jsx(Yee,{})}]),i=c=>r.navigate(c);ZY.createRoot(document.getElementById("root")).render(o.jsx(v.StrictMode,{children:o.jsx(zV,{medplum:t,navigate:i,children:o.jsxs(RR,{theme:n,children:[o.jsx(Za,{position:"bottom-right"}),o.jsx(bX,{router:r})]})})}))}Zee().catch(console.error);
|
|
586
|
-
//# sourceMappingURL=index-
|
|
586
|
+
//# sourceMappingURL=index-DSdcgbUx.js.map
|