@authorizerdev/authorizer-js 3.0.0 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -28,13 +28,13 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
 
30
30
  // src/index.ts
31
- var src_exports = {};
32
- __export(src_exports, {
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
33
  Authorizer: () => Authorizer,
34
34
  OAuthProviders: () => OAuthProviders,
35
35
  ResponseTypes: () => ResponseTypes
36
36
  });
37
- module.exports = __toCommonJS(src_exports);
37
+ module.exports = __toCommonJS(index_exports);
38
38
  var import_cross_fetch = __toESM(require("cross-fetch"));
39
39
 
40
40
  // src/constants.ts
@@ -42,8 +42,7 @@ var DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS = 60;
42
42
  var CLEANUP_IFRAME_TIMEOUT_IN_SECONDS = 2;
43
43
 
44
44
  // src/types.ts
45
- var OAuthProviders;
46
- (function(OAuthProviders2) {
45
+ var OAuthProviders = /* @__PURE__ */ (function(OAuthProviders2) {
47
46
  OAuthProviders2["Apple"] = "apple";
48
47
  OAuthProviders2["Github"] = "github";
49
48
  OAuthProviders2["Google"] = "google";
@@ -54,20 +53,20 @@ var OAuthProviders;
54
53
  OAuthProviders2["Twitch"] = "twitch";
55
54
  OAuthProviders2["Roblox"] = "roblox";
56
55
  OAuthProviders2["Discord"] = "discord";
57
- })(OAuthProviders || (OAuthProviders = {}));
58
- var ResponseTypes;
59
- (function(ResponseTypes2) {
56
+ return OAuthProviders2;
57
+ })({});
58
+ var ResponseTypes = /* @__PURE__ */ (function(ResponseTypes2) {
60
59
  ResponseTypes2["Code"] = "code";
61
60
  ResponseTypes2["Token"] = "token";
62
- })(ResponseTypes || (ResponseTypes = {}));
61
+ return ResponseTypes2;
62
+ })({});
63
63
 
64
64
  // src/utils.ts
65
65
  var hasWindow = /* @__PURE__ */ __name(() => typeof window !== "undefined", "hasWindow");
66
66
  var trimURL = /* @__PURE__ */ __name((url) => {
67
67
  let trimmedData = url.trim();
68
68
  const lastChar = trimmedData[trimmedData.length - 1];
69
- if (lastChar === "/")
70
- trimmedData = trimmedData.slice(0, -1);
69
+ if (lastChar === "/") trimmedData = trimmedData.slice(0, -1);
71
70
  return trimmedData;
72
71
  }, "trimURL");
