@tramvai/module-common 2.70.1 → 2.72.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/lib/CommonModule.browser.js +100 -0
  2. package/lib/CommonModule.es.js +100 -0
  3. package/lib/CommonModule.js +106 -0
  4. package/lib/actions/ActionModule.browser.js +79 -0
  5. package/lib/actions/ActionModule.es.js +79 -0
  6. package/lib/actions/ActionModule.js +82 -0
  7. package/lib/actions/actionChecker.browser.js +52 -0
  8. package/lib/actions/actionChecker.es.js +52 -0
  9. package/lib/actions/actionChecker.js +56 -0
  10. package/lib/actions/actionExecution.browser.js +107 -0
  11. package/lib/actions/actionExecution.es.js +107 -0
  12. package/lib/actions/actionExecution.js +118 -0
  13. package/lib/actions/actionPageRunner.browser.browser.js +33 -0
  14. package/lib/actions/actionPageRunner.es.js +61 -0
  15. package/lib/actions/actionPageRunner.js +65 -0
  16. package/lib/actions/actionRegistry.browser.js +33 -0
  17. package/lib/actions/actionRegistry.es.js +33 -0
  18. package/lib/actions/actionRegistry.js +45 -0
  19. package/lib/actions/actionTramvaiReducer.browser.js +10 -0
  20. package/lib/actions/actionTramvaiReducer.es.js +10 -0
  21. package/lib/actions/actionTramvaiReducer.js +15 -0
  22. package/lib/actions/conditions/always.browser.js +10 -0
  23. package/lib/actions/conditions/always.es.js +10 -0
  24. package/lib/actions/conditions/always.js +14 -0
  25. package/lib/actions/conditions/helpers.browser.js +4 -0
  26. package/lib/actions/conditions/helpers.es.js +4 -0
  27. package/lib/actions/conditions/helpers.js +9 -0
  28. package/lib/actions/conditions/onlyBrowser.browser.js +12 -0
  29. package/lib/actions/conditions/onlyBrowser.es.js +12 -0
  30. package/lib/actions/conditions/onlyBrowser.js +16 -0
  31. package/lib/actions/conditions/onlyServer.browser.js +12 -0
  32. package/lib/actions/conditions/onlyServer.es.js +12 -0
  33. package/lib/actions/conditions/onlyServer.js +16 -0
  34. package/lib/actions/conditions/pageBrowser.browser.js +13 -0
  35. package/lib/actions/conditions/pageBrowser.es.js +13 -0
  36. package/lib/actions/conditions/pageBrowser.js +17 -0
  37. package/lib/actions/conditions/pageServer.browser.js +13 -0
  38. package/lib/actions/conditions/pageServer.es.js +13 -0
  39. package/lib/actions/conditions/pageServer.js +17 -0
  40. package/lib/actions/constants.browser.js +9 -0
  41. package/lib/actions/constants.es.js +9 -0
  42. package/lib/actions/constants.js +13 -0
  43. package/lib/bundleManager/bundleManager.browser.js +105 -0
  44. package/lib/bundleManager/bundleManager.es.js +105 -0
  45. package/lib/bundleManager/bundleManager.js +115 -0
  46. package/lib/cache/CacheModule.browser.js +58 -0
  47. package/lib/cache/CacheModule.es.js +58 -0
  48. package/lib/cache/CacheModule.js +62 -0
  49. package/lib/cache/cacheFactory.browser.js +7 -0
  50. package/lib/cache/cacheFactory.es.js +7 -0
  51. package/lib/cache/cacheFactory.js +15 -0
  52. package/lib/cache/clientProviders.browser.js +3 -0
  53. package/lib/cache/papi.es.js +18 -0
  54. package/lib/cache/papi.js +22 -0
  55. package/lib/cache/serverProviders.es.js +18 -0
  56. package/lib/cache/serverProviders.js +22 -0
  57. package/lib/child-app/ChildAppModule.browser.js +38 -0
  58. package/lib/child-app/ChildAppModule.es.js +38 -0
  59. package/lib/child-app/ChildAppModule.js +40 -0
  60. package/lib/child-app/actions.browser.js +19 -0
  61. package/lib/child-app/actions.es.js +19 -0
  62. package/lib/child-app/actions.js +23 -0
  63. package/lib/child-app/clientProviders.browser.js +18 -0
  64. package/lib/child-app/command.browser.js +35 -0
  65. package/lib/child-app/command.es.js +35 -0
  66. package/lib/child-app/command.js +40 -0
  67. package/lib/child-app/serverProviders.es.js +3 -0
  68. package/lib/child-app/serverProviders.js +7 -0
  69. package/lib/child-app/state.browser.js +13 -0
  70. package/lib/child-app/state.es.js +13 -0
  71. package/lib/child-app/state.js +17 -0
  72. package/lib/command/CommandModule.browser.js +52 -0
  73. package/lib/command/CommandModule.es.js +52 -0
  74. package/lib/command/CommandModule.js +54 -0
  75. package/lib/command/commandLineRunner.browser.js +147 -0
  76. package/lib/command/commandLineRunner.es.js +147 -0
  77. package/lib/command/commandLineRunner.js +151 -0
  78. package/lib/command/defaultLines.browser.js +25 -0
  79. package/lib/command/defaultLines.es.js +25 -0
  80. package/lib/command/defaultLines.js +29 -0
  81. package/lib/componentRegistry/componentRegistry.browser.js +25 -0
  82. package/lib/componentRegistry/componentRegistry.es.js +25 -0
  83. package/lib/componentRegistry/componentRegistry.js +34 -0
  84. package/lib/createConsumerContext/createConsumerContext.browser.js +62 -0
  85. package/lib/createConsumerContext/createConsumerContext.es.js +62 -0
  86. package/lib/createConsumerContext/createConsumerContext.js +67 -0
  87. package/lib/executionContext/executionContextManager.browser.js +57 -0
  88. package/lib/executionContext/executionContextManager.es.js +57 -0
  89. package/lib/executionContext/executionContextManager.js +61 -0
  90. package/lib/index.browser.js +13 -1300
  91. package/lib/index.es.js +13 -1318
  92. package/lib/index.js +38 -1341
  93. package/lib/providers/clientProviders.browser.js +22 -0
  94. package/lib/providers/serverProviders.es.js +3 -0
  95. package/lib/providers/serverProviders.js +7 -0
  96. package/lib/pubsub/PubSubModule.browser.js +44 -0
  97. package/lib/pubsub/PubSubModule.es.js +44 -0
  98. package/lib/pubsub/PubSubModule.js +46 -0
  99. package/lib/requestManager/RequestManagerModule.browser.browser.js +38 -0
  100. package/lib/requestManager/RequestManagerModule.es.js +35 -0
  101. package/lib/requestManager/RequestManagerModule.js +37 -0
  102. package/lib/requestManager/RequestManagerStore.browser.js +8 -0
  103. package/lib/requestManager/RequestManagerStore.es.js +8 -0
  104. package/lib/requestManager/RequestManagerStore.js +13 -0
  105. package/lib/requestManager/requestManager.browser.js +57 -0
  106. package/lib/requestManager/requestManager.es.js +57 -0
  107. package/lib/requestManager/requestManager.js +61 -0
  108. package/lib/requestManager/sharedProviders.browser.js +23 -0
  109. package/lib/requestManager/sharedProviders.es.js +23 -0
  110. package/lib/requestManager/sharedProviders.js +27 -0
  111. package/lib/responseManager/ResponseManagerModule.browser.browser.js +21 -0
  112. package/lib/responseManager/ResponseManagerModule.es.js +13 -0
  113. package/lib/responseManager/ResponseManagerModule.js +15 -0
  114. package/lib/responseManager/responseManager.browser.js +52 -0
  115. package/lib/responseManager/responseManager.es.js +52 -0
  116. package/lib/responseManager/responseManager.js +61 -0
  117. package/lib/responseManager/sharedProviders.browser.js +13 -0
  118. package/lib/responseManager/sharedProviders.es.js +13 -0
  119. package/lib/responseManager/sharedProviders.js +17 -0
  120. package/lib/state/StateModule.browser.js +54 -0
  121. package/lib/state/StateModule.es.js +54 -0
  122. package/lib/state/StateModule.js +60 -0
  123. package/package.json +24 -25
