FRE-600: Fix code review blockers

- Consolidated duplicate UndoManagers to single instance
- Fixed connection promise to only resolve on 'connected' status
- Fixed WebSocketProvider import (WebsocketProvider)
- Added proper doc.destroy() cleanup
- Renamed isPresenceInitialized property to avoid conflict

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
2026-04-25 00:08:01 -04:00
parent 65b552bb08
commit 7c684a42cc
48450 changed files with 5679671 additions and 383 deletions

25
node_modules/browser-tabs-lock/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,25 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.3.0] - 2023-04-25
- Allows passing of custom storage handler which can be used to override the fact that this lib writes to localstorage
## [1.2.15] - 2021-08-09
### Changed
- Readme and post install message
## [1.2.14] - 2021-04-29
### Changed
- Dependency upgrade:
- https://github.com/supertokens/browser-tabs-lock/pull/21
- https://github.com/supertokens/browser-tabs-lock/pull/19
- https://github.com/supertokens/browser-tabs-lock/pull/16
## [1.2.13] - 2021-04-24
### Changed
- Upgraded version of Lodash: https://github.com/supertokens/browser-tabs-lock/issues/20

20
node_modules/browser-tabs-lock/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2019 SuperTokens, VRAI Labs Pvt. Ltd, India
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

157
node_modules/browser-tabs-lock/README.md generated vendored Normal file
View File

