effector-storage 7.1.0 → 8.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.
Files changed (88) hide show
  1. package/README.md +12 -9
  2. package/async-storage/index.cjs +1 -1
  3. package/async-storage/index.cjs.map +1 -1
  4. package/async-storage/index.d.cts +20 -9
  5. package/async-storage/index.d.ts +20 -9
  6. package/async-storage/index.js +1 -1
  7. package/async-storage/index.js.map +1 -1
  8. package/broadcast/index.cjs +1 -1
  9. package/broadcast/index.cjs.map +1 -1
  10. package/broadcast/index.d.cts +105 -26
  11. package/broadcast/index.d.ts +105 -26
  12. package/broadcast/index.js +1 -1
  13. package/broadcast/index.js.map +1 -1
  14. package/core/index.cjs +1 -1
  15. package/core/index.cjs.map +1 -1
  16. package/core/index.d.cts +99 -21
  17. package/core/index.d.ts +99 -21
  18. package/core/index.js +1 -1
  19. package/core/index.js.map +1 -1
  20. package/core/package.json +3 -0
  21. package/index.cjs +1 -1
  22. package/index.cjs.map +1 -1
  23. package/index.d.cts +101 -22
  24. package/index.d.ts +101 -22
  25. package/index.js +1 -1
  26. package/index.js.map +1 -1
  27. package/local/index.cjs +1 -1
  28. package/local/index.cjs.map +1 -1
  29. package/local/index.d.cts +105 -26
  30. package/local/index.d.ts +105 -26
  31. package/local/index.js +1 -1
  32. package/local/index.js.map +1 -1
  33. package/log/index.cjs +1 -1
  34. package/log/index.cjs.map +1 -1
  35. package/log/index.d.cts +21 -9
  36. package/log/index.d.ts +21 -9
  37. package/log/index.js +1 -1
  38. package/log/index.js.map +1 -1
  39. package/memory/index.cjs +1 -1
  40. package/memory/index.cjs.map +1 -1
  41. package/memory/index.d.cts +105 -26
  42. package/memory/index.d.ts +105 -26
  43. package/memory/index.js +1 -1
  44. package/memory/index.js.map +1 -1
  45. package/nil/index.cjs +1 -1
  46. package/nil/index.cjs.map +1 -1
  47. package/nil/index.d.cts +20 -9
  48. package/nil/index.d.ts +20 -9
  49. package/nil/index.js +1 -1
  50. package/nil/index.js.map +1 -1
  51. package/package.json +3 -3
  52. package/query/index.cjs +1 -1
  53. package/query/index.cjs.map +1 -1
  54. package/query/index.d.cts +105 -26
  55. package/query/index.d.ts +105 -26
  56. package/query/index.js +1 -1
  57. package/query/index.js.map +1 -1
  58. package/session/index.cjs +1 -1
  59. package/session/index.cjs.map +1 -1
  60. package/session/index.d.cts +105 -26
  61. package/session/index.d.ts +105 -26
  62. package/session/index.js +1 -1
  63. package/session/index.js.map +1 -1
  64. package/storage/index.cjs +1 -1
  65. package/storage/index.cjs.map +1 -1
  66. package/storage/index.d.cts +20 -9
  67. package/storage/index.d.ts +20 -9
  68. package/storage/index.js +1 -1
  69. package/storage/index.js.map +1 -1
  70. package/tools/index.cjs +1 -1
  71. package/tools/index.cjs.map +1 -1
  72. package/tools/index.d.cts +18 -9
  73. package/tools/index.d.ts +18 -9
  74. package/tools/index.js +1 -1
  75. package/tools/index.js.map +1 -1
  76. package/tools/package.json +3 -0
  77. package/async-storage/index.js.flow +0 -37
  78. package/broadcast/index.js.flow +0 -132
  79. package/core/index.js.flow +0 -113
  80. package/index.js.flow +0 -146
  81. package/local/index.js.flow +0 -140
  82. package/log/index.js.flow +0 -32
  83. package/memory/index.js.flow +0 -133
  84. package/nil/index.js.flow +0 -31
  85. package/query/index.js.flow +0 -159
  86. package/session/index.js.flow +0 -140
  87. package/storage/index.js.flow +0 -36
  88. package/tools/index.js.flow +0 -104
package/README.md CHANGED
@@ -156,6 +156,9 @@ In order to synchronize _something_, you need to specify effector units. Dependi
156
156
 
157
157
  ### Options
158
158
 
159
+ > [!NOTE]
160
+ > These are common options, valid for any adapter. However, individual storage adapters may define and use their own specific options. Please reference the documentation for your exact adapter for more information.
161
+
159
162
  - `key`? ([_string_]): Key for local/session storage, to store value in. If omitted — `store` name is used. **Note!** If `key` is not specified, `store` _must_ have a `name`! You can use `'effector/babel-plugin'` to have those names automatically.
160
163
  - `keyPrefix`? ([_string_]): Prefix, used in adapter, to be concatenated to `key`. By default = `''`.
161
164
  - `clock`? ([_Event_] | [_Effect_] | [_Store_]): Unit, if passed – then value from `store`/`source` will be stored in the storage only upon its trigger.
@@ -201,7 +204,7 @@ export type Contract<Data> =
201
204
  }
202
205
  ```
203
206
 
204
- So, it could be simple type guard function in trivial use cases, or more complex object with `isData` type guard and `getErrorMessages` function, which returns array of error messages. This format is fully compatible with [Farfetched contracts](https://farfetched.pages.dev/api/primitives/contract.html), so you can use any adapter from Farfetched ([runtypes](https://farfetched.pages.dev/api/contracts/runtypes.html), [zod](https://farfetched.pages.dev/api/contracts/zod.html), [io-ts](https://farfetched.pages.dev/api/contracts/io-ts.html), [superstruct](https://farfetched.pages.dev/api/contracts/superstruct.html), [typed-contracts](https://farfetched.pages.dev/api/contracts/typed-contracts.html)) with `persist` and `contract` option:
207
+ So, it could be simple type guard function in trivial use cases, or more complex object with `isData` type guard and `getErrorMessages` function, which returns array of error messages. This format is fully compatible with [Farfetched contracts](https://withease.effector.dev/protocols/contract.html), so you can use any adapter from Farfetched ([runtypes](https://ff.effector.dev/api/contracts/runtypes.html), [zod](https://ff.effector.dev/api/contracts/zod.html), [io-ts](https://ff.effector.dev/api/contracts/io-ts.html), [superstruct](https://ff.effector.dev/api/contracts/superstruct.html), [typed-contracts](https://ff.effector.dev/api/contracts/typed-contracts.html), [valibot](https://ff.effector.dev/api/contracts/valibot.html)) with `persist` and `contract` option:
205
208
 
206
209
  ```typescript