package/lib/index.es.js CHANGED
@@ -1,1319 +1,14 @@
1
- import { __decorate } from 'tslib';
2
- import eachObj from '@tinkoff/utils/object/each';
3
- import { createBundle, provide, Scope, Module, commandLineListTokens, COMMAND_LINE_RUNNER_TOKEN, COMMAND_LINES_TOKEN, DI_TOKEN, isTramvaiAction, ACTION_PARAMETERS, createToken, ACTIONS_LIST_TOKEN, IS_DI_CHILD_CONTAINER_TOKEN, BUNDLE_LIST_TOKEN } from '@tramvai/core';
4
- import { EnvironmentModule } from '@tramvai/module-environment';
5
- import { CookieModule } from '@tramvai/module-cookie';
6
- export { COOKIE_MANAGER_TOKEN } from '@tramvai/module-cookie';
7
- import { LogModule } from '@tramvai/module-log';
8
- import { Hooks } from '@tinkoff/hook-runner';
9
- import { REQUEST_MANAGER_TOKEN, COMBINE_REDUCERS, CONTEXT_TOKEN, RESPONSE_MANAGER_TOKEN, ACTION_EXECUTION_TOKEN, ROOT_EXECUTION_CONTEXT_TOKEN, LOGGER_TOKEN, EXECUTION_CONTEXT_MANAGER_TOKEN, COMMAND_LINE_EXECUTION_CONTEXT_TOKEN, PUBSUB_FACTORY_TOKEN, PUBSUB_TOKEN, ROOT_PUBSUB_TOKEN, ACTION_REGISTRY_TOKEN, ACTION_CONDITIONALS, STORE_TOKEN, ACTION_PAGE_RUNNER_TOKEN, DISPATCHER_TOKEN, DISPATCHER_CONTEXT_TOKEN, STORE_MIDDLEWARE, INITIAL_APP_STATE_TOKEN, CLEAR_CACHE_TOKEN, CREATE_CACHE_TOKEN, REGISTER_CLEAR_CACHE_TOKEN, HOOK_TOKEN, COMPONENT_REGISTRY_TOKEN, BUNDLE_MANAGER_TOKEN, ADDITIONAL_BUNDLE_TOKEN } from '@tramvai/tokens-common';
1
+ export { CommonModule } from './CommonModule.es.js';
2
+ export { CommandModule } from './command/CommandModule.es.js';
3
+ export { ActionExecution } from './actions/actionExecution.es.js';
4
+ export { ExecutionContextManager } from './executionContext/executionContextManager.es.js';
5
+ import './actions/ActionModule.es.js';
6
+ export { createConsumerContext } from './createConsumerContext/createConsumerContext.es.js';
7
+ export { CommonChildAppModule } from './child-app/ChildAppModule.es.js';
10
8
  export * from '@tramvai/tokens-common';
