@descope/web-component 4.4.2 → 4.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldGet as n,__classPrivateFieldSet as e,__awaiter as t}from"tslib";import{compose as s}from"@descope/sdk-helpers";import{injectStyleMixin as i}from"@descope/sdk-mixins/inject-style-mixin";import"./constants/content.js";import"./constants/uiComponents.js";import"./types.js";import o from"./helpers/state.js";import"@descope/escape-markdown";import"./helpers/webauthn.js";import{dragElement as l,addOnResize as r,limitCoordinateToScreenBoundaries as a}from"./helpers/positionHelpers.js";var d,c,p,h,m,g,f,x,u,b,v;const w=document.createElement("template");w.innerHTML='\n<div class="debugger">\n <div class="header">\n <span>Debugger messages</span>\n </div>\n <div class="content">\n <div class="empty-state">\n No errors detected 👀\n </div>\n </div>\n</div>\n';const C=s(i)(HTMLElement);class y extends C{constructor(){super(),d.add(this),c.set(this,new o({messages:[]})),p.set(this,void 0),h.set(this,void 0),m.set(this,void 0),g.set(this,{resize:n(this,d,"m",v).bind(this)}),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(w.content.cloneNode(!0)),e(this,p,this.shadowRoot.querySelector(".debugger"),"f"),e(this,h,n(this,p,"f").querySelector(".content"),"f"),e(this,m,n(this,p,"f").querySelector(".header"),"f"),n(this,d,"m",f).call(this)}updateData(e){n(this,c,"f").update((n=>({messages:n.messages.concat(e)})))}init(){const e=Object.create(null,{init:{get:()=>super.init}});return t(this,void 0,void 0,(function*(){var t;null===(t=e.init)||void 0===t||t.call(this),l(n(this,p,"f"),n(this,m,"f"),{top:"all",bottom:100,left:100,right:100}),window.addEventListener("resize",n(this,g,"f").resize),r(n(this,p,"f")),n(this,p,"f").onresize=n(this,d,"m",b).bind(this),n(this,c,"f").subscribe(n(this,d,"m",x).bind(this))}))}disconnectedCallback(){n(this,c,"f").unsubscribeAll(),window.removeEventListener("resize",n(this,g,"f").resize)}}c=new WeakMap,p=new WeakMap,h=new WeakMap,m=new WeakMap,g=new WeakMap,d=new WeakSet,f=function(){this.injectStyle('\n .debugger {\n all: initial;\n width: 300px;\n height: 200px;\n background-color: #FAFAFA;\n position: fixed;\n font-family: "Helvetica Neue", sans-serif;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 5px 10px;\n border-radius: 8px;\n overflow: hidden;\n border: 1px solid lightgrey;\n pointer-events: initial;\n display: flex;\n flex-direction: column;\n min-width: 200px;\n max-width: 600px;\n max-height: calc(100% - 64px);\n min-height: 200px;\n resize: both;\n }\n\n .header {\n padding: 8px 16px;\n display: flex;\n align-items: center;\n background-color: #EEEEEE;\n cursor: move;\n border-bottom: 1px solid #e0e0e0;\n }\n\n .content {\n font-size: 14px;\n flex-grow: 1;\n overflow: auto;\n }\n\n .msg {\n border-bottom: 1px solid lightgrey;\n padding: 8px 16px;\n display: flex;\n gap: 5px;\n background-color: #FAFAFA;\n }\n\n .msg.collapsible {\n cursor: pointer;\n }\n\n .empty-state {\n padding: 8px 16px;\n background-color: #FAFAFA;\n }\n\n\n .msg.collapsible:not(.collapsed) {\n background-color: #F5F5F5;\n }\n\n .msg_title {\n padding-bottom: 5px;\n display: flex;\n gap: 8px;\n font-weight: 500;\n }\n\n .msg svg {\n padding: 1px;\n flex-shrink: 0;\n margin-top: -2px;\n }\n\n .msg_content {\n overflow: hidden;\n flex-grow: 1;\n margin-right:5px;\n }\n\n .msg_desc {\n color: #646464;\n cursor: initial;\n word-wrap: break-word;\n }\n\n .msg.collapsed .msg_desc {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .msg.collapsible.collapsed .chevron {\n transform: rotate(-45deg) translateX(-2px);\n }\n\n .msg.collapsible .chevron {\n content: "";\n width:6px;\n height:6px;\n border-bottom: 2px solid grey;\n border-right: 2px solid grey;\n transform: rotate(45deg) translateX(-1px);\n margin: 5px;\n flex-shrink:0;\n }\n'),n(this,p,"f").style.top="32px",n(this,p,"f").style.left=window.innerWidth-300-32+"px"},x=function(e){n(this,d,"m",u).call(this,e),n(this,d,"m",b).call(this)},u=function(e){n(this,h,"f").innerHTML=e.messages.map((n=>`\n <div class="msg">\n <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M5.99984 13.167L8.99984 10.167L11.9998 13.167L13.1665 12.0003L10.1665 9.00033L13.1665 6.00033L11.9998 4.83366L8.99984 7.83366L5.99984 4.83366L4.83317 6.00033L7.83317 9.00033L4.83317 12.0003L5.99984 13.167ZM8.99984 17.3337C7.84706 17.3337 6.76373 17.1148 5.74984 16.677C4.73595 16.2398 3.854 15.6462 3.104 14.8962C2.354 14.1462 1.76039 13.2642 1.32317 12.2503C0.885393 11.2364 0.666504 10.1531 0.666504 9.00033C0.666504 7.84755 0.885393 6.76421 1.32317 5.75033C1.76039 4.73644 2.354 3.85449 3.104 3.10449C3.854 2.35449 4.73595 1.7606 5.74984 1.32283C6.76373 0.885603 7.84706 0.666992 8.99984 0.666992C10.1526 0.666992 11.2359 0.885603 12.2498 1.32283C13.2637 1.7606 14.1457 2.35449 14.8957 3.10449C15.6457 3.85449 16.2393 4.73644 16.6765 5.75033C17.1143 6.76421 17.3332 7.84755 17.3332 9.00033C17.3332 10.1531 17.1143 11.2364 16.6765 12.2503C16.2393 13.2642 15.6457 14.1462 14.8957 14.8962C14.1457 15.6462 13.2637 16.2398 12.2498 16.677C11.2359 17.1148 10.1526 17.3337 8.99984 17.3337ZM8.99984 15.667C10.8609 15.667 12.4373 15.0212 13.729 13.7295C15.0207 12.4378 15.6665 10.8614 15.6665 9.00033C15.6665 7.13921 15.0207 5.56283 13.729 4.27116C12.4373 2.97949 10.8609 2.33366 8.99984 2.33366C7.13873 2.33366 5.56234 2.97949 4.27067 4.27116C2.979 5.56283 2.33317 7.13921 2.33317 9.00033C2.33317 10.8614 2.979 12.4378 4.27067 13.7295C5.56234 15.0212 7.13873 15.667 8.99984 15.667Z" fill="#ED404A"/>\n</svg>\n\n <div class="msg_content">\n <div class="msg_title">\n ${n.title}\n </div>\n <div class="msg_desc">\n ${n.description}\n </div>\n </div>\n <div class="chevron"></div>\n </div>\n `)).join("")},b=function(){n(this,h,"f").querySelectorAll(".msg").forEach((n=>{const e=n.querySelector(".msg_desc"),t=e.scrollWidth>e.clientWidth,s=e.clientHeight>20;t||s?(n.classList.add("collapsible"),n.onclick=e=>{e.target.classList.contains("msg_desc")||n.classList.toggle("collapsed")}):(n.classList.remove("collapsible"),n.onclick=null)}))},v=function(){const[e,t]=a(n(this,p,"f"),Number.parseInt(n(this,p,"f").style.left,10),Number.parseInt(n(this,p,"f").style.top,10),{top:"all",bottom:100,left:100,right:100});n(this,p,"f").style.top=`${t}px`,n(this,p,"f").style.left=`${e}px`},customElements.get("descope-debugger")||customElements.define("descope-debugger",y);export{y as default};
1
+ import{__classPrivateFieldGet as n,__classPrivateFieldSet as e,__awaiter as t}from"tslib";import{compose as s,escapeHtml as i}from"@descope/sdk-helpers";import{injectStyleMixin as o}from"@descope/sdk-mixins/inject-style-mixin";import"./constants/content.js";import"./constants/uiComponents.js";import"./types.js";import l from"./helpers/state.js";import"@descope/escape-markdown";import"./helpers/webauthn.js";import{dragElement as r,addOnResize as a,limitCoordinateToScreenBoundaries as d}from"./helpers/positionHelpers.js";var c,p,h,m,g,f,x,u,b,v,w;const C=document.createElement("template");C.innerHTML='\n<div class="debugger">\n <div class="header">\n <span>Debugger messages</span>\n </div>\n <div class="content">\n <div class="empty-state">\n No errors detected 👀\n </div>\n </div>\n</div>\n';const y=s(o)(HTMLElement);class L extends y{constructor(){super(),c.add(this),p.set(this,new l({messages:[]})),h.set(this,void 0),m.set(this,void 0),g.set(this,void 0),f.set(this,{resize:n(this,c,"m",w).bind(this)}),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(C.content.cloneNode(!0)),e(this,h,this.shadowRoot.querySelector(".debugger"),"f"),e(this,m,n(this,h,"f").querySelector(".content"),"f"),e(this,g,n(this,h,"f").querySelector(".header"),"f"),n(this,c,"m",x).call(this)}updateData(e){n(this,p,"f").update((n=>({messages:n.messages.concat(e)})))}init(){const e=Object.create(null,{init:{get:()=>super.init}});return t(this,void 0,void 0,(function*(){var t;null===(t=e.init)||void 0===t||t.call(this),r(n(this,h,"f"),n(this,g,"f"),{top:"all",bottom:100,left:100,right:100}),window.addEventListener("resize",n(this,f,"f").resize),a(n(this,h,"f")),n(this,h,"f").onresize=n(this,c,"m",v).bind(this),n(this,p,"f").subscribe(n(this,c,"m",u).bind(this))}))}disconnectedCallback(){n(this,p,"f").unsubscribeAll(),window.removeEventListener("resize",n(this,f,"f").resize)}}p=new WeakMap,h=new WeakMap,m=new WeakMap,g=new WeakMap,f=new WeakMap,c=new WeakSet,x=function(){this.injectStyle('\n .debugger {\n all: initial;\n width: 300px;\n height: 200px;\n background-color: #FAFAFA;\n position: fixed;\n font-family: "Helvetica Neue", sans-serif;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 5px 10px;\n border-radius: 8px;\n overflow: hidden;\n border: 1px solid lightgrey;\n pointer-events: initial;\n display: flex;\n flex-direction: column;\n min-width: 200px;\n max-width: 600px;\n max-height: calc(100% - 64px);\n min-height: 200px;\n resize: both;\n }\n\n .header {\n padding: 8px 16px;\n display: flex;\n align-items: center;\n background-color: #EEEEEE;\n cursor: move;\n border-bottom: 1px solid #e0e0e0;\n }\n\n .content {\n font-size: 14px;\n flex-grow: 1;\n overflow: auto;\n }\n\n .msg {\n border-bottom: 1px solid lightgrey;\n padding: 8px 16px;\n display: flex;\n gap: 5px;\n background-color: #FAFAFA;\n }\n\n .msg.collapsible {\n cursor: pointer;\n }\n\n .empty-state {\n padding: 8px 16px;\n background-color: #FAFAFA;\n }\n\n\n .msg.collapsible:not(.collapsed) {\n background-color: #F5F5F5;\n }\n\n .msg_title {\n padding-bottom: 5px;\n display: flex;\n gap: 8px;\n font-weight: 500;\n }\n\n .msg svg {\n padding: 1px;\n flex-shrink: 0;\n margin-top: -2px;\n }\n\n .msg_content {\n overflow: hidden;\n flex-grow: 1;\n margin-right:5px;\n }\n\n .msg_desc {\n color: #646464;\n cursor: initial;\n word-wrap: break-word;\n }\n\n .msg.collapsed .msg_desc {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .msg.collapsible.collapsed .chevron {\n transform: rotate(-45deg) translateX(-2px);\n }\n\n .msg.collapsible .chevron {\n content: "";\n width:6px;\n height:6px;\n border-bottom: 2px solid grey;\n border-right: 2px solid grey;\n transform: rotate(45deg) translateX(-1px);\n margin: 5px;\n flex-shrink:0;\n }\n'),n(this,h,"f").style.top="32px",n(this,h,"f").style.left=window.innerWidth-300-32+"px"},u=function(e){n(this,c,"m",b).call(this,e),n(this,c,"m",v).call(this)},b=function(e){n(this,m,"f").innerHTML=e.messages.map((n=>`\n <div class="msg">\n <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M5.99984 13.167L8.99984 10.167L11.9998 13.167L13.1665 12.0003L10.1665 9.00033L13.1665 6.00033L11.9998 4.83366L8.99984 7.83366L5.99984 4.83366L4.83317 6.00033L7.83317 9.00033L4.83317 12.0003L5.99984 13.167ZM8.99984 17.3337C7.84706 17.3337 6.76373 17.1148 5.74984 16.677C4.73595 16.2398 3.854 15.6462 3.104 14.8962C2.354 14.1462 1.76039 13.2642 1.32317 12.2503C0.885393 11.2364 0.666504 10.1531 0.666504 9.00033C0.666504 7.84755 0.885393 6.76421 1.32317 5.75033C1.76039 4.73644 2.354 3.85449 3.104 3.10449C3.854 2.35449 4.73595 1.7606 5.74984 1.32283C6.76373 0.885603 7.84706 0.666992 8.99984 0.666992C10.1526 0.666992 11.2359 0.885603 12.2498 1.32283C13.2637 1.7606 14.1457 2.35449 14.8957 3.10449C15.6457 3.85449 16.2393 4.73644 16.6765 5.75033C17.1143 6.76421 17.3332 7.84755 17.3332 9.00033C17.3332 10.1531 17.1143 11.2364 16.6765 12.2503C16.2393 13.2642 15.6457 14.1462 14.8957 14.8962C14.1457 15.6462 13.2637 16.2398 12.2498 16.677C11.2359 17.1148 10.1526 17.3337 8.99984 17.3337ZM8.99984 15.667C10.8609 15.667 12.4373 15.0212 13.729 13.7295C15.0207 12.4378 15.6665 10.8614 15.6665 9.00033C15.6665 7.13921 15.0207 5.56283 13.729 4.27116C12.4373 2.97949 10.8609 2.33366 8.99984 2.33366C7.13873 2.33366 5.56234 2.97949 4.27067 4.27116C2.979 5.56283 2.33317 7.13921 2.33317 9.00033C2.33317 10.8614 2.979 12.4378 4.27067 13.7295C5.56234 15.0212 7.13873 15.667 8.99984 15.667Z" fill="#ED404A"/>\n</svg>\n\n <div class="msg_content">\n <div class="msg_title">\n ${i(n.title)}\n </div>\n <div class="msg_desc">\n ${i(n.description)}\n </div>\n </div>\n <div class="chevron"></div>\n </div>\n `)).join("")},v=function(){n(this,m,"f").querySelectorAll(".msg").forEach((n=>{const e=n.querySelector(".msg_desc"),t=e.scrollWidth>e.clientWidth,s=e.clientHeight>20;t||s?(n.classList.add("collapsible"),n.onclick=e=>{e.target.classList.contains("msg_desc")||n.classList.toggle("collapsed")}):(n.classList.remove("collapsible"),n.onclick=null)}))},w=function(){const[e,t]=d(n(this,h,"f"),Number.parseInt(n(this,h,"f").style.left,10),Number.parseInt(n(this,h,"f").style.top,10),{top:"all",bottom:100,left:100,right:100});n(this,h,"f").style.top=`${t}px`,n(this,h,"f").style.left=`${e}px`},customElements.get("descope-debugger")||customElements.define("descope-debugger",L);export{L as default};
2
2
  //# sourceMappingURL=debugger-wc.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"debugger-wc.js","sources":["../../src/lib/debugger-wc.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport { compose } from '@descope/sdk-helpers';\nimport { injectStyleMixin } from '@descope/sdk-mixins/inject-style-mixin';\nimport {\n addOnResize,\n dragElement,\n limitCoordinateToScreenBoundaries,\n State,\n} from './helpers';\nimport { DebuggerMessage } from './types';\n\nconst INITIAL_POS_THRESHOLD = 32;\nconst INITIAL_WIDTH = 300;\nconst INITIAL_HEIGHT = 200;\nconst MIN_SIZE = 200;\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n<div class=\"debugger\">\n <div class=\"header\">\n <span>Debugger messages</span>\n </div>\n <div class=\"content\">\n <div class=\"empty-state\">\n No errors detected 👀\n </div>\n </div>\n</div>\n`;\n\nconst icon = `<svg width=\"18\" height=\"18\" viewBox=\"0 0 18 18\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path d=\"M5.99984 13.167L8.99984 10.167L11.9998 13.167L13.1665 12.0003L10.1665 9.00033L13.1665 6.00033L11.9998 4.83366L8.99984 7.83366L5.99984 4.83366L4.83317 6.00033L7.83317 9.00033L4.83317 12.0003L5.99984 13.167ZM8.99984 17.3337C7.84706 17.3337 6.76373 17.1148 5.74984 16.677C4.73595 16.2398 3.854 15.6462 3.104 14.8962C2.354 14.1462 1.76039 13.2642 1.32317 12.2503C0.885393 11.2364 0.666504 10.1531 0.666504 9.00033C0.666504 7.84755 0.885393 6.76421 1.32317 5.75033C1.76039 4.73644 2.354 3.85449 3.104 3.10449C3.854 2.35449 4.73595 1.7606 5.74984 1.32283C6.76373 0.885603 7.84706 0.666992 8.99984 0.666992C10.1526 0.666992 11.2359 0.885603 12.2498 1.32283C13.2637 1.7606 14.1457 2.35449 14.8957 3.10449C15.6457 3.85449 16.2393 4.73644 16.6765 5.75033C17.1143 6.76421 17.3332 7.84755 17.3332 9.00033C17.3332 10.1531 17.1143 11.2364 16.6765 12.2503C16.2393 13.2642 15.6457 14.1462 14.8957 14.8962C14.1457 15.6462 13.2637 16.2398 12.2498 16.677C11.2359 17.1148 10.1526 17.3337 8.99984 17.3337ZM8.99984 15.667C10.8609 15.667 12.4373 15.0212 13.729 13.7295C15.0207 12.4378 15.6665 10.8614 15.6665 9.00033C15.6665 7.13921 15.0207 5.56283 13.729 4.27116C12.4373 2.97949 10.8609 2.33366 8.99984 2.33366C7.13873 2.33366 5.56234 2.97949 4.27067 4.27116C2.979 5.56283 2.33317 7.13921 2.33317 9.00033C2.33317 10.8614 2.979 12.4378 4.27067 13.7295C5.56234 15.0212 7.13873 15.667 8.99984 15.667Z\" fill=\"#ED404A\"/>\n</svg>\n`;\n\nconst style = `\n .debugger {\n all: initial;\n width: ${INITIAL_WIDTH}px;\n height: ${INITIAL_HEIGHT}px;\n background-color: #FAFAFA;\n position: fixed;\n font-family: \"Helvetica Neue\", sans-serif;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 5px 10px;\n border-radius: 8px;\n overflow: hidden;\n border: 1px solid lightgrey;\n pointer-events: initial;\n display: flex;\n flex-direction: column;\n min-width: ${MIN_SIZE}px;\n max-width: 600px;\n max-height: calc(100% - ${INITIAL_POS_THRESHOLD * 2}px);\n min-height: ${MIN_SIZE}px;\n resize: both;\n }\n\n .header {\n padding: 8px 16px;\n display: flex;\n align-items: center;\n background-color: #EEEEEE;\n cursor: move;\n border-bottom: 1px solid #e0e0e0;\n }\n\n .content {\n font-size: 14px;\n flex-grow: 1;\n overflow: auto;\n }\n\n .msg {\n border-bottom: 1px solid lightgrey;\n padding: 8px 16px;\n display: flex;\n gap: 5px;\n background-color: #FAFAFA;\n }\n\n .msg.collapsible {\n cursor: pointer;\n }\n\n .empty-state {\n padding: 8px 16px;\n background-color: #FAFAFA;\n }\n\n\n .msg.collapsible:not(.collapsed) {\n background-color: #F5F5F5;\n }\n\n .msg_title {\n padding-bottom: 5px;\n display: flex;\n gap: 8px;\n font-weight: 500;\n }\n\n .msg svg {\n padding: 1px;\n flex-shrink: 0;\n margin-top: -2px;\n }\n\n .msg_content {\n overflow: hidden;\n flex-grow: 1;\n margin-right:5px;\n }\n\n .msg_desc {\n color: #646464;\n cursor: initial;\n word-wrap: break-word;\n }\n\n .msg.collapsed .msg_desc {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .msg.collapsible.collapsed .chevron {\n transform: rotate(-45deg) translateX(-2px);\n }\n\n .msg.collapsible .chevron {\n content: \"\";\n width:6px;\n height:6px;\n border-bottom: 2px solid grey;\n border-right: 2px solid grey;\n transform: rotate(45deg) translateX(-1px);\n margin: 5px;\n flex-shrink:0;\n }\n`;\n\ntype MessagesState = { messages: DebuggerMessage[] };\n\nconst BaseClass = compose(injectStyleMixin)(HTMLElement);\n\nclass Debugger extends BaseClass {\n #messagesState = new State<MessagesState>({ messages: [] });\n\n #rootEle: HTMLDivElement;\n\n #contentEle: HTMLDivElement;\n\n #headerEle: HTMLDivElement;\n\n #eventsCbRefs = {\n resize: this.#onWindowResize.bind(this),\n };\n\n constructor() {\n super();\n\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n\n this.#rootEle = this.shadowRoot.querySelector<HTMLDivElement>('.debugger');\n this.#contentEle = this.#rootEle.querySelector<HTMLDivElement>('.content');\n this.#headerEle = this.#rootEle.querySelector<HTMLDivElement>('.header');\n\n this.#initStyle();\n }\n\n #initStyle() {\n this.injectStyle(style);\n\n this.#rootEle.style.top = `${INITIAL_POS_THRESHOLD}px`;\n this.#rootEle.style.left = `${\n window.innerWidth - INITIAL_WIDTH - INITIAL_POS_THRESHOLD\n }px`;\n }\n\n updateData(data: DebuggerMessage | DebuggerMessage[]) {\n this.#messagesState.update((state) => ({\n messages: state.messages.concat(data),\n }));\n }\n\n #onNewMessages(data: MessagesState) {\n this.#renderMessages(data);\n this.#setCollapsibleMessages();\n }\n\n #renderMessages(data: MessagesState) {\n this.#contentEle.innerHTML = data.messages\n .map(\n (message) => `\n <div class=\"msg\">\n ${icon}\n <div class=\"msg_content\">\n <div class=\"msg_title\">\n ${message.title}\n </div>\n <div class=\"msg_desc\">\n ${message.description}\n </div>\n </div>\n <div class=\"chevron\"></div>\n </div>\n `,\n )\n .join('');\n }\n\n #setCollapsibleMessages() {\n this.#contentEle.querySelectorAll('.msg').forEach((ele: HTMLElement) => {\n const descEle = ele.querySelector('.msg_desc');\n const lineHeight = 20;\n const isScroll = descEle.scrollWidth > descEle.clientWidth;\n const isMultiLine = descEle.clientHeight > lineHeight;\n const isCollapsible = isScroll || isMultiLine;\n\n if (isCollapsible) {\n ele.classList.add('collapsible');\n ele.onclick = (e: MouseEvent) => {\n // message description should not toggle collapse\n if (!(e.target as HTMLElement).classList.contains('msg_desc')) {\n ele.classList.toggle('collapsed');\n }\n };\n } else {\n ele.classList.remove('collapsible');\n ele.onclick = null;\n }\n });\n }\n\n #onWindowResize() {\n // when window is resizing we want to make sure debugger is still visible\n const [left, top] = limitCoordinateToScreenBoundaries(\n this.#rootEle,\n Number.parseInt(this.#rootEle.style.left, 10),\n Number.parseInt(this.#rootEle.style.top, 10),\n { top: 'all', bottom: 100, left: 100, right: 100 },\n );\n this.#rootEle.style.top = `${top}px`;\n this.#rootEle.style.left = `${left}px`;\n }\n\n async init() {\n super.init?.();\n dragElement(this.#rootEle, this.#headerEle, {\n top: 'all',\n bottom: 100,\n left: 100,\n right: 100,\n });\n\n window.addEventListener('resize', this.#eventsCbRefs.resize);\n\n addOnResize(this.#rootEle);\n this.#rootEle.onresize = this.#setCollapsibleMessages.bind(this);\n\n this.#messagesState.subscribe(this.#onNewMessages.bind(this));\n }\n\n disconnectedCallback() {\n this.#messagesState.unsubscribeAll();\n window.removeEventListener('resize', this.#eventsCbRefs.resize);\n }\n}\n\nif (!customElements.get('descope-debugger')) {\n customElements.define('descope-debugger', Debugger);\n}\nexport default Debugger;\n"],"names":["template","document","createElement","innerHTML","BaseClass","compose","injectStyleMixin","HTMLElement","Debugger","constructor","super","_Debugger_messagesState","set","this","State","messages","_Debugger_rootEle","_Debugger_contentEle","_Debugger_headerEle","_Debugger_eventsCbRefs","resize","__classPrivateFieldGet","_Debugger_instances","_Debugger_onWindowResize","bind","attachShadow","mode","shadowRoot","appendChild","content","cloneNode","__classPrivateFieldSet","querySelector","_Debugger_initStyle","call","updateData","data","update","state","concat","init","_a","_super","dragElement","top","bottom","left","right","window","addEventListener","addOnResize","onresize","_Debugger_setCollapsibleMessages","subscribe","_Debugger_onNewMessages","disconnectedCallback","unsubscribeAll","removeEventListener","injectStyle","style","innerWidth","_Debugger_renderMessages","map","message","title","description","join","querySelectorAll","forEach","ele","descEle","isScroll","scrollWidth","clientWidth","isMultiLine","clientHeight","classList","add","onclick","e","target","contains","toggle","remove","limitCoordinateToScreenBoundaries","Number","parseInt","customElements","get","define"],"mappings":"uhBAWA,MAKMA,EAAWC,SAASC,cAAc,YACxCF,EAASG,UAAY,sNAarB,MAiHMC,EAAYC,EAAQC,EAARD,CAA0BE,aAE5C,MAAMC,UAAiBJ,EAarB,WAAAK,GACEC,oBAbFC,EAAiBC,IAAAC,KAAA,IAAIC,EAAqB,CAAEC,SAAU,MAEtDC,EAAyBJ,IAAAC,UAAA,GAEzBI,EAA4BL,IAAAC,UAAA,GAE5BK,EAA2BN,IAAAC,UAAA,GAE3BM,EAAgBP,IAAAC,KAAA,CACdO,OAAQC,EAAAR,KAAIS,EAAA,IAAAC,GAAiBC,KAAKX,QAMlCA,KAAKY,aAAa,CAAEC,KAAM,SAC1Bb,KAAKc,WAAWC,YAAY5B,EAAS6B,QAAQC,WAAU,IAEvDC,EAAAlB,KAAgBG,EAAAH,KAAKc,WAAWK,cAA8B,aAAY,KAC1ED,EAAAlB,KAAmBI,EAAAI,EAAAR,KAAIG,EAAA,KAAUgB,cAA8B,YAAW,KAC1ED,EAAAlB,KAAkBK,EAAAG,EAAAR,KAAIG,EAAA,KAAUgB,cAA8B,WAAU,KAExEX,EAAAR,KAAIS,EAAA,IAAAW,GAAJC,KAAArB,KACD,CAWD,UAAAsB,CAAWC,GACTf,EAAAR,KAAmBF,EAAA,KAAC0B,QAAQC,IAAW,CACrCvB,SAAUuB,EAAMvB,SAASwB,OAAOH,MAEnC,CA+DK,IAAAI,0GACM,QAAVC,EAAAC,EAAMF,YAAI,IAAAC,GAAAA,EAAAP,KAAArB,MACV8B,EAAYtB,EAAAR,KAAIG,EAAA,KAAWK,EAAAR,YAAiB,CAC1C+B,IAAK,MACLC,OAAQ,IACRC,KAAM,IACNC,MAAO,MAGTC,OAAOC,iBAAiB,SAAU5B,EAAAR,KAAkBM,EAAA,KAACC,QAErD8B,EAAY7B,EAAAR,KAAIG,EAAA,MAChBK,EAAAR,KAAIG,EAAA,KAAUmC,SAAW9B,EAAAR,KAAIS,EAAA,IAAA8B,GAAyB5B,KAAKX,MAE3DQ,EAAAR,KAAIF,EAAA,KAAgB0C,UAAUhC,EAAAR,KAAmBS,EAAA,IAAAgC,GAAC9B,KAAKX,SACxD,CAED,oBAAA0C,GACElC,EAAAR,KAAIF,EAAA,KAAgB6C,iBACpBR,OAAOS,oBAAoB,SAAUpC,EAAAR,KAAkBM,EAAA,KAACC,OACzD,mGA/FCP,KAAK6C,YAzIK,07DA2IVrC,EAAAR,KAAaG,EAAA,KAAC2C,MAAMf,IAAM,OAC1BvB,EAAAR,KAAaG,EAAA,KAAC2C,MAAMb,KAClBE,OAAOY,WApKS,IADQ,GAoKC,IAG7B,aAQexB,GACbf,EAAAR,KAAoBS,EAAA,IAAAuC,GAAA3B,KAApBrB,KAAqBuB,GACrBf,EAAAR,KAAIS,EAAA,IAAA8B,GAAJlB,KAAArB,KACF,aAEgBuB,GACdf,EAAAR,KAAgBI,EAAA,KAACd,UAAYiC,EAAKrB,SAC/B+C,KACEC,GAAY,qlDAKTA,EAAQC,oEAGRD,EAAQE,iGAObC,KAAK,GACV,EAACd,EAAA,WAGC/B,EAAAR,KAAII,EAAA,KAAakD,iBAAiB,QAAQC,SAASC,IACjD,MAAMC,EAAUD,EAAIrC,cAAc,aAE5BuC,EAAWD,EAAQE,YAAcF,EAAQG,YACzCC,EAAcJ,EAAQK,aAFT,GAGGJ,GAAYG,GAGhCL,EAAIO,UAAUC,IAAI,eAClBR,EAAIS,QAAWC,IAEPA,EAAEC,OAAuBJ,UAAUK,SAAS,aAChDZ,EAAIO,UAAUM,OAAO,YACtB,IAGHb,EAAIO,UAAUO,OAAO,eACrBd,EAAIS,QAAU,KACf,GAEL,EAACvD,EAAA,WAIC,MAAOuB,EAAMF,GAAOwC,EAClB/D,EAAAR,KAAaG,EAAA,KACbqE,OAAOC,SAASjE,EAAAR,KAAaG,EAAA,KAAC2C,MAAMb,KAAM,IAC1CuC,OAAOC,SAASjE,EAAAR,KAAIG,EAAA,KAAU2C,MAAMf,IAAK,IACzC,CAAEA,IAAK,MAAOC,OAAQ,IAAKC,KAAM,IAAKC,MAAO,MAE/C1B,EAAAR,KAAaG,EAAA,KAAC2C,MAAMf,IAAM,GAAGA,MAC7BvB,EAAAR,KAAaG,EAAA,KAAC2C,MAAMb,KAAO,GAAGA,KAChC,EAyBGyC,eAAeC,IAAI,qBACtBD,eAAeE,OAAO,mBAAoBjF"}