@@ -0,0 +1,157 @@
[![SuperTokens banner](https://raw.githubusercontent.com/supertokens/supertokens-logo/master/images/Artboard%20%E2%80%93%2027%402x.png)](https://supertokens.io)
[![License: MIT](https://img.shields.io/badge/License-MIT-brightgreen.svg)](https://github.com/supertokens/auth-node-mysql-ref-jwt/blob/master/LICENSE)
<a href="https://supertokens.io/discord">
<img src="https://img.shields.io/discord/603466164219281420.svg?logo=discord"
alt="chat on Discord"></a>
[![Slack](https://img.shields.io/badge/slack-chat-brightgreen?logo=slack)](https://join.slack.com/t/webmobilesecurity/shared_invite/enQtODM4MDM2MTQ1MDYyLTFiNmNhYzRlNGNjODhkNjc5MDRlYTBmZTBiNjFhOTFhYjI1MTc3ZWI2ZjY3Y2M3ZjY1MGJhZmRiNDFjNDNjOTM)
# Browser Tabs Lock
Using this package, you can easily get lock functionality across tabs on all modern browsers.
**This library was originally designed to be used as a part of our project - SuperTokens - an open source auth solution for web and mobile apps. Support us by checking it out [here](https://supertokens.io).**
We are also offering free, one-to-one implementation support:
- Schedule a short call with us on https://calendly.com/supertokens-rishabh.
## Some things to note about:
- This is not a reentrant lock. So please do not attempt to re-acquire a lock using the same lock instance with the same key without releasing the acquired lock / key first.
- Theoretically speaking, it is impossible to have foolproof locking built on top of javascript in the browser. One can only make it so that in all practical scenarios, it emulates locking.
## Installation using Node:
```bash
npm i --save browser-tabs-lock
```
### Usage in an async function:
```js
import SuperTokensLock from "browser-tabs-lock";
let superTokensLock = new SuperTokensLock()
async function lockingIsFun() {
if (await superTokensLock.acquireLock("hello", 5000)) {
// lock has been acquired... we can do anything we want now.
// ...
await superTokensLock.releaseLock("hello");
} else {
// failed to acquire lock after trying for 5 seconds.
}
}
```
### Usage using callbacks:
```js
import SuperTokensLock from "browser-tabs-lock";
let superTokensLock = new SuperTokensLock()
superTokensLock.acquireLock("hello", 5000).then((success) => {
if (success) {
// lock has been acquired... we can do anything we want now.
// ...
superTokensLock.releaseLock("hello").then(() => {
// lock released, continue
});
} else {
// failed to acquire lock after trying for 5 seconds.
}
});
```
## Installation using plain JS
As of version 1.2.0 of browser-tabs-lock the package can also be used as in plain javascript script.
### Add the script
```html
<script
type="text/javascript"
src="https://cdn.jsdelivr.net/gh/supertokens/browser-tabs-lock@1.2/bundle/bundle.js">
</script>
```
### Creating and using the lock
```js
let lock = new supertokenslock.getNewInstance();
lock.acquireLock("hello")
.then(success => {
if (success) {
// lock has been acquired... we can do anything we want now.
...
lock.releaseLock("hello").then(() => {
// lock released, continue
});
} else {
// failed to acquire lock after trying for 5 seconds.
}
});
```
Also note, that if your web app only needs to work on google chrome, you can use the [Web Locks API](https://developer.mozilla.org/en-US/docs/Web/API/Lock) instead. This probably has true locking!
## Migrating from 1.1x to 1.2x
In some cases, version 1.1x did not entirely ensure mutual exclusion. To explain the problem:
Lets say you create two lock instances L1 and L2. L1 acquires a lock with key K1 and is performing some action that takes 20 seconds to finish.
Immediately after L1 acquires a lock, L2 tries to acquire a lock with the same key(K1). Normally L2 would not be able to acquire the lock until L1 releases it (in this case after 20 seconds) or when the tab that uses L1 is closed abruptly. However it is seen that sometimes L2 is able to acquire the lock automatically after 10 seconds (note that L1 has still not released the lock) - thereby breaking mutual exclusion.
This bug has been fixed and released in version 1.2x of browser-tabs-lock. We highly recommend users to upgrade to 1.2x versions.
After upgrading the only change that requires attention to is that ```lock.releaseLock``` is now an asynchronous function and needs to be handled accordingly.
#### Using async/await
Simply change calls to releaseLock from
```js
lock.releaseLock("hello");
```
to
```js
await lock.releaseLock("hello");
```
#### Using callbacks
Simple change calls to releaseLock from
```js
lock.releaseLock("hello");
```
to
```js
lock.releaseLock("hello")
.then(() => {
// continue
});
```
## Test coverage
In an effort to make this package as production ready as possible we use puppeteer to run browser-tabs-lock in a headless browser environment and perform the following action:
- Create 15 tabs in the browser. Each tab tries to acquire a lock with the same key(K1) and then updates a counter in local storage(C1) as well as updates a counter local to that tab(Ct). The local counter(Ct) serves as a way to know how many times that particular tab has updated local storage counter(C1). This process happens recursively for 20 seconds. After 20 seconds we signal all tabs to stop and after all of them have stopped, we calculate the sum of all the local counter values(sum(Ct...Cn)) for each tab and compare that with the value in local storage(C1). If the two values are the same and the value in local storage matches an estimated value then we know that all tabs use locking in a proper manner.
- Create a tab(T1) which acquires a lock with a key(K1). We then create another tab(T2) that tries to acquire a lock with the same key(K1) and after waiting for some time we verify that the second tab(T2) does not acquire the lock. We close both tabs, note however that tab 1(T1) still had not released the lock. We create another tab(T3) that tries to acquire a lock with the same key(K1) and we verify that the tab is able to acquire the lock. This way we can be sure that locks are released when the tab that holds it(in this case T1) is closed abruptly.
- Create a tab that creates two separate instances of the lock object I1 and I2. I1 acquires a lock with a key(K1), immediately after I2 tries to acquire the lock with the same key(K1). We verify that I2 cannot acquire the lock even after some time has passed. I1 then releases the lock and immediately after I2 tries the acquire it, we verify that I2 can now acquire the lock.
- Create a tab that holds 15 separate lock instances. Each instance tries to acquire the lock using the same key(K1), it then updates a counter(C1) in local storage and also updates a local counter value specific to this instance (Ci). After incrementing the counters the instance recursively repeats this process. We wait for 20 seconds after which we signal each instance to stop and wait for all of them to stop. We then get the counter value from storage(C1) and add all local counter values(sum(Ci....Cn)) and compare the 2 values. We verify that the values are the same and the value in local storage(C1) matches an estimated value. This way we can be sure that in a single tab multiple lock instances using the same key work correctly.
## Support, questions and bugs
For now, we are most reachable via team@supertokens.io and via the GitHub issues feature
## Authors
Created with :heart: by the folks at [SuperTokens](https://supertokens.io). We are a startup passionate about security and solving software challenges in a way that's helpful for everyone! Please feel free to give us feedback at team@supertokens.io, until our website is ready :grinning:

3
node_modules/browser-tabs-lock/bundleEntry.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
import SuperTokensLock from "./index";
declare var getNewInstance: () => SuperTokensLock;
export { getNewInstance };

7
node_modules/browser-tabs-lock/bundleEntry.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var index_1 = require("./index");
var getNewInstance = function () {
return new index_1.default();
};
exports.getNewInstance = getNewInstance;

61
node_modules/browser-tabs-lock/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,61 @@
export declare type StorageHandler = {
key: (index: number) => Promise<string | null>;
getItem: (key: string) => Promise<string | null>;
clear: () => Promise<void>;
removeItem: (key: string) => Promise<void>;
setItem: (key: string, value: string) => Promise<void>;
/**
* Sync versions of the storage functions
*/
keySync: (index: number) => string | null;
getItemSync: (key: string) => string | null;
clearSync: () => void;
removeItemSync: (key: string) => void;
setItemSync: (key: string, value: string) => void;
};
export default class SuperTokensLock {
private static waiters;
private id;
private acquiredIatSet;
private storageHandler;
constructor(storageHandler?: StorageHandler);
/**
* @async
* @memberOf Lock
* @function acquireLock
* @param {string} lockKey - Key for which the lock is being acquired
* @param {number} [timeout=5000] - Maximum time for which the function will wait to acquire the lock
* @returns {Promise<boolean>}
* @description Will return true if lock is being acquired, else false.
* Also the lock can be acquired for maximum 10 secs
*/
acquireLock(lockKey: string, timeout?: number): Promise<boolean>;
private refreshLockWhileAcquired;
private waitForSomethingToChange;
private static addToWaiting;
private static removeFromWaiting;
private static notifyWaiters;
/**
* @function releaseLock
* @memberOf Lock
* @param {string} lockKey - Key for which lock is being released
* @returns {void}
* @description Release a lock.
*/
releaseLock(lockKey: string): Promise<void>;
/**
* @function releaseLock
* @memberOf Lock
* @param {string} lockKey - Key for which lock is being released
* @returns {void}
* @description Release a lock.
*/
private releaseLock__private__;
/**
* @function lockCorrector
* @returns {void}
* @description If a lock is acquired by a tab and the tab is closed before the lock is
* released, this function will release those locks
*/
private static lockCorrector;
}

400
node_modules/browser-tabs-lock/index.js generated vendored Normal file
View File

@@ -0,0 +1,400 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var _this = this;
Object.defineProperty(exports, "__esModule", { value: true });
var processLock_1 = require("./processLock");
/**
* @author: SuperTokens (https://github.com/supertokens)
* This library was created as a part of a larger project, SuperTokens(https://supertokens.io) - the best session management solution.
* You can also check out our other projects on https://github.com/supertokens
*
* To contribute to this package visit https://github.com/supertokens/browser-tabs-lock
* If you face any problems you can file an issue on https://github.com/supertokens/browser-tabs-lock/issues
*
* If you have any questions or if you just want to say hi visit https://supertokens.io/discord
*/
/**
* @constant
* @type {string}
* @default
* @description All the locks taken by this package will have this as prefix
*/
var LOCK_STORAGE_KEY = 'browser-tabs-lock-key';
var DEFAULT_STORAGE_HANDLER = {
key: function (index) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
throw new Error("Unsupported");
});
}); },
getItem: function (key) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
throw new Error("Unsupported");
});
}); },
clear: function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, window.localStorage.clear()];
});
}); },
removeItem: function (key) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
throw new Error("Unsupported");
});
}); },
setItem: function (key, value) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
throw new Error("Unsupported");
});
}); },
keySync: function (index) {
return window.localStorage.key(index);
},
getItemSync: function (key) {
return window.localStorage.getItem(key);
},
clearSync: function () {
return window.localStorage.clear();
},
removeItemSync: function (key) {
return window.localStorage.removeItem(key);
},
setItemSync: function (key, value) {
return window.localStorage.setItem(key, value);
},
};
/**
* @function delay
* @param {number} milliseconds - How long the delay should be in terms of milliseconds
* @returns {Promise<void>}
*/
function delay(milliseconds) {
return new Promise(function (resolve) { return setTimeout(resolve, milliseconds); });
}
/**
* @function generateRandomString
* @params {number} length - How long the random string should be
* @returns {string}
* @description returns random string whose length is equal to the length passed as parameter
*/
function generateRandomString(length) {
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
var randomstring = '';
for (var i = 0; i < length; i++) {
var INDEX = Math.floor(Math.random() * CHARS.length);
randomstring += CHARS[INDEX];
}
return randomstring;
}
/**
* @function getLockId
* @returns {string}
* @description Generates an id which will be unique for the browser tab
*/
function getLockId() {
return Date.now().toString() + generateRandomString(15);
}
var SuperTokensLock = /** @class */ (function () {
function SuperTokensLock(storageHandler) {
this.acquiredIatSet = new Set();
this.storageHandler = undefined;
this.id = getLockId();
this.acquireLock = this.acquireLock.bind(this);
this.releaseLock = this.releaseLock.bind(this);
this.releaseLock__private__ = this.releaseLock__private__.bind(this);
this.waitForSomethingToChange = this.waitForSomethingToChange.bind(this);
this.refreshLockWhileAcquired = this.refreshLockWhileAcquired.bind(this);
this.storageHandler = storageHandler;
if (SuperTokensLock.waiters === undefined) {
SuperTokensLock.waiters = [];
}
}
/**
* @async
* @memberOf Lock
* @function acquireLock
* @param {string} lockKey - Key for which the lock is being acquired
* @param {number} [timeout=5000] - Maximum time for which the function will wait to acquire the lock
* @returns {Promise<boolean>}
* @description Will return true if lock is being acquired, else false.
* Also the lock can be acquired for maximum 10 secs
*/
SuperTokensLock.prototype.acquireLock = function (lockKey, timeout) {
if (timeout === void 0) { timeout = 5000; }
return __awaiter(this, void 0, void 0, function () {
var iat, MAX_TIME, STORAGE_KEY, STORAGE, lockObj, TIMEOUT_KEY, lockObjPostDelay, parsedLockObjPostDelay;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
iat = Date.now() + generateRandomString(4);
MAX_TIME = Date.now() + timeout;
STORAGE_KEY = LOCK_STORAGE_KEY + "-" + lockKey;
STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
_a.label = 1;
case 1:
if (!(Date.now() < MAX_TIME)) return [3 /*break*/, 8];
return [4 /*yield*/, delay(30)];
case 2:
_a.sent();
lockObj = STORAGE.getItemSync(STORAGE_KEY);
if (!(lockObj === null)) return [3 /*break*/, 5];
TIMEOUT_KEY = this.id + "-" + lockKey + "-" + iat;
// there is a problem if setItem happens at the exact same time for 2 different processes.. so we add some random delay here.
return [4 /*yield*/, delay(Math.floor(Math.random() * 25))];
case 3:
// there is a problem if setItem happens at the exact same time for 2 different processes.. so we add some random delay here.
_a.sent();
STORAGE.setItemSync(STORAGE_KEY, JSON.stringify({
id: this.id,
iat: iat,
timeoutKey: TIMEOUT_KEY,
timeAcquired: Date.now(),
timeRefreshed: Date.now()
}));
return [4 /*yield*/, delay(30)];
case 4:
_a.sent(); // this is to prevent race conditions. This time must be more than the time it takes for storage.setItem
lockObjPostDelay = STORAGE.getItemSync(STORAGE_KEY);
if (lockObjPostDelay !== null) {
parsedLockObjPostDelay = JSON.parse(lockObjPostDelay);
if (parsedLockObjPostDelay.id === this.id && parsedLockObjPostDelay.iat === iat) {
this.acquiredIatSet.add(iat);
this.refreshLockWhileAcquired(STORAGE_KEY, iat);
return [2 /*return*/, true];
}
}
return [3 /*break*/, 7];
case 5:
SuperTokensLock.lockCorrector(this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler);
return [4 /*yield*/, this.waitForSomethingToChange(MAX_TIME)];
case 6:
_a.sent();
_a.label = 7;
case 7:
iat = Date.now() + generateRandomString(4);
return [3 /*break*/, 1];
case 8: return [2 /*return*/, false];
}
});
});
};
SuperTokensLock.prototype.refreshLockWhileAcquired = function (storageKey, iat) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
var STORAGE, lockObj, parsedLockObj;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, processLock_1.default().lock(iat)];
case 1:
_a.sent();
if (!this.acquiredIatSet.has(iat)) {
processLock_1.default().unlock(iat);
return [2 /*return*/];
}
STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
lockObj = STORAGE.getItemSync(storageKey);
if (lockObj !== null) {
parsedLockObj = JSON.parse(lockObj);
parsedLockObj.timeRefreshed = Date.now();
STORAGE.setItemSync(storageKey, JSON.stringify(parsedLockObj));
processLock_1.default().unlock(iat);
}
else {
processLock_1.default().unlock(iat);
return [2 /*return*/];
}
this.refreshLockWhileAcquired(storageKey, iat);
return [2 /*return*/];
}
});
}); }, 1000);
return [2 /*return*/];
});
});
};
SuperTokensLock.prototype.waitForSomethingToChange = function (MAX_TIME) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, new Promise(function (resolve) {
var resolvedCalled = false;
var startedAt = Date.now();
var MIN_TIME_TO_WAIT = 50; // ms
var removedListeners = false;
function stopWaiting() {
if (!removedListeners) {
window.removeEventListener('storage', stopWaiting);
SuperTokensLock.removeFromWaiting(stopWaiting);
clearTimeout(timeOutId);
removedListeners = true;
}
if (!resolvedCalled) {
resolvedCalled = true;
var timeToWait = MIN_TIME_TO_WAIT - (Date.now() - startedAt);
if (timeToWait > 0) {
setTimeout(resolve, timeToWait);
}
else {
resolve(null);
}
}
}
window.addEventListener('storage', stopWaiting);
SuperTokensLock.addToWaiting(stopWaiting);
var timeOutId = setTimeout(stopWaiting, Math.max(0, MAX_TIME - Date.now()));
})];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
SuperTokensLock.addToWaiting = function (func) {
this.removeFromWaiting(func);
if (SuperTokensLock.waiters === undefined) {
return;
}
SuperTokensLock.waiters.push(func);
};
SuperTokensLock.removeFromWaiting = function (func) {
if (SuperTokensLock.waiters === undefined) {
return;
}
SuperTokensLock.waiters = SuperTokensLock.waiters.filter(function (i) { return i !== func; });
};
SuperTokensLock.notifyWaiters = function () {
if (SuperTokensLock.waiters === undefined) {
return;
}
var waiters = SuperTokensLock.waiters.slice(); // so that if Lock.waiters is changed it's ok.
waiters.forEach(function (i) { return i(); });
};
/**
* @function releaseLock
* @memberOf Lock
* @param {string} lockKey - Key for which lock is being released
* @returns {void}
* @description Release a lock.
*/
SuperTokensLock.prototype.releaseLock = function (lockKey) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.releaseLock__private__(lockKey)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* @function releaseLock
* @memberOf Lock
* @param {string} lockKey - Key for which lock is being released
* @returns {void}
* @description Release a lock.
*/
SuperTokensLock.prototype.releaseLock__private__ = function (lockKey) {
return __awaiter(this, void 0, void 0, function () {
var STORAGE, STORAGE_KEY, lockObj, parsedlockObj;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
STORAGE_KEY = LOCK_STORAGE_KEY + "-" + lockKey;
lockObj = STORAGE.getItemSync(STORAGE_KEY);
if (lockObj === null) {
return [2 /*return*/];
}
parsedlockObj = JSON.parse(lockObj);
if (!(parsedlockObj.id === this.id)) return [3 /*break*/, 2];
return [4 /*yield*/, processLock_1.default().lock(parsedlockObj.iat)];
case 1:
_a.sent();
this.acquiredIatSet.delete(parsedlockObj.iat);
STORAGE.removeItemSync(STORAGE_KEY);
processLock_1.default().unlock(parsedlockObj.iat);
SuperTokensLock.notifyWaiters();
_a.label = 2;
case 2: return [2 /*return*/];
}
});
});
};
/**
* @function lockCorrector
* @returns {void}
* @description If a lock is acquired by a tab and the tab is closed before the lock is
* released, this function will release those locks
*/
SuperTokensLock.lockCorrector = function (storageHandler) {
var MIN_ALLOWED_TIME = Date.now() - 5000;
var STORAGE = storageHandler;
var KEYS = [];
var currIndex = 0;
while (true) {
var key = STORAGE.keySync(currIndex);
if (key === null) {
break;
}
KEYS.push(key);
currIndex++;
}
var notifyWaiters = false;
for (var i = 0; i < KEYS.length; i++) {
var LOCK_KEY = KEYS[i];
if (LOCK_KEY.includes(LOCK_STORAGE_KEY)) {
var lockObj = STORAGE.getItemSync(LOCK_KEY);
if (lockObj !== null) {
var parsedlockObj = JSON.parse(lockObj);
if ((parsedlockObj.timeRefreshed === undefined && parsedlockObj.timeAcquired < MIN_ALLOWED_TIME) ||
(parsedlockObj.timeRefreshed !== undefined && parsedlockObj.timeRefreshed < MIN_ALLOWED_TIME)) {
STORAGE.removeItemSync(LOCK_KEY);
notifyWaiters = true;
}
}
}
}
if (notifyWaiters) {
SuperTokensLock.notifyWaiters();
}
};
SuperTokensLock.waiters = undefined;
return SuperTokensLock;
}());
exports.default = SuperTokensLock;

