New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

localsync

Package Overview
Dependencies
Maintainers
1
Versions
47
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

localsync - npm Package Compare versions

Comparing version 1.7.2 to 2.0.1

lib/__tests__/localsync.test.d.ts

55

lib/index.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var storagesync_1 = require("./storagesync");
var cookiesync_1 = require("./cookiesync");
var serversync_1 = require("./serversync");
var REGEX = {
TRIDENT_EDGE: /(Trident|Edge)/i
};
/**
* Creates an isomorphic synchronizer to transmit objects to other tabs.
* @param {string} key The key to synchronize on.
* @param {function} action The action to run when trigger is executed. Should return the payload to be transmitted to the handlers on other tabs.
* @param {function} handler The handler which is executed on other tabs when a synchronization is triggered. Argument is the return value of the action.
* @param {boolean} [options.tracing=false] Option to turn on tracing for debugging.
* @param {Object} [options.logger=console] The logger to debug to.
* @param {string} [options.logLevel=info] The log level to trace at.
* @param {number} [options.idLength=8] The number of characters to use for unique instance ID.
* @param {number} [options.pollFrequency=3000] The frequency (in milliseconds) to poll at.
* @param {string} [options.path='/'] The path to store the cookie at.
* @param {boolean} [options.secure=false] Flag to set the cookies secure flag.
* @param {boolean} [options.httpOnly=false] Flag to set the cookies httpOnly flag.
* @return {Object} cookiesync instance with start, stop, trigger, isRunning, isFallback, and instanceID properties.
*/
function localsync(key, action, handler, opts, navigator) {
if (opts === void 0) { opts = {}; }
if (navigator === void 0) { navigator = getNavigator(); }
var sync = navigator === null ? serversync_1.default : isEdgeOrIE(navigator) ? cookiesync_1.default : storagesync_1.default;
var completeOpts = tslib_1.__assign({}, getDefaultOpts(), opts);
return sync(key, action, handler, completeOpts);
}
exports.default = localsync;
function getDefaultOpts() {
return {
tracing: false,
logger: console,
logLevel: "info",
idLength: 8,
pollFrequency: 3000,
path: "/",
secure: false,
httpOnly: false
};
}
function getNavigator() {
return typeof window === "object" && process.env.NODE_ENV !== "test" ? window.navigator : null;
}
function isEdgeOrIE(navigator) {
if (navigator === null)
return false;
return navigator.appName === "Microsoft Internet Explorer" || (navigator.appName === "Netscape" && REGEX.TRIDENT_EDGE.test(navigator.appVersion));
}
const localsyncShim_1 = require("./localsyncShim");
var localsync_1 = require("./localsync");
exports.localsync = localsync_1.localsync;
exports.default = localsyncShim_1.localsyncShim;
//# sourceMappingURL=index.js.map
{
"name": "localsync",
"version": "1.7.2",
"version": "2.0.1",
"description": "a lightweight module to sync JS objects in realtime across tabs / windows of a browser.",
"main": "lib/index.js",
"types": "index.d.ts",
"scripts": {
"start": "npm run build -- --watch",
"prebuild": "rimraf lib",
"build": "tsc --project tsconfig.build.json --rootDir src --outDir lib",
"test": "jest",
"preversion": "npm test"
},
"dependencies": {
"invariant": "^2.2.2",
"local-storage": "^1.4.2",
"tslib": "^1.8.0",
"universal-cookie": "^2.0.0"
},
"devDependencies": {
"@types/invariant": "^2.2.29",
"@types/jest": "^21.1.6",
"@types/node": "^8.0.52",
"@types/sinon": "^4.0.0",
"babel-core": "^6.26.0",
"babel-jest": "^21.2.0",
"babel-preset-env": "^1.6.1",
"cross-env": "^5.1.1",
"jest": "^21.2.1",
"rimraf": "^2.6.2",
"sinon": "^4.1.2",
"ts-jest": "^21.2.2",
"tslint": "^5.8.0",
"typescript": "^2.6.1"
},
"jest": {
"transform": {
"^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"json"
],
"testRegex": "/__tests__/.*\\.test\\.(ts|tsx)$",
"globals": {
"__JEST__": true,
"ts-jest": {
"useBabelrc": true
}
}
},
"repository": {
"type": "git",
"url": "git+https://github.com/noderaider/localsync.git"
},
"files": [
"lib",
"src",
"doc"
],
"keywords": [

@@ -67,8 +20,45 @@ "sync",

],
"scripts": {
"start": "yarn build --watch",
"clean": "rm -rf lib doc tsconfig.tsbuildinfo",
"prebuild": "yarn clean",
"build": "tsc --build",
"test": "jest",
"prerelease": "yarn build && yarn test",
"release": "yarn publish --patch --non-interactive --access public",
"postrelease": "yarn release-gh-pages",
"prerelease-gh-pages": "yarn doc",
"release-gh-pages": "run-s gh-pages-subtree gh-pages-push gh-pages-delete",
"postrelease-gh-pages": "yarn clean-doc",
"predoc": "rm -rf doc",
"doc": "esdoc -c ./esdoc.json && ncp CNAME doc/CNAME",
"gh-pages-subtree": "git subtree split --prefix doc -b gh-pages",
"gh-pages-push": "git push -f origin gh-pages:gh-pages",
"gh-pages-delete": "git branch -D gh-pages"
},
"dependencies": {
"cookiesync": "^2.0.0",
"localsync-core": "^2.0.0",
"serversync": "^2.0.0",
"storagesync": "^2.0.0",
"tslib": "^1.10.0"
},
"devDependencies": {
"@types/jest": "^24.0.16",
"@types/node": "^12.6.9",
"jest": "^24.8.0",
"npm-run-all": "^2.1.1",
"ts-jest": "^24.0.2",
"typescript": "^3.5.3"
},
"author": "Cole Chamberlain <colewc@google.com> (https://github.com/cchamberlain)",
"license": "MIT",
"bugs": {
"url": "https://github.com/noderaider/localsync/issues"
},
"homepage": "http://localsync.js.org"
"homepage": "http://localsync.js.org",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/noderaider/localsync.git"
}
}

