elf-sync-state-yomo 1.0.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.
package/README.md ADDED
@@ -0,0 +1,93 @@
1
+ # Sync State
2
+
3
+ [![npm](https://img.shields.io/npm/v/elf-sync-state?logo=npm&style=flat-square)](https://www.npmjs.com/package/elf-sync-state) [![GitHub](https://img.shields.io/github/license/ricardojbarrios/elf-sync-state?style=flat-square)](https://github.com/RicardoJBarrios/elf-sync-state/blob/main/LICENSE.md) [![GitHub Repo stars](https://img.shields.io/github/stars/ricardojbarrios/elf-sync-state?logo=github&style=flat-square)](https://github.com/RicardoJBarrios/elf-sync-state)
4
+
5
+ > Syncs elf store state across tabs
6
+
7
+ The `syncState()` function gives you the ability to synchronize an [elf store](https://ngneat.github.io/elf/) state across multiple tabs, windows or iframes using the [Broadcast Channel API](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API).
8
+
9
+ First, you need to install the package via npm:
10
+
11
+ ```bash
12
+ npm i elf-sync-state
13
+ ```
14
+
15
+ To use it you should call the `syncState()` function passing the store:
16
+
17
+ ```ts
18
+ import { createStore, withProps } from '@ngneat/elf';
19
+ import { syncState } from 'elf-sync-state';
20
+
21
+ interface AuthProps {
22
+ user: { id: string } | null;
23
+ token: string | null;
24
+ }
25
+
26
+ const authStore = createStore(
27
+ { name: 'auth' },
28
+ withProps<AuthProps>({ user: null, token: null })
29
+ );
30
+
31
+ syncState(authStore);
32
+ ```
33
+
34
+ As the second parameter you can pass an optional `Options` object, which can be used to define the following:
35
+
36
+ - `channel`: the name of the channel (by default - the store name plus a `@store` suffix).
37
+ - `source`: a function that receives the store and return what to sync from it. The default is `(store) => store`.
38
+ - `preUpdate`: a function to map the event message and get the data. The default is `(event) => event.data`.
39
+ - `runGuard`: a function that returns whether the actual implementation should be run. The default is `() => typeof window !== 'undefined' && typeof window.BroadcastChannel !== 'undefined'`.
40
+
41
+ ```ts
42
+ import { syncState } from 'elf-sync-state';
43
+ import { authStore } from './auth.store';
44
+
45
+ syncState(authStore, { channel: 'auth-channel' });
46
+ ```
47
+
48
+ The sync state also returns the [`BroadcastChannel`](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel) object created or `undefined` if the `runGuard` function returns `false`.
49
+
50
+ ```ts
51
+ import { syncState } from 'elf-sync-state';
52
+ import { authStore } from './auth.store';
53
+
54
+ const channel: BroadcastChannel | undefined = syncState(authStore);
55
+ ```
56
+
57
+ ## Sync a subset of the state
58
+
59
+ The `includeKeys()` operator can be used to sync a subset of the state:
60
+
61
+ ```ts
62
+ import { includeKeys, syncState } from 'elf-sync-state';
63
+ import { authStore } from './auth.store';
64
+
65
+ syncState(authStore, {
66
+ source: (store) => store.pipe(includeKeys(['user'])),
67
+ });
68
+ ```
69
+
70
+ ## Pre Update interceptor
71
+
72
+ The `preUpdate` option can be used to intercept the [`MessageEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent)
73
+ and modify the data to be synchronized taking into account other properties of the event.
74
+
75
+ ```ts
76
+ import { includeKeys, syncState } from 'elf-sync-state';
77
+ import { authStore } from './auth.store';
78
+
79
+ syncState(authStore, {
80
+ preUpdate: (event) => {
81
+ console.log(event);
82
+ return event.origin === '' ? undefined : event.data;
83
+ },
84
+ });
85
+ ```
86
+
87
+ ## Integration with Elf :mage_woman:
88
+
89
+ The use of this library has been tested together with other Elf libraries, such as [elf-entities](https://ngneat.github.io/elf/docs/features/entities/entities), [elf-persist-state](https://ngneat.github.io/elf/docs/features/persist-state) or [elf-state-history](https://ngneat.github.io/elf/docs/features/history). I have also tried to be consistent with their programming style and documentation to help with integration.
90
+
91
+ [Here](https://stackblitz.com/edit/angular-elf-sync-state?devToolsHeight=33&file=src/app/todo.repository.ts) you can see an example of using all of these in an Angular application. Just open the result in two different tabs to see the library in action.
92
+
93
+ > :warning: There may be a desync due to hot reload
package/index.cjs ADDED
@@ -0,0 +1,22 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('rxjs'), require('rxjs/operators'), require('lodash-es'), require('@yomo/presencejs')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'rxjs', 'rxjs/operators', 'lodash-es', '@yomo/presencejs'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ElfSyncState = {}, global.Rx, global.Rx, global["lodash-es"], global.Presence));
5
+ })(this, (function (exports, rxjs, operators, lodashEs, Presence) { 'use strict';
6
+
7
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
+
9
+ var Presence__default = /*#__PURE__*/_interopDefaultLegacy(Presence);
10
+
11
+ function includeKeys(a){return rxjs.pipe(operators.map(b=>Object.keys(b).reduce((c,d)=>(a.includes(d)&&(c[d]=b[d]),c),{})))}
12
+
13
+ function syncState(a,b){const c={channel:`${a.name}@store`,source:a=>a.asObservable(),preUpdate:a=>a.data,runGuard:()=>"undefined"!=typeof window&&"undefined"!=typeof window.BroadcastChannel},d=Object.assign(Object.assign({},c),b);if(!d.runGuard())return;const e=new BroadcastChannel(d.channel);let f=!0;const g=new Presence__default["default"]("https://prsc.yomo.dev",{auth:{// Certification Type
14
+ type:"token",// Api for getting access token
15
+ endpoint:"https://ae59-159-146-14-53.ngrok.io/api/presence-auth"}});return g.on("connected",()=>{console.log("Connected to server: ",g.host);}),e.addEventListener("message",b=>{const c=d.preUpdate(b);f=!1,a.update(a=>Object.assign(Object.assign({},a),c));}),d.source(a).pipe(rxjs.skip(1),rxjs.distinctUntilChanged(lodashEs.isEqual),rxjs.tap(a=>{f?e.postMessage(a):f=!0;}),rxjs.finalize(()=>e.close())).subscribe(),e}
16
+
17
+ exports.includeKeys = includeKeys;
18
+ exports.syncState = syncState;
19
+
20
+ Object.defineProperty(exports, '__esModule', { value: true });
21
+
22
+ }));
package/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { includeKeys } from './lib/include-keys';
2
+ export { syncState } from './lib/sync-state';
package/index.js ADDED
@@ -0,0 +1,12 @@
1
+ import { pipe, skip, distinctUntilChanged, tap, finalize } from 'rxjs';
2
+ import { map } from 'rxjs/operators';
3
+ import { isEqual } from 'lodash-es';
4
+ import Presence from '@yomo/presencejs';
5
+
6
+ function includeKeys(a){return pipe(map(b=>Object.keys(b).reduce((c,d)=>(a.includes(d)&&(c[d]=b[d]),c),{})))}
7
+
8
+ function syncState(a,b){const c={channel:`${a.name}@store`,source:a=>a.asObservable(),preUpdate:a=>a.data,runGuard:()=>"undefined"!=typeof window&&"undefined"!=typeof window.BroadcastChannel},d=Object.assign(Object.assign({},c),b);if(!d.runGuard())return;const e=new BroadcastChannel(d.channel);let f=!0;const g=new Presence("https://prsc.yomo.dev",{auth:{// Certification Type
9
+ type:"token",// Api for getting access token
10
+ endpoint:"https://ae59-159-146-14-53.ngrok.io/api/presence-auth"}});return g.on("connected",()=>{console.log("Connected to server: ",g.host);}),e.addEventListener("message",b=>{const c=d.preUpdate(b);f=!1,a.update(a=>Object.assign(Object.assign({},a),c));}),d.source(a).pipe(skip(1),distinctUntilChanged(isEqual),tap(a=>{f?e.postMessage(a):f=!0;}),finalize(()=>e.close())).subscribe(),e}
11
+
12
+ export { includeKeys, syncState };
@@ -0,0 +1,3 @@
1
+ import { Store, StoreValue } from '@ngneat/elf';
2
+ import { OperatorFunction } from 'rxjs';
3
+ export declare function includeKeys<S extends Store, State extends StoreValue<S>>(keys: Array<keyof State>): OperatorFunction<State, Partial<State>>;
@@ -0,0 +1,10 @@
1
+ import { Store, StoreValue } from '@ngneat/elf';
2
+ import { Observable } from 'rxjs';
3
+ interface Options<S extends Store> {
4
+ channel?: string;
5
+ source?: (store: S) => Observable<Partial<StoreValue<S>>>;
6
+ preUpdate?: (event: MessageEvent<Partial<StoreValue<S>>>) => Partial<StoreValue<S>>;
7
+ runGuard?: () => boolean;
8
+ }
9
+ export declare function syncState<S extends Store>(store: S, options?: Options<S>): BroadcastChannel | undefined;
10
+ export {};
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "elf-sync-state-yomo",
3
+ "version": "1.0.0",
4
+ "description": "Syncs elf store state across tabs",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "bugs": {
9
+ "url": "https://github.com/RicardoJBarrios/elf-sync-state/issues"
10
+ },
11
+ "homepage": "https://github.com/RicardoJBarrios/elf-sync-state/blob/main/README.md",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/RicardoJBarrios/elf-sync-state"
15
+ },
16
+ "keywords": [
17
+ "javascript",
18
+ "state-management",
19
+ "elf",
20
+ "broadcastchannel",
21
+ "sync-state"
22
+ ],
23
+ "dependencies": {
24
+ "lodash-es": ">= 4.0.0"
25
+ },
26
+ "peerDependencies": {
27
+ "@ngneat/elf": ">= 1.3.0",
28
+ "rxjs": ">= 7.0.0",
29
+ "@yomo/presencejs": "^1.0.0-alpha.4"
30
+ },
31
+ "sideEffects": false,
32
+ "license": "MIT",
33
+ "module": "./index.js",
34
+ "main": "./index.cjs",
35
+ "type": "module",
36
+ "types": "./index.d.ts",
37
+ "exports": {
38
+ ".": {
39
+ "types": "./index.d.ts",
40
+ "import": "./index.js",
41
+ "require": "./index.cjs"
42
+ }
43
+ }
44
+ }