@authorizerdev/authorizer-js 1.2.18 → 2.0.0-beta.0

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/README.md CHANGED
@@ -7,6 +7,10 @@ It supports:
7
7
  - [CommonJS(cjs)](https://flaviocopes.com/commonjs/) build for NodeJS version that don't support ES Modules
8
8
  - [ESM (ES Modules)](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/) build for modern javascript standard, i.e. ES Modules
9
9
 
10
+ # Migration from 1.x -> 2.x
11
+
12
+ `2.x` version of `@authorizerdev/authorizer-js` has a uniform response structure that will help your applications to get right error codes and success response. Methods here have `{data, errors}` as response object for methods of this library
13
+
10
14
  All the above versions require `Authorizer` instance to be instantiated and used. Instance constructor requires an object with the following keys
11
15
 
12
16
  | Key | Description |
@@ -18,7 +22,7 @@ All the above versions require `Authorizer` instance to be instantiated and used
18
22
 
19
23
  ```js
20
24
  const authRef = new Authorizer({
21
- authorizerURL: "https://app.herokuapp.com",
25
+ authorizerURL: 'https://app.herokuapp.com',
22
26
  redirectURL: window.location.origin,
23
27
  });
24
28
  ```
@@ -38,22 +42,22 @@ const authRef = new Authorizer({
38
42
  const authorizerRef = new authorizerdev.Authorizer({
39
43
  authorizerURL: `AUTHORIZER_URL`,
40
44
  redirectURL: window.location.origin,
41
- clientID: "YOUR_CLIENT_ID", // can be obtained from authorizer dashboard
45
+ clientID: 'YOUR_CLIENT_ID', // can be obtained from authorizer dashboard
42
46
  });
43
47
 
44
48
  // use the button selector as per your application
45
- const logoutBtn = document.getElementById("logout");
46
- logoutBtn.addEventListener("click", async function () {
49
+ const logoutBtn = document.getElementById('logout');
50
+ logoutBtn.addEventListener('click', async function () {
47
51
  await authorizerRef.logout();
48
- window.location.href = "/";
52
+ window.location.href = '/';
49
53
  });
50
54
 
51
55
  async function onLoad() {
52
- const res = await authorizerRef.authorize({
53
- response_type: "code",
56
+ const { data, errors } = await authorizerRef.authorize({
57
+ response_type: 'code',
54
58
  use_refresh_token: false,
55
59
  });
56
- if (res && res.access_token) {
60
+ if (data && data.access_token) {
57
61
  // get user profile using the access token
58
62
  const user = await authorizerRef.getProfile({
59
63
  Authorization: `Bearer ${res.access_token}`,
@@ -80,17 +84,17 @@ yarn add @authorizerdev/authoirzer-js
80
84
  - Step 2: Import and initialize the authorizer instance
81
85
 
82
86
  ```js
83
- const { Authorizer } = require("@authorizerdev/authoirzer-js");
87
+ const { Authorizer } = require('@authorizerdev/authoirzer-js');
84
88
 
85
89
  const authRef = new Authorizer({
86
- authorizerURL: "https://app.heroku.com",
87
- redirectURL: "http://app.heroku.com/app",
90
+ authorizerURL: 'https://app.heroku.com',
91
+ redirectURL: 'http://app.heroku.com/app',
88
92
  });
89
93
 
90
94
  async function main() {
91
95
  await authRef.login({
92
- email: "foo@bar.com",
93
- password: "test",
96
+ email: 'foo@bar.com',
97
+ password: 'test',
94
98
  });
95
99
  }
96
100
  ```
@@ -108,17 +112,17 @@ yarn add @authorizerdev/authorizer-js
108
112
  - Step 2: Import and initialize the authorizer instance
109
113
 
110
114
  ```js
111
- import { Authorizer } from "@authorizerdev/authorizer-js";
115
+ import { Authorizer } from '@authorizerdev/authorizer-js';
112
116
 
113
117
  const authRef = new Authorizer({
114
- authorizerURL: "https://app.heroku.com",
115
- redirectURL: "http://app.heroku.com/app",
118
+ authorizerURL: 'https://app.heroku.com',
119
+ redirectURL: 'http://app.heroku.com/app',
116
120
  });
117
121
 
118
122
  async function main() {
119
123
  await authRef.login({
120
- email: "foo@bar.com",
121
- password: "test",
124
+ email: 'foo@bar.com',
125
+ password: 'test',
122
126
  });
123
127
  }
124
128
  ```
@@ -1,14 +1,16 @@
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
- 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=E(U())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL),(yield this.graphqlQuery({query:`
1
+ var authorizerdev=(()=>{var ye=Object.create;var k=Object.defineProperty,_e=Object.defineProperties,me=Object.getOwnPropertyDescriptor,ge=Object.getOwnPropertyDescriptors,we=Object.getOwnPropertyNames,G=Object.getOwnPropertySymbols,be=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty,Re=Object.prototype.propertyIsEnumerable;var P=(n,e,o)=>e in n?k(n,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):n[e]=o,I=(n,e)=>{for(var o in e||(e={}))W.call(e,o)&&P(n,o,e[o]);if(G)for(var o of G(e))Re.call(e,o)&&P(n,o,e[o]);return n},Z=(n,e)=>_e(n,ge(e)),a=(n,e)=>k(n,"name",{value:e,configurable:!0});var ve=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ee=(n,e)=>{for(var o in e)k(n,o,{get:e[o],enumerable:!0})},X=(n,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of we(e))!W.call(n,r)&&r!==o&&k(n,r,{get:()=>e[r],enumerable:!(s=me(e,r))||s.enumerable});return n};var Te=(n,e,o)=>(o=n!=null?ye(be(n)):{},X(e||!n||!n.__esModule?k(o,"default",{value:n,enumerable:!0}):o,n)),Ue=n=>X(k({},"__esModule",{value:!0}),n);var u=(n,e,o)=>(P(n,typeof e!="symbol"?e+"":e,o),o);var l=(n,e,o)=>new Promise((s,r)=>{var c=m=>{try{w(o.next(m))}catch(_){r(_)}},g=m=>{try{w(o.throw(m))}catch(_){r(_)}},w=m=>m.done?s(m.value):Promise.resolve(m.value).then(c,g);w((o=o.apply(n,e)).next())});var ee=ve((R,Y)=>{var K=typeof self!="undefined"?self:R,$=function(){function n(){this.fetch=!1,this.DOMException=K.DOMException}return a(n,"F"),n.prototype=K,new n}();(function(n){var e=function(o){var s={searchParams:"URLSearchParams"in n,iterable:"Symbol"in n&&"iterator"in Symbol,blob:"FileReader"in n&&"Blob"in n&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in n,arrayBuffer:"ArrayBuffer"in n};function r(t){return t&&DataView.prototype.isPrototypeOf(t)}if(a(r,"isDataView"),s.arrayBuffer)var c=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],g=ArrayBuffer.isView||function(t){return t&&c.indexOf(Object.prototype.toString.call(t))>-1};function w(t){if(typeof t!="string"&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}a(w,"normalizeName");function m(t){return typeof t!="string"&&(t=String(t)),t}a(m,"normalizeValue");function _(t){var i={next:function(){var h=t.shift();return{done:h===void 0,value:h}}};return s.iterable&&(i[Symbol.iterator]=function(){return i}),i}a(_,"iteratorFor");function p(t){this.map={},t instanceof p?t.forEach(function(i,h){this.append(h,i)},this):Array.isArray(t)?t.forEach(function(i){this.append(i[0],i[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(i){this.append(i,t[i])},this)}a(p,"Headers"),p.prototype.append=function(t,i){t=w(t),i=m(i);var h=this.map[t];this.map[t]=h?h+", "+i:i},p.prototype.delete=function(t){delete this.map[w(t)]},p.prototype.get=function(t){return t=w(t),this.has(t)?this.map[t]:null},p.prototype.has=function(t){return this.map.hasOwnProperty(w(t))},p.prototype.set=function(t,i){this.map[w(t)]=m(i)},p.prototype.forEach=function(t,i){for(var h in this.map)this.map.hasOwnProperty(h)&&t.call(i,this.map[h],h,this)},p.prototype.keys=function(){var t=[];return this.forEach(function(i,h){t.push(h)}),_(t)},p.prototype.values=function(){var t=[];return this.forEach(function(i){t.push(i)}),_(t)},p.prototype.entries=function(){var t=[];return this.forEach(function(i,h){t.push([h,i])}),_(t)},s.iterable&&(p.prototype[Symbol.iterator]=p.prototype.entries);function B(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}a(B,"consumed");function Q(t){return new Promise(function(i,h){t.onload=function(){i(t.result)},t.onerror=function(){h(t.error)}})}a(Q,"fileReaderReady");function ae(t){var i=new FileReader,h=Q(i);return i.readAsArrayBuffer(t),h}a(ae,"readBlobAsArrayBuffer");function ce(t){var i=new FileReader,h=Q(i);return i.readAsText(t),h}a(ce,"readBlobAsText");function he(t){for(var i=new Uint8Array(t),h=new Array(i.length),y=0;y<i.length;y++)h[y]=String.fromCharCode(i[y]);return h.join("")}a(he,"readArrayBufferAsText");function V(t){if(t.slice)return t.slice(0);var i=new Uint8Array(t.byteLength);return i.set(new Uint8Array(t)),i.buffer}a(V,"bufferClone");function J(){return this.bodyUsed=!1,this._initBody=function(t){this._bodyInit=t,t?typeof t=="string"?this._bodyText=t:s.blob&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:s.formData&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:s.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():s.arrayBuffer&&s.blob&&r(t)?(this._bodyArrayBuffer=V(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(t)||g(t))?this._bodyArrayBuffer=V(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||(typeof t=="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(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},s.blob&&(this.blob=function(){var t=B(this);if(t)return t;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(ae)}),this.text=function(){var t=B(this);if(t)return t;if(this._bodyBlob)return ce(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(he(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(le)}),this.json=function(){return this.text().then(JSON.parse)},this}a(J,"Body");var ue=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function de(t){var i=t.toUpperCase();return ue.indexOf(i)>-1?i:t}a(de,"normalizeMethod");function E(t,i){i=i||{};var h=i.body;if(t instanceof E){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,i.headers||(this.headers=new p(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,!h&&t._bodyInit!=null&&(h=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=i.credentials||this.credentials||"same-origin",(i.headers||!this.headers)&&(this.headers=new p(i.headers)),this.method=de(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")&&h)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(h)}a(E,"Request"),E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function le(t){var i=new FormData;return t.trim().split("&").forEach(function(h){if(h){var y=h.split("="),f=y.shift().replace(/\+/g," "),d=y.join("=").replace(/\+/g," ");i.append(decodeURIComponent(f),decodeURIComponent(d))}}),i}a(le,"decode");function pe(t){var i=new p,h=t.replace(/\r?\n[\t ]+/g," ");return h.split(/\r?\n/).forEach(function(y){var f=y.split(":"),d=f.shift().trim();if(d){var x=f.join(":").trim();i.append(d,x)}}),i}a(pe,"parseHeaders"),J.call(E.prototype);function b(t,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 p(i.headers),this.url=i.url||"",this._initBody(t)}a(b,"Response"),J.call(b.prototype),b.prototype.clone=function(){return new b(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},b.error=function(){var t=new b(null,{status:0,statusText:""});return t.type="error",t};var fe=[301,302,303,307,308];b.redirect=function(t,i){if(fe.indexOf(i)===-1)throw new RangeError("Invalid status code");return new b(null,{status:i,headers:{location:t}})},o.DOMException=n.DOMException;try{new o.DOMException}catch(t){o.DOMException=function(i,h){this.message=i,this.name=h;var y=Error(i);this.stack=y.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function D(t,i){return new Promise(function(h,y){var f=new E(t,i);if(f.signal&&f.signal.aborted)return y(new o.DOMException("Aborted","AbortError"));var d=new XMLHttpRequest;function x(){d.abort()}a(x,"abortXhr"),d.onload=function(){var O={status:d.status,statusText:d.statusText,headers:pe(d.getAllResponseHeaders()||"")};O.url="responseURL"in d?d.responseURL:O.headers.get("X-Request-URL");var C="response"in d?d.response:d.responseText;h(new b(C,O))},d.onerror=function(){y(new TypeError("Network request failed"))},d.ontimeout=function(){y(new TypeError("Network request failed"))},d.onabort=function(){y(new o.DOMException("Aborted","AbortError"))},d.open(f.method,f.url,!0),f.credentials==="include"?d.withCredentials=!0:f.credentials==="omit"&&(d.withCredentials=!1),"responseType"in d&&s.blob&&(d.responseType="blob"),f.headers.forEach(function(O,C){d.setRequestHeader(C,O)}),f.signal&&(f.signal.addEventListener("abort",x),d.onreadystatechange=function(){d.readyState===4&&f.signal.removeEventListener("abort",x)}),d.send(typeof f._bodyInit=="undefined"?null:f._bodyInit)})}return a(D,"fetch"),D.polyfill=!0,n.fetch||(n.fetch=D,n.Headers=p,n.Request=E,n.Response=b),o.Headers=p,o.Request=E,o.Response=b,o.fetch=D,Object.defineProperty(o,"__esModule",{value:!0}),o}({})})($);$.fetch.ponyfill=!0;delete $.fetch.polyfill;var A=$;R=A.fetch;R.default=A.fetch;R.fetch=A.fetch;R.Headers=A.Headers;R.Request=A.Request;R.Response=A.Response;Y.exports=R});var Oe={};Ee(Oe,{Authorizer:()=>H,OAuthProviders:()=>q,ResponseTypes:()=>L});var ie=Te(ee());var q;(function(n){n.Apple="apple",n.Github="github",n.Google="google",n.Facebook="facebook",n.LinkedIn="linkedin",n.Twitter="twitter",n.Microsoft="microsoft",n.Twitch="twitch"})(q||(q={}));var L;(function(n){n.Code="code",n.Token="token"})(L||(L={}));var T=a(()=>typeof window!="undefined","hasWindow"),j=a(n=>{let e=n.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),re=a(()=>T()?window.crypto||window.msCrypto:null,"getCrypto"),Ae=a(()=>{let n=re();return n&&n.subtle||n.webkitSubtle},"getCryptoSubtle"),U=a(()=>{let n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",o=re();return o&&Array.from(o.getRandomValues(new Uint8Array(43))).forEach(r=>e+=n[r%n.length]),e},"createRandomString"),v=a(n=>T()?btoa(n):Buffer.from(n).toString("base64"),"encode");var te=a(n=>Object.keys(n).filter(e=>typeof n[e]!="undefined").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(n[e])}`).join("&"),"createQueryParams"),oe=a(n=>l(void 0,null,function*(){let e=Ae().digest({name:"SHA-256"},new TextEncoder().encode(n));return window.msCrypto?new Promise((o,s)=>{e.oncomplete=r=>{o(r.target.result)},e.onerror=r=>{s(r.error)},e.onabort=()=>{s(new Error("The digest operation was aborted"))}}):yield e}),"sha256"),Le=a(n=>{let e={"+":"-","/":"_","=":""};return n.replace(/[+/=]/g,o=>e[o])},"urlEncodeB64");var se=a(n=>{let e=new Uint8Array(n);return Le(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),ne=a((n,e,o=60)=>new Promise((s,r)=>{let c=window.document.createElement("iframe");c.setAttribute("id","authorizer-iframe"),c.setAttribute("width","0"),c.setAttribute("height","0"),c.style.display="none";let g=a(()=>{window.document.body.contains(c)&&(window.document.body.removeChild(c),window.removeEventListener("message",m,!1))},"removeIframe"),w=setTimeout(()=>{g()},o*1e3),m=a(function(_){if(_.origin!==e||!_.data||!_.data.response)return;let p=_.source;p&&p.close(),_.data.response.error?r(_.data.response):s(_.data.response),clearTimeout(w),window.removeEventListener("message",m,!1),setTimeout(g,2*1e3)},"iframeEventHandler");window.addEventListener("message",m,!1),window.document.body.appendChild(c),c.setAttribute("src",n)}),"executeIframe");var z="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",S=`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 { ${z} }`,M=a(()=>T()?window.fetch:ie.default,"getFetcher"),N=class N{constructor(e){u(this,"config");u(this,"codeVerifier");u(this,"authorize",a(e=>l(this,null,function*(){if(!T())return this.errorResponse([new Error("this feature is only supported in browser")]);let o=["openid","profile","email"];e.use_refresh_token&&o.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:o.join(" "),client_id:this.config.clientID};if(e.response_type===L.Code){this.codeVerifier=U();let c=yield oe(this.codeVerifier),g=se(c);s.code_challenge=g}let r=`${this.config.authorizerURL}/authorize?${te(s)}`;if(s.response_mode!=="web_message")return window.location.replace(r),this.okResponse(void 0);try{let c=yield ne(r,this.config.authorizerURL,60);if(e.response_type===L.Code){let g=yield this.getToken({code:c.code});return g.errors.length?this.errorResponse(g.errors):this.okResponse(g.data)}return this.okResponse(c)}catch(c){return c.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(c)}}),"authorize"));u(this,"browserLogin",a(()=>l(this,null,function*(){try{let e=yield this.getSession();return e.errors.length?this.errorResponse(e.errors):this.okResponse(e.data)}catch(e){return T()?(window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{data:void 0,errors:[new Error("browserLogin is only supported for browsers")]}}}),"browserLogin"));u(this,"forgotPassword",a(e=>l(this,null,function*(){var o;e.state||(e.state=v(U())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let s=yield this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}});return(o=s==null?void 0:s.errors)!=null&&o.length?this.errorResponse(s.errors):this.okResponse(s==null?void 0:s.data.forgot_password)}catch(s){return this.errorResponse([s])}}),"forgotPassword"));u(this,"getMetaData",a(()=>l(this,null,function*(){var e;try{let o=yield this.graphqlQuery({query:"query { meta { version client_id 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 } }"});return(e=o==null?void 0:o.errors)!=null&&e.length?this.errorResponse(o.errors):this.okResponse(o.data.meta)}catch(o){return this.errorResponse([o])}}),"getMetaData"));u(this,"getProfile",a(e=>l(this,null,function*(){var o;try{let s=yield this.graphqlQuery({query:`query { profile { ${z} } }`,headers:e});return(o=s==null?void 0:s.errors)!=null&&o.length?this.errorResponse(s.errors):this.okResponse(s.data.profile)}catch(s){return this.errorResponse([s])}}),"getProfile"));u(this,"getSession",a((e,o)=>l(this,null,function*(){var s,r;try{let c=yield this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${S} } }`,headers:e,variables:{params:o}});return(s=c==null?void 0:c.errors)!=null&&s.length?this.errorResponse(c.errors):this.okResponse((r=c.data)==null?void 0:r.session)}catch(c){return this.errorResponse(c)}}),"getSession"));u(this,"getToken",a(e=>l(this,null,function*(){if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse([new Error("Invalid refresh_token")]);if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse([new Error("Invalid code verifier")]);let o={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let r=yield M()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(o),headers:I({},this.config.extraHeaders),credentials:"include"}),c=yield r.json();return r.status>=400?this.errorResponse([new Error(c.error_description||c.error)]):this.okResponse(c)}catch(s){return this.errorResponse(s)}}),"getToken"));u(this,"login",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`
2
+ mutation login($data: LoginInput!) { login(params: $data) { ${S}}}
3
+ `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.login)}catch(r){return this.errorResponse([new Error(r)])}}),"login"));u(this,"logout",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:" mutation { logout { message } } ",headers:e});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.response)}catch(r){return this.errorResponse([r])}}),"logout"));u(this,"magicLinkLogin",a(e=>l(this,null,function*(){var o,s;try{e.state||(e.state=v(U())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);let r=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=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:`
5
+ `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.magic_link_login)}catch(r){return this.errorResponse([r])}}),"magicLinkLogin"));u(this,"oauthLogin",a((e,o,s,r)=>l(this,null,function*(){let c=r;if(c||(c=v(U())),!Object.values(q).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!T())throw new Error("oauthLogin is only supported for browsers");o&&o.length&&(c+=`&roles=${o.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${s||this.config.redirectURL}&state=${c}`)}),"oauthLogin"));u(this,"resendOtp",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`
6
6
  mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }}
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
- mutation signup($data: SignUpInput!) { signup(params: $data) { ${x}}}
9
- `,variables:{data:e}})).signup}catch(t){throw new Error(t)}}),"signup"));d(this,"updateProfile",n((e,t)=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:t,variables:{data:e}})).update_profile}catch(s){throw new Error(s)}}),"updateProfile"));d(this,"deactivateAccount",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e})).deactivate_account}catch(t){throw new Error(t)}}),"deactivateAccount"));d(this,"validateJWTToken",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}})).validate_jwt_token}catch(t){throw new Error(t)}}),"validateJWTToken"));d(this,"validateSession",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${H} } } }`,variables:{params:e}})).validate_session}catch(t){throw new Error(t)}}),"validateSession"));d(this,"verifyEmail",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`
10
- mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${x}}}
11
- `,variables:{data:e}})).verify_email}catch(t){throw new Error(t)}}),"verifyEmail"));d(this,"verifyOtp",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`
12
- mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${x}}}
13
- `,variables:{data:e}})).verify_otp}catch(t){throw new Error(t)}}),"verifyOtp"));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=W(I({},e.extraHeaders||{}),{"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"}),this.config.clientID=e.clientID.trim()}};n(P,"Authorizer");return Re(Oe);})();
7
+ `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.resend_otp)}catch(r){return this.errorResponse([r])}}),"resendOtp"));u(this,"resetPassword",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.reset_password)}catch(r){return this.errorResponse([r])}}),"resetPassword"));u(this,"revokeToken",a(e=>l(this,null,function*(){if(!e.refresh_token&&!e.refresh_token.trim())return this.errorResponse([new Error("Invalid refresh_token")]);let r=yield(yield M()(`${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();return this.okResponse(r)}),"revokeToken"));u(this,"signup",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`
8
+ mutation signup($data: SignUpInput!) { signup(params: $data) { ${S}}}
9
+ `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.signup)}catch(r){return this.errorResponse([r])}}),"signup"));u(this,"updateProfile",a((e,o)=>l(this,null,function*(){var s,r;try{let c=yield this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:o,variables:{data:e}});return(s=c==null?void 0:c.errors)!=null&&s.length?this.errorResponse(c.errors):this.okResponse((r=c.data)==null?void 0:r.update_profile)}catch(c){return this.errorResponse([c])}}),"updateProfile"));u(this,"deactivateAccount",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.deactivate_account)}catch(r){return this.errorResponse([r])}}),"deactivateAccount"));u(this,"validateJWTToken",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.validate_jwt_token)}catch(r){return this.errorResponse([r])}}),"validateJWTToken"));u(this,"validateSession",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${z} } } }`,variables:{params:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.validate_session)}catch(r){return this.errorResponse([r])}}),"validateSession"));u(this,"verifyEmail",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`
10
+ mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${S}}}
11
+ `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_email)}catch(r){return this.errorResponse([r])}}),"verifyEmail"));u(this,"resendVerifyEmail",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`
12
+ mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }}
13
+ `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_email)}catch(r){return this.errorResponse([r])}}),"resendVerifyEmail"));u(this,"verifyOtp",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`
14
+ mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${S}}}
15
+ `,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_otp)}catch(r){return this.errorResponse([r])}}),"verifyOtp"));u(this,"graphqlQuery",a(e=>l(this,null,function*(){var c;let r=yield(yield M()(`${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();return(c=r==null?void 0:r.errors)!=null&&c.length?{data:void 0,errors:r.errors}:{data:r.data,errors:[]}}),"graphqlQuery"));u(this,"errorResponse",a(e=>({data:void 0,errors:e}),"errorResponse"));u(this,"okResponse",a(e=>({data:e,errors:[]}),"okResponse"));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=j(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=j(e.redirectURL),this.config.extraHeaders=Z(I({},e.extraHeaders||{}),{"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"}),this.config.clientID=e.clientID.trim()}};a(N,"Authorizer");var H=N;return Ue(Oe);})();
14
16
  window.__TAURI__ = authorizerdev
