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,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e||self).hankoFrontendSdk={})}(this,function(e){function t(){return t=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},t.apply(this,arguments)}function n(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,r(e,t)}function i(e){return i=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},i(e)}function r(e,t){return r=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},r(e,t)}function o(e,t,n){return o=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},o.apply(null,arguments)}function s(e){var t="function"==typeof Map?new Map:void 0;return s=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,n)}function n(){return o(e,arguments,i(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),r(n,e)},s(e)}function a(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}var c=/*#__PURE__*/function(){function e(){}return e.throttle=function(e,t,n){void 0===n&&(n={});var i,r,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(i,r)};return function(){var n=Date.now();h||!1!==a||(h=n);var s=t-(n-h);i=this,r=[].slice.call(arguments),s<=0||s>t?(o&&(window.clearTimeout(o),o=null),h=n,e.apply(i,r)):o||!1===u||(o=window.setTimeout(l,s))}},e}(),u="hanko-session-created",h="hanko-session-expired",l="hanko-user-logged-out",d="hanko-user-deleted",f="hanko-after-state-change",v="hanko-before-state-change",p=/*#__PURE__*/function(e){function t(t,n){return e.call(this,t,{detail:n})||this}return n(t,e),t}(/*#__PURE__*/s(CustomEvent)),m=/*#__PURE__*/function(){function e(){this.throttleLimit=1e3,this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=c.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,i=e.once,r=void 0!==i&&i,o=e.throttle,s=this.wrapCallback(e.callback,void 0!==o&&o);return this._addEventListener(n,s,{once:r}),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,i){return this.addEventListenerWithType(e.mapAddEventListenerParams(t,n,i))},t.onSessionCreated=function(e,t){return this.addEventListener(u,{callback:e,once:t},!0)},t.onSessionExpired=function(e,t){return this.addEventListener(h,{callback:e,once:t},!0)},t.onUserLoggedOut=function(e,t){return this.addEventListener(l,{callback:e,once:t})},t.onUserDeleted=function(e,t){return this.addEventListener(d,{callback:e,once:t})},t.onAfterStateChange=function(e,t){return this.addEventListener(f,{callback:e,once:t},!1)},t.onBeforeStateChange=function(e,t){return this.addEventListener(v,{callback:e,once:t},!1)},e}(),y=/*#__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(u,e)},t.dispatchSessionExpiredEvent=function(){this.dispatch(h,null)},t.dispatchUserLoggedOutEvent=function(){this.dispatch(l,null)},t.dispatchUserDeletedEvent=function(){this.dispatch(d,null)},t.dispatchAfterStateChangeEvent=function(e){this.dispatch(f,e)},t.dispatchBeforeStateChangeEvent=function(e){this.dispatch(v,e)},e}(),g=/*#__PURE__*/function(e){function t(n,i,r){var o;return(o=e.call(this,n)||this).code=void 0,o.cause=void 0,o.code=i,o.cause=r,Object.setPrototypeOf(a(o),t.prototype),o}return n(t,e),t}(/*#__PURE__*/s(Error)),S=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Technical error","somethingWentWrong",n)||this,Object.setPrototypeOf(a(i),t.prototype),i}return n(t,e),t}(g),k=/*#__PURE__*/function(e){function t(n,i){var r;return r=e.call(this,"Conflict error","conflict",i)||this,Object.setPrototypeOf(a(r),t.prototype),r}return n(t,e),t}(g),b=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Request timed out error","requestTimeout",n)||this,Object.setPrototypeOf(a(i),t.prototype),i}return n(t,e),t}(g),w=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Request cancelled error","requestCancelled",n)||this,Object.setPrototypeOf(a(i),t.prototype),i}return n(t,e),t}(g),C=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Invalid password error","invalidPassword",n)||this,Object.setPrototypeOf(a(i),t.prototype),i}return n(t,e),t}(g),P=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Invalid Passcode error","invalidPasscode",n)||this,Object.setPrototypeOf(a(i),t.prototype),i}return n(t,e),t}(g),E=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Invalid WebAuthn credential error","invalidWebauthnCredential",n)||this,Object.setPrototypeOf(a(i),t.prototype),i}return n(t,e),t}(g),x=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Passcode expired error","passcodeExpired",n)||this,Object.setPrototypeOf(a(i),t.prototype),i}return n(t,e),t}(g),A=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Maximum number of Passcode attempts reached error","passcodeAttemptsReached",n)||this,Object.setPrototypeOf(a(i),t.prototype),i}return n(t,e),t}(g),_=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Not found error","notFound",n)||this,Object.setPrototypeOf(a(i),t.prototype),i}return n(t,e),t}(g),O=/*#__PURE__*/function(e){function t(n,i){var r;return(r=e.call(this,"Too many requests error","tooManyRequests",i)||this).retryAfter=void 0,r.retryAfter=n,Object.setPrototypeOf(a(r),t.prototype),r}return n(t,e),t}(g),j=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Unauthorized error","unauthorized",n)||this,Object.setPrototypeOf(a(i),t.prototype),i}return n(t,e),t}(g),I=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Forbidden error","forbidden",n)||this,Object.setPrototypeOf(a(i),t.prototype),i}return n(t,e),t}(g),L=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"User verification error","userVerification",n)||this,Object.setPrototypeOf(a(i),t.prototype),i}return n(t,e),t}(g),T=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",n)||this,Object.setPrototypeOf(a(i),t.prototype),i}return n(t,e),t}(g),N=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"The email address already exists","emailAddressAlreadyExistsError",n)||this,Object.setPrototypeOf(a(i),t.prototype),i}return n(t,e),t}(g),R=/*#__PURE__*/function(e){function t(n,i){var r;return r=e.call(this,"An error occurred during third party sign up/sign in",n,i)||this,Object.setPrototypeOf(a(r),t.prototype),r}return n(t,e),t}(g);function D(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)e[i]=n[i]}return e}var K=function e(t,n){function i(e,i,r){if("undefined"!=typeof document){"number"==typeof(r=D({},n,r)).expires&&(r.expires=new Date(Date.now()+864e5*r.expires)),r.expires&&(r.expires=r.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var s in r)r[s]&&(o+="; "+s,!0!==r[s]&&(o+="="+r[s].split(";")[0]));return document.cookie=e+"="+t.write(i,e)+o}}return Object.create({set:i,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],i={},r=0;r<n.length;r++){var o=n[r].split("="),s=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(i[a]=t.read(s,a),e===a)break}catch(e){}}return e?i[e]:i}},remove:function(e,t){i(e,"",D({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,D({},this.attributes,t))},withConverter:function(t){return e(D({},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:"/"}),q=/*#__PURE__*/function(){function e(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=e.prototype;return n.getAuthCookie=function(){return K.get(this.authCookieName)},n.setAuthCookie=function(e,n){var i={secure:!0,sameSite:this.authCookieSameSite};void 0!==this.authCookieDomain&&(i.domain=this.authCookieDomain);var r=t({},i,n);if(("none"===r.sameSite||"None"===r.sameSite)&&!1===r.secure)throw new S(new Error("Secure attribute must be set when SameSite=None"));K.set(this.authCookieName,e,r)},n.removeAuthCookie=function(){K.remove(this.authCookieName)},e}(),F=/*#__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}(),M=/*#__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}(),H=/*#__PURE__*/function(){function e(e,n){var i;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=e,this.timeout=null!=(i=n.timeout)?i:13e3,this.dispatcher=new y,this.cookie=new q(t({},n)),this.sessionTokenStorage=new F({keyName:n.cookieName}),this.lang=n.lang,this.sessionTokenLocation=n.sessionTokenLocation}var n=e.prototype;return n._fetch=function(e,t,n){void 0===n&&(n=new XMLHttpRequest);var i=this,r=this.api+e,o=this.timeout,s=this.getAuthToken(),a=this.lang;return new Promise(function(e,c){n.open(t.method,r,!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(){i.processHeaders(n),e(new M(n))},n.onerror=function(){c(new S)},n.ontimeout=function(){c(new b)},n.send(t.body?t.body.toString():null)})},n.processHeaders=function(e){var t="",n=0,i="";if(e.getAllResponseHeaders().split("\r\n").forEach(function(r){var o=r.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")&&(i=e.getResponseHeader("X-Session-Retention"))}),t){var r=new RegExp("^https://"),o=!!this.api.match(r)&&!!window.location.href.match(r),s="session"===i?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)}},e}(),W=function(e,t){this.client=void 0,this.client=new H(e,t)},z=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return n(t,e),t.prototype.validate=function(){try{return Promise.resolve(this.client.get("/sessions/validate")).then(function(e){if(!e.ok)throw new S;return Promise.resolve(e.json())})}catch(e){return Promise.reject(e)}},t}(W),B=/*#__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}(),J=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)},V=/*#__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 i=this.calcTimeToNextCheck(e);this.sessionExpiresSoon(t)?this.scheduleSessionExpiry(i):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)}},i)},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}(),X=/*#__PURE__*/function(){function e(e,t,n,i){var r=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":r.onSessionExpired(t);break;case"sessionCreated":r.onSessionCreated(t);break;case"requestLeadership":r.onLeadershipRequested(t)}},this.onSessionExpired=t,this.onSessionCreated=n,this.onLeadershipRequested=i,this.channel=new BroadcastChannel(e),this.channel.onmessage=this.handleMessage}return e.prototype.post=function(e){this.channel.postMessage(e)},e}(),G=/*#__PURE__*/function(e){function t(t,n){var i;(i=e.call(this)||this).listener=new m,i.checkInterval=3e4,i.client=void 0,i.sessionState=void 0,i.windowActivityManager=void 0,i.scheduler=void 0,i.sessionChannel=void 0,i.isLoggedIn=void 0,i.client=new z(t,n),n.sessionCheckInterval&&(i.checkInterval=n.sessionCheckInterval<3e3?3e3:n.sessionCheckInterval),i.sessionState=new B(n.cookieName+"_session_state"),i.sessionChannel=new X(i.getSessionCheckChannelName(n.sessionTokenLocation,n.sessionCheckChannelName),function(){return i.onChannelSessionExpired()},function(e){return i.onChannelSessionCreated(e)},function(){return i.onChannelLeadershipRequested()}),i.scheduler=new V(i.checkInterval,function(){return i.checkSession()},function(){return i.onSessionExpired()}),i.windowActivityManager=new J(function(){return i.startSessionCheck()},function(){return i.scheduler.stop()});var r=Date.now(),o=i.sessionState.load();return i.isLoggedIn=r<o.expiration,i.initializeEventListeners(),i.startSessionCheck(),i}n(t,e);var i=t.prototype;return i.initializeEventListeners=function(){var e=this;this.listener.onSessionCreated(function(t){var n=t.claims,i=Date.parse(n.expiration),r=Date.now();e.isLoggedIn=!0,e.sessionState.save({expiration:i,lastCheck:r}),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()})},i.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)}},i.checkSession=function(){try{var e=this,t=Date.now();return Promise.resolve(e.client.validate()).then(function(n){var i=n.is_valid,r=n.claims,o=n.expiration_time,s=o?Date.parse(o):0;return!i&&e.isLoggedIn&&e.dispatchSessionExpiredEvent(),i?(e.isLoggedIn=!0,e.sessionState.save({lastCheck:t,expiration:s})):(e.isLoggedIn=!1,e.sessionState.save(null),e.sessionChannel.post({action:"sessionExpired"})),{is_valid:i,claims:r,expiration:s}})}catch(e){return Promise.reject(e)}},i.onSessionExpired=function(){this.isLoggedIn&&(this.isLoggedIn=!1,this.sessionState.save(null),this.sessionChannel.post({action:"sessionExpired"}),this.dispatchSessionExpiredEvent())},i.onChannelSessionExpired=function(){this.isLoggedIn&&(this.isLoggedIn=!1,this.dispatchSessionExpiredEvent())},i.onChannelSessionCreated=function(e){var t=e.claims,n=Date.now(),i=Date.parse(t.expiration)-n;this.isLoggedIn=!0,this.dispatchSessionCreatedEvent({claims:t,expirationSeconds:i})},i.onChannelLeadershipRequested=function(){this.windowActivityManager.hasFocus()||this.scheduler.stop()},i.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},t}(y),$=/*#__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 Q(e){const t="==".slice(0,(4-e.length%4)%4),n=e.replace(/-/g,"+").replace(/_/g,"/")+t,i=atob(n),r=new ArrayBuffer(i.length),o=new Uint8Array(r);for(let e=0;e<i.length;e++)o[e]=i.charCodeAt(e);return r}function Y(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 Z="copy",ee="convert";function te(e,t,n){if(t===Z)return n;if(t===ee)return e(n);if(t instanceof Array)return n.map(n=>te(e,t[0],n));if(t instanceof Object){const i={};for(const[r,o]of Object.entries(t)){if(o.derive){const e=o.derive(n);void 0!==e&&(n[r]=e)}if(r in n)i[r]=null!=n[r]?te(e,o.schema,n[r]):null;else if(o.required)throw new Error(`Missing key: ${r}`)}return i}}function ne(e,t){return{required:!0,schema:e,derive:t}}function ie(e){return{required:!0,schema:e}}function re(e){return{required:!1,schema:e}}var oe={type:ie(Z),id:ie(ee),transports:re(Z)},se={appid:re(Z),appidExclude:re(Z),credProps:re(Z)},ae={appid:re(Z),appidExclude:re(Z),credProps:re(Z)},ce={publicKey:ie({rp:ie(Z),user:ie({id:ie(ee),name:ie(Z),displayName:ie(Z)}),challenge:ie(ee),pubKeyCredParams:ie(Z),timeout:re(Z),excludeCredentials:re([oe]),authenticatorSelection:re(Z),attestation:re(Z),extensions:re(se)}),signal:re(Z)},ue={type:ie(Z),id:ie(Z),rawId:ie(ee),authenticatorAttachment:re(Z),response:ie({clientDataJSON:ie(ee),attestationObject:ie(ee),transports:ne(Z,e=>{var t;return(null==(t=e.getTransports)?void 0:t.call(e))||[]})}),clientExtensionResults:ne(ae,e=>e.getClientExtensionResults())},he={mediation:re(Z),publicKey:ie({challenge:ie(ee),timeout:re(Z),rpId:re(Z),allowCredentials:re([oe]),userVerification:re(Z),extensions:re(se)}),signal:re(Z)},le={type:ie(Z),id:ie(Z),rawId:ie(ee),authenticatorAttachment:re(Z),response:ie({clientDataJSON:ie(ee),authenticatorData:ie(ee),signature:ie(ee),userHandle:ie(ee)}),clientExtensionResults:ne(ae,e=>e.getClientExtensionResults())};async function de(e){const t=await navigator.credentials.get(function(e){return te(Q,he,e)}(e));return function(e){return te(Y,le,e)}(t)}var fe=/*#__PURE__*/function(){function e(){this.abortController=new AbortController}e.getInstance=function(){return e.instance||(e.instance=new e),e.instance};var n=e.prototype;return n.createAbortSignal=function(){return this.abortController.abort(),this.abortController=new AbortController,this.abortController.signal},n.getWebauthnCredential=function(e){try{return Promise.resolve(de(t({},e,{signal:this.createAbortSignal()})))}catch(e){return Promise.reject(e)}},n.getConditionalWebauthnCredential=function(e){try{return Promise.resolve(de({publicKey:e,mediation:"conditional",signal:this.createAbortSignal()}))}catch(e){return Promise.reject(e)}},n.createWebauthnCredential=function(e){try{return Promise.resolve(async function(e){return t=await navigator.credentials.create(function(e){return te(Q,ce,e)}(e)),te(Y,ue,t);var t}(t({},e,{signal:this.createAbortSignal()})))}catch(e){return Promise.reject(e)}},e}();function ve(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}fe.instance=null;var pe=function(e,t,n,i,r){void 0===i&&(i="webauthn_credential_already_exists"),void 0===r&&(r="Webauthn credential already exists");try{return Promise.resolve(ve(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:i,message:r},e})}))}catch(e){return Promise.reject(e)}},me={preflight:function(e){try{var t=e.actions.register_client_capabilities,n=t.run,i=$.supported();return Promise.resolve($.isConditionalMediationAvailable()).then(function(e){return Promise.resolve($.isPlatformAuthenticatorAvailable()).then(function(r){return Promise.resolve(n.call(t,{webauthn_available:i,webauthn_conditional_mediation_available:e,webauthn_platform_authenticator_available:r}))})})}catch(e){return Promise.reject(e)}},login_passkey:function(e){try{var t=fe.getInstance();return Promise.resolve(ve(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=fe.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=fe.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 r;if(t)return n;function a(t){var n;if(r)return t;var i=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 i&&i.then?i.then(function(t){return n?t:e}):n?i:e}var c=function(){if((null==o?void 0:o.length)>0){var t="access_denied"===o?"third_party_access_denied":"technical_error",n=i.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(),r=1,e})}}();return c&&c.then?c.then(a):a(c)},i=new URLSearchParams(window.location.search),r=i.get("hanko_token"),o=i.get("error"),s=function(e){e.forEach(function(e){return i.delete(e)});var t=i.toString()?"?"+i.toString():"";history.replaceState(null,null,""+window.location.pathname+t)},a=function(){if((null==r?void 0:r.length)>0)return s(["hanko_token"]),Promise.resolve(e.actions.exchange_token.run({token:r})).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)}}},ye={login_init:function(e){try{return Promise.resolve(void function(){try{var t=fe.getInstance();Promise.resolve(function(){if(e.payload.request_options)return function(n,i){try{var r=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 r&&r.then?r.then(void 0,function(){}):r}()}())}catch(e){return Promise.reject(e)}}())}catch(e){return Promise.reject(e)}}};function ge(e,t,n){if(!e.s){if(n instanceof Se){if(!n.s)return void(n.o=ge.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(ge.bind(null,e,t),ge.bind(null,e,2));e.s=t,e.v=n;const i=e.o;i&&i(e)}}var Se=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var i=new e,r=this.s;if(r){var o=1&r?t:n;if(o){try{ge(i,1,o(this.v))}catch(e){ge(i,2,e)}return i}return this}return this.o=function(e){try{var r=e.v;1&e.s?ge(i,1,t?t(r):r):n?ge(i,1,n(r)):ge(i,2,r)}catch(e){ge(i,2,e)}},i},e}();function ke(e){return e instanceof Se&&1&e.s}var be=/*#__PURE__*/function(){function e(e,t,n,i){var r=this;if(void 0===i&&(i={}),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 me){var o=me[this.name];this.autoStep=function(){return o(r)}}if(this.name in ye){var s=ye[this.name];this.passkeyAutofillActivation=function(){return s(r)}}var a=i.dispatchAfterStateChangeEvent,c=void 0===a||a,u=i.excludeAutoSteps,h=i.previousAction,l=void 0===h?null:h,d=i.isCached,f=void 0!==d&&d,v=i.cacheKey,p=void 0===v?"hanko-flow-state":v;this.excludeAutoSteps=void 0===u?null:u,this.previousAction=l,this.isCached=f,this.cacheKey=p,c&&this.dispatchAfterStateChangeEvent()}var n=e.prototype;return n.buildActionMap=function(e){var t=this,n={};return Object.keys(e).forEach(function(i){n[i]=new we(e[i],t)}),new Proxy(n,{get:function(e,n){if(n in e)return e[n];var i="string"==typeof n?n:n.toString();return we.createDisabled(i,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(t({},this.serialize(),{is_cached:!0})))},n.removeFromLocalStorage=function(){localStorage.removeItem(this.cacheKey)},e.initializeFlowState=function(t,n,i,r){void 0===r&&(r={});try{var o,s=new e(t,n,i,r),a=function(){if("all"!=s.excludeAutoSteps)return function(e,t,n){for(var i;;){var r=e();if(ke(r)&&(r=r.v),!r)return o;if(r.then){i=0;break}var o=n();if(o&&o.then){if(!ke(o)){i=1;break}o=o.s}if(t){var s=t();if(s&&s.then&&!ke(s)){i=2;break}}}var a=new Se,c=ge.bind(null,a,2);return(0===i?r.then(h):1===i?o.then(u):s.then(l)).then(void 0,c),a;function u(i){o=i;do{if(t&&(s=t())&&s.then&&!ke(s))return void s.then(l).then(void 0,c);if(!(r=e())||ke(r)&&!r.v)return void ge(a,1,o);if(r.then)return void r.then(h).then(void 0,c);ke(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):ge(a,1,o)}function l(){(r=e())?r.then?r.then(h).then(void 0,c):h(r):ge(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)}},e.readFromLocalStorage=function(e){var t=localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(e){return}},e.create=function(n,i,r){void 0===r&&(r={});try{var o=r.cacheKey,s=void 0===o?"hanko-flow-state":o,a=r.loadFromCache;if(void 0===a||a){var c=e.readFromLocalStorage(s);if(c)return Promise.resolve(e.deserialize(n,c,t({},r,{cacheKey:s})))}return Promise.resolve(e.fetchState(n,"/"+i)).then(function(o){return e.initializeFlowState(n,i,o,t({},r,{cacheKey:s}))})}catch(e){return Promise.reject(e)}},e.deserialize=function(n,i,r){void 0===r&&(r={});try{return Promise.resolve(e.initializeFlowState(n,i.flow_name,i,t({},r,{previousAction:i.previous_action,isCached:i.is_cached})))}catch(e){return Promise.reject(e)}},e.fetchState=function(t,n,i){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(t.client.post(n,i)).then(function(e){return e.json()})},function(t){return e.createErrorResponse(t)}))}catch(e){return Promise.reject(e)}},e.createErrorResponse=function(e){return{actions:null,csrf_token:"",name:"error",payload:null,status:0,error:e}},e}(),we=/*#__PURE__*/function(){function e(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 e.createDisabled=function(t,n){return new e({action:t,href:"",inputs:{},description:"Disabled action"},n,!1)},e.prototype.run=function(e,n){void 0===e&&(e=null),void 0===n&&(n={});try{var i=this,r=i.parentState,o=r.name,s=r.hanko,a=r.flowName,c=r.csrfToken,u=r.invokedAction,h=r.excludeAutoSteps,l=r.cacheKey,d=n.dispatchAfterStateChangeEvent,f=void 0===d||d;if(!i.enabled)throw new Error("Action '"+i.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.");i.parentState.invokedAction={name:i.name,relatedStateName:o},s.relay.dispatchBeforeStateChangeEvent({state:i.parentState});var v=t({},Object.keys(i.inputs).reduce(function(e,t){var n=i.inputs[t];return void 0!==n.value&&(e[t]=n.value),e},{}),e);return Promise.resolve(be.fetchState(s,i.href,{input_data:v,csrf_token:c})).then(function(e){return i.parentState.removeFromLocalStorage(),be.initializeFlowState(s,a,e,{dispatchAfterStateChangeEvent:f,excludeAutoSteps:h,previousAction:u,cacheKey:l})})}catch(e){return Promise.reject(e)}},e}(),Ce=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}n(t,e);var i=t.prototype;return i.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 j;if(!t.ok)throw new S;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 j;if(!t.ok)throw new S;return t.json()})})}catch(e){return Promise.reject(e)}},i.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 S})}catch(e){return Promise.reject(e)}},t}(W),Pe=/*#__PURE__*/function(e){function i(n,i){var r;(r=e.call(this)||this).session=void 0,r.user=void 0,r.cookie=void 0,r.client=void 0,r.relay=void 0;var o=t({timeout:13e3,cookieName:"hanko",localStorageKey:"hanko",sessionCheckInterval:3e4,sessionCheckChannelName:"hanko-session-check"},i);return r.client=new H(n,o),r.session=new z(n,o),r.user=new Ce(n,o),r.relay=new G(n,o),r.cookie=new q(o),r}n(i,e);var r=i.prototype;return r.setLang=function(e){this.client.lang=e},r.createState=function(e,t){return void 0===t&&(t={}),be.create(this,e,t)},r.getUser=function(){try{return Promise.resolve(this.user.getCurrent())}catch(e){return Promise.reject(e)}},r.validateSession=function(){try{return Promise.resolve(this.session.validate())}catch(e){return Promise.reject(e)}},r.getSessionToken=function(){return this.cookie.getAuthCookie()},r.logout=function(){try{return Promise.resolve(this.user.logout())}catch(e){return Promise.reject(e)}},i}(m);e.Action=we,e.Client=W,e.ConflictError=k,e.CustomEventWithDetail=p,e.EmailAddressAlreadyExistsError=N,e.ForbiddenError=I,e.Hanko=Pe,e.HankoError=g,e.HttpClient=H,e.InvalidPasscodeError=P,e.InvalidPasswordError=C,e.InvalidWebauthnCredentialError=E,e.MaxNumOfEmailAddressesReachedError=T,e.MaxNumOfPasscodeAttemptsReachedError=A,e.NotFoundError=_,e.PasscodeExpiredError=x,e.Relay=G,e.RequestTimeoutError=b,e.SessionClient=z,e.State=be,e.TechnicalError=S,e.ThirdPartyError=R,e.TooManyRequestsError=O,e.UnauthorizedError=j,e.UserClient=Ce,e.UserVerificationError=L,e.WebauthnRequestCancelledError=w,e.WebauthnSupport=$,e.sessionCreatedType=u,e.sessionExpiredType=h,e.userDeletedType=d,e.userLoggedOutType=l}); //# sourceMappingURL=sdk.umd.js.map