@descope/web-component 3.35.1 → 3.36.1

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
- "use strict";var t=require("tslib"),e=require("@descope/sdk-helpers"),i=require("@descope/sdk-mixins/static-resources-mixin"),s=require("@descope/sdk-mixins/theme-mixin"),r=require("@descope/web-js-sdk"),o=require("../constants/index.js"),n=require("../helpers/helpers.js"),a=require("../helpers/state.js");require("@descope/escape-markdown"),require("../helpers/webauthn.js");var l,d,u,c,h,g,f,v,p,_,b,m,w,C,F,A,P,k,x,E,I,G=require("../helpers/flowInputs.js"),j=require("../mixins/formMountMixin.js"),y=require("./initTemplate.js"),U=require("../constants/content.js"),L=require("../constants/general.js");function M(t){return Object.freeze({__proto__:null,default:t})}const O=e.compose(s.themeMixin,i.staticResourcesMixin,j.formMountMixin)(HTMLElement);class S extends O{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(e){super(),l.add(this),u.set(this,!1),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t.__classPrivateFieldGet(this,l,"m",E).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)}},c.set(this,new a),h.set(this,new a),g.set(this,{}),this.getComponentsContext=()=>t.__classPrivateFieldGet(this,g,"f"),this.nextRequestStatus=new a({isLoading:!1}),f.set(this,void 0),v.set(this,{popstate:t.__classPrivateFieldGet(this,l,"m",m).bind(this),componentsContext:t.__classPrivateFieldGet(this,l,"m",P).bind(this)}),p.set(this,void 0),this.getConfig=()=>t.__awaiter(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),t.__classPrivateFieldSet(this,p,e,"f"),t.__classPrivateFieldGet(this,l,"m",_).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 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 G.transformFlowInputFormData(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return G.extractNestedAttribute(this.formConfig,"value")}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return t.__awaiter(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return t.__awaiter(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return t.__awaiter(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),s=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=s.version)&&void 0!==e||(s.version=0),s}))}getTargetLocales(){return t.__awaiter(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}getComponentsVersion(){return t.__awaiter(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 e=Object.create(null,{init:{get:()=>super.init}});return t.__awaiter(this,void 0,void 0,(function*(){var i;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(i=e.init)||void 0===i?void 0:i.call(this),t.__classPrivateFieldGet(this,h,"f").subscribe(t.__classPrivateFieldGet(this,l,"m",x).bind(this)),t.__classPrivateFieldGet(this,h,"f").update({isDebug:this.debug}),t.__classPrivateFieldGet(this,l,"m",b).call(this),yield t.__classPrivateFieldGet(this,l,"m",F).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 s=yield this.getConfig();if("isMissingConfig"in s&&s.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");t.__classPrivateFieldGet(this,l,"m",I).call(this);const{executionId:r,stepId:o,token:a,code:d,exchangeError:g,redirectAuthCallbackUrl:f,redirectAuthBackupCallbackUri:p,redirectAuthCodeChallenge:_,redirectAuthInitiator:m,ssoQueryParams:w}=n.handleUrlParams(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t.__classPrivateFieldGet(this,v,"f").popstate),window.addEventListener("components-context",t.__classPrivateFieldGet(this,v,"f").componentsContext),t.__classPrivateFieldGet(this,c,"f").subscribe(t.__classPrivateFieldGet(this,l,"m",C).bind(this)),t.__classPrivateFieldGet(this,c,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:o,executionId:r,token:a,code:d,exchangeError:g,redirectAuthCallbackUrl:f,redirectAuthBackupCallbackUri:p,redirectAuthCodeChallenge:_,redirectAuthInitiator:m},w)),t.__classPrivateFieldSet(this,u,!0,"f")}))}disconnectedCallback(){t.__classPrivateFieldGet(this,c,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,h,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,l,"m",k).call(this),window.removeEventListener("popstate",t.__classPrivateFieldGet(this,v,"f").popstate),window.removeEventListener("components-context",t.__classPrivateFieldGet(this,v,"f").componentsContext)}attributeChangedCallback(e,i,s){if(this.shadowRoot.isConnected&&t.__classPrivateFieldGet(this,u,"f")&&i!==s&&d.observedAttributes.includes(e)){t.__classPrivateFieldGet(this,l,"m",b).call(this);const r=null===i;t.__classPrivateFieldGet(this,c,"f").update((({stepId:t,executionId:i})=>{let o=t,a=i;return r||(a=null,o=null,n.clearRunIdsFromUrl()),{[n.camelCase(e)]:s,stepId:o,executionId:a}})),t.__classPrivateFieldGet(this,h,"f").update({isDebug:this.debug})}}}d=S,u=new WeakMap,c=new WeakMap,h=new WeakMap,g=new WeakMap,f=new WeakMap,v=new WeakMap,p=new WeakMap,l=new WeakSet,_=function(){this.shadowRoot.appendChild(y.content.cloneNode(!0)),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},b=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id"];d.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[n.camelCase(e)])throw Error(`${e} cannot be empty`)}))},m=function(){const{stepId:e,executionId:i}=n.getRunIdsFromUrl(this.flowId);t.__classPrivateFieldGet(this,c,"f").update({stepId:e,executionId:i})},w=function(e,i){this.sdk=r(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout},d.sdkConfigOverrides),{projectId:e,baseUrl:i})),["start","next"].forEach((e=>{const i=this.sdk.flow[e];this.sdk.flow[e]=(...e)=>t.__awaiter(this,void 0,void 0,(function*(){try{return yield i(...e)}catch(t){return{error:{errorCode:L.FETCH_EXCEPTION_ERROR_CODE,errorDescription:t.toString()}}}}))}))},C=function(e,i,s){return t.__awaiter(this,void 0,void 0,(function*(){const{projectId:i,baseUrl:r}=e;if(s("projectId")||s("baseUrl")){if(!i)return;t.__classPrivateFieldGet(this,l,"m",w).call(this,i,r)}t.__classPrivateFieldGet(this,p,"f").call(this,e)}))},F=function(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t.__classPrivateFieldGet(this,l,"m",A).call(this))}))},A=function(){return t.__awaiter(this,void 0,void 0,(function*(){const t=n.getContentUrl({projectId:this.projectId,filename:U.CONFIG_FILENAME,assetsFolder:U.PREV_VER_ASSETS_FOLDER,baseUrl:this.baseStaticUrl});try{return yield n.fetchContent(t,"json"),!0}catch(t){return!1}}))},P=function(e){t.__classPrivateFieldSet(this,g,Object.assign(Object.assign({},t.__classPrivateFieldGet(this,g,"f")),e.detail),"f")},k=function(){var e;null===(e=t.__classPrivateFieldGet(this,f,"f"))||void 0===e||e.remove(),t.__classPrivateFieldSet(this,f,null,"f")},x=function(e){return t.__awaiter(this,arguments,void 0,(function*({isDebug:e}){e?(t.__classPrivateFieldSet(this,f,document.createElement("descope-debugger"),"f"),Object.assign(t.__classPrivateFieldGet(this,f,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return M(require("../debugger-wc.js"))})),document.body.appendChild(t.__classPrivateFieldGet(this,f,"f"))):t.__classPrivateFieldGet(this,l,"m",k).call(this)}))},E=function(e,i){var s;e&&this.debug&&(null===(s=t.__classPrivateFieldGet(this,f,"f"))||void 0===s||s.updateData({title:e,description:i}))},I=function(){this.rootElement.onkeydown=t=>{var e,i,s;const r=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),n=o.ELEMENTS_TO_IGNORE_ENTER_KEY_ON.includes(null!==(s=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==s?s:"");if("Enter"!==t.key||r||n)return;t.preventDefault();const a=this.rootElement.querySelectorAll("descope-button");if(1===a.length&&"false"!==a[0].getAttribute("auto-submit"))return void a[0].click();const l=Array.from(a).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===l.length)return void l[0].click();const d=Array.from(a).filter((t=>"button"===t.getAttribute("data-type")));if(1===d.length)"false"!==d[0].getAttribute("auto-submit")&&d[0].click();else if(0===d.length){const t=Array.from(a).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}},S.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.35.1"}},module.exports=S;
1
+ "use strict";var e=require("tslib"),t=require("@descope/sdk-helpers"),i=require("@descope/sdk-mixins/static-resources-mixin"),r=require("@descope/sdk-mixins/theme-mixin"),s=require("@descope/web-js-sdk"),o=require("../constants/index.js"),n=require("../helpers/helpers.js"),a=require("../helpers/state.js");require("@descope/escape-markdown"),require("../helpers/webauthn.js");var l,d,u,c,h,g,f,v,p,_,b,m,w,C,F,k,A,P,x,E,I,G=require("../helpers/flowInputs.js"),j=require("../mixins/formMountMixin.js"),y=require("./initTemplate.js"),U=require("../constants/content.js"),L=require("../constants/general.js");function M(e){return Object.freeze({__proto__:null,default:e})}const O=t.compose(r.themeMixin,i.staticResourcesMixin,j.formMountMixin)(HTMLElement);class S extends O{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(t){super(),l.add(this),u.set(this,!1),this.flowStatus="initial",this.loggerWrapper={error:(t,i="")=>{this.logger.error(t,i,new Error),e.__classPrivateFieldGet(this,l,"m",E).call(this,t,i)},warn:(e,t="")=>{this.logger.warn(e,t)},info:(e,t="",i={})=>{this.logger.info(e,t,i)},debug:(e,t="")=>{this.logger.debug(e,t)}},c.set(this,new a),h.set(this,new a),g.set(this,{}),this.getComponentsContext=()=>e.__classPrivateFieldGet(this,g,"f"),this.nextRequestStatus=new a({isLoading:!1}),f.set(this,void 0),v.set(this,{popstate:e.__classPrivateFieldGet(this,l,"m",m).bind(this),componentsContext:e.__classPrivateFieldGet(this,l,"m",A).bind(this)}),p.set(this,void 0),this.getConfig=()=>e.__awaiter(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),e.__classPrivateFieldSet(this,p,t,"f"),e.__classPrivateFieldGet(this,l,"m",_).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(e){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 e;const t=null!==(e=this.getAttribute("auto-focus"))&&void 0!==e?e:"true";return"skipFirstScreen"===t?t:"true"===t}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var e;return"true"===(null!==(e=this.getAttribute("store-last-authenticated-user"))&&void 0!==e?e:"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 G.transformFlowInputFormData(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return G.extractNestedAttribute(this.formConfig,"value")}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"executionContext"in e?e.executionContext:void 0}))}getProjectConfig(){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"projectConfig"in e?e.projectConfig:void 0}))}getFlowConfig(){return e.__awaiter(this,void 0,void 0,(function*(){var e,t;const i=yield this.getProjectConfig(),r=(null===(e=null==i?void 0:i.flows)||void 0===e?void 0:e[this.flowId])||{};return null!==(t=r.version)&&void 0!==t||(r.version=0),r}))}getTargetLocales(){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getFlowConfig();return((null==e?void 0:e.targetLocales)||[]).map((e=>e.toLowerCase()))}))}getComponentsVersion(){return e.__awaiter(this,void 0,void 0,(function*(){var e;const t=yield this.getConfig(),i="projectConfig"in t?null===(e=t.projectConfig)||void 0===e?void 0:e.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const t=Object.create(null,{init:{get:()=>super.init}});return e.__awaiter(this,void 0,void 0,(function*(){var i;if(this.flowStatus="loading",["ready","error","success"].forEach((e=>this.addEventListener(e,(()=>{this.flowStatus=e})))),yield null===(i=t.init)||void 0===i?void 0:i.call(this),e.__classPrivateFieldGet(this,h,"f").subscribe(e.__classPrivateFieldGet(this,l,"m",x).bind(this)),e.__classPrivateFieldGet(this,h,"f").update({isDebug:this.debug}),e.__classPrivateFieldGet(this,l,"m",b).call(this),yield e.__classPrivateFieldGet(this,l,"m",F).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 r=yield this.getConfig();if("isMissingConfig"in r&&r.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");e.__classPrivateFieldGet(this,l,"m",I).call(this);const{executionId:s,stepId:o,token:a,code:d,exchangeError:g,redirectAuthCallbackUrl:f,redirectAuthBackupCallbackUri:p,redirectAuthCodeChallenge:_,redirectAuthInitiator:m,ssoQueryParams:w}=n.handleUrlParams(this.flowId,this.loggerWrapper);window.addEventListener("popstate",e.__classPrivateFieldGet(this,v,"f").popstate),window.addEventListener("components-context",e.__classPrivateFieldGet(this,v,"f").componentsContext),e.__classPrivateFieldGet(this,c,"f").subscribe(e.__classPrivateFieldGet(this,l,"m",C).bind(this)),e.__classPrivateFieldGet(this,c,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:o,executionId:s,token:a,code:d,exchangeError:g,redirectAuthCallbackUrl:f,redirectAuthBackupCallbackUri:p,redirectAuthCodeChallenge:_,redirectAuthInitiator:m},w)),e.__classPrivateFieldSet(this,u,!0,"f")}))}disconnectedCallback(){e.__classPrivateFieldGet(this,c,"f").unsubscribeAll(),e.__classPrivateFieldGet(this,h,"f").unsubscribeAll(),e.__classPrivateFieldGet(this,l,"m",P).call(this),window.removeEventListener("popstate",e.__classPrivateFieldGet(this,v,"f").popstate),window.removeEventListener("components-context",e.__classPrivateFieldGet(this,v,"f").componentsContext)}attributeChangedCallback(t,i,r){if(this.shadowRoot.isConnected&&e.__classPrivateFieldGet(this,u,"f")&&i!==r&&d.observedAttributes.includes(t)){e.__classPrivateFieldGet(this,l,"m",b).call(this);const s=null===i;e.__classPrivateFieldGet(this,c,"f").update((({stepId:e,executionId:i})=>{let o=e,a=i;return s||(a=null,o=null,n.clearRunIdsFromUrl()),{[n.camelCase(t)]:r,stepId:o,executionId:a}})),e.__classPrivateFieldGet(this,h,"f").update({isDebug:this.debug})}}}d=S,u=new WeakMap,c=new WeakMap,h=new WeakMap,g=new WeakMap,f=new WeakMap,v=new WeakMap,p=new WeakMap,l=new WeakSet,_=function(){this.shadowRoot.appendChild(y.content.cloneNode(!0)),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},b=function(){const e=["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"];d.observedAttributes.forEach((t=>{if(!e.includes(t)&&!this[n.camelCase(t)])throw Error(`${t} cannot be empty`)}))},m=function(){const{stepId:t,executionId:i}=n.getRunIdsFromUrl(this.flowId);e.__classPrivateFieldGet(this,c,"f").update({stepId:t,executionId:i})},w=function(t,i){this.sdk=s(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},d.sdkConfigOverrides),{projectId:t,baseUrl:i})),["start","next"].forEach((t=>{const i=this.sdk.flow[t];this.sdk.flow[t]=(...t)=>e.__awaiter(this,void 0,void 0,(function*(){try{return yield i(...t)}catch(e){return{error:{errorCode:L.FETCH_EXCEPTION_ERROR_CODE,errorDescription:e.toString()}}}}))}))},C=function(t,i,r){return e.__awaiter(this,void 0,void 0,(function*(){const{projectId:i,baseUrl:s}=t;if(r("projectId")||r("baseUrl")){if(!i)return;e.__classPrivateFieldGet(this,l,"m",w).call(this,i,s)}e.__classPrivateFieldGet(this,p,"f").call(this,t)}))},F=function(){return e.__awaiter(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"isMissingConfig"in t&&t.isMissingConfig&&(yield e.__classPrivateFieldGet(this,l,"m",k).call(this))}))},k=function(){return e.__awaiter(this,void 0,void 0,(function*(){const e=n.getContentUrl({projectId:this.projectId,filename:U.CONFIG_FILENAME,assetsFolder:U.PREV_VER_ASSETS_FOLDER,baseUrl:this.baseStaticUrl});try{return yield n.fetchContent(e,"json"),!0}catch(e){return!1}}))},A=function(t){e.__classPrivateFieldSet(this,g,Object.assign(Object.assign({},e.__classPrivateFieldGet(this,g,"f")),t.detail),"f")},P=function(){var t;null===(t=e.__classPrivateFieldGet(this,f,"f"))||void 0===t||t.remove(),e.__classPrivateFieldSet(this,f,null,"f")},x=function(t){return e.__awaiter(this,arguments,void 0,(function*({isDebug:t}){t?(e.__classPrivateFieldSet(this,f,document.createElement("descope-debugger"),"f"),Object.assign(e.__classPrivateFieldGet(this,f,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return M(require("../debugger-wc.js"))})),document.body.appendChild(e.__classPrivateFieldGet(this,f,"f"))):e.__classPrivateFieldGet(this,l,"m",P).call(this)}))},E=function(t,i){var r;t&&this.debug&&(null===(r=e.__classPrivateFieldGet(this,f,"f"))||void 0===r||r.updateData({title:t,description:i}))},I=function(){this.rootElement.onkeydown=e=>{var t,i,r;const s=!!(null===(t=this.shadowRoot.activeElement)||void 0===t?void 0:t.getAttribute("href")),n=o.ELEMENTS_TO_IGNORE_ENTER_KEY_ON.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==e.key||s||n)return;e.preventDefault();const a=this.rootElement.querySelectorAll("descope-button");if(1===a.length&&"false"!==a[0].getAttribute("auto-submit"))return void a[0].click();const l=Array.from(a).filter((e=>"true"===e.getAttribute("auto-submit")));if(1===l.length)return void l[0].click();const d=Array.from(a).filter((e=>"button"===e.getAttribute("data-type")));if(1===d.length)"false"!==d[0].getAttribute("auto-submit")&&d[0].click();else if(0===d.length){const e=Array.from(a).filter((e=>"sso"===e.getAttribute("data-type")));1===e.length&&"false"!==e[0].getAttribute("auto-submit")&&e[0].click()}}},S.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.36.1"}},module.exports=S;
2
2
  //# sourceMappingURL=BaseDescopeWc.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"BaseDescopeWc.js","sources":["../../../src/lib/descope-wc/BaseDescopeWc.ts"],"sourcesContent":["import { compose } from '@descope/sdk-helpers';\n// eslint-disable-next-line import/no-duplicates\nimport { staticResourcesMixin } from '@descope/sdk-mixins/static-resources-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { themeMixin } from '@descope/sdk-mixins/theme-mixin';\nimport createSdk from '@descope/web-js-sdk';\nimport {\n CONFIG_FILENAME,\n ELEMENTS_TO_IGNORE_ENTER_KEY_ON,\n FETCH_EXCEPTION_ERROR_CODE,\n PREV_VER_ASSETS_FOLDER,\n} from '../constants';\nimport {\n camelCase,\n clearRunIdsFromUrl,\n fetchContent,\n getContentUrl,\n getRunIdsFromUrl,\n handleUrlParams,\n State,\n} from '../helpers';\nimport {\n extractNestedAttribute,\n transformFlowInputFormData,\n} from '../helpers/flowInputs';\nimport { IsChanged } from '../helpers/state';\nimport { formMountMixin } from '../mixins';\nimport {\n AutoFocusOptions,\n DebuggerMessage,\n DebugState,\n DescopeUI,\n FlowConfig,\n FlowState,\n FlowStateUpdateFn,\n FlowStatus,\n ProjectConfiguration,\n SdkConfig,\n} from '../types';\nimport initTemplate from './initTemplate';\n\n// this is replaced in build time\ndeclare const BUILD_VERSION: string;\n\nconst BaseClass = compose(\n themeMixin,\n staticResourcesMixin,\n formMountMixin,\n)(HTMLElement);\n\n// this base class is responsible for WC initialization\nclass BaseDescopeWc extends BaseClass {\n static get observedAttributes() {\n return [\n 'project-id',\n 'flow-id',\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'storage-prefix',\n 'preview',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'keep-last-authenticated-user-after-logout',\n 'validate-on-blur',\n 'style-id',\n ];\n }\n\n // this is a way for extending the sdk config from outside\n static sdkConfigOverrides: Partial<SdkConfig> = {\n baseHeaders: {\n 'x-descope-sdk-name': 'web-component',\n 'x-descope-sdk-version': BUILD_VERSION,\n },\n };\n\n #init = false;\n\n flowStatus: FlowStatus = 'initial';\n\n loggerWrapper = {\n error: (message: string, description = '') => {\n this.logger.error(message, description, new Error());\n this.#updateDebuggerMessages(message, description);\n },\n warn: (message: string, description = '') => {\n this.logger.warn(message, description);\n },\n info: (message: string, description = '', state: any = {}) => {\n this.logger.info(message, description, state);\n },\n debug: (message: string, description = '') => {\n this.logger.debug(message, description);\n },\n };\n\n #flowState = new State<FlowState>();\n\n #debugState = new State<DebugState>();\n\n #componentsContext = {};\n\n getComponentsContext = () => this.#componentsContext;\n\n nextRequestStatus = new State<{ isLoading: boolean }>({ isLoading: false });\n\n rootElement: HTMLDivElement;\n\n contentRootElement: HTMLDivElement;\n\n slotElement: HTMLSlotElement;\n\n #debuggerEle: HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n #eventsCbRefs = {\n popstate: this.#syncStateIdFromUrl.bind(this),\n componentsContext: this.#handleComponentsContext.bind(this),\n };\n\n sdk: ReturnType<typeof createSdk>;\n\n #updateExecState: FlowStateUpdateFn;\n\n descopeUI: Promise<DescopeUI>;\n\n constructor(updateExecState: FlowStateUpdateFn) {\n super();\n this.#updateExecState = updateExecState;\n\n this.#initShadowDom();\n }\n\n #initShadowDom() {\n this.shadowRoot.appendChild(initTemplate.content.cloneNode(true));\n this.slotElement = document.createElement('slot');\n this.slotElement.classList.add('hidden');\n this.rootElement.appendChild(this.slotElement);\n }\n\n get flowId() {\n return this.getAttribute('flow-id');\n }\n\n get client() {\n try {\n return (JSON.parse(this.getAttribute('client')) || {}) as Record<\n string,\n any\n >;\n } catch (e) {\n return {};\n }\n }\n\n get tenantId() {\n return this.getAttribute('tenant') || undefined;\n }\n\n get redirectUrl() {\n return this.getAttribute('redirect-url') || undefined;\n }\n\n get debug() {\n return this.getAttribute('debug') === 'true';\n }\n\n get locale() {\n return this.getAttribute('locale') || undefined;\n }\n\n get autoFocus(): AutoFocusOptions {\n const res = this.getAttribute('auto-focus') ?? 'true';\n if (res === 'skipFirstScreen') {\n return res;\n }\n return res === 'true';\n }\n\n get validateOnBlur() {\n return this.getAttribute('validate-on-blur') === 'true';\n }\n\n get storeLastAuthenticatedUser() {\n const res = this.getAttribute('store-last-authenticated-user') ?? 'true';\n return res === 'true';\n }\n\n get keepLastAuthenticatedUserAfterLogout() {\n const res = this.getAttribute('keep-last-authenticated-user-after-logout');\n return res === 'true';\n }\n\n get storagePrefix() {\n return this.getAttribute('storage-prefix') || '';\n }\n\n get preview() {\n return !!this.getAttribute('preview');\n }\n\n get formConfig() {\n return transformFlowInputFormData(this.form);\n }\n\n get form() {\n return this.getAttribute('form');\n }\n\n get formConfigValues() {\n return extractNestedAttribute(this.formConfig, 'value');\n }\n\n #validateAttrs() {\n const optionalAttributes = [\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'keep-last-authenticated-user-after-logout',\n 'preview',\n 'storage-prefix',\n 'form',\n 'client',\n 'validate-on-blur',\n 'style-id',\n ];\n\n BaseDescopeWc.observedAttributes.forEach((attr: string) => {\n if (!optionalAttributes.includes(attr) && !this[camelCase(attr)])\n throw Error(`${attr} cannot be empty`);\n });\n }\n\n #syncStateIdFromUrl() {\n const { stepId, executionId } = getRunIdsFromUrl(this.flowId);\n this.#flowState.update({ stepId, executionId });\n }\n\n #createSdk(projectId: string, baseUrl: string) {\n this.sdk = createSdk({\n // Use persist tokens options in order to add existing tokens in outgoing requests (if they exists)\n persistTokens: true,\n preview: this.preview,\n storagePrefix: this.storagePrefix,\n storeLastAuthenticatedUser: this.storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout:\n this.keepLastAuthenticatedUserAfterLogout,\n ...BaseDescopeWc.sdkConfigOverrides,\n projectId,\n baseUrl,\n });\n\n // we are wrapping the next & start function so we can indicate the request status\n ['start', 'next'].forEach((key) => {\n const origFn = this.sdk.flow[key];\n\n this.sdk.flow[key] = async (...args: Parameters<typeof origFn>) => {\n try {\n const resp = await origFn(...args);\n return resp;\n } catch (e) {\n // return a generic error object in case of an error\n return {\n error: {\n errorCode: FETCH_EXCEPTION_ERROR_CODE,\n errorDescription: e.toString(),\n },\n };\n }\n };\n });\n }\n\n async #onFlowChange(\n currentState: FlowState,\n _prevState: FlowState,\n isChanged: IsChanged<FlowState>,\n ) {\n const { projectId, baseUrl } = currentState;\n\n const shouldCreateSdkInstance =\n isChanged('projectId') || isChanged('baseUrl');\n\n if (shouldCreateSdkInstance) {\n if (!projectId) return;\n // Initialize the sdk when got a new project id\n this.#createSdk(projectId, baseUrl);\n }\n\n // update runtime state\n this.#updateExecState(currentState);\n }\n\n async #getIsFlowsVersionMismatch() {\n const config = await this.getConfig();\n\n return (\n 'isMissingConfig' in config &&\n config.isMissingConfig &&\n (await this.#isPrevVerConfig())\n );\n }\n\n // we are not using fetchStaticResource here\n // because we do not want to use the fallbacks mechanism\n async #isPrevVerConfig() {\n const prevVerConfigUrl = getContentUrl({\n projectId: this.projectId,\n filename: CONFIG_FILENAME,\n assetsFolder: PREV_VER_ASSETS_FOLDER,\n baseUrl: this.baseStaticUrl,\n });\n try {\n await fetchContent(prevVerConfigUrl, 'json');\n return true;\n } catch (e) {\n return false;\n }\n }\n\n getConfig = async () => (await this.config) || { isMissingConfig: true };\n\n #handleComponentsContext(e: CustomEvent) {\n this.#componentsContext = { ...this.#componentsContext, ...e.detail };\n }\n\n get isRestartOnError() {\n return this.getAttribute('restart-on-error') === 'true';\n }\n\n async getExecutionContext() {\n const config = await this.getConfig();\n return 'executionContext' in config ? config.executionContext : undefined;\n }\n\n #disableDebugger() {\n this.#debuggerEle?.remove();\n this.#debuggerEle = null;\n }\n\n async #handleDebugMode({ isDebug }) {\n if (isDebug) {\n this.#debuggerEle = document.createElement(\n 'descope-debugger',\n ) as HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n Object.assign(this.#debuggerEle.style, {\n position: 'fixed',\n top: '0',\n right: '0',\n height: '100vh',\n width: '100vw',\n pointerEvents: 'none',\n zIndex: 99999,\n });\n\n // we are importing the debugger dynamically so we won't load it when it's not needed\n await import('../debugger-wc');\n\n document.body.appendChild(this.#debuggerEle);\n } else {\n this.#disableDebugger();\n }\n }\n\n #updateDebuggerMessages(title: string, description: string) {\n if (title && this.debug)\n this.#debuggerEle?.updateData({ title, description });\n }\n\n async getProjectConfig(): Promise<ProjectConfiguration> {\n const config = await this.getConfig();\n return 'projectConfig' in config ? config.projectConfig : undefined;\n }\n\n async getFlowConfig(): Promise<FlowConfig> {\n const projectConfig = await this.getProjectConfig();\n\n const flowConfig =\n projectConfig?.flows?.[this.flowId] || ({} as FlowConfig);\n flowConfig.version ??= 0;\n return flowConfig;\n }\n\n async getTargetLocales() {\n const flowConfig = await this.getFlowConfig();\n return (flowConfig?.targetLocales || []).map((locale: string) =>\n locale.toLowerCase(),\n );\n }\n\n #handleKeyPress() {\n // we want to simulate submit when the user presses Enter\n this.rootElement.onkeydown = (e) => {\n // we do not want to submit the form if the focus is on a link element\n const isLinkEleFocused =\n !!this.shadowRoot.activeElement?.getAttribute('href');\n const isIgnoredElementFocused = ELEMENTS_TO_IGNORE_ENTER_KEY_ON.includes(\n this.shadowRoot.activeElement?.localName ?? '',\n );\n\n if (e.key !== 'Enter' || isLinkEleFocused || isIgnoredElementFocused)\n return;\n\n e.preventDefault();\n const buttons: NodeListOf<HTMLButtonElement> =\n this.rootElement.querySelectorAll('descope-button');\n\n // in case there is a single button on the page, click on it\n if (\n buttons.length === 1 &&\n buttons[0].getAttribute('auto-submit') !== 'false'\n ) {\n buttons[0].click();\n return;\n }\n\n const autoSubmitButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('auto-submit') === 'true',\n );\n if (autoSubmitButtons.length === 1) {\n autoSubmitButtons[0].click();\n return;\n }\n\n const genericButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'button',\n );\n\n // in case there is a single \"generic\" button on the page, click on it\n if (genericButtons.length === 1) {\n if (genericButtons[0].getAttribute('auto-submit') !== 'false') {\n genericButtons[0].click();\n }\n } else if (genericButtons.length === 0) {\n const ssoButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'sso',\n );\n\n // in case there is a single \"sso\" button on the page, click on it\n if (ssoButtons.length === 1) {\n if (ssoButtons[0].getAttribute('auto-submit') !== 'false') {\n ssoButtons[0].click();\n }\n }\n }\n };\n }\n\n async getComponentsVersion() {\n const config = await this.getConfig();\n const version =\n 'projectConfig' in config ? config.projectConfig?.componentsVersion : {};\n\n if (version) return version;\n\n this.logger.error('Did not get components version, using latest version');\n\n return 'latest';\n }\n\n static descopeUI: any;\n\n async init() {\n this.flowStatus = 'loading';\n ['ready', 'error', 'success'].forEach((status: FlowStatus) =>\n this.addEventListener(status, () => {\n this.flowStatus = status;\n }),\n );\n\n await super.init?.();\n this.#debugState.subscribe(this.#handleDebugMode.bind(this));\n this.#debugState.update({ isDebug: this.debug });\n\n this.#validateAttrs();\n\n if (await this.#getIsFlowsVersionMismatch()) {\n this.loggerWrapper.error(\n 'This SDK version does not support your flows version',\n 'Make sure to upgrade your flows to the latest version or use an older SDK version',\n );\n\n return;\n }\n\n const config = await this.getConfig();\n if ('isMissingConfig' in config && config.isMissingConfig) {\n this.loggerWrapper.error(\n 'Cannot get config file',\n 'Make sure that your projectId & flowId are correct',\n );\n\n return;\n }\n\n this.#handleKeyPress();\n\n const {\n executionId,\n stepId,\n token,\n code,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ssoQueryParams,\n } = handleUrlParams(this.flowId, this.loggerWrapper);\n\n // we want to update the state when user clicks on back in the browser\n window.addEventListener('popstate', this.#eventsCbRefs.popstate);\n\n // adding event to listen to events coming from components (e.g. recaptcha risk token) that want to add data to the context\n // this data will be sent to the server on the next request\n window.addEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n\n this.#flowState.subscribe(this.#onFlowChange.bind(this));\n\n this.#flowState.update({\n projectId: this.projectId,\n flowId: this.flowId,\n baseUrl: this.baseUrl,\n tenant: this.tenantId,\n redirectUrl: this.redirectUrl,\n locale: this.locale,\n stepId,\n executionId,\n token,\n code,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ...ssoQueryParams,\n });\n\n this.#init = true;\n }\n\n disconnectedCallback() {\n this.#flowState.unsubscribeAll();\n this.#debugState.unsubscribeAll();\n this.#disableDebugger();\n window.removeEventListener('popstate', this.#eventsCbRefs.popstate);\n window.removeEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n }\n\n attributeChangedCallback(\n attrName: string,\n oldValue: string,\n newValue: string,\n ) {\n if (!this.shadowRoot.isConnected || !this.#init) return;\n\n if (\n oldValue !== newValue &&\n BaseDescopeWc.observedAttributes.includes(attrName)\n ) {\n this.#validateAttrs();\n\n const isInitialRun = oldValue === null;\n\n this.#flowState.update(({ stepId, executionId }) => {\n let newStepId = stepId;\n let newExecutionId = executionId;\n\n // If not initial run and we got a new project/flow, we want to restart the step\n if (!isInitialRun) {\n newExecutionId = null;\n newStepId = null;\n clearRunIdsFromUrl();\n }\n\n return {\n [camelCase(attrName)]: newValue,\n stepId: newStepId,\n executionId: newExecutionId,\n };\n });\n\n this.#debugState.update({ isDebug: this.debug });\n }\n }\n}\n\nexport default BaseDescopeWc;\n"],"names":["BaseClass","compose","themeMixin","staticResourcesMixin","formMountMixin","HTMLElement","BaseDescopeWc","observedAttributes","constructor","updateExecState","super","_BaseDescopeWc_init","set","this","flowStatus","loggerWrapper","error","message","description","logger","Error","__classPrivateFieldGet","call","warn","info","state","debug","_BaseDescopeWc_flowState","State","_BaseDescopeWc_debugState","_BaseDescopeWc_componentsContext","getComponentsContext","nextRequestStatus","isLoading","_BaseDescopeWc_debuggerEle","_BaseDescopeWc_eventsCbRefs","popstate","_BaseDescopeWc_instances","_BaseDescopeWc_syncStateIdFromUrl","bind","componentsContext","_BaseDescopeWc_handleComponentsContext","_BaseDescopeWc_updateExecState","getConfig","config","isMissingConfig","__classPrivateFieldSet","_BaseDescopeWc_initShadowDom","flowId","getAttribute","client","JSON","parse","e","tenantId","undefined","redirectUrl","locale","autoFocus","res","_b","validateOnBlur","storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout","storagePrefix","preview","formConfig","transformFlowInputFormData","form","formConfigValues","extractNestedAttribute","isRestartOnError","getExecutionContext","executionContext","getProjectConfig","projectConfig","getFlowConfig","flowConfig","flows","_c","version","getTargetLocales","targetLocales","map","toLowerCase","getComponentsVersion","componentsVersion","init","forEach","status","addEventListener","_super","subscribe","_BaseDescopeWc_handleDebugMode","update","isDebug","_BaseDescopeWc_validateAttrs","_BaseDescopeWc_getIsFlowsVersionMismatch","_BaseDescopeWc_handleKeyPress","executionId","stepId","token","code","exchangeError","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthCodeChallenge","redirectAuthInitiator","ssoQueryParams","handleUrlParams","window","_BaseDescopeWc_onFlowChange","Object","assign","projectId","baseUrl","tenant","disconnectedCallback","unsubscribeAll","_BaseDescopeWc_disableDebugger","removeEventListener","attributeChangedCallback","attrName","oldValue","newValue","shadowRoot","isConnected","_a","includes","isInitialRun","newStepId","newExecutionId","clearRunIdsFromUrl","camelCase","appendChild","initTemplate","content","cloneNode","slotElement","document","createElement","classList","add","rootElement","optionalAttributes","attr","getRunIdsFromUrl","_BaseDescopeWc_createSdk","sdk","createSdk","persistTokens","sdkConfigOverrides","key","origFn","flow","args","__awaiter","errorCode","FETCH_EXCEPTION_ERROR_CODE","errorDescription","toString","currentState","_prevState","isChanged","_BaseDescopeWc_isPrevVerConfig","prevVerConfigUrl","getContentUrl","filename","CONFIG_FILENAME","assetsFolder","PREV_VER_ASSETS_FOLDER","baseStaticUrl","fetchContent","detail","remove","arguments","style","position","top","right","height","width","pointerEvents","zIndex","Promise","resolve","then","_interopNamespaceDefaultOnly","require","body","_BaseDescopeWc_updateDebuggerMessages","title","updateData","onkeydown","isLinkEleFocused","activeElement","isIgnoredElementFocused","ELEMENTS_TO_IGNORE_ENTER_KEY_ON","localName","_d","preventDefault","buttons","querySelectorAll","length","click","autoSubmitButtons","Array","from","filter","button","genericButtons","ssoButtons","baseHeaders"],"mappings":"8pBA4CA,MAAMA,EAAYC,EAAOA,QACvBC,EAAUA,WACVC,EAAoBA,qBACpBC,EAAcA,eAHEH,CAIhBI,aAGF,MAAMC,UAAsBN,EAC1B,6BAAWO,GACT,MAAO,CACL,aACA,UACA,WACA,SACA,SACA,QACA,iBACA,UACA,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,OAEpB,YADAE,EAAkB,GAAGD,QAIvB,MAAMM,EAAiBJ,MAAMC,KAAKN,GAASO,QACxCC,GAAgD,WAArCA,EAAOhK,aAAa,eAIlC,GAA8B,IAA1BiK,EAAeP,OACqC,UAAlDO,EAAe,GAAGjK,aAAa,gBACjCiK,EAAe,GAAGN,aAEf,GAA8B,IAA1BM,EAAeP,OAAc,CACtC,MAAMQ,EAAaL,MAAMC,KAAKN,GAASO,QACpCC,GAAgD,QAArCA,EAAOhK,aAAa,eAIR,IAAtBkK,EAAWR,QACqC,UAA9CQ,EAAW,GAAGlK,aAAa,gBAC7BkK,EAAW,GAAGP,OAGnB,EAEL,EAjYOtM,EAAAiJ,mBAAyC,CAC9C6D,YAAa,CACX,qBAAsB,gBACtB,wBAAyB"}
