@descope/web-component 4.6.1 → 4.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -125,6 +125,10 @@ Content-Security-Policy:
125
125
 
126
126
  If the SRI hash is not available in the configuration (older projects), the component will load normally without integrity checks. No breaking changes required.
127
127
 
128
+ ### Cross-origin OAuth popups
129
+
130
+ When the OAuth popup's redirect page is on a different origin than the page that opens it (see `popup-origin`), the popup sends the OAuth result only to the opener origin Descope attests for that popup. Descope attests the origin of the page that opened the popup when it is one of the project's approved domains, or when the project has no approved domains. Otherwise the popup answers only over a same-origin `BroadcastChannel`, so list the main application's domain in the project's approved domains.
131
+
128
132
  ## Optional Attributes
129
133
 
130
134
  | Attribute | Available options | Default value |
@@ -1,2 +1,2 @@
1
- "use strict";var _=require("./content.js"),E=require("./uiComponents.js");exports.ASSETS_FOLDER=_.ASSETS_FOLDER,exports.BASE_CONTENT_URL=_.BASE_CONTENT_URL,exports.CONFIG_FILENAME=_.CONFIG_FILENAME,exports.OVERRIDE_CONTENT_URL=_.OVERRIDE_CONTENT_URL,exports.PREV_VER_ASSETS_FOLDER=_.PREV_VER_ASSETS_FOLDER,exports.UI_COMPONENTS_URL_KEY=E.UI_COMPONENTS_URL_KEY,exports.APPLICATION_SCOPES_PARAM_NAME="application_scopes",exports.CUSTOM_APP_ID_PARAM_NAME="custom_app_id",exports.CUSTOM_INTERACTIONS={submit:"submit",polling:"polling"},exports.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD="data-exclude-field",exports.DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON="data-exclude-next",exports.DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED="data-opt-in-last-used-auth",exports.DESCOPE_ATTRIBUTE_PREFIX="data-descope-",exports.DESCOPE_IDP_INITIATED_PARAM_NAME="descope_idp_initiated",exports.DESCOPE_LAST_AUTH_BADGE_COMPONENT='descope-attachment[data-type="last-auth-badge"]',exports.DESCOPE_LAST_AUTH_IN_FLIGHT_LOCAL_STORAGE_KEY="dls_last_auth_in_flight",exports.DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY="dls_last_auth",exports.DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY="dls_last_submitted_login_id",exports.DESCOPE_SSO_QUERY_PARAMS_SESSION_STORAGE_KEY_PREFIX="dls_sso_query_params",exports.ELEMENTS_TO_IGNORE_ENTER_KEY_ON=["descope-multi-select-combo-box","descope-text-area"],exports.ELEMENT_TYPE_ATTRIBUTE="data-type",exports.HAS_DYNAMIC_VALUES_ATTR_NAME="data-has-dynamic-attr-values",exports.OIDC_ERROR_REDIRECT_URI_PARAM_NAME="oidc_error_redirect_uri",exports.OIDC_IDP_STATE_ID_PARAM_NAME="state_id",exports.OIDC_LOGIN_HINT_PARAM_NAME="oidc_login_hint",exports.OIDC_PROMPT_PARAM_NAME="oidc_prompt",exports.OIDC_RESOURCE_PARAM_NAME="oidc_resource",exports.RESPONSE_ACTIONS={redirect:"redirect",poll:"poll",webauthnCreate:"webauthnCreate",webauthnGet:"webauthnGet",nativeBridge:"nativeBridge",loadForm:"loadForm"},exports.SAML_IDP_STATE_ID_PARAM_NAME="saml_idp_state_id",exports.SAML_IDP_USERNAME_PARAM_NAME="saml_idp_username",exports.SDK_SCRIPTS_LOAD_TIMEOUT=5e3,exports.SDK_SCRIPT_RESULTS_KEY="sdkScriptsResults",exports.SSO_APP_ID_PARAM_NAME="sso_app_id",exports.SSO_QUERY_PARAMS_MAX_AGE_MS=6e5,exports.THIRD_PARTY_APP_ID_PARAM_NAME="third_party_app_id",exports.THIRD_PARTY_APP_STATE_ID_PARAM_NAME="third_party_app_state_id",exports.URL_CODE_PARAM_NAME="code",exports.URL_ERR_PARAM_NAME="err",exports.URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME="ra-backup-callback",exports.URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME="ra-callback",exports.URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME="ra-challenge",exports.URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME="ra-initiator",exports.URL_REDIRECT_MODE_PARAM_NAME="redirect_mode",exports.URL_RUN_IDS_PARAM_NAME="descope-login-flow",exports.URL_TOKEN_PARAM_NAME="t",exports.WEBAUTHN_TIMEOUT=9e4,exports.WSFED_IDP_STATE_ID_PARAM_NAME="wsfed_idp_state_id";
1
+ "use strict";var _=require("./content.js"),E=require("./uiComponents.js");exports.ASSETS_FOLDER=_.ASSETS_FOLDER,exports.BASE_CONTENT_URL=_.BASE_CONTENT_URL,exports.CONFIG_FILENAME=_.CONFIG_FILENAME,exports.OVERRIDE_CONTENT_URL=_.OVERRIDE_CONTENT_URL,exports.PREV_VER_ASSETS_FOLDER=_.PREV_VER_ASSETS_FOLDER,exports.UI_COMPONENTS_URL_KEY=E.UI_COMPONENTS_URL_KEY,exports.APPLICATION_SCOPES_PARAM_NAME="application_scopes",exports.CUSTOM_APP_ID_PARAM_NAME="custom_app_id",exports.CUSTOM_INTERACTIONS={submit:"submit",polling:"polling"},exports.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD="data-exclude-field",exports.DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON="data-exclude-next",exports.DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED="data-opt-in-last-used-auth",exports.DESCOPE_ATTRIBUTE_PREFIX="data-descope-",exports.DESCOPE_IDP_INITIATED_PARAM_NAME="descope_idp_initiated",exports.DESCOPE_LAST_AUTH_BADGE_COMPONENT='descope-attachment[data-type="last-auth-badge"]',exports.DESCOPE_LAST_AUTH_IN_FLIGHT_LOCAL_STORAGE_KEY="dls_last_auth_in_flight",exports.DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY="dls_last_auth",exports.DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY="dls_last_submitted_login_id",exports.DESCOPE_SSO_QUERY_PARAMS_SESSION_STORAGE_KEY_PREFIX="dls_sso_query_params",exports.ELEMENTS_TO_IGNORE_ENTER_KEY_ON=["descope-multi-select-combo-box","descope-text-area"],exports.ELEMENT_TYPE_ATTRIBUTE="data-type",exports.HAS_DYNAMIC_VALUES_ATTR_NAME="data-has-dynamic-attr-values",exports.OIDC_ERROR_REDIRECT_URI_PARAM_NAME="oidc_error_redirect_uri",exports.OIDC_IDP_STATE_ID_PARAM_NAME="state_id",exports.OIDC_LOGIN_HINT_PARAM_NAME="oidc_login_hint",exports.OIDC_PROMPT_PARAM_NAME="oidc_prompt",exports.OIDC_RESOURCE_PARAM_NAME="oidc_resource",exports.RESPONSE_ACTIONS={redirect:"redirect",poll:"poll",webauthnCreate:"webauthnCreate",webauthnGet:"webauthnGet",nativeBridge:"nativeBridge",loadForm:"loadForm"},exports.SAML_IDP_STATE_ID_PARAM_NAME="saml_idp_state_id",exports.SAML_IDP_USERNAME_PARAM_NAME="saml_idp_username",exports.SDK_SCRIPTS_LOAD_TIMEOUT=5e3,exports.SDK_SCRIPT_RESULTS_KEY="sdkScriptsResults",exports.SSO_APP_ID_PARAM_NAME="sso_app_id",exports.SSO_QUERY_PARAMS_MAX_AGE_MS=6e5,exports.THIRD_PARTY_APP_ID_PARAM_NAME="third_party_app_id",exports.THIRD_PARTY_APP_STATE_ID_PARAM_NAME="third_party_app_state_id",exports.URL_CODE_PARAM_NAME="code",exports.URL_ERR_PARAM_NAME="err",exports.URL_POPUP_OPENER_ORIGIN_PARAM_NAME="popup_opener_origin",exports.URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME="ra-backup-callback",exports.URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME="ra-callback",exports.URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME="ra-challenge",exports.URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME="ra-initiator",exports.URL_REDIRECT_MODE_PARAM_NAME="redirect_mode",exports.URL_RUN_IDS_PARAM_NAME="descope-login-flow",exports.URL_TOKEN_PARAM_NAME="t",exports.WEBAUTHN_TIMEOUT=9e4,exports.WSFED_IDP_STATE_ID_PARAM_NAME="wsfed_idp_state_id";
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../src/lib/constants/index.ts"],"sourcesContent":["export * from './general';\nexport * from './content';\nexport * from './uiComponents';\n\nexport const URL_RUN_IDS_PARAM_NAME = 'descope-login-flow';\nexport const URL_TOKEN_PARAM_NAME = 't';\nexport const URL_CODE_PARAM_NAME = 'code';\nexport const URL_REDIRECT_MODE_PARAM_NAME = 'redirect_mode';\nexport const URL_ERR_PARAM_NAME = 'err';\nexport const URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME = 'ra-challenge';\nexport const URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME = 'ra-callback';\nexport const URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME =\n 'ra-backup-callback';\nexport const URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME = 'ra-initiator';\nexport const DESCOPE_ATTRIBUTE_PREFIX = 'data-descope-';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_FIELD = 'data-exclude-field';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON = 'data-exclude-next';\nexport const DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY = 'dls_last_auth';\nexport const DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY =\n 'dls_last_submitted_login_id';\n// prefix only, the project and flow are appended so two flows on one page do\n// not overwrite each other\nexport const DESCOPE_SSO_QUERY_PARAMS_SESSION_STORAGE_KEY_PREFIX =\n 'dls_sso_query_params';\n// matches the server side state lifetime\nexport const SSO_QUERY_PARAMS_MAX_AGE_MS = 10 * 60 * 1000;\nexport const DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED = 'data-opt-in-last-used-auth';\n\n// SSO query params\nexport const OIDC_IDP_STATE_ID_PARAM_NAME = 'state_id';\nexport const SAML_IDP_STATE_ID_PARAM_NAME = 'saml_idp_state_id';\nexport const WSFED_IDP_STATE_ID_PARAM_NAME = 'wsfed_idp_state_id';\nexport const SAML_IDP_USERNAME_PARAM_NAME = 'saml_idp_username';\nexport const DESCOPE_IDP_INITIATED_PARAM_NAME = 'descope_idp_initiated';\nexport const SSO_APP_ID_PARAM_NAME = 'sso_app_id';\nexport const CUSTOM_APP_ID_PARAM_NAME = 'custom_app_id';\nexport const THIRD_PARTY_APP_ID_PARAM_NAME = 'third_party_app_id';\nexport const THIRD_PARTY_APP_STATE_ID_PARAM_NAME = 'third_party_app_state_id';\nexport const OIDC_LOGIN_HINT_PARAM_NAME = 'oidc_login_hint';\nexport const OIDC_PROMPT_PARAM_NAME = 'oidc_prompt';\nexport const OIDC_RESOURCE_PARAM_NAME = 'oidc_resource';\nexport const OIDC_ERROR_REDIRECT_URI_PARAM_NAME = 'oidc_error_redirect_uri';\nexport const APPLICATION_SCOPES_PARAM_NAME = 'application_scopes';\n\nexport const ELEMENT_TYPE_ATTRIBUTE = 'data-type';\n\nexport const SDK_SCRIPT_RESULTS_KEY = 'sdkScriptsResults';\n\nexport const RESPONSE_ACTIONS = {\n redirect: 'redirect',\n poll: 'poll',\n webauthnCreate: 'webauthnCreate',\n webauthnGet: 'webauthnGet',\n nativeBridge: 'nativeBridge',\n loadForm: 'loadForm',\n};\n\nexport const CUSTOM_INTERACTIONS = {\n submit: 'submit',\n polling: 'polling',\n};\n\nexport const HAS_DYNAMIC_VALUES_ATTR_NAME = 'data-has-dynamic-attr-values';\n\nexport const ELEMENTS_TO_IGNORE_ENTER_KEY_ON = [\n 'descope-multi-select-combo-box',\n 'descope-text-area',\n];\n\nexport const SDK_SCRIPTS_LOAD_TIMEOUT = 5000;\n\n// Password manager extensions can leave navigator.credentials.get/create\n// pending for minutes after their prompt is dismissed, with no signal we can\n// observe. Long on purpose, so a slow but genuine passkey is not cut off.\nexport const WEBAUTHN_TIMEOUT = 90000;\n\nexport const DESCOPE_LAST_AUTH_BADGE_COMPONENT =\n 'descope-attachment[data-type=\"last-auth-badge\"]';\n\nexport const DESCOPE_LAST_AUTH_IN_FLIGHT_LOCAL_STORAGE_KEY =\n 'dls_last_auth_in_flight';\n"],"names":["submit","polling","redirect","poll","webauthnCreate","webauthnGet","nativeBridge","loadForm"],"mappings":"8YA0C6C,sDAPL,4CAsBL,CACjCA,OAAQ,SACRC,QAAS,mDA5CoC,mEACM,+DAUH,8DAZV,yDAmBQ,kEA4C9C,wGAGA,sEA/DiD,4EAEjD,0FAIA,+DAyC6C,CAC7C,iCACA,oDAtBoC,iDAkBM,0EArBM,+DAZN,8CASF,iDACJ,+CACE,yCAQR,CAC9BC,SAAU,WACVC,KAAM,OACNC,eAAgB,iBAChBC,YAAa,cACbC,aAAc,eACdC,SAAU,iDAxBgC,yDAEA,qDAqCJ,mCAvBF,kDAZD,iDATM,0CAWE,iEACM,uDA/BhB,kCAED,2DAIhC,mEAFmD,6DADC,8DAIA,oDANV,+CAHN,kDACF,6BAqEJ,0CA3Ca"}
1
+ {"version":3,"file":"index.js","sources":["../../../src/lib/constants/index.ts"],"sourcesContent":["export * from './general';\nexport * from './content';\nexport * from './uiComponents';\n\nexport const URL_RUN_IDS_PARAM_NAME = 'descope-login-flow';\nexport const URL_TOKEN_PARAM_NAME = 't';\nexport const URL_CODE_PARAM_NAME = 'code';\nexport const URL_REDIRECT_MODE_PARAM_NAME = 'redirect_mode';\nexport const URL_ERR_PARAM_NAME = 'err';\nexport const URL_POPUP_OPENER_ORIGIN_PARAM_NAME = 'popup_opener_origin';\nexport const URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME = 'ra-challenge';\nexport const URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME = 'ra-callback';\nexport const URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME =\n 'ra-backup-callback';\nexport const URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME = 'ra-initiator';\nexport const DESCOPE_ATTRIBUTE_PREFIX = 'data-descope-';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_FIELD = 'data-exclude-field';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON = 'data-exclude-next';\nexport const DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY = 'dls_last_auth';\nexport const DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY =\n 'dls_last_submitted_login_id';\n// prefix only, the project and flow are appended so two flows on one page do\n// not overwrite each other\nexport const DESCOPE_SSO_QUERY_PARAMS_SESSION_STORAGE_KEY_PREFIX =\n 'dls_sso_query_params';\n// matches the server side state lifetime\nexport const SSO_QUERY_PARAMS_MAX_AGE_MS = 10 * 60 * 1000;\nexport const DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED = 'data-opt-in-last-used-auth';\n\n// SSO query params\nexport const OIDC_IDP_STATE_ID_PARAM_NAME = 'state_id';\nexport const SAML_IDP_STATE_ID_PARAM_NAME = 'saml_idp_state_id';\nexport const WSFED_IDP_STATE_ID_PARAM_NAME = 'wsfed_idp_state_id';\nexport const SAML_IDP_USERNAME_PARAM_NAME = 'saml_idp_username';\nexport const DESCOPE_IDP_INITIATED_PARAM_NAME = 'descope_idp_initiated';\nexport const SSO_APP_ID_PARAM_NAME = 'sso_app_id';\nexport const CUSTOM_APP_ID_PARAM_NAME = 'custom_app_id';\nexport const THIRD_PARTY_APP_ID_PARAM_NAME = 'third_party_app_id';\nexport const THIRD_PARTY_APP_STATE_ID_PARAM_NAME = 'third_party_app_state_id';\nexport const OIDC_LOGIN_HINT_PARAM_NAME = 'oidc_login_hint';\nexport const OIDC_PROMPT_PARAM_NAME = 'oidc_prompt';\nexport const OIDC_RESOURCE_PARAM_NAME = 'oidc_resource';\nexport const OIDC_ERROR_REDIRECT_URI_PARAM_NAME = 'oidc_error_redirect_uri';\nexport const APPLICATION_SCOPES_PARAM_NAME = 'application_scopes';\n\nexport const ELEMENT_TYPE_ATTRIBUTE = 'data-type';\n\nexport const SDK_SCRIPT_RESULTS_KEY = 'sdkScriptsResults';\n\nexport const RESPONSE_ACTIONS = {\n redirect: 'redirect',\n poll: 'poll',\n webauthnCreate: 'webauthnCreate',\n webauthnGet: 'webauthnGet',\n nativeBridge: 'nativeBridge',\n loadForm: 'loadForm',\n};\n\nexport const CUSTOM_INTERACTIONS = {\n submit: 'submit',\n polling: 'polling',\n};\n\nexport const HAS_DYNAMIC_VALUES_ATTR_NAME = 'data-has-dynamic-attr-values';\n\nexport const ELEMENTS_TO_IGNORE_ENTER_KEY_ON = [\n 'descope-multi-select-combo-box',\n 'descope-text-area',\n];\n\nexport const SDK_SCRIPTS_LOAD_TIMEOUT = 5000;\n\n// Password manager extensions can leave navigator.credentials.get/create\n// pending for minutes after their prompt is dismissed, with no signal we can\n// observe. Long on purpose, so a slow but genuine passkey is not cut off.\nexport const WEBAUTHN_TIMEOUT = 90000;\n\nexport const DESCOPE_LAST_AUTH_BADGE_COMPONENT =\n 'descope-attachment[data-type=\"last-auth-badge\"]';\n\nexport const DESCOPE_LAST_AUTH_IN_FLIGHT_LOCAL_STORAGE_KEY =\n 'dls_last_auth_in_flight';\n"],"names":["submit","polling","redirect","poll","webauthnCreate","webauthnGet","nativeBridge","loadForm"],"mappings":"8YA2C6C,sDAPL,4CAsBL,CACjCA,OAAQ,SACRC,QAAS,mDA5CoC,mEACM,+DAUH,8DAZV,yDAmBQ,kEA4C9C,wGAGA,sEA/DiD,4EAEjD,0FAIA,+DAyC6C,CAC7C,iCACA,oDAtBoC,iDAkBM,0EArBM,+DAZN,8CASF,iDACJ,+CACE,yCAQR,CAC9BC,SAAU,WACVC,KAAM,OACNC,eAAgB,iBAChBC,YAAa,cACbC,aAAc,eACdC,SAAU,iDAxBgC,yDAEA,qDAqCJ,mCAvBF,kDAZD,iDATM,0CAWE,iEACM,uDAhChB,kCAED,iDACgB,2EAIhD,mEAFmD,6DADC,8DAIA,oDAPV,+CAHN,kDACF,6BAsEJ,0CA3Ca"}
@@ -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/sdk-mixins/inject-style-mixin"),n=require("@descope/sdk-mixins/telemetry-mixin"),o=require("@descope/web-js-sdk"),a=require("../constants/index.js"),l=require("../helpers/helpers.js"),d=require("../helpers/state.js");require("@descope/escape-markdown"),require("../helpers/webauthn.js");var u,c,h,g,f,p,v,_,m,b,w,k,C,P,x,F,y,A,E,S,I,j,G,M,O,q,U=require("../helpers/storage.js"),L=require("../helpers/flowInputs.js"),R=require("../mixins/formMountMixin.js"),T=require("../mixins/componentConditionsMixin.js"),W=require("../mixins/duplicateFlowWarningMixin.js"),N=require("../mixins/passwordManagerMixin.js"),D=require("../mixins/validationTrackingMixin.js"),K=require("../constants/content.js"),V=require("../constants/general.js");function z(t){return Object.freeze({__proto__:null,default:t})}const H=e.compose(s.themeMixin,i.staticResourcesMixin,R.formMountMixin,T.componentConditionsMixin,W.duplicateFlowWarningMixin,N.passwordManagerMixin,r.injectStyleMixin,n.telemetryMixin,D.validationTrackingMixin)(HTMLElement);class J extends H{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","send-session-token","style-id"]}constructor(e){super(),u.add(this),this.sdkVersion="4.6.1",h.set(this,!1),g.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t.__classPrivateFieldGet(this,u,"m",q).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)}},f.set(this,new d),p.set(this,new d),v.set(this,{}),this.getComponentsContext=()=>t.__classPrivateFieldGet(this,v,"f"),this.nextRequestStatus=new d({isLoading:!1}),_.set(this,void 0),m.set(this,{popstate:t.__classPrivateFieldGet(this,u,"m",P).bind(this),componentsContext:t.__classPrivateFieldGet(this,u,"m",S).bind(this)}),b.set(this,void 0),this.getConfig=()=>t.__awaiter(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),I.set(this,void 0),j.set(this,void 0),t.__classPrivateFieldSet(this,b,e,"f"),t.__classPrivateFieldGet(this,u,"m",k).call(this)}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get sendSessionToken(){return"true"===this.getAttribute("send-session-token")}get preview(){return!!this.getAttribute("preview")}get formConfig(){return L.transformFlowInputFormData(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return L.extractNestedAttribute(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t.__classPrivateFieldGet(this,g,"f")}set customStorage(e){if(e&&"function"!=typeof e.getItem)throw new Error("Custom storage must have a getItem method");if(e&&"function"!=typeof e.setItem)throw new Error("Custom storage must have a setItem method");if(e&&"function"!=typeof e.removeItem)throw new Error("Custom storage must have a removeItem method");t.__classPrivateFieldSet(this,g,e,"f"),U.setCustomStorage(e)}get lazyStart(){return"true"===this.getAttribute("lazy-start")}start(){var e;null===(e=t.__classPrivateFieldGet(this,j,"f"))||void 0===e||e.call(this),t.__classPrivateFieldSet(this,I,Promise.resolve(),"f")}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()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,s;const r=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),n=a.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 o=this.rootElement.querySelectorAll("descope-button");if(1===o.length&&"false"!==o[0].getAttribute("auto-submit"))return void o[0].click();const l=Array.from(o).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===l.length)return void l[0].click();const d=Array.from(o).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(o).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return 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,p,"f").subscribe(t.__classPrivateFieldGet(this,u,"m",O).bind(this)),t.__classPrivateFieldGet(this,p,"f").update({isDebug:this.debug}),t.__classPrivateFieldGet(this,u,"m",C).call(this),yield t.__classPrivateFieldGet(this,u,"m",A).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");const{executionId:r,stepId:n,token:o,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:g,redirectAuthBackupCallbackUri:v,redirectAuthCodeChallenge:_,redirectAuthInitiator:b,ssoQueryParams:w}=l.handleUrlParams(this.flowId,this.projectId,this.loggerWrapper);window.addEventListener("popstate",t.__classPrivateFieldGet(this,m,"f").popstate),window.addEventListener("components-context",t.__classPrivateFieldGet(this,m,"f").componentsContext),t.__classPrivateFieldGet(this,f,"f").subscribe(t.__classPrivateFieldGet(this,u,"m",y).bind(this)),t.__classPrivateFieldGet(this,f,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:r,token:o,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:g,redirectAuthBackupCallbackUri:v,redirectAuthCodeChallenge:_,redirectAuthInitiator:b},w)),t.__classPrivateFieldSet(this,h,!0,"f")}))}disconnectedCallback(){var e;t.__classPrivateFieldGet(this,f,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,p,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,u,"m",M).call(this),window.removeEventListener("popstate",t.__classPrivateFieldGet(this,m,"f").popstate),window.removeEventListener("components-context",t.__classPrivateFieldGet(this,m,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,s){var r;if(null===(r=super.attributeChangedCallback)||void 0===r||r.call(this,e,i,s),this.shadowRoot.isConnected&&t.__classPrivateFieldGet(this,h,"f")&&i!==s&&c.observedAttributes.includes(e)){t.__classPrivateFieldGet(this,u,"m",C).call(this);const r=null===i;t.__classPrivateFieldGet(this,f,"f").update((({stepId:t,executionId:i})=>{let n=t,o=i;return r||(o=null,n=null,l.clearRunIdsFromUrl()),{[l.camelCase(e)]:s,stepId:n,executionId:o}})),t.__classPrivateFieldGet(this,p,"f").update({isDebug:this.debug})}}}c=J,h=new WeakMap,g=new WeakMap,f=new WeakMap,p=new WeakMap,v=new WeakMap,_=new WeakMap,m=new WeakMap,b=new WeakMap,I=new WeakMap,j=new WeakMap,u=new WeakSet,w=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},k=function(){t.__classPrivateFieldGet(this,u,"m",w).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},C=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","send-session-token","style-id","outbound-app-id","outbound-app-scopes","theme-override"];c.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[l.camelCase(e)])throw Error(`${e} cannot be empty`)}))},P=function(){const{stepId:e,executionId:i}=l.getRunIdsFromUrl(this.flowId);t.__classPrivateFieldGet(this,f,"f").update({stepId:e,executionId:i})},x=function(e,i){o.createSdk&&"function"==typeof o.createSdk||this.logger.error("SDK was not loaded properly",o.createSdk,JSON.stringify(o.createSdk));const s=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},c.sdkConfigOverrides),{projectId:e,baseUrl:i});t.__classPrivateFieldGet(this,g,"f")&&(s.customStorage=t.__classPrivateFieldGet(this,g,"f")),this.sdk=o.createSdk(s);const r={start:1,next:7};["start","next"].forEach((e=>{const i=this.sdk.flow[e],s=l.withRetry(i,1e3,3);this.sdk.flow[e]=(...i)=>t.__awaiter(this,void 0,void 0,(function*(){const n=[...i],o=r[e],a=t.__classPrivateFieldGet(this,u,"m",F).call(this,n[o]);void 0!==a&&(n[o]=a);try{return yield s(...n)}catch(t){return this.logger.error(`Error in sdk flow ${e} function`,t),{error:{errorCode:V.FETCH_EXCEPTION_ERROR_CODE,errorDescription:t.toString()}}}}))}));const n=this.sdk.flow.start;this.sdk.flow.start=(...e)=>t.__awaiter(this,void 0,void 0,(function*(){return yield t.__classPrivateFieldGet(this,u,"m",G).call(this),n.apply(this.sdk.flow,e)}))},F=function(t){if(!this.sendSessionToken)return t;const e=null===o.getSessionToken||void 0===o.getSessionToken?void 0:o.getSessionToken(this.storagePrefix);return e?Object.assign(Object.assign({},null!=t?t:{}),{sessionJwt:e}):t},y=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,u,"m",x).call(this,i,r)}t.__classPrivateFieldGet(this,b,"f").call(this,e)}))},A=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,u,"m",E).call(this))}))},E=function(){return t.__awaiter(this,void 0,void 0,(function*(){const t=l.getContentUrl({projectId:this.projectId,filename:K.CONFIG_FILENAME,assetsFolder:K.PREV_VER_ASSETS_FOLDER,baseUrl:this.baseStaticUrl});try{return yield l.fetchContent(t,"json"),!0}catch(t){return!1}}))},S=function(e){t.__classPrivateFieldSet(this,v,Object.assign(Object.assign({},t.__classPrivateFieldGet(this,v,"f")),e.detail),"f")},G=function(){return this.lazyStart?(t.__classPrivateFieldGet(this,I,"f")||t.__classPrivateFieldSet(this,I,new Promise((e=>{t.__classPrivateFieldSet(this,j,e,"f")})),"f"),t.__classPrivateFieldGet(this,I,"f")):Promise.resolve()},M=function(){var e;null===(e=t.__classPrivateFieldGet(this,_,"f"))||void 0===e||e.remove(),t.__classPrivateFieldSet(this,_,null,"f")},O=function(e){return t.__awaiter(this,arguments,void 0,(function*({isDebug:e}){e?(t.__classPrivateFieldSet(this,_,document.createElement("descope-debugger"),"f"),Object.assign(t.__classPrivateFieldGet(this,_,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return z(require("../debugger-wc.js"))})),document.body.appendChild(t.__classPrivateFieldGet(this,_,"f"))):t.__classPrivateFieldGet(this,u,"m",M).call(this)}))},q=function(e,i){var s;e&&this.debug&&(null===(s=t.__classPrivateFieldGet(this,_,"f"))||void 0===s||s.updateData({title:e,description:i}))},J.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.6.1"}},module.exports=J;
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/sdk-mixins/inject-style-mixin"),n=require("@descope/sdk-mixins/telemetry-mixin"),o=require("@descope/web-js-sdk"),a=require("../constants/index.js"),l=require("../helpers/helpers.js"),d=require("../helpers/state.js");require("@descope/escape-markdown"),require("../helpers/webauthn.js");var u,c,h,g,f,p,v,_,m,b,w,k,C,P,x,F,y,A,E,S,I,j,G,M,O,q,U=require("../helpers/storage.js"),L=require("../helpers/flowInputs.js"),R=require("../mixins/formMountMixin.js"),T=require("../mixins/componentConditionsMixin.js"),W=require("../mixins/duplicateFlowWarningMixin.js"),N=require("../mixins/passwordManagerMixin.js"),D=require("../mixins/validationTrackingMixin.js"),K=require("../constants/content.js"),V=require("../constants/general.js");function z(t){return Object.freeze({__proto__:null,default:t})}const H=e.compose(s.themeMixin,i.staticResourcesMixin,R.formMountMixin,T.componentConditionsMixin,W.duplicateFlowWarningMixin,N.passwordManagerMixin,r.injectStyleMixin,n.telemetryMixin,D.validationTrackingMixin)(HTMLElement);class J extends H{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","send-session-token","style-id"]}constructor(e){super(),u.add(this),this.sdkVersion="4.6.3",h.set(this,!1),g.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t.__classPrivateFieldGet(this,u,"m",q).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)}},f.set(this,new d),p.set(this,new d),v.set(this,{}),this.getComponentsContext=()=>t.__classPrivateFieldGet(this,v,"f"),this.nextRequestStatus=new d({isLoading:!1}),_.set(this,void 0),m.set(this,{popstate:t.__classPrivateFieldGet(this,u,"m",P).bind(this),componentsContext:t.__classPrivateFieldGet(this,u,"m",S).bind(this)}),b.set(this,void 0),this.getConfig=()=>t.__awaiter(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),I.set(this,void 0),j.set(this,void 0),t.__classPrivateFieldSet(this,b,e,"f"),t.__classPrivateFieldGet(this,u,"m",k).call(this)}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get sendSessionToken(){return"true"===this.getAttribute("send-session-token")}get preview(){return!!this.getAttribute("preview")}get formConfig(){return L.transformFlowInputFormData(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return L.extractNestedAttribute(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t.__classPrivateFieldGet(this,g,"f")}set customStorage(e){if(e&&"function"!=typeof e.getItem)throw new Error("Custom storage must have a getItem method");if(e&&"function"!=typeof e.setItem)throw new Error("Custom storage must have a setItem method");if(e&&"function"!=typeof e.removeItem)throw new Error("Custom storage must have a removeItem method");t.__classPrivateFieldSet(this,g,e,"f"),U.setCustomStorage(e)}get lazyStart(){return"true"===this.getAttribute("lazy-start")}start(){var e;null===(e=t.__classPrivateFieldGet(this,j,"f"))||void 0===e||e.call(this),t.__classPrivateFieldSet(this,I,Promise.resolve(),"f")}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()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,s;const r=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),n=a.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 o=this.rootElement.querySelectorAll("descope-button");if(1===o.length&&"false"!==o[0].getAttribute("auto-submit"))return void o[0].click();const l=Array.from(o).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===l.length)return void l[0].click();const d=Array.from(o).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(o).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return 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,p,"f").subscribe(t.__classPrivateFieldGet(this,u,"m",O).bind(this)),t.__classPrivateFieldGet(this,p,"f").update({isDebug:this.debug}),t.__classPrivateFieldGet(this,u,"m",C).call(this),yield t.__classPrivateFieldGet(this,u,"m",A).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");const{executionId:r,stepId:n,token:o,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:g,redirectAuthBackupCallbackUri:v,redirectAuthCodeChallenge:_,redirectAuthInitiator:b,ssoQueryParams:w}=l.handleUrlParams(this.flowId,this.projectId,this.loggerWrapper);window.addEventListener("popstate",t.__classPrivateFieldGet(this,m,"f").popstate),window.addEventListener("components-context",t.__classPrivateFieldGet(this,m,"f").componentsContext),t.__classPrivateFieldGet(this,f,"f").subscribe(t.__classPrivateFieldGet(this,u,"m",y).bind(this)),t.__classPrivateFieldGet(this,f,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:r,token:o,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:g,redirectAuthBackupCallbackUri:v,redirectAuthCodeChallenge:_,redirectAuthInitiator:b},w)),t.__classPrivateFieldSet(this,h,!0,"f")}))}disconnectedCallback(){var e;t.__classPrivateFieldGet(this,f,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,p,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,u,"m",M).call(this),window.removeEventListener("popstate",t.__classPrivateFieldGet(this,m,"f").popstate),window.removeEventListener("components-context",t.__classPrivateFieldGet(this,m,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,s){var r;if(null===(r=super.attributeChangedCallback)||void 0===r||r.call(this,e,i,s),this.shadowRoot.isConnected&&t.__classPrivateFieldGet(this,h,"f")&&i!==s&&c.observedAttributes.includes(e)){t.__classPrivateFieldGet(this,u,"m",C).call(this);const r=null===i;t.__classPrivateFieldGet(this,f,"f").update((({stepId:t,executionId:i})=>{let n=t,o=i;return r||(o=null,n=null,l.clearRunIdsFromUrl()),{[l.camelCase(e)]:s,stepId:n,executionId:o}})),t.__classPrivateFieldGet(this,p,"f").update({isDebug:this.debug})}}}c=J,h=new WeakMap,g=new WeakMap,f=new WeakMap,p=new WeakMap,v=new WeakMap,_=new WeakMap,m=new WeakMap,b=new WeakMap,I=new WeakMap,j=new WeakMap,u=new WeakSet,w=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},k=function(){t.__classPrivateFieldGet(this,u,"m",w).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},C=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","send-session-token","style-id","outbound-app-id","outbound-app-scopes","theme-override"];c.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[l.camelCase(e)])throw Error(`${e} cannot be empty`)}))},P=function(){const{stepId:e,executionId:i}=l.getRunIdsFromUrl(this.flowId);t.__classPrivateFieldGet(this,f,"f").update({stepId:e,executionId:i})},x=function(e,i){o.createSdk&&"function"==typeof o.createSdk||this.logger.error("SDK was not loaded properly",o.createSdk,JSON.stringify(o.createSdk));const s=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},c.sdkConfigOverrides),{projectId:e,baseUrl:i});t.__classPrivateFieldGet(this,g,"f")&&(s.customStorage=t.__classPrivateFieldGet(this,g,"f")),this.sdk=o.createSdk(s);const r={start:1,next:7};["start","next"].forEach((e=>{const i=this.sdk.flow[e],s=l.withRetry(i,1e3,3);this.sdk.flow[e]=(...i)=>t.__awaiter(this,void 0,void 0,(function*(){const n=[...i],o=r[e],a=t.__classPrivateFieldGet(this,u,"m",F).call(this,n[o]);void 0!==a&&(n[o]=a);try{return yield s(...n)}catch(t){return this.logger.error(`Error in sdk flow ${e} function`,t),{error:{errorCode:V.FETCH_EXCEPTION_ERROR_CODE,errorDescription:t.toString()}}}}))}));const n=this.sdk.flow.start;this.sdk.flow.start=(...e)=>t.__awaiter(this,void 0,void 0,(function*(){return yield t.__classPrivateFieldGet(this,u,"m",G).call(this),n.apply(this.sdk.flow,e)}))},F=function(t){if(!this.sendSessionToken)return t;const e=null===o.getSessionToken||void 0===o.getSessionToken?void 0:o.getSessionToken(this.storagePrefix);return e?Object.assign(Object.assign({},null!=t?t:{}),{sessionJwt:e}):t},y=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,u,"m",x).call(this,i,r)}t.__classPrivateFieldGet(this,b,"f").call(this,e)}))},A=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,u,"m",E).call(this))}))},E=function(){return t.__awaiter(this,void 0,void 0,(function*(){const t=l.getContentUrl({projectId:this.projectId,filename:K.CONFIG_FILENAME,assetsFolder:K.PREV_VER_ASSETS_FOLDER,baseUrl:this.baseStaticUrl});try{return yield l.fetchContent(t,"json"),!0}catch(t){return!1}}))},S=function(e){t.__classPrivateFieldSet(this,v,Object.assign(Object.assign({},t.__classPrivateFieldGet(this,v,"f")),e.detail),"f")},G=function(){return this.lazyStart?(t.__classPrivateFieldGet(this,I,"f")||t.__classPrivateFieldSet(this,I,new Promise((e=>{t.__classPrivateFieldSet(this,j,e,"f")})),"f"),t.__classPrivateFieldGet(this,I,"f")):Promise.resolve()},M=function(){var e;null===(e=t.__classPrivateFieldGet(this,_,"f"))||void 0===e||e.remove(),t.__classPrivateFieldSet(this,_,null,"f")},O=function(e){return t.__awaiter(this,arguments,void 0,(function*({isDebug:e}){e?(t.__classPrivateFieldSet(this,_,document.createElement("descope-debugger"),"f"),Object.assign(t.__classPrivateFieldGet(this,_,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return z(require("../debugger-wc.js"))})),document.body.appendChild(t.__classPrivateFieldGet(this,_,"f"))):t.__classPrivateFieldGet(this,u,"m",M).call(this)}))},q=function(e,i){var s;e&&this.debug&&(null===(s=t.__classPrivateFieldGet(this,_,"f"))||void 0===s||s.updateData({title:e,description:i}))},J.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.6.3"}},module.exports=J;
2
2
  //# sourceMappingURL=BaseDescopeWc.js.map
