@elementor/angie-sdk 1.2.0-beta.1 → 1.3.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{"use strict";var e={d:(t,i)=>{for(var s in i)e.o(i,s)&&!e.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:i[s]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{ANGIE_SIDEBAR_STATE_OPEN:()=>_t,AngieDetector:()=>v,AngieLocalServerTransport:()=>p,AngieMCPTransport:()=>u,AngieMcpSdk:()=>Nt,AngieRemoteServerTransport:()=>_,AngieServerType:()=>w,BrowserContextTransport:()=>E,ClientManager:()=>k,HostEventType:()=>y,HostLocalStorageEventType:()=>f,MessageEventType:()=>m,RegistrationQueue:()=>Ut,applyWidth:()=>kt,clearReferrerRedirect:()=>jt,disableNavigationPrevention:()=>Ct,getAngieIframe:()=>lt,getAngieSidebarSavedState:()=>vt,getReferrerRedirect:()=>Gt,initAngieSidebar:()=>At,initializeResize:()=>Rt,loadState:()=>It,loadWidth:()=>St,navigateAngieIframe:()=>Dt,saveState:()=>bt,saveWidth:()=>Et,setReferrerRedirect:()=>$t,toggleAngieSidebar:()=>st,waitForDocumentReady:()=>nt});const i={none:0,error:1,warn:2,info:3,debug:4},s={error:"error",warn:"warn",info:"info",log:"info",debug:"debug"},r=(e,t)=>i[e]<=i[t],n=e=>"string"==typeof e?e:JSON.stringify(e),o=(e,t)=>`${n(e)} > ${n(t)}`,a=(e,t)=>{let i=`[${n(e)}]`;return typeof window<"u"?{text:`%c${i}`,style:`color: ${t.color||"#00bcd4"}; font-weight: bold;`}:{text:i}},c=(e,t,i,n)=>(...o)=>{if(!r(s[e],n()))return;if(!t)return void console[e](...o);let{text:c,style:d}=a(t,i);d?console[e](c,d,...o):console[e](c,...o)},d=(e,t)=>{let i=t.logLevel??"debug",s=()=>i;return{log:c("log",e,t,s),info:c("info",e,t,s),warn:c("warn",e,t,s),error:c("error",e,t,s),debug:c("debug",e,t,s),setLogLevel:e=>{i=e},extend:s=>d(e?o(e,s):s,{...t,logLevel:i})}},l=(e,t)=>d(e,{color:"#00bcd4",logLevel:"debug",...t}),g=l("angie-sdk",{color:"#00BCD4",logLevel:"error"}),h=e=>g.extend(e);var u,p,_,w,m,f,y;!function(e){e.POST_MESSAGE="postMessage"}(u||(u={})),function(e){e.POST_MESSAGE="postMessage"}(p||(p={})),function(e){e.STREAMABLE_HTTP="streamableHttp",e.SSE="sse"}(_||(_={})),function(e){e.LOCAL="local",e.REMOTE="remote"}(w||(w={})),function(e){e.SDK_ANGIE_READY_PING="sdk-angie-ready-ping",e.SDK_ANGIE_REFRESH_PING="sdk-angie-refresh-ping",e.SDK_ANGIE_ALL_SERVERS_REGISTERED="sdk-angie-all-servers-registered",e.SDK_REQUEST_CLIENT_CREATION="sdk-request-client-creation",e.SDK_REQUEST_INIT_SERVER="sdk-request-init-server",e.SDK_TRIGGER_ANGIE="sdk-trigger-angie",e.SDK_TRIGGER_ANGIE_RESPONSE="sdk-trigger-angie-response",e.ANGIE_SIDEBAR_RESIZED="angie-sidebar-resized",e.ANGIE_SIDEBAR_TOGGLED="angie-sidebar-toggled",e.ANGIE_CHAT_TOGGLE="angie-chat-toggle",e.ANGIE_STUDIO_TOGGLE="angie-studio-toggle",e.ANGIE_NAVIGATE_TO_URL="angie/navigate-to-url",e.ANGIE_PAGE_RELOAD="angie/page-reload",e.ANGIE_DISABLE_NAVIGATION_PREVENTION="angie/disable-navigation-prevention",e.ANGIE_NAVIGATE_AFTER_RESPONSE="angie/navigate-after-response"}(m||(m={})),function(e){e.SET="ANGIE_SET_LOCALSTORAGE",e.GET="ANGIE_GET_LOCALSTORAGE"}(f||(f={})),function(e){e.RESET_HASH="reset-hash",e.HOST_READY="host/ready",e.ANGIE_LOADED="angie/loaded",e.ANGIE_READY="angie/ready"}(y||(y={}));const S=h("angie-detector");class v{isAngieReady=!1;readyPromise;readyResolve;constructor(){if(this.readyPromise=new Promise(e=>{this.readyResolve=e}),"undefined"==typeof window)return;let e=0;const t=()=>{if(this.isAngieReady||e>=500)return void(!this.isAngieReady&&e>=500&&this.handleDetectionTimeout());const i=new MessageChannel;i.port1.onmessage=e=>{this.handleAngieReady(e.data),i.port1.close(),i.port2.close()};const s={type:m.SDK_ANGIE_READY_PING,timestamp:Date.now()};window.postMessage(s,window.location.origin,[i.port2]),e++,setTimeout(t,500)};t()}handleAngieReady(e){this.isAngieReady=!0;const t={isReady:!0,version:e.version,capabilities:e.capabilities};this.readyResolve&&this.readyResolve(t)}handleDetectionTimeout(){this.readyResolve&&this.readyResolve({isReady:!1}),S.warn("Detection timeout - Angie may not be available")}isReady(){return this.isAngieReady}async waitForReady(){return this.readyPromise}}const b=require("@modelcontextprotocol/sdk/types.js");class E{sessionId;onmessage;onerror;onclose;_port;_started=!1;_closed=!1;constructor(e){if(!e)throw new Error("MessagePort is required");this._port=e,this._port.onmessage=e=>{try{const t=b.JSONRPCMessageSchema.parse(e.data);this.onmessage?.(t)}catch(e){const t=new Error(`Failed to parse message: ${e}`);this.onerror?.(t)}},this._port.onmessageerror=e=>{const t=new Error(`MessagePort error: ${JSON.stringify(e)}`);this.onerror?.(t)}}async start(){if(this._started)throw new Error("BrowserContextTransport already started! If using Client or Server class, note that connect() calls start() automatically.");if(this._closed)throw new Error("Cannot start a closed BrowserContextTransport");this._started=!0,this._port.start()}async send(e){if(this._closed)throw new Error("Cannot send on a closed BrowserContextTransport");return new Promise((t,i)=>{try{this._port.postMessage(e),t()}catch(e){const t=e instanceof Error?e:new Error(String(e));this.onerror?.(t),i(t)}})}async close(){this._closed||(this._closed=!0,this._port.close(),this.onclose?.())}}class k{async requestClientCreation(e){const{config:t}=e,i={serverId:e.id,serverName:t.name,serverTitle:t.title,serverVersion:t.version,description:t.description,transport:t.transport||p.POST_MESSAGE,capabilities:t.capabilities,instanceId:e.instanceId};return"type"in t&&"remote"===t.type&&(i.remote={url:t.url}),new Promise((e,t)=>{const s=new MessageChannel,r=setTimeout(()=>{t(new Error("Client creation request timed out after 15000ms"))},15e3);s.port1.onmessage=t=>{clearTimeout(r),e(t.data)};const n={type:m.SDK_REQUEST_CLIENT_CREATION,payload:i,timestamp:Date.now()};window.postMessage(n,window.location.origin,[s.port2])})}}const I={open:!1,iframe:null,iframeUrlObject:null};class T extends Error{}T.prototype.name="InvalidTokenError";var R,A,P,C={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},O=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(O||{});(P=O||(O={})).reset=function(){R=3,A=C},P.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");R=e},P.setLogger=function(e){A=e};var x=class e{constructor(e){this._name=e}debug(...t){R>=4&&A.debug(e._format(this._name,this._method),...t)}info(...t){R>=3&&A.info(e._format(this._name,this._method),...t)}warn(...t){R>=2&&A.warn(e._format(this._name,this._method),...t)}error(...t){R>=1&&A.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,i){const s=new e(`${t}.${i}`);return s.debug("begin"),s}static _format(e,t){const i=`[${e}]`;return t?`${i} ${t}:`:i}static debug(t,...i){R>=4&&A.debug(e._format(t),...i)}static info(t,...i){R>=3&&A.info(e._format(t),...i)}static warn(t,...i){R>=2&&A.warn(e._format(t),...i)}static error(t,...i){R>=1&&A.error(e._format(t),...i)}};O.reset();var U=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new T("Invalid token specified: must be a string");t||(t={});const i=!0===t.header?0:1,s=e.split(".")[i];if("string"!=typeof s)throw new T(`Invalid token specified: missing part #${i+1}`);let r;try{r=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let i=t.charCodeAt(0).toString(16).toUpperCase();return i.length<2&&(i="0"+i),"%"+i}))}(t)}catch(e){return atob(t)}}(s)}catch(e){throw new T(`Invalid token specified: invalid base64 for part #${i+1} (${e.message})`)}try{return JSON.parse(r)}catch(e){throw new T(`Invalid token specified: invalid json for part #${i+1} (${e.message})`)}}(e)}catch(e){throw x.error("JwtUtils.decode",e),e}}static async generateSignedJwt(e,t,i){const s=`${D.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${D.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,r=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},i,(new TextEncoder).encode(s));return`${s}.${D.encodeBase64Url(new Uint8Array(r))}`}static async generateSignedJwtWithHmac(e,t,i){const s=`${D.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${D.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,r=await window.crypto.subtle.sign("HMAC",i,(new TextEncoder).encode(s));return`${s}.${D.encodeBase64Url(new Uint8Array(r))}`}},N=e=>btoa([...new Uint8Array(e)].map(e=>String.fromCharCode(e)).join("")),L=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){const t="10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(+t^e._randomWord()&15>>+t/4).toString(16));return t.replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),i=await crypto.subtle.digest("SHA-256",t);return N(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw x.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const i=(new TextEncoder).encode([e,t].join(":"));return N(i)}static async hash(e,t){const i=(new TextEncoder).encode(t),s=await crypto.subtle.digest(e,i);return new Uint8Array(s)}static async customCalculateJwkThumbprint(t){let i;switch(t.kty){case"RSA":i={e:t.e,kty:t.kty,n:t.n};break;case"EC":i={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":i={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":i={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const s=await e.hash("SHA-256",JSON.stringify(i));return e.encodeBase64Url(s)}static async generateDPoPProof({url:t,accessToken:i,httpMethod:s,keyPair:r,nonce:n}){let o,a;const c={jti:window.crypto.randomUUID(),htm:null!=s?s:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};i&&(o=await e.hash("SHA-256",i),a=e.encodeBase64Url(o),c.ath=a),n&&(c.nonce=n);try{const e=await crypto.subtle.exportKey("jwk",r.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await U.generateSignedJwt(t,c,r.privateKey)}catch(e){throw e instanceof TypeError?new Error(`Error exporting dpop public key: ${e.message}`):e}}static async generateDPoPJkt(t){try{const i=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(i)}catch(e){throw e instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${e.message}`):e}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}static async generateClientAssertionJwt(t,i,s,r="HS256"){const n=Math.floor(Date.now()/1e3),o={alg:r,typ:"JWT"},a={iss:t,sub:t,aud:s,jti:e.generateUUIDv4(),exp:n+300,iat:n},c={HS256:"SHA-256",HS384:"SHA-384",HS512:"SHA-512"}[r];if(!c)throw new Error(`Unsupported algorithm: ${r}. Supported algorithms are: HS256, HS384, HS512`);const d=new TextEncoder,l=await crypto.subtle.importKey("raw",d.encode(i),{name:"HMAC",hash:c},!1,["sign"]);return await U.generateSignedJwtWithHmac(o,a,l)}};L.encodeBase64Url=e=>N(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var D=L,q=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new x(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},M=class{static center({...e}){var t;return null==e.width&&(e.width=null!=(t=[800,720,600,480].find(e=>e<=window.outerWidth/1.618))?t:360),null!=e.left||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),null!=e.height&&(null!=e.top||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter(([,e])=>null!=e).map(([e,t])=>`${e}=${"boolean"!=typeof t?t:t?"yes":"no"}`).join(",")}},H=class e extends q{constructor(){super(...arguments),this._logger=new x(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const i=this._logger.create("init");t=Math.max(Math.floor(t),1);const s=e.getEpochTime()+t;if(this.expiration===s&&this._timerHandle)return void i.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),i.debug("using duration",t),this._expiration=s;const r=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*r)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},$=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const i=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(i.slice(1))}},G=";",j=class extends Error{constructor(e,t){var i,s,r;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw x.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(i=e.error_description)?i:null,this.error_uri=null!=(s=e.error_uri)?s:null,this.state=e.userState,this.session_state=null!=(r=e.session_state)?r:null,this.url_state=e.url_state}},W=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},z=class{constructor(e){this._logger=new x("AccessTokenEvents"),this._expiringTimer=new H("Access token expiring"),this._expiredTimer=new H("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const i=e.expires_in;if(t.debug("access token present, remaining duration:",i),i>0){let e=i-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug("registering expiring timer, raising in",e,"seconds"),this._expiringTimer.init(e)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const s=i+1;t.debug("registering expired timer, raising in",s,"seconds"),this._expiredTimer.init(s)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},F=class{constructor(e,t,i,s,r){this._callback=e,this._client_id=t,this._intervalInSeconds=s,this._stopOnError=r,this._logger=new x("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};const n=new URL(i);this._frame_origin=n.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=n.href}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)})}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,1e3*this._intervalInSeconds)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},K=class{constructor(){this._logger=new x("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},J=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},B=class{constructor(e=[],t=null,i={}){this._jwtHandler=t,this._extraHeaders=i,this._logger=new x("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:i,...s}=t;if(!i)return await fetch(e,s);const r=new AbortController,n=setTimeout(()=>r.abort(),1e3*i);try{return await fetch(e,{...t,signal:r.signal})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw new W("Network timed out");throw e}finally{clearTimeout(n)}}async getJson(e,{token:t,credentials:i,timeoutInSeconds:s}={}){const r=this._logger.create("getJson"),n={Accept:this._contentTypes.join(", ")};let o;t&&(r.debug("token passed, setting Authorization header"),n.Authorization="Bearer "+t),this._appendExtraHeaders(n);try{r.debug("url:",e),o=await this.fetchWithTimeout(e,{method:"GET",headers:n,timeoutInSeconds:s,credentials:i})}catch(e){throw r.error("Network Error"),e}r.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find(e=>a.startsWith(e))&&r.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),o.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(e){if(r.error("Error parsing JSON response",e),o.ok)throw e;throw new Error(`${o.statusText} (${o.status})`)}if(!o.ok){if(r.error("Error from server:",c),c.error)throw new j(c);throw new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:i,timeoutInSeconds:s,initCredentials:r,extraHeaders:n}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...n};let c;void 0!==i&&(a.Authorization="Basic "+i),this._appendExtraHeaders(a);try{o.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:s,credentials:r})}catch(e){throw o.error("Network error"),e}o.debug("HTTP response received, status",c.status);const d=c.headers.get("Content-Type");if(d&&!this._contentTypes.find(e=>d.startsWith(e)))throw new Error(`Invalid response Content-Type: ${null!=d?d:"undefined"}, from URL: ${e}`);const l=await c.text();let g={};if(l)try{g=JSON.parse(l)}catch(e){if(o.error("Error parsing JSON response",e),c.ok)throw e;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(o.error("Error from server:",g),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new J(e,`${JSON.stringify(g)}`)}if(g.error)throw new j(g,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(g)}`)}return g}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),i=Object.keys(this._extraHeaders),s=["accept","content-type"],r=["authorization"];0!==i.length&&i.forEach(i=>{if(s.includes(i.toLocaleLowerCase()))return void t.warn("Protected header could not be set",i,s);if(r.includes(i.toLocaleLowerCase())&&Object.keys(e).includes(i))return void t.warn("Header could not be overridden",i,r);const n="function"==typeof this._extraHeaders[i]?this._extraHeaders[i]():this._extraHeaders[i];n&&""!==n&&(e[i]=n)})}},Q=class{constructor(e){this._settings=e,this._logger=new x("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new B(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const i=this._logger.create(`_getMetadataProperty('${e}')`),s=await this.getMetadata();if(i.debug("resolved"),void 0===s[e]){if(!0===t)return void i.warn("Metadata does not contain optional property");i.throw(new Error("Metadata does not contain property "+e))}return s[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const i=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",i),!Array.isArray(i.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=i.keys,this._signingKeys}},V=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new x("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){return this._logger.create(`get('${e}')`),e=this._prefix+e,await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let i=0;i<e;i++){const e=await this._store.key(i);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},X=class{constructor({authority:e,metadataUrl:t,metadata:i,signingKeys:s,metadataSeed:r,client_id:n,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:d,post_logout_redirect_uri:l,client_authentication:g="client_secret_post",token_endpoint_auth_signing_alg:h="HS256",prompt:u,display:p,max_age:_,ui_locales:w,acr_values:m,resource:f,response_mode:y,filterProtocolClaims:S=!0,loadUserInfo:v=!1,requestTimeoutInSeconds:b,staleStateAgeInSeconds:E=900,mergeClaimsStrategy:k={array:"replace"},disablePKCE:I=!1,stateStore:T,revokeTokenAdditionalContentTypes:R,fetchRequestCredentials:A,refreshTokenAllowedScope:P,extraQueryParams:C={},extraTokenParams:O={},extraHeaders:x={},dpop:U,omitScopeWhenRequesting:N=!1}){var L;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=i,this.metadataSeed=r,this.signingKeys=s,this.client_id=n,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=d,this.post_logout_redirect_uri=l,this.client_authentication=g,this.token_endpoint_auth_signing_alg=h,this.prompt=u,this.display=p,this.max_age=_,this.ui_locales=w,this.acr_values=m,this.resource=f,this.response_mode=y,this.filterProtocolClaims=null==S||S,this.loadUserInfo=!!v,this.staleStateAgeInSeconds=E,this.mergeClaimsStrategy=k,this.omitScopeWhenRequesting=N,this.disablePKCE=!!I,this.revokeTokenAdditionalContentTypes=R,this.fetchRequestCredentials=A||"same-origin",this.requestTimeoutInSeconds=b,T)this.stateStore=T;else{const e="undefined"!=typeof window?window.localStorage:new K;this.stateStore=new V({store:e})}if(this.refreshTokenAllowedScope=P,this.extraQueryParams=C,this.extraTokenParams=O,this.extraHeaders=x,this.dpop=U,this.dpop&&!(null==(L=this.dpop)?void 0:L.store))throw new Error("A DPoPStore is required when dpop is enabled")}},Y=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new x("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const i=U.decode(e);return t.debug("JWT decoding successful"),i}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new B(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const i=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",i);const s=await this._jsonService.getJson(i,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",s),s}},Z=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new x("TokenClient"),this._jsonService=new B(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:i=this._settings.client_id,client_secret:s=this._settings.client_secret,extraHeaders:r,...n}){const o=this._logger.create("exchangeCode");i||o.throw(new Error("A client_id is required")),t||o.throw(new Error("A redirect_uri is required")),n.code||o.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[e,t]of Object.entries(n))null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==s)throw o.throw(new Error("A client_secret is required")),null;let c;const d=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=D.generateBasicAuth(i,s);break;case"client_secret_post":a.append("client_id",i),s&&a.append("client_secret",s);break;case"client_secret_jwt":{const e=await D.generateClientAssertionJwt(i,s,d,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",i),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const l=await this._jsonService.postForm(d,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:r});return o.debug("got response"),l}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:i=this._settings.client_secret,scope:s=this._settings.scope,...r}){const n=this._logger.create("exchangeCredentials");t||n.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set("scope",s);for(const[e,t]of Object.entries(r))null!=t&&o.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==i)throw n.throw(new Error("A client_secret is required")),null;let a;const c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":a=D.generateBasicAuth(t,i);break;case"client_secret_post":o.append("client_id",t),i&&o.append("client_secret",i);break;case"client_secret_jwt":{const e=await D.generateClientAssertionJwt(t,i,c,this._settings.token_endpoint_auth_signing_alg);o.append("client_id",t),o.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),o.append("client_assertion",e);break}}n.debug("got token endpoint");const d=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),d}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:i=this._settings.client_secret,timeoutInSeconds:s,extraHeaders:r,...n}){const o=this._logger.create("exchangeRefreshToken");t||o.throw(new Error("A client_id is required")),n.refresh_token||o.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[e,t]of Object.entries(n))Array.isArray(t)?t.forEach(t=>a.append(e,t)):null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==i)throw o.throw(new Error("A client_secret is required")),null;let c;const d=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=D.generateBasicAuth(t,i);break;case"client_secret_post":a.append("client_id",t),i&&a.append("client_secret",i);break;case"client_secret_jwt":{const e=await D.generateClientAssertionJwt(t,i,d,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",t),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const l=await this._jsonService.postForm(d,{body:a,basicAuth:c,timeoutInSeconds:s,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:r});return o.debug("got response"),l}async revoke(e){var t;const i=this._logger.create("revoke");e.token||i.throw(new Error("A token is required"));const s=await this._metadataService.getRevocationEndpoint(!1);i.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const r=new URLSearchParams;for(const[t,i]of Object.entries(e))null!=i&&r.set(t,i);r.set("client_id",this._settings.client_id),this._settings.client_secret&&r.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(s,{body:r,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),i.debug("got response")}},ee=class{constructor(e,t,i){this._settings=e,this._metadataService=t,this._claimsService=i,this._logger=new x("ResponseValidator"),this._userInfoService=new Y(this._settings,this._metadataService),this._tokenClient=new Z(this._settings,this._metadataService)}async validateSigninResponse(e,t,i){const s=this._logger.create("validateSigninResponse");this._processSigninState(e,t),s.debug("state processed"),await this._processCode(e,t,i),s.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),s.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),s.debug("claims processed")}async validateCredentialsResponse(e,t){const i=this._logger.create("validateCredentialsResponse"),s=e.isOpenId&&!!e.id_token;s&&this._validateIdTokenAttributes(e),i.debug("tokens validated"),await this._processClaims(e,t,s),i.debug("claims processed")}async validateRefreshResponse(e,t){const i=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),i.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const s=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,s),i.debug("claims processed")}validateSignoutResponse(e,t){const i=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&i.throw(new Error("State does not match")),i.debug("state validated"),e.userState=t.data,e.error)throw i.warn("Response was error",e.error),new j(e)}_processSigninState(e,t){const i=this._logger.create("_processSigninState");if(t.id!==e.state&&i.throw(new Error("State does not match")),t.client_id||i.throw(new Error("No client_id on state")),t.authority||i.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&i.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&i.throw(new Error("client_id mismatch on settings vs. signin state")),i.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw i.warn("Response was error",e.error),new j(e);t.code_verifier&&!e.code&&i.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,i=!0){const s=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void s.debug("not loading user info");s.debug("loading user info");const r=await this._userInfoService.getClaims(e.access_token);s.debug("user info claims received from user info endpoint"),i&&r.sub!==e.profile.sub&&s.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(r)),s.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,i){const s=this._logger.create("_processCode");if(e.code){s.debug("Validating code");const r=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:i,...t.extraTokenParams});Object.assign(e,r)}else s.debug("No code to process")}_validateIdTokenAttributes(e,t){var i;const s=this._logger.create("_validateIdTokenAttributes");s.debug("decoding ID Token JWT");const r=U.decode(null!=(i=e.id_token)?i:"");if(r.sub||s.throw(new Error("ID Token is missing a subject claim")),t){const e=U.decode(t);r.sub!==e.sub&&s.throw(new Error("sub in id_token does not match current sub")),r.auth_time&&r.auth_time!==e.auth_time&&s.throw(new Error("auth_time in id_token does not match original auth_time")),r.azp&&r.azp!==e.azp&&s.throw(new Error("azp in id_token does not match original azp")),!r.azp&&e.azp&&s.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=r}},te=class e{constructor(e){this.id=e.id||D.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=H.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new x("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return x.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,i){const s=x.createStatic("State","clearStaleState"),r=H.getEpochTime()-i,n=await t.getAllKeys();s.debug("got keys",n);for(let i=0;i<n.length;i++){const o=n[i],a=await t.get(o);let c=!1;if(a)try{const t=await e.fromStorageString(a);s.debug("got item from key:",o,t.created),t.created<=r&&(c=!0)}catch(e){s.error("Error parsing state for key:",o,e),c=!0}else s.debug("no item in storage for key:",o),c=!0;c&&(s.debug("removed item for key:",o),t.remove(o))}}},ie=class e extends te{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(t){const i=!0===t.code_verifier?D.generateCodeVerifier():t.code_verifier||void 0,s=i?await D.generateCodeChallenge(i):void 0;return new e({...t,code_verifier:i,code_challenge:s})}toStorageString(){return new x("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){x.createStatic("SigninState","fromStorageString");const i=JSON.parse(t);return e.create(i)}},se=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:i,client_id:s,redirect_uri:r,response_type:n,scope:o,state_data:a,response_mode:c,request_type:d,client_secret:l,nonce:g,url_state:h,resource:u,skipUserInfo:p,extraQueryParams:_,extraTokenParams:w,disablePKCE:m,dpopJkt:f,omitScopeWhenRequesting:y,...S}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!s)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!r)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!n)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!o)throw this._logger.error("create: No scope passed"),new Error("scope");if(!i)throw this._logger.error("create: No authority passed"),new Error("authority");const v=await ie.create({data:a,request_type:d,url_state:h,code_verifier:!m,client_id:s,authority:i,redirect_uri:r,response_mode:c,client_secret:l,scope:o,extraTokenParams:w,skipUserInfo:p}),b=new URL(t);b.searchParams.append("client_id",s),b.searchParams.append("redirect_uri",r),b.searchParams.append("response_type",n),y||b.searchParams.append("scope",o),g&&b.searchParams.append("nonce",g),f&&b.searchParams.append("dpop_jkt",f);let E=v.id;h&&(E=`${E}${G}${h}`),b.searchParams.append("state",E),v.code_challenge&&(b.searchParams.append("code_challenge",v.code_challenge),b.searchParams.append("code_challenge_method","S256")),u&&(Array.isArray(u)?u:[u]).forEach(e=>b.searchParams.append("resource",e));for(const[e,t]of Object.entries({response_mode:c,...S,..._}))null!=t&&b.searchParams.append(e,t.toString());return new e({url:b.href,state:v})}};se._logger=new x("SigninRequest");var re=se,ne=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(G);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(G))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-H.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+H.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},oe=class{constructor({url:e,state_data:t,id_token_hint:i,post_logout_redirect_uri:s,extraQueryParams:r,request_type:n,client_id:o,url_state:a}){if(this._logger=new x("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(i&&c.searchParams.append("id_token_hint",i),o&&c.searchParams.append("client_id",o),s&&(c.searchParams.append("post_logout_redirect_uri",s),t||a)){this.state=new te({data:t,request_type:n,url_state:a});let e=this.state.id;a&&(e=`${e}${G}${a}`),c.searchParams.append("state",e)}for(const[e,t]of Object.entries({...r}))null!=t&&c.searchParams.append(e,t.toString());this.url=c.href}},ae=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(G);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(G))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},ce=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],de=["sub","iss","aud","exp","iat"],le=class{constructor(e){this._settings=e,this._logger=new x("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:ce;for(const i of e)de.includes(i)||delete t[i]}return t}mergeClaims(e,t){const i={...e};for(const[e,s]of Object.entries(t))if(i[e]!==s)if(Array.isArray(i[e])||Array.isArray(s))if("replace"==this._settings.mergeClaimsStrategy.array)i[e]=s;else{const t=Array.isArray(i[e])?i[e]:[i[e]];for(const e of Array.isArray(s)?s:[s])t.includes(e)||t.push(e);i[e]=t}else"object"==typeof i[e]&&"object"==typeof s?i[e]=this.mergeClaims(i[e],s):i[e]=s;return i}},ge=class{constructor(e,t){this.keys=e,this.nonce=t}},he=class{constructor(e,t){this._logger=new x("OidcClient"),this.settings=e instanceof X?e:new X(e),this.metadataService=null!=t?t:new Q(this.settings),this._claimsService=new le(this.settings),this._validator=new ee(this.settings,this.metadataService,this._claimsService),this._tokenClient=new Z(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:i,request_type:s,id_token_hint:r,login_hint:n,skipUserInfo:o,nonce:a,url_state:c,response_type:d=this.settings.response_type,scope:l=this.settings.scope,redirect_uri:g=this.settings.redirect_uri,prompt:h=this.settings.prompt,display:u=this.settings.display,max_age:p=this.settings.max_age,ui_locales:_=this.settings.ui_locales,acr_values:w=this.settings.acr_values,resource:m=this.settings.resource,response_mode:f=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:S=this.settings.extraTokenParams,dpopJkt:v,omitScopeWhenRequesting:b=this.settings.omitScopeWhenRequesting}){const E=this._logger.create("createSigninRequest");if("code"!==d)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const k=await this.metadataService.getAuthorizationEndpoint();E.debug("Received authorization endpoint",k);const I=await re.create({url:k,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:g,response_type:d,scope:l,state_data:e,url_state:c,prompt:h,display:u,max_age:p,ui_locales:_,id_token_hint:r,login_hint:n,acr_values:w,dpopJkt:v,resource:m,request:t,request_uri:i,extraQueryParams:y,extraTokenParams:S,request_type:s,response_mode:f,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:b});await this.clearStaleState();const T=I.state;return await this.settings.stateStore.set(T.id,T.toStorageString()),I}async readSigninResponseState(e,t=!1){const i=this._logger.create("readSigninResponseState"),s=new ne($.readParams(e,this.settings.response_mode));if(!s.state)throw i.throw(new Error("No state in response")),null;const r=await this.settings.stateStore[t?"remove":"get"](s.state);if(!r)throw i.throw(new Error("No matching state found in storage")),null;return{state:await ie.fromStorageString(r),response:s}}async processSigninResponse(e,t,i=!0){const s=this._logger.create("processSigninResponse"),{state:r,response:n}=await this.readSigninResponseState(e,i);if(s.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(n,r,t)}catch(e){if(!(e instanceof J&&this.settings.dpop))throw e;{const i=await this.getDpopProof(this.settings.dpop.store,e.nonce);t.DPoP=i,await this._validator.validateSigninResponse(n,r,t)}}return n}async getDpopProof(e,t){let i,s;return(await e.getAllKeys()).includes(this.settings.client_id)?(s=await e.get(this.settings.client_id),s.nonce!==t&&t&&(s.nonce=t,await e.set(this.settings.client_id,s))):(i=await D.generateDPoPKeys(),s=new ge(i,t),await e.set(this.settings.client_id,s)),await D.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:s.keys,nonce:s.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:i=!1,extraTokenParams:s={}}){const r=await this._tokenClient.exchangeCredentials({username:e,password:t,...s}),n=new ne(new URLSearchParams);return Object.assign(n,r),await this._validator.validateCredentialsResponse(n,i),n}async useRefreshToken({state:e,redirect_uri:t,resource:i,timeoutInSeconds:s,extraHeaders:r,extraTokenParams:n}){var o;const a=this._logger.create("useRefreshToken");let c,d;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(o=e.scope)?void 0:o.split(" "))||[]).filter(e=>t.includes(e)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);r={...r,DPoP:e}}try{d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:i,timeoutInSeconds:s,extraHeaders:r,...n})}catch(o){if(!(o instanceof J&&this.settings.dpop))throw o;r.DPoP=await this.getDpopProof(this.settings.dpop.store,o.nonce),d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:i,timeoutInSeconds:s,extraHeaders:r,...n})}const l=new ne(new URLSearchParams);return Object.assign(l,d),a.debug("validating response",l),await this._validator.validateRefreshResponse(l,{...e,scope:c}),l}async createSignoutRequest({state:e,id_token_hint:t,client_id:i,request_type:s,url_state:r,post_logout_redirect_uri:n=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",c),i||!n||t||(i=this.settings.client_id);const d=new oe({url:c,id_token_hint:t,client_id:i,post_logout_redirect_uri:n,state_data:e,extraQueryParams:o,request_type:s,url_state:r});await this.clearStaleState();const l=d.state;return l&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(l.id,l.toStorageString())),d}async readSignoutResponseState(e,t=!1){const i=this._logger.create("readSignoutResponseState"),s=new ae($.readParams(e,this.settings.response_mode));if(!s.state){if(i.debug("No state in response"),s.error)throw i.warn("Response was error:",s.error),new j(s);return{state:void 0,response:s}}const r=await this.settings.stateStore[t?"remove":"get"](s.state);if(!r)throw i.throw(new Error("No matching state found in storage")),null;return{state:await te.fromStorageString(r),response:s}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:i,response:s}=await this.readSignoutResponseState(e,!0);return i?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(s,i)):t.debug("No state from storage; skipping response validation"),s}clearStaleState(){return this._logger.create("clearStaleState"),te.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},ue=class{constructor(e){this._userManager=e,this._logger=new x("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const i=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,i.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,i.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){i.debug("initializing check session iframe");const s=this._userManager.settings.client_id,r=this._userManager.settings.checkSessionIntervalInSeconds,n=this._userManager.settings.stopCheckSessionOnError,o=new F(this._callback,s,e,r,n);await o.load(),this._checkSessionIFrame=o,o.start(t)}else i.warn("no check session iframe found in the metadata")}catch(e){i.error("Error from getCheckSessionIframe:",e instanceof Error?e.message:e)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval(async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(t){e.error("error from querySessionStatus",t instanceof Error?t.message:t)}},1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let i=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(i=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),i?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch(e=>{this._logger.error(e)})}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},pe=class e{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-H.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+H.getEpochTime())}get expired(){const e=this.expires_in;if(void 0!==e)return e<=0}get scopes(){var e,t;return null!=(t=null==(e=this.scope)?void 0:e.split(" "))?t:[]}toStorageString(){return new x("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return x.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},_e="oidc-client",we=class{constructor(){this._abort=new q("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:i,keepOpen:s}=await new Promise((i,s)=>{const r=r=>{var n;const o=r.data,a=null!=(n=e.scriptOrigin)?n:window.location.origin;if(r.origin===a&&(null==o?void 0:o.source)===_e){try{const i=$.readParams(o.url,e.response_mode).get("state");if(i||t.warn("no state found in response url"),r.source!==this._window&&i!==e.state)return}catch{this._dispose(),s(new Error("Invalid response from window"))}i(o)}};window.addEventListener("message",r,!1),this._disposeHandlers.add(()=>window.removeEventListener("message",r,!1));const n=new BroadcastChannel(`oidc-client-popup-${e.state}`);n.addEventListener("message",r,!1),this._disposeHandlers.add(()=>n.close()),this._disposeHandlers.add(this._abort.addHandler(e=>{this._dispose(),s(e)}))});return t.debug("got response from window"),this._dispose(),s||this.close(),{url:i}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,i=!1,s=window.location.origin){const r={source:_e,url:t,keepOpen:i},n=new x("_notifyParent");if(e)n.debug("With parent. Using parent.postMessage."),e.postMessage(r,s);else{n.debug("No parent. Using BroadcastChannel.");const e=new URL(t).searchParams.get("state");if(!e)throw new Error("No parent and no state in URL. Can't complete notification.");const i=new BroadcastChannel(`oidc-client-popup-${e}`);i.postMessage(r),i.close()}}},me={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},fe="_blank",ye=60,Se=2,ve=class extends X{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:i=e.post_logout_redirect_uri,popupWindowFeatures:s=me,popupWindowTarget:r=fe,redirectMethod:n="assign",redirectTarget:o="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:d,silent_redirect_uri:l=e.redirect_uri,silentRequestTimeoutInSeconds:g,automaticSilentRenew:h=!0,validateSubOnSilentRenew:u=!0,includeIdTokenInSilentRenew:p=!1,monitorSession:_=!1,monitorAnonymousSession:w=!1,checkSessionIntervalInSeconds:m=Se,query_status_response_type:f="code",stopCheckSessionOnError:y=!0,revokeTokenTypes:S=["access_token","refresh_token"],revokeTokensOnSignout:v=!1,includeIdTokenInSilentSignout:b=!1,accessTokenExpiringNotificationTimeInSeconds:E=ye,userStore:k}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=i,this.popupWindowFeatures=s,this.popupWindowTarget=r,this.redirectMethod=n,this.redirectTarget=o,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=l,this.silentRequestTimeoutInSeconds=g||d||10,this.automaticSilentRenew=h,this.validateSubOnSilentRenew=u,this.includeIdTokenInSilentRenew=p,this.monitorSession=_,this.monitorAnonymousSession=w,this.checkSessionIntervalInSeconds=m,this.stopCheckSessionOnError=y,this.query_status_response_type=f,this.revokeTokenTypes=S,this.revokeTokensOnSignout=v,this.includeIdTokenInSilentSignout=b,this.accessTokenExpiringNotificationTimeInSeconds=E,k)this.userStore=k;else{const e="undefined"!=typeof window?window.sessionStorage:new K;this.userStore=new V({store:e})}}},be=class e extends we{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new x("IFrameWindow"),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout(()=>{this._abort.raise(new W("IFrame timed out without a response"))},1e3*this._timeoutInSeconds);return this._disposeHandlers.add(()=>clearTimeout(t)),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",e=>{var t;const i=e.target;null==(t=i.parentNode)||t.removeChild(i),this._abort.raise(new Error("IFrame removed from DOM"))},!0),null==(e=this._frame.contentWindow)||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},Ee=class{constructor(e){this._settings=e,this._logger=new x("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new be({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),be.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},ke=class extends we{constructor({popupWindowTarget:e=fe,popupWindowFeatures:t={},popupSignal:i,popupAbortOnClose:s}){super(),this._logger=new x("PopupWindow");const r=M.center({...me,...t});this._window=window.open(void 0,e,M.serialize(r)),this.abortOnClose=Boolean(s),i&&i.addEventListener("abort",()=>{var e;this._abort.raise(new Error(null!=(e=i.reason)?e:"Popup aborted"))}),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout(()=>{this._window&&"boolean"==typeof this._window.closed&&!this._window.closed?this.close():this._abort.raise(new Error("Popup blocked by user"))},1e3*t.closePopupWindowAfterInSeconds)}async navigate(e){var t;null==(t=this._window)||t.focus();const i=setInterval(()=>{this._window&&!this._window.closed||(this._logger.debug("Popup closed by user or isolated by redirect"),s(),this._disposeHandlers.delete(s),this.abortOnClose&&this._abort.raise(new Error("Popup closed by user")))},500),s=()=>clearInterval(i);return this._disposeHandlers.add(s),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),t||window.opener||window.close()}},Ie=class{constructor(e){this._settings=e,this._logger=new x("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:i,popupAbortOnClose:s}){return new ke({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:i,popupAbortOnClose:s})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),ke.notifyOpener(e,t)}},Te=class{constructor(e){this._settings=e,this._logger=new x("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var i;this._logger.create("prepare");let s=window.self;"top"===t&&(s=null!=(i=window.top)?i:window.self);const r=s.location[e].bind(s.location);let n;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise((t,i)=>{n=i,window.addEventListener("pageshow",()=>t(window.location.href)),r(e.url)});return await t},close:()=>{this._logger.create("close"),null==n||n(new Error("Redirect aborted")),s.stop()}}}async callback(){}},Re=class extends z{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new x("UserManagerEvents"),this._userLoaded=new q("User loaded"),this._userUnloaded=new q("User unloaded"),this._silentRenewError=new q("Silent renew error"),this._userSignedIn=new q("User signed in"),this._userSignedOut=new q("User signed out"),this._userSessionChanged=new q("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},Ae=class{constructor(e){this._userManager=e,this._logger=new x("SilentRenewService"),this._isStarted=!1,this._retryTimer=new H("Retry Silent Renew"),this._tokenExpiring=async()=>{const e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof W)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),await this._userManager.events._raiseSilentRenewError(t)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},Pe=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},Ce=class{constructor(e,t,i,s){this._logger=new x("UserManager"),this.settings=new ve(e),this._client=new he(e),this._redirectNavigator=null!=t?t:new Te(this.settings),this._popupNavigator=null!=i?i:new Ie(this.settings),this._iframeNavigator=null!=s?s:new Ee(this.settings),this._events=new Re(this.settings),this._silentRenewService=new Ae(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new ue(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),i=await this._loadUser();return i?(t.info("user loaded"),await this._events.load(i,e),i):(t.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");const{redirectMethod:i,...s}=e;let r;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(r=await this.generateDPoPJkt(this.settings.dpop));const n=await this._redirectNavigator.prepare({redirectMethod:i});await this._signinStart({request_type:"si:r",dpopJkt:r,...s},n)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),i=await this._signinEnd(e);return i.profile&&i.profile.sub?t.info("success, signed in subject",i.profile.sub):t.info("no subject"),i}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:i=!1}){const s=this._logger.create("signinResourceOwnerCredential"),r=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:i,extraTokenParams:this.settings.extraTokenParams});s.debug("got signin response");const n=await this._buildUser(r);return n.profile&&n.profile.sub?s.info("success, signed in subject",n.profile.sub):s.info("no subject"),n}async signinPopup(e={}){var t;const i=this._logger.create("signinPopup");let s;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:r,popupWindowTarget:n,popupSignal:o,popupAbortOnClose:a,...c}=e,d=this.settings.popup_redirect_uri;d||i.throw(new Error("No popup_redirect_uri configured"));const l=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:n,popupSignal:o,popupAbortOnClose:a}),g=await this._signin({request_type:"si:p",redirect_uri:d,display:"popup",dpopJkt:s,...c},l);return g&&(g.profile&&g.profile.sub?i.info("success, signed in subject",g.profile.sub):i.info("no subject")),g}async signinPopupCallback(e=window.location.href,t=!1){const i=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),i.info("success")}async signinSilent(e={}){var t,i;const s=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:r,...n}=e;let o,a=await this._loadUser();if(!e.forceIframeAuth&&(null==a?void 0:a.refresh_token)){s.debug("using refresh token");const e=new Pe(a);return await this._useRefreshToken({state:e,redirect_uri:n.redirect_uri,resource:n.resource,extraTokenParams:n.extraTokenParams,timeoutInSeconds:r})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(o=await this.generateDPoPJkt(this.settings.dpop));const c=this.settings.silent_redirect_uri;let d;c||s.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(s.debug("subject prior to silent renew:",a.profile.sub),d=a.profile.sub);const l=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r});return a=await this._signin({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:o,...n},l,d),a&&((null==(i=a.profile)?void 0:i.sub)?s.info("success, signed in subject",a.profile.sub):s.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),i=new pe({...e.state,...t});return await this.storeUser(i),await this._events.load(i),i}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:i}=await this._client.readSignoutResponseState(e);if(i)switch(i.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:i,...s}=e,r=this.settings.silent_redirect_uri;r||t.throw(new Error("No silent_redirect_uri configured"));const n=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:i}),a=await this._signinStart({request_type:"si:s",redirect_uri:r,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==n?void 0:n.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...s},o);try{const e={},i=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),i.session_state&&i.profile.sub?(t.info("success for subject",i.profile.sub),{session_state:i.session_state,sub:i.profile.sub}):(t.info("success, user not authenticated"),null)}catch(e){if(this.settings.monitorAnonymousSession&&e instanceof j)switch(e.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:e.session_state}}throw e}}async _signin(e,t,i){const s=await this._signinStart(e,t);return await this._signinEnd(s.url,i)}async _signinStart(e,t){const i=this._logger.create("_signinStart");try{const s=await this._client.createSigninRequest(e);return i.debug("got signin request"),await t.navigate({url:s.url,state:s.state.id,response_mode:s.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw i.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signinEnd(e,t){const i=this._logger.create("_signinEnd"),s=await this._client.processSigninResponse(e,{});return i.debug("got signin response"),await this._buildUser(s,t)}async _buildUser(e,t){const i=this._logger.create("_buildUser"),s=new pe(e);if(t){if(t!==s.profile.sub)throw i.debug("current user does not match user returned from signin. sub from signin:",s.profile.sub),new j({...e,error:"login_required"});i.debug("current user matches user returned from signin")}return await this.storeUser(s),i.debug("user stored"),await this._events.load(s),s}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:i,...s}=e,r=await this._redirectNavigator.prepare({redirectMethod:i});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...s},r),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),i=await this._signoutEnd(e);return t.info("success"),i}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:i,popupWindowTarget:s,popupSignal:r,...n}=e,o=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:i,popupWindowTarget:s,popupSignal:r});await this._signout({request_type:"so:p",post_logout_redirect_uri:o,state:null==o?void 0:{},...n},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const i=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),i.info("success")}async _signout(e,t){const i=await this._signoutStart(e,t);return await this._signoutEnd(i.url)}async _signoutStart(e={},t){var i;const s=this._logger.create("_signoutStart");try{const r=await this._loadUser();s.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(r);const n=e.id_token_hint||r&&r.id_token;n&&(s.debug("setting id_token_hint in signout request"),e.id_token_hint=n),await this.removeUser(),s.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return s.debug("got signout request"),await t.navigate({url:o.url,state:null==(i=o.state)?void 0:i.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw s.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),i=await this._client.processSignoutResponse(e);return t.debug("got signout response"),i}async signoutSilent(e={}){var t;const i=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:s,...r}=e,n=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,o=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:n,...r},a),i.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const i=this._logger.create("_revokeInternal");if(!e)return;const s=t.filter(t=>"string"==typeof e[t]);if(s.length){for(const t of s)await this._client.revokeToken(e[t],t),i.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),i.debug("user stored"),await this._events.load(e)}else i.debug("no need to revoke due to no token(s)")}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),pe.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const i=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,i)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,i,s){var r,n;const o=await(null==(n=null==(r=this.settings.dpop)?void 0:r.store)?void 0:n.get(this.settings.client_id));if(o)return await D.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:i,keyPair:o.keys,nonce:s})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const i=await D.generateDPoPKeys();t=new ge(i),await e.store.set(this.settings.client_id,t)}return await D.generateDPoPJkt(t.keys)}};const Oe="OAUTH2_LOGIN_FLOW_COMPLETE_EVENT",xe="OAUTH_GET_TOP_URL",Ue="OAUTH_REDIRECT_TOP_WINDOW",Ne="OAUTH_UPDATE_URL",Le="OAUTH2_CHECK_PENDING",De={ORIGIN:"origin",TOP_ORIGIN:"oauth2_top_origin",TOP_WP_URL:"oauth2_top_wp_url",LOGIN_SUCCESS:"oauth2_login_success",STATE:"oauth2_state"},qe=60,Me=Math.max(qe-15,20),He=l("oidc-auth",{color:"green"}),$e=e=>He.extend(e);l("oidc-auth-utils");const Ge=()=>"undefined"==typeof window?"":new URLSearchParams(window.location.search).get("origin")||"";class je{static instance=null;settings=null;constructor(){}static getInstance(){return je.instance||(je.instance=new je),je.instance}configure(e){this.settings=e}isConfigured(){return null!==this.settings}getSettings(){if(!this.settings)throw new Error("OidcAuthConfig not configured. Call configure() or pass settings to OidcAuthClient.initialize().");return this.settings}getAuthOrigin(){const{authOrigin:e,authEndpoint:t}=this.getSettings();return e||new URL(t).origin}isAccessTokenProactiveRefreshEnabled(){return this.settings?.accessTokenProactiveRefreshEnabled??!0}getOidcSettings(){const e="undefined"==typeof window?"":window.location.origin,{clientId:t,authEndpoint:i}=this.getSettings(),s=this.getAuthOrigin(),r="undefined"!=typeof window?new V({store:window.localStorage}):void 0,{accessTokenExpiringNotificationTimeInSeconds:n=qe}=this.getSettings();return{client_id:t,authority:s,redirect_uri:`${e}/login/oauth-callback`,post_logout_redirect_uri:e,response_type:"code",scope:"openid offline_access",automaticSilentRenew:!1,accessTokenExpiringNotificationTimeInSeconds:n,stateStore:r,userStore:r,metadata:{issuer:s,authorization_endpoint:i,token_endpoint:`${s}/connect/api/v1/oauth2/token`,end_session_endpoint:`${s}/logout/`}}}getAccessTokenExpiringNotificationTimeInSeconds(){return this.getSettings().accessTokenExpiringNotificationTimeInSeconds??qe}getAccessTokenFreshnessThresholdInSeconds(){return this.getSettings().accessTokenFreshnessThresholdInSeconds??Me}getAllowedParentOrigins(){return this.settings?.allowedParentOrigins}}const We=je.getInstance(),ze=$e("oidc-auth:host-api"),Fe=async e=>new Promise((t,i)=>{const s=new MessageChannel;let r=!1;const n=()=>{r=!0,s.port1.close()},o=setTimeout(()=>{r||(n(),i(new Error(`Host message timeout: ${e.type}`)))},1e4);s.port1.onmessage=e=>{clearTimeout(o),n(),"success"!==e.data.status?i(e.data.payload):t(e.data.payload)};const a=new URLSearchParams(window.location.search).get("origin")||"";if(!function(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return!1;const t=We.getAllowedParentOrigins();return!t||0===t.length||t.includes(e)}(a))return clearTimeout(o),n(),void i(new Error("Origin not allowed"));ze.log("posting message to host",e),window.top.postMessage({type:e.type,payload:e.payload,...e.data||{}},a,[s.port2])}),Ke=$e("oidc-auth:OidcAuthTimer");class Je{timerHandle=null;expiration=null;initialized=!1;callback=()=>{};constructor(){this.timerHandle=null}init(e,t,i){const s=e-this.getEpochTime(),r=Math.max(s-t,10);this.cancel(),this.expiration=r,this.callback=i,Ke.debug("OIDC: timer - using expiration",r,s,t,e,s-t),this.timerHandle=setTimeout(this.callback,1e3*r),this.initialized=!0}cancel(){this.timerHandle&&(clearTimeout(this.timerHandle),this.timerHandle=null),this.expiration=null}getEpochTime(){return Math.floor(Date.now()/1e3)}isInitialized(){return this.initialized}}const Be=$e("oidc-auth:OidcAuthClient");class Qe{static instance=null;userManager=null;initialized=!1;accessTokenExpiringTimer=null;retryTimers=new Set;constructor(){}static getInstance(){return Qe.instance||(Qe.instance=new Qe),Qe.instance}isInitialized(){return this.initialized}ensureInitialized(){if(!this.userManager)throw new Error("OidcAuthClient not initialized. Call initialize() first.");return this.userManager}initialize(e){if(e&&(this.initialized=!1,We.configure(e)),this.initialized)Be.info("OIDC: initialize() - already initialized, skipping");else if("undefined"!=typeof window)if(We.isConfigured())try{Be.info("OIDC: initialize() - starting initialization");const e=We.getOidcSettings();this.userManager=new Ce(e),O.setLogger(Be),O.setLevel(O.ERROR),this.initAccessTokenExpiringTimer(),this.initialized=!0}catch(e){throw Be.error("OIDC: initialize() - FAILED:",e),e}else Be.warn("OIDC: initialize() - skipped, config not set");else Be.warn("OidcAuthClient cannot initialize on server side")}async initAccessTokenExpiringTimer(){We.isAccessTokenProactiveRefreshEnabled()?this.getUser().then(e=>{const t=e?.expires_at;t&&(this.accessTokenExpiringTimer||(this.accessTokenExpiringTimer=new Je),this.accessTokenExpiringTimer.init(t,We.getAccessTokenExpiringNotificationTimeInSeconds(),async()=>{Be.info("OIDC: timer proactive refresh access token expiring timer fired",t),this.proactiveRefreshWithRetry()}))}).catch(e=>{Be.error("OIDC: initAccessTokenExpiringTimer - FAILED:",e)}):Be.warn("OIDC: timer - not starting, access token proactive refresh is disabled")}async getUser(){if(!this.userManager)return null;try{return await this.userManager.getUser()}catch(e){return Be.error("OIDC: getUser - FAILED:",e),null}}async storeUser(e){const t=this.ensureInitialized();await t.storeUser(e)}async getAccessToken(){const e=await this.getUser();if(!e)return Be.info("OIDC: getAccessToken - no user found"),null;if(e.expired)try{const e=await this.signinSilent();return e?.access_token||null}catch(e){return Be.error("OIDC: getAccessToken - silent renew failed:",e),null}return this.isTokenFresh(e)||this.signinSilent().catch(e=>{Be.error("OIDC: getAccessToken - background refresh failed:",e)}),e.access_token}getUserData(){if("undefined"==typeof window)return null;try{const e=We.getOidcSettings(),t=`oidc.user:${e.authority}:${e.client_id}`,i=localStorage.getItem(t);if(!i)return null;const s=JSON.parse(i),r=s?.profile;return r?.sub?(Be.info("OIDC: USER:",{profile:r}),{id:r.sub,email:r.email||"",first_name:r.given_name,last_name:r.family_name}):null}catch(e){return Be.error("OIDC: getUserData - FAILED:",e),null}}async isAuthenticated(){const e=await this.getUser();return null!==e&&!e.expired}async signinRedirect(e){const t=this.ensureInitialized();await t.signinRedirect({state:e?{data:e}:void 0,prompt:"login"})}async signinCallback(){const e=this.ensureInitialized(),t=await e.signinCallback();if(!t)throw Be.error("OIDC: signinCallback - FAILED: no user returned"),new Error("Signin callback failed: no user returned");return t}async signinSilent(e){return this.ensureInitialized(),"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request("oidc-token-refresh",async()=>{const t=await this.getUser();return t&&this.isTokenFresh(t,e)?t:this.doSigninSilent()}):(Be.warn("OIDC: signinSilent - navigator.locks not available, proceeding without lock"),this.doSigninSilent())}isTokenFresh(e,t){if(!e.expires_at)return!1;const i=t??We.getAccessTokenFreshnessThresholdInSeconds(),s=Math.floor(Date.now()/1e3);return e.expires_at-s>i}async doSigninSilent(){const e=this.ensureInitialized();try{return await e.signinSilent()}catch(e){throw Be.error("OIDC: doSigninSilent - FAILED:",e),e}}proactiveRefreshWithRetry(e=1){if("undefined"!=typeof document&&"hidden"===document.visibilityState){Be.info("OIDC: tab is hidden, deferring proactive refresh until visible");const t=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",t),this.proactiveRefreshWithRetry(e))};return void document.addEventListener("visibilitychange",t)}this.signinSilent(We.getAccessTokenExpiringNotificationTimeInSeconds()).then(()=>{this.initAccessTokenExpiringTimer()}).catch(t=>{if(Be.error(`OIDC: proactive refresh failed (attempt ${e}/2):`,t),e<2){const t=setTimeout(()=>{this.retryTimers.delete(t),this.proactiveRefreshWithRetry(e+1)},3e3);this.retryTimers.add(t)}else Be.error("OIDC: proactive refresh exhausted all retries")})}async removeUser(){const e=this.ensureInitialized();this.accessTokenExpiringTimer?.cancel(),this.retryTimers.forEach(clearTimeout),this.retryTimers.clear(),await e.removeUser()}onUserLoaded(e){this.ensureInitialized().events.addUserLoaded(e)}offUserLoaded(e){this.ensureInitialized().events.removeUserLoaded(e)}onUserUnloaded(e){this.ensureInitialized().events.addUserUnloaded(e)}offUserUnloaded(e){this.ensureInitialized().events.removeUserUnloaded(e)}onSilentRenewError(e){this.ensureInitialized().events.addSilentRenewError(e)}offSilentRenewError(e){this.ensureInitialized().events.removeSilentRenewError(e)}onAccessTokenExpiring(e){this.ensureInitialized().events.addAccessTokenExpiring(e)}offAccessTokenExpiring(e){this.ensureInitialized().events.removeAccessTokenExpiring(e)}onAccessTokenExpired(e){this.ensureInitialized().events.addAccessTokenExpired(e)}offAccessTokenExpired(e){this.ensureInitialized().events.removeAccessTokenExpired(e)}getLogoutUrl(e,t){const i=new URL(function(e){return`${We.getAuthOrigin()}${e.logoutPath}`}(e));return t&&i.searchParams.set("redirect_to",t),i.toString()}getWindowOriginParam(){const e=new URL(window.location.href).searchParams.get(De.ORIGIN);if(!e)throw new Error("iframe origin param is required");return e}async getTopUrl(){return(await Fe({type:xe})).topUrl}async isOAuthFlowPending(){try{return(await Fe({type:Le})).isPending}catch(e){return Be.warn("OIDC: isOAuthFlowPending() - failed to check, assuming not pending:",e),!1}}async triggerLoginFlowViaParent({loginPath:e,windowPath:t}){Be.info("OIDC: triggerLoginFlowViaParent() - starting");const i=await this.getTopUrl(),s=new URL(i).origin,r=`${s}${t}`,n=new URL(`${window.location.origin}${e}`);n.searchParams.set(De.TOP_ORIGIN,s),n.searchParams.set(De.TOP_WP_URL,r),Be.info("OIDC: triggerLoginFlowViaParent() - redirecting parent to:",n.toString()),await Fe({type:Ue,payload:{url:n.toString()}})}async handleLoginFlowComplete(e,t){if(!t)throw new Error("oauthUserState is required");const i=this.getWindowOriginParam(),s=t.state,r=s?.data?.[De.TOP_ORIGIN];if(i!==r)throw Be.error("OIDC: handleLoginFlowComplete - origin mismatch:",i,"!==",r),new Error("Invalid origin in OAuth state");try{const e=new pe(t);await this.storeUser(e),this.initAccessTokenExpiringTimer(),window.dispatchEvent(new CustomEvent("oidc-auth-completed"))}catch(t){Be.error("OIDC: handleLoginFlowComplete - FAILED to store user:",t),await this.triggerLoginFlowViaParent(e)}}async triggerLogoutViaParent(e,t=!0){const i=await this.getTopUrl(),s=new URL(i).origin,r=t?`${s}${e.windowPath}`:s;await this.removeUser();const n=this.getLogoutUrl(e,r);await Fe({type:Ue,payload:{url:n}})}async cleanOAuthParamsFromUrl(){try{const e=await this.getTopUrl(),t=new URL(e);t.searchParams.delete("oauth_code"),t.searchParams.delete("oauth_state"),t.searchParams.delete("start-oauth"),t.searchParams.delete(De.LOGIN_SUCCESS),t.searchParams.delete(De.STATE),await Fe({type:Ne,payload:{url:t.toString()}})}catch(e){Be.warn("Failed to clean OAuth params from URL:",e)}}setupLoginFlowMessageListener(e){let t=!1;const i=i=>{if(i.data?.type!==Oe)return;if(i.origin!==Ge())return void Be.error("OIDC: origin mismatch - expected:",Ge(),"received:",i.origin);if(t)return void Be.debug("OIDC: LOGIN_FLOW_COMPLETE already processed, ignoring duplicate");const s=i.data.payload;s?.oauthState?(t=!0,this.handleLoginFlowComplete(e,s.oauthState).catch(e=>{Be.error("OIDC: Failed to handle login flow complete:",e),t=!1})):Be.warn("OIDC: LOGIN_FLOW_COMPLETE but no oauthState in payload")};return window.addEventListener("message",i),()=>{window.removeEventListener("message",i)}}async getTokenExpirationInfo(){const e=await this.getUser();if(!e||!e.expires_at)return{expiresAt:null,expiresInSeconds:null,isExpired:!0};const t=new Date(1e3*e.expires_at),i=Date.now(),s=Math.floor((1e3*e.expires_at-i)/1e3);return{expiresAt:t,expiresInSeconds:s,isExpired:s<=0}}async forceTokenRefresh(){return Be.info("OIDC: forceTokenRefresh() - manually triggering token refresh"),this.signinSilent()}}const Ve=Qe.getInstance();"undefined"!=typeof window&&(window.oidcAuthClient=Ve);const Xe=$e("oidc-auth:oidc-auth-redirect");function Ye(e,t){e.postMessage({status:"success",payload:t})}function Ze(e,t){e.postMessage({status:"error",payload:t})}function et({targets:e,onSuccess:t,attempt:i=1}){const s=new URLSearchParams(window.location.search);if(!s.get(De.LOGIN_SUCCESS))return void Xe.warn("OIDC: No login_success param found, skipping");const r=s.get(De.STATE);if(r){if(!e.window?.contentWindow||!e.windowURL)return Xe.warn("Cannot forward OIDC state: iframe not available"),void(i<5?setTimeout(()=>{et({targets:e,onSuccess:t,attempt:i+1})},500):Xe.error("OIDC: Failed to forward login flow after",5,"attempts - iframe never became available"));try{const i=JSON.parse(r),s=i.state?.data?.[De.TOP_ORIGIN];if(s&&s!==window.location.origin)return void Xe.error("Origin mismatch in OIDC state:",s,"vs",window.location.origin);!function(e,t){const i=t.window?.contentWindow,s=t.windowURL?.origin;i&&s?i.postMessage({type:Oe,payload:e},s):Xe.warn("Cannot send OIDC state: window or origin not available")}({oauthState:i},e);const n=new URL(window.location.href);n.searchParams.delete(De.LOGIN_SUCCESS),n.searchParams.delete(De.STATE),history.replaceState({},"",n.toString()),t?.()}catch(e){Xe.error("Failed to parse or forward OIDC state:",e)}}else Xe.warn("OIDC login complete but no state found in URL")}const tt=h("oauth");function it(){try{localStorage.setItem("angie_sidebar_state","open")}catch(e){tt.warn("localStorage not available")}setTimeout(()=>{window.toggleAngieSidebar(!0)},500)}const st=(e,t)=>{const i=document.getElementById("angie-sidebar-container");i&&i.setAttribute("aria-hidden",t?"false":"true"),t?e.removeAttribute("tabindex"):e.setAttribute("tabindex","-1")},rt=(e,t)=>{e.postMessage({status:"success",payload:t})},nt=()=>new Promise(e=>{"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e(null)}),ot=h("sdk");var at;!function(e){e.POST_MESSAGE="postMessage"}(at||(at={}));const ct=h("iframe-utils");let dt=null;const lt=()=>(dt&&document.contains(dt)||(dt=document.querySelector('iframe[src*="angie/"]')),dt),gt=(e,t)=>{ct.log("postMessageToAngieIframe",e,t);const i=lt();if(!i?.contentWindow)return!1;const s=t||(()=>{const e=lt();if(!e)return null;try{return new URL(e.src).origin}catch(e){return ct.error("Error parsing iframe URL:",e),null}})();return s?(i.contentWindow.postMessage(e,s),!0):(ct.error("Could not determine target origin for Angie iframe"),!1)},ht="/* Angie Sidebar - CSS Variables */\n:root {\n --angie-sidebar-z-index: 1200; /* below MUI popups, elementor popups and media library modal */\n --angie-sidebar-width: 330px;\n --angie-sidebar-transition: margin 0.3s ease-in-out, transform 0.3s ease-in-out;\n /* Direction-aware transform values for sidebar positioning */\n --angie-sidebar-hide-transform: translateX(-100%); /* LTR: hide to the left */\n --angie-sidebar-show-transform: translateX(0);\n}\n\n/* RTL-specific transform values */\n[dir=\"rtl\"] {\n --angie-sidebar-hide-transform: translateX(100%); /* RTL: hide to the right */\n}\n\n/* Respect user's motion preferences */\n@media (prefers-reduced-motion: reduce) {\n :root {\n --angie-sidebar-transition: none;\n }\n}\n\n/* Apply transitions only when user is actively toggling */\nbody.angie-sidebar-transitioning {\n transition: var(--angie-sidebar-transition) !important;\n}\n\nbody.angie-sidebar-transitioning #angie-sidebar-container {\n transition: var(--angie-sidebar-transition) !important;\n}\n\n/* Layout (default) - Push content */\n@media (min-width: 768px) {\n body.angie-sidebar-active {\n padding-inline-start: var(--angie-sidebar-width) !important;\n }\n\n #angie-sidebar-container {\n position: fixed;\n top: 0;\n inset-inline-start: 0;\n width: var(--angie-sidebar-width);\n height: 100vh;\n z-index: var(--angie-sidebar-z-index) !important; /* below elementor popups and media library modal */\n background: #FCFCFC;\n transform: var(--angie-sidebar-hide-transform);\n outline: none;\n overflow: hidden;\n /* No default transition - only when transitioning */\n }\n\n /* Resize handle */\n #angie-sidebar-container::after {\n content: '';\n position: absolute;\n top: 0;\n inset-inline-end: 0;\n width: 4px;\n height: 100%;\n cursor: ew-resize;\n background: transparent;\n z-index: 1000001;\n }\n\n /* Pink border during resize */\n #angie-sidebar-container.angie-resizing {\n border-inline-end-color: #ff69b4 !important;\n border-inline-end-width: 2px !important;\n }\n\n /* Disable iframe pointer events during resize */\n #angie-sidebar-container.angie-resizing iframe#angie-iframe {\n pointer-events: none !important;\n }\n}\n\n/* Active states */\nbody.angie-sidebar-active #angie-sidebar-container {\n transform: var(--angie-sidebar-show-transform);\n}\n\n/* Studio mode - sidebar takes full width */\n@media (min-width: 768px) {\n html.angie-studio-active body.angie-sidebar-active #angie-sidebar-container {\n width: 100%;\n }\n}\n\n/* High contrast mode support */\n@media (prefers-contrast: high) {\n #angie-sidebar-container {\n border-color: #000;\n box-shadow: none;\n }\n}\n\n/* Screen reader only class */\n.angie-sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n/* Plugin conflict resolution */\nbody.angie-sidebar-active {\n /* Reset common conflicting styles */\n box-sizing: border-box !important;\n position: relative !important;\n}\n\n#angie-sidebar-toggle {\n z-index: 99999 !important;\n}\n",ut=h("sidebar");let pt=!1;const _t="open",wt="closed",mt=350,ft=590,yt=370;function St(){if("undefined"==typeof window)return yt;try{const e=window.localStorage.getItem("angie_sidebar_width");if(e){const t=parseInt(e,10);if(t>=mt&&t<=ft)return t}}catch(e){ut.warn("localStorage not available")}return yt}function vt(){return"undefined"==typeof window?null:localStorage.getItem("angie_sidebar_state")}function bt(e){try{localStorage.setItem("angie_sidebar_state",e)}catch(e){ut.warn("localStorage not available")}}function Et(e){try{localStorage.setItem("angie_sidebar_width",e.toString())}catch(e){ut.warn("localStorage not available")}}function kt(e){document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`)}function It(){!function(){if("undefined"==typeof window)return!1;const e=new URLSearchParams(window.location.search);return e.has(De.LOGIN_SUCCESS)||e.has(De.STATE)||e.has(De.TOP_ORIGIN)}()?Tt(vt()||_t):function(){Tt(wt);try{localStorage.setItem("angie_sidebar_state",wt)}catch(e){ut.warn("localStorage not available")}}()}function Tt(e){"undefined"!=typeof window&&window.toggleAngieSidebar&&window.toggleAngieSidebar(e===_t,!0)}function Rt(){const e=document.getElementById("angie-sidebar-container");if(!e)return;let t=!1,i=0,s=0;e.addEventListener("mousedown",r=>{const n=e.getBoundingClientRect();("rtl"===document.documentElement.dir?r.clientX<=n.left+4:r.clientX>=n.right-4)&&(t=!0,i=r.clientX,s=n.width,e.classList.add("angie-resizing"),document.body.style.cursor="ew-resize",document.body.style.userSelect="none",r.preventDefault(),r.stopPropagation())}),document.addEventListener("mousemove",e=>{if(!t)return;let r;r="rtl"===document.documentElement.dir?i-e.clientX:e.clientX-i,kt(Math.max(mt,Math.min(ft,s+r))),e.preventDefault(),e.stopPropagation()}),document.addEventListener("mouseup",i=>{if(t){t=!1,e.classList.remove("angie-resizing"),document.body.style.cursor="",document.body.style.userSelect="";const r=parseInt(getComputedStyle(document.documentElement).getPropertyValue("--angie-sidebar-width"),10);Et(r),gt({type:m.ANGIE_SIDEBAR_RESIZED,payload:{initialWidth:s,width:r}}),i.preventDefault(),i.stopPropagation()}}),kt(St())}function At(e){!function(){if("undefined"==typeof document||pt)return;const e="angie-sidebar-styles";if(document.getElementById(e))return void(pt=!0);const t=document.createElement("style");t.id=e,t.textContent=ht;const i=document.head||document.getElementsByTagName("head")[0];i.insertBefore(t,i.firstChild),pt=!0}(),"undefined"!=typeof window&&(window.toggleAngieSidebar=function(e){return function(t,i){const s=document.body,r=document.getElementById("angie-sidebar-container");if(!r)return void ut.warn("Required elements not found!");const n=s.classList.contains("angie-sidebar-active"),o=void 0!==t?t:!n;i||(s.classList.add("angie-sidebar-transitioning"),setTimeout(function(){s.classList.remove("angie-sidebar-transitioning")},300)),o?s.classList.add("angie-sidebar-active"):s.classList.remove("angie-sidebar-active"),o&&setTimeout(function(){gt({type:"focusInput"})},i?0:300),e&&e(o,r,i),bt(o?_t:wt);const a=new CustomEvent("angieSidebarToggle",{detail:{isOpen:o,sidebar:r,skipTransition:i}});document.dispatchEvent(a),gt({type:m.ANGIE_SIDEBAR_TOGGLED,payload:{state:o?"opened":"closed"}})}}(e),window.addEventListener("message",function(e){if(e.data&&"toggleAngieSidebar"===e.data.type){const{force:t,skipTransition:i}=e.data.payload||{};window.toggleAngieSidebar&&window.toggleAngieSidebar(t,i)}}))}const Pt=h("iframe"),Ct=async()=>{if(I.iframe?.contentWindow&&I.iframeUrlObject)try{Pt.log("Disabling navigation prevention in Angie iframe"),I.iframe.contentWindow.postMessage({type:m.ANGIE_DISABLE_NAVIGATION_PREVENTION},I.iframeUrlObject.origin),await new Promise(e=>setTimeout(e,100))}catch(e){throw Pt.error("Failed to disable navigation prevention:",e),e}else Pt.warn("Cannot disable navigation prevention: iframe or origin not available")},Ot=async e=>{if(window.screen.availWidth<=768)return void Pt.log("Mobile detected, skipping iframe injection");let t=document.getElementById("angie-sidebar-container");if(!t){const e=performance.now();if(Pt.log("⏱️ Waiting for sidebar container..."),await new Promise(e=>{let i=0;const s=setInterval(()=>{t=document.getElementById("angie-sidebar-container"),i++,(t||i>20)&&(clearInterval(s),t&&e())},100);setTimeout(()=>{if(clearInterval(s),t)return void e();const i=new MutationObserver(()=>{t=document.getElementById("angie-sidebar-container"),t&&(i.disconnect(),e())});i.observe(document.body,{childList:!0,subtree:!0}),setTimeout(()=>{i.disconnect(),e()},8e3)},2e3)}),Pt.log(`⏱️ Sidebar container detection took: ${(performance.now()-e).toFixed(2)}ms`),!t)return void Pt.error("Sidebar container not found")}const{iframe:i,iframeUrlObject:s}=await(async e=>{const t=e.origin,i=new URL(e.path,t),s=i.pathname.slice(1).replace(/\//,"--")+"-"+Math.random().toString(36).substring(7);return new Promise(r=>{const n=new URL(t);n.pathname=i.pathname;const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";if(n.searchParams.append("colorScheme",e.uiTheme||o||"light"),n.searchParams.append("sdkVersion",e.sdkVersion),n.searchParams.append("instanceId",s),n.searchParams.append("origin",window.location.origin),e.isRTL&&n.searchParams.append("isRTL",e.isRTL?"true":"false"),"localhost"===window.location.hostname&&window.location.search.includes("debug_error")){const e=new URLSearchParams(window.location.search).get("debug_error");e&&n.searchParams.append("debug_error",e)}i.searchParams.forEach((e,t)=>{n.searchParams.set(t,e)}),n.searchParams.set("ver",(new Date).getTime().toString());const a=e.parent||document,c=a.createElement("iframe"),d={"background-color":"transparent","color-scheme":"normal",...e.css};window.addEventListener("message",async e=>{if(e.origin===n.origin)switch(e.data.type){case y.ANGIE_READY:r({iframe:c,iframeUrlObject:n});break;case y.ANGIE_LOADED:c.contentWindow?.postMessage({type:y.HOST_READY,instanceId:s},n.origin)}}),c.setAttribute("src",n.href),c.id="angie-iframe",c.setAttribute("frameborder","0"),c.setAttribute("scrolling","no"),c.setAttribute("style",Object.entries(d).map(([e,t])=>`${e}: ${t}`).join("; ")),c.setAttribute("allow","clipboard-write; clipboard-read"),e.insertCallback?e.insertCallback(c):a.body.appendChild(c)})})({origin:e.origin||"https://angie.elementor.com",path:"angie/wp-admin",insertCallback:e=>{Pt.log("Injecting Angie iframe into sidebar container"),e.setAttribute("title","Angie AI Assistant"),e.setAttribute("role","application"),e.setAttribute("aria-label","Angie AI Assistant Interface");const i=document.getElementById("angie-sidebar-loading");i&&(i.textContent=""),t?.appendChild(e),st(e,!0),e.addEventListener("load",()=>{e.focus()})},css:{width:"100%",height:"100%",border:"none",outline:"none"},uiTheme:e.uiTheme,isRTL:e.isRTL,sdkVersion:"1.2.0"});I.iframe=i,I.iframeUrlObject=s,window.addEventListener("message",e=>{if(e.origin===I.iframeUrlObject?.origin)switch(e.data.type){case f.SET:window.localStorage.setItem(e.data.key,e.data.value);break;case f.GET:{const t=e.ports[0],i=window.localStorage.getItem(e.data.key);t.postMessage({value:i});break}}}),(e=>{window.addEventListener("message",async t=>{const i=t.origin===window.location.origin,s=t.origin===e.iframeUrlObject?.origin;if(i||s)switch(t?.data?.type){case m.SDK_ANGIE_ALL_SERVERS_REGISTERED:break;case m.SDK_ANGIE_READY_PING:{const e=t.ports[0];ot.log("Angie is ready",t),rt(e,{message:"Angie is ready"});break}case m.SDK_REQUEST_CLIENT_CREATION:{const i=t.data.payload;try{const s=t.ports[0],r=new MessageChannel;r.port1.onmessage=e=>{s.postMessage({success:!0,data:e.data})};const n={type:m.SDK_REQUEST_CLIENT_CREATION,payload:{success:!0,...i,clientId:`dynamic-client-${i.serverName}-${i.serverVersion}-${Date.now()}`,requestId:t.data.payload.requestId},timestamp:Date.now()};if(!e.iframe)throw new Error("Iframe not found");e.iframe.contentWindow?.postMessage(n,e.iframeUrlObject?.origin||"",[r.port2])}catch(e){ot.error(`Failed to create client for SDK server "${i.serverName}":`,e)}break}case m.SDK_TRIGGER_ANGIE:ot.log("SDK Trigger Angie received",t.data);try{const{requestId:i,prompt:s,context:r}=t.data.payload;if(!e.iframe)throw new Error("Iframe not found");e.iframe.contentWindow?.postMessage({type:m.SDK_TRIGGER_ANGIE,payload:{requestId:i,prompt:s,context:r}},e.iframeUrlObject?.origin||""),window.postMessage({type:m.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!0,requestId:i,response:"Angie triggered successfully"}},window.location.origin)}catch(e){ot.error("Failed to trigger Angie:",e),window.postMessage({type:m.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!1,requestId:t.data.payload?.requestId,error:e instanceof Error?e.message:"Unknown error"}},window.location.origin)}}})})(I),function({trustedOrigin:e,onOAuthParamsCleared:t}){window.addEventListener("message",i=>{if(i.origin!==e)return;const s=i.ports?.[0];switch(i.data.type){case xe:if(!s)return;Ye(s,{topUrl:window.location.href});break;case Ue:window.location.href=i.data.payload.url;break;case Ne:{if(!s)return;const e=i.data.payload.url;if(!history?.replaceState)return void Ze(s,{message:"URL update not supported in this browser"});try{const i=window.location.href;history.replaceState({},"",e),function(e,t){const i=new URL(e).searchParams,s=new URL(t).searchParams,r=[De.LOGIN_SUCCESS,De.STATE,De.TOP_ORIGIN];return r.some(e=>i.has(e))&&!r.some(e=>s.has(e))}(i,e)&&t?.(),Ye(s,{message:"URL updated successfully"})}catch(e){Ze(s,{message:"URL update failed: "+(e instanceof Error?e.message:"Unknown error")})}break}case Le:if(!s)return;Ye(s,{isPending:"true"===new URLSearchParams(window.location.search).get(De.LOGIN_SUCCESS)})}})}({trustedOrigin:I.iframeUrlObject?.origin??"",onOAuthParamsCleared:it}),(()=>{const e={window:I.iframe,windowURL:I.iframeUrlObject};window.addEventListener("load",()=>{tt.log("OIDC: Window load event fired, forwarding OIDC state if present"),et({targets:e,onSuccess:it})}),et({targets:e,onSuccess:it})})(),window.addEventListener("message",async t=>{if([window.location.origin,e.origin||"https://angie.elementor.com"].includes(t.origin))if(t?.data?.type===m.ANGIE_CHAT_TOGGLE)I.open=t.data.open,I.iframe&&st(I.iframe,I.open);else if(t?.data?.type===m.ANGIE_STUDIO_TOGGLE){const e=t.data.isStudioOpen;if(!I.iframe)return;if(e)document.documentElement.classList.add("angie-studio-active");else{const e=St();document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`),document.documentElement.classList.remove("angie-studio-active")}}else if(t?.data?.type===m.ANGIE_NAVIGATE_TO_URL){const{url:e="",confirmed:i=!1}=t.data.payload||{};if(!i)return void Pt.log("Navigation requires user confirmation");if(!((e,t=[])=>{const i=0===t.length&&"undefined"!=typeof window?[window.location.origin]:t;if(!e.startsWith("http"))return!1;try{const t=new URL(e);return i.includes(t.origin)}catch{return!1}})(e))return void Pt.error("Navigation blocked: Invalid or unsafe URL",{url:e});await Ct(),window.location.assign(e)}else if(t?.data?.type===m.ANGIE_PAGE_RELOAD){const{confirmed:e=!1}=t.data.payload||{};if(!e)return void Pt.log("Page reload requires user confirmation");Pt.log("Page reload confirmed - disabling navigation prevention and reloading"),await Ct(),setTimeout(()=>{window.location.reload()},50)}else t?.data?.type===y.RESET_HASH&&(window.location.hash="",rt(t.ports[0],{message:"Hash reset successfully"}))})},xt=h("registration-queue");class Ut{queue=[];isProcessing=!1;add(e){const t={id:this.generateId(e),config:e,timestamp:Date.now(),status:"pending"};return this.queue.push(t),xt.log(`Added server "${e.name}" to queue`),t}getAll(){return[...this.queue]}getPending(){return this.queue.filter(e=>"pending"===e.status)}updateStatus(e,t,i){const s=this.queue.find(t=>t.id===e);s&&(s.status=t,i?s.error=i:"pending"!==t&&"registered"!==t||delete s.error,xt.log(`Updated server ${e} status to ${t}`))}async processQueue(e){if(this.isProcessing)return void xt.log("Already processing queue");this.isProcessing=!0;const t=this.getPending();xt.log(`Processing ${t.length} pending registrations`);try{for(const i of t)try{await e(i),this.updateStatus(i.id,"registered")}catch(e){const t=e instanceof Error?e.message:String(e);this.updateStatus(i.id,"failed",t),xt.error(`Failed to process registration ${i.id}:`,t)}}finally{this.isProcessing=!1}}clear(){this.queue=[],xt.log("Cleared all registrations")}resetAllToPending(){if(this.isProcessing)return xt.log("Cannot reset to pending - processing in progress"),!1;const e=this.queue.filter(e=>"registered"===e.status).length,t=this.queue.filter(e=>"failed"===e.status).length;return this.queue.forEach(e=>{"pending"!==e.status&&(e.status="pending",delete e.error)}),xt.log(`Reset ${e+t} registrations to pending`),!0}remove(e){const t=this.queue.findIndex(t=>t.id===e);return-1!==t&&(this.queue.splice(t,1),xt.log(`Removed registration ${e}`),!0)}generateId(e){return`reg_${e.name}_${e.version}_${Date.now()}`}}class Nt{angieDetector;clientManager;logger;registrationQueue;isInitialized=!1;instanceId;constructor(){this.instanceId=Math.random().toString(36).substring(2,8),this.logger=h({instanceId:this.instanceId}),this.logger.log("Constructor called - initializing SDK"),this.angieDetector=new v,this.registrationQueue=new Ut,this.clientManager=new k,this.logger.log("Setting up event handlers"),this.setupAngieReadyHandler(),this.setupServerInitHandler(),this.setupReRegistrationHandler(),this.logger.log("SDK initialization complete")}async loadSidebar(e){At(),await Ot({origin:e?.origin||"https://angie.elementor.com",uiTheme:e?.uiTheme||"light",isRTL:e?.isRTL||!1,...e}),this.setupPromptHashDetection()}setupReRegistrationHandler(){window.addEventListener("message",e=>{if(e.data?.type===m.SDK_ANGIE_REFRESH_PING)if(this.logger.log("Angie refresh ping received"),this.registrationQueue.resetAllToPending()){const e=this.registrationQueue.getPending().length;this.logger.log(`Successfully reset ${e} registrations, processing queue`),this.handleAngieReady()}else this.logger.log("Skipping queue reset - processing already in progress")})}setupAngieReadyHandler(){this.angieDetector.waitForReady().then(e=>{e.isReady?this.handleAngieReady():this.logger.warn("Angie not detected - servers will remain queued")}).catch(e=>{this.logger.error("Error waiting for Angie:",e)})}async handleAngieReady(){this.logger.log("Angie is ready, processing queued registrations");try{await this.registrationQueue.processQueue(async e=>{this.logger.log(`processQueue callback called for "${e.config.name}"`),await this.processRegistration(e)}),this.isInitialized=!0,this.logger.log("Initialization complete")}catch(e){this.logger.error("Error processing registration queue:",e)}}async processRegistration(e){this.logger.log(`Processing registration for server "${e.config.name}" (ID: ${e.id})`);try{this.logger.log(`Calling clientManager.requestClientCreation for "${e.config.name}"`);const t={...e,instanceId:this.instanceId};await this.clientManager.requestClientCreation(t),this.logger.log(`Successfully registered server "${e.config.name}"`)}catch(t){throw this.logger.error(`Failed to register server "${e.config.name}":`,t),t}}registerLocalServer(e){return e.type=w.LOCAL,e.transport=p.POST_MESSAGE,this.registerServer(e)}registerRemoteServer(e){return e.type=w.REMOTE,this.registerServer(e)}isLocalServerConfig(e){return e.type===w.LOCAL||!e.type&&"server"in e}isRemoteServerConfig(e){return e.type===w.REMOTE&&"url"in e}async registerServer(e){if(!e.type)return this.logger.warn("For a local server, please use registerLocalServer instead of registerServer"),void this.registerLocalServer(e);if(this.logger.log(`registerServer called for "${e.name}"`),!e.name)throw new Error("Server name is required");if(!e.description)throw new Error("Server description is required");if(this.isLocalServerConfig(e)&&!e.server)throw new Error("Server instance is required for local servers");this.logger.log(`Registering server "${e.name}"`);const t=this.registrationQueue.add(e);if(this.logger.log(`Added registration to queue: ${t.id}`),this.angieDetector.isReady())try{await this.processRegistration(t),this.registrationQueue.updateStatus(t.id,"registered"),this.logger.log(`Server "${e.name}" registered successfully`)}catch(e){const i=e instanceof Error?e.message:String(e);throw this.registrationQueue.updateStatus(t.id,"failed",i),e}else this.logger.log(`Server "${e.name}" queued until Angie is ready`)}getRegistrations(){return this.registrationQueue.getAll()}getPendingRegistrations(){return this.registrationQueue.getPending()}isAngieReady(){return this.angieDetector.isReady()}isReady(){return this.isInitialized}async waitForReady(){if(!(await this.angieDetector.waitForReady()).isReady)throw new Error("Angie is not available");for(;!this.isInitialized;)await new Promise(e=>setTimeout(e,100))}async triggerAngie(e){if(!this.isAngieReady())throw new Error("Angie is not ready. Please wait for Angie to be available before triggering.");const t=this.generateRequestId(),i=e.options?.timeout||3e4;return new Promise((s,r)=>{const n=setTimeout(()=>{r(new Error("Angie trigger request timed out"))},i),o=e=>{e.data?.type===m.SDK_TRIGGER_ANGIE_RESPONSE&&e.data?.payload?.requestId===t&&(clearTimeout(n),window.removeEventListener("message",o),s(e.data.payload))};window.addEventListener("message",o);const a={type:m.SDK_TRIGGER_ANGIE,payload:{requestId:t,prompt:e.prompt,options:e.options,context:{pageUrl:window.location.href,pageTitle:document.title,...e.context}},timestamp:Date.now()};this.logger.log(`Triggering Angie with prompt (Request ID: ${t})`),window.postMessage(a,window.location.origin)})}destroy(){this.registrationQueue.clear(),this.logger.log("SDK destroyed")}setupServerInitHandler(){window.addEventListener("message",e=>{e.data?.type===m.SDK_REQUEST_INIT_SERVER&&(this.logger.log("Server init request received"),this.handleServerInitRequest(e))})}handleServerInitRequest(e){const{clientId:t,serverId:i,instanceId:s}=e.data.payload||{};if(t&&i)if(this.logger.log(`Server init request received - Request instanceId: ${s}, This instanceId: ${this.instanceId}`),s&&s!==this.instanceId)this.logger.log(`Ignoring server init request for different instance. Request instanceId: ${s}, this instanceId: ${this.instanceId}`);else{this.logger.log(`Handling server init request for clientId: ${t}, serverId: ${i}`);try{const t=this.registrationQueue.getAll().find(e=>e.id===i);if(!t)return void this.logger.error(`No registration found for serverId: ${i}`);if("type"in t.config&&"remote"===t.config.type)return void this.logger.log("Remote server registration detected; skipping local connect");const s=e.ports[0];if(!s)return void this.logger.error("No port provided in server init request");const r=t.config.server;this.migrateInstructionsCompat(r);const n=new E(s);r.connect(n),this.logger.log(`Server "${t.config.name}" initialized successfully`)}catch(e){this.logger.error(`Error initializing server for clientId ${t}:`,e)}}else this.logger.error("Invalid server init request - missing clientId or serverId")}migrateInstructionsCompat(e){try{const t="server"in e&&e.server?e.server:e,i=t._serverInfo,s=t._instructions;i?.instructions&&!s&&(t._instructions=i.instructions,this.logger.log("Migrated instructions from serverInfo to serverOptions (backward compat)"))}catch{}}generateRequestId(){return`${this.instanceId}-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}async handlePromptHash(){const e=window.location.hash;if(e.startsWith("#angie-prompt="))try{const t=e.replace("#angie-prompt=",""),i=decodeURIComponent(t);if(!i)return void this.logger.warn("Empty prompt detected in hash");this.logger.log("Detected prompt in hash:",i),await this.waitForReady();const s=await this.triggerAngie({prompt:i,context:{source:"hash-parameter",pageUrl:window.location.href,timestamp:(new Date).toISOString()}});this.logger.log("Triggered successfully from hash:",s),window.location.hash=""}catch(e){this.logger.error("Failed to trigger from hash:",e)}}setupPromptHashDetection(){this.handlePromptHash(),window.addEventListener("hashchange",()=>this.handlePromptHash())}}const Lt=h("navigation"),Dt=(e,t)=>{if(lt()){t.isOpen&&window.toggleAngieSidebar&&window.toggleAngieSidebar(!0);const i=gt({type:"angie-route-navigation",path:e,payload:t});return i||Lt.error("Failed to post navigation message to Angie iframe"),i}return Lt.error("Angie iframe not found"),!1},qt="angie_return_url",Mt=h("referrer-redirect");function Ht(e){try{return new URL(e,window.location.origin).origin===window.location.origin}catch{return!1}}function $t(e,t){if(!Ht(e))return Mt.warn("Invalid redirect URL rejected:",e),!1;try{const i={url:e};return t&&(i.prompt=t),localStorage.setItem(qt,JSON.stringify(i)),!0}catch(e){return Mt.warn("localStorage not available"),!1}}function Gt(){try{const e=localStorage.getItem(qt);if(!e)return null;let t;try{t=JSON.parse(e)}catch{return Mt.warn("Stored redirect data is not valid JSON, returning null"),null}return t.url&&"string"==typeof t.url?Ht(t.url)?t:(Mt.warn("Stored redirect URL is invalid, returning null:",t.url),null):(Mt.warn("Stored redirect data missing url field, returning null"),null)}catch(e){return Mt.warn("localStorage not available"),null}}function jt(){try{localStorage.removeItem(qt)}catch(e){Mt.warn("localStorage not available")}}module.exports=t})();
|
|
1
|
+
(()=>{"use strict";var e={d:(t,i)=>{for(var s in i)e.o(i,s)&&!e.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:i[s]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{ANGIE_SIDEBAR_STATE_OPEN:()=>vt,AngieDetector:()=>v,AngieLocalServerTransport:()=>p,AngieMCPTransport:()=>h,AngieMcpSdk:()=>$t,AngieRemoteServerTransport:()=>_,AngieServerType:()=>w,BrowserContextTransport:()=>E,ClientManager:()=>k,HostEventType:()=>y,HostLocalStorageEventType:()=>f,MessageEventType:()=>m,RegistrationQueue:()=>Ht,applyWidth:()=>Ct,clearReferrerRedirect:()=>ot,disableNavigationPrevention:()=>Dt,getAngieIframe:()=>wt,getAngieSidebarSavedState:()=>Rt,getReferrerRedirect:()=>nt,initAngieSidebar:()=>Nt,initializeResize:()=>Ut,loadState:()=>Ot,loadWidth:()=>Tt,navigateAngieIframe:()=>jt,saveState:()=>At,saveWidth:()=>Pt,setReferrerRedirect:()=>rt,toggleAngieSidebar:()=>dt,waitForDocumentReady:()=>gt});const i={none:0,error:1,warn:2,info:3,debug:4},s={error:"error",warn:"warn",info:"info",log:"info",debug:"debug"},r=(e,t)=>i[e]<=i[t],n=e=>"string"==typeof e?e:JSON.stringify(e),o=(e,t)=>`${n(e)} > ${n(t)}`,a=(e,t)=>{let i=`[${n(e)}]`;return typeof window<"u"?{text:`%c${i}`,style:`color: ${t.color||"#00bcd4"}; font-weight: bold;`}:{text:i}},c=(e,t,i,n)=>(...o)=>{if(!r(s[e],n()))return;if(!t)return void console[e](...o);let{text:c,style:d}=a(t,i);d?console[e](c,d,...o):console[e](c,...o)},d=(e,t)=>{let i=t.logLevel??"debug",s=()=>i;return{log:c("log",e,t,s),info:c("info",e,t,s),warn:c("warn",e,t,s),error:c("error",e,t,s),debug:c("debug",e,t,s),setLogLevel:e=>{i=e},extend:s=>d(e?o(e,s):s,{...t,logLevel:i})}},l=(e,t)=>d(e,{color:"#00bcd4",logLevel:"debug",...t}),g=l("angie-sdk",{color:"#00BCD4",logLevel:"error"}),u=e=>g.extend(e);var h,p,_,w,m,f,y;!function(e){e.POST_MESSAGE="postMessage"}(h||(h={})),function(e){e.POST_MESSAGE="postMessage"}(p||(p={})),function(e){e.STREAMABLE_HTTP="streamableHttp",e.SSE="sse"}(_||(_={})),function(e){e.LOCAL="local",e.REMOTE="remote"}(w||(w={})),function(e){e.SDK_ANGIE_READY_PING="sdk-angie-ready-ping",e.SDK_ANGIE_REFRESH_PING="sdk-angie-refresh-ping",e.SDK_ANGIE_ALL_SERVERS_REGISTERED="sdk-angie-all-servers-registered",e.SDK_REQUEST_CLIENT_CREATION="sdk-request-client-creation",e.SDK_REQUEST_INIT_SERVER="sdk-request-init-server",e.SDK_TRIGGER_ANGIE="sdk-trigger-angie",e.SDK_TRIGGER_ANGIE_RESPONSE="sdk-trigger-angie-response",e.ANGIE_SIDEBAR_RESIZED="angie-sidebar-resized",e.ANGIE_SIDEBAR_TOGGLED="angie-sidebar-toggled",e.ANGIE_CHAT_TOGGLE="angie-chat-toggle",e.ANGIE_STUDIO_TOGGLE="angie-studio-toggle",e.ANGIE_NAVIGATE_TO_URL="angie/navigate-to-url",e.ANGIE_PAGE_RELOAD="angie/page-reload",e.ANGIE_DISABLE_NAVIGATION_PREVENTION="angie/disable-navigation-prevention",e.ANGIE_NAVIGATE_AFTER_RESPONSE="angie/navigate-after-response"}(m||(m={})),function(e){e.SET="ANGIE_SET_LOCALSTORAGE",e.GET="ANGIE_GET_LOCALSTORAGE"}(f||(f={})),function(e){e.RESET_HASH="reset-hash",e.HOST_READY="host/ready",e.ANGIE_LOADED="angie/loaded",e.ANGIE_READY="angie/ready"}(y||(y={}));const S=u("angie-detector");class v{isAngieReady=!1;readyPromise;readyResolve;constructor(){if(this.readyPromise=new Promise(e=>{this.readyResolve=e}),"undefined"==typeof window)return;let e=0;const t=()=>{if(this.isAngieReady||e>=500)return void(!this.isAngieReady&&e>=500&&this.handleDetectionTimeout());const i=new MessageChannel;i.port1.onmessage=e=>{this.handleAngieReady(e.data),i.port1.close(),i.port2.close()};const s={type:m.SDK_ANGIE_READY_PING,timestamp:Date.now()};window.postMessage(s,window.location.origin,[i.port2]),e++,setTimeout(t,500)};t()}handleAngieReady(e){this.isAngieReady=!0;const t={isReady:!0,version:e.version,capabilities:e.capabilities};this.readyResolve&&this.readyResolve(t)}handleDetectionTimeout(){this.readyResolve&&this.readyResolve({isReady:!1}),S.warn("Detection timeout - Angie may not be available")}isReady(){return this.isAngieReady}async waitForReady(){return this.readyPromise}}const b=require("@modelcontextprotocol/sdk/types.js");class E{sessionId;onmessage;onerror;onclose;_port;_started=!1;_closed=!1;constructor(e){if(!e)throw new Error("MessagePort is required");this._port=e,this._port.onmessage=e=>{try{const t=b.JSONRPCMessageSchema.parse(e.data);this.onmessage?.(t)}catch(e){const t=new Error(`Failed to parse message: ${e}`);this.onerror?.(t)}},this._port.onmessageerror=e=>{const t=new Error(`MessagePort error: ${JSON.stringify(e)}`);this.onerror?.(t)}}async start(){if(this._started)throw new Error("BrowserContextTransport already started! If using Client or Server class, note that connect() calls start() automatically.");if(this._closed)throw new Error("Cannot start a closed BrowserContextTransport");this._started=!0,this._port.start()}async send(e){if(this._closed)throw new Error("Cannot send on a closed BrowserContextTransport");return new Promise((t,i)=>{try{this._port.postMessage(e),t()}catch(e){const t=e instanceof Error?e:new Error(String(e));this.onerror?.(t),i(t)}})}async close(){this._closed||(this._closed=!0,this._port.close(),this.onclose?.())}}class k{async requestClientCreation(e){const{config:t}=e,i={serverId:e.id,serverName:t.name,serverTitle:t.title,serverVersion:t.version,description:t.description,transport:t.transport||p.POST_MESSAGE,capabilities:t.capabilities,instanceId:e.instanceId};return"type"in t&&"remote"===t.type&&(i.remote={url:t.url}),new Promise((e,t)=>{const s=new MessageChannel,r=setTimeout(()=>{t(new Error("Client creation request timed out after 15000ms"))},15e3);s.port1.onmessage=t=>{clearTimeout(r),e(t.data)};const n={type:m.SDK_REQUEST_CLIENT_CREATION,payload:i,timestamp:Date.now()};window.postMessage(n,window.location.origin,[s.port2])})}}const I={open:!1,iframe:null,iframeUrlObject:null};class T extends Error{}T.prototype.name="InvalidTokenError";var R,A,P,C={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},O=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(O||{});(P=O||(O={})).reset=function(){R=3,A=C},P.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");R=e},P.setLogger=function(e){A=e};var x=class e{constructor(e){this._name=e}debug(...t){R>=4&&A.debug(e._format(this._name,this._method),...t)}info(...t){R>=3&&A.info(e._format(this._name,this._method),...t)}warn(...t){R>=2&&A.warn(e._format(this._name,this._method),...t)}error(...t){R>=1&&A.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,i){const s=new e(`${t}.${i}`);return s.debug("begin"),s}static _format(e,t){const i=`[${e}]`;return t?`${i} ${t}:`:i}static debug(t,...i){R>=4&&A.debug(e._format(t),...i)}static info(t,...i){R>=3&&A.info(e._format(t),...i)}static warn(t,...i){R>=2&&A.warn(e._format(t),...i)}static error(t,...i){R>=1&&A.error(e._format(t),...i)}};O.reset();var U=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new T("Invalid token specified: must be a string");t||(t={});const i=!0===t.header?0:1,s=e.split(".")[i];if("string"!=typeof s)throw new T(`Invalid token specified: missing part #${i+1}`);let r;try{r=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let i=t.charCodeAt(0).toString(16).toUpperCase();return i.length<2&&(i="0"+i),"%"+i}))}(t)}catch(e){return atob(t)}}(s)}catch(e){throw new T(`Invalid token specified: invalid base64 for part #${i+1} (${e.message})`)}try{return JSON.parse(r)}catch(e){throw new T(`Invalid token specified: invalid json for part #${i+1} (${e.message})`)}}(e)}catch(e){throw x.error("JwtUtils.decode",e),e}}static async generateSignedJwt(e,t,i){const s=`${D.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${D.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,r=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},i,(new TextEncoder).encode(s));return`${s}.${D.encodeBase64Url(new Uint8Array(r))}`}static async generateSignedJwtWithHmac(e,t,i){const s=`${D.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${D.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,r=await window.crypto.subtle.sign("HMAC",i,(new TextEncoder).encode(s));return`${s}.${D.encodeBase64Url(new Uint8Array(r))}`}},N=e=>btoa([...new Uint8Array(e)].map(e=>String.fromCharCode(e)).join("")),L=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){const t="10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(+t^e._randomWord()&15>>+t/4).toString(16));return t.replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),i=await crypto.subtle.digest("SHA-256",t);return N(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw x.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const i=(new TextEncoder).encode([e,t].join(":"));return N(i)}static async hash(e,t){const i=(new TextEncoder).encode(t),s=await crypto.subtle.digest(e,i);return new Uint8Array(s)}static async customCalculateJwkThumbprint(t){let i;switch(t.kty){case"RSA":i={e:t.e,kty:t.kty,n:t.n};break;case"EC":i={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":i={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":i={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const s=await e.hash("SHA-256",JSON.stringify(i));return e.encodeBase64Url(s)}static async generateDPoPProof({url:t,accessToken:i,httpMethod:s,keyPair:r,nonce:n}){let o,a;const c={jti:window.crypto.randomUUID(),htm:null!=s?s:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};i&&(o=await e.hash("SHA-256",i),a=e.encodeBase64Url(o),c.ath=a),n&&(c.nonce=n);try{const e=await crypto.subtle.exportKey("jwk",r.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await U.generateSignedJwt(t,c,r.privateKey)}catch(e){throw e instanceof TypeError?new Error(`Error exporting dpop public key: ${e.message}`):e}}static async generateDPoPJkt(t){try{const i=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(i)}catch(e){throw e instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${e.message}`):e}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}static async generateClientAssertionJwt(t,i,s,r="HS256"){const n=Math.floor(Date.now()/1e3),o={alg:r,typ:"JWT"},a={iss:t,sub:t,aud:s,jti:e.generateUUIDv4(),exp:n+300,iat:n},c={HS256:"SHA-256",HS384:"SHA-384",HS512:"SHA-512"}[r];if(!c)throw new Error(`Unsupported algorithm: ${r}. Supported algorithms are: HS256, HS384, HS512`);const d=new TextEncoder,l=await crypto.subtle.importKey("raw",d.encode(i),{name:"HMAC",hash:c},!1,["sign"]);return await U.generateSignedJwtWithHmac(o,a,l)}};L.encodeBase64Url=e=>N(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var D=L,q=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new x(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},M=class{static center({...e}){var t;return null==e.width&&(e.width=null!=(t=[800,720,600,480].find(e=>e<=window.outerWidth/1.618))?t:360),null!=e.left||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),null!=e.height&&(null!=e.top||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter(([,e])=>null!=e).map(([e,t])=>`${e}=${"boolean"!=typeof t?t:t?"yes":"no"}`).join(",")}},H=class e extends q{constructor(){super(...arguments),this._logger=new x(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const i=this._logger.create("init");t=Math.max(Math.floor(t),1);const s=e.getEpochTime()+t;if(this.expiration===s&&this._timerHandle)return void i.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),i.debug("using duration",t),this._expiration=s;const r=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*r)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},$=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const i=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(i.slice(1))}},G=";",j=class extends Error{constructor(e,t){var i,s,r;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw x.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(i=e.error_description)?i:null,this.error_uri=null!=(s=e.error_uri)?s:null,this.state=e.userState,this.session_state=null!=(r=e.session_state)?r:null,this.url_state=e.url_state}},W=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},z=class{constructor(e){this._logger=new x("AccessTokenEvents"),this._expiringTimer=new H("Access token expiring"),this._expiredTimer=new H("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const i=e.expires_in;if(t.debug("access token present, remaining duration:",i),i>0){let e=i-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug("registering expiring timer, raising in",e,"seconds"),this._expiringTimer.init(e)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const s=i+1;t.debug("registering expired timer, raising in",s,"seconds"),this._expiredTimer.init(s)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},F=class{constructor(e,t,i,s,r){this._callback=e,this._client_id=t,this._intervalInSeconds=s,this._stopOnError=r,this._logger=new x("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};const n=new URL(i);this._frame_origin=n.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=n.href}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)})}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,1e3*this._intervalInSeconds)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},K=class{constructor(){this._logger=new x("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},J=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},B=class{constructor(e=[],t=null,i={}){this._jwtHandler=t,this._extraHeaders=i,this._logger=new x("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:i,...s}=t;if(!i)return await fetch(e,s);const r=new AbortController,n=setTimeout(()=>r.abort(),1e3*i);try{return await fetch(e,{...t,signal:r.signal})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw new W("Network timed out");throw e}finally{clearTimeout(n)}}async getJson(e,{token:t,credentials:i,timeoutInSeconds:s}={}){const r=this._logger.create("getJson"),n={Accept:this._contentTypes.join(", ")};let o;t&&(r.debug("token passed, setting Authorization header"),n.Authorization="Bearer "+t),this._appendExtraHeaders(n);try{r.debug("url:",e),o=await this.fetchWithTimeout(e,{method:"GET",headers:n,timeoutInSeconds:s,credentials:i})}catch(e){throw r.error("Network Error"),e}r.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find(e=>a.startsWith(e))&&r.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),o.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(e){if(r.error("Error parsing JSON response",e),o.ok)throw e;throw new Error(`${o.statusText} (${o.status})`)}if(!o.ok){if(r.error("Error from server:",c),c.error)throw new j(c);throw new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:i,timeoutInSeconds:s,initCredentials:r,extraHeaders:n}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...n};let c;void 0!==i&&(a.Authorization="Basic "+i),this._appendExtraHeaders(a);try{o.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:s,credentials:r})}catch(e){throw o.error("Network error"),e}o.debug("HTTP response received, status",c.status);const d=c.headers.get("Content-Type");if(d&&!this._contentTypes.find(e=>d.startsWith(e)))throw new Error(`Invalid response Content-Type: ${null!=d?d:"undefined"}, from URL: ${e}`);const l=await c.text();let g={};if(l)try{g=JSON.parse(l)}catch(e){if(o.error("Error parsing JSON response",e),c.ok)throw e;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(o.error("Error from server:",g),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new J(e,`${JSON.stringify(g)}`)}if(g.error)throw new j(g,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(g)}`)}return g}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),i=Object.keys(this._extraHeaders),s=["accept","content-type"],r=["authorization"];0!==i.length&&i.forEach(i=>{if(s.includes(i.toLocaleLowerCase()))return void t.warn("Protected header could not be set",i,s);if(r.includes(i.toLocaleLowerCase())&&Object.keys(e).includes(i))return void t.warn("Header could not be overridden",i,r);const n="function"==typeof this._extraHeaders[i]?this._extraHeaders[i]():this._extraHeaders[i];n&&""!==n&&(e[i]=n)})}},Q=class{constructor(e){this._settings=e,this._logger=new x("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new B(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const i=this._logger.create(`_getMetadataProperty('${e}')`),s=await this.getMetadata();if(i.debug("resolved"),void 0===s[e]){if(!0===t)return void i.warn("Metadata does not contain optional property");i.throw(new Error("Metadata does not contain property "+e))}return s[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const i=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",i),!Array.isArray(i.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=i.keys,this._signingKeys}},V=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new x("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){return this._logger.create(`get('${e}')`),e=this._prefix+e,await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let i=0;i<e;i++){const e=await this._store.key(i);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},X=class{constructor({authority:e,metadataUrl:t,metadata:i,signingKeys:s,metadataSeed:r,client_id:n,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:d,post_logout_redirect_uri:l,client_authentication:g="client_secret_post",token_endpoint_auth_signing_alg:u="HS256",prompt:h,display:p,max_age:_,ui_locales:w,acr_values:m,resource:f,response_mode:y,filterProtocolClaims:S=!0,loadUserInfo:v=!1,requestTimeoutInSeconds:b,staleStateAgeInSeconds:E=900,mergeClaimsStrategy:k={array:"replace"},disablePKCE:I=!1,stateStore:T,revokeTokenAdditionalContentTypes:R,fetchRequestCredentials:A,refreshTokenAllowedScope:P,extraQueryParams:C={},extraTokenParams:O={},extraHeaders:x={},dpop:U,omitScopeWhenRequesting:N=!1}){var L;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=i,this.metadataSeed=r,this.signingKeys=s,this.client_id=n,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=d,this.post_logout_redirect_uri=l,this.client_authentication=g,this.token_endpoint_auth_signing_alg=u,this.prompt=h,this.display=p,this.max_age=_,this.ui_locales=w,this.acr_values=m,this.resource=f,this.response_mode=y,this.filterProtocolClaims=null==S||S,this.loadUserInfo=!!v,this.staleStateAgeInSeconds=E,this.mergeClaimsStrategy=k,this.omitScopeWhenRequesting=N,this.disablePKCE=!!I,this.revokeTokenAdditionalContentTypes=R,this.fetchRequestCredentials=A||"same-origin",this.requestTimeoutInSeconds=b,T)this.stateStore=T;else{const e="undefined"!=typeof window?window.localStorage:new K;this.stateStore=new V({store:e})}if(this.refreshTokenAllowedScope=P,this.extraQueryParams=C,this.extraTokenParams=O,this.extraHeaders=x,this.dpop=U,this.dpop&&!(null==(L=this.dpop)?void 0:L.store))throw new Error("A DPoPStore is required when dpop is enabled")}},Y=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new x("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const i=U.decode(e);return t.debug("JWT decoding successful"),i}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new B(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const i=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",i);const s=await this._jsonService.getJson(i,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",s),s}},Z=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new x("TokenClient"),this._jsonService=new B(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:i=this._settings.client_id,client_secret:s=this._settings.client_secret,extraHeaders:r,...n}){const o=this._logger.create("exchangeCode");i||o.throw(new Error("A client_id is required")),t||o.throw(new Error("A redirect_uri is required")),n.code||o.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[e,t]of Object.entries(n))null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==s)throw o.throw(new Error("A client_secret is required")),null;let c;const d=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=D.generateBasicAuth(i,s);break;case"client_secret_post":a.append("client_id",i),s&&a.append("client_secret",s);break;case"client_secret_jwt":{const e=await D.generateClientAssertionJwt(i,s,d,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",i),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const l=await this._jsonService.postForm(d,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:r});return o.debug("got response"),l}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:i=this._settings.client_secret,scope:s=this._settings.scope,...r}){const n=this._logger.create("exchangeCredentials");t||n.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set("scope",s);for(const[e,t]of Object.entries(r))null!=t&&o.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==i)throw n.throw(new Error("A client_secret is required")),null;let a;const c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":a=D.generateBasicAuth(t,i);break;case"client_secret_post":o.append("client_id",t),i&&o.append("client_secret",i);break;case"client_secret_jwt":{const e=await D.generateClientAssertionJwt(t,i,c,this._settings.token_endpoint_auth_signing_alg);o.append("client_id",t),o.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),o.append("client_assertion",e);break}}n.debug("got token endpoint");const d=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),d}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:i=this._settings.client_secret,timeoutInSeconds:s,extraHeaders:r,...n}){const o=this._logger.create("exchangeRefreshToken");t||o.throw(new Error("A client_id is required")),n.refresh_token||o.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[e,t]of Object.entries(n))Array.isArray(t)?t.forEach(t=>a.append(e,t)):null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==i)throw o.throw(new Error("A client_secret is required")),null;let c;const d=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=D.generateBasicAuth(t,i);break;case"client_secret_post":a.append("client_id",t),i&&a.append("client_secret",i);break;case"client_secret_jwt":{const e=await D.generateClientAssertionJwt(t,i,d,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",t),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const l=await this._jsonService.postForm(d,{body:a,basicAuth:c,timeoutInSeconds:s,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:r});return o.debug("got response"),l}async revoke(e){var t;const i=this._logger.create("revoke");e.token||i.throw(new Error("A token is required"));const s=await this._metadataService.getRevocationEndpoint(!1);i.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const r=new URLSearchParams;for(const[t,i]of Object.entries(e))null!=i&&r.set(t,i);r.set("client_id",this._settings.client_id),this._settings.client_secret&&r.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(s,{body:r,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),i.debug("got response")}},ee=class{constructor(e,t,i){this._settings=e,this._metadataService=t,this._claimsService=i,this._logger=new x("ResponseValidator"),this._userInfoService=new Y(this._settings,this._metadataService),this._tokenClient=new Z(this._settings,this._metadataService)}async validateSigninResponse(e,t,i){const s=this._logger.create("validateSigninResponse");this._processSigninState(e,t),s.debug("state processed"),await this._processCode(e,t,i),s.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),s.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),s.debug("claims processed")}async validateCredentialsResponse(e,t){const i=this._logger.create("validateCredentialsResponse"),s=e.isOpenId&&!!e.id_token;s&&this._validateIdTokenAttributes(e),i.debug("tokens validated"),await this._processClaims(e,t,s),i.debug("claims processed")}async validateRefreshResponse(e,t){const i=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),i.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const s=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,s),i.debug("claims processed")}validateSignoutResponse(e,t){const i=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&i.throw(new Error("State does not match")),i.debug("state validated"),e.userState=t.data,e.error)throw i.warn("Response was error",e.error),new j(e)}_processSigninState(e,t){const i=this._logger.create("_processSigninState");if(t.id!==e.state&&i.throw(new Error("State does not match")),t.client_id||i.throw(new Error("No client_id on state")),t.authority||i.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&i.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&i.throw(new Error("client_id mismatch on settings vs. signin state")),i.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw i.warn("Response was error",e.error),new j(e);t.code_verifier&&!e.code&&i.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,i=!0){const s=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void s.debug("not loading user info");s.debug("loading user info");const r=await this._userInfoService.getClaims(e.access_token);s.debug("user info claims received from user info endpoint"),i&&r.sub!==e.profile.sub&&s.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(r)),s.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,i){const s=this._logger.create("_processCode");if(e.code){s.debug("Validating code");const r=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:i,...t.extraTokenParams});Object.assign(e,r)}else s.debug("No code to process")}_validateIdTokenAttributes(e,t){var i;const s=this._logger.create("_validateIdTokenAttributes");s.debug("decoding ID Token JWT");const r=U.decode(null!=(i=e.id_token)?i:"");if(r.sub||s.throw(new Error("ID Token is missing a subject claim")),t){const e=U.decode(t);r.sub!==e.sub&&s.throw(new Error("sub in id_token does not match current sub")),r.auth_time&&r.auth_time!==e.auth_time&&s.throw(new Error("auth_time in id_token does not match original auth_time")),r.azp&&r.azp!==e.azp&&s.throw(new Error("azp in id_token does not match original azp")),!r.azp&&e.azp&&s.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=r}},te=class e{constructor(e){this.id=e.id||D.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=H.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new x("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return x.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,i){const s=x.createStatic("State","clearStaleState"),r=H.getEpochTime()-i,n=await t.getAllKeys();s.debug("got keys",n);for(let i=0;i<n.length;i++){const o=n[i],a=await t.get(o);let c=!1;if(a)try{const t=await e.fromStorageString(a);s.debug("got item from key:",o,t.created),t.created<=r&&(c=!0)}catch(e){s.error("Error parsing state for key:",o,e),c=!0}else s.debug("no item in storage for key:",o),c=!0;c&&(s.debug("removed item for key:",o),t.remove(o))}}},ie=class e extends te{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(t){const i=!0===t.code_verifier?D.generateCodeVerifier():t.code_verifier||void 0,s=i?await D.generateCodeChallenge(i):void 0;return new e({...t,code_verifier:i,code_challenge:s})}toStorageString(){return new x("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){x.createStatic("SigninState","fromStorageString");const i=JSON.parse(t);return e.create(i)}},se=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:i,client_id:s,redirect_uri:r,response_type:n,scope:o,state_data:a,response_mode:c,request_type:d,client_secret:l,nonce:g,url_state:u,resource:h,skipUserInfo:p,extraQueryParams:_,extraTokenParams:w,disablePKCE:m,dpopJkt:f,omitScopeWhenRequesting:y,...S}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!s)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!r)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!n)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!o)throw this._logger.error("create: No scope passed"),new Error("scope");if(!i)throw this._logger.error("create: No authority passed"),new Error("authority");const v=await ie.create({data:a,request_type:d,url_state:u,code_verifier:!m,client_id:s,authority:i,redirect_uri:r,response_mode:c,client_secret:l,scope:o,extraTokenParams:w,skipUserInfo:p}),b=new URL(t);b.searchParams.append("client_id",s),b.searchParams.append("redirect_uri",r),b.searchParams.append("response_type",n),y||b.searchParams.append("scope",o),g&&b.searchParams.append("nonce",g),f&&b.searchParams.append("dpop_jkt",f);let E=v.id;u&&(E=`${E}${G}${u}`),b.searchParams.append("state",E),v.code_challenge&&(b.searchParams.append("code_challenge",v.code_challenge),b.searchParams.append("code_challenge_method","S256")),h&&(Array.isArray(h)?h:[h]).forEach(e=>b.searchParams.append("resource",e));for(const[e,t]of Object.entries({response_mode:c,...S,..._}))null!=t&&b.searchParams.append(e,t.toString());return new e({url:b.href,state:v})}};se._logger=new x("SigninRequest");var re=se,ne=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(G);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(G))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-H.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+H.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},oe=class{constructor({url:e,state_data:t,id_token_hint:i,post_logout_redirect_uri:s,extraQueryParams:r,request_type:n,client_id:o,url_state:a}){if(this._logger=new x("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(i&&c.searchParams.append("id_token_hint",i),o&&c.searchParams.append("client_id",o),s&&(c.searchParams.append("post_logout_redirect_uri",s),t||a)){this.state=new te({data:t,request_type:n,url_state:a});let e=this.state.id;a&&(e=`${e}${G}${a}`),c.searchParams.append("state",e)}for(const[e,t]of Object.entries({...r}))null!=t&&c.searchParams.append(e,t.toString());this.url=c.href}},ae=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(G);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(G))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},ce=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],de=["sub","iss","aud","exp","iat"],le=class{constructor(e){this._settings=e,this._logger=new x("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:ce;for(const i of e)de.includes(i)||delete t[i]}return t}mergeClaims(e,t){const i={...e};for(const[e,s]of Object.entries(t))if(i[e]!==s)if(Array.isArray(i[e])||Array.isArray(s))if("replace"==this._settings.mergeClaimsStrategy.array)i[e]=s;else{const t=Array.isArray(i[e])?i[e]:[i[e]];for(const e of Array.isArray(s)?s:[s])t.includes(e)||t.push(e);i[e]=t}else"object"==typeof i[e]&&"object"==typeof s?i[e]=this.mergeClaims(i[e],s):i[e]=s;return i}},ge=class{constructor(e,t){this.keys=e,this.nonce=t}},ue=class{constructor(e,t){this._logger=new x("OidcClient"),this.settings=e instanceof X?e:new X(e),this.metadataService=null!=t?t:new Q(this.settings),this._claimsService=new le(this.settings),this._validator=new ee(this.settings,this.metadataService,this._claimsService),this._tokenClient=new Z(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:i,request_type:s,id_token_hint:r,login_hint:n,skipUserInfo:o,nonce:a,url_state:c,response_type:d=this.settings.response_type,scope:l=this.settings.scope,redirect_uri:g=this.settings.redirect_uri,prompt:u=this.settings.prompt,display:h=this.settings.display,max_age:p=this.settings.max_age,ui_locales:_=this.settings.ui_locales,acr_values:w=this.settings.acr_values,resource:m=this.settings.resource,response_mode:f=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:S=this.settings.extraTokenParams,dpopJkt:v,omitScopeWhenRequesting:b=this.settings.omitScopeWhenRequesting}){const E=this._logger.create("createSigninRequest");if("code"!==d)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const k=await this.metadataService.getAuthorizationEndpoint();E.debug("Received authorization endpoint",k);const I=await re.create({url:k,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:g,response_type:d,scope:l,state_data:e,url_state:c,prompt:u,display:h,max_age:p,ui_locales:_,id_token_hint:r,login_hint:n,acr_values:w,dpopJkt:v,resource:m,request:t,request_uri:i,extraQueryParams:y,extraTokenParams:S,request_type:s,response_mode:f,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:b});await this.clearStaleState();const T=I.state;return await this.settings.stateStore.set(T.id,T.toStorageString()),I}async readSigninResponseState(e,t=!1){const i=this._logger.create("readSigninResponseState"),s=new ne($.readParams(e,this.settings.response_mode));if(!s.state)throw i.throw(new Error("No state in response")),null;const r=await this.settings.stateStore[t?"remove":"get"](s.state);if(!r)throw i.throw(new Error("No matching state found in storage")),null;return{state:await ie.fromStorageString(r),response:s}}async processSigninResponse(e,t,i=!0){const s=this._logger.create("processSigninResponse"),{state:r,response:n}=await this.readSigninResponseState(e,i);if(s.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(n,r,t)}catch(e){if(!(e instanceof J&&this.settings.dpop))throw e;{const i=await this.getDpopProof(this.settings.dpop.store,e.nonce);t.DPoP=i,await this._validator.validateSigninResponse(n,r,t)}}return n}async getDpopProof(e,t){let i,s;return(await e.getAllKeys()).includes(this.settings.client_id)?(s=await e.get(this.settings.client_id),s.nonce!==t&&t&&(s.nonce=t,await e.set(this.settings.client_id,s))):(i=await D.generateDPoPKeys(),s=new ge(i,t),await e.set(this.settings.client_id,s)),await D.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:s.keys,nonce:s.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:i=!1,extraTokenParams:s={}}){const r=await this._tokenClient.exchangeCredentials({username:e,password:t,...s}),n=new ne(new URLSearchParams);return Object.assign(n,r),await this._validator.validateCredentialsResponse(n,i),n}async useRefreshToken({state:e,redirect_uri:t,resource:i,timeoutInSeconds:s,extraHeaders:r,extraTokenParams:n}){var o;const a=this._logger.create("useRefreshToken");let c,d;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(o=e.scope)?void 0:o.split(" "))||[]).filter(e=>t.includes(e)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);r={...r,DPoP:e}}try{d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:i,timeoutInSeconds:s,extraHeaders:r,...n})}catch(o){if(!(o instanceof J&&this.settings.dpop))throw o;r.DPoP=await this.getDpopProof(this.settings.dpop.store,o.nonce),d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:i,timeoutInSeconds:s,extraHeaders:r,...n})}const l=new ne(new URLSearchParams);return Object.assign(l,d),a.debug("validating response",l),await this._validator.validateRefreshResponse(l,{...e,scope:c}),l}async createSignoutRequest({state:e,id_token_hint:t,client_id:i,request_type:s,url_state:r,post_logout_redirect_uri:n=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",c),i||!n||t||(i=this.settings.client_id);const d=new oe({url:c,id_token_hint:t,client_id:i,post_logout_redirect_uri:n,state_data:e,extraQueryParams:o,request_type:s,url_state:r});await this.clearStaleState();const l=d.state;return l&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(l.id,l.toStorageString())),d}async readSignoutResponseState(e,t=!1){const i=this._logger.create("readSignoutResponseState"),s=new ae($.readParams(e,this.settings.response_mode));if(!s.state){if(i.debug("No state in response"),s.error)throw i.warn("Response was error:",s.error),new j(s);return{state:void 0,response:s}}const r=await this.settings.stateStore[t?"remove":"get"](s.state);if(!r)throw i.throw(new Error("No matching state found in storage")),null;return{state:await te.fromStorageString(r),response:s}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:i,response:s}=await this.readSignoutResponseState(e,!0);return i?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(s,i)):t.debug("No state from storage; skipping response validation"),s}clearStaleState(){return this._logger.create("clearStaleState"),te.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},he=class{constructor(e){this._userManager=e,this._logger=new x("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const i=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,i.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,i.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){i.debug("initializing check session iframe");const s=this._userManager.settings.client_id,r=this._userManager.settings.checkSessionIntervalInSeconds,n=this._userManager.settings.stopCheckSessionOnError,o=new F(this._callback,s,e,r,n);await o.load(),this._checkSessionIFrame=o,o.start(t)}else i.warn("no check session iframe found in the metadata")}catch(e){i.error("Error from getCheckSessionIframe:",e instanceof Error?e.message:e)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval(async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(t){e.error("error from querySessionStatus",t instanceof Error?t.message:t)}},1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let i=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(i=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),i?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch(e=>{this._logger.error(e)})}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},pe=class e{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-H.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+H.getEpochTime())}get expired(){const e=this.expires_in;if(void 0!==e)return e<=0}get scopes(){var e,t;return null!=(t=null==(e=this.scope)?void 0:e.split(" "))?t:[]}toStorageString(){return new x("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return x.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},_e="oidc-client",we=class{constructor(){this._abort=new q("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:i,keepOpen:s}=await new Promise((i,s)=>{const r=r=>{var n;const o=r.data,a=null!=(n=e.scriptOrigin)?n:window.location.origin;if(r.origin===a&&(null==o?void 0:o.source)===_e){try{const i=$.readParams(o.url,e.response_mode).get("state");if(i||t.warn("no state found in response url"),r.source!==this._window&&i!==e.state)return}catch{this._dispose(),s(new Error("Invalid response from window"))}i(o)}};window.addEventListener("message",r,!1),this._disposeHandlers.add(()=>window.removeEventListener("message",r,!1));const n=new BroadcastChannel(`oidc-client-popup-${e.state}`);n.addEventListener("message",r,!1),this._disposeHandlers.add(()=>n.close()),this._disposeHandlers.add(this._abort.addHandler(e=>{this._dispose(),s(e)}))});return t.debug("got response from window"),this._dispose(),s||this.close(),{url:i}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,i=!1,s=window.location.origin){const r={source:_e,url:t,keepOpen:i},n=new x("_notifyParent");if(e)n.debug("With parent. Using parent.postMessage."),e.postMessage(r,s);else{n.debug("No parent. Using BroadcastChannel.");const e=new URL(t).searchParams.get("state");if(!e)throw new Error("No parent and no state in URL. Can't complete notification.");const i=new BroadcastChannel(`oidc-client-popup-${e}`);i.postMessage(r),i.close()}}},me={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},fe="_blank",ye=60,Se=2,ve=class extends X{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:i=e.post_logout_redirect_uri,popupWindowFeatures:s=me,popupWindowTarget:r=fe,redirectMethod:n="assign",redirectTarget:o="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:d,silent_redirect_uri:l=e.redirect_uri,silentRequestTimeoutInSeconds:g,automaticSilentRenew:u=!0,validateSubOnSilentRenew:h=!0,includeIdTokenInSilentRenew:p=!1,monitorSession:_=!1,monitorAnonymousSession:w=!1,checkSessionIntervalInSeconds:m=Se,query_status_response_type:f="code",stopCheckSessionOnError:y=!0,revokeTokenTypes:S=["access_token","refresh_token"],revokeTokensOnSignout:v=!1,includeIdTokenInSilentSignout:b=!1,accessTokenExpiringNotificationTimeInSeconds:E=ye,userStore:k}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=i,this.popupWindowFeatures=s,this.popupWindowTarget=r,this.redirectMethod=n,this.redirectTarget=o,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=l,this.silentRequestTimeoutInSeconds=g||d||10,this.automaticSilentRenew=u,this.validateSubOnSilentRenew=h,this.includeIdTokenInSilentRenew=p,this.monitorSession=_,this.monitorAnonymousSession=w,this.checkSessionIntervalInSeconds=m,this.stopCheckSessionOnError=y,this.query_status_response_type=f,this.revokeTokenTypes=S,this.revokeTokensOnSignout=v,this.includeIdTokenInSilentSignout=b,this.accessTokenExpiringNotificationTimeInSeconds=E,k)this.userStore=k;else{const e="undefined"!=typeof window?window.sessionStorage:new K;this.userStore=new V({store:e})}}},be=class e extends we{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new x("IFrameWindow"),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout(()=>{this._abort.raise(new W("IFrame timed out without a response"))},1e3*this._timeoutInSeconds);return this._disposeHandlers.add(()=>clearTimeout(t)),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",e=>{var t;const i=e.target;null==(t=i.parentNode)||t.removeChild(i),this._abort.raise(new Error("IFrame removed from DOM"))},!0),null==(e=this._frame.contentWindow)||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},Ee=class{constructor(e){this._settings=e,this._logger=new x("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new be({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),be.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},ke=class extends we{constructor({popupWindowTarget:e=fe,popupWindowFeatures:t={},popupSignal:i,popupAbortOnClose:s}){super(),this._logger=new x("PopupWindow");const r=M.center({...me,...t});this._window=window.open(void 0,e,M.serialize(r)),this.abortOnClose=Boolean(s),i&&i.addEventListener("abort",()=>{var e;this._abort.raise(new Error(null!=(e=i.reason)?e:"Popup aborted"))}),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout(()=>{this._window&&"boolean"==typeof this._window.closed&&!this._window.closed?this.close():this._abort.raise(new Error("Popup blocked by user"))},1e3*t.closePopupWindowAfterInSeconds)}async navigate(e){var t;null==(t=this._window)||t.focus();const i=setInterval(()=>{this._window&&!this._window.closed||(this._logger.debug("Popup closed by user or isolated by redirect"),s(),this._disposeHandlers.delete(s),this.abortOnClose&&this._abort.raise(new Error("Popup closed by user")))},500),s=()=>clearInterval(i);return this._disposeHandlers.add(s),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),t||window.opener||window.close()}},Ie=class{constructor(e){this._settings=e,this._logger=new x("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:i,popupAbortOnClose:s}){return new ke({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:i,popupAbortOnClose:s})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),ke.notifyOpener(e,t)}},Te=class{constructor(e){this._settings=e,this._logger=new x("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var i;this._logger.create("prepare");let s=window.self;"top"===t&&(s=null!=(i=window.top)?i:window.self);const r=s.location[e].bind(s.location);let n;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise((t,i)=>{n=i,window.addEventListener("pageshow",()=>t(window.location.href)),r(e.url)});return await t},close:()=>{this._logger.create("close"),null==n||n(new Error("Redirect aborted")),s.stop()}}}async callback(){}},Re=class extends z{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new x("UserManagerEvents"),this._userLoaded=new q("User loaded"),this._userUnloaded=new q("User unloaded"),this._silentRenewError=new q("Silent renew error"),this._userSignedIn=new q("User signed in"),this._userSignedOut=new q("User signed out"),this._userSessionChanged=new q("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},Ae=class{constructor(e){this._userManager=e,this._logger=new x("SilentRenewService"),this._isStarted=!1,this._retryTimer=new H("Retry Silent Renew"),this._tokenExpiring=async()=>{const e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof W)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),await this._userManager.events._raiseSilentRenewError(t)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},Pe=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},Ce=class{constructor(e,t,i,s){this._logger=new x("UserManager"),this.settings=new ve(e),this._client=new ue(e),this._redirectNavigator=null!=t?t:new Te(this.settings),this._popupNavigator=null!=i?i:new Ie(this.settings),this._iframeNavigator=null!=s?s:new Ee(this.settings),this._events=new Re(this.settings),this._silentRenewService=new Ae(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new he(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),i=await this._loadUser();return i?(t.info("user loaded"),await this._events.load(i,e),i):(t.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");const{redirectMethod:i,...s}=e;let r;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(r=await this.generateDPoPJkt(this.settings.dpop));const n=await this._redirectNavigator.prepare({redirectMethod:i});await this._signinStart({request_type:"si:r",dpopJkt:r,...s},n)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),i=await this._signinEnd(e);return i.profile&&i.profile.sub?t.info("success, signed in subject",i.profile.sub):t.info("no subject"),i}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:i=!1}){const s=this._logger.create("signinResourceOwnerCredential"),r=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:i,extraTokenParams:this.settings.extraTokenParams});s.debug("got signin response");const n=await this._buildUser(r);return n.profile&&n.profile.sub?s.info("success, signed in subject",n.profile.sub):s.info("no subject"),n}async signinPopup(e={}){var t;const i=this._logger.create("signinPopup");let s;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:r,popupWindowTarget:n,popupSignal:o,popupAbortOnClose:a,...c}=e,d=this.settings.popup_redirect_uri;d||i.throw(new Error("No popup_redirect_uri configured"));const l=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:n,popupSignal:o,popupAbortOnClose:a}),g=await this._signin({request_type:"si:p",redirect_uri:d,display:"popup",dpopJkt:s,...c},l);return g&&(g.profile&&g.profile.sub?i.info("success, signed in subject",g.profile.sub):i.info("no subject")),g}async signinPopupCallback(e=window.location.href,t=!1){const i=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),i.info("success")}async signinSilent(e={}){var t,i;const s=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:r,...n}=e;let o,a=await this._loadUser();if(!e.forceIframeAuth&&(null==a?void 0:a.refresh_token)){s.debug("using refresh token");const e=new Pe(a);return await this._useRefreshToken({state:e,redirect_uri:n.redirect_uri,resource:n.resource,extraTokenParams:n.extraTokenParams,timeoutInSeconds:r})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(o=await this.generateDPoPJkt(this.settings.dpop));const c=this.settings.silent_redirect_uri;let d;c||s.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(s.debug("subject prior to silent renew:",a.profile.sub),d=a.profile.sub);const l=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r});return a=await this._signin({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:o,...n},l,d),a&&((null==(i=a.profile)?void 0:i.sub)?s.info("success, signed in subject",a.profile.sub):s.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),i=new pe({...e.state,...t});return await this.storeUser(i),await this._events.load(i),i}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:i}=await this._client.readSignoutResponseState(e);if(i)switch(i.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:i,...s}=e,r=this.settings.silent_redirect_uri;r||t.throw(new Error("No silent_redirect_uri configured"));const n=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:i}),a=await this._signinStart({request_type:"si:s",redirect_uri:r,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==n?void 0:n.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...s},o);try{const e={},i=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),i.session_state&&i.profile.sub?(t.info("success for subject",i.profile.sub),{session_state:i.session_state,sub:i.profile.sub}):(t.info("success, user not authenticated"),null)}catch(e){if(this.settings.monitorAnonymousSession&&e instanceof j)switch(e.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:e.session_state}}throw e}}async _signin(e,t,i){const s=await this._signinStart(e,t);return await this._signinEnd(s.url,i)}async _signinStart(e,t){const i=this._logger.create("_signinStart");try{const s=await this._client.createSigninRequest(e);return i.debug("got signin request"),await t.navigate({url:s.url,state:s.state.id,response_mode:s.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw i.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signinEnd(e,t){const i=this._logger.create("_signinEnd"),s=await this._client.processSigninResponse(e,{});return i.debug("got signin response"),await this._buildUser(s,t)}async _buildUser(e,t){const i=this._logger.create("_buildUser"),s=new pe(e);if(t){if(t!==s.profile.sub)throw i.debug("current user does not match user returned from signin. sub from signin:",s.profile.sub),new j({...e,error:"login_required"});i.debug("current user matches user returned from signin")}return await this.storeUser(s),i.debug("user stored"),await this._events.load(s),s}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:i,...s}=e,r=await this._redirectNavigator.prepare({redirectMethod:i});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...s},r),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),i=await this._signoutEnd(e);return t.info("success"),i}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:i,popupWindowTarget:s,popupSignal:r,...n}=e,o=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:i,popupWindowTarget:s,popupSignal:r});await this._signout({request_type:"so:p",post_logout_redirect_uri:o,state:null==o?void 0:{},...n},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const i=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),i.info("success")}async _signout(e,t){const i=await this._signoutStart(e,t);return await this._signoutEnd(i.url)}async _signoutStart(e={},t){var i;const s=this._logger.create("_signoutStart");try{const r=await this._loadUser();s.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(r);const n=e.id_token_hint||r&&r.id_token;n&&(s.debug("setting id_token_hint in signout request"),e.id_token_hint=n),await this.removeUser(),s.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return s.debug("got signout request"),await t.navigate({url:o.url,state:null==(i=o.state)?void 0:i.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw s.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),i=await this._client.processSignoutResponse(e);return t.debug("got signout response"),i}async signoutSilent(e={}){var t;const i=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:s,...r}=e,n=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,o=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:n,...r},a),i.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const i=this._logger.create("_revokeInternal");if(!e)return;const s=t.filter(t=>"string"==typeof e[t]);if(s.length){for(const t of s)await this._client.revokeToken(e[t],t),i.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),i.debug("user stored"),await this._events.load(e)}else i.debug("no need to revoke due to no token(s)")}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),pe.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const i=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,i)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,i,s){var r,n;const o=await(null==(n=null==(r=this.settings.dpop)?void 0:r.store)?void 0:n.get(this.settings.client_id));if(o)return await D.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:i,keyPair:o.keys,nonce:s})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const i=await D.generateDPoPKeys();t=new ge(i),await e.store.set(this.settings.client_id,t)}return await D.generateDPoPJkt(t.keys)}};const Oe="OAUTH2_LOGIN_FLOW_COMPLETE_EVENT",xe="OAUTH_GET_TOP_URL",Ue="OAUTH_REDIRECT_TOP_WINDOW",Ne="OAUTH_UPDATE_URL",Le="OAUTH2_CHECK_PENDING",De={ORIGIN:"origin",TOP_ORIGIN:"oauth2_top_origin",TOP_WP_URL:"oauth2_top_wp_url",LOGIN_SUCCESS:"oauth2_login_success",STATE:"oauth2_state"},qe=60,Me=Math.max(qe-15,20),He=l("oidc-auth",{color:"green"}),$e=e=>He.extend(e);l("oidc-auth-utils");const Ge=()=>"undefined"==typeof window?"":new URLSearchParams(window.location.search).get("origin")||"";class je{static instance=null;settings=null;constructor(){}static getInstance(){return je.instance||(je.instance=new je),je.instance}configure(e){this.settings=e}isConfigured(){return null!==this.settings}getSettings(){if(!this.settings)throw new Error("OidcAuthConfig not configured. Call configure() or pass settings to OidcAuthClient.initialize().");return this.settings}getAuthOrigin(){const{authOrigin:e,authEndpoint:t}=this.getSettings();return e||new URL(t).origin}isAccessTokenProactiveRefreshEnabled(){return this.settings?.accessTokenProactiveRefreshEnabled??!0}getOidcSettings(){const e="undefined"==typeof window?"":window.location.origin,{clientId:t,authEndpoint:i}=this.getSettings(),s=this.getAuthOrigin(),r="undefined"!=typeof window?new V({store:window.localStorage}):void 0,{accessTokenExpiringNotificationTimeInSeconds:n=qe}=this.getSettings();return{client_id:t,authority:s,redirect_uri:`${e}/login/oauth-callback`,post_logout_redirect_uri:e,response_type:"code",scope:"openid offline_access",automaticSilentRenew:!1,accessTokenExpiringNotificationTimeInSeconds:n,stateStore:r,userStore:r,metadata:{issuer:s,authorization_endpoint:i,token_endpoint:`${s}/connect/api/v1/oauth2/token`,end_session_endpoint:`${s}/logout/`}}}getAccessTokenExpiringNotificationTimeInSeconds(){return this.getSettings().accessTokenExpiringNotificationTimeInSeconds??qe}getAccessTokenFreshnessThresholdInSeconds(){return this.getSettings().accessTokenFreshnessThresholdInSeconds??Me}getAllowedParentOrigins(){return this.settings?.allowedParentOrigins}}const We=je.getInstance(),ze=$e("oidc-auth:host-api"),Fe=async e=>new Promise((t,i)=>{const s=new MessageChannel;let r=!1;const n=()=>{r=!0,s.port1.close()},o=setTimeout(()=>{r||(n(),i(new Error(`Host message timeout: ${e.type}`)))},1e4);s.port1.onmessage=e=>{clearTimeout(o),n(),"success"!==e.data.status?i(e.data.payload):t(e.data.payload)};const a=new URLSearchParams(window.location.search).get("origin")||"";if(!function(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return!1;const t=We.getAllowedParentOrigins();return!t||0===t.length||t.includes(e)}(a))return clearTimeout(o),n(),void i(new Error("Origin not allowed"));ze.log("posting message to host",e),window.top.postMessage({type:e.type,payload:e.payload,...e.data||{}},a,[s.port2])}),Ke=$e("oidc-auth:OidcAuthTimer");class Je{timerHandle=null;expiration=null;initialized=!1;callback=()=>{};constructor(){this.timerHandle=null}init(e,t,i){const s=e-this.getEpochTime(),r=Math.max(s-t,10);this.cancel(),this.expiration=r,this.callback=i,Ke.debug("OIDC: timer - using expiration",r,s,t,e,s-t),this.timerHandle=setTimeout(this.callback,1e3*r),this.initialized=!0}cancel(){this.timerHandle&&(clearTimeout(this.timerHandle),this.timerHandle=null),this.expiration=null}getEpochTime(){return Math.floor(Date.now()/1e3)}isInitialized(){return this.initialized}}const Be=$e("oidc-auth:OidcAuthClient");class Qe{static instance=null;userManager=null;initialized=!1;accessTokenExpiringTimer=null;retryTimers=new Set;constructor(){}static getInstance(){return Qe.instance||(Qe.instance=new Qe),Qe.instance}isInitialized(){return this.initialized}ensureInitialized(){if(!this.userManager)throw new Error("OidcAuthClient not initialized. Call initialize() first.");return this.userManager}initialize(e){if(e&&(this.initialized=!1,We.configure(e)),this.initialized)Be.info("OIDC: initialize() - already initialized, skipping");else if("undefined"!=typeof window)if(We.isConfigured())try{Be.info("OIDC: initialize() - starting initialization");const e=We.getOidcSettings();this.userManager=new Ce(e),O.setLogger(Be),O.setLevel(O.ERROR),this.initAccessTokenExpiringTimer(),this.initialized=!0}catch(e){throw Be.error("OIDC: initialize() - FAILED:",e),e}else Be.warn("OIDC: initialize() - skipped, config not set");else Be.warn("OidcAuthClient cannot initialize on server side")}async initAccessTokenExpiringTimer(){We.isAccessTokenProactiveRefreshEnabled()?this.getUser().then(e=>{const t=e?.expires_at;t&&(this.accessTokenExpiringTimer||(this.accessTokenExpiringTimer=new Je),this.accessTokenExpiringTimer.init(t,We.getAccessTokenExpiringNotificationTimeInSeconds(),async()=>{Be.info("OIDC: timer proactive refresh access token expiring timer fired",t),this.proactiveRefreshWithRetry()}))}).catch(e=>{Be.error("OIDC: initAccessTokenExpiringTimer - FAILED:",e)}):Be.warn("OIDC: timer - not starting, access token proactive refresh is disabled")}async getUser(){if(!this.userManager)return null;try{return await this.userManager.getUser()}catch(e){return Be.error("OIDC: getUser - FAILED:",e),null}}async storeUser(e){const t=this.ensureInitialized();await t.storeUser(e)}async getAccessToken(){const e=await this.getUser();if(!e)return Be.info("OIDC: getAccessToken - no user found"),null;if(e.expired)try{const e=await this.signinSilent();return e?.access_token||null}catch(e){return Be.error("OIDC: getAccessToken - silent renew failed:",e),null}return this.isTokenFresh(e)||this.signinSilent().catch(e=>{Be.error("OIDC: getAccessToken - background refresh failed:",e)}),e.access_token}getUserData(){if("undefined"==typeof window)return null;try{const e=We.getOidcSettings(),t=`oidc.user:${e.authority}:${e.client_id}`,i=localStorage.getItem(t);if(!i)return null;const s=JSON.parse(i),r=s?.profile;return r?.sub?(Be.info("OIDC: USER:",{profile:r}),{id:r.sub,email:r.email||"",first_name:r.given_name,last_name:r.family_name}):null}catch(e){return Be.error("OIDC: getUserData - FAILED:",e),null}}async isAuthenticated(){const e=await this.getUser();return null!==e&&!e.expired}async signinRedirect(e){const t=this.ensureInitialized();await t.signinRedirect({state:e?{data:e}:void 0,prompt:"login"})}async signinCallback(){const e=this.ensureInitialized(),t=await e.signinCallback();if(!t)throw Be.error("OIDC: signinCallback - FAILED: no user returned"),new Error("Signin callback failed: no user returned");return t}async signinSilent(e){return this.ensureInitialized(),"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request("oidc-token-refresh",async()=>{const t=await this.getUser();return t&&this.isTokenFresh(t,e)?t:this.doSigninSilent()}):(Be.warn("OIDC: signinSilent - navigator.locks not available, proceeding without lock"),this.doSigninSilent())}isTokenFresh(e,t){if(!e.expires_at)return!1;const i=t??We.getAccessTokenFreshnessThresholdInSeconds(),s=Math.floor(Date.now()/1e3);return e.expires_at-s>i}async doSigninSilent(){const e=this.ensureInitialized();try{return await e.signinSilent()}catch(e){throw Be.error("OIDC: doSigninSilent - FAILED:",e),e}}proactiveRefreshWithRetry(e=1){if("undefined"!=typeof document&&"hidden"===document.visibilityState){Be.info("OIDC: tab is hidden, deferring proactive refresh until visible");const t=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",t),this.proactiveRefreshWithRetry(e))};return void document.addEventListener("visibilitychange",t)}this.signinSilent(We.getAccessTokenExpiringNotificationTimeInSeconds()).then(()=>{this.initAccessTokenExpiringTimer()}).catch(t=>{if(Be.error(`OIDC: proactive refresh failed (attempt ${e}/2):`,t),e<2){const t=setTimeout(()=>{this.retryTimers.delete(t),this.proactiveRefreshWithRetry(e+1)},3e3);this.retryTimers.add(t)}else Be.error("OIDC: proactive refresh exhausted all retries")})}async removeUser(){const e=this.ensureInitialized();this.accessTokenExpiringTimer?.cancel(),this.retryTimers.forEach(clearTimeout),this.retryTimers.clear(),await e.removeUser()}onUserLoaded(e){this.ensureInitialized().events.addUserLoaded(e)}offUserLoaded(e){this.ensureInitialized().events.removeUserLoaded(e)}onUserUnloaded(e){this.ensureInitialized().events.addUserUnloaded(e)}offUserUnloaded(e){this.ensureInitialized().events.removeUserUnloaded(e)}onSilentRenewError(e){this.ensureInitialized().events.addSilentRenewError(e)}offSilentRenewError(e){this.ensureInitialized().events.removeSilentRenewError(e)}onAccessTokenExpiring(e){this.ensureInitialized().events.addAccessTokenExpiring(e)}offAccessTokenExpiring(e){this.ensureInitialized().events.removeAccessTokenExpiring(e)}onAccessTokenExpired(e){this.ensureInitialized().events.addAccessTokenExpired(e)}offAccessTokenExpired(e){this.ensureInitialized().events.removeAccessTokenExpired(e)}getLogoutUrl(e,t){const i=new URL(function(e){return`${We.getAuthOrigin()}${e.logoutPath}`}(e));return t&&i.searchParams.set("redirect_to",t),i.toString()}getWindowOriginParam(){const e=new URL(window.location.href).searchParams.get(De.ORIGIN);if(!e)throw new Error("iframe origin param is required");return e}async getTopUrl(){return(await Fe({type:xe})).topUrl}async isOAuthFlowPending(){try{return(await Fe({type:Le})).isPending}catch(e){return Be.warn("OIDC: isOAuthFlowPending() - failed to check, assuming not pending:",e),!1}}async triggerLoginFlowViaParent({loginPath:e,windowPath:t}){Be.info("OIDC: triggerLoginFlowViaParent() - starting");const i=await this.getTopUrl(),s=new URL(i).origin,r=`${s}${t}`,n=new URL(`${window.location.origin}${e}`);n.searchParams.set(De.TOP_ORIGIN,s),n.searchParams.set(De.TOP_WP_URL,r),Be.info("OIDC: triggerLoginFlowViaParent() - redirecting parent to:",n.toString()),await Fe({type:Ue,payload:{url:n.toString()}})}async handleLoginFlowComplete(e,t){if(!t)throw new Error("oauthUserState is required");const i=this.getWindowOriginParam(),s=t.state,r=s?.data?.[De.TOP_ORIGIN];if(i!==r)throw Be.error("OIDC: handleLoginFlowComplete - origin mismatch:",i,"!==",r),new Error("Invalid origin in OAuth state");try{const e=new pe(t);await this.storeUser(e),this.initAccessTokenExpiringTimer(),window.dispatchEvent(new CustomEvent("oidc-auth-completed"))}catch(t){Be.error("OIDC: handleLoginFlowComplete - FAILED to store user:",t),await this.triggerLoginFlowViaParent(e)}}async triggerLogoutViaParent(e,t=!0){const i=await this.getTopUrl(),s=new URL(i).origin,r=t?`${s}${e.windowPath}`:s;await this.removeUser();const n=this.getLogoutUrl(e,r);await Fe({type:Ue,payload:{url:n}})}async cleanOAuthParamsFromUrl(){try{const e=await this.getTopUrl(),t=new URL(e);t.searchParams.delete("oauth_code"),t.searchParams.delete("oauth_state"),t.searchParams.delete("start-oauth"),t.searchParams.delete(De.LOGIN_SUCCESS),t.searchParams.delete(De.STATE),await Fe({type:Ne,payload:{url:t.toString()}})}catch(e){Be.warn("Failed to clean OAuth params from URL:",e)}}setupLoginFlowMessageListener(e){let t=!1;const i=i=>{if(i.data?.type!==Oe)return;if(i.origin!==Ge())return void Be.error("OIDC: origin mismatch - expected:",Ge(),"received:",i.origin);if(t)return void Be.debug("OIDC: LOGIN_FLOW_COMPLETE already processed, ignoring duplicate");const s=i.data.payload;s?.oauthState?(t=!0,this.handleLoginFlowComplete(e,s.oauthState).catch(e=>{Be.error("OIDC: Failed to handle login flow complete:",e),t=!1})):Be.warn("OIDC: LOGIN_FLOW_COMPLETE but no oauthState in payload")};return window.addEventListener("message",i),()=>{window.removeEventListener("message",i)}}async getTokenExpirationInfo(){const e=await this.getUser();if(!e||!e.expires_at)return{expiresAt:null,expiresInSeconds:null,isExpired:!0};const t=new Date(1e3*e.expires_at),i=Date.now(),s=Math.floor((1e3*e.expires_at-i)/1e3);return{expiresAt:t,expiresInSeconds:s,isExpired:s<=0}}async forceTokenRefresh(){return Be.info("OIDC: forceTokenRefresh() - manually triggering token refresh"),this.signinSilent()}}const Ve=Qe.getInstance();"undefined"!=typeof window&&(window.oidcAuthClient=Ve);const Xe=$e("oidc-auth:oidc-auth-redirect");function Ye(e,t){e.postMessage({status:"success",payload:t})}function Ze(e,t){e.postMessage({status:"error",payload:t})}function et({targets:e,onSuccess:t,attempt:i=1}){const s=new URLSearchParams(window.location.search);if(!s.get(De.LOGIN_SUCCESS))return void Xe.warn("OIDC: No login_success param found, skipping");const r=s.get(De.STATE);if(r){if(!e.window?.contentWindow||!e.windowURL)return Xe.warn("Cannot forward OIDC state: iframe not available"),void(i<5?setTimeout(()=>{et({targets:e,onSuccess:t,attempt:i+1})},500):Xe.error("OIDC: Failed to forward login flow after",5,"attempts - iframe never became available"));try{const i=JSON.parse(r),s=i.state?.data?.[De.TOP_ORIGIN];if(s&&s!==window.location.origin)return void Xe.error("Origin mismatch in OIDC state:",s,"vs",window.location.origin);!function(e,t){const i=t.window?.contentWindow,s=t.windowURL?.origin;i&&s?i.postMessage({type:Oe,payload:e},s):Xe.warn("Cannot send OIDC state: window or origin not available")}({oauthState:i},e);const n=new URL(window.location.href);n.searchParams.delete(De.LOGIN_SUCCESS),n.searchParams.delete(De.STATE),history.replaceState({},"",n.toString()),t?.()}catch(e){Xe.error("Failed to parse or forward OIDC state:",e)}}else Xe.warn("OIDC login complete but no state found in URL")}const tt="angie_return_url",it=u("referrer-redirect");function st(e){try{return new URL(e,window.location.origin).origin===window.location.origin}catch{return!1}}function rt(e,t){if(!st(e))return it.warn("Invalid redirect URL rejected:",e),!1;try{const i={url:e};return t&&(i.prompt=t),localStorage.setItem(tt,JSON.stringify(i)),!0}catch(e){return it.warn("localStorage not available"),!1}}function nt(){try{const e=localStorage.getItem(tt);if(!e)return null;let t;try{t=JSON.parse(e)}catch{return it.warn("Stored redirect data is not valid JSON, returning null"),null}return t.url&&"string"==typeof t.url?st(t.url)?t:(it.warn("Stored redirect URL is invalid, returning null:",t.url),null):(it.warn("Stored redirect data missing url field, returning null"),null)}catch(e){return it.warn("localStorage not available"),null}}function ot(){try{localStorage.removeItem(tt)}catch(e){it.warn("localStorage not available")}}const at=u("oauth");function ct(){const e=nt();if(e)return ot(),void(window.location.href=(t=e.url,i=e.prompt,i?`${t}#angie-prompt=${encodeURIComponent(i)}`:t));var t,i;try{localStorage.setItem("angie_sidebar_state","open")}catch(e){at.warn("localStorage not available")}setTimeout(()=>{window.toggleAngieSidebar(!0)},500)}const dt=(e,t)=>{const i=document.getElementById("angie-sidebar-container");i&&i.setAttribute("aria-hidden",t?"false":"true"),t?e.removeAttribute("tabindex"):e.setAttribute("tabindex","-1")},lt=(e,t)=>{e.postMessage({status:"success",payload:t})},gt=()=>new Promise(e=>{"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e(null)}),ut=u("sdk");var ht;!function(e){e.POST_MESSAGE="postMessage"}(ht||(ht={}));const pt=u("iframe-utils");let _t=null;const wt=()=>(_t&&document.contains(_t)||(_t=document.querySelector('iframe[src*="angie/"]')),_t),mt=(e,t)=>{pt.log("postMessageToAngieIframe",e,t);const i=wt();if(!i?.contentWindow)return!1;const s=t||(()=>{const e=wt();if(!e)return null;try{return new URL(e.src).origin}catch(e){return pt.error("Error parsing iframe URL:",e),null}})();return s?(i.contentWindow.postMessage(e,s),!0):(pt.error("Could not determine target origin for Angie iframe"),!1)},ft="/* Angie Sidebar - CSS Variables */\n:root {\n --angie-sidebar-z-index: 1200; /* below MUI popups, elementor popups and media library modal */\n --angie-sidebar-width: 330px;\n --angie-sidebar-transition: margin 0.3s ease-in-out, transform 0.3s ease-in-out;\n /* Direction-aware transform values for sidebar positioning */\n --angie-sidebar-hide-transform: translateX(-100%); /* LTR: hide to the left */\n --angie-sidebar-show-transform: translateX(0);\n}\n\n/* RTL-specific transform values */\n[dir=\"rtl\"] {\n --angie-sidebar-hide-transform: translateX(100%); /* RTL: hide to the right */\n}\n\n/* Respect user's motion preferences */\n@media (prefers-reduced-motion: reduce) {\n :root {\n --angie-sidebar-transition: none;\n }\n}\n\n/* Apply transitions only when user is actively toggling */\nbody.angie-sidebar-transitioning {\n transition: var(--angie-sidebar-transition) !important;\n}\n\nbody.angie-sidebar-transitioning #angie-sidebar-container {\n transition: var(--angie-sidebar-transition) !important;\n}\n\n/* Layout (default) - Push content */\n@media (min-width: 768px) {\n body.angie-sidebar-active {\n padding-inline-start: var(--angie-sidebar-width) !important;\n }\n\n #angie-sidebar-container {\n position: fixed;\n top: 0;\n inset-inline-start: 0;\n width: var(--angie-sidebar-width);\n height: 100vh;\n z-index: var(--angie-sidebar-z-index) !important; /* below elementor popups and media library modal */\n background: #FCFCFC;\n transform: var(--angie-sidebar-hide-transform);\n outline: none;\n overflow: hidden;\n /* No default transition - only when transitioning */\n }\n\n /* Resize handle */\n #angie-sidebar-container::after {\n content: '';\n position: absolute;\n top: 0;\n inset-inline-end: 0;\n width: 4px;\n height: 100%;\n cursor: ew-resize;\n background: transparent;\n z-index: 1000001;\n }\n\n /* Pink border during resize */\n #angie-sidebar-container.angie-resizing {\n border-inline-end-color: #ff69b4 !important;\n border-inline-end-width: 2px !important;\n }\n\n /* Disable iframe pointer events during resize */\n #angie-sidebar-container.angie-resizing iframe#angie-iframe {\n pointer-events: none !important;\n }\n}\n\n/* Active states */\nbody.angie-sidebar-active #angie-sidebar-container {\n transform: var(--angie-sidebar-show-transform);\n}\n\n/* Studio mode - sidebar takes full width */\n@media (min-width: 768px) {\n html.angie-studio-active body.angie-sidebar-active #angie-sidebar-container {\n width: 100%;\n }\n}\n\n/* High contrast mode support */\n@media (prefers-contrast: high) {\n #angie-sidebar-container {\n border-color: #000;\n box-shadow: none;\n }\n}\n\n/* Screen reader only class */\n.angie-sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n/* Plugin conflict resolution */\nbody.angie-sidebar-active {\n /* Reset common conflicting styles */\n box-sizing: border-box !important;\n position: relative !important;\n}\n\n#angie-sidebar-toggle {\n z-index: 99999 !important;\n}\n",yt=u("sidebar");let St=!1;const vt="open",bt="closed",Et=350,kt=590,It=370;function Tt(){if("undefined"==typeof window)return It;try{const e=window.localStorage.getItem("angie_sidebar_width");if(e){const t=parseInt(e,10);if(t>=Et&&t<=kt)return t}}catch(e){yt.warn("localStorage not available")}return It}function Rt(){return"undefined"==typeof window?null:localStorage.getItem("angie_sidebar_state")}function At(e){try{localStorage.setItem("angie_sidebar_state",e)}catch(e){yt.warn("localStorage not available")}}function Pt(e){try{localStorage.setItem("angie_sidebar_width",e.toString())}catch(e){yt.warn("localStorage not available")}}function Ct(e){document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`)}function Ot(){!function(){if("undefined"==typeof window)return!1;const e=new URLSearchParams(window.location.search);return e.has(De.LOGIN_SUCCESS)||e.has(De.STATE)||e.has(De.TOP_ORIGIN)}()?xt(Rt()||vt):function(){xt(bt);try{localStorage.setItem("angie_sidebar_state",bt)}catch(e){yt.warn("localStorage not available")}}()}function xt(e){"undefined"!=typeof window&&window.toggleAngieSidebar&&window.toggleAngieSidebar(e===vt,!0)}function Ut(){const e=document.getElementById("angie-sidebar-container");if(!e)return;let t=!1,i=0,s=0;e.addEventListener("mousedown",r=>{const n=e.getBoundingClientRect();("rtl"===document.documentElement.dir?r.clientX<=n.left+4:r.clientX>=n.right-4)&&(t=!0,i=r.clientX,s=n.width,e.classList.add("angie-resizing"),document.body.style.cursor="ew-resize",document.body.style.userSelect="none",r.preventDefault(),r.stopPropagation())}),document.addEventListener("mousemove",e=>{if(!t)return;let r;r="rtl"===document.documentElement.dir?i-e.clientX:e.clientX-i,Ct(Math.max(Et,Math.min(kt,s+r))),e.preventDefault(),e.stopPropagation()}),document.addEventListener("mouseup",i=>{if(t){t=!1,e.classList.remove("angie-resizing"),document.body.style.cursor="",document.body.style.userSelect="";const r=parseInt(getComputedStyle(document.documentElement).getPropertyValue("--angie-sidebar-width"),10);Pt(r),mt({type:m.ANGIE_SIDEBAR_RESIZED,payload:{initialWidth:s,width:r}}),i.preventDefault(),i.stopPropagation()}}),Ct(Tt())}function Nt(e){!function(){if("undefined"==typeof document||St)return;const e="angie-sidebar-styles";if(document.getElementById(e))return void(St=!0);const t=document.createElement("style");t.id=e,t.textContent=ft;const i=document.head||document.getElementsByTagName("head")[0];i.insertBefore(t,i.firstChild),St=!0}(),"undefined"!=typeof window&&(window.toggleAngieSidebar=function(e){return function(t,i){const s=document.body,r=document.getElementById("angie-sidebar-container");if(!r)return void yt.warn("Required elements not found!");const n=s.classList.contains("angie-sidebar-active"),o=void 0!==t?t:!n;i||(s.classList.add("angie-sidebar-transitioning"),setTimeout(function(){s.classList.remove("angie-sidebar-transitioning")},300)),o?s.classList.add("angie-sidebar-active"):s.classList.remove("angie-sidebar-active"),o&&setTimeout(function(){mt({type:"focusInput"})},i?0:300),e&&e(o,r,i),At(o?vt:bt);const a=new CustomEvent("angieSidebarToggle",{detail:{isOpen:o,sidebar:r,skipTransition:i}});document.dispatchEvent(a),mt({type:m.ANGIE_SIDEBAR_TOGGLED,payload:{state:o?"opened":"closed"}})}}(e),window.addEventListener("message",function(e){if(e.data&&"toggleAngieSidebar"===e.data.type){const{force:t,skipTransition:i}=e.data.payload||{};window.toggleAngieSidebar&&window.toggleAngieSidebar(t,i)}}))}const Lt=u("iframe"),Dt=async()=>{if(I.iframe?.contentWindow&&I.iframeUrlObject)try{Lt.log("Disabling navigation prevention in Angie iframe"),I.iframe.contentWindow.postMessage({type:m.ANGIE_DISABLE_NAVIGATION_PREVENTION},I.iframeUrlObject.origin),await new Promise(e=>setTimeout(e,100))}catch(e){throw Lt.error("Failed to disable navigation prevention:",e),e}else Lt.warn("Cannot disable navigation prevention: iframe or origin not available")},qt=async e=>{if(window.screen.availWidth<=768)return void Lt.log("Mobile detected, skipping iframe injection");let t=document.getElementById("angie-sidebar-container");if(!t){const e=performance.now();if(Lt.log("⏱️ Waiting for sidebar container..."),await new Promise(e=>{let i=0;const s=setInterval(()=>{t=document.getElementById("angie-sidebar-container"),i++,(t||i>20)&&(clearInterval(s),t&&e())},100);setTimeout(()=>{if(clearInterval(s),t)return void e();const i=new MutationObserver(()=>{t=document.getElementById("angie-sidebar-container"),t&&(i.disconnect(),e())});i.observe(document.body,{childList:!0,subtree:!0}),setTimeout(()=>{i.disconnect(),e()},8e3)},2e3)}),Lt.log(`⏱️ Sidebar container detection took: ${(performance.now()-e).toFixed(2)}ms`),!t)return void Lt.error("Sidebar container not found")}const{iframe:i,iframeUrlObject:s}=await(async e=>{const t=e.origin,i=new URL(e.path,t),s=i.pathname.slice(1).replace(/\//,"--")+"-"+Math.random().toString(36).substring(7);return new Promise(r=>{const n=new URL(t);n.pathname=i.pathname;const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";if(n.searchParams.append("colorScheme",e.uiTheme||o||"light"),n.searchParams.append("sdkVersion",e.sdkVersion),n.searchParams.append("instanceId",s),n.searchParams.append("origin",window.location.origin),e.isRTL&&n.searchParams.append("isRTL",e.isRTL?"true":"false"),"localhost"===window.location.hostname&&window.location.search.includes("debug_error")){const e=new URLSearchParams(window.location.search).get("debug_error");e&&n.searchParams.append("debug_error",e)}i.searchParams.forEach((e,t)=>{n.searchParams.set(t,e)}),n.searchParams.set("ver",(new Date).getTime().toString());const a=e.parent||document,c=a.createElement("iframe"),d={"background-color":"transparent","color-scheme":"normal",...e.css};window.addEventListener("message",async e=>{if(e.origin===n.origin)switch(e.data.type){case y.ANGIE_READY:r({iframe:c,iframeUrlObject:n});break;case y.ANGIE_LOADED:c.contentWindow?.postMessage({type:y.HOST_READY,instanceId:s},n.origin)}}),c.setAttribute("src",n.href),c.id="angie-iframe",c.setAttribute("frameborder","0"),c.setAttribute("scrolling","no"),c.setAttribute("style",Object.entries(d).map(([e,t])=>`${e}: ${t}`).join("; ")),c.setAttribute("allow","clipboard-write; clipboard-read"),e.insertCallback?e.insertCallback(c):a.body.appendChild(c)})})({origin:e.origin||"https://angie.elementor.com",path:"angie/wp-admin",insertCallback:e=>{Lt.log("Injecting Angie iframe into sidebar container"),e.setAttribute("title","Angie AI Assistant"),e.setAttribute("role","application"),e.setAttribute("aria-label","Angie AI Assistant Interface");const i=document.getElementById("angie-sidebar-loading");i&&(i.textContent=""),t?.appendChild(e),dt(e,!0),e.addEventListener("load",()=>{e.focus()})},css:{width:"100%",height:"100%",border:"none",outline:"none"},uiTheme:e.uiTheme,isRTL:e.isRTL,sdkVersion:"1.3.0"});I.iframe=i,I.iframeUrlObject=s,window.addEventListener("message",e=>{if(e.origin===I.iframeUrlObject?.origin)switch(e.data.type){case f.SET:window.localStorage.setItem(e.data.key,e.data.value);break;case f.GET:{const t=e.ports[0],i=window.localStorage.getItem(e.data.key);t.postMessage({value:i});break}}}),(e=>{window.addEventListener("message",async t=>{const i=t.origin===window.location.origin,s=t.origin===e.iframeUrlObject?.origin;if(i||s)switch(t?.data?.type){case m.SDK_ANGIE_ALL_SERVERS_REGISTERED:break;case m.SDK_ANGIE_READY_PING:{const e=t.ports[0];ut.log("Angie is ready",t),lt(e,{message:"Angie is ready"});break}case m.SDK_REQUEST_CLIENT_CREATION:{const i=t.data.payload;try{const s=t.ports[0],r=new MessageChannel;r.port1.onmessage=e=>{s.postMessage({success:!0,data:e.data})};const n={type:m.SDK_REQUEST_CLIENT_CREATION,payload:{success:!0,...i,clientId:`dynamic-client-${i.serverName}-${i.serverVersion}-${Date.now()}`,requestId:t.data.payload.requestId},timestamp:Date.now()};if(!e.iframe)throw new Error("Iframe not found");e.iframe.contentWindow?.postMessage(n,e.iframeUrlObject?.origin||"",[r.port2])}catch(e){ut.error(`Failed to create client for SDK server "${i.serverName}":`,e)}break}case m.SDK_TRIGGER_ANGIE:ut.log("SDK Trigger Angie received",t.data);try{const{requestId:i,prompt:s,context:r}=t.data.payload;if(!e.iframe)throw new Error("Iframe not found");e.iframe.contentWindow?.postMessage({type:m.SDK_TRIGGER_ANGIE,payload:{requestId:i,prompt:s,context:r}},e.iframeUrlObject?.origin||""),window.postMessage({type:m.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!0,requestId:i,response:"Angie triggered successfully"}},window.location.origin)}catch(e){ut.error("Failed to trigger Angie:",e),window.postMessage({type:m.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!1,requestId:t.data.payload?.requestId,error:e instanceof Error?e.message:"Unknown error"}},window.location.origin)}}})})(I),function({trustedOrigin:e,onOAuthParamsCleared:t}){window.addEventListener("message",i=>{if(i.origin!==e)return;const s=i.ports?.[0];switch(i.data.type){case xe:if(!s)return;Ye(s,{topUrl:window.location.href});break;case Ue:window.location.href=i.data.payload.url;break;case Ne:{if(!s)return;const e=i.data.payload.url;if(!history?.replaceState)return void Ze(s,{message:"URL update not supported in this browser"});try{const i=window.location.href;history.replaceState({},"",e),function(e,t){const i=new URL(e).searchParams,s=new URL(t).searchParams,r=[De.LOGIN_SUCCESS,De.STATE,De.TOP_ORIGIN];return r.some(e=>i.has(e))&&!r.some(e=>s.has(e))}(i,e)&&t?.(),Ye(s,{message:"URL updated successfully"})}catch(e){Ze(s,{message:"URL update failed: "+(e instanceof Error?e.message:"Unknown error")})}break}case Le:if(!s)return;Ye(s,{isPending:"true"===new URLSearchParams(window.location.search).get(De.LOGIN_SUCCESS)})}})}({trustedOrigin:I.iframeUrlObject?.origin??"",onOAuthParamsCleared:ct}),(()=>{const e={window:I.iframe,windowURL:I.iframeUrlObject};window.addEventListener("load",()=>{at.log("OIDC: Window load event fired, forwarding OIDC state if present"),et({targets:e,onSuccess:ct})}),et({targets:e,onSuccess:ct})})(),window.addEventListener("message",async t=>{if([window.location.origin,e.origin||"https://angie.elementor.com"].includes(t.origin))if(t?.data?.type===m.ANGIE_CHAT_TOGGLE)I.open=t.data.open,I.iframe&&dt(I.iframe,I.open);else if(t?.data?.type===m.ANGIE_STUDIO_TOGGLE){const e=t.data.isStudioOpen;if(!I.iframe)return;if(e)document.documentElement.classList.add("angie-studio-active");else{const e=Tt();document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`),document.documentElement.classList.remove("angie-studio-active")}}else if(t?.data?.type===m.ANGIE_NAVIGATE_TO_URL){const{url:e="",confirmed:i=!1}=t.data.payload||{};if(!i)return void Lt.log("Navigation requires user confirmation");if(!((e,t=[])=>{const i=0===t.length&&"undefined"!=typeof window?[window.location.origin]:t;if(!e.startsWith("http"))return!1;try{const t=new URL(e);return i.includes(t.origin)}catch{return!1}})(e))return void Lt.error("Navigation blocked: Invalid or unsafe URL",{url:e});await Dt(),window.location.assign(e)}else if(t?.data?.type===m.ANGIE_PAGE_RELOAD){const{confirmed:e=!1}=t.data.payload||{};if(!e)return void Lt.log("Page reload requires user confirmation");Lt.log("Page reload confirmed - disabling navigation prevention and reloading"),await Dt(),setTimeout(()=>{window.location.reload()},50)}else t?.data?.type===y.RESET_HASH&&(window.location.hash="",lt(t.ports[0],{message:"Hash reset successfully"}))})},Mt=u("registration-queue");class Ht{queue=[];isProcessing=!1;add(e){const t={id:this.generateId(e),config:e,timestamp:Date.now(),status:"pending"};return this.queue.push(t),Mt.log(`Added server "${e.name}" to queue`),t}getAll(){return[...this.queue]}getPending(){return this.queue.filter(e=>"pending"===e.status)}updateStatus(e,t,i){const s=this.queue.find(t=>t.id===e);s&&(s.status=t,i?s.error=i:"pending"!==t&&"registered"!==t||delete s.error,Mt.log(`Updated server ${e} status to ${t}`))}async processQueue(e){if(this.isProcessing)return void Mt.log("Already processing queue");this.isProcessing=!0;const t=this.getPending();Mt.log(`Processing ${t.length} pending registrations`);try{for(const i of t)try{await e(i),this.updateStatus(i.id,"registered")}catch(e){const t=e instanceof Error?e.message:String(e);this.updateStatus(i.id,"failed",t),Mt.error(`Failed to process registration ${i.id}:`,t)}}finally{this.isProcessing=!1}}clear(){this.queue=[],Mt.log("Cleared all registrations")}resetAllToPending(){if(this.isProcessing)return Mt.log("Cannot reset to pending - processing in progress"),!1;const e=this.queue.filter(e=>"registered"===e.status).length,t=this.queue.filter(e=>"failed"===e.status).length;return this.queue.forEach(e=>{"pending"!==e.status&&(e.status="pending",delete e.error)}),Mt.log(`Reset ${e+t} registrations to pending`),!0}remove(e){const t=this.queue.findIndex(t=>t.id===e);return-1!==t&&(this.queue.splice(t,1),Mt.log(`Removed registration ${e}`),!0)}generateId(e){return`reg_${e.name}_${e.version}_${Date.now()}`}}class $t{angieDetector;clientManager;logger;registrationQueue;isInitialized=!1;instanceId;constructor(){this.instanceId=Math.random().toString(36).substring(2,8),this.logger=u({instanceId:this.instanceId}),this.logger.log("Constructor called - initializing SDK"),this.angieDetector=new v,this.registrationQueue=new Ht,this.clientManager=new k,this.logger.log("Setting up event handlers"),this.setupAngieReadyHandler(),this.setupServerInitHandler(),this.setupReRegistrationHandler(),this.logger.log("SDK initialization complete")}async loadSidebar(e){Nt(),await qt({origin:e?.origin||"https://angie.elementor.com",uiTheme:e?.uiTheme||"light",isRTL:e?.isRTL||!1,...e}),this.setupPromptHashDetection()}setupReRegistrationHandler(){window.addEventListener("message",e=>{if(e.data?.type===m.SDK_ANGIE_REFRESH_PING)if(this.logger.log("Angie refresh ping received"),this.registrationQueue.resetAllToPending()){const e=this.registrationQueue.getPending().length;this.logger.log(`Successfully reset ${e} registrations, processing queue`),this.handleAngieReady()}else this.logger.log("Skipping queue reset - processing already in progress")})}setupAngieReadyHandler(){this.angieDetector.waitForReady().then(e=>{e.isReady?this.handleAngieReady():this.logger.warn("Angie not detected - servers will remain queued")}).catch(e=>{this.logger.error("Error waiting for Angie:",e)})}async handleAngieReady(){this.logger.log("Angie is ready, processing queued registrations");try{await this.registrationQueue.processQueue(async e=>{this.logger.log(`processQueue callback called for "${e.config.name}"`),await this.processRegistration(e)}),this.isInitialized=!0,this.logger.log("Initialization complete")}catch(e){this.logger.error("Error processing registration queue:",e)}}async processRegistration(e){this.logger.log(`Processing registration for server "${e.config.name}" (ID: ${e.id})`);try{this.logger.log(`Calling clientManager.requestClientCreation for "${e.config.name}"`);const t={...e,instanceId:this.instanceId};await this.clientManager.requestClientCreation(t),this.logger.log(`Successfully registered server "${e.config.name}"`)}catch(t){throw this.logger.error(`Failed to register server "${e.config.name}":`,t),t}}registerLocalServer(e){return e.type=w.LOCAL,e.transport=p.POST_MESSAGE,this.registerServer(e)}registerRemoteServer(e){return e.type=w.REMOTE,this.registerServer(e)}isLocalServerConfig(e){return e.type===w.LOCAL||!e.type&&"server"in e}isRemoteServerConfig(e){return e.type===w.REMOTE&&"url"in e}async registerServer(e){if(!e.type)return this.logger.warn("For a local server, please use registerLocalServer instead of registerServer"),void this.registerLocalServer(e);if(this.logger.log(`registerServer called for "${e.name}"`),!e.name)throw new Error("Server name is required");if(!e.description)throw new Error("Server description is required");if(this.isLocalServerConfig(e)&&!e.server)throw new Error("Server instance is required for local servers");this.logger.log(`Registering server "${e.name}"`);const t=this.registrationQueue.add(e);if(this.logger.log(`Added registration to queue: ${t.id}`),this.angieDetector.isReady())try{await this.processRegistration(t),this.registrationQueue.updateStatus(t.id,"registered"),this.logger.log(`Server "${e.name}" registered successfully`)}catch(e){const i=e instanceof Error?e.message:String(e);throw this.registrationQueue.updateStatus(t.id,"failed",i),e}else this.logger.log(`Server "${e.name}" queued until Angie is ready`)}getRegistrations(){return this.registrationQueue.getAll()}getPendingRegistrations(){return this.registrationQueue.getPending()}isAngieReady(){return this.angieDetector.isReady()}isReady(){return this.isInitialized}async waitForReady(){if(!(await this.angieDetector.waitForReady()).isReady)throw new Error("Angie is not available");for(;!this.isInitialized;)await new Promise(e=>setTimeout(e,100))}async triggerAngie(e){if(!this.isAngieReady())throw new Error("Angie is not ready. Please wait for Angie to be available before triggering.");const t=this.generateRequestId(),i=e.options?.timeout||3e4;return new Promise((s,r)=>{const n=setTimeout(()=>{r(new Error("Angie trigger request timed out"))},i),o=e=>{e.data?.type===m.SDK_TRIGGER_ANGIE_RESPONSE&&e.data?.payload?.requestId===t&&(clearTimeout(n),window.removeEventListener("message",o),s(e.data.payload))};window.addEventListener("message",o);const a={type:m.SDK_TRIGGER_ANGIE,payload:{requestId:t,prompt:e.prompt,options:e.options,context:{pageUrl:window.location.href,pageTitle:document.title,...e.context}},timestamp:Date.now()};this.logger.log(`Triggering Angie with prompt (Request ID: ${t})`),window.postMessage(a,window.location.origin)})}destroy(){this.registrationQueue.clear(),this.logger.log("SDK destroyed")}setupServerInitHandler(){window.addEventListener("message",e=>{e.data?.type===m.SDK_REQUEST_INIT_SERVER&&(this.logger.log("Server init request received"),this.handleServerInitRequest(e))})}handleServerInitRequest(e){const{clientId:t,serverId:i,instanceId:s}=e.data.payload||{};if(t&&i)if(this.logger.log(`Server init request received - Request instanceId: ${s}, This instanceId: ${this.instanceId}`),s&&s!==this.instanceId)this.logger.log(`Ignoring server init request for different instance. Request instanceId: ${s}, this instanceId: ${this.instanceId}`);else{this.logger.log(`Handling server init request for clientId: ${t}, serverId: ${i}`);try{const t=this.registrationQueue.getAll().find(e=>e.id===i);if(!t)return void this.logger.error(`No registration found for serverId: ${i}`);if("type"in t.config&&"remote"===t.config.type)return void this.logger.log("Remote server registration detected; skipping local connect");const s=e.ports[0];if(!s)return void this.logger.error("No port provided in server init request");const r=t.config.server;this.migrateInstructionsCompat(r);const n=new E(s);r.connect(n),this.logger.log(`Server "${t.config.name}" initialized successfully`)}catch(e){this.logger.error(`Error initializing server for clientId ${t}:`,e)}}else this.logger.error("Invalid server init request - missing clientId or serverId")}migrateInstructionsCompat(e){try{const t="server"in e&&e.server?e.server:e,i=t._serverInfo,s=t._instructions;i?.instructions&&!s&&(t._instructions=i.instructions,this.logger.log("Migrated instructions from serverInfo to serverOptions (backward compat)"))}catch{}}generateRequestId(){return`${this.instanceId}-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}async handlePromptHash(){const e=window.location.hash;if(e.startsWith("#angie-prompt="))try{const t=e.replace("#angie-prompt=",""),i=decodeURIComponent(t);if(!i)return void this.logger.warn("Empty prompt detected in hash");this.logger.log("Detected prompt in hash:",i),await this.waitForReady();const s=await this.triggerAngie({prompt:i,context:{source:"hash-parameter",pageUrl:window.location.href,timestamp:(new Date).toISOString()}});this.logger.log("Triggered successfully from hash:",s),window.location.hash=""}catch(e){this.logger.error("Failed to trigger from hash:",e)}}setupPromptHashDetection(){this.handlePromptHash(),window.addEventListener("hashchange",()=>this.handlePromptHash())}}const Gt=u("navigation"),jt=(e,t)=>{if(wt()){t.isOpen&&window.toggleAngieSidebar&&window.toggleAngieSidebar(!0);const i=mt({type:"angie-route-navigation",path:e,payload:t});return i||Gt.error("Failed to post navigation message to Angie iframe"),i}return Gt.error("Angie iframe not found"),!1};module.exports=t})();
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{JSONRPCMessageSchema as e}from"@modelcontextprotocol/sdk/types.js";const t={none:0,error:1,warn:2,info:3,debug:4},i={error:"error",warn:"warn",info:"info",log:"info",debug:"debug"},s=(e,i)=>t[e]<=t[i],r=e=>"string"==typeof e?e:JSON.stringify(e),n=(e,t)=>`${r(e)} > ${r(t)}`,o=(e,t)=>{let i=`[${r(e)}]`;return typeof window<"u"?{text:`%c${i}`,style:`color: ${t.color||"#00bcd4"}; font-weight: bold;`}:{text:i}},a=(e,t,r,n)=>(...a)=>{if(!s(i[e],n()))return;if(!t)return void console[e](...a);let{text:c,style:d}=o(t,r);d?console[e](c,d,...a):console[e](c,...a)},c=(e,t)=>{let i=t.logLevel??"debug",s=()=>i;return{log:a("log",e,t,s),info:a("info",e,t,s),warn:a("warn",e,t,s),error:a("error",e,t,s),debug:a("debug",e,t,s),setLogLevel:e=>{i=e},extend:s=>c(e?n(e,s):s,{...t,logLevel:i})}},d=(e,t)=>c(e,{color:"#00bcd4",logLevel:"debug",...t}),l=d("angie-sdk",{color:"#00BCD4",logLevel:"error"}),g=e=>l.extend(e);var h,u,p,_,w,m,f;!function(e){e.POST_MESSAGE="postMessage"}(h||(h={})),function(e){e.POST_MESSAGE="postMessage"}(u||(u={})),function(e){e.STREAMABLE_HTTP="streamableHttp",e.SSE="sse"}(p||(p={})),function(e){e.LOCAL="local",e.REMOTE="remote"}(_||(_={})),function(e){e.SDK_ANGIE_READY_PING="sdk-angie-ready-ping",e.SDK_ANGIE_REFRESH_PING="sdk-angie-refresh-ping",e.SDK_ANGIE_ALL_SERVERS_REGISTERED="sdk-angie-all-servers-registered",e.SDK_REQUEST_CLIENT_CREATION="sdk-request-client-creation",e.SDK_REQUEST_INIT_SERVER="sdk-request-init-server",e.SDK_TRIGGER_ANGIE="sdk-trigger-angie",e.SDK_TRIGGER_ANGIE_RESPONSE="sdk-trigger-angie-response",e.ANGIE_SIDEBAR_RESIZED="angie-sidebar-resized",e.ANGIE_SIDEBAR_TOGGLED="angie-sidebar-toggled",e.ANGIE_CHAT_TOGGLE="angie-chat-toggle",e.ANGIE_STUDIO_TOGGLE="angie-studio-toggle",e.ANGIE_NAVIGATE_TO_URL="angie/navigate-to-url",e.ANGIE_PAGE_RELOAD="angie/page-reload",e.ANGIE_DISABLE_NAVIGATION_PREVENTION="angie/disable-navigation-prevention",e.ANGIE_NAVIGATE_AFTER_RESPONSE="angie/navigate-after-response"}(w||(w={})),function(e){e.SET="ANGIE_SET_LOCALSTORAGE",e.GET="ANGIE_GET_LOCALSTORAGE"}(m||(m={})),function(e){e.RESET_HASH="reset-hash",e.HOST_READY="host/ready",e.ANGIE_LOADED="angie/loaded",e.ANGIE_READY="angie/ready"}(f||(f={}));const y=g("angie-detector");class S{isAngieReady=!1;readyPromise;readyResolve;constructor(){if(this.readyPromise=new Promise(e=>{this.readyResolve=e}),"undefined"==typeof window)return;let e=0;const t=()=>{if(this.isAngieReady||e>=500)return void(!this.isAngieReady&&e>=500&&this.handleDetectionTimeout());const i=new MessageChannel;i.port1.onmessage=e=>{this.handleAngieReady(e.data),i.port1.close(),i.port2.close()};const s={type:w.SDK_ANGIE_READY_PING,timestamp:Date.now()};window.postMessage(s,window.location.origin,[i.port2]),e++,setTimeout(t,500)};t()}handleAngieReady(e){this.isAngieReady=!0;const t={isReady:!0,version:e.version,capabilities:e.capabilities};this.readyResolve&&this.readyResolve(t)}handleDetectionTimeout(){this.readyResolve&&this.readyResolve({isReady:!1}),y.warn("Detection timeout - Angie may not be available")}isReady(){return this.isAngieReady}async waitForReady(){return this.readyPromise}}class v{sessionId;onmessage;onerror;onclose;_port;_started=!1;_closed=!1;constructor(t){if(!t)throw new Error("MessagePort is required");this._port=t,this._port.onmessage=t=>{try{const i=e.parse(t.data);this.onmessage?.(i)}catch(e){const t=new Error(`Failed to parse message: ${e}`);this.onerror?.(t)}},this._port.onmessageerror=e=>{const t=new Error(`MessagePort error: ${JSON.stringify(e)}`);this.onerror?.(t)}}async start(){if(this._started)throw new Error("BrowserContextTransport already started! If using Client or Server class, note that connect() calls start() automatically.");if(this._closed)throw new Error("Cannot start a closed BrowserContextTransport");this._started=!0,this._port.start()}async send(e){if(this._closed)throw new Error("Cannot send on a closed BrowserContextTransport");return new Promise((t,i)=>{try{this._port.postMessage(e),t()}catch(e){const t=e instanceof Error?e:new Error(String(e));this.onerror?.(t),i(t)}})}async close(){this._closed||(this._closed=!0,this._port.close(),this.onclose?.())}}class b{async requestClientCreation(e){const{config:t}=e,i={serverId:e.id,serverName:t.name,serverTitle:t.title,serverVersion:t.version,description:t.description,transport:t.transport||u.POST_MESSAGE,capabilities:t.capabilities,instanceId:e.instanceId};return"type"in t&&"remote"===t.type&&(i.remote={url:t.url}),new Promise((e,t)=>{const s=new MessageChannel,r=setTimeout(()=>{t(new Error("Client creation request timed out after 15000ms"))},15e3);s.port1.onmessage=t=>{clearTimeout(r),e(t.data)};const n={type:w.SDK_REQUEST_CLIENT_CREATION,payload:i,timestamp:Date.now()};window.postMessage(n,window.location.origin,[s.port2])})}}const E={open:!1,iframe:null,iframeUrlObject:null};class k extends Error{}k.prototype.name="InvalidTokenError";var I,T,R,A={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},P=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(P||{});(R=P||(P={})).reset=function(){I=3,T=A},R.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");I=e},R.setLogger=function(e){T=e};var C=class e{constructor(e){this._name=e}debug(...t){I>=4&&T.debug(e._format(this._name,this._method),...t)}info(...t){I>=3&&T.info(e._format(this._name,this._method),...t)}warn(...t){I>=2&&T.warn(e._format(this._name,this._method),...t)}error(...t){I>=1&&T.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,i){const s=new e(`${t}.${i}`);return s.debug("begin"),s}static _format(e,t){const i=`[${e}]`;return t?`${i} ${t}:`:i}static debug(t,...i){I>=4&&T.debug(e._format(t),...i)}static info(t,...i){I>=3&&T.info(e._format(t),...i)}static warn(t,...i){I>=2&&T.warn(e._format(t),...i)}static error(t,...i){I>=1&&T.error(e._format(t),...i)}};P.reset();var x=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new k("Invalid token specified: must be a string");t||(t={});const i=!0===t.header?0:1,s=e.split(".")[i];if("string"!=typeof s)throw new k(`Invalid token specified: missing part #${i+1}`);let r;try{r=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let i=t.charCodeAt(0).toString(16).toUpperCase();return i.length<2&&(i="0"+i),"%"+i}))}(t)}catch(e){return atob(t)}}(s)}catch(e){throw new k(`Invalid token specified: invalid base64 for part #${i+1} (${e.message})`)}try{return JSON.parse(r)}catch(e){throw new k(`Invalid token specified: invalid json for part #${i+1} (${e.message})`)}}(e)}catch(e){throw C.error("JwtUtils.decode",e),e}}static async generateSignedJwt(e,t,i){const s=`${L.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${L.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,r=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},i,(new TextEncoder).encode(s));return`${s}.${L.encodeBase64Url(new Uint8Array(r))}`}static async generateSignedJwtWithHmac(e,t,i){const s=`${L.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${L.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,r=await window.crypto.subtle.sign("HMAC",i,(new TextEncoder).encode(s));return`${s}.${L.encodeBase64Url(new Uint8Array(r))}`}},O=e=>btoa([...new Uint8Array(e)].map(e=>String.fromCharCode(e)).join("")),U=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){const t="10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(+t^e._randomWord()&15>>+t/4).toString(16));return t.replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),i=await crypto.subtle.digest("SHA-256",t);return O(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw C.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const i=(new TextEncoder).encode([e,t].join(":"));return O(i)}static async hash(e,t){const i=(new TextEncoder).encode(t),s=await crypto.subtle.digest(e,i);return new Uint8Array(s)}static async customCalculateJwkThumbprint(t){let i;switch(t.kty){case"RSA":i={e:t.e,kty:t.kty,n:t.n};break;case"EC":i={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":i={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":i={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const s=await e.hash("SHA-256",JSON.stringify(i));return e.encodeBase64Url(s)}static async generateDPoPProof({url:t,accessToken:i,httpMethod:s,keyPair:r,nonce:n}){let o,a;const c={jti:window.crypto.randomUUID(),htm:null!=s?s:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};i&&(o=await e.hash("SHA-256",i),a=e.encodeBase64Url(o),c.ath=a),n&&(c.nonce=n);try{const e=await crypto.subtle.exportKey("jwk",r.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await x.generateSignedJwt(t,c,r.privateKey)}catch(e){throw e instanceof TypeError?new Error(`Error exporting dpop public key: ${e.message}`):e}}static async generateDPoPJkt(t){try{const i=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(i)}catch(e){throw e instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${e.message}`):e}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}static async generateClientAssertionJwt(t,i,s,r="HS256"){const n=Math.floor(Date.now()/1e3),o={alg:r,typ:"JWT"},a={iss:t,sub:t,aud:s,jti:e.generateUUIDv4(),exp:n+300,iat:n},c={HS256:"SHA-256",HS384:"SHA-384",HS512:"SHA-512"}[r];if(!c)throw new Error(`Unsupported algorithm: ${r}. Supported algorithms are: HS256, HS384, HS512`);const d=new TextEncoder,l=await crypto.subtle.importKey("raw",d.encode(i),{name:"HMAC",hash:c},!1,["sign"]);return await x.generateSignedJwtWithHmac(o,a,l)}};U.encodeBase64Url=e=>O(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var L=U,N=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new C(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},D=class{static center({...e}){var t;return null==e.width&&(e.width=null!=(t=[800,720,600,480].find(e=>e<=window.outerWidth/1.618))?t:360),null!=e.left||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),null!=e.height&&(null!=e.top||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter(([,e])=>null!=e).map(([e,t])=>`${e}=${"boolean"!=typeof t?t:t?"yes":"no"}`).join(",")}},q=class e extends N{constructor(){super(...arguments),this._logger=new C(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const i=this._logger.create("init");t=Math.max(Math.floor(t),1);const s=e.getEpochTime()+t;if(this.expiration===s&&this._timerHandle)return void i.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),i.debug("using duration",t),this._expiration=s;const r=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*r)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},M=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const i=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(i.slice(1))}},H=";",$=class extends Error{constructor(e,t){var i,s,r;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw C.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(i=e.error_description)?i:null,this.error_uri=null!=(s=e.error_uri)?s:null,this.state=e.userState,this.session_state=null!=(r=e.session_state)?r:null,this.url_state=e.url_state}},j=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},G=class{constructor(e){this._logger=new C("AccessTokenEvents"),this._expiringTimer=new q("Access token expiring"),this._expiredTimer=new q("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const i=e.expires_in;if(t.debug("access token present, remaining duration:",i),i>0){let e=i-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug("registering expiring timer, raising in",e,"seconds"),this._expiringTimer.init(e)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const s=i+1;t.debug("registering expired timer, raising in",s,"seconds"),this._expiredTimer.init(s)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},z=class{constructor(e,t,i,s,r){this._callback=e,this._client_id=t,this._intervalInSeconds=s,this._stopOnError=r,this._logger=new C("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};const n=new URL(i);this._frame_origin=n.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=n.href}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)})}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,1e3*this._intervalInSeconds)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},W=class{constructor(){this._logger=new C("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},F=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},K=class{constructor(e=[],t=null,i={}){this._jwtHandler=t,this._extraHeaders=i,this._logger=new C("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:i,...s}=t;if(!i)return await fetch(e,s);const r=new AbortController,n=setTimeout(()=>r.abort(),1e3*i);try{return await fetch(e,{...t,signal:r.signal})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw new j("Network timed out");throw e}finally{clearTimeout(n)}}async getJson(e,{token:t,credentials:i,timeoutInSeconds:s}={}){const r=this._logger.create("getJson"),n={Accept:this._contentTypes.join(", ")};let o;t&&(r.debug("token passed, setting Authorization header"),n.Authorization="Bearer "+t),this._appendExtraHeaders(n);try{r.debug("url:",e),o=await this.fetchWithTimeout(e,{method:"GET",headers:n,timeoutInSeconds:s,credentials:i})}catch(e){throw r.error("Network Error"),e}r.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find(e=>a.startsWith(e))&&r.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),o.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(e){if(r.error("Error parsing JSON response",e),o.ok)throw e;throw new Error(`${o.statusText} (${o.status})`)}if(!o.ok){if(r.error("Error from server:",c),c.error)throw new $(c);throw new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:i,timeoutInSeconds:s,initCredentials:r,extraHeaders:n}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...n};let c;void 0!==i&&(a.Authorization="Basic "+i),this._appendExtraHeaders(a);try{o.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:s,credentials:r})}catch(e){throw o.error("Network error"),e}o.debug("HTTP response received, status",c.status);const d=c.headers.get("Content-Type");if(d&&!this._contentTypes.find(e=>d.startsWith(e)))throw new Error(`Invalid response Content-Type: ${null!=d?d:"undefined"}, from URL: ${e}`);const l=await c.text();let g={};if(l)try{g=JSON.parse(l)}catch(e){if(o.error("Error parsing JSON response",e),c.ok)throw e;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(o.error("Error from server:",g),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new F(e,`${JSON.stringify(g)}`)}if(g.error)throw new $(g,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(g)}`)}return g}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),i=Object.keys(this._extraHeaders),s=["accept","content-type"],r=["authorization"];0!==i.length&&i.forEach(i=>{if(s.includes(i.toLocaleLowerCase()))return void t.warn("Protected header could not be set",i,s);if(r.includes(i.toLocaleLowerCase())&&Object.keys(e).includes(i))return void t.warn("Header could not be overridden",i,r);const n="function"==typeof this._extraHeaders[i]?this._extraHeaders[i]():this._extraHeaders[i];n&&""!==n&&(e[i]=n)})}},J=class{constructor(e){this._settings=e,this._logger=new C("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new K(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const i=this._logger.create(`_getMetadataProperty('${e}')`),s=await this.getMetadata();if(i.debug("resolved"),void 0===s[e]){if(!0===t)return void i.warn("Metadata does not contain optional property");i.throw(new Error("Metadata does not contain property "+e))}return s[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const i=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",i),!Array.isArray(i.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=i.keys,this._signingKeys}},B=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new C("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){return this._logger.create(`get('${e}')`),e=this._prefix+e,await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let i=0;i<e;i++){const e=await this._store.key(i);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},Q=class{constructor({authority:e,metadataUrl:t,metadata:i,signingKeys:s,metadataSeed:r,client_id:n,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:d,post_logout_redirect_uri:l,client_authentication:g="client_secret_post",token_endpoint_auth_signing_alg:h="HS256",prompt:u,display:p,max_age:_,ui_locales:w,acr_values:m,resource:f,response_mode:y,filterProtocolClaims:S=!0,loadUserInfo:v=!1,requestTimeoutInSeconds:b,staleStateAgeInSeconds:E=900,mergeClaimsStrategy:k={array:"replace"},disablePKCE:I=!1,stateStore:T,revokeTokenAdditionalContentTypes:R,fetchRequestCredentials:A,refreshTokenAllowedScope:P,extraQueryParams:C={},extraTokenParams:x={},extraHeaders:O={},dpop:U,omitScopeWhenRequesting:L=!1}){var N;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=i,this.metadataSeed=r,this.signingKeys=s,this.client_id=n,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=d,this.post_logout_redirect_uri=l,this.client_authentication=g,this.token_endpoint_auth_signing_alg=h,this.prompt=u,this.display=p,this.max_age=_,this.ui_locales=w,this.acr_values=m,this.resource=f,this.response_mode=y,this.filterProtocolClaims=null==S||S,this.loadUserInfo=!!v,this.staleStateAgeInSeconds=E,this.mergeClaimsStrategy=k,this.omitScopeWhenRequesting=L,this.disablePKCE=!!I,this.revokeTokenAdditionalContentTypes=R,this.fetchRequestCredentials=A||"same-origin",this.requestTimeoutInSeconds=b,T)this.stateStore=T;else{const e="undefined"!=typeof window?window.localStorage:new W;this.stateStore=new B({store:e})}if(this.refreshTokenAllowedScope=P,this.extraQueryParams=C,this.extraTokenParams=x,this.extraHeaders=O,this.dpop=U,this.dpop&&!(null==(N=this.dpop)?void 0:N.store))throw new Error("A DPoPStore is required when dpop is enabled")}},V=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new C("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const i=x.decode(e);return t.debug("JWT decoding successful"),i}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new K(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const i=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",i);const s=await this._jsonService.getJson(i,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",s),s}},X=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new C("TokenClient"),this._jsonService=new K(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:i=this._settings.client_id,client_secret:s=this._settings.client_secret,extraHeaders:r,...n}){const o=this._logger.create("exchangeCode");i||o.throw(new Error("A client_id is required")),t||o.throw(new Error("A redirect_uri is required")),n.code||o.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[e,t]of Object.entries(n))null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==s)throw o.throw(new Error("A client_secret is required")),null;let c;const d=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=L.generateBasicAuth(i,s);break;case"client_secret_post":a.append("client_id",i),s&&a.append("client_secret",s);break;case"client_secret_jwt":{const e=await L.generateClientAssertionJwt(i,s,d,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",i),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const l=await this._jsonService.postForm(d,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:r});return o.debug("got response"),l}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:i=this._settings.client_secret,scope:s=this._settings.scope,...r}){const n=this._logger.create("exchangeCredentials");t||n.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set("scope",s);for(const[e,t]of Object.entries(r))null!=t&&o.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==i)throw n.throw(new Error("A client_secret is required")),null;let a;const c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":a=L.generateBasicAuth(t,i);break;case"client_secret_post":o.append("client_id",t),i&&o.append("client_secret",i);break;case"client_secret_jwt":{const e=await L.generateClientAssertionJwt(t,i,c,this._settings.token_endpoint_auth_signing_alg);o.append("client_id",t),o.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),o.append("client_assertion",e);break}}n.debug("got token endpoint");const d=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),d}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:i=this._settings.client_secret,timeoutInSeconds:s,extraHeaders:r,...n}){const o=this._logger.create("exchangeRefreshToken");t||o.throw(new Error("A client_id is required")),n.refresh_token||o.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[e,t]of Object.entries(n))Array.isArray(t)?t.forEach(t=>a.append(e,t)):null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==i)throw o.throw(new Error("A client_secret is required")),null;let c;const d=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=L.generateBasicAuth(t,i);break;case"client_secret_post":a.append("client_id",t),i&&a.append("client_secret",i);break;case"client_secret_jwt":{const e=await L.generateClientAssertionJwt(t,i,d,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",t),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const l=await this._jsonService.postForm(d,{body:a,basicAuth:c,timeoutInSeconds:s,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:r});return o.debug("got response"),l}async revoke(e){var t;const i=this._logger.create("revoke");e.token||i.throw(new Error("A token is required"));const s=await this._metadataService.getRevocationEndpoint(!1);i.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const r=new URLSearchParams;for(const[t,i]of Object.entries(e))null!=i&&r.set(t,i);r.set("client_id",this._settings.client_id),this._settings.client_secret&&r.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(s,{body:r,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),i.debug("got response")}},Y=class{constructor(e,t,i){this._settings=e,this._metadataService=t,this._claimsService=i,this._logger=new C("ResponseValidator"),this._userInfoService=new V(this._settings,this._metadataService),this._tokenClient=new X(this._settings,this._metadataService)}async validateSigninResponse(e,t,i){const s=this._logger.create("validateSigninResponse");this._processSigninState(e,t),s.debug("state processed"),await this._processCode(e,t,i),s.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),s.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),s.debug("claims processed")}async validateCredentialsResponse(e,t){const i=this._logger.create("validateCredentialsResponse"),s=e.isOpenId&&!!e.id_token;s&&this._validateIdTokenAttributes(e),i.debug("tokens validated"),await this._processClaims(e,t,s),i.debug("claims processed")}async validateRefreshResponse(e,t){const i=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),i.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const s=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,s),i.debug("claims processed")}validateSignoutResponse(e,t){const i=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&i.throw(new Error("State does not match")),i.debug("state validated"),e.userState=t.data,e.error)throw i.warn("Response was error",e.error),new $(e)}_processSigninState(e,t){const i=this._logger.create("_processSigninState");if(t.id!==e.state&&i.throw(new Error("State does not match")),t.client_id||i.throw(new Error("No client_id on state")),t.authority||i.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&i.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&i.throw(new Error("client_id mismatch on settings vs. signin state")),i.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw i.warn("Response was error",e.error),new $(e);t.code_verifier&&!e.code&&i.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,i=!0){const s=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void s.debug("not loading user info");s.debug("loading user info");const r=await this._userInfoService.getClaims(e.access_token);s.debug("user info claims received from user info endpoint"),i&&r.sub!==e.profile.sub&&s.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(r)),s.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,i){const s=this._logger.create("_processCode");if(e.code){s.debug("Validating code");const r=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:i,...t.extraTokenParams});Object.assign(e,r)}else s.debug("No code to process")}_validateIdTokenAttributes(e,t){var i;const s=this._logger.create("_validateIdTokenAttributes");s.debug("decoding ID Token JWT");const r=x.decode(null!=(i=e.id_token)?i:"");if(r.sub||s.throw(new Error("ID Token is missing a subject claim")),t){const e=x.decode(t);r.sub!==e.sub&&s.throw(new Error("sub in id_token does not match current sub")),r.auth_time&&r.auth_time!==e.auth_time&&s.throw(new Error("auth_time in id_token does not match original auth_time")),r.azp&&r.azp!==e.azp&&s.throw(new Error("azp in id_token does not match original azp")),!r.azp&&e.azp&&s.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=r}},Z=class e{constructor(e){this.id=e.id||L.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=q.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new C("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return C.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,i){const s=C.createStatic("State","clearStaleState"),r=q.getEpochTime()-i,n=await t.getAllKeys();s.debug("got keys",n);for(let i=0;i<n.length;i++){const o=n[i],a=await t.get(o);let c=!1;if(a)try{const t=await e.fromStorageString(a);s.debug("got item from key:",o,t.created),t.created<=r&&(c=!0)}catch(e){s.error("Error parsing state for key:",o,e),c=!0}else s.debug("no item in storage for key:",o),c=!0;c&&(s.debug("removed item for key:",o),t.remove(o))}}},ee=class e extends Z{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(t){const i=!0===t.code_verifier?L.generateCodeVerifier():t.code_verifier||void 0,s=i?await L.generateCodeChallenge(i):void 0;return new e({...t,code_verifier:i,code_challenge:s})}toStorageString(){return new C("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){C.createStatic("SigninState","fromStorageString");const i=JSON.parse(t);return e.create(i)}},te=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:i,client_id:s,redirect_uri:r,response_type:n,scope:o,state_data:a,response_mode:c,request_type:d,client_secret:l,nonce:g,url_state:h,resource:u,skipUserInfo:p,extraQueryParams:_,extraTokenParams:w,disablePKCE:m,dpopJkt:f,omitScopeWhenRequesting:y,...S}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!s)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!r)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!n)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!o)throw this._logger.error("create: No scope passed"),new Error("scope");if(!i)throw this._logger.error("create: No authority passed"),new Error("authority");const v=await ee.create({data:a,request_type:d,url_state:h,code_verifier:!m,client_id:s,authority:i,redirect_uri:r,response_mode:c,client_secret:l,scope:o,extraTokenParams:w,skipUserInfo:p}),b=new URL(t);b.searchParams.append("client_id",s),b.searchParams.append("redirect_uri",r),b.searchParams.append("response_type",n),y||b.searchParams.append("scope",o),g&&b.searchParams.append("nonce",g),f&&b.searchParams.append("dpop_jkt",f);let E=v.id;h&&(E=`${E}${H}${h}`),b.searchParams.append("state",E),v.code_challenge&&(b.searchParams.append("code_challenge",v.code_challenge),b.searchParams.append("code_challenge_method","S256")),u&&(Array.isArray(u)?u:[u]).forEach(e=>b.searchParams.append("resource",e));for(const[e,t]of Object.entries({response_mode:c,...S,..._}))null!=t&&b.searchParams.append(e,t.toString());return new e({url:b.href,state:v})}};te._logger=new C("SigninRequest");var ie=te,se=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(H);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(H))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-q.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+q.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},re=class{constructor({url:e,state_data:t,id_token_hint:i,post_logout_redirect_uri:s,extraQueryParams:r,request_type:n,client_id:o,url_state:a}){if(this._logger=new C("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(i&&c.searchParams.append("id_token_hint",i),o&&c.searchParams.append("client_id",o),s&&(c.searchParams.append("post_logout_redirect_uri",s),t||a)){this.state=new Z({data:t,request_type:n,url_state:a});let e=this.state.id;a&&(e=`${e}${H}${a}`),c.searchParams.append("state",e)}for(const[e,t]of Object.entries({...r}))null!=t&&c.searchParams.append(e,t.toString());this.url=c.href}},ne=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(H);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(H))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},oe=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],ae=["sub","iss","aud","exp","iat"],ce=class{constructor(e){this._settings=e,this._logger=new C("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:oe;for(const i of e)ae.includes(i)||delete t[i]}return t}mergeClaims(e,t){const i={...e};for(const[e,s]of Object.entries(t))if(i[e]!==s)if(Array.isArray(i[e])||Array.isArray(s))if("replace"==this._settings.mergeClaimsStrategy.array)i[e]=s;else{const t=Array.isArray(i[e])?i[e]:[i[e]];for(const e of Array.isArray(s)?s:[s])t.includes(e)||t.push(e);i[e]=t}else"object"==typeof i[e]&&"object"==typeof s?i[e]=this.mergeClaims(i[e],s):i[e]=s;return i}},de=class{constructor(e,t){this.keys=e,this.nonce=t}},le=class{constructor(e,t){this._logger=new C("OidcClient"),this.settings=e instanceof Q?e:new Q(e),this.metadataService=null!=t?t:new J(this.settings),this._claimsService=new ce(this.settings),this._validator=new Y(this.settings,this.metadataService,this._claimsService),this._tokenClient=new X(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:i,request_type:s,id_token_hint:r,login_hint:n,skipUserInfo:o,nonce:a,url_state:c,response_type:d=this.settings.response_type,scope:l=this.settings.scope,redirect_uri:g=this.settings.redirect_uri,prompt:h=this.settings.prompt,display:u=this.settings.display,max_age:p=this.settings.max_age,ui_locales:_=this.settings.ui_locales,acr_values:w=this.settings.acr_values,resource:m=this.settings.resource,response_mode:f=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:S=this.settings.extraTokenParams,dpopJkt:v,omitScopeWhenRequesting:b=this.settings.omitScopeWhenRequesting}){const E=this._logger.create("createSigninRequest");if("code"!==d)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const k=await this.metadataService.getAuthorizationEndpoint();E.debug("Received authorization endpoint",k);const I=await ie.create({url:k,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:g,response_type:d,scope:l,state_data:e,url_state:c,prompt:h,display:u,max_age:p,ui_locales:_,id_token_hint:r,login_hint:n,acr_values:w,dpopJkt:v,resource:m,request:t,request_uri:i,extraQueryParams:y,extraTokenParams:S,request_type:s,response_mode:f,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:b});await this.clearStaleState();const T=I.state;return await this.settings.stateStore.set(T.id,T.toStorageString()),I}async readSigninResponseState(e,t=!1){const i=this._logger.create("readSigninResponseState"),s=new se(M.readParams(e,this.settings.response_mode));if(!s.state)throw i.throw(new Error("No state in response")),null;const r=await this.settings.stateStore[t?"remove":"get"](s.state);if(!r)throw i.throw(new Error("No matching state found in storage")),null;return{state:await ee.fromStorageString(r),response:s}}async processSigninResponse(e,t,i=!0){const s=this._logger.create("processSigninResponse"),{state:r,response:n}=await this.readSigninResponseState(e,i);if(s.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(n,r,t)}catch(e){if(!(e instanceof F&&this.settings.dpop))throw e;{const i=await this.getDpopProof(this.settings.dpop.store,e.nonce);t.DPoP=i,await this._validator.validateSigninResponse(n,r,t)}}return n}async getDpopProof(e,t){let i,s;return(await e.getAllKeys()).includes(this.settings.client_id)?(s=await e.get(this.settings.client_id),s.nonce!==t&&t&&(s.nonce=t,await e.set(this.settings.client_id,s))):(i=await L.generateDPoPKeys(),s=new de(i,t),await e.set(this.settings.client_id,s)),await L.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:s.keys,nonce:s.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:i=!1,extraTokenParams:s={}}){const r=await this._tokenClient.exchangeCredentials({username:e,password:t,...s}),n=new se(new URLSearchParams);return Object.assign(n,r),await this._validator.validateCredentialsResponse(n,i),n}async useRefreshToken({state:e,redirect_uri:t,resource:i,timeoutInSeconds:s,extraHeaders:r,extraTokenParams:n}){var o;const a=this._logger.create("useRefreshToken");let c,d;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(o=e.scope)?void 0:o.split(" "))||[]).filter(e=>t.includes(e)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);r={...r,DPoP:e}}try{d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:i,timeoutInSeconds:s,extraHeaders:r,...n})}catch(o){if(!(o instanceof F&&this.settings.dpop))throw o;r.DPoP=await this.getDpopProof(this.settings.dpop.store,o.nonce),d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:i,timeoutInSeconds:s,extraHeaders:r,...n})}const l=new se(new URLSearchParams);return Object.assign(l,d),a.debug("validating response",l),await this._validator.validateRefreshResponse(l,{...e,scope:c}),l}async createSignoutRequest({state:e,id_token_hint:t,client_id:i,request_type:s,url_state:r,post_logout_redirect_uri:n=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",c),i||!n||t||(i=this.settings.client_id);const d=new re({url:c,id_token_hint:t,client_id:i,post_logout_redirect_uri:n,state_data:e,extraQueryParams:o,request_type:s,url_state:r});await this.clearStaleState();const l=d.state;return l&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(l.id,l.toStorageString())),d}async readSignoutResponseState(e,t=!1){const i=this._logger.create("readSignoutResponseState"),s=new ne(M.readParams(e,this.settings.response_mode));if(!s.state){if(i.debug("No state in response"),s.error)throw i.warn("Response was error:",s.error),new $(s);return{state:void 0,response:s}}const r=await this.settings.stateStore[t?"remove":"get"](s.state);if(!r)throw i.throw(new Error("No matching state found in storage")),null;return{state:await Z.fromStorageString(r),response:s}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:i,response:s}=await this.readSignoutResponseState(e,!0);return i?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(s,i)):t.debug("No state from storage; skipping response validation"),s}clearStaleState(){return this._logger.create("clearStaleState"),Z.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},ge=class{constructor(e){this._userManager=e,this._logger=new C("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const i=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,i.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,i.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){i.debug("initializing check session iframe");const s=this._userManager.settings.client_id,r=this._userManager.settings.checkSessionIntervalInSeconds,n=this._userManager.settings.stopCheckSessionOnError,o=new z(this._callback,s,e,r,n);await o.load(),this._checkSessionIFrame=o,o.start(t)}else i.warn("no check session iframe found in the metadata")}catch(e){i.error("Error from getCheckSessionIframe:",e instanceof Error?e.message:e)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval(async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(t){e.error("error from querySessionStatus",t instanceof Error?t.message:t)}},1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let i=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(i=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),i?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch(e=>{this._logger.error(e)})}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},he=class e{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-q.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+q.getEpochTime())}get expired(){const e=this.expires_in;if(void 0!==e)return e<=0}get scopes(){var e,t;return null!=(t=null==(e=this.scope)?void 0:e.split(" "))?t:[]}toStorageString(){return new C("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return C.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},ue="oidc-client",pe=class{constructor(){this._abort=new N("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:i,keepOpen:s}=await new Promise((i,s)=>{const r=r=>{var n;const o=r.data,a=null!=(n=e.scriptOrigin)?n:window.location.origin;if(r.origin===a&&(null==o?void 0:o.source)===ue){try{const i=M.readParams(o.url,e.response_mode).get("state");if(i||t.warn("no state found in response url"),r.source!==this._window&&i!==e.state)return}catch{this._dispose(),s(new Error("Invalid response from window"))}i(o)}};window.addEventListener("message",r,!1),this._disposeHandlers.add(()=>window.removeEventListener("message",r,!1));const n=new BroadcastChannel(`oidc-client-popup-${e.state}`);n.addEventListener("message",r,!1),this._disposeHandlers.add(()=>n.close()),this._disposeHandlers.add(this._abort.addHandler(e=>{this._dispose(),s(e)}))});return t.debug("got response from window"),this._dispose(),s||this.close(),{url:i}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,i=!1,s=window.location.origin){const r={source:ue,url:t,keepOpen:i},n=new C("_notifyParent");if(e)n.debug("With parent. Using parent.postMessage."),e.postMessage(r,s);else{n.debug("No parent. Using BroadcastChannel.");const e=new URL(t).searchParams.get("state");if(!e)throw new Error("No parent and no state in URL. Can't complete notification.");const i=new BroadcastChannel(`oidc-client-popup-${e}`);i.postMessage(r),i.close()}}},_e={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},we="_blank",me=60,fe=2,ye=class extends Q{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:i=e.post_logout_redirect_uri,popupWindowFeatures:s=_e,popupWindowTarget:r=we,redirectMethod:n="assign",redirectTarget:o="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:d,silent_redirect_uri:l=e.redirect_uri,silentRequestTimeoutInSeconds:g,automaticSilentRenew:h=!0,validateSubOnSilentRenew:u=!0,includeIdTokenInSilentRenew:p=!1,monitorSession:_=!1,monitorAnonymousSession:w=!1,checkSessionIntervalInSeconds:m=fe,query_status_response_type:f="code",stopCheckSessionOnError:y=!0,revokeTokenTypes:S=["access_token","refresh_token"],revokeTokensOnSignout:v=!1,includeIdTokenInSilentSignout:b=!1,accessTokenExpiringNotificationTimeInSeconds:E=me,userStore:k}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=i,this.popupWindowFeatures=s,this.popupWindowTarget=r,this.redirectMethod=n,this.redirectTarget=o,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=l,this.silentRequestTimeoutInSeconds=g||d||10,this.automaticSilentRenew=h,this.validateSubOnSilentRenew=u,this.includeIdTokenInSilentRenew=p,this.monitorSession=_,this.monitorAnonymousSession=w,this.checkSessionIntervalInSeconds=m,this.stopCheckSessionOnError=y,this.query_status_response_type=f,this.revokeTokenTypes=S,this.revokeTokensOnSignout=v,this.includeIdTokenInSilentSignout=b,this.accessTokenExpiringNotificationTimeInSeconds=E,k)this.userStore=k;else{const e="undefined"!=typeof window?window.sessionStorage:new W;this.userStore=new B({store:e})}}},Se=class e extends pe{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new C("IFrameWindow"),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout(()=>{this._abort.raise(new j("IFrame timed out without a response"))},1e3*this._timeoutInSeconds);return this._disposeHandlers.add(()=>clearTimeout(t)),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",e=>{var t;const i=e.target;null==(t=i.parentNode)||t.removeChild(i),this._abort.raise(new Error("IFrame removed from DOM"))},!0),null==(e=this._frame.contentWindow)||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},ve=class{constructor(e){this._settings=e,this._logger=new C("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new Se({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),Se.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},be=class extends pe{constructor({popupWindowTarget:e=we,popupWindowFeatures:t={},popupSignal:i,popupAbortOnClose:s}){super(),this._logger=new C("PopupWindow");const r=D.center({..._e,...t});this._window=window.open(void 0,e,D.serialize(r)),this.abortOnClose=Boolean(s),i&&i.addEventListener("abort",()=>{var e;this._abort.raise(new Error(null!=(e=i.reason)?e:"Popup aborted"))}),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout(()=>{this._window&&"boolean"==typeof this._window.closed&&!this._window.closed?this.close():this._abort.raise(new Error("Popup blocked by user"))},1e3*t.closePopupWindowAfterInSeconds)}async navigate(e){var t;null==(t=this._window)||t.focus();const i=setInterval(()=>{this._window&&!this._window.closed||(this._logger.debug("Popup closed by user or isolated by redirect"),s(),this._disposeHandlers.delete(s),this.abortOnClose&&this._abort.raise(new Error("Popup closed by user")))},500),s=()=>clearInterval(i);return this._disposeHandlers.add(s),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),t||window.opener||window.close()}},Ee=class{constructor(e){this._settings=e,this._logger=new C("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:i,popupAbortOnClose:s}){return new be({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:i,popupAbortOnClose:s})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),be.notifyOpener(e,t)}},ke=class{constructor(e){this._settings=e,this._logger=new C("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var i;this._logger.create("prepare");let s=window.self;"top"===t&&(s=null!=(i=window.top)?i:window.self);const r=s.location[e].bind(s.location);let n;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise((t,i)=>{n=i,window.addEventListener("pageshow",()=>t(window.location.href)),r(e.url)});return await t},close:()=>{this._logger.create("close"),null==n||n(new Error("Redirect aborted")),s.stop()}}}async callback(){}},Ie=class extends G{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new C("UserManagerEvents"),this._userLoaded=new N("User loaded"),this._userUnloaded=new N("User unloaded"),this._silentRenewError=new N("Silent renew error"),this._userSignedIn=new N("User signed in"),this._userSignedOut=new N("User signed out"),this._userSessionChanged=new N("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},Te=class{constructor(e){this._userManager=e,this._logger=new C("SilentRenewService"),this._isStarted=!1,this._retryTimer=new q("Retry Silent Renew"),this._tokenExpiring=async()=>{const e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof j)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),await this._userManager.events._raiseSilentRenewError(t)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},Re=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},Ae=class{constructor(e,t,i,s){this._logger=new C("UserManager"),this.settings=new ye(e),this._client=new le(e),this._redirectNavigator=null!=t?t:new ke(this.settings),this._popupNavigator=null!=i?i:new Ee(this.settings),this._iframeNavigator=null!=s?s:new ve(this.settings),this._events=new Ie(this.settings),this._silentRenewService=new Te(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new ge(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),i=await this._loadUser();return i?(t.info("user loaded"),await this._events.load(i,e),i):(t.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");const{redirectMethod:i,...s}=e;let r;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(r=await this.generateDPoPJkt(this.settings.dpop));const n=await this._redirectNavigator.prepare({redirectMethod:i});await this._signinStart({request_type:"si:r",dpopJkt:r,...s},n)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),i=await this._signinEnd(e);return i.profile&&i.profile.sub?t.info("success, signed in subject",i.profile.sub):t.info("no subject"),i}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:i=!1}){const s=this._logger.create("signinResourceOwnerCredential"),r=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:i,extraTokenParams:this.settings.extraTokenParams});s.debug("got signin response");const n=await this._buildUser(r);return n.profile&&n.profile.sub?s.info("success, signed in subject",n.profile.sub):s.info("no subject"),n}async signinPopup(e={}){var t;const i=this._logger.create("signinPopup");let s;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:r,popupWindowTarget:n,popupSignal:o,popupAbortOnClose:a,...c}=e,d=this.settings.popup_redirect_uri;d||i.throw(new Error("No popup_redirect_uri configured"));const l=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:n,popupSignal:o,popupAbortOnClose:a}),g=await this._signin({request_type:"si:p",redirect_uri:d,display:"popup",dpopJkt:s,...c},l);return g&&(g.profile&&g.profile.sub?i.info("success, signed in subject",g.profile.sub):i.info("no subject")),g}async signinPopupCallback(e=window.location.href,t=!1){const i=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),i.info("success")}async signinSilent(e={}){var t,i;const s=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:r,...n}=e;let o,a=await this._loadUser();if(!e.forceIframeAuth&&(null==a?void 0:a.refresh_token)){s.debug("using refresh token");const e=new Re(a);return await this._useRefreshToken({state:e,redirect_uri:n.redirect_uri,resource:n.resource,extraTokenParams:n.extraTokenParams,timeoutInSeconds:r})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(o=await this.generateDPoPJkt(this.settings.dpop));const c=this.settings.silent_redirect_uri;let d;c||s.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(s.debug("subject prior to silent renew:",a.profile.sub),d=a.profile.sub);const l=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r});return a=await this._signin({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:o,...n},l,d),a&&((null==(i=a.profile)?void 0:i.sub)?s.info("success, signed in subject",a.profile.sub):s.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),i=new he({...e.state,...t});return await this.storeUser(i),await this._events.load(i),i}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:i}=await this._client.readSignoutResponseState(e);if(i)switch(i.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:i,...s}=e,r=this.settings.silent_redirect_uri;r||t.throw(new Error("No silent_redirect_uri configured"));const n=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:i}),a=await this._signinStart({request_type:"si:s",redirect_uri:r,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==n?void 0:n.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...s},o);try{const e={},i=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),i.session_state&&i.profile.sub?(t.info("success for subject",i.profile.sub),{session_state:i.session_state,sub:i.profile.sub}):(t.info("success, user not authenticated"),null)}catch(e){if(this.settings.monitorAnonymousSession&&e instanceof $)switch(e.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:e.session_state}}throw e}}async _signin(e,t,i){const s=await this._signinStart(e,t);return await this._signinEnd(s.url,i)}async _signinStart(e,t){const i=this._logger.create("_signinStart");try{const s=await this._client.createSigninRequest(e);return i.debug("got signin request"),await t.navigate({url:s.url,state:s.state.id,response_mode:s.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw i.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signinEnd(e,t){const i=this._logger.create("_signinEnd"),s=await this._client.processSigninResponse(e,{});return i.debug("got signin response"),await this._buildUser(s,t)}async _buildUser(e,t){const i=this._logger.create("_buildUser"),s=new he(e);if(t){if(t!==s.profile.sub)throw i.debug("current user does not match user returned from signin. sub from signin:",s.profile.sub),new $({...e,error:"login_required"});i.debug("current user matches user returned from signin")}return await this.storeUser(s),i.debug("user stored"),await this._events.load(s),s}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:i,...s}=e,r=await this._redirectNavigator.prepare({redirectMethod:i});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...s},r),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),i=await this._signoutEnd(e);return t.info("success"),i}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:i,popupWindowTarget:s,popupSignal:r,...n}=e,o=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:i,popupWindowTarget:s,popupSignal:r});await this._signout({request_type:"so:p",post_logout_redirect_uri:o,state:null==o?void 0:{},...n},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const i=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),i.info("success")}async _signout(e,t){const i=await this._signoutStart(e,t);return await this._signoutEnd(i.url)}async _signoutStart(e={},t){var i;const s=this._logger.create("_signoutStart");try{const r=await this._loadUser();s.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(r);const n=e.id_token_hint||r&&r.id_token;n&&(s.debug("setting id_token_hint in signout request"),e.id_token_hint=n),await this.removeUser(),s.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return s.debug("got signout request"),await t.navigate({url:o.url,state:null==(i=o.state)?void 0:i.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw s.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),i=await this._client.processSignoutResponse(e);return t.debug("got signout response"),i}async signoutSilent(e={}){var t;const i=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:s,...r}=e,n=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,o=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:n,...r},a),i.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const i=this._logger.create("_revokeInternal");if(!e)return;const s=t.filter(t=>"string"==typeof e[t]);if(s.length){for(const t of s)await this._client.revokeToken(e[t],t),i.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),i.debug("user stored"),await this._events.load(e)}else i.debug("no need to revoke due to no token(s)")}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),he.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const i=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,i)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,i,s){var r,n;const o=await(null==(n=null==(r=this.settings.dpop)?void 0:r.store)?void 0:n.get(this.settings.client_id));if(o)return await L.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:i,keyPair:o.keys,nonce:s})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const i=await L.generateDPoPKeys();t=new de(i),await e.store.set(this.settings.client_id,t)}return await L.generateDPoPJkt(t.keys)}};const Pe="OAUTH2_LOGIN_FLOW_COMPLETE_EVENT",Ce="OAUTH_GET_TOP_URL",xe="OAUTH_REDIRECT_TOP_WINDOW",Oe="OAUTH_UPDATE_URL",Ue="OAUTH2_CHECK_PENDING",Le="oauth2_top_origin",Ne="oauth2_login_success",De="oauth2_state",qe=60,Me=Math.max(qe-15,20),He=d("oidc-auth",{color:"green"}),$e=e=>He.extend(e);d("oidc-auth-utils");const je=()=>"undefined"==typeof window?"":new URLSearchParams(window.location.search).get("origin")||"";class Ge{static instance=null;settings=null;constructor(){}static getInstance(){return Ge.instance||(Ge.instance=new Ge),Ge.instance}configure(e){this.settings=e}isConfigured(){return null!==this.settings}getSettings(){if(!this.settings)throw new Error("OidcAuthConfig not configured. Call configure() or pass settings to OidcAuthClient.initialize().");return this.settings}getAuthOrigin(){const{authOrigin:e,authEndpoint:t}=this.getSettings();return e||new URL(t).origin}isAccessTokenProactiveRefreshEnabled(){return this.settings?.accessTokenProactiveRefreshEnabled??!0}getOidcSettings(){const e="undefined"==typeof window?"":window.location.origin,{clientId:t,authEndpoint:i}=this.getSettings(),s=this.getAuthOrigin(),r="undefined"!=typeof window?new B({store:window.localStorage}):void 0,{accessTokenExpiringNotificationTimeInSeconds:n=qe}=this.getSettings();return{client_id:t,authority:s,redirect_uri:`${e}/login/oauth-callback`,post_logout_redirect_uri:e,response_type:"code",scope:"openid offline_access",automaticSilentRenew:!1,accessTokenExpiringNotificationTimeInSeconds:n,stateStore:r,userStore:r,metadata:{issuer:s,authorization_endpoint:i,token_endpoint:`${s}/connect/api/v1/oauth2/token`,end_session_endpoint:`${s}/logout/`}}}getAccessTokenExpiringNotificationTimeInSeconds(){return this.getSettings().accessTokenExpiringNotificationTimeInSeconds??qe}getAccessTokenFreshnessThresholdInSeconds(){return this.getSettings().accessTokenFreshnessThresholdInSeconds??Me}getAllowedParentOrigins(){return this.settings?.allowedParentOrigins}}const ze=Ge.getInstance(),We=$e("oidc-auth:host-api"),Fe=async e=>new Promise((t,i)=>{const s=new MessageChannel;let r=!1;const n=()=>{r=!0,s.port1.close()},o=setTimeout(()=>{r||(n(),i(new Error(`Host message timeout: ${e.type}`)))},1e4);s.port1.onmessage=e=>{clearTimeout(o),n(),"success"!==e.data.status?i(e.data.payload):t(e.data.payload)};const a=new URLSearchParams(window.location.search).get("origin")||"";if(!function(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return!1;const t=ze.getAllowedParentOrigins();return!t||0===t.length||t.includes(e)}(a))return clearTimeout(o),n(),void i(new Error("Origin not allowed"));We.log("posting message to host",e),window.top.postMessage({type:e.type,payload:e.payload,...e.data||{}},a,[s.port2])}),Ke=$e("oidc-auth:OidcAuthTimer");class Je{timerHandle=null;expiration=null;initialized=!1;callback=()=>{};constructor(){this.timerHandle=null}init(e,t,i){const s=e-this.getEpochTime(),r=Math.max(s-t,10);this.cancel(),this.expiration=r,this.callback=i,Ke.debug("OIDC: timer - using expiration",r,s,t,e,s-t),this.timerHandle=setTimeout(this.callback,1e3*r),this.initialized=!0}cancel(){this.timerHandle&&(clearTimeout(this.timerHandle),this.timerHandle=null),this.expiration=null}getEpochTime(){return Math.floor(Date.now()/1e3)}isInitialized(){return this.initialized}}const Be=$e("oidc-auth:OidcAuthClient");class Qe{static instance=null;userManager=null;initialized=!1;accessTokenExpiringTimer=null;retryTimers=new Set;constructor(){}static getInstance(){return Qe.instance||(Qe.instance=new Qe),Qe.instance}isInitialized(){return this.initialized}ensureInitialized(){if(!this.userManager)throw new Error("OidcAuthClient not initialized. Call initialize() first.");return this.userManager}initialize(e){if(e&&(this.initialized=!1,ze.configure(e)),this.initialized)Be.info("OIDC: initialize() - already initialized, skipping");else if("undefined"!=typeof window)if(ze.isConfigured())try{Be.info("OIDC: initialize() - starting initialization");const e=ze.getOidcSettings();this.userManager=new Ae(e),P.setLogger(Be),P.setLevel(P.ERROR),this.initAccessTokenExpiringTimer(),this.initialized=!0}catch(e){throw Be.error("OIDC: initialize() - FAILED:",e),e}else Be.warn("OIDC: initialize() - skipped, config not set");else Be.warn("OidcAuthClient cannot initialize on server side")}async initAccessTokenExpiringTimer(){ze.isAccessTokenProactiveRefreshEnabled()?this.getUser().then(e=>{const t=e?.expires_at;t&&(this.accessTokenExpiringTimer||(this.accessTokenExpiringTimer=new Je),this.accessTokenExpiringTimer.init(t,ze.getAccessTokenExpiringNotificationTimeInSeconds(),async()=>{Be.info("OIDC: timer proactive refresh access token expiring timer fired",t),this.proactiveRefreshWithRetry()}))}).catch(e=>{Be.error("OIDC: initAccessTokenExpiringTimer - FAILED:",e)}):Be.warn("OIDC: timer - not starting, access token proactive refresh is disabled")}async getUser(){if(!this.userManager)return null;try{return await this.userManager.getUser()}catch(e){return Be.error("OIDC: getUser - FAILED:",e),null}}async storeUser(e){const t=this.ensureInitialized();await t.storeUser(e)}async getAccessToken(){const e=await this.getUser();if(!e)return Be.info("OIDC: getAccessToken - no user found"),null;if(e.expired)try{const e=await this.signinSilent();return e?.access_token||null}catch(e){return Be.error("OIDC: getAccessToken - silent renew failed:",e),null}return this.isTokenFresh(e)||this.signinSilent().catch(e=>{Be.error("OIDC: getAccessToken - background refresh failed:",e)}),e.access_token}getUserData(){if("undefined"==typeof window)return null;try{const e=ze.getOidcSettings(),t=`oidc.user:${e.authority}:${e.client_id}`,i=localStorage.getItem(t);if(!i)return null;const s=JSON.parse(i),r=s?.profile;return r?.sub?(Be.info("OIDC: USER:",{profile:r}),{id:r.sub,email:r.email||"",first_name:r.given_name,last_name:r.family_name}):null}catch(e){return Be.error("OIDC: getUserData - FAILED:",e),null}}async isAuthenticated(){const e=await this.getUser();return null!==e&&!e.expired}async signinRedirect(e){const t=this.ensureInitialized();await t.signinRedirect({state:e?{data:e}:void 0,prompt:"login"})}async signinCallback(){const e=this.ensureInitialized(),t=await e.signinCallback();if(!t)throw Be.error("OIDC: signinCallback - FAILED: no user returned"),new Error("Signin callback failed: no user returned");return t}async signinSilent(e){return this.ensureInitialized(),"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request("oidc-token-refresh",async()=>{const t=await this.getUser();return t&&this.isTokenFresh(t,e)?t:this.doSigninSilent()}):(Be.warn("OIDC: signinSilent - navigator.locks not available, proceeding without lock"),this.doSigninSilent())}isTokenFresh(e,t){if(!e.expires_at)return!1;const i=t??ze.getAccessTokenFreshnessThresholdInSeconds(),s=Math.floor(Date.now()/1e3);return e.expires_at-s>i}async doSigninSilent(){const e=this.ensureInitialized();try{return await e.signinSilent()}catch(e){throw Be.error("OIDC: doSigninSilent - FAILED:",e),e}}proactiveRefreshWithRetry(e=1){if("undefined"!=typeof document&&"hidden"===document.visibilityState){Be.info("OIDC: tab is hidden, deferring proactive refresh until visible");const t=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",t),this.proactiveRefreshWithRetry(e))};return void document.addEventListener("visibilitychange",t)}this.signinSilent(ze.getAccessTokenExpiringNotificationTimeInSeconds()).then(()=>{this.initAccessTokenExpiringTimer()}).catch(t=>{if(Be.error(`OIDC: proactive refresh failed (attempt ${e}/2):`,t),e<2){const t=setTimeout(()=>{this.retryTimers.delete(t),this.proactiveRefreshWithRetry(e+1)},3e3);this.retryTimers.add(t)}else Be.error("OIDC: proactive refresh exhausted all retries")})}async removeUser(){const e=this.ensureInitialized();this.accessTokenExpiringTimer?.cancel(),this.retryTimers.forEach(clearTimeout),this.retryTimers.clear(),await e.removeUser()}onUserLoaded(e){this.ensureInitialized().events.addUserLoaded(e)}offUserLoaded(e){this.ensureInitialized().events.removeUserLoaded(e)}onUserUnloaded(e){this.ensureInitialized().events.addUserUnloaded(e)}offUserUnloaded(e){this.ensureInitialized().events.removeUserUnloaded(e)}onSilentRenewError(e){this.ensureInitialized().events.addSilentRenewError(e)}offSilentRenewError(e){this.ensureInitialized().events.removeSilentRenewError(e)}onAccessTokenExpiring(e){this.ensureInitialized().events.addAccessTokenExpiring(e)}offAccessTokenExpiring(e){this.ensureInitialized().events.removeAccessTokenExpiring(e)}onAccessTokenExpired(e){this.ensureInitialized().events.addAccessTokenExpired(e)}offAccessTokenExpired(e){this.ensureInitialized().events.removeAccessTokenExpired(e)}getLogoutUrl(e,t){const i=new URL(function(e){return`${ze.getAuthOrigin()}${e.logoutPath}`}(e));return t&&i.searchParams.set("redirect_to",t),i.toString()}getWindowOriginParam(){const e=new URL(window.location.href).searchParams.get("origin");if(!e)throw new Error("iframe origin param is required");return e}async getTopUrl(){return(await Fe({type:Ce})).topUrl}async isOAuthFlowPending(){try{return(await Fe({type:Ue})).isPending}catch(e){return Be.warn("OIDC: isOAuthFlowPending() - failed to check, assuming not pending:",e),!1}}async triggerLoginFlowViaParent({loginPath:e,windowPath:t}){Be.info("OIDC: triggerLoginFlowViaParent() - starting");const i=await this.getTopUrl(),s=new URL(i).origin,r=`${s}${t}`,n=new URL(`${window.location.origin}${e}`);n.searchParams.set(Le,s),n.searchParams.set("oauth2_top_wp_url",r),Be.info("OIDC: triggerLoginFlowViaParent() - redirecting parent to:",n.toString()),await Fe({type:xe,payload:{url:n.toString()}})}async handleLoginFlowComplete(e,t){if(!t)throw new Error("oauthUserState is required");const i=this.getWindowOriginParam(),s=t.state,r=s?.data?.[Le];if(i!==r)throw Be.error("OIDC: handleLoginFlowComplete - origin mismatch:",i,"!==",r),new Error("Invalid origin in OAuth state");try{const e=new he(t);await this.storeUser(e),this.initAccessTokenExpiringTimer(),window.dispatchEvent(new CustomEvent("oidc-auth-completed"))}catch(t){Be.error("OIDC: handleLoginFlowComplete - FAILED to store user:",t),await this.triggerLoginFlowViaParent(e)}}async triggerLogoutViaParent(e,t=!0){const i=await this.getTopUrl(),s=new URL(i).origin,r=t?`${s}${e.windowPath}`:s;await this.removeUser();const n=this.getLogoutUrl(e,r);await Fe({type:xe,payload:{url:n}})}async cleanOAuthParamsFromUrl(){try{const e=await this.getTopUrl(),t=new URL(e);t.searchParams.delete("oauth_code"),t.searchParams.delete("oauth_state"),t.searchParams.delete("start-oauth"),t.searchParams.delete(Ne),t.searchParams.delete(De),await Fe({type:Oe,payload:{url:t.toString()}})}catch(e){Be.warn("Failed to clean OAuth params from URL:",e)}}setupLoginFlowMessageListener(e){let t=!1;const i=i=>{if(i.data?.type!==Pe)return;if(i.origin!==je())return void Be.error("OIDC: origin mismatch - expected:",je(),"received:",i.origin);if(t)return void Be.debug("OIDC: LOGIN_FLOW_COMPLETE already processed, ignoring duplicate");const s=i.data.payload;s?.oauthState?(t=!0,this.handleLoginFlowComplete(e,s.oauthState).catch(e=>{Be.error("OIDC: Failed to handle login flow complete:",e),t=!1})):Be.warn("OIDC: LOGIN_FLOW_COMPLETE but no oauthState in payload")};return window.addEventListener("message",i),()=>{window.removeEventListener("message",i)}}async getTokenExpirationInfo(){const e=await this.getUser();if(!e||!e.expires_at)return{expiresAt:null,expiresInSeconds:null,isExpired:!0};const t=new Date(1e3*e.expires_at),i=Date.now(),s=Math.floor((1e3*e.expires_at-i)/1e3);return{expiresAt:t,expiresInSeconds:s,isExpired:s<=0}}async forceTokenRefresh(){return Be.info("OIDC: forceTokenRefresh() - manually triggering token refresh"),this.signinSilent()}}const Ve=Qe.getInstance();"undefined"!=typeof window&&(window.oidcAuthClient=Ve);const Xe=$e("oidc-auth:oidc-auth-redirect");function Ye(e,t){e.postMessage({status:"success",payload:t})}function Ze(e,t){e.postMessage({status:"error",payload:t})}function et({targets:e,onSuccess:t,attempt:i=1}){const s=new URLSearchParams(window.location.search);if(!s.get(Ne))return void Xe.warn("OIDC: No login_success param found, skipping");const r=s.get(De);if(r){if(!e.window?.contentWindow||!e.windowURL)return Xe.warn("Cannot forward OIDC state: iframe not available"),void(i<5?setTimeout(()=>{et({targets:e,onSuccess:t,attempt:i+1})},500):Xe.error("OIDC: Failed to forward login flow after",5,"attempts - iframe never became available"));try{const i=JSON.parse(r),s=i.state?.data?.[Le];if(s&&s!==window.location.origin)return void Xe.error("Origin mismatch in OIDC state:",s,"vs",window.location.origin);!function(e,t){const i=t.window?.contentWindow,s=t.windowURL?.origin;i&&s?i.postMessage({type:Pe,payload:e},s):Xe.warn("Cannot send OIDC state: window or origin not available")}({oauthState:i},e);const n=new URL(window.location.href);n.searchParams.delete(Ne),n.searchParams.delete(De),history.replaceState({},"",n.toString()),t?.()}catch(e){Xe.error("Failed to parse or forward OIDC state:",e)}}else Xe.warn("OIDC login complete but no state found in URL")}const tt=g("oauth");function it(){try{localStorage.setItem("angie_sidebar_state","open")}catch(e){tt.warn("localStorage not available")}setTimeout(()=>{window.toggleAngieSidebar(!0)},500)}const st=(e,t)=>{const i=document.getElementById("angie-sidebar-container");i&&i.setAttribute("aria-hidden",t?"false":"true"),t?e.removeAttribute("tabindex"):e.setAttribute("tabindex","-1")},rt=(e,t)=>{e.postMessage({status:"success",payload:t})},nt=()=>new Promise(e=>{"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e(null)}),ot=g("sdk");var at;(at||(at={})).POST_MESSAGE="postMessage";const ct=g("iframe-utils");let dt=null;const lt=()=>(dt&&document.contains(dt)||(dt=document.querySelector('iframe[src*="angie/"]')),dt),gt=(e,t)=>{ct.log("postMessageToAngieIframe",e,t);const i=lt();if(!i?.contentWindow)return!1;const s=t||(()=>{const e=lt();if(!e)return null;try{return new URL(e.src).origin}catch(e){return ct.error("Error parsing iframe URL:",e),null}})();return s?(i.contentWindow.postMessage(e,s),!0):(ct.error("Could not determine target origin for Angie iframe"),!1)},ht=g("sidebar");let ut=!1;const pt="open",_t="closed";function wt(){if("undefined"==typeof window)return 370;try{const e=window.localStorage.getItem("angie_sidebar_width");if(e){const t=parseInt(e,10);if(t>=350&&t<=590)return t}}catch(e){ht.warn("localStorage not available")}return 370}function mt(){return"undefined"==typeof window?null:localStorage.getItem("angie_sidebar_state")}function ft(e){try{localStorage.setItem("angie_sidebar_state",e)}catch(e){ht.warn("localStorage not available")}}function yt(e){try{localStorage.setItem("angie_sidebar_width",e.toString())}catch(e){ht.warn("localStorage not available")}}function St(e){document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`)}function vt(){!function(){if("undefined"==typeof window)return!1;const e=new URLSearchParams(window.location.search);return e.has(Ne)||e.has(De)||e.has(Le)}()?bt(mt()||pt):function(){bt(_t);try{localStorage.setItem("angie_sidebar_state",_t)}catch(e){ht.warn("localStorage not available")}}()}function bt(e){"undefined"!=typeof window&&window.toggleAngieSidebar&&window.toggleAngieSidebar(e===pt,!0)}function Et(){const e=document.getElementById("angie-sidebar-container");if(!e)return;let t=!1,i=0,s=0;e.addEventListener("mousedown",r=>{const n=e.getBoundingClientRect();("rtl"===document.documentElement.dir?r.clientX<=n.left+4:r.clientX>=n.right-4)&&(t=!0,i=r.clientX,s=n.width,e.classList.add("angie-resizing"),document.body.style.cursor="ew-resize",document.body.style.userSelect="none",r.preventDefault(),r.stopPropagation())}),document.addEventListener("mousemove",e=>{if(!t)return;let r;r="rtl"===document.documentElement.dir?i-e.clientX:e.clientX-i,St(Math.max(350,Math.min(590,s+r))),e.preventDefault(),e.stopPropagation()}),document.addEventListener("mouseup",i=>{if(t){t=!1,e.classList.remove("angie-resizing"),document.body.style.cursor="",document.body.style.userSelect="";const r=parseInt(getComputedStyle(document.documentElement).getPropertyValue("--angie-sidebar-width"),10);yt(r),gt({type:w.ANGIE_SIDEBAR_RESIZED,payload:{initialWidth:s,width:r}}),i.preventDefault(),i.stopPropagation()}}),St(wt())}function kt(e){!function(){if("undefined"==typeof document||ut)return;const e="angie-sidebar-styles";if(document.getElementById(e))return void(ut=!0);const t=document.createElement("style");t.id=e,t.textContent="/* Angie Sidebar - CSS Variables */\n:root {\n --angie-sidebar-z-index: 1200; /* below MUI popups, elementor popups and media library modal */\n --angie-sidebar-width: 330px;\n --angie-sidebar-transition: margin 0.3s ease-in-out, transform 0.3s ease-in-out;\n /* Direction-aware transform values for sidebar positioning */\n --angie-sidebar-hide-transform: translateX(-100%); /* LTR: hide to the left */\n --angie-sidebar-show-transform: translateX(0);\n}\n\n/* RTL-specific transform values */\n[dir=\"rtl\"] {\n --angie-sidebar-hide-transform: translateX(100%); /* RTL: hide to the right */\n}\n\n/* Respect user's motion preferences */\n@media (prefers-reduced-motion: reduce) {\n :root {\n --angie-sidebar-transition: none;\n }\n}\n\n/* Apply transitions only when user is actively toggling */\nbody.angie-sidebar-transitioning {\n transition: var(--angie-sidebar-transition) !important;\n}\n\nbody.angie-sidebar-transitioning #angie-sidebar-container {\n transition: var(--angie-sidebar-transition) !important;\n}\n\n/* Layout (default) - Push content */\n@media (min-width: 768px) {\n body.angie-sidebar-active {\n padding-inline-start: var(--angie-sidebar-width) !important;\n }\n\n #angie-sidebar-container {\n position: fixed;\n top: 0;\n inset-inline-start: 0;\n width: var(--angie-sidebar-width);\n height: 100vh;\n z-index: var(--angie-sidebar-z-index) !important; /* below elementor popups and media library modal */\n background: #FCFCFC;\n transform: var(--angie-sidebar-hide-transform);\n outline: none;\n overflow: hidden;\n /* No default transition - only when transitioning */\n }\n\n /* Resize handle */\n #angie-sidebar-container::after {\n content: '';\n position: absolute;\n top: 0;\n inset-inline-end: 0;\n width: 4px;\n height: 100%;\n cursor: ew-resize;\n background: transparent;\n z-index: 1000001;\n }\n\n /* Pink border during resize */\n #angie-sidebar-container.angie-resizing {\n border-inline-end-color: #ff69b4 !important;\n border-inline-end-width: 2px !important;\n }\n\n /* Disable iframe pointer events during resize */\n #angie-sidebar-container.angie-resizing iframe#angie-iframe {\n pointer-events: none !important;\n }\n}\n\n/* Active states */\nbody.angie-sidebar-active #angie-sidebar-container {\n transform: var(--angie-sidebar-show-transform);\n}\n\n/* Studio mode - sidebar takes full width */\n@media (min-width: 768px) {\n html.angie-studio-active body.angie-sidebar-active #angie-sidebar-container {\n width: 100%;\n }\n}\n\n/* High contrast mode support */\n@media (prefers-contrast: high) {\n #angie-sidebar-container {\n border-color: #000;\n box-shadow: none;\n }\n}\n\n/* Screen reader only class */\n.angie-sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n/* Plugin conflict resolution */\nbody.angie-sidebar-active {\n /* Reset common conflicting styles */\n box-sizing: border-box !important;\n position: relative !important;\n}\n\n#angie-sidebar-toggle {\n z-index: 99999 !important;\n}\n";const i=document.head||document.getElementsByTagName("head")[0];i.insertBefore(t,i.firstChild),ut=!0}(),"undefined"!=typeof window&&(window.toggleAngieSidebar=function(e){return function(t,i){const s=document.body,r=document.getElementById("angie-sidebar-container");if(!r)return void ht.warn("Required elements not found!");const n=s.classList.contains("angie-sidebar-active"),o=void 0!==t?t:!n;i||(s.classList.add("angie-sidebar-transitioning"),setTimeout(function(){s.classList.remove("angie-sidebar-transitioning")},300)),o?s.classList.add("angie-sidebar-active"):s.classList.remove("angie-sidebar-active"),o&&setTimeout(function(){gt({type:"focusInput"})},i?0:300),e&&e(o,r,i),ft(o?pt:_t);const a=new CustomEvent("angieSidebarToggle",{detail:{isOpen:o,sidebar:r,skipTransition:i}});document.dispatchEvent(a),gt({type:w.ANGIE_SIDEBAR_TOGGLED,payload:{state:o?"opened":"closed"}})}}(e),window.addEventListener("message",function(e){if(e.data&&"toggleAngieSidebar"===e.data.type){const{force:t,skipTransition:i}=e.data.payload||{};window.toggleAngieSidebar&&window.toggleAngieSidebar(t,i)}}))}const It=g("iframe"),Tt=async()=>{if(E.iframe?.contentWindow&&E.iframeUrlObject)try{It.log("Disabling navigation prevention in Angie iframe"),E.iframe.contentWindow.postMessage({type:w.ANGIE_DISABLE_NAVIGATION_PREVENTION},E.iframeUrlObject.origin),await new Promise(e=>setTimeout(e,100))}catch(e){throw It.error("Failed to disable navigation prevention:",e),e}else It.warn("Cannot disable navigation prevention: iframe or origin not available")},Rt=async e=>{if(window.screen.availWidth<=768)return void It.log("Mobile detected, skipping iframe injection");let t=document.getElementById("angie-sidebar-container");if(!t){const e=performance.now();if(It.log("⏱️ Waiting for sidebar container..."),await new Promise(e=>{let i=0;const s=setInterval(()=>{t=document.getElementById("angie-sidebar-container"),i++,(t||i>20)&&(clearInterval(s),t&&e())},100);setTimeout(()=>{if(clearInterval(s),t)return void e();const i=new MutationObserver(()=>{t=document.getElementById("angie-sidebar-container"),t&&(i.disconnect(),e())});i.observe(document.body,{childList:!0,subtree:!0}),setTimeout(()=>{i.disconnect(),e()},8e3)},2e3)}),It.log(`⏱️ Sidebar container detection took: ${(performance.now()-e).toFixed(2)}ms`),!t)return void It.error("Sidebar container not found")}const{iframe:i,iframeUrlObject:s}=await(async e=>{const t=e.origin,i=new URL(e.path,t),s=i.pathname.slice(1).replace(/\//,"--")+"-"+Math.random().toString(36).substring(7);return new Promise(r=>{const n=new URL(t);n.pathname=i.pathname;const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";if(n.searchParams.append("colorScheme",e.uiTheme||o||"light"),n.searchParams.append("sdkVersion",e.sdkVersion),n.searchParams.append("instanceId",s),n.searchParams.append("origin",window.location.origin),e.isRTL&&n.searchParams.append("isRTL",e.isRTL?"true":"false"),"localhost"===window.location.hostname&&window.location.search.includes("debug_error")){const e=new URLSearchParams(window.location.search).get("debug_error");e&&n.searchParams.append("debug_error",e)}i.searchParams.forEach((e,t)=>{n.searchParams.set(t,e)}),n.searchParams.set("ver",(new Date).getTime().toString());const a=e.parent||document,c=a.createElement("iframe"),d={"background-color":"transparent","color-scheme":"normal",...e.css};window.addEventListener("message",async e=>{if(e.origin===n.origin)switch(e.data.type){case f.ANGIE_READY:r({iframe:c,iframeUrlObject:n});break;case f.ANGIE_LOADED:c.contentWindow?.postMessage({type:f.HOST_READY,instanceId:s},n.origin)}}),c.setAttribute("src",n.href),c.id="angie-iframe",c.setAttribute("frameborder","0"),c.setAttribute("scrolling","no"),c.setAttribute("style",Object.entries(d).map(([e,t])=>`${e}: ${t}`).join("; ")),c.setAttribute("allow","clipboard-write; clipboard-read"),e.insertCallback?e.insertCallback(c):a.body.appendChild(c)})})({origin:e.origin||"https://angie.elementor.com",path:"angie/wp-admin",insertCallback:e=>{It.log("Injecting Angie iframe into sidebar container"),e.setAttribute("title","Angie AI Assistant"),e.setAttribute("role","application"),e.setAttribute("aria-label","Angie AI Assistant Interface");const i=document.getElementById("angie-sidebar-loading");i&&(i.textContent=""),t?.appendChild(e),st(e,!0),e.addEventListener("load",()=>{e.focus()})},css:{width:"100%",height:"100%",border:"none",outline:"none"},uiTheme:e.uiTheme,isRTL:e.isRTL,sdkVersion:"1.2.0"});E.iframe=i,E.iframeUrlObject=s,window.addEventListener("message",e=>{if(e.origin===E.iframeUrlObject?.origin)switch(e.data.type){case m.SET:window.localStorage.setItem(e.data.key,e.data.value);break;case m.GET:{const t=e.ports[0],i=window.localStorage.getItem(e.data.key);t.postMessage({value:i});break}}}),(e=>{window.addEventListener("message",async t=>{const i=t.origin===window.location.origin,s=t.origin===e.iframeUrlObject?.origin;if(i||s)switch(t?.data?.type){case w.SDK_ANGIE_ALL_SERVERS_REGISTERED:break;case w.SDK_ANGIE_READY_PING:{const e=t.ports[0];ot.log("Angie is ready",t),rt(e,{message:"Angie is ready"});break}case w.SDK_REQUEST_CLIENT_CREATION:{const i=t.data.payload;try{const s=t.ports[0],r=new MessageChannel;r.port1.onmessage=e=>{s.postMessage({success:!0,data:e.data})};const n={type:w.SDK_REQUEST_CLIENT_CREATION,payload:{success:!0,...i,clientId:`dynamic-client-${i.serverName}-${i.serverVersion}-${Date.now()}`,requestId:t.data.payload.requestId},timestamp:Date.now()};if(!e.iframe)throw new Error("Iframe not found");e.iframe.contentWindow?.postMessage(n,e.iframeUrlObject?.origin||"",[r.port2])}catch(e){ot.error(`Failed to create client for SDK server "${i.serverName}":`,e)}break}case w.SDK_TRIGGER_ANGIE:ot.log("SDK Trigger Angie received",t.data);try{const{requestId:i,prompt:s,context:r}=t.data.payload;if(!e.iframe)throw new Error("Iframe not found");e.iframe.contentWindow?.postMessage({type:w.SDK_TRIGGER_ANGIE,payload:{requestId:i,prompt:s,context:r}},e.iframeUrlObject?.origin||""),window.postMessage({type:w.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!0,requestId:i,response:"Angie triggered successfully"}},window.location.origin)}catch(e){ot.error("Failed to trigger Angie:",e),window.postMessage({type:w.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!1,requestId:t.data.payload?.requestId,error:e instanceof Error?e.message:"Unknown error"}},window.location.origin)}}})})(E),function({trustedOrigin:e,onOAuthParamsCleared:t}){window.addEventListener("message",i=>{if(i.origin!==e)return;const s=i.ports?.[0];switch(i.data.type){case Ce:if(!s)return;Ye(s,{topUrl:window.location.href});break;case xe:window.location.href=i.data.payload.url;break;case Oe:{if(!s)return;const e=i.data.payload.url;if(!history?.replaceState)return void Ze(s,{message:"URL update not supported in this browser"});try{const i=window.location.href;history.replaceState({},"",e),function(e,t){const i=new URL(e).searchParams,s=new URL(t).searchParams,r=[Ne,De,Le];return r.some(e=>i.has(e))&&!r.some(e=>s.has(e))}(i,e)&&t?.(),Ye(s,{message:"URL updated successfully"})}catch(e){Ze(s,{message:"URL update failed: "+(e instanceof Error?e.message:"Unknown error")})}break}case Ue:if(!s)return;Ye(s,{isPending:"true"===new URLSearchParams(window.location.search).get(Ne)})}})}({trustedOrigin:E.iframeUrlObject?.origin??"",onOAuthParamsCleared:it}),(()=>{const e={window:E.iframe,windowURL:E.iframeUrlObject};window.addEventListener("load",()=>{tt.log("OIDC: Window load event fired, forwarding OIDC state if present"),et({targets:e,onSuccess:it})}),et({targets:e,onSuccess:it})})(),window.addEventListener("message",async t=>{if([window.location.origin,e.origin||"https://angie.elementor.com"].includes(t.origin))if(t?.data?.type===w.ANGIE_CHAT_TOGGLE)E.open=t.data.open,E.iframe&&st(E.iframe,E.open);else if(t?.data?.type===w.ANGIE_STUDIO_TOGGLE){const e=t.data.isStudioOpen;if(!E.iframe)return;if(e)document.documentElement.classList.add("angie-studio-active");else{const e=wt();document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`),document.documentElement.classList.remove("angie-studio-active")}}else if(t?.data?.type===w.ANGIE_NAVIGATE_TO_URL){const{url:e="",confirmed:i=!1}=t.data.payload||{};if(!i)return void It.log("Navigation requires user confirmation");if(!((e,t=[])=>{const i=0===t.length&&"undefined"!=typeof window?[window.location.origin]:t;if(!e.startsWith("http"))return!1;try{const t=new URL(e);return i.includes(t.origin)}catch{return!1}})(e))return void It.error("Navigation blocked: Invalid or unsafe URL",{url:e});await Tt(),window.location.assign(e)}else if(t?.data?.type===w.ANGIE_PAGE_RELOAD){const{confirmed:e=!1}=t.data.payload||{};if(!e)return void It.log("Page reload requires user confirmation");It.log("Page reload confirmed - disabling navigation prevention and reloading"),await Tt(),setTimeout(()=>{window.location.reload()},50)}else t?.data?.type===f.RESET_HASH&&(window.location.hash="",rt(t.ports[0],{message:"Hash reset successfully"}))})},At=g("registration-queue");class Pt{queue=[];isProcessing=!1;add(e){const t={id:this.generateId(e),config:e,timestamp:Date.now(),status:"pending"};return this.queue.push(t),At.log(`Added server "${e.name}" to queue`),t}getAll(){return[...this.queue]}getPending(){return this.queue.filter(e=>"pending"===e.status)}updateStatus(e,t,i){const s=this.queue.find(t=>t.id===e);s&&(s.status=t,i?s.error=i:"pending"!==t&&"registered"!==t||delete s.error,At.log(`Updated server ${e} status to ${t}`))}async processQueue(e){if(this.isProcessing)return void At.log("Already processing queue");this.isProcessing=!0;const t=this.getPending();At.log(`Processing ${t.length} pending registrations`);try{for(const i of t)try{await e(i),this.updateStatus(i.id,"registered")}catch(e){const t=e instanceof Error?e.message:String(e);this.updateStatus(i.id,"failed",t),At.error(`Failed to process registration ${i.id}:`,t)}}finally{this.isProcessing=!1}}clear(){this.queue=[],At.log("Cleared all registrations")}resetAllToPending(){if(this.isProcessing)return At.log("Cannot reset to pending - processing in progress"),!1;const e=this.queue.filter(e=>"registered"===e.status).length,t=this.queue.filter(e=>"failed"===e.status).length;return this.queue.forEach(e=>{"pending"!==e.status&&(e.status="pending",delete e.error)}),At.log(`Reset ${e+t} registrations to pending`),!0}remove(e){const t=this.queue.findIndex(t=>t.id===e);return-1!==t&&(this.queue.splice(t,1),At.log(`Removed registration ${e}`),!0)}generateId(e){return`reg_${e.name}_${e.version}_${Date.now()}`}}class Ct{angieDetector;clientManager;logger;registrationQueue;isInitialized=!1;instanceId;constructor(){this.instanceId=Math.random().toString(36).substring(2,8),this.logger=g({instanceId:this.instanceId}),this.logger.log("Constructor called - initializing SDK"),this.angieDetector=new S,this.registrationQueue=new Pt,this.clientManager=new b,this.logger.log("Setting up event handlers"),this.setupAngieReadyHandler(),this.setupServerInitHandler(),this.setupReRegistrationHandler(),this.logger.log("SDK initialization complete")}async loadSidebar(e){kt(),await Rt({origin:e?.origin||"https://angie.elementor.com",uiTheme:e?.uiTheme||"light",isRTL:e?.isRTL||!1,...e}),this.setupPromptHashDetection()}setupReRegistrationHandler(){window.addEventListener("message",e=>{if(e.data?.type===w.SDK_ANGIE_REFRESH_PING)if(this.logger.log("Angie refresh ping received"),this.registrationQueue.resetAllToPending()){const e=this.registrationQueue.getPending().length;this.logger.log(`Successfully reset ${e} registrations, processing queue`),this.handleAngieReady()}else this.logger.log("Skipping queue reset - processing already in progress")})}setupAngieReadyHandler(){this.angieDetector.waitForReady().then(e=>{e.isReady?this.handleAngieReady():this.logger.warn("Angie not detected - servers will remain queued")}).catch(e=>{this.logger.error("Error waiting for Angie:",e)})}async handleAngieReady(){this.logger.log("Angie is ready, processing queued registrations");try{await this.registrationQueue.processQueue(async e=>{this.logger.log(`processQueue callback called for "${e.config.name}"`),await this.processRegistration(e)}),this.isInitialized=!0,this.logger.log("Initialization complete")}catch(e){this.logger.error("Error processing registration queue:",e)}}async processRegistration(e){this.logger.log(`Processing registration for server "${e.config.name}" (ID: ${e.id})`);try{this.logger.log(`Calling clientManager.requestClientCreation for "${e.config.name}"`);const t={...e,instanceId:this.instanceId};await this.clientManager.requestClientCreation(t),this.logger.log(`Successfully registered server "${e.config.name}"`)}catch(t){throw this.logger.error(`Failed to register server "${e.config.name}":`,t),t}}registerLocalServer(e){return e.type=_.LOCAL,e.transport=u.POST_MESSAGE,this.registerServer(e)}registerRemoteServer(e){return e.type=_.REMOTE,this.registerServer(e)}isLocalServerConfig(e){return e.type===_.LOCAL||!e.type&&"server"in e}isRemoteServerConfig(e){return e.type===_.REMOTE&&"url"in e}async registerServer(e){if(!e.type)return this.logger.warn("For a local server, please use registerLocalServer instead of registerServer"),void this.registerLocalServer(e);if(this.logger.log(`registerServer called for "${e.name}"`),!e.name)throw new Error("Server name is required");if(!e.description)throw new Error("Server description is required");if(this.isLocalServerConfig(e)&&!e.server)throw new Error("Server instance is required for local servers");this.logger.log(`Registering server "${e.name}"`);const t=this.registrationQueue.add(e);if(this.logger.log(`Added registration to queue: ${t.id}`),this.angieDetector.isReady())try{await this.processRegistration(t),this.registrationQueue.updateStatus(t.id,"registered"),this.logger.log(`Server "${e.name}" registered successfully`)}catch(e){const i=e instanceof Error?e.message:String(e);throw this.registrationQueue.updateStatus(t.id,"failed",i),e}else this.logger.log(`Server "${e.name}" queued until Angie is ready`)}getRegistrations(){return this.registrationQueue.getAll()}getPendingRegistrations(){return this.registrationQueue.getPending()}isAngieReady(){return this.angieDetector.isReady()}isReady(){return this.isInitialized}async waitForReady(){if(!(await this.angieDetector.waitForReady()).isReady)throw new Error("Angie is not available");for(;!this.isInitialized;)await new Promise(e=>setTimeout(e,100))}async triggerAngie(e){if(!this.isAngieReady())throw new Error("Angie is not ready. Please wait for Angie to be available before triggering.");const t=this.generateRequestId(),i=e.options?.timeout||3e4;return new Promise((s,r)=>{const n=setTimeout(()=>{r(new Error("Angie trigger request timed out"))},i),o=e=>{e.data?.type===w.SDK_TRIGGER_ANGIE_RESPONSE&&e.data?.payload?.requestId===t&&(clearTimeout(n),window.removeEventListener("message",o),s(e.data.payload))};window.addEventListener("message",o);const a={type:w.SDK_TRIGGER_ANGIE,payload:{requestId:t,prompt:e.prompt,options:e.options,context:{pageUrl:window.location.href,pageTitle:document.title,...e.context}},timestamp:Date.now()};this.logger.log(`Triggering Angie with prompt (Request ID: ${t})`),window.postMessage(a,window.location.origin)})}destroy(){this.registrationQueue.clear(),this.logger.log("SDK destroyed")}setupServerInitHandler(){window.addEventListener("message",e=>{e.data?.type===w.SDK_REQUEST_INIT_SERVER&&(this.logger.log("Server init request received"),this.handleServerInitRequest(e))})}handleServerInitRequest(e){const{clientId:t,serverId:i,instanceId:s}=e.data.payload||{};if(t&&i)if(this.logger.log(`Server init request received - Request instanceId: ${s}, This instanceId: ${this.instanceId}`),s&&s!==this.instanceId)this.logger.log(`Ignoring server init request for different instance. Request instanceId: ${s}, this instanceId: ${this.instanceId}`);else{this.logger.log(`Handling server init request for clientId: ${t}, serverId: ${i}`);try{const t=this.registrationQueue.getAll().find(e=>e.id===i);if(!t)return void this.logger.error(`No registration found for serverId: ${i}`);if("type"in t.config&&"remote"===t.config.type)return void this.logger.log("Remote server registration detected; skipping local connect");const s=e.ports[0];if(!s)return void this.logger.error("No port provided in server init request");const r=t.config.server;this.migrateInstructionsCompat(r);const n=new v(s);r.connect(n),this.logger.log(`Server "${t.config.name}" initialized successfully`)}catch(e){this.logger.error(`Error initializing server for clientId ${t}:`,e)}}else this.logger.error("Invalid server init request - missing clientId or serverId")}migrateInstructionsCompat(e){try{const t="server"in e&&e.server?e.server:e,i=t._serverInfo,s=t._instructions;i?.instructions&&!s&&(t._instructions=i.instructions,this.logger.log("Migrated instructions from serverInfo to serverOptions (backward compat)"))}catch{}}generateRequestId(){return`${this.instanceId}-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}async handlePromptHash(){const e=window.location.hash;if(e.startsWith("#angie-prompt="))try{const t=e.replace("#angie-prompt=",""),i=decodeURIComponent(t);if(!i)return void this.logger.warn("Empty prompt detected in hash");this.logger.log("Detected prompt in hash:",i),await this.waitForReady();const s=await this.triggerAngie({prompt:i,context:{source:"hash-parameter",pageUrl:window.location.href,timestamp:(new Date).toISOString()}});this.logger.log("Triggered successfully from hash:",s),window.location.hash=""}catch(e){this.logger.error("Failed to trigger from hash:",e)}}setupPromptHashDetection(){this.handlePromptHash(),window.addEventListener("hashchange",()=>this.handlePromptHash())}}const xt=g("navigation"),Ot=(e,t)=>{if(lt()){t.isOpen&&window.toggleAngieSidebar&&window.toggleAngieSidebar(!0);const i=gt({type:"angie-route-navigation",path:e,payload:t});return i||xt.error("Failed to post navigation message to Angie iframe"),i}return xt.error("Angie iframe not found"),!1},Ut="angie_return_url",Lt=g("referrer-redirect");function Nt(e){try{return new URL(e,window.location.origin).origin===window.location.origin}catch{return!1}}function Dt(e,t){if(!Nt(e))return Lt.warn("Invalid redirect URL rejected:",e),!1;try{const i={url:e};return t&&(i.prompt=t),localStorage.setItem(Ut,JSON.stringify(i)),!0}catch(e){return Lt.warn("localStorage not available"),!1}}function qt(){try{const e=localStorage.getItem(Ut);if(!e)return null;let t;try{t=JSON.parse(e)}catch{return Lt.warn("Stored redirect data is not valid JSON, returning null"),null}return t.url&&"string"==typeof t.url?Nt(t.url)?t:(Lt.warn("Stored redirect URL is invalid, returning null:",t.url),null):(Lt.warn("Stored redirect data missing url field, returning null"),null)}catch(e){return Lt.warn("localStorage not available"),null}}function Mt(){try{localStorage.removeItem(Ut)}catch(e){Lt.warn("localStorage not available")}}export{pt as ANGIE_SIDEBAR_STATE_OPEN,S as AngieDetector,u as AngieLocalServerTransport,h as AngieMCPTransport,Ct as AngieMcpSdk,p as AngieRemoteServerTransport,_ as AngieServerType,v as BrowserContextTransport,b as ClientManager,f as HostEventType,m as HostLocalStorageEventType,w as MessageEventType,Pt as RegistrationQueue,St as applyWidth,Mt as clearReferrerRedirect,Tt as disableNavigationPrevention,lt as getAngieIframe,mt as getAngieSidebarSavedState,qt as getReferrerRedirect,kt as initAngieSidebar,Et as initializeResize,vt as loadState,wt as loadWidth,Ot as navigateAngieIframe,ft as saveState,yt as saveWidth,Dt as setReferrerRedirect,st as toggleAngieSidebar,nt as waitForDocumentReady};
|
|
1
|
+
import{JSONRPCMessageSchema as e}from"@modelcontextprotocol/sdk/types.js";const t={none:0,error:1,warn:2,info:3,debug:4},i={error:"error",warn:"warn",info:"info",log:"info",debug:"debug"},s=(e,i)=>t[e]<=t[i],r=e=>"string"==typeof e?e:JSON.stringify(e),n=(e,t)=>`${r(e)} > ${r(t)}`,o=(e,t)=>{let i=`[${r(e)}]`;return typeof window<"u"?{text:`%c${i}`,style:`color: ${t.color||"#00bcd4"}; font-weight: bold;`}:{text:i}},a=(e,t,r,n)=>(...a)=>{if(!s(i[e],n()))return;if(!t)return void console[e](...a);let{text:c,style:d}=o(t,r);d?console[e](c,d,...a):console[e](c,...a)},c=(e,t)=>{let i=t.logLevel??"debug",s=()=>i;return{log:a("log",e,t,s),info:a("info",e,t,s),warn:a("warn",e,t,s),error:a("error",e,t,s),debug:a("debug",e,t,s),setLogLevel:e=>{i=e},extend:s=>c(e?n(e,s):s,{...t,logLevel:i})}},d=(e,t)=>c(e,{color:"#00bcd4",logLevel:"debug",...t}),l=d("angie-sdk",{color:"#00BCD4",logLevel:"error"}),g=e=>l.extend(e);var h,u,p,_,w,m,f;!function(e){e.POST_MESSAGE="postMessage"}(h||(h={})),function(e){e.POST_MESSAGE="postMessage"}(u||(u={})),function(e){e.STREAMABLE_HTTP="streamableHttp",e.SSE="sse"}(p||(p={})),function(e){e.LOCAL="local",e.REMOTE="remote"}(_||(_={})),function(e){e.SDK_ANGIE_READY_PING="sdk-angie-ready-ping",e.SDK_ANGIE_REFRESH_PING="sdk-angie-refresh-ping",e.SDK_ANGIE_ALL_SERVERS_REGISTERED="sdk-angie-all-servers-registered",e.SDK_REQUEST_CLIENT_CREATION="sdk-request-client-creation",e.SDK_REQUEST_INIT_SERVER="sdk-request-init-server",e.SDK_TRIGGER_ANGIE="sdk-trigger-angie",e.SDK_TRIGGER_ANGIE_RESPONSE="sdk-trigger-angie-response",e.ANGIE_SIDEBAR_RESIZED="angie-sidebar-resized",e.ANGIE_SIDEBAR_TOGGLED="angie-sidebar-toggled",e.ANGIE_CHAT_TOGGLE="angie-chat-toggle",e.ANGIE_STUDIO_TOGGLE="angie-studio-toggle",e.ANGIE_NAVIGATE_TO_URL="angie/navigate-to-url",e.ANGIE_PAGE_RELOAD="angie/page-reload",e.ANGIE_DISABLE_NAVIGATION_PREVENTION="angie/disable-navigation-prevention",e.ANGIE_NAVIGATE_AFTER_RESPONSE="angie/navigate-after-response"}(w||(w={})),function(e){e.SET="ANGIE_SET_LOCALSTORAGE",e.GET="ANGIE_GET_LOCALSTORAGE"}(m||(m={})),function(e){e.RESET_HASH="reset-hash",e.HOST_READY="host/ready",e.ANGIE_LOADED="angie/loaded",e.ANGIE_READY="angie/ready"}(f||(f={}));const y=g("angie-detector");class S{isAngieReady=!1;readyPromise;readyResolve;constructor(){if(this.readyPromise=new Promise(e=>{this.readyResolve=e}),"undefined"==typeof window)return;let e=0;const t=()=>{if(this.isAngieReady||e>=500)return void(!this.isAngieReady&&e>=500&&this.handleDetectionTimeout());const i=new MessageChannel;i.port1.onmessage=e=>{this.handleAngieReady(e.data),i.port1.close(),i.port2.close()};const s={type:w.SDK_ANGIE_READY_PING,timestamp:Date.now()};window.postMessage(s,window.location.origin,[i.port2]),e++,setTimeout(t,500)};t()}handleAngieReady(e){this.isAngieReady=!0;const t={isReady:!0,version:e.version,capabilities:e.capabilities};this.readyResolve&&this.readyResolve(t)}handleDetectionTimeout(){this.readyResolve&&this.readyResolve({isReady:!1}),y.warn("Detection timeout - Angie may not be available")}isReady(){return this.isAngieReady}async waitForReady(){return this.readyPromise}}class v{sessionId;onmessage;onerror;onclose;_port;_started=!1;_closed=!1;constructor(t){if(!t)throw new Error("MessagePort is required");this._port=t,this._port.onmessage=t=>{try{const i=e.parse(t.data);this.onmessage?.(i)}catch(e){const t=new Error(`Failed to parse message: ${e}`);this.onerror?.(t)}},this._port.onmessageerror=e=>{const t=new Error(`MessagePort error: ${JSON.stringify(e)}`);this.onerror?.(t)}}async start(){if(this._started)throw new Error("BrowserContextTransport already started! If using Client or Server class, note that connect() calls start() automatically.");if(this._closed)throw new Error("Cannot start a closed BrowserContextTransport");this._started=!0,this._port.start()}async send(e){if(this._closed)throw new Error("Cannot send on a closed BrowserContextTransport");return new Promise((t,i)=>{try{this._port.postMessage(e),t()}catch(e){const t=e instanceof Error?e:new Error(String(e));this.onerror?.(t),i(t)}})}async close(){this._closed||(this._closed=!0,this._port.close(),this.onclose?.())}}class b{async requestClientCreation(e){const{config:t}=e,i={serverId:e.id,serverName:t.name,serverTitle:t.title,serverVersion:t.version,description:t.description,transport:t.transport||u.POST_MESSAGE,capabilities:t.capabilities,instanceId:e.instanceId};return"type"in t&&"remote"===t.type&&(i.remote={url:t.url}),new Promise((e,t)=>{const s=new MessageChannel,r=setTimeout(()=>{t(new Error("Client creation request timed out after 15000ms"))},15e3);s.port1.onmessage=t=>{clearTimeout(r),e(t.data)};const n={type:w.SDK_REQUEST_CLIENT_CREATION,payload:i,timestamp:Date.now()};window.postMessage(n,window.location.origin,[s.port2])})}}const E={open:!1,iframe:null,iframeUrlObject:null};class k extends Error{}k.prototype.name="InvalidTokenError";var I,T,R,A={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},P=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(P||{});(R=P||(P={})).reset=function(){I=3,T=A},R.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");I=e},R.setLogger=function(e){T=e};var C=class e{constructor(e){this._name=e}debug(...t){I>=4&&T.debug(e._format(this._name,this._method),...t)}info(...t){I>=3&&T.info(e._format(this._name,this._method),...t)}warn(...t){I>=2&&T.warn(e._format(this._name,this._method),...t)}error(...t){I>=1&&T.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,i){const s=new e(`${t}.${i}`);return s.debug("begin"),s}static _format(e,t){const i=`[${e}]`;return t?`${i} ${t}:`:i}static debug(t,...i){I>=4&&T.debug(e._format(t),...i)}static info(t,...i){I>=3&&T.info(e._format(t),...i)}static warn(t,...i){I>=2&&T.warn(e._format(t),...i)}static error(t,...i){I>=1&&T.error(e._format(t),...i)}};P.reset();var x=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new k("Invalid token specified: must be a string");t||(t={});const i=!0===t.header?0:1,s=e.split(".")[i];if("string"!=typeof s)throw new k(`Invalid token specified: missing part #${i+1}`);let r;try{r=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let i=t.charCodeAt(0).toString(16).toUpperCase();return i.length<2&&(i="0"+i),"%"+i}))}(t)}catch(e){return atob(t)}}(s)}catch(e){throw new k(`Invalid token specified: invalid base64 for part #${i+1} (${e.message})`)}try{return JSON.parse(r)}catch(e){throw new k(`Invalid token specified: invalid json for part #${i+1} (${e.message})`)}}(e)}catch(e){throw C.error("JwtUtils.decode",e),e}}static async generateSignedJwt(e,t,i){const s=`${L.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${L.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,r=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},i,(new TextEncoder).encode(s));return`${s}.${L.encodeBase64Url(new Uint8Array(r))}`}static async generateSignedJwtWithHmac(e,t,i){const s=`${L.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${L.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,r=await window.crypto.subtle.sign("HMAC",i,(new TextEncoder).encode(s));return`${s}.${L.encodeBase64Url(new Uint8Array(r))}`}},O=e=>btoa([...new Uint8Array(e)].map(e=>String.fromCharCode(e)).join("")),U=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){const t="10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(+t^e._randomWord()&15>>+t/4).toString(16));return t.replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),i=await crypto.subtle.digest("SHA-256",t);return O(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw C.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const i=(new TextEncoder).encode([e,t].join(":"));return O(i)}static async hash(e,t){const i=(new TextEncoder).encode(t),s=await crypto.subtle.digest(e,i);return new Uint8Array(s)}static async customCalculateJwkThumbprint(t){let i;switch(t.kty){case"RSA":i={e:t.e,kty:t.kty,n:t.n};break;case"EC":i={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":i={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":i={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const s=await e.hash("SHA-256",JSON.stringify(i));return e.encodeBase64Url(s)}static async generateDPoPProof({url:t,accessToken:i,httpMethod:s,keyPair:r,nonce:n}){let o,a;const c={jti:window.crypto.randomUUID(),htm:null!=s?s:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};i&&(o=await e.hash("SHA-256",i),a=e.encodeBase64Url(o),c.ath=a),n&&(c.nonce=n);try{const e=await crypto.subtle.exportKey("jwk",r.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await x.generateSignedJwt(t,c,r.privateKey)}catch(e){throw e instanceof TypeError?new Error(`Error exporting dpop public key: ${e.message}`):e}}static async generateDPoPJkt(t){try{const i=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(i)}catch(e){throw e instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${e.message}`):e}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}static async generateClientAssertionJwt(t,i,s,r="HS256"){const n=Math.floor(Date.now()/1e3),o={alg:r,typ:"JWT"},a={iss:t,sub:t,aud:s,jti:e.generateUUIDv4(),exp:n+300,iat:n},c={HS256:"SHA-256",HS384:"SHA-384",HS512:"SHA-512"}[r];if(!c)throw new Error(`Unsupported algorithm: ${r}. Supported algorithms are: HS256, HS384, HS512`);const d=new TextEncoder,l=await crypto.subtle.importKey("raw",d.encode(i),{name:"HMAC",hash:c},!1,["sign"]);return await x.generateSignedJwtWithHmac(o,a,l)}};U.encodeBase64Url=e=>O(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var L=U,N=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new C(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},D=class{static center({...e}){var t;return null==e.width&&(e.width=null!=(t=[800,720,600,480].find(e=>e<=window.outerWidth/1.618))?t:360),null!=e.left||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),null!=e.height&&(null!=e.top||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter(([,e])=>null!=e).map(([e,t])=>`${e}=${"boolean"!=typeof t?t:t?"yes":"no"}`).join(",")}},q=class e extends N{constructor(){super(...arguments),this._logger=new C(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const i=this._logger.create("init");t=Math.max(Math.floor(t),1);const s=e.getEpochTime()+t;if(this.expiration===s&&this._timerHandle)return void i.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),i.debug("using duration",t),this._expiration=s;const r=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*r)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},M=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const i=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(i.slice(1))}},H=";",$=class extends Error{constructor(e,t){var i,s,r;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw C.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(i=e.error_description)?i:null,this.error_uri=null!=(s=e.error_uri)?s:null,this.state=e.userState,this.session_state=null!=(r=e.session_state)?r:null,this.url_state=e.url_state}},j=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},G=class{constructor(e){this._logger=new C("AccessTokenEvents"),this._expiringTimer=new q("Access token expiring"),this._expiredTimer=new q("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const i=e.expires_in;if(t.debug("access token present, remaining duration:",i),i>0){let e=i-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug("registering expiring timer, raising in",e,"seconds"),this._expiringTimer.init(e)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const s=i+1;t.debug("registering expired timer, raising in",s,"seconds"),this._expiredTimer.init(s)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},z=class{constructor(e,t,i,s,r){this._callback=e,this._client_id=t,this._intervalInSeconds=s,this._stopOnError=r,this._logger=new C("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};const n=new URL(i);this._frame_origin=n.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=n.href}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)})}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,1e3*this._intervalInSeconds)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},W=class{constructor(){this._logger=new C("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},F=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},K=class{constructor(e=[],t=null,i={}){this._jwtHandler=t,this._extraHeaders=i,this._logger=new C("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:i,...s}=t;if(!i)return await fetch(e,s);const r=new AbortController,n=setTimeout(()=>r.abort(),1e3*i);try{return await fetch(e,{...t,signal:r.signal})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw new j("Network timed out");throw e}finally{clearTimeout(n)}}async getJson(e,{token:t,credentials:i,timeoutInSeconds:s}={}){const r=this._logger.create("getJson"),n={Accept:this._contentTypes.join(", ")};let o;t&&(r.debug("token passed, setting Authorization header"),n.Authorization="Bearer "+t),this._appendExtraHeaders(n);try{r.debug("url:",e),o=await this.fetchWithTimeout(e,{method:"GET",headers:n,timeoutInSeconds:s,credentials:i})}catch(e){throw r.error("Network Error"),e}r.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find(e=>a.startsWith(e))&&r.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),o.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(e){if(r.error("Error parsing JSON response",e),o.ok)throw e;throw new Error(`${o.statusText} (${o.status})`)}if(!o.ok){if(r.error("Error from server:",c),c.error)throw new $(c);throw new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:i,timeoutInSeconds:s,initCredentials:r,extraHeaders:n}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...n};let c;void 0!==i&&(a.Authorization="Basic "+i),this._appendExtraHeaders(a);try{o.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:s,credentials:r})}catch(e){throw o.error("Network error"),e}o.debug("HTTP response received, status",c.status);const d=c.headers.get("Content-Type");if(d&&!this._contentTypes.find(e=>d.startsWith(e)))throw new Error(`Invalid response Content-Type: ${null!=d?d:"undefined"}, from URL: ${e}`);const l=await c.text();let g={};if(l)try{g=JSON.parse(l)}catch(e){if(o.error("Error parsing JSON response",e),c.ok)throw e;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(o.error("Error from server:",g),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new F(e,`${JSON.stringify(g)}`)}if(g.error)throw new $(g,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(g)}`)}return g}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),i=Object.keys(this._extraHeaders),s=["accept","content-type"],r=["authorization"];0!==i.length&&i.forEach(i=>{if(s.includes(i.toLocaleLowerCase()))return void t.warn("Protected header could not be set",i,s);if(r.includes(i.toLocaleLowerCase())&&Object.keys(e).includes(i))return void t.warn("Header could not be overridden",i,r);const n="function"==typeof this._extraHeaders[i]?this._extraHeaders[i]():this._extraHeaders[i];n&&""!==n&&(e[i]=n)})}},J=class{constructor(e){this._settings=e,this._logger=new C("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new K(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const i=this._logger.create(`_getMetadataProperty('${e}')`),s=await this.getMetadata();if(i.debug("resolved"),void 0===s[e]){if(!0===t)return void i.warn("Metadata does not contain optional property");i.throw(new Error("Metadata does not contain property "+e))}return s[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const i=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",i),!Array.isArray(i.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=i.keys,this._signingKeys}},B=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new C("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){return this._logger.create(`get('${e}')`),e=this._prefix+e,await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let i=0;i<e;i++){const e=await this._store.key(i);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},Q=class{constructor({authority:e,metadataUrl:t,metadata:i,signingKeys:s,metadataSeed:r,client_id:n,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:d,post_logout_redirect_uri:l,client_authentication:g="client_secret_post",token_endpoint_auth_signing_alg:h="HS256",prompt:u,display:p,max_age:_,ui_locales:w,acr_values:m,resource:f,response_mode:y,filterProtocolClaims:S=!0,loadUserInfo:v=!1,requestTimeoutInSeconds:b,staleStateAgeInSeconds:E=900,mergeClaimsStrategy:k={array:"replace"},disablePKCE:I=!1,stateStore:T,revokeTokenAdditionalContentTypes:R,fetchRequestCredentials:A,refreshTokenAllowedScope:P,extraQueryParams:C={},extraTokenParams:x={},extraHeaders:O={},dpop:U,omitScopeWhenRequesting:L=!1}){var N;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=i,this.metadataSeed=r,this.signingKeys=s,this.client_id=n,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=d,this.post_logout_redirect_uri=l,this.client_authentication=g,this.token_endpoint_auth_signing_alg=h,this.prompt=u,this.display=p,this.max_age=_,this.ui_locales=w,this.acr_values=m,this.resource=f,this.response_mode=y,this.filterProtocolClaims=null==S||S,this.loadUserInfo=!!v,this.staleStateAgeInSeconds=E,this.mergeClaimsStrategy=k,this.omitScopeWhenRequesting=L,this.disablePKCE=!!I,this.revokeTokenAdditionalContentTypes=R,this.fetchRequestCredentials=A||"same-origin",this.requestTimeoutInSeconds=b,T)this.stateStore=T;else{const e="undefined"!=typeof window?window.localStorage:new W;this.stateStore=new B({store:e})}if(this.refreshTokenAllowedScope=P,this.extraQueryParams=C,this.extraTokenParams=x,this.extraHeaders=O,this.dpop=U,this.dpop&&!(null==(N=this.dpop)?void 0:N.store))throw new Error("A DPoPStore is required when dpop is enabled")}},V=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new C("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const i=x.decode(e);return t.debug("JWT decoding successful"),i}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new K(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const i=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",i);const s=await this._jsonService.getJson(i,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",s),s}},X=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new C("TokenClient"),this._jsonService=new K(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:i=this._settings.client_id,client_secret:s=this._settings.client_secret,extraHeaders:r,...n}){const o=this._logger.create("exchangeCode");i||o.throw(new Error("A client_id is required")),t||o.throw(new Error("A redirect_uri is required")),n.code||o.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[e,t]of Object.entries(n))null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==s)throw o.throw(new Error("A client_secret is required")),null;let c;const d=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=L.generateBasicAuth(i,s);break;case"client_secret_post":a.append("client_id",i),s&&a.append("client_secret",s);break;case"client_secret_jwt":{const e=await L.generateClientAssertionJwt(i,s,d,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",i),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const l=await this._jsonService.postForm(d,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:r});return o.debug("got response"),l}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:i=this._settings.client_secret,scope:s=this._settings.scope,...r}){const n=this._logger.create("exchangeCredentials");t||n.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set("scope",s);for(const[e,t]of Object.entries(r))null!=t&&o.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==i)throw n.throw(new Error("A client_secret is required")),null;let a;const c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":a=L.generateBasicAuth(t,i);break;case"client_secret_post":o.append("client_id",t),i&&o.append("client_secret",i);break;case"client_secret_jwt":{const e=await L.generateClientAssertionJwt(t,i,c,this._settings.token_endpoint_auth_signing_alg);o.append("client_id",t),o.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),o.append("client_assertion",e);break}}n.debug("got token endpoint");const d=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),d}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:i=this._settings.client_secret,timeoutInSeconds:s,extraHeaders:r,...n}){const o=this._logger.create("exchangeRefreshToken");t||o.throw(new Error("A client_id is required")),n.refresh_token||o.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[e,t]of Object.entries(n))Array.isArray(t)?t.forEach(t=>a.append(e,t)):null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==i)throw o.throw(new Error("A client_secret is required")),null;let c;const d=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=L.generateBasicAuth(t,i);break;case"client_secret_post":a.append("client_id",t),i&&a.append("client_secret",i);break;case"client_secret_jwt":{const e=await L.generateClientAssertionJwt(t,i,d,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",t),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const l=await this._jsonService.postForm(d,{body:a,basicAuth:c,timeoutInSeconds:s,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:r});return o.debug("got response"),l}async revoke(e){var t;const i=this._logger.create("revoke");e.token||i.throw(new Error("A token is required"));const s=await this._metadataService.getRevocationEndpoint(!1);i.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const r=new URLSearchParams;for(const[t,i]of Object.entries(e))null!=i&&r.set(t,i);r.set("client_id",this._settings.client_id),this._settings.client_secret&&r.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(s,{body:r,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),i.debug("got response")}},Y=class{constructor(e,t,i){this._settings=e,this._metadataService=t,this._claimsService=i,this._logger=new C("ResponseValidator"),this._userInfoService=new V(this._settings,this._metadataService),this._tokenClient=new X(this._settings,this._metadataService)}async validateSigninResponse(e,t,i){const s=this._logger.create("validateSigninResponse");this._processSigninState(e,t),s.debug("state processed"),await this._processCode(e,t,i),s.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),s.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),s.debug("claims processed")}async validateCredentialsResponse(e,t){const i=this._logger.create("validateCredentialsResponse"),s=e.isOpenId&&!!e.id_token;s&&this._validateIdTokenAttributes(e),i.debug("tokens validated"),await this._processClaims(e,t,s),i.debug("claims processed")}async validateRefreshResponse(e,t){const i=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),i.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const s=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,s),i.debug("claims processed")}validateSignoutResponse(e,t){const i=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&i.throw(new Error("State does not match")),i.debug("state validated"),e.userState=t.data,e.error)throw i.warn("Response was error",e.error),new $(e)}_processSigninState(e,t){const i=this._logger.create("_processSigninState");if(t.id!==e.state&&i.throw(new Error("State does not match")),t.client_id||i.throw(new Error("No client_id on state")),t.authority||i.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&i.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&i.throw(new Error("client_id mismatch on settings vs. signin state")),i.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw i.warn("Response was error",e.error),new $(e);t.code_verifier&&!e.code&&i.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,i=!0){const s=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void s.debug("not loading user info");s.debug("loading user info");const r=await this._userInfoService.getClaims(e.access_token);s.debug("user info claims received from user info endpoint"),i&&r.sub!==e.profile.sub&&s.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(r)),s.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,i){const s=this._logger.create("_processCode");if(e.code){s.debug("Validating code");const r=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:i,...t.extraTokenParams});Object.assign(e,r)}else s.debug("No code to process")}_validateIdTokenAttributes(e,t){var i;const s=this._logger.create("_validateIdTokenAttributes");s.debug("decoding ID Token JWT");const r=x.decode(null!=(i=e.id_token)?i:"");if(r.sub||s.throw(new Error("ID Token is missing a subject claim")),t){const e=x.decode(t);r.sub!==e.sub&&s.throw(new Error("sub in id_token does not match current sub")),r.auth_time&&r.auth_time!==e.auth_time&&s.throw(new Error("auth_time in id_token does not match original auth_time")),r.azp&&r.azp!==e.azp&&s.throw(new Error("azp in id_token does not match original azp")),!r.azp&&e.azp&&s.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=r}},Z=class e{constructor(e){this.id=e.id||L.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=q.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new C("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return C.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,i){const s=C.createStatic("State","clearStaleState"),r=q.getEpochTime()-i,n=await t.getAllKeys();s.debug("got keys",n);for(let i=0;i<n.length;i++){const o=n[i],a=await t.get(o);let c=!1;if(a)try{const t=await e.fromStorageString(a);s.debug("got item from key:",o,t.created),t.created<=r&&(c=!0)}catch(e){s.error("Error parsing state for key:",o,e),c=!0}else s.debug("no item in storage for key:",o),c=!0;c&&(s.debug("removed item for key:",o),t.remove(o))}}},ee=class e extends Z{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(t){const i=!0===t.code_verifier?L.generateCodeVerifier():t.code_verifier||void 0,s=i?await L.generateCodeChallenge(i):void 0;return new e({...t,code_verifier:i,code_challenge:s})}toStorageString(){return new C("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){C.createStatic("SigninState","fromStorageString");const i=JSON.parse(t);return e.create(i)}},te=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:i,client_id:s,redirect_uri:r,response_type:n,scope:o,state_data:a,response_mode:c,request_type:d,client_secret:l,nonce:g,url_state:h,resource:u,skipUserInfo:p,extraQueryParams:_,extraTokenParams:w,disablePKCE:m,dpopJkt:f,omitScopeWhenRequesting:y,...S}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!s)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!r)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!n)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!o)throw this._logger.error("create: No scope passed"),new Error("scope");if(!i)throw this._logger.error("create: No authority passed"),new Error("authority");const v=await ee.create({data:a,request_type:d,url_state:h,code_verifier:!m,client_id:s,authority:i,redirect_uri:r,response_mode:c,client_secret:l,scope:o,extraTokenParams:w,skipUserInfo:p}),b=new URL(t);b.searchParams.append("client_id",s),b.searchParams.append("redirect_uri",r),b.searchParams.append("response_type",n),y||b.searchParams.append("scope",o),g&&b.searchParams.append("nonce",g),f&&b.searchParams.append("dpop_jkt",f);let E=v.id;h&&(E=`${E}${H}${h}`),b.searchParams.append("state",E),v.code_challenge&&(b.searchParams.append("code_challenge",v.code_challenge),b.searchParams.append("code_challenge_method","S256")),u&&(Array.isArray(u)?u:[u]).forEach(e=>b.searchParams.append("resource",e));for(const[e,t]of Object.entries({response_mode:c,...S,..._}))null!=t&&b.searchParams.append(e,t.toString());return new e({url:b.href,state:v})}};te._logger=new C("SigninRequest");var ie=te,se=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(H);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(H))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-q.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+q.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},re=class{constructor({url:e,state_data:t,id_token_hint:i,post_logout_redirect_uri:s,extraQueryParams:r,request_type:n,client_id:o,url_state:a}){if(this._logger=new C("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(i&&c.searchParams.append("id_token_hint",i),o&&c.searchParams.append("client_id",o),s&&(c.searchParams.append("post_logout_redirect_uri",s),t||a)){this.state=new Z({data:t,request_type:n,url_state:a});let e=this.state.id;a&&(e=`${e}${H}${a}`),c.searchParams.append("state",e)}for(const[e,t]of Object.entries({...r}))null!=t&&c.searchParams.append(e,t.toString());this.url=c.href}},ne=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(H);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(H))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},oe=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],ae=["sub","iss","aud","exp","iat"],ce=class{constructor(e){this._settings=e,this._logger=new C("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:oe;for(const i of e)ae.includes(i)||delete t[i]}return t}mergeClaims(e,t){const i={...e};for(const[e,s]of Object.entries(t))if(i[e]!==s)if(Array.isArray(i[e])||Array.isArray(s))if("replace"==this._settings.mergeClaimsStrategy.array)i[e]=s;else{const t=Array.isArray(i[e])?i[e]:[i[e]];for(const e of Array.isArray(s)?s:[s])t.includes(e)||t.push(e);i[e]=t}else"object"==typeof i[e]&&"object"==typeof s?i[e]=this.mergeClaims(i[e],s):i[e]=s;return i}},de=class{constructor(e,t){this.keys=e,this.nonce=t}},le=class{constructor(e,t){this._logger=new C("OidcClient"),this.settings=e instanceof Q?e:new Q(e),this.metadataService=null!=t?t:new J(this.settings),this._claimsService=new ce(this.settings),this._validator=new Y(this.settings,this.metadataService,this._claimsService),this._tokenClient=new X(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:i,request_type:s,id_token_hint:r,login_hint:n,skipUserInfo:o,nonce:a,url_state:c,response_type:d=this.settings.response_type,scope:l=this.settings.scope,redirect_uri:g=this.settings.redirect_uri,prompt:h=this.settings.prompt,display:u=this.settings.display,max_age:p=this.settings.max_age,ui_locales:_=this.settings.ui_locales,acr_values:w=this.settings.acr_values,resource:m=this.settings.resource,response_mode:f=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:S=this.settings.extraTokenParams,dpopJkt:v,omitScopeWhenRequesting:b=this.settings.omitScopeWhenRequesting}){const E=this._logger.create("createSigninRequest");if("code"!==d)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const k=await this.metadataService.getAuthorizationEndpoint();E.debug("Received authorization endpoint",k);const I=await ie.create({url:k,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:g,response_type:d,scope:l,state_data:e,url_state:c,prompt:h,display:u,max_age:p,ui_locales:_,id_token_hint:r,login_hint:n,acr_values:w,dpopJkt:v,resource:m,request:t,request_uri:i,extraQueryParams:y,extraTokenParams:S,request_type:s,response_mode:f,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:b});await this.clearStaleState();const T=I.state;return await this.settings.stateStore.set(T.id,T.toStorageString()),I}async readSigninResponseState(e,t=!1){const i=this._logger.create("readSigninResponseState"),s=new se(M.readParams(e,this.settings.response_mode));if(!s.state)throw i.throw(new Error("No state in response")),null;const r=await this.settings.stateStore[t?"remove":"get"](s.state);if(!r)throw i.throw(new Error("No matching state found in storage")),null;return{state:await ee.fromStorageString(r),response:s}}async processSigninResponse(e,t,i=!0){const s=this._logger.create("processSigninResponse"),{state:r,response:n}=await this.readSigninResponseState(e,i);if(s.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(n,r,t)}catch(e){if(!(e instanceof F&&this.settings.dpop))throw e;{const i=await this.getDpopProof(this.settings.dpop.store,e.nonce);t.DPoP=i,await this._validator.validateSigninResponse(n,r,t)}}return n}async getDpopProof(e,t){let i,s;return(await e.getAllKeys()).includes(this.settings.client_id)?(s=await e.get(this.settings.client_id),s.nonce!==t&&t&&(s.nonce=t,await e.set(this.settings.client_id,s))):(i=await L.generateDPoPKeys(),s=new de(i,t),await e.set(this.settings.client_id,s)),await L.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:s.keys,nonce:s.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:i=!1,extraTokenParams:s={}}){const r=await this._tokenClient.exchangeCredentials({username:e,password:t,...s}),n=new se(new URLSearchParams);return Object.assign(n,r),await this._validator.validateCredentialsResponse(n,i),n}async useRefreshToken({state:e,redirect_uri:t,resource:i,timeoutInSeconds:s,extraHeaders:r,extraTokenParams:n}){var o;const a=this._logger.create("useRefreshToken");let c,d;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(o=e.scope)?void 0:o.split(" "))||[]).filter(e=>t.includes(e)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);r={...r,DPoP:e}}try{d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:i,timeoutInSeconds:s,extraHeaders:r,...n})}catch(o){if(!(o instanceof F&&this.settings.dpop))throw o;r.DPoP=await this.getDpopProof(this.settings.dpop.store,o.nonce),d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:i,timeoutInSeconds:s,extraHeaders:r,...n})}const l=new se(new URLSearchParams);return Object.assign(l,d),a.debug("validating response",l),await this._validator.validateRefreshResponse(l,{...e,scope:c}),l}async createSignoutRequest({state:e,id_token_hint:t,client_id:i,request_type:s,url_state:r,post_logout_redirect_uri:n=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",c),i||!n||t||(i=this.settings.client_id);const d=new re({url:c,id_token_hint:t,client_id:i,post_logout_redirect_uri:n,state_data:e,extraQueryParams:o,request_type:s,url_state:r});await this.clearStaleState();const l=d.state;return l&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(l.id,l.toStorageString())),d}async readSignoutResponseState(e,t=!1){const i=this._logger.create("readSignoutResponseState"),s=new ne(M.readParams(e,this.settings.response_mode));if(!s.state){if(i.debug("No state in response"),s.error)throw i.warn("Response was error:",s.error),new $(s);return{state:void 0,response:s}}const r=await this.settings.stateStore[t?"remove":"get"](s.state);if(!r)throw i.throw(new Error("No matching state found in storage")),null;return{state:await Z.fromStorageString(r),response:s}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:i,response:s}=await this.readSignoutResponseState(e,!0);return i?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(s,i)):t.debug("No state from storage; skipping response validation"),s}clearStaleState(){return this._logger.create("clearStaleState"),Z.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},ge=class{constructor(e){this._userManager=e,this._logger=new C("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const i=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,i.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,i.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){i.debug("initializing check session iframe");const s=this._userManager.settings.client_id,r=this._userManager.settings.checkSessionIntervalInSeconds,n=this._userManager.settings.stopCheckSessionOnError,o=new z(this._callback,s,e,r,n);await o.load(),this._checkSessionIFrame=o,o.start(t)}else i.warn("no check session iframe found in the metadata")}catch(e){i.error("Error from getCheckSessionIframe:",e instanceof Error?e.message:e)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval(async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(t){e.error("error from querySessionStatus",t instanceof Error?t.message:t)}},1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let i=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(i=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),i?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch(e=>{this._logger.error(e)})}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},he=class e{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-q.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+q.getEpochTime())}get expired(){const e=this.expires_in;if(void 0!==e)return e<=0}get scopes(){var e,t;return null!=(t=null==(e=this.scope)?void 0:e.split(" "))?t:[]}toStorageString(){return new C("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return C.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},ue="oidc-client",pe=class{constructor(){this._abort=new N("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:i,keepOpen:s}=await new Promise((i,s)=>{const r=r=>{var n;const o=r.data,a=null!=(n=e.scriptOrigin)?n:window.location.origin;if(r.origin===a&&(null==o?void 0:o.source)===ue){try{const i=M.readParams(o.url,e.response_mode).get("state");if(i||t.warn("no state found in response url"),r.source!==this._window&&i!==e.state)return}catch{this._dispose(),s(new Error("Invalid response from window"))}i(o)}};window.addEventListener("message",r,!1),this._disposeHandlers.add(()=>window.removeEventListener("message",r,!1));const n=new BroadcastChannel(`oidc-client-popup-${e.state}`);n.addEventListener("message",r,!1),this._disposeHandlers.add(()=>n.close()),this._disposeHandlers.add(this._abort.addHandler(e=>{this._dispose(),s(e)}))});return t.debug("got response from window"),this._dispose(),s||this.close(),{url:i}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,i=!1,s=window.location.origin){const r={source:ue,url:t,keepOpen:i},n=new C("_notifyParent");if(e)n.debug("With parent. Using parent.postMessage."),e.postMessage(r,s);else{n.debug("No parent. Using BroadcastChannel.");const e=new URL(t).searchParams.get("state");if(!e)throw new Error("No parent and no state in URL. Can't complete notification.");const i=new BroadcastChannel(`oidc-client-popup-${e}`);i.postMessage(r),i.close()}}},_e={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},we="_blank",me=60,fe=2,ye=class extends Q{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:i=e.post_logout_redirect_uri,popupWindowFeatures:s=_e,popupWindowTarget:r=we,redirectMethod:n="assign",redirectTarget:o="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:d,silent_redirect_uri:l=e.redirect_uri,silentRequestTimeoutInSeconds:g,automaticSilentRenew:h=!0,validateSubOnSilentRenew:u=!0,includeIdTokenInSilentRenew:p=!1,monitorSession:_=!1,monitorAnonymousSession:w=!1,checkSessionIntervalInSeconds:m=fe,query_status_response_type:f="code",stopCheckSessionOnError:y=!0,revokeTokenTypes:S=["access_token","refresh_token"],revokeTokensOnSignout:v=!1,includeIdTokenInSilentSignout:b=!1,accessTokenExpiringNotificationTimeInSeconds:E=me,userStore:k}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=i,this.popupWindowFeatures=s,this.popupWindowTarget=r,this.redirectMethod=n,this.redirectTarget=o,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=l,this.silentRequestTimeoutInSeconds=g||d||10,this.automaticSilentRenew=h,this.validateSubOnSilentRenew=u,this.includeIdTokenInSilentRenew=p,this.monitorSession=_,this.monitorAnonymousSession=w,this.checkSessionIntervalInSeconds=m,this.stopCheckSessionOnError=y,this.query_status_response_type=f,this.revokeTokenTypes=S,this.revokeTokensOnSignout=v,this.includeIdTokenInSilentSignout=b,this.accessTokenExpiringNotificationTimeInSeconds=E,k)this.userStore=k;else{const e="undefined"!=typeof window?window.sessionStorage:new W;this.userStore=new B({store:e})}}},Se=class e extends pe{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new C("IFrameWindow"),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout(()=>{this._abort.raise(new j("IFrame timed out without a response"))},1e3*this._timeoutInSeconds);return this._disposeHandlers.add(()=>clearTimeout(t)),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",e=>{var t;const i=e.target;null==(t=i.parentNode)||t.removeChild(i),this._abort.raise(new Error("IFrame removed from DOM"))},!0),null==(e=this._frame.contentWindow)||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},ve=class{constructor(e){this._settings=e,this._logger=new C("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new Se({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),Se.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},be=class extends pe{constructor({popupWindowTarget:e=we,popupWindowFeatures:t={},popupSignal:i,popupAbortOnClose:s}){super(),this._logger=new C("PopupWindow");const r=D.center({..._e,...t});this._window=window.open(void 0,e,D.serialize(r)),this.abortOnClose=Boolean(s),i&&i.addEventListener("abort",()=>{var e;this._abort.raise(new Error(null!=(e=i.reason)?e:"Popup aborted"))}),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout(()=>{this._window&&"boolean"==typeof this._window.closed&&!this._window.closed?this.close():this._abort.raise(new Error("Popup blocked by user"))},1e3*t.closePopupWindowAfterInSeconds)}async navigate(e){var t;null==(t=this._window)||t.focus();const i=setInterval(()=>{this._window&&!this._window.closed||(this._logger.debug("Popup closed by user or isolated by redirect"),s(),this._disposeHandlers.delete(s),this.abortOnClose&&this._abort.raise(new Error("Popup closed by user")))},500),s=()=>clearInterval(i);return this._disposeHandlers.add(s),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),t||window.opener||window.close()}},Ee=class{constructor(e){this._settings=e,this._logger=new C("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:i,popupAbortOnClose:s}){return new be({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:i,popupAbortOnClose:s})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),be.notifyOpener(e,t)}},ke=class{constructor(e){this._settings=e,this._logger=new C("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var i;this._logger.create("prepare");let s=window.self;"top"===t&&(s=null!=(i=window.top)?i:window.self);const r=s.location[e].bind(s.location);let n;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise((t,i)=>{n=i,window.addEventListener("pageshow",()=>t(window.location.href)),r(e.url)});return await t},close:()=>{this._logger.create("close"),null==n||n(new Error("Redirect aborted")),s.stop()}}}async callback(){}},Ie=class extends G{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new C("UserManagerEvents"),this._userLoaded=new N("User loaded"),this._userUnloaded=new N("User unloaded"),this._silentRenewError=new N("Silent renew error"),this._userSignedIn=new N("User signed in"),this._userSignedOut=new N("User signed out"),this._userSessionChanged=new N("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},Te=class{constructor(e){this._userManager=e,this._logger=new C("SilentRenewService"),this._isStarted=!1,this._retryTimer=new q("Retry Silent Renew"),this._tokenExpiring=async()=>{const e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof j)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),await this._userManager.events._raiseSilentRenewError(t)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},Re=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},Ae=class{constructor(e,t,i,s){this._logger=new C("UserManager"),this.settings=new ye(e),this._client=new le(e),this._redirectNavigator=null!=t?t:new ke(this.settings),this._popupNavigator=null!=i?i:new Ee(this.settings),this._iframeNavigator=null!=s?s:new ve(this.settings),this._events=new Ie(this.settings),this._silentRenewService=new Te(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new ge(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),i=await this._loadUser();return i?(t.info("user loaded"),await this._events.load(i,e),i):(t.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");const{redirectMethod:i,...s}=e;let r;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(r=await this.generateDPoPJkt(this.settings.dpop));const n=await this._redirectNavigator.prepare({redirectMethod:i});await this._signinStart({request_type:"si:r",dpopJkt:r,...s},n)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),i=await this._signinEnd(e);return i.profile&&i.profile.sub?t.info("success, signed in subject",i.profile.sub):t.info("no subject"),i}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:i=!1}){const s=this._logger.create("signinResourceOwnerCredential"),r=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:i,extraTokenParams:this.settings.extraTokenParams});s.debug("got signin response");const n=await this._buildUser(r);return n.profile&&n.profile.sub?s.info("success, signed in subject",n.profile.sub):s.info("no subject"),n}async signinPopup(e={}){var t;const i=this._logger.create("signinPopup");let s;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:r,popupWindowTarget:n,popupSignal:o,popupAbortOnClose:a,...c}=e,d=this.settings.popup_redirect_uri;d||i.throw(new Error("No popup_redirect_uri configured"));const l=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:n,popupSignal:o,popupAbortOnClose:a}),g=await this._signin({request_type:"si:p",redirect_uri:d,display:"popup",dpopJkt:s,...c},l);return g&&(g.profile&&g.profile.sub?i.info("success, signed in subject",g.profile.sub):i.info("no subject")),g}async signinPopupCallback(e=window.location.href,t=!1){const i=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),i.info("success")}async signinSilent(e={}){var t,i;const s=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:r,...n}=e;let o,a=await this._loadUser();if(!e.forceIframeAuth&&(null==a?void 0:a.refresh_token)){s.debug("using refresh token");const e=new Re(a);return await this._useRefreshToken({state:e,redirect_uri:n.redirect_uri,resource:n.resource,extraTokenParams:n.extraTokenParams,timeoutInSeconds:r})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(o=await this.generateDPoPJkt(this.settings.dpop));const c=this.settings.silent_redirect_uri;let d;c||s.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(s.debug("subject prior to silent renew:",a.profile.sub),d=a.profile.sub);const l=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r});return a=await this._signin({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:o,...n},l,d),a&&((null==(i=a.profile)?void 0:i.sub)?s.info("success, signed in subject",a.profile.sub):s.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),i=new he({...e.state,...t});return await this.storeUser(i),await this._events.load(i),i}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:i}=await this._client.readSignoutResponseState(e);if(i)switch(i.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:i,...s}=e,r=this.settings.silent_redirect_uri;r||t.throw(new Error("No silent_redirect_uri configured"));const n=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:i}),a=await this._signinStart({request_type:"si:s",redirect_uri:r,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==n?void 0:n.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...s},o);try{const e={},i=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),i.session_state&&i.profile.sub?(t.info("success for subject",i.profile.sub),{session_state:i.session_state,sub:i.profile.sub}):(t.info("success, user not authenticated"),null)}catch(e){if(this.settings.monitorAnonymousSession&&e instanceof $)switch(e.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:e.session_state}}throw e}}async _signin(e,t,i){const s=await this._signinStart(e,t);return await this._signinEnd(s.url,i)}async _signinStart(e,t){const i=this._logger.create("_signinStart");try{const s=await this._client.createSigninRequest(e);return i.debug("got signin request"),await t.navigate({url:s.url,state:s.state.id,response_mode:s.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw i.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signinEnd(e,t){const i=this._logger.create("_signinEnd"),s=await this._client.processSigninResponse(e,{});return i.debug("got signin response"),await this._buildUser(s,t)}async _buildUser(e,t){const i=this._logger.create("_buildUser"),s=new he(e);if(t){if(t!==s.profile.sub)throw i.debug("current user does not match user returned from signin. sub from signin:",s.profile.sub),new $({...e,error:"login_required"});i.debug("current user matches user returned from signin")}return await this.storeUser(s),i.debug("user stored"),await this._events.load(s),s}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:i,...s}=e,r=await this._redirectNavigator.prepare({redirectMethod:i});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...s},r),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),i=await this._signoutEnd(e);return t.info("success"),i}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:i,popupWindowTarget:s,popupSignal:r,...n}=e,o=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:i,popupWindowTarget:s,popupSignal:r});await this._signout({request_type:"so:p",post_logout_redirect_uri:o,state:null==o?void 0:{},...n},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const i=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),i.info("success")}async _signout(e,t){const i=await this._signoutStart(e,t);return await this._signoutEnd(i.url)}async _signoutStart(e={},t){var i;const s=this._logger.create("_signoutStart");try{const r=await this._loadUser();s.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(r);const n=e.id_token_hint||r&&r.id_token;n&&(s.debug("setting id_token_hint in signout request"),e.id_token_hint=n),await this.removeUser(),s.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return s.debug("got signout request"),await t.navigate({url:o.url,state:null==(i=o.state)?void 0:i.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw s.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),i=await this._client.processSignoutResponse(e);return t.debug("got signout response"),i}async signoutSilent(e={}){var t;const i=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:s,...r}=e,n=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,o=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:n,...r},a),i.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const i=this._logger.create("_revokeInternal");if(!e)return;const s=t.filter(t=>"string"==typeof e[t]);if(s.length){for(const t of s)await this._client.revokeToken(e[t],t),i.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),i.debug("user stored"),await this._events.load(e)}else i.debug("no need to revoke due to no token(s)")}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),he.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const i=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,i)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,i,s){var r,n;const o=await(null==(n=null==(r=this.settings.dpop)?void 0:r.store)?void 0:n.get(this.settings.client_id));if(o)return await L.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:i,keyPair:o.keys,nonce:s})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const i=await L.generateDPoPKeys();t=new de(i),await e.store.set(this.settings.client_id,t)}return await L.generateDPoPJkt(t.keys)}};const Pe="OAUTH2_LOGIN_FLOW_COMPLETE_EVENT",Ce="OAUTH_GET_TOP_URL",xe="OAUTH_REDIRECT_TOP_WINDOW",Oe="OAUTH_UPDATE_URL",Ue="OAUTH2_CHECK_PENDING",Le="oauth2_top_origin",Ne="oauth2_login_success",De="oauth2_state",qe=60,Me=Math.max(qe-15,20),He=d("oidc-auth",{color:"green"}),$e=e=>He.extend(e);d("oidc-auth-utils");const je=()=>"undefined"==typeof window?"":new URLSearchParams(window.location.search).get("origin")||"";class Ge{static instance=null;settings=null;constructor(){}static getInstance(){return Ge.instance||(Ge.instance=new Ge),Ge.instance}configure(e){this.settings=e}isConfigured(){return null!==this.settings}getSettings(){if(!this.settings)throw new Error("OidcAuthConfig not configured. Call configure() or pass settings to OidcAuthClient.initialize().");return this.settings}getAuthOrigin(){const{authOrigin:e,authEndpoint:t}=this.getSettings();return e||new URL(t).origin}isAccessTokenProactiveRefreshEnabled(){return this.settings?.accessTokenProactiveRefreshEnabled??!0}getOidcSettings(){const e="undefined"==typeof window?"":window.location.origin,{clientId:t,authEndpoint:i}=this.getSettings(),s=this.getAuthOrigin(),r="undefined"!=typeof window?new B({store:window.localStorage}):void 0,{accessTokenExpiringNotificationTimeInSeconds:n=qe}=this.getSettings();return{client_id:t,authority:s,redirect_uri:`${e}/login/oauth-callback`,post_logout_redirect_uri:e,response_type:"code",scope:"openid offline_access",automaticSilentRenew:!1,accessTokenExpiringNotificationTimeInSeconds:n,stateStore:r,userStore:r,metadata:{issuer:s,authorization_endpoint:i,token_endpoint:`${s}/connect/api/v1/oauth2/token`,end_session_endpoint:`${s}/logout/`}}}getAccessTokenExpiringNotificationTimeInSeconds(){return this.getSettings().accessTokenExpiringNotificationTimeInSeconds??qe}getAccessTokenFreshnessThresholdInSeconds(){return this.getSettings().accessTokenFreshnessThresholdInSeconds??Me}getAllowedParentOrigins(){return this.settings?.allowedParentOrigins}}const ze=Ge.getInstance(),We=$e("oidc-auth:host-api"),Fe=async e=>new Promise((t,i)=>{const s=new MessageChannel;let r=!1;const n=()=>{r=!0,s.port1.close()},o=setTimeout(()=>{r||(n(),i(new Error(`Host message timeout: ${e.type}`)))},1e4);s.port1.onmessage=e=>{clearTimeout(o),n(),"success"!==e.data.status?i(e.data.payload):t(e.data.payload)};const a=new URLSearchParams(window.location.search).get("origin")||"";if(!function(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return!1;const t=ze.getAllowedParentOrigins();return!t||0===t.length||t.includes(e)}(a))return clearTimeout(o),n(),void i(new Error("Origin not allowed"));We.log("posting message to host",e),window.top.postMessage({type:e.type,payload:e.payload,...e.data||{}},a,[s.port2])}),Ke=$e("oidc-auth:OidcAuthTimer");class Je{timerHandle=null;expiration=null;initialized=!1;callback=()=>{};constructor(){this.timerHandle=null}init(e,t,i){const s=e-this.getEpochTime(),r=Math.max(s-t,10);this.cancel(),this.expiration=r,this.callback=i,Ke.debug("OIDC: timer - using expiration",r,s,t,e,s-t),this.timerHandle=setTimeout(this.callback,1e3*r),this.initialized=!0}cancel(){this.timerHandle&&(clearTimeout(this.timerHandle),this.timerHandle=null),this.expiration=null}getEpochTime(){return Math.floor(Date.now()/1e3)}isInitialized(){return this.initialized}}const Be=$e("oidc-auth:OidcAuthClient");class Qe{static instance=null;userManager=null;initialized=!1;accessTokenExpiringTimer=null;retryTimers=new Set;constructor(){}static getInstance(){return Qe.instance||(Qe.instance=new Qe),Qe.instance}isInitialized(){return this.initialized}ensureInitialized(){if(!this.userManager)throw new Error("OidcAuthClient not initialized. Call initialize() first.");return this.userManager}initialize(e){if(e&&(this.initialized=!1,ze.configure(e)),this.initialized)Be.info("OIDC: initialize() - already initialized, skipping");else if("undefined"!=typeof window)if(ze.isConfigured())try{Be.info("OIDC: initialize() - starting initialization");const e=ze.getOidcSettings();this.userManager=new Ae(e),P.setLogger(Be),P.setLevel(P.ERROR),this.initAccessTokenExpiringTimer(),this.initialized=!0}catch(e){throw Be.error("OIDC: initialize() - FAILED:",e),e}else Be.warn("OIDC: initialize() - skipped, config not set");else Be.warn("OidcAuthClient cannot initialize on server side")}async initAccessTokenExpiringTimer(){ze.isAccessTokenProactiveRefreshEnabled()?this.getUser().then(e=>{const t=e?.expires_at;t&&(this.accessTokenExpiringTimer||(this.accessTokenExpiringTimer=new Je),this.accessTokenExpiringTimer.init(t,ze.getAccessTokenExpiringNotificationTimeInSeconds(),async()=>{Be.info("OIDC: timer proactive refresh access token expiring timer fired",t),this.proactiveRefreshWithRetry()}))}).catch(e=>{Be.error("OIDC: initAccessTokenExpiringTimer - FAILED:",e)}):Be.warn("OIDC: timer - not starting, access token proactive refresh is disabled")}async getUser(){if(!this.userManager)return null;try{return await this.userManager.getUser()}catch(e){return Be.error("OIDC: getUser - FAILED:",e),null}}async storeUser(e){const t=this.ensureInitialized();await t.storeUser(e)}async getAccessToken(){const e=await this.getUser();if(!e)return Be.info("OIDC: getAccessToken - no user found"),null;if(e.expired)try{const e=await this.signinSilent();return e?.access_token||null}catch(e){return Be.error("OIDC: getAccessToken - silent renew failed:",e),null}return this.isTokenFresh(e)||this.signinSilent().catch(e=>{Be.error("OIDC: getAccessToken - background refresh failed:",e)}),e.access_token}getUserData(){if("undefined"==typeof window)return null;try{const e=ze.getOidcSettings(),t=`oidc.user:${e.authority}:${e.client_id}`,i=localStorage.getItem(t);if(!i)return null;const s=JSON.parse(i),r=s?.profile;return r?.sub?(Be.info("OIDC: USER:",{profile:r}),{id:r.sub,email:r.email||"",first_name:r.given_name,last_name:r.family_name}):null}catch(e){return Be.error("OIDC: getUserData - FAILED:",e),null}}async isAuthenticated(){const e=await this.getUser();return null!==e&&!e.expired}async signinRedirect(e){const t=this.ensureInitialized();await t.signinRedirect({state:e?{data:e}:void 0,prompt:"login"})}async signinCallback(){const e=this.ensureInitialized(),t=await e.signinCallback();if(!t)throw Be.error("OIDC: signinCallback - FAILED: no user returned"),new Error("Signin callback failed: no user returned");return t}async signinSilent(e){return this.ensureInitialized(),"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request("oidc-token-refresh",async()=>{const t=await this.getUser();return t&&this.isTokenFresh(t,e)?t:this.doSigninSilent()}):(Be.warn("OIDC: signinSilent - navigator.locks not available, proceeding without lock"),this.doSigninSilent())}isTokenFresh(e,t){if(!e.expires_at)return!1;const i=t??ze.getAccessTokenFreshnessThresholdInSeconds(),s=Math.floor(Date.now()/1e3);return e.expires_at-s>i}async doSigninSilent(){const e=this.ensureInitialized();try{return await e.signinSilent()}catch(e){throw Be.error("OIDC: doSigninSilent - FAILED:",e),e}}proactiveRefreshWithRetry(e=1){if("undefined"!=typeof document&&"hidden"===document.visibilityState){Be.info("OIDC: tab is hidden, deferring proactive refresh until visible");const t=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",t),this.proactiveRefreshWithRetry(e))};return void document.addEventListener("visibilitychange",t)}this.signinSilent(ze.getAccessTokenExpiringNotificationTimeInSeconds()).then(()=>{this.initAccessTokenExpiringTimer()}).catch(t=>{if(Be.error(`OIDC: proactive refresh failed (attempt ${e}/2):`,t),e<2){const t=setTimeout(()=>{this.retryTimers.delete(t),this.proactiveRefreshWithRetry(e+1)},3e3);this.retryTimers.add(t)}else Be.error("OIDC: proactive refresh exhausted all retries")})}async removeUser(){const e=this.ensureInitialized();this.accessTokenExpiringTimer?.cancel(),this.retryTimers.forEach(clearTimeout),this.retryTimers.clear(),await e.removeUser()}onUserLoaded(e){this.ensureInitialized().events.addUserLoaded(e)}offUserLoaded(e){this.ensureInitialized().events.removeUserLoaded(e)}onUserUnloaded(e){this.ensureInitialized().events.addUserUnloaded(e)}offUserUnloaded(e){this.ensureInitialized().events.removeUserUnloaded(e)}onSilentRenewError(e){this.ensureInitialized().events.addSilentRenewError(e)}offSilentRenewError(e){this.ensureInitialized().events.removeSilentRenewError(e)}onAccessTokenExpiring(e){this.ensureInitialized().events.addAccessTokenExpiring(e)}offAccessTokenExpiring(e){this.ensureInitialized().events.removeAccessTokenExpiring(e)}onAccessTokenExpired(e){this.ensureInitialized().events.addAccessTokenExpired(e)}offAccessTokenExpired(e){this.ensureInitialized().events.removeAccessTokenExpired(e)}getLogoutUrl(e,t){const i=new URL(function(e){return`${ze.getAuthOrigin()}${e.logoutPath}`}(e));return t&&i.searchParams.set("redirect_to",t),i.toString()}getWindowOriginParam(){const e=new URL(window.location.href).searchParams.get("origin");if(!e)throw new Error("iframe origin param is required");return e}async getTopUrl(){return(await Fe({type:Ce})).topUrl}async isOAuthFlowPending(){try{return(await Fe({type:Ue})).isPending}catch(e){return Be.warn("OIDC: isOAuthFlowPending() - failed to check, assuming not pending:",e),!1}}async triggerLoginFlowViaParent({loginPath:e,windowPath:t}){Be.info("OIDC: triggerLoginFlowViaParent() - starting");const i=await this.getTopUrl(),s=new URL(i).origin,r=`${s}${t}`,n=new URL(`${window.location.origin}${e}`);n.searchParams.set(Le,s),n.searchParams.set("oauth2_top_wp_url",r),Be.info("OIDC: triggerLoginFlowViaParent() - redirecting parent to:",n.toString()),await Fe({type:xe,payload:{url:n.toString()}})}async handleLoginFlowComplete(e,t){if(!t)throw new Error("oauthUserState is required");const i=this.getWindowOriginParam(),s=t.state,r=s?.data?.[Le];if(i!==r)throw Be.error("OIDC: handleLoginFlowComplete - origin mismatch:",i,"!==",r),new Error("Invalid origin in OAuth state");try{const e=new he(t);await this.storeUser(e),this.initAccessTokenExpiringTimer(),window.dispatchEvent(new CustomEvent("oidc-auth-completed"))}catch(t){Be.error("OIDC: handleLoginFlowComplete - FAILED to store user:",t),await this.triggerLoginFlowViaParent(e)}}async triggerLogoutViaParent(e,t=!0){const i=await this.getTopUrl(),s=new URL(i).origin,r=t?`${s}${e.windowPath}`:s;await this.removeUser();const n=this.getLogoutUrl(e,r);await Fe({type:xe,payload:{url:n}})}async cleanOAuthParamsFromUrl(){try{const e=await this.getTopUrl(),t=new URL(e);t.searchParams.delete("oauth_code"),t.searchParams.delete("oauth_state"),t.searchParams.delete("start-oauth"),t.searchParams.delete(Ne),t.searchParams.delete(De),await Fe({type:Oe,payload:{url:t.toString()}})}catch(e){Be.warn("Failed to clean OAuth params from URL:",e)}}setupLoginFlowMessageListener(e){let t=!1;const i=i=>{if(i.data?.type!==Pe)return;if(i.origin!==je())return void Be.error("OIDC: origin mismatch - expected:",je(),"received:",i.origin);if(t)return void Be.debug("OIDC: LOGIN_FLOW_COMPLETE already processed, ignoring duplicate");const s=i.data.payload;s?.oauthState?(t=!0,this.handleLoginFlowComplete(e,s.oauthState).catch(e=>{Be.error("OIDC: Failed to handle login flow complete:",e),t=!1})):Be.warn("OIDC: LOGIN_FLOW_COMPLETE but no oauthState in payload")};return window.addEventListener("message",i),()=>{window.removeEventListener("message",i)}}async getTokenExpirationInfo(){const e=await this.getUser();if(!e||!e.expires_at)return{expiresAt:null,expiresInSeconds:null,isExpired:!0};const t=new Date(1e3*e.expires_at),i=Date.now(),s=Math.floor((1e3*e.expires_at-i)/1e3);return{expiresAt:t,expiresInSeconds:s,isExpired:s<=0}}async forceTokenRefresh(){return Be.info("OIDC: forceTokenRefresh() - manually triggering token refresh"),this.signinSilent()}}const Ve=Qe.getInstance();"undefined"!=typeof window&&(window.oidcAuthClient=Ve);const Xe=$e("oidc-auth:oidc-auth-redirect");function Ye(e,t){e.postMessage({status:"success",payload:t})}function Ze(e,t){e.postMessage({status:"error",payload:t})}function et({targets:e,onSuccess:t,attempt:i=1}){const s=new URLSearchParams(window.location.search);if(!s.get(Ne))return void Xe.warn("OIDC: No login_success param found, skipping");const r=s.get(De);if(r){if(!e.window?.contentWindow||!e.windowURL)return Xe.warn("Cannot forward OIDC state: iframe not available"),void(i<5?setTimeout(()=>{et({targets:e,onSuccess:t,attempt:i+1})},500):Xe.error("OIDC: Failed to forward login flow after",5,"attempts - iframe never became available"));try{const i=JSON.parse(r),s=i.state?.data?.[Le];if(s&&s!==window.location.origin)return void Xe.error("Origin mismatch in OIDC state:",s,"vs",window.location.origin);!function(e,t){const i=t.window?.contentWindow,s=t.windowURL?.origin;i&&s?i.postMessage({type:Pe,payload:e},s):Xe.warn("Cannot send OIDC state: window or origin not available")}({oauthState:i},e);const n=new URL(window.location.href);n.searchParams.delete(Ne),n.searchParams.delete(De),history.replaceState({},"",n.toString()),t?.()}catch(e){Xe.error("Failed to parse or forward OIDC state:",e)}}else Xe.warn("OIDC login complete but no state found in URL")}const tt="angie_return_url",it=g("referrer-redirect");function st(e){try{return new URL(e,window.location.origin).origin===window.location.origin}catch{return!1}}function rt(e,t){if(!st(e))return it.warn("Invalid redirect URL rejected:",e),!1;try{const i={url:e};return t&&(i.prompt=t),localStorage.setItem(tt,JSON.stringify(i)),!0}catch(e){return it.warn("localStorage not available"),!1}}function nt(){try{const e=localStorage.getItem(tt);if(!e)return null;let t;try{t=JSON.parse(e)}catch{return it.warn("Stored redirect data is not valid JSON, returning null"),null}return t.url&&"string"==typeof t.url?st(t.url)?t:(it.warn("Stored redirect URL is invalid, returning null:",t.url),null):(it.warn("Stored redirect data missing url field, returning null"),null)}catch(e){return it.warn("localStorage not available"),null}}function ot(){try{localStorage.removeItem(tt)}catch(e){it.warn("localStorage not available")}}const at=g("oauth");function ct(){const e=nt();if(e)return ot(),void(window.location.href=(t=e.url,i=e.prompt,i?`${t}#angie-prompt=${encodeURIComponent(i)}`:t));var t,i;try{localStorage.setItem("angie_sidebar_state","open")}catch(e){at.warn("localStorage not available")}setTimeout(()=>{window.toggleAngieSidebar(!0)},500)}const dt=(e,t)=>{const i=document.getElementById("angie-sidebar-container");i&&i.setAttribute("aria-hidden",t?"false":"true"),t?e.removeAttribute("tabindex"):e.setAttribute("tabindex","-1")},lt=(e,t)=>{e.postMessage({status:"success",payload:t})},gt=()=>new Promise(e=>{"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e(null)}),ht=g("sdk");var ut;(ut||(ut={})).POST_MESSAGE="postMessage";const pt=g("iframe-utils");let _t=null;const wt=()=>(_t&&document.contains(_t)||(_t=document.querySelector('iframe[src*="angie/"]')),_t),mt=(e,t)=>{pt.log("postMessageToAngieIframe",e,t);const i=wt();if(!i?.contentWindow)return!1;const s=t||(()=>{const e=wt();if(!e)return null;try{return new URL(e.src).origin}catch(e){return pt.error("Error parsing iframe URL:",e),null}})();return s?(i.contentWindow.postMessage(e,s),!0):(pt.error("Could not determine target origin for Angie iframe"),!1)},ft=g("sidebar");let yt=!1;const St="open",vt="closed";function bt(){if("undefined"==typeof window)return 370;try{const e=window.localStorage.getItem("angie_sidebar_width");if(e){const t=parseInt(e,10);if(t>=350&&t<=590)return t}}catch(e){ft.warn("localStorage not available")}return 370}function Et(){return"undefined"==typeof window?null:localStorage.getItem("angie_sidebar_state")}function kt(e){try{localStorage.setItem("angie_sidebar_state",e)}catch(e){ft.warn("localStorage not available")}}function It(e){try{localStorage.setItem("angie_sidebar_width",e.toString())}catch(e){ft.warn("localStorage not available")}}function Tt(e){document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`)}function Rt(){!function(){if("undefined"==typeof window)return!1;const e=new URLSearchParams(window.location.search);return e.has(Ne)||e.has(De)||e.has(Le)}()?At(Et()||St):function(){At(vt);try{localStorage.setItem("angie_sidebar_state",vt)}catch(e){ft.warn("localStorage not available")}}()}function At(e){"undefined"!=typeof window&&window.toggleAngieSidebar&&window.toggleAngieSidebar(e===St,!0)}function Pt(){const e=document.getElementById("angie-sidebar-container");if(!e)return;let t=!1,i=0,s=0;e.addEventListener("mousedown",r=>{const n=e.getBoundingClientRect();("rtl"===document.documentElement.dir?r.clientX<=n.left+4:r.clientX>=n.right-4)&&(t=!0,i=r.clientX,s=n.width,e.classList.add("angie-resizing"),document.body.style.cursor="ew-resize",document.body.style.userSelect="none",r.preventDefault(),r.stopPropagation())}),document.addEventListener("mousemove",e=>{if(!t)return;let r;r="rtl"===document.documentElement.dir?i-e.clientX:e.clientX-i,Tt(Math.max(350,Math.min(590,s+r))),e.preventDefault(),e.stopPropagation()}),document.addEventListener("mouseup",i=>{if(t){t=!1,e.classList.remove("angie-resizing"),document.body.style.cursor="",document.body.style.userSelect="";const r=parseInt(getComputedStyle(document.documentElement).getPropertyValue("--angie-sidebar-width"),10);It(r),mt({type:w.ANGIE_SIDEBAR_RESIZED,payload:{initialWidth:s,width:r}}),i.preventDefault(),i.stopPropagation()}}),Tt(bt())}function Ct(e){!function(){if("undefined"==typeof document||yt)return;const e="angie-sidebar-styles";if(document.getElementById(e))return void(yt=!0);const t=document.createElement("style");t.id=e,t.textContent="/* Angie Sidebar - CSS Variables */\n:root {\n --angie-sidebar-z-index: 1200; /* below MUI popups, elementor popups and media library modal */\n --angie-sidebar-width: 330px;\n --angie-sidebar-transition: margin 0.3s ease-in-out, transform 0.3s ease-in-out;\n /* Direction-aware transform values for sidebar positioning */\n --angie-sidebar-hide-transform: translateX(-100%); /* LTR: hide to the left */\n --angie-sidebar-show-transform: translateX(0);\n}\n\n/* RTL-specific transform values */\n[dir=\"rtl\"] {\n --angie-sidebar-hide-transform: translateX(100%); /* RTL: hide to the right */\n}\n\n/* Respect user's motion preferences */\n@media (prefers-reduced-motion: reduce) {\n :root {\n --angie-sidebar-transition: none;\n }\n}\n\n/* Apply transitions only when user is actively toggling */\nbody.angie-sidebar-transitioning {\n transition: var(--angie-sidebar-transition) !important;\n}\n\nbody.angie-sidebar-transitioning #angie-sidebar-container {\n transition: var(--angie-sidebar-transition) !important;\n}\n\n/* Layout (default) - Push content */\n@media (min-width: 768px) {\n body.angie-sidebar-active {\n padding-inline-start: var(--angie-sidebar-width) !important;\n }\n\n #angie-sidebar-container {\n position: fixed;\n top: 0;\n inset-inline-start: 0;\n width: var(--angie-sidebar-width);\n height: 100vh;\n z-index: var(--angie-sidebar-z-index) !important; /* below elementor popups and media library modal */\n background: #FCFCFC;\n transform: var(--angie-sidebar-hide-transform);\n outline: none;\n overflow: hidden;\n /* No default transition - only when transitioning */\n }\n\n /* Resize handle */\n #angie-sidebar-container::after {\n content: '';\n position: absolute;\n top: 0;\n inset-inline-end: 0;\n width: 4px;\n height: 100%;\n cursor: ew-resize;\n background: transparent;\n z-index: 1000001;\n }\n\n /* Pink border during resize */\n #angie-sidebar-container.angie-resizing {\n border-inline-end-color: #ff69b4 !important;\n border-inline-end-width: 2px !important;\n }\n\n /* Disable iframe pointer events during resize */\n #angie-sidebar-container.angie-resizing iframe#angie-iframe {\n pointer-events: none !important;\n }\n}\n\n/* Active states */\nbody.angie-sidebar-active #angie-sidebar-container {\n transform: var(--angie-sidebar-show-transform);\n}\n\n/* Studio mode - sidebar takes full width */\n@media (min-width: 768px) {\n html.angie-studio-active body.angie-sidebar-active #angie-sidebar-container {\n width: 100%;\n }\n}\n\n/* High contrast mode support */\n@media (prefers-contrast: high) {\n #angie-sidebar-container {\n border-color: #000;\n box-shadow: none;\n }\n}\n\n/* Screen reader only class */\n.angie-sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n/* Plugin conflict resolution */\nbody.angie-sidebar-active {\n /* Reset common conflicting styles */\n box-sizing: border-box !important;\n position: relative !important;\n}\n\n#angie-sidebar-toggle {\n z-index: 99999 !important;\n}\n";const i=document.head||document.getElementsByTagName("head")[0];i.insertBefore(t,i.firstChild),yt=!0}(),"undefined"!=typeof window&&(window.toggleAngieSidebar=function(e){return function(t,i){const s=document.body,r=document.getElementById("angie-sidebar-container");if(!r)return void ft.warn("Required elements not found!");const n=s.classList.contains("angie-sidebar-active"),o=void 0!==t?t:!n;i||(s.classList.add("angie-sidebar-transitioning"),setTimeout(function(){s.classList.remove("angie-sidebar-transitioning")},300)),o?s.classList.add("angie-sidebar-active"):s.classList.remove("angie-sidebar-active"),o&&setTimeout(function(){mt({type:"focusInput"})},i?0:300),e&&e(o,r,i),kt(o?St:vt);const a=new CustomEvent("angieSidebarToggle",{detail:{isOpen:o,sidebar:r,skipTransition:i}});document.dispatchEvent(a),mt({type:w.ANGIE_SIDEBAR_TOGGLED,payload:{state:o?"opened":"closed"}})}}(e),window.addEventListener("message",function(e){if(e.data&&"toggleAngieSidebar"===e.data.type){const{force:t,skipTransition:i}=e.data.payload||{};window.toggleAngieSidebar&&window.toggleAngieSidebar(t,i)}}))}const xt=g("iframe"),Ot=async()=>{if(E.iframe?.contentWindow&&E.iframeUrlObject)try{xt.log("Disabling navigation prevention in Angie iframe"),E.iframe.contentWindow.postMessage({type:w.ANGIE_DISABLE_NAVIGATION_PREVENTION},E.iframeUrlObject.origin),await new Promise(e=>setTimeout(e,100))}catch(e){throw xt.error("Failed to disable navigation prevention:",e),e}else xt.warn("Cannot disable navigation prevention: iframe or origin not available")},Ut=async e=>{if(window.screen.availWidth<=768)return void xt.log("Mobile detected, skipping iframe injection");let t=document.getElementById("angie-sidebar-container");if(!t){const e=performance.now();if(xt.log("⏱️ Waiting for sidebar container..."),await new Promise(e=>{let i=0;const s=setInterval(()=>{t=document.getElementById("angie-sidebar-container"),i++,(t||i>20)&&(clearInterval(s),t&&e())},100);setTimeout(()=>{if(clearInterval(s),t)return void e();const i=new MutationObserver(()=>{t=document.getElementById("angie-sidebar-container"),t&&(i.disconnect(),e())});i.observe(document.body,{childList:!0,subtree:!0}),setTimeout(()=>{i.disconnect(),e()},8e3)},2e3)}),xt.log(`⏱️ Sidebar container detection took: ${(performance.now()-e).toFixed(2)}ms`),!t)return void xt.error("Sidebar container not found")}const{iframe:i,iframeUrlObject:s}=await(async e=>{const t=e.origin,i=new URL(e.path,t),s=i.pathname.slice(1).replace(/\//,"--")+"-"+Math.random().toString(36).substring(7);return new Promise(r=>{const n=new URL(t);n.pathname=i.pathname;const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";if(n.searchParams.append("colorScheme",e.uiTheme||o||"light"),n.searchParams.append("sdkVersion",e.sdkVersion),n.searchParams.append("instanceId",s),n.searchParams.append("origin",window.location.origin),e.isRTL&&n.searchParams.append("isRTL",e.isRTL?"true":"false"),"localhost"===window.location.hostname&&window.location.search.includes("debug_error")){const e=new URLSearchParams(window.location.search).get("debug_error");e&&n.searchParams.append("debug_error",e)}i.searchParams.forEach((e,t)=>{n.searchParams.set(t,e)}),n.searchParams.set("ver",(new Date).getTime().toString());const a=e.parent||document,c=a.createElement("iframe"),d={"background-color":"transparent","color-scheme":"normal",...e.css};window.addEventListener("message",async e=>{if(e.origin===n.origin)switch(e.data.type){case f.ANGIE_READY:r({iframe:c,iframeUrlObject:n});break;case f.ANGIE_LOADED:c.contentWindow?.postMessage({type:f.HOST_READY,instanceId:s},n.origin)}}),c.setAttribute("src",n.href),c.id="angie-iframe",c.setAttribute("frameborder","0"),c.setAttribute("scrolling","no"),c.setAttribute("style",Object.entries(d).map(([e,t])=>`${e}: ${t}`).join("; ")),c.setAttribute("allow","clipboard-write; clipboard-read"),e.insertCallback?e.insertCallback(c):a.body.appendChild(c)})})({origin:e.origin||"https://angie.elementor.com",path:"angie/wp-admin",insertCallback:e=>{xt.log("Injecting Angie iframe into sidebar container"),e.setAttribute("title","Angie AI Assistant"),e.setAttribute("role","application"),e.setAttribute("aria-label","Angie AI Assistant Interface");const i=document.getElementById("angie-sidebar-loading");i&&(i.textContent=""),t?.appendChild(e),dt(e,!0),e.addEventListener("load",()=>{e.focus()})},css:{width:"100%",height:"100%",border:"none",outline:"none"},uiTheme:e.uiTheme,isRTL:e.isRTL,sdkVersion:"1.3.0"});E.iframe=i,E.iframeUrlObject=s,window.addEventListener("message",e=>{if(e.origin===E.iframeUrlObject?.origin)switch(e.data.type){case m.SET:window.localStorage.setItem(e.data.key,e.data.value);break;case m.GET:{const t=e.ports[0],i=window.localStorage.getItem(e.data.key);t.postMessage({value:i});break}}}),(e=>{window.addEventListener("message",async t=>{const i=t.origin===window.location.origin,s=t.origin===e.iframeUrlObject?.origin;if(i||s)switch(t?.data?.type){case w.SDK_ANGIE_ALL_SERVERS_REGISTERED:break;case w.SDK_ANGIE_READY_PING:{const e=t.ports[0];ht.log("Angie is ready",t),lt(e,{message:"Angie is ready"});break}case w.SDK_REQUEST_CLIENT_CREATION:{const i=t.data.payload;try{const s=t.ports[0],r=new MessageChannel;r.port1.onmessage=e=>{s.postMessage({success:!0,data:e.data})};const n={type:w.SDK_REQUEST_CLIENT_CREATION,payload:{success:!0,...i,clientId:`dynamic-client-${i.serverName}-${i.serverVersion}-${Date.now()}`,requestId:t.data.payload.requestId},timestamp:Date.now()};if(!e.iframe)throw new Error("Iframe not found");e.iframe.contentWindow?.postMessage(n,e.iframeUrlObject?.origin||"",[r.port2])}catch(e){ht.error(`Failed to create client for SDK server "${i.serverName}":`,e)}break}case w.SDK_TRIGGER_ANGIE:ht.log("SDK Trigger Angie received",t.data);try{const{requestId:i,prompt:s,context:r}=t.data.payload;if(!e.iframe)throw new Error("Iframe not found");e.iframe.contentWindow?.postMessage({type:w.SDK_TRIGGER_ANGIE,payload:{requestId:i,prompt:s,context:r}},e.iframeUrlObject?.origin||""),window.postMessage({type:w.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!0,requestId:i,response:"Angie triggered successfully"}},window.location.origin)}catch(e){ht.error("Failed to trigger Angie:",e),window.postMessage({type:w.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!1,requestId:t.data.payload?.requestId,error:e instanceof Error?e.message:"Unknown error"}},window.location.origin)}}})})(E),function({trustedOrigin:e,onOAuthParamsCleared:t}){window.addEventListener("message",i=>{if(i.origin!==e)return;const s=i.ports?.[0];switch(i.data.type){case Ce:if(!s)return;Ye(s,{topUrl:window.location.href});break;case xe:window.location.href=i.data.payload.url;break;case Oe:{if(!s)return;const e=i.data.payload.url;if(!history?.replaceState)return void Ze(s,{message:"URL update not supported in this browser"});try{const i=window.location.href;history.replaceState({},"",e),function(e,t){const i=new URL(e).searchParams,s=new URL(t).searchParams,r=[Ne,De,Le];return r.some(e=>i.has(e))&&!r.some(e=>s.has(e))}(i,e)&&t?.(),Ye(s,{message:"URL updated successfully"})}catch(e){Ze(s,{message:"URL update failed: "+(e instanceof Error?e.message:"Unknown error")})}break}case Ue:if(!s)return;Ye(s,{isPending:"true"===new URLSearchParams(window.location.search).get(Ne)})}})}({trustedOrigin:E.iframeUrlObject?.origin??"",onOAuthParamsCleared:ct}),(()=>{const e={window:E.iframe,windowURL:E.iframeUrlObject};window.addEventListener("load",()=>{at.log("OIDC: Window load event fired, forwarding OIDC state if present"),et({targets:e,onSuccess:ct})}),et({targets:e,onSuccess:ct})})(),window.addEventListener("message",async t=>{if([window.location.origin,e.origin||"https://angie.elementor.com"].includes(t.origin))if(t?.data?.type===w.ANGIE_CHAT_TOGGLE)E.open=t.data.open,E.iframe&&dt(E.iframe,E.open);else if(t?.data?.type===w.ANGIE_STUDIO_TOGGLE){const e=t.data.isStudioOpen;if(!E.iframe)return;if(e)document.documentElement.classList.add("angie-studio-active");else{const e=bt();document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`),document.documentElement.classList.remove("angie-studio-active")}}else if(t?.data?.type===w.ANGIE_NAVIGATE_TO_URL){const{url:e="",confirmed:i=!1}=t.data.payload||{};if(!i)return void xt.log("Navigation requires user confirmation");if(!((e,t=[])=>{const i=0===t.length&&"undefined"!=typeof window?[window.location.origin]:t;if(!e.startsWith("http"))return!1;try{const t=new URL(e);return i.includes(t.origin)}catch{return!1}})(e))return void xt.error("Navigation blocked: Invalid or unsafe URL",{url:e});await Ot(),window.location.assign(e)}else if(t?.data?.type===w.ANGIE_PAGE_RELOAD){const{confirmed:e=!1}=t.data.payload||{};if(!e)return void xt.log("Page reload requires user confirmation");xt.log("Page reload confirmed - disabling navigation prevention and reloading"),await Ot(),setTimeout(()=>{window.location.reload()},50)}else t?.data?.type===f.RESET_HASH&&(window.location.hash="",lt(t.ports[0],{message:"Hash reset successfully"}))})},Lt=g("registration-queue");class Nt{queue=[];isProcessing=!1;add(e){const t={id:this.generateId(e),config:e,timestamp:Date.now(),status:"pending"};return this.queue.push(t),Lt.log(`Added server "${e.name}" to queue`),t}getAll(){return[...this.queue]}getPending(){return this.queue.filter(e=>"pending"===e.status)}updateStatus(e,t,i){const s=this.queue.find(t=>t.id===e);s&&(s.status=t,i?s.error=i:"pending"!==t&&"registered"!==t||delete s.error,Lt.log(`Updated server ${e} status to ${t}`))}async processQueue(e){if(this.isProcessing)return void Lt.log("Already processing queue");this.isProcessing=!0;const t=this.getPending();Lt.log(`Processing ${t.length} pending registrations`);try{for(const i of t)try{await e(i),this.updateStatus(i.id,"registered")}catch(e){const t=e instanceof Error?e.message:String(e);this.updateStatus(i.id,"failed",t),Lt.error(`Failed to process registration ${i.id}:`,t)}}finally{this.isProcessing=!1}}clear(){this.queue=[],Lt.log("Cleared all registrations")}resetAllToPending(){if(this.isProcessing)return Lt.log("Cannot reset to pending - processing in progress"),!1;const e=this.queue.filter(e=>"registered"===e.status).length,t=this.queue.filter(e=>"failed"===e.status).length;return this.queue.forEach(e=>{"pending"!==e.status&&(e.status="pending",delete e.error)}),Lt.log(`Reset ${e+t} registrations to pending`),!0}remove(e){const t=this.queue.findIndex(t=>t.id===e);return-1!==t&&(this.queue.splice(t,1),Lt.log(`Removed registration ${e}`),!0)}generateId(e){return`reg_${e.name}_${e.version}_${Date.now()}`}}class Dt{angieDetector;clientManager;logger;registrationQueue;isInitialized=!1;instanceId;constructor(){this.instanceId=Math.random().toString(36).substring(2,8),this.logger=g({instanceId:this.instanceId}),this.logger.log("Constructor called - initializing SDK"),this.angieDetector=new S,this.registrationQueue=new Nt,this.clientManager=new b,this.logger.log("Setting up event handlers"),this.setupAngieReadyHandler(),this.setupServerInitHandler(),this.setupReRegistrationHandler(),this.logger.log("SDK initialization complete")}async loadSidebar(e){Ct(),await Ut({origin:e?.origin||"https://angie.elementor.com",uiTheme:e?.uiTheme||"light",isRTL:e?.isRTL||!1,...e}),this.setupPromptHashDetection()}setupReRegistrationHandler(){window.addEventListener("message",e=>{if(e.data?.type===w.SDK_ANGIE_REFRESH_PING)if(this.logger.log("Angie refresh ping received"),this.registrationQueue.resetAllToPending()){const e=this.registrationQueue.getPending().length;this.logger.log(`Successfully reset ${e} registrations, processing queue`),this.handleAngieReady()}else this.logger.log("Skipping queue reset - processing already in progress")})}setupAngieReadyHandler(){this.angieDetector.waitForReady().then(e=>{e.isReady?this.handleAngieReady():this.logger.warn("Angie not detected - servers will remain queued")}).catch(e=>{this.logger.error("Error waiting for Angie:",e)})}async handleAngieReady(){this.logger.log("Angie is ready, processing queued registrations");try{await this.registrationQueue.processQueue(async e=>{this.logger.log(`processQueue callback called for "${e.config.name}"`),await this.processRegistration(e)}),this.isInitialized=!0,this.logger.log("Initialization complete")}catch(e){this.logger.error("Error processing registration queue:",e)}}async processRegistration(e){this.logger.log(`Processing registration for server "${e.config.name}" (ID: ${e.id})`);try{this.logger.log(`Calling clientManager.requestClientCreation for "${e.config.name}"`);const t={...e,instanceId:this.instanceId};await this.clientManager.requestClientCreation(t),this.logger.log(`Successfully registered server "${e.config.name}"`)}catch(t){throw this.logger.error(`Failed to register server "${e.config.name}":`,t),t}}registerLocalServer(e){return e.type=_.LOCAL,e.transport=u.POST_MESSAGE,this.registerServer(e)}registerRemoteServer(e){return e.type=_.REMOTE,this.registerServer(e)}isLocalServerConfig(e){return e.type===_.LOCAL||!e.type&&"server"in e}isRemoteServerConfig(e){return e.type===_.REMOTE&&"url"in e}async registerServer(e){if(!e.type)return this.logger.warn("For a local server, please use registerLocalServer instead of registerServer"),void this.registerLocalServer(e);if(this.logger.log(`registerServer called for "${e.name}"`),!e.name)throw new Error("Server name is required");if(!e.description)throw new Error("Server description is required");if(this.isLocalServerConfig(e)&&!e.server)throw new Error("Server instance is required for local servers");this.logger.log(`Registering server "${e.name}"`);const t=this.registrationQueue.add(e);if(this.logger.log(`Added registration to queue: ${t.id}`),this.angieDetector.isReady())try{await this.processRegistration(t),this.registrationQueue.updateStatus(t.id,"registered"),this.logger.log(`Server "${e.name}" registered successfully`)}catch(e){const i=e instanceof Error?e.message:String(e);throw this.registrationQueue.updateStatus(t.id,"failed",i),e}else this.logger.log(`Server "${e.name}" queued until Angie is ready`)}getRegistrations(){return this.registrationQueue.getAll()}getPendingRegistrations(){return this.registrationQueue.getPending()}isAngieReady(){return this.angieDetector.isReady()}isReady(){return this.isInitialized}async waitForReady(){if(!(await this.angieDetector.waitForReady()).isReady)throw new Error("Angie is not available");for(;!this.isInitialized;)await new Promise(e=>setTimeout(e,100))}async triggerAngie(e){if(!this.isAngieReady())throw new Error("Angie is not ready. Please wait for Angie to be available before triggering.");const t=this.generateRequestId(),i=e.options?.timeout||3e4;return new Promise((s,r)=>{const n=setTimeout(()=>{r(new Error("Angie trigger request timed out"))},i),o=e=>{e.data?.type===w.SDK_TRIGGER_ANGIE_RESPONSE&&e.data?.payload?.requestId===t&&(clearTimeout(n),window.removeEventListener("message",o),s(e.data.payload))};window.addEventListener("message",o);const a={type:w.SDK_TRIGGER_ANGIE,payload:{requestId:t,prompt:e.prompt,options:e.options,context:{pageUrl:window.location.href,pageTitle:document.title,...e.context}},timestamp:Date.now()};this.logger.log(`Triggering Angie with prompt (Request ID: ${t})`),window.postMessage(a,window.location.origin)})}destroy(){this.registrationQueue.clear(),this.logger.log("SDK destroyed")}setupServerInitHandler(){window.addEventListener("message",e=>{e.data?.type===w.SDK_REQUEST_INIT_SERVER&&(this.logger.log("Server init request received"),this.handleServerInitRequest(e))})}handleServerInitRequest(e){const{clientId:t,serverId:i,instanceId:s}=e.data.payload||{};if(t&&i)if(this.logger.log(`Server init request received - Request instanceId: ${s}, This instanceId: ${this.instanceId}`),s&&s!==this.instanceId)this.logger.log(`Ignoring server init request for different instance. Request instanceId: ${s}, this instanceId: ${this.instanceId}`);else{this.logger.log(`Handling server init request for clientId: ${t}, serverId: ${i}`);try{const t=this.registrationQueue.getAll().find(e=>e.id===i);if(!t)return void this.logger.error(`No registration found for serverId: ${i}`);if("type"in t.config&&"remote"===t.config.type)return void this.logger.log("Remote server registration detected; skipping local connect");const s=e.ports[0];if(!s)return void this.logger.error("No port provided in server init request");const r=t.config.server;this.migrateInstructionsCompat(r);const n=new v(s);r.connect(n),this.logger.log(`Server "${t.config.name}" initialized successfully`)}catch(e){this.logger.error(`Error initializing server for clientId ${t}:`,e)}}else this.logger.error("Invalid server init request - missing clientId or serverId")}migrateInstructionsCompat(e){try{const t="server"in e&&e.server?e.server:e,i=t._serverInfo,s=t._instructions;i?.instructions&&!s&&(t._instructions=i.instructions,this.logger.log("Migrated instructions from serverInfo to serverOptions (backward compat)"))}catch{}}generateRequestId(){return`${this.instanceId}-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}async handlePromptHash(){const e=window.location.hash;if(e.startsWith("#angie-prompt="))try{const t=e.replace("#angie-prompt=",""),i=decodeURIComponent(t);if(!i)return void this.logger.warn("Empty prompt detected in hash");this.logger.log("Detected prompt in hash:",i),await this.waitForReady();const s=await this.triggerAngie({prompt:i,context:{source:"hash-parameter",pageUrl:window.location.href,timestamp:(new Date).toISOString()}});this.logger.log("Triggered successfully from hash:",s),window.location.hash=""}catch(e){this.logger.error("Failed to trigger from hash:",e)}}setupPromptHashDetection(){this.handlePromptHash(),window.addEventListener("hashchange",()=>this.handlePromptHash())}}const qt=g("navigation"),Mt=(e,t)=>{if(wt()){t.isOpen&&window.toggleAngieSidebar&&window.toggleAngieSidebar(!0);const i=mt({type:"angie-route-navigation",path:e,payload:t});return i||qt.error("Failed to post navigation message to Angie iframe"),i}return qt.error("Angie iframe not found"),!1};export{St as ANGIE_SIDEBAR_STATE_OPEN,S as AngieDetector,u as AngieLocalServerTransport,h as AngieMCPTransport,Dt as AngieMcpSdk,p as AngieRemoteServerTransport,_ as AngieServerType,v as BrowserContextTransport,b as ClientManager,f as HostEventType,m as HostLocalStorageEventType,w as MessageEventType,Nt as RegistrationQueue,Tt as applyWidth,ot as clearReferrerRedirect,Ot as disableNavigationPrevention,wt as getAngieIframe,Et as getAngieSidebarSavedState,nt as getReferrerRedirect,Ct as initAngieSidebar,Pt as initializeResize,Rt as loadState,bt as loadWidth,Mt as navigateAngieIframe,kt as saveState,It as saveWidth,rt as setReferrerRedirect,dt as toggleAngieSidebar,gt as waitForDocumentReady};
|