@matreshka/bff 0.20.0 → 0.21.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.
@@ -9,12 +9,12 @@ export type CompatibleForEachRef<RefType extends ContextRef<any, any>> = [
9
9
  ForEachItemArray<RefType>
10
10
  ] extends [never] ? never : RefType;
11
11
  type ForEachItemData<RefType extends ContextRef<any, any>> = ForEachItemArray<RefType>[number];
12
- type ForEachTypedItemRef<ContextType extends JsonObject, PathType extends string, ValueType> = Omit<ContextRef<any, any>, "context" | "path" | "ref" | "value"> & {
12
+ type ForEachTypedItemRef<ContextType extends JsonObject, PathType extends string, ValueType> = Omit<ContextRef<any, any>, "context" | "path" | "ref" | "get"> & {
13
13
  readonly context: Context<ContextType>;
14
14
  readonly path: PathType;
15
15
  readonly __valueType?: ValueType;
16
- value(): ValueType;
17
- value(): JsonObject;
16
+ get(): ValueType;
17
+ get(): JsonObject;
18
18
  ref<K extends Paths<ValueType>>(path: K): ForEachTypedItemRef<ContextType, `${PathType}.${K & string}`, PathValue<ValueType, K>>;
19
19
  ref<P2 extends string>(path: ContextRef<ContextType, P2>): ContextRef<ContextType, `${PathType}.${P2}`>;
20
20
  };
@@ -11,14 +11,14 @@ const track_created_instances_1 = require("../core/utils/track-created-instances
11
11
  const component_1 = require("./component");
12
12
  /** Возвращает массив элементов списка из ref; не-массив даёт пустой массив. */
13
13
  function getForEachValue(ref) {
14
- const rawValue = ref.value();
14
+ const rawValue = ref.get();
15
15
  return Array.isArray(rawValue)
16
16
  ? rawValue
17
17
  : [];
18
18
  }
19
19
  /**
20
20
  * Связывает ref элемента списка с ref индекса в {@link ForEachContext},
21
- * чтобы генератор мог читать `ref.value()` и вложенные поля элемента.
21
+ * чтобы генератор мог читать `ref.get()` и вложенные поля элемента.
22
22
  */
23
23
  function createForEachItemLink(ref, indexRef) {
24
24
  return ref.strictRef(indexRef);
@@ -27,22 +27,16 @@ const forEach = (config) => new ForEach(config);
27
27
  exports.forEach = forEach;
28
28
  class ForEachContext extends core_1.Context {
29
29
  /**
30
- * Синхронно поднимает `data$`, чтобы индексы элементов были доступны при preload-сериализации.
30
+ * Синхронно поднимает хранилище до async {@link init} (preload-сериализация индексов).
31
31
  * @returns Тот же экземпляр контекста.
32
32
  */
33
33
  initSync() {
34
- // Запрет на повторную инициализацию контекста
35
- if (this.inited())
34
+ if (this.inited()) {
36
35
  return this;
36
+ }
37
37
  this.data$ = new rxjs_1.BehaviorSubject({});
38
38
  this.subscribeToDataChanges();
39
- }
40
- /**
41
- * После in-place обновления карты индексов в `data$` — одна синхронизация с клиентом.
42
- * @see Context.emitAfterInPlaceMutation
43
- */
44
- syncIndexStoreFromMutations() {
45
- super.emitAfterInPlaceMutation();
39
+ return this;
46
40
  }
47
41
  /**
48
42
  * Контекст индексов элементов ForEach; данные не загружаются снаружи (`schema` пустой).
@@ -173,15 +167,14 @@ class ForEach extends component_1.Component {
173
167
  const value = getForEachValue(this.config.ref);
174
168
  const itemsCheckSum = value.map(this.config.track).join("|");
175
169
  this.lastItemsCheckSum = itemsCheckSum;
176
- // Тот же объект, что в BehaviorSubject: мутируем in-place, чтобы strictRef видел
177
- // индекс через getValue() без next() (иначе срабатывали бы подписчики Context).
178
- const store = this.componentContext.data$.getValue();
179
- for (const key of Object.keys(store)) {
180
- delete store[key];
170
+ const items = Array.isArray(value) ? value : [];
171
+ const store = {};
172
+ for (let index = 0; index < items.length; index++) {
173
+ store[this.itemId(items[index])] = { index: `${index}` };
181
174
  }
182
- const components = (Array.isArray(value) ? value : []).map((item, index) => {
175
+ this.componentContext.replace(store);
176
+ return items.map((item) => {
183
177
  const itemId = this.itemId(item);
184
- store[itemId] = { index: `${index}` };
185
178
  if (cache.has(itemId)) {
186
179
  return cache.get(itemId);
187
180
  }
@@ -192,8 +185,6 @@ class ForEach extends component_1.Component {
192
185
  cache.set(itemId, result);
193
186
  return result;
194
187
  });
195
- this.componentContext.syncIndexStoreFromMutations();
196
- return components;
197
188
  }
198
189
  /**
199
190
  * Синхронизирует элементы списка с клиентом для одного instance ForEach.
@@ -249,10 +240,11 @@ class ForEach extends component_1.Component {
249
240
  if (this.instanceCount === 1) {
250
241
  const contextSubscription = new rxjs_1.Subscription();
251
242
  this.contextSubscription = contextSubscription;
252
- contextSubscription.add(this.config.ref.context.init$.subscribe(() => {
253
- contextSubscription.add(this.config.ref.context.data$.pipe((0, rxjs_1.skip)(1)).subscribe(() => {
254
- void this.syncComponents(true);
255
- }));
243
+ contextSubscription.add(this.config.ref.context
244
+ .watch()
245
+ .pipe((0, rxjs_1.skip)(1))
246
+ .subscribe(() => {
247
+ void this.syncComponents(true);
256
248
  }));
257
249
  }
258
250
  });
@@ -289,7 +281,7 @@ class ForEach extends component_1.Component {
289
281
  this.stopUsing$.subscribe(() => {
290
282
  this.instanceStates.clear();
291
283
  });
292
- // Инициализируем контекст сразу, чтобы при ранней сериализации data$ уже существовал.
284
+ // Инициализируем контекст сразу, чтобы при ранней сериализации хранилище уже существовало.
293
285
  void this.componentContext.initSync();
294
286
  }
295
287
  /**
@@ -106,10 +106,11 @@ class ItemList {
106
106
  }
107
107
  const contextSubscription = new rxjs_1.Subscription();
108
108
  this.contextSubscription = contextSubscription;
109
- contextSubscription.add(this.config.ref.context.init$.subscribe(() => {
110
- contextSubscription.add(this.config.ref.context.data$.pipe((0, rxjs_1.skip)(1)).subscribe(() => {
111
- this.syncToHost(true);
112
- }));
109
+ contextSubscription.add(this.config.ref.context
110
+ .watch()
111
+ .pipe((0, rxjs_1.skip)(1))
112
+ .subscribe(() => {
113
+ this.syncToHost(true);
113
114
  }));
114
115
  }
115
116
  /**
@@ -179,13 +180,14 @@ class ItemList {
179
180
  generateItems(instance) {
180
181
  const cache = this.getInstanceState(instance).itemsCache;
181
182
  const value = (0, types_1.getItemListValue)(this.config.ref);
182
- const store = this.indexContext.data$.getValue();
183
- for (const key of Object.keys(store)) {
184
- delete store[key];
183
+ const store = {};
184
+ for (let index = 0; index < value.length; index++) {
185
+ const cacheKey = this.itemCacheKey(value[index]);
186
+ store[cacheKey] = { index: `${index}` };
185
187
  }
186
- const items = value.map((data, index) => {
188
+ this.indexContext.replace(store);
189
+ return value.map((data) => {
187
190
  const cacheKey = this.itemCacheKey(data);
188
- store[cacheKey] = { index: `${index}` };
189
191
  let item = cache.get(cacheKey);
190
192
  if (!item) {
191
193
  item = this.config.generator({
@@ -196,8 +198,6 @@ class ItemList {
196
198
  }
197
199
  return { id: this.trackId(data), item };
198
200
  });
199
- this.indexContext.syncIndexStoreFromMutations();
200
- return items;
201
201
  }
202
202
  }
203
203
  exports.ItemList = ItemList;
@@ -4,8 +4,11 @@ type ItemListIndexContext = Record<string, {
4
4
  }>;
5
5
  /** Контекст индексов элементов ItemList; данные не загружаются снаружи. */
6
6
  export declare class ItemListIndexStore<T extends JsonObject = ItemListIndexContext> extends Context<T> {
7
+ /**
8
+ * Синхронно поднимает хранилище до async {@link init}, чтобы `replace` в serialize
9
+ * не перезаписывался пустым `{}` из `initDataCallback`.
10
+ */
7
11
  initSync(): this;
8
- syncIndexStoreFromMutations(): void;
9
12
  constructor(preload: boolean);
10
13
  }
11
14
  export {};
@@ -6,16 +6,18 @@ const v4_1 = require("zod/v4");
6
6
  const core_1 = require("../../core");
7
7
  /** Контекст индексов элементов ItemList; данные не загружаются снаружи. */
8
8
  class ItemListIndexStore extends core_1.Context {
9
+ /**
10
+ * Синхронно поднимает хранилище до async {@link init}, чтобы `replace` в serialize
11
+ * не перезаписывался пустым `{}` из `initDataCallback`.
12
+ */
9
13
  initSync() {
10
- if (this.inited())
14
+ if (this.inited()) {
11
15
  return this;
16
+ }
12
17
  this.data$ = new rxjs_1.BehaviorSubject({});
13
18
  this.subscribeToDataChanges();
14
19
  return this;
15
20
  }
16
- syncIndexStoreFromMutations() {
17
- super.emitAfterInPlaceMutation();
18
- }
19
21
  constructor(preload) {
20
22
  super({
21
23
  data: async () => ({}),
@@ -1,16 +1,16 @@
1
1
  import type { Paths, PathValue } from "ts-essentials";
2
2
  import type { ComponentTreeNode, ContextRef, JsonObject } from "../../core";
3
3
  export type ListArrayValue = readonly unknown[] | unknown[];
4
- type ItemArray<RefType extends ContextRef<any, any>> = Extract<ReturnType<RefType["value"]>, ListArrayValue>;
4
+ type ItemArray<RefType extends ContextRef<any, any>> = Extract<ReturnType<RefType["get"]>, ListArrayValue>;
5
5
  export type CompatibleItemListRef<RefType extends ContextRef<any, any>> = [
6
6
  ItemArray<RefType>
7
7
  ] extends [never] ? never : RefType;
8
8
  export type ItemListItemData<RefType extends ContextRef<any, any>> = ItemArray<RefType>[number];
9
- export type ItemListTypedItemRef<ContextType extends JsonObject, PathType extends string, ValueType> = Omit<ContextRef<any, any>, "path" | "ref" | "value"> & {
9
+ export type ItemListTypedItemRef<ContextType extends JsonObject, PathType extends string, ValueType> = Omit<ContextRef<any, any>, "path" | "ref" | "get"> & {
10
10
  readonly path: PathType;
11
11
  readonly __valueType?: ValueType;
12
- value(): ValueType;
13
- value(): JsonObject;
12
+ get(): ValueType;
13
+ get(): JsonObject;
14
14
  ref<K extends Paths<ValueType>>(path: K): ItemListTypedItemRef<ContextType, `${PathType}.${K & string}`, PathValue<ValueType, K>>;
15
15
  ref<P2 extends string>(path: ContextRef<ContextType, P2>): ContextRef<ContextType, `${PathType}.${P2}`>;
16
16
  };
@@ -35,6 +35,6 @@ type ItemListIndexContextRecord = Record<string, {
35
35
  index: `${number}`;
36
36
  }>;
37
37
  export declare function createItemListItemLink<ContextType extends JsonObject, PathType extends string, RefType extends ContextRef<ContextType, PathType> & {
38
- value(): ListArrayValue | undefined;
38
+ get(): ListArrayValue | undefined;
39
39
  }>(ref: RefType, indexRef: ContextRef<ItemListIndexContextRecord, `${string}.index`>): ItemListItemLink<RefType>;
40
40
  export {};
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getItemListValue = getItemListValue;
4
4
  exports.createItemListItemLink = createItemListItemLink;
5
5
  function getItemListValue(ref) {
6
- const rawValue = ref.value();
6
+ const rawValue = ref.get();
7
7
  return Array.isArray(rawValue)
8
8
  ? rawValue
9
9
  : [];
@@ -23,7 +23,7 @@ export declare class ContextRef<ContextType extends JsonObject = JsonObject, Pat
23
23
  * `@{<id контекста other>.<путь other>}` (через `other.toString()`), без подстановки
24
24
  * значения на момент вызова.
25
25
  *
26
- * При каждом чтении `Context.value` подставляет в эту строку актуальное значение по
26
+ * При каждом чтении {@link Context.get} подставляет в эту строку актуальное значение по
27
27
  * ссылке `other` (тот же механизм, что и для обычных путей с плейсхолдерами).
28
28
  * Если во втором контексте меняется строка-сегмент пути или индекс, одна и та же
29
29
  * ссылка `ContextRef` продолжает указывать на корректные данные.
@@ -42,12 +42,13 @@ export declare class ContextRef<ContextType extends JsonObject = JsonObject, Pat
42
42
  * @experimental
43
43
  */
44
44
  strictRef<OtherContextType extends JsonObject, OtherPathType extends Paths<OtherContextType>>(other: ContextRef<OtherContextType, OtherPathType>): ContextRef<ContextType, `${PathType}.${PathValue<OtherContextType, OtherPathType> & string}`>;
45
- value(): PathValue<ContextType, PathType>;
45
+ /** Значение по текущему пути (делегирует {@link Context.get}). */
46
+ get(): PathValue<ContextType, PathType>;
46
47
  /**
47
- * Запись значения по текущему пути через {@link Context.setValue}.
48
+ * Запись значения по текущему пути через {@link Context.set}.
48
49
  * Если контекст уже уничтожен, вызов игнорируется (без исключения).
49
50
  */
50
- setValue(value: PathValue<ContextType, PathType>): void;
51
+ set(value: PathValue<ContextType, PathType>): void;
51
52
  toString(): string;
52
53
  toJSON(): string;
53
54
  }
@@ -20,7 +20,7 @@ class ContextRef {
20
20
  * `@{<id контекста other>.<путь other>}` (через `other.toString()`), без подстановки
21
21
  * значения на момент вызова.
22
22
  *
23
- * При каждом чтении `Context.value` подставляет в эту строку актуальное значение по
23
+ * При каждом чтении {@link Context.get} подставляет в эту строку актуальное значение по
24
24
  * ссылке `other` (тот же механизм, что и для обычных путей с плейсхолдерами).
25
25
  * Если во втором контексте меняется строка-сегмент пути или индекс, одна и та же
26
26
  * ссылка `ContextRef` продолжает указывать на корректные данные.
@@ -42,20 +42,21 @@ class ContextRef {
42
42
  const fullPath = `${this.path}.${other.toString()}`;
43
43
  return new ContextRef(this.context, fullPath);
44
44
  }
45
- // Строгое значение по текущему пути
46
- value() {
47
- // Явно выбираем перегрузку Context.value(string): unknown и приводим к ожидаемому типу
48
- return this.context.value(this.path);
45
+ /** Значение по текущему пути (делегирует {@link Context.get}). */
46
+ get() {
47
+ return this.context.get(this.path);
49
48
  }
50
49
  /**
51
- * Запись значения по текущему пути через {@link Context.setValue}.
50
+ * Запись значения по текущему пути через {@link Context.set}.
52
51
  * Если контекст уже уничтожен, вызов игнорируется (без исключения).
53
52
  */
54
- setValue(value) {
53
+ set(value) {
55
54
  if (this.context.isDestroyed()) {
56
55
  return;
57
56
  }
58
- this.context.setValue(this.path, value);
57
+ this.context.set({
58
+ [this.path]: value,
59
+ });
59
60
  }
60
61
  toString() {
61
62
  return `@{${this.context.id}.${this.path}}`;
@@ -1,9 +1,13 @@
1
1
  import { JsonObject } from "@matreshka/shared/types/json";
2
- import { BehaviorSubject } from "rxjs";
2
+ import { BehaviorSubject, Observable } from "rxjs";
3
3
  import { Paths, PathValue } from "ts-essentials";
4
4
  import { ZodObject } from "zod/v4";
5
5
  import type { Client } from "../client";
6
6
  import { ContextRef } from "./context-ref";
7
+ /** Частичное обновление данных контекста по dotted-путям (см. {@link Context.set}). */
8
+ export type ContextPathPatch<T extends JsonObject> = Partial<{
9
+ [K in Paths<T>]: PathValue<T, K>;
10
+ }>;
7
11
  /**
8
12
  * Контекст данных, связанных с клиентом.
9
13
  *
@@ -16,7 +20,7 @@ export declare class Context<T extends JsonObject> {
16
20
  /** Уникальный идентификатор контекста */
17
21
  readonly id: `${string}-${string}-${string}-${string}-${string}`;
18
22
  /** Реактивное хранилище данных контекста. */
19
- data$?: BehaviorSubject<T>;
23
+ protected data$?: BehaviorSubject<T>;
20
24
  /** Схема валидации данных контекста */
21
25
  readonly schema?: ZodObject;
22
26
  /** Флаг, указывающий, что контекст должен быть инициализирован при авторизации клиента */
@@ -28,7 +32,7 @@ export declare class Context<T extends JsonObject> {
28
32
  readonly persistent: boolean;
29
33
  /** Реактивное хранилище инициализации контекста */
30
34
  private _init$;
31
- readonly init$: import("rxjs").Observable<void>;
35
+ readonly init$: Observable<void>;
32
36
  /**
33
37
  * Отслеживает, было ли изменение данных инициировано клиентом.
34
38
  * Если да — синхронизация с клиентом не требуется.
@@ -42,6 +46,7 @@ export declare class Context<T extends JsonObject> {
42
46
  private dataSubscription?;
43
47
  private clientSubscriptions;
44
48
  private assertNotDestroyed;
49
+ private assertInitialized;
45
50
  /** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
46
51
  private reportInitFailureToClients;
47
52
  /**
@@ -85,18 +90,45 @@ export declare class Context<T extends JsonObject> {
85
90
  * Возвращает значение из контекста по указанному пути.
86
91
  *
87
92
  * Путь может содержать плейсхолдеры, которые будут заменены актуальными значениями.
93
+ * Объекты и массивы — **копия** ({@link structuredClone}); in-place мутация результата
94
+ * не меняет контекст. Для снимка всего `T` — {@link snapshot}.
88
95
  *
89
96
  * @param path Строка с путём до значения.
90
97
  * @returns Значение по заданному пути или undefined.
91
98
  */
92
- value<K extends Paths<T>>(path: K): PathValue<T, K>;
93
- setValue<K extends Paths<T>>(path: K, value: PathValue<T, K>): void;
99
+ get<K extends Paths<T>>(path: K): PathValue<T, K>;
94
100
  /**
95
- * После мутаций объекта из `data$!.getValue()` in-place без вызовов `next()`
96
- * подписчики и клиенты не получают обновление. Метод публикует в поток глубокую
97
- * копию текущего состояния и запускает обычную цепочку (diff → сообщения клиенту).
101
+ * Частичное обновление данных по dotted-путям одним вызовом `next`.
102
+ *
103
+ * Предпочтительный способ правки нескольких полей на BFF. Ключ с явным
104
+ * `undefined` применяется (отличие от отсутствующего ключа в patch).
105
+ * Для целого снимка после load — {@link replace}.
106
+ */
107
+ set(patch: ContextPathPatch<T>): void;
108
+ /**
109
+ * Полная замена корня контекста (результат load, `{ ...loaded, field }`).
110
+ *
111
+ * Не merge patch: переданный объект становится новым состоянием целиком.
112
+ */
113
+ replace(data: T): void;
114
+ /**
115
+ * Глубокая копия всего `T` (structured clone корня).
116
+ *
117
+ * Для одного поля — {@link get}. Нужен, когда на время async нужен отсоединённый
118
+ * снимок всего состояния, а не ссылка на живые данные.
119
+ */
120
+ snapshot(): T;
121
+ /**
122
+ * Read-only поток данных контекста для подписок и RxJS-операторов.
123
+ *
124
+ * Если {@link init} ещё не создал хранилище, подписка **ждёт** успешного init
125
+ * ({@link init$}), затем ведёт себя как после init. При {@link destroy} до init
126
+ * поток завершается без эмиссий.
127
+ *
128
+ * После подключения сразу эмитит текущее состояние, затем каждое обновление
129
+ * через {@link set}, {@link replace} и т.п.
98
130
  */
99
- emitAfterInPlaceMutation(): void;
131
+ watch(): Observable<T>;
100
132
  /**
101
133
 
102
134
  * @param path Путь до значения.
@@ -107,7 +139,7 @@ export declare class Context<T extends JsonObject> {
107
139
  * Ссылка на значение в **этом** контексте по пути, который задаётся **во втором**
108
140
  * контексте строкой и меняется во времени.
109
141
  *
110
- * В отличие от прямого чтения `other.value()` при создании ссылки, в путь записывается
142
+ * В отличие от прямого чтения `other.get()` при создании ссылки, в путь записывается
111
143
  * только плейсхолдер `@{<id контекста other>.<путь other>}` (см. `ContextRef.toString`).
112
144
  * При каждом обращении `Context.value` подставляет актуальное значение поля `other`;
113
145
  * это уже строка-путь относительно корня текущего контекста (например `cards.1.balance`).
@@ -14,6 +14,13 @@ const objects_diff_1 = require("../utils/objects-diff");
14
14
  const replace_context_keys_1 = require("../utils/replace-context-keys");
15
15
  const set_object_property_1 = require("../utils/set-object-property");
16
16
  const context_ref_1 = require("./context-ref");
17
+ /** Отделяет чтение через {@link Context.get} от живого дерева в хранилище. */
18
+ function cloneGetResult(value) {
19
+ if (value !== null && typeof value === "object") {
20
+ return structuredClone(value);
21
+ }
22
+ return value;
23
+ }
17
24
  /** Глобальный реестр контекстов: lookup по id, привязки к клиентам, учёт init. */
18
25
  const contextRegistry = new Map();
19
26
  function registerContext(context) {
@@ -70,6 +77,11 @@ class Context {
70
77
  throw new Error(`Context ${this.id} has been destroyed`);
71
78
  }
72
79
  }
80
+ assertInitialized() {
81
+ if (!this.data$) {
82
+ throw new Error(`Context ${this.id} is not initialized`);
83
+ }
84
+ }
73
85
  /** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
74
86
  reportInitFailureToClients(error) {
75
87
  getRegistryEntry(this.id)?.clients.forEach((_, client) => {
@@ -202,7 +214,7 @@ class Context {
202
214
  (0, set_object_property_1.setObjectProperty)(data, change.key, change.value);
203
215
  });
204
216
  this.dataChangedByClient = client;
205
- this.data$.next(data);
217
+ this.replace(data);
206
218
  return;
207
219
  }
208
220
  })));
@@ -302,27 +314,78 @@ class Context {
302
314
  void this.initPromise.catch(() => { });
303
315
  return this.initPromise;
304
316
  }
305
- value(path) {
317
+ get(path) {
306
318
  this.assertNotDestroyed();
307
- return (0, fetch_from_object_1.fetchFromObject)(this.data$.getValue(), (0, replace_context_keys_1.replaceContextKeys)(path, getContextById));
319
+ this.assertInitialized();
320
+ const value = (0, fetch_from_object_1.fetchFromObject)(this.data$.getValue(), (0, replace_context_keys_1.replaceContextKeys)(path, getContextById));
321
+ return cloneGetResult(value);
308
322
  }
309
- setValue(path, value) {
323
+ /**
324
+ * Частичное обновление данных по dotted-путям одним вызовом `next`.
325
+ *
326
+ * Предпочтительный способ правки нескольких полей на BFF. Ключ с явным
327
+ * `undefined` применяется (отличие от отсутствующего ключа в patch).
328
+ * Для целого снимка после load — {@link replace}.
329
+ */
330
+ set(patch) {
310
331
  this.assertNotDestroyed();
332
+ this.assertInitialized();
311
333
  const data = this.data$.getValue();
312
- (0, set_object_property_1.setObjectProperty)(data, path, value);
334
+ for (const path of Object.keys(patch)) {
335
+ // hasOwnProperty: «loading: undefined» пишем, пропущенный ключ — не трогаем.
336
+ if (Object.prototype.hasOwnProperty.call(patch, path)) {
337
+ (0, set_object_property_1.setObjectProperty)(data, path, patch[path]);
338
+ }
339
+ }
313
340
  this.data$.next(data);
314
341
  }
315
342
  /**
316
- * После мутаций объекта из `data$!.getValue()` in-place без вызовов `next()`
317
- * подписчики и клиенты не получают обновление. Метод публикует в поток глубокую
318
- * копию текущего состояния и запускает обычную цепочку (diff → сообщения клиенту).
343
+ * Полная замена корня контекста (результат load, `{ ...loaded, field }`).
344
+ *
345
+ * Не merge patch: переданный объект становится новым состоянием целиком.
319
346
  */
320
- emitAfterInPlaceMutation() {
347
+ replace(data) {
321
348
  this.assertNotDestroyed();
322
- if (!this.data$) {
323
- return;
349
+ this.assertInitialized();
350
+ this.data$.next(data);
351
+ }
352
+ /**
353
+ * Глубокая копия всего `T` (structured clone корня).
354
+ *
355
+ * Для одного поля — {@link get}. Нужен, когда на время async нужен отсоединённый
356
+ * снимок всего состояния, а не ссылка на живые данные.
357
+ */
358
+ snapshot() {
359
+ this.assertNotDestroyed();
360
+ this.assertInitialized();
361
+ return structuredClone(this.data$.getValue());
362
+ }
363
+ /**
364
+ * Read-only поток данных контекста для подписок и RxJS-операторов.
365
+ *
366
+ * Если {@link init} ещё не создал хранилище, подписка **ждёт** успешного init
367
+ * ({@link init$}), затем ведёт себя как после init. При {@link destroy} до init
368
+ * поток завершается без эмиссий.
369
+ *
370
+ * После подключения сразу эмитит текущее состояние, затем каждое обновление
371
+ * через {@link set}, {@link replace} и т.п.
372
+ */
373
+ watch() {
374
+ this.assertNotDestroyed();
375
+ // asObservable() — без .next у подписчиков; тот же поток, что у внутреннего Subject.
376
+ const connect = () => {
377
+ if (this.destroyed || !this.data$) {
378
+ // destroy до init: init$ уже complete, подписчик не должен висеть.
379
+ return rxjs_1.EMPTY;
380
+ }
381
+ return this.data$.asObservable();
382
+ };
383
+ // init уже создал Subject (в т.ч. промежуточный `{}` во время await load).
384
+ if (this.data$) {
385
+ return connect();
324
386
  }
325
- this.data$.next(structuredClone(this.data$.getValue()));
387
+ // boot() до init(): ждём успешный init, затем обычные эмиссии BehaviorSubject.
388
+ return this.init$.pipe((0, rxjs_1.take)(1), (0, rxjs_1.switchMap)(() => connect()));
326
389
  }
327
390
  /**
328
391
 
@@ -337,7 +400,7 @@ class Context {
337
400
  * Ссылка на значение в **этом** контексте по пути, который задаётся **во втором**
338
401
  * контексте строкой и меняется во времени.
339
402
  *
340
- * В отличие от прямого чтения `other.value()` при создании ссылки, в путь записывается
403
+ * В отличие от прямого чтения `other.get()` при создании ссылки, в путь записывается
341
404
  * только плейсхолдер `@{<id контекста other>.<путь other>}` (см. `ContextRef.toString`).
342
405
  * При каждом обращении `Context.value` подставляет актуальное значение поля `other`;
343
406
  * это уже строка-путь относительно корня текущего контекста (например `cards.1.balance`).
@@ -9,7 +9,7 @@ import { ContextRef, ContextRefValue } from "../context/context-ref";
9
9
  * @example
10
10
  * ```ts
11
11
  * function bindAmount(ref: ContextValueRef<number | undefined>) {
12
- * ref.value(); // number | undefined
12
+ * ref.get(); // number | undefined
13
13
  * }
14
14
  *
15
15
  * bindAmount(pageContext.ref("amount"));
@@ -17,8 +17,8 @@ import { ContextRef, ContextRefValue } from "../context/context-ref";
17
17
  */
18
18
  export type ContextValueRef<ValueType> = ContextRef<any, any> & {
19
19
  readonly __valueType?: ValueType;
20
- value(): ValueType;
21
- setValue(value: ValueType): void;
20
+ get(): ValueType;
21
+ set(value: ValueType): void;
22
22
  };
23
23
  /**
24
24
  * Ref `R` совместим с ожидаемым типом значения `ValueType` (проверка на call site).
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.replaceContextKeys = replaceContextKeys;
4
- const fetch_from_object_1 = require("@matreshka/shared/utils/fetch-from-object");
5
4
  const parse_context_path_1 = require("./parse-context-path");
6
5
  /**
7
6
  * Заменяет плейсхолдеры вида `{ключ}` в строке значениями из объекта контекста.
@@ -27,7 +26,7 @@ function replaceContextKeys(str, resolveContext) {
27
26
  if (!context.inited()) {
28
27
  throw new Error(`Context ${pathInfo.contextId} not initialized`);
29
28
  }
30
- const value = (0, fetch_from_object_1.fetchFromObject)(context.data$.getValue(), pathInfo.key);
29
+ const value = context.get(pathInfo.key);
31
30
  str = replaceAll(str, `@{${path}}`, value ?? defaultValue);
32
31
  });
33
32
  const restContextKeys = findContextKeys(str);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@matreshka/bff",
3
- "version": "0.20.0",
3
+ "version": "0.21.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",