@@ -5,44 +5,67 @@ [![NPM](https://raw.githubusercontent.com/noderaider/localsync/master/public/images/localsync.gif)](https://npmjs.com/packages/localsync)

**:exclamation: v1.1.x: Now a modular lerna repo! Synchronization strategies have been split out into separate packages.**
_See [this blog post](https://medium.com/@noderaider/my-battle-with-browser-tabs-5c00ae8e3d2c) for detailed information regarding the issues localsync solves._
*See [my battle with browser tabs](https://medium.com/@noderaider/my-battle-with-browser-tabs-5c00ae8e3d2c) for detailed information regarding the issues localsync solves.*
#### Features
* Uses local storage event emitters to sync objects in realtime across tabs.
* Never calls the tab that the event occurred on.
* Falls back to cookie polling internally if using an unsupported browser (IE 9+ / Edge).
* Isomorphic.
* Tested with mocha.
- Uses local storage event emitters to sync objects in realtime across tabs.
- Never calls the tab that the event occurred on.
- Falls back to cookie polling internally if using an unsupported browser (IE 9+ / Edge).
- Isomorphic.
- Tested with Jest.
- Written with TypeScript.
[![Build Status](https://travis-ci.org/noderaider/localsync.svg?branch=master)](https://travis-ci.org/noderaider/localsync)
[![codecov](https://codecov.io/gh/noderaider/localsync/branch/master/graph/badge.svg)](https://codecov.io/gh/noderaider/localsync)
[![NPM](https://nodei.co/npm/localsync.png?stars=true&downloads=true)](https://nodei.co/npm/localsync/)
## Install
`npm install -S localsync`
`yarn add localsync`
___
OR
`npm install localsync`
---
# Version 2
## How to use
```js
import localsync from 'localsync'
```ts
import { localsync } from "localsync";
/** Create an action that will trigger a sync to other tabs. */
const action = (userID, first, last) => ({ userID, first, last })
/** Create a publisher that optionally transforms some data to a payload to be transmitted to other tabs. */
const publisher = (userID, firstName, lastName) => ({
userID,
firstName,
lastName
});
/** Create a handler that will run on all tabs that did not trigger the sync. */
const handler = (value, old, url) => {
console.info(`Another tab at url ${url} switched user from "${old.first} ${old.last}" to "${value.first} ${value.last}".`)
// do something with value.userID
}
/** Create a subscriber that will receive published payloads on all tabs that did not trigger the sync. */
const subscriber = (current, previous, url) => {
console.info(
`Another tab at url ${url} switched user from "${previous.firstName} ${previous.lastName}" to "${current.firstName} ${current.lastName}".`
);
// do something with `current.userID`
};
/** Create a synchronizer. localsync supports N number of synchronizers for different things across your app. The key 'user' defines a localsync synchronization channel. */
const usersync = localsync('user', action, handler)
/**
* Create a synchronizer channel.
*
* @remarks
* `localsync` supports N number of synchronizers for different things across your app.
* The key 'user' defines a localsync synchronization channel.
*/
const createUserSync = localsync({ channel: "user" });
/**
* Create a controller for the synchronizer.
*
* @remarks
* To create the controller, you must pass the publisher and the subscriber.
*/
const userController = createUserSync(publisher, subscriber);
/**
* Start synchronizing.

@@ -53,56 +76,106 @@ * Passing true tells localsync to poll the current storage mechanism once on

*/
usersync.start(true)
userController.start(true);
/** IE / Edge do not support local storage across multiple tabs. localsync will automatically fallback to a cookie polling mechanism here. You don't need to do anything else. */
if(usersync.isFallback)
console.warn('browser doesnt support local storage synchronization, falling back to cookie synchronization.')
/**
* IE / Edge do not support local storage across multiple tabs.
* localsync will automatically fallback to a cookie polling mechanism here. You don't need to do anything else.
*/
if (userController.isFallback) {
console.warn(
"browser doesnt support local storage synchronization, falling back to cookie synchronization."
);
}
/**
* `isServer` can be used to detect if the current code is running in a server environment (for SSR).
*/
if (userController.isServer) {
console.debug("Detected a SSR environment.");
}
/** Trigger an action that will get handled on other tabs. */
usersync.trigger(1, 'jimmy', 'john')
userController.trigger(1, "jimmy", "john");
console.info(usersync.mechanism) /** => 'storagesync' on chrome, 'cookiesync' on IE */
/** Trigger an action that will get handled on other tabs. */
userController.trigger(1, "jimmy", "john");
console.info(
userController.mechanism
); /** => 'storagesync' on chrome, 'cookiesync' on IE */
setTimeout(() => {
/** Trigger another action in 5 seconds. */
usersync.trigger(2, 'jane', 'wonka')
}, 5000)
userController.trigger(2, "jane", "wonka");
}, 5000);
setTimeout(() => {
/** If its still running, stop syncing in 10 seconds. */
if(usersync.isRunning)
usersync.stop()
}, 10000)
if (userController.isRunning) {
userController.stop();
}
}, 10000);
```
___
### API
## Structure and Roadmap
```ts
const createSync = localsync({ channel: string, level?: LogLevel, fallback?: FallbackOptions })
localsync has a **singular** purpose: to synchronize events from one client to many using a common interface and the least invasive mechanism for the current browsing medium.
const sync = createSync((publisher: (...args) => TMessage, subscriber: (message: TMessage) => void);
Internally, localsync is comprised of several small `sync` packages that all adhere to the common localsync interface. The main localsync package does no actual synchronization on its own but rather determines the most appropriate synchronization strategy and calls upon the necessary packages to invoke it. All the packages with brief descriptions are listed here:
const { start, stop, trigger, isRunning, isFallback } = sync;
```
#### 1.x.x
#### Input
*Guaranteed synchronization between clients of the same browser (Chrome :left_right_arrow: Chrome, IE :left_right_arrow: IE, etc.)*
| **name** | **type** | **default** | **description** |
| ---------- | -------- | ----------- | ------------------------------------------------------------------------ |
| `channel` | `string` | `required` | a string that is used for this synchronization instance. |
| `level` | `string` | `'INFO'` | the log level to use when tracing (`ERROR`, `WARN`, `INFO`, `DEBUG`) |
| `fallback` | `object` | `see below` | optional fallback options if you need more control over cookie fallback. |
* **[localsync](https://npmjs.com/packages/localsync)** - Determines synchronization mechanism and invokes it.
**`FallbackOptions`**
*Mechanism packages*
| **name** | **type** | **default** | **description** |
| --------------- | --------- | ----------- | ----------------------------------------------------------------------------------------- |
| `level` | `string` | `'INFO'` | the log level to use when tracing (`ERROR`, `WARN`, `INFO`, `DEBUG`) |
| `pollFrequency` | `number` | `3000` | `fallback: cookiesync` the number in milliseconds that should be used for cookie polling |
| `path` | `string` | `'/'` | `fallback: cookiesync` The path to use for cookies |
| `secure` | `boolean` | `false` | `fallback: cookiesync` Whether to set the secure flag on cookies or not (not recommended) |
| `httpOnly` | `boolean` | `false` | `fallback: cookiesync` Whether to set the http only flag on cookies or not |
* **[:bullettrain_front: storagesync](https://npmjs.com/packages/storagesync)** - Synchronizes data in a push fashion using local storage `storage` event for a given browser.
* **[:cookie: cookiesync](https://npmjs.com/packages/cookiesync)** - Synchronizes data via cookie polling mechanism for a given browser.
* **[:computer: serversync](https://npmjs.com/packages/serversync)** - Mocks the localsync interface on server environments but does no actual synchronization (for now).
#### Output
#### 2.x.x (In Progress)
_Interface of `localsync` returned controller_
*The primary goal of 2.0 is to enable cross-browser localsync (Chrome :left_right_arrow: IE, Firefox :left_right_arrow: Safari, etc.). The following additional mechanisms are being implemented to make this happen:*
| **name** | **type** | **defaults** | **description** |
| ------------ | ---------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `start` | `function` | `N/A` | Call to start syncing. Accepts one boolean parameter (default false). If passed true, will run the synchronization on start. |
| `stop` | `function` | `N/A` | Call to stop syncing |
| `trigger` | `function` | `N/A` | Call to trigger a sync to occur to all other clients |
| `mechanism` | `string` | `(storage|cookie|server)sync` | The underlying mechanism that was selected for synchronization |
| `isRunning` | `boolean` | `false` | Is synchronization currently enabled |
| `isFallback` | `boolean` | `false` | Is the selected mechanism a fallback strategy |
| `isServer` | `boolean` | `false` | Is the current client running in a server environment |
* **[:rocket: webrtcsync](https://npmjs.com/packages/webrtcsync)** - Synchronizes data across any supporting browser using WebRTC technology.
* **[:airplane: socketsync](https://npmjs.com/packages/socketsync)** - Synchronizes data across any supporting browser using web sockets technology (Fallback for WebRTC).
## Structure and Roadmap
___
localsync has a **singular** purpose: to synchronize events from one client to many using a common interface and the least invasive mechanism for the current browsing medium.
## API
Internally, localsync is comprised of several small `sync` packages that all adhere to the common localsync interface. The main localsync package does no actual synchronization on its own but rather determines the most appropriate synchronization strategy and calls upon the necessary packages to invoke it. All the packages with brief descriptions are listed here:
_Guaranteed synchronization between clients of the same browser (Chrome :left_right_arrow: Chrome, IE :left_right_arrow: IE, etc.)_
- **[localsync](https://npmjs.com/packages/localsync)** - Determines synchronization mechanism and invokes it.
_Mechanism packages_
- **[:bullettrain_front: storagesync](https://npmjs.com/packages/storagesync)** - Synchronizes data in a push fashion using local storage `storage` event for a given browser.
- **[:cookie: cookiesync](https://npmjs.com/packages/cookiesync)** - Synchronizes data via cookie polling mechanism for a given browser.
- **[:computer: serversync](https://npmjs.com/packages/serversync)** - Mocks the localsync interface on server environments but does no actual synchronization (for now).
---
# Version 1 API
```js

@@ -120,34 +193,19 @@ const sync = localsync(key: string, action: (...args) => payload, handler: payload => {}, [opts: Object])

**handler**: a function that will be invoked on this client when any other client's trigger function is invoked. *NOTE: This handler will NEVER be called due to this clients trigger function being called, only other clients.*
**handler**: a function that will be invoked on this client when any other client's trigger function is invoked. _NOTE: This handler will NEVER be called due to this clients trigger function being called, only other clients._
**opts**: An optional object argument that may be specified to control how localsync operates. Supported values are shown below.
**name** | **type** | **default** | **description**
-------- | -------- | ----------- | ---------------
`tracing` | `boolean` | `false` | toggles tracing for debugging purposes
`logger` | `Object` | `console` | the logger object to trace to
`loglevel` | `string` | `'info'` | the log level to use when tracing (`error`, `warn`, `info`, `trace`)
`pollFrequency` | `number` | `3000` | `fallback: cookiesync` the number in milliseconds that should be used for cookie polling
`idLength` | `number` | `8` | `fallback: cookiesync` the number of characters to use for tracking the current instance (tab)
`path` | `string` | `'/'` | `fallback: cookiesync` The path to use for cookies
`secure` | `boolean` | `false` | `fallback: cookiesync` Whether to set the secure flag on cookies or not (not recommended)
`httpOnly` | `boolean` | `false` | `fallback: cookiesync` Whether to set the http only flag on cookies or not
| **name** | **type** | **default** | **description** |
| --------------- | --------- | ----------- | ---------------------------------------------------------------------------------------------- |
| `tracing` | `boolean` | `false` | toggles tracing for debugging purposes |
| `logger` | `Object` | `console` | the logger object to trace to |
| `loglevel` | `string` | `'info'` | the log level to use when tracing (`error`, `warn`, `info`, `trace`) |
| `pollFrequency` | `number` | `3000` | `fallback: cookiesync` the number in milliseconds that should be used for cookie polling |
| `idLength` | `number` | `8` | `fallback: cookiesync` the number of characters to use for tracking the current instance (tab) |
| `path` | `string` | `'/'` | `fallback: cookiesync` The path to use for cookies |
| `secure` | `boolean` | `false` | `fallback: cookiesync` Whether to set the secure flag on cookies or not (not recommended) |
| `httpOnly` | `boolean` | `false` | `fallback: cookiesync` Whether to set the http only flag on cookies or not |
---
#### Output
*Interface of returned localsync object*
**name** | **type** | **defaults** | **description**
-------- | -------- | ----------- | ---------------
`start` | `function` | `N/A` | Call to start syncing. Accepts one boolean parameter (default false). If passed true, will run the synchronization on start.
`stop` | `function` | `N/A` | Call to stop syncing
`trigger` | `function` | `N/A` | Call to trigger a sync to occur to all other clients
`mechanism` | `string` | `(storage|cookie|server)sync` | The underlying mechanism that was selected for synchronization
`isRunning` | `boolean` | `false` | Is synchronization currently enabled
`isFallback` | `boolean` | `false` | Is the selected mechanism a fallback strategy
`isServer` | `boolean` | `false` | Is the current client running in a server environment
___
## Contributing

@@ -158,7 +216,6 @@

```bash
npm i -g lerna@latest
git clone https://github.com/noderaider/localsync
cd localsync
lerna bootstrap
lerna run start
yarn
yarn build
```

@@ -173,5 +230,4 @@

___
---
<sup>Feature requests and pull requests encouraged!</sup>
<sup>Feature / bug fixes via pull requests encouraged!</sup>

@@ -1,72 +0,67 @@

jest.mock("universal-cookie");
import localsync from "..";
const localsyncAny = localsync as any;
const fooBar = { foo: "bar" };
import { localsync } from "../localsync";
import { Controller } from "localsync-core";
describe("localsync", () => {
const mechanisms = [ "storagesync", "cookiesync", "serversync", "socketsync", "webrtcsync" ];
test("should have default function export", () => {
expect(typeof localsync).toBe("function");
});
describe("lib", () => {
describe("localsync", () => {
test("should throw if no args passed", () => expect(() => localsyncAny()).toThrow());
test("should throw if one arg passed", () => expect(() => localsyncAny("key")).toThrow());
test("should throw if two args passed", () => expect(() => localsyncAny("key", () => fooBar)).toThrow());
test("should export an object", () => {
expect(typeof localsync("namesync", () => fooBar, value => {})).toBe("object");
});
describe("adheres to localsync interface", () => {
let controls = null;
beforeEach(() => { controls = localsync("namesync", () => fooBar, value => {}); });
afterEach(() => { controls = null; });
test("should have start property", () => expect(controls.start).toBeTruthy());
test("should have start function", () => expect(typeof controls.start).toBe("function"));
test("should have stop property", () => expect(controls.stop).toBeTruthy());
test("should have stop function", () => expect(typeof controls.stop).toBe("function"));
test("should have trigger property", () => expect(controls.trigger).toBeTruthy());
test("should have trigger function", () => expect(typeof controls.trigger).toBe("function"));
test("should have mechanism property", () => expect(controls.mechanism).toBeTruthy());
test("should have mechanism string", () => expect(typeof controls.mechanism).toBe("string"));
test("should have valid mechanism", () => expect(controls.mechanism).toBeTruthy());
test("should have isRunning property", () => expect(controls.isRunning).toBeDefined());
test("should have isRunning boolean", () => expect(typeof controls.isRunning).toBe("boolean"));
test("should have isFallback property", () => expect(controls.isFallback).toBeDefined());
test("should have isFallback boolean", () => expect(typeof controls.isFallback).toBe("boolean"));
test("should have isServer property", () => expect(controls.isServer).toBeDefined());
test("should have isServer boolean", () => expect(typeof controls.isServer).toBe("boolean"));
});
describe("server environment", function() {
let controls = null;
beforeEach(() => { controls = localsync("namesync", () => fooBar, value => {}); });
afterEach(() => { controls = null; });
test("mechanism should be serversync", () => {
expect(controls.mechanism).toBeTruthy();
expect(controls.mechanism).toBe("serversync");
let controller: Controller | undefined;
beforeEach(() => {
controller = localsync({ channel: "test-channel" })(
() => {
foo: "bar";
},
_value => {}
);
});
test("isServer should be true", () => expect(controls.isServer).toBe(true));
test("isFallback should be false", () => expect(controls.isFallback).toBe(false));
afterEach(() => {
controller = undefined;
});
test("default mechanism should be storagesync", () => {
expect(controller!.mechanism).toBe("storagesync");
});
test("isServer should be false by default", () => {
expect(controller!.isServer).toBe(false);
});
test("isFallback should be false", () => {
expect(controller!.isFallback).toBe(false);
});
});
/*
// TODO: Figure out alternative to rewire with TypeScript support.
describe("modern browser environment", function() {
const navigatorsIE = [ { appName: "Netscape", appVersion: "5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" }
];
const navigatorsIE = [
{
appName: "Netscape",
appVersion:
"5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
}
];
for (let nav of navigatorsIE) {
describe(`navigator ${JSON.stringify(nav)}`, () => {
let undo = null;
let controls = null;
beforeEach(() => {
controls = localsync("namesync", () => fooBar, value => {}, null, nav);
undo = lib.__set__("navigator", nav);
controls = localsync(
"namesync",
() => {
foo: "bar";
},
value => {}
);
});
afterEach(() => {
controls = null;
undo();
});
test("mechanism should be storagesync", () => {
expect(controls.mechanism).toBeTruthy();
expect(controls.mechanism).toBe("storagesync");
});
test("isServer should be false", () => expect(controls.isServer).toBe(false));
test("isFallback should be false", () => expect(controls.isFallback).toBe(false));
test("isServer should be false", () => {
expect(controls.isServer).toBe(false);
});
test("isFallback should be false", () => {
expect(controls.isFallback).toBe(false);
});
});

@@ -77,25 +72,43 @@ }

describe("legacy browser environment", function() {
const navigatorsIE = [ { appName: "Microsoft Internet Explorer" }
, { appName: "Netscape", appVersion: "Trident/7.0" }
, { appName: "Netscape", appVersion: "5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240" }
];
const navigatorsIE = [
{ appName: "Microsoft Internet Explorer" },
{ appName: "Netscape", appVersion: "Trident/7.0" },
{
appName: "Netscape",
appVersion:
"5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240"
}
];
for (let nav of navigatorsIE) {
describe(`navigator ${JSON.stringify(nav)}`, () => {
let undo = null;
let controls = null;
beforeEach(() => {
controls = localsync("namesync", () => fooBar, value => {}, null, nav);
undo = lib.__set__("navigator", nav);
controls = localsync(
"namesync",
() => {
foo: "bar";
},
value => {}
);
});
afterEach(() => {
controls = null;
undo();
});
test("mechanism should be cookiesync", () => {
expect(controls.mechanism).toBeTruthy();
expect(controls.mechanism).toBe("cookiesync");
});
test("isServer should be false", () => expect(controls.isServer).toBe(false));
test("isFallback should be true", () => expect(controls.isFallback).toBe(true));
test("isServer should be false", () => {
expect(controls.isServer).toBe(false);
});
test("isFallback should be true", () => {
expect(controls.isFallback).toBe(true);
});
});
}
});
*/
});
});

@@ -1,51 +0,3 @@

import storagesync from "./storagesync";
import cookiesync from "./cookiesync";
import serversync from "./serversync";
const REGEX = {
TRIDENT_EDGE: /(Trident|Edge)/i
};
/**
* Creates an isomorphic synchronizer to transmit objects to other tabs.
* @param {string} key The key to synchronize on.
* @param {function} action The action to run when trigger is executed. Should return the payload to be transmitted to the handlers on other tabs.
* @param {function} handler The handler which is executed on other tabs when a synchronization is triggered. Argument is the return value of the action.
* @param {boolean} [options.tracing=false] Option to turn on tracing for debugging.
* @param {Object} [options.logger=console] The logger to debug to.
* @param {string} [options.logLevel=info] The log level to trace at.
* @param {number} [options.idLength=8] The number of characters to use for unique instance ID.
* @param {number} [options.pollFrequency=3000] The frequency (in milliseconds) to poll at.
* @param {string} [options.path='/'] The path to store the cookie at.
* @param {boolean} [options.secure=false] Flag to set the cookies secure flag.
* @param {boolean} [options.httpOnly=false] Flag to set the cookies httpOnly flag.
* @return {Object} cookiesync instance with start, stop, trigger, isRunning, isFallback, and instanceID properties.
*/
export default function localsync(key: string, action, handler, opts: Partial<Localsync.Opts> = {}, navigator = getNavigator()) {
const sync = navigator === null ? serversync : isEdgeOrIE(navigator) ? cookiesync : storagesync;
const completeOpts: Localsync.Opts = { ...getDefaultOpts(), ...opts };
return sync(key, action, handler, completeOpts);
}
function getDefaultOpts(): Localsync.Opts {
return {
tracing: false,
logger: console,
logLevel: "info",
idLength: 8,
pollFrequency: 3000,
path: "/",
secure: false,
httpOnly: false
};
}
function getNavigator(): Localsync.LocalsyncNavigator {
return typeof window === "object" && process.env.NODE_ENV !== "test" ? window.navigator : null;
}
function isEdgeOrIE(navigator): boolean {
if (navigator === null)
return false;
return navigator.appName === "Microsoft Internet Explorer" || (navigator.appName === "Netscape" && REGEX.TRIDENT_EDGE.test(navigator.appVersion));
}
import { localsyncShim } from "./localsyncShim";
export { localsync } from "./localsync";
export default localsyncShim;

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc