@descope/web-component 3.45.1 → 3.46.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/constants/index.js +1 -1
- package/dist/cjs/constants/index.js.map +1 -1
- package/dist/cjs/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/cjs/descope-wc/DescopeWc.js +1 -1
- package/dist/cjs/descope-wc/DescopeWc.js.map +1 -1
- package/dist/cjs/helpers/helpers.js +1 -1
- package/dist/cjs/helpers/helpers.js.map +1 -1
- package/dist/cjs/types.js.map +1 -1
- package/dist/esm/constants/index.js +1 -1
- package/dist/esm/constants/index.js.map +1 -1
- package/dist/esm/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/esm/descope-wc/DescopeWc.js +1 -1
- package/dist/esm/descope-wc/DescopeWc.js.map +1 -1
- package/dist/esm/helpers/helpers.js +1 -1
- package/dist/esm/helpers/helpers.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/index.d.ts +43 -42
- package/dist/index.js +2 -3
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.js","sources":["../../../src/lib/helpers/helpers.ts"],"sourcesContent":["import {\n ASSETS_FOLDER,\n BASE_CONTENT_URL,\n DESCOPE_ATTRIBUTE_PREFIX,\n URL_CODE_PARAM_NAME,\n URL_ERR_PARAM_NAME,\n URL_RUN_IDS_PARAM_NAME,\n URL_TOKEN_PARAM_NAME,\n URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME,\n URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME,\n URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME,\n URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME,\n OIDC_IDP_STATE_ID_PARAM_NAME,\n SAML_IDP_STATE_ID_PARAM_NAME,\n SAML_IDP_USERNAME_PARAM_NAME,\n SSO_APP_ID_PARAM_NAME,\n OIDC_LOGIN_HINT_PARAM_NAME,\n DESCOPE_IDP_INITIATED_PARAM_NAME,\n OVERRIDE_CONTENT_URL,\n OIDC_PROMPT_PARAM_NAME,\n OIDC_ERROR_REDIRECT_URI_PARAM_NAME,\n THIRD_PARTY_APP_ID_PARAM_NAME,\n THIRD_PARTY_APP_STATE_ID_PARAM_NAME,\n APPLICATION_SCOPES_PARAM_NAME,\n SDK_SCRIPT_RESULTS_KEY,\n URL_REDIRECT_MODE_PARAM_NAME,\n} from '../constants';\nimport { EXCLUDED_STATE_KEYS } from '../constants/customScreens';\nimport {\n AutoFocusOptions,\n CustomScreenState,\n Direction,\n Locale,\n SSOQueryParams,\n StepState,\n} from '../types';\n\nconst MD_COMPONENTS = ['descope-enriched-text'];\n\nfunction getUrlParam(paramName: string) {\n const urlParams = new URLSearchParams(window.location.search);\n\n return urlParams.get(paramName);\n}\n\nfunction getFlowUrlParam() {\n return getUrlParam(URL_RUN_IDS_PARAM_NAME);\n}\n\nfunction setFlowUrlParam(id: string) {\n if (window.history.pushState && id !== getFlowUrlParam()) {\n const newUrl = new URL(window.location.href);\n const search = new URLSearchParams(newUrl.search);\n search.set(URL_RUN_IDS_PARAM_NAME, id);\n newUrl.search = search.toString();\n window.history.pushState({}, '', newUrl.toString());\n }\n}\n\nfunction resetUrlParam(paramName: string) {\n if (window.history.replaceState && getUrlParam(paramName)) {\n const newUrl = new URL(window.location.href);\n const search = new URLSearchParams(newUrl.search);\n search.delete(paramName);\n newUrl.search = search.toString();\n window.history.replaceState({}, '', newUrl.toString());\n }\n}\n\nconst getFlowIdFromExecId = (executionId: string) => {\n const regex = /(.*)\\|#\\|.*/;\n return regex.exec(executionId)?.[1] || '';\n};\n\nexport async function fetchContent<T extends 'text' | 'json'>(\n url: string,\n returnType: T,\n): Promise<{\n body: T extends 'json' ? Record<string, any> : string;\n headers: Record<string, string>;\n}> {\n const res = await fetch(url, { cache: 'default' });\n if (!res.ok) {\n throw Error(`Error fetching URL ${url} [${res.status}]`);\n }\n\n return {\n body: await res[returnType || 'text'](),\n headers: Object.fromEntries(res.headers.entries()),\n };\n}\n\nconst pathJoin = (...paths: string[]) => paths.join('/').replace(/\\/+/g, '/'); // preventing duplicate separators\n\nexport function getContentUrl({\n projectId,\n filename,\n assetsFolder = ASSETS_FOLDER,\n baseUrl,\n}: {\n projectId: string;\n filename: string;\n assetsFolder?: string;\n baseUrl?: string;\n}) {\n const url = new URL(OVERRIDE_CONTENT_URL || baseUrl || BASE_CONTENT_URL);\n url.pathname = pathJoin(url.pathname, projectId, assetsFolder, filename);\n\n return url.toString();\n}\n\nexport function getAnimationDirection(\n currentIdxStr: string,\n prevIdxStr: string,\n) {\n if (!prevIdxStr) return undefined;\n\n const currentIdx = +currentIdxStr;\n const prevIdx = +prevIdxStr;\n\n if (Number.isNaN(currentIdx) || Number.isNaN(prevIdx)) return undefined;\n if (currentIdx > prevIdx) return Direction.forward;\n if (currentIdx < prevIdx) return Direction.backward;\n return undefined;\n}\n\nexport const getRunIdsFromUrl = (flowId: string) => {\n let [executionId = '', stepId = ''] = (getFlowUrlParam() || '').split('_');\n const executionFlowId = getFlowIdFromExecId(executionId);\n\n // if the flow id does not match, this execution id is not for this flow\n if (!flowId || (executionFlowId && executionFlowId !== flowId)) {\n executionId = '';\n stepId = '';\n }\n\n return { executionId, stepId, executionFlowId };\n};\n\nexport const setRunIdsOnUrl = (executionId: string, stepId: string) => {\n setFlowUrlParam([executionId, stepId].join('_'));\n};\n\nexport function isChromium() {\n return (\n /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)\n );\n}\n\nexport function clearRunIdsFromUrl() {\n resetUrlParam(URL_RUN_IDS_PARAM_NAME);\n}\n\nexport function getTokenFromUrl() {\n return getUrlParam(URL_TOKEN_PARAM_NAME) || undefined;\n}\n\nexport function clearTokenFromUrl() {\n resetUrlParam(URL_TOKEN_PARAM_NAME);\n}\n\nexport function getCodeFromUrl() {\n return getUrlParam(URL_CODE_PARAM_NAME) || undefined;\n}\n\nexport function getIsPopupFromUrl() {\n return getUrlParam(URL_REDIRECT_MODE_PARAM_NAME) === 'popup';\n}\n\nexport function getExchangeErrorFromUrl() {\n return getUrlParam(URL_ERR_PARAM_NAME) || undefined;\n}\n\nexport function clearCodeFromUrl() {\n resetUrlParam(URL_CODE_PARAM_NAME);\n}\n\nexport function clearIsPopupFromUrl() {\n resetUrlParam(URL_REDIRECT_MODE_PARAM_NAME);\n}\n\nexport function clearExchangeErrorFromUrl() {\n resetUrlParam(URL_ERR_PARAM_NAME);\n}\n\nexport function getRedirectAuthFromUrl() {\n const redirectAuthCodeChallenge = getUrlParam(\n URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME,\n );\n const redirectAuthCallbackUrl = getUrlParam(\n URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME,\n );\n const redirectAuthBackupCallbackUri = getUrlParam(\n URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME,\n );\n const redirectAuthInitiator = getUrlParam(\n URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME,\n );\n return {\n redirectAuthCodeChallenge,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthInitiator,\n };\n}\n\nexport function getOIDCIDPParamFromUrl() {\n return getUrlParam(OIDC_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function clearOIDCIDPParamFromUrl() {\n resetUrlParam(OIDC_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function getSAMLIDPParamFromUrl() {\n return getUrlParam(SAML_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function clearSAMLIDPParamFromUrl() {\n resetUrlParam(SAML_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function getSAMLIDPUsernameParamFromUrl() {\n return getUrlParam(SAML_IDP_USERNAME_PARAM_NAME);\n}\n\nexport function clearSAMLIDPUsernameParamFromUrl() {\n resetUrlParam(SAML_IDP_USERNAME_PARAM_NAME);\n}\n\nexport function getDescopeIDPInitiatedParamFromUrl() {\n return getUrlParam(DESCOPE_IDP_INITIATED_PARAM_NAME);\n}\n\nexport function clearDescopeIDPInitiatedParamFromUrl() {\n resetUrlParam(DESCOPE_IDP_INITIATED_PARAM_NAME);\n}\n\nexport function getSSOAppIdParamFromUrl() {\n return getUrlParam(SSO_APP_ID_PARAM_NAME);\n}\n\nexport function getThirdPartyAppIdParamFromUrl() {\n return getUrlParam(THIRD_PARTY_APP_ID_PARAM_NAME);\n}\n\nexport function clearSSOAppIdParamFromUrl() {\n resetUrlParam(SSO_APP_ID_PARAM_NAME);\n}\n\nexport function clearThirdPartyAppIdParamFromUrl() {\n resetUrlParam(THIRD_PARTY_APP_ID_PARAM_NAME);\n}\n\nexport function getThirdPartyAppStateIdParamFromUrl() {\n return getUrlParam(THIRD_PARTY_APP_STATE_ID_PARAM_NAME);\n}\n\nexport function clearThirdPartyAppStateIdParamFromUrl() {\n resetUrlParam(THIRD_PARTY_APP_STATE_ID_PARAM_NAME);\n}\n\nexport function getApplicationScopesParamFromUrl() {\n return getUrlParam(APPLICATION_SCOPES_PARAM_NAME);\n}\n\nexport function clearApplicationScopesParamFromUrl() {\n resetUrlParam(APPLICATION_SCOPES_PARAM_NAME);\n}\n\nexport function getOIDCLoginHintParamFromUrl() {\n return getUrlParam(OIDC_LOGIN_HINT_PARAM_NAME);\n}\n\nexport function clearOIDCLoginHintParamFromUrl() {\n resetUrlParam(OIDC_LOGIN_HINT_PARAM_NAME);\n}\n\nexport function getOIDCPromptParamFromUrl() {\n return getUrlParam(OIDC_PROMPT_PARAM_NAME);\n}\n\nexport function clearOIDCPromptParamFromUrl() {\n resetUrlParam(OIDC_PROMPT_PARAM_NAME);\n}\n\nexport function getOIDCErrorRedirectUriParamFromUrl() {\n return getUrlParam(OIDC_ERROR_REDIRECT_URI_PARAM_NAME);\n}\n\nexport function clearOIDCErrorRedirectUriParamFromUrl() {\n resetUrlParam(OIDC_ERROR_REDIRECT_URI_PARAM_NAME);\n}\n\nexport const camelCase = (s: string) =>\n s.replace(/-./g, (x) => x[1].toUpperCase());\n\nexport const createIsChanged =\n <T extends Record<string, any>>(state: T, prevState: T) =>\n (attrName: keyof T) =>\n state[attrName] !== prevState[attrName];\n\nexport const getElementDescopeAttributes = (ele: HTMLElement) =>\n Array.from(ele?.attributes || []).reduce((acc, attr) => {\n const descopeAttrName = new RegExp(\n `^${DESCOPE_ATTRIBUTE_PREFIX}(\\\\S+)$`,\n ).exec(attr.name)?.[1];\n\n return !descopeAttrName\n ? acc\n : Object.assign(acc, { [descopeAttrName]: attr.value });\n }, {});\n\nexport const getFlowConfig = (config: Record<string, any>, flowId: string) =>\n config?.flows?.[flowId] || {};\n\nexport const handleUrlParams = (\n flowId: string,\n logger: { debug: (...data: any[]) => void },\n) => {\n const { executionId, stepId, executionFlowId } = getRunIdsFromUrl(flowId);\n\n // if the flow id does not match, we do not want to read & remove any query params\n // because it's probably belongs to another flow\n if (executionFlowId && flowId !== executionFlowId) {\n logger.debug(\n 'Flow id does not match the execution flow id, skipping url params handling',\n );\n return { ssoQueryParams: {} };\n }\n\n if (executionId || stepId) {\n clearRunIdsFromUrl();\n }\n\n const token = getTokenFromUrl();\n if (token) {\n clearTokenFromUrl();\n }\n\n const code = getCodeFromUrl();\n if (code) {\n clearCodeFromUrl();\n }\n\n // this is used for oauth when we want to open the provider login page in a new tab\n const isPopup = getIsPopupFromUrl();\n if (isPopup) {\n clearIsPopupFromUrl();\n }\n\n const exchangeError = getExchangeErrorFromUrl();\n if (exchangeError) {\n clearExchangeErrorFromUrl();\n }\n\n // these query params are retained to allow the flow to be refreshed\n // without losing the redirect auth state\n const {\n redirectAuthCodeChallenge,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthInitiator,\n } = getRedirectAuthFromUrl();\n\n const oidcIdpStateId = getOIDCIDPParamFromUrl();\n if (oidcIdpStateId) {\n clearOIDCIDPParamFromUrl();\n }\n\n const samlIdpStateId = getSAMLIDPParamFromUrl();\n if (samlIdpStateId) {\n clearSAMLIDPParamFromUrl();\n }\n\n const samlIdpUsername = getSAMLIDPUsernameParamFromUrl();\n if (samlIdpStateId) {\n clearSAMLIDPUsernameParamFromUrl();\n }\n\n const descopeIdpInitiated = getDescopeIDPInitiatedParamFromUrl();\n if (descopeIdpInitiated) {\n clearDescopeIDPInitiatedParamFromUrl();\n }\n\n const ssoAppId = getSSOAppIdParamFromUrl();\n if (ssoAppId) {\n clearSSOAppIdParamFromUrl();\n }\n\n const thirdPartyAppId = getThirdPartyAppIdParamFromUrl();\n if (thirdPartyAppId) {\n clearThirdPartyAppIdParamFromUrl();\n }\n\n const thirdPartyAppStateId = getThirdPartyAppStateIdParamFromUrl();\n if (thirdPartyAppStateId) {\n clearThirdPartyAppStateIdParamFromUrl();\n }\n\n const applicationScopes = getApplicationScopesParamFromUrl();\n if (applicationScopes) {\n clearApplicationScopesParamFromUrl();\n }\n\n const oidcLoginHint = getOIDCLoginHintParamFromUrl();\n if (oidcLoginHint) {\n clearOIDCLoginHintParamFromUrl();\n }\n\n const oidcPrompt = getOIDCPromptParamFromUrl();\n if (oidcPrompt) {\n clearOIDCPromptParamFromUrl();\n }\n\n const oidcErrorRedirectUri = getOIDCErrorRedirectUriParamFromUrl();\n if (oidcErrorRedirectUri) {\n clearOIDCErrorRedirectUriParamFromUrl();\n }\n\n const idpInitiatedVal = descopeIdpInitiated === 'true';\n\n return {\n executionId,\n stepId,\n token,\n code,\n isPopup,\n exchangeError,\n redirectAuthCodeChallenge,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthInitiator,\n ssoQueryParams: {\n oidcIdpStateId,\n samlIdpStateId,\n samlIdpUsername,\n descopeIdpInitiated: idpInitiatedVal,\n ssoAppId,\n oidcLoginHint,\n oidcPrompt,\n oidcErrorRedirectUri,\n thirdPartyAppId,\n thirdPartyAppStateId,\n applicationScopes,\n },\n };\n};\n\nexport const loadFont = (url: string) => {\n if (!url) return;\n\n const font = document.createElement('link');\n font.href = url;\n font.rel = 'stylesheet';\n document.head.appendChild(font);\n};\n\nconst compareArrays = (array1: any[], array2: any[]) =>\n array1.length === array2.length &&\n array1.every((value: any, index: number) => value === array2[index]);\n\nexport const withMemCache = <I extends any[], O>(fn: (...args: I) => O) => {\n let prevArgs: any[];\n let cache: any;\n return Object.assign(\n (...args: I) => {\n if (prevArgs && compareArrays(prevArgs, args)) return cache as O;\n\n prevArgs = args;\n cache = fn(...args);\n\n return cache as O;\n },\n {\n reset: () => {\n prevArgs = undefined;\n cache = undefined;\n },\n },\n );\n};\n\nexport const handleAutoFocus = (\n ele: HTMLElement,\n autoFocus: AutoFocusOptions,\n isFirstScreen: boolean,\n) => {\n if (\n autoFocus === true ||\n (autoFocus === 'skipFirstScreen' && !isFirstScreen)\n ) {\n // focus the first visible input\n const firstVisibleInput: HTMLInputElement = ele.querySelector('*[name]');\n setTimeout(() => {\n firstVisibleInput?.focus();\n });\n }\n};\n\nexport const handleReportValidityOnBlur = (rootEle: HTMLElement) => {\n rootEle.querySelectorAll('*[name]').forEach((ele: HTMLInputElement) => {\n ele.addEventListener('blur', () => {\n const onBlur = () => {\n // reportValidity also focus the element if it's invalid\n // in order to prevent this we need to override the focus method\n const origFocus = ele.focus;\n // eslint-disable-next-line no-param-reassign\n ele.focus = () => {};\n ele.reportValidity?.();\n setTimeout(() => {\n // eslint-disable-next-line no-param-reassign\n ele.focus = origFocus;\n });\n };\n\n const isInputAlreadyInErrorState = ele.getAttribute('invalid') === 'true';\n\n if (isInputAlreadyInErrorState || ele.value?.length) {\n onBlur();\n return;\n }\n\n // If the input is not in an error state, has no value, and a `formnovalidate` button was clicked,\n // we want to prevent triggering validation.\n // This handles a case where a required input was focused, and the user then clicked a social login button —\n // in that case, we don't want the required error message to flash for a split second.\n const ref = { timer: undefined };\n\n const onClick = (e: MouseEvent) => {\n const target = e.target as HTMLElement;\n\n if (target.getAttribute('formnovalidate') === 'true') {\n clearTimeout(ref.timer);\n ref.timer = undefined;\n }\n };\n\n ref.timer = setTimeout(() => {\n rootEle.removeEventListener('click', onClick);\n onBlur();\n ref.timer = undefined;\n }, 150);\n\n rootEle.addEventListener('click', onClick, { once: true });\n });\n });\n};\n\n/**\n * To return a fallback value in case the timeout expires and the promise\n * isn't fulfilled:\n *\n * const promise = loadUserCount();\n * const count = await timeoutPromise(2000, promise, 0);\n *\n * Or without a fallback value to just throw an error if the timeout expires:\n *\n * try {\n * count = await timeoutPromise(2000, promise);\n * }\n *\n * Fallback is returned only in case of timeout, so if the passed promise rejects\n * the fallback value is not used, and the returned promise will throw as well.\n */\nexport function timeoutPromise<T>(\n timeout: number,\n promise: Promise<T>,\n fallback?: T,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n let expired = false;\n const timer = setTimeout(() => {\n expired = true;\n if (fallback !== undefined) {\n resolve(fallback);\n } else {\n reject(new Error(`Promise timed out after ${timeout} ms`));\n }\n }, timeout);\n\n promise\n .then((value) => {\n if (!expired) {\n clearTimeout(timer);\n resolve(value);\n }\n })\n .catch((error) => {\n if (!expired) {\n clearTimeout(timer);\n reject(error);\n }\n });\n });\n}\n\nexport const getChromiumVersion = (): number => {\n const brands = (navigator as any)?.userAgentData?.brands;\n const found = brands?.find(\n ({ brand, version }) => brand === 'Chromium' && parseFloat(version),\n );\n return found ? found.version : 0;\n};\n\n// As an optimization - We can show first screen if we have startScreenId and we don't have any other of the ssoAppId/oidcIdpStateId/samlIdp params\n// - If there startScreenId it means that the sdk can show the first screen and we don't need to wait for the sdk to return the first screen\n// - If there is any one else of the other params (like oidcIdpStateId, ..) - we can't skip this call because descope may decide not to show the first screen (in cases like a user is already logged in)\nexport const showFirstScreenOnExecutionInit = (\n startScreenId: string,\n {\n oidcIdpStateId,\n samlIdpStateId,\n samlIdpUsername,\n ssoAppId,\n oidcLoginHint,\n oidcPrompt,\n oidcErrorRedirectUri,\n thirdPartyAppId,\n thirdPartyAppStateId,\n applicationScopes,\n }: SSOQueryParams,\n): boolean =>\n !!startScreenId &&\n !oidcIdpStateId &&\n !samlIdpStateId &&\n !samlIdpUsername &&\n !ssoAppId &&\n !oidcLoginHint &&\n !oidcPrompt &&\n !oidcErrorRedirectUri &&\n !thirdPartyAppId &&\n !thirdPartyAppStateId &&\n !applicationScopes;\n\nexport const injectSamlIdpForm = (\n url: string,\n samlResponse: string,\n relayState: string,\n submitCallback: (form: HTMLFormElement) => void,\n) => {\n const formEle = document.createElement('form');\n formEle.method = 'POST';\n formEle.action = url;\n formEle.innerHTML = `\n <input type=\"hidden\" role=\"saml-response\" name=\"SAMLResponse\" value=\"${samlResponse}\" />\n <input type=\"hidden\" role=\"saml-relay-state\" name=\"RelayState\" value=\"${relayState}\" />\n <input style=\"display: none;\" id=\"SAMLSubmitButton\" type=\"submit\" value=\"Continue\" />\n `;\n\n document.body.appendChild(formEle);\n\n submitCallback(formEle);\n};\n\nexport const submitForm = (formEle: HTMLFormElement) => formEle?.submit();\n\nexport const getFirstNonEmptyValue = (obj: object, keys: string[]) => {\n const firstNonEmptyKey = keys.find((key) => obj[key]);\n return firstNonEmptyKey ? obj[firstNonEmptyKey] : null;\n};\n\nexport const leadingDebounce = <T extends (...args: any[]) => void>(\n func: T,\n wait = 100,\n) => {\n let timeout: NodeJS.Timeout;\n return function executedFunction(...args) {\n if (!timeout) func.apply(this, args);\n clearTimeout(timeout);\n timeout = setTimeout(() => {\n timeout = null;\n }, wait);\n } as T;\n};\n\nexport function getUserLocale(locale: string): Locale {\n if (locale) {\n return { locale: locale.toLowerCase(), fallback: locale.toLowerCase() };\n }\n const nl = navigator.language;\n if (!nl) {\n return { locale: '', fallback: '' };\n }\n\n if (nl.includes('-')) {\n return {\n locale: nl.toLowerCase(),\n fallback: nl.split('-')[0].toLowerCase(),\n };\n }\n\n return { locale: nl.toLowerCase(), fallback: nl.toLowerCase() };\n}\n\nexport const clearPreviousExternalInputs = () => {\n document\n .querySelectorAll('[data-hidden-input=\"true\"]')\n .forEach((ele) => ele.remove());\n};\n\nexport const shouldHandleMarkdown = (compName: string) =>\n MD_COMPONENTS.includes(compName);\n\nconst omitBy = <T extends Record<string, any>>(\n obj: T,\n predicate: (value: any, key: keyof T) => boolean,\n): T =>\n Object.fromEntries(\n Object.entries(obj).filter(\n ([key, value]) => !predicate(value, key as keyof T),\n ),\n ) as T;\n\nexport const transformStepStateForCustomScreen = (\n state: Partial<StepState>,\n) => {\n const sanitizedState: CustomScreenState = omitBy(\n state.screenState,\n (_, key) => EXCLUDED_STATE_KEYS.includes(key) || key.startsWith('_'),\n );\n\n const {\n screenState: { errorText, errorType },\n } = state;\n\n if (errorText || errorType) {\n sanitizedState.error = { text: errorText, type: errorType };\n }\n\n if (state.action) {\n sanitizedState.action = state.action;\n }\n\n if (state.screenState?.componentsConfig?.thirdPartyAppApproveScopes?.data) {\n sanitizedState.inboundAppApproveScopes =\n state.screenState.componentsConfig.thirdPartyAppApproveScopes.data;\n }\n\n return sanitizedState;\n};\n\nexport const transformScreenInputs = (inputs: Record<string, any>) => {\n const res = { ...inputs };\n\n if (inputs.inboundAppApproveScopes) {\n res.thirdPartyAppApproveScopes = inputs.inboundAppApproveScopes;\n }\n\n return res;\n};\n\nexport function getScriptResultPath(scriptId: string, resultKey?: string) {\n const path = resultKey ? `${scriptId}_${resultKey}` : scriptId;\n return `${SDK_SCRIPT_RESULTS_KEY}.${path}`;\n}\n\nexport const openCenteredPopup = (\n url: string,\n title: string,\n w: number,\n h: number,\n) => {\n const dualScreenLeft =\n window.screenLeft !== undefined\n ? window.screenLeft\n : (window.screen as any).left;\n const dualScreenTop =\n window.screenTop !== undefined\n ? window.screenTop\n : (window.screen as any).top;\n\n const width =\n window.innerWidth ||\n document.documentElement.clientWidth ||\n window.screen.width;\n const height =\n window.innerHeight ||\n document.documentElement.clientHeight ||\n window.screen.height;\n\n const left = (width - w) / 2 + dualScreenLeft;\n const top = (height - h) / 2 + dualScreenTop;\n\n const popup = window.open(\n url,\n title,\n `width=${w},height=${h},top=${top},left=${left},scrollbars=yes,resizable=yes`,\n );\n\n popup.focus();\n\n return popup;\n};\n"],"names":["MD_COMPONENTS","getUrlParam","paramName","URLSearchParams","window","location","search","get","resetUrlParam","history","replaceState","newUrl","URL","href","delete","toString","getRunIdsFromUrl","flowId","executionId","stepId","URL_RUN_IDS_PARAM_NAME","split","executionFlowId","_a","exec","getFlowIdFromExecId","clearRunIdsFromUrl","getTokenFromUrl","URL_TOKEN_PARAM_NAME","undefined","clearTokenFromUrl","getCodeFromUrl","URL_CODE_PARAM_NAME","getIsPopupFromUrl","URL_REDIRECT_MODE_PARAM_NAME","getExchangeErrorFromUrl","URL_ERR_PARAM_NAME","clearCodeFromUrl","clearIsPopupFromUrl","clearExchangeErrorFromUrl","getRedirectAuthFromUrl","redirectAuthCodeChallenge","URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME","redirectAuthCallbackUrl","URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME","redirectAuthBackupCallbackUri","URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME","redirectAuthInitiator","URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME","getOIDCIDPParamFromUrl","OIDC_IDP_STATE_ID_PARAM_NAME","clearOIDCIDPParamFromUrl","getSAMLIDPParamFromUrl","SAML_IDP_STATE_ID_PARAM_NAME","clearSAMLIDPParamFromUrl","getSAMLIDPUsernameParamFromUrl","SAML_IDP_USERNAME_PARAM_NAME","clearSAMLIDPUsernameParamFromUrl","getDescopeIDPInitiatedParamFromUrl","DESCOPE_IDP_INITIATED_PARAM_NAME","clearDescopeIDPInitiatedParamFromUrl","getSSOAppIdParamFromUrl","SSO_APP_ID_PARAM_NAME","getThirdPartyAppIdParamFromUrl","THIRD_PARTY_APP_ID_PARAM_NAME","clearSSOAppIdParamFromUrl","clearThirdPartyAppIdParamFromUrl","getThirdPartyAppStateIdParamFromUrl","THIRD_PARTY_APP_STATE_ID_PARAM_NAME","clearThirdPartyAppStateIdParamFromUrl","getApplicationScopesParamFromUrl","APPLICATION_SCOPES_PARAM_NAME","clearApplicationScopesParamFromUrl","getOIDCLoginHintParamFromUrl","OIDC_LOGIN_HINT_PARAM_NAME","clearOIDCLoginHintParamFromUrl","getOIDCPromptParamFromUrl","OIDC_PROMPT_PARAM_NAME","clearOIDCPromptParamFromUrl","getOIDCErrorRedirectUriParamFromUrl","OIDC_ERROR_REDIRECT_URI_PARAM_NAME","clearOIDCErrorRedirectUriParamFromUrl","s","replace","x","toUpperCase","document","querySelectorAll","forEach","ele","remove","state","prevState","attrName","url","returnType","res","fetch","cache","ok","Error","status","body","headers","Object","fromEntries","entries","currentIdxStr","prevIdxStr","currentIdx","prevIdx","Number","isNaN","Direction","forward","backward","brands","navigator","userAgentData","found","find","brand","version","parseFloat","projectId","filename","assetsFolder","ASSETS_FOLDER","baseUrl","OVERRIDE_CONTENT_URL","BASE_CONTENT_URL","pathname","paths","join","pathJoin","Array","from","attributes","reduce","acc","attr","descopeAttrName","RegExp","DESCOPE_ATTRIBUTE_PREFIX","name","assign","value","obj","keys","firstNonEmptyKey","key","scriptId","resultKey","path","SDK_SCRIPT_RESULTS_KEY","locale","toLowerCase","fallback","nl","language","includes","autoFocus","isFirstScreen","firstVisibleInput","querySelector","setTimeout","focus","rootEle","addEventListener","onBlur","origFocus","reportValidity","call","getAttribute","length","ref","timer","onClick","e","target","clearTimeout","removeEventListener","once","logger","debug","ssoQueryParams","token","code","isPopup","exchangeError","oidcIdpStateId","samlIdpStateId","samlIdpUsername","descopeIdpInitiated","ssoAppId","thirdPartyAppId","thirdPartyAppStateId","applicationScopes","oidcLoginHint","oidcPrompt","oidcErrorRedirectUri","samlResponse","relayState","submitCallback","formEle","createElement","method","action","innerHTML","appendChild","test","userAgent","vendor","func","wait","timeout","args","apply","this","title","w","h","dualScreenLeft","screenLeft","screen","left","dualScreenTop","screenTop","top","innerWidth","documentElement","clientWidth","width","innerHeight","clientHeight","height","popup","open","compName","startScreenId","submit","promise","Promise","resolve","reject","expired","then","catch","error","inputs","inboundAppApproveScopes","thirdPartyAppApproveScopes","sanitizedState","screenState","predicate","_","EXCLUDED_STATE_KEYS","startsWith","filter","errorText","errorType","text","type","_c","_b","componentsConfig","data","fn","prevArgs","array2","array1","every","index","reset"],"mappings":"gLAqCA,MAAMA,EAAgB,CAAC,yBAEvB,SAASC,EAAYC,GAGnB,OAFkB,IAAIC,gBAAgBC,OAAOC,SAASC,QAErCC,IAAIL,EACvB,CAgBA,SAASM,EAAcN,GACrB,GAAIE,OAAOK,QAAQC,cAAgBT,EAAYC,GAAY,CACzD,MAAMS,EAAS,IAAIC,IAAIR,OAAOC,SAASQ,MACjCP,EAAS,IAAIH,gBAAgBQ,EAAOL,QAC1CA,EAAOQ,OAAOZ,GACdS,EAAOL,OAASA,EAAOS,WACvBX,OAAOK,QAAQC,aAAa,CAAA,EAAI,GAAIC,EAAOI,WAC5C,CACH,CA2Da,MAAAC,EAAoBC,IAC/B,IAAKC,EAAc,GAAIC,EAAS,KAjFzBlB,EAAYmB,EAAAA,yBAiFyC,IAAIC,MAAM,KACtE,MAAMC,EA3DoB,CAACJ,UAE3B,OAAiC,QAA1BK,EADO,cACDC,KAAKN,UAAe,IAAAK,OAAA,EAAAA,EAAA,KAAM,EAAE,EAyDjBE,CAAoBP,GAQ5C,QALKD,GAAWK,GAAmBA,IAAoBL,KACrDC,EAAc,GACdC,EAAS,IAGJ,CAAED,cAAaC,SAAQG,kBAAiB,WAajCI,IACdlB,EAAcY,EAAsBA,uBACtC,UAEgBO,IACd,OAAO1B,EAAY2B,8BAAyBC,CAC9C,UAEgBC,IACdtB,EAAcoB,EAAoBA,qBACpC,UAEgBG,IACd,OAAO9B,EAAY+B,6BAAwBH,CAC7C,UAEgBI,IACd,MAAqD,UAA9ChC,EAAYiC,+BACrB,UAEgBC,IACd,OAAOlC,EAAYmC,4BAAuBP,CAC5C,UAEgBQ,IACd7B,EAAcwB,EAAmBA,oBACnC,UAEgBM,IACd9B,EAAc0B,EAA4BA,6BAC5C,UAEgBK,IACd/B,EAAc4B,EAAkBA,mBAClC,UAEgBI,IAad,MAAO,CACLC,0BAbgCxC,EAChC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,QACZ,IAAIuE,KACF,OAAIoD,IAT4BC,EASQrD,GATvBsD,EASaF,GAR3B9F,SAAW+F,EAAO/F,QACzBgG,EAAOC,OAAM,CAAC7H,EAAY8H,IAAkB9H,IAAU2H,EAAOG,QASzDJ,EAAWpD,EACXtH,EAAQyK,KAAMnD,IAHwCtH,EATtC,IAAC4K,EAAeD,CAcf,GAEnB,CACEI,MAAO,KACLL,OAAW/O,EACXqE,OAAQrE,CAAS,GAGtB"}
|
|
1
|
+
{"version":3,"file":"helpers.js","sources":["../../../src/lib/helpers/helpers.ts"],"sourcesContent":["import {\n ASSETS_FOLDER,\n BASE_CONTENT_URL,\n DESCOPE_ATTRIBUTE_PREFIX,\n URL_CODE_PARAM_NAME,\n URL_ERR_PARAM_NAME,\n URL_RUN_IDS_PARAM_NAME,\n URL_TOKEN_PARAM_NAME,\n URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME,\n URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME,\n URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME,\n URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME,\n OIDC_IDP_STATE_ID_PARAM_NAME,\n SAML_IDP_STATE_ID_PARAM_NAME,\n SAML_IDP_USERNAME_PARAM_NAME,\n SSO_APP_ID_PARAM_NAME,\n OIDC_LOGIN_HINT_PARAM_NAME,\n DESCOPE_IDP_INITIATED_PARAM_NAME,\n OVERRIDE_CONTENT_URL,\n OIDC_PROMPT_PARAM_NAME,\n OIDC_RESOURCE_PARAM_NAME,\n OIDC_ERROR_REDIRECT_URI_PARAM_NAME,\n THIRD_PARTY_APP_ID_PARAM_NAME,\n THIRD_PARTY_APP_STATE_ID_PARAM_NAME,\n APPLICATION_SCOPES_PARAM_NAME,\n SDK_SCRIPT_RESULTS_KEY,\n URL_REDIRECT_MODE_PARAM_NAME,\n} from '../constants';\nimport { EXCLUDED_STATE_KEYS } from '../constants/customScreens';\nimport {\n AutoFocusOptions,\n CustomScreenState,\n Direction,\n Locale,\n SSOQueryParams,\n StepState,\n} from '../types';\n\nconst MD_COMPONENTS = ['descope-enriched-text'];\n\nfunction getUrlParam(paramName: string) {\n const urlParams = new URLSearchParams(window.location.search);\n\n return urlParams.get(paramName);\n}\n\nfunction getFlowUrlParam() {\n return getUrlParam(URL_RUN_IDS_PARAM_NAME);\n}\n\nfunction setFlowUrlParam(id: string) {\n if (window.history.pushState && id !== getFlowUrlParam()) {\n const newUrl = new URL(window.location.href);\n const search = new URLSearchParams(newUrl.search);\n search.set(URL_RUN_IDS_PARAM_NAME, id);\n newUrl.search = search.toString();\n window.history.pushState({}, '', newUrl.toString());\n }\n}\n\nfunction resetUrlParam(paramName: string) {\n if (window.history.replaceState && getUrlParam(paramName)) {\n const newUrl = new URL(window.location.href);\n const search = new URLSearchParams(newUrl.search);\n search.delete(paramName);\n newUrl.search = search.toString();\n window.history.replaceState({}, '', newUrl.toString());\n }\n}\n\nconst getFlowIdFromExecId = (executionId: string) => {\n const regex = /(.*)\\|#\\|.*/;\n return regex.exec(executionId)?.[1] || '';\n};\n\nexport async function fetchContent<T extends 'text' | 'json'>(\n url: string,\n returnType: T,\n): Promise<{\n body: T extends 'json' ? Record<string, any> : string;\n headers: Record<string, string>;\n}> {\n const res = await fetch(url, { cache: 'default' });\n if (!res.ok) {\n throw Error(`Error fetching URL ${url} [${res.status}]`);\n }\n\n return {\n body: await res[returnType || 'text'](),\n headers: Object.fromEntries(res.headers.entries()),\n };\n}\n\nconst pathJoin = (...paths: string[]) => paths.join('/').replace(/\\/+/g, '/'); // preventing duplicate separators\n\nexport function getContentUrl({\n projectId,\n filename,\n assetsFolder = ASSETS_FOLDER,\n baseUrl,\n}: {\n projectId: string;\n filename: string;\n assetsFolder?: string;\n baseUrl?: string;\n}) {\n const url = new URL(OVERRIDE_CONTENT_URL || baseUrl || BASE_CONTENT_URL);\n url.pathname = pathJoin(url.pathname, projectId, assetsFolder, filename);\n\n return url.toString();\n}\n\nexport function getAnimationDirection(\n currentIdxStr: string,\n prevIdxStr: string,\n) {\n if (!prevIdxStr) return undefined;\n\n const currentIdx = +currentIdxStr;\n const prevIdx = +prevIdxStr;\n\n if (Number.isNaN(currentIdx) || Number.isNaN(prevIdx)) return undefined;\n if (currentIdx > prevIdx) return Direction.forward;\n if (currentIdx < prevIdx) return Direction.backward;\n return undefined;\n}\n\nexport const getRunIdsFromUrl = (flowId: string) => {\n let [executionId = '', stepId = ''] = (getFlowUrlParam() || '').split('_');\n const executionFlowId = getFlowIdFromExecId(executionId);\n\n // if the flow id does not match, this execution id is not for this flow\n if (!flowId || (executionFlowId && executionFlowId !== flowId)) {\n executionId = '';\n stepId = '';\n }\n\n return { executionId, stepId, executionFlowId };\n};\n\nexport const setRunIdsOnUrl = (executionId: string, stepId: string) => {\n setFlowUrlParam([executionId, stepId].join('_'));\n};\n\nexport function isChromium() {\n return (\n /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)\n );\n}\n\nexport function clearRunIdsFromUrl() {\n resetUrlParam(URL_RUN_IDS_PARAM_NAME);\n}\n\nexport function getTokenFromUrl() {\n return getUrlParam(URL_TOKEN_PARAM_NAME) || undefined;\n}\n\nexport function clearTokenFromUrl() {\n resetUrlParam(URL_TOKEN_PARAM_NAME);\n}\n\nexport function getCodeFromUrl() {\n return getUrlParam(URL_CODE_PARAM_NAME) || undefined;\n}\n\nexport function getIsPopupFromUrl() {\n return getUrlParam(URL_REDIRECT_MODE_PARAM_NAME) === 'popup';\n}\n\nexport function getExchangeErrorFromUrl() {\n return getUrlParam(URL_ERR_PARAM_NAME) || undefined;\n}\n\nexport function clearCodeFromUrl() {\n resetUrlParam(URL_CODE_PARAM_NAME);\n}\n\nexport function clearIsPopupFromUrl() {\n resetUrlParam(URL_REDIRECT_MODE_PARAM_NAME);\n}\n\nexport function clearExchangeErrorFromUrl() {\n resetUrlParam(URL_ERR_PARAM_NAME);\n}\n\nexport function getRedirectAuthFromUrl() {\n const redirectAuthCodeChallenge = getUrlParam(\n URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME,\n );\n const redirectAuthCallbackUrl = getUrlParam(\n URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME,\n );\n const redirectAuthBackupCallbackUri = getUrlParam(\n URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME,\n );\n const redirectAuthInitiator = getUrlParam(\n URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME,\n );\n return {\n redirectAuthCodeChallenge,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthInitiator,\n };\n}\n\nexport function getOIDCIDPParamFromUrl() {\n return getUrlParam(OIDC_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function clearOIDCIDPParamFromUrl() {\n resetUrlParam(OIDC_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function getSAMLIDPParamFromUrl() {\n return getUrlParam(SAML_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function clearSAMLIDPParamFromUrl() {\n resetUrlParam(SAML_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function getSAMLIDPUsernameParamFromUrl() {\n return getUrlParam(SAML_IDP_USERNAME_PARAM_NAME);\n}\n\nexport function clearSAMLIDPUsernameParamFromUrl() {\n resetUrlParam(SAML_IDP_USERNAME_PARAM_NAME);\n}\n\nexport function getDescopeIDPInitiatedParamFromUrl() {\n return getUrlParam(DESCOPE_IDP_INITIATED_PARAM_NAME);\n}\n\nexport function clearDescopeIDPInitiatedParamFromUrl() {\n resetUrlParam(DESCOPE_IDP_INITIATED_PARAM_NAME);\n}\n\nexport function getSSOAppIdParamFromUrl() {\n return getUrlParam(SSO_APP_ID_PARAM_NAME);\n}\n\nexport function getThirdPartyAppIdParamFromUrl() {\n return getUrlParam(THIRD_PARTY_APP_ID_PARAM_NAME);\n}\n\nexport function clearSSOAppIdParamFromUrl() {\n resetUrlParam(SSO_APP_ID_PARAM_NAME);\n}\n\nexport function clearThirdPartyAppIdParamFromUrl() {\n resetUrlParam(THIRD_PARTY_APP_ID_PARAM_NAME);\n}\n\nexport function getThirdPartyAppStateIdParamFromUrl() {\n return getUrlParam(THIRD_PARTY_APP_STATE_ID_PARAM_NAME);\n}\n\nexport function clearThirdPartyAppStateIdParamFromUrl() {\n resetUrlParam(THIRD_PARTY_APP_STATE_ID_PARAM_NAME);\n}\n\nexport function getApplicationScopesParamFromUrl() {\n return getUrlParam(APPLICATION_SCOPES_PARAM_NAME);\n}\n\nexport function clearApplicationScopesParamFromUrl() {\n resetUrlParam(APPLICATION_SCOPES_PARAM_NAME);\n}\n\nexport function getOIDCLoginHintParamFromUrl() {\n return getUrlParam(OIDC_LOGIN_HINT_PARAM_NAME);\n}\n\nexport function clearOIDCLoginHintParamFromUrl() {\n resetUrlParam(OIDC_LOGIN_HINT_PARAM_NAME);\n}\n\nexport function getOIDCPromptParamFromUrl() {\n return getUrlParam(OIDC_PROMPT_PARAM_NAME);\n}\n\nexport function clearOIDCPromptParamFromUrl() {\n resetUrlParam(OIDC_PROMPT_PARAM_NAME);\n}\n\nexport function getOIDCErrorRedirectUriParamFromUrl() {\n return getUrlParam(OIDC_ERROR_REDIRECT_URI_PARAM_NAME);\n}\n\nexport function clearOIDCErrorRedirectUriParamFromUrl() {\n resetUrlParam(OIDC_ERROR_REDIRECT_URI_PARAM_NAME);\n}\n\nexport function getOIDCResourceParamFromUrl() {\n return getUrlParam(OIDC_RESOURCE_PARAM_NAME);\n}\n\nexport function clearOIDCResourceParamFromUrl() {\n resetUrlParam(OIDC_RESOURCE_PARAM_NAME);\n}\n\nexport const camelCase = (s: string) =>\n s.replace(/-./g, (x) => x[1].toUpperCase());\n\nexport const createIsChanged =\n <T extends Record<string, any>>(state: T, prevState: T) =>\n (attrName: keyof T) =>\n state[attrName] !== prevState[attrName];\n\nexport const getElementDescopeAttributes = (ele: HTMLElement) =>\n Array.from(ele?.attributes || []).reduce((acc, attr) => {\n const descopeAttrName = new RegExp(\n `^${DESCOPE_ATTRIBUTE_PREFIX}(\\\\S+)$`,\n ).exec(attr.name)?.[1];\n\n return !descopeAttrName\n ? acc\n : Object.assign(acc, { [descopeAttrName]: attr.value });\n }, {});\n\nexport const getFlowConfig = (config: Record<string, any>, flowId: string) =>\n config?.flows?.[flowId] || {};\n\nexport const handleUrlParams = (\n flowId: string,\n logger: { debug: (...data: any[]) => void },\n) => {\n const { executionId, stepId, executionFlowId } = getRunIdsFromUrl(flowId);\n\n // if the flow id does not match, we do not want to read & remove any query params\n // because it's probably belongs to another flow\n if (executionFlowId && flowId !== executionFlowId) {\n logger.debug(\n 'Flow id does not match the execution flow id, skipping url params handling',\n );\n return { ssoQueryParams: {} };\n }\n\n if (executionId || stepId) {\n clearRunIdsFromUrl();\n }\n\n const token = getTokenFromUrl();\n if (token) {\n clearTokenFromUrl();\n }\n\n const code = getCodeFromUrl();\n if (code) {\n clearCodeFromUrl();\n }\n\n // this is used for oauth when we want to open the provider login page in a new tab\n const isPopup = getIsPopupFromUrl();\n if (isPopup) {\n clearIsPopupFromUrl();\n }\n\n const exchangeError = getExchangeErrorFromUrl();\n if (exchangeError) {\n clearExchangeErrorFromUrl();\n }\n\n // these query params are retained to allow the flow to be refreshed\n // without losing the redirect auth state\n const {\n redirectAuthCodeChallenge,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthInitiator,\n } = getRedirectAuthFromUrl();\n\n const oidcIdpStateId = getOIDCIDPParamFromUrl();\n if (oidcIdpStateId) {\n clearOIDCIDPParamFromUrl();\n }\n\n const samlIdpStateId = getSAMLIDPParamFromUrl();\n if (samlIdpStateId) {\n clearSAMLIDPParamFromUrl();\n }\n\n const samlIdpUsername = getSAMLIDPUsernameParamFromUrl();\n if (samlIdpStateId) {\n clearSAMLIDPUsernameParamFromUrl();\n }\n\n const descopeIdpInitiated = getDescopeIDPInitiatedParamFromUrl();\n if (descopeIdpInitiated) {\n clearDescopeIDPInitiatedParamFromUrl();\n }\n\n const ssoAppId = getSSOAppIdParamFromUrl();\n if (ssoAppId) {\n clearSSOAppIdParamFromUrl();\n }\n\n const thirdPartyAppId = getThirdPartyAppIdParamFromUrl();\n if (thirdPartyAppId) {\n clearThirdPartyAppIdParamFromUrl();\n }\n\n const thirdPartyAppStateId = getThirdPartyAppStateIdParamFromUrl();\n if (thirdPartyAppStateId) {\n clearThirdPartyAppStateIdParamFromUrl();\n }\n\n const applicationScopes = getApplicationScopesParamFromUrl();\n if (applicationScopes) {\n clearApplicationScopesParamFromUrl();\n }\n\n const oidcLoginHint = getOIDCLoginHintParamFromUrl();\n if (oidcLoginHint) {\n clearOIDCLoginHintParamFromUrl();\n }\n\n const oidcPrompt = getOIDCPromptParamFromUrl();\n if (oidcPrompt) {\n clearOIDCPromptParamFromUrl();\n }\n\n const oidcErrorRedirectUri = getOIDCErrorRedirectUriParamFromUrl();\n if (oidcErrorRedirectUri) {\n clearOIDCErrorRedirectUriParamFromUrl();\n }\n\n const oidcResource = getOIDCResourceParamFromUrl();\n if (oidcResource) {\n clearOIDCResourceParamFromUrl();\n }\n\n const idpInitiatedVal = descopeIdpInitiated === 'true';\n\n return {\n executionId,\n stepId,\n token,\n code,\n isPopup,\n exchangeError,\n redirectAuthCodeChallenge,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthInitiator,\n ssoQueryParams: {\n oidcIdpStateId,\n samlIdpStateId,\n samlIdpUsername,\n descopeIdpInitiated: idpInitiatedVal,\n ssoAppId,\n oidcLoginHint,\n oidcPrompt,\n oidcErrorRedirectUri,\n oidcResource,\n thirdPartyAppId,\n thirdPartyAppStateId,\n applicationScopes,\n },\n };\n};\n\nexport const loadFont = (url: string) => {\n if (!url) return;\n\n const font = document.createElement('link');\n font.href = url;\n font.rel = 'stylesheet';\n document.head.appendChild(font);\n};\n\nconst compareArrays = (array1: any[], array2: any[]) =>\n array1.length === array2.length &&\n array1.every((value: any, index: number) => value === array2[index]);\n\nexport const withMemCache = <I extends any[], O>(fn: (...args: I) => O) => {\n let prevArgs: any[];\n let cache: any;\n return Object.assign(\n (...args: I) => {\n if (prevArgs && compareArrays(prevArgs, args)) return cache as O;\n\n prevArgs = args;\n cache = fn(...args);\n\n return cache as O;\n },\n {\n reset: () => {\n prevArgs = undefined;\n cache = undefined;\n },\n },\n );\n};\n\nexport const handleAutoFocus = (\n ele: HTMLElement,\n autoFocus: AutoFocusOptions,\n isFirstScreen: boolean,\n) => {\n if (\n autoFocus === true ||\n (autoFocus === 'skipFirstScreen' && !isFirstScreen)\n ) {\n // focus the first visible input\n const firstVisibleInput: HTMLInputElement = ele.querySelector('*[name]');\n setTimeout(() => {\n firstVisibleInput?.focus();\n });\n }\n};\n\nexport const handleReportValidityOnBlur = (rootEle: HTMLElement) => {\n rootEle.querySelectorAll('*[name]').forEach((ele: HTMLInputElement) => {\n ele.addEventListener('blur', () => {\n const onBlur = () => {\n // reportValidity also focus the element if it's invalid\n // in order to prevent this we need to override the focus method\n const origFocus = ele.focus;\n // eslint-disable-next-line no-param-reassign\n ele.focus = () => {};\n ele.reportValidity?.();\n setTimeout(() => {\n // eslint-disable-next-line no-param-reassign\n ele.focus = origFocus;\n });\n };\n\n const isInputAlreadyInErrorState = ele.getAttribute('invalid') === 'true';\n\n if (isInputAlreadyInErrorState || ele.value?.length) {\n onBlur();\n return;\n }\n\n // If the input is not in an error state, has no value, and a `formnovalidate` button was clicked,\n // we want to prevent triggering validation.\n // This handles a case where a required input was focused, and the user then clicked a social login button —\n // in that case, we don't want the required error message to flash for a split second.\n const ref = { timer: undefined };\n\n const onClick = (e: MouseEvent) => {\n const target = e.target as HTMLElement;\n\n if (target.getAttribute('formnovalidate') === 'true') {\n clearTimeout(ref.timer);\n ref.timer = undefined;\n }\n };\n\n ref.timer = setTimeout(() => {\n rootEle.removeEventListener('click', onClick);\n onBlur();\n ref.timer = undefined;\n }, 150);\n\n rootEle.addEventListener('click', onClick, { once: true });\n });\n });\n};\n\n/**\n * To return a fallback value in case the timeout expires and the promise\n * isn't fulfilled:\n *\n * const promise = loadUserCount();\n * const count = await timeoutPromise(2000, promise, 0);\n *\n * Or without a fallback value to just throw an error if the timeout expires:\n *\n * try {\n * count = await timeoutPromise(2000, promise);\n * }\n *\n * Fallback is returned only in case of timeout, so if the passed promise rejects\n * the fallback value is not used, and the returned promise will throw as well.\n */\nexport function timeoutPromise<T>(\n timeout: number,\n promise: Promise<T>,\n fallback?: T,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n let expired = false;\n const timer = setTimeout(() => {\n expired = true;\n if (fallback !== undefined) {\n resolve(fallback);\n } else {\n reject(new Error(`Promise timed out after ${timeout} ms`));\n }\n }, timeout);\n\n promise\n .then((value) => {\n if (!expired) {\n clearTimeout(timer);\n resolve(value);\n }\n })\n .catch((error) => {\n if (!expired) {\n clearTimeout(timer);\n reject(error);\n }\n });\n });\n}\n\nexport const getChromiumVersion = (): number => {\n const brands = (navigator as any)?.userAgentData?.brands;\n const found = brands?.find(\n ({ brand, version }) => brand === 'Chromium' && parseFloat(version),\n );\n return found ? found.version : 0;\n};\n\n// As an optimization - We can show first screen if we have startScreenId and we don't have any other of the ssoAppId/oidcIdpStateId/samlIdp params\n// - If there startScreenId it means that the sdk can show the first screen and we don't need to wait for the sdk to return the first screen\n// - If there is any one else of the other params (like oidcIdpStateId, ..) - we can't skip this call because descope may decide not to show the first screen (in cases like a user is already logged in)\nexport const showFirstScreenOnExecutionInit = (\n startScreenId: string,\n {\n oidcIdpStateId,\n samlIdpStateId,\n samlIdpUsername,\n ssoAppId,\n oidcLoginHint,\n oidcPrompt,\n oidcErrorRedirectUri,\n oidcResource,\n thirdPartyAppId,\n thirdPartyAppStateId,\n applicationScopes,\n }: SSOQueryParams,\n): boolean =>\n !!startScreenId &&\n !oidcIdpStateId &&\n !samlIdpStateId &&\n !samlIdpUsername &&\n !ssoAppId &&\n !oidcLoginHint &&\n !oidcPrompt &&\n !oidcErrorRedirectUri &&\n !oidcResource &&\n !thirdPartyAppId &&\n !thirdPartyAppStateId &&\n !applicationScopes;\n\nexport const injectSamlIdpForm = (\n url: string,\n samlResponse: string,\n relayState: string,\n submitCallback: (form: HTMLFormElement) => void,\n) => {\n const formEle = document.createElement('form');\n formEle.method = 'POST';\n formEle.action = url;\n formEle.innerHTML = `\n <input type=\"hidden\" role=\"saml-response\" name=\"SAMLResponse\" value=\"${samlResponse}\" />\n <input type=\"hidden\" role=\"saml-relay-state\" name=\"RelayState\" value=\"${relayState}\" />\n <input style=\"display: none;\" id=\"SAMLSubmitButton\" type=\"submit\" value=\"Continue\" />\n `;\n\n document.body.appendChild(formEle);\n\n submitCallback(formEle);\n};\n\nexport const submitForm = (formEle: HTMLFormElement) => formEle?.submit();\n\nexport const getFirstNonEmptyValue = (obj: object, keys: string[]) => {\n const firstNonEmptyKey = keys.find((key) => obj[key]);\n return firstNonEmptyKey ? obj[firstNonEmptyKey] : null;\n};\n\nexport const leadingDebounce = <T extends (...args: any[]) => void>(\n func: T,\n wait = 100,\n) => {\n let timeout: NodeJS.Timeout;\n return function executedFunction(...args) {\n if (!timeout) func.apply(this, args);\n clearTimeout(timeout);\n timeout = setTimeout(() => {\n timeout = null;\n }, wait);\n } as T;\n};\n\nexport function getUserLocale(locale: string): Locale {\n if (locale) {\n return { locale: locale.toLowerCase(), fallback: locale.toLowerCase() };\n }\n const nl = navigator.language;\n if (!nl) {\n return { locale: '', fallback: '' };\n }\n\n if (nl.includes('-')) {\n return {\n locale: nl.toLowerCase(),\n fallback: nl.split('-')[0].toLowerCase(),\n };\n }\n\n return { locale: nl.toLowerCase(), fallback: nl.toLowerCase() };\n}\n\nexport const clearPreviousExternalInputs = () => {\n document\n .querySelectorAll('[data-hidden-input=\"true\"]')\n .forEach((ele) => ele.remove());\n};\n\nexport const shouldHandleMarkdown = (compName: string) =>\n MD_COMPONENTS.includes(compName);\n\nconst omitBy = <T extends Record<string, any>>(\n obj: T,\n predicate: (value: any, key: keyof T) => boolean,\n): T =>\n Object.fromEntries(\n Object.entries(obj).filter(\n ([key, value]) => !predicate(value, key as keyof T),\n ),\n ) as T;\n\nexport const transformStepStateForCustomScreen = (\n state: Partial<StepState>,\n) => {\n const sanitizedState: CustomScreenState = omitBy(\n state.screenState,\n (_, key) => EXCLUDED_STATE_KEYS.includes(key) || key.startsWith('_'),\n );\n\n const {\n screenState: { errorText, errorType },\n } = state;\n\n if (errorText || errorType) {\n sanitizedState.error = { text: errorText, type: errorType };\n }\n\n if (state.action) {\n sanitizedState.action = state.action;\n }\n\n if (state.screenState?.componentsConfig?.thirdPartyAppApproveScopes?.data) {\n sanitizedState.inboundAppApproveScopes =\n state.screenState.componentsConfig.thirdPartyAppApproveScopes.data;\n }\n\n return sanitizedState;\n};\n\nexport const transformScreenInputs = (inputs: Record<string, any>) => {\n const res = { ...inputs };\n\n if (inputs.inboundAppApproveScopes) {\n res.thirdPartyAppApproveScopes = inputs.inboundAppApproveScopes;\n }\n\n return res;\n};\n\nexport function getScriptResultPath(scriptId: string, resultKey?: string) {\n const path = resultKey ? `${scriptId}_${resultKey}` : scriptId;\n return `${SDK_SCRIPT_RESULTS_KEY}.${path}`;\n}\n\nexport const openCenteredPopup = (\n url: string,\n title: string,\n w: number,\n h: number,\n) => {\n const dualScreenLeft =\n window.screenLeft !== undefined\n ? window.screenLeft\n : (window.screen as any).left;\n const dualScreenTop =\n window.screenTop !== undefined\n ? window.screenTop\n : (window.screen as any).top;\n\n const width =\n window.innerWidth ||\n document.documentElement.clientWidth ||\n window.screen.width;\n const height =\n window.innerHeight ||\n document.documentElement.clientHeight ||\n window.screen.height;\n\n const left = (width - w) / 2 + dualScreenLeft;\n const top = (height - h) / 2 + dualScreenTop;\n\n const popup = window.open(\n url,\n title,\n `width=${w},height=${h},top=${top},left=${left},scrollbars=yes,resizable=yes`,\n );\n\n popup.focus();\n\n return popup;\n};\n"],"names":["MD_COMPONENTS","getUrlParam","paramName","URLSearchParams","window","location","search","get","resetUrlParam","history","replaceState","newUrl","URL","href","delete","toString","getRunIdsFromUrl","flowId","executionId","stepId","URL_RUN_IDS_PARAM_NAME","split","executionFlowId","_a","exec","getFlowIdFromExecId","clearRunIdsFromUrl","getTokenFromUrl","URL_TOKEN_PARAM_NAME","undefined","clearTokenFromUrl","getCodeFromUrl","URL_CODE_PARAM_NAME","getIsPopupFromUrl","URL_REDIRECT_MODE_PARAM_NAME","getExchangeErrorFromUrl","URL_ERR_PARAM_NAME","clearCodeFromUrl","clearIsPopupFromUrl","clearExchangeErrorFromUrl","getRedirectAuthFromUrl","redirectAuthCodeChallenge","URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME","redirectAuthCallbackUrl","URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME","redirectAuthBackupCallbackUri","URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME","redirectAuthInitiator","URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME","getOIDCIDPParamFromUrl","OIDC_IDP_STATE_ID_PARAM_NAME","clearOIDCIDPParamFromUrl","getSAMLIDPParamFromUrl","SAML_IDP_STATE_ID_PARAM_NAME","clearSAMLIDPParamFromUrl","getSAMLIDPUsernameParamFromUrl","SAML_IDP_USERNAME_PARAM_NAME","clearSAMLIDPUsernameParamFromUrl","getDescopeIDPInitiatedParamFromUrl","DESCOPE_IDP_INITIATED_PARAM_NAME","clearDescopeIDPInitiatedParamFromUrl","getSSOAppIdParamFromUrl","SSO_APP_ID_PARAM_NAME","getThirdPartyAppIdParamFromUrl","THIRD_PARTY_APP_ID_PARAM_NAME","clearSSOAppIdParamFromUrl","clearThirdPartyAppIdParamFromUrl","getThirdPartyAppStateIdParamFromUrl","THIRD_PARTY_APP_STATE_ID_PARAM_NAME","clearThirdPartyAppStateIdParamFromUrl","getApplicationScopesParamFromUrl","APPLICATION_SCOPES_PARAM_NAME","clearApplicationScopesParamFromUrl","getOIDCLoginHintParamFromUrl","OIDC_LOGIN_HINT_PARAM_NAME","clearOIDCLoginHintParamFromUrl","getOIDCPromptParamFromUrl","OIDC_PROMPT_PARAM_NAME","clearOIDCPromptParamFromUrl","getOIDCErrorRedirectUriParamFromUrl","OIDC_ERROR_REDIRECT_URI_PARAM_NAME","clearOIDCErrorRedirectUriParamFromUrl","getOIDCResourceParamFromUrl","OIDC_RESOURCE_PARAM_NAME","clearOIDCResourceParamFromUrl","s","replace","x","toUpperCase","document","querySelectorAll","forEach","ele","remove","state","prevState","attrName","url","returnType","res","fetch","cache","ok","Error","status","body","headers","Object","fromEntries","entries","currentIdxStr","prevIdxStr","currentIdx","prevIdx","Number","isNaN","Direction","forward","backward","brands","navigator","userAgentData","found","find","brand","version","parseFloat","projectId","filename","assetsFolder","ASSETS_FOLDER","baseUrl","OVERRIDE_CONTENT_URL","BASE_CONTENT_URL","pathname","paths","join","pathJoin","Array","from","attributes","reduce","acc","attr","descopeAttrName","RegExp","DESCOPE_ATTRIBUTE_PREFIX","name","assign","value","obj","keys","firstNonEmptyKey","key","scriptId","resultKey","path","SDK_SCRIPT_RESULTS_KEY","locale","toLowerCase","fallback","nl","language","includes","autoFocus","isFirstScreen","firstVisibleInput","querySelector","setTimeout","focus","rootEle","addEventListener","onBlur","origFocus","reportValidity","call","getAttribute","length","ref","timer","onClick","e","target","clearTimeout","removeEventListener","once","logger","debug","ssoQueryParams","token","code","isPopup","exchangeError","oidcIdpStateId","samlIdpStateId","samlIdpUsername","descopeIdpInitiated","ssoAppId","thirdPartyAppId","thirdPartyAppStateId","applicationScopes","oidcLoginHint","oidcPrompt","oidcErrorRedirectUri","oidcResource","samlResponse","relayState","submitCallback","formEle","createElement","method","action","innerHTML","appendChild","test","userAgent","vendor","func","wait","timeout","args","apply","this","title","w","h","dualScreenLeft","screenLeft","screen","left","dualScreenTop","screenTop","top","innerWidth","documentElement","clientWidth","width","innerHeight","clientHeight","height","popup","open","compName","startScreenId","submit","promise","Promise","resolve","reject","expired","then","catch","error","inputs","inboundAppApproveScopes","thirdPartyAppApproveScopes","sanitizedState","screenState","predicate","_","EXCLUDED_STATE_KEYS","startsWith","filter","errorText","errorType","text","type","_c","_b","componentsConfig","data","fn","prevArg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,YAAYY,iBAAiBd,2BAA2Be,MAG3Dd,CAAc,uBAvR0Be,IAC/C,IAAIC,EACA3K,EACJ,OAAOM,OAAOyC,QACZ,IAAIwE,KACF,OAAIoD,IAT4BC,EASQrD,GATvBsD,EASaF,GAR3B/F,SAAWgG,EAAOhG,QACzBiG,EAAOC,OAAM,CAAC9H,EAAY+H,IAAkB/H,IAAU4H,EAAOG,QASzDJ,EAAWpD,EACXvH,EAAQ0K,KAAMnD,IAHwCvH,EATtC,IAAC6K,EAAeD,CAcf,GAEnB,CACEI,MAAO,KACLL,OAAWnP,EACXwE,OAAQxE,CAAS,GAGtB"}
|
package/dist/cjs/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sources":["../../src/lib/types.ts"],"sourcesContent":["/* istanbul ignore file */\n\nimport createSdk from '@descope/web-js-sdk';\n\nexport type SdkConfig = Parameters<typeof createSdk>[0];\nexport type Sdk = ReturnType<typeof createSdk>;\n\nexport type SdkFlowNext = Sdk['flow']['next'];\n\nexport type ComponentsDynamicAttrs = {\n attributes: Record<string, any>;\n};\n\nexport type ComponentsConfig = Record<string, any> & {\n componentsDynamicAttrs?: Record<string, ComponentsDynamicAttrs>;\n};\nexport type CssVars = Record<string, any>;\n\ntype KeepArgsByIndex<F, Indices extends readonly number[]> = F extends (\n ...args: infer A\n) => infer R\n ? (...args: PickArgsByIndex<A, Indices>) => R\n : never;\n\ntype PickArgsByIndex<\n All extends readonly any[],\n Indices extends readonly number[],\n> = {\n [K in keyof Indices]: Indices[K] extends keyof All ? All[Indices[K]] : never;\n};\n\ntype Project = {\n name: string;\n};\n\nexport enum Direction {\n backward = 'backward',\n forward = 'forward',\n}\n\nexport interface LastAuthState {\n loginId?: string;\n name?: string;\n}\n\nexport interface ScreenState {\n errorText?: string;\n errorType?: string;\n componentsConfig?: ComponentsConfig;\n cssVars?: CssVars;\n form?: Record<string, string>;\n inputs?: Record<string, string>; // Backward compatibility\n lastAuth?: LastAuthState;\n project?: Project;\n totp?: { image?: string; provisionUrl?: string };\n notp?: { image?: string; redirectUrl?: string };\n selfProvisionDomains?: unknown;\n user?: unknown;\n sso?: unknown;\n dynamicSelects?: unknown;\n keysInUse?: unknown;\n genericForm?: unknown;\n linkId?: unknown;\n sentTo?: unknown;\n clientScripts?: ClientScript[];\n}\n\nexport type SSOQueryParams = {\n oidcIdpStateId?: string;\n samlIdpStateId?: string;\n samlIdpUsername?: string;\n descopeIdpInitiated?: boolean;\n ssoAppId?: string;\n thirdPartyAppId: string;\n thirdPartyAppStateId?: string;\n applicationScopes?: string;\n} & OIDCOptions;\n\nexport type OIDCOptions = {\n oidcLoginHint?: string;\n oidcPrompt?: string;\n oidcErrorRedirectUri?: string;\n};\n\nexport type Locale = {\n locale: string;\n fallback: string;\n};\n\nexport type FlowState = {\n flowId: string;\n projectId: string;\n baseUrl: string;\n tenant: string;\n stepId: string;\n stepName: string;\n executionId: string;\n action: string;\n redirectTo: string;\n redirectIsPopup: boolean;\n openInNewTabUrl?: string;\n redirectUrl: string;\n screenId: string;\n screenState: ScreenState;\n token: string;\n code: string;\n isPopup: boolean;\n exchangeError: string;\n webauthnTransactionId: string;\n webauthnOptions: string;\n redirectAuthCodeChallenge: string;\n redirectAuthCallbackUrl: string;\n redirectAuthBackupCallbackUri: string;\n redirectAuthInitiator: string;\n deferredRedirect: boolean;\n locale: string;\n samlIdpResponseUrl: string;\n samlIdpResponseSamlResponse: string;\n samlIdpResponseRelayState: string;\n nativeResponseType: string;\n nativePayload: Record<string, any>;\n reqTimestamp: number;\n} & SSOQueryParams;\n\nexport type StepState = {\n screenState: ScreenState;\n screenId: string;\n stepName: string;\n htmlFilename: string;\n htmlLocaleFilename: string;\n next: NextFn;\n direction: Direction | undefined;\n samlIdpUsername: string;\n action?: string;\n} & OIDCOptions;\n\nexport type CustomScreenState = Omit<\n ScreenState,\n 'cssVars' | 'componentsConfig' | 'inputs'\n> & {\n error?: {\n text: ScreenState['errorText'];\n type: ScreenState['errorType'];\n };\n action?: string;\n inboundAppApproveScopes?: {\n desc: string;\n id: string;\n required: boolean;\n }[];\n};\n\nexport type DebugState = {\n isDebug: boolean;\n};\n\nexport interface ScriptElement extends HTMLDivElement {\n moduleRes?: ScriptModule;\n}\n\nexport type ScriptModule = {\n stop: () => void;\n start: () => void;\n /**\n * Refreshes any tokens or state that might be needed before form submission\n * Currently implemented for reCAPTCHA to ensure we have a fresh token\n */\n refresh?: () => Promise<void>;\n};\n\nexport type ClientScript = {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n};\n\nexport type NextFn = KeepArgsByIndex<SdkFlowNext, [2, 5]>;\nexport type NextFnReturnPromiseValue = Awaited<ReturnType<NextFn>>;\n\nexport type DebuggerMessage = {\n title: string;\n description?: string;\n};\n\nexport type FlowStateUpdateFn = (state: FlowState) => void;\n\ntype Operator =\n | 'equal'\n | 'not-equal'\n | 'contains'\n | 'greater-than'\n | 'greater-than-or-equal'\n | 'less-than'\n | 'less-than-or-equal'\n | 'empty'\n | 'not-empty'\n | 'is-true'\n | 'is-false'\n | 'in'\n | 'not-in'\n | 'in-range'\n | 'not-in-range'\n | 'devised-by';\n\nexport interface ClientConditionResult {\n screenId: string;\n screenName: string;\n clientScripts?: ClientScript[];\n componentsConfig?: ComponentsConfig;\n interactionId: string;\n}\n\nexport interface ClientCondition {\n operator: Operator;\n key: string;\n predicate?: string | number;\n met: ClientConditionResult;\n unmet?: ClientConditionResult;\n}\n\nexport type AutoFocusOptions = true | false | 'skipFirstScreen';\n\nexport type ThemeOptions = 'light' | 'dark' | 'os';\n\nexport type Key =\n | 'lastAuth.loginId'\n | 'idpInitiated'\n | 'externalToken'\n | 'abTestingKey';\n\ntype CheckFunction = (ctx: Context, predicate?: string | number) => boolean;\n\nexport type ConditionsMap = {\n [key in Key]: {\n [operator in Operator]?: CheckFunction;\n };\n};\n\nexport interface Context {\n loginId?: string;\n code?: string;\n token?: string;\n abTestingKey?: number;\n}\n\nexport type DescopeUI = Record<string, () => Promise<void>> & {\n componentsThemeManager: Record<string, any>;\n};\n\ntype Font = {\n family: string[];\n label: string;\n url?: string;\n};\n\ntype ThemeTemplate = {\n fonts: {\n font1: Font;\n font2: Font;\n };\n};\n\nexport type FlowConfig = {\n startScreenId?: string;\n startScreenName?: string;\n version: number;\n targetLocales?: string[];\n conditions?: ClientCondition[];\n condition?: ClientCondition;\n fingerprintEnabled?: boolean;\n fingerprintKey?: string;\n sdkScripts?: [\n {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n },\n ];\n clientScripts?: ClientScript[];\n componentsConfig?: ComponentsConfig;\n};\n\nexport interface ProjectConfiguration {\n componentsVersion: string;\n cssTemplate: {\n dark: ThemeTemplate;\n light: ThemeTemplate;\n };\n flows: {\n [key: string]: FlowConfig; // dynamic key names for flows\n };\n}\n\nexport type FlowStatus = 'loading' | 'error' | 'success' | 'ready' | 'initial';\n"],"names":["Direction"],"mappings":"aAmCA,IAAYA,EAAAA,QAGXA,eAAA,GAHWA,EAAAA,QAASA,YAATA,kBAGX,CAAA,IAFC,SAAA,WACAA,EAAA,QAAA"}
|
|
1
|
+
{"version":3,"file":"types.js","sources":["../../src/lib/types.ts"],"sourcesContent":["/* istanbul ignore file */\n\nimport createSdk from '@descope/web-js-sdk';\n\nexport type SdkConfig = Parameters<typeof createSdk>[0];\nexport type Sdk = ReturnType<typeof createSdk>;\n\nexport type SdkFlowNext = Sdk['flow']['next'];\n\nexport type ComponentsDynamicAttrs = {\n attributes: Record<string, any>;\n};\n\nexport type ComponentsConfig = Record<string, any> & {\n componentsDynamicAttrs?: Record<string, ComponentsDynamicAttrs>;\n};\nexport type CssVars = Record<string, any>;\n\ntype KeepArgsByIndex<F, Indices extends readonly number[]> = F extends (\n ...args: infer A\n) => infer R\n ? (...args: PickArgsByIndex<A, Indices>) => R\n : never;\n\ntype PickArgsByIndex<\n All extends readonly any[],\n Indices extends readonly number[],\n> = {\n [K in keyof Indices]: Indices[K] extends keyof All ? All[Indices[K]] : never;\n};\n\ntype Project = {\n name: string;\n};\n\nexport enum Direction {\n backward = 'backward',\n forward = 'forward',\n}\n\nexport interface LastAuthState {\n loginId?: string;\n name?: string;\n}\n\nexport interface ScreenState {\n errorText?: string;\n errorType?: string;\n componentsConfig?: ComponentsConfig;\n cssVars?: CssVars;\n form?: Record<string, string>;\n inputs?: Record<string, string>; // Backward compatibility\n lastAuth?: LastAuthState;\n project?: Project;\n totp?: { image?: string; provisionUrl?: string };\n notp?: { image?: string; redirectUrl?: string };\n selfProvisionDomains?: unknown;\n user?: unknown;\n sso?: unknown;\n dynamicSelects?: unknown;\n keysInUse?: unknown;\n genericForm?: unknown;\n linkId?: unknown;\n sentTo?: unknown;\n clientScripts?: ClientScript[];\n}\n\nexport type SSOQueryParams = {\n oidcIdpStateId?: string;\n samlIdpStateId?: string;\n samlIdpUsername?: string;\n descopeIdpInitiated?: boolean;\n ssoAppId?: string;\n thirdPartyAppId: string;\n thirdPartyAppStateId?: string;\n applicationScopes?: string;\n} & OIDCOptions;\n\nexport type OIDCOptions = {\n oidcLoginHint?: string;\n oidcPrompt?: string;\n oidcErrorRedirectUri?: string;\n oidcResource?: string;\n};\n\nexport type Locale = {\n locale: string;\n fallback: string;\n};\n\nexport type FlowState = {\n flowId: string;\n projectId: string;\n baseUrl: string;\n tenant: string;\n stepId: string;\n stepName: string;\n executionId: string;\n action: string;\n redirectTo: string;\n redirectIsPopup: boolean;\n openInNewTabUrl?: string;\n redirectUrl: string;\n screenId: string;\n screenState: ScreenState;\n token: string;\n code: string;\n isPopup: boolean;\n exchangeError: string;\n webauthnTransactionId: string;\n webauthnOptions: string;\n redirectAuthCodeChallenge: string;\n redirectAuthCallbackUrl: string;\n redirectAuthBackupCallbackUri: string;\n redirectAuthInitiator: string;\n deferredRedirect: boolean;\n locale: string;\n samlIdpResponseUrl: string;\n samlIdpResponseSamlResponse: string;\n samlIdpResponseRelayState: string;\n nativeResponseType: string;\n nativePayload: Record<string, any>;\n reqTimestamp: number;\n} & SSOQueryParams;\n\nexport type StepState = {\n screenState: ScreenState;\n screenId: string;\n stepName: string;\n htmlFilename: string;\n htmlLocaleFilename: string;\n next: NextFn;\n direction: Direction | undefined;\n samlIdpUsername: string;\n action?: string;\n} & OIDCOptions;\n\nexport type CustomScreenState = Omit<\n ScreenState,\n 'cssVars' | 'componentsConfig' | 'inputs'\n> & {\n error?: {\n text: ScreenState['errorText'];\n type: ScreenState['errorType'];\n };\n action?: string;\n inboundAppApproveScopes?: {\n desc: string;\n id: string;\n required: boolean;\n }[];\n};\n\nexport type DebugState = {\n isDebug: boolean;\n};\n\nexport interface ScriptElement extends HTMLDivElement {\n moduleRes?: ScriptModule;\n}\n\nexport type ScriptModule = {\n stop: () => void;\n start: () => void;\n /**\n * Refreshes any tokens or state that might be needed before form submission\n * Currently implemented for reCAPTCHA to ensure we have a fresh token\n */\n refresh?: () => Promise<void>;\n};\n\nexport type ClientScript = {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n};\n\nexport type NextFn = KeepArgsByIndex<SdkFlowNext, [2, 5]>;\nexport type NextFnReturnPromiseValue = Awaited<ReturnType<NextFn>>;\n\nexport type DebuggerMessage = {\n title: string;\n description?: string;\n};\n\nexport type FlowStateUpdateFn = (state: FlowState) => void;\n\ntype Operator =\n | 'equal'\n | 'not-equal'\n | 'contains'\n | 'greater-than'\n | 'greater-than-or-equal'\n | 'less-than'\n | 'less-than-or-equal'\n | 'empty'\n | 'not-empty'\n | 'is-true'\n | 'is-false'\n | 'in'\n | 'not-in'\n | 'in-range'\n | 'not-in-range'\n | 'devised-by';\n\nexport interface ClientConditionResult {\n screenId: string;\n screenName: string;\n clientScripts?: ClientScript[];\n componentsConfig?: ComponentsConfig;\n interactionId: string;\n}\n\nexport interface ClientCondition {\n operator: Operator;\n key: string;\n predicate?: string | number;\n met: ClientConditionResult;\n unmet?: ClientConditionResult;\n}\n\nexport type AutoFocusOptions = true | false | 'skipFirstScreen';\n\nexport type ThemeOptions = 'light' | 'dark' | 'os';\n\nexport type Key =\n | 'lastAuth.loginId'\n | 'idpInitiated'\n | 'externalToken'\n | 'abTestingKey';\n\ntype CheckFunction = (ctx: Context, predicate?: string | number) => boolean;\n\nexport type ConditionsMap = {\n [key in Key]: {\n [operator in Operator]?: CheckFunction;\n };\n};\n\nexport interface Context {\n loginId?: string;\n code?: string;\n token?: string;\n abTestingKey?: number;\n}\n\nexport type DescopeUI = Record<string, () => Promise<void>> & {\n componentsThemeManager: Record<string, any>;\n};\n\ntype Font = {\n family: string[];\n label: string;\n url?: string;\n};\n\ntype ThemeTemplate = {\n fonts: {\n font1: Font;\n font2: Font;\n };\n};\n\nexport type FlowConfig = {\n startScreenId?: string;\n startScreenName?: string;\n version: number;\n targetLocales?: string[];\n conditions?: ClientCondition[];\n condition?: ClientCondition;\n fingerprintEnabled?: boolean;\n fingerprintKey?: string;\n sdkScripts?: [\n {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n },\n ];\n clientScripts?: ClientScript[];\n componentsConfig?: ComponentsConfig;\n};\n\nexport interface ProjectConfiguration {\n componentsVersion: string;\n cssTemplate: {\n dark: ThemeTemplate;\n light: ThemeTemplate;\n };\n flows: {\n [key: string]: FlowConfig; // dynamic key names for flows\n };\n}\n\nexport type FlowStatus = 'loading' | 'error' | 'success' | 'ready' | 'initial';\n"],"names":["Direction"],"mappings":"aAmCA,IAAYA,EAAAA,QAGXA,eAAA,GAHWA,EAAAA,QAASA,YAATA,kBAGX,CAAA,IAFC,SAAA,WACAA,EAAA,QAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{ASSETS_FOLDER,BASE_CONTENT_URL,CONFIG_FILENAME,OVERRIDE_CONTENT_URL,PREV_VER_ASSETS_FOLDER}from"./content.js";export{UI_COMPONENTS_URL_KEY}from"./uiComponents.js";const e="descope-login-flow",t="t",a="code",i="redirect_mode",d="err",o="ra-challenge",r="ra-callback",_="ra-backup-callback",p="ra-initiator",
|
|
1
|
+
export{ASSETS_FOLDER,BASE_CONTENT_URL,CONFIG_FILENAME,OVERRIDE_CONTENT_URL,PREV_VER_ASSETS_FOLDER}from"./content.js";export{UI_COMPONENTS_URL_KEY}from"./uiComponents.js";const e="descope-login-flow",t="t",a="code",i="redirect_mode",d="err",o="ra-challenge",r="ra-callback",_="ra-backup-callback",p="ra-initiator",c="data-descope-",l="data-exclude-field",s="data-exclude-next",n="dls_last_auth",u="state_id",m="saml_idp_state_id",E="saml_idp_username",b="descope_idp_initiated",h="sso_app_id",R="third_party_app_id",S="third_party_app_state_id",x="oidc_login_hint",N="oidc_prompt",O="oidc_resource",g="oidc_error_redirect_uri",C="application_scopes",T="data-type",F="sdkScriptsResults",L={redirect:"redirect",poll:"poll",webauthnCreate:"webauthnCreate",webauthnGet:"webauthnGet",nativeBridge:"nativeBridge",loadForm:"loadForm"},w={submit:"submit",polling:"polling"},f="data-has-dynamic-attr-values",k=["descope-multi-select-combo-box","descope-text-area"],y=5e3;export{C as APPLICATION_SCOPES_PARAM_NAME,w as CUSTOM_INTERACTIONS,l as DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,s as DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON,c as DESCOPE_ATTRIBUTE_PREFIX,b as DESCOPE_IDP_INITIATED_PARAM_NAME,n as DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY,k as ELEMENTS_TO_IGNORE_ENTER_KEY_ON,T as ELEMENT_TYPE_ATTRIBUTE,f as HAS_DYNAMIC_VALUES_ATTR_NAME,g as OIDC_ERROR_REDIRECT_URI_PARAM_NAME,u as OIDC_IDP_STATE_ID_PARAM_NAME,x as OIDC_LOGIN_HINT_PARAM_NAME,N as OIDC_PROMPT_PARAM_NAME,O as OIDC_RESOURCE_PARAM_NAME,L as RESPONSE_ACTIONS,m as SAML_IDP_STATE_ID_PARAM_NAME,E as SAML_IDP_USERNAME_PARAM_NAME,y as SDK_SCRIPTS_LOAD_TIMEOUT,F as SDK_SCRIPT_RESULTS_KEY,h as SSO_APP_ID_PARAM_NAME,R as THIRD_PARTY_APP_ID_PARAM_NAME,S as THIRD_PARTY_APP_STATE_ID_PARAM_NAME,a as URL_CODE_PARAM_NAME,d as URL_ERR_PARAM_NAME,_ as URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME,r as URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME,o as URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME,p as URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME,i as URL_REDIRECT_MODE_PARAM_NAME,e as URL_RUN_IDS_PARAM_NAME,t as URL_TOKEN_PARAM_NAME};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/lib/constants/index.ts"],"sourcesContent":["export * from './general';\nexport * from './content';\nexport * from './uiComponents';\n\nexport const URL_RUN_IDS_PARAM_NAME = 'descope-login-flow';\nexport const URL_TOKEN_PARAM_NAME = 't';\nexport const URL_CODE_PARAM_NAME = 'code';\nexport const URL_REDIRECT_MODE_PARAM_NAME = 'redirect_mode';\nexport const URL_ERR_PARAM_NAME = 'err';\nexport const URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME = 'ra-challenge';\nexport const URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME = 'ra-callback';\nexport const URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME =\n 'ra-backup-callback';\nexport const URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME = 'ra-initiator';\nexport const DESCOPE_ATTRIBUTE_PREFIX = 'data-descope-';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_FIELD = 'data-exclude-field';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON = 'data-exclude-next';\nexport const DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY = 'dls_last_auth';\n\n// SSO query params\nexport const OIDC_IDP_STATE_ID_PARAM_NAME = 'state_id';\nexport const SAML_IDP_STATE_ID_PARAM_NAME = 'saml_idp_state_id';\nexport const SAML_IDP_USERNAME_PARAM_NAME = 'saml_idp_username';\nexport const DESCOPE_IDP_INITIATED_PARAM_NAME = 'descope_idp_initiated';\nexport const SSO_APP_ID_PARAM_NAME = 'sso_app_id';\nexport const THIRD_PARTY_APP_ID_PARAM_NAME = 'third_party_app_id';\nexport const THIRD_PARTY_APP_STATE_ID_PARAM_NAME = 'third_party_app_state_id';\nexport const OIDC_LOGIN_HINT_PARAM_NAME = 'oidc_login_hint';\nexport const OIDC_PROMPT_PARAM_NAME = 'oidc_prompt';\nexport const OIDC_ERROR_REDIRECT_URI_PARAM_NAME = 'oidc_error_redirect_uri';\nexport const APPLICATION_SCOPES_PARAM_NAME = 'application_scopes';\n\nexport const ELEMENT_TYPE_ATTRIBUTE = 'data-type';\n\nexport const SDK_SCRIPT_RESULTS_KEY = 'sdkScriptsResults';\n\nexport const RESPONSE_ACTIONS = {\n redirect: 'redirect',\n poll: 'poll',\n webauthnCreate: 'webauthnCreate',\n webauthnGet: 'webauthnGet',\n nativeBridge: 'nativeBridge',\n loadForm: 'loadForm',\n};\n\nexport const CUSTOM_INTERACTIONS = {\n submit: 'submit',\n polling: 'polling',\n};\n\nexport const HAS_DYNAMIC_VALUES_ATTR_NAME = 'data-has-dynamic-attr-values';\n\nexport const ELEMENTS_TO_IGNORE_ENTER_KEY_ON = [\n 'descope-multi-select-combo-box',\n 'descope-text-area',\n];\n\nexport const SDK_SCRIPTS_LOAD_TIMEOUT = 5000;\n"],"names":["URL_RUN_IDS_PARAM_NAME","URL_TOKEN_PARAM_NAME","URL_CODE_PARAM_NAME","URL_REDIRECT_MODE_PARAM_NAME","URL_ERR_PARAM_NAME","URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME","URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME","URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME","URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME","DESCOPE_ATTRIBUTE_PREFIX","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON","DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY","OIDC_IDP_STATE_ID_PARAM_NAME","SAML_IDP_STATE_ID_PARAM_NAME","SAML_IDP_USERNAME_PARAM_NAME","DESCOPE_IDP_INITIATED_PARAM_NAME","SSO_APP_ID_PARAM_NAME","THIRD_PARTY_APP_ID_PARAM_NAME","THIRD_PARTY_APP_STATE_ID_PARAM_NAME","OIDC_LOGIN_HINT_PARAM_NAME","OIDC_PROMPT_PARAM_NAME","OIDC_ERROR_REDIRECT_URI_PARAM_NAME","APPLICATION_SCOPES_PARAM_NAME","ELEMENT_TYPE_ATTRIBUTE","SDK_SCRIPT_RESULTS_KEY","RESPONSE_ACTIONS","redirect","poll","webauthnCreate","webauthnGet","nativeBridge","loadForm","CUSTOM_INTERACTIONS","submit","polling","HAS_DYNAMIC_VALUES_ATTR_NAME","ELEMENTS_TO_IGNORE_ENTER_KEY_ON","SDK_SCRIPTS_LOAD_TIMEOUT"],"mappings":"0KAIO,MAAMA,EAAyB,qBACzBC,EAAuB,IACvBC,EAAsB,OACtBC,EAA+B,gBAC/BC,EAAqB,MACrBC,EAAyC,eACzCC,EAAwC,cACxCC,EACX,qBACWC,EAAyC,eACzCC,EAA2B,gBAC3BC,EAAkC,qBAClCC,EAAwC,oBACxCC,EAAsC,gBAGtCC,EAA+B,WAC/BC,EAA+B,oBAC/BC,EAA+B,oBAC/BC,EAAmC,wBACnCC,EAAwB,aACxBC,EAAgC,qBAChCC,EAAsC,2BACtCC,EAA6B,kBAC7BC,EAAyB,cACzBC,EAAqC,0BACrCC,EAAgC,qBAEhCC,EAAyB,YAEzBC,EAAyB,oBAEzBC,EAAmB,CAC9BC,SAAU,WACVC,KAAM,OACNC,eAAgB,iBAChBC,YAAa,cACbC,aAAc,eACdC,SAAU,YAGCC,EAAsB,CACjCC,OAAQ,SACRC,QAAS,WAGEC,EAA+B,+BAE/BC,EAAkC,CAC7C,iCACA,qBAGWC,EAA2B"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/lib/constants/index.ts"],"sourcesContent":["export * from './general';\nexport * from './content';\nexport * from './uiComponents';\n\nexport const URL_RUN_IDS_PARAM_NAME = 'descope-login-flow';\nexport const URL_TOKEN_PARAM_NAME = 't';\nexport const URL_CODE_PARAM_NAME = 'code';\nexport const URL_REDIRECT_MODE_PARAM_NAME = 'redirect_mode';\nexport const URL_ERR_PARAM_NAME = 'err';\nexport const URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME = 'ra-challenge';\nexport const URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME = 'ra-callback';\nexport const URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME =\n 'ra-backup-callback';\nexport const URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME = 'ra-initiator';\nexport const DESCOPE_ATTRIBUTE_PREFIX = 'data-descope-';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_FIELD = 'data-exclude-field';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON = 'data-exclude-next';\nexport const DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY = 'dls_last_auth';\n\n// SSO query params\nexport const OIDC_IDP_STATE_ID_PARAM_NAME = 'state_id';\nexport const SAML_IDP_STATE_ID_PARAM_NAME = 'saml_idp_state_id';\nexport const SAML_IDP_USERNAME_PARAM_NAME = 'saml_idp_username';\nexport const DESCOPE_IDP_INITIATED_PARAM_NAME = 'descope_idp_initiated';\nexport const SSO_APP_ID_PARAM_NAME = 'sso_app_id';\nexport const THIRD_PARTY_APP_ID_PARAM_NAME = 'third_party_app_id';\nexport const THIRD_PARTY_APP_STATE_ID_PARAM_NAME = 'third_party_app_state_id';\nexport const OIDC_LOGIN_HINT_PARAM_NAME = 'oidc_login_hint';\nexport const OIDC_PROMPT_PARAM_NAME = 'oidc_prompt';\nexport const OIDC_RESOURCE_PARAM_NAME = 'oidc_resource';\nexport const OIDC_ERROR_REDIRECT_URI_PARAM_NAME = 'oidc_error_redirect_uri';\nexport const APPLICATION_SCOPES_PARAM_NAME = 'application_scopes';\n\nexport const ELEMENT_TYPE_ATTRIBUTE = 'data-type';\n\nexport const SDK_SCRIPT_RESULTS_KEY = 'sdkScriptsResults';\n\nexport const RESPONSE_ACTIONS = {\n redirect: 'redirect',\n poll: 'poll',\n webauthnCreate: 'webauthnCreate',\n webauthnGet: 'webauthnGet',\n nativeBridge: 'nativeBridge',\n loadForm: 'loadForm',\n};\n\nexport const CUSTOM_INTERACTIONS = {\n submit: 'submit',\n polling: 'polling',\n};\n\nexport const HAS_DYNAMIC_VALUES_ATTR_NAME = 'data-has-dynamic-attr-values';\n\nexport const ELEMENTS_TO_IGNORE_ENTER_KEY_ON = [\n 'descope-multi-select-combo-box',\n 'descope-text-area',\n];\n\nexport const SDK_SCRIPTS_LOAD_TIMEOUT = 5000;\n"],"names":["URL_RUN_IDS_PARAM_NAME","URL_TOKEN_PARAM_NAME","URL_CODE_PARAM_NAME","URL_REDIRECT_MODE_PARAM_NAME","URL_ERR_PARAM_NAME","URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME","URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME","URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME","URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME","DESCOPE_ATTRIBUTE_PREFIX","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON","DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY","OIDC_IDP_STATE_ID_PARAM_NAME","SAML_IDP_STATE_ID_PARAM_NAME","SAML_IDP_USERNAME_PARAM_NAME","DESCOPE_IDP_INITIATED_PARAM_NAME","SSO_APP_ID_PARAM_NAME","THIRD_PARTY_APP_ID_PARAM_NAME","THIRD_PARTY_APP_STATE_ID_PARAM_NAME","OIDC_LOGIN_HINT_PARAM_NAME","OIDC_PROMPT_PARAM_NAME","OIDC_RESOURCE_PARAM_NAME","OIDC_ERROR_REDIRECT_URI_PARAM_NAME","APPLICATION_SCOPES_PARAM_NAME","ELEMENT_TYPE_ATTRIBUTE","SDK_SCRIPT_RESULTS_KEY","RESPONSE_ACTIONS","redirect","poll","webauthnCreate","webauthnGet","nativeBridge","loadForm","CUSTOM_INTERACTIONS","submit","polling","HAS_DYNAMIC_VALUES_ATTR_NAME","ELEMENTS_TO_IGNORE_ENTER_KEY_ON","SDK_SCRIPTS_LOAD_TIMEOUT"],"mappings":"0KAIO,MAAMA,EAAyB,qBACzBC,EAAuB,IACvBC,EAAsB,OACtBC,EAA+B,gBAC/BC,EAAqB,MACrBC,EAAyC,eACzCC,EAAwC,cACxCC,EACX,qBACWC,EAAyC,eACzCC,EAA2B,gBAC3BC,EAAkC,qBAClCC,EAAwC,oBACxCC,EAAsC,gBAGtCC,EAA+B,WAC/BC,EAA+B,oBAC/BC,EAA+B,oBAC/BC,EAAmC,wBACnCC,EAAwB,aACxBC,EAAgC,qBAChCC,EAAsC,2BACtCC,EAA6B,kBAC7BC,EAAyB,cACzBC,EAA2B,gBAC3BC,EAAqC,0BACrCC,EAAgC,qBAEhCC,EAAyB,YAEzBC,EAAyB,oBAEzBC,EAAmB,CAC9BC,SAAU,WACVC,KAAM,OACNC,eAAgB,iBAChBC,YAAa,cACbC,aAAc,eACdC,SAAU,YAGCC,EAAsB,CACjCC,OAAQ,SACRC,QAAS,WAGEC,EAA+B,+BAE/BC,EAAkC,CAC7C,iCACA,qBAGWC,EAA2B"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as r}from"@descope/sdk-helpers";import{staticResourcesMixin as o}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as s}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import u from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as a}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as f,fetchContent as g}from"../helpers/helpers.js";import p from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{transformFlowInputFormData as m,extractNestedAttribute as b}from"../helpers/flowInputs.js";import{formMountMixin as v}from"../mixins/formMountMixin.js";import{CONFIG_FILENAME as w,PREV_VER_ASSETS_FOLDER as k}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as C}from"../constants/general.js";var A,x,y,j,I,E,L,U,M,S,O,W,D,P,N,F,R,T,B,V,q,H;const J=r(s,o,v,n)(HTMLElement);class K extends J{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(r){super(),A.add(this),y.set(this,!1),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,A,"m",q).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},j.set(this,new p),I.set(this,new p),E.set(this,{}),this.getComponentsContext=()=>t(this,E,"f"),this.nextRequestStatus=new p({isLoading:!1}),L.set(this,void 0),U.set(this,{popstate:t(this,A,"m",D).bind(this),componentsContext:t(this,A,"m",T).bind(this)}),M.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,M,r,"f"),t(this,A,"m",O).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get tenantId(){return this.getAttribute("tenant")||void 0}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return m(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return b(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),r=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=r.version)&&void 0!==e||(r.version=0),r}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const r=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=r.init)||void 0===e?void 0:e.call(this),t(this,I,"f").subscribe(t(this,A,"m",V).bind(this)),t(this,I,"f").update({isDebug:this.debug}),t(this,A,"m",W).call(this),yield t(this,A,"m",F).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const o=yield this.getConfig();if("isMissingConfig"in o&&o.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");t(this,A,"m",H).call(this);const{executionId:s,stepId:n,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,U,"f").popstate),window.addEventListener("components-context",t(this,U,"f").componentsContext),t(this,j,"f").subscribe(t(this,A,"m",N).bind(this)),t(this,j,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:s,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,y,!0,"f")}))}disconnectedCallback(){t(this,j,"f").unsubscribeAll(),t(this,I,"f").unsubscribeAll(),t(this,A,"m",B).call(this),window.removeEventListener("popstate",t(this,U,"f").popstate),window.removeEventListener("components-context",t(this,U,"f").componentsContext)}attributeChangedCallback(e,i,r){if(this.shadowRoot.isConnected&&t(this,y,"f")&&i!==r&&x.observedAttributes.includes(e)){t(this,A,"m",W).call(this);const o=null===i;t(this,j,"f").update((({stepId:t,executionId:i})=>{let s=t,n=i;return o||(n=null,s=null,d()),{[c(e)]:r,stepId:s,executionId:n}})),t(this,I,"f").update({isDebug:this.debug})}}}x=K,y=new WeakMap,j=new WeakMap,I=new WeakMap,E=new WeakMap,L=new WeakMap,U=new WeakMap,M=new WeakMap,A=new WeakSet,S=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},O=function(){t(this,A,"m",S).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},W=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id","outbound-app-id","outbound-app-scopes"];x.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},D=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,j,"f").update({stepId:e,executionId:i})},P=function(t,i){this.sdk=u(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},x.sdkConfigOverrides),{projectId:t,baseUrl:i})),["start","next"].forEach((t=>{const i=this.sdk.flow[t];this.sdk.flow[t]=(...t)=>e(this,void 0,void 0,(function*(){try{return yield i(...t)}catch(t){return{error:{errorCode:C,errorDescription:t.toString()}}}}))}))},N=function(i,r,o){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:r}=i;if(o("projectId")||o("baseUrl")){if(!e)return;t(this,A,"m",P).call(this,e,r)}t(this,M,"f").call(this,i)}))},F=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,A,"m",R).call(this))}))},R=function(){return e(this,void 0,void 0,(function*(){const t=f({projectId:this.projectId,filename:w,assetsFolder:k,baseUrl:this.baseStaticUrl});try{return yield g(t,"json"),!0}catch(t){return!1}}))},T=function(e){i(this,E,Object.assign(Object.assign({},t(this,E,"f")),e.detail),"f")},B=function(){var e;null===(e=t(this,L,"f"))||void 0===e||e.remove(),i(this,L,null,"f")},V=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,L,document.createElement("descope-debugger"),"f"),Object.assign(t(this,L,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield import("../debugger-wc.js"),document.body.appendChild(t(this,L,"f"))):t(this,A,"m",B).call(this)}))},q=function(e,i){var r;e&&this.debug&&(null===(r=t(this,L,"f"))||void 0===r||r.updateData({title:e,description:i}))},H=function(){this.rootElement.onkeydown=t=>{var e,i,r;const o=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),s=a.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||o||s)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const u=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===u.length)return void u[0].click();const l=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}},K.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.45.1"}};export{K as default};
|
|
1
|
+
import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as r}from"@descope/sdk-helpers";import{staticResourcesMixin as o}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as s}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import u from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as a}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as f,fetchContent as g}from"../helpers/helpers.js";import p from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{transformFlowInputFormData as m,extractNestedAttribute as b}from"../helpers/flowInputs.js";import{formMountMixin as v}from"../mixins/formMountMixin.js";import{CONFIG_FILENAME as w,PREV_VER_ASSETS_FOLDER as k}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as C}from"../constants/general.js";var A,x,y,j,I,E,L,U,M,S,O,W,D,P,N,F,R,T,B,V,q,H;const J=r(s,o,v,n)(HTMLElement);class K extends J{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(r){super(),A.add(this),y.set(this,!1),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,A,"m",q).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},j.set(this,new p),I.set(this,new p),E.set(this,{}),this.getComponentsContext=()=>t(this,E,"f"),this.nextRequestStatus=new p({isLoading:!1}),L.set(this,void 0),U.set(this,{popstate:t(this,A,"m",D).bind(this),componentsContext:t(this,A,"m",T).bind(this)}),M.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,M,r,"f"),t(this,A,"m",O).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get tenantId(){return this.getAttribute("tenant")||void 0}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return m(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return b(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),r=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=r.version)&&void 0!==e||(r.version=0),r}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const r=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=r.init)||void 0===e?void 0:e.call(this),t(this,I,"f").subscribe(t(this,A,"m",V).bind(this)),t(this,I,"f").update({isDebug:this.debug}),t(this,A,"m",W).call(this),yield t(this,A,"m",F).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const o=yield this.getConfig();if("isMissingConfig"in o&&o.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");t(this,A,"m",H).call(this);const{executionId:s,stepId:n,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,U,"f").popstate),window.addEventListener("components-context",t(this,U,"f").componentsContext),t(this,j,"f").subscribe(t(this,A,"m",N).bind(this)),t(this,j,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:s,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,y,!0,"f")}))}disconnectedCallback(){t(this,j,"f").unsubscribeAll(),t(this,I,"f").unsubscribeAll(),t(this,A,"m",B).call(this),window.removeEventListener("popstate",t(this,U,"f").popstate),window.removeEventListener("components-context",t(this,U,"f").componentsContext)}attributeChangedCallback(e,i,r){if(this.shadowRoot.isConnected&&t(this,y,"f")&&i!==r&&x.observedAttributes.includes(e)){t(this,A,"m",W).call(this);const o=null===i;t(this,j,"f").update((({stepId:t,executionId:i})=>{let s=t,n=i;return o||(n=null,s=null,d()),{[c(e)]:r,stepId:s,executionId:n}})),t(this,I,"f").update({isDebug:this.debug})}}}x=K,y=new WeakMap,j=new WeakMap,I=new WeakMap,E=new WeakMap,L=new WeakMap,U=new WeakMap,M=new WeakMap,A=new WeakSet,S=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},O=function(){t(this,A,"m",S).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},W=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id","outbound-app-id","outbound-app-scopes"];x.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},D=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,j,"f").update({stepId:e,executionId:i})},P=function(t,i){this.sdk=u(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},x.sdkConfigOverrides),{projectId:t,baseUrl:i})),["start","next"].forEach((t=>{const i=this.sdk.flow[t];this.sdk.flow[t]=(...t)=>e(this,void 0,void 0,(function*(){try{return yield i(...t)}catch(t){return{error:{errorCode:C,errorDescription:t.toString()}}}}))}))},N=function(i,r,o){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:r}=i;if(o("projectId")||o("baseUrl")){if(!e)return;t(this,A,"m",P).call(this,e,r)}t(this,M,"f").call(this,i)}))},F=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,A,"m",R).call(this))}))},R=function(){return e(this,void 0,void 0,(function*(){const t=f({projectId:this.projectId,filename:w,assetsFolder:k,baseUrl:this.baseStaticUrl});try{return yield g(t,"json"),!0}catch(t){return!1}}))},T=function(e){i(this,E,Object.assign(Object.assign({},t(this,E,"f")),e.detail),"f")},B=function(){var e;null===(e=t(this,L,"f"))||void 0===e||e.remove(),i(this,L,null,"f")},V=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,L,document.createElement("descope-debugger"),"f"),Object.assign(t(this,L,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield import("../debugger-wc.js"),document.body.appendChild(t(this,L,"f"))):t(this,A,"m",B).call(this)}))},q=function(e,i){var r;e&&this.debug&&(null===(r=t(this,L,"f"))||void 0===r||r.updateData({title:e,description:i}))},H=function(){this.rootElement.onkeydown=t=>{var e,i,r;const o=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),s=a.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||o||s)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const u=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===u.length)return void u[0].click();const l=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}},K.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.46.1"}};export{K as default};
|
|
2
2
|
//# sourceMappingURL=BaseDescopeWc.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{ensureFingerprintIds as o,clearFingerprintData as n}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as r,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as l,URL_TOKEN_PARAM_NAME as d,URL_RUN_IDS_PARAM_NAME as c,SDK_SCRIPTS_LOAD_TIMEOUT as h,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as p,ELEMENT_TYPE_ATTRIBUTE as u,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as g}from"../constants/index.js";import{timeoutPromise as v,withMemCache as m,leadingDebounce as f,getUserLocale as b,showFirstScreenOnExecutionInit as w,injectSamlIdpForm as S,openCenteredPopup as y,getAnimationDirection as I,handleAutoFocus as C,transformStepStateForCustomScreen as k,getElementDescopeAttributes as R,getScriptResultPath as W,submitForm as O,transformScreenInputs as E,handleReportValidityOnBlur as x,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 N,setNOTPVariable as $,setCssVars as q,updateScreenFromScreenState as M,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 J}from"../helpers/lastAuth.js";import _ from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as G,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,Ie,Ce,ke,Re,We,Oe,Ee,xe,Ae,je,Te,Le;class Ue extends _{static set sdkConfigOverrides(e){_.sdkConfigOverrides=e}static get sdkConfigOverrides(){return _.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)===G)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",Le).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:I}=i.data;if(y!==r.poll&&e(this,fe,"f").call(this),"completed"===b)return this.storeLastAuthenticatedUser&&H(S),void e(this,Z,"m",Le).call(this,"success",w);I&&window.open(I,"_blank");const{executionId:C,stepId:k,stepName:R,screen:W,redirect:O,webauthn:E,error:x,samlIdpResponse:A,nativeResponse:j}=i.data,T=Date.now();y!==r.poll?(this.loggerWrapper.info(`Step "${R||`#${k}`}" is ${b}`,"",{screen:W,status:b,stepId:k,stepName:R,action:y,error:x}),(null===(m=W.state)||void 0===m?void 0:m.clientScripts)&&t(this,ie,this.loadSdkScripts(W.state.clientScripts),"f"),this.flowState.update({stepId:k,stepName:R,executionId:C,action:y,redirectTo:null==O?void 0:O.url,redirectIsPopup:null==O?void 0:O.isPopup,screenId:null==W?void 0:W.id,screenState:null==W?void 0:W.state,webauthnTransactionId:null==E?void 0:E.transactionId,webauthnOptions:null==E?void 0:E.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",Ce).call(this)){const o=null==t?void 0:t.getAttribute("id");e(this,Z,"m",We).call(this,t);const n=yield e(this,Z,"m",ke).call(this),r=R(t);if(this.nextRequestStatus.update({isLoading:!0}),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 a=this.loadSdkScriptsModules();if(a.length>0){const e=a.filter((e=>"function"==typeof e.refresh)).map((e=>e.refresh()));e.length>0&&(yield v(h,Promise.all(e),null))}const l=this.getComponentsContext(),d=Object.assign(Object.assign(Object.assign(Object.assign({},l),r),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(o,d),this.nextRequestStatus.update({isLoading:!1}),e(this,Z,"m",Oe).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:{[W(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.11",`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));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(),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:C,screenId:k,screenState:R,redirectTo:W,redirectIsPopup:x,redirectUrl:A,token:j,code:T,isPopup:L,exchangeError:U,webauthnTransactionId:P,webauthnOptions:N,redirectAuthCodeChallenge:$,redirectAuthCallbackUrl:q,redirectAuthBackupCallbackUri:M,redirectAuthInitiator:F,locale:V,samlIdpResponseUrl:H,samlIdpResponseSamlResponse:_,samlIdpResponseRelayState:G,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=q&&$?{callbackUrl:q,codeChallenge:$,backupCallbackUri:M}: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},ce.conditions)),i.push(...e||[])}else ce.condition?({startScreenId:ee,conditionInteractionId:oe}=K(ce.condition,{loginId:de,code:T,token:j,abTestingKey:ne})):(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:J(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)){this.loggerWrapper.debug("Creating popup channel",f);const e=new BroadcastChannel(f);return this.loggerWrapper.debug("Posting message to popup channel",JSON.stringify({code:T,exchangeError:U})),e.postMessage({data:{code:T,exchangeError:U},action:"code"}),this.loggerWrapper.debug("Popup channel message posted, closing channel"),e.close(),this.loggerWrapper.debug("Popup channel closed, closing window"),void window.close()}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(C===r.loadForm&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>c(e)))){if(!H||!_)return void this.loggerWrapper.error("Did not get saml idp params data to load");S(H,_,G||"",O)}if(C===r.redirect&&(c("redirectTo")||c("deferredRedirect"))){if(!W)return void this.loggerWrapper.error("Did not get redirect url");if("android"===F&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${x}`),x){this.loggerWrapper.debug("Opening redirect in popup");const t=y(W,"?",598,700);this.loggerWrapper.debug("Creating broadcast channel");const i=new BroadcastChannel(f);this.loggerWrapper.debug("Starting popup closed detection");const s=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event and clearing interval"),clearInterval(s),e(this,Z,"m",Le).call(this,"popupclosed",{}),this.loggerWrapper.debug("Closing channel"),i.close())}),1e3);this.loggerWrapper.debug("Listening for postMessage on channel");const o=e=>{if(this.loggerWrapper.debug("Received postMessage on channel",JSON.stringify(e)),this.loggerWrapper.debug("Comparing origins",JSON.stringify({eventOrigin:e.origin,windowLocationOrigin:window.location.origin})),e.origin!==window.location.origin)return;this.loggerWrapper.debug("PostMessage origin matches, processing message");const{action:t,data:i}=e.data;this.loggerWrapper.debug(`PostMessage action: ${t}, data: ${JSON.stringify(i)}`),"code"===t&&(this.loggerWrapper.debug("Updating flow state with code and exchangeError"),this.flowState.update({code:i.code,exchangeError:i.exchangeError}))};i.onmessage=o}else this.handleRedirect(W);return}if(C===r.webauthnCreate||C===r.webauthnGet){if(!P||!N)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=C===r.webauthnCreate?yield this.sdk.webauthn.helpers.create(N):yield this.sdk.webauthn.helpers.get(N)}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(C===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:Ie,oidcErrorRedirectUri:Ce,samlIdpUsername:ke}=Y,Re={direction:I(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:ke,oidcLoginHint:ye,oidcPrompt:Ie,oidcErrorRedirectUri:Ce,action:C},We=J(de);w(ee,Y)?Re.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=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({},this.formConfigValues),E(s)),T&&{exchangeCode:T,idpInitiated:!0}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j&&{token:j}));return e(this,be,"f").call(this,i),i})):(c("projectId")||c("baseUrl")||c("executionId")||c("stepId"))&&(Re.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,m,t,ce.version,he.componentsVersion,E(s));return e(this,be,"f").call(this,i),i}))),this.loggerWrapper.debug("Got a screen with id",Re.screenId),yield e(this,Z,"m",ue).call(this,Re),this.stepState.update(Re)}))}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(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),$(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),q(n,g,h.cssVars,this.loggerWrapper),n.replaceChildren(g);const r=!s.htmlFilename;setTimeout((()=>{e(this,Z,"m",Ee).call(this),this.validateOnBlur&&x(n),M(n,h),e(this,Z,"m",Ie).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),C(n,this.autoFocus,r)})),e(this,Z,"m",Te).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}])`))}}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",Le).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=""}))})),C(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",Ie).call(this,{isFirstScreen:h,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)})))}}))},Ie=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,Z,"m",Le).call(this,"ready",{}),i||e(this,Z,"m",re).call(this,s),e(this,Z,"m",Le).call(this,"page-updated",{screenName:s}),e(this,Z,"m",Le).call(this,"screen-updated",{screenName:s})},Ce=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})),{})}))},We=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())}))},Oe=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)}},Ee=function(){j();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,Z,"m",xe).call(this,t)))},xe=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){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)}))}))},Te=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",je).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:""})})))}))}))},Le=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))};export{Ue 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 I,handleAutoFocus as C,transformStepStateForCustomScreen as k,getElementDescopeAttributes as R,getScriptResultPath as W,submitForm as O,transformScreenInputs as E,handleReportValidityOnBlur as x,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 N,setNOTPVariable as $,setCssVars as q,updateScreenFromScreenState as M,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 J}from"../helpers/lastAuth.js";import _ from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as G,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,Ie,Ce,ke,Re,We,Oe,Ee,xe,Ae,je,Te,Le;class Ue extends _{static set sdkConfigOverrides(e){_.sdkConfigOverrides=e}static get sdkConfigOverrides(){return _.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)===G)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",Le).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:I}=i.data;if(y!==r.poll&&e(this,fe,"f").call(this),"completed"===b)return this.storeLastAuthenticatedUser&&H(S),void e(this,Z,"m",Le).call(this,"success",w);I&&window.open(I,"_blank");const{executionId:C,stepId:k,stepName:R,screen:W,redirect:O,webauthn:E,error:x,samlIdpResponse:A,nativeResponse:j}=i.data,T=Date.now();y!==r.poll?(this.loggerWrapper.info(`Step "${R||`#${k}`}" is ${b}`,"",{screen:W,status:b,stepId:k,stepName:R,action:y,error:x}),(null===(m=W.state)||void 0===m?void 0:m.clientScripts)&&t(this,ie,this.loadSdkScripts(W.state.clientScripts),"f"),this.flowState.update({stepId:k,stepName:R,executionId:C,action:y,redirectTo:null==O?void 0:O.url,redirectIsPopup:null==O?void 0:O.isPopup,screenId:null==W?void 0:W.id,screenState:null==W?void 0:W.state,webauthnTransactionId:null==E?void 0:E.transactionId,webauthnOptions:null==E?void 0:E.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",Ce).call(this)){const o=null==t?void 0:t.getAttribute("id");e(this,Z,"m",We).call(this,t);const n=yield e(this,Z,"m",ke).call(this),r=R(t);if(this.nextRequestStatus.update({isLoading:!0}),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 a=this.loadSdkScriptsModules();if(a.length>0){const e=a.filter((e=>"function"==typeof e.refresh)).map((e=>e.refresh()));e.length>0&&(yield v(h,Promise.all(e),null))}const l=this.getComponentsContext(),d=Object.assign(Object.assign(Object.assign(Object.assign({},l),r),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(o,d),this.nextRequestStatus.update({isLoading:!1}),e(this,Z,"m",Oe).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:{[W(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.11",`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));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(),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:C,screenId:k,screenState:R,redirectTo:W,redirectIsPopup:x,redirectUrl:A,token:j,code:T,isPopup:L,exchangeError:U,webauthnTransactionId:P,webauthnOptions:N,redirectAuthCodeChallenge:$,redirectAuthCallbackUrl:q,redirectAuthBackupCallbackUri:M,redirectAuthInitiator:F,locale:V,samlIdpResponseUrl:H,samlIdpResponseSamlResponse:_,samlIdpResponseRelayState:G,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=q&&$?{callbackUrl:q,codeChallenge:$,backupCallbackUri:M}: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},ce.conditions)),i.push(...e||[])}else ce.condition?({startScreenId:ee,conditionInteractionId:oe}=K(ce.condition,{loginId:de,code:T,token:j,abTestingKey:ne})):(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:J(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)){this.loggerWrapper.debug("Creating popup channel",f);const e=new BroadcastChannel(f);return this.loggerWrapper.debug("Posting message to popup channel",JSON.stringify({code:T,exchangeError:U})),e.postMessage({data:{code:T,exchangeError:U},action:"code"}),this.loggerWrapper.debug("Popup channel message posted, closing channel"),e.close(),this.loggerWrapper.debug("Popup channel closed, closing window"),void window.close()}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(C===r.loadForm&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>c(e)))){if(!H||!_)return void this.loggerWrapper.error("Did not get saml idp params data to load");S(H,_,G||"",O)}if(C===r.redirect&&(c("redirectTo")||c("deferredRedirect"))){if(!W)return void this.loggerWrapper.error("Did not get redirect url");if("android"===F&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${x}`),x){this.loggerWrapper.debug("Opening redirect in popup");const t=y(W,"?",598,700);this.loggerWrapper.debug("Creating broadcast channel");const i=new BroadcastChannel(f);this.loggerWrapper.debug("Starting popup closed detection");const s=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event and clearing interval"),clearInterval(s),e(this,Z,"m",Le).call(this,"popupclosed",{}),this.loggerWrapper.debug("Closing channel"),i.close())}),1e3);this.loggerWrapper.debug("Listening for postMessage on channel");const o=e=>{if(this.loggerWrapper.debug("Received postMessage on channel",JSON.stringify(e)),this.loggerWrapper.debug("Comparing origins",JSON.stringify({eventOrigin:e.origin,windowLocationOrigin:window.location.origin})),e.origin!==window.location.origin)return;this.loggerWrapper.debug("PostMessage origin matches, processing message");const{action:t,data:i}=e.data;this.loggerWrapper.debug(`PostMessage action: ${t}, data: ${JSON.stringify(i)}`),"code"===t&&(this.loggerWrapper.debug("Updating flow state with code and exchangeError"),this.flowState.update({code:i.code,exchangeError:i.exchangeError}))};i.onmessage=o}else this.handleRedirect(W);return}if(C===r.webauthnCreate||C===r.webauthnGet){if(!P||!N)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=C===r.webauthnCreate?yield this.sdk.webauthn.helpers.create(N):yield this.sdk.webauthn.helpers.get(N)}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(C===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:Ie,oidcErrorRedirectUri:Ce,oidcResource:ke,samlIdpUsername:Re}=Y,We={direction:I(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:Ie,oidcErrorRedirectUri:Ce,oidcResource:ke,action:C},Oe=J(de);w(ee,Y)?We.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:ge},Y),{lastAuth:Oe,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({},this.formConfigValues),E(s)),T&&{exchangeCode:T,idpInitiated:!0}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j&&{token:j}));return e(this,be,"f").call(this,i),i})):(c("projectId")||c("baseUrl")||c("executionId")||c("stepId"))&&(We.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,m,t,ce.version,he.componentsVersion,E(s));return e(this,be,"f").call(this,i),i}))),this.loggerWrapper.debug("Got a screen with id",We.screenId),yield e(this,Z,"m",ue).call(this,We),this.stepState.update(We)}))}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(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),$(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),q(n,g,h.cssVars,this.loggerWrapper),n.replaceChildren(g);const r=!s.htmlFilename;setTimeout((()=>{e(this,Z,"m",Ee).call(this),this.validateOnBlur&&x(n),M(n,h),e(this,Z,"m",Ie).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),C(n,this.autoFocus,r)})),e(this,Z,"m",Te).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}])`))}}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",Le).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=""}))})),C(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",Ie).call(this,{isFirstScreen:h,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)})))}}))},Ie=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,Z,"m",Le).call(this,"ready",{}),i||e(this,Z,"m",re).call(this,s),e(this,Z,"m",Le).call(this,"page-updated",{screenName:s}),e(this,Z,"m",Le).call(this,"screen-updated",{screenName:s})},Ce=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})),{})}))},We=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())}))},Oe=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)}},Ee=function(){j();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,Z,"m",xe).call(this,t)))},xe=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){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)}))}))},Te=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",je).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:""})})))}))}))},Le=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))};export{Ue as default};
|
|
2
2
|
//# sourceMappingURL=DescopeWc.js.map
|