@emilgroup/public-api-sdk 1.40.1-beta.25 → 1.40.1-beta.27

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
@@ -17,11 +17,11 @@ Although this package can be used in both TypeScript and JavaScript, it is inten
17
17
  Navigate to the folder of your consuming project and run one of the following commands:
18
18
 
19
19
  ```
20
- npm install @emilgroup/public-api-sdk@1.40.1-beta.25 --save
20
+ npm install @emilgroup/public-api-sdk@1.40.1-beta.27 --save
21
21
  ```
22
22
  or
23
23
  ```
24
- yarn add @emilgroup/public-api-sdk@1.40.1-beta.25
24
+ yarn add @emilgroup/public-api-sdk@1.40.1-beta.27
25
25
  ```
26
26
 
27
27
  And then you can import `PublicApi`.
package/base.ts CHANGED
@@ -72,9 +72,8 @@ export enum Environment {
72
72
  let _retry_count = 0
73
73
  let _retry = null
74
74
 
75
- // Marks each request with the account (username) of the SDK object that sent it: only SDK objects of that
76
- // account refresh and resend it, never an object of another account open in the same browser.
77
- const REQUEST_OWNER = '_emilSdkOwner';
75
+ // Refreshes in flight per account (BaseAPI.shareRefresh).
76
+ const refreshesInFlight = new Map<string, Promise<LoginClass>>();
78
77
 
79
78
  export function resetRetry() {
80
79
  _retry_count = 0
@@ -346,7 +345,10 @@ export class BaseAPI {
346
345
  const { username } = this.configuration;
347
346
 
348
347
  if (!username) {
349
- throw new Error('Failed to refresh token.');
348
+ // This object cannot refresh at all, so the session it relied on is over for it.
349
+ const cannotRefresh: any = new Error('Failed to refresh token.');
350
+ cannotRefresh.sessionExpired = true;
351
+ throw cannotRefresh;
350
352
  }
351
353
 
352
354
  const refreshTokenAxios = globalAxios.create()
@@ -417,6 +419,10 @@ export class BaseAPI {
417
419
  this.storeTokenData(null);
418
420
  }
419
421
 
422
+ // Marks each request with the account (username) of the SDK object that sent it: only SDK objects of that
423
+ // account refresh and resend it, never an object of another account in the same app.
424
+ private static readonly REQUEST_OWNER = '_emilSdkOwner';
425
+
420
426
  private ownAccount(): string {
421
427
  return (this.configuration.username || '').toLowerCase();
422
428
  }
@@ -426,7 +432,70 @@ export class BaseAPI {
426
432
  if (!this.ownAccount()) {
427
433
  return { ...options };
428
434
  }
429
- return { ...options, [REQUEST_OWNER]: this.ownAccount() } as AxiosRequestConfig;
435
+ return { ...options, [BaseAPI.REQUEST_OWNER]: this.ownAccount() } as AxiosRequestConfig;
436
+ }
437
+
438
+ // Sent for another account: only that account's SDK objects handle it. Unmarked requests as before.
439
+ private sentByOtherAccount(config?: AxiosRequestConfig): boolean {
440
+ const owner = (config as Record<string, unknown> | undefined)?.[BaseAPI.REQUEST_OWNER];
441
+ return owner !== undefined && owner !== this.ownAccount();
442
+ }
443
+
444
+
445
+ // One refresh per account; an object without a username keeps its own, which fails as before.
446
+ private sharedRefresh(): Promise<LoginClass> {
447
+ const account = this.ownAccount();
448
+ if (!account) {
449
+ return this.refreshTokenInternal();
450
+ }
451
+ return BaseAPI.shareRefresh(refreshesInFlight, account, () => this.refreshTokenInternal());
452
+ }
453
+
454
+ private refreshRunning(): boolean {
455
+ const account = this.ownAccount();
456
+ return !!account && refreshesInFlight.has(account);
457
+ }
458
+
459
+ // Joins the refresh already in flight for this key, or starts one: calls refused at the same time wait for
460
+ // one refresh instead of each starting their own (a refresh token may be single-use). The entry is removed
461
+ // when the refresh settles.
462
+ private static shareRefresh<K, T>(inFlight: Map<K, Promise<T>>, key: K, start: () => Promise<T>): Promise<T> {
463
+ const running = inFlight.get(key);
464
+ if (running) {
465
+ return running;
466
+ }
467
+ const refresh = start();
468
+ inFlight.set(key, refresh);
469
+ const settled = () => { inFlight.delete(key); };
470
+ refresh.then(settled, settled);
471
+ return refresh;
472
+ }
473
+
474
+ // A refused call that joins a refresh already running is not a new try: only started refreshes count toward
475
+ // the limit, so every call refused at the same time is retried.
476
+ private mayRefreshAfterNetworkError(): boolean {
477
+ if (this.refreshRunning()) {
478
+ return true;
479
+ }
480
+ if (_retry_count >= 4) {
481
+ return false;
482
+ }
483
+ _retry_count++;
484
+ return true;
485
+ }
486
+
487
+
488
+ // Rejects as before (the refresh's response body, or its error). Marks it as an ended session only when the
489
+ // refresh was refused (401 or 403) or could not run (no username, marked where it is thrown); a server error
490
+ // or a network error says nothing about the session, so an app must not log the user out for it. A body that
491
+ // is not an object cannot carry the mark and is kept as it is.
492
+ private rejectEndedSession(error: any): Promise<never> {
493
+ const rejection = error.response?.data || error;
494
+ const status = error.response?.status;
495
+ if (typeof rejection === 'object' && (status === 401 || status === 403)) {
496
+ rejection.sessionExpired = true;
497
+ }
498
+ return Promise.reject(rejection);
430
499
  }
431
500
 
432
501
  private attachInterceptor(axios: AxiosInstance) {
@@ -436,9 +505,7 @@ export class BaseAPI {
436
505
  },
437
506
  async (err) => {
438
507
  let originalConfig = err.config;
439
- // Sent for another account: only that account's SDK objects handle it. Unmarked requests as before.
440
- const owner = originalConfig?.[REQUEST_OWNER];
441
- if (owner !== undefined && owner !== this.ownAccount()) {
508
+ if (this.sentByOtherAccount(originalConfig)) {
442
509
  return Promise.reject(err);
443
510
  }
444
511
  if (err.response && !(err.response instanceof XMLHttpRequest)) { // sometimes buggy and is of type request
@@ -447,7 +514,7 @@ export class BaseAPI {
447
514
  && !originalConfig._retry) {
448
515
  originalConfig._retry = true;
449
516
  try {
450
- const reply = await this.refreshTokenInternal();
517
+ const reply = await this.sharedRefresh();
451
518
  this.tokenData.permissions = reply.permissions;
452
519
  this.applyTokenReply(reply, true);
453
520
  this.storeTokenData(this.tokenData);
@@ -464,10 +531,7 @@ export class BaseAPI {
464
531
  return this.retryWithToken(axios, originalConfig);
465
532
  });
466
533
  } catch (_error) {
467
- if (_error.response && _error.response.data) {
468
- return Promise.reject(_error.response.data);
469
- }
470
- return Promise.reject(_error);
534
+ return this.rejectEndedSession(_error);
471
535
  }
472
536
  }
473
537
  } else if (err.message === NETWORK_ERROR_MESSAGE && this.canRetryWithToken(originalConfig)) {
@@ -480,12 +544,11 @@ export class BaseAPI {
480
544
  } else if (err.message === NETWORK_ERROR_MESSAGE
481
545
  && (originalConfig.headers.hasOwnProperty('Authorization')
482
546
  || (this.configuration.cookieAuth && originalConfig.withCredentials && this.canResend(originalConfig)))
483
- && _retry_count < 4
547
+ && this.mayRefreshAfterNetworkError()
484
548
  ) {
485
- _retry_count++;
486
549
  try {
487
550
  // In session mode an unreadable 401 (no CORS headers on the error reply) also lands here.
488
- const reply = await this.refreshTokenInternal();
551
+ const reply = await this.sharedRefresh();
489
552
  this.tokenData.permissions = reply.permissions;
490
553
 
491
554
  _retry = true;
@@ -501,10 +564,7 @@ export class BaseAPI {
501
564
  return retried;
502
565
  });
503
566
  } catch (_error) {
504
- if (_error.response && _error.response.data) {
505
- return Promise.reject(_error.response.data);
506
- }
507
- return Promise.reject(_error);
567
+ return this.rejectEndedSession(_error);
508
568
  }
509
569
  }
510
570
  return Promise.reject(err);
package/dist/base.d.ts CHANGED
@@ -96,8 +96,15 @@ export declare class BaseAPI {
96
96
  private storeTokenData;
97
97
  loadTokenData(): void;
98
98
  cleanTokenData(): void;
99
+ private static readonly REQUEST_OWNER;
99
100
  private ownAccount;
100
101
  protected withOwner(options?: AxiosRequestConfig): AxiosRequestConfig;
102
+ private sentByOtherAccount;
103
+ private sharedRefresh;
104
+ private refreshRunning;
105
+ private static shareRefresh;
106
+ private mayRefreshAfterNetworkError;
107
+ private rejectEndedSession;
101
108
  private attachInterceptor;
102
109
  }
103
110
  /**
package/dist/base.js CHANGED
@@ -117,9 +117,8 @@ var Environment;
117
117
  })(Environment = exports.Environment || (exports.Environment = {}));
118
118
  var _retry_count = 0;
119
119
  var _retry = null;
120
- // Marks each request with the account (username) of the SDK object that sent it: only SDK objects of that
121
- // account refresh and resend it, never an object of another account open in the same browser.
122
- var REQUEST_OWNER = '_emilSdkOwner';
120
+ // Refreshes in flight per account (BaseAPI.shareRefresh).
121
+ var refreshesInFlight = new Map();
123
122
  function resetRetry() {
124
123
  _retry_count = 0;
125
124
  }
@@ -356,14 +355,16 @@ var BaseAPI = /** @class */ (function () {
356
355
  };
357
356
  BaseAPI.prototype.refreshTokenInternal = function () {
358
357
  return __awaiter(this, void 0, void 0, function () {
359
- var username, refreshTokenAxios, options, response;
358
+ var username, cannotRefresh, refreshTokenAxios, options, response;
360
359
  var _this = this;
361
360
  return __generator(this, function (_a) {
362
361
  switch (_a.label) {
363
362
  case 0:
364
363
  username = this.configuration.username;
365
364
  if (!username) {
366
- throw new Error('Failed to refresh token.');
365
+ cannotRefresh = new Error('Failed to refresh token.');
366
+ cannotRefresh.sessionExpired = true;
367
+ throw cannotRefresh;
367
368
  }
368
369
  refreshTokenAxios = axios_1.default.create();
369
370
  refreshTokenAxios.interceptors.response.use(function (response) {
@@ -439,21 +440,77 @@ var BaseAPI = /** @class */ (function () {
439
440
  if (!this.ownAccount()) {
440
441
  return __assign({}, options);
441
442
  }
442
- return __assign(__assign({}, options), (_a = {}, _a[REQUEST_OWNER] = this.ownAccount(), _a));
443
+ return __assign(__assign({}, options), (_a = {}, _a[BaseAPI.REQUEST_OWNER] = this.ownAccount(), _a));
444
+ };
445
+ // Sent for another account: only that account's SDK objects handle it. Unmarked requests as before.
446
+ BaseAPI.prototype.sentByOtherAccount = function (config) {
447
+ var owner = config === null || config === void 0 ? void 0 : config[BaseAPI.REQUEST_OWNER];
448
+ return owner !== undefined && owner !== this.ownAccount();
449
+ };
450
+ // One refresh per account; an object without a username keeps its own, which fails as before.
451
+ BaseAPI.prototype.sharedRefresh = function () {
452
+ var _this = this;
453
+ var account = this.ownAccount();
454
+ if (!account) {
455
+ return this.refreshTokenInternal();
456
+ }
457
+ return BaseAPI.shareRefresh(refreshesInFlight, account, function () { return _this.refreshTokenInternal(); });
458
+ };
459
+ BaseAPI.prototype.refreshRunning = function () {
460
+ var account = this.ownAccount();
461
+ return !!account && refreshesInFlight.has(account);
462
+ };
463
+ // Joins the refresh already in flight for this key, or starts one: calls refused at the same time wait for
464
+ // one refresh instead of each starting their own (a refresh token may be single-use). The entry is removed
465
+ // when the refresh settles.
466
+ BaseAPI.shareRefresh = function (inFlight, key, start) {
467
+ var running = inFlight.get(key);
468
+ if (running) {
469
+ return running;
470
+ }
471
+ var refresh = start();
472
+ inFlight.set(key, refresh);
473
+ var settled = function () { inFlight.delete(key); };
474
+ refresh.then(settled, settled);
475
+ return refresh;
476
+ };
477
+ // A refused call that joins a refresh already running is not a new try: only started refreshes count toward
478
+ // the limit, so every call refused at the same time is retried.
479
+ BaseAPI.prototype.mayRefreshAfterNetworkError = function () {
480
+ if (this.refreshRunning()) {
481
+ return true;
482
+ }
483
+ if (_retry_count >= 4) {
484
+ return false;
485
+ }
486
+ _retry_count++;
487
+ return true;
488
+ };
489
+ // Rejects as before (the refresh's response body, or its error). Marks it as an ended session only when the
490
+ // refresh was refused (401 or 403) or could not run (no username, marked where it is thrown); a server error
491
+ // or a network error says nothing about the session, so an app must not log the user out for it. A body that
492
+ // is not an object cannot carry the mark and is kept as it is.
493
+ BaseAPI.prototype.rejectEndedSession = function (error) {
494
+ var _a, _b;
495
+ var rejection = ((_a = error.response) === null || _a === void 0 ? void 0 : _a.data) || error;
496
+ var status = (_b = error.response) === null || _b === void 0 ? void 0 : _b.status;
497
+ if (typeof rejection === 'object' && (status === 401 || status === 403)) {
498
+ rejection.sessionExpired = true;
499
+ }
500
+ return Promise.reject(rejection);
443
501
  };
444
502
  BaseAPI.prototype.attachInterceptor = function (axios) {
445
503
  var _this = this;
446
504
  axios.interceptors.response.use(function (res) {
447
505
  return res;
448
506
  }, function (err) { return __awaiter(_this, void 0, void 0, function () {
449
- var originalConfig, owner, reply, _error_1, reply, _error_2;
507
+ var originalConfig, reply, _error_1, reply, _error_2;
450
508
  var _this = this;
451
509
  return __generator(this, function (_a) {
452
510
  switch (_a.label) {
453
511
  case 0:
454
512
  originalConfig = err.config;
455
- owner = originalConfig === null || originalConfig === void 0 ? void 0 : originalConfig[REQUEST_OWNER];
456
- if (owner !== undefined && owner !== this.ownAccount()) {
513
+ if (this.sentByOtherAccount(originalConfig)) {
457
514
  return [2 /*return*/, Promise.reject(err)];
458
515
  }
459
516
  if (!(err.response && !(err.response instanceof XMLHttpRequest))) return [3 /*break*/, 5];
@@ -463,7 +520,7 @@ var BaseAPI = /** @class */ (function () {
463
520
  _a.label = 1;
464
521
  case 1:
465
522
  _a.trys.push([1, 3, , 4]);
466
- return [4 /*yield*/, this.refreshTokenInternal()];
523
+ return [4 /*yield*/, this.sharedRefresh()];
467
524
  case 2:
468
525
  reply = _a.sent();
469
526
  this.tokenData.permissions = reply.permissions;
@@ -482,10 +539,7 @@ var BaseAPI = /** @class */ (function () {
482
539
  })];
483
540
  case 3:
484
541
  _error_1 = _a.sent();
485
- if (_error_1.response && _error_1.response.data) {
486
- return [2 /*return*/, Promise.reject(_error_1.response.data)];
487
- }
488
- return [2 /*return*/, Promise.reject(_error_1)];
542
+ return [2 /*return*/, this.rejectEndedSession(_error_1)];
489
543
  case 4: return [3 /*break*/, 10];
490
544
  case 5:
491
545
  if (!(err.message === NETWORK_ERROR_MESSAGE && this.canRetryWithToken(originalConfig))) return [3 /*break*/, 6];
@@ -499,12 +553,11 @@ var BaseAPI = /** @class */ (function () {
499
553
  if (!(err.message === NETWORK_ERROR_MESSAGE
500
554
  && (originalConfig.headers.hasOwnProperty('Authorization')
501
555
  || (this.configuration.cookieAuth && originalConfig.withCredentials && this.canResend(originalConfig)))
502
- && _retry_count < 4)) return [3 /*break*/, 10];
503
- _retry_count++;
556
+ && this.mayRefreshAfterNetworkError())) return [3 /*break*/, 10];
504
557
  _a.label = 7;
505
558
  case 7:
506
559
  _a.trys.push([7, 9, , 10]);
507
- return [4 /*yield*/, this.refreshTokenInternal()];
560
+ return [4 /*yield*/, this.sharedRefresh()];
508
561
  case 8:
509
562
  reply = _a.sent();
510
563
  this.tokenData.permissions = reply.permissions;
@@ -519,15 +572,15 @@ var BaseAPI = /** @class */ (function () {
519
572
  })];
520
573
  case 9:
521
574
  _error_2 = _a.sent();
522
- if (_error_2.response && _error_2.response.data) {
523
- return [2 /*return*/, Promise.reject(_error_2.response.data)];
524
- }
525
- return [2 /*return*/, Promise.reject(_error_2)];
575
+ return [2 /*return*/, this.rejectEndedSession(_error_2)];
526
576
  case 10: return [2 /*return*/, Promise.reject(err)];
527
577
  }
528
578
  });
529
579
  }); });
530
580
  };
581
+ // Marks each request with the account (username) of the SDK object that sent it: only SDK objects of that
582
+ // account refresh and resend it, never an object of another account in the same app.
583
+ BaseAPI.REQUEST_OWNER = '_emilSdkOwner';
531
584
  return BaseAPI;
532
585
  }());
533
586
  exports.BaseAPI = BaseAPI;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@emilgroup/public-api-sdk",
3
- "version": "1.40.1-beta.25",
3
+ "version": "1.40.1-beta.27",
4
4
  "description": "OpenAPI client for @emilgroup/public-api-sdk",
5
5
  "author": "OpenAPI-Generator Contributors",
6
6
  "keywords": [
@@ -18,7 +18,7 @@
18
18
  "prepare": "npm run build"
19
19
  },
20
20
  "dependencies": {
21
- "axios": "1.20.0"
21
+ "axios": "1.21.1"
22
22
  },
23
23
  "devDependencies": {
24
24