@descope/web-component 3.53.1 → 3.53.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as r}from"@descope/sdk-helpers";import{staticResourcesMixin as o}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as s}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{createSdk as u}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as a}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as g,fetchContent as f}from"../helpers/helpers.js";import p from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as m}from"../helpers/storage.js";import{transformFlowInputFormData as b,extractNestedAttribute as v}from"../helpers/flowInputs.js";import{formMountMixin as w}from"../mixins/formMountMixin.js";import{CONFIG_FILENAME as k,PREV_VER_ASSETS_FOLDER as C}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as y}from"../constants/general.js";var A,x,I,j,E,L,S,U,M,O,W,D,P,N,F,K,R,T,B,H,J,V;const q=r(s,o,w,n)(HTMLElement);class z extends q{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(r){super(),A.add(this),I.set(this,!1),j.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,A,"m",V).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},E.set(this,new p),L.set(this,new p),S.set(this,{}),this.getComponentsContext=()=>t(this,S,"f"),this.nextRequestStatus=new p({isLoading:!1}),U.set(this,void 0),M.set(this,{popstate:t(this,A,"m",N).bind(this),componentsContext:t(this,A,"m",B).bind(this)}),O.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,O,r,"f"),t(this,A,"m",D).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get tenantId(){return this.getAttribute("tenant")||void 0}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return b(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return v(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t(this,j,"f")}set customStorage(t){if(t&&"function"!=typeof t.getItem)throw new Error("Custom storage must have a getItem method");if(t&&"function"!=typeof t.setItem)throw new Error("Custom storage must have a setItem method");if(t&&"function"!=typeof t.removeItem)throw new Error("Custom storage must have a removeItem method");i(this,j,t,"f"),m(t)}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),r=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=r.version)&&void 0!==e||(r.version=0),r}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,r;const o=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),s=a.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||o||s)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const u=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===u.length)return void u[0].click();const l=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const r=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=r.init)||void 0===e?void 0:e.call(this),t(this,L,"f").subscribe(t(this,A,"m",J).bind(this)),t(this,L,"f").update({isDebug:this.debug}),t(this,A,"m",P).call(this),yield t(this,A,"m",R).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const o=yield this.getConfig();if("isMissingConfig"in o&&o.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:s,stepId:n,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:g,redirectAuthCodeChallenge:f,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,M,"f").popstate),window.addEventListener("components-context",t(this,M,"f").componentsContext),t(this,E,"f").subscribe(t(this,A,"m",K).bind(this)),t(this,E,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:s,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:g,redirectAuthCodeChallenge:f,redirectAuthInitiator:p},m)),i(this,I,!0,"f")}))}disconnectedCallback(){t(this,E,"f").unsubscribeAll(),t(this,L,"f").unsubscribeAll(),t(this,A,"m",H).call(this),window.removeEventListener("popstate",t(this,M,"f").popstate),window.removeEventListener("components-context",t(this,M,"f").componentsContext)}attributeChangedCallback(e,i,r){if(this.shadowRoot.isConnected&&t(this,I,"f")&&i!==r&&x.observedAttributes.includes(e)){t(this,A,"m",P).call(this);const o=null===i;t(this,E,"f").update((({stepId:t,executionId:i})=>{let s=t,n=i;return o||(n=null,s=null,d()),{[c(e)]:r,stepId:s,executionId:n}})),t(this,L,"f").update({isDebug:this.debug})}}}x=z,I=new WeakMap,j=new WeakMap,E=new WeakMap,L=new WeakMap,S=new WeakMap,U=new WeakMap,M=new WeakMap,O=new WeakMap,A=new WeakSet,W=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},D=function(){t(this,A,"m",W).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},P=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id","outbound-app-id","outbound-app-scopes"];x.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},N=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,E,"f").update({stepId:e,executionId:i})},F=function(i,r){u&&"function"==typeof u||this.logger.error("SDK was not loaded properly",u,JSON.stringify(u));const o=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},x.sdkConfigOverrides),{projectId:i,baseUrl:r});t(this,j,"f")&&(o.customStorage=t(this,j,"f")),this.sdk=u(o),["start","next"].forEach((t=>{const i=this.sdk.flow[t];this.sdk.flow[t]=(...t)=>e(this,void 0,void 0,(function*(){try{return yield i(...t)}catch(t){return{error:{errorCode:y,errorDescription:t.toString()}}}}))}))},K=function(i,r,o){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:r}=i;if(o("projectId")||o("baseUrl")){if(!e)return;t(this,A,"m",F).call(this,e,r)}t(this,O,"f").call(this,i)}))},R=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,A,"m",T).call(this))}))},T=function(){return e(this,void 0,void 0,(function*(){const t=g({projectId:this.projectId,filename:k,assetsFolder:C,baseUrl:this.baseStaticUrl});try{return yield f(t,"json"),!0}catch(t){return!1}}))},B=function(e){i(this,S,Object.assign(Object.assign({},t(this,S,"f")),e.detail),"f")},H=function(){var e;null===(e=t(this,U,"f"))||void 0===e||e.remove(),i(this,U,null,"f")},J=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,U,document.createElement("descope-debugger"),"f"),Object.assign(t(this,U,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield import("../debugger-wc.js"),document.body.appendChild(t(this,U,"f"))):t(this,A,"m",H).call(this)}))},V=function(e,i){var r;e&&this.debug&&(null===(r=t(this,U,"f"))||void 0===r||r.updateData({title:e,description:i}))},z.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.53.1"}};export{z as default};
1
+ import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as r}from"@descope/sdk-helpers";import{staticResourcesMixin as o}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as s}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{createSdk as u}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as a}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as g,fetchContent as f}from"../helpers/helpers.js";import p from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as m}from"../helpers/storage.js";import{transformFlowInputFormData as b,extractNestedAttribute as v}from"../helpers/flowInputs.js";import{formMountMixin as w}from"../mixins/formMountMixin.js";import{CONFIG_FILENAME as k,PREV_VER_ASSETS_FOLDER as C}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as y}from"../constants/general.js";var A,x,I,j,E,L,S,U,M,O,W,D,P,N,F,K,R,T,B,H,J,V;const q=r(s,o,w,n)(HTMLElement);class z extends q{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(r){super(),A.add(this),I.set(this,!1),j.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,A,"m",V).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},E.set(this,new p),L.set(this,new p),S.set(this,{}),this.getComponentsContext=()=>t(this,S,"f"),this.nextRequestStatus=new p({isLoading:!1}),U.set(this,void 0),M.set(this,{popstate:t(this,A,"m",N).bind(this),componentsContext:t(this,A,"m",B).bind(this)}),O.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,O,r,"f"),t(this,A,"m",D).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get tenantId(){return this.getAttribute("tenant")||void 0}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return b(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return v(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t(this,j,"f")}set customStorage(t){if(t&&"function"!=typeof t.getItem)throw new Error("Custom storage must have a getItem method");if(t&&"function"!=typeof t.setItem)throw new Error("Custom storage must have a setItem method");if(t&&"function"!=typeof t.removeItem)throw new Error("Custom storage must have a removeItem method");i(this,j,t,"f"),m(t)}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),r=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=r.version)&&void 0!==e||(r.version=0),r}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,r;const o=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),s=a.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||o||s)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const u=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===u.length)return void u[0].click();const l=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const r=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=r.init)||void 0===e?void 0:e.call(this),t(this,L,"f").subscribe(t(this,A,"m",J).bind(this)),t(this,L,"f").update({isDebug:this.debug}),t(this,A,"m",P).call(this),yield t(this,A,"m",R).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const o=yield this.getConfig();if("isMissingConfig"in o&&o.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:s,stepId:n,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:g,redirectAuthCodeChallenge:f,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,M,"f").popstate),window.addEventListener("components-context",t(this,M,"f").componentsContext),t(this,E,"f").subscribe(t(this,A,"m",K).bind(this)),t(this,E,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:s,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:g,redirectAuthCodeChallenge:f,redirectAuthInitiator:p},m)),i(this,I,!0,"f")}))}disconnectedCallback(){t(this,E,"f").unsubscribeAll(),t(this,L,"f").unsubscribeAll(),t(this,A,"m",H).call(this),window.removeEventListener("popstate",t(this,M,"f").popstate),window.removeEventListener("components-context",t(this,M,"f").componentsContext)}attributeChangedCallback(e,i,r){if(this.shadowRoot.isConnected&&t(this,I,"f")&&i!==r&&x.observedAttributes.includes(e)){t(this,A,"m",P).call(this);const o=null===i;t(this,E,"f").update((({stepId:t,executionId:i})=>{let s=t,n=i;return o||(n=null,s=null,d()),{[c(e)]:r,stepId:s,executionId:n}})),t(this,L,"f").update({isDebug:this.debug})}}}x=z,I=new WeakMap,j=new WeakMap,E=new WeakMap,L=new WeakMap,S=new WeakMap,U=new WeakMap,M=new WeakMap,O=new WeakMap,A=new WeakSet,W=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},D=function(){t(this,A,"m",W).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},P=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id","outbound-app-id","outbound-app-scopes"];x.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},N=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,E,"f").update({stepId:e,executionId:i})},F=function(i,r){u&&"function"==typeof u||this.logger.error("SDK was not loaded properly",u,JSON.stringify(u));const o=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},x.sdkConfigOverrides),{projectId:i,baseUrl:r});t(this,j,"f")&&(o.customStorage=t(this,j,"f")),this.sdk=u(o),["start","next"].forEach((t=>{const i=this.sdk.flow[t];this.sdk.flow[t]=(...t)=>e(this,void 0,void 0,(function*(){try{return yield i(...t)}catch(t){return{error:{errorCode:y,errorDescription:t.toString()}}}}))}))},K=function(i,r,o){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:r}=i;if(o("projectId")||o("baseUrl")){if(!e)return;t(this,A,"m",F).call(this,e,r)}t(this,O,"f").call(this,i)}))},R=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,A,"m",T).call(this))}))},T=function(){return e(this,void 0,void 0,(function*(){const t=g({projectId:this.projectId,filename:k,assetsFolder:C,baseUrl:this.baseStaticUrl});try{return yield f(t,"json"),!0}catch(t){return!1}}))},B=function(e){i(this,S,Object.assign(Object.assign({},t(this,S,"f")),e.detail),"f")},H=function(){var e;null===(e=t(this,U,"f"))||void 0===e||e.remove(),i(this,U,null,"f")},J=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,U,document.createElement("descope-debugger"),"f"),Object.assign(t(this,U,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield import("../debugger-wc.js"),document.body.appendChild(t(this,U,"f"))):t(this,A,"m",H).call(this)}))},V=function(e,i){var r;e&&this.debug&&(null===(r=t(this,U,"f"))||void 0===r||r.updateData({title:e,description:i}))},z.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.53.2"}};export{z as default};
2
2
  //# sourceMappingURL=BaseDescopeWc.js.map
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{ensureFingerprintIds as o,clearFingerprintData as n}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as r,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as l,URL_TOKEN_PARAM_NAME as d,URL_RUN_IDS_PARAM_NAME as c,SDK_SCRIPTS_LOAD_TIMEOUT as h,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as p,ELEMENT_TYPE_ATTRIBUTE as u,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as g}from"../constants/index.js";import{timeoutPromise as m,withMemCache as v,leadingDebounce as f,getUserLocale as b,showFirstScreenOnExecutionInit as w,injectSamlIdpForm as S,openCenteredPopup as y,getAnimationDirection as C,handleAutoFocus as I,transformStepStateForCustomScreen as k,getElementDescopeAttributes as R,getScriptResultPath as O,submitForm as W,transformScreenInputs as x,handleReportValidityOnBlur as E,getFirstNonEmptyValue as A,clearPreviousExternalInputs as j}from"../helpers/helpers.js";import T from"../helpers/state.js";import{disableWebauthnButtons as L,updateTemplateFromScreenState as U,setPhoneAutoDetectDefaultCode as P,setTOTPVariable as $,setNOTPVariable as N,setCssVars as M,updateScreenFromScreenState as q,replaceElementMessage as F}from"../helpers/templates.js";import{isConditionalLoginSupported as V}from"../helpers/webauthn.js";import{getABTestingKey as D}from"../helpers/abTestingKey.js";import{calculateConditions as B,calculateCondition as K}from"../helpers/conditions.js";import{setLastAuth as H,getLastAuth as _}from"../helpers/lastAuth.js";import G from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as J,FETCH_ERROR_RESPONSE_ERROR_CODE as z,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as Q,FLOW_TIMED_OUT_ERROR_CODE as X,POLLING_STATUS_NOT_FOUND_ERROR_CODE as Y}from"../constants/general.js";var Z,ee,te,ie,se,oe,ne,re,ae,le,de,ce,he,pe,ue,ge,me,ve,fe,be,we,Se,ye,Ce,Ie,ke,Re,Oe,We,xe,Ee,Ae,je,Te,Le,Ue,Pe;class $e extends G{static set sdkConfigOverrides(e){G.sdkConfigOverrides=e}static get sdkConfigOverrides(){return G.sdkConfigOverrides}constructor(){const s=new T({deferredRedirect:!1});super(s.update.bind(s)),Z.add(this),this.stepState=new T({}),ee.set(this,void 0),te.set(this,null),ie.set(this,null),se.set(this,{visibilitychange:e(this,Z,"m",oe).bind(this)}),this.bridgeVersion=2,this.nativeCallbacks={},pe.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},ge.set(this,(t=>{const i=()=>{this.contentRootElement.classList.toggle("hidden",t),this.slotElement.classList.toggle("hidden",!t),t&&(this.contentRootElement.innerHTML="")};t&&this.contentRootElement.hasChildNodes()?e(this,Z,"m",me).call(this,i):i()})),ve.set(this,((s,o,n,l,d=!1)=>{const c=[X,Y];if(this.flowState.current.action===r.poll){this.logger.debug("polling - Scheduling polling request");const r=Date.now(),h=d?500:2e3;t(this,ee,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const p=this.sdk.flow.next(s,o,a.polling,n,l,{}),u=document.hidden&&!d&&Date.now()-r>h+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield m(e,p)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,ve,"f").call(this,s,o,n,l,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===J)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,ve,"f").call(this,s,o,n,l);this.logger.debug("polling - Got a response"),(null==g?void 0:g.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(g.error,null,4)),(null===(i=null==g?void 0:g.error)||void 0===i?void 0:i.errorCode)&&c.includes(g.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):e(this,ve,"f").call(this,s,o,n,l),e(this,be,"f").call(this,g)}))),h),"f")}})),fe.set(this,(()=>{clearTimeout(e(this,ee,"f")),t(this,ee,null,"f")})),be.set(this,(i=>{var s,o,n,a,l,d,c,h,p,u,g,m,v;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,r=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,Z,"m",Ue).call(this,"error",(null==i?void 0:i.error)||{errorCode:z,errorDescription:r,errorMessage:t}),this.loggerWrapper.error((null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorDescription)||t,(null===(l=null==i?void 0:i.error)||void 0===l?void 0:l.errorMessage)||r);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==Q&&c!==X||!this.isRestartOnError||e(this,Z,"m",he).call(this))}null===(h=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===h||h.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(p=i.data)||void 0===p?void 0:p.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(m=i.data)||void 0===m?void 0:m.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:C}=i.data;if(y!==r.poll&&e(this,fe,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&H(S);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),void e(this,Z,"m",Ue).call(this,"success",t)}this.storeLastAuthenticatedUser&&H(S,!0),C&&window.open(C,"_blank");const{executionId:I,stepId:k,stepName:R,screen:O,redirect:W,webauthn:x,error:E,samlIdpResponse:A,nativeResponse:j}=i.data,T=Date.now();y!==r.poll?(this.loggerWrapper.info(`Step "${R||`#${k}`}" is ${b}`,"",{screen:O,status:b,stepId:k,stepName:R,action:y,error:E}),(null===(v=O.state)||void 0===v?void 0:v.clientScripts)&&t(this,ie,this.loadSdkScripts(O.state.clientScripts),"f"),this.flowState.update({stepId:k,stepName:R,executionId:I,action:y,redirectTo:null==W?void 0:W.url,redirectIsPopup:null==W?void 0:W.isPopup,screenId:null==O?void 0:O.id,screenState:null==O?void 0:O.state,webauthnTransactionId:null==x?void 0:x.transactionId,webauthnOptions:null==x?void 0:x.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,nativeResponseType:null==j?void 0:j.type,nativePayload:null==j?void 0:j.payload,reqTimestamp:T})):this.flowState.update({action:y,reqTimestamp:T})})),we.set(this,v((()=>i(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),Re.set(this,null),Ae.set(this,f(((t,s)=>i(this,void 0,void 0,(function*(){var i;if("true"===t.getAttribute("formnovalidate")||e(this,Z,"m",Ie).call(this)){const o=null==t?void 0:t.getAttribute("id");e(this,Z,"m",Oe).call(this,t);const n=yield e(this,Z,"m",ke).call(this),r=R(t);this.nextRequestStatus.update({isLoading:!0});const a=Object.assign(Object.assign(Object.assign({},r),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(o,a),this.nextRequestStatus.update({isLoading:!1}),e(this,Z,"m",We).call(this,n)}}))))),this.flowState=s}nativeResume(t,i){var s,o,n,r,a;const h=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let{exchangeCode:e}=h;if(!e){e=null===(s=new URL(h.url).searchParams)||void 0===s?void 0:s.get(l)}null===(n=(o=this.nativeCallbacks).complete)||void 0===n||n.call(o,{exchangeCode:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(h.url),i=t.searchParams.get(d),s=t.searchParams.get(c).split("_").pop();e(this,fe,"f").call(this),this.flowState.update({token:i,stepId:s,action:void 0})}else if("beforeScreen"===t){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=h;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=h,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(r=this.nativeCallbacks).complete)||void 0===a||a.call(r,h)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[O(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=Promise.all(null==e?void 0:e.map((e=>i(this,void 0,void 0,(function*(){var i,s;const o=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(o){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=o;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}yield this.injectNpmLib("@descope/flow-scripts","1.0.13",`dist/${e.id}.js`);const n=null===(s=globalThis.descope)||void 0===s?void 0:s[e.id];return new Promise(((i,s)=>{try{const s=n(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i),this.loggerWrapper);if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t),this.nextRequestStatus.subscribe((()=>{var t;this.loggerWrapper.debug("Unloading script",e.id),null===(t=s.stop)||void 0===t||t.call(s)}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),h)}));return Promise.race([s,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){if(!window.descopeBridge)return this._init();this.lazyInit=this._init}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,Z,"m",de).call(this),window.addEventListener("visibilitychange",e(this,se,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var i;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,fe,"f").call(this),null===(i=e(this,te,"f"))||void 0===i||i.abort(),t(this,te,null,"f"),window.removeEventListener("visibilitychange",e(this,se,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=b(e),o=yield this.getTargetLocales();return o.includes(s.locale)?i=`${t}-${s.locale}.html`:o.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(l,d,c){return i(this,void 0,void 0,(function*(){var h,p;const{projectId:u,flowId:g,tenant:m,stepId:v,executionId:f,action:I,screenId:k,screenState:R,redirectTo:O,redirectIsPopup:E,redirectUrl:A,token:j,code:T,isPopup:L,exchangeError:U,webauthnTransactionId:P,webauthnOptions:$,redirectAuthCodeChallenge:N,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:F,locale:V,samlIdpResponseUrl:H,samlIdpResponseSamlResponse:G,samlIdpResponseRelayState:J,nativeResponseType:z,nativePayload:Q,reqTimestamp:X}=l,Y=s(l,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","nativeResponseType","nativePayload","reqTimestamp"]);let ee,se,oe;const ne=D(),{outboundAppId:re}=this,{outboundAppScopes:le}=this,de=this.sdk.getLastUserLoginId(),ce=yield this.getFlowConfig(),he=yield this.getProjectConfig(),pe=Object.entries(he.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),ge=M&&N?{callbackUrl:M,codeChallenge:N,backupCallbackUri:q}:void 0,me=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;let fe={};if(!f){const i=[...ce.clientScripts||[],...ce.sdkScripts||[]];if(ce.conditions){let e=[];({startScreenId:ee,conditionInteractionId:oe,startScreenName:se,clientScripts:e,componentsConfig:fe}=B({loginId:de,code:T,token:j,abTestingKey:ne,lastAuth:_(de)},ce.conditions)),i.push(...e||[])}else ce.condition?({startScreenId:ee,conditionInteractionId:oe}=K(ce.condition,{loginId:de,code:T,token:j,abTestingKey:ne,lastAuth:_(de)})):(se=ce.startScreenName,ee=ce.startScreenId);if(t(this,ie,this.loadSdkScripts(i),"f"),ce.fingerprintEnabled&&ce.fingerprintKey?yield o(ce.fingerprintKey,this.baseUrl):n(),!w(ee,Y)){const t=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:ge},Y),{client:this.client}),A&&{redirectUrl:A}),{lastAuth:_(de),abTestingKey:ne,locale:b(V).locale,nativeOptions:me,outboundAppId:re,outboundAppScopes:le}),oe,"",he.componentsVersion,pe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),T?{exchangeCode:T,idpInitiated:!0}:{}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j?{token:j}:{}),Y.oidcLoginHint?{externalId:Y.oidcLoginHint}:{}));return e(this,be,"f").call(this,t),void("completed"!==(null===(h=null==t?void 0:t.data)||void 0===h?void 0:h.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:L,code:T,exchangeError:U,isCodeChanged:c("code"),isExchangeErrorChanged:c("exchangeError")})),L&&(c("code")&&T||c("exchangeError")&&U))return void e(this,Z,"m",Pe).call(this,f,T,U);if(f&&(c("token")&&j||c("code")&&T||c("exchangeError")&&U)){const t=yield this.sdk.flow.next(f,v,a.submit,ce.version,he.componentsVersion,{token:j,exchangeCode:T,exchangeError:U});return e(this,be,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(I===r.loadForm&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>c(e)))){if(!H||!G)return void this.loggerWrapper.error("Did not get saml idp params data to load");S(H,G,J||"",W)}if(I===r.redirect&&(c("redirectTo")||c("deferredRedirect"))){if(!O)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===O)return;if("android"===F&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${E}`),E){this.loggerWrapper.debug("Opening redirect in popup");const t=y(O,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));const s=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const t=i?this.popupOrigin:window.location.origin;if(e.origin!==t)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${t}"`);const{action:s,data:o}=e.data||{};"code"===s&&this.flowState.update({code:o.code,exchangeError:o.exchangeError})};let o;this.loggerWrapper.debug("Starting popup closed detection");const n=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(n),e(this,Z,"m",Ue).call(this,"popupclosed",{}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==o||o())}),1e3);if(i)window.addEventListener("message",s),o=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",s)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(f);e.onmessage=s,o=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(O),this.flowState.update({redirectTo:"no-op"}),e(this,Z,"m",Ue).call(this,"popupclosed",{});return}if(I===r.webauthnCreate||I===r.webauthnGet){if(!P||!$)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s;null===(p=e(this,te,"f"))||void 0===p||p.abort(),t(this,te,null,"f");try{i=I===r.webauthnCreate?yield this.sdk.webauthn.helpers.create($):yield this.sdk.webauthn.helpers.get($)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),s=e.name}const o=yield this.sdk.flow.next(f,v,a.submit,ce.version,he.componentsVersion,{transactionId:P,response:i,failure:s});e(this,be,"f").call(this,o)}if(I===r.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,v,a.submit,ce.version,he.componentsVersion,t);e(this,be,"f").call(this,i)})),void e(this,Z,"m",ae).call(this,z,Q);if(c("action")&&e(this,ve,"f").call(this,f,v,ce.version,he.componentsVersion),!k&&!ee)return void this.loggerWrapper.warn("No screen was found to show");const we=ee||k,Se=yield this.getHtmlFilenameWithLocale(V,we),{oidcLoginHint:ye,oidcPrompt:Ce,oidcErrorRedirectUri:Ie,oidcResource:ke,samlIdpUsername:Re}=Y,Oe={direction:C(v,d.stepId),screenState:Object.assign(Object.assign({},R),{form:Object.assign(Object.assign({},this.formConfigValues),null==R?void 0:R.form),lastAuth:{loginId:de,name:this.sdk.getLastUserDisplayName()||de},componentsConfig:Object.assign(Object.assign(Object.assign({},ce.componentsConfig),fe),null==R?void 0:R.componentsConfig)}),htmlFilename:`${we}.html`,htmlLocaleFilename:Se,screenId:we,stepName:l.stepName||se,samlIdpUsername:Re,oidcLoginHint:ye,oidcPrompt:Ce,oidcErrorRedirectUri:Ie,oidcResource:ke,action:I},We=_(de);w(ee,Y)?Oe.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ce?void 0:ce.clientScripts)||[];yield e(this,Z,"m",je).call(this,i);const o=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:ge},Y),{lastAuth:We,preview:this.preview,abTestingKey:ne,client:this.client}),A&&{redirectUrl:A}),{locale:b(V).locale,nativeOptions:me,outboundAppId:re,outboundAppScopes:le}),oe,t,he.componentsVersion,pe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),x(s)),T&&{exchangeCode:T,idpInitiated:!0}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j&&{token:j}),Oe.next.isCustomScreen);return e(this,be,"f").call(this,o),o})):(c("projectId")||c("baseUrl")||c("executionId")||c("stepId"))&&(Oe.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==R?void 0:R.clientScripts)||[];yield e(this,Z,"m",je).call(this,i);const o=yield this.sdk.flow.next(f,v,t,ce.version,he.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),x(s)),Oe.next.isCustomScreen);return e(this,be,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",Oe.screenId),yield e(this,Z,"m",ue).call(this,Oe),this.stepState.update(Oe)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n;const{htmlFilename:r,htmlLocaleFilename:l,direction:d,next:c,screenState:h}=t;this.loggerWrapper.debug("Rendering a flow screen");const p=document.createElement("template");p.innerHTML=yield this.getPageContent(r,l);const g=p.content.cloneNode(!0),m=this.loadDescopeUiComponents(p);this.sdk.webauthn.helpers.isSupported()?yield e(this,Z,"m",ye).call(this,g,c):L(g),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(n=h.form)||void 0===n?void 0:n.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),U(g,h,this.formConfig,this.loggerWrapper);const{geo:v}=yield this.getExecutionContext();P(g,v);const f=()=>i(this,void 0,void 0,(function*(){var i,o;yield m;const n=this.contentRootElement;$(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),N(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),M(n,g,h.cssVars,this.loggerWrapper),n.replaceChildren(g);const r=!s.htmlFilename;setTimeout((()=>{e(this,Z,"m",xe).call(this),this.validateOnBlur&&E(n),q(n,h),e(this,Z,"m",Ce).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),I(n,this.autoFocus,r)})),e(this,Z,"m",Le).call(this,c);n.querySelector(`[${u}="polling"]`)&&c(a.polling,{})}));d?e(this,Z,"m",me).call(this,f):f()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${p}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}ee=new WeakMap,te=new WeakMap,ie=new WeakMap,se=new WeakMap,pe=new WeakMap,ge=new WeakMap,ve=new WeakMap,fe=new WeakMap,be=new WeakMap,we=new WeakMap,Re=new WeakMap,Ae=new WeakMap,Z=new WeakSet,oe=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},ne=function(t,s,o){return i(this,void 0,void 0,(function*(){var i;return(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&new Promise((i=>{this.nativeCallbacks.screenNext=o,this.nativeCallbacks.screenResolve=i,e(this,Z,"m",ae).call(this,"beforeScreen",{screen:t,context:s})}))}))},re=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,Z,"m",ae).call(this,"afterScreen",{screen:t})},ae=function(t,i){e(this,Z,"m",Ue).call(this,"bridge",{type:t,payload:i})},le=function({errorText:e,errorType:t}){const i=()=>{var i;let s=e;try{s=(null===(i=this.errorTransformer)||void 0===i?void 0:i.call(this,{text:e,type:t}))||e}catch(e){this.loggerWrapper.error("Error transforming error message",e.message)}F(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},de=function(){var t,i,o;null===(t=this.stepState)||void 0===t||t.subscribe(this.onStepChange.bind(this),(e=>{var t=e.screenState,i=s(void 0===t?{}:t,["errorText","errorType"]),o=s(e,["screenState"]);return Object.assign(Object.assign({},o),{screenState:i})})),null===(i=this.stepState)||void 0===i||i.subscribe(e(this,Z,"m",le).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(o=this.stepState)||void 0===o||o.subscribe(e(this,Z,"m",ce).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0})},ce=function({errorText:e,errorType:t}){(t||e)&&(this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((e=>{e.shadowRoot.querySelectorAll("descope-text-field[data-id]").forEach((e=>{e.value=""}))})),I(this.contentRootElement,this.autoFocus,!1))},he=function(){return i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update({stepId:null,executionId:null})):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},ue=function(o){return i(this,void 0,void 0,(function*(){var i;const n=Object.assign(Object.assign({},this.stepState.current),o),{next:r,stepName:a}=n,l=s(n,["next","stepName"]),d=k(l);let c=yield e(this,Z,"m",ne).call(this,a,d,r);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,a,d,r,this)));const h=!this.stepState.current.htmlFilename;if(e(this,ge,"f").call(this,c),r&&(r.isCustomScreen=c),e(this,pe,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,pe,c,"f"),c?this.stepState.unsubscribeAll():e(this,Z,"m",de).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,Z,"m",Ce).call(this,{isFirstScreen:h,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},me=function(e){this.contentRootElement.addEventListener("transitionend",(()=>{this.loggerWrapper.debug("page switch transition end"),this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0}),this.loggerWrapper.debug("page switch transition start"),this.contentRootElement.classList.add("fade-out")},Se=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const i=`user-${t}`;e.setAttribute("name",i),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:i)}))}},ye=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,te,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield V())){const{options:s,transactionId:n}=(yield e(this,we,"f").call(this))||{};s&&n&&(e(this,Z,"m",Se).call(this,r),t(this,te,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,te,"f")).then((e=>i(this,void 0,void 0,(function*(){o(r.id,{transactionId:n,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},Ce=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,Z,"m",Ue).call(this,"ready",{}),i||e(this,Z,"m",re).call(this,s),e(this,Z,"m",Ue).call(this,"page-updated",{screenName:s}),e(this,Z,"m",Ue).call(this,"screen-updated",{screenName:s})},Ie=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"===t.localName||t.classList.contains("hidden")||(null===(i=t.reportValidity)||void 0===i||i.call(t),e&&(e=null===(s=t.checkValidity)||void 0===s?void 0:s.call(t)))})),e},ke=function(){return i(this,void 0,void 0,(function*(){const e=this.getInputs();return(yield Promise.all(e.map((e=>i(this,void 0,void 0,(function*(){return{name:e.getAttribute("name"),value:e.value}})))))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},Oe=function(s){const o=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),n=()=>i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",n),s.removeAttribute("loading"),o.forEach((e=>{e.removeAttribute("disabled")}));const e=yield this.getFlowConfig(),t=[...e.clientScripts||[],...e.sdkScripts||[]];this.loadSdkScripts(t)})),r=()=>{var i;window.removeEventListener("pageshow",e(this,Re,"f")),t(this,Re,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),n())}),"f"),window.addEventListener("pageshow",e(this,Re,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&n(),this.removeEventListener("popupclosed",n),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},a=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?(this.addEventListener("popupclosed",n,{once:!0}),s.setAttribute("loading","true"),o.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(a),r())}))},We=function(e={}){var t,i;const s=A(e,["externalId","email","phone"]),o=A(e,["newPassword","password"]);if(s&&o)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:o});null===(i=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===i||i.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},xe=function(){j();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,Z,"m",Ee).call(this,t)))},Ee=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const i=t.getAttribute("slot"),s=`input-${e.id}-${i}`,o=document.createElement("slot");o.setAttribute("name",s),o.setAttribute("slot",i),e.appendChild(o),t.setAttribute("slot",s),this.appendChild(t)}))},je=function(t){return i(this,void 0,void 0,(function*(){if(e(this,ie,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ie,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-t).toString())}const i=this.loadSdkScriptsModules(),s=t.map((e=>e.id));for(const e of i)if(s.includes(e.id))try{if("function"==typeof e.present){(yield e.present())||this.loggerWrapper.debug(`Sdk script ${e.id} was cancelled`)}}catch(t){this.loggerWrapper.error(`Failed to present ${e.id} script module`,t.message)}const o=[];for(const e of i)"function"==typeof e.refresh&&o.push(e.refresh());if(o.length>0)try{yield m(h,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},Te=function(t){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((i=>{i.addEventListener("input",(()=>{var s;(null===(s=i.checkValidity)||void 0===s?void 0:s.call(i))&&e(this,Ae,"f").call(this,i,t)}))}))},Le=function(t){this.contentRootElement.querySelectorAll(`descope-button:not([${g}]), [data-type="button"]:not([${g}]`).forEach((i=>{i.onclick=()=>{e(this,Ae,"f").call(this,i,t)}})),e(this,Z,"m",Te).call(this,t),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${p}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},Ue=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},Pe=function(e,t,i){var s;const[o,n]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],r={data:{code:t,exchangeError:i},action:"code"};if("descope-wc"===o&&n){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",n);try{window.opener.postMessage(r,n)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(r),t.close()}try{window.close()}catch(e){}};export{$e as default};
1
+ import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{ensureFingerprintIds as o,clearFingerprintData as n}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as r,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as l,URL_TOKEN_PARAM_NAME as d,URL_RUN_IDS_PARAM_NAME as c,SDK_SCRIPTS_LOAD_TIMEOUT as h,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as p,ELEMENT_TYPE_ATTRIBUTE as u,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as g}from"../constants/index.js";import{timeoutPromise as m,withMemCache as v,leadingDebounce as f,getUserLocale as b,showFirstScreenOnExecutionInit as w,injectSamlIdpForm as S,openCenteredPopup as y,getAnimationDirection as C,handleAutoFocus as I,transformStepStateForCustomScreen as k,getElementDescopeAttributes as R,getScriptResultPath as O,submitForm as W,transformScreenInputs as x,handleReportValidityOnBlur as E,getFirstNonEmptyValue as A,clearPreviousExternalInputs as j}from"../helpers/helpers.js";import T from"../helpers/state.js";import{disableWebauthnButtons as L,updateTemplateFromScreenState as U,setPhoneAutoDetectDefaultCode as P,setTOTPVariable as $,setNOTPVariable as N,setCssVars as M,updateScreenFromScreenState as q,replaceElementMessage as F}from"../helpers/templates.js";import{isConditionalLoginSupported as V}from"../helpers/webauthn.js";import{getABTestingKey as D}from"../helpers/abTestingKey.js";import{calculateConditions as B,calculateCondition as K}from"../helpers/conditions.js";import{setLastAuth as H,getLastAuth as _}from"../helpers/lastAuth.js";import G from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as J,FETCH_ERROR_RESPONSE_ERROR_CODE as z,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as Q,FLOW_TIMED_OUT_ERROR_CODE as X,POLLING_STATUS_NOT_FOUND_ERROR_CODE as Y}from"../constants/general.js";var Z,ee,te,ie,se,oe,ne,re,ae,le,de,ce,he,pe,ue,ge,me,ve,fe,be,we,Se,ye,Ce,Ie,ke,Re,Oe,We,xe,Ee,Ae,je,Te,Le,Ue,Pe;class $e extends G{static set sdkConfigOverrides(e){G.sdkConfigOverrides=e}static get sdkConfigOverrides(){return G.sdkConfigOverrides}constructor(){const s=new T({deferredRedirect:!1});super(s.update.bind(s)),Z.add(this),this.stepState=new T({}),ee.set(this,void 0),te.set(this,null),ie.set(this,null),se.set(this,{visibilitychange:e(this,Z,"m",oe).bind(this)}),this.bridgeVersion=2,this.nativeCallbacks={},pe.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},ge.set(this,(t=>{const i=()=>{this.contentRootElement.classList.toggle("hidden",t),this.slotElement.classList.toggle("hidden",!t),t&&(this.contentRootElement.innerHTML="")};t&&this.contentRootElement.hasChildNodes()?e(this,Z,"m",me).call(this,i):i()})),ve.set(this,((s,o,n,l,d=!1)=>{const c=[X,Y];if(this.flowState.current.action===r.poll){this.logger.debug("polling - Scheduling polling request");const r=Date.now(),h=d?500:2e3;t(this,ee,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const p=this.sdk.flow.next(s,o,a.polling,n,l,{}),u=document.hidden&&!d&&Date.now()-r>h+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield m(e,p)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,ve,"f").call(this,s,o,n,l,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===J)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,ve,"f").call(this,s,o,n,l);this.logger.debug("polling - Got a response"),(null==g?void 0:g.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(g.error,null,4)),(null===(i=null==g?void 0:g.error)||void 0===i?void 0:i.errorCode)&&c.includes(g.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):e(this,ve,"f").call(this,s,o,n,l),e(this,be,"f").call(this,g)}))),h),"f")}})),fe.set(this,(()=>{clearTimeout(e(this,ee,"f")),t(this,ee,null,"f")})),be.set(this,(i=>{var s,o,n,a,l,d,c,h,p,u,g,m,v;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,r=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,Z,"m",Ue).call(this,"error",(null==i?void 0:i.error)||{errorCode:z,errorDescription:r,errorMessage:t}),this.loggerWrapper.error((null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorDescription)||t,(null===(l=null==i?void 0:i.error)||void 0===l?void 0:l.errorMessage)||r);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==Q&&c!==X||!this.isRestartOnError||e(this,Z,"m",he).call(this))}null===(h=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===h||h.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(p=i.data)||void 0===p?void 0:p.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(m=i.data)||void 0===m?void 0:m.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:C}=i.data;if(y!==r.poll&&e(this,fe,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&H(S);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),void e(this,Z,"m",Ue).call(this,"success",t)}this.storeLastAuthenticatedUser&&H(S,!0),C&&window.open(C,"_blank");const{executionId:I,stepId:k,stepName:R,screen:O,redirect:W,webauthn:x,error:E,samlIdpResponse:A,nativeResponse:j}=i.data,T=Date.now();y!==r.poll?(this.loggerWrapper.info(`Step "${R||`#${k}`}" is ${b}`,"",{screen:O,status:b,stepId:k,stepName:R,action:y,error:E}),(null===(v=O.state)||void 0===v?void 0:v.clientScripts)&&t(this,ie,this.loadSdkScripts(O.state.clientScripts),"f"),this.flowState.update({stepId:k,stepName:R,executionId:I,action:y,redirectTo:null==W?void 0:W.url,redirectIsPopup:null==W?void 0:W.isPopup,screenId:null==O?void 0:O.id,screenState:null==O?void 0:O.state,webauthnTransactionId:null==x?void 0:x.transactionId,webauthnOptions:null==x?void 0:x.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,nativeResponseType:null==j?void 0:j.type,nativePayload:null==j?void 0:j.payload,reqTimestamp:T})):this.flowState.update({action:y,reqTimestamp:T})})),we.set(this,v((()=>i(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),Re.set(this,null),Ae.set(this,f(((t,s)=>i(this,void 0,void 0,(function*(){var i;if("true"===t.getAttribute("formnovalidate")||e(this,Z,"m",Ie).call(this)){const o=null==t?void 0:t.getAttribute("id");e(this,Z,"m",Oe).call(this,t);const n=yield e(this,Z,"m",ke).call(this),r=R(t);this.nextRequestStatus.update({isLoading:!0});const a=Object.assign(Object.assign(Object.assign({},r),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(o,a),this.nextRequestStatus.update({isLoading:!1}),e(this,Z,"m",We).call(this,n)}}))))),this.flowState=s}nativeResume(t,i){var s,o,n,r,a;const h=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let{exchangeCode:e}=h;if(!e){e=null===(s=new URL(h.url).searchParams)||void 0===s?void 0:s.get(l)}null===(n=(o=this.nativeCallbacks).complete)||void 0===n||n.call(o,{exchangeCode:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(h.url),i=t.searchParams.get(d),s=t.searchParams.get(c).split("_").pop();e(this,fe,"f").call(this),this.flowState.update({token:i,stepId:s,action:void 0})}else if("beforeScreen"===t){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=h;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=h,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(r=this.nativeCallbacks).complete)||void 0===a||a.call(r,h)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[O(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=Promise.all(null==e?void 0:e.map((e=>i(this,void 0,void 0,(function*(){var i,s;const o=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(o){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=o;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}yield this.injectNpmLib("@descope/flow-scripts","1.0.13",`dist/${e.id}.js`);const n=null===(s=globalThis.descope)||void 0===s?void 0:s[e.id];return new Promise(((i,s)=>{try{const s=n(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i),this.loggerWrapper);if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t),this.nextRequestStatus.subscribe((()=>{var t;this.loggerWrapper.debug("Unloading script",e.id),null===(t=s.stop)||void 0===t||t.call(s)}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),h)}));return Promise.race([s,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){if(!window.descopeBridge)return this._init();this.lazyInit=this._init}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,Z,"m",de).call(this),window.addEventListener("visibilitychange",e(this,se,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var i;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,fe,"f").call(this),null===(i=e(this,te,"f"))||void 0===i||i.abort(),t(this,te,null,"f"),window.removeEventListener("visibilitychange",e(this,se,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=b(e),o=yield this.getTargetLocales();return o.includes(s.locale)?i=`${t}-${s.locale}.html`:o.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(l,d,c){return i(this,void 0,void 0,(function*(){var h,p;const{projectId:u,flowId:g,tenant:m,stepId:v,executionId:f,action:I,screenId:k,screenState:R,redirectTo:O,redirectIsPopup:E,redirectUrl:A,token:j,code:T,isPopup:L,exchangeError:U,webauthnTransactionId:P,webauthnOptions:$,redirectAuthCodeChallenge:N,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:F,locale:V,samlIdpResponseUrl:H,samlIdpResponseSamlResponse:G,samlIdpResponseRelayState:J,nativeResponseType:z,nativePayload:Q,reqTimestamp:X}=l,Y=s(l,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","nativeResponseType","nativePayload","reqTimestamp"]);let ee,se,oe;const ne=D(),{outboundAppId:re}=this,{outboundAppScopes:le}=this,de=this.sdk.getLastUserLoginId(),ce=yield this.getFlowConfig(),he=yield this.getProjectConfig(),pe=Object.entries(he.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),ge=M&&N?{callbackUrl:M,codeChallenge:N,backupCallbackUri:q}:void 0,me=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;let fe={};if(!f){const i=[...ce.clientScripts||[],...ce.sdkScripts||[]];if(ce.conditions){let e=[];({startScreenId:ee,conditionInteractionId:oe,startScreenName:se,clientScripts:e,componentsConfig:fe}=B({loginId:de,code:T,token:j,abTestingKey:ne,lastAuth:_(de)},ce.conditions)),i.push(...e||[])}else ce.condition?({startScreenId:ee,conditionInteractionId:oe}=K(ce.condition,{loginId:de,code:T,token:j,abTestingKey:ne,lastAuth:_(de)})):(se=ce.startScreenName,ee=ce.startScreenId);if(t(this,ie,this.loadSdkScripts(i),"f"),ce.fingerprintEnabled&&ce.fingerprintKey?yield o(ce.fingerprintKey,this.baseUrl):n(),!w(ee,Y)){const t=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:ge},Y),{client:this.client}),A&&{redirectUrl:A}),{lastAuth:_(de),abTestingKey:ne,locale:b(V).locale,nativeOptions:me,outboundAppId:re,outboundAppScopes:le}),oe,"",he.componentsVersion,pe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),T?{exchangeCode:T,idpInitiated:!0}:{}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j?{token:j}:{}),Y.oidcLoginHint?{externalId:Y.oidcLoginHint}:{}));return e(this,be,"f").call(this,t),void("completed"!==(null===(h=null==t?void 0:t.data)||void 0===h?void 0:h.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:L,code:T,exchangeError:U,isCodeChanged:c("code"),isExchangeErrorChanged:c("exchangeError")})),L&&(c("code")&&T||c("exchangeError")&&U))return void e(this,Z,"m",Pe).call(this,f,T,U);if(f&&(c("token")&&j||c("code")&&T||c("exchangeError")&&U)){const t=yield this.sdk.flow.next(f,v,a.submit,ce.version,he.componentsVersion,{token:j,exchangeCode:T,exchangeError:U});return e(this,be,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(I===r.loadForm&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>c(e)))){if(!H||!G)return void this.loggerWrapper.error("Did not get saml idp params data to load");S(H,G,J||"",W)}if(I===r.redirect&&(c("redirectTo")||c("deferredRedirect"))){if(!O)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===O)return;if("android"===F&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${E}`),E){this.loggerWrapper.debug("Opening redirect in popup");const t=y(O,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));const s=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const t=i?this.popupOrigin:window.location.origin;if(e.origin!==t)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${t}"`);const{action:s,data:o}=e.data||{};"code"===s&&this.flowState.update({code:o.code,exchangeError:o.exchangeError})};let o;this.loggerWrapper.debug("Starting popup closed detection");const n=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(n),e(this,Z,"m",Ue).call(this,"popupclosed",{}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==o||o())}),1e3);if(i)window.addEventListener("message",s),o=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",s)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(f);e.onmessage=s,o=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(O),this.flowState.update({redirectTo:"no-op"}),e(this,Z,"m",Ue).call(this,"popupclosed",{});return}if(I===r.webauthnCreate||I===r.webauthnGet){if(!P||!$)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s;null===(p=e(this,te,"f"))||void 0===p||p.abort(),t(this,te,null,"f");try{i=I===r.webauthnCreate?yield this.sdk.webauthn.helpers.create($):yield this.sdk.webauthn.helpers.get($)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),s=e.name}const o=yield this.sdk.flow.next(f,v,a.submit,ce.version,he.componentsVersion,{transactionId:P,response:i,failure:s});e(this,be,"f").call(this,o)}if(I===r.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,v,a.submit,ce.version,he.componentsVersion,t);e(this,be,"f").call(this,i)})),e(this,Z,"m",ae).call(this,z,Q),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if(c("action")&&e(this,ve,"f").call(this,f,v,ce.version,he.componentsVersion),!k&&!ee)return void this.loggerWrapper.warn("No screen was found to show");const we=ee||k,Se=yield this.getHtmlFilenameWithLocale(V,we),{oidcLoginHint:ye,oidcPrompt:Ce,oidcErrorRedirectUri:Ie,oidcResource:ke,samlIdpUsername:Re}=Y,Oe={direction:C(v,d.stepId),screenState:Object.assign(Object.assign({},R),{form:Object.assign(Object.assign({},this.formConfigValues),null==R?void 0:R.form),lastAuth:{loginId:de,name:this.sdk.getLastUserDisplayName()||de},componentsConfig:Object.assign(Object.assign(Object.assign({},ce.componentsConfig),fe),null==R?void 0:R.componentsConfig)}),htmlFilename:`${we}.html`,htmlLocaleFilename:Se,screenId:we,stepName:l.stepName||se,samlIdpUsername:Re,oidcLoginHint:ye,oidcPrompt:Ce,oidcErrorRedirectUri:Ie,oidcResource:ke,action:I},We=_(de);w(ee,Y)?Oe.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ce?void 0:ce.clientScripts)||[];yield e(this,Z,"m",je).call(this,i);const o=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:ge},Y),{lastAuth:We,preview:this.preview,abTestingKey:ne,client:this.client}),A&&{redirectUrl:A}),{locale:b(V).locale,nativeOptions:me,outboundAppId:re,outboundAppScopes:le}),oe,t,he.componentsVersion,pe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),x(s)),T&&{exchangeCode:T,idpInitiated:!0}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j&&{token:j}),Oe.next.isCustomScreen);return e(this,be,"f").call(this,o),o})):(c("projectId")||c("baseUrl")||c("executionId")||c("stepId"))&&(Oe.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==R?void 0:R.clientScripts)||[];yield e(this,Z,"m",je).call(this,i);const o=yield this.sdk.flow.next(f,v,t,ce.version,he.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),x(s)),Oe.next.isCustomScreen);return e(this,be,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",Oe.screenId),yield e(this,Z,"m",ue).call(this,Oe),this.stepState.update(Oe)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n;const{htmlFilename:r,htmlLocaleFilename:l,direction:d,next:c,screenState:h}=t;this.loggerWrapper.debug("Rendering a flow screen");const p=document.createElement("template");p.innerHTML=yield this.getPageContent(r,l);const g=p.content.cloneNode(!0),m=this.loadDescopeUiComponents(p);this.sdk.webauthn.helpers.isSupported()?yield e(this,Z,"m",ye).call(this,g,c):L(g),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(n=h.form)||void 0===n?void 0:n.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),U(g,h,this.formConfig,this.loggerWrapper);const{geo:v}=yield this.getExecutionContext();P(g,v);const f=()=>i(this,void 0,void 0,(function*(){var i,o;yield m;const n=this.contentRootElement;$(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),N(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),M(n,g,h.cssVars,this.loggerWrapper),n.replaceChildren(g);const r=!s.htmlFilename;setTimeout((()=>{e(this,Z,"m",xe).call(this),this.validateOnBlur&&E(n),q(n,h),e(this,Z,"m",Ce).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),I(n,this.autoFocus,r)})),e(this,Z,"m",Le).call(this,c);n.querySelector(`[${u}="polling"]`)&&c(a.polling,{})}));d?e(this,Z,"m",me).call(this,f):f()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${p}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}ee=new WeakMap,te=new WeakMap,ie=new WeakMap,se=new WeakMap,pe=new WeakMap,ge=new WeakMap,ve=new WeakMap,fe=new WeakMap,be=new WeakMap,we=new WeakMap,Re=new WeakMap,Ae=new WeakMap,Z=new WeakSet,oe=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},ne=function(t,s,o){return i(this,void 0,void 0,(function*(){var i;return(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&new Promise((i=>{this.nativeCallbacks.screenNext=o,this.nativeCallbacks.screenResolve=i,e(this,Z,"m",ae).call(this,"beforeScreen",{screen:t,context:s})}))}))},re=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,Z,"m",ae).call(this,"afterScreen",{screen:t})},ae=function(t,i){e(this,Z,"m",Ue).call(this,"bridge",{type:t,payload:i})},le=function({errorText:e,errorType:t}){const i=()=>{var i;let s=e;try{s=(null===(i=this.errorTransformer)||void 0===i?void 0:i.call(this,{text:e,type:t}))||e}catch(e){this.loggerWrapper.error("Error transforming error message",e.message)}F(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},de=function(){var t,i,o;null===(t=this.stepState)||void 0===t||t.subscribe(this.onStepChange.bind(this),(e=>{var t=e.screenState,i=s(void 0===t?{}:t,["errorText","errorType"]),o=s(e,["screenState"]);return Object.assign(Object.assign({},o),{screenState:i})})),null===(i=this.stepState)||void 0===i||i.subscribe(e(this,Z,"m",le).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(o=this.stepState)||void 0===o||o.subscribe(e(this,Z,"m",ce).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0})},ce=function({errorText:e,errorType:t}){(t||e)&&(this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((e=>{e.shadowRoot.querySelectorAll("descope-text-field[data-id]").forEach((e=>{e.value=""}))})),I(this.contentRootElement,this.autoFocus,!1))},he=function(){return i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update({stepId:null,executionId:null})):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},ue=function(o){return i(this,void 0,void 0,(function*(){var i;const n=Object.assign(Object.assign({},this.stepState.current),o),{next:r,stepName:a}=n,l=s(n,["next","stepName"]),d=k(l);let c=yield e(this,Z,"m",ne).call(this,a,d,r);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,a,d,r,this)));const h=!this.stepState.current.htmlFilename;if(e(this,ge,"f").call(this,c),r&&(r.isCustomScreen=c),e(this,pe,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,pe,c,"f"),c?this.stepState.unsubscribeAll():e(this,Z,"m",de).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,Z,"m",Ce).call(this,{isFirstScreen:h,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},me=function(e){this.contentRootElement.addEventListener("transitionend",(()=>{this.loggerWrapper.debug("page switch transition end"),this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0}),this.loggerWrapper.debug("page switch transition start"),this.contentRootElement.classList.add("fade-out")},Se=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const i=`user-${t}`;e.setAttribute("name",i),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:i)}))}},ye=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,te,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield V())){const{options:s,transactionId:n}=(yield e(this,we,"f").call(this))||{};s&&n&&(e(this,Z,"m",Se).call(this,r),t(this,te,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,te,"f")).then((e=>i(this,void 0,void 0,(function*(){o(r.id,{transactionId:n,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},Ce=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,Z,"m",Ue).call(this,"ready",{}),i||e(this,Z,"m",re).call(this,s),e(this,Z,"m",Ue).call(this,"page-updated",{screenName:s}),e(this,Z,"m",Ue).call(this,"screen-updated",{screenName:s})},Ie=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"===t.localName||t.classList.contains("hidden")||(null===(i=t.reportValidity)||void 0===i||i.call(t),e&&(e=null===(s=t.checkValidity)||void 0===s?void 0:s.call(t)))})),e},ke=function(){return i(this,void 0,void 0,(function*(){const e=this.getInputs();return(yield Promise.all(e.map((e=>i(this,void 0,void 0,(function*(){return{name:e.getAttribute("name"),value:e.value}})))))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},Oe=function(s){const o=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),n=()=>i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",n),s.removeAttribute("loading"),o.forEach((e=>{e.removeAttribute("disabled")}));const e=yield this.getFlowConfig(),t=[...e.clientScripts||[],...e.sdkScripts||[]];this.loadSdkScripts(t)})),r=()=>{var i;window.removeEventListener("pageshow",e(this,Re,"f")),t(this,Re,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),n())}),"f"),window.addEventListener("pageshow",e(this,Re,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&n(),this.removeEventListener("popupclosed",n),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},a=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?(this.addEventListener("popupclosed",n,{once:!0}),s.setAttribute("loading","true"),o.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(a),r())}))},We=function(e={}){var t,i;const s=A(e,["externalId","email","phone"]),o=A(e,["newPassword","password"]);if(s&&o)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:o});null===(i=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===i||i.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},xe=function(){j();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,Z,"m",Ee).call(this,t)))},Ee=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const i=t.getAttribute("slot"),s=`input-${e.id}-${i}`,o=document.createElement("slot");o.setAttribute("name",s),o.setAttribute("slot",i),e.appendChild(o),t.setAttribute("slot",s),this.appendChild(t)}))},je=function(t){return i(this,void 0,void 0,(function*(){if(e(this,ie,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ie,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-t).toString())}const i=this.loadSdkScriptsModules(),s=t.map((e=>e.id));for(const e of i)if(s.includes(e.id))try{if("function"==typeof e.present){(yield e.present())||this.loggerWrapper.debug(`Sdk script ${e.id} was cancelled`)}}catch(t){this.loggerWrapper.error(`Failed to present ${e.id} script module`,t.message)}const o=[];for(const e of i)"function"==typeof e.refresh&&o.push(e.refresh());if(o.length>0)try{yield m(h,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},Te=function(t){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((i=>{i.addEventListener("input",(()=>{var s;(null===(s=i.checkValidity)||void 0===s?void 0:s.call(i))&&e(this,Ae,"f").call(this,i,t)}))}))},Le=function(t){this.contentRootElement.querySelectorAll(`descope-button:not([${g}]), [data-type="button"]:not([${g}]`).forEach((i=>{i.onclick=()=>{e(this,Ae,"f").call(this,i,t)}})),e(this,Z,"m",Te).call(this,t),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${p}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},Ue=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},Pe=function(e,t,i){var s;const[o,n]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],r={data:{code:t,exchangeError:i},action:"code"};if("descope-wc"===o&&n){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",n);try{window.opener.postMessage(r,n)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(r),t.close()}try{window.close()}catch(e){}};export{$e as default};
2
2
  //# sourceMappingURL=DescopeWc.js.map