UNPKG

fhirclient

Version:

JavaScript client for Fast Healthcare Interoperability Resources

2 lines 55.4 kB
/*! For license information please see fhir-client.pure.min.js.LICENSE.txt */ (()=>{var e={804:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(116),o=r(725),s=r(170),i=r(517),{Response:a}=window,c=n.debug.extend("client");class u extends i.default{constructor(e,t){const r="string"==typeof t?{serverUrl:t}:t;(0,n.assert)(r.serverUrl&&r.serverUrl.match(/https?:\/\/.+/),'A "serverUrl" option is required and must begin with "http(s)"'),super(r.serverUrl),this.units=n.units,this.state=r,this.environment=e,this._refreshTask=null;const o=this;this.patient={get id(){return o.getPatientId()},read:e=>{const t=this.patient.id;return t?this.request({...e,url:`Patient/${t}`}):Promise.reject(new Error("Patient is not available"))},request:(e,t={})=>this.patient.id?(async()=>{const r=await async function(e,t){const r=(0,n.absolute)("/",t.state.serverUrl);async function o(e){const r=e.pathname.split("/").pop();(0,n.assert)(r,`Invalid url "${e}"`),(0,n.assert)(s.patientCompartment.indexOf(r)>-1,`Cannot filter "${r}" resources by patient`);const o=await(0,n.fetchConformanceStatement)(t.state.serverUrl),i=(0,n.getPatientParam)(o,r);return e.searchParams.set(i,t.patient.id),e.href}return"string"==typeof e||e instanceof URL?{url:await o(new URL(e+"",r))}:(e.url=await o(new URL(e.url+"",r)),e)}(e,this);return this.request(r,t)})():Promise.reject(new Error("Patient is not available"))},this.encounter={get id(){return o.getEncounterId()},read:e=>{const t=this.encounter.id;return t?this.request({...e,url:`Encounter/${t}`}):Promise.reject(new Error("Encounter is not available"))}},this.user={get fhirUser(){return o.getFhirUser()},get id(){return o.getUserId()},get resourceType(){return o.getUserType()},read:e=>{const t=this.user.fhirUser;return t?this.request({...e,url:t}):Promise.reject(new Error("User is not available"))}},this.connect(e.fhir)}connect(e){if("function"==typeof e){const t={baseUrl:this.state.serverUrl.replace(/\/$/,"")},r=this.getState("tokenResponse.access_token");if(r)t.auth={token:r};else{const{username:e,password:r}=this.state;e&&r&&(t.auth={user:e,pass:r})}this.api=e(t);const n=this.getState("tokenResponse.patient");n&&(this.patient.api=e({...t,patient:n}))}return this}getPatientId(){const e=this.state.tokenResponse;return e?e.patient?e.patient:((this.state.scope||"").match(/\blaunch(\/patient)?\b/)?c("The ID of the selected patient is not available. Please check if your server supports that."):c(o.default.noScopeForId,"patient","patient"),null):(this.state.authorizeUri?c(o.default.noIfNoAuth,"the ID of the selected patient"):c(o.default.noFreeContext,"selected patient"),null)}getEncounterId(){const e=this.state.tokenResponse;return e?e.encounter?e.encounter:((this.state.scope||"").match(/\blaunch(\/encounter)?\b/)?c("The ID of the selected encounter is not available. Please check if your server supports that, and that the selected patient has any recorded encounters."):c(o.default.noScopeForId,"encounter","encounter"),null):(this.state.authorizeUri?c(o.default.noIfNoAuth,"the ID of the selected encounter"):c(o.default.noFreeContext,"selected encounter"),null)}getIdToken(){const e=this.state.tokenResponse;if(e){const t=e.id_token,r=this.state.scope||"";if(!t){const e=r.match(/\bopenid\b/),t=r.match(/\bprofile\b/),n=r.match(/\bfhirUser\b/);return c(e&&(n||t)?"The id_token is not available. Please check if your server supports that.":"You are trying to get the id_token but you are not using the right scopes. Please add 'openid' and 'fhirUser' or 'profile' to the scopes you are requesting."),null}return(0,n.jwtDecode)(t,this.environment)}return this.state.authorizeUri?c(o.default.noIfNoAuth,"the id_token"):c(o.default.noFreeContext,"id_token"),null}getFhirUser(){const e=this.getIdToken();return e?e.fhirUser?e.fhirUser.split("/").slice(-2).join("/"):e.profile:null}getUserId(){const e=this.getFhirUser();return e?e.split("/")[1]:null}getUserType(){const e=this.getFhirUser();return e?e.split("/")[0]:null}getAuthorizationHeader(){const e=this.getState("tokenResponse.access_token");if(e)return"Bearer "+e;const{username:t,password:r}=this.state;return t&&r?"Basic "+this.environment.btoa(t+":"+r):null}async _clearState(){const e=this.environment.getStorage(),t=await e.get(s.SMART_KEY);t&&await e.unset(t),await e.unset(s.SMART_KEY),this.state.tokenResponse={}}async request(e,t={},r={}){var s;const i=n.debug.extend("client:request");let c;(0,n.assert)(e,"request requires an url or request options as argument"),"string"==typeof e||e instanceof URL?(c=String(e),e={}):c=String(e.url),c=(0,n.absolute)(c,this.state.serverUrl);const u={graph:!1!==t.graph,flat:!!t.flat,pageLimit:null!==(s=t.pageLimit)&&void 0!==s?s:1,resolveReferences:(0,n.makeArray)(t.resolveReferences||[]),useRefreshToken:!1!==t.useRefreshToken,onPage:"function"==typeof t.onPage?t.onPage:void 0},l=e.signal||void 0;u.useRefreshToken&&await this.refreshIfNeeded({signal:l});const h=this.getAuthorizationHeader();let f;return h&&(e.headers={...e.headers,authorization:h}),i("%s, options: %O, fhirOptions: %O",c,e,u),super.fhirRequest(c,e).then((t=>e.includeResponse?(f=t.response,t.body):t)).catch((async e=>{if(401==e.status){if(!this.getState("tokenResponse.access_token"))throw e.message+="\nThis app cannot be accessed directly. Please launch it as SMART app!",e;if(!u.useRefreshToken)throw i("Your session has expired and the useRefreshToken option is set to false. Please re-launch the app."),await this._clearState(),e.message+="\n"+o.default.expired,e;throw i("Auto-refresh failed! Please re-launch the app."),await this._clearState(),e.message+="\n"+o.default.expired,e}throw e})).catch((e=>{throw 403==e.status&&i("Permission denied! Please make sure that you have requested the proper scopes."),e})).then((async t=>!t||"string"==typeof t||t instanceof a?e.includeResponse?{body:t,response:f}:t:(await this.fetchReferences(t,u.resolveReferences,u.graph,r,e),Promise.resolve(t).then((async e=>{if(e&&"Bundle"==e.resourceType){const t=e.link||[];if(u.flat&&(e=(e.entry||[]).map((e=>e.resource))),u.onPage&&await u.onPage(e,{...r}),--u.pageLimit){const o=t.find((e=>"next"==e.relation));if(e=(0,n.makeArray)(e),o&&o.url){const t=await this.request({url:o.url,signal:l},u,r);return u.onPage?null:u.resolveReferences.length?(Object.assign(r,t.references),e.concat((0,n.makeArray)(t.data||t))):e.concat((0,n.makeArray)(t))}}}return e})).then((e=>{if(u.graph)r={};else if(!u.onPage&&u.resolveReferences.length)return{data:e,references:r};return e})).then((t=>e.includeResponse?{body:t,response:f}:t)))))}refreshIfNeeded(e={}){const t=this.getState("tokenResponse.access_token"),r=this.getState("tokenResponse.refresh_token"),n=this.state.expiresAt||0;return t&&r&&n-10<Date.now()/1e3?this.refresh(e):Promise.resolve(this.state)}refresh(e={}){var t,r;const o=n.debug.extend("client:refresh");o("Attempting to refresh with refresh_token...");const s=null===(r=null===(t=this.state)||void 0===t?void 0:t.tokenResponse)||void 0===r?void 0:r.refresh_token;(0,n.assert)(s,"Unable to refresh. No refresh_token found.");const i=this.state.tokenUri;(0,n.assert)(i,"Unable to refresh. No tokenUri found.");const a=this.getState("tokenResponse.scope")||"",c=a.search(/\boffline_access\b/)>-1,u=a.search(/\bonline_access\b/)>-1;if((0,n.assert)(c||u,"Unable to refresh. No offline_access or online_access scope found."),!this._refreshTask){let t=`grant_type=refresh_token&refresh_token=${encodeURIComponent(s)}`;this.environment.options.refreshTokenWithClientId&&(t+=`&client_id=${this.state.clientId}`);const r={credentials:this.environment.options.refreshTokenWithCredentials||"same-origin",...e,method:"POST",mode:"cors",headers:{...e.headers||{},"content-type":"application/x-www-form-urlencoded"},body:t};if(!("authorization"in r.headers)){const{clientSecret:e,clientId:t}=this.state;e&&(r.headers.authorization="Basic "+this.environment.btoa(t+":"+e))}this._refreshTask=(0,n.request)(i,r).then((e=>((0,n.assert)(e.access_token,"No access token received"),o("Received new access token response %O",e),this.state.tokenResponse={...this.state.tokenResponse,...e},this.state.expiresAt=(0,n.getAccessTokenExpiration)(e,this.environment),this.state))).catch((e=>{var t,r;throw(null===(r=null===(t=this.state)||void 0===t?void 0:t.tokenResponse)||void 0===r?void 0:r.refresh_token)&&(o("Deleting the expired or invalid refresh token."),delete this.state.tokenResponse.refresh_token),e})).finally((()=>{this._refreshTask=null;const e=this.state.key;e?this.environment.getStorage().set(e,this.state):o("No 'key' found in Clint.state. Cannot persist the instance.")}))}return this._refreshTask}byCode(e,t){return(0,n.byCode)(e,t)}byCodes(e,t){return(0,n.byCodes)(e,t)}getPath(e,t=""){return(0,n.getPath)(e,t)}getState(e=""){return(0,n.getPath)({...this.state},e)}}t.default=u},517:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(170),o=r(116),s=o.debug.extend("FhirClient");t.default=class{constructor(e){(0,o.assert)(e&&"string"==typeof e&&e.match(/https?:\/\/.+/),'A "fhirBaseUrl" string parameter is required and must begin with "http(s)"'),this.fhirBaseUrl=e}async create(e,t){return this.fhirRequest(e.resourceType,{...t,method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json",...(t||{}).headers}})}async update(e,t){return this.fhirRequest(`${e.resourceType}/${e.id}`,{...t,method:"PUT",body:JSON.stringify(e),headers:{"content-type":"application/json",...(t||{}).headers}})}async delete(e,t={}){return this.fhirRequest(e,{...t,method:"DELETE"})}async patch(e,t,r={}){return(0,o.assertJsonPatch)(t),this.fhirRequest(e,{...r,method:"PATCH",body:JSON.stringify(t),headers:{prefer:"return=presentation","content-type":"application/json-patch+json; charset=UTF-8",...r.headers}})}async resolveRef(e,t,r,n,s={}){const i=(0,o.getPath)(e,t);if(i){const a=Array.isArray(i);return Promise.all((0,o.makeArray)(i).filter(Boolean).map(((i,c)=>{const u=i.reference;if(u)return this.fhirRequest(u,{...s,includeResponse:!1,cacheMap:n}).then((n=>{r&&(a?t.indexOf("..")>-1?(0,o.setPath)(e,`${t.replace("..",`.${c}.`)}`,n):(0,o.setPath)(e,`${t}.${c}`,n):(0,o.setPath)(e,t,n))})).catch((e=>{if(404!==(null==e?void 0:e.status))throw e;console.warn(`Missing reference ${u}. ${e}`)}))})))}}async resolveReferences(e,t,r={}){await this.fetchReferences(e,t,!0,{},r)}async fetchReferences(e,t,r,n={},o={}){if("Bundle"==e.resourceType){for(const s of e.entry||[])s.resource&&await this.fetchReferences(s.resource,t,r,n,o);return n}let i=t.map((e=>String(e).trim())).filter(Boolean);if(i=i.reduce(((e,t)=>(e.includes(t)?s('Duplicated reference path "%s"',t):e.push(t),e)),[]),!i.length)return Promise.resolve(n);const a={};i.forEach((e=>{const t=e.split(".").length;a[t]||(a[t]=[]),a[t].push(e)}));let c=Promise.resolve();return Object.keys(a).sort().forEach((t=>{const s=a[t];c=c.then((()=>Promise.all(s.map((t=>this.resolveRef(e,t,r,n,o))))))})),await c,n}async getReferences(e,t,r={}){const n=await this.fetchReferences(e,t,!1,{},r),o={};for(const e in n)o[e]=await n[e];return o}async*resources(e,t){let r=0;for await(const n of this.pages(e,t))for(const e of n.entry||[]){if((null==t?void 0:t.limit)&&++r>t.limit)return;yield e.resource}}async*pages(e,t){var r,n;const{limit:o,...s}=t||{},i=e=>this.fhirRequest(e,s);let a="string"==typeof e||e instanceof URL?await i(e):e,c=0;for(;a&&"Bundle"===a.resourceType&&(!o||++c<=o)&&(yield a,!(null===(r=null==s?void 0:s.signal)||void 0===r?void 0:r.aborted));){const e=(null!==(n=a.link)&&void 0!==n?n:[]).find((e=>"next"===e.relation&&"string"==typeof e.url));if(!e)break;a=await i(e.url)}}async fhirRequest(e,t={}){(0,o.assert)(t,"fhirRequest requires a uri as first argument");const r=e+"",n=(0,o.absolute)(r,this.fhirBaseUrl),{cacheMap:s}=t;return s?(r in s||(s[r]=(0,o.request)(n,t).then((e=>(s[r]=e,e))).catch((e=>{throw delete s[r],e}))),s[r]):(0,o.request)(n,t)}async getFhirVersion(){return(0,o.fetchConformanceStatement)(this.fhirBaseUrl).then((e=>e.fhirVersion))}async getFhirRelease(){return this.getFhirVersion().then((e=>{var t;return null!==(t=n.fhirVersions[e])&&void 0!==t?t:0}))}}},273:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r extends Error{constructor(e){super(`${e.status} ${e.statusText}\nURL: ${e.url}`),this.name="HttpError",this.response=e,this.statusCode=e.status,this.status=e.status,this.statusText=e.statusText}async parse(){if(!this.response.bodyUsed)try{const e=this.response.headers.get("content-type")||"text/plain";if(e.match(/\bjson\b/i)){let e=await this.response.json();e.error?(this.message+="\n"+e.error,e.error_description&&(this.message+=": "+e.error_description)):this.message+="\n\n"+JSON.stringify(e,null,4)}else if(e.match(/^text\//i)){let e=await this.response.text();e&&(this.message+="\n\n"+e)}}catch{}return this}toJSON(){return{name:this.name,statusCode:this.statusCode,status:this.status,statusText:this.statusText,message:this.message}}}t.default=r},901:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(922),o=r(804),s=r(188),i=r(662),a=r(127);t.default=class{constructor(e={}){this._url=null,this._storage=null,this.security=i,this.options={replaceBrowserHistory:!0,fullSessionStorageSupport:!0,refreshTokenWithCredentials:"same-origin",...e}}relative(e){return new URL(e,this.getUrl().href).href}get fhir(){return"function"==typeof fhir?fhir:null}getUrl(){return this._url||(this._url=new URL(location+"")),this._url}redirect(e){location.href=e}getStorage(){return this._storage||(this._storage=new s.default),this._storage}getAbortController(){return AbortController}atob(e){return window.atob(e)}btoa(e){return window.btoa(e)}base64urlencode(e){return"string"==typeof e?(0,a.encodeURL)(e):(0,a.fromUint8Array)(e,!0)}base64urldecode(e){return(0,a.decode)(e)}getSmartApi(){return{ready:(...e)=>(0,n.ready)(this,...e),authorize:e=>(0,n.authorize)(this,e),init:e=>(0,n.init)(this,e),client:e=>new o.default(this,e),options:this.options,utils:{security:i}}}}},952:(e,t,r)=>{"use strict";const n=r(901),o=r(517),s=new n.default,{ready:i,authorize:a,init:c,client:u,options:l,utils:h}=s.getSmartApi(),f={AbortController:window.AbortController,client:u,FhirClient:o.default,utils:h,oauth2:{settings:l,ready:i,authorize:a,init:c}};e.exports=f},116:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertJsonPatch=t.assert=t.getTargetWindow=t.getPatientParam=t.byCodes=t.byCode=t.getAccessTokenExpiration=t.getTimeInFuture=t.jwtDecode=t.randomString=t.absolute=t.makeArray=t.setPath=t.getPath=t.fetchConformanceStatement=t.getAndCache=t.request=t.loweCaseKeys=t.responseToJSON=t.checkResponse=t.units=t.debug=void 0;const n=r(273),o=r(170),s=r(833),{fetch:i}=window,a=s("FHIR");t.debug=a;const c={};function u({value:e,code:t}){if("number"!=typeof e)throw new Error("Found a non-numerical unit: "+e+" "+t)}async function l(e){if(!e.ok){const t=new n.default(e);throw await t.parse(),t}return e}function h(e){return e.text().then((e=>e.length?JSON.parse(e):""))}function f(e){if(!e)return e;if(Array.isArray(e))return e.map((e=>e&&"object"==typeof e?f(e):e));let t={};return Object.keys(e).forEach((r=>{const n=r.toLowerCase(),o=e[r];t[n]=o&&"object"==typeof o?f(o):o})),t}function p(e,t={}){const{includeResponse:r,...n}=t;return i(e,{mode:"cors",...n,headers:{accept:"application/json",...f(n.headers)}}).then(l).then((e=>{const t=e.headers.get("content-type")+"";return t.match(/\bjson\b/i)?h(e).then((t=>({res:e,body:t}))):t.match(/^text\//i)?e.text().then((t=>({res:e,body:t}))):{res:e}})).then((({res:e,body:t})=>{if(!t&&201==e.status){const t=e.headers.get("location");if(t)return p(t,{...n,method:"GET",body:null,includeResponse:r})}return r?{body:t,response:e}:void 0===t?e:t}))}function d(e,t,r=!1){return r||!c[e]?(c[e]=p(e,t),c[e]):Promise.resolve(c[e])}function g(e,t=""){if(!(t=t.trim()))return e;let r=t.split("."),n=e;for(;n&&r.length;){const e=r.shift();if(!e&&Array.isArray(n))return n.map((e=>g(e,r.join("."))));n=n[e]}return n}function y(e){return Array.isArray(e)?e:[e]}function m(e,t){const r=e.split(".")[1];return r?JSON.parse(t.atob(r)):null}function w(e,t){const r={};function n(e,t){e&&Array.isArray(e.coding)&&e.coding.forEach((({code:e})=>{e&&(r[e]=r[e]||[],r[e].push(t))}))}return y(e).forEach((e=>{"Observation"===e.resourceType&&e[t]&&(Array.isArray(e[t])?e[t].forEach((t=>n(t,e))):n(e[t],e))})),r}function b(e,t){if(!e)throw new Error(t)}t.units={cm({code:e,value:t}){if(u({code:e,value:t}),"cm"==e)return t;if("m"==e)return 100*t;if("in"==e)return 2.54*t;if("[in_us]"==e)return 2.54*t;if("[in_i]"==e)return 2.54*t;if("ft"==e)return 30.48*t;if("[ft_us]"==e)return 30.48*t;throw new Error("Unrecognized length unit: "+e)},kg({code:e,value:t}){if(u({code:e,value:t}),"kg"==e)return t;if("g"==e)return t/1e3;if(e.match(/lb/))return t/2.20462;if(e.match(/oz/))return t/35.274;throw new Error("Unrecognized weight unit: "+e)},any:e=>(u(e),e.value)},t.checkResponse=l,t.responseToJSON=h,t.loweCaseKeys=f,t.request=p,t.getAndCache=d,t.fetchConformanceStatement=function(e="/",t){const r=String(e).replace(/\/*$/,"/")+"metadata";return d(r,t).catch((e=>{throw new Error(`Failed to fetch the conformance statement from "${r}". ${e}`)}))},t.getPath=g,t.setPath=function(e,t,r,n=!1){return t.trim().split(".").reduce(((e,t,o,s)=>{if(!e||o!==s.length-1)return e&&void 0===e[t]&&n&&(e[t]=s[o+1].match(/^[0-9]+$/)?[]:{}),e?e[t]:void 0;e[t]=r}),e),e},t.makeArray=y,t.absolute=function(e,t){return e.match(/^http/)||e.match(/^urn/)?e:String(t||"").replace(/\/+$/,"")+"/"+e.replace(/^\/+/,"")},t.randomString=function(e=8,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"){const r=[],n=t.length;for(;e--;)r.push(t.charAt(Math.floor(Math.random()*n)));return r.join("")},t.jwtDecode=m,t.getTimeInFuture=function(e=120,t){return Math.floor(+(t||new Date)/1e3+e)},t.getAccessTokenExpiration=function(e,t){const r=Math.floor(Date.now()/1e3);if(e.expires_in)return r+e.expires_in;if(e.access_token){let r=m(e.access_token,t);if(r&&r.exp)return r.exp}return r+300},t.byCode=w,t.byCodes=function(e,t){const r=w(e,t);return(...e)=>e.filter((e=>e+""in r)).reduce(((e,t)=>e.concat(r[t+""])),[])},t.getPatientParam=function(e,t){const r=(g(e,"rest.0.resource")||[]).find((e=>e.type===t));if(!r)throw new Error(`Resource "${t}" is not supported by this FHIR server`);if(!Array.isArray(r.searchParam))throw new Error(`No search parameters supported for "${t}" on this FHIR server`);if("Patient"==t&&r.searchParam.find((e=>"_id"==e.name)))return"_id";const n=o.patientParams.find((e=>r.searchParam.find((t=>t.name==e))));if(!n)throw new Error("I don't know what param to use for "+t);return n},t.getTargetWindow=async function(e,t=800,r=720){if("function"==typeof e&&(e=await e()),e&&"object"==typeof e)return e;if("string"!=typeof e)return a("Invalid target type '%s'. Failing back to '_self'.",typeof e),self;if("_self"==e)return self;if("_parent"==e)return parent;if("_top"==e)return top||self;if("_blank"==e){let e,t=null;try{if(t=window.open("","SMARTAuthPopup"),!t)throw new Error("Perhaps window.open was blocked")}catch(t){e=t}return t||(a("Cannot open window. Failing back to '_self'. %s",e),self)}if("popup"==e){let e,n=null;try{if(n=window.open("","SMARTAuthPopup",["height="+r,"width="+t,"menubar=0","resizable=1","status=0","top="+(screen.height-r)/2,"left="+(screen.width-t)/2].join(",")),!n)throw new Error("Perhaps the popup window was blocked")}catch(t){e=t}return n||(a("Cannot open window. Failing back to '_self'. %s",e),self)}return frames[e]||(a("Unknown target '%s'. Failing back to '_self'.",e),self)},t.assert=b,t.assertJsonPatch=function(e){b(Array.isArray(e),"The JSON patch must be an array"),b(e.length>0,"The JSON patch array should not be empty"),e.forEach((e=>{b(["add","replace","test","move","copy","remove"].indexOf(e.op)>-1,'Each patch operation must have an "op" property which must be one of: "add", "replace", "test", "move", "copy", "remove"'),b(e.path&&typeof e.path,`Invalid "${e.op}" operation. Missing "path" property`),"add"==e.op||"replace"==e.op||"test"==e.op?(b("value"in e,`Invalid "${e.op}" operation. Missing "value" property`),b(3==Object.keys(e).length,`Invalid "${e.op}" operation. Contains unknown properties`)):"move"==e.op||"copy"==e.op?(b("string"==typeof e.from,`Invalid "${e.op}" operation. Requires a string "from" property`),b(3==Object.keys(e).length,`Invalid "${e.op}" operation. Contains unknown properties`)):b(2==Object.keys(e).length,`Invalid "${e.op}" operation. Contains unknown properties`)}))}},662:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.signCompactJws=t.importJWK=t.generatePKCEChallenge=t.digestSha256=t.randomBytes=void 0;const n=r(127),o="object"==typeof globalThis&&globalThis.crypto?globalThis.crypto:r(525).default,s=()=>{if(!o.subtle){if(!globalThis.isSecureContext)throw new Error("Some of the required subtle crypto functionality is not available unless you run this app in secure context (using HTTPS or running locally). See https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts");throw new Error("Some of the required subtle crypto functionality is not available in the current environment (no crypto.subtle)")}return o.subtle},i={ES384:{name:"ECDSA",namedCurve:"P-384"},RS384:{name:"RSASSA-PKCS1-v1_5",modulusLength:4096,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-384"}}};function a(e){return o.getRandomValues(new Uint8Array(e))}async function c(e){const t=(new TextEncoder).encode(e),r=await s().digest("SHA-256",t);return new Uint8Array(r)}t.randomBytes=a,t.digestSha256=c,t.generatePKCEChallenge=async(e=96)=>{const t=a(e),r=(0,n.fromUint8Array)(t,!0);return{codeChallenge:(0,n.fromUint8Array)(await c(r),!0),codeVerifier:r}},t.importJWK=async function(e){if(!e.alg)throw new Error('The "alg" property of the JWK must be set to "ES384" or "RS384"');if(Array.isArray(e.key_ops)||(e.key_ops=["sign"]),!e.key_ops.includes("sign"))throw new Error('The "key_ops" property of the JWK does not contain "sign"');try{return await s().importKey("jwk",e,i[e.alg],!0===e.ext,e.key_ops)}catch(t){throw new Error(`The ${e.alg} is not supported by this browser: ${t}`)}},t.signCompactJws=async function(e,t,r,o){const i=JSON.stringify({...r,alg:e}),a=JSON.stringify(o),c=`${(0,n.encodeURL)(i)}.${(0,n.encodeURL)(a)}`,u=await s().sign({...t.algorithm,hash:"SHA-384"},t,(new TextEncoder).encode(c));return`${c}.${(0,n.fromUint8Array)(new Uint8Array(u),!0)}`}},170:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SMART_KEY=t.patientParams=t.fhirVersions=t.patientCompartment=void 0,t.patientCompartment=["Account","AdverseEvent","AllergyIntolerance","Appointment","AppointmentResponse","AuditEvent","Basic","BodySite","BodyStructure","CarePlan","CareTeam","ChargeItem","Claim","ClaimResponse","ClinicalImpression","Communication","CommunicationRequest","Composition","Condition","Consent","Coverage","CoverageEligibilityRequest","CoverageEligibilityResponse","DetectedIssue","DeviceRequest","DeviceUseRequest","DeviceUseStatement","DiagnosticOrder","DiagnosticReport","DocumentManifest","DocumentReference","EligibilityRequest","Encounter","EnrollmentRequest","EpisodeOfCare","ExplanationOfBenefit","FamilyMemberHistory","Flag","Goal","Group","ImagingManifest","ImagingObjectSelection","ImagingStudy","Immunization","ImmunizationEvaluation","ImmunizationRecommendation","Invoice","List","MeasureReport","Media","MedicationAdministration","MedicationDispense","MedicationOrder","MedicationRequest","MedicationStatement","MolecularSequence","NutritionOrder","Observation","Order","Patient","Person","Procedure","ProcedureRequest","Provenance","QuestionnaireResponse","ReferralRequest","RelatedPerson","RequestGroup","ResearchSubject","RiskAssessment","Schedule","ServiceRequest","Specimen","SupplyDelivery","SupplyRequest","VisionPrescription"],t.fhirVersions={"0.4.0":2,"0.5.0":2,"1.0.0":2,"1.0.1":2,"1.0.2":2,"1.1.0":3,"1.4.0":3,"1.6.0":3,"1.8.0":3,"3.0.0":3,"3.0.1":3,"3.3.0":4,"3.5.0":4,"4.0.0":4,"4.0.1":4},t.patientParams=["patient","subject","requester","member","actor","beneficiary"],t.SMART_KEY="SMART_KEY"},922:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.init=t.buildTokenRequest=t.ready=t.onMessage=t.isInPopUp=t.isInFrame=t.authorize=t.getSecurityExtensions=t.fetchWellKnownJson=t.KEY=void 0;const n=r(116),o=r(804),s=r(170);Object.defineProperty(t,"KEY",{enumerable:!0,get:function(){return s.SMART_KEY}});const i=n.debug.extend("oauth2");function a(){return"object"==typeof window}async function c(e="/",t){const r=String(e).replace(/\/*$/,"/")+".well-known/smart-configuration";return(0,n.getAndCache)(r,t).catch((e=>{throw new Error(`Failed to fetch the well-known json "${r}". ${e.message}`)}))}async function u(e="/",t,r){return async function(e="/",t){return c(e,t).then((e=>{if(!e.authorization_endpoint||!e.token_endpoint)throw new Error("Invalid wellKnownJson");return{registrationUri:e.registration_endpoint||"",authorizeUri:e.authorization_endpoint,tokenUri:e.token_endpoint,codeChallengeMethods:e.code_challenge_methods_supported||[]}}))}(e,t).catch((()=>async function(e="/",t){return(0,n.fetchConformanceStatement)(e,t).then((e=>{const t=((0,n.getPath)(e||{},"rest.0.security.extension")||[]).filter((e=>"http://fhir-registry.smarthealthit.org/StructureDefinition/oauth-uris"===e.url)).map((e=>e.extension))[0],r={registrationUri:"",authorizeUri:"",tokenUri:"",codeChallengeMethods:[]};return t&&t.forEach((e=>{"register"===e.url&&(r.registrationUri=e.valueUri),"authorize"===e.url&&(r.authorizeUri=e.valueUri),"token"===e.url&&(r.tokenUri=e.valueUri)})),r}))}(e,r)))}async function l(e,t={}){const r=e.getUrl();if(Array.isArray(t)){const o=r.searchParams.get("iss")||r.searchParams.get("fhirServiceUrl");if(!o)throw new Error('Passing in an "iss" url parameter is required if authorize uses multiple configurations');const s=t.find((e=>{if(e.issMatch){if("function"==typeof e.issMatch)return!!e.issMatch(o);if("string"==typeof e.issMatch)return e.issMatch===o;if(e.issMatch instanceof RegExp)return e.issMatch.test(o)}return!1}));return(0,n.assert)(s,`No configuration found matching the current "iss" parameter "${o}"`),await l(e,s)}const{clientSecret:o,fakeTokenResponse:c,encounterId:d,target:g,width:y,height:m,pkceMode:w,clientPublicKeySetUrl:b,redirect_uri:C,client_id:v}=t;let{iss:S,launch:A,patientId:k,fhirServiceUrl:R,redirectUri:P,noRedirect:U,scope:E="",clientId:_,completeInTarget:x,clientPrivateJwk:F,stateKey:T}=t;const I=e.getStorage();S=r.searchParams.get("iss")||S,R=r.searchParams.get("fhirServiceUrl")||R,A=r.searchParams.get("launch")||A,k=r.searchParams.get("patientId")||k,_=r.searchParams.get("clientId")||_,_||(_=v),P||(P=C),P?P.match(/^https?\:\/\//)||(P=e.relative(P)):P=e.relative(".");const K=String(S||R||"");if(!K)throw new Error("No server url found. It must be specified as `iss` or as `fhirServiceUrl` parameter");if(S&&i("Making %s launch...",A?"EHR":"standalone"),A&&!E.match(/launch/)&&(E+=" launch"),a()){const e=h(),t=f();(e||t)&&!0!==x&&!1!==x&&(x=e,console.warn('Your app is being authorized from within an iframe or popup window. Please be explicit and provide a "completeInTarget" option. Use "true" to complete the authorization in the same window, or "false" to try to complete it in the parent or the opener window. See http://docs.smarthealthit.org/client-js/api.html'))}const j=await I.get(s.SMART_KEY);await I.unset(j),T=null!=T?T:(0,n.randomString)(16);const O={clientId:_,scope:E,redirectUri:P,serverUrl:K,clientSecret:o,clientPrivateJwk:F,tokenResponse:{},key:T,completeInTarget:x,clientPublicKeySetUrl:b};(!a()||(0,n.getPath)(e,"options.fullSessionStorageSupport"))&&await I.set(s.SMART_KEY,T),c&&Object.assign(O.tokenResponse,c),k&&Object.assign(O.tokenResponse,{patient:k}),d&&Object.assign(O.tokenResponse,{encounter:d});let M=P+"?state="+encodeURIComponent(T);if(R&&!S)return i("Making fake launch..."),await I.set(T,O),U?M:await e.redirect(M);const q=await u(K,t.wellKnownRequestOptions,t.conformanceRequestOptions);if(Object.assign(O,q),await I.set(T,O),!O.authorizeUri)return U?M:await e.redirect(M);const B=["response_type=code","client_id="+encodeURIComponent(_||""),"scope="+encodeURIComponent(E),"redirect_uri="+encodeURIComponent(P),"aud="+encodeURIComponent(K),"state="+encodeURIComponent(T)];if(A&&B.push("launch="+encodeURIComponent(A)),function(e,t){if("disabled"===t)return!1;if("unsafeV1"===t)return!0;if("required"===t){if(!e)throw new Error("Required PKCE code challenge method (`S256`) was not found in the server's codeChallengeMethods declaration.");return!0}return e}(q.codeChallengeMethods.includes("S256"),w)){let t=await e.security.generatePKCEChallenge();Object.assign(O,t),await I.set(T,O),B.push("code_challenge="+O.codeChallenge),B.push("code_challenge_method=S256")}if(M=O.authorizeUri+"?"+B.join("&"),U)return M;if(!g||!a())return await e.redirect(M);{let e;if(e=await(0,n.getTargetWindow)(g,y,m),e!==self)try{e.sessionStorage.removeItem(j),e.sessionStorage.setItem(T,JSON.stringify(O))}catch(t){(0,n.debug)('Failed to modify window.sessionStorage. Perhaps it is from different origin?. Failing back to "_self". %s',t),e=self}if(e!==self)try{e.location.href=M,self.addEventListener("message",p)}catch(e){(0,n.debug)('Failed to modify window.location. Perhaps it is from different origin?. Failing back to "_self". %s',e),self.location.href=M}else self.location.href=M}}function h(){try{return self!==top&&parent!==self}catch(e){return!0}}function f(){try{return self===top&&!!opener&&opener!==self&&!!window.name}catch(e){return!1}}function p(e){"completeAuth"==e.data.type&&e.origin===new URL(self.location.href).origin&&(window.removeEventListener("message",p),window.location.href=e.data.url)}async function d(e,t={}){var r,c;const u=e.getUrl(),l=e.getStorage(),p=u.searchParams;let d=p.get("state")||t.stateKey;const y=p.get("code")||t.code,m=p.get("error"),w=p.get("error_description");if(d||(d=await l.get(s.SMART_KEY)),m||w)throw new Error([m,w].filter(Boolean).join(": "));i("key: %s, code: %s",d,y),(0,n.assert)(d,"No 'state' parameter found. Please (re)launch the app.");let b=await l.get(d);const C=!a()||(0,n.getPath)(e,"options.fullSessionStorageSupport");if(a()&&b&&!b.completeInTarget){const e=h(),t=f();if((e||t)&&!u.searchParams.get("complete")){u.searchParams.set("complete","1");const{href:r,origin:n}=u;return e&&parent.postMessage({type:"completeAuth",url:r},n),t&&(opener.postMessage({type:"completeAuth",url:r},n),window.close()),new Promise((()=>{}))}}u.searchParams.delete("complete");const v=!(!p.has("state")&&!t.stateKey);if(a()&&(0,n.getPath)(e,"options.replaceBrowserHistory")&&(y||v)&&(y&&(p.delete("code"),i("Removed code parameter from the url.")),v&&C&&(p.delete("state"),i("Removed state parameter from the url.")),window.history.replaceState&&window.history.replaceState({},"",u.href)),(0,n.assert)(b,"No state found! Please (re)launch the app."),y&&!(null===(r=b.tokenResponse)||void 0===r?void 0:r.access_token)&&b.tokenUri){(0,n.assert)(y,"'code' url parameter is required"),i("Preparing to exchange the code for access token...");const r=await g(e,{code:y,state:b,clientPublicKeySetUrl:t.clientPublicKeySetUrl,privateKey:t.privateKey||b.clientPrivateJwk});i("Token request options: %O",r);const o=await(0,n.request)(b.tokenUri,r);i("Token response: %O",o),(0,n.assert)(o.access_token,"Failed to obtain access token."),b.expiresAt=(0,n.getAccessTokenExpiration)(o,e),b={...b,tokenResponse:o},await l.set(d,b),i("Authorization successful!")}else i((null===(c=b.tokenResponse)||void 0===c?void 0:c.access_token)?"Already authorized":"No authorization needed");C&&await l.set(s.SMART_KEY,d);const S=new o.default(e,b);return i("Created client instance: %O",S),S}async function g(e,{code:t,state:r,clientPublicKeySetUrl:o,privateKey:s}){const{redirectUri:a,clientSecret:c,tokenUri:u,clientId:l,codeVerifier:h}=r;(0,n.assert)(a,"Missing state.redirectUri"),(0,n.assert)(u,"Missing state.tokenUri"),(0,n.assert)(l,"Missing state.clientId");const f={method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:`code=${t}&grant_type=authorization_code&redirect_uri=${encodeURIComponent(a)}`};if(c)f.headers.authorization="Basic "+e.btoa(l+":"+c),i("Using state.clientSecret to construct the authorization header: %s",f.headers.authorization);else if(s){const t="key"in s?s.key:await e.security.importJWK(s),a={typ:"JWT",kid:s.kid,jku:o||r.clientPublicKeySetUrl},c={iss:l,sub:l,aud:u,jti:e.base64urlencode(e.security.randomBytes(32)),exp:(0,n.getTimeInFuture)(120)},h=await e.security.signCompactJws(s.alg,t,a,c);f.body+=`&client_assertion_type=${encodeURIComponent("urn:ietf:params:oauth:client-assertion-type:jwt-bearer")}`,f.body+=`&client_assertion=${encodeURIComponent(h)}`,i("Using state.clientPrivateJwk to add a client_assertion to the POST body")}else i("Public client detected; adding state.clientId to the POST body"),f.body+=`&client_id=${encodeURIComponent(l)}`;return h&&(i("Found state.codeVerifier, adding to the POST body"),f.body+="&code_verifier="+h),f}t.fetchWellKnownJson=c,t.getSecurityExtensions=u,t.authorize=l,t.isInFrame=h,t.isInPopUp=f,t.onMessage=p,t.ready=d,t.buildTokenRequest=g,t.init=async function(e,t,r){const n=e.getUrl(),i=n.searchParams.get("code"),a=n.searchParams.get("state");if(i&&a)return d(e,r);const c=e.getStorage(),u=a||await c.get(s.SMART_KEY),h=await c.get(u);return h?new o.default(e,h):l(e,t).then((()=>new Promise((()=>{}))))}},188:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{async get(e){const t=sessionStorage[e];return t?JSON.parse(t):null}async set(e,t){return sessionStorage[e]=JSON.stringify(t),t}async unset(e){return e in sessionStorage&&(delete sessionStorage[e],!0)}}},725:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={expired:"Session expired! Please re-launch the app",noScopeForId:"Trying to get the ID of the selected %s. Please add 'launch' or 'launch/%s' to the requested scopes and try again.",noIfNoAuth:"You are trying to get %s but the app is not authorized yet.",noFreeContext:"Please don't use open fhir servers if you need to access launch context items like the %S."}},833:(e,t,r)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,o=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(o=n))})),t.splice(o,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(736)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},736:(e,t,r)=>{e.exports=function(e){function t(e){let r,o,s,i=null;function a(...e){if(!a.enabled)return;const n=a,o=Number(new Date),s=o-(r||o);n.diff=s,n.prev=r,n.curr=o,r=o,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,o)=>{if("%%"===r)return"%";i++;const s=t.formatters[o];if("function"==typeof s){const t=e[i];r=s.call(n,t),e.splice(i,1),i--}return r})),t.formatArgs.call(n,e),(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(o!==t.namespaces&&(o=t.namespaces,s=t.enabled(e)),s),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function o(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(o),...t.skips.map(o).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),o=n.length;for(r=0;r<o;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=r(585),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}},127:function(e,t,r){"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==r.g&&r.g,e.exports=function(){"use strict";var e,t="3.7.7",r=t,n="function"==typeof Buffer,o="function"==typeof TextDecoder?new TextDecoder:void 0,s="function"==typeof TextEncoder?new TextEncoder:void 0,i=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),a=(e={},i.forEach((function(t,r){return e[t]=r})),e),c=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,u=String.fromCharCode.bind(String),l="function"==typeof Uint8Array.from?Uint8Array.from.bind(Uint8Array):function(e){return new Uint8Array(Array.prototype.slice.call(e,0))},h=function(e){return e.replace(/=/g,"").replace(/[+\/]/g,(function(e){return"+"==e?"-":"_"}))},f=function(e){return e.replace(/[^A-Za-z0-9\+\/]/g,"")},p=function(e){for(var t,r,n,o,s="",a=e.length%3,c=0;c<e.length;){if((r=e.charCodeAt(c++))>255||(n=e.charCodeAt(c++))>255||(o=e.charCodeAt(c++))>255)throw new TypeError("invalid character found");s+=i[(t=r<<16|n<<8|o)>>18&63]+i[t>>12&63]+i[t>>6&63]+i[63&t]}return a?s.slice(0,a-3)+"===".substring(a):s},d="function"==typeof btoa?function(e){return btoa(e)}:n?function(e){return Buffer.from(e,"binary").toString("base64")}:p,g=n?function(e){return Buffer.from(e).toString("base64")}:function(e){for(var t=[],r=0,n=e.length;r<n;r+=4096)t.push(u.apply(null,e.subarray(r,r+4096)));return d(t.join(""))},y=function(e,t){return void 0===t&&(t=!1),t?h(g(e)):g(e)},m=function(e){if(e.length<2)return(t=e.charCodeAt(0))<128?e:t<2048?u(192|t>>>6)+u(128|63&t):u(224|t>>>12&15)+u(128|t>>>6&63)+u(128|63&t);var t=65536+1024*(e.charCodeAt(0)-55296)+(e.charCodeAt(1)-56320);return u(240|t>>>18&7)+u(128|t>>>12&63)+u(128|t>>>6&63)+u(128|63&t)},w=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,b=function(e){return e.replace(w,m)},C=n?function(e){return Buffer.from(e,"utf8").toString("base64")}:s?function(e){return g(s.encode(e))}:function(e){return d(b(e))},v=function(e,t){return void 0===t&&(t=!1),t?h(C(e)):C(e)},S=function(e){return v(e,!0)},A=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,k=function(e){switch(e.length){case 4:var t=((7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3))-65536;return u(55296+(t>>>10))+u(56320+(1023&t));case 3:return u((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return u((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},R=function(e){return e.replace(A,k)},P=function(e){if(e=e.replace(/\s+/g,""),!c.test(e))throw new TypeError("malformed base64.");e+="==".slice(2-(3&e.length));for(var t,r,n,o="",s=0;s<e.length;)t=a[e.charAt(s++)]<<18|a[e.charAt(s++)]<<12|(r=a[e.charAt(s++)])<<6|(n=a[e.charAt(s++)]),o+=64===r?u(t>>16&255):64===n?u(t>>16&255,t>>8&255):u(t>>16&255,t>>8&255,255&t);return o},U="function"==typeof atob?function(e){return atob(f(e))}:n?function(e){return Buffer.from(e,"base64").toString("binary")}:P,E=n?function(e){return l(Buffer.from(e,"base64"))}:function(e){return l(U(e).split("").map((function(e){return e.charCodeAt(0)})))},_=function(e){return E(F(e))},x=n?function(e){return Buffer.from(e,"base64").toString("utf8")}:o?function(e){return o.decode(E(e))}:function(e){return R(U(e))},F=function(e){return f(e.replace(/[-_]/g,(function(e){return"-"==e?"+":"/"})))},T=function(e){return x(F(e))},I=function(e){return{value:e,enumerable:!1,writable:!0,configurable:!0}},K=function(){var e=function(e,t){return Object.defineProperty(String.prototype,e,I(t))};e("fromBase64",(function(){return T(this)})),e("toBase64",(function(e){return v(this,e)})),e("toBase64URI",(function(){return v(this,!0)})),e("toBase64URL",(function(){return v(this,!0)})),e("toUint8Array",(function(){return _(this)}))},j=function(){var e=function(e,t){return Object.defineProperty(Uint8Array.prototype,e,I(t))};e("toBase64",(function(e){return y(this,e)})),e("toBase64URI",(function(){return y(this,!0)})),e("toBase64URL",(function(){return y(this,!0)}))},O={version:t,VERSION:r,atob:U,atobPolyfill:P,btoa:d,btoaPolyfill:p,fromBase64:T,toBase64:v,encode:v,encodeURI:S,encodeURL:S,utob:b,btou:R,decode:T,isValid:function(e){if("string"!=typeof e)return!1;var t=e.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},fromUint8Array:y,toUint8Array:_,extendString:K,extendUint8Array:j,extendBuiltins:function(){K(),j()},Base64:{}};return Object.keys(O).forEach((function(e){return O.Base64[e]=O[e]})),O}()},585:e=>{var t=1e3,r=60*t,n=60*r,o=24*n,s=7*o;function i(e,t,r,n){var o=t>=1.5*r;return Math.round(e/r)+" "+n+(o?"s":"")}e.exports=function(e,a){a=a||{};var c,u,l=typeof e;if("string"===l&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var i=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(i){var a=parseFloat(i[1]);switch((i[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*s;case"days":case"day":case"d":return a*o;case"hours":case"hour":case"hrs":case"hr":case"h":return a*n;case"minutes":case"minute":case"mins":case"min":case"m":return a*r;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(e);if("number"===l&&isFinite(e))return a.long?(c=e,(u=Math.abs(c))>=o?i(c,u,o,"day"):u>=n?i(c,u,n,"hour"):u>=r?i(c,u,r,"minute"):u>=t?i(c,u,t,"second"):c+" ms"):function(e){var s=Math.abs(e);return s>=o?Math.round(e/o)+"d":s>=n?Math.round(e/n)+"h":s>=r?Math.round(e/r)+"m":s>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},525:(e,t,r)=>{"use strict";r.d(t,{default:()=>n}),r(358);const n=window.crypto},358:()=>{"use strict";var e,t;e="undefined"!=typeof self?self:void 0,t=function(e){if("function"!=typeof Promise)throw"Promise support required";var t=e.crypto||e.msCrypto;if(t){var r=t.subtle||t.webkitSubtle;if(r){var n=e.Crypto||t.constructor||Object,o=e.SubtleCrypto||r.constructor||Object,s=(e.CryptoKey||e.Key,e.navigator.userAgent.indexOf("Edge/")>-1),i=!!e.msCrypto&&!s,a=!t.subtle&&!!t.webkitSubtle;if(i||a){var c={KoZIhvcNAQEB:"1.2.840.113549.1.1.1"},u={"1.2.840.113549.1.1.1":"KoZIhvcNAQEB"};if(["generateKey","importKey","unwrapKey"].forEach((function(e){var n=r[e];r[e]=function(o,s,c){var u,l,b,A,k,R=[].slice.call(arguments);switch(e){case"generateKey":u=g(o),l=s,b=c;break;case"importKey":u=g(c),l=R[3],b=R[4],"jwk"===o&&((s=m(s)).alg||(s.alg=y(u)),s.key_ops||(s.key_ops="oct"!==s.kty?"d"in s?b.filter(S):b.filter(v):b.slice()),R[1]=(A=m(s),i&&(A.extractable=A.ext,delete A.ext),p(unescape(encodeURIComponent(JSON.stringify(A)))).buffer));break;case"unwrapKey":u=R[4],l=R[5],b=R[6],R[2]=c._key}if("generateKey"===e&&"HMAC"===u.name&&u.hash)return u.length=u.length||{"SHA-1":512,"SHA-256":512,"SHA-384":1024,"SHA-512":1024}[u.hash.name],r.importKey("raw",t.getRandomValues(new Uint8Array(u.length+7>>3)),u,l,b);if(a&&"generateKey"===e&&"RSASSA-PKCS1-v1_5"===u.name&&(!u.modulusLength||u.modulusLength>=2048))return(o=g(o)).name="RSAES-PKCS1-v1_5",delete o.hash,r.generateKey(o,!0,["encrypt","decrypt"]).then((function(e){return Promise.all([r.exportKey("jwk",e.publicKey),r.exportKey("jwk",e.privateKey)])})).then((function(e){return e[0].alg=e[1].alg=y(u),e[0].key_ops=b.filter(v),e[1].key_ops=b.filter(S),Promise.all([r.importKey("jwk",e[0],u,!0,e[0].key_ops),r.importKey("jwk",e[1],u,l,e[1].key_ops)])})).then((function(e){return{publicKey:e[0],privateKey:e[1]}}));if((a||i&&"SHA-1"===(u.hash||{}).name)&&"importKey"===e&&"jwk"===o&&"HMAC"===u.name&&"oct"===s.kty)return r.importKey("raw",p(f(s.k)),c,R[3],R[4]);if(a&&"importKey"===e&&("spki"===o||"pkcs8"===o))return r.importKey("jwk",function(e){var t=w(e),r=!1;t.length>2&&(r=!0,t.shift());var n={ext:!0};if("1.2.840.113549.1.1.1"!==t[0][0])throw new TypeError("Unsupported key type");var o=["n","e","d","p","q","dp","dq","qi"],s=w(t[1]);r&&s.shift();for(var i=0;i<s.length;i++)s[i][0]||(s[i]=s[i].subarray(1)),n[o[i]]=h(d(s[i]));return n.kty="RSA",n}(s),c,R[3],R[4]);if(i&&"unwrapKey"===e)return r.decrypt(R[3],c,s).then((function(e){return r.importKey(o,e,R[4],R[5],R[6])}));try{k=n.apply(r,R)}catch(e){return Promise.reject(e)}return i&&(k=new Promise((function(e,t){k.onabort=k.onerror=function(e){t(e)},k.oncomplete=function(t){e(t.target.result)}}))),k=k.then((function(e){return"HMAC"===u.name&&(u.length||(u.length=8*e.algorithm.length)),0==u.name.search("RSA")&&(u.modulusLength||(u.modulusLength=(e.publicKey||e).algorithm.modulusLength),u.publicExponent||(u.publicExponent=(e.publicKey||e).algorithm.publicExponent)),e.publicKey&&e.privateKey?{publicKey:new C(e.publicKey,u,l,b.filter(v)),privateKey:new C(e.privateKey,u,l,b.filter(S))}:new C(e,u,l,b)}))}})),["exportKey","wrapKey"].forEach((function(e){var t=r[e];r[e]=function(n,o,s){var c,u=[].slice.call(arguments);switch(e){case"exportKey":u[1]=o._key;break;case"wrapKey":u[1]=o._key,u[2]=s._key}if((a||i&&"SHA-1"===(o.algorithm.hash||{}).name)&&"exportKey"===e&&"jwk"===n&&"HMAC"===o.algorithm.name&&(u[0]="raw"),!a||"exportKey"!==e||"spki"!==n&&"pkcs8"!==n||(u[0]="jwk"),i&&"wrapKey"===e)return r.exportKey(n,o).then((function(e){return"jwk"===n&&(e=p(unescape(encodeURIComponent(JSON.stringify(m(e)))))),r.encrypt(u[3],s,e)}));try{c=t.apply(r,u)}catch(e){return Promise.reject(e)}return i&&(c=new Promise((function(e,t){c.onabort=c.onerror=function(e){t(e)},c.oncomplete=function(t){e(t.target.result)}}))),"exportKey"===e&&"jwk"===n&&(c=c.then((function(e){return(a||i&&"SHA-1"===(o.algorithm.hash||{}).name)&&"HMAC"===o.algorithm.name?{kty:"oct",alg:y(o.algorithm),key_ops:o.usages.slice(),ext:!0,k:h(d(e))}:((e=m(e)).alg||(e.alg=y(o.algorithm)),e.key_ops||(e.key_ops="public"===o.type?o.usages.filter(v):"private"===o.type?o.usages.filter(S):o.usages.slice()),e)}))),!a||"exportKey"!==e||"spki"!==n&&"pkcs8"!==n||(c=c.then((function(e){return e=function(e){var t,r=[["",null]],n=!1;if("RSA"!==e.kty)throw new TypeError("Unsupported key type");for(var o=["n","e","d","p","q","dp","dq","qi"],s=[],i=0;i<o.length&&o[i]in e;i++){var a=s[i]=p(f(e[o[i]]));128&a[0]&&(s[i]=new Uint8Array(a.length+1),s[i].set(a,1))}return s.length>2&&(n=!0,s.unshift(new Uint8Array([0]))),r[0][0]="1.2.840.113549.1.1.1",t=s,r.push(new Uint8Array(b(t)).buffer),n?r.unshift(new Uint8Array([0])):r[1]={tag:3,value:r[1]},new Uint8Array(b(r)).buffer}(m(e)),e}))),c}})),["encrypt","decrypt","sign","verify"].forEach((function(e){var t=r[e];r[e]=function(n,o,s,a){if(i&&(!s.byteLength||a&&!a.byteLength))throw new Error("Empy input is not allowed");var c,u=[].slice.call(arguments),l=g(n);if(i&&"decrypt"===e&&"AES-GCM"===l.name){var h=n.tagLength>>3;u[2]=(s.buffer||s).slice(0,s.byteLength-h),n.tag=(s.buffer||s).slice(s.byteLength-h)}u[1]=o._key;try{c=t.apply(r,u)}catch(e){return Promise.reject(e)}return i&&(c=new Promi