synapse-storage 3.0.8 → 3.0.9

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/dist/reactive.cjs CHANGED
@@ -1,642 +1 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/reactive/index.ts
21
- var reactive_exports = {};
22
- __export(reactive_exports, {
23
- Dispatcher: () => Dispatcher,
24
- EffectsModule: () => EffectsModule,
25
- combineEffects: () => combineEffects,
26
- createDispatcher: () => createDispatcher,
27
- createEffect: () => createEffect,
28
- createEffectBase: () => createEffectBase,
29
- loggerDispatcherMiddleware: () => loggerDispatcherMiddleware,
30
- ofType: () => ofType,
31
- ofTypes: () => ofTypes,
32
- ofTypesWaitAll: () => ofTypesWaitAll,
33
- selectorMap: () => selectorMap,
34
- selectorObject: () => selectorObject,
35
- validateMap: () => validateMap
36
- });
37
- module.exports = __toCommonJS(reactive_exports);
38
-
39
- // src/reactive/dispatcher/dispatcher.module.ts
40
- var import_rxjs = require("rxjs");
41
- var Dispatcher = class {
42
- /**
43
- * Создает новый экземпляр Dispatcher
44
- */
45
- constructor(options) {
46
- this.options = options;
47
- this.storage = options.storage;
48
- this.middlewareAPI = {
49
- getState: () => this.storage.getState(),
50
- dispatch: async (action) => {
51
- this.actions$.next(action);
52
- return action.payload;
53
- },
54
- storage: this.storage,
55
- actions$: this.actions,
56
- actions: this.dispatch,
57
- watchers: this.watchers,
58
- findActionByType: (type) => this.findActionByType(type),
59
- findWatcherByType: (type) => this.findWatcherByType(type)
60
- };
61
- if (options.middlewares && options.middlewares.length > 0) {
62
- this.use(...options.middlewares);
63
- }
64
- }
65
- // Поток действий
66
- actions$ = new import_rxjs.Subject();
67
- // Публичный Observable для действий
68
- actions = this.actions$.asObservable();
69
- // Методы диспетчеризации действий с типизацией
70
- dispatch = {};
71
- // Watcher'ы для реактивной подписки на изменения
72
- watchers = {};
73
- // Ссылка на хранилище
74
- storage;
75
- // Только один массив для хранения инициализированных middleware
76
- middlewareFunctions = [];
77
- // API для инициализации middleware
78
- middlewareAPI;
79
- /**
80
- * Добавляет middleware в цепочку обработки
81
- */
82
- use(...middlewares) {
83
- for (let i = 0; i < middlewares.length; i++) {
84
- try {
85
- const initializedMiddleware = middlewares[i](this.middlewareAPI);
86
- this.middlewareFunctions.push(initializedMiddleware);
87
- } catch (error) {
88
- console.error(`Error initializing middleware [${i}]:`, error);
89
- }
90
- }
91
- return this;
92
- }
93
- /**
94
- * Получает все действия с улучшенной типизацией
95
- */
96
- getActions() {
97
- return this.dispatch;
98
- }
99
- /**
100
- * Получает типизированные действия диспетчера
101
- */
102
- getTypedDispatch() {
103
- return this.dispatch;
104
- }
105
- /**
106
- * Получает типизированные watcher'ы
107
- */
108
- getTypedWatchers() {
109
- return this.watchers;
110
- }
111
- /**
112
- * Находит действие по типу
113
- */
114
- findActionByType(actionType) {
115
- return Object.values(this.dispatch).find((action) => {
116
- return action.actionType.split(`[${this.storage.name}]`)[1] === actionType;
117
- });
118
- }
119
- /**
120
- * Находит наблюдатель по типу
121
- */
122
- findWatcherByType(actionType) {
123
- return Object.values(this.watchers).find((watcher) => watcher.actionType === actionType);
124
- }
125
- /**
126
- * Создает действие
127
- */
128
- createAction(actionConfig, executionOptions) {
129
- const actionType = `[${this.storage.name}]${actionConfig.type}`;
130
- let lastArgs = null;
131
- let lastResult = null;
132
- const dispatchFn = async (params) => {
133
- const args = [params];
134
- if (executionOptions?.memoize && lastArgs && lastResult) {
135
- if (executionOptions.memoize(args, lastArgs, lastResult)) {
136
- return lastResult;
137
- }
138
- }
139
- const actionObject = {
140
- type: actionType,
141
- meta: actionConfig.meta
142
- };
143
- let result;
144
- if (this.middlewareFunctions.length > 0) {
145
- let chain = async (action) => {
146
- if (executionOptions?.worker) {
147
- return this.executeInWorker(executionOptions.worker, actionType, args, actionConfig.action);
148
- } else {
149
- return Promise.resolve(actionConfig.action(params));
150
- }
151
- };
152
- for (let i = this.middlewareFunctions.length - 1; i >= 0; i--) {
153
- const currentMiddleware = this.middlewareFunctions[i];
154
- const nextChain = chain;
155
- chain = async (action) => {
156
- const next = async (nextAction) => nextChain(nextAction);
157
- return currentMiddleware(next)(action);
158
- };
159
- }
160
- result = await chain(actionObject);
161
- } else {
162
- if (executionOptions?.worker) {
163
- result = await this.executeInWorker(executionOptions.worker, actionType, args, actionConfig.action);
164
- } else {
165
- result = await actionConfig.action(params);
166
- }
167
- }
168
- actionObject.payload = result;
169
- lastArgs = [...args];
170
- lastResult = result;
171
- this.actions$.next(actionObject);
172
- return result;
173
- };
174
- dispatchFn._type = "dispatch";
175
- Object.defineProperty(dispatchFn, "actionType", {
176
- value: actionType,
177
- writable: false,
178
- enumerable: true
179
- });
180
- if (actionConfig.meta) {
181
- Object.defineProperty(dispatchFn, "meta", {
182
- value: actionConfig.meta,
183
- writable: false,
184
- enumerable: true
185
- });
186
- }
187
- return dispatchFn;
188
- }
189
- /**
190
- * Создает watcher для отслеживания изменений в хранилище
191
- */
192
- createWatcher(config) {
193
- const actionType = `[${this.storage.name}]${config.type}`;
194
- const subject = new import_rxjs.Subject();
195
- let prevValue;
196
- const unsubscribe = this.storage.subscribe(config.selector, (value) => {
197
- if (!config.shouldTrigger || config.shouldTrigger(prevValue, value)) {
198
- const action = {
199
- type: actionType,
200
- payload: value,
201
- meta: config.meta
202
- };
203
- this.actions$.next(action);
204
- subject.next(action);
205
- prevValue = value;
206
- }
207
- });
208
- const watcherFn = () => subject.asObservable();
209
- watcherFn._type = "watchers";
210
- Object.defineProperty(watcherFn, "actionType", {
211
- value: actionType,
212
- writable: false,
213
- enumerable: true
214
- });
215
- if (config.meta) {
216
- Object.defineProperty(watcherFn, "meta", {
217
- value: config.meta,
218
- writable: false,
219
- enumerable: true
220
- });
221
- }
222
- Object.defineProperty(watcherFn, "unsubscribe", {
223
- value: unsubscribe,
224
- writable: false,
225
- enumerable: true
226
- });
227
- return watcherFn;
228
- }
229
- /**
230
- * Выполняет действие в worker
231
- */
232
- async executeInWorker(worker, actionType, args, fallbackAction) {
233
- return new Promise((resolve, reject) => {
234
- const requestId = `${actionType}_${Date.now()}_${Math.random()}`;
235
- const handleMessage = (event) => {
236
- if (event.data.requestId === requestId) {
237
- worker.removeEventListener("message", handleMessage);
238
- if (event.data.error) {
239
- reject(new Error(event.data.error));
240
- } else {
241
- resolve(event.data.result);
242
- }
243
- }
244
- };
245
- worker.addEventListener("message", handleMessage);
246
- worker.postMessage({
247
- type: actionType,
248
- args,
249
- requestId
250
- });
251
- setTimeout(() => {
252
- worker.removeEventListener("message", handleMessage);
253
- reject(new Error(`Worker execution timeout for action: ${actionType}`));
254
- }, 3e4);
255
- });
256
- }
257
- };
258
- function createDispatcher(options, actionsSetup) {
259
- const dispatcher = new Dispatcher(options);
260
- const actions = actionsSetup(options.storage, {
261
- createAction: (actionConfig, executionOptions) => dispatcher.createAction(actionConfig, executionOptions),
262
- createWatcher: (config) => dispatcher.createWatcher(config)
263
- });
264
- for (const [key, fn] of Object.entries(actions)) {
265
- if (typeof fn === "function") {
266
- const type = fn._type;
267
- dispatcher[type][key] = fn;
268
- }
269
- }
270
- return dispatcher;
271
- }
272
-
273
- // src/reactive/dispatcher/middlewares/logger.middleware.ts
274
- function getStateDiff(prevState, nextState) {
275
- const diff = {};
276
- const allKeys = [.../* @__PURE__ */ new Set([...Object.keys(prevState), ...Object.keys(nextState)])];
277
- allKeys.forEach((key) => {
278
- if (key in prevState && key in nextState) {
279
- if (typeof prevState[key] === "object" && prevState[key] !== null && typeof nextState[key] === "object" && nextState[key] !== null && !Array.isArray(prevState[key]) && !Array.isArray(nextState[key])) {
280
- const nestedDiff = getStateDiff(prevState[key], nextState[key]);
281
- if (Object.keys(nestedDiff).length > 0) {
282
- diff[key] = nestedDiff;
283
- }
284
- } else if (JSON.stringify(prevState[key]) !== JSON.stringify(nextState[key])) {
285
- diff[key] = { PREV: prevState[key], NEXT: nextState[key] };
286
- }
287
- } else if (key in prevState) {
288
- diff[key] = { PREV: prevState[key], NEXT: void 0 };
289
- } else {
290
- diff[key] = { PREV: void 0, NEXT: nextState[key] };
291
- }
292
- });
293
- return diff;
294
- }
295
- var loggerDispatcherMiddleware = (options = {}) => {
296
- const defaultTranslations = {
297
- action: "\u0414\u0435\u0439\u0441\u0442\u0432\u0438\u0435",
298
- prevState: "\u041F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0435\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435",
299
- nextState: "\u0421\u043B\u0435\u0434\u0443\u044E\u0449\u0435\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435",
300
- duration: "\u0414\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",
301
- error: "\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0438",
302
- diff: "\u0418\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F",
303
- changesCount: "\u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439",
304
- showFullState: "\u041F\u043E\u043B\u043D\u043E\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435"
305
- };
306
- const defaultOptions = {
307
- collapsed: false,
308
- duration: true,
309
- diff: false,
310
- showFullState: true,
311
- // Показывать полное состояние по умолчанию
312
- translations: defaultTranslations,
313
- colors: {
314
- title: "#3498db",
315
- prevState: "#9E9E9E",
316
- fullState: "#008a15",
317
- action: "#03A9F4",
318
- nextState: "#4CAF50",
319
- error: "#F20404",
320
- diff: "#9C27B0"
321
- }
322
- };
323
- const mergedOptions = {
324
- ...defaultOptions,
325
- ...options,
326
- // Объединяем переводы отдельно, чтобы позволить частичное переопределение
327
- translations: {
328
- ...defaultTranslations,
329
- ...options.translations || {}
330
- },
331
- // Объединяем цвета отдельно, чтобы позволить частичное переопределение
332
- colors: {
333
- ...defaultOptions.colors,
334
- ...options.colors || {}
335
- }
336
- };
337
- const { collapsed, duration, colors, translations } = mergedOptions;
338
- return (api) => (next) => async (action) => {
339
- const started = Date.now();
340
- const prevState = await api.getState();
341
- try {
342
- const result = await next(action);
343
- const nextState = await api.getState();
344
- const ended = Date.now();
345
- const time = ended - started;
346
- const title = `${action.type}`;
347
- const groupMethod = collapsed ? console.groupCollapsed : console.group;
348
- groupMethod(`%c ${title}`, `color: ${colors.title}; font-weight: bold`);
349
- console.log(`%c ${translations.action}:`, `color: ${colors.action}; font-weight: bold`, action);
350
- if (mergedOptions.diff) {
351
- const stateDiff = getStateDiff(prevState, nextState);
352
- const changesCount = Object.keys(stateDiff).length;
353
- console.log(`%c ${translations.diff} (${translations.changesCount}: ${changesCount}):`, `color: ${colors.diff}; font-weight: bold`, stateDiff);
354
- }
355
- if (mergedOptions.showFullState) {
356
- console.groupCollapsed(`%c ${translations.showFullState}`, `color: ${colors.fullState}; font-weight: bold`);
357
- console.log(`%c ${translations.prevState}:`, `color: ${colors.prevState}; font-weight: bold`, prevState);
358
- console.log(`%c ${translations.nextState}:`, `color: ${colors.nextState}; font-weight: bold`, nextState);
359
- console.groupEnd();
360
- }
361
- if (duration) {
362
- console.log(`%c ${translations.duration}: %c ${time}ms`, "font-weight: bold", "color: #4CAF50");
363
- }
364
- console.groupEnd();
365
- return result;
366
- } catch (error) {
367
- console.error(`%c ${translations.error}:`, `color: ${colors.error}; font-weight: bold`, action.type, error);
368
- throw error;
369
- }
370
- };
371
- };
372
-
373
- // src/reactive/effects/effects.module.ts
374
- var import_rxjs4 = require("rxjs");
375
- var import_operators3 = require("rxjs/operators");
376
-
377
- // src/reactive/effects/utils/chunkRequestConsistent.ts
378
- var import_rxjs2 = require("rxjs");
379
- var import_operators = require("rxjs/operators");
380
-
381
- // src/_utils/chunk.util.ts
382
- function chunk(array, size = 1) {
383
- if (size <= 0) throw new Error("Size must be greater than 0");
384
- if (!array || !array.length) return [];
385
- const result = [];
386
- const length = array.length;
387
- let index = 0;
388
- while (index < length) {
389
- result.push(array.slice(index, index + size));
390
- index += size;
391
- }
392
- return result;
393
- }
394
-
395
- // src/reactive/effects/utils/chunkRequestConsistent.ts
396
- var chunkRequestConsistent = (fn, arr, size, delayMs = 0) => {
397
- const chunks = chunk(arr, size).map((chunkItem) => (0, import_rxjs2.of)(chunkItem).pipe((0, import_operators.delay)(delayMs), (0, import_operators.mergeMap)(fn)));
398
- return (0, import_rxjs2.of)(...chunks).pipe((0, import_operators.concatAll)(), (0, import_operators.toArray)());
399
- };
400
-
401
- // src/reactive/effects/utils/chunkRequestParallel.ts
402
- var import_rxjs3 = require("rxjs");
403
- var import_operators2 = require("rxjs/operators");
404
- var chunkRequestParallel = (fn, arr, size, delayMs = 0) => (0, import_rxjs3.forkJoin)(chunk(arr, size).map((chunkItem, index) => (0, import_rxjs3.timer)(index * delayMs).pipe((0, import_operators2.mergeMap)(() => fn(chunkItem)))));
405
-
406
- // src/reactive/effects/effects.module.ts
407
- function ofType(actionFn) {
408
- const { actionType } = actionFn;
409
- if (!actionType) {
410
- console.warn("ofType: Action function does not have actionType property", actionFn);
411
- return (0, import_operators3.filter)(() => false);
412
- }
413
- return (source$) => {
414
- return source$.pipe((0, import_operators3.filter)((action) => action !== void 0 && action.type === actionType));
415
- };
416
- }
417
- function ofTypes(actionFns) {
418
- const actionTypes = actionFns.map((fn) => fn.actionType).filter(Boolean);
419
- if (actionTypes.length === 0) {
420
- console.warn("ofTypes: No valid action types found in array", actionFns);
421
- return (0, import_operators3.filter)(() => false);
422
- }
423
- return (source$) => {
424
- return source$.pipe((0, import_operators3.filter)((action) => action !== void 0 && actionTypes.includes(action.type)));
425
- };
426
- }
427
- function ofTypesWaitAll(actionFns) {
428
- return (source$) => {
429
- const actionTypes = actionFns.map((fn) => fn.actionType).filter(Boolean);
430
- if (actionTypes.length === 0) {
431
- console.warn("ofTypesWaitAll: No valid action types found in array", actionFns);
432
- return (0, import_rxjs4.of)([]);
433
- }
434
- const actionStreams = actionTypes.map(
435
- (type, index) => source$.pipe(
436
- (0, import_operators3.filter)((action) => action.type === type),
437
- (0, import_operators3.take)(1),
438
- (0, import_operators3.map)(
439
- (action) => (
440
- // Сохраняем ассоциацию с индексом, чтобы соответствовать
441
- // порядку в исходном массиве actionFns
442
- { index, action }
443
- )
444
- )
445
- )
446
- );
447
- return (0, import_rxjs4.combineLatest)(actionStreams).pipe(
448
- (0, import_operators3.map)((results) => {
449
- results.sort((a, b) => a.index - b.index);
450
- return results.map((r) => r.action);
451
- })
452
- );
453
- };
454
- }
455
- function selectorMap(state$, ...selectors) {
456
- return state$.pipe(
457
- (0, import_operators3.map)((state) => {
458
- return selectors.map((selector) => selector(state));
459
- })
460
- );
461
- }
462
- function selectorObject(state$, selectors) {
463
- return state$.pipe(
464
- (0, import_operators3.map)((state) => {
465
- const result = {};
466
- for (const [key, selector] of Object.entries(selectors)) {
467
- result[key] = selector(state);
468
- }
469
- return result;
470
- })
471
- );
472
- }
473
- function validateMap({
474
- validator,
475
- apiCall
476
- }) {
477
- return (0, import_rxjs4.pipe)(
478
- (0, import_operators3.switchMap)((pipeData) => {
479
- const callApi = () => apiCall(pipeData, {
480
- chunkRequest: chunkRequestParallel,
481
- chunkRequestConsistent
482
- });
483
- if (!validator) return callApi();
484
- const validateConfig = validator(pipeData);
485
- const { conditions, skipAction } = validateConfig;
486
- const conditionMet = conditions.every(Boolean);
487
- if (!conditionMet) {
488
- if (Array.isArray(skipAction)) {
489
- return (0, import_rxjs4.of)(...skipAction?.filter(Boolean).map((action) => typeof action === "function" ? action() : action));
490
- }
491
- return (0, import_rxjs4.of)(typeof skipAction === "function" ? skipAction() : skipAction);
492
- }
493
- return callApi();
494
- })
495
- );
496
- }
497
- var EffectsModule = class {
498
- /**
499
- * Создает модуль эффектов с доступом к состоянию, внешним состояниям и конфигурации
500
- * @param storage Хранилище состояния
501
- * @param externalStates Внешние состояния
502
- * @param dispatchers Объект с диспетчерами
503
- * @param services Объект с сервисами
504
- * @param config Глобальная конфигурация для всех эффектов
505
- */
506
- constructor(storage, externalStates = {}, dispatchers, services = {}, config = {}) {
507
- this.storage = storage;
508
- this.externalStates = externalStates;
509
- this.dispatchers = dispatchers;
510
- this.services = services;
511
- this.config = config;
512
- this.subscribeToDispatchers();
513
- this.state$ = new import_rxjs4.Observable((observer) => {
514
- this.storage.getState().then((state) => observer.next(state));
515
- const unsubscribe = this.storage.subscribeToAll(() => {
516
- this.storage.getState().then((state) => observer.next(state));
517
- });
518
- return () => unsubscribe();
519
- }).pipe((0, import_operators3.share)());
520
- }
521
- effects = [];
522
- subscriptions = [];
523
- running = false;
524
- action$ = new import_rxjs4.Subject();
525
- /**
526
- * Поток состояния
527
- */
528
- state$;
529
- /**
530
- * Подписывается на действия от всех диспетчеров
531
- */
532
- subscribeToDispatchers() {
533
- for (const [_, dispatcher] of Object.entries(this.dispatchers)) {
534
- const subscription = dispatcher.actions.subscribe((action) => {
535
- this.action$.next(action);
536
- });
537
- this.subscriptions.push(subscription);
538
- }
539
- }
540
- add(effect) {
541
- this.effects.push(effect);
542
- if (this.running) {
543
- this.subscribeToEffect(effect);
544
- }
545
- return this;
546
- }
547
- /**
548
- * Добавляет несколько эффектов
549
- * @param effects Эффекты для добавления
550
- * @returns Текущий модуль
551
- */
552
- addEffects(effects) {
553
- effects.forEach((effect) => this.add(effect));
554
- return this;
555
- }
556
- /**
557
- * Запускает все эффекты
558
- * @returns Текущий модуль
559
- */
560
- start() {
561
- if (this.running) {
562
- return this;
563
- }
564
- this.effects.forEach((effect) => this.subscribeToEffect(effect));
565
- this.running = true;
566
- return this;
567
- }
568
- /**
569
- * Останавливает все эффекты
570
- * @returns Текущий модуль
571
- */
572
- stop() {
573
- this.subscriptions.forEach((sub) => sub.unsubscribe());
574
- this.subscriptions = [];
575
- this.running = false;
576
- return this;
577
- }
578
- /**
579
- * Подписывается на конкретный эффект
580
- * @param effect Эффект для подписки
581
- */
582
- subscribeToEffect(effect) {
583
- try {
584
- const output$ = effect(this.action$.asObservable(), this.state$, this.externalStates, this.dispatchers, this.services, this.config).pipe(
585
- (0, import_operators3.catchError)((err) => {
586
- console.error("Error in effect:", err);
587
- return (0, import_rxjs4.of)(null);
588
- })
589
- );
590
- const subscription = output$.subscribe((result) => {
591
- if (result === null || result === void 0) {
592
- return;
593
- }
594
- if (typeof result === "function") {
595
- try {
596
- result();
597
- } catch (callError) {
598
- console.error("Error calling effect result function:", callError);
599
- }
600
- }
601
- });
602
- this.subscriptions.push(subscription);
603
- } catch (setupError) {
604
- console.error("Error setting up effect:", setupError);
605
- }
606
- }
607
- };
608
- function createEffectBase(effect) {
609
- return effect;
610
- }
611
- function createEffect(effect) {
612
- return effect;
613
- }
614
- function combineEffects(...effects) {
615
- return (action$, state$, externalStates, dispatchers, services, config) => {
616
- const outputs = effects.map((effect) => {
617
- try {
618
- return effect(action$, state$, externalStates, dispatchers, services, config);
619
- } catch (error) {
620
- console.error("Error in one of combined effects:", error);
621
- return (0, import_rxjs4.of)(null);
622
- }
623
- });
624
- return (0, import_rxjs4.merge)(...outputs);
625
- };
626
- }
627
- // Annotate the CommonJS export names for ESM import in node:
628
- 0 && (module.exports = {
629
- Dispatcher,
630
- EffectsModule,
631
- combineEffects,
632
- createDispatcher,
633
- createEffect,
634
- createEffectBase,
635
- loggerDispatcherMiddleware,
636
- ofType,
637
- ofTypes,
638
- ofTypesWaitAll,
639
- selectorMap,
640
- selectorObject,
641
- validateMap
642
- });
1
+ "use strict";var A=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var j=Object.prototype.hasOwnProperty;var I=(r,e)=>{for(var t in e)A(r,t,{get:e[t],enumerable:!0})},q=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of M(e))!j.call(r,n)&&n!==t&&A(r,n,{get:()=>e[n],enumerable:!(s=k(e,n))||s.enumerable});return r};var B=r=>q(A({},"__esModule",{value:!0}),r);var Q={};I(Q,{Dispatcher:()=>b,EffectsModule:()=>w,combineEffects:()=>H,createDispatcher:()=>K,createEffect:()=>G,createEffectBase:()=>X,loggerDispatcherMiddleware:()=>L,ofType:()=>V,ofTypes:()=>N,ofTypesWaitAll:()=>_,selectorMap:()=>U,selectorObject:()=>z,validateMap:()=>J});module.exports=B(Q);var v=require("rxjs"),b=class{constructor(e){this.options=e;this.storage=e.storage,this.middlewareAPI={getState:()=>this.storage.getState(),dispatch:async t=>(this.actions$.next(t),t.payload),storage:this.storage,actions$:this.actions,actions:this.dispatch,watchers:this.watchers,findActionByType:t=>this.findActionByType(t),findWatcherByType:t=>this.findWatcherByType(t)},e.middlewares&&e.middlewares.length>0&&this.use(...e.middlewares)}actions$=new v.Subject;actions=this.actions$.asObservable();dispatch={};watchers={};storage;middlewareFunctions=[];middlewareAPI;use(...e){for(let t=0;t<e.length;t++)try{let s=e[t](this.middlewareAPI);this.middlewareFunctions.push(s)}catch(s){console.error(`Error initializing middleware [${t}]:`,s)}return this}getActions(){return this.dispatch}getTypedDispatch(){return this.dispatch}getTypedWatchers(){return this.watchers}findActionByType(e){return Object.values(this.dispatch).find(t=>t.actionType.split(`[${this.storage.name}]`)[1]===e)}findWatcherByType(e){return Object.values(this.watchers).find(t=>t.actionType===e)}createAction(e,t){let s=`[${this.storage.name}]${e.type}`,n=null,a=null,i=async o=>{let c=[o];if(t?.memoize&&n&&a&&t.memoize(c,n,a))return a;let u={type:s,meta:e.meta},d;if(this.middlewareFunctions.length>0){let y=async f=>t?.worker?this.executeInWorker(t.worker,s,c,e.action):Promise.resolve(e.action(o));for(let f=this.middlewareFunctions.length-1;f>=0;f--){let h=this.middlewareFunctions[f],g=y;y=async E=>h(async x=>g(x))(E)}d=await y(u)}else t?.worker?d=await this.executeInWorker(t.worker,s,c,e.action):d=await e.action(o);return u.payload=d,n=[...c],a=d,this.actions$.next(u),d};return i._type="dispatch",Object.defineProperty(i,"actionType",{value:s,writable:!1,enumerable:!0}),e.meta&&Object.defineProperty(i,"meta",{value:e.meta,writable:!1,enumerable:!0}),i}createWatcher(e){let t=`[${this.storage.name}]${e.type}`,s=new v.Subject,n,a=this.storage.subscribe(e.selector,o=>{if(!e.shouldTrigger||e.shouldTrigger(n,o)){let c={type:t,payload:o,meta:e.meta};this.actions$.next(c),s.next(c),n=o}}),i=()=>s.asObservable();return i._type="watchers",Object.defineProperty(i,"actionType",{value:t,writable:!1,enumerable:!0}),e.meta&&Object.defineProperty(i,"meta",{value:e.meta,writable:!1,enumerable:!0}),Object.defineProperty(i,"unsubscribe",{value:a,writable:!1,enumerable:!0}),i}async executeInWorker(e,t,s,n){return new Promise((a,i)=>{let o=`${t}_${Date.now()}_${Math.random()}`,c=u=>{u.data.requestId===o&&(e.removeEventListener("message",c),u.data.error?i(new Error(u.data.error)):a(u.data.result))};e.addEventListener("message",c),e.postMessage({type:t,args:s,requestId:o}),setTimeout(()=>{e.removeEventListener("message",c),i(new Error(`Worker execution timeout for action: ${t}`))},3e4)})}};function K(r,e){let t=new b(r),s=e(r.storage,{createAction:(n,a)=>t.createAction(n,a),createWatcher:n=>t.createWatcher(n)});for(let[n,a]of Object.entries(s))if(typeof a=="function"){let i=a._type;t[i][n]=a}return t}function F(r,e){let t={};return[...new Set([...Object.keys(r),...Object.keys(e)])].forEach(n=>{if(n in r&&n in e)if(typeof r[n]=="object"&&r[n]!==null&&typeof e[n]=="object"&&e[n]!==null&&!Array.isArray(r[n])&&!Array.isArray(e[n])){let a=F(r[n],e[n]);Object.keys(a).length>0&&(t[n]=a)}else JSON.stringify(r[n])!==JSON.stringify(e[n])&&(t[n]={PREV:r[n],NEXT:e[n]});else n in r?t[n]={PREV:r[n],NEXT:void 0}:t[n]={PREV:void 0,NEXT:e[n]}}),t}var L=(r={})=>{let e={action:"\u0414\u0435\u0439\u0441\u0442\u0432\u0438\u0435",prevState:"\u041F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0435\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435",nextState:"\u0421\u043B\u0435\u0434\u0443\u044E\u0449\u0435\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435",duration:"\u0414\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",error:"\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0438",diff:"\u0418\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F",changesCount:"\u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439",showFullState:"\u041F\u043E\u043B\u043D\u043E\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435"},t={collapsed:!1,duration:!0,diff:!1,showFullState:!0,translations:e,colors:{title:"#3498db",prevState:"#9E9E9E",fullState:"#008a15",action:"#03A9F4",nextState:"#4CAF50",error:"#F20404",diff:"#9C27B0"}},s={...t,...r,translations:{...e,...r.translations||{}},colors:{...t.colors,...r.colors||{}}},{collapsed:n,duration:a,colors:i,translations:o}=s;return c=>u=>async d=>{let y=Date.now(),f=await c.getState();try{let h=await u(d),g=await c.getState(),D=Date.now()-y,x=`${d.type}`;if((n?console.groupCollapsed:console.group)(`%c ${x}`,`color: ${i.title}; font-weight: bold`),console.log(`%c ${o.action}:`,`color: ${i.action}; font-weight: bold`,d),s.diff){let P=F(f,g),W=Object.keys(P).length;console.log(`%c ${o.diff} (${o.changesCount}: ${W}):`,`color: ${i.diff}; font-weight: bold`,P)}return s.showFullState&&(console.groupCollapsed(`%c ${o.showFullState}`,`color: ${i.fullState}; font-weight: bold`),console.log(`%c ${o.prevState}:`,`color: ${i.prevState}; font-weight: bold`,f),console.log(`%c ${o.nextState}:`,`color: ${i.nextState}; font-weight: bold`,g),console.groupEnd()),a&&console.log(`%c ${o.duration}: %c ${D}ms`,"font-weight: bold","color: #4CAF50"),console.groupEnd(),h}catch(h){throw console.error(`%c ${o.error}:`,`color: ${i.error}; font-weight: bold`,d.type,h),h}}};var p=require("rxjs"),l=require("rxjs/operators");var S=require("rxjs"),T=require("rxjs/operators");function R(r,e=1){if(e<=0)throw new Error("Size must be greater than 0");if(!r||!r.length)return[];let t=[],s=r.length,n=0;for(;n<s;)t.push(r.slice(n,n+e)),n+=e;return t}var O=(r,e,t,s=0)=>{let n=R(e,t).map(a=>(0,S.of)(a).pipe((0,T.delay)(s),(0,T.mergeMap)(r)));return(0,S.of)(...n).pipe((0,T.concatAll)(),(0,T.toArray)())};var m=require("rxjs"),$=require("rxjs/operators");var C=(r,e,t,s=0)=>(0,m.forkJoin)(R(e,t).map((n,a)=>(0,m.timer)(a*s).pipe((0,$.mergeMap)(()=>r(n)))));function V(r){let{actionType:e}=r;return e?t=>t.pipe((0,l.filter)(s=>s!==void 0&&s.type===e)):(console.warn("ofType: Action function does not have actionType property",r),(0,l.filter)(()=>!1))}function N(r){let e=r.map(t=>t.actionType).filter(Boolean);return e.length===0?(console.warn("ofTypes: No valid action types found in array",r),(0,l.filter)(()=>!1)):t=>t.pipe((0,l.filter)(s=>s!==void 0&&e.includes(s.type)))}function _(r){return e=>{let t=r.map(n=>n.actionType).filter(Boolean);if(t.length===0)return console.warn("ofTypesWaitAll: No valid action types found in array",r),(0,p.of)([]);let s=t.map((n,a)=>e.pipe((0,l.filter)(i=>i.type===n),(0,l.take)(1),(0,l.map)(i=>({index:a,action:i}))));return(0,p.combineLatest)(s).pipe((0,l.map)(n=>(n.sort((a,i)=>a.index-i.index),n.map(a=>a.action))))}}function U(r,...e){return r.pipe((0,l.map)(t=>e.map(s=>s(t))))}function z(r,e){return r.pipe((0,l.map)(t=>{let s={};for(let[n,a]of Object.entries(e))s[n]=a(t);return s}))}function J({validator:r,apiCall:e}){return(0,p.pipe)((0,l.switchMap)(t=>{let s=()=>e(t,{chunkRequest:C,chunkRequestConsistent:O});if(!r)return s();let n=r(t),{conditions:a,skipAction:i}=n;return a.every(Boolean)?s():Array.isArray(i)?(0,p.of)(...i?.filter(Boolean).map(c=>typeof c=="function"?c():c)):(0,p.of)(typeof i=="function"?i():i)}))}var w=class{constructor(e,t={},s,n={},a={}){this.storage=e;this.externalStates=t;this.dispatchers=s;this.services=n;this.config=a;this.subscribeToDispatchers(),this.state$=new p.Observable(i=>{this.storage.getState().then(c=>i.next(c));let o=this.storage.subscribeToAll(()=>{this.storage.getState().then(c=>i.next(c))});return()=>o()}).pipe((0,l.share)())}effects=[];subscriptions=[];running=!1;action$=new p.Subject;state$;subscribeToDispatchers(){for(let[e,t]of Object.entries(this.dispatchers)){let s=t.actions.subscribe(n=>{this.action$.next(n)});this.subscriptions.push(s)}}add(e){return this.effects.push(e),this.running&&this.subscribeToEffect(e),this}addEffects(e){return e.forEach(t=>this.add(t)),this}start(){return this.running?this:(this.effects.forEach(e=>this.subscribeToEffect(e)),this.running=!0,this)}stop(){return this.subscriptions.forEach(e=>e.unsubscribe()),this.subscriptions=[],this.running=!1,this}subscribeToEffect(e){try{let s=e(this.action$.asObservable(),this.state$,this.externalStates,this.dispatchers,this.services,this.config).pipe((0,l.catchError)(n=>(console.error("Error in effect:",n),(0,p.of)(null)))).subscribe(n=>{if(n!=null&&typeof n=="function")try{n()}catch(a){console.error("Error calling effect result function:",a)}});this.subscriptions.push(s)}catch(t){console.error("Error setting up effect:",t)}}};function X(r){return r}function G(r){return r}function H(...r){return(e,t,s,n,a,i)=>{let o=r.map(c=>{try{return c(e,t,s,n,a,i)}catch(u){return console.error("Error in one of combined effects:",u),(0,p.of)(null)}});return(0,p.merge)(...o)}}0&&(module.exports={Dispatcher,EffectsModule,combineEffects,createDispatcher,createEffect,createEffectBase,loggerDispatcherMiddleware,ofType,ofTypes,ofTypesWaitAll,selectorMap,selectorObject,validateMap});