@descope/web-component 4.0.2 → 4.2.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/README.md +14 -0
- package/dist/cjs/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/cjs/descope-wc/BaseDescopeWc.js.map +1 -1
- package/dist/cjs/descope-wc/DescopeWc.js +1 -1
- package/dist/cjs/descope-wc/DescopeWc.js.map +1 -1
- package/dist/cjs/mixins/componentConditionsMixin.js.map +1 -1
- package/dist/esm/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/esm/descope-wc/BaseDescopeWc.js.map +1 -1
- package/dist/esm/descope-wc/DescopeWc.js +1 -1
- package/dist/esm/descope-wc/DescopeWc.js.map +1 -1
- package/dist/esm/mixins/componentConditionsMixin.js.map +1 -1
- package/dist/index.d.ts +718 -291
- package/dist/index.js +2 -2
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"componentConditionsMixin.js","sources":["../../../src/lib/mixins/componentConditionsMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export, no-param-reassign */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n REALTIME_CONDITION_DEBOUNCE_MS,\n REALTIME_CONDITION_EVENTS,\n} from '../helpers/realtime-conditions/config';\nimport {\n collectReferencedFormKeys,\n collectTouchedComponentIds,\n evaluateAll,\n FormSnapshot,\n} from '../helpers/realtime-conditions/evaluator';\nimport {\n apply,\n COMPONENT_ACTIONS,\n escapeSelector,\n} from '../helpers/realtime-conditions/applier';\nimport { DESCOPE_ATTRIBUTE_EXCLUDE_FIELD } from '../constants';\nimport type { RealtimeComponentsCondition, ScreenState } from '../types';\n\nconst LOG_PREFIX = 'component-conditions:';\n\n// What the mixin needs from its host: a way to subscribe to loading state\n// so input handling can pause while the next request is in flight. Defined\n// as an interface (not imported) to avoid a circular dependency on BaseDescopeWc.\nexport interface PausableHost {\n nextRequestStatus?: {\n // subscribe returns a token; pass that token to unsubscribe — not the handler.\n subscribe: (cb: (v: { isLoading: boolean }) => void) => string;\n unsubscribe?: (token: string) => void;\n };\n}\n\nexport interface RealtimeRuntime {\n conditions: RealtimeComponentsCondition[];\n // IDs of components that any rule can change\n touchedIds: Set<string>;\n // latest form values on screen\n snapshot: FormSnapshot;\n // what's currently applied on screen for touched components.\n // Compared against on each re-evaluation to know what to change.\n applied: Record<string, string>;\n // What the server told us to apply for these components. Stays fixed for\n // the screen's lifetime so we can fall back to it when a real-time rule\n // stops matching. Without this, a server-set action could disappear when\n // a real-time rule briefly fires on the same component.\n serverBaseline: Record<string, string>;\n debounceTimer: ReturnType<typeof setTimeout> | null;\n // true while paused (during submit, to avoid stale updates)\n paused: boolean;\n unsubscribePauseListener: (() => void) | null;\n // the listener we attach to form events (kept so we can detach)\n inputHandler: (e: Event) => void;\n // the screen root we work against\n root: HTMLElement | null;\n}\n\n// Some inputs already have `name=\"form.x\"`, others use `name=\"x\"`. Always\n// return the `form.x` form so it lines up with what rules reference.\nfunction toFormKey(name: string): string {\n return name.startsWith('form.') ? name : `form.${name}`;\n}\n\n// Try the full `form.x` first (descope components), then `x` (plain inputs).\nfunction findInputForFormKey(\n root: ParentNode,\n formKey: string,\n): Element | null {\n const bare = formKey.startsWith('form.')\n ? formKey.slice('form.'.length)\n : formKey;\n return (\n root.querySelector(`[name=\"${escapeSelector(formKey)}\"]`) ||\n root.querySelector(`[name=\"${escapeSelector(bare)}\"]`)\n );\n}\n\n// Read the current value off a form input. Reads JS properties (not HTML\n// attributes) so we pick up both the component's default and any value\n// carried over from earlier screens.\n//\n// Native <input type=checkbox> needs special handling: `.value` is always\n// \"on\", only `.checked` reflects the real state. Descope boolean components\n// (descope-checkbox, descope-switch-toggle) expose `.checked` on their class.\nfunction readInputValue(el: Element): unknown {\n if (el instanceof HTMLInputElement) {\n return el.type === 'checkbox' ? el.checked : el.value;\n }\n if ('checked' in el) {\n return (el as unknown as { checked: boolean }).checked;\n }\n if ('value' in el) {\n return (el as unknown as { value: unknown }).value;\n }\n return undefined;\n}\n\nfunction shallowEqualStringMap(\n a: Record<string, string>,\n b: Record<string, string>,\n): boolean {\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n return keysA.every((k) => a[k] === b[k]);\n}\n\nfunction emptyRuntime(): RealtimeRuntime {\n return {\n conditions: [],\n touchedIds: new Set(),\n snapshot: {},\n applied: {},\n serverBaseline: {},\n debounceTimer: null,\n paused: false,\n unsubscribePauseListener: null,\n inputHandler: () => {},\n root: null,\n };\n}\n\n// For each touched component, pick the real-time action if a rule is firing\n// for it, otherwise fall back to the server's action. Components that no rule\n// touches are not in the result — those were already painted by\n// applyComponentsState.\nfunction effectiveActions(\n realtimeVerdict: Record<string, string>,\n serverBaseline: Record<string, string>,\n touchedIds: Set<string>,\n): Record<string, string> {\n const out: Record<string, string> = {};\n touchedIds.forEach((id) => {\n if (realtimeVerdict[id]) {\n out[id] = realtimeVerdict[id];\n } else if (serverBaseline[id]) {\n out[id] = serverBaseline[id];\n }\n });\n return out;\n}\n\nexport const componentConditionsMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n // Pull in loggerMixin so `this.logger` is available no matter where\n // this mixin sits in the chain.\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class ComponentConditionsMixin extends BaseClass {\n // One runtime per <descope-wc> element.\n #rtRuntime: RealtimeRuntime = emptyRuntime();\n\n /**\n * Apply the server's hide/disable/read-only actions to the DOM.\n * Logs unknown actions here (runs once per screen) but stays quiet on\n * the keystroke path to avoid log spam.\n */\n applyComponentsState(\n root: ParentNode,\n componentsState: Record<string, string> | undefined,\n ): void {\n if (!componentsState) return;\n Object.entries(componentsState).forEach(([id, action]) => {\n if (!(COMPONENT_ACTIONS as readonly string[]).includes(action)) {\n this.logger.error(\n `Unknown component action \"${action}\" for component with id \"${id}\"`,\n `Valid actions are ${COMPONENT_ACTIONS.map((a) => `\"${a}\"`).join(\n ', ',\n )}`,\n );\n }\n });\n apply(root, {}, componentsState);\n }\n\n /**\n * Set up real-time conditions for the current screen. Safe to call\n * twice — a second call rebuilds from screenState.\n *\n * Must run AFTER `updateScreenFromScreenState`, so the DOM reads below\n * see both server-shipped values and any component defaults from the\n * HTML.\n */\n initRealtimeConditions(\n rootElement: HTMLElement,\n screenState: ScreenState | undefined,\n ): void {\n this.#teardownRealtimeRuntime();\n\n const conditions = screenState?.realtimeComponentsConditions ?? [];\n if (!conditions.length) {\n this.logger.debug(\n `${LOG_PREFIX} no real-time rules to apply on this screen`,\n );\n return;\n }\n this.logger.info(\n `${LOG_PREFIX} found ${conditions.length} real-time rule(s) for this screen`,\n );\n\n // screenState.form uses \"phone\"; rules reference \"form.phone\".\n // Add the prefix on the way in.\n const initialSnapshot: FormSnapshot = {};\n Object.entries(screenState?.form ?? {}).forEach(([k, v]) => {\n initialSnapshot[`form.${k}`] = v;\n });\n\n // For every key the rules reference, read the current DOM value.\n // Component defaults (e.g. `checked=\"true\"` on a descope-checkbox)\n // live only in the HTML and don't make it into screenState.form, so\n // without this read the first evaluation would miss them.\n collectReferencedFormKeys(conditions).forEach((formKey) => {\n const el = findInputForFormKey(rootElement, formKey);\n if (!el) return;\n const v = readInputValue(el);\n if (v !== undefined) initialSnapshot[formKey] = v;\n });\n\n const touchedIds = collectTouchedComponentIds(conditions);\n\n // What to fall back to when a real-time rule stops matching for a\n // touched component — the actions set by server-only rules (rules\n // with no client-side conditions).\n const serverBaseline: Record<string, string> = {};\n // What's already painted on the DOM (touched components only), so\n // the first real-time evaluation can diff against the right state.\n const initialApplied: Record<string, string> = {};\n\n Object.entries(screenState?.componentsState ?? {}).forEach(\n ([id, action]) => {\n if (!touchedIds.has(id)) return;\n initialApplied[id] = action;\n },\n );\n\n Object.entries(screenState?.serverOnlyComponentsState ?? {}).forEach(\n ([id, action]) => {\n if (touchedIds.has(id)) {\n serverBaseline[id] = action;\n }\n },\n );\n\n const runtime: RealtimeRuntime = {\n conditions,\n touchedIds,\n snapshot: initialSnapshot,\n applied: initialApplied,\n serverBaseline,\n debounceTimer: null,\n paused: false,\n unsubscribePauseListener: null,\n inputHandler: () => {},\n root: rootElement,\n };\n\n // Re-run the rules now that we've read the real DOM values. The\n // server evaluated without seeing component defaults, so its\n // `componentsState` can disagree with what the user actually sees.\n // Apply the diff once before listening for input.\n const reconciled = effectiveActions(\n evaluateAll(conditions, initialSnapshot),\n serverBaseline,\n touchedIds,\n );\n if (!shallowEqualStringMap(initialApplied, reconciled)) {\n runtime.applied = apply(rootElement, initialApplied, reconciled);\n }\n\n runtime.inputHandler = (e: Event) =>\n this.#handleRealtimeInput(e as InputEvent);\n\n REALTIME_CONDITION_EVENTS.forEach((ev) => {\n rootElement.addEventListener(ev, runtime.inputHandler, true);\n });\n this.logger.debug(\n `${LOG_PREFIX} listening for \"${REALTIME_CONDITION_EVENTS.join(\n '\" and \"',\n )}\" events on form fields; ${\n Object.keys(initialApplied).length\n } component(s) start hidden / disabled / read-only by these rules`,\n );\n\n // Pause while a /next request is in flight. Without this, a debounced\n // evaluation could run between submit and the next screen render and\n // change components that are about to be replaced — causing flicker,\n // or hiding something the next screen needs visible.\n const pauseState = (this as unknown as PausableHost).nextRequestStatus;\n if (pauseState?.subscribe) {\n const handler = ({ isLoading }: { isLoading: boolean }) => {\n runtime.paused = isLoading;\n if (isLoading && runtime.debounceTimer) {\n clearTimeout(runtime.debounceTimer);\n runtime.debounceTimer = null;\n }\n };\n // subscribe returns a token; unsubscribe needs that token, not the\n // handler. Without storing it, handlers leak across screens and\n // keep old runtimes (and their DOM roots) alive.\n const token = pauseState.subscribe(handler);\n runtime.unsubscribePauseListener = () => {\n if (token !== undefined && token !== null) {\n pauseState.unsubscribe?.(token);\n }\n };\n }\n\n this.#rtRuntime = runtime;\n }\n\n #handleRealtimeInput(e: InputEvent): void {\n const runtime = this.#rtRuntime;\n if (!runtime.root || runtime.paused) return;\n\n const target = e.target as Element | null;\n if (!target) return;\n if (target.hasAttribute?.(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD)) return;\n\n const name = target.getAttribute?.('name');\n if (!name) return;\n\n // Update the snapshot only — evaluation is debounced. Use readInputValue\n // so checkboxes read the same way as at mount; otherwise `target.value`\n // would be the string \"on\" for native checkboxes and break is-true rules.\n const key = toFormKey(name);\n runtime.snapshot[key] = readInputValue(target);\n\n if (runtime.debounceTimer) {\n clearTimeout(runtime.debounceTimer);\n }\n runtime.debounceTimer = setTimeout(() => {\n runtime.debounceTimer = null;\n this.#reEvaluateRealtime();\n }, REALTIME_CONDITION_DEBOUNCE_MS);\n }\n\n #reEvaluateRealtime(): void {\n const runtime = this.#rtRuntime;\n if (!runtime.root) return;\n\n let next: Record<string, string>;\n try {\n next = effectiveActions(\n evaluateAll(runtime.conditions, runtime.snapshot),\n runtime.serverBaseline,\n runtime.touchedIds,\n );\n } catch (e) {\n this.logger.error(\n `${LOG_PREFIX} failed to evaluate real-time rules — keeping the previous state`,\n (e as Error)?.message,\n );\n return;\n }\n\n const prevApplied = runtime.applied;\n if (shallowEqualStringMap(prevApplied, next)) return;\n\n this.logger.debug(\n `${LOG_PREFIX} form changed — updating components: was ${JSON.stringify(\n prevApplied,\n )}, now ${JSON.stringify(next)}`,\n );\n runtime.applied = apply(runtime.root, prevApplied, next);\n }\n\n // Clean up listeners and timers when the host leaves the DOM. Reaches\n // us only if BaseDescopeWc calls `super.disconnectedCallback?.()`;\n // otherwise teardown happens lazily on the next initRealtimeConditions.\n disconnectedCallback() {\n // disconnectedCallback isn't on HTMLElement in the lib types, but it\n // exists at runtime — forward into super in case the chain uses it.\n // @ts-expect-error custom-element lifecycle method missing from lib types\n super.disconnectedCallback?.();\n this.#teardownRealtimeRuntime();\n }\n\n #teardownRealtimeRuntime(): void {\n const r = this.#rtRuntime;\n if (r.debounceTimer) {\n clearTimeout(r.debounceTimer);\n }\n if (r.unsubscribePauseListener) {\n r.unsubscribePauseListener();\n }\n if (r.root) {\n // Undo anything we applied so the next screen starts clean. Skip\n // if the root is already gone (replaced by the next screen) —\n // nothing left to undo.\n if (Object.keys(r.applied).length > 0 && r.root.isConnected) {\n apply(r.root, r.applied, {});\n }\n REALTIME_CONDITION_EVENTS.forEach((ev) => {\n r.root!.removeEventListener(ev, r.inputHandler, true);\n });\n }\n this.#rtRuntime = emptyRuntime();\n }\n };\n },\n);\n"],"names":["LOG_PREFIX","readInputValue","el","HTMLInputElement","type","checked","value","shallowEqualStringMap","a","b","keysA","Object","keys","keysB","length","every","k","emptyRuntime","conditions","touchedIds","Set","snapshot","applied","serverBaseline","debounceTimer","paused","unsubscribePauseListener","inputHandler","root","effectiveActions","realtimeVerdict","out","forEach","id","componentConditionsMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","_a","constructor","_ComponentConditionsMixin_rtRuntime","set","this","applyComponentsState","componentsState","entries","action","COMPONENT_ACTIONS","includes","logger","error","map","join","apply","initRealtimeConditions","rootElement","screenState","__classPrivateFieldGet","_ComponentConditionsMixin_instances","_ComponentConditionsMixin_teardownRealtimeRuntime","call","_b","realtimeComponentsConditions","debug","info","initialSnapshot","_c","form","v","collectReferencedFormKeys","formKey","bare","startsWith","slice","querySelector","escapeSelector","findInputForFormKey","undefined","collectTouchedComponentIds","initialApplied","_d","has","_e","serverOnlyComponentsState","runtime","reconciled","evaluateAll","e","REALTIME_CONDITION_EVENTS","ev","addEventListener","pauseState","nextRequestStatus","subscribe","handler","isLoading","clearTimeout","token","unsubscribe","__classPrivateFieldSet","disconnectedCallback","super","target","hasAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","name","getAttribute","key","toFormKey","setTimeout","_ComponentConditionsMixin_reEvaluateRealtime","REALTIME_CONDITION_DEBOUNCE_MS","next","message","prevApplied","JSON","stringify","r","isConnected","removeEventListener"],"mappings":"gTAqBA,MAAMA,EAAa,wBAgEnB,SAASC,EAAeC,GACtB,OAAIA,aAAcC,iBACG,aAAZD,EAAGE,KAAsBF,EA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3F,KAAM2F,EAAEjG,QAAS,CAAE,GAE7BoE,4BAA0B1D,SAAS2D,IACjC4B,EAAE3F,KAAM6F,oBAAoB9B,EAAI4B,EAAE5F,cAAc,EAAK,KAGzD0E,EAAAA,uBAAAzD,KAAIF,EAAczB,QACnB,EACDuB,CAAA"}
|
|
1
|
+
{"version":3,"file":"componentConditionsMixin.js","sources":["../../../src/lib/mixins/componentConditionsMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export, no-param-reassign */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n REALTIME_CONDITION_DEBOUNCE_MS,\n REALTIME_CONDITION_EVENTS,\n} from '../helpers/realtime-conditions/config';\nimport {\n collectReferencedFormKeys,\n collectTouchedComponentIds,\n evaluateAll,\n FormSnapshot,\n} from '../helpers/realtime-conditions/evaluator';\nimport {\n apply,\n COMPONENT_ACTIONS,\n escapeSelector,\n} from '../helpers/realtime-conditions/applier';\nimport { DESCOPE_ATTRIBUTE_EXCLUDE_FIELD } from '../constants';\nimport type { RealtimeComponentsCondition, ScreenState } from '../types';\n\nconst LOG_PREFIX = 'component-conditions:';\n\n// What the mixin needs from its host: a way to subscribe to loading state\n// so input handling can pause while the next request is in flight. Defined\n// as an interface (not imported) to avoid a circular dependency on BaseDescopeWc.\nexport interface PausableHost {\n nextRequestStatus?: {\n // subscribe returns a token; pass that token to unsubscribe — not the handler.\n subscribe: (cb: (v: { isLoading: boolean }) => void) => string;\n unsubscribe?: (token: string) => void;\n };\n}\n\nexport interface RealtimeRuntime {\n conditions: RealtimeComponentsCondition[];\n // IDs of components that any rule can change\n touchedIds: Set<string>;\n // latest form values on screen\n snapshot: FormSnapshot;\n // what's currently applied on screen for touched components.\n // Compared against on each re-evaluation to know what to change.\n applied: Record<string, string>;\n // What the server told us to apply for these components. Stays fixed for\n // the screen's lifetime so we can fall back to it when a real-time rule\n // stops matching. Without this, a server-set action could disappear when\n // a real-time rule briefly fires on the same component.\n serverBaseline: Record<string, string>;\n debounceTimer: ReturnType<typeof setTimeout> | null;\n // true while paused (during submit, to avoid stale updates)\n paused: boolean;\n unsubscribePauseListener: (() => void) | null;\n // the listener we attach to form events (kept so we can detach)\n inputHandler: (e: Event) => void;\n // the screen root we work against\n root: HTMLElement | null;\n}\n\n// Some inputs already have `name=\"form.x\"`, others use `name=\"x\"`. Always\n// return the `form.x` form so it lines up with what rules reference.\nfunction toFormKey(name: string): string {\n return name.startsWith('form.') ? name : `form.${name}`;\n}\n\n// Try the full `form.x` first (descope components), then `x` (plain inputs).\nfunction findInputForFormKey(\n root: ParentNode,\n formKey: string,\n): Element | null {\n const bare = formKey.startsWith('form.')\n ? formKey.slice('form.'.length)\n : formKey;\n return (\n root.querySelector(`[name=\"${escapeSelector(formKey)}\"]`) ||\n root.querySelector(`[name=\"${escapeSelector(bare)}\"]`)\n );\n}\n\n// Read the current value off a form input. Reads JS properties (not HTML\n// attributes) so we pick up both the component's default and any value\n// carried over from earlier screens.\n//\n// Native <input type=checkbox> needs special handling: `.value` is always\n// \"on\", only `.checked` reflects the real state. Descope boolean components\n// (descope-checkbox, descope-switch-toggle) expose `.checked` on their class.\nfunction readInputValue(el: Element): unknown {\n if (el instanceof HTMLInputElement) {\n return el.type === 'checkbox' ? el.checked : el.value;\n }\n if ('checked' in el) {\n return (el as unknown as { checked: boolean }).checked;\n }\n if ('value' in el) {\n return (el as unknown as { value: unknown }).value;\n }\n return undefined;\n}\n\nfunction shallowEqualStringMap(\n a: Record<string, string>,\n b: Record<string, string>,\n): boolean {\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n return keysA.every((k) => a[k] === b[k]);\n}\n\nfunction emptyRuntime(): RealtimeRuntime {\n return {\n conditions: [],\n touchedIds: new Set(),\n snapshot: {},\n applied: {},\n serverBaseline: {},\n debounceTimer: null,\n paused: false,\n unsubscribePauseListener: null,\n inputHandler: () => {},\n root: null,\n };\n}\n\n// For each touched component, pick the real-time action if a rule is firing\n// for it, otherwise fall back to the server's action. Components that no rule\n// touches are not in the result — those were already painted by\n// applyComponentsState.\nfunction effectiveActions(\n realtimeVerdict: Record<string, string>,\n serverBaseline: Record<string, string>,\n touchedIds: Set<string>,\n): Record<string, string> {\n const out: Record<string, string> = {};\n touchedIds.forEach((id) => {\n if (realtimeVerdict[id]) {\n out[id] = realtimeVerdict[id];\n } else if (serverBaseline[id]) {\n out[id] = serverBaseline[id];\n }\n });\n return out;\n}\n\nexport const componentConditionsMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n // Pull in loggerMixin so `this.logger` is available no matter where\n // this mixin sits in the chain.\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class ComponentConditionsMixin extends BaseClass {\n // One runtime per <descope-wc> element.\n #rtRuntime: RealtimeRuntime = emptyRuntime();\n\n /**\n * Apply the server's hide/disable/read-only actions to the DOM.\n * Logs unknown actions here (runs once per screen) but stays quiet on\n * the keystroke path to avoid log spam.\n */\n applyComponentsState(\n root: ParentNode,\n componentsState: Record<string, string> | undefined,\n ): void {\n if (!componentsState) return;\n Object.entries(componentsState).forEach(([id, action]) => {\n if (!(COMPONENT_ACTIONS as readonly string[]).includes(action)) {\n this.logger.error(\n `Unknown component action \"${action}\" for component with id \"${id}\"`,\n `Valid actions are ${COMPONENT_ACTIONS.map((a) => `\"${a}\"`).join(\n ', ',\n )}`,\n );\n }\n });\n apply(root, {}, componentsState);\n }\n\n /**\n * Set up real-time conditions for the current screen. Safe to call\n * twice — a second call rebuilds from screenState.\n *\n * Must run AFTER `updateScreenFromScreenState`, so the DOM reads below\n * see both server-shipped values and any component defaults from the\n * HTML.\n */\n initRealtimeConditions(\n rootElement: HTMLElement,\n screenState: ScreenState | undefined,\n ): void {\n this.#teardownRealtimeRuntime();\n\n const conditions = screenState?.realtimeComponentsConditions ?? [];\n if (!conditions.length) {\n this.logger.debug(\n `${LOG_PREFIX} no real-time rules to apply on this screen`,\n );\n return;\n }\n this.logger.info(\n `${LOG_PREFIX} found ${conditions.length} real-time rule(s) for this screen`,\n );\n\n // screenState.form uses \"phone\"; rules reference \"form.phone\".\n // Add the prefix on the way in.\n const initialSnapshot: FormSnapshot = {};\n Object.entries(screenState?.form ?? {}).forEach(([k, v]) => {\n initialSnapshot[`form.${k}`] = v;\n });\n\n // For every key the rules reference, read the current DOM value.\n // Component defaults (e.g. `checked=\"true\"` on a descope-checkbox)\n // live only in the HTML and don't make it into screenState.form, so\n // without this read the first evaluation would miss them.\n collectReferencedFormKeys(conditions).forEach((formKey) => {\n const el = findInputForFormKey(rootElement, formKey);\n if (!el) return;\n const v = readInputValue(el);\n if (v !== undefined) initialSnapshot[formKey] = v;\n });\n\n const touchedIds = collectTouchedComponentIds(conditions);\n\n // What to fall back to when a real-time rule stops matching for a\n // touched component — the actions set by server-only rules (rules\n // with no client-side conditions).\n const serverBaseline: Record<string, string> = {};\n // What's already painted on the DOM (touched components only), so\n // the first real-time evaluation can diff against the right state.\n const initialApplied: Record<string, string> = {};\n\n Object.entries(screenState?.componentsState ?? {}).forEach(\n ([id, action]) => {\n if (!touchedIds.has(id)) return;\n initialApplied[id] = action;\n },\n );\n\n Object.entries(screenState?.serverOnlyComponentsState ?? {}).forEach(\n ([id, action]) => {\n if (touchedIds.has(id)) {\n serverBaseline[id] = action;\n }\n },\n );\n\n const runtime: RealtimeRuntime = {\n conditions,\n touchedIds,\n snapshot: initialSnapshot,\n applied: initialApplied,\n serverBaseline,\n debounceTimer: null,\n paused: false,\n unsubscribePauseListener: null,\n inputHandler: () => {},\n root: rootElement,\n };\n\n // Re-run the rules now that we've read the real DOM values. The\n // server evaluated without seeing component defaults, so its\n // `componentsState` can disagree with what the user actually sees.\n // Apply the diff once before listening for input.\n const reconciled = effectiveActions(\n evaluateAll(conditions, initialSnapshot),\n serverBaseline,\n touchedIds,\n );\n if (!shallowEqualStringMap(initialApplied, reconciled)) {\n runtime.applied = apply(rootElement, initialApplied, reconciled);\n }\n\n runtime.inputHandler = (e: Event) =>\n this.#handleRealtimeInput(e as InputEvent);\n\n REALTIME_CONDITION_EVENTS.forEach((ev) => {\n rootElement.addEventListener(ev, runtime.inputHandler, true);\n });\n this.logger.debug(\n `${LOG_PREFIX} listening for \"${REALTIME_CONDITION_EVENTS.join(\n '\" and \"',\n )}\" events on form fields; ${\n Object.keys(initialApplied).length\n } component(s) start hidden / disabled / read-only by these rules`,\n );\n\n // Pause while a /next request is in flight. Without this, a debounced\n // evaluation could run between submit and the next screen render and\n // change components that are about to be replaced — causing flicker,\n // or hiding something the next screen needs visible.\n const pauseState = (this as unknown as PausableHost).nextRequestStatus;\n if (pauseState?.subscribe) {\n const handler = ({ isLoading }: { isLoading: boolean }) => {\n runtime.paused = isLoading;\n if (isLoading && runtime.debounceTimer) {\n clearTimeout(runtime.debounceTimer);\n runtime.debounceTimer = null;\n }\n };\n // subscribe returns a token; unsubscribe needs that token, not the\n // handler. Without storing it, handlers leak across screens and\n // keep old runtimes (and their DOM roots) alive.\n const token = pauseState.subscribe(handler);\n runtime.unsubscribePauseListener = () => {\n if (token !== undefined && token !== null) {\n pauseState.unsubscribe?.(token);\n }\n };\n }\n\n this.#rtRuntime = runtime;\n }\n\n #handleRealtimeInput(e: InputEvent): void {\n const runtime = this.#rtRuntime;\n if (!runtime.root || runtime.paused) return;\n\n const target = e.target as Element | null;\n if (!target) return;\n if (target.hasAttribute?.(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD)) return;\n\n const name = target.getAttribute?.('name');\n if (!name) return;\n\n // Update the snapshot only — evaluation is debounced. Use readInputValue\n // so checkboxes read the same way as at mount; otherwise `target.value`\n // would be the string \"on\" for native checkboxes and break is-true rules.\n const key = toFormKey(name);\n runtime.snapshot[key] = readInputValue(target);\n\n if (runtime.debounceTimer) {\n clearTimeout(runtime.debounceTimer);\n }\n runtime.debounceTimer = setTimeout(() => {\n runtime.debounceTimer = null;\n this.#reEvaluateRealtime();\n }, REALTIME_CONDITION_DEBOUNCE_MS);\n }\n\n #reEvaluateRealtime(): void {\n const runtime = this.#rtRuntime;\n if (!runtime.root) return;\n\n let next: Record<string, string>;\n try {\n next = effectiveActions(\n evaluateAll(runtime.conditions, runtime.snapshot),\n runtime.serverBaseline,\n runtime.touchedIds,\n );\n } catch (e) {\n this.logger.error(\n `${LOG_PREFIX} failed to evaluate real-time rules — keeping the previous state`,\n (e as Error)?.message,\n );\n return;\n }\n\n const prevApplied = runtime.applied;\n if (shallowEqualStringMap(prevApplied, next)) return;\n\n this.logger.debug(\n `${LOG_PREFIX} form changed — updating components: was ${JSON.stringify(\n prevApplied,\n )}, now ${JSON.stringify(next)}`,\n );\n runtime.applied = apply(runtime.root, prevApplied, next);\n }\n\n // Clean up listeners and timers when the host leaves the DOM. Reaches\n // us only if BaseDescopeWc calls `super.disconnectedCallback?.()`;\n // otherwise teardown happens lazily on the next initRealtimeConditions.\n disconnectedCallback() {\n // disconnectedCallback isn't on HTMLElement in the lib types, but it\n // exists at runtime — forward into super in case the chain uses it.\n super.disconnectedCallback?.();\n this.#teardownRealtimeRuntime();\n }\n\n #teardownRealtimeRuntime(): void {\n const r = this.#rtRuntime;\n if (r.debounceTimer) {\n clearTimeout(r.debounceTimer);\n }\n if (r.unsubscribePauseListener) {\n r.unsubscribePauseListener();\n }\n if (r.root) {\n // Undo anything we applied so the next screen starts clean. Skip\n // if the root is already gone (replaced by the next screen) —\n // nothing left to undo.\n if (Object.keys(r.applied).length > 0 && r.root.isConnected) {\n apply(r.root, r.applied, {});\n }\n REALTIME_CONDITION_EVENTS.forEach((ev) => {\n r.root!.removeEventListener(ev, r.inputHandler, true);\n });\n }\n this.#rtRuntime = emptyRuntime();\n }\n };\n },\n);\n"],"names":["LOG_PREFIX","readInputValue","el","HTMLInputElement","type","checked","value","shallowEqualStringMap","a","b","keysA","Object","keys","keysB","length","every","k","emptyRuntime","conditions","touchedIds","Set","snapshot","applied","serverBaseline","debounceTimer","paused","unsubscribePauseListener","inputHandler","root","effectiveActions","realtimeVerdict","out","forEach","id","componentConditionsMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","_a","constructor","_ComponentConditionsMixin_rtRuntime","set","this","applyComponentsState","componentsState","entries","action","COMPONENT_ACTIONS","includes","logger","error","map","join","apply","initRealtimeConditions","rootElement","screenState","__classPrivateFieldGet","_ComponentConditionsMixin_instances","_ComponentConditionsMixin_teardownRealtimeRuntime","call","_b","realtimeComponentsConditions","debug","info","initialSnapshot","_c","form","v","collectReferencedFormKeys","formKey","bare","startsWith","slice","querySelector","escapeSelector","findInputForFormKey","undefined","collectTouchedComponentIds","initialApplied","_d","has","_e","serverOnlyComponentsState","runtime","reconciled","evaluateAll","e","REALTIME_CONDITION_EVENTS","ev","addEventListener","pauseState","nextRequestStatus","subscribe","handler","isLoading","clearTimeout","token","unsubscribe","__classPrivateFieldSet","disconnectedCallback","super","target","hasAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","name","getAttribute","key","toFormKey","setTimeout","_ComponentConditionsMixin_reEvaluateRealtime","REALTIME_CONDITION_DEBOUNCE_MS","next","message","prevApplied","JSON","stringify","r","isConnected","removeEventListener"],"mappings":"gTAqBA,MAAMA,EAAa,wBAgEnB,SAASC,EAAeC,GACtB,OAAIA,aAAcC,iBACG,aAAZD,EAAGE,KAAsBF,EAAGG,QAAUH,EAAGI,MAE9C,YAAaJ,EACPA,EAAuCG,QAE7C,UAAWH,EACLA,EAAqCI,WAD/C,CAIF,CAEA,SAASC,EACPC,EACAC,GAEA,MAAMC,EAAQC,OAAOC,KAAKJ,GACpBK,EAAQF,OAAOC,KAAKH,GAC1B,OAAIC,EAAMI,SAAWD,EAAMC,QACpBJ,EAAMK,OAAOC,GAAMR,EAAEQ,KAAOP,EAAEO,IACvC,CAEA,SAASC,IACP,MAAO,CACLC,WAAY,GACZC,WAAY,IAAIC,IAChBC,SAAU,CAAE,EACZC,QAAS,CAAE,EACXC,eAAgB,CAAE,EAClBC,cAAe,KACfC,QAAQ,EACRC,yBAA0B,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ACxBmC,EAAAA,uBAAAf,KAAIgB,EAAA,IAAAoD,GAAJlD,KAAAlB,KAA0B,GACzBqE,EAA8BA,+BAClC,eAGC,MAAM3B,EAAU3B,EAAAA,uBAAAf,YAChB,IAAK0C,EAAQ1D,KAAM,OAEnB,IAAIsF,EACJ,IACEA,EAAOrF,EACL2D,cAAYF,EAAQpE,WAAYoE,EAAQjE,UACxCiE,EAAQ/D,eACR+D,EAAQnE,WAEX,CAAC,MAAOsE,GAKP,YAJA7C,KAAKO,OAAOC,MACV,GAAGpD,oEACFyF,aAAC,EAADA,EAAa0B,QAGjB,CAED,MAAMC,EAAc9B,EAAQhE,QACxBf,EAAsB6G,EAAaF,KAEvCtE,KAAKO,OAAOc,MACV,GAAGjE,6CAAsDqH,KAAKC,UAC5DF,WACQC,KAAKC,UAAUJ,MAE3B5B,EAAQhE,QAAUiC,QAAM+B,EAAQ1D,KAAMwF,EAAaF,GACpD,eAaC,MAAMK,EAAI5D,EAAAA,uBAAAf,YACN2E,EAAE/F,eACJ0E,aAAaqB,EAAE/F,eAEb+F,EAAE7F,0BACJ6F,EAAE7F,2BAEA6F,EAAE3F,OAIAjB,OAAOC,KAAK2G,EAAEjG,SAASR,OAAS,GAAKyG,EAAE3F,KAAK4F,aAC9CjE,EAAKA,MAACgE,EAAE3F,KAAM2F,EAAEjG,QAAS,CAAE,GAE7BoE,4BAA0B1D,SAAS2D,IACjC4B,EAAE3F,KAAM6F,oBAAoB9B,EAAI4B,EAAE5F,cAAc,EAAK,KAGzD0E,EAAAA,uBAAAzD,KAAIF,EAAczB,QACnB,EACDuB,CAAA"}
|
|
@@ -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 a}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as u}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as f,fetchContent as g,withRetry as p}from"../helpers/helpers.js";import m from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as b}from"../helpers/storage.js";import{transformFlowInputFormData as v,extractNestedAttribute as w}from"../helpers/flowInputs.js";import{formMountMixin as k}from"../mixins/formMountMixin.js";import{componentConditionsMixin as C}from"../mixins/componentConditionsMixin.js";import{duplicateFlowWarningMixin as y}from"../mixins/duplicateFlowWarningMixin.js";import{passwordManagerMixin as A}from"../mixins/passwordManagerMixin.js";import{CONFIG_FILENAME as x,PREV_VER_ASSETS_FOLDER as j}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as I}from"../constants/general.js";var E,M,L,S,U,O,W,D,P,N,F,K,R,T,B,H,J,V,q,$,z,Q;const G=r(s,o,k,C,y,A,n)(HTMLElement);class X extends G{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(),E.add(this),L.set(this,!1),S.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,E,"m",Q).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},U.set(this,new m),O.set(this,new m),W.set(this,{}),this.getComponentsContext=()=>t(this,W,"f"),this.nextRequestStatus=new m({isLoading:!1}),D.set(this,void 0),P.set(this,{popstate:t(this,E,"m",T).bind(this),componentsContext:t(this,E,"m",q).bind(this)}),N.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,N,r,"f"),t(this,E,"m",K).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return v(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return w(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,S,"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,S,t,"f"),b(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=u.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 a=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===a.length)return void a[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,O,"f").subscribe(t(this,E,"m",z).bind(this)),t(this,O,"f").update({isDebug:this.debug}),t(this,E,"m",R).call(this),yield t(this,E,"m",J).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:a,code:u,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,P,"f").popstate),window.addEventListener("components-context",t(this,P,"f").componentsContext),t(this,U,"f").subscribe(t(this,E,"m",H).bind(this)),t(this,U,"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:a,code:u,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,L,!0,"f")}))}disconnectedCallback(){var e;t(this,U,"f").unsubscribeAll(),t(this,O,"f").unsubscribeAll(),t(this,E,"m",$).call(this),window.removeEventListener("popstate",t(this,P,"f").popstate),window.removeEventListener("components-context",t(this,P,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,r){var o;if(null===(o=super.attributeChangedCallback)||void 0===o||o.call(this,e,i,r),this.shadowRoot.isConnected&&t(this,L,"f")&&i!==r&&M.observedAttributes.includes(e)){t(this,E,"m",R).call(this);const o=null===i;t(this,U,"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,O,"f").update({isDebug:this.debug})}}}M=X,L=new WeakMap,S=new WeakMap,U=new WeakMap,O=new WeakMap,W=new WeakMap,D=new WeakMap,P=new WeakMap,N=new WeakMap,E=new WeakSet,F=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},K=function(){t(this,E,"m",F).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},R=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","theme-override"];M.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},T=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,U,"f").update({stepId:e,executionId:i})},B=function(i,r){a&&"function"==typeof a||this.logger.error("SDK was not loaded properly",a,JSON.stringify(a));const o=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},M.sdkConfigOverrides),{projectId:i,baseUrl:r});t(this,S,"f")&&(o.customStorage=t(this,S,"f")),this.sdk=a(o),["start","next"].forEach((t=>{const i=this.sdk.flow[t],r=p(i,1e3,3);this.sdk.flow[t]=(...i)=>e(this,void 0,void 0,(function*(){try{return yield r(...i)}catch(e){return this.logger.error(`Error in sdk flow ${t} function`,e),{error:{errorCode:I,errorDescription:e.toString()}}}}))}))},H=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,E,"m",B).call(this,e,r)}t(this,N,"f").call(this,i)}))},J=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,E,"m",V).call(this))}))},V=function(){return e(this,void 0,void 0,(function*(){const t=f({projectId:this.projectId,filename:x,assetsFolder:j,baseUrl:this.baseStaticUrl});try{return yield g(t,"json"),!0}catch(t){return!1}}))},q=function(e){i(this,W,Object.assign(Object.assign({},t(this,W,"f")),e.detail),"f")},$=function(){var e;null===(e=t(this,D,"f"))||void 0===e||e.remove(),i(this,D,null,"f")},z=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,D,document.createElement("descope-debugger"),"f"),Object.assign(t(this,D,"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,D,"f"))):t(this,E,"m",$).call(this)}))},Q=function(e,i){var r;e&&this.debug&&(null===(r=t(this,D,"f"))||void 0===r||r.updateData({title:e,description:i}))},X.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.0.2"}};export{X 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{telemetryMixin as a}from"@descope/sdk-mixins/telemetry-mixin";import{createSdk as u}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as l}from"../constants/index.js";import{handleUrlParams as d,clearRunIdsFromUrl as c,camelCase as h,getRunIdsFromUrl as f,getContentUrl as g,fetchContent as p,withRetry as m}from"../helpers/helpers.js";import b from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as v}from"../helpers/storage.js";import{transformFlowInputFormData as w,extractNestedAttribute as k}from"../helpers/flowInputs.js";import{formMountMixin as C}from"../mixins/formMountMixin.js";import{componentConditionsMixin as y}from"../mixins/componentConditionsMixin.js";import{duplicateFlowWarningMixin as x}from"../mixins/duplicateFlowWarningMixin.js";import{passwordManagerMixin as A}from"../mixins/passwordManagerMixin.js";import{CONFIG_FILENAME as j,PREV_VER_ASSETS_FOLDER as I}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as E}from"../constants/general.js";var M,L,S,U,O,W,D,P,N,F,K,R,T,V,B,H,J,q,$,z,Q,G;const X=r(s,o,C,y,x,A,n,a)(HTMLElement);class Y extends X{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(),M.add(this),this.sdkVersion="4.2.0",S.set(this,!1),U.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,M,"m",G).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)}},O.set(this,new b),W.set(this,new b),D.set(this,{}),this.getComponentsContext=()=>t(this,D,"f"),this.nextRequestStatus=new b({isLoading:!1}),P.set(this,void 0),N.set(this,{popstate:t(this,M,"m",V).bind(this),componentsContext:t(this,M,"m",$).bind(this)}),F.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,F,r,"f"),t(this,M,"m",R).call(this)}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return w(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return k(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,U,"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,U,t,"f"),v(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=l.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 a=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===a.length)return void a[0].click();const u=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===u.length)"false"!==u[0].getAttribute("auto-submit")&&u[0].click();else if(0===u.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,W,"f").subscribe(t(this,M,"m",Q).bind(this)),t(this,W,"f").update({isDebug:this.debug}),t(this,M,"m",T).call(this),yield t(this,M,"m",J).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:a,code:u,isPopup:l,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=d(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,N,"f").popstate),window.addEventListener("components-context",t(this,N,"f").componentsContext),t(this,O,"f").subscribe(t(this,M,"m",H).bind(this)),t(this,O,"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:a,code:u,isPopup:l,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,S,!0,"f")}))}disconnectedCallback(){var e;t(this,O,"f").unsubscribeAll(),t(this,W,"f").unsubscribeAll(),t(this,M,"m",z).call(this),window.removeEventListener("popstate",t(this,N,"f").popstate),window.removeEventListener("components-context",t(this,N,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,r){var o;if(null===(o=super.attributeChangedCallback)||void 0===o||o.call(this,e,i,r),this.shadowRoot.isConnected&&t(this,S,"f")&&i!==r&&L.observedAttributes.includes(e)){t(this,M,"m",T).call(this);const o=null===i;t(this,O,"f").update((({stepId:t,executionId:i})=>{let s=t,n=i;return o||(n=null,s=null,c()),{[h(e)]:r,stepId:s,executionId:n}})),t(this,W,"f").update({isDebug:this.debug})}}}L=Y,S=new WeakMap,U=new WeakMap,O=new WeakMap,W=new WeakMap,D=new WeakMap,P=new WeakMap,N=new WeakMap,F=new WeakMap,M=new WeakSet,K=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 ")},R=function(){t(this,M,"m",K).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},T=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","theme-override"];L.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[h(e)])throw Error(`${e} cannot be empty`)}))},V=function(){const{stepId:e,executionId:i}=f(this.flowId);t(this,O,"f").update({stepId:e,executionId:i})},B=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},L.sdkConfigOverrides),{projectId:i,baseUrl:r});t(this,U,"f")&&(o.customStorage=t(this,U,"f")),this.sdk=u(o),["start","next"].forEach((t=>{const i=this.sdk.flow[t],r=m(i,1e3,3);this.sdk.flow[t]=(...i)=>e(this,void 0,void 0,(function*(){try{return yield r(...i)}catch(e){return this.logger.error(`Error in sdk flow ${t} function`,e),{error:{errorCode:E,errorDescription:e.toString()}}}}))}))},H=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,M,"m",B).call(this,e,r)}t(this,F,"f").call(this,i)}))},J=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,M,"m",q).call(this))}))},q=function(){return e(this,void 0,void 0,(function*(){const t=g({projectId:this.projectId,filename:j,assetsFolder:I,baseUrl:this.baseStaticUrl});try{return yield p(t,"json"),!0}catch(t){return!1}}))},$=function(e){i(this,D,Object.assign(Object.assign({},t(this,D,"f")),e.detail),"f")},z=function(){var e;null===(e=t(this,P,"f"))||void 0===e||e.remove(),i(this,P,null,"f")},Q=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,P,document.createElement("descope-debugger"),"f"),Object.assign(t(this,P,"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,P,"f"))):t(this,M,"m",z).call(this)}))},G=function(e,i){var r;e&&this.debug&&(null===(r=t(this,P,"f"))||void 0===r||r.updateData({title:e,description:i}))},Y.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.2.0"}};export{Y as default};
|
|
2
2
|
//# sourceMappingURL=BaseDescopeWc.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseDescopeWc.js","sources":["../../../src/lib/descope-wc/BaseDescopeWc.ts"],"sourcesContent":["import { compose } from '@descope/sdk-helpers';\n// eslint-disable-next-line import/no-duplicates\nimport { staticResourcesMixin } from '@descope/sdk-mixins/static-resources-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { themeMixin } from '@descope/sdk-mixins/theme-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { injectStyleMixin } from '@descope/sdk-mixins/inject-style-mixin';\nimport { createSdk } from '@descope/web-js-sdk';\nimport {\n CONFIG_FILENAME,\n ELEMENTS_TO_IGNORE_ENTER_KEY_ON,\n FETCH_EXCEPTION_ERROR_CODE,\n PREV_VER_ASSETS_FOLDER,\n} from '../constants';\nimport {\n camelCase,\n clearRunIdsFromUrl,\n fetchContent,\n getContentUrl,\n getRunIdsFromUrl,\n handleUrlParams,\n State,\n withRetry,\n} from '../helpers';\nimport {\n extractNestedAttribute,\n transformFlowInputFormData,\n} from '../helpers/flowInputs';\nimport { setCustomStorage } from '../helpers/storage';\nimport { IsChanged } from '../helpers/state';\nimport {\n formMountMixin,\n componentConditionsMixin,\n duplicateFlowWarningMixin,\n passwordManagerMixin,\n} from '../mixins';\nimport {\n AutoFocusOptions,\n CustomStorage,\n DebuggerMessage,\n DebugState,\n DescopeUI,\n FlowConfig,\n FlowState,\n FlowStateUpdateFn,\n FlowStatus,\n ProjectConfiguration,\n SdkConfig,\n} from '../types';\n\n// this is replaced in build time\ndeclare const BUILD_VERSION: string;\n\nconst BaseClass = compose(\n themeMixin,\n staticResourcesMixin,\n formMountMixin,\n componentConditionsMixin,\n duplicateFlowWarningMixin,\n passwordManagerMixin,\n injectStyleMixin,\n)(HTMLElement);\n\n// this base class is responsible for WC initialization\nclass BaseDescopeWc extends BaseClass {\n static get observedAttributes() {\n return [\n 'project-id',\n 'flow-id',\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'storage-prefix',\n 'preview',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'refresh-cookie-name',\n 'keep-last-authenticated-user-after-logout',\n 'validate-on-blur',\n 'style-id',\n ];\n }\n\n // this is a way for extending the sdk config from outside\n static sdkConfigOverrides: Partial<SdkConfig> = {\n baseHeaders: {\n 'x-descope-sdk-name': 'web-component',\n 'x-descope-sdk-version': BUILD_VERSION,\n },\n };\n\n #init = false;\n\n #customStorage: CustomStorage | undefined;\n\n flowStatus: FlowStatus = 'initial';\n\n loggerWrapper = {\n error: (message: string, description = '') => {\n this.logger.error(message, description, new Error());\n this.#updateDebuggerMessages(message, description);\n },\n warn: (message: string, description = '') => {\n this.logger.warn(message, description);\n },\n info: (message: string, description = '', state: any = {}) => {\n this.logger.info(message, description, state);\n },\n debug: (message: string, description = '') => {\n this.logger.debug(message, description);\n },\n };\n\n #flowState = new State<FlowState>();\n\n #debugState = new State<DebugState>();\n\n #componentsContext = {};\n\n getComponentsContext = () => this.#componentsContext;\n\n nextRequestStatus = new State<{ isLoading: boolean }>({ isLoading: false });\n\n rootElement: HTMLDivElement;\n\n contentRootElement: HTMLDivElement;\n\n slotElement: HTMLSlotElement;\n\n #debuggerEle: HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n #eventsCbRefs = {\n popstate: this.#syncStateIdFromUrl.bind(this),\n componentsContext: this.#handleComponentsContext.bind(this),\n };\n\n sdk: ReturnType<typeof createSdk>;\n\n #updateExecState: FlowStateUpdateFn;\n\n descopeUI: Promise<DescopeUI>;\n\n constructor(updateExecState: FlowStateUpdateFn) {\n super();\n this.#updateExecState = updateExecState;\n\n this.#initShadowDom();\n }\n\n #loadInitStyle() {\n this.injectStyle(`\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n `);\n }\n\n #initShadowDom() {\n this.#loadInitStyle();\n this.slotElement = document.createElement('slot');\n this.slotElement.classList.add('hidden');\n this.rootElement.appendChild(this.slotElement);\n }\n\n get flowId() {\n return this.getAttribute('flow-id');\n }\n\n get client() {\n try {\n return (JSON.parse(this.getAttribute('client')) || {}) as Record<\n string,\n any\n >;\n } catch (e) {\n return {};\n }\n }\n\n get redirectUrl() {\n return this.getAttribute('redirect-url') || undefined;\n }\n\n get debug() {\n return this.getAttribute('debug') === 'true';\n }\n\n get locale() {\n return this.getAttribute('locale') || undefined;\n }\n\n get autoFocus(): AutoFocusOptions {\n const res = this.getAttribute('auto-focus') ?? 'true';\n if (res === 'skipFirstScreen') {\n return res;\n }\n return res === 'true';\n }\n\n get validateOnBlur() {\n return this.getAttribute('validate-on-blur') === 'true';\n }\n\n get storeLastAuthenticatedUser() {\n const res = this.getAttribute('store-last-authenticated-user') ?? 'true';\n return res === 'true';\n }\n\n get refreshCookieName() {\n return this.getAttribute('refresh-cookie-name') || '';\n }\n\n get keepLastAuthenticatedUserAfterLogout() {\n const res = this.getAttribute('keep-last-authenticated-user-after-logout');\n return res === 'true';\n }\n\n get storagePrefix() {\n return this.getAttribute('storage-prefix') || '';\n }\n\n get preview() {\n return !!this.getAttribute('preview');\n }\n\n get formConfig() {\n return transformFlowInputFormData(this.form);\n }\n\n get form() {\n return this.getAttribute('form');\n }\n\n get formConfigValues() {\n return extractNestedAttribute(this.formConfig, 'value');\n }\n\n get outboundAppId() {\n return this.getAttribute('outbound-app-id');\n }\n\n get outboundAppScopes() {\n try {\n const scopes = JSON.parse(this.getAttribute('outbound-app-scopes'));\n if (!scopes) return null;\n return scopes;\n } catch (err) {\n return null;\n }\n }\n\n get popupOrigin(): string | null {\n return this.getAttribute('popup-origin');\n }\n\n // grouped getter/setter for customStorage\n get customStorage(): CustomStorage | undefined {\n return this.#customStorage;\n }\n\n set customStorage(storage: CustomStorage | undefined) {\n if (storage && typeof storage.getItem !== 'function') {\n throw new Error('Custom storage must have a getItem method');\n }\n if (storage && typeof storage.setItem !== 'function') {\n throw new Error('Custom storage must have a setItem method');\n }\n if (storage && typeof storage.removeItem !== 'function') {\n throw new Error('Custom storage must have a removeItem method');\n }\n this.#customStorage = storage;\n setCustomStorage(storage);\n }\n\n #validateAttrs() {\n const optionalAttributes = [\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'refresh-cookie-name',\n 'keep-last-authenticated-user-after-logout',\n 'preview',\n 'storage-prefix',\n 'form',\n 'client',\n 'validate-on-blur',\n 'style-id',\n 'outbound-app-id',\n 'outbound-app-scopes',\n 'theme-override',\n ];\n\n BaseDescopeWc.observedAttributes.forEach((attr: string) => {\n if (!optionalAttributes.includes(attr) && !this[camelCase(attr)])\n throw Error(`${attr} cannot be empty`);\n });\n }\n\n #syncStateIdFromUrl() {\n const { stepId, executionId } = getRunIdsFromUrl(this.flowId);\n this.#flowState.update({ stepId, executionId });\n }\n\n #createSdk(projectId: string, baseUrl: string) {\n if (!createSdk || typeof createSdk !== 'function') {\n this.logger.error(\n 'SDK was not loaded properly',\n createSdk,\n JSON.stringify(createSdk),\n );\n }\n const config: any = {\n // Use persist tokens options in order to add existing tokens in outgoing requests (if they exists)\n persistTokens: true,\n preview: this.preview,\n storagePrefix: this.storagePrefix,\n storeLastAuthenticatedUser: this.storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout:\n this.keepLastAuthenticatedUserAfterLogout,\n refreshCookieName: this.refreshCookieName,\n ...BaseDescopeWc.sdkConfigOverrides,\n projectId,\n baseUrl,\n };\n if (this.#customStorage) {\n config.customStorage = this.#customStorage;\n }\n\n this.sdk = createSdk(config);\n\n // we are wrapping the next & start function so we can indicate the request status\n ['start', 'next'].forEach((key) => {\n const origFn = this.sdk.flow[key];\n const fnWithRetry = withRetry(origFn, 1000, 3);\n\n this.sdk.flow[key] = async (...args: Parameters<typeof origFn>) => {\n try {\n const resp = await fnWithRetry(...args);\n return resp;\n } catch (e) {\n this.logger.error(`Error in sdk flow ${key} function`, e);\n // return a generic error object in case of an error\n return {\n error: {\n errorCode: FETCH_EXCEPTION_ERROR_CODE,\n errorDescription: e.toString(),\n },\n };\n }\n };\n });\n }\n\n async #onFlowChange(\n currentState: FlowState,\n _prevState: FlowState,\n isChanged: IsChanged<FlowState>,\n ) {\n const { projectId, baseUrl } = currentState;\n\n const shouldCreateSdkInstance =\n isChanged('projectId') || isChanged('baseUrl');\n\n if (shouldCreateSdkInstance) {\n if (!projectId) return;\n // Initialize the sdk when got a new project id\n this.#createSdk(projectId, baseUrl);\n }\n\n // update runtime state\n this.#updateExecState(currentState);\n }\n\n async #getIsFlowsVersionMismatch() {\n const config = await this.getConfig();\n\n return (\n 'isMissingConfig' in config &&\n config.isMissingConfig &&\n (await this.#isPrevVerConfig())\n );\n }\n\n // we are not using fetchStaticResource here\n // because we do not want to use the fallbacks mechanism\n async #isPrevVerConfig() {\n const prevVerConfigUrl = getContentUrl({\n projectId: this.projectId,\n filename: CONFIG_FILENAME,\n assetsFolder: PREV_VER_ASSETS_FOLDER,\n baseUrl: this.baseStaticUrl,\n });\n try {\n await fetchContent(prevVerConfigUrl, 'json');\n return true;\n } catch (e) {\n return false;\n }\n }\n\n getConfig = async () => (await this.config) || { isMissingConfig: true };\n\n #handleComponentsContext(e: CustomEvent) {\n this.#componentsContext = { ...this.#componentsContext, ...e.detail };\n }\n\n get isRestartOnError() {\n return this.getAttribute('restart-on-error') === 'true';\n }\n\n async getExecutionContext() {\n const config = await this.getConfig();\n return 'executionContext' in config ? config.executionContext : undefined;\n }\n\n #disableDebugger() {\n this.#debuggerEle?.remove();\n this.#debuggerEle = null;\n }\n\n async #handleDebugMode({ isDebug }) {\n if (isDebug) {\n this.#debuggerEle = document.createElement(\n 'descope-debugger',\n ) as HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n Object.assign(this.#debuggerEle.style, {\n position: 'fixed',\n top: '0',\n right: '0',\n height: '100vh',\n width: '100vw',\n pointerEvents: 'none',\n zIndex: 99999,\n });\n\n // we are importing the debugger dynamically so we won't load it when it's not needed\n await import('../debugger-wc');\n\n document.body.appendChild(this.#debuggerEle);\n } else {\n this.#disableDebugger();\n }\n }\n\n #updateDebuggerMessages(title: string, description: string) {\n if (title && this.debug)\n this.#debuggerEle?.updateData({ title, description });\n }\n\n async getProjectConfig(): Promise<ProjectConfiguration> {\n const config = await this.getConfig();\n return 'projectConfig' in config ? config.projectConfig : undefined;\n }\n\n async getFlowConfig(): Promise<FlowConfig> {\n const projectConfig = await this.getProjectConfig();\n\n const flowConfig =\n projectConfig?.flows?.[this.flowId] || ({} as FlowConfig);\n flowConfig.version ??= 0;\n return flowConfig;\n }\n\n async getTargetLocales() {\n const flowConfig = await this.getFlowConfig();\n return (flowConfig?.targetLocales || []).map((locale: string) =>\n locale.toLowerCase(),\n );\n }\n\n handleKeyPress() {\n this.logger.debug('Enable key press handler');\n // we want to simulate submit when the user presses Enter\n this.rootElement.onkeydown = (e) => {\n // we do not want to submit the form if the focus is on a link element\n const isLinkEleFocused =\n !!this.shadowRoot.activeElement?.getAttribute('href');\n const isIgnoredElementFocused = ELEMENTS_TO_IGNORE_ENTER_KEY_ON.includes(\n this.shadowRoot.activeElement?.localName ?? '',\n );\n\n if (e.key !== 'Enter' || isLinkEleFocused || isIgnoredElementFocused)\n return;\n\n e.preventDefault();\n const buttons: NodeListOf<HTMLButtonElement> =\n this.rootElement.querySelectorAll('descope-button');\n\n // in case there is a single button on the page, click on it\n if (\n buttons.length === 1 &&\n buttons[0].getAttribute('auto-submit') !== 'false'\n ) {\n buttons[0].click();\n return;\n }\n\n const autoSubmitButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('auto-submit') === 'true',\n );\n if (autoSubmitButtons.length === 1) {\n autoSubmitButtons[0].click();\n return;\n }\n\n const genericButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'button',\n );\n\n // in case there is a single \"generic\" button on the page, click on it\n if (genericButtons.length === 1) {\n if (genericButtons[0].getAttribute('auto-submit') !== 'false') {\n genericButtons[0].click();\n }\n } else if (genericButtons.length === 0) {\n const ssoButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'sso',\n );\n\n // in case there is a single \"sso\" button on the page, click on it\n if (ssoButtons.length === 1) {\n if (ssoButtons[0].getAttribute('auto-submit') !== 'false') {\n ssoButtons[0].click();\n }\n }\n }\n };\n }\n\n disableKeyPressHandler() {\n this.logger.debug('Disable key press handler');\n this.rootElement.onkeydown = null;\n }\n\n async getComponentsVersion() {\n const config = await this.getConfig();\n const version =\n 'projectConfig' in config ? config.projectConfig?.componentsVersion : {};\n\n if (version) return version;\n\n this.logger.error('Did not get components version, using latest version');\n\n return 'latest';\n }\n\n static descopeUI: any;\n\n async init() {\n this.flowStatus = 'loading';\n ['ready', 'error', 'success'].forEach((status: FlowStatus) =>\n this.addEventListener(status, () => {\n this.flowStatus = status;\n }),\n );\n\n await super.init?.();\n this.#debugState.subscribe(this.#handleDebugMode.bind(this));\n this.#debugState.update({ isDebug: this.debug });\n\n this.#validateAttrs();\n\n if (await this.#getIsFlowsVersionMismatch()) {\n this.loggerWrapper.error(\n 'This SDK version does not support your flows version',\n 'Make sure to upgrade your flows to the latest version or use an older SDK version',\n );\n\n return;\n }\n\n const config = await this.getConfig();\n if ('isMissingConfig' in config && config.isMissingConfig) {\n this.loggerWrapper.error(\n 'Cannot get config file',\n 'Make sure that your projectId & flowId are correct',\n );\n\n return;\n }\n\n const {\n executionId,\n stepId,\n token,\n code,\n isPopup,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ssoQueryParams,\n } = handleUrlParams(this.flowId, this.loggerWrapper);\n\n // we want to update the state when user clicks on back in the browser\n window.addEventListener('popstate', this.#eventsCbRefs.popstate);\n\n // adding event to listen to events coming from components (e.g. recaptcha risk token) that want to add data to the context\n // this data will be sent to the server on the next request\n window.addEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n\n this.#flowState.subscribe(this.#onFlowChange.bind(this));\n\n this.#flowState.update({\n projectId: this.projectId,\n flowId: this.flowId,\n baseUrl: this.baseUrl,\n tenant: this.tenantId,\n redirectUrl: this.redirectUrl,\n locale: this.locale,\n stepId,\n executionId,\n token,\n code,\n isPopup,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ...ssoQueryParams,\n });\n\n this.#init = true;\n }\n\n disconnectedCallback() {\n this.#flowState.unsubscribeAll();\n this.#debugState.unsubscribeAll();\n this.#disableDebugger();\n window.removeEventListener('popstate', this.#eventsCbRefs.popstate);\n window.removeEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n // Forward to the composed mixin chain so each mixin's\n // disconnectedCallback (e.g. componentConditionsMixin) gets to clean up.\n // Without this, mixin disconnectedCallbacks are dead code.\n super.disconnectedCallback?.();\n }\n\n attributeChangedCallback(\n attrName: string,\n oldValue: string,\n newValue: string,\n ) {\n // Forward to the composed mixin chain first so other mixins always receive\n // the callback, regardless of the early return below.\n super.attributeChangedCallback?.(attrName, oldValue, newValue);\n\n if (!this.shadowRoot.isConnected || !this.#init) return;\n\n if (\n oldValue !== newValue &&\n BaseDescopeWc.observedAttributes.includes(attrName)\n ) {\n this.#validateAttrs();\n\n const isInitialRun = oldValue === null;\n\n this.#flowState.update(({ stepId, executionId }) => {\n let newStepId = stepId;\n let newExecutionId = executionId;\n\n // If not initial run and we got a new project/flow, we want to restart the step\n if (!isInitialRun) {\n newExecutionId = null;\n newStepId = null;\n clearRunIdsFromUrl();\n }\n\n return {\n [camelCase(attrName)]: newValue,\n stepId: newStepId,\n executionId: newExecutionId,\n };\n });\n\n this.#debugState.update({ isDebug: this.debug });\n }\n }\n}\n\nexport default BaseDescopeWc;\n"],"names":["BaseClass","compose","themeMixin","staticResourcesMixin","formMountMixin","componentConditionsMixin","duplicateFlowWarningMixin","passwordManagerMixin","injectStyleMixin","HTMLElement","BaseDescopeWc","observedAttributes","constructor","updateExecState","super","_BaseDescopeWc_init","set","this","_BaseDescopeWc_customStorage","flowStatus","loggerWrapper","error","message","description","logger","Error","__classPrivateFieldGet","call","warn","info","state","debug","_BaseDescopeWc_flowState","State","_BaseDescopeWc_debugState","_BaseDescopeWc_componentsContext","getComponentsContext","nextRequestStatus","isLoading","_BaseDescopeWc_debuggerEle","_BaseDescopeWc_eventsCbRefs","popstate","_BaseDescopeWc_instances","_BaseDescopeWc_syncStateIdFromUrl","bind","componentsContext","_BaseDescopeWc_handleComponentsContext","_BaseDescopeWc_updateExecState","getConfig","config","isMissingConfig","__classPrivateFieldSet","_BaseDescopeWc_initShadowDom","flowId","getAttribute","client","JSON","parse","e","redirectUrl","undefined","locale","autoFocus","res","_b","validateOnBlur","storeLastAuthenticatedUser","refreshCookieName","keepLastAuthenticatedUserAfterLogout","storagePrefix","preview","formConfig","transformFlowInputFormData","form","formConfigValues","extractNestedAttribute","outboundAppId","outboundAppScopes","scopes","err","popupOrigin","customStorage","storage","getItem","setItem","removeItem","setCustomStorage","isRestartOnError","getExecutionContext","executionContext","getProjectConfig","projectConfig","getFlowConfig","flowConfig","flows","_c","version","getTargetLocales","targetLocales","map","toLowerCase","handleKeyPress","rootElement","onkeydown","isLinkEleFocused","shadowRoot","activeElement","isIgnoredElementFocused","ELEMENTS_TO_IGNORE_ENTER_KEY_ON","includes","localName","_d","key","preventDefault","buttons","querySelectorAll","length","click","autoSubmitButtons","Array","from","filter","button","genericButtons","ssoButtons","disableKeyPressHandler","getComponentsVersion","componentsVersion","init","forEach","status","addEventListener","_super","subscribe","_BaseDescopeWc_handleDebugMode","update","isDebug","_BaseDescopeWc_validateAttrs","_BaseDescopeWc_getIsFlowsVersionMismatch","executionId","stepId","token","code","isPopup","exchangeError","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthCodeChallenge","redirectAuthInitiator","ssoQueryParams","handleUrlParams","window","_BaseDescopeWc_onFlowChange","Object","assign","projectId","baseUrl","tenant","tenantId","disconnectedCallback","unsubscribeAll","_BaseDescopeWc_disableDebugger","removeEventListener","attributeChangedCallback","attrName","oldValue","newValue","isConnected","_a","isInitialRun","newStepId","newExecutionId","clearRunIdsFromUrl","camelCase","injectStyle","_BaseDescopeWc_loadInitStyle","slotElement","document","createElement","classList","add","appendChild","optionalAttributes","attr","getRunIdsFromUrl","_BaseDescopeWc_createSdk","createSdk","stringify","persistTokens","sdkConfigOverrides","sdk","origFn","flow","fnWithRetry","withRetry","args","__awaiter","errorCode","FETCH_EXCEPTION_ERROR_CODE","errorDescription","toString","currentState","_prevState","isChanged","_BaseDescopeWc_isPrevVerConfig","prevVerConfigUrl","getContentUrl","filename","CONFIG_FILENAME","assetsFolder","PREV_VER_ASSETS_FOLDER","baseStaticUrl","fetchContent","detail","remove","arguments","style","position","top","right","height","width","pointerEvents","zIndex","import","body","_BaseDescopeWc_updateDebuggerMessages","title","updateData","baseHeaders"],"mappings":"s3CAqDA,MAAMA,EAAYC,EAChBC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAPgBP,CAQhBQ,aAGF,MAAMC,UAAsBV,EAC1B,6BAA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5M,gBAC3C,EA5YOb,EAAAmL,mBAAyC,CAC9CwC,YAAa,CACX,qBAAsB,gBACtB,wBAAyB"}
|
|
1
|
+
{"version":3,"file":"BaseDescopeWc.js","sources":["../../../src/lib/descope-wc/BaseDescopeWc.ts"],"sourcesContent":["import { compose } from '@descope/sdk-helpers';\n// eslint-disable-next-line import/no-duplicates\nimport { staticResourcesMixin } from '@descope/sdk-mixins/static-resources-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { themeMixin } from '@descope/sdk-mixins/theme-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { injectStyleMixin } from '@descope/sdk-mixins/inject-style-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { telemetryMixin } from '@descope/sdk-mixins/telemetry-mixin';\nimport { createSdk } from '@descope/web-js-sdk';\nimport {\n CONFIG_FILENAME,\n ELEMENTS_TO_IGNORE_ENTER_KEY_ON,\n FETCH_EXCEPTION_ERROR_CODE,\n PREV_VER_ASSETS_FOLDER,\n} from '../constants';\nimport {\n camelCase,\n clearRunIdsFromUrl,\n fetchContent,\n getContentUrl,\n getRunIdsFromUrl,\n handleUrlParams,\n State,\n withRetry,\n} from '../helpers';\nimport {\n extractNestedAttribute,\n transformFlowInputFormData,\n} from '../helpers/flowInputs';\nimport { setCustomStorage } from '../helpers/storage';\nimport { IsChanged } from '../helpers/state';\nimport {\n formMountMixin,\n componentConditionsMixin,\n duplicateFlowWarningMixin,\n passwordManagerMixin,\n} from '../mixins';\nimport {\n AutoFocusOptions,\n CustomStorage,\n DebuggerMessage,\n DebugState,\n DescopeUI,\n FlowConfig,\n FlowState,\n FlowStateUpdateFn,\n FlowStatus,\n ProjectConfiguration,\n SdkConfig,\n} from '../types';\n\n// this is replaced in build time\ndeclare const BUILD_VERSION: string;\n\nconst BaseClass = compose(\n themeMixin,\n staticResourcesMixin,\n formMountMixin,\n componentConditionsMixin,\n duplicateFlowWarningMixin,\n passwordManagerMixin,\n injectStyleMixin,\n telemetryMixin,\n)(HTMLElement);\n\n// this base class is responsible for WC initialization\nclass BaseDescopeWc extends BaseClass {\n static get observedAttributes() {\n return [\n 'project-id',\n 'flow-id',\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'storage-prefix',\n 'preview',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'refresh-cookie-name',\n 'keep-last-authenticated-user-after-logout',\n 'validate-on-blur',\n 'style-id',\n ];\n }\n\n sdkVersion = BUILD_VERSION;\n\n // this is a way for extending the sdk config from outside\n static sdkConfigOverrides: Partial<SdkConfig> = {\n baseHeaders: {\n 'x-descope-sdk-name': 'web-component',\n 'x-descope-sdk-version': BUILD_VERSION,\n },\n };\n\n #init = false;\n\n #customStorage: CustomStorage | undefined;\n\n flowStatus: FlowStatus = 'initial';\n\n loggerWrapper = {\n error: (message: string, description = '') => {\n this.logger.error(message, description, new Error());\n this.#updateDebuggerMessages(message, description);\n },\n warn: (message: string, description = '') => {\n this.logger.warn(message, description);\n },\n info: (message: string, description = '', state: any = {}) => {\n this.logger.info(message, description, state);\n },\n debug: (message: string, description = '') => {\n this.logger.debug(message, description);\n },\n };\n\n #flowState = new State<FlowState>();\n\n #debugState = new State<DebugState>();\n\n #componentsContext = {};\n\n getComponentsContext = () => this.#componentsContext;\n\n nextRequestStatus = new State<{ isLoading: boolean }>({ isLoading: false });\n\n rootElement: HTMLDivElement;\n\n contentRootElement: HTMLDivElement;\n\n slotElement: HTMLSlotElement;\n\n #debuggerEle: HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n #eventsCbRefs = {\n popstate: this.#syncStateIdFromUrl.bind(this),\n componentsContext: this.#handleComponentsContext.bind(this),\n };\n\n sdk: ReturnType<typeof createSdk>;\n\n #updateExecState: FlowStateUpdateFn;\n\n descopeUI: Promise<DescopeUI>;\n\n constructor(updateExecState: FlowStateUpdateFn) {\n super();\n this.#updateExecState = updateExecState;\n\n this.#initShadowDom();\n }\n\n #loadInitStyle() {\n this.injectStyle(`\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n `);\n }\n\n #initShadowDom() {\n this.#loadInitStyle();\n this.slotElement = document.createElement('slot');\n this.slotElement.classList.add('hidden');\n this.rootElement.appendChild(this.slotElement);\n }\n\n get client() {\n try {\n return (JSON.parse(this.getAttribute('client')) || {}) as Record<\n string,\n any\n >;\n } catch (e) {\n return {};\n }\n }\n\n get redirectUrl() {\n return this.getAttribute('redirect-url') || undefined;\n }\n\n get debug() {\n return this.getAttribute('debug') === 'true';\n }\n\n get locale() {\n return this.getAttribute('locale') || undefined;\n }\n\n get autoFocus(): AutoFocusOptions {\n const res = this.getAttribute('auto-focus') ?? 'true';\n if (res === 'skipFirstScreen') {\n return res;\n }\n return res === 'true';\n }\n\n get validateOnBlur() {\n return this.getAttribute('validate-on-blur') === 'true';\n }\n\n get storeLastAuthenticatedUser() {\n const res = this.getAttribute('store-last-authenticated-user') ?? 'true';\n return res === 'true';\n }\n\n get refreshCookieName() {\n return this.getAttribute('refresh-cookie-name') || '';\n }\n\n get keepLastAuthenticatedUserAfterLogout() {\n const res = this.getAttribute('keep-last-authenticated-user-after-logout');\n return res === 'true';\n }\n\n get storagePrefix() {\n return this.getAttribute('storage-prefix') || '';\n }\n\n get preview() {\n return !!this.getAttribute('preview');\n }\n\n get formConfig() {\n return transformFlowInputFormData(this.form);\n }\n\n get form() {\n return this.getAttribute('form');\n }\n\n get formConfigValues() {\n return extractNestedAttribute(this.formConfig, 'value');\n }\n\n get outboundAppId() {\n return this.getAttribute('outbound-app-id');\n }\n\n get outboundAppScopes() {\n try {\n const scopes = JSON.parse(this.getAttribute('outbound-app-scopes'));\n if (!scopes) return null;\n return scopes;\n } catch (err) {\n return null;\n }\n }\n\n get popupOrigin(): string | null {\n return this.getAttribute('popup-origin');\n }\n\n // grouped getter/setter for customStorage\n get customStorage(): CustomStorage | undefined {\n return this.#customStorage;\n }\n\n set customStorage(storage: CustomStorage | undefined) {\n if (storage && typeof storage.getItem !== 'function') {\n throw new Error('Custom storage must have a getItem method');\n }\n if (storage && typeof storage.setItem !== 'function') {\n throw new Error('Custom storage must have a setItem method');\n }\n if (storage && typeof storage.removeItem !== 'function') {\n throw new Error('Custom storage must have a removeItem method');\n }\n this.#customStorage = storage;\n setCustomStorage(storage);\n }\n\n #validateAttrs() {\n const optionalAttributes = [\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'refresh-cookie-name',\n 'keep-last-authenticated-user-after-logout',\n 'preview',\n 'storage-prefix',\n 'form',\n 'client',\n 'validate-on-blur',\n 'style-id',\n 'outbound-app-id',\n 'outbound-app-scopes',\n 'theme-override',\n ];\n\n BaseDescopeWc.observedAttributes.forEach((attr: string) => {\n if (!optionalAttributes.includes(attr) && !this[camelCase(attr)])\n throw Error(`${attr} cannot be empty`);\n });\n }\n\n #syncStateIdFromUrl() {\n const { stepId, executionId } = getRunIdsFromUrl(this.flowId);\n this.#flowState.update({ stepId, executionId });\n }\n\n #createSdk(projectId: string, baseUrl: string) {\n if (!createSdk || typeof createSdk !== 'function') {\n this.logger.error(\n 'SDK was not loaded properly',\n createSdk,\n JSON.stringify(createSdk),\n );\n }\n const config: any = {\n // Use persist tokens options in order to add existing tokens in outgoing requests (if they exists)\n persistTokens: true,\n preview: this.preview,\n storagePrefix: this.storagePrefix,\n storeLastAuthenticatedUser: this.storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout:\n this.keepLastAuthenticatedUserAfterLogout,\n refreshCookieName: this.refreshCookieName,\n ...BaseDescopeWc.sdkConfigOverrides,\n projectId,\n baseUrl,\n };\n if (this.#customStorage) {\n config.customStorage = this.#customStorage;\n }\n\n this.sdk = createSdk(config);\n\n // we are wrapping the next & start function so we can indicate the request status\n ['start', 'next'].forEach((key) => {\n const origFn = this.sdk.flow[key];\n const fnWithRetry = withRetry(origFn, 1000, 3);\n\n this.sdk.flow[key] = async (...args: Parameters<typeof origFn>) => {\n try {\n const resp = await fnWithRetry(...args);\n return resp;\n } catch (e) {\n this.logger.error(`Error in sdk flow ${key} function`, e);\n // return a generic error object in case of an error\n return {\n error: {\n errorCode: FETCH_EXCEPTION_ERROR_CODE,\n errorDescription: e.toString(),\n },\n };\n }\n };\n });\n }\n\n async #onFlowChange(\n currentState: FlowState,\n _prevState: FlowState,\n isChanged: IsChanged<FlowState>,\n ) {\n const { projectId, baseUrl } = currentState;\n\n const shouldCreateSdkInstance =\n isChanged('projectId') || isChanged('baseUrl');\n\n if (shouldCreateSdkInstance) {\n if (!projectId) return;\n // Initialize the sdk when got a new project id\n this.#createSdk(projectId, baseUrl);\n }\n\n // update runtime state\n this.#updateExecState(currentState);\n }\n\n async #getIsFlowsVersionMismatch() {\n const config = await this.getConfig();\n\n return (\n 'isMissingConfig' in config &&\n config.isMissingConfig &&\n (await this.#isPrevVerConfig())\n );\n }\n\n // we are not using fetchStaticResource here\n // because we do not want to use the fallbacks mechanism\n async #isPrevVerConfig() {\n const prevVerConfigUrl = getContentUrl({\n projectId: this.projectId,\n filename: CONFIG_FILENAME,\n assetsFolder: PREV_VER_ASSETS_FOLDER,\n baseUrl: this.baseStaticUrl,\n });\n try {\n await fetchContent(prevVerConfigUrl, 'json');\n return true;\n } catch (e) {\n return false;\n }\n }\n\n getConfig = async () => (await this.config) || { isMissingConfig: true };\n\n #handleComponentsContext(e: CustomEvent) {\n this.#componentsContext = { ...this.#componentsContext, ...e.detail };\n }\n\n get isRestartOnError() {\n return this.getAttribute('restart-on-error') === 'true';\n }\n\n async getExecutionContext() {\n const config = await this.getConfig();\n return 'executionContext' in config ? config.executionContext : undefined;\n }\n\n #disableDebugger() {\n this.#debuggerEle?.remove();\n this.#debuggerEle = null;\n }\n\n async #handleDebugMode({ isDebug }) {\n if (isDebug) {\n this.#debuggerEle = document.createElement(\n 'descope-debugger',\n ) as HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n Object.assign(this.#debuggerEle.style, {\n position: 'fixed',\n top: '0',\n right: '0',\n height: '100vh',\n width: '100vw',\n pointerEvents: 'none',\n zIndex: 99999,\n });\n\n // we are importing the debugger dynamically so we won't load it when it's not needed\n await import('../debugger-wc');\n\n document.body.appendChild(this.#debuggerEle);\n } else {\n this.#disableDebugger();\n }\n }\n\n #updateDebuggerMessages(title: string, description: string) {\n if (title && this.debug)\n this.#debuggerEle?.updateData({ title, description });\n }\n\n async getProjectConfig(): Promise<ProjectConfiguration> {\n const config = await this.getConfig();\n return 'projectConfig' in config ? config.projectConfig : undefined;\n }\n\n async getFlowConfig(): Promise<FlowConfig> {\n const projectConfig = await this.getProjectConfig();\n\n const flowConfig =\n projectConfig?.flows?.[this.flowId] || ({} as FlowConfig);\n flowConfig.version ??= 0;\n return flowConfig;\n }\n\n async getTargetLocales() {\n const flowConfig = await this.getFlowConfig();\n return (flowConfig?.targetLocales || []).map((locale: string) =>\n locale.toLowerCase(),\n );\n }\n\n handleKeyPress() {\n this.logger.debug('Enable key press handler');\n // we want to simulate submit when the user presses Enter\n this.rootElement.onkeydown = (e) => {\n // we do not want to submit the form if the focus is on a link element\n const isLinkEleFocused =\n !!this.shadowRoot.activeElement?.getAttribute('href');\n const isIgnoredElementFocused = ELEMENTS_TO_IGNORE_ENTER_KEY_ON.includes(\n this.shadowRoot.activeElement?.localName ?? '',\n );\n\n if (e.key !== 'Enter' || isLinkEleFocused || isIgnoredElementFocused)\n return;\n\n e.preventDefault();\n const buttons: NodeListOf<HTMLButtonElement> =\n this.rootElement.querySelectorAll('descope-button');\n\n // in case there is a single button on the page, click on it\n if (\n buttons.length === 1 &&\n buttons[0].getAttribute('auto-submit') !== 'false'\n ) {\n buttons[0].click();\n return;\n }\n\n const autoSubmitButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('auto-submit') === 'true',\n );\n if (autoSubmitButtons.length === 1) {\n autoSubmitButtons[0].click();\n return;\n }\n\n const genericButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'button',\n );\n\n // in case there is a single \"generic\" button on the page, click on it\n if (genericButtons.length === 1) {\n if (genericButtons[0].getAttribute('auto-submit') !== 'false') {\n genericButtons[0].click();\n }\n } else if (genericButtons.length === 0) {\n const ssoButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'sso',\n );\n\n // in case there is a single \"sso\" button on the page, click on it\n if (ssoButtons.length === 1) {\n if (ssoButtons[0].getAttribute('auto-submit') !== 'false') {\n ssoButtons[0].click();\n }\n }\n }\n };\n }\n\n disableKeyPressHandler() {\n this.logger.debug('Disable key press handler');\n this.rootElement.onkeydown = null;\n }\n\n async getComponentsVersion() {\n const config = await this.getConfig();\n const version =\n 'projectConfig' in config ? config.projectConfig?.componentsVersion : {};\n\n if (version) return version;\n\n this.logger.error('Did not get components version, using latest version');\n\n return 'latest';\n }\n\n static descopeUI: any;\n\n async init() {\n this.flowStatus = 'loading';\n ['ready', 'error', 'success'].forEach((status: FlowStatus) =>\n this.addEventListener(status, () => {\n this.flowStatus = status;\n }),\n );\n\n await super.init?.();\n this.#debugState.subscribe(this.#handleDebugMode.bind(this));\n this.#debugState.update({ isDebug: this.debug });\n\n this.#validateAttrs();\n\n if (await this.#getIsFlowsVersionMismatch()) {\n this.loggerWrapper.error(\n 'This SDK version does not support your flows version',\n 'Make sure to upgrade your flows to the latest version or use an older SDK version',\n );\n\n return;\n }\n\n const config = await this.getConfig();\n if ('isMissingConfig' in config && config.isMissingConfig) {\n this.loggerWrapper.error(\n 'Cannot get config file',\n 'Make sure that your projectId & flowId are correct',\n );\n\n return;\n }\n\n const {\n executionId,\n stepId,\n token,\n code,\n isPopup,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ssoQueryParams,\n } = handleUrlParams(this.flowId, this.loggerWrapper);\n\n // we want to update the state when user clicks on back in the browser\n window.addEventListener('popstate', this.#eventsCbRefs.popstate);\n\n // adding event to listen to events coming from components (e.g. recaptcha risk token) that want to add data to the context\n // this data will be sent to the server on the next request\n window.addEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n\n this.#flowState.subscribe(this.#onFlowChange.bind(this));\n\n this.#flowState.update({\n projectId: this.projectId,\n flowId: this.flowId,\n baseUrl: this.baseUrl,\n tenant: this.tenantId,\n redirectUrl: this.redirectUrl,\n locale: this.locale,\n stepId,\n executionId,\n token,\n code,\n isPopup,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ...ssoQueryParams,\n });\n\n this.#init = true;\n }\n\n disconnectedCallback() {\n this.#flowState.unsubscribeAll();\n this.#debugState.unsubscribeAll();\n this.#disableDebugger();\n window.removeEventListener('popstate', this.#eventsCbRefs.popstate);\n window.removeEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n // Forward to the composed mixin chain so each mixin's\n // disconnectedCallback (e.g. componentConditionsMixin) gets to clean up.\n // Without this, mixin disconnectedCallbacks are dead code.\n super.disconnectedCallback?.();\n }\n\n attributeChangedCallback(\n attrName: string,\n oldValue: string,\n newValue: string,\n ) {\n // Forward to the composed mixin chain first so other mixins always receive\n // the callback, regardless of the early return below.\n super.attributeChangedCallback?.(attrName, oldValue, newValue);\n\n if (!this.shadowRoot.isConnected || !this.#init) return;\n\n if (\n oldValue !== newValue &&\n BaseDescopeWc.observedAttributes.includes(attrName)\n ) {\n this.#validateAttrs();\n\n const isInitialRun = oldValue === null;\n\n this.#flowState.update(({ stepId, executionId }) => {\n let newStepId = stepId;\n let newExecutionId = executionId;\n\n // If not initial run and we got a new project/flow, we want to restart the step\n if (!isInitialRun) {\n newExecutionId = null;\n newStepId = null;\n clearRunIdsFromUrl();\n }\n\n return {\n [camelCase(attrName)]: newValue,\n stepId: newStepId,\n executionId: newExecutionId,\n };\n });\n\n this.#debugState.update({ isDebug: this.debug });\n }\n }\n}\n\nexport default BaseDescopeWc;\n"],"names":["BaseClass","compose","themeMixin","staticResourcesMixin","formMountMixin","componentConditionsMixin","duplicateFlowWarningMixin","passwordManagerMixin","injectStyleMixin","telemetryMixin","HTMLElement","BaseDescopeWc","observedAttributes","constructor","updateExecState","super","this","sdkVersion","_BaseDescopeWc_init","set","_BaseDescopeWc_customStorage","flowStatus","loggerWrapper","error","message","description","logger","Error","__classPrivateFieldGet","call","warn","info","state","debug","_BaseDescopeWc_flowState","State","_BaseDescopeWc_debugState","_BaseDescopeWc_componentsContext","getComponentsContext","nextRequestStatus","isLoading","_BaseDescopeWc_debuggerEle","_BaseDescopeWc_eventsCbRefs","popstate","_BaseDescopeWc_instances","_BaseDescopeWc_syncStateIdFromUrl","bind","componentsContext","_BaseDescopeWc_handleComponentsContext","_BaseDescopeWc_updateExecState","getConfig","config","isMissingConfig","__classPrivateFieldSet","_BaseDescopeWc_initShadowDom","client","JSON","parse","getAttribute","e","redirectUrl","undefined","locale","autoFocus","res","_b","validateOnBlur","storeLastAuthenticatedUser","refreshCookieName","keepLastAuthenticatedUserAfterLogout","storagePrefix","preview","formConfig","transformFlowInputFormData","form","formConfigValues","extractNestedAttribute","outboundAppId","outboundAppScopes","scopes","err","popupOrigin","customStorage","storage","getItem","setItem","removeItem","setCustomStorage","isRestartOnError","getExecutionContext","executionContext","getProjectConfig","projectConfig","getFlowConfig","flowConfig","flows","flowId","_c","version","getTargetLocales","targetLocales","map","toLowerCase","handleKeyPress","rootElement","onkeydown","isLinkEleFocused","shadowRoot","activeElement","isIgnoredElementFocused","ELEMENTS_TO_IGNORE_ENTER_KEY_ON","includes","localName","_d","key","preventDefault","buttons","querySelectorAll","length","click","autoSubmitButtons","Array","from","filter","button","genericButtons","ssoButtons","disableKeyPressHandler","getComponentsVersion","componentsVersion","init","forEach","status","addEventListener","_super","subscribe","_BaseDescopeWc_handleDebugMode","update","isDebug","_BaseDescopeWc_validateAttrs","_BaseDescopeWc_getIsFlowsVersionMismatch","executionId","stepId","token","code","isPopup","exchangeError","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthCodeChallenge","redirectAuthInitiator","ssoQueryParams","handleUrlParams","window","_BaseDescopeWc_onFlowChange","Object","assign","projectId","baseUrl","tenant","tenantId","disconnectedCallback","unsubscribeAll","_BaseDescopeWc_disableDebugger","removeEventListener","attributeChangedCallback","attrName","oldValue","newValue","isConnected","_a","isInitialRun","newStepId","newExecutionId","clearRunIdsFromUrl","camelCase","injectStyle","_BaseDescopeWc_loadInitStyle","slotElement","document","createElement","classList","add","appendChild","optionalAttributes","attr","getRunIdsFromUrl","_BaseDescopeWc_createSdk","createSdk","stringify","persistTokens","sdkConfigOverrides","sdk","origFn","flow","fnWithRetry","withRetry","args","__awaiter","errorCode","FETCH_EXCEPTION_ERROR_CODE","errorDescription","toString","currentState","_prevState","isChanged","_BaseDescopeWc_isPrevVerConfig","prevVerConfigUrl","getContentUrl","filename","CONFIG_FILENAME","assetsFolder","PREV_VER_ASSETS_FOLDER","baseStaticUrl","fetchContent","detail","remove","arguments","style","position","top","right","height","width","pointerEvents","zIndex","import","body","_BaseDescopeWc_updateDebuggerMessages","title","updateData","baseHeaders"],"mappings":"27CAuDA,MAAMA,EAAYC,EAChBC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EARgBR,CAShBS,aAGF,MAAMC,UAAsBX,EAC1B,6BAAWY,GACT,MAAO,CACL,aACA,UACA,WACA,SACA,SACA,QACA,iBACA,UACA,eACA,aACA,gCACA,sBACA,4CACA,mBACA,WAEH,CAiED,WAAAC,CAAYC,GACVC,oBAhEFC,KAAUC,WAAG,QAUbC,EAAAC,IAAAH,MAAQ,GAERI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est as s}from"tslib";import{getUserLocale as o}from"@descope/sdk-helpers";import{ensureFingerprintIds as r,clearFingerprintData as n}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as l,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as d,URL_ERR_PARAM_NAME as c,URL_TOKEN_PARAM_NAME as p,URL_RUN_IDS_PARAM_NAME as h,SDK_SCRIPTS_LOAD_TIMEOUT as u,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as g,ELEMENT_TYPE_ATTRIBUTE as v,DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED as m,DESCOPE_LAST_AUTH_BADGE_COMPONENT as f,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as b}from"../constants/index.js";import{timeoutPromise as w,withMemCache as S,leadingDebounce as y,showFirstScreenOnExecutionInit as I,injectSamlIdpForm as R,injectWsFedIdpForm as C,openCenteredPopup as W,getAnimationDirection as k,handleAutoFocus as O,transformStepStateForCustomScreen as x,getElementDescopeAttributes as E,getScriptResultPath as A,submitForm as j,transformScreenInputs as T,handleReportValidityOnBlur as L,clearPreviousExternalInputs as U}from"../helpers/helpers.js";import P from"../helpers/state.js";import{disableWebauthnButtons as F,updateTemplateFromScreenState as $,setComponentsAutoDetectByGeo as N,setComponentsAutoDetectByLocale as M,setTOTPVariable as q,setNOTPVariable as V,setCssVars as D,updateScreenFromScreenState as B,replaceElementMessage as K}from"../helpers/templates.js";import{isConditionalLoginSupported as H}from"../helpers/webauthn.js";import{getABTestingKey as _}from"../helpers/abTestingKey.js";import{calculateConditions as G,calculateCondition as J}from"../helpers/conditions.js";import{setLastAuth as z,getInFlightLastUsedPerScreen as Q,clearInFlightLastAuth as X,getLastAuth as Y,updateLastUsedPerScreen as Z}from"../helpers/lastAuth.js";import ee from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as te,FETCH_ERROR_RESPONSE_ERROR_CODE as ie,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as se,FLOW_TIMED_OUT_ERROR_CODE as oe,NONCE_VALIDATION_ERROR_CODE as re,POLLING_STATUS_NOT_FOUND_ERROR_CODE as ne}from"../constants/general.js";var le,ae,de,ce,pe,he,ue,ge,ve,me,fe,be,we,Se,ye,Ie,Re,Ce,We,ke,Oe,xe,Ee,Ae,je,Te,Le,Ue,Pe,Fe,$e,Ne,Me,qe,Ve,De,Be,Ke,He;class _e extends ee{static set sdkConfigOverrides(e){ee.sdkConfigOverrides=e}static get sdkConfigOverrides(){return ee.sdkConfigOverrides}constructor(){const s=new P({deferredRedirect:!1,deferredPolling:!1});super(s.update.bind(s)),le.add(this),this.stepState=new P({}),ae.set(this,void 0),de.set(this,null),ce.set(this,null),pe.set(this,{visibilitychange:e(this,le,"m",he).bind(this)}),this.bridgeVersion=2,this.nativeCallbacks={},Se.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},Ie.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,le,"m",Re).call(this,i):i()})),Ce.set(this,((s,o,r,n,d=!1)=>{const c=[oe,ne,re];if(this.flowState.current.action===l.poll){if(e(this,ke,"f").call(this)&&document.hidden)return this.logger.debug("polling - Deferring polling until in foreground"),void this.flowState.update({deferredPolling:!0});this.logger.debug("polling - Scheduling polling request");const l=Date.now(),p=d?500:2e3;t(this,ae,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const h=this.sdk.flow.next(s,o,a.polling,r,n,{}),u=document.hidden&&!d&&Date.now()-l>p+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield w(e,h)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,Ce,"f").call(this,s,o,r,n,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===te)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,Ce,"f").call(this,s,o,r,n);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,Ce,"f").call(this,s,o,r,n),e(this,Oe,"f").call(this,g)}))),p),"f")}})),We.set(this,(()=>{clearTimeout(e(this,ae,"f")),t(this,ae,null,"f")})),ke.set(this,(()=>!!window.descopeBridge||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))),Oe.set(this,(i=>{var s,o,r,n,a,d,c,p,h,u,g,v,m;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,l=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(r=null==i?void 0:i.response)||void 0===r?void 0:r.statusText}`;e(this,le,"m",Ke).call(this,"error",(null==i?void 0:i.error)||{errorCode:ie,errorDescription:l,errorMessage:t}),this.loggerWrapper.error((null===(n=null==i?void 0:i.error)||void 0===n?void 0:n.errorDescription)||t,(null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorMessage)||l);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==se&&c!==oe&&c!==re||!this.isRestartOnError||e(this,le,"m",we).call(this))}null===(p=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===p||p.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(h=i.data)||void 0===h?void 0:h.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(v=i.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:I}=i.data;if(y!==l.poll&&e(this,We,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&z(Object.assign(Object.assign({},S),{lastUsedPerScreen:Q()})),X(this.loggerWrapper);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),void e(this,le,"m",Ke).call(this,"success",t)}this.storeLastAuthenticatedUser&&z(S,!0),I&&window.open(I,"_blank");const{executionId:R,stepId:C,stepName:W,screen:k,redirect:O,webauthn:x,error:E,samlIdpResponse:A,wsFedIdpResponse:j,nativeResponse:T}=i.data,L=Date.now();y!==l.poll?(this.loggerWrapper.info(`Step "${W||`#${C}`}" is ${b}`,"",{screen:k,status:b,stepId:C,stepName:W,action:y,error:E}),(null===(m=k.state)||void 0===m?void 0:m.clientScripts)&&t(this,ce,this.loadSdkScripts(k.state.clientScripts),"f"),this.flowState.update({stepId:C,stepName:W,executionId:R,action:y,redirectTo:null==O?void 0:O.url,redirectIsPopup:null==O?void 0:O.isPopup,screenId:null==k?void 0:k.id,screenState:null==k?void 0:k.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,wsFedIdpResponseUrl:null==j?void 0:j.url,wsFedIdpResponseWresult:null==j?void 0:j.wresult,wsFedIdpResponseWctx:null==j?void 0:j.wctx,nativeResponseType:null==T?void 0:T.type,nativePayload:null==T?void 0:T.payload,reqTimestamp:L})):this.flowState.update({action:y,reqTimestamp:L})})),xe.set(this,S((()=>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)}}))))),Ue.set(this,null),Ne.set(this,y(((t,s,o)=>i(this,void 0,void 0,(function*(){var i,r;if("true"===t.getAttribute("formnovalidate")||e(this,le,"m",Te).call(this)){const n=null==t?void 0:t.getAttribute("id");e(this,le,"m",Ve).call(this,t,n,o),e(this,le,"m",Pe).call(this,t);const l=yield e(this,le,"m",Le).call(this),a=E(t);this.nextRequestStatus.update({isLoading:!0});const d=Object.assign(Object.assign(Object.assign({},a),l),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin}),c=yield s(n,d);this.nextRequestStatus.update({isLoading:!1}),this.captureLastSubmittedLoginId(l,null===(r=null==c?void 0:c.data)||void 0===r?void 0:r.executionId),this.storeCredentials(l)}}))))),this.flowState=s}nativeResume(t,i){var s,o,r,n,l,a;const u=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let e,{exchangeCode:t}=u;if(!t){const i=new URL(u.url);t=null===(s=i.searchParams)||void 0===s?void 0:s.get(d),e=(null===(o=i.searchParams)||void 0===o?void 0:o.get(c))||void 0}null===(n=(r=this.nativeCallbacks).complete)||void 0===n||n.call(r,{exchangeCode:t,exchangeError:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(u.url),i=t.searchParams.get(p),s=t.searchParams.get(h).split("_").pop();e(this,We,"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}=u;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=u,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(l=this.nativeCallbacks).complete)||void 0===a||a.call(l,u)}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:{[A(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,o;const r=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(r){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=r;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}(null===(s=globalThis.descope)||void 0===s?void 0:s[e.id])||(yield this.injectNpmLib("@descope/flow-scripts","1.0.17",`dist/${e.id}.js`));const n=null===(o=globalThis.descope)||void 0===o?void 0:o[e.id];return new Promise(((i,s)=>{try{const s=n(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i),this.loggerWrapper);if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t);const i=this.nextRequestStatus.subscribe((()=>{var o;this.loggerWrapper.debug("Stopping script",e.id),(null===(o=s.stop)||void 0===o?void 0:o.call(s))&&(this.nextRequestStatus.unsubscribe(i),this.loggerWrapper.debug("Removing script",e.id),this.shadowRoot.removeChild(t))}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),u)}));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,le,"m",fe).call(this),window.addEventListener("visibilitychange",e(this,pe,"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,We,"f").call(this),null===(i=e(this,de,"f"))||void 0===i||i.abort(),t(this,de,null,"f"),window.removeEventListener("visibilitychange",e(this,pe,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=o(e),r=yield this.getTargetLocales();return r.includes(s.locale)?i=`${t}-${s.locale}.html`:r.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return 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(d,c,p){return i(this,void 0,void 0,(function*(){var h,u;const{projectId:g,flowId:v,tenant:m,stepId:f,executionId:b,action:w,screenId:S,screenState:y,redirectTo:O,redirectIsPopup:x,redirectUrl:E,token:A,code:L,isPopup:U,exchangeError:P,webauthnTransactionId:F,webauthnOptions:$,redirectAuthCodeChallenge:N,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:V,locale:D,samlIdpResponseUrl:B,samlIdpResponseSamlResponse:K,samlIdpResponseRelayState:H,wsFedIdpResponseUrl:z,wsFedIdpResponseWresult:Q,wsFedIdpResponseWctx:Z,nativeResponseType:ee,nativePayload:te,reqTimestamp:ie}=d,se=s(d,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx","nativeResponseType","nativePayload","reqTimestamp"]);let oe,re,ne;const ae=_(),{outboundAppId:pe}=this,{outboundAppScopes:he}=this,ue=this.sdk.getLastUserLoginId(),ge=yield this.getFlowConfig(),me=yield this.getProjectConfig(),fe=Object.entries(me.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),be=M&&N?{callbackUrl:M,codeChallenge:N,backupCallbackUri:q}:void 0,we=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect,externalAuthRedirect:this.nativeOptions.externalAuthRedirect}:void 0;let Se={};if(!b){X(this.loggerWrapper);const i=[...ge.clientScripts||[],...ge.sdkScripts||[]];if(ge.conditions){let e=[];({startScreenId:oe,conditionInteractionId:ne,startScreenName:re,clientScripts:e,componentsConfig:Se}=G({loginId:ue,code:L,token:A,abTestingKey:ae,lastAuth:Y(ue,this.loggerWrapper)},ge.conditions)),i.push(...e||[])}else ge.condition?({startScreenId:oe,conditionInteractionId:ne}=J(ge.condition,{loginId:ue,code:L,token:A,abTestingKey:ae,lastAuth:Y(ue,this.loggerWrapper)})):(re=ge.startScreenName,oe=ge.startScreenId);if(t(this,ce,this.loadSdkScripts(i),"f"),ge.fingerprintEnabled&&ge.fingerprintKey?yield r(ge.fingerprintKey,this.baseUrl):n(),!I(oe,se)){const t=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:be},se),{client:this.client}),E&&{redirectUrl:E}),{lastAuth:Y(ue,this.loggerWrapper),abTestingKey:ae,locale:o(D).locale,nativeOptions:we,outboundAppId:pe,outboundAppScopes:he}),ne,"",me.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),L?{exchangeCode:L,idpInitiated:!0}:{}),se.descopeIdpInitiated&&{idpInitiated:!0}),A?{token:A}:{}),se.oidcLoginHint?{externalId:se.oidcLoginHint}:{}));return e(this,Oe,"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:U,code:L,exchangeError:P,isCodeChanged:p("code"),isExchangeErrorChanged:p("exchangeError")})),U&&(p("code")&&L||p("exchangeError")&&P))return void e(this,le,"m",He).call(this,b,L,P);if(b&&(p("token")&&A||p("code")&&L||p("exchangeError")&&P)){const t=yield this.sdk.flow.next(b,f,a.submit,ge.version,me.componentsVersion,{token:A,exchangeCode:L,exchangeError:P});return e(this,Oe,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(w===l.loadForm&&B&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>p(e)))){if(!K)return void this.loggerWrapper.error("Did not get saml idp params data to load");R(B,K,H||"",j)}if(w===l.loadForm&&z&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>p(e)))){if(!Q)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");C(z,Q,Z||"",j)}if(w===l.redirect&&(p("redirectTo")||p("deferredRedirect"))){if(!O)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===O)return;if("android"===V&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${x}`),x){this.loggerWrapper.debug("Opening redirect in popup");const t=W(O,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));let s=!1;const o=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:o,data:r}=e.data||{};"code"===o&&(s=!0,this.flowState.update({code:r.code,exchangeError:r.exchangeError}))};let r;this.loggerWrapper.debug("Starting popup closed detection");const n=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(n),e(this,le,"m",Ke).call(this,"popupclosed",{abandoned:!s}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==r||r())}),1e3);if(i)window.addEventListener("message",o),r=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",o)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(b);e.onmessage=o,r=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(O),this.flowState.update({redirectTo:"no-op"}),e(this,le,"m",Ke).call(this,"popupclosed",{});return}if(w===l.webauthnCreate||w===l.webauthnGet){if(!F||!$)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s,o,r;null===(u=e(this,de,"f"))||void 0===u||u.abort(),t(this,de,null,"f");try{i=w===l.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,o=e.reason,r=e.message}const n=yield this.sdk.flow.next(b,f,a.submit,ge.version,me.componentsVersion,{transactionId:F,response:i,failure:s,failureReason:o,failureMessage:r});e(this,Oe,"f").call(this,n)}if(w===l.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(b,f,a.submit,ge.version,me.componentsVersion,t);e(this,Oe,"f").call(this,i)})),e(this,le,"m",ve).call(this,ee,te),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if((p("action")||p("deferredPolling"))&&e(this,Ce,"f").call(this,b,f,ge.version,me.componentsVersion),!S&&!oe)return void this.loggerWrapper.warn("No screen was found to show");const Ie=oe||S,Re=yield this.getHtmlFilenameWithLocale(D,Ie),{oidcLoginHint:We,oidcPrompt:ke,oidcErrorRedirectUri:xe,oidcResource:Ee,samlIdpUsername:Ae}=se,je={direction:k(f,c.stepId),screenState:Object.assign(Object.assign({},y),{form:Object.assign(Object.assign({},this.formConfigValues),null==y?void 0:y.form),lastAuth:{loginId:ue,name:this.sdk.getLastUserDisplayName()||ue},componentsConfig:Object.assign(Object.assign(Object.assign({},ge.componentsConfig),Se),null==y?void 0:y.componentsConfig)}),htmlFilename:`${Ie}.html`,htmlLocaleFilename:Re,screenId:Ie,stepName:d.stepName||re,samlIdpUsername:Ae,oidcLoginHint:We,oidcPrompt:ke,oidcErrorRedirectUri:xe,oidcResource:Ee,action:w,locale:o(D).locale},Te=Y(ue,this.loggerWrapper);I(oe,se)?je.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ge?void 0:ge.clientScripts)||[];yield e(this,le,"m",Me).call(this,i);const r=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:be},se),{lastAuth:Te,preview:this.preview,abTestingKey:ae,client:this.client}),E&&{redirectUrl:E}),{locale:o(D).locale,nativeOptions:we,outboundAppId:pe,outboundAppScopes:he}),ne,t,me.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),T(s)),L&&{exchangeCode:L,idpInitiated:!0}),se.descopeIdpInitiated&&{idpInitiated:!0}),A&&{token:A}),je.next.isCustomScreen);return e(this,Oe,"f").call(this,r),r})):(p("projectId")||p("baseUrl")||p("executionId")||p("stepId"))&&(je.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==y?void 0:y.clientScripts)||[];yield e(this,le,"m",Me).call(this,i);const o=yield this.sdk.flow.next(b,f,t,ge.version,me.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),T(s)),je.next.isCustomScreen);return e(this,Oe,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",je.screenId),yield e(this,le,"m",ye).call(this,je),this.stepState.update(je)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,r,n;const{htmlFilename:l,htmlLocaleFilename:d,direction:c,next:p,screenState:h,screenId:u}=t;this.loggerWrapper.debug("Rendering a flow screen"),this.updateScreenUser(null==h?void 0:h.user);const g=document.createElement("template");g.innerHTML=yield this.getPageContent(l,d);const m=g.content.cloneNode(!0),f=this.loadDescopeUiComponents(g);this.sdk.webauthn.helpers.isSupported()?yield e(this,le,"m",Ae).call(this,m,p):F(m),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(r=h.form)||void 0===r?void 0:r.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),$(m,h,this.formConfig,this.loggerWrapper),this.applyComponentsState(m,null==h?void 0:h.componentsState);const{geo:b}=null!==(n=yield this.getExecutionContext())&&void 0!==n?n:{};N(m,b),M(m,t.locale);const w=()=>i(this,void 0,void 0,(function*(){var i,o;yield f;const r=this.contentRootElement;q(r,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),V(r,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),D(r,m,h.cssVars,this.loggerWrapper),r.replaceChildren(m);const n=!s.htmlFilename;setTimeout((()=>{e(this,le,"m",Fe).call(this),this.updateUsernameAnchor(),this.validateOnBlur&&L(r),B(r,h),this.initRealtimeConditions(r,h),e(this,le,"m",je).call(this,{isFirstScreen:n,isCustomScreen:!1,stepName:t.stepName}),O(r,this.autoFocus,n),e(this,le,"m",De).call(this,u)})),e(this,le,"m",Be).call(this,p,u);r.querySelector(`[${v}="polling"]`)&&p(a.polling,{})}));c?e(this,le,"m",Re).call(this,w):w()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${g}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}ae=new WeakMap,de=new WeakMap,ce=new WeakMap,pe=new WeakMap,Se=new WeakMap,Ie=new WeakMap,Ce=new WeakMap,We=new WeakMap,ke=new WeakMap,Oe=new WeakMap,xe=new WeakMap,Ue=new WeakMap,Ne=new WeakMap,le=new WeakSet,he=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1,deferredPolling:!1})}),300)},ue=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,le,"m",ve).call(this,"beforeScreen",{screen:t,context:s})}))}))},ge=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,le,"m",ve).call(this,"afterScreen",{screen:t})},ve=function(t,i){e(this,le,"m",Ke).call(this,"bridge",{type:t,payload:i})},me=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)}K(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},fe=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,le,"m",me).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,le,"m",be).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})},be=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=""}))})),O(this.contentRootElement,this.autoFocus,!1))},we=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")}))},ye=function(o){return i(this,void 0,void 0,(function*(){var i;const r=Object.assign(Object.assign({},this.stepState.current),o),{next:n,stepName:l}=r,a=s(r,["next","stepName"]),d=x(a);let c=yield e(this,le,"m",ue).call(this,l,d,n);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,l,d,n,this)));const p=!this.stepState.current.htmlFilename;if(e(this,Ie,"f").call(this,c),n&&(n.isCustomScreen=c),e(this,Se,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,Se,c,"f"),c?this.stepState.unsubscribeAll():e(this,le,"m",fe).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,le,"m",je).call(this,{isFirstScreen:p,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},Re=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")},Ee=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)}))}},Ae=function(s,o){return i(this,void 0,void 0,(function*(){var r;null===(r=e(this,de,"f"))||void 0===r||r.abort();const n=s.querySelector('*[autocomplete="webauthn"]');if(n&&(yield H())){const{options:s,transactionId:r}=(yield e(this,xe,"f").call(this))||{};s&&r&&(e(this,le,"m",Ee).call(this,n),t(this,de,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,de,"f")).then((e=>i(this,void 0,void 0,(function*(){o(n.id,{transactionId:r,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},je=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,le,"m",Ke).call(this,"ready",{}),i||e(this,le,"m",ge).call(this,s),e(this,le,"m",Ke).call(this,"page-updated",{screenName:s}),e(this,le,"m",Ke).call(this,"screen-updated",{screenName:s})},Te=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"===t.localName||t.classList.contains("hidden")||(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},Le=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})),{})}))},Pe=function(s){var o,r;const n=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),l=(null===(r=null===(o=this.flowState.current)||void 0===o?void 0:o.screenState)||void 0===r?void 0:r.clientScripts)||[],a=()=>{s.removeAttribute("loading"),n.forEach((e=>{e.removeAttribute("disabled")}))},d=e=>i(this,void 0,void 0,(function*(){var s;this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",d);if(!0===(null===(s=null==e?void 0:e.detail)||void 0===s?void 0:s.abandoned)&&l.length)return t(this,ce,(()=>i(this,void 0,void 0,(function*(){try{yield this.loadSdkScripts(l)}catch(e){this.loggerWrapper.warn("Failed to refresh client scripts on popup close",null==e?void 0:e.message)}})))(),"f"),void a();a();const o=yield this.getFlowConfig(),r=[...o.clientScripts||[],...o.sdkScripts||[]];this.loadSdkScripts(r)})),c=()=>{var i;window.removeEventListener("pageshow",e(this,Ue,"f")),t(this,Ue,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),d())}),"f"),window.addEventListener("pageshow",e(this,Ue,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&d(),this.removeEventListener("popupclosed",d),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},p=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?(this.addEventListener("popupclosed",d,{once:!0}),s.setAttribute("loading","true"),n.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(p),"success"===this.flowStatus?(this.removeEventListener("popupclosed",d),a()):c())}))},Fe=function(){U();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,le,"m",$e).call(this,t)))},$e=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)}))},Me=function(t){return i(this,void 0,void 0,(function*(){if(e(this,ce,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ce,"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)}const o=[];for(const e of i)"function"==typeof e.refresh&&o.push(e.refresh());if(o.length>0)try{yield w(u,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},qe=function(t,i){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((s=>{s.addEventListener("input",(()=>{var o;(null===(o=s.checkValidity)||void 0===o?void 0:o.call(s))&&e(this,Ne,"f").call(this,s,t,i)}))}))},Ve=function(e,t,i){t&&i&&"true"===e.getAttribute(m)&&Z(i,t,this.loggerWrapper)},De=function(e){var t;const i=this.sdk.getLastUserLoginId(),s=null===(t=Y(i,this.loggerWrapper).lastUsedPerScreen)||void 0===t?void 0:t[e];if(!s)return;const o=this.contentRootElement.querySelector(f),r=this.contentRootElement.querySelector(`#${CSS.escape(s)}`);o&&r&&(r.replaceWith(o),o.appendChild(r))},Be=function(t,i){this.contentRootElement.querySelectorAll(`descope-button:not([${b}]), [data-type="button"]:not([${b}]`).forEach((s=>{s.onclick=()=>{e(this,Ne,"f").call(this,s,t,i)}})),e(this,le,"m",qe).call(this,t,i),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${g}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},Ke=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},He=function(e,t,i){var s;const[o,r]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],n={data:{code:t,exchangeError:i},action:"code"};if("descope-wc"===o&&r){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",r);try{window.opener.postMessage(n,r)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(n),t.close()}try{window.close()}catch(e){}};export{_e as default};
|
|
1
|
+
import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{getUserLocale as o}from"@descope/sdk-helpers";import{ensureFingerprintIds as r,clearFingerprintData as n}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as l,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as d,URL_ERR_PARAM_NAME as c,URL_TOKEN_PARAM_NAME as p,URL_RUN_IDS_PARAM_NAME as h,SDK_SCRIPTS_LOAD_TIMEOUT as u,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as g,ELEMENT_TYPE_ATTRIBUTE as v,DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED as m,DESCOPE_LAST_AUTH_BADGE_COMPONENT as f,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as b}from"../constants/index.js";import{timeoutPromise as w,withMemCache as S,leadingDebounce as y,showFirstScreenOnExecutionInit as I,injectSamlIdpForm as R,injectWsFedIdpForm as C,openCenteredPopup as W,getAnimationDirection as k,handleAutoFocus as x,transformStepStateForCustomScreen as O,getElementDescopeAttributes as E,getScriptResultPath as A,submitForm as j,transformScreenInputs as T,handleReportValidityOnBlur as L,clearPreviousExternalInputs as U}from"../helpers/helpers.js";import P from"../helpers/state.js";import{disableWebauthnButtons as F,updateTemplateFromScreenState as $,setComponentsAutoDetectByGeo as M,setComponentsAutoDetectByLocale as N,setTOTPVariable as q,setNOTPVariable as V,setCssVars as D,updateScreenFromScreenState as B,replaceElementMessage as K}from"../helpers/templates.js";import{isConditionalLoginSupported as H}from"../helpers/webauthn.js";import{getABTestingKey as _}from"../helpers/abTestingKey.js";import{calculateConditions as G,calculateCondition as J}from"../helpers/conditions.js";import{setLastAuth as z,getInFlightLastUsedPerScreen as Q,clearInFlightLastAuth as X,getLastAuth as Y,updateLastUsedPerScreen as Z}from"../helpers/lastAuth.js";import ee from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as te,FETCH_ERROR_RESPONSE_ERROR_CODE as ie,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as se,FLOW_TIMED_OUT_ERROR_CODE as oe,NONCE_VALIDATION_ERROR_CODE as re,POLLING_STATUS_NOT_FOUND_ERROR_CODE as ne}from"../constants/general.js";var le,ae,de,ce,pe,he,ue,ge,ve,me,fe,be,we,Se,ye,Ie,Re,Ce,We,ke,xe,Oe,Ee,Ae,je,Te,Le,Ue,Pe,Fe,$e,Me,Ne,qe,Ve,De,Be,Ke,He,_e;class Ge extends ee{static set sdkConfigOverrides(e){ee.sdkConfigOverrides=e}static get sdkConfigOverrides(){return ee.sdkConfigOverrides}constructor(){const s=new P({deferredRedirect:!1,deferredPolling:!1});super(s.update.bind(s)),le.add(this),this.stepState=new P({}),ae.set(this,void 0),de.set(this,null),ce.set(this,null),pe.set(this,{visibilitychange:e(this,le,"m",he).bind(this)}),this.bridgeVersion=Ge.bridgeVersion,ue.set(this,void 0),this.nativeCallbacks={},ye.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},Re.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,le,"m",Ce).call(this,i):i()})),We.set(this,((s,o,r,n,d=!1)=>{const c=[oe,ne,re];if(this.flowState.current.action===l.poll){if(e(this,xe,"f").call(this)&&document.hidden)return this.logger.debug("polling - Deferring polling until in foreground"),void this.flowState.update({deferredPolling:!0});this.logger.debug("polling - Scheduling polling request");const l=Date.now(),p=d?500:2e3;t(this,ae,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const h=this.sdk.flow.next(s,o,a.polling,r,n,{}),u=document.hidden&&!d&&Date.now()-l>p+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield w(e,h)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,We,"f").call(this,s,o,r,n,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===te)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,We,"f").call(this,s,o,r,n);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,We,"f").call(this,s,o,r,n),e(this,Oe,"f").call(this,g)}))),p),"f")}})),ke.set(this,(()=>{clearTimeout(e(this,ae,"f")),t(this,ae,null,"f")})),xe.set(this,(()=>!!window.descopeBridge||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))),Oe.set(this,(i=>{var s,o,r,n,a,d,c,p,h,u,g,v,m;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,l=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(r=null==i?void 0:i.response)||void 0===r?void 0:r.statusText}`;e(this,le,"m",He).call(this,"error",(null==i?void 0:i.error)||{errorCode:ie,errorDescription:l,errorMessage:t}),this.loggerWrapper.error((null===(n=null==i?void 0:i.error)||void 0===n?void 0:n.errorDescription)||t,(null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorMessage)||l);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==se&&c!==oe&&c!==re||!this.isRestartOnError||e(this,le,"m",Se).call(this))}null===(p=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===p||p.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(h=i.data)||void 0===h?void 0:h.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(v=i.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:I}=i.data;if(y!==l.poll&&e(this,ke,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&z(Object.assign(Object.assign({},S),{lastUsedPerScreen:Q()})),X(this.loggerWrapper);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),void e(this,le,"m",He).call(this,"success",t)}this.storeLastAuthenticatedUser&&z(S,!0),I&&window.open(I,"_blank");const{executionId:R,stepId:C,stepName:W,screen:k,redirect:x,webauthn:O,error:E,samlIdpResponse:A,wsFedIdpResponse:j,nativeResponse:T}=i.data,L=Date.now();y!==l.poll?(this.loggerWrapper.info(`Step "${W||`#${C}`}" is ${b}`,"",{screen:k,status:b,stepId:C,stepName:W,action:y,error:E}),(null===(m=k.state)||void 0===m?void 0:m.clientScripts)&&t(this,ce,this.loadSdkScripts(k.state.clientScripts),"f"),this.flowState.update({stepId:C,stepName:W,executionId:R,action:y,redirectTo:null==x?void 0:x.url,redirectIsPopup:null==x?void 0:x.isPopup,screenId:null==k?void 0:k.id,screenState:null==k?void 0:k.state,webauthnTransactionId:null==O?void 0:O.transactionId,webauthnOptions:null==O?void 0:O.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,wsFedIdpResponseUrl:null==j?void 0:j.url,wsFedIdpResponseWresult:null==j?void 0:j.wresult,wsFedIdpResponseWctx:null==j?void 0:j.wctx,nativeResponseType:null==T?void 0:T.type,nativePayload:null==T?void 0:T.payload,reqTimestamp:L})):this.flowState.update({action:y,reqTimestamp:L})})),Ee.set(this,S((()=>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)}}))))),Pe.set(this,null),Ne.set(this,y(((t,s,o)=>i(this,void 0,void 0,(function*(){var i,r;if("true"===t.getAttribute("formnovalidate")||e(this,le,"m",Le).call(this)){const n=null==t?void 0:t.getAttribute("id");e(this,le,"m",De).call(this,t,n,o),e(this,le,"m",Fe).call(this,t);const l=yield e(this,le,"m",Ue).call(this),a=E(t);this.nextRequestStatus.update({isLoading:!0});const d=Object.assign(Object.assign(Object.assign({},a),l),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin}),c=yield s(n,d);this.nextRequestStatus.update({isLoading:!1}),this.captureLastSubmittedLoginId(l,null===(r=null==c?void 0:c.data)||void 0===r?void 0:r.executionId),this.storeCredentials(l)}}))))),this.flowState=s}nativeResume(t,i){var s,o,r,n,l,a;const u=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let e,{exchangeCode:t}=u;if(!t){const i=new URL(u.url);t=null===(s=i.searchParams)||void 0===s?void 0:s.get(d),e=(null===(o=i.searchParams)||void 0===o?void 0:o.get(c))||void 0}null===(n=(r=this.nativeCallbacks).complete)||void 0===n||n.call(r,{exchangeCode:t,exchangeError:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(u.url),i=t.searchParams.get(p),s=t.searchParams.get(h).split("_").pop();e(this,ke,"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}=u;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=u,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(l=this.nativeCallbacks).complete)||void 0===a||a.call(l,u)}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:{[A(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,o;const r=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(r){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=r;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}(null===(s=globalThis.descope)||void 0===s?void 0:s[e.id])||(yield this.injectNpmLib("@descope/flow-scripts","1.0.17",`dist/${e.id}.js`));const n=null===(o=globalThis.descope)||void 0===o?void 0:o[e.id];return new Promise(((i,s)=>{try{const s=n(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i),this.loggerWrapper);if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t);const i=this.nextRequestStatus.subscribe((()=>{var o;this.loggerWrapper.debug("Stopping script",e.id),(null===(o=s.stop)||void 0===o?void 0:o.call(s))&&(this.nextRequestStatus.unsubscribe(i),this.loggerWrapper.debug("Removing script",e.id),this.shadowRoot.removeChild(t))}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),u)}));return Promise.race([s,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){var e,i;if(!window.descopeBridge)return this._init();this.lazyInit=this._init,t(this,ue,null===(i=null===(e=null===window||void 0===window?void 0:window.descopeBridge)||void 0===e?void 0:e.registerFlow)||void 0===i?void 0:i.call(e,this),"f")}_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,le,"m",be).call(this),window.addEventListener("visibilitychange",e(this,pe,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var i,s,o;super.disconnectedCallback(),e(this,ue,"f")&&(null===(s=null===(i=window.descopeBridge)||void 0===i?void 0:i.unregisterFlow)||void 0===s||s.call(i,e(this,ue,"f")),t(this,ue,void 0,"f")),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,ke,"f").call(this),null===(o=e(this,de,"f"))||void 0===o||o.abort(),t(this,de,null,"f"),window.removeEventListener("visibilitychange",e(this,pe,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=o(e),r=yield this.getTargetLocales();return r.includes(s.locale)?i=`${t}-${s.locale}.html`:r.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return 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(d,c,p){return i(this,void 0,void 0,(function*(){var h,u;const{projectId:g,flowId:v,tenant:m,stepId:f,executionId:b,action:w,screenId:S,screenState:y,redirectTo:x,redirectIsPopup:O,redirectUrl:E,token:A,code:L,isPopup:U,exchangeError:P,webauthnTransactionId:F,webauthnOptions:$,redirectAuthCodeChallenge:M,redirectAuthCallbackUrl:N,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:V,locale:D,samlIdpResponseUrl:B,samlIdpResponseSamlResponse:K,samlIdpResponseRelayState:H,wsFedIdpResponseUrl:z,wsFedIdpResponseWresult:Q,wsFedIdpResponseWctx:Z,nativeResponseType:ee,nativePayload:te,reqTimestamp:ie}=d,se=s(d,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx","nativeResponseType","nativePayload","reqTimestamp"]);let oe,re,ne;const ae=_(),{outboundAppId:pe}=this,{outboundAppScopes:he}=this,ue=this.sdk.getLastUserLoginId(),ge=yield this.getFlowConfig(),ve=yield this.getProjectConfig(),fe=Object.entries(ve.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),be=N&&M?{callbackUrl:N,codeChallenge:M,backupCallbackUri:q}:void 0,we=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect,externalAuthRedirect:this.nativeOptions.externalAuthRedirect}:void 0;let Se={};if(!b){X(this.loggerWrapper);const i=[...ge.clientScripts||[],...ge.sdkScripts||[]];if(ge.conditions){let e=[];({startScreenId:oe,conditionInteractionId:ne,startScreenName:re,clientScripts:e,componentsConfig:Se}=G({loginId:ue,code:L,token:A,abTestingKey:ae,lastAuth:Y(ue,this.loggerWrapper)},ge.conditions)),i.push(...e||[])}else ge.condition?({startScreenId:oe,conditionInteractionId:ne}=J(ge.condition,{loginId:ue,code:L,token:A,abTestingKey:ae,lastAuth:Y(ue,this.loggerWrapper)})):(re=ge.startScreenName,oe=ge.startScreenId);if(t(this,ce,this.loadSdkScripts(i),"f"),ge.fingerprintEnabled&&ge.fingerprintKey?yield r(ge.fingerprintKey,this.baseUrl):n(),!I(oe,se)){const t=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:be},se),{client:this.client}),E&&{redirectUrl:E}),{lastAuth:Y(ue,this.loggerWrapper),abTestingKey:ae,locale:o(D).locale,nativeOptions:we,outboundAppId:pe,outboundAppScopes:he}),ne,"",ve.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),L?{exchangeCode:L,idpInitiated:!0}:{}),se.descopeIdpInitiated&&{idpInitiated:!0}),A?{token:A}:{}),se.oidcLoginHint?{externalId:se.oidcLoginHint}:{}));return e(this,Oe,"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:U,code:L,exchangeError:P,isCodeChanged:p("code"),isExchangeErrorChanged:p("exchangeError")})),U&&(p("code")&&L||p("exchangeError")&&P))return void e(this,le,"m",_e).call(this,b,L,P);if(b&&(p("token")&&A||p("code")&&L||p("exchangeError")&&P)){const t=yield this.sdk.flow.next(b,f,a.submit,ge.version,ve.componentsVersion,{token:A,exchangeCode:L,exchangeError:P});return e(this,Oe,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(w===l.loadForm&&B&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>p(e)))){if(!K)return void this.loggerWrapper.error("Did not get saml idp params data to load");R(B,K,H||"",j)}if(w===l.loadForm&&z&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>p(e)))){if(!Q)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");C(z,Q,Z||"",j)}if(w===l.redirect&&(p("redirectTo")||p("deferredRedirect"))){if(!x)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===x)return;if("android"===V&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${O}`),O){this.loggerWrapper.debug("Opening redirect in popup");const t=W(x,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));let s=!1;const o=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:o,data:r}=e.data||{};"code"===o&&(s=!0,this.flowState.update({code:r.code,exchangeError:r.exchangeError}))};let r;this.loggerWrapper.debug("Starting popup closed detection");const n=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(n),e(this,le,"m",He).call(this,"popupclosed",{abandoned:!s}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==r||r())}),1e3);if(i)window.addEventListener("message",o),r=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",o)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(b);e.onmessage=o,r=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(x),this.flowState.update({redirectTo:"no-op"}),e(this,le,"m",He).call(this,"popupclosed",{});return}if(w===l.webauthnCreate||w===l.webauthnGet){if(!F||!$)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s,o,r;null===(u=e(this,de,"f"))||void 0===u||u.abort(),t(this,de,null,"f");try{i=w===l.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,o=e.reason,r=e.message}const n=yield this.sdk.flow.next(b,f,a.submit,ge.version,ve.componentsVersion,{transactionId:F,response:i,failure:s,failureReason:o,failureMessage:r});e(this,Oe,"f").call(this,n)}if(w===l.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(b,f,a.submit,ge.version,ve.componentsVersion,t);e(this,Oe,"f").call(this,i)})),e(this,le,"m",me).call(this,ee,te),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if((p("action")||p("deferredPolling"))&&e(this,We,"f").call(this,b,f,ge.version,ve.componentsVersion),!S&&!oe)return void this.loggerWrapper.warn("No screen was found to show");const ye=oe||S,Re=yield this.getHtmlFilenameWithLocale(D,ye),{oidcLoginHint:Ce,oidcPrompt:ke,oidcErrorRedirectUri:xe,oidcResource:Ee,samlIdpUsername:Ae}=se,je={direction:k(f,c.stepId),screenState:Object.assign(Object.assign({},y),{form:Object.assign(Object.assign({},this.formConfigValues),null==y?void 0:y.form),lastAuth:{loginId:ue,name:this.sdk.getLastUserDisplayName()||ue},componentsConfig:Object.assign(Object.assign(Object.assign({},ge.componentsConfig),Se),null==y?void 0:y.componentsConfig)}),htmlFilename:`${ye}.html`,htmlLocaleFilename:Re,screenId:ye,stepName:d.stepName||re,samlIdpUsername:Ae,oidcLoginHint:Ce,oidcPrompt:ke,oidcErrorRedirectUri:xe,oidcResource:Ee,action:w,locale:o(D).locale},Te=Y(ue,this.loggerWrapper);I(oe,se)?je.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ge?void 0:ge.clientScripts)||[];yield e(this,le,"m",qe).call(this,i);const r=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:be},se),{lastAuth:Te,preview:this.preview,abTestingKey:ae,client:this.client}),E&&{redirectUrl:E}),{locale:o(D).locale,nativeOptions:we,outboundAppId:pe,outboundAppScopes:he}),ne,t,ve.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),T(s)),L&&{exchangeCode:L,idpInitiated:!0}),se.descopeIdpInitiated&&{idpInitiated:!0}),A&&{token:A}),je.next.isCustomScreen);return e(this,Oe,"f").call(this,r),r})):(p("projectId")||p("baseUrl")||p("executionId")||p("stepId"))&&(je.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==y?void 0:y.clientScripts)||[];yield e(this,le,"m",qe).call(this,i);const o=yield this.sdk.flow.next(b,f,t,ge.version,ve.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),T(s)),je.next.isCustomScreen);return e(this,Oe,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",je.screenId),yield e(this,le,"m",Ie).call(this,je),this.stepState.update(je)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,r,n;const{htmlFilename:l,htmlLocaleFilename:d,direction:c,next:p,screenState:h,screenId:u}=t;this.loggerWrapper.debug("Rendering a flow screen"),this.updateScreenUser(null==h?void 0:h.user);const g=document.createElement("template");g.innerHTML=yield this.getPageContent(l,d);const m=g.content.cloneNode(!0),f=this.loadDescopeUiComponents(g);this.sdk.webauthn.helpers.isSupported()?yield e(this,le,"m",je).call(this,m,p):F(m),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(r=h.form)||void 0===r?void 0:r.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),$(m,h,this.formConfig,this.loggerWrapper),this.applyComponentsState(m,null==h?void 0:h.componentsState);const{geo:b}=null!==(n=yield this.getExecutionContext())&&void 0!==n?n:{};M(m,b),N(m,t.locale);const w=()=>i(this,void 0,void 0,(function*(){var i,o;yield f;const r=this.contentRootElement;q(r,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),V(r,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),D(r,m,h.cssVars,this.loggerWrapper),r.replaceChildren(m);const n=!s.htmlFilename;setTimeout((()=>{e(this,le,"m",$e).call(this),this.updateUsernameAnchor(),this.validateOnBlur&&L(r),B(r,h),this.initRealtimeConditions(r,h),e(this,le,"m",Te).call(this,{isFirstScreen:n,isCustomScreen:!1,stepName:t.stepName}),x(r,this.autoFocus,n),e(this,le,"m",Be).call(this,u)})),e(this,le,"m",Ke).call(this,p,u);r.querySelector(`[${v}="polling"]`)&&p(a.polling,{})}));c?e(this,le,"m",Ce).call(this,w):w()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${g}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}ae=new WeakMap,de=new WeakMap,ce=new WeakMap,pe=new WeakMap,ue=new WeakMap,ye=new WeakMap,Re=new WeakMap,We=new WeakMap,ke=new WeakMap,xe=new WeakMap,Oe=new WeakMap,Ee=new WeakMap,Pe=new WeakMap,Ne=new WeakMap,le=new WeakSet,he=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1,deferredPolling:!1})}),300)},ge=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,le,"m",me).call(this,"beforeScreen",{screen:t,context:s})}))}))},ve=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,le,"m",me).call(this,"afterScreen",{screen:t})},me=function(t,i){e(this,le,"m",He).call(this,"bridge",{type:t,payload:i})},fe=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)}K(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},be=function(){var t,i,o,r;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,le,"m",fe).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,le,"m",we).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(r=this.flowState)||void 0===r||r.subscribe((({screenId:e,executionId:t})=>{var i;try{this.updateTelemetryContext({screenId:e,executionId:t})}catch(e){null===(i=this.logger)||void 0===i||i.error("Error updating telemetry screenId:",e)}}),(e=>({screenId:e.screenId,executionId:e.executionId})))},we=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=""}))})),x(this.contentRootElement,this.autoFocus,!1))},Se=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")}))},Ie=function(o){return i(this,void 0,void 0,(function*(){var i;const r=Object.assign(Object.assign({},this.stepState.current),o),{next:n,stepName:l}=r,a=s(r,["next","stepName"]),d=O(a);let c=yield e(this,le,"m",ge).call(this,l,d,n);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,l,d,n,this)));const p=!this.stepState.current.htmlFilename;if(e(this,Re,"f").call(this,c),n&&(n.isCustomScreen=c),e(this,ye,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,ye,c,"f"),c?this.stepState.unsubscribeAll():e(this,le,"m",be).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,le,"m",Te).call(this,{isFirstScreen:p,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},Ce=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")},Ae=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)}))}},je=function(s,o){return i(this,void 0,void 0,(function*(){var r;null===(r=e(this,de,"f"))||void 0===r||r.abort();const n=s.querySelector('*[autocomplete="webauthn"]');if(n&&(yield H())){const{options:s,transactionId:r}=(yield e(this,Ee,"f").call(this))||{};s&&r&&(e(this,le,"m",Ae).call(this,n),t(this,de,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,de,"f")).then((e=>i(this,void 0,void 0,(function*(){o(n.id,{transactionId:r,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},Te=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,le,"m",He).call(this,"ready",{}),i||e(this,le,"m",ve).call(this,s),e(this,le,"m",He).call(this,"page-updated",{screenName:s}),e(this,le,"m",He).call(this,"screen-updated",{screenName:s})},Le=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"===t.localName||t.classList.contains("hidden")||(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},Ue=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})),{})}))},Fe=function(s){var o,r;const n=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),l=(null===(r=null===(o=this.flowState.current)||void 0===o?void 0:o.screenState)||void 0===r?void 0:r.clientScripts)||[],a=()=>{s.removeAttribute("loading"),n.forEach((e=>{e.removeAttribute("disabled")}))},d=e=>i(this,void 0,void 0,(function*(){var s;this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",d);if(!0===(null===(s=null==e?void 0:e.detail)||void 0===s?void 0:s.abandoned)&&l.length)return t(this,ce,(()=>i(this,void 0,void 0,(function*(){try{yield this.loadSdkScripts(l)}catch(e){this.loggerWrapper.warn("Failed to refresh client scripts on popup close",null==e?void 0:e.message)}})))(),"f"),void a();a();const o=yield this.getFlowConfig(),r=[...o.clientScripts||[],...o.sdkScripts||[]];this.loadSdkScripts(r)})),c=()=>{var i;window.removeEventListener("pageshow",e(this,Pe,"f")),t(this,Pe,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),d())}),"f"),window.addEventListener("pageshow",e(this,Pe,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&d(),this.removeEventListener("popupclosed",d),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},p=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?(this.addEventListener("popupclosed",d,{once:!0}),s.setAttribute("loading","true"),n.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(p),"success"===this.flowStatus?(this.removeEventListener("popupclosed",d),a()):c())}))},$e=function(){U();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,le,"m",Me).call(this,t)))},Me=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)}))},qe=function(t){return i(this,void 0,void 0,(function*(){if(e(this,ce,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ce,"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)}const o=[];for(const e of i)"function"==typeof e.refresh&&o.push(e.refresh());if(o.length>0)try{yield w(u,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},Ve=function(t,i){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((s=>{s.addEventListener("input",(()=>{var o;(null===(o=s.checkValidity)||void 0===o?void 0:o.call(s))&&e(this,Ne,"f").call(this,s,t,i)}))}))},De=function(e,t,i){t&&i&&"true"===e.getAttribute(m)&&Z(i,t,this.loggerWrapper)},Be=function(e){var t;const i=this.sdk.getLastUserLoginId(),s=null===(t=Y(i,this.loggerWrapper).lastUsedPerScreen)||void 0===t?void 0:t[e];if(!s)return;const o=this.contentRootElement.querySelector(f),r=this.contentRootElement.querySelector(`#${CSS.escape(s)}`);o&&r&&(r.replaceWith(o),o.appendChild(r))},Ke=function(t,i){this.contentRootElement.querySelectorAll(`descope-button:not([${b}]), [data-type="button"]:not([${b}]`).forEach((s=>{s.onclick=()=>{e(this,Ne,"f").call(this,s,t,i)}})),e(this,le,"m",Ve).call(this,t,i),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${g}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},He=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},_e=function(e,t,i){var s;const[o,r]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],n={data:{code:t,exchangeError:i},action:"code"};if("descope-wc"===o&&r){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",r);try{window.opener.postMessage(n,r)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(n),t.close()}try{window.close()}catch(e){}},Ge.bridgeVersion=3;export{Ge as default};
|
|
2
2
|
//# sourceMappingURL=DescopeWc.js.map
|