UNPKG

@teamhanko/hanko-frontend-sdk

Version:

A package for simplifying UI integration with the Hanko API. It is meant for use in browsers only.

3 lines (2 loc) 37 kB
function e(){return e=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},e.apply(this,arguments)}function t(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,r(e,t)}function n(e){return n=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},n(e)}function r(e,t){return r=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},r(e,t)}function i(e,t,n){return i=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}()?Reflect.construct.bind():function(e,t,n){var i=[null];i.push.apply(i,t);var o=new(Function.bind.apply(e,i));return n&&r(o,n.prototype),o},i.apply(null,arguments)}function o(e){var t="function"==typeof Map?new Map:void 0;return o=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,o)}function o(){return i(e,arguments,n(this).constructor)}return o.prototype=Object.create(e.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),r(o,e)},o(e)}function s(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}var a=/*#__PURE__*/function(){function e(){}return e.throttle=function(e,t,n){void 0===n&&(n={});var r,i,o,s=n.leading,a=void 0===s||s,c=n.trailing,u=void 0===c||c,h=0,l=function(){h=!1===a?0:Date.now(),o=null,e.apply(r,i)};return function(){var n=Date.now();h||!1!==a||(h=n);var s=t-(n-h);r=this,i=[].slice.call(arguments),s<=0||s>t?(o&&(window.clearTimeout(o),o=null),h=n,e.apply(r,i)):o||!1===u||(o=window.setTimeout(l,s))}},e}(),c="hanko-session-created",u="hanko-session-expired",h="hanko-user-logged-out",l="hanko-user-deleted",d="hanko-after-state-change",f="hanko-before-state-change",p=/*#__PURE__*/function(e){function n(t,n){return e.call(this,t,{detail:n})||this}return t(n,e),n}(/*#__PURE__*/o(CustomEvent)),v=/*#__PURE__*/function(){function e(){this.throttleLimit=1e3,this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=a.throttle}var t=e.prototype;return t.wrapCallback=function(e,t){var n=function(t){e(t.detail)};return t?this._throttle(n,this.throttleLimit,{leading:!0,trailing:!1}):n},t.addEventListenerWithType=function(e){var t=this,n=e.type,r=e.once,i=void 0!==r&&r,o=e.throttle,s=this.wrapCallback(e.callback,void 0!==o&&o);return this._addEventListener(n,s,{once:i}),function(){return t._removeEventListener(n,s)}},e.mapAddEventListenerParams=function(e,t,n){return{type:e,callback:t.callback,once:t.once,throttle:n}},t.addEventListener=function(t,n,r){return this.addEventListenerWithType(e.mapAddEventListenerParams(t,n,r))},t.onSessionCreated=function(e,t){return this.addEventListener(c,{callback:e,once:t},!0)},t.onSessionExpired=function(e,t){return this.addEventListener(u,{callback:e,once:t},!0)},t.onUserLoggedOut=function(e,t){return this.addEventListener(h,{callback:e,once:t})},t.onUserDeleted=function(e,t){return this.addEventListener(l,{callback:e,once:t})},t.onAfterStateChange=function(e,t){return this.addEventListener(d,{callback:e,once:t},!1)},t.onBeforeStateChange=function(e,t){return this.addEventListener(f,{callback:e,once:t},!1)},e}(),m=/*#__PURE__*/function(){function e(){this._dispatchEvent=document.dispatchEvent.bind(document)}var t=e.prototype;return t.dispatch=function(e,t){this._dispatchEvent(new p(e,t))},t.dispatchSessionCreatedEvent=function(e){this.dispatch(c,e)},t.dispatchSessionExpiredEvent=function(){this.dispatch(u,null)},t.dispatchUserLoggedOutEvent=function(){this.dispatch(h,null)},t.dispatchUserDeletedEvent=function(){this.dispatch(l,null)},t.dispatchAfterStateChangeEvent=function(e){this.dispatch(d,e)},t.dispatchBeforeStateChangeEvent=function(e){this.dispatch(f,e)},e}(),y=/*#__PURE__*/function(e){function n(t,r,i){var o;return(o=e.call(this,t)||this).code=void 0,o.cause=void 0,o.code=r,o.cause=i,Object.setPrototypeOf(s(o),n.prototype),o}return t(n,e),n}(/*#__PURE__*/o(Error)),g=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Technical error","somethingWentWrong",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),S=/*#__PURE__*/function(e){function n(t,r){var i;return i=e.call(this,"Conflict error","conflict",r)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(y),k=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Request timed out error","requestTimeout",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),b=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Request cancelled error","requestCancelled",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),w=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Invalid password error","invalidPassword",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),C=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Invalid Passcode error","invalidPasscode",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),P=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Invalid WebAuthn credential error","invalidWebauthnCredential",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),x=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Passcode expired error","passcodeExpired",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),E=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Maximum number of Passcode attempts reached error","passcodeAttemptsReached",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),A=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Not found error","notFound",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),_=/*#__PURE__*/function(e){function n(t,r){var i;return(i=e.call(this,"Too many requests error","tooManyRequests",r)||this).retryAfter=void 0,i.retryAfter=t,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(y),O=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Unauthorized error","unauthorized",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),I=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Forbidden error","forbidden",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),j=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"User verification error","userVerification",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),L=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),T=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"The email address already exists","emailAddressAlreadyExistsError",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),N=/*#__PURE__*/function(e){function n(t,r){var i;return i=e.call(this,"An error occurred during third party sign up/sign in",t,r)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(y);function R(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)e[r]=n[r]}return e}var D=function e(t,n){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=R({},n,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var s in i)i[s]&&(o+="; "+s,!0!==i[s]&&(o+="="+i[s].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+o}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],r={},i=0;i<n.length;i++){var o=n[i].split("="),s=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(r[a]=t.read(s,a),e===a)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",R({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,R({},this.attributes,t))},withConverter:function(t){return e(R({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"}),K=/*#__PURE__*/function(){function t(e){var t,n;this.authCookieName=void 0,this.authCookieDomain=void 0,this.authCookieSameSite=void 0,this.authCookieName=null!=(t=e.cookieName)?t:"hanko",this.authCookieDomain=e.cookieDomain,this.authCookieSameSite=null!=(n=e.cookieSameSite)?n:"lax"}var n=t.prototype;return n.getAuthCookie=function(){return D.get(this.authCookieName)},n.setAuthCookie=function(t,n){var r={secure:!0,sameSite:this.authCookieSameSite};void 0!==this.authCookieDomain&&(r.domain=this.authCookieDomain);var i=e({},r,n);if(("none"===i.sameSite||"None"===i.sameSite)&&!1===i.secure)throw new g(new Error("Secure attribute must be set when SameSite=None"));D.set(this.authCookieName,t,i)},n.removeAuthCookie=function(){D.remove(this.authCookieName)},t}(),q=/*#__PURE__*/function(){function e(e){this.keyName=void 0,this.keyName=e.keyName}var t=e.prototype;return t.getSessionToken=function(){return sessionStorage.getItem(this.keyName)},t.setSessionToken=function(e){sessionStorage.setItem(this.keyName,e)},t.removeSessionToken=function(){sessionStorage.removeItem(this.keyName)},e}(),U=/*#__PURE__*/function(){function e(e){this._xhr=void 0,this._xhr=e}return e.prototype.getResponseHeader=function(e){return this._xhr.getResponseHeader(e)},e}(),F=/*#__PURE__*/function(){function e(e){this.headers=void 0,this.ok=void 0,this.status=void 0,this.statusText=void 0,this.url=void 0,this._decodedJSON=void 0,this.xhr=void 0,this.headers=new U(e),this.ok=e.status>=200&&e.status<=299,this.status=e.status,this.statusText=e.statusText,this.url=e.responseURL,this.xhr=e}var t=e.prototype;return t.json=function(){return this._decodedJSON||(this._decodedJSON=JSON.parse(this.xhr.response)),this._decodedJSON},t.parseNumericHeader=function(e){var t=parseInt(this.headers.getResponseHeader(e),10);return isNaN(t)?0:t},e}(),M=/*#__PURE__*/function(){function t(t,n){var r;this.timeout=void 0,this.api=void 0,this.dispatcher=void 0,this.cookie=void 0,this.sessionTokenStorage=void 0,this.lang=void 0,this.sessionTokenLocation=void 0,this.api=t,this.timeout=null!=(r=n.timeout)?r:13e3,this.dispatcher=new m,this.cookie=new K(e({},n)),this.sessionTokenStorage=new q({keyName:n.cookieName}),this.lang=n.lang,this.sessionTokenLocation=n.sessionTokenLocation}var n=t.prototype;return n._fetch=function(e,t,n){void 0===n&&(n=new XMLHttpRequest);var r=this,i=this.api+e,o=this.timeout,s=this.getAuthToken(),a=this.lang;return new Promise(function(e,c){n.open(t.method,i,!0),n.setRequestHeader("Accept","application/json"),n.setRequestHeader("Content-Type","application/json"),n.setRequestHeader("X-Language",a),s&&n.setRequestHeader("Authorization","Bearer "+s),n.timeout=o,n.withCredentials=!0,n.onload=function(){r.processHeaders(n),e(new F(n))},n.onerror=function(){c(new g)},n.ontimeout=function(){c(new k)},n.send(t.body?t.body.toString():null)})},n.processHeaders=function(e){var t="",n=0,r="";if(e.getAllResponseHeaders().split("\r\n").forEach(function(i){var o=i.toLowerCase();o.startsWith("x-auth-token")?t=e.getResponseHeader("X-Auth-Token"):o.startsWith("x-session-lifetime")?n=parseInt(e.getResponseHeader("X-Session-Lifetime"),10):o.startsWith("x-session-retention")&&(r=e.getResponseHeader("X-Session-Retention"))}),t){var i=new RegExp("^https://"),o=!!this.api.match(i)&&!!window.location.href.match(i),s="session"===r?void 0:new Date((new Date).getTime()+1e3*n);this.setAuthToken(t,{secure:o,expires:s})}},n.get=function(e){return this._fetch(e,{method:"GET"})},n.post=function(e,t){return this._fetch(e,{method:"POST",body:JSON.stringify(t)})},n.put=function(e,t){return this._fetch(e,{method:"PUT",body:JSON.stringify(t)})},n.patch=function(e,t){return this._fetch(e,{method:"PATCH",body:JSON.stringify(t)})},n.delete=function(e){return this._fetch(e,{method:"DELETE"})},n.getAuthToken=function(){var e="";switch(this.sessionTokenLocation){case"cookie":default:e=this.cookie.getAuthCookie();break;case"sessionStorage":e=this.sessionTokenStorage.getSessionToken()}return e},n.setAuthToken=function(e,t){switch(this.sessionTokenLocation){case"cookie":default:return this.cookie.setAuthCookie(e,t);case"sessionStorage":return this.sessionTokenStorage.setSessionToken(e)}},t}(),H=function(e,t){this.client=void 0,this.client=new M(e,t)},W=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}return t(n,e),n.prototype.validate=function(){try{return Promise.resolve(this.client.get("/sessions/validate")).then(function(e){if(!e.ok)throw new g;return Promise.resolve(e.json())})}catch(e){return Promise.reject(e)}},n}(H),z=/*#__PURE__*/function(){function e(e){this.storageKey=void 0,this.defaultState={expiration:0,lastCheck:0},this.storageKey=e}var t=e.prototype;return t.load=function(){var e=window.localStorage.getItem(this.storageKey);return null==e?this.defaultState:JSON.parse(e)},t.save=function(e){window.localStorage.setItem(this.storageKey,JSON.stringify(e||this.defaultState))},e}(),B=function(e,t){var n=this;this.onActivityCallback=void 0,this.onInactivityCallback=void 0,this.handleFocus=function(){n.onActivityCallback()},this.handleBlur=function(){n.onInactivityCallback()},this.handleVisibilityChange=function(){"visible"===document.visibilityState?n.onActivityCallback():n.onInactivityCallback()},this.hasFocus=function(){return document.hasFocus()},this.onActivityCallback=e,this.onInactivityCallback=t,window.addEventListener("focus",this.handleFocus),window.addEventListener("blur",this.handleBlur),document.addEventListener("visibilitychange",this.handleVisibilityChange)},J=/*#__PURE__*/function(){function e(e,t,n){this.intervalID=null,this.timeoutID=null,this.checkInterval=void 0,this.checkSession=void 0,this.onSessionExpired=void 0,this.checkInterval=e,this.checkSession=t,this.onSessionExpired=n}var t=e.prototype;return t.scheduleSessionExpiry=function(e){var t=this;this.stop(),this.timeoutID=setTimeout(function(){try{return t.stop(),t.onSessionExpired(),Promise.resolve()}catch(e){return Promise.reject(e)}},e)},t.start=function(e,t){var n=this;void 0===e&&(e=0),void 0===t&&(t=0);var r=this.calcTimeToNextCheck(e);this.sessionExpiresSoon(t)?this.scheduleSessionExpiry(r):this.timeoutID=setTimeout(function(){try{return Promise.resolve(n.checkSession()).then(function(e){if(e.is_valid){if(n.sessionExpiresSoon(e.expiration))return void n.scheduleSessionExpiry(e.expiration-Date.now());n.intervalID=setInterval(function(){try{return Promise.resolve(n.checkSession()).then(function(t){(e=t).is_valid?n.sessionExpiresSoon(e.expiration)&&n.scheduleSessionExpiry(e.expiration-Date.now()):n.stop()})}catch(e){return Promise.reject(e)}},n.checkInterval)}else n.stop()})}catch(e){return Promise.reject(e)}},r)},t.stop=function(){this.timeoutID&&(clearTimeout(this.timeoutID),this.timeoutID=null),this.intervalID&&(clearInterval(this.intervalID),this.intervalID=null)},t.isRunning=function(){return null!==this.timeoutID||null!==this.intervalID},t.sessionExpiresSoon=function(e){return e>0&&e-Date.now()<=this.checkInterval},t.calcTimeToNextCheck=function(e){var t=Date.now()-e;return this.checkInterval>=t?this.checkInterval-t%this.checkInterval:0},e}(),V=/*#__PURE__*/function(){function e(e,t,n,r){var i=this;void 0===e&&(e="hanko_session"),this.channel=void 0,this.onSessionExpired=void 0,this.onSessionCreated=void 0,this.onLeadershipRequested=void 0,this.handleMessage=function(e){var t=e.data;switch(t.action){case"sessionExpired":i.onSessionExpired(t);break;case"sessionCreated":i.onSessionCreated(t);break;case"requestLeadership":i.onLeadershipRequested(t)}},this.onSessionExpired=t,this.onSessionCreated=n,this.onLeadershipRequested=r,this.channel=new BroadcastChannel(e),this.channel.onmessage=this.handleMessage}return e.prototype.post=function(e){this.channel.postMessage(e)},e}(),X=/*#__PURE__*/function(e){function n(t,n){var r;(r=e.call(this)||this).listener=new v,r.checkInterval=3e4,r.client=void 0,r.sessionState=void 0,r.windowActivityManager=void 0,r.scheduler=void 0,r.sessionChannel=void 0,r.isLoggedIn=void 0,r.client=new W(t,n),n.sessionCheckInterval&&(r.checkInterval=n.sessionCheckInterval<3e3?3e3:n.sessionCheckInterval),r.sessionState=new z(n.cookieName+"_session_state"),r.sessionChannel=new V(r.getSessionCheckChannelName(n.sessionTokenLocation,n.sessionCheckChannelName),function(){return r.onChannelSessionExpired()},function(e){return r.onChannelSessionCreated(e)},function(){return r.onChannelLeadershipRequested()}),r.scheduler=new J(r.checkInterval,function(){return r.checkSession()},function(){return r.onSessionExpired()}),r.windowActivityManager=new B(function(){return r.startSessionCheck()},function(){return r.scheduler.stop()});var i=Date.now(),o=r.sessionState.load();return r.isLoggedIn=i<o.expiration,r.initializeEventListeners(),r.startSessionCheck(),r}t(n,e);var r=n.prototype;return r.initializeEventListeners=function(){var e=this;this.listener.onSessionCreated(function(t){var n=t.claims,r=Date.parse(n.expiration),i=Date.now();e.isLoggedIn=!0,e.sessionState.save({expiration:r,lastCheck:i}),e.sessionChannel.post({action:"sessionCreated",claims:n}),e.startSessionCheck()}),this.listener.onUserLoggedOut(function(){e.isLoggedIn=!1,e.sessionChannel.post({action:"sessionExpired"}),e.sessionState.save(null),e.scheduler.stop()}),window.addEventListener("beforeunload",function(){return e.scheduler.stop()})},r.startSessionCheck=function(){if(this.windowActivityManager.hasFocus()&&(this.sessionChannel.post({action:"requestLeadership"}),!this.scheduler.isRunning())){var e=this.sessionState.load();this.isLoggedIn&&this.scheduler.start(e.lastCheck,e.expiration)}},r.checkSession=function(){try{var e=this,t=Date.now();return Promise.resolve(e.client.validate()).then(function(n){var r=n.is_valid,i=n.claims,o=n.expiration_time,s=o?Date.parse(o):0;return!r&&e.isLoggedIn&&e.dispatchSessionExpiredEvent(),r?(e.isLoggedIn=!0,e.sessionState.save({lastCheck:t,expiration:s})):(e.isLoggedIn=!1,e.sessionState.save(null),e.sessionChannel.post({action:"sessionExpired"})),{is_valid:r,claims:i,expiration:s}})}catch(e){return Promise.reject(e)}},r.onSessionExpired=function(){this.isLoggedIn&&(this.isLoggedIn=!1,this.sessionState.save(null),this.sessionChannel.post({action:"sessionExpired"}),this.dispatchSessionExpiredEvent())},r.onChannelSessionExpired=function(){this.isLoggedIn&&(this.isLoggedIn=!1,this.dispatchSessionExpiredEvent())},r.onChannelSessionCreated=function(e){var t=e.claims,n=Date.now(),r=Date.parse(t.expiration)-n;this.isLoggedIn=!0,this.dispatchSessionCreatedEvent({claims:t,expirationSeconds:r})},r.onChannelLeadershipRequested=function(){this.windowActivityManager.hasFocus()||this.scheduler.stop()},r.getSessionCheckChannelName=function(e,t){if("sessionStorage"!==e)return t;var n=sessionStorage.getItem("sessionCheckChannelName");return null!=n&&""!==n||(n=t+"-"+(Math.floor(100*Math.random())+1),sessionStorage.setItem("sessionCheckChannelName",n)),n},n}(m),G=/*#__PURE__*/function(){function e(){}return e.supported=function(){return!!(navigator.credentials&&navigator.credentials.create&&navigator.credentials.get&&window.PublicKeyCredential)},e.isPlatformAuthenticatorAvailable=function(){try{return this.supported()&&window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?Promise.resolve(window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()):Promise.resolve(!1)}catch(e){return Promise.reject(e)}},e.isSecurityKeySupported=function(){try{return void 0!==window.PublicKeyCredential&&window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported?Promise.resolve(window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported()):Promise.resolve(this.supported())}catch(e){return Promise.reject(e)}},e.isConditionalMediationAvailable=function(){try{return window.PublicKeyCredential&&window.PublicKeyCredential.isConditionalMediationAvailable?Promise.resolve(window.PublicKeyCredential.isConditionalMediationAvailable()):Promise.resolve(!1)}catch(e){return Promise.reject(e)}},e}();function $(e){const t="==".slice(0,(4-e.length%4)%4),n=e.replace(/-/g,"+").replace(/_/g,"/")+t,r=atob(n),i=new ArrayBuffer(r.length),o=new Uint8Array(i);for(let e=0;e<r.length;e++)o[e]=r.charCodeAt(e);return i}function Q(e){const t=new Uint8Array(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}var Y="copy",Z="convert";function ee(e,t,n){if(t===Y)return n;if(t===Z)return e(n);if(t instanceof Array)return n.map(n=>ee(e,t[0],n));if(t instanceof Object){const r={};for(const[i,o]of Object.entries(t)){if(o.derive){const e=o.derive(n);void 0!==e&&(n[i]=e)}if(i in n)r[i]=null!=n[i]?ee(e,o.schema,n[i]):null;else if(o.required)throw new Error(`Missing key: ${i}`)}return r}}function te(e,t){return{required:!0,schema:e,derive:t}}function ne(e){return{required:!0,schema:e}}function re(e){return{required:!1,schema:e}}var ie={type:ne(Y),id:ne(Z),transports:re(Y)},oe={appid:re(Y),appidExclude:re(Y),credProps:re(Y)},se={appid:re(Y),appidExclude:re(Y),credProps:re(Y)},ae={publicKey:ne({rp:ne(Y),user:ne({id:ne(Z),name:ne(Y),displayName:ne(Y)}),challenge:ne(Z),pubKeyCredParams:ne(Y),timeout:re(Y),excludeCredentials:re([ie]),authenticatorSelection:re(Y),attestation:re(Y),extensions:re(oe)}),signal:re(Y)},ce={type:ne(Y),id:ne(Y),rawId:ne(Z),authenticatorAttachment:re(Y),response:ne({clientDataJSON:ne(Z),attestationObject:ne(Z),transports:te(Y,e=>{var t;return(null==(t=e.getTransports)?void 0:t.call(e))||[]})}),clientExtensionResults:te(se,e=>e.getClientExtensionResults())},ue={mediation:re(Y),publicKey:ne({challenge:ne(Z),timeout:re(Y),rpId:re(Y),allowCredentials:re([ie]),userVerification:re(Y),extensions:re(oe)}),signal:re(Y)},he={type:ne(Y),id:ne(Y),rawId:ne(Z),authenticatorAttachment:re(Y),response:ne({clientDataJSON:ne(Z),authenticatorData:ne(Z),signature:ne(Z),userHandle:ne(Z)}),clientExtensionResults:te(se,e=>e.getClientExtensionResults())};async function le(e){const t=await navigator.credentials.get(function(e){return ee($,ue,e)}(e));return function(e){return ee(Q,he,e)}(t)}var de=/*#__PURE__*/function(){function t(){this.abortController=new AbortController}t.getInstance=function(){return t.instance||(t.instance=new t),t.instance};var n=t.prototype;return n.createAbortSignal=function(){return this.abortController.abort(),this.abortController=new AbortController,this.abortController.signal},n.getWebauthnCredential=function(t){try{return Promise.resolve(le(e({},t,{signal:this.createAbortSignal()})))}catch(e){return Promise.reject(e)}},n.getConditionalWebauthnCredential=function(e){try{return Promise.resolve(le({publicKey:e,mediation:"conditional",signal:this.createAbortSignal()}))}catch(e){return Promise.reject(e)}},n.createWebauthnCredential=function(t){try{return Promise.resolve(async function(e){return t=await navigator.credentials.create(function(e){return ee($,ae,e)}(e)),ee(Q,ce,t);var t}(e({},t,{signal:this.createAbortSignal()})))}catch(e){return Promise.reject(e)}},t}();function fe(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}de.instance=null;var pe=function(e,t,n,r,i){void 0===r&&(r="webauthn_credential_already_exists"),void 0===i&&(i="Webauthn credential already exists");try{return Promise.resolve(fe(function(){return Promise.resolve(t.createWebauthnCredential(n)).then(function(t){return Promise.resolve(e.actions.webauthn_verify_attestation_response.run({public_key:t}))})},function(){return Promise.resolve(e.actions.back.run()).then(function(e){return e.error={code:r,message:i},e})}))}catch(e){return Promise.reject(e)}},ve={preflight:function(e){try{var t=e.actions.register_client_capabilities,n=t.run,r=G.supported();return Promise.resolve(G.isConditionalMediationAvailable()).then(function(e){return Promise.resolve(G.isPlatformAuthenticatorAvailable()).then(function(i){return Promise.resolve(n.call(t,{webauthn_available:r,webauthn_conditional_mediation_available:e,webauthn_platform_authenticator_available:i}))})})}catch(e){return Promise.reject(e)}},login_passkey:function(e){try{var t=de.getInstance();return Promise.resolve(fe(function(){return Promise.resolve(t.getWebauthnCredential(e.payload.request_options)).then(function(t){return Promise.resolve(e.actions.webauthn_verify_assertion_response.run({assertion_response:t}))})},function(){return Promise.resolve(e.actions.back.run()).then(function(t){return e.error&&(t.error=e.error),t})}))}catch(e){return Promise.reject(e)}},onboarding_verify_passkey_attestation:function(e){try{var t=de.getInstance();return Promise.resolve(pe(e,t,e.payload.creation_options))}catch(e){return Promise.reject(e)}},webauthn_credential_verification:function(e){try{var t=de.getInstance();return Promise.resolve(pe(e,t,e.payload.creation_options))}catch(e){return Promise.reject(e)}},thirdparty:function(e){try{var t,n=function(n){var i;if(t)return n;function a(t){var n;if(i)return t;var r=function(){if(e.isCached)return Promise.resolve(e.actions.back.run()).then(function(e){return n=1,e});e.saveToLocalStorage(),window.location.assign(e.payload.redirect_url)}();return r&&r.then?r.then(function(t){return n?t:e}):n?r:e}var c=function(){if((null==o?void 0:o.length)>0){var t="access_denied"===o?"third_party_access_denied":"technical_error",n=r.get("error_description");return s(["error","error_description"]),Promise.resolve(e.actions.back.run(null,{dispatchAfterStateChangeEvent:!1})).then(function(e){return e.error={code:t,message:n},e.dispatchAfterStateChangeEvent(),i=1,e})}}();return c&&c.then?c.then(a):a(c)},r=new URLSearchParams(window.location.search),i=r.get("hanko_token"),o=r.get("error"),s=function(e){e.forEach(function(e){return r.delete(e)});var t=r.toString()?"?"+r.toString():"";history.replaceState(null,null,""+window.location.pathname+t)},a=function(){if((null==i?void 0:i.length)>0)return s(["hanko_token"]),Promise.resolve(e.actions.exchange_token.run({token:i})).then(function(e){return t=1,e})}();return Promise.resolve(a&&a.then?a.then(n):n(a))}catch(e){return Promise.reject(e)}},success:function(e){try{var t=e.payload.claims,n=Date.parse(t.expiration)-Date.now();return e.removeFromLocalStorage(),e.hanko.relay.dispatchSessionCreatedEvent({claims:t,expirationSeconds:n}),Promise.resolve(e)}catch(e){return Promise.reject(e)}},account_deleted:function(e){try{return e.removeFromLocalStorage(),e.hanko.relay.dispatchUserDeletedEvent(),Promise.resolve(e)}catch(e){return Promise.reject(e)}}},me={login_init:function(e){try{return Promise.resolve(void function(){try{var t=de.getInstance();Promise.resolve(function(){if(e.payload.request_options)return function(n,r){try{var i=Promise.resolve(t.getConditionalWebauthnCredential(e.payload.request_options.publicKey)).then(function(t){return Promise.resolve(e.actions.webauthn_verify_assertion_response.run({assertion_response:t}))})}catch(e){return}return i&&i.then?i.then(void 0,function(){}):i}()}())}catch(e){return Promise.reject(e)}}())}catch(e){return Promise.reject(e)}}};function ye(e,t,n){if(!e.s){if(n instanceof ge){if(!n.s)return void(n.o=ye.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(ye.bind(null,e,t),ye.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}var ge=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,i=this.s;if(i){var o=1&i?t:n;if(o){try{ye(r,1,o(this.v))}catch(e){ye(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?ye(r,1,t?t(i):i):n?ye(r,1,n(i)):ye(r,2,i)}catch(e){ye(r,2,e)}},r},e}();function Se(e){return e instanceof ge&&1&e.s}var ke=/*#__PURE__*/function(){function t(e,t,n,r){var i=this;if(void 0===r&&(r={}),this.name=void 0,this.flowName=void 0,this.error=void 0,this.payload=void 0,this.actions=void 0,this.csrfToken=void 0,this.status=void 0,this.previousAction=void 0,this.isCached=void 0,this.cacheKey=void 0,this.hanko=void 0,this.invokedAction=void 0,this.excludeAutoSteps=void 0,this.autoStep=void 0,this.passkeyAutofillActivation=void 0,this.flowName=t,this.name=n.name,this.error=n.error,this.payload=n.payload,this.csrfToken=n.csrf_token,this.status=n.status,this.hanko=e,this.actions=this.buildActionMap(n.actions),this.name in ve){var o=ve[this.name];this.autoStep=function(){return o(i)}}if(this.name in me){var s=me[this.name];this.passkeyAutofillActivation=function(){return s(i)}}var a=r.dispatchAfterStateChangeEvent,c=void 0===a||a,u=r.excludeAutoSteps,h=r.previousAction,l=void 0===h?null:h,d=r.isCached,f=void 0!==d&&d,p=r.cacheKey,v=void 0===p?"hanko-flow-state":p;this.excludeAutoSteps=void 0===u?null:u,this.previousAction=l,this.isCached=f,this.cacheKey=v,c&&this.dispatchAfterStateChangeEvent()}var n=t.prototype;return n.buildActionMap=function(e){var t=this,n={};return Object.keys(e).forEach(function(r){n[r]=new be(e[r],t)}),new Proxy(n,{get:function(e,n){if(n in e)return e[n];var r="string"==typeof n?n:n.toString();return be.createDisabled(r,t)}})},n.dispatchAfterStateChangeEvent=function(){this.hanko.relay.dispatchAfterStateChangeEvent({state:this})},n.serialize=function(){return{flow_name:this.flowName,name:this.name,error:this.error,payload:this.payload,csrf_token:this.csrfToken,status:this.status,previous_action:this.previousAction,actions:Object.fromEntries(Object.entries(this.actions).map(function(e){var t=e[1];return[e[0],{action:t.name,href:t.href,inputs:t.inputs,description:null}]}))}},n.saveToLocalStorage=function(){localStorage.setItem(this.cacheKey,JSON.stringify(e({},this.serialize(),{is_cached:!0})))},n.removeFromLocalStorage=function(){localStorage.removeItem(this.cacheKey)},t.initializeFlowState=function(e,n,r,i){void 0===i&&(i={});try{var o,s=new t(e,n,r,i),a=function(){if("all"!=s.excludeAutoSteps)return function(e,t,n){for(var r;;){var i=e();if(Se(i)&&(i=i.v),!i)return o;if(i.then){r=0;break}var o=n();if(o&&o.then){if(!Se(o)){r=1;break}o=o.s}if(t){var s=t();if(s&&s.then&&!Se(s)){r=2;break}}}var a=new ge,c=ye.bind(null,a,2);return(0===r?i.then(h):1===r?o.then(u):s.then(l)).then(void 0,c),a;function u(r){o=r;do{if(t&&(s=t())&&s.then&&!Se(s))return void s.then(l).then(void 0,c);if(!(i=e())||Se(i)&&!i.v)return void ye(a,1,o);if(i.then)return void i.then(h).then(void 0,c);Se(o=n())&&(o=o.v)}while(!o||!o.then);o.then(u).then(void 0,c)}function h(e){e?(o=n())&&o.then?o.then(u).then(void 0,c):u(o):ye(a,1,o)}function l(){(i=e())?i.then?i.then(h).then(void 0,c):h(i):ye(a,1,o)}}(function(){var e;return!(o||!s||!s.autoStep||null!=(e=s.excludeAutoSteps)&&e.includes(s.name))},void 0,function(){return Promise.resolve(s.autoStep()).then(function(e){if(e.name==s.name)return o=1,e;s=e})})}();return Promise.resolve(a&&a.then?a.then(function(e){return o?e:s}):o?a:s)}catch(e){return Promise.reject(e)}},t.readFromLocalStorage=function(e){var t=localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(e){return}},t.create=function(n,r,i){void 0===i&&(i={});try{var o=i.cacheKey,s=void 0===o?"hanko-flow-state":o,a=i.loadFromCache;if(void 0===a||a){var c=t.readFromLocalStorage(s);if(c)return Promise.resolve(t.deserialize(n,c,e({},i,{cacheKey:s})))}return Promise.resolve(t.fetchState(n,"/"+r)).then(function(o){return t.initializeFlowState(n,r,o,e({},i,{cacheKey:s}))})}catch(e){return Promise.reject(e)}},t.deserialize=function(n,r,i){void 0===i&&(i={});try{return Promise.resolve(t.initializeFlowState(n,r.flow_name,r,e({},i,{previousAction:r.previous_action,isCached:r.is_cached})))}catch(e){return Promise.reject(e)}},t.fetchState=function(e,n,r){try{return Promise.resolve(function(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}(function(){return Promise.resolve(e.client.post(n,r)).then(function(e){return e.json()})},function(e){return t.createErrorResponse(e)}))}catch(e){return Promise.reject(e)}},t.createErrorResponse=function(e){return{actions:null,csrf_token:"",name:"error",payload:null,status:0,error:e}},t}(),be=/*#__PURE__*/function(){function t(e,t,n){void 0===n&&(n=!0),this.enabled=void 0,this.href=void 0,this.name=void 0,this.inputs=void 0,this.parentState=void 0,this.enabled=n,this.href=e.href,this.name=e.action,this.inputs=e.inputs,this.parentState=t}return t.createDisabled=function(e,n){return new t({action:e,href:"",inputs:{},description:"Disabled action"},n,!1)},t.prototype.run=function(t,n){void 0===t&&(t=null),void 0===n&&(n={});try{var r=this,i=r.parentState,o=i.name,s=i.hanko,a=i.flowName,c=i.csrfToken,u=i.invokedAction,h=i.excludeAutoSteps,l=i.cacheKey,d=n.dispatchAfterStateChangeEvent,f=void 0===d||d;if(!r.enabled)throw new Error("Action '"+r.name+"' is not enabled in state '"+o+"'");if(u)throw new Error("An action '"+u.name+"' has already been invoked on state '"+u.relatedStateName+"'. No further actions can be run.");r.parentState.invokedAction={name:r.name,relatedStateName:o},s.relay.dispatchBeforeStateChangeEvent({state:r.parentState});var p=e({},Object.keys(r.inputs).reduce(function(e,t){var n=r.inputs[t];return void 0!==n.value&&(e[t]=n.value),e},{}),t);return Promise.resolve(ke.fetchState(s,r.href,{input_data:p,csrf_token:c})).then(function(e){return r.parentState.removeFromLocalStorage(),ke.initializeFlowState(s,a,e,{dispatchAfterStateChangeEvent:f,excludeAutoSteps:h,previousAction:u,cacheKey:l})})}catch(e){return Promise.reject(e)}},t}(),we=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.getCurrent=function(){try{var e=this;return Promise.resolve(e.client.get("/me")).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new O;if(!t.ok)throw new g;var n=t.json();return Promise.resolve(e.client.get("/users/"+n.id)).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new O;if(!t.ok)throw new g;return t.json()})})}catch(e){return Promise.reject(e)}},r.logout=function(){try{var e=this;return Promise.resolve(e.client.post("/logout")).then(function(t){if(e.client.sessionTokenStorage.removeSessionToken(),e.client.cookie.removeAuthCookie(),e.client.dispatcher.dispatchUserLoggedOutEvent(),401===t.status);else if(!t.ok)throw new g})}catch(e){return Promise.reject(e)}},n}(H),Ce=/*#__PURE__*/function(n){function r(t,r){var i;(i=n.call(this)||this).session=void 0,i.user=void 0,i.cookie=void 0,i.client=void 0,i.relay=void 0;var o=e({timeout:13e3,cookieName:"hanko",localStorageKey:"hanko",sessionCheckInterval:3e4,sessionCheckChannelName:"hanko-session-check"},r);return i.client=new M(t,o),i.session=new W(t,o),i.user=new we(t,o),i.relay=new X(t,o),i.cookie=new K(o),i}t(r,n);var i=r.prototype;return i.setLang=function(e){this.client.lang=e},i.createState=function(e,t){return void 0===t&&(t={}),ke.create(this,e,t)},i.getUser=function(){try{return Promise.resolve(this.user.getCurrent())}catch(e){return Promise.reject(e)}},i.validateSession=function(){try{return Promise.resolve(this.session.validate())}catch(e){return Promise.reject(e)}},i.getSessionToken=function(){return this.cookie.getAuthCookie()},i.logout=function(){try{return Promise.resolve(this.user.logout())}catch(e){return Promise.reject(e)}},r}(v);exports.Action=be,exports.Client=H,exports.ConflictError=S,exports.CustomEventWithDetail=p,exports.EmailAddressAlreadyExistsError=T,exports.ForbiddenError=I,exports.Hanko=Ce,exports.HankoError=y,exports.HttpClient=M,exports.InvalidPasscodeError=C,exports.InvalidPasswordError=w,exports.InvalidWebauthnCredentialError=P,exports.MaxNumOfEmailAddressesReachedError=L,exports.MaxNumOfPasscodeAttemptsReachedError=E,exports.NotFoundError=A,exports.PasscodeExpiredError=x,exports.Relay=X,exports.RequestTimeoutError=k,exports.SessionClient=W,exports.State=ke,exports.TechnicalError=g,exports.ThirdPartyError=N,exports.TooManyRequestsError=_,exports.UnauthorizedError=O,exports.UserClient=we,exports.UserVerificationError=j,exports.WebauthnRequestCancelledError=b,exports.WebauthnSupport=G,exports.sessionCreatedType=c,exports.sessionExpiredType=u,exports.userDeletedType=l,exports.userLoggedOutType=h; //# sourceMappingURL=sdk.cjs.map