UNPKG

fhirclient-pkce

Version:

JavaScript client for Fast Healthcare Interoperability Resources

1 lines 114 kB
(()=>{var e={7946:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(3458),a=r(2612),o=r(628),{Response:i}=window,s=n.debug.extend("client");function c(e,t,r,a,o){let i=n.makeArray(t.resolveReferences).filter(Boolean).map((e=>String(e).trim())).filter(Boolean);if(i=i.filter(((e,t)=>!(i.indexOf(e,t+1)>-1&&(s('Duplicated reference path "%s"',e),1)))),!i.length)return Promise.resolve();const c={};i.forEach((e=>{const t=e.split(".").length;c[t]||(c[t]=[]),c[t].push(e)}));let d=Promise.resolve();return Object.keys(c).sort().forEach((i=>{const s=c[i];d=d.then((()=>Promise.all(s.map((i=>function(e,t,r,a,o,i){const s=n.getPath(e,t);if(s){const c=Array.isArray(s);return Promise.all(n.makeArray(s).filter(Boolean).map(((s,d)=>{const u=s.reference;if(u)return function(e,t,r,n){return t[e]||(t[e]=r.request({url:e,signal:n}).then((r=>(t[e]=r,r)),(r=>{throw delete t[e],r}))),Promise.resolve(t[e])}(u,a,o,i).then((a=>{r&&(c?t.indexOf("..")>-1?n.setPath(e,`${t.replace("..",`.${d}.`)}`,a):n.setPath(e,`${t}.${d}`,a):n.setPath(e,t,a))})).catch((e=>{if(404!==e.status)throw e}))})))}}(e,i,!!t.graph,r,a,o))))))})),d}t.default=class{constructor(e,t){this.units=n.units;const r="string"==typeof t?{serverUrl:t}:t;n.assert(r.serverUrl&&r.serverUrl.match(/https?:\/\/.+/),'A "serverUrl" option is required and must begin with "http(s)"'),this.state=r,this.environment=e,this._refreshTask=null;const a=this;this.patient={get id(){return a.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=n.absolute("/",t.state.serverUrl);async function a(e){const r=e.pathname.split("/").pop();n.assert(r,`Invalid url "${e}"`),n.assert(o.patientCompartment.indexOf(r)>-1,`Cannot filter "${r}" resources by patient`);const a=await n.fetchConformanceStatement(t.state.serverUrl),i=n.getPatientParam(a,r);return e.searchParams.set(i,t.patient.id),e.href}return"string"==typeof e||e instanceof URL?{url:await a(new URL(e+"",r))}:(e.url=await a(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 a.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 a.getFhirUser()},get id(){return a.getUserId()},get resourceType(){return a.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/)?s("The ID of the selected patient is not available. Please check if your server supports that."):s(a.default.noScopeForId,"patient","patient"),null):(this.state.authorizeUri?s(a.default.noIfNoAuth,"the ID of the selected patient"):s(a.default.noFreeContext,"selected patient"),null)}getEncounterId(){const e=this.state.tokenResponse;return e?e.encounter?e.encounter:((this.state.scope||"").match(/\blaunch(\/encounter)?\b/)?s("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."):s(a.default.noScopeForId,"encounter","encounter"),null):(this.state.authorizeUri?s(a.default.noIfNoAuth,"the ID of the selected encounter"):s(a.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 s(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 n.jwtDecode(t,this.environment)}return this.state.authorizeUri?s(a.default.noIfNoAuth,"the id_token"):s(a.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(o.SMART_KEY);t&&await e.unset(t),await e.unset(o.SMART_KEY),this.state.tokenResponse={}}create(e,t){return this.request({...t,url:`${e.resourceType}`,method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",...(t||{}).headers}})}update(e,t){return this.request({...t,url:`${e.resourceType}/${e.id}`,method:"PUT",body:JSON.stringify(e),headers:{"Content-Type":"application/json",...(t||{}).headers}})}delete(e,t={}){return this.request({...t,url:e,method:"DELETE"})}async patch(e,t,r={}){return n.assertJsonPatch(t),this.request({...r,url:e,method:"PATCH",body:JSON.stringify(t),headers:{prefer:"return=presentation","content-type":"application/json-patch+json; charset=UTF-8",...r.headers}})}async request(e,t={},r={}){var o;const s=n.debug.extend("client:request");let d;n.assert(e,"request requires an url or request options as argument"),"string"==typeof e||e instanceof URL?(d=String(e),e={}):d=String(e.url),d=n.absolute(d,this.state.serverUrl);const u={graph:!1!==t.graph,flat:!!t.flat,pageLimit:null!==(o=t.pageLimit)&&void 0!==o?o:1,resolveReferences:t.resolveReferences||[],useRefreshToken:!1!==t.useRefreshToken,onPage:"function"==typeof t.onPage?t.onPage:void 0},l=e.signal||void 0;let p;return(u.useRefreshToken?this.refreshIfNeeded({signal:l}).then((()=>e)):Promise.resolve(e)).then((e=>{const t=this.getAuthorizationHeader();return t&&(e.headers={...e.headers,Authorization:t}),e})).then((e=>(s("%s, options: %O, fhirOptions: %O",d,e,u),n.request(d,e).then((t=>e.includeResponse?(p=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 s("Your session has expired and the useRefreshToken option is set to false. Please re-launch the app."),await this._clearState(),e.message+="\n"+a.default.expired,e;throw s("Auto-refresh failed! Please re-launch the app."),await this._clearState(),e.message+="\n"+a.default.expired,e}throw e})).catch((e=>{throw 403==e.status&&s("Permission denied! Please make sure that you have requested the proper scopes."),e})).then((t=>t?"string"==typeof t||t instanceof i?t:(async e=>("Bundle"==e.resourceType?await Promise.all((e.entry||[]).map((e=>c(e.resource,u,r,this,l)))):await c(e,u,r,this,l),e))(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 a=t.find((e=>"next"==e.relation));if(e=n.makeArray(e),a&&a.url){const t=await this.request({url:a.url,signal:l},u,r);return u.onPage?null:u.resolveReferences.length?(Object.assign(r,t.references),e.concat(n.makeArray(t.data||t))):e.concat(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:p}:t)):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 a=n.debug.extend("client:refresh");a("Attempting to refresh with refresh_token...");const o=null===(r=null===(t=this.state)||void 0===t?void 0:t.tokenResponse)||void 0===r?void 0:r.refresh_token;n.assert(o,"Unable to refresh. No refresh_token found.");const i=this.state.tokenUri;n.assert(i,"Unable to refresh. No tokenUri found.");const s=this.getState("tokenResponse.scope")||"",c=s.search(/\boffline_access\b/)>-1,d=s.search(/\bonline_access\b/)>-1;if(n.assert(c||d,"Unable to refresh. No offline_access or online_access scope found."),!this._refreshTask){const t={credentials:this.environment.options.refreshTokenWithCredentials||"same-origin",...e,method:"POST",mode:"cors",headers:{...e.headers||{},"content-type":"application/x-www-form-urlencoded"},body:`grant_type=refresh_token&refresh_token=${encodeURIComponent(o)}`};if(!("authorization"in t.headers)){const{clientSecret:e,clientId:r}=this.state;e&&(t.headers.authorization="Basic "+this.environment.btoa(r+":"+e))}this._refreshTask=n.request(i,t).then((e=>(n.assert(e.access_token,"No access token received"),a("Received new access token response %O",e),Object.assign(this.state.tokenResponse,e),this.state.expiresAt=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)&&(a("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):a("No 'key' found in Clint.state. Cannot persist the instance.")}))}return this._refreshTask}byCode(e,t){return n.byCode(e,t)}byCodes(e,t){return n.byCodes(e,t)}getPath(e,t=""){return n.getPath(e,t)}getState(e=""){return n.getPath({...this.state},e)}getFhirVersion(){return n.fetchConformanceStatement(this.state.serverUrl).then((e=>e.fhirVersion))}getFhirRelease(){return this.getFhirVersion().then((e=>{var t;return null!==(t=o.fhirVersions[e])&&void 0!==t?t:0}))}}},5685:(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},2254:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(9349),a=r(7946),o=r(5424);t.default=class{constructor(e={}){this._url=null,this._storage=null,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 o.default),this._storage}getAbortController(){return AbortController}atob(e){return window.atob(e)}btoa(e){return window.btoa(e)}getSmartApi(){return{ready:(...e)=>n.ready(this,...e),authorize:e=>n.authorize(this,e),init:e=>n.init(this,e),client:e=>new a.default(this,e),options:this.options}}}},1769:(e,t,r)=>{"use strict";const n=new(r(2254).default),{ready:a,authorize:o,init:i,client:s,options:c}=n.getSmartApi(),d={AbortController:window.AbortController,client:s,oauth2:{settings:c,ready:a,authorize:o,init:i}};e.exports=d},3458:(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.responseToJSON=t.checkResponse=t.units=t.debug=void 0;const n=r(5685),a=r(628),o=r(1227),{fetch:i}=window,s=o("FHIR");t.debug=s;const c={};function d({value:e,code:t}){if("number"!=typeof e)throw new Error("Found a non-numerical unit: "+e+" "+t)}async function u(e){if(!e.ok){const t=new n.default(e);throw await t.parse(),t}return e}function l(e){return e.text().then((e=>e.length?JSON.parse(e):""))}function p(e,t={}){const{includeResponse:r,...n}=t;return i(e,{mode:"cors",...n,headers:{accept:"application/json",...n.headers}}).then(u).then((e=>{const t=e.headers.get("Content-Type")+"";return t.match(/\bjson\b/i)?l(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 h(e,t,r=!1){return r||!c[e]?(c[e]=p(e,t),c[e]):Promise.resolve(c[e])}function f(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=>f(e,r.join("."))));n=n[e]}return n}function y(e){return Array.isArray(e)?e:[e]}function w(e,t){const r=e.split(".")[1];return r?JSON.parse(t.atob(r)):null}function g(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 m(e,t){if(!e)throw new Error(t)}t.units={cm({code:e,value:t}){if(d({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(d({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=>(d(e),e.value)},t.checkResponse=u,t.responseToJSON=l,t.request=p,t.getAndCache=h,t.fetchConformanceStatement=function(e="/",t){const r=String(e).replace(/\/*$/,"/")+"metadata";return h(r,t).catch((e=>{throw new Error(`Failed to fetch the conformance statement from "${r}". ${e}`)}))},t.getPath=f,t.setPath=function(e,t,r,n=!1){return t.trim().split(".").reduce(((e,t,a,o)=>{if(!e||a!==o.length-1)return e&&void 0===e[t]&&n&&(e[t]=o[a+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=w,t.getTimeInFuture=function(e=120,t=new Date){return Math.floor(t.getTime()/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=w(e.access_token,t);if(r&&r.exp)return r.exp}return r+300},t.byCode=g,t.byCodes=function(e,t){const r=g(e,t);return(...e)=>e.filter((e=>e+""in r)).reduce(((e,t)=>e.concat(r[t+""])),[])},t.getPatientParam=function(e,t){const r=(f(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=a.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 s("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;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||(s("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||(s("Cannot open window. Failing back to '_self'. %s",e),self)}return frames[e]||(s("Unknown target '%s'. Failing back to '_self'.",e),self)},t.assert=m,t.assertJsonPatch=function(e){m(Array.isArray(e),"The JSON patch must be an array"),m(e.length>0,"The JSON patch array should not be empty"),e.forEach((e=>{m(["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"'),m(e.path&&typeof e.path,`Invalid "${e.op}" operation. Missing "path" property`),"add"==e.op||"replace"==e.op||"test"==e.op?(m("value"in e,`Invalid "${e.op}" operation. Missing "value" property`),m(3==Object.keys(e).length,`Invalid "${e.op}" operation. Contains unknown properties`)):"move"==e.op||"copy"==e.op?(m("string"==typeof e.from,`Invalid "${e.op}" operation. Requires a string "from" property`),m(3==Object.keys(e).length,`Invalid "${e.op}" operation. Contains unknown properties`)):m(2==Object.keys(e).length,`Invalid "${e.op}" operation. Contains unknown properties`)}))}},1405:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.signCompactJws=t.importKey=t.generatePKCEChallenge=t.randomBytes=t.digestSha256=t.base64urlencode=t.base64urldecode=void 0;const n=r(7277),a=n.base64url.encode;t.base64urlencode=a;const o=n.base64url.decode;let i;t.base64urldecode=o,i=window.crypto.subtle,t.digestSha256=async e=>{let t;t="string"==typeof e?(new TextEncoder).encode(e).buffer:e;const r=await i.digest("SHA-256",t);return new Uint8Array(r)},t.randomBytes=e=>{var t;return"undefined"!=typeof window&&(null===(t=null===window||void 0===window?void 0:window.crypto)||void 0===t?void 0:t.getRandomValues)?window.crypto.getRandomValues(new Uint8Array(e)):(void 0)(e)},t.generatePKCEChallenge=async(e=96)=>{const r=t.randomBytes(e),n=a(r);return{codeChallenge:a(await t.digestSha256(n)),codeVerifier:n}},t.importKey=async e=>n.importJWK(e),t.signCompactJws=async(e,t,r,a)=>new n.SignJWT(a).setProtectedHeader({...r,alg:e}).sign(t)},628:(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"},9349:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.init=t.ready=t.buildTokenRequest=t.completeAuth=t.onMessage=t.isInPopUp=t.isInFrame=t.authorize=t.getSecurityExtensions=t.fetchWellKnownJson=t.KEY=void 0;const n=r(3458),a=r(7946),o=r(628);Object.defineProperty(t,"KEY",{enumerable:!0,get:function(){return o.SMART_KEY}});const i=r(1405),s=n.debug.extend("oauth2");function c(){return"object"==typeof window}function d(e="/",t){const r=String(e).replace(/\/*$/,"/")+".well-known/smart-configuration";return n.getAndCache(r,t).catch((e=>{throw new Error(`Failed to fetch the well-known json "${r}". ${e.message}`)}))}function u(e,t="/"){return console.log("Getting sec extension",t),function(e="/",t){return d(e,void 0).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||["S256"]}}))}(t).catch((e=>function(e="/",t){return n.fetchConformanceStatement(e,t).then((e=>{const t=(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:["S256"]};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}))}(t)))}async function l(e,t={}){const r=e.getUrl();if(Array.isArray(t)){const a=r.searchParams.get("iss")||r.searchParams.get("fhirServiceUrl");if(!a)throw new Error('Passing in an "iss" url parameter is required if authorize uses multiple configurations');const o=t.find((e=>{if(e.issMatch){if("function"==typeof e.issMatch)return!!e.issMatch(a);if("string"==typeof e.issMatch)return e.issMatch===a;if(e.issMatch instanceof RegExp)return e.issMatch.test(a)}return!1}));return n.assert(o,`No configuration found matching the current "iss" parameter "${a}"`),await l(e,o)}const{redirect_uri:a,clientSecret:d,clientPrivateJwk:y,fakeTokenResponse:w,patientId:g,encounterId:m,client_id:S,target:E,width:v,height:A,pkceMode:b}=t;let{iss:C,launch:_,fhirServiceUrl:J,redirectUri:P,noRedirect:k,scope:W="",clientId:K,completeInTarget:H}=t;const I=e.getStorage();C=r.searchParams.get("iss")||C,J=r.searchParams.get("fhirServiceUrl")||J,_=r.searchParams.get("launch")||_,K||(K=S),P||(P=a),P?P.match(/^https?\:\/\//)||(P=e.relative(P)):P=e.relative(".");const T=String(C||J||"");if(!T)throw new Error("No server url found. It must be specified as `iss` or as `fhirServiceUrl` parameter");if(C&&s("Making %s launch...",_?"EHR":"standalone"),_&&!W.match(/launch/)&&(W+=" launch"),c()){const e=p(),t=h();(e||t)&&!0!==H&&!1!==H&&(H=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 R=await I.get(o.SMART_KEY);await I.unset(R);const U=n.randomString(16),O={clientId:K,scope:W,redirectUri:P,serverUrl:T,clientSecret:d,clientPrivateJwk:y,tokenResponse:{},key:U,completeInTarget:H};(!c()||n.getPath(e,"options.fullSessionStorageSupport"))&&await I.set(o.SMART_KEY,U),w&&Object.assign(O.tokenResponse,w),g&&Object.assign(O.tokenResponse,{patient:g}),m&&Object.assign(O.tokenResponse,{encounter:m});let D=P+"?state="+encodeURIComponent(U);if(J&&!C)return s("Making fake launch..."),await I.set(U,O),k?D:await e.redirect(D);const x=await u(0,T);if(Object.assign(O,x),await I.set(U,O),!O.authorizeUri)return k?D:await e.redirect(D);const M=["response_type=code","client_id="+encodeURIComponent(K||""),"scope="+encodeURIComponent(W),"redirect_uri="+encodeURIComponent(P),"aud="+encodeURIComponent(T),"state="+encodeURIComponent(U)];if(_&&M.push("launch="+encodeURIComponent(_)),"required"===b&&!x.codeChallengeMethods.includes("S256"))throw new Error("Required PKCE code challenge method (`S256`) was not found.");if("disabled"!==b&&x.codeChallengeMethods.includes("S256")){let e=await i.generatePKCEChallenge();Object.assign(O,e),await I.set(U,O),M.push("code_challenge="+O.codeChallenge),M.push("code_challenge_method=S256")}if(D=O.authorizeUri+"?"+M.join("&"),k)return D;if(!E||!c())return await e.redirect(D);{let e;if(e=await n.getTargetWindow(E,v,A),e!==self)try{e.sessionStorage.removeItem(R),e.sessionStorage.setItem(U,JSON.stringify(O))}catch(t){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=D,self.addEventListener("message",f)}catch(e){n.debug('Failed to modify window.location. Perhaps it is from different origin?. Failing back to "_self". %s',e),self.location.href=D}else self.location.href=D}}function p(){try{return self!==top&&parent!==self}catch(e){return!0}}function h(){try{return self===top&&!!opener&&opener!==self&&!!window.name}catch(e){return!1}}function f(e){"completeAuth"==e.data.type&&e.origin===new URL(self.location.href).origin&&(window.removeEventListener("message",f),window.location.href=e.data.url)}async function y(e){var t,r;const i=e.getUrl(),d=e.getStorage(),u=i.searchParams;let l=u.get("state");const f=u.get("code"),y=u.get("error"),g=u.get("error_description");if(l||(l=await d.get(o.SMART_KEY)),y||g)throw new Error([y,g].filter(Boolean).join(": "));s("key: %s, code: %s",l,f),n.assert(l,"No 'state' parameter found. Please (re)launch the app.");let m=await d.get(l);const S=!c()||n.getPath(e,"options.fullSessionStorageSupport");if(c()&&m&&!m.completeInTarget){const e=p(),t=h();if((e||t)&&!i.searchParams.get("complete")){i.searchParams.set("complete","1");const{href:r,origin:n}=i;return e&&parent.postMessage({type:"completeAuth",url:r},n),t&&(opener.postMessage({type:"completeAuth",url:r},n),window.close()),new Promise((()=>{}))}}i.searchParams.delete("complete");const E=u.has("state");if(c()&&n.getPath(e,"options.replaceBrowserHistory")&&(f||E)&&(f&&(u.delete("code"),s("Removed code parameter from the url.")),E&&S&&(u.delete("state"),s("Removed state parameter from the url.")),window.history.replaceState&&window.history.replaceState({},"",i.href)),n.assert(m,"No state found! Please (re)launch the app."),f&&!(null===(t=m.tokenResponse)||void 0===t?void 0:t.access_token)&&m.tokenUri){n.assert(f,"'code' url parameter is required"),s("Preparing to exchange the code for access token...");const t=await w(e,f,m);s("Token request options: %O",t);const r=await n.request(m.tokenUri,t);s("Token response: %O",r),n.assert(r.access_token,"Failed to obtain access token."),m.expiresAt=n.getAccessTokenExpiration(r,e),m={...m,tokenResponse:r},await d.set(l,m),s("Authorization successful!")}else s((null===(r=m.tokenResponse)||void 0===r?void 0:r.access_token)?"Already authorized":"No authorization needed");S&&await d.set(o.SMART_KEY,l);const v=new a.default(e,m);return s("Created client instance: %O",v),v}async function w(e,t,r){const{redirectUri:a,clientSecret:o,clientPublicKeySetUrl:c,clientPrivateJwk:d,tokenUri:u,clientId:l,codeVerifier:p}=r;n.assert(a,"Missing state.redirectUri"),n.assert(u,"Missing state.tokenUri"),n.assert(l,"Missing state.clientId");const h={method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:`code=${t}&grant_type=authorization_code&redirect_uri=${encodeURIComponent(a)}`};if(o)h.headers.Authorization="Basic "+e.btoa(l+":"+o),s("Using state.clientSecret to construct the authorization header: %s",h.headers.Authorization);else if(d){const e=await i.importKey(d),t={typ:"JWT",kid:d.kid,jku:c},r={iss:l,sub:l,aud:u,jti:i.base64urlencode(i.randomBytes(32)),exp:n.getTimeInFuture(120)},a=await i.signCompactJws(d.alg,e,t,r);h.body+=`&client_assertion_type=${encodeURIComponent("urn:ietf:params:oauth:client-assertion-type:jwt-bearer")}`,h.body+=`&client_assertion=${encodeURIComponent(a)}`,s("Using state.clientPrivateJwk to add a client_assertion to the POST body")}else s("Public client detected; adding state.clientId to the POST body"),h.body+=`&client_id=${encodeURIComponent(l)}`;return p&&(s("Found state.codeVerifier, adding to the POST body"),h.body+="&code_verifier="+p),h}t.fetchWellKnownJson=d,t.getSecurityExtensions=u,t.authorize=l,t.isInFrame=p,t.isInPopUp=h,t.onMessage=f,t.completeAuth=y,t.buildTokenRequest=w,t.ready=async function(e,t,r){let n=y(e);return t&&(n=n.then(t)),r&&(n=n.catch(r)),n},t.init=async function(e,t){const r=e.getUrl(),n=r.searchParams.get("code"),i=r.searchParams.get("state");if(n&&i)return y(e);const s=e.getStorage(),c=i||await s.get(o.SMART_KEY),d=await s.get(c);return d?new a.default(e,d):l(e,t).then((()=>new Promise((()=>{}))))}},5424:(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)}}},2612:(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."}},1227:(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,a=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(a=n))})),t.splice(a,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(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("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&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$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(2447)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},2447:(e,t,r)=>{e.exports=function(e){function t(e){let r,a,o,i=null;function s(...e){if(!s.enabled)return;const n=s,a=Number(new Date),o=a-(r||a);n.diff=o,n.prev=r,n.curr=a,r=a,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,a)=>{if("%%"===r)return"%";i++;const o=t.formatters[a];if("function"==typeof o){const t=e[i];r=o.call(n,t),e.splice(i,1),i--}return r})),t.formatArgs.call(n,e),(n.log||t.log).apply(n,e)}return s.namespace=e,s.useColors=t.useColors(),s.color=t.selectColor(e),s.extend=n,s.destroy=t.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(a!==t.namespaces&&(a=t.namespaces,o=t.enabled(e)),o),set:e=>{i=e}}),"function"==typeof t.init&&t.init(s),s}function n(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function a(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(a),...t.skips.map(a).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,]+/),a=n.length;for(r=0;r<a;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(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(7824),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}},7824:e=>{var t=1e3,r=60*t,n=60*r,a=24*n;function o(e,t,r,n){var a=t>=1.5*r;return Math.round(e/r)+" "+n+(a?"s":"")}e.exports=function(e,i){i=i||{};var s,c,d=typeof e;if("string"===d&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var o=/^(-?(?:\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(o){var i=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*i;case"weeks":case"week":case"w":return 6048e5*i;case"days":case"day":case"d":return i*a;case"hours":case"hour":case"hrs":case"hr":case"h":return i*n;case"minutes":case"minute":case"mins":case"min":case"m":return i*r;case"seconds":case"second":case"secs":case"sec":case"s":return i*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:return}}}}(e);if("number"===d&&isFinite(e))return i.long?(s=e,(c=Math.abs(s))>=a?o(s,c,a,"day"):c>=n?o(s,c,n,"hour"):c>=r?o(s,c,r,"minute"):c>=t?o(s,c,t,"second"):s+" ms"):function(e){var o=Math.abs(e);return o>=a?Math.round(e/a)+"d":o>=n?Math.round(e/n)+"h":o>=r?Math.round(e/r)+"m":o>=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))}},7277:(e,t,r)=>{"use strict";r.r(t),r.d(t,{CompactEncrypt:()=>p.CompactEncrypt,CompactSign:()=>f.CompactSign,EmbeddedJWK:()=>E.EmbeddedJWK,EncryptJWT:()=>m.EncryptJWT,FlattenedEncrypt:()=>h.FlattenedEncrypt,FlattenedSign:()=>y.FlattenedSign,GeneralEncrypt:()=>i.GeneralEncrypt,GeneralSign:()=>w.GeneralSign,SignJWT:()=>g.SignJWT,UnsecuredJWT:()=>b.UnsecuredJWT,base64url:()=>H,calculateJwkThumbprint:()=>S.calculateJwkThumbprint,compactDecrypt:()=>n.compactDecrypt,compactVerify:()=>s.compactVerify,createLocalJWKSet:()=>v.createLocalJWKSet,createRemoteJWKSet:()=>A.createRemoteJWKSet,decodeJwt:()=>P.decodeJwt,decodeProtectedHeader:()=>J.decodeProtectedHeader,errors:()=>k,exportJWK:()=>C.exportJWK,exportPKCS8:()=>C.exportPKCS8,exportSPKI:()=>C.exportSPKI,flattenedDecrypt:()=>a.flattenedDecrypt,flattenedVerify:()=>c.flattenedVerify,generalDecrypt:()=>o.generalDecrypt,generalVerify:()=>d.generalVerify,generateKeyPair:()=>W.generateKeyPair,generateSecret:()=>K.generateSecret,importJWK:()=>_.importJWK,importPKCS8:()=>_.importPKCS8,importSPKI:()=>_.importSPKI,importX509:()=>_.importX509,jwtDecrypt:()=>l.jwtDecrypt,jwtVerify:()=>u.jwtVerify});var n=r(8920),a=r(8115),o=r(8982),i=r(5063),s=r(7309),c=r(8170),d=r(6257),u=r(5540),l=r(8112),p=r(2398),h=r(975),f=r(5326),y=r(9307),w=r(2310),g=r(3433),m=r(6125),S=r(814),E=r(2376),v=r(8464),A=r(9746),b=r(7770),C=r(2531),_=r(1503),J=r(3878),P=r(7879),k=r(8842),W=r(3619),K=r(2125),H=r(6001)},8920:(e,t,r)=>{"use strict";r.d(t,{compactDecrypt:()=>i});var n=r(8115),a=r(8842),o=r(1538);async function i(e,t,r){if(e instanceof Uint8Array&&(e=o.decoder.decode(e)),"string"!=typeof e)throw new a.JWEInvalid("Compact JWE must be a string or Uint8Array");const{0:i,1:s,2:c,3:d,4:u,length:l}=e.split(".");if(5!==l)throw new a.JWEInvalid("Invalid Compact JWE");const p=await(0,n.flattenedDecrypt)({ciphertext:d,iv:c||void 0,protected:i||void 0,tag:u||void 0,encrypted_key:s||void 0},t,r),h={plaintext:p.plaintext,protectedHeader:p.protectedHeader};return"function"==typeof t?{...h,key:p.key}:h}},2398:(e,t,r)=>{"use strict";r.d(t,{CompactEncrypt:()=>a});var n=r(975);class a{constructor(e){this._flattened=new n.FlattenedEncrypt(e)}setContentEncryptionKey(e){return this._flattened.setContentEncryptionKey(e),this}setInitializationVector(e){return this._flattened.setInitializationVector(e),this}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}setKeyManagementParameters(e){return this._flattened.setKeyManagementParameters(e),this}async encrypt(e,t){const r=await this._flattened.encrypt(e,t);return[r.protected,r.encrypted_key,r.iv,r.ciphertext,r.tag].join(".")}}},8115:(e,t,r)=>{"use strict";r.d(t,{flattenedDecrypt:()=>f});var n=r(9166),a=r(5790),o=r(5515),i=r(8842),s=r(2085),c=r(2674),d=r(813),u=r(1538),l=r(1002),p=r(3406),h=r(5154);async function f(e,t,r){var f;if(!(0,c.default)(e))throw new i.JWEInvalid("Flattened JWE must be an object");if(void 0===e.protected&&void 0===e.header&&void 0===e.unprotected)throw new i.JWEInvalid("JOSE Header missing");if("string"!=typeof e.iv)throw new i.JWEInvalid("JWE Initialization Vector missing or incorrect type");if("string"!=typeof e.ciphertext)throw new i.JWEInvalid("JWE Ciphertext missing or incorrect type");if("string"!=typeof e.tag)throw new i.JWEInvalid("JWE Authentication Tag missing or incorrect type");if(void 0!==e.protected&&"string"!=typeof e.protected)throw new i.JWEInvalid("JWE Protected Header incorrect type");if(void 0!==e.encrypted_key&&"string"!=typeof e.encrypted_key)throw new i.JWEInvalid("JWE Encrypted Key incorrect type");if(void 0!==e.aad&&"string"!=typeof e.aad)throw new i.JWEInvalid("JWE AAD incorrect type");if(void 0!==e.header&&!(0,c.default)(e.header))throw new i.JWEInvalid("JWE Shared Unprotected Header incorrect type");if(void 0!==e.unprotected&&!(0,c.default)(e.unprotected))throw new i.JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");let y;if(e.protected){const t=(0,n.decode)(e.protected);try{y=JSON.parse(u.decoder.decode(t))}catch(e){throw new i.JWEInvalid("JWE Protected Header is invalid")}}if(!(0,s.default)(y,e.header,e.unprotected))throw new i.JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");const w={...y,...e.header,...e.unprotected};if((0,p.default)(i.JWEInvalid,new Map,null==r?void 0:r.crit,y,w),void 0!==w.zip){if(!y||!y.zip)throw new i.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if("DEF"!==w.zip)throw new i.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}const{alg:g,enc:m}=w;if("string"!=typeof g||!g)throw new i.JWEInvalid("missing JWE Algorithm (alg) in JWE Header");if("string"!=typeof m||!m)throw new i.JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");const S=r&&(0,h.default)("keyManagementAlgorithms",r.keyManagementAlgorithms),E=r&&(0,h.default)("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(S&&!S.has(g))throw new i.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');if(E&&!E.has(m))throw new i.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed');let v;void 0!==e.encrypted_key&&(v=(0,n.decode)(e.encrypted_key));let A,b=!1;"function"==typeof t&&(t=await t(y,e),b=!0);try{A=await(0,d.default)(g,t,v,w)}catch(e){if(e instanceof TypeError)throw e;A=(0,l.default)(m)}const C=(0,n.decode)(e.iv),_=(0,n.decode)(e.tag),J=u.encoder.encode(null!==(f=e.protected)&&void 0!==f?f:"");let P;P=void 0!==e.aad?(0,u.concat)(J,u.encoder.encode("."),u.encoder.encode(e.aad)):J;let k=await(0,a.default)(m,A,(0,n.decode)(e.ciphertext),C,_,P);"DEF"===w.zip&&(k=await((null==r?void 0:r.inflateRaw)||o.inflate)(k));const W={plaintext:k};return void 0!==e.protected&&(W.protectedHeader=y),void 0!==e.aad&&(W.additionalAuthenticatedData=(0,n.decode)(e.aad)),void 0!==e.unprotected&&(W.sharedUnprotectedHeader=e.unprotected),void 0!==e.header&&(W.unprotectedHeader=e.header),b?{...W,key:t}:W}},975:(e,t,r)=>{"use strict";r.d(t,{FlattenedEncrypt:()=>h,unprotected:()=>p});var n=r(9166),a=r(1088),o=r(5515),i=r(8948),s=r(8751),c=r(8842),d=r(2085),u=r(1538),l=r(3406);const p=Symbol();class h{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=e}setKeyManagementParameters(e){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=e,this}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}setContentEncryptionKey(e){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=e,this}setInitializationVector(e){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=e,this}async encrypt(e,t){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new c.JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!(0,d.default)(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new c.JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if((0,l.default)(c.JWEInvalid,new Map,null==t?void 0:t.crit,this._protectedHeader,r),void 0!==r.zip){if(!this._protectedHeader||!this._protectedHeader.zip)throw new c.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if("DEF"!==r.zip)throw new c.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}const{alg:h,enc:f}=r;if("string"!=typeof h||!h)throw new c.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("string"!=typeof f||!f)throw new c.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let y,w,g,m,S,E,v;if("dir"===h){if(this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption")}else if("ECDH-ES"===h&&this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");{let r;({cek:w,encryptedKey:y,parameters:r}=await(0,s.default)(h,f,e,this._cek,this._keyManagementParameters)),r&&(t&&p in t?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...r}:this.setUnprotectedHeader(r):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...r}:this.setProtectedHeader(r))}if(this._iv||(this._iv=(0,i.default)(f)),m=this._protectedHeader?u.encoder.encode((0,n.encode)(JSON.stringify(this._protectedHeader))):u.encoder.encode(""),this._aad?(S=(0,n.encode)(this._aad),g=(0,u.concat)(m,u.encoder.encode("."),u.encoder.encode(S))):g=m,"DEF"===r.zip){const e=await((null==t?void 0:t.deflateRaw)||o.deflate)(this._plaintext);({ciphertext:E,tag:v}=await(0,a.default)(f,e,w,this._iv,g))}else({ciphertext:E,tag:v}=await(0,a.default)(f,this._plaintext,w,this._iv,g));const A={ciphertext:(0,n.encode)(E),iv:(0,n.encode)(this._iv),tag:(0,n.encode)(v)};return y&&(A.encrypted_key=(0,n.encode)(y)),S&&(A.aad=S),this._protectedHeader&&(A.protected=u.decoder.decode(m)),this._sharedUnprotectedHeader&&(A.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(A.header=this._unprotectedHeader),A}}},8982:(e,t,r)=>{"use strict";r.d(t,{generalDecrypt:()=>i});var n=r(8115),a=r(8842),o=r(2674);async function i(e,t,r){if(!(0,o.default)(e))throw new a.JWEInvalid("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(o.default))throw new a.JWEInvalid("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new a.JWEInvalid("JWE Recipients has no members");for(const a of e.recipients)try{return await(0,n.flattenedDecrypt)({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:a.encrypted_key,header:a.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch(e){}throw new a.JWEDecryptionFailed}},5063:(e,t,r)=>{"use strict";r.d(t,{GeneralEncrypt:()=>l});var n=r(975),a=r(8842),o=r(1002),i=r(2085),s=r(8751),c=r(9166),d=r(3406);class u{constructor(e,t,r){this.parent=e,this.key=t,this.options=r}setUnprotectedHeader(e){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}addRecipient(...e){return this.parent.addRecipient(...e)}encrypt(...e){return this.parent.encrypt(...e)}done(){return this.parent}}class l{constructor(e){this._recipients=[],this._plaintext=e}addRecipient(e,t){const r=new u(this,e,{crit:null==t?void 0:t.crit});return this._recipients.push(r),r}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}async encrypt(e){var t,r,u;if(!this._recipients.length)throw new a.JWEInvalid("at least one recipient must be added");if(e={deflateRaw:null==e?void 0:e.deflateRaw},1===this._recipients.length){const[t]=this._recipients,r=await new n.FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(t.unprotectedHeader).encrypt(t.key,{...t.options,...e});let a={ciphertext:r.ciphertext,iv:r.iv,recipients:[{}],tag:r.tag};return r.aad&&(a.aad=r.aad),r.protected&&(a.protected=r.protected),r.unprotected&&(a.unprotected=r.unprotected),r.encrypted_key&&(a.recipients[0].encrypted_key=r.encrypted_key),r.header&&(a.recipients[0].header=r.header),a}let l;for(let e=0;e<this._recipients.length;e++){const t=this._recipients[e];if(!(0,i.default)(this._protectedHeader,this._unprotectedHeader,t.unprotectedHeader))throw new a.JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader,...t.unprotectedHeader},{alg:n}=r;if("string"!=typeof n||!n)throw new a.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("dir"===n||"ECDH-ES"===n)throw new a.JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');if("string"!=typeof r.enc||!r.enc)throw new a.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(l){if(l!==r.enc)throw new a.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}else l=r.enc;if((0,d.default)(a.JWEInvalid,new Map,t.options.crit,this._protectedHeader,r),!(void 0===r.zip||this._protectedHeader&&this._protectedHeade