effector-storage 6.0.1 → 6.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,6 +17,7 @@ Small module for [Effector](https://github.com/effector/effector) ☄️ to sync
17
17
  - [with `localStorage`](#with-localstorage)
18
18
  - [with `sessionStorage`](#with-sessionstorage)
19
19
  - [with query string](#with-query-string)
20
+ - [with `BroadcastChannel`](#with-broadcastchannel)
20
21
  - [with React Native AsyncStorage](#with-react-native-asyncstorage)
21
22
  - [with React Native EncryptedStorage](#with-react-native-encryptedstorage)
22
23
  - [extra adapters](#extra-adapters)
@@ -105,12 +106,19 @@ persist({ store: $id, key: 'id' })
105
106
 
106
107
  If two (or more) stores are persisted in query string with the same key — they are synced between themselves.
107
108
 
108
- ⚠️ **Note**<br>
109
- Use this only with plain string stores (`Store<string | null>`) to avoid strange unexpected behavior.
109
+ ### with `BroadcastChannel`
110
+
111
+ Docs: [effector-storage/broadcast](https://github.com/yumauri/effector-storage/tree/main/src/broadcast/README.md)
112
+
113
+ You can sync stores across different browsing contexts (tabs, windows, workers), just import `persist` from `'effector-storage/broadcast'`:
114
+
115
+ ```javascript
116
+ import { persist } from 'effector-storage/broadcast'
117
+ ```
110
118
 
111
119
  ### with React Native AsyncStorage
112
120
 
113
- ❗️ Will be deprecated in next minor release and removed in next major release, in favor of [`@effector-storage/react-native-async-storage`](https://github.com/yumauri/effector-storage-extras/tree/main/packages/react-native-async-storage).
121
+ ❗️ Deprecated and will be removed in next major release, in favor of [`@effector-storage/react-native-async-storage`](https://github.com/yumauri/effector-storage-extras/tree/main/packages/react-native-async-storage).
114
122
 
115
123
  Docs: [effector-storage/rn/async](https://github.com/yumauri/effector-storage/tree/main/src/rn/async/README.md)
116
124
 
@@ -128,7 +136,7 @@ persist({ store: $counter })
128
136
 
129
137
  ### with React Native EncryptedStorage
130
138
 
131
- ❗️ Will be deprecated in next minor release and removed in next major release, in favor of [`@effector-storage/react-native-encrypted-storage`](https://github.com/yumauri/effector-storage-extras/tree/main/packages/react-native-encrypted-storage).
139
+ ❗️ Deprecated and will be removed in next major release, in favor of [`@effector-storage/react-native-encrypted-storage`](https://github.com/yumauri/effector-storage-extras/tree/main/packages/react-native-encrypted-storage).
132
140
 
133
141
  Docs: [effector-storage/rn/encrypted](https://github.com/yumauri/effector-storage/tree/main/src/rn/encrypted/README.md)
134
142
 
@@ -180,7 +188,7 @@ In order to synchronize _something_, you need to specify effector units. Dependi
180
188
 
181
189
  - `store` ([_Store_]): Store to synchronize with local/session storage.
182
190
  - `source` ([_Event_] | [_Effect_] | [_Store_]): Source unit, which updates will be sent to local/session storage.
183
- - `target` ([_Event_] | [_Effect_] | [_Store_]): Target unit, which will receive updates from local/session storage (as well as initial value). Must be different than `source` to avoid circular updates — `source` updates are forwarded directly to `target`.
191
+ - `target` ([_Event_] | [_Effect_] | [_Store_]): Target unit, which will receive updates from local/session storage (as well as initial value). Must be different than `source` to avoid circular updates — `source` updates are passed directly to `target`.
184
192
 
185
193
  ### Options
186
194
 
@@ -425,7 +433,7 @@ If your storage can be updated from _external source_, and doesn't have any even
425
433
  You can use optional `pickup` parameter to specify unit to trigger update (keep in mind, that when you add `pickup`, `persist` _will not_ get initial value from storage automatically):
426
434
 
427
435
  ```javascript
428
- import { createEvent, createStore, forward } from 'effector'
436
+ import { createEvent, createStore } from 'effector'
429
437
  import { persist } from 'effector-storage/session'
430
438
 
431
439
  // event, which will be used to trigger update
@@ -444,7 +452,7 @@ pickup()
444
452
  Another option, if you have your own adapter, you can add this feature right into it:
445
453
 
446
454
  ```javascript
447
- import { createEvent, createStore, forward } from 'effector'
455
+ import { createEvent, createStore } from 'effector'
448
456
  import { persist } from 'effector-storage'
449
457
 
450
458
  // event, which will be used in adapter to react to
@@ -562,9 +570,10 @@ Use this approach with caution, beware of infinite circular updates. To avoid th
562
570
  - [x] [localStorage] support (docs: [effector-storage/local](https://github.com/yumauri/effector-storage/tree/main/src/local/README.md))
563
571
  - [x] [sessionStorage] support (docs: [effector-storage/session](https://github.com/yumauri/effector-storage/tree/main/src/session/README.md))
564
572
  - [x] [query string](https://developer.mozilla.org/en-US/docs/Web/API/Location/search) support (docs: [effector-storage/query](https://github.com/yumauri/effector-storage/tree/main/src/query/README.md))
565
- - [x] [AsyncStorage] support (docs: [effector-storage/rn/async](https://github.com/yumauri/effector-storage/tree/main/src/rn/async/README.md))
566
- - [x] [EncryptedStorage] support (docs: [effector-storage/rn/encrypted](https://github.com/yumauri/effector-storage/tree/main/src/rn/encrypted/README.md))
567
- - [ ] [IndexedDB] support
573
+ - [x] [BroadcastChannel] support (docs: [effector-storage/broadcast](https://github.com/yumauri/effector-storage/tree/main/src/broadcast/README.md))
574
+ - [x] [AsyncStorage] support (extras: [@effector-storage/react-native-async-storage](https://github.com/yumauri/effector-storage-extras/tree/main/packages/react-native-async-storage))
575
+ - [x] [EncryptedStorage] support (extras: [@effector-storage/react-native-encrypted-storage](https://github.com/yumauri/effector-storage-extras/tree/main/packages/react-native-encrypted-storage))
576
+ - [x] [IndexedDB] support (extras: [@effector-storage/idb-keyval](https://github.com/yumauri/effector-storage-extras/tree/main/packages/idb-keyval))
568
577
  - [ ] [Cookies] support
569
578
  - [ ] you name it support
570
579
 
@@ -578,6 +587,7 @@ Use this approach with caution, beware of infinite circular updates. To avoid th
578
587
  [sessionstorage]: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
579
588
  [`'storage'`]: https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent
580
589
  [indexeddb]: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
590
+ [broadcastchannel]: https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel
581
591
  [asyncstorage]: https://react-native-async-storage.github.io/async-storage/
582
592
  [encryptedstorage]: https://github.com/emeraldsanto/react-native-encrypted-storage
583
593
  [cookies]: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
@@ -0,0 +1,2 @@
1
+ "use strict";var e=require("../core/index.cjs"),r=require("../nil/index.cjs"),t=new Map;function a(e){return"undefined"!=typeof BroadcastChannel?function({channel:e="effector-storage"}){var r,a=t.get(e)??(r=new BroadcastChannel(e));r&&t.set(e,r);var s=(e,r)=>(a.addEventListener("message",(({data:t})=>{null==t?r((()=>{throw new Error("Unable to deserialize message")})):t.key===e&&r((()=>t.value))})),a.addEventListener("messageerror",(()=>{r((()=>{throw new Error("Unable to deserialize message")}))})),{get(e){if(e)return e()},set(r){a.postMessage({key:e,value:r})}});return s.keyArea=a,s}({...e}):r.nil({keyArea:"broadcast"})}function s(r){return t=>e.persist({adapter:a,...r,...t})}a.factory=!0;var n=s();exports.broadcast=a,exports.createPersist=s,exports.persist=n;
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1,116 @@
1
+ import { Unit, Store, Event, Effect, Subscription } from 'effector'
2
+
3
+ interface StorageAdapter {
4
+ <State>(key: string, update: (raw?: any) => any): {
5
+ get(raw?: any, ctx?: any): State | Promise<State | undefined> | undefined
6
+ set(value: State, ctx?: any): void
7
+ }
8
+ keyArea?: any
9
+ noop?: boolean
10
+ }
11
+ interface StorageAdapterFactory<AdapterConfig> {
12
+ (config?: AdapterConfig): StorageAdapter
13
+ factory: true
14
+ }
15
+ type Contract<Data> =
16
+ | ((raw: unknown) => raw is Data)
17
+ | {
18
+ isData: (raw: unknown) => raw is Data
19
+ getErrorMessages: (raw: unknown) => string[]
20
+ }
21
+ type Done<State> = {
22
+ key: string
23
+ keyPrefix: string
24
+ operation: 'set' | 'get'
25
+ value: State
26
+ }
27
+ type Fail<Err> = {
28
+ key: string
29
+ keyPrefix: string
30
+ operation: 'set' | 'get'
31
+ error: Err
32
+ value?: any
33
+ }
34
+ type Finally<State, Err> =
35
+ | (Done<State> & {
36
+ status: 'done'
37
+ })
38
+ | (Fail<Err> & {
39
+ status: 'fail'
40
+ })
41
+ interface ConfigPersist$1 {
42
+ pickup?: Unit<any>
43
+ context?: Unit<any>
44
+ keyPrefix?: string
45
+ contract?: Contract<any>
46
+ }
47
+ interface ConfigCommon<State, Err = Error> {
48
+ clock?: Unit<any>
49
+ done?: Unit<Done<State>>
50
+ fail?: Unit<Fail<Err>>
51
+ finally?: Unit<Finally<State, Err>>
52
+ pickup?: Unit<any>
53
+ context?: Unit<any>
54
+ key?: string
55
+ keyPrefix?: string
56
+ contract?: Contract<State | undefined>
57
+ }
58
+ interface ConfigJustStore<State> {
59
+ store: Store<State>
60
+ }
61
+ interface ConfigJustSourceTarget<State> {
62
+ source: Store<State> | Event<State> | Effect<State, any, any>
63
+ target: Store<State> | Event<State> | Effect<State, any, any>
64
+ }
65
+ interface ConfigStore$1<State, Err = Error>
66
+ extends ConfigCommon<State, Err>,
67
+ ConfigJustStore<State> {}
68
+ interface ConfigSourceTarget$1<State, Err = Error>
69
+ extends ConfigCommon<State, Err>,
70
+ ConfigJustSourceTarget<State> {}
71
+
72
+ interface BroadcastConfig {
73
+ channel?: string
74
+ }
75
+
76
+ interface ConfigPersist extends ConfigPersist$1 {}
77
+ interface ConfigStore<State, Err = Error>
78
+ extends BroadcastConfig,
79
+ ConfigStore$1<State, Err> {}
80
+ interface ConfigSourceTarget<State, Err = Error>
81
+ extends BroadcastConfig,
82
+ ConfigSourceTarget$1<State, Err> {}
83
+ interface Persist {
84
+ <State, Err = Error>(config: ConfigSourceTarget<State, Err>): Subscription
85
+ <State, Err = Error>(config: ConfigStore<State, Err>): Subscription
86
+ }
87
+ declare function broadcast(config?: BroadcastConfig): StorageAdapter
88
+ declare namespace broadcast {
89
+ var factory: true
90
+ }
91
+ /**
92
+ * Creates custom partially applied `persist`
93
+ * with predefined BroadcastChannel adapter
94
+ */
95
+ declare function createPersist(defaults?: ConfigPersist): Persist
96
+ /**
97
+ * Default partially applied `persist`
98
+ */
99
+ declare const persist: Persist
100
+
101
+ export {
102
+ BroadcastConfig,
103
+ ConfigPersist,
104
+ ConfigSourceTarget,
105
+ ConfigStore,
106
+ Contract,
107
+ Done,
108
+ Fail,
109
+ Finally,
110
+ Persist,
111
+ StorageAdapter,
112
+ StorageAdapterFactory,
113
+ broadcast,
114
+ createPersist,
115
+ persist,
116
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":["../../src/broadcast/adapter.ts","../../src/broadcast/index.ts"],"sourcesContent":["import type { StorageAdapter } from '../types'\n\nexport interface BroadcastConfig {\n channel?: string\n}\n\n/**\n * BroadcastChannel instances cache\n */\nconst channels = new Map<string, BroadcastChannel>()\n\n/**\n * BroadcastChannel adapter factory\n */\nexport function adapter({\n channel = 'effector-storage',\n}: BroadcastConfig): StorageAdapter {\n let created: BroadcastChannel | undefined\n const bus = channels.get(channel) ?? (created = new BroadcastChannel(channel))\n if (created) channels.set(channel, created)\n\n const adapter: StorageAdapter = <State>(\n key: string,\n update: (raw?: any) => any\n ) => {\n bus.addEventListener('message', ({ data }) => {\n // according to e2e tests, chromium can call `message`\n // instead of `messageerror`, with `null` as message's data\n if (data == null) {\n update(() => {\n throw new Error('Unable to deserialize message')\n })\n } else if (data.key === key) {\n update(() => {\n return data.value\n })\n }\n })\n\n // I know only one case when this event can be fired:\n // if message was sent from page to shared worker, and it contains `SharedArrayBuffer`\n // https://bugs.webkit.org/show_bug.cgi?id=171216\n bus.addEventListener('messageerror', () => {\n update(() => {\n throw new Error('Unable to deserialize message')\n })\n })\n\n return {\n get(box?: () => State | undefined) {\n if (box) return box()\n },\n\n set(value: State) {\n bus.postMessage({ key, value })\n },\n }\n }\n\n adapter.keyArea = bus\n return adapter\n}\n","import type { Subscription } from 'effector'\nimport type {\n ConfigPersist as BaseConfigPersist,\n ConfigStore as BaseConfigStore,\n ConfigSourceTarget as BaseConfigSourceTarget,\n StorageAdapter,\n} from '../types'\nimport type { BroadcastConfig } from './adapter'\nimport { persist as base } from '../core'\nimport { nil } from '../nil'\nimport { adapter } from './adapter'\n\nexport type {\n Contract,\n Done,\n Fail,\n Finally,\n StorageAdapter,\n StorageAdapterFactory,\n} from '../types'\nexport type { BroadcastConfig } from './adapter'\n\nexport interface ConfigPersist extends BaseConfigPersist {}\n\nexport interface ConfigStore<State, Err = Error>\n extends BroadcastConfig,\n BaseConfigStore<State, Err> {}\n\nexport interface ConfigSourceTarget<State, Err = Error>\n extends BroadcastConfig,\n BaseConfigSourceTarget<State, Err> {}\n\nexport interface Persist {\n <State, Err = Error>(config: ConfigSourceTarget<State, Err>): Subscription\n <State, Err = Error>(config: ConfigStore<State, Err>): Subscription\n}\n\n/**\n * Function, checking if `BroadcastChannel` exists and accessible\n */\nfunction supports() {\n return typeof BroadcastChannel !== 'undefined'\n}\n\n/**\n * Creates BroadcastChannel string adapter\n */\nbroadcast.factory = true as const\nexport function broadcast(config?: BroadcastConfig): StorageAdapter {\n return supports()\n ? adapter({\n ...config,\n })\n : nil({ keyArea: 'broadcast' })\n}\n\n/**\n * Creates custom partially applied `persist`\n * with predefined BroadcastChannel adapter\n */\nexport function createPersist(defaults?: ConfigPersist): Persist {\n return (config) =>\n base({\n adapter: broadcast,\n ...defaults,\n ...config,\n })\n}\n\n/**\n * Default partially applied `persist`\n */\nexport const persist = createPersist()\n"],"names":["channels","Map","broadcast","config","BroadcastChannel","channel","created","bus","get","set","adapter","key","update","addEventListener","data","Error","value","box","postMessage","keyArea","nil","createPersist","defaults","base","factory","persist"],"mappings":"8EASMA,EAAW,IAAIC,ICuCd,SAASC,EAAUC,GACxB,MARmC,oBAArBC,iBD3BT,UAAiBC,QACtBA,EAAU,qBAEV,IAAIC,EACEC,EAAMP,EAASQ,IAAIH,KAAaC,EAAU,IAAIF,iBAAiBC,IACjEC,GAASN,EAASS,IAAIJ,EAASC,GAEnC,IAAMI,EAA0BA,CAC9BC,EACAC,KAEAL,EAAIM,iBAAiB,WAAW,EAAGC,WAGrB,MAARA,EACFF,GAAO,KACL,MAAM,IAAIG,MAAM,gCAAgC,IAEzCD,EAAKH,MAAQA,GACtBC,GAAO,IACEE,EAAKE,OAEhB,IAMFT,EAAIM,iBAAiB,gBAAgB,KACnCD,GAAO,KACL,MAAM,IAAIG,MAAM,gCAAgC,GAChD,IAGG,CACLP,IAAIS,GACF,GAAIA,EAAK,OAAOA,GACjB,EAEDR,IAAIO,GACFT,EAAIW,YAAY,CAAEP,MAAKK,SACzB,IAKJ,OADAN,EAAQS,QAAUZ,EACXG,CACT,CCXMA,CAAQ,IACHP,IAELiB,EAAAA,IAAI,CAAED,QAAS,aACrB,CAMO,SAASE,EAAcC,GAC5B,OAAQnB,GACNoB,EAAAA,QAAK,CACHb,QAASR,KACNoB,KACAnB,GAET,CApBAD,EAAUsB,SAAU,EAyBPC,IAAAA,EAAUJ"}
@@ -0,0 +1,116 @@
1
+ import { Unit, Store, Event, Effect, Subscription } from 'effector'
2
+
3
+ interface StorageAdapter {
4
+ <State>(key: string, update: (raw?: any) => any): {
5
+ get(raw?: any, ctx?: any): State | Promise<State | undefined> | undefined
6
+ set(value: State, ctx?: any): void
7
+ }
8
+ keyArea?: any
9
+ noop?: boolean
10
+ }
11
+ interface StorageAdapterFactory<AdapterConfig> {
12
+ (config?: AdapterConfig): StorageAdapter
13
+ factory: true
14
+ }
15
+ type Contract<Data> =
16
+ | ((raw: unknown) => raw is Data)
17
+ | {
18
+ isData: (raw: unknown) => raw is Data
19
+ getErrorMessages: (raw: unknown) => string[]
20
+ }
21
+ type Done<State> = {
22
+ key: string
23
+ keyPrefix: string
24
+ operation: 'set' | 'get'
25
+ value: State
26
+ }
27
+ type Fail<Err> = {
28
+ key: string
29
+ keyPrefix: string
30
+ operation: 'set' | 'get'
31
+ error: Err
32
+ value?: any
33
+ }
34
+ type Finally<State, Err> =
35
+ | (Done<State> & {
36
+ status: 'done'
37
+ })
38
+ | (Fail<Err> & {
39
+ status: 'fail'
40
+ })
41
+ interface ConfigPersist$1 {
42
+ pickup?: Unit<any>
43
+ context?: Unit<any>
44
+ keyPrefix?: string
45
+ contract?: Contract<any>
46
+ }
47
+ interface ConfigCommon<State, Err = Error> {
48
+ clock?: Unit<any>
49
+ done?: Unit<Done<State>>
50
+ fail?: Unit<Fail<Err>>
51
+ finally?: Unit<Finally<State, Err>>
52
+ pickup?: Unit<any>
53
+ context?: Unit<any>
54
+ key?: string
55
+ keyPrefix?: string
56
+ contract?: Contract<State | undefined>
57
+ }
58
+ interface ConfigJustStore<State> {
59
+ store: Store<State>
60
+ }
61
+ interface ConfigJustSourceTarget<State> {
62
+ source: Store<State> | Event<State> | Effect<State, any, any>
63
+ target: Store<State> | Event<State> | Effect<State, any, any>
64
+ }
65
+ interface ConfigStore$1<State, Err = Error>
66
+ extends ConfigCommon<State, Err>,
67
+ ConfigJustStore<State> {}
68
+ interface ConfigSourceTarget$1<State, Err = Error>
69
+ extends ConfigCommon<State, Err>,
70
+ ConfigJustSourceTarget<State> {}
71
+
72
+ interface BroadcastConfig {
73
+ channel?: string
74
+ }
75
+
76
+ interface ConfigPersist extends ConfigPersist$1 {}
77
+ interface ConfigStore<State, Err = Error>
78
+ extends BroadcastConfig,
79
+ ConfigStore$1<State, Err> {}
80
+ interface ConfigSourceTarget<State, Err = Error>
81
+ extends BroadcastConfig,
82
+ ConfigSourceTarget$1<State, Err> {}
83
+ interface Persist {
84
+ <State, Err = Error>(config: ConfigSourceTarget<State, Err>): Subscription
85
+ <State, Err = Error>(config: ConfigStore<State, Err>): Subscription
86
+ }
87
+ declare function broadcast(config?: BroadcastConfig): StorageAdapter
88
+ declare namespace broadcast {
89
+ var factory: true
90
+ }
91
+ /**
92
+ * Creates custom partially applied `persist`
93
+ * with predefined BroadcastChannel adapter
94
+ */
95
+ declare function createPersist(defaults?: ConfigPersist): Persist
96
+ /**
97
+ * Default partially applied `persist`
98
+ */
99
+ declare const persist: Persist
100
+
101
+ export {
102
+ BroadcastConfig,
103
+ ConfigPersist,
104
+ ConfigSourceTarget,
105
+ ConfigStore,
106
+ Contract,
107
+ Done,
108
+ Fail,
109
+ Finally,
110
+ Persist,
111
+ StorageAdapter,
112
+ StorageAdapterFactory,
113
+ broadcast,
114
+ createPersist,
115
+ persist,
116
+ }
@@ -0,0 +1,2 @@
1
+ import{persist as e}from"../core/index.js";import{nil as r}from"../nil/index.js";var a=new Map;function t(e){return"undefined"!=typeof BroadcastChannel?function({channel:e="effector-storage"}){var r,t=a.get(e)??(r=new BroadcastChannel(e));r&&a.set(e,r);var n=(e,r)=>(t.addEventListener("message",(({data:a})=>{null==a?r((()=>{throw new Error("Unable to deserialize message")})):a.key===e&&r((()=>a.value))})),t.addEventListener("messageerror",(()=>{r((()=>{throw new Error("Unable to deserialize message")}))})),{get(e){if(e)return e()},set(r){t.postMessage({key:e,value:r})}});return n.keyArea=t,n}({...e}):r({keyArea:"broadcast"})}function n(r){return a=>e({adapter:t,...r,...a})}t.factory=!0;var s=n();export{t as broadcast,n as createPersist,s as persist};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Flowtype definitions for index
3
+ * Generated by Flowgen from a Typescript Definition
4
+ * Flowgen v1.21.0
5
+ * @flow
6
+ */
7
+
8
+ import { Unit, Store, Event, Effect, Subscription } from 'effector'
9
+ declare interface StorageAdapter {
10
+ <State>(
11
+ key: string,
12
+ update: (raw?: any) => any
13
+ ): {
14
+ get(raw?: any, ctx?: any): State | Promise<State | void> | void,
15
+ set(value: State, ctx?: any): void,
16
+ ...
17
+ };
18
+ keyArea?: any;
19
+ noop?: boolean;
20
+ }
21
+ declare interface StorageAdapterFactory<AdapterConfig> {
22
+ (config?: AdapterConfig): StorageAdapter;
23
+ factory: true;
24
+ }
25
+ declare type Contract<Data> =
26
+ | ((raw: mixed) => boolean)
27
+ | {
28
+ isData: (raw: mixed) => boolean,
29
+ getErrorMessages: (raw: mixed) => string[],
30
+ ...
31
+ }
32
+ declare type Done<State> = {
33
+ key: string,
34
+ keyPrefix: string,
35
+ operation: 'set' | 'get',
36
+ value: State,
37
+ ...
38
+ }
39
+ declare type Fail<Err> = {
40
+ key: string,
41
+ keyPrefix: string,
42
+ operation: 'set' | 'get',
43
+ error: Err,
44
+ value?: any,
45
+ ...
46
+ }
47
+ declare type Finally<State, Err> =
48
+ | {
49
+ ...Done<State>,
50
+ ...{
51
+ status: 'done',
52
+ ...
53
+ },
54
+ }
55
+ | {
56
+ ...Fail<Err>,
57
+ ...{
58
+ status: 'fail',
59
+ ...
60
+ },
61
+ }
62
+ declare interface ConfigPersist$1 {
63
+ pickup?: Unit<any>;
64
+ context?: Unit<any>;
65
+ keyPrefix?: string;
66
+ contract?: Contract<any>;
67
+ }
68
+ declare interface ConfigCommon<State, Err = Error> {
69
+ clock?: Unit<any>;
70
+ done?: Unit<Done<State>>;
71
+ fail?: Unit<Fail<Err>>;
72
+ finally?: Unit<Finally<State, Err>>;
73
+ pickup?: Unit<any>;
74
+ context?: Unit<any>;
75
+ key?: string;
76
+ keyPrefix?: string;
77
+ contract?: Contract<State | void>;
78
+ }
79
+ declare interface ConfigJustStore<State> {
80
+ store: Store<State>;
81
+ }
82
+ declare interface ConfigJustSourceTarget<State> {
83
+ source: Store<State> | Event<State> | Effect<State, any, any>;
84
+ target: Store<State> | Event<State> | Effect<State, any, any>;
85
+ }
86
+ declare type ConfigStore$1<State, Err = Error> = { ... } & ConfigCommon<
87
+ State,
88
+ Err
89
+ > &
90
+ ConfigJustStore<State>
91
+ declare type ConfigSourceTarget$1<State, Err = Error> = { ... } & ConfigCommon<
92
+ State,
93
+ Err
94
+ > &
95
+ ConfigJustSourceTarget<State>
96
+ declare interface BroadcastConfig {
97
+ channel?: string;
98
+ }
99
+ declare type ConfigPersist = { ... } & ConfigPersist$1
100
+ declare type ConfigStore<State, Err = Error> = { ... } & BroadcastConfig &
101
+ ConfigStore$1<State, Err>
102
+ declare type ConfigSourceTarget<State, Err = Error> = {
103
+ ...
104
+ } & BroadcastConfig &
105
+ ConfigSourceTarget$1<State, Err>
106
+ declare interface Persist {
107
+ <State, Err>(config: ConfigSourceTarget<State, Err>): Subscription;
108
+ <State, Err>(config: ConfigStore<State, Err>): Subscription;
109
+ }
110
+ declare var broadcast: typeof npm$namespace$broadcast
111
+
112
+ declare var npm$namespace$broadcast: {|
113
+ (config?: BroadcastConfig): StorageAdapter,
114
+ factory: typeof broadcast$factory,
115
+ |}
116
+ declare var broadcast$factory: true
117
+ declare function createPersist(defaults?: ConfigPersist): Persist
118
+ declare var persist: Persist
119
+ declare export {
120
+ BroadcastConfig,
121
+ ConfigPersist,
122
+ ConfigSourceTarget,
123
+ ConfigStore,
124
+ Contract,
125
+ Done,
126
+ Fail,
127
+ Finally,
128
+ Persist,
129
+ StorageAdapter,
130
+ StorageAdapterFactory,
131
+ broadcast,
132
+ createPersist,
133
+ persist,
134
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../src/broadcast/adapter.ts","../../src/broadcast/index.ts"],"sourcesContent":["import type { StorageAdapter } from '../types'\n\nexport interface BroadcastConfig {\n channel?: string\n}\n\n/**\n * BroadcastChannel instances cache\n */\nconst channels = new Map<string, BroadcastChannel>()\n\n/**\n * BroadcastChannel adapter factory\n */\nexport function adapter({\n channel = 'effector-storage',\n}: BroadcastConfig): StorageAdapter {\n let created: BroadcastChannel | undefined\n const bus = channels.get(channel) ?? (created = new BroadcastChannel(channel))\n if (created) channels.set(channel, created)\n\n const adapter: StorageAdapter = <State>(\n key: string,\n update: (raw?: any) => any\n ) => {\n bus.addEventListener('message', ({ data }) => {\n // according to e2e tests, chromium can call `message`\n // instead of `messageerror`, with `null` as message's data\n if (data == null) {\n update(() => {\n throw new Error('Unable to deserialize message')\n })\n } else if (data.key === key) {\n update(() => {\n return data.value\n })\n }\n })\n\n // I know only one case when this event can be fired:\n // if message was sent from page to shared worker, and it contains `SharedArrayBuffer`\n // https://bugs.webkit.org/show_bug.cgi?id=171216\n bus.addEventListener('messageerror', () => {\n update(() => {\n throw new Error('Unable to deserialize message')\n })\n })\n\n return {\n get(box?: () => State | undefined) {\n if (box) return box()\n },\n\n set(value: State) {\n bus.postMessage({ key, value })\n },\n }\n }\n\n adapter.keyArea = bus\n return adapter\n}\n","import type { Subscription } from 'effector'\nimport type {\n ConfigPersist as BaseConfigPersist,\n ConfigStore as BaseConfigStore,\n ConfigSourceTarget as BaseConfigSourceTarget,\n StorageAdapter,\n} from '../types'\nimport type { BroadcastConfig } from './adapter'\nimport { persist as base } from '../core'\nimport { nil } from '../nil'\nimport { adapter } from './adapter'\n\nexport type {\n Contract,\n Done,\n Fail,\n Finally,\n StorageAdapter,\n StorageAdapterFactory,\n} from '../types'\nexport type { BroadcastConfig } from './adapter'\n\nexport interface ConfigPersist extends BaseConfigPersist {}\n\nexport interface ConfigStore<State, Err = Error>\n extends BroadcastConfig,\n BaseConfigStore<State, Err> {}\n\nexport interface ConfigSourceTarget<State, Err = Error>\n extends BroadcastConfig,\n BaseConfigSourceTarget<State, Err> {}\n\nexport interface Persist {\n <State, Err = Error>(config: ConfigSourceTarget<State, Err>): Subscription\n <State, Err = Error>(config: ConfigStore<State, Err>): Subscription\n}\n\n/**\n * Function, checking if `BroadcastChannel` exists and accessible\n */\nfunction supports() {\n return typeof BroadcastChannel !== 'undefined'\n}\n\n/**\n * Creates BroadcastChannel string adapter\n */\nbroadcast.factory = true as const\nexport function broadcast(config?: BroadcastConfig): StorageAdapter {\n return supports()\n ? adapter({\n ...config,\n })\n : nil({ keyArea: 'broadcast' })\n}\n\n/**\n * Creates custom partially applied `persist`\n * with predefined BroadcastChannel adapter\n */\nexport function createPersist(defaults?: ConfigPersist): Persist {\n return (config) =>\n base({\n adapter: broadcast,\n ...defaults,\n ...config,\n })\n}\n\n/**\n * Default partially applied `persist`\n */\nexport const persist = createPersist()\n"],"names":["channels","Map","broadcast","config","BroadcastChannel","channel","created","bus","get","set","adapter","key","update","addEventListener","data","Error","value","box","postMessage","keyArea","nil","createPersist","defaults","base","factory","persist"],"mappings":"iFASA,IAAMA,EAAW,IAAIC,ICuCd,SAASC,EAAUC,GACxB,MARmC,oBAArBC,iBD3BT,UAAiBC,QACtBA,EAAU,qBAEV,IAAIC,EACEC,EAAMP,EAASQ,IAAIH,KAAaC,EAAU,IAAIF,iBAAiBC,IACjEC,GAASN,EAASS,IAAIJ,EAASC,GAEnC,IAAMI,EAA0BA,CAC9BC,EACAC,KAEAL,EAAIM,iBAAiB,WAAW,EAAGC,WAGrB,MAARA,EACFF,GAAO,KACL,MAAM,IAAIG,MAAM,gCAAgC,IAEzCD,EAAKH,MAAQA,GACtBC,GAAO,IACEE,EAAKE,OAEhB,IAMFT,EAAIM,iBAAiB,gBAAgB,KACnCD,GAAO,KACL,MAAM,IAAIG,MAAM,gCAAgC,GAChD,IAGG,CACLP,IAAIS,GACF,GAAIA,EAAK,OAAOA,GACjB,EAEDR,IAAIO,GACFT,EAAIW,YAAY,CAAEP,MAAKK,SACzB,IAKJ,OADAN,EAAQS,QAAUZ,EACXG,CACT,CCXMA,CAAQ,IACHP,IAELiB,EAAI,CAAED,QAAS,aACrB,CAMO,SAASE,EAAcC,GAC5B,OAAQnB,GACNoB,EAAK,CACHb,QAASR,KACNoB,KACAnB,GAET,CApBAD,EAAUsB,SAAU,EAyBPC,IAAAA,EAAUJ"}
@@ -0,0 +1,8 @@
1
+ {
2
+ "type": "module",
3
+ "sideEffects": false,
4
+ "main": "index.cjs",
5
+ "module": "index.js",
6
+ "react-native": "index.js",
7
+ "types": "index.d.ts"
8
+ }
package/core/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("effector"),r=new Map,t=e=>(r,t)=>e(t,r.ref),o=e.createEvent();o.watch((e=>console.error(e.error))),exports.persist=function(a){var{adapter:i,store:f,source:s=f,target:n=f,clock:d=s,done:c,fail:u=o,finally:l,pickup:p,context:v,key:y,keyPrefix:g="",contract:m}=a;if(!i)throw Error("Adapter is not defined");if(!s)throw Error("Store or source is not defined");if(!n)throw Error("Target is not defined");if(!y&&s.shortName===s.id)throw Error("Key or name is not defined");if(s===n&&!e.is.store(s))throw Error("Source must be different from target");void 0===a.def&&e.is.store(s)&&(a.def=s.defaultState);var k="factory"in i?i(a):i,w=y||s.shortName,h=function(t,o){var a=r.get(t);void 0===a&&(a=new Map,r.set(t,a));var i=a.get(o);return void 0!==i||(i=e.createStore(null,{serialize:"ignore"}),a.set(o,i)),i}(k.keyArea||k,g+w),E=e.createNode(),x=()=>e.clearNode(E),P=e=>({status:r="fail",params:t,result:o,error:a})=>"done"===r?{status:r,key:w,keyPrefix:g,operation:e,value:"get"===e?o:t}:{status:r,key:w,keyPrefix:g,operation:e,value:t,error:a};return e.withRegion(E,(()=>{var r=e.createStore({ref:void 0},{serialize:"ignore"}),o=k(g+w,(e=>D(e))),a=e.attach({source:r,effect:t(o.get)}),i=e.attach({source:r,effect:t(o.set)}),f=e.createEffect((e=>r=>!e||void 0===r||("isData"in e?e.isData(r):e(r))?r:(()=>{throw"getErrorMessages"in e?e.getErrorMessages(r):void 0})())(m)),y=e.createEvent(),E=y.filterMap((({status:e,key:r,keyPrefix:t,operation:o,value:a})=>"done"===e?{key:r,keyPrefix:t,operation:o,value:a}:void 0)),x=y.filterMap((({status:e,key:r,keyPrefix:t,operation:o,error:a,value:i})=>"fail"===e?{key:r,keyPrefix:t,operation:o,error:a,value:i}:void 0)),M=e.createEvent(),D=a;r.updates.watch((()=>{D=(r=>{try{return e.scopeBind(r,{safe:!0})}catch(e){return r}})(a)})),e.sample({source:s,clock:d,target:M}),e.guard({source:e.sample(h,M,((e,r)=>[r,e])),filter:([e,r])=>e!==r,target:i.prepend((([e])=>e))}),e.forward({from:[a.doneData,i],to:h}),e.sample({source:e.merge([a.doneData,h]),target:f}),e.forward({from:f.doneData,to:n}),e.forward({from:[a.finally.map(P("get")),i.finally.map(P("set")),f.fail.map(P("validate"))],to:y}),e.forward({from:x,to:u}),c&&e.forward({from:E,to:c}),l&&e.forward({from:y,to:l}),v&&r.on(v,(({ref:e},r)=>({ref:void 0===r?e:r}))),p?(e.forward({from:p,to:a.prepend((()=>{}))}),r.on(p,(({ref:e},r)=>({ref:void 0===r?e:r})))):a()})),x.unsubscribe=x};
1
+ "use strict";var e=require("effector"),r=new Map,t=e=>([r],t)=>e(t,r),a=e.createEvent();a.watch((e=>console.error(e.error))),exports.persist=function(o){var{adapter:i,store:s,source:c=s,target:n=s,clock:l=c,done:f,fail:d=a,finally:u,pickup:p,context:g,key:k,keyPrefix:v="",contract:y}=o;if(!i)throw Error("Adapter is not defined");if(!c)throw Error("Store or source is not defined");if(!n)throw Error("Target is not defined");if(!k&&c.shortName===c.id)throw Error("Key or name is not defined");if(c===n&&!e.is.store(c))throw Error("Source must be different from target");void 0===o.def&&e.is.store(c)&&(o.def=c.defaultState);var m="factory"in i?i(o):i,h=k||c.shortName,w=function(t,a){var o=r.get(t);void 0===o&&(o=new Map,r.set(t,o));var i=o.get(a);return void 0!==i||(i=e.createStore(null,{serialize:"ignore"}),o.set(a,i)),i}(m.keyArea||m,v+h),E=e.createNode(),x=()=>e.clearNode(E),P=e=>({status:r="fail",params:t,result:a,error:o})=>"done"===r?{status:r,key:h,keyPrefix:v,operation:e,value:"get"===e?a:t}:{status:r,key:h,keyPrefix:v,operation:e,value:"function"==typeof t?void 0:t,error:o};return e.withRegion(E,(()=>{var r=e.createStore([],{serialize:"ignore"}),a=m(v+h,(e=>D(e))),o=e.attach({source:r,effect:t(a.get)}),i=e.attach({source:r,effect:t(a.set)}),s=e.createEffect((e=>r=>!e||void 0===r||("isData"in e?e.isData(r):e(r))?r:(()=>{throw"getErrorMessages"in e?e.getErrorMessages(r):void 0})())(y)),k=e.createEvent(),E=k.filterMap((({status:e,key:r,keyPrefix:t,operation:a,value:o})=>"done"===e?{key:r,keyPrefix:t,operation:a,value:o}:void 0)),x=k.filterMap((({status:e,key:r,keyPrefix:t,operation:a,error:o,value:i})=>"fail"===e?{key:r,keyPrefix:t,operation:a,error:o,value:i}:void 0)),M=e.createEvent(),D=o;r.updates.watch((()=>{D=(r=>{try{return e.scopeBind(r,{safe:!0})}catch(e){return r}})(o)})),e.sample({source:c,clock:l,target:M}),e.guard({source:e.sample(w,M,((e,r)=>[r,e])),filter:([e,r])=>e!==r,target:i.prepend((([e])=>e))}),e.sample({clock:[o.doneData,i],target:w}),e.sample({clock:[o.doneData,w],target:s}),e.sample({clock:s.doneData,target:n}),e.sample({clock:[o.finally.map(P("get")),i.finally.map(P("set")),s.fail.map(P("validate"))],target:k}),u&&e.sample({clock:k,target:u}),f&&e.sample({clock:E,target:f}),e.sample({clock:x,target:d}),g&&r.on(g,(([e],r)=>[void 0===r?e:r])),p?(e.sample({clock:p,fn:()=>{},target:o}),r.on(p,(([e],r)=>[void 0===r?e:r]))):o()})),x.unsubscribe=x};
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../../src/core/area.ts","../../src/core/index.ts"],"sourcesContent":["import type { Store } from 'effector'\nimport { createStore } from 'effector'\n\n/**\n * Keys areas / namespaces cache\n */\nconst areas = new Map<any, Map<string, Store<any>>>()\n\n/**\n * Get store, responsible for the key in key area / namespace\n */\nexport function getAreaStorage<State>(keyArea: any, key: string): Store<State> {\n let area = areas.get(keyArea)\n if (area === undefined) {\n area = new Map()\n areas.set(keyArea, area)\n }\n\n let store = area.get(key)\n if (store !== undefined) {\n return store\n }\n\n store = createStore(null, { serialize: 'ignore' })\n area.set(key, store)\n\n return store\n}\n","import type { Effect, Subscription } from 'effector'\nimport type {\n ConfigAdapter,\n ConfigAdapterFactory,\n ConfigPersist,\n ConfigSourceTarget,\n ConfigStore,\n Contract,\n Done,\n Fail,\n Finally,\n} from '../types'\nimport {\n attach,\n clearNode,\n createEvent,\n createEffect,\n createNode,\n createStore,\n forward,\n guard,\n is,\n merge,\n sample,\n scopeBind,\n withRegion,\n} from 'effector'\nimport { getAreaStorage } from './area'\n\n// helper function to swap two function arguments\n// end extract current context from ref-box\nconst contextual =\n <T, C, R>(fn: (value: T, ctx?: C) => R) =>\n (ctx: { ref?: C }, value: T) =>\n fn(value, ctx.ref)\n\n// helper function to validate data with contract\nconst contracted =\n <T>(contract?: Contract<T>) =>\n (raw: unknown) =>\n !contract || // no contract -> data is valid\n raw === undefined || // `undefined` is always valid\n ('isData' in contract ? contract.isData(raw) : contract(raw))\n ? (raw as T)\n : (() => {\n throw 'getErrorMessages' in contract\n ? contract.getErrorMessages(raw)\n : undefined\n })()\n\n// helper function for safe bind effects to scope\n// since version 22.4.0 there is `safe` option in `scopeBind`,\n// but as long as effector-storage supports 22.0 this helper is required\nconst safeBind = (fx: Effect<any, any, any>) => {\n try {\n // @ts-expect-error due to old typings in import\n return scopeBind(fx, { safe: true })\n } catch (e) {\n return fx\n }\n}\n\n/**\n * Default sink for unhandled errors\n */\nconst sink = createEvent<Fail<any>>()\nsink.watch((payload) => console.error(payload.error))\n\n/**\n * Main `persist` function\n */\nexport function persist<State, Err = Error>(\n config: Partial<\n (ConfigAdapter | ConfigAdapterFactory<any>) &\n ConfigPersist &\n ConfigStore<State, Err> &\n ConfigSourceTarget<State, Err>\n >\n): Subscription {\n const {\n adapter: adapterOrFactory,\n store,\n source = store,\n target = store,\n clock = source,\n done,\n fail = sink,\n finally: anyway,\n pickup,\n context,\n key: keyName,\n keyPrefix = '',\n contract,\n } = config\n\n if (!adapterOrFactory) {\n throw Error('Adapter is not defined')\n }\n if (!source) {\n throw Error('Store or source is not defined')\n }\n if (!target) {\n throw Error('Target is not defined')\n }\n if (!keyName && source.shortName === (source as any).id) {\n throw Error('Key or name is not defined')\n }\n if (source === target && !is.store(source)) {\n throw Error('Source must be different from target')\n }\n\n // get default value from store, if given\n // this is used in adapter factory\n if ((config as any).def === undefined && is.store(source)) {\n ;(config as any).def = source.defaultState\n }\n\n const adapter =\n 'factory' in adapterOrFactory ? adapterOrFactory(config) : adapterOrFactory\n\n const key = keyName || source.shortName\n const storage = getAreaStorage<State>(\n adapter.keyArea || adapter,\n keyPrefix + key\n )\n const region = createNode()\n const desist = () => clearNode(region)\n\n const op =\n (operation: 'get' | 'set' | 'validate') =>\n ({ status = 'fail', params, result, error }: any): any =>\n status === 'done'\n ? {\n status,\n key,\n keyPrefix,\n operation,\n value: operation === 'get' ? result : params,\n }\n : {\n status,\n key,\n keyPrefix,\n operation,\n value: params,\n error,\n }\n\n // create all auxiliary units and nodes within the region,\n // to be able to remove them all at once on unsubscription\n withRegion(region, () => {\n const ctx = createStore<{ ref: any }>(\n { ref: undefined },\n { serialize: 'ignore' }\n )\n\n const value = adapter<State>(keyPrefix + key, (x) => bindedGet(x))\n\n const getFx = attach({\n source: ctx,\n effect: contextual(value.get),\n }) as any as Effect<void, State, Err>\n\n const setFx = attach({\n source: ctx,\n effect: contextual(value.set),\n }) as any as Effect<State, void, Err>\n\n const validateFx = createEffect<unknown, State>(contracted(contract))\n\n const localAnyway = createEvent<Finally<State, Err>>()\n const localDone = localAnyway.filterMap<Done<State>>(\n ({ status, key, keyPrefix, operation, value }) =>\n status === 'done' ? { key, keyPrefix, operation, value } : undefined\n )\n const localFail = localAnyway.filterMap<Fail<Err>>(\n ({ status, key, keyPrefix, operation, error, value }: any) =>\n status === 'fail'\n ? { key, keyPrefix, operation, error, value }\n : undefined\n )\n\n const trigger = createEvent<State>()\n\n let bindedGet: (raw?: any) => any = getFx\n ctx.updates.watch(() => {\n bindedGet = safeBind(getFx)\n })\n\n sample({\n source,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n clock: clock!, // `clock` is always defined, as long as `source` is defined\n target: trigger,\n })\n\n guard({\n source: sample(storage, trigger, (current, proposed) => [\n proposed,\n current,\n ]),\n filter: ([proposed, current]) => proposed !== current,\n target: setFx.prepend(([proposed]: State[]) => proposed),\n })\n forward({ from: [getFx.doneData, setFx], to: storage })\n sample({\n source: merge([getFx.doneData, storage]),\n target: validateFx as any,\n })\n forward({ from: validateFx.doneData, to: target })\n\n forward({\n from: [\n getFx.finally.map(op('get')),\n setFx.finally.map(op('set')),\n validateFx.fail.map(op('validate')),\n ],\n to: localAnyway,\n })\n\n forward({ from: localFail, to: fail })\n if (done) forward({ from: localDone, to: done })\n if (anyway) forward({ from: localAnyway, to: anyway })\n\n if (context) {\n ctx.on(context, ({ ref }, payload) => ({\n ref: payload === undefined ? ref : payload,\n }))\n }\n\n if (pickup) {\n // pick up value from storage ONLY on `pickup` update\n forward({ from: pickup, to: getFx.prepend(() => undefined) })\n ctx.on(pickup, ({ ref }, payload) => ({\n ref: payload === undefined ? ref : payload,\n }))\n } else {\n // kick getter to pick up initial value from storage\n getFx()\n }\n })\n\n return (desist.unsubscribe = desist)\n}\n"],"names":["areas","Map","contextual","fn","ctx","value","ref","sink","createEvent","watch","payload","console","error","config","adapter","adapterOrFactory","store","source","target","clock","done","fail","finally","anyway","pickup","context","key","keyName","keyPrefix","contract","Error","shortName","id","is","undefined","def","defaultState","storage","keyArea","area","get","set","createStore","serialize","getAreaStorage","region","createNode","desist","clearNode","op","operation","status","params","result","withRegion","x","bindedGet","getFx","attach","effect","setFx","validateFx","createEffect","raw","isData","getErrorMessages","contracted","localAnyway","localDone","filterMap","localFail","trigger","updates","fx","scopeBind","safe","e","safeBind","sample","guard","current","proposed","filter","prepend","forward","from","doneData","to","merge","map","on","unsubscribe"],"mappings":"uCAMMA,EAAQ,IAAIC,ICyBZC,EACMC,GACV,CAACC,EAAkBC,IACjBF,EAAGE,EAAOD,EAAIE,KA+BZC,EAAOC,EAAWA,cACxBD,EAAKE,OAAOC,GAAYC,QAAQC,MAAMF,EAAQE,yBAKvC,SACLC,GAOA,IACEC,QAASC,EAAgBC,MACzBA,EAAKC,OACLA,EAASD,EAAKE,OACdA,EAASF,EAAKG,MACdA,EAAQF,EAAMG,KACdA,EAAIC,KACJA,EAAOd,EACPe,QAASC,EAAMC,OACfA,EAAMC,QACNA,EACAC,IAAKC,EAAOC,UACZA,EAAY,GAAEC,SACdA,GACEhB,EAEJ,IAAKE,EACH,MAAMe,MAAM,0BAEd,IAAKb,EACH,MAAMa,MAAM,kCAEd,IAAKZ,EACH,MAAMY,MAAM,yBAEd,IAAKH,GAAWV,EAAOc,YAAed,EAAee,GACnD,MAAMF,MAAM,8BAEd,GAAIb,IAAWC,IAAWe,EAAEA,GAACjB,MAAMC,G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AMgE,EAAAA,QAAQ,CAAEC,KAAMjB,EAAWmB,GAAInE,IACrCG,GAAQ6D,EAAAA,QAAQ,CAAEC,KAAMlB,EAAaoB,GAAIhE,IAEzCE,GACFrB,EAAIsF,GAAGjE,GAAS,EAAGnB,OAAOI,KAAa,CACrCJ,SAAiB4B,IAAZxB,EAAwBJ,EAAMI,MAInCc,GAEF4D,UAAQ,CAAEC,KAAM7D,EAAQ+D,GAAI9B,EAAM0B,SAAQ,KAAe,MACzD/E,EAAIsF,GAAGlE,GAAQ,EAAGlB,OAAOI,KAAa,CACpCJ,SAAiB4B,IAAZxB,EAAwBJ,EAAMI,OAIrC+C,GACF,IAGMV,EAAO4C,YAAc5C,CAC/B"}
1
+ {"version":3,"file":"index.cjs","sources":["../../src/core/area.ts","../../src/core/index.ts"],"sourcesContent":["import type { Store } from 'effector'\nimport { createStore } from 'effector'\n\n/**\n * Keys areas / namespaces cache\n */\nconst areas = new Map<any, Map<string, Store<any>>>()\n\n/**\n * Get store, responsible for the key in key area / namespace\n */\nexport function getAreaStorage<State>(keyArea: any, key: string): Store<State> {\n let area = areas.get(keyArea)\n if (area === undefined) {\n area = new Map()\n areas.set(keyArea, area)\n }\n\n let store = area.get(key)\n if (store !== undefined) {\n return store\n }\n\n store = createStore(null, { serialize: 'ignore' })\n area.set(key, store)\n\n return store\n}\n","import type { Effect, Subscription } from 'effector'\nimport type {\n ConfigAdapter,\n ConfigAdapterFactory,\n ConfigPersist,\n ConfigSourceTarget,\n ConfigStore,\n Contract,\n Done,\n Fail,\n Finally,\n} from '../types'\nimport {\n attach,\n clearNode,\n createEvent,\n createEffect,\n createNode,\n createStore,\n guard,\n is,\n sample,\n scopeBind,\n withRegion,\n} from 'effector'\nimport { getAreaStorage } from './area'\n\n// helper function to swap two function arguments\n// end extract current context from ref-box\nconst contextual =\n <T, C, R>(fn: (value: T, ctx?: C) => R) =>\n ([ref]: [C?], value: T) =>\n fn(value, ref)\n\n// helper function to validate data with contract\nconst contracted =\n <T>(contract?: Contract<T>) =>\n (raw: unknown) =>\n !contract || // no contract -> data is valid\n raw === undefined || // `undefined` is always valid\n ('isData' in contract ? contract.isData(raw) : contract(raw))\n ? (raw as T)\n : (() => {\n throw 'getErrorMessages' in contract\n ? contract.getErrorMessages(raw)\n : undefined\n })()\n\n// helper function for safe bind effects to scope\n// since version 22.4.0 there is `safe` option in `scopeBind`,\n// but as long as effector-storage supports 22.0 this helper is required\nconst safeBind = (fx: Effect<any, any, any>) => {\n try {\n // @ts-expect-error due to old typings in import\n return scopeBind(fx, { safe: true })\n } catch (e) {\n return fx\n }\n}\n\n/**\n * Default sink for unhandled errors\n */\nconst sink = createEvent<Fail<any>>()\nsink.watch((payload) => console.error(payload.error))\n\n/**\n * Main `persist` function\n */\nexport function persist<State, Err = Error>(\n config: Partial<\n (ConfigAdapter | ConfigAdapterFactory<any>) &\n ConfigPersist &\n ConfigStore<State, Err> &\n ConfigSourceTarget<State, Err>\n >\n): Subscription {\n const {\n adapter: adapterOrFactory,\n store,\n source = store,\n target = store,\n clock = source,\n done,\n fail = sink,\n finally: anyway,\n pickup,\n context,\n key: keyName,\n keyPrefix = '',\n contract,\n } = config\n\n if (!adapterOrFactory) {\n throw Error('Adapter is not defined')\n }\n if (!source) {\n throw Error('Store or source is not defined')\n }\n if (!target) {\n throw Error('Target is not defined')\n }\n if (!keyName && source.shortName === (source as any).id) {\n throw Error('Key or name is not defined')\n }\n if (source === target && !is.store(source)) {\n throw Error('Source must be different from target')\n }\n\n // get default value from store, if given\n // this is used in adapter factory\n if ((config as any).def === undefined && is.store(source)) {\n ;(config as any).def = source.defaultState\n }\n\n const adapter =\n 'factory' in adapterOrFactory ? adapterOrFactory(config) : adapterOrFactory\n\n const key = keyName || source.shortName\n const storage = getAreaStorage<State>(\n adapter.keyArea || adapter,\n keyPrefix + key\n )\n const region = createNode()\n const desist = () => clearNode(region)\n\n const op =\n (operation: 'get' | 'set' | 'validate') =>\n ({ status = 'fail', params, result, error }: any): any =>\n status === 'done'\n ? {\n status,\n key,\n keyPrefix,\n operation,\n value: operation === 'get' ? result : params,\n }\n : {\n status,\n key,\n keyPrefix,\n operation,\n value: typeof params === 'function' ? undefined : params, // hide internal \"box\" implementation\n error,\n }\n\n // create all auxiliary units and nodes within the region,\n // to be able to remove them all at once on unsubscription\n withRegion(region, () => {\n const ctx = createStore<[any?]>([], { serialize: 'ignore' })\n\n const value = adapter<State>(keyPrefix + key, (x) => bindedGet(x))\n\n const getFx = attach({\n source: ctx,\n effect: contextual(value.get),\n }) as any as Effect<void, State, Err>\n\n const setFx = attach({\n source: ctx,\n effect: contextual(value.set),\n }) as any as Effect<State, void, Err>\n\n const validateFx = createEffect<unknown, State>(contracted(contract))\n\n const localAnyway = createEvent<Finally<State, Err>>()\n const localDone = localAnyway.filterMap<Done<State>>(\n ({ status, key, keyPrefix, operation, value }) =>\n status === 'done' ? { key, keyPrefix, operation, value } : undefined\n )\n const localFail = localAnyway.filterMap<Fail<Err>>(\n ({ status, key, keyPrefix, operation, error, value }: any) =>\n status === 'fail'\n ? { key, keyPrefix, operation, error, value }\n : undefined\n )\n\n const trigger = createEvent<State>()\n\n let bindedGet: (raw?: any) => any = getFx\n ctx.updates.watch(() => {\n bindedGet = safeBind(getFx)\n })\n\n sample({\n source,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n clock: clock!, // `clock` is always defined, as long as `source` is defined\n target: trigger,\n })\n\n guard({\n source: sample(storage, trigger, (current, proposed) => [\n proposed,\n current,\n ]),\n filter: ([proposed, current]) => proposed !== current,\n target: setFx.prepend(([proposed]: State[]) => proposed),\n })\n sample({ clock: [getFx.doneData, setFx], target: storage as any })\n sample({ clock: [getFx.doneData, storage], target: validateFx as any })\n sample({ clock: validateFx.doneData, target })\n\n sample({\n clock: [\n getFx.finally.map(op('get')),\n setFx.finally.map(op('set')),\n validateFx.fail.map(op('validate')),\n ],\n target: localAnyway,\n })\n\n if (anyway) sample({ clock: localAnyway, target: anyway })\n if (done) sample({ clock: localDone, target: done })\n sample({ clock: localFail, target: fail })\n\n if (context) {\n ctx.on(context, ([ref], payload) => [\n payload === undefined ? ref : payload,\n ])\n }\n\n if (pickup) {\n // pick up value from storage ONLY on `pickup` update\n sample({ clock: pickup, fn: () => undefined, target: getFx })\n ctx.on(pickup, ([ref], payload) => [\n payload === undefined ? ref : payload,\n ])\n } else {\n // kick getter to pick up initial value from storage\n getFx()\n }\n })\n\n return (desist.unsubscribe = desist)\n}\n"],"names":["areas","Map","contextual","fn","ref","value","sink","createEvent","watch","payload","console","error","config","adapter","adapterOrFactory","store","source","target","clock","done","fail","finally","anyway","pickup","context","key","keyName","keyPrefix","contract","Error","shortName","id","is","undefined","def","defaultState","storage","keyArea","area","get","set","createStore","serialize","getAreaStorage","region","createNode","desist","clearNode","op","operation","status","params","result","withRegion","ctx","x","bindedGet","getFx","attach","effect","setFx","validateFx","createEffect","raw","isData","getErrorMessages","contracted","localAnyway","localDone","filterMap","localFail","trigger","updates","fx","scopeBind","safe","e","safeBind","sample","guard","current","proposed","filter","prepend","doneData","map","on","unsubscribe"],"mappings":"uCAMMA,EAAQ,IAAIC,ICuBZC,EACMC,GACV,EAAEC,GAAYC,IACZF,EAAGE,EAAOD,GA+BRE,EAAOC,EAAWA,cACxBD,EAAKE,OAAOC,GAAYC,QAAQC,MAAMF,EAAQE,yBAKvC,SACLC,GAOA,IACEC,QAASC,EAAgBC,MACzBA,EAAKC,OACLA,EAASD,EAAKE,OACdA,EAASF,EAAKG,MACdA,EAAQF,EAAMG,KACdA,EAAIC,KACJA,EAAOd,EACPe,QAASC,EAAMC,OACfA,EAAMC,QACNA,EACAC,IAAKC,EAAOC,UACZA,EAAY,GAAEC,SACdA,GACEhB,EAEJ,IAAKE,EACH,MAAMe,MAAM,0BAEd,IAAKb,EACH,MAAMa,MAAM,kCAEd,IAAKZ,EACH,MAAMY,MAAM,yBAEd,IAAKH,GAAWV,EAAOc,YAAed,EAAee,GACnD,MAAMF,MAAM,8BAEd,GAAIb,IAAW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AOiD,EAAalD,OAAQK,IAC7CH,GAAM2D,EAAAA,OAAO,CAAE5D,MAAOkD,EAAWnD,OAAQE,IAC7C2D,SAAO,CAAE5D,MAAOoD,EAAWrD,OAAQG,IAE/BI,GACF8B,EAAIgC,GAAG9D,GAAS,EAAEpB,GAAMK,IAAY,MACtBwB,IAAZxB,EAAwBL,EAAMK,KAI9Bc,GAEFuD,SAAO,CAAE5D,MAAOK,EAAQpB,GAAIA,KAAe,EAAEc,OAAQwC,IACrDH,EAAIgC,GAAG/D,GAAQ,EAAEnB,GAAMK,IAAY,MACrBwB,IAAZxB,EAAwBL,EAAMK,MAIhCgD,GACF,IAGMX,EAAOyC,YAAczC,CAC/B"}
package/core/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{createStore as e,createEvent as r,is as o,createNode as t,withRegion as a,attach as i,createEffect as f,sample as n,guard as s,forward as d,merge as u,scopeBind as l,clearNode as c}from"effector";var p=new Map,v=e=>(r,o)=>e(o,r.ref),y=r();function k(k){var{adapter:m,store:g,source:h=g,target:w=g,clock:x=h,done:E,fail:P=y,finally:M,pickup:D,context:b,key:S,keyPrefix:z="",contract:A}=k;if(!m)throw Error("Adapter is not defined");if(!h)throw Error("Store or source is not defined");if(!w)throw Error("Target is not defined");if(!S&&h.shortName===h.id)throw Error("Key or name is not defined");if(h===w&&!o.store(h))throw Error("Source must be different from target");void 0===k.def&&o.store(h)&&(k.def=h.defaultState);var N="factory"in m?m(k):m,K=S||h.shortName,T=function(r,o){var t=p.get(r);void 0===t&&(t=new Map,p.set(r,t));var a=t.get(o);return void 0!==a||(a=e(null,{serialize:"ignore"}),t.set(o,a)),a}(N.keyArea||N,z+K),j=t(),q=()=>c(j),B=e=>({status:r="fail",params:o,result:t,error:a})=>"done"===r?{status:r,key:K,keyPrefix:z,operation:e,value:"get"===e?t:o}:{status:r,key:K,keyPrefix:z,operation:e,value:o,error:a};return a(j,(()=>{var o=e({ref:void 0},{serialize:"ignore"}),t=N(z+K,(e=>S(e))),a=i({source:o,effect:v(t.get)}),c=i({source:o,effect:v(t.set)}),p=f((e=>r=>!e||void 0===r||("isData"in e?e.isData(r):e(r))?r:(()=>{throw"getErrorMessages"in e?e.getErrorMessages(r):void 0})())(A)),y=r(),k=y.filterMap((({status:e,key:r,keyPrefix:o,operation:t,value:a})=>"done"===e?{key:r,keyPrefix:o,operation:t,value:a}:void 0)),m=y.filterMap((({status:e,key:r,keyPrefix:o,operation:t,error:a,value:i})=>"fail"===e?{key:r,keyPrefix:o,operation:t,error:a,value:i}:void 0)),g=r(),S=a;o.updates.watch((()=>{S=(e=>{try{return l(e,{safe:!0})}catch(r){return e}})(a)})),n({source:h,clock:x,target:g}),s({source:n(T,g,((e,r)=>[r,e])),filter:([e,r])=>e!==r,target:c.prepend((([e])=>e))}),d({from:[a.doneData,c],to:T}),n({source:u([a.doneData,T]),target:p}),d({from:p.doneData,to:w}),d({from:[a.finally.map(B("get")),c.finally.map(B("set")),p.fail.map(B("validate"))],to:y}),d({from:m,to:P}),E&&d({from:k,to:E}),M&&d({from:y,to:M}),b&&o.on(b,(({ref:e},r)=>({ref:void 0===r?e:r}))),D?(d({from:D,to:a.prepend((()=>{}))}),o.on(D,(({ref:e},r)=>({ref:void 0===r?e:r})))):a()})),q.unsubscribe=q}y.watch((e=>console.error(e.error)));export{k as persist};
1
+ import{createStore as e,createEvent as r,is as t,createNode as o,withRegion as a,attach as i,createEffect as n,sample as s,guard as f,scopeBind as c,clearNode as l}from"effector";var d=new Map,u=e=>([r],t)=>e(t,r),k=r();function g(g){var{adapter:p,store:v,source:y=v,target:h=v,clock:m=y,done:w,fail:x=k,finally:E,pickup:P,context:M,key:D,keyPrefix:b="",contract:S}=g;if(!p)throw Error("Adapter is not defined");if(!y)throw Error("Store or source is not defined");if(!h)throw Error("Target is not defined");if(!D&&y.shortName===y.id)throw Error("Key or name is not defined");if(y===h&&!t.store(y))throw Error("Source must be different from target");void 0===g.def&&t.store(y)&&(g.def=y.defaultState);var z="factory"in p?p(g):p,A=D||y.shortName,N=function(r,t){var o=d.get(r);void 0===o&&(o=new Map,d.set(r,o));var a=o.get(t);return void 0!==a||(a=e(null,{serialize:"ignore"}),o.set(t,a)),a}(z.keyArea||z,b+A),K=o(),T=()=>l(K),j=e=>({status:r="fail",params:t,result:o,error:a})=>"done"===r?{status:r,key:A,keyPrefix:b,operation:e,value:"get"===e?o:t}:{status:r,key:A,keyPrefix:b,operation:e,value:"function"==typeof t?void 0:t,error:a};return a(K,(()=>{var t=e([],{serialize:"ignore"}),o=z(b+A,(e=>D(e))),a=i({source:t,effect:u(o.get)}),l=i({source:t,effect:u(o.set)}),d=n((e=>r=>!e||void 0===r||("isData"in e?e.isData(r):e(r))?r:(()=>{throw"getErrorMessages"in e?e.getErrorMessages(r):void 0})())(S)),k=r(),g=k.filterMap((({status:e,key:r,keyPrefix:t,operation:o,value:a})=>"done"===e?{key:r,keyPrefix:t,operation:o,value:a}:void 0)),p=k.filterMap((({status:e,key:r,keyPrefix:t,operation:o,error:a,value:i})=>"fail"===e?{key:r,keyPrefix:t,operation:o,error:a,value:i}:void 0)),v=r(),D=a;t.updates.watch((()=>{D=(e=>{try{return c(e,{safe:!0})}catch(r){return e}})(a)})),s({source:y,clock:m,target:v}),f({source:s(N,v,((e,r)=>[r,e])),filter:([e,r])=>e!==r,target:l.prepend((([e])=>e))}),s({clock:[a.doneData,l],target:N}),s({clock:[a.doneData,N],target:d}),s({clock:d.doneData,target:h}),s({clock:[a.finally.map(j("get")),l.finally.map(j("set")),d.fail.map(j("validate"))],target:k}),E&&s({clock:k,target:E}),w&&s({clock:g,target:w}),s({clock:p,target:x}),M&&t.on(M,(([e],r)=>[void 0===r?e:r])),P?(s({clock:P,fn:()=>{},target:a}),t.on(P,(([e],r)=>[void 0===r?e:r]))):a()})),T.unsubscribe=T}k.watch((e=>console.error(e.error)));export{g as persist};
2
2
  //# sourceMappingURL=index.js.map