11
- import isObject from '@tinkoff/utils/is/object';
12
- import isArray from '@tinkoff/utils/is/array';
13
- import { resolveLazyComponent, __lazyErrorHandler } from '@tramvai/react';
14
- import { fileSystemPagesEnabled, getAllFileSystemPages, getAllFileSystemLayouts, getAllFileSystemErrorBoundaries, isFileSystemPageComponent, fileSystemPageToLayoutKey, fileSystemPageToErrorBoundaryKey } from '@tramvai/experiments';
15
- import pathOr from '@tinkoff/utils/object/pathOr';
16
- import flatten from '@tinkoff/utils/array/flatten';
17
- import { createEvent, createReducer, convertAction, createDispatcher, devTools, Provider } from '@tramvai/state';
18
- import { FASTIFY_REQUEST } from '@tramvai/tokens-server-private';
19
- import { format, parse } from '@tinkoff/url';
20
- import isEmpty from '@tinkoff/utils/is/empty';
21
- import values from '@tinkoff/utils/object/values';
22
- import { COMMAND_LINE_TIMING_INFO_TOKEN, COMMAND_LINE_EXECUTION_END_TOKEN } from '@tramvai/tokens-core-private';
23
- import { createChildContainer, provide as provide$1, Scope as Scope$1, createToken as createToken$1 } from '@tinkoff/dippy';
24
- import { isSilentError, ConditionFailError, ExecutionAbortError } from '@tinkoff/errors';
25
- import { PubSub } from '@tinkoff/pubsub';
26
- import identity from '@tinkoff/utils/function/identity';
27
- import objectMap from '@tinkoff/utils/object/map';
28
- import uniq from '@tinkoff/utils/array/uniq';
29
- import difference from '@tinkoff/utils/array/difference';
30
- import toArray from '@tinkoff/utils/array/toArray';
31
- import LRU from '@tinkoff/lru-cache-nano';
32
- import { SERVER_MODULE_PAPI_PRIVATE_ROUTE } from '@tramvai/tokens-server';
33
- import { createPapiMethod } from '@tramvai/papi';
34
- import { AbortController } from 'node-abort-controller';
35
- import { jsx } from 'react/jsx-runtime';
36
- import { EXTEND_RENDER } from '@tramvai/tokens-render';
37
- import { CHILD_APP_INTERNAL_ROOT_DI_BORROW_TOKEN, commandLineListTokens as commandLineListTokens$1 } from '@tramvai/tokens-child-app';
38
-
39
- const FS_PAGES_DEFAULT_BUNDLE = '__default';
40
- class BundleManager {
41
- constructor({ bundleList, componentRegistry, actionRegistry, dispatcher, logger }) {
42
- this.bundles = bundleList;
43
- this.componentRegistry = componentRegistry;
44
- this.actionRegistry = actionRegistry;
45
- this.dispatcher = dispatcher;
46
- if (fileSystemPagesEnabled()) {
47
- const log = logger('file-system-pages:bundle-manager');
48
- const components = getAllFileSystemPages();
49
- const layouts = getAllFileSystemLayouts();
50
- const errorBoundaries = getAllFileSystemErrorBoundaries();
51
- const getComponentsFor = (mapping, getKey) => Object.keys(mapping).reduce((result, key) => {
52
- // eslint-disable-next-line no-param-reassign
53
- result[getKey(key)] = mapping[key];
54
- return result;
55
- }, {});
56
- const componentsDefaultBundle = createBundle({
57
- name: FS_PAGES_DEFAULT_BUNDLE,
58
- components: {
59
- ...getComponentsFor(layouts, fileSystemPageToLayoutKey),
60
- ...getComponentsFor(errorBoundaries, fileSystemPageToErrorBoundaryKey),
61
- ...components,
62
- },
63
- });
64
- this.bundles[FS_PAGES_DEFAULT_BUNDLE] = () => Promise.resolve({
65
- default: componentsDefaultBundle,
66
- });
67
- for (const key in componentsDefaultBundle.components) {
68
- this.componentRegistry.add(key, componentsDefaultBundle.components[key], FS_PAGES_DEFAULT_BUNDLE);
69
- }
70
- log.debug({
71
- event: 'create default bundle with file-system pages',
72
- components: Object.keys(components),
73
- });
74
- }
75
- }
76
- get(name, pageComponent) {
77
- // use fake bundle with file-system pages
78
- if (isFileSystemPageComponent(pageComponent)) {
79
- // eslint-disable-next-line no-param-reassign
80
- name = FS_PAGES_DEFAULT_BUNDLE;
81
- }
82
- return this.loadBundle(name, pageComponent).then((bundle) => this.resolve(bundle.default, pageComponent));
83
- }
84
- has(name, pageComponent) {
85
- // use fake bundle with file-system pages
86
- if (isFileSystemPageComponent(pageComponent)) {
87
- // eslint-disable-next-line no-param-reassign
88
- name = FS_PAGES_DEFAULT_BUNDLE;
89
- }
90
- return !!this.bundles[name];
91
- }
92
- async resolve(bundle, pageComponent) {
93
- // preload `lazy` components then register actions and reducers
94
- if (pageComponent && bundle.components[pageComponent]) {
95
- const componentOrLoader = bundle.components[pageComponent];
96
- const component = await resolveLazyComponent(componentOrLoader);
97
- if (!component) {
98
- return;
99
- }
100
- // allow page components to register any other components
101
- if ('components' in component && isObject(component.components)) {
102
- eachObj((cmp, name) => {
103
- this.componentRegistry.add(name, cmp, pageComponent);
104
- }, component.components);
105
- }
106
- if ('actions' in component && isArray(component.actions)) {
107
- this.actionRegistry.add(pageComponent, component.actions);
108
- }
109
- if ('reducers' in component && isArray(component.reducers)) {
110
- component.reducers.forEach((reducer) => {
111
- this.dispatcher.registerStore(reducer);
112
- });
113
- }
114
- }
115
- eachObj((component, name) => {
116
- this.componentRegistry.add(name, component, bundle.name);
117
- }, bundle.components);
118
- if (bundle.actions) {
119
- this.actionRegistry.add(bundle.name, bundle.actions);
120
- }
121
- if (bundle.reducers) {
122
- bundle.reducers.forEach((reducer) => {
123
- this.dispatcher.registerStore(reducer);
124
- });
125
- }
126
- return bundle;
127
- }
128
- loadBundle(name, pageComponent) {
129
- if (!this.has(name, pageComponent)) {
130
- return Promise.reject(new Error(`Bundle "${name}" not found`));
131
- }
132
- return this.bundles[name]().catch((e) => __lazyErrorHandler(e, this.bundles[name]));
133
- }
134
- }
135
-
136
- const DEFAULT_GROUP = '__default';
137
- class ComponentRegistry {
138
- constructor({ componentList } = {}) {
139
- this.components = {
140
- [DEFAULT_GROUP]: Object.assign({}, ...flatten(componentList !== null && componentList !== void 0 ? componentList : [])),
141
- };
142
- }
143
- add(name, component, group = DEFAULT_GROUP) {
144
- const groupComponents = this.components[group] || {};
145
- groupComponents[name] = component;
146
- this.components[group] = groupComponents;
147
- }
148
- get(name, group = DEFAULT_GROUP) {
149
- const groupComponents = this.components[group] || {};
150
- return groupComponents[name] || this.components[DEFAULT_GROUP][name];
151
- }
152
- getComponentParam(param, defaultValue, component, group) {
153
- return pathOr([param], defaultValue, this.get(component, group));
154
- }
155
- }
156
-
157
- const setRequest = createEvent('setRequest');
158
- const RequestManagerStore = createReducer('requestManager', {}).on(setRequest, (_, state) => {
159
- return state;
160
- });
161
-
162
- class RequestManager {
163
- constructor({ request }) {
164
- this.request = request || {};
165
- if (typeof window === 'undefined') {
166
- this.url = format({
167
- protocol: this.getHeader('x-forwarded-proto') || this.request.protocol,
168
- host: this.getHost(),
169
- path: this.request.url,
170
- });
171
- }
172
- else {
173
- this.url = window.location.href;
174
- }
175
- }
176
- getBody() {
177
- return this.request.body;
178
- }
179
- getUrl() {
180
- return this.url;
181
- }
182
- getParsedUrl() {
183
- if (!this.parsedUrl) {
184
- this.parsedUrl = parse(this.url);
185
- }
186
- return this.parsedUrl;
187
- }
188
- getMethod() {
189
- return this.request.method;
190
- }
191
- getHeader(key) {
192
- var _a;
193
- return (_a = this.request.headers) === null || _a === void 0 ? void 0 : _a[key];
194
- }
195
- getHeaders() {
196
- return this.request.headers;
197
- }
198
- getCookie(key) {
199
- return this.request.cookies[key];
200
- }
201
- getCookies() {
202
- return this.request.cookies;
203
- }
204
- getClientIp() {
205
- var _a, _b;
206
- return this.getHeader('x-real-ip') || ((_b = (_a = this.request) === null || _a === void 0 ? void 0 : _a.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) || '';
207
- }
208
- getHost() {
209
- if (typeof window === 'undefined') {
210
- return (this.getHeader('x-original-host') || this.getHeader('host'));
211
- }
212
- return window.location.host;
213
- }
214
- }
215
-
216
- const sharedProviders$1 = [
217
- provide({
218
- provide: REQUEST_MANAGER_TOKEN,
219
- scope: Scope.REQUEST,
220
- useClass: RequestManager,
221
- deps: {
222
- request: FASTIFY_REQUEST,
223
- },
224
- }),
225
- provide({
226
- provide: COMBINE_REDUCERS,
227
- multi: true,
228
- useValue: RequestManagerStore,
229
- }),
230
- ];
231
-
232
- let RequestManagerModule = class RequestManagerModule {
233
- };
234
- RequestManagerModule = __decorate([
235
- Module({
236
- providers: [
237
- ...sharedProviders$1,
238
- provide({
239
- provide: commandLineListTokens.customerStart,
240
- multi: true,
241
- useFactory: ({ context, requestManager }) => {
242
- return function dehydrateRequestManager() {
243
- return context.dispatch(setRequest({
244
- body: requestManager.getBody(),
245
- headers: {
246
- 'x-real-ip': requestManager.getClientIp(),
247
- },
248
- }));
249
- };
250
- },
251
- deps: {
252
- context: CONTEXT_TOKEN,
253
- requestManager: REQUEST_MANAGER_TOKEN,
254
- },
255
- }),
256
- ],
257
- })
258
- ], RequestManagerModule);
259
-
260
- class ResponseManager {
261
- constructor() {
262
- this.body = '';
263
- this.headers = {};
264
- this.cookies = {};
265
- this.status = 200;
266
- }
267
- getBody() {
268
- return this.body;
269
- }
270
- setBody(value) {
271
- this.body = value;
272
- }
273
- getHeader(key) {
274
- if (key === 'set-cookie') {
275
- return values(this.cookies);
276
- }
277
- return this.headers[key];
278
- }
279
- getHeaders() {
280
- if (isEmpty(this.cookies)) {
281
- return this.headers;
282
- }
283
- return {
284
- ...this.headers,
285
- 'Set-Cookie': values(this.cookies),
286
- };
287
- }
288
- setHeader(key, value) {
289
- this.headers[key] = value;
290
- }
291
- getCookie(key) {
292
- return this.cookies[key];
293
- }
294
- getCookies() {
295
- return this.cookies;
296
- }
297
- setCookie(key, value) {
298
- this.cookies[key] = value;
299
- }
300
- setStatus(status) {
301
- this.status = status;
302
- }
303
- getStatus() {
304
- return this.status;
305
- }
306
- }
307
-
308
- const sharedProviders = [
309
- provide({
310
- provide: RESPONSE_MANAGER_TOKEN,
311
- scope: Scope.REQUEST,
312
- useClass: ResponseManager,
313
- }),
314
- ];
315
-
316
- let ResponseManagerModule = class ResponseManagerModule {
317
- };
318
- ResponseManagerModule = __decorate([
319
- Module({
320
- providers: [...sharedProviders],
321
- })
322
- ], ResponseManagerModule);
323
-
324
- class ConsumerContext {
325
- constructor({ di, dispatcherContext, pubsub, store }) {
326
- /* Side Effects */
327
- this.executeAction = (action, payload) => {
328
- return this.di.get(ACTION_EXECUTION_TOKEN).run(action, payload);
329
- };
330
- /* State manager */
331
- this.dispatch = (actionOrNameEvent, payload) => {
332
- return new Promise((resolve, reject) => {
333
- try {
334
- resolve(this.store.dispatch(convertAction(actionOrNameEvent, payload)));
335
- }
336
- catch (err) {
337
- reject(err);
338
- }
339
- });
340
- };
341
- this.dispatchWith = (createActionOrType, options) => {
342
- return typeof createActionOrType === 'function'
343
- ? (...args) => this.dispatch(createActionOrType(...args), options)
344
- : (payload) => this.dispatch(createActionOrType, payload);
345
- };
346
- /**
347
- * @deprecated
348
- */
349
- this.getStore = (store) => {
350
- return this.dispatcher.getStore(store);
351
- };
352
- this.dehydrate = () => ({
353
- dispatcher: this.dispatcher.dehydrate(),
354
- });
355
- this.getState = (...args) => {
356
- return this.store.getState(args[0]);
357
- };
358
- this.subscribe = (...args) => {
359
- return this.store.subscribe(args[0], args[1]);
360
- };
361
- this.hasStore = (store) => this.dispatcher.hasStore(store);
362
- this.registerStore = (store) => this.dispatcher.registerStore(store);
363
- this.unregisterStore = (store) => this.dispatcher.unregisterStore(store);
364
- this.store = store;
365
- // @ts-expect-error
366
- this.dispatcher = dispatcherContext;
367
- // TODO убрать, нужно для некоторых старых сторов на платформе
368
- this.dispatcher.setContext(this);
369
- this.di = di; // кажется этого здесь не должно быть
370
- this.pubsub = pubsub;
371
- }
372
- }
373
- function createConsumerContext({ di, dispatcherContext, pubsub, store }) {
374
- return new ConsumerContext({
375
- di,
376
- dispatcherContext,
377
- pubsub,
378
- store,
379
- });
380
- }
381
-
382
- const resolveDi = (type, status, diContainer, providers) => {
383
- let di = diContainer;
384
- if (status === 'customer' && type !== 'client') {
385
- di = createChildContainer(di);
386
- }
387
- if (providers) {
388
- providers.forEach((item) => {
389
- return di.register(item);
390
- });
391
- }
392
- return di;
393
- };
394
- class CommandLineRunner {
395
- constructor({ lines, rootDi, logger, executionContextManager, executionEndHandlers }) {
396
- this.executionContextByDi = new WeakMap();
397
- this.abortControllerByDi = new WeakMap();
398
- this.lines = lines;
399
- this.rootDi = rootDi;
400
- this.log = logger('command:command-line-runner');
401
- this.executionContextManager = executionContextManager;
402
- this.executionEndHandlers = executionEndHandlers;
403
- }
404
- run(type, status, providers, customDi) {
405
- const di = customDi !== null && customDi !== void 0 ? customDi : resolveDi(type, status, this.rootDi, providers);
406
- const rootExecutionContext = di.get({ token: ROOT_EXECUTION_CONTEXT_TOKEN, optional: true });
407
- this.log.debug({
408
- event: 'command-run',
409
- type,
410
- status,
411
- });
412
- const timingInfo = {};
413
- di.register({ provide: COMMAND_LINE_TIMING_INFO_TOKEN, useValue: timingInfo });
414
- return (this.lines[type][status]
415
- .reduce((chain, line) => {
416
- return chain.then(() => {
417
- const lineName = line.toString();
418
- timingInfo[lineName] = { start: performance.now() };
419
- // eslint-disable-next-line promise/no-nesting
420
- return Promise.resolve()
421
- .then(() => {
422
- return this.executionContextManager.withContext(rootExecutionContext, `command-line:${lineName}`, async (executionContext, abortController) => {
423
- this.executionContextByDi.set(di, executionContext);
424
- this.abortControllerByDi.set(di, abortController);
425
- await this.createLineChain(di, line);
426
- });
427
- })
428
- .finally(() => {
429
- timingInfo[lineName].end = performance.now();
430
- });
431
- });
432
- }, Promise.resolve())
433
- // После завершения цепочки отдаем context выполнения
434
- .finally(() => {
435
- this.executionContextByDi.delete(di);
436
- this.abortControllerByDi.delete(di);
437
- if (this.executionEndHandlers) {
438
- for (const executionEndHandler of this.executionEndHandlers) {
439
- executionEndHandler(di, type, status, timingInfo);
440
- }
441
- }
442
- })
443
- .then(() => di));
444
- }
445
- resolveExecutionContextFromDi(di) {
446
- var _a;
447
- return (_a = this.executionContextByDi.get(di)) !== null && _a !== void 0 ? _a : null;
448
- }
449
- createLineChain(di, line) {
450
- let lineInstance;
451
- try {
452
- lineInstance = di.get({ token: line, optional: true });
453
- // Пропускаем step. Так как нет действий
454
- if (lineInstance === null) {
455
- return Promise.resolve();
456
- }
457
- }
458
- catch (e) {
459
- // Логируем ошибку и дальше падаем
460
- this.log.error(e);
461
- return this.throwError(e, di);
462
- }
463
- if (!Array.isArray(lineInstance)) {
464
- return this.instanceExecute(lineInstance, line, di);
465
- }
466
- return Promise.all(lineInstance.map((instance) => {
467
- return this.instanceExecute(instance, line, di);
468
- }));
469
- }
470
- instanceExecute(instance, line, di) {
471
- if (!(instance instanceof Function)) {
472
- const error = new TypeError(`Expected function in line processing "commandLineListTokens.${line.toString()}", received "${instance}".
473
- Check that all commandLineListTokens subscribers return functions`);
474
- if (process.env.NODE_ENV !== 'production') {
475
- const instances = di.get(line);
476
- const record = di.getRecord(line.toString());
477
- // пробегаемся по всем инстансам и для текущего получаем его запись, из которой можно получить стек
478
- for (let i = 0; i < instances.length; i++) {
479
- if (instances[i] === instance) {
480
- // @ts-expect-error
481
- error.stack = `${error.stack}\n---- caused by: ----\n${record.multi[i].stack || ''}`;
482
- }
483
- }
484
- }
485
- this.log.error({
486
- event: 'line-error',
487
- error,
488
- line: line.toString(),
489
- });
490
- return;
491
- }
492
- const { name = '' } = instance;
493
- this.log.debug({
494
- event: 'line-run',
495
- line: line.toString(),
496
- command: name,
497
- });
498
- return Promise.resolve()
499
- .then(() => instance())
500
- .catch((err) => {
501
- var _a;
502
- this.log[isSilentError(err) ? 'debug' : 'error']({
503
- event: 'line-error',
504
- error: err,
505
- line: line.toString(),
506
- command: name,
507
- });
508
- // in case if any error happens during line execution results from other line handlers will not be used anyway
509
- (_a = this.abortControllerByDi.get(di)) === null || _a === void 0 ? void 0 : _a.abort();
510
- this.throwError(err, di);
511
- });
512
- }
513
- // eslint-disable-next-line class-methods-use-this
514
- throwError(err, di) {
515
- if (typeof err === 'object') {
516
- // eslint-disable-next-line no-param-reassign
517
- err.di = di;
518
- }
519
- throw err;
520
- }
521
- }
522
-
523
- const command$1 = {
524
- init: [commandLineListTokens.init, commandLineListTokens.listen],
525
- close: [commandLineListTokens.close],
526
- customer: [
527
- commandLineListTokens.customerStart,
528
- commandLineListTokens.resolveUserDeps,
529
- commandLineListTokens.resolvePageDeps,
530
- commandLineListTokens.generatePage,
531
- commandLineListTokens.clear,
532
- ],
533
- spa: [
534
- commandLineListTokens.resolveUserDeps,
535
- commandLineListTokens.resolvePageDeps,
536
- commandLineListTokens.spaTransition,
537
- ],
538
- afterSpa: [commandLineListTokens.afterSpaTransition],
539
- };
540
- const lines$1 = {
541
- server: command$1,
542
- client: command$1,
543
- };
544
-
545
- let CommandModule = class CommandModule {
546
- };
547
- CommandModule = __decorate([
548
- Module({
549
- providers: [
550
- provide$1({
551
- // Раннер процессов
552
- provide: COMMAND_LINE_RUNNER_TOKEN,
553
- scope: Scope$1.SINGLETON,
554
- useClass: CommandLineRunner,
555
- deps: {
556
- lines: COMMAND_LINES_TOKEN,
557
- rootDi: DI_TOKEN,
558
- logger: LOGGER_TOKEN,
559
- executionContextManager: EXECUTION_CONTEXT_MANAGER_TOKEN,
560
- executionEndHandlers: {
561
- token: COMMAND_LINE_EXECUTION_END_TOKEN,
562
- optional: true,
563
- },
564
- },
565
- }),
566
- provide$1({
567
- provide: COMMAND_LINE_EXECUTION_CONTEXT_TOKEN,
568
- useFactory: ({ di, commandLineRunner }) => {
569
- return () => {
570
- return commandLineRunner.resolveExecutionContextFromDi(di);
571
- };
572
- },
573
- deps: {
574
- di: DI_TOKEN,
575
- commandLineRunner: COMMAND_LINE_RUNNER_TOKEN,
576
- },
577
- }),
578
- provide$1({
579
- // Дефолтный список команл
580
- provide: COMMAND_LINES_TOKEN,
581
- scope: Scope$1.SINGLETON,
582
- useValue: lines$1,
583
- }),
584
- ],
585
- })
586
- ], CommandModule);
587
-
588
- let PubSubModule = class PubSubModule {
589
- };
590
- PubSubModule = __decorate([
591
- Module({
592
- providers: [
593
- provide({
594
- // Фабрика для создания pubsub
595
- provide: PUBSUB_FACTORY_TOKEN,
596
- scope: Scope.SINGLETON,
597
- useFactory: (deps) => () => {
598
- return new PubSub({
599
- logger: deps.logger('pubsub'),
600
- });
601
- },
602
- deps: {
603
- logger: LOGGER_TOKEN,
604
- },
605
- }),
606
- provide({
607
- provide: PUBSUB_TOKEN,
608
- scope: Scope.REQUEST,
609
- useFactory: ({ createPubsub }) => createPubsub(),
610
- deps: {
611
- createPubsub: PUBSUB_FACTORY_TOKEN,
612
- },
613
- }),
614
- provide({
615
- provide: ROOT_PUBSUB_TOKEN,
616
- scope: Scope.SINGLETON,
617
- useFactory: ({ createPubsub }) => createPubsub(),
618
- deps: {
619
- createPubsub: PUBSUB_FACTORY_TOKEN,
620
- },
621
- }),
622
- ],
623
- })
624
- ], PubSubModule);
625
-
626
- const providers$2 = [];
627
-
628
- const actionServerStateEvent = createEvent('action state execution in server');
629
- const initalState = { serverState: {} };
630
- const actionTramvaiReducer = createReducer('actionTramvai', initalState).on(actionServerStateEvent, (state, payload) => ({
631
- ...state,
632
- serverState: payload,
633
- }));
634
-
635
- /**
636
- * @deprecated only for compatibility with legacy createAction
637
- */
638
- const actionType = {
639
- global: 'global',
640
- local: 'local',
641
- };
642
-
643
- const DEFAULT_CONDITIONS = {};
644
- class ActionChecker {
645
- // eslint-disable-next-line max-params
646
- constructor(globalConditionals, payload, parameters, executionState, type) {
647
- var _a;
648
- this.globalConditionals = globalConditionals;
649
- this.payload = payload;
650
- this.parameters = parameters;
651
- this.executionState = executionState;
652
- this.type = type;
653
- this.status = true;
654
- this.forbiddenMarker = false;
655
- this.key = null;
656
- // для глобальных экшенов мы должны дедублицировать выполнение и меньше выполнять
657
- if (type === actionType.global) {
658
- // если экшен был уже выполнен, то считаем, что его не нужно больше выполнять
659
- this.status = executionState.status !== 'success';
660
- }
661
- this.conditions = (_a = parameters.conditions) !== null && _a !== void 0 ? _a : DEFAULT_CONDITIONS;
662
- }
663
- check() {
664
- this.globalConditionals.forEach((filter) => {
665
- this.key = filter.key;
666
- filter.fn(this);
667
- });
668
- return this.getStatus();
669
- }
670
- setState(value) {
671
- this.executionState.state[this.key] = value;
672
- }
673
- getState() {
674
- return this.executionState.state[this.key];
675
- }
676
- forbid() {
677
- this.executionState.status = 'forbidden';
678
- this.executionState.forbiddenBy = this.key;
679
- this.forbiddenMarker = true;
680
- }
681
- allow() {
682
- this.status = true;
683
- }
684
- getStatus() {
685
- if (this.forbiddenMarker) {
686
- return false;
687
- }
688
- return this.status;
689
- }
690
- }
691
-
692
- const EMPTY_DEPS = {};
693
- const DEFAULT_PAYLOAD = {};
694
- const getParameters = (action) => action[ACTION_PARAMETERS];
695
- class ActionExecution {
696
- constructor({ store, context, di, executionContextManager, actionConditionals, transformAction, }) {
697
- this.actionConditionals = flatten(actionConditionals !== null && actionConditionals !== void 0 ? actionConditionals : []);
698
- this.context = context;
699
- this.store = store;
700
- this.di = di;
701
- this.executionContextManager = executionContextManager;
702
- this.execution = new Map();
703
- this.transformAction = transformAction || identity;
704
- const initialState = store.getState(actionTramvaiReducer);
705
- if (initialState && initialState.serverState) {
706
- objectMap((value, key) => {
707
- this.execution.set(key, value);
708
- }, initialState.serverState);
709
- }
710
- }
711
- async runInContext(executionContext, action, ...params) {
712
- var _a, _b;
713
- let parameters;
714
- const payload = (_a = params[0]) !== null && _a !== void 0 ? _a : DEFAULT_PAYLOAD;
715
- // TODO: replace type with pure context usage
716
- const type = (executionContext === null || executionContext === void 0 ? void 0 : executionContext.values.pageActions) === true ? actionType.global : actionType.local;
717
- // TODO: remove else branch after migration to new declareAction
718
- if (isTramvaiAction(action)) {
719
- parameters = action;
720
- }
721
- else {
722
- this.transformAction(action);
723
- parameters = getParameters(action);
724
- }
725
- const executionState = this.getExecutionState(parameters.name);
726
- if (!this.canExecuteAction(payload, parameters, executionState, type)) {
727
- switch (parameters.conditionsFailResult) {
728
- case 'reject':
729
- return Promise.reject(new ConditionFailError({
730
- conditionName: (_b = executionState.forbiddenBy) !== null && _b !== void 0 ? _b : 'unknown',
731
- targetName: parameters.name,
732
- }));
733
- default:
734
- return Promise.resolve();
735
- }
736
- }
737
- executionState.status = 'pending';
738
- return this.executionContextManager.withContext(executionContext, {
739
- name: parameters.name,
740
- values: (executionContext === null || executionContext === void 0 ? void 0 : executionContext.values.pageActions) === true ? { pageActions: false } : undefined,
741
- }, (executionActionContext, abortController) => {
742
- const context = this.createActionContext(executionContext, executionActionContext, abortController, parameters);
743
- return Promise.resolve()
744
- .then(() => {
745
- if (isTramvaiAction(action)) {
746
- return action.fn.apply(context, params);
747
- }
748
- return action(this.context, payload, context.deps);
749
- })
750
- .then((data) => {
751
- executionState.status = 'success';
752
- return data;
753
- })
754
- .catch((err) => {
755
- executionState.status = 'failed';
756
- throw err;
757
- });
758
- });
759
- }
760
- async run(action, ...params) {
761
- return this.runInContext(null, action, ...params);
762
- }
763
- getExecutionState(name) {
764
- let executionState = this.execution.get(name);
765
- // TODO: probably do not need to create executionState on client as it is not used
766
- if (!executionState) {
767
- executionState = { status: 'pending', state: {} };
768
- this.execution.set(name, executionState);
769
- }
770
- return executionState;
771
- }
772
- canExecuteAction(payload, parameters, executionState, type) {
773
- const actionChecker = new ActionChecker(this.actionConditionals, payload, parameters, executionState, type);
774
- return actionChecker.check();
775
- }
776
- createActionContext(parentExecutionContext, actionExecutionContext, abortController, parameters) {
777
- return {
778
- abortController,
779
- abortSignal: actionExecutionContext === null || actionExecutionContext === void 0 ? void 0 : actionExecutionContext.abortSignal,
780
- executeAction: this.runInContext.bind(this, actionExecutionContext),
781
- deps: parameters.deps ? this.di.getOfDeps(parameters.deps) : EMPTY_DEPS,
782
- actionType: (parentExecutionContext === null || parentExecutionContext === void 0 ? void 0 : parentExecutionContext.values.pageActions) ? 'page' : 'standalone',
783
- dispatch: this.store.dispatch,
784
- getState: this.store.getState,
785
- };
786
- }
787
- }
788
-
789
- const GLOBAL_PARAMETER = '@@global';
790
- class ActionRegistry {
791
- constructor({ actionsList }) {
792
- this.actions = new Map([[GLOBAL_PARAMETER, flatten(actionsList)]]);
793
- }
794
- add(type, actions) {
795
- const normalized = toArray(actions);
796
- this.actions.set(type, uniq(this.actions.has(type) ? [...this.actions.get(type), ...normalized] : normalized));
797
- }
798
- get(type, addingActions) {
799
- return uniq([...(this.actions.get(type) || []), ...(addingActions || [])]);
800
- }
801
- getGlobal() {
802
- return this.actions.get(GLOBAL_PARAMETER);
803
- }
804
- remove(type, actions) {
805
- if (!actions) {
806
- this.actions.delete(type);
807
- return;
808
- }
809
- const normalized = toArray(actions);
810
- if (this.actions.has(type)) {
811
- this.actions.set(type, difference(this.actions.get(type), normalized));
812
- }
813
- }
814
- }
815
-
816
- class ActionPageRunner {
817
- constructor(deps) {
818
- this.deps = deps;
819
- this.log = deps.logger('action:action-page-runner');
820
- }
821
- // TODO stopRunAtError нужен только для редиректов на стороне сервера в экшенах. И нужно пересмотреть реализацию редиректов
822
- runActions(actions, stopRunAtError = () => false) {
823
- return this.deps.executionContextManager.withContext(this.deps.commandLineExecutionContext(), { name: 'pageActions', values: { pageActions: true } }, (executionContext, abortController) => {
824
- return new Promise((resolve, reject) => {
825
- const timeoutMarker = setTimeout(() => {
826
- this.log.warn(`page actions has exceeded timeout of ${this.deps.limitTime}ms, ignore some results of execution`);
827
- abortController.abort();
828
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
829
- endChecker();
830
- }, this.deps.limitTime);
831
- const endChecker = () => {
832
- clearTimeout(timeoutMarker);
833
- const result = {};
834
- // TODO: dehydrate only actions on first level as inner actions are running on client despite their execution on server
835
- this.deps.actionExecution.execution.forEach((value, key) => {
836
- // достаем значения экшенов, которые успешно выполнились, остальные выполнятся на клиенте
837
- if (value.status === 'success') {
838
- result[key] = value;
839
- }
840
- });
841
- this.syncStateActions(result);
842
- resolve();
843
- };
844
- const actionMapper = (action) => {
845
- return Promise.resolve()
846
- .then(() => this.deps.actionExecution.runInContext(executionContext, action))
847
- .catch((error) => {
848
- if (!isSilentError(error)) {
849
- const parameters = isTramvaiAction(action) ? action : action[ACTION_PARAMETERS];
850
- this.log.error({
851
- error,
852
- event: `action-execution-error`,
853
- message: `${parameters.name} execution error`,
854
- });
855
- }
856
- if (stopRunAtError(error)) {
857
- clearTimeout(timeoutMarker);
858
- reject(error);
859
- }
860
- });
861
- };
862
- // eslint-disable-next-line promise/catch-or-return
863
- Promise.all(actions.map(actionMapper)).then(endChecker);
864
- });
865
- });
866
- }
867
- syncStateActions(success) {
868
- return this.deps.store.dispatch(actionServerStateEvent(success));
869
- }
870
- }
871
-
872
- const alwaysCondition = {
873
- key: 'alwaysCondition',
874
- fn: (checker) => {
875
- if (checker.conditions.always) {
876
- checker.allow();
877
- }
878
- },
879
- };
880
-
881
- const isServer = typeof window === 'undefined';
882
- const isBrowser = !isServer;
883
-
884
- const onlyServer = {
885
- key: 'onlyServer',
886
- fn: (checker) => {
887
- if (checker.conditions.onlyServer && isBrowser) {
888
- checker.forbid();
889
- }
890
- },
891
- };
892
-
893
- const onlyBrowser = {
894
- key: 'onlyBrowser',
895
- fn: (checker) => {
896
- if (checker.conditions.onlyBrowser && isServer) {
897
- checker.forbid();
898
- }
899
- },
900
- };
901
-
902
- const pageServer = {
903
- key: 'pageServer',
904
- fn: (checker) => {
905
- if (checker.conditions.pageServer && checker.type === actionType.global && isBrowser) {
906
- checker.forbid();
907
- }
908
- },
909
- };
910
-
911
- const pageBrowser = {
912
- key: 'pageBrowser',
913
- fn: (checker) => {
914
- if (checker.conditions.pageBrowser && checker.type === actionType.global && isServer) {
915
- checker.forbid();
916
- }
917
- },
918
- };
919
-
920
- const LIMIT_ACTION_GLOBAL_TIME_RUN = createToken('limitActionGlobalTimeRun');
921
- let ActionModule = class ActionModule {
922
- };
923
- ActionModule = __decorate([
924
- Module({
925
- providers: [
926
- provide({
927
- provide: COMBINE_REDUCERS,
928
- multi: true,
929
- useValue: actionTramvaiReducer,
930
- }),
931
- provide({
932
- // Регистер глобальных экшенов
933
- provide: ACTION_REGISTRY_TOKEN,
934
- scope: Scope.SINGLETON,
935
- useClass: ActionRegistry,
936
- deps: { actionsList: ACTIONS_LIST_TOKEN },
937
- }),
938
- provide({
939
- provide: ACTION_EXECUTION_TOKEN,
940
- scope: Scope.REQUEST,
941
- useClass: ActionExecution,
942
- deps: {
943
- actionConditionals: { token: ACTION_CONDITIONALS, optional: true },
944
- context: CONTEXT_TOKEN,
945
- store: STORE_TOKEN,
946
- di: DI_TOKEN,
947
- executionContextManager: EXECUTION_CONTEXT_MANAGER_TOKEN,
948
- transformAction: {
949
- token: 'actionTransformAction',
950
- optional: true,
951
- },
952
- },
953
- }),
954
- provide({
955
- provide: ACTION_PAGE_RUNNER_TOKEN,
956
- scope: Scope.REQUEST,
957
- useClass: ActionPageRunner,
958
- deps: {
959
- actionExecution: ACTION_EXECUTION_TOKEN,
960
- executionContextManager: EXECUTION_CONTEXT_MANAGER_TOKEN,
961
- commandLineExecutionContext: COMMAND_LINE_EXECUTION_CONTEXT_TOKEN,
962
- store: STORE_TOKEN,
963
- limitTime: LIMIT_ACTION_GLOBAL_TIME_RUN,
964
- logger: LOGGER_TOKEN,
965
- },
966
- }),
967
- provide({
968
- provide: LIMIT_ACTION_GLOBAL_TIME_RUN,
969
- useValue: 500,
970
- }),
971
- provide({
972
- provide: ACTION_CONDITIONALS,
973
- multi: true,
974
- useValue: [alwaysCondition, onlyServer, onlyBrowser, pageServer, pageBrowser],
975
- }),
976
- ],
977
- })
978
- ], ActionModule);
979
-
980
- let StateModule = class StateModule {
981
- };
982
- StateModule = __decorate([
983
- Module({
984
- providers: [
985
- provide({
986
- provide: DISPATCHER_TOKEN,
987
- scope: Scope.SINGLETON,
988
- useFactory: ({ stores }) => createDispatcher({ stores: stores && flatten(stores) }),
989
- deps: {
990
- stores: {
991
- token: COMBINE_REDUCERS,
992
- optional: true,
993
- },
994
- },
995
- }),
996
- provide({
997
- provide: DISPATCHER_CONTEXT_TOKEN,
998
- scope: Scope.REQUEST,
999
- useFactory: ({ dispatcher, initialState, middlewares }) => {
1000
- return dispatcher.createContext({}, initialState, [
1001
- devTools.middleware(),
1002
- ...flatten(middlewares || []),
1003
- ]);
1004
- },
1005
- deps: {
1006
- dispatcher: DISPATCHER_TOKEN,
1007
- middlewares: { token: STORE_MIDDLEWARE, optional: true },
1008
- initialState: { token: INITIAL_APP_STATE_TOKEN, optional: true },
1009
- },
1010
- }),
1011
- provide({
1012
- provide: STORE_TOKEN,
1013
- scope: Scope.REQUEST,
1014
- useFactory: ({ dispatcherContext }) => ({
1015
- getState: dispatcherContext.getState.bind(dispatcherContext),
1016
- dispatch: dispatcherContext.dispatch.bind(dispatcherContext),
1017
- subscribe: dispatcherContext.subscribe.bind(dispatcherContext),
1018
- }),
1019
- deps: {
1020
- dispatcherContext: DISPATCHER_CONTEXT_TOKEN,
1021
- },
1022
- }),
1023
- ],
1024
- })
1025
- ], StateModule);
1026
-
1027
- const cacheFactory = (type, options = { max: 100 }) => {
1028
- return new LRU(options);
1029
- };
1030
-
1031
- const papiClearCache = ({ clearCache, logger, }) => {
1032
- const log = logger('cache:papi-clear-cache');
1033
- return createPapiMethod({
1034
- method: 'post',
1035
- path: '/clear-cache',
1036
- async handler({ responseManager }) {
1037
- await clearCache();
1038
- // DEVOPS-1661
1039
- responseManager.setStatus(404);
1040
- responseManager.setHeader('X-Status', 'done');
1041
- log.info('SERVER:CLEAR:CACHE:INTERNAL');
1042
- },
1043
- });
1044
- };
1045
-
1046
- const providers$1 = [
1047
- provide({
1048
- provide: SERVER_MODULE_PAPI_PRIVATE_ROUTE,
1049
- multi: true,
1050
- useFactory: papiClearCache,
1051
- deps: {
1052
- clearCache: CLEAR_CACHE_TOKEN,
1053
- logger: LOGGER_TOKEN,
1054
- },
1055
- }),
1056
- ];
1057
-
1058
- const cachesToken = createToken$1('_cachesList');
1059
- let CacheModule = class CacheModule {
1060
- };
1061
- CacheModule = __decorate([
1062
- Module({
1063
- providers: [
1064
- ...providers$1,
1065
- {
1066
- provide: cachesToken,
1067
- scope: Scope.SINGLETON,
1068
- useValue: [],
1069
- },
1070
- {
1071
- provide: CREATE_CACHE_TOKEN,
1072
- useFactory: ({ caches, isChildDi }) => {
1073
- if (isChildDi) {
1074
- return cacheFactory;
1075
- }
1076
- return (type, ...args) => {
1077
- const cache = cacheFactory(type, ...args);
1078
- caches.push(cache);
1079
- return cache;
1080
- };
1081
- },
1082
- deps: {
1083
- caches: cachesToken,
1084
- isChildDi: { token: IS_DI_CHILD_CONTAINER_TOKEN, optional: true },
1085
- },
1086
- },
1087
- {
1088
- provide: CLEAR_CACHE_TOKEN,
1089
- scope: Scope.SINGLETON,
1090
- useFactory: ({ caches, cachesClear }) => {
1091
- return (type) => {
1092
- caches.forEach((cache) => cache.clear());
1093
- if (cachesClear) {
1094
- return Promise.all(cachesClear.map((clear) => clear(type)));
1095
- }
1096
- return Promise.resolve();
1097
- };
1098
- },
1099
- deps: {
1100
- caches: cachesToken,
1101
- cachesClear: { token: REGISTER_CLEAR_CACHE_TOKEN, optional: true },
1102
- },
1103
- },
1104
- ],
1105
- })
1106
- ], CacheModule);
1107
-
1108
- const EMPTY_VALUES = {};
1109
- const normalizeOptions = (nameOrOptions) => {
1110
- return typeof nameOrOptions === 'string' ? { name: nameOrOptions } : nameOrOptions;
1111
- };
1112
- class ExecutionContextManager {
1113
- async withContext(parentContext, nameOrOptions, cb) {
1114
- const options = normalizeOptions(nameOrOptions);
1115
- const { name, values: selfValues = EMPTY_VALUES } = options;
1116
- const contextName = parentContext ? `${parentContext.name}.${name}` : name;
1117
- if (parentContext === null || parentContext === void 0 ? void 0 : parentContext.abortSignal.aborted) {
1118
- throw new ExecutionAbortError({
1119
- message: `Execution aborted in context "${contextName}"`,
1120
- contextName,
1121
- });
1122
- }
1123
- const abortController = new AbortController();
1124
- let abortListener;
1125
- let values = selfValues;
1126
- if (parentContext) {
1127
- values = {
1128
- ...parentContext.values,
1129
- ...selfValues,
1130
- };
1131
- abortListener = () => {
1132
- abortController.abort();
1133
- };
1134
- // abort child context AbortController if parent AbortController was aborted
1135
- parentContext.abortSignal.addEventListener('abort', abortListener);
1136
- }
1137
- const context = {
1138
- name: contextName,
1139
- abortSignal: abortController.signal,
1140
- values,
1141
- };
1142
- try {
1143
- const result = await cb(context, abortController);
1144
- return result;
1145
- }
1146
- catch (error) {
1147
- if (typeof error === 'object' && !error.executionContextName) {
1148
- error.executionContextName = context.name;
1149
- }
1150
- throw error;
1151
- }
1152
- finally {
1153
- // @ts-expect-error
1154
- if (abortListener && parentContext) {
1155
- parentContext.abortSignal.removeEventListener('abort', abortListener);
1156
- }
1157
- }
1158
- }
1159
- }
1160
-
1161
- let CommonModule = class CommonModule {
1162
- };
1163
- CommonModule = __decorate([
1164
- Module({
1165
- imports: [
1166
- CommandModule,
1167
- EnvironmentModule,
1168
- PubSubModule,
1169
- LogModule,
1170
- CookieModule,
1171
- ActionModule,
1172
- StateModule,
1173
- RequestManagerModule,
1174
- ResponseManagerModule,
1175
- CacheModule,
1176
- ],
1177
- providers: [
1178
- provide({
1179
- // Инстанс хук системы
1180
- provide: HOOK_TOKEN,
1181
- scope: Scope.SINGLETON,
1182
- useClass: Hooks,
1183
- }),
1184
- provide({
1185
- // Регистр ui компонентов
1186
- provide: COMPONENT_REGISTRY_TOKEN,
1187
- scope: Scope.SINGLETON,
1188
- useClass: ComponentRegistry,
1189
- deps: {
1190
- componentList: { token: 'componentDefaultList', optional: true },
1191
- },
1192
- }),
1193
- provide({
1194
- // Управление бандлами, хранение и получение
1195
- provide: BUNDLE_MANAGER_TOKEN,
1196
- scope: Scope.SINGLETON,
1197
- useFactory: ({ additionalBundleList, ...bundleManagerDeps }) => {
1198
- additionalBundleList === null || additionalBundleList === void 0 ? void 0 : additionalBundleList.forEach((bundles) => {
1199
- eachObj((bundle, name) => {
1200
- const bundleAlreadyExists = name in bundleManagerDeps.bundleList;
1201
- if (!bundleAlreadyExists) {
1202
- // eslint-disable-next-line no-param-reassign
1203
- bundleManagerDeps.bundleList[name] = () => Promise.resolve({ default: bundle });
1204
- }
1205
- }, bundles);
1206
- });
1207
- return new BundleManager(bundleManagerDeps);
1208
- },
1209
- deps: {
1210
- bundleList: BUNDLE_LIST_TOKEN,
1211
- additionalBundleList: { token: ADDITIONAL_BUNDLE_TOKEN, optional: true },
1212
- componentRegistry: COMPONENT_REGISTRY_TOKEN,
1213
- actionRegistry: ACTION_REGISTRY_TOKEN,
1214
- dispatcher: DISPATCHER_TOKEN,
1215
- logger: LOGGER_TOKEN,
1216
- },
1217
- }),
1218
- provide({
1219
- // Клиентский контекст исполнения
1220
- provide: CONTEXT_TOKEN,
1221
- scope: Scope.REQUEST,
1222
- useFactory: createConsumerContext,
1223
- deps: {
1224
- di: DI_TOKEN,
1225
- pubsub: PUBSUB_TOKEN,
1226
- dispatcherContext: DISPATCHER_CONTEXT_TOKEN,
1227
- store: STORE_TOKEN,
1228
- },
1229
- }),
1230
- provide({
1231
- provide: EXECUTION_CONTEXT_MANAGER_TOKEN,
1232
- useClass: ExecutionContextManager,
1233
- }),
1234
- ...providers$2,
1235
- ],
1236
- })
1237
- ], CommonModule);
1238
-
1239
- const providers = [];
1240
-
1241
- const stateProviders = [
1242
- provide({
1243
- provide: CHILD_APP_INTERNAL_ROOT_DI_BORROW_TOKEN,
1244
- multi: true,
1245
- useValue: [DISPATCHER_TOKEN, STORE_TOKEN, CONTEXT_TOKEN],
1246
- }),
1247
- ];
1248
-
1249
- const command = {
1250
- customer: [
1251
- commandLineListTokens$1.customerStart,
1252
- commandLineListTokens$1.resolveUserDeps,
1253
- commandLineListTokens$1.resolvePageDeps,
1254
- ],
1255
- clear: [commandLineListTokens$1.clear],
1256
- spa: [
1257
- commandLineListTokens$1.resolveUserDeps,
1258
- commandLineListTokens$1.resolvePageDeps,
1259
- commandLineListTokens$1.spaTransition,
1260
- ],
1261
- afterSpa: [commandLineListTokens$1.afterSpaTransition],
1262
- };
1263
- const lines = {
1264
- server: command,
1265
- client: command,
1266
- };
1267
- const commandProviders = [
1268
- provide({
1269
- provide: CHILD_APP_INTERNAL_ROOT_DI_BORROW_TOKEN,
1270
- multi: true,
1271
- useValue: COMMAND_LINE_RUNNER_TOKEN,
1272
- }),
1273
- provide({
1274
- provide: COMMAND_LINES_TOKEN,
1275
- scope: Scope.SINGLETON,
1276
- useValue: lines,
1277
- }),
1278
- ];
1279
-
1280
- const actionsProviders = [
1281
- provide({
1282
- provide: CHILD_APP_INTERNAL_ROOT_DI_BORROW_TOKEN,
1283
- multi: true,
1284
- useValue: [ACTION_EXECUTION_TOKEN, ACTION_PAGE_RUNNER_TOKEN],
1285
- }),
1286
- provide({
1287
- provide: COMBINE_REDUCERS,
1288
- multi: true,
1289
- useValue: actionTramvaiReducer,
1290
- }),
1291
- ];
1292
-
1293
- let CommonChildAppModule = class CommonChildAppModule {
1294
- };
1295
- CommonChildAppModule = __decorate([
1296
- Module({
1297
- providers: [
1298
- ...providers,
1299
- ...stateProviders,
1300
- ...commandProviders,
1301
- ...actionsProviders,
1302
- provide({
1303
- provide: EXTEND_RENDER,
1304
- multi: true,
1305
- useFactory: ({ context }) => {
1306
- const serverState = typeof window !== 'undefined' ? context.getState() : undefined;
1307
- return (render) => {
1308
- return (jsx(Provider, { context: context, serverState: serverState, children: render }));
1309
- };
1310
- },
1311
- deps: {
1312
- context: CONTEXT_TOKEN,
1313
- },
1314
- }),
1315
- ],
1316
- })
1317
- ], CommonChildAppModule);
1318
-
1319
- export { ActionExecution, CommandModule, CommonChildAppModule, CommonModule, ExecutionContextManager, alwaysCondition, createConsumerContext, onlyBrowser, onlyServer, pageBrowser, pageServer };
9
+ export { COOKIE_MANAGER_TOKEN } from '@tramvai/module-cookie';
10
+ export { alwaysCondition } from './actions/conditions/always.es.js';
11
+ export { onlyServer } from './actions/conditions/onlyServer.es.js';
12
+ export { onlyBrowser } from './actions/conditions/onlyBrowser.es.js';
13
+ export { pageServer } from './actions/conditions/pageServer.es.js';
14
+ export { pageBrowser } from './actions/conditions/pageBrowser.es.js';