@@ -1,2 +1,2 @@
1
- "use strict";var e,t,i,s,r,o,n,a,l,d,c,u,h,p,g,v,m,_,f,b,S,w,E,I,P,R,O,C,F,y,T,A,k,W,x,N,U,L,G,j,D,M,q,V,$,B,H=require("tslib"),K=require("@descope/sdk-helpers"),X=require("@descope/web-js-sdk"),J=require("../constants/index.js"),Q=require("../helpers/helpers.js"),z=require("../helpers/state.js"),Y=require("../helpers/templates.js"),Z=require("../helpers/webauthn.js"),ee=require("../helpers/oidcSession.js"),te=require("../helpers/abTestingKey.js"),ie=require("../helpers/conditions.js"),se=require("../helpers/lastAuth.js"),re=require("../helpers/realtime-conditions/applier.js"),oe=require("./BaseDescopeWc.js"),ne=require("../constants/general.js");const ae="__descope_webauthn_timed_out__";class le extends oe{static set sdkConfigOverrides(e){oe.sdkConfigOverrides=e}static get sdkConfigOverrides(){return oe.sdkConfigOverrides}constructor(){const a=new z({deferredRedirect:!1,deferredPolling:!1});super(a.update.bind(a)),e.add(this),this.stepState=new z({}),t.set(this,void 0),i.set(this,null),s.set(this,null),r.set(this,{visibilitychange:H.__classPrivateFieldGet(this,e,"m",o).bind(this)}),this.bridgeVersion=le.bridgeVersion,n.set(this,void 0),this.nativeCallbacks={},g.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},_.set(this,(t=>{const i=()=>{this.contentRootElement.classList.toggle("hidden",t),this.slotElement.classList.toggle("hidden",!t),t&&(this.contentRootElement.innerHTML="")};t&&this.contentRootElement.hasChildNodes()?H.__classPrivateFieldGet(this,e,"m",f).call(this,i):i()})),b.set(this,((e,i,s,r,o=!1)=>{const n=[ne.FLOW_TIMED_OUT_ERROR_CODE,ne.POLLING_STATUS_NOT_FOUND_ERROR_CODE,ne.NONCE_VALIDATION_ERROR_CODE];if(this.flowState.current.action===J.RESPONSE_ACTIONS.poll){if(H.__classPrivateFieldGet(this,w,"f").call(this)&&document.hidden)return this.logger.debug("polling - Deferring polling until in foreground"),void this.flowState.update({deferredPolling:!0});this.logger.debug("polling - Scheduling polling request");const a=Date.now(),l=o?500:2e3;H.__classPrivateFieldSet(this,t,setTimeout((()=>H.__awaiter(this,void 0,void 0,(function*(){var t,d;this.logger.debug("polling - Calling next");const c=this.sdk.flow.next(e,i,J.CUSTOM_INTERACTIONS.polling,s,r,{}),u=document.hidden&&!o&&Date.now()-a>l+500;let h;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;h=yield Q.timeoutPromise(e,c)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void H.__classPrivateFieldGet(this,b,"f").call(this,e,i,s,r,u)}if((null===(t=null==h?void 0:h.error)||void 0===t?void 0:t.errorCode)===ne.FETCH_EXCEPTION_ERROR_CODE)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void H.__classPrivateFieldGet(this,b,"f").call(this,e,i,s,r);this.logger.debug("polling - Got a response"),(null==h?void 0:h.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(h.error,null,4)),(null===(d=null==h?void 0:h.error)||void 0===d?void 0:d.errorCode)&&n.includes(h.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):H.__classPrivateFieldGet(this,b,"f").call(this,e,i,s,r),H.__classPrivateFieldGet(this,E,"f").call(this,h)}))),l),"f")}})),S.set(this,(()=>{clearTimeout(H.__classPrivateFieldGet(this,t,"f")),H.__classPrivateFieldSet(this,t,null,"f")})),w.set(this,(()=>!!window.descopeBridge||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))),E.set(this,(t=>{var i,r,o,n,a,l,d,c,u,h,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,d=`${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}`;H.__classPrivateFieldGet(this,e,"m",$).call(this,"error",(null==t?void 0:t.error)||{errorCode:ne.FETCH_ERROR_RESPONSE_ERROR_CODE,errorDescription:d,errorMessage:s}),this.loggerWrapper.error((null===(n=null==t?void 0:t.error)||void 0===n?void 0:n.errorDescription)||s,(null===(a=null==t?void 0:t.error)||void 0===a?void 0:a.errorMessage)||d);const c=null===(l=null==t?void 0:t.error)||void 0===l?void 0:l.errorCode;return void(c!==ne.FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE&&c!==ne.FLOW_TIMED_OUT_ERROR_CODE&&c!==ne.NONCE_VALIDATION_ERROR_CODE||!this.isRestartOnError||H.__classPrivateFieldGet(this,e,"m",p).call(this))}null===(c=null===(d=t.data)||void 0===d?void 0:d.runnerLogs)||void 0===c||c.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===(g=null===(h=null===(u=t.data)||void 0===u?void 0:u.screen)||void 0===h?void 0:h.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}`,`${_?`${_} - `:""}${t.data.error.message}`):_&&this.loggerWrapper.error(_);const{status:f,authInfo:b,lastAuth:w,action:E,openInNewTabUrl:I}=t.data;if(E!==J.RESPONSE_ACTIONS.poll&&H.__classPrivateFieldGet(this,S,"f").call(this),"completed"===f){this.storeLastAuthenticatedUser&&se.setLastAuth(Object.assign(Object.assign({},w),{lastUsedPerScreen:se.getInFlightLastUsedPerScreen()})),se.clearInFlightLastAuth(this.loggerWrapper);const i=Object.assign({},b);return t.data.output&&Object.keys(t.data.output).length>0&&(i.flowOutput=t.data.output),this.setValidationTrackingExecution(t.data.executionId),ee.clearSsoQueryParams(this.projectId,this.flowId),void H.__classPrivateFieldGet(this,e,"m",$).call(this,"success",i)}this.storeLastAuthenticatedUser&&se.setLastAuth(w,!0),I&&window.open(I,"_blank");const{executionId:P,stepId:R,stepName:O,screen:C,redirect:F,webauthn:y,error:T,samlIdpResponse:A,wsFedIdpResponse:k,nativeResponse:W}=t.data,x=Date.now();E!==J.RESPONSE_ACTIONS.poll?(this.loggerWrapper.info(`Step "${O||`#${R}`}" is ${f}`,"",{screen:C,status:f,stepId:R,stepName:O,action:E,error:T}),(null===(m=C.state)||void 0===m?void 0:m.clientScripts)&&H.__classPrivateFieldSet(this,s,this.loadSdkScripts(C.state.clientScripts),"f"),this.flowState.update({stepId:R,stepName:O,executionId:P,action:E,redirectTo:null==F?void 0:F.url,redirectIsPopup:null==F?void 0:F.isPopup,screenId:null==C?void 0:C.id,screenState:null==C?void 0:C.state,webauthnTransactionId:null==y?void 0:y.transactionId,webauthnOptions:null==y?void 0:y.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,wsFedIdpResponseUrl:null==k?void 0:k.url,wsFedIdpResponseWresult:null==k?void 0:k.wresult,wsFedIdpResponseWctx:null==k?void 0:k.wctx,nativeResponseType:null==W?void 0:W.type,nativePayload:null==W?void 0:W.payload,reqTimestamp:x})):this.flowState.update({action:E,reqTimestamp:x})})),I.set(this,Q.withMemCache((()=>H.__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)}}))))),C.set(this,void 0),F.set(this,void 0),x.set(this,null),G.set(this,Q.leadingDebounce(((t,i,s)=>H.__awaiter(this,void 0,void 0,(function*(){var r;if("true"!==t.getAttribute("loading")&&"true"!==t.getAttribute("disabled")){if("true"===t.getAttribute("formnovalidate")||H.__classPrivateFieldGet(this,e,"m",k).call(this)){const o=null==t?void 0:t.getAttribute("id");H.__classPrivateFieldGet(this,e,"m",M).call(this,t,o,s);const n=H.__classPrivateFieldGet(this,e,"m",N).call(this,t);try{const s=yield H.__classPrivateFieldGet(this,e,"m",W).call(this),n=Q.getElementDescopeAttributes(t);this.nextRequestStatus.update({isLoading:!0});const a=Object.assign(Object.assign(Object.assign({},n),s),{origin:H.__classPrivateFieldGet(this,e,"a",A)}),l=yield i(o,a);this.nextRequestStatus.update({isLoading:!1}),this.captureLastSubmittedLoginId(s,null===(r=null==l?void 0:l.data)||void 0===r?void 0:r.executionId),this.storeCredentials(s)}catch(e){throw n(),e}}}else this.loggerWrapper.debug("Submit already in flight, ignoring")}))))),this.flowState=a,this.setValidationTrackingSender(((e,t)=>H.__awaiter(this,[e,t],void 0,(function*({executionId:e,events:t},{keepalive:i}){const s=yield this.sdk.flow.event(e,t,i);return{ok:s.ok,retryable:s.code>=500||429===s.code}}))))}nativeResume(e,t){var i,s,r,o,n,a;const l=JSON.parse(t);if("oauthWeb"===e||"sso"===e){let e,{exchangeCode:t}=l;if(!t){const r=new URL(l.url);t=null===(i=r.searchParams)||void 0===i?void 0:i.get(J.URL_CODE_PARAM_NAME),e=(null===(s=r.searchParams)||void 0===s?void 0:s.get(J.URL_ERR_PARAM_NAME))||void 0}null===(o=(r=this.nativeCallbacks).complete)||void 0===o||o.call(r,{exchangeCode:t,exchangeError:e,idpInitiated:!0})}else if("magicLink"===e){const e=new URL(l.url),t=e.searchParams.get(J.URL_TOKEN_PARAM_NAME),i=e.searchParams.get(J.URL_RUN_IDS_PARAM_NAME).split("_").pop();H.__classPrivateFieldGet(this,S,"f").call(this),this.flowState.update({token:t,stepId:i,action:void 0})}else if("beforeScreen"===e){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=l;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===e){const{interactionId:e,form:t}=l,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(n=this.nativeCallbacks).complete)||void 0===a||a.call(n,l)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[Q.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=>H.__awaiter(this,void 0,void 0,(function*(){var i,s,r;const o=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(o){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=o;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}(null===(s=globalThis.descope)||void 0===s?void 0:s[e.id])||(yield this.injectNpmLib("@descope/flow-scripts","1.0.21",`dist/${e.id}.js`));const n=null===(r=globalThis.descope)||void 0===r?void 0:r[e.id];return new Promise(((i,s)=>{try{const s=n(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i),this.loggerWrapper);if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t);const r=this.nextRequestStatus.subscribe((()=>{var i;this.loggerWrapper.debug("Stopping script",e.id),(null===(i=s.stop)||void 0===i?void 0:i.call(s))&&(this.nextRequestStatus.unsubscribe(r),this.loggerWrapper.debug("Removing script",e.id),this.shadowRoot.removeChild(t))}));"function"==typeof s.present&&i(e.id)}}catch(e){s(e)}}))})))));let s;const r=new Promise((e=>{s=setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),J.SDK_SCRIPTS_LOAD_TIMEOUT)}));return Promise.race([i,r]).finally((()=>clearTimeout(s)))}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){var e,t;if(!window.descopeBridge)return this._init();this.lazyInit=this._init,H.__classPrivateFieldSet(this,n,null===(t=null===(e=null===window||void 0===window?void 0:window.descopeBridge)||void 0===e?void 0:e.registerFlow)||void 0===t?void 0:t.call(e,this),"f")}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return H.__awaiter(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),H.__classPrivateFieldGet(this,e,"m",u).call(this),window.addEventListener("visibilitychange",H.__classPrivateFieldGet(this,r,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var e,t,s;super.disconnectedCallback(),this.teardownValidationTracking(),H.__classPrivateFieldGet(this,n,"f")&&(null===(t=null===(e=window.descopeBridge)||void 0===e?void 0:e.unregisterFlow)||void 0===t||t.call(e,H.__classPrivateFieldGet(this,n,"f")),H.__classPrivateFieldSet(this,n,void 0,"f")),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),H.__classPrivateFieldGet(this,S,"f").call(this),null===(s=H.__classPrivateFieldGet(this,i,"f"))||void 0===s||s.abort(),H.__classPrivateFieldSet(this,i,null,"f"),window.removeEventListener("visibilitychange",H.__classPrivateFieldGet(this,r,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return H.__awaiter(this,void 0,void 0,(function*(){let i;const s=K.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 H.__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 H.__awaiter(this,void 0,void 0,(function*(){var n,a;const{projectId:l,flowId:c,tenant:u,stepId:h,executionId:p,action:g,screenId:_,screenState:f,redirectTo:S,redirectIsPopup:w,redirectUrl:I,token:P,code:R,isPopup:O,exchangeError:T,webauthnTransactionId:k,webauthnOptions:W,redirectAuthCodeChallenge:x,redirectAuthCallbackUrl:N,redirectAuthBackupCallbackUri:U,redirectAuthInitiator:L,locale:G,samlIdpResponseUrl:D,samlIdpResponseSamlResponse:M,samlIdpResponseRelayState:q,wsFedIdpResponseUrl:V,wsFedIdpResponseWresult:z,wsFedIdpResponseWctx:Y,nativeResponseType:Z,nativePayload:ee,reqTimestamp:re}=t,oe=H.__rest(t,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx","nativeResponseType","nativePayload","reqTimestamp"]);let ne,ae,le;const de=te.getABTestingKey(),{outboundAppId:ce,outboundAppScopes:ue}=this,he=this.sdk.getLastUserLoginId();o("flowId")&&this.setValidationTrackingEnabled(!1);const pe=yield this.getFlowConfig();H.__classPrivateFieldGet(this,e,"m",y).call(this,pe,p,o);const ge=yield this.getProjectConfig(),ve=Object.entries(ge.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),me=N&&x?{callbackUrl:N,codeChallenge:x,backupCallbackUri:U}:void 0,_e=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect,externalAuthRedirect:this.nativeOptions.externalAuthRedirect}:void 0;let fe={};if(!p){se.clearInFlightLastAuth(this.loggerWrapper);const t=[...pe.clientScripts||[],...pe.sdkScripts||[]];if(pe.conditions){let e=[];({startScreenId:ne,conditionInteractionId:le,startScreenName:ae,clientScripts:e,componentsConfig:fe}=ie.calculateConditions({loginId:he,code:R,token:P,abTestingKey:de,lastAuth:se.getLastAuth(he,this.loggerWrapper)},pe.conditions)),t.push(...e||[])}else pe.condition?({startScreenId:ne,startScreenName:ae,conditionInteractionId:le}=ie.calculateCondition(pe.condition,{loginId:he,code:R,token:P,abTestingKey:de,lastAuth:se.getLastAuth(he,this.loggerWrapper)})):(ae=pe.startScreenName,ne=pe.startScreenId);if(H.__classPrivateFieldSet(this,C,ne,"f"),H.__classPrivateFieldSet(this,F,ae,"f"),H.__classPrivateFieldSet(this,s,this.loadSdkScripts(t),"f"),pe.fingerprintEnabled&&pe.fingerprintKey?yield X.ensureFingerprintIds(pe.fingerprintKey,this.baseUrl):X.clearFingerprintData(),!Q.showFirstScreenOnExecutionInit(ne,oe)){const t=yield this.sdk.flow.start(c,Object.assign(Object.assign(Object.assign(Object.assign({tenant:u,redirectAuth:me},oe),{client:this.client}),I&&{redirectUrl:I}),{lastAuth:se.getLastAuth(he,this.loggerWrapper),abTestingKey:de,locale:K.getUserLocale(G).locale,nativeOptions:_e,outboundAppId:ce,outboundAppScopes:ue}),le,"",ge.componentsVersion,ve,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:H.__classPrivateFieldGet(this,e,"a",A)},this.formConfigValues),R?{exchangeCode:R,idpInitiated:!0}:{}),oe.descopeIdpInitiated&&{idpInitiated:!0}),P?{token:P}:{}),oe.oidcLoginHint?{externalId:oe.oidcLoginHint}:{}));return H.__classPrivateFieldGet(this,E,"f").call(this,t),void("completed"!==(null===(n=null==t?void 0:t.data)||void 0===n?void 0:n.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:O,code:R,exchangeError:T,isCodeChanged:o("code"),isExchangeErrorChanged:o("exchangeError")})),O&&(o("code")&&R||o("exchangeError")&&T))return void H.__classPrivateFieldGet(this,e,"m",B).call(this,p,R,T);if(p&&(o("token")&&P||o("code")&&R||o("exchangeError")&&T)){const t=yield this.sdk.flow.next(p,h,J.CUSTOM_INTERACTIONS.submit,pe.version,ge.componentsVersion,{token:P,exchangeCode:R,exchangeError:T,origin:H.__classPrivateFieldGet(this,e,"a",A)});return H.__classPrivateFieldGet(this,E,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(g===J.RESPONSE_ACTIONS.loadForm&&D&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>o(e)))){if(!M)return void this.loggerWrapper.error("Did not get saml idp params data to load");Q.injectSamlIdpForm(D,M,q||"",Q.submitForm)}if(g===J.RESPONSE_ACTIONS.loadForm&&V&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>o(e)))){if(!z)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");Q.injectWsFedIdpForm(V,z,Y||"",Q.submitForm)}if(g===J.RESPONSE_ACTIONS.redirect&&(o("redirectTo")||o("deferredRedirect"))){if(!S)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===S)return;if("android"===L&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${w}`),w){this.loggerWrapper.debug("Opening redirect in popup");const t=Q.openCenteredPopup(S,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));let s=!1;const r=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const t=i?this.popupOrigin:window.location.origin;if(e.origin!==t)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${t}"`);const{action:r,data:o}=e.data||{};"code"===r&&(s=!0,this.flowState.update({code:o.code,exchangeError:o.exchangeError}))};let o;this.loggerWrapper.debug("Starting popup closed detection");const n=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(n),H.__classPrivateFieldGet(this,e,"m",$).call(this,"popupclosed",{abandoned:!s}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==o||o())}),1e3);if(i)window.addEventListener("message",r),o=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",r)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(p);e.onmessage=r,o=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(S),this.flowState.update({redirectTo:"no-op"}),H.__classPrivateFieldGet(this,e,"m",$).call(this,"popupclosed",{});return}if(g===J.RESPONSE_ACTIONS.webauthnCreate||g===J.RESPONSE_ACTIONS.webauthnGet){if(!k||!W)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");null===(a=H.__classPrivateFieldGet(this,i,"f"))||void 0===a||a.abort(),H.__classPrivateFieldSet(this,i,null,"f");const t=yield H.__classPrivateFieldGet(this,e,"m",m).call(this,g,W),s=yield this.sdk.flow.next(p,h,J.CUSTOM_INTERACTIONS.submit,pe.version,ge.componentsVersion,Object.assign({transactionId:k},t));H.__classPrivateFieldGet(this,E,"f").call(this,s)}if(g===J.RESPONSE_ACTIONS.nativeBridge)return this.nativeCallbacks.complete=e=>H.__awaiter(this,void 0,void 0,(function*(){const t=yield this.sdk.flow.next(p,h,J.CUSTOM_INTERACTIONS.submit,pe.version,ge.componentsVersion,e);H.__classPrivateFieldGet(this,E,"f").call(this,t)})),H.__classPrivateFieldGet(this,e,"m",d).call(this,Z,ee),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if((o("action")||o("deferredPolling"))&&H.__classPrivateFieldGet(this,b,"f").call(this,p,h,pe.version,ge.componentsVersion),!_&&!ne)return void this.loggerWrapper.warn("No screen was found to show");const be=ne||_,Se=yield this.getHtmlFilenameWithLocale(G,be),{oidcLoginHint:we,oidcPrompt:Ee,oidcErrorRedirectUri:Ie,oidcResource:Pe,samlIdpUsername:Re}=oe,Oe={direction:Q.getAnimationDirection(h,r.stepId),screenState:Object.assign(Object.assign({},f),{form:Object.assign(Object.assign({},this.formConfigValues),null==f?void 0:f.form),lastAuth:{loginId:he,name:this.sdk.getLastUserDisplayName()||he},componentsConfig:Object.assign(Object.assign(Object.assign({},pe.componentsConfig),fe),null==f?void 0:f.componentsConfig)}),htmlFilename:`${be}.html`,htmlLocaleFilename:Se,screenId:be,stepName:t.stepName||ae,samlIdpUsername:Re,oidcLoginHint:we,oidcPrompt:Ee,oidcErrorRedirectUri:Ie,oidcResource:Pe,action:g,locale:K.getUserLocale(G).locale},Ce=se.getLastAuth(he,this.loggerWrapper);Q.showFirstScreenOnExecutionInit(ne,oe)?Oe.next=(t,i)=>H.__awaiter(this,void 0,void 0,(function*(){const s=(null==pe?void 0:pe.clientScripts)||[];yield H.__classPrivateFieldGet(this,e,"m",j).call(this,s);const r=yield this.sdk.flow.start(c,Object.assign(Object.assign(Object.assign(Object.assign({tenant:u,redirectAuth:me},oe),{lastAuth:Ce,preview:this.preview,abTestingKey:de,client:this.client}),I&&{redirectUrl:I}),{locale:K.getUserLocale(G).locale,nativeOptions:_e,outboundAppId:ce,outboundAppScopes:ue}),le,t,ge.componentsVersion,ve,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),Q.transformScreenInputs(i)),R&&{exchangeCode:R,idpInitiated:!0}),oe.descopeIdpInitiated&&{idpInitiated:!0}),P&&{token:P}),Oe.next.isCustomScreen);return H.__classPrivateFieldGet(this,E,"f").call(this,r),r})):(o("projectId")||o("baseUrl")||o("executionId")||o("stepId"))&&(Oe.next=(t,i)=>H.__awaiter(this,void 0,void 0,(function*(){const s=(null==f?void 0:f.clientScripts)||[];yield H.__classPrivateFieldGet(this,e,"m",j).call(this,s);const r=yield this.sdk.flow.next(p,h,t,pe.version,ge.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),Q.transformScreenInputs(i)),Oe.next.isCustomScreen);return H.__classPrivateFieldGet(this,E,"f").call(this,r),r}))),this.loggerWrapper.debug("Got a screen with id",Oe.screenId),yield H.__classPrivateFieldGet(this,e,"m",v).call(this,Oe),this.stepState.update(Oe)}))}onStepChange(t,i){return H.__awaiter(this,void 0,void 0,(function*(){var s,r,o;const{htmlFilename:n,htmlLocaleFilename:a,direction:l,next:d,screenState:c,screenId:u}=t;this.loggerWrapper.debug("Rendering a flow screen"),this.updateScreenUser(null==c?void 0:c.user);const h=document.createElement("template");h.innerHTML=yield this.getPageContent(n,a);const p=h.content.cloneNode(!0),g=this.loadDescopeUiComponents(h);this.sdk.webauthn.helpers.isSupported()?yield H.__classPrivateFieldGet(this,e,"m",R).call(this,p,d):Y.disableWebauthnButtons(p),!t.samlIdpUsername||(null===(s=c.form)||void 0===s?void 0:s.loginId)||(null===(r=c.form)||void 0===r?void 0:r.email)||(c.form||(c.form={}),c.form.loginId=t.samlIdpUsername,c.form.email=t.samlIdpUsername),Y.updateTemplateFromScreenState(p,c,this.formConfig,this.loggerWrapper),this.applyComponentsState(p,null==c?void 0:c.componentsState);const{geo:v}=null!==(o=yield this.getExecutionContext())&&void 0!==o?o:{};Y.setComponentsAutoDetectByGeo(p,v),Y.setComponentsAutoDetectByLocale(p,t.locale);const m=()=>H.__awaiter(this,void 0,void 0,(function*(){var s,r;yield g;const o=this.contentRootElement;Y.setTOTPVariable(o,null===(s=null==c?void 0:c.totp)||void 0===s?void 0:s.image),Y.setNOTPVariable(o,null===(r=null==c?void 0:c.notp)||void 0===r?void 0:r.image),Y.setCssVars(o,p,c.cssVars,this.loggerWrapper),o.replaceChildren(p);const n=!i.htmlFilename;setTimeout((()=>{H.__classPrivateFieldGet(this,e,"m",U).call(this),this.updateUsernameAnchor(),this.validateOnBlur&&Q.handleReportValidityOnBlur(o,(t=>this.trackValidationErrors([t],H.__classPrivateFieldGet(this,e,"a",T)))),Y.updateScreenFromScreenState(o,c),this.initRealtimeConditions(o,c),H.__classPrivateFieldGet(this,e,"m",O).call(this,{isFirstScreen:n,isCustomScreen:!1,stepName:t.stepName}),Q.handleAutoFocus(o,this.autoFocus,n),H.__classPrivateFieldGet(this,e,"m",q).call(this,u)})),H.__classPrivateFieldGet(this,e,"m",V).call(this,d,u);o.querySelector(`[${J.ELEMENT_TYPE_ATTRIBUTE}="polling"]`)&&d(J.CUSTOM_INTERACTIONS.polling,{})}));l?H.__classPrivateFieldGet(this,e,"m",f).call(this,m):m()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${J.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}t=new WeakMap,i=new WeakMap,s=new WeakMap,r=new WeakMap,n=new WeakMap,g=new WeakMap,_=new WeakMap,b=new WeakMap,S=new WeakMap,w=new WeakMap,E=new WeakMap,I=new WeakMap,C=new WeakMap,F=new WeakMap,x=new WeakMap,G=new WeakMap,e=new WeakSet,o=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1,deferredPolling:!1})}),300)},a=function(t,i,s){return H.__awaiter(this,void 0,void 0,(function*(){var r;return(null===(r=this.nativeOptions)||void 0===r?void 0:r.bridgeVersion)>=2&&new Promise((r=>{this.nativeCallbacks.screenNext=s,this.nativeCallbacks.screenResolve=r,H.__classPrivateFieldGet(this,e,"m",d).call(this,"beforeScreen",{screen:t,context:i})}))}))},l=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&H.__classPrivateFieldGet(this,e,"m",d).call(this,"afterScreen",{screen:t})},d=function(t,i){H.__classPrivateFieldGet(this,e,"m",$).call(this,"bridge",{type:t,payload:i})},c=function({errorText:e,errorType:t}){const i=()=>{var i;let s=e;try{s=(null===(i=this.errorTransformer)||void 0===i?void 0:i.call(this,{text:e,type:t}))||e}catch(e){this.loggerWrapper.error("Error transforming error message",e.message)}Y.replaceElementMessage(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},u=function(){var t,i,s,r;null===(t=this.stepState)||void 0===t||t.subscribe(this.onStepChange.bind(this),(e=>{var t=e.screenState,i=void 0===t?{}:t,{errorText:s,errorType:r}=i,o=H.__rest(i,["errorText","errorType"]),n=H.__rest(e,["screenState"]);return Object.assign(Object.assign({},n),{screenState:o})})),null===(i=this.stepState)||void 0===i||i.subscribe(H.__classPrivateFieldGet(this,e,"m",c).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(s=this.stepState)||void 0===s||s.subscribe(H.__classPrivateFieldGet(this,e,"m",h).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(r=this.flowState)||void 0===r||r.subscribe((({screenId:e,executionId:t})=>{var i;try{this.updateTelemetryContext({screenId:e,executionId:t})}catch(e){null===(i=this.logger)||void 0===i||i.error("Error updating telemetry screenId:",e)}}),(e=>({screenId:e.screenId,executionId:e.executionId})))},h=function({errorText:e,errorType:t}){(t||e)&&(this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((e=>{e.shadowRoot.querySelectorAll("descope-text-field[data-id]").forEach((e=>{e.value=""}))})),Q.handleAutoFocus(this.contentRootElement,this.autoFocus,!1))},p=function(){return H.__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")}))},v=function(t){return H.__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=H.__rest(s,["next","stepName"]),l=Q.transformStepStateForCustomScreen(n);let d=yield H.__classPrivateFieldGet(this,e,"m",a).call(this,o,l,r);d||(d=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,o,l,r,this)));const c=!this.stepState.current.htmlFilename;if(H.__classPrivateFieldGet(this,_,"f").call(this,d),r&&(r.isCustomScreen=d),H.__classPrivateFieldGet(this,g,"f")!==d){const[t,i]=["flow","custom"].sort((()=>d?-1:1));this.loggerWrapper.debug(`Switching from ${i} screen to ${t} screen`),H.__classPrivateFieldSet(this,g,d,"f"),d?this.stepState.unsubscribeAll():H.__classPrivateFieldGet(this,e,"m",u).call(this)}d?(this.loggerWrapper.debug("Showing a custom screen"),H.__classPrivateFieldGet(this,e,"m",O).call(this,{isFirstScreen:c,isCustomScreen:d,stepName:t.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=d}))},m=function(e,t){return H.__awaiter(this,void 0,void 0,(function*(){const i=new AbortController;try{const s=e===J.RESPONSE_ACTIONS.webauthnCreate?this.sdk.webauthn.helpers.create(t,i):this.sdk.webauthn.helpers.get(t,i),r=yield Q.timeoutPromise(J.WEBAUTHN_TIMEOUT,s,ae);return r!==ae?{response:r}:(i.abort(),this.loggerWrapper.warn(`WebAuthn operation timed out after ${J.WEBAUTHN_TIMEOUT}ms`),{failure:"AbortError",failureReason:"aborted",failureMessage:"Passkey operation timed out"})}catch(e){return"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),{failure:e.name,failureReason:e.reason,failureMessage:e.message}}}))},f=function(e){this.contentRootElement.addEventListener("transitionend",(()=>{this.loggerWrapper.debug("page switch transition end"),this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0}),this.loggerWrapper.debug("page switch transition start"),this.contentRootElement.classList.add("fade-out")},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)}))}},R=function(t,s){return H.__awaiter(this,void 0,void 0,(function*(){var r;null===(r=H.__classPrivateFieldGet(this,i,"f"))||void 0===r||r.abort();const o=t.querySelector('*[autocomplete="webauthn"]');if(o&&(yield Z.isConditionalLoginSupported())){const{options:t,transactionId:r}=(yield H.__classPrivateFieldGet(this,I,"f").call(this))||{};t&&r&&(H.__classPrivateFieldGet(this,e,"m",P).call(this,o),H.__classPrivateFieldSet(this,i,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(t,H.__classPrivateFieldGet(this,i,"f")).then((e=>H.__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)})))}}))},O=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&H.__classPrivateFieldGet(this,e,"m",$).call(this,"ready",{}),i||H.__classPrivateFieldGet(this,e,"m",l).call(this,s),H.__classPrivateFieldGet(this,e,"m",$).call(this,"page-updated",{screenName:s}),H.__classPrivateFieldGet(this,e,"m",$).call(this,"screen-updated",{screenName:s})},y=function(e,t,i){this.setValidationTrackingEnabled(!!e.clientValidationTrackingEnabled),t&&i("executionId")&&this.setValidationTrackingExecution(t)},T=function(){var e,t,i,s,r,o,n;const a=null===(e=this.flowState)||void 0===e?void 0:e.current;return(null==a?void 0:a.executionId)?{executionId:a.executionId,screenId:a.screenId,screenName:(null===(n=null===(o=this.stepState)||void 0===o?void 0:o.current)||void 0===n?void 0:n.stepName)||a.stepName}:{executionId:void 0,screenId:null!==(t=H.__classPrivateFieldGet(this,C,"f"))&&void 0!==t?t:null==a?void 0:a.screenId,screenName:null!==(i=H.__classPrivateFieldGet(this,F,"f"))&&void 0!==i?i:(null===(r=null===(s=this.stepState)||void 0===s?void 0:s.current)||void 0===r?void 0:r.stepName)||(null==a?void 0:a.stepName)}},A=function(){var e;return(null===(e=this.nativeOptions)||void 0===e?void 0:e.origin)||window.location.origin},k=function(){let t=!0;const i=[];return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((e=>{var s,r,o;"slot"===e.localName||re.isHiddenByCondition(e,this.contentRootElement)||(null===(s=e.reportValidity)||void 0===s||s.call(e),e.validity&&!e.validity.valid&&i.push(e),t&&(t=null===(o=null===(r=e.checkValidity)||void 0===r?void 0:r.call(e))||void 0===o||o))})),i.length&&this.trackValidationErrors(i,H.__classPrivateFieldGet(this,e,"a",T)),t},W=function(){return H.__awaiter(this,void 0,void 0,(function*(){const e=this.getInputs();return(yield Promise.all(e.map((e=>H.__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})),{})}))},N=function(e){var t,i;const r=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((t=>t!==e)),o=(null===(i=null===(t=this.flowState.current)||void 0===t?void 0:t.screenState)||void 0===i?void 0:i.clientScripts)||[];e.setAttribute("loading","true"),r.forEach((e=>e.setAttribute("disabled","true")));const n=()=>{e.removeAttribute("loading"),r.forEach((e=>{e.removeAttribute("disabled")}))},a=e=>H.__awaiter(this,void 0,void 0,(function*(){var t;this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",a);if(!0===(null===(t=null==e?void 0:e.detail)||void 0===t?void 0:t.abandoned)&&o.length)return H.__classPrivateFieldSet(this,s,(()=>H.__awaiter(this,void 0,void 0,(function*(){try{yield this.loadSdkScripts(o)}catch(e){this.loggerWrapper.warn("Failed to refresh client scripts on popup close",null==e?void 0:e.message)}})))(),"f"),void n();n();const i=yield this.getFlowConfig(),r=[...i.clientScripts||[],...i.sdkScripts||[]];this.loadSdkScripts(r)})),l=()=>{var e;window.removeEventListener("pageshow",H.__classPrivateFieldGet(this,x,"f")),H.__classPrivateFieldSet(this,x,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),a())}),"f"),window.addEventListener("pageshow",H.__classPrivateFieldGet(this,x,"f"),{once:!0});const t=null===(e=this.stepState)||void 0===e?void 0:e.subscribe(((e,i)=>{e===i&&a(),this.removeEventListener("popupclosed",a),this.stepState.unsubscribe(t)}),(e=>e.screenId),{forceUpdate:!0})},d=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?this.addEventListener("popupclosed",a,{once:!0}):(this.nextRequestStatus.unsubscribe(d),"success"===this.flowStatus?(this.removeEventListener("popupclosed",a),n()):l())}));return n},U=function(){Q.clearPreviousExternalInputs();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>H.__classPrivateFieldGet(this,e,"m",L).call(this,t)))},L=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)}))},j=function(e){return H.__awaiter(this,void 0,void 0,(function*(){if(H.__classPrivateFieldGet(this,s,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const e=Date.now();yield H.__classPrivateFieldGet(this,s,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-e).toString())}const t=this.loadSdkScriptsModules(),i=e.map((e=>e.id));for(const e of t)if(i.includes(e.id))try{if("function"==typeof e.present){(yield e.present())||this.loggerWrapper.debug(`Sdk script ${e.id} was cancelled`)}}catch(t){this.loggerWrapper.error(`Failed to present ${e.id} script module`,t.message)}const r=[];for(const e of t)"function"==typeof e.refresh&&r.push(e.refresh());if(r.length>0)try{yield Q.timeoutPromise(J.SDK_SCRIPTS_LOAD_TIMEOUT,Promise.all(r),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},D=function(e,t){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((i=>{i.addEventListener("input",(()=>{var s;(null===(s=i.checkValidity)||void 0===s?void 0:s.call(i))&&H.__classPrivateFieldGet(this,G,"f").call(this,i,e,t)}))}))},M=function(e,t,i){t&&i&&"true"===e.getAttribute(J.DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED)&&se.updateLastUsedPerScreen(i,t,this.loggerWrapper)},q=function(e){var t;const i=this.sdk.getLastUserLoginId(),s=null===(t=se.getLastAuth(i,this.loggerWrapper).lastUsedPerScreen)||void 0===t?void 0:t[e];if(!s)return;const r=this.contentRootElement.querySelector(J.DESCOPE_LAST_AUTH_BADGE_COMPONENT),o=this.contentRootElement.querySelector(`#${CSS.escape(s)}`);r&&o&&(o.replaceWith(r),r.appendChild(o))},V=function(t,i){this.contentRootElement.querySelectorAll(`descope-button:not([${J.DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON}]), [data-type="button"]:not([${J.DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON}]`).forEach((e=>{e.onclick=()=>{H.__classPrivateFieldGet(this,G,"f").call(this,e,t,i)}})),H.__classPrivateFieldGet(this,e,"m",D).call(this,t,i),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${J.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},$=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},B=function(e,t,i){var s;const[r,o]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],n={data:{code:t,exchangeError:i},action:"code"};if("descope-wc"===r&&o){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",o);try{window.opener.postMessage(n,o)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(n),t.close()}try{window.close()}catch(e){}},le.bridgeVersion=3,module.exports=le;
1
+ "use strict";var e,t,i,s,r,o,n,a,l,d,c,u,p,h,g,v,m,_,f,b,S,w,E,I,P,R,O,C,F,T,y,A,k,W,x,N,U,L,G,j,D,M,q,V,$,B,H=require("tslib"),K=require("@descope/sdk-helpers"),X=require("@descope/web-js-sdk"),J=require("../constants/index.js"),Q=require("../helpers/helpers.js"),z=require("../helpers/state.js"),Y=require("../helpers/templates.js"),Z=require("../helpers/webauthn.js"),ee=require("../helpers/oidcSession.js"),te=require("../helpers/abTestingKey.js"),ie=require("../helpers/conditions.js"),se=require("../helpers/lastAuth.js"),re=require("../helpers/realtime-conditions/applier.js"),oe=require("./BaseDescopeWc.js"),ne=require("../constants/general.js");const ae="__descope_webauthn_timed_out__";class le extends oe{static set sdkConfigOverrides(e){oe.sdkConfigOverrides=e}static get sdkConfigOverrides(){return oe.sdkConfigOverrides}constructor(){const a=new z({deferredRedirect:!1,deferredPolling:!1});super(a.update.bind(a)),e.add(this),this.stepState=new z({}),t.set(this,void 0),i.set(this,null),s.set(this,null),r.set(this,{visibilitychange:H.__classPrivateFieldGet(this,e,"m",o).bind(this)}),this.bridgeVersion=le.bridgeVersion,n.set(this,void 0),this.nativeCallbacks={},g.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},_.set(this,(t=>{const i=()=>{this.contentRootElement.classList.toggle("hidden",t),this.slotElement.classList.toggle("hidden",!t),t&&(this.contentRootElement.innerHTML="")};t&&this.contentRootElement.hasChildNodes()?H.__classPrivateFieldGet(this,e,"m",f).call(this,i):i()})),b.set(this,((e,i,s,r,o=!1)=>{const n=[ne.FLOW_TIMED_OUT_ERROR_CODE,ne.POLLING_STATUS_NOT_FOUND_ERROR_CODE,ne.NONCE_VALIDATION_ERROR_CODE];if(this.flowState.current.action===J.RESPONSE_ACTIONS.poll){if(H.__classPrivateFieldGet(this,w,"f").call(this)&&document.hidden)return this.logger.debug("polling - Deferring polling until in foreground"),void this.flowState.update({deferredPolling:!0});this.logger.debug("polling - Scheduling polling request");const a=Date.now(),l=o?500:2e3;H.__classPrivateFieldSet(this,t,setTimeout((()=>H.__awaiter(this,void 0,void 0,(function*(){var t,d;this.logger.debug("polling - Calling next");const c=this.sdk.flow.next(e,i,J.CUSTOM_INTERACTIONS.polling,s,r,{}),u=document.hidden&&!o&&Date.now()-a>l+500;let p;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;p=yield Q.timeoutPromise(e,c)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void H.__classPrivateFieldGet(this,b,"f").call(this,e,i,s,r,u)}if((null===(t=null==p?void 0:p.error)||void 0===t?void 0:t.errorCode)===ne.FETCH_EXCEPTION_ERROR_CODE)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void H.__classPrivateFieldGet(this,b,"f").call(this,e,i,s,r);this.logger.debug("polling - Got a response"),(null==p?void 0:p.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(p.error,null,4)),(null===(d=null==p?void 0:p.error)||void 0===d?void 0:d.errorCode)&&n.includes(p.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):H.__classPrivateFieldGet(this,b,"f").call(this,e,i,s,r),H.__classPrivateFieldGet(this,E,"f").call(this,p)}))),l),"f")}})),S.set(this,(()=>{clearTimeout(H.__classPrivateFieldGet(this,t,"f")),H.__classPrivateFieldSet(this,t,null,"f")})),w.set(this,(()=>!!window.descopeBridge||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))),E.set(this,(t=>{var i,r,o,n,a,l,d,c,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,d=`${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}`;H.__classPrivateFieldGet(this,e,"m",$).call(this,"error",(null==t?void 0:t.error)||{errorCode:ne.FETCH_ERROR_RESPONSE_ERROR_CODE,errorDescription:d,errorMessage:s}),this.loggerWrapper.error((null===(n=null==t?void 0:t.error)||void 0===n?void 0:n.errorDescription)||s,(null===(a=null==t?void 0:t.error)||void 0===a?void 0:a.errorMessage)||d);const c=null===(l=null==t?void 0:t.error)||void 0===l?void 0:l.errorCode;return void(c!==ne.FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE&&c!==ne.FLOW_TIMED_OUT_ERROR_CODE&&c!==ne.NONCE_VALIDATION_ERROR_CODE||!this.isRestartOnError||H.__classPrivateFieldGet(this,e,"m",h).call(this))}null===(c=null===(d=t.data)||void 0===d?void 0:d.runnerLogs)||void 0===c||c.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===(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}`,`${_?`${_} - `:""}${t.data.error.message}`):_&&this.loggerWrapper.error(_);const{status:f,authInfo:b,lastAuth:w,action:E,openInNewTabUrl:I}=t.data;if(E!==J.RESPONSE_ACTIONS.poll&&H.__classPrivateFieldGet(this,S,"f").call(this),"completed"===f){this.storeLastAuthenticatedUser&&se.setLastAuth(Object.assign(Object.assign({},w),{lastUsedPerScreen:se.getInFlightLastUsedPerScreen()})),se.clearInFlightLastAuth(this.loggerWrapper);const i=Object.assign({},b);return t.data.output&&Object.keys(t.data.output).length>0&&(i.flowOutput=t.data.output),this.setValidationTrackingExecution(t.data.executionId),ee.clearSsoQueryParams(this.projectId,this.flowId),void H.__classPrivateFieldGet(this,e,"m",$).call(this,"success",i)}this.storeLastAuthenticatedUser&&se.setLastAuth(w,!0),I&&window.open(I,"_blank");const{executionId:P,stepId:R,stepName:O,screen:C,redirect:F,webauthn:T,error:y,samlIdpResponse:A,wsFedIdpResponse:k,nativeResponse:W}=t.data,x=Date.now();E!==J.RESPONSE_ACTIONS.poll?(this.loggerWrapper.info(`Step "${O||`#${R}`}" is ${f}`,"",{screen:C,status:f,stepId:R,stepName:O,action:E,error:y}),(null===(m=C.state)||void 0===m?void 0:m.clientScripts)&&H.__classPrivateFieldSet(this,s,this.loadSdkScripts(C.state.clientScripts),"f"),this.flowState.update({stepId:R,stepName:O,executionId:P,action:E,redirectTo:null==F?void 0:F.url,redirectIsPopup:null==F?void 0:F.isPopup,screenId:null==C?void 0:C.id,screenState:null==C?void 0:C.state,webauthnTransactionId:null==T?void 0:T.transactionId,webauthnOptions:null==T?void 0:T.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,wsFedIdpResponseUrl:null==k?void 0:k.url,wsFedIdpResponseWresult:null==k?void 0:k.wresult,wsFedIdpResponseWctx:null==k?void 0:k.wctx,nativeResponseType:null==W?void 0:W.type,nativePayload:null==W?void 0:W.payload,reqTimestamp:x})):this.flowState.update({action:E,reqTimestamp:x})})),I.set(this,Q.withMemCache((()=>H.__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)}}))))),C.set(this,void 0),F.set(this,void 0),x.set(this,null),G.set(this,Q.leadingDebounce(((t,i,s)=>H.__awaiter(this,void 0,void 0,(function*(){var r;if("true"!==t.getAttribute("loading")&&"true"!==t.getAttribute("disabled")){if("true"===t.getAttribute("formnovalidate")||H.__classPrivateFieldGet(this,e,"m",k).call(this)){const o=null==t?void 0:t.getAttribute("id");H.__classPrivateFieldGet(this,e,"m",M).call(this,t,o,s);const n=H.__classPrivateFieldGet(this,e,"m",N).call(this,t);try{const s=yield H.__classPrivateFieldGet(this,e,"m",W).call(this),n=Q.getElementDescopeAttributes(t);this.nextRequestStatus.update({isLoading:!0});const a=Object.assign(Object.assign(Object.assign({},n),s),{origin:H.__classPrivateFieldGet(this,e,"a",A)}),l=yield i(o,a);this.nextRequestStatus.update({isLoading:!1}),this.captureLastSubmittedLoginId(s,null===(r=null==l?void 0:l.data)||void 0===r?void 0:r.executionId),this.storeCredentials(s)}catch(e){throw n(),e}}}else this.loggerWrapper.debug("Submit already in flight, ignoring")}))))),this.flowState=a,this.setValidationTrackingSender(((e,t)=>H.__awaiter(this,[e,t],void 0,(function*({executionId:e,events:t},{keepalive:i}){const s=yield this.sdk.flow.event(e,t,i);return{ok:s.ok,retryable:s.code>=500||429===s.code}}))))}nativeResume(e,t){var i,s,r,o,n,a;const l=JSON.parse(t);if("oauthWeb"===e||"sso"===e){let e,{exchangeCode:t}=l;if(!t){const r=new URL(l.url);t=null===(i=r.searchParams)||void 0===i?void 0:i.get(J.URL_CODE_PARAM_NAME),e=(null===(s=r.searchParams)||void 0===s?void 0:s.get(J.URL_ERR_PARAM_NAME))||void 0}null===(o=(r=this.nativeCallbacks).complete)||void 0===o||o.call(r,{exchangeCode:t,exchangeError:e,idpInitiated:!0})}else if("magicLink"===e){const e=new URL(l.url),t=e.searchParams.get(J.URL_TOKEN_PARAM_NAME),i=e.searchParams.get(J.URL_RUN_IDS_PARAM_NAME).split("_").pop();H.__classPrivateFieldGet(this,S,"f").call(this),this.flowState.update({token:t,stepId:i,action:void 0})}else if("beforeScreen"===e){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=l;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===e){const{interactionId:e,form:t}=l,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(n=this.nativeCallbacks).complete)||void 0===a||a.call(n,l)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[Q.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=>H.__awaiter(this,void 0,void 0,(function*(){var i,s,r;const o=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(o){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=o;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}(null===(s=globalThis.descope)||void 0===s?void 0:s[e.id])||(yield this.injectNpmLib("@descope/flow-scripts","1.0.21",`dist/${e.id}.js`));const n=null===(r=globalThis.descope)||void 0===r?void 0:r[e.id];return new Promise(((i,s)=>{try{const s=n(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i),this.loggerWrapper);if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t);const r=this.nextRequestStatus.subscribe((()=>{var i;this.loggerWrapper.debug("Stopping script",e.id),(null===(i=s.stop)||void 0===i?void 0:i.call(s))&&(this.nextRequestStatus.unsubscribe(r),this.loggerWrapper.debug("Removing script",e.id),this.shadowRoot.removeChild(t))}));"function"==typeof s.present&&i(e.id)}}catch(e){s(e)}}))})))));let s;const r=new Promise((e=>{s=setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),J.SDK_SCRIPTS_LOAD_TIMEOUT)}));return Promise.race([i,r]).finally((()=>clearTimeout(s)))}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){var e,t;if(!window.descopeBridge)return this._init();this.lazyInit=this._init,H.__classPrivateFieldSet(this,n,null===(t=null===(e=null===window||void 0===window?void 0:window.descopeBridge)||void 0===e?void 0:e.registerFlow)||void 0===t?void 0:t.call(e,this),"f")}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return H.__awaiter(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),H.__classPrivateFieldGet(this,e,"m",u).call(this),window.addEventListener("visibilitychange",H.__classPrivateFieldGet(this,r,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var e,t,s;super.disconnectedCallback(),this.teardownValidationTracking(),H.__classPrivateFieldGet(this,n,"f")&&(null===(t=null===(e=window.descopeBridge)||void 0===e?void 0:e.unregisterFlow)||void 0===t||t.call(e,H.__classPrivateFieldGet(this,n,"f")),H.__classPrivateFieldSet(this,n,void 0,"f")),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),H.__classPrivateFieldGet(this,S,"f").call(this),null===(s=H.__classPrivateFieldGet(this,i,"f"))||void 0===s||s.abort(),H.__classPrivateFieldSet(this,i,null,"f"),window.removeEventListener("visibilitychange",H.__classPrivateFieldGet(this,r,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return H.__awaiter(this,void 0,void 0,(function*(){let i;const s=K.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 H.__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 H.__awaiter(this,void 0,void 0,(function*(){var n,a;const{projectId:l,flowId:c,tenant:u,stepId:p,executionId:h,action:g,screenId:_,screenState:f,redirectTo:S,redirectIsPopup:w,redirectUrl:I,token:P,code:R,isPopup:O,exchangeError:y,webauthnTransactionId:k,webauthnOptions:W,redirectAuthCodeChallenge:x,redirectAuthCallbackUrl:N,redirectAuthBackupCallbackUri:U,redirectAuthInitiator:L,locale:G,samlIdpResponseUrl:D,samlIdpResponseSamlResponse:M,samlIdpResponseRelayState:q,wsFedIdpResponseUrl:V,wsFedIdpResponseWresult:z,wsFedIdpResponseWctx:Y,nativeResponseType:Z,nativePayload:ee,reqTimestamp:re}=t,oe=H.__rest(t,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx","nativeResponseType","nativePayload","reqTimestamp"]);let ne,ae,le;const de=te.getABTestingKey(),{outboundAppId:ce,outboundAppScopes:ue}=this,pe=this.sdk.getLastUserLoginId();o("flowId")&&this.setValidationTrackingEnabled(!1);const he=yield this.getFlowConfig();H.__classPrivateFieldGet(this,e,"m",T).call(this,he,h,o);const ge=yield this.getProjectConfig(),ve=Object.entries(ge.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),me=N&&x?{callbackUrl:N,codeChallenge:x,backupCallbackUri:U}:void 0,_e=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect,externalAuthRedirect:this.nativeOptions.externalAuthRedirect}:void 0;let fe={};if(!h){se.clearInFlightLastAuth(this.loggerWrapper);const t=[...he.clientScripts||[],...he.sdkScripts||[]];if(he.conditions){let e=[];({startScreenId:ne,conditionInteractionId:le,startScreenName:ae,clientScripts:e,componentsConfig:fe}=ie.calculateConditions({loginId:pe,code:R,token:P,abTestingKey:de,lastAuth:se.getLastAuth(pe,this.loggerWrapper)},he.conditions)),t.push(...e||[])}else he.condition?({startScreenId:ne,startScreenName:ae,conditionInteractionId:le}=ie.calculateCondition(he.condition,{loginId:pe,code:R,token:P,abTestingKey:de,lastAuth:se.getLastAuth(pe,this.loggerWrapper)})):(ae=he.startScreenName,ne=he.startScreenId);if(H.__classPrivateFieldSet(this,C,ne,"f"),H.__classPrivateFieldSet(this,F,ae,"f"),H.__classPrivateFieldSet(this,s,this.loadSdkScripts(t),"f"),he.fingerprintEnabled&&he.fingerprintKey?yield X.ensureFingerprintIds(he.fingerprintKey,this.baseUrl):X.clearFingerprintData(),!Q.showFirstScreenOnExecutionInit(ne,oe)){const t=yield this.sdk.flow.start(c,Object.assign(Object.assign(Object.assign(Object.assign({tenant:u,redirectAuth:me},oe),{client:this.client}),I&&{redirectUrl:I}),{lastAuth:se.getLastAuth(pe,this.loggerWrapper),abTestingKey:de,locale:K.getUserLocale(G).locale,nativeOptions:_e,outboundAppId:ce,outboundAppScopes:ue}),le,"",ge.componentsVersion,ve,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:H.__classPrivateFieldGet(this,e,"a",A)},this.formConfigValues),R?{exchangeCode:R,idpInitiated:!0}:{}),oe.descopeIdpInitiated&&{idpInitiated:!0}),P?{token:P}:{}),oe.oidcLoginHint?{externalId:oe.oidcLoginHint}:{}));return H.__classPrivateFieldGet(this,E,"f").call(this,t),void("completed"!==(null===(n=null==t?void 0:t.data)||void 0===n?void 0:n.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:O,code:R,exchangeError:y,isCodeChanged:o("code"),isExchangeErrorChanged:o("exchangeError")})),O&&(o("code")&&R||o("exchangeError")&&y))return void H.__classPrivateFieldGet(this,e,"m",B).call(this,h,R,y);if(h&&(o("token")&&P||o("code")&&R||o("exchangeError")&&y)){const t=yield this.sdk.flow.next(h,p,J.CUSTOM_INTERACTIONS.submit,he.version,ge.componentsVersion,{token:P,exchangeCode:R,exchangeError:y,origin:H.__classPrivateFieldGet(this,e,"a",A)});return H.__classPrivateFieldGet(this,E,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(g===J.RESPONSE_ACTIONS.loadForm&&D&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>o(e)))){if(!M)return void this.loggerWrapper.error("Did not get saml idp params data to load");Q.injectSamlIdpForm(D,M,q||"",Q.submitForm)}if(g===J.RESPONSE_ACTIONS.loadForm&&V&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>o(e)))){if(!z)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");Q.injectWsFedIdpForm(V,z,Y||"",Q.submitForm)}if(g===J.RESPONSE_ACTIONS.redirect&&(o("redirectTo")||o("deferredRedirect"))){if(!S)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===S)return;if("android"===L&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${w}`),w){this.loggerWrapper.debug("Opening redirect in popup");const t=Q.openCenteredPopup(S,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));let s=!1;const r=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const t=i?this.popupOrigin:window.location.origin;if(e.origin!==t)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${t}"`);const{action:r,data:o}=e.data||{};"code"===r&&(s=!0,this.flowState.update({code:o.code,exchangeError:o.exchangeError}))};let o;this.loggerWrapper.debug("Starting popup closed detection");const n=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(n),H.__classPrivateFieldGet(this,e,"m",$).call(this,"popupclosed",{abandoned:!s}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==o||o())}),1e3);if(i)window.addEventListener("message",r),o=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",r)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(h);e.onmessage=r,o=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(S),this.flowState.update({redirectTo:"no-op"}),H.__classPrivateFieldGet(this,e,"m",$).call(this,"popupclosed",{});return}if(g===J.RESPONSE_ACTIONS.webauthnCreate||g===J.RESPONSE_ACTIONS.webauthnGet){if(!k||!W)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");null===(a=H.__classPrivateFieldGet(this,i,"f"))||void 0===a||a.abort(),H.__classPrivateFieldSet(this,i,null,"f");const t=yield H.__classPrivateFieldGet(this,e,"m",m).call(this,g,W),s=yield this.sdk.flow.next(h,p,J.CUSTOM_INTERACTIONS.submit,he.version,ge.componentsVersion,Object.assign({transactionId:k},t));H.__classPrivateFieldGet(this,E,"f").call(this,s)}if(g===J.RESPONSE_ACTIONS.nativeBridge)return this.nativeCallbacks.complete=e=>H.__awaiter(this,void 0,void 0,(function*(){const t=yield this.sdk.flow.next(h,p,J.CUSTOM_INTERACTIONS.submit,he.version,ge.componentsVersion,e);H.__classPrivateFieldGet(this,E,"f").call(this,t)})),H.__classPrivateFieldGet(this,e,"m",d).call(this,Z,ee),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if((o("action")||o("deferredPolling"))&&H.__classPrivateFieldGet(this,b,"f").call(this,h,p,he.version,ge.componentsVersion),!_&&!ne)return void this.loggerWrapper.warn("No screen was found to show");const be=ne||_,Se=yield this.getHtmlFilenameWithLocale(G,be),{oidcLoginHint:we,oidcPrompt:Ee,oidcErrorRedirectUri:Ie,oidcResource:Pe,samlIdpUsername:Re}=oe,Oe={direction:Q.getAnimationDirection(p,r.stepId),screenState:Object.assign(Object.assign({},f),{form:Object.assign(Object.assign({},this.formConfigValues),null==f?void 0:f.form),lastAuth:{loginId:pe,name:this.sdk.getLastUserDisplayName()||pe},componentsConfig:Object.assign(Object.assign(Object.assign({},he.componentsConfig),fe),null==f?void 0:f.componentsConfig)}),htmlFilename:`${be}.html`,htmlLocaleFilename:Se,screenId:be,stepName:t.stepName||ae,samlIdpUsername:Re,oidcLoginHint:we,oidcPrompt:Ee,oidcErrorRedirectUri:Ie,oidcResource:Pe,action:g,locale:K.getUserLocale(G).locale},Ce=se.getLastAuth(pe,this.loggerWrapper);Q.showFirstScreenOnExecutionInit(ne,oe)?Oe.next=(t,i)=>H.__awaiter(this,void 0,void 0,(function*(){const s=(null==he?void 0:he.clientScripts)||[];yield H.__classPrivateFieldGet(this,e,"m",j).call(this,s);const r=yield this.sdk.flow.start(c,Object.assign(Object.assign(Object.assign(Object.assign({tenant:u,redirectAuth:me},oe),{lastAuth:Ce,preview:this.preview,abTestingKey:de,client:this.client}),I&&{redirectUrl:I}),{locale:K.getUserLocale(G).locale,nativeOptions:_e,outboundAppId:ce,outboundAppScopes:ue}),le,t,ge.componentsVersion,ve,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),Q.transformScreenInputs(i)),R&&{exchangeCode:R,idpInitiated:!0}),oe.descopeIdpInitiated&&{idpInitiated:!0}),P&&{token:P}),Oe.next.isCustomScreen);return H.__classPrivateFieldGet(this,E,"f").call(this,r),r})):(o("projectId")||o("baseUrl")||o("executionId")||o("stepId"))&&(Oe.next=(t,i)=>H.__awaiter(this,void 0,void 0,(function*(){const s=(null==f?void 0:f.clientScripts)||[];yield H.__classPrivateFieldGet(this,e,"m",j).call(this,s);const r=yield this.sdk.flow.next(h,p,t,he.version,ge.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),Q.transformScreenInputs(i)),Oe.next.isCustomScreen);return H.__classPrivateFieldGet(this,E,"f").call(this,r),r}))),this.loggerWrapper.debug("Got a screen with id",Oe.screenId),yield H.__classPrivateFieldGet(this,e,"m",v).call(this,Oe),this.stepState.update(Oe)}))}onStepChange(t,i){return H.__awaiter(this,void 0,void 0,(function*(){var s,r,o;const{htmlFilename:n,htmlLocaleFilename:a,direction:l,next:d,screenState:c,screenId:u}=t;this.loggerWrapper.debug("Rendering a flow screen"),this.updateScreenUser(null==c?void 0:c.user);const p=document.createElement("template");p.innerHTML=yield this.getPageContent(n,a);const h=p.content.cloneNode(!0),g=this.loadDescopeUiComponents(p);this.sdk.webauthn.helpers.isSupported()?yield H.__classPrivateFieldGet(this,e,"m",R).call(this,h,d):Y.disableWebauthnButtons(h),!t.samlIdpUsername||(null===(s=c.form)||void 0===s?void 0:s.loginId)||(null===(r=c.form)||void 0===r?void 0:r.email)||(c.form||(c.form={}),c.form.loginId=t.samlIdpUsername,c.form.email=t.samlIdpUsername),Y.updateTemplateFromScreenState(h,c,this.formConfig,this.loggerWrapper),this.applyComponentsState(h,null==c?void 0:c.componentsState);const{geo:v}=null!==(o=yield this.getExecutionContext())&&void 0!==o?o:{};Y.setComponentsAutoDetectByGeo(h,v),Y.setComponentsAutoDetectByLocale(h,t.locale);const m=()=>H.__awaiter(this,void 0,void 0,(function*(){var s,r;yield g;const o=this.contentRootElement;Y.setTOTPVariable(o,null===(s=null==c?void 0:c.totp)||void 0===s?void 0:s.image),Y.setNOTPVariable(o,null===(r=null==c?void 0:c.notp)||void 0===r?void 0:r.image),Y.setCssVars(o,h,c.cssVars,this.loggerWrapper),o.replaceChildren(h);const n=!i.htmlFilename;setTimeout((()=>{H.__classPrivateFieldGet(this,e,"m",U).call(this),this.updateUsernameAnchor(),this.validateOnBlur&&Q.handleReportValidityOnBlur(o,(t=>this.trackValidationErrors([t],H.__classPrivateFieldGet(this,e,"a",y)))),Y.updateScreenFromScreenState(o,c),this.initRealtimeConditions(o,c),H.__classPrivateFieldGet(this,e,"m",O).call(this,{isFirstScreen:n,isCustomScreen:!1,stepName:t.stepName}),Q.handleAutoFocus(o,this.autoFocus,n),H.__classPrivateFieldGet(this,e,"m",q).call(this,u)})),H.__classPrivateFieldGet(this,e,"m",V).call(this,d,u);o.querySelector(`[${J.ELEMENT_TYPE_ATTRIBUTE}="polling"]`)&&d(J.CUSTOM_INTERACTIONS.polling,{})}));l?H.__classPrivateFieldGet(this,e,"m",f).call(this,m):m()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${J.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}t=new WeakMap,i=new WeakMap,s=new WeakMap,r=new WeakMap,n=new WeakMap,g=new WeakMap,_=new WeakMap,b=new WeakMap,S=new WeakMap,w=new WeakMap,E=new WeakMap,I=new WeakMap,C=new WeakMap,F=new WeakMap,x=new WeakMap,G=new WeakMap,e=new WeakSet,o=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1,deferredPolling:!1})}),300)},a=function(t,i,s){return H.__awaiter(this,void 0,void 0,(function*(){var r;return(null===(r=this.nativeOptions)||void 0===r?void 0:r.bridgeVersion)>=2&&new Promise((r=>{this.nativeCallbacks.screenNext=s,this.nativeCallbacks.screenResolve=r,H.__classPrivateFieldGet(this,e,"m",d).call(this,"beforeScreen",{screen:t,context:i})}))}))},l=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&H.__classPrivateFieldGet(this,e,"m",d).call(this,"afterScreen",{screen:t})},d=function(t,i){H.__classPrivateFieldGet(this,e,"m",$).call(this,"bridge",{type:t,payload:i})},c=function({errorText:e,errorType:t}){const i=()=>{var i;let s=e;try{s=(null===(i=this.errorTransformer)||void 0===i?void 0:i.call(this,{text:e,type:t}))||e}catch(e){this.loggerWrapper.error("Error transforming error message",e.message)}Y.replaceElementMessage(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},u=function(){var t,i,s,r;null===(t=this.stepState)||void 0===t||t.subscribe(this.onStepChange.bind(this),(e=>{var t=e.screenState,i=void 0===t?{}:t,{errorText:s,errorType:r}=i,o=H.__rest(i,["errorText","errorType"]),n=H.__rest(e,["screenState"]);return Object.assign(Object.assign({},n),{screenState:o})})),null===(i=this.stepState)||void 0===i||i.subscribe(H.__classPrivateFieldGet(this,e,"m",c).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(s=this.stepState)||void 0===s||s.subscribe(H.__classPrivateFieldGet(this,e,"m",p).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(r=this.flowState)||void 0===r||r.subscribe((({screenId:e,executionId:t})=>{var i;try{this.updateTelemetryContext({screenId:e,executionId:t})}catch(e){null===(i=this.logger)||void 0===i||i.error("Error updating telemetry screenId:",e)}}),(e=>({screenId:e.screenId,executionId:e.executionId})))},p=function({errorText:e,errorType:t}){(t||e)&&(this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((e=>{e.shadowRoot.querySelectorAll("descope-text-field[data-id]").forEach((e=>{e.value=""}))})),Q.handleAutoFocus(this.contentRootElement,this.autoFocus,!1))},h=function(){return H.__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")}))},v=function(t){return H.__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=H.__rest(s,["next","stepName"]),l=Q.transformStepStateForCustomScreen(n);let d=yield H.__classPrivateFieldGet(this,e,"m",a).call(this,o,l,r);d||(d=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,o,l,r,this)));const c=!this.stepState.current.htmlFilename;if(H.__classPrivateFieldGet(this,_,"f").call(this,d),r&&(r.isCustomScreen=d),H.__classPrivateFieldGet(this,g,"f")!==d){const[t,i]=["flow","custom"].sort((()=>d?-1:1));this.loggerWrapper.debug(`Switching from ${i} screen to ${t} screen`),H.__classPrivateFieldSet(this,g,d,"f"),d?this.stepState.unsubscribeAll():H.__classPrivateFieldGet(this,e,"m",u).call(this)}d?(this.loggerWrapper.debug("Showing a custom screen"),H.__classPrivateFieldGet(this,e,"m",O).call(this,{isFirstScreen:c,isCustomScreen:d,stepName:t.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=d}))},m=function(e,t){return H.__awaiter(this,void 0,void 0,(function*(){const i=new AbortController;try{const s=e===J.RESPONSE_ACTIONS.webauthnCreate?this.sdk.webauthn.helpers.create(t,i):this.sdk.webauthn.helpers.get(t,i),r=yield Q.timeoutPromise(J.WEBAUTHN_TIMEOUT,s,ae);return r!==ae?{response:r}:(i.abort(),this.loggerWrapper.warn(`WebAuthn operation timed out after ${J.WEBAUTHN_TIMEOUT}ms`),{failure:"AbortError",failureReason:"aborted",failureMessage:"Passkey operation timed out"})}catch(e){return"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),{failure:e.name,failureReason:e.reason,failureMessage:e.message}}}))},f=function(e){this.contentRootElement.addEventListener("transitionend",(()=>{this.loggerWrapper.debug("page switch transition end"),this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0}),this.loggerWrapper.debug("page switch transition start"),this.contentRootElement.classList.add("fade-out")},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)}))}},R=function(t,s){return H.__awaiter(this,void 0,void 0,(function*(){var r;null===(r=H.__classPrivateFieldGet(this,i,"f"))||void 0===r||r.abort();const o=t.querySelector('*[autocomplete="webauthn"]');if(o&&(yield Z.isConditionalLoginSupported())){const{options:t,transactionId:r}=(yield H.__classPrivateFieldGet(this,I,"f").call(this))||{};t&&r&&(H.__classPrivateFieldGet(this,e,"m",P).call(this,o),H.__classPrivateFieldSet(this,i,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(t,H.__classPrivateFieldGet(this,i,"f")).then((e=>H.__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)})))}}))},O=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&H.__classPrivateFieldGet(this,e,"m",$).call(this,"ready",{}),i||H.__classPrivateFieldGet(this,e,"m",l).call(this,s),H.__classPrivateFieldGet(this,e,"m",$).call(this,"page-updated",{screenName:s}),H.__classPrivateFieldGet(this,e,"m",$).call(this,"screen-updated",{screenName:s})},T=function(e,t,i){this.setValidationTrackingEnabled(!!e.clientValidationTrackingEnabled),t&&i("executionId")&&this.setValidationTrackingExecution(t)},y=function(){var e,t,i,s,r,o,n;const a=null===(e=this.flowState)||void 0===e?void 0:e.current;return(null==a?void 0:a.executionId)?{executionId:a.executionId,screenId:a.screenId,screenName:(null===(n=null===(o=this.stepState)||void 0===o?void 0:o.current)||void 0===n?void 0:n.stepName)||a.stepName}:{executionId:void 0,screenId:null!==(t=H.__classPrivateFieldGet(this,C,"f"))&&void 0!==t?t:null==a?void 0:a.screenId,screenName:null!==(i=H.__classPrivateFieldGet(this,F,"f"))&&void 0!==i?i:(null===(r=null===(s=this.stepState)||void 0===s?void 0:s.current)||void 0===r?void 0:r.stepName)||(null==a?void 0:a.stepName)}},A=function(){var e;return(null===(e=this.nativeOptions)||void 0===e?void 0:e.origin)||window.location.origin},k=function(){let t=!0;const i=[];return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((e=>{var s,r,o;"slot"===e.localName||re.isHiddenByCondition(e,this.contentRootElement)||(null===(s=e.reportValidity)||void 0===s||s.call(e),e.validity&&!e.validity.valid&&i.push(e),t&&(t=null===(o=null===(r=e.checkValidity)||void 0===r?void 0:r.call(e))||void 0===o||o))})),i.length&&this.trackValidationErrors(i,H.__classPrivateFieldGet(this,e,"a",y)),t},W=function(){return H.__awaiter(this,void 0,void 0,(function*(){const e=this.getInputs();return(yield Promise.all(e.map((e=>H.__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})),{})}))},N=function(e){var t,i;const r=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((t=>t!==e)),o=(null===(i=null===(t=this.flowState.current)||void 0===t?void 0:t.screenState)||void 0===i?void 0:i.clientScripts)||[];e.setAttribute("loading","true"),r.forEach((e=>e.setAttribute("disabled","true")));const n=()=>{e.removeAttribute("loading"),r.forEach((e=>{e.removeAttribute("disabled")}))},a=e=>H.__awaiter(this,void 0,void 0,(function*(){var t;this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",a);if(!0===(null===(t=null==e?void 0:e.detail)||void 0===t?void 0:t.abandoned)&&o.length)return H.__classPrivateFieldSet(this,s,(()=>H.__awaiter(this,void 0,void 0,(function*(){try{yield this.loadSdkScripts(o)}catch(e){this.loggerWrapper.warn("Failed to refresh client scripts on popup close",null==e?void 0:e.message)}})))(),"f"),void n();n();const i=yield this.getFlowConfig(),r=[...i.clientScripts||[],...i.sdkScripts||[]];this.loadSdkScripts(r)})),l=()=>{var e;window.removeEventListener("pageshow",H.__classPrivateFieldGet(this,x,"f")),H.__classPrivateFieldSet(this,x,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),a())}),"f"),window.addEventListener("pageshow",H.__classPrivateFieldGet(this,x,"f"),{once:!0});const t=null===(e=this.stepState)||void 0===e?void 0:e.subscribe(((e,i)=>{e===i&&a(),this.removeEventListener("popupclosed",a),this.stepState.unsubscribe(t)}),(e=>e.screenId),{forceUpdate:!0})},d=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?this.addEventListener("popupclosed",a,{once:!0}):(this.nextRequestStatus.unsubscribe(d),"success"===this.flowStatus?(this.removeEventListener("popupclosed",a),n()):l())}));return n},U=function(){Q.clearPreviousExternalInputs();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>H.__classPrivateFieldGet(this,e,"m",L).call(this,t)))},L=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)}))},j=function(e){return H.__awaiter(this,void 0,void 0,(function*(){if(H.__classPrivateFieldGet(this,s,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const e=Date.now();yield H.__classPrivateFieldGet(this,s,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-e).toString())}const t=this.loadSdkScriptsModules(),i=e.map((e=>e.id));for(const e of t)if(i.includes(e.id))try{if("function"==typeof e.present){(yield e.present())||this.loggerWrapper.debug(`Sdk script ${e.id} was cancelled`)}}catch(t){this.loggerWrapper.error(`Failed to present ${e.id} script module`,t.message)}const r=[];for(const e of t)"function"==typeof e.refresh&&r.push(e.refresh());if(r.length>0)try{yield Q.timeoutPromise(J.SDK_SCRIPTS_LOAD_TIMEOUT,Promise.all(r),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},D=function(e,t){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((i=>{i.addEventListener("input",(()=>{var s;(null===(s=i.checkValidity)||void 0===s?void 0:s.call(i))&&H.__classPrivateFieldGet(this,G,"f").call(this,i,e,t)}))}))},M=function(e,t,i){t&&i&&"true"===e.getAttribute(J.DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED)&&se.updateLastUsedPerScreen(i,t,this.loggerWrapper)},q=function(e){var t;const i=this.sdk.getLastUserLoginId(),s=null===(t=se.getLastAuth(i,this.loggerWrapper).lastUsedPerScreen)||void 0===t?void 0:t[e];if(!s)return;const r=this.contentRootElement.querySelector(J.DESCOPE_LAST_AUTH_BADGE_COMPONENT),o=this.contentRootElement.querySelector(`#${CSS.escape(s)}`);r&&o&&(o.replaceWith(r),r.appendChild(o))},V=function(t,i){this.contentRootElement.querySelectorAll(`descope-button:not([${J.DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON}]), [data-type="button"]:not([${J.DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON}]`).forEach((e=>{e.onclick=()=>{H.__classPrivateFieldGet(this,G,"f").call(this,e,t,i)}})),H.__classPrivateFieldGet(this,e,"m",D).call(this,t,i),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${J.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},$=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},B=function(e,t,i){var s;const[r,o]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],n="descope-wc"===r&&!!o,a=n?Q.getTrustedPopupOpenerOrigin(o):void 0;n&&!a&&this.loggerWrapper.warn("Popup opener origin is not approved for this project, add it to the approved domains to send the OAuth result to it",o);const l={data:{code:t,exchangeError:i},action:"code"};if(a){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",a);try{window.opener.postMessage(l,a)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(l),t.close()}try{window.close()}catch(e){}},le.bridgeVersion=3,module.exports=le;
2
2
  //# sourceMappingURL=DescopeWc.js.map