@trymellon/js 1.7.7 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,489 @@
1
+ function wn(e){if(e.recommendedFlow==="fallback")return e.fallbackType==="email"?"FALLBACK_EMAIL":e.fallbackType==="qr"?"FALLBACK_QR":"FALLBACK";switch(e.mode){case"login":return"READY_LOGIN";case"register":return"READY_REGISTER";default:return"READY"}}function Pn(e){return e==="register"?"READY_REGISTER":"READY_LOGIN"}function te(e,t){if(e==null||t==null||t.type==="RESET")return"IDLE";if(t.type==="TAB_CHANGE"){let r=t.payload?.tab;if(r!=="register"&&r!=="login")return e;let n=Pn(r);switch(e){case"READY":case"READY_REGISTER":case"READY_LOGIN":case"FALLBACK":case"FALLBACK_EMAIL":case"FALLBACK_QR":case"AUTHENTICATING":case"ERROR":return n;default:return e}}switch(e){case"IDLE":if(t.type==="ENV_EVAL_START")return"EVALUATING_ENV";break;case"EVALUATING_ENV":if(t.type==="ENV_RESOLVED")return wn(t.payload);if(t.type==="ENV_DETACH")return"IDLE";if(t.type==="ENV_ERROR")return"ERROR";break;case"READY":case"READY_REGISTER":case"READY_LOGIN":if(t.type==="START_AUTH")return"AUTHENTICATING";break;case"AUTHENTICATING":if(t.type==="AUTH_SUCCESS")return"SUCCESS";if(t.type==="AUTH_ERROR")return"ERROR";if(t.type==="AUTH_FALLBACK")return"FALLBACK";if(t.type==="AUTH_FALLBACK_EMAIL")return"FALLBACK_EMAIL";if(t.type==="AUTH_FALLBACK_QR")return"FALLBACK_QR";break;default:break}return e}var T="IDLE";var lr=["IDLE","EVALUATING_ENV","READY","READY_REGISTER","READY_LOGIN","AUTHENTICATING","SUCCESS","ERROR","FALLBACK","FALLBACK_EMAIL","FALLBACK_QR"],re=["login","register","auto"],B=["light","dark"],ne=["register","login"],oe=["modal","inline"],ie=["email","qr"],se=["direct-auth","open-modal"],ae=["default","pill"],le=["default","minimal"],ur=["passkey","fallback"];function ct(e){if(e==null||typeof e!="object")return!1;let t=e;return!(typeof t.isPasskeySupported!="boolean"||typeof t.platformAuthenticatorAvailable!="boolean"||t.recommendedFlow!=="passkey"&&t.recommendedFlow!=="fallback")}function S(e,t){return typeof e=="string"&&t.includes(e)}function pt(e){return S(e,lr)}function k(e){return pt(e)?e:T}function F(e){return S(e,re)}function ue(e){return S(e,B)}function de(e){return S(e,ne)}function ve(e){return S(e,oe)}function mt(e){return S(e,se)}function ft(e){return S(e,ae)}function ht(e){return S(e,le)}function gt(e){if(e==null||typeof e!="object")return!1;let t=e;return S(t.recommendedFlow,ur)&&F(t.mode)&&(t.fallbackType===void 0||S(t.fallbackType,ie))}function Te(e){if(e==null||typeof e!="object")return!1;let t=e,r=t.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":return!0;case"ENV_RESOLVED":return gt(t.payload);case"TAB_CHANGE":return t.payload!=null&&typeof t.payload=="object"&&de(t.payload.tab);default:return!1}}var Se="login",K="light",Ce="modal",Ie="register",z={register:"Register",login:"Sign in"},Me="open-modal",Le="default",xe="default",ce={appId:"",publishableKey:"",mode:Se,externalUserId:null,theme:K,action:Me,triggerOnly:!1,buttonVariant:Le},bt={open:!1,mode:Ce,tab:Ie,tabLabels:z,theme:K,sessionId:null,onboardingUrl:null,isMobileOverride:null,appId:"",publishableKey:"",appName:null,dialogTitle:null,dialogDescription:null,externalUserId:null,modalVariant:xe};function dr(e){if(e==null||typeof e!="object")return!1;let t=e;return typeof t.appId=="string"&&typeof t.publishableKey=="string"&&F(t.mode)&&(t.externalUserId===null||typeof t.externalUserId=="string")&&ue(t.theme)&&mt(t.action)&&typeof t.triggerOnly=="boolean"&&ft(t.buttonVariant)}function cr(e){if(e==null||typeof e!="object")return!1;let t=e;return typeof t.register=="string"&&typeof t.login=="string"}function pr(e){if(e==null||typeof e!="object")return!1;let t=e;return typeof t.open=="boolean"&&ve(t.mode)&&de(t.tab)&&cr(t.tabLabels)&&ue(t.theme)&&(t.sessionId===null||typeof t.sessionId=="string")&&(t.onboardingUrl===null||typeof t.onboardingUrl=="string")&&(t.isMobileOverride===null||typeof t.isMobileOverride=="boolean")&&(t.fallbackType===void 0||t.fallbackType==="email"||t.fallbackType==="qr")&&typeof t.appId=="string"&&typeof t.publishableKey=="string"&&(t.appName==null||typeof t.appName=="string")&&(t.dialogTitle==null||typeof t.dialogTitle=="string")&&(t.dialogDescription==null||typeof t.dialogDescription=="string")&&(t.externalUserId==null||typeof t.externalUserId=="string")&&ht(t.modalVariant)}function mr(){return ce}function fr(){return bt}function Et(e){return dr(e)?e:mr()}function yt(e){return pr(e)?e:fr()}function R(e,t){let r=k(e);return Te(t)?te(r,t):r}function At(e,t,r){return{state:e,theme:t.theme,mode:t.mode,buttonVariant:t.buttonVariant,...t.mode==="register"&&r?.registerSessionReady!==void 0&&{registerSessionReady:r.registerSessionReady},...r?.primaryButtonLabel!==void 0&&{primaryButtonLabel:r.primaryButtonLabel},...r?.primaryButtonAriaLabel!==void 0&&{primaryButtonAriaLabel:r.primaryButtonAriaLabel}}}function _t(e,t,r){return{state:e,theme:t.theme,tab:t.tab,tabLabels:t.tabLabels,...t.tab==="register"&&r?.registerSessionReady!==void 0&&{registerSessionReady:r.registerSessionReady},primaryButtonLabel:r?.primaryButtonLabel??"Try Passkey",primaryButtonAriaLabel:r?.primaryButtonAriaLabel??"Try Passkey, use this device"}}function Nn(e){return typeof e?.getClientStatus=="function"}async function hr(e){if(!Nn(e.envStatusPort))return T;let t=e.envStatusPort,r=k(e.currentState),n=F(e.mode)?e.mode:"login",o=e.isMobileOverride===!0,i=e.fallbackType==="email"||e.fallbackType==="qr"?e.fallbackType:void 0,a=R(r,{type:"ENV_EVAL_START"}),l;try{let h=await t.getClientStatus();if(!ct(h))return R(a,{type:"ENV_ERROR"});l=h}catch{return R(a,{type:"ENV_ERROR"})}let d=o===!0?"fallback":l.recommendedFlow,p={recommendedFlow:d,mode:n,...d==="fallback"&&i!=null&&{fallbackType:i}};return R(a,{type:"ENV_RESOLVED",payload:p})}function gr(e){return R(e,{type:"START_AUTH"})!==e}function Bn(e,t,r,n){let o=R(e,{type:"START_AUTH"});return t==="register"?r.register(n):r.authenticate(n),o}var Fn={email:{type:"AUTH_FALLBACK_EMAIL"},qr:{type:"AUTH_FALLBACK_QR"},generic:{type:"AUTH_FALLBACK"}};function Kn(e,t){return R(e,Fn[t==="email"?"email":t==="qr"?"qr":"generic"])}var v={envEvalStart(e){return R(e,{type:"ENV_EVAL_START"})},evaluateEnv(e){return hr(e)},startAuth(e,t,r,n){return Bn(e,t,r,n)},handleAuthSuccess(e){return R(e,{type:"AUTH_SUCCESS"})},handleAuthError(e){return R(e,{type:"AUTH_ERROR"})},tryHandleAuthSuccess(e){return e!=="AUTHENTICATING"?null:R(e,{type:"AUTH_SUCCESS"})},tryHandleAuthError(e){return e!=="AUTHENTICATING"?null:R(e,{type:"AUTH_ERROR"})},handleFallback(e,t){return Kn(e,t)},tabChange(e,t){return R(e,{type:"TAB_CHANGE",payload:{tab:t}})},reset(e){return R(e,{type:"RESET"})}};function V(e){return e==null||e.trim()===""?"":e.trim()}function M(e){let t=V(e);return t===""?null:t}function Oe(e){if(e==null)return!1;let t=e.trim().toLowerCase();return t==="true"||t==="1"||t===""}function br(e){if(e==null||e.trim()==="")return null;let t=e.trim().toLowerCase();return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:null}function C(e,t,r){if(e==null||e.trim()==="")return r;let n=e.trim().toLowerCase();return t.includes(n)?n:r}function Er(e,t){if(e==null||e.trim()==="")return;let r=e.trim().toLowerCase();if(t.includes(r))return r}function Rt(e){let t={appId:V(e.getAttribute("app-id")),publishableKey:V(e.getAttribute("publishable-key")),mode:C(e.getAttribute("mode"),re,Se),externalUserId:M(e.getAttribute("external-user-id")),theme:C(e.getAttribute("theme"),B,K),action:C(e.getAttribute("action"),se,Me),triggerOnly:Oe(e.getAttribute("trigger-only")),buttonVariant:C(e.getAttribute("button-variant"),ae,Le)};return Et(t)}var H="mellon-root",De=".mellon-btn",ke='[data-mellon-action^="fallback"]',we="fallback-email",Q="fallback-qr",pe="TryMellon",vt="Try Passkey",me="TryMellon, open authentication",Tt="Try Passkey, use this device",w="http://www.w3.org/2000/svg",St="mellon-modal-wrapper",fe="mellon-modal-overlay",Ct="mellon-modal-panel",he="mellon-modal-tabs",It="mellon-modal-content",q="cross-device",Mt="fallback-cta",Pe="mellon-dialog-title",ge="mellon-dialog-desc",yr="TryMellon \u2014 Sign in or register",Ar=e=>`${e} \u2014 Sign in or register`,_r="Pick Register or Sign in to continue.",Rr="Or sign in with",L="mellon-cross-device-wrap",Lt="mellon-modal-separator",xt="mellon-modal-close-btn",vr="Close dialog",Tr="Try from another device",Sr="mellon-cross-device-cta",Cr="Try with QR",Ir="mellon-cross-device-skeleton",Mr="mellon-cross-device-error",Lr="mellon-cross-device-slot-wrap",xr="Loading QRs",Or="QR could not be loaded. Try again.";function Dr(){let e=document.createElementNS(w,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("class","mellon-btn-icon"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","2"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round");let t=document.createElementNS(w,"path");t.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(w,"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(w,"path");return n.setAttribute("d","M5 19.05A9 9 0 0 1 3 12a9 9 0 0 1 2-5.05"),e.appendChild(t),e.appendChild(r),e.appendChild(n),e}function Vn(e,t=pe,r=me){let n=document.createElement("button");return n.type="button",n.className="mellon-btn",n.setAttribute("aria-label",r),n.disabled=e,n.appendChild(Dr()),n.appendChild(document.createTextNode(t)),n}function Hn(e,t=pe,r=me){let n=document.createElement("button");n.type="button",n.className="mellon-btn mellon-btn-pill",n.setAttribute("aria-label",r),n.disabled=e;let o=document.createElement("span");return o.className="mellon-btn-pill-icon-circle",o.setAttribute("aria-hidden","true"),o.appendChild(Dr()),n.appendChild(o),n.appendChild(document.createTextNode(t)),n}function qn(e,t=pe,r=me){return n=>e==="pill"?Hn(n,t,r):Vn(n,t,r)}function jn(e){return{variant:e.buttonVariant??"default",label:e.primaryButtonLabel??pe,ariaLabel:e.primaryButtonAriaLabel??me}}function Ot(e){let{variant:t,label:r,ariaLabel:n}=jn(e);return qn(t,r,n)(!1)}function Gn(e){let{shadowRoot:t}=e,r=t.getElementById(H);return r||(r=document.createElement("div"),r.id=H,r.className="mellon-root",t.appendChild(r)),r}function $(e,t){let r=document.createElement("p");return r.className=e,r.textContent=t,r}function Wn(e,t){let r=document.createElement("button");return r.type="button",r.className="mellon-btn mellon-btn-fallback",r.setAttribute("data-mellon-action",e),r.textContent=t,r}var Yn={FALLBACK:{action:"fallback",label:"Continuar"},FALLBACK_EMAIL:{action:we,label:"Continuar con email"},FALLBACK_QR:{action:Q,label:"Continuar con QR"}};function zn(e){let t=document.createElement("div");t.className="mellon-fallback";let r=document.createElement("p");r.className="mellon-message",r.textContent="Fallback disponible.",t.appendChild(r);let{action:n,label:o}=Yn[e];return t.appendChild(Wn(n,o)),t}function Qn(e,t){let r=document.createDocumentFragment();switch(e){case"IDLE":case"EVALUATING_ENV":r.appendChild($("mellon-loading","Loading\u2026"));break;case"READY_LOGIN":r.appendChild(Ot(t));break;case"READY_REGISTER":t.registerSessionReady===!1?r.appendChild($("mellon-loading","Preparando registro\u2026")):r.appendChild(Ot(t));break;case"READY":r.appendChild(Ot(t));break;case"AUTHENTICATING":r.appendChild($("mellon-loading","Authenticating\u2026"));break;case"SUCCESS":r.appendChild($("mellon-message","Success."));break;case"ERROR":r.appendChild($("mellon-message","Something went wrong."));break;case"FALLBACK":case"FALLBACK_EMAIL":case"FALLBACK_QR":r.appendChild(zn(e));break;default:r.appendChild($("mellon-loading","Loading\u2026"))}return r}function Dt(e,t,r={}){let n=k(t),o=Gn(e),i=Qn(n,r);o.replaceChildren(...Array.from(i.childNodes))}function $n(e){return{theme:e.theme,mode:e.mode,buttonVariant:e.buttonVariant,registerSessionReady:e.registerSessionReady,primaryButtonLabel:e.primaryButtonLabel,primaryButtonAriaLabel:e.primaryButtonAriaLabel}}function Xn(e){return{theme:e.theme,mode:e.tab,buttonVariant:"pill",registerSessionReady:e.registerSessionReady,primaryButtonLabel:e.primaryButtonLabel,primaryButtonAriaLabel:e.primaryButtonAriaLabel}}function kr(e,t){Dt(e,t.state,$n(t))}function wr(e,t){Dt(e,t.state,Xn(t))}var Pr=".mellon-modal-tabs",kt="data-tab",Ur='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',Nr='[data-mellon-modal-close="true"]';function Br(e){if(e===we)return"email";if(e===Q)return"qr"}function Fr(e,t){let r=n=>{let o=n.target instanceof Element?n.target:null;if(!o)return;let i=o.closest(ke);if(i instanceof HTMLButtonElement){t.onFallbackClick(Br(i.getAttribute("data-mellon-action")));return}o.closest(De)&&t.onPrimaryClick()};return e.addEventListener("click",r),()=>e.removeEventListener("click",r)}function Kr(e,t){let r=n=>{let o=n.target instanceof Element?n.target:null;if(!o)return;if(t.onCloseClick&&o.closest(Nr)instanceof HTMLElement){t.onCloseClick();return}let i=o.closest(ke);if(i instanceof HTMLButtonElement){t.onFallbackClick(Br(i.getAttribute("data-mellon-action")));return}if(e.querySelector(Pr)?.contains(o)){let d=o.closest(`[${kt}]`)?.getAttribute(kt);if(d==="register"||d==="login"){t.onTabChange(d);return}}if(o.closest(De)){t.onPrimaryClick();return}if(t.onOverlayClick){let l=e.querySelector(`.${fe}`);l&&o===l&&t.onOverlayClick()}};return e.addEventListener("click",r),()=>e.removeEventListener("click",r)}var be=`
2
+ :host {
3
+ display: block;
4
+ max-width: 100%;
5
+ border: none;
6
+ outline: none;
7
+ /* Inherit --font-sans from host (e.g. landing: Noto Sans JP) or --mellon-font-sans; fallback system stack. */
8
+ font-family: var(--font-sans, var(--mellon-font-sans, system-ui, -apple-system, sans-serif));
9
+ --mellon-surface: var(--mellon-surface, hsl(var(--surface-elevated, 220 14% 98%)));
10
+ --mellon-text: var(--mellon-text, hsl(var(--text-strong, 220 12% 14%)));
11
+ --mellon-text-muted: var(--mellon-text-muted, hsl(var(--text-muted, 220 10% 48%)));
12
+ --mellon-border: var(--mellon-border, hsl(var(--border-strong, 220 10% 90%)));
13
+ --mellon-primary: var(--mellon-primary, hsl(var(--primary, 217 91% 58%)));
14
+ --mellon-primary-contrast: var(--mellon-primary-contrast, #fff);
15
+ --mellon-radius: var(--mellon-radius, var(--radius, 8px));
16
+ --mellon-focus-ring: var(--mellon-focus-ring, hsl(217 91% 50%));
17
+ --mellon-overlay: var(--mellon-overlay, rgba(0,0,0,0.5));
18
+ /* Panel padding: keeps content away from edges; host can override. */
19
+ --mellon-modal-panel-padding: var(--mellon-modal-panel-padding, 2rem);
20
+ /* Cross-device CTA: text colour (grey between strong and muted). */
21
+ --mellon-cta-text-color: var(--mellon-cta-text-color, var(--mellon-text-muted));
22
+ /* Separator: line and "or" text (standard UI divider). */
23
+ --mellon-separator-line: var(--mellon-border);
24
+ --mellon-separator-text: var(--mellon-text-muted);
25
+ /* QR icon button (cross-device). */
26
+ --mellon-qr-btn-bg: var(--mellon-qr-btn-bg, transparent);
27
+ --mellon-qr-btn-border: var(--mellon-qr-btn-border, var(--mellon-border));
28
+ --mellon-qr-btn-color: var(--mellon-qr-btn-color, var(--mellon-text));
29
+ }
30
+ :host([theme="dark"]) {
31
+ --mellon-surface: var(--mellon-surface, hsl(var(--surface-elevated, 220 12% 11%)));
32
+ --mellon-text: var(--mellon-text, hsl(var(--text-strong, 220 10% 96%)));
33
+ --mellon-text-muted: var(--mellon-text-muted, hsl(var(--text-muted, 220 8% 62%)));
34
+ --mellon-border: var(--mellon-border, hsl(var(--border-strong, 220 10% 22%)));
35
+ --mellon-primary: var(--mellon-primary, hsl(var(--primary, 217 96% 72%)));
36
+ --mellon-primary-contrast: var(--mellon-primary-contrast, #fff);
37
+ --mellon-focus-ring: var(--mellon-focus-ring, hsl(217 96% 65%));
38
+ }
39
+ /* Pill variant: landing-style button (circle + label) uses same tokens. */
40
+ :host([button-variant="pill"]) .mellon-btn-pill {
41
+ --mellon-btn-bg: var(--mellon-surface);
42
+ --mellon-btn-border: var(--mellon-border);
43
+ --mellon-btn-text: var(--mellon-text);
44
+ }
45
+ .mellon-root {
46
+ padding: 1rem;
47
+ min-width: 0;
48
+ background: var(--mellon-surface);
49
+ color: var(--mellon-text);
50
+ border-radius: var(--mellon-radius);
51
+ }
52
+ .mellon-loading,
53
+ .mellon-message {
54
+ margin: 0;
55
+ font-size: 0.875rem;
56
+ color: var(--mellon-text-muted);
57
+ }
58
+ .mellon-btn {
59
+ display: inline-flex;
60
+ align-items: center;
61
+ gap: 0.75rem;
62
+ min-height: 48px;
63
+ padding: 12px 24px;
64
+ font-size: 1rem;
65
+ font-weight: 500;
66
+ background: var(--mellon-primary);
67
+ color: var(--mellon-primary-contrast);
68
+ border: none;
69
+ border-radius: 8px;
70
+ cursor: pointer;
71
+ box-shadow: 0 1px 2px rgba(0,0,0,0.05);
72
+ }
73
+ .mellon-btn:hover:not(:disabled) {
74
+ opacity: 0.92;
75
+ }
76
+ .mellon-btn:focus-visible {
77
+ outline: 2px solid var(--mellon-focus-ring);
78
+ outline-offset: 2px;
79
+ }
80
+ .mellon-btn .mellon-btn-icon {
81
+ width: 1.25em;
82
+ height: 1.25em;
83
+ flex-shrink: 0;
84
+ }
85
+ .mellon-btn:disabled {
86
+ opacity: 0.6;
87
+ cursor: not-allowed;
88
+ }
89
+ .mellon-btn-pill {
90
+ min-height: 48px;
91
+ min-width: 48px;
92
+ padding: 0.5rem 1.25rem;
93
+ border-radius: 9999px;
94
+ border: none;
95
+ background: var(--mellon-surface);
96
+ color: var(--mellon-text);
97
+ gap: 0.75rem;
98
+ }
99
+ .mellon-btn-pill .mellon-btn-pill-icon-circle {
100
+ display: inline-flex;
101
+ align-items: center;
102
+ justify-content: center;
103
+ width: 1.275em;
104
+ height: 1.275em;
105
+ border-radius: 50%;
106
+ border: 2px solid currentColor;
107
+ flex-shrink: 0;
108
+ }
109
+ .mellon-btn-pill .mellon-btn-pill-icon-circle .mellon-btn-icon {
110
+ width: 0.85em;
111
+ height: 0.85em;
112
+ }
113
+ @media (prefers-reduced-motion: reduce) {
114
+ .mellon-btn, .mellon-modal-wrapper { transition: none; }
115
+ }
116
+ `.trim(),Vr=typeof ShadowRoot<"u"&&"adoptedStyleSheets"in ShadowRoot.prototype&&typeof CSSStyleSheet<"u"&&"replaceSync"in CSSStyleSheet.prototype;function wt(){if(!Vr)return null;try{let e=new CSSStyleSheet;return e.replaceSync(be),e}catch{return null}}function Pt(){return be}var Hr=`
117
+ /* Host: full viewport when open, no border (only the inner panel has border). */
118
+ :host {
119
+ border: none;
120
+ outline: none;
121
+ }
122
+ :host([open="true"]) {
123
+ position: fixed;
124
+ inset: 0;
125
+ z-index: 2147483647;
126
+ pointer-events: none;
127
+ }
128
+ :host([open="true"]) .mellon-modal-wrapper {
129
+ pointer-events: auto;
130
+ }
131
+ /* Wrapper: fills host, no border. Overlay + panel are the only visible layers. */
132
+ .mellon-modal-wrapper {
133
+ position: relative;
134
+ box-sizing: border-box;
135
+ width: 100%;
136
+ height: 100%;
137
+ border: none;
138
+ outline: none;
139
+ }
140
+ /* Overlay: full viewport, transparent grey only (no border). */
141
+ .mellon-modal-overlay {
142
+ position: fixed;
143
+ inset: 0;
144
+ background: var(--mellon-overlay, rgba(0,0,0,0.5));
145
+ z-index: 1;
146
+ border: none;
147
+ }
148
+ /* Panel: vertical gap 2rem (top/bottom) so it doesn't sit flush with viewport edge; sides 1.5rem. Match landing font via --font-sans. */
149
+ .mellon-modal-panel {
150
+ position: fixed;
151
+ inset: max(2rem, env(safe-area-inset-top)) max(1.5rem, env(safe-area-inset-right)) max(2rem, env(safe-area-inset-bottom)) max(1.5rem, env(safe-area-inset-left));
152
+ margin: auto;
153
+ z-index: 2;
154
+ width: calc(100% - 3rem);
155
+ max-width: 30rem;
156
+ max-height: min(90vh, 34rem);
157
+ overflow-y: auto;
158
+ overflow-x: hidden;
159
+ box-sizing: border-box;
160
+ background: var(--mellon-surface);
161
+ color: var(--mellon-text);
162
+ font-family: var(--font-sans, var(--mellon-font-sans, inherit));
163
+ border-radius: 12px;
164
+ border: 1px solid var(--mellon-border);
165
+ padding: var(--mellon-modal-panel-padding);
166
+ box-shadow: 0 4px 6px -1px rgba(0,0,0,0.08), 0 2px 4px -2px rgba(0,0,0,0.04);
167
+ -webkit-overflow-scrolling: touch;
168
+ }
169
+ /* Close button: circular "X" in the top-right corner, aligned with panel padding. */
170
+ .mellon-modal-close-btn {
171
+ position: absolute;
172
+ top: 0.75rem;
173
+ right: 0.75rem;
174
+ left: auto;
175
+ bottom: auto;
176
+ width: 2.25rem; /* 36px */
177
+ height: 2.25rem; /* 36px */
178
+ display: inline-flex;
179
+ align-items: center;
180
+ justify-content: center;
181
+ border-radius: 9999px;
182
+ border: none;
183
+ background: color-mix(in srgb, var(--mellon-surface) 80%, #000 20%);
184
+ color: var(--mellon-text-muted);
185
+ cursor: pointer;
186
+ padding: 0;
187
+ font-size: 1.1rem;
188
+ line-height: 1;
189
+ }
190
+ .mellon-modal-close-btn:hover:not(:disabled) {
191
+ background: color-mix(in srgb, var(--mellon-surface) 70%, #000 30%);
192
+ color: var(--mellon-text);
193
+ }
194
+ .mellon-modal-close-btn:focus-visible {
195
+ outline: 2px solid var(--mellon-focus-ring);
196
+ outline-offset: 2px;
197
+ }
198
+ :host([theme="dark"]) .mellon-modal-panel {
199
+ box-shadow: 0 8px 24px -4px rgba(0,0,0,0.35), 0 4px 8px -4px rgba(0,0,0,0.2);
200
+ }
201
+ /* Dialog title and description: centered, with vertical breathing room. */
202
+ .mellon-dialog-title,
203
+ .mellon-dialog-desc {
204
+ margin: 0 0 0.75rem;
205
+ padding: 0;
206
+ font-size: 1rem;
207
+ line-height: 1.5;
208
+ color: var(--mellon-text);
209
+ text-align: center;
210
+ }
211
+ .mellon-dialog-title {
212
+ font-weight: 600;
213
+ font-size: 1.125rem;
214
+ margin-top: 1.25rem;
215
+ }
216
+ .mellon-dialog-desc {
217
+ color: var(--mellon-text-muted);
218
+ font-size: 0.875rem;
219
+ margin-bottom: 1rem;
220
+ }
221
+ /* Modal spacing scale: base 0.5rem (8px); sections 0.75\u20131rem; tight 0.25rem. */
222
+ .mellon-modal-tabs {
223
+ display: flex;
224
+ gap: 0;
225
+ padding: 0 0 0.75rem;
226
+ border-bottom: none;
227
+ }
228
+ .mellon-modal-tabs button {
229
+ flex: 1;
230
+ min-height: 2.75rem;
231
+ padding: 0.625rem 1rem;
232
+ font-size: 0.875rem;
233
+ font-weight: 400;
234
+ background: transparent;
235
+ color: var(--mellon-text-muted);
236
+ border: none;
237
+ border-bottom: 1px solid var(--mellon-border);
238
+ cursor: pointer;
239
+ }
240
+ .mellon-modal-tabs button[aria-selected="true"] {
241
+ border-bottom-color: var(--mellon-primary);
242
+ font-weight: 600;
243
+ color: var(--mellon-text);
244
+ }
245
+ .mellon-modal-tabs button:hover {
246
+ color: var(--mellon-text);
247
+ }
248
+ .mellon-modal-tabs button:focus-visible {
249
+ outline: 2px solid var(--mellon-focus-ring);
250
+ outline-offset: 2px;
251
+ }
252
+ /* Content wrapper: QR wrap \u2192 separator "or" \u2192 passkey; all centered with consistent vertical gap. */
253
+ .mellon-modal-content {
254
+ display: flex;
255
+ flex-direction: column;
256
+ align-items: center;
257
+ gap: 0.5rem; /* 8px */
258
+ }
259
+ /* QR / cross-device area: centered; no min-height when empty to avoid extra space. */
260
+ .mellon-cross-device-wrap {
261
+ min-height: 11.25rem; /* 180px */
262
+ width: 100%;
263
+ display: flex;
264
+ align-items: center;
265
+ justify-content: center;
266
+ position: relative;
267
+ margin-top: 0.85rem; /* ~10% m\xE1s margen con el top (tabs) */
268
+ margin-bottom: 0.5rem; /* 8px */
269
+ }
270
+ /* Skeleton and error (modal-owned): visibility by data-qr-area-state. */
271
+ .mellon-cross-device-skeleton,
272
+ .mellon-cross-device-error {
273
+ margin: 0;
274
+ font-size: 0.875rem;
275
+ color: var(--mellon-cta-text-color);
276
+ text-align: center;
277
+ width: 11.25rem; /* 180px */
278
+ height: 11.25rem; /* 180px */
279
+ padding: 0 0.75rem; /* 0 12px */
280
+ display: flex;
281
+ align-items: center;
282
+ justify-content: center;
283
+ border-radius: 0.75rem;
284
+ border: 1px dashed var(--mellon-separator-line);
285
+ box-sizing: border-box;
286
+ background: var(--mellon-surface-elevated, rgba(128, 128, 128, 0.12));
287
+ }
288
+ .mellon-cross-device-wrap[data-qr-area-state="default"] .mellon-cross-device-error,
289
+ .mellon-cross-device-wrap[data-qr-area-state="loaded"] .mellon-cross-device-skeleton,
290
+ .mellon-cross-device-wrap[data-qr-area-state="loaded"] .mellon-cross-device-error {
291
+ display: none;
292
+ }
293
+ .mellon-cross-device-wrap[data-qr-area-state="waiting"] .mellon-cross-device-slot-wrap,
294
+ .mellon-cross-device-wrap[data-qr-area-state="waiting"] .mellon-cross-device-error {
295
+ display: none;
296
+ }
297
+ .mellon-cross-device-wrap[data-qr-area-state="waiting"] .mellon-cross-device-skeleton {
298
+ display: flex;
299
+ }
300
+ .mellon-cross-device-wrap[data-qr-area-state="timeout"] .mellon-cross-device-slot-wrap,
301
+ .mellon-cross-device-wrap[data-qr-area-state="timeout"] .mellon-cross-device-skeleton {
302
+ display: none;
303
+ }
304
+ .mellon-cross-device-wrap[data-qr-area-state="timeout"] .mellon-cross-device-error {
305
+ display: flex;
306
+ }
307
+ .mellon-cross-device-slot-wrap {
308
+ display: flex;
309
+ flex-direction: column;
310
+ align-items: center;
311
+ justify-content: center;
312
+ width: 11.25rem; /* 180px */
313
+ height: 11.25rem; /* 180px */
314
+ }
315
+ /* Default slot content: "Try from another device" (variable colour) + QR icon button; centered in column. */
316
+ .mellon-cross-device-cta {
317
+ display: flex;
318
+ flex-direction: column;
319
+ align-items: center;
320
+ gap: 0.75rem;
321
+ width: fit-content;
322
+ max-width: 100%;
323
+ margin-top: 0.5rem;
324
+ margin-left: auto;
325
+ margin-right: auto;
326
+ }
327
+ .mellon-cross-device-cta-text {
328
+ margin: 0;
329
+ font-size: 0.875rem;
330
+ color: var(--mellon-cta-text-color);
331
+ }
332
+ .mellon-cross-device-cta .mellon-btn-qr-icon {
333
+ display: inline-flex;
334
+ align-items: center;
335
+ justify-content: center;
336
+ min-width: 48px;
337
+ min-height: 48px;
338
+ padding: 0.5rem;
339
+ background: var(--mellon-qr-btn-bg);
340
+ color: var(--mellon-qr-btn-color);
341
+ border: 1px solid var(--mellon-qr-btn-border);
342
+ border-radius: var(--mellon-radius);
343
+ cursor: pointer;
344
+ }
345
+ .mellon-cross-device-cta .mellon-btn-qr-icon:hover:not(:disabled) {
346
+ background: var(--mellon-separator-line);
347
+ }
348
+ .mellon-cross-device-cta .mellon-btn-qr-icon:focus-visible {
349
+ outline: 2px solid var(--mellon-focus-ring);
350
+ outline-offset: 2px;
351
+ }
352
+ .mellon-qr-icon {
353
+ width: 1.75rem;
354
+ height: 1.75rem;
355
+ }
356
+ /* Separator: standard UI divider \u2014 line | "or" | line (all colours via variables). ~15% m\xE1s margen con el bloque de arriba. */
357
+ .mellon-modal-separator {
358
+ display: flex;
359
+ align-items: center;
360
+ gap: 1rem;
361
+ width: 100%;
362
+ margin-top: 0.875rem; /* 0.75rem + ~15% */
363
+ margin-bottom: 0;
364
+ font-size: 0.8125rem;
365
+ font-weight: 500;
366
+ color: var(--mellon-separator-text);
367
+ }
368
+ .mellon-modal-separator::before,
369
+ .mellon-modal-separator::after {
370
+ content: '';
371
+ flex: 1;
372
+ min-width: 0;
373
+ height: 0;
374
+ border-bottom: 1px solid var(--mellon-separator-line);
375
+ }
376
+ .mellon-modal-separator .mellon-separator-text {
377
+ text-transform: uppercase;
378
+ letter-spacing: 0.08em;
379
+ font-size: 0.75rem;
380
+ flex-shrink: 0;
381
+ position: relative;
382
+ padding: 0.375rem 1.25rem;
383
+ background: transparent;
384
+ z-index: 0;
385
+ }
386
+ .mellon-modal-separator .mellon-separator-text::before {
387
+ content: '';
388
+ position: absolute;
389
+ top: 50%;
390
+ left: 50%;
391
+ width: 140%;
392
+ height: 220%;
393
+ transform: translate(-50%, -50%) rotate(45deg);
394
+ border-radius: 0.35rem;
395
+ border: 2px solid var(--mellon-separator-line);
396
+ background: color-mix(in srgb, var(--mellon-surface) 80%, var(--mellon-text) 20%);
397
+ z-index: -1;
398
+ }
399
+ /* Passkey slot/root centered in content wrapper. Less space between separator and this block. */
400
+ .mellon-modal-separator + .mellon-root {
401
+ margin-top: -0.25rem;
402
+ }
403
+ .mellon-modal-content .mellon-root {
404
+ display: flex;
405
+ justify-content: center;
406
+ width: 100%;
407
+ }
408
+ /* QR skeleton loading dots: "Loading QRs" + animated trailing dots while waiting. */
409
+ .mellon-qr-dots {
410
+ display: inline-block;
411
+ width: 1.5em;
412
+ text-align: left;
413
+ overflow: hidden;
414
+ }
415
+ .mellon-qr-dots::after {
416
+ content: '...';
417
+ display: inline-block;
418
+ animation: mellon-qr-dots 1s steps(4, end) infinite;
419
+ }
420
+ @keyframes mellon-qr-dots {
421
+ 0% {
422
+ clip-path: inset(0 100% 0 0);
423
+ }
424
+ 33% {
425
+ clip-path: inset(0 66% 0 0);
426
+ }
427
+ 66% {
428
+ clip-path: inset(0 33% 0 0);
429
+ }
430
+ 100% {
431
+ clip-path: inset(0 0 0 0);
432
+ }
433
+ }
434
+ @media (prefers-reduced-motion: reduce) {
435
+ .mellon-qr-dots::after {
436
+ animation: none;
437
+ }
438
+ }
439
+ /* Minimal variant: transparent black, white border, same as landing (auth.styles modalContent) */
440
+ [data-mellon-modal-variant="minimal"] .mellon-modal-panel {
441
+ border-radius: 1rem;
442
+ border-width: 2px;
443
+ border-style: solid;
444
+ }
445
+ :host([theme="dark"]) [data-mellon-modal-variant="minimal"] {
446
+ --mellon-border: rgba(255, 255, 255, 0.9);
447
+ }
448
+ :host([theme="light"]) [data-mellon-modal-variant="minimal"] {
449
+ --mellon-border: rgba(0, 0, 0, 0.15);
450
+ }
451
+ :host([theme="dark"]) [data-mellon-modal-variant="minimal"] .mellon-modal-panel {
452
+ background: rgba(0, 0, 0, 0.88);
453
+ }
454
+ :host([theme="light"]) [data-mellon-modal-variant="minimal"] .mellon-modal-panel {
455
+ background: rgba(255, 255, 255, 0.95);
456
+ }
457
+ [data-mellon-modal-variant="minimal"] .mellon-modal-tabs {
458
+ padding: 0.5rem 1rem 0;
459
+ border-bottom-width: 2px;
460
+ }
461
+ [data-mellon-modal-variant="minimal"] .mellon-modal-tabs button {
462
+ padding: 0.4rem 0.6rem;
463
+ font-size: 0.8125rem;
464
+ }
465
+ /* Responsive: narrow viewports \u2014 minimum padding so 5% does not get too small. */
466
+ @media (max-width: 22.5rem) {
467
+ .mellon-modal-panel {
468
+ --mellon-modal-panel-padding: max(1rem, 5%);
469
+ }
470
+ .mellon-modal-tabs {
471
+ padding: 0.75rem 0;
472
+ }
473
+ .mellon-modal-tabs button {
474
+ padding: 0.625rem 0.75rem;
475
+ }
476
+ .mellon-modal-content {
477
+ gap: 0.75rem;
478
+ }
479
+ }
480
+ /* Responsive: very short viewport (e.g. landscape) \u2014 ensure panel scrolls. */
481
+ @media (max-height: 400px) {
482
+ .mellon-modal-panel {
483
+ max-height: calc(100dvh - 4rem);
484
+ }
485
+ }
486
+ `.trim();function qr(){return be+`
487
+ `+Hr}function jr(){if(!Vr)return null;try{let e=new CSSStyleSheet;return e.replaceSync(be+`
488
+ `+Hr),e}catch{return null}}var f=e=>({ok:!0,value:e}),c=e=>({ok:!1,error:e});var Ue=class e extends Error{code;details;isTryMellonError=!0;constructor(t,r,n){super(r),this.name="TryMellonError",this.code=t,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},Jn={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.",UNKNOWN_ERROR:"An unknown error occurred"};function b(e,t,r){return new Ue(e,t??Jn[e],r)}function Ut(e){return e instanceof Ue||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===!0}function Gr(){return b("NOT_SUPPORTED")}function A(e,t){return b("INVALID_ARGUMENT",`Invalid argument: ${e} - ${t}`,{field:e,reason:t})}function Wr(e){return b("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function Nt(e){return b("NOT_SUPPORTED",`No base64 ${e==="encode"?"encoding":"decoding"} available`,{type:e})}function Bt(e,t){try{let r=new URL(e);if(r.protocol!=="https:"&&r.protocol!=="http:")throw A(t,"must use http or https protocol")}catch(r){throw Ut(r)?r:A(t,"must be a valid URL")}}function j(e,t,r,n){if(!Number.isFinite(e))throw A(t,"must be a finite number");if(e<r||e>n)throw A(t,`must be between ${r} and ${n}`)}function Ne(e,t){if(typeof e!="string"||e.length===0)throw A(t,"must be a non-empty string");if(!/^[A-Za-z0-9_-]+$/.test(e))throw A(t,"must be a valid base64url string")}var Zn={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function Ee(e){if(typeof e!="string")return"UNKNOWN_ERROR";let t=e.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"}[t]??"UNKNOWN_ERROR"}function _(e){if(e instanceof DOMException){let t=e.name,r=e.message||"WebAuthn operation failed",n=Zn[t]??"UNKNOWN_ERROR";return b(n,r,{originalError:e})}return e instanceof Error?b("UNKNOWN_ERROR",e.message,{originalError:e}):b("UNKNOWN_ERROR","An unknown error occurred",{originalError:e})}function g(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function u(e){return typeof e=="string"}function P(e){return typeof e=="number"&&Number.isFinite(e)}function Be(e){return typeof e=="boolean"}function X(e){return Array.isArray(e)}function s(e,t){return c(b("UNKNOWN_ERROR",e,{...t,originalData:t?.originalData}))}function m(e,t){return e[t]}function Yr(e,t){return!g(e)||!u(e.name)||!u(e.id)?s("Invalid API response: challenge.rp must have name and id strings",{originalData:t}):f(!0)}function zr(e,t){return!g(e)||!u(e.id)||!u(e.name)||!u(e.displayName)?s("Invalid API response: challenge.user must have id, name, displayName strings",{originalData:t}):f(!0)}function Qr(e,t){if(!X(e))return s("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:t});for(let r of e)if(!g(r)||r.type!=="public-key"||!P(r.alg))return s("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:t});return f(!0)}function Ft(e,t){if(!g(e))return s("Invalid API response: user must be object",{field:"user",originalData:t});let r=m(e,"user_id"),n=m(e,"external_user_id");if(!u(r)||!u(n))return s("Invalid API response: user must have user_id and external_user_id strings",{originalData:t});let o=e.email,i=e.metadata;return o!==void 0&&!u(o)?s("Invalid API response: user.email must be string",{originalData:t}):i!==void 0&&(typeof i!="object"||i===null)?s("Invalid API response: user.metadata must be object",{originalData:t}):f({user_id:r,external_user_id:n,...o!==void 0&&{email:o},...i!==void 0&&{metadata:i}})}function Kt(e){if(!g(e))return s("Invalid API response: expected object",{originalData:e});let t=m(e,"session_id");if(!u(t))return s("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let r=m(e,"challenge");if(!g(r))return s("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=Yr(m(r,"rp"),e);if(!n.ok)return n;let o=zr(m(r,"user"),e);if(!o.ok)return o;let i=m(r,"challenge");if(!u(i))return s("Invalid API response: challenge.challenge must be string",{originalData:e});let a=Qr(m(r,"pubKeyCredParams"),e);if(!a.ok)return a;let l=r.timeout;if(l!==void 0&&!P(l))return s("Invalid API response: challenge.timeout must be number",{originalData:e});let d=r.excludeCredentials;if(d!==void 0){if(!X(d))return s("Invalid API response: excludeCredentials must be array",{originalData:e});for(let h of d)if(!g(h)||h.type!=="public-key"||!u(h.id))return s("Invalid API response: excludeCredentials items must have id and type",{originalData:e})}let p=r.authenticatorSelection;return p!==void 0&&!g(p)?s("Invalid API response: authenticatorSelection must be object",{originalData:e}):f({session_id:t,challenge:{rp:r.rp,user:r.user,challenge:i,pubKeyCredParams:r.pubKeyCredParams,...l!==void 0&&{timeout:l},...d!==void 0&&{excludeCredentials:d},...p!==void 0&&{authenticatorSelection:p}}})}function Vt(e){if(!g(e))return s("Invalid API response: expected object",{originalData:e});let t=m(e,"session_id");if(!u(t))return s("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let r=m(e,"challenge");if(!g(r))return s("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=m(r,"challenge"),o=m(r,"rpId"),i=r.allowCredentials;if(!u(n))return s("Invalid API response: challenge.challenge must be string",{originalData:e});if(!u(o))return s("Invalid API response: challenge.rpId must be string",{originalData:e});if(i!==void 0&&!X(i))return s("Invalid API response: allowCredentials must be array",{originalData:e});if(i){for(let d of i)if(!g(d)||d.type!=="public-key"||!u(d.id))return s("Invalid API response: allowCredentials items must have id and type",{originalData:e})}let a=r.timeout;if(a!==void 0&&!P(a))return s("Invalid API response: challenge.timeout must be number",{originalData:e});let l=r.userVerification;return l!==void 0&&!["required","preferred","discouraged"].includes(String(l))?s("Invalid API response: userVerification must be required|preferred|discouraged",{originalData:e}):f({session_id:t,challenge:{challenge:n,rpId:o,allowCredentials:i??[],...a!==void 0&&{timeout:a},...l!==void 0&&{userVerification:l}}})}function Ht(e){if(!g(e))return s("Invalid API response: expected object",{originalData:e});let t=m(e,"credential_id"),r=m(e,"status"),n=m(e,"session_token"),o=m(e,"user");if(!u(t))return s("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!u(r))return s("Invalid API response: status must be string",{field:"status",originalData:e});if(!u(n))return s("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=Ft(o,e);if(!i.ok)return s(i.error.message,{originalData:e});let a=e.redirect_url;return a!==void 0&&!u(a)?s("Invalid API response: redirect_url must be string",{originalData:e}):f({credential_id:t,status:r,session_token:n,user:i.value,...a!==void 0&&{redirect_url:a}})}function qt(e){if(!g(e))return s("Invalid API response: expected object",{originalData:e});let t=m(e,"authenticated"),r=m(e,"session_token"),n=m(e,"user"),o=m(e,"signals");if(!Be(t))return s("Invalid API response: authenticated must be boolean",{field:"authenticated",originalData:e});if(!u(r))return s("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=Ft(n,e);if(!i.ok)return s(i.error.message,{originalData:e});if(o!==void 0&&!g(o))return s("Invalid API response: signals must be object",{originalData:e});let a=e.redirect_url;return a!==void 0&&!u(a)?s("Invalid API response: redirect_url must be string",{originalData:e}):f({authenticated:t,session_token:r,user:i.value,signals:o,...a!==void 0&&{redirect_url:a}})}function jt(e){if(!g(e))return s("Invalid API response: expected object",{originalData:e});let t=m(e,"valid"),r=m(e,"user_id"),n=m(e,"external_user_id"),o=m(e,"tenant_id"),i=m(e,"app_id");return Be(t)?u(r)?u(n)?u(o)?u(i)?f({valid:t,user_id:r,external_user_id:n,tenant_id:o,app_id:i}):s("Invalid API response: app_id must be string",{field:"app_id",originalData:e}):s("Invalid API response: tenant_id must be string",{field:"tenant_id",originalData:e}):s("Invalid API response: external_user_id must be string",{field:"external_user_id",originalData:e}):s("Invalid API response: user_id must be string",{field:"user_id",originalData:e}):s("Invalid API response: valid must be boolean",{field:"valid",originalData:e})}function Gt(e){if(!g(e))return s("Invalid API response: expected object",{originalData:e});let t=e.session_token??e.sessionToken;if(!u(t))return s("Invalid API response: session_token/sessionToken must be string",{field:"session_token",originalData:e});let r=e.redirect_url;return r!==void 0&&!u(r)?s("Invalid API response: redirect_url must be string",{originalData:e}):f({sessionToken:t,...r!==void 0&&{redirectUrl:r}})}var eo=["pending_passkey","pending_data","completed"],to=["pending_data","completed"];function Wt(e){if(!g(e))return s("Invalid API response: expected object",{originalData:e});let t=m(e,"session_id"),r=m(e,"onboarding_url"),n=m(e,"expires_in");return u(t)?u(r)?P(n)?f({session_id:t,onboarding_url:r,expires_in:n}):s("Invalid API response: expires_in must be number",{field:"expires_in",originalData:e}):s("Invalid API response: onboarding_url must be string",{field:"onboarding_url",originalData:e}):s("Invalid API response: session_id must be string",{field:"session_id",originalData:e})}function Yt(e){if(!g(e))return s("Invalid API response: expected object",{originalData:e});let t=m(e,"status"),r=m(e,"onboarding_url"),n=m(e,"expires_in");return!u(t)||!eo.includes(t)?s("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):u(r)?P(n)?f({status:t,onboarding_url:r,expires_in:n}):s("Invalid API response: expires_in must be number",{originalData:e}):s("Invalid API response: onboarding_url must be string",{originalData:e})}function zt(e){if(!g(e))return s("Invalid API response: expected object",{originalData:e});let t=m(e,"session_id"),r=m(e,"status"),n=m(e,"onboarding_url");if(!u(t))return s("Invalid API response: session_id must be string",{field:"session_id",originalData:e});if(r!=="pending_passkey")return s("Invalid API response: status must be pending_passkey",{field:"status",originalData:e});if(!u(n))return s("Invalid API response: onboarding_url must be string",{originalData:e});let o=e.challenge,i;if(o!==void 0){let a=ro(o);if(!a.ok)return a;i=a.value}return f({session_id:t,status:"pending_passkey",onboarding_url:n,...i!==void 0&&{challenge:i}})}function ro(e){if(!g(e))return s("Invalid API response: challenge must be object",{originalData:e});let t=m(e,"rp"),r=m(e,"user"),n=m(e,"challenge"),o=m(e,"pubKeyCredParams");if(!g(t)||!u(t.name)||!u(t.id))return s("Invalid API response: challenge.rp must have name and id",{originalData:e});if(!g(r)||!u(r.id)||!u(r.name)||!u(r.displayName))return s("Invalid API response: challenge.user must have id, name, displayName",{originalData:e});if(!u(n))return s("Invalid API response: challenge.challenge must be string",{originalData:e});if(!X(o))return s("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let i of o)if(!g(i)||i.type!=="public-key"||!P(i.alg))return s("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});return f({rp:t,user:r,challenge:n,pubKeyCredParams:o})}function Qt(e){if(!g(e))return s("Invalid API response: expected object",{originalData:e});let t=m(e,"session_id"),r=m(e,"status"),n=m(e,"user_id"),o=m(e,"tenant_id");return u(t)?!u(r)||!to.includes(r)?s("Invalid API response: status must be pending_data|completed",{originalData:e}):u(n)?u(o)?f({session_id:t,status:r,user_id:n,tenant_id:o}):s("Invalid API response: tenant_id must be string",{originalData:e}):s("Invalid API response: user_id must be string",{originalData:e}):s("Invalid API response: session_id must be string",{originalData:e})}function $t(e){if(!g(e))return s("Invalid API response: expected object",{originalData:e});let t=m(e,"session_id"),r=m(e,"status"),n=m(e,"user_id"),o=m(e,"tenant_id"),i=m(e,"session_token");return u(t)?r!=="completed"?s("Invalid API response: status must be completed",{originalData:e}):!u(n)||!u(o)||!u(i)?s("Invalid API response: user_id, tenant_id, session_token must be strings",{originalData:e}):f({session_id:t,status:"completed",user_id:n,tenant_id:o,session_token:i}):s("Invalid API response: session_id must be string",{originalData:e})}function Fe(e){return e==null?f(void 0):g(e)&&Object.keys(e).length===0?f(void 0):s("Invalid API response: expected empty body (204)",{originalData:e})}function no(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.challenge=="string"&&t.rp!=null&&typeof t.rp=="object"&&t.user!=null&&typeof t.user=="object"&&Array.isArray(t.pubKeyCredParams)}function oo(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.challenge=="string"&&typeof t.rpId=="string"}function Ke(e){if(!g(e))return s("Invalid API response: expected object",{originalData:e});let t="resultado"in e&&g(e.resultado)?e.resultado:e,r=t.session_id,n=t.qr_url,o=t.expires_at,i=t.polling_token;if(!u(r)||!u(n)||!u(o)||!u(i))return s("Invalid API response: missing required fields",{originalData:e});let a={session_id:r,qr_url:n,expires_at:o,polling_token:i};return t.external_user_id!==void 0&&u(t.external_user_id)&&(a.external_user_id=t.external_user_id),f(a)}function Xt(e){if(!g(e))return s("Invalid API response: expected object",{originalData:e});let t="resultado"in e&&g(e.resultado)?e.resultado:e,r=t.status;if(!u(r)||!["pending","authenticated","completed"].includes(r))return s("Invalid API response: invalid status",{originalData:e});let n=t.user_id,o=t.session_token,i=t.redirect_url;return n!==void 0&&!u(n)?s("Invalid API response: user_id must be a string when present",{originalData:e}):o!==void 0&&!u(o)?s("Invalid API response: session_token must be a string when present",{originalData:e}):i!==void 0&&!u(i)?s("Invalid API response: redirect_url must be a string when present",{originalData:e}):f({status:r,user_id:n,session_token:o,redirect_url:i})}function Jt(e){if(!g(e))return s("Invalid API response: expected object",{originalData:e});let t=e.type,r=t==="registration"?"registration":"auth",n=e.options;if(!g(n))return s("Invalid API response: options are required",{originalData:e});let o=200,i=$r(e.approval_context,o),a=$r(e.application_name,o);if(i===!1||a===!1)return s("Invalid API response: approval_context/application_name must be string max 200 chars",{originalData:e});let l={};return typeof i=="string"&&(l.approval_context=i),typeof a=="string"&&(l.application_name=a),r==="registration"?no(n)?f({type:"registration",options:n,...l}):s("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):oo(n)?f({type:"auth",options:n,...l}):s("Invalid API response: auth options must have challenge and rpId",{originalData:e})}function $r(e,t){if(e!=null)return typeof e!="string"||e.length>t?!1:e}function Zt(e){if(!g(e))return s("Invalid API response: expected object",{originalData:e});let t=m(e,"challenge"),r=m(e,"recovery_session_id");return g(t)?u(r)?f({challenge:t,recovery_session_id:r}):s("Invalid API response: recovery_session_id must be string",{field:"recovery_session_id",originalData:e}):s("Invalid API response: challenge must be object",{field:"challenge",originalData:e})}function er(e){if(!g(e))return s("Invalid API response: expected object",{originalData:e});let t=m(e,"status"),r=m(e,"session_token"),n=m(e,"user"),o=m(e,"credential_id");if(!u(t))return s("Invalid API response: status must be string",{field:"status",originalData:e});if(!u(r))return s("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!u(o))return s("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!g(n))return s("Invalid API response: user must be object",{field:"user",originalData:e});let i=m(n,"user_id");if(!u(i))return s("Invalid API response: user.user_id must be string",{field:"user.user_id",originalData:e});let l=e.redirect_url;if(l!==void 0&&!u(l))return s("Invalid API response: redirect_url must be string",{field:"redirect_url",originalData:e});let d=n;return f({status:t,session_token:r,credential_id:o,user:{user_id:i,external_user_id:u(d.external_user_id)?d.external_user_id:void 0,email:u(d.email)?d.email:void 0,metadata:g(d.metadata)?d.metadata:void 0},...l!==void 0&&{redirect_url:l}})}var Ve=class{constructor(t,r,n={}){this.httpClient=t;this.baseUrl=r;this.defaultHeaders=n}mergeHeaders(t){return{...this.defaultHeaders,...t}}async post(t,r,n){let o=`${this.baseUrl}${t}`,i=await this.httpClient.post(o,r,this.mergeHeaders());return i.ok?n(i.value):c(i.error)}async get(t,r,n){let o=`${this.baseUrl}${t}`,i=await this.httpClient.get(o,this.mergeHeaders(n));return i.ok?r(i.value):c(i.error)}async startRegister(t){return this.post("/v1/passkeys/register/start",t,Kt)}async startAuth(t){return this.post("/v1/passkeys/auth/start",t,Vt)}async finishRegister(t){return this.post("/v1/passkeys/register/finish",t,Ht)}async finishAuthentication(t){return this.post("/v1/passkeys/auth/finish",t,qt)}async validateSession(t){return this.get("/v1/sessions/validate",jt,{Authorization:`Bearer ${t}`})}async startEmailFallback(t){let r=`${this.baseUrl}/v1/fallback/email/start`,n=await this.httpClient.post(r,{userId:t.userId,email:t.email},this.mergeHeaders());return n.ok?f(void 0):c(n.error)}async verifyEmailCode(t){let r={userId:t.userId,code:t.code};return t.successUrl&&(r.success_url=t.successUrl),this.post("/v1/fallback/email/verify",r,Gt)}async startOnboarding(t){return this.post("/v1/onboarding/start",t,Wt)}async getOnboardingStatus(t){return this.get(`/v1/onboarding/${t}/status`,Yt)}async getOnboardingRegister(t){return this.get(`/v1/onboarding/${t}/register`,zt)}async registerOnboardingPasskey(t,r){return this.post(`/v1/onboarding/${t}/register-passkey`,r,Qt)}async completeOnboarding(t,r){return this.post(`/v1/onboarding/${t}/complete`,r,$t)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},Ke)}async initCrossDeviceRegistration(t){let r=typeof t?.externalUserId=="string"?t.externalUserId.trim():"",n=r.length>0?{external_user_id:r}:{};return this.post("/v1/auth/cross-device/init-registration",n,Ke)}async getCrossDeviceStatus(t,r){let n={};return typeof r=="string"&&r.length>0&&(n["X-Polling-Token"]=r),this.get(`/v1/auth/cross-device/status/${t}`,Xt,Object.keys(n).length>0?n:void 0)}async getCrossDeviceContext(t){return this.get(`/v1/auth/cross-device/context/${t}`,Jt)}async verifyCrossDeviceAuth(t){return this.post("/v1/auth/cross-device/verify",t,Fe)}async verifyCrossDeviceRegistration(t){return this.post("/v1/auth/cross-device/verify-registration",t,Fe)}async verifyAccountRecoveryOtp(t,r){return this.post("/v1/users/recovery/verify",{external_id:t,otp:r},Zt)}async completeAccountRecovery(t,r){return this.post("/v1/users/recovery/complete",{recovery_session_id:t,credential:r},er)}};function io(e){return typeof e=="object"&&e!==null&&e.ok===!0&&"resultado"in e}function Zr(e){if(typeof e!="object"||e===null)return!1;let t=e;if(t.ok!==!1||!t.error||typeof t.error!="object")return!1;let r=t.error;return typeof r.code=="string"&&typeof r.message=="string"}function Xr(e,t){if(Zr(e))return{message:e.error.message,code:Ee(e.error.code)};let r=e,n=r?.error;if(typeof n=="object"&&n!==null&&"code"in n&&typeof n.code=="string")return{message:n.message??r?.message??t,code:Ee(n.code)};let o=r?.message??t,i=r?.error,a=typeof i=="string"?Ee(i):i===void 0?"NETWORK_FAILURE":Ee(String(i));return{message:o,code:a}}var so=3e4;function ao(){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 Jr(e,t){let r=t*Math.pow(2,e);return Math.min(r,so)}function lo(e,t){return e!=="GET"?!1:t>=500||t===429}var He=class{constructor(t,r=0,n=1e3,o){this.timeoutMs=t;this.maxRetries=r;this.retryDelayMs=n;this.logger=o}async get(t,r){return this.request(t,{method:"GET",headers:r})}async post(t,r,n){return this.request(t,{method:"POST",body:JSON.stringify(r),headers:{"Content-Type":"application/json",...n}})}async request(t,r){let n=(r.method??"GET").toUpperCase(),o=ao(),i=new Headers(r.headers);i.set("X-Request-Id",o),this.logger&&this.logger.debug("request",{requestId:o,url:t,method:n});let a;for(let l=0;l<=this.maxRetries;l++)try{let d=new AbortController,p=setTimeout(()=>d.abort(),this.timeoutMs);try{let h=await fetch(t,{...r,headers:i,signal:d.signal});if(!h.ok){let O;try{O=await h.json()}catch{}let{message:Y,code:ar}=Xr(O,h.statusText),D=b(ar,Y,{requestId:o,status:h.status,statusText:h.statusText,data:O});if(lo(n,h.status)&&l<this.maxRetries){a=D,clearTimeout(p),await new Promise(kn=>setTimeout(kn,Jr(l,this.retryDelayMs)));continue}return c(D)}if(h.status===204)return f(void 0);if(h.headers.get("content-length")==="0")return f(void 0);let y=await h.json();if(io(y))return f(y.resultado);let I=y;if(typeof y=="object"&&y!==null&&I.ok===!0&&!("resultado"in I))return f(void 0);if(Zr(y)){let{message:O,code:Y}=Xr(y,h.statusText);return c(b(Y,O,{requestId:o,status:h.status,statusText:h.statusText,data:y}))}return f(y)}finally{clearTimeout(p)}}catch(d){if(a=d,n==="GET"&&l<this.maxRetries)await new Promise(h=>setTimeout(h,Jr(l,this.retryDelayMs)));else break}return a instanceof Error&&a.name==="AbortError"?c(b("TIMEOUT","Request timed out",{requestId:o})):c(b("NETWORK_FAILURE",a instanceof Error?a.message:"Request failed",{requestId:o,cause:a}))}};function x(e){let t=new Uint8Array(e),r=Array.from(t,o=>String.fromCharCode(o)).join("");if(typeof globalThis.btoa>"u")throw Nt("encode");return globalThis.btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function uo(e){if(typeof globalThis.atob>"u")throw Nt("decode");let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4,n=r===0?t:t+"=".repeat(4-r),o=globalThis.atob(n);return Uint8Array.from(o,i=>i.charCodeAt(0))}function J(e){let t=uo(e),r=new ArrayBuffer(t.length);return new Uint8Array(r).set(t),r}function en(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function U(e){if(!e.response)throw b("UNKNOWN_ERROR","Credential response is missing",{credential:e});let t=e.response;if(!en(t))throw b("UNKNOWN_ERROR","Invalid credential response structure",{response:t});if(!("attestationObject"in t))throw b("UNKNOWN_ERROR","Invalid credential response structure for register: attestationObject is missing",{response:t});let r=t.clientDataJSON,n=t.attestationObject;return{id:e.id,rawId:x(e.rawId),response:{clientDataJSON:x(r),attestationObject:x(n)},type:"public-key"}}function qe(e){if(!e.response)throw b("UNKNOWN_ERROR","Credential response is missing",{credential:e});let t=e.response;if(!en(t))throw b("UNKNOWN_ERROR","Invalid credential response structure",{response:t});if(!("authenticatorData"in t)||!("signature"in t))throw b("UNKNOWN_ERROR","Invalid credential response structure for auth: authenticatorData or signature is missing",{response:t});let r=t.clientDataJSON,n=t.authenticatorData,o=t.signature,i=t.userHandle;return{id:e.id,rawId:x(e.rawId),response:{authenticatorData:x(n),clientDataJSON:x(r),signature:x(o),...i&&{userHandle:x(i)}},type:"public-key"}}function Z(){try{return!(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return!1}}async function co(){try{return!Z()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?!1:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function je(){let e=Z(),t=await co();return{isPasskeySupported:e,platformAuthenticatorAvailable:t,recommendedFlow:e?"passkey":"fallback"}}function G(e,t="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw Wr(t)}async function ye(e){let{operation:t,eventEmitter:r,start:n,createOptions:o,invoke:i,finish:a}=e;try{if(r.emit("start",{type:"start",operation:t}),!Z()){let E=Gr();return r.emit("error",{type:"error",error:E}),c(E)}let l=await n();if(!l.ok)return r.emit("error",{type:"error",error:l.error}),c(l.error);let d=o(l.value);if(!d.ok)return r.emit("error",{type:"error",error:d.error}),c(d.error);let p=await i(d.value);if(!p){let E=A("credential",`${t==="register"?"creation":"retrieval"} failed`);return r.emit("error",{type:"error",error:E}),c(E)}try{G(p)}catch(E){let y=_(E);return r.emit("error",{type:"error",error:y}),c(y)}let h=await a(l.value,p);return h.ok?f(h.value):(r.emit("error",{type:"error",error:h.error}),c(h.error))}catch(l){let d=_(l);return r.emit("error",{type:"error",error:d}),c(d)}}function W(e,t){try{Ne(e.challenge,"challenge"),Ne(e.user.id,"user.id");let r=J(e.challenge),n=J(e.user.id),o={userVerification:"preferred"};e.authenticatorSelection&&(o={...e.authenticatorSelection}),t&&(o={...o,authenticatorAttachment:t});let i={rp:{id:e.rp.id,name:e.rp.name},user:{id:n,name:e.user.name,displayName:e.user.displayName},challenge:r,pubKeyCredParams:e.pubKeyCredParams,...e.timeout!==void 0&&{timeout:e.timeout},attestation:"none",authenticatorSelection:o,...e.excludeCredentials&&{excludeCredentials:e.excludeCredentials.map(a=>({id:J(a.id),type:a.type,...a.transports&&{transports:a.transports}}))}};return f({publicKey:i})}catch(r){return c(_(r))}}function tr(e,t){try{Ne(e.challenge,"challenge");let r=J(e.challenge);return f({publicKey:{challenge:r,rpId:e.rpId,...e.timeout!==void 0&&{timeout:e.timeout},userVerification:e.userVerification??"preferred",...e.allowCredentials&&{allowCredentials:e.allowCredentials.map(n=>({id:J(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...t!==void 0&&{mediation:t}})}catch(r){return c(_(r))}}async function tn(e,t,r){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let i=A("externalUserId","must be a non-empty string");return r.emit("error",{type:"error",error:i}),c(i)}let o=await ye({operation:"register",eventEmitter:r,start:()=>t.startRegister({external_user_id:n}),createOptions:i=>W(i.challenge,e.authenticatorType),invoke:async i=>{let a={...i,...e.signal&&{signal:e.signal}};return navigator.credentials.create(a)},finish:async(i,a)=>{let l=await t.finishRegister({session_id:i.session_id,credential:U(a),...e.successUrl&&{success_url:e.successUrl}});return l.ok?f({success:!0,credentialId:l.value.credential_id,credential_id:l.value.credential_id,status:l.value.status,sessionToken:l.value.session_token,user:{userId:l.value.user.user_id,externalUserId:l.value.user.external_user_id,email:l.value.user.email,metadata:l.value.user.metadata},...l.value.redirect_url&&{redirectUrl:l.value.redirect_url}}):c(l.error)}});return o.ok&&r.emit("success",{type:"success",operation:"register",token:o.value.sessionToken,user:o.value.user}),o}async function rn(e,t,r){let n=e.externalUserId??e.external_user_id,o=n!==void 0&&typeof n=="string"&&n.trim()!=="",i=await ye({operation:"authenticate",eventEmitter:r,start:()=>t.startAuth(o?{external_user_id:n.trim()}:{}),createOptions:a=>tr(a.challenge,e.mediation),invoke:async a=>{let l={...a,...e.signal&&{signal:e.signal}};return navigator.credentials.get(l)},finish:async(a,l)=>{let d=await t.finishAuthentication({session_id:a.session_id,credential:qe(l),...e.successUrl&&{success_url:e.successUrl}});return d.ok?f({authenticated:d.value.authenticated,sessionToken:d.value.session_token,user:{userId:d.value.user.user_id,externalUserId:d.value.user.external_user_id,email:d.value.user.email,metadata:d.value.user.metadata},signals:d.value.signals,...d.value.redirect_url&&{redirectUrl:d.value.redirect_url}}):c(d.error)}});return i.ok&&r.emit("success",{type:"success",operation:"authenticate",token:i.value.sessionToken,user:i.value.user}),i}async function Ge(e,t){return t?t.aborted?"aborted":new Promise(r=>{let n=()=>{o(),r("aborted")},o=()=>{clearTimeout(i),t.removeEventListener("abort",n)},i=setTimeout(()=>{o(),r("completed")},e);t.addEventListener("abort",n)}):(await new Promise(r=>setTimeout(r,e)),"completed")}var po=2e3,mo=60,We=class{constructor(t){this.apiClient=t}async startFlow(t,r){let n=await this.apiClient.startOnboarding({user_role:t.user_role});if(!n.ok)return c(n.error);let{session_id:o}=n.value;for(let i=0;i<mo;i++){if(r?.aborted)return c(b("ABORT_ERROR","Operation aborted by user or timeout"));if(await Ge(po,r)==="aborted")return c(b("ABORT_ERROR","Operation aborted by user or timeout"));let l=await this.apiClient.getOnboardingStatus(o);if(!l.ok)return c(l.error);let d=l.value.status,p=l.value.onboarding_url;if(d==="pending_passkey"){let h=await this.apiClient.getOnboardingRegister(o);if(!h.ok)return c(h.error);let E=h.value;if(!E.challenge)return c(b("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:p}));let y=W(E.challenge);if(!y.ok)return c(y.error);let I;try{I=await navigator.credentials.create(y.value)}catch(D){return c(_(D))}try{G(I,"create")}catch(D){return c(_(D))}let O;try{O=U(I)}catch(D){return c(_(D))}let Y=await this.apiClient.registerOnboardingPasskey(o,{credential:O,challenge:E.challenge.challenge});return Y.ok?await this.apiClient.completeOnboarding(o,{company_name:t.company_name}):c(Y.error)}if(d==="completed")return await this.apiClient.completeOnboarding(o,{company_name:t.company_name})}return c(b("TIMEOUT","Onboarding timed out"))}};var fo=2e3,ho=60,Ye=class{constructor(t){this.apiClient=t}async init(){return this.apiClient.initCrossDeviceAuth()}async initRegistration(t){return this.apiClient.initCrossDeviceRegistration(t)}async waitForSession(t,r,n){if(r?.aborted)return c(b("ABORT_ERROR","Operation aborted by user or timeout"));for(let o=0;o<ho;o++){let i=await this.apiClient.getCrossDeviceStatus(t,n);if(!i.ok)return c(i.error);if(i.value.status==="completed"){if(!i.value.session_token||!i.value.user_id)return c(b("UNKNOWN_ERROR","Missing data in completed session"));let l=i.value.redirect_url!=null&&i.value.redirect_url!==""?i.value.redirect_url:void 0;return f({session_token:i.value.session_token,user_id:i.value.user_id,...l!==void 0&&{redirectUrl:l}})}if(await Ge(fo,r)==="aborted")return c(b("ABORT_ERROR","Operation aborted by user or timeout"))}return c(b("TIMEOUT","Cross-device authentication timed out"))}async approve(t){let r=await this.apiClient.getCrossDeviceContext(t);if(!r.ok)return c(r.error);let n=r.value;return n.type==="registration"?this.executeRegistrationApproval(t,n):this.executeAuthApproval(t,n)}async executeRegistrationApproval(t,r){let n=W(r.options);if(!n.ok)return c(n.error);let o;try{o=await navigator.credentials.create(n.value)}catch(a){return c(_(a))}try{G(o,"create")}catch(a){return c(_(a))}let i;try{i=U(o)}catch(a){return c(_(a))}return this.apiClient.verifyCrossDeviceRegistration({session_id:t,credential:i})}async executeAuthApproval(t,r){let n=tr(r.options);if(!n.ok)return c(n.error);let o;try{o=await navigator.credentials.get(n.value)}catch(a){return c(_(a))}try{G(o,"get")}catch(a){return c(_(a))}let i;try{i=qe(o)}catch(a){return c(_(a))}return this.apiClient.verifyCrossDeviceAuth({session_id:t,credential:i})}};var ze=class{handlers;constructor(){this.handlers=new Map}on(t,r){let n=this.handlers.get(t);return n||(n=new Set,this.handlers.set(t,n)),n.add(r),()=>{this.off(t,r)}}off(t,r){let n=this.handlers.get(t);n&&(n.delete(r),n.size===0&&this.handlers.delete(t))}emit(t,r){let n=this.handlers.get(t);if(n)for(let o of n)try{o(r)}catch{}}removeAllListeners(){this.handlers.clear()}};var rr="https://api.trymellonauth.com",nn="https://api.trymellonauth.com/v1/telemetry";var on="trymellon_sandbox_session_token_v1";function sn(e){return{async send(t){let r=JSON.stringify(t);if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"){navigator.sendBeacon(e,r);return}typeof fetch<"u"&&await fetch(e,{method:"POST",body:r,headers:{"Content-Type":"application/json"},keepalive:!0})}}}function nr(e,t){return{event:e,latencyMs:t,ok:!0}}var Qe=class{constructor(t,r,n,o,i){this.apiClient=t;this.eventEmitter=r;this.sandbox=n;this.sandboxToken=o;this.telemetrySender=i}async sandboxAuthResult(t,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 t==="register"?Promise.resolve(f({success:!0,credentialId:"",status:"sandbox",sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:o}})):Promise.resolve(f({authenticated:!0,sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:o}}))}async register(t){if(this.sandbox){let o=await this.sandboxAuthResult("register",t);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 tn(t,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(nr("register",Date.now()-r)).catch(()=>{}),n}async authenticate(t){if(this.sandbox){let o=await this.sandboxAuthResult("authenticate",t);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 rn(t,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(nr("authenticate",Date.now()-r)).catch(()=>{}),n}};async function an(e,t,r){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let i=A("externalUserId","must be a non-empty string");return r.emit("error",{type:"error",error:i}),c(i)}if(!e.otp||typeof e.otp!="string"||e.otp.trim().length!==6){let i=A("otp","must be a 6-digit string");return r.emit("error",{type:"error",error:i}),c(i)}let o=await ye({operation:"register",eventEmitter:r,start:()=>t.verifyAccountRecoveryOtp(n,e.otp),createOptions:i=>W(i.challenge),invoke:async i=>navigator.credentials.create(i),finish:async(i,a)=>{let l=await t.completeAccountRecovery(i.recovery_session_id,U(a));if(!l.ok)return c(l.error);let{credential_id:d,status:p,session_token:h,user:E,redirect_url:y}=l.value;return f({success:!0,credentialId:d,status:p,sessionToken:h,user:{userId:E.user_id,externalUserId:E.external_user_id,email:E.email,metadata:E.metadata},...y!==void 0&&{redirectUrl:y}})}});return o.ok&&r.emit("success",{type:"success",operation:"register",token:o.value.sessionToken,user:o.value.user}),o}var $e=class{constructor(t,r){this.apiClient=t;this.eventEmitter=r}recover(t){return an(t,this.apiClient,this.eventEmitter)}};var Xe=class e{sandbox;sandboxToken;apiClient;eventEmitter;telemetrySender;crossDeviceManager;authService;recoveryService;onboarding;static create(t){try{let r=t.appId,n=t.publishableKey;if(!r||typeof r!="string"||r.trim()==="")return c(A("appId","must be a non-empty string"));if(!n||typeof n!="string"||n.trim()==="")return c(A("publishableKey","must be a non-empty string"));let o=t.apiBaseUrl??rr;Bt(o,"apiBaseUrl");let i=t.timeoutMs??3e4;return j(i,"timeoutMs",1e3,3e5),t.maxRetries!==void 0&&j(t.maxRetries,"maxRetries",0,10),t.retryDelayMs!==void 0&&j(t.retryDelayMs,"retryDelayMs",100,1e4),f(new e(t))}catch(r){return Ut(r)?c(r):c(A("config",r.message))}}constructor(t){this.sandbox=t.sandbox===!0,this.sandboxToken=this.sandbox&&t.sandboxToken!=null&&t.sandboxToken!==""?t.sandboxToken:on;let r=t.appId,n=t.publishableKey;if(!r||typeof r!="string"||r.trim()==="")throw A("appId","must be a non-empty string");if(!n||typeof n!="string"||n.trim()==="")throw A("publishableKey","must be a non-empty string");let o=t.apiBaseUrl??rr;Bt(o,"apiBaseUrl");let i=t.timeoutMs??3e4;j(i,"timeoutMs",1e3,3e5),t.maxRetries!==void 0&&j(t.maxRetries,"maxRetries",0,10),t.retryDelayMs!==void 0&&j(t.retryDelayMs,"retryDelayMs",100,1e4);let a=t.maxRetries??3,l=t.retryDelayMs??1e3,d=new He(i,a,l,t.logger),p=t.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),h={"X-App-Id":r.trim(),Authorization:`Bearer ${n.trim()}`,...p&&{Origin:p}};this.apiClient=new Ve(d,o,h),this.eventEmitter=new ze,t.enableTelemetry&&(this.telemetrySender=t.telemetrySender??sn(t.telemetryEndpoint??nn)),this.authService=new Qe(this.apiClient,this.eventEmitter,this.sandbox,this.sandboxToken,this.telemetrySender),this.recoveryService=new $e(this.apiClient,this.eventEmitter),this.onboarding=new We(this.apiClient),this.crossDeviceManager=new Ye(this.apiClient)}static isSupported(){return Z()}async register(t){return this.authService.register(t)}async authenticate(t){return this.authService.authenticate(t)}async validateSession(t){return this.sandbox&&t===this.sandboxToken?Promise.resolve(f({valid:!0,user_id:"sandbox-user",external_user_id:"sandbox",tenant_id:"sandbox-tenant",app_id:"sandbox-app"})):this.apiClient.validateSession(t)}async getStatus(){return je()}on(t,r){return this.eventEmitter.on(t,r)}version(){return"2.0.0"}fallback={email:{start:async t=>this.apiClient.startEmailFallback(t),verify:async t=>{let r=await this.apiClient.verifyEmailCode({userId:t.userId,code:t.code,...t.successUrl&&{successUrl:t.successUrl}});return r.ok?f({sessionToken:r.value.sessionToken,...r.value.redirectUrl&&{redirectUrl:r.value.redirectUrl}}):r}}};auth={crossDevice:{init:()=>this.crossDeviceManager.init(),initRegistration:t=>this.crossDeviceManager.initRegistration(t??{}),waitForSession:(t,r,n)=>this.crossDeviceManager.waitForSession(t,r,n),getContext:t=>this.apiClient.getCrossDeviceContext(t),approve:t=>this.crossDeviceManager.approve(t)},recoverAccount:t=>this.recoveryService.recover(t)}};function or(e){let t=Xe.create({appId:e.appId,publishableKey:e.publishableKey});return!t.ok||t.value==null?null:t.value}function hn(e){if(e==null||typeof e!="object")return!1;let t=e,r=typeof t.authenticate=="function",n=typeof t.register=="function",o=typeof t.on=="function";return r&&n&&o}function gn(e){return e?{externalUserId:e}:{}}var Je="mellon:open",Ae="mellon:open-request",N="mellon:close",Ze="mellon:success",et="mellon:error",tt="mellon:start",_e="mellon:cancelled",rt="mellon:fallback",nt="mellon:tab-change";function ot(e,t,r,n){e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:n.bubbles,composed:n.composed}))}function it(e){return e==="authenticate"?"login":"register"}function Eo(e){if(e==null||typeof e!="object")return;let t=e,r=t.userId;if(typeof r!="string"||r.length===0)return;let n={userId:r};return typeof t.externalUserId=="string"&&(n.externalUserId=t.externalUserId),typeof t.email=="string"&&(n.email=t.email),t.metadata!=null&&typeof t.metadata=="object"&&!Array.isArray(t.metadata)&&(n.metadata=t.metadata),n}function yo(e){return e!=null&&typeof e=="object"&&e.type==="start"&&(e.operation==="register"||e.operation==="authenticate")}function Ao(e){let t=e;return e!=null&&typeof e=="object"&&t.type==="success"&&typeof t.token=="string"&&(t.operation==="register"||t.operation==="authenticate")}function _o(e){return e!=null&&typeof e=="object"&&e.type==="error"}function Ro(e){return e!=null&&typeof e=="object"&&e.type==="cancelled"&&(e.operation==="register"||e.operation==="authenticate")}var ir={subscribe(e,t){if(e==null||t==null)throw new TypeError("eventBridgeAdapter.subscribe: core and host are required");let r=[],n="authenticate",o=!1,i=e.on("start",p=>{if(!yo(p))return;n=p.operation,o=!1;let h={operation:it(p.operation),...typeof p.nonce=="string"&&{nonce:p.nonce}};ot(t,tt,h,{bubbles:!0,composed:!0})});r.push(i);let a=e.on("success",p=>{if(!Ao(p)||o||p.token.length===0)return;o=!0;let h=Eo(p.user),E={operation:it(p.operation),token:p.token,...typeof p.nonce=="string"&&{nonce:p.nonce},...h!==void 0&&{user:h},...typeof p.redirectUrl=="string"&&{redirectUrl:p.redirectUrl}};ot(t,Ze,E,{bubbles:!1,composed:!0})});r.push(a);let l=e.on("error",p=>{if(!_o(p)||o)return;let h=p.error?.code??"UNKNOWN_ERROR",E={operation:it(p.operation??n),code:h,message:typeof p.error?.message=="string"?p.error.message:"Unknown error",...typeof p.nonce=="string"&&{nonce:p.nonce}};ot(t,et,E,{bubbles:!0,composed:!0})});r.push(l);let d=e.on("cancelled",p=>{if(!Ro(p))return;let h={operation:it(p.operation),...typeof p.nonce=="string"&&{nonce:p.nonce}};ot(t,_e,h,{bubbles:!0,composed:!0})});return r.push(d),function(){for(let h of r)h()}}};function bn(e){return{isPasskeySupported:e.isPasskeySupported,platformAuthenticatorAvailable:e.platformAuthenticatorAvailable,recommendedFlow:e.recommendedFlow}}function vo(){return{getClientStatus:async()=>{let e=await je();return bn(e)}}}function En(e){let t=e;if(typeof t.getStatus!="function")return vo();let r=t.getStatus;return{getClientStatus:async()=>{let n=await r();return bn(n)}}}function yn(e){return new CustomEvent(Je,{detail:e,bubbles:!0,composed:!0})}function An(e){return new CustomEvent(N,{detail:e,bubbles:!0,composed:!0})}function _n(e){return new CustomEvent(_e,{detail:e,bubbles:!0,composed:!0})}function Rn(e){return new CustomEvent(rt,{detail:e,bubbles:!0,composed:!0})}function vn(e){return new CustomEvent(nt,{detail:e,bubbles:!0,composed:!0})}var st=class{_currentState=T;_lastRenderedState=null;_renderDirty=!0;_pendingOperation="authenticate";_currentNonce=void 0;_envEvalRequestId=0;get currentState(){return this._currentState}setState(t){this._currentState=t,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(t){this._pendingOperation=t==="login"?"authenticate":"register"}get pendingOperation(){return this._pendingOperation}setNonce(t){this._currentNonce=t}consumeCancelledDetailIfAuthenticating(){if(this._currentState!=="AUTHENTICATING")return null;let t={operation:this._pendingOperation==="authenticate"?"login":this._pendingOperation,...this._currentNonce!==void 0&&{nonce:this._currentNonce}};return this._currentNonce=void 0,t}handleAuthSuccess(){let t=v.tryHandleAuthSuccess(this._currentState);t!==null&&this.setState(t)}handleAuthError(){let t=v.tryHandleAuthError(this._currentState);t!==null&&this.setState(t)}onStartEvent(t){t?.nonce!==void 0&&(this._currentNonce=t.nonce)}startAuthFromClick(t,r,n){if(!t||!gr(this._currentState))return;this.setPendingOperationFromTab(r);let o=v.startAuth(this._currentState,r,t,n);this.setState(o)}async runEnvEval(t){let r=++this._envEvalRequestId;this.setState(v.envEvalStart(this._currentState));let n=await v.evaluateEnv({...t,currentState:this._currentState});return r!==this._envEvalRequestId?null:n}reset(){this._currentState=v.reset(this._currentState),this._lastRenderedState=null,this._renderDirty=!0,this._currentNonce=void 0}setStateForRender(t){this._currentState=t,this._renderDirty=!0}};var ee=class extends HTMLElement{_controller=new st;_unsubscribeBridge=null;_core=null;_lastCoreConfig=null;setState(t){this._controller.setState(t),this.scheduleRenderIfNeeded()}invalidateRender(){this._controller.invalidateRender(),this.scheduleRenderIfNeeded()}scheduleRenderIfNeeded(){this.shadowRoot&&this._controller.consumeRenderDecision()&&this._render()}_emitCancelledIfAuthenticating(){let t=this._controller.consumeCancelledDetailIfAuthenticating();return t?(this.dispatchEvent(_n(t)),!0):!1}attachCore(t){if(this._core!==null&&this._teardownCore(),t==null){this._core=null,this._controller.reset(),this.scheduleRenderIfNeeded();return}if(!hn(t))throw new Error("[trymellon-auth] attachCore requires a CoreAuthPort-compatible instance.");this._core=t,this._unsubscribeBridge=ir.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.handleAuthSuccess(),this.scheduleRenderIfNeeded()};_onMellonError=()=>{this._controller.handleAuthError(),this.scheduleRenderIfNeeded()};_onMellonStart=t=>{let r=t.detail;this._controller.onStartEvent(r)};startAuthFromClick(){this._core&&this.canStartAuth()&&(this._controller.startAuthFromClick(this._core,this.getTabKind(),this.getCoreAuthOptions()),this.scheduleRenderIfNeeded())}dispatchFallback(t){let r=t!==void 0?{...this.getFallbackDetail(),fallbackType:t}:this.getFallbackDetail();this.dispatchEvent(Rn(r))}async _runEnvEval(){if(!this._core)return;let t={...this.getEnvEvalParams(),envStatusPort:En(this._core)},r=await this._controller.runEnvEval(t);r!==null&&(!this._core||!this.isConnected||this.setState(r))}_maybeAutoCreateCoreAndRunEnvEval(){if(this._core!==null)return;let t=this.getCoreConfig();if(!t)return;let r=or(t);if(!r){this.attachCore(null);return}this.attachCore(r)}_reconcileCoreFromConfig(){let t=this.getCoreConfig();if(this._lastCoreConfig===null&&t===null||this._lastCoreConfig!==null&&t!==null&&this._lastCoreConfig.appId===t.appId&&this._lastCoreConfig.publishableKey===t.publishableKey)return;if(this._lastCoreConfig=t,t===null){this.attachCore(null);return}let n=or(t);this.attachCore(n??null)}disconnectedCallback(){this._teardownCore()}get currentState(){return this._controller.currentState}reset(){this._emitCancelledIfAuthenticating(),this._controller.reset(),this.scheduleRenderIfNeeded()}setStateForRender(t){this._controller.setStateForRender(t),this.scheduleRenderIfNeeded()}};function To(e){if(e==null||e.trim()==="")return z;let t=e.split(",").map(o=>o.trim()),r=t[0]??z.register,n=t[1]??z.login;return{register:r,login:n}}function at(e){let t={open:Oe(e.getAttribute("open")),mode:C(e.getAttribute("mode"),oe,Ce),tab:C(e.getAttribute("tab"),ne,Ie),tabLabels:To(e.getAttribute("tab-labels")),theme:C(e.getAttribute("theme"),B,K),sessionId:M(e.getAttribute("session-id")),onboardingUrl:M(e.getAttribute("onboarding-url")),isMobileOverride:br(e.getAttribute("is-mobile-override")),fallbackType:Er(e.getAttribute("fallback-type"),ie),appId:V(e.getAttribute("app-id")),publishableKey:V(e.getAttribute("publishable-key")),appName:M(e.getAttribute("app-name")),dialogTitle:M(e.getAttribute("dialog-title")),dialogDescription:M(e.getAttribute("dialog-description")),externalUserId:M(e.getAttribute("external-user-id")),modalVariant:C(e.getAttribute("modal-variant"),le,xe)};return yt(t)}function So(e){let t=e.querySelector(`.${St}`);return t||(t=document.createElement("div"),t.className=St,e.appendChild(t)),t}function Co(e){let t=e.querySelector(`.${fe}`);return t||(t=document.createElement("div"),t.className=fe,t.setAttribute("aria-hidden","true"),e.appendChild(t)),t}function Io(e){let t=e.querySelector(`.${Ct}`);return t||(t=document.createElement("div"),t.className=Ct,e.appendChild(t)),t}function Mo(e,t){e.setAttribute("role","dialog"),e.setAttribute("aria-modal",t==="modal"?"true":"false"),e.setAttribute("aria-labelledby",Pe),e.setAttribute("aria-describedby",ge)}function Lo(e,t){let r=e.querySelector(`#${Pe}`);r||(r=document.createElement("h2"),r.id=Pe,r.className="mellon-dialog-title",e.insertBefore(r,e.firstChild));let n=t.dialogTitle?.trim()??(t.appName?.trim()?Ar(t.appName.trim()):yr);r.textContent=n;let o=e.querySelector(`#${ge}`);o||(o=document.createElement("p"),o.id=ge,o.className="mellon-dialog-desc",e.insertBefore(o,r.nextSibling)),o.textContent=t.dialogDescription?.trim()??_r}function xo(e){let t=e.querySelector(`.${xt}`);t||(t=document.createElement("button"),t.type="button",t.className=xt,t.setAttribute("aria-label",vr),t.setAttribute("data-mellon-modal-close","true"),t.textContent="\xD7",e.appendChild(t))}function Oo(e,t){let r=e.querySelector(`.${he}`);if(!r){r=document.createElement("div"),r.className=he,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 l=e.querySelector(`#${ge}`);e.insertBefore(r,l?l.nextSibling:e.firstChild)}let[n,o]=r.querySelectorAll("button");return n&&(n.textContent=t.register),o&&(o.textContent=t.login),r}function sr(e){let t=e.querySelector(`.${It}`);if(!t){t=document.createElement("div"),t.className=It;let r=e.querySelector(`.${he}`);e.insertBefore(t,r?r.nextSibling:e.firstChild)}return t}function Do(){let e=document.createElementNS(w,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("class","mellon-qr-icon"),e.setAttribute("fill","currentColor");let t=document.createElementNS(w,"path");return t.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"),e.appendChild(t),e}function Tn(){let e=document.createDocumentFragment(),t=document.createElement("div");t.className=Sr;let r=document.createElement("p");r.className="mellon-cross-device-cta-text",r.textContent=Tr,t.appendChild(r);let n=document.createElement("button");return n.type="button",n.className="mellon-btn mellon-btn-qr-icon",n.setAttribute("data-mellon-action",Q),n.setAttribute("aria-label",Cr),n.appendChild(Do()),t.appendChild(n),e.appendChild(t),e}function ko(){let e=document.createElement("div");e.className=Ir,e.setAttribute("aria-live","polite");let t=document.createElement("span");t.textContent=xr;let r=document.createElement("span");return r.className="mellon-qr-dots",r.setAttribute("aria-hidden","true"),e.appendChild(t),e.appendChild(r),e}function wo(){let e=document.createElement("div");return e.className=Mr,e.setAttribute("aria-live","polite"),e.textContent=Or,e}function Po(e){let t=sr(e),r=t.querySelector(`.${L}`);if(!r){r=document.createElement("div"),r.className=L,r.setAttribute("data-qr-area-state","default"),r.appendChild(ko()),r.appendChild(wo());let o=document.createElement("div");o.className=Lr;let i=document.createElement("slot");i.name=q,i.appendChild(Tn()),o.appendChild(i),r.appendChild(o),t.appendChild(r)}let n=r.querySelector(`slot[name="${q}"]`);if(!n){let o=document.createElement("slot");return o.name=q,o.appendChild(Tn()),r.appendChild(o),o}return n}function Uo(e){let t=sr(e);if(t.querySelector(`.${Lt}`))return;let r=document.createElement("div");r.className=Lt,r.setAttribute("aria-hidden","true");let n=document.createElement("span");n.className="mellon-separator-text",n.textContent=Rr,r.appendChild(n);let o=t.querySelector(`.${L}`);t.insertBefore(r,o?o.nextSibling:t.firstChild)}function No(e){let t=sr(e),r=t.querySelector("slot:not([name])");if(!r){r=document.createElement("slot");let o=document.createElement("div");o.id=H,o.className="mellon-root",r.appendChild(o),t.appendChild(r)}let n=e.querySelector(`#${H}`);return n||(n=document.createElement("div"),n.id=H,n.className="mellon-root",r.appendChild(n)),n}function Bo(e){let t=e.querySelector(`slot[name="${Mt}"]`);return t||(t=document.createElement("slot"),t.name=Mt,e.appendChild(t)),t}function Fo(e,t){let r=e.querySelector(`.${he}`);if(!r)return;let n=r.querySelector('[data-tab="register"]'),o=r.querySelector('[data-tab="login"]');n&&n.setAttribute("aria-selected",String(t==="register")),o&&o.setAttribute("aria-selected",String(t==="login"))}function Re(e,t){if(e==null||t==null)return;let r=So(e);r.setAttribute("data-mellon-modal-variant",t.modalVariant),t.mode==="modal"&&Co(r);let n=Io(r);Mo(n,t.mode),Lo(n,t),xo(n),Oo(n,t.tabLabels),Po(n),Uo(n),No(n),Bo(n),Fo(n,t.tab)}function Ko(e){return!(e.hidden===!0||e.getAttribute("aria-hidden")==="true")}function Sn(e){return Array.from(e.querySelectorAll(Ur)).filter(r=>Ko(r))}function Cn(e){let t=null,r=null,n=!1;function o(l){if(l.key!=="Tab")return;let d=Sn(e);if(d.length===0)return;let p=l.target instanceof Node?l.target:null,h=p?d.indexOf(p):-1,E=d.length-1,y;l.shiftKey?y=h<=0?E:h-1:y=h>=E?0:h+1;let I=d[y];I&&(l.preventDefault(),I.focus())}function i(){if(n)return;t=document.activeElement;let d=Sn(e)[0];d&&d.focus(),r=o,e.addEventListener("keydown",r,!0),n=!0}function a(){if(!n)return;r&&(e.removeEventListener("keydown",r,!0),r=null),n=!1;let l=e.getRootNode()?.ownerDocument??document,d=t instanceof HTMLElement&&l.body.contains(t)?t:null;if(d)d.focus();else{let p=l.body,h=p.getAttribute("tabindex");p.setAttribute("tabindex","-1"),p.focus(),h===null?p.removeAttribute("tabindex"):p.setAttribute("tabindex",h)}t=null}return{activate:i,deactivate:a}}var Vo="mellon-modal-wrapper",Ho="mellon-modal-overlay",qo="mellon-modal-panel",In=["app-id","publishable-key","mode","external-user-id","theme","action","trigger-only","button-variant"],Mn=["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"],lt={wrapper:`.${Vo}`,overlay:`.${Ho}`,panel:`.${qo}`},Ln="user";var jo={SUCCESS:{reason:"success"},AUTHENTICATING:{reason:"cancel"},ERROR:{reason:"error"}};function Go(e){return jo[e]??{reason:Ln}}var ut=class extends ee{static get observedAttributes(){return[...Mn]}_parsed=at(this);_focusTrap=null;_unregisterInteractions=null;_generatedExternalUserId=null;_qrLoadTimeoutId=null;_qrSlotChangeBound=null;_boundEscapeKeydown=t=>{t.key==="Escape"&&this._parsed.open&&(t.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 t=this.attachShadow({mode:"open"}),r=jr();if(r)t.adoptedStyleSheets=[r];else{let n=document.createElement("style");n.textContent=qr(),t.appendChild(n)}this._parsed=at(this),Re(t,this._parsed),this._registerInteractions(),this._render(),this._applyModalVisibility(),this._maybeAutoCreateCoreAndRunEnvEval()}_registerInteractions(){this.shadowRoot&&(this._unregisterInteractions?.(),this._unregisterInteractions=Kr(this.shadowRoot,{onTabChange:t=>{this.dispatchEvent(vn({tab:t})),this.setAttribute("tab",t)},onPrimaryClick:()=>this.startAuthFromClick(),onFallbackClick:t=>this.dispatchFallback(t),onOverlayClick:()=>{this.open=!1},onCloseClick:()=>{this.open=!1}}))}attributeChangedCallback(t,r,n){if(this.shadowRoot){if(this._parsed=at(this),t==="open"){if(this._parsed.open&&r!=="true"){let o={timestamp:Date.now()};this.dispatchEvent(yn(o)),this._startQrLoadWait()}if(!this._parsed.open){this._clearQrLoadWait(),this._transitionToIdle();return}}t==="tab"&&(this._emitCancelledIfAuthenticating(),this.setState(v.tabChange(this.currentState,this._parsed.tab))),(t==="app-id"||t==="publishable-key")&&this._reconcileCoreFromConfig(),Re(this.shadowRoot,this._parsed),this._render(),this._applyModalVisibility()}}_startQrLoadWait(){let t=this.shadowRoot;if(!t)return;let r=t.querySelector(`.${L}`),n=t.querySelector(`slot[name="${q}"]`);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(`.${L}`);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(`.${L}`);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 t=this.shadowRoot;if(!t)return;let r=t.querySelector(`slot[name="${q}"]`);r&&this._qrSlotChangeBound&&(r.removeEventListener("slotchange",this._qrSlotChangeBound),this._qrSlotChangeBound=null);let n=t.querySelector(`.${L}`);n&&n.setAttribute("data-qr-area-state","default")}_transitionToIdle(){this._generatedExternalUserId=null;let r={reason:Go(this.currentState).reason,timestamp:Date.now()};this.dispatchEvent(An(r)),this._emitCancelledIfAuthenticating(),this.setState(v.reset(this.currentState)),this.shadowRoot&&(Re(this.shadowRoot,this._parsed),this.scheduleRenderIfNeeded(),this._applyModalVisibility())}get open(){return this._parsed.open}set open(t){this.setAttribute("open",t?"true":"false")}get mode(){return this._parsed.mode}set mode(t){this.setAttribute("mode",t)}get tab(){return this._parsed.tab}set tab(t){this.setAttribute("tab",t)}get tabLabels(){return`${this._parsed.tabLabels.register},${this._parsed.tabLabels.login}`}set tabLabels(t){t==null||t===""?this.removeAttribute("tab-labels"):this.setAttribute("tab-labels",t)}get theme(){return this._parsed.theme}set theme(t){this.setAttribute("theme",t)}get sessionId(){return this._parsed.sessionId}set sessionId(t){t==null?this.removeAttribute("session-id"):this.setAttribute("session-id",t)}get onboardingUrl(){return this._parsed.onboardingUrl}set onboardingUrl(t){t==null?this.removeAttribute("onboarding-url"):this.setAttribute("onboarding-url",t)}get isMobileOverride(){return this._parsed.isMobileOverride}set isMobileOverride(t){t==null?this.removeAttribute("is-mobile-override"):this.setAttribute("is-mobile-override",t?"true":"false")}get fallbackType(){return this._parsed.fallbackType}set fallbackType(t){t==null?this.removeAttribute("fallback-type"):this.setAttribute("fallback-type",t)}get appId(){return this._parsed.appId}set appId(t){this.setAttribute("app-id",t??"")}get publishableKey(){return this._parsed.publishableKey}set publishableKey(t){this.setAttribute("publishable-key",t??"")}get appName(){return this._parsed.appName}set appName(t){t==null?this.removeAttribute("app-name"):this.setAttribute("app-name",t)}get dialogTitle(){return this._parsed.dialogTitle}set dialogTitle(t){t==null?this.removeAttribute("dialog-title"):this.setAttribute("dialog-title",t)}get dialogDescription(){return this._parsed.dialogDescription}set dialogDescription(t){t==null?this.removeAttribute("dialog-description"):this.setAttribute("dialog-description",t)}get externalUserId(){return this._parsed.externalUserId}set externalUserId(t){t==null?this.removeAttribute("external-user-id"):this.setAttribute("external-user-id",t)}disconnectedCallback(){this._unregisterInteractions?.(),this._unregisterInteractions=null,this.removeEventListener("keydown",this._boundEscapeKeydown,!0),super.disconnectedCallback()}reset(){this._transitionToIdle()}getTabKind(){return this._parsed.tab}getCoreAuthOptions(){let t=this._resolveExternalUserId();return t?{externalUserId:t}:{}}_resolveExternalUserId(){let t=this._parsed.externalUserId?.trim();return t||(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 t=this.shadowRoot.querySelector(lt.wrapper);t&&(t.hidden=!this._parsed.open);let r=this.shadowRoot.querySelector(lt.overlay);r&&(r.hidden=this._parsed.mode!=="modal");let n=this.shadowRoot.querySelector(lt.panel);n&&n.setAttribute("aria-hidden",String(!this._parsed.open)),this._parsed.open&&t?(this._focusTrap||(this._focusTrap=Cn(t)),this._focusTrap.activate()):this._focusTrap?.deactivate()}_render(){if(!this.shadowRoot)return;Re(this.shadowRoot,this._parsed),this._applyModalVisibility();let t=_t(this.currentState,this._parsed,{registerSessionReady:this._parsed.tab==="register"?this.canStartAuth():void 0,primaryButtonLabel:vt,primaryButtonAriaLabel:Tt}),r={shadowRoot:this.shadowRoot};wr(r,t)}};var dt=class extends ee{static get observedAttributes(){return[...In]}_parsed={...ce};_internalModal=null;_focusRestoreTarget=null;_unregisterInteractions=null;_onInternalModalClose=()=>{this._internalModal&&(this._internalModal.open=!1),this._restoreFocusToTrigger()};_restoreFocusToTrigger(){let t=this._focusRestoreTarget;this._focusRestoreTarget=null,!(!t?.isConnected||typeof t.focus!="function")&&t.focus()}connectedCallback(){if(this.shadowRoot){this._registerInteractions(),this._core!==null&&this._unsubscribeBridge===null&&this.attachCore(this._core),this._syncInternalModalAttributes(),this._ensureInternalModal();return}let t=this.attachShadow({mode:"open"}),r=wt();if(r)t.adoptedStyleSheets=[r];else{let n=document.createElement("style");n.textContent=Pt(),t.appendChild(n)}this._parsed=Rt(this),this._syncThemeAttribute(),this._registerInteractions(),this._render(),this._reconcileCoreFromConfig(),this._ensureInternalModal()}_registerInteractions(){this.shadowRoot&&(this._unregisterInteractions?.(),this._unregisterInteractions=Fr(this.shadowRoot,{onPrimaryClick:()=>this._onPrimaryClick(),onFallbackClick:t=>this.dispatchFallback(t)}))}attributeChangedCallback(t,r,n){if(!this.shadowRoot)return;let o=this._parsed.mode;if(this._parsed=Rt(this),(t==="button-variant"||t==="theme")&&this.invalidateRender(),(t==="app-id"||t==="publishable-key")&&this._reconcileCoreFromConfig(),t==="mode"&&(this._parsed.mode==="register"||this._parsed.mode==="login")){let i=this._parsed.mode;o!==i&&(this._emitCancelledIfAuthenticating(),this.setState(v.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(Ae,{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 gn(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 t=this._parsed.mode==="login"||this._parsed.mode==="register"?this._parsed.mode:void 0;return t!==void 0?{operation:t}:{}}_render(){if(!this.shadowRoot)return;let t=At(this.currentState,this._parsed,{registerSessionReady:this._parsed.mode==="register"?this.canStartAuth():void 0}),r={shadowRoot:this.shadowRoot};kr(r,t)}_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 t=this._parsed.mode==="auto"?"login":this._parsed.mode;this._internalModal.setAttribute("tab",t)}_ensureInternalModal(){if(this._parsed.action!=="open-modal"||!this.shadowRoot)return;if(this._parsed.triggerOnly){this._internalModal?.isConnected&&(this._internalModal.removeEventListener(N,this._onInternalModalClose),this._internalModal.remove(),this._internalModal=null);return}if(this._internalModal?.isConnected){this._syncInternalModalAttributes();return}let t=document.createElement("trymellon-auth-modal");this._internalModal=t,this._syncInternalModalAttributes(),t.addEventListener(N,this._onInternalModalClose),typeof document<"u"&&document.body?document.body.appendChild(t):this.shadowRoot.appendChild(t)}disconnectedCallback(){this._unregisterInteractions?.(),this._unregisterInteractions=null,this._internalModal?.isConnected&&(this._internalModal.removeEventListener(N,this._onInternalModalClose),this._internalModal.remove(),this._internalModal=null),super.disconnectedCallback()}};var Kl="0.1.0",On="trymellon-auth",Dn="trymellon-auth-modal";typeof customElements<"u"&&!customElements.get(On)&&customElements.define(On,dt);typeof customElements<"u"&&!customElements.get(Dn)&&customElements.define(Dn,ut);export{be as BASE_STYLES,T as INITIAL_UI_STATE,_e as MELLON_CANCELLED,N as MELLON_CLOSE,et as MELLON_ERROR,rt as MELLON_FALLBACK,Je as MELLON_OPEN,Ae as MELLON_OPEN_REQUEST,tt as MELLON_START,Ze as MELLON_SUCCESS,nt as MELLON_TAB_CHANGE,Dn as TRYMELLON_AUTH_MODAL_TAG,On as TRYMELLON_AUTH_TAG,dt as TryMellonAuthElement,ut as TryMellonAuthModalElement,Kl as UI_VERSION,wt as createConstructableStylesheet,ir as eventBridgeAdapter,te as getNextState,Pt as getStylesFallback};
489
+ //# sourceMappingURL=index.js.map