52
node_modules/browser-tabs-lock/package.json generated vendored Normal file
View File

@@ -0,0 +1,52 @@
{
"name": "browser-tabs-lock",
"version": "1.3.0",
"description": "provides locking mechanism to sync across browser tabs",
"main": "index.js",
"scripts": {
"pack-test": "npm run pack && npx mocha --timeout 40000 --exit",
"pack": "rm -f ./bundle/* && ./node_modules/.bin/webpack -p",
"build": "npx tsc -p tsconfig.json",
"test": "npx mocha --timeout 40000 --exit",
"postinstall": "node scripts/postinstall.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/supertokens/browser-tabs-lock.git"
},
"devDependencies": {
"puppeteer": "2.0.0",
"typescript": "3.5.2",
"mocha": "6.1.4",
"mocha-jsdom": "2.0.0",
"webpack": "^4.35.0",
"webpack-cli": "^3.3.5"
},
"dependencies": {
"lodash": ">=4.17.21"
},
"keywords": [
"browser",
"tabs",
"browser sync",
"tabs synchronization",
"locks",
"tabs lock",
"locking in browser",
"chrome",
"firefox",
"IE",
"safari"
],
"contributors": [
"bhumilsarvaiya",
"rishabhpoddar",
"nkshah2",
"supertokens"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/supertokens/browser-tabs-lock/issues"
},
"homepage": "https://github.com/supertokens/browser-tabs-lock#readme"
}