@@ -0,0 +1,263 @@
1
+ interface GrapQlResponseType {
2
+ data: any | undefined;
3
+ errors: Error[];
4
+ }
5
+ interface ApiResponse<T> {
6
+ errors: Error[];
7
+ data: T | undefined;
8
+ }
9
+ interface ConfigType {
10
+ authorizerURL: string;
11
+ redirectURL: string;
12
+ clientID: string;
13
+ extraHeaders?: Record<string, string>;
14
+ }
15
+ interface User {
16
+ id: string;
17
+ email: string;
18
+ preferred_username: string;
19
+ email_verified: boolean;
20
+ signup_methods: string;
21
+ given_name?: string | null;
22
+ family_name?: string | null;
23
+ middle_name?: string | null;
24
+ nickname?: string | null;
25
+ picture?: string | null;
26
+ gender?: string | null;
27
+ birthdate?: string | null;
28
+ phone_number?: string | null;
29
+ phone_number_verified?: boolean | null;
30
+ roles?: string[];
31
+ created_at: number;
32
+ updated_at: number;
33
+ is_multi_factor_auth_enabled?: boolean;
34
+ app_data?: Record<string, any>;
35
+ }
36
+ interface AuthToken {
37
+ message?: string;
38
+ access_token: string;
39
+ expires_in: number;
40
+ id_token: string;
41
+ refresh_token?: string;
42
+ user?: User;
43
+ should_show_email_otp_screen?: boolean;
44
+ should_show_mobile_otp_screen?: boolean;
45
+ should_show_totp_screen?: boolean;
46
+ authenticator_scanner_image?: string;
47
+ authenticator_secret?: string;
48
+ authenticator_recovery_codes?: string[];
49
+ }
50
+ interface GenericResponse {
51
+ message: string;
52
+ }
53
+ type Headers = Record<string, string>;
54
+ interface LoginInput {
55
+ email?: string;
56
+ phone_number?: string;
57
+ password: string;
58
+ roles?: string[];
59
+ scope?: string[];
60
+ state?: string;
61
+ }
62
+ interface SignupInput {
63
+ email?: string;
64
+ password: string;
65
+ confirm_password: string;
66
+ given_name?: string;
67
+ family_name?: string;
68
+ middle_name?: string;
69
+ nickname?: string;
70
+ picture?: string;
71
+ gender?: string;
72
+ birthdate?: string;
73
+ phone_number?: string;
74
+ roles?: string[];
75
+ scope?: string[];
76
+ redirect_uri?: string;
77
+ is_multi_factor_auth_enabled?: boolean;
78
+ state?: string;
79
+ app_data?: Record<string, any>;
80
+ }
81
+ interface MagicLinkLoginInput {
82
+ email: string;
83
+ roles?: string[];
84
+ scopes?: string[];
85
+ state?: string;
86
+ redirect_uri?: string;
87
+ }
88
+ interface VerifyEmailInput {
89
+ token: string;
90
+ state?: string;
91
+ }
92
+ interface ResendVerifyEmailInput {
93
+ email: string;
94
+ identifier: string;
95
+ }
96
+ interface VerifyOtpInput {
97
+ email?: string;
98
+ phone_number?: string;
99
+ otp: string;
100
+ state?: string;
101
+ is_totp?: boolean;
102
+ }
103
+ interface ResendOtpInput {
104
+ email?: string;
105
+ phone_number?: string;
106
+ }
107
+ interface GraphqlQueryInput {
108
+ query: string;
109
+ variables?: Record<string, any>;
110
+ headers?: Headers;
111
+ }
112
+ interface MetaData {
113
+ version: string;
114
+ client_id: string;
115
+ is_google_login_enabled: boolean;
116
+ is_facebook_login_enabled: boolean;
117
+ is_github_login_enabled: boolean;
118
+ is_linkedin_login_enabled: boolean;
119
+ is_apple_login_enabled: boolean;
120
+ is_twitter_login_enabled: boolean;
121
+ is_microsoft_login_enabled: boolean;
122
+ is_twitch_login_enabled: boolean;
123
+ is_email_verification_enabled: boolean;
124
+ is_basic_authentication_enabled: boolean;
125
+ is_magic_link_login_enabled: boolean;
126
+ is_sign_up_enabled: boolean;
127
+ is_strong_password_enabled: boolean;
128
+ is_multi_factor_auth_enabled: boolean;
129
+ is_mobile_basic_authentication_enabled: boolean;
130
+ is_phone_verification_enabled: boolean;
131
+ }
132
+ interface UpdateProfileInput {
133
+ old_password?: string;
134
+ new_password?: string;
135
+ confirm_new_password?: string;
136
+ email?: string;
137
+ given_name?: string;
138
+ family_name?: string;
139
+ middle_name?: string;
140
+ nickname?: string;
141
+ gender?: string;
142
+ birthdate?: string;
143
+ phone_number?: string;
144
+ picture?: string;
145
+ is_multi_factor_auth_enabled?: boolean;
146
+ app_data?: Record<string, any>;
147
+ }
148
+ interface ForgotPasswordInput {
149
+ email: string;
150
+ state?: string;
151
+ redirect_uri?: string;
152
+ }
153
+ interface ForgotPasswordResponse {
154
+ message: string;
155
+ should_show_mobile_otp_screen?: boolean;
156
+ }
157
+ interface ResetPasswordInput {
158
+ token: string;
159
+ password: string;
160
+ confirm_password: string;
161
+ }
162
+ interface SessionQueryInput {
163
+ roles?: string[];
164
+ }
165
+ interface IsValidJWTQueryInput {
166
+ jwt: string;
167
+ roles?: string[];
168
+ }
169
+ interface ValidJWTResponse {
170
+ valid: string;
171
+ message: string;
172
+ }
173
+ declare enum OAuthProviders {
174
+ Apple = "apple",
175
+ Github = "github",
176
+ Google = "google",
177
+ Facebook = "facebook",
178
+ LinkedIn = "linkedin",
179
+ Twitter = "twitter",
180
+ Microsoft = "microsoft",
181
+ Twitch = "twitch"
182
+ }
183
+ declare enum ResponseTypes {
184
+ Code = "code",
185
+ Token = "token"
186
+ }
187
+ interface AuthorizeInput {
188
+ response_type: ResponseTypes;
189
+ use_refresh_token?: boolean;
190
+ response_mode?: string;
191
+ }
192
+ interface AuthorizeResponse {
193
+ state: string;
194
+ code?: string;
195
+ error?: string;
196
+ error_description?: string;
197
+ }
198
+ interface RevokeTokenInput {
199
+ refresh_token: string;
200
+ }
201
+ interface GetTokenInput {
202
+ code?: string;
203
+ grant_type?: string;
204
+ refresh_token?: string;
205
+ }
206
+ interface GetTokenResponse {
207
+ access_token: string;
208
+ expires_in: number;
209
+ id_token: string;
210
+ refresh_token?: string;
211
+ }
212
+ interface ValidateJWTTokenInput {
213
+ token_type: 'access_token' | 'id_token' | 'refresh_token';
214
+ token: string;
215
+ roles?: string[];
216
+ }
217
+ interface ValidateJWTTokenResponse {
218
+ is_valid: boolean;
219
+ claims: Record<string, any>;
220
+ }
221
+ interface ValidateSessionInput {
222
+ cookie?: string;
223
+ roles?: string[];
224
+ }
225
+ interface ValidateSessionResponse {
226
+ is_valid: boolean;
227
+ user: User;
228
+ }
229
+
230
+ declare class Authorizer {
231
+ config: ConfigType;
232
+ codeVerifier: string;
233
+ constructor(config: ConfigType);
234
+ authorize: (data: AuthorizeInput) => Promise<ApiResponse<GetTokenResponse> | ApiResponse<AuthorizeResponse>>;
235
+ browserLogin: () => Promise<ApiResponse<AuthToken>>;
236
+ forgotPassword: (data: ForgotPasswordInput) => Promise<ApiResponse<ForgotPasswordResponse>>;
237
+ getMetaData: () => Promise<ApiResponse<MetaData>>;
238
+ getProfile: (headers?: Headers) => Promise<ApiResponse<User>>;
239
+ getSession: (headers?: Headers, params?: SessionQueryInput) => Promise<ApiResponse<AuthToken>>;
240
+ getToken: (data: GetTokenInput) => Promise<ApiResponse<GetTokenResponse>>;
241
+ login: (data: LoginInput) => Promise<ApiResponse<AuthToken>>;
242
+ logout: (headers?: Headers) => Promise<ApiResponse<GenericResponse>>;
243
+ magicLinkLogin: (data: MagicLinkLoginInput) => Promise<ApiResponse<GenericResponse>>;
244
+ oauthLogin: (oauthProvider: string, roles?: string[], redirect_uri?: string, state?: string) => Promise<void>;
245
+ resendOtp: (data: ResendOtpInput) => Promise<ApiResponse<GenericResponse>>;
246
+ resetPassword: (data: ResetPasswordInput) => Promise<ApiResponse<GenericResponse>>;
247
+ revokeToken: (data: {
248
+ refresh_token: string;
249
+ }) => Promise<ApiResponse<any>>;
250
+ signup: (data: SignupInput) => Promise<ApiResponse<AuthToken>>;
251
+ updateProfile: (data: UpdateProfileInput, headers?: Headers) => Promise<ApiResponse<GenericResponse>>;
252
+ deactivateAccount: (headers?: Headers) => Promise<ApiResponse<GenericResponse>>;
253
+ validateJWTToken: (params?: ValidateJWTTokenInput) => Promise<ApiResponse<ValidateJWTTokenResponse>>;
254
+ validateSession: (params?: ValidateSessionInput) => Promise<ApiResponse<ValidateSessionResponse>>;
255
+ verifyEmail: (data: VerifyEmailInput) => Promise<ApiResponse<AuthToken>>;
256
+ resendVerifyEmail: (data: ResendVerifyEmailInput) => Promise<ApiResponse<GenericResponse>>;
257
+ verifyOtp: (data: VerifyOtpInput) => Promise<ApiResponse<AuthToken>>;
258
+ graphqlQuery: (data: GraphqlQueryInput) => Promise<GrapQlResponseType>;
259
+ errorResponse: (errors: Error[]) => ApiResponse<any>;
260
+ okResponse: (data: any) => ApiResponse<any>;
261
+ }
262
+
263
+ export { type ApiResponse, type AuthToken, type AuthorizeInput, type AuthorizeResponse, Authorizer, type ConfigType, type ForgotPasswordInput, type ForgotPasswordResponse, type GenericResponse, type GetTokenInput, type GetTokenResponse, type GrapQlResponseType, type GraphqlQueryInput, type Headers, type IsValidJWTQueryInput, type LoginInput, type MagicLinkLoginInput, type MetaData, OAuthProviders, type ResendOtpInput, type ResendVerifyEmailInput, type ResetPasswordInput, ResponseTypes, type RevokeTokenInput, type SessionQueryInput, type SignupInput, type UpdateProfileInput, type User, type ValidJWTResponse, type ValidateJWTTokenInput, type ValidateJWTTokenResponse, type ValidateSessionInput, type ValidateSessionResponse, type VerifyEmailInput, type VerifyOtpInput };
package/lib/index.d.ts CHANGED
@@ -1,3 +1,11 @@
1
+ interface GrapQlResponseType {
2
+ data: any | undefined;
3
+ errors: Error[];
4
+ }
5
+ interface ApiResponse<T> {
6
+ errors: Error[];
7
+ data: T | undefined;
8
+ }
1
9
  interface ConfigType {
2
10
  authorizerURL: string;
3
11
  redirectURL: string;
@@ -39,7 +47,7 @@ interface AuthToken {
39
47
  authenticator_secret?: string;
40
48
  authenticator_recovery_codes?: string[];
41
49
  }
42
- interface Response {
50
+ interface GenericResponse {
43
51
  message: string;
44
52
  }
45
53
  type Headers = Record<string, string>;
@@ -81,6 +89,10 @@ interface VerifyEmailInput {
81
89
  token: string;
82
90
  state?: string;
83
91
  }
92
+ interface ResendVerifyEmailInput {
93
+ email: string;
94
+ identifier: string;
95
+ }
84
96
  interface VerifyOtpInput {
85
97
  email?: string;
86
98
  phone_number?: string;
@@ -138,6 +150,10 @@ interface ForgotPasswordInput {
138
150
  state?: string;
139
151
  redirect_uri?: string;
140
152
  }
153
+ interface ForgotPasswordResponse {
154
+ message: string;
155
+ should_show_mobile_otp_screen?: boolean;
156
+ }
141
157
  interface ResetPasswordInput {
142
158
  token: string;
143
159
  password: string;
@@ -215,30 +231,33 @@ declare class Authorizer {
215
231
  config: ConfigType;
216
232
  codeVerifier: string;
217
233
  constructor(config: ConfigType);
218
- authorize: (data: AuthorizeInput) => Promise<GetTokenResponse | AuthorizeResponse | undefined>;
219
- browserLogin: () => Promise<AuthToken | void>;
220
- forgotPassword: (data: ForgotPasswordInput) => Promise<Response | void>;
221
- getMetaData: () => Promise<MetaData | void>;
222
- getProfile: (headers?: Headers) => Promise<User | void>;
223
- getSession: (headers?: Headers, params?: SessionQueryInput) => Promise<AuthToken>;
224
- getToken: (data: GetTokenInput) => Promise<GetTokenResponse>;
225
- graphqlQuery: (data: GraphqlQueryInput) => Promise<any>;
226
- login: (data: LoginInput) => Promise<AuthToken | void>;
227
- logout: (headers?: Headers) => Promise<Response | void>;
228
- magicLinkLogin: (data: MagicLinkLoginInput) => Promise<Response>;
234
+ authorize: (data: AuthorizeInput) => Promise<ApiResponse<GetTokenResponse> | ApiResponse<AuthorizeResponse>>;
235
+ browserLogin: () => Promise<ApiResponse<AuthToken>>;
236
+ forgotPassword: (data: ForgotPasswordInput) => Promise<ApiResponse<ForgotPasswordResponse>>;
237
+ getMetaData: () => Promise<ApiResponse<MetaData>>;
238
+ getProfile: (headers?: Headers) => Promise<ApiResponse<User>>;
239
+ getSession: (headers?: Headers, params?: SessionQueryInput) => Promise<ApiResponse<AuthToken>>;
240
+ getToken: (data: GetTokenInput) => Promise<ApiResponse<GetTokenResponse>>;
241
+ login: (data: LoginInput) => Promise<ApiResponse<AuthToken>>;
242
+ logout: (headers?: Headers) => Promise<ApiResponse<GenericResponse>>;
243
+ magicLinkLogin: (data: MagicLinkLoginInput) => Promise<ApiResponse<GenericResponse>>;
229
244
  oauthLogin: (oauthProvider: string, roles?: string[], redirect_uri?: string, state?: string) => Promise<void>;
230
- resendOtp: (data: ResendOtpInput) => Promise<Response | void>;
231
- resetPassword: (data: ResetPasswordInput) => Promise<Response | void>;
245
+ resendOtp: (data: ResendOtpInput) => Promise<ApiResponse<GenericResponse>>;
246
+ resetPassword: (data: ResetPasswordInput) => Promise<ApiResponse<GenericResponse>>;
232
247
  revokeToken: (data: {
233
248
  refresh_token: string;
234
- }) => Promise<any>;
235
- signup: (data: SignupInput) => Promise<AuthToken | void>;
236
- updateProfile: (data: UpdateProfileInput, headers?: Headers) => Promise<Response | void>;
237
- deactivateAccount: (headers?: Headers) => Promise<Response | void>;
238
- validateJWTToken: (params?: ValidateJWTTokenInput) => Promise<ValidateJWTTokenResponse>;
239
- validateSession: (params?: ValidateSessionInput) => Promise<ValidateSessionResponse>;
240
- verifyEmail: (data: VerifyEmailInput) => Promise<AuthToken | void>;
241
- verifyOtp: (data: VerifyOtpInput) => Promise<AuthToken | void>;
249
+ }) => Promise<ApiResponse<any>>;
250
+ signup: (data: SignupInput) => Promise<ApiResponse<AuthToken>>;
251
+ updateProfile: (data: UpdateProfileInput, headers?: Headers) => Promise<ApiResponse<GenericResponse>>;
252
+ deactivateAccount: (headers?: Headers) => Promise<ApiResponse<GenericResponse>>;
253
+ validateJWTToken: (params?: ValidateJWTTokenInput) => Promise<ApiResponse<ValidateJWTTokenResponse>>;
254
+ validateSession: (params?: ValidateSessionInput) => Promise<ApiResponse<ValidateSessionResponse>>;
255
+ verifyEmail: (data: VerifyEmailInput) => Promise<ApiResponse<AuthToken>>;
256
+ resendVerifyEmail: (data: ResendVerifyEmailInput) => Promise<ApiResponse<GenericResponse>>;
257
+ verifyOtp: (data: VerifyOtpInput) => Promise<ApiResponse<AuthToken>>;
258
+ graphqlQuery: (data: GraphqlQueryInput) => Promise<GrapQlResponseType>;
259
+ errorResponse: (errors: Error[]) => ApiResponse<any>;
260
+ okResponse: (data: any) => ApiResponse<any>;
242
261
  }
243
262
 
244
- export { AuthToken, AuthorizeInput, AuthorizeResponse, Authorizer, ConfigType, ForgotPasswordInput, GetTokenInput, GetTokenResponse, GraphqlQueryInput, Headers, IsValidJWTQueryInput, LoginInput, MagicLinkLoginInput, MetaData, OAuthProviders, ResendOtpInput, ResetPasswordInput, Response, ResponseTypes, RevokeTokenInput, SessionQueryInput, SignupInput, UpdateProfileInput, User, ValidJWTResponse, ValidateJWTTokenInput, ValidateJWTTokenResponse, ValidateSessionInput, ValidateSessionResponse, VerifyEmailInput, VerifyOtpInput };
263
+ export { type ApiResponse, type AuthToken, type AuthorizeInput, type AuthorizeResponse, Authorizer, type ConfigType, type ForgotPasswordInput, type ForgotPasswordResponse, type GenericResponse, type GetTokenInput, type GetTokenResponse, type GrapQlResponseType, type GraphqlQueryInput, type Headers, type IsValidJWTQueryInput, type LoginInput, type MagicLinkLoginInput, type MetaData, OAuthProviders, type ResendOtpInput, type ResendVerifyEmailInput, type ResetPasswordInput, ResponseTypes, type RevokeTokenInput, type SessionQueryInput, type SignupInput, type UpdateProfileInput, type User, type ValidJWTResponse, type ValidateJWTTokenInput, type ValidateJWTTokenResponse, type ValidateSessionInput, type ValidateSessionResponse, type VerifyEmailInput, type VerifyOtpInput };
package/lib/index.js CHANGED
@@ -1,13 +1,15 @@
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
- mutation login($data: LoginInput!) { login(params: $data) { ${f}}}
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:`
1
+ var x=Object.create;var l=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var Q=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var i=(o,r)=>l(o,"name",{value:r,configurable:!0});var D=(o,r)=>{for(var t in r)l(o,t,{get:r[t],enumerable:!0})},$=(o,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let e of O(r))!z.call(o,e)&&e!==t&&l(o,e,{get:()=>r[e],enumerable:!(s=C(r,e))||s.enumerable});return o};var A=(o,r,t)=>(t=o!=null?x(Q(o)):{},$(r||!o||!o.__esModule?l(t,"default",{value:o,enumerable:!0}):t,o)),N=o=>$(l({},"__esModule",{value:!0}),o);var H={};D(H,{Authorizer:()=>b,OAuthProviders:()=>_,ResponseTypes:()=>d});module.exports=N(H);var I=A(require("cross-fetch"));var _;(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"})(_||(_={}));var d;(function(o){o.Code="code",o.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),y=i(o=>{let r=o.trim();return r[r.length-1]==="/"&&(r=r.slice(0,-1)),r},"trimURL"),U=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),F=i(()=>{let o=U();return o&&o.subtle||o.webkitSubtle},"getCryptoSubtle"),u=i(()=>{let o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",r="",t=U();return t&&Array.from(t.getRandomValues(new Uint8Array(43))).forEach(e=>r+=o[e%o.length]),r},"createRandomString"),c=i(o=>p()?btoa(o):Buffer.from(o).toString("base64"),"encode");var E=i(o=>Object.keys(o).filter(r=>typeof o[r]<"u").map(r=>`${encodeURIComponent(r)}=${encodeURIComponent(o[r])}`).join("&"),"createQueryParams"),T=i(async o=>{let r=F().digest({name:"SHA-256"},new TextEncoder().encode(o));return window.msCrypto?new Promise((t,s)=>{r.oncomplete=e=>{t(e.target.result)},r.onerror=e=>{s(e.error)},r.onabort=()=>{s(new Error("The digest operation was aborted"))}}):await r},"sha256"),M=i(o=>{let r={"+":"-","/":"_","=":""};return o.replace(/[+/=]/g,t=>r[t])},"urlEncodeB64");var L=i(o=>{let r=new Uint8Array(o);return M(window.btoa(String.fromCharCode(...Array.from(r))))},"bufferToBase64UrlEncoded"),q=i((o,r,t=60)=>new Promise((s,e)=>{let n=window.document.createElement("iframe");n.setAttribute("id","authorizer-iframe"),n.setAttribute("width","0"),n.setAttribute("height","0"),n.style.display="none";let a=i(()=>{window.document.body.contains(n)&&(window.document.body.removeChild(n),window.removeEventListener("message",f,!1))},"removeIframe"),S=setTimeout(()=>{a()},t*1e3),f=i(function(h){if(h.origin!==r||!h.data||!h.data.response)return;let v=h.source;v&&v.close(),h.data.response.error?e(h.data.response):s(h.data.response),clearTimeout(S),window.removeEventListener("message",f,!1),setTimeout(a,2*1e3)},"iframeEventHandler");window.addEventListener("message",f,!1),window.document.body.appendChild(n),n.setAttribute("src",o)}),"executeIframe");var R="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",g=`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 { ${R} }`,w=i(()=>p()?window.fetch:I.default,"getFetcher"),k=class k{config;codeVerifier;constructor(r){if(!r)throw new Error("Configuration is required");if(this.config=r,!r.authorizerURL&&!r.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(r.authorizerURL&&(this.config.authorizerURL=y(r.authorizerURL)),!r.redirectURL&&!r.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=y(r.redirectURL),this.config.extraHeaders={...r.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=r.clientID.trim()}authorize=async r=>{if(!p())return this.errorResponse([new Error("this feature is only supported in browser")]);let t=["openid","profile","email"];r.use_refresh_token&&t.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:r.response_mode||"web_message",state:c(u()),nonce:c(u()),response_type:r.response_type,scope:t.join(" "),client_id:this.config.clientID};if(r.response_type===d.Code){this.codeVerifier=u();let n=await T(this.codeVerifier),a=L(n);s.code_challenge=a}let e=`${this.config.authorizerURL}/authorize?${E(s)}`;if(s.response_mode!=="web_message")return window.location.replace(e),this.okResponse(void 0);try{let n=await q(e,this.config.authorizerURL,60);if(r.response_type===d.Code){let a=await this.getToken({code:n.code});return a.errors.length?this.errorResponse(a.errors):this.okResponse(a.data)}return this.okResponse(n)}catch(n){return n.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(n)}};browserLogin=async()=>{try{let r=await this.getSession();return r.errors.length?this.errorResponse(r.errors):this.okResponse(r.data)}catch(r){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(r)):{data:void 0,errors:[new Error("browserLogin is only supported for browsers")]}}};forgotPassword=async r=>{var t;r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);try{let s=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:r}});return(t=s==null?void 0:s.errors)!=null&&t.length?this.errorResponse(s.errors):this.okResponse(s==null?void 0:s.data.forgot_password)}catch(s){return this.errorResponse([s])}};getMetaData=async()=>{var r;try{let t=await this.graphqlQuery({query:"query { meta { version client_id 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 } }"});return(r=t==null?void 0:t.errors)!=null&&r.length?this.errorResponse(t.errors):this.okResponse(t.data.meta)}catch(t){return this.errorResponse([t])}};getProfile=async r=>{var t;try{let s=await this.graphqlQuery({query:`query { profile { ${R} } }`,headers:r});return(t=s==null?void 0:s.errors)!=null&&t.length?this.errorResponse(s.errors):this.okResponse(s.data.profile)}catch(s){return this.errorResponse([s])}};getSession=async(r,t)=>{var s,e;try{let n=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${g} } }`,headers:r,variables:{params:t}});return(s=n==null?void 0:n.errors)!=null&&s.length?this.errorResponse(n.errors):this.okResponse((e=n.data)==null?void 0:e.session)}catch(n){return this.errorResponse(n)}};getToken=async r=>{if(r.grant_type||(r.grant_type="authorization_code"),r.grant_type==="refresh_token"&&!r.refresh_token)return this.errorResponse([new Error("Invalid refresh_token")]);if(r.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse([new Error("Invalid code verifier")]);let t={client_id:this.config.clientID,code:r.code||"",code_verifier:this.codeVerifier||"",grant_type:r.grant_type||"",refresh_token:r.refresh_token||""};try{let e=await w()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(t),headers:{...this.config.extraHeaders},credentials:"include"}),n=await e.json();return e.status>=400?this.errorResponse([new Error(n.error_description||n.error)]):this.okResponse(n)}catch(s){return this.errorResponse(s)}};login=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`
2
+ mutation login($data: LoginInput!) { login(params: $data) { ${g}}}
3
+ `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.login)}catch(e){return this.errorResponse([new Error(e)])}};logout=async r=>{var t,s;try{let e=await this.graphqlQuery({query:" mutation { logout { message } } ",headers:r});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.response)}catch(e){return this.errorResponse([e])}};magicLinkLogin=async r=>{var t,s;try{r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);let e=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,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:`
5
+ `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.magic_link_login)}catch(e){return this.errorResponse([e])}};oauthLogin=async(r,t,s,e)=>{let n=e;if(n||(n=c(u())),!Object.values(_).includes(r))throw new Error(`only following oauth providers are supported: ${Object.values(r).toString()}`);if(!p())throw new Error("oauthLogin is only supported for browsers");t&&t.length&&(n+=`&roles=${t.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${r}?redirect_uri=${s||this.config.redirectURL}&state=${n}`)};resendOtp=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`
6
6
  mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }}
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
- 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(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
- mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${f}}}
11
- `,variables:{data:e}})).verify_email}catch(r){throw new Error(r)}};verifyOtp=async e=>{try{return(await this.graphqlQuery({query:`
12
- mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${f}}}
13
- `,variables:{data:e}})).verify_otp}catch(r){throw new Error(r)}}};n(w,"Authorizer");0&&(module.exports={Authorizer,OAuthProviders,ResponseTypes});
7
+ `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.resend_otp)}catch(e){return this.errorResponse([e])}};resetPassword=async r=>{var t,s;try{let e=await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.reset_password)}catch(e){return this.errorResponse([e])}};revokeToken=async r=>{if(!r.refresh_token&&!r.refresh_token.trim())return this.errorResponse([new Error("Invalid refresh_token")]);let e=await(await w()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:{...this.config.extraHeaders},body:JSON.stringify({refresh_token:r.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(e)};signup=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`
8
+ mutation signup($data: SignUpInput!) { signup(params: $data) { ${g}}}
9
+ `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.signup)}catch(e){return this.errorResponse([e])}};updateProfile=async(r,t)=>{var s,e;try{let n=await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:t,variables:{data:r}});return(s=n==null?void 0:n.errors)!=null&&s.length?this.errorResponse(n.errors):this.okResponse((e=n.data)==null?void 0:e.update_profile)}catch(n){return this.errorResponse([n])}};deactivateAccount=async r=>{var t,s;try{let e=await this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:r});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.deactivate_account)}catch(e){return this.errorResponse([e])}};validateJWTToken=async r=>{var t,s;try{let e=await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.validate_jwt_token)}catch(e){return this.errorResponse([e])}};validateSession=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${R} } } }`,variables:{params:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.validate_session)}catch(e){return this.errorResponse([e])}};verifyEmail=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`
10
+ mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${g}}}
11
+ `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.verify_email)}catch(e){return this.errorResponse([e])}};resendVerifyEmail=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`
12
+ mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }}
13
+ `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.verify_email)}catch(e){return this.errorResponse([e])}};verifyOtp=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`
14
+ mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${g}}}
15
+ `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.verify_otp)}catch(e){return this.errorResponse([e])}};graphqlQuery=async r=>{var n;let e=await(await w()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:r.query,variables:r.variables||{}}),headers:{...this.config.extraHeaders,...r.headers||{}},credentials:"include"})).json();return(n=e==null?void 0:e.errors)!=null&&n.length?{data:void 0,errors:e.errors}:{data:e.data,errors:[]}};errorResponse=r=>({data:void 0,errors:r});okResponse=r=>({data:r,errors:[]})};i(k,"Authorizer");var b=k;0&&(module.exports={Authorizer,OAuthProviders,ResponseTypes});
package/lib/index.mjs CHANGED
@@ -1,13 +1,15 @@
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
- mutation login($data: LoginInput!) { login(params: $data) { ${p}}}
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:`
1
+ var q=Object.defineProperty;var i=(n,r)=>q(n,"name",{value:r,configurable:!0});import O from"cross-fetch";var _;(function(n){n.Apple="apple",n.Github="github",n.Google="google",n.Facebook="facebook",n.LinkedIn="linkedin",n.Twitter="twitter",n.Microsoft="microsoft",n.Twitch="twitch"})(_||(_={}));var d;(function(n){n.Code="code",n.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),m=i(n=>{let r=n.trim();return r[r.length-1]==="/"&&(r=r.slice(0,-1)),r},"trimURL"),k=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),x=i(()=>{let n=k();return n&&n.subtle||n.webkitSubtle},"getCryptoSubtle"),u=i(()=>{let n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",r="",s=k();return s&&Array.from(s.getRandomValues(new Uint8Array(43))).forEach(e=>r+=n[e%n.length]),r},"createRandomString"),c=i(n=>p()?btoa(n):Buffer.from(n).toString("base64"),"encode");var v=i(n=>Object.keys(n).filter(r=>typeof n[r]<"u").map(r=>`${encodeURIComponent(r)}=${encodeURIComponent(n[r])}`).join("&"),"createQueryParams"),$=i(async n=>{let r=x().digest({name:"SHA-256"},new TextEncoder().encode(n));return window.msCrypto?new Promise((s,t)=>{r.oncomplete=e=>{s(e.target.result)},r.onerror=e=>{t(e.error)},r.onabort=()=>{t(new Error("The digest operation was aborted"))}}):await r},"sha256"),C=i(n=>{let r={"+":"-","/":"_","=":""};return n.replace(/[+/=]/g,s=>r[s])},"urlEncodeB64");var U=i(n=>{let r=new Uint8Array(n);return C(window.btoa(String.fromCharCode(...Array.from(r))))},"bufferToBase64UrlEncoded"),E=i((n,r,s=60)=>new Promise((t,e)=>{let o=window.document.createElement("iframe");o.setAttribute("id","authorizer-iframe"),o.setAttribute("width","0"),o.setAttribute("height","0"),o.style.display="none";let a=i(()=>{window.document.body.contains(o)&&(window.document.body.removeChild(o),window.removeEventListener("message",g,!1))},"removeIframe"),L=setTimeout(()=>{a()},s*1e3),g=i(function(h){if(h.origin!==r||!h.data||!h.data.response)return;let b=h.source;b&&b.close(),h.data.response.error?e(h.data.response):t(h.data.response),clearTimeout(L),window.removeEventListener("message",g,!1),setTimeout(a,2*1e3)},"iframeEventHandler");window.addEventListener("message",g,!1),window.document.body.appendChild(o),o.setAttribute("src",n)}),"executeIframe");var w="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",l=`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 { ${w} }`,y=i(()=>p()?window.fetch:O,"getFetcher"),R=class R{config;codeVerifier;constructor(r){if(!r)throw new Error("Configuration is required");if(this.config=r,!r.authorizerURL&&!r.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(r.authorizerURL&&(this.config.authorizerURL=m(r.authorizerURL)),!r.redirectURL&&!r.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=m(r.redirectURL),this.config.extraHeaders={...r.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=r.clientID.trim()}authorize=async r=>{if(!p())return this.errorResponse([new Error("this feature is only supported in browser")]);let s=["openid","profile","email"];r.use_refresh_token&&s.push("offline_access");let t={redirect_uri:this.config.redirectURL,response_mode:r.response_mode||"web_message",state:c(u()),nonce:c(u()),response_type:r.response_type,scope:s.join(" "),client_id:this.config.clientID};if(r.response_type===d.Code){this.codeVerifier=u();let o=await $(this.codeVerifier),a=U(o);t.code_challenge=a}let e=`${this.config.authorizerURL}/authorize?${v(t)}`;if(t.response_mode!=="web_message")return window.location.replace(e),this.okResponse(void 0);try{let o=await E(e,this.config.authorizerURL,60);if(r.response_type===d.Code){let a=await this.getToken({code:o.code});return a.errors.length?this.errorResponse(a.errors):this.okResponse(a.data)}return this.okResponse(o)}catch(o){return o.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(o)}};browserLogin=async()=>{try{let r=await this.getSession();return r.errors.length?this.errorResponse(r.errors):this.okResponse(r.data)}catch(r){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(r)):{data:void 0,errors:[new Error("browserLogin is only supported for browsers")]}}};forgotPassword=async r=>{var s;r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);try{let t=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:r}});return(s=t==null?void 0:t.errors)!=null&&s.length?this.errorResponse(t.errors):this.okResponse(t==null?void 0:t.data.forgot_password)}catch(t){return this.errorResponse([t])}};getMetaData=async()=>{var r;try{let s=await this.graphqlQuery({query:"query { meta { version client_id 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 } }"});return(r=s==null?void 0:s.errors)!=null&&r.length?this.errorResponse(s.errors):this.okResponse(s.data.meta)}catch(s){return this.errorResponse([s])}};getProfile=async r=>{var s;try{let t=await this.graphqlQuery({query:`query { profile { ${w} } }`,headers:r});return(s=t==null?void 0:t.errors)!=null&&s.length?this.errorResponse(t.errors):this.okResponse(t.data.profile)}catch(t){return this.errorResponse([t])}};getSession=async(r,s)=>{var t,e;try{let o=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${l} } }`,headers:r,variables:{params:s}});return(t=o==null?void 0:o.errors)!=null&&t.length?this.errorResponse(o.errors):this.okResponse((e=o.data)==null?void 0:e.session)}catch(o){return this.errorResponse(o)}};getToken=async r=>{if(r.grant_type||(r.grant_type="authorization_code"),r.grant_type==="refresh_token"&&!r.refresh_token)return this.errorResponse([new Error("Invalid refresh_token")]);if(r.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse([new Error("Invalid code verifier")]);let s={client_id:this.config.clientID,code:r.code||"",code_verifier:this.codeVerifier||"",grant_type:r.grant_type||"",refresh_token:r.refresh_token||""};try{let e=await y()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(s),headers:{...this.config.extraHeaders},credentials:"include"}),o=await e.json();return e.status>=400?this.errorResponse([new Error(o.error_description||o.error)]):this.okResponse(o)}catch(t){return this.errorResponse(t)}};login=async r=>{var s,t;try{let e=await this.graphqlQuery({query:`
2
+ mutation login($data: LoginInput!) { login(params: $data) { ${l}}}
3
+ `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.login)}catch(e){return this.errorResponse([new Error(e)])}};logout=async r=>{var s,t;try{let e=await this.graphqlQuery({query:" mutation { logout { message } } ",headers:r});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.response)}catch(e){return this.errorResponse([e])}};magicLinkLogin=async r=>{var s,t;try{r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);let e=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,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:`
5
+ `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.magic_link_login)}catch(e){return this.errorResponse([e])}};oauthLogin=async(r,s,t,e)=>{let o=e;if(o||(o=c(u())),!Object.values(_).includes(r))throw new Error(`only following oauth providers are supported: ${Object.values(r).toString()}`);if(!p())throw new Error("oauthLogin is only supported for browsers");s&&s.length&&(o+=`&roles=${s.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${r}?redirect_uri=${t||this.config.redirectURL}&state=${o}`)};resendOtp=async r=>{var s,t;try{let e=await this.graphqlQuery({query:`
6
6
  mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }}
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
- 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(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
- mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${p}}}
11
- `,variables:{data:e}})).verify_email}catch(r){throw new Error(r)}};verifyOtp=async e=>{try{return(await this.graphqlQuery({query:`
12
- mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${p}}}
13
- `,variables:{data:e}})).verify_otp}catch(r){throw new Error(r)}}};n(m,"Authorizer");export{m as Authorizer,_ as OAuthProviders,l as ResponseTypes};
7
+ `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.resend_otp)}catch(e){return this.errorResponse([e])}};resetPassword=async r=>{var s,t;try{let e=await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.reset_password)}catch(e){return this.errorResponse([e])}};revokeToken=async r=>{if(!r.refresh_token&&!r.refresh_token.trim())return this.errorResponse([new Error("Invalid refresh_token")]);let e=await(await y()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:{...this.config.extraHeaders},body:JSON.stringify({refresh_token:r.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(e)};signup=async r=>{var s,t;try{let e=await this.graphqlQuery({query:`
8
+ mutation signup($data: SignUpInput!) { signup(params: $data) { ${l}}}
9
+ `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.signup)}catch(e){return this.errorResponse([e])}};updateProfile=async(r,s)=>{var t,e;try{let o=await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:s,variables:{data:r}});return(t=o==null?void 0:o.errors)!=null&&t.length?this.errorResponse(o.errors):this.okResponse((e=o.data)==null?void 0:e.update_profile)}catch(o){return this.errorResponse([o])}};deactivateAccount=async r=>{var s,t;try{let e=await this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:r});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.deactivate_account)}catch(e){return this.errorResponse([e])}};validateJWTToken=async r=>{var s,t;try{let e=await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.validate_jwt_token)}catch(e){return this.errorResponse([e])}};validateSession=async r=>{var s,t;try{let e=await this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${w} } } }`,variables:{params:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.validate_session)}catch(e){return this.errorResponse([e])}};verifyEmail=async r=>{var s,t;try{let e=await this.graphqlQuery({query:`
10
+ mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${l}}}
11
+ `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.verify_email)}catch(e){return this.errorResponse([e])}};resendVerifyEmail=async r=>{var s,t;try{let e=await this.graphqlQuery({query:`
12
+ mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }}
13
+ `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.verify_email)}catch(e){return this.errorResponse([e])}};verifyOtp=async r=>{var s,t;try{let e=await this.graphqlQuery({query:`
14
+ mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${l}}}
15
+ `,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.verify_otp)}catch(e){return this.errorResponse([e])}};graphqlQuery=async r=>{var o;let e=await(await y()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:r.query,variables:r.variables||{}}),headers:{...this.config.extraHeaders,...r.headers||{}},credentials:"include"})).json();return(o=e==null?void 0:e.errors)!=null&&o.length?{data:void 0,errors:e.errors}:{data:e.data,errors:[]}};errorResponse=r=>({data:void 0,errors:r});okResponse=r=>({data:r,errors:[]})};i(R,"Authorizer");var T=R;export{T as Authorizer,_ as OAuthProviders,d as ResponseTypes};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@authorizerdev/authorizer-js",
3
- "version": "1.2.18",
3
+ "version": "2.0.0-beta.0",
4
4
  "packageManager": "pnpm@7.28.0",
