@descope/web-component 3.70.4 → 3.70.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/constants/index.js +1 -1
- package/dist/cjs/constants/index.js.map +1 -1
- package/dist/cjs/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/cjs/descope-wc/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/passwordManagerMixin.js +2 -0
- package/dist/cjs/mixins/passwordManagerMixin.js.map +1 -0
- package/dist/cjs/types.js.map +1 -1
- package/dist/esm/constants/index.js +1 -1
- package/dist/esm/constants/index.js.map +1 -1
- package/dist/esm/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/esm/descope-wc/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/passwordManagerMixin.js +2 -0
- package/dist/esm/mixins/passwordManagerMixin.js.map +1 -0
- package/dist/esm/types.js.map +1 -1
- package/dist/index.d.ts +509 -88
- package/dist/index.js +2 -2
- package/package.json +2 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var e=require("tslib"),t=require("@descope/sdk-helpers"),i=require("@descope/sdk-mixins"),r=require("../constants/index.js"),s=require("../helpers/helpers.js");require("../helpers/state.js"),require("@descope/escape-markdown"),require("../helpers/webauthn.js");const n=["externalId","email","phone"],o=["newPassword","password"],a="data-username-anchor",l=e=>{var t;if(!e)return"";try{const i=null===(t=window.sessionStorage)||void 0===t?void 0:t.getItem(r.DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY);if(!i)return"";const s=JSON.parse(i);return s.executionId===e&&s.loginId||""}catch(e){return""}},d=(e,t,i,s)=>{var o;const l=(null==i?void 0:i.email)||(null===(o=null==i?void 0:i.loginIds)||void 0===o?void 0:o[0]);(e=>e.querySelector("descope-new-password")||e.querySelector("descope-password"))(t)?l?(e=>{const t=['input[autocomplete="username"]',...n.map((e=>`[name="${e}"]`))].join(", ");return e.some((e=>e.querySelector(t)))})([e,t])?s.debug("Username anchor: screen already has an identifier field"):(s.debug("Username anchor: injecting hidden username input"),e.appendChild((e=>{const t=document.createElement("input");return t.setAttribute("autocomplete","username"),t.setAttribute("name","username"),t.setAttribute("type","email"),t.setAttribute("readonly","true"),t.setAttribute("tabindex","-1"),t.setAttribute("aria-hidden","true"),t.setAttribute(r.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,"true"),t.setAttribute(a,"true"),t.setAttribute("value",e),t.value=e,Object.assign(t.style,{position:"absolute",opacity:"0",pointerEvents:"none",height:"0",border:"0"}),t})(l))):s.debug("Username anchor: no user identifier available"):s.debug("Username anchor: no password component on screen")},u=t.createSingletonMixin((u=>{var c,v,p,h,g;const m=t.compose(i.loggerMixin)(u);return g=class extends m{constructor(){super(...arguments),c.add(this),v.set(this,void 0)}updateScreenUser(t){var i,r,s;e.__classPrivateFieldSet(this,v,{email:null==t?void 0:t.email,loginIds:(null===(i=null==t?void 0:t.loginIds)||void 0===i?void 0:i.length)?t.loginIds:[l(e.__classPrivateFieldGet(this,c,"a",h))||(null===(s=null===(r=e.__classPrivateFieldGet(this,c,"a",p).sdk)||void 0===r?void 0:r.getLastUserLoginId)||void 0===s?void 0:s.call(r))].filter(Boolean)},"f")}updateUsernameAnchor(){document.querySelectorAll(`[${a}="true"]`).forEach((e=>e.remove())),d(this,e.__classPrivateFieldGet(this,c,"a",p).contentRootElement,e.__classPrivateFieldGet(this,v,"f"),this.logger)}captureLastSubmittedLoginId(t={},i){const o=s.getFirstNonEmptyValue(t,n);o&&((e,t)=>{var i;if(e&&t)try{null===(i=window.sessionStorage)||void 0===i||i.setItem(r.DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,JSON.stringify({executionId:t,loginId:e}))}catch(e){}})(o,i||e.__classPrivateFieldGet(this,c,"a",h))}storeCredentials(t={}){var i,r,a,l,d;const u=s.getFirstNonEmptyValue(t,n)||(null===(i=e.__classPrivateFieldGet(this,v,"f"))||void 0===i?void 0:i.email)||(null===(a=null===(r=e.__classPrivateFieldGet(this,v,"f"))||void 0===r?void 0:r.loginIds)||void 0===a?void 0:a[0]),c=s.getFirstNonEmptyValue(t,o);if(u&&c)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:u,password:c});null===(d=null===(l=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===l?void 0:l.store)||void 0===d||d.call(l,e)}catch(e){this.logger.error("Could not store credentials",e.message)}}},v=new WeakMap,c=new WeakSet,p=function(){return this},h=function(){var t,i;return(null===(i=null===(t=e.__classPrivateFieldGet(this,c,"a",p).flowState)||void 0===t?void 0:t.current)||void 0===i?void 0:i.executionId)||""},g}));exports.passwordManagerMixin=u;
|
|
2
|
+
//# sourceMappingURL=passwordManagerMixin.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"passwordManagerMixin.js","sources":["../../../src/lib/mixins/passwordManagerMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n} from '../constants';\nimport { getFirstNonEmptyValue } from '../helpers';\nimport type { ScreenStateUser } from '../types';\n\nconst LOGIN_ID_FIELDS = ['externalId', 'email', 'phone'];\nconst PASSWORD_FIELDS = ['newPassword', 'password'];\n\nconst USERNAME_ANCHOR_ATTRIBUTE = 'data-username-anchor';\n\n// What the mixin needs from its host. Defined as an interface (not imported)\n// to avoid a circular dependency on DescopeWc. Exported so declaration emit\n// can name it from BaseDescopeWc's composed base class.\nexport interface PasswordManagerHost {\n contentRootElement?: HTMLElement;\n flowState?: { current?: { executionId?: string } };\n sdk?: { getLastUserLoginId?: () => string };\n}\n\n// the last identifier the user submitted on a previous screen in this flow\n// (e.g. the email entered before a magic link was sent), used when neither\n// the flow state nor a previous authentication provides one.\n// kept in sessionStorage (tab scoped, cleared when the tab closes) so it\n// survives page reloads during the flow, and scoped to the flow execution so\n// a stale identifier is never carried into another flow (or another user)\n// running in the same tab\nconst getLastSubmittedLoginId = (executionId: string): string => {\n // a missing execution id must never match anything, otherwise two flows\n // without one would share the stored identifier\n if (!executionId) {\n return '';\n }\n try {\n const raw = window.sessionStorage?.getItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n );\n if (!raw) {\n return '';\n }\n const stored = JSON.parse(raw);\n return stored.executionId === executionId ? stored.loginId || '' : '';\n } catch (e) {\n return '';\n }\n};\n\nconst setLastSubmittedLoginId = (loginId: string, executionId: string) => {\n if (!loginId || !executionId) {\n return;\n }\n try {\n window.sessionStorage?.setItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n JSON.stringify({ executionId, loginId }),\n );\n } catch (e) {\n // sessionStorage unavailable, losing reload persistence is acceptable\n }\n};\n\nconst clearUsernameAnchorIfExists = () => {\n document\n .querySelectorAll(`[${USERNAME_ANCHOR_ATTRIBUTE}=\"true\"]`)\n .forEach((ele) => ele.remove());\n};\n\nconst findPasswordComponent = (contentRootEle: Element) =>\n contentRootEle.querySelector('descope-new-password') ||\n contentRootEle.querySelector('descope-password');\n\n// an identifier is already on screen when there is an autocomplete=\"username\"\n// input, or a component collecting one of the login id fields (e.g.\n// descope-email-field renders its input inside a closed shadow root, so only\n// its name attribute is visible from here)\nconst hasLoginIdField = (roots: Element[]) => {\n const selector = [\n 'input[autocomplete=\"username\"]',\n ...LOGIN_ID_FIELDS.map((field) => `[name=\"${field}\"]`),\n ].join(', ');\n return roots.some((root) => root.querySelector(selector));\n};\n\nconst createUsernameAnchor = (loginId: string) => {\n const input = document.createElement('input');\n input.setAttribute('autocomplete', 'username');\n input.setAttribute('name', 'username');\n input.setAttribute('type', 'email');\n input.setAttribute('readonly', 'true');\n input.setAttribute('tabindex', '-1');\n input.setAttribute('aria-hidden', 'true');\n // never collect the anchor's value into the submitted form data\n input.setAttribute(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD, 'true');\n // cleaned up by clearUsernameAnchorIfExists between screens\n input.setAttribute(USERNAME_ANCHOR_ATTRIBUTE, 'true');\n // some password managers read the markup value rather than the property\n input.setAttribute('value', loginId);\n input.value = loginId;\n // real input hidden via CSSOM: managers ignore type=\"hidden\", and strict\n // CSP style-src blocks style attributes\n Object.assign(input.style, {\n position: 'absolute',\n opacity: '0',\n pointerEvents: 'none',\n height: '0',\n border: '0',\n });\n return input;\n};\n\n// Anchors a hidden autocomplete=\"username\" input on password screens that\n// have no identifier input, so password managers can associate the credential\n// with a user (descope/etc#16712). Appended to the host light DOM — password\n// manager save heuristics (verified on WebKit) do not scan shadow trees\nconst injectUsernameAnchorIfNeeded = (\n hostEle: HTMLElement,\n contentRootEle: Element,\n user: ScreenStateUser | undefined,\n logger: { debug: (...args: string[]) => void },\n) => {\n const loginId = user?.email || user?.loginIds?.[0];\n\n if (!findPasswordComponent(contentRootEle)) {\n logger.debug('Username anchor: no password component on screen');\n return;\n }\n if (!loginId) {\n logger.debug('Username anchor: no user identifier available');\n return;\n }\n if (hasLoginIdField([hostEle, contentRootEle])) {\n logger.debug('Username anchor: screen already has an identifier field');\n return;\n }\n\n logger.debug('Username anchor: injecting hidden username input');\n hostEle.appendChild(createUsernameAnchor(loginId));\n};\n\n/**\n * Password manager integrations: keeps track of the current screen's user\n * identifier, anchors a hidden username input on password screens that have\n * no identifier input, and stores submitted credentials via the Credential\n * Management API.\n */\nexport const passwordManagerMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class PasswordManagerMixinClass extends BaseClass {\n // the authenticated user of the current screen (if any), used as a\n // fallback identifier for password manager integrations on screens that\n // have no identifier input (e.g. step-up password change)\n #screenUser?: ScreenStateUser;\n\n get #host() {\n return this as unknown as PasswordManagerHost;\n }\n\n get #executionId() {\n return this.#host.flowState?.current?.executionId || '';\n }\n\n // called on every screen render. flow state does not always carry the\n // user (e.g. after magic link auth), so fall back to the login id\n // submitted earlier in this flow, then to the last authenticated user\n updateScreenUser(stateUser?: ScreenStateUser) {\n this.#screenUser = {\n email: stateUser?.email,\n loginIds: stateUser?.loginIds?.length\n ? stateUser.loginIds\n : [\n getLastSubmittedLoginId(this.#executionId) ||\n this.#host.sdk?.getLastUserLoginId?.(),\n ].filter(Boolean),\n };\n }\n\n updateUsernameAnchor() {\n // clear the previous screen's anchor, so each screen gets an anchor\n // only if it needs one\n clearUsernameAnchorIfExists();\n\n injectUsernameAnchorIfNeeded(\n this,\n this.#host.contentRootElement,\n this.#screenUser,\n this.logger,\n );\n }\n\n // called after a successful next(): on flows that render their first\n // screen before the flow starts, the execution id only exists on the\n // response, so prefer it over the current flow state\n captureLastSubmittedLoginId(formData = {}, responseExecutionId?: string) {\n const loginId = getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS);\n if (loginId) {\n setLastSubmittedLoginId(\n loginId,\n responseExecutionId || this.#executionId,\n );\n }\n }\n\n // handle storing passwords in password managers\n storeCredentials(formData = {}) {\n const id =\n getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS) ||\n this.#screenUser?.email ||\n this.#screenUser?.loginIds?.[0];\n const password = getFirstNonEmptyValue(formData, PASSWORD_FIELDS);\n\n // PasswordCredential not supported in Firefox\n if (id && password) {\n try {\n if (!globalThis.PasswordCredential) {\n return;\n }\n const cred = new globalThis.PasswordCredential({ id, password });\n\n navigator?.credentials?.store?.(cred);\n } catch (e) {\n this.logger.error('Could not store credentials', e.message);\n }\n }\n }\n };\n },\n);\n"],"names":["LOGIN_ID_FIELDS","PASSWORD_FIELDS","USERNAME_ANCHOR_ATTRIBUTE","getLastSubmittedLoginId","executionId","raw","_a","window","sessionStorage","getItem","DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY","stored","JSON","parse","loginId","e","injectUsernameAnchorIfNeeded","hostEle","contentRootEle","user","logger","email","loginIds","querySelector","findPasswordComponent","roots","selector","map","field","join","some","root","hasLoginIdField","debug","appendChild","input","document","createElement","setAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","value","Object","assign","style","position","opacity","pointerEvents","height","border","createUsernameAnchor","passwordManagerMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","constructor","_PasswordManagerMixinClass_screenUser","set","this","updateScreenUser","stateUser","__classPrivateFieldSet","_b","length","__classPrivateFieldGet","_PasswordManagerMixinClass_instances","_PasswordManagerMixinClass_executionId_get","_d","_c","_PasswordManagerMixinClass_host_get","sdk","getLastUserLoginId","call","filter","Boolean","updateUsernameAnchor","querySelectorAll","forEach","ele","remove","contentRootElement","captureLastSubmittedLoginId","formData","responseExecutionId","getFirstNonEmptyValue","setItem","stringify","setLastSubmittedLoginId","storeCredentials","id","password","globalThis","PasswordCredential","cred","_f","_e","navigator","credentials","store","error","message","flowState","current"],"mappings":"kRAUA,MAAMA,EAAkB,CAAC,aAAc,QAAS,SAC1CC,EAAkB,CAAC,cAAe,YAElCC,EAA4B,uBAkB5BC,EAA2BC,UAG/B,IAAKA,EACH,MAAO,GAET,IACE,MAAMC,EAA2B,QAArBC,EAAAC,OAAOC,sBAAc,IAAAF,OAAA,EAAAA,EAAEG,QACjCC,EAAmDA,qDAErD,IAAKL,EACH,MAAO,GAET,MAAMM,EAASC,KAAKC,MAAMR,GAC1B,OAAOM,EAAOP,cAAgBA,GAAcO,EAAOG,SAAgB,EACpE,CAAC,MAAOC,GACP,MAAO,EACR,GAsEGC,EAA+B,CACnCC,EACAC,EACAC,EACAC,WAEA,MAAMN,GAAUK,aAAI,EAAJA,EAAME,SAA0B,UAAjBF,aAAI,EAAJ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H,KAAIC,aAErB,QAAhCI,EAAwB,QAAxBC,EAAA,OAAAC,gBAAA,IAAAA,eAAA,EAAAA,UAAWC,mBAAa,IAAAF,OAAA,EAAAA,EAAAG,aAAQ,IAAAJ,GAAAA,EAAAtB,KAAAuB,EAAAF,EACjC,CAAC,MAAO/E,GACP4C,KAAKvC,OAAOgF,MAAM,8BAA+BrF,EAAEsF,QACpD,CAEJ,4CArEC,OAAO1C,IACR,uBAGC,OAAoC,QAA7BU,EAAoB,QAApBN,EAAAE,EAAAA,uBAAAN,KAAUO,EAAA,IAAAI,GAACgC,iBAAS,IAAAvC,OAAA,EAAAA,EAAEwC,eAAO,IAAAlC,OAAA,EAAAA,EAAEjE,cAAe,EACtD,EAiEDE,CAAA"}
|
package/dist/cjs/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sources":["../../src/lib/types.ts"],"sourcesContent":["/* istanbul ignore file */\n\nimport type { JWTResponse } from '@descope/web-js-sdk';\nimport { createSdk } from '@descope/web-js-sdk';\n\nexport type SdkConfig = Parameters<typeof createSdk>[0];\nexport type Sdk = ReturnType<typeof createSdk>;\n\nexport type SdkFlowNext = Sdk['flow']['next'];\n\nexport type ComponentsDynamicAttrs = {\n attributes: Record<string, any>;\n};\n\nexport type ComponentsConfig = Record<string, any> & {\n componentsDynamicAttrs?: Record<string, ComponentsDynamicAttrs>;\n};\nexport type CssVars = Record<string, any>;\n\ntype KeepArgsByIndex<F, Indices extends readonly number[]> = F extends (\n ...args: infer A\n) => infer R\n ? (...args: PickArgsByIndex<A, Indices>) => R\n : never;\n\ntype PickArgsByIndex<\n All extends readonly any[],\n Indices extends readonly number[],\n> = {\n [K in keyof Indices]: Indices[K] extends keyof All ? All[Indices[K]] : never;\n};\n\ntype Project = {\n name: string;\n};\n\nexport enum Direction {\n backward = 'backward',\n forward = 'forward',\n}\n\nexport type LastAuthState = NonNullable<\n NextFnReturnPromiseValue['data']['lastAuth']\n> & {\n loginId?: string;\n name?: string;\n lastUsedPerScreen?: Record<string, string>;\n};\n\nexport type RealtimeOperandKind = 'value' | 'form' | 'list';\n\n// Operators the SDK is allowed to evaluate locally. The server's\n// clientSupportedRealtimeOperators must stay in sync — anything outside this\n// list is pre-evaluated server-side and shipped as a value operand.\n//\n// is-email / is-phone are intentionally absent: the server validates them\n// with dedicated libraries (contact.IsValid*); the client has no equivalent,\n// so the server keeps these CCs server-only.\nexport type RealtimeOperator =\n | 'equal'\n | 'not-equal'\n | 'contains'\n | 'doesnt-contains'\n | 'greater-than'\n | 'greater-than-or-equal'\n | 'less-than'\n | 'less-than-or-equal'\n | 'empty'\n | 'not-empty'\n | 'is-true'\n | 'is-false'\n | 'in'\n | 'not-in'\n | 'matches';\n\nexport interface RealtimeOperand {\n kind: RealtimeOperandKind;\n // Form is the context key the client looks up from the live form snapshot\n // (e.g. \"form.phone\"). Set only when kind === 'form'.\n form?: string;\n // Items is the operand list when kind === 'list'. Each element is a nested\n // operand — either a form placeholder or a resolved literal. Used when the\n // server detects an `in` / `not-in` / `contains` predicate whose array\n // contains `{{form.X}}` references; the client resolves them at eval time.\n items?: RealtimeOperand[];\n // Pre-resolved literal. Set only when kind === 'value', and may legitimately\n // be false / 0 / \"\" — do not treat absence as \"no value\" without checking\n // kind first.\n value?: unknown;\n}\n\nexport interface RealtimeAtomicCondition {\n operator: RealtimeOperator;\n target?: RealtimeOperand;\n predicate?: RealtimeOperand;\n}\n\nexport interface RealtimeRule {\n logicalOr?: boolean;\n atomicConditions: RealtimeAtomicCondition[];\n}\n\nexport interface RealtimeComponentsCondition {\n id?: string;\n componentIds: string[];\n action: string;\n rules: RealtimeRule[];\n}\n\nexport interface ScreenState {\n errorText?: string;\n errorType?: string;\n componentsConfig?: ComponentsConfig;\n cssVars?: CssVars;\n form?: Record<string, string>;\n inputs?: Record<string, string>; // Backward compatibility\n lastAuth?: LastAuthState;\n project?: Project;\n totp?: { image?: string; provisionUrl?: string };\n notp?: { image?: string; redirectUrl?: string };\n selfProvisionDomains?: unknown;\n user?: unknown;\n sso?: unknown;\n dynamicSelects?: unknown;\n keysInUse?: unknown;\n genericForm?: unknown;\n linkId?: unknown;\n sentTo?: unknown;\n clientScripts?: ClientScript[];\n // map of component IDs to their state — the FULL last-wins verdict over\n // all CCs (server-only + client-eligible) the BE evaluated at screen-init.\n // Used by `applyComponentsState` for the first DOM paint.\n componentsState?: Record<string, string>;\n // Subset of `componentsState` contributed by SERVER-ONLY CCs — those the\n // client cannot re-evaluate locally (operators on the server-only\n // allow-list like `is-email`, or rules referencing context the client\n // doesn't have). Parallels `componentsState` in structure but excludes\n // contributions from client-eligible CCs that also ship in\n // `realtimeComponentsConditions`.\n //\n // The realtime layer uses this as the fallback action to restore when a\n // realtime CC stops firing on a touched component — without it the SDK\n // can't tell whether the action in `componentsState` came from a\n // server-only CC (must persist) or from a realtime CC also re-shipped\n // (must clear).\n //\n // Absent on old backends; new SDKs fall back to a legacy heuristic that\n // infers the same information from `componentsState`, so the old-BE /\n // new-SDK combination still works correctly.\n serverOnlyComponentsState?: Record<string, string>;\n // Client-evaluable visibility conditions, populated only by new backends.\n // Absent on old backends; new SDKs ignore when absent.\n realtimeComponentsConditions?: RealtimeComponentsCondition[];\n}\n\nexport type SSOQueryParams = {\n oidcIdpStateId?: string;\n samlIdpStateId?: string;\n wsfedIdpStateId?: string;\n samlIdpUsername?: string;\n descopeIdpInitiated?: boolean;\n ssoAppId?: string;\n customAppId?: string;\n thirdPartyAppId: string;\n thirdPartyAppStateId?: string;\n applicationScopes?: string;\n} & OIDCOptions;\n\nexport type OIDCOptions = {\n oidcLoginHint?: string;\n oidcPrompt?: string;\n oidcErrorRedirectUri?: string;\n oidcResource?: string;\n};\n\nexport type FlowState = {\n flowId: string;\n projectId: string;\n baseUrl: string;\n tenant: string;\n stepId: string;\n stepName: string;\n executionId: string;\n action: string;\n redirectTo: string;\n redirectIsPopup: boolean;\n openInNewTabUrl?: string;\n redirectUrl: string;\n screenId: string;\n screenState: ScreenState;\n token: string;\n code: string;\n isPopup: boolean;\n exchangeError: string;\n webauthnTransactionId: string;\n webauthnOptions: string;\n redirectAuthCodeChallenge: string;\n redirectAuthCallbackUrl: string;\n redirectAuthBackupCallbackUri: string;\n redirectAuthInitiator: string;\n deferredRedirect: boolean;\n deferredPolling: boolean;\n locale: string;\n samlIdpResponseUrl: string;\n samlIdpResponseSamlResponse: string;\n samlIdpResponseRelayState: string;\n wsFedIdpResponseUrl: string;\n wsFedIdpResponseWresult: string;\n wsFedIdpResponseWctx: string;\n nativeResponseType: string;\n nativePayload: Record<string, any>;\n reqTimestamp: number;\n} & SSOQueryParams;\n\nexport type StepState = {\n screenState: ScreenState;\n screenId: string;\n stepName: string;\n htmlFilename: string;\n htmlLocaleFilename: string;\n next: NextFn;\n direction: Direction | undefined;\n samlIdpUsername: string;\n action?: string;\n locale?: string;\n} & OIDCOptions;\n\nexport type CustomScreenState = Omit<\n ScreenState,\n 'cssVars' | 'componentsConfig' | 'inputs'\n> & {\n error?: {\n text: ScreenState['errorText'];\n type: ScreenState['errorType'];\n };\n action?: string;\n inboundAppApproveScopes?: {\n desc: string;\n id: string;\n required: boolean;\n }[];\n};\n\nexport type DebugState = {\n isDebug: boolean;\n};\n\nexport interface ScriptElement extends HTMLDivElement {\n moduleRes?: ScriptModule;\n}\n\nexport type ScriptModule = {\n /**\n * Unique identifier of the module.\n */\n id: string;\n /**\n * Notifies the module that it should start any profiling or monitoring.\n */\n start?: () => void;\n /**\n * Notifies the module that it should stop any profiling or monitoring.\n */\n stop?: () => void;\n /**\n * Presents the user with any required interaction to get a refreshed token or state,\n * e.g., a challenge or captcha.\n *\n * Modules should return a value of true if the presentation completed successfully,\n * false if it was cancelled by the user, and throw an error in case of failure.\n *\n * This is called before form submission (via a next call) after a button click.\n */\n present?: () => Promise<boolean>;\n /**\n * Refreshes any tokens or state that might be needed before form submission.\n *\n * Modules should throw an error in case of failure.\n */\n refresh?: () => Promise<void>;\n};\n\nexport type ClientScript = {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n};\n\nexport type NextFn = KeepArgsByIndex<SdkFlowNext, [2, 5]> & {\n isCustomScreen?: boolean;\n};\nexport type NextFnReturnPromiseValue = Awaited<ReturnType<NextFn>>;\n\nexport type DebuggerMessage = {\n title: string;\n description?: string;\n};\n\nexport type FlowStateUpdateFn = (state: FlowState) => void;\n\ntype Operator =\n | 'equal'\n | 'not-equal'\n | 'contains'\n | 'greater-than'\n | 'greater-than-or-equal'\n | 'less-than'\n | 'less-than-or-equal'\n | 'empty'\n | 'not-empty'\n | 'is-true'\n | 'is-false'\n | 'in'\n | 'not-in'\n | 'in-range'\n | 'not-in-range'\n | 'devised-by';\n\nexport interface ClientConditionResult {\n screenId: string;\n screenName: string;\n clientScripts?: ClientScript[];\n componentsConfig?: ComponentsConfig;\n interactionId: string;\n}\n\nexport interface ClientCondition {\n operator: Operator;\n key: string;\n predicate?: string | number;\n met: ClientConditionResult;\n unmet?: ClientConditionResult;\n}\n\nexport type AutoFocusOptions = true | false | 'skipFirstScreen';\n\nexport type ThemeOptions = 'light' | 'dark' | 'os';\n\nexport type Key =\n | 'lastAuth.loginId'\n | 'idpInitiated'\n | 'externalToken'\n | 'abTestingKey';\n\ntype CheckFunction = (ctx: Context, predicate?: string | number) => boolean;\n\nexport type ConditionsMap = {\n [key in Key]: {\n [operator in Operator]?: CheckFunction;\n };\n};\n\nexport interface Context {\n loginId?: string;\n code?: string;\n token?: string;\n abTestingKey?: number;\n lastAuth?: LastAuthState;\n}\n\nexport type DescopeUI = Record<string, () => Promise<void>> & {\n componentsThemeManager: Record<string, any>;\n};\n\ntype Font = {\n family: string[];\n label: string;\n url?: string;\n};\n\ntype ThemeTemplate = {\n fonts: {\n font1: Font;\n font2: Font;\n };\n};\n\ntype ThemeColor = {\n main: string;\n dark: string;\n light: string;\n highlight: string;\n contrast: string;\n};\n\nexport type OverrideTheme = {\n globals?: {\n colors?: {\n primary?: ThemeColor;\n secondary?: ThemeColor;\n };\n };\n};\n\nexport type OverrideThemes = {\n dark?: OverrideTheme;\n light?: OverrideTheme;\n};\n\nexport type FlowConfig = {\n startScreenId?: string;\n startScreenName?: string;\n version: number;\n targetLocales?: string[];\n conditions?: ClientCondition[];\n condition?: ClientCondition;\n fingerprintEnabled?: boolean;\n fingerprintKey?: string;\n sdkScripts?: [\n {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n },\n ];\n clientScripts?: ClientScript[];\n componentsConfig?: ComponentsConfig;\n};\n\nexport interface ProjectConfiguration {\n componentsVersion: string;\n cssTemplate: {\n dark: ThemeTemplate;\n light: ThemeTemplate;\n };\n flows: {\n [key: string]: FlowConfig; // dynamic key names for flows\n };\n}\n\nexport type FlowStatus = 'loading' | 'error' | 'success' | 'ready' | 'initial';\n\nexport type CustomStorage = {\n getItem: (key: string) => string | null;\n setItem: (key: string, value: string) => void;\n removeItem: (key: string) => void;\n};\n\nexport type FlowJWTResponse = JWTResponse & {\n flowOutput?: Record<string, any>;\n};\n"],"names":["Direction"],"mappings":"aAoCA,IAAYA,EAAAA,QAGXA,eAAA,GAHWA,EAAAA,QAASA,YAATA,kBAGX,CAAA,IAFC,SAAA,WACAA,EAAA,QAAA"}
|
|
1
|
+
{"version":3,"file":"types.js","sources":["../../src/lib/types.ts"],"sourcesContent":["/* istanbul ignore file */\n\nimport type { JWTResponse } from '@descope/web-js-sdk';\nimport { createSdk } from '@descope/web-js-sdk';\n\nexport type SdkConfig = Parameters<typeof createSdk>[0];\nexport type Sdk = ReturnType<typeof createSdk>;\n\nexport type SdkFlowNext = Sdk['flow']['next'];\n\nexport type ComponentsDynamicAttrs = {\n attributes: Record<string, any>;\n};\n\nexport type ComponentsConfig = Record<string, any> & {\n componentsDynamicAttrs?: Record<string, ComponentsDynamicAttrs>;\n};\nexport type CssVars = Record<string, any>;\n\ntype KeepArgsByIndex<F, Indices extends readonly number[]> = F extends (\n ...args: infer A\n) => infer R\n ? (...args: PickArgsByIndex<A, Indices>) => R\n : never;\n\ntype PickArgsByIndex<\n All extends readonly any[],\n Indices extends readonly number[],\n> = {\n [K in keyof Indices]: Indices[K] extends keyof All ? All[Indices[K]] : never;\n};\n\ntype Project = {\n name: string;\n};\n\nexport enum Direction {\n backward = 'backward',\n forward = 'forward',\n}\n\nexport type LastAuthState = NonNullable<\n NextFnReturnPromiseValue['data']['lastAuth']\n> & {\n loginId?: string;\n name?: string;\n lastUsedPerScreen?: Record<string, string>;\n};\n\nexport type RealtimeOperandKind = 'value' | 'form' | 'list';\n\n// Operators the SDK is allowed to evaluate locally. The server's\n// clientSupportedRealtimeOperators must stay in sync — anything outside this\n// list is pre-evaluated server-side and shipped as a value operand.\n//\n// is-email / is-phone are intentionally absent: the server validates them\n// with dedicated libraries (contact.IsValid*); the client has no equivalent,\n// so the server keeps these CCs server-only.\nexport type RealtimeOperator =\n | 'equal'\n | 'not-equal'\n | 'contains'\n | 'doesnt-contains'\n | 'greater-than'\n | 'greater-than-or-equal'\n | 'less-than'\n | 'less-than-or-equal'\n | 'empty'\n | 'not-empty'\n | 'is-true'\n | 'is-false'\n | 'in'\n | 'not-in'\n | 'matches';\n\nexport interface RealtimeOperand {\n kind: RealtimeOperandKind;\n // Form is the context key the client looks up from the live form snapshot\n // (e.g. \"form.phone\"). Set only when kind === 'form'.\n form?: string;\n // Items is the operand list when kind === 'list'. Each element is a nested\n // operand — either a form placeholder or a resolved literal. Used when the\n // server detects an `in` / `not-in` / `contains` predicate whose array\n // contains `{{form.X}}` references; the client resolves them at eval time.\n items?: RealtimeOperand[];\n // Pre-resolved literal. Set only when kind === 'value', and may legitimately\n // be false / 0 / \"\" — do not treat absence as \"no value\" without checking\n // kind first.\n value?: unknown;\n}\n\nexport interface RealtimeAtomicCondition {\n operator: RealtimeOperator;\n target?: RealtimeOperand;\n predicate?: RealtimeOperand;\n}\n\nexport interface RealtimeRule {\n logicalOr?: boolean;\n atomicConditions: RealtimeAtomicCondition[];\n}\n\nexport interface RealtimeComponentsCondition {\n id?: string;\n componentIds: string[];\n action: string;\n rules: RealtimeRule[];\n}\n\n// the server sends the full user object; only the fields the SDK reads are\n// typed here\nexport interface ScreenStateUser {\n email?: string;\n loginIds?: string[];\n [key: string]: unknown;\n}\n\nexport interface ScreenState {\n errorText?: string;\n errorType?: string;\n componentsConfig?: ComponentsConfig;\n cssVars?: CssVars;\n form?: Record<string, string>;\n inputs?: Record<string, string>; // Backward compatibility\n lastAuth?: LastAuthState;\n project?: Project;\n totp?: { image?: string; provisionUrl?: string };\n notp?: { image?: string; redirectUrl?: string };\n selfProvisionDomains?: unknown;\n user?: ScreenStateUser;\n sso?: unknown;\n dynamicSelects?: unknown;\n keysInUse?: unknown;\n genericForm?: unknown;\n linkId?: unknown;\n sentTo?: unknown;\n clientScripts?: ClientScript[];\n // map of component IDs to their state — the FULL last-wins verdict over\n // all CCs (server-only + client-eligible) the BE evaluated at screen-init.\n // Used by `applyComponentsState` for the first DOM paint.\n componentsState?: Record<string, string>;\n // Subset of `componentsState` contributed by SERVER-ONLY CCs — those the\n // client cannot re-evaluate locally (operators on the server-only\n // allow-list like `is-email`, or rules referencing context the client\n // doesn't have). Parallels `componentsState` in structure but excludes\n // contributions from client-eligible CCs that also ship in\n // `realtimeComponentsConditions`.\n //\n // The realtime layer uses this as the fallback action to restore when a\n // realtime CC stops firing on a touched component — without it the SDK\n // can't tell whether the action in `componentsState` came from a\n // server-only CC (must persist) or from a realtime CC also re-shipped\n // (must clear).\n //\n // Absent on old backends; new SDKs fall back to a legacy heuristic that\n // infers the same information from `componentsState`, so the old-BE /\n // new-SDK combination still works correctly.\n serverOnlyComponentsState?: Record<string, string>;\n // Client-evaluable visibility conditions, populated only by new backends.\n // Absent on old backends; new SDKs ignore when absent.\n realtimeComponentsConditions?: RealtimeComponentsCondition[];\n}\n\nexport type SSOQueryParams = {\n oidcIdpStateId?: string;\n samlIdpStateId?: string;\n wsfedIdpStateId?: string;\n samlIdpUsername?: string;\n descopeIdpInitiated?: boolean;\n ssoAppId?: string;\n customAppId?: string;\n thirdPartyAppId: string;\n thirdPartyAppStateId?: string;\n applicationScopes?: string;\n} & OIDCOptions;\n\nexport type OIDCOptions = {\n oidcLoginHint?: string;\n oidcPrompt?: string;\n oidcErrorRedirectUri?: string;\n oidcResource?: string;\n};\n\nexport type FlowState = {\n flowId: string;\n projectId: string;\n baseUrl: string;\n tenant: string;\n stepId: string;\n stepName: string;\n executionId: string;\n action: string;\n redirectTo: string;\n redirectIsPopup: boolean;\n openInNewTabUrl?: string;\n redirectUrl: string;\n screenId: string;\n screenState: ScreenState;\n token: string;\n code: string;\n isPopup: boolean;\n exchangeError: string;\n webauthnTransactionId: string;\n webauthnOptions: string;\n redirectAuthCodeChallenge: string;\n redirectAuthCallbackUrl: string;\n redirectAuthBackupCallbackUri: string;\n redirectAuthInitiator: string;\n deferredRedirect: boolean;\n deferredPolling: boolean;\n locale: string;\n samlIdpResponseUrl: string;\n samlIdpResponseSamlResponse: string;\n samlIdpResponseRelayState: string;\n wsFedIdpResponseUrl: string;\n wsFedIdpResponseWresult: string;\n wsFedIdpResponseWctx: string;\n nativeResponseType: string;\n nativePayload: Record<string, any>;\n reqTimestamp: number;\n} & SSOQueryParams;\n\nexport type StepState = {\n screenState: ScreenState;\n screenId: string;\n stepName: string;\n htmlFilename: string;\n htmlLocaleFilename: string;\n next: NextFn;\n direction: Direction | undefined;\n samlIdpUsername: string;\n action?: string;\n locale?: string;\n} & OIDCOptions;\n\nexport type CustomScreenState = Omit<\n ScreenState,\n 'cssVars' | 'componentsConfig' | 'inputs'\n> & {\n error?: {\n text: ScreenState['errorText'];\n type: ScreenState['errorType'];\n };\n action?: string;\n inboundAppApproveScopes?: {\n desc: string;\n id: string;\n required: boolean;\n }[];\n};\n\nexport type DebugState = {\n isDebug: boolean;\n};\n\nexport interface ScriptElement extends HTMLDivElement {\n moduleRes?: ScriptModule;\n}\n\nexport type ScriptModule = {\n /**\n * Unique identifier of the module.\n */\n id: string;\n /**\n * Notifies the module that it should start any profiling or monitoring.\n */\n start?: () => void;\n /**\n * Notifies the module that it should stop any profiling or monitoring.\n */\n stop?: () => void;\n /**\n * Presents the user with any required interaction to get a refreshed token or state,\n * e.g., a challenge or captcha.\n *\n * Modules should return a value of true if the presentation completed successfully,\n * false if it was cancelled by the user, and throw an error in case of failure.\n *\n * This is called before form submission (via a next call) after a button click.\n */\n present?: () => Promise<boolean>;\n /**\n * Refreshes any tokens or state that might be needed before form submission.\n *\n * Modules should throw an error in case of failure.\n */\n refresh?: () => Promise<void>;\n};\n\nexport type ClientScript = {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n};\n\nexport type NextFn = KeepArgsByIndex<SdkFlowNext, [2, 5]> & {\n isCustomScreen?: boolean;\n};\nexport type NextFnReturnPromiseValue = Awaited<ReturnType<NextFn>>;\n\nexport type DebuggerMessage = {\n title: string;\n description?: string;\n};\n\nexport type FlowStateUpdateFn = (state: FlowState) => void;\n\ntype Operator =\n | 'equal'\n | 'not-equal'\n | 'contains'\n | 'greater-than'\n | 'greater-than-or-equal'\n | 'less-than'\n | 'less-than-or-equal'\n | 'empty'\n | 'not-empty'\n | 'is-true'\n | 'is-false'\n | 'in'\n | 'not-in'\n | 'in-range'\n | 'not-in-range'\n | 'devised-by';\n\nexport interface ClientConditionResult {\n screenId: string;\n screenName: string;\n clientScripts?: ClientScript[];\n componentsConfig?: ComponentsConfig;\n interactionId: string;\n}\n\nexport interface ClientCondition {\n operator: Operator;\n key: string;\n predicate?: string | number;\n met: ClientConditionResult;\n unmet?: ClientConditionResult;\n}\n\nexport type AutoFocusOptions = true | false | 'skipFirstScreen';\n\nexport type ThemeOptions = 'light' | 'dark' | 'os';\n\nexport type Key =\n | 'lastAuth.loginId'\n | 'idpInitiated'\n | 'externalToken'\n | 'abTestingKey';\n\ntype CheckFunction = (ctx: Context, predicate?: string | number) => boolean;\n\nexport type ConditionsMap = {\n [key in Key]: {\n [operator in Operator]?: CheckFunction;\n };\n};\n\nexport interface Context {\n loginId?: string;\n code?: string;\n token?: string;\n abTestingKey?: number;\n lastAuth?: LastAuthState;\n}\n\nexport type DescopeUI = Record<string, () => Promise<void>> & {\n componentsThemeManager: Record<string, any>;\n};\n\ntype Font = {\n family: string[];\n label: string;\n url?: string;\n};\n\ntype ThemeTemplate = {\n fonts: {\n font1: Font;\n font2: Font;\n };\n};\n\ntype ThemeColor = {\n main: string;\n dark: string;\n light: string;\n highlight: string;\n contrast: string;\n};\n\nexport type OverrideTheme = {\n globals?: {\n colors?: {\n primary?: ThemeColor;\n secondary?: ThemeColor;\n };\n };\n};\n\nexport type OverrideThemes = {\n dark?: OverrideTheme;\n light?: OverrideTheme;\n};\n\nexport type FlowConfig = {\n startScreenId?: string;\n startScreenName?: string;\n version: number;\n targetLocales?: string[];\n conditions?: ClientCondition[];\n condition?: ClientCondition;\n fingerprintEnabled?: boolean;\n fingerprintKey?: string;\n sdkScripts?: [\n {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n },\n ];\n clientScripts?: ClientScript[];\n componentsConfig?: ComponentsConfig;\n};\n\nexport interface ProjectConfiguration {\n componentsVersion: string;\n cssTemplate: {\n dark: ThemeTemplate;\n light: ThemeTemplate;\n };\n flows: {\n [key: string]: FlowConfig; // dynamic key names for flows\n };\n}\n\nexport type FlowStatus = 'loading' | 'error' | 'success' | 'ready' | 'initial';\n\nexport type CustomStorage = {\n getItem: (key: string) => string | null;\n setItem: (key: string, value: string) => void;\n removeItem: (key: string) => void;\n};\n\nexport type FlowJWTResponse = JWTResponse & {\n flowOutput?: Record<string, any>;\n};\n"],"names":["Direction"],"mappings":"aAoCA,IAAYA,EAAAA,QAGXA,eAAA,GAHWA,EAAAA,QAASA,YAATA,kBAGX,CAAA,IAFC,SAAA,WACAA,EAAA,QAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{ASSETS_FOLDER,BASE_CONTENT_URL,CONFIG_FILENAME,OVERRIDE_CONTENT_URL,PREV_VER_ASSETS_FOLDER}from"./content.js";export{UI_COMPONENTS_URL_KEY}from"./uiComponents.js";const t="descope-login-flow",e="t",a="code",d="redirect_mode",
|
|
1
|
+
export{ASSETS_FOLDER,BASE_CONTENT_URL,CONFIG_FILENAME,OVERRIDE_CONTENT_URL,PREV_VER_ASSETS_FOLDER}from"./content.js";export{UI_COMPONENTS_URL_KEY}from"./uiComponents.js";const t="descope-login-flow",e="t",a="code",d="redirect_mode",_="err",i="ra-challenge",o="ra-callback",s="ra-backup-callback",r="ra-initiator",l="data-descope-",p="data-exclude-field",c="data-exclude-next",n="dls_last_auth",u="dls_last_submitted_login_id",m="data-opt-in-last-used-auth",h="state_id",E="saml_idp_state_id",b="wsfed_idp_state_id",g="saml_idp_username",R="descope_idp_initiated",S="sso_app_id",x="custom_app_id",N="third_party_app_id",O="third_party_app_state_id",C="oidc_login_hint",T="oidc_prompt",f="oidc_resource",w="oidc_error_redirect_uri",F="application_scopes",L="data-type",y="sdkScriptsResults",k={redirect:"redirect",poll:"poll",webauthnCreate:"webauthnCreate",webauthnGet:"webauthnGet",nativeBridge:"nativeBridge",loadForm:"loadForm"},A={submit:"submit",polling:"polling"},I="data-has-dynamic-attr-values",U=["descope-multi-select-combo-box","descope-text-area"],v=5e3,B='descope-attachment[data-type="last-auth-badge"]',D="dls_last_auth_in_flight";export{F as APPLICATION_SCOPES_PARAM_NAME,x as CUSTOM_APP_ID_PARAM_NAME,A as CUSTOM_INTERACTIONS,p as DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,c as DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON,m as DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED,l as DESCOPE_ATTRIBUTE_PREFIX,R as DESCOPE_IDP_INITIATED_PARAM_NAME,B as DESCOPE_LAST_AUTH_BADGE_COMPONENT,D as DESCOPE_LAST_AUTH_IN_FLIGHT_LOCAL_STORAGE_KEY,n as DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY,u as DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,U as ELEMENTS_TO_IGNORE_ENTER_KEY_ON,L as ELEMENT_TYPE_ATTRIBUTE,I as HAS_DYNAMIC_VALUES_ATTR_NAME,w as OIDC_ERROR_REDIRECT_URI_PARAM_NAME,h as OIDC_IDP_STATE_ID_PARAM_NAME,C as OIDC_LOGIN_HINT_PARAM_NAME,T as OIDC_PROMPT_PARAM_NAME,f as OIDC_RESOURCE_PARAM_NAME,k as RESPONSE_ACTIONS,E as SAML_IDP_STATE_ID_PARAM_NAME,g as SAML_IDP_USERNAME_PARAM_NAME,v as SDK_SCRIPTS_LOAD_TIMEOUT,y as SDK_SCRIPT_RESULTS_KEY,S as SSO_APP_ID_PARAM_NAME,N as THIRD_PARTY_APP_ID_PARAM_NAME,O as THIRD_PARTY_APP_STATE_ID_PARAM_NAME,a as URL_CODE_PARAM_NAME,_ as URL_ERR_PARAM_NAME,s as URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME,o as URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME,i as URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME,r as URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME,d as URL_REDIRECT_MODE_PARAM_NAME,t as URL_RUN_IDS_PARAM_NAME,e as URL_TOKEN_PARAM_NAME,b as WSFED_IDP_STATE_ID_PARAM_NAME};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/lib/constants/index.ts"],"sourcesContent":["export * from './general';\nexport * from './content';\nexport * from './uiComponents';\n\nexport const URL_RUN_IDS_PARAM_NAME = 'descope-login-flow';\nexport const URL_TOKEN_PARAM_NAME = 't';\nexport const URL_CODE_PARAM_NAME = 'code';\nexport const URL_REDIRECT_MODE_PARAM_NAME = 'redirect_mode';\nexport const URL_ERR_PARAM_NAME = 'err';\nexport const URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME = 'ra-challenge';\nexport const URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME = 'ra-callback';\nexport const URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME =\n 'ra-backup-callback';\nexport const URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME = 'ra-initiator';\nexport const DESCOPE_ATTRIBUTE_PREFIX = 'data-descope-';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_FIELD = 'data-exclude-field';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON = 'data-exclude-next';\nexport const DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY = 'dls_last_auth';\nexport const DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED = 'data-opt-in-last-used-auth';\n\n// SSO query params\nexport const OIDC_IDP_STATE_ID_PARAM_NAME = 'state_id';\nexport const SAML_IDP_STATE_ID_PARAM_NAME = 'saml_idp_state_id';\nexport const WSFED_IDP_STATE_ID_PARAM_NAME = 'wsfed_idp_state_id';\nexport const SAML_IDP_USERNAME_PARAM_NAME = 'saml_idp_username';\nexport const DESCOPE_IDP_INITIATED_PARAM_NAME = 'descope_idp_initiated';\nexport const SSO_APP_ID_PARAM_NAME = 'sso_app_id';\nexport const CUSTOM_APP_ID_PARAM_NAME = 'custom_app_id';\nexport const THIRD_PARTY_APP_ID_PARAM_NAME = 'third_party_app_id';\nexport const THIRD_PARTY_APP_STATE_ID_PARAM_NAME = 'third_party_app_state_id';\nexport const OIDC_LOGIN_HINT_PARAM_NAME = 'oidc_login_hint';\nexport const OIDC_PROMPT_PARAM_NAME = 'oidc_prompt';\nexport const OIDC_RESOURCE_PARAM_NAME = 'oidc_resource';\nexport const OIDC_ERROR_REDIRECT_URI_PARAM_NAME = 'oidc_error_redirect_uri';\nexport const APPLICATION_SCOPES_PARAM_NAME = 'application_scopes';\n\nexport const ELEMENT_TYPE_ATTRIBUTE = 'data-type';\n\nexport const SDK_SCRIPT_RESULTS_KEY = 'sdkScriptsResults';\n\nexport const RESPONSE_ACTIONS = {\n redirect: 'redirect',\n poll: 'poll',\n webauthnCreate: 'webauthnCreate',\n webauthnGet: 'webauthnGet',\n nativeBridge: 'nativeBridge',\n loadForm: 'loadForm',\n};\n\nexport const CUSTOM_INTERACTIONS = {\n submit: 'submit',\n polling: 'polling',\n};\n\nexport const HAS_DYNAMIC_VALUES_ATTR_NAME = 'data-has-dynamic-attr-values';\n\nexport const ELEMENTS_TO_IGNORE_ENTER_KEY_ON = [\n 'descope-multi-select-combo-box',\n 'descope-text-area',\n];\n\nexport const SDK_SCRIPTS_LOAD_TIMEOUT = 5000;\n\nexport const DESCOPE_LAST_AUTH_BADGE_COMPONENT =\n 'descope-attachment[data-type=\"last-auth-badge\"]';\n\nexport const DESCOPE_LAST_AUTH_IN_FLIGHT_LOCAL_STORAGE_KEY =\n 'dls_last_auth_in_flight';\n"],"names":["URL_RUN_IDS_PARAM_NAME","URL_TOKEN_PARAM_NAME","URL_CODE_PARAM_NAME","URL_REDIRECT_MODE_PARAM_NAME","URL_ERR_PARAM_NAME","URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME","URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME","URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME","URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME","DESCOPE_ATTRIBUTE_PREFIX","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON","DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY","DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED","OIDC_IDP_STATE_ID_PARAM_NAME","SAML_IDP_STATE_ID_PARAM_NAME","WSFED_IDP_STATE_ID_PARAM_NAME","SAML_IDP_USERNAME_PARAM_NAME","DESCOPE_IDP_INITIATED_PARAM_NAME","SSO_APP_ID_PARAM_NAME","CUSTOM_APP_ID_PARAM_NAME","THIRD_PARTY_APP_ID_PARAM_NAME","THIRD_PARTY_APP_STATE_ID_PARAM_NAME","OIDC_LOGIN_HINT_PARAM_NAME","OIDC_PROMPT_PARAM_NAME","OIDC_RESOURCE_PARAM_NAME","OIDC_ERROR_REDIRECT_URI_PARAM_NAME","APPLICATION_SCOPES_PARAM_NAME","ELEMENT_TYPE_ATTRIBUTE","SDK_SCRIPT_RESULTS_KEY","RESPONSE_ACTIONS","redirect","poll","webauthnCreate","webauthnGet","nativeBridge","loadForm","CUSTOM_INTERACTIONS","submit","polling","HAS_DYNAMIC_VALUES_ATTR_NAME","ELEMENTS_TO_IGNORE_ENTER_KEY_ON","SDK_SCRIPTS_LOAD_TIMEOUT","DESCOPE_LAST_AUTH_BADGE_COMPONENT","DESCOPE_LAST_AUTH_IN_FLIGHT_LOCAL_STORAGE_KEY"],"mappings":"0KAIO,MAAMA,EAAyB,qBACzBC,EAAuB,IACvBC,EAAsB,OACtBC,EAA+B,gBAC/BC,EAAqB,MACrBC,EAAyC,eACzCC,EAAwC,cACxCC,EACX,qBACWC,EAAyC,eACzCC,EAA2B,gBAC3BC,EAAkC,qBAClCC,EAAwC,oBACxCC,EAAsC,gBACtCC,EAAqC,6BAGrCC,EAA+B,WAC/BC,EAA+B,oBAC/BC,EAAgC,qBAChCC,EAA+B,oBAC/BC,EAAmC,wBACnCC,EAAwB,aACxBC,EAA2B,gBAC3BC,EAAgC,qBAChCC,EAAsC,2BACtCC,EAA6B,kBAC7BC,EAAyB,cACzBC,EAA2B,gBAC3BC,EAAqC,0BACrCC,EAAgC,qBAEhCC,EAAyB,YAEzBC,EAAyB,oBAEzBC,EAAmB,CAC9BC,SAAU,WACVC,KAAM,OACNC,eAAgB,iBAChBC,YAAa,cACbC,aAAc,eACdC,SAAU,YAGCC,EAAsB,CACjCC,OAAQ,SACRC,QAAS,WAGEC,EAA+B,+BAE/BC,EAAkC,CAC7C,iCACA,qBAGWC,EAA2B,IAE3BC,EACX,kDAEWC,EACX"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/lib/constants/index.ts"],"sourcesContent":["export * from './general';\nexport * from './content';\nexport * from './uiComponents';\n\nexport const URL_RUN_IDS_PARAM_NAME = 'descope-login-flow';\nexport const URL_TOKEN_PARAM_NAME = 't';\nexport const URL_CODE_PARAM_NAME = 'code';\nexport const URL_REDIRECT_MODE_PARAM_NAME = 'redirect_mode';\nexport const URL_ERR_PARAM_NAME = 'err';\nexport const URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME = 'ra-challenge';\nexport const URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME = 'ra-callback';\nexport const URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME =\n 'ra-backup-callback';\nexport const URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME = 'ra-initiator';\nexport const DESCOPE_ATTRIBUTE_PREFIX = 'data-descope-';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_FIELD = 'data-exclude-field';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON = 'data-exclude-next';\nexport const DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY = 'dls_last_auth';\nexport const DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY =\n 'dls_last_submitted_login_id';\nexport const DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED = 'data-opt-in-last-used-auth';\n\n// SSO query params\nexport const OIDC_IDP_STATE_ID_PARAM_NAME = 'state_id';\nexport const SAML_IDP_STATE_ID_PARAM_NAME = 'saml_idp_state_id';\nexport const WSFED_IDP_STATE_ID_PARAM_NAME = 'wsfed_idp_state_id';\nexport const SAML_IDP_USERNAME_PARAM_NAME = 'saml_idp_username';\nexport const DESCOPE_IDP_INITIATED_PARAM_NAME = 'descope_idp_initiated';\nexport const SSO_APP_ID_PARAM_NAME = 'sso_app_id';\nexport const CUSTOM_APP_ID_PARAM_NAME = 'custom_app_id';\nexport const THIRD_PARTY_APP_ID_PARAM_NAME = 'third_party_app_id';\nexport const THIRD_PARTY_APP_STATE_ID_PARAM_NAME = 'third_party_app_state_id';\nexport const OIDC_LOGIN_HINT_PARAM_NAME = 'oidc_login_hint';\nexport const OIDC_PROMPT_PARAM_NAME = 'oidc_prompt';\nexport const OIDC_RESOURCE_PARAM_NAME = 'oidc_resource';\nexport const OIDC_ERROR_REDIRECT_URI_PARAM_NAME = 'oidc_error_redirect_uri';\nexport const APPLICATION_SCOPES_PARAM_NAME = 'application_scopes';\n\nexport const ELEMENT_TYPE_ATTRIBUTE = 'data-type';\n\nexport const SDK_SCRIPT_RESULTS_KEY = 'sdkScriptsResults';\n\nexport const RESPONSE_ACTIONS = {\n redirect: 'redirect',\n poll: 'poll',\n webauthnCreate: 'webauthnCreate',\n webauthnGet: 'webauthnGet',\n nativeBridge: 'nativeBridge',\n loadForm: 'loadForm',\n};\n\nexport const CUSTOM_INTERACTIONS = {\n submit: 'submit',\n polling: 'polling',\n};\n\nexport const HAS_DYNAMIC_VALUES_ATTR_NAME = 'data-has-dynamic-attr-values';\n\nexport const ELEMENTS_TO_IGNORE_ENTER_KEY_ON = [\n 'descope-multi-select-combo-box',\n 'descope-text-area',\n];\n\nexport const SDK_SCRIPTS_LOAD_TIMEOUT = 5000;\n\nexport const DESCOPE_LAST_AUTH_BADGE_COMPONENT =\n 'descope-attachment[data-type=\"last-auth-badge\"]';\n\nexport const DESCOPE_LAST_AUTH_IN_FLIGHT_LOCAL_STORAGE_KEY =\n 'dls_last_auth_in_flight';\n"],"names":["URL_RUN_IDS_PARAM_NAME","URL_TOKEN_PARAM_NAME","URL_CODE_PARAM_NAME","URL_REDIRECT_MODE_PARAM_NAME","URL_ERR_PARAM_NAME","URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME","URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME","URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME","URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME","DESCOPE_ATTRIBUTE_PREFIX","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON","DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY","DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY","DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED","OIDC_IDP_STATE_ID_PARAM_NAME","SAML_IDP_STATE_ID_PARAM_NAME","WSFED_IDP_STATE_ID_PARAM_NAME","SAML_IDP_USERNAME_PARAM_NAME","DESCOPE_IDP_INITIATED_PARAM_NAME","SSO_APP_ID_PARAM_NAME","CUSTOM_APP_ID_PARAM_NAME","THIRD_PARTY_APP_ID_PARAM_NAME","THIRD_PARTY_APP_STATE_ID_PARAM_NAME","OIDC_LOGIN_HINT_PARAM_NAME","OIDC_PROMPT_PARAM_NAME","OIDC_RESOURCE_PARAM_NAME","OIDC_ERROR_REDIRECT_URI_PARAM_NAME","APPLICATION_SCOPES_PARAM_NAME","ELEMENT_TYPE_ATTRIBUTE","SDK_SCRIPT_RESULTS_KEY","RESPONSE_ACTIONS","redirect","poll","webauthnCreate","webauthnGet","nativeBridge","loadForm","CUSTOM_INTERACTIONS","submit","polling","HAS_DYNAMIC_VALUES_ATTR_NAME","ELEMENTS_TO_IGNORE_ENTER_KEY_ON","SDK_SCRIPTS_LOAD_TIMEOUT","DESCOPE_LAST_AUTH_BADGE_COMPONENT","DESCOPE_LAST_AUTH_IN_FLIGHT_LOCAL_STORAGE_KEY"],"mappings":"0KAIO,MAAMA,EAAyB,qBACzBC,EAAuB,IACvBC,EAAsB,OACtBC,EAA+B,gBAC/BC,EAAqB,MACrBC,EAAyC,eACzCC,EAAwC,cACxCC,EACX,qBACWC,EAAyC,eACzCC,EAA2B,gBAC3BC,EAAkC,qBAClCC,EAAwC,oBACxCC,EAAsC,gBACtCC,EACX,8BACWC,EAAqC,6BAGrCC,EAA+B,WAC/BC,EAA+B,oBAC/BC,EAAgC,qBAChCC,EAA+B,oBAC/BC,EAAmC,wBACnCC,EAAwB,aACxBC,EAA2B,gBAC3BC,EAAgC,qBAChCC,EAAsC,2BACtCC,EAA6B,kBAC7BC,EAAyB,cACzBC,EAA2B,gBAC3BC,EAAqC,0BACrCC,EAAgC,qBAEhCC,EAAyB,YAEzBC,EAAyB,oBAEzBC,EAAmB,CAC9BC,SAAU,WACVC,KAAM,OACNC,eAAgB,iBAChBC,YAAa,cACbC,aAAc,eACdC,SAAU,YAGCC,EAAsB,CACjCC,OAAQ,SACRC,QAAS,WAGEC,EAA+B,+BAE/BC,EAAkC,CAC7C,iCACA,qBAGWC,EAA2B,IAE3BC,EACX,kDAEWC,EACX"}
|
|
@@ -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{CONFIG_FILENAME as A,PREV_VER_ASSETS_FOLDER as x}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as I}from"../constants/general.js";var j,E,L,M,S,U,O,W,D,P,N,F,K,R,T,B,H,J,V,q,$,z;const Q=r(s,o,k,C,y,n)(HTMLElement);class G extends Q{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(r){super(),j.add(this),L.set(this,!1),M.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,j,"m",z).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)}},S.set(this,new m),U.set(this,new m),O.set(this,{}),this.getComponentsContext=()=>t(this,O,"f"),this.nextRequestStatus=new m({isLoading:!1}),W.set(this,void 0),D.set(this,{popstate:t(this,j,"m",R).bind(this),componentsContext:t(this,j,"m",V).bind(this)}),P.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,P,r,"f"),t(this,j,"m",F).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,M,"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,M,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,U,"f").subscribe(t(this,j,"m",$).bind(this)),t(this,U,"f").update({isDebug:this.debug}),t(this,j,"m",K).call(this),yield t(this,j,"m",H).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,D,"f").popstate),window.addEventListener("components-context",t(this,D,"f").componentsContext),t(this,S,"f").subscribe(t(this,j,"m",B).bind(this)),t(this,S,"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,S,"f").unsubscribeAll(),t(this,U,"f").unsubscribeAll(),t(this,j,"m",q).call(this),window.removeEventListener("popstate",t(this,D,"f").popstate),window.removeEventListener("components-context",t(this,D,"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&&E.observedAttributes.includes(e)){t(this,j,"m",K).call(this);const o=null===i;t(this,S,"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,U,"f").update({isDebug:this.debug})}}}E=G,L=new WeakMap,M=new WeakMap,S=new WeakMap,U=new WeakMap,O=new WeakMap,W=new WeakMap,D=new WeakMap,P=new WeakMap,j=new WeakSet,N=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 ")},F=function(){t(this,j,"m",N).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},K=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"];E.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},R=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,S,"f").update({stepId:e,executionId:i})},T=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},E.sdkConfigOverrides),{projectId:i,baseUrl:r});t(this,M,"f")&&(o.customStorage=t(this,M,"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()}}}}))}))},B=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,j,"m",T).call(this,e,r)}t(this,P,"f").call(this,i)}))},H=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,j,"m",J).call(this))}))},J=function(){return e(this,void 0,void 0,(function*(){const t=f({projectId:this.projectId,filename:A,assetsFolder:x,baseUrl:this.baseStaticUrl});try{return yield g(t,"json"),!0}catch(t){return!1}}))},V=function(e){i(this,O,Object.assign(Object.assign({},t(this,O,"f")),e.detail),"f")},q=function(){var e;null===(e=t(this,W,"f"))||void 0===e||e.remove(),i(this,W,null,"f")},$=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,W,document.createElement("descope-debugger"),"f"),Object.assign(t(this,W,"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,W,"f"))):t(this,j,"m",q).call(this)}))},z=function(e,i){var r;e&&this.debug&&(null===(r=t(this,W,"f"))||void 0===r||r.updateData({title:e,description:i}))},G.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.70.4"}};export{G as default};
|
|
1
|
+
import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as r}from"@descope/sdk-helpers";import{staticResourcesMixin as o}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as s}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{createSdk as 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":"3.70.6"}};export{X 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} 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 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","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":"6yCAoDA,MAAMA,EAAYC,EAChBC,EACAC,EACAC,EACAC,EACAC,EACAC,EANgBN,CAOhBO,aAGF,MAAMC,UAAsBT,EAC1B,6BAAWU,GACT,MAAO,CACL,aACA,UACA,WACA,SACA,SACA,QACA,iBACA,UACA,eACA,aACA,gCACA,sBACA,4CACA,mBACA,WAEH,CA+DD,WAAAC,CAAYC,GACVC,oBAtDFC,EAAAC,IAAAC,MAAQ,GAERC,EAA0CF,IAAAC,UAAA,GAE1CA,KAAUE,WAAe,UAEzBF,KAAAG,cAAgB,CACdC,MAAO,CAACC,EAAiBC,EAAc,MACrCN,KAAKO,OAAOH,MAAMC,EAASC,EAAa,IAAIE,OAC5CC,EAAAT,cAAAU,KAAAV,KAA6BK,EAASC,EAAY,EAEpDK,KAAM,CAACN,EAAiBC,EAAc,MACpCN,KAAKO,OAAOI,KAAKN,EAASC,EAAY,EAExCM,KAAM,CAACP,EAAiBC,EAAc,GAAIO,EAAa,CAAA,KACrDb,KAAKO,OAAOK,KAAKP,EAASC,EAAaO,EAAM,EAE/CC,MAAO,CAACT,EAAiBC,EAAc,MACrCN,KAAKO,OAAOO,MAAMT,EAASC,EAAY,GAI3CS,EAAahB,IAAAC,KAAA,IAAIgB,GAEjBC,EAAclB,IAAAC,KAAA,IAAIgB,GAElBE,EAAAnB,IAAAC,KAAqB,CAAA,GAErBA,KAAAmB,qBAAuB,IAAMV,EAAAT,YAE7BA,KAAiBoB,kBAAG,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ASC,cAC3B,oBAGD,KAEDzB,OAAOC,OAAOhI,EAAAT,KAAiBsB,EAAA,KAACiL,MAAO,CACrCC,SAAU,QACVC,IAAK,IACLC,MAAO,IACPC,OAAQ,QACRC,MAAO,QACPC,cAAe,OACfC,OAAQ,cAIJC,OAAO,qBAEb/C,SAASgD,KAAK5C,YAAY3J,EAAAT,KAAiBsB,EAAA,OAE3Cb,EAAAT,KAAIyB,EAAA,IAAAuH,GAAJtI,KAAAV,QAIoB,EAAAiN,EAAA,SAAAC,EAAe5M,SACjC4M,GAASlN,KAAKc,QACC,QAAjBiC,EAAAtC,EAAAT,KAAiBsB,EAAA,YAAA,IAAAyB,GAAAA,EAAEoK,WAAW,CAAED,QAAO5M,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';\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","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uH,GAAJtI,KAAAV,QAIoB,EAAAiN,EAAA,SAAAC,EAAe5M,SACjC4M,GAASlN,KAAKc,QACC,QAAjBiC,EAAAtC,EAAAT,KAAiBsB,EAAA,YAAA,IAAAyB,GAAAA,EAAEoK,WAAW,CAAED,QAAO5M,gBAC3C,EA5YOb,EAAAmL,mBAAyC,CAC9CwC,YAAa,CACX,qBAAsB,gBACtB,wBAAyB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{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 P,getFirstNonEmptyValue as L,clearPreviousExternalInputs as U}from"../helpers/helpers.js";import F from"../helpers/state.js";import{disableWebauthnButtons as $,updateTemplateFromScreenState as N,setComponentsAutoDetectByGeo as M,setComponentsAutoDetectByLocale as q,setTOTPVariable as V,setNOTPVariable as D,setCssVars as B,updateScreenFromScreenState as K,replaceElementMessage as H}from"../helpers/templates.js";import{isConditionalLoginSupported as _}from"../helpers/webauthn.js";import{getABTestingKey as G}from"../helpers/abTestingKey.js";import{calculateConditions as J,calculateCondition as z}from"../helpers/conditions.js";import{setLastAuth as Q,getInFlightLastUsedPerScreen as X,clearInFlightLastAuth as Y,getLastAuth as Z,updateLastUsedPerScreen as ee}from"../helpers/lastAuth.js";import te from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as ie,FETCH_ERROR_RESPONSE_ERROR_CODE as se,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as oe,FLOW_TIMED_OUT_ERROR_CODE as re,NONCE_VALIDATION_ERROR_CODE as ne,POLLING_STATUS_NOT_FOUND_ERROR_CODE as le}from"../constants/general.js";var 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,Pe,Le,Ue,Fe,$e,Ne,Me,qe,Ve,De,Be,Ke,He,_e,Ge;class Je extends te{static set sdkConfigOverrides(e){te.sdkConfigOverrides=e}static get sdkConfigOverrides(){return te.sdkConfigOverrides}constructor(){const s=new F({deferredRedirect:!1,deferredPolling:!1});super(s.update.bind(s)),ae.add(this),this.stepState=new F({}),de.set(this,void 0),ce.set(this,null),pe.set(this,null),he.set(this,{visibilitychange:e(this,ae,"m",ue).bind(this)}),this.bridgeVersion=2,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,ae,"m",Ce).call(this,i):i()})),We.set(this,((s,o,r,n,d=!1)=>{const c=[re,le,ne];if(this.flowState.current.action===l.poll){if(e(this,Oe,"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,de,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)===ie)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,xe,"f").call(this,g)}))),p),"f")}})),ke.set(this,(()=>{clearTimeout(e(this,de,"f")),t(this,de,null,"f")})),Oe.set(this,(()=>!!window.descopeBridge||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))),xe.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,ae,"m",_e).call(this,"error",(null==i?void 0:i.error)||{errorCode:se,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!==oe&&c!==re&&c!==ne||!this.isRestartOnError||e(this,ae,"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&&Q(Object.assign(Object.assign({},S),{lastUsedPerScreen:X()})),Y(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,ae,"m",_e).call(this,"success",t)}this.storeLastAuthenticatedUser&&Q(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,P=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,pe,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:P})):this.flowState.update({action:y,reqTimestamp:P})})),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)}}))))),Ue.set(this,null),qe.set(this,y(((t,s,o)=>i(this,void 0,void 0,(function*(){var i;if("true"===t.getAttribute("formnovalidate")||e(this,ae,"m",Pe).call(this)){const r=null==t?void 0:t.getAttribute("id");e(this,ae,"m",Be).call(this,t,r,o),e(this,ae,"m",Fe).call(this,t);const n=yield e(this,ae,"m",Le).call(this),l=E(t);this.nextRequestStatus.update({isLoading:!0});const a=Object.assign(Object.assign(Object.assign({},l),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(r,a),this.nextRequestStatus.update({isLoading:!1}),e(this,ae,"m",$e).call(this,n)}}))))),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(){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,ae,"m",be).call(this),window.addEventListener("visibilitychange",e(this,he,"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,ke,"f").call(this),null===(i=e(this,ce,"f"))||void 0===i||i.abort(),t(this,ce,null,"f"),window.removeEventListener("visibilitychange",e(this,he,"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:P,isPopup:L,exchangeError:U,webauthnTransactionId:F,webauthnOptions:$,redirectAuthCodeChallenge:N,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:V,locale:D,samlIdpResponseUrl:B,samlIdpResponseSamlResponse:K,samlIdpResponseRelayState:H,wsFedIdpResponseUrl:_,wsFedIdpResponseWresult:Q,wsFedIdpResponseWctx:X,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 le=G(),{outboundAppId:de}=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=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){Y(this.loggerWrapper);const i=[...ge.clientScripts||[],...ge.sdkScripts||[]];if(ge.conditions){let e=[];({startScreenId:oe,conditionInteractionId:ne,startScreenName:re,clientScripts:e,componentsConfig:Se}=J({loginId:ue,code:P,token:A,abTestingKey:le,lastAuth:Z(ue,this.loggerWrapper)},ge.conditions)),i.push(...e||[])}else ge.condition?({startScreenId:oe,conditionInteractionId:ne}=z(ge.condition,{loginId:ue,code:P,token:A,abTestingKey:le,lastAuth:Z(ue,this.loggerWrapper)})):(re=ge.startScreenName,oe=ge.startScreenId);if(t(this,pe,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:Z(ue,this.loggerWrapper),abTestingKey:le,locale:o(D).locale,nativeOptions:we,outboundAppId:de,outboundAppScopes:he}),ne,"",ve.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),P?{exchangeCode:P,idpInitiated:!0}:{}),se.descopeIdpInitiated&&{idpInitiated:!0}),A?{token:A}:{}),se.oidcLoginHint?{externalId:se.oidcLoginHint}:{}));return e(this,xe,"f").call(this,t),void("completed"!==(null===(h=null==t?void 0:t.data)||void 0===h?void 0:h.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:L,code:P,exchangeError:U,isCodeChanged:p("code"),isExchangeErrorChanged:p("exchangeError")})),L&&(p("code")&&P||p("exchangeError")&&U))return void e(this,ae,"m",Ge).call(this,b,P,U);if(b&&(p("token")&&A||p("code")&&P||p("exchangeError")&&U)){const t=yield this.sdk.flow.next(b,f,a.submit,ge.version,ve.componentsVersion,{token:A,exchangeCode:P,exchangeError:U});return e(this,xe,"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&&_&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>p(e)))){if(!Q)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");C(_,Q,X||"",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,ae,"m",_e).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,ae,"m",_e).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,ce,"f"))||void 0===u||u.abort(),t(this,ce,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,xe,"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,xe,"f").call(this,i)})),e(this,ae,"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:Oe,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:Oe,oidcResource:Ee,action:w,locale:o(D).locale},Te=Z(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,ae,"m",Ve).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:le,client:this.client}),E&&{redirectUrl:E}),{locale:o(D).locale,nativeOptions:we,outboundAppId:de,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)),P&&{exchangeCode:P,idpInitiated:!0}),se.descopeIdpInitiated&&{idpInitiated:!0}),A&&{token:A}),je.next.isCustomScreen);return e(this,xe,"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,ae,"m",Ve).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,xe,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",je.screenId),yield e(this,ae,"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");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,ae,"m",je).call(this,m,p):$(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),N(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),q(m,t.locale);const w=()=>i(this,void 0,void 0,(function*(){var i,o;yield f;const r=this.contentRootElement;V(r,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),D(r,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),B(r,m,h.cssVars,this.loggerWrapper),r.replaceChildren(m);const n=!s.htmlFilename;setTimeout((()=>{e(this,ae,"m",Ne).call(this),this.validateOnBlur&&P(r),K(r,h),this.initRealtimeConditions(r,h),e(this,ae,"m",Te).call(this,{isFirstScreen:n,isCustomScreen:!1,stepName:t.stepName}),O(r,this.autoFocus,n),e(this,ae,"m",Ke).call(this,u)})),e(this,ae,"m",He).call(this,p,u);r.querySelector(`[${v}="polling"]`)&&p(a.polling,{})}));c?e(this,ae,"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}}de=new WeakMap,ce=new WeakMap,pe=new WeakMap,he=new WeakMap,ye=new WeakMap,Re=new WeakMap,We=new WeakMap,ke=new WeakMap,Oe=new WeakMap,xe=new WeakMap,Ee=new WeakMap,Ue=new WeakMap,qe=new WeakMap,ae=new WeakSet,ue=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,ae,"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,ae,"m",me).call(this,"afterScreen",{screen:t})},me=function(t,i){e(this,ae,"m",_e).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)}H(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},be=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,ae,"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,ae,"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})},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=""}))})),O(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=x(a);let c=yield e(this,ae,"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,ae,"m",be).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,ae,"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,ce,"f"))||void 0===r||r.abort();const n=s.querySelector('*[autocomplete="webauthn"]');if(n&&(yield _())){const{options:s,transactionId:r}=(yield e(this,Ee,"f").call(this))||{};s&&r&&(e(this,ae,"m",Ae).call(this,n),t(this,ce,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,ce,"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,ae,"m",_e).call(this,"ready",{}),i||e(this,ae,"m",ve).call(this,s),e(this,ae,"m",_e).call(this,"page-updated",{screenName:s}),e(this,ae,"m",_e).call(this,"screen-updated",{screenName:s})},Pe=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})),{})}))},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,pe,(()=>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())}))},$e=function(e={}){var t,i;const s=L(e,["externalId","email","phone"]),o=L(e,["newPassword","password"]);if(s&&o)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:o});null===(i=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===i||i.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},Ne=function(){U();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,ae,"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)}))},Ve=function(t){return i(this,void 0,void 0,(function*(){if(e(this,pe,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,pe,"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)}}))},De=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,qe,"f").call(this,s,t,i)}))}))},Be=function(e,t,i){t&&i&&"true"===e.getAttribute(m)&&ee(i,t,this.loggerWrapper)},Ke=function(e){var t;const i=this.sdk.getLastUserLoginId(),s=null===(t=Z(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))},He=function(t,i){this.contentRootElement.querySelectorAll(`descope-button:not([${b}]), [data-type="button"]:not([${b}]`).forEach((s=>{s.onclick=()=>{e(this,qe,"f").call(this,s,t,i)}})),e(this,ae,"m",De).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:""})})))}))}))},_e=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},Ge=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{Je 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 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};
|
|
2
2
|
//# sourceMappingURL=DescopeWc.js.map
|