73
72
  var getCrypto = /* @__PURE__ */ __name(() => {
@@ -92,7 +91,9 @@ var createQueryParams = /* @__PURE__ */ __name((params) => {
92
91
  return Object.keys(params).filter((k) => typeof params[k] !== "undefined").map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`).join("&");
93
92
  }, "createQueryParams");
94
93
  var sha256 = /* @__PURE__ */ __name(async (s) => {
95
- const digestOp = getCryptoSubtle().digest({
94
+ const subtle = getCryptoSubtle();
95
+ if (!subtle) throw new Error("Web Crypto API is not available");
96
+ const digestOp = subtle.digest({
96
97
  name: "SHA-256"
97
98
  }, new TextEncoder().encode(s));
98
99
  if (window.msCrypto) {
@@ -122,8 +123,16 @@ var bufferToBase64UrlEncoded = /* @__PURE__ */ __name((input) => {
122
123
  const ie11SafeInput = new Uint8Array(input);
123
124
  return urlEncodeB64(window.btoa(String.fromCharCode(...Array.from(ie11SafeInput))));
124
125
  }, "bufferToBase64UrlEncoded");
126
+ var originFromAuthorizerUrl = /* @__PURE__ */ __name((authorizerUrl) => {
127
+ try {
128
+ return new URL(authorizerUrl).origin;
129
+ } catch {
130
+ return authorizerUrl;
131
+ }
132
+ }, "originFromAuthorizerUrl");
125
133
  var executeIframe = /* @__PURE__ */ __name((authorizeUrl, eventOrigin, timeoutInSeconds = DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS) => {
126
134
  return new Promise((resolve, reject) => {
135
+ const expectedOrigin = originFromAuthorizerUrl(eventOrigin);
127
136
  const iframe = window.document.createElement("iframe");
128
137
  iframe.setAttribute("id", "authorizer-iframe");
129
138
  iframe.setAttribute("width", "0");
@@ -136,17 +145,16 @@ var executeIframe = /* @__PURE__ */ __name((authorizeUrl, eventOrigin, timeoutIn
136
145
  }
137
146
  }, "removeIframe");
138
147
  const timeoutSetTimeoutId = setTimeout(() => {
148
+ reject(new Error("Authorization timeout"));
139
149
  removeIframe();
140
150
  }, timeoutInSeconds * 1e3);
141
151
  const iframeEventHandler = /* @__PURE__ */ __name(function(e) {
142
- if (e.origin !== eventOrigin)
143
- return;
144
- if (!e.data || !e.data.response)
145
- return;
152
+ if (e.origin !== expectedOrigin) return;
153
+ if (!e.data || !e.data.response) return;
146
154
  const eventSource = e.source;
147
- if (eventSource)
148
- eventSource.close();
149
- e.data.response.error ? reject(e.data.response) : resolve(e.data.response);
155
+ if (eventSource) eventSource.close();
156
+ if (e.data.response.error) reject(e.data.response);
157
+ else resolve(e.data.response);
150
158
  clearTimeout(timeoutSetTimeoutId);
151
159
  window.removeEventListener("message", iframeEventHandler, false);
152
160
  setTimeout(removeIframe, CLEANUP_IFRAME_TIMEOUT_IN_SECONDS * 1e3);
@@ -161,44 +169,72 @@ var executeIframe = /* @__PURE__ */ __name((authorizeUrl, eventOrigin, timeoutIn
161
169
  var userFragment = "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 revoked_timestamp is_multi_factor_auth_enabled app_data";
162
170
  var authTokenFragment = `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 { ${userFragment} }`;
163
171
  var getFetcher = /* @__PURE__ */ __name(() => hasWindow() ? window.fetch : import_cross_fetch.default, "getFetcher");
172
+ function toErrorList(errors) {
173
+ if (Array.isArray(errors)) {
174
+ return errors.map((item) => {
175
+ if (item instanceof Error) return item;
176
+ if (item && typeof item === "object" && "message" in item) return new Error(String(item.message));
177
+ return new Error(String(item));
178
+ });
179
+ }
180
+ if (errors instanceof Error) return [
181
+ errors
182
+ ];
183
+ if (errors !== null && typeof errors === "object") {
184
+ const o = errors;
185
+ if (typeof o.error_description === "string") return [
186
+ new Error(o.error_description)
187
+ ];
188
+ if (typeof o.error === "string") {
189
+ const desc = typeof o.error_description === "string" ? `: ${o.error_description}` : "";
190
+ return [
191
+ new Error(`${o.error}${desc}`)
192
+ ];
193
+ }
194
+ if (typeof o.message === "string") return [
195
+ new Error(o.message)
196
+ ];
197
+ }
198
+ if (errors === void 0 || errors === null) return [
199
+ new Error("Unknown error")
200
+ ];
201
+ return [
202
+ new Error(String(errors))
203
+ ];
204
+ }
205
+ __name(toErrorList, "toErrorList");
164
206
  var _Authorizer = class _Authorizer {
165
207
  // class variable
166
208
  config;
167
209
  codeVerifier;
168
210
  // constructor
169
211
  constructor(config) {
170
- if (!config)
171
- throw new Error("Configuration is required");
212
+ var _a, _b;
213
+ if (!config) throw new Error("Configuration is required");
172
214
  this.config = config;
173
- if (!config.authorizerURL && !config.authorizerURL.trim())
174
- throw new Error("Invalid authorizerURL");
175
- if (config.authorizerURL)
176
- this.config.authorizerURL = trimURL(config.authorizerURL);
177
- if (!config.redirectURL && !config.redirectURL.trim())
178
- throw new Error("Invalid redirectURL");
179
- else
180
- this.config.redirectURL = trimURL(config.redirectURL);
215
+ if (!((_a = config.authorizerURL) == null ? void 0 : _a.trim())) throw new Error("Invalid authorizerURL");
216
+ this.config.authorizerURL = trimURL(config.authorizerURL);
217
+ if (!((_b = config.redirectURL) == null ? void 0 : _b.trim())) throw new Error("Invalid redirectURL");
218
+ this.config.redirectURL = trimURL(config.redirectURL);
219
+ this.config.clientID = ((config == null ? void 0 : config.clientID) || "").trim();
181
220
  this.config.extraHeaders = {
182
221
  ...config.extraHeaders || {},
183
- "x-authorizer-url": this.config.authorizerURL,
184
- "x-authorizer-client-id": this.config.clientID || "",
222
+ "x-authorizer-url": config.authorizerURL,
223
+ "x-authorizer-client-id": config.clientID || "",
185
224
  "Content-Type": "application/json"
186
225
  };
187
- this.config.clientID = ((config == null ? void 0 : config.clientID) || "").trim();
188
226
  }
189
- authorize = async (data) => {
227
+ authorize = /* @__PURE__ */ __name(async (data) => {
190
228
  var _a;
191
- if (!hasWindow())
192
- return this.errorResponse([
193
- new Error("this feature is only supported in browser")
194
- ]);
229
+ if (!hasWindow()) return this.errorResponse([
230
+ new Error("this feature is only supported in browser")
231
+ ]);
195
232
  const scopes = [
196
233
  "openid",
197
234
  "profile",
198
235
  "email"
199
236
  ];
200
- if (data.use_refresh_token)
201
- scopes.push("offline_access");
237
+ if (data.use_refresh_token) scopes.push("offline_access");
202
238
  const requestData = {
203
239
  redirect_uri: this.config.redirectURL,
204
240
  response_mode: data.response_mode || "web_message",
@@ -213,6 +249,7 @@ var _Authorizer = class _Authorizer {
213
249
  const sha = await sha256(this.codeVerifier);
214
250
  const codeChallenge = bufferToBase64UrlEncoded(sha);
215
251
  requestData.code_challenge = codeChallenge;
252
+ requestData.code_challenge_method = "S256";
216
253
  }
217
254
  const authorizeURL = `${this.config.authorizerURL}/authorize?${createQueryParams(requestData)}`;
218
255
  if (requestData.response_mode !== "web_message") {
@@ -230,12 +267,16 @@ var _Authorizer = class _Authorizer {
230
267
  return this.okResponse(iframeRes);
231
268
  } catch (err) {
232
269
  if (err.error) {
233
- window.location.replace(`${this.config.authorizerURL}/app?state=${encode(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`);
270
+ window.location.replace(`${this.config.authorizerURL}/app?state=${encode(JSON.stringify({
271
+ clientID: this.config.clientID,
272
+ redirectURL: this.config.redirectURL,
273
+ authorizerURL: this.config.authorizerURL
274
+ }))}&redirect_uri=${encodeURIComponent(this.config.redirectURL || "")}`);
234
275
  }
235
276
  return this.errorResponse(err);
236
277
  }
237
- };
238
- browserLogin = async () => {
278
+ }, "authorize");
279
+ browserLogin = /* @__PURE__ */ __name(async () => {
239
280
  try {
240
281
  const tokenResp = await this.getSession();
241
282
  return tokenResp.errors.length ? this.errorResponse(tokenResp.errors) : this.okResponse(tokenResp.data);
@@ -248,16 +289,18 @@ var _Authorizer = class _Authorizer {
248
289
  ]
249
290
  };
250
291
  }
251
- window.location.replace(`${this.config.authorizerURL}/app?state=${encode(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`);
292
+ window.location.replace(`${this.config.authorizerURL}/app?state=${encode(JSON.stringify({
293
+ clientID: this.config.clientID,
294
+ redirectURL: this.config.redirectURL,
295
+ authorizerURL: this.config.authorizerURL
296
+ }))}&redirect_uri=${encodeURIComponent(this.config.redirectURL || "")}`);
252
297
  return this.errorResponse(err);
253
298
  }
254
- };
255
- forgotPassword = async (data) => {
256
- var _a;
257
- if (!data.state)
258
- data.state = encode(createRandomString());
259
- if (!data.redirect_uri)
260
- data.redirect_uri = this.config.redirectURL;
299
+ }, "browserLogin");
300
+ forgotPassword = /* @__PURE__ */ __name(async (data) => {
301
+ var _a, _b;
302
+ if (!data.state) data.state = encode(createRandomString());
303
+ if (!data.redirect_uri) data.redirect_uri = this.config.redirectURL;
261
304
  try {
262
305
  const forgotPasswordResp = await this.graphqlQuery({
263
306
  query: "mutation forgotPassword($data: ForgotPasswordRequest!) { forgot_password(params: $data) { message should_show_mobile_otp_screen } }",
@@ -265,14 +308,14 @@ var _Authorizer = class _Authorizer {
265
308
  data
266
309
  }
267
310
  });
268
- return ((_a = forgotPasswordResp == null ? void 0 : forgotPasswordResp.errors) == null ? void 0 : _a.length) ? this.errorResponse(forgotPasswordResp.errors) : this.okResponse(forgotPasswordResp == null ? void 0 : forgotPasswordResp.data.forgot_password);
311
+ return ((_a = forgotPasswordResp == null ? void 0 : forgotPasswordResp.errors) == null ? void 0 : _a.length) ? this.errorResponse(forgotPasswordResp.errors) : this.okResponse((_b = forgotPasswordResp == null ? void 0 : forgotPasswordResp.data) == null ? void 0 : _b.forgot_password);
269
312
  } catch (error) {
270
313
  return this.errorResponse([
271
314
  error
272
315
  ]);
273
316
  }
274
- };
275
- getMetaData = async () => {
317
+ }, "forgotPassword");
318
+ getMetaData = /* @__PURE__ */ __name(async () => {
276
319
  var _a;
277
320
  try {
278
321
  const res = await this.graphqlQuery({
@@ -284,8 +327,8 @@ var _Authorizer = class _Authorizer {
284
327
  error
285
328
  ]);
286
329
  }
287
- };
288
- getProfile = async (headers) => {
330
+ }, "getMetaData");
331
+ getProfile = /* @__PURE__ */ __name(async (headers) => {
289
332
  var _a;
290
333
  try {
291
334
  const profileRes = await this.graphqlQuery({
@@ -298,9 +341,9 @@ var _Authorizer = class _Authorizer {
298
341
  error
299
342
  ]);
300
343
  }
301
- };
344
+ }, "getProfile");
302
345
  // this is used to verify / get session using cookie by default. If using node.js pass authorization header
303
- getSession = async (headers, params) => {
346
+ getSession = /* @__PURE__ */ __name(async (headers, params) => {
304
347
  var _a, _b;
305
348
  try {
306
349
  const res = await this.graphqlQuery({
@@ -314,18 +357,16 @@ var _Authorizer = class _Authorizer {
314
357
  } catch (err) {
315
358
  return this.errorResponse(err);
316
359
  }
317
- };
318
- getToken = async (data) => {
319
- if (!data.grant_type)
320
- data.grant_type = "authorization_code";
321
- if (data.grant_type === "refresh_token" && !data.refresh_token)
322
- return this.errorResponse([
323
- new Error("Invalid refresh_token")
324
- ]);
325
- if (data.grant_type === "authorization_code" && !this.codeVerifier)
326
- return this.errorResponse([
327
- new Error("Invalid code verifier")
328
- ]);
360
+ }, "getSession");
361
+ getToken = /* @__PURE__ */ __name(async (data) => {
362
+ var _a;
363
+ if (!data.grant_type) data.grant_type = "authorization_code";
364
+ if (data.grant_type === "refresh_token" && !((_a = data.refresh_token) == null ? void 0 : _a.trim())) return this.errorResponse([
365
+ new Error("Invalid refresh_token")
366
+ ]);
367
+ if (data.grant_type === "authorization_code" && !this.codeVerifier) return this.errorResponse([
368
+ new Error("Invalid code verifier")
369
+ ]);
329
370
  const requestData = {
330
371
  client_id: this.config.clientID,
331
372
  code: data.code || "",
@@ -343,17 +384,28 @@ var _Authorizer = class _Authorizer {
343
384
  },
344
385
  credentials: "include"
345
386
  });
346
- const json = await res.json();
347
- if (res.status >= 400)
387
+ const text = await res.text();
388
+ let json = {};
389
+ if (text) {
390
+ try {
391
+ json = JSON.parse(text);
392
+ } catch {
393
+ return this.errorResponse([
394
+ new Error(res.ok ? "Invalid JSON from token endpoint" : `HTTP ${res.status}`)
395
+ ]);
396
+ }
397
+ }
398
+ if (!res.ok) {
348
399
  return this.errorResponse([
349
- new Error(json.error_description || json.error)
400
+ new Error(String(json.error_description || json.error || `HTTP ${res.status}`))
350
401
  ]);
402
+ }
351
403
  return this.okResponse(json);
352
404
  } catch (err) {
353
405
  return this.errorResponse(err);
354
406
  }
355
- };
356
- login = async (data) => {
407
+ }, "getToken");
408
+ login = /* @__PURE__ */ __name(async (data) => {
357
409
  var _a, _b;
358
410
  try {
359
411
  const res = await this.graphqlQuery({
@@ -366,32 +418,28 @@ var _Authorizer = class _Authorizer {
366
418
  });
367
419
  return ((_a = res == null ? void 0 : res.errors) == null ? void 0 : _a.length) ? this.errorResponse(res.errors) : this.okResponse((_b = res.data) == null ? void 0 : _b.login);
368
420
  } catch (err) {
369
- return this.errorResponse([
370
- new Error(err)
371
- ]);
421
+ return this.errorResponse(err);
372
422
  }
373
- };
374
- logout = async (headers) => {
423
+ }, "login");
424
+ logout = /* @__PURE__ */ __name(async (headers) => {
375
425
  var _a, _b;
376
426
  try {
377
427
  const res = await this.graphqlQuery({
378
428
  query: " mutation { logout { message } } ",
379
429
  headers
380
430
  });
381
- return ((_a = res == null ? void 0 : res.errors) == null ? void 0 : _a.length) ? this.errorResponse(res.errors) : this.okResponse((_b = res.data) == null ? void 0 : _b.response);
431
+ return ((_a = res == null ? void 0 : res.errors) == null ? void 0 : _a.length) ? this.errorResponse(res.errors) : this.okResponse((_b = res.data) == null ? void 0 : _b.logout);
382
432
  } catch (err) {
383
433
  return this.errorResponse([
384
434
  err
385
435
  ]);
386
436
  }
387
- };
388
- magicLinkLogin = async (data) => {
437
+ }, "logout");
438
+ magicLinkLogin = /* @__PURE__ */ __name(async (data) => {
389
439
  var _a, _b;
390
440
  try {
391
- if (!data.state)
392
- data.state = encode(createRandomString());
393
- if (!data.redirect_uri)
394
- data.redirect_uri = this.config.redirectURL;
441
+ if (!data.state) data.state = encode(createRandomString());
442
+ if (!data.redirect_uri) data.redirect_uri = this.config.redirectURL;
395
443
  const res = await this.graphqlQuery({
396
444
  query: `
397
445
  mutation magicLinkLogin($data: MagicLinkLoginRequest!) { magic_link_login(params: $data) { message }}
@@ -406,22 +454,21 @@ var _Authorizer = class _Authorizer {
406
454
  err
407
455
  ]);
408
456
  }
409
- };
410
- oauthLogin = async (oauthProvider, roles, redirect_uri, state) => {
457
+ }, "magicLinkLogin");
458
+ oauthLogin = /* @__PURE__ */ __name(async (oauthProvider, roles, redirect_uri, state) => {
411
459
  let urlState = state;
412
460
  if (!urlState) {
413
461
  urlState = encode(createRandomString());
414
462
  }
415
- if (!Object.values(OAuthProviders).includes(oauthProvider)) {
416
- throw new Error(`only following oauth providers are supported: ${Object.values(oauthProvider).toString()}`);
463
+ const oauthProviderIds = Object.values(OAuthProviders);
464
+ if (!oauthProviderIds.includes(oauthProvider)) {
465
+ throw new Error(`only following oauth providers are supported: ${oauthProviderIds.join(", ")}`);
417
466
  }
418
- if (!hasWindow())
419
- throw new Error("oauthLogin is only supported for browsers");
420
- if (roles && roles.length)
421
- urlState += `&roles=${roles.join(",")}`;
422
- window.location.replace(`${this.config.authorizerURL}/oauth_login/${oauthProvider}?redirect_uri=${redirect_uri || this.config.redirectURL}&state=${urlState}`);
423
- };
424
- resendOtp = async (data) => {
467
+ if (!hasWindow()) throw new Error("oauthLogin is only supported for browsers");
468
+ if (roles && roles.length) urlState += `&roles=${roles.join(",")}`;
469
+ window.location.replace(`${this.config.authorizerURL}/oauth_login/${oauthProvider}?redirect_uri=${encodeURIComponent(redirect_uri || this.config.redirectURL || "")}&state=${encodeURIComponent(urlState)}`);
470
+ }, "oauthLogin");
471
+ resendOtp = /* @__PURE__ */ __name(async (data) => {
425
472
  var _a, _b;
426
473
  try {
427
474
  const res = await this.graphqlQuery({
@@ -438,8 +485,8 @@ var _Authorizer = class _Authorizer {
438
485
  err
439
486
  ]);
440
487
  }
441
- };
442
- resetPassword = async (data) => {
488
+ }, "resendOtp");
489
+ resetPassword = /* @__PURE__ */ __name(async (data) => {
443
490
  var _a, _b;
444
491
  try {
445
492
  const resetPasswordRes = await this.graphqlQuery({
@@ -454,27 +501,47 @@ var _Authorizer = class _Authorizer {
454
501
  error
455
502
  ]);
456
503
  }
457
- };
458
- revokeToken = async (data) => {
459
- if (!data.refresh_token && !data.refresh_token.trim())
460
- return this.errorResponse([
461
- new Error("Invalid refresh_token")
462
- ]);
463
- const fetcher = getFetcher();
464
- const res = await fetcher(`${this.config.authorizerURL}/oauth/revoke`, {
465
- method: "POST",
466
- headers: {
467
- ...this.config.extraHeaders
468
- },
469
- body: JSON.stringify({
470
- refresh_token: data.refresh_token,
471
- client_id: this.config.clientID
472
- })
473
- });
474
- const responseData = await res.json();
475
- return this.okResponse(responseData);
476
- };
477
- signup = async (data) => {
504
+ }, "resetPassword");
505
+ revokeToken = /* @__PURE__ */ __name(async (data) => {
506
+ var _a;
507
+ if (!((_a = data.refresh_token) == null ? void 0 : _a.trim())) return this.errorResponse([
508
+ new Error("Invalid refresh_token")
509
+ ]);
510
+ try {
511
+ const fetcher = getFetcher();
512
+ const res = await fetcher(`${this.config.authorizerURL}/oauth/revoke`, {
513
+ method: "POST",
514
+ headers: {
515
+ ...this.config.extraHeaders
516
+ },
517
+ body: JSON.stringify({
518
+ refresh_token: data.refresh_token,
519
+ client_id: this.config.clientID
520
+ })
521
+ });
522
+ const text = await res.text();
523
+ let responseData = {};
524
+ if (text) {
525
+ try {
526
+ responseData = JSON.parse(text);
527
+ } catch {
528
+ return this.errorResponse([
529
+ new Error(res.ok ? "Invalid JSON from revoke endpoint" : `HTTP ${res.status}`)
530
+ ]);
531
+ }
532
+ }
533
+ if (!res.ok) {
534
+ const errBody = responseData;
535
+ return this.errorResponse([
536
+ new Error(String(errBody.error_description || errBody.error || `HTTP ${res.status}`))
537
+ ]);
538
+ }
539
+ return this.okResponse(responseData);
540
+ } catch (err) {
541
+ return this.errorResponse(err);
542
+ }
543
+ }, "revokeToken");
544
+ signup = /* @__PURE__ */ __name(async (data) => {
478
545
  var _a, _b;
479
546
  try {
480
547
  const res = await this.graphqlQuery({
@@ -491,8 +558,8 @@ var _Authorizer = class _Authorizer {
491
558
  err
492
559
  ]);
493
560
  }
494
- };
495
- updateProfile = async (data, headers) => {
561
+ }, "signup");
562
+ updateProfile = /* @__PURE__ */ __name(async (data, headers) => {
496
563
  var _a, _b;
497
564
  try {
498
565
  const updateProfileRes = await this.graphqlQuery({
@@ -508,8 +575,8 @@ var _Authorizer = class _Authorizer {
508
575
  error
509
576
  ]);
510
577
  }
511
- };
512
- deactivateAccount = async (headers) => {
578
+ }, "updateProfile");
579
+ deactivateAccount = /* @__PURE__ */ __name(async (headers) => {
513
580
  var _a, _b;
514
581
  try {
515
582
  const res = await this.graphqlQuery({
@@ -522,8 +589,8 @@ var _Authorizer = class _Authorizer {
522
589
  error
523
590
  ]);
524
591
  }
525
- };
526
- validateJWTToken = async (params) => {
592
+ }, "deactivateAccount");
593
+ validateJWTToken = /* @__PURE__ */ __name(async (params) => {
527
594
  var _a, _b;
528
595
  try {
529
596
  const res = await this.graphqlQuery({
@@ -538,8 +605,8 @@ var _Authorizer = class _Authorizer {
538
605
  error
539
606
  ]);
540
607
  }
541
- };
542
- validateSession = async (params) => {
608
+ }, "validateJWTToken");
609
+ validateSession = /* @__PURE__ */ __name(async (params) => {
543
610
  var _a, _b;
544
611
  try {
545
612
  const res = await this.graphqlQuery({
@@ -554,8 +621,8 @@ var _Authorizer = class _Authorizer {
554
621
  error
555
622
  ]);
556
623
  }
557
- };
558
- verifyEmail = async (data) => {
624
+ }, "validateSession");
625
+ verifyEmail = /* @__PURE__ */ __name(async (data) => {
559
626
  var _a, _b;
560
627
  try {
561
628
  const res = await this.graphqlQuery({
@@ -572,8 +639,8 @@ var _Authorizer = class _Authorizer {
572
639
  err
573
640
  ]);
574
641
  }
575
- };
576
- resendVerifyEmail = async (data) => {
642
+ }, "verifyEmail");
643
+ resendVerifyEmail = /* @__PURE__ */ __name(async (data) => {
577
644
  var _a, _b;
578
645
  try {
579
646
  const res = await this.graphqlQuery({
@@ -590,8 +657,8 @@ var _Authorizer = class _Authorizer {
590
657
  err
591
658
  ]);
592
659
  }
593
- };
594
- verifyOtp = async (data) => {
660
+ }, "resendVerifyEmail");
661
+ verifyOtp = /* @__PURE__ */ __name(async (data) => {
595
662
  var _a, _b;
596
663
  try {
597
664
  const res = await this.graphqlQuery({
@@ -608,10 +675,10 @@ var _Authorizer = class _Authorizer {
608
675
  err
609
676
  ]);
610
677
  }
611
- };
678
+ }, "verifyOtp");
612
679
  // helper to execute graphql queries
613
680
  // takes in any query or mutation string as value
614
- graphqlQuery = async (data) => {
681
+ graphqlQuery = /* @__PURE__ */ __name(async (data) => {
615
682
  var _a;
616
683
  const fetcher = getFetcher();
617
684
  const res = await fetcher(`${this.config.authorizerURL}/graphql`, {
@@ -626,30 +693,58 @@ var _Authorizer = class _Authorizer {
626
693
  },
627
694
  credentials: "include"
628
695
  });
629
- const json = await res.json();
696
+ const text = await res.text();
697
+ let json = {};
698
+ if (text) {
699
+ try {
700
+ json = JSON.parse(text);
701
+ } catch {
702
+ return {
703
+ data: void 0,
704
+ errors: [
705
+ new Error(res.ok ? "Invalid JSON from GraphQL endpoint" : `HTTP ${res.status}`)
706
+ ]
707
+ };
708
+ }
709
+ } else if (!res.ok) {
710
+ return {
711
+ data: void 0,
712
+ errors: [
713
+ new Error(`HTTP ${res.status}`)
714
+ ]
715
+ };
716
+ }
630
717
  if ((_a = json == null ? void 0 : json.errors) == null ? void 0 : _a.length) {
631
718
  return {
632
719
  data: void 0,
633
- errors: json.errors
720
+ errors: toErrorList(json.errors)
721
+ };
722
+ }
723
+ if (!res.ok) {
724
+ return {
725
+ data: void 0,
726
+ errors: [
727
+ new Error(`HTTP ${res.status}`)
728
+ ]
634
729
  };
635
730
  }
636
731
  return {
637
732
  data: json.data,
638
733
  errors: []
639
734
  };
640
- };
641
- errorResponse = (errors) => {
735
+ }, "graphqlQuery");
736
+ errorResponse = /* @__PURE__ */ __name((errors) => {
642
737
  return {
643
738
  data: void 0,
644
- errors
739
+ errors: toErrorList(errors)
645
740
  };
646
- };
647
- okResponse = (data) => {
741
+ }, "errorResponse");
742
+ okResponse = /* @__PURE__ */ __name((data) => {
648
743
  return {
649
744
  data,
650
745
  errors: []
651
746
  };
652
- };
747
+ }, "okResponse");
653
748
  };
654
749
  __name(_Authorizer, "Authorizer");
655
750
  var Authorizer = _Authorizer;