@trymellon/js 2.3.1 → 2.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ReactNode } from 'react';
3
- import { T as TryMellon, R as Result, a as RegisterResult, b as TryMellonError, c as RegisterOptions, A as AuthenticateResult, d as AuthenticateOptions, E as EnrollmentResult, e as EnrollOptions } from './trymellon-CO_2wLZz.cjs';
3
+ import { T as TryMellon, R as Result, a as RegisterResult, b as TryMellonError, c as RegisterOptions, A as AuthenticateResult, d as AuthenticateOptions, E as EnrollmentResult, e as EnrollOptions } from './trymellon-BKAS6p95.cjs';
4
4
 
5
5
  declare function TryMellonProvider(props: {
6
6
  client: TryMellon;
package/dist/react.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ReactNode } from 'react';
3
- import { T as TryMellon, R as Result, a as RegisterResult, b as TryMellonError, c as RegisterOptions, A as AuthenticateResult, d as AuthenticateOptions, E as EnrollmentResult, e as EnrollOptions } from './trymellon-CO_2wLZz.js';
3
+ import { T as TryMellon, R as Result, a as RegisterResult, b as TryMellonError, c as RegisterOptions, A as AuthenticateResult, d as AuthenticateOptions, E as EnrollmentResult, e as EnrollOptions } from './trymellon-BKAS6p95.js';
4
4
 
5
5
  declare function TryMellonProvider(props: {
6
6
  client: TryMellon;
@@ -674,6 +674,11 @@ declare class TryMellon {
674
674
  * This constructor will throw errors if configuration is invalid.
675
675
  */
676
676
  constructor(config: TryMellonConfig);
677
+ /**
678
+ * DX: warn when sandbox is ON and origin is not localhost/127.0.0.1 (e.g. production).
679
+ * No-op in non-browser (SSR/Node). No exceptions; only console.warn.
680
+ */
681
+ private warnIfSandboxOnProd;
677
682
  /**
678
683
  * Bridge (KP-BRIDGE-04): complete enrollment or auth from a second device (e.g. mobile scanning desktop QR).
679
684
  * Use kind 'enrollment' for enrollment-bridge sessions, 'auth' for auth-bridge sessions.
@@ -674,6 +674,11 @@ declare class TryMellon {
674
674
  * This constructor will throw errors if configuration is invalid.
675
675
  */
676
676
  constructor(config: TryMellonConfig);
677
+ /**
678
+ * DX: warn when sandbox is ON and origin is not localhost/127.0.0.1 (e.g. production).
679
+ * No-op in non-browser (SSR/Node). No exceptions; only console.warn.
680
+ */
681
+ private warnIfSandboxOnProd;
677
682
  /**
678
683
  * Bridge (KP-BRIDGE-04): complete enrollment or auth from a second device (e.g. mobile scanning desktop QR).
679
684
  * Use kind 'enrollment' for enrollment-bridge sessions, 'auth' for auth-bridge sessions.
package/dist/ui/index.js CHANGED
@@ -1,4 +1,4 @@
1
- function Zn(t){if(t.recommendedFlow==="fallback")return t.fallbackType==="email"?"FALLBACK_EMAIL":t.fallbackType==="qr"?"FALLBACK_QR":"FALLBACK";switch(t.mode){case"login":return"READY_LOGIN";case"register":return"READY_REGISTER";default:return"READY"}}function eo(t){return t==="register"?"READY_REGISTER":"READY_LOGIN"}function se(t,e){if(t==null||e==null||e.type==="RESET")return"IDLE";if(e.type==="TAB_CHANGE"){let r=e.payload?.tab;if(r!=="register"&&r!=="login")return t;let n=eo(r);switch(t){case"READY":case"READY_REGISTER":case"READY_LOGIN":case"FALLBACK":case"FALLBACK_EMAIL":case"FALLBACK_QR":case"AUTHENTICATING":case"ERROR":return n;default:return t}}switch(t){case"IDLE":if(e.type==="ENV_EVAL_START")return"EVALUATING_ENV";if(e.type==="ENROLLMENT_READY_SET")return"ENROLLMENT_READY";break;case"EVALUATING_ENV":if(e.type==="ENV_RESOLVED")return Zn(e.payload);if(e.type==="ENV_DETACH")return"IDLE";if(e.type==="ENV_ERROR")return"ERROR";break;case"READY":case"READY_REGISTER":case"READY_LOGIN":if(e.type==="START_AUTH")return"AUTHENTICATING";break;case"AUTHENTICATING":if(e.type==="AUTH_SUCCESS")return"SUCCESS";if(e.type==="AUTH_ERROR")return"ERROR";if(e.type==="AUTH_FALLBACK")return"FALLBACK";if(e.type==="AUTH_FALLBACK_EMAIL")return"FALLBACK_EMAIL";if(e.type==="AUTH_FALLBACK_QR")return"FALLBACK_QR";break;case"ENROLLMENT_READY":if(e.type==="START_ENROLL")return"ENROLLING";break;case"ENROLLING":if(e.type==="ENROLL_SUCCESS")return"ENROLLMENT_SUCCESS";if(e.type==="ENROLL_ERROR")return"ENROLLMENT_ERROR";break;case"ENROLLMENT_ERROR":if(e.type==="ENROLL_RETRY")return"ENROLLMENT_READY";break;default:break}return t}var k="IDLE";var Sr=["IDLE","EVALUATING_ENV","READY","READY_REGISTER","READY_LOGIN","AUTHENTICATING","SUCCESS","ERROR","FALLBACK","FALLBACK_EMAIL","FALLBACK_QR","ENROLLMENT_READY","ENROLLING","ENROLLMENT_SUCCESS","ENROLLMENT_ERROR"],ae=["login","register","auto"],G=["light","dark"],le=["register","login"],ue=["modal","inline"],de=["email","qr"],ce=["direct-auth","open-modal"],pe=["default","pill"],me=["default","minimal"],Cr=["passkey","fallback"];function St(t){if(t==null||typeof t!="object")return!1;let e=t;return!(typeof e.isPasskeySupported!="boolean"||typeof e.platformAuthenticatorAvailable!="boolean"||e.recommendedFlow!=="passkey"&&e.recommendedFlow!=="fallback")}function D(t,e){return typeof t=="string"&&e.includes(t)}function Ct(t){return D(t,Sr)}function B(t){return Ct(t)?t:k}function j(t){return D(t,ae)}function ge(t){return D(t,G)}function fe(t){return D(t,le)}function Oe(t){return D(t,ue)}function It(t){return D(t,ce)}function Lt(t){return D(t,pe)}function Mt(t){return D(t,me)}function Ot(t){if(t==null||typeof t!="object")return!1;let e=t;return D(e.recommendedFlow,Cr)&&j(e.mode)&&(e.fallbackType===void 0||D(e.fallbackType,de))}function xe(t){if(t==null||typeof t!="object")return!1;let e=t,r=e.type;if(typeof r!="string")return!1;switch(r){case"ENV_EVAL_START":case"ENV_DETACH":case"ENV_ERROR":case"RESET":case"START_AUTH":case"AUTH_SUCCESS":case"AUTH_ERROR":case"AUTH_FALLBACK":case"AUTH_FALLBACK_EMAIL":case"AUTH_FALLBACK_QR":case"ENROLLMENT_READY_SET":case"START_ENROLL":case"ENROLL_SUCCESS":case"ENROLL_ERROR":case"ENROLL_RETRY":return!0;case"ENV_RESOLVED":return Ot(e.payload);case"TAB_CHANGE":return e.payload!=null&&typeof e.payload=="object"&&fe(e.payload.tab);default:return!1}}var ke="login",Y="light",De="modal",Ne="register",Q={register:"Register",login:"Sign in"},Pe="open-modal",we="default",Ue="default",he={appId:"",publishableKey:"",mode:ke,externalUserId:null,theme:Y,action:Pe,triggerOnly:!1,buttonVariant:we,buttonLabel:null,buttonAriaLabel:null,ticketId:null},xt={open:!1,mode:De,tab:Ne,tabLabels:Q,theme:Y,sessionId:null,onboardingUrl:null,isMobileOverride:null,appId:"",publishableKey:"",appName:null,dialogTitle:null,dialogDescription:null,externalUserId:null,modalVariant:Ue};function Ir(t){if(t==null||typeof t!="object")return!1;let e=t;return typeof e.appId=="string"&&typeof e.publishableKey=="string"&&j(e.mode)&&(e.externalUserId===null||typeof e.externalUserId=="string")&&ge(e.theme)&&It(e.action)&&typeof e.triggerOnly=="boolean"&&Lt(e.buttonVariant)&&(e.ticketId===void 0||e.ticketId===null||typeof e.ticketId=="string")}function Lr(t){if(t==null||typeof t!="object")return!1;let e=t;return typeof e.register=="string"&&typeof e.login=="string"}function Mr(t){if(t==null||typeof t!="object")return!1;let e=t;return typeof e.open=="boolean"&&Oe(e.mode)&&fe(e.tab)&&Lr(e.tabLabels)&&ge(e.theme)&&(e.sessionId===null||typeof e.sessionId=="string")&&(e.onboardingUrl===null||typeof e.onboardingUrl=="string")&&(e.isMobileOverride===null||typeof e.isMobileOverride=="boolean")&&(e.fallbackType===void 0||e.fallbackType==="email"||e.fallbackType==="qr")&&typeof e.appId=="string"&&typeof e.publishableKey=="string"&&(e.appName==null||typeof e.appName=="string")&&(e.dialogTitle==null||typeof e.dialogTitle=="string")&&(e.dialogDescription==null||typeof e.dialogDescription=="string")&&(e.externalUserId==null||typeof e.externalUserId=="string")&&Mt(e.modalVariant)}function Or(){return he}function xr(){return xt}function kt(t){return Ir(t)?t:Or()}function Dt(t){return Mr(t)?t:xr()}function T(t,e){let r=B(t);return xe(e)?se(r,e):r}function Nt(t,e,r){return{state:t,theme:e.theme,mode:e.mode,buttonVariant:e.buttonVariant,...e.mode==="register"&&r?.registerSessionReady!==void 0&&{registerSessionReady:r.registerSessionReady},...r?.primaryButtonLabel!==void 0&&{primaryButtonLabel:r.primaryButtonLabel},...r?.primaryButtonAriaLabel!==void 0&&{primaryButtonAriaLabel:r.primaryButtonAriaLabel}}}function Pt(t,e,r){return{state:t,theme:e.theme,tab:e.tab,tabLabels:e.tabLabels,...e.tab==="register"&&r?.registerSessionReady!==void 0&&{registerSessionReady:r.registerSessionReady},primaryButtonLabel:r?.primaryButtonLabel??"Try Passkey",primaryButtonAriaLabel:r?.primaryButtonAriaLabel??"Try Passkey, use this device"}}function ro(t){return typeof t?.getClientStatus=="function"}async function kr(t){if(!ro(t.envStatusPort))return k;let e=t.envStatusPort,r=B(t.currentState),n=j(t.mode)?t.mode:"login",o=t.isMobileOverride===!0,i=t.fallbackType==="email"||t.fallbackType==="qr"?t.fallbackType:void 0,a=T(r,{type:"ENV_EVAL_START"}),u;try{let f=await e.getClientStatus();if(!St(f))return T(a,{type:"ENV_ERROR"});u=f}catch{return T(a,{type:"ENV_ERROR"})}let p=o===!0?"fallback":u.recommendedFlow,g={recommendedFlow:p,mode:n,...p==="fallback"&&i!=null&&{fallbackType:i}};return T(a,{type:"ENV_RESOLVED",payload:g})}function Nr(t){return T(t,{type:"START_AUTH"})!==t}function no(t,e,r,n){let o=T(t,{type:"START_AUTH"});return e==="register"?r.register(n):r.authenticate(n),o}function oo(t,e,r){let n=t;n!=="ENROLLMENT_READY"&&(n=T(n,{type:"ENROLLMENT_READY_SET",payload:{ticketId:r.ticketId}}));let o=T(n,{type:"START_ENROLL"});return e.enroll(r),o}function Dr(t,e,r,n,o){return t!==e?null:T(t,{type:o==="success"?r:n})}var io={email:{type:"AUTH_FALLBACK_EMAIL"},qr:{type:"AUTH_FALLBACK_QR"},generic:{type:"AUTH_FALLBACK"}};function so(t,e){return T(t,io[e==="email"?"email":e==="qr"?"qr":"generic"])}var I={envEvalStart(t){return T(t,{type:"ENV_EVAL_START"})},evaluateEnv(t){return kr(t)},startAuth(t,e,r,n){return no(t,e,r,n)},handleAuthOutcome(t,e){return Dr(t,"AUTHENTICATING","AUTH_SUCCESS","AUTH_ERROR",e)},handleFallback(t,e){return so(t,e)},tabChange(t,e){return T(t,{type:"TAB_CHANGE",payload:{tab:e}})},reset(t){return T(t,{type:"RESET"})},startEnrollment(t,e,r){return oo(t,e,r)},handleEnrollOutcome(t,e){return Dr(t,"ENROLLING","ENROLL_SUCCESS","ENROLL_ERROR",e)},enrollRetry(t){return T(t,{type:"ENROLL_RETRY"})}};function W(t){return t==null||t.trim()===""?"":t.trim()}function M(t){let e=W(t);return e===""?null:e}function Be(t){if(t==null)return!1;let e=t.trim().toLowerCase();return e==="true"||e==="1"||e===""}function Pr(t){if(t==null||t.trim()==="")return null;let e=t.trim().toLowerCase();return e==="true"||e==="1"?!0:e==="false"||e==="0"?!1:null}function N(t,e,r){if(t==null||t.trim()==="")return r;let n=t.trim().toLowerCase();return e.includes(n)?n:r}function wr(t,e){if(t==null||t.trim()==="")return;let r=t.trim().toLowerCase();if(e.includes(r))return r}function wt(t){let e={appId:W(t.getAttribute("app-id")),publishableKey:W(t.getAttribute("publishable-key")),mode:N(t.getAttribute("mode"),ae,ke),externalUserId:M(t.getAttribute("external-user-id")),theme:N(t.getAttribute("theme"),G,Y),action:N(t.getAttribute("action"),ce,Pe),triggerOnly:Be(t.getAttribute("trigger-only")),buttonVariant:N(t.getAttribute("button-variant"),pe,we),buttonLabel:M(t.getAttribute("button-label")),buttonAriaLabel:M(t.getAttribute("button-aria-label")),ticketId:M(t.getAttribute("ticket-id"))};return kt(e)}var $="mellon-root",Fe=".mellon-btn",Ke='[data-mellon-action^="fallback"]',Ve="fallback-email",J="fallback-qr",Ee="TryMellon",Ut="Try Passkey",be="TryMellon, open authentication",Bt="Try Passkey, use this device",F="http://www.w3.org/2000/svg",ye="mellon-modal-wrapper",z="mellon-modal-overlay",_e="mellon-modal-panel",Re="mellon-modal-tabs",Ft="mellon-modal-content",K="cross-device",Kt="fallback-cta",He="mellon-dialog-title",Ae="mellon-dialog-desc",Ur="TryMellon \u2014 Sign in or register",Br=t=>`${t} \u2014 Sign in or register`,Fr="Pick Register or Sign in to continue.",Kr="Or sign in with",w="mellon-cross-device-wrap",Vt="mellon-modal-separator",Ht="mellon-modal-close-btn",Vr="Close dialog",Hr="Try from another device",qr="mellon-cross-device-cta",Gr="Try with QR",jr="mellon-cross-device-skeleton",Yr="mellon-cross-device-error",Wr="mellon-cross-device-slot-wrap",$r="Loading QRs",zr="QR could not be loaded. Try again.";function Xr(){let t=document.createElementNS(F,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("class","mellon-btn-icon"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round");let e=document.createElementNS(F,"path");e.setAttribute("d","M12 22a10 10 0 0 0 10-10 10 10 0 0 0-20 0 10 10 0 0 0 10 10Z");let r=document.createElementNS(F,"path");r.setAttribute("d","M12 14a2 2 0 0 0 2-2 2 2 0 0 0-2-2 2 2 0 0 0-2 2 2 2 0 0 0 2 2Z");let n=document.createElementNS(F,"path");return n.setAttribute("d","M5 19.05A9 9 0 0 1 3 12a9 9 0 0 1 2-5.05"),t.appendChild(e),t.appendChild(r),t.appendChild(n),t}function ao(t,e=Ee,r=be){let n=document.createElement("button");return n.type="button",n.className="mellon-btn",n.setAttribute("aria-label",r),n.disabled=t,n.appendChild(Xr()),n.appendChild(document.createTextNode(e)),n}function lo(t,e=Ee,r=be){let n=document.createElement("button");n.type="button",n.className="mellon-btn mellon-btn-pill",n.setAttribute("aria-label",r),n.disabled=t;let o=document.createElement("span");return o.className="mellon-btn-pill-icon-circle",o.setAttribute("aria-hidden","true"),o.appendChild(Xr()),n.appendChild(o),n.appendChild(document.createTextNode(e)),n}function uo(t,e=Ee,r=be){return n=>t==="pill"?lo(n,e,r):ao(n,e,r)}function co(t){return{variant:t.buttonVariant??"default",label:t.primaryButtonLabel??Ee,ariaLabel:t.primaryButtonAriaLabel??be}}function qt(t){let{variant:e,label:r,ariaLabel:n}=co(t);return uo(e,r,n)(!1)}function po(t){let{shadowRoot:e}=t,r=e.getElementById($);return r||(r=document.createElement("div"),r.id=$,r.className="mellon-root",e.appendChild(r)),r}function Z(t,e){let r=document.createElement("p");return r.className=t,r.textContent=e,r}function mo(t,e){let r=document.createElement("button");return r.type="button",r.className="mellon-btn mellon-btn-fallback",r.setAttribute("data-mellon-action",t),r.textContent=e,r}var go={FALLBACK:{action:"fallback",label:"Continuar"},FALLBACK_EMAIL:{action:Ve,label:"Continuar con email"},FALLBACK_QR:{action:J,label:"Continuar con QR"}};function fo(t){let e=document.createElement("div");e.className="mellon-fallback";let r=document.createElement("p");r.className="mellon-message",r.textContent="Fallback disponible.",e.appendChild(r);let{action:n,label:o}=go[t];return e.appendChild(mo(n,o)),e}function ho(t,e){let r=document.createDocumentFragment();switch(t){case"IDLE":case"EVALUATING_ENV":r.appendChild(Z("mellon-loading","Loading\u2026"));break;case"READY_LOGIN":r.appendChild(qt(e));break;case"READY_REGISTER":e.registerSessionReady===!1?r.appendChild(Z("mellon-loading","Preparando registro\u2026")):r.appendChild(qt(e));break;case"READY":r.appendChild(qt(e));break;case"AUTHENTICATING":r.appendChild(Z("mellon-loading","Authenticating\u2026"));break;case"SUCCESS":r.appendChild(Z("mellon-message","Success."));break;case"ERROR":r.appendChild(Z("mellon-message","Something went wrong."));break;case"FALLBACK":case"FALLBACK_EMAIL":case"FALLBACK_QR":r.appendChild(fo(t));break;default:r.appendChild(Z("mellon-loading","Loading\u2026"))}return r}function Gt(t,e,r={}){let n=B(e),o=po(t),i=ho(n,r);o.replaceChildren(...Array.from(i.childNodes))}function Eo(t){return{theme:t.theme,mode:t.mode,buttonVariant:t.buttonVariant,registerSessionReady:t.registerSessionReady,primaryButtonLabel:t.primaryButtonLabel,primaryButtonAriaLabel:t.primaryButtonAriaLabel}}function bo(t){return{theme:t.theme,mode:t.tab,buttonVariant:"pill",registerSessionReady:t.registerSessionReady,primaryButtonLabel:t.primaryButtonLabel,primaryButtonAriaLabel:t.primaryButtonAriaLabel}}function Qr(t,e){Gt(t,e.state,Eo(e))}function Jr(t,e){Gt(t,e.state,bo(e))}var Zr=".mellon-modal-tabs",jt="data-tab",en='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',tn='[data-mellon-modal-close="true"]';function rn(t){if(t===Ve)return"email";if(t===J)return"qr"}function nn(t,e){let r=n=>{let o=n.target instanceof Element?n.target:null;if(!o)return;let i=o.closest(Ke);if(i instanceof HTMLButtonElement){e.onFallbackClick(rn(i.getAttribute("data-mellon-action")));return}o.closest(Fe)&&e.onPrimaryClick()};return t.addEventListener("click",r),()=>t.removeEventListener("click",r)}function on(t,e){let r=n=>{let o=n.target instanceof Element?n.target:null;if(!o)return;if(e.onCloseClick&&o.closest(tn)instanceof HTMLElement){e.onCloseClick();return}let i=o.closest(Ke);if(i instanceof HTMLButtonElement){e.onFallbackClick(rn(i.getAttribute("data-mellon-action")));return}if(t.querySelector(Zr)?.contains(o)){let p=o.closest(`[${jt}]`)?.getAttribute(jt);if(p==="register"||p==="login"){e.onTabChange(p);return}}if(o.closest(Fe)){e.onPrimaryClick();return}if(e.onOverlayClick){let u=t.querySelector(`.${z}`);u&&o===u&&e.onOverlayClick()}};return t.addEventListener("click",r),()=>t.removeEventListener("click",r)}var ve=`
1
+ function ro(t){if(t.recommendedFlow==="fallback")return t.fallbackType==="email"?"FALLBACK_EMAIL":t.fallbackType==="qr"?"FALLBACK_QR":"FALLBACK";switch(t.mode){case"login":return"READY_LOGIN";case"register":return"READY_REGISTER";default:return"READY"}}function no(t){return t==="register"?"READY_REGISTER":"READY_LOGIN"}function se(t,e){if(t==null||e==null||e.type==="RESET")return"IDLE";if(e.type==="TAB_CHANGE"){let r=e.payload?.tab;if(r!=="register"&&r!=="login")return t;let n=no(r);switch(t){case"READY":case"READY_REGISTER":case"READY_LOGIN":case"FALLBACK":case"FALLBACK_EMAIL":case"FALLBACK_QR":case"AUTHENTICATING":case"ERROR":return n;default:return t}}switch(t){case"IDLE":if(e.type==="ENV_EVAL_START")return"EVALUATING_ENV";if(e.type==="ENROLLMENT_READY_SET")return"ENROLLMENT_READY";break;case"EVALUATING_ENV":if(e.type==="ENV_RESOLVED")return ro(e.payload);if(e.type==="ENV_DETACH")return"IDLE";if(e.type==="ENV_ERROR")return"ERROR";break;case"READY":case"READY_REGISTER":case"READY_LOGIN":if(e.type==="START_AUTH")return"AUTHENTICATING";break;case"AUTHENTICATING":if(e.type==="AUTH_SUCCESS")return"SUCCESS";if(e.type==="AUTH_ERROR")return"ERROR";if(e.type==="AUTH_FALLBACK")return"FALLBACK";if(e.type==="AUTH_FALLBACK_EMAIL")return"FALLBACK_EMAIL";if(e.type==="AUTH_FALLBACK_QR")return"FALLBACK_QR";break;case"ENROLLMENT_READY":if(e.type==="START_ENROLL")return"ENROLLING";break;case"ENROLLING":if(e.type==="ENROLL_SUCCESS")return"ENROLLMENT_SUCCESS";if(e.type==="ENROLL_ERROR")return"ENROLLMENT_ERROR";break;case"ENROLLMENT_ERROR":if(e.type==="ENROLL_RETRY")return"ENROLLMENT_READY";break;default:break}return t}var k="IDLE";var Ir=["IDLE","EVALUATING_ENV","READY","READY_REGISTER","READY_LOGIN","AUTHENTICATING","SUCCESS","ERROR","FALLBACK","FALLBACK_EMAIL","FALLBACK_QR","ENROLLMENT_READY","ENROLLING","ENROLLMENT_SUCCESS","ENROLLMENT_ERROR"],ae=["login","register","auto"],G=["light","dark"],le=["register","login"],ue=["modal","inline"],de=["email","qr"],ce=["direct-auth","open-modal"],pe=["default","pill"],me=["default","minimal"],Lr=["passkey","fallback"];function Tt(t){if(t==null||typeof t!="object")return!1;let e=t;return!(typeof e.isPasskeySupported!="boolean"||typeof e.platformAuthenticatorAvailable!="boolean"||e.recommendedFlow!=="passkey"&&e.recommendedFlow!=="fallback")}function D(t,e){return typeof t=="string"&&e.includes(t)}function Ct(t){return D(t,Ir)}function B(t){return Ct(t)?t:k}function j(t){return D(t,ae)}function ge(t){return D(t,G)}function fe(t){return D(t,le)}function Oe(t){return D(t,ue)}function It(t){return D(t,ce)}function Lt(t){return D(t,pe)}function Mt(t){return D(t,me)}function Ot(t){if(t==null||typeof t!="object")return!1;let e=t;return D(e.recommendedFlow,Lr)&&j(e.mode)&&(e.fallbackType===void 0||D(e.fallbackType,de))}function xe(t){if(t==null||typeof t!="object")return!1;let e=t,r=e.type;if(typeof r!="string")return!1;switch(r){case"ENV_EVAL_START":case"ENV_DETACH":case"ENV_ERROR":case"RESET":case"START_AUTH":case"AUTH_SUCCESS":case"AUTH_ERROR":case"AUTH_FALLBACK":case"AUTH_FALLBACK_EMAIL":case"AUTH_FALLBACK_QR":case"ENROLLMENT_READY_SET":case"START_ENROLL":case"ENROLL_SUCCESS":case"ENROLL_ERROR":case"ENROLL_RETRY":return!0;case"ENV_RESOLVED":return Ot(e.payload);case"TAB_CHANGE":return e.payload!=null&&typeof e.payload=="object"&&fe(e.payload.tab);default:return!1}}var ke="login",Y="light",De="modal",Ne="register",Q={register:"Register",login:"Sign in"},we="open-modal",Pe="default",Ue="default",he={appId:"",publishableKey:"",mode:ke,externalUserId:null,theme:Y,action:we,triggerOnly:!1,buttonVariant:Pe,buttonLabel:null,buttonAriaLabel:null,ticketId:null},xt={open:!1,mode:De,tab:Ne,tabLabels:Q,theme:Y,sessionId:null,onboardingUrl:null,isMobileOverride:null,appId:"",publishableKey:"",appName:null,dialogTitle:null,dialogDescription:null,externalUserId:null,modalVariant:Ue};function Mr(t){if(t==null||typeof t!="object")return!1;let e=t;return typeof e.appId=="string"&&typeof e.publishableKey=="string"&&j(e.mode)&&(e.externalUserId===null||typeof e.externalUserId=="string")&&ge(e.theme)&&It(e.action)&&typeof e.triggerOnly=="boolean"&&Lt(e.buttonVariant)&&(e.ticketId===void 0||e.ticketId===null||typeof e.ticketId=="string")}function Or(t){if(t==null||typeof t!="object")return!1;let e=t;return typeof e.register=="string"&&typeof e.login=="string"}function xr(t){if(t==null||typeof t!="object")return!1;let e=t;return typeof e.open=="boolean"&&Oe(e.mode)&&fe(e.tab)&&Or(e.tabLabels)&&ge(e.theme)&&(e.sessionId===null||typeof e.sessionId=="string")&&(e.onboardingUrl===null||typeof e.onboardingUrl=="string")&&(e.isMobileOverride===null||typeof e.isMobileOverride=="boolean")&&(e.fallbackType===void 0||e.fallbackType==="email"||e.fallbackType==="qr")&&typeof e.appId=="string"&&typeof e.publishableKey=="string"&&(e.appName==null||typeof e.appName=="string")&&(e.dialogTitle==null||typeof e.dialogTitle=="string")&&(e.dialogDescription==null||typeof e.dialogDescription=="string")&&(e.externalUserId==null||typeof e.externalUserId=="string")&&Mt(e.modalVariant)}function kr(){return he}function Dr(){return xt}function kt(t){return Mr(t)?t:kr()}function Dt(t){return xr(t)?t:Dr()}function T(t,e){let r=B(t);return xe(e)?se(r,e):r}function Nt(t,e,r){return{state:t,theme:e.theme,mode:e.mode,buttonVariant:e.buttonVariant,...e.mode==="register"&&r?.registerSessionReady!==void 0&&{registerSessionReady:r.registerSessionReady},...r?.primaryButtonLabel!==void 0&&{primaryButtonLabel:r.primaryButtonLabel},...r?.primaryButtonAriaLabel!==void 0&&{primaryButtonAriaLabel:r.primaryButtonAriaLabel}}}function wt(t,e,r){return{state:t,theme:e.theme,tab:e.tab,tabLabels:e.tabLabels,...e.tab==="register"&&r?.registerSessionReady!==void 0&&{registerSessionReady:r.registerSessionReady},primaryButtonLabel:r?.primaryButtonLabel??"Try Passkey",primaryButtonAriaLabel:r?.primaryButtonAriaLabel??"Try Passkey, use this device"}}function io(t){return typeof t?.getClientStatus=="function"}async function Nr(t){if(!io(t.envStatusPort))return k;let e=t.envStatusPort,r=B(t.currentState),n=j(t.mode)?t.mode:"login",o=t.isMobileOverride===!0,i=t.fallbackType==="email"||t.fallbackType==="qr"?t.fallbackType:void 0,a=T(r,{type:"ENV_EVAL_START"}),u;try{let f=await e.getClientStatus();if(!Tt(f))return T(a,{type:"ENV_ERROR"});u=f}catch{return T(a,{type:"ENV_ERROR"})}let p=o===!0?"fallback":u.recommendedFlow,g={recommendedFlow:p,mode:n,...p==="fallback"&&i!=null&&{fallbackType:i}};return T(a,{type:"ENV_RESOLVED",payload:g})}function Pr(t){return T(t,{type:"START_AUTH"})!==t}function so(t,e,r,n){let o=T(t,{type:"START_AUTH"});return e==="register"?r.register(n):r.authenticate(n),o}function ao(t,e,r){let n=t;n!=="ENROLLMENT_READY"&&(n=T(n,{type:"ENROLLMENT_READY_SET",payload:{ticketId:r.ticketId}}));let o=T(n,{type:"START_ENROLL"});return e.enroll(r),o}function wr(t,e,r,n,o){return t!==e?null:T(t,{type:o==="success"?r:n})}var lo={email:{type:"AUTH_FALLBACK_EMAIL"},qr:{type:"AUTH_FALLBACK_QR"},generic:{type:"AUTH_FALLBACK"}};function uo(t,e){return T(t,lo[e==="email"?"email":e==="qr"?"qr":"generic"])}var I={envEvalStart(t){return T(t,{type:"ENV_EVAL_START"})},evaluateEnv(t){return Nr(t)},startAuth(t,e,r,n){return so(t,e,r,n)},handleAuthOutcome(t,e){return wr(t,"AUTHENTICATING","AUTH_SUCCESS","AUTH_ERROR",e)},handleFallback(t,e){return uo(t,e)},tabChange(t,e){return T(t,{type:"TAB_CHANGE",payload:{tab:e}})},reset(t){return T(t,{type:"RESET"})},startEnrollment(t,e,r){return ao(t,e,r)},handleEnrollOutcome(t,e){return wr(t,"ENROLLING","ENROLL_SUCCESS","ENROLL_ERROR",e)},enrollRetry(t){return T(t,{type:"ENROLL_RETRY"})}};function W(t){return t==null||t.trim()===""?"":t.trim()}function M(t){let e=W(t);return e===""?null:e}function Be(t){if(t==null)return!1;let e=t.trim().toLowerCase();return e==="true"||e==="1"||e===""}function Ur(t){if(t==null||t.trim()==="")return null;let e=t.trim().toLowerCase();return e==="true"||e==="1"?!0:e==="false"||e==="0"?!1:null}function N(t,e,r){if(t==null||t.trim()==="")return r;let n=t.trim().toLowerCase();return e.includes(n)?n:r}function Br(t,e){if(t==null||t.trim()==="")return;let r=t.trim().toLowerCase();if(e.includes(r))return r}function Pt(t){let e={appId:W(t.getAttribute("app-id")),publishableKey:W(t.getAttribute("publishable-key")),mode:N(t.getAttribute("mode"),ae,ke),externalUserId:M(t.getAttribute("external-user-id")),theme:N(t.getAttribute("theme"),G,Y),action:N(t.getAttribute("action"),ce,we),triggerOnly:Be(t.getAttribute("trigger-only")),buttonVariant:N(t.getAttribute("button-variant"),pe,Pe),buttonLabel:M(t.getAttribute("button-label")),buttonAriaLabel:M(t.getAttribute("button-aria-label")),ticketId:M(t.getAttribute("ticket-id"))};return kt(e)}var $="mellon-root",Fe=".mellon-btn",Ke='[data-mellon-action^="fallback"]',Ve="fallback-email",J="fallback-qr",Ee="TryMellon",Ut="Try Passkey",be="TryMellon, open authentication",Bt="Try Passkey, use this device",F="http://www.w3.org/2000/svg",ye="mellon-modal-wrapper",z="mellon-modal-overlay",_e="mellon-modal-panel",Re="mellon-modal-tabs",Ft="mellon-modal-content",K="cross-device",Kt="fallback-cta",He="mellon-dialog-title",Ae="mellon-dialog-desc",Fr="TryMellon \u2014 Sign in or register",Kr=t=>`${t} \u2014 Sign in or register`,Vr="Pick Register or Sign in to continue.",Hr="Or sign in with",P="mellon-cross-device-wrap",Vt="mellon-modal-separator",Ht="mellon-modal-close-btn",qr="Close dialog",Gr="Try from another device",jr="mellon-cross-device-cta",Yr="Try with QR",Wr="mellon-cross-device-skeleton",$r="mellon-cross-device-error",zr="mellon-cross-device-slot-wrap",Xr="Loading QRs",Qr="QR could not be loaded. Try again.";function Jr(){let t=document.createElementNS(F,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("class","mellon-btn-icon"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round");let e=document.createElementNS(F,"path");e.setAttribute("d","M12 22a10 10 0 0 0 10-10 10 10 0 0 0-20 0 10 10 0 0 0 10 10Z");let r=document.createElementNS(F,"path");r.setAttribute("d","M12 14a2 2 0 0 0 2-2 2 2 0 0 0-2-2 2 2 0 0 0-2 2 2 2 0 0 0 2 2Z");let n=document.createElementNS(F,"path");return n.setAttribute("d","M5 19.05A9 9 0 0 1 3 12a9 9 0 0 1 2-5.05"),t.appendChild(e),t.appendChild(r),t.appendChild(n),t}function co(t,e=Ee,r=be){let n=document.createElement("button");return n.type="button",n.className="mellon-btn",n.setAttribute("aria-label",r),n.disabled=t,n.appendChild(Jr()),n.appendChild(document.createTextNode(e)),n}function po(t,e=Ee,r=be){let n=document.createElement("button");n.type="button",n.className="mellon-btn mellon-btn-pill",n.setAttribute("aria-label",r),n.disabled=t;let o=document.createElement("span");return o.className="mellon-btn-pill-icon-circle",o.setAttribute("aria-hidden","true"),o.appendChild(Jr()),n.appendChild(o),n.appendChild(document.createTextNode(e)),n}function mo(t,e=Ee,r=be){return n=>t==="pill"?po(n,e,r):co(n,e,r)}function go(t){return{variant:t.buttonVariant??"default",label:t.primaryButtonLabel??Ee,ariaLabel:t.primaryButtonAriaLabel??be}}function qt(t){let{variant:e,label:r,ariaLabel:n}=go(t);return mo(e,r,n)(!1)}function fo(t){let{shadowRoot:e}=t,r=e.getElementById($);return r||(r=document.createElement("div"),r.id=$,r.className="mellon-root",e.appendChild(r)),r}function Z(t,e){let r=document.createElement("p");return r.className=t,r.textContent=e,r}function ho(t,e){let r=document.createElement("button");return r.type="button",r.className="mellon-btn mellon-btn-fallback",r.setAttribute("data-mellon-action",t),r.textContent=e,r}var Eo={FALLBACK:{action:"fallback",label:"Continuar"},FALLBACK_EMAIL:{action:Ve,label:"Continuar con email"},FALLBACK_QR:{action:J,label:"Continuar con QR"}};function bo(t){let e=document.createElement("div");e.className="mellon-fallback";let r=document.createElement("p");r.className="mellon-message",r.textContent="Fallback disponible.",e.appendChild(r);let{action:n,label:o}=Eo[t];return e.appendChild(ho(n,o)),e}function yo(t,e){let r=document.createDocumentFragment();switch(t){case"IDLE":case"EVALUATING_ENV":r.appendChild(Z("mellon-loading","Loading\u2026"));break;case"READY_LOGIN":r.appendChild(qt(e));break;case"READY_REGISTER":e.registerSessionReady===!1?r.appendChild(Z("mellon-loading","Preparando registro\u2026")):r.appendChild(qt(e));break;case"READY":r.appendChild(qt(e));break;case"AUTHENTICATING":r.appendChild(Z("mellon-loading","Authenticating\u2026"));break;case"SUCCESS":r.appendChild(Z("mellon-message","Success."));break;case"ERROR":r.appendChild(Z("mellon-message","Something went wrong."));break;case"FALLBACK":case"FALLBACK_EMAIL":case"FALLBACK_QR":r.appendChild(bo(t));break;default:r.appendChild(Z("mellon-loading","Loading\u2026"))}return r}function Gt(t,e,r={}){let n=B(e),o=fo(t),i=yo(n,r);o.replaceChildren(...Array.from(i.childNodes))}function _o(t){return{theme:t.theme,mode:t.mode,buttonVariant:t.buttonVariant,registerSessionReady:t.registerSessionReady,primaryButtonLabel:t.primaryButtonLabel,primaryButtonAriaLabel:t.primaryButtonAriaLabel}}function Ro(t){return{theme:t.theme,mode:t.tab,buttonVariant:"pill",registerSessionReady:t.registerSessionReady,primaryButtonLabel:t.primaryButtonLabel,primaryButtonAriaLabel:t.primaryButtonAriaLabel}}function Zr(t,e){Gt(t,e.state,_o(e))}function en(t,e){Gt(t,e.state,Ro(e))}var tn=".mellon-modal-tabs",jt="data-tab",rn='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',nn='[data-mellon-modal-close="true"]';function on(t){if(t===Ve)return"email";if(t===J)return"qr"}function sn(t,e){let r=n=>{let o=n.target instanceof Element?n.target:null;if(!o)return;let i=o.closest(Ke);if(i instanceof HTMLButtonElement){e.onFallbackClick(on(i.getAttribute("data-mellon-action")));return}o.closest(Fe)&&e.onPrimaryClick()};return t.addEventListener("click",r),()=>t.removeEventListener("click",r)}function an(t,e){let r=n=>{let o=n.target instanceof Element?n.target:null;if(!o)return;if(e.onCloseClick&&o.closest(nn)instanceof HTMLElement){e.onCloseClick();return}let i=o.closest(Ke);if(i instanceof HTMLButtonElement){e.onFallbackClick(on(i.getAttribute("data-mellon-action")));return}if(t.querySelector(tn)?.contains(o)){let p=o.closest(`[${jt}]`)?.getAttribute(jt);if(p==="register"||p==="login"){e.onTabChange(p);return}}if(o.closest(Fe)){e.onPrimaryClick();return}if(e.onOverlayClick){let u=t.querySelector(`.${z}`);u&&o===u&&e.onOverlayClick()}};return t.addEventListener("click",r),()=>t.removeEventListener("click",r)}var ve=`
2
2
  :host {
3
3
  display: block;
4
4
  max-width: 100%;
@@ -113,7 +113,7 @@ function Zn(t){if(t.recommendedFlow==="fallback")return t.fallbackType==="email"
113
113
  @media (prefers-reduced-motion: reduce) {
114
114
  .mellon-btn, .mellon-modal-wrapper { transition: none; }
115
115
  }
116
- `.trim(),sn=typeof ShadowRoot<"u"&&"adoptedStyleSheets"in ShadowRoot.prototype&&typeof CSSStyleSheet<"u"&&"replaceSync"in CSSStyleSheet.prototype;function Yt(){if(!sn)return null;try{let t=new CSSStyleSheet;return t.replaceSync(ve),t}catch{return null}}function Wt(){return ve}var an=`
116
+ `.trim(),ln=typeof ShadowRoot<"u"&&"adoptedStyleSheets"in ShadowRoot.prototype&&typeof CSSStyleSheet<"u"&&"replaceSync"in CSSStyleSheet.prototype;function Yt(){if(!ln)return null;try{let t=new CSSStyleSheet;return t.replaceSync(ve),t}catch{return null}}function Wt(){return ve}var un=`
117
117
  /* Host: full viewport when open, no border (only the inner panel has border). */
118
118
  :host {
119
119
  border: none;
@@ -486,7 +486,7 @@ function Zn(t){if(t.recommendedFlow==="fallback")return t.fallbackType==="email"
486
486
  max-height: calc(100dvh - 4rem);
487
487
  }
488
488
  }
489
- `.trim();function ln(){return ve+`
490
- `+an}function un(){if(!sn)return null;try{let t=new CSSStyleSheet;return t.replaceSync(ve+`
491
- `+an),t}catch{return null}}var $t="https://api.trymellonauth.com",dn="https://api.trymellonauth.com/v1/telemetry";var cn="trymellon_sandbox_session_token_v1",pn="/v1/enrollment-bridge",mn="/v1/auth-bridge";var c=t=>({ok:!0,value:t}),l=t=>({ok:!1,error:t});var qe=class t extends Error{code;details;isTryMellonError=!0;constructor(e,r,n){super(r),this.name="TryMellonError",this.code=e,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,t)}},yo={NOT_SUPPORTED:"WebAuthn is not supported in this environment",USER_CANCELLED:"User cancelled the operation",PASSKEY_NOT_FOUND:"Passkey not found",SESSION_EXPIRED:"Session has expired",NETWORK_FAILURE:"Network request failed",INVALID_ARGUMENT:"Invalid argument provided",TIMEOUT:"Operation timed out",ABORTED:"Operation was aborted",ABORT_ERROR:"Operation aborted by user or timeout",CHALLENGE_MISMATCH:"This link was already used or expired. Please try again from your computer.",TICKET_NOT_FOUND:"Enrollment ticket not found or invalid",TICKET_EXPIRED:"Enrollment ticket has expired",TICKET_ALREADY_USED:"Enrollment ticket was already used",PIN_MISMATCH:"PIN does not match",PIN_LOCKED:"PIN is locked due to too many failed attempts",BRIDGE_SESSION_EXPIRED:"Bridge session has expired",UNKNOWN_ERROR:"An unknown error occurred"};function E(t,e,r){return new qe(t,e??yo[t],r)}function zt(t){return t instanceof qe||typeof t=="object"&&t!==null&&"isTryMellonError"in t&&t.isTryMellonError===!0}function gn(){return E("NOT_SUPPORTED")}function R(t,e){return E("INVALID_ARGUMENT",`Invalid argument: ${t} - ${e}`,{field:t,reason:e})}function fn(t){return E("UNKNOWN_ERROR",`Failed to ${t} credential`,{operation:t})}function Xt(t){return E("NOT_SUPPORTED",`No base64 ${t==="encode"?"encoding":"decoding"} available`,{type:t})}function hn(t,e){try{let r=new URL(t);if(r.protocol!=="https:"&&r.protocol!=="http:")throw R(e,"must use http or https protocol")}catch(r){throw zt(r)?r:R(e,"must be a valid URL")}}function Ge(t,e,r,n){if(!Number.isFinite(t))throw R(e,"must be a finite number");if(t<r||t>n)throw R(e,`must be between ${r} and ${n}`)}function je(t,e){if(typeof t!="string"||t.length===0)throw R(e,"must be a non-empty string");if(!/^[A-Za-z0-9_-]+$/.test(t))throw R(e,"must be a valid base64url string")}var _o={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function X(t){if(typeof t!="string")return"UNKNOWN_ERROR";let e=t.toLowerCase().trim();return{challenge_mismatch:"CHALLENGE_MISMATCH",session_expired:"SESSION_EXPIRED",unauthorized:"SESSION_EXPIRED",validation_error:"INVALID_ARGUMENT",invalid_argument:"INVALID_ARGUMENT",user_not_found:"SESSION_EXPIRED",passkey_not_found:"PASSKEY_NOT_FOUND",ticket_not_found:"TICKET_NOT_FOUND",ticket_expired:"TICKET_EXPIRED",ticket_already_consumed:"TICKET_ALREADY_USED",not_found:"TICKET_NOT_FOUND",expired:"TICKET_EXPIRED",already_consumed:"TICKET_ALREADY_USED",context_mismatch:"CHALLENGE_MISMATCH",challenge_not_found:"CHALLENGE_MISMATCH",invalid_ticket_id:"INVALID_ARGUMENT",invalid_context_hash:"INVALID_ARGUMENT",invalid_ticket_status:"INVALID_ARGUMENT",invalid_config:"INVALID_ARGUMENT",enrollment_not_enabled:"INVALID_ARGUMENT",pin_mismatch:"PIN_MISMATCH",pin_locked:"PIN_LOCKED",bridge_not_enabled:"UNKNOWN_ERROR",bridge_session_expired:"BRIDGE_SESSION_EXPIRED",session_not_found:"BRIDGE_SESSION_EXPIRED"}[e]??"UNKNOWN_ERROR"}function _(t){if(t instanceof DOMException){let e=t.name,r=t.message||"WebAuthn operation failed",n=_o[e]??"UNKNOWN_ERROR";return E(n,r,{originalError:t})}return t instanceof Error?E("UNKNOWN_ERROR",t.message,{originalError:t}):E("UNKNOWN_ERROR","An unknown error occurred",{originalError:t})}function h(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function d(t){return typeof t=="string"}function V(t){return typeof t=="number"&&Number.isFinite(t)}function Ye(t){return typeof t=="boolean"}function ee(t){return Array.isArray(t)}function s(t,e){return l(E("UNKNOWN_ERROR",t,{...e,originalData:e?.originalData}))}function m(t,e){return t[e]}function Ro(t,e){return!h(t)||!d(t.name)||!d(t.id)?s("Invalid API response: challenge.rp must have name and id strings",{originalData:e}):c(!0)}function Ao(t,e){return!h(t)||!d(t.id)||!d(t.name)||!d(t.displayName)?s("Invalid API response: challenge.user must have id, name, displayName strings",{originalData:e}):c(!0)}function vo(t,e){if(!ee(t))return s("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let r of t)if(!h(r)||r.type!=="public-key"||!V(r.alg))return s("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});return c(!0)}function We(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"session_id");if(!d(e))return s("Invalid API response: session_id must be string",{field:"session_id",originalData:t});let r=m(t,"challenge");if(!h(r))return s("Invalid API response: challenge must be object",{field:"challenge",originalData:t});let n=Ro(m(r,"rp"),t);if(!n.ok)return n;let o=Ao(m(r,"user"),t);if(!o.ok)return o;let i=m(r,"challenge");if(!d(i))return s("Invalid API response: challenge.challenge must be string",{originalData:t});let a=vo(m(r,"pubKeyCredParams"),t);if(!a.ok)return a;let u=r.timeout;if(u!==void 0&&!V(u))return s("Invalid API response: challenge.timeout must be number",{originalData:t});let p=r.excludeCredentials;if(p!==void 0){if(!ee(p))return s("Invalid API response: excludeCredentials must be array",{originalData:t});for(let f of p)if(!h(f)||f.type!=="public-key"||!d(f.id))return s("Invalid API response: excludeCredentials items must have id and type",{originalData:t})}let g=r.authenticatorSelection;return g!==void 0&&!h(g)?s("Invalid API response: authenticatorSelection must be object",{originalData:t}):c({session_id:e,challenge:{rp:r.rp,user:r.user,challenge:i,pubKeyCredParams:r.pubKeyCredParams,...u!==void 0&&{timeout:u},...p!==void 0&&{excludeCredentials:p},...g!==void 0&&{authenticatorSelection:g}}})}function Qt(t,e){if(!h(t))return s("Invalid API response: user must be object",{field:"user",originalData:e});let r=m(t,"user_id"),n=m(t,"external_user_id");if(!d(r)||!d(n))return s("Invalid API response: user must have user_id and external_user_id strings",{originalData:e});let o=t.email,i=t.metadata;return o!==void 0&&!d(o)?s("Invalid API response: user.email must be string",{originalData:e}):i!==void 0&&(typeof i!="object"||i===null)?s("Invalid API response: user.metadata must be object",{originalData:e}):c({user_id:r,external_user_id:n,...o!==void 0&&{email:o},...i!==void 0&&{metadata:i}})}function Jt(t){let e=We(t);return e.ok?c({session_id:e.value.session_id,challenge:e.value.challenge}):e}function Zt(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"session_id");if(!d(e))return s("Invalid API response: session_id must be string",{field:"session_id",originalData:t});let r=m(t,"challenge");if(!h(r))return s("Invalid API response: challenge must be object",{field:"challenge",originalData:t});let n=m(r,"challenge"),o=m(r,"rpId"),i=r.allowCredentials;if(!d(n))return s("Invalid API response: challenge.challenge must be string",{originalData:t});if(!d(o))return s("Invalid API response: challenge.rpId must be string",{originalData:t});if(i!==void 0&&!ee(i))return s("Invalid API response: allowCredentials must be array",{originalData:t});if(i){for(let p of i)if(!h(p)||p.type!=="public-key"||!d(p.id))return s("Invalid API response: allowCredentials items must have id and type",{originalData:t})}let a=r.timeout;if(a!==void 0&&!V(a))return s("Invalid API response: challenge.timeout must be number",{originalData:t});let u=r.userVerification;return u!==void 0&&!["required","preferred","discouraged"].includes(String(u))?s("Invalid API response: userVerification must be required|preferred|discouraged",{originalData:t}):c({session_id:e,challenge:{challenge:n,rpId:o,allowCredentials:i??[],...a!==void 0&&{timeout:a},...u!==void 0&&{userVerification:u}}})}function er(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"credential_id"),r=m(t,"status"),n=m(t,"session_token"),o=m(t,"user");if(!d(e))return s("Invalid API response: credential_id must be string",{field:"credential_id",originalData:t});if(!d(r))return s("Invalid API response: status must be string",{field:"status",originalData:t});if(!d(n))return s("Invalid API response: session_token must be string",{field:"session_token",originalData:t});let i=Qt(o,t);if(!i.ok)return l(i.error);let a=t.redirect_url;return a!==void 0&&!d(a)?s("Invalid API response: redirect_url must be string",{originalData:t}):c({credential_id:e,status:r,session_token:n,user:i.value,...a!==void 0&&{redirect_url:a}})}function tr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"authenticated"),r=m(t,"session_token"),n=m(t,"user"),o=m(t,"signals");if(!Ye(e))return s("Invalid API response: authenticated must be boolean",{field:"authenticated",originalData:t});if(!d(r))return s("Invalid API response: session_token must be string",{field:"session_token",originalData:t});let i=Qt(n,t);if(!i.ok)return l(i.error);if(o!==void 0&&!h(o))return s("Invalid API response: signals must be object",{originalData:t});let a=t.redirect_url;return a!==void 0&&!d(a)?s("Invalid API response: redirect_url must be string",{originalData:t}):c({authenticated:e,session_token:r,user:i.value,signals:o,...a!==void 0&&{redirect_url:a}})}function rr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"valid"),r=m(t,"user_id"),n=m(t,"external_user_id"),o=m(t,"tenant_id"),i=m(t,"app_id");return Ye(e)?d(r)?d(n)?d(o)?d(i)?c({valid:e,userId:r,externalUserId:n,tenantId:o,appId:i}):s("Invalid API response: app_id must be string",{field:"app_id",originalData:t}):s("Invalid API response: tenant_id must be string",{field:"tenant_id",originalData:t}):s("Invalid API response: external_user_id must be string",{field:"external_user_id",originalData:t}):s("Invalid API response: user_id must be string",{field:"user_id",originalData:t}):s("Invalid API response: valid must be boolean",{field:"valid",originalData:t})}function nr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=t.session_token??t.sessionToken;if(!d(e))return s("Invalid API response: session_token/sessionToken must be string",{field:"session_token",originalData:t});let r=t.redirect_url;return r!==void 0&&!d(r)?s("Invalid API response: redirect_url must be string",{originalData:t}):c({sessionToken:e,...r!==void 0&&{redirectUrl:r}})}var To=["pending_passkey","pending_data","completed"],So=["pending_data","completed"];function or(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"session_id"),r=m(t,"onboarding_url"),n=m(t,"expires_in");return d(e)?d(r)?V(n)?c({session_id:e,onboarding_url:r,expires_in:n}):s("Invalid API response: expires_in must be number",{field:"expires_in",originalData:t}):s("Invalid API response: onboarding_url must be string",{field:"onboarding_url",originalData:t}):s("Invalid API response: session_id must be string",{field:"session_id",originalData:t})}function ir(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"status"),r=m(t,"onboarding_url"),n=m(t,"expires_in");return!d(e)||!To.includes(e)?s("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:t}):d(r)?V(n)?c({status:e,onboarding_url:r,expires_in:n}):s("Invalid API response: expires_in must be number",{originalData:t}):s("Invalid API response: onboarding_url must be string",{originalData:t})}function sr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"session_id"),r=m(t,"status"),n=m(t,"onboarding_url");if(!d(e))return s("Invalid API response: session_id must be string",{field:"session_id",originalData:t});if(r!=="pending_passkey")return s("Invalid API response: status must be pending_passkey",{field:"status",originalData:t});if(!d(n))return s("Invalid API response: onboarding_url must be string",{originalData:t});let o=t.challenge,i;if(o!==void 0){let a=Co(o);if(!a.ok)return a;i=a.value}return c({session_id:e,status:"pending_passkey",onboarding_url:n,...i!==void 0&&{challenge:i}})}function Co(t){if(!h(t))return s("Invalid API response: challenge must be object",{originalData:t});let e=m(t,"rp"),r=m(t,"user"),n=m(t,"challenge"),o=m(t,"pubKeyCredParams");if(!h(e)||!d(e.name)||!d(e.id))return s("Invalid API response: challenge.rp must have name and id",{originalData:t});if(!h(r)||!d(r.id)||!d(r.name)||!d(r.displayName))return s("Invalid API response: challenge.user must have id, name, displayName",{originalData:t});if(!d(n))return s("Invalid API response: challenge.challenge must be string",{originalData:t});if(!ee(o))return s("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:t});for(let i of o)if(!h(i)||i.type!=="public-key"||!V(i.alg))return s("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:t});return c({rp:e,user:r,challenge:n,pubKeyCredParams:o})}function ar(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"session_id"),r=m(t,"status"),n=m(t,"user_id"),o=m(t,"tenant_id");return d(e)?!d(r)||!So.includes(r)?s("Invalid API response: status must be pending_data|completed",{originalData:t}):d(n)?d(o)?c({session_id:e,status:r,user_id:n,tenant_id:o}):s("Invalid API response: tenant_id must be string",{originalData:t}):s("Invalid API response: user_id must be string",{originalData:t}):s("Invalid API response: session_id must be string",{originalData:t})}function lr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"session_id"),r=m(t,"status"),n=m(t,"user_id"),o=m(t,"tenant_id"),i=m(t,"session_token");return d(e)?r!=="completed"?s("Invalid API response: status must be completed",{originalData:t}):!d(n)||!d(o)||!d(i)?s("Invalid API response: user_id, tenant_id, session_token must be strings",{originalData:t}):c({session_id:e,status:"completed",user_id:n,tenant_id:o,session_token:i}):s("Invalid API response: session_id must be string",{originalData:t})}function $e(t){return t==null?c(void 0):h(t)&&Object.keys(t).length===0?c(void 0):s("Invalid API response: expected empty body (204)",{originalData:t})}function Io(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.challenge=="string"&&e.rp!=null&&typeof e.rp=="object"&&e.user!=null&&typeof e.user=="object"&&Array.isArray(e.pubKeyCredParams)}function Lo(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.challenge=="string"&&typeof e.rpId=="string"}function ze(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e="resultado"in t&&h(t.resultado)?t.resultado:t,r=e.session_id,n=e.qr_url,o=e.expires_at,i=e.polling_token;if(!d(r)||!d(n)||!d(o)||!d(i))return s("Invalid API response: missing required fields",{originalData:t});let a={session_id:r,qr_url:n,expires_at:o,polling_token:i};return e.external_user_id!==void 0&&d(e.external_user_id)&&(a.external_user_id=e.external_user_id),c(a)}function ur(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e="resultado"in t&&h(t.resultado)?t.resultado:t,r=e.status;if(!d(r)||!["pending","authenticated","completed"].includes(r))return s("Invalid API response: invalid status",{originalData:t});let n=e.user_id,o=e.session_token,i=e.redirect_url;return n!==void 0&&!d(n)?s("Invalid API response: user_id must be a string when present",{originalData:t}):o!==void 0&&!d(o)?s("Invalid API response: session_token must be a string when present",{originalData:t}):i!==void 0&&!d(i)?s("Invalid API response: redirect_url must be a string when present",{originalData:t}):c({status:r,user_id:n,session_token:o,redirect_url:i})}function dr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=t.type,r=e==="registration"?"registration":"auth",n=t.options;if(!h(n))return s("Invalid API response: options are required",{originalData:t});let o=200,i=En(t.approval_context,o),a=En(t.application_name,o);if(i===!1||a===!1)return s("Invalid API response: approval_context/application_name must be string max 200 chars",{originalData:t});let u={};return typeof i=="string"&&(u.approval_context=i),typeof a=="string"&&(u.application_name=a),r==="registration"?Io(n)?c({type:"registration",options:n,...u}):s("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:t}):Lo(n)?c({type:"auth",options:n,...u}):s("Invalid API response: auth options must have challenge and rpId",{originalData:t})}function En(t,e){if(t!=null)return typeof t!="string"||t.length>e?!1:t}function cr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"challenge"),r=m(t,"recovery_session_id");return h(e)?d(r)?c({challenge:e,recovery_session_id:r}):s("Invalid API response: recovery_session_id must be string",{field:"recovery_session_id",originalData:t}):s("Invalid API response: challenge must be object",{field:"challenge",originalData:t})}function pr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"status"),r=m(t,"session_token"),n=m(t,"user"),o=m(t,"credential_id");if(!d(e))return s("Invalid API response: status must be string",{field:"status",originalData:t});if(!d(r))return s("Invalid API response: session_token must be string",{field:"session_token",originalData:t});if(!d(o))return s("Invalid API response: credential_id must be string",{field:"credential_id",originalData:t});if(!h(n))return s("Invalid API response: user must be object",{field:"user",originalData:t});let i=m(n,"user_id");if(!d(i))return s("Invalid API response: user.user_id must be string",{field:"user.user_id",originalData:t});let u=t.redirect_url;if(u!==void 0&&!d(u))return s("Invalid API response: redirect_url must be string",{field:"redirect_url",originalData:t});let p=n;return c({status:e,session_token:r,credential_id:o,user:{user_id:i,external_user_id:d(p.external_user_id)?p.external_user_id:void 0,email:d(p.email)?p.email:void 0,metadata:h(p.metadata)?p.metadata:void 0},...u!==void 0&&{redirect_url:u}})}function mr(t){let e=We(t);return e.ok?c({session_id:e.value.session_id,challenge:e.value.challenge}):e}function Mo(t,e){if(!h(t))return s("Invalid API response: user must be object",{field:"user",originalData:e});let r=m(t,"user_id");if(!d(r))return s("Invalid API response: user.user_id must be string",{originalData:e});let n=t.external_user_id;if(n!==void 0&&!d(n))return s("Invalid API response: user.external_user_id must be string",{originalData:e});let o=t.email;if(o!==void 0&&!d(o))return s("Invalid API response: user.email must be string",{originalData:e});let i=t.metadata;return i!==void 0&&(typeof i!="object"||i===null)?s("Invalid API response: user.metadata must be object",{originalData:e}):c({user_id:r,...n!==void 0&&{external_user_id:n},...o!==void 0&&{email:o},...i!==void 0&&{metadata:i}})}function gr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"credential_id"),r=m(t,"status"),n=m(t,"session_token"),o=m(t,"user");if(!d(e))return s("Invalid API response: credential_id must be string",{field:"credential_id",originalData:t});if(!d(r))return s("Invalid API response: status must be string",{field:"status",originalData:t});if(!d(n))return s("Invalid API response: session_token must be string",{field:"session_token",originalData:t});let i=Mo(o,t);return i.ok?c({credential_id:e,status:r,session_token:n,user:i.value}):i}var Oo=["pending","pin_verified","pin_locked","completed"];function fr(t){if(!h(t))return s("Invalid bridge context response: expected object",{originalData:t});let e=m(t,"type");if(e!=="auth"&&e!=="registration")return s('Invalid bridge context response: type must be "auth" or "registration"',{field:"type",expected:"auth | registration",originalData:t});let r=m(t,"options");if(!h(r))return s("Invalid bridge context response: options must be object",{field:"options",originalData:t});let n=t.application_name;return n!==void 0&&!d(n)?s("Invalid bridge context response: application_name must be string",{field:"application_name",originalData:t}):c({type:e,options:r,...n!==void 0&&{application_name:n}})}function hr(t){if(!h(t))return s("Invalid bridge verify response: expected object",{originalData:t});let e=m(t,"session_id");if(!d(e)||e.trim()==="")return s("Invalid bridge verify response: session_id must be non-empty string (UUID expected)",{field:"session_id",originalData:t});let r=t.challenge;if(r!==void 0&&!d(r))return s("Invalid bridge verify response: challenge must be string when present",{field:"challenge",originalData:t});let n=t.registration_options;if(n!==void 0&&!h(n))return s("Invalid bridge verify response: registration_options must be object when present",{field:"registration_options",originalData:t});let o=t.authentication_options;return o!==void 0&&!h(o)?s("Invalid bridge verify response: authentication_options must be object when present",{field:"authentication_options",originalData:t}):c({session_id:e,...r!==void 0&&{challenge:r},...n!==void 0&&{registration_options:n},...o!==void 0&&{authentication_options:o}})}function Er(t){if(!h(t))return s("Invalid bridge complete enrollment response: expected object",{originalData:t});let e=m(t,"credential_id"),r=m(t,"entity_id"),n=m(t,"user_id"),o=m(t,"session_token");return d(e)?d(r)?d(n)?d(o)?c({credential_id:e,entity_id:r,user_id:n,session_token:o}):s("Invalid bridge complete enrollment response: session_token must be string",{field:"session_token",originalData:t}):s("Invalid bridge complete enrollment response: user_id must be string",{field:"user_id",originalData:t}):s("Invalid bridge complete enrollment response: entity_id must be string",{field:"entity_id",originalData:t}):s("Invalid bridge complete enrollment response: credential_id must be string",{field:"credential_id",originalData:t})}function br(t){if(!h(t))return s("Invalid bridge complete auth response: expected object",{originalData:t});let e=m(t,"session_token");return d(e)?c({session_token:e}):s("Invalid bridge complete auth response: session_token must be string",{field:"session_token",originalData:t})}function yr(t){if(!h(t))return s("Invalid bridge status response: expected object",{originalData:t});let e=m(t,"status");if(typeof e!="string"||!Oo.includes(e))return s("Invalid bridge status response: status must be one of pending, pin_verified, pin_locked, completed",{field:"status",originalData:t});let r=t.ts;return r!==void 0&&!d(r)?s("Invalid bridge status response: ts must be string when present",{field:"ts",originalData:t}):c({status:e,...r!==void 0&&{ts:r}})}var Xe=class{constructor(e,r,n={}){this.httpClient=e;this.baseUrl=r;this.defaultHeaders=n}mergeHeaders(e){return{...this.defaultHeaders,...e}}async post(e,r,n,o){let i=`${this.baseUrl}${e}`,a=await this.httpClient.post(i,r,this.mergeHeaders(o));return a.ok?n(a.value):l(a.error)}async get(e,r,n){let o=`${this.baseUrl}${e}`,i=await this.httpClient.get(o,this.mergeHeaders(n));return i.ok?r(i.value):l(i.error)}async startRegister(e){return this.post("/v1/passkeys/register/start",e,Jt)}async startAuth(e){return this.post("/v1/passkeys/auth/start",e,Zt)}async finishRegister(e){return this.post("/v1/passkeys/register/finish",e,er)}async finishAuthentication(e){return this.post("/v1/passkeys/auth/finish",e,tr)}async validateSession(e){return this.get("/v1/sessions/validate",rr,{Authorization:`Bearer ${e}`})}async startEmailFallback(e){let r=`${this.baseUrl}/v1/fallback/email/start`,n=await this.httpClient.post(r,{userId:e.userId,email:e.email},this.mergeHeaders());return n.ok?c(void 0):l(n.error)}async verifyEmailCode(e){let r={userId:e.userId,code:e.code};return e.successUrl&&(r.success_url=e.successUrl),this.post("/v1/fallback/email/verify",r,nr)}async startOnboarding(e){return this.post("/v1/onboarding/start",e,or)}async getOnboardingStatus(e){return this.get(`/v1/onboarding/${e}/status`,ir)}async getOnboardingRegister(e){return this.get(`/v1/onboarding/${e}/register`,sr)}async registerOnboardingPasskey(e,r){return this.post(`/v1/onboarding/${e}/register-passkey`,r,ar)}async completeOnboarding(e,r){return this.post(`/v1/onboarding/${e}/complete`,r,lr)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},ze)}async initCrossDeviceRegistration(e){let r=typeof e?.externalUserId=="string"?e.externalUserId.trim():"",n=r.length>0?{external_user_id:r}:{};return this.post("/v1/auth/cross-device/init-registration",n,ze)}async getCrossDeviceStatus(e,r){let n={};return typeof r=="string"&&r.length>0&&(n["X-Polling-Token"]=r),this.get(`/v1/auth/cross-device/status/${e}`,ur,Object.keys(n).length>0?n:void 0)}async getCrossDeviceContext(e){return this.get(`/v1/auth/cross-device/context/${e}`,dr)}async verifyCrossDeviceAuth(e){return this.post("/v1/auth/cross-device/verify",e,$e)}async verifyCrossDeviceRegistration(e){return this.post("/v1/auth/cross-device/verify-registration",e,$e)}async verifyAccountRecoveryOtp(e,r){return this.post("/v1/users/recovery/verify",{external_id:e,otp:r},cr)}async completeAccountRecovery(e,r){return this.post("/v1/users/recovery/complete",{recovery_session_id:e,credential:r},pr)}async startEnrollment(e,r,n){return this.post("/v1/enrollment/register/options",{ticket_id:e,context_hash:r},mr,n)}async finishEnrollment(e,r,n){return this.post("/v1/enrollment/register",{...r,ticket_id:e},gr,n)}bridgePrefix(e){return e==="enrollment"?pn:mn}async getBridgeContext(e,r,n){return this.get(`${this.bridgePrefix(r)}/context/${e}`,fr,n)}async verifyBridgePin(e,r,n,o){return this.post(`${this.bridgePrefix(n)}/verify/${e}`,{pin:r},hr,o)}async completeBridgeEnrollment(e,r){return this.post(`${this.bridgePrefix("enrollment")}/complete`,e,Er,r)}async completeBridgeAuth(e,r){return this.post(`${this.bridgePrefix("auth")}/complete`,e,br,r)}getBridgeStatusUrl(e,r){return`${this.baseUrl}${this.bridgePrefix(r)}/status/${e}`}async getBridgeStatus(e,r,n){return this.get(`${this.bridgePrefix(r)}/status/${e}`,yr,n)}};function xo(t){return typeof t=="object"&&t!==null&&t.ok===!0&&"resultado"in t}function _n(t){if(typeof t!="object"||t===null)return!1;let e=t;if(e.ok!==!1||!e.error||typeof e.error!="object")return!1;let r=e.error;return typeof r.code=="string"&&typeof r.message=="string"}function bn(t,e){if(_n(t))return{message:t.error.message,code:X(t.error.code)};let r=t,n=r?.error;if(typeof n=="object"&&n!==null&&"code"in n&&typeof n.code=="string")return{message:n.message??r?.message??e,code:X(n.code)};let o=r?.message??e,i=r?.error,a=typeof i=="string"?X(i):i===void 0?"NETWORK_FAILURE":X(String(i));return{message:o,code:a}}function ko(){if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();throw new Error("Web Crypto API is required but not available.")}function yn(t,e){let r=e*Math.pow(2,t);return Math.min(r,3e4)}function Do(t,e){return t!=="GET"?!1:e>=500||e===429}var Qe=class{constructor(e,r=0,n=1e3,o){this.timeoutMs=e;this.maxRetries=r;this.retryDelayMs=n;this.logger=o}async get(e,r){return this.request(e,{method:"GET",headers:r})}async post(e,r,n){return this.request(e,{method:"POST",body:JSON.stringify(r),headers:{"Content-Type":"application/json",...n}})}async request(e,r){let n=(r.method??"GET").toUpperCase(),o=ko(),i=new Headers(r.headers);i.set("X-Request-Id",o),this.logger&&this.logger.debug("request",{requestId:o,url:e,method:n});let a;for(let u=0;u<=this.maxRetries;u++)try{let p=new AbortController,g=setTimeout(()=>p.abort(),this.timeoutMs);try{let f=await fetch(e,{...r,headers:i,signal:p.signal});if(!f.ok){let S;try{S=await f.json()}catch{}let{message:v,code:L}=bn(S,f.statusText),C=E(L,v,{requestId:o,status:f.status,statusText:f.statusText,data:S});if(Do(n,f.status)&&u<this.maxRetries){a=C,clearTimeout(g),await new Promise(Rt=>setTimeout(Rt,yn(u,this.retryDelayMs)));continue}return l(C)}if(f.status===204)return c(void 0);if(f.headers.get("content-length")==="0")return c(void 0);let b=await f.json();if(xo(b))return c(b.resultado);let A=b;if(typeof b=="object"&&b!==null&&A.ok===!0&&!("resultado"in A))return c(void 0);if(_n(b)){let{message:S,code:v}=bn(b,f.statusText);return l(E(v,S,{requestId:o,status:f.status,statusText:f.statusText,data:b}))}return c(b)}finally{clearTimeout(g)}}catch(p){if(a=p,n==="GET"&&u<this.maxRetries)await new Promise(f=>setTimeout(f,yn(u,this.retryDelayMs)));else break}return a instanceof Error&&a.name==="AbortError"?l(E("TIMEOUT","Request timed out",{requestId:o})):l(E("NETWORK_FAILURE",a instanceof Error?a.message:"Request failed",{requestId:o,cause:a}))}};function U(t){let e=new Uint8Array(t),r=Array.from(e,o=>String.fromCharCode(o)).join("");if(typeof globalThis.btoa>"u")throw Xt("encode");return globalThis.btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function No(t){if(typeof globalThis.atob>"u")throw Xt("decode");let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4,n=r===0?e:e+"=".repeat(4-r),o=globalThis.atob(n);return Uint8Array.from(o,i=>i.charCodeAt(0))}function te(t){return No(t).buffer}function Rn(t){return t!==null&&typeof t=="object"&&"clientDataJSON"in t&&t.clientDataJSON instanceof ArrayBuffer}function x(t){if(!t.response)throw E("UNKNOWN_ERROR","Credential response is missing",{credential:t});let e=t.response;if(!Rn(e))throw E("UNKNOWN_ERROR","Invalid credential response structure",{response:e});if(!("attestationObject"in e))throw E("UNKNOWN_ERROR","Invalid credential response structure for register: attestationObject is missing",{response:e});let r=e.clientDataJSON,n=e.attestationObject;return{id:t.id,rawId:U(t.rawId),response:{clientDataJSON:U(r),attestationObject:U(n)},type:"public-key"}}function re(t){if(!t.response)throw E("UNKNOWN_ERROR","Credential response is missing",{credential:t});let e=t.response;if(!Rn(e))throw E("UNKNOWN_ERROR","Invalid credential response structure",{response:e});if(!("authenticatorData"in e)||!("signature"in e))throw E("UNKNOWN_ERROR","Invalid credential response structure for auth: authenticatorData or signature is missing",{response:e});let r=e.clientDataJSON,n=e.authenticatorData,o=e.signature,i=e.userHandle;return{id:t.id,rawId:U(t.rawId),response:{authenticatorData:U(n),clientDataJSON:U(r),signature:U(o),...i&&{userHandle:U(i)}},type:"public-key"}}function O(t,e="create"){if(!t||typeof t!="object"||!("id"in t)||!("rawId"in t)||!("response"in t))throw fn(e)}function ne(){try{return!(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return!1}}async function Po(){try{return!ne()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?!1:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function Je(){let t=ne(),e=await Po();return{isPasskeySupported:t,platformAuthenticatorAvailable:e,recommendedFlow:t?"passkey":"fallback"}}async function Te(t){let{operation:e,eventEmitter:r,start:n,createOptions:o,invoke:i,finish:a}=t;try{if(r.emit("start",{type:"start",operation:e}),!ne()){let y=gn();return r.emit("error",{type:"error",error:y}),l(y)}let u=await n();if(!u.ok)return r.emit("error",{type:"error",error:u.error}),l(u.error);let p=o(u.value);if(!p.ok)return r.emit("error",{type:"error",error:p.error}),l(p.error);let g=await i(p.value);if(!g){let y=R("credential",`${e==="register"?"creation":"retrieval"} failed`);return r.emit("error",{type:"error",error:y}),l(y)}try{O(g)}catch(y){let b=_(y);return r.emit("error",{type:"error",error:b}),l(b)}let f=await a(u.value,g);return f.ok?c(f.value):(r.emit("error",{type:"error",error:f.error}),l(f.error))}catch(u){let p=_(u);return r.emit("error",{type:"error",error:p}),l(p)}}function P(t,e){try{je(t.challenge,"challenge"),je(t.user.id,"user.id");let r=te(t.challenge),n=te(t.user.id),o={userVerification:"preferred"};t.authenticatorSelection&&(o={...t.authenticatorSelection}),e&&(o={...o,authenticatorAttachment:e});let i={rp:{id:t.rp.id,name:t.rp.name},user:{id:n,name:t.user.name,displayName:t.user.displayName},challenge:r,pubKeyCredParams:t.pubKeyCredParams,...t.timeout!==void 0&&{timeout:t.timeout},attestation:"none",authenticatorSelection:o,...t.excludeCredentials&&{excludeCredentials:t.excludeCredentials.map(a=>({id:te(a.id),type:a.type,...a.transports&&{transports:a.transports}}))}};return c({publicKey:i})}catch(r){return l(_(r))}}async function An(t,e){let r=P(t);if(!r.ok)return l(r.error);let n={...r.value,...e!==void 0&&{signal:e}},o;try{o=await navigator.credentials.create(n)}catch(i){return l(_(i))}try{O(o,"create")}catch(i){return l(_(i))}try{return c(x(o))}catch(i){return l(_(i))}}function Se(t,e){try{je(t.challenge,"challenge");let r=te(t.challenge);return c({publicKey:{challenge:r,rpId:t.rpId,...t.timeout!==void 0&&{timeout:t.timeout},userVerification:t.userVerification??"preferred",...t.allowCredentials&&{allowCredentials:t.allowCredentials.map(n=>({id:te(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...e!==void 0&&{mediation:e}})}catch(r){return l(_(r))}}async function vn(t,e,r){let n=t.externalUserId??t.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let i=R("externalUserId","must be a non-empty string");return r.emit("error",{type:"error",error:i}),l(i)}let o=await Te({operation:"register",eventEmitter:r,start:()=>e.startRegister({external_user_id:n}),createOptions:i=>P(i.challenge,t.authenticatorType),invoke:async i=>{let a={...i,...t.signal&&{signal:t.signal}};return navigator.credentials.create(a)},finish:async(i,a)=>{let u=await e.finishRegister({session_id:i.session_id,credential:x(a),...t.successUrl&&{success_url:t.successUrl}});return u.ok?c({success:!0,credentialId:u.value.credential_id,credential_id:u.value.credential_id,status:u.value.status,sessionToken:u.value.session_token,user:{userId:u.value.user.user_id,externalUserId:u.value.user.external_user_id,email:u.value.user.email,metadata:u.value.user.metadata},...u.value.redirect_url&&{redirectUrl:u.value.redirect_url}}):l(u.error)}});return o.ok&&r.emit("success",{type:"success",operation:"register",token:o.value.sessionToken,user:o.value.user}),o}async function Tn(t,e,r){let n=t.externalUserId??t.external_user_id,o=n!==void 0&&typeof n=="string"&&n.trim()!=="",i=await Te({operation:"authenticate",eventEmitter:r,start:()=>e.startAuth(o?{external_user_id:n.trim()}:{}),createOptions:a=>Se(a.challenge,t.mediation),invoke:async a=>{let u={...a,...t.signal&&{signal:t.signal}};return navigator.credentials.get(u)},finish:async(a,u)=>{let p=await e.finishAuthentication({session_id:a.session_id,credential:re(u),...t.successUrl&&{success_url:t.successUrl}});return p.ok?c({authenticated:p.value.authenticated,sessionToken:p.value.session_token,user:{userId:p.value.user.user_id,externalUserId:p.value.user.external_user_id,email:p.value.user.email,metadata:p.value.user.metadata},signals:p.value.signals,...p.value.redirect_url&&{redirectUrl:p.value.redirect_url}}):l(p.error)}});return i.ok&&r.emit("success",{type:"success",operation:"authenticate",token:i.value.sessionToken,user:i.value.user}),i}async function Ze(t,e){return e?e.aborted?"aborted":new Promise(r=>{let n=()=>{o(),r("aborted")},o=()=>{clearTimeout(i),e.removeEventListener("abort",n)},i=setTimeout(()=>{o(),r("completed")},t);e.addEventListener("abort",n)}):(await new Promise(r=>setTimeout(r,t)),"completed")}var wo=2e3,Uo=60,et=class{constructor(e){this.apiClient=e}async startFlow(e,r){let n=await this.apiClient.startOnboarding({user_role:e.user_role});if(!n.ok)return l(n.error);let{session_id:o}=n.value;for(let i=0;i<Uo;i++){if(r?.aborted)return l(E("ABORT_ERROR","Operation aborted by user or timeout"));if(await Ze(wo,r)==="aborted")return l(E("ABORT_ERROR","Operation aborted by user or timeout"));let u=await this.apiClient.getOnboardingStatus(o);if(!u.ok)return l(u.error);let p=u.value.status,g=u.value.onboarding_url;if(p==="pending_passkey"){let f=await this.apiClient.getOnboardingRegister(o);if(!f.ok)return l(f.error);let y=f.value;if(!y.challenge)return l(E("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:g}));let b=P(y.challenge);if(!b.ok)return l(b.error);let A;try{A=await navigator.credentials.create(b.value)}catch(C){return l(_(C))}try{O(A,"create")}catch(C){return l(_(C))}let S;try{S=x(A)}catch(C){return l(_(C))}let v=await this.apiClient.registerOnboardingPasskey(o,{credential:S,challenge:y.challenge.challenge});return v.ok?await this.apiClient.completeOnboarding(o,{company_name:e.company_name}):l(v.error)}if(p==="completed")return await this.apiClient.completeOnboarding(o,{company_name:e.company_name})}return l(E("TIMEOUT","Onboarding timed out"))}};var Sn="trymellon_context_hash";var Bo=/^[a-f0-9]{64}$/;function Fo(t){return typeof t=="string"&&Bo.test(t)}function Ko(){let t=new Uint8Array(32);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(t);else throw new Error("crypto.getRandomValues is not available");return Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("")}function Vo(){let t=null;return{getItem(){return t},setItem(e,r){t=r}}}var Cn=Vo();function In(t){let e=t.getItem(Sn);if(e&&Fo(e))return e;let r=Ko();return t.setItem(Sn,r),r}function oe(t){let e=t??Cn;try{return In(e)}catch{return In(Cn)}}var tt=class{constructor(e,r){this.apiClient=e;this.storage=r}async enroll(e){if(e.signal?.aborted)return l(E("ABORT_ERROR","Operation aborted by user or timeout"));let r=this.storage??(typeof sessionStorage<"u"?sessionStorage:void 0),n=oe(r),o=await this.apiClient.startEnrollment(e.ticketId,n);if(!o.ok)return l(o.error);let i=await An(o.value.challenge,e.signal);if(!i.ok)return l(i.error);let a=await this.apiClient.finishEnrollment(e.ticketId,{credential:i.value,context_hash:n});return a.ok?c({sessionToken:a.value.session_token}):l(a.error)}};var Ho=2e3,qo=60,rt=class{constructor(e){this.apiClient=e}async init(){return this.apiClient.initCrossDeviceAuth()}async initRegistration(e){return this.apiClient.initCrossDeviceRegistration(e)}async waitForSession(e,r,n){if(r?.aborted)return l(E("ABORT_ERROR","Operation aborted by user or timeout"));for(let o=0;o<qo;o++){let i=await this.apiClient.getCrossDeviceStatus(e,n);if(!i.ok)return l(i.error);if(i.value.status==="completed"){if(!i.value.session_token||!i.value.user_id)return l(E("UNKNOWN_ERROR","Missing data in completed session"));let u=i.value.redirect_url!=null&&i.value.redirect_url!==""?i.value.redirect_url:void 0;return c({session_token:i.value.session_token,user_id:i.value.user_id,...u!==void 0&&{redirectUrl:u}})}if(await Ze(Ho,r)==="aborted")return l(E("ABORT_ERROR","Operation aborted by user or timeout"))}return l(E("TIMEOUT","Cross-device authentication timed out"))}async approve(e){let r=await this.apiClient.getCrossDeviceContext(e);if(!r.ok)return l(r.error);let n=r.value;return n.type==="registration"?this.executeRegistrationApproval(e,n):this.executeAuthApproval(e,n)}async executeRegistrationApproval(e,r){let n=P(r.options);if(!n.ok)return l(n.error);let o;try{o=await navigator.credentials.create(n.value)}catch(a){return l(_(a))}try{O(o,"create")}catch(a){return l(_(a))}let i;try{i=x(o)}catch(a){return l(_(a))}return this.apiClient.verifyCrossDeviceRegistration({session_id:e,credential:i})}async executeAuthApproval(e,r){let n=Se(r.options);if(!n.ok)return l(n.error);let o;try{o=await navigator.credentials.get(n.value)}catch(a){return l(_(a))}try{O(o,"get")}catch(a){return l(_(a))}let i;try{i=re(o)}catch(a){return l(_(a))}return this.apiClient.verifyCrossDeviceAuth({session_id:e,credential:i})}};var Go=new Set(["pin_verified","pin_locked","completed"]),jo=1500,Yo=3e5;function Ln(t){return Go.has(t)}function nt(t){return t==null||typeof t!="string"||t.trim()===""?l(R("sessionId","must be a non-empty string")):c(t.trim())}function Wo(t){return{sessionToken:t.session_token,credentialId:t.credential_id,userId:t.user_id,entityId:t.entity_id}}function $o(t){return{sessionToken:t.session_token}}async function zo(t,e,r,n){let i=(n.presencePin!=null&&n.presencePin!==""?n.presencePin:null)??(typeof n.onPinRequired=="function"?await n.onPinRequired():null);return i==null||i===""?l(E("INVALID_ARGUMENT","Bridge requires PIN: provide presencePin or onPinRequired in options")):t.verifyBridgePin(e,i,r)}var ot=class{constructor(e,r){this.apiClient=e;this.storage=r}async waitForResult(e,r){let n=nt(e);if(!n.ok)return l(n.error);let o=r?.kind??"enrollment",i=r?.useSse!==!1,a=r?.timeoutMs??Yo,u=async p=>{for(;;){let g=await this.apiClient.getBridgeStatus(n.value,o);if(!g.ok)return l(g.error);if(Ln(g.value.status))return c(g.value);if(Date.now()-p>=a)return l(E("TIMEOUT","Bridge status wait timed out"));await new Promise(f=>setTimeout(f,jo))}};return i&&typeof EventSource<"u"?new Promise(p=>{let g=this.apiClient.getBridgeStatusUrl(n.value,o),f=!1,y=A=>{if(!f){f=!0;try{b.close()}catch{}p(A)}},b;try{b=new EventSource(g)}catch{u(Date.now()).then(y);return}b.onmessage=A=>{try{let S=typeof A.data=="string"?A.data:String(A.data),v=JSON.parse(S);if(v!==null&&typeof v=="object"&&"status"in v&&typeof v.status=="string"){let L=v.status;if(Ln(L)){let C=v.ts;y(c({status:L,...typeof C=="string"&&{ts:C}}))}}}catch{}},b.onerror=()=>{if(!f){try{b.close()}catch{}u(Date.now()).then(y)}}}):u(Date.now())}async getContext(e,r){let n=nt(e);return n.ok?this.apiClient.getBridgeContext(n.value,r):l(n.error)}async verifyPin(e,r,n){let o=nt(e);return o.ok?r==null||typeof r!="string"||r===""?l(R("pin","must be a non-empty string")):this.apiClient.verifyBridgePin(o.value,r,n):l(o.error)}async complete(e,r){let n=nt(e);if(!n.ok)return l(n.error);let o=r?.kind??"enrollment",i=await this.apiClient.getBridgeContext(n.value,o);if(!i.ok)return l(i.error);let a=i.value,u=await zo(this.apiClient,n.value,o,r??{kind:o});if(!u.ok)return l(u.error);let p=u.value;if(r?.signal?.aborted)return l(E("ABORT_ERROR","Operation aborted by user or timeout"));let g=a.type==="registration"?"enrollment":"auth";if(o!==g)return l(E("INVALID_ARGUMENT",`Bridge context type "${a.type}" does not match kind "${o}"`));if(a.type==="registration"){if(!r?.ticketId?.trim()||!r?.entityId?.trim())return l(R("ticketId/entityId","required for enrollment bridge complete"));let L=p.registration_options;if(!L||typeof L!="object")return l(E("UNKNOWN_ERROR","Bridge verify response missing registration_options"));let C=P(L);if(!C.ok)return l(C.error);let Rt={...C.value,...r.signal!==void 0&&{signal:r.signal}},At;try{At=await navigator.credentials.create(Rt)}catch(Tt){return l(_(Tt))}try{O(At,"create")}catch(Tt){return l(_(Tt))}let Me=x(At),Qn=this.storage??(typeof sessionStorage<"u"?sessionStorage:void 0),Jn=oe(Qn),vt=await this.apiClient.completeBridgeEnrollment({session_id:n.value,ticket_id:r.ticketId,entity_id:r.entityId,context_hash:Jn,registration_response:{id:Me.id,rawId:Me.rawId,response:Me.response,type:Me.type}});return vt.ok?c(Wo(vt.value)):l(vt.error)}let f=p.authentication_options;if(!f||typeof f!="object")return l(E("UNKNOWN_ERROR","Bridge verify response missing authentication_options"));let y=Se(f);if(!y.ok)return l(y.error);let b={...y.value,...r?.signal!==void 0&&{signal:r.signal}},A;try{A=await navigator.credentials.get(b)}catch(L){return l(_(L))}try{O(A,"get")}catch(L){return l(_(L))}let S=re(A),v=await this.apiClient.completeBridgeAuth({session_id:n.value,credential:{id:S.id,rawId:S.rawId,response:S.response,type:S.type}});return v.ok?c($o(v.value)):l(v.error)}};var it=class{handlers;constructor(){this.handlers=new Map}on(e,r){let n=this.handlers.get(e);return n||(n=new Set,this.handlers.set(e,n)),n.add(r),()=>{this.off(e,r)}}off(e,r){let n=this.handlers.get(e);n&&(n.delete(r),n.size===0&&this.handlers.delete(e))}emit(e,r){let n=this.handlers.get(e);if(n)for(let o of n)try{o(r)}catch(i){console.warn("[TryMellon] Event handler threw:",i)}}removeAllListeners(){this.handlers.clear()}};function Mn(t){return{async send(e){let r=JSON.stringify(e);if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"){navigator.sendBeacon(t,r);return}typeof fetch<"u"&&await fetch(t,{method:"POST",body:r,headers:{"Content-Type":"application/json"},keepalive:!0})}}}function _r(t,e){return{event:t,latencyMs:e,ok:!0}}var st=class{constructor(e,r,n,o,i){this.apiClient=e;this.eventEmitter=r;this.sandbox=n;this.sandboxToken=o;this.telemetrySender=i}async sandboxAuthResult(e,r){let n="externalUserId"in r?r.externalUserId??r.external_user_id??"sandbox":r.external_user_id??r.externalUserId??"sandbox",o=typeof n=="string"?n:"sandbox";return e==="register"?Promise.resolve(c({success:!0,credentialId:"",status:"sandbox",sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:o}})):Promise.resolve(c({authenticated:!0,sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:o}}))}async register(e){if(this.sandbox){let o=await this.sandboxAuthResult("register",e);return o.ok&&this.eventEmitter.emit("success",{type:"success",operation:"register",token:o.value.sessionToken,user:o.value.user}),o}let r=Date.now(),n=await vn(e,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(_r("register",Date.now()-r)).catch(o=>console.warn("[TryMellon] Telemetry send failed",o)),n}async authenticate(e){if(this.sandbox){let o=await this.sandboxAuthResult("authenticate",e);return o.ok&&this.eventEmitter.emit("success",{type:"success",operation:"authenticate",token:o.value.sessionToken,user:o.value.user}),o}let r=Date.now(),n=await Tn(e,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(_r("authenticate",Date.now()-r)).catch(o=>console.warn("[TryMellon] Telemetry send failed",o)),n}};async function On(t,e,r){let n=t.externalUserId??t.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let i=R("externalUserId","must be a non-empty string");return r.emit("error",{type:"error",error:i}),l(i)}if(!t.otp||typeof t.otp!="string"||t.otp.trim().length!==6){let i=R("otp","must be a 6-digit string");return r.emit("error",{type:"error",error:i}),l(i)}let o=await Te({operation:"register",eventEmitter:r,start:()=>e.verifyAccountRecoveryOtp(n,t.otp),createOptions:i=>{let a=i.challenge;return!a||typeof a!="object"||!("rp"in a)||!("user"in a)||!("challenge"in a)||!("pubKeyCredParams"in a)?l(R("challenge","invalid recovery challenge structure")):P(a)},invoke:async i=>navigator.credentials.create(i),finish:async(i,a)=>{let u=await e.completeAccountRecovery(i.recovery_session_id,x(a));if(!u.ok)return l(u.error);let{credential_id:p,status:g,session_token:f,user:y,redirect_url:b}=u.value;return c({success:!0,credentialId:p,status:g,sessionToken:f,user:{userId:y.user_id,externalUserId:y.external_user_id,email:y.email,metadata:y.metadata},...b!==void 0&&{redirectUrl:b}})}});return o.ok&&r.emit("success",{type:"success",operation:"register",token:o.value.sessionToken,user:o.value.user}),o}var at=class{constructor(e,r){this.apiClient=e;this.eventEmitter=r}recover(e){return On(e,this.apiClient,this.eventEmitter)}};var lt=class t{sandbox;sandboxToken;apiClient;eventEmitter;telemetrySender;crossDeviceManager;authService;recoveryService;onboarding;enrollmentManager;bridgeManager;contextHashStorage;static validateConfig(e){let{appId:r,publishableKey:n}=e;if(!r||typeof r!="string"||r.trim()==="")throw R("appId","must be a non-empty string");if(!n||typeof n!="string"||n.trim()==="")throw R("publishableKey","must be a non-empty string");let o=e.apiBaseUrl??$t;hn(o,"apiBaseUrl");let i=e.timeoutMs??3e4;Ge(i,"timeoutMs",1e3,3e5),e.maxRetries!==void 0&&Ge(e.maxRetries,"maxRetries",0,10),e.retryDelayMs!==void 0&&Ge(e.retryDelayMs,"retryDelayMs",100,1e4)}static create(e){try{return t.validateConfig(e),c(new t(e))}catch(r){return zt(r)?l(r):l(R("config",r.message))}}constructor(e){this.sandbox=e.sandbox===!0,this.sandboxToken=this.sandbox&&e.sandboxToken!=null&&e.sandboxToken!==""?e.sandboxToken:cn,t.validateConfig(e);let r=e.appId,n=e.publishableKey,o=e.apiBaseUrl??$t,i=e.timeoutMs??3e4,a=e.maxRetries??3,u=e.retryDelayMs??1e3,p=new Qe(i,a,u,e.logger),g=e.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),f={"X-App-Id":r.trim(),Authorization:`Bearer ${n.trim()}`,...g&&{Origin:g}};this.apiClient=new Xe(p,o,f),this.eventEmitter=new it,e.enableTelemetry&&(this.telemetrySender=e.telemetrySender??Mn(e.telemetryEndpoint??dn)),this.authService=new st(this.apiClient,this.eventEmitter,this.sandbox,this.sandboxToken,this.telemetrySender),this.recoveryService=new at(this.apiClient,this.eventEmitter),this.contextHashStorage=e.contextHashStorage,this.onboarding=new et(this.apiClient),this.enrollmentManager=new tt(this.apiClient,this.contextHashStorage),this.crossDeviceManager=new rt(this.apiClient),this.bridgeManager=new ot(this.apiClient,this.contextHashStorage)}get bridge(){return{getContext:(e,r)=>this.bridgeManager.getContext(e,r),verifyPin:(e,r,n)=>this.bridgeManager.verifyPin(e,r,n),complete:(e,r)=>this.bridgeManager.complete(e,r),waitForResult:(e,r)=>this.bridgeManager.waitForResult(e,r)}}static isSupported(){return ne()}async register(e){return this.authService.register(e)}async authenticate(e){return this.authService.authenticate(e)}async enroll(e){this.eventEmitter.emit("start",{type:"start",operation:"enroll"});let r=await this.enrollmentManager.enroll(e);return r.ok?this.eventEmitter.emit("success",{type:"success",operation:"enroll",token:r.value.sessionToken}):this.eventEmitter.emit("error",{type:"error",operation:"enroll",error:r.error}),r}getContextHash(){let e=this.contextHashStorage??(typeof sessionStorage<"u"?sessionStorage:void 0);return oe(e)}async validateSession(e){return this.sandbox&&e===this.sandboxToken?Promise.resolve(c({valid:!0,userId:"sandbox-user",externalUserId:"sandbox",tenantId:"sandbox-tenant",appId:"sandbox-app"})):this.apiClient.validateSession(e)}async getStatus(){return Je()}on(e,r){return this.eventEmitter.on(e,r)}version(){return"2.3.1"}fallback={email:{start:async e=>this.apiClient.startEmailFallback(e),verify:async e=>{let r=await this.apiClient.verifyEmailCode({userId:e.userId,code:e.code,...e.successUrl&&{successUrl:e.successUrl}});return r.ok?c({sessionToken:r.value.sessionToken,...r.value.redirectUrl&&{redirectUrl:r.value.redirectUrl}}):r}}};auth={crossDevice:{init:()=>this.crossDeviceManager.init(),initRegistration:e=>this.crossDeviceManager.initRegistration(e??{}),waitForSession:(e,r,n)=>this.crossDeviceManager.waitForSession(e,r,n),getContext:e=>this.apiClient.getCrossDeviceContext(e),approve:e=>this.crossDeviceManager.approve(e)},recoverAccount:e=>this.recoveryService.recover(e)}};function Rr(t){let e=lt.create({appId:t.appId,publishableKey:t.publishableKey});return!e.ok||e.value==null?null:e.value}function kn(t){if(t==null||typeof t!="object")return!1;let e=t,r=typeof e.authenticate=="function",n=typeof e.register=="function",o=typeof e.on=="function",i=typeof e.enroll=="function",a=typeof e.getContextHash=="function";return r&&n&&o&&i&&a}function Dn(t){return t?{externalUserId:t}:{}}var ut="mellon:open",Ce="mellon:open-request",H="mellon:close",q="mellon:success",dt="mellon:error",ct="mellon:start",Ie="mellon:cancelled",pt="mellon:fallback",mt="mellon:tab-change",Ar="mellon:context-ready";function gt(t,e,r,n){t.dispatchEvent(new CustomEvent(e,{detail:r,bubbles:n.bubbles,composed:n.composed}))}function ft(t){return t==="authenticate"?"login":t==="enroll"?"enroll":"register"}function oi(t){if(t==null||typeof t!="object")return;let e=t,r=e.userId;if(typeof r!="string"||r.length===0)return;let n={userId:r};return typeof e.externalUserId=="string"&&(n.externalUserId=e.externalUserId),typeof e.email=="string"&&(n.email=e.email),e.metadata!=null&&typeof e.metadata=="object"&&!Array.isArray(e.metadata)&&(n.metadata=e.metadata),n}function ii(t){return t!=null&&typeof t=="object"&&t.type==="start"&&(t.operation==="register"||t.operation==="authenticate"||t.operation==="enroll")}function si(t){let e=t;return t!=null&&typeof t=="object"&&e.type==="success"&&typeof e.token=="string"&&(e.operation==="register"||e.operation==="authenticate"||e.operation==="enroll")}function ai(t){return t!=null&&typeof t=="object"&&t.type==="error"}function li(t){return t!=null&&typeof t=="object"&&t.type==="cancelled"&&(t.operation==="register"||t.operation==="authenticate"||t.operation==="enroll")}var vr={subscribe(t,e){if(t==null||e==null)throw new TypeError("eventBridgeAdapter.subscribe: core and host are required");let r=[],n="authenticate",o=!1,i=t.on("start",g=>{if(!ii(g))return;n=g.operation,o=!1;let f={operation:ft(g.operation),...typeof g.nonce=="string"&&{nonce:g.nonce}};gt(e,ct,f,{bubbles:!0,composed:!0})});r.push(i);let a=t.on("success",g=>{if(!si(g)||o||g.token.length===0)return;o=!0;let f=oi(g.user),y={operation:ft(g.operation),token:g.token,...typeof g.nonce=="string"&&{nonce:g.nonce},...f!==void 0&&{user:f},...typeof g.redirectUrl=="string"&&{redirectUrl:g.redirectUrl}};gt(e,q,y,{bubbles:!1,composed:!0})});r.push(a);let u=t.on("error",g=>{if(!ai(g)||o)return;let f=g.error?.code??"UNKNOWN_ERROR",y=X(typeof f=="string"?f:String(f)),b={operation:ft(g.operation??n),code:y,message:typeof g.error?.message=="string"?g.error.message:"Unknown error",...typeof g.nonce=="string"&&{nonce:g.nonce}};gt(e,dt,b,{bubbles:!0,composed:!0})});r.push(u);let p=t.on("cancelled",g=>{if(!li(g))return;let f={operation:ft(g.operation),...typeof g.nonce=="string"&&{nonce:g.nonce}};gt(e,Ie,f,{bubbles:!0,composed:!0})});return r.push(p),function(){for(let f of r)f()}}};function Nn(t){return{isPasskeySupported:t.isPasskeySupported,platformAuthenticatorAvailable:t.platformAuthenticatorAvailable,recommendedFlow:t.recommendedFlow}}function ui(){return{getClientStatus:async()=>{let t=await Je();return Nn(t)}}}function Pn(t){let e=t;if(typeof e.getStatus!="function")return ui();let r=e.getStatus;return{getClientStatus:async()=>{let n=await r();return Nn(n)}}}function wn(t){return new CustomEvent(ut,{detail:t,bubbles:!0,composed:!0})}function Un(t){return new CustomEvent(H,{detail:t,bubbles:!0,composed:!0})}function Bn(t){return new CustomEvent(Ie,{detail:t,bubbles:!0,composed:!0})}function Fn(t){return new CustomEvent(pt,{detail:t,bubbles:!0,composed:!0})}function Kn(t){return new CustomEvent(mt,{detail:t,bubbles:!0,composed:!0})}function Vn(t){return new CustomEvent(Ar,{detail:t,bubbles:!1,composed:!0})}var ht=class{_currentState=k;_lastRenderedState=null;_renderDirty=!0;_pendingOperation="authenticate";_currentNonce=void 0;_envEvalRequestId=0;get currentState(){return this._currentState}setState(e){this._currentState=e,this._renderDirty=!0}invalidateRender(){this._renderDirty=!0}consumeRenderDecision(){return!this._renderDirty&&this._currentState===this._lastRenderedState?!1:(this._lastRenderedState=this._currentState,this._renderDirty=!1,!0)}setPendingOperationFromTab(e){this._pendingOperation=e==="login"?"authenticate":"register"}get pendingOperation(){return this._pendingOperation}setNonce(e){this._currentNonce=e}consumeCancelledDetailIfAuthenticating(){if(this._currentState!=="AUTHENTICATING")return null;let e={operation:this._pendingOperation==="authenticate"?"login":this._pendingOperation,...this._currentNonce!==void 0&&{nonce:this._currentNonce}};return this._currentNonce=void 0,e}handleAuthSuccess(){let e=I.handleAuthOutcome(this._currentState,"success");e!==null&&this.setState(e)}handleAuthError(){let e=I.handleAuthOutcome(this._currentState,"error");e!==null&&this.setState(e)}handleEnrollSuccess(){let e=I.handleEnrollOutcome(this._currentState,"success");e!==null&&this.setState(e)}handleEnrollError(){let e=I.handleEnrollOutcome(this._currentState,"error");e!==null&&this.setState(e)}onStartEvent(e){e?.nonce!==void 0&&(this._currentNonce=e.nonce)}startAuthFromClick(e,r,n){if(!e||!Nr(this._currentState))return;this.setPendingOperationFromTab(r);let o=I.startAuth(this._currentState,r,e,n);this.setState(o)}startEnrollment(e,r){if(!e)return;let n=I.startEnrollment(this._currentState,e,r);this.setState(n)}async runEnvEval(e){let r=++this._envEvalRequestId;this.setState(I.envEvalStart(this._currentState));let n=await I.evaluateEnv({...e,currentState:this._currentState});return r!==this._envEvalRequestId?null:n}reset(){this._currentState=I.reset(this._currentState),this._lastRenderedState=null,this._renderDirty=!0,this._currentNonce=void 0}setStateForRender(e){this._currentState=e,this._renderDirty=!0}};var ie=class extends HTMLElement{_controller=new ht;_unsubscribeBridge=null;_core=null;_lastCoreConfig=null;setState(e){this._controller.setState(e),this.scheduleRenderIfNeeded()}invalidateRender(){this._controller.invalidateRender(),this.scheduleRenderIfNeeded()}scheduleRenderIfNeeded(){this.shadowRoot&&this._controller.consumeRenderDecision()&&this._render()}_emitCancelledIfAuthenticating(){let e=this._controller.consumeCancelledDetailIfAuthenticating();return e?(this.dispatchEvent(Bn(e)),!0):!1}attachCore(e){if(this._core!==null&&this._teardownCore(),e==null){this._core=null,this._controller.reset(),this.scheduleRenderIfNeeded();return}if(!kn(e))throw new Error("[trymellon-auth] attachCore requires a CoreAuthPort-compatible instance.");this._core=e,this._unsubscribeBridge=vr.subscribe(this._core,this),this._attachHostListeners(),this._runEnvEval()}_teardownCore(){this._unsubscribeBridge?.(),this._unsubscribeBridge=null,this.removeEventListener("mellon:start",this._onMellonStart),this.removeEventListener("mellon:success",this._onMellonSuccess),this.removeEventListener("mellon:error",this._onMellonError),this._core=null}_attachHostListeners(){this.removeEventListener("mellon:start",this._onMellonStart),this.removeEventListener("mellon:success",this._onMellonSuccess),this.removeEventListener("mellon:error",this._onMellonError),this.addEventListener("mellon:start",this._onMellonStart),this.addEventListener("mellon:success",this._onMellonSuccess),this.addEventListener("mellon:error",this._onMellonError)}_onMellonSuccess=()=>{this._controller.currentState==="ENROLLING"?this._controller.handleEnrollSuccess():this._controller.handleAuthSuccess(),this.scheduleRenderIfNeeded()};_onMellonError=()=>{this._controller.currentState==="ENROLLING"?this._controller.handleEnrollError():this._controller.handleAuthError(),this.scheduleRenderIfNeeded()};_onMellonStart=e=>{let r=e.detail;this._controller.onStartEvent(r)};startAuthFromClick(){this._core&&this.canStartAuth()&&(this._controller.startAuthFromClick(this._core,this.getTabKind(),this.getCoreAuthOptions()),this.scheduleRenderIfNeeded())}dispatchFallback(e){let r=e!==void 0?{...this.getFallbackDetail(),fallbackType:e}:this.getFallbackDetail();this.dispatchEvent(Fn(r))}async _runEnvEval(){if(!this._core)return;let e={...this.getEnvEvalParams(),envStatusPort:Pn(this._core)},r=await this._controller.runEnvEval(e);r!==null&&(!this._core||!this.isConnected||this.setState(r))}_maybeAutoCreateCoreAndRunEnvEval(){if(this._core!==null)return;let e=this.getCoreConfig();if(!e)return;let r=Rr(e);if(!r){this.attachCore(null);return}this.attachCore(r)}_reconcileCoreFromConfig(){let e=this.getCoreConfig();if(this._lastCoreConfig===null&&e===null||this._lastCoreConfig!==null&&e!==null&&this._lastCoreConfig.appId===e.appId&&this._lastCoreConfig.publishableKey===e.publishableKey)return;if(this._lastCoreConfig=e,e===null){this.attachCore(null);return}let n=Rr(e);this.attachCore(n??null)}disconnectedCallback(){this._teardownCore()}get currentState(){return this._controller.currentState}reset(){this._emitCancelledIfAuthenticating(),this._controller.reset(),this.scheduleRenderIfNeeded()}setStateForRender(e){this._controller.setStateForRender(e),this.scheduleRenderIfNeeded()}};function di(t){if(t==null||t.trim()==="")return Q;let e=t.split(",").map(o=>o.trim()),r=e[0]??Q.register,n=e[1]??Q.login;return{register:r,login:n}}function Et(t){let e={open:Be(t.getAttribute("open")),mode:N(t.getAttribute("mode"),ue,De),tab:N(t.getAttribute("tab"),le,Ne),tabLabels:di(t.getAttribute("tab-labels")),theme:N(t.getAttribute("theme"),G,Y),sessionId:M(t.getAttribute("session-id")),onboardingUrl:M(t.getAttribute("onboarding-url")),isMobileOverride:Pr(t.getAttribute("is-mobile-override")),fallbackType:wr(t.getAttribute("fallback-type"),de),appId:W(t.getAttribute("app-id")),publishableKey:W(t.getAttribute("publishable-key")),appName:M(t.getAttribute("app-name")),dialogTitle:M(t.getAttribute("dialog-title")),dialogDescription:M(t.getAttribute("dialog-description")),externalUserId:M(t.getAttribute("external-user-id")),modalVariant:N(t.getAttribute("modal-variant"),me,Ue)};return Dt(e)}function ci(t){let e=t.querySelector(`.${ye}`);return e||(e=document.createElement("div"),e.className=ye,t.appendChild(e)),e}function pi(t){let e=t.querySelector(`.${z}`);return e||(e=document.createElement("div"),e.className=z,e.setAttribute("aria-hidden","true"),t.appendChild(e)),e}function mi(t){let e=t.querySelector(`.${_e}`);return e||(e=document.createElement("div"),e.className=_e,t.appendChild(e)),e}function gi(t,e){t.setAttribute("role","dialog"),t.setAttribute("aria-modal",e==="modal"?"true":"false"),t.setAttribute("aria-labelledby",He),t.setAttribute("aria-describedby",Ae)}function fi(t,e){let r=t.querySelector(`#${He}`);r||(r=document.createElement("h2"),r.id=He,r.className="mellon-dialog-title",t.insertBefore(r,t.firstChild));let n=e.dialogTitle?.trim()??(e.appName?.trim()?Br(e.appName.trim()):Ur);r.textContent=n;let o=t.querySelector(`#${Ae}`);o||(o=document.createElement("p"),o.id=Ae,o.className="mellon-dialog-desc",t.insertBefore(o,r.nextSibling)),o.textContent=e.dialogDescription?.trim()??Fr}function hi(t){let e=t.querySelector(`.${Ht}`);e||(e=document.createElement("button"),e.type="button",e.className=Ht,e.setAttribute("aria-label",Vr),e.setAttribute("data-mellon-modal-close","true"),e.textContent="\xD7",t.appendChild(e))}function Ei(t,e){let r=t.querySelector(`.${Re}`);if(!r){r=document.createElement("div"),r.className=Re,r.setAttribute("role","tablist");let i=document.createElement("button");i.type="button",i.setAttribute("data-tab","register"),i.setAttribute("role","tab");let a=document.createElement("button");a.type="button",a.setAttribute("data-tab","login"),a.setAttribute("role","tab"),r.appendChild(i),r.appendChild(a);let u=t.querySelector(`#${Ae}`);t.insertBefore(r,u?u.nextSibling:t.firstChild)}let[n,o]=r.querySelectorAll("button");return n&&(n.textContent=e.register),o&&(o.textContent=e.login),r}function Tr(t){let e=t.querySelector(`.${Ft}`);if(!e){e=document.createElement("div"),e.className=Ft;let r=t.querySelector(`.${Re}`);t.insertBefore(e,r?r.nextSibling:t.firstChild)}return e}function bi(){let t=document.createElementNS(F,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("class","mellon-qr-icon"),t.setAttribute("fill","currentColor");let e=document.createElementNS(F,"path");return e.setAttribute("d","M3 3h6v6H3V3zm2 2v2h2V5H5zm8-2h6v6h-6V3zm2 2v2h2V5h-2zM3 15h6v6H3v-6zm2 2v2h2v-2H5zm8-2h6v6h-6v-6zm2 2v2h2v-2h-2zm4-12h2v2h-2V5zm0 8h2v2h-2v-2zm-4 4h2v2h-2v-2zm0-8h2v2h-2V9zm0 4h2v2h-2v-2z"),t.appendChild(e),t}function Hn(){let t=document.createDocumentFragment(),e=document.createElement("div");e.className=qr;let r=document.createElement("p");r.className="mellon-cross-device-cta-text",r.textContent=Hr,e.appendChild(r);let n=document.createElement("button");return n.type="button",n.className="mellon-btn mellon-btn-qr-icon",n.setAttribute("data-mellon-action",J),n.setAttribute("aria-label",Gr),n.appendChild(bi()),e.appendChild(n),t.appendChild(e),t}function yi(){let t=document.createElement("div");t.className=jr,t.setAttribute("aria-live","polite");let e=document.createElement("span");e.textContent=$r;let r=document.createElement("span");return r.className="mellon-qr-dots",r.setAttribute("aria-hidden","true"),t.appendChild(e),t.appendChild(r),t}function _i(){let t=document.createElement("div");return t.className=Yr,t.setAttribute("aria-live","polite"),t.textContent=zr,t}function Ri(t){let e=Tr(t),r=e.querySelector(`.${w}`);if(!r){r=document.createElement("div"),r.className=w,r.setAttribute("data-qr-area-state","default"),r.appendChild(yi()),r.appendChild(_i());let o=document.createElement("div");o.className=Wr;let i=document.createElement("slot");i.name=K,i.appendChild(Hn()),o.appendChild(i),r.appendChild(o),e.appendChild(r)}let n=r.querySelector(`slot[name="${K}"]`);if(!n){let o=document.createElement("slot");return o.name=K,o.appendChild(Hn()),r.appendChild(o),o}return n}function Ai(t){let e=Tr(t);if(e.querySelector(`.${Vt}`))return;let r=document.createElement("div");r.className=Vt,r.setAttribute("aria-hidden","true");let n=document.createElement("span");n.className="mellon-separator-text",n.textContent=Kr,r.appendChild(n);let o=e.querySelector(`.${w}`);e.insertBefore(r,o?o.nextSibling:e.firstChild)}function vi(t){let e=Tr(t),r=e.querySelector("slot:not([name])");if(!r){r=document.createElement("slot");let o=document.createElement("div");o.id=$,o.className="mellon-root",r.appendChild(o),e.appendChild(r)}let n=t.querySelector(`#${$}`);return n||(n=document.createElement("div"),n.id=$,n.className="mellon-root",r.appendChild(n)),n}function Ti(t){let e=t.querySelector(`slot[name="${Kt}"]`);return e||(e=document.createElement("slot"),e.name=Kt,t.appendChild(e)),e}function Si(t,e){let r=t.querySelector(`.${Re}`);if(!r)return;let n=r.querySelector('[data-tab="register"]'),o=r.querySelector('[data-tab="login"]');n&&n.setAttribute("aria-selected",String(e==="register")),o&&o.setAttribute("aria-selected",String(e==="login"))}function Le(t,e){if(t==null||e==null)return;let r=ci(t);r.setAttribute("data-mellon-modal-variant",e.modalVariant),e.mode==="modal"&&pi(r);let n=mi(r);gi(n,e.mode),fi(n,e),hi(n),Ei(n,e.tabLabels),Ri(n),Ai(n),vi(n),Ti(n),Si(n,e.tab)}function Ci(t){return!(t.hidden===!0||t.getAttribute("aria-hidden")==="true")}function qn(t){return Array.from(t.querySelectorAll(en)).filter(r=>Ci(r))}function Gn(t){let e=null,r=null,n=!1;function o(u){if(u.key!=="Tab")return;let p=qn(t);if(p.length===0)return;let g=u.target instanceof Node?u.target:null,f=g?p.indexOf(g):-1,y=p.length-1,b;u.shiftKey?b=f<=0?y:f-1:b=f>=y?0:f+1;let A=p[b];A&&(u.preventDefault(),A.focus())}function i(){if(n)return;e=document.activeElement;let p=qn(t)[0];p&&p.focus(),r=o,t.addEventListener("keydown",r,!0),n=!0}function a(){if(!n)return;r&&(t.removeEventListener("keydown",r,!0),r=null),n=!1;let u=t.getRootNode()?.ownerDocument??document,p=e instanceof HTMLElement&&u.body.contains(e)?e:null;if(p)p.focus();else{let g=u.body,f=g.getAttribute("tabindex");g.setAttribute("tabindex","-1"),g.focus(),f===null?g.removeAttribute("tabindex"):g.setAttribute("tabindex",f)}e=null}return{activate:i,deactivate:a}}var jn=["app-id","publishable-key","mode","external-user-id","theme","action","trigger-only","button-variant","button-label","button-aria-label","ticket-id"],Yn=["open","mode","tab","tab-labels","theme","session-id","onboarding-url","is-mobile-override","fallback-type","app-id","publishable-key","app-name","dialog-title","dialog-description","external-user-id","modal-variant","qr-load-timeout-ms"],bt={wrapper:`.${ye}`,overlay:`.${z}`,panel:`.${_e}`},Wn="user";var Ii={SUCCESS:{reason:"success"},AUTHENTICATING:{reason:"cancel"},ERROR:{reason:"error"}};function Li(t){return Ii[t]??{reason:Wn}}var yt=class extends ie{static get observedAttributes(){return[...Yn]}_parsed=Et(this);_focusTrap=null;_unregisterInteractions=null;_generatedExternalUserId=null;_qrLoadTimeoutId=null;_qrSlotChangeBound=null;_boundEscapeKeydown=e=>{e.key==="Escape"&&this._parsed.open&&(e.preventDefault(),this.open=!1)};connectedCallback(){if(this.addEventListener("keydown",this._boundEscapeKeydown,!0),this.shadowRoot){this._registerInteractions(),this._core!==null&&this._unsubscribeBridge===null&&this.attachCore(this._core);return}let e=this.attachShadow({mode:"open"}),r=un();if(r)e.adoptedStyleSheets=[r];else{let n=document.createElement("style");n.textContent=ln(),e.appendChild(n)}this._parsed=Et(this),Le(e,this._parsed),this._registerInteractions(),this._render(),this._applyModalVisibility(),this._maybeAutoCreateCoreAndRunEnvEval()}_registerInteractions(){this.shadowRoot&&(this._unregisterInteractions?.(),this._unregisterInteractions=on(this.shadowRoot,{onTabChange:e=>{this.dispatchEvent(Kn({tab:e})),this.setAttribute("tab",e)},onPrimaryClick:()=>this.startAuthFromClick(),onFallbackClick:e=>this.dispatchFallback(e),onOverlayClick:()=>{this.open=!1},onCloseClick:()=>{this.open=!1}}))}attributeChangedCallback(e,r,n){if(this.shadowRoot){if(this._parsed=Et(this),e==="open"){if(this._parsed.open&&r!=="true"){this._clearCrossDeviceSlot();let o={timestamp:Date.now()};this.dispatchEvent(wn(o)),this._startQrLoadWait()}if(!this._parsed.open){this._clearQrLoadWait(),this._transitionToIdle();return}}e==="tab"&&(this._emitCancelledIfAuthenticating(),this.setState(I.tabChange(this.currentState,this._parsed.tab))),(e==="app-id"||e==="publishable-key")&&this._reconcileCoreFromConfig(),Le(this.shadowRoot,this._parsed),this._render(),this._applyModalVisibility()}}_clearCrossDeviceSlot(){this.querySelectorAll(`[slot="${K}"]`).forEach(e=>e.remove())}_startQrLoadWait(){let e=this.shadowRoot;if(!e)return;let r=e.querySelector(`.${w}`),n=e.querySelector(`slot[name="${K}"]`);if(!r||!n)return;r.setAttribute("data-qr-area-state","waiting");let o=Math.max(1e3,parseInt(this.getAttribute("qr-load-timeout-ms")??String(12e3),10)||12e3);this._qrLoadTimeoutId=window.setTimeout(()=>{if(this._qrLoadTimeoutId=null,!this.shadowRoot)return;let a=this.shadowRoot.querySelector(`.${w}`);a?.getAttribute("data-qr-area-state")==="waiting"&&a.setAttribute("data-qr-area-state","timeout")},o);let i=()=>{if(n.assignedNodes().length>0){this._clearQrLoadWait();let a=this.shadowRoot?.querySelector(`.${w}`);a&&a.setAttribute("data-qr-area-state","loaded")}};this._qrSlotChangeBound=i,n.addEventListener("slotchange",i),n.assignedNodes().length>0&&i()}_clearQrLoadWait(){this._qrLoadTimeoutId!=null&&(clearTimeout(this._qrLoadTimeoutId),this._qrLoadTimeoutId=null);let e=this.shadowRoot;if(!e)return;let r=e.querySelector(`slot[name="${K}"]`);r&&this._qrSlotChangeBound&&(r.removeEventListener("slotchange",this._qrSlotChangeBound),this._qrSlotChangeBound=null);let n=e.querySelector(`.${w}`);n&&n.setAttribute("data-qr-area-state","default")}_transitionToIdle(){this._generatedExternalUserId=null;let r={reason:Li(this.currentState).reason,timestamp:Date.now()};this.dispatchEvent(Un(r)),this._emitCancelledIfAuthenticating(),this.setState(I.reset(this.currentState)),this.shadowRoot&&(Le(this.shadowRoot,this._parsed),this.scheduleRenderIfNeeded(),this._applyModalVisibility())}get open(){return this._parsed.open}set open(e){this.setAttribute("open",e?"true":"false")}get mode(){return this._parsed.mode}set mode(e){this.setAttribute("mode",e)}get tab(){return this._parsed.tab}set tab(e){this.setAttribute("tab",e)}get tabLabels(){return`${this._parsed.tabLabels.register},${this._parsed.tabLabels.login}`}set tabLabels(e){e==null||e===""?this.removeAttribute("tab-labels"):this.setAttribute("tab-labels",e)}get theme(){return this._parsed.theme}set theme(e){this.setAttribute("theme",e)}get sessionId(){return this._parsed.sessionId}set sessionId(e){e==null?this.removeAttribute("session-id"):this.setAttribute("session-id",e)}get onboardingUrl(){return this._parsed.onboardingUrl}set onboardingUrl(e){e==null?this.removeAttribute("onboarding-url"):this.setAttribute("onboarding-url",e)}get isMobileOverride(){return this._parsed.isMobileOverride}set isMobileOverride(e){e==null?this.removeAttribute("is-mobile-override"):this.setAttribute("is-mobile-override",e?"true":"false")}get fallbackType(){return this._parsed.fallbackType}set fallbackType(e){e==null?this.removeAttribute("fallback-type"):this.setAttribute("fallback-type",e)}get appId(){return this._parsed.appId}set appId(e){this.setAttribute("app-id",e??"")}get publishableKey(){return this._parsed.publishableKey}set publishableKey(e){this.setAttribute("publishable-key",e??"")}get appName(){return this._parsed.appName}set appName(e){e==null?this.removeAttribute("app-name"):this.setAttribute("app-name",e)}get dialogTitle(){return this._parsed.dialogTitle}set dialogTitle(e){e==null?this.removeAttribute("dialog-title"):this.setAttribute("dialog-title",e)}get dialogDescription(){return this._parsed.dialogDescription}set dialogDescription(e){e==null?this.removeAttribute("dialog-description"):this.setAttribute("dialog-description",e)}get externalUserId(){return this._parsed.externalUserId}set externalUserId(e){e==null?this.removeAttribute("external-user-id"):this.setAttribute("external-user-id",e)}disconnectedCallback(){this._unregisterInteractions?.(),this._unregisterInteractions=null,this.removeEventListener("keydown",this._boundEscapeKeydown,!0),super.disconnectedCallback()}reset(){this._transitionToIdle()}getTabKind(){return this._parsed.tab}getCoreAuthOptions(){let e=this._resolveExternalUserId();return e?{externalUserId:e}:{}}_resolveExternalUserId(){let e=this._parsed.externalUserId?.trim();return e||(this.getTabKind()!=="register"?null:(this._generatedExternalUserId??=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():null,this._generatedExternalUserId))}canStartAuth(){return!0}getEnvEvalParams(){return{mode:this._parsed.tab,isMobileOverride:this._parsed.isMobileOverride??void 0,fallbackType:this._parsed.fallbackType}}getCoreConfig(){return!this._parsed.appId||!this._parsed.publishableKey?null:{appId:this._parsed.appId,publishableKey:this._parsed.publishableKey}}getFallbackDetail(){return{operation:this._parsed.tab}}_applyModalVisibility(){if(!this.shadowRoot)return;let e=this.shadowRoot.querySelector(bt.wrapper);e&&(e.hidden=!this._parsed.open);let r=this.shadowRoot.querySelector(bt.overlay);r&&(r.hidden=this._parsed.mode!=="modal");let n=this.shadowRoot.querySelector(bt.panel);n&&n.setAttribute("aria-hidden",String(!this._parsed.open)),this._parsed.open&&e?(this._focusTrap||(this._focusTrap=Gn(e)),this._focusTrap.activate()):this._focusTrap?.deactivate()}_render(){if(!this.shadowRoot)return;Le(this.shadowRoot,this._parsed),this._applyModalVisibility();let e=Pt(this.currentState,this._parsed,{registerSessionReady:this._parsed.tab==="register"?this.canStartAuth():void 0,primaryButtonLabel:Ut,primaryButtonAriaLabel:Bt}),r={shadowRoot:this.shadowRoot};Jr(r,e)}};var _t=class extends ie{static get observedAttributes(){return[...jn]}_parsed={...he};get ticketId(){let e=this._parsed.ticketId;return e===void 0?null:e}_internalModal=null;_focusRestoreTarget=null;_unregisterInteractions=null;_onInternalModalClose=()=>{this._internalModal&&(this._internalModal.open=!1),this._restoreFocusToTrigger()};_onInternalModalSuccess=e=>{let r=e;this.dispatchEvent(new CustomEvent(q,{detail:r.detail,bubbles:!1,composed:!0}))};_restoreFocusToTrigger(){let e=this._focusRestoreTarget;this._focusRestoreTarget=null,!(!e?.isConnected||typeof e.focus!="function")&&e.focus()}_emitContextReadyIfEnrollment(){!this._core||!this.ticketId||this.dispatchEvent(Vn({contextHash:this._core.getContextHash()}))}enroll(){let e=this.ticketId;!e||!this._core||this._controller.startEnrollment(this._core,{ticketId:e})}connectedCallback(){if(this.shadowRoot){this._registerInteractions(),this._core!==null&&this._unsubscribeBridge===null&&this.attachCore(this._core),this._emitContextReadyIfEnrollment(),this._syncInternalModalAttributes(),this._ensureInternalModal();return}let e=this.attachShadow({mode:"open"}),r=Yt();if(r)e.adoptedStyleSheets=[r];else{let n=document.createElement("style");n.textContent=Wt(),e.appendChild(n)}this._parsed=wt(this),this._syncThemeAttribute(),this._registerInteractions(),this._render(),this._reconcileCoreFromConfig(),this._emitContextReadyIfEnrollment(),this._ensureInternalModal()}_registerInteractions(){this.shadowRoot&&(this._unregisterInteractions?.(),this._unregisterInteractions=nn(this.shadowRoot,{onPrimaryClick:()=>this._onPrimaryClick(),onFallbackClick:e=>this.dispatchFallback(e)}))}attributeChangedCallback(e,r,n){if(!this.shadowRoot)return;let o=this._parsed.mode;if(this._parsed=wt(this),(e==="button-variant"||e==="theme")&&this.invalidateRender(),(e==="app-id"||e==="publishable-key")&&this._reconcileCoreFromConfig(),(e==="ticket-id"||e==="app-id"||e==="publishable-key")&&this._emitContextReadyIfEnrollment(),e==="mode"&&(this._parsed.mode==="register"||this._parsed.mode==="login")){let i=this._parsed.mode;o!==i&&(this._emitCancelledIfAuthenticating(),this.setState(I.tabChange(this.currentState,i)))}this._syncThemeAttribute(),this.scheduleRenderIfNeeded(),this._syncInternalModalAttributes(),this._ensureInternalModal()}_onPrimaryClick(){if(this._parsed.action==="open-modal"){this._focusRestoreTarget=document.activeElement instanceof Element?document.activeElement:null,this.dispatchEvent(new CustomEvent(Ce,{detail:{},bubbles:!0,composed:!0})),!this._parsed.triggerOnly&&this._internalModal&&(this._internalModal.open=!0);return}this.startAuthFromClick()}getTabKind(){return this._parsed.mode==="auto"?"login":this._parsed.mode}getCoreAuthOptions(){return Dn(this._parsed.externalUserId)}canStartAuth(){return!0}getEnvEvalParams(){return{mode:this._parsed.mode}}getCoreConfig(){return!this._parsed.appId||!this._parsed.publishableKey?null:{appId:this._parsed.appId,publishableKey:this._parsed.publishableKey}}getFallbackDetail(){let e=this._parsed.mode==="login"||this._parsed.mode==="register"?this._parsed.mode:void 0;return e!==void 0?{operation:e}:{}}_render(){if(!this.shadowRoot)return;let e=Nt(this.currentState,this._parsed,{registerSessionReady:this._parsed.mode==="register"?this.canStartAuth():void 0,primaryButtonLabel:this._parsed.buttonLabel??void 0,primaryButtonAriaLabel:this._parsed.buttonAriaLabel??void 0}),r={shadowRoot:this.shadowRoot};Qr(r,e)}_syncThemeAttribute(){this.getAttribute("theme")!==this._parsed.theme&&this.setAttribute("theme",this._parsed.theme)}_syncInternalModalAttributes(){if(!this._internalModal)return;this._internalModal.setAttribute("app-id",this._parsed.appId??""),this._internalModal.setAttribute("publishable-key",this._parsed.publishableKey??""),this._internalModal.setAttribute("theme",this._parsed.theme);let e=this._parsed.mode==="auto"?"login":this._parsed.mode;this._internalModal.setAttribute("tab",e),this._internalModal.setAttribute("modal-variant","minimal")}_ensureInternalModal(){if(this._parsed.action!=="open-modal"||!this.shadowRoot)return;if(this._parsed.triggerOnly){this._internalModal?.isConnected&&(this._internalModal.removeEventListener(H,this._onInternalModalClose),this._internalModal.remove(),this._internalModal=null);return}if(this._internalModal?.isConnected){this._syncInternalModalAttributes();return}let e=document.createElement("trymellon-auth-modal");this._internalModal=e,this._syncInternalModalAttributes(),e.addEventListener(H,this._onInternalModalClose),e.addEventListener(q,this._onInternalModalSuccess),typeof document<"u"&&document.body?document.body.appendChild(e):this.shadowRoot.appendChild(e)}disconnectedCallback(){this._unregisterInteractions?.(),this._unregisterInteractions=null,this._internalModal?.isConnected&&(this._internalModal.removeEventListener(H,this._onInternalModalClose),this._internalModal.removeEventListener(q,this._onInternalModalSuccess),this._internalModal.remove(),this._internalModal=null),super.disconnectedCallback()}};var Ju="0.1.0",zn="trymellon-auth",Xn="trymellon-auth-modal";typeof customElements<"u"&&!customElements.get(zn)&&customElements.define(zn,_t);typeof customElements<"u"&&!customElements.get(Xn)&&customElements.define(Xn,yt);export{ve as BASE_STYLES,k as INITIAL_UI_STATE,Ie as MELLON_CANCELLED,H as MELLON_CLOSE,dt as MELLON_ERROR,pt as MELLON_FALLBACK,ut as MELLON_OPEN,Ce as MELLON_OPEN_REQUEST,ct as MELLON_START,q as MELLON_SUCCESS,mt as MELLON_TAB_CHANGE,Xn as TRYMELLON_AUTH_MODAL_TAG,zn as TRYMELLON_AUTH_TAG,_t as TryMellonAuthElement,yt as TryMellonAuthModalElement,Ju as UI_VERSION,Yt as createConstructableStylesheet,vr as eventBridgeAdapter,se as getNextState,Wt as getStylesFallback};
489
+ `.trim();function dn(){return ve+`
490
+ `+un}function cn(){if(!ln)return null;try{let t=new CSSStyleSheet;return t.replaceSync(ve+`
491
+ `+un),t}catch{return null}}var $t="https://api.trymellonauth.com",pn="https://api.trymellonauth.com/v1/telemetry";var mn="trymellon_sandbox_session_token_v1",gn="https://trymellon.com/docs/getting-started#sandbox",fn="/v1/enrollment-bridge",hn="/v1/auth-bridge";var c=t=>({ok:!0,value:t}),l=t=>({ok:!1,error:t});var qe=class t extends Error{code;details;isTryMellonError=!0;constructor(e,r,n){super(r),this.name="TryMellonError",this.code=e,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,t)}},Ao={NOT_SUPPORTED:"WebAuthn is not supported in this environment",USER_CANCELLED:"User cancelled the operation",PASSKEY_NOT_FOUND:"Passkey not found",SESSION_EXPIRED:"Session has expired",NETWORK_FAILURE:"Network request failed",INVALID_ARGUMENT:"Invalid argument provided",TIMEOUT:"Operation timed out",ABORTED:"Operation was aborted",ABORT_ERROR:"Operation aborted by user or timeout",CHALLENGE_MISMATCH:"This link was already used or expired. Please try again from your computer.",TICKET_NOT_FOUND:"Enrollment ticket not found or invalid",TICKET_EXPIRED:"Enrollment ticket has expired",TICKET_ALREADY_USED:"Enrollment ticket was already used",PIN_MISMATCH:"PIN does not match",PIN_LOCKED:"PIN is locked due to too many failed attempts",BRIDGE_SESSION_EXPIRED:"Bridge session has expired",UNKNOWN_ERROR:"An unknown error occurred"};function E(t,e,r){return new qe(t,e??Ao[t],r)}function zt(t){return t instanceof qe||typeof t=="object"&&t!==null&&"isTryMellonError"in t&&t.isTryMellonError===!0}function En(){return E("NOT_SUPPORTED")}function R(t,e){return E("INVALID_ARGUMENT",`Invalid argument: ${t} - ${e}`,{field:t,reason:e})}function bn(t){return E("UNKNOWN_ERROR",`Failed to ${t} credential`,{operation:t})}function Xt(t){return E("NOT_SUPPORTED",`No base64 ${t==="encode"?"encoding":"decoding"} available`,{type:t})}function yn(t,e){try{let r=new URL(t);if(r.protocol!=="https:"&&r.protocol!=="http:")throw R(e,"must use http or https protocol")}catch(r){throw zt(r)?r:R(e,"must be a valid URL")}}function Ge(t,e,r,n){if(!Number.isFinite(t))throw R(e,"must be a finite number");if(t<r||t>n)throw R(e,`must be between ${r} and ${n}`)}function je(t,e){if(typeof t!="string"||t.length===0)throw R(e,"must be a non-empty string");if(!/^[A-Za-z0-9_-]+$/.test(t))throw R(e,"must be a valid base64url string")}var vo={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"},So=["origin_not_allowed","origin_not_allowed_for_application"];function Qt(t){return So.includes(t)}function X(t){if(typeof t!="string")return"UNKNOWN_ERROR";let e=t.toLowerCase().trim();return{challenge_mismatch:"CHALLENGE_MISMATCH",session_expired:"SESSION_EXPIRED",unauthorized:"SESSION_EXPIRED",validation_error:"INVALID_ARGUMENT",invalid_argument:"INVALID_ARGUMENT",user_not_found:"SESSION_EXPIRED",passkey_not_found:"PASSKEY_NOT_FOUND",ticket_not_found:"TICKET_NOT_FOUND",ticket_expired:"TICKET_EXPIRED",ticket_already_consumed:"TICKET_ALREADY_USED",not_found:"TICKET_NOT_FOUND",expired:"TICKET_EXPIRED",already_consumed:"TICKET_ALREADY_USED",context_mismatch:"CHALLENGE_MISMATCH",challenge_not_found:"CHALLENGE_MISMATCH",invalid_ticket_id:"INVALID_ARGUMENT",invalid_context_hash:"INVALID_ARGUMENT",invalid_ticket_status:"INVALID_ARGUMENT",invalid_config:"INVALID_ARGUMENT",enrollment_not_enabled:"INVALID_ARGUMENT",pin_mismatch:"PIN_MISMATCH",pin_locked:"PIN_LOCKED",bridge_not_enabled:"UNKNOWN_ERROR",bridge_session_expired:"BRIDGE_SESSION_EXPIRED",session_not_found:"BRIDGE_SESSION_EXPIRED",origin_not_allowed:"INVALID_ARGUMENT",origin_not_allowed_for_application:"INVALID_ARGUMENT"}[e]??"UNKNOWN_ERROR"}function _(t){if(t instanceof DOMException){let e=t.name,r=t.message||"WebAuthn operation failed",n=vo[e]??"UNKNOWN_ERROR";return E(n,r,{originalError:t})}return t instanceof Error?E("UNKNOWN_ERROR",t.message,{originalError:t}):E("UNKNOWN_ERROR","An unknown error occurred",{originalError:t})}function h(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function d(t){return typeof t=="string"}function V(t){return typeof t=="number"&&Number.isFinite(t)}function Ye(t){return typeof t=="boolean"}function ee(t){return Array.isArray(t)}function s(t,e){return l(E("UNKNOWN_ERROR",t,{...e,originalData:e?.originalData}))}function m(t,e){return t[e]}function To(t,e){return!h(t)||!d(t.name)||!d(t.id)?s("Invalid API response: challenge.rp must have name and id strings",{originalData:e}):c(!0)}function Co(t,e){return!h(t)||!d(t.id)||!d(t.name)||!d(t.displayName)?s("Invalid API response: challenge.user must have id, name, displayName strings",{originalData:e}):c(!0)}function Io(t,e){if(!ee(t))return s("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let r of t)if(!h(r)||r.type!=="public-key"||!V(r.alg))return s("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});return c(!0)}function We(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"session_id");if(!d(e))return s("Invalid API response: session_id must be string",{field:"session_id",originalData:t});let r=m(t,"challenge");if(!h(r))return s("Invalid API response: challenge must be object",{field:"challenge",originalData:t});let n=To(m(r,"rp"),t);if(!n.ok)return n;let o=Co(m(r,"user"),t);if(!o.ok)return o;let i=m(r,"challenge");if(!d(i))return s("Invalid API response: challenge.challenge must be string",{originalData:t});let a=Io(m(r,"pubKeyCredParams"),t);if(!a.ok)return a;let u=r.timeout;if(u!==void 0&&!V(u))return s("Invalid API response: challenge.timeout must be number",{originalData:t});let p=r.excludeCredentials;if(p!==void 0){if(!ee(p))return s("Invalid API response: excludeCredentials must be array",{originalData:t});for(let f of p)if(!h(f)||f.type!=="public-key"||!d(f.id))return s("Invalid API response: excludeCredentials items must have id and type",{originalData:t})}let g=r.authenticatorSelection;return g!==void 0&&!h(g)?s("Invalid API response: authenticatorSelection must be object",{originalData:t}):c({session_id:e,challenge:{rp:r.rp,user:r.user,challenge:i,pubKeyCredParams:r.pubKeyCredParams,...u!==void 0&&{timeout:u},...p!==void 0&&{excludeCredentials:p},...g!==void 0&&{authenticatorSelection:g}}})}function Jt(t,e){if(!h(t))return s("Invalid API response: user must be object",{field:"user",originalData:e});let r=m(t,"user_id"),n=m(t,"external_user_id");if(!d(r)||!d(n))return s("Invalid API response: user must have user_id and external_user_id strings",{originalData:e});let o=t.email,i=t.metadata;return o!==void 0&&!d(o)?s("Invalid API response: user.email must be string",{originalData:e}):i!==void 0&&(typeof i!="object"||i===null)?s("Invalid API response: user.metadata must be object",{originalData:e}):c({user_id:r,external_user_id:n,...o!==void 0&&{email:o},...i!==void 0&&{metadata:i}})}function Zt(t){let e=We(t);return e.ok?c({session_id:e.value.session_id,challenge:e.value.challenge}):e}function er(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"session_id");if(!d(e))return s("Invalid API response: session_id must be string",{field:"session_id",originalData:t});let r=m(t,"challenge");if(!h(r))return s("Invalid API response: challenge must be object",{field:"challenge",originalData:t});let n=m(r,"challenge"),o=m(r,"rpId"),i=r.allowCredentials;if(!d(n))return s("Invalid API response: challenge.challenge must be string",{originalData:t});if(!d(o))return s("Invalid API response: challenge.rpId must be string",{originalData:t});if(i!==void 0&&!ee(i))return s("Invalid API response: allowCredentials must be array",{originalData:t});if(i){for(let p of i)if(!h(p)||p.type!=="public-key"||!d(p.id))return s("Invalid API response: allowCredentials items must have id and type",{originalData:t})}let a=r.timeout;if(a!==void 0&&!V(a))return s("Invalid API response: challenge.timeout must be number",{originalData:t});let u=r.userVerification;return u!==void 0&&!["required","preferred","discouraged"].includes(String(u))?s("Invalid API response: userVerification must be required|preferred|discouraged",{originalData:t}):c({session_id:e,challenge:{challenge:n,rpId:o,allowCredentials:i??[],...a!==void 0&&{timeout:a},...u!==void 0&&{userVerification:u}}})}function tr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"credential_id"),r=m(t,"status"),n=m(t,"session_token"),o=m(t,"user");if(!d(e))return s("Invalid API response: credential_id must be string",{field:"credential_id",originalData:t});if(!d(r))return s("Invalid API response: status must be string",{field:"status",originalData:t});if(!d(n))return s("Invalid API response: session_token must be string",{field:"session_token",originalData:t});let i=Jt(o,t);if(!i.ok)return l(i.error);let a=t.redirect_url;return a!==void 0&&!d(a)?s("Invalid API response: redirect_url must be string",{originalData:t}):c({credential_id:e,status:r,session_token:n,user:i.value,...a!==void 0&&{redirect_url:a}})}function rr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"authenticated"),r=m(t,"session_token"),n=m(t,"user"),o=m(t,"signals");if(!Ye(e))return s("Invalid API response: authenticated must be boolean",{field:"authenticated",originalData:t});if(!d(r))return s("Invalid API response: session_token must be string",{field:"session_token",originalData:t});let i=Jt(n,t);if(!i.ok)return l(i.error);if(o!==void 0&&!h(o))return s("Invalid API response: signals must be object",{originalData:t});let a=t.redirect_url;return a!==void 0&&!d(a)?s("Invalid API response: redirect_url must be string",{originalData:t}):c({authenticated:e,session_token:r,user:i.value,signals:o,...a!==void 0&&{redirect_url:a}})}function nr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"valid"),r=m(t,"user_id"),n=m(t,"external_user_id"),o=m(t,"tenant_id"),i=m(t,"app_id");return Ye(e)?d(r)?d(n)?d(o)?d(i)?c({valid:e,userId:r,externalUserId:n,tenantId:o,appId:i}):s("Invalid API response: app_id must be string",{field:"app_id",originalData:t}):s("Invalid API response: tenant_id must be string",{field:"tenant_id",originalData:t}):s("Invalid API response: external_user_id must be string",{field:"external_user_id",originalData:t}):s("Invalid API response: user_id must be string",{field:"user_id",originalData:t}):s("Invalid API response: valid must be boolean",{field:"valid",originalData:t})}function or(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=t.session_token??t.sessionToken;if(!d(e))return s("Invalid API response: session_token/sessionToken must be string",{field:"session_token",originalData:t});let r=t.redirect_url;return r!==void 0&&!d(r)?s("Invalid API response: redirect_url must be string",{originalData:t}):c({sessionToken:e,...r!==void 0&&{redirectUrl:r}})}var Lo=["pending_passkey","pending_data","completed"],Mo=["pending_data","completed"];function ir(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"session_id"),r=m(t,"onboarding_url"),n=m(t,"expires_in");return d(e)?d(r)?V(n)?c({session_id:e,onboarding_url:r,expires_in:n}):s("Invalid API response: expires_in must be number",{field:"expires_in",originalData:t}):s("Invalid API response: onboarding_url must be string",{field:"onboarding_url",originalData:t}):s("Invalid API response: session_id must be string",{field:"session_id",originalData:t})}function sr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"status"),r=m(t,"onboarding_url"),n=m(t,"expires_in");return!d(e)||!Lo.includes(e)?s("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:t}):d(r)?V(n)?c({status:e,onboarding_url:r,expires_in:n}):s("Invalid API response: expires_in must be number",{originalData:t}):s("Invalid API response: onboarding_url must be string",{originalData:t})}function ar(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"session_id"),r=m(t,"status"),n=m(t,"onboarding_url");if(!d(e))return s("Invalid API response: session_id must be string",{field:"session_id",originalData:t});if(r!=="pending_passkey")return s("Invalid API response: status must be pending_passkey",{field:"status",originalData:t});if(!d(n))return s("Invalid API response: onboarding_url must be string",{originalData:t});let o=t.challenge,i;if(o!==void 0){let a=Oo(o);if(!a.ok)return a;i=a.value}return c({session_id:e,status:"pending_passkey",onboarding_url:n,...i!==void 0&&{challenge:i}})}function Oo(t){if(!h(t))return s("Invalid API response: challenge must be object",{originalData:t});let e=m(t,"rp"),r=m(t,"user"),n=m(t,"challenge"),o=m(t,"pubKeyCredParams");if(!h(e)||!d(e.name)||!d(e.id))return s("Invalid API response: challenge.rp must have name and id",{originalData:t});if(!h(r)||!d(r.id)||!d(r.name)||!d(r.displayName))return s("Invalid API response: challenge.user must have id, name, displayName",{originalData:t});if(!d(n))return s("Invalid API response: challenge.challenge must be string",{originalData:t});if(!ee(o))return s("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:t});for(let i of o)if(!h(i)||i.type!=="public-key"||!V(i.alg))return s("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:t});return c({rp:e,user:r,challenge:n,pubKeyCredParams:o})}function lr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"session_id"),r=m(t,"status"),n=m(t,"user_id"),o=m(t,"tenant_id");return d(e)?!d(r)||!Mo.includes(r)?s("Invalid API response: status must be pending_data|completed",{originalData:t}):d(n)?d(o)?c({session_id:e,status:r,user_id:n,tenant_id:o}):s("Invalid API response: tenant_id must be string",{originalData:t}):s("Invalid API response: user_id must be string",{originalData:t}):s("Invalid API response: session_id must be string",{originalData:t})}function ur(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"session_id"),r=m(t,"status"),n=m(t,"user_id"),o=m(t,"tenant_id"),i=m(t,"session_token");return d(e)?r!=="completed"?s("Invalid API response: status must be completed",{originalData:t}):!d(n)||!d(o)||!d(i)?s("Invalid API response: user_id, tenant_id, session_token must be strings",{originalData:t}):c({session_id:e,status:"completed",user_id:n,tenant_id:o,session_token:i}):s("Invalid API response: session_id must be string",{originalData:t})}function $e(t){return t==null?c(void 0):h(t)&&Object.keys(t).length===0?c(void 0):s("Invalid API response: expected empty body (204)",{originalData:t})}function xo(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.challenge=="string"&&e.rp!=null&&typeof e.rp=="object"&&e.user!=null&&typeof e.user=="object"&&Array.isArray(e.pubKeyCredParams)}function ko(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.challenge=="string"&&typeof e.rpId=="string"}function ze(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e="resultado"in t&&h(t.resultado)?t.resultado:t,r=e.session_id,n=e.qr_url,o=e.expires_at,i=e.polling_token;if(!d(r)||!d(n)||!d(o)||!d(i))return s("Invalid API response: missing required fields",{originalData:t});let a={session_id:r,qr_url:n,expires_at:o,polling_token:i};return e.external_user_id!==void 0&&d(e.external_user_id)&&(a.external_user_id=e.external_user_id),c(a)}function dr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e="resultado"in t&&h(t.resultado)?t.resultado:t,r=e.status;if(!d(r)||!["pending","authenticated","completed"].includes(r))return s("Invalid API response: invalid status",{originalData:t});let n=e.user_id,o=e.session_token,i=e.redirect_url;return n!==void 0&&!d(n)?s("Invalid API response: user_id must be a string when present",{originalData:t}):o!==void 0&&!d(o)?s("Invalid API response: session_token must be a string when present",{originalData:t}):i!==void 0&&!d(i)?s("Invalid API response: redirect_url must be a string when present",{originalData:t}):c({status:r,user_id:n,session_token:o,redirect_url:i})}function cr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=t.type,r=e==="registration"?"registration":"auth",n=t.options;if(!h(n))return s("Invalid API response: options are required",{originalData:t});let o=200,i=_n(t.approval_context,o),a=_n(t.application_name,o);if(i===!1||a===!1)return s("Invalid API response: approval_context/application_name must be string max 200 chars",{originalData:t});let u={};return typeof i=="string"&&(u.approval_context=i),typeof a=="string"&&(u.application_name=a),r==="registration"?xo(n)?c({type:"registration",options:n,...u}):s("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:t}):ko(n)?c({type:"auth",options:n,...u}):s("Invalid API response: auth options must have challenge and rpId",{originalData:t})}function _n(t,e){if(t!=null)return typeof t!="string"||t.length>e?!1:t}function pr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"challenge"),r=m(t,"recovery_session_id");return h(e)?d(r)?c({challenge:e,recovery_session_id:r}):s("Invalid API response: recovery_session_id must be string",{field:"recovery_session_id",originalData:t}):s("Invalid API response: challenge must be object",{field:"challenge",originalData:t})}function mr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"status"),r=m(t,"session_token"),n=m(t,"user"),o=m(t,"credential_id");if(!d(e))return s("Invalid API response: status must be string",{field:"status",originalData:t});if(!d(r))return s("Invalid API response: session_token must be string",{field:"session_token",originalData:t});if(!d(o))return s("Invalid API response: credential_id must be string",{field:"credential_id",originalData:t});if(!h(n))return s("Invalid API response: user must be object",{field:"user",originalData:t});let i=m(n,"user_id");if(!d(i))return s("Invalid API response: user.user_id must be string",{field:"user.user_id",originalData:t});let u=t.redirect_url;if(u!==void 0&&!d(u))return s("Invalid API response: redirect_url must be string",{field:"redirect_url",originalData:t});let p=n;return c({status:e,session_token:r,credential_id:o,user:{user_id:i,external_user_id:d(p.external_user_id)?p.external_user_id:void 0,email:d(p.email)?p.email:void 0,metadata:h(p.metadata)?p.metadata:void 0},...u!==void 0&&{redirect_url:u}})}function gr(t){let e=We(t);return e.ok?c({session_id:e.value.session_id,challenge:e.value.challenge}):e}function Do(t,e){if(!h(t))return s("Invalid API response: user must be object",{field:"user",originalData:e});let r=m(t,"user_id");if(!d(r))return s("Invalid API response: user.user_id must be string",{originalData:e});let n=t.external_user_id;if(n!==void 0&&!d(n))return s("Invalid API response: user.external_user_id must be string",{originalData:e});let o=t.email;if(o!==void 0&&!d(o))return s("Invalid API response: user.email must be string",{originalData:e});let i=t.metadata;return i!==void 0&&(typeof i!="object"||i===null)?s("Invalid API response: user.metadata must be object",{originalData:e}):c({user_id:r,...n!==void 0&&{external_user_id:n},...o!==void 0&&{email:o},...i!==void 0&&{metadata:i}})}function fr(t){if(!h(t))return s("Invalid API response: expected object",{originalData:t});let e=m(t,"credential_id"),r=m(t,"status"),n=m(t,"session_token"),o=m(t,"user");if(!d(e))return s("Invalid API response: credential_id must be string",{field:"credential_id",originalData:t});if(!d(r))return s("Invalid API response: status must be string",{field:"status",originalData:t});if(!d(n))return s("Invalid API response: session_token must be string",{field:"session_token",originalData:t});let i=Do(o,t);return i.ok?c({credential_id:e,status:r,session_token:n,user:i.value}):i}var No=["pending","pin_verified","pin_locked","completed"];function hr(t){if(!h(t))return s("Invalid bridge context response: expected object",{originalData:t});let e=m(t,"type");if(e!=="auth"&&e!=="registration")return s('Invalid bridge context response: type must be "auth" or "registration"',{field:"type",expected:"auth | registration",originalData:t});let r=m(t,"options");if(!h(r))return s("Invalid bridge context response: options must be object",{field:"options",originalData:t});let n=t.application_name;return n!==void 0&&!d(n)?s("Invalid bridge context response: application_name must be string",{field:"application_name",originalData:t}):c({type:e,options:r,...n!==void 0&&{application_name:n}})}function Er(t){if(!h(t))return s("Invalid bridge verify response: expected object",{originalData:t});let e=m(t,"session_id");if(!d(e)||e.trim()==="")return s("Invalid bridge verify response: session_id must be non-empty string (UUID expected)",{field:"session_id",originalData:t});let r=t.challenge;if(r!==void 0&&!d(r))return s("Invalid bridge verify response: challenge must be string when present",{field:"challenge",originalData:t});let n=t.registration_options;if(n!==void 0&&!h(n))return s("Invalid bridge verify response: registration_options must be object when present",{field:"registration_options",originalData:t});let o=t.authentication_options;return o!==void 0&&!h(o)?s("Invalid bridge verify response: authentication_options must be object when present",{field:"authentication_options",originalData:t}):c({session_id:e,...r!==void 0&&{challenge:r},...n!==void 0&&{registration_options:n},...o!==void 0&&{authentication_options:o}})}function br(t){if(!h(t))return s("Invalid bridge complete enrollment response: expected object",{originalData:t});let e=m(t,"credential_id"),r=m(t,"entity_id"),n=m(t,"user_id"),o=m(t,"session_token");return d(e)?d(r)?d(n)?d(o)?c({credential_id:e,entity_id:r,user_id:n,session_token:o}):s("Invalid bridge complete enrollment response: session_token must be string",{field:"session_token",originalData:t}):s("Invalid bridge complete enrollment response: user_id must be string",{field:"user_id",originalData:t}):s("Invalid bridge complete enrollment response: entity_id must be string",{field:"entity_id",originalData:t}):s("Invalid bridge complete enrollment response: credential_id must be string",{field:"credential_id",originalData:t})}function yr(t){if(!h(t))return s("Invalid bridge complete auth response: expected object",{originalData:t});let e=m(t,"session_token");return d(e)?c({session_token:e}):s("Invalid bridge complete auth response: session_token must be string",{field:"session_token",originalData:t})}function _r(t){if(!h(t))return s("Invalid bridge status response: expected object",{originalData:t});let e=m(t,"status");if(typeof e!="string"||!No.includes(e))return s("Invalid bridge status response: status must be one of pending, pin_verified, pin_locked, completed",{field:"status",originalData:t});let r=t.ts;return r!==void 0&&!d(r)?s("Invalid bridge status response: ts must be string when present",{field:"ts",originalData:t}):c({status:e,...r!==void 0&&{ts:r}})}var Xe=class{constructor(e,r,n={}){this.httpClient=e;this.baseUrl=r;this.defaultHeaders=n}mergeHeaders(e){return{...this.defaultHeaders,...e}}async post(e,r,n,o){let i=`${this.baseUrl}${e}`,a=await this.httpClient.post(i,r,this.mergeHeaders(o));return a.ok?n(a.value):l(a.error)}async get(e,r,n){let o=`${this.baseUrl}${e}`,i=await this.httpClient.get(o,this.mergeHeaders(n));return i.ok?r(i.value):l(i.error)}async startRegister(e){return this.post("/v1/passkeys/register/start",e,Zt)}async startAuth(e){return this.post("/v1/passkeys/auth/start",e,er)}async finishRegister(e){return this.post("/v1/passkeys/register/finish",e,tr)}async finishAuthentication(e){return this.post("/v1/passkeys/auth/finish",e,rr)}async validateSession(e){return this.get("/v1/sessions/validate",nr,{Authorization:`Bearer ${e}`})}async startEmailFallback(e){let r=`${this.baseUrl}/v1/fallback/email/start`,n=await this.httpClient.post(r,{userId:e.userId,email:e.email},this.mergeHeaders());return n.ok?c(void 0):l(n.error)}async verifyEmailCode(e){let r={userId:e.userId,code:e.code};return e.successUrl&&(r.success_url=e.successUrl),this.post("/v1/fallback/email/verify",r,or)}async startOnboarding(e){return this.post("/v1/onboarding/start",e,ir)}async getOnboardingStatus(e){return this.get(`/v1/onboarding/${e}/status`,sr)}async getOnboardingRegister(e){return this.get(`/v1/onboarding/${e}/register`,ar)}async registerOnboardingPasskey(e,r){return this.post(`/v1/onboarding/${e}/register-passkey`,r,lr)}async completeOnboarding(e,r){return this.post(`/v1/onboarding/${e}/complete`,r,ur)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},ze)}async initCrossDeviceRegistration(e){let r=typeof e?.externalUserId=="string"?e.externalUserId.trim():"",n=r.length>0?{external_user_id:r}:{};return this.post("/v1/auth/cross-device/init-registration",n,ze)}async getCrossDeviceStatus(e,r){let n={};return typeof r=="string"&&r.length>0&&(n["X-Polling-Token"]=r),this.get(`/v1/auth/cross-device/status/${e}`,dr,Object.keys(n).length>0?n:void 0)}async getCrossDeviceContext(e){return this.get(`/v1/auth/cross-device/context/${e}`,cr)}async verifyCrossDeviceAuth(e){return this.post("/v1/auth/cross-device/verify",e,$e)}async verifyCrossDeviceRegistration(e){return this.post("/v1/auth/cross-device/verify-registration",e,$e)}async verifyAccountRecoveryOtp(e,r){return this.post("/v1/users/recovery/verify",{external_id:e,otp:r},pr)}async completeAccountRecovery(e,r){return this.post("/v1/users/recovery/complete",{recovery_session_id:e,credential:r},mr)}async startEnrollment(e,r,n){return this.post("/v1/enrollment/register/options",{ticket_id:e,context_hash:r},gr,n)}async finishEnrollment(e,r,n){return this.post("/v1/enrollment/register",{...r,ticket_id:e},fr,n)}bridgePrefix(e){return e==="enrollment"?fn:hn}async getBridgeContext(e,r,n){return this.get(`${this.bridgePrefix(r)}/context/${e}`,hr,n)}async verifyBridgePin(e,r,n,o){return this.post(`${this.bridgePrefix(n)}/verify/${e}`,{pin:r},Er,o)}async completeBridgeEnrollment(e,r){return this.post(`${this.bridgePrefix("enrollment")}/complete`,e,br,r)}async completeBridgeAuth(e,r){return this.post(`${this.bridgePrefix("auth")}/complete`,e,yr,r)}getBridgeStatusUrl(e,r){return`${this.baseUrl}${this.bridgePrefix(r)}/status/${e}`}async getBridgeStatus(e,r,n){return this.get(`${this.bridgePrefix(r)}/status/${e}`,_r,n)}};function wo(t){return typeof t=="object"&&t!==null&&t.ok===!0&&"resultado"in t}function Rr(t){if(typeof t!="object"||t===null)return!1;let e=t;if(e.ok!==!1||!e.error||typeof e.error!="object")return!1;let r=e.error;return typeof r.code=="string"&&typeof r.message=="string"}var Po="https://trymellon.com/docs/getting-started#allowed-origins",Uo="Add your origin to allowed origins in the TryMellon dashboard.";function Rn(t){let e=t.error.hint??Uo,r=t.error.docs_url??Po;console.warn(`[TryMellon] ${e} See: ${r}`)}function An(t,e){if(Rr(t))return{message:t.error.message,code:X(t.error.code)};let r=t,n=r?.error;if(typeof n=="object"&&n!==null&&"code"in n&&typeof n.code=="string")return{message:n.message??r?.message??e,code:X(n.code)};let o=r?.message??e,i=r?.error,a=typeof i=="string"?X(i):i===void 0?"NETWORK_FAILURE":X(String(i));return{message:o,code:a}}function Bo(){if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();throw new Error("Web Crypto API is required but not available.")}function vn(t,e){let r=e*Math.pow(2,t);return Math.min(r,3e4)}function Fo(t,e){return t!=="GET"?!1:e>=500||e===429}var Qe=class{constructor(e,r=0,n=1e3,o){this.timeoutMs=e;this.maxRetries=r;this.retryDelayMs=n;this.logger=o}async get(e,r){return this.request(e,{method:"GET",headers:r})}async post(e,r,n){return this.request(e,{method:"POST",body:JSON.stringify(r),headers:{"Content-Type":"application/json",...n}})}async request(e,r){let n=(r.method??"GET").toUpperCase(),o=Bo(),i=new Headers(r.headers);i.set("X-Request-Id",o),this.logger&&this.logger.debug("request",{requestId:o,url:e,method:n});let a;for(let u=0;u<=this.maxRetries;u++)try{let p=new AbortController,g=setTimeout(()=>p.abort(),this.timeoutMs);try{let f=await fetch(e,{...r,headers:i,signal:p.signal});if(!f.ok){let v;try{v=await f.json()}catch{}Rr(v)&&Qt(v.error.code)&&Rn(v);let{message:S,code:L}=An(v,f.statusText),C=E(L,S,{requestId:o,status:f.status,statusText:f.statusText,data:v});if(Fo(n,f.status)&&u<this.maxRetries){a=C,clearTimeout(g),await new Promise(Rt=>setTimeout(Rt,vn(u,this.retryDelayMs)));continue}return l(C)}if(f.status===204)return c(void 0);if(f.headers.get("content-length")==="0")return c(void 0);let b=await f.json();if(wo(b))return c(b.resultado);let A=b;if(typeof b=="object"&&b!==null&&A.ok===!0&&!("resultado"in A))return c(void 0);if(Rr(b)){Qt(b.error.code)&&Rn(b);let{message:v,code:S}=An(b,f.statusText);return l(E(S,v,{requestId:o,status:f.status,statusText:f.statusText,data:b}))}return c(b)}finally{clearTimeout(g)}}catch(p){if(a=p,n==="GET"&&u<this.maxRetries)await new Promise(f=>setTimeout(f,vn(u,this.retryDelayMs)));else break}return a instanceof Error&&a.name==="AbortError"?l(E("TIMEOUT","Request timed out",{requestId:o})):l(E("NETWORK_FAILURE",a instanceof Error?a.message:"Request failed",{requestId:o,cause:a}))}};function U(t){let e=new Uint8Array(t),r=Array.from(e,o=>String.fromCharCode(o)).join("");if(typeof globalThis.btoa>"u")throw Xt("encode");return globalThis.btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ko(t){if(typeof globalThis.atob>"u")throw Xt("decode");let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4,n=r===0?e:e+"=".repeat(4-r),o=globalThis.atob(n);return Uint8Array.from(o,i=>i.charCodeAt(0))}function te(t){return Ko(t).buffer}function Sn(t){return t!==null&&typeof t=="object"&&"clientDataJSON"in t&&t.clientDataJSON instanceof ArrayBuffer}function x(t){if(!t.response)throw E("UNKNOWN_ERROR","Credential response is missing",{credential:t});let e=t.response;if(!Sn(e))throw E("UNKNOWN_ERROR","Invalid credential response structure",{response:e});if(!("attestationObject"in e))throw E("UNKNOWN_ERROR","Invalid credential response structure for register: attestationObject is missing",{response:e});let r=e.clientDataJSON,n=e.attestationObject;return{id:t.id,rawId:U(t.rawId),response:{clientDataJSON:U(r),attestationObject:U(n)},type:"public-key"}}function re(t){if(!t.response)throw E("UNKNOWN_ERROR","Credential response is missing",{credential:t});let e=t.response;if(!Sn(e))throw E("UNKNOWN_ERROR","Invalid credential response structure",{response:e});if(!("authenticatorData"in e)||!("signature"in e))throw E("UNKNOWN_ERROR","Invalid credential response structure for auth: authenticatorData or signature is missing",{response:e});let r=e.clientDataJSON,n=e.authenticatorData,o=e.signature,i=e.userHandle;return{id:t.id,rawId:U(t.rawId),response:{authenticatorData:U(n),clientDataJSON:U(r),signature:U(o),...i&&{userHandle:U(i)}},type:"public-key"}}function O(t,e="create"){if(!t||typeof t!="object"||!("id"in t)||!("rawId"in t)||!("response"in t))throw bn(e)}function ne(){try{return!(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return!1}}async function Vo(){try{return!ne()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?!1:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function Je(){let t=ne(),e=await Vo();return{isPasskeySupported:t,platformAuthenticatorAvailable:e,recommendedFlow:t?"passkey":"fallback"}}async function Se(t){let{operation:e,eventEmitter:r,start:n,createOptions:o,invoke:i,finish:a}=t;try{if(r.emit("start",{type:"start",operation:e}),!ne()){let y=En();return r.emit("error",{type:"error",error:y}),l(y)}let u=await n();if(!u.ok)return r.emit("error",{type:"error",error:u.error}),l(u.error);let p=o(u.value);if(!p.ok)return r.emit("error",{type:"error",error:p.error}),l(p.error);let g=await i(p.value);if(!g){let y=R("credential",`${e==="register"?"creation":"retrieval"} failed`);return r.emit("error",{type:"error",error:y}),l(y)}try{O(g)}catch(y){let b=_(y);return r.emit("error",{type:"error",error:b}),l(b)}let f=await a(u.value,g);return f.ok?c(f.value):(r.emit("error",{type:"error",error:f.error}),l(f.error))}catch(u){let p=_(u);return r.emit("error",{type:"error",error:p}),l(p)}}function w(t,e){try{je(t.challenge,"challenge"),je(t.user.id,"user.id");let r=te(t.challenge),n=te(t.user.id),o={userVerification:"preferred"};t.authenticatorSelection&&(o={...t.authenticatorSelection}),e&&(o={...o,authenticatorAttachment:e});let i={rp:{id:t.rp.id,name:t.rp.name},user:{id:n,name:t.user.name,displayName:t.user.displayName},challenge:r,pubKeyCredParams:t.pubKeyCredParams,...t.timeout!==void 0&&{timeout:t.timeout},attestation:"none",authenticatorSelection:o,...t.excludeCredentials&&{excludeCredentials:t.excludeCredentials.map(a=>({id:te(a.id),type:a.type,...a.transports&&{transports:a.transports}}))}};return c({publicKey:i})}catch(r){return l(_(r))}}async function Tn(t,e){let r=w(t);if(!r.ok)return l(r.error);let n={...r.value,...e!==void 0&&{signal:e}},o;try{o=await navigator.credentials.create(n)}catch(i){return l(_(i))}try{O(o,"create")}catch(i){return l(_(i))}try{return c(x(o))}catch(i){return l(_(i))}}function Te(t,e){try{je(t.challenge,"challenge");let r=te(t.challenge);return c({publicKey:{challenge:r,rpId:t.rpId,...t.timeout!==void 0&&{timeout:t.timeout},userVerification:t.userVerification??"preferred",...t.allowCredentials&&{allowCredentials:t.allowCredentials.map(n=>({id:te(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...e!==void 0&&{mediation:e}})}catch(r){return l(_(r))}}async function Cn(t,e,r){let n=t.externalUserId??t.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let i=R("externalUserId","must be a non-empty string");return r.emit("error",{type:"error",error:i}),l(i)}let o=await Se({operation:"register",eventEmitter:r,start:()=>e.startRegister({external_user_id:n}),createOptions:i=>w(i.challenge,t.authenticatorType),invoke:async i=>{let a={...i,...t.signal&&{signal:t.signal}};return navigator.credentials.create(a)},finish:async(i,a)=>{let u=await e.finishRegister({session_id:i.session_id,credential:x(a),...t.successUrl&&{success_url:t.successUrl}});return u.ok?c({success:!0,credentialId:u.value.credential_id,credential_id:u.value.credential_id,status:u.value.status,sessionToken:u.value.session_token,user:{userId:u.value.user.user_id,externalUserId:u.value.user.external_user_id,email:u.value.user.email,metadata:u.value.user.metadata},...u.value.redirect_url&&{redirectUrl:u.value.redirect_url}}):l(u.error)}});return o.ok&&r.emit("success",{type:"success",operation:"register",token:o.value.sessionToken,user:o.value.user}),o}async function In(t,e,r){let n=t.externalUserId??t.external_user_id,o=n!==void 0&&typeof n=="string"&&n.trim()!=="",i=await Se({operation:"authenticate",eventEmitter:r,start:()=>e.startAuth(o?{external_user_id:n.trim()}:{}),createOptions:a=>Te(a.challenge,t.mediation),invoke:async a=>{let u={...a,...t.signal&&{signal:t.signal}};return navigator.credentials.get(u)},finish:async(a,u)=>{let p=await e.finishAuthentication({session_id:a.session_id,credential:re(u),...t.successUrl&&{success_url:t.successUrl}});return p.ok?c({authenticated:p.value.authenticated,sessionToken:p.value.session_token,user:{userId:p.value.user.user_id,externalUserId:p.value.user.external_user_id,email:p.value.user.email,metadata:p.value.user.metadata},signals:p.value.signals,...p.value.redirect_url&&{redirectUrl:p.value.redirect_url}}):l(p.error)}});return i.ok&&r.emit("success",{type:"success",operation:"authenticate",token:i.value.sessionToken,user:i.value.user}),i}async function Ze(t,e){return e?e.aborted?"aborted":new Promise(r=>{let n=()=>{o(),r("aborted")},o=()=>{clearTimeout(i),e.removeEventListener("abort",n)},i=setTimeout(()=>{o(),r("completed")},t);e.addEventListener("abort",n)}):(await new Promise(r=>setTimeout(r,t)),"completed")}var Ho=2e3,qo=60,et=class{constructor(e){this.apiClient=e}async startFlow(e,r){let n=await this.apiClient.startOnboarding({user_role:e.user_role});if(!n.ok)return l(n.error);let{session_id:o}=n.value;for(let i=0;i<qo;i++){if(r?.aborted)return l(E("ABORT_ERROR","Operation aborted by user or timeout"));if(await Ze(Ho,r)==="aborted")return l(E("ABORT_ERROR","Operation aborted by user or timeout"));let u=await this.apiClient.getOnboardingStatus(o);if(!u.ok)return l(u.error);let p=u.value.status,g=u.value.onboarding_url;if(p==="pending_passkey"){let f=await this.apiClient.getOnboardingRegister(o);if(!f.ok)return l(f.error);let y=f.value;if(!y.challenge)return l(E("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:g}));let b=w(y.challenge);if(!b.ok)return l(b.error);let A;try{A=await navigator.credentials.create(b.value)}catch(C){return l(_(C))}try{O(A,"create")}catch(C){return l(_(C))}let v;try{v=x(A)}catch(C){return l(_(C))}let S=await this.apiClient.registerOnboardingPasskey(o,{credential:v,challenge:y.challenge.challenge});return S.ok?await this.apiClient.completeOnboarding(o,{company_name:e.company_name}):l(S.error)}if(p==="completed")return await this.apiClient.completeOnboarding(o,{company_name:e.company_name})}return l(E("TIMEOUT","Onboarding timed out"))}};var Ln="trymellon_context_hash";var Go=/^[a-f0-9]{64}$/;function jo(t){return typeof t=="string"&&Go.test(t)}function Yo(){let t=new Uint8Array(32);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(t);else throw new Error("crypto.getRandomValues is not available");return Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("")}function Wo(){let t=null;return{getItem(){return t},setItem(e,r){t=r}}}var Mn=Wo();function On(t){let e=t.getItem(Ln);if(e&&jo(e))return e;let r=Yo();return t.setItem(Ln,r),r}function oe(t){let e=t??Mn;try{return On(e)}catch{return On(Mn)}}var tt=class{constructor(e,r){this.apiClient=e;this.storage=r}async enroll(e){if(e.signal?.aborted)return l(E("ABORT_ERROR","Operation aborted by user or timeout"));let r=this.storage??(typeof sessionStorage<"u"?sessionStorage:void 0),n=oe(r),o=await this.apiClient.startEnrollment(e.ticketId,n);if(!o.ok)return l(o.error);let i=await Tn(o.value.challenge,e.signal);if(!i.ok)return l(i.error);let a=await this.apiClient.finishEnrollment(e.ticketId,{credential:i.value,context_hash:n});return a.ok?c({sessionToken:a.value.session_token}):l(a.error)}};var $o=2e3,zo=60,rt=class{constructor(e){this.apiClient=e}async init(){return this.apiClient.initCrossDeviceAuth()}async initRegistration(e){return this.apiClient.initCrossDeviceRegistration(e)}async waitForSession(e,r,n){if(r?.aborted)return l(E("ABORT_ERROR","Operation aborted by user or timeout"));for(let o=0;o<zo;o++){let i=await this.apiClient.getCrossDeviceStatus(e,n);if(!i.ok)return l(i.error);if(i.value.status==="completed"){if(!i.value.session_token||!i.value.user_id)return l(E("UNKNOWN_ERROR","Missing data in completed session"));let u=i.value.redirect_url!=null&&i.value.redirect_url!==""?i.value.redirect_url:void 0;return c({session_token:i.value.session_token,user_id:i.value.user_id,...u!==void 0&&{redirectUrl:u}})}if(await Ze($o,r)==="aborted")return l(E("ABORT_ERROR","Operation aborted by user or timeout"))}return l(E("TIMEOUT","Cross-device authentication timed out"))}async approve(e){let r=await this.apiClient.getCrossDeviceContext(e);if(!r.ok)return l(r.error);let n=r.value;return n.type==="registration"?this.executeRegistrationApproval(e,n):this.executeAuthApproval(e,n)}async executeRegistrationApproval(e,r){let n=w(r.options);if(!n.ok)return l(n.error);let o;try{o=await navigator.credentials.create(n.value)}catch(a){return l(_(a))}try{O(o,"create")}catch(a){return l(_(a))}let i;try{i=x(o)}catch(a){return l(_(a))}return this.apiClient.verifyCrossDeviceRegistration({session_id:e,credential:i})}async executeAuthApproval(e,r){let n=Te(r.options);if(!n.ok)return l(n.error);let o;try{o=await navigator.credentials.get(n.value)}catch(a){return l(_(a))}try{O(o,"get")}catch(a){return l(_(a))}let i;try{i=re(o)}catch(a){return l(_(a))}return this.apiClient.verifyCrossDeviceAuth({session_id:e,credential:i})}};var Xo=new Set(["pin_verified","pin_locked","completed"]),Qo=1500,Jo=3e5;function xn(t){return Xo.has(t)}function nt(t){return t==null||typeof t!="string"||t.trim()===""?l(R("sessionId","must be a non-empty string")):c(t.trim())}function Zo(t){return{sessionToken:t.session_token,credentialId:t.credential_id,userId:t.user_id,entityId:t.entity_id}}function ei(t){return{sessionToken:t.session_token}}async function ti(t,e,r,n){let i=(n.presencePin!=null&&n.presencePin!==""?n.presencePin:null)??(typeof n.onPinRequired=="function"?await n.onPinRequired():null);return i==null||i===""?l(E("INVALID_ARGUMENT","Bridge requires PIN: provide presencePin or onPinRequired in options")):t.verifyBridgePin(e,i,r)}var ot=class{constructor(e,r){this.apiClient=e;this.storage=r}async waitForResult(e,r){let n=nt(e);if(!n.ok)return l(n.error);let o=r?.kind??"enrollment",i=r?.useSse!==!1,a=r?.timeoutMs??Jo,u=async p=>{for(;;){let g=await this.apiClient.getBridgeStatus(n.value,o);if(!g.ok)return l(g.error);if(xn(g.value.status))return c(g.value);if(Date.now()-p>=a)return l(E("TIMEOUT","Bridge status wait timed out"));await new Promise(f=>setTimeout(f,Qo))}};return i&&typeof EventSource<"u"?new Promise(p=>{let g=this.apiClient.getBridgeStatusUrl(n.value,o),f=!1,y=A=>{if(!f){f=!0;try{b.close()}catch{}p(A)}},b;try{b=new EventSource(g)}catch{u(Date.now()).then(y);return}b.onmessage=A=>{try{let v=typeof A.data=="string"?A.data:String(A.data),S=JSON.parse(v);if(S!==null&&typeof S=="object"&&"status"in S&&typeof S.status=="string"){let L=S.status;if(xn(L)){let C=S.ts;y(c({status:L,...typeof C=="string"&&{ts:C}}))}}}catch{}},b.onerror=()=>{if(!f){try{b.close()}catch{}u(Date.now()).then(y)}}}):u(Date.now())}async getContext(e,r){let n=nt(e);return n.ok?this.apiClient.getBridgeContext(n.value,r):l(n.error)}async verifyPin(e,r,n){let o=nt(e);return o.ok?r==null||typeof r!="string"||r===""?l(R("pin","must be a non-empty string")):this.apiClient.verifyBridgePin(o.value,r,n):l(o.error)}async complete(e,r){let n=nt(e);if(!n.ok)return l(n.error);let o=r?.kind??"enrollment",i=await this.apiClient.getBridgeContext(n.value,o);if(!i.ok)return l(i.error);let a=i.value,u=await ti(this.apiClient,n.value,o,r??{kind:o});if(!u.ok)return l(u.error);let p=u.value;if(r?.signal?.aborted)return l(E("ABORT_ERROR","Operation aborted by user or timeout"));let g=a.type==="registration"?"enrollment":"auth";if(o!==g)return l(E("INVALID_ARGUMENT",`Bridge context type "${a.type}" does not match kind "${o}"`));if(a.type==="registration"){if(!r?.ticketId?.trim()||!r?.entityId?.trim())return l(R("ticketId/entityId","required for enrollment bridge complete"));let L=p.registration_options;if(!L||typeof L!="object")return l(E("UNKNOWN_ERROR","Bridge verify response missing registration_options"));let C=w(L);if(!C.ok)return l(C.error);let Rt={...C.value,...r.signal!==void 0&&{signal:r.signal}},At;try{At=await navigator.credentials.create(Rt)}catch(St){return l(_(St))}try{O(At,"create")}catch(St){return l(_(St))}let Me=x(At),eo=this.storage??(typeof sessionStorage<"u"?sessionStorage:void 0),to=oe(eo),vt=await this.apiClient.completeBridgeEnrollment({session_id:n.value,ticket_id:r.ticketId,entity_id:r.entityId,context_hash:to,registration_response:{id:Me.id,rawId:Me.rawId,response:Me.response,type:Me.type}});return vt.ok?c(Zo(vt.value)):l(vt.error)}let f=p.authentication_options;if(!f||typeof f!="object")return l(E("UNKNOWN_ERROR","Bridge verify response missing authentication_options"));let y=Te(f);if(!y.ok)return l(y.error);let b={...y.value,...r?.signal!==void 0&&{signal:r.signal}},A;try{A=await navigator.credentials.get(b)}catch(L){return l(_(L))}try{O(A,"get")}catch(L){return l(_(L))}let v=re(A),S=await this.apiClient.completeBridgeAuth({session_id:n.value,credential:{id:v.id,rawId:v.rawId,response:v.response,type:v.type}});return S.ok?c(ei(S.value)):l(S.error)}};var it=class{handlers;constructor(){this.handlers=new Map}on(e,r){let n=this.handlers.get(e);return n||(n=new Set,this.handlers.set(e,n)),n.add(r),()=>{this.off(e,r)}}off(e,r){let n=this.handlers.get(e);n&&(n.delete(r),n.size===0&&this.handlers.delete(e))}emit(e,r){let n=this.handlers.get(e);if(n)for(let o of n)try{o(r)}catch(i){console.warn("[TryMellon] Event handler threw:",i)}}removeAllListeners(){this.handlers.clear()}};function kn(t){return{async send(e){let r=JSON.stringify(e);if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"){navigator.sendBeacon(t,r);return}typeof fetch<"u"&&await fetch(t,{method:"POST",body:r,headers:{"Content-Type":"application/json"},keepalive:!0})}}}function Ar(t,e){return{event:t,latencyMs:e,ok:!0}}var st=class{constructor(e,r,n,o,i){this.apiClient=e;this.eventEmitter=r;this.sandbox=n;this.sandboxToken=o;this.telemetrySender=i}async sandboxAuthResult(e,r){let n="externalUserId"in r?r.externalUserId??r.external_user_id??"sandbox":r.external_user_id??r.externalUserId??"sandbox",o=typeof n=="string"?n:"sandbox";return e==="register"?Promise.resolve(c({success:!0,credentialId:"",status:"sandbox",sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:o}})):Promise.resolve(c({authenticated:!0,sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:o}}))}async register(e){if(this.sandbox){let o=await this.sandboxAuthResult("register",e);return o.ok&&this.eventEmitter.emit("success",{type:"success",operation:"register",token:o.value.sessionToken,user:o.value.user}),o}let r=Date.now(),n=await Cn(e,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Ar("register",Date.now()-r)).catch(o=>console.warn("[TryMellon] Telemetry send failed",o)),n}async authenticate(e){if(this.sandbox){let o=await this.sandboxAuthResult("authenticate",e);return o.ok&&this.eventEmitter.emit("success",{type:"success",operation:"authenticate",token:o.value.sessionToken,user:o.value.user}),o}let r=Date.now(),n=await In(e,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Ar("authenticate",Date.now()-r)).catch(o=>console.warn("[TryMellon] Telemetry send failed",o)),n}};async function Dn(t,e,r){let n=t.externalUserId??t.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let i=R("externalUserId","must be a non-empty string");return r.emit("error",{type:"error",error:i}),l(i)}if(!t.otp||typeof t.otp!="string"||t.otp.trim().length!==6){let i=R("otp","must be a 6-digit string");return r.emit("error",{type:"error",error:i}),l(i)}let o=await Se({operation:"register",eventEmitter:r,start:()=>e.verifyAccountRecoveryOtp(n,t.otp),createOptions:i=>{let a=i.challenge;return!a||typeof a!="object"||!("rp"in a)||!("user"in a)||!("challenge"in a)||!("pubKeyCredParams"in a)?l(R("challenge","invalid recovery challenge structure")):w(a)},invoke:async i=>navigator.credentials.create(i),finish:async(i,a)=>{let u=await e.completeAccountRecovery(i.recovery_session_id,x(a));if(!u.ok)return l(u.error);let{credential_id:p,status:g,session_token:f,user:y,redirect_url:b}=u.value;return c({success:!0,credentialId:p,status:g,sessionToken:f,user:{userId:y.user_id,externalUserId:y.external_user_id,email:y.email,metadata:y.metadata},...b!==void 0&&{redirectUrl:b}})}});return o.ok&&r.emit("success",{type:"success",operation:"register",token:o.value.sessionToken,user:o.value.user}),o}var at=class{constructor(e,r){this.apiClient=e;this.eventEmitter=r}recover(e){return Dn(e,this.apiClient,this.eventEmitter)}};function di(t){if(typeof t!="string"||t==="")return!1;try{let e=new URL(t).hostname.toLowerCase();return e==="localhost"||e==="127.0.0.1"}catch{return!1}}var lt=class t{sandbox;sandboxToken;apiClient;eventEmitter;telemetrySender;crossDeviceManager;authService;recoveryService;onboarding;enrollmentManager;bridgeManager;contextHashStorage;static validateConfig(e){let{appId:r,publishableKey:n}=e;if(!r||typeof r!="string"||r.trim()==="")throw R("appId","must be a non-empty string");if(!n||typeof n!="string"||n.trim()==="")throw R("publishableKey","must be a non-empty string");let o=e.apiBaseUrl??$t;yn(o,"apiBaseUrl");let i=e.timeoutMs??3e4;Ge(i,"timeoutMs",1e3,3e5),e.maxRetries!==void 0&&Ge(e.maxRetries,"maxRetries",0,10),e.retryDelayMs!==void 0&&Ge(e.retryDelayMs,"retryDelayMs",100,1e4)}static create(e){try{return t.validateConfig(e),c(new t(e))}catch(r){return zt(r)?l(r):l(R("config",r.message))}}constructor(e){this.sandbox=e.sandbox===!0,this.sandboxToken=this.sandbox&&e.sandboxToken!=null&&e.sandboxToken!==""?e.sandboxToken:mn,t.validateConfig(e);let r=e.appId,n=e.publishableKey,o=e.apiBaseUrl??$t,i=e.timeoutMs??3e4,a=e.maxRetries??3,u=e.retryDelayMs??1e3,p=new Qe(i,a,u,e.logger),g=e.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),f={"X-App-Id":r.trim(),Authorization:`Bearer ${n.trim()}`,...g&&{Origin:g}};this.apiClient=new Xe(p,o,f),this.eventEmitter=new it,e.enableTelemetry&&(this.telemetrySender=e.telemetrySender??kn(e.telemetryEndpoint??pn)),this.authService=new st(this.apiClient,this.eventEmitter,this.sandbox,this.sandboxToken,this.telemetrySender),this.recoveryService=new at(this.apiClient,this.eventEmitter),this.contextHashStorage=e.contextHashStorage,this.onboarding=new et(this.apiClient),this.enrollmentManager=new tt(this.apiClient,this.contextHashStorage),this.crossDeviceManager=new rt(this.apiClient),this.bridgeManager=new ot(this.apiClient,this.contextHashStorage),this.warnIfSandboxOnProd()}warnIfSandboxOnProd(){if(typeof window>"u"||!this.sandbox)return;let e=window.location.origin;di(e)||console.warn(`[TryMellon] Sandbox mode is ON but origin is not localhost (current: ${e}). Use sandbox: false in production. See: ${gn}`)}get bridge(){return{getContext:(e,r)=>this.bridgeManager.getContext(e,r),verifyPin:(e,r,n)=>this.bridgeManager.verifyPin(e,r,n),complete:(e,r)=>this.bridgeManager.complete(e,r),waitForResult:(e,r)=>this.bridgeManager.waitForResult(e,r)}}static isSupported(){return ne()}async register(e){return this.authService.register(e)}async authenticate(e){return this.authService.authenticate(e)}async enroll(e){this.eventEmitter.emit("start",{type:"start",operation:"enroll"});let r=await this.enrollmentManager.enroll(e);return r.ok?this.eventEmitter.emit("success",{type:"success",operation:"enroll",token:r.value.sessionToken}):this.eventEmitter.emit("error",{type:"error",operation:"enroll",error:r.error}),r}getContextHash(){let e=this.contextHashStorage??(typeof sessionStorage<"u"?sessionStorage:void 0);return oe(e)}async validateSession(e){return this.sandbox&&e===this.sandboxToken?Promise.resolve(c({valid:!0,userId:"sandbox-user",externalUserId:"sandbox",tenantId:"sandbox-tenant",appId:"sandbox-app"})):this.apiClient.validateSession(e)}async getStatus(){return Je()}on(e,r){return this.eventEmitter.on(e,r)}version(){return"2.3.2"}fallback={email:{start:async e=>this.apiClient.startEmailFallback(e),verify:async e=>{let r=await this.apiClient.verifyEmailCode({userId:e.userId,code:e.code,...e.successUrl&&{successUrl:e.successUrl}});return r.ok?c({sessionToken:r.value.sessionToken,...r.value.redirectUrl&&{redirectUrl:r.value.redirectUrl}}):r}}};auth={crossDevice:{init:()=>this.crossDeviceManager.init(),initRegistration:e=>this.crossDeviceManager.initRegistration(e??{}),waitForSession:(e,r,n)=>this.crossDeviceManager.waitForSession(e,r,n),getContext:e=>this.apiClient.getCrossDeviceContext(e),approve:e=>this.crossDeviceManager.approve(e)},recoverAccount:e=>this.recoveryService.recover(e)}};function vr(t){let e=lt.create({appId:t.appId,publishableKey:t.publishableKey});return!e.ok||e.value==null?null:e.value}function wn(t){if(t==null||typeof t!="object")return!1;let e=t,r=typeof e.authenticate=="function",n=typeof e.register=="function",o=typeof e.on=="function",i=typeof e.enroll=="function",a=typeof e.getContextHash=="function";return r&&n&&o&&i&&a}function Pn(t){return t?{externalUserId:t}:{}}var ut="mellon:open",Ce="mellon:open-request",H="mellon:close",q="mellon:success",dt="mellon:error",ct="mellon:start",Ie="mellon:cancelled",pt="mellon:fallback",mt="mellon:tab-change",Sr="mellon:context-ready";function gt(t,e,r,n){t.dispatchEvent(new CustomEvent(e,{detail:r,bubbles:n.bubbles,composed:n.composed}))}function ft(t){return t==="authenticate"?"login":t==="enroll"?"enroll":"register"}function ci(t){if(t==null||typeof t!="object")return;let e=t,r=e.userId;if(typeof r!="string"||r.length===0)return;let n={userId:r};return typeof e.externalUserId=="string"&&(n.externalUserId=e.externalUserId),typeof e.email=="string"&&(n.email=e.email),e.metadata!=null&&typeof e.metadata=="object"&&!Array.isArray(e.metadata)&&(n.metadata=e.metadata),n}function pi(t){return t!=null&&typeof t=="object"&&t.type==="start"&&(t.operation==="register"||t.operation==="authenticate"||t.operation==="enroll")}function mi(t){let e=t;return t!=null&&typeof t=="object"&&e.type==="success"&&typeof e.token=="string"&&(e.operation==="register"||e.operation==="authenticate"||e.operation==="enroll")}function gi(t){return t!=null&&typeof t=="object"&&t.type==="error"}function fi(t){return t!=null&&typeof t=="object"&&t.type==="cancelled"&&(t.operation==="register"||t.operation==="authenticate"||t.operation==="enroll")}var Tr={subscribe(t,e){if(t==null||e==null)throw new TypeError("eventBridgeAdapter.subscribe: core and host are required");let r=[],n="authenticate",o=!1,i=t.on("start",g=>{if(!pi(g))return;n=g.operation,o=!1;let f={operation:ft(g.operation),...typeof g.nonce=="string"&&{nonce:g.nonce}};gt(e,ct,f,{bubbles:!0,composed:!0})});r.push(i);let a=t.on("success",g=>{if(!mi(g)||o||g.token.length===0)return;o=!0;let f=ci(g.user),y={operation:ft(g.operation),token:g.token,...typeof g.nonce=="string"&&{nonce:g.nonce},...f!==void 0&&{user:f},...typeof g.redirectUrl=="string"&&{redirectUrl:g.redirectUrl}};gt(e,q,y,{bubbles:!1,composed:!0})});r.push(a);let u=t.on("error",g=>{if(!gi(g)||o)return;let f=g.error?.code??"UNKNOWN_ERROR",y=X(typeof f=="string"?f:String(f)),b={operation:ft(g.operation??n),code:y,message:typeof g.error?.message=="string"?g.error.message:"Unknown error",...typeof g.nonce=="string"&&{nonce:g.nonce}};gt(e,dt,b,{bubbles:!0,composed:!0})});r.push(u);let p=t.on("cancelled",g=>{if(!fi(g))return;let f={operation:ft(g.operation),...typeof g.nonce=="string"&&{nonce:g.nonce}};gt(e,Ie,f,{bubbles:!0,composed:!0})});return r.push(p),function(){for(let f of r)f()}}};function Un(t){return{isPasskeySupported:t.isPasskeySupported,platformAuthenticatorAvailable:t.platformAuthenticatorAvailable,recommendedFlow:t.recommendedFlow}}function hi(){return{getClientStatus:async()=>{let t=await Je();return Un(t)}}}function Bn(t){let e=t;if(typeof e.getStatus!="function")return hi();let r=e.getStatus;return{getClientStatus:async()=>{let n=await r();return Un(n)}}}function Fn(t){return new CustomEvent(ut,{detail:t,bubbles:!0,composed:!0})}function Kn(t){return new CustomEvent(H,{detail:t,bubbles:!0,composed:!0})}function Vn(t){return new CustomEvent(Ie,{detail:t,bubbles:!0,composed:!0})}function Hn(t){return new CustomEvent(pt,{detail:t,bubbles:!0,composed:!0})}function qn(t){return new CustomEvent(mt,{detail:t,bubbles:!0,composed:!0})}function Gn(t){return new CustomEvent(Sr,{detail:t,bubbles:!1,composed:!0})}var ht=class{_currentState=k;_lastRenderedState=null;_renderDirty=!0;_pendingOperation="authenticate";_currentNonce=void 0;_envEvalRequestId=0;get currentState(){return this._currentState}setState(e){this._currentState=e,this._renderDirty=!0}invalidateRender(){this._renderDirty=!0}consumeRenderDecision(){return!this._renderDirty&&this._currentState===this._lastRenderedState?!1:(this._lastRenderedState=this._currentState,this._renderDirty=!1,!0)}setPendingOperationFromTab(e){this._pendingOperation=e==="login"?"authenticate":"register"}get pendingOperation(){return this._pendingOperation}setNonce(e){this._currentNonce=e}consumeCancelledDetailIfAuthenticating(){if(this._currentState!=="AUTHENTICATING")return null;let e={operation:this._pendingOperation==="authenticate"?"login":this._pendingOperation,...this._currentNonce!==void 0&&{nonce:this._currentNonce}};return this._currentNonce=void 0,e}handleAuthSuccess(){let e=I.handleAuthOutcome(this._currentState,"success");e!==null&&this.setState(e)}handleAuthError(){let e=I.handleAuthOutcome(this._currentState,"error");e!==null&&this.setState(e)}handleEnrollSuccess(){let e=I.handleEnrollOutcome(this._currentState,"success");e!==null&&this.setState(e)}handleEnrollError(){let e=I.handleEnrollOutcome(this._currentState,"error");e!==null&&this.setState(e)}onStartEvent(e){e?.nonce!==void 0&&(this._currentNonce=e.nonce)}startAuthFromClick(e,r,n){if(!e||!Pr(this._currentState))return;this.setPendingOperationFromTab(r);let o=I.startAuth(this._currentState,r,e,n);this.setState(o)}startEnrollment(e,r){if(!e)return;let n=I.startEnrollment(this._currentState,e,r);this.setState(n)}async runEnvEval(e){let r=++this._envEvalRequestId;this.setState(I.envEvalStart(this._currentState));let n=await I.evaluateEnv({...e,currentState:this._currentState});return r!==this._envEvalRequestId?null:n}reset(){this._currentState=I.reset(this._currentState),this._lastRenderedState=null,this._renderDirty=!0,this._currentNonce=void 0}setStateForRender(e){this._currentState=e,this._renderDirty=!0}};var ie=class extends HTMLElement{_controller=new ht;_unsubscribeBridge=null;_core=null;_lastCoreConfig=null;setState(e){this._controller.setState(e),this.scheduleRenderIfNeeded()}invalidateRender(){this._controller.invalidateRender(),this.scheduleRenderIfNeeded()}scheduleRenderIfNeeded(){this.shadowRoot&&this._controller.consumeRenderDecision()&&this._render()}_emitCancelledIfAuthenticating(){let e=this._controller.consumeCancelledDetailIfAuthenticating();return e?(this.dispatchEvent(Vn(e)),!0):!1}attachCore(e){if(this._core!==null&&this._teardownCore(),e==null){this._core=null,this._controller.reset(),this.scheduleRenderIfNeeded();return}if(!wn(e))throw new Error("[trymellon-auth] attachCore requires a CoreAuthPort-compatible instance.");this._core=e,this._unsubscribeBridge=Tr.subscribe(this._core,this),this._attachHostListeners(),this._runEnvEval()}_teardownCore(){this._unsubscribeBridge?.(),this._unsubscribeBridge=null,this.removeEventListener("mellon:start",this._onMellonStart),this.removeEventListener("mellon:success",this._onMellonSuccess),this.removeEventListener("mellon:error",this._onMellonError),this._core=null}_attachHostListeners(){this.removeEventListener("mellon:start",this._onMellonStart),this.removeEventListener("mellon:success",this._onMellonSuccess),this.removeEventListener("mellon:error",this._onMellonError),this.addEventListener("mellon:start",this._onMellonStart),this.addEventListener("mellon:success",this._onMellonSuccess),this.addEventListener("mellon:error",this._onMellonError)}_onMellonSuccess=()=>{this._controller.currentState==="ENROLLING"?this._controller.handleEnrollSuccess():this._controller.handleAuthSuccess(),this.scheduleRenderIfNeeded()};_onMellonError=()=>{this._controller.currentState==="ENROLLING"?this._controller.handleEnrollError():this._controller.handleAuthError(),this.scheduleRenderIfNeeded()};_onMellonStart=e=>{let r=e.detail;this._controller.onStartEvent(r)};startAuthFromClick(){this._core&&this.canStartAuth()&&(this._controller.startAuthFromClick(this._core,this.getTabKind(),this.getCoreAuthOptions()),this.scheduleRenderIfNeeded())}dispatchFallback(e){let r=e!==void 0?{...this.getFallbackDetail(),fallbackType:e}:this.getFallbackDetail();this.dispatchEvent(Hn(r))}async _runEnvEval(){if(!this._core)return;let e={...this.getEnvEvalParams(),envStatusPort:Bn(this._core)},r=await this._controller.runEnvEval(e);r!==null&&(!this._core||!this.isConnected||this.setState(r))}_maybeAutoCreateCoreAndRunEnvEval(){if(this._core!==null)return;let e=this.getCoreConfig();if(!e)return;let r=vr(e);if(!r){this.attachCore(null);return}this.attachCore(r)}_reconcileCoreFromConfig(){let e=this.getCoreConfig();if(this._lastCoreConfig===null&&e===null||this._lastCoreConfig!==null&&e!==null&&this._lastCoreConfig.appId===e.appId&&this._lastCoreConfig.publishableKey===e.publishableKey)return;if(this._lastCoreConfig=e,e===null){this.attachCore(null);return}let n=vr(e);this.attachCore(n??null)}disconnectedCallback(){this._teardownCore()}get currentState(){return this._controller.currentState}reset(){this._emitCancelledIfAuthenticating(),this._controller.reset(),this.scheduleRenderIfNeeded()}setStateForRender(e){this._controller.setStateForRender(e),this.scheduleRenderIfNeeded()}};function Ei(t){if(t==null||t.trim()==="")return Q;let e=t.split(",").map(o=>o.trim()),r=e[0]??Q.register,n=e[1]??Q.login;return{register:r,login:n}}function Et(t){let e={open:Be(t.getAttribute("open")),mode:N(t.getAttribute("mode"),ue,De),tab:N(t.getAttribute("tab"),le,Ne),tabLabels:Ei(t.getAttribute("tab-labels")),theme:N(t.getAttribute("theme"),G,Y),sessionId:M(t.getAttribute("session-id")),onboardingUrl:M(t.getAttribute("onboarding-url")),isMobileOverride:Ur(t.getAttribute("is-mobile-override")),fallbackType:Br(t.getAttribute("fallback-type"),de),appId:W(t.getAttribute("app-id")),publishableKey:W(t.getAttribute("publishable-key")),appName:M(t.getAttribute("app-name")),dialogTitle:M(t.getAttribute("dialog-title")),dialogDescription:M(t.getAttribute("dialog-description")),externalUserId:M(t.getAttribute("external-user-id")),modalVariant:N(t.getAttribute("modal-variant"),me,Ue)};return Dt(e)}function bi(t){let e=t.querySelector(`.${ye}`);return e||(e=document.createElement("div"),e.className=ye,t.appendChild(e)),e}function yi(t){let e=t.querySelector(`.${z}`);return e||(e=document.createElement("div"),e.className=z,e.setAttribute("aria-hidden","true"),t.appendChild(e)),e}function _i(t){let e=t.querySelector(`.${_e}`);return e||(e=document.createElement("div"),e.className=_e,t.appendChild(e)),e}function Ri(t,e){t.setAttribute("role","dialog"),t.setAttribute("aria-modal",e==="modal"?"true":"false"),t.setAttribute("aria-labelledby",He),t.setAttribute("aria-describedby",Ae)}function Ai(t,e){let r=t.querySelector(`#${He}`);r||(r=document.createElement("h2"),r.id=He,r.className="mellon-dialog-title",t.insertBefore(r,t.firstChild));let n=e.dialogTitle?.trim()??(e.appName?.trim()?Kr(e.appName.trim()):Fr);r.textContent=n;let o=t.querySelector(`#${Ae}`);o||(o=document.createElement("p"),o.id=Ae,o.className="mellon-dialog-desc",t.insertBefore(o,r.nextSibling)),o.textContent=e.dialogDescription?.trim()??Vr}function vi(t){let e=t.querySelector(`.${Ht}`);e||(e=document.createElement("button"),e.type="button",e.className=Ht,e.setAttribute("aria-label",qr),e.setAttribute("data-mellon-modal-close","true"),e.textContent="\xD7",t.appendChild(e))}function Si(t,e){let r=t.querySelector(`.${Re}`);if(!r){r=document.createElement("div"),r.className=Re,r.setAttribute("role","tablist");let i=document.createElement("button");i.type="button",i.setAttribute("data-tab","register"),i.setAttribute("role","tab");let a=document.createElement("button");a.type="button",a.setAttribute("data-tab","login"),a.setAttribute("role","tab"),r.appendChild(i),r.appendChild(a);let u=t.querySelector(`#${Ae}`);t.insertBefore(r,u?u.nextSibling:t.firstChild)}let[n,o]=r.querySelectorAll("button");return n&&(n.textContent=e.register),o&&(o.textContent=e.login),r}function Cr(t){let e=t.querySelector(`.${Ft}`);if(!e){e=document.createElement("div"),e.className=Ft;let r=t.querySelector(`.${Re}`);t.insertBefore(e,r?r.nextSibling:t.firstChild)}return e}function Ti(){let t=document.createElementNS(F,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("class","mellon-qr-icon"),t.setAttribute("fill","currentColor");let e=document.createElementNS(F,"path");return e.setAttribute("d","M3 3h6v6H3V3zm2 2v2h2V5H5zm8-2h6v6h-6V3zm2 2v2h2V5h-2zM3 15h6v6H3v-6zm2 2v2h2v-2H5zm8-2h6v6h-6v-6zm2 2v2h2v-2h-2zm4-12h2v2h-2V5zm0 8h2v2h-2v-2zm-4 4h2v2h-2v-2zm0-8h2v2h-2V9zm0 4h2v2h-2v-2z"),t.appendChild(e),t}function jn(){let t=document.createDocumentFragment(),e=document.createElement("div");e.className=jr;let r=document.createElement("p");r.className="mellon-cross-device-cta-text",r.textContent=Gr,e.appendChild(r);let n=document.createElement("button");return n.type="button",n.className="mellon-btn mellon-btn-qr-icon",n.setAttribute("data-mellon-action",J),n.setAttribute("aria-label",Yr),n.appendChild(Ti()),e.appendChild(n),t.appendChild(e),t}function Ci(){let t=document.createElement("div");t.className=Wr,t.setAttribute("aria-live","polite");let e=document.createElement("span");e.textContent=Xr;let r=document.createElement("span");return r.className="mellon-qr-dots",r.setAttribute("aria-hidden","true"),t.appendChild(e),t.appendChild(r),t}function Ii(){let t=document.createElement("div");return t.className=$r,t.setAttribute("aria-live","polite"),t.textContent=Qr,t}function Li(t){let e=Cr(t),r=e.querySelector(`.${P}`);if(!r){r=document.createElement("div"),r.className=P,r.setAttribute("data-qr-area-state","default"),r.appendChild(Ci()),r.appendChild(Ii());let o=document.createElement("div");o.className=zr;let i=document.createElement("slot");i.name=K,i.appendChild(jn()),o.appendChild(i),r.appendChild(o),e.appendChild(r)}let n=r.querySelector(`slot[name="${K}"]`);if(!n){let o=document.createElement("slot");return o.name=K,o.appendChild(jn()),r.appendChild(o),o}return n}function Mi(t){let e=Cr(t);if(e.querySelector(`.${Vt}`))return;let r=document.createElement("div");r.className=Vt,r.setAttribute("aria-hidden","true");let n=document.createElement("span");n.className="mellon-separator-text",n.textContent=Hr,r.appendChild(n);let o=e.querySelector(`.${P}`);e.insertBefore(r,o?o.nextSibling:e.firstChild)}function Oi(t){let e=Cr(t),r=e.querySelector("slot:not([name])");if(!r){r=document.createElement("slot");let o=document.createElement("div");o.id=$,o.className="mellon-root",r.appendChild(o),e.appendChild(r)}let n=t.querySelector(`#${$}`);return n||(n=document.createElement("div"),n.id=$,n.className="mellon-root",r.appendChild(n)),n}function xi(t){let e=t.querySelector(`slot[name="${Kt}"]`);return e||(e=document.createElement("slot"),e.name=Kt,t.appendChild(e)),e}function ki(t,e){let r=t.querySelector(`.${Re}`);if(!r)return;let n=r.querySelector('[data-tab="register"]'),o=r.querySelector('[data-tab="login"]');n&&n.setAttribute("aria-selected",String(e==="register")),o&&o.setAttribute("aria-selected",String(e==="login"))}function Le(t,e){if(t==null||e==null)return;let r=bi(t);r.setAttribute("data-mellon-modal-variant",e.modalVariant),e.mode==="modal"&&yi(r);let n=_i(r);Ri(n,e.mode),Ai(n,e),vi(n),Si(n,e.tabLabels),Li(n),Mi(n),Oi(n),xi(n),ki(n,e.tab)}function Di(t){return!(t.hidden===!0||t.getAttribute("aria-hidden")==="true")}function Yn(t){return Array.from(t.querySelectorAll(rn)).filter(r=>Di(r))}function Wn(t){let e=null,r=null,n=!1;function o(u){if(u.key!=="Tab")return;let p=Yn(t);if(p.length===0)return;let g=u.target instanceof Node?u.target:null,f=g?p.indexOf(g):-1,y=p.length-1,b;u.shiftKey?b=f<=0?y:f-1:b=f>=y?0:f+1;let A=p[b];A&&(u.preventDefault(),A.focus())}function i(){if(n)return;e=document.activeElement;let p=Yn(t)[0];p&&p.focus(),r=o,t.addEventListener("keydown",r,!0),n=!0}function a(){if(!n)return;r&&(t.removeEventListener("keydown",r,!0),r=null),n=!1;let u=t.getRootNode()?.ownerDocument??document,p=e instanceof HTMLElement&&u.body.contains(e)?e:null;if(p)p.focus();else{let g=u.body,f=g.getAttribute("tabindex");g.setAttribute("tabindex","-1"),g.focus(),f===null?g.removeAttribute("tabindex"):g.setAttribute("tabindex",f)}e=null}return{activate:i,deactivate:a}}var $n=["app-id","publishable-key","mode","external-user-id","theme","action","trigger-only","button-variant","button-label","button-aria-label","ticket-id"],zn=["open","mode","tab","tab-labels","theme","session-id","onboarding-url","is-mobile-override","fallback-type","app-id","publishable-key","app-name","dialog-title","dialog-description","external-user-id","modal-variant","qr-load-timeout-ms"],bt={wrapper:`.${ye}`,overlay:`.${z}`,panel:`.${_e}`},Xn="user";var Ni={SUCCESS:{reason:"success"},AUTHENTICATING:{reason:"cancel"},ERROR:{reason:"error"}};function wi(t){return Ni[t]??{reason:Xn}}var yt=class extends ie{static get observedAttributes(){return[...zn]}_parsed=Et(this);_focusTrap=null;_unregisterInteractions=null;_generatedExternalUserId=null;_qrLoadTimeoutId=null;_qrSlotChangeBound=null;_boundEscapeKeydown=e=>{e.key==="Escape"&&this._parsed.open&&(e.preventDefault(),this.open=!1)};connectedCallback(){if(this.addEventListener("keydown",this._boundEscapeKeydown,!0),this.shadowRoot){this._registerInteractions(),this._core!==null&&this._unsubscribeBridge===null&&this.attachCore(this._core);return}let e=this.attachShadow({mode:"open"}),r=cn();if(r)e.adoptedStyleSheets=[r];else{let n=document.createElement("style");n.textContent=dn(),e.appendChild(n)}this._parsed=Et(this),Le(e,this._parsed),this._registerInteractions(),this._render(),this._applyModalVisibility(),this._maybeAutoCreateCoreAndRunEnvEval()}_registerInteractions(){this.shadowRoot&&(this._unregisterInteractions?.(),this._unregisterInteractions=an(this.shadowRoot,{onTabChange:e=>{this.dispatchEvent(qn({tab:e})),this.setAttribute("tab",e)},onPrimaryClick:()=>this.startAuthFromClick(),onFallbackClick:e=>this.dispatchFallback(e),onOverlayClick:()=>{this.open=!1},onCloseClick:()=>{this.open=!1}}))}attributeChangedCallback(e,r,n){if(this.shadowRoot){if(this._parsed=Et(this),e==="open"){if(this._parsed.open&&r!=="true"){this._clearCrossDeviceSlot();let o={timestamp:Date.now()};this.dispatchEvent(Fn(o)),this._startQrLoadWait()}if(!this._parsed.open){this._clearQrLoadWait(),this._transitionToIdle();return}}e==="tab"&&(this._emitCancelledIfAuthenticating(),this.setState(I.tabChange(this.currentState,this._parsed.tab))),(e==="app-id"||e==="publishable-key")&&this._reconcileCoreFromConfig(),Le(this.shadowRoot,this._parsed),this._render(),this._applyModalVisibility()}}_clearCrossDeviceSlot(){this.querySelectorAll(`[slot="${K}"]`).forEach(e=>e.remove())}_startQrLoadWait(){let e=this.shadowRoot;if(!e)return;let r=e.querySelector(`.${P}`),n=e.querySelector(`slot[name="${K}"]`);if(!r||!n)return;r.setAttribute("data-qr-area-state","waiting");let o=Math.max(1e3,parseInt(this.getAttribute("qr-load-timeout-ms")??String(12e3),10)||12e3);this._qrLoadTimeoutId=window.setTimeout(()=>{if(this._qrLoadTimeoutId=null,!this.shadowRoot)return;let a=this.shadowRoot.querySelector(`.${P}`);a?.getAttribute("data-qr-area-state")==="waiting"&&a.setAttribute("data-qr-area-state","timeout")},o);let i=()=>{if(n.assignedNodes().length>0){this._clearQrLoadWait();let a=this.shadowRoot?.querySelector(`.${P}`);a&&a.setAttribute("data-qr-area-state","loaded")}};this._qrSlotChangeBound=i,n.addEventListener("slotchange",i),n.assignedNodes().length>0&&i()}_clearQrLoadWait(){this._qrLoadTimeoutId!=null&&(clearTimeout(this._qrLoadTimeoutId),this._qrLoadTimeoutId=null);let e=this.shadowRoot;if(!e)return;let r=e.querySelector(`slot[name="${K}"]`);r&&this._qrSlotChangeBound&&(r.removeEventListener("slotchange",this._qrSlotChangeBound),this._qrSlotChangeBound=null);let n=e.querySelector(`.${P}`);n&&n.setAttribute("data-qr-area-state","default")}_transitionToIdle(){this._generatedExternalUserId=null;let r={reason:wi(this.currentState).reason,timestamp:Date.now()};this.dispatchEvent(Kn(r)),this._emitCancelledIfAuthenticating(),this.setState(I.reset(this.currentState)),this.shadowRoot&&(Le(this.shadowRoot,this._parsed),this.scheduleRenderIfNeeded(),this._applyModalVisibility())}get open(){return this._parsed.open}set open(e){this.setAttribute("open",e?"true":"false")}get mode(){return this._parsed.mode}set mode(e){this.setAttribute("mode",e)}get tab(){return this._parsed.tab}set tab(e){this.setAttribute("tab",e)}get tabLabels(){return`${this._parsed.tabLabels.register},${this._parsed.tabLabels.login}`}set tabLabels(e){e==null||e===""?this.removeAttribute("tab-labels"):this.setAttribute("tab-labels",e)}get theme(){return this._parsed.theme}set theme(e){this.setAttribute("theme",e)}get sessionId(){return this._parsed.sessionId}set sessionId(e){e==null?this.removeAttribute("session-id"):this.setAttribute("session-id",e)}get onboardingUrl(){return this._parsed.onboardingUrl}set onboardingUrl(e){e==null?this.removeAttribute("onboarding-url"):this.setAttribute("onboarding-url",e)}get isMobileOverride(){return this._parsed.isMobileOverride}set isMobileOverride(e){e==null?this.removeAttribute("is-mobile-override"):this.setAttribute("is-mobile-override",e?"true":"false")}get fallbackType(){return this._parsed.fallbackType}set fallbackType(e){e==null?this.removeAttribute("fallback-type"):this.setAttribute("fallback-type",e)}get appId(){return this._parsed.appId}set appId(e){this.setAttribute("app-id",e??"")}get publishableKey(){return this._parsed.publishableKey}set publishableKey(e){this.setAttribute("publishable-key",e??"")}get appName(){return this._parsed.appName}set appName(e){e==null?this.removeAttribute("app-name"):this.setAttribute("app-name",e)}get dialogTitle(){return this._parsed.dialogTitle}set dialogTitle(e){e==null?this.removeAttribute("dialog-title"):this.setAttribute("dialog-title",e)}get dialogDescription(){return this._parsed.dialogDescription}set dialogDescription(e){e==null?this.removeAttribute("dialog-description"):this.setAttribute("dialog-description",e)}get externalUserId(){return this._parsed.externalUserId}set externalUserId(e){e==null?this.removeAttribute("external-user-id"):this.setAttribute("external-user-id",e)}disconnectedCallback(){this._unregisterInteractions?.(),this._unregisterInteractions=null,this.removeEventListener("keydown",this._boundEscapeKeydown,!0),super.disconnectedCallback()}reset(){this._transitionToIdle()}getTabKind(){return this._parsed.tab}getCoreAuthOptions(){let e=this._resolveExternalUserId();return e?{externalUserId:e}:{}}_resolveExternalUserId(){let e=this._parsed.externalUserId?.trim();return e||(this.getTabKind()!=="register"?null:(this._generatedExternalUserId??=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():null,this._generatedExternalUserId))}canStartAuth(){return!0}getEnvEvalParams(){return{mode:this._parsed.tab,isMobileOverride:this._parsed.isMobileOverride??void 0,fallbackType:this._parsed.fallbackType}}getCoreConfig(){return!this._parsed.appId||!this._parsed.publishableKey?null:{appId:this._parsed.appId,publishableKey:this._parsed.publishableKey}}getFallbackDetail(){return{operation:this._parsed.tab}}_applyModalVisibility(){if(!this.shadowRoot)return;let e=this.shadowRoot.querySelector(bt.wrapper);e&&(e.hidden=!this._parsed.open);let r=this.shadowRoot.querySelector(bt.overlay);r&&(r.hidden=this._parsed.mode!=="modal");let n=this.shadowRoot.querySelector(bt.panel);n&&n.setAttribute("aria-hidden",String(!this._parsed.open)),this._parsed.open&&e?(this._focusTrap||(this._focusTrap=Wn(e)),this._focusTrap.activate()):this._focusTrap?.deactivate()}_render(){if(!this.shadowRoot)return;Le(this.shadowRoot,this._parsed),this._applyModalVisibility();let e=wt(this.currentState,this._parsed,{registerSessionReady:this._parsed.tab==="register"?this.canStartAuth():void 0,primaryButtonLabel:Ut,primaryButtonAriaLabel:Bt}),r={shadowRoot:this.shadowRoot};en(r,e)}};var _t=class extends ie{static get observedAttributes(){return[...$n]}_parsed={...he};get ticketId(){let e=this._parsed.ticketId;return e===void 0?null:e}_internalModal=null;_focusRestoreTarget=null;_unregisterInteractions=null;_onInternalModalClose=()=>{this._internalModal&&(this._internalModal.open=!1),this._restoreFocusToTrigger()};_onInternalModalSuccess=e=>{let r=e;this.dispatchEvent(new CustomEvent(q,{detail:r.detail,bubbles:!1,composed:!0}))};_restoreFocusToTrigger(){let e=this._focusRestoreTarget;this._focusRestoreTarget=null,!(!e?.isConnected||typeof e.focus!="function")&&e.focus()}_emitContextReadyIfEnrollment(){!this._core||!this.ticketId||this.dispatchEvent(Gn({contextHash:this._core.getContextHash()}))}enroll(){let e=this.ticketId;!e||!this._core||this._controller.startEnrollment(this._core,{ticketId:e})}connectedCallback(){if(this.shadowRoot){this._registerInteractions(),this._core!==null&&this._unsubscribeBridge===null&&this.attachCore(this._core),this._emitContextReadyIfEnrollment(),this._syncInternalModalAttributes(),this._ensureInternalModal();return}let e=this.attachShadow({mode:"open"}),r=Yt();if(r)e.adoptedStyleSheets=[r];else{let n=document.createElement("style");n.textContent=Wt(),e.appendChild(n)}this._parsed=Pt(this),this._syncThemeAttribute(),this._registerInteractions(),this._render(),this._reconcileCoreFromConfig(),this._emitContextReadyIfEnrollment(),this._ensureInternalModal()}_registerInteractions(){this.shadowRoot&&(this._unregisterInteractions?.(),this._unregisterInteractions=sn(this.shadowRoot,{onPrimaryClick:()=>this._onPrimaryClick(),onFallbackClick:e=>this.dispatchFallback(e)}))}attributeChangedCallback(e,r,n){if(!this.shadowRoot)return;let o=this._parsed.mode;if(this._parsed=Pt(this),(e==="button-variant"||e==="theme")&&this.invalidateRender(),(e==="app-id"||e==="publishable-key")&&this._reconcileCoreFromConfig(),(e==="ticket-id"||e==="app-id"||e==="publishable-key")&&this._emitContextReadyIfEnrollment(),e==="mode"&&(this._parsed.mode==="register"||this._parsed.mode==="login")){let i=this._parsed.mode;o!==i&&(this._emitCancelledIfAuthenticating(),this.setState(I.tabChange(this.currentState,i)))}this._syncThemeAttribute(),this.scheduleRenderIfNeeded(),this._syncInternalModalAttributes(),this._ensureInternalModal()}_onPrimaryClick(){if(this._parsed.action==="open-modal"){this._focusRestoreTarget=document.activeElement instanceof Element?document.activeElement:null,this.dispatchEvent(new CustomEvent(Ce,{detail:{},bubbles:!0,composed:!0})),!this._parsed.triggerOnly&&this._internalModal&&(this._internalModal.open=!0);return}this.startAuthFromClick()}getTabKind(){return this._parsed.mode==="auto"?"login":this._parsed.mode}getCoreAuthOptions(){return Pn(this._parsed.externalUserId)}canStartAuth(){return!0}getEnvEvalParams(){return{mode:this._parsed.mode}}getCoreConfig(){return!this._parsed.appId||!this._parsed.publishableKey?null:{appId:this._parsed.appId,publishableKey:this._parsed.publishableKey}}getFallbackDetail(){let e=this._parsed.mode==="login"||this._parsed.mode==="register"?this._parsed.mode:void 0;return e!==void 0?{operation:e}:{}}_render(){if(!this.shadowRoot)return;let e=Nt(this.currentState,this._parsed,{registerSessionReady:this._parsed.mode==="register"?this.canStartAuth():void 0,primaryButtonLabel:this._parsed.buttonLabel??void 0,primaryButtonAriaLabel:this._parsed.buttonAriaLabel??void 0}),r={shadowRoot:this.shadowRoot};Zr(r,e)}_syncThemeAttribute(){this.getAttribute("theme")!==this._parsed.theme&&this.setAttribute("theme",this._parsed.theme)}_syncInternalModalAttributes(){if(!this._internalModal)return;this._internalModal.setAttribute("app-id",this._parsed.appId??""),this._internalModal.setAttribute("publishable-key",this._parsed.publishableKey??""),this._internalModal.setAttribute("theme",this._parsed.theme);let e=this._parsed.mode==="auto"?"login":this._parsed.mode;this._internalModal.setAttribute("tab",e),this._internalModal.setAttribute("modal-variant","minimal")}_ensureInternalModal(){if(this._parsed.action!=="open-modal"||!this.shadowRoot)return;if(this._parsed.triggerOnly){this._internalModal?.isConnected&&(this._internalModal.removeEventListener(H,this._onInternalModalClose),this._internalModal.remove(),this._internalModal=null);return}if(this._internalModal?.isConnected){this._syncInternalModalAttributes();return}let e=document.createElement("trymellon-auth-modal");this._internalModal=e,this._syncInternalModalAttributes(),e.addEventListener(H,this._onInternalModalClose),e.addEventListener(q,this._onInternalModalSuccess),typeof document<"u"&&document.body?document.body.appendChild(e):this.shadowRoot.appendChild(e)}disconnectedCallback(){this._unregisterInteractions?.(),this._unregisterInteractions=null,this._internalModal?.isConnected&&(this._internalModal.removeEventListener(H,this._onInternalModalClose),this._internalModal.removeEventListener(q,this._onInternalModalSuccess),this._internalModal.remove(),this._internalModal=null),super.disconnectedCallback()}};var id="0.1.0",Jn="trymellon-auth",Zn="trymellon-auth-modal";typeof customElements<"u"&&!customElements.get(Jn)&&customElements.define(Jn,_t);typeof customElements<"u"&&!customElements.get(Zn)&&customElements.define(Zn,yt);export{ve as BASE_STYLES,k as INITIAL_UI_STATE,Ie as MELLON_CANCELLED,H as MELLON_CLOSE,dt as MELLON_ERROR,pt as MELLON_FALLBACK,ut as MELLON_OPEN,Ce as MELLON_OPEN_REQUEST,ct as MELLON_START,q as MELLON_SUCCESS,mt as MELLON_TAB_CHANGE,Zn as TRYMELLON_AUTH_MODAL_TAG,Jn as TRYMELLON_AUTH_TAG,_t as TryMellonAuthElement,yt as TryMellonAuthModalElement,id as UI_VERSION,Yt as createConstructableStylesheet,Tr as eventBridgeAdapter,se as getNextState,Wt as getStylesFallback};
492
492
  //# sourceMappingURL=index.js.map