@matreshka/bff 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +32 -0
- package/README.md +35 -0
- package/dist/components/actions/server-action.d.ts +30 -0
- package/dist/components/actions/server-action.js +23 -0
- package/dist/components/aliases/button.d.ts +17 -0
- package/dist/components/aliases/button.js +54 -0
- package/dist/components/aliases/column.d.ts +11 -0
- package/dist/components/aliases/column.js +31 -0
- package/dist/components/aliases/row.d.ts +11 -0
- package/dist/components/aliases/row.js +31 -0
- package/dist/components/aliases/surface.d.ts +11 -0
- package/dist/components/aliases/surface.js +30 -0
- package/dist/components/app.d.ts +5 -0
- package/dist/components/app.js +12 -0
- package/dist/components/board.d.ts +58 -0
- package/dist/components/board.js +152 -0
- package/dist/components/boot.d.ts +2 -0
- package/dist/components/boot.js +39 -0
- package/dist/components/camera.d.ts +77 -0
- package/dist/components/camera.js +116 -0
- package/dist/components/charts/bar-chart.d.ts +14 -0
- package/dist/components/charts/bar-chart.js +27 -0
- package/dist/components/charts/chart.d.ts +69 -0
- package/dist/components/charts/chart.js +42 -0
- package/dist/components/charts/doughnut-chart.d.ts +14 -0
- package/dist/components/charts/doughnut-chart.js +27 -0
- package/dist/components/charts/line-chart.d.ts +14 -0
- package/dist/components/charts/line-chart.js +27 -0
- package/dist/components/charts/pie-chart.d.ts +14 -0
- package/dist/components/charts/pie-chart.js +27 -0
- package/dist/components/charts/polar-area-chart.d.ts +14 -0
- package/dist/components/charts/polar-area-chart.js +27 -0
- package/dist/components/charts/radar-chart.d.ts +14 -0
- package/dist/components/charts/radar-chart.js +27 -0
- package/dist/components/component.d.ts +159 -0
- package/dist/components/component.js +380 -0
- package/dist/components/container.d.ts +48 -0
- package/dist/components/container.js +80 -0
- package/dist/components/dialog.d.ts +83 -0
- package/dist/components/dialog.js +120 -0
- package/dist/components/entry-component.d.ts +34 -0
- package/dist/components/entry-component.js +74 -0
- package/dist/components/enum/password-input-kind.d.ts +1 -0
- package/dist/components/enum/password-input-kind.js +5 -0
- package/dist/components/enum/popover-position-area.d.ts +1 -0
- package/dist/components/enum/popover-position-area.js +5 -0
- package/dist/components/enum/text-input-kind.d.ts +1 -0
- package/dist/components/enum/text-input-kind.js +5 -0
- package/dist/components/enum/textarea-resize.d.ts +1 -0
- package/dist/components/enum/textarea-resize.js +5 -0
- package/dist/components/file-upload-area.d.ts +79 -0
- package/dist/components/file-upload-area.js +138 -0
- package/dist/components/for-each.d.ts +188 -0
- package/dist/components/for-each.js +362 -0
- package/dist/components/form.d.ts +62 -0
- package/dist/components/form.js +92 -0
- package/dist/components/grid.d.ts +80 -0
- package/dist/components/grid.js +79 -0
- package/dist/components/index.d.ts +55 -0
- package/dist/components/index.js +76 -0
- package/dist/components/inputs/input-component.d.ts +37 -0
- package/dist/components/inputs/input-component.js +30 -0
- package/dist/components/inputs/number-input.d.ts +45 -0
- package/dist/components/inputs/number-input.js +43 -0
- package/dist/components/inputs/password-input.d.ts +28 -0
- package/dist/components/inputs/password-input.js +42 -0
- package/dist/components/inputs/text-editor.d.ts +91 -0
- package/dist/components/inputs/text-editor.js +282 -0
- package/dist/components/inputs/text-input.d.ts +48 -0
- package/dist/components/inputs/text-input.js +40 -0
- package/dist/components/inputs/textarea.d.ts +36 -0
- package/dist/components/inputs/textarea.js +42 -0
- package/dist/components/item-list/flatten-nested-items.d.ts +11 -0
- package/dist/components/item-list/flatten-nested-items.js +100 -0
- package/dist/components/item-list/index.d.ts +5 -0
- package/dist/components/item-list/index.js +21 -0
- package/dist/components/item-list/item-list-host.d.ts +10 -0
- package/dist/components/item-list/item-list-host.js +2 -0
- package/dist/components/item-list/item-list.d.ts +68 -0
- package/dist/components/item-list/item-list.js +206 -0
- package/dist/components/item-list/list-from-ref-context.d.ts +11 -0
- package/dist/components/item-list/list-from-ref-context.js +27 -0
- package/dist/components/item-list/nested-items-host-support.d.ts +36 -0
- package/dist/components/item-list/nested-items-host-support.js +109 -0
- package/dist/components/item-list/types.d.ts +40 -0
- package/dist/components/item-list/types.js +13 -0
- package/dist/components/line.d.ts +43 -0
- package/dist/components/line.js +35 -0
- package/dist/components/map.d.ts +83 -0
- package/dist/components/map.js +146 -0
- package/dist/components/outputs/currency.d.ts +63 -0
- package/dist/components/outputs/currency.js +42 -0
- package/dist/components/outputs/datetime.d.ts +69 -0
- package/dist/components/outputs/datetime.js +49 -0
- package/dist/components/outputs/icon.d.ts +43 -0
- package/dist/components/outputs/icon.js +38 -0
- package/dist/components/outputs/iframe.d.ts +48 -0
- package/dist/components/outputs/iframe.js +44 -0
- package/dist/components/outputs/image.d.ts +73 -0
- package/dist/components/outputs/image.js +63 -0
- package/dist/components/outputs/number.d.ts +39 -0
- package/dist/components/outputs/number.js +47 -0
- package/dist/components/outputs/output-component.d.ts +58 -0
- package/dist/components/outputs/output-component.js +50 -0
- package/dist/components/outputs/progress-bar.d.ts +33 -0
- package/dist/components/outputs/progress-bar.js +42 -0
- package/dist/components/outputs/progress-spinner.d.ts +37 -0
- package/dist/components/outputs/progress-spinner.js +43 -0
- package/dist/components/outputs/qr-code.d.ts +28 -0
- package/dist/components/outputs/qr-code.js +40 -0
- package/dist/components/outputs/text.d.ts +57 -0
- package/dist/components/outputs/text.js +78 -0
- package/dist/components/outputs/vector.d.ts +47 -0
- package/dist/components/outputs/vector.js +53 -0
- package/dist/components/page.d.ts +96 -0
- package/dist/components/page.js +127 -0
- package/dist/components/popover.d.ts +63 -0
- package/dist/components/popover.js +96 -0
- package/dist/components/stack.d.ts +158 -0
- package/dist/components/stack.js +146 -0
- package/dist/components/types/component-sequence.d.ts +3 -0
- package/dist/components/types/component-sequence.js +2 -0
- package/dist/components/types/container-overlay.d.ts +3 -0
- package/dist/components/types/container-overlay.js +2 -0
- package/dist/components/utils/component-factory-shared.d.ts +4 -0
- package/dist/components/utils/component-factory-shared.js +12 -0
- package/dist/core/actions/action.d.ts +35 -0
- package/dist/core/actions/action.js +45 -0
- package/dist/core/actions/animate-component.d.ts +58 -0
- package/dist/core/actions/animate-component.js +57 -0
- package/dist/core/actions/local-action.d.ts +8 -0
- package/dist/core/actions/local-action.js +12 -0
- package/dist/core/actions/set-context-value.d.ts +18 -0
- package/dist/core/actions/set-context-value.js +32 -0
- package/dist/core/actions/set-context-values.d.ts +34 -0
- package/dist/core/actions/set-context-values.js +30 -0
- package/dist/core/actions/toggle-context-value.d.ts +21 -0
- package/dist/core/actions/toggle-context-value.js +30 -0
- package/dist/core/actions/write-text-to-clipboard.d.ts +30 -0
- package/dist/core/actions/write-text-to-clipboard.js +44 -0
- package/dist/core/boot.d.ts +2 -0
- package/dist/core/boot.js +8 -0
- package/dist/core/client-context.d.ts +7 -0
- package/dist/core/client-context.js +20 -0
- package/dist/core/client.d.ts +133 -0
- package/dist/core/client.js +292 -0
- package/dist/core/conditions/condition-group.d.ts +14 -0
- package/dist/core/conditions/condition-group.js +30 -0
- package/dist/core/conditions/condition-operand.d.ts +27 -0
- package/dist/core/conditions/condition-operand.js +15 -0
- package/dist/core/conditions/condition.d.ts +27 -0
- package/dist/core/conditions/condition.js +35 -0
- package/dist/core/conditions/context-array-includes.d.ts +32 -0
- package/dist/core/conditions/context-array-includes.js +52 -0
- package/dist/core/conditions/context-array-length.d.ts +86 -0
- package/dist/core/conditions/context-array-length.js +155 -0
- package/dist/core/conditions/context-value-defined.d.ts +12 -0
- package/dist/core/conditions/context-value-defined.js +21 -0
- package/dist/core/conditions/context-value-equal.d.ts +14 -0
- package/dist/core/conditions/context-value-equal.js +26 -0
- package/dist/core/conditions/context-value-in.d.ts +17 -0
- package/dist/core/conditions/context-value-in.js +26 -0
- package/dist/core/conditions/context-value-not-equal.d.ts +14 -0
- package/dist/core/conditions/context-value-not-equal.js +26 -0
- package/dist/core/conditions/context-value-undefined.d.ts +12 -0
- package/dist/core/conditions/context-value-undefined.js +21 -0
- package/dist/core/conditions/desktop-device.d.ts +11 -0
- package/dist/core/conditions/desktop-device.js +21 -0
- package/dist/core/conditions/groups.d.ts +71 -0
- package/dist/core/conditions/groups.js +74 -0
- package/dist/core/conditions/index.d.ts +17 -0
- package/dist/core/conditions/index.js +33 -0
- package/dist/core/conditions/mobile-device.d.ts +11 -0
- package/dist/core/conditions/mobile-device.js +21 -0
- package/dist/core/conditions/not-desktop-device.d.ts +11 -0
- package/dist/core/conditions/not-desktop-device.js +21 -0
- package/dist/core/conditions/not-mobile-device.d.ts +11 -0
- package/dist/core/conditions/not-mobile-device.js +21 -0
- package/dist/core/conditions/not-tablet-device.d.ts +11 -0
- package/dist/core/conditions/not-tablet-device.js +21 -0
- package/dist/core/conditions/tablet-device.d.ts +11 -0
- package/dist/core/conditions/tablet-device.js +21 -0
- package/dist/core/context/context-ref.d.ts +48 -0
- package/dist/core/context/context-ref.js +58 -0
- package/dist/core/context/context.d.ts +121 -0
- package/dist/core/context/context.js +353 -0
- package/dist/core/entry-context.d.ts +14 -0
- package/dist/core/entry-context.js +31 -0
- package/dist/core/gateway-connection.d.ts +29 -0
- package/dist/core/gateway-connection.js +146 -0
- package/dist/core/index.d.ts +30 -0
- package/dist/core/index.js +46 -0
- package/dist/core/matreshka.d.ts +61 -0
- package/dist/core/matreshka.js +186 -0
- package/dist/core/router.d.ts +38 -0
- package/dist/core/router.js +116 -0
- package/dist/core/types/client-settings.d.ts +31 -0
- package/dist/core/types/client-settings.js +2 -0
- package/dist/core/types/component-instance.d.ts +25 -0
- package/dist/core/types/component-instance.js +42 -0
- package/dist/core/types/component-tree-node.d.ts +11 -0
- package/dist/core/types/component-tree-node.js +18 -0
- package/dist/core/types/componentable.d.ts +21 -0
- package/dist/core/types/componentable.js +2 -0
- package/dist/core/types/context-ref-primitive-value.d.ts +5 -0
- package/dist/core/types/context-ref-primitive-value.js +2 -0
- package/dist/core/types/message.d.ts +15 -0
- package/dist/core/types/message.js +2 -0
- package/dist/core/types/mixed-with-callbacks-array.d.ts +9 -0
- package/dist/core/types/mixed-with-callbacks-array.js +2 -0
- package/dist/core/types/native-picker-context-ref.d.ts +7 -0
- package/dist/core/types/native-picker-context-ref.js +2 -0
- package/dist/core/types/pageable.d.ts +15 -0
- package/dist/core/types/pageable.js +2 -0
- package/dist/core/types/standalone-component.d.ts +9 -0
- package/dist/core/types/standalone-component.js +2 -0
- package/dist/core/types/status-code.d.ts +319 -0
- package/dist/core/types/status-code.js +322 -0
- package/dist/core/utils/calculate-components.d.ts +13 -0
- package/dist/core/utils/calculate-components.js +40 -0
- package/dist/core/utils/color-token-id.d.ts +11 -0
- package/dist/core/utils/color-token-id.js +24 -0
- package/dist/core/utils/deep-pick.d.ts +2 -0
- package/dist/core/utils/deep-pick.js +54 -0
- package/dist/core/utils/hex-to-hsl.d.ts +14 -0
- package/dist/core/utils/hex-to-hsl.js +49 -0
- package/dist/core/utils/incoming-message-observer.d.ts +9 -0
- package/dist/core/utils/incoming-message-observer.js +23 -0
- package/dist/core/utils/merge-deep.d.ts +8 -0
- package/dist/core/utils/merge-deep.js +39 -0
- package/dist/core/utils/objects-diff.d.ts +13 -0
- package/dist/core/utils/objects-diff.js +56 -0
- package/dist/core/utils/parse-context-path.d.ts +4 -0
- package/dist/core/utils/parse-context-path.js +16 -0
- package/dist/core/utils/replace-context-keys.d.ts +12 -0
- package/dist/core/utils/replace-context-keys.js +90 -0
- package/dist/core/utils/serialize-component-tree.d.ts +9 -0
- package/dist/core/utils/serialize-component-tree.js +24 -0
- package/dist/core/utils/set-object-property.d.ts +2 -0
- package/dist/core/utils/set-object-property.js +29 -0
- package/dist/core/utils/track-created-instances.d.ts +10 -0
- package/dist/core/utils/track-created-instances.js +18 -0
- package/dist/core/version.d.ts +1 -0
- package/dist/core/version.js +21 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +19 -0
- package/dist/platforms/android-platform.d.ts +6 -0
- package/dist/platforms/android-platform.js +10 -0
- package/dist/platforms/browser-platform.d.ts +79 -0
- package/dist/platforms/browser-platform.js +143 -0
- package/dist/platforms/client-platform.d.ts +6 -0
- package/dist/platforms/client-platform.js +10 -0
- package/dist/platforms/index.d.ts +12 -0
- package/dist/platforms/index.js +28 -0
- package/dist/platforms/ios-platform.d.ts +6 -0
- package/dist/platforms/ios-platform.js +10 -0
- package/dist/platforms/max-mini-app-platform.d.ts +45 -0
- package/dist/platforms/max-mini-app-platform.js +87 -0
- package/dist/platforms/mobile-platform.d.ts +117 -0
- package/dist/platforms/mobile-platform.js +316 -0
- package/dist/platforms/platform.d.ts +109 -0
- package/dist/platforms/platform.js +224 -0
- package/dist/platforms/pwa-platform.d.ts +6 -0
- package/dist/platforms/pwa-platform.js +10 -0
- package/dist/platforms/server-platform.d.ts +6 -0
- package/dist/platforms/server-platform.js +10 -0
- package/dist/platforms/telegram-mini-app-platform.d.ts +87 -0
- package/dist/platforms/telegram-mini-app-platform.js +166 -0
- package/dist/platforms/utils/client-platform.d.ts +4 -0
- package/dist/platforms/utils/client-platform.js +38 -0
- package/dist/platforms/utils/mobile-ble-services.d.ts +3 -0
- package/dist/platforms/utils/mobile-ble-services.js +31 -0
- package/dist/platforms/web-platform.d.ts +9 -0
- package/dist/platforms/web-platform.js +13 -0
- package/package.json +109 -0
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { JsonObject } from "@matreshka/shared/types/json";
|
|
2
|
+
import { BehaviorSubject } from "rxjs";
|
|
3
|
+
import { Paths, PathValue } from "ts-essentials";
|
|
4
|
+
import { ZodObject } from "zod/v4";
|
|
5
|
+
import type { Client } from "../client";
|
|
6
|
+
import { ContextRef } from "./context-ref";
|
|
7
|
+
/**
|
|
8
|
+
* Контекст данных, связанных с клиентом.
|
|
9
|
+
*
|
|
10
|
+
* Используется для хранения и синхронизации состояния между сервером и клиентом,
|
|
11
|
+
* а также для отслеживания ошибок валидации и управления реактивными изменениями.
|
|
12
|
+
*
|
|
13
|
+
* @template T Тип структуры данных контекста.
|
|
14
|
+
*/
|
|
15
|
+
export declare class Context<T extends JsonObject> {
|
|
16
|
+
/** Уникальный идентификатор контекста */
|
|
17
|
+
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
18
|
+
/** Реактивное хранилище данных контекста. */
|
|
19
|
+
data$?: BehaviorSubject<T>;
|
|
20
|
+
/** Схема валидации данных контекста */
|
|
21
|
+
readonly schema?: ZodObject;
|
|
22
|
+
/** Флаг, указывающий, что контекст должен быть инициализирован при авторизации клиента */
|
|
23
|
+
readonly preload: boolean;
|
|
24
|
+
/** Реактивное хранилище инициализации контекста */
|
|
25
|
+
private _init$;
|
|
26
|
+
readonly init$: import("rxjs").Observable<void>;
|
|
27
|
+
/**
|
|
28
|
+
* Отслеживает, было ли изменение данных инициировано клиентом.
|
|
29
|
+
* Если да — синхронизация с клиентом не требуется.
|
|
30
|
+
*/
|
|
31
|
+
private dataChangedByClient?;
|
|
32
|
+
private initDataCallback?;
|
|
33
|
+
private initPromise?;
|
|
34
|
+
private initializing;
|
|
35
|
+
private destroyed;
|
|
36
|
+
private subscriptions;
|
|
37
|
+
private dataSubscription?;
|
|
38
|
+
private assertNotDestroyed;
|
|
39
|
+
/** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
|
|
40
|
+
private reportInitFailureToClients;
|
|
41
|
+
/**
|
|
42
|
+
* Создаёт экземпляр контекста, привязанный к конкретному клиенту.
|
|
43
|
+
*
|
|
44
|
+
* Подписывается на входящие сообщения от клиента и ошибки, связанные с этим контекстом.
|
|
45
|
+
|
|
46
|
+
*/
|
|
47
|
+
constructor(config: {
|
|
48
|
+
data: () => Promise<T>;
|
|
49
|
+
schema?: ZodObject;
|
|
50
|
+
preload?: boolean;
|
|
51
|
+
});
|
|
52
|
+
/** `data$` создан (init мог ещё выполняться — см. {@link init}). */
|
|
53
|
+
inited(): boolean;
|
|
54
|
+
/** Данные загружены: `initDataCallback` завершился. */
|
|
55
|
+
private isInitComplete;
|
|
56
|
+
/** Контекст уничтожен и больше не может использоваться. */
|
|
57
|
+
isDestroyed(): boolean;
|
|
58
|
+
destroy(): void;
|
|
59
|
+
private sendContextInit;
|
|
60
|
+
authorizeClient(client: Client): void;
|
|
61
|
+
protected subscribeToDataChanges(): void;
|
|
62
|
+
/**
|
|
63
|
+
* Инициализирует контекст: создаёт `data$`, загружает начальные данные через
|
|
64
|
+
* `initDataCallback` и запускает синхронизацию с клиентами.
|
|
65
|
+
*
|
|
66
|
+
* Повторные вызовы безопасны: параллельные `init()` ждут один и тот же promise.
|
|
67
|
+
*
|
|
68
|
+
* Семантика ошибок:
|
|
69
|
+
* - `await context.init()` — reject при сбое загрузки (для `boot()`, диалогов).
|
|
70
|
+
* - `void context.init()` — reject не уходит в unhandledRejection; ошибка в `client.error$`.
|
|
71
|
+
* - `destroy()` во время async-загрузки — тихий выход, без throw (ожидаемая гонка).
|
|
72
|
+
*
|
|
73
|
+
* @returns Текущий экземпляр контекста (resolve) или reject при ошибке загрузки.
|
|
74
|
+
*/
|
|
75
|
+
init(): Promise<this>;
|
|
76
|
+
/**
|
|
77
|
+
* Возвращает значение из контекста по указанному пути.
|
|
78
|
+
*
|
|
79
|
+
* Путь может содержать плейсхолдеры, которые будут заменены актуальными значениями.
|
|
80
|
+
*
|
|
81
|
+
* @param path Строка с путём до значения.
|
|
82
|
+
* @returns Значение по заданному пути или undefined.
|
|
83
|
+
*/
|
|
84
|
+
value<K extends Paths<T>>(path: K): PathValue<T, K>;
|
|
85
|
+
setValue<K extends Paths<T>>(path: K, value: PathValue<T, K>): void;
|
|
86
|
+
/**
|
|
87
|
+
* После мутаций объекта из `data$!.getValue()` in-place без вызовов `next()`
|
|
88
|
+
* подписчики и клиенты не получают обновление. Метод публикует в поток глубокую
|
|
89
|
+
* копию текущего состояния и запускает обычную цепочку (diff → сообщения клиенту).
|
|
90
|
+
*/
|
|
91
|
+
emitAfterInPlaceMutation(): void;
|
|
92
|
+
/**
|
|
93
|
+
|
|
94
|
+
* @param path Путь до значения.
|
|
95
|
+
* @returns Плейсхолдер для использования в шаблонах и компонентах.
|
|
96
|
+
*/
|
|
97
|
+
ref<K extends Paths<T>>(path: K): ContextRef<T, K>;
|
|
98
|
+
/**
|
|
99
|
+
* Ссылка на значение в **этом** контексте по пути, который задаётся **во втором**
|
|
100
|
+
* контексте строкой и меняется во времени.
|
|
101
|
+
*
|
|
102
|
+
* В отличие от прямого чтения `other.value()` при создании ссылки, в путь записывается
|
|
103
|
+
* только плейсхолдер `@{<id контекста other>.<путь other>}` (см. `ContextRef.toString`).
|
|
104
|
+
* При каждом обращении `Context.value` подставляет актуальное значение поля `other`;
|
|
105
|
+
* это уже строка-путь относительно корня текущего контекста (например `cards.1.balance`).
|
|
106
|
+
*
|
|
107
|
+
* Типичный случай: во втором контексте хранится полный или частичный dotted-путь в данных
|
|
108
|
+
* этого контекста; после мутации того поля одна и та же ссылка `strictRef` продолжает работать.
|
|
109
|
+
*
|
|
110
|
+
* Пример: `cardsContext` с данными `{ cards: [{ balance: 100 }, { balance: 200 }] }`;
|
|
111
|
+
* во втором контексте `{ path: "cards.1.balance" }`. Вызов
|
|
112
|
+
* `cardsContext.strictRef(pathContext.ref("path"))` при чтении даёт `200`.
|
|
113
|
+
*
|
|
114
|
+
* Для суффикса к фиксированному префиксу в этом же контексте используйте
|
|
115
|
+
* `this.ref("…").strictRef(other)`.
|
|
116
|
+
*
|
|
117
|
+
* @experimental
|
|
118
|
+
*/
|
|
119
|
+
strictRef<OtherContextType extends JsonObject, OtherPathType extends Paths<OtherContextType>>(other: ContextRef<OtherContextType, OtherPathType>): ContextRef<T, PathValue<OtherContextType, OtherPathType> & Paths<T>>;
|
|
120
|
+
toJSON(): `${string}-${string}-${string}-${string}-${string}`;
|
|
121
|
+
}
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Context = void 0;
|
|
4
|
+
const index_1 = require("@matreshka/shared/messages/bff-to-client/context/index");
|
|
5
|
+
const index_2 = require("@matreshka/shared/messages/client-to-bff/context/index");
|
|
6
|
+
const fetch_from_object_1 = require("@matreshka/shared/utils/fetch-from-object");
|
|
7
|
+
const rxjs_1 = require("rxjs");
|
|
8
|
+
const v4_1 = require("zod/v4");
|
|
9
|
+
const client_context_1 = require("../client-context");
|
|
10
|
+
const deep_pick_1 = require("../utils/deep-pick");
|
|
11
|
+
const incoming_message_observer_1 = require("../utils/incoming-message-observer");
|
|
12
|
+
const objects_diff_1 = require("../utils/objects-diff");
|
|
13
|
+
const replace_context_keys_1 = require("../utils/replace-context-keys");
|
|
14
|
+
const set_object_property_1 = require("../utils/set-object-property");
|
|
15
|
+
const context_ref_1 = require("./context-ref");
|
|
16
|
+
/** Глобальный реестр контекстов: lookup по id, привязки к клиентам, учёт init. */
|
|
17
|
+
const contextRegistry = new Map();
|
|
18
|
+
function registerContext(context) {
|
|
19
|
+
contextRegistry.set(context.id, {
|
|
20
|
+
context,
|
|
21
|
+
clients: new Map(),
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
function unregisterContext(contextId) {
|
|
25
|
+
contextRegistry.delete(contextId);
|
|
26
|
+
}
|
|
27
|
+
function getContextById(contextId) {
|
|
28
|
+
return contextRegistry.get(contextId)?.context;
|
|
29
|
+
}
|
|
30
|
+
function getRegistryEntry(contextId) {
|
|
31
|
+
return contextRegistry.get(contextId);
|
|
32
|
+
}
|
|
33
|
+
function bindClient(context, client) {
|
|
34
|
+
const entry = contextRegistry.get(context.id);
|
|
35
|
+
if (!entry || entry.clients.has(client)) {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
entry.clients.set(client, { initSent: false });
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
function markInitSent(contextId, client) {
|
|
42
|
+
const binding = contextRegistry.get(contextId)?.clients.get(client);
|
|
43
|
+
if (binding) {
|
|
44
|
+
binding.initSent = true;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function isInitSent(contextId, client) {
|
|
48
|
+
return contextRegistry.get(contextId)?.clients.get(client)?.initSent ?? false;
|
|
49
|
+
}
|
|
50
|
+
function unbindClient(contextId, client) {
|
|
51
|
+
const entry = contextRegistry.get(contextId);
|
|
52
|
+
if (!entry) {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
entry.clients.delete(client);
|
|
56
|
+
return entry.clients.size === 0;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Контекст данных, связанных с клиентом.
|
|
60
|
+
*
|
|
61
|
+
* Используется для хранения и синхронизации состояния между сервером и клиентом,
|
|
62
|
+
* а также для отслеживания ошибок валидации и управления реактивными изменениями.
|
|
63
|
+
*
|
|
64
|
+
* @template T Тип структуры данных контекста.
|
|
65
|
+
*/
|
|
66
|
+
class Context {
|
|
67
|
+
assertNotDestroyed() {
|
|
68
|
+
if (this.destroyed) {
|
|
69
|
+
throw new Error(`Context ${this.id} has been destroyed`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
|
|
73
|
+
reportInitFailureToClients(error) {
|
|
74
|
+
getRegistryEntry(this.id)?.clients.forEach((_, client) => {
|
|
75
|
+
client.error$.next(error);
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Создаёт экземпляр контекста, привязанный к конкретному клиенту.
|
|
80
|
+
*
|
|
81
|
+
* Подписывается на входящие сообщения от клиента и ошибки, связанные с этим контекстом.
|
|
82
|
+
|
|
83
|
+
*/
|
|
84
|
+
constructor(config) {
|
|
85
|
+
/** Уникальный идентификатор контекста */
|
|
86
|
+
this.id = crypto.randomUUID();
|
|
87
|
+
/** Реактивное хранилище инициализации контекста */
|
|
88
|
+
this._init$ = new rxjs_1.ReplaySubject(1);
|
|
89
|
+
this.init$ = this._init$.asObservable();
|
|
90
|
+
this.initializing = false;
|
|
91
|
+
this.destroyed = false;
|
|
92
|
+
this.subscriptions = new rxjs_1.Subscription();
|
|
93
|
+
this.schema = config.schema;
|
|
94
|
+
registerContext(this);
|
|
95
|
+
this.initDataCallback = config.data;
|
|
96
|
+
this.preload = config.preload ?? false;
|
|
97
|
+
}
|
|
98
|
+
/** `data$` создан (init мог ещё выполняться — см. {@link init}). */
|
|
99
|
+
inited() {
|
|
100
|
+
return !!this.data$;
|
|
101
|
+
}
|
|
102
|
+
/** Данные загружены: `initDataCallback` завершился. */
|
|
103
|
+
isInitComplete() {
|
|
104
|
+
return !!this.data$ && !this.initializing;
|
|
105
|
+
}
|
|
106
|
+
/** Контекст уничтожен и больше не может использоваться. */
|
|
107
|
+
isDestroyed() {
|
|
108
|
+
return this.destroyed;
|
|
109
|
+
}
|
|
110
|
+
destroy() {
|
|
111
|
+
if (this.destroyed) {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
this.destroyed = true;
|
|
115
|
+
getRegistryEntry(this.id)?.clients.forEach((_, client) => {
|
|
116
|
+
client.outcomingMessage$.next(new index_1.ContextDestroyMessage(this.id));
|
|
117
|
+
});
|
|
118
|
+
this.subscriptions.unsubscribe();
|
|
119
|
+
this.dataSubscription?.unsubscribe();
|
|
120
|
+
this.dataSubscription = undefined;
|
|
121
|
+
this.data$?.complete();
|
|
122
|
+
this.data$ = undefined;
|
|
123
|
+
this.initializing = false;
|
|
124
|
+
this.initPromise = undefined;
|
|
125
|
+
this.dataChangedByClient = undefined;
|
|
126
|
+
this.initDataCallback = undefined;
|
|
127
|
+
this._init$.complete();
|
|
128
|
+
unregisterContext(this.id);
|
|
129
|
+
}
|
|
130
|
+
sendContextInit(client) {
|
|
131
|
+
if (this.destroyed || !this.data$) {
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
client.outcomingMessage$.next(new index_1.ContextInitMessage(this.id, structuredClone(this.data$.getValue())));
|
|
135
|
+
}
|
|
136
|
+
authorizeClient(client) {
|
|
137
|
+
this.assertNotDestroyed();
|
|
138
|
+
if (!bindClient(this, client)) {
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (this.preload) {
|
|
142
|
+
void this.init().then(() => {
|
|
143
|
+
if (this.destroyed) {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
this.sendContextInit(client);
|
|
147
|
+
markInitSent(this.id, client);
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
this.subscriptions.add(client.destroy$.subscribe(() => {
|
|
151
|
+
if (this.destroyed) {
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
client.outcomingMessage$.next(new index_1.ContextDestroyMessage(this.id));
|
|
155
|
+
if (unbindClient(this.id, client)) {
|
|
156
|
+
this.destroy();
|
|
157
|
+
}
|
|
158
|
+
}));
|
|
159
|
+
this.subscriptions.add(client.incomingMessage$
|
|
160
|
+
.pipe((0, rxjs_1.filter)((unsafeMessage) => unsafeMessage.scope === this.id))
|
|
161
|
+
.subscribe((0, incoming_message_observer_1.incomingMessageObserver)(client, (unsafeMessage) => {
|
|
162
|
+
if (this.destroyed) {
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (unsafeMessage instanceof index_2.ContextInitMessage) {
|
|
166
|
+
void this.init().then(() => {
|
|
167
|
+
if (this.destroyed) {
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
this.sendContextInit(client);
|
|
171
|
+
if (!isInitSent(this.id, client)) {
|
|
172
|
+
markInitSent(this.id, client);
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
if (unsafeMessage instanceof index_2.ContextValuesMessage) {
|
|
178
|
+
const payloadSchema = v4_1.z.array(v4_1.z.strictObject({ key: v4_1.z.string(), value: v4_1.z.unknown() }));
|
|
179
|
+
const changes = payloadSchema.parse(unsafeMessage.payload);
|
|
180
|
+
const data = this.data$.getValue();
|
|
181
|
+
changes.forEach((change) => {
|
|
182
|
+
if (this.schema) {
|
|
183
|
+
const keySchema = (0, deep_pick_1.zodDeepPick)(this.schema, change.key);
|
|
184
|
+
keySchema.parse(change.value);
|
|
185
|
+
}
|
|
186
|
+
// @ts-expect-error Проверка типа происходит при помощи zod, так что ошибка не актуальна
|
|
187
|
+
(0, set_object_property_1.setObjectProperty)(data, change.key, change.value);
|
|
188
|
+
});
|
|
189
|
+
this.dataChangedByClient = client;
|
|
190
|
+
this.data$.next(data);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
})));
|
|
194
|
+
}
|
|
195
|
+
subscribeToDataChanges() {
|
|
196
|
+
let prevData; // pairwise() из rxjs имеет сцефику, если в next передать измененный объект, то prev и active совпадут, поэтому лучше хранить копию самому
|
|
197
|
+
this.dataSubscription?.unsubscribe();
|
|
198
|
+
this.dataSubscription = this.data$.subscribe((data) => {
|
|
199
|
+
if (this.destroyed) {
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
// Во время init() не шлём diff (сохраняем текущую семантику: первая "реальная" установка данных не должна рассылаться как изменения).
|
|
203
|
+
if (!this.initializing && prevData) {
|
|
204
|
+
let diff;
|
|
205
|
+
getRegistryEntry(this.id)?.clients.forEach((_, client) => {
|
|
206
|
+
if (this.dataChangedByClient !== client) {
|
|
207
|
+
// Не первое присваивание
|
|
208
|
+
// Сравнение двух объектов, поиск измененных ключей
|
|
209
|
+
if (diff === undefined) {
|
|
210
|
+
diff = (0, objects_diff_1.objectsDiff)(prevData, data);
|
|
211
|
+
}
|
|
212
|
+
if (Object.keys(diff).length) {
|
|
213
|
+
// Изменения есть
|
|
214
|
+
client.outcomingMessage$.next(new index_1.ContextValuesMessage(this.id, Object.entries(diff).map(([key, value]) => ({
|
|
215
|
+
key,
|
|
216
|
+
value,
|
|
217
|
+
}))));
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
this.dataChangedByClient = undefined;
|
|
223
|
+
prevData = structuredClone(data);
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Инициализирует контекст: создаёт `data$`, загружает начальные данные через
|
|
228
|
+
* `initDataCallback` и запускает синхронизацию с клиентами.
|
|
229
|
+
*
|
|
230
|
+
* Повторные вызовы безопасны: параллельные `init()` ждут один и тот же promise.
|
|
231
|
+
*
|
|
232
|
+
* Семантика ошибок:
|
|
233
|
+
* - `await context.init()` — reject при сбое загрузки (для `boot()`, диалогов).
|
|
234
|
+
* - `void context.init()` — reject не уходит в unhandledRejection; ошибка в `client.error$`.
|
|
235
|
+
* - `destroy()` во время async-загрузки — тихий выход, без throw (ожидаемая гонка).
|
|
236
|
+
*
|
|
237
|
+
* @returns Текущий экземпляр контекста (resolve) или reject при ошибке загрузки.
|
|
238
|
+
*/
|
|
239
|
+
async init() {
|
|
240
|
+
// Контекст уже уничтожен — не бросаем, чтобы fire-and-forget init() после
|
|
241
|
+
// закрытия диалога не давал unhandledRejection.
|
|
242
|
+
if (this.destroyed) {
|
|
243
|
+
return this;
|
|
244
|
+
}
|
|
245
|
+
// Сначала ждём уже запущенный init (в т.ч. void context.init() в конструкторе диалога).
|
|
246
|
+
// Нельзя проверять inited() раньше initPromise: data$ появляется с {} до await initDataCallback().
|
|
247
|
+
if (this.initPromise)
|
|
248
|
+
return this.initPromise;
|
|
249
|
+
if (this.isInitComplete())
|
|
250
|
+
return this;
|
|
251
|
+
// Базовый promise загрузки. Отдельно от initPromise, чтобы развести:
|
|
252
|
+
// - обработку ошибок для await-вызовов;
|
|
253
|
+
// - подавление unhandledRejection для void-вызовов.
|
|
254
|
+
const loading = (async () => {
|
|
255
|
+
if (this.destroyed) {
|
|
256
|
+
return this;
|
|
257
|
+
}
|
|
258
|
+
// data$ создаём синхронно до await, чтобы не было окна data$ === undefined
|
|
259
|
+
// (например, при сериализации компонента во время init()).
|
|
260
|
+
this.initializing = true;
|
|
261
|
+
this.data$ = new rxjs_1.BehaviorSubject({});
|
|
262
|
+
this.subscribeToDataChanges();
|
|
263
|
+
const initialData = await this.initDataCallback();
|
|
264
|
+
// Диалог/страница могли закрыться, пока ждали initDataCallback — не применяем данные.
|
|
265
|
+
if (this.destroyed) {
|
|
266
|
+
return this;
|
|
267
|
+
}
|
|
268
|
+
this.data$.next(initialData);
|
|
269
|
+
this.initializing = false;
|
|
270
|
+
this._init$.next();
|
|
271
|
+
return this;
|
|
272
|
+
})();
|
|
273
|
+
// Первая «страховка»: гасим reject у loading для void context.init().
|
|
274
|
+
void loading.catch(() => { });
|
|
275
|
+
this.initPromise = loading.catch((e) => {
|
|
276
|
+
// Сбрасываем promise, чтобы следующий init() мог повторить попытку.
|
|
277
|
+
this.initPromise = undefined;
|
|
278
|
+
// destroy() во время загрузки — не считаем ошибкой.
|
|
279
|
+
if (this.destroyed) {
|
|
280
|
+
return this;
|
|
281
|
+
}
|
|
282
|
+
this.reportInitFailureToClients(e);
|
|
283
|
+
throw e;
|
|
284
|
+
});
|
|
285
|
+
// Вторая «страховка»: initPromise re-throw'ит ошибку для await context.init(),
|
|
286
|
+
// но для void-вызова reject не должен становиться unhandled.
|
|
287
|
+
void this.initPromise.catch(() => { });
|
|
288
|
+
return this.initPromise;
|
|
289
|
+
}
|
|
290
|
+
value(path) {
|
|
291
|
+
this.assertNotDestroyed();
|
|
292
|
+
return (0, fetch_from_object_1.fetchFromObject)(this.data$.getValue(), (0, replace_context_keys_1.replaceContextKeys)(path, getContextById));
|
|
293
|
+
}
|
|
294
|
+
setValue(path, value) {
|
|
295
|
+
this.assertNotDestroyed();
|
|
296
|
+
const data = this.data$.getValue();
|
|
297
|
+
(0, set_object_property_1.setObjectProperty)(data, path, value);
|
|
298
|
+
this.data$.next(data);
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* После мутаций объекта из `data$!.getValue()` in-place без вызовов `next()`
|
|
302
|
+
* подписчики и клиенты не получают обновление. Метод публикует в поток глубокую
|
|
303
|
+
* копию текущего состояния и запускает обычную цепочку (diff → сообщения клиенту).
|
|
304
|
+
*/
|
|
305
|
+
emitAfterInPlaceMutation() {
|
|
306
|
+
this.assertNotDestroyed();
|
|
307
|
+
if (!this.data$) {
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
this.data$.next(structuredClone(this.data$.getValue()));
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
|
|
314
|
+
* @param path Путь до значения.
|
|
315
|
+
* @returns Плейсхолдер для использования в шаблонах и компонентах.
|
|
316
|
+
*/
|
|
317
|
+
ref(path) {
|
|
318
|
+
this.assertNotDestroyed();
|
|
319
|
+
return new context_ref_1.ContextRef(this, path);
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Ссылка на значение в **этом** контексте по пути, который задаётся **во втором**
|
|
323
|
+
* контексте строкой и меняется во времени.
|
|
324
|
+
*
|
|
325
|
+
* В отличие от прямого чтения `other.value()` при создании ссылки, в путь записывается
|
|
326
|
+
* только плейсхолдер `@{<id контекста other>.<путь other>}` (см. `ContextRef.toString`).
|
|
327
|
+
* При каждом обращении `Context.value` подставляет актуальное значение поля `other`;
|
|
328
|
+
* это уже строка-путь относительно корня текущего контекста (например `cards.1.balance`).
|
|
329
|
+
*
|
|
330
|
+
* Типичный случай: во втором контексте хранится полный или частичный dotted-путь в данных
|
|
331
|
+
* этого контекста; после мутации того поля одна и та же ссылка `strictRef` продолжает работать.
|
|
332
|
+
*
|
|
333
|
+
* Пример: `cardsContext` с данными `{ cards: [{ balance: 100 }, { balance: 200 }] }`;
|
|
334
|
+
* во втором контексте `{ path: "cards.1.balance" }`. Вызов
|
|
335
|
+
* `cardsContext.strictRef(pathContext.ref("path"))` при чтении даёт `200`.
|
|
336
|
+
*
|
|
337
|
+
* Для суффикса к фиксированному префиксу в этом же контексте используйте
|
|
338
|
+
* `this.ref("…").strictRef(other)`.
|
|
339
|
+
*
|
|
340
|
+
* @experimental
|
|
341
|
+
*/
|
|
342
|
+
strictRef(other) {
|
|
343
|
+
this.assertNotDestroyed();
|
|
344
|
+
const path = other.toString();
|
|
345
|
+
return new context_ref_1.ContextRef(this, path);
|
|
346
|
+
}
|
|
347
|
+
toJSON() {
|
|
348
|
+
this.assertNotDestroyed();
|
|
349
|
+
this.authorizeClient((0, client_context_1.currentClient)());
|
|
350
|
+
return this.id;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
exports.Context = Context;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { EntryComponent } from "../components";
|
|
2
|
+
import type { Client } from "./client";
|
|
3
|
+
import type { ComponentInstance } from "./types/component-instance";
|
|
4
|
+
/** Instance entry-компонента, внутри сериализации дерева которого выполняется код. */
|
|
5
|
+
export declare function currentEntry(): ComponentInstance<EntryComponent>;
|
|
6
|
+
/** @internal */
|
|
7
|
+
export declare function tryCurrentEntry(): ComponentInstance<EntryComponent> | undefined;
|
|
8
|
+
/** @internal */
|
|
9
|
+
export declare function runWithEntry<T>(entry: ComponentInstance<EntryComponent>, fn: () => T): T;
|
|
10
|
+
/**
|
|
11
|
+
* Сериализация в контексте entry instance; для глобальных App-оверлеев — {@link Client.ensureAppOverlayEntry}.
|
|
12
|
+
* @internal
|
|
13
|
+
*/
|
|
14
|
+
export declare function runWithEntryContext<T>(entry: ComponentInstance<EntryComponent> | undefined, client: Client, fn: () => T): T;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.currentEntry = currentEntry;
|
|
4
|
+
exports.tryCurrentEntry = tryCurrentEntry;
|
|
5
|
+
exports.runWithEntry = runWithEntry;
|
|
6
|
+
exports.runWithEntryContext = runWithEntryContext;
|
|
7
|
+
const node_async_hooks_1 = require("node:async_hooks");
|
|
8
|
+
const entryStorage = new node_async_hooks_1.AsyncLocalStorage();
|
|
9
|
+
/** Instance entry-компонента, внутри сериализации дерева которого выполняется код. */
|
|
10
|
+
function currentEntry() {
|
|
11
|
+
const entry = entryStorage.getStore();
|
|
12
|
+
if (!entry) {
|
|
13
|
+
throw new Error("currentEntry() only within EntryComponent.serialize() stack");
|
|
14
|
+
}
|
|
15
|
+
return entry;
|
|
16
|
+
}
|
|
17
|
+
/** @internal */
|
|
18
|
+
function tryCurrentEntry() {
|
|
19
|
+
return entryStorage.getStore();
|
|
20
|
+
}
|
|
21
|
+
/** @internal */
|
|
22
|
+
function runWithEntry(entry, fn) {
|
|
23
|
+
return entryStorage.run(entry, fn);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Сериализация в контексте entry instance; для глобальных App-оверлеев — {@link Client.ensureAppOverlayEntry}.
|
|
27
|
+
* @internal
|
|
28
|
+
*/
|
|
29
|
+
function runWithEntryContext(entry, client, fn) {
|
|
30
|
+
return runWithEntry(entry ?? client.ensureAppOverlayEntry(), fn);
|
|
31
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Subject } from "rxjs";
|
|
2
|
+
import type { ClientSettingsResolver, Matreshka } from "./matreshka";
|
|
3
|
+
export type ConnectGatewayInput = {
|
|
4
|
+
url: string;
|
|
5
|
+
token: string;
|
|
6
|
+
resolveClientSettings: ClientSettingsResolver;
|
|
7
|
+
};
|
|
8
|
+
/** WebSocket-подключение BFF к gateway. */
|
|
9
|
+
export declare class GatewayConnection {
|
|
10
|
+
private readonly matreshka;
|
|
11
|
+
private readonly socket;
|
|
12
|
+
private readonly sessions;
|
|
13
|
+
private readonly subscriptions;
|
|
14
|
+
private readonly resolveClientSettings;
|
|
15
|
+
private closed;
|
|
16
|
+
readonly connected$: Subject<void>;
|
|
17
|
+
readonly disconnected$: Subject<void>;
|
|
18
|
+
readonly error$: Subject<unknown>;
|
|
19
|
+
constructor(matreshka: Matreshka, input: ConnectGatewayInput);
|
|
20
|
+
disconnect(): void;
|
|
21
|
+
private bindSocketEvents;
|
|
22
|
+
private handleGatewayMessage;
|
|
23
|
+
private openSession;
|
|
24
|
+
private closeSession;
|
|
25
|
+
private closeAllSessions;
|
|
26
|
+
private sendToGateway;
|
|
27
|
+
private unsubscribeAll;
|
|
28
|
+
}
|
|
29
|
+
export declare function buildGatewayWebSocketUrl(serverUrl: string, token: string): string;
|