@supabase/gotrue-js 2.9.0 → 2.10.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.
@@ -32,7 +32,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
32
32
  });
33
33
  };
34
34
  Object.defineProperty(exports, "__esModule", { value: true });
35
- exports.decodeJWTPayload = exports.Deferred = exports.decodeBase64URL = exports.removeItemAsync = exports.getItemAsync = exports.setItemAsync = exports.looksLikeFetchResponse = exports.resolveFetch = exports.getParameterByName = exports.isBrowser = exports.uuid = exports.expiresAt = void 0;
35
+ exports.retryable = exports.sleep = exports.decodeJWTPayload = exports.Deferred = exports.decodeBase64URL = exports.removeItemAsync = exports.getItemAsync = exports.setItemAsync = exports.looksLikeFetchResponse = exports.resolveFetch = exports.getParameterByName = exports.isBrowser = exports.uuid = exports.expiresAt = void 0;
36
36
  function expiresAt(expiresIn) {
37
37
  const timeNow = Math.round(Date.now() / 1000);
38
38
  return timeNow + expiresIn;
@@ -166,4 +166,43 @@ function decodeJWTPayload(token) {
166
166
  return JSON.parse(decodeBase64URL(base64Url));
167
167
  }
168
168
  exports.decodeJWTPayload = decodeJWTPayload;
169
+ /**
170
+ * Creates a promise that resolves to null after some time.
171
+ */
172
+ function sleep(time) {
173
+ return new Promise((accept) => {
174
+ setTimeout(() => accept(null), time);
175
+ });
176
+ }
177
+ exports.sleep = sleep;
178
+ /**
179
+ * Converts the provided async function into a retryable function. Each result
180
+ * or thrown error is sent to the isRetryable function which should return true
181
+ * if the function should run again.
182
+ */
183
+ function retryable(fn, isRetryable) {
184
+ const promise = new Promise((accept, reject) => {
185
+ // eslint-disable-next-line @typescript-eslint/no-extra-semi
186
+ ;
187
+ (() => __awaiter(this, void 0, void 0, function* () {
188
+ for (let attempt = 0; attempt < Infinity; attempt++) {
189
+ try {
190
+ const result = yield fn(attempt);
191
+ if (!isRetryable(attempt, null, result)) {
192
+ accept(result);
193
+ return;
194
+ }
195
+ }
196
+ catch (e) {
197
+ if (!isRetryable(attempt, e)) {
198
+ reject(e);
199
+ return;
200
+ }
201
+ }
202
+ }
203
+ }))();
204
+ });
205
+ return promise;
206
+ }
207
+ exports.retryable = retryable;
169
208
  //# sourceMappingURL=helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAgB,SAAS,CAAC,SAAiB;IACzC,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAA;IAC7C,OAAO,OAAO,GAAG,SAAS,CAAA;AAC5B,CAAC;AAHD,8BAGC;AAED,SAAgB,IAAI;IAClB,OAAO,sCAAsC,CAAC,OAAO,CAAC,OAAO,EAAE,UAAU,CAAC;QACxE,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EAChC,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,GAAG,GAAG,CAAA;QACpC,OAAO,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAA;IACvB,CAAC,CAAC,CAAA;AACJ,CAAC;AAND,oBAMC;AAEM,MAAM,SAAS,GAAG,GAAG,EAAE,CAAC,OAAO,QAAQ,KAAK,WAAW,CAAA;AAAjD,QAAA,SAAS,aAAwC;AAE9D,SAAgB,kBAAkB,CAAC,IAAY,EAAE,GAAY;;IAC3D,IAAI,CAAC,GAAG;QAAE,GAAG,GAAG,CAAA,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,QAAQ,0CAAE,IAAI,KAAI,EAAE,CAAA;IAC5C,6CAA6C;IAC7C,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS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,SAAgB,KAAK,CAAC,IAAY;IAChC,OAAO,IAAI,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;QAC5B,UAAU,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAA;IACtC,CAAC,CAAC,CAAA;AACJ,CAAC;AAJD,sBAIC;AAED;;;;GAIG;AACH,SAAgB,SAAS,CACvB,EAAmC,EACnC,WAAwE;IAExE,MAAM,OAAO,GAAG,IAAI,OAAO,CAAI,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE;QAChD,4DAA4D;QAC5D,CAAC;QAAA,CAAC,GAAS,EAAE;YACX,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,QAAQ,EAAE,OAAO,EAAE,EAAE;gBACnD,IAAI;oBACF,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,CAAA;oBAEhC,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,EAAE;wBACvC,MAAM,CAAC,MAAM,CAAC,CAAA;wBACd,OAAM;qBACP;iBACF;gBAAC,OAAO,CAAM,EAAE;oBACf,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE;wBAC5B,MAAM,CAAC,CAAC,CAAC,CAAA;wBACT,OAAM;qBACP;iBACF;aACF;QACH,CAAC,CAAA,CAAC,EAAE,CAAA;IACN,CAAC,CAAC,CAAA;IAEF,OAAO,OAAO,CAAA;AAChB,CAAC;AA1BD,8BA0BC"}
@@ -1,2 +1,2 @@
1
- export declare const version = "2.9.0";
1
+ export declare const version = "2.10.0";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -2,5 +2,5 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.version = void 0;
4
4
  // Generated by genversion.
5
- exports.version = '2.9.0';
5
+ exports.version = '2.10.0';
6
6
  //# sourceMappingURL=version.js.map
@@ -26,8 +26,7 @@ export default class GoTrueClient {
26
26
  protected persistSession: boolean;
27
27
  protected storage: SupportedStorage;
28
28
  protected stateChangeEmitters: Map<string, Subscription>;
29
- protected refreshTokenTimer?: ReturnType<typeof setTimeout>;
30
- protected networkRetries: number;
29
+ protected autoRefreshTicker: ReturnType<typeof setInterval> | null;
31
30
  protected refreshingDeferred: Deferred<CallRefreshTokenResult> | null;
32
31
  /**
33
32
  * Keeps track of the async client initialization.
@@ -234,12 +233,45 @@ export default class GoTrueClient {
234
233
  private _persistSession;
235
234
  private _removeSession;
236
235
  /**
237
- * Clear and re-create refresh token timer
238
- * @param value time intervals in milliseconds.
239
- * @param session The current session.
236
+ * Starts an auto-refresh process in the background. The session is checked
237
+ * every few seconds. Close to the time of expiration a process is started to
238
+ * refresh the session. If refreshing fails it will be retried for as long as
239
+ * necessary.
240
+ *
241
+ * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need
242
+ * to call this function, it will be called for you.
243
+ *
244
+ * On browsers the refresh process works only when the tab/window is in the
245
+ * foreground to conserve resources as well as prevent race conditions and
246
+ * flooding auth with requests.
247
+ *
248
+ * On non-browser platforms the refresh process works *continuously* in the
249
+ * background, which may not be desireable. You should hook into your
250
+ * platform's foreground indication mechanism and call these methods
251
+ * appropriately to conserve resources.
252
+ *
253
+ * {@see #stopAutoRefresh}
254
+ */
255
+ startAutoRefresh(): Promise<void>;
256
+ /**
257
+ * Stops an active auto refresh process running in the background (if any).
258
+ * See {@link #startAutoRefresh} for more details.
259
+ */
260
+ stopAutoRefresh(): Promise<void>;
261
+ /**
262
+ * Runs the auto refresh token tick.
263
+ */
264
+ private _autoRefreshTokenTick;
265
+ /**
266
+ * Registers callbacks on the browser / platform, which in-turn run
267
+ * algorithms when the browser window/tab are in foreground. On non-browser
268
+ * platforms it assumes always foreground.
240
269
  */
241
- private _startAutoRefreshToken;
242
270
  private _handleVisibilityChange;
271
+ /**
272
+ * Callback registered with `window.addEventListener('visibilitychange')`.
273
+ */
274
+ private _onVisibilityChanged;
243
275
  /**
244
276
  * Generates the relevant login URL for a third-party provider.
245
277
  * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed.
@@ -249,36 +281,27 @@ export default class GoTrueClient {
249
281
  private _getUrlForProvider;
250
282
  private _unenroll;
251
283
  /**
252
- * Enrolls a factor
253
- * @param friendlyName Human readable name assigned to a device
254
- * @param factorType device which we're validating against. Can only be TOTP for now.
255
- * @param issuer domain which the user is enrolling with
284
+ * {@see GoTrueMFAApi#enroll}
256
285
  */
257
286
  private _enroll;
258
287
  /**
259
- * Validates a device as part of the enrollment step.
260
- * @param factorId System assigned identifier for authenticator device as returned by enroll
261
- * @param code Code Generated by an authenticator device
288
+ * {@see GoTrueMFAApi#verify}
262
289
  */
263
290
  private _verify;
264
291
  /**
265
- * Creates a challenge which a user can verify against
266
- * @param factorId System assigned identifier for authenticator device as returned by enroll
292
+ * {@see GoTrueMFAApi#challenge}
267
293
  */
268
294
  private _challenge;
269
295
  /**
270
- * Creates a challenge and immediately verifies it
271
- * @param factorId System assigned identifier for authenticator device as returned by enroll
272
- * @param code Code Generated by an authenticator device
296
+ * {@see GoTrueMFAApi#challengeAndVerify}
273
297
  */
274
298
  private _challengeAndVerify;
275
299
  /**
276
- * Displays all devices for a given user
300
+ * {@see GoTrueMFAApi#listFactors}
277
301
  */
278
302
  private _listFactors;
279
303
  /**
280
- * Gets the current and next authenticator assurance level (AAL)
281
- * and the current authentication methods for the session (AMR)
304
+ * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel}
282
305
  */
283
306
  private _getAuthenticatorAssuranceLevel;
284
307
  }
@@ -1 +1 @@
1
- {"version":3,"file":"GoTrueClient.d.ts","sourceRoot":"","sources":["../../src/GoTrueClient.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAQ7C,OAAO,EACL,SAAS,EAQV,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,KAAK,EAA2D,MAAM,aAAa,CAAA;AAC5F,OAAO,EAEL,QAA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AA;KACjB,GACL,OAAO,CACN;QACE,IAAI,EAAE,EAAE,CAAA;QACR,KAAK,EAAE,IAAI,CAAA;KACZ,GACD;QAAE,IAAI,EAAE,IAAI,CAAC;QAAC,KAAK,EAAE,SAAS,CAAA;KAAE,CACnC;IAgBD;;;OAGG;YACW,mBAAmB;IA8BjC,OAAO,CAAC,eAAe;IAWvB,OAAO,CAAC,qBAAqB;IAqB7B;;;OAGG;YACW,kBAAkB;YAoClB,iBAAiB;IAwC/B,OAAO,CAAC,qBAAqB;IAI7B;;;OAGG;YACW,YAAY;IAU1B,OAAO,CAAC,eAAe;YAIT,cAAc;IAQ5B;;;;;;;;;;;;;;;;;;;OAmBG;IACG,gBAAgB;IAWtB;;;OAGG;IACG,eAAe;IASrB;;OAEG;YACW,qBAAqB;IA0BnC;;;;OAIG;YACW,uBAAuB;IAwBrC;;OAEG;YACW,oBAAoB;IAoBlC;;;;;OAKG;IACH,OAAO,CAAC,kBAAkB;YAsBZ,SAAS;IAmBvB;;OAEG;YACW,OAAO;IAkCrB;;OAEG;YACW,OAAO;IAoCrB;;OAEG;YACW,UAAU;IAwBxB;;OAEG;YACW,mBAAmB;IAgBjC;;OAEG;YACW,YAAY;IAuB1B;;OAEG;YACW,+BAA+B;CAoC9C"}
@@ -8,10 +8,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
10
  import GoTrueAdminApi from './GoTrueAdminApi';
11
- import { DEFAULT_HEADERS, EXPIRY_MARGIN, GOTRUE_URL, NETWORK_FAILURE, STORAGE_KEY, } from './lib/constants';
11
+ import { DEFAULT_HEADERS, EXPIRY_MARGIN, GOTRUE_URL, STORAGE_KEY, } from './lib/constants';
12
12
  import { AuthImplicitGrantRedirectError, AuthInvalidCredentialsError, AuthRetryableFetchError, AuthSessionMissingError, AuthUnknownError, isAuthApiError, isAuthError, } from './lib/errors';
13
13
  import { _request, _sessionResponse, _userResponse, _ssoResponse } from './lib/fetch';
14
- import { decodeJWTPayload, Deferred, getItemAsync, getParameterByName, isBrowser, removeItemAsync, resolveFetch, setItemAsync, uuid, } from './lib/helpers';
14
+ import { decodeJWTPayload, Deferred, getItemAsync, getParameterByName, isBrowser, removeItemAsync, resolveFetch, setItemAsync, uuid, retryable, sleep, } from './lib/helpers';
15
15
  import localStorageAdapter from './lib/local-storage';
16
16
  import { polyfillGlobalThis } from './lib/polyfills';
17
17
  polyfillGlobalThis(); // Make "globalThis" available
@@ -23,13 +23,18 @@ const DEFAULT_OPTIONS = {
23
23
  detectSessionInUrl: true,
24
24
  headers: DEFAULT_HEADERS,
25
25
  };
26
+ /** Current session will be checked for refresh at this interval. */
27
+ const AUTO_REFRESH_TICK_DURATION = 10 * 1000;
28
+ /**
29
+ * A token refresh will be attempted this many ticks before the current session expires. */
30
+ const AUTO_REFRESH_TICK_THRESHOLD = 3;
26
31
  export default class GoTrueClient {
27
32
  /**
28
33
  * Create a new client for use in the browser.
29
34
  */
30
35
  constructor(options) {
31
36
  this.stateChangeEmitters = new Map();
32
- this.networkRetries = 0;
37
+ this.autoRefreshTicker = null;
33
38
  this.refreshingDeferred = null;
34
39
  /**
35
40
  * Keeps track of the async client initialization.
@@ -54,7 +59,6 @@ export default class GoTrueClient {
54
59
  this.headers = settings.headers;
55
60
  this.fetch = resolveFetch(settings.fetch);
56
61
  this.detectSessionInUrl = settings.detectSessionInUrl;
57
- this.initialize();
58
62
  this.mfa = {
59
63
  verify: this._verify.bind(this),
60
64
  enroll: this._enroll.bind(this),
@@ -64,6 +68,7 @@ export default class GoTrueClient {
64
68
  challengeAndVerify: this._challengeAndVerify.bind(this),
65
69
  getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this),
66
70
  };
71
+ this.initialize();
67
72
  }
68
73
  /**
69
74
  * Initializes the client session either from the url or from storage.
@@ -117,7 +122,7 @@ export default class GoTrueClient {
117
122
  };
118
123
  }
119
124
  finally {
120
- this._handleVisibilityChange();
125
+ yield this._handleVisibilityChange();
121
126
  }
122
127
  });
123
128
  }
@@ -742,11 +747,20 @@ export default class GoTrueClient {
742
747
  _refreshAccessToken(refreshToken) {
743
748
  return __awaiter(this, void 0, void 0, function* () {
744
749
  try {
745
- return yield _request(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, {
746
- body: { refresh_token: refreshToken },
747
- headers: this.headers,
748
- xform: _sessionResponse,
749
- });
750
+ const startedAt = Date.now();
751
+ // will attempt to refresh the token with exponential backoff
752
+ return yield retryable((attempt) => __awaiter(this, void 0, void 0, function* () {
753
+ yield sleep(attempt * 200); // 0, 200, 400, 800, ...
754
+ return yield _request(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, {
755
+ body: { refresh_token: refreshToken },
756
+ headers: this.headers,
757
+ xform: _sessionResponse,
758
+ });
759
+ }), (attempt, _, result) => result &&
760
+ result.error &&
761
+ result.error instanceof AuthRetryableFetchError &&
762
+ // retryable only if the request can be sent before the backoff overflows the tick duration
763
+ Date.now() + (attempt + 1) * 200 - startedAt < AUTO_REFRESH_TICK_DURATION);
750
764
  }
751
765
  catch (error) {
752
766
  if (isAuthError(error)) {
@@ -794,21 +808,11 @@ export default class GoTrueClient {
794
808
  const timeNow = Math.round(Date.now() / 1000);
795
809
  if (((_a = currentSession.expires_at) !== null && _a !== void 0 ? _a : Infinity) < timeNow + EXPIRY_MARGIN) {
796
810
  if (this.autoRefreshToken && currentSession.refresh_token) {
797
- this.networkRetries++;
798
811
  const { error } = yield this._callRefreshToken(currentSession.refresh_token);
799
812
  if (error) {
800
813
  console.log(error.message);
801
- if (error instanceof AuthRetryableFetchError &&
802
- this.networkRetries < NETWORK_FAILURE.MAX_RETRIES) {
803
- if (this.refreshTokenTimer)
804
- clearTimeout(this.refreshTokenTimer);
805
- this.refreshTokenTimer = setTimeout(() => this._recoverAndRefresh(), Math.pow(NETWORK_FAILURE.RETRY_INTERVAL, this.networkRetries) * 100 // exponential backoff
806
- );
807
- return;
808
- }
809
814
  yield this._removeSession();
810
815
  }
811
- this.networkRetries = 0;
812
816
  }
813
817
  else {
814
818
  yield this._removeSession();
@@ -876,13 +880,6 @@ export default class GoTrueClient {
876
880
  if (!this.persistSession) {
877
881
  this.inMemorySession = session;
878
882
  }
879
- const expiresAt = session.expires_at;
880
- if (expiresAt) {
881
- const timeNow = Math.round(Date.now() / 1000);
882
- const expiresIn = expiresAt - timeNow;
883
- const refreshDurationBeforeExpires = expiresIn > EXPIRY_MARGIN ? EXPIRY_MARGIN : 0.5;
884
- this._startAutoRefreshToken((expiresIn - refreshDurationBeforeExpires) * 1000);
885
- }
886
883
  if (this.persistSession && session.expires_at) {
887
884
  yield this._persistSession(session);
888
885
  }
@@ -899,51 +896,119 @@ export default class GoTrueClient {
899
896
  else {
900
897
  this.inMemorySession = null;
901
898
  }
902
- if (this.refreshTokenTimer) {
903
- clearTimeout(this.refreshTokenTimer);
899
+ });
900
+ }
901
+ /**
902
+ * Starts an auto-refresh process in the background. The session is checked
903
+ * every few seconds. Close to the time of expiration a process is started to
904
+ * refresh the session. If refreshing fails it will be retried for as long as
905
+ * necessary.
906
+ *
907
+ * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need
908
+ * to call this function, it will be called for you.
909
+ *
910
+ * On browsers the refresh process works only when the tab/window is in the
911
+ * foreground to conserve resources as well as prevent race conditions and
912
+ * flooding auth with requests.
913
+ *
914
+ * On non-browser platforms the refresh process works *continuously* in the
915
+ * background, which may not be desireable. You should hook into your
916
+ * platform's foreground indication mechanism and call these methods
917
+ * appropriately to conserve resources.
918
+ *
919
+ * {@see #stopAutoRefresh}
920
+ */
921
+ startAutoRefresh() {
922
+ return __awaiter(this, void 0, void 0, function* () {
923
+ yield this.stopAutoRefresh();
924
+ this.autoRefreshTicker = setInterval(() => this._autoRefreshTokenTick(), AUTO_REFRESH_TICK_DURATION);
925
+ // run the tick immediately
926
+ yield this._autoRefreshTokenTick();
927
+ });
928
+ }
929
+ /**
930
+ * Stops an active auto refresh process running in the background (if any).
931
+ * See {@link #startAutoRefresh} for more details.
932
+ */
933
+ stopAutoRefresh() {
934
+ return __awaiter(this, void 0, void 0, function* () {
935
+ const ticker = this.autoRefreshTicker;
936
+ this.autoRefreshTicker = null;
937
+ if (ticker) {
938
+ clearInterval(ticker);
904
939
  }
905
940
  });
906
941
  }
907
942
  /**
908
- * Clear and re-create refresh token timer
909
- * @param value time intervals in milliseconds.
910
- * @param session The current session.
943
+ * Runs the auto refresh token tick.
911
944
  */
912
- _startAutoRefreshToken(value) {
913
- if (this.refreshTokenTimer)
914
- clearTimeout(this.refreshTokenTimer);
915
- if (value <= 0 || !this.autoRefreshToken)
916
- return;
917
- this.refreshTokenTimer = setTimeout(() => __awaiter(this, void 0, void 0, function* () {
918
- this.networkRetries++;
919
- const { data: { session }, error: sessionError, } = yield this.getSession();
920
- if (!sessionError && session) {
921
- const { error } = yield this._callRefreshToken(session.refresh_token);
922
- if (!error)
923
- this.networkRetries = 0;
924
- if (error instanceof AuthRetryableFetchError &&
925
- this.networkRetries < NETWORK_FAILURE.MAX_RETRIES)
926
- this._startAutoRefreshToken(Math.pow(NETWORK_FAILURE.RETRY_INTERVAL, this.networkRetries) * 100); // exponential backoff
927
- }
928
- }), value);
929
- if (typeof this.refreshTokenTimer.unref === 'function')
930
- this.refreshTokenTimer.unref();
945
+ _autoRefreshTokenTick() {
946
+ return __awaiter(this, void 0, void 0, function* () {
947
+ const now = Date.now();
948
+ try {
949
+ const { data: { session }, error, } = yield this.getSession();
950
+ if (!session || !session.refresh_token || !session.expires_at) {
951
+ return;
952
+ }
953
+ // session will expire in this many ticks (or has already expired if <= 0)
954
+ const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / AUTO_REFRESH_TICK_DURATION);
955
+ if (expiresInTicks < AUTO_REFRESH_TICK_THRESHOLD) {
956
+ yield this._callRefreshToken(session.refresh_token);
957
+ }
958
+ }
959
+ catch (e) {
960
+ console.error('Auto refresh tick failed with error. This is likely a transient error.', e);
961
+ }
962
+ });
931
963
  }
964
+ /**
965
+ * Registers callbacks on the browser / platform, which in-turn run
966
+ * algorithms when the browser window/tab are in foreground. On non-browser
967
+ * platforms it assumes always foreground.
968
+ */
932
969
  _handleVisibilityChange() {
933
- if (!isBrowser() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) {
934
- return false;
935
- }
936
- try {
937
- window === null || window === void 0 ? void 0 : window.addEventListener('visibilitychange', () => __awaiter(this, void 0, void 0, function* () {
938
- if (document.visibilityState === 'visible') {
970
+ return __awaiter(this, void 0, void 0, function* () {
971
+ if (!isBrowser() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) {
972
+ if (this.autoRefreshToken) {
973
+ // in non-browser environments the refresh token ticker runs always
974
+ this.startAutoRefresh();
975
+ }
976
+ return false;
977
+ }
978
+ try {
979
+ window === null || window === void 0 ? void 0 : window.addEventListener('visibilitychange', () => __awaiter(this, void 0, void 0, function* () { return yield this._onVisibilityChanged(false); }));
980
+ // now immediately call the visbility changed callback to setup with the
981
+ // current visbility state
982
+ yield this._onVisibilityChanged(true); // initial call
983
+ }
984
+ catch (error) {
985
+ console.error('_handleVisibilityChange', error);
986
+ }
987
+ });
988
+ }
989
+ /**
990
+ * Callback registered with `window.addEventListener('visibilitychange')`.
991
+ */
992
+ _onVisibilityChanged(isInitial) {
993
+ return __awaiter(this, void 0, void 0, function* () {
994
+ if (document.visibilityState === 'visible') {
995
+ if (!isInitial) {
996
+ // initial visibility change setup is handled in another flow under #initialize()
939
997
  yield this.initializePromise;
940
998
  yield this._recoverAndRefresh();
941
999
  }
942
- }));
943
- }
944
- catch (error) {
945
- console.error('_handleVisibilityChange', error);
946
- }
1000
+ if (this.autoRefreshToken) {
1001
+ // in browser environments the refresh token ticker runs only on focused tabs
1002
+ // which prevents race conditions
1003
+ this.startAutoRefresh();
1004
+ }
1005
+ }
1006
+ else if (document.visibilityState === 'hidden') {
1007
+ if (this.autoRefreshToken) {
1008
+ this.stopAutoRefresh();
1009
+ }
1010
+ }
1011
+ });
947
1012
  }
948
1013
  /**
949
1014
  * Generates the relevant login URL for a third-party provider.
@@ -987,10 +1052,7 @@ export default class GoTrueClient {
987
1052
  });
988
1053
  }
989
1054
  /**
990
- * Enrolls a factor
991
- * @param friendlyName Human readable name assigned to a device
992
- * @param factorType device which we're validating against. Can only be TOTP for now.
993
- * @param issuer domain which the user is enrolling with
1055
+ * {@see GoTrueMFAApi#enroll}
994
1056
  */
995
1057
  _enroll(params) {
996
1058
  var _a, _b;
@@ -1026,9 +1088,7 @@ export default class GoTrueClient {
1026
1088
  });
1027
1089
  }
1028
1090
  /**
1029
- * Validates a device as part of the enrollment step.
1030
- * @param factorId System assigned identifier for authenticator device as returned by enroll
1031
- * @param code Code Generated by an authenticator device
1091
+ * {@see GoTrueMFAApi#verify}
1032
1092
  */
1033
1093
  _verify(params) {
1034
1094
  var _a;
@@ -1059,8 +1119,7 @@ export default class GoTrueClient {
1059
1119
  });
1060
1120
  }
1061
1121
  /**
1062
- * Creates a challenge which a user can verify against
1063
- * @param factorId System assigned identifier for authenticator device as returned by enroll
1122
+ * {@see GoTrueMFAApi#challenge}
1064
1123
  */
1065
1124
  _challenge(params) {
1066
1125
  var _a;
@@ -1084,9 +1143,7 @@ export default class GoTrueClient {
1084
1143
  });
1085
1144
  }
1086
1145
  /**
1087
- * Creates a challenge and immediately verifies it
1088
- * @param factorId System assigned identifier for authenticator device as returned by enroll
1089
- * @param code Code Generated by an authenticator device
1146
+ * {@see GoTrueMFAApi#challengeAndVerify}
1090
1147
  */
1091
1148
  _challengeAndVerify(params) {
1092
1149
  return __awaiter(this, void 0, void 0, function* () {
@@ -1104,7 +1161,7 @@ export default class GoTrueClient {
1104
1161
  });
1105
1162
  }
1106
1163
  /**
1107
- * Displays all devices for a given user
1164
+ * {@see GoTrueMFAApi#listFactors}
1108
1165
  */
1109
1166
  _listFactors() {
1110
1167
  return __awaiter(this, void 0, void 0, function* () {
@@ -1124,8 +1181,7 @@ export default class GoTrueClient {
1124
1181
  });
1125
1182
  }
1126
1183
  /**
1127
- * Gets the current and next authenticator assurance level (AAL)
1128
- * and the current authentication methods for the session (AMR)
1184
+ * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel}
1129
1185
  */
1130
1186
  _getAuthenticatorAssuranceLevel() {
1131
1187
  var _a, _b;