1
+ {"version":3,"file":"debugger-wc.js","sources":["../../src/lib/debugger-wc.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport { compose, escapeHtml } from '@descope/sdk-helpers';\nimport { injectStyleMixin } from '@descope/sdk-mixins/inject-style-mixin';\nimport {\n addOnResize,\n dragElement,\n limitCoordinateToScreenBoundaries,\n State,\n} from './helpers';\nimport { DebuggerMessage } from './types';\n\nconst INITIAL_POS_THRESHOLD = 32;\nconst INITIAL_WIDTH = 300;\nconst INITIAL_HEIGHT = 200;\nconst MIN_SIZE = 200;\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n<div class=\"debugger\">\n <div class=\"header\">\n <span>Debugger messages</span>\n </div>\n <div class=\"content\">\n <div class=\"empty-state\">\n No errors detected 👀\n </div>\n </div>\n</div>\n`;\n\nconst icon = `<svg width=\"18\" height=\"18\" viewBox=\"0 0 18 18\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path d=\"M5.99984 13.167L8.99984 10.167L11.9998 13.167L13.1665 12.0003L10.1665 9.00033L13.1665 6.00033L11.9998 4.83366L8.99984 7.83366L5.99984 4.83366L4.83317 6.00033L7.83317 9.00033L4.83317 12.0003L5.99984 13.167ZM8.99984 17.3337C7.84706 17.3337 6.76373 17.1148 5.74984 16.677C4.73595 16.2398 3.854 15.6462 3.104 14.8962C2.354 14.1462 1.76039 13.2642 1.32317 12.2503C0.885393 11.2364 0.666504 10.1531 0.666504 9.00033C0.666504 7.84755 0.885393 6.76421 1.32317 5.75033C1.76039 4.73644 2.354 3.85449 3.104 3.10449C3.854 2.35449 4.73595 1.7606 5.74984 1.32283C6.76373 0.885603 7.84706 0.666992 8.99984 0.666992C10.1526 0.666992 11.2359 0.885603 12.2498 1.32283C13.2637 1.7606 14.1457 2.35449 14.8957 3.10449C15.6457 3.85449 16.2393 4.73644 16.6765 5.75033C17.1143 6.76421 17.3332 7.84755 17.3332 9.00033C17.3332 10.1531 17.1143 11.2364 16.6765 12.2503C16.2393 13.2642 15.6457 14.1462 14.8957 14.8962C14.1457 15.6462 13.2637 16.2398 12.2498 16.677C11.2359 17.1148 10.1526 17.3337 8.99984 17.3337ZM8.99984 15.667C10.8609 15.667 12.4373 15.0212 13.729 13.7295C15.0207 12.4378 15.6665 10.8614 15.6665 9.00033C15.6665 7.13921 15.0207 5.56283 13.729 4.27116C12.4373 2.97949 10.8609 2.33366 8.99984 2.33366C7.13873 2.33366 5.56234 2.97949 4.27067 4.27116C2.979 5.56283 2.33317 7.13921 2.33317 9.00033C2.33317 10.8614 2.979 12.4378 4.27067 13.7295C5.56234 15.0212 7.13873 15.667 8.99984 15.667Z\" fill=\"#ED404A\"/>\n</svg>\n`;\n\nconst style = `\n .debugger {\n all: initial;\n width: ${INITIAL_WIDTH}px;\n height: ${INITIAL_HEIGHT}px;\n background-color: #FAFAFA;\n position: fixed;\n font-family: \"Helvetica Neue\", sans-serif;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 5px 10px;\n border-radius: 8px;\n overflow: hidden;\n border: 1px solid lightgrey;\n pointer-events: initial;\n display: flex;\n flex-direction: column;\n min-width: ${MIN_SIZE}px;\n max-width: 600px;\n max-height: calc(100% - ${INITIAL_POS_THRESHOLD * 2}px);\n min-height: ${MIN_SIZE}px;\n resize: both;\n }\n\n .header {\n padding: 8px 16px;\n display: flex;\n align-items: center;\n background-color: #EEEEEE;\n cursor: move;\n border-bottom: 1px solid #e0e0e0;\n }\n\n .content {\n font-size: 14px;\n flex-grow: 1;\n overflow: auto;\n }\n\n .msg {\n border-bottom: 1px solid lightgrey;\n padding: 8px 16px;\n display: flex;\n gap: 5px;\n background-color: #FAFAFA;\n }\n\n .msg.collapsible {\n cursor: pointer;\n }\n\n .empty-state {\n padding: 8px 16px;\n background-color: #FAFAFA;\n }\n\n\n .msg.collapsible:not(.collapsed) {\n background-color: #F5F5F5;\n }\n\n .msg_title {\n padding-bottom: 5px;\n display: flex;\n gap: 8px;\n font-weight: 500;\n }\n\n .msg svg {\n padding: 1px;\n flex-shrink: 0;\n margin-top: -2px;\n }\n\n .msg_content {\n overflow: hidden;\n flex-grow: 1;\n margin-right:5px;\n }\n\n .msg_desc {\n color: #646464;\n cursor: initial;\n word-wrap: break-word;\n }\n\n .msg.collapsed .msg_desc {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .msg.collapsible.collapsed .chevron {\n transform: rotate(-45deg) translateX(-2px);\n }\n\n .msg.collapsible .chevron {\n content: \"\";\n width:6px;\n height:6px;\n border-bottom: 2px solid grey;\n border-right: 2px solid grey;\n transform: rotate(45deg) translateX(-1px);\n margin: 5px;\n flex-shrink:0;\n }\n`;\n\ntype MessagesState = { messages: DebuggerMessage[] };\n\nconst BaseClass = compose(injectStyleMixin)(HTMLElement);\n\nclass Debugger extends BaseClass {\n #messagesState = new State<MessagesState>({ messages: [] });\n\n #rootEle: HTMLDivElement;\n\n #contentEle: HTMLDivElement;\n\n #headerEle: HTMLDivElement;\n\n #eventsCbRefs = {\n resize: this.#onWindowResize.bind(this),\n };\n\n constructor() {\n super();\n\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n\n this.#rootEle = this.shadowRoot.querySelector<HTMLDivElement>('.debugger');\n this.#contentEle = this.#rootEle.querySelector<HTMLDivElement>('.content');\n this.#headerEle = this.#rootEle.querySelector<HTMLDivElement>('.header');\n\n this.#initStyle();\n }\n\n #initStyle() {\n this.injectStyle(style);\n\n this.#rootEle.style.top = `${INITIAL_POS_THRESHOLD}px`;\n this.#rootEle.style.left = `${\n window.innerWidth - INITIAL_WIDTH - INITIAL_POS_THRESHOLD\n }px`;\n }\n\n updateData(data: DebuggerMessage | DebuggerMessage[]) {\n this.#messagesState.update((state) => ({\n messages: state.messages.concat(data),\n }));\n }\n\n #onNewMessages(data: MessagesState) {\n this.#renderMessages(data);\n this.#setCollapsibleMessages();\n }\n\n #renderMessages(data: MessagesState) {\n this.#contentEle.innerHTML = data.messages\n .map(\n (message) => `\n <div class=\"msg\">\n ${icon}\n <div class=\"msg_content\">\n <div class=\"msg_title\">\n ${escapeHtml(message.title)}\n </div>\n <div class=\"msg_desc\">\n ${escapeHtml(message.description)}\n </div>\n </div>\n <div class=\"chevron\"></div>\n </div>\n `,\n )\n .join('');\n }\n\n #setCollapsibleMessages() {\n this.#contentEle.querySelectorAll('.msg').forEach((ele: HTMLElement) => {\n const descEle = ele.querySelector('.msg_desc');\n const lineHeight = 20;\n const isScroll = descEle.scrollWidth > descEle.clientWidth;\n const isMultiLine = descEle.clientHeight > lineHeight;\n const isCollapsible = isScroll || isMultiLine;\n\n if (isCollapsible) {\n ele.classList.add('collapsible');\n ele.onclick = (e: MouseEvent) => {\n // message description should not toggle collapse\n if (!(e.target as HTMLElement).classList.contains('msg_desc')) {\n ele.classList.toggle('collapsed');\n }\n };\n } else {\n ele.classList.remove('collapsible');\n ele.onclick = null;\n }\n });\n }\n\n #onWindowResize() {\n // when window is resizing we want to make sure debugger is still visible\n const [left, top] = limitCoordinateToScreenBoundaries(\n this.#rootEle,\n Number.parseInt(this.#rootEle.style.left, 10),\n Number.parseInt(this.#rootEle.style.top, 10),\n { top: 'all', bottom: 100, left: 100, right: 100 },\n );\n this.#rootEle.style.top = `${top}px`;\n this.#rootEle.style.left = `${left}px`;\n }\n\n async init() {\n super.init?.();\n dragElement(this.#rootEle, this.#headerEle, {\n top: 'all',\n bottom: 100,\n left: 100,\n right: 100,\n });\n\n window.addEventListener('resize', this.#eventsCbRefs.resize);\n\n addOnResize(this.#rootEle);\n this.#rootEle.onresize = this.#setCollapsibleMessages.bind(this);\n\n this.#messagesState.subscribe(this.#onNewMessages.bind(this));\n }\n\n disconnectedCallback() {\n this.#messagesState.unsubscribeAll();\n window.removeEventListener('resize', this.#eventsCbRefs.resize);\n }\n}\n\nif (!customElements.get('descope-debugger')) {\n customElements.define('descope-debugger', Debugger);\n}\nexport default Debugger;\n"],"names":["template","document","createElement","innerHTML","BaseClass","compose","injectStyleMixin","HTMLElement","Debugger","constructor","super","_Debugger_messagesState","set","this","State","messages","_Debugger_rootEle","_Debugger_contentEle","_Debugger_headerEle","_Debugger_eventsCbRefs","resize","__classPrivateFieldGet","_Debugger_instances","_Debugger_onWindowResize","bind","attachShadow","mode","shadowRoot","appendChild","content","cloneNode","__classPrivateFieldSet","querySelector","_Debugger_initStyle","call","updateData","data","update","state","concat","init","_a","_super","dragElement","top","bottom","left","right","window","addEventListener","addOnResize","onresize","_Debugger_setCollapsibleMessages","subscribe","_Debugger_onNewMessages","disconnectedCallback","unsubscribeAll","removeEventListener","injectStyle","style","innerWidth","_Debugger_renderMessages","map","message","escapeHtml","title","description","join","querySelectorAll","forEach","ele","descEle","isScroll","scrollWidth","clientWidth","isMultiLine","clientHeight","classList","add","onclick","e","target","contains","toggle","remove","limitCoordinateToScreenBoundaries","Number","parseInt","customElements","get","define"],"mappings":"uiBAWA,MAKMA,EAAWC,SAASC,cAAc,YACxCF,EAASG,UAAY,sNAarB,MAiHMC,EAAYC,EAAQC,EAARD,CAA0BE,aAE5C,MAAMC,UAAiBJ,EAarB,WAAAK,GACEC,oBAbFC,EAAiBC,IAAAC,KAAA,IAAIC,EAAqB,CAAEC,SAAU,MAEtDC,EAAyBJ,IAAAC,UAAA,GAEzBI,EAA4BL,IAAAC,UAAA,GAE5BK,EAA2BN,IAAAC,UAAA,GAE3BM,EAAgBP,IAAAC,KAAA,CACdO,OAAQC,EAAAR,KAAIS,EAAA,IAAAC,GAAiBC,KAAKX,QAMlCA,KAAKY,aAAa,CAAEC,KAAM,SAC1Bb,KAAKc,WAAWC,YAAY5B,EAAS6B,QAAQC,WAAU,IAEvDC,EAAAlB,KAAgBG,EAAAH,KAAKc,WAAWK,cAA8B,aAAY,KAC1ED,EAAAlB,KAAmBI,EAAAI,EAAAR,KAAIG,EAAA,KAAUgB,cAA8B,YAAW,KAC1ED,EAAAlB,KAAkBK,EAAAG,EAAAR,KAAIG,EAAA,KAAUgB,cAA8B,WAAU,KAExEX,EAAAR,KAAIS,EAAA,IAAAW,GAAJC,KAAArB,KACD,CAWD,UAAAsB,CAAWC,GACTf,EAAAR,KAAmBF,EAAA,KAAC0B,QAAQC,IAAW,CACrCvB,SAAUuB,EAAMvB,SAASwB,OAAOH,MAEnC,CA+DK,IAAAI,0GACM,QAAVC,EAAAC,EAAMF,YAAI,IAAAC,GAAAA,EAAAP,KAAArB,MACV8B,EAAYtB,EAAAR,KAAIG,EAAA,KAAWK,EAAAR,YAAiB,CAC1C+B,IAAK,MACLC,OAAQ,IACRC,KAAM,IACNC,MAAO,MAGTC,OAAOC,iBAAiB,SAAU5B,EAAAR,KAAkBM,EAAA,KAACC,QAErD8B,EAAY7B,EAAAR,KAAIG,EAAA,MAChBK,EAAAR,KAAIG,EAAA,KAAUmC,SAAW9B,EAAAR,KAAIS,EAAA,IAAA8B,GAAyB5B,KAAKX,MAE3DQ,EAAAR,KAAIF,EAAA,KAAgB0C,UAAUhC,EAAAR,KAAmBS,EAAA,IAAAgC,GAAC9B,KAAKX,SACxD,CAED,oBAAA0C,GACElC,EAAAR,KAAIF,EAAA,KAAgB6C,iBACpBR,OAAOS,oBAAoB,SAAUpC,EAAAR,KAAkBM,EAAA,KAACC,OACzD,mGA/FCP,KAAK6C,YAzIK,07DA2IVrC,EAAAR,KAAaG,EAAA,KAAC2C,MAAMf,IAAM,OAC1BvB,EAAAR,KAAaG,EAAA,KAAC2C,MAAMb,KAClBE,OAAOY,WApKS,IADQ,GAoKC,IAG7B,aAQexB,GACbf,EAAAR,KAAoBS,EAAA,IAAAuC,GAAA3B,KAApBrB,KAAqBuB,GACrBf,EAAAR,KAAIS,EAAA,IAAA8B,GAAJlB,KAAArB,KACF,aAEgBuB,GACdf,EAAAR,KAAgBI,EAAA,KAACd,UAAYiC,EAAKrB,SAC/B+C,KACEC,GAAY,qlDAKTC,EAAWD,EAAQE,qEAGnBD,EAAWD,EAAQG,kGAOxBC,KAAK,GACV,EAACf,EAAA,WAGC/B,EAAAR,KAAII,EAAA,KAAamD,iBAAiB,QAAQC,SAASC,IACjD,MAAMC,EAAUD,EAAItC,cAAc,aAE5BwC,EAAWD,EAAQE,YAAcF,EAAQG,YACzCC,EAAcJ,EAAQK,aAFT,GAGGJ,GAAYG,GAGhCL,EAAIO,UAAUC,IAAI,eAClBR,EAAIS,QAAWC,IAEPA,EAAEC,OAAuBJ,UAAUK,SAAS,aAChDZ,EAAIO,UAAUM,OAAO,YACtB,IAGHb,EAAIO,UAAUO,OAAO,eACrBd,EAAIS,QAAU,KACf,GAEL,EAACxD,EAAA,WAIC,MAAOuB,EAAMF,GAAOyC,EAClBhE,EAAAR,KAAaG,EAAA,KACbsE,OAAOC,SAASlE,EAAAR,KAAaG,EAAA,KAAC2C,MAAMb,KAAM,IAC1CwC,OAAOC,SAASlE,EAAAR,KAAIG,EAAA,KAAU2C,MAAMf,IAAK,IACzC,CAAEA,IAAK,MAAOC,OAAQ,IAAKC,KAAM,IAAKC,MAAO,MAE/C1B,EAAAR,KAAaG,EAAA,KAAC2C,MAAMf,IAAM,GAAGA,MAC7BvB,EAAAR,KAAaG,EAAA,KAAC2C,MAAMb,KAAO,GAAGA,KAChC,EAyBG0C,eAAeC,IAAI,qBACtBD,eAAeE,OAAO,mBAAoBlF"}
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as s}from"@descope/sdk-helpers";import{staticResourcesMixin as r}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as o}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{telemetryMixin as a}from"@descope/sdk-mixins/telemetry-mixin";import{createSdk as u,getSessionToken as l}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as d}from"../constants/index.js";import{handleUrlParams as h,clearRunIdsFromUrl as c,camelCase as f,getRunIdsFromUrl as g,getContentUrl as p,fetchContent as m,withRetry as v}from"../helpers/helpers.js";import b from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as w}from"../helpers/storage.js";import{transformFlowInputFormData as k,extractNestedAttribute as y}from"../helpers/flowInputs.js";import{formMountMixin as C}from"../mixins/formMountMixin.js";import{componentConditionsMixin as x}from"../mixins/componentConditionsMixin.js";import{duplicateFlowWarningMixin as A}from"../mixins/duplicateFlowWarningMixin.js";import{passwordManagerMixin as j}from"../mixins/passwordManagerMixin.js";import{validationTrackingMixin as I}from"../mixins/validationTrackingMixin.js";import{CONFIG_FILENAME as E,PREV_VER_ASSETS_FOLDER as M}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as S}from"../constants/general.js";var L,U,O,W,P,D,N,T,F,K,R,z,J,V,B,H,q,$,Q,G,X,Y,Z,_,tt,et;const it=s(o,r,C,x,A,j,n,a,I)(HTMLElement);class st extends it{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","send-session-token","style-id"]}constructor(s){super(),L.add(this),this.sdkVersion="4.4.2",O.set(this,!1),W.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,L,"m",et).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)}},P.set(this,new b),D.set(this,new b),N.set(this,{}),this.getComponentsContext=()=>t(this,N,"f"),this.nextRequestStatus=new b({isLoading:!1}),T.set(this,void 0),F.set(this,{popstate:t(this,L,"m",V).bind(this),componentsContext:t(this,L,"m",G).bind(this)}),K.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),X.set(this,void 0),Y.set(this,void 0),i(this,K,s,"f"),t(this,L,"m",z).call(this)}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get sendSessionToken(){return"true"===this.getAttribute("send-session-token")}get preview(){return!!this.getAttribute("preview")}get formConfig(){return k(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return y(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,W,"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,W,t,"f"),w(t)}get lazyStart(){return"true"===this.getAttribute("lazy-start")}start(){var e;null===(e=t(this,Y,"f"))||void 0===e||e.call(this),i(this,X,Promise.resolve(),"f")}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(),s=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=s.version)&&void 0!==e||(s.version=0),s}))}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,s;const r=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),o=d.includes(null!==(s=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==s?s:"");if("Enter"!==t.key||r||o)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const a=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===a.length)return void a[0].click();const u=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===u.length)"false"!==u[0].getAttribute("auto-submit")&&u[0].click();else if(0===u.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const s=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=s.init)||void 0===e?void 0:e.call(this),t(this,D,"f").subscribe(t(this,L,"m",tt).bind(this)),t(this,D,"f").update({isDebug:this.debug}),t(this,L,"m",J).call(this),yield t(this,L,"m",$).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 r=yield this.getConfig();if("isMissingConfig"in r&&r.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:o,stepId:n,token:a,code:u,isPopup:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=h(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,F,"f").popstate),window.addEventListener("components-context",t(this,F,"f").componentsContext),t(this,P,"f").subscribe(t(this,L,"m",q).bind(this)),t(this,P,"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:o,token:a,code:u,isPopup:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,O,!0,"f")}))}disconnectedCallback(){var e;t(this,P,"f").unsubscribeAll(),t(this,D,"f").unsubscribeAll(),t(this,L,"m",_).call(this),window.removeEventListener("popstate",t(this,F,"f").popstate),window.removeEventListener("components-context",t(this,F,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,s){var r;if(null===(r=super.attributeChangedCallback)||void 0===r||r.call(this,e,i,s),this.shadowRoot.isConnected&&t(this,O,"f")&&i!==s&&U.observedAttributes.includes(e)){t(this,L,"m",J).call(this);const r=null===i;t(this,P,"f").update((({stepId:t,executionId:i})=>{let o=t,n=i;return r||(n=null,o=null,c()),{[f(e)]:s,stepId:o,executionId:n}})),t(this,D,"f").update({isDebug:this.debug})}}}U=st,O=new WeakMap,W=new WeakMap,P=new WeakMap,D=new WeakMap,N=new WeakMap,T=new WeakMap,F=new WeakMap,K=new WeakMap,X=new WeakMap,Y=new WeakMap,L=new WeakSet,R=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 ")},z=function(){t(this,L,"m",R).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},J=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","send-session-token","style-id","outbound-app-id","outbound-app-scopes","theme-override"];U.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[f(e)])throw Error(`${e} cannot be empty`)}))},V=function(){const{stepId:e,executionId:i}=g(this.flowId);t(this,P,"f").update({stepId:e,executionId:i})},B=function(i,s){u&&"function"==typeof u||this.logger.error("SDK was not loaded properly",u,JSON.stringify(u));const r=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},U.sdkConfigOverrides),{projectId:i,baseUrl:s});t(this,W,"f")&&(r.customStorage=t(this,W,"f")),this.sdk=u(r);const o={start:1,next:7};["start","next"].forEach((i=>{const s=this.sdk.flow[i],r=v(s,1e3,3);this.sdk.flow[i]=(...s)=>e(this,void 0,void 0,(function*(){const e=[...s],n=o[i],a=t(this,L,"m",H).call(this,e[n]);void 0!==a&&(e[n]=a);try{return yield r(...e)}catch(t){return this.logger.error(`Error in sdk flow ${i} function`,t),{error:{errorCode:S,errorDescription:t.toString()}}}}))}));const n=this.sdk.flow.start;this.sdk.flow.start=(...i)=>e(this,void 0,void 0,(function*(){return yield t(this,L,"m",Z).call(this),n.apply(this.sdk.flow,i)}))},H=function(t){if(!this.sendSessionToken)return t;const e=null==l?void 0:l(this.storagePrefix);return e?Object.assign(Object.assign({},null!=t?t:{}),{sessionJwt:e}):t},q=function(i,s,r){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:s}=i;if(r("projectId")||r("baseUrl")){if(!e)return;t(this,L,"m",B).call(this,e,s)}t(this,K,"f").call(this,i)}))},$=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,L,"m",Q).call(this))}))},Q=function(){return e(this,void 0,void 0,(function*(){const t=p({projectId:this.projectId,filename:E,assetsFolder:M,baseUrl:this.baseStaticUrl});try{return yield m(t,"json"),!0}catch(t){return!1}}))},G=function(e){i(this,N,Object.assign(Object.assign({},t(this,N,"f")),e.detail),"f")},Z=function(){return this.lazyStart?(t(this,X,"f")||i(this,X,new Promise((t=>{i(this,Y,t,"f")})),"f"),t(this,X,"f")):Promise.resolve()},_=function(){var e;null===(e=t(this,T,"f"))||void 0===e||e.remove(),i(this,T,null,"f")},tt=function(s){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,T,document.createElement("descope-debugger"),"f"),Object.assign(t(this,T,"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,T,"f"))):t(this,L,"m",_).call(this)}))},et=function(e,i){var s;e&&this.debug&&(null===(s=t(this,T,"f"))||void 0===s||s.updateData({title:e,description:i}))},st.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.4.2"}};export{st as default};
1
+ import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as s}from"@descope/sdk-helpers";import{staticResourcesMixin as r}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as o}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{telemetryMixin as a}from"@descope/sdk-mixins/telemetry-mixin";import{createSdk as u,getSessionToken as l}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as d}from"../constants/index.js";import{handleUrlParams as h,clearRunIdsFromUrl as c,camelCase as f,getRunIdsFromUrl as g,getContentUrl as p,fetchContent as m,withRetry as v}from"../helpers/helpers.js";import b from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as w}from"../helpers/storage.js";import{transformFlowInputFormData as k,extractNestedAttribute as y}from"../helpers/flowInputs.js";import{formMountMixin as C}from"../mixins/formMountMixin.js";import{componentConditionsMixin as x}from"../mixins/componentConditionsMixin.js";import{duplicateFlowWarningMixin as A}from"../mixins/duplicateFlowWarningMixin.js";import{passwordManagerMixin as j}from"../mixins/passwordManagerMixin.js";import{validationTrackingMixin as I}from"../mixins/validationTrackingMixin.js";import{CONFIG_FILENAME as E,PREV_VER_ASSETS_FOLDER as M}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as S}from"../constants/general.js";var L,U,O,W,P,D,N,T,F,K,R,z,J,V,B,H,q,$,Q,G,X,Y,Z,_,tt,et;const it=s(o,r,C,x,A,j,n,a,I)(HTMLElement);class st extends it{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","send-session-token","style-id"]}constructor(s){super(),L.add(this),this.sdkVersion="4.4.4",O.set(this,!1),W.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,L,"m",et).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)}},P.set(this,new b),D.set(this,new b),N.set(this,{}),this.getComponentsContext=()=>t(this,N,"f"),this.nextRequestStatus=new b({isLoading:!1}),T.set(this,void 0),F.set(this,{popstate:t(this,L,"m",V).bind(this),componentsContext:t(this,L,"m",G).bind(this)}),K.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),X.set(this,void 0),Y.set(this,void 0),i(this,K,s,"f"),t(this,L,"m",z).call(this)}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get sendSessionToken(){return"true"===this.getAttribute("send-session-token")}get preview(){return!!this.getAttribute("preview")}get formConfig(){return k(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return y(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,W,"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,W,t,"f"),w(t)}get lazyStart(){return"true"===this.getAttribute("lazy-start")}start(){var e;null===(e=t(this,Y,"f"))||void 0===e||e.call(this),i(this,X,Promise.resolve(),"f")}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(),s=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=s.version)&&void 0!==e||(s.version=0),s}))}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,s;const r=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),o=d.includes(null!==(s=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==s?s:"");if("Enter"!==t.key||r||o)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const a=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===a.length)return void a[0].click();const u=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===u.length)"false"!==u[0].getAttribute("auto-submit")&&u[0].click();else if(0===u.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const s=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=s.init)||void 0===e?void 0:e.call(this),t(this,D,"f").subscribe(t(this,L,"m",tt).bind(this)),t(this,D,"f").update({isDebug:this.debug}),t(this,L,"m",J).call(this),yield t(this,L,"m",$).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 r=yield this.getConfig();if("isMissingConfig"in r&&r.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:o,stepId:n,token:a,code:u,isPopup:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=h(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,F,"f").popstate),window.addEventListener("components-context",t(this,F,"f").componentsContext),t(this,P,"f").subscribe(t(this,L,"m",q).bind(this)),t(this,P,"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:o,token:a,code:u,isPopup:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,O,!0,"f")}))}disconnectedCallback(){var e;t(this,P,"f").unsubscribeAll(),t(this,D,"f").unsubscribeAll(),t(this,L,"m",_).call(this),window.removeEventListener("popstate",t(this,F,"f").popstate),window.removeEventListener("components-context",t(this,F,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,s){var r;if(null===(r=super.attributeChangedCallback)||void 0===r||r.call(this,e,i,s),this.shadowRoot.isConnected&&t(this,O,"f")&&i!==s&&U.observedAttributes.includes(e)){t(this,L,"m",J).call(this);const r=null===i;t(this,P,"f").update((({stepId:t,executionId:i})=>{let o=t,n=i;return r||(n=null,o=null,c()),{[f(e)]:s,stepId:o,executionId:n}})),t(this,D,"f").update({isDebug:this.debug})}}}U=st,O=new WeakMap,W=new WeakMap,P=new WeakMap,D=new WeakMap,N=new WeakMap,T=new WeakMap,F=new WeakMap,K=new WeakMap,X=new WeakMap,Y=new WeakMap,L=new WeakSet,R=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 ")},z=function(){t(this,L,"m",R).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},J=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","send-session-token","style-id","outbound-app-id","outbound-app-scopes","theme-override"];U.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[f(e)])throw Error(`${e} cannot be empty`)}))},V=function(){const{stepId:e,executionId:i}=g(this.flowId);t(this,P,"f").update({stepId:e,executionId:i})},B=function(i,s){u&&"function"==typeof u||this.logger.error("SDK was not loaded properly",u,JSON.stringify(u));const r=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},U.sdkConfigOverrides),{projectId:i,baseUrl:s});t(this,W,"f")&&(r.customStorage=t(this,W,"f")),this.sdk=u(r);const o={start:1,next:7};["start","next"].forEach((i=>{const s=this.sdk.flow[i],r=v(s,1e3,3);this.sdk.flow[i]=(...s)=>e(this,void 0,void 0,(function*(){const e=[...s],n=o[i],a=t(this,L,"m",H).call(this,e[n]);void 0!==a&&(e[n]=a);try{return yield r(...e)}catch(t){return this.logger.error(`Error in sdk flow ${i} function`,t),{error:{errorCode:S,errorDescription:t.toString()}}}}))}));const n=this.sdk.flow.start;this.sdk.flow.start=(...i)=>e(this,void 0,void 0,(function*(){return yield t(this,L,"m",Z).call(this),n.apply(this.sdk.flow,i)}))},H=function(t){if(!this.sendSessionToken)return t;const e=null==l?void 0:l(this.storagePrefix);return e?Object.assign(Object.assign({},null!=t?t:{}),{sessionJwt:e}):t},q=function(i,s,r){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:s}=i;if(r("projectId")||r("baseUrl")){if(!e)return;t(this,L,"m",B).call(this,e,s)}t(this,K,"f").call(this,i)}))},$=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,L,"m",Q).call(this))}))},Q=function(){return e(this,void 0,void 0,(function*(){const t=p({projectId:this.projectId,filename:E,assetsFolder:M,baseUrl:this.baseStaticUrl});try{return yield m(t,"json"),!0}catch(t){return!1}}))},G=function(e){i(this,N,Object.assign(Object.assign({},t(this,N,"f")),e.detail),"f")},Z=function(){return this.lazyStart?(t(this,X,"f")||i(this,X,new Promise((t=>{i(this,Y,t,"f")})),"f"),t(this,X,"f")):Promise.resolve()},_=function(){var e;null===(e=t(this,T,"f"))||void 0===e||e.remove(),i(this,T,null,"f")},tt=function(s){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,T,document.createElement("descope-debugger"),"f"),Object.assign(t(this,T,"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,T,"f"))):t(this,L,"m",_).call(this)}))},et=function(e,i){var s;e&&this.debug&&(null===(s=t(this,T,"f"))||void 0===s||s.updateData({title:e,description:i}))},st.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.4.4"}};export{st as default};
2
2
  //# sourceMappingURL=BaseDescopeWc.js.map
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{getUserLocale as o}from"@descope/sdk-helpers";import{ensureFingerprintIds as n,clearFingerprintData as r}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,WEBAUTHN_TIMEOUT as v,ELEMENT_TYPE_ATTRIBUTE as m,DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED as f,DESCOPE_LAST_AUTH_BADGE_COMPONENT as b,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as w}from"../constants/index.js";import{timeoutPromise as S,withMemCache as y,leadingDebounce as I,showFirstScreenOnExecutionInit as k,injectSamlIdpForm as R,injectWsFedIdpForm as C,openCenteredPopup as W,getAnimationDirection as x,handleAutoFocus as E,transformStepStateForCustomScreen as O,getElementDescopeAttributes as A,getScriptResultPath as j,submitForm as T,transformScreenInputs as L,handleReportValidityOnBlur as U,clearPreviousExternalInputs as P}from"../helpers/helpers.js";import F from"../helpers/state.js";import{disableWebauthnButtons as N,updateTemplateFromScreenState as $,setComponentsAutoDetectByGeo as M,setComponentsAutoDetectByLocale as V,setTOTPVariable as q,setNOTPVariable as D,setCssVars as B,updateScreenFromScreenState as _,replaceElementMessage as K}from"../helpers/templates.js";import{isConditionalLoginSupported as H}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 ne,NONCE_VALIDATION_ERROR_CODE as re,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,ke,Re,Ce,We,xe,Ee,Oe,Ae,je,Te,Le,Ue,Pe,Fe,Ne,$e,Me,Ve,qe,De,Be,_e,Ke,He,Ge,Je,ze,Qe,Xe,Ye;const Ze="__descope_webauthn_timed_out__";class et 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=et.bridgeVersion,ge.set(this,void 0),this.nativeCallbacks={},Ie.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},Ce.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",We).call(this,i):i()})),xe.set(this,((s,o,n,r,d=!1)=>{const c=[ne,le,re];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,n,r,{}),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 S(e,h)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,xe,"f").call(this,s,o,n,r,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,xe,"f").call(this,s,o,n,r);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,xe,"f").call(this,s,o,n,r),e(this,Ae,"f").call(this,g)}))),p),"f")}})),Ee.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))),Ae.set(this,(i=>{var s,o,n,r,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===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,ae,"m",Xe).call(this,"error",(null==i?void 0:i.error)||{errorCode:se,errorDescription:l,errorMessage:t}),this.loggerWrapper.error((null===(r=null==i?void 0:i.error)||void 0===r?void 0:r.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!==ne&&c!==re||!this.isRestartOnError||e(this,ae,"m",ye).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,Ee,"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),this.setValidationTrackingExecution(i.data.executionId),void e(this,ae,"m",Xe).call(this,"success",t)}this.storeLastAuthenticatedUser&&Q(S,!0),I&&window.open(I,"_blank");const{executionId:k,stepId:R,stepName:C,screen:W,redirect:x,webauthn:E,error:O,samlIdpResponse:A,wsFedIdpResponse:j,nativeResponse:T}=i.data,L=Date.now();y!==l.poll?(this.loggerWrapper.info(`Step "${C||`#${R}`}" is ${b}`,"",{screen:W,status:b,stepId:R,stepName:C,action:y,error:O}),(null===(m=W.state)||void 0===m?void 0:m.clientScripts)&&t(this,pe,this.loadSdkScripts(W.state.clientScripts),"f"),this.flowState.update({stepId:R,stepName:C,executionId:k,action:y,redirectTo:null==x?void 0:x.url,redirectIsPopup:null==x?void 0:x.isPopup,screenId:null==W?void 0:W.id,screenState:null==W?void 0:W.state,webauthnTransactionId:null==E?void 0:E.transactionId,webauthnOptions:null==E?void 0:E.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,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})})),je.set(this,y((()=>i(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),Pe.set(this,void 0),Fe.set(this,void 0),qe.set(this,null),Ke.set(this,I(((t,s,o)=>i(this,void 0,void 0,(function*(){var i,n;if("true"===t.getAttribute("formnovalidate")||e(this,ae,"m",Me).call(this)){const r=null==t?void 0:t.getAttribute("id");e(this,ae,"m",Je).call(this,t,r,o),e(this,ae,"m",De).call(this,t);const l=yield e(this,ae,"m",Ve).call(this),a=A(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(r,d);this.nextRequestStatus.update({isLoading:!1}),this.captureLastSubmittedLoginId(l,null===(n=null==c?void 0:c.data)||void 0===n?void 0:n.executionId),this.storeCredentials(l)}}))))),this.flowState=s,this.setValidationTrackingSender(((e,t)=>i(this,[e,t],void 0,(function*({executionId:e,events:t},{keepalive:i}){const s=yield this.sdk.flow.event(e,t,i);return{ok:s.ok,retryable:s.code>=500||429===s.code}}))))}nativeResume(t,i){var s,o,n,r,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===(r=(n=this.nativeCallbacks).complete)||void 0===r||r.call(n,{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,Ee,"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:{[j(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 n=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(n){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=n;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.19",`dist/${e.id}.js`));const r=null===(o=globalThis.descope)||void 0===o?void 0:o[e.id];return new Promise(((i,s)=>{try{const s=r(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 o=this.nextRequestStatus.subscribe((()=>{var i;this.loggerWrapper.debug("Stopping script",e.id),(null===(i=s.stop)||void 0===i?void 0:i.call(s))&&(this.nextRequestStatus.unsubscribe(o),this.loggerWrapper.debug("Removing script",e.id),this.shadowRoot.removeChild(t))}));"function"==typeof s.present&&i(e.id)}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),u)}));return Promise.race([s,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){var e,i;if(!window.descopeBridge)return this._init();this.lazyInit=this._init,t(this,ge,null===(i=null===(e=null===window||void 0===window?void 0:window.descopeBridge)||void 0===e?void 0:e.registerFlow)||void 0===i?void 0:i.call(e,this),"f")}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,ae,"m",we).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,s,o;super.disconnectedCallback(),this.teardownValidationTracking(),e(this,ge,"f")&&(null===(s=null===(i=window.descopeBridge)||void 0===i?void 0:i.unregisterFlow)||void 0===s||s.call(i,e(this,ge,"f")),t(this,ge,void 0,"f")),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,Ee,"f").call(this),null===(o=e(this,ce,"f"))||void 0===o||o.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),n=yield this.getTargetLocales();return n.includes(s.locale)?i=`${t}-${s.locale}.html`:n.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:I,redirectIsPopup:E,redirectUrl:O,token:A,code:j,isPopup:U,exchangeError:P,webauthnTransactionId:F,webauthnOptions:N,redirectAuthCodeChallenge:$,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:V,redirectAuthInitiator:q,locale:D,samlIdpResponseUrl:B,samlIdpResponseSamlResponse:_,samlIdpResponseRelayState:K,wsFedIdpResponseUrl:H,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,ne,re;const le=G(),{outboundAppId:de,outboundAppScopes:he}=this,ue=this.sdk.getLastUserLoginId();p("flowId")&&this.setValidationTrackingEnabled(!1);const ge=yield this.getFlowConfig();e(this,ae,"m",Ne).call(this,ge,b,p);const ve=yield this.getProjectConfig(),me=Object.entries(ve.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),be=M&&$?{callbackUrl:M,codeChallenge:$,backupCallbackUri:V}: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:re,startScreenName:ne,clientScripts:e,componentsConfig:Se}=J({loginId:ue,code:j,token:A,abTestingKey:le,lastAuth:Z(ue,this.loggerWrapper)},ge.conditions)),i.push(...e||[])}else ge.condition?({startScreenId:oe,startScreenName:ne,conditionInteractionId:re}=z(ge.condition,{loginId:ue,code:j,token:A,abTestingKey:le,lastAuth:Z(ue,this.loggerWrapper)})):(ne=ge.startScreenName,oe=ge.startScreenId);if(t(this,Pe,oe,"f"),t(this,Fe,ne,"f"),t(this,pe,this.loadSdkScripts(i),"f"),ge.fingerprintEnabled&&ge.fingerprintKey?yield n(ge.fingerprintKey,this.baseUrl):r(),!k(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}),O&&{redirectUrl:O}),{lastAuth:Z(ue,this.loggerWrapper),abTestingKey:le,locale:o(D).locale,nativeOptions:we,outboundAppId:de,outboundAppScopes:he}),re,"",ve.componentsVersion,me,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),j?{exchangeCode:j,idpInitiated:!0}:{}),se.descopeIdpInitiated&&{idpInitiated:!0}),A?{token:A}:{}),se.oidcLoginHint?{externalId:se.oidcLoginHint}:{}));return e(this,Ae,"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:j,exchangeError:P,isCodeChanged:p("code"),isExchangeErrorChanged:p("exchangeError")})),U&&(p("code")&&j||p("exchangeError")&&P))return void e(this,ae,"m",Ye).call(this,b,j,P);if(b&&(p("token")&&A||p("code")&&j||p("exchangeError")&&P)){const t=yield this.sdk.flow.next(b,f,a.submit,ge.version,ve.componentsVersion,{token:A,exchangeCode:j,exchangeError:P});return e(this,Ae,"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(!_)return void this.loggerWrapper.error("Did not get saml idp params data to load");R(B,_,K||"",T)}if(w===l.loadForm&&H&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>p(e)))){if(!Q)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");C(H,Q,X||"",T)}if(w===l.redirect&&(p("redirectTo")||p("deferredRedirect"))){if(!I)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===I)return;if("android"===q&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${E}`),E){this.loggerWrapper.debug("Opening redirect in popup");const t=W(I,"?",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:n}=e.data||{};"code"===o&&(s=!0,this.flowState.update({code:n.code,exchangeError:n.exchangeError}))};let n;this.loggerWrapper.debug("Starting popup closed detection");const r=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(r),e(this,ae,"m",Xe).call(this,"popupclosed",{abandoned:!s}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==n||n())}),1e3);if(i)window.addEventListener("message",o),n=()=>{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,n=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(I),this.flowState.update({redirectTo:"no-op"}),e(this,ae,"m",Xe).call(this,"popupclosed",{});return}if(w===l.webauthnCreate||w===l.webauthnGet){if(!F||!N)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");null===(u=e(this,ce,"f"))||void 0===u||u.abort(),t(this,ce,null,"f");const i=yield e(this,ae,"m",Re).call(this,w,N),s=yield this.sdk.flow.next(b,f,a.submit,ge.version,ve.componentsVersion,Object.assign({transactionId:F},i));e(this,Ae,"f").call(this,s)}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,Ae,"f").call(this,i)})),e(this,ae,"m",fe).call(this,ee,te),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if((p("action")||p("deferredPolling"))&&e(this,xe,"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,Ie=yield this.getHtmlFilenameWithLocale(D,ye),{oidcLoginHint:Ce,oidcPrompt:We,oidcErrorRedirectUri:Ee,oidcResource:Oe,samlIdpUsername:je}=se,Te={direction:x(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:Ie,screenId:ye,stepName:d.stepName||ne,samlIdpUsername:je,oidcLoginHint:Ce,oidcPrompt:We,oidcErrorRedirectUri:Ee,oidcResource:Oe,action:w,locale:o(D).locale},Le=Z(ue,this.loggerWrapper);k(oe,se)?Te.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ge?void 0:ge.clientScripts)||[];yield e(this,ae,"m",He).call(this,i);const n=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:be},se),{lastAuth:Le,preview:this.preview,abTestingKey:le,client:this.client}),O&&{redirectUrl:O}),{locale:o(D).locale,nativeOptions:we,outboundAppId:de,outboundAppScopes:he}),re,t,ve.componentsVersion,me,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),L(s)),j&&{exchangeCode:j,idpInitiated:!0}),se.descopeIdpInitiated&&{idpInitiated:!0}),A&&{token:A}),Te.next.isCustomScreen);return e(this,Ae,"f").call(this,n),n})):(p("projectId")||p("baseUrl")||p("executionId")||p("stepId"))&&(Te.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==y?void 0:y.clientScripts)||[];yield e(this,ae,"m",He).call(this,i);const o=yield this.sdk.flow.next(b,f,t,ge.version,ve.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),L(s)),Te.next.isCustomScreen);return e(this,Ae,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",Te.screenId),yield e(this,ae,"m",ke).call(this,Te),this.stepState.update(Te)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n,r;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 v=g.content.cloneNode(!0),f=this.loadDescopeUiComponents(g);this.sdk.webauthn.helpers.isSupported()?yield e(this,ae,"m",Le).call(this,v,p):N(v),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(n=h.form)||void 0===n?void 0:n.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),$(v,h,this.formConfig,this.loggerWrapper),this.applyComponentsState(v,null==h?void 0:h.componentsState);const{geo:b}=null!==(r=yield this.getExecutionContext())&&void 0!==r?r:{};M(v,b),V(v,t.locale);const w=()=>i(this,void 0,void 0,(function*(){var i,o;yield f;const n=this.contentRootElement;q(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),D(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),B(n,v,h.cssVars,this.loggerWrapper),n.replaceChildren(v);const r=!s.htmlFilename;setTimeout((()=>{e(this,ae,"m",Be).call(this),this.updateUsernameAnchor(),this.validateOnBlur&&U(n,(t=>this.trackValidationErrors([t],e(this,ae,"a",$e)))),_(n,h),this.initRealtimeConditions(n,h),e(this,ae,"m",Ue).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),E(n,this.autoFocus,r),e(this,ae,"m",ze).call(this,u)})),e(this,ae,"m",Qe).call(this,p,u);n.querySelector(`[${m}="polling"]`)&&p(a.polling,{})}));c?e(this,ae,"m",We).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,ge=new WeakMap,Ie=new WeakMap,Ce=new WeakMap,xe=new WeakMap,Ee=new WeakMap,Oe=new WeakMap,Ae=new WeakMap,je=new WeakMap,Pe=new WeakMap,Fe=new WeakMap,qe=new WeakMap,Ke=new WeakMap,ae=new WeakSet,ue=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1,deferredPolling:!1})}),300)},ve=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",fe).call(this,"beforeScreen",{screen:t,context:s})}))}))},me=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,ae,"m",fe).call(this,"afterScreen",{screen:t})},fe=function(t,i){e(this,ae,"m",Xe).call(this,"bridge",{type:t,payload:i})},be=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()},we=function(){var t,i,o,n;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",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}),null===(o=this.stepState)||void 0===o||o.subscribe(e(this,ae,"m",Se).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===(n=this.flowState)||void 0===n||n.subscribe((({screenId:e,executionId:t})=>{var i;try{this.updateTelemetryContext({screenId:e,executionId:t})}catch(e){null===(i=this.logger)||void 0===i||i.error("Error updating telemetry screenId:",e)}}),(e=>({screenId:e.screenId,executionId:e.executionId})))},Se=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=""}))})),E(this.contentRootElement,this.autoFocus,!1))},ye=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")}))},ke=function(o){return i(this,void 0,void 0,(function*(){var i;const n=Object.assign(Object.assign({},this.stepState.current),o),{next:r,stepName:l}=n,a=s(n,["next","stepName"]),d=O(a);let c=yield e(this,ae,"m",ve).call(this,l,d,r);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,l,d,r,this)));const p=!this.stepState.current.htmlFilename;if(e(this,Ce,"f").call(this,c),r&&(r.isCustomScreen=c),e(this,Ie,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,Ie,c,"f"),c?this.stepState.unsubscribeAll():e(this,ae,"m",we).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,ae,"m",Ue).call(this,{isFirstScreen:p,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},Re=function(e,t){return i(this,void 0,void 0,(function*(){const i=new AbortController;try{const s=e===l.webauthnCreate?this.sdk.webauthn.helpers.create(t,i):this.sdk.webauthn.helpers.get(t,i),o=yield S(v,s,Ze);return o!==Ze?{response:o}:(i.abort(),this.loggerWrapper.warn(`WebAuthn operation timed out after ${v}ms`),{failure:"AbortError",failureReason:"aborted",failureMessage:"Passkey operation timed out"})}catch(e){return"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),{failure:e.name,failureReason:e.reason,failureMessage:e.message}}}))},We=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")},Te=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)}))}},Le=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,ce,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield H())){const{options:s,transactionId:n}=(yield e(this,je,"f").call(this))||{};s&&n&&(e(this,ae,"m",Te).call(this,r),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(r.id,{transactionId:n,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},Ue=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,ae,"m",Xe).call(this,"ready",{}),i||e(this,ae,"m",me).call(this,s),e(this,ae,"m",Xe).call(this,"page-updated",{screenName:s}),e(this,ae,"m",Xe).call(this,"screen-updated",{screenName:s})},Ne=function(e,t,i){this.setValidationTrackingEnabled(!!e.clientValidationTrackingEnabled),t&&i("executionId")&&this.setValidationTrackingExecution(t)},$e=function(){var t,i,s,o,n,r,l;const a=null===(t=this.flowState)||void 0===t?void 0:t.current;return(null==a?void 0:a.executionId)?{executionId:a.executionId,screenId:a.screenId,screenName:(null===(l=null===(r=this.stepState)||void 0===r?void 0:r.current)||void 0===l?void 0:l.stepName)||a.stepName}:{executionId:void 0,screenId:null!==(i=e(this,Pe,"f"))&&void 0!==i?i:null==a?void 0:a.screenId,screenName:null!==(s=e(this,Fe,"f"))&&void 0!==s?s:(null===(n=null===(o=this.stepState)||void 0===o?void 0:o.current)||void 0===n?void 0:n.stepName)||(null==a?void 0:a.stepName)}},Me=function(){let t=!0;const i=[];return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((e=>{var s,o;"slot"===e.localName||e.classList.contains("hidden")||(null===(s=e.reportValidity)||void 0===s||s.call(e),e.validity&&!e.validity.valid&&i.push(e),t&&(t=null===(o=e.checkValidity)||void 0===o?void 0:o.call(e)))})),i.length&&this.trackValidationErrors(i,e(this,ae,"a",$e)),t},Ve=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})),{})}))},De=function(s){var o,n;const r=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),l=(null===(n=null===(o=this.flowState.current)||void 0===o?void 0:o.screenState)||void 0===n?void 0:n.clientScripts)||[],a=()=>{s.removeAttribute("loading"),r.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(),n=[...o.clientScripts||[],...o.sdkScripts||[]];this.loadSdkScripts(n)})),c=()=>{var i;window.removeEventListener("pageshow",e(this,qe,"f")),t(this,qe,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),d())}),"f"),window.addEventListener("pageshow",e(this,qe,"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"),r.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(p),"success"===this.flowStatus?(this.removeEventListener("popupclosed",d),a()):c())}))},Be=function(){P();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,ae,"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)}))},He=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 S(u,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},Ge=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,Ke,"f").call(this,s,t,i)}))}))},Je=function(e,t,i){t&&i&&"true"===e.getAttribute(f)&&ee(i,t,this.loggerWrapper)},ze=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(b),n=this.contentRootElement.querySelector(`#${CSS.escape(s)}`);o&&n&&(n.replaceWith(o),o.appendChild(n))},Qe=function(t,i){this.contentRootElement.querySelectorAll(`descope-button:not([${w}]), [data-type="button"]:not([${w}]`).forEach((s=>{s.onclick=()=>{e(this,Ke,"f").call(this,s,t,i)}})),e(this,ae,"m",Ge).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:""})})))}))}))},Xe=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},Ye=function(e,t,i){var s;const[o,n]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],r={data:{code:t,exchangeError:i},action:"code"};if("descope-wc"===o&&n){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",n);try{window.opener.postMessage(r,n)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(r),t.close()}try{window.close()}catch(e){}},et.bridgeVersion=3;export{et 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 n,clearFingerprintData as r}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,WEBAUTHN_TIMEOUT as v,ELEMENT_TYPE_ATTRIBUTE as m,DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED as f,DESCOPE_LAST_AUTH_BADGE_COMPONENT as b,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as w}from"../constants/index.js";import{timeoutPromise as S,withMemCache as y,leadingDebounce as I,showFirstScreenOnExecutionInit as k,injectSamlIdpForm as R,injectWsFedIdpForm as W,openCenteredPopup as C,getAnimationDirection as x,handleAutoFocus as E,transformStepStateForCustomScreen as O,getElementDescopeAttributes as A,getScriptResultPath as j,submitForm as T,transformScreenInputs as L,handleReportValidityOnBlur as U,clearPreviousExternalInputs as P}from"../helpers/helpers.js";import F from"../helpers/state.js";import{disableWebauthnButtons as N,updateTemplateFromScreenState as $,setComponentsAutoDetectByGeo as M,setComponentsAutoDetectByLocale as V,setTOTPVariable as q,setNOTPVariable as D,setCssVars as B,updateScreenFromScreenState as _,replaceElementMessage as K}from"../helpers/templates.js";import{isConditionalLoginSupported as H}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 ne,NONCE_VALIDATION_ERROR_CODE as re,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,ke,Re,We,Ce,xe,Ee,Oe,Ae,je,Te,Le,Ue,Pe,Fe,Ne,$e,Me,Ve,qe,De,Be,_e,Ke,He,Ge,Je,ze,Qe,Xe,Ye;const Ze="__descope_webauthn_timed_out__";class et 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=et.bridgeVersion,ge.set(this,void 0),this.nativeCallbacks={},Ie.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},We.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()})),xe.set(this,((s,o,n,r,d=!1)=>{const c=[ne,le,re];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,n,r,{}),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 S(e,h)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,xe,"f").call(this,s,o,n,r,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,xe,"f").call(this,s,o,n,r);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,xe,"f").call(this,s,o,n,r),e(this,Ae,"f").call(this,g)}))),p),"f")}})),Ee.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))),Ae.set(this,(i=>{var s,o,n,r,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===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,ae,"m",Xe).call(this,"error",(null==i?void 0:i.error)||{errorCode:se,errorDescription:l,errorMessage:t}),this.loggerWrapper.error((null===(r=null==i?void 0:i.error)||void 0===r?void 0:r.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!==ne&&c!==re||!this.isRestartOnError||e(this,ae,"m",ye).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,Ee,"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),this.setValidationTrackingExecution(i.data.executionId),void e(this,ae,"m",Xe).call(this,"success",t)}this.storeLastAuthenticatedUser&&Q(S,!0),I&&window.open(I,"_blank");const{executionId:k,stepId:R,stepName:W,screen:C,redirect:x,webauthn:E,error:O,samlIdpResponse:A,wsFedIdpResponse:j,nativeResponse:T}=i.data,L=Date.now();y!==l.poll?(this.loggerWrapper.info(`Step "${W||`#${R}`}" is ${b}`,"",{screen:C,status:b,stepId:R,stepName:W,action:y,error:O}),(null===(m=C.state)||void 0===m?void 0:m.clientScripts)&&t(this,pe,this.loadSdkScripts(C.state.clientScripts),"f"),this.flowState.update({stepId:R,stepName:W,executionId:k,action:y,redirectTo:null==x?void 0:x.url,redirectIsPopup:null==x?void 0:x.isPopup,screenId:null==C?void 0:C.id,screenState:null==C?void 0:C.state,webauthnTransactionId:null==E?void 0:E.transactionId,webauthnOptions:null==E?void 0:E.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,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})})),je.set(this,y((()=>i(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),Pe.set(this,void 0),Fe.set(this,void 0),qe.set(this,null),Ke.set(this,I(((t,s,o)=>i(this,void 0,void 0,(function*(){var i,n;if("true"!==t.getAttribute("loading")&&"true"!==t.getAttribute("disabled")){if("true"===t.getAttribute("formnovalidate")||e(this,ae,"m",Me).call(this)){const r=null==t?void 0:t.getAttribute("id");e(this,ae,"m",Je).call(this,t,r,o);const l=e(this,ae,"m",De).call(this,t);try{const o=yield e(this,ae,"m",Ve).call(this),l=A(t);this.nextRequestStatus.update({isLoading:!0});const a=Object.assign(Object.assign(Object.assign({},l),o),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin}),d=yield s(r,a);this.nextRequestStatus.update({isLoading:!1}),this.captureLastSubmittedLoginId(o,null===(n=null==d?void 0:d.data)||void 0===n?void 0:n.executionId),this.storeCredentials(o)}catch(e){throw l(),e}}}else this.loggerWrapper.debug("Submit already in flight, ignoring")}))))),this.flowState=s,this.setValidationTrackingSender(((e,t)=>i(this,[e,t],void 0,(function*({executionId:e,events:t},{keepalive:i}){const s=yield this.sdk.flow.event(e,t,i);return{ok:s.ok,retryable:s.code>=500||429===s.code}}))))}nativeResume(t,i){var s,o,n,r,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===(r=(n=this.nativeCallbacks).complete)||void 0===r||r.call(n,{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,Ee,"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:{[j(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 n=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(n){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=n;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.19",`dist/${e.id}.js`));const r=null===(o=globalThis.descope)||void 0===o?void 0:o[e.id];return new Promise(((i,s)=>{try{const s=r(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 o=this.nextRequestStatus.subscribe((()=>{var i;this.loggerWrapper.debug("Stopping script",e.id),(null===(i=s.stop)||void 0===i?void 0:i.call(s))&&(this.nextRequestStatus.unsubscribe(o),this.loggerWrapper.debug("Removing script",e.id),this.shadowRoot.removeChild(t))}));"function"==typeof s.present&&i(e.id)}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),u)}));return Promise.race([s,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){var e,i;if(!window.descopeBridge)return this._init();this.lazyInit=this._init,t(this,ge,null===(i=null===(e=null===window||void 0===window?void 0:window.descopeBridge)||void 0===e?void 0:e.registerFlow)||void 0===i?void 0:i.call(e,this),"f")}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,ae,"m",we).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,s,o;super.disconnectedCallback(),this.teardownValidationTracking(),e(this,ge,"f")&&(null===(s=null===(i=window.descopeBridge)||void 0===i?void 0:i.unregisterFlow)||void 0===s||s.call(i,e(this,ge,"f")),t(this,ge,void 0,"f")),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,Ee,"f").call(this),null===(o=e(this,ce,"f"))||void 0===o||o.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),n=yield this.getTargetLocales();return n.includes(s.locale)?i=`${t}-${s.locale}.html`:n.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:I,redirectIsPopup:E,redirectUrl:O,token:A,code:j,isPopup:U,exchangeError:P,webauthnTransactionId:F,webauthnOptions:N,redirectAuthCodeChallenge:$,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:V,redirectAuthInitiator:q,locale:D,samlIdpResponseUrl:B,samlIdpResponseSamlResponse:_,samlIdpResponseRelayState:K,wsFedIdpResponseUrl:H,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,ne,re;const le=G(),{outboundAppId:de,outboundAppScopes:he}=this,ue=this.sdk.getLastUserLoginId();p("flowId")&&this.setValidationTrackingEnabled(!1);const ge=yield this.getFlowConfig();e(this,ae,"m",Ne).call(this,ge,b,p);const ve=yield this.getProjectConfig(),me=Object.entries(ve.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),be=M&&$?{callbackUrl:M,codeChallenge:$,backupCallbackUri:V}: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:re,startScreenName:ne,clientScripts:e,componentsConfig:Se}=J({loginId:ue,code:j,token:A,abTestingKey:le,lastAuth:Z(ue,this.loggerWrapper)},ge.conditions)),i.push(...e||[])}else ge.condition?({startScreenId:oe,startScreenName:ne,conditionInteractionId:re}=z(ge.condition,{loginId:ue,code:j,token:A,abTestingKey:le,lastAuth:Z(ue,this.loggerWrapper)})):(ne=ge.startScreenName,oe=ge.startScreenId);if(t(this,Pe,oe,"f"),t(this,Fe,ne,"f"),t(this,pe,this.loadSdkScripts(i),"f"),ge.fingerprintEnabled&&ge.fingerprintKey?yield n(ge.fingerprintKey,this.baseUrl):r(),!k(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}),O&&{redirectUrl:O}),{lastAuth:Z(ue,this.loggerWrapper),abTestingKey:le,locale:o(D).locale,nativeOptions:we,outboundAppId:de,outboundAppScopes:he}),re,"",ve.componentsVersion,me,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),j?{exchangeCode:j,idpInitiated:!0}:{}),se.descopeIdpInitiated&&{idpInitiated:!0}),A?{token:A}:{}),se.oidcLoginHint?{externalId:se.oidcLoginHint}:{}));return e(this,Ae,"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:j,exchangeError:P,isCodeChanged:p("code"),isExchangeErrorChanged:p("exchangeError")})),U&&(p("code")&&j||p("exchangeError")&&P))return void e(this,ae,"m",Ye).call(this,b,j,P);if(b&&(p("token")&&A||p("code")&&j||p("exchangeError")&&P)){const t=yield this.sdk.flow.next(b,f,a.submit,ge.version,ve.componentsVersion,{token:A,exchangeCode:j,exchangeError:P});return e(this,Ae,"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(!_)return void this.loggerWrapper.error("Did not get saml idp params data to load");R(B,_,K||"",T)}if(w===l.loadForm&&H&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>p(e)))){if(!Q)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");W(H,Q,X||"",T)}if(w===l.redirect&&(p("redirectTo")||p("deferredRedirect"))){if(!I)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===I)return;if("android"===q&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${E}`),E){this.loggerWrapper.debug("Opening redirect in popup");const t=C(I,"?",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:n}=e.data||{};"code"===o&&(s=!0,this.flowState.update({code:n.code,exchangeError:n.exchangeError}))};let n;this.loggerWrapper.debug("Starting popup closed detection");const r=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(r),e(this,ae,"m",Xe).call(this,"popupclosed",{abandoned:!s}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==n||n())}),1e3);if(i)window.addEventListener("message",o),n=()=>{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,n=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(I),this.flowState.update({redirectTo:"no-op"}),e(this,ae,"m",Xe).call(this,"popupclosed",{});return}if(w===l.webauthnCreate||w===l.webauthnGet){if(!F||!N)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");null===(u=e(this,ce,"f"))||void 0===u||u.abort(),t(this,ce,null,"f");const i=yield e(this,ae,"m",Re).call(this,w,N),s=yield this.sdk.flow.next(b,f,a.submit,ge.version,ve.componentsVersion,Object.assign({transactionId:F},i));e(this,Ae,"f").call(this,s)}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,Ae,"f").call(this,i)})),e(this,ae,"m",fe).call(this,ee,te),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if((p("action")||p("deferredPolling"))&&e(this,xe,"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,Ie=yield this.getHtmlFilenameWithLocale(D,ye),{oidcLoginHint:We,oidcPrompt:Ce,oidcErrorRedirectUri:Ee,oidcResource:Oe,samlIdpUsername:je}=se,Te={direction:x(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:Ie,screenId:ye,stepName:d.stepName||ne,samlIdpUsername:je,oidcLoginHint:We,oidcPrompt:Ce,oidcErrorRedirectUri:Ee,oidcResource:Oe,action:w,locale:o(D).locale},Le=Z(ue,this.loggerWrapper);k(oe,se)?Te.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ge?void 0:ge.clientScripts)||[];yield e(this,ae,"m",He).call(this,i);const n=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:be},se),{lastAuth:Le,preview:this.preview,abTestingKey:le,client:this.client}),O&&{redirectUrl:O}),{locale:o(D).locale,nativeOptions:we,outboundAppId:de,outboundAppScopes:he}),re,t,ve.componentsVersion,me,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),L(s)),j&&{exchangeCode:j,idpInitiated:!0}),se.descopeIdpInitiated&&{idpInitiated:!0}),A&&{token:A}),Te.next.isCustomScreen);return e(this,Ae,"f").call(this,n),n})):(p("projectId")||p("baseUrl")||p("executionId")||p("stepId"))&&(Te.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==y?void 0:y.clientScripts)||[];yield e(this,ae,"m",He).call(this,i);const o=yield this.sdk.flow.next(b,f,t,ge.version,ve.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),L(s)),Te.next.isCustomScreen);return e(this,Ae,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",Te.screenId),yield e(this,ae,"m",ke).call(this,Te),this.stepState.update(Te)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n,r;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 v=g.content.cloneNode(!0),f=this.loadDescopeUiComponents(g);this.sdk.webauthn.helpers.isSupported()?yield e(this,ae,"m",Le).call(this,v,p):N(v),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(n=h.form)||void 0===n?void 0:n.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),$(v,h,this.formConfig,this.loggerWrapper),this.applyComponentsState(v,null==h?void 0:h.componentsState);const{geo:b}=null!==(r=yield this.getExecutionContext())&&void 0!==r?r:{};M(v,b),V(v,t.locale);const w=()=>i(this,void 0,void 0,(function*(){var i,o;yield f;const n=this.contentRootElement;q(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),D(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),B(n,v,h.cssVars,this.loggerWrapper),n.replaceChildren(v);const r=!s.htmlFilename;setTimeout((()=>{e(this,ae,"m",Be).call(this),this.updateUsernameAnchor(),this.validateOnBlur&&U(n,(t=>this.trackValidationErrors([t],e(this,ae,"a",$e)))),_(n,h),this.initRealtimeConditions(n,h),e(this,ae,"m",Ue).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),E(n,this.autoFocus,r),e(this,ae,"m",ze).call(this,u)})),e(this,ae,"m",Qe).call(this,p,u);n.querySelector(`[${m}="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,ge=new WeakMap,Ie=new WeakMap,We=new WeakMap,xe=new WeakMap,Ee=new WeakMap,Oe=new WeakMap,Ae=new WeakMap,je=new WeakMap,Pe=new WeakMap,Fe=new WeakMap,qe=new WeakMap,Ke=new WeakMap,ae=new WeakSet,ue=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1,deferredPolling:!1})}),300)},ve=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",fe).call(this,"beforeScreen",{screen:t,context:s})}))}))},me=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,ae,"m",fe).call(this,"afterScreen",{screen:t})},fe=function(t,i){e(this,ae,"m",Xe).call(this,"bridge",{type:t,payload:i})},be=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()},we=function(){var t,i,o,n;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",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}),null===(o=this.stepState)||void 0===o||o.subscribe(e(this,ae,"m",Se).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===(n=this.flowState)||void 0===n||n.subscribe((({screenId:e,executionId:t})=>{var i;try{this.updateTelemetryContext({screenId:e,executionId:t})}catch(e){null===(i=this.logger)||void 0===i||i.error("Error updating telemetry screenId:",e)}}),(e=>({screenId:e.screenId,executionId:e.executionId})))},Se=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=""}))})),E(this.contentRootElement,this.autoFocus,!1))},ye=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")}))},ke=function(o){return i(this,void 0,void 0,(function*(){var i;const n=Object.assign(Object.assign({},this.stepState.current),o),{next:r,stepName:l}=n,a=s(n,["next","stepName"]),d=O(a);let c=yield e(this,ae,"m",ve).call(this,l,d,r);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,l,d,r,this)));const p=!this.stepState.current.htmlFilename;if(e(this,We,"f").call(this,c),r&&(r.isCustomScreen=c),e(this,Ie,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,Ie,c,"f"),c?this.stepState.unsubscribeAll():e(this,ae,"m",we).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,ae,"m",Ue).call(this,{isFirstScreen:p,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},Re=function(e,t){return i(this,void 0,void 0,(function*(){const i=new AbortController;try{const s=e===l.webauthnCreate?this.sdk.webauthn.helpers.create(t,i):this.sdk.webauthn.helpers.get(t,i),o=yield S(v,s,Ze);return o!==Ze?{response:o}:(i.abort(),this.loggerWrapper.warn(`WebAuthn operation timed out after ${v}ms`),{failure:"AbortError",failureReason:"aborted",failureMessage:"Passkey operation timed out"})}catch(e){return"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),{failure:e.name,failureReason:e.reason,failureMessage:e.message}}}))},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")},Te=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)}))}},Le=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,ce,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield H())){const{options:s,transactionId:n}=(yield e(this,je,"f").call(this))||{};s&&n&&(e(this,ae,"m",Te).call(this,r),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(r.id,{transactionId:n,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},Ue=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,ae,"m",Xe).call(this,"ready",{}),i||e(this,ae,"m",me).call(this,s),e(this,ae,"m",Xe).call(this,"page-updated",{screenName:s}),e(this,ae,"m",Xe).call(this,"screen-updated",{screenName:s})},Ne=function(e,t,i){this.setValidationTrackingEnabled(!!e.clientValidationTrackingEnabled),t&&i("executionId")&&this.setValidationTrackingExecution(t)},$e=function(){var t,i,s,o,n,r,l;const a=null===(t=this.flowState)||void 0===t?void 0:t.current;return(null==a?void 0:a.executionId)?{executionId:a.executionId,screenId:a.screenId,screenName:(null===(l=null===(r=this.stepState)||void 0===r?void 0:r.current)||void 0===l?void 0:l.stepName)||a.stepName}:{executionId:void 0,screenId:null!==(i=e(this,Pe,"f"))&&void 0!==i?i:null==a?void 0:a.screenId,screenName:null!==(s=e(this,Fe,"f"))&&void 0!==s?s:(null===(n=null===(o=this.stepState)||void 0===o?void 0:o.current)||void 0===n?void 0:n.stepName)||(null==a?void 0:a.stepName)}},Me=function(){let t=!0;const i=[];return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((e=>{var s,o;"slot"===e.localName||e.classList.contains("hidden")||(null===(s=e.reportValidity)||void 0===s||s.call(e),e.validity&&!e.validity.valid&&i.push(e),t&&(t=null===(o=e.checkValidity)||void 0===o?void 0:o.call(e)))})),i.length&&this.trackValidationErrors(i,e(this,ae,"a",$e)),t},Ve=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})),{})}))},De=function(s){var o,n;const r=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),l=(null===(n=null===(o=this.flowState.current)||void 0===o?void 0:o.screenState)||void 0===n?void 0:n.clientScripts)||[];s.setAttribute("loading","true"),r.forEach((e=>e.setAttribute("disabled","true")));const a=()=>{s.removeAttribute("loading"),r.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(),n=[...o.clientScripts||[],...o.sdkScripts||[]];this.loadSdkScripts(n)})),c=()=>{var i;window.removeEventListener("pageshow",e(this,qe,"f")),t(this,qe,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),d())}),"f"),window.addEventListener("pageshow",e(this,qe,"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}):(this.nextRequestStatus.unsubscribe(p),"success"===this.flowStatus?(this.removeEventListener("popupclosed",d),a()):c())}));return a},Be=function(){P();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,ae,"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)}))},He=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 S(u,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},Ge=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,Ke,"f").call(this,s,t,i)}))}))},Je=function(e,t,i){t&&i&&"true"===e.getAttribute(f)&&ee(i,t,this.loggerWrapper)},ze=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(b),n=this.contentRootElement.querySelector(`#${CSS.escape(s)}`);o&&n&&(n.replaceWith(o),o.appendChild(n))},Qe=function(t,i){this.contentRootElement.querySelectorAll(`descope-button:not([${w}]), [data-type="button"]:not([${w}]`).forEach((s=>{s.onclick=()=>{e(this,Ke,"f").call(this,s,t,i)}})),e(this,ae,"m",Ge).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:""})})))}))}))},Xe=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},Ye=function(e,t,i){var s;const[o,n]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],r={data:{code:t,exchangeError:i},action:"code"};if("descope-wc"===o&&n){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",n);try{window.opener.postMessage(r,n)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(r),t.close()}try{window.close()}catch(e){}},et.bridgeVersion=3;export{et as default};
2
2
  //# sourceMappingURL=DescopeWc.js.map