5
5
  "author": "Lakhan Samani",
6
6
  "license": "MIT",
@@ -35,31 +35,42 @@
35
35
  "dependencies": {
36
36
  "cross-fetch": "^3.1.5"
37
37
  },
38
+ "lint-staged": {
39
+ "**/*.{js,jsx,ts,tsx}": [
40
+ "npm run lint:fix"
41
+ ]
42
+ },
38
43
  "devDependencies": {
39
- "@antfu/eslint-config": "^0.35.3",
40
- "@rollup/plugin-node-resolve": "^13.0.4",
41
- "@rollup/plugin-typescript": "^8.2.5",
42
- "@swc/core": "^1.3.37",
43
- "@types/node": "^20.4.4",
44
- "bumpp": "^9.0.0",
45
- "eslint": "^8.35.0",
46
- "husky": "^7.0.1",
47
- "jest": "^27.0.6",
48
- "rimraf": "^2.7.1",
49
- "rollup": "^2.56.0",
50
- "rollup-plugin-filesize": "^9.1.1",
51
- "rollup-plugin-serve": "^1.1.0",
52
- "rollup-plugin-terser": "^7.0.2",
53
- "tslib": "^2.3.0",
54
- "tsup": "^6.6.3",
55
- "typescript": "^4.3.5"
44
+ "@antfu/eslint-config": "^2.1.0",
45
+ "@rollup/plugin-node-resolve": "^15.2.3",
46
+ "@rollup/plugin-terser": "^0.4.4",
47
+ "@rollup/plugin-typescript": "^11.1.5",
48
+ "@swc/core": "^1.3.99",
49
+ "@types/jest": "^29.5.10",
50
+ "@types/node": "^20.9.4",
51
+ "@typescript-eslint/eslint-plugin": "^6.13.2",
52
+ "@typescript-eslint/parser": "^6.13.2",
53
+ "bumpp": "^9.2.0",
54
+ "eslint": "^8.54.0",
55
+ "husky": "^8.0.0",
56
+ "jest": "^29.7.0",
57
+ "lint-staged": "^15.2.0",
58
+ "rollup": "^2.79.1",
59
+ "rollup-plugin-filesize": "^10.0.0",
60
+ "rollup-plugin-serve": "^2.0.2",
61
+ "testcontainers": "^10.3.2",
62
+ "ts-jest": "^29.1.1",
63
+ "tslib": "^2.6.2",
64
+ "tsup": "^8.0.1",
65
+ "typescript": "^5.3.2"
56
66
  },
57
67
  "scripts": {
58
68
  "start": "rollup -w --config rollup.test.config.js",
59
69
  "ts-types": "tsc --emitDeclarationOnly --outDir lib",
60
70
  "build": "tsup",
61
- "test": "npm run build && jest --testTimeout=20000 --runInBand",
71
+ "test": "npm run build && jest --testTimeout=500000 --runInBand",
62
72
  "release": "pnpm build && bumpp --commit --push --tag && pnpm publish",
73
+ "release-beta": "pnpm build && bumpp --commit --push --tag && pnpm publish --tag beta",
63
74
  "lint": "eslint --ignore-pattern 'tsup.config.ts' --ext .ts,.tsx,.js,.jsx,.json .",
64
75
  "lint:fix": "eslint --ignore-pattern 'tsup.config.ts' --ext .ts,.tsx,.js,.jsx,.json . --fix"
65
76
  }