@lomray/react-mobx-manager 3.5.2 → 3.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/context.js +1 -1
- package/context.js.map +1 -1
- package/index.d.ts +1 -0
- package/index.js +1 -1
- package/logger.d.ts +66 -0
- package/logger.js +2 -0
- package/logger.js.map +1 -0
- package/manager.d.ts +6 -3
- package/manager.js +1 -1
- package/manager.js.map +1 -1
- package/package.json +1 -1
- package/types.d.ts +3 -0
package/context.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e,{useState as t,useEffect as r,useContext as
|
|
1
|
+
import e,{useState as t,useEffect as r,useContext as n}from"react";import{ROOT_CONTEXT_ID as o}from"./constants.js";const a=e.createContext({}),c=e.createContext(o),l=({parentId:t,children:r,touchableStores:n})=>{const o=s();return n&&o.touchedStores(n),e.createElement(c.Provider,{value:t,children:r})},i=({children:n,storeManager:o,fallback:c,shouldInit:i=!1})=>{const[s,d]=t(!i);return r((()=>{i&&o.init().then((()=>d(!0)))}),[i,o]),e.createElement(a.Provider,{value:o},e.createElement(l,{parentId:"root"},s?n:c||n))},s=()=>n(a),d=()=>n(c);export{a as StoreManagerContext,c as StoreManagerParentContext,l as StoreManagerParentProvider,i as StoreManagerProvider,s as useStoreManager,d as useStoreManagerParent};
|
|
2
2
|
//# sourceMappingURL=context.js.map
|
package/context.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","sources":["../src/context.tsx"],"sourcesContent":["import type { FC, ReactElement } from 'react';\nimport React, { useContext, useEffect, useState } from 'react';\nimport { ROOT_CONTEXT_ID } from './constants';\nimport type Manager from './manager';\nimport type { TStores } from './types';\n\ninterface IStoreManagerProvider {\n storeManager: Manager;\n shouldInit?: boolean;\n fallback?: ReactElement;\n children?: React.ReactNode;\n}\n\ninterface IStoreManagerParentProvider {\n parentId: string;\n children?: React.ReactNode;\n touchableStores?: TStores;\n}\n\n/**\n * Mobx store manager context\n */\nconst StoreManagerContext = React.createContext<Manager>({} as Manager);\n\n/**\n * To spread relationships\n */\nconst StoreManagerParentContext =\n React.createContext<IStoreManagerParentProvider['parentId']>(ROOT_CONTEXT_ID);\n\n/**\n * Mobx store manager parent provider\n * @constructor\n */\nconst StoreManagerParentProvider: FC<Omit<IStoreManagerParentProvider, 'contextId'>> = ({\n parentId,\n children,\n touchableStores,\n}) => {\n const storeManager = useStoreManager();\n\n if (touchableStores) {\n storeManager.touchedStores(touchableStores);\n }\n\n return <StoreManagerParentContext.Provider value={parentId} children={children} />;\n};\n\n/**\n * Mobx store manager provider\n * @constructor\n */\nconst StoreManagerProvider: FC<IStoreManagerProvider> = ({\n children,\n storeManager,\n fallback,\n shouldInit = false,\n}) => {\n const [isInit, setInit] = useState(!shouldInit);\n\n useEffect(() => {\n if (!shouldInit) {\n return;\n }\n\n storeManager
|
|
1
|
+
{"version":3,"file":"context.js","sources":["../src/context.tsx"],"sourcesContent":["import type { FC, ReactElement } from 'react';\nimport React, { useContext, useEffect, useState } from 'react';\nimport { ROOT_CONTEXT_ID } from './constants';\nimport type Manager from './manager';\nimport type { TStores } from './types';\n\ninterface IStoreManagerProvider {\n storeManager: Manager;\n shouldInit?: boolean;\n fallback?: ReactElement;\n children?: React.ReactNode;\n}\n\ninterface IStoreManagerParentProvider {\n parentId: string;\n children?: React.ReactNode;\n touchableStores?: TStores;\n}\n\n/**\n * Mobx store manager context\n */\nconst StoreManagerContext = React.createContext<Manager>({} as Manager);\n\n/**\n * To spread relationships\n */\nconst StoreManagerParentContext =\n React.createContext<IStoreManagerParentProvider['parentId']>(ROOT_CONTEXT_ID);\n\n/**\n * Mobx store manager parent provider\n * @constructor\n */\nconst StoreManagerParentProvider: FC<Omit<IStoreManagerParentProvider, 'contextId'>> = ({\n parentId,\n children,\n touchableStores,\n}) => {\n const storeManager = useStoreManager();\n\n if (touchableStores) {\n storeManager.touchedStores(touchableStores);\n }\n\n return <StoreManagerParentContext.Provider value={parentId} children={children} />;\n};\n\n/**\n * Mobx store manager provider\n * @constructor\n */\nconst StoreManagerProvider: FC<IStoreManagerProvider> = ({\n children,\n storeManager,\n fallback,\n shouldInit = false,\n}) => {\n const [isInit, setInit] = useState(!shouldInit);\n\n useEffect(() => {\n if (!shouldInit) {\n return;\n }\n\n void storeManager.init().then(() => setInit(true));\n }, [shouldInit, storeManager]);\n\n return (\n <StoreManagerContext.Provider value={storeManager}>\n <StoreManagerParentProvider parentId=\"root\">\n {isInit ? children : fallback || children}\n </StoreManagerParentProvider>\n </StoreManagerContext.Provider>\n );\n};\n\nconst useStoreManager = (): Manager => useContext(StoreManagerContext);\n\nconst useStoreManagerParent = (): IStoreManagerParentProvider['parentId'] =>\n useContext(StoreManagerParentContext);\n\nexport {\n StoreManagerContext,\n StoreManagerParentContext,\n StoreManagerProvider,\n StoreManagerParentProvider,\n useStoreManager,\n useStoreManagerParent,\n};\n"],"names":["StoreManagerContext","React","createContext","StoreManagerParentContext","ROOT_CONTEXT_ID","StoreManagerParentProvider","parentId","children","touchableStores","storeManager","useStoreManager","touchedStores","createElement","Provider","value","StoreManagerProvider","fallback","shouldInit","isInit","setInit","useState","useEffect","init","then","useContext","useStoreManagerParent"],"mappings":"oHAsBM,MAAAA,EAAsBC,EAAMC,cAAuB,IAKnDC,EACJF,EAAMC,cAAuDE,GAMzDC,EAAiF,EACrFC,WACAC,WACAC,sBAEA,MAAMC,EAAeC,IAMrB,OAJIF,GACFC,EAAaE,cAAcH,GAGtBP,EAACW,cAAAT,EAA0BU,SAAS,CAAAC,MAAOR,EAAUC,SAAUA,GAAY,EAO9EQ,EAAkD,EACtDR,WACAE,eACAO,WACAC,cAAa,MAEb,MAAOC,EAAQC,GAAWC,GAAUH,GAUpC,OARAI,GAAU,KACHJ,GAIAR,EAAaa,OAAOC,MAAK,IAAMJ,GAAQ,IAAM,GACjD,CAACF,EAAYR,IAGdR,gBAACD,EAAoBa,SAAS,CAAAC,MAAOL,GACnCR,EAACW,cAAAP,GAA2BC,SAAS,QAClCY,EAASX,EAAWS,GAAYT,GAGrC,EAGEG,EAAkB,IAAec,EAAWxB,GAE5CyB,EAAwB,IAC5BD,EAAWrB"}
|
package/index.d.ts
CHANGED
package/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{StoreManagerContext,StoreManagerParentContext,StoreManagerParentProvider,StoreManagerProvider,useStoreManager,useStoreManagerParent}from"./context.js";export{default as Manager}from"./manager.js";export{default as onChangeListener}from"./on-change-listener.js";export{default as wakeup}from"./wakeup.js";export{default as withStores}from"./with-stores.js";export{isPropExcludedFromExport,isPropObservableExported,isPropSimpleExported,makeExported}from"./make-exported.js";export{default as Events}from"./events.js";
|
|
1
|
+
export{StoreManagerContext,StoreManagerParentContext,StoreManagerParentProvider,StoreManagerProvider,useStoreManager,useStoreManagerParent}from"./context.js";export{default as Manager}from"./manager.js";export{default as onChangeListener}from"./on-change-listener.js";export{default as wakeup}from"./wakeup.js";export{default as withStores}from"./with-stores.js";export{isPropExcludedFromExport,isPropObservableExported,isPropSimpleExported,makeExported}from"./make-exported.js";export{default as Events}from"./events.js";export{default as Logger}from"./logger.js";
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/logger.d.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import Manager from "./manager.js";
|
|
2
|
+
interface ILoggerOpts {
|
|
3
|
+
/**
|
|
4
|
+
* 0 - disabled
|
|
5
|
+
* 1 - error
|
|
6
|
+
* 2 - warning
|
|
7
|
+
* 3 - info
|
|
8
|
+
* 4 - debug
|
|
9
|
+
*/
|
|
10
|
+
level: number;
|
|
11
|
+
manager: Manager;
|
|
12
|
+
}
|
|
13
|
+
interface ILoggerLogOpts {
|
|
14
|
+
level: ILoggerOpts['level'];
|
|
15
|
+
err?: Error;
|
|
16
|
+
payload?: Record<string, any>;
|
|
17
|
+
}
|
|
18
|
+
declare class Logger {
|
|
19
|
+
/**
|
|
20
|
+
* Logger options
|
|
21
|
+
*/
|
|
22
|
+
protected options: ILoggerOpts;
|
|
23
|
+
/**
|
|
24
|
+
* @constructor
|
|
25
|
+
*/
|
|
26
|
+
/**
|
|
27
|
+
* @constructor
|
|
28
|
+
*/
|
|
29
|
+
constructor(opts: ILoggerOpts);
|
|
30
|
+
/**
|
|
31
|
+
* Log message
|
|
32
|
+
*/
|
|
33
|
+
/**
|
|
34
|
+
* Log message
|
|
35
|
+
*/
|
|
36
|
+
log(msg: string, { level, err, payload }: ILoggerLogOpts): void;
|
|
37
|
+
/**
|
|
38
|
+
* Log error message
|
|
39
|
+
*/
|
|
40
|
+
/**
|
|
41
|
+
* Log error message
|
|
42
|
+
*/
|
|
43
|
+
err(msg: string, err?: unknown, payload?: Record<string, any>): void;
|
|
44
|
+
/**
|
|
45
|
+
* Log warning message
|
|
46
|
+
*/
|
|
47
|
+
/**
|
|
48
|
+
* Log warning message
|
|
49
|
+
*/
|
|
50
|
+
warn(msg: string, payload?: Record<string, any>): void;
|
|
51
|
+
/**
|
|
52
|
+
* Log info message
|
|
53
|
+
*/
|
|
54
|
+
/**
|
|
55
|
+
* Log info message
|
|
56
|
+
*/
|
|
57
|
+
info(msg: string, payload?: Record<string, any>): void;
|
|
58
|
+
/**
|
|
59
|
+
* Log debug message
|
|
60
|
+
*/
|
|
61
|
+
/**
|
|
62
|
+
* Log debug message
|
|
63
|
+
*/
|
|
64
|
+
debug(msg: string, payload?: Record<string, any>, hasSnapshot?: boolean): void;
|
|
65
|
+
}
|
|
66
|
+
export { Logger as default, ILoggerOpts, ILoggerLogOpts };
|
package/logger.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
class e{options;constructor(e){this.options=e}log(e,{level:o,err:l,payload:a}){if(this.options.level<o)return;let t="log";switch(o){case 1:t="error";break;case 2:t="warn";break;case 3:t="info"}console[t](...[e,l,a].filter(Boolean))}err(e,o,l){this.log(e,{err:o,level:1,payload:l})}warn(e,o){this.log(e,{level:2,payload:o})}info(e,o){this.log(e,{level:3,payload:o})}debug(e,o={},l=!1){l&&(o.additional={relations:Object.fromEntries(this.options.manager.getStoresRelations().entries())}),this.log(`DEBUG: ${e}`,{level:4,payload:{...o}})}}export{e as default};
|
|
2
|
+
//# sourceMappingURL=logger.js.map
|
package/logger.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger.js","sources":["../src/logger.ts"],"sourcesContent":["import type Manager from './manager';\n\nexport interface ILoggerOpts {\n /**\n * 0 - disabled\n * 1 - error\n * 2 - warning\n * 3 - info\n * 4 - debug\n */\n level: number;\n manager: Manager;\n}\n\nexport interface ILoggerLogOpts {\n level: ILoggerOpts['level'];\n err?: Error;\n payload?: Record<string, any>;\n}\n\nclass Logger {\n /**\n * Logger options\n */\n protected options: ILoggerOpts;\n\n /**\n * @constructor\n */\n constructor(opts: ILoggerOpts) {\n this.options = opts;\n }\n\n /**\n * Log message\n */\n public log(msg: string, { level, err, payload }: ILoggerLogOpts): void {\n if (this.options.level < level) {\n return;\n }\n\n let type = 'log';\n\n switch (level) {\n case 1:\n type = 'error';\n break;\n\n case 2:\n type = 'warn';\n break;\n\n case 3:\n type = 'info';\n break;\n }\n\n console[type](...[msg, err, payload].filter(Boolean));\n }\n\n /**\n * Log error message\n */\n public err(msg: string, err?: unknown, payload?: Record<string, any>): void {\n this.log(msg, { err: err as Error, level: 1, payload });\n }\n\n /**\n * Log warning message\n */\n public warn(msg: string, payload?: Record<string, any>): void {\n this.log(msg, { level: 2, payload });\n }\n\n /**\n * Log info message\n */\n public info(msg: string, payload?: Record<string, any>): void {\n this.log(msg, { level: 3, payload });\n }\n\n /**\n * Log debug message\n */\n public debug(msg: string, payload: Record<string, any> = {}, hasSnapshot = false): void {\n if (hasSnapshot) {\n payload.additional = {\n relations: Object.fromEntries(this.options.manager.getStoresRelations().entries()),\n };\n }\n\n this.log(`DEBUG: ${msg}`, { level: 4, payload: { ...payload } });\n }\n}\n\nexport default Logger;\n"],"names":["Logger","options","constructor","opts","this","log","msg","level","err","payload","type","console","filter","Boolean","warn","info","debug","hasSnapshot","additional","relations","Object","fromEntries","manager","getStoresRelations","entries"],"mappings":"AAoBA,MAAMA,EAIMC,QAKVC,YAAYC,GACVC,KAAKH,QAAUE,CAChB,CAKME,IAAIC,GAAaC,MAAEA,EAAKC,IAAEA,EAAGC,QAAEA,IACpC,GAAIL,KAAKH,QAAQM,MAAQA,EACvB,OAGF,IAAIG,EAAO,MAEX,OAAQH,GACN,KAAK,EACHG,EAAO,QACP,MAEF,KAAK,EACHA,EAAO,OACP,MAEF,KAAK,EACHA,EAAO,OAIXC,QAAQD,MAAS,CAACJ,EAAKE,EAAKC,GAASG,OAAOC,SAC7C,CAKML,IAAIF,EAAaE,EAAeC,GACrCL,KAAKC,IAAIC,EAAK,CAAEE,IAAKA,EAAcD,MAAO,EAAGE,WAC9C,CAKMK,KAAKR,EAAaG,GACvBL,KAAKC,IAAIC,EAAK,CAAEC,MAAO,EAAGE,WAC3B,CAKMM,KAAKT,EAAaG,GACvBL,KAAKC,IAAIC,EAAK,CAAEC,MAAO,EAAGE,WAC3B,CAKMO,MAAMV,EAAaG,EAA+B,CAAA,EAAIQ,GAAc,GACrEA,IACFR,EAAQS,WAAa,CACnBC,UAAWC,OAAOC,YAAYjB,KAAKH,QAAQqB,QAAQC,qBAAqBC,aAI5EpB,KAAKC,IAAI,UAAUC,IAAO,CAAEC,MAAO,EAAGE,QAAS,IAAKA,IACrD"}
|
package/manager.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import Logger from "./logger.js";
|
|
1
2
|
import CombinedStorage from "./storages/combined-storage.js";
|
|
2
3
|
import StoreStatus from "./store-status.js";
|
|
3
4
|
import { IConstructableStore, IGroupedStores, IManagerOptions, IManagerParams, IPersistOptions, IStoreParams, IStorePersisted, TAnyStore, TInitStore, TStoreDefinition, TStores } from "./types.js";
|
|
@@ -46,13 +47,17 @@ declare class Manager {
|
|
|
46
47
|
* @see withStores
|
|
47
48
|
*/
|
|
48
49
|
protected suspenseRelations: Map<string, Set<string>>;
|
|
50
|
+
/**
|
|
51
|
+
* Mobx manager logger
|
|
52
|
+
*/
|
|
53
|
+
protected readonly logger: Logger;
|
|
49
54
|
/**
|
|
50
55
|
* @constructor
|
|
51
56
|
*/
|
|
52
57
|
/**
|
|
53
58
|
* @constructor
|
|
54
59
|
*/
|
|
55
|
-
constructor({ initState, storesParams, storage, options }?: IManagerParams);
|
|
60
|
+
constructor({ initState, storesParams, storage, options, logger }?: IManagerParams);
|
|
56
61
|
/**
|
|
57
62
|
* Init store manager
|
|
58
63
|
*/
|
|
@@ -102,11 +107,9 @@ declare class Manager {
|
|
|
102
107
|
pushInitState: (storesState?: Record<string, any>) => void;
|
|
103
108
|
/**
|
|
104
109
|
* Get store identity
|
|
105
|
-
* @protected
|
|
106
110
|
*/
|
|
107
111
|
/**
|
|
108
112
|
* Get store identity
|
|
109
|
-
* @protected
|
|
110
113
|
*/
|
|
111
114
|
protected getStoreId<T extends TAnyStore>(store: IConstructableStore<T> | TInitStore, params?: IStoreParams): string;
|
|
112
115
|
/**
|
package/manager.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import t from"@lomray/event-manager";import{toJS as e,isObservableProp as s}from"mobx";import{ROOT_CONTEXT_ID as o}from"./constants.js";import r from"./deep-merge.js";import i from"./events.js";import{isPropExcludedFromExport as
|
|
1
|
+
import t from"@lomray/event-manager";import{toJS as e,isObservableProp as s}from"mobx";import{ROOT_CONTEXT_ID as o}from"./constants.js";import r from"./deep-merge.js";import i from"./events.js";import n from"./logger.js";import{isPropExcludedFromExport as a,isPropSimpleExported as l,isPropObservableExported as h}from"./make-exported.js";import d from"./on-change-listener.js";import p from"./storages/combined-storage.js";import S from"./store-status.js";import c from"./wakeup.js";class u{static instance;stores=new Map;storesRelations=new Map;static persistedStores=new Set;initState;storage;storesParams;options={shouldDisablePersist:!1,shouldRemoveInitState:!0};suspenseRelations=new Map;logger;constructor({initState:t,storesParams:e,storage:s,options:o,logger:r}={}){if(this.initState=t||{},this.storesParams=e||{},this.logger=r&&"log"in r?r:new n({level:3,...r??{},manager:this}),this.storage=s instanceof p?s:s?new p({default:s}):void 0,Object.assign(this.options,o||{}),u.instance=this,"undefined"!=typeof window){const t=window.mbxM;window.mbxM={push:this.pushInitState},(Array.isArray(t)?t:[]).forEach(this.pushInitState)}}async init(){try{this.storage&&await this.storage.get()}catch(t){this.logger.err("Failed initialized store manager: ",t)}return this}static get(){if(!u.instance)throw new Error("Store manager is not initialized.");return u.instance}getStores(){return this.stores}getStoresRelations(){return this.storesRelations}getSuspenseRelations(){return this.suspenseRelations}static getPersistedStoresIds(){return u.persistedStores}pushInitState=(t={})=>{for(const[e,s]of Object.entries(t))this.initState[e]=s};getStoreId(t,e={}){const{id:s,contextId:o,key:r}=e;if(s)return s;if(t.libStoreId)return t.libStoreId;let i=t.id||t.name||t.constructor.name;return t.isGlobal?i:(i=`${i}--${o}`,r?`${i}--${r}`:i)}getStore(t,e={}){const s=this.getStoreId(t,e);return this.stores.has(s)?this.stores.get(s):t.isGlobal?this.createStore(t,{id:s,contextId:"global",parentId:o,suspenseId:"",componentName:"root-app",componentProps:{}}):this.lookupStore(s,e)}lookupStore(t,e){const{contextId:s,parentId:r}=e,i=t.split("--")?.[0],{ids:n,parentId:a}=this.storesRelations.get(s)??{ids:new Set,parentId:r},l=[...n].filter((t=>t.startsWith(`${i}--`)));if(1===l.length)return this.stores.get(l[0]);if(l.length>1)this.logger.err("Parent context has multiple stores with the same id, please pass key to getStore function.");else if(a&&a!==o)return this.lookupStore(t,{contextId:this.getBiggerContext(a,r)})}getBiggerContext(t,e){if(!t)return e;if(!e)return t;const s=/[^a-zA-Z]/g;return t.replace(s,"")>e.replace(s,"")?t:e}createStore(e,s){const{id:r,contextId:n,parentId:a,suspenseId:l,componentName:h,componentProps:d}=s;if(this.stores.has(r))return this.stores.get(r);const p=new e({...this.storesParams,storeManager:this,getStore:(t,e={contextId:n,parentId:a})=>this.getStore(t,e),componentProps:d,initState:this.initState[r]});return p.libStoreId=r,p.isGlobal=e.isGlobal,p.libStoreContextId=e.isGlobal?"global":n,p.libStoreParentId=e.isGlobal||!a||a===n?o:a,p.libStoreSuspenseId=l,p.libStoreComponentName=h,this.setStoreStatus(p,e.isGlobal?S.inUse:S.init),this.prepareStore(p),t.publish(i.CREATE_STORE,{store:e}),p}createStores(t,e,s,o,r,i={}){const n=t.reduce(((t,[n,a])=>{const{id:l,store:h,isParent:d=!1}="store"in a?a:{store:a,id:void 0,isParent:!1},p=l||(d?this.getStore(h,{contextId:s,parentId:e})?.libStoreId:this.getStoreId(h,{key:n,contextId:s}));if(!p){const i=`Cannot find or create store '${n}': '${this.getStoreId(h)}'`;return this.logger.warn(i),this.logger.debug(i,{contextId:s,parentId:e,suspenseId:o,componentName:r,isParent:d},!0),t}const S=this.createStore(h,{id:p,contextId:s,parentId:e,suspenseId:o,componentName:r,componentProps:i});return d?t.parentStores[n]=S:S.isGlobal?t.globalStores[n]=S:t.relativeStores[n]=S,t}),{relativeStores:{},parentStores:{},globalStores:{}});return this.createRelationContext(s,e,r),n}createRelationContext(t,e,s){this.storesRelations.has(t)||this.storesRelations.set(t,{ids:new Set,parentId:e&&e!==t?e:o,componentName:s})}removeRelationContext(t){const e=this.storesRelations.get(t);!e||t===o||e.ids.size>0||this.storesRelations.delete(t)}prepareStore(t){const e=t.libStoreId,s=t.libStoreContextId,o=t.libStoreSuspenseId;if(this.stores.has(e))return;const i=this.initState[e];if(i&&r(t,i),"wakeup"in t&&u.persistedStores.has(e)&&t.wakeup?.({initState:i,persistedState:this.storage?.getStoreData(t),manager:this}),u.persistedStores.has(e)&&"addOnChangeListener"in t){const e=t.onDestroy?.bind(t),s=t.addOnChangeListener(t,this);t.onDestroy=()=>{s?.(),e?.()}}t.init?.(),this.createRelationContext(s,t.libStoreParentId,t.libStoreComponentName),this.suspenseRelations.has(o)||this.suspenseRelations.set(o,new Set);const{ids:n}=this.storesRelations.get(s);this.stores.set(e,t),n.add(e),this.suspenseRelations.get(o).add(e)}removeStore(e){const s=e.libStoreId,o=e.libStoreSuspenseId,{ids:r}=this.storesRelations.get(e.libStoreContextId)??{ids:new Set};this.stores.has(s)&&(this.stores.delete(s),r.delete(s),o&&this.suspenseRelations.get(o)?.has(s)&&this.suspenseRelations.get(o).delete(s),this.removeRelationContext(e.libStoreContextId),"onDestroy"in e&&e.onDestroy?.(),t.publish(i.DELETE_STORE,{store:e}))}mountStores(e,{globalStores:s={},relativeStores:o={}}){const{shouldRemoveInitState:r}=this.options,n={...s,...o};return Object.values(n).forEach((e=>{const s=e.libStoreId;r&&this.initState[s]&&delete this.initState[s],this.setStoreStatus(e,S.inUse),t.publish(i.MOUNT_STORE,{store:e})})),()=>{Object.values(n).forEach((e=>{e.isGlobal||(this.setStoreStatus(e,S.unused),t.publish(i.UNMOUNT_STORE,{store:e}))})),this.removeRelationContext(e)}}touchedStores(t){Object.values(t).forEach((t=>{t.libStoreStatus!==S.init||t.isGlobal||this.setStoreStatus(t,S.touched)}))}setStoreStatus(t,e){const{destroyTimers:{init:s=500,touched:o=1e4,unused:r=1e3}={}}=this.options;t.libStoreStatus=e,clearTimeout(t.libDestroyTimer);let i=0;switch(e){case S.init:i=s;break;case S.touched:i=o;break;case S.unused:i=r}i&&(t.libDestroyTimer=setTimeout((()=>this.removeStore(t)),i))}getStoreState(t,e=!1){return t.toJSON?.()??u.getObservableProps(t,e)}toJSON(t,e=!1){const s={},o=Array.isArray(t)?t.reduce(((t,e)=>(this.stores.has(e)&&t.set(e,this.stores.get(e)),t)),new Map):this.stores;for(const[t,r]of o.entries())s[t]=this.getStoreState(r,e);return s}async savePersistedStore(t){if(this.options.shouldDisablePersist||!this.storage)return!1;try{return await this.storage.saveStoreData(t,this.getStoreState(t,!0)),!0}catch(t){this.logger.err("Failed to persist stores: ",t)}return!1}static getObservableProps(t,o=!1){const r=e(t);return Object.entries(r).reduce(((e,[r,i])=>({...e,...s(t,r)&&!a(t,r,o)||l(t,r)?{[r]:i}:{},...h(t,r)?{[r]:u.getObservableProps(t[r])}:{}})),{})}static persistStore(t,e,s={}){return u.persistedStores.add(e),t.libStoreId=e,"libStorageOptions"in t.prototype||(t.prototype.libStorageOptions=s),"wakeup"in t.prototype||(t.prototype.wakeup=c),"addOnChangeListener"in t.prototype||(t.prototype.addOnChangeListener=d),t}}export{u as default};
|
|
2
2
|
//# sourceMappingURL=manager.js.map
|
package/manager.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.js","sources":["../src/manager.ts"],"sourcesContent":["import EventManager from '@lomray/event-manager';\nimport { isObservableProp, toJS } from 'mobx';\nimport { ROOT_CONTEXT_ID } from './constants';\nimport deepMerge from './deep-merge';\nimport Events from './events';\nimport {\n isPropExcludedFromExport,\n isPropObservableExported,\n isPropSimpleExported,\n} from './make-exported';\nimport onChangeListener from './on-change-listener';\nimport CombinedStorage from './storages/combined-storage';\nimport StoreStatus from './store-status';\nimport type {\n IConstructableStore,\n IGroupedStores,\n IManagerOptions,\n IManagerParams,\n IPersistOptions,\n IStoreParams,\n IStorePersisted,\n TAnyStore,\n TInitStore,\n TStoreDefinition,\n TStores,\n} from './types';\nimport wakeup from './wakeup';\n\n/**\n * Mobx stores manager\n */\nclass Manager {\n /**\n * Manger instance\n */\n protected static instance: Manager;\n\n /**\n * Created stores\n */\n protected readonly stores = new Map<string, TInitStore>();\n\n /**\n * Relations between stores\n */\n protected readonly storesRelations = new Map<\n string, // contextId\n { ids: Set<string>; parentId: string | null; componentName?: string }\n >();\n\n /**\n * Save persisted stores identities\n */\n protected static readonly persistedStores = new Set<string>();\n\n /**\n * Initial stores state (local storage, custom etc.)\n */\n protected readonly initState: Record<string, any>;\n\n /**\n * Storage for persisted stores\n */\n public readonly storage?: CombinedStorage;\n\n /**\n * Additional store's constructor params\n */\n protected readonly storesParams: IManagerParams['storesParams'];\n\n /**\n * Manager options\n */\n public readonly options: IManagerOptions = {\n shouldDisablePersist: false,\n shouldRemoveInitState: true,\n };\n\n /**\n * Suspense stores relations\n * @see withStores\n */\n protected suspenseRelations: Map<string, Set<string>> = new Map();\n\n /**\n * @constructor\n */\n public constructor({ initState, storesParams, storage, options }: IManagerParams = {}) {\n this.initState = initState || {};\n this.storesParams = storesParams || {};\n this.storage =\n storage instanceof CombinedStorage\n ? storage\n : storage\n ? new CombinedStorage({ default: storage })\n : undefined;\n\n Object.assign(this.options, options || {});\n\n Manager.instance = this;\n\n // only client side\n if (typeof window !== 'undefined') {\n const state = window.mbxM;\n\n window.mbxM = { push: this.pushInitState };\n\n (Array.isArray(state) ? state : []).forEach(this.pushInitState);\n }\n }\n\n /**\n * Init store manager\n */\n public async init(): Promise<Manager> {\n if (this.storage) {\n await this.storage.get();\n }\n\n return this;\n }\n\n /**\n * Get manager instance\n */\n public static get(): Manager {\n if (!Manager.instance) {\n throw new Error('Store manager is not initialized.');\n }\n\n return Manager.instance;\n }\n\n /**\n * Get all stores\n */\n public getStores(): Manager['stores'] {\n return this.stores;\n }\n\n /**\n * Get stores relations\n */\n public getStoresRelations(): Manager['storesRelations'] {\n return this.storesRelations;\n }\n\n /**\n * Get suspense relations with stores\n */\n public getSuspenseRelations(): Manager['suspenseRelations'] {\n return this.suspenseRelations;\n }\n\n /**\n * Get persisted stores ids\n */\n public static getPersistedStoresIds(): Set<string> {\n return Manager.persistedStores;\n }\n\n /**\n * Push initial state dynamically\n * E.g. when stream html\n */\n public pushInitState = (storesState: Record<string, any> = {}): void => {\n for (const [storeId, state] of Object.entries(storesState)) {\n this.initState[storeId] = state;\n }\n };\n\n /**\n * Get store identity\n * @protected\n */\n protected getStoreId<T extends TAnyStore>(\n store: IConstructableStore<T> | TInitStore,\n params: IStoreParams = {},\n ): string {\n const { id, contextId, key } = params;\n\n if (id) {\n return id;\n }\n\n if (store.libStoreId) {\n return store.libStoreId;\n }\n\n let storeId = (store['id'] as string) || (store['name'] as string) || store.constructor.name;\n\n if (store.isGlobal) {\n return storeId;\n }\n\n storeId = `${storeId}--${contextId!}`;\n\n return key ? `${storeId}--${key}` : storeId;\n }\n\n /**\n * Get exist store\n */\n public getStore<T>(store: IConstructableStore<T>, params: IStoreParams = {}): T | undefined {\n const storeId = this.getStoreId(store, params);\n\n // full match\n if (this.stores.has(storeId)) {\n return this.stores.get(storeId) as T;\n }\n\n // in case with global store (create if not exist)\n if (store.isGlobal) {\n return this.createStore(store, {\n id: storeId,\n contextId: 'global',\n parentId: ROOT_CONTEXT_ID,\n suspenseId: '',\n componentName: 'root-app',\n componentProps: {},\n });\n }\n\n // try to look up store in current or parent context\n return this.lookupStore(storeId, params) as T;\n }\n\n /**\n * Lookup store\n */\n protected lookupStore(id: string, params: IStoreParams): TInitStore<TAnyStore> | undefined {\n const { contextId, parentId: defaultParentId } = params;\n const clearId = id.split('--')?.[0];\n const { ids, parentId } = this.storesRelations.get(contextId!) ?? {\n ids: new Set(),\n parentId: defaultParentId,\n };\n\n const matchedIds = [...ids].filter((storeId) => storeId.startsWith(`${clearId}--`));\n\n if (matchedIds.length === 1) {\n return this.stores.get(matchedIds[0]);\n } else if (matchedIds.length > 1) {\n console.error(\n 'Parent context has multiple stores with the same id, please pass key to getStore function.',\n );\n\n return undefined;\n }\n\n if (!parentId || parentId === ROOT_CONTEXT_ID) {\n return undefined;\n }\n\n return this.lookupStore(id, { contextId: this.getBiggerContext(parentId, defaultParentId) });\n }\n\n /**\n * Get bigger context from two\n */\n protected getBiggerContext(ctx1?: string, ctx2?: string): string | undefined {\n if (!ctx1) {\n return ctx2;\n } else if (!ctx2) {\n return ctx1;\n }\n\n const regexp = /[^a-zA-Z]/g;\n\n return ctx1.replace(regexp, '') > ctx2.replace(regexp, '') ? ctx1 : ctx2;\n }\n\n /**\n * Create new store instance\n */\n protected createStore<T>(\n store: IConstructableStore<T>,\n params: Omit<Required<IStoreParams>, 'key'>,\n ): T {\n const { id, contextId, parentId, suspenseId, componentName, componentProps } = params;\n\n // only for global store\n if (this.stores.has(id)) {\n return this.stores.get(id) as T;\n }\n\n const newStore = new store({\n ...this.storesParams,\n storeManager: this,\n getStore: <TS>(\n targetStore: IConstructableStore<TS>,\n targetParams = { contextId, parentId },\n ) => this.getStore(targetStore, targetParams),\n componentProps,\n initState: this.initState[id],\n });\n\n // assign params to new store\n newStore.libStoreId = id;\n newStore.isGlobal = store.isGlobal;\n newStore.libStoreContextId = store.isGlobal ? 'global' : contextId;\n newStore.libStoreParentId =\n store.isGlobal || !parentId || parentId === contextId ? ROOT_CONTEXT_ID : parentId;\n newStore.libStoreSuspenseId = suspenseId;\n newStore.libStoreComponentName = componentName;\n\n this.setStoreStatus(newStore, store.isGlobal ? StoreStatus.inUse : StoreStatus.init);\n this.prepareStore(newStore);\n EventManager.publish(Events.CREATE_STORE, { store });\n\n return newStore as T;\n }\n\n /**\n * Create stores for component\n *\n * NOTE: use only inside withStores wrapper\n */\n public createStores(\n map: [string, TStoreDefinition][],\n parentId: string,\n contextId: string,\n suspenseId: string,\n componentName: string,\n componentProps: Record<string, any> = {},\n ): IGroupedStores {\n const result = map.reduce(\n (res, [key, store]) => {\n const {\n id,\n store: s,\n isParent = false,\n } = 'store' in store ? store : { store, id: undefined, isParent: false };\n const storeId =\n id ||\n (isParent\n ? (this.getStore(s, { contextId, parentId })?.libStoreId as string)\n : this.getStoreId(s, { key, contextId }));\n\n if (!storeId) {\n return res;\n }\n\n const storeInstance = this.createStore(s, {\n id: storeId,\n contextId,\n parentId,\n suspenseId,\n componentName,\n componentProps,\n });\n\n if (isParent) {\n res.parentStores[key] = storeInstance;\n } else if (storeInstance.isGlobal) {\n res.globalStores[key] = storeInstance;\n } else {\n res.relativeStores[key] = storeInstance;\n }\n\n return res;\n },\n { relativeStores: {}, parentStores: {}, globalStores: {} },\n );\n\n // need create context relation in case when component doesn't include relative stores\n this.createRelationContext(contextId, parentId, componentName);\n\n return result;\n }\n\n /**\n * Create empty relation context\n */\n protected createRelationContext(\n contextId: string,\n parentId?: string,\n componentName?: string,\n ): void {\n if (this.storesRelations.has(contextId)) {\n return;\n }\n\n this.storesRelations.set(contextId, {\n ids: new Set(),\n parentId: !parentId || parentId === contextId ? ROOT_CONTEXT_ID : parentId,\n componentName,\n });\n }\n\n /**\n * Delete relation context id\n */\n protected removeRelationContext(contextId: string): void {\n const storesRelations = this.storesRelations.get(contextId);\n\n if (!storesRelations || contextId === ROOT_CONTEXT_ID || storesRelations.ids.size > 0) {\n return;\n }\n\n this.storesRelations.delete(contextId);\n }\n\n /**\n * Prepare store before usage\n */\n protected prepareStore(store: TStores[string]): void {\n const storeId = store.libStoreId!;\n const contextId = store.libStoreContextId!;\n const suspenseId = store.libStoreSuspenseId!;\n\n if (this.stores.has(storeId)) {\n return;\n }\n\n // restore initial state from server\n const initState = this.initState[storeId];\n\n if (initState) {\n deepMerge(store, initState);\n }\n\n // restore persisted state\n if ('wakeup' in store && Manager.persistedStores.has(storeId)) {\n store.wakeup?.({\n initState,\n persistedState: this.storage?.getStoreData(store),\n manager: this,\n });\n }\n\n // track changes in persisted store\n if (Manager.persistedStores.has(storeId) && 'addOnChangeListener' in store) {\n const onDestroyDefault = store.onDestroy?.bind(store);\n const removeListener = store.addOnChangeListener!(store, this);\n\n store.onDestroy = () => {\n removeListener?.();\n onDestroyDefault?.();\n };\n }\n\n store.init?.();\n this.createRelationContext(contextId, store.libStoreParentId, store.libStoreComponentName);\n\n if (!this.suspenseRelations.has(suspenseId)) {\n this.suspenseRelations.set(suspenseId, new Set());\n }\n\n const { ids } = this.storesRelations.get(contextId)!;\n\n // add store to manager\n this.stores.set(storeId, store);\n ids.add(storeId);\n // add store relation with suspense\n this.suspenseRelations.get(suspenseId)!.add(storeId);\n }\n\n /**\n * Remove store\n */\n protected removeStore(store: TStores[string]): void {\n const storeId = store.libStoreId!;\n const suspenseId = store.libStoreSuspenseId!;\n const { ids } = this.storesRelations.get(store.libStoreContextId!) ?? { ids: new Set() };\n\n if (!this.stores.has(storeId)) {\n return;\n }\n\n this.stores.delete(storeId);\n ids.delete(storeId);\n\n if (suspenseId && this.suspenseRelations.get(suspenseId)?.has(storeId)) {\n this.suspenseRelations.get(suspenseId)!.delete(storeId);\n }\n\n this.removeRelationContext(store.libStoreContextId!);\n\n if ('onDestroy' in store) {\n store.onDestroy?.();\n }\n\n EventManager.publish(Events.DELETE_STORE, { store });\n }\n\n /**\n * Mount stores to component\n *\n * NOTE: use only inside withStores wrapper\n */\n public mountStores(\n contextId: string,\n { globalStores = {}, relativeStores = {} }: Partial<IGroupedStores>,\n ): () => void {\n const { shouldRemoveInitState } = this.options;\n const touchableStores = { ...globalStores, ...relativeStores };\n\n Object.values(touchableStores).forEach((store) => {\n const storeId = store.libStoreId!;\n\n // cleanup init state\n if (shouldRemoveInitState && this.initState[storeId]) {\n delete this.initState[storeId];\n }\n\n this.setStoreStatus(store, StoreStatus.inUse);\n EventManager.publish(Events.MOUNT_STORE, { store });\n });\n\n return () => {\n Object.values(touchableStores).forEach((store) => {\n if (store.isGlobal) {\n return;\n }\n\n this.setStoreStatus(store, StoreStatus.unused);\n EventManager.publish(Events.UNMOUNT_STORE, { store });\n });\n\n this.removeRelationContext(contextId);\n };\n }\n\n /**\n * Change the stores status to touched\n */\n public touchedStores(stores: TStores): void {\n Object.values(stores).forEach((store) => {\n if (store.libStoreStatus !== StoreStatus.init || store.isGlobal) {\n return;\n }\n\n this.setStoreStatus(store, StoreStatus.touched);\n });\n }\n\n /**\n * Change store status\n */\n protected setStoreStatus(store: TStores[string], status: StoreStatus): void {\n const { destroyTimers: { init = 500, touched = 10000, unused = 1000 } = {} } = this.options;\n\n store.libStoreStatus = status;\n\n clearTimeout(store.libDestroyTimer);\n\n let destroyTime = 0;\n\n switch (status) {\n case StoreStatus.init:\n destroyTime = init;\n break;\n\n case StoreStatus.touched:\n destroyTime = touched;\n break;\n\n case StoreStatus.unused:\n destroyTime = unused;\n break;\n }\n\n if (!destroyTime) {\n return;\n }\n\n store.libDestroyTimer = setTimeout(() => this.removeStore(store), destroyTime);\n }\n\n /**\n * Get store state\n */\n public getStoreState(store: TAnyStore, withNotExported = false): Record<string, any> {\n return store.toJSON?.() ?? Manager.getObservableProps(store, withNotExported);\n }\n\n /**\n * Get store's state\n */\n public toJSON(ids?: string[], isIncludeExported = false): Record<string, any> {\n const result = {};\n const stores = Array.isArray(ids)\n ? ids.reduce((res, id) => {\n if (this.stores.has(id)) {\n res.set(id, this.stores.get(id)!);\n }\n\n return res;\n }, new Map<string, TInitStore>())\n : this.stores;\n\n for (const [storeId, store] of stores.entries()) {\n result[storeId] = this.getStoreState(store, isIncludeExported);\n }\n\n return result;\n }\n\n /**\n * Save persisted store state to provided storage\n */\n public async savePersistedStore(store: IStorePersisted): Promise<boolean> {\n if (this.options.shouldDisablePersist || !this.storage) {\n return false;\n }\n\n try {\n await this.storage.saveStoreData(store, this.getStoreState(store, true));\n\n return true;\n } catch (e) {\n console.error('Failed to persist stores: ', e);\n }\n\n return false;\n }\n\n /**\n * Get observable store props (fields)\n */\n public static getObservableProps(store: TAnyStore, withNotExported = false): Record<string, any> {\n const props = toJS(store);\n\n return Object.entries(props).reduce(\n (res, [prop, value]) => ({\n ...res,\n ...((isObservableProp(store, prop) &&\n !isPropExcludedFromExport(store, prop, withNotExported)) ||\n isPropSimpleExported(store, prop)\n ? { [prop]: value }\n : {}),\n ...(isPropObservableExported(store, prop)\n ? { [prop]: Manager.getObservableProps(store[prop] as TAnyStore) }\n : {}),\n }),\n {},\n );\n }\n\n /**\n * Persist store\n */\n public static persistStore<TSt>(\n store: IConstructableStore<TSt>,\n id: string,\n options: IPersistOptions = {},\n ): IConstructableStore<TSt> {\n Manager.persistedStores.add(id);\n\n store.libStoreId = id;\n\n // add storage options\n if (!('libStorageOptions' in store.prototype)) {\n store.prototype.libStorageOptions = options;\n }\n\n // add default wakeup handler\n if (!('wakeup' in store.prototype)) {\n store.prototype.wakeup = wakeup;\n }\n\n // add default changes listener\n if (!('addOnChangeListener' in store.prototype)) {\n store.prototype.addOnChangeListener = onChangeListener;\n }\n\n return store;\n }\n}\n\nexport default Manager;\n"],"names":["Manager","static","stores","Map","storesRelations","Set","initState","storage","storesParams","options","shouldDisablePersist","shouldRemoveInitState","suspenseRelations","constructor","this","CombinedStorage","default","undefined","Object","assign","instance","window","state","mbxM","push","pushInitState","Array","isArray","forEach","async","get","Error","getStores","getStoresRelations","getSuspenseRelations","persistedStores","storesState","storeId","entries","getStoreId","store","params","id","contextId","key","libStoreId","name","isGlobal","getStore","has","createStore","parentId","ROOT_CONTEXT_ID","suspenseId","componentName","componentProps","lookupStore","defaultParentId","clearId","split","ids","matchedIds","filter","startsWith","length","console","error","getBiggerContext","ctx1","ctx2","regexp","replace","newStore","storeManager","targetStore","targetParams","libStoreContextId","libStoreParentId","libStoreSuspenseId","libStoreComponentName","setStoreStatus","StoreStatus","inUse","init","prepareStore","EventManager","publish","Events","CREATE_STORE","createStores","map","result","reduce","res","s","isParent","storeInstance","parentStores","globalStores","relativeStores","createRelationContext","set","removeRelationContext","size","delete","deepMerge","wakeup","persistedState","getStoreData","manager","onDestroyDefault","onDestroy","bind","removeListener","addOnChangeListener","add","removeStore","DELETE_STORE","mountStores","touchableStores","values","MOUNT_STORE","unused","UNMOUNT_STORE","touchedStores","libStoreStatus","touched","status","destroyTimers","clearTimeout","libDestroyTimer","destroyTime","setTimeout","getStoreState","withNotExported","toJSON","getObservableProps","isIncludeExported","saveStoreData","e","props","toJS","prop","value","isObservableProp","isPropExcludedFromExport","isPropSimpleExported","isPropObservableExported","prototype","libStorageOptions","onChangeListener"],"mappings":"ycA+BA,MAAMA,EAIMC,gBAKSC,OAAS,IAAIC,IAKbC,gBAAkB,IAAID,IAQ/BF,uBAAkC,IAAII,IAK7BC,UAKHC,QAKGC,aAKHC,QAA2B,CACzCC,sBAAsB,EACtBC,uBAAuB,GAOfC,kBAA8C,IAAIT,IAK5DU,aAAmBP,UAAEA,EAASE,aAAEA,EAAYD,QAAEA,EAAOE,QAAEA,GAA4B,IAejF,GAdAK,KAAKR,UAAYA,GAAa,GAC9BQ,KAAKN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,GACV,CAAE,KACFI,EAAyB3G,EAAOsG,GAChC,CAAEA,CAACA,GAAO9I,EAAQwI,mBAAmBhG,EAAMsG,KAC3C,CAAE,KAER,CAAE,EAEL,CAKM7I,oBACLuC,EACAE,EACAjC,EAA2B,CAAA,GAqB3B,OAnBAT,EAAQmC,gBAAgBgF,IAAIzE,GAE5BF,EAAMK,WAAaH,EAGb,sBAAuBF,EAAM4G,YACjC5G,EAAM4G,UAAUC,kBAAoB5I,GAIhC,WAAY+B,EAAM4G,YACtB5G,EAAM4G,UAAU1C,OAASA,GAIrB,wBAAyBlE,EAAM4G,YACnC5G,EAAM4G,UAAUlC,oBAAsBoC,GAGjC9G,CACR"}
|
|
1
|
+
{"version":3,"file":"manager.js","sources":["../src/manager.ts"],"sourcesContent":["import EventManager from '@lomray/event-manager';\nimport { isObservableProp, toJS } from 'mobx';\nimport { ROOT_CONTEXT_ID } from './constants';\nimport deepMerge from './deep-merge';\nimport Events from './events';\nimport Logger from './logger';\nimport {\n isPropExcludedFromExport,\n isPropObservableExported,\n isPropSimpleExported,\n} from './make-exported';\nimport onChangeListener from './on-change-listener';\nimport CombinedStorage from './storages/combined-storage';\nimport StoreStatus from './store-status';\nimport type {\n IConstructableStore,\n IGroupedStores,\n IManagerOptions,\n IManagerParams,\n IPersistOptions,\n IStoreParams,\n IStorePersisted,\n TAnyStore,\n TInitStore,\n TStoreDefinition,\n TStores,\n} from './types';\nimport wakeup from './wakeup';\n\n/**\n * Mobx stores manager\n */\nclass Manager {\n /**\n * Manger instance\n */\n protected static instance: Manager;\n\n /**\n * Created stores\n */\n protected readonly stores = new Map<string, TInitStore>();\n\n /**\n * Relations between stores\n */\n protected readonly storesRelations = new Map<\n string, // contextId\n { ids: Set<string>; parentId: string | null; componentName?: string }\n >();\n\n /**\n * Save persisted stores identities\n */\n protected static readonly persistedStores = new Set<string>();\n\n /**\n * Initial stores state (local storage, custom etc.)\n */\n protected readonly initState: Record<string, any>;\n\n /**\n * Storage for persisted stores\n */\n public readonly storage?: CombinedStorage;\n\n /**\n * Additional store's constructor params\n */\n protected readonly storesParams: IManagerParams['storesParams'];\n\n /**\n * Manager options\n */\n public readonly options: IManagerOptions = {\n shouldDisablePersist: false,\n shouldRemoveInitState: true,\n };\n\n /**\n * Suspense stores relations\n * @see withStores\n */\n protected suspenseRelations: Map<string, Set<string>> = new Map();\n\n /**\n * Mobx manager logger\n */\n protected readonly logger: Logger;\n\n /**\n * @constructor\n */\n public constructor({ initState, storesParams, storage, options, logger }: IManagerParams = {}) {\n this.initState = initState || {};\n this.storesParams = storesParams || {};\n this.logger =\n logger && 'log' in logger\n ? logger\n : new Logger({ level: 3, ...(logger ?? {}), manager: this });\n this.storage =\n storage instanceof CombinedStorage\n ? storage\n : storage\n ? new CombinedStorage({ default: storage })\n : undefined;\n\n Object.assign(this.options, options || {});\n\n Manager.instance = this;\n\n // only client side\n if (typeof window !== 'undefined') {\n const state = window.mbxM;\n\n window.mbxM = { push: this.pushInitState };\n\n (Array.isArray(state) ? state : []).forEach(this.pushInitState);\n }\n }\n\n /**\n * Init store manager\n */\n public async init(): Promise<Manager> {\n try {\n if (this.storage) {\n await this.storage.get();\n }\n } catch (e) {\n this.logger.err('Failed initialized store manager: ', e);\n }\n\n return this;\n }\n\n /**\n * Get manager instance\n */\n public static get(): Manager {\n if (!Manager.instance) {\n throw new Error('Store manager is not initialized.');\n }\n\n return Manager.instance;\n }\n\n /**\n * Get all stores\n */\n public getStores(): Manager['stores'] {\n return this.stores;\n }\n\n /**\n * Get stores relations\n */\n public getStoresRelations(): Manager['storesRelations'] {\n return this.storesRelations;\n }\n\n /**\n * Get suspense relations with stores\n */\n public getSuspenseRelations(): Manager['suspenseRelations'] {\n return this.suspenseRelations;\n }\n\n /**\n * Get persisted stores ids\n */\n public static getPersistedStoresIds(): Set<string> {\n return Manager.persistedStores;\n }\n\n /**\n * Push initial state dynamically\n * E.g. when stream html\n */\n public pushInitState = (storesState: Record<string, any> = {}): void => {\n for (const [storeId, state] of Object.entries(storesState)) {\n this.initState[storeId] = state;\n }\n };\n\n /**\n * Get store identity\n */\n protected getStoreId<T extends TAnyStore>(\n store: IConstructableStore<T> | TInitStore,\n params: IStoreParams = {},\n ): string {\n const { id, contextId, key } = params;\n\n if (id) {\n return id;\n }\n\n if (store.libStoreId) {\n return store.libStoreId;\n }\n\n let storeId = (store['id'] as string) || (store['name'] as string) || store.constructor.name;\n\n if (store.isGlobal) {\n return storeId;\n }\n\n storeId = `${storeId}--${contextId!}`;\n\n return key ? `${storeId}--${key}` : storeId;\n }\n\n /**\n * Get exist store\n */\n public getStore<T>(store: IConstructableStore<T>, params: IStoreParams = {}): T | undefined {\n const storeId = this.getStoreId(store, params);\n\n // full match\n if (this.stores.has(storeId)) {\n return this.stores.get(storeId) as T;\n }\n\n // in case with global store (create if not exist)\n if (store.isGlobal) {\n return this.createStore(store, {\n id: storeId,\n contextId: 'global',\n parentId: ROOT_CONTEXT_ID,\n suspenseId: '',\n componentName: 'root-app',\n componentProps: {},\n });\n }\n\n // try to look up store in current or parent context\n return this.lookupStore(storeId, params) as T;\n }\n\n /**\n * Lookup store\n */\n protected lookupStore(id: string, params: IStoreParams): TInitStore<TAnyStore> | undefined {\n const { contextId, parentId: defaultParentId } = params;\n const clearId = id.split('--')?.[0];\n const { ids, parentId } = this.storesRelations.get(contextId!) ?? {\n ids: new Set(),\n parentId: defaultParentId,\n };\n\n const matchedIds = [...ids].filter((storeId) => storeId.startsWith(`${clearId}--`));\n\n if (matchedIds.length === 1) {\n return this.stores.get(matchedIds[0]);\n } else if (matchedIds.length > 1) {\n this.logger.err(\n 'Parent context has multiple stores with the same id, please pass key to getStore function.',\n );\n\n return undefined;\n }\n\n if (!parentId || parentId === ROOT_CONTEXT_ID) {\n return undefined;\n }\n\n return this.lookupStore(id, { contextId: this.getBiggerContext(parentId, defaultParentId) });\n }\n\n /**\n * Get bigger context from two\n */\n protected getBiggerContext(ctx1?: string, ctx2?: string): string | undefined {\n if (!ctx1) {\n return ctx2;\n } else if (!ctx2) {\n return ctx1;\n }\n\n const regexp = /[^a-zA-Z]/g;\n\n return ctx1.replace(regexp, '') > ctx2.replace(regexp, '') ? ctx1 : ctx2;\n }\n\n /**\n * Create new store instance\n */\n protected createStore<T>(\n store: IConstructableStore<T>,\n params: Omit<Required<IStoreParams>, 'key'>,\n ): T {\n const { id, contextId, parentId, suspenseId, componentName, componentProps } = params;\n\n // only for global store\n if (this.stores.has(id)) {\n return this.stores.get(id) as T;\n }\n\n const newStore = new store({\n ...this.storesParams,\n storeManager: this,\n getStore: <TS>(\n targetStore: IConstructableStore<TS>,\n targetParams = { contextId, parentId },\n ) => this.getStore(targetStore, targetParams),\n componentProps,\n initState: this.initState[id],\n });\n\n // assign params to new store\n newStore.libStoreId = id;\n newStore.isGlobal = store.isGlobal;\n newStore.libStoreContextId = store.isGlobal ? 'global' : contextId;\n newStore.libStoreParentId =\n store.isGlobal || !parentId || parentId === contextId ? ROOT_CONTEXT_ID : parentId;\n newStore.libStoreSuspenseId = suspenseId;\n newStore.libStoreComponentName = componentName;\n\n this.setStoreStatus(newStore, store.isGlobal ? StoreStatus.inUse : StoreStatus.init);\n this.prepareStore(newStore);\n EventManager.publish(Events.CREATE_STORE, { store });\n\n return newStore as T;\n }\n\n /**\n * Create stores for component\n *\n * NOTE: use only inside withStores wrapper\n */\n public createStores(\n map: [string, TStoreDefinition][],\n parentId: string,\n contextId: string,\n suspenseId: string,\n componentName: string,\n componentProps: Record<string, any> = {},\n ): IGroupedStores {\n const result = map.reduce(\n (res, [key, store]) => {\n const {\n id,\n store: s,\n isParent = false,\n } = 'store' in store ? store : { store, id: undefined, isParent: false };\n const storeId =\n id ||\n (isParent\n ? (this.getStore(s, { contextId, parentId })?.libStoreId as string)\n : this.getStoreId(s, { key, contextId }));\n\n if (!storeId) {\n const msg = `Cannot find or create store '${key}': '${this.getStoreId(s)}'`;\n\n this.logger.warn(msg);\n this.logger.debug(\n msg,\n { contextId, parentId, suspenseId, componentName, isParent },\n true,\n );\n\n return res;\n }\n\n const storeInstance = this.createStore(s, {\n id: storeId,\n contextId,\n parentId,\n suspenseId,\n componentName,\n componentProps,\n });\n\n if (isParent) {\n res.parentStores[key] = storeInstance;\n } else if (storeInstance.isGlobal) {\n res.globalStores[key] = storeInstance;\n } else {\n res.relativeStores[key] = storeInstance;\n }\n\n return res;\n },\n { relativeStores: {}, parentStores: {}, globalStores: {} },\n );\n\n // need create context relation in case when component doesn't include relative stores\n this.createRelationContext(contextId, parentId, componentName);\n\n return result;\n }\n\n /**\n * Create empty relation context\n */\n protected createRelationContext(\n contextId: string,\n parentId?: string,\n componentName?: string,\n ): void {\n if (this.storesRelations.has(contextId)) {\n return;\n }\n\n this.storesRelations.set(contextId, {\n ids: new Set(),\n parentId: !parentId || parentId === contextId ? ROOT_CONTEXT_ID : parentId,\n componentName,\n });\n }\n\n /**\n * Delete relation context id\n */\n protected removeRelationContext(contextId: string): void {\n const storesRelations = this.storesRelations.get(contextId);\n\n if (!storesRelations || contextId === ROOT_CONTEXT_ID || storesRelations.ids.size > 0) {\n return;\n }\n\n this.storesRelations.delete(contextId);\n }\n\n /**\n * Prepare store before usage\n */\n protected prepareStore(store: TStores[string]): void {\n const storeId = store.libStoreId!;\n const contextId = store.libStoreContextId!;\n const suspenseId = store.libStoreSuspenseId!;\n\n if (this.stores.has(storeId)) {\n return;\n }\n\n // restore initial state from server\n const initState = this.initState[storeId];\n\n if (initState) {\n deepMerge(store, initState);\n }\n\n // restore persisted state\n if ('wakeup' in store && Manager.persistedStores.has(storeId)) {\n store.wakeup?.({\n initState,\n persistedState: this.storage?.getStoreData(store),\n manager: this,\n });\n }\n\n // track changes in persisted store\n if (Manager.persistedStores.has(storeId) && 'addOnChangeListener' in store) {\n const onDestroyDefault = store.onDestroy?.bind(store);\n const removeListener = store.addOnChangeListener!(store, this);\n\n store.onDestroy = () => {\n removeListener?.();\n onDestroyDefault?.();\n };\n }\n\n store.init?.();\n this.createRelationContext(contextId, store.libStoreParentId, store.libStoreComponentName);\n\n if (!this.suspenseRelations.has(suspenseId)) {\n this.suspenseRelations.set(suspenseId, new Set());\n }\n\n const { ids } = this.storesRelations.get(contextId)!;\n\n // add store to manager\n this.stores.set(storeId, store);\n ids.add(storeId);\n // add store relation with suspense\n this.suspenseRelations.get(suspenseId)!.add(storeId);\n }\n\n /**\n * Remove store\n */\n protected removeStore(store: TStores[string]): void {\n const storeId = store.libStoreId!;\n const suspenseId = store.libStoreSuspenseId!;\n const { ids } = this.storesRelations.get(store.libStoreContextId!) ?? { ids: new Set() };\n\n if (!this.stores.has(storeId)) {\n return;\n }\n\n this.stores.delete(storeId);\n ids.delete(storeId);\n\n if (suspenseId && this.suspenseRelations.get(suspenseId)?.has(storeId)) {\n this.suspenseRelations.get(suspenseId)!.delete(storeId);\n }\n\n this.removeRelationContext(store.libStoreContextId!);\n\n if ('onDestroy' in store) {\n store.onDestroy?.();\n }\n\n EventManager.publish(Events.DELETE_STORE, { store });\n }\n\n /**\n * Mount stores to component\n *\n * NOTE: use only inside withStores wrapper\n */\n public mountStores(\n contextId: string,\n { globalStores = {}, relativeStores = {} }: Partial<IGroupedStores>,\n ): () => void {\n const { shouldRemoveInitState } = this.options;\n const touchableStores = { ...globalStores, ...relativeStores };\n\n Object.values(touchableStores).forEach((store) => {\n const storeId = store.libStoreId!;\n\n // cleanup init state\n if (shouldRemoveInitState && this.initState[storeId]) {\n delete this.initState[storeId];\n }\n\n this.setStoreStatus(store, StoreStatus.inUse);\n EventManager.publish(Events.MOUNT_STORE, { store });\n });\n\n return () => {\n Object.values(touchableStores).forEach((store) => {\n if (store.isGlobal) {\n return;\n }\n\n this.setStoreStatus(store, StoreStatus.unused);\n EventManager.publish(Events.UNMOUNT_STORE, { store });\n });\n\n this.removeRelationContext(contextId);\n };\n }\n\n /**\n * Change the stores status to touched\n */\n public touchedStores(stores: TStores): void {\n Object.values(stores).forEach((store) => {\n if (store.libStoreStatus !== StoreStatus.init || store.isGlobal) {\n return;\n }\n\n this.setStoreStatus(store, StoreStatus.touched);\n });\n }\n\n /**\n * Change store status\n */\n protected setStoreStatus(store: TStores[string], status: StoreStatus): void {\n const { destroyTimers: { init = 500, touched = 10000, unused = 1000 } = {} } = this.options;\n\n store.libStoreStatus = status;\n\n clearTimeout(store.libDestroyTimer);\n\n let destroyTime = 0;\n\n switch (status) {\n case StoreStatus.init:\n destroyTime = init;\n break;\n\n case StoreStatus.touched:\n destroyTime = touched;\n break;\n\n case StoreStatus.unused:\n destroyTime = unused;\n break;\n }\n\n if (!destroyTime) {\n return;\n }\n\n store.libDestroyTimer = setTimeout(() => this.removeStore(store), destroyTime);\n }\n\n /**\n * Get store state\n */\n public getStoreState(store: TAnyStore, withNotExported = false): Record<string, any> {\n return store.toJSON?.() ?? Manager.getObservableProps(store, withNotExported);\n }\n\n /**\n * Get store's state\n */\n public toJSON(ids?: string[], isIncludeExported = false): Record<string, any> {\n const result = {};\n const stores = Array.isArray(ids)\n ? ids.reduce((res, id) => {\n if (this.stores.has(id)) {\n res.set(id, this.stores.get(id)!);\n }\n\n return res;\n }, new Map<string, TInitStore>())\n : this.stores;\n\n for (const [storeId, store] of stores.entries()) {\n result[storeId] = this.getStoreState(store, isIncludeExported);\n }\n\n return result;\n }\n\n /**\n * Save persisted store state to provided storage\n */\n public async savePersistedStore(store: IStorePersisted): Promise<boolean> {\n if (this.options.shouldDisablePersist || !this.storage) {\n return false;\n }\n\n try {\n await this.storage.saveStoreData(store, this.getStoreState(store, true));\n\n return true;\n } catch (e) {\n this.logger.err('Failed to persist stores: ', e);\n }\n\n return false;\n }\n\n /**\n * Get observable store props (fields)\n */\n public static getObservableProps(store: TAnyStore, withNotExported = false): Record<string, any> {\n const props = toJS(store);\n\n return Object.entries(props).reduce(\n (res, [prop, value]) => ({\n ...res,\n ...((isObservableProp(store, prop) &&\n !isPropExcludedFromExport(store, prop, withNotExported)) ||\n isPropSimpleExported(store, prop)\n ? { [prop]: value }\n : {}),\n ...(isPropObservableExported(store, prop)\n ? { [prop]: Manager.getObservableProps(store[prop] as TAnyStore) }\n : {}),\n }),\n {},\n );\n }\n\n /**\n * Persist store\n */\n public static persistStore<TSt>(\n store: IConstructableStore<TSt>,\n id: string,\n options: IPersistOptions = {},\n ): IConstructableStore<TSt> {\n Manager.persistedStores.add(id);\n\n store.libStoreId = id;\n\n // add storage options\n if (!('libStorageOptions' in store.prototype)) {\n store.prototype.libStorageOptions = options;\n }\n\n // add default wakeup handler\n if (!('wakeup' in store.prototype)) {\n store.prototype.wakeup = wakeup;\n }\n\n // add default changes listener\n if (!('addOnChangeListener' in store.prototype)) {\n store.prototype.addOnChangeListener = onChangeListener;\n }\n\n return store;\n }\n}\n\nexport default Manager;\n"],"names":["Manager","static","stores","Map","storesRelations","Set","initState","storage","storesParams","options","shouldDisablePersist","shouldRemoveInitState","suspenseRelations","logger","constructor","this","Logger","level","manager","CombinedStorage","default","undefined","Object","assign","instance","window","state","mbxM","push","pushInitState","Array","isArray","forEach","async","get","e","err","Error","getStores","getStoresRelations","getSuspenseRelations","persistedStores","storesState","storeId","entries","getStoreId","store","params","id","contextId","key","libStoreId","name","isGlobal","getStore","has","createStore","parentId","ROOT_CONTEXT_ID","suspenseId","componentName","componentProps","lookupStore","defaultParentId","clearId","split","ids","matchedIds","filter","startsWith","length","getBiggerContext","ctx1","ctx2","regexp","replace","newStore","storeManager","targetStore","targetParams","libStoreContextId","libStoreParentId","libStoreSuspenseId","libStoreComponentName","setStoreStatus","StoreStatus","inUse","init","prepareStore","EventManager","publish","Events","CREATE_STORE","createStores","map","result","reduce","res","s","isParent","msg","warn","debug","storeInstance","parentStores","globalStores","relativeStores","createRelationContext","set","removeRelationContext","size","delete","deepMerge","wakeup","persistedState","getStoreData","onDestroyDefault","onDestroy","bind","removeListener","addOnChangeListener","add","removeStore","DELETE_STORE","mountStores","touchableStores","values","MOUNT_STORE","unused","UNMOUNT_STORE","touchedStores","libStoreStatus","touched","status","destroyTimers","clearTimeout","libDestroyTimer","destroyTime","setTimeout","getStoreState","withNotExported","toJSON","getObservableProps","isIncludeExported","saveStoreData","props","toJS","prop","value","isObservableProp","isPropExcludedFromExport","isPropSimpleExported","isPropObservableExported","prototype","libStorageOptions","onChangeListener"],"mappings":"oeAgCA,MAAMA,EAIMC,gBAKSC,OAAS,IAAIC,IAKbC,gBAAkB,IAAID,IAQ/BF,uBAAkC,IAAII,IAK7BC,UAKHC,QAKGC,aAKHC,QAA2B,CACzCC,sBAAsB,EACtBC,uBAAuB,GAOfC,kBAA8C,IAAIT,IAKzCU,OAKnBC,aAAmBR,UAAEA,EAASE,aAAEA,EAAYD,QAAEA,EAAOE,QAAEA,EAAOI,OAAEA,GAA2B,IAmBzF,GAlBAE,KAAKT,UAAYA,GAAa,GAC9BS,KAAKP,aAAeA,GAAgB,GACpCO,KAAKF,OACHA,GAAU,QAASA,EACfA,EACA,IAAIG,EAAO,CAAEC,MAAO,KAAOJ,GAAU,GAAKK,QAASH,OACzDA,KAAKR,QACHA,aAAmBY,EACfZ,EACAA,EACE,IAAIY,EAAgB,CAAEC,QAASb,SAC/Bc,EAERC,OAAOC,OAAOR,KAAKN,QAASA,GAAW,CAAE,GAEzCT,EAAQwB,SAAWT,KAGG,oBAAXU,OAAwB,CACjC,MAAMC,EAAQD,OAAOE,KAErBF,OAAOE,KAAO,CAAEC,KAAMb,KAAKc,gBAE1BC,MAAMC,QAAQL,GAASA,EAAQ,IAAIM,QAAQjB,KAAKc,cAClD,CACF,CAKMI,aACL,IACMlB,KAAKR,eACDQ,KAAKR,QAAQ2B,KAEtB,CAAC,MAAOC,GACPpB,KAAKF,OAAOuB,IAAI,qCAAsCD,EACvD,CAED,OAAOpB,IACR,CAKMd,aACL,IAAKD,EAAQwB,SACX,MAAM,IAAIa,MAAM,qCAGlB,OAAOrC,EAAQwB,QAChB,CAKMc,YACL,OAAOvB,KAAKb,MACb,CAKMqC,qBACL,OAAOxB,KAAKX,eACb,CAKMoC,uBACL,OAAOzB,KAAKH,iBACb,CAKMX,+BACL,OAAOD,E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/package.json
CHANGED
package/types.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
2
|
import Events from "./events.js";
|
|
3
|
+
import Logger from "./logger.js";
|
|
4
|
+
import { ILoggerOpts } from "./logger.js";
|
|
3
5
|
import Manager from "./manager.js";
|
|
4
6
|
import CombinedStorage from "./storages/combined-storage.js";
|
|
5
7
|
import StoreStatus from "./store-status.js";
|
|
@@ -55,6 +57,7 @@ interface IManagerParams {
|
|
|
55
57
|
storage?: IStorage | CombinedStorage;
|
|
56
58
|
options?: IManagerOptions;
|
|
57
59
|
initState?: Record<string, any>;
|
|
60
|
+
logger?: Logger | Omit<ILoggerOpts, 'manager'>;
|
|
58
61
|
}
|
|
59
62
|
type TWakeup = (state: {
|
|
60
63
|
manager: Manager;
|