@medplum/app 4.5.0 → 4.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -84,7 +84,7 @@ function F3(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&
|
|
|
84
84
|
*
|
|
85
85
|
* Copy of "partysocket" from Partykit team, a fork of the original "Reconnecting WebSocket"
|
|
86
86
|
* https://github.com/partykit/partykit/blob/main/packages/partysocket
|
|
87
|
-
*/const Ec={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let XE=!1;function IV(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");Ec.Event=globalThis.Event,Ec.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},Ec.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function zV(e,t){if(!e)throw new Error(t)}function Sh(e){return new e.constructor(e.type,e)}const $s={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let ZE=!1;class Za extends vm{constructor(t,n,r={}){XE||(IV(),XE=!0),super(),this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._closeCalled=!1,this._messageQueue=[],this._debugLogger=console.log.bind(console),this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=o=>{this._debug("open event");const{minUptime:l=$s.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),l),zV(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(c=>this._ws?.send(c)),this._messageQueue=[],this.onopen&&this.onopen(o),this.dispatchEvent(Sh(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(Sh(o))},this._handleError=o=>{this._debug("error event",o.message),this._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(o),this._debug("exec error listeners"),this.dispatchEvent(Sh(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(Sh(o))},this._url=t,this._protocols=n,this._options=r,this._options.startClosed&&(this._shouldReconnect=!1),this._options.binaryType?this._binaryType=this._options.binaryType:this._binaryType="blob",this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return Za.CONNECTING}get OPEN(){return Za.OPEN}get CLOSING(){return Za.CLOSING}get CLOSED(){return Za.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((n,r)=>(typeof r=="string"?n+=r.length:r instanceof Blob?n+=r.size:n+=r.byteLength,n),0)+(this._ws?.bufferedAmount??0)}get extensions(){return this._ws?.extensions??""}get protocol(){return this._ws?.protocol??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?Za.CLOSED:Za.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=$s.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=$s.reconnectionDelayGrowFactor,minReconnectionDelay:n=$s.minReconnectionDelay,maxReconnectionDelay:r=$s.maxReconnectionDelay}=this._options;let o=0;return this._retryCount>0&&(o=n*Math.pow(t,this._retryCount-1),o>r&&(o=r)),this._debug("next delay",o),o}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=$s.maxRetries,connectionTimeout:n=$s.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"&&!ZE&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),ZE=!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 Ec.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Ec.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new Ec.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 $V=5e3;class ux extends vm{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 UV{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new ux(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class BV{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof bA))throw new ft(gn("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new ft(gn("Not a valid URL"))}const l=r?.ReconnectingWebSocket?new r.ReconnectingWebSocket(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger}):new Za(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger});this.medplum=t,this.ws=l,this.masterSubEmitter=new ux,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=r?.pingIntervalMs??$V,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{try{const r=JSON.parse(n.data);if(r.type==="pong"){this.waitingForPong=!1;return}const o=r,l=o?.entry?.[0]?.resource;if(l.type==="heartbeat"){this.masterSubEmitter?.dispatchEvent({type:"heartbeat",payload:o});return}if(l.type==="handshake"){const d=rl(l.subscription),f={type:"connect",payload:{subscriptionId:d}};this.masterSubEmitter?.dispatchEvent(f);const p=this.criteriaEntriesBySubscriptionId.get(d);if(!p){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}p.connecting=!1,p.emitter.dispatchEvent({...f});return}this.masterSubEmitter?.dispatchEvent({type:"message",payload:o});const c=this.criteriaEntriesBySubscriptionId.get(rl(l.subscription));if(!c){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}c.emitter.dispatchEvent({type:"message",payload:o})}catch(r){console.error(r);const o={type:"error",payload:r};this.masterSubEmitter?.dispatchEvent(o);for(const l of this.getAllCriteriaEmitters())l.dispatchEvent({...o})}}),t.addEventListener("error",()=>{const n={type:"error",payload:new ft(K$(new Error("WebSocket error")))};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n})}),t.addEventListener("close",()=>{const n={type:"close"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),this.masterSubEmitter?.removeAllListeners())}),t.addEventListener("open",()=>{const n={type:"open"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.refreshAllSubscriptions().catch(console.error),this.pingTimer||(this.pingTimer=setInterval(()=>{if(this.waitingForPong){this.waitingForPong=!1,t.reconnect();return}t.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0},this.pingIntervalMs))}),this.medplum.addEventListener("change",()=>{const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&this.currentProfile?.id!==n.id&&this.ws.reconnect(),this.currentProfile=n})}emitError(t,n){const r={type:"error",payload:n};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){const{subscriptionId:n}=t;if(n){const r={type:"disconnect",payload:{subscriptionId:n}};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){let n=t?.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${_t(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:t.criteria})).id);const{parameter:r}=await this.medplum.get(`fhir/R4/Subscription/${n}/$get-ws-binding-token`),o=r?.find(c=>c.name==="token")?.valueString,l=r?.find(c=>c.name==="websocket-url")?.valueUrl;if(!o)throw new ft(gn("Failed to get token"));if(!l)throw new ft(gn("Failed to get URL from $get-ws-binding-token"));return[n,o]}maybeGetCriteriaEntry(t,n){const r=this.criteriaEntries.get(t);if(r){if(!n)return r.bareCriteria;for(const o of r.criteriaWithProps)if(Co(n,o.subscriptionProps))return o}}getAllCriteriaEmitters(){const t=[];for(const n of this.criteriaEntries.values()){n.bareCriteria&&t.push(n.bareCriteria.emitter);for(const r of n.criteriaWithProps)t.push(r.emitter)}return t}addCriteriaEntry(t){const{criteria:n,subscriptionProps:r}=t;let o;this.criteriaEntries.has(n)?o=this.criteriaEntries.get(n):(o={criteriaWithProps:[]},this.criteriaEntries.set(n,o)),r?o.criteriaWithProps.push(t):o.bareCriteria=t}removeCriteriaEntry(t){const{criteria:n,subscriptionProps:r,subscriptionId:o,token:l}=t;if(!this.criteriaEntries.has(n))return;const c=this.criteriaEntries.get(n);r?c.criteriaWithProps=c.criteriaWithProps.filter(d=>{const f=d.subscriptionProps;return!Co(r,f)}):c.bareCriteria=void 0,!c.bareCriteria&&c.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),this.masterSubEmitter?._removeCriteria(n)),o&&this.criteriaEntriesBySubscriptionId.delete(o),l&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:l}}))}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 o=new UV(t,n);return this.addCriteriaEntry(o),this.subscribeToCriteria(o).catch(console.error),o.emitter}removeCriteria(t,n){const r=this.maybeGetCriteriaEntry(t,n);if(!r){console.warn("Criteria not known to `SubscriptionManager`. Possibly called remove too many times.");return}r.refCount-=1,!(r.refCount>0)&&(this.maybeEmitDisconnect(r),this.removeCriteriaEntry(r))}getWebSocket(){return this.ws}closeWebSocket(){this.wsClosed||(this.wsClosed=!0,this.ws.close())}reconnectWebSocket(){this.ws.reconnect(),this.wsClosed=!1}getCriteriaCount(){return this.getAllCriteriaEmitters().length}getMasterEmitter(){return this.masterSubEmitter||(this.masterSubEmitter=new ux(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const xA="4.5.0-e2f7d4ec4",VV=ln.FHIR_JSON+", */*; q=0.1",FV="https://api.medplum.com/",HV=1e3,qV=6e4,GV=0,QV=3e5,WV="Binary/",JE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},vc={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"},KV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class bA extends vm{constructor(t){if(super(),this.initComplete=!0,t?.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=t?.fetch??XV(),this.storage=t?.storage??new MV,this.createPdfImpl=t?.createPdf,this.baseUrl=wb(t?.baseUrl??FV),this.fhirBaseUrl=fo(this.baseUrl,t?.fhirUrlPath??"fhir/R4"),this.authorizeUrl=fo(this.baseUrl,t?.authorizeUrl??"oauth2/authorize"),this.tokenUrl=fo(this.baseUrl,t?.tokenUrl??"oauth2/token"),this.logoutUrl=fo(this.baseUrl,t?.logoutUrl??"oauth2/logout"),this.fhircastHubUrl=fo(this.baseUrl,t?.fhircastHubUrl??"fhircast/STU3"),this.clientId=t?.clientId??"",this.clientSecret=t?.clientSecret??"",this.credentialsInHeader=t?.authCredentialsMethod==="header",this.defaultHeaders=t?.defaultHeaders??{},this.onUnauthenticated=t?.onUnauthenticated,this.refreshGracePeriod=t?.refreshGracePeriod??QV,this.cacheTime=t?.cacheTime??(po()?qV:GV),this.cacheTime>0?this.requestCache=new AD(t?.resourceCacheSize??HV):this.requestCache=void 0,t?.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t?.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve(),this.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}async attemptResumeActiveLogin(){const t=this.getActiveLogin();t&&(this.setAccessToken(t.accessToken,t.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}getFhircastHubUrl(){return this.fhircastHubUrl}getDefaultHeaders(){return this.defaultHeaders}clear(){this.storage.clear(),po()&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){this.storage.setString("activeLogin",void 0),this.requestCache?.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.refreshPromise=void 0,this.accessTokenExpires=void 0,this.sessionDetails=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(t){t=t.toString(),this.requestCache?.delete(t)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(t){const n=fo(this.fhirBaseUrl,t);if(this.requestCache)for(const r of this.requestCache.keys())(r.endsWith(n)||r.includes(n+"?"))&&this.requestCache.delete(r)}get(t,n={}){t=t.toString();const r=this.getCacheEntry(t,n);if(r)return r.value;let o;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?o=new Promise((c,d)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:c,reject:d}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):o=this.request("GET",t,n);const l=new Fi(o);return this.setCacheEntry(t,l),l}post(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("POST",t,o)}put(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("PUT",t,o)}patch(t,n,r={}){return t=t.toString(),this.setRequestBody(r,n),this.setRequestContentType(r,ln.JSON_PATCH),this.invalidateUrl(t),this.request("PATCH",t,r)}delete(t,n){return t=t.toString(),this.invalidateUrl(t),this.request("DELETE",t,n)}async startNewUser(t,n){const{codeChallengeMethod:r,codeChallenge:o}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:r,codeChallenge:o},void 0,n)}async startNewProject(t,n){return this.post("auth/newproject",t,void 0,n)}async startNewPatient(t,n){return this.post("auth/newpatient",t,void 0,n)}async startLogin(t,n){return this.post("auth/login",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async startGoogleLogin(t,n){return this.post("auth/google",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async ensureCodeChallenge(t){return t.codeChallenge?t:{...t,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(t){const r=new URLSearchParams(Xn.getSearch()).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){Xn.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,o,l=!0){let c=o;l&&(c=await this.ensureCodeChallenge(o)),Xn.assign(this.getExternalAuthRedirectUri(t,n,r,c,l))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");return this.fetchTokens({grant_type:vc.TokenExchange,subject_token_type:YV.AccessToken,client_id:n,subject_token:t})}getExternalAuthRedirectUri(t,n,r,o,l=!0){const c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",n),c.searchParams.set("redirect_uri",r),c.searchParams.set("scope",o.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(o)),l){const{codeChallenge:d,codeChallengeMethod:f}=o;if(!f)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!d)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");c.searchParams.set("code_challenge_method",f),c.searchParams.set("code_challenge",d)}return c.toString()}fhirUrl(...t){return new URL(fo(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=VU(n)),r}search(t,n,r){const o=this.fhirSearchUrl(t,n),l="search-"+o.toString(),c=this.getCacheEntry(l,r);if(c)return c.value;const d=this.getBundle(o,r);return this.setCacheEntry(l,d),d}searchOne(t,n,r){const o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();const l="searchOne-"+o.toString(),c=this.getCacheEntry(l,r);if(c)return c.value;const d=new Fi(this.search(t,o.searchParams,r).then(f=>f.entry?.[0]?.resource));return this.setCacheEntry(l,d),d}searchResources(t,n,r){const l="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(l,r);if(c)return c.value;const d=new Fi(this.search(t,n,r).then(tT));return this.setCacheEntry(l,d),d}async*searchResourcePages(t,n,r){let o=this.fhirSearchUrl(t,n);for(;o;){const l=new URL(o).searchParams;l.has("_count")||l.set("_count","1000");const c=await this.search(t,l,r),d=c.link?.find(f=>f.relation==="next");if(!c.entry?.length&&!d)break;yield tT(c),o=d?.url?new URL(d.url):void 0}}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){const r=this.requestCache?.get(this.fhirUrl(t,n).toString())?.value;return r?.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return JE;const[r,o]=n.split("/");if(!(!r||!o))return this.getCached(r,o)}readResource(t,n,r){if(!n)throw new Error('The "id" parameter cannot be null, undefined, or an empty string.');return this.get(this.fhirUrl(t,n),r)}readReference(t,n){const r=t.reference;if(!r)return new Fi(Promise.reject(new Error("Missing reference")));if(r==="system")return new Fi(Promise.resolve(JE));const[o,l]=r.split("/");return!o||!l?new Fi(Promise.reject(new Error("Invalid reference"))):this.readResource(o,l,n)}requestSchema(t){if(ID(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Fi((async()=>{const l=`{
|
|
87
|
+
*/const Ec={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let XE=!1;function IV(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");Ec.Event=globalThis.Event,Ec.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},Ec.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function zV(e,t){if(!e)throw new Error(t)}function Sh(e){return new e.constructor(e.type,e)}const $s={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let ZE=!1;class Za extends vm{constructor(t,n,r={}){XE||(IV(),XE=!0),super(),this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._closeCalled=!1,this._messageQueue=[],this._debugLogger=console.log.bind(console),this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=o=>{this._debug("open event");const{minUptime:l=$s.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),l),zV(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(c=>this._ws?.send(c)),this._messageQueue=[],this.onopen&&this.onopen(o),this.dispatchEvent(Sh(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(Sh(o))},this._handleError=o=>{this._debug("error event",o.message),this._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(o),this._debug("exec error listeners"),this.dispatchEvent(Sh(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(Sh(o))},this._url=t,this._protocols=n,this._options=r,this._options.startClosed&&(this._shouldReconnect=!1),this._options.binaryType?this._binaryType=this._options.binaryType:this._binaryType="blob",this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return Za.CONNECTING}get OPEN(){return Za.OPEN}get CLOSING(){return Za.CLOSING}get CLOSED(){return Za.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((n,r)=>(typeof r=="string"?n+=r.length:r instanceof Blob?n+=r.size:n+=r.byteLength,n),0)+(this._ws?.bufferedAmount??0)}get extensions(){return this._ws?.extensions??""}get protocol(){return this._ws?.protocol??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?Za.CLOSED:Za.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=$s.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=$s.reconnectionDelayGrowFactor,minReconnectionDelay:n=$s.minReconnectionDelay,maxReconnectionDelay:r=$s.maxReconnectionDelay}=this._options;let o=0;return this._retryCount>0&&(o=n*Math.pow(t,this._retryCount-1),o>r&&(o=r)),this._debug("next delay",o),o}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:t=$s.maxRetries,connectionTimeout:n=$s.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"&&!ZE&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),ZE=!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 Ec.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Ec.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new Ec.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 $V=5e3;class ux extends vm{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 UV{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new ux(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class BV{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof bA))throw new ft(gn("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new ft(gn("Not a valid URL"))}const l=r?.ReconnectingWebSocket?new r.ReconnectingWebSocket(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger}):new Za(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger});this.medplum=t,this.ws=l,this.masterSubEmitter=new ux,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=r?.pingIntervalMs??$V,this.currentProfile=t.getProfile(),this.setupListeners()}setupListeners(){const t=this.ws;t.addEventListener("message",n=>{try{const r=JSON.parse(n.data);if(r.type==="pong"){this.waitingForPong=!1;return}const o=r,l=o?.entry?.[0]?.resource;if(l.type==="heartbeat"){this.masterSubEmitter?.dispatchEvent({type:"heartbeat",payload:o});return}if(l.type==="handshake"){const d=rl(l.subscription),f={type:"connect",payload:{subscriptionId:d}};this.masterSubEmitter?.dispatchEvent(f);const p=this.criteriaEntriesBySubscriptionId.get(d);if(!p){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}p.connecting=!1,p.emitter.dispatchEvent({...f});return}this.masterSubEmitter?.dispatchEvent({type:"message",payload:o});const c=this.criteriaEntriesBySubscriptionId.get(rl(l.subscription));if(!c){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}c.emitter.dispatchEvent({type:"message",payload:o})}catch(r){console.error(r);const o={type:"error",payload:r};this.masterSubEmitter?.dispatchEvent(o);for(const l of this.getAllCriteriaEmitters())l.dispatchEvent({...o})}}),t.addEventListener("error",()=>{const n={type:"error",payload:new ft(K$(new Error("WebSocket error")))};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n})}),t.addEventListener("close",()=>{const n={type:"close"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),this.masterSubEmitter?.removeAllListeners())}),t.addEventListener("open",()=>{const n={type:"open"};this.masterSubEmitter?.dispatchEvent(n);for(const r of this.getAllCriteriaEmitters())r.dispatchEvent({...n});this.refreshAllSubscriptions().catch(console.error),this.pingTimer||(this.pingTimer=setInterval(()=>{if(this.waitingForPong){this.waitingForPong=!1,t.reconnect();return}t.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0},this.pingIntervalMs))}),this.medplum.addEventListener("change",()=>{const n=this.medplum.getProfile();this.currentProfile&&n===void 0?this.ws.close():n&&this.currentProfile?.id!==n.id&&this.ws.reconnect(),this.currentProfile=n})}emitError(t,n){const r={type:"error",payload:n};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}maybeEmitDisconnect(t){const{subscriptionId:n}=t;if(n){const r={type:"disconnect",payload:{subscriptionId:n}};this.masterSubEmitter?.dispatchEvent(r),t.emitter.dispatchEvent({...r})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}async getTokenForCriteria(t){let n=t?.subscriptionId;n||(n=(await this.medplum.createResource({...t.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${_t(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:t.criteria})).id);const{parameter:r}=await this.medplum.get(`fhir/R4/Subscription/${n}/$get-ws-binding-token`),o=r?.find(c=>c.name==="token")?.valueString,l=r?.find(c=>c.name==="websocket-url")?.valueUrl;if(!o)throw new ft(gn("Failed to get token"));if(!l)throw new ft(gn("Failed to get URL from $get-ws-binding-token"));return[n,o]}maybeGetCriteriaEntry(t,n){const r=this.criteriaEntries.get(t);if(r){if(!n)return r.bareCriteria;for(const o of r.criteriaWithProps)if(Co(n,o.subscriptionProps))return o}}getAllCriteriaEmitters(){const t=[];for(const n of this.criteriaEntries.values()){n.bareCriteria&&t.push(n.bareCriteria.emitter);for(const r of n.criteriaWithProps)t.push(r.emitter)}return t}addCriteriaEntry(t){const{criteria:n,subscriptionProps:r}=t;let o;this.criteriaEntries.has(n)?o=this.criteriaEntries.get(n):(o={criteriaWithProps:[]},this.criteriaEntries.set(n,o)),r?o.criteriaWithProps.push(t):o.bareCriteria=t}removeCriteriaEntry(t){const{criteria:n,subscriptionProps:r,subscriptionId:o,token:l}=t;if(!this.criteriaEntries.has(n))return;const c=this.criteriaEntries.get(n);r?c.criteriaWithProps=c.criteriaWithProps.filter(d=>{const f=d.subscriptionProps;return!Co(r,f)}):c.bareCriteria=void 0,!c.bareCriteria&&c.criteriaWithProps.length===0&&(this.criteriaEntries.delete(n),this.masterSubEmitter?._removeCriteria(n)),o&&this.criteriaEntriesBySubscriptionId.delete(o),l&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:l}}))}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 o=new UV(t,n);return this.addCriteriaEntry(o),this.subscribeToCriteria(o).catch(console.error),o.emitter}removeCriteria(t,n){const r=this.maybeGetCriteriaEntry(t,n);if(!r){console.warn("Criteria not known to `SubscriptionManager`. Possibly called remove too many times.");return}r.refCount-=1,!(r.refCount>0)&&(this.maybeEmitDisconnect(r),this.removeCriteriaEntry(r))}getWebSocket(){return this.ws}closeWebSocket(){this.wsClosed||(this.wsClosed=!0,this.ws.close())}reconnectWebSocket(){this.ws.reconnect(),this.wsClosed=!1}getCriteriaCount(){return this.getAllCriteriaEmitters().length}getMasterEmitter(){return this.masterSubEmitter||(this.masterSubEmitter=new ux(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const xA="4.5.1-199a27ba6",VV=ln.FHIR_JSON+", */*; q=0.1",FV="https://api.medplum.com/",HV=1e3,qV=6e4,GV=0,QV=3e5,WV="Binary/",JE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},vc={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"},KV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class bA extends vm{constructor(t){if(super(),this.initComplete=!0,t?.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=t?.fetch??XV(),this.storage=t?.storage??new MV,this.createPdfImpl=t?.createPdf,this.baseUrl=wb(t?.baseUrl??FV),this.fhirBaseUrl=fo(this.baseUrl,t?.fhirUrlPath??"fhir/R4"),this.authorizeUrl=fo(this.baseUrl,t?.authorizeUrl??"oauth2/authorize"),this.tokenUrl=fo(this.baseUrl,t?.tokenUrl??"oauth2/token"),this.logoutUrl=fo(this.baseUrl,t?.logoutUrl??"oauth2/logout"),this.fhircastHubUrl=fo(this.baseUrl,t?.fhircastHubUrl??"fhircast/STU3"),this.clientId=t?.clientId??"",this.clientSecret=t?.clientSecret??"",this.credentialsInHeader=t?.authCredentialsMethod==="header",this.defaultHeaders=t?.defaultHeaders??{},this.onUnauthenticated=t?.onUnauthenticated,this.refreshGracePeriod=t?.refreshGracePeriod??QV,this.cacheTime=t?.cacheTime??(po()?qV:GV),this.cacheTime>0?this.requestCache=new AD(t?.resourceCacheSize??HV):this.requestCache=void 0,t?.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t?.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve(),this.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}async attemptResumeActiveLogin(){const t=this.getActiveLogin();t&&(this.setAccessToken(t.accessToken,t.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}getFhircastHubUrl(){return this.fhircastHubUrl}getDefaultHeaders(){return this.defaultHeaders}clear(){this.storage.clear(),po()&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){this.storage.setString("activeLogin",void 0),this.requestCache?.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.refreshPromise=void 0,this.accessTokenExpires=void 0,this.sessionDetails=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(t){t=t.toString(),this.requestCache?.delete(t)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(t){const n=fo(this.fhirBaseUrl,t);if(this.requestCache)for(const r of this.requestCache.keys())(r.endsWith(n)||r.includes(n+"?"))&&this.requestCache.delete(r)}get(t,n={}){t=t.toString();const r=this.getCacheEntry(t,n);if(r)return r.value;let o;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?o=new Promise((c,d)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:c,reject:d}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):o=this.request("GET",t,n);const l=new Fi(o);return this.setCacheEntry(t,l),l}post(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("POST",t,o)}put(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("PUT",t,o)}patch(t,n,r={}){return t=t.toString(),this.setRequestBody(r,n),this.setRequestContentType(r,ln.JSON_PATCH),this.invalidateUrl(t),this.request("PATCH",t,r)}delete(t,n){return t=t.toString(),this.invalidateUrl(t),this.request("DELETE",t,n)}async startNewUser(t,n){const{codeChallengeMethod:r,codeChallenge:o}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:r,codeChallenge:o},void 0,n)}async startNewProject(t,n){return this.post("auth/newproject",t,void 0,n)}async startNewPatient(t,n){return this.post("auth/newpatient",t,void 0,n)}async startLogin(t,n){return this.post("auth/login",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async startGoogleLogin(t,n){return this.post("auth/google",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async ensureCodeChallenge(t){return t.codeChallenge?t:{...t,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(t){const r=new URLSearchParams(Xn.getSearch()).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){Xn.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,o,l=!0){let c=o;l&&(c=await this.ensureCodeChallenge(o)),Xn.assign(this.getExternalAuthRedirectUri(t,n,r,c,l))}async exchangeExternalAccessToken(t,n){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");return this.fetchTokens({grant_type:vc.TokenExchange,subject_token_type:YV.AccessToken,client_id:n,subject_token:t})}getExternalAuthRedirectUri(t,n,r,o,l=!0){const c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",n),c.searchParams.set("redirect_uri",r),c.searchParams.set("scope",o.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(o)),l){const{codeChallenge:d,codeChallengeMethod:f}=o;if(!f)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!d)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");c.searchParams.set("code_challenge_method",f),c.searchParams.set("code_challenge",d)}return c.toString()}fhirUrl(...t){return new URL(fo(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=VU(n)),r}search(t,n,r){const o=this.fhirSearchUrl(t,n),l="search-"+o.toString(),c=this.getCacheEntry(l,r);if(c)return c.value;const d=this.getBundle(o,r);return this.setCacheEntry(l,d),d}searchOne(t,n,r){const o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();const l="searchOne-"+o.toString(),c=this.getCacheEntry(l,r);if(c)return c.value;const d=new Fi(this.search(t,o.searchParams,r).then(f=>f.entry?.[0]?.resource));return this.setCacheEntry(l,d),d}searchResources(t,n,r){const l="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(l,r);if(c)return c.value;const d=new Fi(this.search(t,n,r).then(tT));return this.setCacheEntry(l,d),d}async*searchResourcePages(t,n,r){let o=this.fhirSearchUrl(t,n);for(;o;){const l=new URL(o).searchParams;l.has("_count")||l.set("_count","1000");const c=await this.search(t,l,r),d=c.link?.find(f=>f.relation==="next");if(!c.entry?.length&&!d)break;yield tT(c),o=d?.url?new URL(d.url):void 0}}valueSetExpand(t,n){const r=this.fhirUrl("ValueSet","$expand");return r.search=new URLSearchParams(t).toString(),this.get(r.toString(),n)}getCached(t,n){const r=this.requestCache?.get(this.fhirUrl(t,n).toString())?.value;return r?.isOk()?r.read():void 0}getCachedReference(t){const n=t.reference;if(!n)return;if(n==="system")return JE;const[r,o]=n.split("/");if(!(!r||!o))return this.getCached(r,o)}readResource(t,n,r){if(!n)throw new Error('The "id" parameter cannot be null, undefined, or an empty string.');return this.get(this.fhirUrl(t,n),r)}readReference(t,n){const r=t.reference;if(!r)return new Fi(Promise.reject(new Error("Missing reference")));if(r==="system")return new Fi(Promise.resolve(JE));const[o,l]=r.split("/");return!o||!l?new Fi(Promise.reject(new Error("Invalid reference"))):this.readResource(o,l,n)}requestSchema(t){if(ID(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Fi((async()=>{const l=`{
|
|
88
88
|
StructureDefinitionList(_filter: "name eq ${t}") {
|
|
89
89
|
resourceType,
|
|
90
90
|
name,
|
|
@@ -604,4 +604,4 @@ Please change the parent <Route path="${E}"> to <Route path="${E==="/"?"*":`${E}
|
|
|
604
604
|
}
|
|
605
605
|
]
|
|
606
606
|
}`,kne="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 Nne(){const e=Re(),{id:t}=Ut(),[n,r]=v.useState(),[o,l]=v.useState(),[c,d]=v.useState(Pne),[f,p]=v.useState(kne),[m,g]=v.useState(ln.FHIR_JSON),x=v.useRef(null),b=v.useRef(null),[w,j]=v.useState(!1);v.useEffect(()=>{e.readResource("Bot",t).then(async A=>{r(A),l(await One(e,A))}).catch(A=>Ne({color:"red",message:Ye(A),autoClose:!1}))},[e,t]);const C=v.useCallback(async()=>id(x.current,{command:"getValue"}),[]),T=v.useCallback(async()=>id(x.current,{command:"getOutput"}),[]),E=v.useCallback(async()=>m===ln.FHIR_JSON?JSON.parse(c):f,[m,c,f]),R=v.useCallback(async A=>{A.preventDefault(),A.stopPropagation(),j(!0);try{const k=await C(),M=await T(),$=await e.createAttachment({data:k,filename:"index.ts",contentType:"text/typescript"}),U=await e.createAttachment({data:M,filename:"index.js",contentType:"text/typescript"}),J=[{op:"add",path:"/sourceCode",value:$},{op:"add",path:"/executableCode",value:U}];await e.patchResource("Bot",t,J),Ne({color:"green",message:"Saved"})}catch(k){Ne({color:"red",message:Ye(k),autoClose:!1})}finally{j(!1)}},[e,t,C,T]),D=v.useCallback(async A=>{A.preventDefault(),A.stopPropagation(),j(!0);try{await e.post(e.fhirUrl("Bot",t,"$deploy")),Ne({color:"green",message:"Deployed"})}catch(k){Ne({color:"red",message:Ye(k),autoClose:!1})}finally{j(!1)}},[e,t]),P=v.useCallback(async A=>{A.preventDefault(),A.stopPropagation(),j(!0);try{const k=await E(),M=await e.post(e.fhirUrl("Bot",t,"$execute"),k,m);await id(b.current,{command:"setValue",value:M}),Ne({color:"green",message:"Success"})}catch(k){Ne({color:"red",message:Ye(k),autoClose:!1})}finally{j(!1)}},[e,t,E,m]);return!n||o===void 0?null:a.jsxs(hr,{m:0,gutter:0,style:{overflow:"hidden"},children:[a.jsx(hr.Col,{span:8,children:a.jsxs(Tr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",mih:400,children:[a.jsx(Ane,{iframeRef:x,language:"typescript",module:"commonjs",testId:"code-frame",defaultValue:o,minHeight:"528px"}),a.jsxs(ye,{justify:"flex-end",gap:"xs",children:[a.jsx(ke,{type:"button",onClick:R,loading:w,leftSection:a.jsx(FH,{size:"1rem"}),children:"Save"}),a.jsx(ke,{type:"button",onClick:D,loading:w,leftSection:a.jsx($b,{size:"1rem"}),children:"Deploy"}),a.jsx(ke,{type:"button",onClick:P,loading:w,leftSection:a.jsx(Aq,{size:"1rem"}),children:"Execute"})]})]})}),a.jsxs(hr.Col,{span:4,children:[a.jsxs(Tr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[a.jsx(on,{data:[{label:"FHIR",value:ln.FHIR_JSON},{label:"HL7",value:ln.HL7_V2}],onChange:A=>g(A.currentTarget.value)}),m===ln.FHIR_JSON?a.jsx(Wc,{value:c,onChange:A=>d(A),autosize:!0,minRows:15}):a.jsx("textarea",{className:_ne.hl7Input,value:f,onChange:A=>p(A.currentTarget.value),rows:15})]}),a.jsx(Tr,{m:2,p:"xs",shadow:"md",children:a.jsx(Dne,{iframeRef:b,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function One(e,t){if(t.sourceCode?.url){const n=t.sourceCode.url?.split("/")?.find(KD);return(await e.download(e.fhirUrl("Binary",n))).text()}return t.code??""}function Tl(e){let t=e.meta;return t&&(t={...t,lastUpdated:void 0,versionId:void 0,author:void 0}),{...e,meta:t}}function Mne(){const e=Re(),{resourceType:t,id:n}=Ut(),r={reference:t+"/"+n},o=v.useCallback(l=>{e.updateResource(Tl(l)).then(()=>{Ne({color:"green",message:"Success"})}).catch(c=>{Ne({color:"red",message:Ye(c),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return a.jsx(lt,{children:a.jsx(PK,{value:r,onSubmit:o})});case"Questionnaire":return a.jsx(lt,{children:a.jsx(oX,{questionnaire:r,onSubmit:o})});default:return null}}function Lne(){const{resourceType:e,id:t}=Ut(),n=Gt({reference:e+"/"+t}),r=wn();return n?a.jsx(lt,{children:a.jsx(NX,{value:n,onStart:(o,l)=>r(`/forms/${rl(l)}`)?.catch(console.error),onEdit:(o,l,c)=>r(`/${c.reference}}`)?.catch(console.error)})}):null}function Ine(){const e=Re(),{resourceType:t,id:n}=Ut(),r=wn();return a.jsxs(lt,{children:[a.jsxs("p",{children:["Are you sure you want to delete this ",t,"?"]}),a.jsx(ke,{color:"red",onClick:()=>{e.deleteResource(t,n).then(()=>r(`/${t}`)?.catch(console.error)).catch(o=>Ne({color:"red",message:Ye(o),autoClose:!1}))},children:"Delete"})]})}const zne="_selectProfileBtn_tbaz6_1",$ne="_chevron_tbaz6_13",ER={selectProfileBtn:zne,chevron:$ne};function Une(){const{resourceType:e,id:t}=Ut(),n=Gt({reference:e+"/"+t}),[r,o]=v.useState(),l=gl({onDropdownClose:()=>l.resetSelectedOption()}),c=v.useMemo(()=>{if(Rn(n?.meta?.profile))return[a.jsx(Xe.Option,{value:"",children:"None"},""),...n.meta.profile.map(f=>a.jsx(Xe.Option,{value:f,children:f},f))]},[n?.meta?.profile]);if(v.useEffect(()=>{n?.meta?.profile?.length===1&&o(n.meta.profile[0])},[n?.meta?.profile]),!n)return null;let d;return Rn(c)&&(d=a.jsx(ye,{justify:"flex-end",children:a.jsxs(Be,{align:"flex-end",gap:"xs",children:[a.jsxs(Xe,{store:l,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:f=>{o(f),l.closeDropdown()},children:[a.jsx(Xe.Target,{children:a.jsx(sr,{onClick:()=>l.toggleDropdown(),children:a.jsxs(Pd,{fw:"bold",fs:"sm",className:ER.selectProfileBtn,children:[a.jsx("span",{children:"Pick profile"}),a.jsx(zb,{stroke:1.5,className:ER.chevron})]})})}),a.jsx(Xe.Dropdown,{w:"max-content",children:a.jsx(Xe.Options,{children:c})})]}),a.jsx(ce,{children:r?a.jsxs(a.Fragment,{children:[a.jsx(Te,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),a.jsx(Te,{span:!0,size:"sm",children:r||"Nothing selected"})]}):a.jsx(Te,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),a.jsx(lt,{children:a.jsxs(Be,{gap:"xl",children:[d,a.jsx(tS,{value:n,profileUrl:r})]})})}function Bne(){const e=Re(),{resourceType:t,id:n}=Ut(),[r,o]=v.useState(),[l,c]=v.useState(),d=wn(),[f,p]=v.useState();v.useEffect(()=>{e.readResource(t,n).then(b=>{o(ii(b)),c(ii(b))}).catch(b=>{p(qt(b)),Ne({color:"red",message:Ye(b),autoClose:!1})})},[e,t,n]);const m=v.useCallback(b=>{p(void 0),e.updateResource(Tl(b)).then(()=>{d(`/${t}/${n}/details`)?.catch(console.error),Ne({id:"succes",color:"green",message:"Success"})}).catch(w=>{p(qt(w)),Ne({color:"red",message:Ye(w),autoClose:!1})})},[e,t,n,d]),g=v.useCallback(b=>{p(void 0);const w=bP.createPatch(r,b);e.patchResource(t,n,w).then(()=>{d(`/${t}/${n}/details`)?.catch(console.error),Ne({id:"succes",color:"green",message:"Success"})}).catch(j=>{p(qt(j)),Ne({color:"red",message:Ye(j),autoClose:!1})})},[e,t,n,r,d]),x=v.useCallback(()=>d(`/${t}/${n}/delete`)?.catch(console.error),[d,t,n]);return l?a.jsx(lt,{children:a.jsx(vp,{defaultValue:l,onSubmit:m,onPatch:g,onDelete:x,outcome:f})}):null}function Vne(){const{resourceType:e,id:t}=Ut(),n=Gt({reference:e+"/"+t});return n?a.jsx(lt,{maw:700,children:n.resourceType==="Patient"?a.jsx(EK,{patient:n}):a.jsx(ya,{icon:a.jsx(bl,{size:16}),title:"Unsupported export type",color:"red",children:"This page is only supported for Patient resources"})}):null}function Pk({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,o=Re(),[l,c]=v.useState();return v.useEffect(()=>{o.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(d=>{c(d.filter(GQ))}).catch(console.error)},[o,n,r]),a.jsx(Tt,{value:t?.url,onChange:d=>{const f=l?.find(p=>p.url===d);f&&n(f)},children:a.jsx(Tt.List,{children:l?.map(d=>{const f=e.meta?.profile?.includes(d.url),p=f?"This profile is present in this resource's meta.profile property.":"This profile is not included in this resource's meta.profile property.";return a.jsx(Tt.Tab,{value:d.url,title:p,rightSection:f&&a.jsx(pb,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:a.jsx(lG,{size:"90%"})}),children:d.title||d.name},d.url)})})})}function kk(e,t){const n=Re(),r=wn();return{defaultValue:{resourceType:e},handleSubmit:c=>{t&&t(void 0),n.createResource(c).then(d=>r("/"+d.resourceType+"/"+d.id)).catch(d=>{t&&t(qt(d)),Ne({color:"red",message:Ye(d),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function Uy(){const{resourceType:e}=Ut(),t=Gr(),[n,r]=v.useState(),{defaultValue:o,handleSubmit:l}=kk(e,r),[c,d]=v.useState(),f=t.pathname.toLowerCase().endsWith("profiles"),p=v.useCallback(m=>{const g=Tl(m);c&&tA(g,c.url),l(g)},[c,l]);return f?a.jsx(lt,{children:a.jsxs(Be,{children:[a.jsx(Pk,{resource:o,currentProfile:c,onChange:d}),c?a.jsx(vp,{defaultValue:o,onSubmit:p,outcome:n,profileUrl:c.url},c.url):a.jsx(Te,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):a.jsx(lt,{children:a.jsx(vp,{defaultValue:o,onSubmit:l,outcome:n})})}function TR(){const e=Re(),{resourceType:t,id:n}=Ut(),r=e.readHistory(t,n).read();return a.jsx(lt,{children:a.jsx(iZ,{history:r})})}function Fne(){const{resourceType:e}=Ut(),[t,n]=v.useState(),{defaultValue:r,handleSubmit:o}=kk(e,n),l=v.useCallback(c=>{o(JSON.parse(c["new-resource"]))},[o]);return a.jsxs(lt,{children:[t&&a.jsx(yr,{outcome:t}),a.jsxs(ut,{onSubmit:l,children:[a.jsx(Wc,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:Ki(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),a.jsx(ye,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:a.jsx(ke,{type:"submit",children:"OK"})})]})]})}function Hne(){const e=Re(),{resourceType:t,id:n}=Ut(),r=Gt({reference:t+"/"+n}),o=wn(),[l,c]=v.useState(),d=v.useCallback(f=>{e.updateResource(Tl(JSON.parse(f.resource))).then(()=>{c(void 0),o(`/${t}/${n}/details`)?.catch(console.error),Ne({color:"green",message:"Success"})}).catch(p=>{Ne({color:"red",message:Ye(p),autoClose:!1})})},[e,t,n,o]);return r?a.jsxs(lt,{children:[l&&a.jsx(yr,{outcome:l}),a.jsxs(ut,{onSubmit:d,children:[a.jsx(Wc,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:Ki(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),a.jsx(ye,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:a.jsx(ke,{type:"submit",children:"OK"})})]})]}):null}function qne(){const{resourceType:e,id:t}=Ut();return Gt({reference:e+"/"+t})?a.jsxs(lt,{children:[a.jsxs(ya,{icon:a.jsx(bl,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",a.jsx("br",{}),a.jsx(Dt,{href:`/forms/${t}`,children:`/forms/${t}`})]}),a.jsx(UP,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function Gne(){const e=Re(),{resourceType:t,id:n}=Ut(),[r,o]=v.useState(),[l,c]=v.useState();return v.useEffect(()=>{e.readResource(t,n).then(d=>o(ii(d))).catch(d=>{Ne({color:"red",message:Ye(d)})})},[e,t,n]),r?a.jsxs(lt,{children:[a.jsxs(Ie,{order:2,children:["Available ",t," profiles"]}),a.jsx(Be,{children:a.jsxs(a.Fragment,{children:[a.jsx(Pk,{resource:r,currentProfile:l,onChange:c}),l?a.jsx(Qne,{profile:l,resource:r,onResourceUpdated:d=>o(d)},l.url):a.jsx(Te,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const Qne=({profile:e,resource:t,onResourceUpdated:n})=>{const r=Re(),[o,l]=v.useState(),[c,d]=v.useState(()=>t.meta?.profile?.includes(e.url)),f=v.useCallback(p=>{l(void 0);const m=Tl(p);c?tA(m,e.url):FU(m,e.url),r.updateResource(m).then(g=>{n(g),Ne({color:"green",message:"Success"})}).catch(g=>{l(qt(g)),Ne({color:"red",message:Ye(g),autoClose:!1})})},[r,e.url,n,c]);return a.jsxs(Be,{children:[a.jsx(zd,{size:"md",checked:c,label:`Conform resource to ${e.title}`,onChange:p=>d(p.currentTarget.checked),"data-testid":"profile-toggle"}),c?a.jsx(vp,{profileUrl:e.url,defaultValue:t,onSubmit:f,outcome:o}):a.jsx("form",{noValidate:!0,onSubmit:p=>{p.preventDefault(),f(t)},children:a.jsx(ye,{justify:"flex-end",mt:"xl",children:a.jsx(ke,{type:"submit",children:"OK"})})})]})},Nk={"Create Only":"create","Update Only":"update","Delete Only":"delete","All Interactions":void 0},Wne=Object.keys(Nk);function Yne(){const e=Re(),{id:t}=Ut(),n=Gt({reference:`Questionnaire/${t}`}),[r,o]=v.useState(),[l,c]=v.useState("create"),[d,f]=v.useState(0),p=e.searchResources("Subscription","status=active&_count=100").read().filter(g=>Kne(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},${_t(n)}`:_t(n)}`,channel:{type:"rest-hook",endpoint:_t(r)},...l?{extension:[{url:"https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction",valueCode:l}]}:void 0}).then(()=>{o(void 0),f(Date.now()),e.invalidateSearches("Subscription"),Ne({color:"green",message:"Success"})}).catch(g=>Ne({color:"red",message:Ye(g),autoClose:!1}))}return a.jsxs(lt,{children:[a.jsx(Ie,{children:"Bots"}),a.jsxs(Be,{children:[p.length===0&&a.jsx("p",{children:"No bots found."}),p.map(g=>a.jsxs("div",{children:[a.jsx("h3",{children:a.jsx(jl,{value:{reference:g.channel?.endpoint},link:!0})}),a.jsxs("p",{children:["Criteria: ",g.criteria]})]},g.id))]}),a.jsx(pn,{}),a.jsxs(Be,{mt:10,children:[a.jsx(Ed,{size:"lg",htmlFor:"bot",children:"Connect to bot"}),a.jsxs(ye,{children:[a.jsx(wl,{name:"bot",resourceType:"Bot",onChange:g=>o(g)}),a.jsx(ke,{onClick:m,children:"Connect"})]}),a.jsx(ye,{children:a.jsx(on,{name:"subscription-trigger-event",defaultValue:"Create Only",label:"Subscription Trigger Event",data:Wne,onChange:g=>c(Nk[g.target.value])})})]}),a.jsx("div",{style:{display:"none"},children:d})]})}function Kne(e,t){if(!t)return!1;const n=e.criteria||"",r=e.channel?.endpoint||"";return n.startsWith("QuestionnaireResponse?")&&r.startsWith("Bot/")&&(n.includes(_t(t))||(t.url?n.includes(t.url):!1))}function Xne(){const{id:e}=Ut(),t=wn(),r=Re().readReference({reference:`Questionnaire/${e}`}).read(),[o,l]=v.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:de.EQUALS,value:r.url?`${r.url},Questionnaire/${e}`:`Questionnaire/${e}`}],fields:["id","_lastUpdated"]});return a.jsx(lt,{children:a.jsx(nu,{search:o,onClick:c=>t(`/${c.resource.resourceType}/${c.resource.id}`)?.catch(console.error),onChange:c=>l(c.definition),hideFilters:!0,hideToolbar:!0})})}function Zne(){const e=Re(),{resourceType:t,id:n}=Ut(),r=Gt({reference:t+"/"+n}),o=v.useCallback(l=>{e.updateResource(Tl(l)).then(()=>{Ne({color:"green",message:"Success"})}).catch(c=>{Ne({color:"red",message:Ye(c),autoClose:!1})})},[e]);return r?a.jsx(lt,{children:a.jsx(EX,{onSubmit:o,definition:r})}):null}function Jne(){const{resourceType:e,id:t}=Ut(),n=Gt({reference:e+"/"+t});return n?a.jsx(lt,{children:e==="MeasureReport"?a.jsx(jK,{measureReport:n}):a.jsx(eS,{value:n})}):null}const ere="_container_1ue98_1",tre="_entry_1ue98_14",nre="_active_1ue98_21",By={container:ere,entry:tre,active:nre};function rre(e){const t=Re(),n=Gt(e.value),[r,o]=v.useState();return v.useEffect(()=>{if(!n)return;const l=bS(n);if(!l)return;const c="reference"in l?l.reference:_t(l);t.search("ServiceRequest","subject="+c).then(d=>{const p=(d.entry??[]).map(m=>m.resource);SP(p),p.reverse(),o(p)}).catch(d=>Ne({color:"red",message:Ye(d),autoClose:!1}))},[t,n]),r?a.jsx("div",{"data-testid":"quick-service-requests",className:By.container,children:r.map(l=>a.jsxs("div",{className:Ot(By.entry,{[By.active]:l.id===n?.id}),children:[a.jsx("p",{children:a.jsx(mt,{to:l,children:ire(l)})}),l.category?.[0]?.text&&a.jsx("p",{children:l.category[0]?.text}),l.code?.coding?.[0]?.code&&a.jsx("p",{children:l.code.coding[0]?.code}),a.jsx("p",{children:ore(l)})]},l.id))}):null}function ire(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function ore(e){return e.authoredOn?e.authoredOn.substring(0,10):e.meta?.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const are="_container_1l2dh_1",sre={container:are};function lre(e){const t=Gt(e.valueSet);if(!t)return null;const n=[""],r=t.compose?.include?.[0]?.concept?.map(o=>o.code);return r&&n.push(...r),e.defaultValue&&!n.includes(e.defaultValue)&&n.push(e.defaultValue),a.jsx("div",{className:sre.container,children:a.jsx(on,{defaultValue:e.defaultValue,onChange:o=>e.onChange(o.currentTarget.value),data:n})})}function cre(e){const t=Gt(e.specimen);return t?a.jsxs(ht,{children:[a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Type"}),a.jsx(ht.Value,{children:"Specimen"})]}),a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Collected"}),a.jsx(ht.Value,{children:mr(t.collection?.collectedDateTime)})]}),a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Specimen Age"}),a.jsx(ht.Value,{children:ure(t)})]}),t.collection?.collectedDateTime&&t.receivedTime?a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Specimen Stability"}),a.jsx(ht.Value,{children:dre(t)})]}):a.jsx(a.Fragment,{})]}):null}function ure(e){const t=e.collection?.collectedDateTime;if(!t)return;const n=new Date(t);return Ok(Mk(n,new Date))}function dre(e){if(!e.collection?.collectedDateTime||!e.receivedTime)return;const t=new Date(e.collection.collectedDateTime),n=new Date(e.receivedTime);return Ok(Mk(t,n))}function Ok(e){return e.toString().padStart(3,"0")+"D"}function Mk(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function fre(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 hre(){const e=Re(),{resourceType:t,id:n}=Ut(),r={reference:t+"/"+n},o=wn(),[l,c]=v.useState(),d=Gt(r,c),f=fre(t),[p,m]=v.useState(()=>{const E=window.location.pathname.split("/").pop();return E&&f.map(R=>R.toLowerCase()).includes(E)?E:f[0].toLowerCase()});async function g(){const R=(await e.readHistory(t,n)).entry?.find(D=>!!D.resource)?.resource;R?x(R):Ne({color:"red",message:"No history to restore",autoClose:!1})}function x(E){e.updateResource(Tl(E)).then(()=>{c(void 0),Ne({color:"green",message:"Success"})}).catch(R=>{Ne({color:"red",message:Ye(R),autoClose:!1})})}if(l)return Z$(l)?a.jsxs(lt,{children:[a.jsx(Ie,{children:"Deleted"}),a.jsx("p",{children:"The resource was deleted."}),a.jsx(ke,{color:"red",onClick:g,children:"Restore"})]}):a.jsx(yr,{outcome:l});function b(E){E||(E=f[0].toLowerCase()),m(E),o(`/${t}/${n}/${E}`)?.catch(console.error)}function w(E){const R=d,D=R.orderDetail||[];D.length===0&&D.push({}),D[0].text!==E&&(D[0].text=E,x({...R,orderDetail:D}))}const j=d&&bS(d),C=d&&Tee(d),T=e.getUserConfiguration()?.option?.find(E=>E.id==="statusValueSet")?.valueString;return a.jsxs(a.Fragment,{children:[d?.resourceType==="ServiceRequest"&&T&&a.jsx(lre,{valueSet:{reference:T},defaultValue:d.orderDetail?.[0]?.text,onChange:w},_t(d)+"-"+d.orderDetail?.[0]?.text),d&&a.jsx(rre,{value:d}),d&&a.jsxs(Tr,{children:[j&&a.jsx(AP,{patient:j}),C&&a.jsx(cre,{specimen:C}),t!=="Patient"&&a.jsx(Rk,{resource:r}),a.jsx(ai,{children:a.jsx(Tt,{value:p.toLowerCase(),onChange:b,children:a.jsx(Tt.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:f.map(E=>a.jsx(Tt.Tab,{value:E.toLowerCase(),children:E},E))})})})]}),a.jsx(gS,{})]})}function Ah(){const e=wn(),{resourceType:t,id:n,versionId:r,tab:o}=Ut(),l=Re(),[c,d]=v.useState(!0),[f,p]=v.useState(),[m,g]=v.useState();if(v.useEffect(()=>{g(void 0),d(!0),l.readHistory(t,n).then(R=>p(R)).then(()=>d(!1)).catch(R=>{g(R),d(!1)})},[l,t,n]),c)return a.jsx(Di,{});const x=f?.entry??[],b=x.findIndex(R=>R.resource?.meta?.versionId===r);if(b===-1)return a.jsxs(lt,{children:[a.jsx(Ie,{children:"Version not found"}),a.jsx(mt,{to:`/${t}/${n}`,children:"Return to resource"})]});const w=x[b].resource,j=b<x.length-1?x[b+1].resource:void 0,C="diff",T=o||C,E=x.length-b;return a.jsx(kd,{maw:1200,children:a.jsx(Sl,{children:a.jsxs(Be,{gap:"lg",children:[m&&a.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)}),a.jsxs(lm,{cols:2,mb:"lg",children:[a.jsx(Oi,{total:x.length,value:E,getControlProps:TP,onChange:R=>e(`/${t}/${n}/_history/${x[x.length-R]?.resource?.meta?.versionId}/${T}`)?.catch(console.error)}),a.jsx(ye,{justify:"right",children:a.jsx(Id,{data:[{value:"diff",label:"Diff"},{value:"raw",label:"Raw"}],value:T,onChange:R=>e(`/${t}/${n}/_history/${r}/${R||C}`)?.catch(console.error)})})]}),a.jsx(ce,{mb:"lg",children:a.jsxs(Cm,{compact:!0,children:[a.jsx(Ti,{term:"Version ID",children:w.meta?.versionId}),a.jsx(Ti,{term:"Author",children:a.jsx(Tc,{value:w.meta?.author,link:!0},w.meta?.author?.reference)}),a.jsx(Ti,{term:"Date/Time",children:mr(w.meta?.lastUpdated)})]})}),T==="diff"&&a.jsx(eZ,{original:j??{resourceType:t,id:n},revised:w}),T==="raw"&&a.jsx("pre",{style:{fontSize:"9pt"},children:JSON.stringify(w,void 0,2)})]})})})}function pre(){const{resourceType:e,id:t}=Ut(),n=wn(),[r,o]=v.useState({resourceType:"Subscription",filters:[{code:"url",operator:de.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return a.jsx(lt,{children:a.jsx(sK,{search:r,onClick:l=>n(`/${l.resource.resourceType}/${l.resource.id}`)?.catch(console.error),onChange:l=>o(l.definition),hideFilters:!0})})}function mre(e){const t=Re(),{resource:n,opened:r,onClose:o}=e,[l,c]=v.useState(!1),[d,f]=v.useState(),[p,m]=v.useState(!1),g=v.useCallback(async()=>{if(n?.id)try{await t.post(t.fhirUrl(n.resourceType,n.id,"$resend"),{subscription:l&&d?_t(d):void 0,verbose:p}),Ne({color:"green",message:"Done"}),o()}catch(x){Ne({color:"red",message:Ye(x),autoClose:!1})}},[t,n,o,l,d,p]);return a.jsx(Un,{opened:r,onClose:o,title:"Resend Subscriptions",children:a.jsx(ut,{onSubmit:g,children:a.jsxs(Be,{children:[a.jsx(Pn,{label:"Choose subscription (all subscriptions by default)",onChange:x=>c(x.currentTarget.checked)}),l&&a.jsx(wl,{name:"subscription",resourceType:"Subscription",placeholder:"Subscription",onChange:f}),a.jsx(Pn,{label:"Verbose mode",onChange:x=>m(x.currentTarget.checked)}),a.jsx(ye,{justify:"flex-end",children:a.jsx(ke,{type:"submit",children:"Resend"})})]})})})}function RR(){const e=Re(),t=bm(),{resourceType:n,id:r}=Ut(),o={reference:n+"/"+r},[l,c]=v.useState(),d=wd(!1);function f(E,R){return e.updateResource({...E,priority:R})}function p(E,R){f(E,"stat").then(R).catch(console.error)}function m(E,R){f(E,"routine").then(R).catch(console.error)}function g(E){t(`/${E.resourceType}/${E.id}`)}function x(E){t(`/${E.resourceType}/${E.id}/edit`)}function b(E){t(`/${E.resourceType}/${E.id}/delete`)}function w(E){c(E),d[1].open()}function j(E){t(`/${E.resourceType}/${E.id}/_history/${E.meta?.versionId}`)}function C(E,R){const D="aws-textract";Ne({id:D,title:"AWS Textract in Progress",message:"Extracting text... This may take a moment...",loading:!0,autoClose:!1}),e.post(e.fhirUrl(E.resourceType,E.id,"$aws-textract"),{}).then(()=>{R(),Qs({id:D,title:"AWS Textract Successful",message:"Text successfully extracted.",color:"green",icon:a.jsx(Po,{size:"1rem"}),loading:!1,withCloseButton:!0})}).catch(P=>Qs({id:D,title:"AWS Textract Error",color:"red",message:Ye(P),icon:a.jsx(sl,{size:"1rem"}),loading:!1,withCloseButton:!0}))}function T(E){const{primaryResource:R,currentResource:D,reloadTimeline:P}=E,A=D.resourceType===R.resourceType&&D.id===R.id,k=D.resourceType==="Communication"&&D.priority!=="stat",M=D.resourceType==="Communication"&&D.priority==="stat",$=A,U=!A,J=!A,Z=!A,Y=e.getProjectMembership()?.admin,H=Y,Q=vne()&&(D.resourceType==="DocumentReference"||D.resourceType==="Media");return a.jsxs(je.Dropdown,{children:[a.jsx(je.Label,{children:"Resource"}),k&&a.jsx(je.Item,{leftSection:a.jsx(Tq,{size:14}),onClick:()=>p(D,P),"aria-label":`Pin ${_t(D)}`,children:"Pin"}),M&&a.jsx(je.Item,{leftSection:a.jsx(_q,{size:14}),onClick:()=>m(D,P),"aria-label":`Unpin ${_t(D)}`,children:"Unpin"}),U&&a.jsx(je.Item,{leftSection:a.jsx(dT,{size:14}),onClick:()=>g(D),"aria-label":`Details ${_t(D)}`,children:"Details"}),$&&a.jsx(je.Item,{leftSection:a.jsx(dT,{size:14}),onClick:()=>j(D),"aria-label":`Details ${_t(D)}`,children:"Details"}),J&&a.jsx(je.Item,{leftSection:a.jsx(IA,{size:14}),onClick:()=>x(D),"aria-label":`Edit ${_t(D)}`,children:"Edit"}),Y&&a.jsxs(a.Fragment,{children:[a.jsx(je.Divider,{}),a.jsx(je.Label,{children:"Admin"}),H&&a.jsx(je.Item,{leftSection:a.jsx(Lq,{size:14}),onClick:()=>w(D),"aria-label":`Resend Subscriptions ${_t(D)}`,children:"Resend Subscriptions"})]}),Q&&a.jsxs(a.Fragment,{children:[a.jsx(je.Divider,{}),a.jsx(je.Label,{children:"AWS AI"}),a.jsx(je.Item,{leftSection:a.jsx(tG,{size:14}),onClick:()=>C(D,P),"aria-label":`AWS Textract ${_t(D)}`,children:"AWS Textract"})]}),Z&&a.jsxs(a.Fragment,{children:[a.jsx(je.Divider,{}),a.jsx(je.Label,{children:"Danger zone"}),a.jsx(je.Item,{color:"red",leftSection:a.jsx(wm,{size:14}),onClick:()=>b(D),"aria-label":`Delete ${_t(D)}`,children:"Delete"})]})]})}return a.jsxs(a.Fragment,{children:[n==="Encounter"&&a.jsx(mY,{encounter:o,getMenu:T}),n==="Patient"&&a.jsx(_K,{patient:o,getMenu:T}),n==="ServiceRequest"&&a.jsx(sZ,{serviceRequest:o,getMenu:T}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&a.jsx(pY,{resource:o,getMenu:T}),a.jsx(mre,{resource:l,opened:d[0],onClose:d[1].close},`resend-subscriptions-${l?.id}`)]})}function gre(e){const{opened:t,close:n,version:r,loadingStatus:o,handleStatus:l,handleUpgrade:c}=e,[d,f]=v.useState(),[p,m]=v.useState(!1);return v.useEffect(()=>{t&&(d||SF("app-tools-page").then(f).catch(console.error),l())},[t,d,l]),d&&r&&!o?r==="unknown"?a.jsx("p",{children:"Unable to determine the current version of the agent. Check the network connectivity of the agent."}):r.startsWith(d)?a.jsxs("p",{children:["This agent is already on the latest version (",d,")."]}):a.jsxs(a.Fragment,{children:[a.jsxs("p",{children:["Are you sure you want to upgrade this agent from version ",r," to version ",d,"?"]}),a.jsxs(ye,{children:[a.jsx(ke,{onClick:()=>{c(p),n()},"aria-label":"Confirm upgrade",children:"Confirm Upgrade"}),a.jsx(Pn,{label:"Force",onChange:g=>m(g.currentTarget.checked)})]})]}):a.jsx(Di,{})}function vre(){const e=Re(),{id:t}=Ut(),n=v.useMemo(()=>({reference:"Agent/"+t}),[t]),[r,o]=v.useState(!1),[l,c]=v.useState(!1),[d,f]=v.useState(!1),[p,m]=v.useState(!1),[g,x]=v.useState(),[b,w]=v.useState(),[j,C]=v.useState(),[T,E]=v.useState(),[R,D]=v.useState(!1),[P,A]=v.useState(!1),[k,M]=v.useState(),[$,{open:U,close:J}]=wd(!1);v.useEffect(()=>{if(r||l||d||R){A(!0);return}A(!1)},[r,l,d,R]);const Z=v.useCallback(()=>{o(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(F=>{x(F.parameter?.find(K=>K.name==="status")?.valueCode),w(F.parameter?.find(K=>K.name==="version")?.valueString),C(F.parameter?.find(K=>K.name==="lastUpdated")?.valueInstant)}).catch(F=>z(Ye(F))).finally(()=>o(!1))},[e,t]),Y=v.useCallback(F=>{const K=F.host,L=F.pingCount||1;K&&(D(!0),e.pushToAgent(n,K,`PING ${L}`,ln.PING,!0).then(q=>E(q)).catch(q=>z(Ye(q))).finally(()=>D(!1)))},[e,n]),H=v.useCallback(()=>{c(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(F=>{I("Agent config reloaded successfully.")}).catch(F=>z(Ye(F))).finally(()=>c(!1))},[e,t]),Q=v.useCallback(F=>{f(!0);const K=e.fhirUrl("Agent",t,"$upgrade");K.searchParams.set("force",String(F)),e.get(K,{cache:"reload"}).then(L=>{I("Agent upgraded successfully.")}).catch(L=>z(Ye(L))).finally(()=>f(!1))},[e,t]),O=v.useCallback(F=>{m(!0);const K=F.logLimit||20;e.get(e.fhirUrl("Agent",t,`$fetch-logs${K!==void 0?`?limit=${K}`:""}`),{cache:"reload"}).then(L=>{const q=L?.parameter?.find(ie=>ie.name==="logs");q&&M(q?.valueString)}).catch(L=>z(Ye(L))).finally(()=>m(!1))},[e,t]);function I(F){Ne({color:"green",title:"Success",icon:a.jsx(Po,{size:"1rem"}),message:F})}function z(F){Ne({color:"red",title:"Error",message:F,autoClose:!1})}return a.jsxs(lt,{children:[a.jsx(Un,{opened:$,onClose:J,title:"Upgrade Agent",centered:!0,children:a.jsx(gre,{opened:$,close:J,version:b,loadingStatus:r,handleStatus:Z,handleUpgrade:Q})}),a.jsx(Ie,{order:1,children:"Agent Tools"}),a.jsxs("div",{style:{marginBottom:10},children:["Agent: ",a.jsx(jl,{value:n,link:!0})]}),a.jsx(pn,{my:"lg"}),a.jsx(Ie,{order:2,children:"Agent Status"}),a.jsx("p",{children:"Retrieve the status of the agent. This tests whether the agent is connected to the Medplum server, and the last time it was able to communicate."}),a.jsx(ke,{onClick:Z,loading:r,disabled:P&&!r,children:"Get Status"}),!r&&g&&a.jsx(fe,{children:a.jsxs(fe.Tbody,{children:[a.jsxs(fe.Tr,{children:[a.jsx(fe.Td,{children:"Status"}),a.jsx(fe.Td,{children:a.jsx(Rm,{status:g})})]}),a.jsxs(fe.Tr,{children:[a.jsx(fe.Td,{children:"Version"}),a.jsx(fe.Td,{children:b})]}),a.jsxs(fe.Tr,{children:[a.jsx(fe.Td,{children:"Last Updated"}),a.jsx(fe.Td,{children:mr(j,void 0,{timeZoneName:"longOffset"})})]})]})}),a.jsx(pn,{my:"lg"}),a.jsx(Ie,{order:2,children:"Reload Config"}),a.jsx("p",{children:"Reload the configuration of this agent, syncing it with the current version of the Agent resource on the Medplum server."}),a.jsx(ke,{onClick:H,loading:l,disabled:P&&!l,"aria-label":"Reload config",children:"Reload Config"}),a.jsx(pn,{my:"lg"}),a.jsx(Ie,{order:2,children:"Upgrade Agent"}),a.jsx("p",{children:"Upgrade the version of this agent, to either the latest (default) or a specified version."}),a.jsx(ke,{onClick:U,loading:d,disabled:P&&!d,"aria-label":"Upgrade agent",children:"Upgrade"}),a.jsx(pn,{my:"lg"}),a.jsxs(ut,{onSubmit:O,children:[a.jsx(Ie,{order:2,children:"Fetch Logs"}),a.jsx("p",{children:"Fetch logs from the agent."}),k?.length?a.jsx(Pd,{block:!0,mb:15,children:k}):null,a.jsxs(ye,{children:[a.jsx(Oc,{w:100,id:"logLimit",name:"logLimit",placeholder:"20",label:"Log Limit"}),a.jsx(ke,{mt:22,loading:p,disabled:P&&!p,"aria-label":"Fetch logs",type:"submit",children:"Fetch Logs"})]})]}),a.jsx(pn,{my:"lg"}),a.jsx(Ie,{order:2,children:"Ping from Agent"}),a.jsx("p",{children:"Send a ping command from the agent to a valid IP address or hostname. Use this tool to troubleshoot local network connectivity."}),a.jsx(ut,{onSubmit:Y,children:a.jsxs(ye,{children:[a.jsx(Ve,{id:"host",name:"host",placeholder:"ex. 127.0.0.1",label:"IP Address / Hostname",rightSection:a.jsx(bn,{size:24,radius:"xl",variant:"filled",type:"submit","aria-label":"Ping",loading:R,disabled:P&&!R,children:a.jsx(Uq,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),a.jsx(Oc,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!R&&T&&a.jsxs(a.Fragment,{children:[a.jsx(Ie,{order:5,mt:"sm",mb:0,children:"Last Ping"}),a.jsx("pre",{children:T})]})]})}function yre(){const e=wn(),t=Re(),[n,r]=v.useState();v.useEffect(()=>{t.get("auth/me",{cache:"no-cache"}).then(r).catch(l=>Ne({color:"red",message:Ye(l),autoClose:!1}))},[t]);function o(l){t.post("auth/revoke",{loginId:l}).then(()=>t.get("auth/me",{cache:"no-cache"})).then(r).then(()=>Ne({color:"green",message:"Login revoked"})).catch(c=>Ne({color:"red",message:Ye(c),autoClose:!1}))}return n?a.jsxs(a.Fragment,{children:[a.jsxs(lt,{children:[a.jsx(Ie,{children:"Security"}),a.jsxs(Cm,{children:[a.jsx(Ti,{term:"ID",children:a.jsx(Dt,{href:`/${_t(n.profile)}`,children:n.profile.id})}),a.jsx(Ti,{term:"Resource Type",children:n.profile.resourceType}),a.jsx(Ti,{term:"Name",children:Jc(n.profile.name?.[0])})]})]}),a.jsxs(lt,{children:[a.jsx(Ie,{children:"Sessions"}),a.jsxs(fe,{children:[a.jsx("thead",{children:a.jsxs("tr",{children:[a.jsx("th",{children:"OS"}),a.jsx("th",{children:"Browser"}),a.jsx("th",{children:"IP Address"}),a.jsx("th",{children:"Auth Method"}),a.jsx("th",{children:"Last Updated"}),a.jsx("th",{})]})}),a.jsx("tbody",{children:n.security.sessions.map(l=>a.jsxs("tr",{children:[a.jsx("td",{children:l.os}),a.jsx("td",{children:l.browser}),a.jsx("td",{children:l.remoteAddress}),a.jsx("td",{children:l.authMethod}),a.jsx("td",{children:mr(l.lastUpdated)}),a.jsx("td",{children:a.jsx(Dt,{href:"#",onClick:()=>o(l.id),children:"Revoke"})})]},l.id))})]})]}),a.jsxs(lt,{children:[a.jsx(Ie,{children:"Password"}),a.jsx(ke,{onClick:()=>e("/changepassword")?.catch(console.error),children:"Change password"})]}),a.jsxs(lt,{children:[a.jsx(Ie,{children:"Multi Factor Auth"}),a.jsxs("p",{children:["Enrolled: ",n.security.mfaEnrolled.toString()]}),!n.security.mfaEnrolled&&a.jsx(ke,{onClick:()=>e("/mfa")?.catch(console.error),children:"Enroll"})]})]}):null}function xre(){const{id:e,secret:t}=Ut(),n=Re(),[r,o]=v.useState(),[l,c]=v.useState(!1),d=tu(r,void 0);return a.jsxs(lt,{width:450,children:[a.jsx(yr,{issues:d}),a.jsxs(ut,{onSubmit:f=>{if(f.password!==f.confirmPassword){o(xo("Passwords do not match","confirmPassword"));return}o(void 0);const p={id:e,secret:t,password:f.password};n.post("auth/setpassword",p).then(()=>c(!0)).catch(m=>o(qt(m)))},children:[a.jsxs(ar,{style:{flexDirection:"column"},children:[a.jsx(Mi,{size:32}),a.jsx(Ie,{children:"Set password"})]}),!l&&a.jsxs(Be,{children:[a.jsx(Qi,{name:"password",label:"New password",required:!0,error:At(r,"password")}),a.jsx(Qi,{name:"confirmPassword",label:"Confirm new password",required:!0,error:At(r,"confirmPassword")}),a.jsx(ye,{justify:"flex-end",mt:"xl",children:a.jsx(ke,{type:"submit",children:"Set password"})})]}),l&&a.jsxs("div",{"data-testid":"success",children:["Password set. You can now ",a.jsx(mt,{to:"/signin",children:"sign in"}),"."]})]})]})}function bre(){const e=Sm(),t=wn(),[n]=xS(),r=ef(),o=v.useCallback(()=>{const l=n.get("next");t(l?.startsWith("/")?l:"/")?.catch(console.error)},[n,t]);return v.useEffect(()=>{e&&n.has("next")&&o()},[e,n,o]),a.jsxs(rP,{onSuccess:()=>o(),onForgotPassword:()=>t("/resetpassword")?.catch(console.error),onRegister:Dk()?()=>t("/register")?.catch(console.error):void 0,googleClientId:r.googleClientId,login:n.get("login")||void 0,projectId:n.get("project")||void 0,children:[a.jsx(Mi,{size:32}),a.jsxs(Ie,{children:["Sign in to ",GA()]}),n.get("project")==="new"&&a.jsx("div",{children:"Sign in again to create a new project"})]})}function Sre(){const e=wn(),t=Gr(),[n,r]=v.useState(),[o,l]=v.useState(),[c,d]=v.useState();return v.useEffect(()=>{const f=Object.fromEntries(new URLSearchParams(t.search).entries());r(f.resourceType),l(f.query),d(JSON.parse(f.fields))},[t]),!n||!o||!c?null:a.jsx(hK,{resourceType:n,checkboxesEnabled:!0,query:o,fields:c,onClick:f=>e(`/${n}/${f.resource.id}`)?.catch(console.error),onAuxClick:f=>window.open(`/${n}/${f.resource.id}`,"_blank"),onBulk:f=>{e(`/bulk/${n}?ids=${f.join(",")}`)?.catch(console.error)}})}function wre(){const{id:e,secret:t}=Ut(),n=Re(),[r,o]=v.useState(),[l,c]=v.useState(!1),d=tu(r,void 0);return a.jsxs(lt,{width:450,children:[a.jsx(yr,{issues:d}),a.jsxs(ut,{onSubmit:()=>{o(void 0);const f={id:e,secret:t};n.post("auth/verifyemail",f).then(()=>c(!0)).catch(p=>o(qt(p)))},children:[a.jsxs(ar,{style:{flexDirection:"column"},children:[a.jsx(Mi,{size:32}),a.jsx(Ie,{children:"Email address verification required"})]}),!l&&a.jsxs(Be,{children:[a.jsx("p",{children:"In order to sign in, click the button below to verify your ability to receive email at the address this link was sent to."}),a.jsx(ye,{justify:"flex-end",mt:"xl",children:a.jsx(ke,{type:"submit",children:"Verify email"})})]}),l&&a.jsxs("div",{"data-testid":"success",children:["Email verified. You can now ",a.jsx(mt,{to:"/signin",children:"sign in"}),"."]})]})]})}function jre(){return a.jsx(HJ,{children:a.jsxs(Ue,{errorElement:a.jsx(nne,{}),children:[a.jsx(Ue,{path:"/signin",element:a.jsx(bre,{})}),a.jsx(Ue,{path:"/oauth",element:a.jsx(yne,{})}),a.jsx(Ue,{path:"/resetpassword",element:a.jsx(bne,{})}),a.jsx(Ue,{path:"/setpassword/:id/:secret",element:a.jsx(xre,{})}),a.jsx(Ue,{path:"/verifyemail/:id/:secret",element:a.jsx(wre,{})}),a.jsx(Ue,{path:"/register",element:a.jsx(xne,{})}),a.jsx(Ue,{path:"/changepassword",element:a.jsx(Jte,{})}),a.jsx(Ue,{path:"/security",element:a.jsx(yre,{})}),a.jsx(Ue,{path:"/mfa",element:a.jsx(mne,{})}),a.jsx(Ue,{path:"/batch",element:a.jsx(Xte,{})}),a.jsx(Ue,{path:"/bulk/:resourceType",element:a.jsx(Zte,{})}),a.jsx(Ue,{path:"/smart",element:a.jsx(Sre,{})}),a.jsx(Ue,{path:"/forms/:id",element:a.jsx(rne,{})}),a.jsx(Ue,{path:"/admin/super",element:a.jsx(Jee,{})}),a.jsx(Ue,{path:"/admin/super/asyncjob",element:a.jsx(Qee,{})}),a.jsx(Ue,{path:"/admin/super/db",element:a.jsx(zee,{})}),a.jsx(Ue,{path:"/admin/config",element:a.jsx(Fee,{})}),a.jsxs(Ue,{path:"/admin",element:a.jsx(Hee,{}),children:[a.jsx(Ue,{path:"patients",element:a.jsx(Vee,{})}),a.jsx(Ue,{path:"bots/new",element:a.jsx(Dee,{})}),a.jsx(Ue,{path:"bots",element:a.jsx(Ree,{})}),a.jsx(Ue,{path:"clients/new",element:a.jsx(Aee,{})}),a.jsx(Ue,{path:"clients",element:a.jsx(_ee,{})}),a.jsx(Ue,{path:"details",element:a.jsx(cR,{})}),a.jsx(Ue,{path:"invite",element:a.jsx(Bee,{})}),a.jsx(Ue,{path:"users",element:a.jsx(nte,{})}),a.jsx(Ue,{path:"project",element:a.jsx(cR,{})}),a.jsx(Ue,{path:"secrets",element:a.jsx(qee,{})}),a.jsx(Ue,{path:"sites",element:a.jsx(Gee,{})}),a.jsx(Ue,{path:"members/:membershipId",element:a.jsx(Uee,{})})]}),a.jsx(Ue,{path:"/lab/assays",element:a.jsx(hne,{})}),a.jsx(Ue,{path:"/lab/panels",element:a.jsx(pne,{})}),a.jsxs(Ue,{path:"/:resourceType/new",element:a.jsx(tne,{}),children:[a.jsx(Ue,{index:!0,element:a.jsx(Uy,{})}),a.jsx(Ue,{path:"form",element:a.jsx(Uy,{})}),a.jsx(Ue,{path:"json",element:a.jsx(Fne,{})}),a.jsx(Ue,{path:"profiles",element:a.jsx(Uy,{})})]}),a.jsxs(Ue,{path:"/:resourceType/:id",element:a.jsx(hre,{}),children:[a.jsx(Ue,{index:!0,element:a.jsx(RR,{})}),a.jsx(Ue,{path:"apply",element:a.jsx(wne,{})}),a.jsx(Ue,{path:"apps",element:a.jsx(jne,{})}),a.jsx(Ue,{path:"event",element:a.jsx(Ene,{})}),a.jsx(Ue,{path:"blame",element:a.jsx(Tne,{})}),a.jsx(Ue,{path:"bots",element:a.jsx(Yne,{})}),a.jsx(Ue,{path:"builder",element:a.jsx(Mne,{})}),a.jsx(Ue,{path:"checklist",element:a.jsx(Lne,{})}),a.jsx(Ue,{path:"delete",element:a.jsx(Ine,{})}),a.jsx(Ue,{path:"details",element:a.jsx(Une,{})}),a.jsx(Ue,{path:"edit",element:a.jsx(Bne,{})}),a.jsx(Ue,{path:"editor",element:a.jsx(Nne,{})}),a.jsxs(Ue,{path:"history",children:[a.jsx(Ue,{index:!0,element:a.jsx(TR,{})}),a.jsx(Ue,{path:":versionId/:tab",element:a.jsx(Ah,{})}),a.jsx(Ue,{path:":versionId",element:a.jsx(Ah,{})})]}),a.jsxs(Ue,{path:"_history",children:[a.jsx(Ue,{index:!0,element:a.jsx(TR,{})}),a.jsx(Ue,{path:":versionId/:tab",element:a.jsx(Ah,{})}),a.jsx(Ue,{path:":versionId",element:a.jsx(Ah,{})})]}),a.jsx(Ue,{path:"json",element:a.jsx(Hne,{})}),a.jsx(Ue,{path:"preview",element:a.jsx(qne,{})}),a.jsx(Ue,{path:"responses",element:a.jsx(Xne,{})}),a.jsx(Ue,{path:"report",element:a.jsx(Jne,{})}),a.jsx(Ue,{path:"ranges",element:a.jsx(Zne,{})}),a.jsx(Ue,{path:"subscriptions",element:a.jsx(pre,{})}),a.jsx(Ue,{path:"timeline",element:a.jsx(RR,{})}),a.jsx(Ue,{path:"tools",element:a.jsx(vre,{})}),a.jsx(Ue,{path:"profiles",element:a.jsx(Gne,{})}),a.jsx(Ue,{path:"export",element:a.jsx(Vne,{})})]}),a.jsx(Ue,{path:"/:resourceType",element:a.jsx(jR,{})}),a.jsx(Ue,{path:"/",element:a.jsx(jR,{})})]})})}function Cre(){const e=Re(),t=e.getUserConfiguration(),n=Gr(),[r]=xS();return e.isLoading()?a.jsx(Di,{}):a.jsx(eQ,{logo:a.jsx(Mi,{size:24}),pathname:n.pathname,searchParams:r,version:xA,menus:Ere(t),displayAddBookmark:!!t?.id,children:a.jsx(v.Suspense,{fallback:a.jsx(Di,{}),children:a.jsx(jre,{})})})}function Ere(e){const t=e?.menu?.map(n=>({title:n.title,links:n.link?.map(r=>({label:r.name,href:r.target,icon:Tre(r.target)}))||[]}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:a.jsx(fq,{})}]}),t}const _R={Patient:Yq,Practitioner:sq,Organization:CH,ServiceRequest:Nq,DiagnosticReport:zq,Questionnaire:oq,admin:yH,AccessPolicy:uq,Subscription:oG,batch:Cq,Observation:bq};function Tre(e){if(e.includes("admin/super/db"))return a.jsx(BH,{});try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in _R){const n=_R[t];return a.jsx(n,{})}}catch{}return a.jsx(cm,{w:30})}async function Rre(){const e=ef(),t=new bA({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=pee([{path:"*",element:a.jsx(Cre,{})}]),o=c=>r.navigate(c);hZ.createRoot(document.getElementById("root")).render(a.jsx(v.StrictMode,{children:a.jsx(wF,{medplum:t,navigate:o,children:a.jsxs(JR,{theme:n,children:[a.jsx(Sa,{position:"bottom-right"}),a.jsx(UJ,{router:r})]})})}))}Rre().catch(console.error);
|
|
607
|
-
//# sourceMappingURL=index-
|
|
607
|
+
//# sourceMappingURL=index-CojoYZmq.js.map
|