@trymellon/js 1.7.3 → 1.7.5

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 ar=Object.create;var w=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var lr=Object.getOwnPropertyNames;var ur=Object.prototype.hasOwnProperty;var De=(e,r)=>(r=Symbol[e])?r:Symbol.for("Symbol."+e),j=e=>{throw TypeError(e)};var cr=(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 pr=(e,r)=>{for(var t in r)w(e,t,{get:r[t],enumerable:!0})},dr=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of lr(r))!ur.call(e,s)&&s!==t&&w(e,s,{get:()=>r[s],enumerable:!(n=Me(r,s))||n.enumerable});return e};var gr=e=>dr(w({},"__esModule",{value:!0}),e);var we=e=>[,,,ar(e?.[De("metadata")]??null)],Ne=["class","method","getter","setter","accessor","field","value","get","set"],K=e=>e!==void 0&&typeof e!="function"?j("Function expected"):e,mr=(e,r,t,n,s)=>({kind:Ne[e],name:r,metadata:n,addInitializer:i=>t._?j("Already initialized"):s.push(K(i||null))}),fr=(e,r)=>cr(r,De("metadata"),e[3]),Ue=(e,r,t,n)=>{for(var s=0,i=e[r>>1],o=i&&i.length;s<o;s++)r&1?i[s].call(t):n=i[s].call(t,n);return n},Fe=(e,r,t,n,s,i)=>{var o,c,f,v,R,m=r&7,b=!!(r&8),_=!!(r&16),O=m>3?e.length+1:m?b?1:2:0,A=Ne[m+5],W=m>3&&(e[O-1]=[]),H=e[O]||(e[O]=[]),T=m&&(!_&&!b&&(s=s.prototype),m<5&&(m>3||!_)&&Me(m<4?s:{get[t](){return xe(this,i)},set[t](I){return Pe(this,i,I)}},t));m?_&&m<4&&Se(i,(m>2?"set ":m>1?"get ":"")+t):Se(s,t);for(var ne=n.length-1;ne>=0;ne--)v=mr(m,t,f={},e[3],H),m&&(v.static=b,v.private=_,R=v.access={has:_?I=>Rr(s,I):I=>t in I},m^3&&(R.get=_?I=>(m^1?xe:yr)(I,s,m^4?i:T.get):I=>I[t]),m>2&&(R.set=_?(I,se)=>Pe(I,s,se,m^4?i:T.set):(I,se)=>I[t]=se)),c=(0,n[ne])(m?m<4?_?i:T[A]:m>4?void 0:{get:T.get,set:T.set}:s,v),f._=1,m^4||c===void 0?K(c)&&(m>4?W.unshift(c):m?_?i=c:T[A]=c:s=c):typeof c!="object"||c===null?j("Object expected"):(K(o=c.get)&&(T.get=o),K(o=c.set)&&(T.set=o),K(o=c.init)&&W.unshift(o));return m||fr(e,s),T&&w(s,t,T),_?m^4?i:T:s};var ie=(e,r,t)=>r.has(e)||j("Cannot "+t),Rr=(e,r)=>Object(r)!==r?j('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 jr={};pr(jr,{TRYMELLON_CONFIG:()=>B,TryMellonService:()=>D,provideTryMellonConfig:()=>Kr});module.exports=gr(jr);var L=require("@angular/core");var d=e=>({ok:!0,value:e}),u=e=>({ok:!1,error:e});var G=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)}},vr={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 y(e,r,t){return new G(e,r??vr[e],t)}function oe(e){return e instanceof G||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===!0}function Le(){return y("NOT_SUPPORTED")}function h(e,r){return y("INVALID_ARGUMENT",`Invalid argument: ${e} - ${r}`,{field:e,reason:r})}function Ke(e){return y("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function ae(e){return y("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 x(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 hr={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function q(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(e){if(e instanceof DOMException){let r=e.name,t=e.message||"WebAuthn operation failed",n=hr[r]??"UNKNOWN_ERROR";return y(n,t,{originalError:e})}return e instanceof Error?y("UNKNOWN_ERROR",e.message,{originalError:e}):y("UNKNOWN_ERROR","An unknown error occurred",{originalError:e})}function g(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function l(e){return typeof e=="string"}function k(e){return typeof e=="number"&&Number.isFinite(e)}function Y(e){return typeof e=="boolean"}function N(e){return Array.isArray(e)}function a(e,r){return u(y("UNKNOWN_ERROR",e,{...r,originalData:r?.originalData}))}function p(e,r){return e[r]}function je(e,r){return!g(e)||!l(e.name)||!l(e.id)?a("Invalid API response: challenge.rp must have name and id strings",{originalData:r}):d(!0)}function qe(e,r){return!g(e)||!l(e.id)||!l(e.name)||!l(e.displayName)?a("Invalid API response: challenge.user must have id, name, displayName strings",{originalData:r}):d(!0)}function Ve(e,r){if(!N(e))return a("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:r});for(let t of e)if(!g(t)||t.type!=="public-key"||!k(t.alg))return a("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:r});return d(!0)}function ue(e,r){if(!g(e))return a("Invalid API response: user must be object",{field:"user",originalData:r});let t=p(e,"user_id"),n=p(e,"external_user_id");if(!l(t)||!l(n))return a("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&&!l(s)?a("Invalid API response: user.email must be string",{originalData:r}):i!==void 0&&(typeof i!="object"||i===null)?a("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 ce(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!l(r))return a("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!g(t))return a("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(!l(i))return a("Invalid API response: challenge.challenge must be string",{originalData:e});let o=Ve(p(t,"pubKeyCredParams"),e);if(!o.ok)return o;let c=t.timeout;if(c!==void 0&&!k(c))return a("Invalid API response: challenge.timeout must be number",{originalData:e});let f=t.excludeCredentials;if(f!==void 0){if(!N(f))return a("Invalid API response: excludeCredentials must be array",{originalData:e});for(let R of f)if(!g(R)||R.type!=="public-key"||!l(R.id))return a("Invalid API response: excludeCredentials items must have id and type",{originalData:e})}let v=t.authenticatorSelection;return v!==void 0&&!g(v)?a("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},...f!==void 0&&{excludeCredentials:f},...v!==void 0&&{authenticatorSelection:v}}})}function pe(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!l(r))return a("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!g(t))return a("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=p(t,"challenge"),s=p(t,"rpId"),i=t.allowCredentials;if(!l(n))return a("Invalid API response: challenge.challenge must be string",{originalData:e});if(!l(s))return a("Invalid API response: challenge.rpId must be string",{originalData:e});if(i!==void 0&&!N(i))return a("Invalid API response: allowCredentials must be array",{originalData:e});if(i){for(let f of i)if(!g(f)||f.type!=="public-key"||!l(f.id))return a("Invalid API response: allowCredentials items must have id and type",{originalData:e})}let o=t.timeout;if(o!==void 0&&!k(o))return a("Invalid API response: challenge.timeout must be number",{originalData:e});let c=t.userVerification;return c!==void 0&&!["required","preferred","discouraged"].includes(String(c))?a("Invalid API response: userVerification must be required|preferred|discouraged",{originalData:e}):d({session_id:r,challenge:{challenge:n,rpId:s,allowCredentials:i??[],...o!==void 0&&{timeout:o},...c!==void 0&&{userVerification:c}}})}function de(e){if(!g(e))return a("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(!l(r))return a("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!l(t))return a("Invalid API response: status must be string",{field:"status",originalData:e});if(!l(n))return a("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=ue(s,e);if(!i.ok)return a(i.error.message,{originalData:e});let o=e.redirect_url;return o!==void 0&&!l(o)?a("Invalid API response: redirect_url must be string",{originalData:e}):d({credential_id:r,status:t,session_token:n,user:i.value,...o!==void 0&&{redirect_url:o}})}function ge(e){if(!g(e))return a("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(!Y(r))return a("Invalid API response: authenticated must be boolean",{field:"authenticated",originalData:e});if(!l(t))return a("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=ue(n,e);if(!i.ok)return a(i.error.message,{originalData:e});if(s!==void 0&&!g(s))return a("Invalid API response: signals must be object",{originalData:e});let o=e.redirect_url;return o!==void 0&&!l(o)?a("Invalid API response: redirect_url must be string",{originalData:e}):d({authenticated:r,session_token:t,user:i.value,signals:s,...o!==void 0&&{redirect_url:o}})}function me(e){if(!g(e))return a("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 Y(r)?l(t)?l(n)?l(s)?l(i)?d({valid:r,user_id:t,external_user_id:n,tenant_id:s,app_id:i}):a("Invalid API response: app_id must be string",{field:"app_id",originalData:e}):a("Invalid API response: tenant_id must be string",{field:"tenant_id",originalData:e}):a("Invalid API response: external_user_id must be string",{field:"external_user_id",originalData:e}):a("Invalid API response: user_id must be string",{field:"user_id",originalData:e}):a("Invalid API response: valid must be boolean",{field:"valid",originalData:e})}function fe(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=e.session_token??e.sessionToken;if(!l(r))return a("Invalid API response: session_token/sessionToken must be string",{field:"session_token",originalData:e});let t=e.redirect_url;return t!==void 0&&!l(t)?a("Invalid API response: redirect_url must be string",{originalData:e}):d({sessionToken:r,...t!==void 0&&{redirectUrl:t}})}var Er=["pending_passkey","pending_data","completed"],br=["pending_data","completed"];function Re(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return l(r)?l(t)?k(n)?d({session_id:r,onboarding_url:t,expires_in:n}):a("Invalid API response: expires_in must be number",{field:"expires_in",originalData:e}):a("Invalid API response: onboarding_url must be string",{field:"onboarding_url",originalData:e}):a("Invalid API response: session_id must be string",{field:"session_id",originalData:e})}function ye(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"status"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return!l(r)||!Er.includes(r)?a("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):l(t)?k(n)?d({status:r,onboarding_url:t,expires_in:n}):a("Invalid API response: expires_in must be number",{originalData:e}):a("Invalid API response: onboarding_url must be string",{originalData:e})}function ve(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"onboarding_url");if(!l(r))return a("Invalid API response: session_id must be string",{field:"session_id",originalData:e});if(t!=="pending_passkey")return a("Invalid API response: status must be pending_passkey",{field:"status",originalData:e});if(!l(n))return a("Invalid API response: onboarding_url must be string",{originalData:e});let s=e.challenge,i;if(s!==void 0){let o=_r(s);if(!o.ok)return o;i=o.value}return d({session_id:r,status:"pending_passkey",onboarding_url:n,...i!==void 0&&{challenge:i}})}function _r(e){if(!g(e))return a("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)||!l(r.name)||!l(r.id))return a("Invalid API response: challenge.rp must have name and id",{originalData:e});if(!g(t)||!l(t.id)||!l(t.name)||!l(t.displayName))return a("Invalid API response: challenge.user must have id, name, displayName",{originalData:e});if(!l(n))return a("Invalid API response: challenge.challenge must be string",{originalData:e});if(!N(s))return a("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let i of s)if(!g(i)||i.type!=="public-key"||!k(i.alg))return a("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});return d({rp:r,user:t,challenge:n,pubKeyCredParams:s})}function he(e){if(!g(e))return a("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 l(r)?!l(t)||!br.includes(t)?a("Invalid API response: status must be pending_data|completed",{originalData:e}):l(n)?l(s)?d({session_id:r,status:t,user_id:n,tenant_id:s}):a("Invalid API response: tenant_id must be string",{originalData:e}):a("Invalid API response: user_id must be string",{originalData:e}):a("Invalid API response: session_id must be string",{originalData:e})}function Ee(e){if(!g(e))return a("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 l(r)?t!=="completed"?a("Invalid API response: status must be completed",{originalData:e}):!l(n)||!l(s)||!l(i)?a("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}):a("Invalid API response: session_id must be string",{originalData:e})}function Tr(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 Ir(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 a("Invalid API response: expected object",{originalData:e});let r="resultado"in e&&g(e.resultado)?e.resultado:e,t=r.session_id,n=r.qr_url,s=r.expires_at,i=r.polling_token;return!l(t)||!l(n)||!l(s)||!l(i)?a("Invalid API response: missing required fields",{originalData:e}):d({session_id:t,qr_url:n,expires_at:s,polling_token:i})}function be(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=e.status;return!l(r)||!["pending","authenticated","completed"].includes(r)?a("Invalid API response: invalid status",{originalData:e}):d({status:r,user_id:e.user_id,session_token:e.session_token})}function _e(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=e.type,t=r==="registration"?"registration":"auth",n=e.options;if(!g(n))return a("Invalid API response: options are required",{originalData:e});let s=200,i=Be(e.approval_context,s),o=Be(e.application_name,s);if(i===!1||o===!1)return a("Invalid API response: approval_context/application_name must be string max 200 chars",{originalData:e});let c={};return typeof i=="string"&&(c.approval_context=i),typeof o=="string"&&(c.application_name=o),t==="registration"?Tr(n)?d({type:"registration",options:n,...c}):a("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):Ir(n)?d({type:"auth",options:n,...c}):a("Invalid API response: auth options must have challenge and rpId",{originalData:e})}function Be(e,r){if(e!=null)return typeof e!="string"||e.length>r?!1:e}function Te(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"challenge"),t=p(e,"recovery_session_id");return g(r)?l(t)?d({challenge:r,recovery_session_id:t}):a("Invalid API response: recovery_session_id must be string",{field:"recovery_session_id",originalData:e}):a("Invalid API response: challenge must be object",{field:"challenge",originalData:e})}function Ie(e){if(!g(e))return a("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(!l(r))return a("Invalid API response: status must be string",{field:"status",originalData:e});if(!l(t))return a("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!l(s))return a("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!g(n))return a("Invalid API response: user must be object",{field:"user",originalData:e});let i=p(n,"user_id");if(!l(i))return a("Invalid API response: user.user_id must be string",{field:"user.user_id",originalData:e});let o=n;return d({status:r,session_token:t,credential_id:s,user:{user_id:i,external_user_id:l(o.external_user_id)?o.external_user_id:void 0,email:l(o.email)?o.email:void 0,metadata:g(o.metadata)?o.metadata:void 0}})}var z=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):u(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):u(i.error)}async startRegister(r){return this.post("/v1/passkeys/register/start",r,ce)}async startAuth(r){return this.post("/v1/passkeys/auth/start",r,pe)}async finishRegister(r){return this.post("/v1/passkeys/register/finish",r,de)}async finishAuthentication(r){return this.post("/v1/passkeys/auth/finish",r,ge)}async validateSession(r){return this.get("/v1/sessions/validate",me,{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):u(n.error)}async verifyEmailCode(r){let t={userId:r.userId,code:r.code};return r.successUrl&&(t.success_url=r.successUrl),this.post("/v1/fallback/email/verify",t,fe)}async startOnboarding(r){return this.post("/onboarding/start",r,Re)}async getOnboardingStatus(r){return this.get(`/onboarding/${r}/status`,ye)}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",{},$)}async initCrossDeviceRegistration(r){return this.post("/v1/auth/cross-device/init-registration",{external_user_id:r.externalUserId},$)}async getCrossDeviceStatus(r,t){let n={};return typeof t=="string"&&t.length>0&&(n["X-Polling-Token"]=t),this.get(`/v1/auth/cross-device/status/${r}`,be,Object.keys(n).length>0?n:void 0)}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?d(void 0):u(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):u(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 Ar(e){return typeof e=="object"&&e!==null&&e.ok===!0&&"resultado"in e}function Cr(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"}function Or(e,r){if(Cr(e))return{message:e.error.message,code:q(e.error.code)};let t=e,n=t?.error;if(typeof n=="object"&&n!==null&&"code"in n&&typeof n.code=="string")return{message:n.message??t?.message??r,code:q(n.code)};let s=t?.message??r,i=t?.error,o=typeof i=="string"?q(i):i===void 0?"NETWORK_FAILURE":q(String(i));return{message:s,code:o}}var kr=3e4;function Sr(){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,kr)}function xr(e,r){return e!=="GET"?!1:r>=500||r===429}var J=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=Sr(),i=new Headers(t.headers);i.set("X-Request-Id",s),this.logger&&this.logger.debug("request",{requestId:s,url:r,method:n});let o;for(let c=0;c<=this.maxRetries;c++)try{let f=new AbortController,v=setTimeout(()=>f.abort(),this.timeoutMs);try{let R=await fetch(r,{...t,headers:i,signal:f.signal});if(!R.ok){let O;try{O=await R.json()}catch{}let{message:A,code:W}=Or(O,R.statusText),H=y(W,A,{requestId:s,status:R.status,statusText:R.statusText,data:O});if(xr(n,R.status)&&c<this.maxRetries){o=H,clearTimeout(v),await new Promise(T=>setTimeout(T,We(c,this.retryDelayMs)));continue}return u(H)}if(R.status===204)return d(void 0);if(R.headers.get("content-length")==="0")return d(void 0);let b=await R.json();if(Ar(b))return d(b.resultado);let _=b;return typeof b=="object"&&b!==null&&_.ok===!0&&!("resultado"in _)?d(void 0):d(b)}finally{clearTimeout(v)}}catch(f){if(o=f,n==="GET"&&c<this.maxRetries)await new Promise(R=>setTimeout(R,We(c,this.retryDelayMs)));else break}return o instanceof Error&&o.name==="AbortError"?u(y("TIMEOUT","Request timed out",{requestId:s})):u(y("NETWORK_FAILURE",o instanceof Error?o.message:"Request failed",{requestId:s,cause:o}))}};function C(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 Pr(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 U(e){let r=Pr(e),t=new ArrayBuffer(r.length);return new Uint8Array(t).set(r),t}function He(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function S(e){if(!e.response)throw y("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!He(r))throw y("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("attestationObject"in r))throw y("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 Z(e){if(!e.response)throw y("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!He(r))throw y("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("authenticatorData"in r)||!("signature"in r))throw y("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 Mr(){try{return!F()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?!1:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function Ge(){let e=F(),r=await Mr();return{isPasskeySupported:e,platformAuthenticatorAvailable:r,recommendedFlow:e?"passkey":"fallback"}}function P(e,r="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw Ke(r)}async function V(e){let{operation:r,eventEmitter:t,start:n,createOptions:s,invoke:i,finish:o}=e;try{if(t.emit("start",{type:"start",operation:r}),!F()){let m=Le();return t.emit("error",{type:"error",error:m}),u(m)}let c=await n();if(!c.ok)return t.emit("error",{type:"error",error:c.error}),u(c.error);let f=s(c.value);if(!f.ok)return t.emit("error",{type:"error",error:f.error}),u(f.error);let v=await i(f.value);if(!v){let m=h("credential",`${r==="register"?"creation":"retrieval"} failed`);return t.emit("error",{type:"error",error:m}),u(m)}try{P(v)}catch(m){let b=E(m);return t.emit("error",{type:"error",error:b}),u(b)}let R=await o(c.value,v);return R.ok?(t.emit("success",{type:"success",operation:r}),d(R.value)):(t.emit("error",{type:"error",error:R.error}),u(R.error))}catch(c){let f=E(c);return t.emit("error",{type:"error",error:f}),u(f)}}function M(e,r){try{X(e.challenge,"challenge"),X(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(o=>({id:U(o.id),type:o.type,...o.transports&&{transports:o.transports}}))}};return d({publicKey:i})}catch(t){return u(E(t))}}function Ae(e,r){try{X(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 u(E(t))}}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}),u(s)}return V({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 o=await r.finishRegister({session_id:s.session_id,credential:S(i),...e.successUrl&&{success_url:e.successUrl}});return o.ok?d({success:!0,credentialId:o.value.credential_id,credential_id:o.value.credential_id,status:o.value.status,sessionToken:o.value.session_token,user:{userId:o.value.user.user_id,externalUserId:o.value.user.external_user_id,email:o.value.user.email,metadata:o.value.user.metadata},...o.value.redirect_url&&{redirectUrl:o.value.redirect_url}}):u(o.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 V({operation:"authenticate",eventEmitter:t,start:()=>r.startAuth(s?{external_user_id:n.trim()}:{}),createOptions:i=>Ae(i.challenge,e.mediation),invoke:async i=>{let o={...i,...e.signal&&{signal:e.signal}};return navigator.credentials.get(o)},finish:async(i,o)=>{let c=await r.finishAuthentication({session_id:i.session_id,credential:Z(o),...e.successUrl&&{success_url:e.successUrl}});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,...c.value.redirect_url&&{redirectUrl:c.value.redirect_url}}):u(c.error)}})}var Dr=2e3,wr=60,Q=class{constructor(r){this.apiClient=r}async startFlow(r){let t=await this.apiClient.startOnboarding({user_role:r.user_role});if(!t.ok)return u(t.error);let{session_id:n}=t.value;for(let s=0;s<wr;s++){await new Promise(f=>setTimeout(f,Dr));let i=await this.apiClient.getOnboardingStatus(n);if(!i.ok)return u(i.error);let o=i.value.status,c=i.value.onboarding_url;if(o==="pending_passkey"){let f=await this.apiClient.getOnboardingRegister(n);if(!f.ok)return u(f.error);let v=f.value;if(!v.challenge)return u(y("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:c}));let R=M(v.challenge);if(!R.ok)return u(R.error);let m;try{m=await navigator.credentials.create(R.value)}catch(A){return u(E(A))}try{P(m,"create")}catch(A){return u(E(A))}let b;try{b=S(m)}catch(A){return u(E(A))}let _=await this.apiClient.registerOnboardingPasskey(n,{credential:b,challenge:v.challenge.challenge});return _.ok?await this.apiClient.completeOnboarding(n,{company_name:r.company_name}):u(_.error)}if(o==="completed")return await this.apiClient.completeOnboarding(n,{company_name:r.company_name})}return u(y("TIMEOUT","Onboarding timed out"))}};var Nr=2e3,Ur=60,ee=class{constructor(r){this.apiClient=r}async init(){return this.apiClient.initCrossDeviceAuth()}async initRegistration(r){return this.apiClient.initCrossDeviceRegistration(r)}async waitForSession(r,t,n){for(let s=0;s<Ur;s++){if(t?.aborted)return u(y("ABORT_ERROR","Operation aborted by user or timeout"));let i=await this.apiClient.getCrossDeviceStatus(r,n);if(!i.ok)return u(i.error);if(i.value.status==="completed")return!i.value.session_token||!i.value.user_id?u(y("UNKNOWN_ERROR","Missing data in completed session")):d({session_token:i.value.session_token,user_id:i.value.user_id});if(t?.aborted)return u(y("ABORT_ERROR","Operation aborted by user or timeout"));if(await new Promise(o=>{let c=setTimeout(()=>{o(null),t?.removeEventListener("abort",f)},Nr),f=()=>{clearTimeout(c),o(null)};t?.addEventListener("abort",f)}),t?.aborted)return u(y("ABORT_ERROR","Operation aborted by user or timeout"))}return u(y("TIMEOUT","Cross-device authentication timed out"))}async approve(r){let t=await this.apiClient.getCrossDeviceContext(r);if(!t.ok)return u(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 u(n.error);let s;try{s=await navigator.credentials.create(n.value)}catch(o){return u(E(o))}try{P(s,"create")}catch(o){return u(E(o))}let i;try{i=S(s)}catch(o){return u(E(o))}return this.apiClient.verifyCrossDeviceRegistration({session_id:r,credential:i})}async executeAuthApproval(r,t){let n=Ae(t.options);if(!n.ok)return u(n.error);let s;try{s=await navigator.credentials.get(n.value)}catch(o){return u(E(o))}try{P(s,"get")}catch(o){return u(E(o))}let i;try{i=Z(s)}catch(o){return u(E(o))}return this.apiClient.verifyCrossDeviceAuth({session_id:r,credential:i})}};var re=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 $e(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}),u(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}),u(s)}return V({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 o=await r.completeAccountRecovery(s.recovery_session_id,S(i));return o.ok?d({success:!0,credentialId:o.value.credential_id,status:o.value.status,sessionToken:o.value.session_token,user:{userId:o.value.user.user_id,externalUserId:o.value.user.external_user_id,email:o.value.user.email,metadata:o.value.user.metadata}}):u(o.error)}})}var Ce="https://api.trymellonauth.com",ze="https://api.trymellonauth.com/v1/telemetry";var Je="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 Oe(e,r){return{event:e,latencyMs:r,ok:!0}}var te=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 u(h("appId","must be a non-empty string"));if(!n||typeof n!="string"||n.trim()==="")return u(h("publishableKey","must be a non-empty string"));let s=r.apiBaseUrl??Ce;le(s,"apiBaseUrl");let i=r.timeoutMs??3e4;return x(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&x(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&x(r.retryDelayMs,"retryDelayMs",100,1e4),d(new e(r))}catch(t){return oe(t)?u(t):u(h("config",t.message))}}constructor(r){this.sandbox=r.sandbox===!0,this.sandboxToken=this.sandbox&&r.sandboxToken!=null&&r.sandboxToken!==""?r.sandboxToken:Je;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;x(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&x(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&x(r.retryDelayMs,"retryDelayMs",100,1e4);let o=r.maxRetries??3,c=r.retryDelayMs??1e3,f=new J(i,o,c,r.logger),v=r.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),R={"X-App-Id":t.trim(),Authorization:`Bearer ${n.trim()}`,...v&&{Origin:v}};this.apiClient=new z(f,s,R),this.onboarding=new Q(this.apiClient),this.crossDeviceManager=new ee(this.apiClient),this.eventEmitter=new re,r.enableTelemetry&&(this.telemetrySender=r.telemetrySender??Ze(r.telemetryEndpoint??ze))}static isSupported(){return F()}sandboxAuthResult(r,t){let n=t.externalUserId??t.external_user_id??"sandbox",s=typeof n=="string"?n:"sandbox";return r==="register"?Promise.resolve(d({success:!0,credentialId:"",status:"sandbox",sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:s}})):Promise.resolve(d({authenticated:!0,sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:s}}))}async register(r){if(this.sandbox)return this.sandboxAuthResult("register",r);let t=Date.now(),n=await Xe(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)return this.sandboxAuthResult("authenticate",r);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(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 Ge()}on(r,t){return this.eventEmitter.on(r,t)}version(){return"1.7.3"}fallback={email:{start:async r=>this.apiClient.startEmailFallback(r),verify:async r=>{let t=await this.apiClient.verifyEmailCode({userId:r.userId,code:r.code,...r.successUrl&&{successUrl:r.successUrl}});return t.ok?d({sessionToken:t.value.sessionToken,...t.value.redirectUrl&&{redirectUrl:t.value.redirectUrl}}):t}}};auth={crossDevice:{init:()=>this.crossDeviceManager.init(),initRegistration:r=>this.crossDeviceManager.initRegistration(r),waitForSession:(r,t,n)=>this.crossDeviceManager.waitForSession(r,t,n),getContext:r=>this.apiClient.getCrossDeviceContext(r),approve:r=>this.crossDeviceManager.approve(r)},recoverAccount:async r=>$e(r,this.apiClient,this.eventEmitter)}};var B=new L.InjectionToken("TRYMELLON_CONFIG"),or,ke;or=[(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 te(this.config)}return this._client}};ke=we(null),D=Fe(ke,0,"TryMellonService",or,D),Ue(ke,1,D);function Kr(e){return{provide:B,useValue:e}}
2
+ "use strict";var ar=Object.create;var w=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var lr=Object.getOwnPropertyNames;var ur=Object.prototype.hasOwnProperty;var De=(e,r)=>(r=Symbol[e])?r:Symbol.for("Symbol."+e),j=e=>{throw TypeError(e)};var cr=(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 pr=(e,r)=>{for(var t in r)w(e,t,{get:r[t],enumerable:!0})},dr=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of lr(r))!ur.call(e,s)&&s!==t&&w(e,s,{get:()=>r[s],enumerable:!(n=Me(r,s))||n.enumerable});return e};var gr=e=>dr(w({},"__esModule",{value:!0}),e);var we=e=>[,,,ar(e?.[De("metadata")]??null)],Ne=["class","method","getter","setter","accessor","field","value","get","set"],K=e=>e!==void 0&&typeof e!="function"?j("Function expected"):e,mr=(e,r,t,n,s)=>({kind:Ne[e],name:r,metadata:n,addInitializer:i=>t._?j("Already initialized"):s.push(K(i||null))}),fr=(e,r)=>cr(r,De("metadata"),e[3]),Ue=(e,r,t,n)=>{for(var s=0,i=e[r>>1],o=i&&i.length;s<o;s++)r&1?i[s].call(t):n=i[s].call(t,n);return n},Fe=(e,r,t,n,s,i)=>{var o,c,f,v,R,m=r&7,b=!!(r&8),_=!!(r&16),O=m>3?e.length+1:m?b?1:2:0,A=Ne[m+5],W=m>3&&(e[O-1]=[]),H=e[O]||(e[O]=[]),T=m&&(!_&&!b&&(s=s.prototype),m<5&&(m>3||!_)&&Me(m<4?s:{get[t](){return xe(this,i)},set[t](I){return Pe(this,i,I)}},t));m?_&&m<4&&Se(i,(m>2?"set ":m>1?"get ":"")+t):Se(s,t);for(var ne=n.length-1;ne>=0;ne--)v=mr(m,t,f={},e[3],H),m&&(v.static=b,v.private=_,R=v.access={has:_?I=>Rr(s,I):I=>t in I},m^3&&(R.get=_?I=>(m^1?xe:yr)(I,s,m^4?i:T.get):I=>I[t]),m>2&&(R.set=_?(I,se)=>Pe(I,s,se,m^4?i:T.set):(I,se)=>I[t]=se)),c=(0,n[ne])(m?m<4?_?i:T[A]:m>4?void 0:{get:T.get,set:T.set}:s,v),f._=1,m^4||c===void 0?K(c)&&(m>4?W.unshift(c):m?_?i=c:T[A]=c:s=c):typeof c!="object"||c===null?j("Object expected"):(K(o=c.get)&&(T.get=o),K(o=c.set)&&(T.set=o),K(o=c.init)&&W.unshift(o));return m||fr(e,s),T&&w(s,t,T),_?m^4?i:T:s};var ie=(e,r,t)=>r.has(e)||j("Cannot "+t),Rr=(e,r)=>Object(r)!==r?j('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 jr={};pr(jr,{TRYMELLON_CONFIG:()=>B,TryMellonService:()=>D,provideTryMellonConfig:()=>Kr});module.exports=gr(jr);var L=require("@angular/core");var d=e=>({ok:!0,value:e}),u=e=>({ok:!1,error:e});var G=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)}},vr={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 y(e,r,t){return new G(e,r??vr[e],t)}function oe(e){return e instanceof G||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===!0}function Le(){return y("NOT_SUPPORTED")}function h(e,r){return y("INVALID_ARGUMENT",`Invalid argument: ${e} - ${r}`,{field:e,reason:r})}function Ke(e){return y("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function ae(e){return y("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 x(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 hr={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function q(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(e){if(e instanceof DOMException){let r=e.name,t=e.message||"WebAuthn operation failed",n=hr[r]??"UNKNOWN_ERROR";return y(n,t,{originalError:e})}return e instanceof Error?y("UNKNOWN_ERROR",e.message,{originalError:e}):y("UNKNOWN_ERROR","An unknown error occurred",{originalError:e})}function g(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function l(e){return typeof e=="string"}function k(e){return typeof e=="number"&&Number.isFinite(e)}function Y(e){return typeof e=="boolean"}function N(e){return Array.isArray(e)}function a(e,r){return u(y("UNKNOWN_ERROR",e,{...r,originalData:r?.originalData}))}function p(e,r){return e[r]}function je(e,r){return!g(e)||!l(e.name)||!l(e.id)?a("Invalid API response: challenge.rp must have name and id strings",{originalData:r}):d(!0)}function qe(e,r){return!g(e)||!l(e.id)||!l(e.name)||!l(e.displayName)?a("Invalid API response: challenge.user must have id, name, displayName strings",{originalData:r}):d(!0)}function Ve(e,r){if(!N(e))return a("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:r});for(let t of e)if(!g(t)||t.type!=="public-key"||!k(t.alg))return a("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:r});return d(!0)}function ue(e,r){if(!g(e))return a("Invalid API response: user must be object",{field:"user",originalData:r});let t=p(e,"user_id"),n=p(e,"external_user_id");if(!l(t)||!l(n))return a("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&&!l(s)?a("Invalid API response: user.email must be string",{originalData:r}):i!==void 0&&(typeof i!="object"||i===null)?a("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 ce(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!l(r))return a("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!g(t))return a("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(!l(i))return a("Invalid API response: challenge.challenge must be string",{originalData:e});let o=Ve(p(t,"pubKeyCredParams"),e);if(!o.ok)return o;let c=t.timeout;if(c!==void 0&&!k(c))return a("Invalid API response: challenge.timeout must be number",{originalData:e});let f=t.excludeCredentials;if(f!==void 0){if(!N(f))return a("Invalid API response: excludeCredentials must be array",{originalData:e});for(let R of f)if(!g(R)||R.type!=="public-key"||!l(R.id))return a("Invalid API response: excludeCredentials items must have id and type",{originalData:e})}let v=t.authenticatorSelection;return v!==void 0&&!g(v)?a("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},...f!==void 0&&{excludeCredentials:f},...v!==void 0&&{authenticatorSelection:v}}})}function pe(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!l(r))return a("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!g(t))return a("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=p(t,"challenge"),s=p(t,"rpId"),i=t.allowCredentials;if(!l(n))return a("Invalid API response: challenge.challenge must be string",{originalData:e});if(!l(s))return a("Invalid API response: challenge.rpId must be string",{originalData:e});if(i!==void 0&&!N(i))return a("Invalid API response: allowCredentials must be array",{originalData:e});if(i){for(let f of i)if(!g(f)||f.type!=="public-key"||!l(f.id))return a("Invalid API response: allowCredentials items must have id and type",{originalData:e})}let o=t.timeout;if(o!==void 0&&!k(o))return a("Invalid API response: challenge.timeout must be number",{originalData:e});let c=t.userVerification;return c!==void 0&&!["required","preferred","discouraged"].includes(String(c))?a("Invalid API response: userVerification must be required|preferred|discouraged",{originalData:e}):d({session_id:r,challenge:{challenge:n,rpId:s,allowCredentials:i??[],...o!==void 0&&{timeout:o},...c!==void 0&&{userVerification:c}}})}function de(e){if(!g(e))return a("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(!l(r))return a("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!l(t))return a("Invalid API response: status must be string",{field:"status",originalData:e});if(!l(n))return a("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=ue(s,e);if(!i.ok)return a(i.error.message,{originalData:e});let o=e.redirect_url;return o!==void 0&&!l(o)?a("Invalid API response: redirect_url must be string",{originalData:e}):d({credential_id:r,status:t,session_token:n,user:i.value,...o!==void 0&&{redirect_url:o}})}function ge(e){if(!g(e))return a("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(!Y(r))return a("Invalid API response: authenticated must be boolean",{field:"authenticated",originalData:e});if(!l(t))return a("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=ue(n,e);if(!i.ok)return a(i.error.message,{originalData:e});if(s!==void 0&&!g(s))return a("Invalid API response: signals must be object",{originalData:e});let o=e.redirect_url;return o!==void 0&&!l(o)?a("Invalid API response: redirect_url must be string",{originalData:e}):d({authenticated:r,session_token:t,user:i.value,signals:s,...o!==void 0&&{redirect_url:o}})}function me(e){if(!g(e))return a("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 Y(r)?l(t)?l(n)?l(s)?l(i)?d({valid:r,user_id:t,external_user_id:n,tenant_id:s,app_id:i}):a("Invalid API response: app_id must be string",{field:"app_id",originalData:e}):a("Invalid API response: tenant_id must be string",{field:"tenant_id",originalData:e}):a("Invalid API response: external_user_id must be string",{field:"external_user_id",originalData:e}):a("Invalid API response: user_id must be string",{field:"user_id",originalData:e}):a("Invalid API response: valid must be boolean",{field:"valid",originalData:e})}function fe(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=e.session_token??e.sessionToken;if(!l(r))return a("Invalid API response: session_token/sessionToken must be string",{field:"session_token",originalData:e});let t=e.redirect_url;return t!==void 0&&!l(t)?a("Invalid API response: redirect_url must be string",{originalData:e}):d({sessionToken:r,...t!==void 0&&{redirectUrl:t}})}var Er=["pending_passkey","pending_data","completed"],br=["pending_data","completed"];function Re(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return l(r)?l(t)?k(n)?d({session_id:r,onboarding_url:t,expires_in:n}):a("Invalid API response: expires_in must be number",{field:"expires_in",originalData:e}):a("Invalid API response: onboarding_url must be string",{field:"onboarding_url",originalData:e}):a("Invalid API response: session_id must be string",{field:"session_id",originalData:e})}function ye(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"status"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return!l(r)||!Er.includes(r)?a("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):l(t)?k(n)?d({status:r,onboarding_url:t,expires_in:n}):a("Invalid API response: expires_in must be number",{originalData:e}):a("Invalid API response: onboarding_url must be string",{originalData:e})}function ve(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"onboarding_url");if(!l(r))return a("Invalid API response: session_id must be string",{field:"session_id",originalData:e});if(t!=="pending_passkey")return a("Invalid API response: status must be pending_passkey",{field:"status",originalData:e});if(!l(n))return a("Invalid API response: onboarding_url must be string",{originalData:e});let s=e.challenge,i;if(s!==void 0){let o=_r(s);if(!o.ok)return o;i=o.value}return d({session_id:r,status:"pending_passkey",onboarding_url:n,...i!==void 0&&{challenge:i}})}function _r(e){if(!g(e))return a("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)||!l(r.name)||!l(r.id))return a("Invalid API response: challenge.rp must have name and id",{originalData:e});if(!g(t)||!l(t.id)||!l(t.name)||!l(t.displayName))return a("Invalid API response: challenge.user must have id, name, displayName",{originalData:e});if(!l(n))return a("Invalid API response: challenge.challenge must be string",{originalData:e});if(!N(s))return a("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let i of s)if(!g(i)||i.type!=="public-key"||!k(i.alg))return a("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});return d({rp:r,user:t,challenge:n,pubKeyCredParams:s})}function he(e){if(!g(e))return a("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 l(r)?!l(t)||!br.includes(t)?a("Invalid API response: status must be pending_data|completed",{originalData:e}):l(n)?l(s)?d({session_id:r,status:t,user_id:n,tenant_id:s}):a("Invalid API response: tenant_id must be string",{originalData:e}):a("Invalid API response: user_id must be string",{originalData:e}):a("Invalid API response: session_id must be string",{originalData:e})}function Ee(e){if(!g(e))return a("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 l(r)?t!=="completed"?a("Invalid API response: status must be completed",{originalData:e}):!l(n)||!l(s)||!l(i)?a("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}):a("Invalid API response: session_id must be string",{originalData:e})}function Tr(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 Ir(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 a("Invalid API response: expected object",{originalData:e});let r="resultado"in e&&g(e.resultado)?e.resultado:e,t=r.session_id,n=r.qr_url,s=r.expires_at,i=r.polling_token;return!l(t)||!l(n)||!l(s)||!l(i)?a("Invalid API response: missing required fields",{originalData:e}):d({session_id:t,qr_url:n,expires_at:s,polling_token:i})}function be(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=e.status;return!l(r)||!["pending","authenticated","completed"].includes(r)?a("Invalid API response: invalid status",{originalData:e}):d({status:r,user_id:e.user_id,session_token:e.session_token})}function _e(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=e.type,t=r==="registration"?"registration":"auth",n=e.options;if(!g(n))return a("Invalid API response: options are required",{originalData:e});let s=200,i=Be(e.approval_context,s),o=Be(e.application_name,s);if(i===!1||o===!1)return a("Invalid API response: approval_context/application_name must be string max 200 chars",{originalData:e});let c={};return typeof i=="string"&&(c.approval_context=i),typeof o=="string"&&(c.application_name=o),t==="registration"?Tr(n)?d({type:"registration",options:n,...c}):a("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):Ir(n)?d({type:"auth",options:n,...c}):a("Invalid API response: auth options must have challenge and rpId",{originalData:e})}function Be(e,r){if(e!=null)return typeof e!="string"||e.length>r?!1:e}function Te(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"challenge"),t=p(e,"recovery_session_id");return g(r)?l(t)?d({challenge:r,recovery_session_id:t}):a("Invalid API response: recovery_session_id must be string",{field:"recovery_session_id",originalData:e}):a("Invalid API response: challenge must be object",{field:"challenge",originalData:e})}function Ie(e){if(!g(e))return a("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(!l(r))return a("Invalid API response: status must be string",{field:"status",originalData:e});if(!l(t))return a("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!l(s))return a("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!g(n))return a("Invalid API response: user must be object",{field:"user",originalData:e});let i=p(n,"user_id");if(!l(i))return a("Invalid API response: user.user_id must be string",{field:"user.user_id",originalData:e});let o=n;return d({status:r,session_token:t,credential_id:s,user:{user_id:i,external_user_id:l(o.external_user_id)?o.external_user_id:void 0,email:l(o.email)?o.email:void 0,metadata:g(o.metadata)?o.metadata:void 0}})}var z=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):u(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):u(i.error)}async startRegister(r){return this.post("/v1/passkeys/register/start",r,ce)}async startAuth(r){return this.post("/v1/passkeys/auth/start",r,pe)}async finishRegister(r){return this.post("/v1/passkeys/register/finish",r,de)}async finishAuthentication(r){return this.post("/v1/passkeys/auth/finish",r,ge)}async validateSession(r){return this.get("/v1/sessions/validate",me,{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):u(n.error)}async verifyEmailCode(r){let t={userId:r.userId,code:r.code};return r.successUrl&&(t.success_url=r.successUrl),this.post("/v1/fallback/email/verify",t,fe)}async startOnboarding(r){return this.post("/v1/onboarding/start",r,Re)}async getOnboardingStatus(r){return this.get(`/v1/onboarding/${r}/status`,ye)}async getOnboardingRegister(r){return this.get(`/v1/onboarding/${r}/register`,ve)}async registerOnboardingPasskey(r,t){return this.post(`/v1/onboarding/${r}/register-passkey`,t,he)}async completeOnboarding(r,t){return this.post(`/v1/onboarding/${r}/complete`,t,Ee)}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,t){let n={};return typeof t=="string"&&t.length>0&&(n["X-Polling-Token"]=t),this.get(`/v1/auth/cross-device/status/${r}`,be,Object.keys(n).length>0?n:void 0)}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?d(void 0):u(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):u(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 Ar(e){return typeof e=="object"&&e!==null&&e.ok===!0&&"resultado"in e}function Cr(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"}function Or(e,r){if(Cr(e))return{message:e.error.message,code:q(e.error.code)};let t=e,n=t?.error;if(typeof n=="object"&&n!==null&&"code"in n&&typeof n.code=="string")return{message:n.message??t?.message??r,code:q(n.code)};let s=t?.message??r,i=t?.error,o=typeof i=="string"?q(i):i===void 0?"NETWORK_FAILURE":q(String(i));return{message:s,code:o}}var kr=3e4;function Sr(){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,kr)}function xr(e,r){return e!=="GET"?!1:r>=500||r===429}var J=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=Sr(),i=new Headers(t.headers);i.set("X-Request-Id",s),this.logger&&this.logger.debug("request",{requestId:s,url:r,method:n});let o;for(let c=0;c<=this.maxRetries;c++)try{let f=new AbortController,v=setTimeout(()=>f.abort(),this.timeoutMs);try{let R=await fetch(r,{...t,headers:i,signal:f.signal});if(!R.ok){let O;try{O=await R.json()}catch{}let{message:A,code:W}=Or(O,R.statusText),H=y(W,A,{requestId:s,status:R.status,statusText:R.statusText,data:O});if(xr(n,R.status)&&c<this.maxRetries){o=H,clearTimeout(v),await new Promise(T=>setTimeout(T,We(c,this.retryDelayMs)));continue}return u(H)}if(R.status===204)return d(void 0);if(R.headers.get("content-length")==="0")return d(void 0);let b=await R.json();if(Ar(b))return d(b.resultado);let _=b;return typeof b=="object"&&b!==null&&_.ok===!0&&!("resultado"in _)?d(void 0):d(b)}finally{clearTimeout(v)}}catch(f){if(o=f,n==="GET"&&c<this.maxRetries)await new Promise(R=>setTimeout(R,We(c,this.retryDelayMs)));else break}return o instanceof Error&&o.name==="AbortError"?u(y("TIMEOUT","Request timed out",{requestId:s})):u(y("NETWORK_FAILURE",o instanceof Error?o.message:"Request failed",{requestId:s,cause:o}))}};function C(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 Pr(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 U(e){let r=Pr(e),t=new ArrayBuffer(r.length);return new Uint8Array(t).set(r),t}function He(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function S(e){if(!e.response)throw y("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!He(r))throw y("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("attestationObject"in r))throw y("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 Z(e){if(!e.response)throw y("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!He(r))throw y("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("authenticatorData"in r)||!("signature"in r))throw y("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 Mr(){try{return!F()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?!1:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function Ge(){let e=F(),r=await Mr();return{isPasskeySupported:e,platformAuthenticatorAvailable:r,recommendedFlow:e?"passkey":"fallback"}}function P(e,r="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw Ke(r)}async function V(e){let{operation:r,eventEmitter:t,start:n,createOptions:s,invoke:i,finish:o}=e;try{if(t.emit("start",{type:"start",operation:r}),!F()){let m=Le();return t.emit("error",{type:"error",error:m}),u(m)}let c=await n();if(!c.ok)return t.emit("error",{type:"error",error:c.error}),u(c.error);let f=s(c.value);if(!f.ok)return t.emit("error",{type:"error",error:f.error}),u(f.error);let v=await i(f.value);if(!v){let m=h("credential",`${r==="register"?"creation":"retrieval"} failed`);return t.emit("error",{type:"error",error:m}),u(m)}try{P(v)}catch(m){let b=E(m);return t.emit("error",{type:"error",error:b}),u(b)}let R=await o(c.value,v);return R.ok?(t.emit("success",{type:"success",operation:r}),d(R.value)):(t.emit("error",{type:"error",error:R.error}),u(R.error))}catch(c){let f=E(c);return t.emit("error",{type:"error",error:f}),u(f)}}function M(e,r){try{X(e.challenge,"challenge"),X(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(o=>({id:U(o.id),type:o.type,...o.transports&&{transports:o.transports}}))}};return d({publicKey:i})}catch(t){return u(E(t))}}function Ae(e,r){try{X(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 u(E(t))}}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}),u(s)}return V({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 o=await r.finishRegister({session_id:s.session_id,credential:S(i),...e.successUrl&&{success_url:e.successUrl}});return o.ok?d({success:!0,credentialId:o.value.credential_id,credential_id:o.value.credential_id,status:o.value.status,sessionToken:o.value.session_token,user:{userId:o.value.user.user_id,externalUserId:o.value.user.external_user_id,email:o.value.user.email,metadata:o.value.user.metadata},...o.value.redirect_url&&{redirectUrl:o.value.redirect_url}}):u(o.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 V({operation:"authenticate",eventEmitter:t,start:()=>r.startAuth(s?{external_user_id:n.trim()}:{}),createOptions:i=>Ae(i.challenge,e.mediation),invoke:async i=>{let o={...i,...e.signal&&{signal:e.signal}};return navigator.credentials.get(o)},finish:async(i,o)=>{let c=await r.finishAuthentication({session_id:i.session_id,credential:Z(o),...e.successUrl&&{success_url:e.successUrl}});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,...c.value.redirect_url&&{redirectUrl:c.value.redirect_url}}):u(c.error)}})}var Dr=2e3,wr=60,Q=class{constructor(r){this.apiClient=r}async startFlow(r){let t=await this.apiClient.startOnboarding({user_role:r.user_role});if(!t.ok)return u(t.error);let{session_id:n}=t.value;for(let s=0;s<wr;s++){await new Promise(f=>setTimeout(f,Dr));let i=await this.apiClient.getOnboardingStatus(n);if(!i.ok)return u(i.error);let o=i.value.status,c=i.value.onboarding_url;if(o==="pending_passkey"){let f=await this.apiClient.getOnboardingRegister(n);if(!f.ok)return u(f.error);let v=f.value;if(!v.challenge)return u(y("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:c}));let R=M(v.challenge);if(!R.ok)return u(R.error);let m;try{m=await navigator.credentials.create(R.value)}catch(A){return u(E(A))}try{P(m,"create")}catch(A){return u(E(A))}let b;try{b=S(m)}catch(A){return u(E(A))}let _=await this.apiClient.registerOnboardingPasskey(n,{credential:b,challenge:v.challenge.challenge});return _.ok?await this.apiClient.completeOnboarding(n,{company_name:r.company_name}):u(_.error)}if(o==="completed")return await this.apiClient.completeOnboarding(n,{company_name:r.company_name})}return u(y("TIMEOUT","Onboarding timed out"))}};var Nr=2e3,Ur=60,ee=class{constructor(r){this.apiClient=r}async init(){return this.apiClient.initCrossDeviceAuth()}async initRegistration(r){return this.apiClient.initCrossDeviceRegistration(r)}async waitForSession(r,t,n){for(let s=0;s<Ur;s++){if(t?.aborted)return u(y("ABORT_ERROR","Operation aborted by user or timeout"));let i=await this.apiClient.getCrossDeviceStatus(r,n);if(!i.ok)return u(i.error);if(i.value.status==="completed")return!i.value.session_token||!i.value.user_id?u(y("UNKNOWN_ERROR","Missing data in completed session")):d({session_token:i.value.session_token,user_id:i.value.user_id});if(t?.aborted)return u(y("ABORT_ERROR","Operation aborted by user or timeout"));if(await new Promise(o=>{let c=setTimeout(()=>{o(null),t?.removeEventListener("abort",f)},Nr),f=()=>{clearTimeout(c),o(null)};t?.addEventListener("abort",f)}),t?.aborted)return u(y("ABORT_ERROR","Operation aborted by user or timeout"))}return u(y("TIMEOUT","Cross-device authentication timed out"))}async approve(r){let t=await this.apiClient.getCrossDeviceContext(r);if(!t.ok)return u(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 u(n.error);let s;try{s=await navigator.credentials.create(n.value)}catch(o){return u(E(o))}try{P(s,"create")}catch(o){return u(E(o))}let i;try{i=S(s)}catch(o){return u(E(o))}return this.apiClient.verifyCrossDeviceRegistration({session_id:r,credential:i})}async executeAuthApproval(r,t){let n=Ae(t.options);if(!n.ok)return u(n.error);let s;try{s=await navigator.credentials.get(n.value)}catch(o){return u(E(o))}try{P(s,"get")}catch(o){return u(E(o))}let i;try{i=Z(s)}catch(o){return u(E(o))}return this.apiClient.verifyCrossDeviceAuth({session_id:r,credential:i})}};var re=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 $e(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}),u(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}),u(s)}return V({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 o=await r.completeAccountRecovery(s.recovery_session_id,S(i));return o.ok?d({success:!0,credentialId:o.value.credential_id,status:o.value.status,sessionToken:o.value.session_token,user:{userId:o.value.user.user_id,externalUserId:o.value.user.external_user_id,email:o.value.user.email,metadata:o.value.user.metadata}}):u(o.error)}})}var Ce="https://api.trymellonauth.com",ze="https://api.trymellonauth.com/v1/telemetry";var Je="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 Oe(e,r){return{event:e,latencyMs:r,ok:!0}}var te=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 u(h("appId","must be a non-empty string"));if(!n||typeof n!="string"||n.trim()==="")return u(h("publishableKey","must be a non-empty string"));let s=r.apiBaseUrl??Ce;le(s,"apiBaseUrl");let i=r.timeoutMs??3e4;return x(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&x(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&x(r.retryDelayMs,"retryDelayMs",100,1e4),d(new e(r))}catch(t){return oe(t)?u(t):u(h("config",t.message))}}constructor(r){this.sandbox=r.sandbox===!0,this.sandboxToken=this.sandbox&&r.sandboxToken!=null&&r.sandboxToken!==""?r.sandboxToken:Je;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;x(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&x(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&x(r.retryDelayMs,"retryDelayMs",100,1e4);let o=r.maxRetries??3,c=r.retryDelayMs??1e3,f=new J(i,o,c,r.logger),v=r.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),R={"X-App-Id":t.trim(),Authorization:`Bearer ${n.trim()}`,...v&&{Origin:v}};this.apiClient=new z(f,s,R),this.onboarding=new Q(this.apiClient),this.crossDeviceManager=new ee(this.apiClient),this.eventEmitter=new re,r.enableTelemetry&&(this.telemetrySender=r.telemetrySender??Ze(r.telemetryEndpoint??ze))}static isSupported(){return F()}sandboxAuthResult(r,t){let n=t.externalUserId??t.external_user_id??"sandbox",s=typeof n=="string"?n:"sandbox";return r==="register"?Promise.resolve(d({success:!0,credentialId:"",status:"sandbox",sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:s}})):Promise.resolve(d({authenticated:!0,sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:s}}))}async register(r){if(this.sandbox)return this.sandboxAuthResult("register",r);let t=Date.now(),n=await Xe(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)return this.sandboxAuthResult("authenticate",r);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(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 Ge()}on(r,t){return this.eventEmitter.on(r,t)}version(){return"1.7.5"}fallback={email:{start:async r=>this.apiClient.startEmailFallback(r),verify:async r=>{let t=await this.apiClient.verifyEmailCode({userId:r.userId,code:r.code,...r.successUrl&&{successUrl:r.successUrl}});return t.ok?d({sessionToken:t.value.sessionToken,...t.value.redirectUrl&&{redirectUrl:t.value.redirectUrl}}):t}}};auth={crossDevice:{init:()=>this.crossDeviceManager.init(),initRegistration:r=>this.crossDeviceManager.initRegistration(r),waitForSession:(r,t,n)=>this.crossDeviceManager.waitForSession(r,t,n),getContext:r=>this.apiClient.getCrossDeviceContext(r),approve:r=>this.crossDeviceManager.approve(r)},recoverAccount:async r=>$e(r,this.apiClient,this.eventEmitter)}};var B=new L.InjectionToken("TRYMELLON_CONFIG"),or,ke;or=[(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 te(this.config)}return this._client}};ke=we(null),D=Fe(ke,0,"TryMellonService",or,D),Ue(ke,1,D);function Kr(e){return{provide:B,useValue:e}}
3
3
  //# sourceMappingURL=angular.cjs.map