@matreshka/bff 0.28.1 → 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.
@@ -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
- // До полей наследника. В отложенном обработчике this уже собран.
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,7 +1,7 @@
1
1
  import { ServerComponentClass } from "@matreshka/client-bff-protocol/enums/server-component-class";
2
2
  import type { ForEachConfig } from "@matreshka/client-bff-protocol/types/for-each-config";
3
3
  import { Paths, PathValue } from "ts-essentials";
4
- import { AnyContext, ComponentInstance, ComponentTreeNode, Context, ContextRef, ContextRefValue, JsonObject, StandaloneComponent } from "../core";
4
+ import { ComponentInstance, ComponentTreeNode, Context, ContextRef, ContextRefValue, JsonObject, StandaloneComponent } from "../core";
5
5
  import { Component, ComponentInitConfig, ComponentProperties } from "./component";
6
6
  type ForEachArrayValue = readonly unknown[] | unknown[];
7
7
  type ForEachItemArray<RefType extends ContextRef<any, any>> = Extract<ContextRefValue<RefType>, ForEachArrayValue>;
@@ -36,7 +36,7 @@ export type ForEachGeneratorProperties<RefType extends ContextRef<any, any>, Com
36
36
  */
37
37
  export type ForEachProperties = {
38
38
  ref: ContextRef;
39
- componentContext: AnyContext;
39
+ componentContext: Context<any>;
40
40
  components?: (ComponentTreeNode | ComponentTreeNode[])[];
41
41
  divider?: ComponentTreeNode[];
42
42
  } & ComponentProperties;
@@ -46,7 +46,7 @@ class ForEachContext extends core_1.Context {
46
46
  super({
47
47
  data: async () => ({}),
48
48
  preload: preload,
49
- schema: core_1.forbiddenUpdatesSchema, // Запрет изменения из внешних источников
49
+ schema: core_1.contextClientUpdatesForbiddenSchema, // Запрет изменения из внешних источников
50
50
  });
51
51
  }
52
52
  }
