@trymellon/js 1.6.1 → 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/angular.cjs CHANGED
@@ -1,3 +1,3 @@
1
1
  "use client";
2
- "use strict";var ir=Object.create;var w=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var or=Object.getOwnPropertyNames;var ar=Object.prototype.hasOwnProperty;var Me=(e,r)=>(r=Symbol[e])?r:Symbol.for("Symbol."+e),V=e=>{throw TypeError(e)};var lr=(e,r,t)=>r in e?w(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var Se=(e,r)=>w(e,"name",{value:r,configurable:!0});var ur=(e,r)=>{for(var t in r)w(e,t,{get:r[t],enumerable:!0})},pr=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of or(r))!ar.call(e,s)&&s!==t&&w(e,s,{get:()=>r[s],enumerable:!(n=ke(r,s))||n.enumerable});return e};var cr=e=>pr(w({},"__esModule",{value:!0}),e);var De=e=>[,,,ir(e?.[Me("metadata")]??null)],we=["class","method","getter","setter","accessor","field","value","get","set"],q=e=>e!==void 0&&typeof e!="function"?V("Function expected"):e,dr=(e,r,t,n,s)=>({kind:we[e],name:r,metadata:n,addInitializer:i=>t._?V("Already initialized"):s.push(q(i||null))}),mr=(e,r)=>lr(r,Me("metadata"),e[3]),Ne=(e,r,t,n)=>{for(var s=0,i=e[r>>1],a=i&&i.length;s<a;s++)r&1?i[s].call(t):n=i[s].call(t,n);return n},Ue=(e,r,t,n,s,i)=>{var a,c,R,v,y,m=r&7,A=!!(r&8),E=!!(r&16),x=m>3?e.length+1:m?A?1:2:0,I=we[m+5],K=m>3&&(e[x-1]=[]),Oe=e[x]||(e[x]=[]),_=m&&(!E&&!A&&(s=s.prototype),m<5&&(m>3||!E)&&ke(m<4?s:{get[t](){return xe(this,i)},set[t](T){return Pe(this,i,T)}},t));m?E&&m<4&&Se(i,(m>2?"set ":m>1?"get ":"")+t):Se(s,t);for(var j=n.length-1;j>=0;j--)v=dr(m,t,R={},e[3],Oe),m&&(v.static=A,v.private=E,y=v.access={has:E?T=>gr(s,T):T=>t in T},m^3&&(y.get=E?T=>(m^1?xe:Rr)(T,s,m^4?i:_.get):T=>T[t]),m>2&&(y.set=E?(T,te)=>Pe(T,s,te,m^4?i:_.set):(T,te)=>T[t]=te)),c=(0,n[j])(m?m<4?E?i:_[I]:m>4?void 0:{get:_.get,set:_.set}:s,v),R._=1,m^4||c===void 0?q(c)&&(m>4?K.unshift(c):m?E?i=c:_[I]=c:s=c):typeof c!="object"||c===null?V("Object expected"):(q(a=c.get)&&(_.get=a),q(a=c.set)&&(_.set=a),q(a=c.init)&&K.unshift(a));return m||mr(e,s),_&&w(s,t,_),E?m^4?i:_:s};var ne=(e,r,t)=>r.has(e)||V("Cannot "+t),gr=(e,r)=>Object(r)!==r?V('Cannot use the "in" operator on this value'):e.has(r),xe=(e,r,t)=>(ne(e,r,"read from private field"),t?t.call(e):r.get(e));var Pe=(e,r,t,n)=>(ne(e,r,"write to private field"),n?n.call(e,t):r.set(e,t),t),Rr=(e,r,t)=>(ne(e,r,"access private method"),t);var Nr={};ur(Nr,{TRYMELLON_CONFIG:()=>B,TryMellonService:()=>D,provideTryMellonConfig:()=>wr});module.exports=cr(Nr);var L=require("@angular/core");var d=e=>({ok:!0,value:e}),l=e=>({ok:!1,error:e});var H=class e extends Error{code;details;isTryMellonError=!0;constructor(r,t,n){super(t),this.name="TryMellonError",this.code=r,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},yr={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 f(e,r,t){return new H(e,r??yr[e],t)}function se(e){return e instanceof H||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===!0}function Fe(){return f("NOT_SUPPORTED")}function h(e,r){return f("INVALID_ARGUMENT",`Invalid argument: ${e} - ${r}`,{field:e,reason:r})}function Le(e){return f("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function ie(e){return f("NOT_SUPPORTED",`No base64 ${e==="encode"?"encoding":"decoding"} available`,{type:e})}function oe(e,r){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw h(r,"must use http or https protocol")}catch(t){throw se(t)?t:h(r,"must be a valid URL")}}function P(e,r,t,n){if(!Number.isFinite(e))throw h(r,"must be a finite number");if(e<t||e>n)throw h(r,`must be between ${t} and ${n}`)}function Y(e,r){if(typeof e!="string"||e.length===0)throw h(r,"must be a non-empty string");if(!/^[A-Za-z0-9_-]+$/.test(e))throw h(r,"must be a valid base64url string")}var fr={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function b(e){if(e instanceof DOMException){let r=e.name,t=e.message||"WebAuthn operation failed",n=fr[r]??"UNKNOWN_ERROR";return f(n,t,{originalError:e})}return e instanceof Error?f("UNKNOWN_ERROR",e.message,{originalError:e}):f("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 O(e){return typeof e=="number"&&Number.isFinite(e)}function G(e){return typeof e=="boolean"}function N(e){return Array.isArray(e)}function o(e,r){return l(f("UNKNOWN_ERROR",e,{...r,originalData:r?.originalData}))}function p(e,r){return e[r]}function Ke(e,r){return!g(e)||!u(e.name)||!u(e.id)?o("Invalid API response: challenge.rp must have name and id strings",{originalData:r}):d(!0)}function je(e,r){return!g(e)||!u(e.id)||!u(e.name)||!u(e.displayName)?o("Invalid API response: challenge.user must have id, name, displayName strings",{originalData:r}):d(!0)}function qe(e,r){if(!N(e))return o("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:r});for(let t of e)if(!g(t)||t.type!=="public-key"||!O(t.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:r});return d(!0)}function ae(e,r){if(!g(e))return o("Invalid API response: user must be object",{field:"user",originalData:r});let t=p(e,"user_id"),n=p(e,"external_user_id");if(!u(t)||!u(n))return o("Invalid API response: user must have user_id and external_user_id strings",{originalData:r});let s=e.email,i=e.metadata;return s!==void 0&&!u(s)?o("Invalid API response: user.email must be string",{originalData:r}):i!==void 0&&(typeof i!="object"||i===null)?o("Invalid API response: user.metadata must be object",{originalData:r}):d({user_id:t,external_user_id:n,...s!==void 0&&{email:s},...i!==void 0&&{metadata:i}})}function le(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!u(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!g(t))return o("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=Ke(p(t,"rp"),e);if(!n.ok)return n;let s=je(p(t,"user"),e);if(!s.ok)return s;let i=p(t,"challenge");if(!u(i))return o("Invalid API response: challenge.challenge must be string",{originalData:e});let a=qe(p(t,"pubKeyCredParams"),e);if(!a.ok)return a;let c=t.timeout;if(c!==void 0&&!O(c))return o("Invalid API response: challenge.timeout must be number",{originalData:e});let R=t.excludeCredentials;if(R!==void 0){if(!N(R))return o("Invalid API response: excludeCredentials must be array",{originalData:e});for(let y of R)if(!g(y)||y.type!=="public-key"||!u(y.id))return o("Invalid API response: excludeCredentials items must have id and type",{originalData:e})}let v=t.authenticatorSelection;return v!==void 0&&!g(v)?o("Invalid API response: authenticatorSelection must be object",{originalData:e}):d({session_id:r,challenge:{rp:t.rp,user:t.user,challenge:i,pubKeyCredParams:t.pubKeyCredParams,...c!==void 0&&{timeout:c},...R!==void 0&&{excludeCredentials:R},...v!==void 0&&{authenticatorSelection:v}}})}function ue(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!u(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!g(t))return o("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=p(t,"challenge"),s=p(t,"rpId"),i=t.allowCredentials;if(!u(n))return o("Invalid API response: challenge.challenge must be string",{originalData:e});if(!u(s))return o("Invalid API response: challenge.rpId must be string",{originalData:e});if(i!==void 0&&!N(i))return o("Invalid API response: allowCredentials must be array",{originalData:e});if(i){for(let R of i)if(!g(R)||R.type!=="public-key"||!u(R.id))return o("Invalid API response: allowCredentials items must have id and type",{originalData:e})}let a=t.timeout;if(a!==void 0&&!O(a))return o("Invalid API response: challenge.timeout must be number",{originalData:e});let c=t.userVerification;return c!==void 0&&!["required","preferred","discouraged"].includes(String(c))?o("Invalid API response: userVerification must be required|preferred|discouraged",{originalData:e}):d({session_id:r,challenge:{challenge:n,rpId:s,allowCredentials:i??[],...a!==void 0&&{timeout:a},...c!==void 0&&{userVerification:c}}})}function pe(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"credential_id"),t=p(e,"status"),n=p(e,"session_token"),s=p(e,"user");if(!u(r))return o("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!u(t))return o("Invalid API response: status must be string",{field:"status",originalData:e});if(!u(n))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=ae(s,e);return i.ok?d({credential_id:r,status:t,session_token:n,user:i.value}):o(i.error.message,{originalData:e})}function ce(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"authenticated"),t=p(e,"session_token"),n=p(e,"user"),s=p(e,"signals");if(!G(r))return o("Invalid API response: authenticated must be boolean",{field:"authenticated",originalData:e});if(!u(t))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=ae(n,e);return i.ok?s!==void 0&&!g(s)?o("Invalid API response: signals must be object",{originalData:e}):d({authenticated:r,session_token:t,user:i.value,signals:s}):o(i.error.message,{originalData:e})}function de(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"valid"),t=p(e,"user_id"),n=p(e,"external_user_id"),s=p(e,"tenant_id"),i=p(e,"app_id");return G(r)?u(t)?u(n)?u(s)?u(i)?d({valid:r,user_id:t,external_user_id:n,tenant_id:s,app_id:i}):o("Invalid API response: app_id must be string",{field:"app_id",originalData:e}):o("Invalid API response: tenant_id must be string",{field:"tenant_id",originalData:e}):o("Invalid API response: external_user_id must be string",{field:"external_user_id",originalData:e}):o("Invalid API response: user_id must be string",{field:"user_id",originalData:e}):o("Invalid API response: valid must be boolean",{field:"valid",originalData:e})}function me(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"sessionToken");return u(r)?d({sessionToken:r}):o("Invalid API response: sessionToken must be string",{field:"sessionToken",originalData:e})}var vr=["pending_passkey","pending_data","completed"],hr=["pending_data","completed"];function ge(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return u(r)?u(t)?O(n)?d({session_id:r,onboarding_url:t,expires_in:n}):o("Invalid API response: expires_in must be number",{field:"expires_in",originalData:e}):o("Invalid API response: onboarding_url must be string",{field:"onboarding_url",originalData:e}):o("Invalid API response: session_id must be string",{field:"session_id",originalData:e})}function Re(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"status"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return!u(r)||!vr.includes(r)?o("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):u(t)?O(n)?d({status:r,onboarding_url:t,expires_in:n}):o("Invalid API response: expires_in must be number",{originalData:e}):o("Invalid API response: onboarding_url must be string",{originalData:e})}function ye(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"onboarding_url");if(!u(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});if(t!=="pending_passkey")return o("Invalid API response: status must be pending_passkey",{field:"status",originalData:e});if(!u(n))return o("Invalid API response: onboarding_url must be string",{originalData:e});let s=e.challenge,i;if(s!==void 0){let a=Er(s);if(!a.ok)return a;i=a.value}return d({session_id:r,status:"pending_passkey",onboarding_url:n,...i!==void 0&&{challenge:i}})}function Er(e){if(!g(e))return o("Invalid API response: challenge must be object",{originalData:e});let r=p(e,"rp"),t=p(e,"user"),n=p(e,"challenge"),s=p(e,"pubKeyCredParams");if(!g(r)||!u(r.name)||!u(r.id))return o("Invalid API response: challenge.rp must have name and id",{originalData:e});if(!g(t)||!u(t.id)||!u(t.name)||!u(t.displayName))return o("Invalid API response: challenge.user must have id, name, displayName",{originalData:e});if(!u(n))return o("Invalid API response: challenge.challenge must be string",{originalData:e});if(!N(s))return o("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let i of s)if(!g(i)||i.type!=="public-key"||!O(i.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});return d({rp:r,user:t,challenge:n,pubKeyCredParams:s})}function fe(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"user_id"),s=p(e,"tenant_id");return u(r)?!u(t)||!hr.includes(t)?o("Invalid API response: status must be pending_data|completed",{originalData:e}):u(n)?u(s)?d({session_id:r,status:t,user_id:n,tenant_id:s}):o("Invalid API response: tenant_id must be string",{originalData:e}):o("Invalid API response: user_id must be string",{originalData:e}):o("Invalid API response: session_id must be string",{originalData:e})}function ve(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"user_id"),s=p(e,"tenant_id"),i=p(e,"session_token");return u(r)?t!=="completed"?o("Invalid API response: status must be completed",{originalData:e}):!u(n)||!u(s)||!u(i)?o("Invalid API response: user_id, tenant_id, session_token must be strings",{originalData:e}):d({session_id:r,status:"completed",user_id:n,tenant_id:s,session_token:i}):o("Invalid API response: session_id must be string",{originalData:e})}function br(e){if(!e||typeof e!="object")return!1;let r=e;return typeof r.challenge=="string"&&r.rp!=null&&typeof r.rp=="object"&&r.user!=null&&typeof r.user=="object"&&Array.isArray(r.pubKeyCredParams)}function _r(e){if(!e||typeof e!="object")return!1;let r=e;return typeof r.challenge=="string"&&typeof r.rpId=="string"}function $(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=e.session_id,t=e.qr_url,n=e.expires_at;return!u(r)||!u(t)||!u(n)?o("Invalid API response: missing required fields",{originalData:e}):d({session_id:r,qr_url:t,expires_at:n})}function he(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=e.status;return!u(r)||!["pending","authenticated","completed"].includes(r)?o("Invalid API response: invalid status",{originalData:e}):d({status:r,user_id:e.user_id,session_token:e.session_token})}function Ee(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=e.type,t=r==="registration"?"registration":"auth",n=e.options;return g(n)?t==="registration"?br(n)?d({type:"registration",options:n}):o("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):_r(n)?d({type:"auth",options:n}):o("Invalid API response: auth options must have challenge and rpId",{originalData:e}):o("Invalid API response: options are required",{originalData:e})}function be(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"challenge"),t=p(e,"recovery_session_id");return g(r)?u(t)?d({challenge:r,recovery_session_id:t}):o("Invalid API response: recovery_session_id must be string",{field:"recovery_session_id",originalData:e}):o("Invalid API response: challenge must be object",{field:"challenge",originalData:e})}function _e(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"status"),t=p(e,"session_token"),n=p(e,"user"),s=p(e,"credential_id");if(!u(r))return o("Invalid API response: status must be string",{field:"status",originalData:e});if(!u(t))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!u(s))return o("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!g(n))return o("Invalid API response: user must be object",{field:"user",originalData:e});let i=p(n,"user_id");if(!u(i))return o("Invalid API response: user.user_id must be string",{field:"user.user_id",originalData:e});let a=n;return d({status:r,session_token:t,credential_id:s,user:{user_id:i,external_user_id:u(a.external_user_id)?a.external_user_id:void 0,email:u(a.email)?a.email:void 0,metadata:g(a.metadata)?a.metadata:void 0}})}var X=class{constructor(r,t,n={}){this.httpClient=r;this.baseUrl=t;this.defaultHeaders=n}mergeHeaders(r){return{...this.defaultHeaders,...r}}async post(r,t,n){let s=`${this.baseUrl}${r}`,i=await this.httpClient.post(s,t,this.mergeHeaders());return i.ok?n(i.value):l(i.error)}async get(r,t,n){let s=`${this.baseUrl}${r}`,i=await this.httpClient.get(s,this.mergeHeaders(n));return i.ok?t(i.value):l(i.error)}async startRegister(r){return this.post("/v1/passkeys/register/start",r,le)}async startAuth(r){return this.post("/v1/passkeys/auth/start",r,ue)}async finishRegister(r){return this.post("/v1/passkeys/register/finish",r,pe)}async finishAuthentication(r){return this.post("/v1/passkeys/auth/finish",r,ce)}async validateSession(r){return this.get("/v1/sessions/validate",de,{Authorization:`Bearer ${r}`})}async startEmailFallback(r){let t=`${this.baseUrl}/v1/fallback/email/start`,n=await this.httpClient.post(t,{userId:r.userId,email:r.email},this.mergeHeaders());return n.ok?d(void 0):l(n.error)}async verifyEmailCode(r,t){return this.post("/v1/fallback/email/verify",{userId:r,code:t},me)}async startOnboarding(r){return this.post("/onboarding/start",r,ge)}async getOnboardingStatus(r){return this.get(`/onboarding/${r}/status`,Re)}async getOnboardingRegister(r){return this.get(`/onboarding/${r}/register`,ye)}async registerOnboardingPasskey(r,t){return this.post(`/onboarding/${r}/register-passkey`,t,fe)}async completeOnboarding(r,t){return this.post(`/onboarding/${r}/complete`,t,ve)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},$)}async initCrossDeviceRegistration(r){return this.post("/v1/auth/cross-device/init-registration",{external_user_id:r.externalUserId},$)}async getCrossDeviceStatus(r){return this.get(`/v1/auth/cross-device/status/${r}`,he)}async getCrossDeviceContext(r){return this.get(`/v1/auth/cross-device/context/${r}`,Ee)}async verifyCrossDeviceAuth(r){let t=`${this.baseUrl}/v1/auth/cross-device/verify`,n=await this.httpClient.post(t,r,this.mergeHeaders());return n.ok?d(void 0):l(n.error)}async verifyCrossDeviceRegistration(r){let t=`${this.baseUrl}/v1/auth/cross-device/verify-registration`,n=await this.httpClient.post(t,r,this.mergeHeaders());return n.ok?d(void 0):l(n.error)}async verifyAccountRecoveryOtp(r,t){return this.post("/v1/users/recovery/verify",{external_id:r,otp:t},be)}async completeAccountRecovery(r,t){return this.post("/v1/users/recovery/complete",{recovery_session_id:r,credential:t},_e)}};var Tr=3e4;function Ar(){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 Ve(e,r){let t=r*Math.pow(2,e);return Math.min(t,Tr)}function Ir(e,r){return e!=="GET"?!1:r>=500||r===429}var z=class{constructor(r,t=0,n=1e3,s){this.timeoutMs=r;this.maxRetries=t;this.retryDelayMs=n;this.logger=s}async get(r,t){return this.request(r,{method:"GET",headers:t})}async post(r,t,n){return this.request(r,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",...n}})}async request(r,t){let n=(t.method??"GET").toUpperCase(),s=Ar(),i=new Headers(t.headers);i.set("X-Request-Id",s),this.logger&&this.logger.debug("request",{requestId:s,url:r,method:n});let a;for(let c=0;c<=this.maxRetries;c++)try{let R=new AbortController,v=setTimeout(()=>R.abort(),this.timeoutMs);try{let y=await fetch(r,{...t,headers:i,signal:R.signal});if(!y.ok){let E;try{E=await y.json()}catch{}let x=E,I=x?.message??y.statusText,K=x?.error,_=f(K==="challenge_mismatch"?"CHALLENGE_MISMATCH":K??"NETWORK_FAILURE",I,{requestId:s,status:y.status,statusText:y.statusText,data:E});if(Ir(n,y.status)&&c<this.maxRetries){a=_,await new Promise(j=>setTimeout(j,Ve(c,this.retryDelayMs)));continue}return l(_)}if(y.status===204)return d(void 0);if(y.headers.get("content-length")==="0")return d(void 0);let A=await y.json();return d(A)}finally{clearTimeout(v)}}catch(R){if(a=R,n==="GET"&&c<this.maxRetries)await new Promise(y=>setTimeout(y,Ve(c,this.retryDelayMs)));else break}return a instanceof Error&&a.name==="AbortError"?l(f("TIMEOUT","Request timed out",{requestId:s})):l(f("NETWORK_FAILURE",a instanceof Error?a.message:"Request failed",{requestId:s,cause:a}))}};function C(e){let r=new Uint8Array(e),t=Array.from(r,s=>String.fromCharCode(s)).join("");if(typeof globalThis.btoa>"u")throw ie("encode");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Cr(e){if(typeof globalThis.atob>"u")throw ie("decode");let r=e.replace(/-/g,"+").replace(/_/g,"/"),t=r.length%4,n=t===0?r:r+"=".repeat(4-t),s=globalThis.atob(n);return Uint8Array.from(s,i=>i.charCodeAt(0))}function U(e){let r=Cr(e),t=new ArrayBuffer(r.length);return new Uint8Array(t).set(r),t}function We(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function S(e){if(!e.response)throw f("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!We(r))throw f("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("attestationObject"in r))throw f("UNKNOWN_ERROR","Invalid credential response structure for register: attestationObject is missing",{response:r});let t=r.clientDataJSON,n=r.attestationObject;return{id:e.id,rawId:C(e.rawId),response:{clientDataJSON:C(t),attestationObject:C(n)},type:"public-key"}}function J(e){if(!e.response)throw f("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!We(r))throw f("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("authenticatorData"in r)||!("signature"in r))throw f("UNKNOWN_ERROR","Invalid credential response structure for auth: authenticatorData or signature is missing",{response:r});let t=r.clientDataJSON,n=r.authenticatorData,s=r.signature,i=r.userHandle;return{id:e.id,rawId:C(e.rawId),response:{authenticatorData:C(n),clientDataJSON:C(t),signature:C(s),...i&&{userHandle:C(i)}},type:"public-key"}}function F(){try{return!(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return!1}}async function Or(){try{return!F()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?!1:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function Be(){let e=F(),r=await Or();return{isPasskeySupported:e,platformAuthenticatorAvailable:r,recommendedFlow:e?"passkey":"fallback"}}function k(e,r="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw Le(r)}async function W(e){let{operation:r,eventEmitter:t,start:n,createOptions:s,invoke:i,finish:a}=e;try{if(t.emit("start",{type:"start",operation:r}),!F()){let m=Fe();return t.emit("error",{type:"error",error:m}),l(m)}let c=await n();if(!c.ok)return t.emit("error",{type:"error",error:c.error}),l(c.error);let R=s(c.value);if(!R.ok)return t.emit("error",{type:"error",error:R.error}),l(R.error);let v=await i(R.value);if(!v){let m=h("credential",`${r==="register"?"creation":"retrieval"} failed`);return t.emit("error",{type:"error",error:m}),l(m)}try{k(v)}catch(m){let A=b(m);return t.emit("error",{type:"error",error:A}),l(A)}let y=await a(c.value,v);return y.ok?(t.emit("success",{type:"success",operation:r}),d(y.value)):(t.emit("error",{type:"error",error:y.error}),l(y.error))}catch(c){let R=b(c);return t.emit("error",{type:"error",error:R}),l(R)}}function M(e,r){try{Y(e.challenge,"challenge"),Y(e.user.id,"user.id");let t=U(e.challenge),n=U(e.user.id),s={userVerification:"preferred"};e.authenticatorSelection&&(s={...e.authenticatorSelection}),r&&(s={...s,authenticatorAttachment:r});let i={rp:{id:e.rp.id,name:e.rp.name},user:{id:n,name:e.user.name,displayName:e.user.displayName},challenge:t,pubKeyCredParams:e.pubKeyCredParams,...e.timeout!==void 0&&{timeout:e.timeout},attestation:"none",authenticatorSelection:s,...e.excludeCredentials&&{excludeCredentials:e.excludeCredentials.map(a=>({id:U(a.id),type:a.type,...a.transports&&{transports:a.transports}}))}};return d({publicKey:i})}catch(t){return l(b(t))}}function Te(e,r){try{Y(e.challenge,"challenge");let t=U(e.challenge);return d({publicKey:{challenge:t,rpId:e.rpId,...e.timeout!==void 0&&{timeout:e.timeout},userVerification:e.userVerification??"preferred",...e.allowCredentials&&{allowCredentials:e.allowCredentials.map(n=>({id:U(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...r!==void 0&&{mediation:r}})}catch(t){return l(b(t))}}async function He(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let s=h("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:s}),l(s)}return W({operation:"register",eventEmitter:t,start:()=>r.startRegister({external_user_id:n}),createOptions:s=>M(s.challenge,e.authenticatorType),invoke:async s=>{let i={...s,...e.signal&&{signal:e.signal}};return navigator.credentials.create(i)},finish:async(s,i)=>{let a=await r.finishRegister({session_id:s.session_id,credential:S(i)});return a.ok?d({success:!0,credentialId:a.value.credential_id,credential_id:a.value.credential_id,status:a.value.status,sessionToken:a.value.session_token,user:{userId:a.value.user.user_id,externalUserId:a.value.user.external_user_id,email:a.value.user.email,metadata:a.value.user.metadata}}):l(a.error)}})}async function Ye(e,r,t){let n=e.externalUserId??e.external_user_id,s=n!==void 0&&typeof n=="string"&&n.trim()!=="";return W({operation:"authenticate",eventEmitter:t,start:()=>r.startAuth(s?{external_user_id:n.trim()}:{}),createOptions:i=>Te(i.challenge,e.mediation),invoke:async i=>{let a={...i,...e.signal&&{signal:e.signal}};return navigator.credentials.get(a)},finish:async(i,a)=>{let c=await r.finishAuthentication({session_id:i.session_id,credential:J(a)});return c.ok?d({authenticated:c.value.authenticated,sessionToken:c.value.session_token,user:{userId:c.value.user.user_id,externalUserId:c.value.user.external_user_id,email:c.value.user.email,metadata:c.value.user.metadata},signals:c.value.signals}):l(c.error)}})}var Sr=2e3,xr=60,Z=class{constructor(r){this.apiClient=r}async startFlow(r){let t=await this.apiClient.startOnboarding({user_role:r.user_role});if(!t.ok)return l(t.error);let{session_id:n}=t.value;for(let s=0;s<xr;s++){await new Promise(R=>setTimeout(R,Sr));let i=await this.apiClient.getOnboardingStatus(n);if(!i.ok)return l(i.error);let a=i.value.status,c=i.value.onboarding_url;if(a==="pending_passkey"){let R=await this.apiClient.getOnboardingRegister(n);if(!R.ok)return l(R.error);let v=R.value;if(!v.challenge)return l(f("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:c}));let y=M(v.challenge);if(!y.ok)return l(y.error);let m;try{m=await navigator.credentials.create(y.value)}catch(I){return l(b(I))}try{k(m,"create")}catch(I){return l(b(I))}let A;try{A=S(m)}catch(I){return l(b(I))}let E=await this.apiClient.registerOnboardingPasskey(n,{credential:A,challenge:v.challenge.challenge});return E.ok?await this.apiClient.completeOnboarding(n,{company_name:r.company_name}):l(E.error)}if(a==="completed")return await this.apiClient.completeOnboarding(n,{company_name:r.company_name})}return l(f("TIMEOUT","Onboarding timed out"))}};var Pr=2e3,kr=60,Q=class{constructor(r){this.apiClient=r}async init(){return this.apiClient.initCrossDeviceAuth()}async initRegistration(r){return this.apiClient.initCrossDeviceRegistration(r)}async waitForSession(r,t){for(let n=0;n<kr;n++){if(t?.aborted)return l(f("ABORT_ERROR","Operation aborted by user or timeout"));let s=await this.apiClient.getCrossDeviceStatus(r);if(!s.ok)return l(s.error);if(s.value.status==="completed")return!s.value.session_token||!s.value.user_id?l(f("UNKNOWN_ERROR","Missing data in completed session")):d({session_token:s.value.session_token,user_id:s.value.user_id});if(t?.aborted)return l(f("ABORT_ERROR","Operation aborted by user or timeout"));if(await new Promise(i=>{let a=setTimeout(()=>{i(null),t?.removeEventListener("abort",c)},Pr),c=()=>{clearTimeout(a),i(null)};t?.addEventListener("abort",c)}),t?.aborted)return l(f("ABORT_ERROR","Operation aborted by user or timeout"))}return l(f("TIMEOUT","Cross-device authentication timed out"))}async approve(r){let t=await this.apiClient.getCrossDeviceContext(r);if(!t.ok)return l(t.error);let n=t.value;return n.type==="registration"?this.executeRegistrationApproval(r,n):this.executeAuthApproval(r,n)}async executeRegistrationApproval(r,t){let n=M(t.options);if(!n.ok)return l(n.error);let s;try{s=await navigator.credentials.create(n.value)}catch(a){return l(b(a))}try{k(s,"create")}catch(a){return l(b(a))}let i;try{i=S(s)}catch(a){return l(b(a))}return this.apiClient.verifyCrossDeviceRegistration({session_id:r,credential:i})}async executeAuthApproval(r,t){let n=Te(t.options);if(!n.ok)return l(n.error);let s;try{s=await navigator.credentials.get(n.value)}catch(a){return l(b(a))}try{k(s,"get")}catch(a){return l(b(a))}let i;try{i=J(s)}catch(a){return l(b(a))}return this.apiClient.verifyCrossDeviceAuth({session_id:r,credential:i})}};var ee=class{handlers;constructor(){this.handlers=new Map}on(r,t){let n=this.handlers.get(r);return n||(n=new Set,this.handlers.set(r,n)),n.add(t),()=>{this.off(r,t)}}off(r,t){let n=this.handlers.get(r);n&&(n.delete(t),n.size===0&&this.handlers.delete(r))}emit(r,t){let n=this.handlers.get(r);n&&n.forEach(s=>{try{s(t)}catch{}})}removeAllListeners(){this.handlers.clear()}};async function Ge(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let s=h("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:s}),l(s)}if(!e.otp||typeof e.otp!="string"||e.otp.trim().length!==6){let s=h("otp","must be a 6-digit string");return t.emit("error",{type:"error",error:s}),l(s)}return W({operation:"register",eventEmitter:t,start:()=>r.verifyAccountRecoveryOtp(n,e.otp),createOptions:s=>M(s.challenge),invoke:async s=>navigator.credentials.create(s),finish:async(s,i)=>{let a=await r.completeAccountRecovery(s.recovery_session_id,S(i));return a.ok?d({success:!0,credentialId:a.value.credential_id,status:a.value.status,sessionToken:a.value.session_token,user:{userId:a.value.user.user_id,externalUserId:a.value.user.external_user_id,email:a.value.user.email,metadata:a.value.user.metadata}}):l(a.error)}})}var Ae="https://api.trymellonauth.com",$e="https://api.trymellonauth.com/v1/telemetry";var Xe="trymellon_sandbox_session_token_v1";function ze(e){return{async send(r){let t=JSON.stringify(r);if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"){navigator.sendBeacon(e,t);return}typeof fetch<"u"&&await fetch(e,{method:"POST",body:t,headers:{"Content-Type":"application/json"},keepalive:!0})}}}function Ie(e,r){return{event:e,latencyMs:r,ok:!0}}var re=class e{sandbox;sandboxToken;apiClient;eventEmitter;telemetrySender;crossDeviceManager;onboarding;static create(r){try{let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")return l(h("appId","must be a non-empty string"));if(!n||typeof n!="string"||n.trim()==="")return l(h("publishableKey","must be a non-empty string"));let s=r.apiBaseUrl??Ae;oe(s,"apiBaseUrl");let i=r.timeoutMs??3e4;return P(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&P(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&P(r.retryDelayMs,"retryDelayMs",100,1e4),d(new e(r))}catch(t){return se(t)?l(t):l(h("config",t.message))}}constructor(r){this.sandbox=r.sandbox===!0,this.sandboxToken=this.sandbox&&r.sandboxToken!=null&&r.sandboxToken!==""?r.sandboxToken:Xe;let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")throw h("appId","must be a non-empty string");if(!n||typeof n!="string"||n.trim()==="")throw h("publishableKey","must be a non-empty string");let s=r.apiBaseUrl??Ae;oe(s,"apiBaseUrl");let i=r.timeoutMs??3e4;P(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&P(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&P(r.retryDelayMs,"retryDelayMs",100,1e4);let a=r.maxRetries??3,c=r.retryDelayMs??1e3,R=new z(i,a,c,r.logger),v=r.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),y={"X-App-Id":t.trim(),Authorization:`Bearer ${n.trim()}`,...v&&{Origin:v}};this.apiClient=new X(R,s,y),this.onboarding=new Z(this.apiClient),this.crossDeviceManager=new Q(this.apiClient),this.eventEmitter=new ee,r.enableTelemetry&&(this.telemetrySender=r.telemetrySender??ze(r.telemetryEndpoint??$e))}static isSupported(){return F()}async register(r){if(this.sandbox){let s=r.externalUserId??r.external_user_id??"sandbox";return Promise.resolve(d({success:!0,credentialId:"",status:"sandbox",sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:typeof s=="string"?s:"sandbox"}}))}let t=Date.now(),n=await He(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Ie("register",Date.now()-t)).catch(()=>{}),n}async authenticate(r){if(this.sandbox){let s=r.externalUserId??r.external_user_id??"sandbox";return Promise.resolve(d({authenticated:!0,sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:typeof s=="string"?s:"sandbox"}}))}let t=Date.now(),n=await Ye(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Ie("authenticate",Date.now()-t)).catch(()=>{}),n}async validateSession(r){return this.sandbox&&r===this.sandboxToken?Promise.resolve(d({valid:!0,user_id:"sandbox-user",external_user_id:"sandbox",tenant_id:"sandbox-tenant",app_id:"sandbox-app"})):this.apiClient.validateSession(r)}async getStatus(){return Be()}on(r,t){return this.eventEmitter.on(r,t)}version(){return"1.6.1"}fallback={email:{start:async r=>this.apiClient.startEmailFallback(r),verify:async r=>this.apiClient.verifyEmailCode(r.userId,r.code)}};auth={crossDevice:{init:()=>this.crossDeviceManager.init(),initRegistration:r=>this.crossDeviceManager.initRegistration(r),waitForSession:(r,t)=>this.crossDeviceManager.waitForSession(r,t),approve:r=>this.crossDeviceManager.approve(r)},recoverAccount:async r=>Ge(r,this.apiClient,this.eventEmitter)}};var B=new L.InjectionToken("TRYMELLON_CONFIG"),sr,Ce;sr=[(0,L.Injectable)({providedIn:"root"})];var D=class{config=(0,L.inject)(B,{optional:!0});_client=null;get client(){if(this._client==null){if(this.config==null)throw new Error("TryMellonService: provide TRYMELLON_CONFIG (e.g. via provideTryMellonConfig(config))");this._client=new re(this.config)}return this._client}};Ce=De(null),D=Ue(Ce,0,"TryMellonService",sr,D),Ne(Ce,1,D);function wr(e){return{provide:B,useValue:e}}
2
+ "use strict";var or=Object.create;var U=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var ar=Object.getOwnPropertyNames;var lr=Object.prototype.hasOwnProperty;var De=(e,r)=>(r=Symbol[e])?r:Symbol.for("Symbol."+e),V=e=>{throw TypeError(e)};var ur=(e,r,t)=>r in e?U(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var ke=(e,r)=>U(e,"name",{value:r,configurable:!0});var pr=(e,r)=>{for(var t in r)U(e,t,{get:r[t],enumerable:!0})},cr=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of ar(r))!lr.call(e,s)&&s!==t&&U(e,s,{get:()=>r[s],enumerable:!(n=Me(r,s))||n.enumerable});return e};var dr=e=>cr(U({},"__esModule",{value:!0}),e);var we=e=>[,,,or(e?.[De("metadata")]??null)],Ne=["class","method","getter","setter","accessor","field","value","get","set"],q=e=>e!==void 0&&typeof e!="function"?V("Function expected"):e,mr=(e,r,t,n,s)=>({kind:Ne[e],name:r,metadata:n,addInitializer:i=>t._?V("Already initialized"):s.push(q(i||null))}),gr=(e,r)=>ur(r,De("metadata"),e[3]),Ue=(e,r,t,n)=>{for(var s=0,i=e[r>>1],a=i&&i.length;s<a;s++)r&1?i[s].call(t):n=i[s].call(t,n);return n},Fe=(e,r,t,n,s,i)=>{var a,d,R,v,y,g=r&7,T=!!(r&8),I=!!(r&16),C=g>3?e.length+1:g?T?1:2:0,A=Ne[g+5],P=g>3&&(e[C-1]=[]),G=e[C]||(e[C]=[]),E=g&&(!I&&!T&&(s=s.prototype),g<5&&(g>3||!I)&&Me(g<4?s:{get[t](){return xe(this,i)},set[t](b){return Pe(this,i,b)}},t));g?I&&g<4&&ke(i,(g>2?"set ":g>1?"get ":"")+t):ke(s,t);for(var O=n.length-1;O>=0;O--)v=mr(g,t,R={},e[3],G),g&&(v.static=T,v.private=I,y=v.access={has:I?b=>Rr(s,b):b=>t in b},g^3&&(y.get=I?b=>(g^1?xe:yr)(b,s,g^4?i:E.get):b=>b[t]),g>2&&(y.set=I?(b,se)=>Pe(b,s,se,g^4?i:E.set):(b,se)=>b[t]=se)),d=(0,n[O])(g?g<4?I?i:E[A]:g>4?void 0:{get:E.get,set:E.set}:s,v),R._=1,g^4||d===void 0?q(d)&&(g>4?P.unshift(d):g?I?i=d:E[A]=d:s=d):typeof d!="object"||d===null?V("Object expected"):(q(a=d.get)&&(E.get=a),q(a=d.set)&&(E.set=a),q(a=d.init)&&P.unshift(a));return g||gr(e,s),E&&U(s,t,E),I?g^4?i:E:s};var ie=(e,r,t)=>r.has(e)||V("Cannot "+t),Rr=(e,r)=>Object(r)!==r?V('Cannot use the "in" operator on this value'):e.has(r),xe=(e,r,t)=>(ie(e,r,"read from private field"),t?t.call(e):r.get(e));var Pe=(e,r,t,n)=>(ie(e,r,"write to private field"),n?n.call(e,t):r.set(e,t),t),yr=(e,r,t)=>(ie(e,r,"access private method"),t);var Lr={};pr(Lr,{TRYMELLON_CONFIG:()=>H,TryMellonService:()=>N,provideTryMellonConfig:()=>Fr});module.exports=dr(Lr);var j=require("@angular/core");var c=e=>({ok:!0,value:e}),l=e=>({ok:!1,error:e});var Y=class e extends Error{code;details;isTryMellonError=!0;constructor(r,t,n){super(t),this.name="TryMellonError",this.code=r,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},fr={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 f(e,r,t){return new Y(e,r??fr[e],t)}function oe(e){return e instanceof Y||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===!0}function Le(){return f("NOT_SUPPORTED")}function h(e,r){return f("INVALID_ARGUMENT",`Invalid argument: ${e} - ${r}`,{field:e,reason:r})}function Ke(e){return f("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function ae(e){return f("NOT_SUPPORTED",`No base64 ${e==="encode"?"encoding":"decoding"} available`,{type:e})}function le(e,r){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw h(r,"must use http or https protocol")}catch(t){throw oe(t)?t:h(r,"must be a valid URL")}}function M(e,r,t,n){if(!Number.isFinite(e))throw h(r,"must be a finite number");if(e<t||e>n)throw h(r,`must be between ${t} and ${n}`)}function X(e,r){if(typeof e!="string"||e.length===0)throw h(r,"must be a non-empty string");if(!/^[A-Za-z0-9_-]+$/.test(e))throw h(r,"must be a valid base64url string")}var vr={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function W(e){if(typeof e!="string")return"UNKNOWN_ERROR";let r=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"}[r]??"UNKNOWN_ERROR"}function _(e){if(e instanceof DOMException){let r=e.name,t=e.message||"WebAuthn operation failed",n=vr[r]??"UNKNOWN_ERROR";return f(n,t,{originalError:e})}return e instanceof Error?f("UNKNOWN_ERROR",e.message,{originalError:e}):f("UNKNOWN_ERROR","An unknown error occurred",{originalError:e})}function m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function u(e){return typeof e=="string"}function k(e){return typeof e=="number"&&Number.isFinite(e)}function $(e){return typeof e=="boolean"}function F(e){return Array.isArray(e)}function o(e,r){return l(f("UNKNOWN_ERROR",e,{...r,originalData:r?.originalData}))}function p(e,r){return e[r]}function je(e,r){return!m(e)||!u(e.name)||!u(e.id)?o("Invalid API response: challenge.rp must have name and id strings",{originalData:r}):c(!0)}function qe(e,r){return!m(e)||!u(e.id)||!u(e.name)||!u(e.displayName)?o("Invalid API response: challenge.user must have id, name, displayName strings",{originalData:r}):c(!0)}function Ve(e,r){if(!F(e))return o("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:r});for(let t of e)if(!m(t)||t.type!=="public-key"||!k(t.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:r});return c(!0)}function ue(e,r){if(!m(e))return o("Invalid API response: user must be object",{field:"user",originalData:r});let t=p(e,"user_id"),n=p(e,"external_user_id");if(!u(t)||!u(n))return o("Invalid API response: user must have user_id and external_user_id strings",{originalData:r});let s=e.email,i=e.metadata;return s!==void 0&&!u(s)?o("Invalid API response: user.email must be string",{originalData:r}):i!==void 0&&(typeof i!="object"||i===null)?o("Invalid API response: user.metadata must be object",{originalData:r}):c({user_id:t,external_user_id:n,...s!==void 0&&{email:s},...i!==void 0&&{metadata:i}})}function pe(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!u(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!m(t))return o("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=je(p(t,"rp"),e);if(!n.ok)return n;let s=qe(p(t,"user"),e);if(!s.ok)return s;let i=p(t,"challenge");if(!u(i))return o("Invalid API response: challenge.challenge must be string",{originalData:e});let a=Ve(p(t,"pubKeyCredParams"),e);if(!a.ok)return a;let d=t.timeout;if(d!==void 0&&!k(d))return o("Invalid API response: challenge.timeout must be number",{originalData:e});let R=t.excludeCredentials;if(R!==void 0){if(!F(R))return o("Invalid API response: excludeCredentials must be array",{originalData:e});for(let y of R)if(!m(y)||y.type!=="public-key"||!u(y.id))return o("Invalid API response: excludeCredentials items must have id and type",{originalData:e})}let v=t.authenticatorSelection;return v!==void 0&&!m(v)?o("Invalid API response: authenticatorSelection must be object",{originalData:e}):c({session_id:r,challenge:{rp:t.rp,user:t.user,challenge:i,pubKeyCredParams:t.pubKeyCredParams,...d!==void 0&&{timeout:d},...R!==void 0&&{excludeCredentials:R},...v!==void 0&&{authenticatorSelection:v}}})}function ce(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!u(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!m(t))return o("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=p(t,"challenge"),s=p(t,"rpId"),i=t.allowCredentials;if(!u(n))return o("Invalid API response: challenge.challenge must be string",{originalData:e});if(!u(s))return o("Invalid API response: challenge.rpId must be string",{originalData:e});if(i!==void 0&&!F(i))return o("Invalid API response: allowCredentials must be array",{originalData:e});if(i){for(let R of i)if(!m(R)||R.type!=="public-key"||!u(R.id))return o("Invalid API response: allowCredentials items must have id and type",{originalData:e})}let a=t.timeout;if(a!==void 0&&!k(a))return o("Invalid API response: challenge.timeout must be number",{originalData:e});let d=t.userVerification;return d!==void 0&&!["required","preferred","discouraged"].includes(String(d))?o("Invalid API response: userVerification must be required|preferred|discouraged",{originalData:e}):c({session_id:r,challenge:{challenge:n,rpId:s,allowCredentials:i??[],...a!==void 0&&{timeout:a},...d!==void 0&&{userVerification:d}}})}function de(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"credential_id"),t=p(e,"status"),n=p(e,"session_token"),s=p(e,"user");if(!u(r))return o("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!u(t))return o("Invalid API response: status must be string",{field:"status",originalData:e});if(!u(n))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=ue(s,e);return i.ok?c({credential_id:r,status:t,session_token:n,user:i.value}):o(i.error.message,{originalData:e})}function me(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"authenticated"),t=p(e,"session_token"),n=p(e,"user"),s=p(e,"signals");if(!$(r))return o("Invalid API response: authenticated must be boolean",{field:"authenticated",originalData:e});if(!u(t))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=ue(n,e);return i.ok?s!==void 0&&!m(s)?o("Invalid API response: signals must be object",{originalData:e}):c({authenticated:r,session_token:t,user:i.value,signals:s}):o(i.error.message,{originalData:e})}function ge(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"valid"),t=p(e,"user_id"),n=p(e,"external_user_id"),s=p(e,"tenant_id"),i=p(e,"app_id");return $(r)?u(t)?u(n)?u(s)?u(i)?c({valid:r,user_id:t,external_user_id:n,tenant_id:s,app_id:i}):o("Invalid API response: app_id must be string",{field:"app_id",originalData:e}):o("Invalid API response: tenant_id must be string",{field:"tenant_id",originalData:e}):o("Invalid API response: external_user_id must be string",{field:"external_user_id",originalData:e}):o("Invalid API response: user_id must be string",{field:"user_id",originalData:e}):o("Invalid API response: valid must be boolean",{field:"valid",originalData:e})}function Re(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"sessionToken");return u(r)?c({sessionToken:r}):o("Invalid API response: sessionToken must be string",{field:"sessionToken",originalData:e})}var hr=["pending_passkey","pending_data","completed"],Er=["pending_data","completed"];function ye(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return u(r)?u(t)?k(n)?c({session_id:r,onboarding_url:t,expires_in:n}):o("Invalid API response: expires_in must be number",{field:"expires_in",originalData:e}):o("Invalid API response: onboarding_url must be string",{field:"onboarding_url",originalData:e}):o("Invalid API response: session_id must be string",{field:"session_id",originalData:e})}function fe(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"status"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return!u(r)||!hr.includes(r)?o("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):u(t)?k(n)?c({status:r,onboarding_url:t,expires_in:n}):o("Invalid API response: expires_in must be number",{originalData:e}):o("Invalid API response: onboarding_url must be string",{originalData:e})}function ve(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"onboarding_url");if(!u(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});if(t!=="pending_passkey")return o("Invalid API response: status must be pending_passkey",{field:"status",originalData:e});if(!u(n))return o("Invalid API response: onboarding_url must be string",{originalData:e});let s=e.challenge,i;if(s!==void 0){let a=br(s);if(!a.ok)return a;i=a.value}return c({session_id:r,status:"pending_passkey",onboarding_url:n,...i!==void 0&&{challenge:i}})}function br(e){if(!m(e))return o("Invalid API response: challenge must be object",{originalData:e});let r=p(e,"rp"),t=p(e,"user"),n=p(e,"challenge"),s=p(e,"pubKeyCredParams");if(!m(r)||!u(r.name)||!u(r.id))return o("Invalid API response: challenge.rp must have name and id",{originalData:e});if(!m(t)||!u(t.id)||!u(t.name)||!u(t.displayName))return o("Invalid API response: challenge.user must have id, name, displayName",{originalData:e});if(!u(n))return o("Invalid API response: challenge.challenge must be string",{originalData:e});if(!F(s))return o("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let i of s)if(!m(i)||i.type!=="public-key"||!k(i.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});return c({rp:r,user:t,challenge:n,pubKeyCredParams:s})}function he(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"user_id"),s=p(e,"tenant_id");return u(r)?!u(t)||!Er.includes(t)?o("Invalid API response: status must be pending_data|completed",{originalData:e}):u(n)?u(s)?c({session_id:r,status:t,user_id:n,tenant_id:s}):o("Invalid API response: tenant_id must be string",{originalData:e}):o("Invalid API response: user_id must be string",{originalData:e}):o("Invalid API response: session_id must be string",{originalData:e})}function Ee(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"user_id"),s=p(e,"tenant_id"),i=p(e,"session_token");return u(r)?t!=="completed"?o("Invalid API response: status must be completed",{originalData:e}):!u(n)||!u(s)||!u(i)?o("Invalid API response: user_id, tenant_id, session_token must be strings",{originalData:e}):c({session_id:r,status:"completed",user_id:n,tenant_id:s,session_token:i}):o("Invalid API response: session_id must be string",{originalData:e})}function _r(e){if(!e||typeof e!="object")return!1;let r=e;return typeof r.challenge=="string"&&r.rp!=null&&typeof r.rp=="object"&&r.user!=null&&typeof r.user=="object"&&Array.isArray(r.pubKeyCredParams)}function Tr(e){if(!e||typeof e!="object")return!1;let r=e;return typeof r.challenge=="string"&&typeof r.rpId=="string"}function z(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r="resultado"in e&&m(e.resultado)?e.resultado:e,t=r.session_id,n=r.qr_url,s=r.expires_at;return!u(t)||!u(n)||!u(s)?o("Invalid API response: missing required fields",{originalData:e}):c({session_id:t,qr_url:n,expires_at:s})}function be(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=e.status;return!u(r)||!["pending","authenticated","completed"].includes(r)?o("Invalid API response: invalid status",{originalData:e}):c({status:r,user_id:e.user_id,session_token:e.session_token})}function _e(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=e.type,t=r==="registration"?"registration":"auth",n=e.options;return m(n)?t==="registration"?_r(n)?c({type:"registration",options:n}):o("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):Tr(n)?c({type:"auth",options:n}):o("Invalid API response: auth options must have challenge and rpId",{originalData:e}):o("Invalid API response: options are required",{originalData:e})}function Te(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"challenge"),t=p(e,"recovery_session_id");return m(r)?u(t)?c({challenge:r,recovery_session_id:t}):o("Invalid API response: recovery_session_id must be string",{field:"recovery_session_id",originalData:e}):o("Invalid API response: challenge must be object",{field:"challenge",originalData:e})}function Ie(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"status"),t=p(e,"session_token"),n=p(e,"user"),s=p(e,"credential_id");if(!u(r))return o("Invalid API response: status must be string",{field:"status",originalData:e});if(!u(t))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!u(s))return o("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!m(n))return o("Invalid API response: user must be object",{field:"user",originalData:e});let i=p(n,"user_id");if(!u(i))return o("Invalid API response: user.user_id must be string",{field:"user.user_id",originalData:e});let a=n;return c({status:r,session_token:t,credential_id:s,user:{user_id:i,external_user_id:u(a.external_user_id)?a.external_user_id:void 0,email:u(a.email)?a.email:void 0,metadata:m(a.metadata)?a.metadata:void 0}})}var J=class{constructor(r,t,n={}){this.httpClient=r;this.baseUrl=t;this.defaultHeaders=n}mergeHeaders(r){return{...this.defaultHeaders,...r}}async post(r,t,n){let s=`${this.baseUrl}${r}`,i=await this.httpClient.post(s,t,this.mergeHeaders());return i.ok?n(i.value):l(i.error)}async get(r,t,n){let s=`${this.baseUrl}${r}`,i=await this.httpClient.get(s,this.mergeHeaders(n));return i.ok?t(i.value):l(i.error)}async startRegister(r){return this.post("/v1/passkeys/register/start",r,pe)}async startAuth(r){return this.post("/v1/passkeys/auth/start",r,ce)}async finishRegister(r){return this.post("/v1/passkeys/register/finish",r,de)}async finishAuthentication(r){return this.post("/v1/passkeys/auth/finish",r,me)}async validateSession(r){return this.get("/v1/sessions/validate",ge,{Authorization:`Bearer ${r}`})}async startEmailFallback(r){let t=`${this.baseUrl}/v1/fallback/email/start`,n=await this.httpClient.post(t,{userId:r.userId,email:r.email},this.mergeHeaders());return n.ok?c(void 0):l(n.error)}async verifyEmailCode(r,t){return this.post("/v1/fallback/email/verify",{userId:r,code:t},Re)}async startOnboarding(r){return this.post("/onboarding/start",r,ye)}async getOnboardingStatus(r){return this.get(`/onboarding/${r}/status`,fe)}async getOnboardingRegister(r){return this.get(`/onboarding/${r}/register`,ve)}async registerOnboardingPasskey(r,t){return this.post(`/onboarding/${r}/register-passkey`,t,he)}async completeOnboarding(r,t){return this.post(`/onboarding/${r}/complete`,t,Ee)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},z)}async initCrossDeviceRegistration(r){return this.post("/v1/auth/cross-device/init-registration",{external_user_id:r.externalUserId},z)}async getCrossDeviceStatus(r){return this.get(`/v1/auth/cross-device/status/${r}`,be)}async getCrossDeviceContext(r){return this.get(`/v1/auth/cross-device/context/${r}`,_e)}async verifyCrossDeviceAuth(r){let t=`${this.baseUrl}/v1/auth/cross-device/verify`,n=await this.httpClient.post(t,r,this.mergeHeaders());return n.ok?c(void 0):l(n.error)}async verifyCrossDeviceRegistration(r){let t=`${this.baseUrl}/v1/auth/cross-device/verify-registration`,n=await this.httpClient.post(t,r,this.mergeHeaders());return n.ok?c(void 0):l(n.error)}async verifyAccountRecoveryOtp(r,t){return this.post("/v1/users/recovery/verify",{external_id:r,otp:t},Te)}async completeAccountRecovery(r,t){return this.post("/v1/users/recovery/complete",{recovery_session_id:r,credential:t},Ie)}};function Ir(e){return typeof e=="object"&&e!==null&&e.ok===!0&&"resultado"in e}function Ar(e){if(typeof e!="object"||e===null)return!1;let r=e;if(r.ok!==!1||!r.error||typeof r.error!="object")return!1;let t=r.error;return typeof t.code=="string"&&typeof t.message=="string"}var Cr=3e4;function Or(){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 We(e,r){let t=r*Math.pow(2,e);return Math.min(t,Cr)}function Sr(e,r){return e!=="GET"?!1:r>=500||r===429}var Z=class{constructor(r,t=0,n=1e3,s){this.timeoutMs=r;this.maxRetries=t;this.retryDelayMs=n;this.logger=s}async get(r,t){return this.request(r,{method:"GET",headers:t})}async post(r,t,n){return this.request(r,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",...n}})}async request(r,t){let n=(t.method??"GET").toUpperCase(),s=Or(),i=new Headers(t.headers);i.set("X-Request-Id",s),this.logger&&this.logger.debug("request",{requestId:s,url:r,method:n});let a;for(let d=0;d<=this.maxRetries;d++)try{let R=new AbortController,v=setTimeout(()=>R.abort(),this.timeoutMs);try{let y=await fetch(r,{...t,headers:i,signal:R.signal});if(!y.ok){let C;try{C=await y.json()}catch{}let A,P;if(Ar(C))A=C.error.message,P=W(C.error.code);else{let E=C,O=E?.error;if(typeof O=="object"&&O!==null&&"code"in O&&typeof O.code=="string")A=O.message??E?.message??y.statusText,P=W(O.code);else{A=E?.message??y.statusText;let b=E?.error;P=typeof b=="string"?W(b):b===void 0?"NETWORK_FAILURE":W(String(b))}}let G=f(P,A,{requestId:s,status:y.status,statusText:y.statusText,data:C});if(Sr(n,y.status)&&d<this.maxRetries){a=G,await new Promise(E=>setTimeout(E,We(d,this.retryDelayMs)));continue}return l(G)}if(y.status===204)return c(void 0);if(y.headers.get("content-length")==="0")return c(void 0);let T=await y.json();if(Ir(T))return c(T.resultado);let I=T;return typeof T=="object"&&T!==null&&I.ok===!0&&!("resultado"in I)?c(void 0):c(T)}finally{clearTimeout(v)}}catch(R){if(a=R,n==="GET"&&d<this.maxRetries)await new Promise(y=>setTimeout(y,We(d,this.retryDelayMs)));else break}return a instanceof Error&&a.name==="AbortError"?l(f("TIMEOUT","Request timed out",{requestId:s})):l(f("NETWORK_FAILURE",a instanceof Error?a.message:"Request failed",{requestId:s,cause:a}))}};function S(e){let r=new Uint8Array(e),t=Array.from(r,s=>String.fromCharCode(s)).join("");if(typeof globalThis.btoa>"u")throw ae("encode");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function kr(e){if(typeof globalThis.atob>"u")throw ae("decode");let r=e.replace(/-/g,"+").replace(/_/g,"/"),t=r.length%4,n=t===0?r:r+"=".repeat(4-t),s=globalThis.atob(n);return Uint8Array.from(s,i=>i.charCodeAt(0))}function L(e){let r=kr(e),t=new ArrayBuffer(r.length);return new Uint8Array(t).set(r),t}function Be(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function x(e){if(!e.response)throw f("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!Be(r))throw f("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("attestationObject"in r))throw f("UNKNOWN_ERROR","Invalid credential response structure for register: attestationObject is missing",{response:r});let t=r.clientDataJSON,n=r.attestationObject;return{id:e.id,rawId:S(e.rawId),response:{clientDataJSON:S(t),attestationObject:S(n)},type:"public-key"}}function Q(e){if(!e.response)throw f("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!Be(r))throw f("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("authenticatorData"in r)||!("signature"in r))throw f("UNKNOWN_ERROR","Invalid credential response structure for auth: authenticatorData or signature is missing",{response:r});let t=r.clientDataJSON,n=r.authenticatorData,s=r.signature,i=r.userHandle;return{id:e.id,rawId:S(e.rawId),response:{authenticatorData:S(n),clientDataJSON:S(t),signature:S(s),...i&&{userHandle:S(i)}},type:"public-key"}}function K(){try{return!(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return!1}}async function xr(){try{return!K()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?!1:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function He(){let e=K(),r=await xr();return{isPasskeySupported:e,platformAuthenticatorAvailable:r,recommendedFlow:e?"passkey":"fallback"}}function D(e,r="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw Ke(r)}async function B(e){let{operation:r,eventEmitter:t,start:n,createOptions:s,invoke:i,finish:a}=e;try{if(t.emit("start",{type:"start",operation:r}),!K()){let g=Le();return t.emit("error",{type:"error",error:g}),l(g)}let d=await n();if(!d.ok)return t.emit("error",{type:"error",error:d.error}),l(d.error);let R=s(d.value);if(!R.ok)return t.emit("error",{type:"error",error:R.error}),l(R.error);let v=await i(R.value);if(!v){let g=h("credential",`${r==="register"?"creation":"retrieval"} failed`);return t.emit("error",{type:"error",error:g}),l(g)}try{D(v)}catch(g){let T=_(g);return t.emit("error",{type:"error",error:T}),l(T)}let y=await a(d.value,v);return y.ok?(t.emit("success",{type:"success",operation:r}),c(y.value)):(t.emit("error",{type:"error",error:y.error}),l(y.error))}catch(d){let R=_(d);return t.emit("error",{type:"error",error:R}),l(R)}}function w(e,r){try{X(e.challenge,"challenge"),X(e.user.id,"user.id");let t=L(e.challenge),n=L(e.user.id),s={userVerification:"preferred"};e.authenticatorSelection&&(s={...e.authenticatorSelection}),r&&(s={...s,authenticatorAttachment:r});let i={rp:{id:e.rp.id,name:e.rp.name},user:{id:n,name:e.user.name,displayName:e.user.displayName},challenge:t,pubKeyCredParams:e.pubKeyCredParams,...e.timeout!==void 0&&{timeout:e.timeout},attestation:"none",authenticatorSelection:s,...e.excludeCredentials&&{excludeCredentials:e.excludeCredentials.map(a=>({id:L(a.id),type:a.type,...a.transports&&{transports:a.transports}}))}};return c({publicKey:i})}catch(t){return l(_(t))}}function Ae(e,r){try{X(e.challenge,"challenge");let t=L(e.challenge);return c({publicKey:{challenge:t,rpId:e.rpId,...e.timeout!==void 0&&{timeout:e.timeout},userVerification:e.userVerification??"preferred",...e.allowCredentials&&{allowCredentials:e.allowCredentials.map(n=>({id:L(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...r!==void 0&&{mediation:r}})}catch(t){return l(_(t))}}async function Ge(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let s=h("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:s}),l(s)}return B({operation:"register",eventEmitter:t,start:()=>r.startRegister({external_user_id:n}),createOptions:s=>w(s.challenge,e.authenticatorType),invoke:async s=>{let i={...s,...e.signal&&{signal:e.signal}};return navigator.credentials.create(i)},finish:async(s,i)=>{let a=await r.finishRegister({session_id:s.session_id,credential:x(i)});return a.ok?c({success:!0,credentialId:a.value.credential_id,credential_id:a.value.credential_id,status:a.value.status,sessionToken:a.value.session_token,user:{userId:a.value.user.user_id,externalUserId:a.value.user.external_user_id,email:a.value.user.email,metadata:a.value.user.metadata}}):l(a.error)}})}async function Ye(e,r,t){let n=e.externalUserId??e.external_user_id,s=n!==void 0&&typeof n=="string"&&n.trim()!=="";return B({operation:"authenticate",eventEmitter:t,start:()=>r.startAuth(s?{external_user_id:n.trim()}:{}),createOptions:i=>Ae(i.challenge,e.mediation),invoke:async i=>{let a={...i,...e.signal&&{signal:e.signal}};return navigator.credentials.get(a)},finish:async(i,a)=>{let d=await r.finishAuthentication({session_id:i.session_id,credential:Q(a)});return d.ok?c({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}):l(d.error)}})}var Pr=2e3,Mr=60,ee=class{constructor(r){this.apiClient=r}async startFlow(r){let t=await this.apiClient.startOnboarding({user_role:r.user_role});if(!t.ok)return l(t.error);let{session_id:n}=t.value;for(let s=0;s<Mr;s++){await new Promise(R=>setTimeout(R,Pr));let i=await this.apiClient.getOnboardingStatus(n);if(!i.ok)return l(i.error);let a=i.value.status,d=i.value.onboarding_url;if(a==="pending_passkey"){let R=await this.apiClient.getOnboardingRegister(n);if(!R.ok)return l(R.error);let v=R.value;if(!v.challenge)return l(f("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:d}));let y=w(v.challenge);if(!y.ok)return l(y.error);let g;try{g=await navigator.credentials.create(y.value)}catch(A){return l(_(A))}try{D(g,"create")}catch(A){return l(_(A))}let T;try{T=x(g)}catch(A){return l(_(A))}let I=await this.apiClient.registerOnboardingPasskey(n,{credential:T,challenge:v.challenge.challenge});return I.ok?await this.apiClient.completeOnboarding(n,{company_name:r.company_name}):l(I.error)}if(a==="completed")return await this.apiClient.completeOnboarding(n,{company_name:r.company_name})}return l(f("TIMEOUT","Onboarding timed out"))}};var Dr=2e3,wr=60,re=class{constructor(r){this.apiClient=r}async init(){return this.apiClient.initCrossDeviceAuth()}async initRegistration(r){return this.apiClient.initCrossDeviceRegistration(r)}async waitForSession(r,t){for(let n=0;n<wr;n++){if(t?.aborted)return l(f("ABORT_ERROR","Operation aborted by user or timeout"));let s=await this.apiClient.getCrossDeviceStatus(r);if(!s.ok)return l(s.error);if(s.value.status==="completed")return!s.value.session_token||!s.value.user_id?l(f("UNKNOWN_ERROR","Missing data in completed session")):c({session_token:s.value.session_token,user_id:s.value.user_id});if(t?.aborted)return l(f("ABORT_ERROR","Operation aborted by user or timeout"));if(await new Promise(i=>{let a=setTimeout(()=>{i(null),t?.removeEventListener("abort",d)},Dr),d=()=>{clearTimeout(a),i(null)};t?.addEventListener("abort",d)}),t?.aborted)return l(f("ABORT_ERROR","Operation aborted by user or timeout"))}return l(f("TIMEOUT","Cross-device authentication timed out"))}async approve(r){let t=await this.apiClient.getCrossDeviceContext(r);if(!t.ok)return l(t.error);let n=t.value;return n.type==="registration"?this.executeRegistrationApproval(r,n):this.executeAuthApproval(r,n)}async executeRegistrationApproval(r,t){let n=w(t.options);if(!n.ok)return l(n.error);let s;try{s=await navigator.credentials.create(n.value)}catch(a){return l(_(a))}try{D(s,"create")}catch(a){return l(_(a))}let i;try{i=x(s)}catch(a){return l(_(a))}return this.apiClient.verifyCrossDeviceRegistration({session_id:r,credential:i})}async executeAuthApproval(r,t){let n=Ae(t.options);if(!n.ok)return l(n.error);let s;try{s=await navigator.credentials.get(n.value)}catch(a){return l(_(a))}try{D(s,"get")}catch(a){return l(_(a))}let i;try{i=Q(s)}catch(a){return l(_(a))}return this.apiClient.verifyCrossDeviceAuth({session_id:r,credential:i})}};var te=class{handlers;constructor(){this.handlers=new Map}on(r,t){let n=this.handlers.get(r);return n||(n=new Set,this.handlers.set(r,n)),n.add(t),()=>{this.off(r,t)}}off(r,t){let n=this.handlers.get(r);n&&(n.delete(t),n.size===0&&this.handlers.delete(r))}emit(r,t){let n=this.handlers.get(r);if(n)for(let s of n)try{s(t)}catch{}}removeAllListeners(){this.handlers.clear()}};async function Xe(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let s=h("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:s}),l(s)}if(!e.otp||typeof e.otp!="string"||e.otp.trim().length!==6){let s=h("otp","must be a 6-digit string");return t.emit("error",{type:"error",error:s}),l(s)}return B({operation:"register",eventEmitter:t,start:()=>r.verifyAccountRecoveryOtp(n,e.otp),createOptions:s=>w(s.challenge),invoke:async s=>navigator.credentials.create(s),finish:async(s,i)=>{let a=await r.completeAccountRecovery(s.recovery_session_id,x(i));return a.ok?c({success:!0,credentialId:a.value.credential_id,status:a.value.status,sessionToken:a.value.session_token,user:{userId:a.value.user.user_id,externalUserId:a.value.user.external_user_id,email:a.value.user.email,metadata:a.value.user.metadata}}):l(a.error)}})}var Ce="https://api.trymellonauth.com",$e="https://api.trymellonauth.com/v1/telemetry";var ze="trymellon_sandbox_session_token_v1";function Je(e){return{async send(r){let t=JSON.stringify(r);if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"){navigator.sendBeacon(e,t);return}typeof fetch<"u"&&await fetch(e,{method:"POST",body:t,headers:{"Content-Type":"application/json"},keepalive:!0})}}}function Oe(e,r){return{event:e,latencyMs:r,ok:!0}}var ne=class e{sandbox;sandboxToken;apiClient;eventEmitter;telemetrySender;crossDeviceManager;onboarding;static create(r){try{let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")return l(h("appId","must be a non-empty string"));if(!n||typeof n!="string"||n.trim()==="")return l(h("publishableKey","must be a non-empty string"));let s=r.apiBaseUrl??Ce;le(s,"apiBaseUrl");let i=r.timeoutMs??3e4;return M(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&M(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&M(r.retryDelayMs,"retryDelayMs",100,1e4),c(new e(r))}catch(t){return oe(t)?l(t):l(h("config",t.message))}}constructor(r){this.sandbox=r.sandbox===!0,this.sandboxToken=this.sandbox&&r.sandboxToken!=null&&r.sandboxToken!==""?r.sandboxToken:ze;let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")throw h("appId","must be a non-empty string");if(!n||typeof n!="string"||n.trim()==="")throw h("publishableKey","must be a non-empty string");let s=r.apiBaseUrl??Ce;le(s,"apiBaseUrl");let i=r.timeoutMs??3e4;M(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&M(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&M(r.retryDelayMs,"retryDelayMs",100,1e4);let a=r.maxRetries??3,d=r.retryDelayMs??1e3,R=new Z(i,a,d,r.logger),v=r.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),y={"X-App-Id":t.trim(),Authorization:`Bearer ${n.trim()}`,...v&&{Origin:v}};this.apiClient=new J(R,s,y),this.onboarding=new ee(this.apiClient),this.crossDeviceManager=new re(this.apiClient),this.eventEmitter=new te,r.enableTelemetry&&(this.telemetrySender=r.telemetrySender??Je(r.telemetryEndpoint??$e))}static isSupported(){return K()}async register(r){if(this.sandbox){let s=r.externalUserId??r.external_user_id??"sandbox";return Promise.resolve(c({success:!0,credentialId:"",status:"sandbox",sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:typeof s=="string"?s:"sandbox"}}))}let t=Date.now(),n=await Ge(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Oe("register",Date.now()-t)).catch(()=>{}),n}async authenticate(r){if(this.sandbox){let s=r.externalUserId??r.external_user_id??"sandbox";return Promise.resolve(c({authenticated:!0,sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:typeof s=="string"?s:"sandbox"}}))}let t=Date.now(),n=await Ye(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Oe("authenticate",Date.now()-t)).catch(()=>{}),n}async validateSession(r){return this.sandbox&&r===this.sandboxToken?Promise.resolve(c({valid:!0,user_id:"sandbox-user",external_user_id:"sandbox",tenant_id:"sandbox-tenant",app_id:"sandbox-app"})):this.apiClient.validateSession(r)}async getStatus(){return He()}on(r,t){return this.eventEmitter.on(r,t)}version(){return"1.6.2"}fallback={email:{start:async r=>this.apiClient.startEmailFallback(r),verify:async r=>this.apiClient.verifyEmailCode(r.userId,r.code)}};auth={crossDevice:{init:()=>this.crossDeviceManager.init(),initRegistration:r=>this.crossDeviceManager.initRegistration(r),waitForSession:(r,t)=>this.crossDeviceManager.waitForSession(r,t),approve:r=>this.crossDeviceManager.approve(r)},recoverAccount:async r=>Xe(r,this.apiClient,this.eventEmitter)}};var H=new j.InjectionToken("TRYMELLON_CONFIG"),ir,Se;ir=[(0,j.Injectable)({providedIn:"root"})];var N=class{config=(0,j.inject)(H,{optional:!0});_client=null;get client(){if(this._client==null){if(this.config==null)throw new Error("TryMellonService: provide TRYMELLON_CONFIG (e.g. via provideTryMellonConfig(config))");this._client=new ne(this.config)}return this._client}};Se=we(null),N=Fe(Se,0,"TryMellonService",ir,N),Ue(Se,1,N);function Fr(e){return{provide:H,useValue:e}}
3
3
  //# sourceMappingURL=angular.cjs.map