@matreshka/bff 0.27.1 → 0.29.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.
@@ -4,7 +4,6 @@ exports.ForEach = exports.forEach = void 0;
4
4
  const server_component_class_1 = require("@matreshka/client-bff-protocol/enums/server-component-class");
5
5
  const for_each_sync_components_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/components/for-each/for-each-sync-components-message");
6
6
  const rxjs_1 = require("rxjs");
7
- const zod_1 = require("zod");
8
7
  const core_1 = require("../core");
9
8
  const serialize_component_tree_1 = require("../core/utils/serialize-component-tree");
10
9
  const track_created_instances_1 = require("../core/utils/track-created-instances");
@@ -47,7 +46,7 @@ class ForEachContext extends core_1.Context {
47
46
  super({
48
47
  data: async () => ({}),
49
48
  preload: preload,
50
- schema: zod_1.z.strictObject({}), // Запрет изменения из внешних источников
49
+ schema: core_1.contextClientUpdatesForbiddenSchema, // Запрет изменения из внешних источников
51
50
  });
52
51
  }
53
52
  }
@@ -1,9 +1,9 @@
1
- import { Context, type JsonObject } from "../../core";
1
+ import { Context, type ContextClientUpdatesForbiddenSchema, 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, ContextClientUpdatesForbiddenSchema> {
7
7
  /**
8
8
  * Синхронно поднимает хранилище до async {@link init}, чтобы `replace` в serialize
9
9
  * не перезаписывался пустым `{}` из `initDataCallback`.
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ItemListIndexStore = void 0;
4
4
  const rxjs_1 = require("rxjs");
5
- const zod_1 = require("zod");
6
5
  const core_1 = require("../../core");
7
6
  /** Контекст индексов элементов ItemList; данные не загружаются снаружи. */
8
7
  class ItemListIndexStore extends core_1.Context {
@@ -22,7 +21,7 @@ class ItemListIndexStore extends core_1.Context {
22
21
  super({
23
22
  data: async () => ({}),
24
23
  preload,
25
- schema: zod_1.z.strictObject({}),
24
+ schema: core_1.contextClientUpdatesForbiddenSchema,
26
25
  });
27
26
  }
28
27
  }
@@ -1,4 +1,5 @@
1
1
  import { JsonObject } from "@matreshka/client-bff-protocol/types/json";
2
+ import { z } from "zod";
2
3
  import { Context, ContextPathPatch } from "../context/context";
3
4
  import { ContextValueOrRef } from "../types/context-value-ref";
4
5
  import { ActionConfig } from "./action";
@@ -12,9 +13,9 @@ export type LocalContextPathPatch<T extends JsonObject> = Partial<{
12
13
  export declare class SetContext<T extends JsonObject> extends LocalAction {
13
14
  private readonly context;
14
15
  private readonly patch;
15
- constructor(context: Context<T>, patch: LocalContextPathPatch<T>, config?: ActionConfig);
16
+ constructor(context: Context<T, z.ZodObject | undefined>, patch: LocalContextPathPatch<T>, config?: ActionConfig);
16
17
  class(): string;
17
18
  payload(): object;
18
19
  }
19
20
  /** @internal */
20
- export declare function createSetContext<T extends JsonObject>(context: Context<T>, patch: LocalContextPathPatch<T>, config?: ActionConfig): SetContext<T>;
21
+ export declare function createSetContext<T extends JsonObject>(context: Context<T, z.ZodObject | undefined>, 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
+ }
@@ -1,6 +1,7 @@
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";
4
5
  import { ActionConfig } from "../actions/action";
5
6
  import { DecContextValue } from "../actions/dec-context-value";
6
7
  import { IncContextValue } from "../actions/inc-context-value";
@@ -25,11 +26,11 @@ export type ContextRefValue<R extends ContextRef> = R extends {
25
26
  readonly __valueType?: infer ValueType;
26
27
  } ? Exclude<ValueType, undefined> : R extends ContextRef<infer ContextType, infer PathType> ? PathValue<ContextType, PathType> : never;
27
28
  export declare class ContextRef<ContextType extends JsonObject = JsonObject, PathType extends string = string> {
28
- readonly context: Context<any>;
29
+ readonly context: Context<ContextType, z.ZodObject | undefined>;
29
30
  readonly path: PathType;
30
31
  /** Локальные (client-only) действия по этому ref. */
31
32
  readonly local: ContextRefLocalActions<ContextType, PathType>;
32
- constructor(context: Context<any>, path: PathType);
33
+ constructor(context: Context<ContextType, z.ZodObject | undefined>, path: PathType);
33
34
  /**
34
35
  * Продолжение пути в рамках того же контекста.
35
36
  * Строго типизировано: K должен быть путём внутри значения по текущему PathType.
@@ -1,7 +1,7 @@
1
1
  import { JsonObject } from "@matreshka/client-bff-protocol/types/json";
2
2
  import { BehaviorSubject, Observable } from "rxjs";
3
3
  import { Paths, PathValue } from "ts-essentials";
4
- import { ZodObject } from "zod";
4
+ import { z } from "zod";
5
5
  import { ActionConfig } from "../actions/action";
6
6
  import { LocalContextPathPatch } from "../actions/set-context";
7
7
  import type { Client } from "../client";
@@ -13,21 +13,107 @@ export type { ContextUpdateDelivery } from "../types/context-update-delivery";
13
13
  export type ContextPathPatch<T extends JsonObject> = Partial<{
14
14
  [K in Paths<T>]: PathValue<T, K>;
15
15
  }>;
16
+ /**
17
+ * Пустая strict-схема: клиент не может менять данные контекста через `context-values`.
18
+ * Используется во внутренних контекстах (ForEach, ItemList).
19
+ */
20
+ export type ContextClientUpdatesForbiddenSchema = z.ZodObject<Record<string, never>, z.core.$strict> & {
21
+ readonly __contextClientUpdatesForbidden?: unique symbol;
22
+ };
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;
40
+ /**
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 context}: без лишних ключей во {@link z.input} и {@link z.output}
63
+ * ({@link ExtraSchemaKeys}, union по веткам); {@link z.output} совместим с `T`
64
+ * ({@link SchemaCompatible}, вложенные подмножества). В контекст попадает output после `parse()`.
65
+ */
66
+ export type ContextSchema<T extends JsonObject, S extends z.ZodObject> = [
67
+ S
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 context} без клиентской Zod-схемы. */
70
+ export type ContextInitWithoutSchema<T extends JsonObject> = {
71
+ data: () => Promise<T>;
72
+ schema?: undefined;
73
+ preload?: boolean;
74
+ persistent?: boolean;
75
+ };
76
+ /** Конфиг {@link context} с Zod-схемой клиентских изменений. */
77
+ export type ContextInitWithSchema<T extends JsonObject, S extends z.ZodObject> = {
78
+ data: () => Promise<T>;
79
+ schema: ContextSchema<T, S>;
80
+ preload?: boolean;
81
+ persistent?: boolean;
82
+ };
83
+ /** Конфигурация {@link context} (единственный аргумент). */
84
+ export type ContextInitConfig<T extends JsonObject, S extends z.ZodObject | undefined = undefined> = S extends z.ZodObject ? ContextInitWithSchema<T, S> : ContextInitWithoutSchema<T>;
85
+ /** Минимальная форма аргумента {@link context}. */
86
+ type ContextInitShape = {
87
+ data: () => Promise<JsonObject>;
88
+ schema?: z.ZodObject;
89
+ preload?: boolean;
90
+ persistent?: boolean;
91
+ };
92
+ /** Тип данных `T` из поля `data` конфига. */
93
+ export type ContextDataFromInit<C extends ContextInitShape> = Awaited<ReturnType<C["data"]>>;
94
+ /** Zod-схема из поля `schema` конфига (или `undefined`). */
95
+ export type ContextSchemaFromInit<C extends ContextInitShape> = C extends {
96
+ schema: z.ZodObject;
97
+ } ? C["schema"] : undefined;
98
+ /** Экземпляр {@link Context} по форме конфига {@link context}. */
99
+ export type ContextFromInit<C extends ContextInitShape> = ContextSchemaFromInit<C> extends z.ZodObject ? Context<ContextDataFromInit<C>, ContextSchemaFromInit<C>> : Context<ContextDataFromInit<C>, undefined>;
100
+ type ValidatedContextInit<C extends ContextInitShape> = ContextInitConfig<ContextDataFromInit<C>, ContextSchemaFromInit<C> extends z.ZodObject ? ContextSchemaFromInit<C> : undefined>;
101
+ type StoredContext = Context<JsonObject, z.ZodObject | undefined>;
16
102
  /**
17
103
  * Контекст данных, связанных с клиентом.
18
104
  *
19
- * Используется для хранения и синхронизации состояния между сервером и клиентом,
20
- * а также для отслеживания ошибок валидации и управления реактивными изменениями.
105
+ * @internal Создавайте экземпляры через {@link context}.
21
106
  *
22
107
  * @template T Тип структуры данных контекста.
108
+ * @template S Zod-схема валидации клиентских изменений (см. {@link ContextSchema}).
23
109
  */
24
- export declare class Context<T extends JsonObject> {
110
+ export declare class Context<T extends JsonObject, S extends z.ZodObject | undefined = undefined> {
25
111
  /** Уникальный идентификатор контекста */
26
112
  readonly id: `${string}-${string}-${string}-${string}-${string}`;
27
113
  /** Реактивное хранилище данных контекста. */
28
114
  protected data$?: BehaviorSubject<T>;
29
115
  /** Схема валидации данных контекста */
30
- readonly schema?: ZodObject;
116
+ readonly schema?: S extends z.ZodObject ? S : undefined;
31
117
  /** Флаг, указывающий, что контекст должен быть инициализирован при авторизации клиента */
32
118
  readonly preload: boolean;
33
119
  /**
@@ -59,8 +145,18 @@ export declare class Context<T extends JsonObject> {
59
145
  private clientSubscriptions;
60
146
  /** Серверный set/replace уже сам отправил diff; в subscribeToDataChanges повторять не нужно. */
61
147
  private skipNextDataSync;
148
+ /** Очередь входящих targeted-сообщений всех клиентов (последовательная обработка). */
149
+ private incomingClientMessages$;
62
150
  private assertNotDestroyed;
63
151
  private assertInitialized;
152
+ /**
153
+ * Клиентское `context-values` разрешено только по ключам {@link schema}.
154
+ * Нет схемы или ключ вне неё — `Error`, patch не применяется.
155
+ * Валидация через {@link zodDeepPick}: output **конечного** поля (leaf transform/refine).
156
+ * Transform/refine родительского object при dotted-patch не поддерживаются.
157
+ */
158
+ private parseClientChange;
159
+ private handleTargetedClientMessage;
64
160
  /** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
65
161
  private reportInitFailureToClients;
66
162
  /**
@@ -69,12 +165,7 @@ export declare class Context<T extends JsonObject> {
69
165
  * Подписывается на входящие сообщения от клиента и ошибки, связанные с этим контекстом.
70
166
 
71
167
  */
72
- constructor(config: {
73
- data: () => Promise<T>;
74
- schema?: ZodObject;
75
- preload?: boolean;
76
- persistent?: boolean;
77
- });
168
+ constructor(config: S extends z.ZodObject ? ContextInitWithSchema<T, S> : ContextInitWithoutSchema<T>);
78
169
  /** `data$` создан (init мог ещё выполняться — см. {@link init}). */
79
170
  inited(): boolean;
80
171
  /** Данные загружены: `initDataCallback` завершился. */
@@ -183,3 +274,15 @@ export declare class Context<T extends JsonObject> {
183
274
  strictRef<OtherContextType extends JsonObject, OtherPathType extends Paths<OtherContextType>>(other: ContextRef<OtherContextType, OtherPathType>): ContextRef<T, PathValue<OtherContextType, OtherPathType> & Paths<T>>;
184
275
  toJSON(): `${string}-${string}-${string}-${string}-${string}`;
185
276
  }
277
+ /** Любой зарегистрированный контекст (с Zod-схемой или без). */
278
+ export type AnyContext = StoredContext;
279
+ /**
280
+ * Создаёт контекст данных BFF: хранилище состояния с синхронизацией клиент ↔ сервер.
281
+ *
282
+ * Тип данных выводится из `data`, тип Zod-схемы — из `schema`. Связь проверяется через
283
+ * {@link ContextSchema}. Generic-параметры у вызова не задаются.
284
+ *
285
+ * Если в начальном `data` нет части полей (например опциональных), укажите тип на колбэке:
286
+ * `data: async (): Promise<MyT> => ({ … })`.
287
+ */
288
+ export declare function context<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 = void 0;
3
+ exports.Context = exports.contextClientUpdatesForbiddenSchema = void 0;
4
+ exports.context = context;
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,11 +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");
24
+ /** @see ContextClientUpdatesForbiddenSchema */
25
+ exports.contextClientUpdatesForbiddenSchema = zod_1.z.strictObject({});
21
26
  /** Отделяет чтение через {@link Context.get} от живого дерева в хранилище. */
22
27
  function cloneGetResult(value) {
23
28
  if (value !== null && typeof value === "object") {
@@ -67,13 +72,16 @@ function unbindClient(contextId, client) {
67
72
  entry.clients.delete(client);
68
73
  return entry.clients.size === 0;
69
74
  }
75
+ function isClientBound(contextId, client) {
76
+ return getRegistryEntry(contextId)?.clients.has(client) ?? false;
77
+ }
70
78
  /**
71
79
  * Контекст данных, связанных с клиентом.
72
80
  *
73
- * Используется для хранения и синхронизации состояния между сервером и клиентом,
74
- * а также для отслеживания ошибок валидации и управления реактивными изменениями.
81
+ * @internal Создавайте экземпляры через {@link context}.
75
82
  *
76
83
  * @template T Тип структуры данных контекста.
84
+ * @template S Zod-схема валидации клиентских изменений (см. {@link ContextSchema}).
77
85
  */
78
86
  class Context {
79
87
  assertNotDestroyed() {
@@ -86,6 +94,60 @@ class Context {
86
94
  throw new Error(`Context ${this.id} is not initialized`);
87
95
  }
88
96
  }
97
+ /**
98
+ * Клиентское `context-values` разрешено только по ключам {@link schema}.
99
+ * Нет схемы или ключ вне неё — `Error`, patch не применяется.
100
+ * Валидация через {@link zodDeepPick}: output **конечного** поля (leaf transform/refine).
101
+ * Transform/refine родительского object при dotted-patch не поддерживаются.
102
+ */
103
+ async parseClientChange(key, value) {
104
+ (0, assert_safe_dotted_path_1.assertSafeDottedPath)(key);
105
+ if (!this.schema) {
106
+ throw new Error(`Context ${this.id} rejected client update for "${key}": validation schema is not set`);
107
+ }
108
+ let keySchema;
109
+ try {
110
+ keySchema = (0, deep_pick_1.zodDeepPick)(this.schema, key);
111
+ }
112
+ catch (cause) {
113
+ const reason = cause instanceof Error ? cause.message : String(cause);
114
+ throw new Error(`Context ${this.id} rejected client update for "${key}": key is not described in the validation schema (${reason})`);
115
+ }
116
+ return keySchema.parseAsync(value);
117
+ }
118
+ async handleTargetedClientMessage(client, unsafeMessage) {
119
+ if (this.destroyed) {
120
+ return;
121
+ }
122
+ if (unsafeMessage instanceof index_2.ContextInitMessage) {
123
+ await this.init();
124
+ if (this.destroyed || !isClientBound(this.id, client)) {
125
+ return;
126
+ }
127
+ this.sendContextInit(client);
128
+ if (!isInitSent(this.id, client)) {
129
+ markInitSent(this.id, client);
130
+ }
131
+ return;
132
+ }
133
+ if (unsafeMessage instanceof index_2.ContextValuesMessage) {
134
+ const payloadSchema = zod_1.z.array(zod_1.z.strictObject({ key: zod_1.z.string(), value: zod_1.z.unknown() }));
135
+ const changes = payloadSchema.parse(unsafeMessage.payload);
136
+ (0, assert_non_overlapping_context_paths_1.assertNonOverlappingContextPaths)(changes.map((change) => change.key));
137
+ const patch = {};
138
+ for (const change of changes) {
139
+ patch[change.key] = await this.parseClientChange(change.key, change.value);
140
+ if (this.destroyed || !isClientBound(this.id, client)) {
141
+ return;
142
+ }
143
+ }
144
+ if (this.destroyed || !isClientBound(this.id, client)) {
145
+ return;
146
+ }
147
+ this.dataChangedByClient = client;
148
+ this.set(patch);
149
+ }
150
+ }
89
151
  /** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
90
152
  reportInitFailureToClients(error) {
91
153
  getRegistryEntry(this.id)?.clients.forEach((_, client) => {
@@ -117,11 +179,22 @@ class Context {
117
179
  this.clientSubscriptions = new Map();
118
180
  /** Серверный set/replace уже сам отправил diff; в subscribeToDataChanges повторять не нужно. */
119
181
  this.skipNextDataSync = false;
120
- this.schema = config.schema;
182
+ /** Очередь входящих targeted-сообщений всех клиентов (последовательная обработка). */
183
+ this.incomingClientMessages$ = new rxjs_1.Subject();
184
+ this.schema = ("schema" in config ? config.schema : undefined);
185
+ if (this.schema) {
186
+ (0, assert_client_update_schema_1.assertClientUpdateSchemaSupported)(this.schema);
187
+ }
121
188
  registerContext(this);
122
189
  this.initDataCallback = config.data;
123
190
  this.preload = config.preload ?? false;
124
191
  this.persistent = config.persistent ?? false;
192
+ this.subscriptions.add(this.incomingClientMessages$
193
+ .pipe((0, rxjs_1.concatMap)(({ client, message }) => (0, rxjs_1.from)(this.handleTargetedClientMessage(client, message)).pipe((0, rxjs_1.catchError)((error) => {
194
+ client.error$.next(error);
195
+ return rxjs_1.EMPTY;
196
+ }))))
197
+ .subscribe());
125
198
  }
126
199
  /** `data$` создан (init мог ещё выполняться — см. {@link init}). */
127
200
  inited() {
@@ -140,6 +213,7 @@ class Context {
140
213
  return;
141
214
  }
142
215
  this.destroyed = true;
216
+ this.incomingClientMessages$.complete();
143
217
  getRegistryEntry(this.id)?.clients.forEach((_, client) => {
144
218
  client.outcomingMessage$.next(new index_1.ContextDestroyMessage(this.id));
145
219
  });
@@ -175,13 +249,15 @@ class Context {
175
249
  return;
176
250
  }
177
251
  if (this.preload) {
178
- void this.init().then(() => {
179
- if (this.destroyed) {
252
+ void this.init()
253
+ .then(() => {
254
+ if (this.destroyed || !isClientBound(this.id, client)) {
180
255
  return;
181
256
  }
182
257
  this.sendContextInit(client);
183
258
  markInitSent(this.id, client);
184
- });
259
+ })
260
+ .catch(() => { });
185
261
  }
186
262
  const clientSubscription = new rxjs_1.Subscription();
187
263
  this.clientSubscriptions.set(client, clientSubscription);
@@ -198,38 +274,12 @@ class Context {
198
274
  clientSubscription.add(client.incomingMessage$
199
275
  .pipe((0, rxjs_1.filter)((unsafeMessage) => unsafeMessage instanceof targeted_message_1.TargetedMessage &&
200
276
  unsafeMessage.target === this.id))
201
- .subscribe((0, incoming_message_observer_1.incomingMessageObserver)(client, (unsafeMessage) => {
202
- if (this.destroyed) {
203
- return;
204
- }
205
- if (unsafeMessage instanceof index_2.ContextInitMessage) {
206
- void this.init().then(() => {
207
- if (this.destroyed) {
208
- return;
209
- }
210
- this.sendContextInit(client);
211
- if (!isInitSent(this.id, client)) {
212
- markInitSent(this.id, client);
213
- }
214
- });
215
- return;
216
- }
217
- if (unsafeMessage instanceof index_2.ContextValuesMessage) {
218
- const payloadSchema = zod_1.z.array(zod_1.z.strictObject({ key: zod_1.z.string(), value: zod_1.z.unknown() }));
219
- const changes = payloadSchema.parse(unsafeMessage.payload);
220
- const patch = {};
221
- changes.forEach((change) => {
222
- if (this.schema) {
223
- const keySchema = (0, deep_pick_1.zodDeepPick)(this.schema, change.key);
224
- keySchema.parse(change.value);
225
- }
226
- patch[change.key] = change.value;
227
- });
228
- this.dataChangedByClient = client;
229
- this.set(patch);
230
- return;
231
- }
232
- })));
277
+ .subscribe((unsafeMessage) => {
278
+ this.incomingClientMessages$.next({
279
+ client,
280
+ message: unsafeMessage,
281
+ });
282
+ }));
233
283
  }
234
284
  subscribeToDataChanges() {
235
285
  let prevData; // pairwise() из rxjs имеет сцефику, если в next передать измененный объект, то prev и active совпадут, поэтому лучше хранить копию самому
@@ -329,8 +379,9 @@ class Context {
329
379
  updateDataAndWait(mutator) {
330
380
  this.assertNotDestroyed();
331
381
  this.assertInitialized();
332
- const prevData = structuredClone(this.data$.getValue());
333
- const nextData = mutator(this.data$.getValue());
382
+ const currentData = this.data$.getValue();
383
+ const prevData = structuredClone(currentData);
384
+ const nextData = mutator(structuredClone(currentData));
334
385
  const diff = (0, objects_diff_1.objectsDiff)(prevData, nextData);
335
386
  this.skipNextDataSync = true;
336
387
  this.data$.next(nextData);
@@ -419,12 +470,14 @@ class Context {
419
470
  * См. `docs/architecture/context-update-delivery.md`.
420
471
  */
421
472
  set(patch) {
473
+ const paths = Object.keys(patch).filter((path) => Object.prototype.hasOwnProperty.call(patch, path));
474
+ (0, assert_non_overlapping_context_paths_1.assertNonOverlappingContextPaths)(paths);
475
+ for (const path of paths) {
476
+ (0, assert_safe_dotted_path_1.assertSafeDottedPath)(path);
477
+ }
422
478
  return this.updateDataAndWait((data) => {
423
- for (const path of Object.keys(patch)) {
424
- // hasOwnProperty: «loading: undefined» пишем, пропущенный ключ — не трогаем.
425
- if (Object.prototype.hasOwnProperty.call(patch, path)) {
426
- (0, set_object_property_1.setObjectProperty)(data, path, patch[path]);
427
- }
479
+ for (const path of paths) {
480
+ (0, set_object_property_1.setObjectProperty)(data, path, patch[path]);
428
481
  }
429
482
  return data;
430
483
  });
@@ -436,7 +489,7 @@ class Context {
436
489
  * Возвращает тот же hot {@link Observable}, что и {@link set}.
437
490
  */
438
491
  replace(data) {
439
- return this.updateDataAndWait(() => data);
492
+ return this.updateDataAndWait(() => structuredClone(data));
440
493
  }
441
494
  /**
442
495
  * Глубокая копия всего `T` (structured clone корня).
@@ -518,3 +571,15 @@ class Context {
518
571
  }
519
572
  }
520
573
  exports.Context = Context;
574
+ /**
575
+ * Создаёт контекст данных BFF: хранилище состояния с синхронизацией клиент ↔ сервер.
576
+ *
577
+ * Тип данных выводится из `data`, тип Zod-схемы — из `schema`. Связь проверяется через
578
+ * {@link ContextSchema}. Generic-параметры у вызова не задаются.
579
+ *
580
+ * Если в начальном `data` нет части полей (например опциональных), укажите тип на колбэке:
581
+ * `data: async (): Promise<MyT> => ({ … })`.
582
+ */
583
+ function context(config) {
584
+ return new Context(config);
585
+ }
@@ -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);
@@ -1,4 +1,4 @@
1
- import type { Context } from "../context/context";
1
+ import type { AnyContext } from "../context/context";
2
2
  /**
3
3
  * Заменяет плейсхолдеры вида `@{ключ}` в строке значениями из объекта контекста.
4
4
  *
@@ -9,4 +9,4 @@ import type { Context } from "../context/context";
9
9
  * @param resolveContext Поиск контекста по id.
10
10
  * @returns Строка с заменёнными плейсхолдерами.
11
11
  */
12
- export declare function replaceContextKeys(str: string, resolveContext: (contextId: string) => Context<any> | undefined): string;
12
+ export declare function replaceContextKeys(str: string, resolveContext: (contextId: string) => AnyContext | undefined): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@matreshka/bff",
3
- "version": "0.27.1",
3
+ "version": "0.29.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",