@descope/web-component 3.49.0 → 3.49.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"BaseDescopeWc.js","sources":["../../../src/lib/descope-wc/BaseDescopeWc.ts"],"sourcesContent":["import { compose } from '@descope/sdk-helpers';\n// eslint-disable-next-line import/no-duplicates\nimport { staticResourcesMixin } from '@descope/sdk-mixins/static-resources-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { themeMixin } from '@descope/sdk-mixins/theme-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { injectStyleMixin } from '@descope/sdk-mixins/inject-style-mixin';\nimport { createSdk } from '@descope/web-js-sdk';\nimport {\n CONFIG_FILENAME,\n ELEMENTS_TO_IGNORE_ENTER_KEY_ON,\n FETCH_EXCEPTION_ERROR_CODE,\n PREV_VER_ASSETS_FOLDER,\n} from '../constants';\nimport {\n camelCase,\n clearRunIdsFromUrl,\n fetchContent,\n getContentUrl,\n getRunIdsFromUrl,\n handleUrlParams,\n State,\n} from '../helpers';\nimport {\n extractNestedAttribute,\n transformFlowInputFormData,\n} from '../helpers/flowInputs';\nimport { setCustomStorage } from '../helpers/storage';\nimport { IsChanged } from '../helpers/state';\nimport { formMountMixin } from '../mixins';\nimport {\n AutoFocusOptions,\n CustomStorage,\n DebuggerMessage,\n DebugState,\n DescopeUI,\n FlowConfig,\n FlowState,\n FlowStateUpdateFn,\n FlowStatus,\n ProjectConfiguration,\n SdkConfig,\n} from '../types';\n\n// this is replaced in build time\ndeclare const BUILD_VERSION: string;\n\nconst BaseClass = compose(\n themeMixin,\n staticResourcesMixin,\n formMountMixin,\n injectStyleMixin,\n)(HTMLElement);\n\n// this base class is responsible for WC initialization\nclass BaseDescopeWc extends BaseClass {\n static get observedAttributes() {\n return [\n 'project-id',\n 'flow-id',\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'storage-prefix',\n 'preview',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'refresh-cookie-name',\n 'keep-last-authenticated-user-after-logout',\n 'validate-on-blur',\n 'style-id',\n ];\n }\n\n // this is a way for extending the sdk config from outside\n static sdkConfigOverrides: Partial<SdkConfig> = {\n baseHeaders: {\n 'x-descope-sdk-name': 'web-component',\n 'x-descope-sdk-version': BUILD_VERSION,\n },\n };\n\n #init = false;\n\n #customStorage: CustomStorage | undefined;\n\n flowStatus: FlowStatus = 'initial';\n\n loggerWrapper = {\n error: (message: string, description = '') => {\n this.logger.error(message, description, new Error());\n this.#updateDebuggerMessages(message, description);\n },\n warn: (message: string, description = '') => {\n this.logger.warn(message, description);\n },\n info: (message: string, description = '', state: any = {}) => {\n this.logger.info(message, description, state);\n },\n debug: (message: string, description = '') => {\n this.logger.debug(message, description);\n },\n };\n\n #flowState = new State<FlowState>();\n\n #debugState = new State<DebugState>();\n\n #componentsContext = {};\n\n getComponentsContext = () => this.#componentsContext;\n\n nextRequestStatus = new State<{ isLoading: boolean }>({ isLoading: false });\n\n rootElement: HTMLDivElement;\n\n contentRootElement: HTMLDivElement;\n\n slotElement: HTMLSlotElement;\n\n #debuggerEle: HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n #eventsCbRefs = {\n popstate: this.#syncStateIdFromUrl.bind(this),\n componentsContext: this.#handleComponentsContext.bind(this),\n };\n\n sdk: ReturnType<typeof createSdk>;\n\n #updateExecState: FlowStateUpdateFn;\n\n descopeUI: Promise<DescopeUI>;\n\n constructor(updateExecState: FlowStateUpdateFn) {\n super();\n this.#updateExecState = updateExecState;\n\n this.#initShadowDom();\n }\n\n #loadInitStyle() {\n 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 `);\n }\n\n #initShadowDom() {\n this.#loadInitStyle();\n this.slotElement = document.createElement('slot');\n this.slotElement.classList.add('hidden');\n this.rootElement.appendChild(this.slotElement);\n }\n\n get flowId() {\n return this.getAttribute('flow-id');\n }\n\n get client() {\n try {\n return (JSON.parse(this.getAttribute('client')) || {}) as Record<\n string,\n any\n >;\n } catch (e) {\n return {};\n }\n }\n\n get tenantId() {\n return this.getAttribute('tenant') || undefined;\n }\n\n get redirectUrl() {\n return this.getAttribute('redirect-url') || undefined;\n }\n\n get debug() {\n return this.getAttribute('debug') === 'true';\n }\n\n get locale() {\n return this.getAttribute('locale') || undefined;\n }\n\n get autoFocus(): AutoFocusOptions {\n const res = this.getAttribute('auto-focus') ?? 'true';\n if (res === 'skipFirstScreen') {\n return res;\n }\n return res === 'true';\n }\n\n get validateOnBlur() {\n return this.getAttribute('validate-on-blur') === 'true';\n }\n\n get storeLastAuthenticatedUser() {\n const res = this.getAttribute('store-last-authenticated-user') ?? 'true';\n return res === 'true';\n }\n\n get refreshCookieName() {\n return this.getAttribute('refresh-cookie-name') || '';\n }\n\n get keepLastAuthenticatedUserAfterLogout() {\n const res = this.getAttribute('keep-last-authenticated-user-after-logout');\n return res === 'true';\n }\n\n get storagePrefix() {\n return this.getAttribute('storage-prefix') || '';\n }\n\n get preview() {\n return !!this.getAttribute('preview');\n }\n\n get formConfig() {\n return transformFlowInputFormData(this.form);\n }\n\n get form() {\n return this.getAttribute('form');\n }\n\n get formConfigValues() {\n return extractNestedAttribute(this.formConfig, 'value');\n }\n\n get outboundAppId() {\n return this.getAttribute('outbound-app-id');\n }\n\n get outboundAppScopes() {\n try {\n const scopes = JSON.parse(this.getAttribute('outbound-app-scopes'));\n if (!scopes) return null;\n return scopes;\n } catch (err) {\n return null;\n }\n }\n\n get popupOrigin(): string | null {\n return this.getAttribute('popup-origin');\n }\n\n // grouped getter/setter for customStorage\n get customStorage(): CustomStorage | undefined {\n return this.#customStorage;\n }\n\n set customStorage(storage: CustomStorage | undefined) {\n if (storage && typeof storage.getItem !== 'function') {\n throw new Error('Custom storage must have a getItem method');\n }\n if (storage && typeof storage.setItem !== 'function') {\n throw new Error('Custom storage must have a setItem method');\n }\n if (storage && typeof storage.removeItem !== 'function') {\n throw new Error('Custom storage must have a removeItem method');\n }\n this.#customStorage = storage;\n setCustomStorage(storage);\n }\n\n #validateAttrs() {\n const optionalAttributes = [\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'refresh-cookie-name',\n 'keep-last-authenticated-user-after-logout',\n 'preview',\n 'storage-prefix',\n 'form',\n 'client',\n 'validate-on-blur',\n 'style-id',\n 'outbound-app-id',\n 'outbound-app-scopes',\n ];\n\n BaseDescopeWc.observedAttributes.forEach((attr: string) => {\n if (!optionalAttributes.includes(attr) && !this[camelCase(attr)])\n throw Error(`${attr} cannot be empty`);\n });\n }\n\n #syncStateIdFromUrl() {\n const { stepId, executionId } = getRunIdsFromUrl(this.flowId);\n this.#flowState.update({ stepId, executionId });\n }\n\n #createSdk(projectId: string, baseUrl: string) {\n if (!createSdk || typeof createSdk !== 'function') {\n this.logger.error(\n 'SDK was not loaded properly',\n createSdk,\n JSON.stringify(createSdk),\n );\n }\n const config: any = {\n // Use persist tokens options in order to add existing tokens in outgoing requests (if they exists)\n persistTokens: true,\n preview: this.preview,\n storagePrefix: this.storagePrefix,\n storeLastAuthenticatedUser: this.storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout:\n this.keepLastAuthenticatedUserAfterLogout,\n refreshCookieName: this.refreshCookieName,\n ...BaseDescopeWc.sdkConfigOverrides,\n projectId,\n baseUrl,\n };\n if (this.#customStorage) {\n config.customStorage = this.#customStorage;\n }\n\n this.sdk = createSdk(config);\n\n // we are wrapping the next & start function so we can indicate the request status\n ['start', 'next'].forEach((key) => {\n const origFn = this.sdk.flow[key];\n\n this.sdk.flow[key] = async (...args: Parameters<typeof origFn>) => {\n try {\n const resp = await origFn(...args);\n return resp;\n } catch (e) {\n // return a generic error object in case of an error\n return {\n error: {\n errorCode: FETCH_EXCEPTION_ERROR_CODE,\n errorDescription: e.toString(),\n },\n };\n }\n };\n });\n }\n\n async #onFlowChange(\n currentState: FlowState,\n _prevState: FlowState,\n isChanged: IsChanged<FlowState>,\n ) {\n const { projectId, baseUrl } = currentState;\n\n const shouldCreateSdkInstance =\n isChanged('projectId') || isChanged('baseUrl');\n\n if (shouldCreateSdkInstance) {\n if (!projectId) return;\n // Initialize the sdk when got a new project id\n this.#createSdk(projectId, baseUrl);\n }\n\n // update runtime state\n this.#updateExecState(currentState);\n }\n\n async #getIsFlowsVersionMismatch() {\n const config = await this.getConfig();\n\n return (\n 'isMissingConfig' in config &&\n config.isMissingConfig &&\n (await this.#isPrevVerConfig())\n );\n }\n\n // we are not using fetchStaticResource here\n // because we do not want to use the fallbacks mechanism\n async #isPrevVerConfig() {\n const prevVerConfigUrl = getContentUrl({\n projectId: this.projectId,\n filename: CONFIG_FILENAME,\n assetsFolder: PREV_VER_ASSETS_FOLDER,\n baseUrl: this.baseStaticUrl,\n });\n try {\n await fetchContent(prevVerConfigUrl, 'json');\n return true;\n } catch (e) {\n return false;\n }\n }\n\n getConfig = async () => (await this.config) || { isMissingConfig: true };\n\n #handleComponentsContext(e: CustomEvent) {\n this.#componentsContext = { ...this.#componentsContext, ...e.detail };\n }\n\n get isRestartOnError() {\n return this.getAttribute('restart-on-error') === 'true';\n }\n\n async getExecutionContext() {\n const config = await this.getConfig();\n return 'executionContext' in config ? config.executionContext : undefined;\n }\n\n #disableDebugger() {\n this.#debuggerEle?.remove();\n this.#debuggerEle = null;\n }\n\n async #handleDebugMode({ isDebug }) {\n if (isDebug) {\n this.#debuggerEle = document.createElement(\n 'descope-debugger',\n ) as HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n Object.assign(this.#debuggerEle.style, {\n position: 'fixed',\n top: '0',\n right: '0',\n height: '100vh',\n width: '100vw',\n pointerEvents: 'none',\n zIndex: 99999,\n });\n\n // we are importing the debugger dynamically so we won't load it when it's not needed\n await import('../debugger-wc');\n\n document.body.appendChild(this.#debuggerEle);\n } else {\n this.#disableDebugger();\n }\n }\n\n #updateDebuggerMessages(title: string, description: string) {\n if (title && this.debug)\n this.#debuggerEle?.updateData({ title, description });\n }\n\n async getProjectConfig(): Promise<ProjectConfiguration> {\n const config = await this.getConfig();\n return 'projectConfig' in config ? config.projectConfig : undefined;\n }\n\n async getFlowConfig(): Promise<FlowConfig> {\n const projectConfig = await this.getProjectConfig();\n\n const flowConfig =\n projectConfig?.flows?.[this.flowId] || ({} as FlowConfig);\n flowConfig.version ??= 0;\n return flowConfig;\n }\n\n async getTargetLocales() {\n const flowConfig = await this.getFlowConfig();\n return (flowConfig?.targetLocales || []).map((locale: string) =>\n locale.toLowerCase(),\n );\n }\n\n #handleKeyPress() {\n // we want to simulate submit when the user presses Enter\n this.rootElement.onkeydown = (e) => {\n // we do not want to submit the form if the focus is on a link element\n const isLinkEleFocused =\n !!this.shadowRoot.activeElement?.getAttribute('href');\n const isIgnoredElementFocused = ELEMENTS_TO_IGNORE_ENTER_KEY_ON.includes(\n this.shadowRoot.activeElement?.localName ?? '',\n );\n\n if (e.key !== 'Enter' || isLinkEleFocused || isIgnoredElementFocused)\n return;\n\n e.preventDefault();\n const buttons: NodeListOf<HTMLButtonElement> =\n this.rootElement.querySelectorAll('descope-button');\n\n // in case there is a single button on the page, click on it\n if (\n buttons.length === 1 &&\n buttons[0].getAttribute('auto-submit') !== 'false'\n ) {\n buttons[0].click();\n return;\n }\n\n const autoSubmitButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('auto-submit') === 'true',\n );\n if (autoSubmitButtons.length === 1) {\n autoSubmitButtons[0].click();\n return;\n }\n\n const genericButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'button',\n );\n\n // in case there is a single \"generic\" button on the page, click on it\n if (genericButtons.length === 1) {\n if (genericButtons[0].getAttribute('auto-submit') !== 'false') {\n genericButtons[0].click();\n }\n } else if (genericButtons.length === 0) {\n const ssoButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'sso',\n );\n\n // in case there is a single \"sso\" button on the page, click on it\n if (ssoButtons.length === 1) {\n if (ssoButtons[0].getAttribute('auto-submit') !== 'false') {\n ssoButtons[0].click();\n }\n }\n }\n };\n }\n\n async getComponentsVersion() {\n const config = await this.getConfig();\n const version =\n 'projectConfig' in config ? config.projectConfig?.componentsVersion : {};\n\n if (version) return version;\n\n this.logger.error('Did not get components version, using latest version');\n\n return 'latest';\n }\n\n static descopeUI: any;\n\n async init() {\n this.flowStatus = 'loading';\n ['ready', 'error', 'success'].forEach((status: FlowStatus) =>\n this.addEventListener(status, () => {\n this.flowStatus = status;\n }),\n );\n\n await super.init?.();\n this.#debugState.subscribe(this.#handleDebugMode.bind(this));\n this.#debugState.update({ isDebug: this.debug });\n\n this.#validateAttrs();\n\n if (await this.#getIsFlowsVersionMismatch()) {\n this.loggerWrapper.error(\n 'This SDK version does not support your flows version',\n 'Make sure to upgrade your flows to the latest version or use an older SDK version',\n );\n\n return;\n }\n\n const config = await this.getConfig();\n if ('isMissingConfig' in config && config.isMissingConfig) {\n this.loggerWrapper.error(\n 'Cannot get config file',\n 'Make sure that your projectId & flowId are correct',\n );\n\n return;\n }\n\n this.#handleKeyPress();\n\n const {\n executionId,\n stepId,\n token,\n code,\n isPopup,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ssoQueryParams,\n } = handleUrlParams(this.flowId, this.loggerWrapper);\n\n // we want to update the state when user clicks on back in the browser\n window.addEventListener('popstate', this.#eventsCbRefs.popstate);\n\n // adding event to listen to events coming from components (e.g. recaptcha risk token) that want to add data to the context\n // this data will be sent to the server on the next request\n window.addEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n\n this.#flowState.subscribe(this.#onFlowChange.bind(this));\n\n this.#flowState.update({\n projectId: this.projectId,\n flowId: this.flowId,\n baseUrl: this.baseUrl,\n tenant: this.tenantId,\n redirectUrl: this.redirectUrl,\n locale: this.locale,\n stepId,\n executionId,\n token,\n code,\n isPopup,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ...ssoQueryParams,\n });\n\n this.#init = true;\n }\n\n disconnectedCallback() {\n this.#flowState.unsubscribeAll();\n this.#debugState.unsubscribeAll();\n this.#disableDebugger();\n window.removeEventListener('popstate', this.#eventsCbRefs.popstate);\n window.removeEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n }\n\n attributeChangedCallback(\n attrName: string,\n oldValue: string,\n newValue: string,\n ) {\n if (!this.shadowRoot.isConnected || !this.#init) return;\n\n if (\n oldValue !== newValue &&\n BaseDescopeWc.observedAttributes.includes(attrName)\n ) {\n this.#validateAttrs();\n\n const isInitialRun = oldValue === null;\n\n this.#flowState.update(({ stepId, executionId }) => {\n let newStepId = stepId;\n let newExecutionId = executionId;\n\n // If not initial run and we got a new project/flow, we want to restart the step\n if (!isInitialRun) {\n newExecutionId = null;\n newStepId = null;\n clearRunIdsFromUrl();\n }\n\n return {\n [camelCase(attrName)]: newValue,\n stepId: newStepId,\n executionId: newExecutionId,\n };\n });\n\n this.#debugState.update({ isDebug: this.debug });\n }\n }\n}\n\nexport default BaseDescopeWc;\n"],"names":["BaseClass","compose","themeMixin","staticResourcesMixin","formMountMixin","injectStyleMixin","HTMLElement","BaseDescopeWc","observedAttributes","constructor","updateExecState","super","_BaseDescopeWc_init","set","this","_BaseDescopeWc_customStorage","flowStatus","loggerWrapper","error","message","description","logger","Error","__classPrivateFieldGet","call","warn","info","state","debug","_BaseDescopeWc_flowState","State","_BaseDescopeWc_debugState","_BaseDescopeWc_componentsContext","getComponentsContext","nextRequestStatus","isLoading","_BaseDescopeWc_debuggerEle","_BaseDescopeWc_eventsCbRefs","popstate","_BaseDescopeWc_instances","_BaseDescopeWc_syncStateIdFromUrl","bind","componentsContext","_BaseDescopeWc_handleComponentsContext","_BaseDescopeWc_updateExecState","getConfig","config","isMissingConfig","__classPrivateFieldSet","_BaseDescopeWc_initShadowDom","flowId","getAttribute","client","JSON","parse","e","tenantId","undefined","redirectUrl","locale","autoFocus","res","_b","validateOnBlur","storeLastAuthenticatedUser","refreshCookieName","keepLastAuthenticatedUserAfterLogout","storagePrefix","preview","formConfig","transformFlowInputFormData","form","formConfigValues","extractNestedAttribute","outboundAppId","outboundAppScopes","scopes","err","popupOrigin","customStorage","storage","getItem","setItem","removeItem","setCustomStorage","isRestartOnError","getExecutionContext","executionContext","getProjectConfig","projectConfig","getFlowConfig","flowConfig","flows","_c","version","getTargetLocales","targetLocales","map","toLowerCase","getComponentsVersion","componentsVersion","init","forEach","status","addEventListener","_super","subscribe","_BaseDescopeWc_handleDebugMode","update","isDebug","_BaseDescopeWc_validateAttrs","_BaseDescopeWc_getIsFlowsVersionMismatch","_BaseDescopeWc_handleKeyPress","executionId","stepId","token","code","isPopup","exchangeError","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthCodeChallenge","redirectAuthInitiator","ssoQueryParams","handleUrlParams","window","_BaseDescopeWc_onFlowChange","Object","assign","projectId","baseUrl","tenant","disconnectedCallback","unsubscribeAll","_BaseDescopeWc_disableDebugger","removeEventListener","attributeChangedCallback","attrName","oldValue","newValue","shadowRoot","isConnected","_a","includes","isInitialRun","newStepId","newExecutionId","clearRunIdsFromUrl","camelCase","injectStyle","_BaseDescopeWc_loadInitStyle","slotElement","document","createElement","classList","add","rootElement","appendChild","optionalAttributes","attr","getRunIdsFromUrl","_BaseDescopeWc_createSdk","createSdk","stringify","persistTokens","sdkConfigOverrides","sdk","key","origFn","flow","args","__awaiter","errorCode","FETCH_EXCEPTION_ERROR_CODE","errorDescription","toString","currentState","_prevState","isChanged","_BaseDescopeWc_isPrevVerConfig","prevVerConfigUrl","getContentUrl","filename","CONFIG_FILENAME","assetsFolder","PREV_VER_ASSETS_FOLDER","baseStaticUrl","fetchContent","detail","remove","arguments","style","position","top","right","height","width","pointerEvents","zIndex","import","body","_BaseDescopeWc_updateDebuggerMessages","title","updateData","onkeydown","isLinkEleFocused","activeElement","isIgnoredElementFocused","ELEMENTS_TO_IGNORE_ENTER_KEY_ON","localName","_d","preventDefault","buttons","querySelectorAll","length","click","autoSubmitButtons","Array","from","filter","button","genericButtons","ssoButtons","baseHeaders"],"mappings":"4nCA+CA,MAAMA,EAAYC,EAChBC,EACAC,EACAC,EACAC,EAJgBJ,CAKhBK,aAGF,MAAMC,UAAsBP,EAC1B,6BAAWQ,GACT,MAAO,CACL,aACA,UACA,WACA,SACA,SACA,QACA,iBACA,UACA,eACA,aACA,gCACA,sBACA,4CACA,mBACA,WAEH,CA+DD,WAAAC,CAAYC,GACVC,oBAtDFC,EAAAC,IAAAC,MAAQ,GAERC,EAA0CF,IAAAC,UAAA,GAE1CA,KAAUE,WAAe,UAEzBF,KAAAG,cAAgB,CACdC,MAAO,CAACC,EAAiBC,EAAc,MACrCN,KAAKO,OAAOH,MAAMC,EAASC,EAAa,IAAIE,OAC5CC,EAAAT,cAAAU,KAAAV,KAA6BK,EAASC,EAAY,EAEpDK,KAAM,CAACN,EAAiBC,EAAc,MACpCN,KAAKO,OAAOI,KAAKN,EAASC,EAAY,EAExCM,KAAM,CAACP,EAAiBC,EAAc,GAAIO,EAAa,CAAA,KACrDb,KAAKO,OAAOK,KAAKP,EAASC,EAAaO,EAAM,EAE/CC,MAAO,CAACT,EAAiBC,EAAc,MACrCN,KAAKO,OAAOO,MAAMT,EAASC,EAAY,GAI3CS,EAAahB,IAAAC,KAAA,IAAIgB,GAEjBC,EAAclB,IAAAC,KAAA,IAAIgB,GAElBE,EAAAnB,IAAAC,KAAqB,CAAA,GAErBA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AG1K,aAAa,gBACjC0K,EAAe,GAAGN,aAEf,GAA8B,IAA1BM,EAAeP,OAAc,CACtC,MAAMQ,EAAaL,MAAMC,KAAKN,GAASO,QACpCC,GAAgD,QAArCA,EAAOzK,aAAa,eAIR,IAAtB2K,EAAWR,QACqC,UAA9CQ,EAAW,GAAG3K,aAAa,gBAC7B2K,EAAW,GAAGP,OAGnB,EAEL,EA5dOhN,EAAA8J,mBAAyC,CAC9C0D,YAAa,CACX,qBAAsB,gBACtB,wBAAyB"}
1
+ {"version":3,"file":"BaseDescopeWc.js","sources":["../../../src/lib/descope-wc/BaseDescopeWc.ts"],"sourcesContent":["import { compose } from '@descope/sdk-helpers';\n// eslint-disable-next-line import/no-duplicates\nimport { staticResourcesMixin } from '@descope/sdk-mixins/static-resources-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { themeMixin } from '@descope/sdk-mixins/theme-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { injectStyleMixin } from '@descope/sdk-mixins/inject-style-mixin';\nimport { createSdk } from '@descope/web-js-sdk';\nimport {\n CONFIG_FILENAME,\n ELEMENTS_TO_IGNORE_ENTER_KEY_ON,\n FETCH_EXCEPTION_ERROR_CODE,\n PREV_VER_ASSETS_FOLDER,\n} from '../constants';\nimport {\n camelCase,\n clearRunIdsFromUrl,\n fetchContent,\n getContentUrl,\n getRunIdsFromUrl,\n handleUrlParams,\n State,\n} from '../helpers';\nimport {\n extractNestedAttribute,\n transformFlowInputFormData,\n} from '../helpers/flowInputs';\nimport { setCustomStorage } from '../helpers/storage';\nimport { IsChanged } from '../helpers/state';\nimport { formMountMixin } from '../mixins';\nimport {\n AutoFocusOptions,\n CustomStorage,\n DebuggerMessage,\n DebugState,\n DescopeUI,\n FlowConfig,\n FlowState,\n FlowStateUpdateFn,\n FlowStatus,\n ProjectConfiguration,\n SdkConfig,\n} from '../types';\n\n// this is replaced in build time\ndeclare const BUILD_VERSION: string;\n\nconst BaseClass = compose(\n themeMixin,\n staticResourcesMixin,\n formMountMixin,\n injectStyleMixin,\n)(HTMLElement);\n\n// this base class is responsible for WC initialization\nclass BaseDescopeWc extends BaseClass {\n static get observedAttributes() {\n return [\n 'project-id',\n 'flow-id',\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'storage-prefix',\n 'preview',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'refresh-cookie-name',\n 'keep-last-authenticated-user-after-logout',\n 'validate-on-blur',\n 'style-id',\n ];\n }\n\n // this is a way for extending the sdk config from outside\n static sdkConfigOverrides: Partial<SdkConfig> = {\n baseHeaders: {\n 'x-descope-sdk-name': 'web-component',\n 'x-descope-sdk-version': BUILD_VERSION,\n },\n };\n\n #init = false;\n\n #customStorage: CustomStorage | undefined;\n\n flowStatus: FlowStatus = 'initial';\n\n loggerWrapper = {\n error: (message: string, description = '') => {\n this.logger.error(message, description, new Error());\n this.#updateDebuggerMessages(message, description);\n },\n warn: (message: string, description = '') => {\n this.logger.warn(message, description);\n },\n info: (message: string, description = '', state: any = {}) => {\n this.logger.info(message, description, state);\n },\n debug: (message: string, description = '') => {\n this.logger.debug(message, description);\n },\n };\n\n #flowState = new State<FlowState>();\n\n #debugState = new State<DebugState>();\n\n #componentsContext = {};\n\n getComponentsContext = () => this.#componentsContext;\n\n nextRequestStatus = new State<{ isLoading: boolean }>({ isLoading: false });\n\n rootElement: HTMLDivElement;\n\n contentRootElement: HTMLDivElement;\n\n slotElement: HTMLSlotElement;\n\n #debuggerEle: HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n #eventsCbRefs = {\n popstate: this.#syncStateIdFromUrl.bind(this),\n componentsContext: this.#handleComponentsContext.bind(this),\n };\n\n sdk: ReturnType<typeof createSdk>;\n\n #updateExecState: FlowStateUpdateFn;\n\n descopeUI: Promise<DescopeUI>;\n\n constructor(updateExecState: FlowStateUpdateFn) {\n super();\n this.#updateExecState = updateExecState;\n\n this.#initShadowDom();\n }\n\n #loadInitStyle() {\n 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 `);\n }\n\n #initShadowDom() {\n this.#loadInitStyle();\n this.slotElement = document.createElement('slot');\n this.slotElement.classList.add('hidden');\n this.rootElement.appendChild(this.slotElement);\n }\n\n get flowId() {\n return this.getAttribute('flow-id');\n }\n\n get client() {\n try {\n return (JSON.parse(this.getAttribute('client')) || {}) as Record<\n string,\n any\n >;\n } catch (e) {\n return {};\n }\n }\n\n get tenantId() {\n return this.getAttribute('tenant') || undefined;\n }\n\n get redirectUrl() {\n return this.getAttribute('redirect-url') || undefined;\n }\n\n get debug() {\n return this.getAttribute('debug') === 'true';\n }\n\n get locale() {\n return this.getAttribute('locale') || undefined;\n }\n\n get autoFocus(): AutoFocusOptions {\n const res = this.getAttribute('auto-focus') ?? 'true';\n if (res === 'skipFirstScreen') {\n return res;\n }\n return res === 'true';\n }\n\n get validateOnBlur() {\n return this.getAttribute('validate-on-blur') === 'true';\n }\n\n get storeLastAuthenticatedUser() {\n const res = this.getAttribute('store-last-authenticated-user') ?? 'true';\n return res === 'true';\n }\n\n get refreshCookieName() {\n return this.getAttribute('refresh-cookie-name') || '';\n }\n\n get keepLastAuthenticatedUserAfterLogout() {\n const res = this.getAttribute('keep-last-authenticated-user-after-logout');\n return res === 'true';\n }\n\n get storagePrefix() {\n return this.getAttribute('storage-prefix') || '';\n }\n\n get preview() {\n return !!this.getAttribute('preview');\n }\n\n get formConfig() {\n return transformFlowInputFormData(this.form);\n }\n\n get form() {\n return this.getAttribute('form');\n }\n\n get formConfigValues() {\n return extractNestedAttribute(this.formConfig, 'value');\n }\n\n get outboundAppId() {\n return this.getAttribute('outbound-app-id');\n }\n\n get outboundAppScopes() {\n try {\n const scopes = JSON.parse(this.getAttribute('outbound-app-scopes'));\n if (!scopes) return null;\n return scopes;\n } catch (err) {\n return null;\n }\n }\n\n get popupOrigin(): string | null {\n return this.getAttribute('popup-origin');\n }\n\n // grouped getter/setter for customStorage\n get customStorage(): CustomStorage | undefined {\n return this.#customStorage;\n }\n\n set customStorage(storage: CustomStorage | undefined) {\n if (storage && typeof storage.getItem !== 'function') {\n throw new Error('Custom storage must have a getItem method');\n }\n if (storage && typeof storage.setItem !== 'function') {\n throw new Error('Custom storage must have a setItem method');\n }\n if (storage && typeof storage.removeItem !== 'function') {\n throw new Error('Custom storage must have a removeItem method');\n }\n this.#customStorage = storage;\n setCustomStorage(storage);\n }\n\n #validateAttrs() {\n const optionalAttributes = [\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'refresh-cookie-name',\n 'keep-last-authenticated-user-after-logout',\n 'preview',\n 'storage-prefix',\n 'form',\n 'client',\n 'validate-on-blur',\n 'style-id',\n 'outbound-app-id',\n 'outbound-app-scopes',\n ];\n\n BaseDescopeWc.observedAttributes.forEach((attr: string) => {\n if (!optionalAttributes.includes(attr) && !this[camelCase(attr)])\n throw Error(`${attr} cannot be empty`);\n });\n }\n\n #syncStateIdFromUrl() {\n const { stepId, executionId } = getRunIdsFromUrl(this.flowId);\n this.#flowState.update({ stepId, executionId });\n }\n\n #createSdk(projectId: string, baseUrl: string) {\n if (!createSdk || typeof createSdk !== 'function') {\n this.logger.error(\n 'SDK was not loaded properly',\n createSdk,\n JSON.stringify(createSdk),\n );\n }\n const config: any = {\n // Use persist tokens options in order to add existing tokens in outgoing requests (if they exists)\n persistTokens: true,\n preview: this.preview,\n storagePrefix: this.storagePrefix,\n storeLastAuthenticatedUser: this.storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout:\n this.keepLastAuthenticatedUserAfterLogout,\n refreshCookieName: this.refreshCookieName,\n ...BaseDescopeWc.sdkConfigOverrides,\n projectId,\n baseUrl,\n };\n if (this.#customStorage) {\n config.customStorage = this.#customStorage;\n }\n\n this.sdk = createSdk(config);\n\n // we are wrapping the next & start function so we can indicate the request status\n ['start', 'next'].forEach((key) => {\n const origFn = this.sdk.flow[key];\n\n this.sdk.flow[key] = async (...args: Parameters<typeof origFn>) => {\n try {\n const resp = await origFn(...args);\n return resp;\n } catch (e) {\n // return a generic error object in case of an error\n return {\n error: {\n errorCode: FETCH_EXCEPTION_ERROR_CODE,\n errorDescription: e.toString(),\n },\n };\n }\n };\n });\n }\n\n async #onFlowChange(\n currentState: FlowState,\n _prevState: FlowState,\n isChanged: IsChanged<FlowState>,\n ) {\n const { projectId, baseUrl } = currentState;\n\n const shouldCreateSdkInstance =\n isChanged('projectId') || isChanged('baseUrl');\n\n if (shouldCreateSdkInstance) {\n if (!projectId) return;\n // Initialize the sdk when got a new project id\n this.#createSdk(projectId, baseUrl);\n }\n\n // update runtime state\n this.#updateExecState(currentState);\n }\n\n async #getIsFlowsVersionMismatch() {\n const config = await this.getConfig();\n\n return (\n 'isMissingConfig' in config &&\n config.isMissingConfig &&\n (await this.#isPrevVerConfig())\n );\n }\n\n // we are not using fetchStaticResource here\n // because we do not want to use the fallbacks mechanism\n async #isPrevVerConfig() {\n const prevVerConfigUrl = getContentUrl({\n projectId: this.projectId,\n filename: CONFIG_FILENAME,\n assetsFolder: PREV_VER_ASSETS_FOLDER,\n baseUrl: this.baseStaticUrl,\n });\n try {\n await fetchContent(prevVerConfigUrl, 'json');\n return true;\n } catch (e) {\n return false;\n }\n }\n\n getConfig = async () => (await this.config) || { isMissingConfig: true };\n\n #handleComponentsContext(e: CustomEvent) {\n this.#componentsContext = { ...this.#componentsContext, ...e.detail };\n }\n\n get isRestartOnError() {\n return this.getAttribute('restart-on-error') === 'true';\n }\n\n async getExecutionContext() {\n const config = await this.getConfig();\n return 'executionContext' in config ? config.executionContext : undefined;\n }\n\n #disableDebugger() {\n this.#debuggerEle?.remove();\n this.#debuggerEle = null;\n }\n\n async #handleDebugMode({ isDebug }) {\n if (isDebug) {\n this.#debuggerEle = document.createElement(\n 'descope-debugger',\n ) as HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n Object.assign(this.#debuggerEle.style, {\n position: 'fixed',\n top: '0',\n right: '0',\n height: '100vh',\n width: '100vw',\n pointerEvents: 'none',\n zIndex: 99999,\n });\n\n // we are importing the debugger dynamically so we won't load it when it's not needed\n await import('../debugger-wc');\n\n document.body.appendChild(this.#debuggerEle);\n } else {\n this.#disableDebugger();\n }\n }\n\n #updateDebuggerMessages(title: string, description: string) {\n if (title && this.debug)\n this.#debuggerEle?.updateData({ title, description });\n }\n\n async getProjectConfig(): Promise<ProjectConfiguration> {\n const config = await this.getConfig();\n return 'projectConfig' in config ? config.projectConfig : undefined;\n }\n\n async getFlowConfig(): Promise<FlowConfig> {\n const projectConfig = await this.getProjectConfig();\n\n const flowConfig =\n projectConfig?.flows?.[this.flowId] || ({} as FlowConfig);\n flowConfig.version ??= 0;\n return flowConfig;\n }\n\n async getTargetLocales() {\n const flowConfig = await this.getFlowConfig();\n return (flowConfig?.targetLocales || []).map((locale: string) =>\n locale.toLowerCase(),\n );\n }\n\n handleKeyPress() {\n this.logger.debug('Enable key press handler');\n // we want to simulate submit when the user presses Enter\n this.rootElement.onkeydown = (e) => {\n // we do not want to submit the form if the focus is on a link element\n const isLinkEleFocused =\n !!this.shadowRoot.activeElement?.getAttribute('href');\n const isIgnoredElementFocused = ELEMENTS_TO_IGNORE_ENTER_KEY_ON.includes(\n this.shadowRoot.activeElement?.localName ?? '',\n );\n\n if (e.key !== 'Enter' || isLinkEleFocused || isIgnoredElementFocused)\n return;\n\n e.preventDefault();\n const buttons: NodeListOf<HTMLButtonElement> =\n this.rootElement.querySelectorAll('descope-button');\n\n // in case there is a single button on the page, click on it\n if (\n buttons.length === 1 &&\n buttons[0].getAttribute('auto-submit') !== 'false'\n ) {\n buttons[0].click();\n return;\n }\n\n const autoSubmitButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('auto-submit') === 'true',\n );\n if (autoSubmitButtons.length === 1) {\n autoSubmitButtons[0].click();\n return;\n }\n\n const genericButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'button',\n );\n\n // in case there is a single \"generic\" button on the page, click on it\n if (genericButtons.length === 1) {\n if (genericButtons[0].getAttribute('auto-submit') !== 'false') {\n genericButtons[0].click();\n }\n } else if (genericButtons.length === 0) {\n const ssoButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'sso',\n );\n\n // in case there is a single \"sso\" button on the page, click on it\n if (ssoButtons.length === 1) {\n if (ssoButtons[0].getAttribute('auto-submit') !== 'false') {\n ssoButtons[0].click();\n }\n }\n }\n };\n }\n\n disableKeyPressHandler() {\n this.logger.debug('Disable key press handler');\n this.rootElement.onkeydown = null;\n }\n\n async getComponentsVersion() {\n const config = await this.getConfig();\n const version =\n 'projectConfig' in config ? config.projectConfig?.componentsVersion : {};\n\n if (version) return version;\n\n this.logger.error('Did not get components version, using latest version');\n\n return 'latest';\n }\n\n static descopeUI: any;\n\n async init() {\n this.flowStatus = 'loading';\n ['ready', 'error', 'success'].forEach((status: FlowStatus) =>\n this.addEventListener(status, () => {\n this.flowStatus = status;\n }),\n );\n\n await super.init?.();\n this.#debugState.subscribe(this.#handleDebugMode.bind(this));\n this.#debugState.update({ isDebug: this.debug });\n\n this.#validateAttrs();\n\n if (await this.#getIsFlowsVersionMismatch()) {\n this.loggerWrapper.error(\n 'This SDK version does not support your flows version',\n 'Make sure to upgrade your flows to the latest version or use an older SDK version',\n );\n\n return;\n }\n\n const config = await this.getConfig();\n if ('isMissingConfig' in config && config.isMissingConfig) {\n this.loggerWrapper.error(\n 'Cannot get config file',\n 'Make sure that your projectId & flowId are correct',\n );\n\n return;\n }\n\n const {\n executionId,\n stepId,\n token,\n code,\n isPopup,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ssoQueryParams,\n } = handleUrlParams(this.flowId, this.loggerWrapper);\n\n // we want to update the state when user clicks on back in the browser\n window.addEventListener('popstate', this.#eventsCbRefs.popstate);\n\n // adding event to listen to events coming from components (e.g. recaptcha risk token) that want to add data to the context\n // this data will be sent to the server on the next request\n window.addEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n\n this.#flowState.subscribe(this.#onFlowChange.bind(this));\n\n this.#flowState.update({\n projectId: this.projectId,\n flowId: this.flowId,\n baseUrl: this.baseUrl,\n tenant: this.tenantId,\n redirectUrl: this.redirectUrl,\n locale: this.locale,\n stepId,\n executionId,\n token,\n code,\n isPopup,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ...ssoQueryParams,\n });\n\n this.#init = true;\n }\n\n disconnectedCallback() {\n this.#flowState.unsubscribeAll();\n this.#debugState.unsubscribeAll();\n this.#disableDebugger();\n window.removeEventListener('popstate', this.#eventsCbRefs.popstate);\n window.removeEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n }\n\n attributeChangedCallback(\n attrName: string,\n oldValue: string,\n newValue: string,\n ) {\n if (!this.shadowRoot.isConnected || !this.#init) return;\n\n if (\n oldValue !== newValue &&\n BaseDescopeWc.observedAttributes.includes(attrName)\n ) {\n this.#validateAttrs();\n\n const isInitialRun = oldValue === null;\n\n this.#flowState.update(({ stepId, executionId }) => {\n let newStepId = stepId;\n let newExecutionId = executionId;\n\n // If not initial run and we got a new project/flow, we want to restart the step\n if (!isInitialRun) {\n newExecutionId = null;\n newStepId = null;\n clearRunIdsFromUrl();\n }\n\n return {\n [camelCase(attrName)]: newValue,\n stepId: newStepId,\n executionId: newExecutionId,\n };\n });\n\n this.#debugState.update({ isDebug: this.debug });\n }\n }\n}\n\nexport default BaseDescopeWc;\n"],"names":["BaseClass","compose","themeMixin","staticResourcesMixin","formMountMixin","injectStyleMixin","HTMLElement","BaseDescopeWc","observedAttributes","constructor","updateExecState","super","_BaseDescopeWc_init","set","this","_BaseDescopeWc_customStorage","flowStatus","loggerWrapper","error","message","description","logger","Error","__classPrivateFieldGet","call","warn","info","state","debug","_BaseDescopeWc_flowState","State","_BaseDescopeWc_debugState","_BaseDescopeWc_componentsContext","getComponentsContext","nextRequestStatus","isLoading","_BaseDescopeWc_debuggerEle","_BaseDescopeWc_eventsCbRefs","popstate","_BaseDescopeWc_instances","_BaseDescopeWc_syncStateIdFromUrl","bind","componentsContext","_BaseDescopeWc_handleComponentsContext","_BaseDescopeWc_updateExecState","getConfig","config","isMissingConfig","__classPrivateFieldSet","_BaseDescopeWc_initShadowDom","flowId","getAttribute","client","JSON","parse","e","tenantId","undefined","redirectUrl","locale","autoFocus","res","_b","validateOnBlur","storeLastAuthenticatedUser","refreshCookieName","keepLastAuthenticatedUserAfterLogout","storagePrefix","preview","formConfig","transformFlowInputFormData","form","formConfigValues","extractNestedAttribute","outboundAppId","outboundAppScopes","scopes","err","popupOrigin","customStorage","storage","getItem","setItem","removeItem","setCustomStorage","isRestartOnError","getExecutionContext","executionContext","getProjectConfig","projectConfig","getFlowConfig","flowConfig","flows","_c","version","getTargetLocales","targetLocales","map","toLowerCase","handleKeyPress","rootElement","onkeydown","isLinkEleFocused","shadowRoot","activeElement","isIgnoredElementFocused","ELEMENTS_TO_IGNORE_ENTER_KEY_ON","includes","localName","_d","key","preventDefault","buttons","querySelectorAll","length","click","autoSubmitButtons","Array","from","filter","button","genericButtons","ssoButtons","disableKeyPressHandler","getComponentsVersion","componentsVersion","init","forEach","status","addEventListener","_super","subscribe","_BaseDescopeWc_handleDebugMode","update","isDebug","_BaseDescopeWc_validateAttrs","_BaseDescopeWc_getIsFlowsVersionMismatch","executionId","stepId","token","code","isPopup","exchangeError","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthCodeChallenge","redirectAuthInitiator","ssoQueryParams","handleUrlParams","window","_BaseDescopeWc_onFlowChange","Object","assign","projectId","baseUrl","tenant","disconnectedCallback","unsubscribeAll","_BaseDescopeWc_disableDebugger","removeEventListener","attributeChangedCallback","attrName","oldValue","newValue","isConnected","_a","isInitialRun","newStepId","newExecutionId","clearRunIdsFromUrl","camelCase","injectStyle","_BaseDescopeWc_loadInitStyle","slotElement","document","createElement","classList","add","appendChild","optionalAttributes","attr","getRunIdsFromUrl","_BaseDescopeWc_createSdk","createSdk","stringify","persistTokens","sdkConfigOverrides","sdk","origFn","flow","args","__awaiter","errorCode","FETCH_EXCEPTION_ERROR_CODE","errorDescription","toString","currentState","_prevState","isChanged","_BaseDescopeWc_isPrevVerConfig","prevVerConfigUrl","getContentUrl","filename","CONFIG_FILENAME","assetsFolder","PREV_VER_ASSETS_FOLDER","baseStaticUrl","fetchContent","detail","remove","arguments","style","position","top","right","height","width","pointerEvents","zIndex","import","body","_BaseDescopeWc_updateDebuggerMessages","title","updateData","baseHeaders"],"mappings":"0nCA+CA,MAAMA,EAAYC,EAChBC,EACAC,EACAC,EACAC,EAJgBJ,CAKhBK,aAGF,MAAMC,UAAsBP,EAC1B,6BAAWQ,GACT,MAAO,CACL,aACA,UACA,WACA,SACA,SACA,QACA,iBACA,UACA,eACA,aACA,gCACA,sBACA,4CACA,mBACA,WAEH,CA+DD,WAAAC,CAAYC,GACVC,oBAtDFC,EAAAC,IAAAC,MAAQ,GAERC,EAA0CF,IAAAC,UAAA,GAE1CA,KAAUE,WAAe,UAEzBF,KAAAG,cAAgB,CACdC,MAAO,CAACC,EAAiBC,EAAc,MACrCN,KAAKO,OAAOH,MAAMC,EAASC,EAAa,IAAIE,OAC5CC,EAAAT,cAAAU,KAAAV,KAA6BK,EAASC,EAAY,EAEpDK,KAAM,CAACN,EAAiBC,EAAc,MACpCN,KAAKO,OAAOI,KAAKN,EAASC,EAAY,EAExCM,KAAM,CAACP,EAAiBC,EAA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AAA,SAAAtE,GAEsB,OAAAiI,EAAAjL,KAAAoM,eAAA,GAAA,WAAA5E,QAAEA,IACnBA,GACFtF,EAAAlC,OAAoBgK,SAASC,cAC3B,oBAGD,KAEDxB,OAAOC,OAAOjI,EAAAT,KAAiBsB,EAAA,KAAC+K,MAAO,CACrCC,SAAU,QACVC,IAAK,IACLC,MAAO,IACPC,OAAQ,QACRC,MAAO,QACPC,cAAe,OACfC,OAAQ,cAIJC,OAAO,qBAEb7C,SAAS8C,KAAK1C,YAAY3J,EAAAT,KAAiBsB,EAAA,OAE3Cb,EAAAT,KAAIyB,EAAA,IAAAuH,GAAJtI,KAAAV,QAIoB,EAAA+M,EAAA,SAAAC,EAAe1M,SACjC0M,GAAShN,KAAKc,QACC,QAAjBkC,EAAAvC,EAAAT,KAAiBsB,EAAA,YAAA,IAAA0B,GAAAA,EAAEiK,WAAW,CAAED,QAAO1M,gBAC3C,EA7YOb,EAAAmL,mBAAyC,CAC9CsC,YAAa,CACX,qBAAsB,gBACtB,wBAAyB"}
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{ensureFingerprintIds as o,clearFingerprintData as n}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as r,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as l,URL_TOKEN_PARAM_NAME as d,URL_RUN_IDS_PARAM_NAME as c,SDK_SCRIPTS_LOAD_TIMEOUT as p,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as h,ELEMENT_TYPE_ATTRIBUTE as u,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as g}from"../constants/index.js";import{timeoutPromise as v,withMemCache as m,leadingDebounce as f,getUserLocale as b,showFirstScreenOnExecutionInit as w,injectSamlIdpForm as S,openCenteredPopup as y,getAnimationDirection as C,handleAutoFocus as I,transformStepStateForCustomScreen as k,getElementDescopeAttributes as R,getScriptResultPath as O,submitForm as W,transformScreenInputs as x,handleReportValidityOnBlur as E,getFirstNonEmptyValue as A,clearPreviousExternalInputs as j}from"../helpers/helpers.js";import T from"../helpers/state.js";import{disableWebauthnButtons as L,updateTemplateFromScreenState as U,setPhoneAutoDetectDefaultCode as P,setTOTPVariable as $,setNOTPVariable as N,setCssVars as M,updateScreenFromScreenState as q,replaceElementMessage as F}from"../helpers/templates.js";import{isConditionalLoginSupported as V}from"../helpers/webauthn.js";import{getABTestingKey as D}from"../helpers/abTestingKey.js";import{calculateConditions as B,calculateCondition as K}from"../helpers/conditions.js";import{setLastAuth as H,getLastAuth as _}from"../helpers/lastAuth.js";import G from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as J,FETCH_ERROR_RESPONSE_ERROR_CODE as z,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as Q,FLOW_TIMED_OUT_ERROR_CODE as X,POLLING_STATUS_NOT_FOUND_ERROR_CODE as Y}from"../constants/general.js";var Z,ee,te,ie,se,oe,ne,re,ae,le,de,ce,pe,he,ue,ge,ve,me,fe,be,we,Se,ye,Ce,Ie,ke,Re,Oe,We,xe,Ee,Ae,je,Te,Le,Ue,Pe;class $e extends G{static set sdkConfigOverrides(e){G.sdkConfigOverrides=e}static get sdkConfigOverrides(){return G.sdkConfigOverrides}constructor(){const s=new T({deferredRedirect:!1});super(s.update.bind(s)),Z.add(this),this.stepState=new T({}),ee.set(this,void 0),te.set(this,null),ie.set(this,null),se.set(this,{visibilitychange:e(this,Z,"m",oe).bind(this)}),this.bridgeVersion=2,this.nativeCallbacks={},he.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},ge.set(this,(t=>{const i=()=>{this.contentRootElement.classList.toggle("hidden",t),this.slotElement.classList.toggle("hidden",!t),t&&(this.contentRootElement.innerHTML="")};t&&this.contentRootElement.hasChildNodes()?e(this,Z,"m",ve).call(this,i):i()})),me.set(this,((s,o,n,l,d=!1)=>{const c=[X,Y];if(this.flowState.current.action===r.poll){this.logger.debug("polling - Scheduling polling request");const r=Date.now(),p=d?500:2e3;t(this,ee,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const h=this.sdk.flow.next(s,o,a.polling,n,l,{}),u=document.hidden&&!d&&Date.now()-r>p+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield v(e,h)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,me,"f").call(this,s,o,n,l,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===J)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,me,"f").call(this,s,o,n,l);this.logger.debug("polling - Got a response"),(null==g?void 0:g.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(g.error,null,4)),(null===(i=null==g?void 0:g.error)||void 0===i?void 0:i.errorCode)&&c.includes(g.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):e(this,me,"f").call(this,s,o,n,l),e(this,be,"f").call(this,g)}))),p),"f")}})),fe.set(this,(()=>{clearTimeout(e(this,ee,"f")),t(this,ee,null,"f")})),be.set(this,(i=>{var s,o,n,a,l,d,c,p,h,u,g,v,m;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,r=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,Z,"m",Ue).call(this,"error",(null==i?void 0:i.error)||{errorCode:z,errorDescription:r,errorMessage:t}),this.loggerWrapper.error((null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorDescription)||t,(null===(l=null==i?void 0:i.error)||void 0===l?void 0:l.errorMessage)||r);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==Q&&c!==X||!this.isRestartOnError||e(this,Z,"m",pe).call(this))}null===(p=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===p||p.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(h=i.data)||void 0===h?void 0:h.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(v=i.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:C}=i.data;if(y!==r.poll&&e(this,fe,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&H(S);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),void e(this,Z,"m",Ue).call(this,"success",t)}this.storeLastAuthenticatedUser&&H(S,!0),C&&window.open(C,"_blank");const{executionId:I,stepId:k,stepName:R,screen:O,redirect:W,webauthn:x,error:E,samlIdpResponse:A,nativeResponse:j}=i.data,T=Date.now();y!==r.poll?(this.loggerWrapper.info(`Step "${R||`#${k}`}" is ${b}`,"",{screen:O,status:b,stepId:k,stepName:R,action:y,error:E}),(null===(m=O.state)||void 0===m?void 0:m.clientScripts)&&t(this,ie,this.loadSdkScripts(O.state.clientScripts),"f"),this.flowState.update({stepId:k,stepName:R,executionId:I,action:y,redirectTo:null==W?void 0:W.url,redirectIsPopup:null==W?void 0:W.isPopup,screenId:null==O?void 0:O.id,screenState:null==O?void 0:O.state,webauthnTransactionId:null==x?void 0:x.transactionId,webauthnOptions:null==x?void 0:x.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,nativeResponseType:null==j?void 0:j.type,nativePayload:null==j?void 0:j.payload,reqTimestamp:T})):this.flowState.update({action:y,reqTimestamp:T})})),we.set(this,m((()=>i(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),Re.set(this,null),Ae.set(this,f(((t,s)=>i(this,void 0,void 0,(function*(){var i;if("true"===t.getAttribute("formnovalidate")||e(this,Z,"m",Ie).call(this)){const o=null==t?void 0:t.getAttribute("id");e(this,Z,"m",Oe).call(this,t);const n=yield e(this,Z,"m",ke).call(this),r=R(t);this.nextRequestStatus.update({isLoading:!0});const a=Object.assign(Object.assign(Object.assign({},r),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(o,a),this.nextRequestStatus.update({isLoading:!1}),e(this,Z,"m",We).call(this,n)}}))))),this.flowState=s}nativeResume(t,i){var s,o,n,r,a;const p=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let{exchangeCode:e}=p;if(!e){e=null===(s=new URL(p.url).searchParams)||void 0===s?void 0:s.get(l)}null===(n=(o=this.nativeCallbacks).complete)||void 0===n||n.call(o,{exchangeCode:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(p.url),i=t.searchParams.get(d),s=t.searchParams.get(c).split("_").pop();e(this,fe,"f").call(this),this.flowState.update({token:i,stepId:s,action:void 0})}else if("beforeScreen"===t){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=p;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=p,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(r=this.nativeCallbacks).complete)||void 0===a||a.call(r,p)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[O(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=Promise.all(null==e?void 0:e.map((e=>i(this,void 0,void 0,(function*(){var i,s;const o=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(o){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=o;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}yield this.injectNpmLib("@descope/flow-scripts","1.0.13",`dist/${e.id}.js`);const n=null===(s=globalThis.descope)||void 0===s?void 0:s[e.id];return new Promise(((i,s)=>{try{const s=n(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i),this.loggerWrapper);if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t),this.nextRequestStatus.subscribe((()=>{var t;this.loggerWrapper.debug("Unloading script",e.id),null===(t=s.stop)||void 0===t||t.call(s)}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),p)}));return Promise.race([s,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){if(!window.descopeBridge)return this._init();this.lazyInit=this._init}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,Z,"m",de).call(this),window.addEventListener("visibilitychange",e(this,se,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var i;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,fe,"f").call(this),null===(i=e(this,te,"f"))||void 0===i||i.abort(),t(this,te,null,"f"),window.removeEventListener("visibilitychange",e(this,se,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=b(e),o=yield this.getTargetLocales();return o.includes(s.locale)?i=`${t}-${s.locale}.html`:o.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(l,d,c){return i(this,void 0,void 0,(function*(){var p,h;const{projectId:u,flowId:g,tenant:v,stepId:m,executionId:f,action:I,screenId:k,screenState:R,redirectTo:O,redirectIsPopup:E,redirectUrl:A,token:j,code:T,isPopup:L,exchangeError:U,webauthnTransactionId:P,webauthnOptions:$,redirectAuthCodeChallenge:N,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:F,locale:V,samlIdpResponseUrl:H,samlIdpResponseSamlResponse:G,samlIdpResponseRelayState:J,nativeResponseType:z,nativePayload:Q,reqTimestamp:X}=l,Y=s(l,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","nativeResponseType","nativePayload","reqTimestamp"]);let ee,se,oe;const ne=D(),{outboundAppId:re}=this,{outboundAppScopes:le}=this,de=this.sdk.getLastUserLoginId(),ce=yield this.getFlowConfig(),pe=yield this.getProjectConfig(),he=Object.entries(pe.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),ge=M&&N?{callbackUrl:M,codeChallenge:N,backupCallbackUri:q}:void 0,ve=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;let fe={};if(!f){const i=[...ce.clientScripts||[],...ce.sdkScripts||[]];if(ce.conditions){let e=[];({startScreenId:ee,conditionInteractionId:oe,startScreenName:se,clientScripts:e,componentsConfig:fe}=B({loginId:de,code:T,token:j,abTestingKey:ne,lastAuth:_(de)},ce.conditions)),i.push(...e||[])}else ce.condition?({startScreenId:ee,conditionInteractionId:oe}=K(ce.condition,{loginId:de,code:T,token:j,abTestingKey:ne,lastAuth:_(de)})):(se=ce.startScreenName,ee=ce.startScreenId);if(t(this,ie,this.loadSdkScripts(i),"f"),ce.fingerprintEnabled&&ce.fingerprintKey?yield o(ce.fingerprintKey,this.baseUrl):n(),!w(ee,Y)){const t=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:ge},Y),{client:this.client}),A&&{redirectUrl:A}),{lastAuth:_(de),abTestingKey:ne,locale:b(V).locale,nativeOptions:ve,outboundAppId:re,outboundAppScopes:le}),oe,"",pe.componentsVersion,he,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),T?{exchangeCode:T,idpInitiated:!0}:{}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j?{token:j}:{}),Y.oidcLoginHint?{externalId:Y.oidcLoginHint}:{}));return e(this,be,"f").call(this,t),void("completed"!==(null===(p=null==t?void 0:t.data)||void 0===p?void 0:p.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:L,code:T,exchangeError:U,isCodeChanged:c("code"),isExchangeErrorChanged:c("exchangeError")})),L&&(c("code")&&T||c("exchangeError")&&U))return void e(this,Z,"m",Pe).call(this,f,T,U);if(f&&(c("token")&&j||c("code")&&T||c("exchangeError")&&U)){const t=yield this.sdk.flow.next(f,m,a.submit,ce.version,pe.componentsVersion,{token:j,exchangeCode:T,exchangeError:U});return e(this,be,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(I===r.loadForm&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>c(e)))){if(!H||!G)return void this.loggerWrapper.error("Did not get saml idp params data to load");S(H,G,J||"",W)}if(I===r.redirect&&(c("redirectTo")||c("deferredRedirect"))){if(!O)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===O)return;if("android"===F&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${E}`),E){this.loggerWrapper.debug("Opening redirect in popup");const t=y(O,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));const s=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const t=i?this.popupOrigin:window.location.origin;if(e.origin!==t)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${t}"`);const{action:s,data:o}=e.data||{};"code"===s&&this.flowState.update({code:o.code,exchangeError:o.exchangeError})};let o;this.loggerWrapper.debug("Starting popup closed detection");const n=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(n),e(this,Z,"m",Ue).call(this,"popupclosed",{}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==o||o())}),1e3);if(i)window.addEventListener("message",s),o=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",s)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(f);e.onmessage=s,o=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(O),this.flowState.update({redirectTo:"no-op"}),e(this,Z,"m",Ue).call(this,"popupclosed",{});return}if(I===r.webauthnCreate||I===r.webauthnGet){if(!P||!$)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s;null===(h=e(this,te,"f"))||void 0===h||h.abort(),t(this,te,null,"f");try{i=I===r.webauthnCreate?yield this.sdk.webauthn.helpers.create($):yield this.sdk.webauthn.helpers.get($)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),s=e.name}const o=yield this.sdk.flow.next(f,m,a.submit,ce.version,pe.componentsVersion,{transactionId:P,response:i,failure:s});e(this,be,"f").call(this,o)}if(I===r.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,m,a.submit,ce.version,pe.componentsVersion,t);e(this,be,"f").call(this,i)})),void e(this,Z,"m",ae).call(this,z,Q);if(c("action")&&e(this,me,"f").call(this,f,m,ce.version,pe.componentsVersion),!k&&!ee)return void this.loggerWrapper.warn("No screen was found to show");const we=ee||k,Se=yield this.getHtmlFilenameWithLocale(V,we),{oidcLoginHint:ye,oidcPrompt:Ce,oidcErrorRedirectUri:Ie,oidcResource:ke,samlIdpUsername:Re}=Y,Oe={direction:C(m,d.stepId),screenState:Object.assign(Object.assign({},R),{form:Object.assign(Object.assign({},this.formConfigValues),null==R?void 0:R.form),lastAuth:{loginId:de,name:this.sdk.getLastUserDisplayName()||de},componentsConfig:Object.assign(Object.assign(Object.assign({},ce.componentsConfig),fe),null==R?void 0:R.componentsConfig)}),htmlFilename:`${we}.html`,htmlLocaleFilename:Se,screenId:we,stepName:l.stepName||se,samlIdpUsername:Re,oidcLoginHint:ye,oidcPrompt:Ce,oidcErrorRedirectUri:Ie,oidcResource:ke,action:I},We=_(de);w(ee,Y)?Oe.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ce?void 0:ce.clientScripts)||[];yield e(this,Z,"m",je).call(this,i);const o=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:ge},Y),{lastAuth:We,preview:this.preview,abTestingKey:ne,client:this.client}),A&&{redirectUrl:A}),{locale:b(V).locale,nativeOptions:ve,outboundAppId:re,outboundAppScopes:le}),oe,t,pe.componentsVersion,he,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),x(s)),T&&{exchangeCode:T,idpInitiated:!0}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j&&{token:j}));return e(this,be,"f").call(this,o),o})):(c("projectId")||c("baseUrl")||c("executionId")||c("stepId"))&&(Oe.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==R?void 0:R.clientScripts)||[];yield e(this,Z,"m",je).call(this,i);const o=yield this.sdk.flow.next(f,m,t,ce.version,pe.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),x(s)));return e(this,be,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",Oe.screenId),yield e(this,Z,"m",ue).call(this,Oe),this.stepState.update(Oe)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n;const{htmlFilename:r,htmlLocaleFilename:l,direction:d,next:c,screenState:p}=t;this.loggerWrapper.debug("Rendering a flow screen");const h=document.createElement("template");h.innerHTML=yield this.getPageContent(r,l);const g=h.content.cloneNode(!0),v=this.loadDescopeUiComponents(h);this.sdk.webauthn.helpers.isSupported()?yield e(this,Z,"m",ye).call(this,g,c):L(g),!t.samlIdpUsername||(null===(o=p.form)||void 0===o?void 0:o.loginId)||(null===(n=p.form)||void 0===n?void 0:n.email)||(p.form||(p.form={}),p.form.loginId=t.samlIdpUsername,p.form.email=t.samlIdpUsername),U(g,p,p.componentsConfig,this.formConfig,this.loggerWrapper);const{geo:m}=yield this.getExecutionContext();P(g,m);const f=()=>i(this,void 0,void 0,(function*(){var i,o;yield v;const n=this.contentRootElement;$(n,null===(i=null==p?void 0:p.totp)||void 0===i?void 0:i.image),N(n,null===(o=null==p?void 0:p.notp)||void 0===o?void 0:o.image),M(n,g,p.cssVars,this.loggerWrapper),n.replaceChildren(g);const r=!s.htmlFilename;setTimeout((()=>{e(this,Z,"m",xe).call(this),this.validateOnBlur&&E(n),q(n,p),e(this,Z,"m",Ce).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),I(n,this.autoFocus,r)})),e(this,Z,"m",Le).call(this,c);n.querySelector(`[${u}="polling"]`)&&c(a.polling,{})}));d?e(this,Z,"m",ve).call(this,f):f()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${h}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}ee=new WeakMap,te=new WeakMap,ie=new WeakMap,se=new WeakMap,he=new WeakMap,ge=new WeakMap,me=new WeakMap,fe=new WeakMap,be=new WeakMap,we=new WeakMap,Re=new WeakMap,Ae=new WeakMap,Z=new WeakSet,oe=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},ne=function(t,s,o){return i(this,void 0,void 0,(function*(){var i;return(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&new Promise((i=>{this.nativeCallbacks.screenNext=o,this.nativeCallbacks.screenResolve=i,e(this,Z,"m",ae).call(this,"beforeScreen",{screen:t,context:s})}))}))},re=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,Z,"m",ae).call(this,"afterScreen",{screen:t})},ae=function(t,i){e(this,Z,"m",Ue).call(this,"bridge",{type:t,payload:i})},le=function({errorText:e,errorType:t}){const i=()=>{var i;let s=e;try{s=(null===(i=this.errorTransformer)||void 0===i?void 0:i.call(this,{text:e,type:t}))||e}catch(e){this.loggerWrapper.error("Error transforming error message",e.message)}F(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},de=function(){var t,i,o;null===(t=this.stepState)||void 0===t||t.subscribe(this.onStepChange.bind(this),(e=>{var t=e.screenState,i=s(void 0===t?{}:t,["errorText","errorType"]),o=s(e,["screenState"]);return Object.assign(Object.assign({},o),{screenState:i})})),null===(i=this.stepState)||void 0===i||i.subscribe(e(this,Z,"m",le).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(o=this.stepState)||void 0===o||o.subscribe(e(this,Z,"m",ce).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0})},ce=function({errorText:e,errorType:t}){(t||e)&&(this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((e=>{e.shadowRoot.querySelectorAll("descope-text-field[data-id]").forEach((e=>{e.value=""}))})),I(this.contentRootElement,this.autoFocus,!1))},pe=function(){return i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update({stepId:null,executionId:null})):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},ue=function(o){return i(this,void 0,void 0,(function*(){var i;const n=Object.assign(Object.assign({},this.stepState.current),o),{next:r,stepName:a}=n,l=s(n,["next","stepName"]),d=k(l);let c=yield e(this,Z,"m",ne).call(this,a,d,r);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,a,d,r,this)));const p=!this.stepState.current.htmlFilename;if(e(this,ge,"f").call(this,c),e(this,he,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,he,c,"f"),c?this.stepState.unsubscribeAll():e(this,Z,"m",de).call(this)}c&&(this.loggerWrapper.debug("Showing a custom screen"),e(this,Z,"m",Ce).call(this,{isFirstScreen:p,isCustomScreen:c,stepName:o.stepName})),this.stepState.forceUpdate=c}))},ve=function(e){this.contentRootElement.addEventListener("transitionend",(()=>{this.loggerWrapper.debug("page switch transition end"),this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0}),this.loggerWrapper.debug("page switch transition start"),this.contentRootElement.classList.add("fade-out")},Se=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const i=`user-${t}`;e.setAttribute("name",i),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:i)}))}},ye=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,te,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield V())){const{options:s,transactionId:n}=(yield e(this,we,"f").call(this))||{};s&&n&&(e(this,Z,"m",Se).call(this,r),t(this,te,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,te,"f")).then((e=>i(this,void 0,void 0,(function*(){o(r.id,{transactionId:n,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},Ce=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,Z,"m",Ue).call(this,"ready",{}),i||e(this,Z,"m",re).call(this,s),e(this,Z,"m",Ue).call(this,"page-updated",{screenName:s}),e(this,Z,"m",Ue).call(this,"screen-updated",{screenName:s})},Ie=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"!==t.localName&&(null===(i=t.reportValidity)||void 0===i||i.call(t),e&&(e=null===(s=t.checkValidity)||void 0===s?void 0:s.call(t)))})),e},ke=function(){return i(this,void 0,void 0,(function*(){const e=this.getInputs();return(yield Promise.all(e.map((e=>i(this,void 0,void 0,(function*(){return{name:e.getAttribute("name"),value:e.value}})))))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},Oe=function(s){const o=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),n=()=>i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",n),s.removeAttribute("loading"),o.forEach((e=>{e.removeAttribute("disabled")}));const e=yield this.getFlowConfig(),t=[...e.clientScripts||[],...e.sdkScripts||[]];this.loadSdkScripts(t)})),r=()=>{var i;window.removeEventListener("pageshow",e(this,Re,"f")),t(this,Re,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),n())}),"f"),window.addEventListener("pageshow",e(this,Re,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&n(),this.removeEventListener("popupclosed",n),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},a=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?(this.addEventListener("popupclosed",n,{once:!0}),s.setAttribute("loading","true"),o.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(a),r())}))},We=function(e={}){var t,i;const s=A(e,["externalId","email","phone"]),o=A(e,["newPassword","password"]);if(s&&o)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:o});null===(i=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===i||i.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},xe=function(){j();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,Z,"m",Ee).call(this,t)))},Ee=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const i=t.getAttribute("slot"),s=`input-${e.id}-${i}`,o=document.createElement("slot");o.setAttribute("name",s),o.setAttribute("slot",i),e.appendChild(o),t.setAttribute("slot",s),this.appendChild(t)}))},je=function(t){return i(this,void 0,void 0,(function*(){if(e(this,ie,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ie,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-t).toString())}const i=this.loadSdkScriptsModules(),s=t.map((e=>e.id));for(const e of i)if(s.includes(e.id))try{if("function"==typeof e.present){(yield e.present())||this.loggerWrapper.debug(`Sdk script ${e.id} was cancelled`)}}catch(t){this.loggerWrapper.error(`Failed to present ${e.id} script module`,t.message)}let o=[];for(const e of i)"function"==typeof e.refresh&&o.push(e.refresh());if(o.length>0)try{yield v(p,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},Te=function(t){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((i=>{i.addEventListener("input",(()=>{var s;(null===(s=i.checkValidity)||void 0===s?void 0:s.call(i))&&e(this,Ae,"f").call(this,i,t)}))}))},Le=function(t){this.contentRootElement.querySelectorAll(`descope-button:not([${g}]), [data-type="button"]:not([${g}]`).forEach((i=>{i.onclick=()=>{e(this,Ae,"f").call(this,i,t)}})),e(this,Z,"m",Te).call(this,t),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${h}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},Ue=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},Pe=function(e,t,i){var s;const[o,n]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],r={data:{code:t,exchangeError:i},action:"code"};if("descope-wc"===o&&n){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",n);try{window.opener.postMessage(r,n)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(r),t.close()}try{window.close()}catch(e){}};export{$e as default};
1
+ import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{ensureFingerprintIds as o,clearFingerprintData as n}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as r,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as l,URL_TOKEN_PARAM_NAME as d,URL_RUN_IDS_PARAM_NAME as c,SDK_SCRIPTS_LOAD_TIMEOUT as h,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as p,ELEMENT_TYPE_ATTRIBUTE as u,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as g}from"../constants/index.js";import{timeoutPromise as v,withMemCache as m,leadingDebounce as f,getUserLocale as b,showFirstScreenOnExecutionInit as w,injectSamlIdpForm as S,openCenteredPopup as y,getAnimationDirection as C,handleAutoFocus as I,transformStepStateForCustomScreen as k,getElementDescopeAttributes as R,getScriptResultPath as O,submitForm as W,transformScreenInputs as x,handleReportValidityOnBlur as E,getFirstNonEmptyValue as A,clearPreviousExternalInputs as j}from"../helpers/helpers.js";import T from"../helpers/state.js";import{disableWebauthnButtons as L,updateTemplateFromScreenState as U,setPhoneAutoDetectDefaultCode as P,setTOTPVariable as $,setNOTPVariable as N,setCssVars as M,updateScreenFromScreenState as q,replaceElementMessage as F}from"../helpers/templates.js";import{isConditionalLoginSupported as V}from"../helpers/webauthn.js";import{getABTestingKey as D}from"../helpers/abTestingKey.js";import{calculateConditions as B,calculateCondition as K}from"../helpers/conditions.js";import{setLastAuth as H,getLastAuth as _}from"../helpers/lastAuth.js";import G from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as J,FETCH_ERROR_RESPONSE_ERROR_CODE as z,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as Q,FLOW_TIMED_OUT_ERROR_CODE as X,POLLING_STATUS_NOT_FOUND_ERROR_CODE as Y}from"../constants/general.js";var Z,ee,te,ie,se,oe,ne,re,ae,le,de,ce,he,pe,ue,ge,ve,me,fe,be,we,Se,ye,Ce,Ie,ke,Re,Oe,We,xe,Ee,Ae,je,Te,Le,Ue,Pe;class $e extends G{static set sdkConfigOverrides(e){G.sdkConfigOverrides=e}static get sdkConfigOverrides(){return G.sdkConfigOverrides}constructor(){const s=new T({deferredRedirect:!1});super(s.update.bind(s)),Z.add(this),this.stepState=new T({}),ee.set(this,void 0),te.set(this,null),ie.set(this,null),se.set(this,{visibilitychange:e(this,Z,"m",oe).bind(this)}),this.bridgeVersion=2,this.nativeCallbacks={},pe.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},ge.set(this,(t=>{const i=()=>{this.contentRootElement.classList.toggle("hidden",t),this.slotElement.classList.toggle("hidden",!t),t&&(this.contentRootElement.innerHTML="")};t&&this.contentRootElement.hasChildNodes()?e(this,Z,"m",ve).call(this,i):i()})),me.set(this,((s,o,n,l,d=!1)=>{const c=[X,Y];if(this.flowState.current.action===r.poll){this.logger.debug("polling - Scheduling polling request");const r=Date.now(),h=d?500:2e3;t(this,ee,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const p=this.sdk.flow.next(s,o,a.polling,n,l,{}),u=document.hidden&&!d&&Date.now()-r>h+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield v(e,p)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,me,"f").call(this,s,o,n,l,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===J)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,me,"f").call(this,s,o,n,l);this.logger.debug("polling - Got a response"),(null==g?void 0:g.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(g.error,null,4)),(null===(i=null==g?void 0:g.error)||void 0===i?void 0:i.errorCode)&&c.includes(g.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):e(this,me,"f").call(this,s,o,n,l),e(this,be,"f").call(this,g)}))),h),"f")}})),fe.set(this,(()=>{clearTimeout(e(this,ee,"f")),t(this,ee,null,"f")})),be.set(this,(i=>{var s,o,n,a,l,d,c,h,p,u,g,v,m;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,r=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,Z,"m",Ue).call(this,"error",(null==i?void 0:i.error)||{errorCode:z,errorDescription:r,errorMessage:t}),this.loggerWrapper.error((null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorDescription)||t,(null===(l=null==i?void 0:i.error)||void 0===l?void 0:l.errorMessage)||r);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==Q&&c!==X||!this.isRestartOnError||e(this,Z,"m",he).call(this))}null===(h=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===h||h.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(p=i.data)||void 0===p?void 0:p.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(v=i.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:C}=i.data;if(y!==r.poll&&e(this,fe,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&H(S);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),void e(this,Z,"m",Ue).call(this,"success",t)}this.storeLastAuthenticatedUser&&H(S,!0),C&&window.open(C,"_blank");const{executionId:I,stepId:k,stepName:R,screen:O,redirect:W,webauthn:x,error:E,samlIdpResponse:A,nativeResponse:j}=i.data,T=Date.now();y!==r.poll?(this.loggerWrapper.info(`Step "${R||`#${k}`}" is ${b}`,"",{screen:O,status:b,stepId:k,stepName:R,action:y,error:E}),(null===(m=O.state)||void 0===m?void 0:m.clientScripts)&&t(this,ie,this.loadSdkScripts(O.state.clientScripts),"f"),this.flowState.update({stepId:k,stepName:R,executionId:I,action:y,redirectTo:null==W?void 0:W.url,redirectIsPopup:null==W?void 0:W.isPopup,screenId:null==O?void 0:O.id,screenState:null==O?void 0:O.state,webauthnTransactionId:null==x?void 0:x.transactionId,webauthnOptions:null==x?void 0:x.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,nativeResponseType:null==j?void 0:j.type,nativePayload:null==j?void 0:j.payload,reqTimestamp:T})):this.flowState.update({action:y,reqTimestamp:T})})),we.set(this,m((()=>i(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),Re.set(this,null),Ae.set(this,f(((t,s)=>i(this,void 0,void 0,(function*(){var i;if("true"===t.getAttribute("formnovalidate")||e(this,Z,"m",Ie).call(this)){const o=null==t?void 0:t.getAttribute("id");e(this,Z,"m",Oe).call(this,t);const n=yield e(this,Z,"m",ke).call(this),r=R(t);this.nextRequestStatus.update({isLoading:!0});const a=Object.assign(Object.assign(Object.assign({},r),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(o,a),this.nextRequestStatus.update({isLoading:!1}),e(this,Z,"m",We).call(this,n)}}))))),this.flowState=s}nativeResume(t,i){var s,o,n,r,a;const h=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let{exchangeCode:e}=h;if(!e){e=null===(s=new URL(h.url).searchParams)||void 0===s?void 0:s.get(l)}null===(n=(o=this.nativeCallbacks).complete)||void 0===n||n.call(o,{exchangeCode:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(h.url),i=t.searchParams.get(d),s=t.searchParams.get(c).split("_").pop();e(this,fe,"f").call(this),this.flowState.update({token:i,stepId:s,action:void 0})}else if("beforeScreen"===t){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=h;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=h,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(r=this.nativeCallbacks).complete)||void 0===a||a.call(r,h)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[O(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=Promise.all(null==e?void 0:e.map((e=>i(this,void 0,void 0,(function*(){var i,s;const o=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(o){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=o;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}yield this.injectNpmLib("@descope/flow-scripts","1.0.13",`dist/${e.id}.js`);const n=null===(s=globalThis.descope)||void 0===s?void 0:s[e.id];return new Promise(((i,s)=>{try{const s=n(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i),this.loggerWrapper);if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t),this.nextRequestStatus.subscribe((()=>{var t;this.loggerWrapper.debug("Unloading script",e.id),null===(t=s.stop)||void 0===t||t.call(s)}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),h)}));return Promise.race([s,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){if(!window.descopeBridge)return this._init();this.lazyInit=this._init}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,Z,"m",de).call(this),window.addEventListener("visibilitychange",e(this,se,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var i;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,fe,"f").call(this),null===(i=e(this,te,"f"))||void 0===i||i.abort(),t(this,te,null,"f"),window.removeEventListener("visibilitychange",e(this,se,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=b(e),o=yield this.getTargetLocales();return o.includes(s.locale)?i=`${t}-${s.locale}.html`:o.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(l,d,c){return i(this,void 0,void 0,(function*(){var h,p;const{projectId:u,flowId:g,tenant:v,stepId:m,executionId:f,action:I,screenId:k,screenState:R,redirectTo:O,redirectIsPopup:E,redirectUrl:A,token:j,code:T,isPopup:L,exchangeError:U,webauthnTransactionId:P,webauthnOptions:$,redirectAuthCodeChallenge:N,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:F,locale:V,samlIdpResponseUrl:H,samlIdpResponseSamlResponse:G,samlIdpResponseRelayState:J,nativeResponseType:z,nativePayload:Q,reqTimestamp:X}=l,Y=s(l,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","nativeResponseType","nativePayload","reqTimestamp"]);let ee,se,oe;const ne=D(),{outboundAppId:re}=this,{outboundAppScopes:le}=this,de=this.sdk.getLastUserLoginId(),ce=yield this.getFlowConfig(),he=yield this.getProjectConfig(),pe=Object.entries(he.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),ge=M&&N?{callbackUrl:M,codeChallenge:N,backupCallbackUri:q}:void 0,ve=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;let fe={};if(!f){const i=[...ce.clientScripts||[],...ce.sdkScripts||[]];if(ce.conditions){let e=[];({startScreenId:ee,conditionInteractionId:oe,startScreenName:se,clientScripts:e,componentsConfig:fe}=B({loginId:de,code:T,token:j,abTestingKey:ne,lastAuth:_(de)},ce.conditions)),i.push(...e||[])}else ce.condition?({startScreenId:ee,conditionInteractionId:oe}=K(ce.condition,{loginId:de,code:T,token:j,abTestingKey:ne,lastAuth:_(de)})):(se=ce.startScreenName,ee=ce.startScreenId);if(t(this,ie,this.loadSdkScripts(i),"f"),ce.fingerprintEnabled&&ce.fingerprintKey?yield o(ce.fingerprintKey,this.baseUrl):n(),!w(ee,Y)){const t=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:ge},Y),{client:this.client}),A&&{redirectUrl:A}),{lastAuth:_(de),abTestingKey:ne,locale:b(V).locale,nativeOptions:ve,outboundAppId:re,outboundAppScopes:le}),oe,"",he.componentsVersion,pe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),T?{exchangeCode:T,idpInitiated:!0}:{}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j?{token:j}:{}),Y.oidcLoginHint?{externalId:Y.oidcLoginHint}:{}));return e(this,be,"f").call(this,t),void("completed"!==(null===(h=null==t?void 0:t.data)||void 0===h?void 0:h.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:L,code:T,exchangeError:U,isCodeChanged:c("code"),isExchangeErrorChanged:c("exchangeError")})),L&&(c("code")&&T||c("exchangeError")&&U))return void e(this,Z,"m",Pe).call(this,f,T,U);if(f&&(c("token")&&j||c("code")&&T||c("exchangeError")&&U)){const t=yield this.sdk.flow.next(f,m,a.submit,ce.version,he.componentsVersion,{token:j,exchangeCode:T,exchangeError:U});return e(this,be,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(I===r.loadForm&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>c(e)))){if(!H||!G)return void this.loggerWrapper.error("Did not get saml idp params data to load");S(H,G,J||"",W)}if(I===r.redirect&&(c("redirectTo")||c("deferredRedirect"))){if(!O)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===O)return;if("android"===F&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${E}`),E){this.loggerWrapper.debug("Opening redirect in popup");const t=y(O,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));const s=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const t=i?this.popupOrigin:window.location.origin;if(e.origin!==t)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${t}"`);const{action:s,data:o}=e.data||{};"code"===s&&this.flowState.update({code:o.code,exchangeError:o.exchangeError})};let o;this.loggerWrapper.debug("Starting popup closed detection");const n=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(n),e(this,Z,"m",Ue).call(this,"popupclosed",{}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==o||o())}),1e3);if(i)window.addEventListener("message",s),o=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",s)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(f);e.onmessage=s,o=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(O),this.flowState.update({redirectTo:"no-op"}),e(this,Z,"m",Ue).call(this,"popupclosed",{});return}if(I===r.webauthnCreate||I===r.webauthnGet){if(!P||!$)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s;null===(p=e(this,te,"f"))||void 0===p||p.abort(),t(this,te,null,"f");try{i=I===r.webauthnCreate?yield this.sdk.webauthn.helpers.create($):yield this.sdk.webauthn.helpers.get($)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),s=e.name}const o=yield this.sdk.flow.next(f,m,a.submit,ce.version,he.componentsVersion,{transactionId:P,response:i,failure:s});e(this,be,"f").call(this,o)}if(I===r.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,m,a.submit,ce.version,he.componentsVersion,t);e(this,be,"f").call(this,i)})),void e(this,Z,"m",ae).call(this,z,Q);if(c("action")&&e(this,me,"f").call(this,f,m,ce.version,he.componentsVersion),!k&&!ee)return void this.loggerWrapper.warn("No screen was found to show");const we=ee||k,Se=yield this.getHtmlFilenameWithLocale(V,we),{oidcLoginHint:ye,oidcPrompt:Ce,oidcErrorRedirectUri:Ie,oidcResource:ke,samlIdpUsername:Re}=Y,Oe={direction:C(m,d.stepId),screenState:Object.assign(Object.assign({},R),{form:Object.assign(Object.assign({},this.formConfigValues),null==R?void 0:R.form),lastAuth:{loginId:de,name:this.sdk.getLastUserDisplayName()||de},componentsConfig:Object.assign(Object.assign(Object.assign({},ce.componentsConfig),fe),null==R?void 0:R.componentsConfig)}),htmlFilename:`${we}.html`,htmlLocaleFilename:Se,screenId:we,stepName:l.stepName||se,samlIdpUsername:Re,oidcLoginHint:ye,oidcPrompt:Ce,oidcErrorRedirectUri:Ie,oidcResource:ke,action:I},We=_(de);w(ee,Y)?Oe.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ce?void 0:ce.clientScripts)||[];yield e(this,Z,"m",je).call(this,i);const o=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:ge},Y),{lastAuth:We,preview:this.preview,abTestingKey:ne,client:this.client}),A&&{redirectUrl:A}),{locale:b(V).locale,nativeOptions:ve,outboundAppId:re,outboundAppScopes:le}),oe,t,he.componentsVersion,pe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),x(s)),T&&{exchangeCode:T,idpInitiated:!0}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j&&{token:j}));return e(this,be,"f").call(this,o),o})):(c("projectId")||c("baseUrl")||c("executionId")||c("stepId"))&&(Oe.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==R?void 0:R.clientScripts)||[];yield e(this,Z,"m",je).call(this,i);const o=yield this.sdk.flow.next(f,m,t,ce.version,he.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),x(s)));return e(this,be,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",Oe.screenId),yield e(this,Z,"m",ue).call(this,Oe),this.stepState.update(Oe)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n;const{htmlFilename:r,htmlLocaleFilename:l,direction:d,next:c,screenState:h}=t;this.loggerWrapper.debug("Rendering a flow screen");const p=document.createElement("template");p.innerHTML=yield this.getPageContent(r,l);const g=p.content.cloneNode(!0),v=this.loadDescopeUiComponents(p);this.sdk.webauthn.helpers.isSupported()?yield e(this,Z,"m",ye).call(this,g,c):L(g),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(n=h.form)||void 0===n?void 0:n.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),U(g,h,h.componentsConfig,this.formConfig,this.loggerWrapper);const{geo:m}=yield this.getExecutionContext();P(g,m);const f=()=>i(this,void 0,void 0,(function*(){var i,o;yield v;const n=this.contentRootElement;$(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),N(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),M(n,g,h.cssVars,this.loggerWrapper),n.replaceChildren(g);const r=!s.htmlFilename;setTimeout((()=>{e(this,Z,"m",xe).call(this),this.validateOnBlur&&E(n),q(n,h),e(this,Z,"m",Ce).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),I(n,this.autoFocus,r)})),e(this,Z,"m",Le).call(this,c);n.querySelector(`[${u}="polling"]`)&&c(a.polling,{})}));d?e(this,Z,"m",ve).call(this,f):f()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${p}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}ee=new WeakMap,te=new WeakMap,ie=new WeakMap,se=new WeakMap,pe=new WeakMap,ge=new WeakMap,me=new WeakMap,fe=new WeakMap,be=new WeakMap,we=new WeakMap,Re=new WeakMap,Ae=new WeakMap,Z=new WeakSet,oe=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},ne=function(t,s,o){return i(this,void 0,void 0,(function*(){var i;return(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&new Promise((i=>{this.nativeCallbacks.screenNext=o,this.nativeCallbacks.screenResolve=i,e(this,Z,"m",ae).call(this,"beforeScreen",{screen:t,context:s})}))}))},re=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,Z,"m",ae).call(this,"afterScreen",{screen:t})},ae=function(t,i){e(this,Z,"m",Ue).call(this,"bridge",{type:t,payload:i})},le=function({errorText:e,errorType:t}){const i=()=>{var i;let s=e;try{s=(null===(i=this.errorTransformer)||void 0===i?void 0:i.call(this,{text:e,type:t}))||e}catch(e){this.loggerWrapper.error("Error transforming error message",e.message)}F(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},de=function(){var t,i,o;null===(t=this.stepState)||void 0===t||t.subscribe(this.onStepChange.bind(this),(e=>{var t=e.screenState,i=s(void 0===t?{}:t,["errorText","errorType"]),o=s(e,["screenState"]);return Object.assign(Object.assign({},o),{screenState:i})})),null===(i=this.stepState)||void 0===i||i.subscribe(e(this,Z,"m",le).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(o=this.stepState)||void 0===o||o.subscribe(e(this,Z,"m",ce).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0})},ce=function({errorText:e,errorType:t}){(t||e)&&(this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((e=>{e.shadowRoot.querySelectorAll("descope-text-field[data-id]").forEach((e=>{e.value=""}))})),I(this.contentRootElement,this.autoFocus,!1))},he=function(){return i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update({stepId:null,executionId:null})):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},ue=function(o){return i(this,void 0,void 0,(function*(){var i;const n=Object.assign(Object.assign({},this.stepState.current),o),{next:r,stepName:a}=n,l=s(n,["next","stepName"]),d=k(l);let c=yield e(this,Z,"m",ne).call(this,a,d,r);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,a,d,r,this)));const h=!this.stepState.current.htmlFilename;if(e(this,ge,"f").call(this,c),e(this,pe,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,pe,c,"f"),c?this.stepState.unsubscribeAll():e(this,Z,"m",de).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,Z,"m",Ce).call(this,{isFirstScreen:h,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},ve=function(e){this.contentRootElement.addEventListener("transitionend",(()=>{this.loggerWrapper.debug("page switch transition end"),this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0}),this.loggerWrapper.debug("page switch transition start"),this.contentRootElement.classList.add("fade-out")},Se=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const i=`user-${t}`;e.setAttribute("name",i),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:i)}))}},ye=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,te,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield V())){const{options:s,transactionId:n}=(yield e(this,we,"f").call(this))||{};s&&n&&(e(this,Z,"m",Se).call(this,r),t(this,te,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,te,"f")).then((e=>i(this,void 0,void 0,(function*(){o(r.id,{transactionId:n,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},Ce=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,Z,"m",Ue).call(this,"ready",{}),i||e(this,Z,"m",re).call(this,s),e(this,Z,"m",Ue).call(this,"page-updated",{screenName:s}),e(this,Z,"m",Ue).call(this,"screen-updated",{screenName:s})},Ie=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"!==t.localName&&(null===(i=t.reportValidity)||void 0===i||i.call(t),e&&(e=null===(s=t.checkValidity)||void 0===s?void 0:s.call(t)))})),e},ke=function(){return i(this,void 0,void 0,(function*(){const e=this.getInputs();return(yield Promise.all(e.map((e=>i(this,void 0,void 0,(function*(){return{name:e.getAttribute("name"),value:e.value}})))))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},Oe=function(s){const o=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),n=()=>i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",n),s.removeAttribute("loading"),o.forEach((e=>{e.removeAttribute("disabled")}));const e=yield this.getFlowConfig(),t=[...e.clientScripts||[],...e.sdkScripts||[]];this.loadSdkScripts(t)})),r=()=>{var i;window.removeEventListener("pageshow",e(this,Re,"f")),t(this,Re,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),n())}),"f"),window.addEventListener("pageshow",e(this,Re,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&n(),this.removeEventListener("popupclosed",n),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},a=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?(this.addEventListener("popupclosed",n,{once:!0}),s.setAttribute("loading","true"),o.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(a),r())}))},We=function(e={}){var t,i;const s=A(e,["externalId","email","phone"]),o=A(e,["newPassword","password"]);if(s&&o)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:o});null===(i=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===i||i.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},xe=function(){j();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,Z,"m",Ee).call(this,t)))},Ee=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const i=t.getAttribute("slot"),s=`input-${e.id}-${i}`,o=document.createElement("slot");o.setAttribute("name",s),o.setAttribute("slot",i),e.appendChild(o),t.setAttribute("slot",s),this.appendChild(t)}))},je=function(t){return i(this,void 0,void 0,(function*(){if(e(this,ie,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ie,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-t).toString())}const i=this.loadSdkScriptsModules(),s=t.map((e=>e.id));for(const e of i)if(s.includes(e.id))try{if("function"==typeof e.present){(yield e.present())||this.loggerWrapper.debug(`Sdk script ${e.id} was cancelled`)}}catch(t){this.loggerWrapper.error(`Failed to present ${e.id} script module`,t.message)}let o=[];for(const e of i)"function"==typeof e.refresh&&o.push(e.refresh());if(o.length>0)try{yield v(h,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},Te=function(t){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((i=>{i.addEventListener("input",(()=>{var s;(null===(s=i.checkValidity)||void 0===s?void 0:s.call(i))&&e(this,Ae,"f").call(this,i,t)}))}))},Le=function(t){this.contentRootElement.querySelectorAll(`descope-button:not([${g}]), [data-type="button"]:not([${g}]`).forEach((i=>{i.onclick=()=>{e(this,Ae,"f").call(this,i,t)}})),e(this,Z,"m",Te).call(this,t),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${p}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},Ue=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},Pe=function(e,t,i){var s;const[o,n]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],r={data:{code:t,exchangeError:i},action:"code"};if("descope-wc"===o&&n){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",n);try{window.opener.postMessage(r,n)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(r),t.close()}try{window.close()}catch(e){}};export{$e as default};
2
2
  //# sourceMappingURL=DescopeWc.js.map