@trymellon/js 1.6.2 → 1.7.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 +1 -1
- package/dist/angular.cjs.map +1 -1
- package/dist/angular.d.cts +1 -1
- package/dist/angular.d.ts +1 -1
- package/dist/angular.js +1 -1
- package/dist/angular.js.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.global.js +2 -2
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/react.d.cts +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/{trymellon-BkIVfr7x.d.cts → trymellon-NWZ51vgt.d.cts} +10 -0
- package/dist/{trymellon-BkIVfr7x.d.ts → trymellon-NWZ51vgt.d.ts} +10 -0
- package/dist/vue.d.cts +1 -1
- package/dist/vue.d.ts +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var c=e=>({ok:true,value:e}),l=e=>({ok:false,error:e});var U=class e extends Error{code;details;isTryMellonError=true;constructor(r,t,n){super(t),this.name="TryMellonError",this.code=r,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,e);}},Ve={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 m(e,r,t){return new U(e,r??Ve[e],t)}function q(e){return e instanceof U||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===true}function J(){return m("NOT_SUPPORTED")}function We(){return m("USER_CANCELLED")}function Be(e){return m("NETWORK_FAILURE",void 0,{cause:e?.message,originalError:e})}function He(){return m("TIMEOUT")}function f(e,r){return m("INVALID_ARGUMENT",`Invalid argument: ${e} - ${r}`,{field:e,reason:r})}function Te(e){return m("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function Z(e){return m("NOT_SUPPORTED",`No base64 ${e==="encode"?"encoding":"decoding"} available`,{type:e})}function Q(e,r){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw f(r,"must use http or https protocol")}catch(t){throw q(t)?t:f(r,"must be a valid URL")}}function O(e,r,t,n){if(!Number.isFinite(e))throw f(r,"must be a finite number");if(e<t||e>n)throw f(r,`must be between ${t} and ${n}`)}function V(e,r){if(typeof e!="string"||e.length===0)throw f(r,"must be a non-empty string");if(!/^[A-Za-z0-9_-]+$/.test(e))throw f(r,"must be a valid base64url string")}var $e={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function F(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 h(e){if(e instanceof DOMException){let r=e.name,t=e.message||"WebAuthn operation failed",n=$e[r]??"UNKNOWN_ERROR";return m(n,t,{originalError:e})}return e instanceof Error?m("UNKNOWN_ERROR",e.message,{originalError:e}):m("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 A(e){return typeof e=="number"&&Number.isFinite(e)}function W(e){return typeof e=="boolean"}function M(e){return Array.isArray(e)}function i(e,r){return l(m("UNKNOWN_ERROR",e,{...r,originalData:r?.originalData}))}function p(e,r){return e[r]}function Ae(e,r){return !g(e)||!u(e.name)||!u(e.id)?i("Invalid API response: challenge.rp must have name and id strings",{originalData:r}):c(true)}function Ie(e,r){return !g(e)||!u(e.id)||!u(e.name)||!u(e.displayName)?i("Invalid API response: challenge.user must have id, name, displayName strings",{originalData:r}):c(true)}function Ce(e,r){if(!M(e))return i("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:r});for(let t of e)if(!g(t)||t.type!=="public-key"||!A(t.alg))return i("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:r});return c(true)}function ee(e,r){if(!g(e))return i("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 i("Invalid API response: user must have user_id and external_user_id strings",{originalData:r});let s=e.email,o=e.metadata;return s!==void 0&&!u(s)?i("Invalid API response: user.email must be string",{originalData:r}):o!==void 0&&(typeof o!="object"||o===null)?i("Invalid API response: user.metadata must be object",{originalData:r}):c({user_id:t,external_user_id:n,...s!==void 0&&{email:s},...o!==void 0&&{metadata:o}})}function re(e){if(!g(e))return i("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!u(r))return i("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!g(t))return i("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=Ae(p(t,"rp"),e);if(!n.ok)return n;let s=Ie(p(t,"user"),e);if(!s.ok)return s;let o=p(t,"challenge");if(!u(o))return i("Invalid API response: challenge.challenge must be string",{originalData:e});let a=Ce(p(t,"pubKeyCredParams"),e);if(!a.ok)return a;let d=t.timeout;if(d!==void 0&&!A(d))return i("Invalid API response: challenge.timeout must be number",{originalData:e});let R=t.excludeCredentials;if(R!==void 0){if(!M(R))return i("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 i("Invalid API response: excludeCredentials items must have id and type",{originalData:e})}let v=t.authenticatorSelection;return v!==void 0&&!g(v)?i("Invalid API response: authenticatorSelection must be object",{originalData:e}):c({session_id:r,challenge:{rp:t.rp,user:t.user,challenge:o,pubKeyCredParams:t.pubKeyCredParams,...d!==void 0&&{timeout:d},...R!==void 0&&{excludeCredentials:R},...v!==void 0&&{authenticatorSelection:v}}})}function te(e){if(!g(e))return i("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!u(r))return i("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!g(t))return i("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=p(t,"challenge"),s=p(t,"rpId"),o=t.allowCredentials;if(!u(n))return i("Invalid API response: challenge.challenge must be string",{originalData:e});if(!u(s))return i("Invalid API response: challenge.rpId must be string",{originalData:e});if(o!==void 0&&!M(o))return i("Invalid API response: allowCredentials must be array",{originalData:e});if(o){for(let R of o)if(!g(R)||R.type!=="public-key"||!u(R.id))return i("Invalid API response: allowCredentials items must have id and type",{originalData:e})}let a=t.timeout;if(a!==void 0&&!A(a))return i("Invalid API response: challenge.timeout must be number",{originalData:e});let d=t.userVerification;return d!==void 0&&!["required","preferred","discouraged"].includes(String(d))?i("Invalid API response: userVerification must be required|preferred|discouraged",{originalData:e}):c({session_id:r,challenge:{challenge:n,rpId:s,allowCredentials:o??[],...a!==void 0&&{timeout:a},...d!==void 0&&{userVerification:d}}})}function ne(e){if(!g(e))return i("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 i("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!u(t))return i("Invalid API response: status must be string",{field:"status",originalData:e});if(!u(n))return i("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let o=ee(s,e);return o.ok?c({credential_id:r,status:t,session_token:n,user:o.value}):i(o.error.message,{originalData:e})}function se(e){if(!g(e))return i("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(!W(r))return i("Invalid API response: authenticated must be boolean",{field:"authenticated",originalData:e});if(!u(t))return i("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let o=ee(n,e);return o.ok?s!==void 0&&!g(s)?i("Invalid API response: signals must be object",{originalData:e}):c({authenticated:r,session_token:t,user:o.value,signals:s}):i(o.error.message,{originalData:e})}function ie(e){if(!g(e))return i("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"),o=p(e,"app_id");return W(r)?u(t)?u(n)?u(s)?u(o)?c({valid:r,user_id:t,external_user_id:n,tenant_id:s,app_id:o}):i("Invalid API response: app_id must be string",{field:"app_id",originalData:e}):i("Invalid API response: tenant_id must be string",{field:"tenant_id",originalData:e}):i("Invalid API response: external_user_id must be string",{field:"external_user_id",originalData:e}):i("Invalid API response: user_id must be string",{field:"user_id",originalData:e}):i("Invalid API response: valid must be boolean",{field:"valid",originalData:e})}function oe(e){if(!g(e))return i("Invalid API response: expected object",{originalData:e});let r=p(e,"sessionToken");return u(r)?c({sessionToken:r}):i("Invalid API response: sessionToken must be string",{field:"sessionToken",originalData:e})}var Xe=["pending_passkey","pending_data","completed"],ze=["pending_data","completed"];function ae(e){if(!g(e))return i("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)?A(n)?c({session_id:r,onboarding_url:t,expires_in:n}):i("Invalid API response: expires_in must be number",{field:"expires_in",originalData:e}):i("Invalid API response: onboarding_url must be string",{field:"onboarding_url",originalData:e}):i("Invalid API response: session_id must be string",{field:"session_id",originalData:e})}function le(e){if(!g(e))return i("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)||!Xe.includes(r)?i("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):u(t)?A(n)?c({status:r,onboarding_url:t,expires_in:n}):i("Invalid API response: expires_in must be number",{originalData:e}):i("Invalid API response: onboarding_url must be string",{originalData:e})}function ue(e){if(!g(e))return i("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 i("Invalid API response: session_id must be string",{field:"session_id",originalData:e});if(t!=="pending_passkey")return i("Invalid API response: status must be pending_passkey",{field:"status",originalData:e});if(!u(n))return i("Invalid API response: onboarding_url must be string",{originalData:e});let s=e.challenge,o;if(s!==void 0){let a=Ge(s);if(!a.ok)return a;o=a.value;}return c({session_id:r,status:"pending_passkey",onboarding_url:n,...o!==void 0&&{challenge:o}})}function Ge(e){if(!g(e))return i("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 i("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 i("Invalid API response: challenge.user must have id, name, displayName",{originalData:e});if(!u(n))return i("Invalid API response: challenge.challenge must be string",{originalData:e});if(!M(s))return i("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let o of s)if(!g(o)||o.type!=="public-key"||!A(o.alg))return i("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});return c({rp:r,user:t,challenge:n,pubKeyCredParams:s})}function pe(e){if(!g(e))return i("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)||!ze.includes(t)?i("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}):i("Invalid API response: tenant_id must be string",{originalData:e}):i("Invalid API response: user_id must be string",{originalData:e}):i("Invalid API response: session_id must be string",{originalData:e})}function ce(e){if(!g(e))return i("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"),o=p(e,"session_token");return u(r)?t!=="completed"?i("Invalid API response: status must be completed",{originalData:e}):!u(n)||!u(s)||!u(o)?i("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:o}):i("Invalid API response: session_id must be string",{originalData:e})}function Ye(e){if(!e||typeof e!="object")return false;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 Je(e){if(!e||typeof e!="object")return false;let r=e;return typeof r.challenge=="string"&&typeof r.rpId=="string"}function B(e){if(!g(e))return i("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;return !u(t)||!u(n)||!u(s)?i("Invalid API response: missing required fields",{originalData:e}):c({session_id:t,qr_url:n,expires_at:s})}function de(e){if(!g(e))return i("Invalid API response: expected object",{originalData:e});let r=e.status;return !u(r)||!["pending","authenticated","completed"].includes(r)?i("Invalid API response: invalid status",{originalData:e}):c({status:r,user_id:e.user_id,session_token:e.session_token})}function ge(e){if(!g(e))return i("Invalid API response: expected object",{originalData:e});let r=e.type,t=r==="registration"?"registration":"auth",n=e.options;return g(n)?t==="registration"?Ye(n)?c({type:"registration",options:n}):i("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):Je(n)?c({type:"auth",options:n}):i("Invalid API response: auth options must have challenge and rpId",{originalData:e}):i("Invalid API response: options are required",{originalData:e})}function me(e){if(!g(e))return i("Invalid API response: expected object",{originalData:e});let r=p(e,"challenge"),t=p(e,"recovery_session_id");return g(r)?u(t)?c({challenge:r,recovery_session_id:t}):i("Invalid API response: recovery_session_id must be string",{field:"recovery_session_id",originalData:e}):i("Invalid API response: challenge must be object",{field:"challenge",originalData:e})}function Re(e){if(!g(e))return i("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 i("Invalid API response: status must be string",{field:"status",originalData:e});if(!u(t))return i("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!u(s))return i("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!g(n))return i("Invalid API response: user must be object",{field:"user",originalData:e});let o=p(n,"user_id");if(!u(o))return i("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:o,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 H=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}`,o=await this.httpClient.post(s,t,this.mergeHeaders());return o.ok?n(o.value):l(o.error)}async get(r,t,n){let s=`${this.baseUrl}${r}`,o=await this.httpClient.get(s,this.mergeHeaders(n));return o.ok?t(o.value):l(o.error)}async startRegister(r){return this.post("/v1/passkeys/register/start",r,re)}async startAuth(r){return this.post("/v1/passkeys/auth/start",r,te)}async finishRegister(r){return this.post("/v1/passkeys/register/finish",r,ne)}async finishAuthentication(r){return this.post("/v1/passkeys/auth/finish",r,se)}async validateSession(r){return this.get("/v1/sessions/validate",ie,{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},oe)}async startOnboarding(r){return this.post("/onboarding/start",r,ae)}async getOnboardingStatus(r){return this.get(`/onboarding/${r}/status`,le)}async getOnboardingRegister(r){return this.get(`/onboarding/${r}/register`,ue)}async registerOnboardingPasskey(r,t){return this.post(`/onboarding/${r}/register-passkey`,t,pe)}async completeOnboarding(r,t){return this.post(`/onboarding/${r}/complete`,t,ce)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},B)}async initCrossDeviceRegistration(r){return this.post("/v1/auth/cross-device/init-registration",{external_user_id:r.externalUserId},B)}async getCrossDeviceStatus(r){return this.get(`/v1/auth/cross-device/status/${r}`,de)}async getCrossDeviceContext(r){return this.get(`/v1/auth/cross-device/context/${r}`,ge)}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},me)}async completeAccountRecovery(r,t){return this.post("/v1/users/recovery/complete",{recovery_session_id:r,credential:t},Re)}};function Ze(e){return typeof e=="object"&&e!==null&&e.ok===true&&"resultado"in e}function Qe(e){if(typeof e!="object"||e===null)return false;let r=e;if(r.ok!==false||!r.error||typeof r.error!="object")return false;let t=r.error;return typeof t.code=="string"&&typeof t.message=="string"}var er=3e4;function rr(){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 Oe(e,r){let t=r*Math.pow(2,e);return Math.min(t,er)}function tr(e,r){return e!=="GET"?false:r>=500||r===429}var $=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=rr(),o=new Headers(t.headers);o.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:o,signal:R.signal});if(!y.ok){let C;try{C=await y.json();}catch{}let _,K;if(Qe(C))_=C.error.message,K=F(C.error.code);else {let x=C,P=x?.error;if(typeof P=="object"&&P!==null&&"code"in P&&typeof P.code=="string")_=P.message??x?.message??y.statusText,K=F(P.code);else {_=x?.message??y.statusText;let j=x?.error;K=typeof j=="string"?F(j):j===void 0?"NETWORK_FAILURE":F(String(j));}}let _e=m(K,_,{requestId:s,status:y.status,statusText:y.statusText,data:C});if(tr(n,y.status)&&d<this.maxRetries){a=_e,await new Promise(x=>setTimeout(x,Oe(d,this.retryDelayMs)));continue}return l(_e)}if(y.status===204)return c(void 0);if(y.headers.get("content-length")==="0")return c(void 0);let b=await y.json();if(Ze(b))return c(b.resultado);let N=b;return typeof b=="object"&&b!==null&&N.ok===true&&!("resultado"in N)?c(void 0):c(b)}finally{clearTimeout(v);}}catch(R){if(a=R,n==="GET"&&d<this.maxRetries)await new Promise(y=>setTimeout(y,Oe(d,this.retryDelayMs)));else break}return a instanceof Error&&a.name==="AbortError"?l(m("TIMEOUT","Request timed out",{requestId:s})):l(m("NETWORK_FAILURE",a instanceof Error?a.message:"Request failed",{requestId:s,cause:a}))}};function T(e){let r=new Uint8Array(e),t=Array.from(r,s=>String.fromCharCode(s)).join("");if(typeof globalThis.btoa>"u")throw Z("encode");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function nr(e){if(typeof globalThis.atob>"u")throw Z("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,o=>o.charCodeAt(0))}function D(e){let r=nr(e),t=new ArrayBuffer(r.length);return new Uint8Array(t).set(r),t}function Se(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function I(e){if(!e.response)throw m("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!Se(r))throw m("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("attestationObject"in r))throw m("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:T(e.rawId),response:{clientDataJSON:T(t),attestationObject:T(n)},type:"public-key"}}function X(e){if(!e.response)throw m("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!Se(r))throw m("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("authenticatorData"in r)||!("signature"in r))throw m("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,o=r.userHandle;return {id:e.id,rawId:T(e.rawId),response:{authenticatorData:T(n),clientDataJSON:T(t),signature:T(s),...o&&{userHandle:T(o)}},type:"public-key"}}function w(){try{return !(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return false}}async function sr(){try{return !w()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?false:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return false}}async function ke(){let e=w(),r=await sr();return {isPasskeySupported:e,platformAuthenticatorAvailable:r,recommendedFlow:e?"passkey":"fallback"}}function S(e,r="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw Te(r)}async function L(e){let{operation:r,eventEmitter:t,start:n,createOptions:s,invoke:o,finish:a}=e;try{if(t.emit("start",{type:"start",operation:r}),!w()){let E=J();return t.emit("error",{type:"error",error:E}),l(E)}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 o(R.value);if(!v){let E=f("credential",`${r==="register"?"creation":"retrieval"} failed`);return t.emit("error",{type:"error",error:E}),l(E)}try{S(v);}catch(E){let b=h(E);return t.emit("error",{type:"error",error:b}),l(b)}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=h(d);return t.emit("error",{type:"error",error:R}),l(R)}}function k(e,r){try{V(e.challenge,"challenge"),V(e.user.id,"user.id");let t=D(e.challenge),n=D(e.user.id),s={userVerification:"preferred"};e.authenticatorSelection&&(s={...e.authenticatorSelection}),r&&(s={...s,authenticatorAttachment:r});let o={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:D(a.id),type:a.type,...a.transports&&{transports:a.transports}}))}};return c({publicKey:o})}catch(t){return l(h(t))}}function ye(e,r){try{V(e.challenge,"challenge");let t=D(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:D(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...r!==void 0&&{mediation:r}})}catch(t){return l(h(t))}}async function xe(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let s=f("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:s}),l(s)}return L({operation:"register",eventEmitter:t,start:()=>r.startRegister({external_user_id:n}),createOptions:s=>k(s.challenge,e.authenticatorType),invoke:async s=>{let o={...s,...e.signal&&{signal:e.signal}};return navigator.credentials.create(o)},finish:async(s,o)=>{let a=await r.finishRegister({session_id:s.session_id,credential:I(o)});return a.ok?c({success:true,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 Pe(e,r,t){let n=e.externalUserId??e.external_user_id,s=n!==void 0&&typeof n=="string"&&n.trim()!=="";return L({operation:"authenticate",eventEmitter:t,start:()=>r.startAuth(s?{external_user_id:n.trim()}:{}),createOptions:o=>ye(o.challenge,e.mediation),invoke:async o=>{let a={...o,...e.signal&&{signal:e.signal}};return navigator.credentials.get(a)},finish:async(o,a)=>{let d=await r.finishAuthentication({session_id:o.session_id,credential:X(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 ir=2e3,or=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<or;s++){await new Promise(R=>setTimeout(R,ir));let o=await this.apiClient.getOnboardingStatus(n);if(!o.ok)return l(o.error);let a=o.value.status,d=o.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(m("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:d}));let y=k(v.challenge);if(!y.ok)return l(y.error);let E;try{E=await navigator.credentials.create(y.value);}catch(_){return l(h(_))}try{S(E,"create");}catch(_){return l(h(_))}let b;try{b=I(E);}catch(_){return l(h(_))}let N=await this.apiClient.registerOnboardingPasskey(n,{credential:b,challenge:v.challenge.challenge});return N.ok?await this.apiClient.completeOnboarding(n,{company_name:r.company_name}):l(N.error)}if(a==="completed")return await this.apiClient.completeOnboarding(n,{company_name:r.company_name})}return l(m("TIMEOUT","Onboarding timed out"))}};var ar=2e3,lr=60,G=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<lr;n++){if(t?.aborted)return l(m("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(m("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(m("ABORT_ERROR","Operation aborted by user or timeout"));if(await new Promise(o=>{let a=setTimeout(()=>{o(null),t?.removeEventListener("abort",d);},ar),d=()=>{clearTimeout(a),o(null);};t?.addEventListener("abort",d);}),t?.aborted)return l(m("ABORT_ERROR","Operation aborted by user or timeout"))}return l(m("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=k(t.options);if(!n.ok)return l(n.error);let s;try{s=await navigator.credentials.create(n.value);}catch(a){return l(h(a))}try{S(s,"create");}catch(a){return l(h(a))}let o;try{o=I(s);}catch(a){return l(h(a))}return this.apiClient.verifyCrossDeviceRegistration({session_id:r,credential:o})}async executeAuthApproval(r,t){let n=ye(t.options);if(!n.ok)return l(n.error);let s;try{s=await navigator.credentials.get(n.value);}catch(a){return l(h(a))}try{S(s,"get");}catch(a){return l(h(a))}let o;try{o=X(s);}catch(a){return l(h(a))}return this.apiClient.verifyCrossDeviceAuth({session_id:r,credential:o})}};var Y=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 Me(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let s=f("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=f("otp","must be a 6-digit string");return t.emit("error",{type:"error",error:s}),l(s)}return L({operation:"register",eventEmitter:t,start:()=>r.verifyAccountRecoveryOtp(n,e.otp),createOptions:s=>k(s.challenge),invoke:async s=>navigator.credentials.create(s),finish:async(s,o)=>{let a=await r.completeAccountRecovery(s.recovery_session_id,I(o));return a.ok?c({success:true,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 fe="https://api.trymellonauth.com",De="https://api.trymellonauth.com/v1/telemetry";var ve="trymellon_sandbox_session_token_v1";function we(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:true});}}}function he(e,r){return {event:e,latencyMs:r,ok:true}}var Ee=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(f("appId","must be a non-empty string"));if(!n||typeof n!="string"||n.trim()==="")return l(f("publishableKey","must be a non-empty string"));let s=r.apiBaseUrl??fe;Q(s,"apiBaseUrl");let o=r.timeoutMs??3e4;return O(o,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&O(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&O(r.retryDelayMs,"retryDelayMs",100,1e4),c(new e(r))}catch(t){return q(t)?l(t):l(f("config",t.message))}}constructor(r){this.sandbox=r.sandbox===true,this.sandboxToken=this.sandbox&&r.sandboxToken!=null&&r.sandboxToken!==""?r.sandboxToken:ve;let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")throw f("appId","must be a non-empty string");if(!n||typeof n!="string"||n.trim()==="")throw f("publishableKey","must be a non-empty string");let s=r.apiBaseUrl??fe;Q(s,"apiBaseUrl");let o=r.timeoutMs??3e4;O(o,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&O(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&O(r.retryDelayMs,"retryDelayMs",100,1e4);let a=r.maxRetries??3,d=r.retryDelayMs??1e3,R=new $(o,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 H(R,s,y),this.onboarding=new z(this.apiClient),this.crossDeviceManager=new G(this.apiClient),this.eventEmitter=new Y,r.enableTelemetry&&(this.telemetrySender=r.telemetrySender??we(r.telemetryEndpoint??De));}static isSupported(){return w()}async register(r){if(this.sandbox){let s=r.externalUserId??r.external_user_id??"sandbox";return Promise.resolve(c({success:true,credentialId:"",status:"sandbox",sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:typeof s=="string"?s:"sandbox"}}))}let t=Date.now(),n=await xe(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(he("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:true,sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:typeof s=="string"?s:"sandbox"}}))}let t=Date.now(),n=await Pe(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(he("authenticate",Date.now()-t)).catch(()=>{}),n}async validateSession(r){return this.sandbox&&r===this.sandboxToken?Promise.resolve(c({valid:true,user_id:"sandbox-user",external_user_id:"sandbox",tenant_id:"sandbox-tenant",app_id:"sandbox-app"})):this.apiClient.validateSession(r)}async getStatus(){return ke()}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=>Me(r,this.apiClient,this.eventEmitter)}};var be=class{debug(r,t){t&&Object.keys(t).length>0?console.debug(`[TryMellon] ${r}`,t):console.debug(`[TryMellon] ${r}`);}info(r,t){t&&Object.keys(t).length>0?console.info(`[TryMellon] ${r}`,t):console.info(`[TryMellon] ${r}`);}warn(r,t){t&&Object.keys(t).length>0?console.warn(`[TryMellon] ${r}`,t):console.warn(`[TryMellon] ${r}`);}error(r,t){t&&Object.keys(t).length>0?console.error(`[TryMellon] ${r}`,t):console.error(`[TryMellon] ${r}`);}};
|
|
2
|
-
exports.ConsoleLogger=
|
|
1
|
+
'use strict';var c=e=>({ok:true,value:e}),l=e=>({ok:false,error:e});var D=class e extends Error{code;details;isTryMellonError=true;constructor(r,t,n){super(t),this.name="TryMellonError",this.code=r,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,e);}},qe={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 m(e,r,t){return new D(e,r??qe[e],t)}function F(e){return e instanceof D||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===true}function X(){return m("NOT_SUPPORTED")}function Ve(){return m("USER_CANCELLED")}function Be(e){return m("NETWORK_FAILURE",void 0,{cause:e?.message,originalError:e})}function We(){return m("TIMEOUT")}function y(e,r){return m("INVALID_ARGUMENT",`Invalid argument: ${e} - ${r}`,{field:e,reason:r})}function ve(e){return m("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function G(e){return m("NOT_SUPPORTED",`No base64 ${e==="encode"?"encoding":"decoding"} available`,{type:e})}function z(e,r){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw y(r,"must use http or https protocol")}catch(t){throw F(t)?t:y(r,"must be a valid URL")}}function O(e,r,t,n){if(!Number.isFinite(e))throw y(r,"must be a finite number");if(e<t||e>n)throw y(r,`must be between ${t} and ${n}`)}function L(e,r){if(typeof e!="string"||e.length===0)throw y(r,"must be a non-empty string");if(!/^[A-Za-z0-9_-]+$/.test(e))throw y(r,"must be a valid base64url string")}var He={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 v(e){if(e instanceof DOMException){let r=e.name,t=e.message||"WebAuthn operation failed",n=He[r]??"UNKNOWN_ERROR";return m(n,t,{originalError:e})}return e instanceof Error?m("UNKNOWN_ERROR",e.message,{originalError:e}):m("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 T(e){return typeof e=="number"&&Number.isFinite(e)}function K(e){return typeof e=="boolean"}function k(e){return Array.isArray(e)}function o(e,r){return l(m("UNKNOWN_ERROR",e,{...r,originalData:r?.originalData}))}function p(e,r){return e[r]}function Ee(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}):c(true)}function be(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}):c(true)}function _e(e,r){if(!k(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"||!T(t.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:r});return c(true)}function Y(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}):c({user_id:t,external_user_id:n,...s!==void 0&&{email:s},...i!==void 0&&{metadata:i}})}function J(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=Ee(p(t,"rp"),e);if(!n.ok)return n;let s=be(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=_e(p(t,"pubKeyCredParams"),e);if(!a.ok)return a;let d=t.timeout;if(d!==void 0&&!T(d))return o("Invalid API response: challenge.timeout must be number",{originalData:e});let R=t.excludeCredentials;if(R!==void 0){if(!k(R))return o("Invalid API response: excludeCredentials must be array",{originalData:e});for(let f of R)if(!g(f)||f.type!=="public-key"||!u(f.id))return o("Invalid API response: excludeCredentials items must have id and type",{originalData:e})}let h=t.authenticatorSelection;return h!==void 0&&!g(h)?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},...h!==void 0&&{authenticatorSelection:h}}})}function Z(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&&!k(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&&!T(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 Q(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=Y(s,e);return i.ok?c({credential_id:r,status:t,session_token:n,user:i.value}):o(i.error.message,{originalData:e})}function ee(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(!K(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=Y(n,e);return i.ok?s!==void 0&&!g(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 re(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 K(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 te(e){if(!g(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 $e=["pending_passkey","pending_data","completed"],Xe=["pending_data","completed"];function ne(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)?T(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 se(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)||!$e.includes(r)?o("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):u(t)?T(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 ie(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=Ge(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 Ge(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(!k(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"||!T(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 oe(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)||!Xe.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 ae(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}):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 ze(e){if(!e||typeof e!="object")return false;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 Ye(e){if(!e||typeof e!="object")return false;let r=e;return typeof r.challenge=="string"&&typeof r.rpId=="string"}function j(e){if(!g(e))return o("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;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 le(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}):c({status:r,user_id:e.user_id,session_token:e.session_token})}function ue(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;if(!g(n))return o("Invalid API response: options are required",{originalData:e});let s=200,i=Te(e.approval_context,s),a=Te(e.application_name,s);if(i===false||a===false)return o("Invalid API response: approval_context/application_name must be string max 200 chars",{originalData:e});let d={};return typeof i=="string"&&(d.approval_context=i),typeof a=="string"&&(d.application_name=a),t==="registration"?ze(n)?c({type:"registration",options:n,...d}):o("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):Ye(n)?c({type:"auth",options:n,...d}):o("Invalid API response: auth options must have challenge and rpId",{originalData:e})}function Te(e,r){if(e!=null)return typeof e!="string"||e.length>r?false:e}function pe(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)?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 ce(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 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:g(a.metadata)?a.metadata:void 0}})}var q=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,J)}async startAuth(r){return this.post("/v1/passkeys/auth/start",r,Z)}async finishRegister(r){return this.post("/v1/passkeys/register/finish",r,Q)}async finishAuthentication(r){return this.post("/v1/passkeys/auth/finish",r,ee)}async validateSession(r){return this.get("/v1/sessions/validate",re,{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},te)}async startOnboarding(r){return this.post("/onboarding/start",r,ne)}async getOnboardingStatus(r){return this.get(`/onboarding/${r}/status`,se)}async getOnboardingRegister(r){return this.get(`/onboarding/${r}/register`,ie)}async registerOnboardingPasskey(r,t){return this.post(`/onboarding/${r}/register-passkey`,t,oe)}async completeOnboarding(r,t){return this.post(`/onboarding/${r}/complete`,t,ae)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},j)}async initCrossDeviceRegistration(r){return this.post("/v1/auth/cross-device/init-registration",{external_user_id:r.externalUserId},j)}async getCrossDeviceStatus(r){return this.get(`/v1/auth/cross-device/status/${r}`,le)}async getCrossDeviceContext(r){return this.get(`/v1/auth/cross-device/context/${r}`,ue)}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},pe)}async completeAccountRecovery(r,t){return this.post("/v1/users/recovery/complete",{recovery_session_id:r,credential:t},ce)}};function Je(e){return typeof e=="object"&&e!==null&&e.ok===true&&"resultado"in e}function Ze(e){if(typeof e!="object"||e===null)return false;let r=e;if(r.ok!==false||!r.error||typeof r.error!="object")return false;let t=r.error;return typeof t.code=="string"&&typeof t.message=="string"}function Qe(e,r){if(Ze(e))return {message:e.error.message,code:w(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:w(n.code)};let s=t?.message??r,i=t?.error,a=typeof i=="string"?w(i):i===void 0?"NETWORK_FAILURE":w(String(i));return {message:s,code:a}}var er=3e4;function rr(){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 Ae(e,r){let t=r*Math.pow(2,e);return Math.min(t,er)}function tr(e,r){return e!=="GET"?false:r>=500||r===429}var V=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=rr(),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,h=setTimeout(()=>R.abort(),this.timeoutMs);try{let f=await fetch(r,{...t,headers:i,signal:R.signal});if(!f.ok){let U;try{U=await f.json();}catch{}let{message:I,code:Ke}=Qe(U,f.statusText),he=m(Ke,I,{requestId:s,status:f.status,statusText:f.statusText,data:U});if(tr(n,f.status)&&d<this.maxRetries){a=he,clearTimeout(h),await new Promise(je=>setTimeout(je,Ae(d,this.retryDelayMs)));continue}return l(he)}if(f.status===204)return c(void 0);if(f.headers.get("content-length")==="0")return c(void 0);let b=await f.json();if(Je(b))return c(b.resultado);let P=b;return typeof b=="object"&&b!==null&&P.ok===true&&!("resultado"in P)?c(void 0):c(b)}finally{clearTimeout(h);}}catch(R){if(a=R,n==="GET"&&d<this.maxRetries)await new Promise(f=>setTimeout(f,Ae(d,this.retryDelayMs)));else break}return a instanceof Error&&a.name==="AbortError"?l(m("TIMEOUT","Request timed out",{requestId:s})):l(m("NETWORK_FAILURE",a instanceof Error?a.message:"Request failed",{requestId:s,cause:a}))}};function _(e){let r=new Uint8Array(e),t=Array.from(r,s=>String.fromCharCode(s)).join("");if(typeof globalThis.btoa>"u")throw G("encode");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function nr(e){if(typeof globalThis.atob>"u")throw G("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 x(e){let r=nr(e),t=new ArrayBuffer(r.length);return new Uint8Array(t).set(r),t}function Ie(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function A(e){if(!e.response)throw m("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!Ie(r))throw m("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("attestationObject"in r))throw m("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:_(e.rawId),response:{clientDataJSON:_(t),attestationObject:_(n)},type:"public-key"}}function B(e){if(!e.response)throw m("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!Ie(r))throw m("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("authenticatorData"in r)||!("signature"in r))throw m("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:_(e.rawId),response:{authenticatorData:_(n),clientDataJSON:_(t),signature:_(s),...i&&{userHandle:_(i)}},type:"public-key"}}function M(){try{return !(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return false}}async function sr(){try{return !M()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?false:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return false}}async function Oe(){let e=M(),r=await sr();return {isPasskeySupported:e,platformAuthenticatorAvailable:r,recommendedFlow:e?"passkey":"fallback"}}function C(e,r="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw ve(r)}async function N(e){let{operation:r,eventEmitter:t,start:n,createOptions:s,invoke:i,finish:a}=e;try{if(t.emit("start",{type:"start",operation:r}),!M()){let E=X();return t.emit("error",{type:"error",error:E}),l(E)}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 h=await i(R.value);if(!h){let E=y("credential",`${r==="register"?"creation":"retrieval"} failed`);return t.emit("error",{type:"error",error:E}),l(E)}try{C(h);}catch(E){let b=v(E);return t.emit("error",{type:"error",error:b}),l(b)}let f=await a(d.value,h);return f.ok?(t.emit("success",{type:"success",operation:r}),c(f.value)):(t.emit("error",{type:"error",error:f.error}),l(f.error))}catch(d){let R=v(d);return t.emit("error",{type:"error",error:R}),l(R)}}function S(e,r){try{L(e.challenge,"challenge"),L(e.user.id,"user.id");let t=x(e.challenge),n=x(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:x(a.id),type:a.type,...a.transports&&{transports:a.transports}}))}};return c({publicKey:i})}catch(t){return l(v(t))}}function de(e,r){try{L(e.challenge,"challenge");let t=x(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:x(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...r!==void 0&&{mediation:r}})}catch(t){return l(v(t))}}async function Ce(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let s=y("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:s}),l(s)}return N({operation:"register",eventEmitter:t,start:()=>r.startRegister({external_user_id:n}),createOptions:s=>S(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:A(i)});return a.ok?c({success:true,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 Se(e,r,t){let n=e.externalUserId??e.external_user_id,s=n!==void 0&&typeof n=="string"&&n.trim()!=="";return N({operation:"authenticate",eventEmitter:t,start:()=>r.startAuth(s?{external_user_id:n.trim()}:{}),createOptions:i=>de(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:B(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 ir=2e3,or=60,W=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<or;s++){await new Promise(R=>setTimeout(R,ir));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 h=R.value;if(!h.challenge)return l(m("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:d}));let f=S(h.challenge);if(!f.ok)return l(f.error);let E;try{E=await navigator.credentials.create(f.value);}catch(I){return l(v(I))}try{C(E,"create");}catch(I){return l(v(I))}let b;try{b=A(E);}catch(I){return l(v(I))}let P=await this.apiClient.registerOnboardingPasskey(n,{credential:b,challenge:h.challenge.challenge});return P.ok?await this.apiClient.completeOnboarding(n,{company_name:r.company_name}):l(P.error)}if(a==="completed")return await this.apiClient.completeOnboarding(n,{company_name:r.company_name})}return l(m("TIMEOUT","Onboarding timed out"))}};var ar=2e3,lr=60,H=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<lr;n++){if(t?.aborted)return l(m("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(m("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(m("ABORT_ERROR","Operation aborted by user or timeout"));if(await new Promise(i=>{let a=setTimeout(()=>{i(null),t?.removeEventListener("abort",d);},ar),d=()=>{clearTimeout(a),i(null);};t?.addEventListener("abort",d);}),t?.aborted)return l(m("ABORT_ERROR","Operation aborted by user or timeout"))}return l(m("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=S(t.options);if(!n.ok)return l(n.error);let s;try{s=await navigator.credentials.create(n.value);}catch(a){return l(v(a))}try{C(s,"create");}catch(a){return l(v(a))}let i;try{i=A(s);}catch(a){return l(v(a))}return this.apiClient.verifyCrossDeviceRegistration({session_id:r,credential:i})}async executeAuthApproval(r,t){let n=de(t.options);if(!n.ok)return l(n.error);let s;try{s=await navigator.credentials.get(n.value);}catch(a){return l(v(a))}try{C(s,"get");}catch(a){return l(v(a))}let i;try{i=B(s);}catch(a){return l(v(a))}return this.apiClient.verifyCrossDeviceAuth({session_id:r,credential:i})}};var $=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 ke(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let s=y("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=y("otp","must be a 6-digit string");return t.emit("error",{type:"error",error:s}),l(s)}return N({operation:"register",eventEmitter:t,start:()=>r.verifyAccountRecoveryOtp(n,e.otp),createOptions:s=>S(s.challenge),invoke:async s=>navigator.credentials.create(s),finish:async(s,i)=>{let a=await r.completeAccountRecovery(s.recovery_session_id,A(i));return a.ok?c({success:true,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 ge="https://api.trymellonauth.com",xe="https://api.trymellonauth.com/v1/telemetry";var me="trymellon_sandbox_session_token_v1";function Me(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:true});}}}function Re(e,r){return {event:e,latencyMs:r,ok:true}}var fe=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(y("appId","must be a non-empty string"));if(!n||typeof n!="string"||n.trim()==="")return l(y("publishableKey","must be a non-empty string"));let s=r.apiBaseUrl??ge;z(s,"apiBaseUrl");let i=r.timeoutMs??3e4;return O(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&O(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&O(r.retryDelayMs,"retryDelayMs",100,1e4),c(new e(r))}catch(t){return F(t)?l(t):l(y("config",t.message))}}constructor(r){this.sandbox=r.sandbox===true,this.sandboxToken=this.sandbox&&r.sandboxToken!=null&&r.sandboxToken!==""?r.sandboxToken:me;let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")throw y("appId","must be a non-empty string");if(!n||typeof n!="string"||n.trim()==="")throw y("publishableKey","must be a non-empty string");let s=r.apiBaseUrl??ge;z(s,"apiBaseUrl");let i=r.timeoutMs??3e4;O(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&O(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&O(r.retryDelayMs,"retryDelayMs",100,1e4);let a=r.maxRetries??3,d=r.retryDelayMs??1e3,R=new V(i,a,d,r.logger),h=r.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),f={"X-App-Id":t.trim(),Authorization:`Bearer ${n.trim()}`,...h&&{Origin:h}};this.apiClient=new q(R,s,f),this.onboarding=new W(this.apiClient),this.crossDeviceManager=new H(this.apiClient),this.eventEmitter=new $,r.enableTelemetry&&(this.telemetrySender=r.telemetrySender??Me(r.telemetryEndpoint??xe));}static isSupported(){return M()}sandboxAuthResult(r,t){let n=t.externalUserId??t.external_user_id??"sandbox",s=typeof n=="string"?n:"sandbox";return r==="register"?Promise.resolve(c({success:true,credentialId:"",status:"sandbox",sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:s}})):Promise.resolve(c({authenticated:true,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 Ce(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Re("register",Date.now()-t)).catch(()=>{}),n}async authenticate(r){if(this.sandbox)return this.sandboxAuthResult("authenticate",r);let t=Date.now(),n=await Se(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Re("authenticate",Date.now()-t)).catch(()=>{}),n}async validateSession(r){return this.sandbox&&r===this.sandboxToken?Promise.resolve(c({valid:true,user_id:"sandbox-user",external_user_id:"sandbox",tenant_id:"sandbox-tenant",app_id:"sandbox-app"})):this.apiClient.validateSession(r)}async getStatus(){return Oe()}on(r,t){return this.eventEmitter.on(r,t)}version(){return "1.7.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),getContext:r=>this.apiClient.getCrossDeviceContext(r),approve:r=>this.crossDeviceManager.approve(r)},recoverAccount:async r=>ke(r,this.apiClient,this.eventEmitter)}};var ye=class{debug(r,t){t&&Object.keys(t).length>0?console.debug(`[TryMellon] ${r}`,t):console.debug(`[TryMellon] ${r}`);}info(r,t){t&&Object.keys(t).length>0?console.info(`[TryMellon] ${r}`,t):console.info(`[TryMellon] ${r}`);}warn(r,t){t&&Object.keys(t).length>0?console.warn(`[TryMellon] ${r}`,t):console.warn(`[TryMellon] ${r}`);}error(r,t){t&&Object.keys(t).length>0?console.error(`[TryMellon] ${r}`,t):console.error(`[TryMellon] ${r}`);}};
|
|
2
|
+
exports.ConsoleLogger=ye;exports.SANDBOX_SESSION_TOKEN=me;exports.TryMellon=fe;exports.TryMellonError=D;exports.createError=m;exports.createInvalidArgumentError=y;exports.createNetworkError=Be;exports.createNotSupportedError=X;exports.createTimeoutError=We;exports.createUserCancelledError=Ve;exports.err=l;exports.isTryMellonError=F;exports.mapWebAuthnError=v;exports.ok=c;//# sourceMappingURL=index.cjs.map
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|