1
+ {"version":3,"file":"BaseDescopeWc.js","sources":["../../../src/lib/descope-wc/BaseDescopeWc.ts"],"sourcesContent":["import { compose } from '@descope/sdk-helpers';\n// eslint-disable-next-line import/no-duplicates\nimport { staticResourcesMixin } from '@descope/sdk-mixins/static-resources-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { themeMixin } from '@descope/sdk-mixins/theme-mixin';\nimport createSdk from '@descope/web-js-sdk';\nimport {\n CONFIG_FILENAME,\n ELEMENTS_TO_IGNORE_ENTER_KEY_ON,\n FETCH_EXCEPTION_ERROR_CODE,\n PREV_VER_ASSETS_FOLDER,\n} from '../constants';\nimport {\n camelCase,\n clearRunIdsFromUrl,\n fetchContent,\n getContentUrl,\n getRunIdsFromUrl,\n handleUrlParams,\n State,\n} from '../helpers';\nimport {\n extractNestedAttribute,\n transformFlowInputFormData,\n} from '../helpers/flowInputs';\nimport { IsChanged } from '../helpers/state';\nimport { formMountMixin } from '../mixins';\nimport {\n AutoFocusOptions,\n DebuggerMessage,\n DebugState,\n DescopeUI,\n FlowConfig,\n FlowState,\n FlowStateUpdateFn,\n FlowStatus,\n ProjectConfiguration,\n SdkConfig,\n} from '../types';\nimport initTemplate from './initTemplate';\n\n// this is replaced in build time\ndeclare const BUILD_VERSION: string;\n\nconst BaseClass = compose(\n themeMixin,\n staticResourcesMixin,\n formMountMixin,\n)(HTMLElement);\n\n// this base class is responsible for WC initialization\nclass BaseDescopeWc extends BaseClass {\n static get observedAttributes() {\n return [\n 'project-id',\n 'flow-id',\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'storage-prefix',\n 'preview',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'refresh-cookie-name',\n 'keep-last-authenticated-user-after-logout',\n 'validate-on-blur',\n 'style-id',\n ];\n }\n\n // this is a way for extending the sdk config from outside\n static sdkConfigOverrides: Partial<SdkConfig> = {\n baseHeaders: {\n 'x-descope-sdk-name': 'web-component',\n 'x-descope-sdk-version': BUILD_VERSION,\n },\n };\n\n #init = false;\n\n flowStatus: FlowStatus = 'initial';\n\n loggerWrapper = {\n error: (message: string, description = '') => {\n this.logger.error(message, description, new Error());\n this.#updateDebuggerMessages(message, description);\n },\n warn: (message: string, description = '') => {\n this.logger.warn(message, description);\n },\n info: (message: string, description = '', state: any = {}) => {\n this.logger.info(message, description, state);\n },\n debug: (message: string, description = '') => {\n this.logger.debug(message, description);\n },\n };\n\n #flowState = new State<FlowState>();\n\n #debugState = new State<DebugState>();\n\n #componentsContext = {};\n\n getComponentsContext = () => this.#componentsContext;\n\n nextRequestStatus = new State<{ isLoading: boolean }>({ isLoading: false });\n\n rootElement: HTMLDivElement;\n\n contentRootElement: HTMLDivElement;\n\n slotElement: HTMLSlotElement;\n\n #debuggerEle: HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n #eventsCbRefs = {\n popstate: this.#syncStateIdFromUrl.bind(this),\n componentsContext: this.#handleComponentsContext.bind(this),\n };\n\n sdk: ReturnType<typeof createSdk>;\n\n #updateExecState: FlowStateUpdateFn;\n\n descopeUI: Promise<DescopeUI>;\n\n constructor(updateExecState: FlowStateUpdateFn) {\n super();\n this.#updateExecState = updateExecState;\n\n this.#initShadowDom();\n }\n\n #initShadowDom() {\n this.shadowRoot.appendChild(initTemplate.content.cloneNode(true));\n this.slotElement = document.createElement('slot');\n this.slotElement.classList.add('hidden');\n this.rootElement.appendChild(this.slotElement);\n }\n\n get flowId() {\n return this.getAttribute('flow-id');\n }\n\n get client() {\n try {\n return (JSON.parse(this.getAttribute('client')) || {}) as Record<\n string,\n any\n >;\n } catch (e) {\n return {};\n }\n }\n\n get tenantId() {\n return this.getAttribute('tenant') || undefined;\n }\n\n get redirectUrl() {\n return this.getAttribute('redirect-url') || undefined;\n }\n\n get debug() {\n return this.getAttribute('debug') === 'true';\n }\n\n get locale() {\n return this.getAttribute('locale') || undefined;\n }\n\n get autoFocus(): AutoFocusOptions {\n const res = this.getAttribute('auto-focus') ?? 'true';\n if (res === 'skipFirstScreen') {\n return res;\n }\n return res === 'true';\n }\n\n get validateOnBlur() {\n return this.getAttribute('validate-on-blur') === 'true';\n }\n\n get storeLastAuthenticatedUser() {\n const res = this.getAttribute('store-last-authenticated-user') ?? 'true';\n return res === 'true';\n }\n\n get refreshCookieName() {\n return this.getAttribute('refresh-cookie-name') || '';\n }\n\n get keepLastAuthenticatedUserAfterLogout() {\n const res = this.getAttribute('keep-last-authenticated-user-after-logout');\n return res === 'true';\n }\n\n get storagePrefix() {\n return this.getAttribute('storage-prefix') || '';\n }\n\n get preview() {\n return !!this.getAttribute('preview');\n }\n\n get formConfig() {\n return transformFlowInputFormData(this.form);\n }\n\n get form() {\n return this.getAttribute('form');\n }\n\n get formConfigValues() {\n return extractNestedAttribute(this.formConfig, 'value');\n }\n\n #validateAttrs() {\n const optionalAttributes = [\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'refresh-cookie-name',\n 'keep-last-authenticated-user-after-logout',\n 'preview',\n 'storage-prefix',\n 'form',\n 'client',\n 'validate-on-blur',\n 'style-id',\n ];\n\n BaseDescopeWc.observedAttributes.forEach((attr: string) => {\n if (!optionalAttributes.includes(attr) && !this[camelCase(attr)])\n throw Error(`${attr} cannot be empty`);\n });\n }\n\n #syncStateIdFromUrl() {\n const { stepId, executionId } = getRunIdsFromUrl(this.flowId);\n this.#flowState.update({ stepId, executionId });\n }\n\n #createSdk(projectId: string, baseUrl: string) {\n this.sdk = createSdk({\n // Use persist tokens options in order to add existing tokens in outgoing requests (if they exists)\n persistTokens: true,\n preview: this.preview,\n storagePrefix: this.storagePrefix,\n storeLastAuthenticatedUser: this.storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout:\n this.keepLastAuthenticatedUserAfterLogout,\n refreshCookieName: this.refreshCookieName,\n ...BaseDescopeWc.sdkConfigOverrides,\n projectId,\n baseUrl,\n });\n\n // we are wrapping the next & start function so we can indicate the request status\n ['start', 'next'].forEach((key) => {\n const origFn = this.sdk.flow[key];\n\n this.sdk.flow[key] = async (...args: Parameters<typeof origFn>) => {\n try {\n const resp = await origFn(...args);\n return resp;\n } catch (e) {\n // return a generic error object in case of an error\n return {\n error: {\n errorCode: FETCH_EXCEPTION_ERROR_CODE,\n errorDescription: e.toString(),\n },\n };\n }\n };\n });\n }\n\n async #onFlowChange(\n currentState: FlowState,\n _prevState: FlowState,\n isChanged: IsChanged<FlowState>,\n ) {\n const { projectId, baseUrl } = currentState;\n\n const shouldCreateSdkInstance =\n isChanged('projectId') || isChanged('baseUrl');\n\n if (shouldCreateSdkInstance) {\n if (!projectId) return;\n // Initialize the sdk when got a new project id\n this.#createSdk(projectId, baseUrl);\n }\n\n // update runtime state\n this.#updateExecState(currentState);\n }\n\n async #getIsFlowsVersionMismatch() {\n const config = await this.getConfig();\n\n return (\n 'isMissingConfig' in config &&\n config.isMissingConfig &&\n (await this.#isPrevVerConfig())\n );\n }\n\n // we are not using fetchStaticResource here\n // because we do not want to use the fallbacks mechanism\n async #isPrevVerConfig() {\n const prevVerConfigUrl = getContentUrl({\n projectId: this.projectId,\n filename: CONFIG_FILENAME,\n assetsFolder: PREV_VER_ASSETS_FOLDER,\n baseUrl: this.baseStaticUrl,\n });\n try {\n await fetchContent(prevVerConfigUrl, 'json');\n return true;\n } catch (e) {\n return false;\n }\n }\n\n getConfig = async () => (await this.config) || { isMissingConfig: true };\n\n #handleComponentsContext(e: CustomEvent) {\n this.#componentsContext = { ...this.#componentsContext, ...e.detail };\n }\n\n get isRestartOnError() {\n return this.getAttribute('restart-on-error') === 'true';\n }\n\n async getExecutionContext() {\n const config = await this.getConfig();\n return 'executionContext' in config ? config.executionContext : undefined;\n }\n\n #disableDebugger() {\n this.#debuggerEle?.remove();\n this.#debuggerEle = null;\n }\n\n async #handleDebugMode({ isDebug }) {\n if (isDebug) {\n this.#debuggerEle = document.createElement(\n 'descope-debugger',\n ) as HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n Object.assign(this.#debuggerEle.style, {\n position: 'fixed',\n top: '0',\n right: '0',\n height: '100vh',\n width: '100vw',\n pointerEvents: 'none',\n zIndex: 99999,\n });\n\n // we are importing the debugger dynamically so we won't load it when it's not needed\n await import('../debugger-wc');\n\n document.body.appendChild(this.#debuggerEle);\n } else {\n this.#disableDebugger();\n }\n }\n\n #updateDebuggerMessages(title: string, description: string) {\n if (title && this.debug)\n this.#debuggerEle?.updateData({ title, description });\n }\n\n async getProjectConfig(): Promise<ProjectConfiguration> {\n const config = await this.getConfig();\n return 'projectConfig' in config ? config.projectConfig : undefined;\n }\n\n async getFlowConfig(): Promise<FlowConfig> {\n const projectConfig = await this.getProjectConfig();\n\n const flowConfig =\n projectConfig?.flows?.[this.flowId] || ({} as FlowConfig);\n flowConfig.version ??= 0;\n return flowConfig;\n }\n\n async getTargetLocales() {\n const flowConfig = await this.getFlowConfig();\n return (flowConfig?.targetLocales || []).map((locale: string) =>\n locale.toLowerCase(),\n );\n }\n\n #handleKeyPress() {\n // we want to simulate submit when the user presses Enter\n this.rootElement.onkeydown = (e) => {\n // we do not want to submit the form if the focus is on a link element\n const isLinkEleFocused =\n !!this.shadowRoot.activeElement?.getAttribute('href');\n const isIgnoredElementFocused = ELEMENTS_TO_IGNORE_ENTER_KEY_ON.includes(\n this.shadowRoot.activeElement?.localName ?? '',\n );\n\n if (e.key !== 'Enter' || isLinkEleFocused || isIgnoredElementFocused)\n return;\n\n e.preventDefault();\n const buttons: NodeListOf<HTMLButtonElement> =\n this.rootElement.querySelectorAll('descope-button');\n\n // in case there is a single button on the page, click on it\n if (\n buttons.length === 1 &&\n buttons[0].getAttribute('auto-submit') !== 'false'\n ) {\n buttons[0].click();\n return;\n }\n\n const autoSubmitButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('auto-submit') === 'true',\n );\n if (autoSubmitButtons.length === 1) {\n autoSubmitButtons[0].click();\n return;\n }\n\n const genericButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'button',\n );\n\n // in case there is a single \"generic\" button on the page, click on it\n if (genericButtons.length === 1) {\n if (genericButtons[0].getAttribute('auto-submit') !== 'false') {\n genericButtons[0].click();\n }\n } else if (genericButtons.length === 0) {\n const ssoButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'sso',\n );\n\n // in case there is a single \"sso\" button on the page, click on it\n if (ssoButtons.length === 1) {\n if (ssoButtons[0].getAttribute('auto-submit') !== 'false') {\n ssoButtons[0].click();\n }\n }\n }\n };\n }\n\n async getComponentsVersion() {\n const config = await this.getConfig();\n const version =\n 'projectConfig' in config ? config.projectConfig?.componentsVersion : {};\n\n if (version) return version;\n\n this.logger.error('Did not get components version, using latest version');\n\n return 'latest';\n }\n\n static descopeUI: any;\n\n async init() {\n this.flowStatus = 'loading';\n ['ready', 'error', 'success'].forEach((status: FlowStatus) =>\n this.addEventListener(status, () => {\n this.flowStatus = status;\n }),\n );\n\n await super.init?.();\n this.#debugState.subscribe(this.#handleDebugMode.bind(this));\n this.#debugState.update({ isDebug: this.debug });\n\n this.#validateAttrs();\n\n if (await this.#getIsFlowsVersionMismatch()) {\n this.loggerWrapper.error(\n 'This SDK version does not support your flows version',\n 'Make sure to upgrade your flows to the latest version or use an older SDK version',\n );\n\n return;\n }\n\n const config = await this.getConfig();\n if ('isMissingConfig' in config && config.isMissingConfig) {\n this.loggerWrapper.error(\n 'Cannot get config file',\n 'Make sure that your projectId & flowId are correct',\n );\n\n return;\n }\n\n this.#handleKeyPress();\n\n const {\n executionId,\n stepId,\n token,\n code,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ssoQueryParams,\n } = handleUrlParams(this.flowId, this.loggerWrapper);\n\n // we want to update the state when user clicks on back in the browser\n window.addEventListener('popstate', this.#eventsCbRefs.popstate);\n\n // adding event to listen to events coming from components (e.g. recaptcha risk token) that want to add data to the context\n // this data will be sent to the server on the next request\n window.addEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n\n this.#flowState.subscribe(this.#onFlowChange.bind(this));\n\n this.#flowState.update({\n projectId: this.projectId,\n flowId: this.flowId,\n baseUrl: this.baseUrl,\n tenant: this.tenantId,\n redirectUrl: this.redirectUrl,\n locale: this.locale,\n stepId,\n executionId,\n token,\n code,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ...ssoQueryParams,\n });\n\n this.#init = true;\n }\n\n disconnectedCallback() {\n this.#flowState.unsubscribeAll();\n this.#debugState.unsubscribeAll();\n this.#disableDebugger();\n window.removeEventListener('popstate', this.#eventsCbRefs.popstate);\n window.removeEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n }\n\n attributeChangedCallback(\n attrName: string,\n oldValue: string,\n newValue: string,\n ) {\n if (!this.shadowRoot.isConnected || !this.#init) return;\n\n if (\n oldValue !== newValue &&\n BaseDescopeWc.observedAttributes.includes(attrName)\n ) {\n this.#validateAttrs();\n\n const isInitialRun = oldValue === null;\n\n this.#flowState.update(({ stepId, executionId }) => {\n let newStepId = stepId;\n let newExecutionId = executionId;\n\n // If not initial run and we got a new project/flow, we want to restart the step\n if (!isInitialRun) {\n newExecutionId = null;\n newStepId = null;\n clearRunIdsFromUrl();\n }\n\n return {\n [camelCase(attrName)]: newValue,\n stepId: newStepId,\n executionId: newExecutionId,\n };\n });\n\n this.#debugState.update({ isDebug: this.debug });\n }\n }\n}\n\nexport default BaseDescopeWc;\n"],"names":["BaseClass","compose","themeMixin","staticResourcesMixin","formMountMixin","HTMLElement","BaseDescopeWc","observedAttributes","constructor","updateExecState","super","_BaseDescopeWc_init","set","this","flowStatus","loggerWrapper","error","message","description","logger","Error","__classPrivateFieldGet","call","warn","info","state","debug","_BaseDescopeWc_flowState","State","_BaseDescopeWc_debugState","_BaseDescopeWc_componentsContext","getComponentsContext","nextRequestStatus","isLoading","_BaseDescopeWc_debuggerEle","_BaseDescopeWc_eventsCbRefs","popstate","_BaseDescopeWc_instances","_BaseDescopeWc_syncStateIdFromUrl","bind","componentsContext","_BaseDescopeWc_handleComponentsContext","_BaseDescopeWc_updateExecState","getConfig","config","isMissingConfig","__classPrivateFieldSet","_BaseDescopeWc_initShadowDom","flowId","getAttribute","client","JSON","parse","e","tenantId","undefined","redirectUrl","locale","autoFocus","res","_b","validateOnBlur","storeLastAuthenticatedUser","refreshCookieName","keepLastAuthenticatedUserAfterLogout","storagePrefix","preview","formConfig","transformFlowInputFormData","form","formConfigValues","extractNestedAttribute","isRestartOnError","getExecutionContext","executionContext","getProjectConfig","projectConfig","getFlowConfig","flowConfig","flows","_c","version","getTargetLocales","targetLocales","map","toLowerCase","getComponentsVersion","componentsVersion","init","forEach","status","addEventListener","_super","subscribe","_BaseDescopeWc_handleDebugMode","update","isDebug","_BaseDescopeWc_validateAttrs","_BaseDescopeWc_getIsFlowsVersionMismatch","_BaseDescopeWc_handleKeyPress","executionId","stepId","token","code","exchangeError","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthCodeChallenge","redirectAuthInitiator","ssoQueryParams","handleUrlParams","window","_BaseDescopeWc_onFlowChange","Object","assign","projectId","baseUrl","tenant","disconnectedCallback","unsubscribeAll","_BaseDescopeWc_disableDebugger","removeEventListener","attributeChangedCallback","attrName","oldValue","newValue","shadowRoot","isConnected","_a","includes","isInitialRun","newStepId","newExecutionId","clearRunIdsFromUrl","camelCase","appendChild","initTemplate","content","cloneNode","slotElement","document","createElement","classList","add","rootElement","optionalAttributes","attr","getRunIdsFromUrl","_BaseDescopeWc_createSdk","sdk","createSdk","persistTokens","sdkConfigOverrides","key","origFn","flow","args","__awaiter","errorCode","FETCH_EXCEPTION_ERROR_CODE","errorDescription","toString","currentState","_prevState","isChanged","_BaseDescopeWc_isPrevVerConfig","prevVerConfigUrl","getContentUrl","filename","CONFIG_FILENAME","assetsFolder","PREV_VER_ASSETS_FOLDER","baseStaticUrl","fetchContent","detail","remove","arguments","style","position","top","right","height","width","pointerEvents","zIndex","Promise","resolve","then","_interopNamespaceDefaultOnly","require","body","_BaseDescopeWc_updateDebuggerMessages","title","updateData","onkeydown","isLinkEleFocused","activeElement","isIgnoredElementFocused","ELEMENTS_TO_IGNORE_ENTER_KEY_ON","localName","_d","preventDefault","buttons","querySelectorAll","length","click","autoSubmitButtons","Array","from","filter","button","genericButtons","ssoButtons","baseHeaders"],"mappings":"8pBA4CA,MAAMA,EAAYC,EAAOA,QACvBC,EAAUA,WACVC,EAAoBA,qBACpBC,EAAcA,eAHEH,CAIhBI,aAGF,MAAMC,UAAsBN,EAC1B,6BAAWO,GACT,MAAO,CACL,aACA,UACA,WACA,SACA,SACA,QACA,iBACA,UACA,eACA,aACA,gCACA,sBACA,4CACA,mBACA,WAEH,CA6DD,WAAAC,CAAYC,GACVC,oBApDFC,EAAAC,IAAAC,MAAQ,GAERA,KAAUC,WAAe,UAEzBD,KAAAE,cAAgB,CACdC,MAAO,CAACC,EAAiBC,EAAc,MACrCL,KAAKM,OAAOH,MAAMC,EAASC,EAAa,IAAIE,OAC5CC,yBAAAR,cAAAS,KA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AAlDO,EAAe,GAAGlK,aAAa,gBACjCkK,EAAe,GAAGN,aAEf,GAA8B,IAA1BM,EAAeP,OAAc,CACtC,MAAMQ,EAAaL,MAAMC,KAAKN,GAASO,QACpCC,GAAgD,QAArCA,EAAOjK,aAAa,eAIR,IAAtBmK,EAAWR,QACqC,UAA9CQ,EAAW,GAAGnK,aAAa,gBAC7BmK,EAAW,GAAGP,OAGnB,EAEL,EAvYOvM,EAAAkJ,mBAAyC,CAC9C6D,YAAa,CACX,qBAAsB,gBACtB,wBAAyB"}
@@ -1,2 +1,2 @@
1
- "use strict";var e,t,i,s,r,o,n,a,l,d,c,h,u,p,g,v,m,f,_,b,S,w,I,E,R,y,C,P=require("tslib"),O=require("@descope/web-js-sdk"),F=require("../constants/index.js"),T=require("../helpers/helpers.js"),A=require("../helpers/state.js"),k=require("../helpers/templates.js"),N=require("../helpers/webauthn.js"),U=require("../helpers/abTestingKey.js"),W=require("../helpers/conditions.js"),j=require("../helpers/lastAuth.js"),x=require("../types.js"),G=require("./BaseDescopeWc.js"),L=require("./sdkScripts/index.js"),D=require("../constants/general.js");t=new WeakMap,i=new WeakMap,s=new WeakMap,r=new WeakMap,l=new WeakMap,d=new WeakMap,c=new WeakMap,h=new WeakMap,u=new WeakMap,I=new WeakMap,e=new WeakSet,o=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},n=function(){return P.__awaiter(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")}))},a=function(t){return P.__awaiter(this,void 0,void 0,(function*(){var i;const s=Object.assign(Object.assign({},this.stepState.current),t),{next:r,stepName:o}=s,n=P.__rest(s,["next","stepName"]),a=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,o,T.transformStepStateForCustomScreen(n),r,this));if(a){this.loggerWrapper.debug("Rendering a custom screen"),this.contentRootElement.innerHTML="",P.__classPrivateFieldGet(this,e,"m",v).call(this,{isFirstScreen:!this.stepState.current.htmlFilename,stepName:t.stepName}),this.stepState.unsubscribeAll();const i=this.stepState.subscribe((()=>{var e;this.stepState.unsubscribe(i),null===(e=this.stepState)||void 0===e||e.subscribe(this.onStepChange.bind(this))}))}P.__classPrivateFieldGet(this,l,"f").call(this,a),this.flowState.forceUpdate=a}))},p=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)}))}},g=function(t,s){return P.__awaiter(this,void 0,void 0,(function*(){var r;null===(r=P.__classPrivateFieldGet(this,i,"f"))||void 0===r||r.abort();const o=t.querySelector('*[autocomplete="webauthn"]');if(o&&(yield N.isConditionalLoginSupported())){const{options:t,transactionId:r}=(yield P.__classPrivateFieldGet(this,u,"f").call(this))||{};t&&r&&(P.__classPrivateFieldGet(this,e,"m",p).call(this,o),P.__classPrivateFieldSet(this,i,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(t,P.__classPrivateFieldGet(this,i,"f")).then((e=>P.__awaiter(this,void 0,void 0,(function*(){s(o.id,{transactionId:r,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},v=function({isFirstScreen:t,stepName:i}){t&&P.__classPrivateFieldGet(this,e,"m",C).call(this,"ready",{}),P.__classPrivateFieldGet(this,e,"m",C).call(this,"page-updated",{screenName:i}),P.__classPrivateFieldGet(this,e,"m",C).call(this,"screen-updated",{screenName:i})},m=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"!==t.localName&&(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},f=function(){return P.__awaiter(this,void 0,void 0,(function*(){const e=Array.from(this.shadowRoot.querySelectorAll(`*[name]:not([${F.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`));return(yield Promise.all(e.map((e=>P.__awaiter(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})),{})}))},_=function(e){const t=this.nextRequestStatus.subscribe((({isLoading:i})=>{i?e.setAttribute("loading","true"):(this.nextRequestStatus.unsubscribe(t),e.removeAttribute("loading"))}))},b=function(e={}){var t,i;const s=T.getFirstNonEmptyValue(e,["externalId","email","phone"]),r=T.getFirstNonEmptyValue(e,["newPassword","password"]);if(s&&r)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:r});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)}},S=function(){T.clearPreviousExternalInputs();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>P.__classPrivateFieldGet(this,e,"m",w).call(this,t)))},w=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const i=t.getAttribute("slot"),s=`input-${e.id}-${i}`,r=document.createElement("slot");r.setAttribute("name",s),r.setAttribute("slot",i),e.appendChild(r),t.setAttribute("slot",s),this.appendChild(t)}))},E=function(e){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((t=>{t.addEventListener("input",(()=>{var i;(null===(i=t.checkValidity)||void 0===i?void 0:i.call(t))&&P.__classPrivateFieldGet(this,I,"f").call(this,t,e)}))}))},R=function(t){this.contentRootElement.querySelectorAll(`descope-button:not([${F.DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON}])`).forEach((e=>{e.onclick=()=>{P.__classPrivateFieldGet(this,I,"f").call(this,e,t)}})),P.__classPrivateFieldGet(this,e,"m",E).call(this,t)},y=function(e,t){this.contentRootElement.addEventListener("transitionend",(()=>{this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0});const i=t===x.Direction.forward?"slide-forward":"slide-backward";Array.from(this.contentRootElement.getElementsByClassName("input-container")).forEach(((e,t)=>{e.style["transition-delay"]=40*t+"ms",e.classList.add(i)})),this.contentRootElement.classList.add("fade-out")},C=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},module.exports=class extends G{static set sdkConfigOverrides(e){G.sdkConfigOverrides=e}static get sdkConfigOverrides(){return G.sdkConfigOverrides}constructor(){const a=new A({deferredRedirect:!1});super(a.update.bind(a)),e.add(this),this.stepState=new A({},{forceUpdate:!0}),t.set(this,void 0),i.set(this,null),s.set(this,null),r.set(this,{visibilitychange:P.__classPrivateFieldGet(this,e,"m",o).bind(this)}),this.bridgeVersion=1,this.nativeResume=(e,t)=>{var i;const s=JSON.parse(t);if(this.logger.info(`nativeResume received payload of type '${e}'`),"oauthWeb"===e||"sso"===e){let{exchangeCode:e}=s;if(!e){e=null===(i=new URL(s.url).searchParams)||void 0===i?void 0:i.get(F.URL_CODE_PARAM_NAME)}this.nativeComplete({exchangeCode:e,idpInitiated:!0})}else if("magicLink"===e){const e=new URL(s.url),t=e.searchParams.get(F.URL_TOKEN_PARAM_NAME),i=e.searchParams.get(F.URL_RUN_IDS_PARAM_NAME).split("_").pop();P.__classPrivateFieldGet(this,c,"f").call(this),this.flowState.update({token:t,stepId:i,action:void 0})}else this.nativeComplete(s)},l.set(this,(e=>{this.contentRootElement.classList.toggle("hidden",e),this.slotElement.classList.toggle("hidden",!e)})),d.set(this,((e,i,s,r,o=!1)=>{if(this.flowState.current.action===F.RESPONSE_ACTIONS.poll){this.logger.debug("polling - Scheduling polling request");const n=Date.now(),a=o?500:2e3;P.__classPrivateFieldSet(this,t,setTimeout((()=>P.__awaiter(this,void 0,void 0,(function*(){var t;this.logger.debug("polling - Calling next");const l=this.sdk.flow.next(e,i,F.CUSTOM_INTERACTIONS.polling,s,r,{}),c=document.hidden&&!o&&Date.now()-n>a+500;let u;c&&this.logger.debug("polling - The polling seems to be throttled");try{const e=c?1e3:6e3;u=yield T.timeoutPromise(e,l)}catch(t){return this.logger.warn(`polling - The ${c?"throttled fetch":"fetch"} call timed out or was aborted`),void P.__classPrivateFieldGet(this,d,"f").call(this,e,i,s,r,c)}if((null===(t=null==u?void 0:u.error)||void 0===t?void 0:t.errorCode)===D.FETCH_EXCEPTION_ERROR_CODE)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void P.__classPrivateFieldGet(this,d,"f").call(this,e,i,s,r);this.logger.debug("polling - Got a response"),(null==u?void 0:u.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(u.error,null,4)),P.__classPrivateFieldGet(this,h,"f").call(this,u),P.__classPrivateFieldGet(this,d,"f").call(this,e,i,s,r)}))),a),"f")}})),c.set(this,(()=>{clearTimeout(P.__classPrivateFieldGet(this,t,"f")),P.__classPrivateFieldSet(this,t,null,"f")})),h.set(this,(t=>{var i,r,o,a,l,d,c,h,u,p,g,v,m;if(!(null==t?void 0:t.ok)){const s=null===(i=null==t?void 0:t.response)||void 0===i?void 0:i.url,c=`${null===(r=null==t?void 0:t.response)||void 0===r?void 0:r.status} - ${null===(o=null==t?void 0:t.response)||void 0===o?void 0:o.statusText}`;P.__classPrivateFieldGet(this,e,"m",C).call(this,"error",(null==t?void 0:t.error)||{errorCode:D.FETCH_ERROR_RESPONSE_ERROR_CODE,errorDescription:c,errorMessage:s}),this.loggerWrapper.error((null===(a=null==t?void 0:t.error)||void 0===a?void 0:a.errorDescription)||s,(null===(l=null==t?void 0:t.error)||void 0===l?void 0:l.errorMessage)||c);const h=null===(d=null==t?void 0:t.error)||void 0===d?void 0:d.errorCode;return void("E102004"!==h&&"E103205"!==h||!this.isRestartOnError||P.__classPrivateFieldGet(this,e,"m",n).call(this))}null===(h=null===(c=t.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===(p=null===(u=t.data)||void 0===u?void 0:u.screen)||void 0===p?void 0:p.state)||void 0===g?void 0:g.errorText;(null===(v=t.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${t.data.error.code}]: ${t.data.error.description}`,`${f?`${f} - `:""}${t.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:_,authInfo:b,lastAuth:S}=t.data;if("completed"===_)return this.storeLastAuthenticatedUser&&j.setLastAuth(S),void P.__classPrivateFieldGet(this,e,"m",C).call(this,"success",b);const{executionId:w,stepId:I,stepName:E,action:R,screen:y,redirect:O,openInNewTabUrl:T,webauthn:A,error:k,samlIdpResponse:N,nativeResponse:U}=t.data;R!==F.RESPONSE_ACTIONS.poll?(this.loggerWrapper.info(`Step "${E||`#${I}`}" is ${_}`,"",{screen:y,status:_,stepId:I,stepName:E,action:R,error:k}),(null===(m=y.state)||void 0===m?void 0:m.clientScripts)&&P.__classPrivateFieldSet(this,s,this.loadSdkScripts(y.state.clientScripts),"f"),this.flowState.update({stepId:I,stepName:E,executionId:w,action:R,redirectTo:null==O?void 0:O.url,openInNewTabUrl:T,screenId:null==y?void 0:y.id,screenState:null==y?void 0:y.state,webauthnTransactionId:null==A?void 0:A.transactionId,webauthnOptions:null==A?void 0:A.options,samlIdpResponseUrl:null==N?void 0:N.url,samlIdpResponseSamlResponse:null==N?void 0:N.samlResponse,samlIdpResponseRelayState:null==N?void 0:N.relayState,nativeResponseType:null==U?void 0:U.type,nativePayload:null==U?void 0:U.payload})):this.flowState.update({action:R})})),u.set(this,T.withMemCache((()=>P.__awaiter(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)}}))))),I.set(this,T.leadingDebounce(((t,i)=>P.__awaiter(this,void 0,void 0,(function*(){var r;if("true"===t.getAttribute("formnovalidate")||P.__classPrivateFieldGet(this,e,"m",m).call(this)){const o=null==t?void 0:t.getAttribute("id");P.__classPrivateFieldGet(this,e,"m",_).call(this,t);const n=yield P.__classPrivateFieldGet(this,e,"m",f).call(this),a=T.getElementDescopeAttributes(t);if(this.nextRequestStatus.update({isLoading:!0}),P.__classPrivateFieldGet(this,s,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const e=Date.now();yield P.__classPrivateFieldGet(this,s,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-e).toString())}const l=this.getComponentsContext(),d=Object.assign(Object.assign(Object.assign(Object.assign({},l),a),n),{origin:(null===(r=this.nativeOptions)||void 0===r?void 0:r.origin)||window.location.origin});yield i(o,d),this.nextRequestStatus.update({isLoading:!1}),P.__classPrivateFieldGet(this,e,"m",b).call(this,n)}}))))),this.flowState=a}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[L.getScriptResultPath(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 i=Promise.all(null==e?void 0:e.map((e=>P.__awaiter(this,void 0,void 0,(function*(){var i;const s=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(s){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=s;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}const r=yield L.default(e.id);return new Promise(((i,s)=>{try{const s=r(e.initArgs,{baseUrl:this.baseUrl},t(e,i));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)}}))}))))),s=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),F.SDK_SCRIPTS_LOAD_TIMEOUT)}));return Promise.race([i,s])}init(){if(!window.isDescopeBridge)return this._init();this.lazyInit=this._init}_init(){const e=Object.create(null,{init:{get:()=>super.init}});return P.__awaiter(this,void 0,void 0,(function*(){var t,i,s;this.shadowRoot.isConnected&&(null===(t=this.flowState)||void 0===t||t.subscribe(this.onFlowChange.bind(this)),null===(i=this.stepState)||void 0===i||i.subscribe(this.onStepChange.bind(this)),window.addEventListener("visibilitychange",P.__classPrivateFieldGet(this,r,"f").visibilitychange)),yield null===(s=e.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var e;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),null===(e=P.__classPrivateFieldGet(this,i,"f"))||void 0===e||e.abort(),P.__classPrivateFieldSet(this,i,null,"f"),window.removeEventListener("visibilitychange",P.__classPrivateFieldGet(this,r,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return P.__awaiter(this,void 0,void 0,(function*(){let i;const s=T.getUserLocale(e),r=yield this.getTargetLocales();return r.includes(s.locale)?i=`${t}-${s.locale}.html`:r.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return P.__awaiter(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(t,r,o){return P.__awaiter(this,void 0,void 0,(function*(){var n,l;const{projectId:c,flowId:u,tenant:p,stepId:g,executionId:v,action:m,screenId:f,screenState:_,redirectTo:b,openInNewTabUrl:S,redirectUrl:w,token:I,code:E,exchangeError:R,webauthnTransactionId:y,webauthnOptions:A,redirectAuthCodeChallenge:k,redirectAuthCallbackUrl:N,redirectAuthBackupCallbackUri:x,redirectAuthInitiator:G,locale:L,samlIdpResponseUrl:D,samlIdpResponseSamlResponse:q,samlIdpResponseRelayState:M,nativeResponseType:$,nativePayload:V}=t,B=P.__rest(t,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","openInNewTabUrl","redirectUrl","token","code","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","nativeResponseType","nativePayload"]);let K,H,X;const J=U.getABTestingKey(),z=this.sdk.getLastUserLoginId(),Y=yield this.getFlowConfig(),Q=yield this.getProjectConfig(),Z=Object.entries(Q.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),ee=N&&k?{callbackUrl:N,codeChallenge:k,backupCallbackUri:x}:void 0,te=this.nativeOptions?{platform:this.nativeOptions.platform,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;if(!v){const e=[...Y.clientScripts||[],...Y.sdkScripts||[]];if(Y.conditions){let t=[];({startScreenId:K,conditionInteractionId:X,startScreenName:H,clientScripts:t}=W.calculateConditions({loginId:z,code:E,token:I,abTestingKey:J},Y.conditions)),e.push(...t||[])}else Y.condition?({startScreenId:K,conditionInteractionId:X}=W.calculateCondition(Y.condition,{loginId:z,code:E,token:I,abTestingKey:J})):(H=Y.startScreenName,K=Y.startScreenId);if(P.__classPrivateFieldSet(this,s,this.loadSdkScripts(e),"f"),Y.fingerprintEnabled&&Y.fingerprintKey?yield O.ensureFingerprintIds(Y.fingerprintKey,this.baseUrl):O.clearFingerprintData(),!T.showFirstScreenOnExecutionInit(K,B)){const e=yield this.sdk.flow.start(u,Object.assign(Object.assign(Object.assign(Object.assign({tenant:p,redirectAuth:ee},B),{client:this.client}),w&&{redirectUrl:w}),{lastAuth:j.getLastAuth(z),abTestingKey:J,locale:T.getUserLocale(L).locale,nativeOptions:te}),X,"",Q.componentsVersion,Z,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),E?{exchangeCode:E,idpInitiated:!0}:{}),B.descopeIdpInitiated&&{idpInitiated:!0}),I?{token:I}:{}),B.oidcLoginHint?{externalId:B.oidcLoginHint}:{}));return P.__classPrivateFieldGet(this,h,"f").call(this,e),void("completed"!==(null===(n=null==e?void 0:e.data)||void 0===n?void 0:n.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(v&&(o("token")&&I||o("code")&&E||o("exchangeError")&&R)){const e=yield this.sdk.flow.next(v,g,F.CUSTOM_INTERACTIONS.submit,Y.version,Q.componentsVersion,{token:I,exchangeCode:E,exchangeError:R});return P.__classPrivateFieldGet(this,h,"f").call(this,e),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(m===F.RESPONSE_ACTIONS.loadForm&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>o(e)))){if(!D||!q)return void this.loggerWrapper.error("Did not get saml idp params data to load");T.injectSamlIdpForm(D,q,M||"",T.submitForm)}if(m===F.RESPONSE_ACTIONS.redirect&&(o("redirectTo")||o("deferredRedirect")))return b?"android"===G&&document.hidden?void this.flowState.update({deferredRedirect:!0}):void window.location.assign(b):void this.loggerWrapper.error("Did not get redirect url");if(m===F.RESPONSE_ACTIONS.webauthnCreate||m===F.RESPONSE_ACTIONS.webauthnGet){if(!y||!A)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let e,t;null===(l=P.__classPrivateFieldGet(this,i,"f"))||void 0===l||l.abort(),P.__classPrivateFieldSet(this,i,null,"f");try{e=m===F.RESPONSE_ACTIONS.webauthnCreate?yield this.sdk.webauthn.helpers.create(A):yield this.sdk.webauthn.helpers.get(A)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),t=e.name}const s=yield this.sdk.flow.next(v,g,F.CUSTOM_INTERACTIONS.submit,Y.version,Q.componentsVersion,{transactionId:y,response:e,failure:t});P.__classPrivateFieldGet(this,h,"f").call(this,s)}if(m===F.RESPONSE_ACTIONS.nativeBridge)return this.nativeComplete=e=>P.__awaiter(this,void 0,void 0,(function*(){const t=yield this.sdk.flow.next(v,g,F.CUSTOM_INTERACTIONS.submit,Y.version,Q.componentsVersion,e);P.__classPrivateFieldGet(this,h,"f").call(this,t)})),void P.__classPrivateFieldGet(this,e,"m",C).call(this,"bridge",{type:$,payload:V});if(P.__classPrivateFieldGet(this,d,"f").call(this,v,g,Y.version,Q.componentsVersion),!f&&!K)return void this.loggerWrapper.warn("No screen was found to show");const ie=K||f,se=yield this.getHtmlFilenameWithLocale(L,ie),{oidcLoginHint:re,oidcPrompt:oe,oidcErrorRedirectUri:ne,samlIdpUsername:ae}=B,le={direction:T.getAnimationDirection(g,r.stepId),screenState:Object.assign(Object.assign({},_),{form:Object.assign(Object.assign({},this.formConfigValues),null==_?void 0:_.form),lastAuth:{loginId:z,name:this.sdk.getLastUserDisplayName()||z}}),htmlFilename:`${ie}.html`,htmlLocaleFilename:se,screenId:ie,stepName:t.stepName||H,samlIdpUsername:ae,oidcLoginHint:re,oidcPrompt:oe,oidcErrorRedirectUri:ne,openInNewTabUrl:S},de=j.getLastAuth(z);T.showFirstScreenOnExecutionInit(K,B)?le.next=(e,t)=>P.__awaiter(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.start(u,Object.assign(Object.assign(Object.assign(Object.assign({tenant:p,redirectAuth:ee},B),{lastAuth:de,preview:this.preview,abTestingKey:J,client:this.client}),w&&{redirectUrl:w}),{locale:T.getUserLocale(L).locale,nativeOptions:te}),X,e,Q.componentsVersion,Z,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),t),E&&{exchangeCode:E,idpInitiated:!0}),B.descopeIdpInitiated&&{idpInitiated:!0}),I&&{token:I}));return P.__classPrivateFieldGet(this,h,"f").call(this,i),i})):(o("projectId")||o("baseUrl")||o("executionId")||o("stepId"))&&(le.next=(e,t)=>P.__awaiter(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(v,g,e,Y.version,Q.componentsVersion,t);return P.__classPrivateFieldGet(this,h,"f").call(this,i),i}))),this.loggerWrapper.debug("Going to render screen with id",le.screenId),yield P.__classPrivateFieldGet(this,e,"m",a).call(this,le),this.stepState.update(le)}))}onStepChange(t,i){return P.__awaiter(this,void 0,void 0,(function*(){var s,r;const{htmlFilename:o,htmlLocaleFilename:n,direction:a,next:l,screenState:d,openInNewTabUrl:c}=t;this.loggerWrapper.debug("Rendering a flow screen");const h=document.createElement("template");h.innerHTML=yield this.getPageContent(o,n);const u=h.content.cloneNode(!0),p=this.loadDescopeUiComponents(h);this.sdk.webauthn.helpers.isSupported()?yield P.__classPrivateFieldGet(this,e,"m",g).call(this,u,l):k.disableWebauthnButtons(u),!t.samlIdpUsername||(null===(s=d.form)||void 0===s?void 0:s.loginId)||(null===(r=d.form)||void 0===r?void 0:r.email)||(d.form||(d.form={}),d.form.loginId=t.samlIdpUsername,d.form.email=t.samlIdpUsername),k.updateTemplateFromScreenState(u,d,d.componentsConfig,this.formConfig,this.errorTransformer,this.loggerWrapper);const{geo:m}=yield this.getExecutionContext();k.setPhoneAutoDetectDefaultCode(u,m);const f=()=>P.__awaiter(this,void 0,void 0,(function*(){var s,r;yield p;const o=this.contentRootElement;k.setTOTPVariable(o,null===(s=null==d?void 0:d.totp)||void 0===s?void 0:s.image),k.setNOTPVariable(o,null===(r=null==d?void 0:d.notp)||void 0===r?void 0:r.image),k.setCssVars(o,u,d.cssVars,this.loggerWrapper),o.replaceChildren(u);const n=!i.htmlFilename;setTimeout((()=>{P.__classPrivateFieldGet(this,e,"m",S).call(this),this.validateOnBlur&&T.handleReportValidityOnBlur(o),k.updateScreenFromScreenState(o,d),P.__classPrivateFieldGet(this,e,"m",v).call(this,{isFirstScreen:n,stepName:t.stepName}),T.handleAutoFocus(o,this.autoFocus,n)})),P.__classPrivateFieldGet(this,e,"m",R).call(this,l);o.querySelector(`[${F.ELEMENT_TYPE_ATTRIBUTE}="polling"]`)&&l(F.CUSTOM_INTERACTIONS.polling,{}),c&&!i.openInNewTabUrl&&window.open(c,"_blank")}));a?P.__classPrivateFieldGet(this,e,"m",y).call(this,f,a):f()}))}};
1
+ "use strict";var e,t,i,s,r,o,n,a,l,d,c,h,u,p,g,v,m,f,_,b,S,w,I,E,R,C,y,P=require("tslib"),O=require("@descope/web-js-sdk"),T=require("../constants/index.js"),F=require("../helpers/helpers.js"),A=require("../helpers/state.js"),k=require("../helpers/templates.js"),N=require("../helpers/webauthn.js"),U=require("../helpers/abTestingKey.js"),W=require("../helpers/conditions.js"),G=require("../helpers/lastAuth.js"),j=require("../types.js"),x=require("./BaseDescopeWc.js"),L=require("./sdkScripts/index.js"),q=require("../constants/general.js");t=new WeakMap,i=new WeakMap,s=new WeakMap,r=new WeakMap,l=new WeakMap,d=new WeakMap,c=new WeakMap,h=new WeakMap,u=new WeakMap,I=new WeakMap,e=new WeakSet,o=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},n=function(){return P.__awaiter(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")}))},a=function(t){return P.__awaiter(this,void 0,void 0,(function*(){var i;const s=Object.assign(Object.assign({},this.stepState.current),t),{next:r,stepName:o}=s,n=P.__rest(s,["next","stepName"]),a=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,o,F.transformStepStateForCustomScreen(n),r,this));if(a){this.loggerWrapper.debug("Rendering a custom screen"),this.contentRootElement.innerHTML="",P.__classPrivateFieldGet(this,e,"m",v).call(this,{isFirstScreen:!this.stepState.current.htmlFilename,stepName:t.stepName}),this.stepState.unsubscribeAll();const i=this.stepState.subscribe((()=>{var e;this.stepState.unsubscribe(i),null===(e=this.stepState)||void 0===e||e.subscribe(this.onStepChange.bind(this))}))}P.__classPrivateFieldGet(this,l,"f").call(this,a)}))},p=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)}))}},g=function(t,s){return P.__awaiter(this,void 0,void 0,(function*(){var r;null===(r=P.__classPrivateFieldGet(this,i,"f"))||void 0===r||r.abort();const o=t.querySelector('*[autocomplete="webauthn"]');if(o&&(yield N.isConditionalLoginSupported())){const{options:t,transactionId:r}=(yield P.__classPrivateFieldGet(this,u,"f").call(this))||{};t&&r&&(P.__classPrivateFieldGet(this,e,"m",p).call(this,o),P.__classPrivateFieldSet(this,i,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(t,P.__classPrivateFieldGet(this,i,"f")).then((e=>P.__awaiter(this,void 0,void 0,(function*(){s(o.id,{transactionId:r,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},v=function({isFirstScreen:t,stepName:i}){t&&P.__classPrivateFieldGet(this,e,"m",y).call(this,"ready",{}),P.__classPrivateFieldGet(this,e,"m",y).call(this,"page-updated",{screenName:i}),P.__classPrivateFieldGet(this,e,"m",y).call(this,"screen-updated",{screenName:i})},m=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"!==t.localName&&(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},f=function(){return P.__awaiter(this,void 0,void 0,(function*(){const e=Array.from(this.shadowRoot.querySelectorAll(`*[name]:not([${T.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`));return(yield Promise.all(e.map((e=>P.__awaiter(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})),{})}))},_=function(e){const t=this.nextRequestStatus.subscribe((({isLoading:i})=>{i?e.setAttribute("loading","true"):(this.nextRequestStatus.unsubscribe(t),e.removeAttribute("loading"))}))},b=function(e={}){var t,i;const s=F.getFirstNonEmptyValue(e,["externalId","email","phone"]),r=F.getFirstNonEmptyValue(e,["newPassword","password"]);if(s&&r)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:r});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)}},S=function(){F.clearPreviousExternalInputs();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>P.__classPrivateFieldGet(this,e,"m",w).call(this,t)))},w=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const i=t.getAttribute("slot"),s=`input-${e.id}-${i}`,r=document.createElement("slot");r.setAttribute("name",s),r.setAttribute("slot",i),e.appendChild(r),t.setAttribute("slot",s),this.appendChild(t)}))},E=function(e){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((t=>{t.addEventListener("input",(()=>{var i;(null===(i=t.checkValidity)||void 0===i?void 0:i.call(t))&&P.__classPrivateFieldGet(this,I,"f").call(this,t,e)}))}))},R=function(t){this.contentRootElement.querySelectorAll(`descope-button:not([${T.DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON}])`).forEach((e=>{e.onclick=()=>{P.__classPrivateFieldGet(this,I,"f").call(this,e,t)}})),P.__classPrivateFieldGet(this,e,"m",E).call(this,t)},C=function(e,t){this.contentRootElement.addEventListener("transitionend",(()=>{this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0});const i=t===j.Direction.forward?"slide-forward":"slide-backward";Array.from(this.contentRootElement.getElementsByClassName("input-container")).forEach(((e,t)=>{e.style["transition-delay"]=40*t+"ms",e.classList.add(i)})),this.contentRootElement.classList.add("fade-out")},y=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},module.exports=class extends x{static set sdkConfigOverrides(e){x.sdkConfigOverrides=e}static get sdkConfigOverrides(){return x.sdkConfigOverrides}constructor(){const a=new A({deferredRedirect:!1});super(a.update.bind(a)),e.add(this),this.stepState=new A({}),t.set(this,void 0),i.set(this,null),s.set(this,null),r.set(this,{visibilitychange:P.__classPrivateFieldGet(this,e,"m",o).bind(this)}),this.bridgeVersion=1,this.nativeResume=(e,t)=>{var i;const s=JSON.parse(t);if(this.logger.info(`nativeResume received payload of type '${e}'`),"oauthWeb"===e||"sso"===e){let{exchangeCode:e}=s;if(!e){e=null===(i=new URL(s.url).searchParams)||void 0===i?void 0:i.get(T.URL_CODE_PARAM_NAME)}this.nativeComplete({exchangeCode:e,idpInitiated:!0})}else if("magicLink"===e){const e=new URL(s.url),t=e.searchParams.get(T.URL_TOKEN_PARAM_NAME),i=e.searchParams.get(T.URL_RUN_IDS_PARAM_NAME).split("_").pop();P.__classPrivateFieldGet(this,c,"f").call(this),this.flowState.update({token:t,stepId:i,action:void 0})}else this.nativeComplete(s)},l.set(this,(e=>{this.contentRootElement.classList.toggle("hidden",e),this.slotElement.classList.toggle("hidden",!e)})),d.set(this,((e,i,s,r,o=!1)=>{if(this.flowState.current.action===T.RESPONSE_ACTIONS.poll){this.logger.debug("polling - Scheduling polling request");const n=Date.now(),a=o?500:2e3;P.__classPrivateFieldSet(this,t,setTimeout((()=>P.__awaiter(this,void 0,void 0,(function*(){var t;this.logger.debug("polling - Calling next");const l=this.sdk.flow.next(e,i,T.CUSTOM_INTERACTIONS.polling,s,r,{}),c=document.hidden&&!o&&Date.now()-n>a+500;let u;c&&this.logger.debug("polling - The polling seems to be throttled");try{const e=c?1e3:6e3;u=yield F.timeoutPromise(e,l)}catch(t){return this.logger.warn(`polling - The ${c?"throttled fetch":"fetch"} call timed out or was aborted`),void P.__classPrivateFieldGet(this,d,"f").call(this,e,i,s,r,c)}if((null===(t=null==u?void 0:u.error)||void 0===t?void 0:t.errorCode)===q.FETCH_EXCEPTION_ERROR_CODE)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void P.__classPrivateFieldGet(this,d,"f").call(this,e,i,s,r);this.logger.debug("polling - Got a response"),(null==u?void 0:u.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(u.error,null,4)),P.__classPrivateFieldGet(this,d,"f").call(this,e,i,s,r),P.__classPrivateFieldGet(this,h,"f").call(this,u)}))),a),"f")}})),c.set(this,(()=>{clearTimeout(P.__classPrivateFieldGet(this,t,"f")),P.__classPrivateFieldSet(this,t,null,"f")})),h.set(this,(t=>{var i,r,o,a,l,d,h,u,p,g,v,m,f;if(!(null==t?void 0:t.ok)){const s=null===(i=null==t?void 0:t.response)||void 0===i?void 0:i.url,c=`${null===(r=null==t?void 0:t.response)||void 0===r?void 0:r.status} - ${null===(o=null==t?void 0:t.response)||void 0===o?void 0:o.statusText}`;P.__classPrivateFieldGet(this,e,"m",y).call(this,"error",(null==t?void 0:t.error)||{errorCode:q.FETCH_ERROR_RESPONSE_ERROR_CODE,errorDescription:c,errorMessage:s}),this.loggerWrapper.error((null===(a=null==t?void 0:t.error)||void 0===a?void 0:a.errorDescription)||s,(null===(l=null==t?void 0:t.error)||void 0===l?void 0:l.errorMessage)||c);const h=null===(d=null==t?void 0:t.error)||void 0===d?void 0:d.errorCode;return void("E102004"!==h&&"E103205"!==h||!this.isRestartOnError||P.__classPrivateFieldGet(this,e,"m",n).call(this))}null===(u=null===(h=t.data)||void 0===h?void 0:h.runnerLogs)||void 0===u||u.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 _=null===(v=null===(g=null===(p=t.data)||void 0===p?void 0:p.screen)||void 0===g?void 0:g.state)||void 0===v?void 0:v.errorText;(null===(m=t.data)||void 0===m?void 0:m.error)?this.loggerWrapper.error(`[${t.data.error.code}]: ${t.data.error.description}`,`${_?`${_} - `:""}${t.data.error.message}`):_&&this.loggerWrapper.error(_);const{status:b,authInfo:S,lastAuth:w,action:I}=t.data;if(I!==T.RESPONSE_ACTIONS.poll&&P.__classPrivateFieldGet(this,c,"f").call(this),"completed"===b)return this.storeLastAuthenticatedUser&&G.setLastAuth(w),void P.__classPrivateFieldGet(this,e,"m",y).call(this,"success",S);const{executionId:E,stepId:R,stepName:C,screen:O,redirect:F,openInNewTabUrl:A,webauthn:k,error:N,samlIdpResponse:U,nativeResponse:W}=t.data,j=Date.now();I!==T.RESPONSE_ACTIONS.poll?(this.loggerWrapper.info(`Step "${C||`#${R}`}" is ${b}`,"",{screen:O,status:b,stepId:R,stepName:C,action:I,error:N}),(null===(f=O.state)||void 0===f?void 0:f.clientScripts)&&P.__classPrivateFieldSet(this,s,this.loadSdkScripts(O.state.clientScripts),"f"),this.flowState.update({stepId:R,stepName:C,executionId:E,action:I,redirectTo:null==F?void 0:F.url,openInNewTabUrl:A,screenId:null==O?void 0:O.id,screenState:null==O?void 0:O.state,webauthnTransactionId:null==k?void 0:k.transactionId,webauthnOptions:null==k?void 0:k.options,samlIdpResponseUrl:null==U?void 0:U.url,samlIdpResponseSamlResponse:null==U?void 0:U.samlResponse,samlIdpResponseRelayState:null==U?void 0:U.relayState,nativeResponseType:null==W?void 0:W.type,nativePayload:null==W?void 0:W.payload,reqTimestamp:j})):this.flowState.update({action:I,reqTimestamp:j})})),u.set(this,F.withMemCache((()=>P.__awaiter(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)}}))))),I.set(this,F.leadingDebounce(((t,i)=>P.__awaiter(this,void 0,void 0,(function*(){var r;if("true"===t.getAttribute("formnovalidate")||P.__classPrivateFieldGet(this,e,"m",m).call(this)){const o=null==t?void 0:t.getAttribute("id");P.__classPrivateFieldGet(this,e,"m",_).call(this,t);const n=yield P.__classPrivateFieldGet(this,e,"m",f).call(this),a=F.getElementDescopeAttributes(t);if(this.nextRequestStatus.update({isLoading:!0}),P.__classPrivateFieldGet(this,s,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const e=Date.now();yield P.__classPrivateFieldGet(this,s,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-e).toString())}const l=this.getComponentsContext(),d=Object.assign(Object.assign(Object.assign(Object.assign({},l),a),n),{origin:(null===(r=this.nativeOptions)||void 0===r?void 0:r.origin)||window.location.origin});yield i(o,d),this.nextRequestStatus.update({isLoading:!1}),P.__classPrivateFieldGet(this,e,"m",b).call(this,n)}}))))),this.flowState=a}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[L.getScriptResultPath(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 i=Promise.all(null==e?void 0:e.map((e=>P.__awaiter(this,void 0,void 0,(function*(){var i;const s=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(s){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=s;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}const r=yield L.default(e.id);return new Promise(((i,s)=>{try{const s=r(e.initArgs,{baseUrl:this.baseUrl},t(e,i));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)}}))}))))),s=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),T.SDK_SCRIPTS_LOAD_TIMEOUT)}));return Promise.race([i,s])}init(){if(!window.isDescopeBridge)return this._init();this.lazyInit=this._init}_init(){const e=Object.create(null,{init:{get:()=>super.init}});return P.__awaiter(this,void 0,void 0,(function*(){var t,i,s;this.shadowRoot.isConnected&&(null===(t=this.flowState)||void 0===t||t.subscribe(this.onFlowChange.bind(this)),null===(i=this.stepState)||void 0===i||i.subscribe(this.onStepChange.bind(this)),window.addEventListener("visibilitychange",P.__classPrivateFieldGet(this,r,"f").visibilitychange)),yield null===(s=e.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var e;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),null===(e=P.__classPrivateFieldGet(this,i,"f"))||void 0===e||e.abort(),P.__classPrivateFieldSet(this,i,null,"f"),window.removeEventListener("visibilitychange",P.__classPrivateFieldGet(this,r,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return P.__awaiter(this,void 0,void 0,(function*(){let i;const s=F.getUserLocale(e),r=yield this.getTargetLocales();return r.includes(s.locale)?i=`${t}-${s.locale}.html`:r.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return P.__awaiter(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(t,r,o){return P.__awaiter(this,void 0,void 0,(function*(){var n,l;const{projectId:c,flowId:u,tenant:p,stepId:g,executionId:v,action:m,screenId:f,screenState:_,redirectTo:b,openInNewTabUrl:S,redirectUrl:w,token:I,code:E,exchangeError:R,webauthnTransactionId:C,webauthnOptions:A,redirectAuthCodeChallenge:k,redirectAuthCallbackUrl:N,redirectAuthBackupCallbackUri:j,redirectAuthInitiator:x,locale:L,samlIdpResponseUrl:q,samlIdpResponseSamlResponse:D,samlIdpResponseRelayState:M,nativeResponseType:$,nativePayload:V,reqTimestamp:B}=t,K=P.__rest(t,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","openInNewTabUrl","redirectUrl","token","code","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","nativeResponseType","nativePayload","reqTimestamp"]);let H,X,J;const z=U.getABTestingKey(),Y=this.sdk.getLastUserLoginId(),Q=yield this.getFlowConfig(),Z=yield this.getProjectConfig(),ee=Object.entries(Z.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),te=N&&k?{callbackUrl:N,codeChallenge:k,backupCallbackUri:j}:void 0,ie=this.nativeOptions?{platform:this.nativeOptions.platform,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;if(!v){const e=[...Q.clientScripts||[],...Q.sdkScripts||[]];if(Q.conditions){let t=[];({startScreenId:H,conditionInteractionId:J,startScreenName:X,clientScripts:t}=W.calculateConditions({loginId:Y,code:E,token:I,abTestingKey:z},Q.conditions)),e.push(...t||[])}else Q.condition?({startScreenId:H,conditionInteractionId:J}=W.calculateCondition(Q.condition,{loginId:Y,code:E,token:I,abTestingKey:z})):(X=Q.startScreenName,H=Q.startScreenId);if(P.__classPrivateFieldSet(this,s,this.loadSdkScripts(e),"f"),Q.fingerprintEnabled&&Q.fingerprintKey?yield O.ensureFingerprintIds(Q.fingerprintKey,this.baseUrl):O.clearFingerprintData(),!F.showFirstScreenOnExecutionInit(H,K)){const e=yield this.sdk.flow.start(u,Object.assign(Object.assign(Object.assign(Object.assign({tenant:p,redirectAuth:te},K),{client:this.client}),w&&{redirectUrl:w}),{lastAuth:G.getLastAuth(Y),abTestingKey:z,locale:F.getUserLocale(L).locale,nativeOptions:ie}),J,"",Z.componentsVersion,ee,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),E?{exchangeCode:E,idpInitiated:!0}:{}),K.descopeIdpInitiated&&{idpInitiated:!0}),I?{token:I}:{}),K.oidcLoginHint?{externalId:K.oidcLoginHint}:{}));return P.__classPrivateFieldGet(this,h,"f").call(this,e),void("completed"!==(null===(n=null==e?void 0:e.data)||void 0===n?void 0:n.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(v&&(o("token")&&I||o("code")&&E||o("exchangeError")&&R)){const e=yield this.sdk.flow.next(v,g,T.CUSTOM_INTERACTIONS.submit,Q.version,Z.componentsVersion,{token:I,exchangeCode:E,exchangeError:R});return P.__classPrivateFieldGet(this,h,"f").call(this,e),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(m===T.RESPONSE_ACTIONS.loadForm&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>o(e)))){if(!q||!D)return void this.loggerWrapper.error("Did not get saml idp params data to load");F.injectSamlIdpForm(q,D,M||"",F.submitForm)}if(m===T.RESPONSE_ACTIONS.redirect&&(o("redirectTo")||o("deferredRedirect")))return b?"android"===x&&document.hidden?void this.flowState.update({deferredRedirect:!0}):void window.location.assign(b):void this.loggerWrapper.error("Did not get redirect url");if(m===T.RESPONSE_ACTIONS.webauthnCreate||m===T.RESPONSE_ACTIONS.webauthnGet){if(!C||!A)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let e,t;null===(l=P.__classPrivateFieldGet(this,i,"f"))||void 0===l||l.abort(),P.__classPrivateFieldSet(this,i,null,"f");try{e=m===T.RESPONSE_ACTIONS.webauthnCreate?yield this.sdk.webauthn.helpers.create(A):yield this.sdk.webauthn.helpers.get(A)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),t=e.name}const s=yield this.sdk.flow.next(v,g,T.CUSTOM_INTERACTIONS.submit,Q.version,Z.componentsVersion,{transactionId:C,response:e,failure:t});P.__classPrivateFieldGet(this,h,"f").call(this,s)}if(m===T.RESPONSE_ACTIONS.nativeBridge)return this.nativeComplete=e=>P.__awaiter(this,void 0,void 0,(function*(){const t=yield this.sdk.flow.next(v,g,T.CUSTOM_INTERACTIONS.submit,Q.version,Z.componentsVersion,e);P.__classPrivateFieldGet(this,h,"f").call(this,t)})),void P.__classPrivateFieldGet(this,e,"m",y).call(this,"bridge",{type:$,payload:V});if(o("action")&&P.__classPrivateFieldGet(this,d,"f").call(this,v,g,Q.version,Z.componentsVersion),!f&&!H)return void this.loggerWrapper.warn("No screen was found to show");const se=H||f,re=yield this.getHtmlFilenameWithLocale(L,se),{oidcLoginHint:oe,oidcPrompt:ne,oidcErrorRedirectUri:ae,samlIdpUsername:le}=K,de={direction:F.getAnimationDirection(g,r.stepId),screenState:Object.assign(Object.assign({},_),{form:Object.assign(Object.assign({},this.formConfigValues),null==_?void 0:_.form),lastAuth:{loginId:Y,name:this.sdk.getLastUserDisplayName()||Y}}),htmlFilename:`${se}.html`,htmlLocaleFilename:re,screenId:se,stepName:t.stepName||X,samlIdpUsername:le,oidcLoginHint:oe,oidcPrompt:ne,oidcErrorRedirectUri:ae,openInNewTabUrl:S},ce=G.getLastAuth(Y);F.showFirstScreenOnExecutionInit(H,K)?de.next=(e,t)=>P.__awaiter(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.start(u,Object.assign(Object.assign(Object.assign(Object.assign({tenant:p,redirectAuth:te},K),{lastAuth:ce,preview:this.preview,abTestingKey:z,client:this.client}),w&&{redirectUrl:w}),{locale:F.getUserLocale(L).locale,nativeOptions:ie}),J,e,Z.componentsVersion,ee,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),t),E&&{exchangeCode:E,idpInitiated:!0}),K.descopeIdpInitiated&&{idpInitiated:!0}),I&&{token:I}));return P.__classPrivateFieldGet(this,h,"f").call(this,i),i})):(o("projectId")||o("baseUrl")||o("executionId")||o("stepId"))&&(de.next=(e,t)=>P.__awaiter(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(v,g,e,Q.version,Z.componentsVersion,t);return P.__classPrivateFieldGet(this,h,"f").call(this,i),i}))),this.loggerWrapper.debug("Got a screen with id",de.screenId),yield P.__classPrivateFieldGet(this,e,"m",a).call(this,de),this.stepState.update(de)}))}onStepChange(t,i){return P.__awaiter(this,void 0,void 0,(function*(){var s,r;const{htmlFilename:o,htmlLocaleFilename:n,direction:a,next:l,screenState:d,openInNewTabUrl:c}=t;this.loggerWrapper.debug("Rendering a flow screen");const h=document.createElement("template");h.innerHTML=yield this.getPageContent(o,n);const u=h.content.cloneNode(!0),p=this.loadDescopeUiComponents(h);this.sdk.webauthn.helpers.isSupported()?yield P.__classPrivateFieldGet(this,e,"m",g).call(this,u,l):k.disableWebauthnButtons(u),!t.samlIdpUsername||(null===(s=d.form)||void 0===s?void 0:s.loginId)||(null===(r=d.form)||void 0===r?void 0:r.email)||(d.form||(d.form={}),d.form.loginId=t.samlIdpUsername,d.form.email=t.samlIdpUsername),k.updateTemplateFromScreenState(u,d,d.componentsConfig,this.formConfig,this.errorTransformer,this.loggerWrapper);const{geo:m}=yield this.getExecutionContext();k.setPhoneAutoDetectDefaultCode(u,m);const f=()=>P.__awaiter(this,void 0,void 0,(function*(){var s,r;yield p;const o=this.contentRootElement;k.setTOTPVariable(o,null===(s=null==d?void 0:d.totp)||void 0===s?void 0:s.image),k.setNOTPVariable(o,null===(r=null==d?void 0:d.notp)||void 0===r?void 0:r.image),k.setCssVars(o,u,d.cssVars,this.loggerWrapper),o.replaceChildren(u);const n=!i.htmlFilename;setTimeout((()=>{P.__classPrivateFieldGet(this,e,"m",S).call(this),this.validateOnBlur&&F.handleReportValidityOnBlur(o),k.updateScreenFromScreenState(o,d),P.__classPrivateFieldGet(this,e,"m",v).call(this,{isFirstScreen:n,stepName:t.stepName}),F.handleAutoFocus(o,this.autoFocus,n)})),P.__classPrivateFieldGet(this,e,"m",R).call(this,l);o.querySelector(`[${T.ELEMENT_TYPE_ATTRIBUTE}="polling"]`)&&l(T.CUSTOM_INTERACTIONS.polling,{}),c&&!i.openInNewTabUrl&&window.open(c,"_blank")}));a?P.__classPrivateFieldGet(this,e,"m",C).call(this,f,a):f()}))}};
2
2
  //# sourceMappingURL=DescopeWc.js.map