@medplum/app 4.3.14 → 4.4.0
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 bO(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 hc={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let PE=!1;function hV(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");hc.Event=globalThis.Event,hc.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},hc.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function pV(e,t){if(!e)throw new Error(t)}function ph(e){return new e.constructor(e.type,e)}const Rs={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let kE=!1;class Ba extends um{constructor(t,n,r={}){PE||(hV(),PE=!0),super(),this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._closeCalled=!1,this._messageQueue=[],this._debugLogger=console.log.bind(console),this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=o=>{this._debug("open event");const{minUptime:s=Rs.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),s),pV(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(ph(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(ph(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(ph(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(ph(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 Ba.CONNECTING}get OPEN(){return Ba.OPEN}get CLOSING(){return Ba.CLOSING}get CLOSED(){return Ba.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?Ba.CLOSED:Ba.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=Rs.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=Rs.reconnectionDelayGrowFactor,minReconnectionDelay:n=Rs.minReconnectionDelay,maxReconnectionDelay:r=Rs.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=Rs.maxRetries,connectionTimeout:n=Rs.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"&&!kE&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),kE=!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 hc.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new hc.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new hc.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 mV=5e3;class Jy extends um{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 gV{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new Jy(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class vV{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof eA))throw new dt(gn("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new dt(gn("Not a valid URL"))}const s=r?.ReconnectingWebSocket?new r.ReconnectingWebSocket(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger}):new Ba(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger});this.medplum=t,this.ws=s,this.masterSubEmitter=new Jy,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=r?.pingIntervalMs??mV,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,s=o?.entry?.[0]?.resource;if(s.type==="heartbeat"){this.masterSubEmitter?.dispatchEvent({type:"heartbeat",payload:o});return}if(s.type==="handshake"){const d=Hs(s.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(Hs(s.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 s of this.getAllCriteriaEmitters())s.dispatchEvent({...o})}}),t.addEventListener("error",()=>{const n={type:"error",payload:new dt(Rz(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 ${At(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,s=r?.find(c=>c.name==="websocket-url")?.valueUrl;if(!o)throw new dt(gn("Failed to get token"));if(!s)throw new dt(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:s}=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),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(Ge(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 gV(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 Jy(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const JD="4.3.14-5f46c080b",yV=un.FHIR_JSON+", */*; q=0.1",xV="https://api.medplum.com/",bV=1e3,SV=6e4,wV=0,jV=3e5,CV="Binary/",NE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},oc={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"},EV={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},TV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class eA extends um{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??RV(),this.storage=t?.storage??new dV,this.createPdfImpl=t?.createPdf,this.baseUrl=db(t?.baseUrl??xV),this.fhirBaseUrl=Zi(this.baseUrl,t?.fhirUrlPath??"fhir/R4"),this.authorizeUrl=Zi(this.baseUrl,t?.authorizeUrl??"oauth2/authorize"),this.tokenUrl=Zi(this.baseUrl,t?.tokenUrl??"oauth2/token"),this.logoutUrl=Zi(this.baseUrl,t?.logoutUrl??"oauth2/logout"),this.fhircastHubUrl=Zi(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??jV,this.cacheTime=t?.cacheTime??(typeof window>"u"?wV:SV),this.cacheTime>0?this.requestCache=new dD(t?.resourceCacheSize??bV):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(),typeof window<"u"&&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=Zi(this.fhirBaseUrl,t);if(this.requestCache)for(const r of this.requestCache.keys())(r.endsWith(n)||r.includes(n+"?"))&&this.requestCache.delete(r)}get(t,n={}){t=t.toString();const r=this.getCacheEntry(t,n);if(r)return r.value;let 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 s=new Ai(o);return this.setCacheEntry(t,s),s}post(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("POST",t,o)}put(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("PUT",t,o)}patch(t,n,r={}){return t=t.toString(),this.setRequestBody(r,n),this.setRequestContentType(r,un.JSON_PATCH),this.invalidateUrl(t),this.request("PATCH",t,r)}delete(t,n){return t=t.toString(),this.invalidateUrl(t),this.request("DELETE",t,n)}async startNewUser(t,n){const{codeChallengeMethod:r,codeChallenge:o}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:r,codeChallenge:o},void 0,n)}async startNewProject(t,n){return this.post("auth/newproject",t,void 0,n)}async startNewPatient(t,n){return this.post("auth/newpatient",t,void 0,n)}async startLogin(t,n){return this.post("auth/login",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async startGoogleLogin(t,n){return this.post("auth/google",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async ensureCodeChallenge(t){return t.codeChallenge?t:{...t,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(t){const r=new URLSearchParams(window.location.search).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){window.location.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,o,s=!0){let c=o;s&&(c=await this.ensureCodeChallenge(o)),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:oc.TokenExchange,subject_token_type:EV.AccessToken,client_id:n,subject_token:t})}getExternalAuthRedirectUri(t,n,r,o,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",o.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(o)),s){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(Zi(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=yU(n)),r}search(t,n,r){const o=this.fhirSearchUrl(t,n),s="search-"+o.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=this.getBundle(o,r);return this.setCacheEntry(s,d),d}searchOne(t,n,r){const o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();const s="searchOne-"+o.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=new Ai(this.search(t,o.searchParams,r).then(f=>f.entry?.[0]?.resource));return this.setCacheEntry(s,d),d}searchResources(t,n,r){const s="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=new Ai(this.search(t,n,r).then(LE));return this.setCacheEntry(s,d),d}async*searchResourcePages(t,n,r){let o=this.fhirSearchUrl(t,n);for(;o;){const s=new URL(o).searchParams;s.has("_count")||s.set("_count","1000");const c=await this.search(t,s,r),d=c.link?.find(f=>f.relation==="next");if(!c.entry?.length&&!d)break;yield LE(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 NE;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 Ai(Promise.reject(new Error("Missing reference")));if(r==="system")return new Ai(Promise.resolve(NE));const[o,s]=r.split("/");return!o||!s?new Ai(Promise.reject(new Error("Invalid reference"))):this.readResource(o,s,n)}requestSchema(t){if(yD(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Ai((async()=>{const s=`{
|
|
87
|
+
*/const hc={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0};let PE=!1;function hV(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");hc.Event=globalThis.Event,hc.ErrorEvent=class extends Event{constructor(t,n){super("error",n),this.message=t.message,this.error=t}},hc.CloseEvent=class extends Event{constructor(t=1e3,n="",r){super("close",r),this.wasClean=!0,this.code=t,this.reason=n}}}function pV(e,t){if(!e)throw new Error(t)}function ph(e){return new e.constructor(e.type,e)}const Rs={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0};let kE=!1;class Ba extends um{constructor(t,n,r={}){PE||(hV(),PE=!0),super(),this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._closeCalled=!1,this._messageQueue=[],this._debugLogger=console.log.bind(console),this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=o=>{this._debug("open event");const{minUptime:s=Rs.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),s),pV(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(ph(o))},this._handleMessage=o=>{this._debug("message event"),this.onmessage&&this.onmessage(o),this.dispatchEvent(ph(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(ph(o)),this._connect()},this._handleClose=o=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(o),this.dispatchEvent(ph(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 Ba.CONNECTING}get OPEN(){return Ba.OPEN}get CLOSING(){return Ba.CLOSING}get CLOSED(){return Ba.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?Ba.CLOSED:Ba.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=Rs.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=Rs.reconnectionDelayGrowFactor,minReconnectionDelay:n=Rs.minReconnectionDelay,maxReconnectionDelay:r=Rs.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=Rs.maxRetries,connectionTimeout:n=Rs.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"&&!kE&&(console.error("‼️ No WebSocket implementation available. You should define options.WebSocket."),kE=!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 hc.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new hc.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new hc.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 mV=5e3;class Jy extends um{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 gV{constructor(t,n){this.connecting=!1,this.criteria=t,this.emitter=new Jy(t),this.refCount=1,this.subscriptionProps=n?{...n}:void 0}clearAttachedSubscription(){this.subscriptionId=void 0,this.token=void 0}}class vV{constructor(t,n,r){if(this.pingTimer=void 0,this.waitingForPong=!1,!(t instanceof eA))throw new dt(gn("First arg of constructor should be a `MedplumClient`"));let o;try{o=new URL(n).toString()}catch{throw new dt(gn("Not a valid URL"))}const s=r?.ReconnectingWebSocket?new r.ReconnectingWebSocket(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger}):new Ba(o,void 0,{debug:r?.debug,debugLogger:r?.debugLogger});this.medplum=t,this.ws=s,this.masterSubEmitter=new Jy,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=r?.pingIntervalMs??mV,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,s=o?.entry?.[0]?.resource;if(s.type==="heartbeat"){this.masterSubEmitter?.dispatchEvent({type:"heartbeat",payload:o});return}if(s.type==="handshake"){const d=Hs(s.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(Hs(s.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 s of this.getAllCriteriaEmitters())s.dispatchEvent({...o})}}),t.addEventListener("error",()=>{const n={type:"error",payload:new dt(Rz(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 ${At(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,s=r?.find(c=>c.name==="websocket-url")?.valueUrl;if(!o)throw new dt(gn("Failed to get token"));if(!s)throw new dt(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:s}=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),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(Ge(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 gV(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 Jy(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}}const JD="4.4.0-1ce85f8ea",yV=un.FHIR_JSON+", */*; q=0.1",xV="https://api.medplum.com/",bV=1e3,SV=6e4,wV=0,jV=3e5,CV="Binary/",NE={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},oc={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"},EV={AccessToken:"urn:ietf:params:oauth:token-type:access_token"},TV={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"};class eA extends um{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??RV(),this.storage=t?.storage??new dV,this.createPdfImpl=t?.createPdf,this.baseUrl=db(t?.baseUrl??xV),this.fhirBaseUrl=Zi(this.baseUrl,t?.fhirUrlPath??"fhir/R4"),this.authorizeUrl=Zi(this.baseUrl,t?.authorizeUrl??"oauth2/authorize"),this.tokenUrl=Zi(this.baseUrl,t?.tokenUrl??"oauth2/token"),this.logoutUrl=Zi(this.baseUrl,t?.logoutUrl??"oauth2/logout"),this.fhircastHubUrl=Zi(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??jV,this.cacheTime=t?.cacheTime??(typeof window>"u"?wV:SV),this.cacheTime>0?this.requestCache=new dD(t?.resourceCacheSize??bV):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(),typeof window<"u"&&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=Zi(this.fhirBaseUrl,t);if(this.requestCache)for(const r of this.requestCache.keys())(r.endsWith(n)||r.includes(n+"?"))&&this.requestCache.delete(r)}get(t,n={}){t=t.toString();const r=this.getCacheEntry(t,n);if(r)return r.value;let 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 s=new Ai(o);return this.setCacheEntry(t,s),s}post(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("POST",t,o)}put(t,n,r,o={}){return t=t.toString(),this.setRequestBody(o,n),r&&this.setRequestContentType(o,r),this.invalidateUrl(t),this.request("PUT",t,o)}patch(t,n,r={}){return t=t.toString(),this.setRequestBody(r,n),this.setRequestContentType(r,un.JSON_PATCH),this.invalidateUrl(t),this.request("PATCH",t,r)}delete(t,n){return t=t.toString(),this.invalidateUrl(t),this.request("DELETE",t,n)}async startNewUser(t,n){const{codeChallengeMethod:r,codeChallenge:o}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:r,codeChallenge:o},void 0,n)}async startNewProject(t,n){return this.post("auth/newproject",t,void 0,n)}async startNewPatient(t,n){return this.post("auth/newpatient",t,void 0,n)}async startLogin(t,n){return this.post("auth/login",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async startGoogleLogin(t,n){return this.post("auth/google",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async ensureCodeChallenge(t){return t.codeChallenge?t:{...t,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(t){const r=new URLSearchParams(window.location.search).get("code");if(!r){await this.requestAuthorization(t);return}return this.processCode(r)}signOutWithRedirect(){window.location.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,r,o,s=!0){let c=o;s&&(c=await this.ensureCodeChallenge(o)),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:oc.TokenExchange,subject_token_type:EV.AccessToken,client_id:n,subject_token:t})}getExternalAuthRedirectUri(t,n,r,o,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",o.scope??"openid profile email"),c.searchParams.set("state",JSON.stringify(o)),s){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(Zi(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){const r=this.fhirUrl(t);return n&&(r.search=yU(n)),r}search(t,n,r){const o=this.fhirSearchUrl(t,n),s="search-"+o.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=this.getBundle(o,r);return this.setCacheEntry(s,d),d}searchOne(t,n,r){const o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();const s="searchOne-"+o.toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=new Ai(this.search(t,o.searchParams,r).then(f=>f.entry?.[0]?.resource));return this.setCacheEntry(s,d),d}searchResources(t,n,r){const s="searchResources-"+this.fhirSearchUrl(t,n).toString(),c=this.getCacheEntry(s,r);if(c)return c.value;const d=new Ai(this.search(t,n,r).then(LE));return this.setCacheEntry(s,d),d}async*searchResourcePages(t,n,r){let o=this.fhirSearchUrl(t,n);for(;o;){const s=new URL(o).searchParams;s.has("_count")||s.set("_count","1000");const c=await this.search(t,s,r),d=c.link?.find(f=>f.relation==="next");if(!c.entry?.length&&!d)break;yield LE(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 NE;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 Ai(Promise.reject(new Error("Missing reference")));if(r==="system")return new Ai(Promise.resolve(NE));const[o,s]=r.split("/");return!o||!s?new Ai(Promise.reject(new Error("Invalid reference"))):this.readResource(o,s,n)}requestSchema(t){if(yD(t))return Promise.resolve();const n=t+"-requestSchema",r=this.getCacheEntry(n,void 0);if(r)return r.value;const o=new Ai((async()=>{const s=`{
|
|
88
88
|
StructureDefinitionList(_filter: "name eq ${t}") {
|
|
89
89
|
resourceType,
|
|
90
90
|
name,
|
|
@@ -125,357 +125,357 @@ function bO(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&
|
|
|
125
125
|
target
|
|
126
126
|
}
|
|
127
127
|
}`.replace(/\s+/g," "),c=await this.graphql(s);mE(c.data.StructureDefinitionList);for(const d of c.data.SearchParameterList)DU(d)})());return this.setCacheEntry(n,o),o}requestProfileSchema(t,n){if(!n?.expandProfile&&ab(t))return Promise.resolve();const r=t+"-requestSchema"+(n?.expandProfile?"-nested":""),o=this.getCacheEntry(r,void 0);if(o)return o.value;const s=new Ai((async()=>{if(n?.expandProfile){const c=this.fhirUrl("StructureDefinition","$expand-profile");c.search=new URLSearchParams({url:t}).toString();const d=await this.post(c.toString(),{});mE(d)}else{const c=await this.searchOne("StructureDefinition",{url:t,_sort:"-_lastUpdated"});if(!c){console.warn(`No StructureDefinition found for ${t}!`);return}vD(c)}})());return this.setCacheEntry(r,s),s}readHistory(t,n,r,o){const s=this.fhirUrl(t,n,"_history");return r?.count&&s.searchParams.set("_count",r.count.toString()),r?.offset&&s.searchParams.set("_offset",r.offset.toString()),this.get(s.toString(),o)}readVersion(t,n,r,o){return this.get(this.fhirUrl(t,n,"_history",r),o)}readPatientEverything(t,n){return this.getBundle(this.fhirUrl("Patient",t,"$everything"),n)}readPatientSummary(t,n){return this.getBundle(this.fhirUrl("Patient",t,"$summary"),n)}createResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");return this.invalidateSearches(t.resourceType),this.post(this.fhirUrl(t.resourceType),t,void 0,n)}async createResourceIfNoneExist(t,n,r){const o=this.fhirUrl(t.resourceType);r?r.headers?Array.isArray(r.headers)?r.headers.push(["If-None-Exist",n]):r.headers instanceof Headers?r.headers.set("If-None-Exist",n):r.headers["If-None-Exist"]=n:r.headers={"If-None-Exist":n}:r={headers:{"If-None-Exist":n}};const s=await this.post(o,t,void 0,r);return this.cacheResource(s),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),s}async upsertResource(t,n,r){const o=this.fhirSearchUrl(t.resourceType,n);let s=await this.put(o,t,void 0,r);return s||(s=t),this.cacheResource(s),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),s}async createAttachment(t,n,r,o,s){let c=IE(t,n,r,o);if(c.contentType===un.XML){const p=c.data;let m;p instanceof Blob?m=await new Promise((g,x)=>{const b=new FileReader;b.onload=()=>{if(!b.result){x(new Error("Failed to load file"));return}g(b.result)},b.readAsText(p,"utf-8")}):ArrayBuffer.isView(p)?m=new TextDecoder().decode(p):m=p,m.includes("<ClinicalDocument")&&m.includes("urn:hl7-org:v3")&&(c={...c,contentType:un.CDA_XML})}const d=s??(typeof n=="object"?n:{}),f=await this.createBinary(c,d);return{contentType:c.contentType,url:f.url,title:c.filename}}createBinary(t,n,r,o,s){const c=IE(t,n,r,o),d=s??(typeof n=="object"?n:{}),{data:f,contentType:p,filename:m,securityContext:g,onProgress:x}=c,b=this.fhirUrl("Binary");return m&&b.searchParams.set("_filename",m),g?.reference&&this.setRequestHeader(d,"X-Security-Context",g.reference),x?this.uploadwithProgress(b,f,p,x,d):this.post(b,f,p,d)}uploadwithProgress(t,n,r,o,s){return new Promise((c,d)=>{const f=new XMLHttpRequest,p=()=>f.abort();s?.signal?.addEventListener("abort",p);const m=g=>{s?.signal?.removeEventListener("abort",p),g instanceof Error?d(g):c(g)};if(f.responseType="json",f.onabort=()=>m(new DOMException("Request aborted","AbortError")),f.onerror=()=>m(new Error("Request error")),o&&(f.upload.onprogress=g=>o(g),f.upload.onload=g=>o(g)),f.onload=()=>{f.status>=200&&f.status<300?m(f.response):m(new dt(Ht(f.response||f.statusText)))},f.open("POST",t),f.withCredentials=!0,f.setRequestHeader("Authorization","Bearer "+this.accessToken),f.setRequestHeader("Cache-Control","no-cache, no-store, max-age=0"),f.setRequestHeader("Content-Type",r),this.options.extendedMode!==!1&&f.setRequestHeader("X-Medplum","extended"),s?.headers){const g=s.headers;for(const[x,b]of Object.entries(g))f.setRequestHeader(x,b)}f.send(n)})}async createPdf(t,n,r,o){if(!this.createPdfImpl)throw new Error("PDF creation not enabled");const s=AV(t,n,r,o),c=typeof n=="object"?n:{},{docDefinition:d,tableLayouts:f,fonts:p,...m}=s,g=await this.createPdfImpl(d,f,p),x={...m,data:g,contentType:"application/pdf"};return this.createBinary(x,c)}createComment(t,n,r){const o=this.getProfile();let s,c;return t.resourceType==="Encounter"&&(s=qt(t),c=t.subject),t.resourceType==="ServiceRequest"&&(s=t.encounter,c=t.subject),t.resourceType==="Patient"&&(c=qt(t)),this.createResource({resourceType:"Communication",status:"completed",basedOn:[qt(t)],encounter:s,subject:c,sender:o?qt(o):void 0,sent:new Date().toISOString(),payload:[{contentString:n}]},r)}async updateResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");if(!t.id)throw new Error("Missing id");let r=await this.put(this.fhirUrl(t.resourceType,t.id),t,void 0,n);return r||(r=t),this.cacheResource(r),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),r}async patchResource(t,n,r,o){const s=await this.patch(this.fhirUrl(t,n),r,o);return this.cacheResource(s),this.invalidateUrl(this.fhirUrl(t,n,"_history")),this.invalidateSearches(t),s}deleteResource(t,n,r){return this.deleteCacheEntry(this.fhirUrl(t,n).toString()),this.invalidateSearches(t),this.delete(this.fhirUrl(t,n),r)}validateResource(t,n){return this.post(this.fhirUrl(t.resourceType,"$validate"),t,void 0,n)}executeBot(t,n,r,o){let s;if(typeof t=="string"){const c=t;s=this.fhirUrl("Bot",c,"$execute")}else{const c=t;s=this.fhirUrl("Bot","$execute"),s.searchParams.set("identifier",c.system+"|"+c.value)}return this.post(s,n,r,o)}executeBatch(t,n){return this.post(this.fhirBaseUrl,t,void 0,n)}sendEmail(t,n){return this.post("email/v1/send",t,un.JSON,n)}graphql(t,n,r,o){return this.post(this.fhirUrl("$graphql"),{query:t,operationName:n,variables:r},un.JSON,o)}readResourceGraph(t,n,r,o){return this.get(`${this.fhirUrl(t,n)}/$graph?graph=${r}`,o)}pushToAgent(t,n,r,o,s,c){const{waitTimeout:d,...f}=c??{};return this.post(this.fhirUrl("Agent",Hs(t),"$push"),{destination:typeof n=="string"?n:At(n),body:r,contentType:o,waitForResponse:s,...d!==void 0?{waitTimeout:d}:void 0},un.FHIR_JSON,f)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(t){(!this.sessionDetails?.profile||At(this.sessionDetails.profile)!==t.profile?.reference)&&this.clearActiveLogin(),this.setAccessToken(t.accessToken,t.refreshToken),this.storage.setObject("activeLogin",t),this.addLogin(t),this.refreshPromise=void 0,await this.refreshProfile()}getAccessToken(){return this.accessToken}isAuthenticated(t){return this.accessTokenExpires!==void 0&&Date.now()<this.accessTokenExpires-(t??this.refreshGracePeriod)}setAccessToken(t,n){this.accessToken=t,this.refreshToken=n,this.accessTokenExpires=cV(t),this.medplumServer=lV(t)}getLogins(){return this.storage.getObject("logins")??[]}addLogin(t){const n=this.getLogins().filter(r=>r.profile?.reference!==t.profile?.reference);n.push(t),this.storage.setObject("logins",n)}async refreshProfile(){return this.medplumServer?(this.profilePromise=new Promise((t,n)=>{this.get("auth/me",{cache:"no-cache"}).then(r=>{this.profilePromise=void 0;const o=this.sessionDetails?.profile?.id!==r.profile.id;this.sessionDetails=r,o&&this.dispatchEvent({type:"change"}),t(r.profile),this.dispatchEvent({type:"profileRefreshed"})}).catch(n)}),this.dispatchEvent({type:"profileRefreshing"}),this.profilePromise):Promise.resolve(void 0)}isLoading(){return!this.isInitialized||!!this.profilePromise&&!this.sessionDetails?.profile}isSuperAdmin(){return!!this.sessionDetails?.project.superAdmin}isProjectAdmin(){return!!this.sessionDetails?.membership.admin}getProject(){return this.sessionDetails?.project}getProjectMembership(){return this.sessionDetails?.membership}getProfile(){return this.sessionDetails?.profile}async getProfileAsync(){return this.profilePromise?this.profilePromise:this.sessionDetails?this.sessionDetails.profile:this.refreshProfile()}getUserConfiguration(){return this.sessionDetails?.config}getAccessPolicy(){return this.sessionDetails?.accessPolicy}async download(t,n={}){this.refreshPromise&&await this.refreshPromise;const r=t.toString();r.startsWith(CV)&&(t=this.fhirUrl(r));let o=n.headers;return o||(o={},n.headers=o),o.Accept||(o.Accept="*/*"),this.addFetchOptionsDefaults(n),(await this.fetchWithRetry(t.toString(),n)).blob()}async createMedia(t,n){const{additionalFields:r,...o}=t,s=await this.createResource({resourceType:"Media",status:"preparation",content:{contentType:t.contentType},...r});o.securityContext||(o.securityContext=qt(s));const c=await this.createAttachment(o,n);return this.updateResource({...s,status:"completed",content:c})}async uploadMedia(t,n,r,o,s){return this.createMedia({data:t,contentType:n,filename:r,additionalFields:o},s)}async createDocumentReference(t,n){const{additionalFields:r,...o}=t,s=await this.createResource({resourceType:"DocumentReference",status:"current",content:[{attachment:{contentType:t.contentType}}],...r});o.securityContext||(o.securityContext=qt(s));const c=await this.createAttachment(o,n);return this.updateResource({...s,content:[{attachment:c}]})}async bulkExport(t="",n,r,o){const s=t&&`${t}/`,c=this.fhirUrl(`${s}$export`);return n&&c.searchParams.set("_type",n),r&&c.searchParams.set("_since",r),this.startAsyncRequest(c.toString(),o)}async startAsyncRequest(t,n={}){this.addFetchOptionsDefaults(n);const r=n.headers;return r.Prefer="respond-async",this.request("POST",t,n)}get keyValue(){return this.keyValueClient||(this.keyValueClient=new uV(this)),this.keyValueClient}getBundle(t,n){return new Ai((async()=>{const r=await this.get(t,n);if(r.entry)for(const o of r.entry)this.cacheResource(o.resource);return r})())}getCacheEntry(t,n){if(!this.requestCache||n?.cache==="no-cache"||n?.cache==="reload")return;const r=this.requestCache.get(t);if(!(!r||r.requestTime+this.cacheTime<Date.now()))return r}setCacheEntry(t,n){this.requestCache&&this.requestCache.set(t,{requestTime:Date.now(),value:n})}cacheResource(t){t?.id&&!t.meta?.tag?.some(n=>n.code==="SUBSETTED")&&this.setCacheEntry(this.fhirUrl(t.resourceType,t.id).toString(),new Ai(Promise.resolve(t)))}deleteCacheEntry(t){this.requestCache&&this.requestCache.delete(t)}async request(t,n,r={},o={}){await this.refreshIfExpired(),r.method=t,this.addFetchOptionsDefaults(r);const s=await this.fetchWithRetry(n,r);if(s.status===401)return this.handleUnauthenticated(t,n,r);if(s.status===204||s.status===304)return;const d=s.headers.get("content-type")?.includes("json");if(s.status===404&&!d)throw new dt(Ez);const f=await this.parseBody(s,d);if(s.status===200&&r.followRedirectOnOk||s.status===201&&r.followRedirectOnCreated){const p=await ME(s,f);if(p)return this.request("GET",p,{...r,body:void 0})}if(s.status===202&&r.pollStatusOnAccepted){const m=await ME(s,f)??o.statusUrl;if(m)return this.pollStatus(m,r,o)}if(s.status>=400)throw new dt(Ht(f));return f}async parseBody(t,n){let r;if(t.headers.get("content-length")!=="0"){if(n)try{r=await t.json()}catch(o){throw console.error("Error parsing response",t.status,o),o}else r=await t.text();return r}}async fetchWithRetry(t,n){t.startsWith("http")||(t=Zi(this.baseUrl,t));const r=n?.maxRetries??2;for(let o=0;o<=r;o++)try{this.options.verbose&&this.logRequest(t,n);const s=await this.fetch(t,n);if(this.options.verbose&&this.logResponse(s),this.setCurrentRateLimit(s),o>=r||!PV(s))return s;const c=this.getRetryDelay(o),d=n.maxRetryTime??2e3;if(c>d)return s;await wE(c)}catch(s){if(s.message==="Failed to fetch"&&o===0&&this.dispatchEvent({type:"offline"}),s.name==="AbortError"||o===r)throw s}throw new Error("Unreachable")}logRequest(t,n){if(console.log(`> ${n.method} ${t}`),n.headers){const r=n.headers;for(const o of Ec(Object.keys(r)))console.log(`> ${o}: ${r[o]}`)}}logResponse(t){console.log(`< ${t.status} ${t.statusText}`),t.headers&&t.headers.forEach((n,r)=>console.log(`< ${r}: ${n}`))}setCurrentRateLimit(t){const n=t.headers?.get("ratelimit");n&&(this.currentRateLimits=n)}rateLimitStatus(){if(!this.currentRateLimits)return[];const t=this.currentRateLimits;return t.split(/\s*;\s*/g).map(n=>{const r=n.split(/\s*,\s*/g);if(r.length!==3)throw new Error("Could not parse RateLimit header: "+t);const o=r[0].substring(1,r[0].length-1),s=r.find(p=>p.startsWith("r=")),c=s?parseInt(s.substring(2),10):NaN,d=r.find(p=>p.startsWith("t=")),f=d?parseInt(d.substring(2),10):NaN;if(!o||Number.isNaN(c)||Number.isNaN(f))throw new Error("Could not parse RateLimit header: "+t);return{name:o,remainingUnits:c,secondsUntilReset:f}})}getRetryDelay(t){const n=this.rateLimitStatus();let r=500*Math.pow(1.5,t);for(const o of n)o.remainingUnits||(r=Math.max(r,o.secondsUntilReset*1e3));return r}async pollStatus(t,n,r){const o={...n,method:"GET",body:void 0,redirect:"follow"};if(r.pollCount===void 0)n.headers&&typeof n.headers=="object"&&"Prefer"in n.headers&&(o.headers={...n.headers},delete o.headers.Prefer),r.statusUrl=t,r.pollCount=1;else{const s=n.pollStatusPeriod??1e3;await wE(s),r.pollCount++}return this.request("GET",t,o,r)}async executeAutoBatch(){if(this.autoBatchQueue===void 0)return;const t=[...this.autoBatchQueue];if(this.autoBatchQueue.length=0,this.autoBatchTimerId=void 0,t.length===1){const o=t[0];try{o.resolve(await this.request(o.method,Zi(this.fhirBaseUrl,o.url),o.options))}catch(s){o.reject(new dt(Ht(s)))}return}const n={resourceType:"Bundle",type:"batch",entry:t.map(o=>({request:{method:o.method,url:o.url},resource:o.options.body?JSON.parse(o.options.body):void 0}))},r=await this.post(this.fhirBaseUrl,n);for(let o=0;o<t.length;o++){const s=t[o],c=r.entry?.[o];c?.response?.outcome&&!hD(c.response.outcome)?s.reject(new dt(c.response.outcome)):s.resolve(c?.resource)}}addFetchOptionsDefaults(t){Object.entries(this.defaultHeaders).forEach(([n,r])=>{this.setRequestHeader(t,n,r)}),this.setRequestHeader(t,"Accept",yV,!0),this.options.extendedMode!==!1&&this.setRequestHeader(t,"X-Medplum","extended"),t.body&&this.setRequestHeader(t,"Content-Type",un.FHIR_JSON,!0),this.accessToken?this.setRequestHeader(t,"Authorization","Bearer "+this.accessToken):this.basicAuth&&this.setRequestHeader(t,"Authorization","Basic "+this.basicAuth),t.cache||(t.cache="no-cache"),t.credentials||(t.credentials="include")}setRequestContentType(t,n){this.setRequestHeader(t,"Content-Type",n)}setRequestHeader(t,n,r,o=!1){t.headers||(t.headers={});const s=t.headers;o&&s[n]||(s[n]=r)}setRequestBody(t,n){typeof n=="string"||typeof Blob<"u"&&(n instanceof Blob||n?.constructor.name==="Blob")||typeof File<"u"&&(n instanceof File||n?.constructor.name==="File")||typeof Uint8Array<"u"&&(n instanceof Uint8Array||n?.constructor.name==="Uint8Array")?t.body=n:n&&(t.body=JSON.stringify(n))}handleUnauthenticated(t,n,r){return this.refresh()?this.request(t,n,r):(this.clear(),this.onUnauthenticated&&this.onUnauthenticated(),Promise.reject(new dt(ad)))}async startPkce(){const t=_E();sessionStorage.setItem("pkceState",t);const n=_E().slice(0,128);sessionStorage.setItem("codeVerifier",n);try{const r=await HB(n);return{codeChallengeMethod:"S256",codeChallenge:fU(r).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}}catch(r){return console.warn("Failed to hash code verifier. Falling back to 'plain' code challenge method",r),{codeChallengeMethod:"plain",codeChallenge:n}}}async requestAuthorization(t){const n=await this.ensureCodeChallenge(t??{}),r=new URL(this.authorizeUrl);r.searchParams.set("response_type","code"),r.searchParams.set("state",sessionStorage.getItem("pkceState")),r.searchParams.set("client_id",n.clientId??this.clientId),r.searchParams.set("redirect_uri",n.redirectUri??OE()),r.searchParams.set("code_challenge_method",n.codeChallengeMethod),r.searchParams.set("code_challenge",n.codeChallenge),r.searchParams.set("scope",n.scope??"openid profile"),window.location.assign(r.toString())}processCode(t,n){const r={grant_type:oc.AuthorizationCode,code:t,client_id:n?.clientId??this.clientId??"",redirect_uri:n?.redirectUri??OE()};if(typeof sessionStorage<"u"){const o=sessionStorage.getItem("codeVerifier");o&&(r.code_verifier=o)}return this.fetchTokens(r)}refreshIfExpired(t){return!this.refreshPromise&&this.accessTokenExpires!==void 0&&!this.isAuthenticated(t)&&this.refresh(),this.refreshPromise??Promise.resolve()}refresh(){if(this.refreshPromise)return this.refreshPromise;if(this.refreshToken)return this.refreshPromise=this.fetchTokens({grant_type:oc.RefreshToken,client_id:this.clientId??"",refresh_token:this.refreshToken}),this.refreshPromise;if(this.clientId&&this.clientSecret)return this.refreshPromise=this.startClientLogin(this.clientId,this.clientSecret),this.refreshPromise}async startClientLogin(t,n){return this.clientId=t,this.clientSecret=n,this.fetchTokens({grant_type:oc.ClientCredentials,client_id:t,client_secret:n})}async startJwtBearerLogin(t,n,r){return this.clientId=t,this.fetchTokens({grant_type:oc.JwtBearer,client_id:t,assertion:n,scope:r})}async startJwtAssertionLogin(t){return this.fetchTokens({grant_type:oc.ClientCredentials,client_assertion_type:TV.JwtBearer,client_assertion:t})}setBasicAuth(t,n){this.clientId=t,this.clientSecret=n,this.basicAuth=RE(t+":"+n)}async fhircastSubscribe(t,n){if(!(typeof t=="string"&&t!==""))throw new dt(gn("Invalid topic provided. Topic must be a valid string."));if(!(typeof n=="object"&&Array.isArray(n)&&n.length>0))throw new dt(gn("Invalid events provided. Events must be an array of event names containing at least one event."));const r={channelType:"websocket",mode:"subscribe",topic:t,events:n},s=(await this.post(this.fhircastHubUrl,DE(r),un.FORM_URL_ENCODED))["hub.channel.endpoint"];if(!s)throw new Error("Invalid response!");return r.endpoint=s,r}async fhircastUnsubscribe(t){if(!Sb(t))throw new dt(gn("Invalid topic or subscriptionRequest. SubscriptionRequest must be an object."));if(!(t.endpoint&&typeof t.endpoint=="string"&&t.endpoint.startsWith("ws")))throw new dt(gn("Provided subscription request must have an endpoint in order to unsubscribe."));t.mode="unsubscribe",await this.post(this.fhircastHubUrl,DE(t),un.FORM_URL_ENCODED)}fhircastConnect(t){return new oV(t)}async fhircastPublish(t,n,r,o){return ZB(n)?this.post(this.fhircastHubUrl,AE(t,n,r,o),un.JSON):(JB(n),this.post(this.fhircastHubUrl,AE(t,n,r),un.JSON))}async fhircastGetContext(t){return this.get(`${this.fhircastHubUrl}/${t}`,{cache:"no-cache"})}async invite(t,n){return this.post("admin/projects/"+t+"/invite",n)}async fetchTokens(t){const n=new URLSearchParams(t),r={...this.defaultHeaders,"Content-Type":un.FORM_URL_ENCODED};this.basicAuth&&(r.Authorization=`Basic ${this.basicAuth}`),this.credentialsInHeader&&(n.delete("client_id"),n.delete("client_secret"),!this.basicAuth&&t.client_id&&t.client_secret&&(r.Authorization=`Basic ${RE(t.client_id+":"+t.client_secret)}`));const o={method:"POST",headers:r,body:n.toString(),credentials:"include"};let s;try{s=await this.fetchWithRetry(this.tokenUrl,o)}catch(d){throw this.refreshPromise=void 0,d}if(!s.ok){this.clearActiveLogin();try{const d=await s.json();throw new dt(io(d.error_description))}catch(d){throw new dt(io("Failed to fetch tokens"),d)}}const c=await s.json();return await this.verifyTokens(c),this.getProfile()}async verifyTokens(t){const n=t.access_token;if(sV(n)){const r=wb(n);if(Date.now()>=r.exp*1e3)throw this.clearActiveLogin(),new dt(Tz);if(r.cid){if(r.cid!==this.clientId)throw this.clearActiveLogin(),new dt(hE)}else if(this.clientId&&r.client_id!==this.clientId)throw this.clearActiveLogin(),new dt(hE)}return this.setActiveLogin({accessToken:n,refreshToken:t.refresh_token,project:t.project,profile:t.profile})}checkSessionDetailsMatchLogin(t){return this.sessionDetails&&t?t.profile?.reference?.endsWith(this.sessionDetails.profile.id)??!1:!0}setupStorageListener(){try{window.addEventListener("storage",t=>{if(t.key===null)window.location.reload();else if(t.key==="activeLogin"){const n=t.oldValue?JSON.parse(t.oldValue):void 0,r=t.newValue?JSON.parse(t.newValue):void 0;n?.profile.reference!==r?.profile.reference||!this.checkSessionDetailsMatchLogin(r)?window.location.reload():r?this.setAccessToken(r.accessToken,r.refreshToken):this.clear()}})}catch{}}getSubscriptionManager(){return this.subscriptionManager||(this.subscriptionManager=new vV(this,vU(this.baseUrl,"/ws/subscriptions-r4"))),this.subscriptionManager}subscribeToCriteria(t,n){return this.getSubscriptionManager().addCriteria(t,n)}unsubscribeFromCriteria(t,n){this.subscriptionManager&&(this.subscriptionManager.removeCriteria(t,n),this.subscriptionManager.getCriteriaCount()===0&&this.subscriptionManager.closeWebSocket())}getMasterSubscriptionEmitter(){return this.getSubscriptionManager().getMasterEmitter()}}function RV(){if(!globalThis.fetch)throw new Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}function OE(){return typeof window>"u"?"":window.location.protocol+"//"+window.location.host+"/"}async function ME(e,t){const n=e.headers.get("content-location");if(n)return n;const r=e.headers.get("location");if(r)return r;if(rm(t)&&t.issue?.[0]?.diagnostics)return t.issue[0].diagnostics}function LE(e){const t=e.entry?.map(n=>n.resource)??[];return Object.assign(t,{bundle:e})}function _V(e){return sr(e)&&"data"in e&&"contentType"in e}function IE(e,t,n,r){return _V(e)?e:{data:e,filename:t,contentType:n,onProgress:r}}function DV(e){return sr(e)&&"docDefinition"in e}function AV(e,t,n,r){return DV(e)?e:{docDefinition:e,filename:t,tableLayouts:n,fonts:r}}function PV(e){return e.status===429||e.status>=500}function Tc({parentContext:e,path:t,elements:n,profileUrl:r,debugMode:o,accessPolicyResource:s}){if(t===e?.path)return;o??=e?.debugMode??!1,s??=e?.accessPolicyResource;let c=kV(t,n,e,!!o);const d=Xy(t,".",2)[1];c=NV(c,s,d),c=OV(c,s,d);const f=Object.create(null);for(const[m,g]of Object.entries(c))f[t+"."+m]=g;let p;if(e&&!e.isDefaultContext)p=e.getExtendedProps;else{const m=Object.create(null);p=g=>{const x=Xy(g,".",2)[1];if(x){if(!m[x]){const b=Zh(x,s?.hiddenFields);m[x]={hidden:b,readonly:b||Zh(x,s?.readonlyFields)}}return m[x]}}}return{path:t,elements:c,elementsByPath:f,profileUrl:r??e?.profileUrl,debugMode:o,getExtendedProps:p,accessPolicyResource:s}}function kV(e,t,n,r){const o=Object.create(null);if(n)for(const[c,d]of Object.entries(n.elementsByPath)){const f=Is(e,c);f!==void 0&&(o[f]=d)}let s=!1;if(t)for(const[c,d]of Object.entries(t))c in o||(o[c]=d,s=!0);return r&&console.assert(s,"Unnecessary ElementsContext; not using any newly provided elements"),o}function NV(e,t,n){if(!t?.hiddenFields?.length)return e;const r=n?n+".":"";return Object.fromEntries(Object.entries(e).filter(([o])=>!Zh(r+o,t.hiddenFields)))}function OV(e,t,n){if(!t?.readonlyFields?.length)return e;const r=Object.create(null),o=n?n+".":"";for(const[s,c]of Object.entries(e))Zh(o+s,t.readonlyFields)?r[s]={...c,readonly:!0}:r[s]=c;return r}function Zh(e,t){if(!t?.length)return!1;const n=e.split(".");for(let r=1;r<=n.length;r++){const o=n.slice(0,r).join(".");if(t.includes(o))return!0}return!1}function tA(e){return e.type!==void 0&&e.type.length>0}function MV(e,t,n,r){const o=F8(e,t.path,{profileUrl:r});if(o){const s=n.typeSchema?.elements??n.elements;return o.some(c=>G8(c,t,n,s))??!1}return console.assert(!1,"getNestedProperty[%s] in isDiscriminatorComponentMatch missed",t.path),!1}function nA(e,t,n,r){if(e)for(const o of t){const s={value:e,type:o.typeSchema?.type??o.type?.[0].code};if(n.every(c=>MV(s,c,o,o.typeSchema?.url??r)))return o.name}}class LV{constructor(t,n,r){if(t.type===void 0)throw new Error("schema must include a type");this.rootSchema=t;const o=Tc({parentContext:void 0,path:this.rootSchema.type,elements:r??this.rootSchema.elements,profileUrl:this.rootSchema.name===this.rootSchema.type?void 0:this.rootSchema.url});if(o===void 0)throw new Error("Could not create root elements context");this.elementsContextStack=[o],this.visitor=n}get elementsContext(){return this.elementsContextStack[this.elementsContextStack.length-1]}crawlElement(t,n,r){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema);const o=Object.fromEntries(Object.entries(this.elementsContext.elements).filter(([s])=>s.startsWith(n)));this.crawlElementsImpl(o,r),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlSlice(t,n,r){const o=this.prepareSlices(r.slices,r);if(!Tn(o.slices))throw new Error(`cannot crawl slice ${n.name} since it has no type information`);this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.sliceAllowList=[n],this.crawlSliceImpl(o.slices[0],n.path,o),this.sliceAllowList=void 0,this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlResource(){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.crawlElementsImpl(this.rootSchema.elements,this.rootSchema.type),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlElementsImpl(t,n){const r=IV(t);for(const o of r)this.crawlElementNode(o,n)}crawlElementNode(t,n){const r=n+"."+t.key;this.visitor.onEnterElement&&this.visitor.onEnterElement(r,t.element,this.elementsContext);for(const o of t.children)this.crawlElementNode(o,n);Tn(t.element?.slicing?.slices)&&this.crawlSlicingImpl(t.element.slicing,r),this.visitor.onExitElement&&this.visitor.onExitElement(r,t.element,this.elementsContext)}prepareSlices(t,n){const r=[];for(const s of t){if(!tA(s))continue;const c=s.type.find(d=>Tn(d.profile))?.profile?.[0];if(Tn(c)){const d=Uc(c);d&&(s.typeSchema=d)}r.push(s)}return{...n,slices:r}}crawlSlicingImpl(t,n){const r=this.prepareSlices(t.slices,t);for(const o of r.slices)(this.sliceAllowList===void 0||this.sliceAllowList.includes(o))&&this.crawlSliceImpl(o,n,r)}crawlSliceImpl(t,n,r){const o=t.typeSchema;o&&this.visitor.onEnterSchema&&this.visitor.onEnterSchema(o),this.visitor.onEnterSlice&&this.visitor.onEnterSlice(n,t,r);let s;const c=o?.elements??t.elements;Tn(c)&&(s=Tc({path:n,parentContext:this.elementsContext,elements:c})),s&&this.elementsContextStack.push(s),this.crawlElementsImpl(c,n),s&&this.elementsContextStack.pop(),this.visitor.onExitSlice&&this.visitor.onExitSlice(n,t,r),o&&this.visitor.onExitSchema&&this.visitor.onExitSchema(o)}}function IV(e){const t=[];function n(s,c){return c.startsWith(s+".")}function r(s,c){for(const d of s.children)if(n(d.key,c.key)){r(d,c);return}s.children.push(c)}const o=Object.entries(e);o.sort((s,c)=>s[0].localeCompare(c[0]));for(const[s,c]of o){const d={key:s,element:c,children:[]};let f=!1;for(const p of t)if(n(p.key,s)){r(p,d),f=!0;break}f||t.push(d)}return t}const ly="__sliceName";function $V(e,t){const n=new zV(e,e.resourceType,"resource");return new LV(t,n).crawlResource(),n.getDefaultValue()}function $E(e,t,n){for(const[r,o]of Object.entries(t)){if(n===void 0||n===r){Jh(e,r,o,t);continue}const s=Is(n,r);s!==void 0&&Jh(e,s,o,t)}return e}class zV{constructor(t,n,r){this.schemaStack=[],this.valueStack=[],this.rootValue=Kr(t),this.valueStack.splice(0,this.valueStack.length,{type:r,path:n,values:[this.rootValue]})}get schema(){return this.schemaStack[this.schemaStack.length-1]}get value(){return this.valueStack[this.valueStack.length-1]}onEnterSchema(t){this.schemaStack.push(t)}onExitSchema(){this.schemaStack.pop()}onEnterElement(t,n,r){const o=this.value.values,s=this.value.path,c=Is(s,t);if(c===void 0)throw new Error(`Expected ${t} to be prefixed by ${s}`);const d=[];for(const f of o){if(f===void 0)continue;const p=Is(r.path,s),m=Array.isArray(f)?f:[f];for(const g of m){UV(g,c,n,r.elements,p),Jh(g,c,n,r.elements);const x=tx(g,c,r.elements,p);x!==void 0&&d.push(x)}}this.valueStack.push({type:"element",path:t,values:d})}onExitElement(t,n,r){if(!this.valueStack.pop())throw new Error("Expected value context to exist when exiting element");const s=Is(this.value.path,t);if(s===void 0)throw new Error(`Expected ${t} to be prefixed by ${this.value.path}`);const c=Is(r.path,this.value.path);for(const d of this.value.values){const f=tx(d,s,r.elements,c);if(Array.isArray(f))for(let p=f.length-1;p>=0;p--){const m=f[p];Tn(m)||f.splice(p,1)}xn(f)&&ex(d,void 0,s,n)}}onEnterSlice(t,n,r){const o=this.value.values,s=[];for(const c of o)if(c!==void 0){const d=Array.isArray(c)?c:[c],f=this.getMatchingSliceValues(d,n,r);s.push(f)}this.valueStack.push({type:"slice",path:t,values:s})}getMatchingSliceValues(t,n,r){const o=[];for(const s of t)(s[ly]??nA(s,[n],r.discriminator,this.schema.url))===n.name&&o.push(s);for(let s=o.length;s<n.min;s++)if(ub(n.type[0].code)){const c=Object.create(null);o.push(c),t.push(c)}return o}onExitSlice(){const t=this.valueStack.pop();if(!t)throw new Error("Expected value context to exist in onExitSlice");for(const n of t.values)for(let r=n.length-1;r>=0;r--){const o=n[r];ly in o&&delete o[ly]}}getDefaultValue(){return this.rootValue}}function UV(e,t,n,r,o){const s=tx(e,t,r,o);n.min>0&&s===void 0&&ub(n.type[0].code)&&(n.isArray?ex(e,[Object.create(null)],t,n):ex(e,Object.create(null),t,n))}function ex(e,t,n,r){if(n.includes("."))throw new Error("key cannot be nested");let o=n;if(n.includes("[x]")){const s=r.type[0].code;o=n.replace("[x]",Ln(s))}t===void 0?delete e[o]:e[o]=t}function tx(e,t,n,r){const o=t.split(".");let s=e,c;for(let d=0;d<o.length;d++){let f=o[d];if(f.includes("[x]")){const p=(r?r+".":"")+o.slice(0,d+1).join("."),g=n[p].type[0].code;f=f.replace("[x]",Ln(g))}if(d===o.length-1){Array.isArray(s)?c=s.map(p=>p[f]):c=s[f];continue}if(Array.isArray(s))s=s.map(p=>p[f]);else if(sr(s)){if(s[f]===void 0)return;s=s[f]}else return}return c}function Jh(e,t,n,r){if(!(n.fixed||n.pattern))return e;if(Array.isArray(e))return e.map(d=>Jh(d,t,n,r));e==null&&(e=Object.create(null));const o=e,s=t.split(".");let c=o;for(let d=0;d<s.length;d++){let f=s[d];if(f.includes("[x]")){const m=r[s.slice(0,d+1).join(".")].type[0].code;f=f.replace("[x]",Ln(m))}if(d===s.length-1){const p=Array.isArray(c)?c:[c];for(const m of p)n.fixed?m[f]??=n.fixed.value:n.pattern&&(m[f]=rA(m[f],n.pattern.value))}else{if(!(f in c)){const p=s.slice(0,d+1).join(".");c[f]=r[p].isArray?[Object.create(null)]:Object.create(null)}c=c[f]}}return o}function rA(e,t){if(Array.isArray(t)&&(Array.isArray(e)||e===void 0))return(e?.length??0)>0?e:Kr(t);if(sr(t)&&(sr(e)&&!Array.isArray(e)||e===void 0)){const n=Kr(e)??Object.create(null);for(const r of Object.keys(t))n[r]=rA(n[r],t[r]);return n}return e}const ir={BOOLEAN:"BOOLEAN",NUMBER:"NUMBER",QUANTITY:"QUANTITY",TEXT:"TEXT",REFERENCE:"REFERENCE",CANONICAL:"CANONICAL",DATE:"DATE",DATETIME:"DATETIME"};function dm(e,t){let n=uo.types[e]?.searchParamsDetails?.[t.code];return n||(n=VV(e,t)),n}function BV(e,t,n){let r=uo.types[e];r||(r={},uo.types[e]=r),r.searchParamsDetails||(r.searchParamsDetails={}),r.searchParamsDetails[t]=n}function VV(e,t){const n=t.code,r=GV(e,t.expression),o={elementDefinitions:[],propertyTypes:new Set,array:!1};for(const c of r){const d=Ph(c),f=mU(()=>d.join("."));d.length===1&&d[0]instanceof Mr?o.propertyTypes.add("boolean"):t.code.endsWith(":identifier")?o.propertyTypes.add("Identifier"):f().endsWith("extension.value.code")||f().endsWith("extension.value.coding.code")?(o.array=!0,o.propertyTypes.clear(),o.propertyTypes.add("code")):iA(o,d,e,1),f().endsWith("extension.valueDateTime")&&(o.array=!1,o.propertyTypes.clear(),o.propertyTypes.add("dateTime"))}const s={type:HV(t,o.propertyTypes),elementDefinitions:o.elementDefinitions.map(c=>({...c,type:c.type?.filter(d=>o.propertyTypes.has(d.code))})).filter(c=>c.type&&c.type.length>0),parsedExpression:WV(e,t.expression),array:o.array};return BV(e,n,s),s}function iA(e,t,n,r){const o=t[r];if(o instanceof Xh){e.propertyTypes.add(o.right.toString());return}if(o instanceof gb){FV(e,o);return}const s=o.toString(),c=is(n,s);if(!c)throw new Error(`Element definition not found for ${n} ${s}`);let d=!1,f=r+1;f<t.length&&t[f]instanceof vb&&(d=!0,f++);const p=t[f];if(c.isArray&&!d&&(e.array=!0),f===t.length-1&&p instanceof Xh){e.elementDefinitions.push(c),e.propertyTypes.add(p.right.toString());return}if(f>=t.length){e.elementDefinitions.push(c);for(const m of c.type)e.propertyTypes.add(m.code);return}for(const m of c.type){let g=m.code;qV(g)&&(g=c.type[0].code),iA(e,t,g,f)}}function FV(e,t){if(t.name==="as"){e.propertyTypes.add(t.args[0].toString());return}if(t.name==="ofType"){e.propertyTypes.add(t.args[0].toString());return}if(t.name==="resolve"){e.propertyTypes.add("string");return}if(t.name==="where"&&t.args[0]instanceof mb){e.propertyTypes.add(t.args[0].right.toString());return}throw new Error(`Unhandled FHIRPath function: ${t.name}`)}function qV(e){return e==="Element"||e==="BackboneElement"}function HV(e,t){switch(e.type){case"date":return t.size===1&&t.has(re.date)?ir.DATE:ir.DATETIME;case"number":return ir.NUMBER;case"quantity":return ir.QUANTITY;case"reference":return t.has(re.canonical)?ir.CANONICAL:ir.REFERENCE;case"token":return t.size===1&&t.has(re.boolean)?ir.BOOLEAN:ir.TEXT;default:return ir.TEXT}}function GV(e,t){const n=[],r=yb(t);return ep(e,r.child,n),n}function WV(e,t){const n=[],r=yb(t);if(ep(e,r.child,n),n.length===0)return r;let o=n[0];for(let s=1;s<n.length;s++)o=new pb(o,n[s]);return new VD("<original-not-available>",o)}function ep(e,t,n){t instanceof pb?(ep(e,t.left,n),ep(e,t.right,n)):t.toString().includes(e+".")&&n.push(t)}function Ph(e){if(e instanceof Xh||e instanceof vb)return[Ph(e.left),e].flat();if(e instanceof Mr)return[e];if(e instanceof hb)return[Ph(e.left),Ph(e.right)].flat();if(e instanceof gb){if(e.name==="where"&&!(e.args[0]instanceof mb))return[];if(e.name==="last")return[]}return[e]}const QV="https://meta.medplum.com/releases",cy=new Map;function YV(e){const t=e;if(!t.tag_name)throw new Error("Manifest missing tag_name");const n=t.assets;if(!n?.length)throw new Error("Manifest missing assets list");for(const r of n){if(!r.browser_download_url)throw new Error("Asset missing browser download URL");if(!r.name)throw new Error("Asset missing name")}}async function KV(e,t,n){let r=cy.get("latest");if(!r){const o="latest",s=new URL(`${QV}/${o}.json`);s.searchParams.set("a",e),s.searchParams.set("c",JD);const c=await fetch(s.toString());if(c.status!==200){let f;try{f=(await c.json()).message}catch(p){console.error(`Failed to parse message from body: ${Ge(p)}`)}throw new Error(`Received status code ${c.status} while fetching manifest for version 'latest'. Message: ${f}`)}const d=await c.json();YV(d),r=d,cy.set("latest",r),cy.set(r.tag_name.slice(1),r)}return r}async function XV(e){const t=await KV(e);if(!t.tag_name.startsWith("v"))throw new Error(`Invalid release name found. Release tag '${t.tag_name}' did not start with 'v'`);return t.tag_name.slice(1)}const oA=v.createContext(void 0);function fm(){return v.useContext(oA)}function De(){return fm().medplum}function hm(){return fm().navigate}function pm(){return fm().profile}const zE=["change","storageInitialized","storageInitFailed","profileRefreshing","profileRefreshed"];function ZV(e){const t=e.medplum,n=e.navigate??JV,[r,o]=v.useState({profile:t.getProfile(),loading:t.isLoading()});v.useEffect(()=>{function c(){o(d=>({...d,profile:t.getProfile(),loading:t.isLoading()}))}for(const d of zE)t.addEventListener(d,c);return()=>{for(const d of zE)t.removeEventListener(d,c)}},[t]);const s=v.useMemo(()=>({...r,medplum:t,navigate:n}),[r,t,n]);return a.jsx(oA.Provider,{value:s,children:e.children})}function JV(e){window.location.assign(e)}const UE=new Map,aA=e=>v.useMemo(()=>{if(!e)return;const t=e.split("?")[0];if(!t)return e;let n;try{n=new URLSearchParams(new URL(e).search)}catch{return e}if(!n.has("Key-Pair-Id")||!n.has("Signature"))return e;const r=n.get("Expires");if(!r||r.length>13)return e;const o=UE.get(t);if(o){const c=new URLSearchParams(new URL(o).search).get("Expires");if(c&&parseInt(c,10)*1e3-5e3>Date.now())return o}return UE.set(t,e),e},[e]);function Gt(e,t){const n=De(),[r,o]=v.useState(()=>BE(n,e)),s=v.useCallback(c=>{co(c,r)||o(c)},[r]);return v.useEffect(()=>{let c=!0;const d=BE(n,e);return!d&&ca(e)?n.readReference(e).then(f=>{c&&s(f)}).catch(f=>{c&&(s(void 0),t&&t(Ht(f)))}):s(d),(()=>c=!1)},[n,e,s,t]),r}function BE(e,t){if(t){if(go(t))return t;if(ca(t))return e.getCachedReference(t)}}const wt={group:"group",display:"display",boolean:"boolean",decimal:"decimal",integer:"integer",date:"date",dateTime:"dateTime",time:"time",string:"string",text:"text",url:"url",choice:"choice",openChoice:"open-choice",attachment:"attachment",reference:"reference",quantity:"quantity"},jb=`${Ui}/fhir/StructureDefinition/questionnaire-itemControl`,eF=`${Ui}/fhir/StructureDefinition/questionnaire-referenceFilter`,nx=`${Ui}/fhir/StructureDefinition/questionnaire-referenceResource`,tF=`${Ui}/fhir/StructureDefinition/questionnaire-validationError`,nF=`${Ui}/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-enableWhenExpression`,rF=`${Ui}/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-calculatedExpression`,iF=`${Ui}/fhir/StructureDefinition/questionnaire-signatureRequired`,kh=`${Ui}/fhir/StructureDefinition/questionnaireresponse-signature`;function oF(e){return e.type==="choice"||e.type==="open-choice"}function aF(e,t){const n=sF(e,t);return n!==void 0?n:lF(e,t)}function sF(e,t){const n=mo(e,nF);if(t&&n){const r=n.valueExpression?.expression;if(r){const o=Yr(t),s=Za(r,[o],{"%resource":o});return to(s)}}}function lF(e,t){if(!e.enableWhen)return!0;const n=e.enableBehavior??"any";for(const r of e.enableWhen){const o=cA(t?.item,r.question);if(r.operator==="exists"&&!r.answerBoolean&&!o?.length){if(n==="any")return!0;continue}const{anyMatch:s,allMatch:c}=pF(r,o,n);if(n==="any"&&s)return!0;if(n==="all"&&!c)return!1}return n!=="any"}function sA(e,t,n=t.item){for(const r of e){const o=n?.find(s=>s.linkId===r.linkId);o&&(cF(t,r,o),r.item&&o.item&&sA(r.item,t,o.item))}}function cF(e,t,n){try{const r=fF(t,e);if(!r)return;const o=dF(t,r);if(!o)return;n.answer=[o]}catch(r){n.extension=[{url:tF,valueString:`Expression evaluation failed: ${Ge(r)}`}]}}const uF={[wt.boolean]:[re.boolean],[wt.date]:[re.date],[wt.dateTime]:[re.dateTime],[wt.time]:[re.time],[wt.url]:[re.string,re.uri,re.url],[wt.attachment]:[re.Attachment],[wt.reference]:[re.Reference],[wt.quantity]:[re.Quantity],[wt.decimal]:[re.decimal,re.integer],[wt.integer]:[re.decimal,re.integer]};function dF(e,t){if(!e.type)return;if(e.type===wt.choice||e.type===wt.openChoice)return{[`value${Ln(t.type)}`]:t.value};if(e.type===wt.string||e.type===wt.text)return typeof t.value=="string"?{valueString:t.value}:void 0;if(uF[e.type]?.includes(t.type))return{[`value${Ln(e.type)}`]:t.value}}function fF(e,t){if(!t)return;const n=mo(e,rF);if(n){const r=n.valueExpression?.expression;if(r){const o=Yr(t),s=Za(r,[o],{"%resource":o});return s.length!==0?s[0]:void 0}}}function lA(e,t,n){const r=[];for(const o of e){const s=n.answerOption?.find(c=>Gs(fo(c))===o);if(s){const c=fo(s);c&&r.push({[t]:c.value})}}return r}function cA(e,t){if(e)for(const n of e){if(n.linkId===t)return n.answer;if(n.item){const r=cA(n.item,t);if(r)return r}}}function hF(e,t,n){if(n==="exists")return!!e===t.value;if(e){const r=n==="="||n==="!="?n?.replace("=","~"):n,[{value:o}]=Za(`%actualAnswer ${r} %expectedAnswer`,[e],{"%actualAnswer":e,"%expectedAnswer":t});return o}else return!1}function pF(e,t,n){const r=t||[],o=vF(e);let s=!1,c=!0;for(const d of r){const f=yF(d),{operator:p}=e;if(hF(f,o,p)?s=!0:c=!1,n==="any"&&s)break}return{anyMatch:s,allMatch:c}}function uA(e){const t=mo(e,nx);if(t){if(t.valueCode!==void 0)return[t.valueCode];if(t.valueCodeableConcept)return t.valueCodeableConcept?.coding?.map(n=>n.code)}}function uy(e,t){const n=Kr(e);let r=mo(n,nx);return!t||t.length===0?(r&&(n.extension=n.extension?.filter(o=>o!==r)),n):(r||(n.extension??=[],r={url:nx},n.extension.push(r)),t.length===1?(r.valueCode=t[0],delete r.valueCodeableConcept):(r.valueCodeableConcept={coding:t.map(o=>({code:o}))},delete r.valueCode),n)}function mF(e,t,n){const r=mo(e,eF);if(!r?.valueString)return;let o=r.valueString;t?.reference&&(o=o.replaceAll("$subj",t.reference)),n?.reference&&(o=o.replaceAll("$encounter",n.reference));const s={},c=o.split("&");for(const d of c){const[f,p]=Xy(d,"=",2);s[f]=p}return s}function VE(e,t){return{resourceType:"QuestionnaireResponse",questionnaire:e.url??At(e),item:Cb(e.item,t?.item),status:"in-progress"}}function Cb(e,t){if(!e)return;const n=[];for(const r of e){if(r.type===wt.display)continue;const o=t?.filter(s=>s.linkId===r.linkId);if(o&&o?.length>0)for(const s of o)s.id=s.id??fA(),s.text=s.text??r.text,s.item=Cb(r.item,s.item),s.answer=hA(r,s),n.push(s);else n.push(dA(r))}return n}function dA(e){return{id:fA(),linkId:e.linkId,text:e.text,item:Cb(e.item,void 0),answer:hA(e)}}let gF=1;function fA(){return"id-"+gF++}function hA(e,t){if(!(e.type===wt.display||e.type===wt.group)){if(t?.answer&&t.answer.length>0)return t.answer;if(e.initial&&e.initial.length>0)return e.initial.map(n=>({...n}));if(e.answerOption)return e.answerOption.filter(n=>n.initialSelected).map(n=>({...n,initialSelected:void 0}))}}function Eb(e){return Ld({value:e},"value")}function fo(e){return Ld({value:e},"value")}function vF(e){return Ld({value:e},"answer")}function yF(e){return Ld({value:e},"value")}function xF(e){const t=Gt(e.questionnaire),n=Gt(e.defaultValue),[,r]=v.useReducer(S=>S+1,0),o=v.useRef({activePage:0});if(!o.current.questionnaire&&t&&(o.current.questionnaire=t,o.current.pages=e.disablePagination?void 0:bF(t)),t&&e.defaultValue&&n&&!o.current.questionnaireResponse&&(o.current.questionnaireResponse=VE(t,n),b()),t&&!e.defaultValue&&!o.current.questionnaireResponse&&(o.current.questionnaireResponse=VE(t),b()),!o.current.questionnaire||!o.current.questionnaireResponse)return{loading:!0};function s(S,j){let C=o.current.questionnaireResponse;for(const R of S)C=C?.item?.find(E=>R.id?E.id===R.id:E.linkId===R.linkId);return j&&(C=C?.item?.find(R=>R.linkId===j.linkId)),C}function c(){o.current.activePage=(o.current.activePage??0)+1,r()}function d(){o.current.activePage=(o.current.activePage??0)-1,r()}function f(S,j){const C=s(S);C&&(C.item??=[],C.item.push(dA(j)),b())}function p(S,j){const C=s(S,j);C&&(C.answer??=[],C.answer.push({}),b())}function m(S,j,C){const R=s(S,j);R&&(R.answer=C,b())}function g(S){const j=o.current.questionnaireResponse;j&&(S?(j.extension=j.extension??[],j.extension=j.extension.filter(C=>C.url!==kh),j.extension.push({url:kh,valueSignature:S})):j.extension=j.extension?.filter(C=>C.url!==kh),b())}function x(){const S=o.current.questionnaire;if(S?.item){const j=o.current.questionnaireResponse;sA(S.item,j)}}function b(){const S=o.current.questionnaireResponse;S&&(x(),r(),e.onChange?.(S))}return{loading:!1,pagination:!!o.current.pages,questionnaire:o.current.questionnaire,questionnaireResponse:o.current.questionnaireResponse,subject:e.subject,encounter:e.encounter,activePage:o.current.activePage,pages:o.current.pages,items:SF(o.current.questionnaire,o.current.pages,o.current.activePage),responseItems:wF(o.current.questionnaireResponse,o.current.pages,o.current.activePage),onNextPage:c,onPrevPage:d,onAddGroup:f,onAddAnswer:p,onChangeAnswer:m,onChangeSignature:g}}function bF(e){if(!(!e?.item||mo(e?.item?.[0],jb)?.valueCodeableConcept?.coding?.[0]?.code!=="page"))return e.item.map((n,r)=>({linkId:n.linkId,title:n.text??`Page ${r+1}`,group:n}))}function SF(e,t,n=0){return t&&e?.item?.[n]?[e.item[n]]:e.item??[]}function wF(e,t,n=0){return t&&e?.item?.[n]?[e.item[n]]:e.item??[]}function jF(e,t,n={leading:!1}){const[r,o]=v.useState(e),s=v.useRef(!1),c=v.useRef(void 0),d=v.useRef(!1),f=v.useCallback(()=>window.clearTimeout(c.current),[]);return v.useEffect(()=>{s.current&&(!d.current&&n.leading?(d.current=!0,o(e)):(f(),c.current=setTimeout(()=>{d.current=!1,o(e)},t)))},[e,n.leading,t,f]),v.useEffect(()=>(s.current=!0,f),[f]),[r,f]}const CF=250;function EF(e,t,n){return pA("searchOne",e,t)}function Rc(e,t,n){return pA("searchResources",e,t)}function pA(e,t,n,r){const o=De(),[s,c]=v.useState(),[d,f]=v.useState(!0),[p,m]=v.useState(),[g,x]=v.useState(),b=o.fhirSearchUrl(t,n).toString(),[S]=jF(b,CF,{leading:!0});return v.useEffect(()=>{S!==s&&(c(S),o[e](t,n).then(j=>{f(!1),m(j),x(Cz)}).catch(j=>{f(!1),m(void 0),x(Ht(j))}))},[o,e,t,n,s,S]),[p,d,g]}function TF(e){const t=e.value;return t?a.jsx(a.Fragment,{children:ID(t)}):null}const mA=["meta","implicitRules","contained","extension","modifierExtension"],gA=["language","text"],ln=v.createContext({path:"",profileUrl:void 0,elements:Object.create(null),elementsByPath:Object.create(null),getExtendedProps:()=>({readonly:!1,hidden:!1}),accessPolicyResource:void 0,debugMode:!1,isDefaultContext:!0});ln.displayName="ElementsContext";const Tb=["extension","modifierExtension"],RF=["id",...mA].filter(e=>!Tb.includes(e));function _F(e){return Object.entries(e).filter(([n,r])=>!Tn(r.type)||r.max===0||r.path.toLowerCase().endsWith("extension.url")&&r.fixed||Tb.includes(n)&&!Tn(r.slicing?.slices)||RF.includes(n)?!1:!(gA.includes(n)&&r.path.split(".").length===2||n.includes(".")))}function FE(e,t){return e.line&&e.line.length>t?e.line[t]:""}function qE(e,t,n){const r=e.line||[];for(;r.length<=t;)r.push("");return r[t]=n,{...e,line:r}}function DF(e){const[t,n]=v.useState(e.defaultValue||{}),r=v.useRef(t);r.current=t;const{getExtendedProps:o}=v.useContext(ln),[s,c,d,f,p,m,g]=v.useMemo(()=>["use","type","line1","line2","city","state","postalCode"].map(_=>o(e.path+"."+_)),[o,e.path]);function x(_){n(_),e.onChange&&e.onChange(_)}function b(_){x({...r.current,use:_})}function S(_){x({...r.current,type:_})}function j(_){x(qE(r.current||{},0,_))}function C(_){x(qE(r.current||{},1,_))}function R(_){x({...r.current,city:_})}function E(_){x({...r.current,state:_})}function T(_){x({...r.current,postalCode:_})}return a.jsxs(ge,{gap:"xs",wrap:"nowrap",grow:!0,children:[a.jsx(sn,{disabled:e.disabled||s?.readonly,"data-testid":"address-use",defaultValue:t.use,onChange:_=>b(_.currentTarget.value),data:["","home","work","temp","old","billing"]}),a.jsx(sn,{disabled:e.disabled||c?.readonly,"data-testid":"address-type",defaultValue:t.type,onChange:_=>S(_.currentTarget.value),data:["","postal","physical","both"]}),a.jsx(Ue,{disabled:e.disabled||d?.readonly,placeholder:"Line 1",defaultValue:FE(t,0),onChange:_=>j(_.currentTarget.value)}),a.jsx(Ue,{disabled:e.disabled||f?.readonly,placeholder:"Line 2",defaultValue:FE(t,1),onChange:_=>C(_.currentTarget.value)}),a.jsx(Ue,{disabled:e.disabled||p?.readonly,placeholder:"City",defaultValue:t.city,onChange:_=>R(_.currentTarget.value)}),a.jsx(Ue,{disabled:e.disabled||m?.readonly,placeholder:"State",defaultValue:t.state,onChange:_=>E(_.currentTarget.value)}),a.jsx(Ue,{disabled:e.disabled||g?.readonly,placeholder:"Postal Code",defaultValue:t.postalCode,onChange:_=>T(_.currentTarget.value)})]})}function AF(e){const t=pm(),[n,r]=v.useState(e.defaultValue||{});function o(s){const c=s?{text:s,authorReference:t&&qt(t),time:new Date().toISOString()}:{};r(c),e.onChange&&e.onChange(c)}return a.jsx(Ue,{disabled:e.disabled,name:e.name,placeholder:"Annotation text",defaultValue:n.text,onChange:s=>o(s.currentTarget.value)})}/**
|
|
128
|
-
* @license @tabler/icons-react v3.
|
|
128
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
129
129
|
*
|
|
130
130
|
* This source code is licensed under the MIT license.
|
|
131
131
|
* See the LICENSE file in the root directory of this source tree.
|
|
132
132
|
*/var PF={outline:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},filled:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none"}};/**
|
|
133
|
-
* @license @tabler/icons-react v3.
|
|
133
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
134
134
|
*
|
|
135
135
|
* This source code is licensed under the MIT license.
|
|
136
136
|
* See the LICENSE file in the root directory of this source tree.
|
|
137
137
|
*/const Be=(e,t,n,r)=>{const o=v.forwardRef(({color:s="currentColor",size:c=24,stroke:d=2,title:f,className:p,children:m,...g},x)=>v.createElement("svg",{ref:x,...PF[e],width:c,height:c,className:["tabler-icon",`tabler-icon-${t}`,p].join(" "),...e==="filled"?{fill:s}:{strokeWidth:d,stroke:s},...g},[f&&v.createElement("title",{key:"svg-title"},f),...r.map(([b,S])=>v.createElement(b,S)),...Array.isArray(m)?m:[m]]));return o.displayName=`${n}`,o};/**
|
|
138
|
-
* @license @tabler/icons-react v3.
|
|
138
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
139
139
|
*
|
|
140
140
|
* This source code is licensed under the MIT license.
|
|
141
141
|
* See the LICENSE file in the root directory of this source tree.
|
|
142
142
|
*/const kF=[["path",{d:"M14 6m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0",key:"svg-0"}],["path",{d:"M4 6l8 0",key:"svg-1"}],["path",{d:"M16 6l4 0",key:"svg-2"}],["path",{d:"M8 12m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0",key:"svg-3"}],["path",{d:"M4 12l2 0",key:"svg-4"}],["path",{d:"M10 12l10 0",key:"svg-5"}],["path",{d:"M17 18m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0",key:"svg-6"}],["path",{d:"M4 18l11 0",key:"svg-7"}],["path",{d:"M19 18l1 0",key:"svg-8"}]],NF=Be("outline","adjustments-horizontal","AdjustmentsHorizontal",kF);/**
|
|
143
|
-
* @license @tabler/icons-react v3.
|
|
143
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
144
144
|
*
|
|
145
145
|
* This source code is licensed under the MIT license.
|
|
146
146
|
* See the LICENSE file in the root directory of this source tree.
|
|
147
147
|
*/const OF=[["path",{d:"M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0",key:"svg-0"}],["path",{d:"M12 8v4",key:"svg-1"}],["path",{d:"M12 16h.01",key:"svg-2"}]],ll=Be("outline","alert-circle","AlertCircle",OF);/**
|
|
148
|
-
* @license @tabler/icons-react v3.
|
|
148
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
149
149
|
*
|
|
150
150
|
* This source code is licensed under the MIT license.
|
|
151
151
|
* See the LICENSE file in the root directory of this source tree.
|
|
152
152
|
*/const MF=[["path",{d:"M12 5l0 14",key:"svg-0"}],["path",{d:"M18 13l-6 6",key:"svg-1"}],["path",{d:"M6 13l6 6",key:"svg-2"}]],LF=Be("outline","arrow-down","ArrowDown",MF);/**
|
|
153
|
-
* @license @tabler/icons-react v3.
|
|
153
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
154
154
|
*
|
|
155
155
|
* This source code is licensed under the MIT license.
|
|
156
156
|
* See the LICENSE file in the root directory of this source tree.
|
|
157
157
|
*/const IF=[["path",{d:"M12 5l0 14",key:"svg-0"}],["path",{d:"M18 11l-6 -6",key:"svg-1"}],["path",{d:"M6 11l6 -6",key:"svg-2"}]],$F=Be("outline","arrow-up","ArrowUp",IF);/**
|
|
158
|
-
* @license @tabler/icons-react v3.
|
|
158
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
159
159
|
*
|
|
160
160
|
* This source code is licensed under the MIT license.
|
|
161
161
|
* See the LICENSE file in the root directory of this source tree.
|
|
162
162
|
*/const zF=[["path",{d:"M5 19h14m1.986 -1.977a2 2 0 0 0 -.146 -.773l-7.1 -12.25a2 2 0 0 0 -3.5 0l-.815 1.405m-1.488 2.568l-4.797 8.277a2 2 0 0 0 1.75 2.75",key:"svg-0"}],["path",{d:"M3 3l18 18",key:"svg-1"}]],UF=Be("outline","bleach-off","BleachOff",zF);/**
|
|
163
|
-
* @license @tabler/icons-react v3.
|
|
163
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
164
164
|
*
|
|
165
165
|
* This source code is licensed under the MIT license.
|
|
166
166
|
* See the LICENSE file in the root directory of this source tree.
|
|
167
167
|
*/const BF=[["path",{d:"M5 19h14a2 2 0 0 0 1.84 -2.75l-7.1 -12.25a2 2 0 0 0 -3.5 0l-7.1 12.25a2 2 0 0 0 1.75 2.75",key:"svg-0"}]],VF=Be("outline","bleach","Bleach",BF);/**
|
|
168
|
-
* @license @tabler/icons-react v3.
|
|
168
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
169
169
|
*
|
|
170
170
|
* This source code is licensed under the MIT license.
|
|
171
171
|
* See the LICENSE file in the root directory of this source tree.
|
|
172
172
|
*/const FF=[["path",{d:"M7 3m0 2a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2z",key:"svg-0"}],["path",{d:"M17 17v2a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-10a2 2 0 0 1 2 -2h2",key:"svg-1"}]],qF=Be("outline","box-multiple","BoxMultiple",FF);/**
|
|
173
|
-
* @license @tabler/icons-react v3.
|
|
173
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
174
174
|
*
|
|
175
175
|
* This source code is licensed under the MIT license.
|
|
176
176
|
* See the LICENSE file in the root directory of this source tree.
|
|
177
177
|
*/const HF=[["path",{d:"M7 4h-4v16h4",key:"svg-0"}],["path",{d:"M17 4h4v16h-4",key:"svg-1"}],["path",{d:"M8 16h.01",key:"svg-2"}],["path",{d:"M12 16h.01",key:"svg-3"}],["path",{d:"M16 16h.01",key:"svg-4"}]],GF=Be("outline","brackets-contain","BracketsContain",HF);/**
|
|
178
|
-
* @license @tabler/icons-react v3.
|
|
178
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
179
179
|
*
|
|
180
180
|
* This source code is licensed under the MIT license.
|
|
181
181
|
* See the LICENSE file in the root directory of this source tree.
|
|
182
182
|
*/const WF=[["path",{d:"M12 7m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0",key:"svg-0"}],["path",{d:"M17 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0",key:"svg-1"}],["path",{d:"M7 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0",key:"svg-2"}]],QF=Be("outline","brand-asana","BrandAsana",WF);/**
|
|
183
|
-
* @license @tabler/icons-react v3.
|
|
183
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
184
184
|
*
|
|
185
185
|
* This source code is licensed under the MIT license.
|
|
186
186
|
* See the LICENSE file in the root directory of this source tree.
|
|
187
187
|
*/const YF=[["path",{d:"M5.029 5.036c-.655 .58 -1.029 1.25 -1.029 1.964c0 2.033 3.033 3.712 6.96 3.967m3.788 -.21c3.064 -.559 5.252 -2.029 5.252 -3.757c0 -2.21 -3.582 -4 -8 -4c-1.605 0 -3.1 .236 -4.352 .643",key:"svg-0"}],["path",{d:"M4 7c0 .664 .088 1.324 .263 1.965l2.737 10.035c.5 1.5 2.239 2 5 2s4.5 -.5 5 -2c.1 -.3 .252 -.812 .457 -1.535m.862 -3.146c.262 -.975 .735 -2.76 1.418 -5.354a7.45 7.45 0 0 0 .263 -1.965",key:"svg-1"}],["path",{d:"M3 3l18 18",key:"svg-2"}]],KF=Be("outline","bucket-off","BucketOff",YF);/**
|
|
188
|
-
* @license @tabler/icons-react v3.
|
|
188
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
189
189
|
*
|
|
190
190
|
* This source code is licensed under the MIT license.
|
|
191
191
|
* See the LICENSE file in the root directory of this source tree.
|
|
192
192
|
*/const XF=[["path",{d:"M12 7m-8 0a8 4 0 1 0 16 0a8 4 0 1 0 -16 0",key:"svg-0"}],["path",{d:"M4 7c0 .664 .088 1.324 .263 1.965l2.737 10.035c.5 1.5 2.239 2 5 2s4.5 -.5 5 -2c.333 -1 1.246 -4.345 2.737 -10.035a7.45 7.45 0 0 0 .263 -1.965",key:"svg-1"}]],ZF=Be("outline","bucket","Bucket",XF);/**
|
|
193
|
-
* @license @tabler/icons-react v3.
|
|
193
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
194
194
|
*
|
|
195
195
|
* This source code is licensed under the MIT license.
|
|
196
196
|
* See the LICENSE file in the root directory of this source tree.
|
|
197
197
|
*/const JF=[["path",{d:"M3 21l18 0",key:"svg-0"}],["path",{d:"M9 8l1 0",key:"svg-1"}],["path",{d:"M9 12l1 0",key:"svg-2"}],["path",{d:"M9 16l1 0",key:"svg-3"}],["path",{d:"M14 8l1 0",key:"svg-4"}],["path",{d:"M14 12l1 0",key:"svg-5"}],["path",{d:"M14 16l1 0",key:"svg-6"}],["path",{d:"M5 21v-16a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v16",key:"svg-7"}]],eq=Be("outline","building","Building",JF);/**
|
|
198
|
-
* @license @tabler/icons-react v3.
|
|
198
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
199
199
|
*
|
|
200
200
|
* This source code is licensed under the MIT license.
|
|
201
201
|
* See the LICENSE file in the root directory of this source tree.
|
|
202
202
|
*/const tq=[["path",{d:"M4 7a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12z",key:"svg-0"}],["path",{d:"M16 3v4",key:"svg-1"}],["path",{d:"M8 3v4",key:"svg-2"}],["path",{d:"M4 11h16",key:"svg-3"}],["path",{d:"M11 15h1",key:"svg-4"}],["path",{d:"M12 15v3",key:"svg-5"}]],$a=Be("outline","calendar","Calendar",tq);/**
|
|
203
|
-
* @license @tabler/icons-react v3.
|
|
203
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
204
204
|
*
|
|
205
205
|
* This source code is licensed under the MIT license.
|
|
206
206
|
* See the LICENSE file in the root directory of this source tree.
|
|
207
207
|
*/const nq=[["path",{d:"M5 12l5 5l10 -10",key:"svg-0"}]],vo=Be("outline","check","Check",nq);/**
|
|
208
|
-
* @license @tabler/icons-react v3.
|
|
208
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
209
209
|
*
|
|
210
210
|
* This source code is licensed under the MIT license.
|
|
211
211
|
* See the LICENSE file in the root directory of this source tree.
|
|
212
212
|
*/const rq=[["path",{d:"M9 11l3 3l8 -8",key:"svg-0"}],["path",{d:"M20 12v6a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h9",key:"svg-1"}]],iq=Be("outline","checkbox","Checkbox",rq);/**
|
|
213
|
-
* @license @tabler/icons-react v3.
|
|
213
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
214
214
|
*
|
|
215
215
|
* This source code is licensed under the MIT license.
|
|
216
216
|
* See the LICENSE file in the root directory of this source tree.
|
|
217
217
|
*/const oq=[["path",{d:"M6 9l6 6l6 -6",key:"svg-0"}]],Rb=Be("outline","chevron-down","ChevronDown",oq);/**
|
|
218
|
-
* @license @tabler/icons-react v3.
|
|
218
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
219
219
|
*
|
|
220
220
|
* This source code is licensed under the MIT license.
|
|
221
221
|
* See the LICENSE file in the root directory of this source tree.
|
|
222
222
|
*/const aq=[["path",{d:"M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0",key:"svg-0"}],["path",{d:"M9 12l2 2l4 -4",key:"svg-1"}]],sq=Be("outline","circle-check","CircleCheck",aq);/**
|
|
223
|
-
* @license @tabler/icons-react v3.
|
|
223
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
224
224
|
*
|
|
225
225
|
* This source code is licensed under the MIT license.
|
|
226
226
|
* See the LICENSE file in the root directory of this source tree.
|
|
227
227
|
*/const lq=[["path",{d:"M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0",key:"svg-0"}],["path",{d:"M9 12l6 0",key:"svg-1"}]],tp=Be("outline","circle-minus","CircleMinus",lq);/**
|
|
228
|
-
* @license @tabler/icons-react v3.
|
|
228
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
229
229
|
*
|
|
230
230
|
* This source code is licensed under the MIT license.
|
|
231
231
|
* See the LICENSE file in the root directory of this source tree.
|
|
232
232
|
*/const cq=[["path",{d:"M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0",key:"svg-0"}],["path",{d:"M9 12h6",key:"svg-1"}],["path",{d:"M12 9v6",key:"svg-2"}]],np=Be("outline","circle-plus","CirclePlus",cq);/**
|
|
233
|
-
* @license @tabler/icons-react v3.
|
|
233
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
234
234
|
*
|
|
235
235
|
* This source code is licensed under the MIT license.
|
|
236
236
|
* See the LICENSE file in the root directory of this source tree.
|
|
237
237
|
*/const uq=[["path",{d:"M7 18a4.6 4.4 0 0 1 0 -9a5 4.5 0 0 1 11 2h1a3.5 3.5 0 0 1 0 7h-1",key:"svg-0"}],["path",{d:"M9 15l3 -3l3 3",key:"svg-1"}],["path",{d:"M12 12l0 9",key:"svg-2"}]],_b=Be("outline","cloud-upload","CloudUpload",uq);/**
|
|
238
|
-
* @license @tabler/icons-react v3.
|
|
238
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
239
239
|
*
|
|
240
240
|
* This source code is licensed under the MIT license.
|
|
241
241
|
* See the LICENSE file in the root directory of this source tree.
|
|
242
242
|
*/const dq=[["path",{d:"M4 6l5.5 0",key:"svg-0"}],["path",{d:"M4 10l5.5 0",key:"svg-1"}],["path",{d:"M4 14l5.5 0",key:"svg-2"}],["path",{d:"M4 18l5.5 0",key:"svg-3"}],["path",{d:"M14.5 6l5.5 0",key:"svg-4"}],["path",{d:"M14.5 10l5.5 0",key:"svg-5"}],["path",{d:"M14.5 14l5.5 0",key:"svg-6"}],["path",{d:"M14.5 18l5.5 0",key:"svg-7"}]],fq=Be("outline","columns","Columns",dq);/**
|
|
243
|
-
* @license @tabler/icons-react v3.
|
|
243
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
244
244
|
*
|
|
245
245
|
* This source code is licensed under the MIT license.
|
|
246
246
|
* See the LICENSE file in the root directory of this source tree.
|
|
247
247
|
*/const hq=[["path",{d:"M7 7m0 2.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667z",key:"svg-0"}],["path",{d:"M4.012 16.737a2.005 2.005 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1",key:"svg-1"}]],Db=Be("outline","copy","Copy",hq);/**
|
|
248
|
-
* @license @tabler/icons-react v3.
|
|
248
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
249
249
|
*
|
|
250
250
|
* This source code is licensed under the MIT license.
|
|
251
251
|
* See the LICENSE file in the root directory of this source tree.
|
|
252
252
|
*/const pq=[["path",{d:"M16.7 8a3 3 0 0 0 -2.7 -2h-4a3 3 0 0 0 0 6h4a3 3 0 0 1 0 6h-4a3 3 0 0 1 -2.7 -2",key:"svg-0"}],["path",{d:"M12 3v3m0 12v3",key:"svg-1"}]],mq=Be("outline","currency-dollar","CurrencyDollar",pq);/**
|
|
253
|
-
* @license @tabler/icons-react v3.
|
|
253
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
254
254
|
*
|
|
255
255
|
* This source code is licensed under the MIT license.
|
|
256
256
|
* See the LICENSE file in the root directory of this source tree.
|
|
257
257
|
*/const gq=[["path",{d:"M12 6m-8 0a8 3 0 1 0 16 0a8 3 0 1 0 -16 0",key:"svg-0"}],["path",{d:"M4 6v6a8 3 0 0 0 16 0v-6",key:"svg-1"}],["path",{d:"M4 12v6a8 3 0 0 0 16 0v-6",key:"svg-2"}]],vq=Be("outline","database","Database",gq);/**
|
|
258
|
-
* @license @tabler/icons-react v3.
|
|
258
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
259
259
|
*
|
|
260
260
|
* This source code is licensed under the MIT license.
|
|
261
261
|
* See the LICENSE file in the root directory of this source tree.
|
|
262
262
|
*/const yq=[["path",{d:"M6 4h10l4 4v10a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2",key:"svg-0"}],["path",{d:"M12 14m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0",key:"svg-1"}],["path",{d:"M14 4l0 4l-6 0l0 -4",key:"svg-2"}]],xq=Be("outline","device-floppy","DeviceFloppy",yq);/**
|
|
263
|
-
* @license @tabler/icons-react v3.
|
|
263
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
264
264
|
*
|
|
265
265
|
* This source code is licensed under the MIT license.
|
|
266
266
|
* See the LICENSE file in the root directory of this source tree.
|
|
267
267
|
*/const bq=[["path",{d:"M5 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0",key:"svg-0"}],["path",{d:"M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0",key:"svg-1"}],["path",{d:"M19 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0",key:"svg-2"}]],Sq=Be("outline","dots","Dots",bq);/**
|
|
268
|
-
* @license @tabler/icons-react v3.
|
|
268
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
269
269
|
*
|
|
270
270
|
* This source code is licensed under the MIT license.
|
|
271
271
|
* See the LICENSE file in the root directory of this source tree.
|
|
272
272
|
*/const wq=[["path",{d:"M7 7h-1a2 2 0 0 0 -2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2 -2v-1",key:"svg-0"}],["path",{d:"M20.385 6.585a2.1 2.1 0 0 0 -2.97 -2.97l-8.415 8.385v3h3l8.385 -8.415z",key:"svg-1"}],["path",{d:"M16 5l3 3",key:"svg-2"}]],vA=Be("outline","edit","Edit",wq);/**
|
|
273
|
-
* @license @tabler/icons-react v3.
|
|
273
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
274
274
|
*
|
|
275
275
|
* This source code is licensed under the MIT license.
|
|
276
276
|
* See the LICENSE file in the root directory of this source tree.
|
|
277
277
|
*/const jq=[["path",{d:"M5 10h14",key:"svg-0"}],["path",{d:"M5 14h14",key:"svg-1"}],["path",{d:"M5 19l14 -14",key:"svg-2"}]],$d=Be("outline","equal-not","EqualNot",jq);/**
|
|
278
|
-
* @license @tabler/icons-react v3.
|
|
278
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
279
279
|
*
|
|
280
280
|
* This source code is licensed under the MIT license.
|
|
281
281
|
* See the LICENSE file in the root directory of this source tree.
|
|
282
282
|
*/const Cq=[["path",{d:"M5 10h14",key:"svg-0"}],["path",{d:"M5 14h14",key:"svg-1"}]],zd=Be("outline","equal","Equal",Cq);/**
|
|
283
|
-
* @license @tabler/icons-react v3.
|
|
283
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
284
284
|
*
|
|
285
285
|
* This source code is licensed under the MIT license.
|
|
286
286
|
* See the LICENSE file in the root directory of this source tree.
|
|
287
287
|
*/const Eq=[["path",{d:"M10.585 10.587a2 2 0 0 0 2.829 2.828",key:"svg-0"}],["path",{d:"M16.681 16.673a8.717 8.717 0 0 1 -4.681 1.327c-3.6 0 -6.6 -2 -9 -6c1.272 -2.12 2.712 -3.678 4.32 -4.674m2.86 -1.146a9.055 9.055 0 0 1 1.82 -.18c3.6 0 6.6 2 9 6c-.666 1.11 -1.379 2.067 -2.138 2.87",key:"svg-1"}],["path",{d:"M3 3l18 18",key:"svg-2"}]],Tq=Be("outline","eye-off","EyeOff",Eq);/**
|
|
288
|
-
* @license @tabler/icons-react v3.
|
|
288
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
289
289
|
*
|
|
290
290
|
* This source code is licensed under the MIT license.
|
|
291
291
|
* See the LICENSE file in the root directory of this source tree.
|
|
292
292
|
*/const Rq=[["path",{d:"M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0",key:"svg-0"}],["path",{d:"M21 12c-2.4 4 -5.4 6 -9 6c-3.6 0 -6.6 -2 -9 -6c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6",key:"svg-1"}]],_q=Be("outline","eye","Eye",Rq);/**
|
|
293
|
-
* @license @tabler/icons-react v3.
|
|
293
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
294
294
|
*
|
|
295
295
|
* This source code is licensed under the MIT license.
|
|
296
296
|
* See the LICENSE file in the root directory of this source tree.
|
|
297
297
|
*/const Dq=[["path",{d:"M14 3v4a1 1 0 0 0 1 1h4",key:"svg-0"}],["path",{d:"M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z",key:"svg-1"}],["path",{d:"M12 17l.01 0",key:"svg-2"}],["path",{d:"M12 11l0 3",key:"svg-3"}]],HE=Be("outline","file-alert","FileAlert",Dq);/**
|
|
298
|
-
* @license @tabler/icons-react v3.
|
|
298
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
299
299
|
*
|
|
300
300
|
* This source code is licensed under the MIT license.
|
|
301
301
|
* See the LICENSE file in the root directory of this source tree.
|
|
302
302
|
*/const Aq=[["path",{d:"M14 3v4a1 1 0 0 0 1 1h4",key:"svg-0"}],["path",{d:"M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z",key:"svg-1"}],["path",{d:"M12 11l0 6",key:"svg-2"}],["path",{d:"M9 14l6 0",key:"svg-3"}]],Pq=Be("outline","file-plus","FilePlus",Aq);/**
|
|
303
|
-
* @license @tabler/icons-react v3.
|
|
303
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
304
304
|
*
|
|
305
305
|
* This source code is licensed under the MIT license.
|
|
306
306
|
* See the LICENSE file in the root directory of this source tree.
|
|
307
307
|
*/const kq=[["path",{d:"M4 4h16v2.172a2 2 0 0 1 -.586 1.414l-4.414 4.414v7l-6 2v-8.5l-4.48 -4.928a2 2 0 0 1 -.52 -1.345v-2.227z",key:"svg-0"}]],Nq=Be("outline","filter","Filter",kq);/**
|
|
308
|
-
* @license @tabler/icons-react v3.
|
|
308
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
309
309
|
*
|
|
310
310
|
* This source code is licensed under the MIT license.
|
|
311
311
|
* See the LICENSE file in the root directory of this source tree.
|
|
312
312
|
*/const Oq=[["path",{d:"M12 3a3 3 0 0 0 -3 3v12a3 3 0 0 0 3 3",key:"svg-0"}],["path",{d:"M6 3a3 3 0 0 1 3 3v12a3 3 0 0 1 -3 3",key:"svg-1"}],["path",{d:"M13 7h7a1 1 0 0 1 1 1v8a1 1 0 0 1 -1 1h-7",key:"svg-2"}],["path",{d:"M5 7h-1a1 1 0 0 0 -1 1v8a1 1 0 0 0 1 1h1",key:"svg-3"}],["path",{d:"M17 12h.01",key:"svg-4"}],["path",{d:"M13 12h.01",key:"svg-5"}]],Mq=Be("outline","forms","Forms",Oq);/**
|
|
313
|
-
* @license @tabler/icons-react v3.
|
|
313
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
314
314
|
*
|
|
315
315
|
* This source code is licensed under the MIT license.
|
|
316
316
|
* See the LICENSE file in the root directory of this source tree.
|
|
317
317
|
*/const Lq=[["path",{d:"M3 4m0 3a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v10a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3z",key:"svg-0"}],["path",{d:"M9 10m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0",key:"svg-1"}],["path",{d:"M15 8l2 0",key:"svg-2"}],["path",{d:"M15 12l2 0",key:"svg-3"}],["path",{d:"M7 16l10 0",key:"svg-4"}]],Iq=Be("outline","id","Id",Lq);/**
|
|
318
|
-
* @license @tabler/icons-react v3.
|
|
318
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
319
319
|
*
|
|
320
320
|
* This source code is licensed under the MIT license.
|
|
321
321
|
* See the LICENSE file in the root directory of this source tree.
|
|
322
322
|
*/const $q=[["path",{d:"M13 5h8",key:"svg-0"}],["path",{d:"M13 9h5",key:"svg-1"}],["path",{d:"M13 15h8",key:"svg-2"}],["path",{d:"M13 19h5",key:"svg-3"}],["path",{d:"M3 4m0 1a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1z",key:"svg-4"}],["path",{d:"M3 14m0 1a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1z",key:"svg-5"}]],GE=Be("outline","list-details","ListDetails",$q);/**
|
|
323
|
-
* @license @tabler/icons-react v3.
|
|
323
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
324
324
|
*
|
|
325
325
|
* This source code is licensed under the MIT license.
|
|
326
326
|
* See the LICENSE file in the root directory of this source tree.
|
|
327
327
|
*/const zq=[["path",{d:"M4 8v-2a2 2 0 0 1 2 -2h2",key:"svg-0"}],["path",{d:"M4 16v2a2 2 0 0 0 2 2h2",key:"svg-1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v2",key:"svg-2"}],["path",{d:"M16 20h2a2 2 0 0 0 2 -2v-2",key:"svg-3"}],["path",{d:"M8 11m0 1a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1v3a1 1 0 0 1 -1 1h-6a1 1 0 0 1 -1 -1z",key:"svg-4"}],["path",{d:"M10 11v-2a2 2 0 1 1 4 0v2",key:"svg-5"}]],Uq=Be("outline","lock-access","LockAccess",zq);/**
|
|
328
|
-
* @license @tabler/icons-react v3.
|
|
328
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
329
329
|
*
|
|
330
330
|
* This source code is licensed under the MIT license.
|
|
331
331
|
* See the LICENSE file in the root directory of this source tree.
|
|
332
332
|
*/const Bq=[["path",{d:"M5 13a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v6a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-6z",key:"svg-0"}],["path",{d:"M11 16a1 1 0 1 0 2 0a1 1 0 0 0 -2 0",key:"svg-1"}],["path",{d:"M8 11v-4a4 4 0 1 1 8 0v4",key:"svg-2"}]],Vq=Be("outline","lock","Lock",Bq);/**
|
|
333
|
-
* @license @tabler/icons-react v3.
|
|
333
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
334
334
|
*
|
|
335
335
|
* This source code is licensed under the MIT license.
|
|
336
336
|
* See the LICENSE file in the root directory of this source tree.
|
|
337
337
|
*/const Fq=[["path",{d:"M14 8v-2a2 2 0 0 0 -2 -2h-7a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h7a2 2 0 0 0 2 -2v-2",key:"svg-0"}],["path",{d:"M9 12h12l-3 -3",key:"svg-1"}],["path",{d:"M18 15l3 -3",key:"svg-2"}]],qq=Be("outline","logout","Logout",Fq);/**
|
|
338
|
-
* @license @tabler/icons-react v3.
|
|
338
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
339
339
|
*
|
|
340
340
|
* This source code is licensed under the MIT license.
|
|
341
341
|
* See the LICENSE file in the root directory of this source tree.
|
|
342
342
|
*/const Hq=[["path",{d:"M5 18l14 -6l-14 -6",key:"svg-0"}]],yA=Be("outline","math-greater","MathGreater",Hq);/**
|
|
343
|
-
* @license @tabler/icons-react v3.
|
|
343
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
344
344
|
*
|
|
345
345
|
* This source code is licensed under the MIT license.
|
|
346
346
|
* See the LICENSE file in the root directory of this source tree.
|
|
347
347
|
*/const Gq=[["path",{d:"M19 18l-14 -6l14 -6",key:"svg-0"}]],xA=Be("outline","math-lower","MathLower",Gq);/**
|
|
348
|
-
* @license @tabler/icons-react v3.
|
|
348
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
349
349
|
*
|
|
350
350
|
* This source code is licensed under the MIT license.
|
|
351
351
|
* See the LICENSE file in the root directory of this source tree.
|
|
352
352
|
*/const Wq=[["path",{d:"M8 9h8",key:"svg-0"}],["path",{d:"M8 13h6",key:"svg-1"}],["path",{d:"M18 4a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-5l-5 3v-3h-2a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12z",key:"svg-2"}]],Qq=Be("outline","message","Message",Wq);/**
|
|
353
|
-
* @license @tabler/icons-react v3.
|
|
353
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
354
354
|
*
|
|
355
355
|
* This source code is licensed under the MIT license.
|
|
356
356
|
* See the LICENSE file in the root directory of this source tree.
|
|
357
357
|
*/const Yq=[["path",{d:"M5 21h14",key:"svg-0"}],["path",{d:"M6 18h2",key:"svg-1"}],["path",{d:"M7 18v3",key:"svg-2"}],["path",{d:"M9 11l3 3l6 -6l-3 -3z",key:"svg-3"}],["path",{d:"M10.5 12.5l-1.5 1.5",key:"svg-4"}],["path",{d:"M17 3l3 3",key:"svg-5"}],["path",{d:"M12 21a6 6 0 0 0 3.715 -10.712",key:"svg-6"}]],Kq=Be("outline","microscope","Microscope",Yq);/**
|
|
358
|
-
* @license @tabler/icons-react v3.
|
|
358
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
359
359
|
*
|
|
360
360
|
* This source code is licensed under the MIT license.
|
|
361
361
|
* See the LICENSE file in the root directory of this source tree.
|
|
362
362
|
*/const Xq=[["path",{d:"M5 12l14 0",key:"svg-0"}]],Zq=Be("outline","minus","Minus",Xq);/**
|
|
363
|
-
* @license @tabler/icons-react v3.
|
|
363
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
364
364
|
*
|
|
365
365
|
* This source code is licensed under the MIT license.
|
|
366
366
|
* See the LICENSE file in the root directory of this source tree.
|
|
367
367
|
*/const Jq=[["path",{d:"M7 16.5l-5 -3l5 -3l5 3v5.5l-5 3z",key:"svg-0"}],["path",{d:"M2 13.5v5.5l5 3",key:"svg-1"}],["path",{d:"M7 16.545l5 -3.03",key:"svg-2"}],["path",{d:"M17 16.5l-5 -3l5 -3l5 3v5.5l-5 3z",key:"svg-3"}],["path",{d:"M12 19l5 3",key:"svg-4"}],["path",{d:"M17 16.5l5 -3",key:"svg-5"}],["path",{d:"M12 13.5v-5.5l-5 -3l5 -3l5 3v5.5",key:"svg-6"}],["path",{d:"M7 5.03v5.455",key:"svg-7"}],["path",{d:"M12 8l5 -3",key:"svg-8"}]],eH=Be("outline","packages","Packages",Jq);/**
|
|
368
|
-
* @license @tabler/icons-react v3.
|
|
368
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
369
369
|
*
|
|
370
370
|
* This source code is licensed under the MIT license.
|
|
371
371
|
* See the LICENSE file in the root directory of this source tree.
|
|
372
372
|
*/const tH=[["path",{d:"M15 4.5l-4 4l-4 1.5l-1.5 1.5l7 7l1.5 -1.5l1.5 -4l4 -4",key:"svg-0"}],["path",{d:"M9 15l-4.5 4.5",key:"svg-1"}],["path",{d:"M14.5 4l5.5 5.5",key:"svg-2"}]],nH=Be("outline","pin","Pin",tH);/**
|
|
373
|
-
* @license @tabler/icons-react v3.
|
|
373
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
374
374
|
*
|
|
375
375
|
* This source code is licensed under the MIT license.
|
|
376
376
|
* See the LICENSE file in the root directory of this source tree.
|
|
377
377
|
*/const rH=[["path",{d:"M3 3l18 18",key:"svg-0"}],["path",{d:"M15 4.5l-3.249 3.249m-2.57 1.433l-2.181 .818l-1.5 1.5l7 7l1.5 -1.5l.82 -2.186m1.43 -2.563l3.25 -3.251",key:"svg-1"}],["path",{d:"M9 15l-4.5 4.5",key:"svg-2"}],["path",{d:"M14.5 4l5.5 5.5",key:"svg-3"}]],iH=Be("outline","pinned-off","PinnedOff",rH);/**
|
|
378
|
-
* @license @tabler/icons-react v3.
|
|
378
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
379
379
|
*
|
|
380
380
|
* This source code is licensed under the MIT license.
|
|
381
381
|
* See the LICENSE file in the root directory of this source tree.
|
|
382
382
|
*/const oH=[["path",{d:"M7 4v16l13 -8z",key:"svg-0"}]],aH=Be("outline","player-play","PlayerPlay",oH);/**
|
|
383
|
-
* @license @tabler/icons-react v3.
|
|
383
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
384
384
|
*
|
|
385
385
|
* This source code is licensed under the MIT license.
|
|
386
386
|
* See the LICENSE file in the root directory of this source tree.
|
|
387
387
|
*/const sH=[["path",{d:"M12 5l0 14",key:"svg-0"}],["path",{d:"M5 12l14 0",key:"svg-1"}]],bA=Be("outline","plus","Plus",sH);/**
|
|
388
|
-
* @license @tabler/icons-react v3.
|
|
388
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
389
389
|
*
|
|
390
390
|
* This source code is licensed under the MIT license.
|
|
391
391
|
* See the LICENSE file in the root directory of this source tree.
|
|
392
392
|
*/const lH=[["path",{d:"M5 21v-16a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v16l-3 -2l-2 2l-2 -2l-2 2l-2 -2l-3 2m4 -14h6m-6 4h6m-2 4h2",key:"svg-0"}]],cH=Be("outline","receipt","Receipt",lH);/**
|
|
393
|
-
* @license @tabler/icons-react v3.
|
|
393
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
394
394
|
*
|
|
395
395
|
* This source code is licensed under the MIT license.
|
|
396
396
|
* See the LICENSE file in the root directory of this source tree.
|
|
397
397
|
*/const uH=[["path",{d:"M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4",key:"svg-0"}],["path",{d:"M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4",key:"svg-1"}]],SA=Be("outline","refresh","Refresh",uH);/**
|
|
398
|
-
* @license @tabler/icons-react v3.
|
|
398
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
399
399
|
*
|
|
400
400
|
* This source code is licensed under the MIT license.
|
|
401
401
|
* See the LICENSE file in the root directory of this source tree.
|
|
402
402
|
*/const dH=[["path",{d:"M4 12v-3a3 3 0 0 1 3 -3h13m-3 -3l3 3l-3 3",key:"svg-0"}],["path",{d:"M20 12v3a3 3 0 0 1 -3 3h-13m3 3l-3 -3l3 -3",key:"svg-1"}]],fH=Be("outline","repeat","Repeat",dH);/**
|
|
403
|
-
* @license @tabler/icons-react v3.
|
|
403
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
404
404
|
*
|
|
405
405
|
* This source code is licensed under the MIT license.
|
|
406
406
|
* See the LICENSE file in the root directory of this source tree.
|
|
407
407
|
*/const hH=[["path",{d:"M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2",key:"svg-0"}],["path",{d:"M9 3m0 2a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v0a2 2 0 0 1 -2 2h-2a2 2 0 0 1 -2 -2z",key:"svg-1"}],["path",{d:"M10 14l4 0",key:"svg-2"}],["path",{d:"M12 12l0 4",key:"svg-3"}]],pH=Be("outline","report-medical","ReportMedical",hH);/**
|
|
408
|
-
* @license @tabler/icons-react v3.
|
|
408
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
409
409
|
*
|
|
410
410
|
* This source code is licensed under the MIT license.
|
|
411
411
|
* See the LICENSE file in the root directory of this source tree.
|
|
412
412
|
*/const mH=[["path",{d:"M3 13m0 2a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v4a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z",key:"svg-0"}],["path",{d:"M17 17l0 .01",key:"svg-1"}],["path",{d:"M13 17l0 .01",key:"svg-2"}],["path",{d:"M15 13l0 -2",key:"svg-3"}],["path",{d:"M11.75 8.75a4 4 0 0 1 6.5 0",key:"svg-4"}],["path",{d:"M8.5 6.5a8 8 0 0 1 13 0",key:"svg-5"}]],gH=Be("outline","router","Router",mH);/**
|
|
413
|
-
* @license @tabler/icons-react v3.
|
|
413
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
414
414
|
*
|
|
415
415
|
* This source code is licensed under the MIT license.
|
|
416
416
|
* See the LICENSE file in the root directory of this source tree.
|
|
417
417
|
*/const vH=[["path",{d:"M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0",key:"svg-0"}],["path",{d:"M21 21l-6 -6",key:"svg-1"}]],yH=Be("outline","search","Search",vH);/**
|
|
418
|
-
* @license @tabler/icons-react v3.
|
|
418
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
419
419
|
*
|
|
420
420
|
* This source code is licensed under the MIT license.
|
|
421
421
|
* See the LICENSE file in the root directory of this source tree.
|
|
422
422
|
*/const xH=[["path",{d:"M10.325 4.317c.426 -1.756 2.924 -1.756 3.35 0a1.724 1.724 0 0 0 2.573 1.066c1.543 -.94 3.31 .826 2.37 2.37a1.724 1.724 0 0 0 1.065 2.572c1.756 .426 1.756 2.924 0 3.35a1.724 1.724 0 0 0 -1.066 2.573c.94 1.543 -.826 3.31 -2.37 2.37a1.724 1.724 0 0 0 -2.572 1.065c-.426 1.756 -2.924 1.756 -3.35 0a1.724 1.724 0 0 0 -2.573 -1.066c-1.543 .94 -3.31 -.826 -2.37 -2.37a1.724 1.724 0 0 0 -1.065 -2.572c-1.756 -.426 -1.756 -2.924 0 -3.35a1.724 1.724 0 0 0 1.066 -2.573c-.94 -1.543 .826 -3.31 2.37 -2.37c1 .608 2.296 .07 2.572 -1.065z",key:"svg-0"}],["path",{d:"M9 12a3 3 0 1 0 6 0a3 3 0 0 0 -6 0",key:"svg-1"}]],rx=Be("outline","settings","Settings",xH);/**
|
|
423
|
-
* @license @tabler/icons-react v3.
|
|
423
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
424
424
|
*
|
|
425
425
|
* This source code is licensed under the MIT license.
|
|
426
426
|
* See the LICENSE file in the root directory of this source tree.
|
|
427
427
|
*/const bH=[["path",{d:"M4 6l7 0",key:"svg-0"}],["path",{d:"M4 12l7 0",key:"svg-1"}],["path",{d:"M4 18l9 0",key:"svg-2"}],["path",{d:"M15 9l3 -3l3 3",key:"svg-3"}],["path",{d:"M18 6l0 12",key:"svg-4"}]],Ab=Be("outline","sort-ascending","SortAscending",bH);/**
|
|
428
|
-
* @license @tabler/icons-react v3.
|
|
428
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
429
429
|
*
|
|
430
430
|
* This source code is licensed under the MIT license.
|
|
431
431
|
* See the LICENSE file in the root directory of this source tree.
|
|
432
432
|
*/const SH=[["path",{d:"M4 6l9 0",key:"svg-0"}],["path",{d:"M4 12l7 0",key:"svg-1"}],["path",{d:"M4 18l7 0",key:"svg-2"}],["path",{d:"M15 15l3 3l3 -3",key:"svg-3"}],["path",{d:"M18 6l0 12",key:"svg-4"}]],Pb=Be("outline","sort-descending","SortDescending",SH);/**
|
|
433
|
-
* @license @tabler/icons-react v3.
|
|
433
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
434
434
|
*
|
|
435
435
|
* This source code is licensed under the MIT license.
|
|
436
436
|
* See the LICENSE file in the root directory of this source tree.
|
|
437
437
|
*/const wH=[["path",{d:"M3 3m0 2a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z",key:"svg-0"}]],jH=Be("outline","square","Square",wH);/**
|
|
438
|
-
* @license @tabler/icons-react v3.
|
|
438
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
439
439
|
*
|
|
440
440
|
* This source code is licensed under the MIT license.
|
|
441
441
|
* See the LICENSE file in the root directory of this source tree.
|
|
442
442
|
*/const CH=[["path",{d:"M12 17.75l-6.172 3.245l1.179 -6.873l-5 -4.867l6.9 -1l3.086 -6.253l3.086 6.253l6.9 1l-5 4.867l1.179 6.873z",key:"svg-0"}]],EH=Be("outline","star","Star",CH);/**
|
|
443
|
-
* @license @tabler/icons-react v3.
|
|
443
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
444
444
|
*
|
|
445
445
|
* This source code is licensed under the MIT license.
|
|
446
446
|
* See the LICENSE file in the root directory of this source tree.
|
|
447
447
|
*/const TH=[["path",{d:"M16 3l4 4l-4 4",key:"svg-0"}],["path",{d:"M10 7l10 0",key:"svg-1"}],["path",{d:"M8 13l-4 4l4 4",key:"svg-2"}],["path",{d:"M4 17l9 0",key:"svg-3"}]],RH=Be("outline","switch-horizontal","SwitchHorizontal",TH);/**
|
|
448
|
-
* @license @tabler/icons-react v3.
|
|
448
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
449
449
|
*
|
|
450
450
|
* This source code is licensed under the MIT license.
|
|
451
451
|
* See the LICENSE file in the root directory of this source tree.
|
|
452
452
|
*/const _H=[["path",{d:"M12.5 21h-7.5a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v7.5",key:"svg-0"}],["path",{d:"M3 10h18",key:"svg-1"}],["path",{d:"M10 3v18",key:"svg-2"}],["path",{d:"M16 19h6",key:"svg-3"}],["path",{d:"M19 16l3 3l-3 3",key:"svg-4"}]],DH=Be("outline","table-export","TableExport",_H);/**
|
|
453
|
-
* @license @tabler/icons-react v3.
|
|
453
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
454
454
|
*
|
|
455
455
|
* This source code is licensed under the MIT license.
|
|
456
456
|
* See the LICENSE file in the root directory of this source tree.
|
|
457
457
|
*/const AH=[["path",{d:"M4 8v-2a2 2 0 0 1 2 -2h2",key:"svg-0"}],["path",{d:"M4 16v2a2 2 0 0 0 2 2h2",key:"svg-1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v2",key:"svg-2"}],["path",{d:"M16 20h2a2 2 0 0 0 2 -2v-2",key:"svg-3"}],["path",{d:"M12 16v-7",key:"svg-4"}],["path",{d:"M9 9h6",key:"svg-5"}]],PH=Be("outline","text-recognition","TextRecognition",AH);/**
|
|
458
|
-
* @license @tabler/icons-react v3.
|
|
458
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
459
459
|
*
|
|
460
460
|
* This source code is licensed under the MIT license.
|
|
461
461
|
* See the LICENSE file in the root directory of this source tree.
|
|
462
462
|
*/const kH=[["path",{d:"M4 7l16 0",key:"svg-0"}],["path",{d:"M10 11l0 6",key:"svg-1"}],["path",{d:"M14 11l0 6",key:"svg-2"}],["path",{d:"M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2 -2l1 -12",key:"svg-3"}],["path",{d:"M9 7v-3a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v3",key:"svg-4"}]],mm=Be("outline","trash","Trash",kH);/**
|
|
463
|
-
* @license @tabler/icons-react v3.
|
|
463
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
464
464
|
*
|
|
465
465
|
* This source code is licensed under the MIT license.
|
|
466
466
|
* See the LICENSE file in the root directory of this source tree.
|
|
467
467
|
*/const NH=[["path",{d:"M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2",key:"svg-0"}],["path",{d:"M7 9l5 -5l5 5",key:"svg-1"}],["path",{d:"M12 4l0 12",key:"svg-2"}]],WE=Be("outline","upload","Upload",NH);/**
|
|
468
|
-
* @license @tabler/icons-react v3.
|
|
468
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
469
469
|
*
|
|
470
470
|
* This source code is licensed under the MIT license.
|
|
471
471
|
* See the LICENSE file in the root directory of this source tree.
|
|
472
472
|
*/const OH=[["path",{d:"M4.876 13.61a4 4 0 1 0 6.124 3.39h6",key:"svg-0"}],["path",{d:"M15.066 20.502a4 4 0 1 0 1.934 -7.502c-.706 0 -1.424 .179 -2 .5l-3 -5.5",key:"svg-1"}],["path",{d:"M16 8a4 4 0 1 0 -8 0c0 1.506 .77 2.818 2 3.5l-3 5.5",key:"svg-2"}]],MH=Be("outline","webhook","Webhook",OH);/**
|
|
473
|
-
* @license @tabler/icons-react v3.
|
|
473
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
474
474
|
*
|
|
475
475
|
* This source code is licensed under the MIT license.
|
|
476
476
|
* See the LICENSE file in the root directory of this source tree.
|
|
477
477
|
*/const LH=[["path",{d:"M18 6l-12 12",key:"svg-0"}],["path",{d:"M6 6l12 12",key:"svg-1"}]],Ys=Be("outline","x","X",LH);/**
|
|
478
|
-
* @license @tabler/icons-react v3.
|
|
478
|
+
* @license @tabler/icons-react v3.35.0 - MIT
|
|
479
479
|
*
|
|
480
480
|
* This source code is licensed under the MIT license.
|
|
481
481
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -550,7 +550,7 @@ function bO(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&
|
|
|
550
550
|
title,
|
|
551
551
|
}
|
|
552
552
|
}`.replace(/\s+/g," ");return(await e.graphql(r)).data.StructureDefinitionList[0]}function QW(e){return e.type==="profile"&&!e?.error&&xn(e.resourceType)}function YW(e,t,n){return t===void 0?e:n===void 0?t:`${t}[${n}]`}const KW="_indented_ldk1d_1",HA={indented:KW};function Ub({propertyDisplayName:e,onClick:t,testId:n}){const r=e?`Add ${e}`:"Add";return e?a.jsx(ke,{title:r,size:"sm",color:"green.6",variant:"subtle","data-testid":n,leftSection:a.jsx(np,{size:"1.25rem"}),onClick:t,children:r}):a.jsx(bn,{title:r,color:"green.6","data-testid":n,onClick:t,children:a.jsx(np,{size:"1.25rem"})})}function GA({propertyDisplayName:e,onClick:t,testId:n}){return a.jsx(bn,{title:e?`Remove ${e}`:"Remove",color:"red.5","data-testid":n,variant:"subtle",onClick:t,children:a.jsx(tp,{size:"1.25rem"})})}function XW(e){const{slice:t,property:n}=e,[r,o]=v.useState(e.defaultValue),s=t.typeSchema?.elements??t.elements,c=v.useContext(ln),d=v.useMemo(()=>{if(Tn(s))return Tc({parentContext:c,elements:s,path:e.path,profileUrl:t.typeSchema?.url})},[c,e.path,t.typeSchema?.url,s]);function f(b){o(b),e.onChange&&e.onChange(b)}const p=t.min>0,m=xn(t.elements),g=BD(t.name),x=e.property.readonly&&r.length===0;return xm(ln.Provider,d,a.jsx(Ot,{title:g,description:t.definition,withAsterisk:p,fhirPath:`${n.path}:${t.name}`,testId:e.testId,readonly:e.property.readonly,children:x?a.jsx(_e,{c:"dimmed",children:"(empty)"}):a.jsxs($e,{className:m?HA.indented:void 0,children:[r.map((b,S)=>a.jsxs(ge,{wrap:"nowrap",children:[a.jsx("div",{style:{flexGrow:1},"data-testid":e.testId&&`${e.testId}-elements-${S}`,children:a.jsx(Bb,{elementDefinitionType:t.type[0],name:t.name,defaultValue:b,onChange:j=>{const C=[...r];C[S]=j,f(C)},outcome:e.outcome,min:t.min,max:t.max,binding:t.binding,path:e.path,valuePath:void 0,readOnly:e.property.readonly})}),!e.property.readonly&&r.length>t.min&&a.jsx(GA,{propertyDisplayName:g,testId:e.testId&&`${e.testId}-remove-${S}`,onClick:j=>{dn(j);const C=[...r];C.splice(S,1),f(C)}})]},`${S}-${r.length}`)),!e.property.readonly&&r.length<t.max&&a.jsx(ge,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:a.jsx(Ub,{propertyDisplayName:g,onClick:b=>{dn(b);const S=[...r,void 0];f(S)},testId:e.testId&&`${e.testId}-add`})})]})}))}function ZW(e){const{property:t}=e,n=De(),[r,o]=v.useState(!0),[s,c]=v.useState([]),[d]=v.useState(()=>Array.isArray(e.defaultValue)?e.defaultValue:[]),[f,p]=v.useState(()=>[d]),m=v.useContext(ln),g=t.type[0]?.code;v.useEffect(()=>{zA({medplum:n,property:t}).then(E=>{c(E);const T=$A(d,E,t.slicing,m.profileUrl);JW(T,E),p(T),o(!1)}).catch(E=>{console.error(E),o(!1)})},[n,t,d,m.profileUrl,p]);function x(E,T){const _=[...f];if(_[T]=E,p(_),e.onChange){const P=_.flat().filter(A=>A!==void 0);e.onChange(P)}}if(r)return a.jsx("div",{children:"Loading..."});const b=s.length,S=f[b],j=!(e.hideNonSliceValues??(g==="Extension"&&s.length>0)),C=Ws(t.path),R=e.property.readonly&&s.length===0&&d.length===0;return a.jsxs($e,{className:e.indent?HA.indented:void 0,children:[R&&a.jsx(_e,{c:"dimmed",children:"(empty)"}),s.map((E,T)=>a.jsx(XW,{slice:E,path:e.path,valuePath:e.valuePath,property:t,defaultValue:f[T],onChange:_=>{x(_,T)},testId:`slice-${E.name}`},E.name)),j&&S.map((E,T)=>a.jsxs(ge,{wrap:"nowrap",style:{flexGrow:1},children:[a.jsx("div",{style:{flexGrow:1},children:a.jsx(Bd,{arrayElement:!0,property:e.property,name:e.name+"."+T,path:e.path,valuePath:YW(e.path,e.valuePath,T),defaultValue:E,onChange:_=>{const P=[...S];P[T]=_,x(P,b)},defaultPropertyType:void 0,outcome:e.outcome})}),!e.property.readonly&&a.jsx(GA,{propertyDisplayName:C,testId:`nonsliced-remove-${T}`,onClick:_=>{dn(_);const P=[...S];P.splice(T,1),x(P,b)}})]},`${T}-${S.length}`)),!e.property.readonly&&j&&f.flat().length<t.max&&a.jsx(ge,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:a.jsx(Ub,{propertyDisplayName:C,onClick:E=>{dn(E);const T=[...S];T.push(void 0),x(T,b)},testId:"nonsliced-add"})})]})}function JW(e,t){for(let n=0;n<t.length;n++){const r=t[n],o=e[n];for(;o.length<r.min;)o.push(void 0)}}function eQ(e){const[t,n]=v.useState(!1),r=SR(),o=v.useRef(null),s={...e.styles};return t||(s.input||(s.input={}),s.input.WebkitTextSecurity="disc"),a.jsxs(lo,{gap:"xs",children:[a.jsx(ol,{...e,styles:{...s,root:{...s.root??{},flexGrow:1}},ref:o,autosize:!0,minRows:1,onFocus:()=>n(!0),onBlur:()=>n(!1)}),a.jsx(bn,{title:"Copy secret",onClick:()=>{r.copy(o.current?.value),Ne({color:"green",message:"Copied"})},children:a.jsx(Db,{})})]})}const tQ=["sun","mon","tue","wed","thu","fri","sat"];function nQ(e){const[t,n]=v.useState(e.defaultValue),[r,o]=v.useState(!e.disabled&&(e.defaultModalOpen??!1)),s=v.useRef(t);return s.current=t,a.jsxs(a.Fragment,{children:[a.jsxs(ge,{gap:"xs",grow:!0,wrap:"nowrap",children:[a.jsx("span",{children:$D(s.current)||"No repeat"}),a.jsx(ke,{disabled:e.disabled,onClick:()=>o(!0),children:"Edit"})]}),!e.disabled&&a.jsx(rQ,{path:e.path,visible:r,defaultValue:s.current,onOk:c=>{e.onChange&&e.onChange(c),n(c),o(!1)},onCancel:()=>o(!1)})]})}const tT={repeat:{period:1,periodUnit:"d"}};function rQ(e){const[t,n]=v.useState(e.defaultValue||tT),{getExtendedProps:r}=v.useContext(ln),[o,s,c,d,f]=v.useMemo(()=>["event","repeat","repeat.period","repeat.periodUnit","repeat.dayOfWeek"].map(j=>r(e.path+"."+j)),[r,e.path]),p=v.useRef(t);p.current=t;function m(j){n({...p.current,event:[j]})}function g(j){n({...p.current,repeat:j})}function x(j){g({...p.current?.repeat,period:j})}function b(j){g({...p.current?.repeat,periodUnit:j})}function S(j){g({...p.current?.repeat,dayOfWeek:j})}return a.jsx(In,{title:"Timing",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:()=>e.onCancel(),children:a.jsxs($e,{children:[a.jsx(Ot,{title:"Starts on",htmlFor:"timing-dialog-start",children:a.jsx(ao,{disabled:o?.readonly,name:"timing-dialog-start",onChange:j=>m(j)})}),a.jsx(Pd,{disabled:s?.readonly,label:"Repeat",checked:!!t.repeat,onChange:j=>g(j.currentTarget.checked?tT.repeat:void 0)}),t.repeat&&a.jsxs(a.Fragment,{children:[a.jsx(Ot,{title:"Repeat every",htmlFor:"timing-dialog-period",children:a.jsxs(ge,{gap:"xs",grow:!0,wrap:"nowrap",children:[a.jsx(Ue,{disabled:c?.readonly,type:"number",step:1,id:"timing-dialog-period",name:"timing-dialog-period",defaultValue:t.repeat.period||1,onChange:j=>x(parseInt(j.currentTarget.value,10)||1)}),a.jsx(sn,{disabled:d?.readonly,id:"timing-dialog-periodUnit",name:"timing-dialog-periodUnit",defaultValue:t.repeat.periodUnit,onChange:j=>b(j.currentTarget.value),data:[{label:"second",value:"s"},{label:"minute",value:"min"},{label:"hour",value:"h"},{label:"day",value:"d"},{label:"week",value:"wk"},{label:"month",value:"mo"},{label:"year",value:"a"}]})]})}),t.repeat.periodUnit==="wk"&&a.jsx(Ot,{title:"Repeat on",children:a.jsx(rd.Group,{multiple:!0,onChange:S,children:a.jsx(ge,{justify:"space-between",mt:"md",gap:"xs",children:tQ.map(j=>a.jsx(rd,{value:j,size:"xs",radius:"xl",disabled:f?.readonly,children:j.charAt(0).toUpperCase()},j))})})})]}),a.jsx(ge,{justify:"flex-end",children:a.jsx(ke,{onClick:()=>e.onOk(t),children:"OK"})})]})})}function Bd(e){const{property:t,name:n,onChange:r,defaultValue:o}=e,s=e.defaultPropertyType&&e.defaultPropertyType!=="undefined"?e.defaultPropertyType:t.type[0].code,c=t.type;if((t.isArray||t.max>1)&&!e.arrayElement){if(s===re.Attachment)return a.jsx($G,{name:n,defaultValue:o,onChange:r,disabled:t.readonly});const d=c[0]?.code!==re.Extension;return a.jsx(ZW,{property:t,name:n,path:e.path,valuePath:e.valuePath,defaultValue:o,indent:d,onChange:r,outcome:e.outcome})}else return c.length>1?a.jsx(iQ,{elementDefinitionTypes:c,...e}):a.jsx(Bb,{name:n,defaultValue:o,onChange:d=>{if(e.onChange){const f=e.name.replace("[x]",Ln(c[0].code));e.onChange(d,f)}},outcome:e.outcome,elementDefinitionType:c[0],min:t.min,max:t.min,binding:t.binding,path:e.path,valuePath:e.valuePath,readOnly:t.readonly})}function iQ(e){const t=e.elementDefinitionTypes;let n;e.defaultPropertyType&&(n=t.find(s=>s.code===e.defaultPropertyType)),n||(n=t[0]);const[r,o]=v.useState(n);return a.jsxs(ge,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[a.jsx(sn,{disabled:e.property.readonly,style:{width:"200px"},defaultValue:r.code,"data-testid":e.name&&e.name+"-selector",onChange:s=>{o(t.find(c=>c.code===s.currentTarget.value))},data:t.map(s=>({value:s.code,label:s.code}))}),a.jsx(Bb,{name:e.name,defaultValue:e.defaultValue,outcome:e.outcome,elementDefinitionType:r,onChange:s=>{e.onChange&&e.onChange(s,e.name.replace("[x]",Ln(r.code)))},min:e.property.min,max:e.property.max,binding:e.property.binding,path:e.property.path,valuePath:e.valuePath,readOnly:e.property.readonly})]})}function Bb(e){const{name:t,onChange:n,outcome:r,binding:o,path:s,valuePath:c,readOnly:d}=e,f=e.min!==void 0&&e.min>0,p=e.elementDefinitionType.code,m=v.useContext(ln),g=v.useMemo(()=>{if(!ub(p)||!xn(e.defaultValue))return e.defaultValue;const S=Object.create(null);if(m.path===e.path)$E(S,m.elements);else{const j=Is(m.path,e.path);if(j===void 0)return e.defaultValue;$E(S,m.elements,j)}return Tn(S)?S:e.defaultValue},[p,m.path,m.elements,e.path,e.defaultValue]);if(!p)return a.jsx("div",{children:"Property type not specified "});function x(){return{name:t,defaultValue:g,onChange:n,outcome:r,path:s,valuePath:c,disabled:d}}function b(){const S=kt(e.outcome,c??s);return{id:t,name:t,"data-testid":t,defaultValue:g,required:f,error:S,disabled:d}}switch(p){case re.SystemString:case re.canonical:case re.string:case re.time:case re.uri:case re.url:return e.path==="Project.secret.value[x]"?a.jsx(eQ,{...b(),onChange:S=>{e.onChange&&e.onChange(S.currentTarget.value)}}):a.jsx(Ue,{...b(),onChange:S=>{n&&n(S.currentTarget.value)}});case re.date:return a.jsx(Ue,{...b(),type:"date",onChange:S=>{n&&n(S.currentTarget.value)}});case re.dateTime:case re.instant:return a.jsx(ao,{...b(),onChange:n,outcome:r});case re.decimal:case re.integer:case re.positiveInt:case re.unsignedInt:return a.jsx(Ue,{...b(),type:"number",step:p===re.decimal?"any":"1",onChange:S=>{if(n){const j=S.currentTarget.valueAsNumber;n(Number.isNaN(j)?void 0:j)}}});case re.code:return a.jsx(RA,{...b(),error:void 0,onChange:n,binding:o?.valueSet,creatable:!0,maxValues:1});case re.boolean:return a.jsx(Dn,{...b(),defaultChecked:!!g,onChange:S=>{n&&n(S.currentTarget.checked)}});case re.base64Binary:case re.markdown:return a.jsx(ol,{...b(),spellCheck:p!==re.base64Binary,onChange:S=>{n&&n(S.currentTarget.value)}});case re.Address:return a.jsx(DF,{...x()});case re.Annotation:return a.jsx(AF,{...x()});case re.Attachment:return a.jsx(_A,{...x()});case re.CodeableConcept:return a.jsx(jW,{binding:o?.valueSet,...x()});case re.Coding:return a.jsx(TW,{binding:o?.valueSet,...x()});case re.ContactDetail:return a.jsx(DW,{...x()});case re.ContactPoint:return a.jsx(qA,{...x()});case re.Extension:return a.jsx(kW,{...x(),propertyType:e.elementDefinitionType});case re.HumanName:return a.jsx(NW,{...x()});case re.Identifier:return a.jsx(OW,{...x()});case re.Money:return a.jsx(LW,{...x()});case re.Period:return a.jsx(IW,{...x()});case re.Duration:case re.Quantity:return a.jsx(Ks,{...x()});case re.Range:return a.jsx(zb,{...x()});case re.Ratio:return a.jsx(zW,{...x()});case re.Reference:return a.jsx(Qa,{...x(),targetTypes:aQ(e.elementDefinitionType)});case re.Timing:return a.jsx(nQ,{...x()});case re.Dosage:case re.UsageContext:default:return a.jsx(Vb,{...x(),typeName:p})}}const oQ=[`${Ui}/fhir/StructureDefinition/`,"https://medplum.com/fhir/StructureDefinition/"];function aQ(e){return e?.targetProfile?.map(t=>{const n=oQ.find(r=>t.startsWith(r));return n?t.slice(n.length):t})}function sQ(e){const[t,n]=v.useState(e.defaultValue??{}),r=v.useContext(ln),o=v.useMemo(()=>_F(r.elements),[r.elements]);function s(d){n(d),e.onChange&&e.onChange(d)}const c={type:e.type,value:t};return a.jsx($e,{style:{flexGrow:1},"data-testid":e.testId,children:o.map(([d,f])=>{const[p,m]=uW(c,d,f),g=f.min!==void 0&&f.min>0,x=e.valuePath?e.valuePath+"."+d:void 0,b=a.jsx(Bd,{property:f,name:d,path:e.path+"."+d,valuePath:x,defaultValue:p,defaultPropertyType:m,onChange:(S,j)=>{s(SW({...t},d,j??d,f,S))},outcome:e.outcome},d);return e.type==="Extension"||Tb.includes(d)?b:f.type.length===1&&f.type[0].code==="boolean"?a.jsx(FA,{title:Ws(d),description:f.description,htmlFor:d,fhirPath:f.path,withAsterisk:g,readonly:f.readonly,children:b},d):a.jsx(Ot,{title:Ws(d),description:f.description,withAsterisk:g,htmlFor:d,outcome:e.outcome,fhirPath:f.path,errorExpression:x,readonly:f.readonly,children:b},d)})})}function Vb(e){const[t]=v.useState(()=>e.defaultValue??{}),n=v.useContext(ln),r=e.profileUrl??n?.profileUrl,o=v.useMemo(()=>im(e.typeName,r),[e.typeName,r]),s=o?.type??e.typeName,c=v.useMemo(()=>{if(o)return Tc({parentContext:n,elements:o.elements,path:e.path,profileUrl:o.url,accessPolicyResource:e.accessPolicyResource})},[o,n,e.path,e.accessPolicyResource]);return o?xm(ln.Provider,c,a.jsx(sQ,{path:e.path,valuePath:e.valuePath,type:s,defaultValue:t,onChange:e.onChange,outcome:e.outcome})):a.jsxs("div",{children:[s," not implemented"]})}const lQ="_noteCite_10swh_5",cQ="_noteRoot_10swh_10",nT={noteCite:lQ,noteRoot:cQ};function WA({value:e}){return e?a.jsx($e,{justify:"flex-start",gap:"xs",children:e.map(t=>t.text&&a.jsx(w0,{classNames:{cite:nT.noteCite,root:nT.noteRoot},cite:t.authorReference?.display||t.authorString,icon:null,children:t.text},`note-${t.text}`))}):null}function dl(e){const{value:t,link:n,...r}=e,[o,s]=v.useState(),c=Gt(t,s);let d;if(o&&!hD(o))d=`[${Ge(o)}]`;else if(c)d=Zo(c);else return null;return n?a.jsx(vt,{to:t,...r,children:d}):a.jsx(_e,{component:"span",...r,children:d})}function pc(e){return a.jsxs(ge,{gap:"xs",children:[a.jsx(os,{size:24,radius:12,value:e.value,link:e.link}),a.jsx(dl,{value:e.value,link:e.link})]})}const uQ={draft:"blue",active:"blue","on-hold":"yellow",revoked:"red",completed:"green","entered-in-error":"red",unknown:"gray",retired:"gray",registered:"blue",preliminary:"blue",final:"green",amended:"yellow",corrected:"yellow",cancelled:"red",requested:"blue",received:"blue",accepted:"blue",rejected:"red",ready:"blue","in-progress":"blue",failed:"red",proposed:"blue",pending:"blue",booked:"blue",arrived:"blue",fulfilled:"green",noshow:"red","checked-in":"blue",waitlist:"gray",routine:"gray",urgent:"red",asap:"red",stat:"red","not-done":"red",connected:"green",disconnected:"red",finished:"green",planned:"gray"};function bm(e){const{status:t,...n}=e;return a.jsx(Ip,{color:e.color||uQ[t],...n,children:t.replace(/-/g," ")})}const dQ="_table_pe9td_1",fQ="_criticalRow_pe9td_12",QA={table:dQ,criticalRow:fQ};Fb.defaultProps={hideObservationNotes:!1,hideSpecimenInfo:!1,hideSubject:!1};function Fb(e){const t=De(),n=Gt(e.value),[r,o]=v.useState();if(v.useEffect(()=>{n?.specimen&&Promise.allSettled(n.specimen.map(c=>t.readReference(c))).then(c=>c.filter(d=>d.status==="fulfilled").map(d=>d.value)).then(o).catch(console.error)},[t,n]),!n)return null;const s=r?.flatMap(c=>c.note||[])||[];if(n.presentedForm&&n.presentedForm.length>0){const c=n.presentedForm[0];c.contentType?.startsWith("text/plain")&&c.data&&s.push({text:window.atob(c.data)})}return a.jsxs($e,{children:[a.jsx(Oe,{children:"Diagnostic Report"}),a.jsx(hQ,{value:n,hideSubject:e.hideSubject}),r&&!e.hideSpecimenInfo&&pQ(r),n.result&&a.jsx(mQ,{hideObservationNotes:e.hideObservationNotes,value:n.result}),s.length>0&&a.jsx(WA,{value:s})]})}function hQ({value:e,hideSubject:t=!1}){return a.jsxs(ge,{mt:"md",gap:30,children:[e.subject&&!t&&a.jsxs("div",{children:[a.jsx(_e,{size:"xs",tt:"uppercase",c:"dimmed",children:"Subject"}),a.jsx(pc,{value:e.subject,link:!0})]}),e.resultsInterpreter?.map(n=>a.jsxs("div",{children:[a.jsx(_e,{size:"xs",tt:"uppercase",c:"dimmed",children:"Interpreter"}),a.jsx(pc,{value:n,link:!0})]},n.reference)),e.performer?.map(n=>a.jsxs("div",{children:[a.jsx(_e,{size:"xs",tt:"uppercase",c:"dimmed",children:"Performer"}),a.jsx(pc,{value:n,link:!0})]},n.reference)),e.issued&&a.jsxs("div",{children:[a.jsx(_e,{size:"xs",tt:"uppercase",c:"dimmed",children:"Issued"}),a.jsx(_e,{children:lr(e.issued)})]}),e.status&&a.jsxs("div",{children:[a.jsx(_e,{size:"xs",tt:"uppercase",c:"dimmed",children:"Status"}),a.jsx(bm,{status:e.status})]})]})}function pQ(e){return a.jsxs($e,{gap:"xs",children:[a.jsx(Oe,{order:2,size:"h6",children:"Specimens"}),a.jsx(vr,{type:"ordered",children:e?.map(t=>a.jsx(vr.Item,{ml:"sm",children:a.jsxs(ge,{gap:20,children:[a.jsxs(ge,{gap:5,children:[a.jsx(_e,{fw:500,children:"Collected:"})," ",lr(t.collection?.collectedDateTime)]}),a.jsxs(ge,{gap:5,children:[a.jsx(_e,{fw:500,children:"Received:"})," ",lr(t.receivedTime)]})]})},`specimen-${t.id}`))})]})}function mQ(e){return a.jsxs("table",{className:QA.table,children:[a.jsx("thead",{children:a.jsxs("tr",{children:[a.jsx("th",{children:"Test"}),a.jsx("th",{children:"Value"}),a.jsx("th",{children:"Reference Range"}),a.jsx("th",{children:"Interpretation"}),a.jsx("th",{children:"Category"}),a.jsx("th",{children:"Performer"}),a.jsx("th",{children:"Status"})]})}),a.jsx("tbody",{children:a.jsx(YA,{value:e.value,ancestorIds:e.ancestorIds,hideObservationNotes:e.hideObservationNotes})})]})}function YA(e){return a.jsx(a.Fragment,{children:e.value?.map(t=>a.jsx(gQ,{value:t,ancestorIds:e.ancestorIds,hideObservationNotes:e.hideObservationNotes},`obs-${ca(t)?t.reference:t.id}`))})}function gQ(e){const t=Gt(e.value);if(!t||e.ancestorIds?.includes(t.id))return null;const n=!e.hideObservationNotes&&t.note,r=xQ(t);return a.jsxs(a.Fragment,{children:[a.jsxs("tr",{className:It({[QA.criticalRow]:r}),children:[a.jsx("td",{rowSpan:n?2:1,children:a.jsx(vt,{to:t,children:a.jsx(oo,{value:t.code})})}),a.jsx("td",{children:a.jsx(vQ,{value:t})}),a.jsx("td",{children:a.jsx(yQ,{value:t.referenceRange})}),a.jsx("td",{children:t.interpretation&&t.interpretation.length>0&&a.jsx(oo,{value:t.interpretation[0]})}),a.jsx("td",{children:t.category&&t.category.length>0&&a.jsx(a.Fragment,{children:t.category.map(o=>a.jsx("div",{children:a.jsx(oo,{value:o})},`category-${Xa(o)}`))})}),a.jsx("td",{children:t.performer?.map(o=>a.jsx(ip,{value:o},o.reference))}),a.jsx("td",{children:t.status&&a.jsx(bm,{status:t.status})})]}),t.hasMember&&a.jsx(YA,{value:t.hasMember,ancestorIds:e.ancestorIds?[...e.ancestorIds,t.id]:[t.id],hideObservationNotes:e.hideObservationNotes}),n&&a.jsx("tr",{children:a.jsx("td",{colSpan:6,children:a.jsx(WA,{value:t.note})})})]})}function vQ(e){const t=e.value;return a.jsx(a.Fragment,{children:zD(t)})}function yQ(e){const t=e.value&&e.value.length>0&&e.value[0];return t?t.text?a.jsx(a.Fragment,{children:t.text}):a.jsx(Ib,{value:t}):null}function xQ(e){const t=e.interpretation?.[0]?.coding?.[0]?.code;return t==="AA"||t==="LL"||t==="HH"||t==="A"}var dy={},Vo={},rT;function KA(){if(rT)return Vo;rT=1,Object.defineProperty(Vo,"__esModule",{value:!0}),Vo.Pointer=Vo.escapeToken=Vo.unescapeToken=void 0;function e(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}Vo.unescapeToken=e;function t(r){return r.replace(/~/g,"~0").replace(/\//g,"~1")}Vo.escapeToken=t;var n=(function(){function r(o){o===void 0&&(o=[""]),this.tokens=o}return r.fromJSON=function(o){var s=o.split("/").map(e);if(s[0]!=="")throw new Error("Invalid JSON Pointer: ".concat(o));return new r(s)},r.prototype.toString=function(){return this.tokens.map(t).join("/")},r.prototype.evaluate=function(o){for(var s=null,c="",d=o,f=1,p=this.tokens.length;f<p;f++)s=d,c=this.tokens[f],!(c=="__proto__"||c=="constructor"||c=="prototype")&&(d=(s||{})[c]);return{parent:s,key:c,value:d}},r.prototype.get=function(o){return this.evaluate(o).value},r.prototype.set=function(o,s){var c=this.evaluate(o);c.parent&&(c.parent[c.key]=s)},r.prototype.push=function(o){this.tokens.push(o)},r.prototype.add=function(o){var s=this.tokens.concat(String(o));return new r(s)},r})();return Vo.Pointer=n,Vo}var hn={},fy={},iT;function XA(){return iT||(iT=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.clone=e.objectType=e.hasOwnProperty=void 0,e.hasOwnProperty=Object.prototype.hasOwnProperty;function t(o){return o===void 0?"undefined":o===null?"null":Array.isArray(o)?"array":typeof o}e.objectType=t;function n(o){return o!=null&&typeof o=="object"}function r(o){if(!n(o))return o;if(o.constructor==Array){for(var s=o.length,c=new Array(s),d=0;d<s;d++)c[d]=r(o[d]);return c}if(o.constructor==Date){var f=new Date(+o);return f}var p={};for(var m in o)e.hasOwnProperty.call(o,m)&&(p[m]=r(o[m]));return p}e.clone=r})(fy)),fy}var mr={},oT;function ZA(){if(oT)return mr;oT=1,Object.defineProperty(mr,"__esModule",{value:!0}),mr.diffAny=mr.diffObjects=mr.diffArrays=mr.intersection=mr.subtract=mr.isDestructive=void 0;var e=XA();function t(m){var g=m.op;return g==="remove"||g==="replace"||g==="copy"||g==="move"}mr.isDestructive=t;function n(m,g){var x={};for(var b in m)e.hasOwnProperty.call(m,b)&&m[b]!==void 0&&(x[b]=1);for(var S in g)e.hasOwnProperty.call(g,S)&&g[S]!==void 0&&delete x[S];return Object.keys(x)}mr.subtract=n;function r(m){for(var g=m.length,x={},b=0;b<g;b++){var S=m[b];for(var j in S)e.hasOwnProperty.call(S,j)&&S[j]!==void 0&&(x[j]=(x[j]||0)+1)}for(var j in x)x[j]<g&&delete x[j];return Object.keys(x)}mr.intersection=r;function o(m){return m.op==="add"}function s(m){return m.op==="remove"}function c(m,g){return{operations:m.operations.concat(g),cost:m.cost+1}}function d(m,g,x,b){b===void 0&&(b=p);var S={"0,0":{operations:[],cost:0}};function j(_,P){var A="".concat(_,",").concat(P),k=S[A];if(k===void 0){if(_>0&&P>0&&!b(m[_-1],g[P-1],x.add(String(_-1))).length)k=j(_-1,P-1);else{var L=[];if(_>0){var z=j(_-1,P),B={op:"remove",index:_-1};L.push(c(z,B))}if(P>0){var Z=j(_,P-1),K={op:"add",index:_-1,value:g[P-1]};L.push(c(Z,K))}if(_>0&&P>0){var Y=j(_-1,P-1),H={op:"replace",index:_-1,original:m[_-1],value:g[P-1]};L.push(c(Y,H))}var W=L.sort(function(M,I){return M.cost-I.cost})[0];k=W}S[A]=k}return k}var C=isNaN(m.length)||m.length<=0?0:m.length,R=isNaN(g.length)||g.length<=0?0:g.length,E=j(C,R).operations,T=E.reduce(function(_,P){var A=_[0],k=_[1];if(o(P)){var L=P.index+1+k,z=L<C+k?String(L):"-",B={op:P.op,path:x.add(z).toString(),value:P.value};return[A.concat(B),k+1]}else if(s(P)){var B={op:P.op,path:x.add(String(P.index+k)).toString()};return[A.concat(B),k-1]}else{var Z=x.add(String(P.index+k)),K=b(P.original,P.value,Z);return[A.concat.apply(A,K),k]}},[[],0])[0];return T}mr.diffArrays=d;function f(m,g,x,b){b===void 0&&(b=p);var S=[];return n(m,g).forEach(function(j){S.push({op:"remove",path:x.add(j).toString()})}),n(g,m).forEach(function(j){S.push({op:"add",path:x.add(j).toString(),value:g[j]})}),r([m,g]).forEach(function(j){S.push.apply(S,b(m[j],g[j],x.add(j)))}),S}mr.diffObjects=f;function p(m,g,x,b){if(b===void 0&&(b=p),m===g)return[];var S=(0,e.objectType)(m),j=(0,e.objectType)(g);return S=="array"&&j=="array"?d(m,g,x,b):S=="object"&&j=="object"?f(m,g,x,b):[{op:"replace",path:x.toString(),value:g}]}return mr.diffAny=p,mr}var aT;function bQ(){if(aT)return hn;aT=1;var e=hn&&hn.__extends||(function(){var C=function(R,E){return C=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(T,_){T.__proto__=_}||function(T,_){for(var P in _)Object.prototype.hasOwnProperty.call(_,P)&&(T[P]=_[P])},C(R,E)};return function(R,E){if(typeof E!="function"&&E!==null)throw new TypeError("Class extends value "+String(E)+" is not a constructor or null");C(R,E);function T(){this.constructor=R}R.prototype=E===null?Object.create(E):(T.prototype=E.prototype,new T)}})();Object.defineProperty(hn,"__esModule",{value:!0}),hn.apply=hn.InvalidOperationError=hn.test=hn.copy=hn.move=hn.replace=hn.remove=hn.add=hn.TestError=hn.MissingError=void 0;var t=KA(),n=XA(),r=ZA(),o=(function(C){e(R,C);function R(E){var T=C.call(this,"Value required at path: ".concat(E))||this;return T.path=E,T.name="MissingError",T}return R})(Error);hn.MissingError=o;var s=(function(C){e(R,C);function R(E,T){var _=C.call(this,"Test failed: ".concat(E," != ").concat(T))||this;return _.actual=E,_.expected=T,_.name="TestError",_}return R})(Error);hn.TestError=s;function c(C,R,E){if(Array.isArray(C))if(R=="-")C.push(E);else{var T=parseInt(R,10);C.splice(T,0,E)}else C[R]=E}function d(C,R){if(Array.isArray(C)){var E=parseInt(R,10);C.splice(E,1)}else delete C[R]}function f(C,R){var E=t.Pointer.fromJSON(R.path).evaluate(C);return E.parent===void 0?new o(R.path):(c(E.parent,E.key,(0,n.clone)(R.value)),null)}hn.add=f;function p(C,R){var E=t.Pointer.fromJSON(R.path).evaluate(C);return E.value===void 0?new o(R.path):(d(E.parent,E.key),null)}hn.remove=p;function m(C,R){var E=t.Pointer.fromJSON(R.path).evaluate(C);if(E.parent===null)return new o(R.path);if(Array.isArray(E.parent)){if(parseInt(E.key,10)>=E.parent.length)return new o(R.path)}else if(E.value===void 0)return new o(R.path);return E.parent[E.key]=(0,n.clone)(R.value),null}hn.replace=m;function g(C,R){var E=t.Pointer.fromJSON(R.from).evaluate(C);if(E.value===void 0)return new o(R.from);var T=t.Pointer.fromJSON(R.path).evaluate(C);return T.parent===void 0?new o(R.path):(d(E.parent,E.key),c(T.parent,T.key,E.value),null)}hn.move=g;function x(C,R){var E=t.Pointer.fromJSON(R.from).evaluate(C);if(E.value===void 0)return new o(R.from);var T=t.Pointer.fromJSON(R.path).evaluate(C);return T.parent===void 0?new o(R.path):(c(T.parent,T.key,(0,n.clone)(E.value)),null)}hn.copy=x;function b(C,R){var E=t.Pointer.fromJSON(R.path).evaluate(C);return(0,r.diffAny)(E.value,R.value,new t.Pointer).length?new s(E.value,R.value):null}hn.test=b;var S=(function(C){e(R,C);function R(E){var T=C.call(this,"Invalid operation: ".concat(E.op))||this;return T.operation=E,T.name="InvalidOperationError",T}return R})(Error);hn.InvalidOperationError=S;function j(C,R){switch(R.op){case"add":return f(C,R);case"remove":return p(C,R);case"replace":return m(C,R);case"move":return g(C,R);case"copy":return x(C,R);case"test":return b(C,R)}return new S(R)}return hn.apply=j,hn}var sT;function SQ(){return sT||(sT=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createTests=e.createPatch=e.applyPatch=e.Pointer=void 0;var t=KA();Object.defineProperty(e,"Pointer",{enumerable:!0,get:function(){return t.Pointer}});var n=bQ(),r=ZA();function o(p,m){return m.map(function(g){return(0,n.apply)(p,g)})}e.applyPatch=o;function s(p){function m(g,x,b){var S=p(g,x,b);return Array.isArray(S)?S:(0,r.diffAny)(g,x,b,m)}return m}function c(p,m,g){var x=new t.Pointer;return(g?s(g):r.diffAny)(p,m,x)}e.createPatch=c;function d(p,m){var g=t.Pointer.fromJSON(m).evaluate(p);if(g!==void 0)return{op:"test",path:m,value:g.value}}function f(p,m){var g=new Array;return m.filter(r.isDestructive).forEach(function(x){var b=d(p,x.path);if(b&&g.push(b),"from"in x){var S=d(p,x.from);S&&g.push(S)}}),g}e.createTests=f})(dy)),dy}var JA=SQ();const wQ="_removed_el5zk_1",jQ="_added_el5zk_6",lT={removed:wQ,added:jQ};function CQ(e){const{name:t,path:n,property:r,originalValue:o,revisedValue:s}=e,c=!!r?.type?.find(m=>m.code==="Attachment"),[d,f]=v.useState(c),p=()=>f(m=>!m);return a.jsx(a.Fragment,{children:c&&!d||!c?a.jsx(a.Fragment,{children:a.jsxs(de.Tr,{children:[a.jsx(de.Td,{children:t}),a.jsx(de.Td,{className:lT.removed,children:o&&a.jsx($i,{path:n,property:r,propertyType:o.type,value:o.value,ignoreMissingValues:!0})}),a.jsx(de.Td,{className:lT.added,children:s&&a.jsx($i,{path:n,property:r,propertyType:s.type,value:s.value,ignoreMissingValues:!0})})]})}):a.jsxs(de.Tr,{children:[a.jsx(de.Td,{children:t}),a.jsx(de.Td,{colSpan:2,style:{textAlign:"right"},children:a.jsx(ke,{onClick:p,variant:"light",children:"Expand"})})]})})}const EQ="_root_15xvr_1",TQ={root:EQ};function RQ(e){const t=De(),{original:n,revised:r}=e,[o,s]=v.useState(!1);v.useEffect(()=>{t.requestSchema(e.original.resourceType).then(()=>s(!0)).catch(console.log)},[t,e.original.resourceType]);const c=v.useMemo(()=>{if(!o)return null;const d=[Yr(n)],f=[Yr(r)],p=[],m=_Q(JA.createPatch(n,r));for(const g of m){const x=g.path,b=DQ(x),S=AQ(n.resourceType,b),j=g.op==="add"?void 0:Za(b,d),C=g.op==="remove"?void 0:Za(b,f);p.push({key:`op-${g.op}-${g.path}`,name:`${Ln(g.op)} ${b}`,path:S?.path??n.resourceType+"."+b,property:S,originalValue:cT(S,j),revisedValue:cT(S,C)})}return p},[o,n,r]);return c?a.jsxs(de,{className:TQ.root,children:[a.jsx(de.Thead,{children:a.jsxs(de.Tr,{children:[a.jsx(de.Th,{}),a.jsx(de.Th,{children:"Before"}),a.jsx(de.Th,{children:"After"})]})}),a.jsx(de.Tbody,{children:c.map(d=>{const{key:f,...p}=d;return a.jsx(CQ,{...p},f)})})]}):null}function _Q(e){const t=[];for(const n of e){const{op:r,path:o}=n;if(o.startsWith("/meta/author")||o.startsWith("/meta/compartment")||o.startsWith("/meta/lastUpdated")||o.startsWith("/meta/versionId"))continue;const s=e.filter(d=>d.op===r&&d.path===o).length,c={op:r,path:o};s>1&&(r==="add"||r==="remove")&&/\/[0-9-]+$/.test(o)&&(c.op="replace",c.path=o.replace(/\/[^/]+$/,"")),t.some(d=>d.op===c.op&&d.path===c.path)||t.push(c)}return t}function DQ(e){const t=e.split("/").filter(Boolean);let n="";for(let r=0;r<t.length;r++){const o=t[r];o==="-"?n+=".last()":/^\d+$/.test(o)?n+=`[${o}]`:(r>0&&(n+="."),n+=o)}return n.endsWith(".url")&&(n=n.replace(/\.url$/,"")),n}function AQ(e,t){return dm(e,{code:e+"."+t,expression:e+"."+t})?.elementDefinitions?.[0]}function cT(e,t){return t&&{type:Array.isArray(t)?t[0].type:t.type,value:PQ(t,!!e?.isArray)}}function PQ(e,t){const n=pU(e).flatMap(r=>r.value);return t?n:n[0]}function qb(e){const{profileUrl:t}=e,n=De(),r=n.getAccessPolicy(),o=Gt(e.value),[s,c]=v.useState(!1);v.useEffect(()=>{if(o)if(t)n.requestProfileSchema(t,{expandProfile:!0}).then(()=>{Uc(t)?c(!0):console.error(`Schema not found for ${t}`)}).catch(f=>{console.error("Error in requestProfileSchema",f)});else{const f=o.resourceType;n.requestSchema(f).then(()=>{c(!0)}).catch(console.error)}},[n,t,o]);const d=v.useMemo(()=>o&&GD(o,zs.READ,r),[r,o]);return!s||!o?null:a.jsx(op,{path:o.resourceType,value:{type:o.resourceType,value:e.forceUseInput?e.value:o},profileUrl:t,ignoreMissingValues:e.ignoreMissingValues,accessPolicyResource:d})}const kQ="_item_5q6yx_1",NQ="_itemPadding_5q6yx_5",uT={item:kQ,itemPadding:NQ};function OQ(e){return a.jsx(Vc,{children:e.children})}function Xs(e){const{resource:t,profile:n,padding:r,popupMenuItems:o,...s}=e,c=n??t.meta?.author,d=e.dateTime??t.meta?.lastUpdated;return a.jsxs(cl,{"data-testid":"timeline-item",fill:!0,...s,children:[a.jsxs(ge,{justify:"space-between",gap:8,mx:"xs",my:"sm",children:[a.jsx(os,{value:c,link:!0,size:"md"}),a.jsxs("div",{style:{flex:1},children:[a.jsx(_e,{size:"sm",children:a.jsx(dl,{c:"dark",fw:500,value:c,link:!0})}),a.jsxs(_e,{size:"xs",children:[a.jsx(vt,{c:"dimmed",to:e.resource,children:lr(d)}),a.jsx(_e,{component:"span",c:"dimmed",mx:8,children:"·"}),a.jsx(vt,{c:"dimmed",to:e.resource,children:e.resource.resourceType})]})]}),o&&a.jsxs(Ce,{position:"bottom-end",shadow:"md",width:200,children:[a.jsx(Ce.Target,{children:a.jsx(bn,{color:"gray",variant:"subtle",radius:"xl","aria-label":`Actions for ${At(e.resource)}`,children:a.jsx(Sq,{})})}),o]})]}),a.jsx(wA,{children:a.jsx("div",{className:It(uT.item,{[uT.itemPadding]:r}),children:e.children})})]})}function eP(e,t){e.sort((n,r)=>{const o=dT(n,t),s=dT(r,t);return o>s?1:o<s?-1:fT(n,t)-fT(r,t)})}function dT(e,t){if(!tP(e,t)){const n=e.priority;if(typeof n=="string")return{stat:4,asap:3,urgent:2}[n]??0}return 0}function fT(e,t){if(!tP(e,t)){if(e.resourceType==="Communication"&&e.sent)return new Date(e.sent).getTime();if((e.resourceType==="DiagnosticReport"||e.resourceType==="Media"||e.resourceType==="Observation")&&e.issued)return new Date(e.issued).getTime();if(e.resourceType==="DocumentReference"&&e.date)return new Date(e.date).getTime()}const n=e.meta?.lastUpdated;return n?new Date(n).getTime():0}function tP(e,t){return!!t&&e.resourceType===t.resourceType&&e.id===t.id}const MQ="_pinnedComment_u08s5_1",LQ={pinnedComment:MQ};function Sm(e){const t=De(),n=t.getProfile(),r=v.useRef(null),o=Gt(e.value),[s,c]=v.useState(),[d,f]=v.useState([]),[p,m]=v.useState(10),g=e.loadTimelineResources,x=v.useRef(d);x.current=d;const b=v.useCallback(k=>{eP(k,o),k.reverse(),f(k)},[o]),S=v.useCallback(k=>{const L=[];for(const z of k){if(z.status!=="fulfilled")continue;const B=z.value;if(B.type==="history"&&c(B),B.entry)for(const Z of B.entry)L.push(Z.resource)}b(L)},[b]),j=v.useCallback(k=>b([...x.current,k]),[b]),C=v.useCallback(()=>{let k,L;"resourceType"in e.value?(k=e.value.resourceType,L=e.value.id):[k,L]=e.value.reference?.split("/"),g(t,k,L).then(S).catch(console.error)},[t,e.value,g,S]);v.useEffect(()=>C(),[C]);function R(k){!o||!e.createCommunication||t.createResource(e.createCommunication(o,n,k)).then(L=>j(L)).catch(console.error)}function E(k){!o||!e.createMedia||t.createResource(e.createMedia(o,n,k)).then(L=>j(L)).then(()=>Ms({id:"upload-notification",color:"teal",title:"Upload complete",message:"",icon:a.jsx(vo,{size:16}),autoClose:2e3})).catch(L=>Ms({id:"upload-notification",color:"red",title:"Upload error",message:Ge(L),icon:a.jsx(HE,{size:16}),autoClose:2e3}))}function T(){Ne({id:"upload-notification",loading:!0,title:"Initializing upload...",message:"Please wait...",autoClose:!1,withCloseButton:!1})}function _(k){Ms({id:"upload-notification",loading:!0,title:"Uploading...",message:FQ(k),autoClose:!1,withCloseButton:!1})}function P(k){Ms({id:"upload-notification",color:"red",title:"Upload error",message:Ge(k),icon:a.jsx(HE,{size:16}),autoClose:2e3})}if(!o)return a.jsx(Jn,{style:{width:"100%",height:"100%"},children:a.jsx(Nr,{})});const A=d.filter(k=>k).slice(0,p);return a.jsxs(OQ,{children:[e.createCommunication&&a.jsx(cl,{children:a.jsx(ut,{testid:"timeline-form",onSubmit:k=>{R(k.text);const L=r.current;L&&(L.value="",L.focus())},children:a.jsxs(ge,{gap:"xs",wrap:"nowrap",style:{width:"100%"},children:[a.jsx(os,{value:n}),a.jsx(Ue,{name:"text",ref:r,placeholder:"Add comment",style:{width:"100%",maxWidth:300}}),a.jsx(bn,{type:"submit",radius:"xl",color:"blue",variant:"filled",children:a.jsx(Qq,{size:16})}),a.jsx(Lb,{securityContext:qt(o),onUpload:E,onUploadStart:T,onUploadProgress:_,onUploadError:P,children:k=>a.jsx(bn,{...k,radius:"xl",color:"blue",variant:"filled",children:a.jsx(_b,{size:16})})})]})})}),A.map(k=>{const L=`${k.resourceType}/${k.id}/${k.meta?.versionId}`,z=e.getMenu?e.getMenu({primaryResource:o,currentResource:k,reloadTimeline:C}):void 0;if(k.resourceType===o.resourceType&&k.id===o.id)return a.jsx(IQ,{history:s,resource:k,popupMenuItems:z},L);switch(k.resourceType){case"AuditEvent":return a.jsx(BQ,{resource:k,popupMenuItems:z},L);case"Communication":return a.jsx(zQ,{resource:k,popupMenuItems:z},L);case"DiagnosticReport":return a.jsx(VQ,{resource:k,popupMenuItems:z},L);case"Media":return a.jsx(UQ,{resource:k,popupMenuItems:z},L);default:return a.jsx(Xs,{resource:k,padding:!0,children:a.jsx(qb,{value:k,ignoreMissingValues:!0})},L)}}),p<d.length&&a.jsx(ge,{justify:"center",pb:"lg",children:a.jsx(ke,{onClick:()=>m(p+10),children:"Show More"})})]})}function IQ(e){const{history:t,resource:n,...r}=e,o=$Q(t,n);return o?a.jsx(Xs,{resource:n,padding:!0,...r,children:a.jsx(RQ,{original:o,revised:e.resource})}):a.jsxs(Xs,{resource:n,padding:!0,...r,children:[a.jsx("h3",{children:"Created"}),a.jsx(qb,{value:n,ignoreMissingValues:!0,forceUseInput:!0})]})}function $Q(e,t){const n=e.entry??[],r=n.findIndex(o=>o.resource?.meta?.versionId===t.meta?.versionId);if(!(r>=n.length-1))return n[r+1].resource}function zQ(e){const n=!e.resource.priority||e.resource.priority==="routine"?void 0:LQ.pinnedComment;return a.jsx(Xs,{resource:e.resource,profile:e.resource.sender,dateTime:e.resource.sent,padding:!0,className:n,popupMenuItems:e.popupMenuItems,children:a.jsx("p",{children:e.resource.payload?.[0]?.contentString})})}function UQ(e){const t=e.resource.content?.contentType,n=t&&!t.startsWith("image/")&&!t.startsWith("video/")&&t!=="application/pdf";return a.jsx(Xs,{resource:e.resource,padding:!!n,popupMenuItems:e.popupMenuItems,children:a.jsx(Ud,{value:e.resource.content})})}function BQ(e){return a.jsx(Xs,{resource:e.resource,padding:!0,popupMenuItems:e.popupMenuItems,children:a.jsx(Zr,{children:a.jsx("pre",{children:e.resource.outcomeDesc})})})}function VQ(e){return a.jsx(Xs,{resource:e.resource,padding:!0,popupMenuItems:e.popupMenuItems,children:a.jsx(Fb,{value:e.resource})})}function FQ(e){if(e.lengthComputable){const t=100*e.loaded/e.total;return`Uploaded: ${hy(e.loaded)} / ${hy(e.total)} ${t.toFixed(2)}%`}return`Uploaded: ${hy(e.loaded)}`}function hy(e){if(e===0)return"0.00 B";const t=Math.floor(Math.log(e)/Math.log(1024));return(e/Math.pow(1024,t)).toFixed(2)+" "+" KMGTP".charAt(t)+"B"}function qQ(e){const{resource:t,...n}=e;return a.jsx(Sm,{value:t,loadTimelineResources:async(r,o,s)=>{const c=`${o}/${s}`;return Promise.allSettled([r.readHistory(o,s),r.search("Task",{_filter:`based-on eq ${c} or focus eq ${c} or subject eq ${c}`,_count:100})])},...n})}function HQ(e){const{encounter:t,...n}=e;return a.jsx(Sm,{value:t,loadTimelineResources:async(r,o,s)=>Promise.allSettled([r.readHistory("Encounter",s),r.search("Communication","encounter=Encounter/"+s),r.search("Media","encounter=Encounter/"+s)]),createCommunication:(r,o,s)=>({resourceType:"Communication",status:"completed",encounter:qt(r),subject:r.subject,sender:qt(o),sent:new Date().toISOString(),payload:[{contentString:s}]}),createMedia:(r,o,s)=>({resourceType:"Media",status:"completed",encounter:qt(r),subject:r.subject,operator:qt(o),issued:new Date().toISOString(),content:s}),...n})}function GQ(e){let t;try{t=sB(e.path,e.resource)}catch(n){return console.warn("FhirPathDisplay:",n),null}if(t.length>1)throw new Error(`Component "path" for "FhirPathDisplay" must resolve to a single element. Received ${t.length} elements [${JSON.stringify(t,null,2)}]`);return a.jsx($i,{value:t[0]||"",propertyType:e.propertyType})}function WQ(e){return a.jsxs(In,{title:"Export",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:e.onCancel,children:[a.jsxs(ce,{display:"flex",style:{justifyContent:"space-between"},children:[e.exportCsv&&a.jsx(hT,{text:"CSV",exportLogic:e.exportCsv,onCancel:e.onCancel}),e.exportTransactionBundle&&a.jsx(hT,{text:"Transaction Bundle",exportLogic:e.exportTransactionBundle,onCancel:e.onCancel})]}),a.jsx(_e,{style:{marginTop:"10px",marginLeft:"2px"},children:"Limited to 1000 records"})]})}function hT(e){return a.jsx(ke,{onClick:()=>{e.exportLogic(),e.onCancel()},children:`Export as ${e.text}`})}const QQ={string:[ue.EQUALS,ue.NOT,ue.CONTAINS,ue.EXACT],fulltext:[ue.EQUALS,ue.NOT,ue.CONTAINS,ue.EXACT],token:[ue.EQUALS,ue.NOT],reference:[ue.EQUALS,ue.NOT],numeric:[ue.EQUALS,ue.NOT_EQUALS,ue.GREATER_THAN,ue.LESS_THAN,ue.GREATER_THAN_OR_EQUALS,ue.LESS_THAN_OR_EQUALS],quantity:[ue.EQUALS,ue.NOT_EQUALS,ue.GREATER_THAN,ue.LESS_THAN,ue.GREATER_THAN_OR_EQUALS,ue.LESS_THAN_OR_EQUALS],date:[ue.EQUALS,ue.NOT_EQUALS,ue.GREATER_THAN,ue.LESS_THAN,ue.GREATER_THAN_OR_EQUALS,ue.LESS_THAN_OR_EQUALS,ue.STARTS_AFTER,ue.ENDS_BEFORE,ue.APPROXIMATELY],datetime:[ue.EQUALS,ue.NOT_EQUALS,ue.GREATER_THAN,ue.LESS_THAN,ue.GREATER_THAN_OR_EQUALS,ue.LESS_THAN_OR_EQUALS,ue.STARTS_AFTER,ue.ENDS_BEFORE,ue.APPROXIMATELY],uri:[ue.EQUALS,ue.NOT,ue.ABOVE,ue.BELOW]},YQ={eq:"equals",ne:"not equals",gt:"greater than",lt:"less than",ge:"greater than or equals",le:"less than or equals",sa:"starts after",eb:"ends before",ap:"approximately",sw:"starts with",contains:"contains",exact:"exact",text:"text",not:"not",above:"above",below:"below",in:"in","not-in":"not in","of-type":"of type",missing:"missing",present:"present",identifier:"identifier",iterate:"iterate"};function Hb(e,t){return{...e,filters:t,offset:0,name:void 0}}function nP(e,t){return Hb(e,(e.filters??[]).filter(n=>n.code!==t))}function wm(e,t,n,r,o){const s=[];return e.filters&&s.push(...e.filters),s.push({code:t,operator:n,value:r??""}),Hb(e,s)}function KQ(e,t){if(!e.filters)return e;const n=[...e.filters];return n.splice(t,1),{...e,filters:n,name:void 0}}function XQ(e,t){return Gb(e,t,-1)}function ZQ(e,t){return Gb(e,t,0)}function JQ(e,t){return Gb(e,t,1)}function Gb(e,t,n){const r=new Date;r.setDate(r.getDate()+n),r.setHours(0,0,0,0);const o=new Date(r.getTime());return o.setDate(o.getDate()+1),o.setTime(o.getTime()-1),jm(e,t,r,o)}function eY(e,t){const n=new Date,r=new Date(n.getTime()+1440*60*1e3);return jm(e,t,n,r)}function tY(e,t){return Wb(e,t,-1)}function nY(e,t){return Wb(e,t,0)}function rY(e,t){return Wb(e,t,1)}function Wb(e,t,n){const r=new Date;r.setMonth(r.getMonth()+n),r.setDate(1),r.setHours(0,0,0,0);const o=new Date(r.getTime());return o.setMonth(o.getMonth()+1),o.setDate(1),o.setHours(0,0,0,0),o.setTime(o.getTime()-1),jm(e,t,r,o)}function iY(e,t){const n=new Date;return n.setMonth(0),n.setDate(1),n.setHours(0,0,0,0),jm(e,t,n,new Date)}function jm(e,t,n,r){return e=nP(e,t),e=pT(e,t,ue.GREATER_THAN_OR_EQUALS,n),e=pT(e,t,ue.LESS_THAN_OR_EQUALS,r),e}function pT(e,t,n,r){return wm(e,t,n,r.toISOString())}function mT(e,t,n=!0){return wm(e,t,ue.MISSING,n.toString())}function oY(e,t){return e.offset===t?e:{...e,offset:t,name:void 0}}function aY(e,t){const n=e.count??sm,r=(t-1)*n;return oY(e,r)}function sY(e,t,n){return t===lY(e)&&n!==void 0&&n===cY(e)?e:{...e,sortRules:[{code:t,descending:!!n}],name:void 0}}function lY(e){const t=e.sortRules;if(!t||t.length===0)return;const n=t[0].code;return n.startsWith("-")?n.substr(1):n}function cY(e){const t=e.sortRules;return!t||t.length===0?!1:!!t[0].descending}function uY(e){return QQ[e.type]}function rP(e){return YQ[e]??""}function Zs(e){let t=e;return t.includes(".")&&(t=t.split(".").pop()),t==="versionId"?"Version ID":(t=t.replace("[x]",""),t=t.replace(/([A-Z])/g," $1"),t=t.replace(/[-_]/g," "),t=t.replace(/\s+/g," "),t=t.trim(),t.toLowerCase()==="id"?"ID":t.split(/\s/).map(Ln).join(" "))}function dY(e,t){const n=t.name;return n==="id"?a.jsx(vt,{to:`/${e.resourceType}/${e.id}`,children:e.id}):n==="meta.versionId"?e.meta?.versionId:n==="_lastUpdated"?lr(e.meta?.lastUpdated):t.elementDefinition&&`${e.resourceType}.${t.name}`===t.elementDefinition.path?fY(e,t.elementDefinition):t.searchParams&&t.searchParams.length===1&&t.name===t.searchParams[0].code?hY(e,t.searchParams[0]):null}function fY(e,t){const n=t.path?.split(".")?.pop()?.replaceAll("[x]","")??"",[r,o]=ym({type:e.resourceType,value:e},n);return r?a.jsx($i,{path:t.path,property:t,propertyType:o,value:r,maxWidth:200,ignoreMissingValues:!0,link:!1}):null}function hY(e,t){const n=Za(t.expression,[{type:e.resourceType,value:e}]);return!n||n.length===0?null:a.jsx(a.Fragment,{children:n.map((r,o)=>a.jsx($i,{propertyType:r.type,value:r.value,maxWidth:200,ignoreMissingValues:!0,link:!1},`${o}-${n.length}`))})}function pY(e){const t=v.useRef(!1),[n,r]=v.useState({search:JSON.parse(Ii(e.search))}),[o,s]=v.useState(!1);v.useEffect(()=>{r({search:e.search})},[e.search]);const c=v.useMemo(()=>{if(!e.visible)return[];const f=e.search.resourceType,p=xD(f),m=fb(f);return Ec(mY(p,m)).map(g=>({value:g,label:Zs(g)}))},[e.visible,e.search.resourceType]);function d(f){r({search:{...n.search,fields:f}})}return a.jsx(In,{title:"Fields",closeButtonProps:{"aria-label":"Close"},opened:e.visible,onClose:()=>{e.onCancel()},size:"auto",withOverlay:!0,closeOnClickOutside:!1,overlayProps:{onMouseDownCapture:()=>{t.current=o},onClick:()=>{t.current||e.onCancel(),t.current=!1},children:a.jsx("div",{"data-testid":"overlay-child"})},children:a.jsxs($e,{children:[a.jsx(Wp,{style:{width:550},placeholder:"Select fields to display",data:c,value:n.search.fields??[],onChange:d,onDropdownOpen:()=>s(!0),onDropdownClose:()=>s(!1),maxDropdownHeight:"250px",clearButtonProps:{"aria-label":"Clear selection"},clearable:!0,searchable:!0}),a.jsx(ge,{justify:"flex-end",children:a.jsx(ke,{onClick:()=>e.onOk(n.search),children:"OK"})})]})})}function mY(e,t){const n=[],r=new Set,o=new Set;for(const s of Object.keys(e.elements))n.push(s),r.add(s.toLowerCase()),o.add(Zs(s));if(t)for(const s of Object.keys(t)){const c=Zs(s);!r.has(s)&&!o.has(c)&&(n.push(s),r.add(s),o.add(c))}return n}function iP(e){const t=dm(e.resourceType,e.searchParam),n=e.name??"filter-value";switch(t.type){case ir.REFERENCE:return a.jsx(Qa,{name:n,defaultValue:e.defaultValue?{reference:e.defaultValue}:void 0,targetTypes:e.searchParam.target,autoFocus:e.autoFocus,onChange:r=>{r?e.onChange(r.reference):e.onChange("")}});case ir.BOOLEAN:return a.jsx(Dn,{name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultChecked:e.defaultValue==="true",autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.checked.toString())});case ir.DATE:return a.jsx(Ue,{type:"date",name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value)});case ir.DATETIME:return a.jsx(ao,{name:n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:e.onChange});case ir.NUMBER:return a.jsx(Ue,{type:"number",name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value)});case ir.QUANTITY:return a.jsx(Ks,{name:n,path:"",defaultValue:gY(e.defaultValue),autoFocus:e.autoFocus,onChange:r=>{r?e.onChange(`${r.value}`):e.onChange("")}});default:return a.jsx(Ue,{name:n,"data-autofocus":e.autoFocus,"data-testid":n,defaultValue:e.defaultValue,autoFocus:e.autoFocus,onChange:r=>e.onChange(r.currentTarget.value),placeholder:"Search value"})}}function gY(e){if(e){const[t,n,r]=e.split("|");if(t)return{value:parseFloat(t),system:n,unit:r}}}function vY(e){const[t,n]=v.useState(Kr(e.search)),r=v.useRef(t);r.current=t,v.useEffect(()=>{n(Kr(e.search))},[e.search]);function o(f){n(wm(r.current,f.code,f.operator,f.value))}const s=e.search.resourceType,c=fb(s)??{},d=t.filters||[];return a.jsx(In,{title:"Filters",closeButtonProps:{"aria-label":"Close"},size:900,opened:e.visible,onClose:e.onCancel,children:a.jsxs(ut,{onSubmit:()=>e.onOk(r.current),children:[a.jsxs("div",{children:[a.jsxs("table",{children:[a.jsxs("colgroup",{children:[a.jsx("col",{style:{width:200}}),a.jsx("col",{style:{width:200}}),a.jsx("col",{style:{width:380}}),a.jsx("col",{style:{width:40}})]}),a.jsx("thead",{children:a.jsxs("tr",{children:[a.jsx("th",{children:"Field"}),a.jsx("th",{children:"Operation"}),a.jsx("th",{children:"Value"}),a.jsx("th",{})]})}),a.jsx("tbody",{children:d.map((f,p)=>a.jsx(yY,{id:`filter-${p}-row`,resourceType:s,searchParams:c,value:f,onChange:m=>{const g=[...d];g[p]=m,n(Hb(r.current,g))},onDelete:()=>n(KQ(r.current,p))},`filter-${p}-row`))})]}),a.jsx(Ub,{propertyDisplayName:"Filter",onClick:()=>o({})})]}),a.jsx(ge,{justify:"flex-end",mt:"xl",children:a.jsx(ur,{children:"OK"})})]})})}function yY(e){const t=e.value,n=v.useRef(t);n.current=t;function r(f){n.current.code=f,n.current.operator=ue.EQUALS,n.current.value="",e.onChange(n.current)}function o(f){n.current.operator=f,n.current.value="",e.onChange(n.current)}function s(f){n.current.value=f,e.onChange(n.current)}const c=e.searchParams[t.code],d=c&&uY(c);return a.jsxs("tr",{children:[a.jsx("td",{children:a.jsx(sn,{"data-testid":`${e.id}-filter-field`,defaultValue:e.value.code,onChange:f=>r(f.currentTarget.value),data:["",...Object.keys(e.searchParams).map(f=>({value:f,label:Zs(f)}))]})}),a.jsx("td",{children:d&&a.jsx(sn,{"data-testid":`${e.id}-filter-operation`,defaultValue:t.operator,onChange:f=>o(f.currentTarget.value),data:["",...d.map(f=>({value:f,label:rP(f)}))]},`${e.id}-filter-value-${e.value.code}`)}),a.jsx("td",{children:c&&t.operator&&a.jsx(iP,{name:`${e.id}-filter-value`,resourceType:e.resourceType,searchParam:c,defaultValue:t.value,onChange:s},`${e.id}-filter-value-${e.value.code}-${e.value.operator}`)}),a.jsx("td",{children:e.onDelete&&a.jsx(bn,{variant:"outline",color:"red",radius:"xl","aria-label":"Delete filter",onClick:e.onDelete,children:a.jsx(Ys,{style:{width:"70%",height:"70%"},stroke:1.5})})})]})}function xY(e){const[t,n]=v.useState(e.defaultValue??"");if(!e.searchParam||!e.filter)return null;function r(){e.onOk({...e.filter,value:t})}return a.jsx(In,{title:e.title,size:"xl",opened:e.visible,onClose:e.onCancel,children:a.jsx(ut,{onSubmit:r,children:a.jsxs(ar,{children:[a.jsx(ar.Col,{span:10,children:a.jsx(iP,{resourceType:e.resourceType,searchParam:e.searchParam,defaultValue:t,autoFocus:!0,onChange:n})}),a.jsx(ar.Col,{span:2,children:a.jsx(ke,{onClick:r,fullWidth:!0,children:"OK"})})]})})})}function bY(e){const{resourceType:t,filter:n}=e,r=uo.types[t].searchParams?.[n.code];if(r){if(r.type==="reference"&&(n.operator===ue.EQUALS||n.operator===ue.NOT_EQUALS))return a.jsx(dl,{value:{reference:n.value}});const o=dm(t,r);if(n.code==="_lastUpdated"||o.type===ir.DATETIME)return a.jsx(a.Fragment,{children:lr(n.value)})}return a.jsx(a.Fragment,{children:n.value})}function SY(e){if(!e.searchParams)return null;function t(s,c){o(sY(e.search,s.code,c))}function n(s){o(nP(e.search,s.code))}function r(s,c){e.onPrompt(s,{code:s.code,operator:c,value:""})}function o(s){e.onChange(s)}return e.searchParams.length===1?a.jsx(wY,{search:e.search,searchParam:e.searchParams[0],onSort:t,onPrompt:r,onChange:o,onClear:n}):a.jsx(Ce.Dropdown,{children:e.searchParams.map(s=>a.jsx(Ce.Item,{children:Zs(s.code)},s.code))})}function wY(e){switch(e.searchParam.type){case"date":return a.jsx(jY,{...e});case"number":case"quantity":return a.jsx(CY,{...e});case"reference":return a.jsx(EY,{...e});case"string":return a.jsx(TY,{...e});case"token":case"uri":return a.jsx(RY,{...e});default:return a.jsxs(a.Fragment,{children:["Unknown search param type: ",e.searchParam.type]})}}function jY(e){const{searchParam:t}=e,n=t.code;return a.jsxs(Ce.Dropdown,{children:[a.jsx(Ce.Item,{leftSection:a.jsx(Ab,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort Oldest to Newest"}),a.jsx(Ce.Item,{leftSection:a.jsx(Pb,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Newest to Oldest"}),a.jsx(Ce.Divider,{}),a.jsx(Ce.Item,{leftSection:a.jsx(zd,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Equals..."}),a.jsx(Ce.Item,{leftSection:a.jsx($d,{size:14}),onClick:()=>e.onPrompt(t,ue.NOT_EQUALS),children:"Does not equal..."}),a.jsx(Ce.Divider,{}),a.jsx(Ce.Item,{leftSection:a.jsx(xA,{size:14}),onClick:()=>e.onPrompt(t,ue.ENDS_BEFORE),children:"Before..."}),a.jsx(Ce.Item,{leftSection:a.jsx(yA,{size:14}),onClick:()=>e.onPrompt(t,ue.STARTS_AFTER),children:"After..."}),a.jsx(Ce.Item,{leftSection:a.jsx(GF,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Between..."}),a.jsx(Ce.Divider,{}),a.jsx(Ce.Item,{leftSection:a.jsx($a,{size:14}),onClick:()=>e.onChange(JQ(e.search,n)),children:"Tomorrow"}),a.jsx(Ce.Item,{leftSection:a.jsx($a,{size:14}),onClick:()=>e.onChange(ZQ(e.search,n)),children:"Today"}),a.jsx(Ce.Item,{leftSection:a.jsx($a,{size:14}),onClick:()=>e.onChange(XQ(e.search,n)),children:"Yesterday"}),a.jsx(Ce.Item,{leftSection:a.jsx($a,{size:14}),onClick:()=>e.onChange(eY(e.search,n)),children:"Next 24 Hours"}),a.jsx(Ce.Divider,{}),a.jsx(Ce.Item,{leftSection:a.jsx($a,{size:14}),onClick:()=>e.onChange(rY(e.search,n)),children:"Next Month"}),a.jsx(Ce.Item,{leftSection:a.jsx($a,{size:14}),onClick:()=>e.onChange(nY(e.search,n)),children:"This Month"}),a.jsx(Ce.Item,{leftSection:a.jsx($a,{size:14}),onClick:()=>e.onChange(tY(e.search,n)),children:"Last Month"}),a.jsx(Ce.Divider,{}),a.jsx(Ce.Item,{leftSection:a.jsx($a,{size:14}),onClick:()=>e.onChange(iY(e.search,n)),children:"Year to date"}),a.jsx(Vd,{...e})]})}function CY(e){const{searchParam:t}=e;return a.jsxs(Ce.Dropdown,{children:[a.jsx(Ce.Item,{leftSection:a.jsx(Ab,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort Smallest to Largest"}),a.jsx(Ce.Item,{leftSection:a.jsx(Pb,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Largest to Smallest"}),a.jsx(Ce.Divider,{}),a.jsx(Ce.Item,{leftSection:a.jsx(zd,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Equals..."}),a.jsx(Ce.Item,{leftSection:a.jsx($d,{size:14}),onClick:()=>e.onPrompt(t,ue.NOT_EQUALS),children:"Does not equal..."}),a.jsx(Ce.Divider,{}),a.jsx(Ce.Item,{leftSection:a.jsx(yA,{size:14}),onClick:()=>e.onPrompt(t,ue.GREATER_THAN),children:"Greater than..."}),a.jsx(Ce.Item,{leftSection:a.jsx(rx,{size:14}),onClick:()=>e.onPrompt(t,ue.GREATER_THAN_OR_EQUALS),children:"Greater than or equal to..."}),a.jsx(Ce.Item,{leftSection:a.jsx(xA,{size:14}),onClick:()=>e.onPrompt(t,ue.LESS_THAN),children:"Less than..."}),a.jsx(Ce.Item,{leftSection:a.jsx(rx,{size:14}),onClick:()=>e.onPrompt(t,ue.LESS_THAN_OR_EQUALS),children:"Less than or equal to..."}),a.jsx(Vd,{...e})]})}function EY(e){const{searchParam:t}=e;return a.jsxs(Ce.Dropdown,{children:[a.jsx(Ce.Item,{leftSection:a.jsx(zd,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Equals..."}),a.jsx(Ce.Item,{leftSection:a.jsx($d,{size:14}),onClick:()=>e.onPrompt(t,ue.NOT),children:"Does not equal..."}),a.jsx(Vd,{...e})]})}function TY(e){const{searchParam:t}=e;return a.jsxs(Ce.Dropdown,{children:[a.jsx(Ce.Item,{leftSection:a.jsx(Ab,{size:14}),onClick:()=>e.onSort(t,!1),children:"Sort A to Z"}),a.jsx(Ce.Item,{leftSection:a.jsx(Pb,{size:14}),onClick:()=>e.onSort(t,!0),children:"Sort Z to A"}),a.jsx(Ce.Divider,{}),a.jsx(Ce.Item,{leftSection:a.jsx(zd,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Equals..."}),a.jsx(Ce.Item,{leftSection:a.jsx($d,{size:14}),onClick:()=>e.onPrompt(t,ue.NOT),children:"Does not equal..."}),a.jsx(Ce.Divider,{}),a.jsx(Ce.Item,{leftSection:a.jsx(ZF,{size:14}),onClick:()=>e.onPrompt(t,ue.CONTAINS),children:"Contains..."}),a.jsx(Ce.Item,{leftSection:a.jsx(KF,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Does not contain..."}),a.jsx(Vd,{...e})]})}function RY(e){const{searchParam:t}=e;return a.jsxs(Ce.Dropdown,{children:[a.jsx(Ce.Item,{leftSection:a.jsx(zd,{size:14}),onClick:()=>e.onPrompt(t,ue.EQUALS),children:"Equals..."}),a.jsx(Ce.Item,{leftSection:a.jsx($d,{size:14}),onClick:()=>e.onPrompt(t,ue.NOT),children:"Does not equal..."}),a.jsx(Vd,{...e})]})}function Vd(e){const{searchParam:t}=e,n=t.code;return a.jsxs(a.Fragment,{children:[a.jsx(Ce.Divider,{}),a.jsx(Ce.Item,{leftSection:a.jsx(VF,{size:14}),onClick:()=>e.onChange(mT(e.search,n)),children:"Missing"}),a.jsx(Ce.Item,{leftSection:a.jsx(UF,{size:14}),onClick:()=>e.onChange(mT(e.search,n,!1)),children:"Not missing"}),a.jsx(Ce.Divider,{}),a.jsx(Ce.Item,{leftSection:a.jsx(Ys,{size:14}),onClick:()=>e.onClear(t),children:"Clear filters"})]})}function oP(e){switch(e){case"next":return{"aria-label":"Next page"};case"previous":return{"aria-label":"Previous page"};case"first":return{"aria-label":"First page"};case"last":return{"aria-label":"Last page"};default:return{}}}const _Y="_root_vlout_1",DY="_table_vlout_8",AY="_tr_vlout_12",PY="_control_vlout_22",kY="_icon_vlout_31",Vu={root:_Y,table:DY,tr:AY,control:PY,icon:kY};function NY(e){const t=e.resourceType,n=[];for(const r of e.fields||["id","_lastUpdated"])n.push(OY(t,r));return n}function OY(e,t){if(t==="_lastUpdated")return{name:"_lastUpdated",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_lastUpdated",name:"_lastUpdated",type:"date",expression:"Resource.meta.lastUpdated"}]};if(t==="meta.versionId")return{name:"meta.versionId",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_versionId",name:"_versionId",type:"token",expression:"Resource.meta.versionId"}]};const n=is(e,t),r=PU(e,t.toLowerCase());if(n&&r)return{name:t,elementDefinition:n,searchParams:[r]};if(n){const o=fb(e);let s;if(o){const c=new RegExp(`${e}\\.${t.replaceAll("[x]","")}([^\\w-]|$)`);s=Object.values(o).filter(d=>!!d.expression&&c.test(d?.expression)),s.length===0&&(s=void 0)}return{name:t,elementDefinition:n,searchParams:s}}if(r){const o=dm(e,r);return{name:t,elementDefinition:o.elementDefinitions?.[0],searchParams:[r]}}return{name:t}}class MY extends Event{constructor(t){super("change"),this.definition=t}}class LY extends Event{constructor(t){super("load"),this.response=t}}class ap extends Event{constructor(t,n){super("click"),this.resource=t,this.browserEvent=n}}function qc(e){const t=De(),[n,r]=v.useState(),{search:o,onLoad:s}=e,[c,d]=v.useState(o);co(o,c)||d(o);const[f,p]=v.useState({selected:{},fieldEditorVisible:!1,filterEditorVisible:!1,exportDialogVisible:!1,filterDialogVisible:!1}),m=v.useRef(f);m.current=f;const g=c.total??"accurate",x=v.useCallback(H=>{r(void 0),t.requestSchema(c.resourceType).then(()=>t.search(c.resourceType,Wa({...c,total:g,fields:void 0}),H)).then(W=>{p({...m.current,searchResponse:W}),s&&s(new LY(W))}).catch(W=>{p({...m.current,searchResponse:void 0}),r(Ht(W))})},[t,c,g,s]),b=v.useCallback(()=>{p({...m.current,searchResponse:void 0}),x({cache:"reload"})},[x]);v.useEffect(()=>{x()},[x]);function S(H,W){H.stopPropagation();const I=H.target.checked,$={...m.current.selected};I?$[W]=!0:delete $[W],p({...m.current,selected:$})}function j(H){H.stopPropagation();const M=H.target.checked,I={},$=m.current.searchResponse;M&&$?.entry&&$.entry.forEach(q=>{q.resource?.id&&(I[q.resource.id]=!0)}),p({...m.current,selected:I})}function C(){const H=m.current;if(!H.searchResponse?.entry||H.searchResponse.entry.length===0)return!1;for(const W of H.searchResponse.entry)if(W.resource?.id&&!H.selected[W.resource.id])return!1;return!0}function R(H){e.onChange&&e.onChange(new MY(H))}function E(H,W){if(CA(H.target)||H.button===2)return;dn(H);const M=jA(H);!M&&e.onClick&&e.onClick(new ap(W,H)),M&&e.onAuxClick&&e.onAuxClick(new ap(W,H))}function T(){return!!(e.onExport??e.onExportCsv??e.onExportTransactionBundle)}if(n)return a.jsx(dr,{outcome:n});if(!yD(c.resourceType))return a.jsx(Jn,{style:{width:"100%",height:"100%"},children:a.jsx(Nr,{})});const _=e.checkboxesEnabled,P=NY(c),A=c.resourceType,k=f.searchResponse,z=k?.entry?.map(H=>H.resource),B="subtle",Z="gray",K=16,Y=window.innerWidth<768;return a.jsxs("div",{className:Vu.root,"data-testid":"search-control",children:[!e.hideToolbar&&a.jsxs(ge,{justify:"space-between",mb:"xl",children:[a.jsxs(ge,{gap:2,children:[a.jsx(ke,{size:"compact-md",variant:B,color:Z,leftSection:a.jsx(fq,{size:K}),onClick:()=>p({...m.current,fieldEditorVisible:!0,dialogOpenTime:Date.now()}),children:"Fields"}),a.jsx(ke,{size:"compact-md",variant:B,color:Z,leftSection:a.jsx(Nq,{size:K}),onClick:()=>p({...m.current,filterEditorVisible:!0,dialogOpenTime:Date.now()}),children:"Filters"}),e.onNew&&a.jsx(ke,{size:"compact-md",variant:B,color:Z,leftSection:a.jsx(Pq,{size:K}),onClick:e.onNew,children:"New..."}),!Y&&T()&&a.jsx(ke,{size:"compact-md",variant:B,color:Z,leftSection:a.jsx(DH,{size:K}),onClick:e.onExport?e.onExport:()=>p({...m.current,exportDialogVisible:!0,dialogOpenTime:Date.now()}),children:"Export..."}),!Y&&e.onDelete&&a.jsx(ke,{size:"compact-md",variant:B,color:Z,leftSection:a.jsx(mm,{size:K}),onClick:()=>e.onDelete(Object.keys(f.selected)),children:"Delete..."}),!Y&&e.onBulk&&a.jsx(ke,{size:"compact-md",variant:B,color:Z,leftSection:a.jsx(qF,{size:K}),onClick:()=>e.onBulk(Object.keys(f.selected)),children:"Bulk..."})]}),a.jsxs(ge,{gap:2,children:[k&&a.jsxs(_e,{size:"xs",c:"dimmed","data-testid":"count-display",children:[aP(c,k).toLocaleString(),"-",BY(c,k).toLocaleString(),k.total!==void 0&&` of ${c.total==="estimate"?"~":""}${k.total?.toLocaleString()}`]}),a.jsx(bn,{variant:B,color:Z,title:"Refresh",onClick:b,children:a.jsx(SA,{size:K})})]})]}),a.jsxs(de,{className:Vu.table,children:[a.jsxs(de.Thead,{children:[a.jsxs(de.Tr,{children:[_&&a.jsx(de.Th,{children:a.jsx("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:C(),onChange:H=>j(H)})}),P.map(H=>a.jsx(de.Th,{children:a.jsxs(Ce,{shadow:"md",width:240,position:"bottom-end",children:[a.jsx(Ce.Target,{children:a.jsx(er,{className:Vu.control,p:2,children:a.jsxs(ge,{justify:"space-between",wrap:"nowrap",children:[a.jsx(_e,{fw:500,children:Zs(H.name)}),a.jsx(Jn,{className:Vu.icon,children:a.jsx(NF,{size:14,stroke:1.5})})]})})}),a.jsx(SY,{search:c,searchParams:H.searchParams,onPrompt:(W,M)=>{p({...m.current,filterDialogVisible:!0,filterDialogSearchParam:W,filterDialogFilter:M,dialogOpenTime:Date.now()})},onChange:W=>{R(W)}})]})},H.name))]}),!e.hideFilters&&a.jsxs(de.Tr,{children:[_&&a.jsx(de.Th,{}),P.map(H=>a.jsx(de.Th,{children:H.searchParams&&a.jsx($Y,{resourceType:A,searchParams:H.searchParams,filters:c.filters})},H.name))]})]}),a.jsx(de.Tbody,{children:z?.map(H=>H&&a.jsxs(de.Tr,{className:Vu.tr,"data-testid":"search-control-row",onClick:W=>E(W,H),onAuxClick:W=>E(W,H),children:[_&&a.jsx(de.Td,{children:a.jsx("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${H.id}`,checked:!!f.selected[H.id],onChange:W=>S(W,H.id)})}),P.map(W=>a.jsx(de.Td,{children:dY(H,W)},W.name))]},H.id))})]}),!z?.length&&a.jsx(Vc,{children:a.jsx(Jn,{style:{height:150},children:a.jsx(_e,{size:"xl",c:"dimmed",children:"No results"})})}),k&&a.jsx(Jn,{m:"md",p:"md",children:a.jsx(ji,{value:zY(c),total:UY(c,k),onChange:H=>R(aY(c,H)),getControlProps:oP})}),a.jsx(pY,{search:c,visible:m.current.fieldEditorVisible,onOk:H=>{R(H),p({...m.current,fieldEditorVisible:!1})},onCancel:()=>{p({...m.current,fieldEditorVisible:!1})}},`search-field-editor-${f.dialogOpenTime}`),a.jsx(vY,{search:c,visible:m.current.filterEditorVisible,onOk:H=>{R(H),p({...m.current,filterEditorVisible:!1})},onCancel:()=>{p({...m.current,filterEditorVisible:!1})}},`search-filter-editor-${f.dialogOpenTime}`),a.jsx(WQ,{visible:m.current.exportDialogVisible,exportCsv:e.onExportCsv,exportTransactionBundle:e.onExportTransactionBundle,onCancel:()=>{p({...m.current,exportDialogVisible:!1})}},`search-export-dialog-${f.dialogOpenTime}`),a.jsx(xY,{visible:m.current.filterDialogVisible,title:f.filterDialogSearchParam?.code?Zs(f.filterDialogSearchParam.code):"",resourceType:A,searchParam:f.filterDialogSearchParam,filter:f.filterDialogFilter,defaultValue:"",onOk:H=>{R(wm(c,H.code,H.operator,H.value)),p({...m.current,filterDialogVisible:!1})},onCancel:()=>{p({...m.current,filterDialogVisible:!1})}},`search-filter-dialog-${f.dialogOpenTime}`)]})}const IY=qc;function $Y(e){const t=(e.filters??[]).filter(n=>e.searchParams.find(r=>r.code===n.code));return t.length===0?a.jsx("span",{children:"no filters"}):a.jsx(a.Fragment,{children:t.map(n=>a.jsxs("div",{children:[rP(n.operator)," ",a.jsx(bY,{resourceType:e.resourceType,filter:n})]},`filter-${n.code}-${n.operator}-${n.value}`))})}function zY(e){return Math.floor((e.offset??0)/(e.count??sm))+1}function UY(e,t){const n=e.count??sm,r=sP(e,t);return Math.ceil(r/n)}function aP(e,t){return Math.min(sP(e,t),(e.offset??0)+1)}function BY(e,t){return Math.max(aP(e,t)+(t.entry?.length??0)-1,0)}function sP(e,t){let n=t.total;return n===void 0&&(n=(e.offset??0)+(t.entry?.length??0)+(t.link?.some(r=>r.relation==="next")?1:0)),n}function VY(e){const t=De(),[n,r]=v.useState(!1),[o,s]=v.useState(),{query:c,fields:d}=e,[f,p]=v.useState(),[m,g]=v.useState({}),x=v.useRef(f);x.current=f;const b=v.useRef({});b.current=m,v.useEffect(()=>{s(void 0),t.graphql(c).then(p).catch(T=>s(Ht(T)))},[t,c]);function S(T,_){T.stopPropagation();const A=T.target.checked,k={...b.current};A?k[_]=!0:delete k[_],g(k)}function j(T){T.stopPropagation();const P=T.target.checked,A={},k=x.current?.data.ResourceList;P&&k&&k.forEach(L=>{L.id&&(A[L.id]=!0)}),g(A)}function C(){const T=x.current?.data.ResourceList;if(!T||T.length===0)return!1;for(const _ of T)if(_.id&&!b.current[_.id])return!1;return!0}function R(T,_){CA(T.target)||(dn(T),T.button!==1&&e.onClick&&e.onClick(new ap(_,T)),T.button===1&&e.onAuxClick&&e.onAuxClick(new ap(_,T)))}if(v.useEffect(()=>{t.requestSchema(e.resourceType).then(()=>r(!0)).catch(console.log)},[t,e.resourceType]),!n)return a.jsx(Nr,{});const E=e.checkboxesEnabled;return a.jsxs("div",{onContextMenu:T=>dn(T),"data-testid":"search-control",children:[a.jsxs(de,{children:[a.jsx(de.Thead,{children:a.jsxs(de.Tr,{children:[E&&a.jsx(de.Th,{children:a.jsx("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:C(),onChange:T=>j(T)})}),d.map(T=>a.jsx(de.Th,{children:T.name},T.name))]})}),a.jsx(de.Tbody,{children:f?.data.ResourceList.map(T=>T&&a.jsxs(de.Tr,{"data-testid":"search-control-row",onClick:_=>R(_,T),onAuxClick:_=>R(_,T),children:[E&&a.jsx(de.Td,{children:a.jsx("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${T.id}`,checked:!!m[T.id],onChange:_=>S(_,T.id)})}),d.map(_=>a.jsx(de.Td,{children:a.jsx(GQ,{propertyType:_.propertyType,path:_.fhirPath,resource:T})},_.name))]},T.id))})]}),f?.data.ResourceList.length===0&&a.jsx("div",{"data-testid":"empty-search",children:"No results"}),o&&a.jsx("div",{"data-testid":"search-error",children:a.jsx("pre",{style:{textAlign:"left"},children:JSON.stringify(o,void 0,2)})}),e.onBulk&&a.jsx(ke,{onClick:()=>e.onBulk(Object.keys(b.current)),children:"Bulk..."})]})}const FY=v.memo(VY),qY="_root_1fbwr_1",HY="_entry_1fbwr_8",GY="_key_1fbwr_13",WY="_value_1fbwr_20",Cm={root:qY,entry:HY,key:GY,value:WY};function ht(e){return a.jsx(Zr,{children:a.jsx("div",{className:Cm.root,children:e.children})})}ht.Entry=function(t){return a.jsx("div",{className:Cm.entry,children:t.children})};ht.Key=function(t){return a.jsx("div",{className:Cm.key,children:t.children})};ht.Value=function(t){return a.jsx("div",{className:Cm.value,children:t.children})};function QY(e){const{group:t}=e;return a.jsx(yr,{withBorder:!0,radius:"md",p:"xs",display:"flex",style:{alignItems:"center",justifyContent:"center"},children:a.jsxs(ge,{children:[t.measureScore&&a.jsx(XY,{group:t}),!t.measureScore&&a.jsx(KY,{group:t})]})})}function YY(e){const{measure:t}=e;return a.jsxs(a.Fragment,{children:[a.jsx(_e,{fz:"md",fw:500,mb:8,children:t.title}),a.jsx(_e,{fz:"xs",c:"dimmed",mb:8,children:t.subtitle})]})}function KY(e){const{group:t}=e,n=t.population,r=n?.find(f=>Xa(f.code)==="numerator"),o=n?.find(f=>Xa(f.code)==="denominator"),s=r?.count,c=o?.count;if(c===0)return a.jsxs(ce,{children:[a.jsx(Oe,{order:3,children:"Not Applicable"}),a.jsx(_e,{children:`Denominator: ${c}`})]});if(s===void 0||c===void 0)return a.jsxs(ce,{children:[a.jsx(Oe,{order:3,children:"Insufficient Data"}),a.jsx(_e,{children:`Numerator: ${s}`}),a.jsx(_e,{children:`Denominator: ${c}`})]});const d=s/c*100;return a.jsx(em,{size:120,thickness:12,roundCaps:!0,sections:[{value:d,color:lP(d)}],label:a.jsx(lo,{justify:"center",children:a.jsxs(_e,{fw:700,fz:18,children:[s," / ",c]})})})}function XY(e){const{group:t}=e,n=t.measureScore?.unit??t.measureScore?.code;return a.jsx(a.Fragment,{children:n==="%"?a.jsx(em,{size:120,thickness:12,roundCaps:!0,sections:[{value:ZY(t),color:lP(t?.measureScore?.value??0)}],label:a.jsx(lo,{justify:"center",children:a.jsx(_e,{fw:700,fz:18,children:a.jsx(ud,{value:t.measureScore})})})}):a.jsx(lo,{h:120,align:"center",children:a.jsx(Oe,{order:3,children:a.jsx(ud,{value:t.measureScore})})})})}function ZY(e){const t=e.measureScore?.value,n=e.measureScore?.unit;return t?t<=1&&n==="%"?t*100:t:0}function lP(e){return e<=33?"red":e<=67?"yellow":"green"}function JY(e){const t=Gt(e.measureReport),[n]=EF("Measure",{url:t?.measure});return t?a.jsxs(ce,{children:[n&&a.jsx(YY,{measure:n}),a.jsx(tm,{cols:{base:3,sm:1},spacing:{base:"md",sm:"sm"},children:t.group?.map((r,o)=>a.jsx(QY,{group:r},r.id??o))})]}):null}const py="patient-export",my="Patient Export",eK={everything:{operation:"$everything",extension:"json",contentType:un.FHIR_JSON},summary:{operation:"$summary",extension:"json",contentType:un.FHIR_JSON},ccda:{operation:"$ccda-export",extension:"xml",contentType:un.CDA_XML},ccdaReferral:{operation:"$ccda-export",type:"referral",extension:"xml",contentType:un.CDA_XML}};function tK(e){const t=De(),{patient:n}=e,r=v.useCallback(async o=>{const s=Hs(n),c=o.format,{operation:d,type:f,contentType:p,extension:m}=eK[c],g=t.fhirUrl("Patient",s,d),x={};f&&(x.type=f),o.author&&(x.author={reference:o.author}),o.authoredOn&&(x.authoredOn=$b(o.authoredOn)),o.startDate&&(x.start=o.startDate),o.endDate&&(x.end=o.endDate),hi.show({id:py,title:my,loading:!0,message:"Exporting...",autoClose:!1,withCloseButton:!1});try{const b=await t.post(g,x,void 0,{cache:"no-cache",headers:{Accept:p}}),S=`Patient-export-${s}-${new Date().toISOString().replaceAll(":","-")}.${m}`;nK(b,S,p),hi.update({id:py,title:my,color:"green",message:"Done",icon:a.jsx(vo,{size:"1rem"}),loading:!1,autoClose:!0,withCloseButton:!0})}catch(b){hi.update({id:py,title:my,color:"red",message:Ge(b),icon:a.jsx(Ys,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})}},[t,n]);return a.jsx(ut,{onSubmit:r,children:a.jsxs($e,{children:[a.jsx(Ot,{title:"Export Format",description:"Required",withAsterisk:!0,children:a.jsx(Ad,{name:"format",data:[{label:"FHIR Everything",value:"everything"},{label:"Patient Summary",value:"summary"},{label:"C-CDA",value:"ccda"},{label:"C-CDA Referral",value:"ccdaReferral"}],fullWidth:!0})}),a.jsx(Ot,{title:"Author",description:"Optional author for composition. Default value is current user.",children:a.jsx(Qa,{name:"author",placeholder:"Author",targetTypes:["Organization","Practitioner","PractitionerRole"]})}),a.jsx(Ot,{title:"Authored On",description:"Optional date for composition authored on. Default value is current date.",children:a.jsx(ao,{name:"authoredOn",placeholder:"Authored on"})}),a.jsx(Ot,{title:"Start Date",description:"The start date of care. If no start date is provided, all records prior to the end date are in scope.",children:a.jsx(ao,{name:"startDate",placeholder:"Start date"})}),a.jsx(Ot,{title:"End Date",description:"The end date of care. If no end date is provided, all records subsequent to the start date are in scope.",children:a.jsx(ao,{name:"endDate",placeholder:"End date"})}),a.jsx(ge,{justify:"right",children:a.jsx(ur,{children:"Request Export"})})]})})}function nK(e,t,n){const r=typeof e=="string"?e:JSON.stringify(e,null,2),o=new Blob([r],{type:n}),s=window.URL.createObjectURL(o),c=document.createElement("a");document.body.appendChild(c),c.style.display="none",c.href=s,c.download=t,c.click(),window.URL.revokeObjectURL(s)}function rK(e){if(e.gender==="male")return"blue";if(e.gender==="female")return"pink"}function cP(e){const t=Gt(e.patient);return t?a.jsxs(ht,{children:[a.jsx(os,{value:t,size:"lg",color:rK(t)}),a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Name"}),a.jsx(ht.Value,{children:a.jsx(vt,{to:t,fw:500,children:t.name?a.jsx(kb,{value:t.name[0],options:{use:!1}}):"[blank]"})})]}),t.birthDate&&a.jsxs(a.Fragment,{children:[a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"DoB"}),a.jsx(ht.Value,{children:t.birthDate})]}),a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Age"}),a.jsx(ht.Value,{children:nU(t.birthDate)})]})]}),t.gender&&a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Gender"}),a.jsx(ht.Value,{children:t.gender})]}),t.address&&a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"State"}),a.jsx(ht.Value,{children:t.address[0]?.state})]}),t.identifier?.map(n=>a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:n?.system}),a.jsx(ht.Value,{children:n?.value})]},`${n?.system}-${n?.value}`))]}):null}function iK(e){const{patient:t,...n}=e,r=v.useCallback((o,s,c)=>{const d=`${s}/${c}`,f=100;return Promise.allSettled([o.readHistory("Patient",c),o.search("Communication",{subject:d,_count:f}),o.search("Device",{patient:d,_count:f}),o.search("DeviceRequest",{patient:d,_count:f}),o.search("DiagnosticReport",{subject:d,_count:f}),o.search("Media",{subject:d,_count:f}),o.search("ServiceRequest",{subject:d,_count:f}),o.search("Task",{subject:d,_count:f})])},[]);return a.jsx(Sm,{value:t,loadTimelineResources:r,createCommunication:(o,s,c)=>({resourceType:"Communication",status:"completed",subject:qt(o),sender:qt(s),sent:new Date().toISOString(),payload:[{contentString:c}]}),createMedia:(o,s,c)=>({resourceType:"Media",status:"completed",subject:qt(o),operator:qt(s),issued:new Date().toISOString(),content:c}),...n})}const oK="_section_pqpwm_1",aK="_hovering_pqpwm_7",ax={section:oK,hovering:aK};function sK(e){const t=De(),n=Gt(e.value),[r,o]=v.useState(!1),[s,c]=v.useState(),[d,f]=v.useState(),[p,m]=v.useState();function g(){f(void 0)}function x(){c(void 0)}const b=v.useRef(p);if(b.current=p,v.useEffect(()=>{t.requestSchema("PlanDefinition").then(()=>o(!0)).catch(console.log)},[t]),v.useEffect(()=>(m(fK(n??{resourceType:"PlanDefinition",status:"active"})),document.addEventListener("mouseover",g),document.addEventListener("click",x),()=>{document.removeEventListener("mouseover",g),document.removeEventListener("click",x)}),[n]),!r||!p)return null;function S(j,C){m({...b.current,[j]:C})}return a.jsx("div",{children:a.jsxs(ut,{testid:"questionnaire-form",onSubmit:()=>e.onSubmit(p),children:[a.jsx(Ue,{label:"Plan Title",py:"md",defaultValue:p.title,onChange:j=>S("title",j.currentTarget.value)}),a.jsx(lK,{actions:p.action||[],selectedKey:s,setSelectedKey:c,hoverKey:d,setHoverKey:f,onChange:j=>S("action",j)}),a.jsx(ur,{children:"Save"})]})})}function lK(e){const t=v.useRef(e.actions);t.current=e.actions;function n(s){e.onChange(t.current.map(c=>c.id===s.id?s:c))}function r(s){e.onChange([...t.current,s]),e.setSelectedKey(s.id)}function o(s){e.onChange(t.current.filter(c=>c!==s))}return a.jsxs($e,{gap:"md",className:ax.section,children:[e.actions.map(s=>a.jsx(cK,{action:s,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,setHoverKey:e.setHoverKey,onChange:n,onRemove:()=>o(s)},s.id)),a.jsx("div",{children:a.jsx(ke,{variant:"outline",onClick:s=>{dn(s),r({id:uP()})},children:"Add action"})})]})}function cK(e){const{action:t}=e,n=dK(t);function r(s){s.stopPropagation(),e.setSelectedKey(e.action.id)}function o(s){dn(s),e.setHoverKey(e.action.id)}return a.jsx("div",{onClick:r,onMouseOver:o,onFocus:o,children:a.jsx(uK,{action:t,actionType:n,onChange:e.onChange,selectedKey:e.selectedKey,hoverKey:e.hoverKey,onRemove:e.onRemove})})}function uK(e){const{action:t}=e,[n,r]=v.useState(e.actionType),o=e.selectedKey===e.action.id,s=e.hoverKey===e.action.id;function c(f,p){e.onChange({...t,[f]:p})}const d=It(ax.section,{[ax.hovering]:s&&!o});return a.jsxs(yr,{"data-testid":t.id,className:d,p:0,radius:"sm",withBorder:!0,children:[a.jsxs(lo,{w:"100%",p:"xs",bg:"gray.0",gap:"md",align:"center",justify:"space-between",children:[a.jsx(Ue,{w:"100%",name:`actionTitle-${t.id}`,defaultValue:t.title,placeholder:"Title",onChange:f=>c("title",f.currentTarget.value)}),a.jsx(ns,{"data-testid":"close-button",onClick:e.onRemove})]}),o&&a.jsxs($e,{gap:"xl",p:"md",children:[a.jsx(ce,{children:a.jsx(Ue,{label:"Task Description",placeholder:"Enter task description",name:`actionDescription-${t.id}`,defaultValue:t.description,onChange:f=>c("description",f.currentTarget.value)})}),a.jsx(ce,{children:a.jsx(sn,{label:"Type of Action",value:n,onChange:f=>{const p=f.currentTarget.value==="standard"?void 0:f.currentTarget.value;r(p),e.onChange({...e.action,definitionCanonical:p==="standard"?void 0:e.action.definitionCanonical})},data:[{value:"standard",label:"Standard task"},{value:"questionnaire",label:"Task with Questionnaire"},{value:"activitydefinition",label:"Task with Activity Definition"}]})}),n==="questionnaire"&&a.jsxs($e,{gap:0,children:[a.jsxs(ge,{gap:0,mb:"xs",children:[a.jsx(_e,{fw:600,children:"Select questionnaire"}),a.jsx(_e,{c:"red",children:"*"})]}),a.jsxs(_e,{size:"sm",c:"dimmed",mb:"sm",children:["Questionnaire to be shown in the task in Encounter view. You can create new one from"," ",a.jsx(Pt,{href:"/Questionnaire",target:"_blank",c:"blue",children:"questionnaires list"})]}),a.jsx(gT,{resourceType:"Questionnaire",action:t,onChange:e.onChange})]}),n==="activitydefinition"&&a.jsxs($e,{gap:0,children:[a.jsxs(ge,{gap:0,mb:"xs",children:[a.jsx(_e,{fw:600,children:"Select activity definition"}),a.jsx(_e,{c:"red",children:"*"})]}),a.jsxs(_e,{size:"sm",c:"dimmed",mb:"sm",children:["ActivityDefinition.kind resource to be shown in the task in Encounter view. You can create new one from"," ",a.jsx(Pt,{href:"/ActivityDefinition",target:"_blank",c:"blue",children:"activity definitions list"})]}),a.jsx(gT,{resourceType:"ActivityDefinition",action:t,onChange:e.onChange})]})]})]})}function gT(e){const{id:t,definitionCanonical:n}=e.action,r=n?.startsWith(e.resourceType+"/")?{reference:n}:void 0;return a.jsx(ul,{name:t,resourceType:e.resourceType,defaultValue:r,onChange:o=>{o?e.onChange({...e.action,definitionCanonical:At(o)}):e.onChange({...e.action,definitionCanonical:void 0})}})}function dK(e){return e.definitionCanonical?.startsWith("Questionnaire")?"questionnaire":e.definitionCanonical?.startsWith("ActivityDefinition")?"activitydefinition":"standard"}let gy=1;function uP(e){if(e){if(e.startsWith("id-")){const t=parseInt(e.substring(3),10);isNaN(t)||(gy=Math.max(gy,t+1))}return e}return"id-"+gy++}function fK(e){return{...e,action:dP(e.action)}}function dP(e){if(e)return e.map(t=>({...t,id:uP(t.id),action:dP(t.action)}))}const Vs=30,sp=50;function lp(e){const t=e.formState,n=e.item,r=e.responseItem;function o(g){t&&e.context&&t.onChangeAnswer(e.context,e.item,g)}const s=n.type;if(!s)return null;const c=n.linkId;if(!c)return null;let d;n.initial&&n.initial.length>0?d=n.initial[0]:n.answerOption&&n.answerOption.length>0&&(d=n.answerOption.find(g=>g.initialSelected));const f=Yb(r,e.index)??Eb(d),p=mo(r,`${Ui}/fhir/StructureDefinition/questionnaire-validationError`);let m=null;switch(s){case wt.display:m=a.jsx("p",{children:e.item.text},e.item.linkId);break;case wt.boolean:m=a.jsx(FA,{title:e.item.text,htmlFor:e.item.linkId,children:a.jsx(Dn,{id:e.item.linkId,name:e.item.linkId,required:e.required??n.required,defaultChecked:f?.value,onChange:g=>o([{valueBoolean:g.currentTarget.checked}])})},e.item.linkId);break;case wt.decimal:m=a.jsx(Ue,{type:"number",step:"any",id:c,name:c,required:e.required??n.required,defaultValue:f?.value,onChange:g=>o(g.currentTarget.value===""?[]:[{valueDecimal:g.currentTarget.valueAsNumber}])});break;case wt.integer:m=a.jsx(Ue,{type:"number",step:1,id:c,name:c,required:e.required??n.required,defaultValue:f?.value,onChange:g=>o(g.currentTarget.value===""?[]:[{valueInteger:g.currentTarget.valueAsNumber}])});break;case wt.date:m=a.jsx(Ue,{type:"date",id:c,name:c,required:e.required??n.required,defaultValue:f?.value,onChange:g=>o([{valueDate:g.currentTarget.value}])});break;case wt.dateTime:m=a.jsx(ao,{name:c,required:e.required??n.required,defaultValue:f?.value,onChange:g=>o([{valueDateTime:g}])});break;case wt.time:m=a.jsx(Ue,{type:"time",id:c,name:c,required:e.required??n.required,defaultValue:f?.value,onChange:g=>o([{valueTime:g.currentTarget.value}])});break;case wt.string:case wt.url:m=a.jsx(Ue,{id:c,name:c,required:e.required??n.required,defaultValue:f?.value,onChange:g=>{const x=g.currentTarget.value;o(x===""?[]:[{valueString:x}])}});break;case wt.text:m=a.jsx(ol,{id:c,name:c,required:e.required??n.required,defaultValue:f?.value,onChange:g=>{const x=g.currentTarget.value;o(x===""?[]:[{valueString:x}])}});break;case wt.attachment:m=a.jsx(ge,{py:4,children:a.jsx(_A,{path:"",name:c,defaultValue:f?.value,onChange:g=>o([{valueAttachment:g}])})});break;case wt.reference:m=a.jsx(Qa,{name:c,required:e.required??n.required,targetTypes:uA(n),searchCriteria:mF(n,t?.subject,t?.encounter),defaultValue:f?.value,onChange:g=>o([{valueReference:g}])});break;case wt.quantity:m=a.jsx(Ks,{path:"",name:c,required:e.required??n.required,defaultValue:f?.value,onChange:g=>o([{valueQuantity:g}]),disableWheel:!0});break;case wt.choice:case wt.openChoice:xK(n)?m=a.jsx(gK,{name:c,item:n,required:e.required??n.required,initial:d,response:r,onChangeAnswer:g=>o(g)}):yK(n)||n.answerValueSet&&!bK(n)?m=a.jsx(hK,{name:c,item:n,required:e.required??n.required,initial:d,response:r,onChangeAnswer:g=>o(g)}):m=a.jsx(mK,{name:c,item:n,required:e.required??n.required,initial:d,response:r,onChangeAnswer:g=>o(g)});break;default:return null}return a.jsxs(a.Fragment,{children:[m,p?.valueString&&a.jsx(_e,{c:"red",size:"lg",mt:4,children:p.valueString})]})}function hK(e){const{name:t,item:n,required:r,initial:o,onChangeAnswer:s,response:c}=e;if(!n.answerOption?.length&&!n.answerValueSet)return a.jsx(Qb,{});const d=Eb(o),f=Yb(c)??d,p=pP(c),m=n.repeats||SK(n);if(n.answerValueSet)return a.jsx(gm,{name:t,placeholder:"Select items",binding:n.answerValueSet,maxValues:m?void 0:1,required:r,onChange:g=>{m?g.length===0?s([{}]):s(g.map(x=>({valueCoding:x}))):s([{valueCoding:g[0]}])},defaultValue:f?.value});if(m){const{propertyName:g,data:x}=wK(n);return a.jsx(Wp,{data:x,placeholder:"Select items",searchable:!0,defaultValue:p||[Gs(d)],required:r,onChange:b=>{if(b.length===0)s([{}]);else{const S=lA(b,g,n);s(S)}}})}else{const g=[""];if(n.answerOption)for(const x of n.answerOption){const b=fo(x);g.push(Gs(b))}return a.jsx(sn,{id:t,name:t,required:r,onChange:x=>{const b=x.currentTarget.selectedIndex;if(b===0){s([{}]);return}const S=n.answerOption[b-1],j=fo(S),C="value"+Ln(j.type);s([{[C]:j.value}])},defaultValue:Id(f?.value)||f?.value,data:g})}}function pK(e,t){return e?t.valueSetExpand({url:e,count:Vs+1}).then(n=>n.expansion?.contains??[]):Promise.resolve([])}function fP(e){const t=De(),[n,r]=v.useState([]),[o,s]=v.useState(!1);return v.useEffect(()=>{async function c(){if(e){s(!0);try{const d=await pK(e,t);r(d)}catch(d){console.error("Error loading value set:",d)}finally{s(!1)}}}c().catch(console.error)},[e,t]),[n,o]}function hP(e,t){return e.map((n,r)=>{const o=`${t}-valueset-${r}`,s={type:"Coding",value:{system:n.system,code:n.code,display:n.display}};return[o,s]})}function mK(e){const{name:t,item:n,required:r,initial:o,onChangeAnswer:s,response:c}=e,d=is("QuestionnaireItemAnswerOption","value[x]"),f=Eb(o),[p,m]=fP(n.answerValueSet),g=[];let x;if(n.answerValueSet)g.push(...hP(p,t));else if(n.answerOption){const C=n.answerOption.slice(0,sp).map((R,E)=>{const T=`${t}-option-${E}`,_=fo(R);return _?.value?(f&&Ii(_)===Ii(f)&&(x=T),[T,_]):null}).filter(R=>R!==null);g.push(...C)}const b=Yb(c),S=vK(g,b);if(m)return a.jsx(_e,{children:"Loading options..."});if(g.length===0)return a.jsx(Qb,{});const j=g.slice(0,Vs);return a.jsxs(a.Fragment,{children:[a.jsx(rr.Group,{name:t,value:S??x,required:r,onChange:C=>{const R=g.find(E=>E[0]===C);if(R){const E=R[1],T="value"+Ln(E.type);s([{[T]:E.value}])}},children:j.map(([C,R])=>a.jsx(rr,{id:C,value:C,py:4,required:r,label:a.jsx($i,{property:d,propertyType:R.type,value:R.value})},C))}),(n.answerValueSet&&g.length>Vs||n.answerOption&&g.length>sp)&&a.jsxs(_e,{size:"sm",c:"dimmed",mt:"xs",children:["Showing first ",Vs," options"]})]})}function gK(e){const{name:t,item:n,onChangeAnswer:r,response:o}=e,s=is("QuestionnaireItemAnswerOption","value[x]"),[c,d]=fP(n.answerValueSet),f=n.answerValueSet?(o?.answer?.map(S=>S.valueCoding)||[]).filter(S=>S!==void 0):pP(o),[p,m]=v.useState(f),g=[];if(n.answerValueSet)g.push(...hP(c,t));else if(n.answerOption){const S=n.answerOption.slice(0,sp).map((j,C)=>{const R=`${t}-option-${C}`,E=fo(j);return E?.value?[R,E]:null}).filter(j=>j!==null);g.push(...S)}if(d)return a.jsx(_e,{children:"Loading options..."});if(g.length===0)return a.jsx(Qb,{});const x=g.slice(0,Vs),b=(S,j)=>{if(n.answerValueSet){const C=p;let R;j?R=[...C,S.value]:R=C.filter(E=>!co(E,S.value)),m(R),R.length===0?r([{}]):r(R.map(E=>({valueCoding:E})))}else{const C=p,R=Gs(S);let E;if(j?E=[...C,R]:E=C.filter(T=>T!==R),m(E),E.length===0)r([{}]);else{const T=lA(E,"value"+Ln(S.type),n);r(T)}}};return a.jsxs(ge,{style:{flexDirection:"column",alignItems:"flex-start"},children:[x.map(([S,j])=>{const C=Gs(j),R=n.answerValueSet?p.some(E=>co(E,j.value)):p.includes(C);return a.jsx(Dn,{id:S,label:a.jsx($i,{property:s,propertyType:j.type,value:j.value}),checked:R,onChange:E=>b(j,E.currentTarget.checked)},S)}),(n.answerValueSet&&g.length>Vs||n.answerOption&&g.length>sp)&&a.jsxs(_e,{size:"sm",c:"dimmed",children:["Showing first ",Vs," options"]})]})}function Qb(){return a.jsx(Ue,{disabled:!0,placeholder:"No Answers Defined"})}function Yb(e,t=0){return fo(e?.answer?.[t]??{})}function pP(e){const t=e?.answer;return t?t.map(r=>fo(r)).map(r=>Id(r?.value)||r?.value).filter(Boolean):[]}function vK(e,t){return e.find(n=>co(n[1].value,t?.value))?.[0]}function Em(e,t){return!!e.extension?.some(n=>n.url===jb&&n.valueCodeableConcept?.coding?.[0]?.code===t)}function yK(e){return Em(e,"drop-down")}function xK(e){return Em(e,"check-box")}function bK(e){return Em(e,"radio-button")}function SK(e){return Em(e,"multi-select")}function wK(e){if(e.answerOption?.length===0)return{propertyName:"",data:[]};const t=e.answerOption[0],n=fo(t),r="value"+Ln(n.type),o=(e.answerOption??[]).map(s=>{const c=fo(s),d=Gs(c);return{value:d,label:d}});return{propertyName:r,data:o}}const jK="_section_my8o4_1",CK="_hovering_my8o4_10",EK="_editing_my8o4_14",TK="_questionBody_my8o4_20",RK="_topActions_my8o4_24",_K="_bottomActions_my8o4_33",DK="_movementActions_my8o4_44",AK="_movementIcons_my8o4_56",PK="_columnAlignment_my8o4_60",kK="_linkIdInput_my8o4_65",NK="_typeSelect_my8o4_70",OK="_preserveBreaks_my8o4_74",Gr={section:jK,hovering:CK,editing:EK,questionBody:TK,topActions:RK,bottomActions:_K,movementActions:DK,movementIcons:AK,columnAlignment:PK,linkIdInput:kK,typeSelect:NK,preserveBreaks:OK};function MK(e){const t=De(),n=Gt(e.questionnaire),[r,o]=v.useState(!1),[s,c]=v.useState(),[d,f]=v.useState(),[p,m]=v.useState();function g(){m(void 0)}function x(){f(void 0)}v.useEffect(()=>{t.requestSchema("Questionnaire").then(()=>o(!0)).catch(console.log)},[t]),v.useEffect(()=>(c(zK(n??{resourceType:"Questionnaire",status:"active"})),document.addEventListener("mouseover",g),document.addEventListener("click",x),()=>{document.removeEventListener("mouseover",g),document.removeEventListener("click",x)}),[n]);const b=(S,j)=>{c(S),e.autoSave&&!j&&e.onSubmit&&e.onSubmit(S)};return!r||!s?null:a.jsx("div",{children:a.jsxs(ut,{testid:"questionnaire-form",onSubmit:()=>e.onSubmit(s),children:[a.jsx(mP,{item:s,selectedKey:d,setSelectedKey:f,hoverKey:p,setHoverKey:m,onChange:b}),a.jsx(ur,{children:"Save"})]})})}function mP(e){const t=e.item,n=e.item,r=go(e.item),o=r||n.type===wt.group,s=n.linkId??"[untitled]",c=e.selectedKey===e.item.id,d=e.hoverKey===e.item.id,f=v.useRef(e.item);f.current=e.item;function p(T){dn(T),e.setSelectedKey(e.item.id)}function m(T){dn(T),e.setHoverKey(e.item.id)}function g(T){const _=f.current;e.onChange({..._,item:_.item?.map(P=>P.id===T.id?T:P)})}function x(T,_){e.onChange({...e.item,item:[...e.item.item??[],T]},_)}function b(T){e.onChange({...e.item,item:e.item.item?.filter(_=>_!==T)})}function S(T,_){e.onChange({...f.current,[T]:_})}function j(T){e.onChange({...e.item,...T})}function C(T){e.onChange({...e.item,item:e.item.item?.map(_=>_===T?{..._,repeats:!_.repeats}:_)})}function R(T,_){const P=VK(e.item.item,T,_);e.onChange({...e.item,item:P})}const E=It(Gr.section,{[Gr.editing]:c,[Gr.hovering]:d&&!c});return a.jsxs("div",{"data-testid":n.linkId,className:E,onClick:p,onMouseOver:m,onFocus:m,children:[a.jsx("div",{className:Gr.questionBody,children:c?a.jsxs(a.Fragment,{children:[r&&a.jsx(Ue,{size:"xl",defaultValue:t.title,onBlur:T=>S("title",T.currentTarget.value)}),!r&&a.jsx(ol,{autosize:!0,minRows:2,defaultValue:n.text,onBlur:T=>S("text",T.currentTarget.value)}),n.type==="reference"&&a.jsx($K,{item:n,onChange:j}),oF(n)&&a.jsx(LK,{item:n,onChange:T=>j(T)})]}):a.jsxs(a.Fragment,{children:[t.title&&a.jsx(Oe,{children:t.title}),n.text&&a.jsx("div",{className:Gr.preserveBreaks,children:n.text}),!o&&a.jsx(lp,{item:n,index:0,required:!1,responseItem:{linkId:n.linkId}})]})}),n.item?.map((T,_)=>a.jsx("div",{children:a.jsx(mP,{item:T,selectedKey:e.selectedKey,setSelectedKey:e.setSelectedKey,hoverKey:e.hoverKey,isFirst:_===0,isLast:_===(e.item.item??[]).length-1,setHoverKey:e.setHoverKey,onChange:g,onRemove:()=>b(T),onRepeatable:C,onMoveUp:()=>R(_,-1),onMoveDown:()=>R(_,1)})},T.id)),!o&&a.jsx("div",{className:Gr.topActions,children:c?a.jsxs(a.Fragment,{children:[a.jsx(Ue,{size:"xs",className:Gr.linkIdInput,defaultValue:n.linkId,onBlur:T=>S("linkId",T.currentTarget.value)}),!o&&a.jsx(sn,{size:"xs",className:Gr.typeSelect,defaultValue:n.type,onChange:T=>S("type",T.currentTarget.value),data:[{value:"display",label:"Display"},{value:"boolean",label:"Boolean"},{value:"decimal",label:"Decimal"},{value:"integer",label:"Integer"},{value:"date",label:"Date"},{value:"dateTime",label:"Date/Time"},{value:"time",label:"Time"},{value:"string",label:"String"},{value:"text",label:"Text"},{value:"url",label:"URL"},{value:"choice",label:"Choice"},{value:"open-choice",label:"Open Choice"},{value:"attachment",label:"Attachment"},{value:"reference",label:"Reference"},{value:"quantity",label:"Quantity"}]})]}):a.jsx("div",{children:s})}),!r&&a.jsx(ce,{className:Gr.movementActions,children:a.jsxs(ce,{className:Gr.columnAlignment,children:[!e.isFirst&&a.jsx(Pt,{href:"#",onClick:T=>{T.preventDefault(),e.onMoveUp&&e.onMoveUp()},children:a.jsx($F,{"data-testid":"up-button",size:15,className:Gr.movementIcons})}),!e.isLast&&a.jsx(Pt,{href:"#",onClick:T=>{T.preventDefault(),e.onMoveDown&&e.onMoveDown()},children:a.jsx(LF,{"data-testid":"down-button",size:15,className:Gr.movementIcons})})]})}),a.jsxs("div",{className:Gr.bottomActions,children:[o&&a.jsxs(a.Fragment,{children:[a.jsx(Pt,{href:"#",onClick:T=>{T.preventDefault(),x({id:Js(),linkId:cx("q"),type:"string",text:"Question"})},children:"Add item"}),a.jsx(Pt,{href:"#",onClick:T=>{T.preventDefault(),x({id:Js(),linkId:cx("g"),type:"group",text:"Group"},!0)},children:"Add group"})]}),r&&a.jsx(Pt,{href:"#",onClick:T=>{T.preventDefault(),x(BK(),!0)},children:"Add Page"}),c&&!r&&a.jsxs(a.Fragment,{children:[a.jsx(Pt,{href:"#",onClick:T=>{T.preventDefault(),e.onRepeatable&&e.onRepeatable(n)},children:n.repeats?"Remove Repeatable":"Make Repeatable"}),a.jsx(Pt,{href:"#",onClick:T=>{T.preventDefault(),e.onRemove&&e.onRemove()},children:"Remove"})]})]})]})}function LK(e){const t=is("QuestionnaireItemAnswerOption","value[x]"),n=e.item.answerOption??[];return a.jsxs("div",{children:[e.item.answerValueSet!==void 0?a.jsx(Ue,{placeholder:"Enter Value Set",defaultValue:e.item.answerValueSet,onChange:r=>e.onChange({...e.item,answerValueSet:r.target.value})}):a.jsx(IK,{options:n,property:t,item:e.item,onChange:e.onChange}),a.jsxs(ce,{display:"flex",children:[a.jsx(Pt,{href:"#",onClick:r=>{dn(r),e.onChange({...e.item,answerValueSet:void 0,answerOption:[...n,{id:Js()}]})},children:"Add choice"}),a.jsx(nm,{w:"lg"}),a.jsx(Pt,{href:"#",onClick:r=>{dn(r),e.onChange({...e.item,answerOption:[],answerValueSet:""})},children:"Add value set"})]})]})}function IK(e){return a.jsx("div",{children:e.options.map(t=>{const[n,r]=ym({type:"QuestionnaireItemAnswerOption",value:t},"value");return a.jsxs("div",{style:{display:"flex",flexDirection:"row",justifyContent:"space-between",alignItems:"center",width:"80%"},children:[a.jsx("div",{children:a.jsx(Bd,{name:"value[x]",path:"Questionnaire.answerOption.value[x]",property:e.property,defaultPropertyType:r,defaultValue:n,onChange:(o,s)=>{const c=[...e.options],d=c.findIndex(f=>f.id===t.id);c[d]={id:t.id,[s]:o},e.onChange({...e.item,answerOption:c})},outcome:void 0},t.id)}),a.jsx("div",{children:a.jsx(Pt,{href:"#",onClick:o=>{dn(o),e.onChange({...e.item,answerOption:e.options.filter(s=>s.id!==t.id)})},children:"Remove"})})]},t.id)})})}function $K(e){const t=uA(e.item)??[];return a.jsxs(a.Fragment,{children:[t.map((n,r)=>a.jsxs(ge,{children:[a.jsx(Mb,{name:"resourceType",placeholder:"Resource Type",defaultValue:n,onChange:o=>{e.onChange(uy(e.item,t.map(s=>s===n?o:s)))}}),a.jsx(Pt,{href:"#",onClick:o=>{dn(o),e.onChange(uy(e.item,t.filter(s=>s!==n)))},children:"Remove"})]},`${n}-${r}`)),a.jsx(Pt,{href:"#",onClick:n=>{dn(n),e.onChange(uy(e.item,[...t,""]))},children:"Add Resource Type"})]})}let sx=1,lx=1;function cx(e){return e+sx++}function Js(){return"id-"+lx++}function zK(e){return{...e,id:e.id||Js(),item:gP(e.item)}}function gP(e){if(e)return e.forEach(t=>{t.id?.match(/^id-\d+$/)&&(lx=Math.max(lx,parseInt(t.id.substring(3),10)+1)),t.linkId?.match(/^q\d+$/)&&(sx=Math.max(sx,parseInt(t.linkId.substring(1),10)+1))}),e.map(t=>({...t,id:t.id||Js(),item:gP(t.item),answerOption:UK(t.answerOption)}))}function UK(e){if(e)return e.map(t=>({...t,id:t.id||Js()}))}function BK(){return{id:Js(),linkId:cx("s"),type:"group",text:"New Page",extension:[{url:jb,valueCodeableConcept:{coding:[{system:"http://hl7.org/fhir/questionnaire-item-control",code:"page"}]}}]}}function VK(e,t,n){const r=e??[],o=t+n;if(o<0||o>=r.length)return r;const s=[...r];return[s[t],s[o]]=[s[o],s[t]],s}/*!
|
|
553
|
-
* Signature Pad v5.1.
|
|
553
|
+
* Signature Pad v5.1.1 | https://github.com/szimek/signature_pad
|
|
554
554
|
* (c) 2025 Szymon Nowak | Released under the MIT license
|
|
555
555
|
*/var cp=class{x;y;pressure;time;constructor(e,t,n,r){if(isNaN(e)||isNaN(t))throw new Error(`Point is invalid: (${e}, ${t})`);this.x=+e,this.y=+t,this.pressure=n||0,this.time=r||Date.now()}distanceTo(e){return Math.sqrt(Math.pow(this.x-e.x,2)+Math.pow(this.y-e.y,2))}equals(e){return this.x===e.x&&this.y===e.y&&this.pressure===e.pressure&&this.time===e.time}velocityFrom(e){return this.time!==e.time?this.distanceTo(e)/(this.time-e.time):0}},FK=class vP{constructor(t,n,r,o,s,c){this.startPoint=t,this.control2=n,this.control1=r,this.endPoint=o,this.startWidth=s,this.endWidth=c}static fromPoints(t,n){const r=this.calculateControlPoints(t[0],t[1],t[2]).c2,o=this.calculateControlPoints(t[1],t[2],t[3]).c1;return new vP(t[1],r,o,t[2],n.start,n.end)}static calculateControlPoints(t,n,r){const o=t.x-n.x,s=t.y-n.y,c=n.x-r.x,d=n.y-r.y,f={x:(t.x+n.x)/2,y:(t.y+n.y)/2},p={x:(n.x+r.x)/2,y:(n.y+r.y)/2},m=Math.sqrt(o*o+s*s),g=Math.sqrt(c*c+d*d),x=f.x-p.x,b=f.y-p.y,S=m+g==0?0:g/(m+g),j={x:p.x+x*S,y:p.y+b*S},C=n.x-j.x,R=n.y-j.y;return{c1:new cp(f.x+C,f.y+R),c2:new cp(p.x+C,p.y+R)}}length(){let n=0,r,o;for(let s=0;s<=10;s+=1){const c=s/10,d=this.point(c,this.startPoint.x,this.control1.x,this.control2.x,this.endPoint.x),f=this.point(c,this.startPoint.y,this.control1.y,this.control2.y,this.endPoint.y);if(s>0){const p=d-r,m=f-o;n+=Math.sqrt(p*p+m*m)}r=d,o=f}return n}point(t,n,r,o,s){return n*(1-t)*(1-t)*(1-t)+3*r*(1-t)*(1-t)*t+3*o*(1-t)*t*t+s*t*t*t}},qK=class{_et;constructor(){try{this._et=new EventTarget}catch{this._et=document}}addEventListener(e,t,n){this._et.addEventListener(e,t,n)}dispatchEvent(e){return this._et.dispatchEvent(e)}removeEventListener(e,t,n){this._et.removeEventListener(e,t,n)}};function HK(e,t=250){let n=0,r=null,o,s,c;const d=()=>{n=Date.now(),r=null,o=e.apply(s,c),r||(s=null,c=[])};return function(...p){const m=Date.now(),g=t-(m-n);return s=this,c=p,g<=0||g>t?(r&&(clearTimeout(r),r=null),n=m,o=e.apply(s,c),r||(s=null,c=[])):r||(r=window.setTimeout(d,g)),o}}var GK=class ux extends qK{constructor(t,n={}){super(),this.canvas=t,this.velocityFilterWeight=n.velocityFilterWeight||.7,this.minWidth=n.minWidth||.5,this.maxWidth=n.maxWidth||2.5,this.throttle=n.throttle??16,this.minDistance=n.minDistance??5,this.dotSize=n.dotSize||0,this.penColor=n.penColor||"black",this.backgroundColor=n.backgroundColor||"rgba(0,0,0,0)",this.compositeOperation=n.compositeOperation||"source-over",this.canvasContextOptions=n.canvasContextOptions??{},this._strokeMoveUpdate=this.throttle?HK(ux.prototype._strokeUpdate,this.throttle):ux.prototype._strokeUpdate,this._handleMouseDown=this._handleMouseDown.bind(this),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this._handleTouchStart=this._handleTouchStart.bind(this),this._handleTouchMove=this._handleTouchMove.bind(this),this._handleTouchEnd=this._handleTouchEnd.bind(this),this._handlePointerDown=this._handlePointerDown.bind(this),this._handlePointerMove=this._handlePointerMove.bind(this),this._handlePointerUp=this._handlePointerUp.bind(this),this._ctx=t.getContext("2d",this.canvasContextOptions),this.clear(),this.on()}dotSize;minWidth;maxWidth;penColor;minDistance;velocityFilterWeight;compositeOperation;backgroundColor;throttle;canvasContextOptions;_ctx;_drawingStroke=!1;_isEmpty=!0;_dataUrl;_dataUrlOptions;_lastPoints=[];_data=[];_lastVelocity=0;_lastWidth=0;_strokeMoveUpdate;_strokePointerId;clear(){const{_ctx:t,canvas:n}=this;t.fillStyle=this.backgroundColor,t.clearRect(0,0,n.width,n.height),t.fillRect(0,0,n.width,n.height),this._data=[],this._reset(this._getPointGroupOptions()),this._isEmpty=!0,this._dataUrl=void 0,this._dataUrlOptions=void 0,this._strokePointerId=void 0}redraw(){const t=this._data,n=this._dataUrl,r=this._dataUrlOptions;this.clear(),n&&this.fromDataURL(n,r),this.fromData(t,{clear:!1})}fromDataURL(t,n={}){return new Promise((r,o)=>{const s=new Image,c=n.ratio||window.devicePixelRatio||1,d=n.width||this.canvas.width/c,f=n.height||this.canvas.height/c,p=n.xOffset||0,m=n.yOffset||0;this._reset(this._getPointGroupOptions()),s.onload=()=>{this._ctx.drawImage(s,p,m,d,f),r()},s.onerror=g=>{o(g)},s.crossOrigin="anonymous",s.src=t,this._isEmpty=!1,this._dataUrl=t,this._dataUrlOptions={...n}})}toDataURL(t="image/png",n){switch(t){case"image/svg+xml":return typeof n!="object"&&(n=void 0),`data:image/svg+xml;base64,${btoa(this.toSVG(n))}`;default:return typeof n!="number"&&(n=void 0),this.canvas.toDataURL(t,n)}}on(){this.canvas.style.touchAction="none",this.canvas.style.msTouchAction="none",this.canvas.style.userSelect="none";const t=/Macintosh/.test(navigator.userAgent)&&"ontouchstart"in document;window.PointerEvent&&!t?this._handlePointerEvents():(this._handleMouseEvents(),"ontouchstart"in window&&this._handleTouchEvents())}off(){this.canvas.style.touchAction="auto",this.canvas.style.msTouchAction="auto",this.canvas.style.userSelect="auto",this.canvas.removeEventListener("pointerdown",this._handlePointerDown),this.canvas.removeEventListener("mousedown",this._handleMouseDown),this.canvas.removeEventListener("touchstart",this._handleTouchStart),this._removeMoveUpEventListeners()}_getListenerFunctions(){const t=window.document===this.canvas.ownerDocument?window:this.canvas.ownerDocument.defaultView??this.canvas.ownerDocument;return{addEventListener:t.addEventListener.bind(t),removeEventListener:t.removeEventListener.bind(t)}}_removeMoveUpEventListeners(){const{removeEventListener:t}=this._getListenerFunctions();t("pointermove",this._handlePointerMove),t("pointerup",this._handlePointerUp),t("mousemove",this._handleMouseMove),t("mouseup",this._handleMouseUp),t("touchmove",this._handleTouchMove),t("touchend",this._handleTouchEnd)}isEmpty(){return this._isEmpty}fromData(t,{clear:n=!0}={}){n&&this.clear(),this._fromData(t,this._drawCurve.bind(this),this._drawDot.bind(this)),this._data=this._data.concat(t)}toData(){return this._data}_isLeftButtonPressed(t,n){return n?t.buttons===1:(t.buttons&1)===1}_pointerEventToSignatureEvent(t){return{event:t,type:t.type,x:t.clientX,y:t.clientY,pressure:"pressure"in t?t.pressure:0}}_touchEventToSignatureEvent(t){const n=t.changedTouches[0];return{event:t,type:t.type,x:n.clientX,y:n.clientY,pressure:n.force}}_handleMouseDown(t){!this._isLeftButtonPressed(t,!0)||this._drawingStroke||this._strokeBegin(this._pointerEventToSignatureEvent(t))}_handleMouseMove(t){if(!this._isLeftButtonPressed(t,!0)||!this._drawingStroke){this._strokeEnd(this._pointerEventToSignatureEvent(t),!1);return}this._strokeMoveUpdate(this._pointerEventToSignatureEvent(t))}_handleMouseUp(t){this._isLeftButtonPressed(t)||this._strokeEnd(this._pointerEventToSignatureEvent(t))}_handleTouchStart(t){t.targetTouches.length!==1||this._drawingStroke||(t.cancelable&&t.preventDefault(),this._strokeBegin(this._touchEventToSignatureEvent(t)))}_handleTouchMove(t){if(t.targetTouches.length===1){if(t.cancelable&&t.preventDefault(),!this._drawingStroke){this._strokeEnd(this._touchEventToSignatureEvent(t),!1);return}this._strokeMoveUpdate(this._touchEventToSignatureEvent(t))}}_handleTouchEnd(t){t.targetTouches.length===0&&(t.cancelable&&t.preventDefault(),this._strokeEnd(this._touchEventToSignatureEvent(t)))}_getPointerId(t){return t.persistentDeviceId||t.pointerId}_allowPointerId(t,n=!1){return typeof this._strokePointerId>"u"?n:this._getPointerId(t)===this._strokePointerId}_handlePointerDown(t){this._drawingStroke||!this._isLeftButtonPressed(t)||!this._allowPointerId(t,!0)||(this._strokePointerId=this._getPointerId(t),t.preventDefault(),this._strokeBegin(this._pointerEventToSignatureEvent(t)))}_handlePointerMove(t){if(this._allowPointerId(t)){if(!this._isLeftButtonPressed(t,!0)||!this._drawingStroke){this._strokeEnd(this._pointerEventToSignatureEvent(t),!1);return}t.preventDefault(),this._strokeMoveUpdate(this._pointerEventToSignatureEvent(t))}}_handlePointerUp(t){this._isLeftButtonPressed(t)||!this._allowPointerId(t)||(t.preventDefault(),this._strokeEnd(this._pointerEventToSignatureEvent(t)))}_getPointGroupOptions(t){return{penColor:t&&"penColor"in t?t.penColor:this.penColor,dotSize:t&&"dotSize"in t?t.dotSize:this.dotSize,minWidth:t&&"minWidth"in t?t.minWidth:this.minWidth,maxWidth:t&&"maxWidth"in t?t.maxWidth:this.maxWidth,velocityFilterWeight:t&&"velocityFilterWeight"in t?t.velocityFilterWeight:this.velocityFilterWeight,compositeOperation:t&&"compositeOperation"in t?t.compositeOperation:this.compositeOperation}}_strokeBegin(t){if(!this.dispatchEvent(new CustomEvent("beginStroke",{detail:t,cancelable:!0})))return;const{addEventListener:r}=this._getListenerFunctions();switch(t.event.type){case"mousedown":r("mousemove",this._handleMouseMove,{passive:!1}),r("mouseup",this._handleMouseUp,{passive:!1});break;case"touchstart":r("touchmove",this._handleTouchMove,{passive:!1}),r("touchend",this._handleTouchEnd,{passive:!1});break;case"pointerdown":r("pointermove",this._handlePointerMove,{passive:!1}),r("pointerup",this._handlePointerUp,{passive:!1});break}this._drawingStroke=!0;const o=this._getPointGroupOptions(),s={...o,points:[]};this._data.push(s),this._reset(o),this._strokeUpdate(t)}_strokeUpdate(t){if(!this._drawingStroke)return;if(this._data.length===0){this._strokeBegin(t);return}this.dispatchEvent(new CustomEvent("beforeUpdateStroke",{detail:t}));const n=this._createPoint(t.x,t.y,t.pressure),r=this._data[this._data.length-1],o=r.points,s=o.length>0&&o[o.length-1],c=s?n.distanceTo(s)<=this.minDistance:!1,d=this._getPointGroupOptions(r);if(!s||!(s&&c)){const f=this._addPoint(n,d);s?f&&this._drawCurve(f,d):this._drawDot(n,d),o.push({time:n.time,x:n.x,y:n.y,pressure:n.pressure})}this.dispatchEvent(new CustomEvent("afterUpdateStroke",{detail:t}))}_strokeEnd(t,n=!0){this._removeMoveUpEventListeners(),this._drawingStroke&&(n&&this._strokeUpdate(t),this._drawingStroke=!1,this._strokePointerId=void 0,this.dispatchEvent(new CustomEvent("endStroke",{detail:t})))}_handlePointerEvents(){this._drawingStroke=!1,this.canvas.addEventListener("pointerdown",this._handlePointerDown,{passive:!1})}_handleMouseEvents(){this._drawingStroke=!1,this.canvas.addEventListener("mousedown",this._handleMouseDown,{passive:!1})}_handleTouchEvents(){this.canvas.addEventListener("touchstart",this._handleTouchStart,{passive:!1})}_reset(t){this._lastPoints=[],this._lastVelocity=0,this._lastWidth=(t.minWidth+t.maxWidth)/2,this._ctx.fillStyle=t.penColor,this._ctx.globalCompositeOperation=t.compositeOperation}_createPoint(t,n,r){const o=this.canvas.getBoundingClientRect();return new cp(t-o.left,n-o.top,r,new Date().getTime())}_addPoint(t,n){const{_lastPoints:r}=this;if(r.push(t),r.length>2){r.length===3&&r.unshift(r[0]);const o=this._calculateCurveWidths(r[1],r[2],n),s=FK.fromPoints(r,o);return r.shift(),s}return null}_calculateCurveWidths(t,n,r){const o=r.velocityFilterWeight*n.velocityFrom(t)+(1-r.velocityFilterWeight)*this._lastVelocity,s=this._strokeWidth(o,r),c={end:s,start:this._lastWidth};return this._lastVelocity=o,this._lastWidth=s,c}_strokeWidth(t,n){return Math.max(n.maxWidth/(t+1),n.minWidth)}_drawCurveSegment(t,n,r){const o=this._ctx;o.moveTo(t,n),o.arc(t,n,r,0,2*Math.PI,!1),this._isEmpty=!1}_drawCurve(t,n){const r=this._ctx,o=t.endWidth-t.startWidth,s=Math.ceil(t.length())*2;r.beginPath(),r.fillStyle=n.penColor;for(let c=0;c<s;c+=1){const d=c/s,f=d*d,p=f*d,m=1-d,g=m*m,x=g*m;let b=x*t.startPoint.x;b+=3*g*d*t.control1.x,b+=3*m*f*t.control2.x,b+=p*t.endPoint.x;let S=x*t.startPoint.y;S+=3*g*d*t.control1.y,S+=3*m*f*t.control2.y,S+=p*t.endPoint.y;const j=Math.min(t.startWidth+p*o,n.maxWidth);this._drawCurveSegment(b,S,j)}r.closePath(),r.fill()}_drawDot(t,n){const r=this._ctx,o=n.dotSize>0?n.dotSize:(n.minWidth+n.maxWidth)/2;r.beginPath(),this._drawCurveSegment(t.x,t.y,o),r.closePath(),r.fillStyle=n.penColor,r.fill()}_fromData(t,n,r){for(const o of t){const{points:s}=o,c=this._getPointGroupOptions(o);if(s.length>1)for(let d=0;d<s.length;d+=1){const f=s[d],p=new cp(f.x,f.y,f.pressure,f.time);d===0&&this._reset(c);const m=this._addPoint(p,c);m&&n(m,c)}else this._reset(c),r(s[0],c)}}toSVG({includeBackgroundColor:t=!1,includeDataUrl:n=!1}={}){const r=this._data,o=Math.max(window.devicePixelRatio||1,1),s=0,c=0,d=this.canvas.width/o,f=this.canvas.height/o,p=document.createElementNS("http://www.w3.org/2000/svg","svg");if(p.setAttribute("xmlns","http://www.w3.org/2000/svg"),p.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"),p.setAttribute("viewBox",`${s} ${c} ${d} ${f}`),p.setAttribute("width",d.toString()),p.setAttribute("height",f.toString()),t&&this.backgroundColor){const m=document.createElement("rect");m.setAttribute("width","100%"),m.setAttribute("height","100%"),m.setAttribute("fill",this.backgroundColor),p.appendChild(m)}if(n&&this._dataUrl){const m=this._dataUrlOptions?.ratio||window.devicePixelRatio||1,g=this._dataUrlOptions?.width||this.canvas.width/m,x=this._dataUrlOptions?.height||this.canvas.height/m,b=this._dataUrlOptions?.xOffset||0,S=this._dataUrlOptions?.yOffset||0,j=document.createElement("image");j.setAttribute("x",b.toString()),j.setAttribute("y",S.toString()),j.setAttribute("width",g.toString()),j.setAttribute("height",x.toString()),j.setAttribute("preserveAspectRatio","none"),j.setAttribute("href",this._dataUrl),p.appendChild(j)}return this._fromData(r,(m,{penColor:g})=>{const x=document.createElement("path");if(!isNaN(m.control1.x)&&!isNaN(m.control1.y)&&!isNaN(m.control2.x)&&!isNaN(m.control2.y)){const b=`M ${m.startPoint.x.toFixed(3)},${m.startPoint.y.toFixed(3)} C ${m.control1.x.toFixed(3)},${m.control1.y.toFixed(3)} ${m.control2.x.toFixed(3)},${m.control2.y.toFixed(3)} ${m.endPoint.x.toFixed(3)},${m.endPoint.y.toFixed(3)}`;x.setAttribute("d",b),x.setAttribute("stroke-width",(m.endWidth*2.25).toFixed(3)),x.setAttribute("stroke",g),x.setAttribute("fill","none"),x.setAttribute("stroke-linecap","round"),p.appendChild(x)}},(m,{penColor:g,dotSize:x,minWidth:b,maxWidth:S})=>{const j=document.createElement("circle"),C=x>0?x:(b+S)/2;j.setAttribute("r",C.toString()),j.setAttribute("cx",m.x.toString()),j.setAttribute("cy",m.y.toString()),j.setAttribute("fill",g),p.appendChild(j)}),p.outerHTML}};function WK(e){const t=De(),{width:n=500,height:r=200,defaultValue:o,who:s,onChange:c,...d}=e,f=v.useRef(null),p=v.useRef(null),m=v.useRef(c);m.current=c,v.useEffect(()=>{function x(){m.current?.({type:[{system:Ui+"/fhir/signature-type",code:"ProofOfOrigin",display:"Proof of Origin"}],when:new Date().toISOString(),who:s??qt(t.getProfile()),data:p.current?.toDataURL()})}if(f.current){const b=new GK(f.current);o?.data&&b.fromDataURL(o.data).catch(console.error),b.addEventListener("endStroke",x),p.current=b}return()=>{p.current&&p.current.removeEventListener("beginStroke",x)}},[t,o,s]);const g=()=>{p.current&&p.current.clear(),m.current?.(void 0)};return a.jsxs(yr,{withBorder:!0,p:0,w:n,h:r,pos:"relative",...d,children:[a.jsx("canvas",{ref:f,width:n,height:r,"aria-label":"Signature input area"}),a.jsx(ke,{onClick:g,"aria-label":"Clear signature",pos:"absolute",top:0,right:0,size:"xs",leftSection:a.jsx(mm,{size:16}),variant:"subtle",color:"gray",children:"Clear"})]})}function yP(e){const t=[...e.context,e.responseItem];return a.jsxs("div",{children:[e.item.text&&a.jsx(Oe,{order:3,mb:"md",children:e.item.text}),a.jsx(dx,{formState:e.formState,context:t,items:e.item.item??[],responseItems:e.responseItem.item??[]})]},e.item.linkId)}function QK(e){return a.jsxs(a.Fragment,{children:[e.responseItems.map(t=>a.jsx(yP,{formState:e.formState,context:e.context,item:e.item,responseItem:t},`group-${t.id}`)),a.jsx(Pt,{onClick:()=>e.formState.onAddGroup(e.context,e.item),children:`Add Group: ${e.item.text}`})]})}function YK(e){const{formState:t,context:n,item:r,responseItem:o}=e,s=r.type!==wt.choice&&r.type!==wt.openChoice,c=o.answer&&o.answer.length>0?o.answer:[{}];return a.jsxs(Ot,{htmlFor:e.item.linkId,title:e.item.text,withAsterisk:e.item.required,children:[a.jsx($e,{gap:"xs",children:c?.map((d,f)=>a.jsx(lp,{formState:t,context:n,item:r,responseItem:o,index:f},`${r.linkId}-${f}`))}),s&&a.jsx(Pt,{onClick:()=>t.onAddAnswer(n,r),children:"Add Item"})]},e.item.linkId)}function dx(e){const{formState:t,context:n,items:r,responseItems:o}=e;return a.jsx($e,{children:r.map((s,c)=>{if(!aF(s,t.questionnaireResponse))return null;if(s.type===wt.display)return a.jsx("p",{children:s.text},`display-${s.id}-${c}`);const d=o.filter(f=>f.linkId===s.linkId);return s.type===wt.group&&s.repeats?a.jsx(QK,{formState:t,context:n,item:s,responseItems:d},`repeating-group-${s.id}-${c}`):s.type===wt.group?a.jsx(yP,{formState:t,context:n,item:s,responseItem:d[0]},`group-${s.id}-${c}`):s.type===wt.boolean?a.jsx(lp,{formState:t,context:n,item:s,responseItem:d[0],index:0},`boolean-item-${s.id}-${c}`):s.repeats?a.jsx(YK,{formState:t,context:n,item:s,responseItem:d[0]},`repeating-item-${s.id}-${c}`):a.jsx(Ot,{htmlFor:s.linkId,title:s.text,withAsterisk:s.required,children:a.jsx(lp,{formState:t,context:n,item:s,responseItem:d[0],index:0})},`repeating-item-${s.id}-${c}`)})})}function KK(e){const{formState:t,submitButtonText:n,excludeButtons:r,children:o}=e,s=t.pages,c=t.activePage,d=c>0,f=c<s.length-1,p=c===s.length-1;return a.jsxs(a.Fragment,{children:[a.jsx(jc,{active:c,allowNextStepsSelect:!1,p:6,children:s.map((m,g)=>a.jsx(jc.Step,{label:m.title,children:g===c&&o},m.linkId))}),!r&&a.jsxs(ge,{justify:"flex-end",mt:"xl",gap:"xs",children:[d&&a.jsx(ke,{onClick:t.onPrevPage,children:"Back"}),f&&a.jsx(ke,{onClick:m=>{m.currentTarget.closest("form").reportValidity()&&t.onNextPage()},children:"Next"}),p&&a.jsx(ur,{children:n??"Submit"})]})]})}function xP(e){const t=De(),[n,r]=v.useState(!1),o=v.useRef(e);o.current=e;const s=v.useCallback(g=>{r(!1),o.current.onChange?.(g)},[]),c=xF({questionnaire:e.questionnaire,defaultValue:e.questionnaireResponse,subject:e.subject,encounter:e.encounter,source:e.source,disablePagination:e.disablePagination,onChange:s}),d=v.useRef(c);d.current=c;const f=v.useMemo(()=>c.loading?!1:!!mo(c.questionnaire,iF),[c]),p=v.useMemo(()=>c.loading?!1:!!c.questionnaireResponse.extension?.find(g=>g.url===kh),[c]),m=v.useCallback(()=>{const g=d.current;if(g.loading)return;const x=o.current.onSubmit;if(!x)return;if(f&&!p){r(!0);return}const b=g.questionnaire,S=g.questionnaireResponse,j=o.current.subject;let C=o.current.source;if(!C){const R=t.getProfile();R&&(C=qt(R))}x({...S,questionnaire:b.url??At(b),subject:j,source:C,authored:new Date().toISOString(),status:"completed"})},[t,f,p]);return c.loading?null:a.jsxs(ut,{testid:"questionnaire-form",onSubmit:m,children:[c.questionnaire.title&&a.jsx(Oe,{children:c.questionnaire.title}),c.pagination?a.jsx(KK,{formState:c,submitButtonText:e.submitButtonText,excludeButtons:e.excludeButtons,children:a.jsx(dx,{formState:c,context:[],items:c.items,responseItems:c.responseItems})}):a.jsxs(a.Fragment,{children:[a.jsx(dx,{formState:c,context:[],items:c.items,responseItems:c.responseItems}),f&&a.jsxs($e,{mt:"md",gap:0,children:[a.jsx(_e,{size:"sm",fw:500,children:"Signature"}),a.jsx(WK,{onChange:c.onChangeSignature}),!p&&n&&a.jsx(_e,{c:"red",size:"sm",children:"Signature is required."})]}),!e.excludeButtons&&a.jsx(ge,{justify:"flex-end",mt:"xl",gap:"xs",children:a.jsx(ur,{children:e.submitButtonText??"Submit"})})]})]})}const XK="_section_4m5it_1",ZK={section:XK},JK=["gender","age","gestationalAge","context","appliesTo","category"],eX={definition:{resourceType:"ObservationDefinition",code:{text:""}},onSubmit:()=>{}};function tX(e){e=Object.assign(eX,e);const t=e.definition,[n,r]=v.useState([]),[o,s]=v.useState(1),[c,d]=v.useState(1);return v.useEffect(()=>{const S=iX(t,d);r(oX(S.qualifiedInterval||[],s))},[t]),a.jsxs(ut,{testid:"reference-range-editor",onSubmit:f,children:[a.jsx($e,{children:n.map(S=>a.jsx(nX,{unit:sX(t.quantitativeDetails?.unit),onChange:g,onAdd:x,onRemove:b,onRemoveGroup:m,intervalGroup:S},`group-${S.id}`))}),a.jsx(bn,{title:"Add Group",variant:"subtle",size:"sm",onClick:S=>{dn(S),p({id:`group-id-${o}`,filters:{},intervals:[]}),s(j=>j+1)},children:a.jsx(np,{})}),a.jsx(ge,{justify:"flex-end",children:a.jsx(ur,{children:"Save"})})]});function f(){const S=n.flatMap(j=>j.intervals).filter(j=>!lX(j));e.onSubmit({...t,qualifiedInterval:S})}function p(S){r(j=>[...j,S])}function m(S){r(j=>j.filter(C=>C.id!==S.id))}function g(S,j){r(C=>{C=[...C];const R=C.find(T=>T.id===S),E=R?.intervals.findIndex(T=>T.id===j.id);return E!==void 0&&R?.intervals[E]&&(R.intervals[E]=j),C})}function x(S,j){j.id===void 0&&(j.id=`id-${c}`,d(C=>C+1)),r(C=>{C=[...C];const R=C.findIndex(E=>E.id===S);if(R!==-1){const E={...C[R]};j={...j,...E.filters},E.intervals=[...E.intervals,j],C[R]=E}return C})}function b(S,j){r(C=>{C=[...C];const R=C.find(E=>E.id===S);return R&&(R.intervals=R.intervals.filter(E=>E.id!==j.id)),C})}}function nX(e){const{intervalGroup:t,unit:n}=e;return a.jsx(Vc,{"data-testid":t.id,className:ZK.section,children:a.jsxs($e,{gap:"lg",children:[a.jsx(ge,{justify:"flex-end",children:a.jsx(bn,{title:"Remove Group",variant:"subtle","data-testid":`remove-group-button-${t.id}`,size:"sm",onClick:r=>{dn(r),e.onRemoveGroup(t)},children:a.jsx(tp,{})},`remove-group-button-${t.id}`)}),a.jsx(rX,{intervalGroup:t,onChange:e.onChange}),a.jsx(pn,{}),t.intervals.map(r=>a.jsxs($e,{gap:"xs",children:[a.jsxs(ge,{children:[a.jsx(Ue,{"data-testid":`condition-${r.id}`,defaultValue:r.condition,label:"Condition: ",size:"sm",onChange:o=>{dn(o),e.onChange(t.id,{...r,condition:o.currentTarget.value.trim()})}},`condition-${r.id}`),a.jsx(bn,{title:"Remove Interval",variant:"subtle",size:"sm","data-testid":`remove-interval-${r.id}`,onClick:o=>{dn(o),e.onRemove(t.id,r)},children:a.jsx(tp,{})},`remove-interval-${r.id}`)]}),a.jsx(zb,{path:"",onChange:o=>{e.onChange(t.id,{...r,range:o})},name:`range-${r.id}`,defaultValue:r.range},`range-${r.id}`)]},`interval-${r.id}`)),a.jsx(bn,{title:"Add Interval",variant:"subtle",size:"sm",onClick:r=>{dn(r),e.onAdd(t.id,{range:{low:{unit:n},high:{unit:n}}})},children:a.jsx(np,{})})]})})}function rX(e){const{intervalGroup:t,onChange:n}=e;t.filters.age||(t.filters.age={});for(const r of["low","high"])t.filters.age[r]?.unit||(t.filters.age[r]={...t.filters.age[r],unit:"years",system:"http://unitsofmeasure.org"});return a.jsxs($e,{style:{maxWidth:"50%"},children:[a.jsx(ge,{children:a.jsx(sn,{data:["","male","female"],label:"Gender:",defaultValue:t.filters.gender||"",onChange:r=>{for(const o of t.intervals){let s=r.currentTarget.value;s===""&&(s=void 0),n(t.id,{...o,gender:s})}}})}),a.jsxs(ge,{gap:"xs",children:[a.jsx(_e,{component:"label",htmlFor:`div-age-${t.id}`,children:"Age:"}),a.jsx("div",{id:`div-age-${t.id}`,children:a.jsx(zb,{path:"",name:`age-${t.id}`,defaultValue:t.filters.age,onChange:r=>{for(const o of t.intervals)n(t.id,{...o,age:r})}},`age-${t.id}`)})]}),a.jsx(sn,{data:["","pre-puberty","follicular","midcycle","luteal","postmenopausal"],label:"Endocrine:",defaultValue:t.filters.context?.text||"",onChange:r=>{for(const o of t.intervals){let s=r.currentTarget.value;s===""?(s=void 0,n(t.id,{...o,context:void 0})):n(t.id,{...o,context:{text:s,coding:[{code:s,system:"http://terminology.hl7.org/CodeSystem/referencerange-meaning"}]}})}}}),a.jsx(sn,{data:["","reference","critical","absolute"],label:"Category: ",defaultValue:t.filters.category,onChange:r=>{for(const o of t.intervals){const s=r.currentTarget.value;s===""?n(t.id,{...o,category:void 0}):n(t.id,{...o,category:s})}}})]})}function iX(e,t){const n=e.qualifiedInterval||[];let r=Math.max(...n.map(o=>{const s=parseInt(o.id?.substring(3)||"",10);return isNaN(s)?Number.NEGATIVE_INFINITY:s}))+1;return Number.isFinite(r)||(r=1),e={...e,qualifiedInterval:n.map(o=>({...o,id:o.id||`id-${r++}`}))},t(r),e}function oX(e,t){let n=1;const r={};for(const o of e){const s=aX(o);s in r||(r[s]={id:`group-id-${n++}`,filters:Object.fromEntries(JK.map(c=>[c,o[c]])),intervals:[]}),r[s].intervals.push(o)}return t(n),Object.values(r)}function aX(e){return[`gender=${e.gender}`,`age=${ld(e.age)}`,`gestationalAge=${ld(e.gestationalAge)}`,`context=${e.context?.text}`,`appliesTo=${e.appliesTo?.map(n=>n.text).join("+")}`,`category=${e.category}`].join(":")}function sX(e){return e&&(hU(e,"http://unitsofmeasure.org")||e.text)}function lX(e){return e.range?.low?.value===void 0&&e.range?.high?.value===void 0}function cX(e){const t=De(),n=Gt(e.value),[r,o]=v.useState(!1),[s,c]=v.useState();if(v.useEffect(()=>{n&&!r&&(t.executeBatch(d(n)).then(c).catch(console.log),o(!0))},[t,n,r]),!n||!s)return null;return a.jsx(ar,{children:n.action?.map((p,m)=>{const g=p.resource&&f(p.resource),x=g?.input?.[0]?.valueReference,b=g?.output?.[0]?.valueReference;return a.jsxs(v.Fragment,{children:[a.jsx(ar.Col,{span:1,p:"md",children:g?.status==="completed"?a.jsx(iq,{}):a.jsx(jH,{color:"gray"})}),a.jsxs(ar.Col,{span:9,p:"xs",children:[a.jsx(_e,{fw:500,children:p.title}),p.description&&a.jsx("div",{children:p.description}),a.jsxs("div",{children:["Last edited by ",a.jsx(dl,{value:g?.meta?.author})," on ",lr(g?.meta?.lastUpdated)]}),a.jsxs("div",{children:["Status: ",a.jsx(bm,{status:g?.status||"unknown"})]})]}),a.jsxs(ar.Col,{span:2,p:"md",children:[x&&!b&&a.jsx(ke,{onClick:()=>e.onStart(g,x),children:"Start"}),x&&b&&a.jsx(ke,{onClick:()=>e.onEdit(g,x,b),children:"Edit"})]})]},`action-${m}`)})});function d(p){const m=[];if(p.action)for(const g of p.action)g.resource?.reference&&m.push({request:{method:"GET",url:g.resource.reference}});return{resourceType:"Bundle",type:"batch",entry:m}}function f(p){for(const m of s?.entry??[])if(m.resource&&p.reference===At(m.resource))return m.resource}}function bP(e,t){const n=uX(e,t);return dX(n,e,t)}function uX(e,t){const n=e.length,r=t.length,o=n+r+1,s=1+2*o,c=s/2|0,d=new Array(s);d[c+1]={i:0,j:-1,prev:void 0,snake:!0};for(let f=0;f<o;f++){for(let p=-f;p<=f;p+=2){const m=c+p,g=m+1,x=m-1,b=d[g],S=d[x];let j,C=0;p===-f||p!==f&&S.i<b.i?(C=b.i,j=b):(C=S.i+1,j=S),d[x]=void 0;let R=C-p,E={i:C,j:R,prev:fX(j),snake:!1};for(;C<n&&R<r&&e[C]===t[R];)C++,R++;if(C>E.i&&(E={i:C,j:R,prev:E,snake:!0}),d[m]=E,C>=n&&R>=r)return d[m]}d[c+f-1]=void 0}}function dX(e,t,n){const r=[];let o=e;for(o.snake&&(o=o.prev);o?.prev&&o.prev.j>=0;){const s=o.i,c=o.j;o=o.prev;const d=o.i,f=o.j,p={position:d,lines:t.slice(d,s)},m={position:f,lines:n.slice(f,c)};let g;p.lines.length===0&&m.lines.length>0?g="insert":p.lines.length>0&&m.lines.length===0?g="delete":g="change",r.push({original:p,revised:m,type:g}),o.snake&&(o=o.prev)}return r}function fX(e){return e&&!e.snake&&e.prev?e.prev:e}function hX(e){const t=(e.entry??[]).filter(r=>!!r.resource).map(r=>({meta:r.resource?.meta,lines:Ii(r.resource,!0).match(/[^\r\n]+/g)})).sort((r,o)=>r.meta.lastUpdated.localeCompare(o.meta.lastUpdated));if(!t.length)return[];const n=t[0].lines.map(r=>({id:t[0].meta.versionId,meta:t[0].meta,value:r,span:1}));return pX(n,t),mX(n),n}function pX(e,t){for(let n=1;n<t.length;n++){const r=bP(t[n-1].lines,t[n].lines);for(const o of r){const s=o.original.position,c=o.original.lines,d=o.revised.lines;if((o.type==="delete"||o.type==="change")&&e.splice(s,c.length),o.type==="insert"||o.type==="change")for(let f=0;f<o.revised.lines.length;f++)e.splice(s+f,0,{id:t[n].meta.versionId,meta:t[n].meta,value:d[f],span:1})}}}function mX(e){let t=0;for(;t<e.length;){let n=t;for(;n<e.length&&e[n].id===e[t].id;)e[n].span=-1,n++;e[t].span=n-t,t=n}}const gX="_container_1tyf3_1",vX="_root_1tyf3_5",yX="_startRow_1tyf3_20",xX="_normalRow_1tyf3_25",bX="_author_1tyf3_30",SX="_dateTime_1tyf3_34",wX="_lineNumber_1tyf3_40",jX="_line_1tyf3_40",CX="_pre_1tyf3_55",Fo={container:gX,root:vX,startRow:yX,normalRow:xX,author:bX,dateTime:SX,lineNumber:wX,line:jX,pre:CX};function EX(e,t){return`/${e.resourceType}/${e.id}/_history/${t}`}function TX(e){const t=Math.floor((Date.now()-Date.parse(e))/1e3),n=Math.floor(t/31536e3);if(n>0)return ac(n,"year");const r=Math.floor(t/2592e3);if(r>0)return ac(r,"month");const o=Math.floor(t/86400);if(o>0)return ac(o,"day");const s=Math.floor(t/3600);if(s>0)return ac(s,"hour");const c=Math.floor(t/60);return c>0?ac(c,"minute"):ac(t,"second")}function ac(e,t){return`${e} ${e===1?t:t+"s"} ago`}function RX(e){const t=De(),[n,r]=v.useState(e.history);if(v.useEffect(()=>{!e.history&&e.resourceType&&e.id&&t.readHistory(e.resourceType,e.id).then(r).catch(console.log)},[t,e.history,e.resourceType,e.id]),!n)return a.jsx("div",{children:"Loading..."});const o=n.entry?.[0]?.resource;if(!o)return null;const s=hX(n);return a.jsx("div",{className:Fo.container,children:a.jsx("table",{className:Fo.root,children:a.jsx("tbody",{children:s.map((c,d)=>a.jsxs("tr",{className:c.span>0?Fo.startRow:Fo.normalRow,children:[c.span>0&&a.jsxs(a.Fragment,{children:[a.jsx("td",{className:Fo.author,rowSpan:c.span,children:a.jsx(dl,{value:c.meta.author,link:!0,fz:"xs"})}),a.jsx("td",{className:Fo.dateTime,rowSpan:c.span,children:a.jsx(vt,{to:EX(o,c.meta.versionId),fz:"xs",children:TX(c.meta.lastUpdated)})})]}),a.jsx("td",{className:Fo.lineNumber,children:d+1}),a.jsx("td",{className:Fo.line,children:a.jsx("pre",{className:Fo.pre,children:c.value})})]},"row-"+d))})})})}const _X="_removed_el5zk_1",DX="_added_el5zk_6",vT={removed:_X,added:DX};function AX(e){let t=e.original,n=e.revised;e.ignoreMeta&&(t={...t,meta:void 0},n={...n,meta:void 0});const r=Ii(t,!0).match(/[^\r\n]+/g),o=Ii(n,!0).match(/[^\r\n]+/g),s=bP(r,o);return a.jsx("pre",{style:{color:"gray"},children:s.map((c,d)=>a.jsx(PX,{delta:c},"delta"+d))})}function PX(e){return a.jsxs(a.Fragment,{children:["...",a.jsx("br",{}),e.delta.original.lines.length>0&&a.jsx("div",{className:vT.removed,children:e.delta.original.lines.join(`
|
|
556
556
|
`)}),e.delta.revised.lines.length>0&&a.jsx("div",{className:vT.added,children:e.delta.revised.lines.join(`
|
|
@@ -604,4 +604,4 @@ Please change the parent <Route path="${E}"> to <Route path="${E==="/"?"*":`${E}
|
|
|
604
604
|
}
|
|
605
605
|
]
|
|
606
606
|
}`,lne="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 cne(){const e=De(),{id:t}=Bt(),[n,r]=v.useState(),[o,s]=v.useState(),[c,d]=v.useState(sne),[f,p]=v.useState(lne),[m,g]=v.useState(un.FHIR_JSON),x=v.useRef(null),b=v.useRef(null),[S,j]=v.useState(!1);v.useEffect(()=>{e.readResource("Bot",t).then(async A=>{r(A),s(await une(e,A))}).catch(A=>Ne({color:"red",message:Ge(A),autoClose:!1}))},[e,t]);const C=v.useCallback(async()=>Xu(x.current,{command:"getValue"}),[]),R=v.useCallback(async()=>Xu(x.current,{command:"getOutput"}),[]),E=v.useCallback(async()=>m===un.FHIR_JSON?JSON.parse(c):f,[m,c,f]),T=v.useCallback(async A=>{A.preventDefault(),A.stopPropagation(),j(!0);try{const k=await C(),L=await R(),z=await e.createAttachment({data:k,filename:"index.ts",contentType:"text/typescript"}),B=await e.createAttachment({data:L,filename:"index.js",contentType:"text/typescript"}),Z=[{op:"add",path:"/sourceCode",value:z},{op:"add",path:"/executableCode",value:B}];await e.patchResource("Bot",t,Z),Ne({color:"green",message:"Saved"})}catch(k){Ne({color:"red",message:Ge(k),autoClose:!1})}finally{j(!1)}},[e,t,C,R]),_=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:Ge(k),autoClose:!1})}finally{j(!1)}},[e,t]),P=v.useCallback(async A=>{A.preventDefault(),A.stopPropagation(),j(!0);try{const k=await E(),L=await e.post(e.fhirUrl("Bot",t,"$execute"),k,m);await Xu(b.current,{command:"setValue",value:L}),Ne({color:"green",message:"Success"})}catch(k){Ne({color:"red",message:Ge(k),autoClose:!1})}finally{j(!1)}},[e,t,E,m]);return!n||o===void 0?null:a.jsxs(ar,{m:0,gutter:0,style:{overflow:"hidden"},children:[a.jsx(ar.Col,{span:8,children:a.jsxs(yr,{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(ge,{justify:"flex-end",gap:"xs",children:[a.jsx(ke,{type:"button",onClick:T,loading:S,leftSection:a.jsx(xq,{size:"1rem"}),children:"Save"}),a.jsx(ke,{type:"button",onClick:_,loading:S,leftSection:a.jsx(_b,{size:"1rem"}),children:"Deploy"}),a.jsx(ke,{type:"button",onClick:P,loading:S,leftSection:a.jsx(aH,{size:"1rem"}),children:"Execute"})]})]})}),a.jsxs(ar.Col,{span:4,children:[a.jsxs(yr,{m:2,pb:"xs",pr:"xs",pt:"xs",shadow:"md",children:[a.jsx(sn,{data:[{label:"FHIR",value:un.FHIR_JSON},{label:"HL7",value:un.HL7_V2}],onChange:A=>g(A.currentTarget.value)}),m===un.FHIR_JSON?a.jsx(Lc,{value:c,onChange:A=>d(A),autosize:!0,minRows:15}):a.jsx("textarea",{className:ine.hl7Input,value:f,onChange:A=>p(A.currentTarget.value),rows:15})]}),a.jsx(yr,{m:2,p:"xs",shadow:"md",children:a.jsx(one,{iframeRef:b,className:"medplum-bot-output-frame",testId:"output-frame",minHeight:"200px"})})]})]})}async function une(e,t){if(t.sourceCode?.url){const n=t.sourceCode.url?.split("/")?.find(PD);return(await e.download(e.fhirUrl("Binary",n))).text()}return t.code??""}function pl(e){let t=e.meta;return t&&(t={...t,lastUpdated:void 0,versionId:void 0,author:void 0}),{...e,meta:t}}function dne(){const e=De(),{resourceType:t,id:n}=Bt(),r={reference:t+"/"+n},o=v.useCallback(s=>{e.updateResource(pl(s)).then(()=>{Ne({color:"green",message:"Success"})}).catch(c=>{Ne({color:"red",message:Ge(c),autoClose:!1})})},[e]);switch(t){case"PlanDefinition":return a.jsx(lt,{children:a.jsx(sK,{value:r,onSubmit:o})});case"Questionnaire":return a.jsx(lt,{children:a.jsx(MK,{questionnaire:r,onSubmit:o})});default:return null}}function fne(){const{resourceType:e,id:t}=Bt(),n=Gt({reference:e+"/"+t}),r=wn();return n?a.jsx(lt,{children:a.jsx(cX,{value:n,onStart:(o,s)=>r(`/forms/${Hs(s)}`)?.catch(console.error),onEdit:(o,s,c)=>r(`/${c.reference}}`)?.catch(console.error)})}):null}function hne(){const e=De(),{resourceType:t,id:n}=Bt(),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:Ge(o),autoClose:!1}))},children:"Delete"})]})}const pne="_selectProfileBtn_tbaz6_1",mne="_chevron_tbaz6_13",aR={selectProfileBtn:pne,chevron:mne};function gne(){const{resourceType:e,id:t}=Bt(),n=Gt({reference:e+"/"+t}),[r,o]=v.useState(),s=il({onDropdownClose:()=>s.resetSelectedOption()}),c=v.useMemo(()=>{if(Tn(n?.meta?.profile))return[a.jsx(We.Option,{value:"",children:"None"},""),...n.meta.profile.map(f=>a.jsx(We.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 Tn(c)&&(d=a.jsx(ge,{justify:"flex-end",children:a.jsxs($e,{align:"flex-end",gap:"xs",children:[a.jsxs(We,{store:s,width:250,position:"bottom-end",withinPortal:!1,onOptionSubmit:f=>{o(f),s.closeDropdown()},children:[a.jsx(We.Target,{children:a.jsx(er,{onClick:()=>s.toggleDropdown(),children:a.jsxs(Cd,{fw:"bold",fs:"sm",className:aR.selectProfileBtn,children:[a.jsx("span",{children:"Pick profile"}),a.jsx(Rb,{stroke:1.5,className:aR.chevron})]})})}),a.jsx(We.Dropdown,{w:"max-content",children:a.jsx(We.Options,{children:c})})]}),a.jsx(ce,{children:r?a.jsxs(a.Fragment,{children:[a.jsx(_e,{span:!0,size:"sm",c:"dimmed",children:"Displaying profile: "}),a.jsx(_e,{span:!0,size:"sm",children:r||"Nothing selected"})]}):a.jsx(_e,{span:!0,size:"sm",c:"dimmed",children:"No profile displayed"})})]})})),a.jsx(lt,{children:a.jsxs($e,{gap:"xl",children:[d,a.jsx(qb,{value:n,profileUrl:r})]})})}function vne(){const e=De(),{resourceType:t,id:n}=Bt(),[r,o]=v.useState(),[s,c]=v.useState(),d=wn(),[f,p]=v.useState();v.useEffect(()=>{e.readResource(t,n).then(b=>{o(Kr(b)),c(Kr(b))}).catch(b=>{p(Ht(b)),Ne({color:"red",message:Ge(b),autoClose:!1})})},[e,t,n]);const m=v.useCallback(b=>{p(void 0),e.updateResource(pl(b)).then(()=>{d(`/${t}/${n}/details`)?.catch(console.error),Ne({id:"succes",color:"green",message:"Success"})}).catch(S=>{p(Ht(S)),Ne({color:"red",message:Ge(S),autoClose:!1})})},[e,t,n,d]),g=v.useCallback(b=>{p(void 0);const S=JA.createPatch(r,b);e.patchResource(t,n,S).then(()=>{d(`/${t}/${n}/details`)?.catch(console.error),Ne({id:"succes",color:"green",message:"Success"})}).catch(j=>{p(Ht(j)),Ne({color:"red",message:Ge(j),autoClose:!1})})},[e,t,n,r,d]),x=v.useCallback(()=>d(`/${t}/${n}/delete`)?.catch(console.error),[d,t,n]);return s?a.jsx(lt,{children:a.jsx(up,{defaultValue:s,onSubmit:m,onPatch:g,onDelete:x,outcome:f})}):null}function yne(){const{resourceType:e,id:t}=Bt(),n=Gt({reference:e+"/"+t});return n?a.jsx(lt,{maw:700,children:n.resourceType==="Patient"?a.jsx(tK,{patient:n}):a.jsx(oa,{icon:a.jsx(ll,{size:16}),title:"Unsupported export type",color:"red",children:"This page is only supported for Patient resources"})}):null}function uk({resource:e,currentProfile:t,onChange:n}){const r=e.resourceType,o=De(),[s,c]=v.useState();return v.useEffect(()=>{o.searchResources("StructureDefinition",{type:r,derivation:"constraint",_count:50}).then(d=>{c(d.filter(wW))}).catch(console.error)},[o,n,r]),a.jsx(_t,{value:t?.url,onChange:d=>{const f=s?.find(p=>p.url===d);f&&n(f)},children:a.jsx(_t.List,{children:s?.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(_t.Tab,{value:d.url,title:p,rightSection:f&&a.jsx(rb,{variant:"outline",color:"green",size:"xs",style:{borderStyle:"none"},children:a.jsx($H,{size:"90%"})}),children:d.title||d.name},d.url)})})})}function dk(e,t){const n=De(),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(Ht(d)),Ne({color:"red",message:Ge(d),autoClose:!1,styles:{description:{whiteSpace:"pre-line"}}})})}}}function Dy(){const{resourceType:e}=Bt(),t=Lr(),[n,r]=v.useState(),{defaultValue:o,handleSubmit:s}=dk(e,r),[c,d]=v.useState(),f=t.pathname.toLowerCase().endsWith("profiles"),p=v.useCallback(m=>{const g=pl(m);c&&LD(g,c.url),s(g)},[c,s]);return f?a.jsx(lt,{children:a.jsxs($e,{children:[a.jsx(uk,{resource:o,currentProfile:c,onChange:d}),c?a.jsx(up,{defaultValue:o,onSubmit:p,outcome:n,profileUrl:c.url},c.url):a.jsx(_e,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})}):a.jsx(lt,{children:a.jsx(up,{defaultValue:o,onSubmit:s,outcome:n})})}function sR(){const e=De(),{resourceType:t,id:n}=Bt(),r=e.readHistory(t,n).read();return a.jsx(lt,{children:a.jsx(OX,{history:r})})}function xne(){const{resourceType:e}=Bt(),[t,n]=v.useState(),{defaultValue:r,handleSubmit:o}=dk(e,n),s=v.useCallback(c=>{o(JSON.parse(c["new-resource"]))},[o]);return a.jsxs(lt,{children:[t&&a.jsx(dr,{outcome:t}),a.jsxs(ut,{onSubmit:s,children:[a.jsx(Lc,{name:"new-resource","data-testid":"create-resource-json",autosize:!0,minRows:24,defaultValue:Ii(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),a.jsx(ge,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:a.jsx(ke,{type:"submit",children:"OK"})})]})]})}function bne(){const e=De(),{resourceType:t,id:n}=Bt(),r=Gt({reference:t+"/"+n}),o=wn(),[s,c]=v.useState(),d=v.useCallback(f=>{e.updateResource(pl(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:Ge(p),autoClose:!1})})},[e,t,n,o]);return r?a.jsxs(lt,{children:[s&&a.jsx(dr,{outcome:s}),a.jsxs(ut,{onSubmit:d,children:[a.jsx(Lc,{name:"resource","data-testid":"resource-json",autosize:!0,minRows:24,defaultValue:Ii(r,!0),formatOnBlur:!0,deserialize:JSON.parse}),a.jsx(ge,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:a.jsx(ke,{type:"submit",children:"OK"})})]})]}):null}function Sne(){const{resourceType:e,id:t}=Bt();return Gt({reference:e+"/"+t})?a.jsxs(lt,{children:[a.jsxs(oa,{icon:a.jsx(ll,{size:16}),mb:"xl",children:["This is just a preview! Access your form here:",a.jsx("br",{}),a.jsx(Pt,{href:`/forms/${t}`,children:`/forms/${t}`})]}),a.jsx(xP,{questionnaire:{reference:e+"/"+t},onSubmit:()=>alert("You submitted the preview")})]}):null}function wne(){const e=De(),{resourceType:t,id:n}=Bt(),[r,o]=v.useState(),[s,c]=v.useState();return v.useEffect(()=>{e.readResource(t,n).then(d=>o(Kr(d))).catch(d=>{Ne({color:"red",message:Ge(d)})})},[e,t,n]),r?a.jsxs(lt,{children:[a.jsxs(Oe,{order:2,children:["Available ",t," profiles"]}),a.jsx($e,{children:a.jsxs(a.Fragment,{children:[a.jsx(uk,{resource:r,currentProfile:s,onChange:c}),s?a.jsx(jne,{profile:s,resource:r,onResourceUpdated:d=>o(d)},s.url):a.jsx(_e,{my:"lg",fz:"lg",fs:"italic",ta:"center",children:"Select a profile above"})]})})]}):null}const jne=({profile:e,resource:t,onResourceUpdated:n})=>{const r=De(),[o,s]=v.useState(),[c,d]=v.useState(()=>t.meta?.profile?.includes(e.url)),f=v.useCallback(p=>{s(void 0);const m=pl(p);c?LD(m,e.url):xU(m,e.url),r.updateResource(m).then(g=>{n(g),Ne({color:"green",message:"Success"})}).catch(g=>{s(Ht(g)),Ne({color:"red",message:Ge(g),autoClose:!1})})},[r,e.url,n,c]);return a.jsxs($e,{children:[a.jsx(Pd,{size:"md",checked:c,label:`Conform resource to ${e.title}`,onChange:p=>d(p.currentTarget.checked),"data-testid":"profile-toggle"}),c?a.jsx(up,{profileUrl:e.url,defaultValue:t,onSubmit:f,outcome:o}):a.jsx("form",{noValidate:!0,onSubmit:p=>{p.preventDefault(),f(t)},children:a.jsx(ge,{justify:"flex-end",mt:"xl",children:a.jsx(ke,{type:"submit",children:"OK"})})})]})},fk={"Create Only":"create","Update Only":"update","Delete Only":"delete","All Interactions":void 0},Cne=Object.keys(fk);function Ene(){const e=De(),{id:t}=Bt(),n=Gt({reference:`Questionnaire/${t}`}),[r,o]=v.useState(),[s,c]=v.useState("create"),[d,f]=v.useState(0),p=e.searchResources("Subscription","status=active&_count=100").read().filter(g=>Tne(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},${At(n)}`:At(n)}`,channel:{type:"rest-hook",endpoint:At(r)},...s?{extension:[{url:"https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction",valueCode:s}]}:void 0}).then(()=>{o(void 0),f(Date.now()),e.invalidateSearches("Subscription"),Ne({color:"green",message:"Success"})}).catch(g=>Ne({color:"red",message:Ge(g),autoClose:!1}))}return a.jsxs(lt,{children:[a.jsx(Oe,{children:"Bots"}),a.jsxs($e,{children:[p.length===0&&a.jsx("p",{children:"No bots found."}),p.map(g=>a.jsxs("div",{children:[a.jsx("h3",{children:a.jsx(dl,{value:{reference:g.channel?.endpoint},link:!0})}),a.jsxs("p",{children:["Criteria: ",g.criteria]})]},g.id))]}),a.jsx(pn,{}),a.jsxs($e,{mt:10,children:[a.jsx(yd,{size:"lg",htmlFor:"bot",children:"Connect to bot"}),a.jsxs(ge,{children:[a.jsx(ul,{name:"bot",resourceType:"Bot",onChange:g=>o(g)}),a.jsx(ke,{onClick:m,children:"Connect"})]}),a.jsx(ge,{children:a.jsx(sn,{name:"subscription-trigger-event",defaultValue:"Create Only",label:"Subscription Trigger Event",data:Cne,onChange:g=>c(fk[g.target.value])})})]}),a.jsx("div",{style:{display:"none"},children:d})]})}function Tne(e,t){if(!t)return!1;const n=e.criteria||"",r=e.channel?.endpoint||"";return n.startsWith("QuestionnaireResponse?")&&r.startsWith("Bot/")&&(n.includes(At(t))||(t.url?n.includes(t.url):!1))}function Rne(){const{id:e}=Bt(),t=wn(),r=De().readReference({reference:`Questionnaire/${e}`}).read(),[o,s]=v.useState({resourceType:"QuestionnaireResponse",filters:[{code:"questionnaire",operator:ue.EQUALS,value:r.url?`${r.url},Questionnaire/${e}`:`Questionnaire/${e}`}],fields:["id","_lastUpdated"]});return a.jsx(lt,{children:a.jsx(qc,{search:o,onClick:c=>t(`/${c.resource.resourceType}/${c.resource.id}`)?.catch(console.error),onChange:c=>s(c.definition),hideFilters:!0,hideToolbar:!0})})}function _ne(){const e=De(),{resourceType:t,id:n}=Bt(),r=Gt({reference:t+"/"+n}),o=v.useCallback(s=>{e.updateResource(pl(s)).then(()=>{Ne({color:"green",message:"Success"})}).catch(c=>{Ne({color:"red",message:Ge(c),autoClose:!1})})},[e]);return r?a.jsx(lt,{children:a.jsx(tX,{onSubmit:o,definition:r})}):null}function Dne(){const{resourceType:e,id:t}=Bt(),n=Gt({reference:e+"/"+t});return n?a.jsx(lt,{children:e==="MeasureReport"?a.jsx(JY,{measureReport:n}):a.jsx(Fb,{value:n})}):null}const Ane="_container_1ue98_1",Pne="_entry_1ue98_14",kne="_active_1ue98_21",Ay={container:Ane,entry:Pne,active:kne};function Nne(e){const t=De(),n=Gt(e.value),[r,o]=v.useState();return v.useEffect(()=>{if(!n)return;const s=lS(n);if(!s)return;const c="reference"in s?s.reference:At(s);t.search("ServiceRequest","subject="+c).then(d=>{const p=(d.entry??[]).map(m=>m.resource);eP(p),p.reverse(),o(p)}).catch(d=>Ne({color:"red",message:Ge(d),autoClose:!1}))},[t,n]),r?a.jsx("div",{"data-testid":"quick-service-requests",className:Ay.container,children:r.map(s=>a.jsxs("div",{className:It(Ay.entry,{[Ay.active]:s.id===n?.id}),children:[a.jsx("p",{children:a.jsx(vt,{to:s,children:One(s)})}),s.category?.[0]?.text&&a.jsx("p",{children:s.category[0]?.text}),s.code?.coding?.[0]?.code&&a.jsx("p",{children:s.code.coding[0]?.code}),a.jsx("p",{children:Mne(s)})]},s.id))}):null}function One(e){if(e.identifier){for(const t of e.identifier)if(t.value)return t.value}return e.id||""}function Mne(e){return e.authoredOn?e.authoredOn.substring(0,10):e.meta?.lastUpdated?e.meta.lastUpdated.substring(0,10):""}const Lne="_container_1l2dh_1",Ine={container:Lne};function $ne(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:Ine.container,children:a.jsx(sn,{defaultValue:e.defaultValue,onChange:o=>e.onChange(o.currentTarget.value),data:n})})}function zne(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:lr(t.collection?.collectedDateTime)})]}),a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Specimen Age"}),a.jsx(ht.Value,{children:Une(t)})]}),t.collection?.collectedDateTime&&t.receivedTime?a.jsxs(ht.Entry,{children:[a.jsx(ht.Key,{children:"Specimen Stability"}),a.jsx(ht.Value,{children:Bne(t)})]}):a.jsx(a.Fragment,{})]}):null}function Une(e){const t=e.collection?.collectedDateTime;if(!t)return;const n=new Date(t);return hk(pk(n,new Date))}function Bne(e){if(!e.collection?.collectedDateTime||!e.receivedTime)return;const t=new Date(e.collection.collectedDateTime),n=new Date(e.receivedTime);return hk(pk(t,n))}function hk(e){return e.toString().padStart(3,"0")+"D"}function pk(e,t){const n=t.getTime()-e.getTime();return Math.floor(n/(1e3*3600*24))}function Vne(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 Fne(){const e=De(),{resourceType:t,id:n}=Bt(),r={reference:t+"/"+n},o=wn(),[s,c]=v.useState(),d=Gt(r,c),f=Vne(t),[p,m]=v.useState(()=>{const E=window.location.pathname.split("/").pop();return E&&f.map(T=>T.toLowerCase()).includes(E)?E:f[0].toLowerCase()});async function g(){const T=(await e.readHistory(t,n)).entry?.find(_=>!!_.resource)?.resource;T?x(T):Ne({color:"red",message:"No history to restore",autoClose:!1})}function x(E){e.updateResource(pl(E)).then(()=>{c(void 0),Ne({color:"green",message:"Success"})}).catch(T=>{Ne({color:"red",message:Ge(T),autoClose:!1})})}if(s)return Dz(s)?a.jsxs(lt,{children:[a.jsx(Oe,{children:"Deleted"}),a.jsx("p",{children:"The resource was deleted."}),a.jsx(ke,{color:"red",onClick:g,children:"Restore"})]}):a.jsx(dr,{outcome:s});function b(E){E||(E=f[0].toLowerCase()),m(E),o(`/${t}/${n}/${E}`)?.catch(console.error)}function S(E){const T=d,_=T.orderDetail||[];_.length===0&&_.push({}),_[0].text!==E&&(_[0].text=E,x({...T,orderDetail:_}))}const j=d&&lS(d),C=d&&nee(d),R=e.getUserConfiguration()?.option?.find(E=>E.id==="statusValueSet")?.valueString;return a.jsxs(a.Fragment,{children:[d?.resourceType==="ServiceRequest"&&R&&a.jsx($ne,{valueSet:{reference:R},defaultValue:d.orderDetail?.[0]?.text,onChange:S},At(d)+"-"+d.orderDetail?.[0]?.text),d&&a.jsx(Nne,{value:d}),d&&a.jsxs(yr,{children:[j&&a.jsx(cP,{patient:j}),C&&a.jsx(zne,{specimen:C}),t!=="Patient"&&a.jsx(ak,{resource:r}),a.jsx(Zr,{children:a.jsx(_t,{value:p.toLowerCase(),onChange:b,children:a.jsx(_t.List,{style:{whiteSpace:"nowrap",flexWrap:"nowrap"},children:f.map(E=>a.jsx(_t.Tab,{value:E.toLowerCase(),children:E},E))})})})]}),a.jsx(iS,{})]})}function jh(){const e=wn(),{resourceType:t,id:n,versionId:r,tab:o}=Bt(),s=De(),[c,d]=v.useState(!0),[f,p]=v.useState(),[m,g]=v.useState();if(v.useEffect(()=>{g(void 0),d(!0),s.readHistory(t,n).then(T=>p(T)).then(()=>d(!1)).catch(T=>{g(T),d(!1)})},[s,t,n]),c)return a.jsx(yi,{});const x=f?.entry??[],b=x.findIndex(T=>T.resource?.meta?.versionId===r);if(b===-1)return a.jsxs(lt,{children:[a.jsx(Oe,{children:"Version not found"}),a.jsx(vt,{to:`/${t}/${n}`,children:"Return to resource"})]});const S=x[b].resource,j=b<x.length-1?x[b+1].resource:void 0,C="diff",R=o||C,E=x.length-b;return a.jsx(Ed,{maw:1200,children:a.jsx(cl,{children:a.jsxs($e,{gap:"lg",children:[m&&a.jsx("pre",{"data-testid":"error",children:JSON.stringify(m,void 0,2)}),a.jsxs(tm,{cols:2,mb:"lg",children:[a.jsx(ji,{total:x.length,value:E,getControlProps:oP,onChange:T=>e(`/${t}/${n}/_history/${x[x.length-T]?.resource?.meta?.versionId}/${R}`)?.catch(console.error)}),a.jsx(ge,{justify:"right",children:a.jsx(Ad,{data:[{value:"diff",label:"Diff"},{value:"raw",label:"Raw"}],value:R,onChange:T=>e(`/${t}/${n}/_history/${r}/${T||C}`)?.catch(console.error)})})]}),a.jsx(ce,{mb:"lg",children:a.jsxs(vm,{compact:!0,children:[a.jsx(mi,{term:"Version ID",children:S.meta?.versionId}),a.jsx(mi,{term:"Author",children:a.jsx(pc,{value:S.meta?.author,link:!0},S.meta?.author?.reference)}),a.jsx(mi,{term:"Date/Time",children:lr(S.meta?.lastUpdated)})]})}),R==="diff"&&a.jsx(AX,{original:j??{resourceType:t,id:n},revised:S}),R==="raw"&&a.jsx("pre",{style:{fontSize:"9pt"},children:JSON.stringify(S,void 0,2)})]})})})}function qne(){const{resourceType:e,id:t}=Bt(),n=wn(),[r,o]=v.useState({resourceType:"Subscription",filters:[{code:"url",operator:ue.EQUALS,value:`${e}/${t}`}],fields:["id","criteria","status","_lastUpdated"]});return a.jsx(lt,{children:a.jsx(IY,{search:r,onClick:s=>n(`/${s.resource.resourceType}/${s.resource.id}`)?.catch(console.error),onChange:s=>o(s.definition),hideFilters:!0})})}function Hne(e){const t=De(),{resource:n,opened:r,onClose:o}=e,[s,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:s&&d?At(d):void 0,verbose:p}),Ne({color:"green",message:"Done"}),o()}catch(x){Ne({color:"red",message:Ge(x),autoClose:!1})}},[t,n,o,s,d,p]);return a.jsx(In,{opened:r,onClose:o,title:"Resend Subscriptions",children:a.jsx(ut,{onSubmit:g,children:a.jsxs($e,{children:[a.jsx(Dn,{label:"Choose subscription (all subscriptions by default)",onChange:x=>c(x.currentTarget.checked)}),s&&a.jsx(ul,{name:"subscription",resourceType:"Subscription",placeholder:"Subscription",onChange:f}),a.jsx(Dn,{label:"Verbose mode",onChange:x=>m(x.currentTarget.checked)}),a.jsx(ge,{justify:"flex-end",children:a.jsx(ke,{type:"submit",children:"Resend"})})]})})})}function lR(){const e=De(),t=hm(),{resourceType:n,id:r}=Bt(),o={reference:n+"/"+r},[s,c]=v.useState(),d=md(!1);function f(E,T){return e.updateResource({...E,priority:T})}function p(E,T){f(E,"stat").then(T).catch(console.error)}function m(E,T){f(E,"routine").then(T).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 S(E){c(E),d[1].open()}function j(E){t(`/${E.resourceType}/${E.id}/_history/${E.meta?.versionId}`)}function C(E,T){const _="aws-textract";Ne({id:_,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(()=>{T(),Ms({id:_,title:"AWS Textract Successful",message:"Text successfully extracted.",color:"green",icon:a.jsx(vo,{size:"1rem"}),loading:!1,withCloseButton:!0})}).catch(P=>Ms({id:_,title:"AWS Textract Error",color:"red",message:Ge(P),icon:a.jsx(Ys,{size:"1rem"}),loading:!1,withCloseButton:!0}))}function R(E){const{primaryResource:T,currentResource:_,reloadTimeline:P}=E,A=_.resourceType===T.resourceType&&_.id===T.id,k=_.resourceType==="Communication"&&_.priority!=="stat",L=_.resourceType==="Communication"&&_.priority==="stat",z=A,B=!A,Z=!A,K=!A,Y=e.getProjectMembership()?.admin,H=Y,W=Wte()&&(_.resourceType==="DocumentReference"||_.resourceType==="Media");return a.jsxs(Ce.Dropdown,{children:[a.jsx(Ce.Label,{children:"Resource"}),k&&a.jsx(Ce.Item,{leftSection:a.jsx(nH,{size:14}),onClick:()=>p(_,P),"aria-label":`Pin ${At(_)}`,children:"Pin"}),L&&a.jsx(Ce.Item,{leftSection:a.jsx(iH,{size:14}),onClick:()=>m(_,P),"aria-label":`Unpin ${At(_)}`,children:"Unpin"}),B&&a.jsx(Ce.Item,{leftSection:a.jsx(GE,{size:14}),onClick:()=>g(_),"aria-label":`Details ${At(_)}`,children:"Details"}),z&&a.jsx(Ce.Item,{leftSection:a.jsx(GE,{size:14}),onClick:()=>j(_),"aria-label":`Details ${At(_)}`,children:"Details"}),Z&&a.jsx(Ce.Item,{leftSection:a.jsx(vA,{size:14}),onClick:()=>x(_),"aria-label":`Edit ${At(_)}`,children:"Edit"}),Y&&a.jsxs(a.Fragment,{children:[a.jsx(Ce.Divider,{}),a.jsx(Ce.Label,{children:"Admin"}),H&&a.jsx(Ce.Item,{leftSection:a.jsx(fH,{size:14}),onClick:()=>S(_),"aria-label":`Resend Subscriptions ${At(_)}`,children:"Resend Subscriptions"})]}),W&&a.jsxs(a.Fragment,{children:[a.jsx(Ce.Divider,{}),a.jsx(Ce.Label,{children:"AWS AI"}),a.jsx(Ce.Item,{leftSection:a.jsx(PH,{size:14}),onClick:()=>C(_,P),"aria-label":`AWS Textract ${At(_)}`,children:"AWS Textract"})]}),K&&a.jsxs(a.Fragment,{children:[a.jsx(Ce.Divider,{}),a.jsx(Ce.Label,{children:"Danger zone"}),a.jsx(Ce.Item,{color:"red",leftSection:a.jsx(mm,{size:14}),onClick:()=>b(_),"aria-label":`Delete ${At(_)}`,children:"Delete"})]})]})}return a.jsxs(a.Fragment,{children:[n==="Encounter"&&a.jsx(HQ,{encounter:o,getMenu:R}),n==="Patient"&&a.jsx(iK,{patient:o,getMenu:R}),n==="ServiceRequest"&&a.jsx(IX,{serviceRequest:o,getMenu:R}),n!=="Encounter"&&n!=="Patient"&&n!=="ServiceRequest"&&a.jsx(qQ,{resource:o,getMenu:R}),a.jsx(Hne,{resource:s,opened:d[0],onClose:d[1].close},`resend-subscriptions-${s?.id}`)]})}function Gne(e){const{opened:t,close:n,version:r,loadingStatus:o,handleStatus:s,handleUpgrade:c}=e,[d,f]=v.useState(),[p,m]=v.useState(!1);return v.useEffect(()=>{t&&(d||XV("app-tools-page").then(f).catch(console.error),s())},[t,d,s]),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(ge,{children:[a.jsx(ke,{onClick:()=>{c(p),n()},"aria-label":"Confirm upgrade",children:"Confirm Upgrade"}),a.jsx(Dn,{label:"Force",onChange:g=>m(g.currentTarget.checked)})]})]}):a.jsx(yi,{})}function Wne(){const e=De(),{id:t}=Bt(),n=v.useMemo(()=>({reference:"Agent/"+t}),[t]),[r,o]=v.useState(!1),[s,c]=v.useState(!1),[d,f]=v.useState(!1),[p,m]=v.useState(!1),[g,x]=v.useState(),[b,S]=v.useState(),[j,C]=v.useState(),[R,E]=v.useState(),[T,_]=v.useState(!1),[P,A]=v.useState(!1),[k,L]=v.useState(),[z,{open:B,close:Z}]=md(!1);v.useEffect(()=>{if(r||s||d||T){A(!0);return}A(!1)},[r,s,d,T]);const K=v.useCallback(()=>{o(!0),e.get(e.fhirUrl("Agent",t,"$status"),{cache:"reload"}).then(q=>{x(q.parameter?.find(N=>N.name==="status")?.valueCode),S(q.parameter?.find(N=>N.name==="version")?.valueString),C(q.parameter?.find(N=>N.name==="lastUpdated")?.valueInstant)}).catch(q=>$(Ge(q))).finally(()=>o(!1))},[e,t]),Y=v.useCallback(q=>{const N=q.host,F=q.pingCount||1;N&&(_(!0),e.pushToAgent(n,N,`PING ${F}`,un.PING,!0).then(J=>E(J)).catch(J=>$(Ge(J))).finally(()=>_(!1)))},[e,n]),H=v.useCallback(()=>{c(!0),e.get(e.fhirUrl("Agent",t,"$reload-config"),{cache:"reload"}).then(q=>{I("Agent config reloaded successfully.")}).catch(q=>$(Ge(q))).finally(()=>c(!1))},[e,t]),W=v.useCallback(q=>{f(!0),e.get(e.fhirUrl("Agent",t,"$upgrade",`?force=${q}`),{cache:"reload"}).then(N=>{I("Agent upgraded successfully.")}).catch(N=>$(Ge(N))).finally(()=>f(!1))},[e,t]),M=v.useCallback(q=>{m(!0);const N=q.logLimit||20;e.get(e.fhirUrl("Agent",t,`$fetch-logs${N!==void 0?`?limit=${N}`:""}`),{cache:"reload"}).then(F=>{const J=F?.parameter?.find(ae=>ae.name==="logs");J&&L(J?.valueString)}).catch(F=>$(Ge(F))).finally(()=>m(!1))},[e,t]);function I(q){Ne({color:"green",title:"Success",icon:a.jsx(vo,{size:"1rem"}),message:q})}function $(q){Ne({color:"red",title:"Error",message:q,autoClose:!1})}return a.jsxs(lt,{children:[a.jsx(In,{opened:z,onClose:Z,title:"Upgrade Agent",centered:!0,children:a.jsx(Gne,{opened:z,close:Z,version:b,loadingStatus:r,handleStatus:K,handleUpgrade:W})}),a.jsx(Oe,{order:1,children:"Agent Tools"}),a.jsxs("div",{style:{marginBottom:10},children:["Agent: ",a.jsx(dl,{value:n,link:!0})]}),a.jsx(pn,{my:"lg"}),a.jsx(Oe,{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:K,loading:r,disabled:P&&!r,children:"Get Status"}),!r&&g&&a.jsx(de,{children:a.jsxs(de.Tbody,{children:[a.jsxs(de.Tr,{children:[a.jsx(de.Td,{children:"Status"}),a.jsx(de.Td,{children:a.jsx(bm,{status:g})})]}),a.jsxs(de.Tr,{children:[a.jsx(de.Td,{children:"Version"}),a.jsx(de.Td,{children:b})]}),a.jsxs(de.Tr,{children:[a.jsx(de.Td,{children:"Last Updated"}),a.jsx(de.Td,{children:lr(j,void 0,{timeZoneName:"longOffset"})})]})]})}),a.jsx(pn,{my:"lg"}),a.jsx(Oe,{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:s,disabled:P&&!s,"aria-label":"Reload config",children:"Reload Config"}),a.jsx(pn,{my:"lg"}),a.jsx(Oe,{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:B,loading:d,disabled:P&&!d,"aria-label":"Upgrade agent",children:"Upgrade"}),a.jsx(pn,{my:"lg"}),a.jsxs(ut,{onSubmit:M,children:[a.jsx(Oe,{order:2,children:"Fetch Logs"}),a.jsx("p",{children:"Fetch logs from the agent."}),k?.length?a.jsx(Cd,{block:!0,mb:15,children:k}):null,a.jsxs(ge,{children:[a.jsx(wc,{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(Oe,{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(ge,{children:[a.jsx(Ue,{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:T,disabled:P&&!T,children:a.jsx(gH,{style:{width:"1rem",height:"1rem"},stroke:1.5})})}),a.jsx(wc,{id:"pingCount",name:"pingCount",placeholder:"1",label:"Ping Count"})]})}),!T&&R&&a.jsxs(a.Fragment,{children:[a.jsx(Oe,{order:5,mt:"sm",mb:0,children:"Last Ping"}),a.jsx("pre",{children:R})]})]})}function Qne(){const e=wn(),t=De(),[n,r]=v.useState();v.useEffect(()=>{t.get("auth/me",{cache:"no-cache"}).then(r).catch(s=>Ne({color:"red",message:Ge(s),autoClose:!1}))},[t]);function o(s){t.post("auth/revoke",{loginId:s}).then(()=>t.get("auth/me",{cache:"no-cache"})).then(r).then(()=>Ne({color:"green",message:"Login revoked"})).catch(c=>Ne({color:"red",message:Ge(c),autoClose:!1}))}return n?a.jsxs(a.Fragment,{children:[a.jsxs(lt,{children:[a.jsx(Oe,{children:"Security"}),a.jsxs(vm,{children:[a.jsx(mi,{term:"ID",children:a.jsx(Pt,{href:`/${At(n.profile)}`,children:n.profile.id})}),a.jsx(mi,{term:"Resource Type",children:n.profile.resourceType}),a.jsx(mi,{term:"Name",children:Bc(n.profile.name?.[0])})]})]}),a.jsxs(lt,{children:[a.jsx(Oe,{children:"Sessions"}),a.jsxs(de,{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(s=>a.jsxs("tr",{children:[a.jsx("td",{children:s.os}),a.jsx("td",{children:s.browser}),a.jsx("td",{children:s.remoteAddress}),a.jsx("td",{children:s.authMethod}),a.jsx("td",{children:lr(s.lastUpdated)}),a.jsx("td",{children:a.jsx(Pt,{href:"#",onClick:()=>o(s.id),children:"Revoke"})})]},s.id))})]})]}),a.jsxs(lt,{children:[a.jsx(Oe,{children:"Password"}),a.jsx(ke,{onClick:()=>e("/changepassword")?.catch(console.error),children:"Change password"})]}),a.jsxs(lt,{children:[a.jsx(Oe,{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 Yne(){const{id:e,secret:t}=Bt(),n=De(),[r,o]=v.useState(),[s,c]=v.useState(!1),d=Fc(r,void 0);return a.jsxs(lt,{width:450,children:[a.jsx(dr,{issues:d}),a.jsxs(ut,{onSubmit:f=>{if(f.password!==f.confirmPassword){o(io("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(Ht(m)))},children:[a.jsxs(Jn,{style:{flexDirection:"column"},children:[a.jsx(Ci,{size:32}),a.jsx(Oe,{children:"Set password"})]}),!s&&a.jsxs($e,{children:[a.jsx(Oi,{name:"password",label:"New password",required:!0,error:kt(r,"password")}),a.jsx(Oi,{name:"confirmPassword",label:"Confirm new password",required:!0,error:kt(r,"confirmPassword")}),a.jsx(ge,{justify:"flex-end",mt:"xl",children:a.jsx(ke,{type:"submit",children:"Set password"})})]}),s&&a.jsxs("div",{"data-testid":"success",children:["Password set. You can now ",a.jsx(vt,{to:"/signin",children:"sign in"}),"."]})]})]})}function Kne(){const e=pm(),t=wn(),[n]=sS(),r=Wd(),o=v.useCallback(()=>{const s=n.get("next");t(s?.startsWith("/")?s:"/")?.catch(console.error)},[n,t]);return v.useEffect(()=>{e&&n.has("next")&&o()},[e,n,o]),a.jsxs(LA,{onSuccess:()=>o(),onForgotPassword:()=>t("/resetpassword")?.catch(console.error),onRegister:lk()?()=>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(Ci,{size:32}),a.jsx(Oe,{children:"Sign in to Medplum"}),n.get("project")==="new"&&a.jsx("div",{children:"Sign in again to create a new project"})]})}function Xne(){const e=wn(),t=Lr(),[n,r]=v.useState(),[o,s]=v.useState(),[c,d]=v.useState();return v.useEffect(()=>{const f=Object.fromEntries(new URLSearchParams(t.search).entries());r(f.resourceType),s(f.query),d(JSON.parse(f.fields))},[t]),!n||!o||!c?null:a.jsx(FY,{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 Zne(){const{id:e,secret:t}=Bt(),n=De(),[r,o]=v.useState(),[s,c]=v.useState(!1),d=Fc(r,void 0);return a.jsxs(lt,{width:450,children:[a.jsx(dr,{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(Ht(p)))},children:[a.jsxs(Jn,{style:{flexDirection:"column"},children:[a.jsx(Ci,{size:32}),a.jsx(Oe,{children:"Email address verification required"})]}),!s&&a.jsxs($e,{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(ge,{justify:"flex-end",mt:"xl",children:a.jsx(ke,{type:"submit",children:"Verify email"})})]}),s&&a.jsxs("div",{"data-testid":"success",children:["Email verified. You can now ",a.jsx(vt,{to:"/signin",children:"sign in"}),"."]})]})]})}function Jne(){return a.jsx(bJ,{children:a.jsxs(Ie,{errorElement:a.jsx(kte,{}),children:[a.jsx(Ie,{path:"/signin",element:a.jsx(Kne,{})}),a.jsx(Ie,{path:"/oauth",element:a.jsx(Qte,{})}),a.jsx(Ie,{path:"/resetpassword",element:a.jsx(Kte,{})}),a.jsx(Ie,{path:"/setpassword/:id/:secret",element:a.jsx(Yne,{})}),a.jsx(Ie,{path:"/verifyemail/:id/:secret",element:a.jsx(Zne,{})}),a.jsx(Ie,{path:"/register",element:a.jsx(Yte,{})}),a.jsx(Ie,{path:"/changepassword",element:a.jsx(Dte,{})}),a.jsx(Ie,{path:"/security",element:a.jsx(Qne,{})}),a.jsx(Ie,{path:"/mfa",element:a.jsx(Hte,{})}),a.jsx(Ie,{path:"/batch",element:a.jsx(Rte,{})}),a.jsx(Ie,{path:"/bulk/:resourceType",element:a.jsx(_te,{})}),a.jsx(Ie,{path:"/smart",element:a.jsx(Xne,{})}),a.jsx(Ie,{path:"/forms/:id",element:a.jsx(Nte,{})}),a.jsx(Ie,{path:"/admin/super",element:a.jsx(Dee,{})}),a.jsx(Ie,{path:"/admin/super/asyncjob",element:a.jsx(jee,{})}),a.jsx(Ie,{path:"/admin/super/db",element:a.jsx(pee,{})}),a.jsx(Ie,{path:"/admin/config",element:a.jsx(xee,{})}),a.jsxs(Ie,{path:"/admin",element:a.jsx(bee,{}),children:[a.jsx(Ie,{path:"patients",element:a.jsx(yee,{})}),a.jsx(Ie,{path:"bots/new",element:a.jsx(oee,{})}),a.jsx(Ie,{path:"bots",element:a.jsx(ree,{})}),a.jsx(Ie,{path:"clients/new",element:a.jsx(aee,{})}),a.jsx(Ie,{path:"clients",element:a.jsx(iee,{})}),a.jsx(Ie,{path:"details",element:a.jsx(qT,{})}),a.jsx(Ie,{path:"invite",element:a.jsx(vee,{})}),a.jsx(Ie,{path:"users",element:a.jsx(kee,{})}),a.jsx(Ie,{path:"project",element:a.jsx(qT,{})}),a.jsx(Ie,{path:"secrets",element:a.jsx(See,{})}),a.jsx(Ie,{path:"sites",element:a.jsx(wee,{})}),a.jsx(Ie,{path:"members/:membershipId",element:a.jsx(gee,{})})]}),a.jsx(Ie,{path:"/lab/assays",element:a.jsx(Fte,{})}),a.jsx(Ie,{path:"/lab/panels",element:a.jsx(qte,{})}),a.jsxs(Ie,{path:"/:resourceType/new",element:a.jsx(Pte,{}),children:[a.jsx(Ie,{index:!0,element:a.jsx(Dy,{})}),a.jsx(Ie,{path:"form",element:a.jsx(Dy,{})}),a.jsx(Ie,{path:"json",element:a.jsx(xne,{})}),a.jsx(Ie,{path:"profiles",element:a.jsx(Dy,{})})]}),a.jsxs(Ie,{path:"/:resourceType/:id",element:a.jsx(Fne,{}),children:[a.jsx(Ie,{index:!0,element:a.jsx(lR,{})}),a.jsx(Ie,{path:"apply",element:a.jsx(Zte,{})}),a.jsx(Ie,{path:"apps",element:a.jsx(Jte,{})}),a.jsx(Ie,{path:"event",element:a.jsx(tne,{})}),a.jsx(Ie,{path:"blame",element:a.jsx(nne,{})}),a.jsx(Ie,{path:"bots",element:a.jsx(Ene,{})}),a.jsx(Ie,{path:"builder",element:a.jsx(dne,{})}),a.jsx(Ie,{path:"checklist",element:a.jsx(fne,{})}),a.jsx(Ie,{path:"delete",element:a.jsx(hne,{})}),a.jsx(Ie,{path:"details",element:a.jsx(gne,{})}),a.jsx(Ie,{path:"edit",element:a.jsx(vne,{})}),a.jsx(Ie,{path:"editor",element:a.jsx(cne,{})}),a.jsxs(Ie,{path:"history",children:[a.jsx(Ie,{index:!0,element:a.jsx(sR,{})}),a.jsx(Ie,{path:":versionId/:tab",element:a.jsx(jh,{})}),a.jsx(Ie,{path:":versionId",element:a.jsx(jh,{})})]}),a.jsxs(Ie,{path:"_history",children:[a.jsx(Ie,{index:!0,element:a.jsx(sR,{})}),a.jsx(Ie,{path:":versionId/:tab",element:a.jsx(jh,{})}),a.jsx(Ie,{path:":versionId",element:a.jsx(jh,{})})]}),a.jsx(Ie,{path:"json",element:a.jsx(bne,{})}),a.jsx(Ie,{path:"preview",element:a.jsx(Sne,{})}),a.jsx(Ie,{path:"responses",element:a.jsx(Rne,{})}),a.jsx(Ie,{path:"report",element:a.jsx(Dne,{})}),a.jsx(Ie,{path:"ranges",element:a.jsx(_ne,{})}),a.jsx(Ie,{path:"subscriptions",element:a.jsx(qne,{})}),a.jsx(Ie,{path:"timeline",element:a.jsx(lR,{})}),a.jsx(Ie,{path:"tools",element:a.jsx(Wne,{})}),a.jsx(Ie,{path:"profiles",element:a.jsx(wne,{})}),a.jsx(Ie,{path:"export",element:a.jsx(yne,{})})]}),a.jsx(Ie,{path:"/:resourceType",element:a.jsx(iR,{})}),a.jsx(Ie,{path:"/",element:a.jsx(iR,{})})]})})}function ere(){const e=De(),t=e.getUserConfiguration(),n=Lr(),[r]=sS();return e.isLoading()?a.jsx(yi,{}):a.jsx(AG,{logo:a.jsx(Ci,{size:24}),pathname:n.pathname,searchParams:r,version:JD,menus:tre(t),displayAddBookmark:!!t?.id,children:a.jsx(v.Suspense,{fallback:a.jsx(yi,{}),children:a.jsx(Jne,{})})})}function tre(e){const t=e?.menu?.map(n=>({title:n.title,links:n.link?.map(r=>({label:r.name,href:r.target,icon:nre(r.target)}))||[]}))||[];return t.push({title:"Settings",links:[{label:"Security",href:"/security",icon:a.jsx(Vq,{})}]}),t}const cR={Patient:EH,Practitioner:Iq,Organization:eq,ServiceRequest:cH,DiagnosticReport:pH,Questionnaire:Mq,admin:QF,AccessPolicy:Uq,Subscription:MH,batch:eH,Observation:Kq};function nre(e){if(e.includes("admin/super/db"))return a.jsx(vq,{});try{const t=new URL(e,"https://app.medplum.com").pathname.split("/")[1];if(t in cR){const n=cR[t];return a.jsx(n,{})}}catch{}return a.jsx(nm,{w:30})}async function rre(){const e=Wd(),t=new eA({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=qJ([{path:"*",element:a.jsx(ere,{})}]),o=c=>r.navigate(c);FX.createRoot(document.getElementById("root")).render(a.jsx(v.StrictMode,{children:a.jsx(ZV,{medplum:t,navigate:o,children:a.jsxs(OR,{theme:n,children:[a.jsx(la,{position:"bottom-right"}),a.jsx(gJ,{router:r})]})})}))}rre().catch(console.error);
|
|
607
|
-
//# sourceMappingURL=index-
|
|
607
|
+
//# sourceMappingURL=index-DoATk7Yv.js.map
|