@teamhanko/hanko-frontend-sdk 0.4.0-alpha → 0.5.4-beta

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/sdk.umd.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t||self).hankoFrontendSdk={})}(this,function(t){function e(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,n(t,e)}function r(t){return r=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},r(t)}function n(t,e){return n=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},n(t,e)}function i(t,e,r){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(t){return!1}}()?Reflect.construct.bind():function(t,e,r){var i=[null];i.push.apply(i,e);var o=new(Function.bind.apply(t,i));return r&&n(o,r.prototype),o},i.apply(null,arguments)}function o(t){var e="function"==typeof Map?new Map:void 0;return o=function(t){if(null===t||-1===Function.toString.call(t).indexOf("[native code]"))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,o)}function o(){return i(t,arguments,r(this).constructor)}return o.prototype=Object.create(t.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),n(o,t)},o(t)}function s(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}var a=/*#__PURE__*/function(t){function r(e,n,i){var o;return(o=t.call(this,e)||this).code=void 0,o.cause=void 0,o.code=n,o.cause=i,Object.setPrototypeOf(s(o),r.prototype),o}return e(r,t),r}(/*#__PURE__*/o(Error)),u=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Technical error","somethingWentWrong",e)||this,Object.setPrototypeOf(s(n),r.prototype),n}return e(r,t),r}(a),c=/*#__PURE__*/function(t){function r(e,n){var i;return i=t.call(this,"Conflict error","conflict",n)||this,Object.setPrototypeOf(s(i),r.prototype),i}return e(r,t),r}(a),h=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Request timed out error","requestTimeout",e)||this,Object.setPrototypeOf(s(n),r.prototype),n}return e(r,t),r}(a),l=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Request cancelled error","requestCancelled",e)||this,Object.setPrototypeOf(s(n),r.prototype),n}return e(r,t),r}(a),d=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Invalid password error","invalidPassword",e)||this,Object.setPrototypeOf(s(n),r.prototype),n}return e(r,t),r}(a),f=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Invalid Passcode error","invalidPasscode",e)||this,Object.setPrototypeOf(s(n),r.prototype),n}return e(r,t),r}(a),p=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Invalid WebAuthn credential error","invalidWebauthnCredential",e)||this,Object.setPrototypeOf(s(n),r.prototype),n}return e(r,t),r}(a),w=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Passcode expired error","passcodeExpired",e)||this,Object.setPrototypeOf(s(n),r.prototype),n}return e(r,t),r}(a),v=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Maximum number of Passcode attempts reached error","passcodeAttemptsReached",e)||this,Object.setPrototypeOf(s(n),r.prototype),n}return e(r,t),r}(a),m=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Not found error","notFound",e)||this,Object.setPrototypeOf(s(n),r.prototype),n}return e(r,t),r}(a),y=/*#__PURE__*/function(t){function r(e,n){var i;return(i=t.call(this,"Too many requests error","tooManyRequests",n)||this).retryAfter=void 0,i.retryAfter=e,Object.setPrototypeOf(s(i),r.prototype),i}return e(r,t),r}(a),g=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Unauthorized error","unauthorized",e)||this,Object.setPrototypeOf(s(n),r.prototype),n}return e(r,t),r}(a),P=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"User verification error","userVerification",e)||this,Object.setPrototypeOf(s(n),r.prototype),n}return e(r,t),r}(a),b=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",e)||this,Object.setPrototypeOf(s(n),r.prototype),n}return e(r,t),r}(a),C=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"The email address already exists","emailAddressAlreadyExistsError",e)||this,Object.setPrototypeOf(s(n),r.prototype),n}return e(r,t),r}(a),A=/*#__PURE__*/function(t){function r(e,n){var i;return i=t.call(this,"An error occurred during third party sign up/sign in",e,n)||this,Object.setPrototypeOf(s(i),r.prototype),i}return e(r,t),r}(a);function S(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)t[n]=r[n]}return t}var j=function t(e,r){function n(t,n,i){if("undefined"!=typeof document){"number"==typeof(i=S({},r,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),t=encodeURIComponent(t).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=t+"="+e.write(n,t)+o}}return Object.create({set:n,get:function(t){if("undefined"!=typeof document&&(!arguments.length||t)){for(var r=document.cookie?document.cookie.split("; "):[],n={},i=0;i<r.length;i++){var o=r[i].split("="),s=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(n[a]=e.read(s,a),t===a)break}catch(t){}}return t?n[t]:n}},remove:function(t,e){n(t,"",S({},e,{expires:-1}))},withAttributes:function(e){return t(this.converter,S({},this.attributes,e))},withConverter:function(e){return t(S({},this.converter,e),this.attributes)}},{attributes:{value:Object.freeze(r)},converter:{value:Object.freeze(e)}})}({read:function(t){return'"'===t[0]&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"}),O=/*#__PURE__*/function(){function t(t){this._xhr=void 0,this._xhr=t}return t.prototype.get=function(t){return this._xhr.getResponseHeader(t)},t}(),k=/*#__PURE__*/function(){function t(t){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 O(t),this.ok=t.status>=200&&t.status<=299,this.status=t.status,this.statusText=t.statusText,this.url=t.responseURL,this.xhr=t}var e=t.prototype;return e.json=function(){return this._decodedJSON||(this._decodedJSON=JSON.parse(this.xhr.response)),this._decodedJSON},e.parseRetryAfterHeader=function(){var t=parseInt(this.headers.get("Retry-After"),10);return isNaN(t)?0:t},t}(),R=/*#__PURE__*/function(){function t(t,e){void 0===e&&(e=13e3),this.timeout=void 0,this.api=void 0,this.authCookieName="hanko",this.api=t,this.timeout=e}var e=t.prototype;return e._fetch=function(t,e,r){void 0===r&&(r=new XMLHttpRequest);var n=this,i=this.api+t,o=this.timeout,s=this._getAuthCookie();return new Promise(function(t,a){r.open(e.method,i,!0),r.setRequestHeader("Accept","application/json"),r.setRequestHeader("Content-Type","application/json"),s&&r.setRequestHeader("Authorization","Bearer "+s),r.timeout=o,r.withCredentials=!0,r.onload=function(){if(r.getAllResponseHeaders().split("\r\n").filter(function(t){return t.toLowerCase().startsWith("x-auth-token")}).length){var e=r.getResponseHeader("X-Auth-Token");e&&n._setAuthCookie(e)}t(new k(r))},r.onerror=function(){a(new u)},r.ontimeout=function(){a(new h)},r.send(e.body?e.body.toString():null)})},e._getAuthCookie=function(){return j.get(this.authCookieName)},e._setAuthCookie=function(t){var e=!!this.api.match("^https://");j.set(this.authCookieName,t,{secure:e})},e.removeAuthCookie=function(){j.remove(this.authCookieName)},e.get=function(t){return this._fetch(t,{method:"GET"})},e.post=function(t,e){return this._fetch(t,{method:"POST",body:JSON.stringify(e)})},e.put=function(t,e){return this._fetch(t,{method:"PUT",body:JSON.stringify(e)})},e.patch=function(t,e){return this._fetch(t,{method:"PATCH",body:JSON.stringify(e)})},e.delete=function(t){return this._fetch(t,{method:"DELETE"})},t}(),E=function(t,e){void 0===e&&(e=13e3),this.client=void 0,this.client=new R(t,e)},_=/*#__PURE__*/function(t){function r(){return t.apply(this,arguments)||this}return e(r,t),r.prototype.get=function(){try{return Promise.resolve(this.client.get("/.well-known/config")).then(function(t){if(!t.ok)throw new u;return t.json()})}catch(t){return Promise.reject(t)}},r}(E),T=/*#__PURE__*/function(){function t(t){void 0===t&&(t="hanko"),this.key=void 0,this.ls=void 0,this.key=t,this.ls={}}var e=t.prototype;return e.read=function(){var t;try{var e=localStorage.getItem(this.key),r=decodeURIComponent(decodeURI(window.atob(e)));t=JSON.parse(r)}catch(t){return this.ls={},this}return this.ls=t,this},e.write=function(){var t=JSON.stringify(this.ls),e=window.btoa(encodeURI(encodeURIComponent(t)));return localStorage.setItem(this.key,e),this},t.timeToRemainingSeconds=function(t){return void 0===t&&(t=0),t-Math.floor(Date.now()/1e3)},t.remainingSecondsToTime=function(t){return void 0===t&&(t=0),Math.floor(Date.now()/1e3)+t},t}(),x=/*#__PURE__*/function(t){function r(){return t.apply(this,arguments)||this}return e(r,t),r.prototype.getUserState=function(t){var e;return(e=this.ls).users||(e.users={}),Object.prototype.hasOwnProperty.call(this.ls.users,t)||(this.ls.users[t]={}),this.ls.users[t]},r}(T),I=/*#__PURE__*/function(t){function r(){return t.apply(this,arguments)||this}e(r,t);var n=r.prototype;return n.getState=function(e){var r;return(r=t.prototype.getUserState.call(this,e)).passcode||(r.passcode={})},n.read=function(){return t.prototype.read.call(this),this},n.getActiveID=function(t){return this.getState(t).id},n.setActiveID=function(t,e){return this.getState(t).id=e,this},n.getEmailID=function(t){return this.getState(t).emailID},n.setEmailID=function(t,e){return this.getState(t).emailID=e,this},n.reset=function(t){var e=this.getState(t);return delete e.id,delete e.ttl,delete e.resendAfter,delete e.emailID,this},n.getTTL=function(t){return T.timeToRemainingSeconds(this.getState(t).ttl)},n.setTTL=function(t,e){return this.getState(t).ttl=T.remainingSecondsToTime(e),this},n.getResendAfter=function(t){return T.timeToRemainingSeconds(this.getState(t).resendAfter)},n.setResendAfter=function(t,e){return this.getState(t).resendAfter=T.remainingSecondsToTime(e),this},r}(x),U=/*#__PURE__*/function(t){function r(e,r){var n;return void 0===r&&(r=13e3),(n=t.call(this,e,r)||this).state=void 0,n.state=new I,n}e(r,t);var n=r.prototype;return n.initialize=function(t,e,r){try{var n=this;n.state.read();var i=n.state.getTTL(t),o=n.state.getActiveID(t),s=n.state.getEmailID(t),a=n.state.getResendAfter(t);if(a>0)throw new y(a);if(!r&&i>0&&e===s)return Promise.resolve({id:o,ttl:i});var c={user_id:t};return e&&(c.email_id=e),Promise.resolve(n.client.post("/passcode/login/initialize",c)).then(function(r){if(429===r.status)throw a=r.parseRetryAfterHeader(),n.state.setResendAfter(t,a).write(),new y(a);if(401===r.status)throw new g;if(!r.ok)throw new u;var i=r.json();return n.state.setActiveID(t,i.id).setTTL(t,i.ttl),e&&n.state.setEmailID(t,e),n.state.write(),i})}catch(t){return Promise.reject(t)}},n.finalize=function(t,e){try{var r=this,n=r.state.read().getActiveID(t);if(r.state.getTTL(t)<=0)throw new w;return Promise.resolve(r.client.post("/passcode/login/finalize",{id:n,code:e})).then(function(e){if(401===e.status)throw new f;if(410===e.status)throw r.state.reset(t).write(),new v;if(!e.ok)throw new u;r.state.reset(t).write()})}catch(t){return Promise.reject(t)}},n.getTTL=function(t){return this.state.read().getTTL(t)},n.getResendAfter=function(t){return this.state.read().getResendAfter(t)},r}(E),N=/*#__PURE__*/function(t){function r(){return t.apply(this,arguments)||this}e(r,t);var n=r.prototype;return n.getState=function(e){var r;return(r=t.prototype.getUserState.call(this,e)).password||(r.password={})},n.read=function(){return t.prototype.read.call(this),this},n.getRetryAfter=function(t){return T.timeToRemainingSeconds(this.getState(t).retryAfter)},n.setRetryAfter=function(t,e){return this.getState(t).retryAfter=T.remainingSecondsToTime(e),this},r}(x),D=/*#__PURE__*/function(t){function r(e,r){var n;return void 0===r&&(r=13e3),(n=t.call(this,e,r)||this).passwordState=void 0,n.passcodeState=void 0,n.passwordState=new N,n.passcodeState=new I,n}e(r,t);var n=r.prototype;return n.login=function(t,e){try{var r=this;return Promise.resolve(r.client.post("/password/login",{user_id:t,password:e})).then(function(e){if(401===e.status)throw new d;if(429===e.status){var n=e.parseRetryAfterHeader();throw r.passwordState.read().setRetryAfter(t,n).write(),new y(n)}if(!e.ok)throw new u;r.passcodeState.read().reset(t).write()})}catch(t){return Promise.reject(t)}},n.update=function(t,e){try{return Promise.resolve(this.client.put("/password",{user_id:t,password:e})).then(function(t){if(401===t.status)throw new g;if(!t.ok)throw new u})}catch(t){return Promise.reject(t)}},n.getRetryAfter=function(t){return this.passwordState.read().getRetryAfter(t)},r}(E),q=/*#__PURE__*/function(t){function r(){return t.apply(this,arguments)||this}e(r,t);var n=r.prototype;return n.getInfo=function(t){try{return Promise.resolve(this.client.post("/user",{email:t})).then(function(t){if(404===t.status)throw new m;if(!t.ok)throw new u;return t.json()})}catch(t){return Promise.reject(t)}},n.create=function(t){try{return Promise.resolve(this.client.post("/users",{email:t})).then(function(t){if(409===t.status)throw new c;if(!t.ok)throw new u;return t.json()})}catch(t){return Promise.reject(t)}},n.getCurrent=function(){try{var t=this;return Promise.resolve(t.client.get("/me")).then(function(e){if(400===e.status||401===e.status||404===e.status)throw new g;if(!e.ok)throw new u;var r=e.json();return Promise.resolve(t.client.get("/users/"+r.id)).then(function(t){if(400===t.status||401===t.status||404===t.status)throw new g;if(!t.ok)throw new u;return t.json()})})}catch(t){return Promise.reject(t)}},n.delete=function(){try{var t=this;return Promise.resolve(t.client.delete("/user")).then(function(e){if(!e.ok){if(401===e.status)throw new g;throw new u}t.client.removeAuthCookie()})}catch(t){return Promise.reject(t)}},n.logout=function(){try{var t=this;return Promise.resolve(t.client.post("/logout")).then(function(e){if(t.client.removeAuthCookie(),401===e.status);else if(!e.ok)throw new u})}catch(t){return Promise.reject(t)}},r}(E);function M(t){const e="==".slice(0,(4-t.length%4)%4),r=t.replace(/-/g,"+").replace(/_/g,"/")+e,n=atob(r),i=new ArrayBuffer(n.length),o=new Uint8Array(i);for(let t=0;t<n.length;t++)o[t]=n.charCodeAt(t);return i}function K(t){const e=new Uint8Array(t);let r="";for(const t of e)r+=String.fromCharCode(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}var W="copy",z="convert";function H(t,e,r){if(e===W)return r;if(e===z)return t(r);if(e instanceof Array)return r.map(r=>H(t,e[0],r));if(e instanceof Object){const n={};for(const[i,o]of Object.entries(e)){if(o.derive){const t=o.derive(r);void 0!==t&&(r[i]=t)}if(i in r)n[i]=null!=r[i]?H(t,o.schema,r[i]):null;else if(o.required)throw new Error(`Missing key: ${i}`)}return n}}function L(t,e){return{required:!0,schema:t,derive:e}}function J(t){return{required:!0,schema:t}}function B(t){return{required:!1,schema:t}}var F={type:J(W),id:J(z),transports:B(W)},V={appid:B(W),appidExclude:B(W),credProps:B(W)},X={appid:B(W),appidExclude:B(W),credProps:B(W)},G={publicKey:J({rp:J(W),user:J({id:J(z),name:J(W),displayName:J(W)}),challenge:J(z),pubKeyCredParams:J(W),timeout:B(W),excludeCredentials:B([F]),authenticatorSelection:B(W),attestation:B(W),extensions:B(V)}),signal:B(W)},$={type:J(W),id:J(W),rawId:J(z),authenticatorAttachment:B(W),response:J({clientDataJSON:J(z),attestationObject:J(z),transports:L(W,t=>{var e;return(null==(e=t.getTransports)?void 0:e.call(t))||[]})}),clientExtensionResults:L(X,t=>t.getClientExtensionResults())},Q={mediation:B(W),publicKey:J({challenge:J(z),timeout:B(W),rpId:B(W),allowCredentials:B([F]),userVerification:B(W),extensions:B(V)}),signal:B(W)},Y={type:J(W),id:J(W),rawId:J(z),authenticatorAttachment:B(W),response:J({clientDataJSON:J(z),authenticatorData:J(z),signature:J(z),userHandle:J(z)}),clientExtensionResults:L(X,t=>t.getClientExtensionResults())};async function Z(t){const e=await navigator.credentials.create(function(t){return H(M,G,t)}(t));return function(t){return H(K,$,t)}(e)}async function tt(t){const e=await navigator.credentials.get(function(t){return H(M,Q,t)}(t));return function(t){return H(K,Y,t)}(e)}var et=/*#__PURE__*/function(){function t(){}return t.supported=function(){return!!(navigator.credentials&&navigator.credentials.create&&navigator.credentials.get&&window.PublicKeyCredential)},t.isPlatformAuthenticatorAvailable=function(){try{return this.supported()&&window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?Promise.resolve(window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()):Promise.resolve(!1)}catch(t){return Promise.reject(t)}},t.isSecurityKeySupported=function(){try{return void 0!==window.PublicKeyCredential&&window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported?Promise.resolve(window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported()):Promise.resolve(this.supported())}catch(t){return Promise.reject(t)}},t.isConditionalMediationAvailable=function(){try{return window.PublicKeyCredential&&window.PublicKeyCredential.isConditionalMediationAvailable?Promise.resolve(window.PublicKeyCredential.isConditionalMediationAvailable()):Promise.resolve(!1)}catch(t){return Promise.reject(t)}},t}(),rt=/*#__PURE__*/function(t){function r(){return t.apply(this,arguments)||this}e(r,t);var n=r.prototype;return n.getState=function(e){var r;return(r=t.prototype.getUserState.call(this,e)).webauthn||(r.webauthn={})},n.read=function(){return t.prototype.read.call(this),this},n.getCredentials=function(t){var e;return(e=this.getState(t)).credentials||(e.credentials=[])},n.addCredential=function(t,e){return this.getCredentials(t).push(e),this},n.matchCredentials=function(t,e){return this.getCredentials(t).filter(function(t){return e.find(function(e){return e.id===t})}).map(function(t){return{id:t}})},r}(x);function nt(t,e){try{var r=t()}catch(t){return e(t)}return r&&r.then?r.then(void 0,e):r}var it=/*#__PURE__*/function(t){function r(e,r){var n;return void 0===r&&(r=13e3),(n=t.call(this,e,r)||this).webauthnState=void 0,n.passcodeState=void 0,n.controller=void 0,n._getCredential=tt,n._createCredential=Z,n.webauthnState=new rt,n.passcodeState=new I,n}e(r,t);var n=r.prototype;return n.login=function(t,e){try{var r=this;return Promise.resolve(r.client.post("/webauthn/login/initialize",{user_id:t})).then(function(n){var i;function o(e){return i?e:Promise.resolve(r.client.post("/webauthn/login/finalize",s)).then(function(e){if(400===e.status||401===e.status)throw new p;if(!e.ok)throw new u;var n=e.json();r.webauthnState.read().addCredential(n.user_id,n.credential_id).write(),r.passcodeState.read().reset(t).write()})}if(!n.ok)throw new u;var s,a=n.json();a.signal=r._createAbortSignal(),e&&(a.mediation="conditional");var c=nt(function(){return Promise.resolve(r._getCredential(a)).then(function(t){s=t})},function(t){throw new l(t)});return c&&c.then?c.then(o):o(c)})}catch(t){return Promise.reject(t)}},n.register=function(){try{var t=this;return Promise.resolve(t.client.post("/webauthn/registration/initialize")).then(function(e){function r(e){return n.transports=n.response.transports,Promise.resolve(t.client.post("/webauthn/registration/finalize",n)).then(function(e){if(e.status>=400&&e.status<=499){if(422===e.status)throw new P;throw new g}if(!e.ok)throw new u;var r=e.json();t.webauthnState.read().addCredential(r.user_id,r.credential_id).write()})}if(e.status>=400&&e.status<=499)throw new g;if(!e.ok)throw new u;var n,i=e.json();i.signal=t._createAbortSignal();var o=nt(function(){return Promise.resolve(t._createCredential(i)).then(function(t){n=t})},function(t){throw new l(t)});return o&&o.then?o.then(r):r()})}catch(t){return Promise.reject(t)}},n.listCredentials=function(){try{return Promise.resolve(this.client.get("/webauthn/credentials")).then(function(t){if(401===t.status)throw new g;if(!t.ok)throw new u;return t.json()})}catch(t){return Promise.reject(t)}},n.updateCredential=function(t,e){try{return Promise.resolve(this.client.patch("/webauthn/credentials/"+t,{name:e})).then(function(t){if(401===t.status)throw new g;if(!t.ok)throw new u})}catch(t){return Promise.reject(t)}},n.deleteCredential=function(t){try{return Promise.resolve(this.client.delete("/webauthn/credentials/"+t)).then(function(t){if(401===t.status)throw new g;if(!t.ok)throw new u})}catch(t){return Promise.reject(t)}},n.shouldRegister=function(t){try{var e=et.supported();if(!t.webauthn_credentials||!t.webauthn_credentials.length)return Promise.resolve(e);var r=this.webauthnState.read().matchCredentials(t.id,t.webauthn_credentials);return Promise.resolve(e&&!r.length)}catch(t){return Promise.reject(t)}},n._createAbortSignal=function(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal},r}(E),ot=/*#__PURE__*/function(t){function r(){return t.apply(this,arguments)||this}e(r,t);var n=r.prototype;return n.list=function(){try{return Promise.resolve(this.client.get("/emails")).then(function(t){if(401===t.status)throw new g;if(!t.ok)throw new u;return t.json()})}catch(t){return Promise.reject(t)}},n.create=function(t){try{return Promise.resolve(this.client.post("/emails",{address:t})).then(function(t){if(t.ok)return t.json();if(400===t.status)throw new C;if(401===t.status)throw new g;if(409===t.status)throw new b;throw new u})}catch(t){return Promise.reject(t)}},n.setPrimaryEmail=function(t){try{return Promise.resolve(this.client.post("/emails/"+t+"/set_primary")).then(function(t){if(401===t.status)throw new g;if(!t.ok)throw new u})}catch(t){return Promise.reject(t)}},n.delete=function(t){try{return Promise.resolve(this.client.delete("/emails/"+t)).then(function(t){if(401===t.status)throw new g;if(!t.ok)throw new u})}catch(t){return Promise.reject(t)}},r}(E),st=/*#__PURE__*/function(t){function r(e,r){return void 0===r&&(r=13e3),t.call(this,e,r)||this}e(r,t);var n=r.prototype;return n.auth=function(t,e){try{var r=new URL("/thirdparty/auth",this.client.api);if(!t)throw new A("somethingWentWrong",new Error("provider missing from request"));if(!e)throw new A("somethingWentWrong",new Error("redirectTo missing from request"));return r.searchParams.append("provider",t),r.searchParams.append("redirect_to",e),window.location.assign(r.href),Promise.resolve()}catch(t){return Promise.reject(t)}},n.getError=function(){var t=new URLSearchParams(window.location.search),e=t.get("error"),r=t.get("error_description");if(e){var n="";switch(e){case"access_denied":n="thirdPartyAccessDenied";break;case"user_conflict":n="emailAddressAlreadyExistsError";break;case"multiple_accounts":n="thirdPartyMultipleAccounts";break;case"unverified_email":n="thirdPartyUnverifiedEmail";break;case"email_maxnum":n="maxNumOfEmailAddressesReached";break;default:n="somethingWentWrong"}return new A(n,new Error(r))}},r}(E),at=/*#__PURE__*/function(t){function r(e,r){return void 0===r&&(r=13e3),t.call(this,e,r)||this}return e(r,t),r.prototype.validate=function(){try{var t=new URLSearchParams(window.location.search).get("hanko_token");return t?(window.history.replaceState(null,null,window.location.pathname),Promise.resolve(this.client.post("/token",{value:t})).then(function(t){if(!t.ok)throw new u})):Promise.resolve()}catch(t){return Promise.reject(t)}},r}(E);t.ConfigClient=_,t.ConflictError=c,t.EmailAddressAlreadyExistsError=C,t.EmailClient=ot,t.Hanko=function(t,e){void 0===e&&(e=13e3),this.api=void 0,this.config=void 0,this.user=void 0,this.webauthn=void 0,this.password=void 0,this.passcode=void 0,this.email=void 0,this.thirdParty=void 0,this.token=void 0,this.api=t,this.config=new _(t,e),this.user=new q(t,e),this.webauthn=new it(t,e),this.password=new D(t,e),this.passcode=new U(t,e),this.email=new ot(t,e),this.thirdParty=new st(t,e),this.token=new at(t,e)},t.HankoError=a,t.InvalidPasscodeError=f,t.InvalidPasswordError=d,t.InvalidWebauthnCredentialError=p,t.MaxNumOfEmailAddressesReachedError=b,t.MaxNumOfPasscodeAttemptsReachedError=v,t.NotFoundError=m,t.PasscodeClient=U,t.PasscodeExpiredError=w,t.PasswordClient=D,t.RequestTimeoutError=h,t.TechnicalError=u,t.ThirdPartyClient=st,t.ThirdPartyError=A,t.TokenClient=at,t.TooManyRequestsError=y,t.UnauthorizedError=g,t.UserClient=q,t.UserVerificationError=P,t.WebauthnClient=it,t.WebauthnRequestCancelledError=l,t.WebauthnSupport=et});
1
+ !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(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(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)),c=/*#__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}(a),u=/*#__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}(a),d=/*#__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}(a),h=/*#__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}(a),l=/*#__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}(a),f=/*#__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}(a),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}(a),v=/*#__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}(a),w=/*#__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}(a),m=/*#__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}(a),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}(a),g=/*#__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}(a),E=/*#__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}(a),S=/*#__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}(a),P=/*#__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}(a),b=/*#__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}(a),k=/*#__PURE__*/function(){function e(e){this.key=void 0,this.ls=void 0,this.key=e,this.ls={}}var t=e.prototype;return t.read=function(){var e;try{var t=localStorage.getItem(this.key),n=decodeURIComponent(decodeURI(window.atob(t)));e=JSON.parse(n)}catch(e){return this.ls={},this}return this.ls=e,this},t.write=function(){var e=JSON.stringify(this.ls),t=window.btoa(encodeURI(encodeURIComponent(e)));return localStorage.setItem(this.key,t),this},e.timeToRemainingSeconds=function(e){return void 0===e&&(e=0),e-Math.floor(Date.now()/1e3)},e.remainingSecondsToTime=function(e){return void 0===e&&(e=0),Math.floor(Date.now()/1e3)+e},e}(),C=/*#__PURE__*/function(e){function n(){return e.call(this,"hanko_session")||this}t(n,e);var r=n.prototype;return r.read=function(){return e.prototype.read.call(this),this},r.getState=function(){var e;return(e=this.ls).session||(e.session={expiry:0,userID:""}),this.ls.session},r.getExpirationSeconds=function(){return k.timeToRemainingSeconds(this.getState().expiry)},r.setExpirationSeconds=function(e){return this.getState().expiry=k.remainingSecondsToTime(e),this},r.getUserID=function(){return this.getState().userID},r.setUserID=function(e){return this.getState().userID=e,this},r.reset=function(){var e=this.getState();return delete e.expiry,delete e.userID,this},n}(k),_=/*#__PURE__*/function(e){function n(){return e.call(this,"hanko")||this}return t(n,e),n.prototype.getUserState=function(e){var t;return(t=this.ls).users||(t.users={}),Object.prototype.hasOwnProperty.call(this.ls.users,e)||(this.ls.users[e]={}),this.ls.users[e]},n}(k),x=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.getState=function(t){var n;return(n=e.prototype.getUserState.call(this,t)).passcode||(n.passcode={})},r.read=function(){return e.prototype.read.call(this),this},r.getActiveID=function(e){return this.getState(e).id},r.setActiveID=function(e,t){return this.getState(e).id=t,this},r.getEmailID=function(e){return this.getState(e).emailID},r.setEmailID=function(e,t){return this.getState(e).emailID=t,this},r.reset=function(e){var t=this.getState(e);return delete t.id,delete t.ttl,delete t.resendAfter,delete t.emailID,this},r.getTTL=function(e){return k.timeToRemainingSeconds(this.getState(e).ttl)},r.setTTL=function(e,t){return this.getState(e).ttl=k.remainingSecondsToTime(t),this},r.getResendAfter=function(e){return k.timeToRemainingSeconds(this.getState(e).resendAfter)},r.setResendAfter=function(e,t){return this.getState(e).resendAfter=k.remainingSecondsToTime(t),this},n}(_),O="hanko-session-created",A="hanko-session-resumed",T="hanko-session-expired",j="hanko-user-logged-out",R="hanko-user-deleted",D="hanko-auth-flow-completed",I="hanko-session-not-present",L=/*#__PURE__*/function(e){function n(t,n){return e.call(this,t,{detail:n})||this}return t(n,e),n}(/*#__PURE__*/o(CustomEvent)),U=/*#__PURE__*/function(){function e(){this._dispatchEvent=document.dispatchEvent.bind(document)}var t=e.prototype;return t.dispatch=function(e,t){this._dispatchEvent(new L(e,t))},t.dispatchSessionResumedEvent=function(e){this.dispatch(A,e)},t.dispatchSessionCreatedEvent=function(e){this.dispatch(O,e)},t.dispatchSessionExpiredEvent=function(){this.dispatch(T,null)},t.dispatchUserLoggedOutEvent=function(){this.dispatch(j,null)},t.dispatchUserDeletedEvent=function(){this.dispatch(R,null)},t.dispatchAuthFlowCompletedEvent=function(e){this.dispatch(D,e)},t.dispatchSessionNotPresent=function(){this.dispatch(I,null)},e}();function N(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 H=function e(t,n){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=N({},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,"",N({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,N({},this.attributes,t))},withConverter:function(t){return e(N({},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:"/"}),W=/*#__PURE__*/function(){function e(){this.authCookieName="hanko"}var t=e.prototype;return t.getAuthCookie=function(){return H.get(this.authCookieName)},t.setAuthCookie=function(e,t){void 0===t&&(t=!0),H.set(this.authCookieName,e,{secure:t})},t.removeAuthCookie=function(){H.remove(this.authCookieName)},e}(),q=/*#__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 q(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}(),F=/*#__PURE__*/function(){function e(e,t){void 0===t&&(t=13e3),this.timeout=void 0,this.api=void 0,this.sessionState=void 0,this.passcodeState=void 0,this.dispatcher=void 0,this.cookie=void 0,this.api=e,this.timeout=t,this.sessionState=new C,this.passcodeState=new x,this.dispatcher=new U,this.cookie=new W}var t=e.prototype;return t._fetch=function(e,t,n){void 0===n&&(n=new XMLHttpRequest);var r=this.api+e,i=this.timeout,o=this.cookie.getAuthCookie();return new Promise(function(e,s){n.open(t.method,r,!0),n.setRequestHeader("Accept","application/json"),n.setRequestHeader("Content-Type","application/json"),o&&n.setRequestHeader("Authorization","Bearer "+o),n.timeout=i,n.withCredentials=!0,n.onload=function(){var t=new M(n);e(t)},n.onerror=function(){s(new c)},n.ontimeout=function(){s(new d)},n.send(t.body?t.body.toString():null)})},t.processResponseHeadersOnLogin=function(e,t){var n="",r=0;if(t.xhr.getAllResponseHeaders().split("\r\n").forEach(function(e){var i=e.toLowerCase();i.startsWith("x-auth-token")?n=t.headers.getResponseHeader("X-Auth-Token"):i.startsWith("x-session-lifetime")&&(r=parseInt(t.headers.getResponseHeader("X-Session-Lifetime"),10))}),n){var i=!!this.api.match("^https://");this.cookie.setAuthCookie(n,i)}this.passcodeState.read().reset(e).write(),r>0&&(this.sessionState.read(),this.sessionState.setExpirationSeconds(r),this.sessionState.setUserID(e),this.sessionState.write(),this.dispatcher.dispatchSessionCreatedEvent({jwt:n,userID:e,expirationSeconds:r}))},t.get=function(e){return this._fetch(e,{method:"GET"})},t.post=function(e,t){return this._fetch(e,{method:"POST",body:JSON.stringify(t)})},t.put=function(e,t){return this._fetch(e,{method:"PUT",body:JSON.stringify(t)})},t.patch=function(e,t){return this._fetch(e,{method:"PATCH",body:JSON.stringify(t)})},t.delete=function(e){return this._fetch(e,{method:"DELETE"})},e}(),K=function(e,t){void 0===t&&(t=13e3),this.client=void 0,this.client=new F(e,t)},z=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}return t(n,e),n.prototype.get=function(){try{return Promise.resolve(this.client.get("/.well-known/config")).then(function(e){if(!e.ok)throw new c;return e.json()})}catch(e){return Promise.reject(e)}},n}(K),J=/*#__PURE__*/function(e){function n(t,n){var r;return void 0===n&&(n=13e3),(r=e.call(this,t,n)||this).state=void 0,r.state=new x,r}t(n,e);var r=n.prototype;return r.initialize=function(e,t,n){try{var r=this;r.state.read();var i=r.state.getTTL(e),o=r.state.getActiveID(e),s=r.state.getEmailID(e),a=r.state.getResendAfter(e);if(a>0)throw new y(a);if(!n&&i>0&&t===s)return Promise.resolve({id:o,ttl:i});var u={user_id:e};return t&&(u.email_id=t),Promise.resolve(r.client.post("/passcode/login/initialize",u)).then(function(n){if(429===n.status)throw a=n.parseNumericHeader("Retry-After"),r.state.setResendAfter(e,a).write(),new y(a);if(!n.ok)throw new c;var i=n.json();return r.state.setActiveID(e,i.id).setTTL(e,i.ttl),t&&r.state.setEmailID(e,t),r.state.write(),i})}catch(e){return Promise.reject(e)}},r.finalize=function(e,t){try{var n=this,r=n.state.read().getActiveID(e);if(n.state.getTTL(e)<=0)throw new v;return Promise.resolve(n.client.post("/passcode/login/finalize",{id:r,code:t})).then(function(t){if(401===t.status)throw new f;if(410===t.status)throw n.state.reset(e).write(),new w;if(!t.ok)throw new c;n.client.processResponseHeadersOnLogin(e,t)})}catch(e){return Promise.reject(e)}},r.getTTL=function(e){return this.state.read().getTTL(e)},r.getResendAfter=function(e){return this.state.read().getResendAfter(e)},n}(K),B=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.getState=function(t){var n;return(n=e.prototype.getUserState.call(this,t)).password||(n.password={})},r.read=function(){return e.prototype.read.call(this),this},r.getRetryAfter=function(e){return k.timeToRemainingSeconds(this.getState(e).retryAfter)},r.setRetryAfter=function(e,t){return this.getState(e).retryAfter=k.remainingSecondsToTime(t),this},n}(_),V=/*#__PURE__*/function(e){function n(t,n){var r;return void 0===n&&(n=13e3),(r=e.call(this,t,n)||this).passwordState=void 0,r.passcodeState=void 0,r.passwordState=new B,r.passcodeState=new x,r}t(n,e);var r=n.prototype;return r.login=function(e,t){try{var n=this;return Promise.resolve(n.client.post("/password/login",{user_id:e,password:t})).then(function(t){if(401===t.status)throw new l;if(429===t.status){var r=t.parseNumericHeader("Retry-After");throw n.passwordState.read().setRetryAfter(e,r).write(),new y(r)}if(!t.ok)throw new c;n.client.processResponseHeadersOnLogin(e,t)})}catch(e){return Promise.reject(e)}},r.update=function(e,t){try{var n=this;return Promise.resolve(n.client.put("/password",{user_id:e,password:t})).then(function(e){if(401===e.status)throw n.client.dispatcher.dispatchSessionExpiredEvent(),new g;if(!e.ok)throw new c})}catch(e){return Promise.reject(e)}},r.getRetryAfter=function(e){return this.passwordState.read().getRetryAfter(e)},n}(K),X=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.getInfo=function(e){try{return Promise.resolve(this.client.post("/user",{email:e})).then(function(e){if(404===e.status)throw new m;if(!e.ok)throw new c;return e.json()})}catch(e){return Promise.reject(e)}},r.create=function(e){try{var t=this;return Promise.resolve(t.client.post("/users",{email:e})).then(function(e){if(409===e.status)throw new u;if(!e.ok)throw new c;var n=e.json();return n&&n.user_id&&t.client.processResponseHeadersOnLogin(n.user_id,e),n})}catch(e){return Promise.reject(e)}},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 g;if(!t.ok)throw new c;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 g;if(!t.ok)throw new c;return t.json()})})}catch(e){return Promise.reject(e)}},r.delete=function(){try{var e=this;return Promise.resolve(e.client.delete("/user")).then(function(t){if(t.ok)return e.client.cookie.removeAuthCookie(),e.client.sessionState.reset().write(),void e.client.dispatcher.dispatchUserDeletedEvent();if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new g;throw new c})}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.cookie.removeAuthCookie(),e.client.sessionState.reset().write(),e.client.dispatcher.dispatchUserLoggedOutEvent(),401===t.status);else if(!t.ok)throw new c})}catch(e){return Promise.reject(e)}},n}(K);function G(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 $(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 Q="copy",Y="convert";function Z(e,t,n){if(t===Q)return n;if(t===Y)return e(n);if(t instanceof Array)return n.map(n=>Z(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]?Z(e,o.schema,n[i]):null;else if(o.required)throw new Error(`Missing key: ${i}`)}return r}}function ee(e,t){return{required:!0,schema:e,derive:t}}function te(e){return{required:!0,schema:e}}function ne(e){return{required:!1,schema:e}}var re={type:te(Q),id:te(Y),transports:ne(Q)},ie={appid:ne(Q),appidExclude:ne(Q),credProps:ne(Q)},oe={appid:ne(Q),appidExclude:ne(Q),credProps:ne(Q)},se={publicKey:te({rp:te(Q),user:te({id:te(Y),name:te(Q),displayName:te(Q)}),challenge:te(Y),pubKeyCredParams:te(Q),timeout:ne(Q),excludeCredentials:ne([re]),authenticatorSelection:ne(Q),attestation:ne(Q),extensions:ne(ie)}),signal:ne(Q)},ae={type:te(Q),id:te(Q),rawId:te(Y),authenticatorAttachment:ne(Q),response:te({clientDataJSON:te(Y),attestationObject:te(Y),transports:ee(Q,e=>{var t;return(null==(t=e.getTransports)?void 0:t.call(e))||[]})}),clientExtensionResults:ee(oe,e=>e.getClientExtensionResults())},ce={mediation:ne(Q),publicKey:te({challenge:te(Y),timeout:ne(Q),rpId:ne(Q),allowCredentials:ne([re]),userVerification:ne(Q),extensions:ne(ie)}),signal:ne(Q)},ue={type:te(Q),id:te(Q),rawId:te(Y),authenticatorAttachment:ne(Q),response:te({clientDataJSON:te(Y),authenticatorData:te(Y),signature:te(Y),userHandle:te(Y)}),clientExtensionResults:ee(oe,e=>e.getClientExtensionResults())};async function de(e){const t=await navigator.credentials.create(function(e){return Z(G,se,e)}(e));return function(e){return Z($,ae,e)}(t)}async function he(e){const t=await navigator.credentials.get(function(e){return Z(G,ce,e)}(e));return function(e){return Z($,ue,e)}(t)}var le=/*#__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}(),fe=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.getState=function(t){var n;return(n=e.prototype.getUserState.call(this,t)).webauthn||(n.webauthn={})},r.read=function(){return e.prototype.read.call(this),this},r.getCredentials=function(e){var t;return(t=this.getState(e)).credentials||(t.credentials=[])},r.addCredential=function(e,t){return this.getCredentials(e).push(t),this},r.matchCredentials=function(e,t){return this.getCredentials(e).filter(function(e){return t.find(function(t){return t.id===e})}).map(function(e){return{id:e}})},n}(_);function pe(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var ve=/*#__PURE__*/function(e){function n(t,n){var r;return void 0===n&&(n=13e3),(r=e.call(this,t,n)||this).webauthnState=void 0,r.passcodeState=void 0,r.controller=void 0,r._getCredential=he,r._createCredential=de,r.webauthnState=new fe,r.passcodeState=new x,r}t(n,e);var r=n.prototype;return r.login=function(e,t){try{var n=this;return Promise.resolve(n.client.post("/webauthn/login/initialize",{user_id:e})).then(function(e){var r;function i(e){return r?e:Promise.resolve(n.client.post("/webauthn/login/finalize",o)).then(function(e){if(400===e.status||401===e.status)throw new p;if(!e.ok)throw new c;var t=e.json();return n.webauthnState.read().addCredential(t.user_id,t.credential_id).write(),n.client.processResponseHeadersOnLogin(t.user_id,e),t})}if(!e.ok)throw new c;var o,s=e.json();s.signal=n._createAbortSignal(),t&&(s.mediation="conditional");var a=pe(function(){return Promise.resolve(n._getCredential(s)).then(function(e){o=e})},function(e){throw new h(e)});return a&&a.then?a.then(i):i(a)})}catch(e){return Promise.reject(e)}},r.register=function(){try{var e=this;return Promise.resolve(e.client.post("/webauthn/registration/initialize")).then(function(t){function n(t){return r.transports=r.response.transports,Promise.resolve(e.client.post("/webauthn/registration/finalize",r)).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new g;if(422===t.status)throw new E;if(!t.ok)throw new c;var n=t.json();e.webauthnState.read().addCredential(n.user_id,n.credential_id).write()})}if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new g;if(!t.ok)throw new c;var r,i=t.json();i.signal=e._createAbortSignal();var o=pe(function(){return Promise.resolve(e._createCredential(i)).then(function(e){r=e})},function(e){throw new h(e)});return o&&o.then?o.then(n):n()})}catch(e){return Promise.reject(e)}},r.listCredentials=function(){try{var e=this;return Promise.resolve(e.client.get("/webauthn/credentials")).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new g;if(!t.ok)throw new c;return t.json()})}catch(e){return Promise.reject(e)}},r.updateCredential=function(e,t){try{var n=this;return Promise.resolve(n.client.patch("/webauthn/credentials/"+e,{name:t})).then(function(e){if(401===e.status)throw n.client.dispatcher.dispatchSessionExpiredEvent(),new g;if(!e.ok)throw new c})}catch(e){return Promise.reject(e)}},r.deleteCredential=function(e){try{var t=this;return Promise.resolve(t.client.delete("/webauthn/credentials/"+e)).then(function(e){if(401===e.status)throw t.client.dispatcher.dispatchSessionExpiredEvent(),new g;if(!e.ok)throw new c})}catch(e){return Promise.reject(e)}},r.shouldRegister=function(e){try{var t=le.supported();if(!e.webauthn_credentials||!e.webauthn_credentials.length)return Promise.resolve(t);var n=this.webauthnState.read().matchCredentials(e.id,e.webauthn_credentials);return Promise.resolve(t&&!n.length)}catch(e){return Promise.reject(e)}},r._createAbortSignal=function(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal},n}(K),we=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.list=function(){try{var e=this;return Promise.resolve(e.client.get("/emails")).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new g;if(!t.ok)throw new c;return t.json()})}catch(e){return Promise.reject(e)}},r.create=function(e){try{var t=this;return Promise.resolve(t.client.post("/emails",{address:e})).then(function(e){if(e.ok)return e.json();if(400===e.status)throw new P;if(401===e.status)throw t.client.dispatcher.dispatchSessionExpiredEvent(),new g;if(409===e.status)throw new S;throw new c})}catch(e){return Promise.reject(e)}},r.setPrimaryEmail=function(e){try{var t=this;return Promise.resolve(t.client.post("/emails/"+e+"/set_primary")).then(function(e){if(401===e.status)throw t.client.dispatcher.dispatchSessionExpiredEvent(),new g;if(!e.ok)throw new c})}catch(e){return Promise.reject(e)}},r.delete=function(e){try{var t=this;return Promise.resolve(t.client.delete("/emails/"+e)).then(function(e){if(401===e.status)throw t.client.dispatcher.dispatchSessionExpiredEvent(),new g;if(!e.ok)throw new c})}catch(e){return Promise.reject(e)}},n}(K),me=/*#__PURE__*/function(e){function n(t,n){return void 0===n&&(n=13e3),e.call(this,t,n)||this}t(n,e);var r=n.prototype;return r.auth=function(e,t){try{var n=new URL("/thirdparty/auth",this.client.api);if(!e)throw new b("somethingWentWrong",new Error("provider missing from request"));if(!t)throw new b("somethingWentWrong",new Error("redirectTo missing from request"));return n.searchParams.append("provider",e),n.searchParams.append("redirect_to",t),window.location.assign(n.href),Promise.resolve()}catch(e){return Promise.reject(e)}},r.getError=function(){var e=new URLSearchParams(window.location.search),t=e.get("error"),n=e.get("error_description");if(t){var r="";switch(t){case"access_denied":r="thirdPartyAccessDenied";break;case"user_conflict":r="emailAddressAlreadyExistsError";break;case"multiple_accounts":r="thirdPartyMultipleAccounts";break;case"unverified_email":r="thirdPartyUnverifiedEmail";break;case"email_maxnum":r="maxNumOfEmailAddressesReached";break;default:r="somethingWentWrong"}return new b(r,new Error(n))}},n}(K),ye=/*#__PURE__*/function(e){function n(t,n){return void 0===n&&(n=13e3),e.call(this,t,n)||this}return t(n,e),n.prototype.validate=function(){try{var e=this,t=new URLSearchParams(window.location.search).get("hanko_token");return t?(window.history.replaceState(null,null,window.location.pathname),Promise.resolve(e.client.post("/token",{value:t})).then(function(t){if(!t.ok)throw new c;var n=t.json();e.client.processResponseHeadersOnLogin(n.user_id,t)})):Promise.resolve()}catch(e){return Promise.reject(e)}},n}(K),ge=/*#__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,d=0,h=function(){d=!1===a?0:Date.now(),o=null,e.apply(r,i)};return function(){var n=Date.now();d||!1!==a||(d=n);var s=t-(n-d);r=this,i=[].slice.call(arguments),s<=0||s>t?(o&&(window.clearTimeout(o),o=null),d=n,e.apply(r,i)):o||!1===u||(o=window.setTimeout(h,s))}},e}(),Ee=/*#__PURE__*/function(){function e(){this.throttleLimit=1e3,this._cleanupFunctions=[],this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=ge.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);this._addEventListener(n,s,{once:i});var a=function(){return t._removeEventListener(n,s)};return this._cleanupFunctions.push(a),a},t.removeEventListeners=function(){this._cleanupFunctions.forEach(function(e){return e()}),this._cleanupFunctions=[]},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(O,{callback:e,once:t},!0)},t.onSessionResumed=function(e,t){return this.addEventListener(A,{callback:e,once:t},!0)},t.onSessionExpired=function(e,t){return this.addEventListener(T,{callback:e,once:t},!0)},t.onUserLoggedOut=function(e,t){return this.addEventListener(j,{callback:e,once:t})},t.onUserDeleted=function(e,t){return this.addEventListener(R,{callback:e,once:t})},t.onAuthFlowCompleted=function(e,t){return this.addEventListener(D,{callback:e,once:t})},t.onSessionNotPresent=function(e,t){return this.addEventListener(I,{callback:e,once:t},!0)},e}(),Se=/*#__PURE__*/function(){function e(){this._tasks=[]}var t=e.prototype;return t.removeTask=function(e){window.clearTimeout(e.timeoutID),this._tasks=this._tasks.filter(function(t){return t!==e})},t.removeTasksWithType=function(e){var t=this;this._tasks.filter(function(t){return t.type===e}).forEach(function(e){return t.removeTask(e)})},t.scheduleTask=function(e,t,n){var r=this,i={timeoutID:window.setTimeout(function(){t(),r.removeTask(i)},1e3*n),type:e,func:t};this._tasks.push(i)},e}(),Pe=/*#__PURE__*/function(e){function n(){var t;return(t=e.call(this)||this)._listener=new Ee,t._scheduler=new Se,t._sessionState=new C,t._cookie=new W,t.scheduleSessionExpiredEvent=function(e){t._scheduler.removeTasksWithType(T),t._scheduler.scheduleTask(T,function(){return t.dispatchSessionExpiredEvent()},e.expirationSeconds)},t.cancelSessionExpiredEvent=function(){t._scheduler.removeTasksWithType(T)},t.handleStorageEvent=function(e){if("hanko_session"===e.key){var n=t.getSessionDetail();n?t.dispatchSessionCreatedEvent(n):t.dispatchSessionExpiredEvent()}},t.listenEventDependencies(),t}t(n,e);var r=n.prototype;return r.getSessionDetail=function(){this._sessionState.read();var e=this._sessionState.getUserID(),t=this._sessionState.getExpirationSeconds(),n=this._cookie.getAuthCookie();return t>0&&null!=e&&e.length?{userID:e,expirationSeconds:t,jwt:n}:null},n.onDocumentReady=function(e){"complete"===document.readyState||"interactive"===document.readyState?setTimeout(e,1):document.addEventListener("DOMContentLoaded",e)},r.listenEventDependencies=function(){var e=this;this._listener.onSessionCreated(this.scheduleSessionExpiredEvent),this._listener.onSessionResumed(this.scheduleSessionExpiredEvent),this._listener.onSessionExpired(this.cancelSessionExpiredEvent),this._listener.onUserDeleted(this.cancelSessionExpiredEvent),this._listener.onUserLoggedOut(this.cancelSessionExpiredEvent),window.addEventListener("storage",this.handleStorageEvent),n.onDocumentReady(function(){return e.dispatchInitialEvents()})},r.dispatchInitialEvents=function(){this._sessionState.read();var e=this.getSessionDetail();e?this.dispatchSessionResumedEvent(e):this.dispatchSessionNotPresent()},n}(U),be=/*#__PURE__*/function(e){function n(t,n){var r;return void 0===n&&(n=13e3),(r=e.call(this)||this).api=void 0,r.config=void 0,r.user=void 0,r.webauthn=void 0,r.password=void 0,r.passcode=void 0,r.email=void 0,r.thirdParty=void 0,r.token=void 0,r.relay=void 0,r.api=t,r.config=new z(t,n),r.user=new X(t,n),r.webauthn=new ve(t,n),r.password=new V(t,n),r.passcode=new J(t,n),r.email=new we(t,n),r.thirdParty=new me(t,n),r.token=new ye(t,n),r.relay=new Pe,r}return t(n,e),n}(Ee);e.ConfigClient=z,e.ConflictError=u,e.CustomEventWithDetail=L,e.EmailAddressAlreadyExistsError=P,e.EmailClient=we,e.Hanko=be,e.HankoError=a,e.InvalidPasscodeError=f,e.InvalidPasswordError=l,e.InvalidWebauthnCredentialError=p,e.MaxNumOfEmailAddressesReachedError=S,e.MaxNumOfPasscodeAttemptsReachedError=w,e.NotFoundError=m,e.PasscodeClient=J,e.PasscodeExpiredError=v,e.PasswordClient=V,e.RequestTimeoutError=d,e.TechnicalError=c,e.ThirdPartyClient=me,e.ThirdPartyError=b,e.TokenClient=ye,e.TooManyRequestsError=y,e.UnauthorizedError=g,e.UserClient=X,e.UserVerificationError=E,e.WebauthnClient=ve,e.WebauthnRequestCancelledError=h,e.WebauthnSupport=le,e.authFlowCompletedType=D,e.sessionCreatedType=O,e.sessionExpiredType=T,e.sessionNotPresentType=I,e.sessionResumedType=A,e.userDeletedType=R,e.userLoggedOutType=j});
2
2
  //# sourceMappingURL=sdk.umd.js.map