@descope/web-component 3.49.2 → 3.50.0
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/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/templates.js +1 -1
- package/dist/cjs/helpers/templates.js.map +1 -1
- package/dist/cjs/types.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/templates.js +1 -1
- package/dist/esm/helpers/templates.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"templates.js","sources":["../../../src/lib/helpers/templates.ts"],"sourcesContent":["import { escapeMarkdown } from '@descope/escape-markdown';\nimport {\n ELEMENT_TYPE_ATTRIBUTE,\n DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,\n HAS_DYNAMIC_VALUES_ATTR_NAME,\n} from '../constants';\nimport { ComponentsConfig, CssVars, ScreenState } from '../types';\nimport { shouldHandleMarkdown } from './helpers';\n\nconst ALLOWED_INPUT_CONFIG_ATTRS = ['disabled'];\n\nexport const replaceElementMessage = (\n baseEle: HTMLElement,\n eleType: string,\n message = '',\n) => {\n const eleList = baseEle.querySelectorAll(\n `[${ELEMENT_TYPE_ATTRIBUTE}=\"${eleType}\"]`,\n );\n eleList.forEach((ele: HTMLElement) => {\n // eslint-disable-next-line no-param-reassign\n ele.textContent = message;\n ele.classList[message ? 'remove' : 'add']('hide');\n });\n};\n\n/**\n * Replace the 'value' attribute of screen inputs with screen state's inputs.\n * For example: if base element contains '<input name=\"key1\" ...>' and screen input is in form of { key1: 'val1' },\n * it will add 'val1' as the input value\n */\nconst replaceElementInputs = (\n baseEle: HTMLElement,\n screenInputs: Record<string, string>,\n) => {\n Object.entries(screenInputs || {}).forEach(([name, value]) => {\n const inputEls = Array.from(\n baseEle.querySelectorAll(\n `*[name=\"${name}\"]:not([${DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`,\n ),\n ) as HTMLInputElement[];\n inputEls.forEach((inputEle) => {\n // eslint-disable-next-line no-param-reassign\n inputEle.value = value;\n });\n });\n};\n\n/**\n * Get object nested path.\n * Examples:\n * - getByPath({ { a { b: 'rob' } }, 'a.b') => 'hey rob'\n * - getByPath({}, 'a.b') => ''\n */\nconst getByPath = (obj: Record<string, any>, path: string) =>\n path.split('.').reduce((prev, next) => prev?.[next] || '', obj);\n\n/**\n * Apply template language on text, based on screen state.\n * Examples:\n * - 'hey {{a.b}}', { a { b: 'rob' }} => 'hey rob'\n * - 'hey {{not.exists}}', {} => 'hey '\n */\nconst applyTemplates = (\n text: string,\n screenState?: Record<string, any>,\n handleMarkdown?: boolean,\n): string =>\n text.replace(/{{(.+?)}}/g, (_, match) =>\n handleMarkdown\n ? escapeMarkdown(getByPath(screenState, match))\n : getByPath(screenState, match),\n );\n\n/**\n * Replace the templates of content of inner text/link elements with screen state data\n */\nconst replaceElementTemplates = (\n baseEle: DocumentFragment,\n screenState?: Record<string, any>,\n) => {\n const eleList = baseEle.querySelectorAll(\n 'descope-text,descope-link,descope-enriched-text,descope-code-snippet',\n );\n eleList.forEach((inEle: HTMLElement) => {\n const handleMarkdown = shouldHandleMarkdown(inEle.localName);\n // eslint-disable-next-line no-param-reassign\n inEle.textContent = applyTemplates(\n inEle.textContent,\n screenState,\n handleMarkdown,\n );\n const href = inEle.getAttribute('href');\n if (href) {\n inEle.setAttribute('href', applyTemplates(href, screenState));\n }\n });\n};\n\nconst replaceTemplateDynamicAttrValues = (\n baseEle: DocumentFragment,\n screenState?: Record<string, any>,\n) => {\n const eleList = baseEle.querySelectorAll(`[${HAS_DYNAMIC_VALUES_ATTR_NAME}]`);\n eleList.forEach((ele: HTMLElement) => {\n Array.from(ele.attributes).forEach((attr) => {\n // eslint-disable-next-line no-param-reassign\n attr.value = applyTemplates(attr.value, screenState);\n });\n });\n};\n\nconst replaceHrefByDataType = (\n baseEle: DocumentFragment,\n dataType: string,\n provisionUrl?: string,\n) => {\n const eleList = baseEle.querySelectorAll(\n `[${ELEMENT_TYPE_ATTRIBUTE}=\"${dataType}\"]`,\n );\n eleList.forEach((ele: HTMLLinkElement) => {\n // eslint-disable-next-line no-param-reassign\n ele.setAttribute('href', provisionUrl);\n });\n};\n\nconst setFormConfigValues = (\n baseEle: DocumentFragment,\n formData: Record<string, string>,\n) => {\n Object.entries(formData).forEach(([name, config]) => {\n const eles = baseEle.querySelectorAll(`[name=\"${name}\"]`);\n\n eles.forEach((ele) => {\n Object.entries(config).forEach(([attrName, attrValue]) => {\n if (ALLOWED_INPUT_CONFIG_ATTRS.includes(attrName)) {\n ele.setAttribute(attrName, attrValue);\n }\n });\n });\n });\n};\n\nexport const setCssVars = (\n rootEle: HTMLElement,\n nextPageTemplate: DocumentFragment,\n cssVars: CssVars,\n logger: {\n error: (message: string, description: string) => void;\n info: (message: string, description: string) => void;\n debug: (message: string, description: string) => void;\n },\n) => {\n if (!cssVars) {\n return;\n }\n\n Object.keys(cssVars).forEach((componentName) => {\n if (!nextPageTemplate.querySelector(componentName)) {\n logger.debug(\n `Skipping css vars for component \"${componentName}\"`,\n `Got css vars for component ${componentName} but Could not find it on next page`,\n );\n\n return;\n }\n const componentClass:\n | (CustomElementConstructor & { cssVarList: CssVars })\n | undefined = customElements.get(componentName) as any;\n\n if (!componentClass) {\n logger.debug(\n `Could not find component class for ${componentName}`,\n 'Check if the component is registered',\n );\n\n return;\n }\n\n Object.keys(cssVars[componentName]).forEach((cssVarKey) => {\n const componentCssVars = cssVars[componentName];\n const varName = componentClass?.cssVarList?.[cssVarKey];\n\n if (!varName) {\n logger.info(\n `Could not find css variable name for ${cssVarKey} in ${componentName}`,\n 'Check if the css variable is defined in the component',\n );\n return;\n }\n\n const value = componentCssVars[cssVarKey];\n\n rootEle.style.setProperty(varName, value);\n });\n });\n};\n\nconst setElementConfig = (\n baseEle: DocumentFragment,\n componentsConfig: ComponentsConfig,\n logger?: { error: (message: string, description: string) => void },\n) => {\n if (!componentsConfig) {\n return;\n }\n const { componentsDynamicAttrs, ...rest } = componentsConfig;\n\n const configMap = Object.keys(rest).reduce((acc, componentName) => {\n acc[`[name=${componentName}]`] = rest[componentName];\n return acc;\n }, {});\n\n if (componentsDynamicAttrs) {\n Object.keys(componentsDynamicAttrs).forEach((componentSelector) => {\n const componentDynamicAttrs = componentsDynamicAttrs[componentSelector];\n if (componentDynamicAttrs) {\n const { attributes } = componentDynamicAttrs;\n if (attributes && Object.keys(attributes).length) {\n configMap[componentSelector] = attributes;\n }\n }\n });\n }\n\n // collect components that needs configuration from DOM\n Object.keys(configMap).forEach((componentsSelector) => {\n baseEle.querySelectorAll(componentsSelector).forEach((comp) => {\n const config = configMap[componentsSelector];\n\n Object.keys(config).forEach((attr) => {\n let value = config[attr];\n\n if (typeof value !== 'string') {\n try {\n value = JSON.stringify(value);\n } catch (e) {\n logger.error(\n `Could not stringify value \"${value}\" for \"${attr}\"`,\n e.message,\n );\n value = '';\n }\n }\n\n comp.setAttribute(attr, value);\n });\n });\n });\n};\n\nconst setImageVariable = (\n rootEle: HTMLElement,\n name: string,\n image?: string,\n) => {\n const imageVarName = (\n customElements.get(name) as CustomElementConstructor & {\n cssVarList: Record<string, string>;\n }\n )?.cssVarList.url;\n\n if (image && imageVarName) {\n rootEle?.style?.setProperty(\n imageVarName,\n `url(data:image/jpg;base64,${image})`,\n );\n }\n};\n\n/**\n * Update a screen template based on the screen state\n * - Show/hide error messages\n * - Replace element templates ({{...}} syntax) with screen state object\n */\nexport const updateTemplateFromScreenState = (\n baseEle: DocumentFragment,\n screenState?: ScreenState,\n componentsConfig?: ComponentsConfig,\n flowInputs?: Record<string, string>,\n logger?: { error: (message: string, description: string) => void },\n) => {\n replaceHrefByDataType(baseEle, 'totp-link', screenState?.totp?.provisionUrl);\n replaceHrefByDataType(baseEle, 'notp-link', screenState?.notp?.redirectUrl);\n replaceElementTemplates(baseEle, screenState);\n setElementConfig(baseEle, componentsConfig, logger);\n replaceTemplateDynamicAttrValues(baseEle, screenState);\n setFormConfigValues(baseEle, flowInputs);\n};\n\n/**\n * Update a screen based on a screen state\n * - Replace values of element inputs with screen state's inputs\n */\nexport const updateScreenFromScreenState = (\n baseEle: HTMLElement,\n screenState?: ScreenState,\n) => {\n replaceElementInputs(baseEle, screenState?.inputs);\n replaceElementInputs(baseEle, screenState?.form);\n};\n\nexport const setTOTPVariable = (rootEle: HTMLElement, image?: string) => {\n setImageVariable(rootEle, 'descope-totp-image', image);\n};\n\nexport const setNOTPVariable = (rootEle: HTMLElement, image?: string) => {\n setImageVariable(rootEle, 'descope-notp-image', image);\n};\n\nexport const setPhoneAutoDetectDefaultCode = (\n fragment: DocumentFragment,\n autoDetectCode?: string,\n) => {\n Array.from(fragment.querySelectorAll('[default-code=\"autoDetect\"]')).forEach(\n (phoneEle) => {\n phoneEle.setAttribute('default-code', autoDetectCode);\n },\n );\n};\n\nexport const disableWebauthnButtons = (fragment: DocumentFragment) => {\n const webauthnButtons = fragment.querySelectorAll(\n `descope-button[${ELEMENT_TYPE_ATTRIBUTE}=\"biometrics\"]`,\n );\n webauthnButtons.forEach((button) => button.setAttribute('disabled', 'true'));\n};\n\nexport const getDescopeUiComponentsList = (clone: DocumentFragment) => [\n ...Array.from(clone.querySelectorAll('*')).reduce<Set<string>>(\n (acc, el: HTMLElement) =>\n el.tagName.startsWith('DESCOPE-')\n ? acc.add(el.tagName.toLocaleLowerCase())\n : acc,\n new Set(),\n ),\n];\n"],"names":["ALLOWED_INPUT_CONFIG_ATTRS","replaceElementInputs","baseEle","screenInputs","Object","entries","forEach","name","value","Array","from","querySelectorAll","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","inputEle","getByPath","obj","path","split","reduce","prev","next","applyTemplates","text","screenState","handleMarkdown","replace","_","match","escapeMarkdown","replaceHrefByDataType","dataType","provisionUrl","ELEMENT_TYPE_ATTRIBUTE","ele","setAttribute","setImageVariable","rootEle","image","imageVarName","_a","customElements","get","cssVarList","url","_b","style","setProperty","fragment","button","eleType","message","textContent","classList","nextPageTemplate","cssVars","logger","keys","componentName","querySelector","debug","componentClass","cssVarKey","componentCssVars","varName","info","autoDetectCode","phoneEle","inputs","form","componentsConfig","flowInputs","totp","notp","redirectUrl","inEle","shouldHandleMarkdown","localName","href","getAttribute","replaceElementTemplates","componentsDynamicAttrs","rest","__rest","configMap","acc","componentSelector","componentDynamicAttrs","attributes","length","componentsSelector","comp","config","attr","JSON","stringify","e","error","setElementConfig","HAS_DYNAMIC_VALUES_ATTR_NAME","replaceTemplateDynamicAttrValues","formData","attrName","attrValue","includes","setFormConfigValues"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"templates.js","sources":["../../../src/lib/helpers/templates.ts"],"sourcesContent":["import { escapeMarkdown } from '@descope/escape-markdown';\nimport {\n ELEMENT_TYPE_ATTRIBUTE,\n DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,\n HAS_DYNAMIC_VALUES_ATTR_NAME,\n} from '../constants';\nimport { ComponentsConfig, CssVars, ScreenState } from '../types';\nimport { shouldHandleMarkdown } from './helpers';\n\nconst ALLOWED_INPUT_CONFIG_ATTRS = ['disabled'];\n\nexport const replaceElementMessage = (\n baseEle: HTMLElement,\n eleType: string,\n message = '',\n) => {\n const eleList = baseEle.querySelectorAll(\n `[${ELEMENT_TYPE_ATTRIBUTE}=\"${eleType}\"]`,\n );\n eleList.forEach((ele: HTMLElement) => {\n // eslint-disable-next-line no-param-reassign\n ele.textContent = message;\n ele.classList[message ? 'remove' : 'add']('hide');\n });\n};\n\n/**\n * Replace the 'value' attribute of screen inputs with screen state's inputs.\n * For example: if base element contains '<input name=\"key1\" ...>' and screen input is in form of { key1: 'val1' },\n * it will add 'val1' as the input value\n */\nconst replaceElementInputs = (\n baseEle: HTMLElement,\n screenInputs: Record<string, string>,\n) => {\n Object.entries(screenInputs || {}).forEach(([name, value]) => {\n const inputEls = Array.from(\n baseEle.querySelectorAll(\n `*[name=\"${name}\"]:not([${DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`,\n ),\n ) as HTMLInputElement[];\n inputEls.forEach((inputEle) => {\n // eslint-disable-next-line no-param-reassign\n inputEle.value = value;\n });\n });\n};\n\n/**\n * Get object nested path.\n * Examples:\n * - getByPath({ { a { b: 'rob' } }, 'a.b') => 'hey rob'\n * - getByPath({}, 'a.b') => ''\n */\nconst getByPath = (obj: Record<string, any>, path: string) =>\n path.split('.').reduce((prev, next) => prev?.[next] || '', obj);\n\n/**\n * Apply template language on text, based on screen state.\n * Examples:\n * - 'hey {{a.b}}', { a { b: 'rob' }} => 'hey rob'\n * - 'hey {{not.exists}}', {} => 'hey '\n */\nconst applyTemplates = (\n text: string,\n screenState?: Record<string, any>,\n handleMarkdown?: boolean,\n): string =>\n text.replace(/{{(.+?)}}/g, (_, match) =>\n handleMarkdown\n ? escapeMarkdown(getByPath(screenState, match))\n : getByPath(screenState, match),\n );\n\n/**\n * Replace the templates of content of inner text/link elements with screen state data\n */\nconst replaceElementTemplates = (\n baseEle: DocumentFragment,\n screenState?: Record<string, any>,\n) => {\n const eleList = baseEle.querySelectorAll(\n 'descope-text,descope-link,descope-enriched-text,descope-code-snippet',\n );\n eleList.forEach((inEle: HTMLElement) => {\n const handleMarkdown = shouldHandleMarkdown(inEle.localName);\n // eslint-disable-next-line no-param-reassign\n inEle.textContent = applyTemplates(\n inEle.textContent,\n screenState,\n handleMarkdown,\n );\n const href = inEle.getAttribute('href');\n if (href) {\n inEle.setAttribute('href', applyTemplates(href, screenState));\n }\n });\n};\n\nconst replaceTemplateDynamicAttrValues = (\n baseEle: DocumentFragment,\n screenState?: Record<string, any>,\n) => {\n const eleList = baseEle.querySelectorAll(`[${HAS_DYNAMIC_VALUES_ATTR_NAME}]`);\n eleList.forEach((ele: HTMLElement) => {\n Array.from(ele.attributes).forEach((attr) => {\n // eslint-disable-next-line no-param-reassign\n attr.value = applyTemplates(attr.value, screenState);\n });\n });\n};\n\nconst replaceHrefByDataType = (\n baseEle: DocumentFragment,\n dataType: string,\n provisionUrl?: string,\n) => {\n const eleList = baseEle.querySelectorAll(\n `[${ELEMENT_TYPE_ATTRIBUTE}=\"${dataType}\"]`,\n );\n eleList.forEach((ele: HTMLLinkElement) => {\n // eslint-disable-next-line no-param-reassign\n ele.setAttribute('href', provisionUrl);\n });\n};\n\nconst setFormConfigValues = (\n baseEle: DocumentFragment,\n formData: Record<string, string>,\n) => {\n Object.entries(formData).forEach(([name, config]) => {\n const eles = baseEle.querySelectorAll(`[name=\"${name}\"]`);\n\n eles.forEach((ele) => {\n Object.entries(config).forEach(([attrName, attrValue]) => {\n if (ALLOWED_INPUT_CONFIG_ATTRS.includes(attrName)) {\n ele.setAttribute(attrName, attrValue);\n }\n });\n });\n });\n};\n\nexport const setCssVars = (\n rootEle: HTMLElement,\n nextPageTemplate: DocumentFragment,\n cssVars: CssVars,\n logger: {\n error: (message: string, description: string) => void;\n info: (message: string, description: string) => void;\n debug: (message: string, description: string) => void;\n },\n) => {\n if (!cssVars) {\n return;\n }\n\n Object.keys(cssVars).forEach((componentName) => {\n if (!nextPageTemplate.querySelector(componentName)) {\n logger.debug(\n `Skipping css vars for component \"${componentName}\"`,\n `Got css vars for component ${componentName} but Could not find it on next page`,\n );\n\n return;\n }\n const componentClass:\n | (CustomElementConstructor & { cssVarList: CssVars })\n | undefined = customElements.get(componentName) as any;\n\n if (!componentClass) {\n logger.debug(\n `Could not find component class for ${componentName}`,\n 'Check if the component is registered',\n );\n\n return;\n }\n\n Object.keys(cssVars[componentName]).forEach((cssVarKey) => {\n const componentCssVars = cssVars[componentName];\n const varName = componentClass?.cssVarList?.[cssVarKey];\n\n if (!varName) {\n logger.info(\n `Could not find css variable name for ${cssVarKey} in ${componentName}`,\n 'Check if the css variable is defined in the component',\n );\n return;\n }\n\n const value = componentCssVars[cssVarKey];\n\n rootEle.style.setProperty(varName, value);\n });\n });\n};\n\nconst setElementConfig = (\n baseEle: DocumentFragment,\n componentsConfig: ComponentsConfig,\n logger?: { error: (message: string, description: string) => void },\n) => {\n if (!componentsConfig) {\n return;\n }\n const { componentsDynamicAttrs, ...rest } = componentsConfig;\n\n const configMap = Object.keys(rest).reduce((acc, componentName) => {\n acc[`[name=${componentName}]`] = rest[componentName];\n return acc;\n }, {});\n\n if (componentsDynamicAttrs) {\n Object.keys(componentsDynamicAttrs).forEach((componentSelector) => {\n const componentDynamicAttrs = componentsDynamicAttrs[componentSelector];\n if (componentDynamicAttrs) {\n const { attributes } = componentDynamicAttrs;\n if (attributes && Object.keys(attributes).length) {\n configMap[componentSelector] = attributes;\n }\n }\n });\n }\n\n // collect components that needs configuration from DOM\n Object.keys(configMap).forEach((componentsSelector) => {\n baseEle.querySelectorAll(componentsSelector).forEach((comp) => {\n const config = configMap[componentsSelector];\n\n Object.keys(config).forEach((attr) => {\n let value = config[attr];\n\n if (typeof value !== 'string') {\n try {\n value = JSON.stringify(value);\n } catch (e) {\n logger.error(\n `Could not stringify value \"${value}\" for \"${attr}\"`,\n e.message,\n );\n value = '';\n }\n }\n\n comp.setAttribute(attr, value);\n });\n });\n });\n};\n\nconst setImageVariable = (\n rootEle: HTMLElement,\n name: string,\n image?: string,\n) => {\n const imageVarName = (\n customElements.get(name) as CustomElementConstructor & {\n cssVarList: Record<string, string>;\n }\n )?.cssVarList.url;\n\n if (image && imageVarName) {\n rootEle?.style?.setProperty(\n imageVarName,\n `url(data:image/jpg;base64,${image})`,\n );\n }\n};\n\nconst applyComponentsState = (\n baseEle: DocumentFragment,\n componentsState: Record<string, string> = {},\n logger?: { error: (message: string, description: string) => void },\n) => {\n Object.entries(componentsState).forEach(([componentId, state]) => {\n const componentEls = baseEle.querySelectorAll(`[id=\"${CSS.escape(componentId)}\"]`);\n componentEls.forEach((compEl) => {\n switch (state) {\n case 'disable':\n compEl.setAttribute('disabled', 'true');\n break;\n case 'hide':\n compEl.classList.add('hidden');\n break;\n default:\n logger?.error(\n `Unknown component state \"${state}\" for component with id \"${componentId}\"`,\n 'Valid states are \"disable\" and \"hide\"',\n );\n break;\n }\n });\n });\n};\n\n/**\n * Update a screen template based on the screen state\n * - Show/hide error messages\n * - Replace element templates ({{...}} syntax) with screen state object\n */\nexport const updateTemplateFromScreenState = (\n baseEle: DocumentFragment,\n screenState?: ScreenState,\n flowInputs?: Record<string, string>,\n logger?: { error: (message: string, description: string) => void },\n) => {\n replaceHrefByDataType(baseEle, 'totp-link', screenState?.totp?.provisionUrl);\n replaceHrefByDataType(baseEle, 'notp-link', screenState?.notp?.redirectUrl);\n replaceElementTemplates(baseEle, screenState);\n setElementConfig(baseEle, screenState?.componentsConfig, logger);\n replaceTemplateDynamicAttrValues(baseEle, screenState);\n setFormConfigValues(baseEle, flowInputs);\n applyComponentsState(baseEle, screenState?.componentsState, logger);\n};\n\n/**\n * Update a screen based on a screen state\n * - Replace values of element inputs with screen state's inputs\n */\nexport const updateScreenFromScreenState = (\n baseEle: HTMLElement,\n screenState?: ScreenState,\n) => {\n replaceElementInputs(baseEle, screenState?.inputs);\n replaceElementInputs(baseEle, screenState?.form);\n};\n\nexport const setTOTPVariable = (rootEle: HTMLElement, image?: string) => {\n setImageVariable(rootEle, 'descope-totp-image', image);\n};\n\nexport const setNOTPVariable = (rootEle: HTMLElement, image?: string) => {\n setImageVariable(rootEle, 'descope-notp-image', image);\n};\n\nexport const setPhoneAutoDetectDefaultCode = (\n fragment: DocumentFragment,\n autoDetectCode?: string,\n) => {\n Array.from(fragment.querySelectorAll('[default-code=\"autoDetect\"]')).forEach(\n (phoneEle) => {\n phoneEle.setAttribute('default-code', autoDetectCode);\n },\n );\n};\n\nexport const disableWebauthnButtons = (fragment: DocumentFragment) => {\n const webauthnButtons = fragment.querySelectorAll(\n `descope-button[${ELEMENT_TYPE_ATTRIBUTE}=\"biometrics\"]`,\n );\n webauthnButtons.forEach((button) => button.setAttribute('disabled', 'true'));\n};\n\nexport const getDescopeUiComponentsList = (clone: DocumentFragment) => [\n ...Array.from(clone.querySelectorAll('*')).reduce<Set<string>>(\n (acc, el: HTMLElement) =>\n el.tagName.startsWith('DESCOPE-')\n ? acc.add(el.tagName.toLocaleLowerCase())\n : acc,\n new Set(),\n ),\n];\n"],"names":["ALLOWED_INPUT_CONFIG_ATTRS","replaceElementInputs","baseEle","screenInputs","Object","entries","forEach","name","value","Array","from","querySelectorAll","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","inputEle","getByPath","obj","path","split","reduce","prev","next","applyTemplates","text","screenState","handleMarkdown","replace","_","match","escapeMarkdown","replaceHrefByDataType","dataType","provisionUrl","ELEMENT_TYPE_ATTRIBUTE","ele","setAttribute","setImageVariable","rootEle","image","imageVarName","_a","customElements","get","cssVarList","url","_b","style","setProperty","fragment","button","eleType","message","textContent","classList","nextPageTemplate","cssVars","logger","keys","componentName","querySelector","debug","componentClass","cssVarKey","componentCssVars","varName","info","autoDetectCode","phoneEle","inputs","form","flowInputs","totp","notp","redirectUrl","inEle","shouldHandleMarkdown","localName","href","getAttribute","replaceElementTemplates","componentsConfig","componentsDynamicAttrs","rest","__rest","configMap","acc","componentSelector","componentDynamicAttrs","attributes","length","componentsSelector","comp","config","attr","JSON","stringify","e","error","setElementConfig","HAS_DYNAMIC_VALUES_ATTR_NAME","replaceTemplateDynamicAttrValues","formData","attrName","attrValue","includes","setFormConfigValues","componentsState","componentId","state","CSS","escape","compEl","add","applyComponentsState"],"mappings":"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"}
|
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 type { JWTResponse } from '@descope/web-js-sdk';\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 /**\n * Unique identifier of the module.\n */\n id: string;\n /**\n * Notifies the module that it should start any profiling or monitoring.\n */\n start?: () => void;\n /**\n * Notifies the module that it should stop any profiling or monitoring.\n */\n stop?: () => void;\n /**\n * Presents the user with any required interaction to get a refreshed token or state,\n * e.g., a challenge or captcha.\n *\n * Modules should return a value of true if the presentation completed successfully,\n * false if it was cancelled by the user, and throw an error in case of failure.\n *\n * This is called before form submission (via a next call) after a button click.\n */\n present?: () => Promise<boolean>;\n /**\n * Refreshes any tokens or state that might be needed before form submission.\n *\n * Modules should throw an error in case of failure.\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 lastAuth?: LastAuthState;\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\nexport type CustomStorage = {\n getItem: (key: string) => string | null;\n setItem: (key: string, value: string) => void;\n removeItem: (key: string) => void;\n};\n\nexport type FlowJWTResponse = JWTResponse & {\n flowOutput?: Record<string, any>;\n};\n"],"names":["Direction"],"mappings":"aAoCA,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 type { JWTResponse } from '@descope/web-js-sdk';\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 // map of component IDs to their state\n componentsState?: Record<string, string>;\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 /**\n * Unique identifier of the module.\n */\n id: string;\n /**\n * Notifies the module that it should start any profiling or monitoring.\n */\n start?: () => void;\n /**\n * Notifies the module that it should stop any profiling or monitoring.\n */\n stop?: () => void;\n /**\n * Presents the user with any required interaction to get a refreshed token or state,\n * e.g., a challenge or captcha.\n *\n * Modules should return a value of true if the presentation completed successfully,\n * false if it was cancelled by the user, and throw an error in case of failure.\n *\n * This is called before form submission (via a next call) after a button click.\n */\n present?: () => Promise<boolean>;\n /**\n * Refreshes any tokens or state that might be needed before form submission.\n *\n * Modules should throw an error in case of failure.\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 lastAuth?: LastAuthState;\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\nexport type CustomStorage = {\n getItem: (key: string) => string | null;\n setItem: (key: string, value: string) => void;\n removeItem: (key: string) => void;\n};\n\nexport type FlowJWTResponse = JWTResponse & {\n flowOutput?: Record<string, any>;\n};\n"],"names":["Direction"],"mappings":"aAoCA,IAAYA,EAAAA,QAGXA,eAAA,GAHWA,EAAAA,QAASA,YAATA,kBAGX,CAAA,IAFC,SAAA,WACAA,EAAA,QAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as r}from"@descope/sdk-helpers";import{staticResourcesMixin as o}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as s}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{createSdk as u}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as a}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as g,fetchContent as f}from"../helpers/helpers.js";import p from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as m}from"../helpers/storage.js";import{transformFlowInputFormData as b,extractNestedAttribute as v}from"../helpers/flowInputs.js";import{formMountMixin as w}from"../mixins/formMountMixin.js";import{CONFIG_FILENAME as k,PREV_VER_ASSETS_FOLDER as C}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as y}from"../constants/general.js";var A,x,I,j,E,L,S,U,M,O,W,D,P,N,F,K,R,T,B,H,J,V;const q=r(s,o,w,n)(HTMLElement);class z extends q{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(r){super(),A.add(this),I.set(this,!1),j.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,A,"m",V).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},E.set(this,new p),L.set(this,new p),S.set(this,{}),this.getComponentsContext=()=>t(this,S,"f"),this.nextRequestStatus=new p({isLoading:!1}),U.set(this,void 0),M.set(this,{popstate:t(this,A,"m",N).bind(this),componentsContext:t(this,A,"m",B).bind(this)}),O.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,O,r,"f"),t(this,A,"m",D).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get tenantId(){return this.getAttribute("tenant")||void 0}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return b(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return v(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t(this,j,"f")}set customStorage(t){if(t&&"function"!=typeof t.getItem)throw new Error("Custom storage must have a getItem method");if(t&&"function"!=typeof t.setItem)throw new Error("Custom storage must have a setItem method");if(t&&"function"!=typeof t.removeItem)throw new Error("Custom storage must have a removeItem method");i(this,j,t,"f"),m(t)}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),r=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=r.version)&&void 0!==e||(r.version=0),r}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,r;const o=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),s=a.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||o||s)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const u=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===u.length)return void u[0].click();const l=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const r=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=r.init)||void 0===e?void 0:e.call(this),t(this,L,"f").subscribe(t(this,A,"m",J).bind(this)),t(this,L,"f").update({isDebug:this.debug}),t(this,A,"m",P).call(this),yield t(this,A,"m",R).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const o=yield this.getConfig();if("isMissingConfig"in o&&o.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:s,stepId:n,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:g,redirectAuthCodeChallenge:f,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,M,"f").popstate),window.addEventListener("components-context",t(this,M,"f").componentsContext),t(this,E,"f").subscribe(t(this,A,"m",K).bind(this)),t(this,E,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:s,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:g,redirectAuthCodeChallenge:f,redirectAuthInitiator:p},m)),i(this,I,!0,"f")}))}disconnectedCallback(){t(this,E,"f").unsubscribeAll(),t(this,L,"f").unsubscribeAll(),t(this,A,"m",H).call(this),window.removeEventListener("popstate",t(this,M,"f").popstate),window.removeEventListener("components-context",t(this,M,"f").componentsContext)}attributeChangedCallback(e,i,r){if(this.shadowRoot.isConnected&&t(this,I,"f")&&i!==r&&x.observedAttributes.includes(e)){t(this,A,"m",P).call(this);const o=null===i;t(this,E,"f").update((({stepId:t,executionId:i})=>{let s=t,n=i;return o||(n=null,s=null,d()),{[c(e)]:r,stepId:s,executionId:n}})),t(this,L,"f").update({isDebug:this.debug})}}}x=z,I=new WeakMap,j=new WeakMap,E=new WeakMap,L=new WeakMap,S=new WeakMap,U=new WeakMap,M=new WeakMap,O=new WeakMap,A=new WeakSet,W=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},D=function(){t(this,A,"m",W).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},P=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id","outbound-app-id","outbound-app-scopes"];x.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},N=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,E,"f").update({stepId:e,executionId:i})},F=function(i,r){u&&"function"==typeof u||this.logger.error("SDK was not loaded properly",u,JSON.stringify(u));const o=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},x.sdkConfigOverrides),{projectId:i,baseUrl:r});t(this,j,"f")&&(o.customStorage=t(this,j,"f")),this.sdk=u(o),["start","next"].forEach((t=>{const i=this.sdk.flow[t];this.sdk.flow[t]=(...t)=>e(this,void 0,void 0,(function*(){try{return yield i(...t)}catch(t){return{error:{errorCode:y,errorDescription:t.toString()}}}}))}))},K=function(i,r,o){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:r}=i;if(o("projectId")||o("baseUrl")){if(!e)return;t(this,A,"m",F).call(this,e,r)}t(this,O,"f").call(this,i)}))},R=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,A,"m",T).call(this))}))},T=function(){return e(this,void 0,void 0,(function*(){const t=g({projectId:this.projectId,filename:k,assetsFolder:C,baseUrl:this.baseStaticUrl});try{return yield f(t,"json"),!0}catch(t){return!1}}))},B=function(e){i(this,S,Object.assign(Object.assign({},t(this,S,"f")),e.detail),"f")},H=function(){var e;null===(e=t(this,U,"f"))||void 0===e||e.remove(),i(this,U,null,"f")},J=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,U,document.createElement("descope-debugger"),"f"),Object.assign(t(this,U,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield import("../debugger-wc.js"),document.body.appendChild(t(this,U,"f"))):t(this,A,"m",H).call(this)}))},V=function(e,i){var r;e&&this.debug&&(null===(r=t(this,U,"f"))||void 0===r||r.updateData({title:e,description:i}))},z.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.49.2"}};export{z as default};
|
|
1
|
+
import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as r}from"@descope/sdk-helpers";import{staticResourcesMixin as o}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as s}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{createSdk as u}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as a}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as g,fetchContent as f}from"../helpers/helpers.js";import p from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as m}from"../helpers/storage.js";import{transformFlowInputFormData as b,extractNestedAttribute as v}from"../helpers/flowInputs.js";import{formMountMixin as w}from"../mixins/formMountMixin.js";import{CONFIG_FILENAME as k,PREV_VER_ASSETS_FOLDER as C}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as y}from"../constants/general.js";var A,x,I,j,E,L,S,U,M,O,W,D,P,N,F,K,R,T,B,H,J,V;const q=r(s,o,w,n)(HTMLElement);class z extends q{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(r){super(),A.add(this),I.set(this,!1),j.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,A,"m",V).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},E.set(this,new p),L.set(this,new p),S.set(this,{}),this.getComponentsContext=()=>t(this,S,"f"),this.nextRequestStatus=new p({isLoading:!1}),U.set(this,void 0),M.set(this,{popstate:t(this,A,"m",N).bind(this),componentsContext:t(this,A,"m",B).bind(this)}),O.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,O,r,"f"),t(this,A,"m",D).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get tenantId(){return this.getAttribute("tenant")||void 0}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return b(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return v(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t(this,j,"f")}set customStorage(t){if(t&&"function"!=typeof t.getItem)throw new Error("Custom storage must have a getItem method");if(t&&"function"!=typeof t.setItem)throw new Error("Custom storage must have a setItem method");if(t&&"function"!=typeof t.removeItem)throw new Error("Custom storage must have a removeItem method");i(this,j,t,"f"),m(t)}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),r=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=r.version)&&void 0!==e||(r.version=0),r}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,r;const o=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),s=a.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||o||s)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const u=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===u.length)return void u[0].click();const l=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const r=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=r.init)||void 0===e?void 0:e.call(this),t(this,L,"f").subscribe(t(this,A,"m",J).bind(this)),t(this,L,"f").update({isDebug:this.debug}),t(this,A,"m",P).call(this),yield t(this,A,"m",R).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const o=yield this.getConfig();if("isMissingConfig"in o&&o.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:s,stepId:n,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:g,redirectAuthCodeChallenge:f,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,M,"f").popstate),window.addEventListener("components-context",t(this,M,"f").componentsContext),t(this,E,"f").subscribe(t(this,A,"m",K).bind(this)),t(this,E,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:s,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:g,redirectAuthCodeChallenge:f,redirectAuthInitiator:p},m)),i(this,I,!0,"f")}))}disconnectedCallback(){t(this,E,"f").unsubscribeAll(),t(this,L,"f").unsubscribeAll(),t(this,A,"m",H).call(this),window.removeEventListener("popstate",t(this,M,"f").popstate),window.removeEventListener("components-context",t(this,M,"f").componentsContext)}attributeChangedCallback(e,i,r){if(this.shadowRoot.isConnected&&t(this,I,"f")&&i!==r&&x.observedAttributes.includes(e)){t(this,A,"m",P).call(this);const o=null===i;t(this,E,"f").update((({stepId:t,executionId:i})=>{let s=t,n=i;return o||(n=null,s=null,d()),{[c(e)]:r,stepId:s,executionId:n}})),t(this,L,"f").update({isDebug:this.debug})}}}x=z,I=new WeakMap,j=new WeakMap,E=new WeakMap,L=new WeakMap,S=new WeakMap,U=new WeakMap,M=new WeakMap,O=new WeakMap,A=new WeakSet,W=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},D=function(){t(this,A,"m",W).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},P=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id","outbound-app-id","outbound-app-scopes"];x.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},N=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,E,"f").update({stepId:e,executionId:i})},F=function(i,r){u&&"function"==typeof u||this.logger.error("SDK was not loaded properly",u,JSON.stringify(u));const o=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},x.sdkConfigOverrides),{projectId:i,baseUrl:r});t(this,j,"f")&&(o.customStorage=t(this,j,"f")),this.sdk=u(o),["start","next"].forEach((t=>{const i=this.sdk.flow[t];this.sdk.flow[t]=(...t)=>e(this,void 0,void 0,(function*(){try{return yield i(...t)}catch(t){return{error:{errorCode:y,errorDescription:t.toString()}}}}))}))},K=function(i,r,o){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:r}=i;if(o("projectId")||o("baseUrl")){if(!e)return;t(this,A,"m",F).call(this,e,r)}t(this,O,"f").call(this,i)}))},R=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,A,"m",T).call(this))}))},T=function(){return e(this,void 0,void 0,(function*(){const t=g({projectId:this.projectId,filename:k,assetsFolder:C,baseUrl:this.baseStaticUrl});try{return yield f(t,"json"),!0}catch(t){return!1}}))},B=function(e){i(this,S,Object.assign(Object.assign({},t(this,S,"f")),e.detail),"f")},H=function(){var e;null===(e=t(this,U,"f"))||void 0===e||e.remove(),i(this,U,null,"f")},J=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,U,document.createElement("descope-debugger"),"f"),Object.assign(t(this,U,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield import("../debugger-wc.js"),document.body.appendChild(t(this,U,"f"))):t(this,A,"m",H).call(this)}))},V=function(e,i){var r;e&&this.debug&&(null===(r=t(this,U,"f"))||void 0===r||r.updateData({title:e,description:i}))},z.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.50.0"}};export{z as default};
|
|
2
2
|
//# sourceMappingURL=BaseDescopeWc.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{ensureFingerprintIds as o,clearFingerprintData as n}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as r,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as l,URL_TOKEN_PARAM_NAME as d,URL_RUN_IDS_PARAM_NAME as c,SDK_SCRIPTS_LOAD_TIMEOUT as h,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as p,ELEMENT_TYPE_ATTRIBUTE as u,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as g}from"../constants/index.js";import{timeoutPromise as v,withMemCache as m,leadingDebounce as f,getUserLocale as b,showFirstScreenOnExecutionInit as w,injectSamlIdpForm as S,openCenteredPopup as y,getAnimationDirection as C,handleAutoFocus as I,transformStepStateForCustomScreen as k,getElementDescopeAttributes as R,getScriptResultPath as O,submitForm as W,transformScreenInputs as x,handleReportValidityOnBlur as E,getFirstNonEmptyValue as A,clearPreviousExternalInputs as j}from"../helpers/helpers.js";import T from"../helpers/state.js";import{disableWebauthnButtons as L,updateTemplateFromScreenState as U,setPhoneAutoDetectDefaultCode as P,setTOTPVariable as $,setNOTPVariable as N,setCssVars as M,updateScreenFromScreenState as q,replaceElementMessage as F}from"../helpers/templates.js";import{isConditionalLoginSupported as V}from"../helpers/webauthn.js";import{getABTestingKey as D}from"../helpers/abTestingKey.js";import{calculateConditions as B,calculateCondition as K}from"../helpers/conditions.js";import{setLastAuth as H,getLastAuth as _}from"../helpers/lastAuth.js";import G from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as J,FETCH_ERROR_RESPONSE_ERROR_CODE as z,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as Q,FLOW_TIMED_OUT_ERROR_CODE as X,POLLING_STATUS_NOT_FOUND_ERROR_CODE as Y}from"../constants/general.js";var Z,ee,te,ie,se,oe,ne,re,ae,le,de,ce,he,pe,ue,ge,ve,me,fe,be,we,Se,ye,Ce,Ie,ke,Re,Oe,We,xe,Ee,Ae,je,Te,Le,Ue,Pe;class $e extends G{static set sdkConfigOverrides(e){G.sdkConfigOverrides=e}static get sdkConfigOverrides(){return G.sdkConfigOverrides}constructor(){const s=new T({deferredRedirect:!1});super(s.update.bind(s)),Z.add(this),this.stepState=new T({}),ee.set(this,void 0),te.set(this,null),ie.set(this,null),se.set(this,{visibilitychange:e(this,Z,"m",oe).bind(this)}),this.bridgeVersion=2,this.nativeCallbacks={},pe.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},ge.set(this,(t=>{const i=()=>{this.contentRootElement.classList.toggle("hidden",t),this.slotElement.classList.toggle("hidden",!t),t&&(this.contentRootElement.innerHTML="")};t&&this.contentRootElement.hasChildNodes()?e(this,Z,"m",ve).call(this,i):i()})),me.set(this,((s,o,n,l,d=!1)=>{const c=[X,Y];if(this.flowState.current.action===r.poll){this.logger.debug("polling - Scheduling polling request");const r=Date.now(),h=d?500:2e3;t(this,ee,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const p=this.sdk.flow.next(s,o,a.polling,n,l,{}),u=document.hidden&&!d&&Date.now()-r>h+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield v(e,p)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,me,"f").call(this,s,o,n,l,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===J)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,me,"f").call(this,s,o,n,l);this.logger.debug("polling - Got a response"),(null==g?void 0:g.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(g.error,null,4)),(null===(i=null==g?void 0:g.error)||void 0===i?void 0:i.errorCode)&&c.includes(g.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):e(this,me,"f").call(this,s,o,n,l),e(this,be,"f").call(this,g)}))),h),"f")}})),fe.set(this,(()=>{clearTimeout(e(this,ee,"f")),t(this,ee,null,"f")})),be.set(this,(i=>{var s,o,n,a,l,d,c,h,p,u,g,v,m;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,r=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,Z,"m",Ue).call(this,"error",(null==i?void 0:i.error)||{errorCode:z,errorDescription:r,errorMessage:t}),this.loggerWrapper.error((null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorDescription)||t,(null===(l=null==i?void 0:i.error)||void 0===l?void 0:l.errorMessage)||r);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==Q&&c!==X||!this.isRestartOnError||e(this,Z,"m",he).call(this))}null===(h=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===h||h.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(p=i.data)||void 0===p?void 0:p.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(v=i.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:C}=i.data;if(y!==r.poll&&e(this,fe,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&H(S);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),void e(this,Z,"m",Ue).call(this,"success",t)}this.storeLastAuthenticatedUser&&H(S,!0),C&&window.open(C,"_blank");const{executionId:I,stepId:k,stepName:R,screen:O,redirect:W,webauthn:x,error:E,samlIdpResponse:A,nativeResponse:j}=i.data,T=Date.now();y!==r.poll?(this.loggerWrapper.info(`Step "${R||`#${k}`}" is ${b}`,"",{screen:O,status:b,stepId:k,stepName:R,action:y,error:E}),(null===(m=O.state)||void 0===m?void 0:m.clientScripts)&&t(this,ie,this.loadSdkScripts(O.state.clientScripts),"f"),this.flowState.update({stepId:k,stepName:R,executionId:I,action:y,redirectTo:null==W?void 0:W.url,redirectIsPopup:null==W?void 0:W.isPopup,screenId:null==O?void 0:O.id,screenState:null==O?void 0:O.state,webauthnTransactionId:null==x?void 0:x.transactionId,webauthnOptions:null==x?void 0:x.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,nativeResponseType:null==j?void 0:j.type,nativePayload:null==j?void 0:j.payload,reqTimestamp:T})):this.flowState.update({action:y,reqTimestamp:T})})),we.set(this,m((()=>i(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),Re.set(this,null),Ae.set(this,f(((t,s)=>i(this,void 0,void 0,(function*(){var i;if("true"===t.getAttribute("formnovalidate")||e(this,Z,"m",Ie).call(this)){const o=null==t?void 0:t.getAttribute("id");e(this,Z,"m",Oe).call(this,t);const n=yield e(this,Z,"m",ke).call(this),r=R(t);this.nextRequestStatus.update({isLoading:!0});const a=Object.assign(Object.assign(Object.assign({},r),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(o,a),this.nextRequestStatus.update({isLoading:!1}),e(this,Z,"m",We).call(this,n)}}))))),this.flowState=s}nativeResume(t,i){var s,o,n,r,a;const h=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let{exchangeCode:e}=h;if(!e){e=null===(s=new URL(h.url).searchParams)||void 0===s?void 0:s.get(l)}null===(n=(o=this.nativeCallbacks).complete)||void 0===n||n.call(o,{exchangeCode:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(h.url),i=t.searchParams.get(d),s=t.searchParams.get(c).split("_").pop();e(this,fe,"f").call(this),this.flowState.update({token:i,stepId:s,action:void 0})}else if("beforeScreen"===t){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=h;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=h,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(r=this.nativeCallbacks).complete)||void 0===a||a.call(r,h)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[O(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=Promise.all(null==e?void 0:e.map((e=>i(this,void 0,void 0,(function*(){var i,s;const o=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(o){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=o;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}yield this.injectNpmLib("@descope/flow-scripts","1.0.13",`dist/${e.id}.js`);const n=null===(s=globalThis.descope)||void 0===s?void 0:s[e.id];return new Promise(((i,s)=>{try{const s=n(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i),this.loggerWrapper);if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t),this.nextRequestStatus.subscribe((()=>{var t;this.loggerWrapper.debug("Unloading script",e.id),null===(t=s.stop)||void 0===t||t.call(s)}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),h)}));return Promise.race([s,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){if(!window.descopeBridge)return this._init();this.lazyInit=this._init}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,Z,"m",de).call(this),window.addEventListener("visibilitychange",e(this,se,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var i;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,fe,"f").call(this),null===(i=e(this,te,"f"))||void 0===i||i.abort(),t(this,te,null,"f"),window.removeEventListener("visibilitychange",e(this,se,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=b(e),o=yield this.getTargetLocales();return o.includes(s.locale)?i=`${t}-${s.locale}.html`:o.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(l,d,c){return i(this,void 0,void 0,(function*(){var h,p;const{projectId:u,flowId:g,tenant:v,stepId:m,executionId:f,action:I,screenId:k,screenState:R,redirectTo:O,redirectIsPopup:E,redirectUrl:A,token:j,code:T,isPopup:L,exchangeError:U,webauthnTransactionId:P,webauthnOptions:$,redirectAuthCodeChallenge:N,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:F,locale:V,samlIdpResponseUrl:H,samlIdpResponseSamlResponse:G,samlIdpResponseRelayState:J,nativeResponseType:z,nativePayload:Q,reqTimestamp:X}=l,Y=s(l,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","nativeResponseType","nativePayload","reqTimestamp"]);let ee,se,oe;const ne=D(),{outboundAppId:re}=this,{outboundAppScopes:le}=this,de=this.sdk.getLastUserLoginId(),ce=yield this.getFlowConfig(),he=yield this.getProjectConfig(),pe=Object.entries(he.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),ge=M&&N?{callbackUrl:M,codeChallenge:N,backupCallbackUri:q}:void 0,ve=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;let fe={};if(!f){const i=[...ce.clientScripts||[],...ce.sdkScripts||[]];if(ce.conditions){let e=[];({startScreenId:ee,conditionInteractionId:oe,startScreenName:se,clientScripts:e,componentsConfig:fe}=B({loginId:de,code:T,token:j,abTestingKey:ne,lastAuth:_(de)},ce.conditions)),i.push(...e||[])}else ce.condition?({startScreenId:ee,conditionInteractionId:oe}=K(ce.condition,{loginId:de,code:T,token:j,abTestingKey:ne,lastAuth:_(de)})):(se=ce.startScreenName,ee=ce.startScreenId);if(t(this,ie,this.loadSdkScripts(i),"f"),ce.fingerprintEnabled&&ce.fingerprintKey?yield o(ce.fingerprintKey,this.baseUrl):n(),!w(ee,Y)){const t=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:ge},Y),{client:this.client}),A&&{redirectUrl:A}),{lastAuth:_(de),abTestingKey:ne,locale:b(V).locale,nativeOptions:ve,outboundAppId:re,outboundAppScopes:le}),oe,"",he.componentsVersion,pe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),T?{exchangeCode:T,idpInitiated:!0}:{}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j?{token:j}:{}),Y.oidcLoginHint?{externalId:Y.oidcLoginHint}:{}));return e(this,be,"f").call(this,t),void("completed"!==(null===(h=null==t?void 0:t.data)||void 0===h?void 0:h.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:L,code:T,exchangeError:U,isCodeChanged:c("code"),isExchangeErrorChanged:c("exchangeError")})),L&&(c("code")&&T||c("exchangeError")&&U))return void e(this,Z,"m",Pe).call(this,f,T,U);if(f&&(c("token")&&j||c("code")&&T||c("exchangeError")&&U)){const t=yield this.sdk.flow.next(f,m,a.submit,ce.version,he.componentsVersion,{token:j,exchangeCode:T,exchangeError:U});return e(this,be,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(I===r.loadForm&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>c(e)))){if(!H||!G)return void this.loggerWrapper.error("Did not get saml idp params data to load");S(H,G,J||"",W)}if(I===r.redirect&&(c("redirectTo")||c("deferredRedirect"))){if(!O)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===O)return;if("android"===F&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${E}`),E){this.loggerWrapper.debug("Opening redirect in popup");const t=y(O,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));const s=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const t=i?this.popupOrigin:window.location.origin;if(e.origin!==t)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${t}"`);const{action:s,data:o}=e.data||{};"code"===s&&this.flowState.update({code:o.code,exchangeError:o.exchangeError})};let o;this.loggerWrapper.debug("Starting popup closed detection");const n=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(n),e(this,Z,"m",Ue).call(this,"popupclosed",{}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==o||o())}),1e3);if(i)window.addEventListener("message",s),o=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",s)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(f);e.onmessage=s,o=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(O),this.flowState.update({redirectTo:"no-op"}),e(this,Z,"m",Ue).call(this,"popupclosed",{});return}if(I===r.webauthnCreate||I===r.webauthnGet){if(!P||!$)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s;null===(p=e(this,te,"f"))||void 0===p||p.abort(),t(this,te,null,"f");try{i=I===r.webauthnCreate?yield this.sdk.webauthn.helpers.create($):yield this.sdk.webauthn.helpers.get($)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),s=e.name}const o=yield this.sdk.flow.next(f,m,a.submit,ce.version,he.componentsVersion,{transactionId:P,response:i,failure:s});e(this,be,"f").call(this,o)}if(I===r.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,m,a.submit,ce.version,he.componentsVersion,t);e(this,be,"f").call(this,i)})),void e(this,Z,"m",ae).call(this,z,Q);if(c("action")&&e(this,me,"f").call(this,f,m,ce.version,he.componentsVersion),!k&&!ee)return void this.loggerWrapper.warn("No screen was found to show");const we=ee||k,Se=yield this.getHtmlFilenameWithLocale(V,we),{oidcLoginHint:ye,oidcPrompt:Ce,oidcErrorRedirectUri:Ie,oidcResource:ke,samlIdpUsername:Re}=Y,Oe={direction:C(m,d.stepId),screenState:Object.assign(Object.assign({},R),{form:Object.assign(Object.assign({},this.formConfigValues),null==R?void 0:R.form),lastAuth:{loginId:de,name:this.sdk.getLastUserDisplayName()||de},componentsConfig:Object.assign(Object.assign(Object.assign({},ce.componentsConfig),fe),null==R?void 0:R.componentsConfig)}),htmlFilename:`${we}.html`,htmlLocaleFilename:Se,screenId:we,stepName:l.stepName||se,samlIdpUsername:Re,oidcLoginHint:ye,oidcPrompt:Ce,oidcErrorRedirectUri:Ie,oidcResource:ke,action:I},We=_(de);w(ee,Y)?Oe.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ce?void 0:ce.clientScripts)||[];yield e(this,Z,"m",je).call(this,i);const o=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:ge},Y),{lastAuth:We,preview:this.preview,abTestingKey:ne,client:this.client}),A&&{redirectUrl:A}),{locale:b(V).locale,nativeOptions:ve,outboundAppId:re,outboundAppScopes:le}),oe,t,he.componentsVersion,pe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),x(s)),T&&{exchangeCode:T,idpInitiated:!0}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j&&{token:j}));return e(this,be,"f").call(this,o),o})):(c("projectId")||c("baseUrl")||c("executionId")||c("stepId"))&&(Oe.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==R?void 0:R.clientScripts)||[];yield e(this,Z,"m",je).call(this,i);const o=yield this.sdk.flow.next(f,m,t,ce.version,he.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),x(s)));return e(this,be,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",Oe.screenId),yield e(this,Z,"m",ue).call(this,Oe),this.stepState.update(Oe)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n;const{htmlFilename:r,htmlLocaleFilename:l,direction:d,next:c,screenState:h}=t;this.loggerWrapper.debug("Rendering a flow screen");const p=document.createElement("template");p.innerHTML=yield this.getPageContent(r,l);const g=p.content.cloneNode(!0),v=this.loadDescopeUiComponents(p);this.sdk.webauthn.helpers.isSupported()?yield e(this,Z,"m",ye).call(this,g,c):L(g),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(n=h.form)||void 0===n?void 0:n.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),U(g,h,h.componentsConfig,this.formConfig,this.loggerWrapper);const{geo:m}=yield this.getExecutionContext();P(g,m);const f=()=>i(this,void 0,void 0,(function*(){var i,o;yield v;const n=this.contentRootElement;$(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),N(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),M(n,g,h.cssVars,this.loggerWrapper),n.replaceChildren(g);const r=!s.htmlFilename;setTimeout((()=>{e(this,Z,"m",xe).call(this),this.validateOnBlur&&E(n),q(n,h),e(this,Z,"m",Ce).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),I(n,this.autoFocus,r)})),e(this,Z,"m",Le).call(this,c);n.querySelector(`[${u}="polling"]`)&&c(a.polling,{})}));d?e(this,Z,"m",ve).call(this,f):f()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${p}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}ee=new WeakMap,te=new WeakMap,ie=new WeakMap,se=new WeakMap,pe=new WeakMap,ge=new WeakMap,me=new WeakMap,fe=new WeakMap,be=new WeakMap,we=new WeakMap,Re=new WeakMap,Ae=new WeakMap,Z=new WeakSet,oe=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},ne=function(t,s,o){return i(this,void 0,void 0,(function*(){var i;return(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&new Promise((i=>{this.nativeCallbacks.screenNext=o,this.nativeCallbacks.screenResolve=i,e(this,Z,"m",ae).call(this,"beforeScreen",{screen:t,context:s})}))}))},re=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,Z,"m",ae).call(this,"afterScreen",{screen:t})},ae=function(t,i){e(this,Z,"m",Ue).call(this,"bridge",{type:t,payload:i})},le=function({errorText:e,errorType:t}){const i=()=>{var i;let s=e;try{s=(null===(i=this.errorTransformer)||void 0===i?void 0:i.call(this,{text:e,type:t}))||e}catch(e){this.loggerWrapper.error("Error transforming error message",e.message)}F(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},de=function(){var t,i,o;null===(t=this.stepState)||void 0===t||t.subscribe(this.onStepChange.bind(this),(e=>{var t=e.screenState,i=s(void 0===t?{}:t,["errorText","errorType"]),o=s(e,["screenState"]);return Object.assign(Object.assign({},o),{screenState:i})})),null===(i=this.stepState)||void 0===i||i.subscribe(e(this,Z,"m",le).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(o=this.stepState)||void 0===o||o.subscribe(e(this,Z,"m",ce).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0})},ce=function({errorText:e,errorType:t}){(t||e)&&(this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((e=>{e.shadowRoot.querySelectorAll("descope-text-field[data-id]").forEach((e=>{e.value=""}))})),I(this.contentRootElement,this.autoFocus,!1))},he=function(){return i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update({stepId:null,executionId:null})):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},ue=function(o){return i(this,void 0,void 0,(function*(){var i;const n=Object.assign(Object.assign({},this.stepState.current),o),{next:r,stepName:a}=n,l=s(n,["next","stepName"]),d=k(l);let c=yield e(this,Z,"m",ne).call(this,a,d,r);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,a,d,r,this)));const h=!this.stepState.current.htmlFilename;if(e(this,ge,"f").call(this,c),e(this,pe,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,pe,c,"f"),c?this.stepState.unsubscribeAll():e(this,Z,"m",de).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,Z,"m",Ce).call(this,{isFirstScreen:h,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},ve=function(e){this.contentRootElement.addEventListener("transitionend",(()=>{this.loggerWrapper.debug("page switch transition end"),this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0}),this.loggerWrapper.debug("page switch transition start"),this.contentRootElement.classList.add("fade-out")},Se=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const i=`user-${t}`;e.setAttribute("name",i),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:i)}))}},ye=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,te,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield V())){const{options:s,transactionId:n}=(yield e(this,we,"f").call(this))||{};s&&n&&(e(this,Z,"m",Se).call(this,r),t(this,te,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,te,"f")).then((e=>i(this,void 0,void 0,(function*(){o(r.id,{transactionId:n,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},Ce=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,Z,"m",Ue).call(this,"ready",{}),i||e(this,Z,"m",re).call(this,s),e(this,Z,"m",Ue).call(this,"page-updated",{screenName:s}),e(this,Z,"m",Ue).call(this,"screen-updated",{screenName:s})},Ie=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"!==t.localName&&(null===(i=t.reportValidity)||void 0===i||i.call(t),e&&(e=null===(s=t.checkValidity)||void 0===s?void 0:s.call(t)))})),e},ke=function(){return i(this,void 0,void 0,(function*(){const e=this.getInputs();return(yield Promise.all(e.map((e=>i(this,void 0,void 0,(function*(){return{name:e.getAttribute("name"),value:e.value}})))))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},Oe=function(s){const o=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),n=()=>i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",n),s.removeAttribute("loading"),o.forEach((e=>{e.removeAttribute("disabled")}));const e=yield this.getFlowConfig(),t=[...e.clientScripts||[],...e.sdkScripts||[]];this.loadSdkScripts(t)})),r=()=>{var i;window.removeEventListener("pageshow",e(this,Re,"f")),t(this,Re,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),n())}),"f"),window.addEventListener("pageshow",e(this,Re,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&n(),this.removeEventListener("popupclosed",n),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},a=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?(this.addEventListener("popupclosed",n,{once:!0}),s.setAttribute("loading","true"),o.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(a),r())}))},We=function(e={}){var t,i;const s=A(e,["externalId","email","phone"]),o=A(e,["newPassword","password"]);if(s&&o)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:o});null===(i=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===i||i.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},xe=function(){j();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,Z,"m",Ee).call(this,t)))},Ee=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const i=t.getAttribute("slot"),s=`input-${e.id}-${i}`,o=document.createElement("slot");o.setAttribute("name",s),o.setAttribute("slot",i),e.appendChild(o),t.setAttribute("slot",s),this.appendChild(t)}))},je=function(t){return i(this,void 0,void 0,(function*(){if(e(this,ie,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ie,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-t).toString())}const i=this.loadSdkScriptsModules(),s=t.map((e=>e.id));for(const e of i)if(s.includes(e.id))try{if("function"==typeof e.present){(yield e.present())||this.loggerWrapper.debug(`Sdk script ${e.id} was cancelled`)}}catch(t){this.loggerWrapper.error(`Failed to present ${e.id} script module`,t.message)}let o=[];for(const e of i)"function"==typeof e.refresh&&o.push(e.refresh());if(o.length>0)try{yield v(h,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},Te=function(t){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((i=>{i.addEventListener("input",(()=>{var s;(null===(s=i.checkValidity)||void 0===s?void 0:s.call(i))&&e(this,Ae,"f").call(this,i,t)}))}))},Le=function(t){this.contentRootElement.querySelectorAll(`descope-button:not([${g}]), [data-type="button"]:not([${g}]`).forEach((i=>{i.onclick=()=>{e(this,Ae,"f").call(this,i,t)}})),e(this,Z,"m",Te).call(this,t),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${p}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},Ue=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},Pe=function(e,t,i){var s;const[o,n]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],r={data:{code:t,exchangeError:i},action:"code"};if("descope-wc"===o&&n){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",n);try{window.opener.postMessage(r,n)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(r),t.close()}try{window.close()}catch(e){}};export{$e as default};
|
|
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 O,submitForm as W,transformScreenInputs as x,handleReportValidityOnBlur as E,getFirstNonEmptyValue as A,clearPreviousExternalInputs as j}from"../helpers/helpers.js";import T from"../helpers/state.js";import{disableWebauthnButtons as L,updateTemplateFromScreenState as U,setPhoneAutoDetectDefaultCode as P,setTOTPVariable as $,setNOTPVariable as N,setCssVars as M,updateScreenFromScreenState as q,replaceElementMessage as F}from"../helpers/templates.js";import{isConditionalLoginSupported as V}from"../helpers/webauthn.js";import{getABTestingKey as D}from"../helpers/abTestingKey.js";import{calculateConditions as B,calculateCondition as K}from"../helpers/conditions.js";import{setLastAuth as H,getLastAuth as _}from"../helpers/lastAuth.js";import G from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as J,FETCH_ERROR_RESPONSE_ERROR_CODE as z,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as Q,FLOW_TIMED_OUT_ERROR_CODE as X,POLLING_STATUS_NOT_FOUND_ERROR_CODE as Y}from"../constants/general.js";var Z,ee,te,ie,se,oe,ne,re,ae,le,de,ce,he,pe,ue,ge,ve,me,fe,be,we,Se,ye,Ie,Ce,ke,Re,Oe,We,xe,Ee,Ae,je,Te,Le,Ue,Pe;class $e extends G{static set sdkConfigOverrides(e){G.sdkConfigOverrides=e}static get sdkConfigOverrides(){return G.sdkConfigOverrides}constructor(){const s=new T({deferredRedirect:!1});super(s.update.bind(s)),Z.add(this),this.stepState=new T({}),ee.set(this,void 0),te.set(this,null),ie.set(this,null),se.set(this,{visibilitychange:e(this,Z,"m",oe).bind(this)}),this.bridgeVersion=2,this.nativeCallbacks={},pe.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},ge.set(this,(t=>{const i=()=>{this.contentRootElement.classList.toggle("hidden",t),this.slotElement.classList.toggle("hidden",!t),t&&(this.contentRootElement.innerHTML="")};t&&this.contentRootElement.hasChildNodes()?e(this,Z,"m",ve).call(this,i):i()})),me.set(this,((s,o,n,l,d=!1)=>{const c=[X,Y];if(this.flowState.current.action===r.poll){this.logger.debug("polling - Scheduling polling request");const r=Date.now(),h=d?500:2e3;t(this,ee,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const p=this.sdk.flow.next(s,o,a.polling,n,l,{}),u=document.hidden&&!d&&Date.now()-r>h+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield v(e,p)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,me,"f").call(this,s,o,n,l,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===J)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,me,"f").call(this,s,o,n,l);this.logger.debug("polling - Got a response"),(null==g?void 0:g.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(g.error,null,4)),(null===(i=null==g?void 0:g.error)||void 0===i?void 0:i.errorCode)&&c.includes(g.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):e(this,me,"f").call(this,s,o,n,l),e(this,be,"f").call(this,g)}))),h),"f")}})),fe.set(this,(()=>{clearTimeout(e(this,ee,"f")),t(this,ee,null,"f")})),be.set(this,(i=>{var s,o,n,a,l,d,c,h,p,u,g,v,m;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,r=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,Z,"m",Ue).call(this,"error",(null==i?void 0:i.error)||{errorCode:z,errorDescription:r,errorMessage:t}),this.loggerWrapper.error((null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorDescription)||t,(null===(l=null==i?void 0:i.error)||void 0===l?void 0:l.errorMessage)||r);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==Q&&c!==X||!this.isRestartOnError||e(this,Z,"m",he).call(this))}null===(h=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===h||h.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(p=i.data)||void 0===p?void 0:p.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(v=i.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:I}=i.data;if(y!==r.poll&&e(this,fe,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&H(S);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),void e(this,Z,"m",Ue).call(this,"success",t)}this.storeLastAuthenticatedUser&&H(S,!0),I&&window.open(I,"_blank");const{executionId:C,stepId:k,stepName:R,screen:O,redirect:W,webauthn:x,error:E,samlIdpResponse:A,nativeResponse:j}=i.data,T=Date.now();y!==r.poll?(this.loggerWrapper.info(`Step "${R||`#${k}`}" is ${b}`,"",{screen:O,status:b,stepId:k,stepName:R,action:y,error:E}),(null===(m=O.state)||void 0===m?void 0:m.clientScripts)&&t(this,ie,this.loadSdkScripts(O.state.clientScripts),"f"),this.flowState.update({stepId:k,stepName:R,executionId:C,action:y,redirectTo:null==W?void 0:W.url,redirectIsPopup:null==W?void 0:W.isPopup,screenId:null==O?void 0:O.id,screenState:null==O?void 0:O.state,webauthnTransactionId:null==x?void 0:x.transactionId,webauthnOptions:null==x?void 0:x.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,nativeResponseType:null==j?void 0:j.type,nativePayload:null==j?void 0:j.payload,reqTimestamp:T})):this.flowState.update({action:y,reqTimestamp:T})})),we.set(this,m((()=>i(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),Re.set(this,null),Ae.set(this,f(((t,s)=>i(this,void 0,void 0,(function*(){var i;if("true"===t.getAttribute("formnovalidate")||e(this,Z,"m",Ce).call(this)){const o=null==t?void 0:t.getAttribute("id");e(this,Z,"m",Oe).call(this,t);const n=yield e(this,Z,"m",ke).call(this),r=R(t);this.nextRequestStatus.update({isLoading:!0});const a=Object.assign(Object.assign(Object.assign({},r),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(o,a),this.nextRequestStatus.update({isLoading:!1}),e(this,Z,"m",We).call(this,n)}}))))),this.flowState=s}nativeResume(t,i){var s,o,n,r,a;const h=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let{exchangeCode:e}=h;if(!e){e=null===(s=new URL(h.url).searchParams)||void 0===s?void 0:s.get(l)}null===(n=(o=this.nativeCallbacks).complete)||void 0===n||n.call(o,{exchangeCode:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(h.url),i=t.searchParams.get(d),s=t.searchParams.get(c).split("_").pop();e(this,fe,"f").call(this),this.flowState.update({token:i,stepId:s,action:void 0})}else if("beforeScreen"===t){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=h;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=h,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(r=this.nativeCallbacks).complete)||void 0===a||a.call(r,h)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[O(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=Promise.all(null==e?void 0:e.map((e=>i(this,void 0,void 0,(function*(){var i,s;const o=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(o){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=o;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}yield this.injectNpmLib("@descope/flow-scripts","1.0.13",`dist/${e.id}.js`);const n=null===(s=globalThis.descope)||void 0===s?void 0:s[e.id];return new Promise(((i,s)=>{try{const s=n(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i),this.loggerWrapper);if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t),this.nextRequestStatus.subscribe((()=>{var t;this.loggerWrapper.debug("Unloading script",e.id),null===(t=s.stop)||void 0===t||t.call(s)}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),h)}));return Promise.race([s,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){if(!window.descopeBridge)return this._init();this.lazyInit=this._init}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,Z,"m",de).call(this),window.addEventListener("visibilitychange",e(this,se,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var i;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,fe,"f").call(this),null===(i=e(this,te,"f"))||void 0===i||i.abort(),t(this,te,null,"f"),window.removeEventListener("visibilitychange",e(this,se,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=b(e),o=yield this.getTargetLocales();return o.includes(s.locale)?i=`${t}-${s.locale}.html`:o.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(l,d,c){return i(this,void 0,void 0,(function*(){var h,p;const{projectId:u,flowId:g,tenant:v,stepId:m,executionId:f,action:C,screenId:k,screenState:R,redirectTo:O,redirectIsPopup:E,redirectUrl:A,token:j,code:T,isPopup:L,exchangeError:U,webauthnTransactionId:P,webauthnOptions:$,redirectAuthCodeChallenge:N,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:F,locale:V,samlIdpResponseUrl:H,samlIdpResponseSamlResponse:G,samlIdpResponseRelayState:J,nativeResponseType:z,nativePayload:Q,reqTimestamp:X}=l,Y=s(l,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","nativeResponseType","nativePayload","reqTimestamp"]);let ee,se,oe;const ne=D(),{outboundAppId:re}=this,{outboundAppScopes:le}=this,de=this.sdk.getLastUserLoginId(),ce=yield this.getFlowConfig(),he=yield this.getProjectConfig(),pe=Object.entries(he.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),ge=M&&N?{callbackUrl:M,codeChallenge:N,backupCallbackUri:q}:void 0,ve=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;let fe={};if(!f){const i=[...ce.clientScripts||[],...ce.sdkScripts||[]];if(ce.conditions){let e=[];({startScreenId:ee,conditionInteractionId:oe,startScreenName:se,clientScripts:e,componentsConfig:fe}=B({loginId:de,code:T,token:j,abTestingKey:ne,lastAuth:_(de)},ce.conditions)),i.push(...e||[])}else ce.condition?({startScreenId:ee,conditionInteractionId:oe}=K(ce.condition,{loginId:de,code:T,token:j,abTestingKey:ne,lastAuth:_(de)})):(se=ce.startScreenName,ee=ce.startScreenId);if(t(this,ie,this.loadSdkScripts(i),"f"),ce.fingerprintEnabled&&ce.fingerprintKey?yield o(ce.fingerprintKey,this.baseUrl):n(),!w(ee,Y)){const t=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:ge},Y),{client:this.client}),A&&{redirectUrl:A}),{lastAuth:_(de),abTestingKey:ne,locale:b(V).locale,nativeOptions:ve,outboundAppId:re,outboundAppScopes:le}),oe,"",he.componentsVersion,pe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),T?{exchangeCode:T,idpInitiated:!0}:{}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j?{token:j}:{}),Y.oidcLoginHint?{externalId:Y.oidcLoginHint}:{}));return e(this,be,"f").call(this,t),void("completed"!==(null===(h=null==t?void 0:t.data)||void 0===h?void 0:h.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:L,code:T,exchangeError:U,isCodeChanged:c("code"),isExchangeErrorChanged:c("exchangeError")})),L&&(c("code")&&T||c("exchangeError")&&U))return void e(this,Z,"m",Pe).call(this,f,T,U);if(f&&(c("token")&&j||c("code")&&T||c("exchangeError")&&U)){const t=yield this.sdk.flow.next(f,m,a.submit,ce.version,he.componentsVersion,{token:j,exchangeCode:T,exchangeError:U});return e(this,be,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(C===r.loadForm&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>c(e)))){if(!H||!G)return void this.loggerWrapper.error("Did not get saml idp params data to load");S(H,G,J||"",W)}if(C===r.redirect&&(c("redirectTo")||c("deferredRedirect"))){if(!O)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===O)return;if("android"===F&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${E}`),E){this.loggerWrapper.debug("Opening redirect in popup");const t=y(O,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));const s=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const t=i?this.popupOrigin:window.location.origin;if(e.origin!==t)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${t}"`);const{action:s,data:o}=e.data||{};"code"===s&&this.flowState.update({code:o.code,exchangeError:o.exchangeError})};let o;this.loggerWrapper.debug("Starting popup closed detection");const n=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(n),e(this,Z,"m",Ue).call(this,"popupclosed",{}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==o||o())}),1e3);if(i)window.addEventListener("message",s),o=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",s)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(f);e.onmessage=s,o=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(O),this.flowState.update({redirectTo:"no-op"}),e(this,Z,"m",Ue).call(this,"popupclosed",{});return}if(C===r.webauthnCreate||C===r.webauthnGet){if(!P||!$)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s;null===(p=e(this,te,"f"))||void 0===p||p.abort(),t(this,te,null,"f");try{i=C===r.webauthnCreate?yield this.sdk.webauthn.helpers.create($):yield this.sdk.webauthn.helpers.get($)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),s=e.name}const o=yield this.sdk.flow.next(f,m,a.submit,ce.version,he.componentsVersion,{transactionId:P,response:i,failure:s});e(this,be,"f").call(this,o)}if(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,Oe={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},We=_(de);w(ee,Y)?Oe.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ce?void 0:ce.clientScripts)||[];yield e(this,Z,"m",je).call(this,i);const o=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:ge},Y),{lastAuth:We,preview:this.preview,abTestingKey:ne,client:this.client}),A&&{redirectUrl:A}),{locale:b(V).locale,nativeOptions:ve,outboundAppId:re,outboundAppScopes:le}),oe,t,he.componentsVersion,pe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),x(s)),T&&{exchangeCode:T,idpInitiated:!0}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j&&{token:j}));return e(this,be,"f").call(this,o),o})):(c("projectId")||c("baseUrl")||c("executionId")||c("stepId"))&&(Oe.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==R?void 0:R.clientScripts)||[];yield e(this,Z,"m",je).call(this,i);const o=yield this.sdk.flow.next(f,m,t,ce.version,he.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),x(s)));return e(this,be,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",Oe.screenId),yield e(this,Z,"m",ue).call(this,Oe),this.stepState.update(Oe)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n;const{htmlFilename:r,htmlLocaleFilename:l,direction:d,next:c,screenState:h}=t;this.loggerWrapper.debug("Rendering a flow screen");const p=document.createElement("template");p.innerHTML=yield this.getPageContent(r,l);const g=p.content.cloneNode(!0),v=this.loadDescopeUiComponents(p);this.sdk.webauthn.helpers.isSupported()?yield e(this,Z,"m",ye).call(this,g,c):L(g),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(n=h.form)||void 0===n?void 0:n.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),U(g,h,this.formConfig,this.loggerWrapper);const{geo:m}=yield this.getExecutionContext();P(g,m);const f=()=>i(this,void 0,void 0,(function*(){var i,o;yield v;const n=this.contentRootElement;$(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),N(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),M(n,g,h.cssVars,this.loggerWrapper),n.replaceChildren(g);const r=!s.htmlFilename;setTimeout((()=>{e(this,Z,"m",xe).call(this),this.validateOnBlur&&E(n),q(n,h),e(this,Z,"m",Ie).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),C(n,this.autoFocus,r)})),e(this,Z,"m",Le).call(this,c);n.querySelector(`[${u}="polling"]`)&&c(a.polling,{})}));d?e(this,Z,"m",ve).call(this,f):f()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${p}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}ee=new WeakMap,te=new WeakMap,ie=new WeakMap,se=new WeakMap,pe=new WeakMap,ge=new WeakMap,me=new WeakMap,fe=new WeakMap,be=new WeakMap,we=new WeakMap,Re=new WeakMap,Ae=new WeakMap,Z=new WeakSet,oe=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},ne=function(t,s,o){return i(this,void 0,void 0,(function*(){var i;return(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&new Promise((i=>{this.nativeCallbacks.screenNext=o,this.nativeCallbacks.screenResolve=i,e(this,Z,"m",ae).call(this,"beforeScreen",{screen:t,context:s})}))}))},re=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,Z,"m",ae).call(this,"afterScreen",{screen:t})},ae=function(t,i){e(this,Z,"m",Ue).call(this,"bridge",{type:t,payload:i})},le=function({errorText:e,errorType:t}){const i=()=>{var i;let s=e;try{s=(null===(i=this.errorTransformer)||void 0===i?void 0:i.call(this,{text:e,type:t}))||e}catch(e){this.loggerWrapper.error("Error transforming error message",e.message)}F(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},de=function(){var t,i,o;null===(t=this.stepState)||void 0===t||t.subscribe(this.onStepChange.bind(this),(e=>{var t=e.screenState,i=s(void 0===t?{}:t,["errorText","errorType"]),o=s(e,["screenState"]);return Object.assign(Object.assign({},o),{screenState:i})})),null===(i=this.stepState)||void 0===i||i.subscribe(e(this,Z,"m",le).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(o=this.stepState)||void 0===o||o.subscribe(e(this,Z,"m",ce).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0})},ce=function({errorText:e,errorType:t}){(t||e)&&(this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((e=>{e.shadowRoot.querySelectorAll("descope-text-field[data-id]").forEach((e=>{e.value=""}))})),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.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},ve=function(e){this.contentRootElement.addEventListener("transitionend",(()=>{this.loggerWrapper.debug("page switch transition end"),this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0}),this.loggerWrapper.debug("page switch transition start"),this.contentRootElement.classList.add("fade-out")},Se=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const i=`user-${t}`;e.setAttribute("name",i),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:i)}))}},ye=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,te,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield V())){const{options:s,transactionId:n}=(yield e(this,we,"f").call(this))||{};s&&n&&(e(this,Z,"m",Se).call(this,r),t(this,te,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,te,"f")).then((e=>i(this,void 0,void 0,(function*(){o(r.id,{transactionId:n,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},Ie=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,Z,"m",Ue).call(this,"ready",{}),i||e(this,Z,"m",re).call(this,s),e(this,Z,"m",Ue).call(this,"page-updated",{screenName:s}),e(this,Z,"m",Ue).call(this,"screen-updated",{screenName:s})},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})),{})}))},Oe=function(s){const o=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),n=()=>i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",n),s.removeAttribute("loading"),o.forEach((e=>{e.removeAttribute("disabled")}));const e=yield this.getFlowConfig(),t=[...e.clientScripts||[],...e.sdkScripts||[]];this.loadSdkScripts(t)})),r=()=>{var i;window.removeEventListener("pageshow",e(this,Re,"f")),t(this,Re,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),n())}),"f"),window.addEventListener("pageshow",e(this,Re,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&n(),this.removeEventListener("popupclosed",n),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},a=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?(this.addEventListener("popupclosed",n,{once:!0}),s.setAttribute("loading","true"),o.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(a),r())}))},We=function(e={}){var t,i;const s=A(e,["externalId","email","phone"]),o=A(e,["newPassword","password"]);if(s&&o)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:o});null===(i=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===i||i.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},xe=function(){j();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,Z,"m",Ee).call(this,t)))},Ee=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const i=t.getAttribute("slot"),s=`input-${e.id}-${i}`,o=document.createElement("slot");o.setAttribute("name",s),o.setAttribute("slot",i),e.appendChild(o),t.setAttribute("slot",s),this.appendChild(t)}))},je=function(t){return i(this,void 0,void 0,(function*(){if(e(this,ie,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ie,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-t).toString())}const i=this.loadSdkScriptsModules(),s=t.map((e=>e.id));for(const e of i)if(s.includes(e.id))try{if("function"==typeof e.present){(yield e.present())||this.loggerWrapper.debug(`Sdk script ${e.id} was cancelled`)}}catch(t){this.loggerWrapper.error(`Failed to present ${e.id} script module`,t.message)}let o=[];for(const e of i)"function"==typeof e.refresh&&o.push(e.refresh());if(o.length>0)try{yield v(h,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},Te=function(t){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((i=>{i.addEventListener("input",(()=>{var s;(null===(s=i.checkValidity)||void 0===s?void 0:s.call(i))&&e(this,Ae,"f").call(this,i,t)}))}))},Le=function(t){this.contentRootElement.querySelectorAll(`descope-button:not([${g}]), [data-type="button"]:not([${g}]`).forEach((i=>{i.onclick=()=>{e(this,Ae,"f").call(this,i,t)}})),e(this,Z,"m",Te).call(this,t),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${p}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},Ue=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},Pe=function(e,t,i){var s;const[o,n]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],r={data:{code:t,exchangeError:i},action:"code"};if("descope-wc"===o&&n){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",n);try{window.opener.postMessage(r,n)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(r),t.close()}try{window.close()}catch(e){}};export{$e as default};
|
|
2
2
|
//# sourceMappingURL=DescopeWc.js.map
|