@matreshka/bff 0.22.0 → 0.23.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.
@@ -6,7 +6,7 @@ import { PlatformId } from "@matreshka/shared/enums/platform-id";
6
6
  import { AnyBffToClientMessage, BffToClientMessage } from "@matreshka/shared/messages/bff-to-client/bff-to-client-message";
7
7
  import { AnyClientToBffMessage } from "@matreshka/shared/messages/client-to-bff/client-to-bff-message";
8
8
  import { ClientState } from "@matreshka/shared/types/client-state";
9
- import { BehaviorSubject, Subject } from "rxjs";
9
+ import { BehaviorSubject, Observable, Subject } from "rxjs";
10
10
  import { z } from "zod/v4";
11
11
  import { Page } from "../components";
12
12
  import { App } from "../components/app";
@@ -82,6 +82,11 @@ export declare class Client {
82
82
  * Отключает transport-слой без уничтожения клиента (grace period).
83
83
  */
84
84
  detachTransport(): void;
85
+ /**
86
+ * Ждёт transport-level receipt для outgoing reliable-сообщения.
87
+ * Если клиент уничтожается раньше receipt, ожидание завершается как terminal.
88
+ */
89
+ waitForDelivery(message: AnyBffToClientMessage): Observable<void>;
85
90
  /**
86
91
  * Entry instance для сериализации глобальных App-оверлеев (platform.setOverlays).
87
92
  */
@@ -116,6 +116,34 @@ class Client {
116
116
  detachTransport() {
117
117
  delete this.transportSend;
118
118
  }
119
+ /**
120
+ * Ждёт transport-level receipt для outgoing reliable-сообщения.
121
+ * Если клиент уничтожается раньше receipt, ожидание завершается как terminal.
122
+ */
123
+ waitForDelivery(message) {
124
+ return new rxjs_1.Observable((subscriber) => {
125
+ const receiptSubscription = this.reliableDelivery
126
+ .waitForReceipt(message)
127
+ .subscribe({
128
+ next: () => {
129
+ subscriber.next(undefined);
130
+ subscriber.complete();
131
+ },
132
+ error: (error) => subscriber.error(error),
133
+ });
134
+ const destroySubscription = this.destroy$.subscribe(() => {
135
+ if (subscriber.closed) {
136
+ return;
137
+ }
138
+ subscriber.next(undefined);
139
+ subscriber.complete();
140
+ });
141
+ return () => {
142
+ receiptSubscription.unsubscribe();
143
+ destroySubscription.unsubscribe();
144
+ };
145
+ });
146
+ }
119
147
  /**
120
148
  * Entry instance для сериализации глобальных App-оверлеев (platform.setOverlays).
121
149
  */
@@ -5,9 +5,9 @@ import { ContextRef, ContextRefValue } from "../context/context-ref";
5
5
  import type { CompatibleContextValueRef } from "../types/context-value-ref";
6
6
  type ContextArrayValue = readonly unknown[] | unknown[];
7
7
  /** Элемент массива по значению `ContextRef`. */
8
- export type ContextRefArrayElement<R extends ContextRef> = Extract<ContextRefValue<R>, ContextArrayValue>[number];
8
+ export type ContextRefArrayElement<R extends ContextRef<any, any>> = Extract<ContextRefValue<R>, ContextArrayValue>[number];
9
9
  /** Ref на массив в контексте (значение по ref — массив или readonly-массив). */
10
- export type CompatibleArrayContextRef<R extends ContextRef> = [
10
+ export type CompatibleArrayContextRef<R extends ContextRef<any, any>> = [
11
11
  Extract<ContextRefValue<R>, ContextArrayValue>
12
12
  ] extends [never] ? never : R;
13
13
  /**
@@ -22,11 +22,11 @@ export type ConditionOperandFor<ValueType> = (ValueType & JsonPrimitive) | Compa
22
22
  * Операнд условия на BFF: JSON-примитив того же типа, что значение по `ref`,
23
23
  * либо другая ссылка с совместимым типом значения (сравнение в рантайме через `===`).
24
24
  */
25
- export type ConditionOperand<R extends ContextRef> = ConditionOperandFor<ContextRefValue<R>>;
25
+ export type ConditionOperand<R extends ContextRef<any, any>> = ConditionOperandFor<ContextRefValue<R>>;
26
26
  /** Значение поля элемента массива по `itemPath` (пустой путь — сам элемент). */
27
27
  export type ArrayIncludesItemValue<Item, P extends string> = P extends "" ? Item : Item extends JsonObject ? PathValue<Item, P & Paths<Item>> : never;
28
28
  /** Операнд {@link ContextArrayIncludes} / {@link ContextArrayNotIncludes}. */
29
- export type ArrayIncludesOperand<R extends ContextRef, P extends string> = ConditionOperandFor<ArrayIncludesItemValue<ContextRefArrayElement<R>, P>>;
29
+ export type ArrayIncludesOperand<R extends ContextRef<any, any>, P extends string> = ConditionOperandFor<ArrayIncludesItemValue<ContextRefArrayElement<R>, P>>;
30
30
  /** Операнд длины массива: число или ссылка на число в контексте. */
31
31
  export type ConditionLengthOperand = ConditionOperandFor<number>;
32
32
  /** Операнд без привязки к конкретному `ref` (сериализация на wire). */
@@ -10,11 +10,11 @@ import { ArrayIncludesOperand, CompatibleArrayContextRef, ContextRefArrayElement
10
10
  *
11
11
  * @internal Используйте {@link contextArrayIncludes} / {@link when.includes}.
12
12
  */
13
- export declare class ContextArrayIncludes<R extends ContextRef, P extends Paths<ContextRefArrayElement<R>> | "" = ""> extends Condition {
13
+ export declare class ContextArrayIncludes<R extends ContextRef<any, any>, P extends Extract<Paths<ContextRefArrayElement<R>>, string> | "" = ""> extends Condition {
14
14
  constructor(ref: CompatibleArrayContextRef<R>, itemPath: P, value: ArrayIncludesOperand<R, P>);
15
15
  }
16
16
  /** Функциональная форма {@link ContextArrayIncludes}. */
17
- export declare function contextArrayIncludes<R extends ContextRef, P extends Paths<ContextRefArrayElement<R>> | "" = "">(ref: CompatibleArrayContextRef<R>, itemPath: P, value: ArrayIncludesOperand<R, P>): ContextArrayIncludes<R, P>;
17
+ export declare function contextArrayIncludes<R extends ContextRef<any, any>, P extends Extract<Paths<ContextRefArrayElement<R>>, string> | "" = "">(ref: CompatibleArrayContextRef<R>, itemPath: P, value: ArrayIncludesOperand<R, P>): ContextArrayIncludes<R, P>;
18
18
  /**
19
19
  * Условие: в массиве из контекста нет элемента, у которого значение по
20
20
  * `itemPath` равно операнду (литерал или `ContextRef`).
@@ -23,8 +23,8 @@ export declare function contextArrayIncludes<R extends ContextRef, P extends Pat
23
23
  *
24
24
  * @internal Используйте {@link contextArrayNotIncludes} / {@link when.excludes}.
25
25
  */
26
- export declare class ContextArrayNotIncludes<R extends ContextRef, P extends Paths<ContextRefArrayElement<R>> | "" = ""> extends Condition {
26
+ export declare class ContextArrayNotIncludes<R extends ContextRef<any, any>, P extends Extract<Paths<ContextRefArrayElement<R>>, string> | "" = ""> extends Condition {
27
27
  constructor(ref: CompatibleArrayContextRef<R>, itemPath: P, value: ArrayIncludesOperand<R, P>);
28
28
  }
29
29
  /** Функциональная форма {@link ContextArrayNotIncludes}. */
30
- export declare function contextArrayNotIncludes<R extends ContextRef, P extends Paths<ContextRefArrayElement<R>> | "" = "">(ref: CompatibleArrayContextRef<R>, itemPath: P, value: ArrayIncludesOperand<R, P>): ContextArrayNotIncludes<R, P>;
30
+ export declare function contextArrayNotIncludes<R extends ContextRef<any, any>, P extends Extract<Paths<ContextRefArrayElement<R>>, string> | "" = "">(ref: CompatibleArrayContextRef<R>, itemPath: P, value: ArrayIncludesOperand<R, P>): ContextArrayNotIncludes<R, P>;
@@ -8,7 +8,7 @@ import { CompatibleArrayContextRef, ConditionLengthOperand } from "./condition-o
8
8
  *
9
9
  * @internal Используйте фабрики длины массива ({@link contextArrayLengthEqual} и др.).
10
10
  */
11
- export declare abstract class ContextArrayLength<R extends ContextRef> extends Condition {
11
+ export declare abstract class ContextArrayLength<R extends ContextRef<any, any>> extends Condition {
12
12
  constructor(ref: CompatibleArrayContextRef<R>, length: ConditionLengthOperand, operator: ArrayLengthCompare);
13
13
  }
14
14
  /**
@@ -16,68 +16,68 @@ export declare abstract class ContextArrayLength<R extends ContextRef> extends C
16
16
  *
17
17
  * @internal Используйте {@link contextArrayLengthEqual} / {@link when.lengthEquals}.
18
18
  */
19
- export declare class ContextArrayLengthEqual<R extends ContextRef> extends Condition {
19
+ export declare class ContextArrayLengthEqual<R extends ContextRef<any, any>> extends Condition {
20
20
  constructor(ref: CompatibleArrayContextRef<R>, length: ConditionLengthOperand);
21
21
  }
22
22
  /** Функциональная форма {@link ContextArrayLengthEqual}. */
23
- export declare function contextArrayLengthEqual<R extends ContextRef>(ref: CompatibleArrayContextRef<R>, length: ConditionLengthOperand): ContextArrayLengthEqual<R>;
23
+ export declare function contextArrayLengthEqual<R extends ContextRef<any, any>>(ref: CompatibleArrayContextRef<R>, length: ConditionLengthOperand): ContextArrayLengthEqual<R>;
24
24
  /**
25
25
  * Алиас: длина массива в контексте строго меньше операнда (`<`).
26
26
  *
27
27
  * @internal Используйте {@link contextArrayLengthLessThan} / {@link when.lengthLessThan}.
28
28
  */
29
- export declare class ContextArrayLengthLessThan<R extends ContextRef> extends Condition {
29
+ export declare class ContextArrayLengthLessThan<R extends ContextRef<any, any>> extends Condition {
30
30
  constructor(ref: CompatibleArrayContextRef<R>, length: ConditionLengthOperand);
31
31
  }
32
32
  /** Функциональная форма {@link ContextArrayLengthLessThan}. */
33
- export declare function contextArrayLengthLessThan<R extends ContextRef>(ref: CompatibleArrayContextRef<R>, length: ConditionLengthOperand): ContextArrayLengthLessThan<R>;
33
+ export declare function contextArrayLengthLessThan<R extends ContextRef<any, any>>(ref: CompatibleArrayContextRef<R>, length: ConditionLengthOperand): ContextArrayLengthLessThan<R>;
34
34
  /**
35
35
  * Алиас: длина массива в контексте меньше или равна операнду (`<=`).
36
36
  *
37
37
  * @internal Используйте {@link contextArrayLengthLessOrEqual} / {@link when.lengthAtMost}.
38
38
  */
39
- export declare class ContextArrayLengthLessOrEqual<R extends ContextRef> extends Condition {
39
+ export declare class ContextArrayLengthLessOrEqual<R extends ContextRef<any, any>> extends Condition {
40
40
  constructor(ref: CompatibleArrayContextRef<R>, length: ConditionLengthOperand);
41
41
  }
42
42
  /** Функциональная форма {@link ContextArrayLengthLessOrEqual}. */
43
- export declare function contextArrayLengthLessOrEqual<R extends ContextRef>(ref: CompatibleArrayContextRef<R>, length: ConditionLengthOperand): ContextArrayLengthLessOrEqual<R>;
43
+ export declare function contextArrayLengthLessOrEqual<R extends ContextRef<any, any>>(ref: CompatibleArrayContextRef<R>, length: ConditionLengthOperand): ContextArrayLengthLessOrEqual<R>;
44
44
  /**
45
45
  * Алиас: длина массива в контексте строго больше операнда (`>`).
46
46
  *
47
47
  * @internal Используйте {@link contextArrayLengthGreaterThan} / {@link when.lengthGreaterThan}.
48
48
  */
49
- export declare class ContextArrayLengthGreaterThan<R extends ContextRef> extends Condition {
49
+ export declare class ContextArrayLengthGreaterThan<R extends ContextRef<any, any>> extends Condition {
50
50
  constructor(ref: CompatibleArrayContextRef<R>, length: ConditionLengthOperand);
51
51
  }
52
52
  /** Функциональная форма {@link ContextArrayLengthGreaterThan}. */
53
- export declare function contextArrayLengthGreaterThan<R extends ContextRef>(ref: CompatibleArrayContextRef<R>, length: ConditionLengthOperand): ContextArrayLengthGreaterThan<R>;
53
+ export declare function contextArrayLengthGreaterThan<R extends ContextRef<any, any>>(ref: CompatibleArrayContextRef<R>, length: ConditionLengthOperand): ContextArrayLengthGreaterThan<R>;
54
54
  /**
55
55
  * Алиас: длина массива в контексте больше или равна операнду (`>=`).
56
56
  *
57
57
  * @internal Используйте {@link contextArrayLengthGreaterOrEqual} / {@link when.lengthAtLeast}.
58
58
  */
59
- export declare class ContextArrayLengthGreaterOrEqual<R extends ContextRef> extends Condition {
59
+ export declare class ContextArrayLengthGreaterOrEqual<R extends ContextRef<any, any>> extends Condition {
60
60
  constructor(ref: CompatibleArrayContextRef<R>, length: ConditionLengthOperand);
61
61
  }
62
62
  /** Функциональная форма {@link ContextArrayLengthGreaterOrEqual}. */
63
- export declare function contextArrayLengthGreaterOrEqual<R extends ContextRef>(ref: CompatibleArrayContextRef<R>, length: ConditionLengthOperand): ContextArrayLengthGreaterOrEqual<R>;
63
+ export declare function contextArrayLengthGreaterOrEqual<R extends ContextRef<any, any>>(ref: CompatibleArrayContextRef<R>, length: ConditionLengthOperand): ContextArrayLengthGreaterOrEqual<R>;
64
64
  /**
65
65
  * Алиас: массив в контексте пуст (длина равна 0).
66
66
  *
67
67
  * @internal Используйте {@link contextValueEmpty} / {@link when.isEmpty}.
68
68
  */
69
- export declare class ContextValueEmpty<R extends ContextRef> extends ContextArrayLengthEqual<R> {
69
+ export declare class ContextValueEmpty<R extends ContextRef<any, any>> extends ContextArrayLengthEqual<R> {
70
70
  constructor(ref: CompatibleArrayContextRef<R>);
71
71
  }
72
72
  /** Функциональная форма {@link ContextValueEmpty}. */
73
- export declare function contextValueEmpty<R extends ContextRef>(ref: CompatibleArrayContextRef<R>): ContextValueEmpty<R>;
73
+ export declare function contextValueEmpty<R extends ContextRef<any, any>>(ref: CompatibleArrayContextRef<R>): ContextValueEmpty<R>;
74
74
  /**
75
75
  * Алиас: массив в контексте непуст (длина строго больше 0).
76
76
  *
77
77
  * @internal Используйте {@link contextValueNotEmpty} / {@link when.notEmpty}.
78
78
  */
79
- export declare class ContextValueNotEmpty<R extends ContextRef> extends ContextArrayLengthGreaterThan<R> {
79
+ export declare class ContextValueNotEmpty<R extends ContextRef<any, any>> extends ContextArrayLengthGreaterThan<R> {
80
80
  constructor(ref: CompatibleArrayContextRef<R>);
81
81
  }
82
82
  /** Функциональная форма {@link ContextValueNotEmpty}. */
83
- export declare function contextValueNotEmpty<R extends ContextRef>(ref: CompatibleArrayContextRef<R>): ContextValueNotEmpty<R>;
83
+ export declare function contextValueNotEmpty<R extends ContextRef<any, any>>(ref: CompatibleArrayContextRef<R>): ContextValueNotEmpty<R>;
@@ -7,8 +7,8 @@ import { ConditionOperand } from "./condition-operand";
7
7
  *
8
8
  * @internal Используйте {@link contextValueEqual} / {@link when.equals}.
9
9
  */
10
- export declare class ContextValueEqual<R extends ContextRef> extends Condition {
10
+ export declare class ContextValueEqual<R extends ContextRef<any, any>> extends Condition {
11
11
  constructor(ref: R, value: ConditionOperand<R>);
12
12
  }
13
13
  /** Функциональная форма {@link ContextValueEqual}. */
14
- export declare function contextValueEqual<R extends ContextRef>(ref: R, value: ConditionOperand<R>): ContextValueEqual<R>;
14
+ export declare function contextValueEqual<R extends ContextRef<any, any>>(ref: R, value: ConditionOperand<R>): ContextValueEqual<R>;
@@ -7,8 +7,8 @@ import { ConditionOperand } from "./condition-operand";
7
7
  *
8
8
  * @internal Используйте {@link contextValueIn} / {@link when.oneOf}.
9
9
  */
10
- export declare class ContextValueIn<R extends ContextRef> extends Condition {
10
+ export declare class ContextValueIn<R extends ContextRef<any, any>> extends Condition {
11
11
  constructor(ref: R, value: ConditionOperand<R>[]);
12
12
  }
13
13
  /** Функциональная форма {@link ContextValueIn}. */
14
- export declare function contextValueIn<R extends ContextRef>(ref: R, value: ConditionOperand<R>[]): ContextValueIn<R>;
14
+ export declare function contextValueIn<R extends ContextRef<any, any>>(ref: R, value: ConditionOperand<R>[]): ContextValueIn<R>;
@@ -7,8 +7,8 @@ import { ConditionOperand } from "./condition-operand";
7
7
  *
8
8
  * @internal Используйте {@link contextValueNotEqual} / {@link when.notEquals}.
9
9
  */
10
- export declare class ContextValueNotEqual<R extends ContextRef> extends Condition {
10
+ export declare class ContextValueNotEqual<R extends ContextRef<any, any>> extends Condition {
11
11
  constructor(ref: R, value: ConditionOperand<R>);
12
12
  }
13
13
  /** Функциональная форма {@link ContextValueNotEqual}. */
14
- export declare function contextValueNotEqual<R extends ContextRef>(ref: R, value: ConditionOperand<R>): ContextValueNotEqual<R>;
14
+ export declare function contextValueNotEqual<R extends ContextRef<any, any>>(ref: R, value: ConditionOperand<R>): ContextValueNotEqual<R>;
@@ -1,10 +1,12 @@
1
1
  import { JsonObject } from "@matreshka/shared/types/json";
2
+ import { Observable } from "rxjs";
2
3
  import { Paths, PathValue } from "ts-essentials";
3
4
  import { ActionConfig } from "../actions/action";
4
5
  import { DecContextValue } from "../actions/dec-context-value";
5
6
  import { IncContextValue } from "../actions/inc-context-value";
6
7
  import { SetContext } from "../actions/set-context";
7
8
  import { ToggleContextValue } from "../actions/toggle-context-value";
9
+ import type { ContextUpdateDelivery } from "../types/context-update-delivery";
8
10
  import { ContextValueOrRef } from "../types/context-value-ref";
9
11
  import { Context } from "./context";
10
12
  type ContextRefLocalSet<ContextType extends JsonObject, PathType extends string> = {
@@ -66,9 +68,10 @@ export declare class ContextRef<ContextType extends JsonObject = JsonObject, Pat
66
68
  get(): PathValue<ContextType, PathType>;
67
69
  /**
68
70
  * Запись значения по текущему пути через {@link Context.set}.
69
- * Если контекст уже уничтожен, вызов игнорируется (без исключения).
71
+ * Hot Observable стартует в момент вызова. Уничтоженный контекст —
72
+ * та же ошибка, что у {@link Context.set}.
70
73
  */
71
- set(value: PathValue<ContextType, PathType>): void;
74
+ set(value: PathValue<ContextType, PathType>): Observable<ContextUpdateDelivery>;
72
75
  toString(): string;
73
76
  toJSON(): string;
74
77
  }
@@ -64,13 +64,11 @@ class ContextRef {
64
64
  }
65
65
  /**
66
66
  * Запись значения по текущему пути через {@link Context.set}.
67
- * Если контекст уже уничтожен, вызов игнорируется (без исключения).
67
+ * Hot Observable стартует в момент вызова. Уничтоженный контекст —
68
+ * та же ошибка, что у {@link Context.set}.
68
69
  */
69
70
  set(value) {
70
- if (this.context.isDestroyed()) {
71
- return;
72
- }
73
- this.context.set({
71
+ return this.context.set({
74
72
  [this.path]: value,
75
73
  });
76
74
  }
@@ -5,8 +5,10 @@ import { ZodObject } from "zod/v4";
5
5
  import { ActionConfig } from "../actions/action";
6
6
  import { LocalContextPathPatch } from "../actions/set-context";
7
7
  import type { Client } from "../client";
8
+ import { ContextUpdateDelivery } from "../types/context-update-delivery";
8
9
  import { ContextValueOrRef } from "../types/context-value-ref";
9
10
  import { ContextRef } from "./context-ref";
11
+ export type { ContextUpdateDelivery } from "../types/context-update-delivery";
10
12
  /** Частичное обновление данных контекста по dotted-путям (см. {@link Context.set}). */
11
13
  export type ContextPathPatch<T extends JsonObject> = Partial<{
12
14
  [K in Paths<T>]: PathValue<T, K>;
@@ -55,6 +57,8 @@ export declare class Context<T extends JsonObject> {
55
57
  private subscriptions;
56
58
  private dataSubscription?;
57
59
  private clientSubscriptions;
60
+ /** Серверный set/replace уже сам отправил diff; в subscribeToDataChanges повторять не нужно. */
61
+ private skipNextDataSync;
58
62
  private assertNotDestroyed;
59
63
  private assertInitialized;
60
64
  /** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
@@ -82,6 +86,10 @@ export declare class Context<T extends JsonObject> {
82
86
  private releaseClientBinding;
83
87
  authorizeClient(client: Client): void;
84
88
  protected subscribeToDataChanges(): void;
89
+ private completeImmediately;
90
+ private recipientsForDiff;
91
+ private emitDiffAndWait;
92
+ private updateDataAndWait;
85
93
  /**
86
94
  * Инициализирует контекст: создаёт `data$`, загружает начальные данные через
87
95
  * `initDataCallback` и запускает синхронизацию с клиентами.
@@ -113,14 +121,20 @@ export declare class Context<T extends JsonObject> {
113
121
  * Предпочтительный способ правки нескольких полей на BFF. Ключ с явным
114
122
  * `undefined` применяется (отличие от отсутствующего ключа в patch).
115
123
  * Для целого снимка после load — {@link replace}.
124
+ *
125
+ * Возвращает hot {@link Observable}: на каждый receipt — {@link ContextUpdateDelivery}
126
+ * с накопительным `delivered`; `complete` после всех адресатов. Пустой diff /
127
+ * нет получателей — один `next({ delivered: [] })` и `complete`.
128
+ * См. `docs/architecture/context-update-delivery.md`.
116
129
  */
117
- set(patch: ContextPathPatch<T>): void;
130
+ set(patch: ContextPathPatch<T>): Observable<ContextUpdateDelivery>;
118
131
  /**
119
132
  * Полная замена корня контекста (результат load, `{ ...loaded, field }`).
120
133
  *
121
134
  * Не merge patch: переданный объект становится новым состоянием целиком.
135
+ * Возвращает тот же hot {@link Observable}, что и {@link set}.
122
136
  */
123
- replace(data: T): void;
137
+ replace(data: T): Observable<ContextUpdateDelivery>;
124
138
  /**
125
139
  * Глубокая копия всего `T` (structured clone корня).
126
140
  *
@@ -115,6 +115,8 @@ class Context {
115
115
  this.destroyed = false;
116
116
  this.subscriptions = new rxjs_1.Subscription();
117
117
  this.clientSubscriptions = new Map();
118
+ /** Серверный set/replace уже сам отправил diff; в subscribeToDataChanges повторять не нужно. */
119
+ this.skipNextDataSync = false;
118
120
  this.schema = config.schema;
119
121
  registerContext(this);
120
122
  this.initDataCallback = config.data;
@@ -215,17 +217,16 @@ class Context {
215
217
  if (unsafeMessage instanceof index_2.ContextValuesMessage) {
216
218
  const payloadSchema = v4_1.z.array(v4_1.z.strictObject({ key: v4_1.z.string(), value: v4_1.z.unknown() }));
217
219
  const changes = payloadSchema.parse(unsafeMessage.payload);
218
- const data = this.data$.getValue();
220
+ const patch = {};
219
221
  changes.forEach((change) => {
220
222
  if (this.schema) {
221
223
  const keySchema = (0, deep_pick_1.zodDeepPick)(this.schema, change.key);
222
224
  keySchema.parse(change.value);
223
225
  }
224
- // @ts-expect-error Проверка типа происходит при помощи zod, так что ошибка не актуальна
225
- (0, set_object_property_1.setObjectProperty)(data, change.key, change.value);
226
+ patch[change.key] = change.value;
226
227
  });
227
228
  this.dataChangedByClient = client;
228
- this.replace(data);
229
+ this.set(patch);
229
230
  return;
230
231
  }
231
232
  })));
@@ -237,6 +238,11 @@ class Context {
237
238
  if (this.destroyed) {
238
239
  return;
239
240
  }
241
+ if (this.skipNextDataSync) {
242
+ this.skipNextDataSync = false;
243
+ prevData = structuredClone(data);
244
+ return;
245
+ }
240
246
  // Во время init() не шлём diff (сохраняем текущую семантику: первая "реальная" установка данных не должна рассылаться как изменения).
241
247
  if (!this.initializing && prevData) {
242
248
  let diff;
@@ -261,6 +267,75 @@ class Context {
261
267
  prevData = structuredClone(data);
262
268
  });
263
269
  }
270
+ completeImmediately() {
271
+ const result$ = new rxjs_1.ReplaySubject(1);
272
+ result$.next({ delivered: [] });
273
+ result$.complete();
274
+ return result$.asObservable();
275
+ }
276
+ recipientsForDiff() {
277
+ const recipients = [];
278
+ getRegistryEntry(this.id)?.clients.forEach((_, client) => {
279
+ if (this.dataChangedByClient !== client) {
280
+ recipients.push(client);
281
+ }
282
+ });
283
+ return recipients;
284
+ }
285
+ emitDiffAndWait(diff) {
286
+ const recipients = this.recipientsForDiff();
287
+ this.dataChangedByClient = undefined;
288
+ if (Object.keys(diff).length === 0 || recipients.length === 0) {
289
+ return this.completeImmediately();
290
+ }
291
+ const payload = Object.entries(diff).map(([key, value]) => ({
292
+ key,
293
+ value,
294
+ }));
295
+ const result$ = new rxjs_1.ReplaySubject(recipients.length);
296
+ const delivered = [];
297
+ let finalized = false;
298
+ const subscriptions = new rxjs_1.Subscription();
299
+ const finishError = (error) => {
300
+ if (finalized) {
301
+ return;
302
+ }
303
+ finalized = true;
304
+ subscriptions.unsubscribe();
305
+ result$.error(error);
306
+ };
307
+ const finishSuccess = (client) => {
308
+ if (finalized) {
309
+ return;
310
+ }
311
+ delivered.push(client);
312
+ result$.next({ delivered: [...delivered] });
313
+ if (delivered.length === recipients.length) {
314
+ finalized = true;
315
+ subscriptions.unsubscribe();
316
+ result$.complete();
317
+ }
318
+ };
319
+ for (const client of recipients) {
320
+ const message = new index_1.ContextValuesMessage(this.id, payload);
321
+ subscriptions.add(client.waitForDelivery(message).subscribe({
322
+ next: () => finishSuccess(client),
323
+ error: (error) => finishError(error),
324
+ }));
325
+ client.outcomingMessage$.next(message);
326
+ }
327
+ return result$.asObservable();
328
+ }
329
+ updateDataAndWait(mutator) {
330
+ this.assertNotDestroyed();
331
+ this.assertInitialized();
332
+ const prevData = structuredClone(this.data$.getValue());
333
+ const nextData = mutator(this.data$.getValue());
334
+ const diff = (0, objects_diff_1.objectsDiff)(prevData, nextData);
335
+ this.skipNextDataSync = true;
336
+ this.data$.next(nextData);
337
+ return this.emitDiffAndWait(diff);
338
+ }
264
339
  /**
265
340
  * Инициализирует контекст: создаёт `data$`, загружает начальные данные через
266
341
  * `initDataCallback` и запускает синхронизацию с клиентами.
@@ -337,28 +412,31 @@ class Context {
337
412
  * Предпочтительный способ правки нескольких полей на BFF. Ключ с явным
338
413
  * `undefined` применяется (отличие от отсутствующего ключа в patch).
339
414
  * Для целого снимка после load — {@link replace}.
415
+ *
416
+ * Возвращает hot {@link Observable}: на каждый receipt — {@link ContextUpdateDelivery}
417
+ * с накопительным `delivered`; `complete` после всех адресатов. Пустой diff /
418
+ * нет получателей — один `next({ delivered: [] })` и `complete`.
419
+ * См. `docs/architecture/context-update-delivery.md`.
340
420
  */
341
421
  set(patch) {
342
- this.assertNotDestroyed();
343
- this.assertInitialized();
344
- const data = this.data$.getValue();
345
- for (const path of Object.keys(patch)) {
346
- // hasOwnProperty: «loading: undefined» пишем, пропущенный ключ — не трогаем.
347
- if (Object.prototype.hasOwnProperty.call(patch, path)) {
348
- (0, set_object_property_1.setObjectProperty)(data, path, patch[path]);
422
+ 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
+ }
349
428
  }
350
- }
351
- this.data$.next(data);
429
+ return data;
430
+ });
352
431
  }
353
432
  /**
354
433
  * Полная замена корня контекста (результат load, `{ ...loaded, field }`).
355
434
  *
356
435
  * Не merge patch: переданный объект становится новым состоянием целиком.
436
+ * Возвращает тот же hot {@link Observable}, что и {@link set}.
357
437
  */
358
438
  replace(data) {
359
- this.assertNotDestroyed();
360
- this.assertInitialized();
361
- this.data$.next(data);
439
+ return this.updateDataAndWait(() => data);
362
440
  }
363
441
  /**
364
442
  * Глубокая копия всего `T` (structured clone корня).
@@ -21,6 +21,7 @@ export * from "@matreshka/shared/types/json";
21
21
  export * from "./types/component-instance";
22
22
  export * from "./types/component-tree-node";
23
23
  export * from "./types/componentable";
24
+ export * from "./types/context-update-delivery";
24
25
  export * from "./types/context-value-ref";
25
26
  export * from "./types/message";
26
27
  export * from "./types/mixed-with-callbacks-array";
@@ -40,6 +40,7 @@ __exportStar(require("@matreshka/shared/types/json"), exports);
40
40
  __exportStar(require("./types/component-instance"), exports);
41
41
  __exportStar(require("./types/component-tree-node"), exports);
42
42
  __exportStar(require("./types/componentable"), exports);
43
+ __exportStar(require("./types/context-update-delivery"), exports);
43
44
  __exportStar(require("./types/context-value-ref"), exports);
44
45
  __exportStar(require("./types/message"), exports);
45
46
  __exportStar(require("./types/mixed-with-callbacks-array"), exports);
@@ -0,0 +1,5 @@
1
+ import type { Client } from "../client";
2
+ /** Прогресс transport-level доставки diff контекста (накопительный список клиентов с receipt). */
3
+ export type ContextUpdateDelivery = {
4
+ delivered: Client[];
5
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@matreshka/bff",
3
- "version": "0.22.0",
3
+ "version": "0.23.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",
@@ -62,7 +62,7 @@
62
62
  "vitest": "^4.1.0"
63
63
  },
64
64
  "dependencies": {
65
- "@matreshka/shared": "^0.21.0",
65
+ "@matreshka/shared": "^0.22.0",
66
66
  "@simplewebauthn/server": "^13.1.1",
67
67
  "@simplewebauthn/types": "^12.0.0",
68
68
  "fast-xml-parser": "^5.3.3",