@authorizerdev/authorizer-js 1.2.15 → 1.2.18
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/lib/authorizer.min.js +3 -3
- package/lib/index.d.ts +4 -0
- package/lib/index.js +3 -3
- package/lib/index.mjs +3 -3
- package/package.json +1 -1
package/lib/authorizer.min.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var authorizerdev=(()=>{var pe=Object.create;var A=Object.defineProperty,ye=Object.defineProperties,we=Object.getOwnPropertyDescriptor,me=Object.getOwnPropertyDescriptors,_e=Object.getOwnPropertyNames,J=Object.getOwnPropertySymbols,ge=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty,be=Object.prototype.propertyIsEnumerable;var j=(o,e,t)=>e in o?A(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,I=(o,e)=>{for(var t in e||(e={}))G.call(e,t)&&j(o,t,e[t]);if(J)for(var t of J(e))be.call(e,t)&&j(o,t,e[t]);return o},W=(o,e)=>ye(o,me(e)),n=(o,e)=>A(o,"name",{value:e,configurable:!0});var Ee=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),ve=(o,e)=>{for(var t in e)A(o,t,{get:e[t],enumerable:!0})},Z=(o,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of _e(e))!G.call(o,c)&&c!==t&&A(o,c,{get:()=>e[c],enumerable:!(s=we(e,c))||s.enumerable});return o};var Te=(o,e,t)=>(t=o!=null?pe(ge(o)):{},Z(e||!o||!o.__esModule?A(t,"default",{value:o,enumerable:!0}):t,o)),Re=o=>Z(A({},"__esModule",{value:!0}),o);var d=(o,e,t)=>(j(o,typeof e!="symbol"?e+"":e,t),t);var f=(o,e,t)=>new Promise((s,c)=>{var u=_=>{try{m(t.next(_))}catch(w){c(w)}},g=_=>{try{m(t.throw(_))}catch(w){c(w)}},m=_=>_.done?s(_.value):Promise.resolve(_.value).then(u,g);m((t=t.apply(o,e)).next())});var Y=Ee((E,K)=>{var X=typeof self!="undefined"?self:E,$=function(){function o(){this.fetch=!1,this.DOMException=X.DOMException}return n(o,"F"),o.prototype=X,new o}();(function(o){var e=function(t){var s={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch(r){return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function c(r){return r&&DataView.prototype.isPrototypeOf(r)}if(n(c,"isDataView"),s.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],g=ArrayBuffer.isView||function(r){return r&&u.indexOf(Object.prototype.toString.call(r))>-1};function m(r){if(typeof r!="string"&&(r=String(r)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(r))throw new TypeError("Invalid character in header field name");return r.toLowerCase()}n(m,"normalizeName");function _(r){return typeof r!="string"&&(r=String(r)),r}n(_,"normalizeValue");function w(r){var i={next:function(){var a=r.shift();return{done:a===void 0,value:a}}};return s.iterable&&(i[Symbol.iterator]=function(){return i}),i}n(w,"iteratorFor");function l(r){this.map={},r instanceof l?r.forEach(function(i,a){this.append(a,i)},this):Array.isArray(r)?r.forEach(function(i){this.append(i[0],i[1])},this):r&&Object.getOwnPropertyNames(r).forEach(function(i){this.append(i,r[i])},this)}n(l,"Headers"),l.prototype.append=function(r,i){r=m(r),i=_(i);var a=this.map[r];this.map[r]=a?a+", "+i:i},l.prototype.delete=function(r){delete this.map[m(r)]},l.prototype.get=function(r){return r=m(r),this.has(r)?this.map[r]:null},l.prototype.has=function(r){return this.map.hasOwnProperty(m(r))},l.prototype.set=function(r,i){this.map[m(r)]=_(i)},l.prototype.forEach=function(r,i){for(var a in this.map)this.map.hasOwnProperty(a)&&r.call(i,this.map[a],a,this)},l.prototype.keys=function(){var r=[];return this.forEach(function(i,a){r.push(a)}),w(r)},l.prototype.values=function(){var r=[];return this.forEach(function(i){r.push(i)}),w(r)},l.prototype.entries=function(){var r=[];return this.forEach(function(i,a){r.push([a,i])}),w(r)},s.iterable&&(l.prototype[Symbol.iterator]=l.prototype.entries);function B(r){if(r.bodyUsed)return Promise.reject(new TypeError("Already read"));r.bodyUsed=!0}n(B,"consumed");function N(r){return new Promise(function(i,a){r.onload=function(){i(r.result)},r.onerror=function(){a(r.error)}})}n(N,"fileReaderReady");function se(r){var i=new FileReader,a=N(i);return i.readAsArrayBuffer(r),a}n(se,"readBlobAsArrayBuffer");function ae(r){var i=new FileReader,a=N(i);return i.readAsText(r),a}n(ae,"readBlobAsText");function ce(r){for(var i=new Uint8Array(r),a=new Array(i.length),y=0;y<i.length;y++)a[y]=String.fromCharCode(i[y]);return a.join("")}n(ce,"readArrayBufferAsText");function Q(r){if(r.slice)return r.slice(0);var i=new Uint8Array(r.byteLength);return i.set(new Uint8Array(r)),i.buffer}n(Q,"bufferClone");function V(){return this.bodyUsed=!1,this._initBody=function(r){this._bodyInit=r,r?typeof r=="string"?this._bodyText=r:s.blob&&Blob.prototype.isPrototypeOf(r)?this._bodyBlob=r:s.formData&&FormData.prototype.isPrototypeOf(r)?this._bodyFormData=r:s.searchParams&&URLSearchParams.prototype.isPrototypeOf(r)?this._bodyText=r.toString():s.arrayBuffer&&s.blob&&c(r)?(this._bodyArrayBuffer=Q(r.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(r)||g(r))?this._bodyArrayBuffer=Q(r):this._bodyText=r=Object.prototype.toString.call(r):this._bodyText="",this.headers.get("content-type")||(typeof r=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):s.searchParams&&URLSearchParams.prototype.isPrototypeOf(r)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},s.blob&&(this.blob=function(){var r=B(this);if(r)return r;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?B(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(se)}),this.text=function(){var r=B(this);if(r)return r;if(this._bodyBlob)return ae(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(ce(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},s.formData&&(this.formData=function(){return this.text().then(fe)}),this.json=function(){return this.text().then(JSON.parse)},this}n(V,"Body");var ue=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function he(r){var i=r.toUpperCase();return ue.indexOf(i)>-1?i:r}n(he,"normalizeMethod");function T(r,i){i=i||{};var a=i.body;if(r instanceof T){if(r.bodyUsed)throw new TypeError("Already read");this.url=r.url,this.credentials=r.credentials,i.headers||(this.headers=new l(r.headers)),this.method=r.method,this.mode=r.mode,this.signal=r.signal,!a&&r._bodyInit!=null&&(a=r._bodyInit,r.bodyUsed=!0)}else this.url=String(r);if(this.credentials=i.credentials||this.credentials||"same-origin",(i.headers||!this.headers)&&(this.headers=new l(i.headers)),this.method=he(i.method||this.method||"GET"),this.mode=i.mode||this.mode||null,this.signal=i.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&a)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(a)}n(T,"Request"),T.prototype.clone=function(){return new T(this,{body:this._bodyInit})};function fe(r){var i=new FormData;return r.trim().split("&").forEach(function(a){if(a){var y=a.split("="),p=y.shift().replace(/\+/g," "),h=y.join("=").replace(/\+/g," ");i.append(decodeURIComponent(p),decodeURIComponent(h))}}),i}n(fe,"decode");function de(r){var i=new l,a=r.replace(/\r?\n[\t ]+/g," ");return a.split(/\r?\n/).forEach(function(y){var p=y.split(":"),h=p.shift().trim();if(h){var k=p.join(":").trim();i.append(h,k)}}),i}n(de,"parseHeaders"),V.call(T.prototype);function b(r,i){i||(i={}),this.type="default",this.status=i.status===void 0?200:i.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in i?i.statusText:"OK",this.headers=new l(i.headers),this.url=i.url||"",this._initBody(r)}n(b,"Response"),V.call(b.prototype),b.prototype.clone=function(){return new b(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new l(this.headers),url:this.url})},b.error=function(){var r=new b(null,{status:0,statusText:""});return r.type="error",r};var le=[301,302,303,307,308];b.redirect=function(r,i){if(le.indexOf(i)===-1)throw new RangeError("Invalid status code");return new b(null,{status:i,headers:{location:r}})},t.DOMException=o.DOMException;try{new t.DOMException}catch(r){t.DOMException=function(i,a){this.message=i,this.name=a;var y=Error(i);this.stack=y.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function D(r,i){return new Promise(function(a,y){var p=new T(r,i);if(p.signal&&p.signal.aborted)return y(new t.DOMException("Aborted","AbortError"));var h=new XMLHttpRequest;function k(){h.abort()}n(k,"abortXhr"),h.onload=function(){var S={status:h.status,statusText:h.statusText,headers:de(h.getAllResponseHeaders()||"")};S.url="responseURL"in h?h.responseURL:S.headers.get("X-Request-URL");var C="response"in h?h.response:h.responseText;a(new b(C,S))},h.onerror=function(){y(new TypeError("Network request failed"))},h.ontimeout=function(){y(new TypeError("Network request failed"))},h.onabort=function(){y(new t.DOMException("Aborted","AbortError"))},h.open(p.method,p.url,!0),p.credentials==="include"?h.withCredentials=!0:p.credentials==="omit"&&(h.withCredentials=!1),"responseType"in h&&s.blob&&(h.responseType="blob"),p.headers.forEach(function(S,C){h.setRequestHeader(C,S)}),p.signal&&(p.signal.addEventListener("abort",k),h.onreadystatechange=function(){h.readyState===4&&p.signal.removeEventListener("abort",k)}),h.send(typeof p._bodyInit=="undefined"?null:p._bodyInit)})}return n(D,"fetch"),D.polyfill=!0,o.fetch||(o.fetch=D,o.Headers=l,o.Request=T,o.Response=b),t.Headers=l,t.Request=T,t.Response=b,t.fetch=D,Object.defineProperty(t,"__esModule",{value:!0}),t}({})})($);$.fetch.ponyfill=!0;delete $.fetch.polyfill;var L=$;E=L.fetch;E.default=L.fetch;E.fetch=L.fetch;E.Headers=L.Headers;E.Request=L.Request;E.Response=L.Response;K.exports=E});var Oe={};ve(Oe,{Authorizer:()=>P,OAuthProviders:()=>q,ResponseTypes:()=>O});var ne=Te(Y());var q;(function(o){o.Apple="apple",o.Github="github",o.Google="google",o.Facebook="facebook",o.LinkedIn="linkedin",o.Twitter="twitter",o.Microsoft="microsoft",o.Twitch="twitch"})(q||(q={}));var O;(function(o){o.Code="code",o.Token="token"})(O||(O={}));var R=n(()=>typeof window!="undefined","hasWindow"),M=n(o=>{let e=o.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),ee=n(()=>R()?window.crypto||window.msCrypto:null,"getCrypto"),Ie=n(()=>{let o=ee();return o&&o.subtle||o.webkitSubtle},"getCryptoSubtle"),U=n(()=>{let o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",t=ee();return t&&Array.from(t.getRandomValues(new Uint8Array(43))).forEach(c=>e+=o[c%o.length]),e},"createRandomString"),v=n(o=>R()?btoa(o):Buffer.from(o).toString("base64"),"encode");var re=n(o=>Object.keys(o).filter(e=>typeof o[e]!="undefined").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(o[e])}`).join("&"),"createQueryParams"),te=n(o=>f(void 0,null,function*(){let e=Ie().digest({name:"SHA-256"},new TextEncoder().encode(o));return window.msCrypto?new Promise((t,s)=>{e.oncomplete=c=>{t(c.target.result)},e.onerror=c=>{s(c.error)},e.onabort=()=>{s(new Error("The digest operation was aborted"))}}):yield e}),"sha256"),Le=n(o=>{let e={"+":"-","/":"_","=":""};return o.replace(/[+/=]/g,t=>e[t])},"urlEncodeB64");var oe=n(o=>{let e=new Uint8Array(o);return Le(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),ie=n((o,e,t=60)=>new Promise((s,c)=>{let u=window.document.createElement("iframe");u.setAttribute("id","authorizer-iframe"),u.setAttribute("width","0"),u.setAttribute("height","0"),u.style.display="none";let g,m=n(()=>{window.document.body.contains(u)&&(window.document.body.removeChild(u),window.removeEventListener("message",g,!1))},"removeIframe"),_=setTimeout(()=>{m()},t*1e3);g=n(function(w){if(w.origin!==e||!w.data||!w.data.response)return;let l=w.source;l&&l.close(),w.data.response.error?c(w.data.response):s(w.data.response),clearTimeout(_),window.removeEventListener("message",g,!1),setTimeout(m,2*1e3)},"iframeEventHandler"),window.addEventListener("message",g,!1),window.document.body.appendChild(u),u.setAttribute("src",o)}),"executeIframe");var H="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",x=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen should_show_totp_screen authenticator_scanner_image authenticator_secret authenticator_recovery_codes user { ${H} }`,z=n(()=>R()?window.fetch:ne.default,"getFetcher"),P=class{constructor(e){d(this,"authorize",n(e=>f(this,null,function*(){if(!R())throw new Error("this feature is only supported in browser");let t=["openid","profile","email"];e.use_refresh_token&&t.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:v(U()),nonce:v(U()),response_type:e.response_type,scope:t.join(" "),client_id:this.config.clientID};if(e.response_type===O.Code){this.codeVerifier=U();let u=yield te(this.codeVerifier),g=oe(u);s.code_challenge=g}let c=`${this.config.authorizerURL}/authorize?${re(s)}`;if(s.response_mode!=="web_message"){window.location.replace(c);return}try{let u=yield ie(c,this.config.authorizerURL,60);return e.response_type===O.Code?yield this.getToken({code:u.code}):u}catch(u){throw u.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),u}}),"authorize"));d(this,"browserLogin",n(()=>f(this,null,function*(){try{return yield this.getSession()}catch(e){if(!R())throw new Error("browserLogin is only supported for browsers");window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`)}}),"browserLogin"));d(this,"forgotPassword",n(e=>f(this,null,function*(){e.state||(e.state=v(U())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{return(yield this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}})).forgot_password}catch(t){throw new Error(t)}}),"forgotPassword"));d(this,"getMetaData",n(()=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_twitch_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"})).meta}catch(e){throw new Error(e)}}),"getMetaData"));d(this,"getProfile",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`query { profile { ${H} } }`,headers:e})).profile}catch(t){throw new Error(t)}}),"getProfile"));d(this,"getSession",n((e,t)=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${x} } }`,headers:e,variables:{params:t}})).session}catch(s){throw new Error(s)}}),"getSession"));d(this,"getToken",n(e=>f(this,null,function*(){if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)throw new Error("Invalid refresh_token");if(e.grant_type==="authorization_code"&&!this.codeVerifier)throw new Error("Invalid code verifier");let t={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let c=yield z()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(t),headers:I({},this.config.extraHeaders),credentials:"include"}),u=yield c.json();if(c.status>=400)throw new Error(u);return u}catch(s){throw new Error(s)}}),"getToken"));d(this,"graphqlQuery",n(e=>f(this,null,function*(){let c=yield(yield z()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:I(I({},this.config.extraHeaders),e.headers||{}),credentials:"include"})).json();if(c.errors&&c.errors.length)throw console.error(c.errors),new Error(c.errors[0].message);return c.data}),"graphqlQuery"));d(this,"login",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`
|
|
1
|
+
var authorizerdev=(()=>{var pe=Object.create;var A=Object.defineProperty,ye=Object.defineProperties,_e=Object.getOwnPropertyDescriptor,we=Object.getOwnPropertyDescriptors,me=Object.getOwnPropertyNames,J=Object.getOwnPropertySymbols,ge=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty,be=Object.prototype.propertyIsEnumerable;var j=(o,e,t)=>e in o?A(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,I=(o,e)=>{for(var t in e||(e={}))G.call(e,t)&&j(o,t,e[t]);if(J)for(var t of J(e))be.call(e,t)&&j(o,t,e[t]);return o},W=(o,e)=>ye(o,we(e)),n=(o,e)=>A(o,"name",{value:e,configurable:!0});var ve=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),Ee=(o,e)=>{for(var t in e)A(o,t,{get:e[t],enumerable:!0})},Z=(o,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of me(e))!G.call(o,c)&&c!==t&&A(o,c,{get:()=>e[c],enumerable:!(s=_e(e,c))||s.enumerable});return o};var Te=(o,e,t)=>(t=o!=null?pe(ge(o)):{},Z(e||!o||!o.__esModule?A(t,"default",{value:o,enumerable:!0}):t,o)),Re=o=>Z(A({},"__esModule",{value:!0}),o);var d=(o,e,t)=>(j(o,typeof e!="symbol"?e+"":e,t),t);var f=(o,e,t)=>new Promise((s,c)=>{var u=m=>{try{w(t.next(m))}catch(_){c(_)}},g=m=>{try{w(t.throw(m))}catch(_){c(_)}},w=m=>m.done?s(m.value):Promise.resolve(m.value).then(u,g);w((t=t.apply(o,e)).next())});var Y=ve((v,K)=>{var X=typeof self!="undefined"?self:v,$=function(){function o(){this.fetch=!1,this.DOMException=X.DOMException}return n(o,"F"),o.prototype=X,new o}();(function(o){var e=function(t){var s={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch(r){return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function c(r){return r&&DataView.prototype.isPrototypeOf(r)}if(n(c,"isDataView"),s.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],g=ArrayBuffer.isView||function(r){return r&&u.indexOf(Object.prototype.toString.call(r))>-1};function w(r){if(typeof r!="string"&&(r=String(r)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(r))throw new TypeError("Invalid character in header field name");return r.toLowerCase()}n(w,"normalizeName");function m(r){return typeof r!="string"&&(r=String(r)),r}n(m,"normalizeValue");function _(r){var i={next:function(){var a=r.shift();return{done:a===void 0,value:a}}};return s.iterable&&(i[Symbol.iterator]=function(){return i}),i}n(_,"iteratorFor");function l(r){this.map={},r instanceof l?r.forEach(function(i,a){this.append(a,i)},this):Array.isArray(r)?r.forEach(function(i){this.append(i[0],i[1])},this):r&&Object.getOwnPropertyNames(r).forEach(function(i){this.append(i,r[i])},this)}n(l,"Headers"),l.prototype.append=function(r,i){r=w(r),i=m(i);var a=this.map[r];this.map[r]=a?a+", "+i:i},l.prototype.delete=function(r){delete this.map[w(r)]},l.prototype.get=function(r){return r=w(r),this.has(r)?this.map[r]:null},l.prototype.has=function(r){return this.map.hasOwnProperty(w(r))},l.prototype.set=function(r,i){this.map[w(r)]=m(i)},l.prototype.forEach=function(r,i){for(var a in this.map)this.map.hasOwnProperty(a)&&r.call(i,this.map[a],a,this)},l.prototype.keys=function(){var r=[];return this.forEach(function(i,a){r.push(a)}),_(r)},l.prototype.values=function(){var r=[];return this.forEach(function(i){r.push(i)}),_(r)},l.prototype.entries=function(){var r=[];return this.forEach(function(i,a){r.push([a,i])}),_(r)},s.iterable&&(l.prototype[Symbol.iterator]=l.prototype.entries);function B(r){if(r.bodyUsed)return Promise.reject(new TypeError("Already read"));r.bodyUsed=!0}n(B,"consumed");function N(r){return new Promise(function(i,a){r.onload=function(){i(r.result)},r.onerror=function(){a(r.error)}})}n(N,"fileReaderReady");function se(r){var i=new FileReader,a=N(i);return i.readAsArrayBuffer(r),a}n(se,"readBlobAsArrayBuffer");function ae(r){var i=new FileReader,a=N(i);return i.readAsText(r),a}n(ae,"readBlobAsText");function ce(r){for(var i=new Uint8Array(r),a=new Array(i.length),y=0;y<i.length;y++)a[y]=String.fromCharCode(i[y]);return a.join("")}n(ce,"readArrayBufferAsText");function Q(r){if(r.slice)return r.slice(0);var i=new Uint8Array(r.byteLength);return i.set(new Uint8Array(r)),i.buffer}n(Q,"bufferClone");function V(){return this.bodyUsed=!1,this._initBody=function(r){this._bodyInit=r,r?typeof r=="string"?this._bodyText=r:s.blob&&Blob.prototype.isPrototypeOf(r)?this._bodyBlob=r:s.formData&&FormData.prototype.isPrototypeOf(r)?this._bodyFormData=r:s.searchParams&&URLSearchParams.prototype.isPrototypeOf(r)?this._bodyText=r.toString():s.arrayBuffer&&s.blob&&c(r)?(this._bodyArrayBuffer=Q(r.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(r)||g(r))?this._bodyArrayBuffer=Q(r):this._bodyText=r=Object.prototype.toString.call(r):this._bodyText="",this.headers.get("content-type")||(typeof r=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):s.searchParams&&URLSearchParams.prototype.isPrototypeOf(r)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},s.blob&&(this.blob=function(){var r=B(this);if(r)return r;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?B(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(se)}),this.text=function(){var r=B(this);if(r)return r;if(this._bodyBlob)return ae(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(ce(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},s.formData&&(this.formData=function(){return this.text().then(fe)}),this.json=function(){return this.text().then(JSON.parse)},this}n(V,"Body");var ue=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function he(r){var i=r.toUpperCase();return ue.indexOf(i)>-1?i:r}n(he,"normalizeMethod");function T(r,i){i=i||{};var a=i.body;if(r instanceof T){if(r.bodyUsed)throw new TypeError("Already read");this.url=r.url,this.credentials=r.credentials,i.headers||(this.headers=new l(r.headers)),this.method=r.method,this.mode=r.mode,this.signal=r.signal,!a&&r._bodyInit!=null&&(a=r._bodyInit,r.bodyUsed=!0)}else this.url=String(r);if(this.credentials=i.credentials||this.credentials||"same-origin",(i.headers||!this.headers)&&(this.headers=new l(i.headers)),this.method=he(i.method||this.method||"GET"),this.mode=i.mode||this.mode||null,this.signal=i.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&a)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(a)}n(T,"Request"),T.prototype.clone=function(){return new T(this,{body:this._bodyInit})};function fe(r){var i=new FormData;return r.trim().split("&").forEach(function(a){if(a){var y=a.split("="),p=y.shift().replace(/\+/g," "),h=y.join("=").replace(/\+/g," ");i.append(decodeURIComponent(p),decodeURIComponent(h))}}),i}n(fe,"decode");function de(r){var i=new l,a=r.replace(/\r?\n[\t ]+/g," ");return a.split(/\r?\n/).forEach(function(y){var p=y.split(":"),h=p.shift().trim();if(h){var k=p.join(":").trim();i.append(h,k)}}),i}n(de,"parseHeaders"),V.call(T.prototype);function b(r,i){i||(i={}),this.type="default",this.status=i.status===void 0?200:i.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in i?i.statusText:"OK",this.headers=new l(i.headers),this.url=i.url||"",this._initBody(r)}n(b,"Response"),V.call(b.prototype),b.prototype.clone=function(){return new b(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new l(this.headers),url:this.url})},b.error=function(){var r=new b(null,{status:0,statusText:""});return r.type="error",r};var le=[301,302,303,307,308];b.redirect=function(r,i){if(le.indexOf(i)===-1)throw new RangeError("Invalid status code");return new b(null,{status:i,headers:{location:r}})},t.DOMException=o.DOMException;try{new t.DOMException}catch(r){t.DOMException=function(i,a){this.message=i,this.name=a;var y=Error(i);this.stack=y.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function D(r,i){return new Promise(function(a,y){var p=new T(r,i);if(p.signal&&p.signal.aborted)return y(new t.DOMException("Aborted","AbortError"));var h=new XMLHttpRequest;function k(){h.abort()}n(k,"abortXhr"),h.onload=function(){var S={status:h.status,statusText:h.statusText,headers:de(h.getAllResponseHeaders()||"")};S.url="responseURL"in h?h.responseURL:S.headers.get("X-Request-URL");var C="response"in h?h.response:h.responseText;a(new b(C,S))},h.onerror=function(){y(new TypeError("Network request failed"))},h.ontimeout=function(){y(new TypeError("Network request failed"))},h.onabort=function(){y(new t.DOMException("Aborted","AbortError"))},h.open(p.method,p.url,!0),p.credentials==="include"?h.withCredentials=!0:p.credentials==="omit"&&(h.withCredentials=!1),"responseType"in h&&s.blob&&(h.responseType="blob"),p.headers.forEach(function(S,C){h.setRequestHeader(C,S)}),p.signal&&(p.signal.addEventListener("abort",k),h.onreadystatechange=function(){h.readyState===4&&p.signal.removeEventListener("abort",k)}),h.send(typeof p._bodyInit=="undefined"?null:p._bodyInit)})}return n(D,"fetch"),D.polyfill=!0,o.fetch||(o.fetch=D,o.Headers=l,o.Request=T,o.Response=b),t.Headers=l,t.Request=T,t.Response=b,t.fetch=D,Object.defineProperty(t,"__esModule",{value:!0}),t}({})})($);$.fetch.ponyfill=!0;delete $.fetch.polyfill;var L=$;v=L.fetch;v.default=L.fetch;v.fetch=L.fetch;v.Headers=L.Headers;v.Request=L.Request;v.Response=L.Response;K.exports=v});var Oe={};Ee(Oe,{Authorizer:()=>P,OAuthProviders:()=>q,ResponseTypes:()=>O});var ne=Te(Y());var q;(function(o){o.Apple="apple",o.Github="github",o.Google="google",o.Facebook="facebook",o.LinkedIn="linkedin",o.Twitter="twitter",o.Microsoft="microsoft",o.Twitch="twitch"})(q||(q={}));var O;(function(o){o.Code="code",o.Token="token"})(O||(O={}));var R=n(()=>typeof window!="undefined","hasWindow"),M=n(o=>{let e=o.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),ee=n(()=>R()?window.crypto||window.msCrypto:null,"getCrypto"),Ie=n(()=>{let o=ee();return o&&o.subtle||o.webkitSubtle},"getCryptoSubtle"),U=n(()=>{let o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",t=ee();return t&&Array.from(t.getRandomValues(new Uint8Array(43))).forEach(c=>e+=o[c%o.length]),e},"createRandomString"),E=n(o=>R()?btoa(o):Buffer.from(o).toString("base64"),"encode");var re=n(o=>Object.keys(o).filter(e=>typeof o[e]!="undefined").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(o[e])}`).join("&"),"createQueryParams"),te=n(o=>f(void 0,null,function*(){let e=Ie().digest({name:"SHA-256"},new TextEncoder().encode(o));return window.msCrypto?new Promise((t,s)=>{e.oncomplete=c=>{t(c.target.result)},e.onerror=c=>{s(c.error)},e.onabort=()=>{s(new Error("The digest operation was aborted"))}}):yield e}),"sha256"),Le=n(o=>{let e={"+":"-","/":"_","=":""};return o.replace(/[+/=]/g,t=>e[t])},"urlEncodeB64");var oe=n(o=>{let e=new Uint8Array(o);return Le(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),ie=n((o,e,t=60)=>new Promise((s,c)=>{let u=window.document.createElement("iframe");u.setAttribute("id","authorizer-iframe"),u.setAttribute("width","0"),u.setAttribute("height","0"),u.style.display="none";let g,w=n(()=>{window.document.body.contains(u)&&(window.document.body.removeChild(u),window.removeEventListener("message",g,!1))},"removeIframe"),m=setTimeout(()=>{w()},t*1e3);g=n(function(_){if(_.origin!==e||!_.data||!_.data.response)return;let l=_.source;l&&l.close(),_.data.response.error?c(_.data.response):s(_.data.response),clearTimeout(m),window.removeEventListener("message",g,!1),setTimeout(w,2*1e3)},"iframeEventHandler"),window.addEventListener("message",g,!1),window.document.body.appendChild(u),u.setAttribute("src",o)}),"executeIframe");var H="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",x=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen should_show_totp_screen authenticator_scanner_image authenticator_secret authenticator_recovery_codes user { ${H} }`,z=n(()=>R()?window.fetch:ne.default,"getFetcher"),P=class{constructor(e){d(this,"authorize",n(e=>f(this,null,function*(){if(!R())throw new Error("this feature is only supported in browser");let t=["openid","profile","email"];e.use_refresh_token&&t.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:E(U()),nonce:E(U()),response_type:e.response_type,scope:t.join(" "),client_id:this.config.clientID};if(e.response_type===O.Code){this.codeVerifier=U();let u=yield te(this.codeVerifier),g=oe(u);s.code_challenge=g}let c=`${this.config.authorizerURL}/authorize?${re(s)}`;if(s.response_mode!=="web_message"){window.location.replace(c);return}try{let u=yield ie(c,this.config.authorizerURL,60);return e.response_type===O.Code?yield this.getToken({code:u.code}):u}catch(u){throw u.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${E(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),u}}),"authorize"));d(this,"browserLogin",n(()=>f(this,null,function*(){try{return yield this.getSession()}catch(e){if(!R())throw new Error("browserLogin is only supported for browsers");window.location.replace(`${this.config.authorizerURL}/app?state=${E(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`)}}),"browserLogin"));d(this,"forgotPassword",n(e=>f(this,null,function*(){e.state||(e.state=E(U())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{return(yield this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}})).forgot_password}catch(t){throw new Error(t)}}),"forgotPassword"));d(this,"getMetaData",n(()=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_twitch_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled is_multi_factor_auth_enabled is_mobile_basic_authentication_enabled is_phone_verification_enabled } }"})).meta}catch(e){throw new Error(e)}}),"getMetaData"));d(this,"getProfile",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`query { profile { ${H} } }`,headers:e})).profile}catch(t){throw new Error(t)}}),"getProfile"));d(this,"getSession",n((e,t)=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${x} } }`,headers:e,variables:{params:t}})).session}catch(s){throw new Error(s)}}),"getSession"));d(this,"getToken",n(e=>f(this,null,function*(){if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)throw new Error("Invalid refresh_token");if(e.grant_type==="authorization_code"&&!this.codeVerifier)throw new Error("Invalid code verifier");let t={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let c=yield z()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(t),headers:I({},this.config.extraHeaders),credentials:"include"}),u=yield c.json();if(c.status>=400)throw new Error(u);return u}catch(s){throw new Error(s)}}),"getToken"));d(this,"graphqlQuery",n(e=>f(this,null,function*(){let c=yield(yield z()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:I(I({},this.config.extraHeaders),e.headers||{}),credentials:"include"})).json();if(c.errors&&c.errors.length)throw console.error(c.errors),new Error(c.errors[0].message);return c.data}),"graphqlQuery"));d(this,"login",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`
|
|
2
2
|
mutation login($data: LoginInput!) { login(params: $data) { ${x}}}
|
|
3
|
-
`,variables:{data:e}})).login}catch(t){throw new Error(t)}}),"login"));d(this,"logout",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:" mutation { logout { message } } ",headers:e})).logout}catch(t){console.error(t)}}),"logout"));d(this,"magicLinkLogin",n(e=>f(this,null,function*(){try{return e.state||(e.state=
|
|
3
|
+
`,variables:{data:e}})).login}catch(t){throw new Error(t)}}),"login"));d(this,"logout",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:" mutation { logout { message } } ",headers:e})).logout}catch(t){console.error(t)}}),"logout"));d(this,"magicLinkLogin",n(e=>f(this,null,function*(){try{return e.state||(e.state=E(U())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL),(yield this.graphqlQuery({query:`
|
|
4
4
|
mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }}
|
|
5
|
-
`,variables:{data:e}})).magic_link_login}catch(t){throw new Error(t)}}),"magicLinkLogin"));d(this,"oauthLogin",n((e,t,s,c)=>f(this,null,function*(){let u=c;if(u||(u=
|
|
5
|
+
`,variables:{data:e}})).magic_link_login}catch(t){throw new Error(t)}}),"magicLinkLogin"));d(this,"oauthLogin",n((e,t,s,c)=>f(this,null,function*(){let u=c;if(u||(u=E(U())),!Object.values(q).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!R())throw new Error("oauthLogin is only supported for browsers");t&&t.length&&(u+=`&roles=${t.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${s||this.config.redirectURL}&state=${u}`)}),"oauthLogin"));d(this,"resendOtp",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`
|
|
6
6
|
mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }}
|
|
7
7
|
`,variables:{data:e}})).resend_otp}catch(t){throw new Error(t)}}),"resendOtp"));d(this,"resetPassword",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}})).reset_password}catch(t){throw new Error(t)}}),"resetPassword"));d(this,"revokeToken",n(e=>f(this,null,function*(){if(!e.refresh_token&&!e.refresh_token.trim())throw new Error("Invalid refresh_token");return yield(yield z()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:I({},this.config.extraHeaders),body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})})).json()}),"revokeToken"));d(this,"signup",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`
|
|
8
8
|
mutation signup($data: SignUpInput!) { signup(params: $data) { ${x}}}
|
package/lib/index.d.ts
CHANGED
|
@@ -86,6 +86,7 @@ interface VerifyOtpInput {
|
|
|
86
86
|
phone_number?: string;
|
|
87
87
|
otp: string;
|
|
88
88
|
state?: string;
|
|
89
|
+
is_totp?: boolean;
|
|
89
90
|
}
|
|
90
91
|
interface ResendOtpInput {
|
|
91
92
|
email?: string;
|
|
@@ -112,6 +113,9 @@ interface MetaData {
|
|
|
112
113
|
is_magic_link_login_enabled: boolean;
|
|
113
114
|
is_sign_up_enabled: boolean;
|
|
114
115
|
is_strong_password_enabled: boolean;
|
|
116
|
+
is_multi_factor_auth_enabled: boolean;
|
|
117
|
+
is_mobile_basic_authentication_enabled: boolean;
|
|
118
|
+
is_phone_verification_enabled: boolean;
|
|
115
119
|
}
|
|
116
120
|
interface UpdateProfileInput {
|
|
117
121
|
old_password?: string;
|
package/lib/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var S=Object.create;var p=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var O=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var n=(t,e)=>p(t,"name",{value:e,configurable:!0});var P=(t,e)=>{for(var r in e)p(t,r,{get:e[r],enumerable:!0})},
|
|
1
|
+
var S=Object.create;var p=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var O=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var n=(t,e)=>p(t,"name",{value:e,configurable:!0});var P=(t,e)=>{for(var r in e)p(t,r,{get:e[r],enumerable:!0})},R=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of C(e))!z.call(t,o)&&o!==r&&p(t,o,{get:()=>e[o],enumerable:!(i=x(e,o))||i.enumerable});return t};var Q=(t,e,r)=>(r=t!=null?S(O(t)):{},R(e||!t||!t.__esModule?p(r,"default",{value:t,enumerable:!0}):r,t)),A=t=>R(p({},"__esModule",{value:!0}),t);var M={};P(M,{Authorizer:()=>w,OAuthProviders:()=>_,ResponseTypes:()=>l});module.exports=A(M);var k=Q(require("cross-fetch"));var _;(function(t){t.Apple="apple",t.Github="github",t.Google="google",t.Facebook="facebook",t.LinkedIn="linkedin",t.Twitter="twitter",t.Microsoft="microsoft",t.Twitch="twitch"})(_||(_={}));var l;(function(t){t.Code="code",t.Token="token"})(l||(l={}));var d=n(()=>typeof window<"u","hasWindow"),m=n(t=>{let e=t.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),U=n(()=>d()?window.crypto||window.msCrypto:null,"getCrypto"),j=n(()=>{let t=U();return t&&t.subtle||t.webkitSubtle},"getCryptoSubtle"),h=n(()=>{let t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",r=U();return r&&Array.from(r.getRandomValues(new Uint8Array(43))).forEach(o=>e+=t[o%t.length]),e},"createRandomString"),a=n(t=>d()?btoa(t):Buffer.from(t).toString("base64"),"encode");var T=n(t=>Object.keys(t).filter(e=>typeof t[e]<"u").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`).join("&"),"createQueryParams"),$=n(async t=>{let e=j().digest({name:"SHA-256"},new TextEncoder().encode(t));return window.msCrypto?new Promise((r,i)=>{e.oncomplete=o=>{r(o.target.result)},e.onerror=o=>{i(o.error)},e.onabort=()=>{i(new Error("The digest operation was aborted"))}}):await e},"sha256"),F=n(t=>{let e={"+":"-","/":"_","=":""};return t.replace(/[+/=]/g,r=>e[r])},"urlEncodeB64");var L=n(t=>{let e=new Uint8Array(t);return F(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),I=n((t,e,r=60)=>new Promise((i,o)=>{let s=window.document.createElement("iframe");s.setAttribute("id","authorizer-iframe"),s.setAttribute("width","0"),s.setAttribute("height","0"),s.style.display="none";let c,E=n(()=>{window.document.body.contains(s)&&(window.document.body.removeChild(s),window.removeEventListener("message",c,!1))},"removeIframe"),q=setTimeout(()=>{E()},r*1e3);c=n(function(u){if(u.origin!==e||!u.data||!u.data.response)return;let v=u.source;v&&v.close(),u.data.response.error?o(u.data.response):i(u.data.response),clearTimeout(q),window.removeEventListener("message",c,!1),setTimeout(E,2*1e3)},"iframeEventHandler"),window.addEventListener("message",c,!1),window.document.body.appendChild(s),s.setAttribute("src",t)}),"executeIframe");var b="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",f=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen should_show_totp_screen authenticator_scanner_image authenticator_secret authenticator_recovery_codes user { ${b} }`,y=n(()=>d()?window.fetch:k.default,"getFetcher"),w=class{constructor(e){if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=m(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=m(e.redirectURL),this.config.extraHeaders={...e.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=e.clientID.trim()}authorize=async e=>{if(!d())throw new Error("this feature is only supported in browser");let r=["openid","profile","email"];e.use_refresh_token&&r.push("offline_access");let i={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:a(h()),nonce:a(h()),response_type:e.response_type,scope:r.join(" "),client_id:this.config.clientID};if(e.response_type===l.Code){this.codeVerifier=h();let s=await $(this.codeVerifier),c=L(s);i.code_challenge=c}let o=`${this.config.authorizerURL}/authorize?${T(i)}`;if(i.response_mode!=="web_message"){window.location.replace(o);return}try{let s=await I(o,this.config.authorizerURL,60);return e.response_type===l.Code?await this.getToken({code:s.code}):s}catch(s){throw s.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${a(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),s}};browserLogin=async()=>{try{return await this.getSession()}catch{if(!d())throw new Error("browserLogin is only supported for browsers");window.location.replace(`${this.config.authorizerURL}/app?state=${a(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`)}};forgotPassword=async e=>{e.state||(e.state=a(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{return(await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}})).forgot_password}catch(r){throw new Error(r)}};getMetaData=async()=>{try{return(await this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_twitch_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled is_multi_factor_auth_enabled is_mobile_basic_authentication_enabled is_phone_verification_enabled } }"})).meta}catch(e){throw new Error(e)}};getProfile=async e=>{try{return(await this.graphqlQuery({query:`query { profile { ${b} } }`,headers:e})).profile}catch(r){throw new Error(r)}};getSession=async(e,r)=>{try{return(await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${f} } }`,headers:e,variables:{params:r}})).session}catch(i){throw new Error(i)}};getToken=async e=>{if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)throw new Error("Invalid refresh_token");if(e.grant_type==="authorization_code"&&!this.codeVerifier)throw new Error("Invalid code verifier");let r={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let o=await y()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(r),headers:{...this.config.extraHeaders},credentials:"include"}),s=await o.json();if(o.status>=400)throw new Error(s);return s}catch(i){throw new Error(i)}};graphqlQuery=async e=>{let o=await(await y()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:{...this.config.extraHeaders,...e.headers||{}},credentials:"include"})).json();if(o.errors&&o.errors.length)throw console.error(o.errors),new Error(o.errors[0].message);return o.data};login=async e=>{try{return(await this.graphqlQuery({query:`
|
|
2
2
|
mutation login($data: LoginInput!) { login(params: $data) { ${f}}}
|
|
3
3
|
`,variables:{data:e}})).login}catch(r){throw new Error(r)}};logout=async e=>{try{return(await this.graphqlQuery({query:" mutation { logout { message } } ",headers:e})).logout}catch(r){console.error(r)}};magicLinkLogin=async e=>{try{return e.state||(e.state=a(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL),(await this.graphqlQuery({query:`
|
|
4
4
|
mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }}
|
|
5
|
-
`,variables:{data:e}})).magic_link_login}catch(r){throw new Error(r)}};oauthLogin=async(e,r,
|
|
5
|
+
`,variables:{data:e}})).magic_link_login}catch(r){throw new Error(r)}};oauthLogin=async(e,r,i,o)=>{let s=o;if(s||(s=a(h())),!Object.values(_).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!d())throw new Error("oauthLogin is only supported for browsers");r&&r.length&&(s+=`&roles=${r.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${i||this.config.redirectURL}&state=${s}`)};resendOtp=async e=>{try{return(await this.graphqlQuery({query:`
|
|
6
6
|
mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }}
|
|
7
7
|
`,variables:{data:e}})).resend_otp}catch(r){throw new Error(r)}};resetPassword=async e=>{try{return(await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}})).reset_password}catch(r){throw new Error(r)}};revokeToken=async e=>{if(!e.refresh_token&&!e.refresh_token.trim())throw new Error("Invalid refresh_token");return await(await y()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:{...this.config.extraHeaders},body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})})).json()};signup=async e=>{try{return(await this.graphqlQuery({query:`
|
|
8
8
|
mutation signup($data: SignUpInput!) { signup(params: $data) { ${f}}}
|
|
9
|
-
`,variables:{data:e}})).signup}catch(r){throw new Error(r)}};updateProfile=async(e,r)=>{try{return(await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:r,variables:{data:e}})).update_profile}catch(
|
|
9
|
+
`,variables:{data:e}})).signup}catch(r){throw new Error(r)}};updateProfile=async(e,r)=>{try{return(await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:r,variables:{data:e}})).update_profile}catch(i){throw new Error(i)}};deactivateAccount=async e=>{try{return(await this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e})).deactivate_account}catch(r){throw new Error(r)}};validateJWTToken=async e=>{try{return(await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}})).validate_jwt_token}catch(r){throw new Error(r)}};validateSession=async e=>{try{return(await this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${b} } } }`,variables:{params:e}})).validate_session}catch(r){throw new Error(r)}};verifyEmail=async e=>{try{return(await this.graphqlQuery({query:`
|
|
10
10
|
mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${f}}}
|
|
11
11
|
`,variables:{data:e}})).verify_email}catch(r){throw new Error(r)}};verifyOtp=async e=>{try{return(await this.graphqlQuery({query:`
|
|
12
12
|
mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${f}}}
|
package/lib/index.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var I=Object.defineProperty;var n=(t,e)=>I(t,"name",{value:e,configurable:!0});import C from"cross-fetch";var _;(function(t){t.Apple="apple",t.Github="github",t.Google="google",t.Facebook="facebook",t.LinkedIn="linkedin",t.Twitter="twitter",t.Microsoft="microsoft",t.Twitch="twitch"})(_||(_={}));var l;(function(t){t.Code="code",t.Token="token"})(l||(l={}));var d=n(()=>typeof window<"u","hasWindow"),w=n(t=>{let e=t.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),
|
|
1
|
+
var I=Object.defineProperty;var n=(t,e)=>I(t,"name",{value:e,configurable:!0});import C from"cross-fetch";var _;(function(t){t.Apple="apple",t.Github="github",t.Google="google",t.Facebook="facebook",t.LinkedIn="linkedin",t.Twitter="twitter",t.Microsoft="microsoft",t.Twitch="twitch"})(_||(_={}));var l;(function(t){t.Code="code",t.Token="token"})(l||(l={}));var d=n(()=>typeof window<"u","hasWindow"),w=n(t=>{let e=t.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),v=n(()=>d()?window.crypto||window.msCrypto:null,"getCrypto"),S=n(()=>{let t=v();return t&&t.subtle||t.webkitSubtle},"getCryptoSubtle"),h=n(()=>{let t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",r=v();return r&&Array.from(r.getRandomValues(new Uint8Array(43))).forEach(s=>e+=t[s%t.length]),e},"createRandomString"),a=n(t=>d()?btoa(t):Buffer.from(t).toString("base64"),"encode");var R=n(t=>Object.keys(t).filter(e=>typeof t[e]<"u").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`).join("&"),"createQueryParams"),U=n(async t=>{let e=S().digest({name:"SHA-256"},new TextEncoder().encode(t));return window.msCrypto?new Promise((r,i)=>{e.oncomplete=s=>{r(s.target.result)},e.onerror=s=>{i(s.error)},e.onabort=()=>{i(new Error("The digest operation was aborted"))}}):await e},"sha256"),x=n(t=>{let e={"+":"-","/":"_","=":""};return t.replace(/[+/=]/g,r=>e[r])},"urlEncodeB64");var T=n(t=>{let e=new Uint8Array(t);return x(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),$=n((t,e,r=60)=>new Promise((i,s)=>{let o=window.document.createElement("iframe");o.setAttribute("id","authorizer-iframe"),o.setAttribute("width","0"),o.setAttribute("height","0"),o.style.display="none";let c,b=n(()=>{window.document.body.contains(o)&&(window.document.body.removeChild(o),window.removeEventListener("message",c,!1))},"removeIframe"),L=setTimeout(()=>{b()},r*1e3);c=n(function(u){if(u.origin!==e||!u.data||!u.data.response)return;let E=u.source;E&&E.close(),u.data.response.error?s(u.data.response):i(u.data.response),clearTimeout(L),window.removeEventListener("message",c,!1),setTimeout(b,2*1e3)},"iframeEventHandler"),window.addEventListener("message",c,!1),window.document.body.appendChild(o),o.setAttribute("src",t)}),"executeIframe");var y="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",p=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen should_show_totp_screen authenticator_scanner_image authenticator_secret authenticator_recovery_codes user { ${y} }`,g=n(()=>d()?window.fetch:C,"getFetcher"),m=class{constructor(e){if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=w(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=w(e.redirectURL),this.config.extraHeaders={...e.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=e.clientID.trim()}authorize=async e=>{if(!d())throw new Error("this feature is only supported in browser");let r=["openid","profile","email"];e.use_refresh_token&&r.push("offline_access");let i={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:a(h()),nonce:a(h()),response_type:e.response_type,scope:r.join(" "),client_id:this.config.clientID};if(e.response_type===l.Code){this.codeVerifier=h();let o=await U(this.codeVerifier),c=T(o);i.code_challenge=c}let s=`${this.config.authorizerURL}/authorize?${R(i)}`;if(i.response_mode!=="web_message"){window.location.replace(s);return}try{let o=await $(s,this.config.authorizerURL,60);return e.response_type===l.Code?await this.getToken({code:o.code}):o}catch(o){throw o.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${a(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),o}};browserLogin=async()=>{try{return await this.getSession()}catch{if(!d())throw new Error("browserLogin is only supported for browsers");window.location.replace(`${this.config.authorizerURL}/app?state=${a(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`)}};forgotPassword=async e=>{e.state||(e.state=a(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{return(await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}})).forgot_password}catch(r){throw new Error(r)}};getMetaData=async()=>{try{return(await this.graphqlQuery({query:"query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_twitch_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled is_multi_factor_auth_enabled is_mobile_basic_authentication_enabled is_phone_verification_enabled } }"})).meta}catch(e){throw new Error(e)}};getProfile=async e=>{try{return(await this.graphqlQuery({query:`query { profile { ${y} } }`,headers:e})).profile}catch(r){throw new Error(r)}};getSession=async(e,r)=>{try{return(await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${p} } }`,headers:e,variables:{params:r}})).session}catch(i){throw new Error(i)}};getToken=async e=>{if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)throw new Error("Invalid refresh_token");if(e.grant_type==="authorization_code"&&!this.codeVerifier)throw new Error("Invalid code verifier");let r={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let s=await g()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(r),headers:{...this.config.extraHeaders},credentials:"include"}),o=await s.json();if(s.status>=400)throw new Error(o);return o}catch(i){throw new Error(i)}};graphqlQuery=async e=>{let s=await(await g()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:{...this.config.extraHeaders,...e.headers||{}},credentials:"include"})).json();if(s.errors&&s.errors.length)throw console.error(s.errors),new Error(s.errors[0].message);return s.data};login=async e=>{try{return(await this.graphqlQuery({query:`
|
|
2
2
|
mutation login($data: LoginInput!) { login(params: $data) { ${p}}}
|
|
3
3
|
`,variables:{data:e}})).login}catch(r){throw new Error(r)}};logout=async e=>{try{return(await this.graphqlQuery({query:" mutation { logout { message } } ",headers:e})).logout}catch(r){console.error(r)}};magicLinkLogin=async e=>{try{return e.state||(e.state=a(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL),(await this.graphqlQuery({query:`
|
|
4
4
|
mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }}
|
|
5
|
-
`,variables:{data:e}})).magic_link_login}catch(r){throw new Error(r)}};oauthLogin=async(e,r,s
|
|
5
|
+
`,variables:{data:e}})).magic_link_login}catch(r){throw new Error(r)}};oauthLogin=async(e,r,i,s)=>{let o=s;if(o||(o=a(h())),!Object.values(_).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!d())throw new Error("oauthLogin is only supported for browsers");r&&r.length&&(o+=`&roles=${r.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${i||this.config.redirectURL}&state=${o}`)};resendOtp=async e=>{try{return(await this.graphqlQuery({query:`
|
|
6
6
|
mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }}
|
|
7
7
|
`,variables:{data:e}})).resend_otp}catch(r){throw new Error(r)}};resetPassword=async e=>{try{return(await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}})).reset_password}catch(r){throw new Error(r)}};revokeToken=async e=>{if(!e.refresh_token&&!e.refresh_token.trim())throw new Error("Invalid refresh_token");return await(await g()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:{...this.config.extraHeaders},body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})})).json()};signup=async e=>{try{return(await this.graphqlQuery({query:`
|
|
8
8
|
mutation signup($data: SignUpInput!) { signup(params: $data) { ${p}}}
|
|
9
|
-
`,variables:{data:e}})).signup}catch(r){throw new Error(r)}};updateProfile=async(e,r)=>{try{return(await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:r,variables:{data:e}})).update_profile}catch(
|
|
9
|
+
`,variables:{data:e}})).signup}catch(r){throw new Error(r)}};updateProfile=async(e,r)=>{try{return(await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:r,variables:{data:e}})).update_profile}catch(i){throw new Error(i)}};deactivateAccount=async e=>{try{return(await this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e})).deactivate_account}catch(r){throw new Error(r)}};validateJWTToken=async e=>{try{return(await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}})).validate_jwt_token}catch(r){throw new Error(r)}};validateSession=async e=>{try{return(await this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${y} } } }`,variables:{params:e}})).validate_session}catch(r){throw new Error(r)}};verifyEmail=async e=>{try{return(await this.graphqlQuery({query:`
|
|
10
10
|
mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${p}}}
|
|
11
11
|
`,variables:{data:e}})).verify_email}catch(r){throw new Error(r)}};verifyOtp=async e=>{try{return(await this.graphqlQuery({query:`
|
|
12
12
|
mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${p}}}
|