@teamhanko/hanko-frontend-sdk 0.4.0-alpha → 0.8.0-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.
@@ -1,2 +1,2 @@
1
- function t(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,r(t,e)}function e(t){return e=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},e(t)}function r(t,e){return r=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},r(t,e)}function n(t,e,i){return n=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,n){var i=[null];i.push.apply(i,e);var o=new(Function.bind.apply(t,i));return n&&r(o,n.prototype),o},n.apply(null,arguments)}function i(t){var o="function"==typeof Map?new Map:void 0;return i=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!==o){if(o.has(t))return o.get(t);o.set(t,i)}function i(){return n(t,arguments,e(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),r(i,t)},i(t)}function o(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}var s=/*#__PURE__*/function(e){function r(t,n,i){var s;return(s=e.call(this,t)||this).code=void 0,s.cause=void 0,s.code=n,s.cause=i,Object.setPrototypeOf(o(s),r.prototype),s}return t(r,e),r}(/*#__PURE__*/i(Error)),a=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Technical error","somethingWentWrong",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),u=/*#__PURE__*/function(e){function r(t,n){var i;return i=e.call(this,"Conflict error","conflict",n)||this,Object.setPrototypeOf(o(i),r.prototype),i}return t(r,e),r}(s),c=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Request timed out error","requestTimeout",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),h=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Request cancelled error","requestCancelled",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),l=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Invalid password error","invalidPassword",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),f=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Invalid Passcode error","invalidPasscode",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),d=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Invalid WebAuthn credential error","invalidWebauthnCredential",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),p=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Passcode expired error","passcodeExpired",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),w=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Maximum number of Passcode attempts reached error","passcodeAttemptsReached",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),v=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Not found error","notFound",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),m=/*#__PURE__*/function(e){function r(t,n){var i;return(i=e.call(this,"Too many requests error","tooManyRequests",n)||this).retryAfter=void 0,i.retryAfter=t,Object.setPrototypeOf(o(i),r.prototype),i}return t(r,e),r}(s),y=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Unauthorized error","unauthorized",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),g=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"User verification error","userVerification",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),P=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),b=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"The email address already exists","emailAddressAlreadyExistsError",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),A=/*#__PURE__*/function(e){function r(t,n){var i;return i=e.call(this,"An error occurred during third party sign up/sign in",t,n)||this,Object.setPrototypeOf(o(i),r.prototype),i}return t(r,e),r}(s);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}(),C=/*#__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}(),k=/*#__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,u){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 C(r))},r.onerror=function(){u(new a)},r.ontimeout=function(){u(new c)},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}(),R=function(t,e){void 0===e&&(e=13e3),this.client=void 0,this.client=new k(t,e)},_=/*#__PURE__*/function(e){function r(){return e.apply(this,arguments)||this}return t(r,e),r.prototype.get=function(){try{return Promise.resolve(this.client.get("/.well-known/config")).then(function(t){if(!t.ok)throw new a;return t.json()})}catch(t){return Promise.reject(t)}},r}(R),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(e){function r(){return e.apply(this,arguments)||this}return t(r,e),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),E=/*#__PURE__*/function(e){function r(){return e.apply(this,arguments)||this}t(r,e);var n=r.prototype;return n.getState=function(t){var r;return(r=e.prototype.getUserState.call(this,t)).passcode||(r.passcode={})},n.read=function(){return e.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),I=/*#__PURE__*/function(e){function r(t,r){var n;return void 0===r&&(r=13e3),(n=e.call(this,t,r)||this).state=void 0,n.state=new E,n}t(r,e);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),u=n.state.getResendAfter(t);if(u>0)throw new m(u);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 u=r.parseRetryAfterHeader(),n.state.setResendAfter(t,u).write(),new m(u);if(401===r.status)throw new y;if(!r.ok)throw new a;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 p;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 w;if(!e.ok)throw new a;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}(R),U=/*#__PURE__*/function(e){function r(){return e.apply(this,arguments)||this}t(r,e);var n=r.prototype;return n.getState=function(t){var r;return(r=e.prototype.getUserState.call(this,t)).password||(r.password={})},n.read=function(){return e.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(e){function r(t,r){var n;return void 0===r&&(r=13e3),(n=e.call(this,t,r)||this).passwordState=void 0,n.passcodeState=void 0,n.passwordState=new U,n.passcodeState=new E,n}t(r,e);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 l;if(429===e.status){var n=e.parseRetryAfterHeader();throw r.passwordState.read().setRetryAfter(t,n).write(),new m(n)}if(!e.ok)throw new a;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 y;if(!t.ok)throw new a})}catch(t){return Promise.reject(t)}},n.getRetryAfter=function(t){return this.passwordState.read().getRetryAfter(t)},r}(R),N=/*#__PURE__*/function(e){function r(){return e.apply(this,arguments)||this}t(r,e);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 v;if(!t.ok)throw new a;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 u;if(!t.ok)throw new a;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 y;if(!e.ok)throw new a;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 y;if(!t.ok)throw new a;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 y;throw new a}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 a})}catch(t){return Promise.reject(t)}},r}(R);function q(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 L="copy",z="convert";function M(t,e,r){if(e===L)return r;if(e===z)return t(r);if(e instanceof Array)return r.map(r=>M(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]?M(t,o.schema,r[i]):null;else if(o.required)throw new Error(`Missing key: ${i}`)}return n}}function H(t,e){return{required:!0,schema:t,derive:e}}function J(t){return{required:!0,schema:t}}function W(t){return{required:!1,schema:t}}var B={type:J(L),id:J(z),transports:W(L)},F={appid:W(L),appidExclude:W(L),credProps:W(L)},V={appid:W(L),appidExclude:W(L),credProps:W(L)},X={publicKey:J({rp:J(L),user:J({id:J(z),name:J(L),displayName:J(L)}),challenge:J(z),pubKeyCredParams:J(L),timeout:W(L),excludeCredentials:W([B]),authenticatorSelection:W(L),attestation:W(L),extensions:W(F)}),signal:W(L)},G={type:J(L),id:J(L),rawId:J(z),authenticatorAttachment:W(L),response:J({clientDataJSON:J(z),attestationObject:J(z),transports:H(L,t=>{var e;return(null==(e=t.getTransports)?void 0:e.call(t))||[]})}),clientExtensionResults:H(V,t=>t.getClientExtensionResults())},$={mediation:W(L),publicKey:J({challenge:J(z),timeout:W(L),rpId:W(L),allowCredentials:W([B]),userVerification:W(L),extensions:W(F)}),signal:W(L)},Q={type:J(L),id:J(L),rawId:J(z),authenticatorAttachment:W(L),response:J({clientDataJSON:J(z),authenticatorData:J(z),signature:J(z),userHandle:J(z)}),clientExtensionResults:H(V,t=>t.getClientExtensionResults())};async function Y(t){const e=await navigator.credentials.create(function(t){return M(q,X,t)}(t));return function(t){return M(K,G,t)}(e)}async function Z(t){const e=await navigator.credentials.get(function(t){return M(q,$,t)}(t));return function(t){return M(K,Q,t)}(e)}var tt=/*#__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}(),et=/*#__PURE__*/function(e){function r(){return e.apply(this,arguments)||this}t(r,e);var n=r.prototype;return n.getState=function(t){var r;return(r=e.prototype.getUserState.call(this,t)).webauthn||(r.webauthn={})},n.read=function(){return e.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 rt(t,e){try{var r=t()}catch(t){return e(t)}return r&&r.then?r.then(void 0,e):r}var nt=/*#__PURE__*/function(e){function r(t,r){var n;return void 0===r&&(r=13e3),(n=e.call(this,t,r)||this).webauthnState=void 0,n.passcodeState=void 0,n.controller=void 0,n._getCredential=Z,n._createCredential=Y,n.webauthnState=new et,n.passcodeState=new E,n}t(r,e);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 d;if(!e.ok)throw new a;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 a;var s,u=n.json();u.signal=r._createAbortSignal(),e&&(u.mediation="conditional");var c=rt(function(){return Promise.resolve(r._getCredential(u)).then(function(t){s=t})},function(t){throw new h(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 g;throw new y}if(!e.ok)throw new a;var r=e.json();t.webauthnState.read().addCredential(r.user_id,r.credential_id).write()})}if(e.status>=400&&e.status<=499)throw new y;if(!e.ok)throw new a;var n,i=e.json();i.signal=t._createAbortSignal();var o=rt(function(){return Promise.resolve(t._createCredential(i)).then(function(t){n=t})},function(t){throw new h(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 y;if(!t.ok)throw new a;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 y;if(!t.ok)throw new a})}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 y;if(!t.ok)throw new a})}catch(t){return Promise.reject(t)}},n.shouldRegister=function(t){try{var e=tt.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}(R),it=/*#__PURE__*/function(e){function r(){return e.apply(this,arguments)||this}t(r,e);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 y;if(!t.ok)throw new a;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 b;if(401===t.status)throw new y;if(409===t.status)throw new P;throw new a})}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 y;if(!t.ok)throw new a})}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 y;if(!t.ok)throw new a})}catch(t){return Promise.reject(t)}},r}(R),ot=/*#__PURE__*/function(e){function r(t,r){return void 0===r&&(r=13e3),e.call(this,t,r)||this}t(r,e);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}(R),st=/*#__PURE__*/function(e){function r(t,r){return void 0===r&&(r=13e3),e.call(this,t,r)||this}return t(r,e),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 a})):Promise.resolve()}catch(t){return Promise.reject(t)}},r}(R),at=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 N(t,e),this.webauthn=new nt(t,e),this.password=new D(t,e),this.passcode=new I(t,e),this.email=new it(t,e),this.thirdParty=new ot(t,e),this.token=new st(t,e)};export{_ as ConfigClient,u as ConflictError,b as EmailAddressAlreadyExistsError,it as EmailClient,at as Hanko,s as HankoError,f as InvalidPasscodeError,l as InvalidPasswordError,d as InvalidWebauthnCredentialError,P as MaxNumOfEmailAddressesReachedError,w as MaxNumOfPasscodeAttemptsReachedError,v as NotFoundError,I as PasscodeClient,p as PasscodeExpiredError,D as PasswordClient,c as RequestTimeoutError,a as TechnicalError,ot as ThirdPartyClient,A as ThirdPartyError,st as TokenClient,m as TooManyRequestsError,y as UnauthorizedError,N as UserClient,g as UserVerificationError,nt as WebauthnClient,h as WebauthnRequestCancelledError,tt as WebauthnSupport};
1
+ function t(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,n(t,e)}function e(t){return e=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},e(t)}function n(t,e){return n=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},n(t,e)}function r(t,e,i){return r=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},r.apply(null,arguments)}function i(t){var o="function"==typeof Map?new Map:void 0;return i=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!==o){if(o.has(t))return o.get(t);o.set(t,i)}function i(){return r(t,arguments,e(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),n(i,t)},i(t)}function o(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}var s=/*#__PURE__*/function(e){function n(t,r,i){var s;return(s=e.call(this,t)||this).code=void 0,s.cause=void 0,s.code=r,s.cause=i,Object.setPrototypeOf(o(s),n.prototype),s}return t(n,e),n}(/*#__PURE__*/i(Error)),a=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Technical error","somethingWentWrong",t)||this,Object.setPrototypeOf(o(r),n.prototype),r}return t(n,e),n}(s),c=/*#__PURE__*/function(e){function n(t,r){var i;return i=e.call(this,"Conflict error","conflict",r)||this,Object.setPrototypeOf(o(i),n.prototype),i}return t(n,e),n}(s),u=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Request timed out error","requestTimeout",t)||this,Object.setPrototypeOf(o(r),n.prototype),r}return t(n,e),n}(s),h=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Request cancelled error","requestCancelled",t)||this,Object.setPrototypeOf(o(r),n.prototype),r}return t(n,e),n}(s),d=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Invalid password error","invalidPassword",t)||this,Object.setPrototypeOf(o(r),n.prototype),r}return t(n,e),n}(s),l=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Invalid Passcode error","invalidPasscode",t)||this,Object.setPrototypeOf(o(r),n.prototype),r}return t(n,e),n}(s),f=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Invalid WebAuthn credential error","invalidWebauthnCredential",t)||this,Object.setPrototypeOf(o(r),n.prototype),r}return t(n,e),n}(s),p=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Passcode expired error","passcodeExpired",t)||this,Object.setPrototypeOf(o(r),n.prototype),r}return t(n,e),n}(s),v=/*#__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(o(r),n.prototype),r}return t(n,e),n}(s),w=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Not found error","notFound",t)||this,Object.setPrototypeOf(o(r),n.prototype),r}return t(n,e),n}(s),m=/*#__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(o(i),n.prototype),i}return t(n,e),n}(s),y=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Unauthorized error","unauthorized",t)||this,Object.setPrototypeOf(o(r),n.prototype),r}return t(n,e),n}(s),g=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"User verification error","userVerification",t)||this,Object.setPrototypeOf(o(r),n.prototype),r}return t(n,e),n}(s),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(o(r),n.prototype),r}return t(n,e),n}(s),E=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"The email address already exists","emailAddressAlreadyExistsError",t)||this,Object.setPrototypeOf(o(r),n.prototype),r}return t(n,e),n}(s),P=/*#__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(o(i),n.prototype),i}return t(n,e),n}(s),b=/*#__PURE__*/function(){function t(t){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),n=decodeURIComponent(decodeURI(window.atob(e)));t=JSON.parse(n)}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}(),k=/*#__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 t;return(t=this.ls).session||(t.session={expiry:0,userID:"",authFlowCompleted:!1}),this.ls.session},r.getExpirationSeconds=function(){return b.timeToRemainingSeconds(this.getState().expiry)},r.setExpirationSeconds=function(t){return this.getState().expiry=b.remainingSecondsToTime(t),this},r.getUserID=function(){return this.getState().userID},r.setUserID=function(t){return this.getState().userID=t,this},r.getAuthFlowCompleted=function(){return this.getState().authFlowCompleted},r.setAuthFlowCompleted=function(t){return this.getState().authFlowCompleted=t,this},r.reset=function(){var t=this.getState();return delete t.expiry,delete t.userID,this},n}(b),_=/*#__PURE__*/function(e){function n(){return e.call(this,"hanko")||this}return t(n,e),n.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]},n}(b),C=/*#__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(t){return this.getState(t).id},r.setActiveID=function(t,e){return this.getState(t).id=e,this},r.getEmailID=function(t){return this.getState(t).emailID},r.setEmailID=function(t,e){return this.getState(t).emailID=e,this},r.reset=function(t){var e=this.getState(t);return delete e.id,delete e.ttl,delete e.resendAfter,delete e.emailID,this},r.getTTL=function(t){return b.timeToRemainingSeconds(this.getState(t).ttl)},r.setTTL=function(t,e){return this.getState(t).ttl=b.remainingSecondsToTime(e),this},r.getResendAfter=function(t){return b.timeToRemainingSeconds(this.getState(t).resendAfter)},r.setResendAfter=function(t,e){return this.getState(t).resendAfter=b.remainingSecondsToTime(e),this},n}(_),A="hanko-session-created",x="hanko-session-expired",O="hanko-user-logged-out",j="hanko-user-deleted",T="hanko-auth-flow-completed",R=/*#__PURE__*/function(e){function n(t,n){return e.call(this,t,{detail:n})||this}return t(n,e),n}(/*#__PURE__*/i(CustomEvent)),I=/*#__PURE__*/function(){function t(){this._dispatchEvent=document.dispatchEvent.bind(document),this._sessionState=new k}var e=t.prototype;return e.dispatch=function(t,e){this._dispatchEvent(new R(t,e))},e.dispatchSessionCreatedEvent=function(t){this.dispatch(A,t)},e.dispatchSessionExpiredEvent=function(){this.dispatch(x,null)},e.dispatchUserLoggedOutEvent=function(){this.dispatch(O,null)},e.dispatchUserDeletedEvent=function(){this.dispatch(j,null)},e.dispatchAuthFlowCompletedEvent=function(t){this._sessionState.read().setAuthFlowCompleted(!0).write(),this.dispatch(T,t)},t}();function D(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)t[r]=n[r]}return t}var L=function t(e,n){function r(t,r,i){if("undefined"!=typeof document){"number"==typeof(i=D({},n,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(r,t)+o}}return Object.create({set:r,get:function(t){if("undefined"!=typeof document&&(!arguments.length||t)){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]=e.read(s,a),t===a)break}catch(t){}}return t?r[t]:r}},remove:function(t,e){r(t,"",D({},e,{expires:-1}))},withAttributes:function(e){return t(this.converter,D({},this.attributes,e))},withConverter:function(e){return t(D({},this.converter,e),this.attributes)}},{attributes:{value:Object.freeze(n)},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:"/"}),U=/*#__PURE__*/function(){function t(){this.authCookieName="hanko"}var e=t.prototype;return e.getAuthCookie=function(){return L.get(this.authCookieName)},e.setAuthCookie=function(t,e){void 0===e&&(e=!0),L.set(this.authCookieName,t,{secure:e})},e.removeAuthCookie=function(){L.remove(this.authCookieName)},t}(),N=/*#__PURE__*/function(){function t(t){this._xhr=void 0,this._xhr=t}return t.prototype.getResponseHeader=function(t){return this._xhr.getResponseHeader(t)},t}(),H=/*#__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 N(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.parseNumericHeader=function(t){var e=parseInt(this.headers.getResponseHeader(t),10);return isNaN(e)?0:e},t}(),F=/*#__PURE__*/function(){function t(t,e){void 0===e&&(e=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=t,this.timeout=e,this.sessionState=new k,this.passcodeState=new C,this.dispatcher=new I,this.cookie=new U}var e=t.prototype;return e._fetch=function(t,e,n){void 0===n&&(n=new XMLHttpRequest);var r=this.api+t,i=this.timeout,o=this.cookie.getAuthCookie();return new Promise(function(t,s){n.open(e.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 e=new H(n);t(e)},n.onerror=function(){s(new a)},n.ontimeout=function(){s(new u)},n.send(e.body?e.body.toString():null)})},e.processResponseHeadersOnLogin=function(t,e){var n="",r=0;if(e.xhr.getAllResponseHeaders().split("\r\n").forEach(function(t){var i=t.toLowerCase();i.startsWith("x-auth-token")?n=e.headers.getResponseHeader("X-Auth-Token"):i.startsWith("x-session-lifetime")&&(r=parseInt(e.headers.getResponseHeader("X-Session-Lifetime"),10))}),n){var i=!!this.api.match("^https://");this.cookie.setAuthCookie(n,i)}this.passcodeState.read().reset(t).write(),r>0&&(this.sessionState.read(),this.sessionState.setExpirationSeconds(r),this.sessionState.setUserID(t),this.sessionState.setAuthFlowCompleted(!1),this.sessionState.write(),this.dispatcher.dispatchSessionCreatedEvent({jwt:n,userID:t,expirationSeconds:r}))},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}(),W=function(t,e){void 0===e&&(e=13e3),this.client=void 0,this.client=new F(t,e)},q=/*#__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(t){if(!t.ok)throw new a;return t.json()})}catch(t){return Promise.reject(t)}},n}(W),K=/*#__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 C,r}t(n,e);var r=n.prototype;return r.initialize=function(t,e,n){try{var r=this;r.state.read();var i=r.state.getTTL(t),o=r.state.getActiveID(t),s=r.state.getEmailID(t),c=r.state.getResendAfter(t);if(c>0)throw new m(c);if(!n&&i>0&&e===s)return Promise.resolve({id:o,ttl:i});var u={user_id:t};return e&&(u.email_id=e),Promise.resolve(r.client.post("/passcode/login/initialize",u)).then(function(n){if(429===n.status)throw c=n.parseNumericHeader("Retry-After"),r.state.setResendAfter(t,c).write(),new m(c);if(!n.ok)throw new a;var i=n.json();return r.state.setActiveID(t,i.id).setTTL(t,i.ttl),e&&r.state.setEmailID(t,e),r.state.write(),i})}catch(t){return Promise.reject(t)}},r.finalize=function(t,e){try{var n=this,r=n.state.read().getActiveID(t);if(n.state.getTTL(t)<=0)throw new p;return Promise.resolve(n.client.post("/passcode/login/finalize",{id:r,code:e})).then(function(e){if(401===e.status)throw new l;if(410===e.status)throw n.state.reset(t).write(),new v;if(!e.ok)throw new a;n.client.processResponseHeadersOnLogin(t,e)})}catch(t){return Promise.reject(t)}},r.getTTL=function(t){return this.state.read().getTTL(t)},r.getResendAfter=function(t){return this.state.read().getResendAfter(t)},n}(W),z=/*#__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(t){return b.timeToRemainingSeconds(this.getState(t).retryAfter)},r.setRetryAfter=function(t,e){return this.getState(t).retryAfter=b.remainingSecondsToTime(e),this},n}(_),M=/*#__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 z,r.passcodeState=new C,r}t(n,e);var r=n.prototype;return r.login=function(t,e){try{var n=this;return Promise.resolve(n.client.post("/password/login",{user_id:t,password:e})).then(function(e){if(401===e.status)throw new d;if(429===e.status){var r=e.parseNumericHeader("Retry-After");throw n.passwordState.read().setRetryAfter(t,r).write(),new m(r)}if(!e.ok)throw new a;n.client.processResponseHeadersOnLogin(t,e)})}catch(t){return Promise.reject(t)}},r.update=function(t,e){try{var n=this;return Promise.resolve(n.client.put("/password",{user_id:t,password:e})).then(function(t){if(401===t.status)throw n.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(!t.ok)throw new a})}catch(t){return Promise.reject(t)}},r.getRetryAfter=function(t){return this.passwordState.read().getRetryAfter(t)},n}(W),J=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.getInfo=function(t){try{return Promise.resolve(this.client.post("/user",{email:t})).then(function(t){if(404===t.status)throw new w;if(!t.ok)throw new a;return t.json()})}catch(t){return Promise.reject(t)}},r.create=function(t){try{var e=this;return Promise.resolve(e.client.post("/users",{email:t})).then(function(t){if(409===t.status)throw new c;if(!t.ok)throw new a;var n=t.json();return n&&n.user_id&&e.client.processResponseHeadersOnLogin(n.user_id,t),n})}catch(t){return Promise.reject(t)}},r.getCurrent=function(){try{var t=this;return Promise.resolve(t.client.get("/me")).then(function(e){if(401===e.status)throw t.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(!e.ok)throw new a;var n=e.json();return Promise.resolve(t.client.get("/users/"+n.id)).then(function(e){if(401===e.status)throw t.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(!e.ok)throw new a;return e.json()})})}catch(t){return Promise.reject(t)}},r.delete=function(){try{var t=this;return Promise.resolve(t.client.delete("/user")).then(function(e){if(e.ok)return t.client.cookie.removeAuthCookie(),t.client.sessionState.reset().write(),void t.client.dispatcher.dispatchUserDeletedEvent();if(401===e.status)throw t.client.dispatcher.dispatchSessionExpiredEvent(),new y;throw new a})}catch(t){return Promise.reject(t)}},r.logout=function(){try{var t=this;return Promise.resolve(t.client.post("/logout")).then(function(e){if(t.client.cookie.removeAuthCookie(),t.client.sessionState.reset().write(),t.client.dispatcher.dispatchUserLoggedOutEvent(),401===e.status);else if(!e.ok)throw new a})}catch(t){return Promise.reject(t)}},n}(W);function B(t){const e="==".slice(0,(4-t.length%4)%4),n=t.replace(/-/g,"+").replace(/_/g,"/")+e,r=atob(n),i=new ArrayBuffer(r.length),o=new Uint8Array(i);for(let t=0;t<r.length;t++)o[t]=r.charCodeAt(t);return i}function V(t){const e=new Uint8Array(t);let n="";for(const t of e)n+=String.fromCharCode(t);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}var X="copy",G="convert";function $(t,e,n){if(e===X)return n;if(e===G)return t(n);if(e instanceof Array)return n.map(n=>$(t,e[0],n));if(e instanceof Object){const r={};for(const[i,o]of Object.entries(e)){if(o.derive){const t=o.derive(n);void 0!==t&&(n[i]=t)}if(i in n)r[i]=null!=n[i]?$(t,o.schema,n[i]):null;else if(o.required)throw new Error(`Missing key: ${i}`)}return r}}function Q(t,e){return{required:!0,schema:t,derive:e}}function Y(t){return{required:!0,schema:t}}function Z(t){return{required:!1,schema:t}}var tt={type:Y(X),id:Y(G),transports:Z(X)},et={appid:Z(X),appidExclude:Z(X),credProps:Z(X)},nt={appid:Z(X),appidExclude:Z(X),credProps:Z(X)},rt={publicKey:Y({rp:Y(X),user:Y({id:Y(G),name:Y(X),displayName:Y(X)}),challenge:Y(G),pubKeyCredParams:Y(X),timeout:Z(X),excludeCredentials:Z([tt]),authenticatorSelection:Z(X),attestation:Z(X),extensions:Z(et)}),signal:Z(X)},it={type:Y(X),id:Y(X),rawId:Y(G),authenticatorAttachment:Z(X),response:Y({clientDataJSON:Y(G),attestationObject:Y(G),transports:Q(X,t=>{var e;return(null==(e=t.getTransports)?void 0:e.call(t))||[]})}),clientExtensionResults:Q(nt,t=>t.getClientExtensionResults())},ot={mediation:Z(X),publicKey:Y({challenge:Y(G),timeout:Z(X),rpId:Z(X),allowCredentials:Z([tt]),userVerification:Z(X),extensions:Z(et)}),signal:Z(X)},st={type:Y(X),id:Y(X),rawId:Y(G),authenticatorAttachment:Z(X),response:Y({clientDataJSON:Y(G),authenticatorData:Y(G),signature:Y(G),userHandle:Y(G)}),clientExtensionResults:Q(nt,t=>t.getClientExtensionResults())};async function at(t){const e=await navigator.credentials.create(function(t){return $(B,rt,t)}(t));return function(t){return $(V,it,t)}(e)}async function ct(t){const e=await navigator.credentials.get(function(t){return $(B,ot,t)}(t));return function(t){return $(V,st,t)}(e)}var ut=/*#__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}(),ht=/*#__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(t){var e;return(e=this.getState(t)).credentials||(e.credentials=[])},r.addCredential=function(t,e){return this.getCredentials(t).push(e),this},r.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}})},n}(_);function dt(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var lt=/*#__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=ct,r._createCredential=at,r.webauthnState=new ht,r.passcodeState=new C,r}t(n,e);var r=n.prototype;return r.login=function(t,e){try{var n=this;return Promise.resolve(n.client.post("/webauthn/login/initialize",{user_id:t})).then(function(t){var r;function i(t){return r?t:Promise.resolve(n.client.post("/webauthn/login/finalize",o)).then(function(t){if(400===t.status||401===t.status)throw new f;if(!t.ok)throw new a;var e=t.json();return n.webauthnState.read().addCredential(e.user_id,e.credential_id).write(),n.client.processResponseHeadersOnLogin(e.user_id,t),e})}if(!t.ok)throw new a;var o,s=t.json();s.signal=n._createAbortSignal(),e&&(s.mediation="conditional");var c=dt(function(){return Promise.resolve(n._getCredential(s)).then(function(t){o=t})},function(t){throw new h(t)});return c&&c.then?c.then(i):i(c)})}catch(t){return Promise.reject(t)}},r.register=function(){try{var t=this;return Promise.resolve(t.client.post("/webauthn/registration/initialize")).then(function(e){function n(e){return r.transports=r.response.transports,Promise.resolve(t.client.post("/webauthn/registration/finalize",r)).then(function(e){if(401===e.status)throw t.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(422===e.status)throw new g;if(!e.ok)throw new a;var n=e.json();t.webauthnState.read().addCredential(n.user_id,n.credential_id).write()})}if(401===e.status)throw t.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(!e.ok)throw new a;var r,i=e.json();i.signal=t._createAbortSignal();var o=dt(function(){return Promise.resolve(t._createCredential(i)).then(function(t){r=t})},function(t){throw new h(t)});return o&&o.then?o.then(n):n()})}catch(t){return Promise.reject(t)}},r.listCredentials=function(){try{var t=this;return Promise.resolve(t.client.get("/webauthn/credentials")).then(function(e){if(401===e.status)throw t.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(!e.ok)throw new a;return e.json()})}catch(t){return Promise.reject(t)}},r.updateCredential=function(t,e){try{var n=this;return Promise.resolve(n.client.patch("/webauthn/credentials/"+t,{name:e})).then(function(t){if(401===t.status)throw n.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(!t.ok)throw new a})}catch(t){return Promise.reject(t)}},r.deleteCredential=function(t){try{var e=this;return Promise.resolve(e.client.delete("/webauthn/credentials/"+t)).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(!t.ok)throw new a})}catch(t){return Promise.reject(t)}},r.shouldRegister=function(t){try{var e=ut.supported();if(!t.webauthn_credentials||!t.webauthn_credentials.length)return Promise.resolve(e);var n=this.webauthnState.read().matchCredentials(t.id,t.webauthn_credentials);return Promise.resolve(e&&!n.length)}catch(t){return Promise.reject(t)}},r._createAbortSignal=function(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal},n}(W),ft=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.list=function(){try{var t=this;return Promise.resolve(t.client.get("/emails")).then(function(e){if(401===e.status)throw t.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(!e.ok)throw new a;return e.json()})}catch(t){return Promise.reject(t)}},r.create=function(t){try{var e=this;return Promise.resolve(e.client.post("/emails",{address:t})).then(function(t){if(t.ok)return t.json();if(400===t.status)throw new E;if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(409===t.status)throw new S;throw new a})}catch(t){return Promise.reject(t)}},r.setPrimaryEmail=function(t){try{var e=this;return Promise.resolve(e.client.post("/emails/"+t+"/set_primary")).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(!t.ok)throw new a})}catch(t){return Promise.reject(t)}},r.delete=function(t){try{var e=this;return Promise.resolve(e.client.delete("/emails/"+t)).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(!t.ok)throw new a})}catch(t){return Promise.reject(t)}},n}(W),pt=/*#__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(t,e){try{var n=new URL("/thirdparty/auth",this.client.api);if(!t)throw new P("somethingWentWrong",new Error("provider missing from request"));if(!e)throw new P("somethingWentWrong",new Error("redirectTo missing from request"));return n.searchParams.append("provider",t),n.searchParams.append("redirect_to",e),window.location.assign(n.href),Promise.resolve()}catch(t){return Promise.reject(t)}},r.getError=function(){var t=new URLSearchParams(window.location.search),e=t.get("error"),n=t.get("error_description");if(e){var r="";switch(e){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 P(r,new Error(n))}},n}(W),vt=/*#__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 t=this,e=new URLSearchParams(window.location.search).get("hanko_token");return e?(window.history.replaceState(null,null,window.location.pathname),Promise.resolve(t.client.post("/token",{value:e})).then(function(e){if(!e.ok)throw new a;var n=e.json();t.client.processResponseHeadersOnLogin(n.user_id,e)})):Promise.resolve()}catch(t){return Promise.reject(t)}},n}(W),wt=/*#__PURE__*/function(){function t(){}return t.throttle=function(t,e,n){void 0===n&&(n={});var r,i,o,s=n.leading,a=void 0===s||s,c=n.trailing,u=void 0===c||c,h=0,d=function(){h=!1===a?0:Date.now(),o=null,t.apply(r,i)};return function(){var n=Date.now();h||!1!==a||(h=n);var s=e-(n-h);r=this,i=[].slice.call(arguments),s<=0||s>e?(o&&(window.clearTimeout(o),o=null),h=n,t.apply(r,i)):o||!1===u||(o=window.setTimeout(d,s))}},t}(),mt=/*#__PURE__*/function(){function t(){this.throttleLimit=1e3,this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=wt.throttle}var e=t.prototype;return e.wrapCallback=function(t,e){var n=function(e){t(e.detail)};return e?this._throttle(n,this.throttleLimit,{leading:!0,trailing:!1}):n},e.addEventListenerWithType=function(t){var e=this,n=t.type,r=t.once,i=void 0!==r&&r,o=t.throttle,s=this.wrapCallback(t.callback,void 0!==o&&o);return this._addEventListener(n,s,{once:i}),function(){return e._removeEventListener(n,s)}},t.mapAddEventListenerParams=function(t,e,n){return{type:t,callback:e.callback,once:e.once,throttle:n}},e.addEventListener=function(e,n,r){return this.addEventListenerWithType(t.mapAddEventListenerParams(e,n,r))},e.onSessionCreated=function(t,e){return this.addEventListener(A,{callback:t,once:e},!0)},e.onSessionExpired=function(t,e){return this.addEventListener(x,{callback:t,once:e},!0)},e.onUserLoggedOut=function(t,e){return this.addEventListener(O,{callback:t,once:e})},e.onUserDeleted=function(t,e){return this.addEventListener(j,{callback:t,once:e})},e.onAuthFlowCompleted=function(t,e){return this.addEventListener(T,{callback:t,once:e})},t}(),yt=/*#__PURE__*/function(){function t(){this._tasks=[]}var e=t.prototype;return e.removeTask=function(t){window.clearTimeout(t.timeoutID),this._tasks=this._tasks.filter(function(e){return e!==t})},e.removeTasksWithType=function(t){var e=this;this._tasks.filter(function(e){return e.type===t}).forEach(function(t){return e.removeTask(t)})},e.scheduleTask=function(t,e,n){var r=this,i={timeoutID:window.setTimeout(function(){e(),r.removeTask(i)},1e3*n),type:t,func:e};this._tasks.push(i)},t}(),gt=/*#__PURE__*/function(){function t(){this._sessionState=void 0,this._cookie=void 0,this._sessionState=new k,this._cookie=new U}var e=t.prototype;return e.get=function(){var e=this._get();return t.validate(e)?e:null},e.isValid=function(){var e=this._get();return t.validate(e)},e._get=function(){return this._sessionState.read(),{userID:this._sessionState.getUserID(),expirationSeconds:this._sessionState.getExpirationSeconds(),jwt:this._cookie.getAuthCookie()}},e.isAuthFlowCompleted=function(){return this._sessionState.read(),this._sessionState.getAuthFlowCompleted()},t.validate=function(t){var e;return!!(t.expirationSeconds>0&&null!=(e=t.userID)&&e.length)},t}(),St=/*#__PURE__*/function(e){function n(){var t;return(t=e.call(this)||this)._listener=new mt,t._scheduler=new yt,t._session=new gt,t.scheduleSessionExpiredEvent=function(e){t._scheduler.removeTasksWithType(x),t._scheduler.scheduleTask(x,function(){return t.dispatchSessionExpiredEvent()},e.expirationSeconds)},t.cancelSessionExpiredEvent=function(){t._scheduler.removeTasksWithType(x)},t.handleStorageEvent=function(e){if("hanko_session"===e.key){var n=t._session.get();n?t._session.isAuthFlowCompleted()?t.dispatchAuthFlowCompletedEvent({userID:n.userID}):t.dispatchSessionCreatedEvent(n):t.dispatchSessionExpiredEvent()}},t.listenEventDependencies(),t}return t(n,e),n.prototype.listenEventDependencies=function(){this._listener.onSessionCreated(this.scheduleSessionExpiredEvent),this._listener.onSessionExpired(this.cancelSessionExpiredEvent),this._listener.onUserDeleted(this.cancelSessionExpiredEvent),this._listener.onUserLoggedOut(this.cancelSessionExpiredEvent),window.addEventListener("storage",this.handleStorageEvent);var t=this._session.get();t&&this.scheduleSessionExpiredEvent(t)},n}(I),Et=/*#__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.session=void 0,r.api=t,r.config=new q(t,n),r.user=new J(t,n),r.webauthn=new lt(t,n),r.password=new M(t,n),r.passcode=new K(t,n),r.email=new ft(t,n),r.thirdParty=new pt(t,n),r.token=new vt(t,n),r.relay=new St,r.session=new gt,r}return t(n,e),n}(mt);export{q as ConfigClient,c as ConflictError,R as CustomEventWithDetail,E as EmailAddressAlreadyExistsError,ft as EmailClient,Et as Hanko,s as HankoError,l as InvalidPasscodeError,d as InvalidPasswordError,f as InvalidWebauthnCredentialError,S as MaxNumOfEmailAddressesReachedError,v as MaxNumOfPasscodeAttemptsReachedError,w as NotFoundError,K as PasscodeClient,p as PasscodeExpiredError,M as PasswordClient,u as RequestTimeoutError,a as TechnicalError,pt as ThirdPartyClient,P as ThirdPartyError,vt as TokenClient,m as TooManyRequestsError,y as UnauthorizedError,J as UserClient,g as UserVerificationError,lt as WebauthnClient,h as WebauthnRequestCancelledError,ut as WebauthnSupport,T as authFlowCompletedType,A as sessionCreatedType,x as sessionExpiredType,j as userDeletedType,O as userLoggedOutType};
2
2
  //# sourceMappingURL=sdk.module.js.map