@descope/applications-portal-widget 0.3.11 → 0.3.12
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/esm/index.js +2 -2
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
|
|
2
2
|
/**
|
|
3
|
-
* @descope/applications-portal-widget v0.3.
|
|
3
|
+
* @descope/applications-portal-widget v0.3.12
|
|
4
4
|
*/
|
|
5
|
-
this["descope-applications-portal-widget"]=function(){"use strict";var e=function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var s in t=arguments[n])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},e.apply(this,arguments)};function t(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]])}return n}function n(e,t,n,r){return new(n||(n=Promise))((function(s,i){function o(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}function r(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}function s(e,t,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,n):s?s.value=n:t.set(e,n),n}function i(...e){return t=>e.reduce(((e,t)=>t(e)),t)}"function"==typeof SuppressedError&&SuppressedError;const o=e=>{const t=document.createElement("template");return t.innerHTML=e,t},a=e=>{const t=Symbol((e=>{const t=e.toString();let n=0;for(let e=0;e<t.length;e++)n=(n<<5)-n+t.charCodeAt(e),n&=n;return n.toString(16)})(e));return n=>{if(n[t])return n;const r=e(n);return r[t]=!0,r}};var c,l,d,u;function h(e,t){const n=Object.getOwnPropertyNames(e),r=Object.getOwnPropertyNames(t);if(n.length!==r.length)return!1;for(let r=0;r<n.length;r+=1){const s=n[r],i=e[s],o=t[s];if(null===i||null===o){if(i!==o)return!1}else if("object"==typeof i&&"object"==typeof o){if(!h(i,o))return!1}else if(i!==o)return!1}return!0}let p=class{constructor(e={},{forceUpdate:t=!1}={}){c.set(this,void 0),l.set(this,{}),d.set(this,0),u.set(this,!0),this.update=e=>{const t="function"==typeof e?e(r(this,c,"f")):e,n=Object.assign(Object.assign({},r(this,c,"f")),t);if(r(this,u,"f")||!h(r(this,c,"f"),n)){const e=r(this,c,"f");s(this,c,n,"f"),Object.freeze(r(this,c,"f")),setTimeout((()=>{Object.values(r(this,l,"f")).forEach((t=>t(n,e,((e,t)=>n=>e[n]!==t[n])(n,e))))}),0)}},s(this,c,e,"f"),s(this,u,t,"f")}get current(){return Object.assign({},r(this,c,"f"))}subscribe(e){return s(this,d,r(this,d,"f")+1,"f"),r(this,l,"f")[r(this,d,"f")]=e,r(this,d,"f").toString()}unsubscribe(e){const t=!!r(this,l,"f")[e];return t&&delete r(this,l,"f")[e],t}unsubscribeAll(){return s(this,l,{},"f"),!0}};c=new WeakMap,l=new WeakMap,d=new WeakMap,u=new WeakMap;const g=["error","warn","info","debug"],f=a((e=>{var t,n,i,o;return o=class extends e{constructor(){super(...arguments),t.add(this),n.set(this,r(this,t,"m",i).call(this,console))}set logger(e){s(this,n,r(this,t,"m",i).call(this,e||console),"f")}get logger(){return r(this,n,"f")}onLogEvent(e,t){}},n=new WeakMap,t=new WeakSet,i=function(e){return g.reduce(((t,n)=>(t[n]=(...t)=>{var r;this.onLogEvent(n,t),null===(r=e[n])||void 0===r||r.call(e,...t)},t)),{})},o})),m="undefined"!=typeof localStorage,w=m&&localStorage.getItem("base.content.url")||"",_=(e,t)=>!t&&`${e} cannot be empty, please make sure to set this attribute`,y=a((e=>{var t,n;return n=class extends e{constructor(){super(...arguments),t.set(this,!0)}connectedCallback(){var e,n;null===(e=super.connectedCallback)||void 0===e||e.call(this),(null===(n=this.shadowRoot)||void 0===n?void 0:n.isConnected)&&r(this,t,"f")&&(s(this,t,!1,"f"),this.init())}async init(){}},t=new WeakMap,n})),v=a((e=>{var t,n;const s=i(f,y)(e);return n=class extends s{constructor(){super(...arguments),t.set(this,{})}async init(){var e,n,s;await(null===(e=super.init)||void 0===e?void 0:e.call(this)),n=this,s=e=>{var n;null===(n=r(this,t,"f")[e])||void 0===n||n.forEach((t=>{t(e,this.getAttribute(e))}))},Array.from(n.attributes).forEach((e=>s(e.name))),new MutationObserver((e=>{e.forEach((e=>{"attributes"===e.type&&s(e.attributeName)}))})).observe(n,{attributes:!0})}observeAttribute(e,n){r(this,t,"f")[e]||(r(this,t,"f")[e]=[]);const s=r(this,t,"f")[e].push(n);return()=>r(this,t,"f")[e].splice(s,1)}observeAttributes(e,t){const n=e.reduce(((e,n)=>(e.push(this.observeAttribute(n,t)),e)),[]);return()=>n.forEach((e=>e()))}},t=new WeakMap,n})),b=e=>t=>{var n,s,o;const a=i(f,y,v)(t),c=Object.keys(e);return o=class extends a{constructor(...e){super(...e),n.add(this),this.observeAttributes(c,r(this,n,"m",s).bind(this))}async init(){var e;c.forEach((e=>r(this,n,"m",s).call(this,e,this.getAttribute(e)))),await(null===(e=super.init)||void 0===e?void 0:e.call(this))}},n=new WeakSet,s=function(t,n){const r=e[t],s="function"==typeof r?r(t,n):r;s&&this.logger.error(s)},o};b.missingAttrValidator=_;const S=a((e=>{const t=i(b({"project-id":_}))(e);return class extends t{get projectId(){return this.getAttribute("project-id")}}})),k=a((e=>class extends e{get baseUrl(){return this.getAttribute("base-url")||""}})),I="Trying the next fallback URL...";function x({projectId:e,filename:t,assetsFolder:n="v2-beta",baseUrl:r="https://static.descope.com/pages"}){const s=new URL(r);return s.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(s.pathname,e,n,t),s.baseUrl=r,s}const E=a((e=>{var t,n,o,a,c;const l=i(f,S,k)(e);return c=class extends l{constructor(){super(...arguments),t.add(this),n.set(this,void 0),o.set(this,void 0)}async fetchStaticResource(e,n){const i=r(this,t,"m",a).call(this,e),c=Array.isArray(i)?e=>{if(e!==i.length-1){const{baseUrl:t}=i[e];s(this,o,t,"f")}}:null;try{const e=await(async(e,t,{logger:n,onSuccess:r})=>{const s=Array.isArray(e)?e:[e];for(let e=0;e<s.length;e++){const i=s[e],o=e===s.length-1;try{const s=await fetch(i.toString(),t);if(s.ok)return null==r||r(e),s;const a=`Error fetching URL ${i} [${s.status}]`;if(o)throw new Error(a);null==n||n.debug(`${a}. ${I}`)}catch(e){const t=`Error fetching URL ${i} [${e.message}]`;if(o)throw new Error(t);null==n||n.debug(`${t}. ${I}`)}}})(i,{cache:"default"},{logger:this.logger,onSuccess:c});return{body:await e[n](),headers:Object.fromEntries(e.headers.entries())}}catch(e){this.logger.error(e.message)}}get baseStaticUrl(){return this.getAttribute("base-static-url")}},n=new WeakMap,o=new WeakMap,t=new WeakSet,a=function(e){const t=w||this.baseStaticUrl;if(t)return x({projectId:this.projectId,filename:e,baseUrl:t});const i=r(this,n,"f")!==this.baseUrl,a=i&&!!this.baseUrl;i&&(s(this,n,this.baseUrl,"f"),s(this,o,void 0,"f"));const c=x({projectId:this.projectId,filename:e,baseUrl:r(this,o,"f")});if(!a)return c;return[x({projectId:this.projectId,filename:e,baseUrl:this.baseUrl+"/pages"}),c]},c})),O=a((e=>{var t,n;const s=i(b({"project-id":_}))(e);return n=class extends s{constructor(){super(...arguments),t.set(this,new Map)}onReset(e,n){if(r(this,t,"f").has(e))throw new Error(`Callback for sectionId ${e} already exists`);return r(this,t,"f").set(e,n),()=>{r(this,t,"f").delete(e)}}async reset(...e){0===e.length?await Promise.all(Array.from(r(this,t,"f").values()).map((e=>e()))):await Promise.all(e.map((e=>{var n;if(!r(this,t,"f").has(e))throw new Error(`Callback for sectionId ${e} does not exist`);return null===(n=r(this,t,"f").get(e))||void 0===n?void 0:n()})))}},t=new WeakMap,n})),T=a((e=>{var t,n,o,a,c;const l=i(E,O,y)(e);return c=class extends l{constructor(){super(...arguments),t.add(this),o.set(this,void 0),a.set(this,(async()=>{try{const{body:e,headers:t}=await this.fetchStaticResource("config.json","json");return{projectConfig:e,executionContext:{geo:t["x-geo"]}}}catch(e){this.logger.error("Cannot fetch config file","make sure that your projectId & flowId are correct")}}))}async init(){await super.init(),this.onReset("config",r(this,t,"m",n).bind(this))}get config(){return r(this,o,"f")||s(this,o,r(this,a,"f").call(this),"f"),r(this,o,"f")}},o=new WeakMap,a=new WeakMap,t=new WeakSet,n=function(){s(this,o,void 0,"f")},c})),C=a((e=>{var t,n,o,a,c,l,d;return d=class extends(i(y,f)(e)){constructor(){super(...arguments),t.add(this),n.set(this,void 0),this.attributeChangedCallback=(e,n,s)=>{var i;null===(i=super.attributeChangedCallback)||void 0===i||i.call(this,e,n,s),"debug"===e&&r(this,t,"m",c).call(this)}}get debug(){return"true"===this.getAttribute("debug")}onLogEvent(e,n){var s;null===(s=super.onLogEvent)||void 0===s||s.call(this,e,n),"error"===e&&r(this,t,"m",l).call(this,n[0]||"Error",n[1])}async init(){var e;await(null===(e=super.init)||void 0===e?void 0:e.call(this)),r(this,t,"m",c).call(this)}},n=new WeakMap,t=new WeakSet,o=function(){var e;null===(e=r(this,n,"f"))||void 0===e||e.remove(),s(this,n,null,"f")},a=async function(){s(this,n,document.createElement("descope-debugger"),"f"),Object.assign(r(this,n,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),await Promise.resolve().then((function(){return eo})),document.body.appendChild(r(this,n,"f"))},c=function(){this.debug?r(this,t,"m",a).call(this):r(this,t,"m",o).call(this)},l=function(e,t){var s;e&&(null===(s=r(this,n,"f"))||void 0===s||s.updateData({title:e,description:t}))},d})),j="load-descope-ui",R="base.ui.components.url",P=m&&localStorage.getItem(R)||"https://descopecdn.com/npm/@descope/web-components-ui@<version>/dist/umd/index.js",U=m&&localStorage.getItem(R)||"https://static.descope.com/npm/@descope/web-components-ui@<version>/dist/umd/index.js",A=m&&localStorage.getItem(R)||"https://cdn.jsdelivr.net/npm/@descope/web-components-ui@<version>/dist/umd/index.js",M=e=>{const t=document.createElement("script");return t.id=e,t},$=(e,t)=>e.replace("<version>",t),N=a((e=>{var t,n,o,a,c,l,d,u,h,p,g,m;const w=i(f,T)(e);return m=class extends w{constructor(){super(...arguments),t.add(this),n.set(this,Symbol("errorCbs")),o.set(this,Symbol("loadCbs")),h.set(this,void 0)}get descopeUi(){return r(this,h,"f")||s(this,h,r(this,t,"m",g).call(this),"f"),r(this,h,"f")}async loadDescopeUiComponents(e){const n=Array.isArray(e)?e:(e=>[...Array.from(e.content.querySelectorAll("*")).reduce(((e,t)=>t.localName.startsWith("descope-")?e.add(t.localName):e),new Set)])(e);return Promise.all(n.map((e=>r(this,t,"m",p).call(this,e))))}get baseCdnUrl(){return this.getAttribute("base-cdn-url")}},n=new WeakMap,o=new WeakMap,h=new WeakMap,t=new WeakSet,a=async function(){var e;const t=await this.config,n=null===(e=null==t?void 0:t.projectConfig)||void 0===e?void 0:e.componentsVersion;return n?this.logger.debug(`Got component version "${n}"`):this.logger.error("Could not get components version"),n},c=function(e){const t=r(this,n,"f"),s=r(this,o,"f");e[t]=[],e[s]=[],Object.defineProperty(e,"onerror",{set(n){e[t].push(n)}}),Object.defineProperty(e,"onload",{set(t){e[s].push(t)}})},l=async function(e,n,s,i){this.logger.debug("Trying to load DescopeUI from a fallback URL");const o=M(s);document.body.append(o),o.addEventListener("error",(()=>{e.forEach((e=>e(`Cannot load DescopeUI from fallback URL, Make sure this URL is valid and return the correct script: "${o.src}"`)))})),o.addEventListener("load",(()=>{n.forEach((e=>e()))})),o.src=$(i,await r(this,t,"m",a).call(this))},d=function(e){e.addEventListener("error",(()=>{e[r(this,n,"f")].forEach((t=>t(`Cannot load DescopeUI from main URL, Make sure this URL is valid and return the correct script: "${e.src}"`))),r(this,t,"m",l).call(this,[r(this,t,"m",l).bind(this,e[r(this,n,"f")],e[r(this,o,"f")],"load-descope-ui-fallback-script-2",A),...e[r(this,n,"f")]],e[r(this,o,"f")],"load-descope-ui-fallback-script",U)})),e.addEventListener("load",(()=>{e[r(this,o,"f")].forEach((e=>e()))}))},u=async function(){if(document.querySelector(`script#${j}`))this.logger.debug("DescopeUI loading script already exists",this);else{this.logger.debug("DescopeUI loading script does not exist, creating it",this);const e=M(j);document.body.append(e),r(this,t,"m",c).call(this,e),r(this,t,"m",d).call(this,e),e.src=$(this.baseCdnUrl||P,await r(this,t,"m",a).call(this))}return document.getElementById(j)},p=async function(e){if(!!customElements.get(e))return void this.logger.debug(`Loading component "${e}" is skipped as it is already defined`);const t=await this.descopeUi;if(t[e])try{return await t[e]()}catch(t){if("NotSupportedError"!==t.name)throw t;console.debug(`Encountered an error while attempting to define the "${e}" component, it is likely that this component is already defined`)}else this.logger.error(`Cannot load UI component "${e}"`,`Descope UI does not have a component named "${e}", available components are: "${Object.keys(t).join(", ")}"`)},g=function(){return new Promise((e=>{globalThis.DescopeUI&&e(globalThis.DescopeUI),r(this,t,"m",u).call(this).then((t=>{t.onerror=this.logger.error,t.onload=()=>{this.logger.debug("DescopeUI was loaded"),e(globalThis.DescopeUI)},setTimeout((()=>{globalThis.DescopeUI&&e(globalThis.DescopeUI)}))}))}))},m})),q="content-root",D="root",L=a((e=>class extends e{constructor(...e){var t,n,r,s;super(...e),this.attachShadow({mode:"open"}).innerHTML=`\n <div id="${D}">\n <div id="${q}"></div>\n </div>\n `;const i=new CSSStyleSheet;i.replaceSync(`\n #${D}, #${q} {\n height: 100%;\n }\n #${D} {\n position: relative;\n height: fit-content;\n }\n `),null!==(t=(s=this.shadowRoot).adoptedStyleSheets)&&void 0!==t||(s.adoptedStyleSheets=[]),this.shadowRoot.adoptedStyleSheets=[...this.shadowRoot.adoptedStyleSheets,i],this.contentRootElement=null===(n=this.shadowRoot)||void 0===n?void 0:n.getElementById(q),this.rootElement=null===(r=this.shadowRoot)||void 0===r?void 0:r.getElementById(D)}})),W="descope-modal";var F;let z=class{constructor(e,t){F.set(this,void 0),this.nodeName="",s(this,F,e,"f"),this.logger=t.logger}get asyncEle(){return(async e=>new Promise((t=>{const n=setInterval((()=>{const r="function"==typeof e?e():e;r&&(clearInterval(n),t(r))}),100);setTimeout((()=>{clearInterval(n),t(null)}),1e3)})))(r(this,F,"f"))}get ele(){var e,t;const n="function"==typeof r(this,F,"f")?r(this,F,"f").call(this):r(this,F,"f");return n?(null==n?void 0:n.localName)!==this.nodeName?(null===(t=this.logger)||void 0===t||t.debug(`node name do not match, expected "${this.nodeName}", received "${n.localName}" `,Error()),null):n:(null===(e=this.logger)||void 0===e||e.debug(`Driver element is not available for ${this.nodeName}`,new Error),null)}};var H;F=new WeakMap;let J=class extends z{constructor(){super(...arguments),H.set(this,void 0),this.nodeName="descope-modal"}close(){var e,t;null===(e=this.ele)||void 0===e||e.removeAttribute("opened"),null===(t=this.afterClose)||void 0===t||t.call(this)}async open(){var e,t;await(null===(e=this.beforeOpen)||void 0===e?void 0:e.call(this)),null===(t=this.ele)||void 0===t||t.setAttribute("opened","true")}reset(){var e;this.ele&&(this.ele.innerHTML=""),r(this,H,"f")&&(null===(e=this.ele)||void 0===e||e.append(r(this,H,"f").content.cloneNode(!0)))}setContent(e){s(this,H,e,"f"),this.reset()}remove(){var e;null===(e=this.ele)||void 0===e||e.remove()}};H=new WeakMap;let K=class extends z{constructor(){super(...arguments),this.nodeName="descope-notification"}close(){var e;null===(e=this.ele)||void 0===e||e.removeAttribute("opened")}show(){var e;null===(e=this.ele)||void 0===e||e.setAttribute("opened","true")}setContent(e){this.ele.innerHTML="",this.ele.appendChild(e.content.cloneNode(!0))}remove(){var e;null===(e=this.ele)||void 0===e||e.remove()}},B=class extends z{constructor(){super(...arguments),this.nodeName="descope-apps-list"}set data(e){this.ele&&(this.ele.data=e)}get data(){var e;return null===(e=this.ele)||void 0===e?void 0:e.data}get ele(){return super.ele}};a((e=>{var t,n;const s=i(y,L,N)(e);return n=class extends s{constructor(){super(...arguments),t.set(this,(()=>{const e=this.loadDescopeUiComponents.bind(this);return class extends J{setContent(t){e(t),super.setContent(t)}}})())}createModal(e){const n=((e={})=>{const t=document.createElement(W);return Object.keys(e).forEach((n=>{t.setAttribute(n,e[n])})),t})(Object.assign(Object.assign({},{}),e));return this.rootElement.append(n),new(r(this,t,"f"))(n,{logger:this.logger})}async init(){var e;this.loadDescopeUiComponents([W]),await(null===(e=super.init)||void 0===e?void 0:e.call(this))}},t=new WeakMap,n}));const V="descope-notification";a((e=>{var t,n;const s=i(y,L,N)(e);return n=class extends s{constructor(){super(...arguments),t.set(this,(()=>{const e=this.loadDescopeUiComponents.bind(this);return class extends K{setContent(t){const n="string"==typeof t?o(t):t;e(n),super.setContent(n)}}})())}createNotification(e){const n=((e={})=>{const t=document.createElement(V);return Object.keys(e).forEach((n=>{t.setAttribute(n,e[n])})),t})(Object.assign(Object.assign({},{}),e));return this.rootElement.append(n),new(r(this,t,"f"))(n,{logger:this.logger})}async init(){var e;await(null===(e=super.init)||void 0===e?void 0:e.call(this)),this.loadDescopeUiComponents([V])}},t=new WeakMap,n}));const G=(e,t)=>!!t&&"light"!==t&&"dark"!==t&&'Supported theme values are "light", "dark", or leave empty for using the OS theme',Y=a((e=>{var t,n,o,a,c,l,d,u,h,p,g,f,m,w;const _=i(b({theme:G}),E,y,N,T,L,v)(e);return w=class extends _{constructor(){super(...arguments),t.add(this),n.set(this,void 0),o.set(this,void 0),g.set(this,(()=>{r(this,t,"m",f).call(this),r(this,m,"f").call(this,"os"===this.getAttribute("theme"))})),m.set(this,(e=>{var n,s,i;const o=e?"addEventListener":"removeEventListener";null===(i=null===(s=null===(n=window.matchMedia)||void 0===n?void 0:n.call(window,"(prefers-color-scheme: dark)"))||void 0===s?void 0:s[o])||void 0===i||i.call(s,"change",(()=>r(this,t,"m",f).call(this)))}))}get theme(){var e,t;const n=this.getAttribute("theme");if("os"===n){return window.matchMedia&&(null===(t=null===(e=window.matchMedia)||void 0===e?void 0:e.call(window,"(prefers-color-scheme: dark)"))||void 0===t?void 0:t.matches)?"dark":"light"}return n||"light"}get styleId(){return this.getAttribute("style-id")||"theme"}async init(){var e;await(null===(e=super.init)||void 0===e?void 0:e.call(this)),r(this,t,"m",l).call(this),r(this,t,"m",d).call(this),r(this,g,"f").call(this),this.observeAttributes(["theme"],r(this,g,"f")),this.observeAttributes(["style-id"],(()=>{s(this,o,null,"f"),r(this,t,"m",h).call(this),r(this,t,"m",l).call(this),r(this,t,"m",d).call(this)}))}},n=new WeakMap,o=new WeakMap,g=new WeakMap,m=new WeakMap,t=new WeakSet,a=async function(){try{const{body:e}=await this.fetchStaticResource(`${this.styleId}.json`,"json");if(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(R))try{this.logger.warn("You are in DEV mode, and UI components override URL was found\ntrying to merge project theme with the default theme of the UI components");const t=await(async()=>{const e=localStorage.getItem(R),t=null==e?void 0:e.replace(/[^\/]+$/,"DescopeDev.js");console.warn("Trying to load DescopeDev.js from",t);const n=document.createElement("script");if(n.src=t,document.body.appendChild(n),await new Promise(((e,t)=>{n.onload=e,n.onerror=t})),globalThis.DescopeDev){const{themeToStyle:e,defaultTheme:t,darkTheme:n}=globalThis.DescopeDev;return{light:e(t),dark:e(n)}}})();t&&(e.light.components=Object.assign(Object.assign({},e.light.components),t.light.components),e.dark.components=Object.assign(Object.assign({},e.dark.components),t.dark.components),this.logger.warn("Theme was merged successfully"),console.log("%cNOTICE! This is not the theme that will be used in production!\n\nMake sure to test it without the override UI components URL!","color: black; background-color:yellow; font-size: x-large"))}catch(e){this.logger.error("Failed to merge UI components theme\n",e)}return e}catch(e){this.logger.error("Cannot fetch theme file","make sure that your projectId & flowId are correct")}},c=function(){return r(this,o,"f")||(s(this,o,r(this,t,"m",a).call(this),"f"),r(this,o,"f").then((e=>this.logger.debug("Fetched theme",e)))),r(this,o,"f")},l=async function(){var e,i,o,a;const l=await r(this,t,"a",c);l&&(r(this,n,"f")||(s(this,n,new CSSStyleSheet,"f"),null!==(e=(a=this.shadowRoot).adoptedStyleSheets)&&void 0!==e||(a.adoptedStyleSheets=[]),this.shadowRoot.adoptedStyleSheets=[...this.shadowRoot.adoptedStyleSheets,r(this,n,"f")]),r(this,n,"f").replaceSync(((null===(i=null==l?void 0:l.light)||void 0===i?void 0:i.globals)||"")+((null===(o=null==l?void 0:l.dark)||void 0===o?void 0:o.globals)||"")))},d=async function(){var e,n;const s=Object.assign({},await r(this,t,"a",c));if(!s)return;const i=await this.descopeUi;(null==i?void 0:i.componentsThemeManager)&&(i.componentsThemeManager.themes={light:null===(e=null==s?void 0:s.light)||void 0===e?void 0:e.components,dark:null===(n=null==s?void 0:s.dark)||void 0===n?void 0:n.components})},u=async function(){var e,t;const{projectConfig:n}=await this.config||{},r=null===(e=null==n?void 0:n.styles)||void 0===e?void 0:e[this.styleId],s=null==n?void 0:n.cssTemplate,i=r||s;return null===(t=null==i?void 0:i[this.theme])||void 0===t?void 0:t.fonts},h=async function(){const e=await r(this,t,"m",u).call(this);e?Object.values(e).forEach((e=>{e.url&&(this.logger.debug(`Loading font from URL "${e.url}"`),(e=>{const t=document.createElement("link");t.href=e,t.rel="stylesheet",document.head.appendChild(t)})(e.url))})):this.logger.debug("No fonts to load")},p=async function(){this.rootElement.setAttribute("data-theme",this.theme);const e=await this.descopeUi;(null==e?void 0:e.componentsThemeManager)&&(e.componentsThemeManager.currentThemeName=this.theme)},f=function(){r(this,t,"m",h).call(this),r(this,t,"m",p).call(this)},w}));var X=(()=>"function"==typeof Symbol&&Symbol.observable||"@@observable")(),Q=()=>Math.random().toString(36).substring(7).split("").join("."),Z={INIT:`@@redux/INIT${Q()}`,REPLACE:`@@redux/REPLACE${Q()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${Q()}`};function ee(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||null===Object.getPrototypeOf(e)}function te(e){if(void 0===e)return"undefined";if(null===e)return"null";const t=typeof e;switch(t){case"boolean":case"string":case"number":case"symbol":case"function":return t}if(Array.isArray(e))return"array";if(function(e){return e instanceof Date||"function"==typeof e.toDateString&&"function"==typeof e.getDate&&"function"==typeof e.setDate}(e))return"date";if(function(e){return e instanceof Error||"string"==typeof e.message&&e.constructor&&"number"==typeof e.constructor.stackTraceLimit}(e))return"error";const n=function(e){return"function"==typeof e.constructor?e.constructor.name:null}(e);switch(n){case"Symbol":case"Promise":case"WeakMap":case"WeakSet":case"Map":case"Set":return n}return Object.prototype.toString.call(e).slice(8,-1).toLowerCase().replace(/\s/g,"")}function ne(e){let t=typeof e;return t=te(e),t}function re(e,t,n){if("function"!=typeof e)throw new Error(`Expected the root reducer to be a function. Instead, received: '${ne(e)}'`);if("function"==typeof t&&"function"==typeof n||"function"==typeof n&&"function"==typeof arguments[3])throw new Error("It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.");if("function"==typeof t&&void 0===n&&(n=t,t=void 0),void 0!==n){if("function"!=typeof n)throw new Error(`Expected the enhancer to be a function. Instead, received: '${ne(n)}'`);return n(re)(e,t)}let r=e,s=t,i=new Map,o=i,a=0,c=!1;function l(){o===i&&(o=new Map,i.forEach(((e,t)=>{o.set(t,e)})))}function d(){if(c)throw new Error("You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");return s}function u(e){if("function"!=typeof e)throw new Error(`Expected the listener to be a function. Instead, received: '${ne(e)}'`);if(c)throw new Error("You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.");let t=!0;l();const n=a++;return o.set(n,e),function(){if(t){if(c)throw new Error("You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.");t=!1,l(),o.delete(n),i=null}}}function h(e){if(!ee(e))throw new Error(`Actions must be plain objects. Instead, the actual type was: '${ne(e)}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`);if(void 0===e.type)throw new Error('Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');if("string"!=typeof e.type)throw new Error(`Action "type" property must be a string. Instead, the actual type was: '${ne(e.type)}'. Value was: '${e.type}' (stringified)`);if(c)throw new Error("Reducers may not dispatch actions.");try{c=!0,s=r(s,e)}finally{c=!1}return(i=o).forEach((e=>{e()})),e}h({type:Z.INIT});return{dispatch:h,subscribe:u,getState:d,replaceReducer:function(e){if("function"!=typeof e)throw new Error(`Expected the nextReducer to be a function. Instead, received: '${ne(e)}`);r=e,h({type:Z.REPLACE})},[X]:function(){const e=u;return{subscribe(t){if("object"!=typeof t||null===t)throw new Error(`Expected the observer to be an object. Instead, received: '${ne(t)}'`);function n(){const e=t;e.next&&e.next(d())}n();return{unsubscribe:e(n)}},[X](){return this}}}}}function se(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}function ie(e){const t=Object.keys(e),n={};for(let r=0;r<t.length;r++){const s=t[r];void 0===e[s]&&se(`No reducer provided for key "${s}"`),"function"==typeof e[s]&&(n[s]=e[s])}const r=Object.keys(n);let s,i;s={};try{!function(e){Object.keys(e).forEach((t=>{const n=e[t];if(void 0===n(void 0,{type:Z.INIT}))throw new Error(`The slice reducer for key "${t}" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);if(void 0===n(void 0,{type:Z.PROBE_UNKNOWN_ACTION()}))throw new Error(`The slice reducer for key "${t}" returned undefined when probed with a random type. Don't try to handle '${Z.INIT}' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.`)}))}(n)}catch(e){i=e}return function(e={},t){if(i)throw i;{const r=function(e,t,n,r){const s=Object.keys(t),i=n&&n.type===Z.INIT?"preloadedState argument passed to createStore":"previous state received by the reducer";if(0===s.length)return"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";if(!ee(e))return`The ${i} has unexpected type of "${ne(e)}". Expected argument to be an object with the following keys: "${s.join('", "')}"`;const o=Object.keys(e).filter((e=>!t.hasOwnProperty(e)&&!r[e]));return o.forEach((e=>{r[e]=!0})),n&&n.type===Z.REPLACE?void 0:o.length>0?`Unexpected ${o.length>1?"keys":"key"} "${o.join('", "')}" found in ${i}. Expected to find one of the known reducer keys instead: "${s.join('", "')}". Unexpected keys will be ignored.`:void 0}(e,n,t,s);r&&se(r)}let o=!1;const a={};for(let s=0;s<r.length;s++){const i=r[s],c=n[i],l=e[i],d=c(l,t);if(void 0===d){const e=t&&t.type;throw new Error(`When called with an action of type ${e?`"${String(e)}"`:"(unknown type)"}, the slice reducer for key "${i}" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.`)}a[i]=d,o=o||d!==l}return o=o||r.length!==Object.keys(e).length,o?a:e}}function oe(...e){return 0===e.length?e=>e:1===e.length?e[0]:e.reduce(((e,t)=>(...n)=>e(t(...n))))}function ae(e){return ee(e)&&"type"in e&&"string"==typeof e.type}var ce=Symbol.for("immer-nothing"),le=Symbol.for("immer-draftable"),de=Symbol.for("immer-state"),ue=[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}];function he(e,...t){{const n=ue[e],r="function"==typeof n?n.apply(null,t):n;throw new Error(`[Immer] ${r}`)}}var pe=Object.getPrototypeOf;function ge(e){return!!e&&!!e[de]}function fe(e){return!!e&&(we(e)||Array.isArray(e)||!!e[le]||!!e.constructor?.[le]||Se(e)||ke(e))}var me=Object.prototype.constructor.toString();function we(e){if(!e||"object"!=typeof e)return!1;const t=pe(e);if(null===t)return!0;const n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object||"function"==typeof n&&Function.toString.call(n)===me}function _e(e,t){0===ye(e)?Object.entries(e).forEach((([n,r])=>{t(n,r,e)})):e.forEach(((n,r)=>t(r,n,e)))}function ye(e){const t=e[de];return t?t.type_:Array.isArray(e)?1:Se(e)?2:ke(e)?3:0}function ve(e,t){return 2===ye(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function be(e,t,n){const r=ye(e);2===r?e.set(t,n):3===r?e.add(n):e[t]=n}function Se(e){return e instanceof Map}function ke(e){return e instanceof Set}function Ie(e){return e.copy_||e.base_}function xe(e,t){if(Se(e))return new Map(e);if(ke(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&we(e)){if(!pe(e)){const t=Object.create(null);return Object.assign(t,e)}return{...e}}const n=Object.getOwnPropertyDescriptors(e);delete n[de];let r=Reflect.ownKeys(n);for(let t=0;t<r.length;t++){const s=r[t],i=n[s];!1===i.writable&&(i.writable=!0,i.configurable=!0),(i.get||i.set)&&(n[s]={configurable:!0,writable:!0,enumerable:i.enumerable,value:e[s]})}return Object.create(pe(e),n)}function Ee(e,t=!1){return Te(e)||ge(e)||!fe(e)||(ye(e)>1&&(e.set=e.add=e.clear=e.delete=Oe),Object.freeze(e),t&&_e(e,((e,t)=>Ee(t,!0)))),e}function Oe(){he(2)}function Te(e){return Object.isFrozen(e)}var Ce,je={};function Re(e){const t=je[e];return t||he(0,e),t}function Pe(){return Ce}function Ue(e,t){t&&(Re("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Ae(e){Me(e),e.drafts_.forEach(Ne),e.drafts_=null}function Me(e){e===Ce&&(Ce=e.parent_)}function $e(e){return Ce={drafts_:[],parent_:Ce,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Ne(e){const t=e[de];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function qe(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return void 0!==e&&e!==n?(n[de].modified_&&(Ae(t),he(4)),fe(e)&&(e=De(t,e),t.parent_||We(t,e)),t.patches_&&Re("Patches").generateReplacementPatches_(n[de].base_,e,t.patches_,t.inversePatches_)):e=De(t,n,[]),Ae(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==ce?e:void 0}function De(e,t,n){if(Te(t))return t;const r=t[de];if(!r)return _e(t,((s,i)=>Le(e,r,t,s,i,n))),t;if(r.scope_!==e)return t;if(!r.modified_)return We(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const t=r.copy_;let s=t,i=!1;3===r.type_&&(s=new Set(t),t.clear(),i=!0),_e(s,((s,o)=>Le(e,r,t,s,o,n,i))),We(e,t,!1),n&&e.patches_&&Re("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function Le(e,t,n,r,s,i,o){if(s===n&&he(5),ge(s)){const o=De(e,s,i&&t&&3!==t.type_&&!ve(t.assigned_,r)?i.concat(r):void 0);if(be(n,r,o),!ge(o))return;e.canAutoFreeze_=!1}else o&&n.add(s);if(fe(s)&&!Te(s)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;De(e,s),t&&t.scope_.parent_||We(e,s)}}function We(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Ee(t,n)}var Fe={get(e,t){if(t===de)return e;const n=Ie(e);if(!ve(n,t))return function(e,t,n){const r=Je(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}(e,n,t);const r=n[t];return e.finalized_||!fe(r)?r:r===He(e.base_,t)?(Be(e),e.copy_[t]=Ve(r,e)):r},has:(e,t)=>t in Ie(e),ownKeys:e=>Reflect.ownKeys(Ie(e)),set(e,t,n){const r=Je(Ie(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const r=He(Ie(e),t),s=r?.[de];if(s&&s.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}(n,r)&&(void 0!==n||ve(e.base_,t)))return!0;Be(e),Ke(e)}return e.copy_[t]===n&&(void 0!==n||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty:(e,t)=>(void 0!==He(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,Be(e),Ke(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=Ie(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:r.enumerable,value:n[t]}:r},defineProperty(){he(11)},getPrototypeOf:e=>pe(e.base_),setPrototypeOf(){he(12)}},ze={};function He(e,t){const n=e[de];return(n?Ie(n):e)[t]}function Je(e,t){if(!(t in e))return;let n=pe(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=pe(n)}}function Ke(e){e.modified_||(e.modified_=!0,e.parent_&&Ke(e.parent_))}function Be(e){e.copy_||(e.copy_=xe(e.base_,e.scope_.immer_.useStrictShallowCopy_))}_e(Fe,((e,t)=>{ze[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}})),ze.deleteProperty=function(e,t){return isNaN(parseInt(t))&&he(13),ze.set.call(this,e,t,void 0)},ze.set=function(e,t,n){return"length"!==t&&isNaN(parseInt(t))&&he(14),Fe.set.call(this,e[0],t,n,e[0])};function Ve(e,t){const n=Se(e)?Re("MapSet").proxyMap_(e,t):ke(e)?Re("MapSet").proxySet_(e,t):function(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Pe(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let s=r,i=Fe;n&&(s=[r],i=ze);const{revoke:o,proxy:a}=Proxy.revocable(s,i);return r.draft_=a,r.revoke_=o,a}(e,t);return(t?t.scope_:Pe()).drafts_.push(n),n}function Ge(e){return ge(e)||he(10,e),Ye(e)}function Ye(e){if(!fe(e)||Te(e))return e;const t=e[de];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=xe(e,t.scope_.immer_.useStrictShallowCopy_)}else n=xe(e,!0);return _e(n,((e,t)=>{be(n,e,Ye(t))})),t&&(t.finalized_=!1),n}var Xe=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,n)=>{if("function"==typeof e&&"function"!=typeof t){const n=t;t=e;const r=this;return function(e=n,...s){return r.produce(e,(e=>t.call(this,e,...s)))}}let r;if("function"!=typeof t&&he(6),void 0!==n&&"function"!=typeof n&&he(7),fe(e)){const s=$e(this),i=Ve(e,void 0);let o=!0;try{r=t(i),o=!1}finally{o?Ae(s):Me(s)}return Ue(s,n),qe(r,s)}if(!e||"object"!=typeof e){if(r=t(e),void 0===r&&(r=e),r===ce&&(r=void 0),this.autoFreeze_&&Ee(r,!0),n){const t=[],s=[];Re("Patches").generateReplacementPatches_(e,r,t,s),n(t,s)}return r}he(1,e)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...n)=>this.produceWithPatches(t,(t=>e(t,...n)));let n,r;const s=this.produce(e,t,((e,t)=>{n=e,r=t}));return[s,n,r]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){fe(e)||he(8),ge(e)&&(e=Ge(e));const t=$e(this),n=Ve(e,void 0);return n[de].isManual_=!0,Me(t),n}finishDraft(e,t){const n=e&&e[de];n&&n.isManual_||he(9);const{scope_:r}=n;return Ue(r,t),qe(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const r=t[n];if(0===r.path.length&&"replace"===r.op){e=r.value;break}}n>-1&&(t=t.slice(n+1));const r=Re("Patches").applyPatches_;return ge(e)?r(e,t):this.produce(e,(e=>r(e,t)))}},Qe=Xe.produce;Xe.produceWithPatches.bind(Xe),Xe.setAutoFreeze.bind(Xe),Xe.setUseStrictShallowCopy.bind(Xe),Xe.applyPatches.bind(Xe),Xe.createDraft.bind(Xe),Xe.finishDraft.bind(Xe);var Ze=(e,t,n)=>{if(1===t.length&&t[0]===n){let t=!1;try{const n={};e(n)===n&&(t=!0)}catch{}if(t){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("The result function returned its own inputs without modification. e.g\n`createSelector([state => state.todos], todos => todos)`\nThis could lead to inefficient memoization and unnecessary re-renders.\nEnsure transformation logic is in the result function, and extraction logic is in the input selectors.",{stack:e})}}},et=(e,t,n)=>{const{memoize:r,memoizeOptions:s}=t,{inputSelectorResults:i,inputSelectorResultsCopy:o}=e,a=r((()=>({})),...s);if(!(a.apply(null,i)===a.apply(null,o))){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("An input selector returned a different result when passed same arguments.\nThis means your output selector will likely run more frequently than intended.\nAvoid returning a new reference inside your input selector, e.g.\n`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)`",{arguments:n,firstInputs:i,secondInputs:o,stack:e})}},tt={inputStabilityCheck:"once",identityFunctionCheck:"once"};var nt=e=>Array.isArray(e)?e:[e];function rt(e){const t=Array.isArray(e[0])?e[0]:e;return function(e,t="expected all items to be functions, instead received the following types: "){if(!e.every((e=>"function"==typeof e))){const n=e.map((e=>"function"==typeof e?`function ${e.name||"unnamed"}()`:typeof e)).join(", ");throw new TypeError(`${t}[${n}]`)}}(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}function st(e,t){const n=[],{length:r}=e;for(let s=0;s<r;s++)n.push(e[s].apply(null,t));return n}var it="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}},ot=0,at=1;function ct(){return{s:ot,v:void 0,o:null,p:null}}function lt(e,t={}){let n=ct();const{resultEqualityCheck:r}=t;let s,i=0;function o(){let t=n;const{length:o}=arguments;for(let e=0,n=o;e<n;e++){const n=arguments[e];if("function"==typeof n||"object"==typeof n&&null!==n){let e=t.o;null===e&&(t.o=e=new WeakMap);const r=e.get(n);void 0===r?(t=ct(),e.set(n,t)):t=r}else{let e=t.p;null===e&&(t.p=e=new Map);const r=e.get(n);void 0===r?(t=ct(),e.set(n,t)):t=r}}const a=t;let c;if(t.s===at)c=t.v;else if(c=e.apply(null,arguments),i++,r){const e=s?.deref?.()??s;null!=e&&r(e,c)&&(c=e,0!==i&&i--);s="object"==typeof c&&null!==c||"function"==typeof c?new it(c):c}return a.s=at,a.v=c,c}return o.clearCache=()=>{n=ct(),o.resetResultsCount()},o.resultsCount=()=>i,o.resetResultsCount=()=>{i=0},o}function dt(e,...t){const n="function"==typeof e?{memoize:e,memoizeOptions:t}:e,r=(...e)=>{let t,r=0,s=0,i={},o=e.pop();"object"==typeof o&&(i=o,o=e.pop()),function(e,t="expected a function, instead received "+typeof e){if("function"!=typeof e)throw new TypeError(t)}(o,`createSelector expects an output function after the inputs, but received: [${typeof o}]`);const a={...n,...i},{memoize:c,memoizeOptions:l=[],argsMemoize:d=lt,argsMemoizeOptions:u=[],devModeChecks:h={}}=a,p=nt(l),g=nt(u),f=rt(e),m=c((function(){return r++,o.apply(null,arguments)}),...p);let w=!0;const _=d((function(){s++;const e=st(f,arguments);t=m.apply(null,e);{const{identityFunctionCheck:n,inputStabilityCheck:r}=((e,t)=>{const{identityFunctionCheck:n,inputStabilityCheck:r}={...tt,...t};return{identityFunctionCheck:{shouldRun:"always"===n||"once"===n&&e,run:Ze},inputStabilityCheck:{shouldRun:"always"===r||"once"===r&&e,run:et}}})(w,h);if(n.shouldRun&&n.run(o,e,t),r.shouldRun){const t=st(f,arguments);r.run({inputSelectorResults:e,inputSelectorResultsCopy:t},{memoize:c,memoizeOptions:p},arguments)}w&&(w=!1)}return t}),...g);return Object.assign(_,{resultFunc:o,memoizedResultFunc:m,dependencies:f,dependencyRecomputations:()=>s,resetDependencyRecomputations:()=>{s=0},lastResult:()=>t,recomputations:()=>r,resetRecomputations:()=>{r=0},memoize:c,argsMemoize:d})};return Object.assign(r,{withTypes:()=>r}),r}var ut=dt(lt),ht=Object.assign(((e,t=ut)=>{!function(e,t="expected an object, instead received "+typeof e){if("object"!=typeof e)throw new TypeError(t)}(e,"createStructuredSelector expects first argument to be an object where each property is a selector, instead received a "+typeof e);const n=Object.keys(e);return t(n.map((t=>e[t])),((...e)=>e.reduce(((e,t,r)=>(e[n[r]]=t,e)),{})))}),{withTypes:()=>ht});function pt(e){return({dispatch:t,getState:n})=>r=>s=>"function"==typeof s?s(t,n,e):r(s)}var gt=pt(),ft=pt;((...e)=>{const t=dt(...e)})(lt);var mt="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(0!==arguments.length)return"object"==typeof arguments[0]?oe:oe.apply(null,arguments)},wt=e=>e&&"function"==typeof e.match;function _t(e,t){function n(...n){if(t){let r=t(...n);if(!r)throw new Error("prepareAction did not return an object");return{type:e,payload:r.payload,..."meta"in r&&{meta:r.meta},..."error"in r&&{error:r.error}}}return{type:e,payload:n[0]}}return n.toString=()=>`${e}`,n.type=e,n.match=t=>ae(t)&&t.type===e,n}function yt(e){return"function"==typeof e&&"type"in e&&wt(e)}function vt(e,t){let n=0;return{measureTime(e){const t=Date.now();try{return e()}finally{const e=Date.now();n+=e-t}},warnIfExceeded(){n>e&&console.warn(`${t} took ${n}ms, which is more than the warning threshold of ${e}ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.`)}}}var bt=class e extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,e.prototype)}static get[Symbol.species](){return e}concat(...e){return super.concat.apply(this,e)}prepend(...t){return 1===t.length&&Array.isArray(t[0])?new e(...t[0].concat(this)):new e(...t.concat(this))}};function St(e){return fe(e)?Qe(e,(()=>{})):e}function kt(e,t,n){if(e.has(t)){let r=e.get(t);return n.update&&(r=n.update(r,t,e),e.set(t,r)),r}if(!n.insert)throw new Error("No insert provided for key not already in map");const r=n.insert(t,e);return e.set(t,r),r}function It(e){return"object"!=typeof e||null==e||Object.isFrozen(e)}function xt(e,t,n){const r=Et(e,t,n);return{detectMutations:()=>Ot(e,t,r,n)}}function Et(e,t=[],n,r="",s=new Set){const i={value:n};if(!e(n)&&!s.has(n)){s.add(n),i.children={};for(const s in n){const o=r?r+"."+s:s;t.length&&-1!==t.indexOf(o)||(i.children[s]=Et(e,t,n[s],o))}}return i}function Ot(e,t=[],n,r,s=!1,i=""){const o=n?n.value:void 0,a=o===r;if(s&&!a&&!Number.isNaN(r))return{wasMutated:!0,path:i};if(e(o)||e(r))return{wasMutated:!1};const c={};for(let e in n.children)c[e]=!0;for(let e in r)c[e]=!0;const l=t.length>0;for(let s in c){const o=i?i+"."+s:s;if(l){if(t.some((e=>e instanceof RegExp?e.test(o):o===e)))continue}const c=Ot(e,t,n.children[s],r[s],a,o);if(c.wasMutated)return c}return{wasMutated:!1}}function Tt(e){const t=typeof e;return null==e||"string"===t||"boolean"===t||"number"===t||Array.isArray(e)||ee(e)}function Ct(e,t="",n=Tt,r,s=[],i){let o;if(!n(e))return{keyPath:t||"<root>",value:e};if("object"!=typeof e||null===e)return!1;if(i?.has(e))return!1;const a=null!=r?r(e):Object.entries(e),c=s.length>0;for(const[e,l]of a){const a=t?t+"."+e:e;if(c){if(s.some((e=>e instanceof RegExp?e.test(a):a===e)))continue}if(!n(l))return{keyPath:a,value:l};if("object"==typeof l&&(o=Ct(l,a,n,r,s,i),o))return o}return i&&jt(e)&&i.add(e),!1}function jt(e){if(!Object.isFrozen(e))return!1;for(const t of Object.values(e))if("object"==typeof t&&null!==t&&!jt(t))return!1;return!0}function Rt(e){return"boolean"==typeof e}var Pt=()=>function(e){const{thunk:t=!0,immutableCheck:n=!0,serializableCheck:r=!0,actionCreatorCheck:s=!0}=e??{};let i=new bt;if(t&&(Rt(t)?i.push(gt):i.push(ft(t.extraArgument))),n){let e={};Rt(n)||(e=n),i.unshift(function(e={}){{let t=function(e,t,r,s){return JSON.stringify(e,n(t,s),r)},n=function(e,t){let n=[],r=[];return t||(t=function(e,t){return n[0]===t?"[Circular ~]":"[Circular ~."+r.slice(0,n.indexOf(t)).join(".")+"]"}),function(s,i){if(n.length>0){var o=n.indexOf(this);~o?n.splice(o+1):n.push(this),~o?r.splice(o,1/0,s):r.push(s),~n.indexOf(i)&&(i=t.call(this,s,i))}else n.push(i);return null==e?i:e.call(this,s,i)}},{isImmutable:r=It,ignoredPaths:s,warnAfter:i=32}=e;const o=xt.bind(null,r,s);return({getState:e})=>{let n,r=e(),s=o(r);return a=>c=>{const l=vt(i,"ImmutableStateInvariantMiddleware");l.measureTime((()=>{if(r=e(),n=s.detectMutations(),s=o(r),n.wasMutated)throw new Error(`A state mutation was detected between dispatches, in the path '${n.path||""}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)}));const d=a(c);return l.measureTime((()=>{if(r=e(),n=s.detectMutations(),s=o(r),n.wasMutated)throw new Error(`A state mutation was detected inside a dispatch, in the path: ${n.path||""}. Take a look at the reducer(s) handling the action ${t(c)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)})),l.warnIfExceeded(),d}}}}(e))}if(r){let e={};Rt(r)||(e=r),i.push(function(e={}){{const{isSerializable:t=Tt,getEntries:n,ignoredActions:r=[],ignoredActionPaths:s=["meta.arg","meta.baseQueryMeta"],ignoredPaths:i=[],warnAfter:o=32,ignoreState:a=!1,ignoreActions:c=!1,disableCache:l=!1}=e,d=!l&&WeakSet?new WeakSet:void 0;return e=>l=>u=>{if(!ae(u))return l(u);const h=l(u),p=vt(o,"SerializableStateInvariantMiddleware");return c||r.length&&-1!==r.indexOf(u.type)||p.measureTime((()=>{const e=Ct(u,"",t,n,s,d);if(e){const{keyPath:t,value:n}=e;console.error(`A non-serializable value was detected in an action, in the path: \`${t}\`. Value:`,n,"\nTake a look at the logic that dispatched this action: ",u,"\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)","\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)")}})),a||(p.measureTime((()=>{const r=Ct(e.getState(),"",t,n,i,d);if(r){const{keyPath:e,value:t}=r;console.error(`A non-serializable value was detected in the state, in the path: \`${e}\`. Value:`,t,`\nTake a look at the reducer(s) handling this action type: ${u.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`)}})),p.warnIfExceeded()),h}}}(e))}if(s){let e={};Rt(s)||(e=s),i.unshift(function(e={}){const{isActionCreator:t=yt}=e;return()=>e=>n=>(t(n)&&console.warn(function(e){const t=e?`${e}`.split("/"):[],n=t[t.length-1]||"actionCreator";return`Detected an action creator with type "${e||"unknown"}" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. \`dispatch(${n}())\` instead of \`dispatch(${n})\`. This is necessary even if the action has no payload.`}(n.type)),e(n))}(e))}return i},Ut=e=>t=>{setTimeout(t,e)},At="undefined"!=typeof window&&window.requestAnimationFrame?window.requestAnimationFrame:Ut(10),Mt=e=>function(t){const{autoBatch:n=!0}=t??{};let r=new bt(e);return n&&r.push(((e={type:"raf"})=>t=>(...n)=>{const r=t(...n);let s=!0,i=!1,o=!1;const a=new Set,c="tick"===e.type?queueMicrotask:"raf"===e.type?At:"callback"===e.type?e.queueNotification:Ut(e.timeout),l=()=>{o=!1,i&&(i=!1,a.forEach((e=>e())))};return Object.assign({},r,{subscribe(e){const t=r.subscribe((()=>s&&e()));return a.add(e),()=>{t(),a.delete(e)}},dispatch(e){try{return s=!e?.meta?.RTK_autoBatch,i=!s,i&&(o||(o=!0,c(l))),r.dispatch(e)}finally{s=!0}}})})("object"==typeof n?n:void 0)),r};function $t(e){const t=Pt(),{reducer:n,middleware:r,devTools:s=!0,preloadedState:i,enhancers:o}=e||{};let a,c;if("function"==typeof n)a=n;else{if(!ee(n))throw new Error("`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers");a=ie(n)}if(r&&"function"!=typeof r)throw new Error("`middleware` field must be a callback");if("function"==typeof r){if(c=r(t),!Array.isArray(c))throw new Error("when using a middleware builder function, an array of middleware must be returned")}else c=t();if(c.some((e=>"function"!=typeof e)))throw new Error("each middleware provided to configureStore must be a function");let l=oe;s&&(l=mt({trace:!0,..."object"==typeof s&&s}));const d=function(...e){return t=>(n,r)=>{const s=t(n,r);let i=()=>{throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")};const o={getState:s.getState,dispatch:(e,...t)=>i(e,...t)},a=e.map((e=>e(o)));return i=oe(...a)(s.dispatch),{...s,dispatch:i}}}(...c),u=Mt(d);if(o&&"function"!=typeof o)throw new Error("`enhancers` field must be a callback");let h="function"==typeof o?o(u):u();if(!Array.isArray(h))throw new Error("`enhancers` callback must return an array");if(h.some((e=>"function"!=typeof e)))throw new Error("each enhancer provided to configureStore must be a function");c.length&&!h.includes(d)&&console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");return re(a,i,l(...h))}function Nt(e){const t={},n=[];let r;const s={addCase(e,i){if(n.length>0)throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");if(r)throw new Error("`builder.addCase` should only be called before calling `builder.addDefaultCase`");const o="string"==typeof e?e:e.type;if(!o)throw new Error("`builder.addCase` cannot be called with an empty action type");if(o in t)throw new Error(`\`builder.addCase\` cannot be called with two reducers for the same action type '${o}'`);return t[o]=i,s},addMatcher(e,t){if(r)throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");return n.push({matcher:e,reducer:t}),s},addDefaultCase(e){if(r)throw new Error("`builder.addDefaultCase` can only be called once");return r=e,s}};return e(s),[t,n,r]}function qt(...e){return t=>e.some((e=>((e,t)=>wt(e)?e.match(t):e(t))(e,t)))}var Dt=["name","message","stack","code"],Lt=class{constructor(e,t){this.payload=e,this.meta=t}_type},Wt=class{constructor(e,t){this.payload=e,this.meta=t}_type},Ft=e=>{if("object"==typeof e&&null!==e){const t={};for(const n of Dt)"string"==typeof e[n]&&(t[n]=e[n]);return t}return{message:String(e)}},zt=(()=>{function e(e,t,n){const r=_t(e+"/fulfilled",((e,t,n,r)=>({payload:e,meta:{...r||{},arg:n,requestId:t,requestStatus:"fulfilled"}}))),s=_t(e+"/pending",((e,t,n)=>({payload:void 0,meta:{...n||{},arg:t,requestId:e,requestStatus:"pending"}}))),i=_t(e+"/rejected",((e,t,r,s,i)=>({payload:s,error:(n&&n.serializeError||Ft)(e||"Rejected"),meta:{...i||{},arg:r,requestId:t,rejectedWithValue:!!s,requestStatus:"rejected",aborted:"AbortError"===e?.name,condition:"ConditionError"===e?.name}})));return Object.assign((function(e){return(o,a,c)=>{const l=n?.idGenerator?n.idGenerator(e):((e=21)=>{let t="",n=e;for(;n--;)t+="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW"[64*Math.random()|0];return t})(),d=new AbortController;let u;function h(e){u=e,d.abort()}const p=async function(){let p;try{let i=n?.condition?.(e,{getState:a,extra:c});if(null!==(g=i)&&"object"==typeof g&&"function"==typeof g.then&&(i=await i),!1===i||d.signal.aborted)throw{name:"ConditionError",message:"Aborted due to condition callback returning false."};const f=new Promise(((e,t)=>d.signal.addEventListener("abort",(()=>t({name:"AbortError",message:u||"Aborted"})))));o(s(l,e,n?.getPendingMeta?.({requestId:l,arg:e},{getState:a,extra:c}))),p=await Promise.race([f,Promise.resolve(t(e,{dispatch:o,getState:a,extra:c,requestId:l,signal:d.signal,abort:h,rejectWithValue:(e,t)=>new Lt(e,t),fulfillWithValue:(e,t)=>new Wt(e,t)})).then((t=>{if(t instanceof Lt)throw t;return t instanceof Wt?r(t.payload,l,e,t.meta):r(t,l,e)}))])}catch(t){p=t instanceof Lt?i(null,l,e,t.payload,t.meta):i(t,l,e)}var g;return n&&!n.dispatchConditionRejection&&i.match(p)&&p.meta.condition||o(p),p}();return Object.assign(p,{abort:h,requestId:l,arg:e,unwrap:()=>p.then(Ht)})}}),{pending:s,rejected:i,fulfilled:r,settled:qt(i,r),typePrefix:e})}return e.withTypes=()=>e,e})();function Ht(e){if(e.meta&&e.meta.rejectedWithValue)throw e.payload;if(e.error)throw e.error;return e.payload}var Jt=Symbol.for("rtk-slice-createasyncthunk");function Kt(e,t){return`${e}/${t}`}function Bt(e,t,n,r){function s(s,...i){let o=n.call(e,s);if(void 0===o){if(!r)throw new Error("selectState returned undefined for an uninjected slice reducer");o=e.getInitialState()}return t(o,...i)}return s.unwrapped=t,s}var Vt=function({creators:e}={}){const t=e?.asyncThunk?.[Jt];return function(e){const{name:n,reducerPath:r=n}=e;if(!n)throw new Error("`name` is a required option for createSlice");"undefined"!=typeof process&&void 0===e.initialState&&console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`");const s=("function"==typeof e.reducers?e.reducers(function(){function e(e,t){return{_reducerDefinitionType:"asyncThunk",payloadCreator:e,...t}}return e.withTypes=()=>e,{reducer:e=>Object.assign({[e.name]:(...t)=>e(...t)}[e.name],{_reducerDefinitionType:"reducer"}),preparedReducer:(e,t)=>({_reducerDefinitionType:"reducerWithPrepare",prepare:e,reducer:t}),asyncThunk:e}}()):e.reducers)||{},i=Object.keys(s),o={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},a={addCase(e,t){const n="string"==typeof e?e:e.type;if(!n)throw new Error("`context.addCase` cannot be called with an empty action type");if(n in o.sliceCaseReducersByType)throw new Error("`context.addCase` cannot be called with two reducers for the same action type: "+n);return o.sliceCaseReducersByType[n]=t,a},addMatcher:(e,t)=>(o.sliceMatchers.push({matcher:e,reducer:t}),a),exposeAction:(e,t)=>(o.actionCreators[e]=t,a),exposeCaseReducer:(e,t)=>(o.sliceCaseReducersByName[e]=t,a)};function c(){if("object"==typeof e.extraReducers)throw new Error("The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");const[t={},n=[],r]="function"==typeof e.extraReducers?Nt(e.extraReducers):[e.extraReducers],s={...t,...o.sliceCaseReducersByType};return function(e,t){if("object"==typeof t)throw new Error("The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");let n,[r,s,i]=Nt(t);if(function(e){return"function"==typeof e}(e))n=()=>St(e());else{const t=St(e);n=()=>t}function o(e=n(),t){let o=[r[t.type],...s.filter((({matcher:e})=>e(t))).map((({reducer:e})=>e))];return 0===o.filter((e=>!!e)).length&&(o=[i]),o.reduce(((e,n)=>{if(n){if(ge(e)){const r=n(e,t);return void 0===r?e:r}if(fe(e))return Qe(e,(e=>n(e,t)));{const r=n(e,t);if(void 0===r){if(null===e)return e;throw new Error("A case reducer on a non-draftable value must not return undefined")}return r}}return e}),e)}return o.getInitialState=n,o}(e.initialState,(e=>{for(let t in s)e.addCase(t,s[t]);for(let t of o.sliceMatchers)e.addMatcher(t.matcher,t.reducer);for(let t of n)e.addMatcher(t.matcher,t.reducer);r&&e.addDefaultCase(r)}))}i.forEach((r=>{const i=s[r],o={reducerName:r,type:Kt(n,r),createNotation:"function"==typeof e.reducers};!function(e){return"asyncThunk"===e._reducerDefinitionType}(i)?function({type:e,reducerName:t,createNotation:n},r,s){let i,o;if("reducer"in r){if(n&&!function(e){return"reducerWithPrepare"===e._reducerDefinitionType}(r))throw new Error("Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");i=r.reducer,o=r.prepare}else i=r;s.addCase(e,i).exposeCaseReducer(t,i).exposeAction(t,o?_t(e,o):_t(e))}(o,i,a):function({type:e,reducerName:t},n,r,s){if(!s)throw new Error("Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.");const{payloadCreator:i,fulfilled:o,pending:a,rejected:c,settled:l,options:d}=n,u=s(e,i,d);r.exposeAction(t,u),o&&r.addCase(u.fulfilled,o);a&&r.addCase(u.pending,a);c&&r.addCase(u.rejected,c);l&&r.addMatcher(u.settled,l);r.exposeCaseReducer(t,{fulfilled:o||Gt,pending:a||Gt,rejected:c||Gt,settled:l||Gt})}(o,i,a,t)}));const l=e=>e,d=new WeakMap;let u;const h={name:n,reducerPath:r,reducer:(e,t)=>(u||(u=c()),u(e,t)),actions:o.actionCreators,caseReducers:o.sliceCaseReducersByName,getInitialState:()=>(u||(u=c()),u.getInitialState()),getSelectors(t=l){const n=kt(d,this,{insert:()=>new WeakMap});return kt(n,t,{insert:()=>{const n={};for(const[r,s]of Object.entries(e.selectors??{}))n[r]=Bt(this,s,t,this!==h);return n}})},selectSlice(e){let t=e[this.reducerPath];if(void 0===t){if(this===h)throw new Error("selectSlice returned undefined for an uninjected slice reducer");t=this.getInitialState()}return t},get selectors(){return this.getSelectors(this.selectSlice)},injectInto(e,{reducerPath:t,...n}={}){const r=t??this.reducerPath;return e.inject({reducerPath:r,reducer:this.reducer},n),{...this,reducerPath:r}}};return h}}();function Gt(){}var Yt="listenerMiddleware";_t(`${Yt}/add`),_t(`${Yt}/removeAll`),_t(`${Yt}/remove`);const Xt=e=>a((t=>{const n=Vt(e),r=Object.assign(Object.assign({},n.actions),e.asyncActions);return class extends(i(f)(t)){constructor(...e){super(...e);const t=$t({reducer:n.reducer,middleware:e=>e({thunk:{extraArgument:this},serializableCheck:!1}),devTools:!1}),s=e=>async(...n)=>{const r=await t.dispatch(e(...n));try{Ht(r)}catch(e){this.logger.error(e.message,r.type,e.stack)}return r},i=Object.keys(r).reduce(((e,t)=>(e[t]=s(r[t]),e)),{});this.actions=i,this.subscribe=(e,n=e=>e)=>t.subscribe((()=>e(n(t.getState()))))}}}));a((e=>class extends(f(e)){validateForm(e){return this.getFormInputs(e).every((e=>{var t,n;return null===(t=e.reportValidity)||void 0===t||t.call(e),null===(n=e.checkValidity)||void 0===n?void 0:n.call(e)}))}getFormInputs(e){return e?Array.from(e.querySelectorAll("[name]")):(this.logger.debug("cannot get form inputs, no root element was received"),[])}getFormData(e){return this.getFormInputs(e).reduce(((e,t)=>Object.assign(e,{[t.getAttribute("name")]:t.value})),{})}setFormData(e,t){this.getFormInputs(e).forEach((e=>{t.hasOwnProperty(e.getAttribute("name"))&&(e.value=t[e.getAttribute("name")])}))}resetFormData(e){this.getFormInputs(e).forEach((e=>{e.value="",e.checked=!1}))}getFormFieldNames(e){return this.getFormInputs(e).map((e=>e.name))}disableFormField(e,t){var n;null===(n=this.getFormInputs(e).find((e=>e.name===t)))||void 0===n||n.setAttribute("disabled","true")}removeFormField(e,t){var n;null===(n=this.getFormInputs(e).find((e=>e.name===t)))||void 0===n||n.remove()}}));const Qt=a((e=>class extends e{get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}}));var Zt;!function(e){e.oidc="oidc",e.saml="saml"}(Zt||(Zt={}));const en=ut((e=>e.ssoAppsList.data),(e=>{var t;return null===(t=null==e?void 0:e.filter)||void 0===t?void 0:t.call(e,(e=>e.appType===Zt.saml))})),tn=ut(en,(e=>e.map((e=>({name:e.name,icon:e.logo,url:e.samlSettings.idpInitiatedUrl}))))),nn=zt("ssoApps/load",((e,{extra:{api:t}})=>t.ssoApps.load())),rn=(e=>(...t)=>n=>{n.addCase(e.pending,((e,n)=>{t.forEach((({onPending:t})=>{null==t||t(e,n)}))})),n.addCase(e.fulfilled,((e,n)=>{t.forEach((({onFulfilled:t})=>{null==t||t(e,n)}))})),n.addCase(e.rejected,((e,n)=>{t.forEach((({onRejected:t})=>{null==t||t(e,n)}))}))})(nn)({onFulfilled:(e,t)=>{var n;e.ssoAppsList.data=null===(n=t.payload)||void 0===n?void 0:n.apps}},(sn=e=>e.ssoAppsList,{onFulfilled:e=>{sn(e).loading=!1},onPending:e=>{sn(e).loading=!0,sn(e).error=null},onRejected:(e,t)=>{sn(e).loading=!1,sn(e).error=t.error}}));var sn;const on={action:nn,reducer:rn},an={ssoAppsList:{data:[],loading:!1,error:null}};class cn extends Error{}function ln(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 n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(e){return atob(t)}}function dn(e,t){if("string"!=typeof e)throw new cn("Invalid token specified: must be a string");t||(t={});const n=!0===t.header?0:1,r=e.split(".")[n];if("string"!=typeof r)throw new cn(`Invalid token specified: missing part #${n+1}`);let s;try{s=ln(r)}catch(e){throw new cn(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(s)}catch(e){throw new cn(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}cn.prototype.name="InvalidTokenError";var un={accessKey:{exchange:"/v1/auth/accesskey/exchange"},otp:{verify:"/v1/auth/otp/verify",signIn:"/v1/auth/otp/signin",signUp:"/v1/auth/otp/signup",update:{email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},signUpOrIn:"/v1/auth/otp/signup-in"},magicLink:{verify:"/v1/auth/magiclink/verify",signIn:"/v1/auth/magiclink/signin",signUp:"/v1/auth/magiclink/signup",update:{email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/phone"},signUpOrIn:"/v1/auth/magiclink/signup-in"},enchantedLink:{verify:"/v1/auth/enchantedlink/verify",signIn:"/v1/auth/enchantedlink/signin",signUp:"/v1/auth/enchantedlink/signup",session:"/v1/auth/enchantedlink/pending-session",update:{email:"/v1/auth/enchantedlink/update/email"},signUpOrIn:"/v1/auth/enchantedlink/signup-in"},oauth:{start:"/v1/auth/oauth/authorize",exchange:"/v1/auth/oauth/exchange",startNative:"v1/auth/oauth/native/start",finishNative:"v1/auth/oauth/native/finish",oneTap:{getOneTapClientId:"/v1/auth/onetap/clientid/{provider}",exchangeOneTapIDToken:"/v1/auth/onetap/idtoken/exchange",verifyOneTapIDToken:"/v1/auth/onetap/idtoken/verify"}},saml:{start:"/v1/auth/saml/authorize",exchange:"/v1/auth/saml/exchange"},totp:{verify:"/v1/auth/totp/verify",signUp:"/v1/auth/totp/signup",update:"/v1/auth/totp/update"},notp:{signIn:"/v1/auth/notp/whatsapp/signin",signUp:"/v1/auth/notp/whatsapp/signup",signUpOrIn:"/v1/auth/notp/whatsapp/signup-in",session:"/v1/auth/notp/pending-session"},webauthn:{signUp:{start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},signIn:{start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},signUpOrIn:{start:"/v1/auth/webauthn/signup-in/start"},update:{start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"}},password:{signUp:"/v1/auth/password/signup",signIn:"/v1/auth/password/signin",sendReset:"/v1/auth/password/reset",update:"/v1/auth/password/update",replace:"/v1/auth/password/replace",policy:"/v1/auth/password/policy"},refresh:"/v1/auth/refresh",selectTenant:"/v1/auth/tenant/select",logout:"/v1/auth/logout",logoutAll:"/v1/auth/logoutall",me:"/v1/auth/me",myTenants:"/v1/auth/me/tenants",history:"/v1/auth/me/history",flow:{start:"/v1/flow/start",next:"/v1/flow/next"}};const hn="<region>",pn=`https://api.${hn}descope.com`,gn=6e5,fn="dct",mn=()=>{const e={};return{headers(t){const n="function"==typeof t.entries?Object.fromEntries(t.entries()):t;return e.Headers=JSON.stringify(n),this},body(t){return e.Body=t,this},url(t){return e.Url=t.toString(),this},method(t){return e.Method=t,this},title(t){return e.Title=t,this},status(t){return e.Status=t,this},build:()=>Object.keys(e).flatMap((t=>e[t]?[`${"Title"!==t?`${t}: `:""}${e[t]}`]:[])).join("\n")}};let wn;const _n=()=>{if(wn)return wn;const e=new Date,t=`${e.getUTCFullYear().toString()}-${(e.getUTCMonth()+1).toString().padStart(2,"0")}-${e.getUTCDate().toString().padStart(2,"0")}-${e.getUTCHours().toString().padStart(2,"0")}:${e.getUTCMinutes().toString().padStart(2,"0")}:${e.getUTCSeconds().toString().padStart(2,"0")}:${e.getUTCMilliseconds().toString()}`,n=Math.floor(1e3+9e3*Math.random());return wn=`${t}-${n}`,wn};var yn,vn;(vn=yn||(yn={})).get="GET",vn.delete="DELETE",vn.post="POST",vn.put="PUT",vn.patch="PATCH";const bn=({path:e,baseUrl:t,queryParams:n,projectId:r})=>{const s=r.slice(1,-27);t=t.replace(hn,s?s+".":"");let i=e?`${t.replace(/\/$/,"")}/${null==e?void 0:e.replace(/^\//,"")}`:t;if(n){const e=Object.keys(n);e.forEach(((t,r)=>{i=`${i}${0===r?"?":""}${t}=${encodeURIComponent(n[t])}${r===e.length-1?"":"&"}`}))}return i},Sn=(...e)=>new Headers(e.reduce(((e,t)=>{const n=(e=>Array.isArray(e)?e:e instanceof Headers?Array.from(e.entries()):e?Object.entries(e):[])(t);return n.reduce(((t,[n,r])=>(e[n]=r,e)),e),e}),{})),kn={"Content-Type":"application/json"},In=(e,t="")=>{let n=e;return t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},xn=e=>{const t={"x-descope-sdk-session-id":_n(),"x-descope-sdk-name":"core-js","x-descope-sdk-version":"2.40.0"};return e&&(t["x-descope-refresh-cookie-name"]=e),t},En=e=>{try{e=JSON.parse(e)}catch(e){return!1}return"object"==typeof e&&null!==e},On=({baseUrl:e,projectId:t,baseConfig:n,refreshCookieName:r,logger:s,hooks:i,cookiePolicy:o,fetch:a})=>{const c=((e,t)=>{const n=(e=>async(...t)=>{const n=await e(...t),r=await n.text();return n.text=()=>Promise.resolve(r),n.json=()=>Promise.resolve(JSON.parse(r)),n.clone=()=>n,n})(t||fetch);return n||null==e||e.warn("Fetch is not defined, you will not be able to send http requests, if you are running in a test, make sure fetch is defined globally"),e?async(...t)=>{if(!n)throw Error("Cannot send http request, fetch is not defined, if you are running in a test, make sure fetch is defined globally");e.log((e=>mn().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const r=await n(...t);return e[r.ok?"log":"error"](await(async e=>{const t=await e.text();return mn().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(r)),r}:n})(s,a),l=async s=>{var a;const l=(null==i?void 0:i.beforeRequest)?i.beforeRequest(s):s,{path:d,body:u,headers:h,queryParams:p,method:g,token:f}=l,m=(e=>void 0===e?void 0:JSON.stringify(e))(u),w={headers:Sn(In(t,f),xn(r),(null==n?void 0:n.baseHeaders)||{},En(m)?kn:{},h),method:g,body:m};null!==o&&(w.credentials=o||"include");const _=await c(bn({path:d,baseUrl:e,queryParams:p,projectId:t}),w);if((null==i?void 0:i.afterRequest)&&await i.afterRequest(s,null==_?void 0:_.clone()),null==i?void 0:i.transformResponse){const e=await _.json(),t=((null===(a=_.headers)||void 0===a?void 0:a.get("set-cookie"))||"").split(";").reduce(((e,t)=>{const[n,r]=t.split("=");return Object.assign(Object.assign({},e),{[n.trim()]:r})}),{}),n=Object.assign(Object.assign({},_),{json:()=>Promise.resolve(e),cookies:t});return n.clone=()=>n,i.transformResponse(n)}return _};return{get:(e,{headers:t,queryParams:n,token:r}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:yn.get,token:r}),post:(e,t,{headers:n,queryParams:r,token:s}={})=>l({path:e,headers:n,queryParams:r,body:t,method:yn.post,token:s}),patch:(e,t,{headers:n,queryParams:r,token:s}={})=>l({path:e,headers:n,queryParams:r,body:t,method:yn.patch,token:s}),put:(e,t,{headers:n,queryParams:r,token:s}={})=>l({path:e,headers:n,queryParams:r,body:t,method:yn.put,token:s}),delete:(e,{headers:t,queryParams:n,token:r}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:yn.delete,token:r}),hooks:i,buildUrl:(n,r)=>bn({projectId:t,baseUrl:e,path:n,queryParams:r})}};var Tn=429;function Cn(e,t,n){var r;let s=jn(e);if(t){if(!(null==s?void 0:s.tenants)&&(null==s?void 0:s[fn])===t)return(null==s?void 0:s[n])||[];s=null===(r=null==s?void 0:s.tenants)||void 0===r?void 0:r[t]}const i=null==s?void 0:s[n];return Array.isArray(i)?i:[]}function jn(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return dn(e)}function Rn(e){const{exp:t}=jn(e);return(new Date).getTime()/1e3>t}function Pn(e){let t=jn(e);const n=Object.keys(null==t?void 0:t.tenants);return Array.isArray(n)?n:[]}function Un(e,t){return Cn(e,t,"permissions")}function An(e,t){return Cn(e,t,"roles")}const Mn=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function $n(e,t){var n;const r=await e,s={code:r.status,ok:r.ok,response:r},i=await r.clone().json();return r.ok?s.data=i:(s.error=i,r.status===Tn&&Object.assign(s.error,{retryAfter:Number.parseInt(null===(n=r.headers)||void 0===n?void 0:n.get("retry-after"))||0})),s}function Nn(e){var t;return(null===(t=jn(e))||void 0===t?void 0:t[fn])||""}const qn=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),Dn=(e,t)=>(n=t)=>t=>{const r=e.filter((e=>e(t)));return!(r.length<e.length)&&(n?n.replace("{val}",t):r.join(" OR "))},Ln=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),Wn=e=>t=>e.test(t),Fn=Wn(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),zn=Wn(/^\+[1-9]{1}[0-9]{3,14}$/),Hn=qn(Fn,'"{val}" is not a valid email'),Jn=qn(zn,'"{val}" is not a valid phone number'),Kn=qn((e=>e.length>=1),"Minimum length is 1");const Bn=qn((e=>"string"==typeof e),"Input is not a string"),Vn=qn((e=>Array.isArray(e)),"Input is not an array"),Gn=qn((e=>"boolean"==typeof e),"Input is not a boolean"),Yn=qn((e=>void 0===e),"Input is defined"),Xn=Dn([Bn(),Yn()],"Input is not a string or undefined"),Qn=Dn([Vn(),Gn()],"Input is not an array or boolean"),Zn=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>Ln(...e).validate(n[t]))),t(...n)),er=e=>[Bn(`"${e}" must be a string`)],tr=e=>[Xn(`"${e}" must be string or undefined`)],nr=e=>[Bn(`"${e}" must be a string`),Kn(`"${e}" must not be empty`)],rr=e=>[Bn(`"${e}" must be a string`),Hn()],sr=e=>[Bn(`"${e}" must be a string`),Jn()],ir=Zn(nr("accessKey")),or=e=>({exchange:ir(((t,n)=>$n(e.post(un.accessKey.exchange,{loginOptions:n},{token:t}))))}),ar=(e,t,n)=>(t.forEach((t=>{const r=t.split(".");let s=r.shift(),i=e;for(;r.length>0;){if(i=i[s],!s||!i)throw Error(`Invalid path "${t}", "${s}" is missing or has no value`);s=r.shift()}if("function"!=typeof i[s])throw Error(`"${t}" is not a function`);const o=i[s];i[s]=n(o)})),e),cr=({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||gn,gn)});var lr,dr;!function(e){e.sms="sms",e.voice="voice",e.whatsapp="whatsapp"}(lr||(lr={})),function(e){e.email="email"}(dr||(dr={}));const ur=Object.assign(Object.assign({},lr),dr);var hr;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(hr||(hr={}));const pr=nr("loginId"),gr=Zn(nr("token")),fr=Zn(pr),mr=Zn(nr("pendingRef")),wr=Zn(pr,rr("email")),_r=e=>({verify:gr((t=>$n(e.post(un.enchantedLink.verify,{token:t})))),signIn:fr(((t,n,r,s)=>$n(e.post(Mn(un.enchantedLink.signIn,ur.email),{loginId:t,URI:n,loginOptions:r},{token:s})))),signUpOrIn:fr(((t,n,r)=>$n(e.post(Mn(un.enchantedLink.signUpOrIn,ur.email),{loginId:t,URI:n,loginOptions:r})))),signUp:fr(((t,n,r,s)=>$n(e.post(Mn(un.enchantedLink.signUp,ur.email),{loginId:t,URI:n,user:r,loginOptions:s})))),waitForSession:mr(((t,n)=>new Promise((r=>{const{pollingIntervalMs:s,timeoutMs:i}=cr(n);let o;const a=setInterval((async()=>{const n=await e.post(un.enchantedLink.session,{pendingRef:t});n.ok&&(clearInterval(a),o&&clearTimeout(o),r($n(Promise.resolve(n))))}),s);o=setTimeout((()=>{r({error:{errorDescription:`Session polling timeout exceeded: ${i}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),i)})))),update:{email:wr(((t,n,r,s,i)=>$n(e.post(un.enchantedLink.update.email,Object.assign({loginId:t,email:n,URI:r},i),{token:s}))))}}),yr=Zn(nr("flowId")),vr=Zn(nr("executionId"),nr("stepId"),nr("interactionId")),br=e=>({start:yr(((t,n,r,s,i,o,a)=>$n(e.post(un.flow.start,{flowId:t,options:n,conditionInteractionId:r,interactionId:s,componentsVersion:i,flowVersions:o,input:a})))),next:vr(((t,n,r,s,i,o)=>$n(e.post(un.flow.next,{executionId:t,stepId:n,interactionId:r,version:s,componentsVersion:i,input:o}))))}),Sr=nr("loginId"),kr=Zn(nr("token")),Ir=Zn(Sr),xr=Zn(Sr,sr("phone")),Er=Zn(Sr,rr("email")),Or=Object.keys(ur).filter((e=>e!==lr.voice)),Tr=e=>({verify:kr((t=>$n(e.post(un.magicLink.verify,{token:t})))),signIn:Or.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ir(((t,r,s,i)=>$n(e.post(Mn(un.magicLink.signIn,n),{loginId:t,URI:r,loginOptions:s},{token:i}))))})),{}),signUp:Or.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ir(((t,r,s,i)=>$n(e.post(Mn(un.magicLink.signUp,n),{loginId:t,URI:r,user:s,loginOptions:i}))))})),{}),signUpOrIn:Or.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ir(((t,r,s)=>$n(e.post(Mn(un.magicLink.signUpOrIn,n),{loginId:t,URI:r,loginOptions:s}))))})),{}),update:{email:Er(((t,n,r,s,i)=>$n(e.post(un.magicLink.update.email,Object.assign({loginId:t,email:n,URI:r},i),{token:s})))),phone:Object.keys(lr).filter((e=>e!==lr.voice)).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:xr(((t,r,s,i,o)=>$n(e.post(Mn(un.magicLink.update.phone,n),Object.assign({loginId:t,phone:r,URI:s},o),{token:i}))))})),{})}});var Cr;!function(e){e.facebook="facebook",e.github="github",e.google="google",e.microsoft="microsoft",e.gitlab="gitlab",e.apple="apple",e.discord="discord",e.linkedin="linkedin",e.slack="slack"}(Cr||(Cr={}));const jr=Zn(nr("code")),Rr=e=>({start:Object.assign(((t,n,r,s)=>$n(e.post(un.oauth.start,r||{},{queryParams:Object.assign({provider:t},n&&{redirectURL:n}),token:s}))),Object.keys(Cr).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:(t,r,s)=>$n(e.post(un.oauth.start,r||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:s}))})),{})),exchange:jr((t=>$n(e.post(un.oauth.exchange,{code:t})))),startNative:(t,n,r)=>$n(e.post(un.oauth.startNative,{provider:t,loginOptions:n,implicit:r})),finishNative:(t,n,r,s,i)=>$n(e.post(un.oauth.finishNative,{provider:t,stateId:n,user:r,code:s,idToken:i})),getOneTapClientId:t=>$n(e.get(un.oauth.oneTap.getOneTapClientId.replace("{provider}",t))),verifyOneTapIDToken:(t,n,r,s)=>$n(e.post(un.oauth.oneTap.verifyOneTapIDToken,{provider:t,idToken:n,nonce:r,loginOptions:s})),exchangeOneTapIDToken:(t,n,r,s)=>$n(e.post(un.oauth.oneTap.exchangeOneTapIDToken,{provider:t,idToken:n,nonce:r,loginOptions:s}))}),Pr=nr("loginId"),Ur=Zn(Pr,nr("code")),Ar=Zn(Pr),Mr=Zn(Pr,sr("phone")),$r=Zn(Pr,rr("email")),Nr=e=>({verify:Object.keys(ur).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ur(((t,r)=>$n(e.post(Mn(un.otp.verify,n),{code:r,loginId:t}))))})),{}),signIn:Object.keys(ur).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ar(((t,r,s)=>$n(e.post(Mn(un.otp.signIn,n),{loginId:t,loginOptions:r},{token:s}))))})),{}),signUp:Object.keys(ur).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ar(((t,r,s)=>$n(e.post(Mn(un.otp.signUp,n),{loginId:t,user:r,loginOptions:s}))))})),{}),signUpOrIn:Object.keys(ur).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ar(((t,r)=>$n(e.post(Mn(un.otp.signUpOrIn,n),{loginId:t,loginOptions:r}))))})),{}),update:{email:$r(((t,n,r,s)=>$n(e.post(un.otp.update.email,Object.assign({loginId:t,email:n},s),{token:r})))),phone:Object.keys(lr).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Mr(((t,r,s,i)=>$n(e.post(Mn(un.otp.update.phone,n),Object.assign({loginId:t,phone:r},i),{token:s}))))})),{})}}),qr=Zn(nr("tenant")),Dr=Zn(nr("code")),Lr=e=>({start:qr(((t,n,r,s,i)=>$n(e.post(un.saml.start,r||{},Object.assign({queryParams:Object.assign(Object.assign({tenant:t},n&&{redirectURL:n}),i&&{ssoId:i})},s&&{token:s}))))),exchange:Dr((t=>$n(e.post(un.saml.exchange,{code:t}))))}),Wr=nr("loginId"),Fr=Zn(Wr,nr("code")),zr=Zn(Wr),Hr=Zn(Wr),Jr=e=>({signUp:zr(((t,n)=>$n(e.post(un.totp.signUp,{loginId:t,user:n})))),verify:Fr(((t,n,r,s)=>$n(e.post(un.totp.verify,{loginId:t,code:n,loginOptions:r},{token:s})))),update:Hr(((t,n)=>$n(e.post(un.totp.update,{loginId:t},{token:n}))))}),Kr=nr("loginId"),Br=nr("newPassword"),Vr=Zn(Kr,nr("password")),Gr=Zn(Kr),Yr=Zn(Kr,Br),Xr=Zn(Kr,nr("oldPassword"),Br),Qr=e=>({signUp:Vr(((t,n,r,s)=>$n(e.post(un.password.signUp,{loginId:t,password:n,user:r,loginOptions:s})))),signIn:Vr(((t,n,r)=>$n(e.post(un.password.signIn,{loginId:t,password:n,loginOptions:r})))),sendReset:Gr(((t,n,r)=>$n(e.post(un.password.sendReset,{loginId:t,redirectUrl:n,templateOptions:r})))),update:Yr(((t,n,r)=>$n(e.post(un.password.update,{loginId:t,newPassword:n},{token:r})))),replace:Xr(((t,n,r)=>$n(e.post(un.password.replace,{loginId:t,oldPassword:n,newPassword:r})))),policy:()=>$n(e.get(un.password.policy))}),Zr=er("loginId"),es=nr("loginId"),ts=nr("origin"),ns=Zn(es,ts,nr("name")),rs=Zn(es,ts),ss=Zn(Zr,ts),is=Zn(es,ts,tr("token")),os=Zn(nr("transactionId"),nr("response")),as=e=>({signUp:{start:ns(((t,n,r,s)=>$n(e.post(un.webauthn.signUp.start,{user:{loginId:t,name:r},origin:n,passkeyOptions:s})))),finish:os(((t,n)=>$n(e.post(un.webauthn.signUp.finish,{transactionId:t,response:n}))))},signIn:{start:ss(((t,n,r,s,i)=>$n(e.post(un.webauthn.signIn.start,{loginId:t,origin:n,loginOptions:r,passkeyOptions:i},{token:s})))),finish:os(((t,n)=>$n(e.post(un.webauthn.signIn.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:rs(((t,n,r)=>$n(e.post(un.webauthn.signUpOrIn.start,{loginId:t,origin:n,passkeyOptions:r}))))},update:{start:is(((t,n,r,s)=>$n(e.post(un.webauthn.update.start,{loginId:t,origin:n,passkeyOptions:s},{token:r})))),finish:os(((t,n)=>$n(e.post(un.webauthn.update.finish,{transactionId:t,response:n}))))}}),cs=er("loginId"),ls=Zn(cs),ds=Zn(nr("pendingRef")),us=e=>({signUpOrIn:ls(((t,n)=>$n(e.post(un.notp.signUpOrIn,{loginId:t,loginOptions:n})))),signUp:ls(((t,n,r)=>$n(e.post(un.notp.signUp,{loginId:t,user:n,loginOptions:r})))),signIn:ls(((t,n,r)=>$n(e.post(un.notp.signIn,{loginId:t,loginOptions:n},{token:r})))),waitForSession:ds(((t,n)=>new Promise((r=>{const{pollingIntervalMs:s,timeoutMs:i}=cr(n);let o;const a=setInterval((async()=>{const n=await e.post(un.notp.session,{pendingRef:t});n.ok&&(clearInterval(a),o&&clearTimeout(o),r($n(Promise.resolve(n))))}),s);o=setTimeout((()=>{r({error:{errorDescription:`Session polling timeout exceeded: ${i}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),i)}))))}),hs=Zn(nr("token")),ps=Zn(tr("token"));var gs,fs=Zn([(gs=nr("projectId"),qn(((e,t)=>n=>Ln(...t).validate(((e,t)=>{const n=(Array.isArray(t)?t.join("."):String(t)).replace(/\[\\?("|')?(\w|d)+\\?("|')?\]/g,((e,t,n)=>"."+n)).split("."),r=n.length;let s=0,i=e===Object(e)?e:void 0;for(;null!=i&&s<r;)i=i[n[s++]];return s&&s===r&&void 0!==i?i:void 0})(n,e)))("projectId",gs))())])((e=>t=>{var n;return e(Object.assign(Object.assign({},t),{hooks:{beforeRequest:e=>{var n;const r=[].concat((null===(n=t.hooks)||void 0===n?void 0:n.beforeRequest)||[]);return null==r?void 0:r.reduce(((e,t)=>t(e)),e)},afterRequest:async(e,n)=>{var r;const s=[].concat((null===(r=t.hooks)||void 0===r?void 0:r.afterRequest)||[]);0!=s.length&&(await Promise.allSettled(null==s?void 0:s.map((t=>t(e,null==n?void 0:n.clone()))))).forEach((e=>{var n;return"rejected"===e.status&&(null===(n=t.logger)||void 0===n?void 0:n.error(e.reason))}))},transformResponse:null===(n=t.hooks)||void 0===n?void 0:n.transformResponse}}))})((({projectId:e,logger:t,baseUrl:n,hooks:r,cookiePolicy:s,baseHeaders:i={},refreshCookieName:o,fetch:a})=>{return c=On({baseUrl:n||pn,projectId:e,logger:t,hooks:r,cookiePolicy:s,baseConfig:{baseHeaders:i},refreshCookieName:o,fetch:a}),{accessKey:or(c),otp:Nr(c),magicLink:Tr(c),enchantedLink:_r(c),oauth:Rr(c),saml:Lr(c),totp:Jr(c),notp:us(c),webauthn:as(c),password:Qr(c),flow:br(c),refresh:ps(((e,t)=>$n(c.post(un.refresh,{},{token:e,queryParams:t})))),selectTenant:Zn([Bn("tenantId")],[Xn('"token" must be string or undefined')])(((e,t)=>$n(c.post(un.selectTenant,{tenant:e},{token:t})))),logout:ps((e=>$n(c.post(un.logout,{},{token:e})))),logoutAll:ps((e=>$n(c.post(un.logoutAll,{},{token:e})))),me:ps((e=>$n(c.get(un.me,{token:e})))),myTenants:Zn([Qn('"tenants" must a string array or a boolean')],[Xn('"token" must be string or undefined')])(((e,t)=>{const n={};return"boolean"==typeof e?n.dct=e:n.ids=e,$n(c.post(un.myTenants,n,{token:t}))})),history:ps((e=>$n(c.get(un.history,{token:e})))),isJwtExpired:hs(Rn),getTenants:hs(Pn),getJwtPermissions:hs(Un),getJwtRoles:hs(An),getCurrentTenant:hs(Nn),httpClient:c};var c}))),ms=Object.assign(fs,{DeliveryMethods:ur});
|
|
5
|
+
this["descope-applications-portal-widget"]=function(){"use strict";var e=function(){return e=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},e.apply(this,arguments)};function t(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}function n(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{c(o.next(e))}catch(e){i(e)}}function a(e){try{c(o.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((o=o.apply(e,t||[])).next())}))}function o(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)}function r(e,t,n,o,r){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?r.call(e,n):r?r.value=n:t.set(e,n),n}function i(...e){return t=>e.reduce(((e,t)=>t(e)),t)}"function"==typeof SuppressedError&&SuppressedError;const s=e=>{const t=document.createElement("template");return t.innerHTML=e,t},a=e=>{const t=Symbol((e=>{const t=e.toString();let n=0;for(let e=0;e<t.length;e++)n=(n<<5)-n+t.charCodeAt(e),n&=n;return n.toString(16)})(e));return n=>{if(n[t])return n;const o=e(n);return o[t]=!0,o}};var c,l,u,d;function p(e,t){const n=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(n.length!==o.length)return!1;for(let o=0;o<n.length;o+=1){const r=n[o],i=e[r],s=t[r];if(null===i||null===s){if(i!==s)return!1}else if("object"==typeof i&&"object"==typeof s){if(!p(i,s))return!1}else if(i!==s)return!1}return!0}let h=class{constructor(e={},{forceUpdate:t=!1}={}){c.set(this,void 0),l.set(this,{}),u.set(this,0),d.set(this,!0),this.update=e=>{const t="function"==typeof e?e(o(this,c,"f")):e,n=Object.assign(Object.assign({},o(this,c,"f")),t);if(o(this,d,"f")||!p(o(this,c,"f"),n)){const e=o(this,c,"f");r(this,c,n,"f"),Object.freeze(o(this,c,"f")),setTimeout((()=>{Object.values(o(this,l,"f")).forEach((t=>t(n,e,((e,t)=>n=>e[n]!==t[n])(n,e))))}),0)}},r(this,c,e,"f"),r(this,d,t,"f")}get current(){return Object.assign({},o(this,c,"f"))}subscribe(e){return r(this,u,o(this,u,"f")+1,"f"),o(this,l,"f")[o(this,u,"f")]=e,o(this,u,"f").toString()}unsubscribe(e){const t=!!o(this,l,"f")[e];return t&&delete o(this,l,"f")[e],t}unsubscribeAll(){return r(this,l,{},"f"),!0}};c=new WeakMap,l=new WeakMap,u=new WeakMap,d=new WeakMap;const f=["error","warn","info","debug"],g=a((e=>{var t,n,i,s;return s=class extends e{constructor(){super(...arguments),t.add(this),n.set(this,o(this,t,"m",i).call(this,console))}set logger(e){r(this,n,o(this,t,"m",i).call(this,e||console),"f")}get logger(){return o(this,n,"f")}onLogEvent(e,t){}},n=new WeakMap,t=new WeakSet,i=function(e){return f.reduce(((t,n)=>(t[n]=(...t)=>{var o;this.onLogEvent(n,t),null===(o=e[n])||void 0===o||o.call(e,...t)},t)),{})},s})),m="undefined"!=typeof localStorage,v=m&&localStorage.getItem("base.content.url")||"",y=(e,t)=>!t&&`${e} cannot be empty, please make sure to set this attribute`,w=a((e=>{var t,n;return n=class extends e{constructor(){super(...arguments),t.set(this,!0)}connectedCallback(){var e,n;null===(e=super.connectedCallback)||void 0===e||e.call(this),(null===(n=this.shadowRoot)||void 0===n?void 0:n.isConnected)&&o(this,t,"f")&&(r(this,t,!1,"f"),this.init())}async init(){}},t=new WeakMap,n})),b=a((e=>{var t,n;const r=i(g,w)(e);return n=class extends r{constructor(){super(...arguments),t.set(this,{})}async init(){var e,n,r;await(null===(e=super.init)||void 0===e?void 0:e.call(this)),n=this,r=e=>{var n;null===(n=o(this,t,"f")[e])||void 0===n||n.forEach((t=>{t(e,this.getAttribute(e))}))},Array.from(n.attributes).forEach((e=>r(e.name))),new MutationObserver((e=>{e.forEach((e=>{"attributes"===e.type&&r(e.attributeName)}))})).observe(n,{attributes:!0})}observeAttribute(e,n){o(this,t,"f")[e]||(o(this,t,"f")[e]=[]);const r=o(this,t,"f")[e].push(n);return()=>o(this,t,"f")[e].splice(r,1)}observeAttributes(e,t){const n=e.reduce(((e,n)=>(e.push(this.observeAttribute(n,t)),e)),[]);return()=>n.forEach((e=>e()))}},t=new WeakMap,n})),k=e=>t=>{var n,r,s;const a=i(g,w,b)(t),c=Object.keys(e);return s=class extends a{constructor(...e){super(...e),n.add(this),this.observeAttributes(c,o(this,n,"m",r).bind(this))}async init(){var e;c.forEach((e=>o(this,n,"m",r).call(this,e,this.getAttribute(e)))),await(null===(e=super.init)||void 0===e?void 0:e.call(this))}},n=new WeakSet,r=function(t,n){const o=e[t],r="function"==typeof o?o(t,n):o;r&&this.logger.error(r)},s};k.missingAttrValidator=y;const S=a((e=>{const t=i(k({"project-id":y}))(e);return class extends t{get projectId(){return this.getAttribute("project-id")}}})),I=a((e=>class extends e{get baseUrl(){return this.getAttribute("base-url")||""}})),O="Trying the next fallback URL...";function j({projectId:e,filename:t,assetsFolder:n="v2-beta",baseUrl:o="https://static.descope.com/pages"}){const r=new URL(o);return r.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(r.pathname,e,n,t),r.baseUrl=o,r}const x=a((e=>{var t,n,s,a,c;const l=i(g,S,I)(e);return c=class extends l{constructor(){super(...arguments),t.add(this),n.set(this,void 0),s.set(this,void 0)}async fetchStaticResource(e,n){const i=o(this,t,"m",a).call(this,e),c=Array.isArray(i)?e=>{if(e!==i.length-1){const{baseUrl:t}=i[e];r(this,s,t,"f")}}:null;try{const e=await(async(e,t,{logger:n,onSuccess:o})=>{const r=Array.isArray(e)?e:[e];for(let e=0;e<r.length;e++){const i=r[e],s=e===r.length-1;try{const r=await fetch(i.toString(),t);if(r.ok)return null==o||o(e),r;const a=`Error fetching URL ${i} [${r.status}]`;if(s)throw new Error(a);null==n||n.debug(`${a}. ${O}`)}catch(e){const t=`Error fetching URL ${i} [${e.message}]`;if(s)throw new Error(t);null==n||n.debug(`${t}. ${O}`)}}})(i,{cache:"default"},{logger:this.logger,onSuccess:c});return{body:await e[n](),headers:Object.fromEntries(e.headers.entries())}}catch(e){this.logger.error(e.message)}}get baseStaticUrl(){return this.getAttribute("base-static-url")}},n=new WeakMap,s=new WeakMap,t=new WeakSet,a=function(e){const t=v||this.baseStaticUrl;if(t)return j({projectId:this.projectId,filename:e,baseUrl:t});const i=o(this,n,"f")!==this.baseUrl,a=i&&!!this.baseUrl;i&&(r(this,n,this.baseUrl,"f"),r(this,s,void 0,"f"));const c=j({projectId:this.projectId,filename:e,baseUrl:o(this,s,"f")});if(!a)return c;return[j({projectId:this.projectId,filename:e,baseUrl:this.baseUrl+"/pages"}),c]},c})),E=a((e=>{var t,n;const r=i(k({"project-id":y}))(e);return n=class extends r{constructor(){super(...arguments),t.set(this,new Map)}onReset(e,n){if(o(this,t,"f").has(e))throw new Error(`Callback for sectionId ${e} already exists`);return o(this,t,"f").set(e,n),()=>{o(this,t,"f").delete(e)}}async reset(...e){0===e.length?await Promise.all(Array.from(o(this,t,"f").values()).map((e=>e()))):await Promise.all(e.map((e=>{var n;if(!o(this,t,"f").has(e))throw new Error(`Callback for sectionId ${e} does not exist`);return null===(n=o(this,t,"f").get(e))||void 0===n?void 0:n()})))}},t=new WeakMap,n})),C=a((e=>{var t,n,s,a,c;const l=i(x,E,w)(e);return c=class extends l{constructor(){super(...arguments),t.add(this),s.set(this,void 0),a.set(this,(async()=>{try{const{body:e,headers:t}=await this.fetchStaticResource("config.json","json");return{projectConfig:e,executionContext:{geo:t["x-geo"]}}}catch(e){this.logger.error("Cannot fetch config file","make sure that your projectId & flowId are correct")}}))}async init(){await super.init(),this.onReset("config",o(this,t,"m",n).bind(this))}get config(){return o(this,s,"f")||r(this,s,o(this,a,"f").call(this),"f"),o(this,s,"f")}},s=new WeakMap,a=new WeakMap,t=new WeakSet,n=function(){r(this,s,void 0,"f")},c})),_=a((e=>{var t,n,s,a,c,l,u;return u=class extends(i(w,g)(e)){constructor(){super(...arguments),t.add(this),n.set(this,void 0),this.attributeChangedCallback=(e,n,r)=>{var i;null===(i=super.attributeChangedCallback)||void 0===i||i.call(this,e,n,r),"debug"===e&&o(this,t,"m",c).call(this)}}get debug(){return"true"===this.getAttribute("debug")}onLogEvent(e,n){var r;null===(r=super.onLogEvent)||void 0===r||r.call(this,e,n),"error"===e&&o(this,t,"m",l).call(this,n[0]||"Error",n[1])}async init(){var e;await(null===(e=super.init)||void 0===e?void 0:e.call(this)),o(this,t,"m",c).call(this)}},n=new WeakMap,t=new WeakSet,s=function(){var e;null===(e=o(this,n,"f"))||void 0===e||e.remove(),r(this,n,null,"f")},a=async function(){r(this,n,document.createElement("descope-debugger"),"f"),Object.assign(o(this,n,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),await Promise.resolve().then((function(){return Zi})),document.body.appendChild(o(this,n,"f"))},c=function(){this.debug?o(this,t,"m",a).call(this):o(this,t,"m",s).call(this)},l=function(e,t){var r;e&&(null===(r=o(this,n,"f"))||void 0===r||r.updateData({title:e,description:t}))},u})),T="load-descope-ui",A="base.ui.components.url",U=m&&localStorage.getItem(A)||"https://descopecdn.com/npm/@descope/web-components-ui@<version>/dist/umd/index.js",R=m&&localStorage.getItem(A)||"https://static.descope.com/npm/@descope/web-components-ui@<version>/dist/umd/index.js",P=m&&localStorage.getItem(A)||"https://cdn.jsdelivr.net/npm/@descope/web-components-ui@<version>/dist/umd/index.js",$=e=>{const t=document.createElement("script");return t.id=e,t},M=(e,t)=>e.replace("<version>",t),D=a((e=>{var t,n,s,a,c,l,u,d,p,h,f,m;const v=i(g,C)(e);return m=class extends v{constructor(){super(...arguments),t.add(this),n.set(this,Symbol("errorCbs")),s.set(this,Symbol("loadCbs")),p.set(this,void 0)}get descopeUi(){return o(this,p,"f")||r(this,p,o(this,t,"m",f).call(this),"f"),o(this,p,"f")}async loadDescopeUiComponents(e){const n=Array.isArray(e)?e:(e=>[...Array.from(e.content.querySelectorAll("*")).reduce(((e,t)=>t.localName.startsWith("descope-")?e.add(t.localName):e),new Set)])(e);return Promise.all(n.map((e=>o(this,t,"m",h).call(this,e))))}get baseCdnUrl(){return this.getAttribute("base-cdn-url")}},n=new WeakMap,s=new WeakMap,p=new WeakMap,t=new WeakSet,a=async function(){var e;const t=await this.config,n=null===(e=null==t?void 0:t.projectConfig)||void 0===e?void 0:e.componentsVersion;return n?this.logger.debug(`Got component version "${n}"`):this.logger.error("Could not get components version"),n},c=function(e){const t=o(this,n,"f"),r=o(this,s,"f");e[t]=[],e[r]=[],Object.defineProperty(e,"onerror",{set(n){e[t].push(n)}}),Object.defineProperty(e,"onload",{set(t){e[r].push(t)}})},l=async function(e,n,r,i){this.logger.debug("Trying to load DescopeUI from a fallback URL");const s=$(r);document.body.append(s),s.addEventListener("error",(()=>{e.forEach((e=>e(`Cannot load DescopeUI from fallback URL, Make sure this URL is valid and return the correct script: "${s.src}"`)))})),s.addEventListener("load",(()=>{n.forEach((e=>e()))})),s.src=M(i,await o(this,t,"m",a).call(this))},u=function(e){e.addEventListener("error",(()=>{e[o(this,n,"f")].forEach((t=>t(`Cannot load DescopeUI from main URL, Make sure this URL is valid and return the correct script: "${e.src}"`))),o(this,t,"m",l).call(this,[o(this,t,"m",l).bind(this,e[o(this,n,"f")],e[o(this,s,"f")],"load-descope-ui-fallback-script-2",P),...e[o(this,n,"f")]],e[o(this,s,"f")],"load-descope-ui-fallback-script",R)})),e.addEventListener("load",(()=>{e[o(this,s,"f")].forEach((e=>e()))}))},d=async function(){if(document.querySelector(`script#${T}`))this.logger.debug("DescopeUI loading script already exists",this);else{this.logger.debug("DescopeUI loading script does not exist, creating it",this);const e=$(T);document.body.append(e),o(this,t,"m",c).call(this,e),o(this,t,"m",u).call(this,e),e.src=M(this.baseCdnUrl||U,await o(this,t,"m",a).call(this))}return document.getElementById(T)},h=async function(e){if(!!customElements.get(e))return void this.logger.debug(`Loading component "${e}" is skipped as it is already defined`);const t=await this.descopeUi;if(t[e])try{return await t[e]()}catch(t){if("NotSupportedError"!==t.name)throw t;console.debug(`Encountered an error while attempting to define the "${e}" component, it is likely that this component is already defined`)}else this.logger.error(`Cannot load UI component "${e}"`,`Descope UI does not have a component named "${e}", available components are: "${Object.keys(t).join(", ")}"`)},f=function(){return new Promise((e=>{globalThis.DescopeUI&&e(globalThis.DescopeUI),o(this,t,"m",d).call(this).then((t=>{t.onerror=this.logger.error,t.onload=()=>{this.logger.debug("DescopeUI was loaded"),e(globalThis.DescopeUI)},setTimeout((()=>{globalThis.DescopeUI&&e(globalThis.DescopeUI)}))}))}))},m})),L="content-root",N="root",W=a((e=>class extends e{constructor(...e){var t,n,o,r;super(...e),this.attachShadow({mode:"open"}).innerHTML=`\n <div id="${N}">\n <div id="${L}"></div>\n </div>\n `;const i=new CSSStyleSheet;i.replaceSync(`\n #${N}, #${L} {\n height: 100%;\n }\n #${N} {\n position: relative;\n height: fit-content;\n }\n `),null!==(t=(r=this.shadowRoot).adoptedStyleSheets)&&void 0!==t||(r.adoptedStyleSheets=[]),this.shadowRoot.adoptedStyleSheets=[...this.shadowRoot.adoptedStyleSheets,i],this.contentRootElement=null===(n=this.shadowRoot)||void 0===n?void 0:n.getElementById(L),this.rootElement=null===(o=this.shadowRoot)||void 0===o?void 0:o.getElementById(N)}})),z="descope-modal";var F;let q=class{constructor(e,t){F.set(this,void 0),this.nodeName="",r(this,F,e,"f"),this.logger=t.logger}get asyncEle(){return(async e=>new Promise((t=>{const n=setInterval((()=>{const o="function"==typeof e?e():e;o&&(clearInterval(n),t(o))}),100);setTimeout((()=>{clearInterval(n),t(null)}),1e3)})))(o(this,F,"f"))}get ele(){var e,t;const n="function"==typeof o(this,F,"f")?o(this,F,"f").call(this):o(this,F,"f");return n?(null==n?void 0:n.localName)!==this.nodeName?(null===(t=this.logger)||void 0===t||t.debug(`node name do not match, expected "${this.nodeName}", received "${n.localName}" `,Error()),null):n:(null===(e=this.logger)||void 0===e||e.debug(`Driver element is not available for ${this.nodeName}`,new Error),null)}};var J;F=new WeakMap;let K=class extends q{constructor(){super(...arguments),J.set(this,void 0),this.nodeName="descope-modal"}close(){var e,t;null===(e=this.ele)||void 0===e||e.removeAttribute("opened"),null===(t=this.afterClose)||void 0===t||t.call(this)}async open(){var e,t;await(null===(e=this.beforeOpen)||void 0===e?void 0:e.call(this)),null===(t=this.ele)||void 0===t||t.setAttribute("opened","true")}reset(){var e;this.ele&&(this.ele.innerHTML=""),o(this,J,"f")&&(null===(e=this.ele)||void 0===e||e.append(o(this,J,"f").content.cloneNode(!0)))}setContent(e){r(this,J,e,"f"),this.reset()}remove(){var e;null===(e=this.ele)||void 0===e||e.remove()}};J=new WeakMap;let V=class extends q{constructor(){super(...arguments),this.nodeName="descope-notification"}close(){var e;null===(e=this.ele)||void 0===e||e.removeAttribute("opened")}show(){var e;null===(e=this.ele)||void 0===e||e.setAttribute("opened","true")}setContent(e){this.ele.innerHTML="",this.ele.appendChild(e.content.cloneNode(!0))}remove(){var e;null===(e=this.ele)||void 0===e||e.remove()}},H=class extends q{constructor(){super(...arguments),this.nodeName="descope-apps-list"}set data(e){this.ele&&(this.ele.data=e)}get data(){var e;return null===(e=this.ele)||void 0===e?void 0:e.data}get ele(){return super.ele}};a((e=>{var t,n;const r=i(w,W,D)(e);return n=class extends r{constructor(){super(...arguments),t.set(this,(()=>{const e=this.loadDescopeUiComponents.bind(this);return class extends K{setContent(t){e(t),super.setContent(t)}}})())}createModal(e){const n=((e={})=>{const t=document.createElement(z);return Object.keys(e).forEach((n=>{t.setAttribute(n,e[n])})),t})(Object.assign(Object.assign({},{}),e));return this.rootElement.append(n),new(o(this,t,"f"))(n,{logger:this.logger})}async init(){var e;this.loadDescopeUiComponents([z]),await(null===(e=super.init)||void 0===e?void 0:e.call(this))}},t=new WeakMap,n}));const B="descope-notification";a((e=>{var t,n;const r=i(w,W,D)(e);return n=class extends r{constructor(){super(...arguments),t.set(this,(()=>{const e=this.loadDescopeUiComponents.bind(this);return class extends V{setContent(t){const n="string"==typeof t?s(t):t;e(n),super.setContent(n)}}})())}createNotification(e){const n=((e={})=>{const t=document.createElement(B);return Object.keys(e).forEach((n=>{t.setAttribute(n,e[n])})),t})(Object.assign(Object.assign({},{}),e));return this.rootElement.append(n),new(o(this,t,"f"))(n,{logger:this.logger})}async init(){var e;await(null===(e=super.init)||void 0===e?void 0:e.call(this)),this.loadDescopeUiComponents([B])}},t=new WeakMap,n}));const Y=(e,t)=>!!t&&"light"!==t&&"dark"!==t&&'Supported theme values are "light", "dark", or leave empty for using the OS theme',X=a((e=>{var t,n,s,a,c,l,u,d,p,h,f,g,m,v;const y=i(k({theme:Y}),x,w,D,C,W,b)(e);return v=class extends y{constructor(){super(...arguments),t.add(this),n.set(this,void 0),s.set(this,void 0),f.set(this,(()=>{o(this,t,"m",g).call(this),o(this,m,"f").call(this,"os"===this.getAttribute("theme"))})),m.set(this,(e=>{var n,r,i;const s=e?"addEventListener":"removeEventListener";null===(i=null===(r=null===(n=window.matchMedia)||void 0===n?void 0:n.call(window,"(prefers-color-scheme: dark)"))||void 0===r?void 0:r[s])||void 0===i||i.call(r,"change",(()=>o(this,t,"m",g).call(this)))}))}get theme(){var e,t;const n=this.getAttribute("theme");if("os"===n){return window.matchMedia&&(null===(t=null===(e=window.matchMedia)||void 0===e?void 0:e.call(window,"(prefers-color-scheme: dark)"))||void 0===t?void 0:t.matches)?"dark":"light"}return n||"light"}get styleId(){return this.getAttribute("style-id")||"theme"}async init(){var e;await(null===(e=super.init)||void 0===e?void 0:e.call(this)),o(this,t,"m",l).call(this),o(this,t,"m",u).call(this),o(this,f,"f").call(this),this.observeAttributes(["theme"],o(this,f,"f")),this.observeAttributes(["style-id"],(()=>{r(this,s,null,"f"),o(this,t,"m",p).call(this),o(this,t,"m",l).call(this),o(this,t,"m",u).call(this)}))}},n=new WeakMap,s=new WeakMap,f=new WeakMap,m=new WeakMap,t=new WeakSet,a=async function(){try{const{body:e}=await this.fetchStaticResource(`${this.styleId}.json`,"json");if(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(A))try{this.logger.warn("You are in DEV mode, and UI components override URL was found\ntrying to merge project theme with the default theme of the UI components");const t=await(async()=>{const e=localStorage.getItem(A),t=null==e?void 0:e.replace(/[^\/]+$/,"DescopeDev.js");console.warn("Trying to load DescopeDev.js from",t);const n=document.createElement("script");if(n.src=t,document.body.appendChild(n),await new Promise(((e,t)=>{n.onload=e,n.onerror=t})),globalThis.DescopeDev){const{themeToStyle:e,defaultTheme:t,darkTheme:n}=globalThis.DescopeDev;return{light:e(t),dark:e(n)}}})();t&&(e.light.components=Object.assign(Object.assign({},e.light.components),t.light.components),e.dark.components=Object.assign(Object.assign({},e.dark.components),t.dark.components),this.logger.warn("Theme was merged successfully"),console.log("%cNOTICE! This is not the theme that will be used in production!\n\nMake sure to test it without the override UI components URL!","color: black; background-color:yellow; font-size: x-large"))}catch(e){this.logger.error("Failed to merge UI components theme\n",e)}return e}catch(e){this.logger.error("Cannot fetch theme file","make sure that your projectId & flowId are correct")}},c=function(){return o(this,s,"f")||(r(this,s,o(this,t,"m",a).call(this),"f"),o(this,s,"f").then((e=>this.logger.debug("Fetched theme",e)))),o(this,s,"f")},l=async function(){var e,i,s,a;const l=await o(this,t,"a",c);l&&(o(this,n,"f")||(r(this,n,new CSSStyleSheet,"f"),null!==(e=(a=this.shadowRoot).adoptedStyleSheets)&&void 0!==e||(a.adoptedStyleSheets=[]),this.shadowRoot.adoptedStyleSheets=[...this.shadowRoot.adoptedStyleSheets,o(this,n,"f")]),o(this,n,"f").replaceSync(((null===(i=null==l?void 0:l.light)||void 0===i?void 0:i.globals)||"")+((null===(s=null==l?void 0:l.dark)||void 0===s?void 0:s.globals)||"")))},u=async function(){var e,n;const r=Object.assign({},await o(this,t,"a",c));if(!r)return;const i=await this.descopeUi;(null==i?void 0:i.componentsThemeManager)&&(i.componentsThemeManager.themes={light:null===(e=null==r?void 0:r.light)||void 0===e?void 0:e.components,dark:null===(n=null==r?void 0:r.dark)||void 0===n?void 0:n.components})},d=async function(){var e,t;const{projectConfig:n}=await this.config||{},o=null===(e=null==n?void 0:n.styles)||void 0===e?void 0:e[this.styleId],r=null==n?void 0:n.cssTemplate,i=o||r;return null===(t=null==i?void 0:i[this.theme])||void 0===t?void 0:t.fonts},p=async function(){const e=await o(this,t,"m",d).call(this);e?Object.values(e).forEach((e=>{e.url&&(this.logger.debug(`Loading font from URL "${e.url}"`),(e=>{const t=document.createElement("link");t.href=e,t.rel="stylesheet",document.head.appendChild(t)})(e.url))})):this.logger.debug("No fonts to load")},h=async function(){this.rootElement.setAttribute("data-theme",this.theme);const e=await this.descopeUi;(null==e?void 0:e.componentsThemeManager)&&(e.componentsThemeManager.currentThemeName=this.theme)},g=function(){o(this,t,"m",p).call(this),o(this,t,"m",h).call(this)},v}));var G=(()=>"function"==typeof Symbol&&Symbol.observable||"@@observable")(),Z=()=>Math.random().toString(36).substring(7).split("").join("."),Q={INIT:`@@redux/INIT${Z()}`,REPLACE:`@@redux/REPLACE${Z()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${Z()}`};function ee(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||null===Object.getPrototypeOf(e)}function te(e){if(void 0===e)return"undefined";if(null===e)return"null";const t=typeof e;switch(t){case"boolean":case"string":case"number":case"symbol":case"function":return t}if(Array.isArray(e))return"array";if(function(e){return e instanceof Date||"function"==typeof e.toDateString&&"function"==typeof e.getDate&&"function"==typeof e.setDate}(e))return"date";if(function(e){return e instanceof Error||"string"==typeof e.message&&e.constructor&&"number"==typeof e.constructor.stackTraceLimit}(e))return"error";const n=function(e){return"function"==typeof e.constructor?e.constructor.name:null}(e);switch(n){case"Symbol":case"Promise":case"WeakMap":case"WeakSet":case"Map":case"Set":return n}return Object.prototype.toString.call(e).slice(8,-1).toLowerCase().replace(/\s/g,"")}function ne(e){let t=typeof e;return t=te(e),t}function oe(e,t,n){if("function"!=typeof e)throw new Error(`Expected the root reducer to be a function. Instead, received: '${ne(e)}'`);if("function"==typeof t&&"function"==typeof n||"function"==typeof n&&"function"==typeof arguments[3])throw new Error("It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.");if("function"==typeof t&&void 0===n&&(n=t,t=void 0),void 0!==n){if("function"!=typeof n)throw new Error(`Expected the enhancer to be a function. Instead, received: '${ne(n)}'`);return n(oe)(e,t)}let o=e,r=t,i=new Map,s=i,a=0,c=!1;function l(){s===i&&(s=new Map,i.forEach(((e,t)=>{s.set(t,e)})))}function u(){if(c)throw new Error("You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");return r}function d(e){if("function"!=typeof e)throw new Error(`Expected the listener to be a function. Instead, received: '${ne(e)}'`);if(c)throw new Error("You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.");let t=!0;l();const n=a++;return s.set(n,e),function(){if(t){if(c)throw new Error("You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.");t=!1,l(),s.delete(n),i=null}}}function p(e){if(!ee(e))throw new Error(`Actions must be plain objects. Instead, the actual type was: '${ne(e)}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`);if(void 0===e.type)throw new Error('Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');if("string"!=typeof e.type)throw new Error(`Action "type" property must be a string. Instead, the actual type was: '${ne(e.type)}'. Value was: '${e.type}' (stringified)`);if(c)throw new Error("Reducers may not dispatch actions.");try{c=!0,r=o(r,e)}finally{c=!1}return(i=s).forEach((e=>{e()})),e}p({type:Q.INIT});return{dispatch:p,subscribe:d,getState:u,replaceReducer:function(e){if("function"!=typeof e)throw new Error(`Expected the nextReducer to be a function. Instead, received: '${ne(e)}`);o=e,p({type:Q.REPLACE})},[G]:function(){const e=d;return{subscribe(t){if("object"!=typeof t||null===t)throw new Error(`Expected the observer to be an object. Instead, received: '${ne(t)}'`);function n(){const e=t;e.next&&e.next(u())}n();return{unsubscribe:e(n)}},[G](){return this}}}}}function re(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}function ie(e){const t=Object.keys(e),n={};for(let o=0;o<t.length;o++){const r=t[o];void 0===e[r]&&re(`No reducer provided for key "${r}"`),"function"==typeof e[r]&&(n[r]=e[r])}const o=Object.keys(n);let r,i;r={};try{!function(e){Object.keys(e).forEach((t=>{const n=e[t];if(void 0===n(void 0,{type:Q.INIT}))throw new Error(`The slice reducer for key "${t}" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);if(void 0===n(void 0,{type:Q.PROBE_UNKNOWN_ACTION()}))throw new Error(`The slice reducer for key "${t}" returned undefined when probed with a random type. Don't try to handle '${Q.INIT}' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.`)}))}(n)}catch(e){i=e}return function(e={},t){if(i)throw i;{const o=function(e,t,n,o){const r=Object.keys(t),i=n&&n.type===Q.INIT?"preloadedState argument passed to createStore":"previous state received by the reducer";if(0===r.length)return"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";if(!ee(e))return`The ${i} has unexpected type of "${ne(e)}". Expected argument to be an object with the following keys: "${r.join('", "')}"`;const s=Object.keys(e).filter((e=>!t.hasOwnProperty(e)&&!o[e]));return s.forEach((e=>{o[e]=!0})),n&&n.type===Q.REPLACE?void 0:s.length>0?`Unexpected ${s.length>1?"keys":"key"} "${s.join('", "')}" found in ${i}. Expected to find one of the known reducer keys instead: "${r.join('", "')}". Unexpected keys will be ignored.`:void 0}(e,n,t,r);o&&re(o)}let s=!1;const a={};for(let r=0;r<o.length;r++){const i=o[r],c=n[i],l=e[i],u=c(l,t);if(void 0===u){const e=t&&t.type;throw new Error(`When called with an action of type ${e?`"${String(e)}"`:"(unknown type)"}, the slice reducer for key "${i}" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.`)}a[i]=u,s=s||u!==l}return s=s||o.length!==Object.keys(e).length,s?a:e}}function se(...e){return 0===e.length?e=>e:1===e.length?e[0]:e.reduce(((e,t)=>(...n)=>e(t(...n))))}function ae(e){return ee(e)&&"type"in e&&"string"==typeof e.type}var ce=Symbol.for("immer-nothing"),le=Symbol.for("immer-draftable"),ue=Symbol.for("immer-state"),de=[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}];function pe(e,...t){{const n=de[e],o="function"==typeof n?n.apply(null,t):n;throw new Error(`[Immer] ${o}`)}}var he=Object.getPrototypeOf;function fe(e){return!!e&&!!e[ue]}function ge(e){return!!e&&(ve(e)||Array.isArray(e)||!!e[le]||!!e.constructor?.[le]||Se(e)||Ie(e))}var me=Object.prototype.constructor.toString();function ve(e){if(!e||"object"!=typeof e)return!1;const t=he(e);if(null===t)return!0;const n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object||"function"==typeof n&&Function.toString.call(n)===me}function ye(e,t){0===we(e)?Object.entries(e).forEach((([n,o])=>{t(n,o,e)})):e.forEach(((n,o)=>t(o,n,e)))}function we(e){const t=e[ue];return t?t.type_:Array.isArray(e)?1:Se(e)?2:Ie(e)?3:0}function be(e,t){return 2===we(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ke(e,t,n){const o=we(e);2===o?e.set(t,n):3===o?e.add(n):e[t]=n}function Se(e){return e instanceof Map}function Ie(e){return e instanceof Set}function Oe(e){return e.copy_||e.base_}function je(e,t){if(Se(e))return new Map(e);if(Ie(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&ve(e)){if(!he(e)){const t=Object.create(null);return Object.assign(t,e)}return{...e}}const n=Object.getOwnPropertyDescriptors(e);delete n[ue];let o=Reflect.ownKeys(n);for(let t=0;t<o.length;t++){const r=o[t],i=n[r];!1===i.writable&&(i.writable=!0,i.configurable=!0),(i.get||i.set)&&(n[r]={configurable:!0,writable:!0,enumerable:i.enumerable,value:e[r]})}return Object.create(he(e),n)}function xe(e,t=!1){return Ce(e)||fe(e)||!ge(e)||(we(e)>1&&(e.set=e.add=e.clear=e.delete=Ee),Object.freeze(e),t&&ye(e,((e,t)=>xe(t,!0)))),e}function Ee(){pe(2)}function Ce(e){return Object.isFrozen(e)}var _e,Te={};function Ae(e){const t=Te[e];return t||pe(0,e),t}function Ue(){return _e}function Re(e,t){t&&(Ae("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Pe(e){$e(e),e.drafts_.forEach(De),e.drafts_=null}function $e(e){e===_e&&(_e=e.parent_)}function Me(e){return _e={drafts_:[],parent_:_e,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function De(e){const t=e[ue];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function Le(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return void 0!==e&&e!==n?(n[ue].modified_&&(Pe(t),pe(4)),ge(e)&&(e=Ne(t,e),t.parent_||ze(t,e)),t.patches_&&Ae("Patches").generateReplacementPatches_(n[ue].base_,e,t.patches_,t.inversePatches_)):e=Ne(t,n,[]),Pe(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==ce?e:void 0}function Ne(e,t,n){if(Ce(t))return t;const o=t[ue];if(!o)return ye(t,((r,i)=>We(e,o,t,r,i,n))),t;if(o.scope_!==e)return t;if(!o.modified_)return ze(e,o.base_,!0),o.base_;if(!o.finalized_){o.finalized_=!0,o.scope_.unfinalizedDrafts_--;const t=o.copy_;let r=t,i=!1;3===o.type_&&(r=new Set(t),t.clear(),i=!0),ye(r,((r,s)=>We(e,o,t,r,s,n,i))),ze(e,t,!1),n&&e.patches_&&Ae("Patches").generatePatches_(o,n,e.patches_,e.inversePatches_)}return o.copy_}function We(e,t,n,o,r,i,s){if(r===n&&pe(5),fe(r)){const s=Ne(e,r,i&&t&&3!==t.type_&&!be(t.assigned_,o)?i.concat(o):void 0);if(ke(n,o,s),!fe(s))return;e.canAutoFreeze_=!1}else s&&n.add(r);if(ge(r)&&!Ce(r)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ne(e,r),t&&t.scope_.parent_||ze(e,r)}}function ze(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&xe(t,n)}var Fe={get(e,t){if(t===ue)return e;const n=Oe(e);if(!be(n,t))return function(e,t,n){const o=Ke(t,n);return o?"value"in o?o.value:o.get?.call(e.draft_):void 0}(e,n,t);const o=n[t];return e.finalized_||!ge(o)?o:o===Je(e.base_,t)?(He(e),e.copy_[t]=Be(o,e)):o},has:(e,t)=>t in Oe(e),ownKeys:e=>Reflect.ownKeys(Oe(e)),set(e,t,n){const o=Ke(Oe(e),t);if(o?.set)return o.set.call(e.draft_,n),!0;if(!e.modified_){const o=Je(Oe(e),t),r=o?.[ue];if(r&&r.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}(n,o)&&(void 0!==n||be(e.base_,t)))return!0;He(e),Ve(e)}return e.copy_[t]===n&&(void 0!==n||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty:(e,t)=>(void 0!==Je(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,He(e),Ve(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=Oe(e),o=Reflect.getOwnPropertyDescriptor(n,t);return o?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:o.enumerable,value:n[t]}:o},defineProperty(){pe(11)},getPrototypeOf:e=>he(e.base_),setPrototypeOf(){pe(12)}},qe={};function Je(e,t){const n=e[ue];return(n?Oe(n):e)[t]}function Ke(e,t){if(!(t in e))return;let n=he(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=he(n)}}function Ve(e){e.modified_||(e.modified_=!0,e.parent_&&Ve(e.parent_))}function He(e){e.copy_||(e.copy_=je(e.base_,e.scope_.immer_.useStrictShallowCopy_))}ye(Fe,((e,t)=>{qe[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}})),qe.deleteProperty=function(e,t){return isNaN(parseInt(t))&&pe(13),qe.set.call(this,e,t,void 0)},qe.set=function(e,t,n){return"length"!==t&&isNaN(parseInt(t))&&pe(14),Fe.set.call(this,e[0],t,n,e[0])};function Be(e,t){const n=Se(e)?Ae("MapSet").proxyMap_(e,t):Ie(e)?Ae("MapSet").proxySet_(e,t):function(e,t){const n=Array.isArray(e),o={type_:n?1:0,scope_:t?t.scope_:Ue(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let r=o,i=Fe;n&&(r=[o],i=qe);const{revoke:s,proxy:a}=Proxy.revocable(r,i);return o.draft_=a,o.revoke_=s,a}(e,t);return(t?t.scope_:Ue()).drafts_.push(n),n}function Ye(e){return fe(e)||pe(10,e),Xe(e)}function Xe(e){if(!ge(e)||Ce(e))return e;const t=e[ue];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=je(e,t.scope_.immer_.useStrictShallowCopy_)}else n=je(e,!0);return ye(n,((e,t)=>{ke(n,e,Xe(t))})),t&&(t.finalized_=!1),n}var Ge=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,n)=>{if("function"==typeof e&&"function"!=typeof t){const n=t;t=e;const o=this;return function(e=n,...r){return o.produce(e,(e=>t.call(this,e,...r)))}}let o;if("function"!=typeof t&&pe(6),void 0!==n&&"function"!=typeof n&&pe(7),ge(e)){const r=Me(this),i=Be(e,void 0);let s=!0;try{o=t(i),s=!1}finally{s?Pe(r):$e(r)}return Re(r,n),Le(o,r)}if(!e||"object"!=typeof e){if(o=t(e),void 0===o&&(o=e),o===ce&&(o=void 0),this.autoFreeze_&&xe(o,!0),n){const t=[],r=[];Ae("Patches").generateReplacementPatches_(e,o,t,r),n(t,r)}return o}pe(1,e)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...n)=>this.produceWithPatches(t,(t=>e(t,...n)));let n,o;const r=this.produce(e,t,((e,t)=>{n=e,o=t}));return[r,n,o]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){ge(e)||pe(8),fe(e)&&(e=Ye(e));const t=Me(this),n=Be(e,void 0);return n[ue].isManual_=!0,$e(t),n}finishDraft(e,t){const n=e&&e[ue];n&&n.isManual_||pe(9);const{scope_:o}=n;return Re(o,t),Le(void 0,o)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(0===o.path.length&&"replace"===o.op){e=o.value;break}}n>-1&&(t=t.slice(n+1));const o=Ae("Patches").applyPatches_;return fe(e)?o(e,t):this.produce(e,(e=>o(e,t)))}},Ze=Ge.produce;Ge.produceWithPatches.bind(Ge),Ge.setAutoFreeze.bind(Ge),Ge.setUseStrictShallowCopy.bind(Ge),Ge.applyPatches.bind(Ge),Ge.createDraft.bind(Ge),Ge.finishDraft.bind(Ge);var Qe=(e,t,n)=>{if(1===t.length&&t[0]===n){let t=!1;try{const n={};e(n)===n&&(t=!0)}catch{}if(t){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("The result function returned its own inputs without modification. e.g\n`createSelector([state => state.todos], todos => todos)`\nThis could lead to inefficient memoization and unnecessary re-renders.\nEnsure transformation logic is in the result function, and extraction logic is in the input selectors.",{stack:e})}}},et=(e,t,n)=>{const{memoize:o,memoizeOptions:r}=t,{inputSelectorResults:i,inputSelectorResultsCopy:s}=e,a=o((()=>({})),...r);if(!(a.apply(null,i)===a.apply(null,s))){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("An input selector returned a different result when passed same arguments.\nThis means your output selector will likely run more frequently than intended.\nAvoid returning a new reference inside your input selector, e.g.\n`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)`",{arguments:n,firstInputs:i,secondInputs:s,stack:e})}},tt={inputStabilityCheck:"once",identityFunctionCheck:"once"};var nt=e=>Array.isArray(e)?e:[e];function ot(e){const t=Array.isArray(e[0])?e[0]:e;return function(e,t="expected all items to be functions, instead received the following types: "){if(!e.every((e=>"function"==typeof e))){const n=e.map((e=>"function"==typeof e?`function ${e.name||"unnamed"}()`:typeof e)).join(", ");throw new TypeError(`${t}[${n}]`)}}(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}function rt(e,t){const n=[],{length:o}=e;for(let r=0;r<o;r++)n.push(e[r].apply(null,t));return n}var it="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}},st=0,at=1;function ct(){return{s:st,v:void 0,o:null,p:null}}function lt(e,t={}){let n=ct();const{resultEqualityCheck:o}=t;let r,i=0;function s(){let t=n;const{length:s}=arguments;for(let e=0,n=s;e<n;e++){const n=arguments[e];if("function"==typeof n||"object"==typeof n&&null!==n){let e=t.o;null===e&&(t.o=e=new WeakMap);const o=e.get(n);void 0===o?(t=ct(),e.set(n,t)):t=o}else{let e=t.p;null===e&&(t.p=e=new Map);const o=e.get(n);void 0===o?(t=ct(),e.set(n,t)):t=o}}const a=t;let c;if(t.s===at)c=t.v;else if(c=e.apply(null,arguments),i++,o){const e=r?.deref?.()??r;null!=e&&o(e,c)&&(c=e,0!==i&&i--);r="object"==typeof c&&null!==c||"function"==typeof c?new it(c):c}return a.s=at,a.v=c,c}return s.clearCache=()=>{n=ct(),s.resetResultsCount()},s.resultsCount=()=>i,s.resetResultsCount=()=>{i=0},s}function ut(e,...t){const n="function"==typeof e?{memoize:e,memoizeOptions:t}:e,o=(...e)=>{let t,o=0,r=0,i={},s=e.pop();"object"==typeof s&&(i=s,s=e.pop()),function(e,t="expected a function, instead received "+typeof e){if("function"!=typeof e)throw new TypeError(t)}(s,`createSelector expects an output function after the inputs, but received: [${typeof s}]`);const a={...n,...i},{memoize:c,memoizeOptions:l=[],argsMemoize:u=lt,argsMemoizeOptions:d=[],devModeChecks:p={}}=a,h=nt(l),f=nt(d),g=ot(e),m=c((function(){return o++,s.apply(null,arguments)}),...h);let v=!0;const y=u((function(){r++;const e=rt(g,arguments);t=m.apply(null,e);{const{identityFunctionCheck:n,inputStabilityCheck:o}=((e,t)=>{const{identityFunctionCheck:n,inputStabilityCheck:o}={...tt,...t};return{identityFunctionCheck:{shouldRun:"always"===n||"once"===n&&e,run:Qe},inputStabilityCheck:{shouldRun:"always"===o||"once"===o&&e,run:et}}})(v,p);if(n.shouldRun&&n.run(s,e,t),o.shouldRun){const t=rt(g,arguments);o.run({inputSelectorResults:e,inputSelectorResultsCopy:t},{memoize:c,memoizeOptions:h},arguments)}v&&(v=!1)}return t}),...f);return Object.assign(y,{resultFunc:s,memoizedResultFunc:m,dependencies:g,dependencyRecomputations:()=>r,resetDependencyRecomputations:()=>{r=0},lastResult:()=>t,recomputations:()=>o,resetRecomputations:()=>{o=0},memoize:c,argsMemoize:u})};return Object.assign(o,{withTypes:()=>o}),o}var dt=ut(lt),pt=Object.assign(((e,t=dt)=>{!function(e,t="expected an object, instead received "+typeof e){if("object"!=typeof e)throw new TypeError(t)}(e,"createStructuredSelector expects first argument to be an object where each property is a selector, instead received a "+typeof e);const n=Object.keys(e);return t(n.map((t=>e[t])),((...e)=>e.reduce(((e,t,o)=>(e[n[o]]=t,e)),{})))}),{withTypes:()=>pt});function ht(e){return({dispatch:t,getState:n})=>o=>r=>"function"==typeof r?r(t,n,e):o(r)}var ft=ht(),gt=ht;((...e)=>{const t=ut(...e)})(lt);var mt="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(0!==arguments.length)return"object"==typeof arguments[0]?se:se.apply(null,arguments)},vt=e=>e&&"function"==typeof e.match;function yt(e,t){function n(...n){if(t){let o=t(...n);if(!o)throw new Error("prepareAction did not return an object");return{type:e,payload:o.payload,..."meta"in o&&{meta:o.meta},..."error"in o&&{error:o.error}}}return{type:e,payload:n[0]}}return n.toString=()=>`${e}`,n.type=e,n.match=t=>ae(t)&&t.type===e,n}function wt(e){return"function"==typeof e&&"type"in e&&vt(e)}function bt(e,t){let n=0;return{measureTime(e){const t=Date.now();try{return e()}finally{const e=Date.now();n+=e-t}},warnIfExceeded(){n>e&&console.warn(`${t} took ${n}ms, which is more than the warning threshold of ${e}ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.`)}}}var kt=class e extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,e.prototype)}static get[Symbol.species](){return e}concat(...e){return super.concat.apply(this,e)}prepend(...t){return 1===t.length&&Array.isArray(t[0])?new e(...t[0].concat(this)):new e(...t.concat(this))}};function St(e){return ge(e)?Ze(e,(()=>{})):e}function It(e,t,n){if(e.has(t)){let o=e.get(t);return n.update&&(o=n.update(o,t,e),e.set(t,o)),o}if(!n.insert)throw new Error("No insert provided for key not already in map");const o=n.insert(t,e);return e.set(t,o),o}function Ot(e){return"object"!=typeof e||null==e||Object.isFrozen(e)}function jt(e,t,n){const o=xt(e,t,n);return{detectMutations:()=>Et(e,t,o,n)}}function xt(e,t=[],n,o="",r=new Set){const i={value:n};if(!e(n)&&!r.has(n)){r.add(n),i.children={};for(const r in n){const s=o?o+"."+r:r;t.length&&-1!==t.indexOf(s)||(i.children[r]=xt(e,t,n[r],s))}}return i}function Et(e,t=[],n,o,r=!1,i=""){const s=n?n.value:void 0,a=s===o;if(r&&!a&&!Number.isNaN(o))return{wasMutated:!0,path:i};if(e(s)||e(o))return{wasMutated:!1};const c={};for(let e in n.children)c[e]=!0;for(let e in o)c[e]=!0;const l=t.length>0;for(let r in c){const s=i?i+"."+r:r;if(l){if(t.some((e=>e instanceof RegExp?e.test(s):s===e)))continue}const c=Et(e,t,n.children[r],o[r],a,s);if(c.wasMutated)return c}return{wasMutated:!1}}function Ct(e){const t=typeof e;return null==e||"string"===t||"boolean"===t||"number"===t||Array.isArray(e)||ee(e)}function _t(e,t="",n=Ct,o,r=[],i){let s;if(!n(e))return{keyPath:t||"<root>",value:e};if("object"!=typeof e||null===e)return!1;if(i?.has(e))return!1;const a=null!=o?o(e):Object.entries(e),c=r.length>0;for(const[e,l]of a){const a=t?t+"."+e:e;if(c){if(r.some((e=>e instanceof RegExp?e.test(a):a===e)))continue}if(!n(l))return{keyPath:a,value:l};if("object"==typeof l&&(s=_t(l,a,n,o,r,i),s))return s}return i&&Tt(e)&&i.add(e),!1}function Tt(e){if(!Object.isFrozen(e))return!1;for(const t of Object.values(e))if("object"==typeof t&&null!==t&&!Tt(t))return!1;return!0}function At(e){return"boolean"==typeof e}var Ut=()=>function(e){const{thunk:t=!0,immutableCheck:n=!0,serializableCheck:o=!0,actionCreatorCheck:r=!0}=e??{};let i=new kt;if(t&&(At(t)?i.push(ft):i.push(gt(t.extraArgument))),n){let e={};At(n)||(e=n),i.unshift(function(e={}){{let t=function(e,t,o,r){return JSON.stringify(e,n(t,r),o)},n=function(e,t){let n=[],o=[];return t||(t=function(e,t){return n[0]===t?"[Circular ~]":"[Circular ~."+o.slice(0,n.indexOf(t)).join(".")+"]"}),function(r,i){if(n.length>0){var s=n.indexOf(this);~s?n.splice(s+1):n.push(this),~s?o.splice(s,1/0,r):o.push(r),~n.indexOf(i)&&(i=t.call(this,r,i))}else n.push(i);return null==e?i:e.call(this,r,i)}},{isImmutable:o=Ot,ignoredPaths:r,warnAfter:i=32}=e;const s=jt.bind(null,o,r);return({getState:e})=>{let n,o=e(),r=s(o);return a=>c=>{const l=bt(i,"ImmutableStateInvariantMiddleware");l.measureTime((()=>{if(o=e(),n=r.detectMutations(),r=s(o),n.wasMutated)throw new Error(`A state mutation was detected between dispatches, in the path '${n.path||""}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)}));const u=a(c);return l.measureTime((()=>{if(o=e(),n=r.detectMutations(),r=s(o),n.wasMutated)throw new Error(`A state mutation was detected inside a dispatch, in the path: ${n.path||""}. Take a look at the reducer(s) handling the action ${t(c)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)})),l.warnIfExceeded(),u}}}}(e))}if(o){let e={};At(o)||(e=o),i.push(function(e={}){{const{isSerializable:t=Ct,getEntries:n,ignoredActions:o=[],ignoredActionPaths:r=["meta.arg","meta.baseQueryMeta"],ignoredPaths:i=[],warnAfter:s=32,ignoreState:a=!1,ignoreActions:c=!1,disableCache:l=!1}=e,u=!l&&WeakSet?new WeakSet:void 0;return e=>l=>d=>{if(!ae(d))return l(d);const p=l(d),h=bt(s,"SerializableStateInvariantMiddleware");return c||o.length&&-1!==o.indexOf(d.type)||h.measureTime((()=>{const e=_t(d,"",t,n,r,u);if(e){const{keyPath:t,value:n}=e;console.error(`A non-serializable value was detected in an action, in the path: \`${t}\`. Value:`,n,"\nTake a look at the logic that dispatched this action: ",d,"\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)","\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)")}})),a||(h.measureTime((()=>{const o=_t(e.getState(),"",t,n,i,u);if(o){const{keyPath:e,value:t}=o;console.error(`A non-serializable value was detected in the state, in the path: \`${e}\`. Value:`,t,`\nTake a look at the reducer(s) handling this action type: ${d.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`)}})),h.warnIfExceeded()),p}}}(e))}if(r){let e={};At(r)||(e=r),i.unshift(function(e={}){const{isActionCreator:t=wt}=e;return()=>e=>n=>(t(n)&&console.warn(function(e){const t=e?`${e}`.split("/"):[],n=t[t.length-1]||"actionCreator";return`Detected an action creator with type "${e||"unknown"}" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. \`dispatch(${n}())\` instead of \`dispatch(${n})\`. This is necessary even if the action has no payload.`}(n.type)),e(n))}(e))}return i},Rt=e=>t=>{setTimeout(t,e)},Pt="undefined"!=typeof window&&window.requestAnimationFrame?window.requestAnimationFrame:Rt(10),$t=e=>function(t){const{autoBatch:n=!0}=t??{};let o=new kt(e);return n&&o.push(((e={type:"raf"})=>t=>(...n)=>{const o=t(...n);let r=!0,i=!1,s=!1;const a=new Set,c="tick"===e.type?queueMicrotask:"raf"===e.type?Pt:"callback"===e.type?e.queueNotification:Rt(e.timeout),l=()=>{s=!1,i&&(i=!1,a.forEach((e=>e())))};return Object.assign({},o,{subscribe(e){const t=o.subscribe((()=>r&&e()));return a.add(e),()=>{t(),a.delete(e)}},dispatch(e){try{return r=!e?.meta?.RTK_autoBatch,i=!r,i&&(s||(s=!0,c(l))),o.dispatch(e)}finally{r=!0}}})})("object"==typeof n?n:void 0)),o};function Mt(e){const t=Ut(),{reducer:n,middleware:o,devTools:r=!0,preloadedState:i,enhancers:s}=e||{};let a,c;if("function"==typeof n)a=n;else{if(!ee(n))throw new Error("`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers");a=ie(n)}if(o&&"function"!=typeof o)throw new Error("`middleware` field must be a callback");if("function"==typeof o){if(c=o(t),!Array.isArray(c))throw new Error("when using a middleware builder function, an array of middleware must be returned")}else c=t();if(c.some((e=>"function"!=typeof e)))throw new Error("each middleware provided to configureStore must be a function");let l=se;r&&(l=mt({trace:!0,..."object"==typeof r&&r}));const u=function(...e){return t=>(n,o)=>{const r=t(n,o);let i=()=>{throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")};const s={getState:r.getState,dispatch:(e,...t)=>i(e,...t)},a=e.map((e=>e(s)));return i=se(...a)(r.dispatch),{...r,dispatch:i}}}(...c),d=$t(u);if(s&&"function"!=typeof s)throw new Error("`enhancers` field must be a callback");let p="function"==typeof s?s(d):d();if(!Array.isArray(p))throw new Error("`enhancers` callback must return an array");if(p.some((e=>"function"!=typeof e)))throw new Error("each enhancer provided to configureStore must be a function");c.length&&!p.includes(u)&&console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");return oe(a,i,l(...p))}function Dt(e){const t={},n=[];let o;const r={addCase(e,i){if(n.length>0)throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");if(o)throw new Error("`builder.addCase` should only be called before calling `builder.addDefaultCase`");const s="string"==typeof e?e:e.type;if(!s)throw new Error("`builder.addCase` cannot be called with an empty action type");if(s in t)throw new Error(`\`builder.addCase\` cannot be called with two reducers for the same action type '${s}'`);return t[s]=i,r},addMatcher(e,t){if(o)throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");return n.push({matcher:e,reducer:t}),r},addDefaultCase(e){if(o)throw new Error("`builder.addDefaultCase` can only be called once");return o=e,r}};return e(r),[t,n,o]}function Lt(...e){return t=>e.some((e=>((e,t)=>vt(e)?e.match(t):e(t))(e,t)))}var Nt=["name","message","stack","code"],Wt=class{constructor(e,t){this.payload=e,this.meta=t}_type},zt=class{constructor(e,t){this.payload=e,this.meta=t}_type},Ft=e=>{if("object"==typeof e&&null!==e){const t={};for(const n of Nt)"string"==typeof e[n]&&(t[n]=e[n]);return t}return{message:String(e)}},qt=(()=>{function e(e,t,n){const o=yt(e+"/fulfilled",((e,t,n,o)=>({payload:e,meta:{...o||{},arg:n,requestId:t,requestStatus:"fulfilled"}}))),r=yt(e+"/pending",((e,t,n)=>({payload:void 0,meta:{...n||{},arg:t,requestId:e,requestStatus:"pending"}}))),i=yt(e+"/rejected",((e,t,o,r,i)=>({payload:r,error:(n&&n.serializeError||Ft)(e||"Rejected"),meta:{...i||{},arg:o,requestId:t,rejectedWithValue:!!r,requestStatus:"rejected",aborted:"AbortError"===e?.name,condition:"ConditionError"===e?.name}})));return Object.assign((function(e){return(s,a,c)=>{const l=n?.idGenerator?n.idGenerator(e):((e=21)=>{let t="",n=e;for(;n--;)t+="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW"[64*Math.random()|0];return t})(),u=new AbortController;let d;function p(e){d=e,u.abort()}const h=async function(){let h;try{let i=n?.condition?.(e,{getState:a,extra:c});if(null!==(f=i)&&"object"==typeof f&&"function"==typeof f.then&&(i=await i),!1===i||u.signal.aborted)throw{name:"ConditionError",message:"Aborted due to condition callback returning false."};const g=new Promise(((e,t)=>u.signal.addEventListener("abort",(()=>t({name:"AbortError",message:d||"Aborted"})))));s(r(l,e,n?.getPendingMeta?.({requestId:l,arg:e},{getState:a,extra:c}))),h=await Promise.race([g,Promise.resolve(t(e,{dispatch:s,getState:a,extra:c,requestId:l,signal:u.signal,abort:p,rejectWithValue:(e,t)=>new Wt(e,t),fulfillWithValue:(e,t)=>new zt(e,t)})).then((t=>{if(t instanceof Wt)throw t;return t instanceof zt?o(t.payload,l,e,t.meta):o(t,l,e)}))])}catch(t){h=t instanceof Wt?i(null,l,e,t.payload,t.meta):i(t,l,e)}var f;return n&&!n.dispatchConditionRejection&&i.match(h)&&h.meta.condition||s(h),h}();return Object.assign(h,{abort:p,requestId:l,arg:e,unwrap:()=>h.then(Jt)})}}),{pending:r,rejected:i,fulfilled:o,settled:Lt(i,o),typePrefix:e})}return e.withTypes=()=>e,e})();function Jt(e){if(e.meta&&e.meta.rejectedWithValue)throw e.payload;if(e.error)throw e.error;return e.payload}var Kt=Symbol.for("rtk-slice-createasyncthunk");function Vt(e,t){return`${e}/${t}`}function Ht(e,t,n,o){function r(r,...i){let s=n.call(e,r);if(void 0===s){if(!o)throw new Error("selectState returned undefined for an uninjected slice reducer");s=e.getInitialState()}return t(s,...i)}return r.unwrapped=t,r}var Bt=function({creators:e}={}){const t=e?.asyncThunk?.[Kt];return function(e){const{name:n,reducerPath:o=n}=e;if(!n)throw new Error("`name` is a required option for createSlice");"undefined"!=typeof process&&void 0===e.initialState&&console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`");const r=("function"==typeof e.reducers?e.reducers(function(){function e(e,t){return{_reducerDefinitionType:"asyncThunk",payloadCreator:e,...t}}return e.withTypes=()=>e,{reducer:e=>Object.assign({[e.name]:(...t)=>e(...t)}[e.name],{_reducerDefinitionType:"reducer"}),preparedReducer:(e,t)=>({_reducerDefinitionType:"reducerWithPrepare",prepare:e,reducer:t}),asyncThunk:e}}()):e.reducers)||{},i=Object.keys(r),s={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},a={addCase(e,t){const n="string"==typeof e?e:e.type;if(!n)throw new Error("`context.addCase` cannot be called with an empty action type");if(n in s.sliceCaseReducersByType)throw new Error("`context.addCase` cannot be called with two reducers for the same action type: "+n);return s.sliceCaseReducersByType[n]=t,a},addMatcher:(e,t)=>(s.sliceMatchers.push({matcher:e,reducer:t}),a),exposeAction:(e,t)=>(s.actionCreators[e]=t,a),exposeCaseReducer:(e,t)=>(s.sliceCaseReducersByName[e]=t,a)};function c(){if("object"==typeof e.extraReducers)throw new Error("The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");const[t={},n=[],o]="function"==typeof e.extraReducers?Dt(e.extraReducers):[e.extraReducers],r={...t,...s.sliceCaseReducersByType};return function(e,t){if("object"==typeof t)throw new Error("The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");let n,[o,r,i]=Dt(t);if(function(e){return"function"==typeof e}(e))n=()=>St(e());else{const t=St(e);n=()=>t}function s(e=n(),t){let s=[o[t.type],...r.filter((({matcher:e})=>e(t))).map((({reducer:e})=>e))];return 0===s.filter((e=>!!e)).length&&(s=[i]),s.reduce(((e,n)=>{if(n){if(fe(e)){const o=n(e,t);return void 0===o?e:o}if(ge(e))return Ze(e,(e=>n(e,t)));{const o=n(e,t);if(void 0===o){if(null===e)return e;throw new Error("A case reducer on a non-draftable value must not return undefined")}return o}}return e}),e)}return s.getInitialState=n,s}(e.initialState,(e=>{for(let t in r)e.addCase(t,r[t]);for(let t of s.sliceMatchers)e.addMatcher(t.matcher,t.reducer);for(let t of n)e.addMatcher(t.matcher,t.reducer);o&&e.addDefaultCase(o)}))}i.forEach((o=>{const i=r[o],s={reducerName:o,type:Vt(n,o),createNotation:"function"==typeof e.reducers};!function(e){return"asyncThunk"===e._reducerDefinitionType}(i)?function({type:e,reducerName:t,createNotation:n},o,r){let i,s;if("reducer"in o){if(n&&!function(e){return"reducerWithPrepare"===e._reducerDefinitionType}(o))throw new Error("Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");i=o.reducer,s=o.prepare}else i=o;r.addCase(e,i).exposeCaseReducer(t,i).exposeAction(t,s?yt(e,s):yt(e))}(s,i,a):function({type:e,reducerName:t},n,o,r){if(!r)throw new Error("Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.");const{payloadCreator:i,fulfilled:s,pending:a,rejected:c,settled:l,options:u}=n,d=r(e,i,u);o.exposeAction(t,d),s&&o.addCase(d.fulfilled,s);a&&o.addCase(d.pending,a);c&&o.addCase(d.rejected,c);l&&o.addMatcher(d.settled,l);o.exposeCaseReducer(t,{fulfilled:s||Yt,pending:a||Yt,rejected:c||Yt,settled:l||Yt})}(s,i,a,t)}));const l=e=>e,u=new WeakMap;let d;const p={name:n,reducerPath:o,reducer:(e,t)=>(d||(d=c()),d(e,t)),actions:s.actionCreators,caseReducers:s.sliceCaseReducersByName,getInitialState:()=>(d||(d=c()),d.getInitialState()),getSelectors(t=l){const n=It(u,this,{insert:()=>new WeakMap});return It(n,t,{insert:()=>{const n={};for(const[o,r]of Object.entries(e.selectors??{}))n[o]=Ht(this,r,t,this!==p);return n}})},selectSlice(e){let t=e[this.reducerPath];if(void 0===t){if(this===p)throw new Error("selectSlice returned undefined for an uninjected slice reducer");t=this.getInitialState()}return t},get selectors(){return this.getSelectors(this.selectSlice)},injectInto(e,{reducerPath:t,...n}={}){const o=t??this.reducerPath;return e.inject({reducerPath:o,reducer:this.reducer},n),{...this,reducerPath:o}}};return p}}();function Yt(){}var Xt="listenerMiddleware";yt(`${Xt}/add`),yt(`${Xt}/removeAll`),yt(`${Xt}/remove`);const Gt=e=>a((t=>{const n=Bt(e),o=Object.assign(Object.assign({},n.actions),e.asyncActions);return class extends(i(g)(t)){constructor(...e){super(...e);const t=Mt({reducer:n.reducer,middleware:e=>e({thunk:{extraArgument:this},serializableCheck:!1}),devTools:!1}),r=e=>async(...n)=>{const o=await t.dispatch(e(...n));try{Jt(o)}catch(e){this.logger.error(e.message,o.type,e.stack)}return o},i=Object.keys(o).reduce(((e,t)=>(e[t]=r(o[t]),e)),{});this.actions=i,this.subscribe=(e,n=e=>e)=>t.subscribe((()=>e(n(t.getState()))))}}}));a((e=>class extends(g(e)){validateForm(e){return this.getFormInputs(e).every((e=>{var t,n;return null===(t=e.reportValidity)||void 0===t||t.call(e),null===(n=e.checkValidity)||void 0===n?void 0:n.call(e)}))}getFormInputs(e){return e?Array.from(e.querySelectorAll("[name]")):(this.logger.debug("cannot get form inputs, no root element was received"),[])}getFormData(e){return this.getFormInputs(e).reduce(((e,t)=>Object.assign(e,{[t.getAttribute("name")]:t.value})),{})}setFormData(e,t){this.getFormInputs(e).forEach((e=>{t.hasOwnProperty(e.getAttribute("name"))&&(e.value=t[e.getAttribute("name")])}))}resetFormData(e){this.getFormInputs(e).forEach((e=>{e.value="",e.checked=!1}))}getFormFieldNames(e){return this.getFormInputs(e).map((e=>e.name))}disableFormField(e,t){var n;null===(n=this.getFormInputs(e).find((e=>e.name===t)))||void 0===n||n.setAttribute("disabled","true")}removeFormField(e,t){var n;null===(n=this.getFormInputs(e).find((e=>e.name===t)))||void 0===n||n.remove()}}));const Zt=a((e=>class extends e{get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}}));var Qt;!function(e){e.oidc="oidc",e.saml="saml"}(Qt||(Qt={}));const en=dt((e=>e.ssoAppsList.data),(e=>{var t;return null===(t=null==e?void 0:e.filter)||void 0===t?void 0:t.call(e,(e=>e.appType===Qt.saml))})),tn=dt(en,(e=>e.map((e=>({name:e.name,icon:e.logo,url:e.samlSettings.idpInitiatedUrl}))))),nn=qt("ssoApps/load",((e,{extra:{api:t}})=>t.ssoApps.load())),on=(e=>(...t)=>n=>{n.addCase(e.pending,((e,n)=>{t.forEach((({onPending:t})=>{null==t||t(e,n)}))})),n.addCase(e.fulfilled,((e,n)=>{t.forEach((({onFulfilled:t})=>{null==t||t(e,n)}))})),n.addCase(e.rejected,((e,n)=>{t.forEach((({onRejected:t})=>{null==t||t(e,n)}))}))})(nn)({onFulfilled:(e,t)=>{var n;e.ssoAppsList.data=null===(n=t.payload)||void 0===n?void 0:n.apps}},(rn=e=>e.ssoAppsList,{onFulfilled:e=>{rn(e).loading=!1},onPending:e=>{rn(e).loading=!0,rn(e).error=null},onRejected:(e,t)=>{rn(e).loading=!1,rn(e).error=t.error}}));var rn;const sn={action:nn,reducer:on},an={ssoAppsList:{data:[],loading:!1,error:null}};class cn extends Error{}function ln(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 n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(e){return atob(t)}}function un(e,t){if("string"!=typeof e)throw new cn("Invalid token specified: must be a string");t||(t={});const n=!0===t.header?0:1,o=e.split(".")[n];if("string"!=typeof o)throw new cn(`Invalid token specified: missing part #${n+1}`);let r;try{r=ln(o)}catch(e){throw new cn(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(r)}catch(e){throw new cn(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}cn.prototype.name="InvalidTokenError";var dn={accessKey:{exchange:"/v1/auth/accesskey/exchange"},otp:{verify:"/v1/auth/otp/verify",signIn:"/v1/auth/otp/signin",signUp:"/v1/auth/otp/signup",update:{email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},signUpOrIn:"/v1/auth/otp/signup-in"},magicLink:{verify:"/v1/auth/magiclink/verify",signIn:"/v1/auth/magiclink/signin",signUp:"/v1/auth/magiclink/signup",update:{email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/phone"},signUpOrIn:"/v1/auth/magiclink/signup-in"},enchantedLink:{verify:"/v1/auth/enchantedlink/verify",signIn:"/v1/auth/enchantedlink/signin",signUp:"/v1/auth/enchantedlink/signup",session:"/v1/auth/enchantedlink/pending-session",update:{email:"/v1/auth/enchantedlink/update/email"},signUpOrIn:"/v1/auth/enchantedlink/signup-in"},oauth:{start:"/v1/auth/oauth/authorize",exchange:"/v1/auth/oauth/exchange",startNative:"v1/auth/oauth/native/start",finishNative:"v1/auth/oauth/native/finish",oneTap:{getOneTapClientId:"/v1/auth/onetap/clientid/{provider}",exchangeOneTapIDToken:"/v1/auth/onetap/idtoken/exchange",verifyOneTapIDToken:"/v1/auth/onetap/idtoken/verify"}},saml:{start:"/v1/auth/saml/authorize",exchange:"/v1/auth/saml/exchange"},totp:{verify:"/v1/auth/totp/verify",signUp:"/v1/auth/totp/signup",update:"/v1/auth/totp/update"},notp:{signIn:"/v1/auth/notp/whatsapp/signin",signUp:"/v1/auth/notp/whatsapp/signup",signUpOrIn:"/v1/auth/notp/whatsapp/signup-in",session:"/v1/auth/notp/pending-session"},webauthn:{signUp:{start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},signIn:{start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},signUpOrIn:{start:"/v1/auth/webauthn/signup-in/start"},update:{start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"}},password:{signUp:"/v1/auth/password/signup",signIn:"/v1/auth/password/signin",sendReset:"/v1/auth/password/reset",update:"/v1/auth/password/update",replace:"/v1/auth/password/replace",policy:"/v1/auth/password/policy"},refresh:"/v1/auth/refresh",selectTenant:"/v1/auth/tenant/select",logout:"/v1/auth/logout",logoutAll:"/v1/auth/logoutall",me:"/v1/auth/me",myTenants:"/v1/auth/me/tenants",history:"/v1/auth/me/history",flow:{start:"/v1/flow/start",next:"/v1/flow/next"}};const pn="<region>",hn=`https://api.${pn}descope.com`,fn=6e5,gn="dct",mn=()=>{const e={};return{headers(t){const n="function"==typeof t.entries?Object.fromEntries(t.entries()):t;return e.Headers=JSON.stringify(n),this},body(t){return e.Body=t,this},url(t){return e.Url=t.toString(),this},method(t){return e.Method=t,this},title(t){return e.Title=t,this},status(t){return e.Status=t,this},build:()=>Object.keys(e).flatMap((t=>e[t]?[`${"Title"!==t?`${t}: `:""}${e[t]}`]:[])).join("\n")}};let vn;const yn=()=>{if(vn)return vn;const e=new Date,t=`${e.getUTCFullYear().toString()}-${(e.getUTCMonth()+1).toString().padStart(2,"0")}-${e.getUTCDate().toString().padStart(2,"0")}-${e.getUTCHours().toString().padStart(2,"0")}:${e.getUTCMinutes().toString().padStart(2,"0")}:${e.getUTCSeconds().toString().padStart(2,"0")}:${e.getUTCMilliseconds().toString()}`,n=Math.floor(1e3+9e3*Math.random());return vn=`${t}-${n}`,vn};var wn,bn;(bn=wn||(wn={})).get="GET",bn.delete="DELETE",bn.post="POST",bn.put="PUT",bn.patch="PATCH";const kn=({path:e,baseUrl:t,queryParams:n,projectId:o})=>{const r=o.slice(1,-27);t=t.replace(pn,r?r+".":"");let i=e?`${t.replace(/\/$/,"")}/${null==e?void 0:e.replace(/^\//,"")}`:t;if(n){const e=Object.keys(n);e.forEach(((t,o)=>{i=`${i}${0===o?"?":""}${t}=${encodeURIComponent(n[t])}${o===e.length-1?"":"&"}`}))}return i},Sn=(...e)=>new Headers(e.reduce(((e,t)=>{const n=(e=>Array.isArray(e)?e:e instanceof Headers?Array.from(e.entries()):e?Object.entries(e):[])(t);return n.reduce(((t,[n,o])=>(e[n]=o,e)),e),e}),{})),In={"Content-Type":"application/json"},On=(e,t="")=>{let n=e;return t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},jn=e=>{const t={"x-descope-sdk-session-id":yn(),"x-descope-sdk-name":"core-js","x-descope-sdk-version":"2.40.0"};return e&&(t["x-descope-refresh-cookie-name"]=e),t},xn=e=>{try{e=JSON.parse(e)}catch(e){return!1}return"object"==typeof e&&null!==e},En=({baseUrl:e,projectId:t,baseConfig:n,refreshCookieName:o,logger:r,hooks:i,cookiePolicy:s,fetch:a})=>{const c=((e,t)=>{const n=(e=>async(...t)=>{const n=await e(...t),o=await n.text();return n.text=()=>Promise.resolve(o),n.json=()=>Promise.resolve(JSON.parse(o)),n.clone=()=>n,n})(t||fetch);return n||null==e||e.warn("Fetch is not defined, you will not be able to send http requests, if you are running in a test, make sure fetch is defined globally"),e?async(...t)=>{if(!n)throw Error("Cannot send http request, fetch is not defined, if you are running in a test, make sure fetch is defined globally");e.log((e=>mn().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const o=await n(...t);return e[o.ok?"log":"error"](await(async e=>{const t=await e.text();return mn().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(o)),o}:n})(r,a),l=async r=>{var a;const l=(null==i?void 0:i.beforeRequest)?i.beforeRequest(r):r,{path:u,body:d,headers:p,queryParams:h,method:f,token:g}=l,m=(e=>void 0===e?void 0:JSON.stringify(e))(d),v={headers:Sn(On(t,g),jn(o),(null==n?void 0:n.baseHeaders)||{},xn(m)?In:{},p),method:f,body:m};null!==s&&(v.credentials=s||"include");const y=await c(kn({path:u,baseUrl:e,queryParams:h,projectId:t}),v);if((null==i?void 0:i.afterRequest)&&await i.afterRequest(r,null==y?void 0:y.clone()),null==i?void 0:i.transformResponse){const e=await y.json(),t=((null===(a=y.headers)||void 0===a?void 0:a.get("set-cookie"))||"").split(";").reduce(((e,t)=>{const[n,o]=t.split("=");return Object.assign(Object.assign({},e),{[n.trim()]:o})}),{}),n=Object.assign(Object.assign({},y),{json:()=>Promise.resolve(e),cookies:t});return n.clone=()=>n,i.transformResponse(n)}return y};return{get:(e,{headers:t,queryParams:n,token:o}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:wn.get,token:o}),post:(e,t,{headers:n,queryParams:o,token:r}={})=>l({path:e,headers:n,queryParams:o,body:t,method:wn.post,token:r}),patch:(e,t,{headers:n,queryParams:o,token:r}={})=>l({path:e,headers:n,queryParams:o,body:t,method:wn.patch,token:r}),put:(e,t,{headers:n,queryParams:o,token:r}={})=>l({path:e,headers:n,queryParams:o,body:t,method:wn.put,token:r}),delete:(e,{headers:t,queryParams:n,token:o}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:wn.delete,token:o}),hooks:i,buildUrl:(n,o)=>kn({projectId:t,baseUrl:e,path:n,queryParams:o})}};var Cn=429;function _n(e,t,n){var o;let r=Tn(e);if(t){if(!(null==r?void 0:r.tenants)&&(null==r?void 0:r[gn])===t)return(null==r?void 0:r[n])||[];r=null===(o=null==r?void 0:r.tenants)||void 0===o?void 0:o[t]}const i=null==r?void 0:r[n];return Array.isArray(i)?i:[]}function Tn(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return un(e)}function An(e){const{exp:t}=Tn(e);return(new Date).getTime()/1e3>t}function Un(e){let t=Tn(e);const n=Object.keys(null==t?void 0:t.tenants);return Array.isArray(n)?n:[]}function Rn(e,t){return _n(e,t,"permissions")}function Pn(e,t){return _n(e,t,"roles")}const $n=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function Mn(e,t){var n;const o=await e,r={code:o.status,ok:o.ok,response:o},i=await o.clone().json();return o.ok?r.data=i:(r.error=i,o.status===Cn&&Object.assign(r.error,{retryAfter:Number.parseInt(null===(n=o.headers)||void 0===n?void 0:n.get("retry-after"))||0})),r}function Dn(e){var t;return(null===(t=Tn(e))||void 0===t?void 0:t[gn])||""}const Ln=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),Nn=(e,t)=>(n=t)=>t=>{const o=e.filter((e=>e(t)));return!(o.length<e.length)&&(n?n.replace("{val}",t):o.join(" OR "))},Wn=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),zn=e=>t=>e.test(t),Fn=zn(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),qn=zn(/^\+[1-9]{1}[0-9]{3,14}$/),Jn=Ln(Fn,'"{val}" is not a valid email'),Kn=Ln(qn,'"{val}" is not a valid phone number'),Vn=Ln((e=>e.length>=1),"Minimum length is 1");const Hn=Ln((e=>"string"==typeof e),"Input is not a string"),Bn=Ln((e=>Array.isArray(e)),"Input is not an array"),Yn=Ln((e=>"boolean"==typeof e),"Input is not a boolean"),Xn=Ln((e=>void 0===e),"Input is defined"),Gn=Nn([Hn(),Xn()],"Input is not a string or undefined"),Zn=Nn([Bn(),Yn()],"Input is not an array or boolean"),Qn=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>Wn(...e).validate(n[t]))),t(...n)),eo=e=>[Hn(`"${e}" must be a string`)],to=e=>[Gn(`"${e}" must be string or undefined`)],no=e=>[Hn(`"${e}" must be a string`),Vn(`"${e}" must not be empty`)],oo=e=>[Hn(`"${e}" must be a string`),Jn()],ro=e=>[Hn(`"${e}" must be a string`),Kn()],io=Qn(no("accessKey")),so=e=>({exchange:io(((t,n)=>Mn(e.post(dn.accessKey.exchange,{loginOptions:n},{token:t}))))}),ao=(e,t,n)=>(t.forEach((t=>{const o=t.split(".");let r=o.shift(),i=e;for(;o.length>0;){if(i=i[r],!r||!i)throw Error(`Invalid path "${t}", "${r}" is missing or has no value`);r=o.shift()}if("function"!=typeof i[r])throw Error(`"${t}" is not a function`);const s=i[r];i[r]=n(s)})),e),co=({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||fn,fn)});var lo,uo;!function(e){e.sms="sms",e.voice="voice",e.whatsapp="whatsapp"}(lo||(lo={})),function(e){e.email="email"}(uo||(uo={}));const po=Object.assign(Object.assign({},lo),uo);var ho;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(ho||(ho={}));const fo=no("loginId"),go=Qn(no("token")),mo=Qn(fo),vo=Qn(no("pendingRef")),yo=Qn(fo,oo("email")),wo=e=>({verify:go((t=>Mn(e.post(dn.enchantedLink.verify,{token:t})))),signIn:mo(((t,n,o,r)=>Mn(e.post($n(dn.enchantedLink.signIn,po.email),{loginId:t,URI:n,loginOptions:o},{token:r})))),signUpOrIn:mo(((t,n,o)=>Mn(e.post($n(dn.enchantedLink.signUpOrIn,po.email),{loginId:t,URI:n,loginOptions:o})))),signUp:mo(((t,n,o,r)=>Mn(e.post($n(dn.enchantedLink.signUp,po.email),{loginId:t,URI:n,user:o,loginOptions:r})))),waitForSession:vo(((t,n)=>new Promise((o=>{const{pollingIntervalMs:r,timeoutMs:i}=co(n);let s;const a=setInterval((async()=>{const n=await e.post(dn.enchantedLink.session,{pendingRef:t});n.ok&&(clearInterval(a),s&&clearTimeout(s),o(Mn(Promise.resolve(n))))}),r);s=setTimeout((()=>{o({error:{errorDescription:`Session polling timeout exceeded: ${i}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),i)})))),update:{email:yo(((t,n,o,r,i)=>Mn(e.post(dn.enchantedLink.update.email,Object.assign({loginId:t,email:n,URI:o},i),{token:r}))))}}),bo=Qn(no("flowId")),ko=Qn(no("executionId"),no("stepId"),no("interactionId")),So=e=>({start:bo(((t,n,o,r,i,s,a)=>Mn(e.post(dn.flow.start,{flowId:t,options:n,conditionInteractionId:o,interactionId:r,componentsVersion:i,flowVersions:s,input:a})))),next:ko(((t,n,o,r,i,s)=>Mn(e.post(dn.flow.next,{executionId:t,stepId:n,interactionId:o,version:r,componentsVersion:i,input:s}))))}),Io=no("loginId"),Oo=Qn(no("token")),jo=Qn(Io),xo=Qn(Io,ro("phone")),Eo=Qn(Io,oo("email")),Co=Object.keys(po).filter((e=>e!==lo.voice)),_o=e=>({verify:Oo((t=>Mn(e.post(dn.magicLink.verify,{token:t})))),signIn:Co.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:jo(((t,o,r,i)=>Mn(e.post($n(dn.magicLink.signIn,n),{loginId:t,URI:o,loginOptions:r},{token:i}))))})),{}),signUp:Co.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:jo(((t,o,r,i)=>Mn(e.post($n(dn.magicLink.signUp,n),{loginId:t,URI:o,user:r,loginOptions:i}))))})),{}),signUpOrIn:Co.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:jo(((t,o,r)=>Mn(e.post($n(dn.magicLink.signUpOrIn,n),{loginId:t,URI:o,loginOptions:r}))))})),{}),update:{email:Eo(((t,n,o,r,i)=>Mn(e.post(dn.magicLink.update.email,Object.assign({loginId:t,email:n,URI:o},i),{token:r})))),phone:Object.keys(lo).filter((e=>e!==lo.voice)).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:xo(((t,o,r,i,s)=>Mn(e.post($n(dn.magicLink.update.phone,n),Object.assign({loginId:t,phone:o,URI:r},s),{token:i}))))})),{})}});var To;!function(e){e.facebook="facebook",e.github="github",e.google="google",e.microsoft="microsoft",e.gitlab="gitlab",e.apple="apple",e.discord="discord",e.linkedin="linkedin",e.slack="slack"}(To||(To={}));const Ao=Qn(no("code")),Uo=e=>({start:Object.assign(((t,n,o,r)=>Mn(e.post(dn.oauth.start,o||{},{queryParams:Object.assign({provider:t},n&&{redirectURL:n}),token:r}))),Object.keys(To).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:(t,o,r)=>Mn(e.post(dn.oauth.start,o||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:r}))})),{})),exchange:Ao((t=>Mn(e.post(dn.oauth.exchange,{code:t})))),startNative:(t,n,o)=>Mn(e.post(dn.oauth.startNative,{provider:t,loginOptions:n,implicit:o})),finishNative:(t,n,o,r,i)=>Mn(e.post(dn.oauth.finishNative,{provider:t,stateId:n,user:o,code:r,idToken:i})),getOneTapClientId:t=>Mn(e.get(dn.oauth.oneTap.getOneTapClientId.replace("{provider}",t))),verifyOneTapIDToken:(t,n,o,r)=>Mn(e.post(dn.oauth.oneTap.verifyOneTapIDToken,{provider:t,idToken:n,nonce:o,loginOptions:r})),exchangeOneTapIDToken:(t,n,o,r)=>Mn(e.post(dn.oauth.oneTap.exchangeOneTapIDToken,{provider:t,idToken:n,nonce:o,loginOptions:r}))}),Ro=no("loginId"),Po=Qn(Ro,no("code")),$o=Qn(Ro),Mo=Qn(Ro,ro("phone")),Do=Qn(Ro,oo("email")),Lo=e=>({verify:Object.keys(po).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Po(((t,o)=>Mn(e.post($n(dn.otp.verify,n),{code:o,loginId:t}))))})),{}),signIn:Object.keys(po).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:$o(((t,o,r)=>Mn(e.post($n(dn.otp.signIn,n),{loginId:t,loginOptions:o},{token:r}))))})),{}),signUp:Object.keys(po).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:$o(((t,o,r)=>Mn(e.post($n(dn.otp.signUp,n),{loginId:t,user:o,loginOptions:r}))))})),{}),signUpOrIn:Object.keys(po).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:$o(((t,o)=>Mn(e.post($n(dn.otp.signUpOrIn,n),{loginId:t,loginOptions:o}))))})),{}),update:{email:Do(((t,n,o,r)=>Mn(e.post(dn.otp.update.email,Object.assign({loginId:t,email:n},r),{token:o})))),phone:Object.keys(lo).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Mo(((t,o,r,i)=>Mn(e.post($n(dn.otp.update.phone,n),Object.assign({loginId:t,phone:o},i),{token:r}))))})),{})}}),No=Qn(no("tenant")),Wo=Qn(no("code")),zo=e=>({start:No(((t,n,o,r,i)=>Mn(e.post(dn.saml.start,o||{},Object.assign({queryParams:Object.assign(Object.assign({tenant:t},n&&{redirectURL:n}),i&&{ssoId:i})},r&&{token:r}))))),exchange:Wo((t=>Mn(e.post(dn.saml.exchange,{code:t}))))}),Fo=no("loginId"),qo=Qn(Fo,no("code")),Jo=Qn(Fo),Ko=Qn(Fo),Vo=e=>({signUp:Jo(((t,n)=>Mn(e.post(dn.totp.signUp,{loginId:t,user:n})))),verify:qo(((t,n,o,r)=>Mn(e.post(dn.totp.verify,{loginId:t,code:n,loginOptions:o},{token:r})))),update:Ko(((t,n)=>Mn(e.post(dn.totp.update,{loginId:t},{token:n}))))}),Ho=no("loginId"),Bo=no("newPassword"),Yo=Qn(Ho,no("password")),Xo=Qn(Ho),Go=Qn(Ho,Bo),Zo=Qn(Ho,no("oldPassword"),Bo),Qo=e=>({signUp:Yo(((t,n,o,r)=>Mn(e.post(dn.password.signUp,{loginId:t,password:n,user:o,loginOptions:r})))),signIn:Yo(((t,n,o)=>Mn(e.post(dn.password.signIn,{loginId:t,password:n,loginOptions:o})))),sendReset:Xo(((t,n,o)=>Mn(e.post(dn.password.sendReset,{loginId:t,redirectUrl:n,templateOptions:o})))),update:Go(((t,n,o)=>Mn(e.post(dn.password.update,{loginId:t,newPassword:n},{token:o})))),replace:Zo(((t,n,o)=>Mn(e.post(dn.password.replace,{loginId:t,oldPassword:n,newPassword:o})))),policy:()=>Mn(e.get(dn.password.policy))}),er=eo("loginId"),tr=no("loginId"),nr=no("origin"),or=Qn(tr,nr,no("name")),rr=Qn(tr,nr),ir=Qn(er,nr),sr=Qn(tr,nr,to("token")),ar=Qn(no("transactionId"),no("response")),cr=e=>({signUp:{start:or(((t,n,o,r)=>Mn(e.post(dn.webauthn.signUp.start,{user:{loginId:t,name:o},origin:n,passkeyOptions:r})))),finish:ar(((t,n)=>Mn(e.post(dn.webauthn.signUp.finish,{transactionId:t,response:n}))))},signIn:{start:ir(((t,n,o,r,i)=>Mn(e.post(dn.webauthn.signIn.start,{loginId:t,origin:n,loginOptions:o,passkeyOptions:i},{token:r})))),finish:ar(((t,n)=>Mn(e.post(dn.webauthn.signIn.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:rr(((t,n,o)=>Mn(e.post(dn.webauthn.signUpOrIn.start,{loginId:t,origin:n,passkeyOptions:o}))))},update:{start:sr(((t,n,o,r)=>Mn(e.post(dn.webauthn.update.start,{loginId:t,origin:n,passkeyOptions:r},{token:o})))),finish:ar(((t,n)=>Mn(e.post(dn.webauthn.update.finish,{transactionId:t,response:n}))))}}),lr=eo("loginId"),ur=Qn(lr),dr=Qn(no("pendingRef")),pr=e=>({signUpOrIn:ur(((t,n)=>Mn(e.post(dn.notp.signUpOrIn,{loginId:t,loginOptions:n})))),signUp:ur(((t,n,o)=>Mn(e.post(dn.notp.signUp,{loginId:t,user:n,loginOptions:o})))),signIn:ur(((t,n,o)=>Mn(e.post(dn.notp.signIn,{loginId:t,loginOptions:n},{token:o})))),waitForSession:dr(((t,n)=>new Promise((o=>{const{pollingIntervalMs:r,timeoutMs:i}=co(n);let s;const a=setInterval((async()=>{const n=await e.post(dn.notp.session,{pendingRef:t});n.ok&&(clearInterval(a),s&&clearTimeout(s),o(Mn(Promise.resolve(n))))}),r);s=setTimeout((()=>{o({error:{errorDescription:`Session polling timeout exceeded: ${i}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),i)}))))}),hr=Qn(no("token")),fr=Qn(to("token"));var gr,mr=Qn([(gr=no("projectId"),Ln(((e,t)=>n=>Wn(...t).validate(((e,t)=>{const n=(Array.isArray(t)?t.join("."):String(t)).replace(/\[\\?("|')?(\w|d)+\\?("|')?\]/g,((e,t,n)=>"."+n)).split("."),o=n.length;let r=0,i=e===Object(e)?e:void 0;for(;null!=i&&r<o;)i=i[n[r++]];return r&&r===o&&void 0!==i?i:void 0})(n,e)))("projectId",gr))())])((e=>t=>{var n;return e(Object.assign(Object.assign({},t),{hooks:{beforeRequest:e=>{var n;const o=[].concat((null===(n=t.hooks)||void 0===n?void 0:n.beforeRequest)||[]);return null==o?void 0:o.reduce(((e,t)=>t(e)),e)},afterRequest:async(e,n)=>{var o;const r=[].concat((null===(o=t.hooks)||void 0===o?void 0:o.afterRequest)||[]);0!=r.length&&(await Promise.allSettled(null==r?void 0:r.map((t=>t(e,null==n?void 0:n.clone()))))).forEach((e=>{var n;return"rejected"===e.status&&(null===(n=t.logger)||void 0===n?void 0:n.error(e.reason))}))},transformResponse:null===(n=t.hooks)||void 0===n?void 0:n.transformResponse}}))})((({projectId:e,logger:t,baseUrl:n,hooks:o,cookiePolicy:r,baseHeaders:i={},refreshCookieName:s,fetch:a})=>{return c=En({baseUrl:n||hn,projectId:e,logger:t,hooks:o,cookiePolicy:r,baseConfig:{baseHeaders:i},refreshCookieName:s,fetch:a}),{accessKey:so(c),otp:Lo(c),magicLink:_o(c),enchantedLink:wo(c),oauth:Uo(c),saml:zo(c),totp:Vo(c),notp:pr(c),webauthn:cr(c),password:Qo(c),flow:So(c),refresh:fr(((e,t)=>Mn(c.post(dn.refresh,{},{token:e,queryParams:t})))),selectTenant:Qn([Hn("tenantId")],[Gn('"token" must be string or undefined')])(((e,t)=>Mn(c.post(dn.selectTenant,{tenant:e},{token:t})))),logout:fr((e=>Mn(c.post(dn.logout,{},{token:e})))),logoutAll:fr((e=>Mn(c.post(dn.logoutAll,{},{token:e})))),me:fr((e=>Mn(c.get(dn.me,{token:e})))),myTenants:Qn([Zn('"tenants" must a string array or a boolean')],[Gn('"token" must be string or undefined')])(((e,t)=>{const n={};return"boolean"==typeof e?n.dct=e:n.ids=e,Mn(c.post(dn.myTenants,n,{token:t}))})),history:fr((e=>Mn(c.get(dn.history,{token:e})))),isJwtExpired:hr(An),getTenants:hr(Un),getJwtPermissions:hr(Rn),getJwtRoles:hr(Pn),getCurrentTenant:hr(Dn),httpClient:c};var c}))),vr=Object.assign(mr,{DeliveryMethods:po});
|
|
6
6
|
/*! js-cookie v3.0.5 | MIT */
|
|
7
|
-
function ws(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)e[r]=n[r]}return e}var _s=function e(t,n){function r(e,r,s){if("undefined"!=typeof document){"number"==typeof(s=ws({},n,s)).expires&&(s.expires=new Date(Date.now()+864e5*s.expires)),s.expires&&(s.expires=s.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var o in s)s[o]&&(i+="; "+o,!0!==s[o]&&(i+="="+s[o].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+i}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],r={},s=0;s<n.length;s++){var i=n[s].split("="),o=i.slice(1).join("=");try{var a=decodeURIComponent(i[0]);if(r[a]=t.read(o,a),e===a)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",ws({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,ws({},this.attributes,t))},withConverter:function(t){return e(ws({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});var ys={default:"endpoint"},vs="Blocked by CSP",bs="The endpoint parameter is not a valid URL",Ss="Failed to load the JS script of the agent",ks="9319";function Is(e,t){var n,r,s,i,o,a=[],c=(n=function(e){var t=function(e,t,n){if(n||2===arguments.length)for(var r,s=0,i=t.length;s<i;s++)!r&&s in t||(r||(r=Array.prototype.slice.call(t,0,s)),r[s]=t[s]);return e.concat(r||Array.prototype.slice.call(t))}([],e,!0);return{current:function(){return t[0]},postpone:function(){var e=t.shift();void 0!==e&&t.push(e)},exclude:function(){t.shift()}}}(e),i=0,r=function(){return Math.random()*Math.min(3e3,100*Math.pow(2,i++))},s=new Set,[n.current(),function(e,t){var i,o=t instanceof Error?t.message:"";if(o===vs||o===bs)n.exclude(),i=0;else if(o===ks)n.exclude();else if(o===Ss){var a=Date.now()-e.getTime()<50,c=n.current();c&&a&&!s.has(c)&&(s.add(c),i=0),n.postpone()}else n.postpone();var l=n.current();return void 0===l?void 0:[l,null!=i?i:e.getTime()+r()-Date.now()]}]),l=c[0],d=c[1];if(void 0===l)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var u=function(e){var n=new Date,r=function(t){return a.push({url:e,startedAt:n,finishedAt:new Date,error:t})},s=t(e);return s.then((function(){return r()}),r),s.catch((function(e){if(null!=o||(o=e),a.length>=5)throw o;var t=d(n,e);if(!t)throw o;var r,s=t[0],i=t[1];return(r=i,new Promise((function(e){return setTimeout(e,r)}))).then((function(){return u(s)}))}))};return u(l).then((function(e){return[e,a]}))}var xs="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js",Es=xs;function Os(n){var r;n.scriptUrlPattern;var s=n.token,i=n.apiKey,o=void 0===i?s:i,a=t(n,["scriptUrlPattern","token","apiKey"]),c=null!==(r=function(e,t){return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,t)?e[t]:void 0}(n,"scriptUrlPattern"))&&void 0!==r?r:xs,l=function(){var e=[],t=function(){e.push({time:new Date,state:document.visibilityState})},n=function(e,t,n,r){return e.addEventListener(t,n,r),function(){return e.removeEventListener(t,n,r)}}(document,"visibilitychange",t);return t(),[e,n]}(),d=l[0],u=l[1];return Promise.resolve().then((function(){if(!o||"string"!=typeof o)throw new Error("API key required");var e=function(e,t){return(Array.isArray(e)?e:[e]).map((function(e){return function(e,t){var n=encodeURIComponent;return e.replace(/<[^<>]+>/g,(function(e){return"<version>"===e?"3":"<apiKey>"===e?n(t):"<loaderVersion>"===e?n("3.11.6"):e}))}(String(e),t)}))}(c,o);return Is(e,Ts)})).catch((function(e){throw u(),function(e){return e instanceof Error&&e.message===ks?new Error(Ss):e}(e)})).then((function(t){var n=t[0],r=t[1];return u(),n.load(e(e({},a),{ldi:{attempts:r,visibilityStates:d}}))}))}function Ts(e){return function(e,t,n){var r,s=document,i="securitypolicyviolation",o=function(t){var n=new URL(e,location.href),s=t.blockedURI;s!==n.href&&s!==n.protocol.slice(0,-1)&&s!==n.origin||(r=t,a())};s.addEventListener(i,o);var a=function(){return s.removeEventListener(i,o)};return Promise.resolve().then(t).then((function(e){return a(),e}),(function(e){return new Promise((function(e){var t=new MessageChannel;t.port1.onmessage=function(){return e()},t.port2.postMessage(null)})).then((function(){if(a(),r)return n(r);throw e}))}))}(e,(function(){return function(e){return new Promise((function(t,n){if(function(e){if(URL.prototype)try{return new URL(e,location.href),!1}catch(e){if(e instanceof Error&&"TypeError"===e.name)return!0;throw e}}(e))throw new Error(bs);var r=document.createElement("script"),s=function(){var e;return null===(e=r.parentNode)||void 0===e?void 0:e.removeChild(r)},i=document.head||document.getElementsByTagName("head")[0];r.onload=function(){s(),t()},r.onerror=function(){s(),n(new Error(Ss))},r.async=!0,r.src=e,i.appendChild(r)}))}(e)}),(function(){throw new Error(vs)})).then(Cs)}function Cs(){var e=window,t="__fpjs_p_l_b",n=e[t];if(function(e,t){var n,r=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==r?void 0:r.configurable)?delete e[t]:r&&!r.writable||(e[t]=void 0)}(e,t),"function"!=typeof(null==n?void 0:n.load))throw new Error(ks);return n}const js=e=>{try{return dn(e).exp}catch(e){return null}},Rs=e=>{const{refresh_expire_in:t,refresh_token:n}=e;return t?Math.floor(Date.now()/1e3)+t:js(n)},Ps=e=>{const{expires_in:t,expires_at:n,access_token:r}=e;return n||(t?Math.floor(Date.now()/1e3)+t:r?js(r):void 0)},Us=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,r)=>{var s;return n[r]=[].concat((null===(s=e.hooks)||void 0===s?void 0:s[r])||[]).concat((null==t?void 0:t[r])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e},As=async e=>{if(!(null==e?void 0:e.ok))return{};const n=await(null==e?void 0:e.clone().json());return(e=>{const{access_token:n,id_token:r,refresh_token:s,refresh_expire_in:i}=e,o=t(e,["access_token","id_token","refresh_token","refresh_expire_in"]);return Object.assign({sessionJwt:e.sessionJwt||n,idToken:r,refreshJwt:e.refreshJwt||s,sessionExpiration:e.sessionExpiration||Ps(e),cookieExpiration:e.cookieExpiration||Rs(e)},o)})((null==n?void 0:n.authInfo)||n||{})},Ms=async e=>{const t=await As(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)},$s="undefined"!=typeof localStorage,Ns=(e,t)=>$s&&(null===localStorage||void 0===localStorage?void 0:localStorage.setItem(e,t)),qs=e=>$s&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(e)),Ds=e=>$s&&(null===localStorage||void 0===localStorage?void 0:localStorage.removeItem(e)),Ls=(...e)=>{console.debug(...e)},Ws="3.2.0",Fs="undefined"!=typeof window,zs=Math.pow(2,31)-1,Hs=`https://descopecdn.com/npm/oidc-client-ts@${Ws}/dist/browser/oidc-client-ts.min.js`,Js=`https://cdn.jsdelivr.net/npm/oidc-client-ts@${Ws}/dist/browser/oidc-client-ts.min.js`,Ks="DS",Bs="DSR",Vs="DSI";function Gs(e=""){return qs(`${e}${Bs}`)||""}function Ys(e=""){return _s.get(Ks)||qs(`${e}${Ks}`)||""}function Xs(e=""){return qs(`${e}${Vs}`)||""}function Qs(e=""){Ds(`${e}${Bs}`),Ds(`${e}${Ks}`),Ds(`${e}${Vs}`),_s.remove(Ks)}const Zs=Fs&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://api.descope.com",ei="vsid",ti="vrid",ni=(e=!1)=>{const t=localStorage.getItem("fp");if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},ri=async(e,t=Zs)=>{try{if(ni())return;const n=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),r=new URL(t);r.pathname="/fXj8gt3x8VulJBna/x96Emn69oZwcd7I6";const s=new URL(t);s.pathname="/fXj8gt3x8VulJBna/w78aRZnnDZ3Aqw0I";const i=s.toString()+"?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>",o=Os({apiKey:e,endpoint:[r.toString(),ys],scriptUrlPattern:[i,Es]}),a=await o,{requestId:c}=await a.get({linkedId:n}),l=((e,t)=>({[ei]:e,[ti]:t}))(n,c);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};localStorage.setItem("fp",JSON.stringify(t))})(l)}catch(e){console.warn("Could not load fingerprint",e)}},si=e=>{const t=ni(!0);return t&&e.body&&(e.body.fpData=t),e},ii="dls_last_user_login_id",oi="dls_last_user_display_name",ai=()=>qs(ii),ci=()=>qs(oi),li=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,r={}]=t,s=ai(),i=ci();return s&&(null!==(n=r.lastAuth)&&void 0!==n||(r.lastAuth={}),r.lastAuth.loginId=s,r.lastAuth.name=i),await e(...t)};function di(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}async function ui(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=wi(n.publicKey.challenge),n.publicKey.user.id=wi(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=wi(e.id)})),n}(e);return n=await navigator.credentials.create(t),JSON.stringify({id:n.id,rawId:_i(n.rawId),type:n.type,response:{attestationObject:_i(n.response.attestationObject),clientDataJSON:_i(n.response.clientDataJSON)}});var n}async function hi(e){const t=fi(e);return mi(await navigator.credentials.get(t))}async function pi(e,t){const n=fi(e);return n.signal=t.signal,n.mediation="conditional",mi(await navigator.credentials.get(n))}async function gi(e=!1){if(!Fs)return Promise.resolve(!1);const t=!!(window.PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return t&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():t}function fi(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=wi(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=wi(e.id)})),n}function mi(e){return JSON.stringify({id:e.id,rawId:_i(e.rawId),type:e.type,response:{authenticatorData:_i(e.response.authenticatorData),clientDataJSON:_i(e.response.clientDataJSON),signature:_i(e.response.signature),userHandle:e.response.userHandle?_i(e.response.userHandle):void 0}})}function wi(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function _i(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var yi,vi=(yi=e=>({async signUp(t,n,r){const s=await e.webauthn.signUp.start(t,window.location.origin,n,r);if(!s.ok)return s;const i=await ui(s.data.options);return await e.webauthn.signUp.finish(s.data.transactionId,i)},async signIn(t,n){const r=await e.webauthn.signIn.start(t,window.location.origin,void 0,void 0,n);if(!r.ok)return r;const s=await hi(r.data.options);return await e.webauthn.signIn.finish(r.data.transactionId,s)},async signUpOrIn(t,n){var r;const s=await e.webauthn.signUpOrIn.start(t,window.location.origin,n);if(!s.ok)return s;if(null===(r=s.data)||void 0===r?void 0:r.create){const t=await ui(s.data.options);return await e.webauthn.signUp.finish(s.data.transactionId,t)}{const t=await hi(s.data.options);return await e.webauthn.signIn.finish(s.data.transactionId,t)}},async update(t,n,r){const s=await e.webauthn.update.start(t,window.location.origin,n,r);if(!s.ok)return s;const i=await ui(s.data.options);return await e.webauthn.update.finish(s.data.transactionId,i)},helpers:{create:ui,get:hi,isSupported:gi,conditional:pi}}),(...e)=>{const t=yi(...e);return Object.assign(t.signUp,e[0].webauthn.signUp),Object.assign(t.signIn,e[0].webauthn.signIn),Object.assign(t.signUpOrIn,e[0].webauthn.signUpOrIn),Object.assign(t.update,e[0].webauthn.update),t});const bi="/fedcm/config";async function Si(e,t){var n,r,s;try{const s=await async function(e,t="google",n,r,s){const i=(()=>{if(window.crypto&&window.crypto.getRandomValues){const e=new Uint8Array(16);return window.crypto.getRandomValues(e),Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}return Math.random().toString(36).substring(2)})(),o=await async function(){return new Promise(((e,t)=>{if(window.google)return void e(window.google.accounts.id);let n=document.getElementById("google-gsi-client-script");n||(n=document.createElement("script"),document.head.appendChild(n),n.async=!0,n.defer=!0,n.id="google-gsi-client-script",n.src="https://accounts.google.com/gsi/client"),n.onload=function(){window.google?e(window.google.accounts.id):t("Failed to load Google GSI client script - not loaded properly")},n.onerror=function(){t("Failed to load Google GSI client script - failed to load")}}))}(),a=await e.oauth.getOneTapClientId(t);if(!a.ok)throw new Error("Failed to get OneTap client ID for provider "+t);const c=a.data.clientId;return new Promise((e=>{var a,l;const d=n=>{e({provider:t,nonce:i,credential:null==n?void 0:n.credential})};o.initialize(Object.assign(Object.assign({},n),{itp_support:null===(a=null==n?void 0:n.itp_support)||void 0===a||a,use_fedcm_for_prompt:null===(l=null==n?void 0:n.use_fedcm_for_prompt)||void 0===l||l,client_id:c,callback:d,nonce:i})),o.prompt((e=>{var t,n;if(s&&(null==e?void 0:e.isDismissedMoment())){const n=null===(t=e.getDismissedReason)||void 0===t?void 0:t.call(e);return null==s||s(n),void d()}if(r&&(null==e?void 0:e.isSkippedMoment())){const t=null===(n=e.getSkippedReason)||void 0===n?void 0:n.call(e);return null==r||r(t),void d()}}))}))}(e,t.provider,t.oneTapConfig,t.onSkipped,t.onDismissed);if(!s.credential)return null;if(null==t?void 0:t.onCodeReceived){const r=await e.oauth.verifyOneTapIDToken(s.provider,s.credential,s.nonce,null==t?void 0:t.loginOptions);if(!r.ok||!r.data)throw new Error("Failed to verify OneTap client ID for provider "+s.provider);null===(n=null==t?void 0:t.onCodeReceived)||void 0===n||n.call(t,r.data.code)}else{const n=await e.oauth.exchangeOneTapIDToken(s.provider,s.credential,s.nonce,null==t?void 0:t.loginOptions);if(!n.ok||!n.data)throw new Error("Failed to exchange OneTap client ID for provider "+s.provider);null===(r=null==t?void 0:t.onAuthenticated)||void 0===r||r.call(t,n.data)}}catch(e){null===(s=null==t?void 0:t.onFailed)||void 0===s||s.call(t,e)}}var ki=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await gi(),r=Object.assign(Object.assign({location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:n},startOptionsVersion:1});return t[1]=r,e.flow.start(...t)}});let Ii;const xi=(e,t)=>new Promise(((n,r)=>{if(!e.length)return r(new Error("No URLs provided to loadScriptWithFallback"));const s=t();if(s)return n(s);const i=e.shift(),o=document.createElement("script");o.src=i,o.id=(e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t).toString(16)})(i),o.onload=()=>{const e=t();if(e)return n(e);throw new Error("Could not get entry after loading script from URL")},o.addEventListener("error",(()=>{xi(e,t),o.setAttribute("data-error","true")})),document.body.appendChild(o)})),Ei=(e,t,n)=>{const r=async()=>{let r,s;return r&&s||({client:r,stateUserKey:s}=await(async(e,t,n)=>{Ii||(Ii=(async()=>{try{return Promise.resolve().then((function(){return na}))}catch(e){return xi([Hs,Js],(()=>window.oidc))}})());const{OidcClient:r,WebStorageStateStore:s}=await Ii;if(!r)throw new Error("oidc-client-ts is not installed. Please install it by running `npm install oidc-client-ts`");const i=t,o=(null==n?void 0:n.redirectUri)||window.location.href,a=(null==n?void 0:n.scope)||"openid email roles descope.custom_claims offline_access",c=`${i}_user`;let l=e.httpClient.buildUrl(t);(null==n?void 0:n.applicationId)&&(l=`${l}/${n.applicationId}`);const d={authority:l,client_id:t,redirect_uri:o,response_type:"code",scope:a,stateStore:new s({store:window.localStorage,prefix:i}),loadUserInfo:!0,fetchRequestCredentials:"same-origin"};return(null==n?void 0:n.redirectUri)&&(d.redirect_uri=n.redirectUri),(null==n?void 0:n.scope)&&(d.scope=n.scope),{client:new r(d),stateUserKey:c}})(e,t,n)),{client:r,stateUserKey:s}},s=async(t="")=>{var n;const{client:s,stateUserKey:i}=await r(),o=await s.processSigninResponse(t||window.location.href);var a;return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(o)))),window.localStorage.setItem(i,JSON.stringify({id_token:(a=o).id_token,session_state:a.session_state,profile:a.profile})),(()=>{const e=new URL(window.location.href);e.searchParams.delete("code"),e.searchParams.delete("state"),window.history.replaceState({},document.title,e.toString())})(),o};return{loginWithRedirect:async(e={},t=!1)=>{const{client:n}=await r(),s=await n.createSigninRequest(e),{url:i}=s;return t||(window.location.href=i),{ok:!0,data:s}},finishLogin:s,finishLoginIfNeed:async(e="")=>{if(window.location.search.includes("code")&&window.location.search.includes("state"))return await s(e)},refreshToken:async t=>{var n;const{client:s,stateUserKey:i}=await r(),o=(e=>{const t=window.localStorage.getItem(e);return t?JSON.parse(t):null})(i);if(!o)throw new Error("User not found in storage to refresh token");let a=t;if(!a){const t={};e.httpClient.hooks.beforeRequest(t),a=t.token}const c=await s.useRefreshToken({state:{refresh_token:a,session_state:o.session_state,profile:o.profile}});return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(c)))),c},logout:async(e,t=!1)=>{const{client:n,stateUserKey:s}=await r();e||(e={}),e.id_token_hint=e.id_token_hint||Xs(),e.post_logout_redirect_uri=e.post_logout_redirect_uri||window.location.href;const i=await n.createSignoutRequest(e),{url:o}=i;return window.localStorage.removeItem(s),t||window.location.replace(o),i}}},Oi=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>n=>{var{fpKey:r,fpLoad:s}=n,i=t(n,["fpKey","fpLoad"]);return Fs?(r&&s&&ri(r).catch((()=>null)),e(Us(i,{beforeRequest:si}))):e(i)}),(e=>n=>{var{autoRefresh:r}=n,s=t(n,["autoRefresh"]);if(!r)return e(s);const{clearAllTimers:i,setTimer:o}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let a,c;Fs&&document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&a&&new Date>a&&(Ls("Expiration time passed, refreshing session"),l.refresh(Gs()||c))}));const l=e(Us(s,{afterRequest:async(e,t)=>{const{sessionJwt:n,refreshJwt:r,sessionExpiration:s}=await As(t);if(401===(null==t?void 0:t.status))Ls("Received 401, canceling all timers"),i();else if(n||s){if(a=((e,t)=>{if(t)return new Date(1e3*t);Ls("Could not extract expiration time from session token, trying to decode the token");try{const t=dn(e);if(t.exp)return new Date(1e3*t.exp)}catch(e){return null}})(n,s),!a)return void Ls("Could not extract expiration time from session token");c=r;const e=(e=>{let t=((n=e)?n.getTime()-(new Date).getTime():0)-2e4;var n;return t>zs&&(Ls(`Timeout is too large (${t}ms), setting it to ${zs}ms`),t=zs),t})(a);if(i(),e<=2e4)return void Ls("Session is too close to expiration, not setting refresh timer");const t=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});Ls(`Setting refresh timer for ${t}. (${e}ms)`),o((()=>{Ls("Refreshing session due to timer"),l.refresh(Gs()||r)}),e)}}}));return ar(l,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const n=await e(...t);return Ls("Clearing all timers"),i(),n}))}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.29.0"},t.baseHeaders)}))),(e=>t=>{const n=di(),r=di(),s=di(),i=e(Us(t,{afterRequest:async(e,t)=>{if(401===(null==t?void 0:t.status))r.pub(null),s.pub(null),n.pub(null);else{const e=await Ms(t);e&&s.pub(e);const{sessionJwt:i,sessionExpiration:o}=await As(t);i&&r.pub(i),(o||i)&&n.pub(o||42)}}})),o=ar(i,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const i=await e(...t);return r.pub(null),s.pub(null),n.pub(null),i}));return Object.assign(o,{onSessionTokenChange:r.sub,onUserChange:s.sub,onIsAuthenticatedChange:e=>n.sub((t=>{e(!!t)}))})}),(e=>n=>{var{storeLastAuthenticatedUser:r=!0,keepLastAuthenticatedUserAfterLogout:s=!1}=n,i=t(n,["storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout"]);if(!r)return Object.assign(e(i),{getLastUserLoginId:ai,getLastUserDisplayName:ci});const o=e(Us(i,{afterRequest:async(e,t)=>{var n;const r=await Ms(t),s=null===(n=null==r?void 0:r.loginIds)||void 0===n?void 0:n[0],i=null==r?void 0:r.name;s&&((e=>{Ns(ii,e)})(s),(e=>{Ns(oi,e)})(i))}}));let a=ar(o,["flow.start"],li);return a=ar(a,["logout","logoutAll"],(e=>t=>async(...n)=>{const r=await t(...n);return e||(Ds(ii),Ds(oi)),r})(s)),Object.assign(a,{getLastUserLoginId:ai,getLastUserDisplayName:ci})}),(e=>n=>{var{persistTokens:r,sessionTokenViaCookie:s,storagePrefix:i}=n,o=t(n,["persistTokens","sessionTokenViaCookie","storagePrefix"]);if(!r||!Fs)return e(o);const a=e(Us(o,{beforeRequest:(c=i,e=>Object.assign(e,{token:e.token||Gs(c)})),afterRequest:async(e,t)=>{const n=/^\/v\d+\/mgmt\//.test(e.path);401===(null==t?void 0:t.status)?n||Qs(i):((e={},t=!1,n="")=>{var r;const{sessionJwt:s,refreshJwt:i}=e;if(i&&Ns(`${n}${Bs}`,i),s)if(t){const n=t.sameSite||"Strict",i=null===(r=t.secure)||void 0===r||r;!function(e,t,n){if(t){const{cookieDomain:r,cookiePath:s,cookieSameSite:i,cookieExpiration:o,cookieSecure:a}=n,c=new Date(1e3*o),l=function(e){const t=window.location.hostname.split("."),n=e.split(".");return t.slice(-n.length).join(".")===e}(r);_s.set(e,t,{path:s,domain:l?r:void 0,expires:c,sameSite:i,secure:a})}}(Ks,s,Object.assign(Object.assign({},e),{cookieSameSite:n,cookieSecure:i}))}else Ns(`${n}${Ks}`,s);e.idToken&&Ns(`${n}${Vs}`,e.idToken)})(await As(t),s,i)}}));var c;const l=ar(a,["logout","logoutAll","oidc.logout"],(e=>t=>async(...n)=>{const r=await t(...n);return Qs(e),r})(i));return Object.assign(l,{getRefreshToken:()=>Gs(i),getSessionToken:()=>Ys(i),getIdToken:()=>Xs(i)})}))((e=>{const t=ms(e),n=Ei(t,e.projectId,e.oidcConfig);return Object.assign(Object.assign({},t),{refresh:async r=>{if(e.oidcConfig)try{return await n.refreshToken(r),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161001",errorDescription:e.toString()}})}const s=Ys(),i=Gs();return t.refresh(r,{dcs:s?"t":"f",dcr:i?"t":"f"})},logout:async r=>{if(e.oidcConfig)try{return await n.logout({id_token_hint:r}),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161000",errorDescription:e.toString()}})}return t.logout(r)},flow:ki(t),webauthn:vi(t),fedcm:(r=t,s=e.projectId,{onetap:{requestExchangeCode(e){Si(r,e)},requestAuthentication(e){Si(r,e)}},oneTap(e,t,n,s,i){Si(r,{provider:e,oneTapConfig:t,loginOptions:n,onSkipped:s,onDismissed:i})},async launch(e){var t;const n={identity:{context:e||"signin",providers:[{configURL:r.httpClient.buildUrl(s+bi),clientId:s}]}},i=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(n));return r.refresh(i.token)},isSupported:()=>Fs&&"IdentityCredential"in window,async isLoggedIn(e){var t;const n=r.httpClient.buildUrl(s+bi);try{const r={identity:{context:e||"signin",providers:[{configURL:n,clientId:s}]}},i=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(r));return!!i&&!!i.token}catch(e){return!1}}}),oidc:n});var r,s})),Ti={load:"/v1/mgmt/sso/idp/apps/load"},Ci=()=>n(void 0,void 0,void 0,(function*(){return new Promise((e=>{e({apps:[{id:"ssoapp1",name:"App 1",description:"This is the first SAML app",enabled:!0,appType:Zt.saml,logo:"logo1",samlSettings:{idpInitiatedUrl:""}},{id:"ssoapp2",name:"App 2",description:"This is the first OIDC app",enabled:!0,appType:Zt.oidc,logo:"logo2"},{id:"ssoapp3",name:"App 3",description:"This is the second SAML app",enabled:!0,appType:Zt.saml,logo:"logo3",samlSettings:{idpInitiatedUrl:""}}]})}))})),ji=({httpClient:e,mock:t})=>({load:()=>n(void 0,void 0,void 0,(function*(){if(t)return Ci();const r=yield e.get(Ti.load);return yield(e=>n(void 0,void 0,void 0,(function*(){const t=yield e.text(),n=JSON.parse(t);if(!e.ok){const t=`${n.errorDescription}${n.errorMessage?`: ${n.errorMessage}`:""}`;throw Error(t||`${e.status} ${e.statusText}`)}e.json=()=>Promise.resolve(n),e.text=()=>Promise.resolve(t)})))(r),r.json()}))}),Ri=a((e=>{var t,o,a,c;const l=i(S,v,f,Qt,k)(e);return c=class extends l{constructor(){super(...arguments),t.add(this),o.set(this,void 0)}get widgetId(){return this.getAttribute("widget-id")}get mock(){return this.getAttribute("mock")}get api(){return r(this,o,"f")||r(this,t,"m",a).call(this),r(this,o,"f")}init(){const e=Object.create(null,{init:{get:()=>super.init}});return n(this,void 0,void 0,(function*(){var n;yield null===(n=e.init)||void 0===n?void 0:n.call(this),this.observeAttributes(["project-id","base-url"],(()=>{r(this,o,"f")&&r(this,t,"m",a).call(this)}))}))}},o=new WeakMap,t=new WeakSet,a=function(){this.logger.debug("creating an sdk instance"),s(this,o,((e,t,n)=>{const r=Oi(Object.assign(Object.assign({},e),{persistTokens:!0,baseHeaders:{"x-descope-widget-type":"applications-portal-widget","x-descope-widget-id":n,"x-descope-widget-version":"0.3.11"}}));return{ssoApps:ji({httpClient:r.httpClient,mock:t})}})({projectId:this.projectId,baseUrl:this.baseUrl,refreshCookieName:this.refreshCookieName},"true"===this.mock,this.widgetId),"f")},c})),Pi=a((e=>{const t=i(Xt({name:"widget",initialState:an,reducers:{},extraReducers:e=>{on.reducer(e)},asyncActions:{loadSSOApps:on.action}}),y,f,Ri)(e);return class extends t{constructor(...e){super(...e),this.state=an,this.subscribe((e=>{this.logger.debug("State update:",e),this.state=e}))}}})),Ui=a((e=>{const t=i(E,b({"widget-id":b.missingAttrValidator}))(e);return class extends t{get widgetId(){return this.getAttribute("widget-id")}fetchWidgetPage(e){return n(this,void 0,void 0,(function*(){return(yield this.fetchStaticResource(`applications-portal-widget/${this.widgetId}/${e}`,"text")).body}))}}})),Ai=a((e=>{var t,s,a,c;return c=class extends(i(f,y,N,L,Ui,Pi)(e)){constructor(){super(...arguments),t.add(this)}onWidgetRootReady(){return n(this,void 0,void 0,(function*(){}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});return n(this,void 0,void 0,(function*(){var n;yield null===(n=e.init)||void 0===n?void 0:n.call(this);const[i]=yield Promise.all([r(this,t,"m",s).call(this),this.actions.loadSSOApps()]);r(this,t,"m",a).call(this,i),this.onWidgetRootReady()}))}},t=new WeakSet,s=function(){return n(this,void 0,void 0,(function*(){const e=o(yield this.fetchWidgetPage("root.html"));return yield this.loadDescopeUiComponents(e),e}))},a=function(e){this.contentRootElement.append(e.content.cloneNode(!0))},c})),Mi=a((e=>{var t,s,o;return o=class extends(i(Pi,f,Ai)(e)){constructor(){super(...arguments),t.add(this)}onWidgetRootReady(){const e=Object.create(null,{onWidgetRootReady:{get:()=>super.onWidgetRootReady}});return n(this,void 0,void 0,(function*(){var n;yield null===(n=e.onWidgetRootReady)||void 0===n?void 0:n.call(this),r(this,t,"m",s).call(this,tn(this.state))}))}},t=new WeakSet,s=function(e){this.appsList=new B((()=>{var e;return null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector("descope-apps-list")}),{logger:this.logger}),this.appsList.data=e},o})),$i=a((e=>class extends(i(C,Y,Mi)(e)){init(){const e=Object.create(null,{init:{get:()=>super.init}});return n(this,void 0,void 0,(function*(){var t;yield null===(t=e.init)||void 0===t?void 0:t.call(this)}))}})),Ni=i((e=>class extends($i(e)){}))(HTMLElement);customElements.define("descope-applications-portal-widget",Ni);const qi=(e,t,n,r={})=>{var s,i,o,a;return[Math.min(Math.max(t,("all"===r.left?e.offsetWidth:null!==(s=r.left)&&void 0!==s?s:0)-e.offsetWidth),window.innerWidth-("all"===r.right?e.offsetWidth:null!==(i=r.right)&&void 0!==i?i:0)),Math.min(Math.max(n,("all"===r.top?e.offsetHeight:null!==(o=r.top)&&void 0!==o?o:0)-e.offsetHeight),window.innerHeight-("all"===r.bottom?e.offsetHeight:null!==(a=r.bottom)&&void 0!==a?a:0))]};var Di,Li,Wi,Fi,zi,Hi,Ji,Ki,Bi,Vi;const Gi=document.createElement("template");Gi.innerHTML=`\n<div style="top:32px; left:${window.innerWidth-300-32}px;" class="debugger">\n <div class="header">\n <span>Debugger messages</span>\n </div>\n <div class="content">\n <div class="empty-state">\n No errors detected 👀\n </div>\n </div>\n</div>\n`;class Yi extends HTMLElement{constructor(){var e,t,n;super(),Di.add(this),Li.set(this,new p({messages:[]})),Wi.set(this,void 0),Fi.set(this,void 0),zi.set(this,void 0),Hi.set(this,{resize:r(this,Di,"m",Vi).bind(this)}),this.attachShadow({mode:"open"}),null===(e=this.shadowRoot)||void 0===e||e.appendChild(Gi.content.cloneNode(!0));const i=new CSSStyleSheet;i.replaceSync('\n.debugger {\n all: initial;\n width: 300px;\n height: 200px;\n background-color: #FAFAFA;\n position: fixed;\n font-family: "Helvetica Neue", sans-serif;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 5px 10px;\n border-radius: 8px;\n overflow: hidden;\n border: 1px solid lightgrey;\n pointer-events: initial;\n display: flex;\n flex-direction: column;\n min-width: 200px;\n max-width: 600px;\n max-height: calc(100% - 64px);\n min-height: 200px;\n resize: both;\n }\n\n .header {\n padding: 8px 16px;\n display: flex;\n align-items: center;\n background-color: #EEEEEE;\n cursor: move;\n border-bottom: 1px solid #e0e0e0;\n }\n\n .content {\n font-size: 14px;\n flex-grow: 1;\n overflow: auto;\n }\n\n .msg {\n border-bottom: 1px solid lightgrey;\n padding: 8px 16px;\n display: flex;\n gap: 5px;\n background-color: #FAFAFA;\n }\n\n .msg.collapsible {\n cursor: pointer;\n }\n\n .empty-state {\n padding: 8px 16px;\n background-color: #FAFAFA;\n }\n\n\n .msg.collapsible:not(.collapsed) {\n background-color: #F5F5F5;\n }\n\n .msg_title {\n padding-bottom: 5px;\n display: flex;\n gap: 8px;\n font-weight: 500;\n }\n\n .msg svg {\n padding: 1px;\n flex-shrink: 0;\n margin-top: -2px;\n }\n\n .msg_content {\n overflow: hidden;\n flex-grow: 1;\n margin-right:5px;\n }\n\n .msg_desc {\n color: #646464;\n cursor: initial;\n word-wrap: break-word;\n }\n\n .msg.collapsed .msg_desc {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .msg.collapsible.collapsed .chevron {\n transform: rotate(-45deg) translateX(-2px);\n }\n\n .msg.collapsible .chevron {\n content: "";\n width:6px;\n height:6px;\n border-bottom: 2px solid grey;\n border-right: 2px solid grey;\n transform: rotate(45deg) translateX(-1px);\n margin: 5px;\n flex-shrink:0;\n }\n'),null!==(t=(n=this.shadowRoot).adoptedStyleSheets)&&void 0!==t||(n.adoptedStyleSheets=[]),this.shadowRoot.adoptedStyleSheets=[...this.shadowRoot.adoptedStyleSheets,i],s(this,Wi,this.shadowRoot.querySelector(".debugger"),"f"),s(this,Fi,r(this,Wi,"f").querySelector(".content"),"f"),s(this,zi,r(this,Wi,"f").querySelector(".header"),"f")}updateData(e){r(this,Li,"f").update((t=>({messages:t.messages.concat(e)})))}connectedCallback(){var e;((e,t,n)=>{let r=0,s=0,i=0,o=0;function a(t){t.preventDefault(),r=i-t.clientX,s=o-t.clientY,i=t.clientX,o=t.clientY;const[a,c]=qi(e,e.offsetLeft-r,e.offsetTop-s,n);e.style.top=`${c}px`,e.style.left=`${a}px`}function c(){document.onmouseup=null,document.onmousemove=null}function l(e){e.preventDefault(),i=e.clientX,o=e.clientY,document.onmouseup=c,document.onmousemove=a}t?t.onmousedown=l:e.onmousedown=l})(r(this,Wi,"f"),r(this,zi,"f"),{top:"all",bottom:100,left:100,right:100}),window.addEventListener("resize",r(this,Hi,"f").resize),(e=r(this,Wi,"f")).onmousemove=t=>{var n;const r=t.target;(r.w&&r.w!==r.offsetWidth||r.h&&r.h!==r.offsetHeight)&&(null===(n=e.onresize)||void 0===n||n.call(e,t)),r.w=r.offsetWidth,r.h=r.offsetHeight},r(this,Wi,"f").onresize=r(this,Di,"m",Bi).bind(this),r(this,Li,"f").subscribe(r(this,Di,"m",Ji).bind(this))}disconnectedCallback(){r(this,Li,"f").unsubscribeAll(),window.removeEventListener("resize",r(this,Hi,"f").resize)}}Li=new WeakMap,Wi=new WeakMap,Fi=new WeakMap,zi=new WeakMap,Hi=new WeakMap,Di=new WeakSet,Ji=function(e){r(this,Di,"m",Ki).call(this,e),r(this,Di,"m",Bi).call(this)},Ki=function(e){r(this,Fi,"f").innerHTML=e.messages.map((e=>`\n <div class="msg">\n <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M5.99984 13.167L8.99984 10.167L11.9998 13.167L13.1665 12.0003L10.1665 9.00033L13.1665 6.00033L11.9998 4.83366L8.99984 7.83366L5.99984 4.83366L4.83317 6.00033L7.83317 9.00033L4.83317 12.0003L5.99984 13.167ZM8.99984 17.3337C7.84706 17.3337 6.76373 17.1148 5.74984 16.677C4.73595 16.2398 3.854 15.6462 3.104 14.8962C2.354 14.1462 1.76039 13.2642 1.32317 12.2503C0.885393 11.2364 0.666504 10.1531 0.666504 9.00033C0.666504 7.84755 0.885393 6.76421 1.32317 5.75033C1.76039 4.73644 2.354 3.85449 3.104 3.10449C3.854 2.35449 4.73595 1.7606 5.74984 1.32283C6.76373 0.885603 7.84706 0.666992 8.99984 0.666992C10.1526 0.666992 11.2359 0.885603 12.2498 1.32283C13.2637 1.7606 14.1457 2.35449 14.8957 3.10449C15.6457 3.85449 16.2393 4.73644 16.6765 5.75033C17.1143 6.76421 17.3332 7.84755 17.3332 9.00033C17.3332 10.1531 17.1143 11.2364 16.6765 12.2503C16.2393 13.2642 15.6457 14.1462 14.8957 14.8962C14.1457 15.6462 13.2637 16.2398 12.2498 16.677C11.2359 17.1148 10.1526 17.3337 8.99984 17.3337ZM8.99984 15.667C10.8609 15.667 12.4373 15.0212 13.729 13.7295C15.0207 12.4378 15.6665 10.8614 15.6665 9.00033C15.6665 7.13921 15.0207 5.56283 13.729 4.27116C12.4373 2.97949 10.8609 2.33366 8.99984 2.33366C7.13873 2.33366 5.56234 2.97949 4.27067 4.27116C2.979 5.56283 2.33317 7.13921 2.33317 9.00033C2.33317 10.8614 2.979 12.4378 4.27067 13.7295C5.56234 15.0212 7.13873 15.667 8.99984 15.667Z" fill="#ED404A"/>\n</svg>\n\n <div class="msg_content">\n <div class="msg_title">\n ${e.title}\n </div>\n <div class="msg_desc">\n ${e.description||""}\n </div>\n </div>\n <div class="chevron"></div>\n </div>\n `)).join("")},Bi=function(){r(this,Fi,"f").querySelectorAll(".msg").forEach((e=>{const t=e,n=t.querySelector(".msg_desc"),r=n.scrollWidth>n.clientWidth,s=n.clientHeight>20;r||s?(t.classList.add("collapsible"),t.onclick=e=>{e.target.classList.contains("msg_desc")||t.classList.toggle("collapsed")}):(t.classList.remove("collapsible"),t.onclick=null)}))},Vi=function(){const[e,t]=qi(r(this,Wi,"f"),Number.parseInt(r(this,Wi,"f").style.left,10),Number.parseInt(r(this,Wi,"f").style.top,10),{top:"all",bottom:100,left:100,right:100});r(this,Wi,"f").style.top=`${t}px`,r(this,Wi,"f").style.left=`${e}px`},customElements.get("descope-debugger")||customElements.define("descope-debugger",Yi);var Xi,Qi,Zi,eo=Object.freeze({__proto__:null,default:Yi}),to={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},no=(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))(no||{});(Zi=no||(no={})).reset=function(){Xi=3,Qi=to},Zi.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");Xi=e},Zi.setLogger=function(e){Qi=e};var ro=class e{constructor(e){this._name=e}debug(...t){Xi>=4&&Qi.debug(e._format(this._name,this._method),...t)}info(...t){Xi>=3&&Qi.info(e._format(this._name,this._method),...t)}warn(...t){Xi>=2&&Qi.warn(e._format(this._name,this._method),...t)}error(...t){Xi>=1&&Qi.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,n){const r=new e(`${t}.${n}`);return r.debug("begin"),r}static _format(e,t){const n=`[${e}]`;return t?`${n} ${t}:`:n}static debug(t,...n){Xi>=4&&Qi.debug(e._format(t),...n)}static info(t,...n){Xi>=3&&Qi.info(e._format(t),...n)}static warn(t,...n){Xi>=2&&Qi.warn(e._format(t),...n)}static error(t,...n){Xi>=1&&Qi.error(e._format(t),...n)}};no.reset();var so=class{static decode(e){try{return dn(e)}catch(e){throw ro.error("JwtUtils.decode",e),e}}static async generateSignedJwt(e,t,n){const r=`${ao.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${ao.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,(new TextEncoder).encode(r));return`${r}.${ao.encodeBase64Url(new Uint8Array(s))}`}},io=e=>btoa([...new Uint8Array(e)].map((e=>String.fromCharCode(e))).join("")),oo=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),n=await crypto.subtle.digest("SHA-256",t);return io(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw ro.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const n=(new TextEncoder).encode([e,t].join(":"));return io(n)}static async hash(e,t){const n=(new TextEncoder).encode(t),r=await crypto.subtle.digest(e,n);return new Uint8Array(r)}static async customCalculateJwkThumbprint(t){let n;switch(t.kty){case"RSA":n={e:t.e,kty:t.kty,n:t.n};break;case"EC":n={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":n={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":n={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const r=await e.hash("SHA-256",JSON.stringify(n));return e.encodeBase64Url(r)}static async generateDPoPProof({url:t,accessToken:n,httpMethod:r,keyPair:s,nonce:i}){let o,a;const c={jti:window.crypto.randomUUID(),htm:null!=r?r:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};n&&(o=await e.hash("SHA-256",n),a=e.encodeBase64Url(o),c.ath=a),i&&(c.nonce=i);try{const e=await crypto.subtle.exportKey("jwk",s.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await so.generateSignedJwt(t,c,s.privateKey)}catch(e){throw e instanceof TypeError?new Error(`Error exporting dpop public key: ${e.message}`):e}}static async generateDPoPJkt(t){try{const n=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(n)}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"])}};oo.encodeBase64Url=e=>io(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var ao=oo,co=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new ro(`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)}},lo=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(",")}},uo=class e extends co{constructor(){super(...arguments),this._logger=new ro(`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 n=this._logger.create("init");t=Math.max(Math.floor(t),1);const r=e.getEpochTime()+t;if(this.expiration===r&&this._timerHandle)return void n.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),n.debug("using duration",t),this._expiration=r;const s=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*s)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},ho=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const n=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(n.slice(1))}},po=";",go=class extends Error{constructor(e,t){var n,r,s;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw ro.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(n=e.error_description)?n:null,this.error_uri=null!=(r=e.error_uri)?r:null,this.state=e.userState,this.session_state=null!=(s=e.session_state)?s:null,this.url_state=e.url_state}},fo=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},mo=class{constructor(e){this._logger=new ro("AccessTokenEvents"),this._expiringTimer=new uo("Access token expiring"),this._expiredTimer=new uo("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 n=e.expires_in;if(t.debug("access token present, remaining duration:",n),n>0){let e=n-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 r=n+1;t.debug("registering expired timer, raising in",r,"seconds"),this._expiredTimer.init(r)}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)}},wo=class{constructor(e,t,n,r,s){this._callback=e,this._client_id=t,this._intervalInSeconds=r,this._stopOnError=s,this._logger=new ro("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 i=new URL(n);this._frame_origin=i.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=i.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)}},_o=class{constructor(){this._logger=new ro("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]}},yo=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},vo=class{constructor(e=[],t=null,n={}){this._jwtHandler=t,this._extraHeaders=n,this._logger=new ro("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:n,...r}=t;if(!n)return await fetch(e,r);const s=new AbortController,i=setTimeout((()=>s.abort()),1e3*n);try{return await fetch(e,{...t,signal:s.signal})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw new fo("Network timed out");throw e}finally{clearTimeout(i)}}async getJson(e,{token:t,credentials:n,timeoutInSeconds:r}={}){const s=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};let o;t&&(s.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+t),this._appendExtraHeaders(i);try{s.debug("url:",e),o=await this.fetchWithTimeout(e,{method:"GET",headers:i,timeoutInSeconds:r,credentials:n})}catch(e){throw s.error("Network Error"),e}s.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find((e=>a.startsWith(e)))&&s.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(s.error("Error parsing JSON response",e),o.ok)throw e;throw new Error(`${o.statusText} (${o.status})`)}if(!o.ok){if(s.error("Error from server:",c),c.error)throw new go(c);throw new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:n,timeoutInSeconds:r,initCredentials:s,extraHeaders:i}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...i};let c;void 0!==n&&(a.Authorization="Basic "+n),this._appendExtraHeaders(a);try{o.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:r,credentials:s})}catch(e){throw o.error("Network error"),e}o.debug("HTTP response received, status",c.status);const l=c.headers.get("Content-Type");if(l&&!this._contentTypes.find((e=>l.startsWith(e))))throw new Error(`Invalid response Content-Type: ${null!=l?l:"undefined"}, from URL: ${e}`);const d=await c.text();let u={};if(d)try{u=JSON.parse(d)}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:",u),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new yo(e,`${JSON.stringify(u)}`)}if(u.error)throw new go(u,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(u)}`)}return u}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),n=Object.keys(this._extraHeaders),r=["accept","content-type"],s=["authorization"];0!==n.length&&n.forEach((n=>{if(r.includes(n.toLocaleLowerCase()))return void t.warn("Protected header could not be set",n,r);if(s.includes(n.toLocaleLowerCase())&&Object.keys(e).includes(n))return void t.warn("Header could not be overridden",n,s);const i="function"==typeof this._extraHeaders[n]?this._extraHeaders[n]():this._extraHeaders[n];i&&""!==i&&(e[n]=i)}))}},bo=class{constructor(e){this._settings=e,this._logger=new ro("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new vo(["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 n=this._logger.create(`_getMetadataProperty('${e}')`),r=await this.getMetadata();if(n.debug("resolved"),void 0===r[e]){if(!0===t)return void n.warn("Metadata does not contain optional property");n.throw(new Error("Metadata does not contain property "+e))}return r[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 n=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",n),!Array.isArray(n.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=n.keys,this._signingKeys}},So=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new ro("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){this._logger.create(`get('${e}')`),e=this._prefix+e;return 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 n=0;n<e;n++){const e=await this._store.key(n);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},ko=class{constructor({authority:e,metadataUrl:t,metadata:n,signingKeys:r,metadataSeed:s,client_id:i,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:l,post_logout_redirect_uri:d,client_authentication:u="client_secret_post",prompt:h,display:p,max_age:g,ui_locales:f,acr_values:m,resource:w,response_mode:_,filterProtocolClaims:y=!0,loadUserInfo:v=!1,requestTimeoutInSeconds:b,staleStateAgeInSeconds:S=900,mergeClaimsStrategy:k={array:"replace"},disablePKCE:I=!1,stateStore:x,revokeTokenAdditionalContentTypes:E,fetchRequestCredentials:O,refreshTokenAllowedScope:T,extraQueryParams:C={},extraTokenParams:j={},extraHeaders:R={},dpop:P,omitScopeWhenRequesting:U=!1}){var A;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=n,this.metadataSeed=s,this.signingKeys=r,this.client_id=i,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=l,this.post_logout_redirect_uri=d,this.client_authentication=u,this.prompt=h,this.display=p,this.max_age=g,this.ui_locales=f,this.acr_values=m,this.resource=w,this.response_mode=_,this.filterProtocolClaims=null==y||y,this.loadUserInfo=!!v,this.staleStateAgeInSeconds=S,this.mergeClaimsStrategy=k,this.omitScopeWhenRequesting=U,this.disablePKCE=!!I,this.revokeTokenAdditionalContentTypes=E,this.fetchRequestCredentials=O||"same-origin",this.requestTimeoutInSeconds=b,x)this.stateStore=x;else{const e="undefined"!=typeof window?window.localStorage:new _o;this.stateStore=new So({store:e})}if(this.refreshTokenAllowedScope=T,this.extraQueryParams=C,this.extraTokenParams=j,this.extraHeaders=R,this.dpop=P,this.dpop&&!(null==(A=this.dpop)?void 0:A.store))throw new Error("A DPoPStore is required when dpop is enabled")}},Io=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new ro("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const n=so.decode(e);return t.debug("JWT decoding successful"),n}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new vo(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 n=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",n);const r=await this._jsonService.getJson(n,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",r),r}},xo=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new ro("TokenClient"),this._jsonService=new vo(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:n=this._settings.client_id,client_secret:r=this._settings.client_secret,extraHeaders:s,...i}){const o=this._logger.create("exchangeCode");n||o.throw(new Error("A client_id is required")),t||o.throw(new Error("A redirect_uri is required")),i.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(i))null!=t&&a.set(e,t);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(null==r)throw o.throw(new Error("A client_secret is required")),null;c=ao.generateBasicAuth(n,r);break;case"client_secret_post":a.append("client_id",n),r&&a.append("client_secret",r)}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const d=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:s});return o.debug("got response"),d}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,scope:r=this._settings.scope,...s}){const i=this._logger.create("exchangeCredentials");t||i.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set("scope",r);for(const[e,t]of Object.entries(s))null!=t&&o.set(e,t);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw i.throw(new Error("A client_secret is required")),null;a=ao.generateBasicAuth(t,n);break;case"client_secret_post":o.append("client_id",t),n&&o.append("client_secret",n)}const c=await this._metadataService.getTokenEndpoint(!1);i.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return i.debug("got response"),l}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,timeoutInSeconds:r,extraHeaders:s,...i}){const o=this._logger.create("exchangeRefreshToken");t||o.throw(new Error("A client_id is required")),i.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(i))Array.isArray(t)?t.forEach((t=>a.append(e,t))):null!=t&&a.set(e,t);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw o.throw(new Error("A client_secret is required")),null;c=ao.generateBasicAuth(t,n);break;case"client_secret_post":a.append("client_id",t),n&&a.append("client_secret",n)}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const d=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:s});return o.debug("got response"),d}async revoke(e){var t;const n=this._logger.create("revoke");e.token||n.throw(new Error("A token is required"));const r=await this._metadataService.getRevocationEndpoint(!1);n.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const s=new URLSearchParams;for(const[t,n]of Object.entries(e))null!=n&&s.set(t,n);s.set("client_id",this._settings.client_id),this._settings.client_secret&&s.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(r,{body:s,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),n.debug("got response")}},Eo=class{constructor(e,t,n){this._settings=e,this._metadataService=t,this._claimsService=n,this._logger=new ro("ResponseValidator"),this._userInfoService=new Io(this._settings,this._metadataService),this._tokenClient=new xo(this._settings,this._metadataService)}async validateSigninResponse(e,t,n){const r=this._logger.create("validateSigninResponse");this._processSigninState(e,t),r.debug("state processed"),await this._processCode(e,t,n),r.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),r.debug("claims processed")}async validateCredentialsResponse(e,t){const n=this._logger.create("validateCredentialsResponse");e.isOpenId&&e.id_token&&this._validateIdTokenAttributes(e),n.debug("tokens validated"),await this._processClaims(e,t,e.isOpenId),n.debug("claims processed")}async validateRefreshResponse(e,t){const n=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),n.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const r=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,r),n.debug("claims processed")}validateSignoutResponse(e,t){const n=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&n.throw(new Error("State does not match")),n.debug("state validated"),e.userState=t.data,e.error)throw n.warn("Response was error",e.error),new go(e)}_processSigninState(e,t){const n=this._logger.create("_processSigninState");if(t.id!==e.state&&n.throw(new Error("State does not match")),t.client_id||n.throw(new Error("No client_id on state")),t.authority||n.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&n.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&n.throw(new Error("client_id mismatch on settings vs. signin state")),n.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw n.warn("Response was error",e.error),new go(e);t.code_verifier&&!e.code&&n.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,n=!0){const r=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void r.debug("not loading user info");r.debug("loading user info");const s=await this._userInfoService.getClaims(e.access_token);r.debug("user info claims received from user info endpoint"),n&&s.sub!==e.profile.sub&&r.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(s)),r.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,n){const r=this._logger.create("_processCode");if(e.code){r.debug("Validating code");const s=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:n,...t.extraTokenParams});Object.assign(e,s)}else r.debug("No code to process")}_validateIdTokenAttributes(e,t){var n;const r=this._logger.create("_validateIdTokenAttributes");r.debug("decoding ID Token JWT");const s=so.decode(null!=(n=e.id_token)?n:"");if(s.sub||r.throw(new Error("ID Token is missing a subject claim")),t){const e=so.decode(t);s.sub!==e.sub&&r.throw(new Error("sub in id_token does not match current sub")),s.auth_time&&s.auth_time!==e.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),s.azp&&s.azp!==e.azp&&r.throw(new Error("azp in id_token does not match original azp")),!s.azp&&e.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=s}},Oo=class e{constructor(e){this.id=e.id||ao.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=uo.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new ro("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 ro.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,n){const r=ro.createStatic("State","clearStaleState"),s=uo.getEpochTime()-n,i=await t.getAllKeys();r.debug("got keys",i);for(let n=0;n<i.length;n++){const o=i[n],a=await t.get(o);let c=!1;if(a)try{const t=await e.fromStorageString(a);r.debug("got item from key:",o,t.created),t.created<=s&&(c=!0)}catch(e){r.error("Error parsing state for key:",o,e),c=!0}else r.debug("no item in storage for key:",o),c=!0;c&&(r.debug("removed item for key:",o),t.remove(o))}}},To=class e extends Oo{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 n=!0===t.code_verifier?ao.generateCodeVerifier():t.code_verifier||void 0,r=n?await ao.generateCodeChallenge(n):void 0;return new e({...t,code_verifier:n,code_challenge:r})}toStorageString(){return new ro("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){ro.createStatic("SigninState","fromStorageString");const n=JSON.parse(t);return e.create(n)}},Co=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:n,client_id:r,redirect_uri:s,response_type:i,scope:o,state_data:a,response_mode:c,request_type:l,client_secret:d,nonce:u,url_state:h,resource:p,skipUserInfo:g,extraQueryParams:f,extraTokenParams:m,disablePKCE:w,dpopJkt:_,omitScopeWhenRequesting:y,...v}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!r)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!s)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!i)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(!n)throw this._logger.error("create: No authority passed"),new Error("authority");const b=await To.create({data:a,request_type:l,url_state:h,code_verifier:!w,client_id:r,authority:n,redirect_uri:s,response_mode:c,client_secret:d,scope:o,extraTokenParams:m,skipUserInfo:g}),S=new URL(t);S.searchParams.append("client_id",r),S.searchParams.append("redirect_uri",s),S.searchParams.append("response_type",i),y||S.searchParams.append("scope",o),u&&S.searchParams.append("nonce",u),_&&S.searchParams.append("dpop_jkt",_);let k=b.id;if(h&&(k=`${k}${po}${h}`),S.searchParams.append("state",k),b.code_challenge&&(S.searchParams.append("code_challenge",b.code_challenge),S.searchParams.append("code_challenge_method","S256")),p){(Array.isArray(p)?p:[p]).forEach((e=>S.searchParams.append("resource",e)))}for(const[e,t]of Object.entries({response_mode:c,...v,...f}))null!=t&&S.searchParams.append(e,t.toString());return new e({url:S.href,state:b})}};Co._logger=new ro("SigninRequest");var jo=Co,Ro=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(po);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(po))}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-uo.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+uo.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},Po=class{constructor({url:e,state_data:t,id_token_hint:n,post_logout_redirect_uri:r,extraQueryParams:s,request_type:i,client_id:o,url_state:a}){if(this._logger=new ro("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(n&&c.searchParams.append("id_token_hint",n),o&&c.searchParams.append("client_id",o),r&&(c.searchParams.append("post_logout_redirect_uri",r),t||a)){this.state=new Oo({data:t,request_type:i,url_state:a});let e=this.state.id;a&&(e=`${e}${po}${a}`),c.searchParams.append("state",e)}for(const[e,t]of Object.entries({...s}))null!=t&&c.searchParams.append(e,t.toString());this.url=c.href}},Uo=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(po);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(po))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},Ao=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],Mo=["sub","iss","aud","exp","iat"],$o=class{constructor(e){this._settings=e,this._logger=new ro("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:Ao;for(const n of e)Mo.includes(n)||delete t[n]}return t}mergeClaims(e,t){const n={...e};for(const[e,r]of Object.entries(t))if(n[e]!==r)if(Array.isArray(n[e])||Array.isArray(r))if("replace"==this._settings.mergeClaimsStrategy.array)n[e]=r;else{const t=Array.isArray(n[e])?n[e]:[n[e]];for(const e of Array.isArray(r)?r:[r])t.includes(e)||t.push(e);n[e]=t}else"object"==typeof n[e]&&"object"==typeof r?n[e]=this.mergeClaims(n[e],r):n[e]=r;return n}},No=class{constructor(e,t){this.keys=e,this.nonce=t}},qo=class{constructor(e,t){this._logger=new ro("OidcClient"),this.settings=e instanceof ko?e:new ko(e),this.metadataService=null!=t?t:new bo(this.settings),this._claimsService=new $o(this.settings),this._validator=new Eo(this.settings,this.metadataService,this._claimsService),this._tokenClient=new xo(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:n,request_type:r,id_token_hint:s,login_hint:i,skipUserInfo:o,nonce:a,url_state:c,response_type:l=this.settings.response_type,scope:d=this.settings.scope,redirect_uri:u=this.settings.redirect_uri,prompt:h=this.settings.prompt,display:p=this.settings.display,max_age:g=this.settings.max_age,ui_locales:f=this.settings.ui_locales,acr_values:m=this.settings.acr_values,resource:w=this.settings.resource,response_mode:_=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:v=this.settings.extraTokenParams,dpopJkt:b,omitScopeWhenRequesting:S=this.settings.omitScopeWhenRequesting}){const k=this._logger.create("createSigninRequest");if("code"!==l)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const I=await this.metadataService.getAuthorizationEndpoint();k.debug("Received authorization endpoint",I);const x=await jo.create({url:I,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:u,response_type:l,scope:d,state_data:e,url_state:c,prompt:h,display:p,max_age:g,ui_locales:f,id_token_hint:s,login_hint:i,acr_values:m,dpopJkt:b,resource:w,request:t,request_uri:n,extraQueryParams:y,extraTokenParams:v,request_type:r,response_mode:_,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:S});await this.clearStaleState();const E=x.state;return await this.settings.stateStore.set(E.id,E.toStorageString()),x}async readSigninResponseState(e,t=!1){const n=this._logger.create("readSigninResponseState"),r=new Ro(ho.readParams(e,this.settings.response_mode));if(!r.state)throw n.throw(new Error("No state in response")),null;const s=await this.settings.stateStore[t?"remove":"get"](r.state);if(!s)throw n.throw(new Error("No matching state found in storage")),null;return{state:await To.fromStorageString(s),response:r}}async processSigninResponse(e,t,n=!0){const r=this._logger.create("processSigninResponse"),{state:s,response:i}=await this.readSigninResponseState(e,n);if(r.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(i,s,t)}catch(e){if(!(e instanceof yo&&this.settings.dpop))throw e;{const n=await this.getDpopProof(this.settings.dpop.store,e.nonce);t.DPoP=n,await this._validator.validateSigninResponse(i,s,t)}}return i}async getDpopProof(e,t){let n,r;return(await e.getAllKeys()).includes(this.settings.client_id)?(r=await e.get(this.settings.client_id),r.nonce!==t&&t&&(r.nonce=t,await e.set(this.settings.client_id,r))):(n=await ao.generateDPoPKeys(),r=new No(n,t),await e.set(this.settings.client_id,r)),await ao.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:r.keys,nonce:r.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n=!1,extraTokenParams:r={}}){const s=await this._tokenClient.exchangeCredentials({username:e,password:t,...r}),i=new Ro(new URLSearchParams);return Object.assign(i,s),await this._validator.validateCredentialsResponse(i,n),i}async useRefreshToken({state:e,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:s,extraTokenParams:i}){var o;const a=this._logger.create("useRefreshToken");let c,l;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);s={...s,DPoP:e}}try{l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:s,...i})}catch(o){if(!(o instanceof yo&&this.settings.dpop))throw o;s.DPoP=await this.getDpopProof(this.settings.dpop.store,o.nonce),l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:s,...i})}const d=new Ro(new URLSearchParams);return Object.assign(d,l),a.debug("validating response",d),await this._validator.validateRefreshResponse(d,{...e,scope:c}),d}async createSignoutRequest({state:e,id_token_hint:t,client_id:n,request_type:r,url_state:s,post_logout_redirect_uri:i=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),n||!i||t||(n=this.settings.client_id);const l=new Po({url:c,id_token_hint:t,client_id:n,post_logout_redirect_uri:i,state_data:e,extraQueryParams:o,request_type:r,url_state:s});await this.clearStaleState();const d=l.state;return d&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(d.id,d.toStorageString())),l}async readSignoutResponseState(e,t=!1){const n=this._logger.create("readSignoutResponseState"),r=new Uo(ho.readParams(e,this.settings.response_mode));if(!r.state){if(n.debug("No state in response"),r.error)throw n.warn("Response was error:",r.error),new go(r);return{state:void 0,response:r}}const s=await this.settings.stateStore[t?"remove":"get"](r.state);if(!s)throw n.throw(new Error("No matching state found in storage")),null;return{state:await Oo.fromStorageString(s),response:r}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:n,response:r}=await this.readSignoutResponseState(e,!0);return n?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(r,n)):t.debug("No state from storage; skipping response validation"),r}clearStaleState(){return this._logger.create("clearStaleState"),Oo.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})}},Do=class{constructor(e){this._userManager=e,this._logger=new ro("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const n=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,n.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,n.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){n.debug("initializing check session iframe");const r=this._userManager.settings.client_id,s=this._userManager.settings.checkSessionIntervalInSeconds,i=this._userManager.settings.stopCheckSessionOnError,o=new wo(this._callback,r,e,s,i);await o.load(),this._checkSessionIFrame=o,o.start(t)}else n.warn("no check session iframe found in the metadata")}catch(e){n.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 n=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(n=!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"),n?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)}}}},Lo=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-uo.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+uo.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 ro("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 ro.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},Wo="oidc-client",Fo=class{constructor(){this._abort=new co("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:n,keepOpen:r}=await new Promise(((n,r)=>{const s=s=>{var i;const o=s.data,a=null!=(i=e.scriptOrigin)?i:window.location.origin;if(s.origin===a&&(null==o?void 0:o.source)===Wo){try{const n=ho.readParams(o.url,e.response_mode).get("state");if(n||t.warn("no state found in response url"),s.source!==this._window&&n!==e.state)return}catch{this._dispose(),r(new Error("Invalid response from window"))}n(o)}};window.addEventListener("message",s,!1),this._disposeHandlers.add((()=>window.removeEventListener("message",s,!1))),this._disposeHandlers.add(this._abort.addHandler((e=>{this._dispose(),r(e)})))}));return t.debug("got response from window"),this._dispose(),r||this.close(),{url:n}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,n=!1,r=window.location.origin){e.postMessage({source:Wo,url:t,keepOpen:n},r)}},zo={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},Ho="_blank",Jo=60,Ko=2,Bo=class extends ko{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:n=e.post_logout_redirect_uri,popupWindowFeatures:r=zo,popupWindowTarget:s=Ho,redirectMethod:i="assign",redirectTarget:o="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:l,silent_redirect_uri:d=e.redirect_uri,silentRequestTimeoutInSeconds:u,automaticSilentRenew:h=!0,validateSubOnSilentRenew:p=!0,includeIdTokenInSilentRenew:g=!1,monitorSession:f=!1,monitorAnonymousSession:m=!1,checkSessionIntervalInSeconds:w=Ko,query_status_response_type:_="code",stopCheckSessionOnError:y=!0,revokeTokenTypes:v=["access_token","refresh_token"],revokeTokensOnSignout:b=!1,includeIdTokenInSilentSignout:S=!1,accessTokenExpiringNotificationTimeInSeconds:k=Jo,userStore:I}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=n,this.popupWindowFeatures=r,this.popupWindowTarget=s,this.redirectMethod=i,this.redirectTarget=o,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=d,this.silentRequestTimeoutInSeconds=u||l||10,this.automaticSilentRenew=h,this.validateSubOnSilentRenew=p,this.includeIdTokenInSilentRenew=g,this.monitorSession=f,this.monitorAnonymousSession=m,this.checkSessionIntervalInSeconds=w,this.stopCheckSessionOnError=y,this.query_status_response_type=_,this.revokeTokenTypes=v,this.revokeTokensOnSignout=b,this.includeIdTokenInSilentSignout=S,this.accessTokenExpiringNotificationTimeInSeconds=k,I)this.userStore=I;else{const e="undefined"!=typeof window?window.sessionStorage:new _o;this.userStore=new So({store:e})}}},Vo=class e extends Fo{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new ro("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 fo("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 n=e.target;null==(t=n.parentNode)||t.removeChild(n),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)}},Go=class{constructor(e){this._settings=e,this._logger=new ro("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new Vo({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),Vo.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},Yo=class extends Fo{constructor({popupWindowTarget:e=Ho,popupWindowFeatures:t={},popupSignal:n}){super(),this._logger=new ro("PopupWindow");const r=lo.center({...zo,...t});this._window=window.open(void 0,e,lo.serialize(r)),n&&n.addEventListener("abort",(()=>{var e;this._abort.raise(new Error(null!=(e=n.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 n=setInterval((()=>{this._window&&!this._window.closed||this._abort.raise(new Error("Popup closed by user"))}),500);return this._disposeHandlers.add((()=>clearInterval(n))),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){if(!window.opener)throw new Error("No window.opener. Can't complete notification.");return super._notifyParent(window.opener,e,t)}},Xo=class{constructor(e){this._settings=e,this._logger=new ro("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:n}){return new Yo({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:n})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),Yo.notifyOpener(e,t)}},Qo=class{constructor(e){this._settings=e,this._logger=new ro("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var n;this._logger.create("prepare");let r=window.self;"top"===t&&(r=null!=(n=window.top)?n:window.self);const s=r.location[e].bind(r.location);let i;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise(((e,t)=>{i=t}));return s(e.url),await t},close:()=>{this._logger.create("close"),null==i||i(new Error("Redirect aborted")),r.stop()}}}async callback(){}},Zo=class extends mo{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new ro("UserManagerEvents"),this._userLoaded=new co("User loaded"),this._userUnloaded=new co("User unloaded"),this._silentRenewError=new co("Silent renew error"),this._userSignedIn=new co("User signed in"),this._userSignedOut=new co("User signed out"),this._userSessionChanged=new co("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()}},ea=class{constructor(e){this._userManager=e,this._logger=new ro("SilentRenewService"),this._isStarted=!1,this._retryTimer=new uo("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 fo)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)}},ta=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}},na=Object.freeze({__proto__:null,AccessTokenEvents:mo,CheckSessionIFrame:wo,DPoPState:No,ErrorResponse:go,ErrorTimeout:fo,InMemoryWebStorage:_o,IndexedDbDPoPStore:class{constructor(){this._dbName="oidc",this._storeName="dpop"}async set(e,t){const n=await this.createStore(this._dbName,this._storeName);await n("readwrite",(n=>(n.put(t,e),this.promisifyRequest(n.transaction))))}async get(e){const t=await this.createStore(this._dbName,this._storeName);return await t("readonly",(t=>this.promisifyRequest(t.get(e))))}async remove(e){const t=await this.get(e),n=await this.createStore(this._dbName,this._storeName);return await n("readwrite",(t=>this.promisifyRequest(t.delete(e)))),t}async getAllKeys(){const e=await this.createStore(this._dbName,this._storeName);return await e("readonly",(e=>this.promisifyRequest(e.getAllKeys())))}promisifyRequest(e){return new Promise(((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)}))}async createStore(e,t){const n=indexedDB.open(e);n.onupgradeneeded=()=>n.result.createObjectStore(t);const r=await this.promisifyRequest(n);return async(e,n)=>{const s=r.transaction(t,e).objectStore(t);return await n(s)}}},get Log(){return no},Logger:ro,MetadataService:bo,OidcClient:qo,OidcClientSettingsStore:ko,SessionMonitor:Do,SigninResponse:Ro,SigninState:To,SignoutResponse:Uo,State:Oo,User:Lo,UserManager:class{constructor(e,t,n,r){this._logger=new ro("UserManager"),this.settings=new Bo(e),this._client=new qo(e),this._redirectNavigator=null!=t?t:new Qo(this.settings),this._popupNavigator=null!=n?n:new Xo(this.settings),this._iframeNavigator=null!=r?r:new Go(this.settings),this._events=new Zo(this.settings),this._silentRenewService=new ea(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new Do(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),n=await this._loadUser();return n?(t.info("user loaded"),await this._events.load(n,e),n):(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:n,...r}=e;let s;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const i=await this._redirectNavigator.prepare({redirectMethod:n});await this._signinStart({request_type:"si:r",dpopJkt:s,...r},i)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),n=await this._signinEnd(e);return n.profile&&n.profile.sub?t.info("success, signed in subject",n.profile.sub):t.info("no subject"),n}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:n=!1}){const r=this._logger.create("signinResourceOwnerCredential"),s=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n,extraTokenParams:this.settings.extraTokenParams});r.debug("got signin response");const i=await this._buildUser(s);return i.profile&&i.profile.sub?r.info("success, signed in subject",i.profile.sub):r.info("no subject"),i}async signinPopup(e={}){var t;const n=this._logger.create("signinPopup");let r;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(r=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:s,popupWindowTarget:i,popupSignal:o,...a}=e,c=this.settings.popup_redirect_uri;c||n.throw(new Error("No popup_redirect_uri configured"));const l=await this._popupNavigator.prepare({popupWindowFeatures:s,popupWindowTarget:i,popupSignal:o}),d=await this._signin({request_type:"si:p",redirect_uri:c,display:"popup",dpopJkt:r,...a},l);return d&&(d.profile&&d.profile.sub?n.info("success, signed in subject",d.profile.sub):n.info("no subject")),d}async signinPopupCallback(e=window.location.href,t=!1){const n=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),n.info("success")}async signinSilent(e={}){var t,n;const r=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:s,...i}=e;let o,a=await this._loadUser();if(null==a?void 0:a.refresh_token){r.debug("using refresh token");const e=new ta(a);return await this._useRefreshToken({state:e,redirect_uri:i.redirect_uri,resource:i.resource,extraTokenParams:i.extraTokenParams,timeoutInSeconds:s})}(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 l;c||r.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(r.debug("subject prior to silent renew:",a.profile.sub),l=a.profile.sub);const d=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});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,...i},d,l),a&&((null==(n=a.profile)?void 0:n.sub)?r.info("success, signed in subject",a.profile.sub):r.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),n=new Lo({...e.state,...t});return await this.storeUser(n),await this._events.load(n),n}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:n}=await this._client.readSignoutResponseState(e);if(n)switch(n.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:n,...r}=e,s=this.settings.silent_redirect_uri;s||t.throw(new Error("No silent_redirect_uri configured"));const i=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n}),a=await this._signinStart({request_type:"si:s",redirect_uri:s,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==i?void 0:i.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...r},o);try{const e={},n=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),n.session_state&&n.profile.sub?(t.info("success for subject",n.profile.sub),{session_state:n.session_state,sub:n.profile.sub}):(t.info("success, user not authenticated"),null)}catch(e){if(this.settings.monitorAnonymousSession&&e instanceof go)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,n){const r=await this._signinStart(e,t);return await this._signinEnd(r.url,n)}async _signinStart(e,t){const n=this._logger.create("_signinStart");try{const r=await this._client.createSigninRequest(e);return n.debug("got signin request"),await t.navigate({url:r.url,state:r.state.id,response_mode:r.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw n.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signinEnd(e,t){const n=this._logger.create("_signinEnd"),r=await this._client.processSigninResponse(e,{});n.debug("got signin response");return await this._buildUser(r,t)}async _buildUser(e,t){const n=this._logger.create("_buildUser"),r=new Lo(e);if(t){if(t!==r.profile.sub)throw n.debug("current user does not match user returned from signin. sub from signin:",r.profile.sub),new go({...e,error:"login_required"});n.debug("current user matches user returned from signin")}return await this.storeUser(r),n.debug("user stored"),await this._events.load(r),r}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:n,...r}=e,s=await this._redirectNavigator.prepare({redirectMethod:n});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...r},s),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),n=await this._signoutEnd(e);return t.info("success"),n}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:n,popupWindowTarget:r,popupSignal:s,...i}=e,o=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:n,popupWindowTarget:r,popupSignal:s});await this._signout({request_type:"so:p",post_logout_redirect_uri:o,state:null==o?void 0:{},...i},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const n=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),n.info("success")}async _signout(e,t){const n=await this._signoutStart(e,t);return await this._signoutEnd(n.url)}async _signoutStart(e={},t){var n;const r=this._logger.create("_signoutStart");try{const s=await this._loadUser();r.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(s);const i=e.id_token_hint||s&&s.id_token;i&&(r.debug("setting id_token_hint in signout request"),e.id_token_hint=i),await this.removeUser(),r.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return r.debug("got signout request"),await t.navigate({url:o.url,state:null==(n=o.state)?void 0:n.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),n=await this._client.processSignoutResponse(e);return t.debug("got signout response"),n}async signoutSilent(e={}){var t;const n=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:r,...s}=e,i=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:r});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:i,...s},a),n.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 n=this._logger.create("_revokeInternal");if(!e)return;const r=t.filter((t=>"string"==typeof e[t]));if(r.length){for(const t of r)await this._client.revokeToken(e[t],t),n.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),n.debug("user stored"),await this._events.load(e)}else n.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"),Lo.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const n=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,n)}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,n,r){var s,i;const o=await(null==(i=null==(s=this.settings.dpop)?void 0:s.store)?void 0:i.get(this.settings.client_id));if(o)return await ao.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:n,keyPair:o.keys,nonce:r})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const n=await ao.generateDPoPKeys();t=new No(n),await e.store.set(this.settings.client_id,t)}return await ao.generateDPoPJkt(t.keys)}},UserManagerSettingsStore:Bo,Version:"3.2.0",WebStorageStateStore:So});return Ni}();
|
|
7
|
+
function yr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)e[o]=n[o]}return e}var wr=function e(t,n){function o(e,o,r){if("undefined"!=typeof document){"number"==typeof(r=yr({},n,r)).expires&&(r.expires=new Date(Date.now()+864e5*r.expires)),r.expires&&(r.expires=r.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var s in r)r[s]&&(i+="; "+s,!0!==r[s]&&(i+="="+r[s].split(";")[0]));return document.cookie=e+"="+t.write(o,e)+i}}return Object.create({set:o,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],o={},r=0;r<n.length;r++){var i=n[r].split("="),s=i.slice(1).join("=");try{var a=decodeURIComponent(i[0]);if(o[a]=t.read(s,a),e===a)break}catch(e){}}return e?o[e]:o}},remove:function(e,t){o(e,"",yr({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,yr({},this.attributes,t))},withConverter:function(t){return e(yr({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});var br={default:"endpoint"},kr="Blocked by CSP",Sr="The endpoint parameter is not a valid URL",Ir="Failed to load the JS script of the agent",Or="9319";function jr(e,t){var n,o,r,i,s,a=[],c=(n=function(e){var t=function(e,t,n){if(n||2===arguments.length)for(var o,r=0,i=t.length;r<i;r++)!o&&r in t||(o||(o=Array.prototype.slice.call(t,0,r)),o[r]=t[r]);return e.concat(o||Array.prototype.slice.call(t))}([],e,!0);return{current:function(){return t[0]},postpone:function(){var e=t.shift();void 0!==e&&t.push(e)},exclude:function(){t.shift()}}}(e),i=0,o=function(){return Math.random()*Math.min(3e3,100*Math.pow(2,i++))},r=new Set,[n.current(),function(e,t){var i,s=t instanceof Error?t.message:"";if(s===kr||s===Sr)n.exclude(),i=0;else if(s===Or)n.exclude();else if(s===Ir){var a=Date.now()-e.getTime()<50,c=n.current();c&&a&&!r.has(c)&&(r.add(c),i=0),n.postpone()}else n.postpone();var l=n.current();return void 0===l?void 0:[l,null!=i?i:e.getTime()+o()-Date.now()]}]),l=c[0],u=c[1];if(void 0===l)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var d=function(e){var n=new Date,o=function(t){return a.push({url:e,startedAt:n,finishedAt:new Date,error:t})},r=t(e);return r.then((function(){return o()}),o),r.catch((function(e){if(null!=s||(s=e),a.length>=5)throw s;var t=u(n,e);if(!t)throw s;var o,r=t[0],i=t[1];return(o=i,new Promise((function(e){return setTimeout(e,o)}))).then((function(){return d(r)}))}))};return d(l).then((function(e){return[e,a]}))}var xr="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js",Er=xr;function Cr(n){var o;n.scriptUrlPattern;var r=n.token,i=n.apiKey,s=void 0===i?r:i,a=t(n,["scriptUrlPattern","token","apiKey"]),c=null!==(o=function(e,t){return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,t)?e[t]:void 0}(n,"scriptUrlPattern"))&&void 0!==o?o:xr,l=function(){var e=[],t=function(){e.push({time:new Date,state:document.visibilityState})},n=function(e,t,n,o){return e.addEventListener(t,n,o),function(){return e.removeEventListener(t,n,o)}}(document,"visibilitychange",t);return t(),[e,n]}(),u=l[0],d=l[1];return Promise.resolve().then((function(){if(!s||"string"!=typeof s)throw new Error("API key required");var e=function(e,t){return(Array.isArray(e)?e:[e]).map((function(e){return function(e,t){var n=encodeURIComponent;return e.replace(/<[^<>]+>/g,(function(e){return"<version>"===e?"3":"<apiKey>"===e?n(t):"<loaderVersion>"===e?n("3.11.6"):e}))}(String(e),t)}))}(c,s);return jr(e,_r)})).catch((function(e){throw d(),function(e){return e instanceof Error&&e.message===Or?new Error(Ir):e}(e)})).then((function(t){var n=t[0],o=t[1];return d(),n.load(e(e({},a),{ldi:{attempts:o,visibilityStates:u}}))}))}function _r(e){return function(e,t,n){var o,r=document,i="securitypolicyviolation",s=function(t){var n=new URL(e,location.href),r=t.blockedURI;r!==n.href&&r!==n.protocol.slice(0,-1)&&r!==n.origin||(o=t,a())};r.addEventListener(i,s);var a=function(){return r.removeEventListener(i,s)};return Promise.resolve().then(t).then((function(e){return a(),e}),(function(e){return new Promise((function(e){var t=new MessageChannel;t.port1.onmessage=function(){return e()},t.port2.postMessage(null)})).then((function(){if(a(),o)return n(o);throw e}))}))}(e,(function(){return function(e){return new Promise((function(t,n){if(function(e){if(URL.prototype)try{return new URL(e,location.href),!1}catch(e){if(e instanceof Error&&"TypeError"===e.name)return!0;throw e}}(e))throw new Error(Sr);var o=document.createElement("script"),r=function(){var e;return null===(e=o.parentNode)||void 0===e?void 0:e.removeChild(o)},i=document.head||document.getElementsByTagName("head")[0];o.onload=function(){r(),t()},o.onerror=function(){r(),n(new Error(Ir))},o.async=!0,o.src=e,i.appendChild(o)}))}(e)}),(function(){throw new Error(kr)})).then(Tr)}function Tr(){var e=window,t="__fpjs_p_l_b",n=e[t];if(function(e,t){var n,o=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==o?void 0:o.configurable)?delete e[t]:o&&!o.writable||(e[t]=void 0)}(e,t),"function"!=typeof(null==n?void 0:n.load))throw new Error(Or);return n}const Ar=e=>{try{return un(e).exp}catch(e){return null}},Ur=e=>{const{refresh_expire_in:t,refresh_token:n}=e;return t?Math.floor(Date.now()/1e3)+t:Ar(n)},Rr=e=>{const{expires_in:t,expires_at:n,access_token:o}=e;return n||(t?Math.floor(Date.now()/1e3)+t:o?Ar(o):void 0)},Pr=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,o)=>{var r;return n[o]=[].concat((null===(r=e.hooks)||void 0===r?void 0:r[o])||[]).concat((null==t?void 0:t[o])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e},$r=async e=>{if(!(null==e?void 0:e.ok))return{};const n=await(null==e?void 0:e.clone().json());return(e=>{const{access_token:n,id_token:o,refresh_token:r,refresh_expire_in:i}=e,s=t(e,["access_token","id_token","refresh_token","refresh_expire_in"]);return Object.assign({sessionJwt:e.sessionJwt||n,idToken:o,refreshJwt:e.refreshJwt||r,sessionExpiration:e.sessionExpiration||Rr(e),cookieExpiration:e.cookieExpiration||Ur(e)},s)})((null==n?void 0:n.authInfo)||n||{})},Mr=async e=>{const t=await $r(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)},Dr="undefined"!=typeof localStorage,Lr=(e,t)=>Dr&&(null===localStorage||void 0===localStorage?void 0:localStorage.setItem(e,t)),Nr=e=>Dr&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(e)),Wr=e=>Dr&&(null===localStorage||void 0===localStorage?void 0:localStorage.removeItem(e)),zr=(...e)=>{console.debug(...e)},Fr="3.2.0",qr="undefined"!=typeof window,Jr=Math.pow(2,31)-1,Kr=`https://descopecdn.com/npm/oidc-client-ts@${Fr}/dist/browser/oidc-client-ts.min.js`,Vr=`https://cdn.jsdelivr.net/npm/oidc-client-ts@${Fr}/dist/browser/oidc-client-ts.min.js`,Hr="DS",Br="DSR",Yr="DSI";function Xr(e=""){return Nr(`${e}${Br}`)||""}function Gr(e=""){return wr.get(Hr)||Nr(`${e}${Hr}`)||""}function Zr(e=""){return Nr(`${e}${Yr}`)||""}function Qr(e=""){Wr(`${e}${Br}`),Wr(`${e}${Hr}`),Wr(`${e}${Yr}`),wr.remove(Hr)}const ei=qr&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://api.descope.com",ti="vsid",ni="vrid",oi=(e=!1)=>{const t=localStorage.getItem("fp");if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},ri=async(e,t=ei)=>{try{if(oi())return;const n=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),o=new URL(t);o.pathname="/fXj8gt3x8VulJBna/x96Emn69oZwcd7I6";const r=new URL(t);r.pathname="/fXj8gt3x8VulJBna/w78aRZnnDZ3Aqw0I";const i=r.toString()+"?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>",s=Cr({apiKey:e,endpoint:[o.toString(),br],scriptUrlPattern:[i,Er]}),a=await s,{requestId:c}=await a.get({linkedId:n}),l=((e,t)=>({[ti]:e,[ni]:t}))(n,c);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};localStorage.setItem("fp",JSON.stringify(t))})(l)}catch(e){console.warn("Could not load fingerprint",e)}},ii=e=>{const t=oi(!0);return t&&e.body&&(e.body.fpData=t),e},si="dls_last_user_login_id",ai="dls_last_user_display_name",ci=()=>Nr(si),li=()=>Nr(ai),ui=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,r=ci(),i=li();return r&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=r,o.lastAuth.name=i),await e(...t)};function di(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}async function pi(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=yi(n.publicKey.challenge),n.publicKey.user.id=yi(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=yi(e.id)})),n}(e);return n=await navigator.credentials.create(t),JSON.stringify({id:n.id,rawId:wi(n.rawId),type:n.type,response:{attestationObject:wi(n.response.attestationObject),clientDataJSON:wi(n.response.clientDataJSON)}});var n}async function hi(e){const t=mi(e);return vi(await navigator.credentials.get(t))}async function fi(e,t){const n=mi(e);return n.signal=t.signal,n.mediation="conditional",vi(await navigator.credentials.get(n))}async function gi(e=!1){if(!qr)return Promise.resolve(!1);const t=!!(window.PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return t&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():t}function mi(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=yi(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=yi(e.id)})),n}function vi(e){return JSON.stringify({id:e.id,rawId:wi(e.rawId),type:e.type,response:{authenticatorData:wi(e.response.authenticatorData),clientDataJSON:wi(e.response.clientDataJSON),signature:wi(e.response.signature),userHandle:e.response.userHandle?wi(e.response.userHandle):void 0}})}function yi(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function wi(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var bi,ki=(bi=e=>({async signUp(t,n,o){const r=await e.webauthn.signUp.start(t,window.location.origin,n,o);if(!r.ok)return r;const i=await pi(r.data.options);return await e.webauthn.signUp.finish(r.data.transactionId,i)},async signIn(t,n){const o=await e.webauthn.signIn.start(t,window.location.origin,void 0,void 0,n);if(!o.ok)return o;const r=await hi(o.data.options);return await e.webauthn.signIn.finish(o.data.transactionId,r)},async signUpOrIn(t,n){var o;const r=await e.webauthn.signUpOrIn.start(t,window.location.origin,n);if(!r.ok)return r;if(null===(o=r.data)||void 0===o?void 0:o.create){const t=await pi(r.data.options);return await e.webauthn.signUp.finish(r.data.transactionId,t)}{const t=await hi(r.data.options);return await e.webauthn.signIn.finish(r.data.transactionId,t)}},async update(t,n,o){const r=await e.webauthn.update.start(t,window.location.origin,n,o);if(!r.ok)return r;const i=await pi(r.data.options);return await e.webauthn.update.finish(r.data.transactionId,i)},helpers:{create:pi,get:hi,isSupported:gi,conditional:fi}}),(...e)=>{const t=bi(...e);return Object.assign(t.signUp,e[0].webauthn.signUp),Object.assign(t.signIn,e[0].webauthn.signIn),Object.assign(t.signUpOrIn,e[0].webauthn.signUpOrIn),Object.assign(t.update,e[0].webauthn.update),t});const Si="/fedcm/config";async function Ii(e,t){var n,o,r;try{const r=await async function(e,t="google",n,o,r){const i=(()=>{if(window.crypto&&window.crypto.getRandomValues){const e=new Uint8Array(16);return window.crypto.getRandomValues(e),Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}return Math.random().toString(36).substring(2)})(),s=await async function(){return new Promise(((e,t)=>{if(window.google)return void e(window.google.accounts.id);let n=document.getElementById("google-gsi-client-script");n||(n=document.createElement("script"),document.head.appendChild(n),n.async=!0,n.defer=!0,n.id="google-gsi-client-script",n.src="https://accounts.google.com/gsi/client"),n.onload=function(){window.google?e(window.google.accounts.id):t("Failed to load Google GSI client script - not loaded properly")},n.onerror=function(){t("Failed to load Google GSI client script - failed to load")}}))}(),a=await e.oauth.getOneTapClientId(t);if(!a.ok)throw new Error("Failed to get OneTap client ID for provider "+t);const c=a.data.clientId;return new Promise((e=>{var a,l;const u=n=>{e({provider:t,nonce:i,credential:null==n?void 0:n.credential})};s.initialize(Object.assign(Object.assign({},n),{itp_support:null===(a=null==n?void 0:n.itp_support)||void 0===a||a,use_fedcm_for_prompt:null===(l=null==n?void 0:n.use_fedcm_for_prompt)||void 0===l||l,client_id:c,callback:u,nonce:i})),s.prompt((e=>{var t,n;if(r&&(null==e?void 0:e.isDismissedMoment())){const n=null===(t=e.getDismissedReason)||void 0===t?void 0:t.call(e);return null==r||r(n),void u()}if(o&&(null==e?void 0:e.isSkippedMoment())){const t=null===(n=e.getSkippedReason)||void 0===n?void 0:n.call(e);return null==o||o(t),void u()}}))}))}(e,t.provider,t.oneTapConfig,t.onSkipped,t.onDismissed);if(!r.credential)return null;if(null==t?void 0:t.onCodeReceived){const o=await e.oauth.verifyOneTapIDToken(r.provider,r.credential,r.nonce,null==t?void 0:t.loginOptions);if(!o.ok||!o.data)throw new Error("Failed to verify OneTap client ID for provider "+r.provider);null===(n=null==t?void 0:t.onCodeReceived)||void 0===n||n.call(t,o.data.code)}else{const n=await e.oauth.exchangeOneTapIDToken(r.provider,r.credential,r.nonce,null==t?void 0:t.loginOptions);if(!n.ok||!n.data)throw new Error("Failed to exchange OneTap client ID for provider "+r.provider);null===(o=null==t?void 0:t.onAuthenticated)||void 0===o||o.call(t,n.data)}}catch(e){null===(r=null==t?void 0:t.onFailed)||void 0===r||r.call(t,e)}}var Oi=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await gi(),o=Object.assign(Object.assign({location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:n},startOptionsVersion:1});return t[1]=o,e.flow.start(...t)}});let ji;const xi=(e,t)=>new Promise(((n,o)=>{if(!e.length)return o(new Error("No URLs provided to loadScriptWithFallback"));const r=t();if(r)return n(r);const i=e.shift(),s=document.createElement("script");s.src=i,s.id=(e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t).toString(16)})(i),s.onload=()=>{const e=t();if(e)return n(e);throw new Error("Could not get entry after loading script from URL")},s.addEventListener("error",(()=>{xi(e,t),s.setAttribute("data-error","true")})),document.body.appendChild(s)})),Ei=(e,t,n)=>{const o=async()=>{let o,r;return o&&r||({client:o,stateUserKey:r}=await(async(e,t,n)=>{ji||(ji=(async()=>{try{return require("oidc-client-ts")}catch(e){return xi([Kr,Vr],(()=>window.oidc))}})());const{OidcClient:o,WebStorageStateStore:r}=await ji;if(!o)throw new Error("oidc-client-ts is not installed. Please install it by running `npm install oidc-client-ts`");const i=t,s=(null==n?void 0:n.redirectUri)||window.location.href,a=(null==n?void 0:n.scope)||"openid email roles descope.custom_claims offline_access",c=`${i}_user`;let l=e.httpClient.buildUrl(t);(null==n?void 0:n.applicationId)&&(l=`${l}/${n.applicationId}`);const u={authority:l,client_id:t,redirect_uri:s,response_type:"code",scope:a,stateStore:new r({store:window.localStorage,prefix:i}),loadUserInfo:!0,fetchRequestCredentials:"same-origin"};return(null==n?void 0:n.redirectUri)&&(u.redirect_uri=n.redirectUri),(null==n?void 0:n.scope)&&(u.scope=n.scope),{client:new o(u),stateUserKey:c}})(e,t,n)),{client:o,stateUserKey:r}},r=async(t="")=>{var n;const{client:r,stateUserKey:i}=await o(),s=await r.processSigninResponse(t||window.location.href);var a;return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(s)))),window.localStorage.setItem(i,JSON.stringify({id_token:(a=s).id_token,session_state:a.session_state,profile:a.profile})),(()=>{const e=new URL(window.location.href);e.searchParams.delete("code"),e.searchParams.delete("state"),window.history.replaceState({},document.title,e.toString())})(),s};return{loginWithRedirect:async(e={},t=!1)=>{const{client:n}=await o(),r=await n.createSigninRequest(e),{url:i}=r;return t||(window.location.href=i),{ok:!0,data:r}},finishLogin:r,finishLoginIfNeed:async(e="")=>{if(window.location.search.includes("code")&&window.location.search.includes("state"))return await r(e)},refreshToken:async t=>{var n;const{client:r,stateUserKey:i}=await o(),s=(e=>{const t=window.localStorage.getItem(e);return t?JSON.parse(t):null})(i);if(!s)throw new Error("User not found in storage to refresh token");let a=t;if(!a){const t={};e.httpClient.hooks.beforeRequest(t),a=t.token}const c=await r.useRefreshToken({state:{refresh_token:a,session_state:s.session_state,profile:s.profile}});return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(c)))),c},logout:async(e,t=!1)=>{const{client:n,stateUserKey:r}=await o();e||(e={}),e.id_token_hint=e.id_token_hint||Zr(),e.post_logout_redirect_uri=e.post_logout_redirect_uri||window.location.href;const i=await n.createSignoutRequest(e),{url:s}=i;return window.localStorage.removeItem(r),t||window.location.replace(s),i}}},Ci=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>n=>{var{fpKey:o,fpLoad:r}=n,i=t(n,["fpKey","fpLoad"]);return qr?(o&&r&&ri(o).catch((()=>null)),e(Pr(i,{beforeRequest:ii}))):e(i)}),(e=>n=>{var{autoRefresh:o}=n,r=t(n,["autoRefresh"]);if(!o)return e(r);const{clearAllTimers:i,setTimer:s}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let a,c;qr&&document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&a&&new Date>a&&(zr("Expiration time passed, refreshing session"),l.refresh(Xr()||c))}));const l=e(Pr(r,{afterRequest:async(e,t)=>{const{sessionJwt:n,refreshJwt:o,sessionExpiration:r}=await $r(t);if(401===(null==t?void 0:t.status))zr("Received 401, canceling all timers"),i();else if(n||r){if(a=((e,t)=>{if(t)return new Date(1e3*t);zr("Could not extract expiration time from session token, trying to decode the token");try{const t=un(e);if(t.exp)return new Date(1e3*t.exp)}catch(e){return null}})(n,r),!a)return void zr("Could not extract expiration time from session token");c=o;const e=(e=>{let t=((n=e)?n.getTime()-(new Date).getTime():0)-2e4;var n;return t>Jr&&(zr(`Timeout is too large (${t}ms), setting it to ${Jr}ms`),t=Jr),t})(a);if(i(),e<=2e4)return void zr("Session is too close to expiration, not setting refresh timer");const t=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});zr(`Setting refresh timer for ${t}. (${e}ms)`),s((()=>{zr("Refreshing session due to timer"),l.refresh(Xr()||o)}),e)}}}));return ao(l,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const n=await e(...t);return zr("Clearing all timers"),i(),n}))}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.29.1"},t.baseHeaders)}))),(e=>t=>{const n=di(),o=di(),r=di(),i=e(Pr(t,{afterRequest:async(e,t)=>{if(401===(null==t?void 0:t.status))o.pub(null),r.pub(null),n.pub(null);else{const e=await Mr(t);e&&r.pub(e);const{sessionJwt:i,sessionExpiration:s}=await $r(t);i&&o.pub(i),(s||i)&&n.pub(s||42)}}})),s=ao(i,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const i=await e(...t);return o.pub(null),r.pub(null),n.pub(null),i}));return Object.assign(s,{onSessionTokenChange:o.sub,onUserChange:r.sub,onIsAuthenticatedChange:e=>n.sub((t=>{e(!!t)}))})}),(e=>n=>{var{storeLastAuthenticatedUser:o=!0,keepLastAuthenticatedUserAfterLogout:r=!1}=n,i=t(n,["storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout"]);if(!o)return Object.assign(e(i),{getLastUserLoginId:ci,getLastUserDisplayName:li});const s=e(Pr(i,{afterRequest:async(e,t)=>{var n;const o=await Mr(t),r=null===(n=null==o?void 0:o.loginIds)||void 0===n?void 0:n[0],i=null==o?void 0:o.name;r&&((e=>{Lr(si,e)})(r),(e=>{Lr(ai,e)})(i))}}));let a=ao(s,["flow.start"],ui);return a=ao(a,["logout","logoutAll"],(e=>t=>async(...n)=>{const o=await t(...n);return e||(Wr(si),Wr(ai)),o})(r)),Object.assign(a,{getLastUserLoginId:ci,getLastUserDisplayName:li})}),(e=>n=>{var{persistTokens:o,sessionTokenViaCookie:r,storagePrefix:i}=n,s=t(n,["persistTokens","sessionTokenViaCookie","storagePrefix"]);if(!o||!qr)return e(s);const a=e(Pr(s,{beforeRequest:(c=i,e=>Object.assign(e,{token:e.token||Xr(c)})),afterRequest:async(e,t)=>{const n=/^\/v\d+\/mgmt\//.test(e.path);401===(null==t?void 0:t.status)?n||Qr(i):((e={},t=!1,n="")=>{var o;const{sessionJwt:r,refreshJwt:i}=e;if(i&&Lr(`${n}${Br}`,i),r)if(t){const n=t.sameSite||"Strict",i=null===(o=t.secure)||void 0===o||o;!function(e,t,n){if(t){const{cookieDomain:o,cookiePath:r,cookieSameSite:i,cookieExpiration:s,cookieSecure:a}=n,c=new Date(1e3*s),l=function(e){const t=window.location.hostname.split("."),n=e.split(".");return t.slice(-n.length).join(".")===e}(o);wr.set(e,t,{path:r,domain:l?o:void 0,expires:c,sameSite:i,secure:a})}}(Hr,r,Object.assign(Object.assign({},e),{cookieSameSite:n,cookieSecure:i}))}else Lr(`${n}${Hr}`,r);e.idToken&&Lr(`${n}${Yr}`,e.idToken)})(await $r(t),r,i)}}));var c;const l=ao(a,["logout","logoutAll","oidc.logout"],(e=>t=>async(...n)=>{const o=await t(...n);return Qr(e),o})(i));return Object.assign(l,{getRefreshToken:()=>Xr(i),getSessionToken:()=>Gr(i),getIdToken:()=>Zr(i)})}))((e=>{const t=vr(e),n=Ei(t,e.projectId,e.oidcConfig);return Object.assign(Object.assign({},t),{refresh:async o=>{if(e.oidcConfig)try{return await n.refreshToken(o),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161001",errorDescription:e.toString()}})}const r=Gr(),i=Xr();return t.refresh(o,{dcs:r?"t":"f",dcr:i?"t":"f"})},logout:async o=>{if(e.oidcConfig)try{return await n.logout({id_token_hint:o}),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161000",errorDescription:e.toString()}})}return t.logout(o)},flow:Oi(t),webauthn:ki(t),fedcm:(o=t,r=e.projectId,{onetap:{requestExchangeCode(e){Ii(o,e)},requestAuthentication(e){Ii(o,e)}},oneTap(e,t,n,r,i){Ii(o,{provider:e,oneTapConfig:t,loginOptions:n,onSkipped:r,onDismissed:i})},async launch(e){var t;const n={identity:{context:e||"signin",providers:[{configURL:o.httpClient.buildUrl(r+Si),clientId:r}]}},i=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(n));return o.refresh(i.token)},isSupported:()=>qr&&"IdentityCredential"in window,async isLoggedIn(e){var t;const n=o.httpClient.buildUrl(r+Si);try{const o={identity:{context:e||"signin",providers:[{configURL:n,clientId:r}]}},i=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(o));return!!i&&!!i.token}catch(e){return!1}}}),oidc:n});var o,r})),_i={load:"/v1/mgmt/sso/idp/apps/load"},Ti=()=>n(void 0,void 0,void 0,(function*(){return new Promise((e=>{e({apps:[{id:"ssoapp1",name:"App 1",description:"This is the first SAML app",enabled:!0,appType:Qt.saml,logo:"logo1",samlSettings:{idpInitiatedUrl:""}},{id:"ssoapp2",name:"App 2",description:"This is the first OIDC app",enabled:!0,appType:Qt.oidc,logo:"logo2"},{id:"ssoapp3",name:"App 3",description:"This is the second SAML app",enabled:!0,appType:Qt.saml,logo:"logo3",samlSettings:{idpInitiatedUrl:""}}]})}))})),Ai=({httpClient:e,mock:t})=>({load:()=>n(void 0,void 0,void 0,(function*(){if(t)return Ti();const o=yield e.get(_i.load);return yield(e=>n(void 0,void 0,void 0,(function*(){const t=yield e.text(),n=JSON.parse(t);if(!e.ok){const t=`${n.errorDescription}${n.errorMessage?`: ${n.errorMessage}`:""}`;throw Error(t||`${e.status} ${e.statusText}`)}e.json=()=>Promise.resolve(n),e.text=()=>Promise.resolve(t)})))(o),o.json()}))}),Ui=a((e=>{var t,s,a,c;const l=i(S,b,g,Zt,I)(e);return c=class extends l{constructor(){super(...arguments),t.add(this),s.set(this,void 0)}get widgetId(){return this.getAttribute("widget-id")}get mock(){return this.getAttribute("mock")}get api(){return o(this,s,"f")||o(this,t,"m",a).call(this),o(this,s,"f")}init(){const e=Object.create(null,{init:{get:()=>super.init}});return n(this,void 0,void 0,(function*(){var n;yield null===(n=e.init)||void 0===n?void 0:n.call(this),this.observeAttributes(["project-id","base-url"],(()=>{o(this,s,"f")&&o(this,t,"m",a).call(this)}))}))}},s=new WeakMap,t=new WeakSet,a=function(){this.logger.debug("creating an sdk instance"),r(this,s,((e,t,n)=>{const o=Ci(Object.assign(Object.assign({},e),{persistTokens:!0,baseHeaders:{"x-descope-widget-type":"applications-portal-widget","x-descope-widget-id":n,"x-descope-widget-version":"0.3.12"}}));return{ssoApps:Ai({httpClient:o.httpClient,mock:t})}})({projectId:this.projectId,baseUrl:this.baseUrl,refreshCookieName:this.refreshCookieName},"true"===this.mock,this.widgetId),"f")},c})),Ri=a((e=>{const t=i(Gt({name:"widget",initialState:an,reducers:{},extraReducers:e=>{sn.reducer(e)},asyncActions:{loadSSOApps:sn.action}}),w,g,Ui)(e);return class extends t{constructor(...e){super(...e),this.state=an,this.subscribe((e=>{this.logger.debug("State update:",e),this.state=e}))}}})),Pi=a((e=>{const t=i(x,k({"widget-id":k.missingAttrValidator}))(e);return class extends t{get widgetId(){return this.getAttribute("widget-id")}fetchWidgetPage(e){return n(this,void 0,void 0,(function*(){return(yield this.fetchStaticResource(`applications-portal-widget/${this.widgetId}/${e}`,"text")).body}))}}})),$i=a((e=>{var t,r,a,c;return c=class extends(i(g,w,D,W,Pi,Ri)(e)){constructor(){super(...arguments),t.add(this)}onWidgetRootReady(){return n(this,void 0,void 0,(function*(){}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});return n(this,void 0,void 0,(function*(){var n;yield null===(n=e.init)||void 0===n?void 0:n.call(this);const[i]=yield Promise.all([o(this,t,"m",r).call(this),this.actions.loadSSOApps()]);o(this,t,"m",a).call(this,i),this.onWidgetRootReady()}))}},t=new WeakSet,r=function(){return n(this,void 0,void 0,(function*(){const e=s(yield this.fetchWidgetPage("root.html"));return yield this.loadDescopeUiComponents(e),e}))},a=function(e){this.contentRootElement.append(e.content.cloneNode(!0))},c})),Mi=a((e=>{var t,r,s;return s=class extends(i(Ri,g,$i)(e)){constructor(){super(...arguments),t.add(this)}onWidgetRootReady(){const e=Object.create(null,{onWidgetRootReady:{get:()=>super.onWidgetRootReady}});return n(this,void 0,void 0,(function*(){var n;yield null===(n=e.onWidgetRootReady)||void 0===n?void 0:n.call(this),o(this,t,"m",r).call(this,tn(this.state))}))}},t=new WeakSet,r=function(e){this.appsList=new H((()=>{var e;return null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector("descope-apps-list")}),{logger:this.logger}),this.appsList.data=e},s})),Di=a((e=>class extends(i(_,X,Mi)(e)){init(){const e=Object.create(null,{init:{get:()=>super.init}});return n(this,void 0,void 0,(function*(){var t;yield null===(t=e.init)||void 0===t?void 0:t.call(this)}))}})),Li=i((e=>class extends(Di(e)){}))(HTMLElement);customElements.define("descope-applications-portal-widget",Li);const Ni=(e,t,n,o={})=>{var r,i,s,a;return[Math.min(Math.max(t,("all"===o.left?e.offsetWidth:null!==(r=o.left)&&void 0!==r?r:0)-e.offsetWidth),window.innerWidth-("all"===o.right?e.offsetWidth:null!==(i=o.right)&&void 0!==i?i:0)),Math.min(Math.max(n,("all"===o.top?e.offsetHeight:null!==(s=o.top)&&void 0!==s?s:0)-e.offsetHeight),window.innerHeight-("all"===o.bottom?e.offsetHeight:null!==(a=o.bottom)&&void 0!==a?a:0))]};var Wi,zi,Fi,qi,Ji,Ki,Vi,Hi,Bi,Yi;const Xi=document.createElement("template");Xi.innerHTML=`\n<div style="top:32px; left:${window.innerWidth-300-32}px;" class="debugger">\n <div class="header">\n <span>Debugger messages</span>\n </div>\n <div class="content">\n <div class="empty-state">\n No errors detected 👀\n </div>\n </div>\n</div>\n`;class Gi extends HTMLElement{constructor(){var e,t,n;super(),Wi.add(this),zi.set(this,new h({messages:[]})),Fi.set(this,void 0),qi.set(this,void 0),Ji.set(this,void 0),Ki.set(this,{resize:o(this,Wi,"m",Yi).bind(this)}),this.attachShadow({mode:"open"}),null===(e=this.shadowRoot)||void 0===e||e.appendChild(Xi.content.cloneNode(!0));const i=new CSSStyleSheet;i.replaceSync('\n.debugger {\n all: initial;\n width: 300px;\n height: 200px;\n background-color: #FAFAFA;\n position: fixed;\n font-family: "Helvetica Neue", sans-serif;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 5px 10px;\n border-radius: 8px;\n overflow: hidden;\n border: 1px solid lightgrey;\n pointer-events: initial;\n display: flex;\n flex-direction: column;\n min-width: 200px;\n max-width: 600px;\n max-height: calc(100% - 64px);\n min-height: 200px;\n resize: both;\n }\n\n .header {\n padding: 8px 16px;\n display: flex;\n align-items: center;\n background-color: #EEEEEE;\n cursor: move;\n border-bottom: 1px solid #e0e0e0;\n }\n\n .content {\n font-size: 14px;\n flex-grow: 1;\n overflow: auto;\n }\n\n .msg {\n border-bottom: 1px solid lightgrey;\n padding: 8px 16px;\n display: flex;\n gap: 5px;\n background-color: #FAFAFA;\n }\n\n .msg.collapsible {\n cursor: pointer;\n }\n\n .empty-state {\n padding: 8px 16px;\n background-color: #FAFAFA;\n }\n\n\n .msg.collapsible:not(.collapsed) {\n background-color: #F5F5F5;\n }\n\n .msg_title {\n padding-bottom: 5px;\n display: flex;\n gap: 8px;\n font-weight: 500;\n }\n\n .msg svg {\n padding: 1px;\n flex-shrink: 0;\n margin-top: -2px;\n }\n\n .msg_content {\n overflow: hidden;\n flex-grow: 1;\n margin-right:5px;\n }\n\n .msg_desc {\n color: #646464;\n cursor: initial;\n word-wrap: break-word;\n }\n\n .msg.collapsed .msg_desc {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .msg.collapsible.collapsed .chevron {\n transform: rotate(-45deg) translateX(-2px);\n }\n\n .msg.collapsible .chevron {\n content: "";\n width:6px;\n height:6px;\n border-bottom: 2px solid grey;\n border-right: 2px solid grey;\n transform: rotate(45deg) translateX(-1px);\n margin: 5px;\n flex-shrink:0;\n }\n'),null!==(t=(n=this.shadowRoot).adoptedStyleSheets)&&void 0!==t||(n.adoptedStyleSheets=[]),this.shadowRoot.adoptedStyleSheets=[...this.shadowRoot.adoptedStyleSheets,i],r(this,Fi,this.shadowRoot.querySelector(".debugger"),"f"),r(this,qi,o(this,Fi,"f").querySelector(".content"),"f"),r(this,Ji,o(this,Fi,"f").querySelector(".header"),"f")}updateData(e){o(this,zi,"f").update((t=>({messages:t.messages.concat(e)})))}connectedCallback(){var e;((e,t,n)=>{let o=0,r=0,i=0,s=0;function a(t){t.preventDefault(),o=i-t.clientX,r=s-t.clientY,i=t.clientX,s=t.clientY;const[a,c]=Ni(e,e.offsetLeft-o,e.offsetTop-r,n);e.style.top=`${c}px`,e.style.left=`${a}px`}function c(){document.onmouseup=null,document.onmousemove=null}function l(e){e.preventDefault(),i=e.clientX,s=e.clientY,document.onmouseup=c,document.onmousemove=a}t?t.onmousedown=l:e.onmousedown=l})(o(this,Fi,"f"),o(this,Ji,"f"),{top:"all",bottom:100,left:100,right:100}),window.addEventListener("resize",o(this,Ki,"f").resize),(e=o(this,Fi,"f")).onmousemove=t=>{var n;const o=t.target;(o.w&&o.w!==o.offsetWidth||o.h&&o.h!==o.offsetHeight)&&(null===(n=e.onresize)||void 0===n||n.call(e,t)),o.w=o.offsetWidth,o.h=o.offsetHeight},o(this,Fi,"f").onresize=o(this,Wi,"m",Bi).bind(this),o(this,zi,"f").subscribe(o(this,Wi,"m",Vi).bind(this))}disconnectedCallback(){o(this,zi,"f").unsubscribeAll(),window.removeEventListener("resize",o(this,Ki,"f").resize)}}zi=new WeakMap,Fi=new WeakMap,qi=new WeakMap,Ji=new WeakMap,Ki=new WeakMap,Wi=new WeakSet,Vi=function(e){o(this,Wi,"m",Hi).call(this,e),o(this,Wi,"m",Bi).call(this)},Hi=function(e){o(this,qi,"f").innerHTML=e.messages.map((e=>`\n <div class="msg">\n <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M5.99984 13.167L8.99984 10.167L11.9998 13.167L13.1665 12.0003L10.1665 9.00033L13.1665 6.00033L11.9998 4.83366L8.99984 7.83366L5.99984 4.83366L4.83317 6.00033L7.83317 9.00033L4.83317 12.0003L5.99984 13.167ZM8.99984 17.3337C7.84706 17.3337 6.76373 17.1148 5.74984 16.677C4.73595 16.2398 3.854 15.6462 3.104 14.8962C2.354 14.1462 1.76039 13.2642 1.32317 12.2503C0.885393 11.2364 0.666504 10.1531 0.666504 9.00033C0.666504 7.84755 0.885393 6.76421 1.32317 5.75033C1.76039 4.73644 2.354 3.85449 3.104 3.10449C3.854 2.35449 4.73595 1.7606 5.74984 1.32283C6.76373 0.885603 7.84706 0.666992 8.99984 0.666992C10.1526 0.666992 11.2359 0.885603 12.2498 1.32283C13.2637 1.7606 14.1457 2.35449 14.8957 3.10449C15.6457 3.85449 16.2393 4.73644 16.6765 5.75033C17.1143 6.76421 17.3332 7.84755 17.3332 9.00033C17.3332 10.1531 17.1143 11.2364 16.6765 12.2503C16.2393 13.2642 15.6457 14.1462 14.8957 14.8962C14.1457 15.6462 13.2637 16.2398 12.2498 16.677C11.2359 17.1148 10.1526 17.3337 8.99984 17.3337ZM8.99984 15.667C10.8609 15.667 12.4373 15.0212 13.729 13.7295C15.0207 12.4378 15.6665 10.8614 15.6665 9.00033C15.6665 7.13921 15.0207 5.56283 13.729 4.27116C12.4373 2.97949 10.8609 2.33366 8.99984 2.33366C7.13873 2.33366 5.56234 2.97949 4.27067 4.27116C2.979 5.56283 2.33317 7.13921 2.33317 9.00033C2.33317 10.8614 2.979 12.4378 4.27067 13.7295C5.56234 15.0212 7.13873 15.667 8.99984 15.667Z" fill="#ED404A"/>\n</svg>\n\n <div class="msg_content">\n <div class="msg_title">\n ${e.title}\n </div>\n <div class="msg_desc">\n ${e.description||""}\n </div>\n </div>\n <div class="chevron"></div>\n </div>\n `)).join("")},Bi=function(){o(this,qi,"f").querySelectorAll(".msg").forEach((e=>{const t=e,n=t.querySelector(".msg_desc"),o=n.scrollWidth>n.clientWidth,r=n.clientHeight>20;o||r?(t.classList.add("collapsible"),t.onclick=e=>{e.target.classList.contains("msg_desc")||t.classList.toggle("collapsed")}):(t.classList.remove("collapsible"),t.onclick=null)}))},Yi=function(){const[e,t]=Ni(o(this,Fi,"f"),Number.parseInt(o(this,Fi,"f").style.left,10),Number.parseInt(o(this,Fi,"f").style.top,10),{top:"all",bottom:100,left:100,right:100});o(this,Fi,"f").style.top=`${t}px`,o(this,Fi,"f").style.left=`${e}px`},customElements.get("descope-debugger")||customElements.define("descope-debugger",Gi);var Zi=Object.freeze({__proto__:null,default:Gi});return Li}();
|
|
8
8
|
//# sourceMappingURL=index.js.map
|