11
node_modules/browser-tabs-lock/processLock.d.ts generated vendored Normal file
View File

@@ -0,0 +1,11 @@
declare class ProcessLocking {
static instance: undefined | ProcessLocking;
private locked;
static getInstance(): ProcessLocking;
private addToLocked;
isLocked: (key: string) => boolean;
lock: (key: string) => Promise<void>;
unlock: (key: string) => void;
}
export default function getLock(): ProcessLocking;
export {};

62
node_modules/browser-tabs-lock/processLock.js generated vendored Normal file
View File

@@ -0,0 +1,62 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ProcessLocking = /** @class */ (function () {
function ProcessLocking() {
var _this = this;
this.locked = new Map();
this.addToLocked = function (key, toAdd) {
var callbacks = _this.locked.get(key);
if (callbacks === undefined) {
if (toAdd === undefined) {
_this.locked.set(key, []);
}
else {
_this.locked.set(key, [toAdd]);
}
}
else {
if (toAdd !== undefined) {
callbacks.unshift(toAdd);
_this.locked.set(key, callbacks);
}
}
};
this.isLocked = function (key) {
return _this.locked.has(key);
};
this.lock = function (key) {
return new Promise(function (resolve, reject) {
if (_this.isLocked(key)) {
_this.addToLocked(key, resolve);
}
else {
_this.addToLocked(key);
resolve();
}
});
};
this.unlock = function (key) {
var callbacks = _this.locked.get(key);
if (callbacks === undefined || callbacks.length === 0) {
_this.locked.delete(key);
return;
}
var toCall = callbacks.pop();
_this.locked.set(key, callbacks);
if (toCall !== undefined) {
setTimeout(toCall, 0);
}
};
}
ProcessLocking.getInstance = function () {
if (ProcessLocking.instance === undefined) {
ProcessLocking.instance = new ProcessLocking();
}
return ProcessLocking.instance;
};
return ProcessLocking;
}());
function getLock() {
return ProcessLocking.getInstance();
}
exports.default = getLock;

View File

@@ -0,0 +1,5 @@
let message = '\u001B[93mThank you for using browser-tabs-lock (\u001B[34m https://github.com/supertokens/browser-tabs-lock \u001B[93m).\n\n' +
'\u001B[93mThis library was created as a part of a larger project, SuperTokens(\u001B[34m https://supertokens.io \u001B[93m) - an open source auth solution.\u001B[0m\n' +
'\u001B[93mYou can also check out our other projects on \u001B[34mhttps://github.com/supertokens\u001B[93m\n\u001B[0m';
console.log(message);