207
210
  // simple type guard
@@ -214,18 +217,18 @@ persist({
214
217
 
215
218
  ```typescript
216
219
  // complex contract with Farfetched adapter
217
- import { Record, Literal, Number } from 'runtypes'
218
- import { runtypeContract } from '@farfetched/runtypes'
220
+ import * as s from 'superstruct'
221
+ import { superstructContract } from '@farfetched/superstruct'
219
222
 
220
- const Asteroid = Record({
221
- type: Literal('asteroid'),
222
- mass: Number,
223
+ const Asteroid = s.type({
224
+ type: s.literal('asteroid'),
225
+ mass: s.number(),
223
226
  })
224
227
 
225
228
  persist({
226
229
  store: $asteroid,
227
230
  key: 'asteroid',
228
- contract: runtypeContract(Asteroid),
231
+ contract: superstructContract(Asteroid),
229
232
  })
230
233
  ```
231
234
 
@@ -300,8 +303,8 @@ interface StorageAdapter {
300
303
  key: string,
301
304
  update: (raw?: any) => void
302
305
  ): {
303
- get(raw?: any, ctx?: any): State | Promise<State | undefined> | undefined
304
- set(value: State, ctx?: any): void
306
+ get(raw?: any, ctx?: any): State | undefined | Promise<State | undefined>
307
+ set(value: State, ctx?: any): void | Promise<void>
305
308
  }
306
309
  keyArea?: any
307
310
  noop?: boolean
@@ -1,2 +1,2 @@
1
- "use strict";function e({storage:e,serialize:t=JSON.stringify,deserialize:a=JSON.parse}){var r=r=>({async get(){var t=await e().getItem(r);return null===t?void 0:a(t)},async set(a){await e().setItem(r,t(a))}});try{r.keyArea=e()}catch(e){}return r}e.factory=!0,exports.asyncStorage=e;
1
+ "use strict";var e=({storage:e,serialize:t=JSON.stringify,deserialize:a=JSON.parse})=>{var r=r=>({async get(){var t=await e().getItem(r);return null===t?void 0:a(t)},async set(a){await e().setItem(r,t(a))}});try{r.keyArea=e()}catch(e){}return r};e.factory=!0,exports.asyncStorage=e;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../../src/async-storage/index.ts"],"sourcesContent":["import type { StorageAdapter } from '../types'\n\nexport interface AsyncStorage {\n getItem: (key: string) => Promise<string | null>\n setItem: (key: string, value: string) => Promise<void>\n}\n\nexport interface AsyncStorageConfig {\n storage: () => AsyncStorage\n serialize?: (value: any) => string\n deserialize?: (value: string) => any\n}\n\n/**\n * Creates generic `AsyncStorage` adapter\n */\nasyncStorage.factory = true as const\nexport function asyncStorage({\n storage,\n serialize = JSON.stringify,\n deserialize = JSON.parse,\n}: AsyncStorageConfig): StorageAdapter {\n const adapter: StorageAdapter = <State>(key: string) => ({\n async get() {\n const item = await storage().getItem(key)\n return item === null ? undefined : deserialize(item)\n },\n\n async set(value: State) {\n await storage().setItem(key, serialize(value))\n },\n })\n\n try {\n adapter.keyArea = storage()\n } catch (error) {\n // do nothing\n }\n\n return adapter\n}\n"],"names":["asyncStorage","storage","serialize","JSON","stringify","deserialize","parse","adapter","key","get","item","getItem","undefined","set","value","setItem","keyArea","error","factory"],"mappings":"aAiBO,SAASA,GAAaC,QAC3BA,EAAOC,UACPA,EAAYC,KAAKC,UAASC,YAC1BA,EAAcF,KAAKG,QAEnB,IAAMC,EAAkCC,IAAiB,CACvD,SAAMC,GACJ,IAAMC,QAAaT,IAAUU,QAAQH,GACrC,OAAgB,OAATE,OAAgBE,EAAYP,EAAYK,EAChD,EAED,SAAMG,CAAIC,SACFb,IAAUc,QAAQP,EAAKN,EAAUY,GACzC,IAGF,IACEP,EAAQS,QAAUf,GACnB,CAAC,MAAOgB,GACP,CAGF,OAAOV,CACT,CAxBAP,EAAakB,SAAU"}
1
+ {"version":3,"file":"index.cjs","sources":["../../src/async-storage/index.ts"],"sourcesContent":["import type { StorageAdapter, StorageAdapterFactory } from '../types'\n\nexport interface AsyncStorage {\n getItem: (key: string) => Promise<string | null>\n setItem: (key: string, value: string) => Promise<void>\n}\n\nexport interface AsyncStorageConfig {\n storage: () => AsyncStorage\n serialize?: (value: any) => string\n deserialize?: (value: string) => any\n}\n\n/**\n * Creates generic `AsyncStorage` adapter\n */\nexport const asyncStorage: StorageAdapterFactory<AsyncStorageConfig> = ({\n storage,\n serialize = JSON.stringify,\n deserialize = JSON.parse,\n}) => {\n const adapter: StorageAdapter = <State>(key: string) => ({\n async get() {\n const item = await storage().getItem(key)\n return item === null ? undefined : deserialize(item)\n },\n\n async set(value: State) {\n await storage().setItem(key, serialize(value))\n },\n })\n\n try {\n adapter.keyArea = storage()\n } catch (_error) {\n // do nothing\n }\n\n return adapter\n}\n\n// mark as factory\nasyncStorage.factory = true\n"],"names":["asyncStorage","storage","serialize","JSON","stringify","deserialize","parse","adapter","key","get","item","getItem","undefined","set","value","setItem","keyArea","_error","factory"],"mappings":"aAgBO,IAAMA,EAA0DA,EACrEC,UACAC,YAAYC,KAAKC,UACjBC,cAAcF,KAAKG,UAEnB,IAAMC,EAAkCC,IAAW,CACjD,SAAMC,GACJ,IAAMC,QAAaT,IAAUU,QAAQH,GACrC,OAAgB,OAATE,OAAgBE,EAAYP,EAAYK,EACjD,EAEA,SAAMG,CAAIC,SACFb,IAAUc,QAAQP,EAAKN,EAAUY,GACzC,IAGF,IACEP,EAAQS,QAAUf,GACpB,CAAE,MAAOgB,GACP,CAGF,OAAOV,GAITP,EAAakB,SAAU"}
@@ -1,11 +1,21 @@
1
+ interface Adapter<State> {
2
+ get(this: void, //
3
+ raw?: any, ctx?: any): State | undefined | Promise<State | undefined>;
4
+ set(this: void, //
5
+ value: State, ctx?: any): void | Promise<void>;
6
+ }
7
+ interface DisposableAdapter<State> extends Adapter<State> {
8
+ (): void;
9
+ }
1
10
  interface StorageAdapter {
2
- <State>(key: string, update: (raw?: any) => void): {
3
- get(raw?: any, ctx?: any): State | Promise<State | undefined> | undefined;
4
- set(value: State, ctx?: any): void;
5
- };
11
+ <State>(key: string, update: (raw?: any) => void): Adapter<State> | DisposableAdapter<State>;
6
12
  keyArea?: any;
7
13
  noop?: boolean;
8
14
  }
15
+ interface StorageAdapterFactory<AdapterConfig> {
16
+ (config: AdapterConfig): StorageAdapter;
17
+ factory: true;
18
+ }
9
19
 
10
20
  interface AsyncStorage {
11
21
  getItem: (key: string) => Promise<string | null>;
@@ -16,9 +26,10 @@ interface AsyncStorageConfig {
16
26
  serialize?: (value: any) => string;
17
27
  deserialize?: (value: string) => any;
18
28
  }
19
- declare function asyncStorage({ storage, serialize, deserialize, }: AsyncStorageConfig): StorageAdapter;
20
- declare namespace asyncStorage {
21
- var factory: true;
22
- }
29
+ /**
30
+ * Creates generic `AsyncStorage` adapter
31
+ */
32
+ declare const asyncStorage: StorageAdapterFactory<AsyncStorageConfig>;
23
33
 
24
- export { type AsyncStorage, type AsyncStorageConfig, asyncStorage };
34
+ export { asyncStorage };
35
+ export type { AsyncStorage, AsyncStorageConfig };
@@ -1,11 +1,21 @@
1
+ interface Adapter<State> {
2
+ get(this: void, //
3
+ raw?: any, ctx?: any): State | undefined | Promise<State | undefined>;
4
+ set(this: void, //
5
+ value: State, ctx?: any): void | Promise<void>;
6
+ }
7
+ interface DisposableAdapter<State> extends Adapter<State> {
8
+ (): void;
9
+ }
1
10
  interface StorageAdapter {
2
- <State>(key: string, update: (raw?: any) => void): {
3
- get(raw?: any, ctx?: any): State | Promise<State | undefined> | undefined;
4
- set(value: State, ctx?: any): void;
5
- };
11
+ <State>(key: string, update: (raw?: any) => void): Adapter<State> | DisposableAdapter<State>;
6
12
  keyArea?: any;
7
13
  noop?: boolean;
8
14
  }
15
+ interface StorageAdapterFactory<AdapterConfig> {
16
+ (config: AdapterConfig): StorageAdapter;
17
+ factory: true;
18
+ }
9
19
 
10
20
  interface AsyncStorage {
11
21
  getItem: (key: string) => Promise<string | null>;
@@ -16,9 +26,10 @@ interface AsyncStorageConfig {
16
26
  serialize?: (value: any) => string;
17
27
  deserialize?: (value: string) => any;
18
28
  }
19
- declare function asyncStorage({ storage, serialize, deserialize, }: AsyncStorageConfig): StorageAdapter;
20
- declare namespace asyncStorage {
21
- var factory: true;
22
- }
29
+ /**
30
+ * Creates generic `AsyncStorage` adapter
31
+ */
32
+ declare const asyncStorage: StorageAdapterFactory<AsyncStorageConfig>;
23
33
 
24
- export { type AsyncStorage, type AsyncStorageConfig, asyncStorage };
34
+ export { asyncStorage };
35
+ export type { AsyncStorage, AsyncStorageConfig };
@@ -1,2 +1,2 @@
1
- function e({storage:e,serialize:t=JSON.stringify,deserialize:a=JSON.parse}){var r=r=>({async get(){var t=await e().getItem(r);return null===t?void 0:a(t)},async set(a){await e().setItem(r,t(a))}});try{r.keyArea=e()}catch(e){}return r}e.factory=!0;export{e as asyncStorage};
1
+ var e=({storage:e,serialize:a=JSON.stringify,deserialize:r=JSON.parse})=>{var t=t=>({async get(){var a=await e().getItem(t);return null===a?void 0:r(a)},async set(r){await e().setItem(t,a(r))}});try{t.keyArea=e()}catch(e){}return t};e.factory=!0;export{e as asyncStorage};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../src/async-storage/index.ts"],"sourcesContent":["import type { StorageAdapter } from '../types'\n\nexport interface AsyncStorage {\n getItem: (key: string) => Promise<string | null>\n setItem: (key: string, value: string) => Promise<void>\n}\n\nexport interface AsyncStorageConfig {\n storage: () => AsyncStorage\n serialize?: (value: any) => string\n deserialize?: (value: string) => any\n}\n\n/**\n * Creates generic `AsyncStorage` adapter\n */\nasyncStorage.factory = true as const\nexport function asyncStorage({\n storage,\n serialize = JSON.stringify,\n deserialize = JSON.parse,\n}: AsyncStorageConfig): StorageAdapter {\n const adapter: StorageAdapter = <State>(key: string) => ({\n async get() {\n const item = await storage().getItem(key)\n return item === null ? undefined : deserialize(item)\n },\n\n async set(value: State) {\n await storage().setItem(key, serialize(value))\n },\n })\n\n try {\n adapter.keyArea = storage()\n } catch (error) {\n // do nothing\n }\n\n return adapter\n}\n"],"names":["asyncStorage","storage","serialize","JSON","stringify","deserialize","parse","adapter","key","get","item","getItem","undefined","set","value","setItem","keyArea","error","factory"],"mappings":"AAiBO,SAASA,GAAaC,QAC3BA,EAAOC,UACPA,EAAYC,KAAKC,UAASC,YAC1BA,EAAcF,KAAKG,QAEnB,IAAMC,EAAkCC,IAAiB,CACvD,SAAMC,GACJ,IAAMC,QAAaT,IAAUU,QAAQH,GACrC,OAAgB,OAATE,OAAgBE,EAAYP,EAAYK,EAChD,EAED,SAAMG,CAAIC,SACFb,IAAUc,QAAQP,EAAKN,EAAUY,GACzC,IAGF,IACEP,EAAQS,QAAUf,GACnB,CAAC,MAAOgB,GACP,CAGF,OAAOV,CACT,CAxBAP,EAAakB,SAAU"}
1
+ {"version":3,"file":"index.js","sources":["../../src/async-storage/index.ts"],"sourcesContent":["import type { StorageAdapter, StorageAdapterFactory } from '../types'\n\nexport interface AsyncStorage {\n getItem: (key: string) => Promise<string | null>\n setItem: (key: string, value: string) => Promise<void>\n}\n\nexport interface AsyncStorageConfig {\n storage: () => AsyncStorage\n serialize?: (value: any) => string\n deserialize?: (value: string) => any\n}\n\n/**\n * Creates generic `AsyncStorage` adapter\n */\nexport const asyncStorage: StorageAdapterFactory<AsyncStorageConfig> = ({\n storage,\n serialize = JSON.stringify,\n deserialize = JSON.parse,\n}) => {\n const adapter: StorageAdapter = <State>(key: string) => ({\n async get() {\n const item = await storage().getItem(key)\n return item === null ? undefined : deserialize(item)\n },\n\n async set(value: State) {\n await storage().setItem(key, serialize(value))\n },\n })\n\n try {\n adapter.keyArea = storage()\n } catch (_error) {\n // do nothing\n }\n\n return adapter\n}\n\n// mark as factory\nasyncStorage.factory = true\n"],"names":["asyncStorage","storage","serialize","JSON","stringify","deserialize","parse","adapter","key","get","item","getItem","undefined","set","value","setItem","keyArea","_error","factory"],"mappings":"AAgBO,IAAMA,EAA0DA,EACrEC,UACAC,YAAYC,KAAKC,UACjBC,cAAcF,KAAKG,UAEnB,IAAMC,EAAkCC,IAAW,CACjD,SAAMC,GACJ,IAAMC,QAAaT,IAAUU,QAAQH,GACrC,OAAgB,OAATE,OAAgBE,EAAYP,EAAYK,EACjD,EAEA,SAAMG,CAAIC,SACFb,IAAUc,QAAQP,EAAKN,EAAUY,GACzC,IAGF,IACEP,EAAQS,QAAUf,GACpB,CAAE,MAAOgB,GACP,CAGF,OAAOV,GAITP,EAAakB,SAAU"}
@@ -1,2 +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;
1
+ "use strict";var e=require("../core/index.cjs"),r=require("../nil/index.cjs"),s=new Map,a=e=>"undefined"!=typeof BroadcastChannel?(({channel:e="effector-storage"})=>{var r,a=s.get(e)??(r=new BroadcastChannel(e));r&&s.set(e,r);var t=(e,r)=>{var s=({data:s})=>{null==s?r(()=>{throw new Error("Unable to deserialize message")}):s.key===e&&r(()=>s.value)},t=()=>{r(()=>{throw new Error("Unable to deserialize message")})};return a.addEventListener("message",s),a.addEventListener("messageerror",t),Object.assign(()=>{a.removeEventListener("message",s),a.removeEventListener("messageerror",t)},{get(e){if(e)return e()},set(r){a.postMessage({key:e,value:r})}})};return t.keyArea=a,t})({...e}):r.nil({keyArea:"broadcast"});a.factory=!0;var t=r=>s=>e.persist({adapter:a,...r,...s}),n=/*#__PURE__*/t();exports.broadcast=a,exports.createPersist=t,exports.persist=n;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +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) => void\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,GAAAA,CAAIS,GACF,GAAIA,EAAK,OAAOA,GACjB,EAEDR,GAAAA,CAAIO,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"}
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 const 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) => void\n ) => {\n const onmessage = ({ data }: MessageEvent) => {\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 const onmessageerror = () => {\n update(() => {\n throw new Error('Unable to deserialize message')\n })\n }\n\n bus.addEventListener('message', onmessage)\n bus.addEventListener('messageerror', onmessageerror)\n\n const dispose = () => {\n bus.removeEventListener('message', onmessage)\n bus.removeEventListener('messageerror', onmessageerror)\n }\n\n return Object.assign(dispose, {\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 ConfigSourceTarget as BaseConfigSourceTarget,\n ConfigStore as BaseConfigStore,\n StorageAdapterFactory,\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 Adapter,\n Contract,\n DisposableAdapter,\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 */\nconst supports = () => typeof BroadcastChannel !== 'undefined'\n\n/**\n * Creates BroadcastChannel adapter\n */\nexport const broadcast: StorageAdapterFactory<\n BroadcastConfig | undefined | void\n> = (config) => {\n return supports()\n ? adapter({\n ...config,\n })\n : nil({ keyArea: 'broadcast' })\n}\n\n// mark as factory\nbroadcast.factory = true\n\n/**\n * Creates custom partially applied `persist`\n * with predefined BroadcastChannel adapter\n */\nexport const createPersist =\n (defaults?: ConfigPersist): Persist =>\n (config) =>\n base({\n adapter: broadcast,\n ...defaults,\n ...config,\n })\n\n/**\n * Default partially applied `persist`\n */\nexport const persist: Persist = /*#__PURE__*/ createPersist()\n"],"names":["channels","Map","broadcast","config","BroadcastChannel","adapter","channel","created","bus","get","set","key","update","onmessage","data","Error","value","onmessageerror","addEventListener","Object","assign","dispose","removeEventListener","box","postMessage","keyArea","nil","factory","createPersist","defaults","base","persist"],"mappings":"8EASMA,EAAW,IAAIC,ICsCRC,EAERC,GAP8C,oBAArBC,iBD5BPC,GACrBC,UAAU,uBAEV,IAAIC,EACEC,EAAMR,EAASS,IAAIH,KAAaC,EAAU,IAAIH,iBAAiBE,IACjEC,GAASP,EAASU,IAAIJ,EAASC,GAEnC,IAAMF,EAA0BA,CAC9BM,EACAC,KAEA,IAAMC,EAAYA,EAAGC,WAGP,MAARA,EACFF,EAAO,KACL,MAAM,IAAIG,MAAM,mCAETD,EAAKH,MAAQA,GACtBC,EAAO,IACEE,EAAKE,QAQZC,EAAiBA,KACrBL,EAAO,KACL,MAAM,IAAIG,MAAM,oCAYpB,OARAP,EAAIU,iBAAiB,UAAWL,GAChCL,EAAIU,iBAAiB,eAAgBD,GAO9BE,OAAOC,OALEC,KACdb,EAAIc,oBAAoB,UAAWT,GACnCL,EAAIc,oBAAoB,eAAgBL,IAGZ,CAC5BR,GAAAA,CAAIc,GACF,GAAIA,EAAK,OAAOA,GAClB,EAEAb,GAAAA,CAAIM,GACFR,EAAIgB,YAAY,CAAEb,MAAKK,SACzB,KAKJ,OADAX,EAAQoB,QAAUjB,EACXH,GCjBHA,CAAQ,IACHF,IAELuB,EAAAA,IAAI,CAAED,QAAS,cAIrBvB,EAAUyB,SAAU,EAMb,IAAMC,EACVC,GACA1B,GACC2B,UAAK,CACHzB,QAASH,KACN2B,KACA1B,IAMI4B,eAAiCH"}
@@ -1,21 +1,97 @@
1
- import { Unit, Store, Event, Effect, Subscription } from 'effector';
1
+ import { Unit, UnitTargetable, Store, Event, Effect, StoreWritable, EventCallable, Subscription } from 'effector';
2
2
 
3
+ /** The Contract interface. */
4
+ interface Contract$1<Raw, Data extends Raw> {
5
+ /**
6
+ * Checks if Raw is Data
7
+ */
8
+ isData: (prepared: Raw) => prepared is Data;
9
+ /**
10
+ * - empty array is dedicated for valid response
11
+ * - array of string with validation erorrs for invalidDataError
12
+ */
13
+ getErrorMessages: (prepared: Raw) => string[];
14
+ }
15
+
16
+ /** The Standard Schema interface. */
17
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
18
+ /** The Standard Schema properties. */
19
+ readonly '~standard': StandardSchemaV1.Props<Input, Output>;
20
+ }
21
+ declare namespace StandardSchemaV1 {
22
+ /** The Standard Schema properties interface. */
23
+ interface Props<Input = unknown, Output = Input> {
24
+ /** The version number of the standard. */
25
+ readonly version: 1;
26
+ /** The vendor name of the schema library. */
27
+ readonly vendor: string;
28
+ /** Validates unknown input values. */
29
+ readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result<Output> | Promise<Result<Output>>;
30
+ /** Inferred types associated with the schema. */
31
+ readonly types?: Types<Input, Output> | undefined;
32
+ }
33
+ /** The result interface of the validate function. */
34
+ type Result<Output> = SuccessResult<Output> | FailureResult;
35
+ /** The result interface if validation succeeds. */
36
+ interface SuccessResult<Output> {
37
+ /** The typed output value. */
38
+ readonly value: Output;
39
+ /** A falsy value for `issues` indicates success. */
40
+ readonly issues?: undefined;
41
+ }
42
+ interface Options {
43
+ /** Explicit support for additional vendor-specific parameters, if needed. */
44
+ readonly libraryOptions?: Record<string, unknown> | undefined;
45
+ }
46
+ /** The result interface if validation fails. */
47
+ interface FailureResult {
48
+ /** The issues of failed validation. */
49
+ readonly issues: ReadonlyArray<Issue>;
50
+ }
51
+ /** The issue interface of the failure output. */
52
+ interface Issue {
53
+ /** The error message of the issue. */
54
+ readonly message: string;
55
+ /** The path of the issue, if any. */
56
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
57
+ }
58
+ /** The path segment interface of the issue. */
59
+ interface PathSegment {
60
+ /** The key representing a path segment. */
61
+ readonly key: PropertyKey;
62
+ }
63
+ /** The Standard Schema types interface. */
64
+ interface Types<Input = unknown, Output = Input> {
65
+ /** The input type of the schema. */
66
+ readonly input: Input;
67
+ /** The output type of the schema. */
68
+ readonly output: Output;
69
+ }
70
+ /** Infers the input type of a Standard Schema. */
71
+ type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];
72
+ /** Infers the output type of a Standard Schema. */
73
+ type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
74
+ }
75
+
76
+ interface Adapter<State> {
77
+ get(this: void, //
78
+ raw?: any, ctx?: any): State | undefined | Promise<State | undefined>;
79
+ set(this: void, //
80
+ value: State, ctx?: any): void | Promise<void>;
81
+ }
82
+ interface DisposableAdapter<State> extends Adapter<State> {
83
+ (): void;
84
+ }
3
85
  interface StorageAdapter {
4
- <State>(key: string, update: (raw?: any) => void): {
5
- get(raw?: any, ctx?: any): State | Promise<State | undefined> | undefined;
6
- set(value: State, ctx?: any): void;
7
- };
86
+ <State>(key: string, update: (raw?: any) => void): Adapter<State> | DisposableAdapter<State>;
8
87
  keyArea?: any;
9
88
  noop?: boolean;
10
89
  }
11
90
  interface StorageAdapterFactory<AdapterConfig> {
12
- (config?: AdapterConfig): StorageAdapter;
91
+ (config: AdapterConfig): StorageAdapter;
13
92
  factory: true;
14
93
  }
15
- type Contract<Data> = ((raw: unknown) => raw is Data) | {
16
- isData: (raw: unknown) => raw is Data;
17
- getErrorMessages: (raw: unknown) => string[];
18
- };
94
+ type Contract<Data> = ((raw: unknown) => raw is Data) | StandardSchemaV1<unknown, Data> | Contract$1<unknown, Data>;
19
95
  type Done<State> = {
20
96
  key: string;
21
97
  keyPrefix: string;
@@ -29,34 +105,36 @@ type Fail<Err> = {
29
105
  error: Err;
30
106
  value?: any;
31
107
  };
32
- type Finally<State, Err> = (Done<State> & {
108
+ type FinallyDone<State> = Done<State> & {
33
109
  status: 'done';
34
- }) | (Fail<Err> & {
110
+ };
111
+ type FinallyFail<Err> = Fail<Err> & {
35
112
  status: 'fail';
36
- });
113
+ };
114
+ type Finally<State, Err> = FinallyDone<State> | FinallyFail<Err>;
37
115
  interface ConfigPersist$1 {
38
- pickup?: Unit<any>;
116
+ pickup?: Unit<any> | Unit<any>[];
39
117
  context?: Unit<any>;
40
118
  keyPrefix?: string;
41
119
  contract?: Contract<any>;
42
120
  }
43
121
  interface ConfigCommon<State, Err = Error> {
44
122
  clock?: Unit<any>;
45
- done?: Unit<Done<State>>;
46
- fail?: Unit<Fail<Err>>;
47
- finally?: Unit<Finally<State, Err>>;
48
- pickup?: Unit<any>;
123
+ done?: UnitTargetable<Done<State>>;
124
+ fail?: UnitTargetable<Fail<Err>>;
125
+ finally?: UnitTargetable<Finally<State, Err>>;
126
+ pickup?: Unit<any> | Unit<any>[];
49
127
  context?: Unit<any>;
50
128
  key?: string;
51
129
  keyPrefix?: string;
52
130
  contract?: Contract<State | undefined>;
53
131
  }
54
132
  interface ConfigJustStore<State> {
55
- store: Store<State>;
133
+ store: StoreWritable<State>;
56
134
  }
57
135
  interface ConfigJustSourceTarget<State> {
58
136
  source: Store<State> | Event<State> | Effect<State, any, any>;
59
- target: Store<State> | Event<State> | Effect<State, any, any>;
137
+ target: StoreWritable<State> | EventCallable<State> | Effect<State, any, any>;
60
138
  }
61
139
  interface ConfigStore$1<State, Err = Error> extends ConfigCommon<State, Err>, ConfigJustStore<State> {
62
140
  }
@@ -77,18 +155,19 @@ interface Persist {
77
155
  <State, Err = Error>(config: ConfigSourceTarget<State, Err>): Subscription;
78
156
  <State, Err = Error>(config: ConfigStore<State, Err>): Subscription;
79
157
  }
80
- declare function broadcast(config?: BroadcastConfig): StorageAdapter;
81
- declare namespace broadcast {
82
- var factory: true;
83
- }
158
+ /**
159
+ * Creates BroadcastChannel adapter
160
+ */
161
+ declare const broadcast: StorageAdapterFactory<BroadcastConfig | undefined | void>;
84
162
  /**
85
163
  * Creates custom partially applied `persist`
86
164
  * with predefined BroadcastChannel adapter
87
165
  */
88
- declare function createPersist(defaults?: ConfigPersist): Persist;
166
+ declare const createPersist: (defaults?: ConfigPersist) => Persist;
89
167
  /**
90
168
  * Default partially applied `persist`
91
169
  */
92
170
  declare const persist: Persist;
93
171
 
94
- export { type BroadcastConfig, type ConfigPersist, type ConfigSourceTarget, type ConfigStore, type Contract, type Done, type Fail, type Finally, type Persist, type StorageAdapter, type StorageAdapterFactory, broadcast, createPersist, persist };
172
+ export { broadcast, createPersist, persist };
173
+ export type { Adapter, BroadcastConfig, ConfigPersist, ConfigSourceTarget, ConfigStore, Contract, DisposableAdapter, Done, Fail, Finally, Persist, StorageAdapter, StorageAdapterFactory };
@@ -1,21 +1,97 @@
1
- import { Unit, Store, Event, Effect, Subscription } from 'effector';
1
+ import { Unit, UnitTargetable, Store, Event, Effect, StoreWritable, EventCallable, Subscription } from 'effector';
2
2
 
3
+ /** The Contract interface. */
4
+ interface Contract$1<Raw, Data extends Raw> {
5
+ /**
6
+ * Checks if Raw is Data
7
+ */
8
+ isData: (prepared: Raw) => prepared is Data;
9
+ /**
10
+ * - empty array is dedicated for valid response
11
+ * - array of string with validation erorrs for invalidDataError
12
+ */
13
+ getErrorMessages: (prepared: Raw) => string[];
14
+ }
15
+
16
+ /** The Standard Schema interface. */
17
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
18
+ /** The Standard Schema properties. */
19
+ readonly '~standard': StandardSchemaV1.Props<Input, Output>;
20
+ }
21
+ declare namespace StandardSchemaV1 {
22
+ /** The Standard Schema properties interface. */
23
+ interface Props<Input = unknown, Output = Input> {
24
+ /** The version number of the standard. */
25
+ readonly version: 1;
26
+ /** The vendor name of the schema library. */
27
+ readonly vendor: string;
28
+ /** Validates unknown input values. */
29
+ readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result<Output> | Promise<Result<Output>>;
30
+ /** Inferred types associated with the schema. */
31
+ readonly types?: Types<Input, Output> | undefined;
32
+ }
33
+ /** The result interface of the validate function. */
34
+ type Result<Output> = SuccessResult<Output> | FailureResult;
35
+ /** The result interface if validation succeeds. */
36
+ interface SuccessResult<Output> {
37
+ /** The typed output value. */
38
+ readonly value: Output;
39
+ /** A falsy value for `issues` indicates success. */
40
+ readonly issues?: undefined;
41
+ }
42
+ interface Options {
43
+ /** Explicit support for additional vendor-specific parameters, if needed. */
44
+ readonly libraryOptions?: Record<string, unknown> | undefined;
45
+ }
46
+ /** The result interface if validation fails. */
47
+ interface FailureResult {
48
+ /** The issues of failed validation. */
49
+ readonly issues: ReadonlyArray<Issue>;
50
+ }
51
+ /** The issue interface of the failure output. */
52
+ interface Issue {
53
+ /** The error message of the issue. */
54
+ readonly message: string;
55
+ /** The path of the issue, if any. */
56
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
57
+ }
58
+ /** The path segment interface of the issue. */
59
+ interface PathSegment {
60
+ /** The key representing a path segment. */
61
+ readonly key: PropertyKey;
62
+ }
63
+ /** The Standard Schema types interface. */
64
+ interface Types<Input = unknown, Output = Input> {
65
+ /** The input type of the schema. */
66
+ readonly input: Input;
67
+ /** The output type of the schema. */
68
+ readonly output: Output;
69
+ }
70
+ /** Infers the input type of a Standard Schema. */
71
+ type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];
72
+ /** Infers the output type of a Standard Schema. */
73
+ type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
74
+ }
75
+
76
+ interface Adapter<State> {
77
+ get(this: void, //
78
+ raw?: any, ctx?: any): State | undefined | Promise<State | undefined>;
79
+ set(this: void, //
80
+ value: State, ctx?: any): void | Promise<void>;
81
+ }
82
+ interface DisposableAdapter<State> extends Adapter<State> {
83
+ (): void;
84
+ }
3
85
  interface StorageAdapter {
4
- <State>(key: string, update: (raw?: any) => void): {
5
- get(raw?: any, ctx?: any): State | Promise<State | undefined> | undefined;
6
- set(value: State, ctx?: any): void;
7
- };
86
+ <State>(key: string, update: (raw?: any) => void): Adapter<State> | DisposableAdapter<State>;
8
87
  keyArea?: any;
9
88
  noop?: boolean;
10
89
  }
11
90
  interface StorageAdapterFactory<AdapterConfig> {
12
- (config?: AdapterConfig): StorageAdapter;
91
+ (config: AdapterConfig): StorageAdapter;
13
92
  factory: true;
14
93
  }
15
- type Contract<Data> = ((raw: unknown) => raw is Data) | {
16
- isData: (raw: unknown) => raw is Data;
17
- getErrorMessages: (raw: unknown) => string[];
18
- };
94
+ type Contract<Data> = ((raw: unknown) => raw is Data) | StandardSchemaV1<unknown, Data> | Contract$1<unknown, Data>;
19
95
  type Done<State> = {
20
96
  key: string;
21
97
  keyPrefix: string;
@@ -29,34 +105,36 @@ type Fail<Err> = {
29
105
  error: Err;
30
106
  value?: any;
31
107
  };
32
- type Finally<State, Err> = (Done<State> & {
108
+ type FinallyDone<State> = Done<State> & {
33
109
  status: 'done';
34
- }) | (Fail<Err> & {
110
+ };
111
+ type FinallyFail<Err> = Fail<Err> & {
35
112
  status: 'fail';
36
- });
113
+ };
114
+ type Finally<State, Err> = FinallyDone<State> | FinallyFail<Err>;
37
115
  interface ConfigPersist$1 {
38
- pickup?: Unit<any>;
116
+ pickup?: Unit<any> | Unit<any>[];
39
117
  context?: Unit<any>;
40
118
  keyPrefix?: string;
41
119
  contract?: Contract<any>;
42
120
  }
43
121
  interface ConfigCommon<State, Err = Error> {
44
122
  clock?: Unit<any>;
45
- done?: Unit<Done<State>>;
46
- fail?: Unit<Fail<Err>>;
47
- finally?: Unit<Finally<State, Err>>;
48
- pickup?: Unit<any>;
123
+ done?: UnitTargetable<Done<State>>;
124
+ fail?: UnitTargetable<Fail<Err>>;
125
+ finally?: UnitTargetable<Finally<State, Err>>;
126
+ pickup?: Unit<any> | Unit<any>[];
49
127
  context?: Unit<any>;
50
128
  key?: string;
51
129
  keyPrefix?: string;
52
130
  contract?: Contract<State | undefined>;
53
131
  }
54
132
  interface ConfigJustStore<State> {
55
- store: Store<State>;
133
+ store: StoreWritable<State>;
56
134
  }
57
135
  interface ConfigJustSourceTarget<State> {
58
136
  source: Store<State> | Event<State> | Effect<State, any, any>;
59
- target: Store<State> | Event<State> | Effect<State, any, any>;
137
+ target: StoreWritable<State> | EventCallable<State> | Effect<State, any, any>;
60
138
  }
61
139
  interface ConfigStore$1<State, Err = Error> extends ConfigCommon<State, Err>, ConfigJustStore<State> {
62
140
  }
@@ -77,18 +155,19 @@ interface Persist {
77
155
  <State, Err = Error>(config: ConfigSourceTarget<State, Err>): Subscription;
78
156
  <State, Err = Error>(config: ConfigStore<State, Err>): Subscription;
79
157
  }
80
- declare function broadcast(config?: BroadcastConfig): StorageAdapter;
81
- declare namespace broadcast {
82
- var factory: true;
83
- }
158
+ /**
159
+ * Creates BroadcastChannel adapter
160
+ */
161
+ declare const broadcast: StorageAdapterFactory<BroadcastConfig | undefined | void>;
84
162
  /**
85
163
  * Creates custom partially applied `persist`
86
164
  * with predefined BroadcastChannel adapter
87
165
  */
88
- declare function createPersist(defaults?: ConfigPersist): Persist;
166
+ declare const createPersist: (defaults?: ConfigPersist) => Persist;
89
167
  /**
90
168
  * Default partially applied `persist`
91
169
  */
92
170
  declare const persist: Persist;
93
171
 
94
- export { type BroadcastConfig, type ConfigPersist, type ConfigSourceTarget, type ConfigStore, type Contract, type Done, type Fail, type Finally, type Persist, type StorageAdapter, type StorageAdapterFactory, broadcast, createPersist, persist };
172
+ export { broadcast, createPersist, persist };
173
+ export type { Adapter, BroadcastConfig, ConfigPersist, ConfigSourceTarget, ConfigStore, Contract, DisposableAdapter, Done, Fail, Finally, Persist, StorageAdapter, StorageAdapterFactory };
@@ -1,2 +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};
1
+ import{persist as e}from"../core/index.js";import{nil as r}from"../nil/index.js";var a=new Map,s=e=>"undefined"!=typeof BroadcastChannel?(({channel:e="effector-storage"})=>{var r,s=a.get(e)??(r=new BroadcastChannel(e));r&&a.set(e,r);var t=(e,r)=>{var a=({data:a})=>{null==a?r(()=>{throw new Error("Unable to deserialize message")}):a.key===e&&r(()=>a.value)},t=()=>{r(()=>{throw new Error("Unable to deserialize message")})};return s.addEventListener("message",a),s.addEventListener("messageerror",t),Object.assign(()=>{s.removeEventListener("message",a),s.removeEventListener("messageerror",t)},{get(e){if(e)return e()},set(r){s.postMessage({key:e,value:r})}})};return t.keyArea=s,t})({...e}):r({keyArea:"broadcast"});s.factory=!0;var t=r=>a=>e({adapter:s,...r,...a}),n=/*#__PURE__*/t();export{s as broadcast,t as createPersist,n as persist};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +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) => void\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,GAAAA,CAAIS,GACF,GAAIA,EAAK,OAAOA,GACjB,EAEDR,GAAAA,CAAIO,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"}
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 const 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) => void\n ) => {\n const onmessage = ({ data }: MessageEvent) => {\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 const onmessageerror = () => {\n update(() => {\n throw new Error('Unable to deserialize message')\n })\n }\n\n bus.addEventListener('message', onmessage)\n bus.addEventListener('messageerror', onmessageerror)\n\n const dispose = () => {\n bus.removeEventListener('message', onmessage)\n bus.removeEventListener('messageerror', onmessageerror)\n }\n\n return Object.assign(dispose, {\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 ConfigSourceTarget as BaseConfigSourceTarget,\n ConfigStore as BaseConfigStore,\n StorageAdapterFactory,\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 Adapter,\n Contract,\n DisposableAdapter,\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 */\nconst supports = () => typeof BroadcastChannel !== 'undefined'\n\n/**\n * Creates BroadcastChannel adapter\n */\nexport const broadcast: StorageAdapterFactory<\n BroadcastConfig | undefined | void\n> = (config) => {\n return supports()\n ? adapter({\n ...config,\n })\n : nil({ keyArea: 'broadcast' })\n}\n\n// mark as factory\nbroadcast.factory = true\n\n/**\n * Creates custom partially applied `persist`\n * with predefined BroadcastChannel adapter\n */\nexport const createPersist =\n (defaults?: ConfigPersist): Persist =>\n (config) =>\n base({\n adapter: broadcast,\n ...defaults,\n ...config,\n })\n\n/**\n * Default partially applied `persist`\n */\nexport const persist: Persist = /*#__PURE__*/ createPersist()\n"],"names":["channels","Map","broadcast","config","BroadcastChannel","adapter","channel","created","bus","get","set","key","update","onmessage","data","Error","value","onmessageerror","addEventListener","Object","assign","dispose","removeEventListener","box","postMessage","keyArea","nil","factory","createPersist","defaults","base","persist"],"mappings":"iFASA,IAAMA,EAAW,IAAIC,ICsCRC,EAERC,GAP8C,oBAArBC,iBD5BPC,GACrBC,UAAU,uBAEV,IAAIC,EACEC,EAAMR,EAASS,IAAIH,KAAaC,EAAU,IAAIH,iBAAiBE,IACjEC,GAASP,EAASU,IAAIJ,EAASC,GAEnC,IAAMF,EAA0BA,CAC9BM,EACAC,KAEA,IAAMC,EAAYA,EAAGC,WAGP,MAARA,EACFF,EAAO,KACL,MAAM,IAAIG,MAAM,mCAETD,EAAKH,MAAQA,GACtBC,EAAO,IACEE,EAAKE,QAQZC,EAAiBA,KACrBL,EAAO,KACL,MAAM,IAAIG,MAAM,oCAYpB,OARAP,EAAIU,iBAAiB,UAAWL,GAChCL,EAAIU,iBAAiB,eAAgBD,GAO9BE,OAAOC,OALEC,KACdb,EAAIc,oBAAoB,UAAWT,GACnCL,EAAIc,oBAAoB,eAAgBL,IAGZ,CAC5BR,GAAAA,CAAIc,GACF,GAAIA,EAAK,OAAOA,GAClB,EAEAb,GAAAA,CAAIM,GACFR,EAAIgB,YAAY,CAAEb,MAAKK,SACzB,KAKJ,OADAX,EAAQoB,QAAUjB,EACXH,GCjBHA,CAAQ,IACHF,IAELuB,EAAI,CAAED,QAAS,cAIrBvB,EAAUyB,SAAU,EAMb,IAAMC,EACVC,GACA1B,GACC2B,EAAK,CACHzB,QAASH,KACN2B,KACA1B,IAMI4B,eAAiCH"}