state-decorator 6.7.0 → 6.8.0-beta.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
@@ -11,12 +11,11 @@ The StateDecorator is a set of Reacts hook that manages a complex component stat
11
11
  - Deterministic state changes (clear separation of effects and side effects)
12
12
  - Ease asynchronous actions state changes (loading states, success & error handlers, parallel actions management, optimistic updates...)
13
13
  - Easily and efficiently share slices of state.
14
- - Easily testable (uses pure functions, utility functions provided)
14
+ - Easily testable (test framework provided)
15
15
  - Easily update state from or react to props changes
16
- - Ease debugging (trace state changes)
16
+ - Ease debugging (trace state changes, dev tools)
17
17
  - Improve code conciseness (no boiler plate code)
18
- - Enforce separation of container components and presentation components.
19
- - Strongly typed
18
+ - Strongly typed (Typescript)
20
19
 
21
20
  # 🏎️ V6: The Store
22
21
 
@@ -139,12 +138,12 @@ export function App(props: Props) => {
139
138
 
140
139
  # React hooks
141
140
 
142
- | Hook | Purpose | Component refreshed on store change | Store is destroyed on unmount |
143
- | ------------- | ------------------------------------------------------ | ----------------------------------- | ----------------------------- |
144
- | useLocalStore | Create a store and binds it to the react component | Y | Y |
145
- | useStore | Binds an existing store to a react component (sharing) | Y | Y |
146
- | useBindStore | Bind an existing store to a react component (sharing) | N | Y |
147
- | useStoreSlice | Binds a store slice to a react component (sharing) | If slice has changed only | N |
141
+ | Hook | Purpose | Return | Component refreshed on store change | Store is destroyed on unmount |
142
+ | ---------------- | --------------------------------------------------- | -------------- | ----------------------------------- | ----------------------------- |
143
+ | useLocalStore | Create a store, binds it to the react component. | State, actions | Y | Y |
144
+ | useGetLocalStore | Create a store, binds it to the react component. | Store | N | Y |
145
+ | useStore | Binds a store instance to the react component. | State, actions | Y | N |
146
+ | useStoreSlice | Binds a store slice to a react component (sharing). | Slice | If slice has changed only | N |
148
147
 
149
148
  # Initial state
150
149
 
@@ -492,63 +491,234 @@ When a hook that creates / binds a store is mounted, the **onMount** option is c
492
491
  ```typescript
493
492
  import { createStore } from 'state-decorator';
494
493
 
494
+ // global store
495
495
  const store = createStore(getInitialState, actionsImpl, {
496
496
  onMount: ({ a }) => {
497
497
  a.loadList;
498
498
  },
499
499
  });
500
500
 
501
- // onMount is called when this component is mounted
501
+ store.init(initialProps);
502
+ ```
503
+
504
+ ```typescript
505
+ import { createStore } from 'state-decorator';
506
+
507
+ // local store
502
508
  function Container(p: ContainerProps) {
503
- useBindStore(store, p);
509
+ const store = useGetLocalStore(getInitialState, actionsImpl, p, {
510
+ onMount: ({ a }) => {
511
+ a.loadList;
512
+ },
513
+ });
504
514
  }
505
515
  ```
506
516
 
507
517
  If an initial action is launched each time a property changes, consider using the **onMount** flag of the **onPropsChange** entry.
508
518
 
509
- ## State sharing and slices
519
+ # Global and Local Stores VS State sharing
510
520
 
511
- - Declare a store and bind it to a component using _useStore_ or _useBindStore_ hooks.
512
- - Deeper in the tree component, use _useStoreSlice_ to get a store slice.
513
- - Component using slices will be refreshed only if their store slice changes.
521
+ There are two ways to share state and actions:
514
522
 
515
- ```typescript
516
- import React from 'react';
517
- import { useStore, useStoreSlice, StoreActions } from 'state-decorator';
523
+ - Using regular props.
524
+ - Using state slices.
518
525
 
519
- // Declare typings & actions as above
526
+ There are two types of stores:
527
+
528
+ - Global store:
529
+
530
+ - store is created as an instance and it is exported from the JS module.
531
+ - it can be imported in any other JS module.
532
+ - store lifespan is equal to the application one.
520
533
 
521
- // Create a store
534
+ - Local store:
535
+ - store is created by a hook and is bound to a React component (each instance of this component owns its own store).
536
+ - action and props can be shared using props or sharing the store itself (see example below)
537
+ - store is destroyed when its React component is unmounted.
522
538
 
539
+ ## Using props
540
+
541
+ - Bind a React component to make store state / actions available on React component.
542
+ - Any change in the store (state, loading actions, ...) will trigger a refresh of the bound React component.
543
+ - Pass state / actions using regular React props.
544
+ - Use React.memo to prevent unecessary React re-renders if needed.
545
+
546
+ ### Global store
547
+
548
+ ```typescript
549
+ // Declare typings & actions as above
550
+
551
+ // Create a store in a dedicated file, named GlobalStore.ts for example
523
552
  export const store = createStore(getInitialState, userAppActions);
524
553
 
525
- // Bind to react component
554
+ //----------------------
555
+
556
+ // In another file
557
+ import React, { memo } from 'react';
558
+ import { useStore } from 'state-decorator';
559
+ import store from './GlobalStore';
526
560
 
527
- export function Container(prop: Props) {
561
+ // Bind to react component
562
+ // Each time the store state changes, a re-render is done.
563
+ export function Container(props: Props) {
528
564
  const { state, actions } = useStore(store, props);
565
+ return (
566
+ <div>
567
+ <Title text={state.title} />
568
+ <Subtitle text={state.subtitle} />
569
+ </div>
570
+ );
571
+ }
529
572
 
530
- // or
531
- // useBindStore(store, props);
532
- // if you are not interested in getting the state here
573
+ // Simple presentation components
574
+ // Use memo to prevent re-render if another part of the state has changed than "title"
575
+ const Title = memo(function Title(props: { title: string }) {
576
+ return <div>{props.text}</div>;
577
+ });
533
578
 
534
- return <div />;
579
+ const Subtitle = memo(function Subtitle(props: { subtitle: string }) {
580
+ return <div>{props.subtitle}</div>;
581
+ });
582
+ ```
583
+
584
+ ### Local Store
585
+
586
+ ```typescript
587
+ import React, { memo } from 'react';
588
+ import { useLocalStore } from 'state-decorator';
589
+
590
+ // Declare typings & actions as above
591
+
592
+ // Create and bind to react component
593
+ // Each time the store state changes, a re-render is done.
594
+ export function Container(props: Props) {
595
+ const { state, actions } = useLocalStore(getInitialState, userAppActions, props);
596
+ return (
597
+ <div>
598
+ <Title text={state.title} />
599
+ <Subtitle text={state.subtitle} />
600
+ </div>
601
+ );
535
602
  }
536
603
 
537
- // Components deeper in the component tree will be refreshed if, and only if,
538
- // slice is changed (here: text property)
604
+ // Simple presentation components
605
+ // Use memo to prevent re-render if another part of the state has changed than "title"
606
+ const Title = memo(function Title(props: { title: string }) {
607
+ return <div>{props.title}</div>;
608
+ });
609
+
610
+ const Subtitle = memo(function Subtitle(props: { subtitle: string }) {
611
+ return <div>{props.subtitle}</div>;
612
+ });
613
+ ```
614
+
615
+ ## State slices
616
+
617
+ Using React props implies useless re-renders and optionally memoization.
539
618
 
540
- export function SubComponent2() {
541
- const s = useStoreSlice(store, ['text']);
542
- return <div>{s.text}</div>;
619
+ To prevent this, React provides [context](https://en.reactjs.org/docs/context.html) hooks.
620
+
621
+ The problem is that if the context contains a complex state with lots of props, if **any** of these props is changing, **all** components that uses this context will be re-rendered.
622
+
623
+ To overcome this problem, the StateDecorator provides a _useStoreSlice_ and _useStoreContextSlice_ hook that allow to define and extracts a slice of the state and trigger a re-render of the React component only if slice has changed.
624
+
625
+ [![Edit Slice](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/slices-v6-eg471?file=/src/SliceView.tsx)
626
+
627
+ ## Global Store
628
+
629
+ ```typescript
630
+ // Declare typings & actions as above
631
+
632
+ // Create a store in a dedicated file, named GlobalStore.ts for example
633
+ export const store = createStore(getInitialState, userAppActions);
634
+
635
+ //----------------------
636
+
637
+ import React, { memo } from 'react';
638
+ import { useStoreSlice } from 'state-decorator';
639
+ import store from './GlobalStore';
640
+
641
+ export function Container(props: Props) {
642
+ return (
643
+ <div>
644
+ <Title />
645
+ <Subtitle />
646
+ </div>
647
+ );
543
648
  }
544
649
 
545
- export function SubComponent() {
546
- const s = useStoreSlice(store, (s) => ({ text: s.text }));
547
- return <div>{s.text}</div>;
650
+ function Title() {
651
+ // extracts the "title" slice
652
+ // component is refresh only if title is changed in the store
653
+ const { title } = useStoreSlice(store, ['title']);
654
+ return <div>{title}</div>;
655
+ }
656
+
657
+ function Subtitle(props: { subtitle: string }) {
658
+ const { subtitle } = useStoreSlice(store, ['subtitle']);
659
+ return <div>{subtitle}</div>;
548
660
  }
549
661
  ```
550
662
 
551
- [![Edit Slice](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/slices-v6-eg471?file=/src/SliceView.tsx)
663
+ ## Local Store
664
+
665
+ ```typescript
666
+ // ------- stores/MyStore.ts --------
667
+
668
+ import React from 'react';
669
+ import { useGetLocalStore, useStoreContextSlice } from 'state-decorator';
670
+
671
+ // Declare typings & actions as above
672
+
673
+ // Create a store context
674
+
675
+ type StoreContextProps = StoreApi<State, Actions, Props>;
676
+
677
+ export const StoreContext = createContext<StoreContextProps>(null);
678
+
679
+ // The StoreContext will allow to access to the store
680
+ // But this context is NOT refreshed if the store state is changed
681
+ export function StoreContextProvider(p: { children: any; propIn: string }) {
682
+ const { children, ...props } = p;
683
+ const store = useGetLocalStore(getInitialState, actionsImpl, props);
684
+ return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>;
685
+ }
686
+
687
+ // In a container file ------------------------
688
+
689
+ import { StoreContextProvider } from 'stores/MyStore';
690
+
691
+ // If Container is destroyed store is destroyed
692
+ export function Container(props: Props) {
693
+ return (
694
+ <StoreContextProvider {...props}>
695
+ <SubComponent />
696
+ <SubComponent2 />
697
+ </StoreContextProvider>
698
+ );
699
+ }
700
+
701
+ // Component deeper in the component tree...
702
+
703
+ import { StoreContext } from 'stores/MyStore';
704
+
705
+ function Title() {
706
+ // extracts the "title" slice
707
+ // component is refresh only if title is changed in the store
708
+ const { title } = useStoreContextSlice(StoreContext, ['title']);
709
+
710
+ // same as
711
+ // const store = useContext(StoreContext)
712
+ // const { title } = useStoreSlice(store, ['title']);
713
+
714
+ return <div>{title}</div>;
715
+ }
716
+
717
+ function Subtitle(props: { subtitle: string }) {
718
+ const { subtitle } = useStoreContextSlice(StoreContext, ['subtitle']);
719
+ return <div>{subtitle}</div>;
720
+ }
721
+ ```
552
722
 
553
723
  # Global configuration
554
724
 
package/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { Context } from 'react';
1
2
  import { setGlobalConfig, GlobalConfig } from './impl';
2
3
  import { DecoratedActions, StoreActions, AsyncAction, SyncAction, SimpleSyncAction, LoadingMap, LoadingParallelMap, StoreOptions, AsyncActionPromise, InvocationContext, GetPromiseInvocationContext, EffectsInvocationContext, InvocationContextActions, WarningNotifyFunc, ErrorEffectsInvocationContext, OnMountInvocationContext, ContextBase, OnPropsChangeEffectsContext, ContextState, ConflictPolicy, Middleware, AbortActionCallback, MiddlewareFactory, LoadingProps } from './types';
3
4
  export { DecoratedActions, StoreActions, LoadingMap, StoreOptions, LoadingParallelMap, AsyncActionPromise as AsynchActionPromise, InvocationContext, GetPromiseInvocationContext, EffectsInvocationContext, InvocationContextActions, WarningNotifyFunc, ErrorEffectsInvocationContext, OnMountInvocationContext, ContextBase, OnPropsChangeEffectsContext, SyncAction, AsyncAction, SimpleSyncAction, ContextState, ConflictPolicy, GlobalConfig, Middleware, setGlobalConfig, LoadingProps, AbortActionCallback, };
@@ -68,18 +69,43 @@ export declare function createStore<S, A extends DecoratedActions, P, DS = {}>(g
68
69
  * A react hook to get a state slice. Will be refresh if, and only if, one property of the slice has changed
69
70
  * @param store The store to listen to.
70
71
  * @param slicerFunc A function that returns a state slice
71
- * @param comparator An optional function to compare if slice property has changed (shallow test by default)
72
72
  * @returns The state slice.
73
73
  */
74
74
  export declare function useStoreSlice<S, A extends DecoratedActions, P, DS, SLICE>(store: StoreApi<S, A, P, DS>, slicerFunc: (ctx: StateListenerContext<S, DS, A>) => SLICE): SLICE;
75
- export declare function useStoreSlice<S, A extends DecoratedActions, P, DS, K extends keyof StateListenerContext<S, DS, A>>(store: StoreApi<S, A, P, DS>, properties: K[]): Pick<StateListenerContext<S, DS, A>, K>;
75
+ /**
76
+ * A react hook to get a state slice. Will be refresh if, and only if, one property of the slice has changed
77
+ * @param store The store to listen to.
78
+ * @param properties list of properties to extract from store
79
+ * @returns The state slice.
80
+ */
81
+ export declare function useStoreSlice<S, A extends DecoratedActions, P, DS, K extends keyof StateListenerContext<S, DS, A>, KL extends keyof A>(store: StoreApi<S, A, P, DS>, properties: K[], loadingProps?: KL[]): Pick<StateListenerContext<S, DS, A>, K> & {
82
+ loadingMap: LoadingMap<Pick<A, KL>>;
83
+ };
84
+ /**
85
+ * A react hook to get a state slice from a store context.
86
+ * The component be refreshed if, and only if, one property of the slice has changed.
87
+ * @param store The store to listen to.
88
+ * @param slicerFunc A function that returns a state slice
89
+ * @returns The state slice.
90
+ */
91
+ export declare function useStoreContextSlice<S, A extends DecoratedActions, P, DS, SLICE>(storeContext: Context<StoreApi<S, A, P, DS>>, slicerFunc: (ctx: StateListenerContext<S, DS, A>) => SLICE): SLICE;
92
+ /**
93
+ * A react hook to get a state slice from a store context.
94
+ * The component will be refreshed if, and only if, one property of the slice has changed.
95
+ * @param store The store to listen to.
96
+ * @param properties list of properties to extract from store
97
+ * @param loadingFlags list of action names to extract their loading state from store (available in loadingMap).
98
+ * @returns The state slice.
99
+ */
100
+ export declare function useStoreContextSlice<S, A extends DecoratedActions, P, DS, K extends keyof StateListenerContext<S, DS, A>, KL extends keyof A>(storeContext: Context<StoreApi<S, A, P, DS>>, properties: K[], loadingProps?: KL[]): Pick<StateListenerContext<S, DS, A>, K> & {
101
+ loadingMap: LoadingMap<Pick<A, KL>>;
102
+ };
76
103
  /**
77
104
  * Binds the store to this component.
78
- * Store will be destroyed when component is unmouted.
105
+ * Store will NOT be destroyed when component is unmouted.
79
106
  * Props passed to actions will come from this components.
80
107
  * If store is configured to react of props changes, it will used passed props.
81
- * A store must be bound to only one React component.
82
- * This component will be refreshed for every change in the store.
108
+ * The component will be refreshed for every change in the store.
83
109
  *
84
110
  * @param store The store to listen to.
85
111
  * @param props The parent component props
@@ -101,14 +127,33 @@ export declare function useStore<S, A extends DecoratedActions, P, DS = {}>(stor
101
127
  * If store is configured to react of props changes, it will used passed props.
102
128
  * A store must be bound to only one React component.
103
129
  *
104
- * This component will NOT be refreshed for any change in the store.
130
+ * The component will NOT be refreshed for any change in the store.
105
131
  *
106
132
  * @param store The store to listen to.
107
133
  * @param props The parent component props
134
+ * @deprecated Do not bind an instance to a component or use useGetLocalStore to create a store local to a component.
108
135
  */
109
136
  export declare function useBindStore<S, A extends DecoratedActions, P, DS = {}>(store: StoreApi<S, A, P, DS>, props?: P): StoreApi<S, A, P, DS>;
137
+ /**
138
+ * Creates a store as a ref to the owner component.
139
+ * Store WILL be destroyed when component is unmouted.
140
+ * Props passed to actions will come from owner components.
141
+ * If store is configured to react of props changes, it will used passed props.
142
+ *
143
+ * This component will NOT be refreshed for any change in the store.
144
+ *
145
+ * @param getInitialState Function to compute initial state from props.
146
+ * @param actionImpl Actions implementation.
147
+ * @param props Owner component props to update state or react on prop changes
148
+ * @param options The store options.
149
+ * @returns store
150
+ */
151
+ export declare function useGetLocalStore<S, A extends DecoratedActions, P, DS = {}>(getInitialState: (p: P) => S, actionImpl: StoreActions<S, A, P, DS>, props?: P, options?: StoreOptions<S, A, P, DS>, middlewares?: MiddlewareFactory<S, A, P>[]): StoreApi<S, A, P, DS>;
110
152
  /**
111
153
  * Creates and manages a local store.
154
+ * The component will be refreshed for every change in the store.
155
+ * Store will NOT be destroyed when component is unmouted.
156
+ *
112
157
  * @param getInitialState Function to compute initial state from props.
113
158
  * @param actionImpl Actions implementation.
114
159
  * @param props Owner component props to update state or react on prop changes
package/index.es.js CHANGED
@@ -1,2 +1,2 @@
1
- import{useReducer as t,useMemo as r,useRef as n,useLayoutEffect as e,useEffect as o}from"react";import{createRef as u,isSimpleSyncAction as c,decorateSimpleSyncAction as i,isAsyncAction as a,decorateAsyncAction as l,computeAsyncActionInput as s,isSyncAction as f,decorateSyncAction as d,globalConfig as p,onPropChange as v,DEFAULT_PROMISE_ID as g,computeDerivedValues as y,buildOnMountInvocationContext as b,isLoadingImpl as x,runMiddlewares as O,buildLoadingMap as h}from"./impl";export{setGlobalConfig}from"./impl";function m(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function j(t){var r={exports:{}};return t(r,r.exports),r.exports}var M,A=j((function(t){t.exports=function(t){if(Array.isArray(t))return t},t.exports.default=t.exports,t.exports.__esModule=!0})),P=j((function(t){t.exports=function(t,r){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t)){var n=[],e=!0,o=!1,u=void 0;try{for(var c,i=t[Symbol.iterator]();!(e=(c=i.next()).done)&&(n.push(c.value),!r||n.length!==r);e=!0);}catch(t){o=!0,u=t}finally{try{e||null==i.return||i.return()}finally{if(o)throw u}}return n}},t.exports.default=t.exports,t.exports.__esModule=!0})),w=j((function(t){t.exports=function(t,r){(null==r||r>t.length)&&(r=t.length);for(var n=0,e=new Array(r);n<r;n++)e[n]=t[n];return e},t.exports.default=t.exports,t.exports.__esModule=!0})),S=j((function(t){t.exports=function(t,r){if(t){if("string"==typeof t)return w(t,r);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?w(t,r):void 0}},t.exports.default=t.exports,t.exports.__esModule=!0})),E=j((function(t){t.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},t.exports.default=t.exports,t.exports.__esModule=!0})),L=m(j((function(t){t.exports=function(t,r){return A(t)||P(t,r)||S(t,r)||E()},t.exports.default=t.exports,t.exports.__esModule=!0}))),_=m(j((function(t){t.exports=function(t,r,n){return r in t?Object.defineProperty(t,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[r]=n,t},t.exports.default=t.exports,t.exports.__esModule=!0})));function k(t,r){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var e=Object.getOwnPropertySymbols(t);r&&(e=e.filter((function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable}))),n.push.apply(n,e)}return n}function R(t){for(var r=1;r<arguments.length;r++){var n=null!=arguments[r]?arguments[r]:{};r%2?k(Object(n),!0).forEach((function(r){_(t,r,n[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):k(Object(n)).forEach((function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))}))}return t}function I(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},e=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,o=u(),m=u(),j=u(),M=u(),A=u(),P=u(),w=u(),S=u(),E=u(!1),L=u([]),k={},I=0;function C(t){var r="".concat(I++);return k[r]=t,function(){delete k[r]}}function D(t,r){var n=R(R({},t),r),e=R(R(R({},n),M.current),{},{isLoading:F,abortAction:J,loading:$(),loadingMap:q()});Object.keys(k).forEach((function(t){k[t](e)}))}function T(t){var r=j.current;j.current=t,E.current?v(o,m,j,r,M,n,N,!1):G(t)}function U(t){o.current=t,y(o,j,m,n),D(o.current,m.current.state)}function G(u){if(!E.current){var c;j.current=u,E.current=!0,o.current=t(u);var i=new Set(null==n?void 0:n.initialActionsMarkedLoading);P.current=Object.keys(r).reduce((function(t,r){return t[r]=i.has(r)?_({},g,!0):{},t}),{}),A.current={},w.current={},S.current={},m.current={state:null,deps:{}},L.current=[];var a={options:n,get state(){return o.current},actions:r,setState:U},l=function(t){var r,n=t();L.current.push(n),null===(r=n.init)||void 0===r||r.call(n,a)};null===(c=p.defaultMiddlewares)||void 0===c||c.forEach(l),null==e||e.forEach(l),y(o,j,m,n),v(o,m,j,null,M,n,N,!0),null!=n&&n.onMount&&n.onMount(b(o,m,j,M)),D(o.current,m.current.state)}}function K(){var t;E.current&&(null==n||null===(t=n.onUnmount)||void 0===t||t.call(n,b(o,m,j,M)),j.current=null,o.current=null,P.current=null,w.current=null,S.current=null,m.current=null,Object.keys(A.current).forEach((function(t){clearTimeout(A.current[t])})),A.current=null,k={},E.current=!1,L.current.forEach((function(t){var r;null===(r=t.destroy)||void 0===r||r.call(t)})),L.current=[])}function N(t,r,e,u,c,i){var a=arguments.length>6&&void 0!==arguments[6]&&arguments[6],l=arguments.length>7&&void 0!==arguments[7]&&arguments[7],s=!1;if(E.current){var f=r,d=!!c&&x(f||P.current,[e,null==i?void 0:i.promiseId]),p=O(L.current,o.current,t,d,e,u,c,i),v=p.newState,b=p.newLoading;if(null!=v&&(s=!0,o.current=v),d!==b&&(f=h(f,e,(null==i?void 0:i.promiseId)||g,b),0===Object.keys(f).length&&(f=void 0)),null!=f&&(s=!0,P.current=f),s)y(o,j,m,n),l||D(v||o.current,m.current.state);else if(a){var M=y(o,j,m,n);M&&!l&&D(v||o.current,m.current.state)}}}var z=Object.keys(r);function F(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return x.apply(void 0,[P.current].concat(r))}function J(t){var r,n,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:g,o=null===(r=w.current[t])||void 0===r||null===(n=r[e])||void 0===n?void 0:n.abortController,u=!1;return o&&(o.abort(),u=!0),u}function $(){if(E.current){var t=P.current;return null!=Object.keys(t).find((function(r){var n=t[r];return Object.keys(n).find((function(t){return!!n[t]}))}))}return null}function q(){if(E.current){var t=P.current;return Object.keys(t).reduce((function(r,n){return r[n]=null!=Object.keys(t[n]).find((function(r){return!!t[n][r]})),r}),{})}return null}function B(){return{getInitialState:t,options:n,actions:r}}return M.current=z.reduce((function(t,e){var u=r[e];return c(u)?t[e]=i(e,u,o,m,j,E,N):a(u)?t[e]=l({actionName:e,stateRef:o,derivedStateRef:m,propsRef:j,loadingMapRef:P,actionsRef:M,promisesRef:w,conflictActionsRef:S,initializedRef:E,options:n,setState:N,action:s(u)}):f(u)&&(t[e]=d(e,u,o,m,j,M,E,A,n,N)),t}),{}),{getConfig:B,setProps:T,addStateListener:C,init:G,destroy:K,isLoading:F,abortAction:J,get actions(){return M.current},get state(){return E.current?R(R({},o.current),m.current.state):null},get loading(){return $()},get loadingMap(){return q()},get loadingParallelMap(){return E.current?P.current:null}}}function C(o,u){var c=t((function(t){return t>100?0:t+1}),0),i=L(c,2)[1],a=r((function(){return u instanceof Function?u:function(t){return G(t,u)}}),[u]),l=n(null);if(null===l.current){var s=o.state;l.current=a(R(R(R({},s),o.actions),{},{actions:o.actions,loading:o.loading,isLoading:o.isLoading,abortAction:o.abortAction,loadingMap:o.loadingMap}))}return e((function(){return o.addStateListener((function(t){var r,n=a(t),e=l.current,o=p.comparator;r=null==e||!o(n,e),l.current=n,r&&i()}))}),[]),l.current}function D(r){var u=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,c=t((function(t){return t>100?0:t+1}),0),i=L(c,2),a=i[1],l=n(r);return r.setProps(u),e((function(){return l.current.addStateListener((function(){a()}))}),[]),o((function(){return function(){return r.destroy()}}),[]),{state:r.state,actions:r.actions,loading:r.loading,isLoading:r.isLoading,abortAction:r.abortAction,loadingMap:r.loadingMap,loadingParallelMap:r.loadingParallelMap}}function T(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return n(t),t.setProps(r),o((function(){return function(){return t.destroy()}}),[]),t}function U(t,r,e,o,u){var c=n();return null==c.current&&(c.current=I(t,r,o,u)),D(c.current,e)}function G(t,r){return r.reduce((function(r,n){return t.hasOwnProperty(n)&&(r[n]=t[n]),r}),{})}function K(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return function(t){return G(t,r)}}!function(t){t.REJECT="reject",t.IGNORE="ignore",t.KEEP_LAST="keepLast",t.KEEP_ALL="keepAll",t.PARALLEL="parallel",t.REUSE="reuse"}(M||(M={}));export default U;export{M as ConflictPolicy,I as createStore,G as pick,K as slice,T as useBindStore,U as useLocalStore,D as useStore,C as useStoreSlice};
1
+ import{useReducer as r,useMemo as t,useRef as n,useLayoutEffect as e,useContext as u,useEffect as o}from"react";import{createRef as c,isSimpleSyncAction as i,decorateSimpleSyncAction as l,isAsyncAction as a,decorateAsyncAction as f,computeAsyncActionInput as s,isSyncAction as d,decorateSyncAction as p,globalConfig as v,onPropChange as g,DEFAULT_PROMISE_ID as y,computeDerivedValues as b,buildOnMountInvocationContext as x,isLoadingImpl as O,runMiddlewares as h,buildLoadingMap as m}from"./impl";export{setGlobalConfig}from"./impl";function j(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}function M(r){var t={exports:{}};return r(t,t.exports),t.exports}var P,A=M((function(r){r.exports=function(r){if(Array.isArray(r))return r},r.exports.default=r.exports,r.exports.__esModule=!0})),w=M((function(r){r.exports=function(r,t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(r)){var n=[],e=!0,u=!1,o=void 0;try{for(var c,i=r[Symbol.iterator]();!(e=(c=i.next()).done)&&(n.push(c.value),!t||n.length!==t);e=!0);}catch(r){u=!0,o=r}finally{try{e||null==i.return||i.return()}finally{if(u)throw o}}return n}},r.exports.default=r.exports,r.exports.__esModule=!0})),S=M((function(r){r.exports=function(r,t){(null==t||t>r.length)&&(t=r.length);for(var n=0,e=new Array(t);n<t;n++)e[n]=r[n];return e},r.exports.default=r.exports,r.exports.__esModule=!0})),E=M((function(r){r.exports=function(r,t){if(r){if("string"==typeof r)return S(r,t);var n=Object.prototype.toString.call(r).slice(8,-1);return"Object"===n&&r.constructor&&(n=r.constructor.name),"Map"===n||"Set"===n?Array.from(r):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?S(r,t):void 0}},r.exports.default=r.exports,r.exports.__esModule=!0})),_=M((function(r){r.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},r.exports.default=r.exports,r.exports.__esModule=!0})),L=j(M((function(r){r.exports=function(r,t){return A(r)||w(r,t)||E(r,t)||_()},r.exports.default=r.exports,r.exports.__esModule=!0}))),k=j(M((function(r){r.exports=function(r,t,n){return t in r?Object.defineProperty(r,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):r[t]=n,r},r.exports.default=r.exports,r.exports.__esModule=!0})));function R(r,t){var n=Object.keys(r);if(Object.getOwnPropertySymbols){var e=Object.getOwnPropertySymbols(r);t&&(e=e.filter((function(t){return Object.getOwnPropertyDescriptor(r,t).enumerable}))),n.push.apply(n,e)}return n}function I(r){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?R(Object(n),!0).forEach((function(t){k(r,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(n)):R(Object(n)).forEach((function(t){Object.defineProperty(r,t,Object.getOwnPropertyDescriptor(n,t))}))}return r}function C(r,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},e=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,u=c(),o=c(),j=c(),M=c(),P=c(),A=c(),w=c(),S=c(),E=c(!1),_=c([]),L={},R=0;function C(r){var t="".concat(R++);return L[t]=r,function(){delete L[t]}}function D(r,t){var n=I(I({},r),t),e=I(I(I({},n),M.current),{},{isLoading:F,abortAction:J,loading:$(),loadingMap:q()});Object.keys(L).forEach((function(r){L[r](e)}))}function T(r){var t=j.current;j.current=r,E.current?g(u,o,j,t,M,n,N,!1):G(r)}function U(r){u.current=r,b(u,j,o,n),D(u.current,o.current.state)}function G(c){if(!E.current){var i;j.current=c,E.current=!0,u.current=r(c);var l=new Set(null==n?void 0:n.initialActionsMarkedLoading);A.current=Object.keys(t).reduce((function(r,t){return r[t]=l.has(t)?k({},y,!0):{},r}),{}),P.current={},w.current={},S.current={},o.current={state:null,deps:{}},_.current=[];var a={options:n,get state(){return u.current},actions:t,setState:U},f=function(r){var t,n=r();_.current.push(n),null===(t=n.init)||void 0===t||t.call(n,a)};null===(i=v.defaultMiddlewares)||void 0===i||i.forEach(f),null==e||e.forEach(f),b(u,j,o,n),g(u,o,j,null,M,n,N,!0),null!=n&&n.onMount&&n.onMount(x(u,o,j,M)),D(u.current,o.current.state)}}function K(){var r;E.current&&(null==n||null===(r=n.onUnmount)||void 0===r||r.call(n,x(u,o,j,M)),j.current=null,u.current=null,A.current=null,w.current=null,S.current=null,o.current=null,Object.keys(P.current).forEach((function(r){clearTimeout(P.current[r])})),P.current=null,L={},E.current=!1,_.current.forEach((function(r){var t;null===(t=r.destroy)||void 0===t||t.call(r)})),_.current=[])}function N(r,t,e,c,i,l){var a=arguments.length>6&&void 0!==arguments[6]&&arguments[6],f=arguments.length>7&&void 0!==arguments[7]&&arguments[7],s=!1;if(E.current){var d=t,p=!!i&&O(d||A.current,[e,null==l?void 0:l.promiseId]),v=h(_.current,u.current,r,p,e,c,i,l),g=v.newState,x=v.newLoading;if(null!=g&&(s=!0,u.current=g),p!==x&&(d=m(d,e,(null==l?void 0:l.promiseId)||y,x),0===Object.keys(d).length&&(d=void 0)),null!=d&&(s=!0,A.current=d),s)b(u,j,o,n),f||D(g||u.current,o.current.state);else if(a){var M=b(u,j,o,n);M&&!f&&D(g||u.current,o.current.state)}}}var z=Object.keys(t);function F(){for(var r=arguments.length,t=new Array(r),n=0;n<r;n++)t[n]=arguments[n];return O.apply(void 0,[A.current].concat(t))}function J(r){var t,n,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:y,u=null===(t=w.current[r])||void 0===t||null===(n=t[e])||void 0===n?void 0:n.abortController,o=!1;return u&&(u.abort(),o=!0),o}function $(){if(E.current){var r=A.current;return null!=Object.keys(r).find((function(t){var n=r[t];return Object.keys(n).find((function(r){return!!n[r]}))}))}return null}function q(){if(E.current){var r=A.current;return Object.keys(r).reduce((function(t,n){return t[n]=null!=Object.keys(r[n]).find((function(t){return!!r[n][t]})),t}),{})}return null}function B(){return{getInitialState:r,options:n,actions:t}}return M.current=z.reduce((function(r,e){var c=t[e];return i(c)?r[e]=l(e,c,u,o,j,E,N):a(c)?r[e]=f({actionName:e,stateRef:u,derivedStateRef:o,propsRef:j,loadingMapRef:A,actionsRef:M,promisesRef:w,conflictActionsRef:S,initializedRef:E,options:n,setState:N,action:s(c)}):d(c)&&(r[e]=p(e,c,u,o,j,M,E,P,n,N)),r}),{}),{getConfig:B,setProps:T,addStateListener:C,init:G,destroy:K,isLoading:F,abortAction:J,get actions(){return M.current},get state(){return E.current?I(I({},u.current),o.current.state):null},get loading(){return $()},get loadingMap(){return q()},get loadingParallelMap(){return E.current?A.current:null}}}function D(u,o,c){var i=r((function(r){return r>100?0:r+1}),0),l=L(i,2)[1],a=t((function(){return o instanceof Function?o:function(r){return z(r,o)}}),[o]),f=t((function(){return function(r){return null!=c&&c.length>0?z(r.loadingMap,c):null}}),[c]),s=n(null),d=n(null);if(null===s.current){var p=I(I(I({},u.state),u.actions),z(u,["loading","isLoading","abortAction","loadingMap"]));s.current=a(p),d.current=f(p)}e((function(){return u.addStateListener((function(r){var t,n=a(r),e=f(r),u=s.current,o=v.comparator;t=null==u||!o(n,u)||!o(e,d.current),s.current=n,d.current=e,t&&l()}))}),[]);var g=s.current,y=d.current;return null==y?g:I(I({},g),{},{loadingMap:y})}function T(r,t,n){return D(u(r),t,n)}function U(t){var u=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,o=r((function(r){return r>100?0:r+1}),0),c=L(o,2),i=c[1],l=n(t);return t.setProps(u),e((function(){return l.current.addStateListener((function(){i()}))}),[]),{state:t.state,actions:t.actions,loading:t.loading,isLoading:t.isLoading,abortAction:t.abortAction,loadingMap:t.loadingMap,loadingParallelMap:t.loadingParallelMap}}function G(r){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return n(r),r.setProps(t),o((function(){return function(){r.destroy()}}),[]),r}function K(r,t,e,u,c){var i=n();null==i.current&&(i.current=C(r,t,u,c));var l=i.current;return l.setProps(e),o((function(){return function(){l.destroy()}}),[]),l}function N(r,t,e,u,c){var i=n();return null==i.current&&(i.current=C(r,t,u,c)),o((function(){return function(){var r;null===(r=i.current)||void 0===r||r.destroy()}}),[]),U(i.current,e)}function z(r,t){return t.reduce((function(t,n){return r.hasOwnProperty(n)&&(t[n]=r[n]),t}),{})}function F(){for(var r=arguments.length,t=new Array(r),n=0;n<r;n++)t[n]=arguments[n];return function(r){return z(r,t)}}!function(r){r.REJECT="reject",r.IGNORE="ignore",r.KEEP_LAST="keepLast",r.KEEP_ALL="keepAll",r.PARALLEL="parallel",r.REUSE="reuse"}(P||(P={}));export default N;export{P as ConflictPolicy,C as createStore,z as pick,F as slice,G as useBindStore,K as useGetLocalStore,N as useLocalStore,U as useStore,T as useStoreContextSlice,D as useStoreSlice};
2
2
  //# sourceMappingURL=index.es.js.map
package/index.es.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","sources":["../src/types.ts","../node_modules/@babel/runtime/helpers/arrayWithHoles.js","../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js","../node_modules/@babel/runtime/helpers/arrayLikeToArray.js","../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js","../node_modules/@babel/runtime/helpers/nonIterableRest.js","../node_modules/@babel/runtime/helpers/slicedToArray.js","../node_modules/@babel/runtime/helpers/defineProperty.js","../src/index.ts"],"sourcesContent":["/*\n * Copyright 2019 Globalsport SAS\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\nexport type PromiseResult<Type> = Type extends Promise<infer X> ? X : null;\n\nexport type NotifyFunc = (msg: string) => void;\n\nexport type PromiseIdMap = { [promiseId: string]: boolean };\n\nexport type LoadingMap<A> = { [pId in keyof A]?: boolean };\nexport type LoadingParallelMap<A> = { [P in keyof A]?: PromiseIdMap };\nexport type InternalLoadingMap<A> = LoadingParallelMap<A>;\n\nexport type LoadingProps<A> = {\n loading: boolean;\n loadingMap: LoadingMap<A>;\n loadingParallelMap: LoadingParallelMap<A>;\n};\n\n// https://github.com/Microsoft/TypeScript/issues/15300\nexport interface DecoratedActions {\n [name: string]: (...args: any[]) => Promise<any> | void;\n}\n\n/**\n * The State decorator can manage only one asynchronous action of same name at a time.\n * This enum is enumertaing all the policies in such case.\n */\nexport enum ConflictPolicy {\n /**\n * Reject the promise.\n */\n REJECT = 'reject',\n\n /**\n * Return a resolved promise with no result.\n */\n IGNORE = 'ignore',\n\n /**\n * Execute only the last call that conflicts after the one ongoing.\n */\n KEEP_LAST = 'keepLast',\n\n /**\n * Execute all calls one after another.\n */\n KEEP_ALL = 'keepAll',\n\n /**\n * Execute all calls one after another.\n * @see getPromiseId\n */\n PARALLEL = 'parallel',\n\n /**\n * Reuse the ongoing promise if any and if possible (same arguments). Only for GET requests!\n */\n REUSE = 'reuse',\n}\n\nexport type PromiseProvider<S, DS, F extends (...args: any[]) => any, A, P> = (\n ctx: GetPromiseInvocationContext<S, DS, F, P, A>\n) => ReturnType<F> | null;\n\n/**\n * Simple form of a synchronous action.\n */\nexport type SimpleSyncAction<S, F extends (...args: any[]) => any, P, DS, FxRes = S> = (\n ctx: InvocationContext<S, DS, F, P>\n) => FxRes | null;\n\nexport type SyncAction<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = {\n /**\n * Function that update the state when the action is called.\n */\n effects?: (ctx: EffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Debounces the action if this parameter is defined.\n */\n debounceTimeout?: number;\n\n /**\n * Debounces the action side effects if this parameter is defined.\n */\n debounceSideEffectsTimeout?: number;\n\n /**\n * Function that calls side effects, ie. effects that are not changing the state directly.\n */\n sideEffects?: (ctx: SideEffectsInvocationContext<S, DS, F, P, A>) => void;\n};\n\n/**\n * Try to abort an action, if the action is <code>abortable</code>.\n * @param actionName The action name\n * @param promiseId If the action conflict type is <code>ConflictType.PARALLEL</code>, the identifier of the promise.\n * @returns <code>true</code> if the action is abortable and an action is ongoing, <code>false</code> otherwise.\n */\nexport type AbortActionCallback<A> = (actionName: keyof A, promiseId?: string) => boolean;\n\nexport type GetErrorMessage<S, DS, F extends (...args: any[]) => any, P> = (\n ctx: ErrorMessageInvocationContext<S, DS, F, P>\n) => string;\n\nexport type ContextState<S> = {\n state: S;\n s: S;\n};\n\nexport type ContextDerivedStateState<DS> = {\n derived: DS;\n ds: DS;\n};\n\nexport type ContextBase<S, P> = ContextState<S> & {\n props: P;\n p: P;\n};\n\nexport type ContextWithDerived<S, DS, P> = ContextBase<S, P> & ContextDerivedStateState<DS>;\n\nexport type InvocationContextActions<A> = {\n actions: A;\n a: A;\n};\n\nexport type WarningNotifyFunc = {\n notifyWarning?: NotifyFunc;\n};\n\nexport type InvocationContext<S, DS, F extends (...args: any[]) => any, P> = ContextWithDerived<S, DS, P> & {\n args: Parameters<F>;\n promiseId: string;\n};\n\nexport type EffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P> = InvocationContext<S, DS, F, P> & {\n result: PromiseResult<ReturnType<F>>;\n res: PromiseResult<ReturnType<F>>;\n};\n\nexport type GetPromiseInvocationContext<S, DS, F extends (...args: any[]) => any, P, A> = InvocationContextActions<A> &\n InvocationContext<S, DS, F, P> & {\n abortSignal: AbortSignal;\n };\n\nexport type ErrorEffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P> = InvocationContext<\n S,\n DS,\n F,\n P\n> & {\n error: Error;\n err: Error;\n};\n\nexport type SuccessMessageInvocationContext<S, DS, F extends (...args: any[]) => any, P> = EffectsInvocationContext<\n S,\n DS,\n F,\n P\n>;\nexport type ErrorMessageInvocationContext<S, DS, F extends (...args: any[]) => any, P> = ErrorEffectsInvocationContext<\n S,\n DS,\n F,\n P\n>;\n\nexport type SideEffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P, A> = EffectsInvocationContext<\n S,\n DS,\n F,\n P\n> &\n InvocationContextActions<A> &\n WarningNotifyFunc;\n\nexport type ErrorSideEffectsInvocationContext<\n S,\n DS,\n F extends (...args: any[]) => any,\n P,\n A\n> = ErrorEffectsInvocationContext<S, DS, F, P> & InvocationContextActions<A> & WarningNotifyFunc;\n\nexport type OnMountInvocationContext<S, A, P> = ContextBase<S, P> & InvocationContextActions<A>;\n\nexport type EffectsType = 'preEffects' | 'effects' | 'errorEffects' | 'optimisticEffects' | null;\n\nexport type MiddlewareActionContext<S, A, P> = {\n name: keyof A;\n type: EffectsType;\n isAsync: boolean;\n context: InvocationContext<S, any, any, P>;\n};\n\nexport type MiddlewareStoreContext<S, A extends DecoratedActions, P> = {\n actions: StoreActions<S, A, P, any, any>;\n state: S;\n setState: (s: S) => void;\n options: StoreOptions<S, A, P, any>;\n};\n\nexport type MiddlewareFactory<S, A extends DecoratedActions, P> = () => Middleware<S, A, P>;\n\n/**\n * A state change middleware.\n * Allow to listen and change a state change on the fly.\n */\nexport type Middleware<S, A extends DecoratedActions, P> = {\n /**\n * Initializes the middleware. Called when the store is initializing.\n */\n init: (storeContext: MiddlewareStoreContext<S, A, P>) => void;\n\n /**\n * Invoked on a state change has occurred and returns a new state or <code>null</code> if unchanged.\n */\n effects: (\n actionContext: MiddlewareActionContext<S, A, P>,\n oldState: S,\n newState: S,\n loading: boolean\n ) => null | {\n state: S;\n loading: boolean;\n };\n\n /**\n * Destroys the middleware. Called when the store is being destroyed.\n */\n destroy: () => void;\n};\n\nexport type AsyncActionBase<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = {\n /**\n * This action can be aborted. An abortSignal will be injected to the <code>promise</code> / <code>promiseGet</code>.\n */\n abortable?: boolean;\n\n /**\n * A function that provides the success message to pass to the notifySuccess function passed as property to the StateDecorator.\n */\n getSuccessMessage?: (ctx: SuccessMessageInvocationContext<S, DS, F, P>) => string;\n\n /**\n * A function that provides the error message to pass to the notifyError function passed as property to the StateDecorator.\n */\n getErrorMessage?: GetErrorMessage<S, DS, F, P>;\n\n /**\n * If set, called with the result of the promise to update the current state.\n */\n effects?: (ctx: EffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * If set, called with the error of the promise to update the current state.\n */\n errorEffects?: (ctx: ErrorEffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Whether reject the promise instead of handling it.\n */\n rejectPromiseOnError?: boolean;\n\n /**\n * Handle side effects when the request succeeded.\n * @param result The result of the request\n * @param newData The data after the reducer is applied\n * @param args The argument during the call of the request function\n * @param props The props passed to the state decorator\n * @param actions The actions available\n * @param notifyWarning If specified, a notify function to indicate that the action is a semi success (use successMessage / getSuccessMessage otherwise).\n */\n sideEffects?: (ctx: SideEffectsInvocationContext<S, DS, F, P, A>) => void;\n\n /**\n * Handle side effects when the request failed.\n * @param error The error of the request\n * @param args The argument during the call of the request function\n * @param props The props passed to the state decorator\n * @param actions The actions available\n * @param notifyWarning If specified, a notify function to indicate that the action is a semi failure (use errorMessage / getErrorMessage otherwise).\n */\n errorSideEffects?: (ctx: ErrorSideEffectsInvocationContext<S, DS, F, P, A>) => void;\n\n /**\n * Retrieve the state to set as current data before the promise is resolved.\n * If the there's no reducer, this data will be used after the promise is done.\n */\n preEffects?: (ctx: InvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Retrieve the state to set as current data before the promise is resolved.\n * If the there's no reducer, this data will be used after the promise is done.\n */\n optimisticEffects?: (ctx: InvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Policy to apply when a call to an asynchronous action is done but a previous call is still not resolved.\n */\n conflictPolicy?: ConflictPolicy;\n\n /**\n * Get an identifier for an action call. Used only when conflictPolicy is ConflictPolicy.PARALLEL.\n * This information will be available in loadingMap. loadingMap[actionName] will be an array of promise identifiers.\n */\n getPromiseId?: (...args: Parameters<F>) => string;\n\n /**\n * Number of retries in case of error (failed to fetch).\n * Do not use this if you are creating objects...\n * Default value is 0 (no retry).\n */\n retryCount?: number;\n\n /**\n * Seed of delay between each retry in milliseconds.\n * The applied delay is retryDelaySeed * retry count.\n * Default value is 1000 (1 second).\n */\n retryDelaySeed?: number;\n\n /**\n * Function to test if the error will trigger an action retry or will fail directly.\n */\n isTriggerRetryError?: (e: Error) => boolean;\n};\n\nexport type AsyncActionPromise<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> = AsyncActionBase<\n S,\n F,\n A,\n P,\n DS,\n FxRes\n> & {\n /**\n * The request, returns a promise\n */\n getPromise: PromiseProvider<S, DS, F, A, P>;\n};\n\nexport type AsyncActionPromiseGet<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = AsyncActionBase<\n S,\n F,\n A,\n P,\n DS,\n FxRes\n> & {\n /**\n * The request, returns a promise that is a GET request.\n * A shortcut to set:\n * - retryCount: 3\n * - conflictPolicy: ConflictPolicy.REUSE\n */\n getGetPromise: PromiseProvider<S, DS, F, A, P>;\n};\n\nexport type AsyncAction<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> =\n | AsyncActionPromise<S, F, A, P, DS, FxRes>\n | AsyncActionPromiseGet<S, F, A, P, DS, FxRes>;\n\nexport type StoreAction<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> =\n | AsyncAction<S, F, A, P, DS, FxRes>\n | SimpleSyncAction<S, F, P, DS, FxRes>\n | SyncAction<S, F, A, P, DS, FxRes>;\n\n/**\n * S: The type of the state\n * A: The type of the actions to pass to the children (used to check keys only).\n */\nexport type StoreActions<S, A extends DecoratedActions, P = {}, DS = {}, FxRes = S> = {\n [Prop in keyof A]: StoreAction<S, A[Prop], A, P, DS, FxRes>;\n};\n\nexport type OnPropsChangeEffectsContext<S, DS, P> = ContextWithDerived<S, DS, P> & {\n indices: number[];\n index: number;\n isInit: boolean;\n};\n\nexport type OnPropsChangeSideEffectsContext<S, P, A, DS = {}> = OnPropsChangeEffectsContext<S, DS, P> & {\n actions: A;\n a: A;\n};\n\ntype DerivedStateOption<S, P, DS> = {\n [k in keyof DS]: {\n getDeps: (ctx: ContextBase<S, P>) => any[];\n get: (ctx: ContextBase<S, P>) => DS[k];\n };\n};\n\nexport type OnPropsChangeOptions<S, DS, A, P> = {\n onMount?: boolean;\n getDeps: (p: P) => any[];\n effects?: (ctx: OnPropsChangeEffectsContext<S, DS, P>) => S;\n sideEffects?: (ctx: OnPropsChangeSideEffectsContext<S, P, A>) => void;\n};\n\nexport type StoreOptions<S, A, P = {}, DS = {}> = {\n /**\n * The state decorator name. Use in debug traces to identify the useStateDecorator instance.\n */\n name?: string;\n\n /**\n * List of action names that are marked as loading at initial time.\n * If you must start your initial actions in a useSideEffect, a render is done before\n * first actions can be trigerred, some actions can be marked as loading at initial time.\n */\n initialActionsMarkedLoading?: (keyof A)[];\n\n /**\n * One or several configurations of inbound properties change managements.\n */\n onPropsChange?: OnPropsChangeOptions<S, DS, A, P> | OnPropsChangeOptions<S, DS, A, P>[];\n\n /**\n * The callback function called if an asynchronous function succeeded and a success messsage is defined.\n */\n notifySuccess?: NotifyFunc;\n\n /**\n * The callback function called if an asynchronous function fails and an error messsage is defined.\n */\n notifyError?: NotifyFunc;\n\n /**\n * The callback function injected in onDone and onFail of asynchronous functions to notify a semi success / failed request.\n */\n notifyWarning?: NotifyFunc;\n\n /**\n * Initial actions.\n */\n onMount?: (ctx: OnMountInvocationContext<S, A, P>) => void;\n\n /**\n * Callback on store destruction.\n */\n onUnmount?: (ctx: OnMountInvocationContext<S, A, P>) => Promise<any> | void;\n\n /**\n * Compute derived state\n */\n derivedState?: DerivedStateOption<S, P, DS>;\n};\n","function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nmodule.exports = _arrayWithHoles;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _iterableToArrayLimit(arr, i) {\n if (typeof Symbol === \"undefined\" || !(Symbol.iterator in Object(arr))) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nmodule.exports = _iterableToArrayLimit;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) {\n arr2[i] = arr[i];\n }\n\n return arr2;\n}\n\nmodule.exports = _arrayLikeToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","var arrayLikeToArray = require(\"./arrayLikeToArray.js\");\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}\n\nmodule.exports = _unsupportedIterableToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nmodule.exports = _nonIterableRest;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","var arrayWithHoles = require(\"./arrayWithHoles.js\");\n\nvar iterableToArrayLimit = require(\"./iterableToArrayLimit.js\");\n\nvar unsupportedIterableToArray = require(\"./unsupportedIterableToArray.js\");\n\nvar nonIterableRest = require(\"./nonIterableRest.js\");\n\nfunction _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}\n\nmodule.exports = _slicedToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nmodule.exports = _defineProperty;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","/*\n * Copyright 2019 Globalsport SAS\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\nimport { useEffect, useLayoutEffect, useMemo, useReducer, useRef } from 'react';\nimport {\n computeAsyncActionInput,\n createRef,\n isSyncAction,\n isAsyncAction,\n isSimpleSyncAction,\n TimeoutMap,\n PromiseMap,\n DEFAULT_PROMISE_ID,\n globalConfig,\n setGlobalConfig,\n GlobalConfig,\n ConflictActionsMap,\n buildOnMountInvocationContext,\n decorateSimpleSyncAction,\n decorateSyncAction,\n decorateAsyncAction,\n computeDerivedValues,\n DerivedState,\n onPropChange,\n runMiddlewares,\n buildLoadingMap,\n isLoadingImpl,\n} from './impl';\n\nimport {\n DecoratedActions,\n StoreActions,\n AsyncAction,\n SyncAction,\n SimpleSyncAction,\n InternalLoadingMap,\n LoadingMap,\n LoadingParallelMap,\n StoreOptions,\n AsyncActionPromise,\n InvocationContext,\n GetPromiseInvocationContext,\n EffectsInvocationContext,\n InvocationContextActions,\n WarningNotifyFunc,\n ErrorEffectsInvocationContext,\n OnMountInvocationContext,\n ContextBase,\n OnPropsChangeEffectsContext,\n ContextState,\n ConflictPolicy,\n Middleware,\n AbortActionCallback,\n MiddlewareFactory,\n MiddlewareStoreContext,\n LoadingProps,\n} from './types';\n\nexport {\n DecoratedActions,\n StoreActions,\n LoadingMap,\n StoreOptions,\n LoadingParallelMap,\n AsyncActionPromise as AsynchActionPromise,\n InvocationContext,\n GetPromiseInvocationContext,\n EffectsInvocationContext,\n InvocationContextActions,\n WarningNotifyFunc,\n ErrorEffectsInvocationContext,\n OnMountInvocationContext,\n ContextBase,\n OnPropsChangeEffectsContext,\n SyncAction,\n AsyncAction,\n SimpleSyncAction,\n ContextState,\n ConflictPolicy,\n GlobalConfig,\n Middleware,\n setGlobalConfig,\n LoadingProps,\n AbortActionCallback,\n};\n\nexport type IsLoadingFunc<A> = (...props: (keyof A | [keyof A, string])[]) => boolean;\ntype StateListenerUnregister = () => void;\n\nexport type StoreApi<S, A extends DecoratedActions, P, DS = {}> = {\n /**\n * The current store state (with derived state if any).\n */\n readonly state: S & DS;\n /**\n * The store decorator (ie. ready to use) actions.\n */\n readonly actions: A;\n /**\n * A boolean that indicates that at least one asynchronous action is loading.\n */\n readonly loading: boolean;\n /**\n * A map of loading actions map (computed on property access)\n */\n readonly loadingMap: LoadingMap<A>;\n /**\n * A map of parallel loading actions map (computed on property access)\n */\n readonly loadingParallelMap: LoadingParallelMap<A>;\n /**\n * Initializes the store with the specified props\n */\n init: (p: P) => void;\n /**\n * Update the store with the specified props\n */\n setProps: (p: P) => void;\n /**\n * Destroy the store\n */\n destroy: () => void;\n /**\n * Abort an asynchronous action marked as abortable.\n */\n abortAction: (actionName: keyof A, promiseId?: string) => boolean;\n /**\n * Add a store state change listener\n */\n addStateListener: (listener: StateListener<S, DS, A>) => StateListenerUnregister;\n /**\n * A function that takes a list of action names or a tuple of [action name, promiseId] and returns <code>true</code> if any action is loading.\n */\n isLoading: IsLoadingFunc<A>;\n\n getConfig: () => {\n getInitialState: (p: P) => S;\n options: StoreOptions<S, A, P, DS>;\n actions: StoreActions<S, A, P, DS>;\n };\n};\n\nexport type StateListenerContext<S, DS, A extends DecoratedActions> = S &\n DS &\n A &\n Pick<StoreApi<S, A, any, DS>, 'loading' | 'loadingMap' | 'isLoading' | 'abortAction'>;\n\nexport type StateListener<S, DS, A extends DecoratedActions> = (ctx: StateListenerContext<S, DS, A>) => void;\n\n// =============================\n//\n// STORE\n//\n// =============================\n\n/**\n * Create a new store.\n * @param getInitialState The state initialization function (using props)\n * @param actionsImpl The actions implementation (pure functions only).\n * @param options Options to configure the store\n * @returns a store.\n */\nexport function createStore<S, A extends DecoratedActions, P, DS = {}>(\n getInitialState: (p: P) => S,\n actionsImpl: StoreActions<S, A, P, DS>,\n options: StoreOptions<S, A, P, DS> = {},\n storeMiddlewares: MiddlewareFactory<S, A, P>[] = null\n): StoreApi<S, A, P, DS> {\n const stateRef = createRef<S>();\n const derivedStateRef = createRef<DerivedState<DS>>();\n const propsRef = createRef<P>();\n const actionsRef = createRef<A>();\n const timeoutRef = createRef<TimeoutMap<A>>();\n const loadingMapRef = createRef<InternalLoadingMap<A>>();\n const promisesRef = createRef<PromiseMap<A>>();\n const conflictActionsRef = createRef<ConflictActionsMap<A>>();\n const initializedRef = createRef(false);\n\n const middlewaresRef = createRef<Middleware<S, A, P>[]>([]);\n\n let stateListeners: Record<string, StateListener<S, DS, A>> = {};\n let stateListenerCount = 0;\n\n function addStateListener(listener: StateListener<S, DS, A>): () => void {\n const id = `${stateListenerCount++}`;\n stateListeners[id] = listener;\n return () => {\n delete stateListeners[id];\n };\n }\n\n function notifyStateListeners(newState: S, derivedState: DS) {\n const s = {\n ...newState,\n ...derivedState,\n };\n\n const ctx: StateListenerContext<S, DS, A> = {\n ...s,\n ...actionsRef.current,\n isLoading,\n abortAction,\n loading: isAnyLoading(),\n loadingMap: getLoadingMap(),\n };\n\n Object.keys(stateListeners).forEach((listenerId) => {\n stateListeners[listenerId](ctx);\n });\n }\n\n function setProps(p: P) {\n const oldProps = propsRef.current;\n\n propsRef.current = p;\n\n if (!initializedRef.current) {\n init(p);\n } else {\n onPropChange(stateRef, derivedStateRef, propsRef, oldProps, actionsRef, options, setState, false);\n }\n }\n\n /** Middleware only: sets the internal state, recompute derived state and notify listeners */\n function setInternalState(s: S) {\n stateRef.current = s;\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n notifyStateListeners(stateRef.current, derivedStateRef.current.state);\n }\n\n function init(p: P) {\n if (!initializedRef.current) {\n propsRef.current = p;\n initializedRef.current = true;\n stateRef.current = getInitialState(p);\n\n const initialActionSet = new Set(options?.initialActionsMarkedLoading);\n\n loadingMapRef.current = (Object.keys(actionsImpl) as (keyof A)[]).reduce<InternalLoadingMap<A>>((acc, name) => {\n acc[name] = initialActionSet.has(name) ? { [DEFAULT_PROMISE_ID]: true } : {};\n return acc;\n }, {});\n\n timeoutRef.current = {};\n promisesRef.current = {};\n conflictActionsRef.current = {};\n derivedStateRef.current = {\n state: null,\n deps: {},\n };\n\n // init middlewares\n middlewaresRef.current = [];\n const ctx: MiddlewareStoreContext<S, A, P> = {\n options,\n get state() {\n return stateRef.current;\n },\n actions: actionsImpl,\n setState: setInternalState,\n };\n const mapper = (m: MiddlewareFactory<S, A, P>) => {\n const middleware = m();\n middlewaresRef.current.push(middleware);\n middleware.init?.(ctx);\n };\n globalConfig.defaultMiddlewares?.forEach(mapper);\n storeMiddlewares?.forEach(mapper);\n // end init\n\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n\n // manage PropsChange with onMount\n onPropChange(stateRef, derivedStateRef, propsRef, null, actionsRef, options, setState, true);\n\n if (options?.onMount) {\n options.onMount(buildOnMountInvocationContext(stateRef, derivedStateRef, propsRef, actionsRef));\n }\n\n notifyStateListeners(stateRef.current, derivedStateRef.current.state);\n }\n }\n\n function destroy() {\n if (initializedRef.current) {\n options?.onUnmount?.(buildOnMountInvocationContext(stateRef, derivedStateRef, propsRef, actionsRef));\n\n propsRef.current = null;\n stateRef.current = null;\n loadingMapRef.current = null;\n promisesRef.current = null;\n conflictActionsRef.current = null;\n derivedStateRef.current = null;\n\n Object.keys(timeoutRef.current).forEach((name) => {\n clearTimeout(timeoutRef.current[name]);\n });\n\n timeoutRef.current = null;\n stateListeners = {};\n initializedRef.current = false;\n\n middlewaresRef.current.forEach((m) => {\n m.destroy?.();\n });\n\n middlewaresRef.current = [];\n }\n }\n\n function setState(\n newStateIn: S,\n newLoadingMapIn: InternalLoadingMap<A>,\n actionName: keyof A,\n actionType: 'preEffects' | 'effects' | 'errorEffects' | null,\n isAsync: boolean,\n actionCtx: any,\n propsChanged: boolean = false,\n init = false\n ) {\n let hasChanged = false;\n\n if (!initializedRef.current) {\n return;\n }\n\n let newLoadingMap = newLoadingMapIn;\n\n const oldLoading = isAsync\n ? isLoadingImpl(newLoadingMap || loadingMapRef.current, [actionName, actionCtx?.promiseId])\n : false;\n\n const { newState, newLoading } = runMiddlewares(\n middlewaresRef.current,\n stateRef.current,\n newStateIn,\n oldLoading,\n actionName,\n actionType,\n isAsync,\n actionCtx\n );\n\n if (newState != null) {\n hasChanged = true;\n stateRef.current = newState;\n }\n\n if (oldLoading !== newLoading) {\n newLoadingMap = buildLoadingMap(\n newLoadingMap,\n actionName,\n actionCtx?.promiseId || DEFAULT_PROMISE_ID,\n newLoading\n );\n if (Object.keys(newLoadingMap).length === 0) {\n newLoadingMap = undefined;\n }\n }\n\n if (newLoadingMap != null) {\n hasChanged = true;\n loadingMapRef.current = newLoadingMap;\n }\n\n if (hasChanged) {\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n if (!init) {\n notifyStateListeners(newState || stateRef.current, derivedStateRef.current.state);\n }\n } else if (propsChanged) {\n const derivedChanged = computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n if (derivedChanged && !init) {\n notifyStateListeners(newState || stateRef.current, derivedStateRef.current.state);\n }\n }\n }\n\n const keys = Object.keys(actionsImpl) as (keyof A)[];\n actionsRef.current = keys.reduce<A>((acc, actionName) => {\n const action = actionsImpl[actionName];\n if (isSimpleSyncAction(action)) {\n acc[actionName] = decorateSimpleSyncAction(\n actionName,\n action,\n stateRef,\n derivedStateRef,\n propsRef,\n initializedRef,\n setState\n ) as any;\n } else if (isAsyncAction(action)) {\n acc[actionName] = decorateAsyncAction({\n actionName,\n stateRef,\n derivedStateRef,\n propsRef,\n loadingMapRef,\n actionsRef,\n promisesRef,\n conflictActionsRef,\n initializedRef,\n options,\n setState,\n action: computeAsyncActionInput(action),\n }) as any;\n } else if (isSyncAction(action)) {\n acc[actionName] = decorateSyncAction(\n actionName,\n action,\n stateRef,\n derivedStateRef,\n propsRef,\n actionsRef,\n initializedRef,\n timeoutRef,\n options,\n setState\n ) as any;\n }\n\n return acc;\n }, {} as A);\n\n function isLoading<K extends keyof A>(...props: (K | [K, string])[]) {\n return isLoadingImpl(loadingMapRef.current, ...props);\n }\n\n function abortAction(actionName: keyof A, promiseId: string = DEFAULT_PROMISE_ID) {\n const abortController = promisesRef.current[actionName]?.[promiseId]?.abortController;\n\n let res = false;\n if (abortController) {\n abortController.abort();\n res = true;\n }\n\n return res;\n }\n\n function isAnyLoading() {\n if (initializedRef.current) {\n const loadingMap = loadingMapRef.current;\n return (\n Object.keys(loadingMap).find((actionName) => {\n const promises = loadingMap[actionName];\n return Object.keys(promises).find((pId) => !!promises[pId]);\n }) != null\n );\n }\n return null;\n }\n\n function getLoadingMap() {\n if (initializedRef.current) {\n const map = loadingMapRef.current;\n const keys = Object.keys(map) as (keyof A)[];\n return keys.reduce<LoadingMap<A>>((acc, actionName) => {\n acc[actionName] = Object.keys(map[actionName]).find((pId) => !!map[actionName][pId]) != null;\n return acc;\n }, {});\n }\n return null;\n }\n\n function getConfig() {\n return {\n getInitialState,\n options,\n actions: actionsImpl,\n };\n }\n\n return {\n getConfig,\n setProps,\n addStateListener,\n init,\n destroy,\n isLoading,\n abortAction,\n get actions() {\n return actionsRef.current;\n },\n get state() {\n if (initializedRef.current) {\n return {\n ...stateRef.current,\n ...derivedStateRef.current.state,\n };\n }\n return null;\n },\n get loading() {\n return isAnyLoading();\n },\n get loadingMap() {\n return getLoadingMap();\n },\n get loadingParallelMap() {\n if (initializedRef.current) {\n return loadingMapRef.current;\n }\n return null;\n },\n };\n}\n\n// =====================================\n//\n// REACT HOOKS\n//\n// =====================================\n\ntype useStoreSlice<S, A extends DecoratedActions, P, DS, SLICE> = (\n store: StoreApi<S, A, P, DS>,\n slicer: (ctx: StateListenerContext<S, DS, A>) => SLICE\n) => SLICE;\n\n/**\n * A react hook to get a state slice. Will be refresh if, and only if, one property of the slice has changed\n * @param store The store to listen to.\n * @param slicerFunc A function that returns a state slice\n * @param comparator An optional function to compare if slice property has changed (shallow test by default)\n * @returns The state slice.\n */\nexport function useStoreSlice<S, A extends DecoratedActions, P, DS, SLICE>(\n store: StoreApi<S, A, P, DS>,\n slicerFunc: (ctx: StateListenerContext<S, DS, A>) => SLICE\n): SLICE;\n\nexport function useStoreSlice<S, A extends DecoratedActions, P, DS, K extends keyof StateListenerContext<S, DS, A>>(\n store: StoreApi<S, A, P, DS>,\n properties: K[]\n): Pick<StateListenerContext<S, DS, A>, K>;\n\nexport function useStoreSlice<S, A extends DecoratedActions, P, DS>(store: StoreApi<S, A, P, DS>, funcOrArr: any) {\n const [, forceRefresh] = useReducer((s) => (s > 100 ? 0 : s + 1), 0);\n\n const slicerFunc = useMemo(\n () => (funcOrArr instanceof Function ? funcOrArr : (ctx: StateListenerContext<S, DS, A>) => pick(ctx, funcOrArr)),\n [funcOrArr]\n );\n\n const sliceRef = useRef<any>(null);\n if (sliceRef.current === null) {\n const s = store.state;\n sliceRef.current = slicerFunc({\n ...s,\n ...store.actions,\n actions: store.actions,\n loading: store.loading,\n isLoading: store.isLoading,\n abortAction: store.abortAction,\n loadingMap: store.loadingMap,\n });\n }\n\n useLayoutEffect(() => {\n const unregister = store.addStateListener((ctx) => {\n let hasChanged = false;\n\n const slice = slicerFunc(ctx);\n const prevSlice = sliceRef.current;\n const compare = globalConfig.comparator;\n\n hasChanged = prevSlice == null || !compare(slice, prevSlice);\n\n sliceRef.current = slice;\n\n if (hasChanged) {\n forceRefresh();\n }\n });\n\n return unregister;\n }, []);\n\n return sliceRef.current;\n}\n\n/**\n * Binds the store to this component.\n * Store will be destroyed when component is unmouted.\n * Props passed to actions will come from this components.\n * If store is configured to react of props changes, it will used passed props.\n * A store must be bound to only one React component.\n * This component will be refreshed for every change in the store.\n *\n * @param store The store to listen to.\n * @param props The parent component props\n * @returns The state, actions and isLoading function.\n */\nexport function useStore<S, A extends DecoratedActions, P, DS = {}>(store: StoreApi<S, A, P, DS>, props: P = null) {\n const [, forceRefresh] = useReducer((s) => (s > 100 ? 0 : s + 1), 0);\n\n const storeRef = useRef(store);\n\n store.setProps(props);\n\n useLayoutEffect(\n () =>\n storeRef.current.addStateListener(() => {\n forceRefresh();\n }),\n []\n );\n\n useEffect(() => () => store.destroy(), []);\n\n return {\n state: store.state,\n actions: store.actions,\n loading: store.loading,\n isLoading: store.isLoading,\n abortAction: store.abortAction,\n loadingMap: store.loadingMap,\n loadingParallelMap: store.loadingParallelMap,\n };\n}\n\n/**\n * Binds the store to this component.\n * Store will be destroyed when component is unmouted.\n * Props passed to actions will come from this components.\n * If store is configured to react of props changes, it will used passed props.\n * A store must be bound to only one React component.\n *\n * This component will NOT be refreshed for any change in the store.\n *\n * @param store The store to listen to.\n * @param props The parent component props\n */\nexport function useBindStore<S, A extends DecoratedActions, P, DS = {}>(store: StoreApi<S, A, P, DS>, props: P = null) {\n // access to store in debugger\n useRef(store);\n\n store.setProps(props);\n useEffect(() => {\n return () => store.destroy();\n }, []);\n return store;\n}\n\n/**\n * Creates and manages a local store.\n * @param getInitialState Function to compute initial state from props.\n * @param actionImpl Actions implementation.\n * @param props Owner component props to update state or react on prop changes\n * @param options The store options.\n * @returns The state, actions and isLoading function.\n */\nexport function useLocalStore<S, A extends DecoratedActions, P, DS = {}>(\n getInitialState: (p: P) => S,\n actionImpl: StoreActions<S, A, P, DS>,\n props?: P,\n options?: StoreOptions<S, A, P, DS>,\n middlewares?: MiddlewareFactory<S, A, P>[]\n) {\n const storeRef = useRef<StoreApi<S, A, P, DS>>();\n if (storeRef.current == null) {\n storeRef.current = createStore(getInitialState, actionImpl, options, middlewares);\n }\n\n return useStore(storeRef.current, props);\n}\n\nexport default useLocalStore;\n\n// ------------- UTILS\n\n/**\n * Creates a new object by picking properties to the object passed a first parameter\n * @param obj Object to pick properties from\n * @param props Property names\n * @returns a new object containing only picked properties\n */\nexport function pick<T, K extends keyof T>(obj: T, props: K[]): Pick<T, K> {\n return props.reduce((acc, p) => {\n if (obj.hasOwnProperty(p)) {\n acc[p] = obj[p];\n }\n return acc;\n }, {} as any);\n}\n\n/**\n * Returns a function that creates a new object by picking properties to the object passed as first parameter.\n * To be used in conjunction of <code>useStoreSlice</code> like in example:\n * const s = useStoreSlice(myStore, slice('list', 'addItem'));\n * @param props Property names\n * @returns a function to pick property from an passed object.\n */\nexport function slice<T, K extends keyof T>(...props: K[]): (obj: T) => Pick<T, K> {\n return (store: T) => pick(store, props);\n}\n"],"names":["ConflictPolicy","module","arr","Array","isArray","exports","i","Symbol","iterator","Object","_arr","_n","_d","_e","undefined","_s","_i","next","done","push","value","length","err","len","arr2","o","minLen","arrayLikeToArray","n","prototype","toString","call","slice","constructor","name","from","test","TypeError","arrayWithHoles","iterableToArrayLimit","unsupportedIterableToArray","nonIterableRest","obj","key","defineProperty","enumerable","configurable","writable","createStore","getInitialState","actionsImpl","options","storeMiddlewares","stateRef","createRef","derivedStateRef","propsRef","actionsRef","timeoutRef","loadingMapRef","promisesRef","conflictActionsRef","initializedRef","middlewaresRef","stateListeners","stateListenerCount","addStateListener","listener","id","notifyStateListeners","newState","derivedState","s","ctx","current","isLoading","abortAction","loading","isAnyLoading","loadingMap","getLoadingMap","keys","forEach","listenerId","setProps","p","oldProps","onPropChange","setState","init","setInternalState","computeDerivedValues","state","initialActionSet","Set","initialActionsMarkedLoading","reduce","acc","has","DEFAULT_PROMISE_ID","deps","actions","mapper","m","middleware","globalConfig","defaultMiddlewares","onMount","buildOnMountInvocationContext","destroy","onUnmount","clearTimeout","newStateIn","newLoadingMapIn","actionName","actionType","isAsync","actionCtx","propsChanged","hasChanged","newLoadingMap","oldLoading","isLoadingImpl","promiseId","runMiddlewares","newLoading","buildLoadingMap","derivedChanged","props","abortController","_promisesRef$current$","_promisesRef$current$2","res","abort","find","promises","pId","map","getConfig","action","isSimpleSyncAction","decorateSimpleSyncAction","isAsyncAction","decorateAsyncAction","computeAsyncActionInput","isSyncAction","decorateSyncAction","useStoreSlice","store","funcOrArr","useReducer","forceRefresh","slicerFunc","useMemo","Function","pick","sliceRef","useRef","useLayoutEffect","prevSlice","compare","comparator","useStore","storeRef","useEffect","loadingParallelMap","useBindStore","useLocalStore","actionImpl","middlewares","hasOwnProperty"],"mappings":"8qBAmCYA,mBC/BZC,UAJA,SAAyBC,GACvB,GAAIC,MAAMC,QAAQF,GAAM,OAAOA,GAIjCD,EAAOI,QAAiB,QAAIJ,EAAOI,QAASJ,sBAA4B,sBCsBxEA,UA3BA,SAA+BC,EAAKI,GAClC,GAAsB,oBAAXC,QAA4BA,OAAOC,YAAYC,OAAOP,GAAjE,CACA,IAAIQ,EAAO,GACPC,GAAK,EACLC,GAAK,EACLC,OAAKC,EAET,IACE,IAAK,IAAiCC,EAA7BC,EAAKd,EAAIK,OAAOC,cAAmBG,GAAMI,EAAKC,EAAGC,QAAQC,QAChER,EAAKS,KAAKJ,EAAGK,QAETd,GAAKI,EAAKW,SAAWf,GAH8CK,GAAK,IAK9E,MAAOW,GACPV,GAAK,EACLC,EAAKS,UAEL,IACOX,GAAsB,MAAhBK,EAAW,QAAWA,EAAW,iBAE5C,GAAIJ,EAAI,MAAMC,GAIlB,OAAOH,IAITT,EAAOI,QAAiB,QA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sBAKAA,gBA9BF,CAAYA,IAAAA"}
1
+ {"version":3,"file":"index.es.js","sources":["../src/types.ts","../node_modules/@babel/runtime/helpers/arrayWithHoles.js","../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js","../node_modules/@babel/runtime/helpers/arrayLikeToArray.js","../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js","../node_modules/@babel/runtime/helpers/nonIterableRest.js","../node_modules/@babel/runtime/helpers/slicedToArray.js","../node_modules/@babel/runtime/helpers/defineProperty.js","../src/index.ts"],"sourcesContent":["/*\n * Copyright 2019 Globalsport SAS\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\nexport type PromiseResult<Type> = Type extends Promise<infer X> ? X : null;\n\nexport type NotifyFunc = (msg: string) => void;\n\nexport type PromiseIdMap = { [promiseId: string]: boolean };\n\nexport type LoadingMap<A> = { [pId in keyof A]?: boolean };\nexport type LoadingParallelMap<A> = { [P in keyof A]?: PromiseIdMap };\nexport type InternalLoadingMap<A> = LoadingParallelMap<A>;\n\nexport type LoadingProps<A> = {\n loading: boolean;\n loadingMap: LoadingMap<A>;\n loadingParallelMap: LoadingParallelMap<A>;\n};\n\n// https://github.com/Microsoft/TypeScript/issues/15300\nexport interface DecoratedActions {\n [name: string]: (...args: any[]) => Promise<any> | void;\n}\n\n/**\n * The State decorator can manage only one asynchronous action of same name at a time.\n * This enum is enumertaing all the policies in such case.\n */\nexport enum ConflictPolicy {\n /**\n * Reject the promise.\n */\n REJECT = 'reject',\n\n /**\n * Return a resolved promise with no result.\n */\n IGNORE = 'ignore',\n\n /**\n * Execute only the last call that conflicts after the one ongoing.\n */\n KEEP_LAST = 'keepLast',\n\n /**\n * Execute all calls one after another.\n */\n KEEP_ALL = 'keepAll',\n\n /**\n * Execute all calls one after another.\n * @see getPromiseId\n */\n PARALLEL = 'parallel',\n\n /**\n * Reuse the ongoing promise if any and if possible (same arguments). Only for GET requests!\n */\n REUSE = 'reuse',\n}\n\nexport type PromiseProvider<S, DS, F extends (...args: any[]) => any, A, P> = (\n ctx: GetPromiseInvocationContext<S, DS, F, P, A>\n) => ReturnType<F> | null;\n\n/**\n * Simple form of a synchronous action.\n */\nexport type SimpleSyncAction<S, F extends (...args: any[]) => any, P, DS, FxRes = S> = (\n ctx: InvocationContext<S, DS, F, P>\n) => FxRes | null;\n\nexport type SyncAction<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = {\n /**\n * Function that update the state when the action is called.\n */\n effects?: (ctx: EffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Debounces the action if this parameter is defined.\n */\n debounceTimeout?: number;\n\n /**\n * Debounces the action side effects if this parameter is defined.\n */\n debounceSideEffectsTimeout?: number;\n\n /**\n * Function that calls side effects, ie. effects that are not changing the state directly.\n */\n sideEffects?: (ctx: SideEffectsInvocationContext<S, DS, F, P, A>) => void;\n};\n\n/**\n * Try to abort an action, if the action is <code>abortable</code>.\n * @param actionName The action name\n * @param promiseId If the action conflict type is <code>ConflictType.PARALLEL</code>, the identifier of the promise.\n * @returns <code>true</code> if the action is abortable and an action is ongoing, <code>false</code> otherwise.\n */\nexport type AbortActionCallback<A> = (actionName: keyof A, promiseId?: string) => boolean;\n\nexport type GetErrorMessage<S, DS, F extends (...args: any[]) => any, P> = (\n ctx: ErrorMessageInvocationContext<S, DS, F, P>\n) => string;\n\nexport type ContextState<S> = {\n state: S;\n s: S;\n};\n\nexport type ContextDerivedStateState<DS> = {\n derived: DS;\n ds: DS;\n};\n\nexport type ContextBase<S, P> = ContextState<S> & {\n props: P;\n p: P;\n};\n\nexport type ContextWithDerived<S, DS, P> = ContextBase<S, P> & ContextDerivedStateState<DS>;\n\nexport type InvocationContextActions<A> = {\n actions: A;\n a: A;\n};\n\nexport type WarningNotifyFunc = {\n notifyWarning?: NotifyFunc;\n};\n\nexport type InvocationContext<S, DS, F extends (...args: any[]) => any, P> = ContextWithDerived<S, DS, P> & {\n args: Parameters<F>;\n promiseId: string;\n};\n\nexport type EffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P> = InvocationContext<S, DS, F, P> & {\n result: PromiseResult<ReturnType<F>>;\n res: PromiseResult<ReturnType<F>>;\n};\n\nexport type GetPromiseInvocationContext<S, DS, F extends (...args: any[]) => any, P, A> = InvocationContextActions<A> &\n InvocationContext<S, DS, F, P> & {\n abortSignal: AbortSignal;\n };\n\nexport type ErrorEffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P> = InvocationContext<\n S,\n DS,\n F,\n P\n> & {\n error: Error;\n err: Error;\n};\n\nexport type SuccessMessageInvocationContext<S, DS, F extends (...args: any[]) => any, P> = EffectsInvocationContext<\n S,\n DS,\n F,\n P\n>;\nexport type ErrorMessageInvocationContext<S, DS, F extends (...args: any[]) => any, P> = ErrorEffectsInvocationContext<\n S,\n DS,\n F,\n P\n>;\n\nexport type SideEffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P, A> = EffectsInvocationContext<\n S,\n DS,\n F,\n P\n> &\n InvocationContextActions<A> &\n WarningNotifyFunc;\n\nexport type ErrorSideEffectsInvocationContext<\n S,\n DS,\n F extends (...args: any[]) => any,\n P,\n A\n> = ErrorEffectsInvocationContext<S, DS, F, P> & InvocationContextActions<A> & WarningNotifyFunc;\n\nexport type OnMountInvocationContext<S, A, P> = ContextBase<S, P> & InvocationContextActions<A>;\n\nexport type EffectsType = 'preEffects' | 'effects' | 'errorEffects' | 'optimisticEffects' | null;\n\nexport type MiddlewareActionContext<S, A, P> = {\n name: keyof A;\n type: EffectsType;\n isAsync: boolean;\n context: InvocationContext<S, any, any, P>;\n};\n\nexport type MiddlewareStoreContext<S, A extends DecoratedActions, P> = {\n actions: StoreActions<S, A, P, any, any>;\n state: S;\n setState: (s: S) => void;\n options: StoreOptions<S, A, P, any>;\n};\n\nexport type MiddlewareFactory<S, A extends DecoratedActions, P> = () => Middleware<S, A, P>;\n\n/**\n * A state change middleware.\n * Allow to listen and change a state change on the fly.\n */\nexport type Middleware<S, A extends DecoratedActions, P> = {\n /**\n * Initializes the middleware. Called when the store is initializing.\n */\n init: (storeContext: MiddlewareStoreContext<S, A, P>) => void;\n\n /**\n * Invoked on a state change has occurred and returns a new state or <code>null</code> if unchanged.\n */\n effects: (\n actionContext: MiddlewareActionContext<S, A, P>,\n oldState: S,\n newState: S,\n loading: boolean\n ) => null | {\n state: S;\n loading: boolean;\n };\n\n /**\n * Destroys the middleware. Called when the store is being destroyed.\n */\n destroy: () => void;\n};\n\nexport type AsyncActionBase<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = {\n /**\n * This action can be aborted. An abortSignal will be injected to the <code>promise</code> / <code>promiseGet</code>.\n */\n abortable?: boolean;\n\n /**\n * A function that provides the success message to pass to the notifySuccess function passed as property to the StateDecorator.\n */\n getSuccessMessage?: (ctx: SuccessMessageInvocationContext<S, DS, F, P>) => string;\n\n /**\n * A function that provides the error message to pass to the notifyError function passed as property to the StateDecorator.\n */\n getErrorMessage?: GetErrorMessage<S, DS, F, P>;\n\n /**\n * If set, called with the result of the promise to update the current state.\n */\n effects?: (ctx: EffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * If set, called with the error of the promise to update the current state.\n */\n errorEffects?: (ctx: ErrorEffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Whether reject the promise instead of handling it.\n */\n rejectPromiseOnError?: boolean;\n\n /**\n * Handle side effects when the request succeeded.\n * @param result The result of the request\n * @param newData The data after the reducer is applied\n * @param args The argument during the call of the request function\n * @param props The props passed to the state decorator\n * @param actions The actions available\n * @param notifyWarning If specified, a notify function to indicate that the action is a semi success (use successMessage / getSuccessMessage otherwise).\n */\n sideEffects?: (ctx: SideEffectsInvocationContext<S, DS, F, P, A>) => void;\n\n /**\n * Handle side effects when the request failed.\n * @param error The error of the request\n * @param args The argument during the call of the request function\n * @param props The props passed to the state decorator\n * @param actions The actions available\n * @param notifyWarning If specified, a notify function to indicate that the action is a semi failure (use errorMessage / getErrorMessage otherwise).\n */\n errorSideEffects?: (ctx: ErrorSideEffectsInvocationContext<S, DS, F, P, A>) => void;\n\n /**\n * Retrieve the state to set as current data before the promise is resolved.\n * If the there's no reducer, this data will be used after the promise is done.\n */\n preEffects?: (ctx: InvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Retrieve the state to set as current data before the promise is resolved.\n * If the there's no reducer, this data will be used after the promise is done.\n */\n optimisticEffects?: (ctx: InvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Policy to apply when a call to an asynchronous action is done but a previous call is still not resolved.\n */\n conflictPolicy?: ConflictPolicy;\n\n /**\n * Get an identifier for an action call. Used only when conflictPolicy is ConflictPolicy.PARALLEL.\n * This information will be available in loadingMap. loadingMap[actionName] will be an array of promise identifiers.\n */\n getPromiseId?: (...args: Parameters<F>) => string;\n\n /**\n * Number of retries in case of error (failed to fetch).\n * Do not use this if you are creating objects...\n * Default value is 0 (no retry).\n */\n retryCount?: number;\n\n /**\n * Seed of delay between each retry in milliseconds.\n * The applied delay is retryDelaySeed * retry count.\n * Default value is 1000 (1 second).\n */\n retryDelaySeed?: number;\n\n /**\n * Function to test if the error will trigger an action retry or will fail directly.\n */\n isTriggerRetryError?: (e: Error) => boolean;\n};\n\nexport type AsyncActionPromise<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> = AsyncActionBase<\n S,\n F,\n A,\n P,\n DS,\n FxRes\n> & {\n /**\n * The request, returns a promise\n */\n getPromise: PromiseProvider<S, DS, F, A, P>;\n};\n\nexport type AsyncActionPromiseGet<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = AsyncActionBase<\n S,\n F,\n A,\n P,\n DS,\n FxRes\n> & {\n /**\n * The request, returns a promise that is a GET request.\n * A shortcut to set:\n * - retryCount: 3\n * - conflictPolicy: ConflictPolicy.REUSE\n */\n getGetPromise: PromiseProvider<S, DS, F, A, P>;\n};\n\nexport type AsyncAction<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> =\n | AsyncActionPromise<S, F, A, P, DS, FxRes>\n | AsyncActionPromiseGet<S, F, A, P, DS, FxRes>;\n\nexport type StoreAction<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> =\n | AsyncAction<S, F, A, P, DS, FxRes>\n | SimpleSyncAction<S, F, P, DS, FxRes>\n | SyncAction<S, F, A, P, DS, FxRes>;\n\n/**\n * S: The type of the state\n * A: The type of the actions to pass to the children (used to check keys only).\n */\nexport type StoreActions<S, A extends DecoratedActions, P = {}, DS = {}, FxRes = S> = {\n [Prop in keyof A]: StoreAction<S, A[Prop], A, P, DS, FxRes>;\n};\n\nexport type OnPropsChangeEffectsContext<S, DS, P> = ContextWithDerived<S, DS, P> & {\n indices: number[];\n index: number;\n isInit: boolean;\n};\n\nexport type OnPropsChangeSideEffectsContext<S, P, A, DS = {}> = OnPropsChangeEffectsContext<S, DS, P> & {\n actions: A;\n a: A;\n};\n\ntype DerivedStateOption<S, P, DS> = {\n [k in keyof DS]: {\n getDeps: (ctx: ContextBase<S, P>) => any[];\n get: (ctx: ContextBase<S, P>) => DS[k];\n };\n};\n\nexport type OnPropsChangeOptions<S, DS, A, P> = {\n onMount?: boolean;\n getDeps: (p: P) => any[];\n effects?: (ctx: OnPropsChangeEffectsContext<S, DS, P>) => S;\n sideEffects?: (ctx: OnPropsChangeSideEffectsContext<S, P, A>) => void;\n};\n\nexport type StoreOptions<S, A, P = {}, DS = {}> = {\n /**\n * The state decorator name. Use in debug traces to identify the useStateDecorator instance.\n */\n name?: string;\n\n /**\n * List of action names that are marked as loading at initial time.\n * If you must start your initial actions in a useSideEffect, a render is done before\n * first actions can be trigerred, some actions can be marked as loading at initial time.\n */\n initialActionsMarkedLoading?: (keyof A)[];\n\n /**\n * One or several configurations of inbound properties change managements.\n */\n onPropsChange?: OnPropsChangeOptions<S, DS, A, P> | OnPropsChangeOptions<S, DS, A, P>[];\n\n /**\n * The callback function called if an asynchronous function succeeded and a success messsage is defined.\n */\n notifySuccess?: NotifyFunc;\n\n /**\n * The callback function called if an asynchronous function fails and an error messsage is defined.\n */\n notifyError?: NotifyFunc;\n\n /**\n * The callback function injected in onDone and onFail of asynchronous functions to notify a semi success / failed request.\n */\n notifyWarning?: NotifyFunc;\n\n /**\n * Initial actions.\n */\n onMount?: (ctx: OnMountInvocationContext<S, A, P>) => void;\n\n /**\n * Callback on store destruction.\n */\n onUnmount?: (ctx: OnMountInvocationContext<S, A, P>) => Promise<any> | void;\n\n /**\n * Compute derived state\n */\n derivedState?: DerivedStateOption<S, P, DS>;\n};\n","function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nmodule.exports = _arrayWithHoles;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _iterableToArrayLimit(arr, i) {\n if (typeof Symbol === \"undefined\" || !(Symbol.iterator in Object(arr))) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nmodule.exports = _iterableToArrayLimit;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) {\n arr2[i] = arr[i];\n }\n\n return arr2;\n}\n\nmodule.exports = _arrayLikeToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","var arrayLikeToArray = require(\"./arrayLikeToArray.js\");\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}\n\nmodule.exports = _unsupportedIterableToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nmodule.exports = _nonIterableRest;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","var arrayWithHoles = require(\"./arrayWithHoles.js\");\n\nvar iterableToArrayLimit = require(\"./iterableToArrayLimit.js\");\n\nvar unsupportedIterableToArray = require(\"./unsupportedIterableToArray.js\");\n\nvar nonIterableRest = require(\"./nonIterableRest.js\");\n\nfunction _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}\n\nmodule.exports = _slicedToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nmodule.exports = _defineProperty;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","/*\n * Copyright 2019 Globalsport SAS\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\nimport { Context, useContext, useEffect, useLayoutEffect, useMemo, useReducer, useRef } from 'react';\nimport {\n computeAsyncActionInput,\n createRef,\n isSyncAction,\n isAsyncAction,\n isSimpleSyncAction,\n TimeoutMap,\n PromiseMap,\n DEFAULT_PROMISE_ID,\n globalConfig,\n setGlobalConfig,\n GlobalConfig,\n ConflictActionsMap,\n buildOnMountInvocationContext,\n decorateSimpleSyncAction,\n decorateSyncAction,\n decorateAsyncAction,\n computeDerivedValues,\n DerivedState,\n onPropChange,\n runMiddlewares,\n buildLoadingMap,\n isLoadingImpl,\n} from './impl';\n\nimport {\n DecoratedActions,\n StoreActions,\n AsyncAction,\n SyncAction,\n SimpleSyncAction,\n InternalLoadingMap,\n LoadingMap,\n LoadingParallelMap,\n StoreOptions,\n AsyncActionPromise,\n InvocationContext,\n GetPromiseInvocationContext,\n EffectsInvocationContext,\n InvocationContextActions,\n WarningNotifyFunc,\n ErrorEffectsInvocationContext,\n OnMountInvocationContext,\n ContextBase,\n OnPropsChangeEffectsContext,\n ContextState,\n ConflictPolicy,\n Middleware,\n AbortActionCallback,\n MiddlewareFactory,\n MiddlewareStoreContext,\n LoadingProps,\n} from './types';\n\nexport {\n DecoratedActions,\n StoreActions,\n LoadingMap,\n StoreOptions,\n LoadingParallelMap,\n AsyncActionPromise as AsynchActionPromise,\n InvocationContext,\n GetPromiseInvocationContext,\n EffectsInvocationContext,\n InvocationContextActions,\n WarningNotifyFunc,\n ErrorEffectsInvocationContext,\n OnMountInvocationContext,\n ContextBase,\n OnPropsChangeEffectsContext,\n SyncAction,\n AsyncAction,\n SimpleSyncAction,\n ContextState,\n ConflictPolicy,\n GlobalConfig,\n Middleware,\n setGlobalConfig,\n LoadingProps,\n AbortActionCallback,\n};\n\nexport type IsLoadingFunc<A> = (...props: (keyof A | [keyof A, string])[]) => boolean;\ntype StateListenerUnregister = () => void;\n\nexport type StoreApi<S, A extends DecoratedActions, P, DS = {}> = {\n /**\n * The current store state (with derived state if any).\n */\n readonly state: S & DS;\n /**\n * The store decorator (ie. ready to use) actions.\n */\n readonly actions: A;\n /**\n * A boolean that indicates that at least one asynchronous action is loading.\n */\n readonly loading: boolean;\n /**\n * A map of loading actions map (computed on property access)\n */\n readonly loadingMap: LoadingMap<A>;\n /**\n * A map of parallel loading actions map (computed on property access)\n */\n readonly loadingParallelMap: LoadingParallelMap<A>;\n /**\n * Initializes the store with the specified props\n */\n init: (p: P) => void;\n /**\n * Update the store with the specified props\n */\n setProps: (p: P) => void;\n /**\n * Destroy the store\n */\n destroy: () => void;\n /**\n * Abort an asynchronous action marked as abortable.\n */\n abortAction: (actionName: keyof A, promiseId?: string) => boolean;\n /**\n * Add a store state change listener\n */\n addStateListener: (listener: StateListener<S, DS, A>) => StateListenerUnregister;\n /**\n * A function that takes a list of action names or a tuple of [action name, promiseId] and returns <code>true</code> if any action is loading.\n */\n isLoading: IsLoadingFunc<A>;\n\n getConfig: () => {\n getInitialState: (p: P) => S;\n options: StoreOptions<S, A, P, DS>;\n actions: StoreActions<S, A, P, DS>;\n };\n};\n\nexport type StateListenerContext<S, DS, A extends DecoratedActions> = S &\n DS &\n A &\n Pick<StoreApi<S, A, any, DS>, 'loading' | 'loadingMap' | 'isLoading' | 'abortAction'>;\n\nexport type StateListener<S, DS, A extends DecoratedActions> = (ctx: StateListenerContext<S, DS, A>) => void;\n\n// =============================\n//\n// STORE\n//\n// =============================\n\n/**\n * Create a new store.\n * @param getInitialState The state initialization function (using props)\n * @param actionsImpl The actions implementation (pure functions only).\n * @param options Options to configure the store\n * @returns a store.\n */\nexport function createStore<S, A extends DecoratedActions, P, DS = {}>(\n getInitialState: (p: P) => S,\n actionsImpl: StoreActions<S, A, P, DS>,\n options: StoreOptions<S, A, P, DS> = {},\n storeMiddlewares: MiddlewareFactory<S, A, P>[] = null\n): StoreApi<S, A, P, DS> {\n const stateRef = createRef<S>();\n const derivedStateRef = createRef<DerivedState<DS>>();\n const propsRef = createRef<P>();\n const actionsRef = createRef<A>();\n const timeoutRef = createRef<TimeoutMap<A>>();\n const loadingMapRef = createRef<InternalLoadingMap<A>>();\n const promisesRef = createRef<PromiseMap<A>>();\n const conflictActionsRef = createRef<ConflictActionsMap<A>>();\n const initializedRef = createRef(false);\n\n const middlewaresRef = createRef<Middleware<S, A, P>[]>([]);\n\n let stateListeners: Record<string, StateListener<S, DS, A>> = {};\n let stateListenerCount = 0;\n\n function addStateListener(listener: StateListener<S, DS, A>): () => void {\n const id = `${stateListenerCount++}`;\n stateListeners[id] = listener;\n return () => {\n delete stateListeners[id];\n };\n }\n\n function notifyStateListeners(newState: S, derivedState: DS) {\n const s = {\n ...newState,\n ...derivedState,\n };\n\n const ctx: StateListenerContext<S, DS, A> = {\n ...s,\n ...actionsRef.current,\n isLoading,\n abortAction,\n loading: isAnyLoading(),\n loadingMap: getLoadingMap(),\n };\n\n Object.keys(stateListeners).forEach((listenerId) => {\n stateListeners[listenerId](ctx);\n });\n }\n\n function setProps(p: P) {\n const oldProps = propsRef.current;\n\n propsRef.current = p;\n\n if (!initializedRef.current) {\n init(p);\n } else {\n onPropChange(stateRef, derivedStateRef, propsRef, oldProps, actionsRef, options, setState, false);\n }\n }\n\n /** Middleware only: sets the internal state, recompute derived state and notify listeners */\n function setInternalState(s: S) {\n stateRef.current = s;\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n notifyStateListeners(stateRef.current, derivedStateRef.current.state);\n }\n\n function init(p: P) {\n if (!initializedRef.current) {\n propsRef.current = p;\n initializedRef.current = true;\n stateRef.current = getInitialState(p);\n\n const initialActionSet = new Set(options?.initialActionsMarkedLoading);\n\n loadingMapRef.current = (Object.keys(actionsImpl) as (keyof A)[]).reduce<InternalLoadingMap<A>>((acc, name) => {\n acc[name] = initialActionSet.has(name) ? { [DEFAULT_PROMISE_ID]: true } : {};\n return acc;\n }, {});\n\n timeoutRef.current = {};\n promisesRef.current = {};\n conflictActionsRef.current = {};\n derivedStateRef.current = {\n state: null,\n deps: {},\n };\n\n // init middlewares\n middlewaresRef.current = [];\n const ctx: MiddlewareStoreContext<S, A, P> = {\n options,\n get state() {\n return stateRef.current;\n },\n actions: actionsImpl,\n setState: setInternalState,\n };\n const mapper = (m: MiddlewareFactory<S, A, P>) => {\n const middleware = m();\n middlewaresRef.current.push(middleware);\n middleware.init?.(ctx);\n };\n globalConfig.defaultMiddlewares?.forEach(mapper);\n storeMiddlewares?.forEach(mapper);\n // end init\n\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n\n // manage PropsChange with onMount\n onPropChange(stateRef, derivedStateRef, propsRef, null, actionsRef, options, setState, true);\n\n if (options?.onMount) {\n options.onMount(buildOnMountInvocationContext(stateRef, derivedStateRef, propsRef, actionsRef));\n }\n\n notifyStateListeners(stateRef.current, derivedStateRef.current.state);\n }\n }\n\n function destroy() {\n if (initializedRef.current) {\n options?.onUnmount?.(buildOnMountInvocationContext(stateRef, derivedStateRef, propsRef, actionsRef));\n\n propsRef.current = null;\n stateRef.current = null;\n loadingMapRef.current = null;\n promisesRef.current = null;\n conflictActionsRef.current = null;\n derivedStateRef.current = null;\n\n Object.keys(timeoutRef.current).forEach((name) => {\n clearTimeout(timeoutRef.current[name]);\n });\n\n timeoutRef.current = null;\n stateListeners = {};\n initializedRef.current = false;\n\n middlewaresRef.current.forEach((m) => {\n m.destroy?.();\n });\n\n middlewaresRef.current = [];\n }\n }\n\n function setState(\n newStateIn: S,\n newLoadingMapIn: InternalLoadingMap<A>,\n actionName: keyof A,\n actionType: 'preEffects' | 'effects' | 'errorEffects' | null,\n isAsync: boolean,\n actionCtx: any,\n propsChanged: boolean = false,\n init = false\n ) {\n let hasChanged = false;\n\n if (!initializedRef.current) {\n return;\n }\n\n let newLoadingMap = newLoadingMapIn;\n\n const oldLoading = isAsync\n ? isLoadingImpl(newLoadingMap || loadingMapRef.current, [actionName, actionCtx?.promiseId])\n : false;\n\n const { newState, newLoading } = runMiddlewares(\n middlewaresRef.current,\n stateRef.current,\n newStateIn,\n oldLoading,\n actionName,\n actionType,\n isAsync,\n actionCtx\n );\n\n if (newState != null) {\n hasChanged = true;\n stateRef.current = newState;\n }\n\n if (oldLoading !== newLoading) {\n newLoadingMap = buildLoadingMap(\n newLoadingMap,\n actionName,\n actionCtx?.promiseId || DEFAULT_PROMISE_ID,\n newLoading\n );\n if (Object.keys(newLoadingMap).length === 0) {\n newLoadingMap = undefined;\n }\n }\n\n if (newLoadingMap != null) {\n hasChanged = true;\n loadingMapRef.current = newLoadingMap;\n }\n\n if (hasChanged) {\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n if (!init) {\n notifyStateListeners(newState || stateRef.current, derivedStateRef.current.state);\n }\n } else if (propsChanged) {\n const derivedChanged = computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n if (derivedChanged && !init) {\n notifyStateListeners(newState || stateRef.current, derivedStateRef.current.state);\n }\n }\n }\n\n const keys = Object.keys(actionsImpl) as (keyof A)[];\n actionsRef.current = keys.reduce<A>((acc, actionName) => {\n const action = actionsImpl[actionName];\n if (isSimpleSyncAction(action)) {\n acc[actionName] = decorateSimpleSyncAction(\n actionName,\n action,\n stateRef,\n derivedStateRef,\n propsRef,\n initializedRef,\n setState\n ) as any;\n } else if (isAsyncAction(action)) {\n acc[actionName] = decorateAsyncAction({\n actionName,\n stateRef,\n derivedStateRef,\n propsRef,\n loadingMapRef,\n actionsRef,\n promisesRef,\n conflictActionsRef,\n initializedRef,\n options,\n setState,\n action: computeAsyncActionInput(action),\n }) as any;\n } else if (isSyncAction(action)) {\n acc[actionName] = decorateSyncAction(\n actionName,\n action,\n stateRef,\n derivedStateRef,\n propsRef,\n actionsRef,\n initializedRef,\n timeoutRef,\n options,\n setState\n ) as any;\n }\n\n return acc;\n }, {} as A);\n\n function isLoading<K extends keyof A>(...props: (K | [K, string])[]) {\n return isLoadingImpl(loadingMapRef.current, ...props);\n }\n\n function abortAction(actionName: keyof A, promiseId: string = DEFAULT_PROMISE_ID) {\n const abortController = promisesRef.current[actionName]?.[promiseId]?.abortController;\n\n let res = false;\n if (abortController) {\n abortController.abort();\n res = true;\n }\n\n return res;\n }\n\n function isAnyLoading() {\n if (initializedRef.current) {\n const loadingMap = loadingMapRef.current;\n return (\n Object.keys(loadingMap).find((actionName) => {\n const promises = loadingMap[actionName];\n return Object.keys(promises).find((pId) => !!promises[pId]);\n }) != null\n );\n }\n return null;\n }\n\n function getLoadingMap() {\n if (initializedRef.current) {\n const map = loadingMapRef.current;\n const keys = Object.keys(map) as (keyof A)[];\n return keys.reduce<LoadingMap<A>>((acc, actionName) => {\n acc[actionName] = Object.keys(map[actionName]).find((pId) => !!map[actionName][pId]) != null;\n return acc;\n }, {});\n }\n return null;\n }\n\n function getConfig() {\n return {\n getInitialState,\n options,\n actions: actionsImpl,\n };\n }\n\n return {\n getConfig,\n setProps,\n addStateListener,\n init,\n destroy,\n isLoading,\n abortAction,\n get actions() {\n return actionsRef.current;\n },\n get state() {\n if (initializedRef.current) {\n return {\n ...stateRef.current,\n ...derivedStateRef.current.state,\n };\n }\n return null;\n },\n get loading() {\n return isAnyLoading();\n },\n get loadingMap() {\n return getLoadingMap();\n },\n get loadingParallelMap() {\n if (initializedRef.current) {\n return loadingMapRef.current;\n }\n return null;\n },\n };\n}\n\n// =====================================\n//\n// REACT HOOKS\n//\n// =====================================\n\ntype useStoreSlice<S, A extends DecoratedActions, P, DS, SLICE> = (\n store: StoreApi<S, A, P, DS>,\n slicer: (ctx: StateListenerContext<S, DS, A>) => SLICE\n) => SLICE;\n\n/**\n * A react hook to get a state slice. Will be refresh if, and only if, one property of the slice has changed\n * @param store The store to listen to.\n * @param slicerFunc A function that returns a state slice\n * @returns The state slice.\n */\nexport function useStoreSlice<S, A extends DecoratedActions, P, DS, SLICE>(\n store: StoreApi<S, A, P, DS>,\n slicerFunc: (ctx: StateListenerContext<S, DS, A>) => SLICE\n): SLICE;\n\n/**\n * A react hook to get a state slice. Will be refresh if, and only if, one property of the slice has changed\n * @param store The store to listen to.\n * @param properties list of properties to extract from store\n * @returns The state slice.\n */\nexport function useStoreSlice<\n S,\n A extends DecoratedActions,\n P,\n DS,\n K extends keyof StateListenerContext<S, DS, A>,\n KL extends keyof A\n>(\n store: StoreApi<S, A, P, DS>,\n properties: K[],\n loadingProps?: KL[]\n): Pick<StateListenerContext<S, DS, A>, K> & { loadingMap: LoadingMap<Pick<A, KL>> };\n\nexport function useStoreSlice<S, A extends DecoratedActions, P, DS>(\n store: StoreApi<S, A, P, DS>,\n funcOrArr: any,\n loadingProps?: any\n) {\n const [, forceRefresh] = useReducer((s) => (s > 100 ? 0 : s + 1), 0);\n\n const slicerFunc = useMemo(\n () => (funcOrArr instanceof Function ? funcOrArr : (ctx: StateListenerContext<S, DS, A>) => pick(ctx, funcOrArr)),\n [funcOrArr]\n );\n\n const loadingMapSlicer = useMemo(() => {\n return (ctx: StateListenerContext<S, DS, A>) =>\n loadingProps != null && loadingProps.length > 0 ? pick(ctx.loadingMap, loadingProps) : null;\n }, [loadingProps]);\n\n const sliceRef = useRef<any>(null);\n const loadingMapRef = useRef<LoadingMap<A>>(null);\n\n if (sliceRef.current === null) {\n const ctx = {\n ...store.state,\n ...store.actions,\n ...pick(store, ['loading', 'isLoading', 'abortAction', 'loadingMap']),\n };\n sliceRef.current = slicerFunc(ctx);\n loadingMapRef.current = loadingMapSlicer(ctx);\n }\n\n useLayoutEffect(() => {\n const unregister = store.addStateListener((ctx) => {\n let hasChanged = false;\n\n const slice = slicerFunc(ctx);\n const loadingSlice = loadingMapSlicer(ctx);\n const prevSlice = sliceRef.current;\n const compare = globalConfig.comparator;\n\n hasChanged = prevSlice == null || !compare(slice, prevSlice) || !compare(loadingSlice, loadingMapRef.current);\n\n sliceRef.current = slice;\n loadingMapRef.current = loadingSlice;\n\n if (hasChanged) {\n forceRefresh();\n }\n });\n\n return unregister;\n }, []);\n\n const slice = sliceRef.current;\n const loadingSlice = loadingMapRef.current;\n\n return loadingSlice == null ? slice : { ...slice, loadingMap: loadingSlice };\n}\n\n/**\n * A react hook to get a state slice from a store context.\n * The component be refreshed if, and only if, one property of the slice has changed.\n * @param store The store to listen to.\n * @param slicerFunc A function that returns a state slice\n * @returns The state slice.\n */\nexport function useStoreContextSlice<S, A extends DecoratedActions, P, DS, SLICE>(\n storeContext: Context<StoreApi<S, A, P, DS>>,\n slicerFunc: (ctx: StateListenerContext<S, DS, A>) => SLICE\n): SLICE;\n\n/**\n * A react hook to get a state slice from a store context.\n * The component will be refreshed if, and only if, one property of the slice has changed.\n * @param store The store to listen to.\n * @param properties list of properties to extract from store\n * @param loadingFlags list of action names to extract their loading state from store (available in loadingMap).\n * @returns The state slice.\n */\nexport function useStoreContextSlice<\n S,\n A extends DecoratedActions,\n P,\n DS,\n K extends keyof StateListenerContext<S, DS, A>,\n KL extends keyof A\n>(\n storeContext: Context<StoreApi<S, A, P, DS>>,\n properties: K[],\n loadingProps?: KL[]\n): Pick<StateListenerContext<S, DS, A>, K> & { loadingMap: LoadingMap<Pick<A, KL>> };\n\nexport function useStoreContextSlice<S, A extends DecoratedActions, P, DS>(\n storeContext: Context<StoreApi<S, A, P, DS>>,\n funcOrArr: any,\n loadingProps?: any\n) {\n const store = useContext(storeContext);\n return useStoreSlice(store, funcOrArr, loadingProps);\n}\n\n/**\n * Binds the store to this component.\n * Store will NOT be destroyed when component is unmouted.\n * Props passed to actions will come from this components.\n * If store is configured to react of props changes, it will used passed props.\n * The component will be refreshed for every change in the store.\n *\n * @param store The store to listen to.\n * @param props The parent component props\n * @returns The state, actions and isLoading function.\n */\nexport function useStore<S, A extends DecoratedActions, P, DS = {}>(store: StoreApi<S, A, P, DS>, props: P = null) {\n const [, forceRefresh] = useReducer((s) => (s > 100 ? 0 : s + 1), 0);\n\n const storeRef = useRef(store);\n\n store.setProps(props);\n\n useLayoutEffect(\n () =>\n storeRef.current.addStateListener(() => {\n forceRefresh();\n }),\n []\n );\n\n return {\n state: store.state,\n actions: store.actions,\n loading: store.loading,\n isLoading: store.isLoading,\n abortAction: store.abortAction,\n loadingMap: store.loadingMap,\n loadingParallelMap: store.loadingParallelMap,\n };\n}\n\n/**\n * Binds the store to this component.\n * Store will be destroyed when component is unmouted.\n * Props passed to actions will come from this components.\n * If store is configured to react of props changes, it will used passed props.\n * A store must be bound to only one React component.\n *\n * The component will NOT be refreshed for any change in the store.\n *\n * @param store The store to listen to.\n * @param props The parent component props\n * @deprecated Do not bind an instance to a component or use useGetLocalStore to create a store local to a component.\n */\nexport function useBindStore<S, A extends DecoratedActions, P, DS = {}>(store: StoreApi<S, A, P, DS>, props: P = null) {\n // access to store in debugger\n useRef(store);\n\n store.setProps(props);\n\n useEffect(\n () => () => {\n store.destroy();\n },\n []\n );\n return store;\n}\n\n/**\n * Creates a store as a ref to the owner component.\n * Store WILL be destroyed when component is unmouted.\n * Props passed to actions will come from owner components.\n * If store is configured to react of props changes, it will used passed props.\n *\n * This component will NOT be refreshed for any change in the store.\n *\n * @param getInitialState Function to compute initial state from props.\n * @param actionImpl Actions implementation.\n * @param props Owner component props to update state or react on prop changes\n * @param options The store options.\n * @returns store\n */\nexport function useGetLocalStore<S, A extends DecoratedActions, P, DS = {}>(\n getInitialState: (p: P) => S,\n actionImpl: StoreActions<S, A, P, DS>,\n props?: P,\n options?: StoreOptions<S, A, P, DS>,\n middlewares?: MiddlewareFactory<S, A, P>[]\n) {\n // access to store in debugger\n const storeRef = useRef<StoreApi<S, A, P, DS>>();\n if (storeRef.current == null) {\n storeRef.current = createStore(getInitialState, actionImpl, options, middlewares);\n }\n\n const store = storeRef.current;\n store.setProps(props);\n\n useEffect(\n () => () => {\n store.destroy();\n },\n []\n );\n\n return store;\n}\n\n/**\n * Creates and manages a local store.\n * The component will be refreshed for every change in the store.\n * Store will NOT be destroyed when component is unmouted.\n *\n * @param getInitialState Function to compute initial state from props.\n * @param actionImpl Actions implementation.\n * @param props Owner component props to update state or react on prop changes\n * @param options The store options.\n * @returns The state, actions and isLoading function.\n */\nexport function useLocalStore<S, A extends DecoratedActions, P, DS = {}>(\n getInitialState: (p: P) => S,\n actionImpl: StoreActions<S, A, P, DS>,\n props?: P,\n options?: StoreOptions<S, A, P, DS>,\n middlewares?: MiddlewareFactory<S, A, P>[]\n) {\n const storeRef = useRef<StoreApi<S, A, P, DS>>();\n if (storeRef.current == null) {\n storeRef.current = createStore(getInitialState, actionImpl, options, middlewares);\n }\n\n useEffect(\n () => () => {\n storeRef.current?.destroy();\n },\n []\n );\n\n return useStore(storeRef.current, props);\n}\n\nexport default useLocalStore;\n\n// ------------- UTILS\n\n/**\n * Creates a new object by picking properties to the object passed a first parameter\n * @param obj Object to pick properties from\n * @param props Property names\n * @returns a new object containing only picked properties\n */\nexport function pick<T, K extends keyof T>(obj: T, props: K[]): Pick<T, K> {\n return props.reduce((acc, p) => {\n if (obj.hasOwnProperty(p)) {\n acc[p] = obj[p];\n }\n return acc;\n }, {} as any);\n}\n\n/**\n * Returns a function that creates a new object by picking properties to the object passed as first parameter.\n * To be used in conjunction of <code>useStoreSlice</code> like in example:\n * const s = useStoreSlice(myStore, slice('list', 'addItem'));\n * @param props Property names\n * @returns a function to pick property from an passed object.\n */\nexport function slice<T, K extends keyof T>(...props: K[]): (obj: T) => Pick<T, K> {\n return (store: T) => pick(store, props);\n}\n"],"names":["ConflictPolicy","module","arr","Array","isArray","exports","i","Symbol","iterator","Object","_arr","_n","_d","_e","undefined","_s","_i","next","done","push","value","length","err","len","arr2","o","minLen","arrayLikeToArray","n","prototype","toString","call","slice","constructor","name","from","test","TypeError","arrayWithHoles","iterableToArrayLimit","unsupportedIterableToArray","nonIterableRest","obj","key","defineProperty","enumerable","configurable","writable","createStore","getInitialState","actionsImpl","options","storeMiddlewares","stateRef","createRef","derivedStateRef","propsRef","actionsRef","timeoutRef","loadingMapRef","promisesRef","conflictActionsRef","initializedRef","middlewaresRef","stateListeners","stateListenerCount","addStateListener","listener","id","notifyStateListeners","newState","derivedState","s","ctx","current","isLoading","abortAction","loading","isAnyLoading","loadingMap","getLoadingMap","keys","forEach","listenerId","setProps","p","oldProps","onPropChange","setState","init","setInternalState","computeDerivedValues","state","initialActionSet","Set","initialActionsMarkedLoading","reduce","acc","has","DEFAULT_PROMISE_ID","deps","actions","mapper","m","middleware","globalConfig","defaultMiddlewares","onMount","buildOnMountInvocationContext","destroy","onUnmount","clearTimeout","newStateIn","newLoadingMapIn","actionName","actionType","isAsync","actionCtx","propsChanged","hasChanged","newLoadingMap","oldLoading","isLoadingImpl","promiseId","runMiddlewares","newLoading","buildLoadingMap","derivedChanged","props","abortController","_promisesRef$current$","_promisesRef$current$2","res","abort","find","promises","pId","map","getConfig","action","isSimpleSyncAction","decorateSimpleSyncAction","isAsyncAction","decorateAsyncAction","computeAsyncActionInput","isSyncAction","decorateSyncAction","useStoreSlice","store","funcOrArr","loadingProps","useReducer","forceRefresh","slicerFunc","useMemo","Function","pick","loadingMapSlicer","sliceRef","useRef","useLayoutEffect","loadingSlice","prevSlice","compare","comparator","useStoreContextSlice","storeContext","useContext","useStore","storeRef","loadingParallelMap","useBindStore","useEffect","useGetLocalStore","actionImpl","middlewares","useLocalStore","hasOwnProperty"],"mappings":"8rBAmCYA,mBC/BZC,UAJA,SAAyBC,GACvB,GAAIC,MAAMC,QAAQF,GAAM,OAAOA,GAIjCD,EAAOI,QAAiB,QAAIJ,EAAOI,QAASJ,sBAA4B,sBCsBxEA,UA3BA,SAA+BC,EAAKI,GAClC,GAAsB,oBAAXC,QAA4BA,OAAOC,YAAYC,OAAOP,GAAjE,CACA,IAAIQ,EAAO,GACPC,GAAK,EACLC,GAAK,EACLC,OAAKC,EAET,IACE,IAAK,IAAiCC,EAA7BC,EAAKd,EAAIK,OAAOC,cAAmBG,GAAMI,EAAKC,EAAGC,QAAQC,QAChER,EAAKS,KAAKJ,EAAGK,QAETd,GAAKI,EAAKW,SAAWf,GAH8CK,GAAK,IAK9E,MAAOW,GACPV,GAAK,EACLC,EAAKS,UAEL,IACOX,GAAsB,MAAhBK,EAAW,QAAWA,EAAW,iBAE5C,GAAIJ,EAAI,MAAMC,GAIlB,OAAOH,IAITT,EAAOI,QAAiB,QAAIJ,EAAOI,QAASJ,sBAA4B,sBClBxEA,UAVA,SAA2BC,EAAKqB,IACnB,MAAPA,GAAeA,EAAMrB,EAAImB,UAAQE,EAAMrB,EAAImB,QAE/C,IAAK,IAAIf,EAAI,EAAGkB,EAAO,IAAIrB,MAAMoB,GAAMjB,EAAIiB,EAAKjB,IAC9CkB,EAAKlB,GAAKJ,EAAII,GAGhB,OAAOkB,GAITvB,EAAOI,QAAiB,QAAIJ,EAAOI,QAASJ,sBAA4B,sBCAxEA,UATA,SAAqCwB,EAAGC,GACtC,GAAKD,EAAL,CACA,GAAiB,iBAANA,EAAgB,OAAOE,EAAiBF,EAAGC,GACtD,IAAIE,EAAInB,OAAOoB,UAAUC,SAAS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,GAAK3C,EAAI2C,IAERY,IACN,aAUWjE,+BAA+BgG,2BAAAA,yBACtC,SAACoB,UAAaQ,EAAKR,EAAOpB,KRlxBnC,SAAYhI,GAIVA,kBAKAA,kBAKAA,uBAKAA,qBAMAA,sBAKAA,gBA9BF,CAAYA,IAAAA"}
package/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("./impl");function r(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function n(e){var t={exports:{}};return e(t,t.exports),t.exports}var o,u=n((function(e){e.exports=function(e){if(Array.isArray(e))return e},e.exports.default=e.exports,e.exports.__esModule=!0})),c=n((function(e){e.exports=function(e,t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e)){var r=[],n=!0,o=!1,u=void 0;try{for(var c,i=e[Symbol.iterator]();!(n=(c=i.next()).done)&&(r.push(c.value),!t||r.length!==t);n=!0);}catch(e){o=!0,u=e}finally{try{n||null==i.return||i.return()}finally{if(o)throw u}}return r}},e.exports.default=e.exports,e.exports.__esModule=!0})),i=n((function(e){e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n},e.exports.default=e.exports,e.exports.__esModule=!0})),a=n((function(e){e.exports=function(e,t){if(e){if("string"==typeof e)return i(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(e,t):void 0}},e.exports.default=e.exports,e.exports.__esModule=!0})),l=n((function(e){e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.default=e.exports,e.exports.__esModule=!0})),s=r(n((function(e){e.exports=function(e,t){return u(e)||c(e,t)||a(e,t)||l()},e.exports.default=e.exports,e.exports.__esModule=!0}))),f=r(n((function(e){e.exports=function(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.default=e.exports,e.exports.__esModule=!0})));function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function p(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach((function(t){f(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function v(e,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,u=t.createRef(),c=t.createRef(),i=t.createRef(),a=t.createRef(),l=t.createRef(),s=t.createRef(),d=t.createRef(),v=t.createRef(),g=t.createRef(!1),y=t.createRef([]),b={},x=0;function O(e){var t="".concat(x++);return b[t]=e,function(){delete b[t]}}function h(e,t){var r=p(p({},e),t),n=p(p(p({},r),a.current),{},{isLoading:j,abortAction:E,loading:L(),loadingMap:_()});Object.keys(b).forEach((function(e){b[e](n)}))}function m(e){var r=i.current;i.current=e,g.current?t.onPropChange(u,c,i,r,a,n,R,!1):S(e)}function A(e){u.current=e,t.computeDerivedValues(u,i,c,n),h(u.current,c.current.state)}function S(p){if(!g.current){var b;i.current=p,g.current=!0,u.current=e(p);var x=new Set(null==n?void 0:n.initialActionsMarkedLoading);s.current=Object.keys(r).reduce((function(e,r){return e[r]=x.has(r)?f({},t.DEFAULT_PROMISE_ID,!0):{},e}),{}),l.current={},d.current={},v.current={},c.current={state:null,deps:{}},y.current=[];var O={options:n,get state(){return u.current},actions:r,setState:A},m=function(e){var t,r=e();y.current.push(r),null===(t=r.init)||void 0===t||t.call(r,O)};null===(b=t.globalConfig.defaultMiddlewares)||void 0===b||b.forEach(m),null==o||o.forEach(m),t.computeDerivedValues(u,i,c,n),t.onPropChange(u,c,i,null,a,n,R,!0),null!=n&&n.onMount&&n.onMount(t.buildOnMountInvocationContext(u,c,i,a)),h(u.current,c.current.state)}}function M(){var e;g.current&&(null==n||null===(e=n.onUnmount)||void 0===e||e.call(n,t.buildOnMountInvocationContext(u,c,i,a)),i.current=null,u.current=null,s.current=null,d.current=null,v.current=null,c.current=null,Object.keys(l.current).forEach((function(e){clearTimeout(l.current[e])})),l.current=null,b={},g.current=!1,y.current.forEach((function(e){var t;null===(t=e.destroy)||void 0===t||t.call(e)})),y.current=[])}function R(e,r,o,a,l,f){var d=arguments.length>6&&void 0!==arguments[6]&&arguments[6],p=arguments.length>7&&void 0!==arguments[7]&&arguments[7],v=!1;if(g.current){var b=r,x=!!l&&t.isLoadingImpl(b||s.current,[o,null==f?void 0:f.promiseId]),O=t.runMiddlewares(y.current,u.current,e,x,o,a,l,f),m=O.newState,A=O.newLoading;if(null!=m&&(v=!0,u.current=m),x!==A&&(b=t.buildLoadingMap(b,o,(null==f?void 0:f.promiseId)||t.DEFAULT_PROMISE_ID,A),0===Object.keys(b).length&&(b=void 0)),null!=b&&(v=!0,s.current=b),v)t.computeDerivedValues(u,i,c,n),p||h(m||u.current,c.current.state);else if(d){var S=t.computeDerivedValues(u,i,c,n);S&&!p&&h(m||u.current,c.current.state)}}}var P=Object.keys(r);function j(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];return t.isLoadingImpl.apply(void 0,[s.current].concat(r))}function E(e){var r,n,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t.DEFAULT_PROMISE_ID,u=null===(r=d.current[e])||void 0===r||null===(n=r[o])||void 0===n?void 0:n.abortController,c=!1;return u&&(u.abort(),c=!0),c}function L(){if(g.current){var e=s.current;return null!=Object.keys(e).find((function(t){var r=e[t];return Object.keys(r).find((function(e){return!!r[e]}))}))}return null}function _(){if(g.current){var e=s.current;return Object.keys(e).reduce((function(t,r){return t[r]=null!=Object.keys(e[r]).find((function(t){return!!e[r][t]})),t}),{})}return null}function w(){return{getInitialState:e,options:n,actions:r}}return a.current=P.reduce((function(e,o){var f=r[o];return t.isSimpleSyncAction(f)?e[o]=t.decorateSimpleSyncAction(o,f,u,c,i,g,R):t.isAsyncAction(f)?e[o]=t.decorateAsyncAction({actionName:o,stateRef:u,derivedStateRef:c,propsRef:i,loadingMapRef:s,actionsRef:a,promisesRef:d,conflictActionsRef:v,initializedRef:g,options:n,setState:R,action:t.computeAsyncActionInput(f)}):t.isSyncAction(f)&&(e[o]=t.decorateSyncAction(o,f,u,c,i,a,g,l,n,R)),e}),{}),{getConfig:w,setProps:m,addStateListener:O,init:S,destroy:M,isLoading:j,abortAction:E,get actions(){return a.current},get state(){return g.current?p(p({},u.current),c.current.state):null},get loading(){return L()},get loadingMap(){return _()},get loadingParallelMap(){return g.current?s.current:null}}}function g(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=e.useReducer((function(e){return e>100?0:e+1}),0),o=s(n,2),u=o[1],c=e.useRef(t);return t.setProps(r),e.useLayoutEffect((function(){return c.current.addStateListener((function(){u()}))}),[]),e.useEffect((function(){return function(){return t.destroy()}}),[]),{state:t.state,actions:t.actions,loading:t.loading,isLoading:t.isLoading,abortAction:t.abortAction,loadingMap:t.loadingMap,loadingParallelMap:t.loadingParallelMap}}function y(t,r,n,o,u){var c=e.useRef();return null==c.current&&(c.current=v(t,r,o,u)),g(c.current,n)}function b(e,t){return t.reduce((function(t,r){return e.hasOwnProperty(r)&&(t[r]=e[r]),t}),{})}exports.ConflictPolicy=void 0,(o=exports.ConflictPolicy||(exports.ConflictPolicy={})).REJECT="reject",o.IGNORE="ignore",o.KEEP_LAST="keepLast",o.KEEP_ALL="keepAll",o.PARALLEL="parallel",o.REUSE="reuse",Object.defineProperty(exports,"setGlobalConfig",{enumerable:!0,get:function(){return t.setGlobalConfig}}),exports.createStore=v,exports.default=y,exports.pick=b,exports.slice=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return function(e){return b(e,t)}},exports.useBindStore=function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return e.useRef(t),t.setProps(r),e.useEffect((function(){return function(){return t.destroy()}}),[]),t},exports.useLocalStore=y,exports.useStore=g,exports.useStoreSlice=function(r,n){var o=e.useReducer((function(e){return e>100?0:e+1}),0),u=s(o,2)[1],c=e.useMemo((function(){return n instanceof Function?n:function(e){return b(e,n)}}),[n]),i=e.useRef(null);if(null===i.current){var a=r.state;i.current=c(p(p(p({},a),r.actions),{},{actions:r.actions,loading:r.loading,isLoading:r.isLoading,abortAction:r.abortAction,loadingMap:r.loadingMap}))}return e.useLayoutEffect((function(){return r.addStateListener((function(e){var r,n=c(e),o=i.current,a=t.globalConfig.comparator;r=null==o||!a(n,o),i.current=n,r&&u()}))}),[]),i.current};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("./impl");function r(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function n(e){var t={exports:{}};return e(t,t.exports),t.exports}var o,u=n((function(e){e.exports=function(e){if(Array.isArray(e))return e},e.exports.default=e.exports,e.exports.__esModule=!0})),c=n((function(e){e.exports=function(e,t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e)){var r=[],n=!0,o=!1,u=void 0;try{for(var c,i=e[Symbol.iterator]();!(n=(c=i.next()).done)&&(r.push(c.value),!t||r.length!==t);n=!0);}catch(e){o=!0,u=e}finally{try{n||null==i.return||i.return()}finally{if(o)throw u}}return r}},e.exports.default=e.exports,e.exports.__esModule=!0})),i=n((function(e){e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n},e.exports.default=e.exports,e.exports.__esModule=!0})),a=n((function(e){e.exports=function(e,t){if(e){if("string"==typeof e)return i(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(e,t):void 0}},e.exports.default=e.exports,e.exports.__esModule=!0})),l=n((function(e){e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.default=e.exports,e.exports.__esModule=!0})),s=r(n((function(e){e.exports=function(e,t){return u(e)||c(e,t)||a(e,t)||l()},e.exports.default=e.exports,e.exports.__esModule=!0}))),f=r(n((function(e){e.exports=function(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.default=e.exports,e.exports.__esModule=!0})));function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function p(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach((function(t){f(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function v(e,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,u=t.createRef(),c=t.createRef(),i=t.createRef(),a=t.createRef(),l=t.createRef(),s=t.createRef(),d=t.createRef(),v=t.createRef(),g=t.createRef(!1),y=t.createRef([]),b={},x=0;function O(e){var t="".concat(x++);return b[t]=e,function(){delete b[t]}}function S(e,t){var r=p(p({},e),t),n=p(p(p({},r),a.current),{},{isLoading:j,abortAction:E,loading:L(),loadingMap:_()});Object.keys(b).forEach((function(e){b[e](n)}))}function h(e){var r=i.current;i.current=e,g.current?t.onPropChange(u,c,i,r,a,n,R,!1):M(e)}function m(e){u.current=e,t.computeDerivedValues(u,i,c,n),S(u.current,c.current.state)}function M(p){if(!g.current){var b;i.current=p,g.current=!0,u.current=e(p);var x=new Set(null==n?void 0:n.initialActionsMarkedLoading);s.current=Object.keys(r).reduce((function(e,r){return e[r]=x.has(r)?f({},t.DEFAULT_PROMISE_ID,!0):{},e}),{}),l.current={},d.current={},v.current={},c.current={state:null,deps:{}},y.current=[];var O={options:n,get state(){return u.current},actions:r,setState:m},h=function(e){var t,r=e();y.current.push(r),null===(t=r.init)||void 0===t||t.call(r,O)};null===(b=t.globalConfig.defaultMiddlewares)||void 0===b||b.forEach(h),null==o||o.forEach(h),t.computeDerivedValues(u,i,c,n),t.onPropChange(u,c,i,null,a,n,R,!0),null!=n&&n.onMount&&n.onMount(t.buildOnMountInvocationContext(u,c,i,a)),S(u.current,c.current.state)}}function A(){var e;g.current&&(null==n||null===(e=n.onUnmount)||void 0===e||e.call(n,t.buildOnMountInvocationContext(u,c,i,a)),i.current=null,u.current=null,s.current=null,d.current=null,v.current=null,c.current=null,Object.keys(l.current).forEach((function(e){clearTimeout(l.current[e])})),l.current=null,b={},g.current=!1,y.current.forEach((function(e){var t;null===(t=e.destroy)||void 0===t||t.call(e)})),y.current=[])}function R(e,r,o,a,l,f){var d=arguments.length>6&&void 0!==arguments[6]&&arguments[6],p=arguments.length>7&&void 0!==arguments[7]&&arguments[7],v=!1;if(g.current){var b=r,x=!!l&&t.isLoadingImpl(b||s.current,[o,null==f?void 0:f.promiseId]),O=t.runMiddlewares(y.current,u.current,e,x,o,a,l,f),h=O.newState,m=O.newLoading;if(null!=h&&(v=!0,u.current=h),x!==m&&(b=t.buildLoadingMap(b,o,(null==f?void 0:f.promiseId)||t.DEFAULT_PROMISE_ID,m),0===Object.keys(b).length&&(b=void 0)),null!=b&&(v=!0,s.current=b),v)t.computeDerivedValues(u,i,c,n),p||S(h||u.current,c.current.state);else if(d){var M=t.computeDerivedValues(u,i,c,n);M&&!p&&S(h||u.current,c.current.state)}}}var P=Object.keys(r);function j(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];return t.isLoadingImpl.apply(void 0,[s.current].concat(r))}function E(e){var r,n,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t.DEFAULT_PROMISE_ID,u=null===(r=d.current[e])||void 0===r||null===(n=r[o])||void 0===n?void 0:n.abortController,c=!1;return u&&(u.abort(),c=!0),c}function L(){if(g.current){var e=s.current;return null!=Object.keys(e).find((function(t){var r=e[t];return Object.keys(r).find((function(e){return!!r[e]}))}))}return null}function _(){if(g.current){var e=s.current;return Object.keys(e).reduce((function(t,r){return t[r]=null!=Object.keys(e[r]).find((function(t){return!!e[r][t]})),t}),{})}return null}function w(){return{getInitialState:e,options:n,actions:r}}return a.current=P.reduce((function(e,o){var f=r[o];return t.isSimpleSyncAction(f)?e[o]=t.decorateSimpleSyncAction(o,f,u,c,i,g,R):t.isAsyncAction(f)?e[o]=t.decorateAsyncAction({actionName:o,stateRef:u,derivedStateRef:c,propsRef:i,loadingMapRef:s,actionsRef:a,promisesRef:d,conflictActionsRef:v,initializedRef:g,options:n,setState:R,action:t.computeAsyncActionInput(f)}):t.isSyncAction(f)&&(e[o]=t.decorateSyncAction(o,f,u,c,i,a,g,l,n,R)),e}),{}),{getConfig:w,setProps:h,addStateListener:O,init:M,destroy:A,isLoading:j,abortAction:E,get actions(){return a.current},get state(){return g.current?p(p({},u.current),c.current.state):null},get loading(){return L()},get loadingMap(){return _()},get loadingParallelMap(){return g.current?s.current:null}}}function g(r,n,o){var u=e.useReducer((function(e){return e>100?0:e+1}),0),c=s(u,2)[1],i=e.useMemo((function(){return n instanceof Function?n:function(e){return x(e,n)}}),[n]),a=e.useMemo((function(){return function(e){return null!=o&&o.length>0?x(e.loadingMap,o):null}}),[o]),l=e.useRef(null),f=e.useRef(null);if(null===l.current){var d=p(p(p({},r.state),r.actions),x(r,["loading","isLoading","abortAction","loadingMap"]));l.current=i(d),f.current=a(d)}e.useLayoutEffect((function(){return r.addStateListener((function(e){var r,n=i(e),o=a(e),u=l.current,s=t.globalConfig.comparator;r=null==u||!s(n,u)||!s(o,f.current),l.current=n,f.current=o,r&&c()}))}),[]);var v=l.current,g=f.current;return null==g?v:p(p({},v),{},{loadingMap:g})}function y(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=e.useReducer((function(e){return e>100?0:e+1}),0),o=s(n,2),u=o[1],c=e.useRef(t);return t.setProps(r),e.useLayoutEffect((function(){return c.current.addStateListener((function(){u()}))}),[]),{state:t.state,actions:t.actions,loading:t.loading,isLoading:t.isLoading,abortAction:t.abortAction,loadingMap:t.loadingMap,loadingParallelMap:t.loadingParallelMap}}function b(t,r,n,o,u){var c=e.useRef();return null==c.current&&(c.current=v(t,r,o,u)),e.useEffect((function(){return function(){var e;null===(e=c.current)||void 0===e||e.destroy()}}),[]),y(c.current,n)}function x(e,t){return t.reduce((function(t,r){return e.hasOwnProperty(r)&&(t[r]=e[r]),t}),{})}exports.ConflictPolicy=void 0,(o=exports.ConflictPolicy||(exports.ConflictPolicy={})).REJECT="reject",o.IGNORE="ignore",o.KEEP_LAST="keepLast",o.KEEP_ALL="keepAll",o.PARALLEL="parallel",o.REUSE="reuse",Object.defineProperty(exports,"setGlobalConfig",{enumerable:!0,get:function(){return t.setGlobalConfig}}),exports.createStore=v,exports.default=b,exports.pick=x,exports.slice=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return function(e){return x(e,t)}},exports.useBindStore=function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return e.useRef(t),t.setProps(r),e.useEffect((function(){return function(){t.destroy()}}),[]),t},exports.useGetLocalStore=function(t,r,n,o,u){var c=e.useRef();null==c.current&&(c.current=v(t,r,o,u));var i=c.current;return i.setProps(n),e.useEffect((function(){return function(){i.destroy()}}),[]),i},exports.useLocalStore=b,exports.useStore=y,exports.useStoreContextSlice=function(t,r,n){return g(e.useContext(t),r,n)},exports.useStoreSlice=g;
2
2
  //# sourceMappingURL=index.js.map
package/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/types.ts","../node_modules/@babel/runtime/helpers/arrayWithHoles.js","../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js","../node_modules/@babel/runtime/helpers/arrayLikeToArray.js","../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js","../node_modules/@babel/runtime/helpers/nonIterableRest.js","../node_modules/@babel/runtime/helpers/slicedToArray.js","../node_modules/@babel/runtime/helpers/defineProperty.js","../src/index.ts"],"sourcesContent":["/*\n * Copyright 2019 Globalsport SAS\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\nexport type PromiseResult<Type> = Type extends Promise<infer X> ? X : null;\n\nexport type NotifyFunc = (msg: string) => void;\n\nexport type PromiseIdMap = { [promiseId: string]: boolean };\n\nexport type LoadingMap<A> = { [pId in keyof A]?: boolean };\nexport type LoadingParallelMap<A> = { [P in keyof A]?: PromiseIdMap };\nexport type InternalLoadingMap<A> = LoadingParallelMap<A>;\n\nexport type LoadingProps<A> = {\n loading: boolean;\n loadingMap: LoadingMap<A>;\n loadingParallelMap: LoadingParallelMap<A>;\n};\n\n// https://github.com/Microsoft/TypeScript/issues/15300\nexport interface DecoratedActions {\n [name: string]: (...args: any[]) => Promise<any> | void;\n}\n\n/**\n * The State decorator can manage only one asynchronous action of same name at a time.\n * This enum is enumertaing all the policies in such case.\n */\nexport enum ConflictPolicy {\n /**\n * Reject the promise.\n */\n REJECT = 'reject',\n\n /**\n * Return a resolved promise with no result.\n */\n IGNORE = 'ignore',\n\n /**\n * Execute only the last call that conflicts after the one ongoing.\n */\n KEEP_LAST = 'keepLast',\n\n /**\n * Execute all calls one after another.\n */\n KEEP_ALL = 'keepAll',\n\n /**\n * Execute all calls one after another.\n * @see getPromiseId\n */\n PARALLEL = 'parallel',\n\n /**\n * Reuse the ongoing promise if any and if possible (same arguments). Only for GET requests!\n */\n REUSE = 'reuse',\n}\n\nexport type PromiseProvider<S, DS, F extends (...args: any[]) => any, A, P> = (\n ctx: GetPromiseInvocationContext<S, DS, F, P, A>\n) => ReturnType<F> | null;\n\n/**\n * Simple form of a synchronous action.\n */\nexport type SimpleSyncAction<S, F extends (...args: any[]) => any, P, DS, FxRes = S> = (\n ctx: InvocationContext<S, DS, F, P>\n) => FxRes | null;\n\nexport type SyncAction<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = {\n /**\n * Function that update the state when the action is called.\n */\n effects?: (ctx: EffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Debounces the action if this parameter is defined.\n */\n debounceTimeout?: number;\n\n /**\n * Debounces the action side effects if this parameter is defined.\n */\n debounceSideEffectsTimeout?: number;\n\n /**\n * Function that calls side effects, ie. effects that are not changing the state directly.\n */\n sideEffects?: (ctx: SideEffectsInvocationContext<S, DS, F, P, A>) => void;\n};\n\n/**\n * Try to abort an action, if the action is <code>abortable</code>.\n * @param actionName The action name\n * @param promiseId If the action conflict type is <code>ConflictType.PARALLEL</code>, the identifier of the promise.\n * @returns <code>true</code> if the action is abortable and an action is ongoing, <code>false</code> otherwise.\n */\nexport type AbortActionCallback<A> = (actionName: keyof A, promiseId?: string) => boolean;\n\nexport type GetErrorMessage<S, DS, F extends (...args: any[]) => any, P> = (\n ctx: ErrorMessageInvocationContext<S, DS, F, P>\n) => string;\n\nexport type ContextState<S> = {\n state: S;\n s: S;\n};\n\nexport type ContextDerivedStateState<DS> = {\n derived: DS;\n ds: DS;\n};\n\nexport type ContextBase<S, P> = ContextState<S> & {\n props: P;\n p: P;\n};\n\nexport type ContextWithDerived<S, DS, P> = ContextBase<S, P> & ContextDerivedStateState<DS>;\n\nexport type InvocationContextActions<A> = {\n actions: A;\n a: A;\n};\n\nexport type WarningNotifyFunc = {\n notifyWarning?: NotifyFunc;\n};\n\nexport type InvocationContext<S, DS, F extends (...args: any[]) => any, P> = ContextWithDerived<S, DS, P> & {\n args: Parameters<F>;\n promiseId: string;\n};\n\nexport type EffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P> = InvocationContext<S, DS, F, P> & {\n result: PromiseResult<ReturnType<F>>;\n res: PromiseResult<ReturnType<F>>;\n};\n\nexport type GetPromiseInvocationContext<S, DS, F extends (...args: any[]) => any, P, A> = InvocationContextActions<A> &\n InvocationContext<S, DS, F, P> & {\n abortSignal: AbortSignal;\n };\n\nexport type ErrorEffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P> = InvocationContext<\n S,\n DS,\n F,\n P\n> & {\n error: Error;\n err: Error;\n};\n\nexport type SuccessMessageInvocationContext<S, DS, F extends (...args: any[]) => any, P> = EffectsInvocationContext<\n S,\n DS,\n F,\n P\n>;\nexport type ErrorMessageInvocationContext<S, DS, F extends (...args: any[]) => any, P> = ErrorEffectsInvocationContext<\n S,\n DS,\n F,\n P\n>;\n\nexport type SideEffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P, A> = EffectsInvocationContext<\n S,\n DS,\n F,\n P\n> &\n InvocationContextActions<A> &\n WarningNotifyFunc;\n\nexport type ErrorSideEffectsInvocationContext<\n S,\n DS,\n F extends (...args: any[]) => any,\n P,\n A\n> = ErrorEffectsInvocationContext<S, DS, F, P> & InvocationContextActions<A> & WarningNotifyFunc;\n\nexport type OnMountInvocationContext<S, A, P> = ContextBase<S, P> & InvocationContextActions<A>;\n\nexport type EffectsType = 'preEffects' | 'effects' | 'errorEffects' | 'optimisticEffects' | null;\n\nexport type MiddlewareActionContext<S, A, P> = {\n name: keyof A;\n type: EffectsType;\n isAsync: boolean;\n context: InvocationContext<S, any, any, P>;\n};\n\nexport type MiddlewareStoreContext<S, A extends DecoratedActions, P> = {\n actions: StoreActions<S, A, P, any, any>;\n state: S;\n setState: (s: S) => void;\n options: StoreOptions<S, A, P, any>;\n};\n\nexport type MiddlewareFactory<S, A extends DecoratedActions, P> = () => Middleware<S, A, P>;\n\n/**\n * A state change middleware.\n * Allow to listen and change a state change on the fly.\n */\nexport type Middleware<S, A extends DecoratedActions, P> = {\n /**\n * Initializes the middleware. Called when the store is initializing.\n */\n init: (storeContext: MiddlewareStoreContext<S, A, P>) => void;\n\n /**\n * Invoked on a state change has occurred and returns a new state or <code>null</code> if unchanged.\n */\n effects: (\n actionContext: MiddlewareActionContext<S, A, P>,\n oldState: S,\n newState: S,\n loading: boolean\n ) => null | {\n state: S;\n loading: boolean;\n };\n\n /**\n * Destroys the middleware. Called when the store is being destroyed.\n */\n destroy: () => void;\n};\n\nexport type AsyncActionBase<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = {\n /**\n * This action can be aborted. An abortSignal will be injected to the <code>promise</code> / <code>promiseGet</code>.\n */\n abortable?: boolean;\n\n /**\n * A function that provides the success message to pass to the notifySuccess function passed as property to the StateDecorator.\n */\n getSuccessMessage?: (ctx: SuccessMessageInvocationContext<S, DS, F, P>) => string;\n\n /**\n * A function that provides the error message to pass to the notifyError function passed as property to the StateDecorator.\n */\n getErrorMessage?: GetErrorMessage<S, DS, F, P>;\n\n /**\n * If set, called with the result of the promise to update the current state.\n */\n effects?: (ctx: EffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * If set, called with the error of the promise to update the current state.\n */\n errorEffects?: (ctx: ErrorEffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Whether reject the promise instead of handling it.\n */\n rejectPromiseOnError?: boolean;\n\n /**\n * Handle side effects when the request succeeded.\n * @param result The result of the request\n * @param newData The data after the reducer is applied\n * @param args The argument during the call of the request function\n * @param props The props passed to the state decorator\n * @param actions The actions available\n * @param notifyWarning If specified, a notify function to indicate that the action is a semi success (use successMessage / getSuccessMessage otherwise).\n */\n sideEffects?: (ctx: SideEffectsInvocationContext<S, DS, F, P, A>) => void;\n\n /**\n * Handle side effects when the request failed.\n * @param error The error of the request\n * @param args The argument during the call of the request function\n * @param props The props passed to the state decorator\n * @param actions The actions available\n * @param notifyWarning If specified, a notify function to indicate that the action is a semi failure (use errorMessage / getErrorMessage otherwise).\n */\n errorSideEffects?: (ctx: ErrorSideEffectsInvocationContext<S, DS, F, P, A>) => void;\n\n /**\n * Retrieve the state to set as current data before the promise is resolved.\n * If the there's no reducer, this data will be used after the promise is done.\n */\n preEffects?: (ctx: InvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Retrieve the state to set as current data before the promise is resolved.\n * If the there's no reducer, this data will be used after the promise is done.\n */\n optimisticEffects?: (ctx: InvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Policy to apply when a call to an asynchronous action is done but a previous call is still not resolved.\n */\n conflictPolicy?: ConflictPolicy;\n\n /**\n * Get an identifier for an action call. Used only when conflictPolicy is ConflictPolicy.PARALLEL.\n * This information will be available in loadingMap. loadingMap[actionName] will be an array of promise identifiers.\n */\n getPromiseId?: (...args: Parameters<F>) => string;\n\n /**\n * Number of retries in case of error (failed to fetch).\n * Do not use this if you are creating objects...\n * Default value is 0 (no retry).\n */\n retryCount?: number;\n\n /**\n * Seed of delay between each retry in milliseconds.\n * The applied delay is retryDelaySeed * retry count.\n * Default value is 1000 (1 second).\n */\n retryDelaySeed?: number;\n\n /**\n * Function to test if the error will trigger an action retry or will fail directly.\n */\n isTriggerRetryError?: (e: Error) => boolean;\n};\n\nexport type AsyncActionPromise<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> = AsyncActionBase<\n S,\n F,\n A,\n P,\n DS,\n FxRes\n> & {\n /**\n * The request, returns a promise\n */\n getPromise: PromiseProvider<S, DS, F, A, P>;\n};\n\nexport type AsyncActionPromiseGet<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = AsyncActionBase<\n S,\n F,\n A,\n P,\n DS,\n FxRes\n> & {\n /**\n * The request, returns a promise that is a GET request.\n * A shortcut to set:\n * - retryCount: 3\n * - conflictPolicy: ConflictPolicy.REUSE\n */\n getGetPromise: PromiseProvider<S, DS, F, A, P>;\n};\n\nexport type AsyncAction<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> =\n | AsyncActionPromise<S, F, A, P, DS, FxRes>\n | AsyncActionPromiseGet<S, F, A, P, DS, FxRes>;\n\nexport type StoreAction<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> =\n | AsyncAction<S, F, A, P, DS, FxRes>\n | SimpleSyncAction<S, F, P, DS, FxRes>\n | SyncAction<S, F, A, P, DS, FxRes>;\n\n/**\n * S: The type of the state\n * A: The type of the actions to pass to the children (used to check keys only).\n */\nexport type StoreActions<S, A extends DecoratedActions, P = {}, DS = {}, FxRes = S> = {\n [Prop in keyof A]: StoreAction<S, A[Prop], A, P, DS, FxRes>;\n};\n\nexport type OnPropsChangeEffectsContext<S, DS, P> = ContextWithDerived<S, DS, P> & {\n indices: number[];\n index: number;\n isInit: boolean;\n};\n\nexport type OnPropsChangeSideEffectsContext<S, P, A, DS = {}> = OnPropsChangeEffectsContext<S, DS, P> & {\n actions: A;\n a: A;\n};\n\ntype DerivedStateOption<S, P, DS> = {\n [k in keyof DS]: {\n getDeps: (ctx: ContextBase<S, P>) => any[];\n get: (ctx: ContextBase<S, P>) => DS[k];\n };\n};\n\nexport type OnPropsChangeOptions<S, DS, A, P> = {\n onMount?: boolean;\n getDeps: (p: P) => any[];\n effects?: (ctx: OnPropsChangeEffectsContext<S, DS, P>) => S;\n sideEffects?: (ctx: OnPropsChangeSideEffectsContext<S, P, A>) => void;\n};\n\nexport type StoreOptions<S, A, P = {}, DS = {}> = {\n /**\n * The state decorator name. Use in debug traces to identify the useStateDecorator instance.\n */\n name?: string;\n\n /**\n * List of action names that are marked as loading at initial time.\n * If you must start your initial actions in a useSideEffect, a render is done before\n * first actions can be trigerred, some actions can be marked as loading at initial time.\n */\n initialActionsMarkedLoading?: (keyof A)[];\n\n /**\n * One or several configurations of inbound properties change managements.\n */\n onPropsChange?: OnPropsChangeOptions<S, DS, A, P> | OnPropsChangeOptions<S, DS, A, P>[];\n\n /**\n * The callback function called if an asynchronous function succeeded and a success messsage is defined.\n */\n notifySuccess?: NotifyFunc;\n\n /**\n * The callback function called if an asynchronous function fails and an error messsage is defined.\n */\n notifyError?: NotifyFunc;\n\n /**\n * The callback function injected in onDone and onFail of asynchronous functions to notify a semi success / failed request.\n */\n notifyWarning?: NotifyFunc;\n\n /**\n * Initial actions.\n */\n onMount?: (ctx: OnMountInvocationContext<S, A, P>) => void;\n\n /**\n * Callback on store destruction.\n */\n onUnmount?: (ctx: OnMountInvocationContext<S, A, P>) => Promise<any> | void;\n\n /**\n * Compute derived state\n */\n derivedState?: DerivedStateOption<S, P, DS>;\n};\n","function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nmodule.exports = _arrayWithHoles;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _iterableToArrayLimit(arr, i) {\n if (typeof Symbol === \"undefined\" || !(Symbol.iterator in Object(arr))) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nmodule.exports = _iterableToArrayLimit;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) {\n arr2[i] = arr[i];\n }\n\n return arr2;\n}\n\nmodule.exports = _arrayLikeToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","var arrayLikeToArray = require(\"./arrayLikeToArray.js\");\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}\n\nmodule.exports = _unsupportedIterableToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nmodule.exports = _nonIterableRest;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","var arrayWithHoles = require(\"./arrayWithHoles.js\");\n\nvar iterableToArrayLimit = require(\"./iterableToArrayLimit.js\");\n\nvar unsupportedIterableToArray = require(\"./unsupportedIterableToArray.js\");\n\nvar nonIterableRest = require(\"./nonIterableRest.js\");\n\nfunction _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}\n\nmodule.exports = _slicedToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nmodule.exports = _defineProperty;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","/*\n * Copyright 2019 Globalsport SAS\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\nimport { useEffect, useLayoutEffect, useMemo, useReducer, useRef } from 'react';\nimport {\n computeAsyncActionInput,\n createRef,\n isSyncAction,\n isAsyncAction,\n isSimpleSyncAction,\n TimeoutMap,\n PromiseMap,\n DEFAULT_PROMISE_ID,\n globalConfig,\n setGlobalConfig,\n GlobalConfig,\n ConflictActionsMap,\n buildOnMountInvocationContext,\n decorateSimpleSyncAction,\n decorateSyncAction,\n decorateAsyncAction,\n computeDerivedValues,\n DerivedState,\n onPropChange,\n runMiddlewares,\n buildLoadingMap,\n isLoadingImpl,\n} from './impl';\n\nimport {\n DecoratedActions,\n StoreActions,\n AsyncAction,\n SyncAction,\n SimpleSyncAction,\n InternalLoadingMap,\n LoadingMap,\n LoadingParallelMap,\n StoreOptions,\n AsyncActionPromise,\n InvocationContext,\n GetPromiseInvocationContext,\n EffectsInvocationContext,\n InvocationContextActions,\n WarningNotifyFunc,\n ErrorEffectsInvocationContext,\n OnMountInvocationContext,\n ContextBase,\n OnPropsChangeEffectsContext,\n ContextState,\n ConflictPolicy,\n Middleware,\n AbortActionCallback,\n MiddlewareFactory,\n MiddlewareStoreContext,\n LoadingProps,\n} from './types';\n\nexport {\n DecoratedActions,\n StoreActions,\n LoadingMap,\n StoreOptions,\n LoadingParallelMap,\n AsyncActionPromise as AsynchActionPromise,\n InvocationContext,\n GetPromiseInvocationContext,\n EffectsInvocationContext,\n InvocationContextActions,\n WarningNotifyFunc,\n ErrorEffectsInvocationContext,\n OnMountInvocationContext,\n ContextBase,\n OnPropsChangeEffectsContext,\n SyncAction,\n AsyncAction,\n SimpleSyncAction,\n ContextState,\n ConflictPolicy,\n GlobalConfig,\n Middleware,\n setGlobalConfig,\n LoadingProps,\n AbortActionCallback,\n};\n\nexport type IsLoadingFunc<A> = (...props: (keyof A | [keyof A, string])[]) => boolean;\ntype StateListenerUnregister = () => void;\n\nexport type StoreApi<S, A extends DecoratedActions, P, DS = {}> = {\n /**\n * The current store state (with derived state if any).\n */\n readonly state: S & DS;\n /**\n * The store decorator (ie. ready to use) actions.\n */\n readonly actions: A;\n /**\n * A boolean that indicates that at least one asynchronous action is loading.\n */\n readonly loading: boolean;\n /**\n * A map of loading actions map (computed on property access)\n */\n readonly loadingMap: LoadingMap<A>;\n /**\n * A map of parallel loading actions map (computed on property access)\n */\n readonly loadingParallelMap: LoadingParallelMap<A>;\n /**\n * Initializes the store with the specified props\n */\n init: (p: P) => void;\n /**\n * Update the store with the specified props\n */\n setProps: (p: P) => void;\n /**\n * Destroy the store\n */\n destroy: () => void;\n /**\n * Abort an asynchronous action marked as abortable.\n */\n abortAction: (actionName: keyof A, promiseId?: string) => boolean;\n /**\n * Add a store state change listener\n */\n addStateListener: (listener: StateListener<S, DS, A>) => StateListenerUnregister;\n /**\n * A function that takes a list of action names or a tuple of [action name, promiseId] and returns <code>true</code> if any action is loading.\n */\n isLoading: IsLoadingFunc<A>;\n\n getConfig: () => {\n getInitialState: (p: P) => S;\n options: StoreOptions<S, A, P, DS>;\n actions: StoreActions<S, A, P, DS>;\n };\n};\n\nexport type StateListenerContext<S, DS, A extends DecoratedActions> = S &\n DS &\n A &\n Pick<StoreApi<S, A, any, DS>, 'loading' | 'loadingMap' | 'isLoading' | 'abortAction'>;\n\nexport type StateListener<S, DS, A extends DecoratedActions> = (ctx: StateListenerContext<S, DS, A>) => void;\n\n// =============================\n//\n// STORE\n//\n// =============================\n\n/**\n * Create a new store.\n * @param getInitialState The state initialization function (using props)\n * @param actionsImpl The actions implementation (pure functions only).\n * @param options Options to configure the store\n * @returns a store.\n */\nexport function createStore<S, A extends DecoratedActions, P, DS = {}>(\n getInitialState: (p: P) => S,\n actionsImpl: StoreActions<S, A, P, DS>,\n options: StoreOptions<S, A, P, DS> = {},\n storeMiddlewares: MiddlewareFactory<S, A, P>[] = null\n): StoreApi<S, A, P, DS> {\n const stateRef = createRef<S>();\n const derivedStateRef = createRef<DerivedState<DS>>();\n const propsRef = createRef<P>();\n const actionsRef = createRef<A>();\n const timeoutRef = createRef<TimeoutMap<A>>();\n const loadingMapRef = createRef<InternalLoadingMap<A>>();\n const promisesRef = createRef<PromiseMap<A>>();\n const conflictActionsRef = createRef<ConflictActionsMap<A>>();\n const initializedRef = createRef(false);\n\n const middlewaresRef = createRef<Middleware<S, A, P>[]>([]);\n\n let stateListeners: Record<string, StateListener<S, DS, A>> = {};\n let stateListenerCount = 0;\n\n function addStateListener(listener: StateListener<S, DS, A>): () => void {\n const id = `${stateListenerCount++}`;\n stateListeners[id] = listener;\n return () => {\n delete stateListeners[id];\n };\n }\n\n function notifyStateListeners(newState: S, derivedState: DS) {\n const s = {\n ...newState,\n ...derivedState,\n };\n\n const ctx: StateListenerContext<S, DS, A> = {\n ...s,\n ...actionsRef.current,\n isLoading,\n abortAction,\n loading: isAnyLoading(),\n loadingMap: getLoadingMap(),\n };\n\n Object.keys(stateListeners).forEach((listenerId) => {\n stateListeners[listenerId](ctx);\n });\n }\n\n function setProps(p: P) {\n const oldProps = propsRef.current;\n\n propsRef.current = p;\n\n if (!initializedRef.current) {\n init(p);\n } else {\n onPropChange(stateRef, derivedStateRef, propsRef, oldProps, actionsRef, options, setState, false);\n }\n }\n\n /** Middleware only: sets the internal state, recompute derived state and notify listeners */\n function setInternalState(s: S) {\n stateRef.current = s;\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n notifyStateListeners(stateRef.current, derivedStateRef.current.state);\n }\n\n function init(p: P) {\n if (!initializedRef.current) {\n propsRef.current = p;\n initializedRef.current = true;\n stateRef.current = getInitialState(p);\n\n const initialActionSet = new Set(options?.initialActionsMarkedLoading);\n\n loadingMapRef.current = (Object.keys(actionsImpl) as (keyof A)[]).reduce<InternalLoadingMap<A>>((acc, name) => {\n acc[name] = initialActionSet.has(name) ? { [DEFAULT_PROMISE_ID]: true } : {};\n return acc;\n }, {});\n\n timeoutRef.current = {};\n promisesRef.current = {};\n conflictActionsRef.current = {};\n derivedStateRef.current = {\n state: null,\n deps: {},\n };\n\n // init middlewares\n middlewaresRef.current = [];\n const ctx: MiddlewareStoreContext<S, A, P> = {\n options,\n get state() {\n return stateRef.current;\n },\n actions: actionsImpl,\n setState: setInternalState,\n };\n const mapper = (m: MiddlewareFactory<S, A, P>) => {\n const middleware = m();\n middlewaresRef.current.push(middleware);\n middleware.init?.(ctx);\n };\n globalConfig.defaultMiddlewares?.forEach(mapper);\n storeMiddlewares?.forEach(mapper);\n // end init\n\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n\n // manage PropsChange with onMount\n onPropChange(stateRef, derivedStateRef, propsRef, null, actionsRef, options, setState, true);\n\n if (options?.onMount) {\n options.onMount(buildOnMountInvocationContext(stateRef, derivedStateRef, propsRef, actionsRef));\n }\n\n notifyStateListeners(stateRef.current, derivedStateRef.current.state);\n }\n }\n\n function destroy() {\n if (initializedRef.current) {\n options?.onUnmount?.(buildOnMountInvocationContext(stateRef, derivedStateRef, propsRef, actionsRef));\n\n propsRef.current = null;\n stateRef.current = null;\n loadingMapRef.current = null;\n promisesRef.current = null;\n conflictActionsRef.current = null;\n derivedStateRef.current = null;\n\n Object.keys(timeoutRef.current).forEach((name) => {\n clearTimeout(timeoutRef.current[name]);\n });\n\n timeoutRef.current = null;\n stateListeners = {};\n initializedRef.current = false;\n\n middlewaresRef.current.forEach((m) => {\n m.destroy?.();\n });\n\n middlewaresRef.current = [];\n }\n }\n\n function setState(\n newStateIn: S,\n newLoadingMapIn: InternalLoadingMap<A>,\n actionName: keyof A,\n actionType: 'preEffects' | 'effects' | 'errorEffects' | null,\n isAsync: boolean,\n actionCtx: any,\n propsChanged: boolean = false,\n init = false\n ) {\n let hasChanged = false;\n\n if (!initializedRef.current) {\n return;\n }\n\n let newLoadingMap = newLoadingMapIn;\n\n const oldLoading = isAsync\n ? isLoadingImpl(newLoadingMap || loadingMapRef.current, [actionName, actionCtx?.promiseId])\n : false;\n\n const { newState, newLoading } = runMiddlewares(\n middlewaresRef.current,\n stateRef.current,\n newStateIn,\n oldLoading,\n actionName,\n actionType,\n isAsync,\n actionCtx\n );\n\n if (newState != null) {\n hasChanged = true;\n stateRef.current = newState;\n }\n\n if (oldLoading !== newLoading) {\n newLoadingMap = buildLoadingMap(\n newLoadingMap,\n actionName,\n actionCtx?.promiseId || DEFAULT_PROMISE_ID,\n newLoading\n );\n if (Object.keys(newLoadingMap).length === 0) {\n newLoadingMap = undefined;\n }\n }\n\n if (newLoadingMap != null) {\n hasChanged = true;\n loadingMapRef.current = newLoadingMap;\n }\n\n if (hasChanged) {\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n if (!init) {\n notifyStateListeners(newState || stateRef.current, derivedStateRef.current.state);\n }\n } else if (propsChanged) {\n const derivedChanged = computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n if (derivedChanged && !init) {\n notifyStateListeners(newState || stateRef.current, derivedStateRef.current.state);\n }\n }\n }\n\n const keys = Object.keys(actionsImpl) as (keyof A)[];\n actionsRef.current = keys.reduce<A>((acc, actionName) => {\n const action = actionsImpl[actionName];\n if (isSimpleSyncAction(action)) {\n acc[actionName] = decorateSimpleSyncAction(\n actionName,\n action,\n stateRef,\n derivedStateRef,\n propsRef,\n initializedRef,\n setState\n ) as any;\n } else if (isAsyncAction(action)) {\n acc[actionName] = decorateAsyncAction({\n actionName,\n stateRef,\n derivedStateRef,\n propsRef,\n loadingMapRef,\n actionsRef,\n promisesRef,\n conflictActionsRef,\n initializedRef,\n options,\n setState,\n action: computeAsyncActionInput(action),\n }) as any;\n } else if (isSyncAction(action)) {\n acc[actionName] = decorateSyncAction(\n actionName,\n action,\n stateRef,\n derivedStateRef,\n propsRef,\n actionsRef,\n initializedRef,\n timeoutRef,\n options,\n setState\n ) as any;\n }\n\n return acc;\n }, {} as A);\n\n function isLoading<K extends keyof A>(...props: (K | [K, string])[]) {\n return isLoadingImpl(loadingMapRef.current, ...props);\n }\n\n function abortAction(actionName: keyof A, promiseId: string = DEFAULT_PROMISE_ID) {\n const abortController = promisesRef.current[actionName]?.[promiseId]?.abortController;\n\n let res = false;\n if (abortController) {\n abortController.abort();\n res = true;\n }\n\n return res;\n }\n\n function isAnyLoading() {\n if (initializedRef.current) {\n const loadingMap = loadingMapRef.current;\n return (\n Object.keys(loadingMap).find((actionName) => {\n const promises = loadingMap[actionName];\n return Object.keys(promises).find((pId) => !!promises[pId]);\n }) != null\n );\n }\n return null;\n }\n\n function getLoadingMap() {\n if (initializedRef.current) {\n const map = loadingMapRef.current;\n const keys = Object.keys(map) as (keyof A)[];\n return keys.reduce<LoadingMap<A>>((acc, actionName) => {\n acc[actionName] = Object.keys(map[actionName]).find((pId) => !!map[actionName][pId]) != null;\n return acc;\n }, {});\n }\n return null;\n }\n\n function getConfig() {\n return {\n getInitialState,\n options,\n actions: actionsImpl,\n };\n }\n\n return {\n getConfig,\n setProps,\n addStateListener,\n init,\n destroy,\n isLoading,\n abortAction,\n get actions() {\n return actionsRef.current;\n },\n get state() {\n if (initializedRef.current) {\n return {\n ...stateRef.current,\n ...derivedStateRef.current.state,\n };\n }\n return null;\n },\n get loading() {\n return isAnyLoading();\n },\n get loadingMap() {\n return getLoadingMap();\n },\n get loadingParallelMap() {\n if (initializedRef.current) {\n return loadingMapRef.current;\n }\n return null;\n },\n };\n}\n\n// =====================================\n//\n// REACT HOOKS\n//\n// =====================================\n\ntype useStoreSlice<S, A extends DecoratedActions, P, DS, SLICE> = (\n store: StoreApi<S, A, P, DS>,\n slicer: (ctx: StateListenerContext<S, DS, A>) => SLICE\n) => SLICE;\n\n/**\n * A react hook to get a state slice. Will be refresh if, and only if, one property of the slice has changed\n * @param store The store to listen to.\n * @param slicerFunc A function that returns a state slice\n * @param comparator An optional function to compare if slice property has changed (shallow test by default)\n * @returns The state slice.\n */\nexport function useStoreSlice<S, A extends DecoratedActions, P, DS, SLICE>(\n store: StoreApi<S, A, P, DS>,\n slicerFunc: (ctx: StateListenerContext<S, DS, A>) => SLICE\n): SLICE;\n\nexport function useStoreSlice<S, A extends DecoratedActions, P, DS, K extends keyof StateListenerContext<S, DS, A>>(\n store: StoreApi<S, A, P, DS>,\n properties: K[]\n): Pick<StateListenerContext<S, DS, A>, K>;\n\nexport function useStoreSlice<S, A extends DecoratedActions, P, DS>(store: StoreApi<S, A, P, DS>, funcOrArr: any) {\n const [, forceRefresh] = useReducer((s) => (s > 100 ? 0 : s + 1), 0);\n\n const slicerFunc = useMemo(\n () => (funcOrArr instanceof Function ? funcOrArr : (ctx: StateListenerContext<S, DS, A>) => pick(ctx, funcOrArr)),\n [funcOrArr]\n );\n\n const sliceRef = useRef<any>(null);\n if (sliceRef.current === null) {\n const s = store.state;\n sliceRef.current = slicerFunc({\n ...s,\n ...store.actions,\n actions: store.actions,\n loading: store.loading,\n isLoading: store.isLoading,\n abortAction: store.abortAction,\n loadingMap: store.loadingMap,\n });\n }\n\n useLayoutEffect(() => {\n const unregister = store.addStateListener((ctx) => {\n let hasChanged = false;\n\n const slice = slicerFunc(ctx);\n const prevSlice = sliceRef.current;\n const compare = globalConfig.comparator;\n\n hasChanged = prevSlice == null || !compare(slice, prevSlice);\n\n sliceRef.current = slice;\n\n if (hasChanged) {\n forceRefresh();\n }\n });\n\n return unregister;\n }, []);\n\n return sliceRef.current;\n}\n\n/**\n * Binds the store to this component.\n * Store will be destroyed when component is unmouted.\n * Props passed to actions will come from this components.\n * If store is configured to react of props changes, it will used passed props.\n * A store must be bound to only one React component.\n * This component will be refreshed for every change in the store.\n *\n * @param store The store to listen to.\n * @param props The parent component props\n * @returns The state, actions and isLoading function.\n */\nexport function useStore<S, A extends DecoratedActions, P, DS = {}>(store: StoreApi<S, A, P, DS>, props: P = null) {\n const [, forceRefresh] = useReducer((s) => (s > 100 ? 0 : s + 1), 0);\n\n const storeRef = useRef(store);\n\n store.setProps(props);\n\n useLayoutEffect(\n () =>\n storeRef.current.addStateListener(() => {\n forceRefresh();\n }),\n []\n );\n\n useEffect(() => () => store.destroy(), []);\n\n return {\n state: store.state,\n actions: store.actions,\n loading: store.loading,\n isLoading: store.isLoading,\n abortAction: store.abortAction,\n loadingMap: store.loadingMap,\n loadingParallelMap: store.loadingParallelMap,\n };\n}\n\n/**\n * Binds the store to this component.\n * Store will be destroyed when component is unmouted.\n * Props passed to actions will come from this components.\n * If store is configured to react of props changes, it will used passed props.\n * A store must be bound to only one React component.\n *\n * This component will NOT be refreshed for any change in the store.\n *\n * @param store The store to listen to.\n * @param props The parent component props\n */\nexport function useBindStore<S, A extends DecoratedActions, P, DS = {}>(store: StoreApi<S, A, P, DS>, props: P = null) {\n // access to store in debugger\n useRef(store);\n\n store.setProps(props);\n useEffect(() => {\n return () => store.destroy();\n }, []);\n return store;\n}\n\n/**\n * Creates and manages a local store.\n * @param getInitialState Function to compute initial state from props.\n * @param actionImpl Actions implementation.\n * @param props Owner component props to update state or react on prop changes\n * @param options The store options.\n * @returns The state, actions and isLoading function.\n */\nexport function useLocalStore<S, A extends DecoratedActions, P, DS = {}>(\n getInitialState: (p: P) => S,\n actionImpl: StoreActions<S, A, P, DS>,\n props?: P,\n options?: StoreOptions<S, A, P, DS>,\n middlewares?: MiddlewareFactory<S, A, P>[]\n) {\n const storeRef = useRef<StoreApi<S, A, P, DS>>();\n if (storeRef.current == null) {\n storeRef.current = createStore(getInitialState, actionImpl, options, middlewares);\n }\n\n return useStore(storeRef.current, props);\n}\n\nexport default useLocalStore;\n\n// ------------- UTILS\n\n/**\n * Creates a new object by picking properties to the object passed a first parameter\n * @param obj Object to pick properties from\n * @param props Property names\n * @returns a new object containing only picked properties\n */\nexport function pick<T, K extends keyof T>(obj: T, props: K[]): Pick<T, K> {\n return props.reduce((acc, p) => {\n if (obj.hasOwnProperty(p)) {\n acc[p] = obj[p];\n }\n return acc;\n }, {} as any);\n}\n\n/**\n * Returns a function that creates a new object by picking properties to the object passed as first parameter.\n * To be used in conjunction of <code>useStoreSlice</code> like in example:\n * const s = useStoreSlice(myStore, slice('list', 'addItem'));\n * @param props Property names\n * @returns a function to pick property from an passed object.\n */\nexport function slice<T, K extends keyof T>(...props: K[]): (obj: T) => Pick<T, K> {\n return (store: T) => pick(store, props);\n}\n"],"names":["ConflictPolicy","module","arr","Array","isArray","exports","i","Symbol","iterator","Object","_arr","_n","_d","_e","undefined","_s","_i","next","done","push","value","length","err","len","arr2","o","minLen","arrayLikeToArray","n","prototype","toString","call","slice","constructor","name","from","test","TypeError","arrayWithHoles","iterableToArrayLimit","unsupportedIterableToArray","nonIterableRest","obj","key","defineProperty","enumerable","configurable","writable","createStore","getInitialState","actionsImpl","options","storeMiddlewares","stateRef","createRef","derivedStateRef","propsRef","actionsRef","timeoutRef","loadingMapRef","promisesRef","conflictActionsRef","initializedRef","middlewaresRef","stateListeners","stateListenerCount","addStateListener","listener","id","notifyStateListeners","newState","derivedState","s","ctx","current","isLoading","abortAction","loading","isAnyLoading","loadingMap","getLoadingMap","keys","forEach","listenerId","setProps","p","oldProps","onPropChange","setState","init","setInternalState","computeDerivedValues","state","initialActionSet","Set","initialActionsMarkedLoading","reduce","acc","has","DEFAULT_PROMISE_ID","deps","actions","mapper","m","middleware","globalConfig","defaultMiddlewares","onMount","buildOnMountInvocationContext","destroy","onUnmount","clearTimeout","newStateIn","newLoadingMapIn","actionName","actionType","isAsync","actionCtx","propsChanged","hasChanged","newLoadingMap","oldLoading","isLoadingImpl","promiseId","runMiddlewares","newLoading","buildLoadingMap","derivedChanged","props","abortController","_promisesRef$current$","_promisesRef$current$2","res","abort","find","promises","pId","map","getConfig","action","isSimpleSyncAction","decorateSimpleSyncAction","isAsyncAction","decorateAsyncAction","computeAsyncActionInput","isSyncAction","decorateSyncAction","useStore","store","useReducer","forceRefresh","storeRef","useRef","useLayoutEffect","useEffect","loadingParallelMap","useLocalStore","actionImpl","middlewares","pick","hasOwnProperty","funcOrArr","slicerFunc","useMemo","Function","sliceRef","prevSlice","compare","comparator"],"mappings":"wRAmCYA,mBC/BZC,UAJA,SAAyBC,GACvB,GAAIC,MAAMC,QAAQF,GAAM,OAAOA,GAIjCD,EAAOI,QAAiB,QAAIJ,EAAOI,QAASJ,sBAA4B,sBCsBxEA,UA3BA,SAA+BC,EAAKI,GAClC,GAAsB,oBAAXC,QAA4BA,OAAOC,YAAYC,OAAOP,GAAjE,CACA,IAAIQ,EAAO,GACPC,GAAK,EACLC,GAAK,EACLC,OAAKC,EAET,IACE,IAAK,IAAiCC,EAA7BC,EAAKd,EAAIK,OAAOC,cAAmBG,GAAMI,EAAKC,EAAGC,QAAQC,QAChER,EAAKS,KAAKJ,EAAGK,QAETd,GAAKI,EAAKW,SAAWf,GAH8CK,GAAK,IAK9E,MAAOW,GAC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I,EAAWzF,GACnB6F,EAAYD,EAAS3F,QACrB6F,EAAU9D,eAAa+D,WAE7BjD,EAA0B,MAAb+C,IAAsBC,EAAQvI,EAAOsI,GAElDD,EAAS3F,QAAU1C,EAEfuF,GACF+B,SAKH,IAEIe,EAAS3F"}
1
+ {"version":3,"file":"index.js","sources":["../src/types.ts","../node_modules/@babel/runtime/helpers/arrayWithHoles.js","../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js","../node_modules/@babel/runtime/helpers/arrayLikeToArray.js","../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js","../node_modules/@babel/runtime/helpers/nonIterableRest.js","../node_modules/@babel/runtime/helpers/slicedToArray.js","../node_modules/@babel/runtime/helpers/defineProperty.js","../src/index.ts"],"sourcesContent":["/*\n * Copyright 2019 Globalsport SAS\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\nexport type PromiseResult<Type> = Type extends Promise<infer X> ? X : null;\n\nexport type NotifyFunc = (msg: string) => void;\n\nexport type PromiseIdMap = { [promiseId: string]: boolean };\n\nexport type LoadingMap<A> = { [pId in keyof A]?: boolean };\nexport type LoadingParallelMap<A> = { [P in keyof A]?: PromiseIdMap };\nexport type InternalLoadingMap<A> = LoadingParallelMap<A>;\n\nexport type LoadingProps<A> = {\n loading: boolean;\n loadingMap: LoadingMap<A>;\n loadingParallelMap: LoadingParallelMap<A>;\n};\n\n// https://github.com/Microsoft/TypeScript/issues/15300\nexport interface DecoratedActions {\n [name: string]: (...args: any[]) => Promise<any> | void;\n}\n\n/**\n * The State decorator can manage only one asynchronous action of same name at a time.\n * This enum is enumertaing all the policies in such case.\n */\nexport enum ConflictPolicy {\n /**\n * Reject the promise.\n */\n REJECT = 'reject',\n\n /**\n * Return a resolved promise with no result.\n */\n IGNORE = 'ignore',\n\n /**\n * Execute only the last call that conflicts after the one ongoing.\n */\n KEEP_LAST = 'keepLast',\n\n /**\n * Execute all calls one after another.\n */\n KEEP_ALL = 'keepAll',\n\n /**\n * Execute all calls one after another.\n * @see getPromiseId\n */\n PARALLEL = 'parallel',\n\n /**\n * Reuse the ongoing promise if any and if possible (same arguments). Only for GET requests!\n */\n REUSE = 'reuse',\n}\n\nexport type PromiseProvider<S, DS, F extends (...args: any[]) => any, A, P> = (\n ctx: GetPromiseInvocationContext<S, DS, F, P, A>\n) => ReturnType<F> | null;\n\n/**\n * Simple form of a synchronous action.\n */\nexport type SimpleSyncAction<S, F extends (...args: any[]) => any, P, DS, FxRes = S> = (\n ctx: InvocationContext<S, DS, F, P>\n) => FxRes | null;\n\nexport type SyncAction<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = {\n /**\n * Function that update the state when the action is called.\n */\n effects?: (ctx: EffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Debounces the action if this parameter is defined.\n */\n debounceTimeout?: number;\n\n /**\n * Debounces the action side effects if this parameter is defined.\n */\n debounceSideEffectsTimeout?: number;\n\n /**\n * Function that calls side effects, ie. effects that are not changing the state directly.\n */\n sideEffects?: (ctx: SideEffectsInvocationContext<S, DS, F, P, A>) => void;\n};\n\n/**\n * Try to abort an action, if the action is <code>abortable</code>.\n * @param actionName The action name\n * @param promiseId If the action conflict type is <code>ConflictType.PARALLEL</code>, the identifier of the promise.\n * @returns <code>true</code> if the action is abortable and an action is ongoing, <code>false</code> otherwise.\n */\nexport type AbortActionCallback<A> = (actionName: keyof A, promiseId?: string) => boolean;\n\nexport type GetErrorMessage<S, DS, F extends (...args: any[]) => any, P> = (\n ctx: ErrorMessageInvocationContext<S, DS, F, P>\n) => string;\n\nexport type ContextState<S> = {\n state: S;\n s: S;\n};\n\nexport type ContextDerivedStateState<DS> = {\n derived: DS;\n ds: DS;\n};\n\nexport type ContextBase<S, P> = ContextState<S> & {\n props: P;\n p: P;\n};\n\nexport type ContextWithDerived<S, DS, P> = ContextBase<S, P> & ContextDerivedStateState<DS>;\n\nexport type InvocationContextActions<A> = {\n actions: A;\n a: A;\n};\n\nexport type WarningNotifyFunc = {\n notifyWarning?: NotifyFunc;\n};\n\nexport type InvocationContext<S, DS, F extends (...args: any[]) => any, P> = ContextWithDerived<S, DS, P> & {\n args: Parameters<F>;\n promiseId: string;\n};\n\nexport type EffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P> = InvocationContext<S, DS, F, P> & {\n result: PromiseResult<ReturnType<F>>;\n res: PromiseResult<ReturnType<F>>;\n};\n\nexport type GetPromiseInvocationContext<S, DS, F extends (...args: any[]) => any, P, A> = InvocationContextActions<A> &\n InvocationContext<S, DS, F, P> & {\n abortSignal: AbortSignal;\n };\n\nexport type ErrorEffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P> = InvocationContext<\n S,\n DS,\n F,\n P\n> & {\n error: Error;\n err: Error;\n};\n\nexport type SuccessMessageInvocationContext<S, DS, F extends (...args: any[]) => any, P> = EffectsInvocationContext<\n S,\n DS,\n F,\n P\n>;\nexport type ErrorMessageInvocationContext<S, DS, F extends (...args: any[]) => any, P> = ErrorEffectsInvocationContext<\n S,\n DS,\n F,\n P\n>;\n\nexport type SideEffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P, A> = EffectsInvocationContext<\n S,\n DS,\n F,\n P\n> &\n InvocationContextActions<A> &\n WarningNotifyFunc;\n\nexport type ErrorSideEffectsInvocationContext<\n S,\n DS,\n F extends (...args: any[]) => any,\n P,\n A\n> = ErrorEffectsInvocationContext<S, DS, F, P> & InvocationContextActions<A> & WarningNotifyFunc;\n\nexport type OnMountInvocationContext<S, A, P> = ContextBase<S, P> & InvocationContextActions<A>;\n\nexport type EffectsType = 'preEffects' | 'effects' | 'errorEffects' | 'optimisticEffects' | null;\n\nexport type MiddlewareActionContext<S, A, P> = {\n name: keyof A;\n type: EffectsType;\n isAsync: boolean;\n context: InvocationContext<S, any, any, P>;\n};\n\nexport type MiddlewareStoreContext<S, A extends DecoratedActions, P> = {\n actions: StoreActions<S, A, P, any, any>;\n state: S;\n setState: (s: S) => void;\n options: StoreOptions<S, A, P, any>;\n};\n\nexport type MiddlewareFactory<S, A extends DecoratedActions, P> = () => Middleware<S, A, P>;\n\n/**\n * A state change middleware.\n * Allow to listen and change a state change on the fly.\n */\nexport type Middleware<S, A extends DecoratedActions, P> = {\n /**\n * Initializes the middleware. Called when the store is initializing.\n */\n init: (storeContext: MiddlewareStoreContext<S, A, P>) => void;\n\n /**\n * Invoked on a state change has occurred and returns a new state or <code>null</code> if unchanged.\n */\n effects: (\n actionContext: MiddlewareActionContext<S, A, P>,\n oldState: S,\n newState: S,\n loading: boolean\n ) => null | {\n state: S;\n loading: boolean;\n };\n\n /**\n * Destroys the middleware. Called when the store is being destroyed.\n */\n destroy: () => void;\n};\n\nexport type AsyncActionBase<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = {\n /**\n * This action can be aborted. An abortSignal will be injected to the <code>promise</code> / <code>promiseGet</code>.\n */\n abortable?: boolean;\n\n /**\n * A function that provides the success message to pass to the notifySuccess function passed as property to the StateDecorator.\n */\n getSuccessMessage?: (ctx: SuccessMessageInvocationContext<S, DS, F, P>) => string;\n\n /**\n * A function that provides the error message to pass to the notifyError function passed as property to the StateDecorator.\n */\n getErrorMessage?: GetErrorMessage<S, DS, F, P>;\n\n /**\n * If set, called with the result of the promise to update the current state.\n */\n effects?: (ctx: EffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * If set, called with the error of the promise to update the current state.\n */\n errorEffects?: (ctx: ErrorEffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Whether reject the promise instead of handling it.\n */\n rejectPromiseOnError?: boolean;\n\n /**\n * Handle side effects when the request succeeded.\n * @param result The result of the request\n * @param newData The data after the reducer is applied\n * @param args The argument during the call of the request function\n * @param props The props passed to the state decorator\n * @param actions The actions available\n * @param notifyWarning If specified, a notify function to indicate that the action is a semi success (use successMessage / getSuccessMessage otherwise).\n */\n sideEffects?: (ctx: SideEffectsInvocationContext<S, DS, F, P, A>) => void;\n\n /**\n * Handle side effects when the request failed.\n * @param error The error of the request\n * @param args The argument during the call of the request function\n * @param props The props passed to the state decorator\n * @param actions The actions available\n * @param notifyWarning If specified, a notify function to indicate that the action is a semi failure (use errorMessage / getErrorMessage otherwise).\n */\n errorSideEffects?: (ctx: ErrorSideEffectsInvocationContext<S, DS, F, P, A>) => void;\n\n /**\n * Retrieve the state to set as current data before the promise is resolved.\n * If the there's no reducer, this data will be used after the promise is done.\n */\n preEffects?: (ctx: InvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Retrieve the state to set as current data before the promise is resolved.\n * If the there's no reducer, this data will be used after the promise is done.\n */\n optimisticEffects?: (ctx: InvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Policy to apply when a call to an asynchronous action is done but a previous call is still not resolved.\n */\n conflictPolicy?: ConflictPolicy;\n\n /**\n * Get an identifier for an action call. Used only when conflictPolicy is ConflictPolicy.PARALLEL.\n * This information will be available in loadingMap. loadingMap[actionName] will be an array of promise identifiers.\n */\n getPromiseId?: (...args: Parameters<F>) => string;\n\n /**\n * Number of retries in case of error (failed to fetch).\n * Do not use this if you are creating objects...\n * Default value is 0 (no retry).\n */\n retryCount?: number;\n\n /**\n * Seed of delay between each retry in milliseconds.\n * The applied delay is retryDelaySeed * retry count.\n * Default value is 1000 (1 second).\n */\n retryDelaySeed?: number;\n\n /**\n * Function to test if the error will trigger an action retry or will fail directly.\n */\n isTriggerRetryError?: (e: Error) => boolean;\n};\n\nexport type AsyncActionPromise<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> = AsyncActionBase<\n S,\n F,\n A,\n P,\n DS,\n FxRes\n> & {\n /**\n * The request, returns a promise\n */\n getPromise: PromiseProvider<S, DS, F, A, P>;\n};\n\nexport type AsyncActionPromiseGet<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = AsyncActionBase<\n S,\n F,\n A,\n P,\n DS,\n FxRes\n> & {\n /**\n * The request, returns a promise that is a GET request.\n * A shortcut to set:\n * - retryCount: 3\n * - conflictPolicy: ConflictPolicy.REUSE\n */\n getGetPromise: PromiseProvider<S, DS, F, A, P>;\n};\n\nexport type AsyncAction<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> =\n | AsyncActionPromise<S, F, A, P, DS, FxRes>\n | AsyncActionPromiseGet<S, F, A, P, DS, FxRes>;\n\nexport type StoreAction<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> =\n | AsyncAction<S, F, A, P, DS, FxRes>\n | SimpleSyncAction<S, F, P, DS, FxRes>\n | SyncAction<S, F, A, P, DS, FxRes>;\n\n/**\n * S: The type of the state\n * A: The type of the actions to pass to the children (used to check keys only).\n */\nexport type StoreActions<S, A extends DecoratedActions, P = {}, DS = {}, FxRes = S> = {\n [Prop in keyof A]: StoreAction<S, A[Prop], A, P, DS, FxRes>;\n};\n\nexport type OnPropsChangeEffectsContext<S, DS, P> = ContextWithDerived<S, DS, P> & {\n indices: number[];\n index: number;\n isInit: boolean;\n};\n\nexport type OnPropsChangeSideEffectsContext<S, P, A, DS = {}> = OnPropsChangeEffectsContext<S, DS, P> & {\n actions: A;\n a: A;\n};\n\ntype DerivedStateOption<S, P, DS> = {\n [k in keyof DS]: {\n getDeps: (ctx: ContextBase<S, P>) => any[];\n get: (ctx: ContextBase<S, P>) => DS[k];\n };\n};\n\nexport type OnPropsChangeOptions<S, DS, A, P> = {\n onMount?: boolean;\n getDeps: (p: P) => any[];\n effects?: (ctx: OnPropsChangeEffectsContext<S, DS, P>) => S;\n sideEffects?: (ctx: OnPropsChangeSideEffectsContext<S, P, A>) => void;\n};\n\nexport type StoreOptions<S, A, P = {}, DS = {}> = {\n /**\n * The state decorator name. Use in debug traces to identify the useStateDecorator instance.\n */\n name?: string;\n\n /**\n * List of action names that are marked as loading at initial time.\n * If you must start your initial actions in a useSideEffect, a render is done before\n * first actions can be trigerred, some actions can be marked as loading at initial time.\n */\n initialActionsMarkedLoading?: (keyof A)[];\n\n /**\n * One or several configurations of inbound properties change managements.\n */\n onPropsChange?: OnPropsChangeOptions<S, DS, A, P> | OnPropsChangeOptions<S, DS, A, P>[];\n\n /**\n * The callback function called if an asynchronous function succeeded and a success messsage is defined.\n */\n notifySuccess?: NotifyFunc;\n\n /**\n * The callback function called if an asynchronous function fails and an error messsage is defined.\n */\n notifyError?: NotifyFunc;\n\n /**\n * The callback function injected in onDone and onFail of asynchronous functions to notify a semi success / failed request.\n */\n notifyWarning?: NotifyFunc;\n\n /**\n * Initial actions.\n */\n onMount?: (ctx: OnMountInvocationContext<S, A, P>) => void;\n\n /**\n * Callback on store destruction.\n */\n onUnmount?: (ctx: OnMountInvocationContext<S, A, P>) => Promise<any> | void;\n\n /**\n * Compute derived state\n */\n derivedState?: DerivedStateOption<S, P, DS>;\n};\n","function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nmodule.exports = _arrayWithHoles;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _iterableToArrayLimit(arr, i) {\n if (typeof Symbol === \"undefined\" || !(Symbol.iterator in Object(arr))) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nmodule.exports = _iterableToArrayLimit;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) {\n arr2[i] = arr[i];\n }\n\n return arr2;\n}\n\nmodule.exports = _arrayLikeToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","var arrayLikeToArray = require(\"./arrayLikeToArray.js\");\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}\n\nmodule.exports = _unsupportedIterableToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nmodule.exports = _nonIterableRest;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","var arrayWithHoles = require(\"./arrayWithHoles.js\");\n\nvar iterableToArrayLimit = require(\"./iterableToArrayLimit.js\");\n\nvar unsupportedIterableToArray = require(\"./unsupportedIterableToArray.js\");\n\nvar nonIterableRest = require(\"./nonIterableRest.js\");\n\nfunction _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}\n\nmodule.exports = _slicedToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nmodule.exports = _defineProperty;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","/*\n * Copyright 2019 Globalsport SAS\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\nimport { Context, useContext, useEffect, useLayoutEffect, useMemo, useReducer, useRef } from 'react';\nimport {\n computeAsyncActionInput,\n createRef,\n isSyncAction,\n isAsyncAction,\n isSimpleSyncAction,\n TimeoutMap,\n PromiseMap,\n DEFAULT_PROMISE_ID,\n globalConfig,\n setGlobalConfig,\n GlobalConfig,\n ConflictActionsMap,\n buildOnMountInvocationContext,\n decorateSimpleSyncAction,\n decorateSyncAction,\n decorateAsyncAction,\n computeDerivedValues,\n DerivedState,\n onPropChange,\n runMiddlewares,\n buildLoadingMap,\n isLoadingImpl,\n} from './impl';\n\nimport {\n DecoratedActions,\n StoreActions,\n AsyncAction,\n SyncAction,\n SimpleSyncAction,\n InternalLoadingMap,\n LoadingMap,\n LoadingParallelMap,\n StoreOptions,\n AsyncActionPromise,\n InvocationContext,\n GetPromiseInvocationContext,\n EffectsInvocationContext,\n InvocationContextActions,\n WarningNotifyFunc,\n ErrorEffectsInvocationContext,\n OnMountInvocationContext,\n ContextBase,\n OnPropsChangeEffectsContext,\n ContextState,\n ConflictPolicy,\n Middleware,\n AbortActionCallback,\n MiddlewareFactory,\n MiddlewareStoreContext,\n LoadingProps,\n} from './types';\n\nexport {\n DecoratedActions,\n StoreActions,\n LoadingMap,\n StoreOptions,\n LoadingParallelMap,\n AsyncActionPromise as AsynchActionPromise,\n InvocationContext,\n GetPromiseInvocationContext,\n EffectsInvocationContext,\n InvocationContextActions,\n WarningNotifyFunc,\n ErrorEffectsInvocationContext,\n OnMountInvocationContext,\n ContextBase,\n OnPropsChangeEffectsContext,\n SyncAction,\n AsyncAction,\n SimpleSyncAction,\n ContextState,\n ConflictPolicy,\n GlobalConfig,\n Middleware,\n setGlobalConfig,\n LoadingProps,\n AbortActionCallback,\n};\n\nexport type IsLoadingFunc<A> = (...props: (keyof A | [keyof A, string])[]) => boolean;\ntype StateListenerUnregister = () => void;\n\nexport type StoreApi<S, A extends DecoratedActions, P, DS = {}> = {\n /**\n * The current store state (with derived state if any).\n */\n readonly state: S & DS;\n /**\n * The store decorator (ie. ready to use) actions.\n */\n readonly actions: A;\n /**\n * A boolean that indicates that at least one asynchronous action is loading.\n */\n readonly loading: boolean;\n /**\n * A map of loading actions map (computed on property access)\n */\n readonly loadingMap: LoadingMap<A>;\n /**\n * A map of parallel loading actions map (computed on property access)\n */\n readonly loadingParallelMap: LoadingParallelMap<A>;\n /**\n * Initializes the store with the specified props\n */\n init: (p: P) => void;\n /**\n * Update the store with the specified props\n */\n setProps: (p: P) => void;\n /**\n * Destroy the store\n */\n destroy: () => void;\n /**\n * Abort an asynchronous action marked as abortable.\n */\n abortAction: (actionName: keyof A, promiseId?: string) => boolean;\n /**\n * Add a store state change listener\n */\n addStateListener: (listener: StateListener<S, DS, A>) => StateListenerUnregister;\n /**\n * A function that takes a list of action names or a tuple of [action name, promiseId] and returns <code>true</code> if any action is loading.\n */\n isLoading: IsLoadingFunc<A>;\n\n getConfig: () => {\n getInitialState: (p: P) => S;\n options: StoreOptions<S, A, P, DS>;\n actions: StoreActions<S, A, P, DS>;\n };\n};\n\nexport type StateListenerContext<S, DS, A extends DecoratedActions> = S &\n DS &\n A &\n Pick<StoreApi<S, A, any, DS>, 'loading' | 'loadingMap' | 'isLoading' | 'abortAction'>;\n\nexport type StateListener<S, DS, A extends DecoratedActions> = (ctx: StateListenerContext<S, DS, A>) => void;\n\n// =============================\n//\n// STORE\n//\n// =============================\n\n/**\n * Create a new store.\n * @param getInitialState The state initialization function (using props)\n * @param actionsImpl The actions implementation (pure functions only).\n * @param options Options to configure the store\n * @returns a store.\n */\nexport function createStore<S, A extends DecoratedActions, P, DS = {}>(\n getInitialState: (p: P) => S,\n actionsImpl: StoreActions<S, A, P, DS>,\n options: StoreOptions<S, A, P, DS> = {},\n storeMiddlewares: MiddlewareFactory<S, A, P>[] = null\n): StoreApi<S, A, P, DS> {\n const stateRef = createRef<S>();\n const derivedStateRef = createRef<DerivedState<DS>>();\n const propsRef = createRef<P>();\n const actionsRef = createRef<A>();\n const timeoutRef = createRef<TimeoutMap<A>>();\n const loadingMapRef = createRef<InternalLoadingMap<A>>();\n const promisesRef = createRef<PromiseMap<A>>();\n const conflictActionsRef = createRef<ConflictActionsMap<A>>();\n const initializedRef = createRef(false);\n\n const middlewaresRef = createRef<Middleware<S, A, P>[]>([]);\n\n let stateListeners: Record<string, StateListener<S, DS, A>> = {};\n let stateListenerCount = 0;\n\n function addStateListener(listener: StateListener<S, DS, A>): () => void {\n const id = `${stateListenerCount++}`;\n stateListeners[id] = listener;\n return () => {\n delete stateListeners[id];\n };\n }\n\n function notifyStateListeners(newState: S, derivedState: DS) {\n const s = {\n ...newState,\n ...derivedState,\n };\n\n const ctx: StateListenerContext<S, DS, A> = {\n ...s,\n ...actionsRef.current,\n isLoading,\n abortAction,\n loading: isAnyLoading(),\n loadingMap: getLoadingMap(),\n };\n\n Object.keys(stateListeners).forEach((listenerId) => {\n stateListeners[listenerId](ctx);\n });\n }\n\n function setProps(p: P) {\n const oldProps = propsRef.current;\n\n propsRef.current = p;\n\n if (!initializedRef.current) {\n init(p);\n } else {\n onPropChange(stateRef, derivedStateRef, propsRef, oldProps, actionsRef, options, setState, false);\n }\n }\n\n /** Middleware only: sets the internal state, recompute derived state and notify listeners */\n function setInternalState(s: S) {\n stateRef.current = s;\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n notifyStateListeners(stateRef.current, derivedStateRef.current.state);\n }\n\n function init(p: P) {\n if (!initializedRef.current) {\n propsRef.current = p;\n initializedRef.current = true;\n stateRef.current = getInitialState(p);\n\n const initialActionSet = new Set(options?.initialActionsMarkedLoading);\n\n loadingMapRef.current = (Object.keys(actionsImpl) as (keyof A)[]).reduce<InternalLoadingMap<A>>((acc, name) => {\n acc[name] = initialActionSet.has(name) ? { [DEFAULT_PROMISE_ID]: true } : {};\n return acc;\n }, {});\n\n timeoutRef.current = {};\n promisesRef.current = {};\n conflictActionsRef.current = {};\n derivedStateRef.current = {\n state: null,\n deps: {},\n };\n\n // init middlewares\n middlewaresRef.current = [];\n const ctx: MiddlewareStoreContext<S, A, P> = {\n options,\n get state() {\n return stateRef.current;\n },\n actions: actionsImpl,\n setState: setInternalState,\n };\n const mapper = (m: MiddlewareFactory<S, A, P>) => {\n const middleware = m();\n middlewaresRef.current.push(middleware);\n middleware.init?.(ctx);\n };\n globalConfig.defaultMiddlewares?.forEach(mapper);\n storeMiddlewares?.forEach(mapper);\n // end init\n\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n\n // manage PropsChange with onMount\n onPropChange(stateRef, derivedStateRef, propsRef, null, actionsRef, options, setState, true);\n\n if (options?.onMount) {\n options.onMount(buildOnMountInvocationContext(stateRef, derivedStateRef, propsRef, actionsRef));\n }\n\n notifyStateListeners(stateRef.current, derivedStateRef.current.state);\n }\n }\n\n function destroy() {\n if (initializedRef.current) {\n options?.onUnmount?.(buildOnMountInvocationContext(stateRef, derivedStateRef, propsRef, actionsRef));\n\n propsRef.current = null;\n stateRef.current = null;\n loadingMapRef.current = null;\n promisesRef.current = null;\n conflictActionsRef.current = null;\n derivedStateRef.current = null;\n\n Object.keys(timeoutRef.current).forEach((name) => {\n clearTimeout(timeoutRef.current[name]);\n });\n\n timeoutRef.current = null;\n stateListeners = {};\n initializedRef.current = false;\n\n middlewaresRef.current.forEach((m) => {\n m.destroy?.();\n });\n\n middlewaresRef.current = [];\n }\n }\n\n function setState(\n newStateIn: S,\n newLoadingMapIn: InternalLoadingMap<A>,\n actionName: keyof A,\n actionType: 'preEffects' | 'effects' | 'errorEffects' | null,\n isAsync: boolean,\n actionCtx: any,\n propsChanged: boolean = false,\n init = false\n ) {\n let hasChanged = false;\n\n if (!initializedRef.current) {\n return;\n }\n\n let newLoadingMap = newLoadingMapIn;\n\n const oldLoading = isAsync\n ? isLoadingImpl(newLoadingMap || loadingMapRef.current, [actionName, actionCtx?.promiseId])\n : false;\n\n const { newState, newLoading } = runMiddlewares(\n middlewaresRef.current,\n stateRef.current,\n newStateIn,\n oldLoading,\n actionName,\n actionType,\n isAsync,\n actionCtx\n );\n\n if (newState != null) {\n hasChanged = true;\n stateRef.current = newState;\n }\n\n if (oldLoading !== newLoading) {\n newLoadingMap = buildLoadingMap(\n newLoadingMap,\n actionName,\n actionCtx?.promiseId || DEFAULT_PROMISE_ID,\n newLoading\n );\n if (Object.keys(newLoadingMap).length === 0) {\n newLoadingMap = undefined;\n }\n }\n\n if (newLoadingMap != null) {\n hasChanged = true;\n loadingMapRef.current = newLoadingMap;\n }\n\n if (hasChanged) {\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n if (!init) {\n notifyStateListeners(newState || stateRef.current, derivedStateRef.current.state);\n }\n } else if (propsChanged) {\n const derivedChanged = computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n if (derivedChanged && !init) {\n notifyStateListeners(newState || stateRef.current, derivedStateRef.current.state);\n }\n }\n }\n\n const keys = Object.keys(actionsImpl) as (keyof A)[];\n actionsRef.current = keys.reduce<A>((acc, actionName) => {\n const action = actionsImpl[actionName];\n if (isSimpleSyncAction(action)) {\n acc[actionName] = decorateSimpleSyncAction(\n actionName,\n action,\n stateRef,\n derivedStateRef,\n propsRef,\n initializedRef,\n setState\n ) as any;\n } else if (isAsyncAction(action)) {\n acc[actionName] = decorateAsyncAction({\n actionName,\n stateRef,\n derivedStateRef,\n propsRef,\n loadingMapRef,\n actionsRef,\n promisesRef,\n conflictActionsRef,\n initializedRef,\n options,\n setState,\n action: computeAsyncActionInput(action),\n }) as any;\n } else if (isSyncAction(action)) {\n acc[actionName] = decorateSyncAction(\n actionName,\n action,\n stateRef,\n derivedStateRef,\n propsRef,\n actionsRef,\n initializedRef,\n timeoutRef,\n options,\n setState\n ) as any;\n }\n\n return acc;\n }, {} as A);\n\n function isLoading<K extends keyof A>(...props: (K | [K, string])[]) {\n return isLoadingImpl(loadingMapRef.current, ...props);\n }\n\n function abortAction(actionName: keyof A, promiseId: string = DEFAULT_PROMISE_ID) {\n const abortController = promisesRef.current[actionName]?.[promiseId]?.abortController;\n\n let res = false;\n if (abortController) {\n abortController.abort();\n res = true;\n }\n\n return res;\n }\n\n function isAnyLoading() {\n if (initializedRef.current) {\n const loadingMap = loadingMapRef.current;\n return (\n Object.keys(loadingMap).find((actionName) => {\n const promises = loadingMap[actionName];\n return Object.keys(promises).find((pId) => !!promises[pId]);\n }) != null\n );\n }\n return null;\n }\n\n function getLoadingMap() {\n if (initializedRef.current) {\n const map = loadingMapRef.current;\n const keys = Object.keys(map) as (keyof A)[];\n return keys.reduce<LoadingMap<A>>((acc, actionName) => {\n acc[actionName] = Object.keys(map[actionName]).find((pId) => !!map[actionName][pId]) != null;\n return acc;\n }, {});\n }\n return null;\n }\n\n function getConfig() {\n return {\n getInitialState,\n options,\n actions: actionsImpl,\n };\n }\n\n return {\n getConfig,\n setProps,\n addStateListener,\n init,\n destroy,\n isLoading,\n abortAction,\n get actions() {\n return actionsRef.current;\n },\n get state() {\n if (initializedRef.current) {\n return {\n ...stateRef.current,\n ...derivedStateRef.current.state,\n };\n }\n return null;\n },\n get loading() {\n return isAnyLoading();\n },\n get loadingMap() {\n return getLoadingMap();\n },\n get loadingParallelMap() {\n if (initializedRef.current) {\n return loadingMapRef.current;\n }\n return null;\n },\n };\n}\n\n// =====================================\n//\n// REACT HOOKS\n//\n// =====================================\n\ntype useStoreSlice<S, A extends DecoratedActions, P, DS, SLICE> = (\n store: StoreApi<S, A, P, DS>,\n slicer: (ctx: StateListenerContext<S, DS, A>) => SLICE\n) => SLICE;\n\n/**\n * A react hook to get a state slice. Will be refresh if, and only if, one property of the slice has changed\n * @param store The store to listen to.\n * @param slicerFunc A function that returns a state slice\n * @returns The state slice.\n */\nexport function useStoreSlice<S, A extends DecoratedActions, P, DS, SLICE>(\n store: StoreApi<S, A, P, DS>,\n slicerFunc: (ctx: StateListenerContext<S, DS, A>) => SLICE\n): SLICE;\n\n/**\n * A react hook to get a state slice. Will be refresh if, and only if, one property of the slice has changed\n * @param store The store to listen to.\n * @param properties list of properties to extract from store\n * @returns The state slice.\n */\nexport function useStoreSlice<\n S,\n A extends DecoratedActions,\n P,\n DS,\n K extends keyof StateListenerContext<S, DS, A>,\n KL extends keyof A\n>(\n store: StoreApi<S, A, P, DS>,\n properties: K[],\n loadingProps?: KL[]\n): Pick<StateListenerContext<S, DS, A>, K> & { loadingMap: LoadingMap<Pick<A, KL>> };\n\nexport function useStoreSlice<S, A extends DecoratedActions, P, DS>(\n store: StoreApi<S, A, P, DS>,\n funcOrArr: any,\n loadingProps?: any\n) {\n const [, forceRefresh] = useReducer((s) => (s > 100 ? 0 : s + 1), 0);\n\n const slicerFunc = useMemo(\n () => (funcOrArr instanceof Function ? funcOrArr : (ctx: StateListenerContext<S, DS, A>) => pick(ctx, funcOrArr)),\n [funcOrArr]\n );\n\n const loadingMapSlicer = useMemo(() => {\n return (ctx: StateListenerContext<S, DS, A>) =>\n loadingProps != null && loadingProps.length > 0 ? pick(ctx.loadingMap, loadingProps) : null;\n }, [loadingProps]);\n\n const sliceRef = useRef<any>(null);\n const loadingMapRef = useRef<LoadingMap<A>>(null);\n\n if (sliceRef.current === null) {\n const ctx = {\n ...store.state,\n ...store.actions,\n ...pick(store, ['loading', 'isLoading', 'abortAction', 'loadingMap']),\n };\n sliceRef.current = slicerFunc(ctx);\n loadingMapRef.current = loadingMapSlicer(ctx);\n }\n\n useLayoutEffect(() => {\n const unregister = store.addStateListener((ctx) => {\n let hasChanged = false;\n\n const slice = slicerFunc(ctx);\n const loadingSlice = loadingMapSlicer(ctx);\n const prevSlice = sliceRef.current;\n const compare = globalConfig.comparator;\n\n hasChanged = prevSlice == null || !compare(slice, prevSlice) || !compare(loadingSlice, loadingMapRef.current);\n\n sliceRef.current = slice;\n loadingMapRef.current = loadingSlice;\n\n if (hasChanged) {\n forceRefresh();\n }\n });\n\n return unregister;\n }, []);\n\n const slice = sliceRef.current;\n const loadingSlice = loadingMapRef.current;\n\n return loadingSlice == null ? slice : { ...slice, loadingMap: loadingSlice };\n}\n\n/**\n * A react hook to get a state slice from a store context.\n * The component be refreshed if, and only if, one property of the slice has changed.\n * @param store The store to listen to.\n * @param slicerFunc A function that returns a state slice\n * @returns The state slice.\n */\nexport function useStoreContextSlice<S, A extends DecoratedActions, P, DS, SLICE>(\n storeContext: Context<StoreApi<S, A, P, DS>>,\n slicerFunc: (ctx: StateListenerContext<S, DS, A>) => SLICE\n): SLICE;\n\n/**\n * A react hook to get a state slice from a store context.\n * The component will be refreshed if, and only if, one property of the slice has changed.\n * @param store The store to listen to.\n * @param properties list of properties to extract from store\n * @param loadingFlags list of action names to extract their loading state from store (available in loadingMap).\n * @returns The state slice.\n */\nexport function useStoreContextSlice<\n S,\n A extends DecoratedActions,\n P,\n DS,\n K extends keyof StateListenerContext<S, DS, A>,\n KL extends keyof A\n>(\n storeContext: Context<StoreApi<S, A, P, DS>>,\n properties: K[],\n loadingProps?: KL[]\n): Pick<StateListenerContext<S, DS, A>, K> & { loadingMap: LoadingMap<Pick<A, KL>> };\n\nexport function useStoreContextSlice<S, A extends DecoratedActions, P, DS>(\n storeContext: Context<StoreApi<S, A, P, DS>>,\n funcOrArr: any,\n loadingProps?: any\n) {\n const store = useContext(storeContext);\n return useStoreSlice(store, funcOrArr, loadingProps);\n}\n\n/**\n * Binds the store to this component.\n * Store will NOT be destroyed when component is unmouted.\n * Props passed to actions will come from this components.\n * If store is configured to react of props changes, it will used passed props.\n * The component will be refreshed for every change in the store.\n *\n * @param store The store to listen to.\n * @param props The parent component props\n * @returns The state, actions and isLoading function.\n */\nexport function useStore<S, A extends DecoratedActions, P, DS = {}>(store: StoreApi<S, A, P, DS>, props: P = null) {\n const [, forceRefresh] = useReducer((s) => (s > 100 ? 0 : s + 1), 0);\n\n const storeRef = useRef(store);\n\n store.setProps(props);\n\n useLayoutEffect(\n () =>\n storeRef.current.addStateListener(() => {\n forceRefresh();\n }),\n []\n );\n\n return {\n state: store.state,\n actions: store.actions,\n loading: store.loading,\n isLoading: store.isLoading,\n abortAction: store.abortAction,\n loadingMap: store.loadingMap,\n loadingParallelMap: store.loadingParallelMap,\n };\n}\n\n/**\n * Binds the store to this component.\n * Store will be destroyed when component is unmouted.\n * Props passed to actions will come from this components.\n * If store is configured to react of props changes, it will used passed props.\n * A store must be bound to only one React component.\n *\n * The component will NOT be refreshed for any change in the store.\n *\n * @param store The store to listen to.\n * @param props The parent component props\n * @deprecated Do not bind an instance to a component or use useGetLocalStore to create a store local to a component.\n */\nexport function useBindStore<S, A extends DecoratedActions, P, DS = {}>(store: StoreApi<S, A, P, DS>, props: P = null) {\n // access to store in debugger\n useRef(store);\n\n store.setProps(props);\n\n useEffect(\n () => () => {\n store.destroy();\n },\n []\n );\n return store;\n}\n\n/**\n * Creates a store as a ref to the owner component.\n * Store WILL be destroyed when component is unmouted.\n * Props passed to actions will come from owner components.\n * If store is configured to react of props changes, it will used passed props.\n *\n * This component will NOT be refreshed for any change in the store.\n *\n * @param getInitialState Function to compute initial state from props.\n * @param actionImpl Actions implementation.\n * @param props Owner component props to update state or react on prop changes\n * @param options The store options.\n * @returns store\n */\nexport function useGetLocalStore<S, A extends DecoratedActions, P, DS = {}>(\n getInitialState: (p: P) => S,\n actionImpl: StoreActions<S, A, P, DS>,\n props?: P,\n options?: StoreOptions<S, A, P, DS>,\n middlewares?: MiddlewareFactory<S, A, P>[]\n) {\n // access to store in debugger\n const storeRef = useRef<StoreApi<S, A, P, DS>>();\n if (storeRef.current == null) {\n storeRef.current = createStore(getInitialState, actionImpl, options, middlewares);\n }\n\n const store = storeRef.current;\n store.setProps(props);\n\n useEffect(\n () => () => {\n store.destroy();\n },\n []\n );\n\n return store;\n}\n\n/**\n * Creates and manages a local store.\n * The component will be refreshed for every change in the store.\n * Store will NOT be destroyed when component is unmouted.\n *\n * @param getInitialState Function to compute initial state from props.\n * @param actionImpl Actions implementation.\n * @param props Owner component props to update state or react on prop changes\n * @param options The store options.\n * @returns The state, actions and isLoading function.\n */\nexport function useLocalStore<S, A extends DecoratedActions, P, DS = {}>(\n getInitialState: (p: P) => S,\n actionImpl: StoreActions<S, A, P, DS>,\n props?: P,\n options?: StoreOptions<S, A, P, DS>,\n middlewares?: MiddlewareFactory<S, A, P>[]\n) {\n const storeRef = useRef<StoreApi<S, A, P, DS>>();\n if (storeRef.current == null) {\n storeRef.current = createStore(getInitialState, actionImpl, options, middlewares);\n }\n\n useEffect(\n () => () => {\n storeRef.current?.destroy();\n },\n []\n );\n\n return useStore(storeRef.current, props);\n}\n\nexport default useLocalStore;\n\n// ------------- UTILS\n\n/**\n * Creates a new object by picking properties to the object passed a first parameter\n * @param obj Object to pick properties from\n * @param props Property names\n * @returns a new object containing only picked properties\n */\nexport function pick<T, K extends keyof T>(obj: T, props: K[]): Pick<T, K> {\n return props.reduce((acc, p) => {\n if (obj.hasOwnProperty(p)) {\n acc[p] = obj[p];\n }\n return acc;\n }, {} as any);\n}\n\n/**\n * Returns a function that creates a new object by picking properties to the object passed as first parameter.\n * To be used in conjunction of <code>useStoreSlice</code> like in example:\n * const s = useStoreSlice(myStore, slice('list', 'addItem'));\n * @param props Property names\n * @returns a function to pick property from an passed object.\n */\nexport function slice<T, K extends keyof T>(...props: K[]): (obj: T) => Pick<T, K> {\n return (store: T) => pick(store, props);\n}\n"],"names":["ConflictPolicy","module","arr","Array","isArray","exports","i","Symbol","iterator","Object","_arr","_n","_d","_e","undefined","_s","_i","next","done","push","value","length","err","len","arr2","o","minLen","arrayLikeToArray","n","prototype","toString","call","slice","constructor","name","from","test","TypeError","arrayWithHoles","iterableToArrayLimit","unsupportedIterableToArray","nonIterableRest","obj","key","defineProperty","enumerable","configurable","writable","createStore","getInitialState","actionsImpl","options","storeMiddlewares","stateRef","createRef","derivedStateRef","propsRef","actionsRef","timeoutRef","loadingMapRef","promisesRef","conflictActionsRef","initializedRef","middlewaresRef","stateListeners","stateListenerCount","addStateListener","listener","id","notifyStateListeners","newState","derivedState","s","ctx","current","isLoading","abortAction","loading","isAnyLoading","loadingMap","getLoadingMap","keys","forEach","listenerId","setProps","p","oldProps","onPropChange","setState","init","setInternalState","computeDerivedValues","state","initialActionSet","Set","initialActionsMarkedLoading","reduce","acc","has","DEFAULT_PROMISE_ID","deps","actions","mapper","m","middleware","globalConfig","defaultMiddlewares","onMount","buildOnMountInvocationContext","destroy","onUnmount","clearTimeout","newStateIn","newLoadingMapIn","actionName","actionType","isAsync","actionCtx","propsChanged","hasChanged","newLoadingMap","oldLoading","isLoadingImpl","promiseId","runMiddlewares","newLoading","buildLoadingMap","derivedChanged","props","abortController","_promisesRef$current$","_promisesRef$current$2","res","abort","find","promises","pId","map","getConfig","action","isSimpleSyncAction","decorateSimpleSyncAction","isAsyncAction","decorateAsyncAction","computeAsyncActionInput","isSyncAction","decorateSyncAction","useStoreSlice","store","funcOrArr","loadingProps","useReducer","forceRefresh","slicerFunc","useMemo","Function","pick","loadingMapSlicer","sliceRef","useRef","useLayoutEffect","loadingSlice","prevSlice","compare","comparator","useStore","storeRef","loadingParallelMap","useLocalStore","actionImpl","middlewares","useEffect","hasOwnProperty","storeContext","useContext"],"mappings":"wRAmCYA,mBC/BZC,UAJA,SAAyBC,GACvB,GAAIC,MAAMC,QAAQF,GAAM,OAAOA,GAIjCD,EAAOI,QAAiB,QAAIJ,EAAOI,QAASJ,sBAA4B,sBCsBxEA,UA3BA,SAA+BC,EAAKI,GAClC,GAAsB,oBAAXC,QAA4BA,OAAOC,YAAYC,OAAOP,GAAjE,CACA,IAAIQ,EAAO,GACPC,GAAK,EACLC,GAAK,EACLC,OAAKC,EAET,IACE,IAAK,IAAiCC,EAA7BC,EAAKd,EAAIK,OAAOC,cAAmBG,GAAMI,EAAKC,EAAGC,QAAQC,QAChER,EAAKS,KAAKJ,EAAGK,QAETd,GAAKI,EAAKW,SAAWf,GAH8CK,GAAK,IAK9E,MAAOW,GACPV,GAAK,EACLC,EAAKS,UAEL,IACOX,GAAsB,MAAhBK,EAAW,QAAWA,EAAW,iBAE5C,GAAIJ,EAAI,MAAMC,GAIlB,OAAOH,IAITT,EAAOI,QAAiB,QAAIJ,EAAOI,QAASJ,sBAA4B,sBClBxEA,UAVA,SAA2BC,EAAKqB,IACnB,MAAPA,GAAeA,EAAMrB,EAAImB,UAAQE,EAAMrB,EAAImB,QAE/C,IAAK,IAAIf,EAAI,EAAGkB,EAAO,IAAIrB,MAAMoB,GAAMjB,EAAIiB,EAAKjB,IAC9CkB,EAAKlB,GAAKJ,EAAII,GAGhB,OAAOkB,GAITvB,EAAOI,QAAiB,QAAIJ,EAAOI,QAASJ,sBAA4B,sBCAxEA,UATA,SAAqCwB,EAAGC,G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EACAwH,EACAzC,EACA7E,EACAuH,OAGMJ,EAAWP,WACO,MAApBO,EAAS5F,UACX4F,EAAS5F,QAAU1B,EAAYC,EAAiBwH,EAAYtH,EAASuH,QAGjEtB,EAAQkB,EAAS5F,eACvB0E,EAAMhE,SAAS4C,GAEf2C,aACE,kBAAM,WACJvB,EAAMvC,aAER,IAGKuC,oFA9GPyB,EACAxB,EACAC,UAGOH,EADO2B,aAAWD,GACGxB,EAAWC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "state-decorator",
3
- "version": "6.7.0",
3
+ "version": "6.8.0-beta.1",
4
4
  "description": "React state management library",
5
5
  "main": "index.js",
6
6
  "module": "index.es.js",