@matreshka/bff 0.29.0 → 0.30.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/dist/components/entry-component.d.ts +14 -2
- package/dist/components/entry-component.js +24 -3
- package/dist/components/item-list/list-from-ref-context.d.ts +2 -2
- package/dist/components/page.d.ts +5 -0
- package/dist/components/page.js +6 -0
- package/dist/core/actions/set-context.d.ts +2 -3
- package/dist/core/context/context-ref.d.ts +2 -3
- package/dist/core/context/context.d.ts +22 -15
- package/dist/core/context/context.js +7 -5
- package/package.json +1 -1
|
@@ -26,15 +26,22 @@ type DefaultInitConfigType = EntryComponentInitConfig<EntryComponent>;
|
|
|
26
26
|
export declare abstract class EntryComponent<InitConfigType extends EntryComponentInitConfig<any> = DefaultInitConfigType, PropertiesType extends EntryComponentProperties = EntryComponentProperties, SerializedConfigType extends EntryServerComponentConfig = EntryServerComponentConfig> extends Component<InitConfigType, PropertiesType> {
|
|
27
27
|
private readonly registeredTools;
|
|
28
28
|
private declaredToolsRegistered;
|
|
29
|
+
private entryLifecycleInteractionsRegistered;
|
|
29
30
|
constructor(config: InitConfigType);
|
|
31
|
+
/**
|
|
32
|
+
* `onEnter` / `onLeave` читаются при первом создании entry-инстанса,
|
|
33
|
+
* уже после конструктора наследника — поля и `this.options` доступны.
|
|
34
|
+
* Дополнительные interaction для того же момента — в {@link registerEntryLifecycleInteractionsExtra}.
|
|
35
|
+
*/
|
|
36
|
+
protected registerEntryLifecycleInteractions(): void;
|
|
37
|
+
/** Хук для наследников: один раз сразу после enter/leave (см. {@link registerEntryLifecycleInteractions}). */
|
|
38
|
+
protected registerEntryLifecycleInteractionsExtra(): void;
|
|
30
39
|
/**
|
|
31
40
|
* Показ entry. По умолчанию — `onEnter` конструктора.
|
|
32
|
-
* Читается в конструкторе, до полей наследника.
|
|
33
41
|
*/
|
|
34
42
|
protected onEnter(): InitConfigType["onEnter"];
|
|
35
43
|
/**
|
|
36
44
|
* Начало ухода entry. По умолчанию — `onLeave` конструктора.
|
|
37
|
-
* Читается в конструкторе, до полей наследника.
|
|
38
45
|
*/
|
|
39
46
|
protected onLeave(): InitConfigType["onLeave"];
|
|
40
47
|
/**
|
|
@@ -63,6 +70,11 @@ export declare abstract class EntryComponent<InitConfigType extends EntryCompone
|
|
|
63
70
|
protected subscribeClientEvents(client: Client): void;
|
|
64
71
|
/** Контекст сериализации дочерних компонентов без полной serialize entry. @internal */
|
|
65
72
|
beginSerializationContext(): ComponentInstance<this>;
|
|
73
|
+
/**
|
|
74
|
+
* Явное создание instance entry (редко для Page/Dialog; для App-оверлеев см.
|
|
75
|
+
* {@link beginSerializationContext}). Обработчики enter/leave регистрируются здесь же.
|
|
76
|
+
*/
|
|
77
|
+
createInstance(): ComponentInstance<this>;
|
|
66
78
|
protected createSelfEntry(): ComponentInstance<this>;
|
|
67
79
|
protected emitInteraction(type: string, payload: unknown, instance: ComponentInstance<this>, handlers: number[]): void;
|
|
68
80
|
}
|
|
@@ -18,20 +18,32 @@ class EntryComponent extends component_1.Component {
|
|
|
18
18
|
super(config);
|
|
19
19
|
this.registeredTools = [];
|
|
20
20
|
this.declaredToolsRegistered = false;
|
|
21
|
-
|
|
21
|
+
this.entryLifecycleInteractionsRegistered = false;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* `onEnter` / `onLeave` читаются при первом создании entry-инстанса,
|
|
25
|
+
* уже после конструктора наследника — поля и `this.options` доступны.
|
|
26
|
+
* Дополнительные interaction для того же момента — в {@link registerEntryLifecycleInteractionsExtra}.
|
|
27
|
+
*/
|
|
28
|
+
registerEntryLifecycleInteractions() {
|
|
29
|
+
if (this.entryLifecycleInteractionsRegistered) {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
this.entryLifecycleInteractionsRegistered = true;
|
|
22
33
|
this.bindDeclaredInteraction("enter", this.onEnter());
|
|
23
34
|
this.bindDeclaredInteraction("leave", this.onLeave());
|
|
35
|
+
this.registerEntryLifecycleInteractionsExtra();
|
|
24
36
|
}
|
|
37
|
+
/** Хук для наследников: один раз сразу после enter/leave (см. {@link registerEntryLifecycleInteractions}). */
|
|
38
|
+
registerEntryLifecycleInteractionsExtra() { }
|
|
25
39
|
/**
|
|
26
40
|
* Показ entry. По умолчанию — `onEnter` конструктора.
|
|
27
|
-
* Читается в конструкторе, до полей наследника.
|
|
28
41
|
*/
|
|
29
42
|
onEnter() {
|
|
30
43
|
return this.config.onEnter;
|
|
31
44
|
}
|
|
32
45
|
/**
|
|
33
46
|
* Начало ухода entry. По умолчанию — `onLeave` конструктора.
|
|
34
|
-
* Читается в конструкторе, до полей наследника.
|
|
35
47
|
*/
|
|
36
48
|
onLeave() {
|
|
37
49
|
return this.config.onLeave;
|
|
@@ -145,7 +157,16 @@ class EntryComponent extends component_1.Component {
|
|
|
145
157
|
beginSerializationContext() {
|
|
146
158
|
return this.createSelfEntry();
|
|
147
159
|
}
|
|
160
|
+
/**
|
|
161
|
+
* Явное создание instance entry (редко для Page/Dialog; для App-оверлеев см.
|
|
162
|
+
* {@link beginSerializationContext}). Обработчики enter/leave регистрируются здесь же.
|
|
163
|
+
*/
|
|
164
|
+
createInstance() {
|
|
165
|
+
this.registerEntryLifecycleInteractions();
|
|
166
|
+
return super.createInstance();
|
|
167
|
+
}
|
|
148
168
|
createSelfEntry() {
|
|
169
|
+
this.registerEntryLifecycleInteractions();
|
|
149
170
|
const instance = super.createSelfEntry();
|
|
150
171
|
const client = (0, client_context_1.currentClient)();
|
|
151
172
|
// Подписка на leave и прочие interaction до commitSerialization instance.entry.
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { Context, type
|
|
1
|
+
import { Context, type JsonObject } from "../../core";
|
|
2
2
|
type ItemListIndexContext = Record<string, {
|
|
3
3
|
index: `${number}`;
|
|
4
4
|
}>;
|
|
5
5
|
/** Контекст индексов элементов ItemList; данные не загружаются снаружи. */
|
|
6
|
-
export declare class ItemListIndexStore<T extends JsonObject = ItemListIndexContext> extends Context<T
|
|
6
|
+
export declare class ItemListIndexStore<T extends JsonObject = ItemListIndexContext> extends Context<T> {
|
|
7
7
|
/**
|
|
8
8
|
* Синхронно поднимает хранилище до async {@link init}, чтобы `replace` в serialize
|
|
9
9
|
* не перезаписывался пустым `{}` из `initDataCallback`.
|
|
@@ -28,6 +28,11 @@ type DefaultInitConfigType = PageInitConfig<Page>;
|
|
|
28
28
|
*/
|
|
29
29
|
export declare abstract class Page<InitConfigType extends PageInitConfig<any> = DefaultInitConfigType, PropertiesType extends PageProperties = PageProperties> extends EntryComponent<InitConfigType, PropertiesType, PageConfig> implements Pageable {
|
|
30
30
|
constructor();
|
|
31
|
+
/**
|
|
32
|
+
* Обработчик прокрутки регистрируется вместе с enter/leave — после конструктора наследника,
|
|
33
|
+
* когда доступны поля подкласса (см. {@link EntryComponent.registerEntryLifecycleInteractions}).
|
|
34
|
+
*/
|
|
35
|
+
protected registerEntryLifecycleInteractionsExtra(): void;
|
|
31
36
|
/**
|
|
32
37
|
* Возвращает HTTP-статус страницы.
|
|
33
38
|
* @returns Статус страницы (по умолчанию 200 OK).
|
package/dist/components/page.js
CHANGED
|
@@ -14,6 +14,12 @@ class Page extends entry_component_1.EntryComponent {
|
|
|
14
14
|
constructor() {
|
|
15
15
|
// @ts-expect-error Page задаёт content в boot(), а не через конфиг конструктора Component.
|
|
16
16
|
super({});
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Обработчик прокрутки регистрируется вместе с enter/leave — после конструктора наследника,
|
|
20
|
+
* когда доступны поля подкласса (см. {@link EntryComponent.registerEntryLifecycleInteractions}).
|
|
21
|
+
*/
|
|
22
|
+
registerEntryLifecycleInteractionsExtra() {
|
|
17
23
|
this.bindDeclaredInteraction("scroll", this.onScroll());
|
|
18
24
|
}
|
|
19
25
|
/**
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { JsonObject } from "@matreshka/client-bff-protocol/types/json";
|
|
2
|
-
import { z } from "zod";
|
|
3
2
|
import { Context, ContextPathPatch } from "../context/context";
|
|
4
3
|
import { ContextValueOrRef } from "../types/context-value-ref";
|
|
5
4
|
import { ActionConfig } from "./action";
|
|
@@ -13,9 +12,9 @@ export type LocalContextPathPatch<T extends JsonObject> = Partial<{
|
|
|
13
12
|
export declare class SetContext<T extends JsonObject> extends LocalAction {
|
|
14
13
|
private readonly context;
|
|
15
14
|
private readonly patch;
|
|
16
|
-
constructor(context: Context<T
|
|
15
|
+
constructor(context: Context<T>, patch: LocalContextPathPatch<T>, config?: ActionConfig);
|
|
17
16
|
class(): string;
|
|
18
17
|
payload(): object;
|
|
19
18
|
}
|
|
20
19
|
/** @internal */
|
|
21
|
-
export declare function createSetContext<T extends JsonObject>(context: Context<T
|
|
20
|
+
export declare function createSetContext<T extends JsonObject>(context: Context<T>, patch: LocalContextPathPatch<T>, config?: ActionConfig): SetContext<T>;
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { JsonObject } from "@matreshka/client-bff-protocol/types/json";
|
|
2
2
|
import { Observable } from "rxjs";
|
|
3
3
|
import { Paths, PathValue } from "ts-essentials";
|
|
4
|
-
import { z } from "zod";
|
|
5
4
|
import { ActionConfig } from "../actions/action";
|
|
6
5
|
import { DecContextValue } from "../actions/dec-context-value";
|
|
7
6
|
import { IncContextValue } from "../actions/inc-context-value";
|
|
@@ -26,11 +25,11 @@ export type ContextRefValue<R extends ContextRef> = R extends {
|
|
|
26
25
|
readonly __valueType?: infer ValueType;
|
|
27
26
|
} ? Exclude<ValueType, undefined> : R extends ContextRef<infer ContextType, infer PathType> ? PathValue<ContextType, PathType> : never;
|
|
28
27
|
export declare class ContextRef<ContextType extends JsonObject = JsonObject, PathType extends string = string> {
|
|
29
|
-
readonly context: Context<ContextType
|
|
28
|
+
readonly context: Context<ContextType>;
|
|
30
29
|
readonly path: PathType;
|
|
31
30
|
/** Локальные (client-only) действия по этому ref. */
|
|
32
31
|
readonly local: ContextRefLocalActions<ContextType, PathType>;
|
|
33
|
-
constructor(context: Context<ContextType
|
|
32
|
+
constructor(context: Context<ContextType>, path: PathType);
|
|
34
33
|
/**
|
|
35
34
|
* Продолжение пути в рамках того же контекста.
|
|
36
35
|
* Строго типизировано: K должен быть путём внутри значения по текущему PathType.
|
|
@@ -59,61 +59,68 @@ type SomeSchemaCompatibleBranchOk<T, Input extends JsonObject> = T extends JsonO
|
|
|
59
59
|
*/
|
|
60
60
|
type SchemaCompatible<T, Input> = Input extends JsonObject ? SomeSchemaCompatibleBranchOk<T, Input> extends true ? never : true : never;
|
|
61
61
|
/**
|
|
62
|
-
* Zod-схема для {@link
|
|
62
|
+
* Zod-схема для {@link createContext}: без лишних ключей во {@link z.input} и {@link z.output}
|
|
63
63
|
* ({@link ExtraSchemaKeys}, union по веткам); {@link z.output} совместим с `T`
|
|
64
64
|
* ({@link SchemaCompatible}, вложенные подмножества). В контекст попадает output после `parse()`.
|
|
65
65
|
*/
|
|
66
66
|
export type ContextSchema<T extends JsonObject, S extends z.ZodObject> = [
|
|
67
67
|
S
|
|
68
68
|
] extends [ContextClientUpdatesForbiddenSchema] ? S : ExtraSchemaKeys<T, z.input<S>> extends never ? ExtraSchemaKeys<T, z.output<S>> extends never ? SchemaCompatible<T, z.output<S>> extends never ? S : never : never : never;
|
|
69
|
-
/** Конфиг {@link
|
|
69
|
+
/** Конфиг {@link createContext} без клиентской Zod-схемы. */
|
|
70
70
|
export type ContextInitWithoutSchema<T extends JsonObject> = {
|
|
71
71
|
data: () => Promise<T>;
|
|
72
72
|
schema?: undefined;
|
|
73
73
|
preload?: boolean;
|
|
74
74
|
persistent?: boolean;
|
|
75
75
|
};
|
|
76
|
-
/** Конфиг {@link
|
|
76
|
+
/** Конфиг {@link createContext} с Zod-схемой клиентских изменений. */
|
|
77
77
|
export type ContextInitWithSchema<T extends JsonObject, S extends z.ZodObject> = {
|
|
78
78
|
data: () => Promise<T>;
|
|
79
79
|
schema: ContextSchema<T, S>;
|
|
80
80
|
preload?: boolean;
|
|
81
81
|
persistent?: boolean;
|
|
82
82
|
};
|
|
83
|
-
/** Конфигурация {@link
|
|
83
|
+
/** Конфигурация {@link createContext} (единственный аргумент). */
|
|
84
84
|
export type ContextInitConfig<T extends JsonObject, S extends z.ZodObject | undefined = undefined> = S extends z.ZodObject ? ContextInitWithSchema<T, S> : ContextInitWithoutSchema<T>;
|
|
85
|
-
/** Минимальная форма аргумента {@link
|
|
85
|
+
/** Минимальная форма аргумента {@link createContext}. */
|
|
86
86
|
type ContextInitShape = {
|
|
87
87
|
data: () => Promise<JsonObject>;
|
|
88
88
|
schema?: z.ZodObject;
|
|
89
89
|
preload?: boolean;
|
|
90
90
|
persistent?: boolean;
|
|
91
91
|
};
|
|
92
|
+
type ContextRuntimeInit<T extends JsonObject> = {
|
|
93
|
+
data: () => Promise<T>;
|
|
94
|
+
schema?: z.ZodObject;
|
|
95
|
+
preload?: boolean;
|
|
96
|
+
persistent?: boolean;
|
|
97
|
+
};
|
|
92
98
|
/** Тип данных `T` из поля `data` конфига. */
|
|
93
99
|
export type ContextDataFromInit<C extends ContextInitShape> = Awaited<ReturnType<C["data"]>>;
|
|
94
100
|
/** Zod-схема из поля `schema` конфига (или `undefined`). */
|
|
95
101
|
export type ContextSchemaFromInit<C extends ContextInitShape> = C extends {
|
|
96
102
|
schema: z.ZodObject;
|
|
97
103
|
} ? C["schema"] : undefined;
|
|
98
|
-
/** Экземпляр {@link Context} по форме конфига {@link
|
|
99
|
-
export type ContextFromInit<C extends ContextInitShape> =
|
|
104
|
+
/** Экземпляр {@link Context} по форме конфига {@link createContext}. */
|
|
105
|
+
export type ContextFromInit<C extends ContextInitShape> = Context<ContextDataFromInit<C>>;
|
|
100
106
|
type ValidatedContextInit<C extends ContextInitShape> = ContextInitConfig<ContextDataFromInit<C>, ContextSchemaFromInit<C> extends z.ZodObject ? ContextSchemaFromInit<C> : undefined>;
|
|
101
|
-
type StoredContext = Context<JsonObject, z.ZodObject | undefined>;
|
|
102
107
|
/**
|
|
103
108
|
* Контекст данных, связанных с клиентом.
|
|
104
109
|
*
|
|
105
|
-
* @internal Создавайте экземпляры через {@link
|
|
110
|
+
* @internal Создавайте экземпляры через {@link createContext}.
|
|
106
111
|
*
|
|
107
112
|
* @template T Тип структуры данных контекста.
|
|
108
|
-
*
|
|
113
|
+
*
|
|
114
|
+
* Zod-схема клиентских изменений задаётся в {@link createContext} через поле `schema`,
|
|
115
|
+
* а не вторым type-параметром: так проще согласовать runtime-схему и тип данных.
|
|
109
116
|
*/
|
|
110
|
-
export declare class Context<T extends JsonObject
|
|
117
|
+
export declare class Context<T extends JsonObject> {
|
|
111
118
|
/** Уникальный идентификатор контекста */
|
|
112
119
|
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
113
120
|
/** Реактивное хранилище данных контекста. */
|
|
114
121
|
protected data$?: BehaviorSubject<T>;
|
|
115
122
|
/** Схема валидации данных контекста */
|
|
116
|
-
readonly schema?:
|
|
123
|
+
readonly schema?: z.ZodObject;
|
|
117
124
|
/** Флаг, указывающий, что контекст должен быть инициализирован при авторизации клиента */
|
|
118
125
|
readonly preload: boolean;
|
|
119
126
|
/**
|
|
@@ -165,7 +172,7 @@ export declare class Context<T extends JsonObject, S extends z.ZodObject | undef
|
|
|
165
172
|
* Подписывается на входящие сообщения от клиента и ошибки, связанные с этим контекстом.
|
|
166
173
|
|
|
167
174
|
*/
|
|
168
|
-
constructor(config:
|
|
175
|
+
constructor(config: ContextRuntimeInit<T>);
|
|
169
176
|
/** `data$` создан (init мог ещё выполняться — см. {@link init}). */
|
|
170
177
|
inited(): boolean;
|
|
171
178
|
/** Данные загружены: `initDataCallback` завершился. */
|
|
@@ -275,7 +282,7 @@ export declare class Context<T extends JsonObject, S extends z.ZodObject | undef
|
|
|
275
282
|
toJSON(): `${string}-${string}-${string}-${string}-${string}`;
|
|
276
283
|
}
|
|
277
284
|
/** Любой зарегистрированный контекст (с Zod-схемой или без). */
|
|
278
|
-
export type AnyContext =
|
|
285
|
+
export type AnyContext = Context<any>;
|
|
279
286
|
/**
|
|
280
287
|
* Создаёт контекст данных BFF: хранилище состояния с синхронизацией клиент ↔ сервер.
|
|
281
288
|
*
|
|
@@ -285,4 +292,4 @@ export type AnyContext = StoredContext;
|
|
|
285
292
|
* Если в начальном `data` нет части полей (например опциональных), укажите тип на колбэке:
|
|
286
293
|
* `data: async (): Promise<MyT> => ({ … })`.
|
|
287
294
|
*/
|
|
288
|
-
export declare function
|
|
295
|
+
export declare function createContext<C extends ContextInitShape>(config: C & ValidatedContextInit<C>): ContextFromInit<C>;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.Context = exports.contextClientUpdatesForbiddenSchema = void 0;
|
|
4
|
-
exports.
|
|
4
|
+
exports.createContext = createContext;
|
|
5
5
|
const index_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/context/index");
|
|
6
6
|
const index_2 = require("@matreshka/client-bff-protocol/messages/client-to-bff/context/index");
|
|
7
7
|
const targeted_message_1 = require("@matreshka/client-bff-protocol/messages/targeted-message");
|
|
@@ -78,10 +78,12 @@ function isClientBound(contextId, client) {
|
|
|
78
78
|
/**
|
|
79
79
|
* Контекст данных, связанных с клиентом.
|
|
80
80
|
*
|
|
81
|
-
* @internal Создавайте экземпляры через {@link
|
|
81
|
+
* @internal Создавайте экземпляры через {@link createContext}.
|
|
82
82
|
*
|
|
83
83
|
* @template T Тип структуры данных контекста.
|
|
84
|
-
*
|
|
84
|
+
*
|
|
85
|
+
* Zod-схема клиентских изменений задаётся в {@link createContext} через поле `schema`,
|
|
86
|
+
* а не вторым type-параметром: так проще согласовать runtime-схему и тип данных.
|
|
85
87
|
*/
|
|
86
88
|
class Context {
|
|
87
89
|
assertNotDestroyed() {
|
|
@@ -181,7 +183,7 @@ class Context {
|
|
|
181
183
|
this.skipNextDataSync = false;
|
|
182
184
|
/** Очередь входящих targeted-сообщений всех клиентов (последовательная обработка). */
|
|
183
185
|
this.incomingClientMessages$ = new rxjs_1.Subject();
|
|
184
|
-
this.schema =
|
|
186
|
+
this.schema = config.schema;
|
|
185
187
|
if (this.schema) {
|
|
186
188
|
(0, assert_client_update_schema_1.assertClientUpdateSchemaSupported)(this.schema);
|
|
187
189
|
}
|
|
@@ -580,6 +582,6 @@ exports.Context = Context;
|
|
|
580
582
|
* Если в начальном `data` нет части полей (например опциональных), укажите тип на колбэке:
|
|
581
583
|
* `data: async (): Promise<MyT> => ({ … })`.
|
|
582
584
|
*/
|
|
583
|
-
function
|
|
585
|
+
function createContext(config) {
|
|
584
586
|
return new Context(config);
|
|
585
587
|
}
|
package/package.json
CHANGED