@tramvai/module-common 2.70.0 → 2.72.0

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