@@ -1,9 +1,9 @@
1
- import { Context, type ForbiddenUpdatesSchema, type JsonObject } from "../../core";
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, ForbiddenUpdatesSchema> {
6
+ export declare class ItemListIndexStore<T extends JsonObject = ItemListIndexContext> extends Context<T> {
7
7
  /**
8
8
  * Синхронно поднимает хранилище до async {@link init}, чтобы `replace` в serialize
9
9
  * не перезаписывался пустым `{}` из `initDataCallback`.
@@ -21,7 +21,7 @@ class ItemListIndexStore extends core_1.Context {
21
21
  super({
22
22
  data: async () => ({}),
23
23
  preload,
24
- schema: core_1.forbiddenUpdatesSchema,
24
+ schema: core_1.contextClientUpdatesForbiddenSchema,
25
25
  });
26
26
  }
27
27
  }
@@ -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).
@@ -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, z.ZodObject | undefined>, patch: LocalContextPathPatch<T>, config?: ActionConfig);
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, z.ZodObject | undefined>, patch: LocalContextPathPatch<T>, config?: ActionConfig): SetContext<T>;
20
+ export declare function createSetContext<T extends JsonObject>(context: Context<T>, patch: LocalContextPathPatch<T>, config?: ActionConfig): SetContext<T>;
@@ -0,0 +1,6 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Клиентские dotted-patch проходят {@link zodDeepPick} только до leaf-поля.
4
+ * Object-level pipe (transform) и checks (refine) на вложенных объектах не поддерживаются.
5
+ */
6
+ export declare function assertClientUpdateSchemaSupported(schema: z.ZodObject, path?: string): void;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertClientUpdateSchemaSupported = assertClientUpdateSchemaSupported;
4
+ const zod_1 = require("zod");
5
+ function unwrapOptionalNullable(schema) {
6
+ let current = schema;
7
+ while (current instanceof zod_1.z.ZodOptional || current instanceof zod_1.z.ZodNullable) {
8
+ current = current.unwrap();
9
+ }
10
+ return current;
11
+ }
12
+ function formatPath(path) {
13
+ return path || "(root)";
14
+ }
15
+ /**
16
+ * Клиентские dotted-patch проходят {@link zodDeepPick} только до leaf-поля.
17
+ * Object-level pipe (transform) и checks (refine) на вложенных объектах не поддерживаются.
18
+ */
19
+ function assertClientUpdateSchemaSupported(schema, path = "") {
20
+ for (const [key, fieldSchema] of Object.entries(schema.shape)) {
21
+ const fieldPath = path ? `${path}.${key}` : key;
22
+ assertClientUpdateFieldSupported(fieldSchema, fieldPath);
23
+ }
24
+ }
25
+ function assertClientUpdateFieldSupported(schema, path) {
26
+ const unwrapped = unwrapOptionalNullable(schema);
27
+ if (unwrapped instanceof zod_1.z.ZodPipe) {
28
+ const inner = unwrapped._def.in;
29
+ if (inner instanceof zod_1.z.ZodObject) {
30
+ throw new Error(`Context validation schema: object-level transform at "${formatPath(path)}" is not supported for dotted-path client updates. Use leaf-level transforms only.`);
31
+ }
32
+ return;
33
+ }
34
+ if (unwrapped instanceof zod_1.z.ZodObject) {
35
+ const checks = unwrapped._def.checks;
36
+ if (checks && checks.length > 0) {
37
+ throw new Error(`Context validation schema: object-level refine at "${formatPath(path)}" is not supported for dotted-path client updates. Use leaf-level refinements only.`);
38
+ }
39
+ assertClientUpdateSchemaSupported(unwrapped, path);
40
+ return;
41
+ }
42
+ if (unwrapped instanceof zod_1.z.ZodArray) {
43
+ assertClientUpdateFieldSupported(unwrapped.element, `${path}[]`);
44
+ }
45
+ }
@@ -8,7 +8,7 @@ import { SetContext } from "../actions/set-context";
8
8
  import { ToggleContextValue } from "../actions/toggle-context-value";
9
9
  import type { ContextUpdateDelivery } from "../types/context-update-delivery";
10
10
  import { ContextValueOrRef } from "../types/context-value-ref";
11
- import { AnyContext } from "./context";
11
+ import { Context } from "./context";
12
12
  type ContextRefLocalSet<ContextType extends JsonObject, PathType extends string> = {
13
13
  set: (value: ContextValueOrRef<PathValue<ContextType, PathType>>, config?: ActionConfig) => SetContext<ContextType>;
14
14
  };
@@ -25,11 +25,11 @@ export type ContextRefValue<R extends ContextRef> = R extends {
25
25
  readonly __valueType?: infer ValueType;
26
26
  } ? Exclude<ValueType, undefined> : R extends ContextRef<infer ContextType, infer PathType> ? PathValue<ContextType, PathType> : never;
27
27
  export declare class ContextRef<ContextType extends JsonObject = JsonObject, PathType extends string = string> {
28
- readonly context: AnyContext;
28
+ readonly context: Context<ContextType>;
29
29
  readonly path: PathType;
30
30
  /** Локальные (client-only) действия по этому ref. */
31
31
  readonly local: ContextRefLocalActions<ContextType, PathType>;
32
- constructor(context: AnyContext, path: PathType);
32
+ constructor(context: Context<ContextType>, path: PathType);
33
33
  /**
34
34
  * Продолжение пути в рамках того же контекста.
35
35
  * Строго типизировано: K должен быть путём внутри значения по текущему PathType.
@@ -17,52 +17,110 @@ export type ContextPathPatch<T extends JsonObject> = Partial<{
17
17
  * Пустая strict-схема: клиент не может менять данные контекста через `context-values`.
18
18
  * Используется во внутренних контекстах (ForEach, ItemList).
19
19
  */
20
- export type ForbiddenUpdatesSchema = z.ZodObject<Record<string, never>, z.core.$strict> & {
21
- readonly __forbiddenUpdatesSchema?: unique symbol;
20
+ export type ContextClientUpdatesForbiddenSchema = z.ZodObject<Record<string, never>, z.core.$strict> & {
21
+ readonly __contextClientUpdatesForbidden?: unique symbol;
22
22
  };
23
- /** @see ForbiddenUpdatesSchema */
24
- export declare const forbiddenUpdatesSchema: ForbiddenUpdatesSchema;
23
+ /** @see ContextClientUpdatesForbiddenSchema */
24
+ export declare const contextClientUpdatesForbiddenSchema: ContextClientUpdatesForbiddenSchema;
25
+ type StripNullish<T> = Exclude<T, null | undefined>;
26
+ type ArrayElement<T> = T extends readonly (infer E)[] ? E : never;
27
+ /** `true`, если output допускает null/undefined как значение, а поле `T` — нет. */
28
+ type NullishValueMismatch<TField, IField> = (null extends IField ? (null extends TField ? never : true) : never) | (undefined extends IField ? undefined extends TField ? never : true : never);
29
+ type FieldExtraSchemaKeysOne<TField, IField> = [StripNullish<IField>] extends [
30
+ JsonObject
31
+ ] ? [StripNullish<TField>] extends [JsonObject] ? ExtraSchemaKeys<StripNullish<TField>, StripNullish<IField>> : never : [StripNullish<IField>] extends [readonly unknown[]] ? [StripNullish<TField>] extends [readonly unknown[]] ? ExtraSchemaKeys<ArrayElement<StripNullish<TField>>, ArrayElement<StripNullish<IField>>> : never : never;
32
+ /** Лишние ключи внутри поля (union, optional/nullable, массивы объектов). */
33
+ type FieldExtraSchemaKeys<TField, IField> = IField extends any ? FieldExtraSchemaKeysOne<TField, IField> : never;
34
+ /** Лишние ключи для одной пары object-веток (коррелированные поля). `true` — есть лишние ключи. */
35
+ type ExtraSchemaKeysObjectExact<T extends JsonObject, Input extends JsonObject> = Exclude<keyof Input, keyof T> extends never ? {
36
+ [K in keyof Input & keyof T]: FieldExtraSchemaKeys<T[K], Input[K]>;
37
+ }[keyof Input & keyof T] extends never ? never : true : true;
38
+ /** Есть ветка `T`, для которой `Input` не содержит лишних ключей. */
39
+ type SomeExtraSchemaKeysBranchOk<T, Input extends JsonObject> = T extends JsonObject ? ExtraSchemaKeysObjectExact<T, Input> extends never ? true : never : never;
25
40
  /**
26
- * Zod-схема для {@link Context}: описывает подмножество полей `T` без лишних ключей;
27
- * типы полей согласованы с {@link z.input} схемы и `Partial<T>`.
41
+ * Лишние ключи в shape схемы относительно `T` (рекурсивно).
42
+ * Union в `Input` и `T` проверяется по отдельным веткам. `true` — есть лишние ключи.
43
+ */
44
+ type ExtraSchemaKeys<T, Input> = Input extends JsonObject ? SomeExtraSchemaKeysBranchOk<T, Input> extends true ? never : true : never;
45
+ type FieldSchemaCompatibleOne<TField, IField> = NullishValueMismatch<TField, IField> extends never ? FieldSchemaCompatibleShape<TField, IField> : true;
46
+ type FieldSchemaCompatibleShape<TField, IField> = [
47
+ StripNullish<IField>
48
+ ] extends [JsonObject] ? [StripNullish<TField>] extends [JsonObject] ? SchemaCompatible<StripNullish<TField>, StripNullish<IField>> : true : [StripNullish<IField>] extends [readonly unknown[]] ? [StripNullish<TField>] extends [readonly unknown[]] ? FieldSchemaCompatible<ArrayElement<StripNullish<TField>>, ArrayElement<StripNullish<IField>>> : true : [StripNullish<IField>] extends [StripNullish<TField>] ? never : true;
49
+ /** Совместимость типа поля с полем контекста (union на входе — по веткам). */
50
+ type FieldSchemaCompatible<TField, IField> = IField extends any ? FieldSchemaCompatibleOne<TField, IField> : never;
51
+ /** Совместимость для одной пары object-веток. `true` — несовместимость. */
52
+ type SchemaCompatibleObjectExact<T extends JsonObject, Input extends JsonObject> = Exclude<keyof Input, keyof T> extends never ? {
53
+ [K in keyof Input & keyof T]: FieldSchemaCompatible<T[K], Input[K]>;
54
+ }[keyof Input & keyof T] extends never ? never : true : true;
55
+ type SomeSchemaCompatibleBranchOk<T, Input extends JsonObject> = T extends JsonObject ? SchemaCompatibleObjectExact<T, Input> extends never ? true : never : never;
56
+ /**
57
+ * Типы полей shape схемы совместимы с `T` (рекурсивно; для клиентской схемы — {@link z.output}).
58
+ * Подмножество ключей на любой глубине; union — по веткам. `true` — несовместимость.
59
+ */
60
+ type SchemaCompatible<T, Input> = Input extends JsonObject ? SomeSchemaCompatibleBranchOk<T, Input> extends true ? never : true : never;
61
+ /**
62
+ * Zod-схема для {@link createContext}: без лишних ключей во {@link z.input} и {@link z.output}
63
+ * ({@link ExtraSchemaKeys}, union по веткам); {@link z.output} совместим с `T`
64
+ * ({@link SchemaCompatible}, вложенные подмножества). В контекст попадает output после `parse()`.
28
65
  */
29
66
  export type ContextSchema<T extends JsonObject, S extends z.ZodObject> = [
30
67
  S
31
- ] extends [ForbiddenUpdatesSchema] ? S : Exclude<keyof z.input<S>, keyof T> extends never ? z.input<S> extends Partial<T> ? S : never : never;
32
- /** Конфиг {@link Context} без клиентской Zod-схемы. */
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 createContext} без клиентской Zod-схемы. */
33
70
  export type ContextInitWithoutSchema<T extends JsonObject> = {
34
71
  data: () => Promise<T>;
35
72
  schema?: undefined;
36
73
  preload?: boolean;
37
74
  persistent?: boolean;
38
75
  };
39
- /** Конфиг {@link Context} с Zod-схемой клиентских изменений. */
76
+ /** Конфиг {@link createContext} с Zod-схемой клиентских изменений. */
40
77
  export type ContextInitWithSchema<T extends JsonObject, S extends z.ZodObject> = {
41
78
  data: () => Promise<T>;
42
79
  schema: ContextSchema<T, S>;
43
80
  preload?: boolean;
44
81
  persistent?: boolean;
45
82
  };
46
- /** Конфигурация {@link Context} (один аргумент конструктора). */
83
+ /** Конфигурация {@link createContext} (единственный аргумент). */
47
84
  export type ContextInitConfig<T extends JsonObject, S extends z.ZodObject | undefined = undefined> = S extends z.ZodObject ? ContextInitWithSchema<T, S> : ContextInitWithoutSchema<T>;
48
- /** Любой зарегистрированный контекст (с Zod-схемой или без). */
49
- export type AnyContext = Context<any, any>;
85
+ /** Минимальная форма аргумента {@link createContext}. */
86
+ type ContextInitShape = {
87
+ data: () => Promise<JsonObject>;
88
+ schema?: z.ZodObject;
89
+ preload?: boolean;
90
+ persistent?: boolean;
91
+ };
92
+ type ContextRuntimeInit<T extends JsonObject> = {
93
+ data: () => Promise<T>;
94
+ schema?: z.ZodObject;
95
+ preload?: boolean;
96
+ persistent?: boolean;
97
+ };
98
+ /** Тип данных `T` из поля `data` конфига. */
99
+ export type ContextDataFromInit<C extends ContextInitShape> = Awaited<ReturnType<C["data"]>>;
100
+ /** Zod-схема из поля `schema` конфига (или `undefined`). */
101
+ export type ContextSchemaFromInit<C extends ContextInitShape> = C extends {
102
+ schema: z.ZodObject;
103
+ } ? C["schema"] : undefined;
104
+ /** Экземпляр {@link Context} по форме конфига {@link createContext}. */
105
+ export type ContextFromInit<C extends ContextInitShape> = Context<ContextDataFromInit<C>>;
106
+ type ValidatedContextInit<C extends ContextInitShape> = ContextInitConfig<ContextDataFromInit<C>, ContextSchemaFromInit<C> extends z.ZodObject ? ContextSchemaFromInit<C> : undefined>;
50
107
  /**
51
108
  * Контекст данных, связанных с клиентом.
52
109
  *
53
- * Используется для хранения и синхронизации состояния между сервером и клиентом,
54
- * а также для отслеживания ошибок валидации и управления реактивными изменениями.
110
+ * @internal Создавайте экземпляры через {@link createContext}.
55
111
  *
56
112
  * @template T Тип структуры данных контекста.
57
- * @template S Zod-схема валидации клиентских изменений (см. {@link ContextSchema}).
113
+ *
114
+ * Zod-схема клиентских изменений задаётся в {@link createContext} через поле `schema`,
115
+ * а не вторым type-параметром: так проще согласовать runtime-схему и тип данных.
58
116
  */
59
- export declare class Context<T extends JsonObject, S extends z.ZodObject | undefined = undefined> {
117
+ export declare class Context<T extends JsonObject> {
60
118
  /** Уникальный идентификатор контекста */
61
119
  readonly id: `${string}-${string}-${string}-${string}-${string}`;
62
120
  /** Реактивное хранилище данных контекста. */
63
121
  protected data$?: BehaviorSubject<T>;
64
122
  /** Схема валидации данных контекста */
65
- readonly schema?: S extends z.ZodObject ? S : undefined;
123
+ readonly schema?: z.ZodObject;
66
124
  /** Флаг, указывающий, что контекст должен быть инициализирован при авторизации клиента */
67
125
  readonly preload: boolean;
68
126
  /**
@@ -94,14 +152,18 @@ export declare class Context<T extends JsonObject, S extends z.ZodObject | undef
94
152
  private clientSubscriptions;
95
153
  /** Серверный set/replace уже сам отправил diff; в subscribeToDataChanges повторять не нужно. */
96
154
  private skipNextDataSync;
155
+ /** Очередь входящих targeted-сообщений всех клиентов (последовательная обработка). */
156
+ private incomingClientMessages$;
97
157
  private assertNotDestroyed;
98
158
  private assertInitialized;
99
159
  /**
100
160
  * Клиентское `context-values` разрешено только по ключам {@link schema}.
101
161
  * Нет схемы или ключ вне неё — `Error`, patch не применяется.
102
- * Несовпадение типа остаётся `ZodError` из `parse`.
162
+ * Валидация через {@link zodDeepPick}: output **конечного** поля (leaf transform/refine).
163
+ * Transform/refine родительского object при dotted-patch не поддерживаются.
103
164
  */
104
- private assertClientChangeAllowed;
165
+ private parseClientChange;
166
+ private handleTargetedClientMessage;
105
167
  /** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
106
168
  private reportInitFailureToClients;
107
169
  /**
@@ -110,7 +172,7 @@ export declare class Context<T extends JsonObject, S extends z.ZodObject | undef
110
172
  * Подписывается на входящие сообщения от клиента и ошибки, связанные с этим контекстом.
111
173
 
112
174
  */
113
- constructor(config: S extends z.ZodObject ? ContextInitWithSchema<T, S> : ContextInitWithoutSchema<T>);
175
+ constructor(config: ContextRuntimeInit<T>);
114
176
  /** `data$` создан (init мог ещё выполняться — см. {@link init}). */
115
177
  inited(): boolean;
116
178
  /** Данные загружены: `initDataCallback` завершился. */
@@ -219,3 +281,15 @@ export declare class Context<T extends JsonObject, S extends z.ZodObject | undef
219
281
  strictRef<OtherContextType extends JsonObject, OtherPathType extends Paths<OtherContextType>>(other: ContextRef<OtherContextType, OtherPathType>): ContextRef<T, PathValue<OtherContextType, OtherPathType> & Paths<T>>;
220
282
  toJSON(): `${string}-${string}-${string}-${string}-${string}`;
221
283
  }
284
+ /** Любой зарегистрированный контекст (с Zod-схемой или без). */
285
+ export type AnyContext = Context<any>;
286
+ /**
287
+ * Создаёт контекст данных BFF: хранилище состояния с синхронизацией клиент ↔ сервер.
288
+ *
289
+ * Тип данных выводится из `data`, тип Zod-схемы — из `schema`. Связь проверяется через
290
+ * {@link ContextSchema}. Generic-параметры у вызова не задаются.
291
+ *
292
+ * Если в начальном `data` нет части полей (например опциональных), укажите тип на колбэке:
293
+ * `data: async (): Promise<MyT> => ({ … })`.
294
+ */
295
+ export declare function createContext<C extends ContextInitShape>(config: C & ValidatedContextInit<C>): ContextFromInit<C>;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Context = exports.forbiddenUpdatesSchema = void 0;
3
+ exports.Context = exports.contextClientUpdatesForbiddenSchema = void 0;
4
+ exports.createContext = createContext;
4
5
  const index_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/context/index");
5
6
  const index_2 = require("@matreshka/client-bff-protocol/messages/client-to-bff/context/index");
6
7
  const targeted_message_1 = require("@matreshka/client-bff-protocol/messages/targeted-message");
@@ -13,13 +14,15 @@ const inc_context_value_1 = require("../actions/inc-context-value");
13
14
  const set_context_1 = require("../actions/set-context");
14
15
  const toggle_context_value_1 = require("../actions/toggle-context-value");
15
16
  const client_context_1 = require("../client-context");
17
+ const assert_non_overlapping_context_paths_1 = require("../utils/assert-non-overlapping-context-paths");
18
+ const assert_safe_dotted_path_1 = require("../utils/assert-safe-dotted-path");
16
19
  const deep_pick_1 = require("../utils/deep-pick");
17
- const incoming_message_observer_1 = require("../utils/incoming-message-observer");
18
20
  const objects_diff_1 = require("../utils/objects-diff");
19
21
  const replace_context_keys_1 = require("../utils/replace-context-keys");
22
+ const assert_client_update_schema_1 = require("./assert-client-update-schema");
20
23
  const context_ref_1 = require("./context-ref");
21
- /** @see ForbiddenUpdatesSchema */
22
- exports.forbiddenUpdatesSchema = zod_1.z.strictObject({});
24
+ /** @see ContextClientUpdatesForbiddenSchema */
25
+ exports.contextClientUpdatesForbiddenSchema = zod_1.z.strictObject({});
23
26
  /** Отделяет чтение через {@link Context.get} от живого дерева в хранилище. */
24
27
  function cloneGetResult(value) {
25
28
  if (value !== null && typeof value === "object") {
@@ -69,14 +72,18 @@ function unbindClient(contextId, client) {
69
72
  entry.clients.delete(client);
70
73
  return entry.clients.size === 0;
71
74
  }
75
+ function isClientBound(contextId, client) {
76
+ return getRegistryEntry(contextId)?.clients.has(client) ?? false;
77
+ }
72
78
  /**
73
79
  * Контекст данных, связанных с клиентом.
74
80
  *
75
- * Используется для хранения и синхронизации состояния между сервером и клиентом,
76
- * а также для отслеживания ошибок валидации и управления реактивными изменениями.
81
+ * @internal Создавайте экземпляры через {@link createContext}.
77
82
  *
78
83
  * @template T Тип структуры данных контекста.
79
- * @template S Zod-схема валидации клиентских изменений (см. {@link ContextSchema}).
84
+ *
85
+ * Zod-схема клиентских изменений задаётся в {@link createContext} через поле `schema`,
86
+ * а не вторым type-параметром: так проще согласовать runtime-схему и тип данных.
80
87
  */
81
88
  class Context {
82
89
  assertNotDestroyed() {
@@ -92,9 +99,11 @@ class Context {
92
99
  /**
93
100
  * Клиентское `context-values` разрешено только по ключам {@link schema}.
94
101
  * Нет схемы или ключ вне неё — `Error`, patch не применяется.
95
- * Несовпадение типа остаётся `ZodError` из `parse`.
102
+ * Валидация через {@link zodDeepPick}: output **конечного** поля (leaf transform/refine).
103
+ * Transform/refine родительского object при dotted-patch не поддерживаются.
96
104
  */
97
- assertClientChangeAllowed(key, value) {
105
+ async parseClientChange(key, value) {
106
+ (0, assert_safe_dotted_path_1.assertSafeDottedPath)(key);
98
107
  if (!this.schema) {
99
108
  throw new Error(`Context ${this.id} rejected client update for "${key}": validation schema is not set`);
100
109
  }
@@ -106,7 +115,40 @@ class Context {
106
115
  const reason = cause instanceof Error ? cause.message : String(cause);
107
116
  throw new Error(`Context ${this.id} rejected client update for "${key}": key is not described in the validation schema (${reason})`);
108
117
  }
109
- keySchema.parse(value);
118
+ return keySchema.parseAsync(value);
119
+ }
120
+ async handleTargetedClientMessage(client, unsafeMessage) {
121
+ if (this.destroyed) {
122
+ return;
123
+ }
124
+ if (unsafeMessage instanceof index_2.ContextInitMessage) {
125
+ await this.init();
126
+ if (this.destroyed || !isClientBound(this.id, client)) {
127
+ return;
128
+ }
129
+ this.sendContextInit(client);
130
+ if (!isInitSent(this.id, client)) {
131
+ markInitSent(this.id, client);
132
+ }
133
+ return;
134
+ }
135
+ if (unsafeMessage instanceof index_2.ContextValuesMessage) {
136
+ const payloadSchema = zod_1.z.array(zod_1.z.strictObject({ key: zod_1.z.string(), value: zod_1.z.unknown() }));
137
+ const changes = payloadSchema.parse(unsafeMessage.payload);
138
+ (0, assert_non_overlapping_context_paths_1.assertNonOverlappingContextPaths)(changes.map((change) => change.key));
139
+ const patch = {};
140
+ for (const change of changes) {
141
+ patch[change.key] = await this.parseClientChange(change.key, change.value);
142
+ if (this.destroyed || !isClientBound(this.id, client)) {
143
+ return;
144
+ }
145
+ }
146
+ if (this.destroyed || !isClientBound(this.id, client)) {
147
+ return;
148
+ }
149
+ this.dataChangedByClient = client;
150
+ this.set(patch);
151
+ }
110
152
  }
111
153
  /** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
112
154
  reportInitFailureToClients(error) {
@@ -139,11 +181,22 @@ class Context {
139
181
  this.clientSubscriptions = new Map();
140
182
  /** Серверный set/replace уже сам отправил diff; в subscribeToDataChanges повторять не нужно. */
141
183
  this.skipNextDataSync = false;
142
- this.schema = ("schema" in config ? config.schema : undefined);
184
+ /** Очередь входящих targeted-сообщений всех клиентов (последовательная обработка). */
185
+ this.incomingClientMessages$ = new rxjs_1.Subject();
186
+ this.schema = config.schema;
187
+ if (this.schema) {
188
+ (0, assert_client_update_schema_1.assertClientUpdateSchemaSupported)(this.schema);
189
+ }
143
190
  registerContext(this);
144
191
  this.initDataCallback = config.data;
145
192
  this.preload = config.preload ?? false;
146
193
  this.persistent = config.persistent ?? false;
194
+ this.subscriptions.add(this.incomingClientMessages$
195
+ .pipe((0, rxjs_1.concatMap)(({ client, message }) => (0, rxjs_1.from)(this.handleTargetedClientMessage(client, message)).pipe((0, rxjs_1.catchError)((error) => {
196
+ client.error$.next(error);
197
+ return rxjs_1.EMPTY;
198
+ }))))
199
+ .subscribe());
147
200
  }
148
201
  /** `data$` создан (init мог ещё выполняться — см. {@link init}). */
149
202
  inited() {
@@ -162,6 +215,7 @@ class Context {
162
215
  return;
163
216
  }
164
217
  this.destroyed = true;
218
+ this.incomingClientMessages$.complete();
165
219
  getRegistryEntry(this.id)?.clients.forEach((_, client) => {
166
220
  client.outcomingMessage$.next(new index_1.ContextDestroyMessage(this.id));
167
221
  });
@@ -197,13 +251,15 @@ class Context {
197
251
  return;
198
252
  }
199
253
  if (this.preload) {
200
- void this.init().then(() => {
201
- if (this.destroyed) {
254
+ void this.init()
255
+ .then(() => {
256
+ if (this.destroyed || !isClientBound(this.id, client)) {
202
257
  return;
203
258
  }
204
259
  this.sendContextInit(client);
205
260
  markInitSent(this.id, client);
206
- });
261
+ })
262
+ .catch(() => { });
207
263
  }
208
264
  const clientSubscription = new rxjs_1.Subscription();
209
265
  this.clientSubscriptions.set(client, clientSubscription);
@@ -220,37 +276,12 @@ class Context {
220
276
  clientSubscription.add(client.incomingMessage$
221
277
  .pipe((0, rxjs_1.filter)((unsafeMessage) => unsafeMessage instanceof targeted_message_1.TargetedMessage &&
222
278
  unsafeMessage.target === this.id))
223
- .subscribe((0, incoming_message_observer_1.incomingMessageObserver)(client, (unsafeMessage) => {
224
- if (this.destroyed) {
225
- return;
226
- }
227
- if (unsafeMessage instanceof index_2.ContextInitMessage) {
228
- void this.init().then(() => {
229
- if (this.destroyed) {
230
- return;
231
- }
232
- this.sendContextInit(client);
233
- if (!isInitSent(this.id, client)) {
234
- markInitSent(this.id, client);
235
- }
236
- });
237
- return;
238
- }
239
- if (unsafeMessage instanceof index_2.ContextValuesMessage) {
240
- const payloadSchema = zod_1.z.array(zod_1.z.strictObject({ key: zod_1.z.string(), value: zod_1.z.unknown() }));
241
- const changes = payloadSchema.parse(unsafeMessage.payload);
242
- for (const change of changes) {
243
- this.assertClientChangeAllowed(change.key, change.value);
244
- }
245
- const patch = {};
246
- for (const change of changes) {
247
- patch[change.key] = change.value;
248
- }
249
- this.dataChangedByClient = client;
250
- this.set(patch);
251
- return;
252
- }
253
- })));
279
+ .subscribe((unsafeMessage) => {
280
+ this.incomingClientMessages$.next({
281
+ client,
282
+ message: unsafeMessage,
283
+ });
284
+ }));
254
285
  }
255
286
  subscribeToDataChanges() {
256
287
  let prevData; // pairwise() из rxjs имеет сцефику, если в next передать измененный объект, то prev и active совпадут, поэтому лучше хранить копию самому
@@ -350,8 +381,9 @@ class Context {
350
381
  updateDataAndWait(mutator) {
351
382
  this.assertNotDestroyed();
352
383
  this.assertInitialized();
353
- const prevData = structuredClone(this.data$.getValue());
354
- const nextData = mutator(this.data$.getValue());
384
+ const currentData = this.data$.getValue();
385
+ const prevData = structuredClone(currentData);
386
+ const nextData = mutator(structuredClone(currentData));
355
387
  const diff = (0, objects_diff_1.objectsDiff)(prevData, nextData);
356
388
  this.skipNextDataSync = true;
357
389
  this.data$.next(nextData);
@@ -440,12 +472,14 @@ class Context {
440
472
  * См. `docs/architecture/context-update-delivery.md`.
441
473
  */
442
474
  set(patch) {
475
+ const paths = Object.keys(patch).filter((path) => Object.prototype.hasOwnProperty.call(patch, path));
476
+ (0, assert_non_overlapping_context_paths_1.assertNonOverlappingContextPaths)(paths);
477
+ for (const path of paths) {
478
+ (0, assert_safe_dotted_path_1.assertSafeDottedPath)(path);
479
+ }
443
480
  return this.updateDataAndWait((data) => {
444
- for (const path of Object.keys(patch)) {
445
- // hasOwnProperty: «loading: undefined» пишем, пропущенный ключ — не трогаем.
446
- if (Object.prototype.hasOwnProperty.call(patch, path)) {
447
- (0, set_object_property_1.setObjectProperty)(data, path, patch[path]);
448
- }
481
+ for (const path of paths) {
482
+ (0, set_object_property_1.setObjectProperty)(data, path, patch[path]);
449
483
  }
450
484
  return data;
451
485
  });
@@ -457,7 +491,7 @@ class Context {
457
491
  * Возвращает тот же hot {@link Observable}, что и {@link set}.
458
492
  */
459
493
  replace(data) {
460
- return this.updateDataAndWait(() => data);
494
+ return this.updateDataAndWait(() => structuredClone(data));
461
495
  }
462
496
  /**
463
497
  * Глубокая копия всего `T` (structured clone корня).
@@ -539,3 +573,15 @@ class Context {
539
573
  }
540
574
  }
541
575
  exports.Context = Context;
576
+ /**
577
+ * Создаёт контекст данных BFF: хранилище состояния с синхронизацией клиент ↔ сервер.
578
+ *
579
+ * Тип данных выводится из `data`, тип Zod-схемы — из `schema`. Связь проверяется через
580
+ * {@link ContextSchema}. Generic-параметры у вызова не задаются.
581
+ *
582
+ * Если в начальном `data` нет части полей (например опциональных), укажите тип на колбэке:
583
+ * `data: async (): Promise<MyT> => ({ … })`.
584
+ */
585
+ function createContext(config) {
586
+ return new Context(config);
587
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Запрещает дубли и вложенные dotted-пути в одном patch
3
+ * (например `user` и `user.name` вместе).
4
+ */
5
+ export declare function assertNonOverlappingContextPaths(paths: string[]): void;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertNonOverlappingContextPaths = assertNonOverlappingContextPaths;
4
+ /**
5
+ * Запрещает дубли и вложенные dotted-пути в одном patch
6
+ * (например `user` и `user.name` вместе).
7
+ */
8
+ function assertNonOverlappingContextPaths(paths) {
9
+ const sorted = [...paths].sort();
10
+ for (let i = 1; i < sorted.length; i++) {
11
+ const previous = sorted[i - 1];
12
+ const current = sorted[i];
13
+ if (current === previous || current.startsWith(`${previous}.`)) {
14
+ throw new Error(`Overlapping context paths: "${previous}" and "${current}"`);
15
+ }
16
+ }
17
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Проверяет dotted-путь данных контекста (сегменты между точками).
3
+ * Запрещены пустые сегменты и prototype pollution.
4
+ */
5
+ export declare function assertSafeDottedPath(key: string): void;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertSafeDottedPath = assertSafeDottedPath;
4
+ const forbiddenPathSegments = new Set([
5
+ "__proto__",
6
+ "prototype",
7
+ "constructor",
8
+ ]);
9
+ /**
10
+ * Проверяет dotted-путь данных контекста (сегменты между точками).
11
+ * Запрещены пустые сегменты и prototype pollution.
12
+ */
13
+ function assertSafeDottedPath(key) {
14
+ if (!key) {
15
+ throw new Error(`Invalid context path: "${key}"`);
16
+ }
17
+ const parts = key.split(".");
18
+ if (parts.some((part) => !part || forbiddenPathSegments.has(part))) {
19
+ throw new Error(`Invalid context path: "${key}"`);
20
+ }
21
+ }
@@ -8,14 +8,35 @@ function isZodObject(schema) {
8
8
  function isZodArray(schema) {
9
9
  return schema instanceof zod_1.z.ZodArray;
10
10
  }
11
+ /** Объектная shape для навигации по dotted-пути (без object-level pipe/transform). */
12
+ function objectShapeForPick(schema) {
13
+ let current = schema;
14
+ for (;;) {
15
+ if (isZodObject(current)) {
16
+ return current;
17
+ }
18
+ if (current instanceof zod_1.z.ZodOptional || current instanceof zod_1.z.ZodNullable) {
19
+ current = current.unwrap();
20
+ continue;
21
+ }
22
+ if (current instanceof zod_1.z.ZodPipe) {
23
+ const inner = current._def.in;
24
+ if (isZodObject(inner)) {
25
+ return inner;
26
+ }
27
+ break;
28
+ }
29
+ break;
30
+ }
31
+ throw Error("Not a zod object");
32
+ }
11
33
  function pickObject(schema, path) {
12
- if (!isZodObject(schema))
13
- throw Error("Not a zod object");
14
- const newSchema = schema.shape?.[path];
34
+ const objectSchema = objectShapeForPick(schema);
35
+ const newSchema = objectSchema.shape?.[path];
15
36
  if (!newSchema)
16
37
  throw Error(
17
38
  // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
18
- `${path} does not exist on schema with keys: ${Object.keys(schema.shape)}`);
39
+ `${path} does not exist on schema with keys: ${Object.keys(objectSchema.shape)}`);
19
40
  return newSchema;
20
41
  }
21
42
  function pickArray(schema) {
@@ -3,7 +3,7 @@ import type { Client } from "../client";
3
3
  * Observer для подписок на `incomingMessage$`: синхронные ошибки в `next`
4
4
  * и ошибки потока перенаправляются в `client.error$`.
5
5
  */
6
- export declare function incomingMessageObserver<T>(client: Client, next: (value: T) => void): {
6
+ export declare function incomingMessageObserver<T>(client: Client, next: (value: T) => void | Promise<void>): {
7
7
  next: (value: T) => void;
8
8
  error: (error: unknown) => void;
9
9
  };
@@ -10,7 +10,12 @@ function incomingMessageObserver(client, next) {
10
10
  return {
11
11
  next: (value) => {
12
12
  try {
13
- next(value);
13
+ const result = next(value);
14
+ if (result instanceof Promise) {
15
+ void result.catch((error) => {
16
+ client.error$.next(error);
17
+ });
18
+ }
14
19
  }
15
20
  catch (error) {
16
21
  client.error$.next(error);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@matreshka/bff",
3
- "version": "0.28.1",
3
+ "version": "0.30.0",
4
4
  "description": "Matreshka BFF: server-driven UI runtime — routing, pages, context, component DSL, and platform APIs",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",