@matreshka/bff 0.33.0 → 0.34.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.
@@ -48,7 +48,10 @@ class Board extends component_1.Component {
48
48
  this.itemsSlot.source = itemsSlot.source;
49
49
  this.itemsSlot.itemLists = itemsSlot.itemLists;
50
50
  (0, item_list_1.attachItemListsToHost)(this, "items", this.itemsSlot);
51
- this.itemListHostAdapter = (0, item_list_1.createItemListHostAdapter)(() => this.instances, (slot) => (slot === "items" ? this.itemsSlot : undefined));
51
+ this.itemListHostAdapter = (0, item_list_1.createItemListHostAdapter)(() => this.instances, (slot) => (slot === "items" ? this.itemsSlot : undefined), "items");
52
+ this.destroyInstance$.subscribe((released) => {
53
+ this.itemListHostAdapter.releaseHostInstance(released);
54
+ });
52
55
  if (config.onCenterChange) {
53
56
  const actions = config.onCenterChange;
54
57
  this.bindActions("center-change", actions);
@@ -100,7 +103,7 @@ class Board extends component_1.Component {
100
103
  instance = this.createInstance();
101
104
  }
102
105
  const result = super.serialize(instance);
103
- const items = (0, item_list_1.flattenNestedItemsForSerialize)(this.itemsSlot, instance);
106
+ const items = this.itemListHostAdapter.serializeSlot(instance);
104
107
  return {
105
108
  ...result,
106
109
  class: server_component_class_1.ServerComponentClass.Board,
@@ -107,6 +107,8 @@ export declare class ForEach<RefType extends AnySchemaContextRef, ComponentType
107
107
  *
108
108
  * @param forEachInstance Instance ForEach на клиенте (связка client + entry + id).
109
109
  */
110
+ /** Ключ на wire: значение `track` без внутреннего префикса индексного контекста. */
111
+ private trackKey;
110
112
  private getInstanceState;
111
113
  /**
112
114
  * Снимает instances элементов списка и удаляет состояние для одного instance ForEach.
@@ -114,45 +116,40 @@ export declare class ForEach<RefType extends AnySchemaContextRef, ComponentType
114
116
  * @param forEachInstance Instance ForEach, инстанс которого прекращено.
115
117
  */
116
118
  private releaseInstanceState;
119
+ /** Снимает instances, созданные одной сериализацией слота. */
120
+ private releaseTrackedInstances;
117
121
  /**
118
- * Снимает instances дочерних компонентов элементов, созданные при последнем preload/sync
119
- * для конкретного instance ForEach.
122
+ * Удаляет слоты, которых больше нет в массиве, и снимает только их instances.
120
123
  *
121
- * @param forEachInstance Instance ForEach, для которого снимаются дочерние instances.
124
+ * @param currentTrackKeys Актуальные значения `track`.
125
+ * @param state Состояние одного instance ForEach.
122
126
  */
123
- private releaseItemSyncInstances;
127
+ private evictRemovedSlots;
124
128
  /**
125
- * Удаляет из кэша элементы, которых больше нет в данных списка.
129
+ * Сериализует слот один раз и запоминает payload вместе с instances.
126
130
  *
127
- * @param currentItemIds Актуальные ключи элементов после `track`.
128
- * @param cache Кэш generator для конкретного instance ForEach.
131
+ * @param tree Узлы элемента из кэша generator.
132
+ * @param state Состояние instance ForEach.
133
+ * @param trackKey Значение `track` элемента.
134
+ * @returns Конфиги строки для клиента.
129
135
  */
130
- private evictRemovedItemCaches;
136
+ private serializeSlotOnce;
131
137
  /**
132
- * Сериализует слоты элементов списка и запоминает созданные instances для последующего снятия.
138
+ * Собирает diff списка: полный порядок ключей и конфиги только новых ключей.
139
+ * Индексный контекст обновляется для всех элементов, уже отданные слоты не сериализуются.
133
140
  *
134
- * @param components Слоты по одному на элемент (узел или массив узлов).
135
- * @param forEachInstance Instance ForEach, в контексте которого выполняется сериализация.
136
- * @returns Сериализованные конфиги для клиента.
141
+ * @param forEachInstance Instance ForEach, для которого строится payload.
142
+ * @returns Payload preload и `ForEachSyncComponentsMessage`.
137
143
  */
138
- private serializeItemsWithTracking;
139
- /**
140
- * Строит дерево компонентов по текущему значению ref: обновляет индексы в
141
- * {@link componentContext}, берёт узлы из кэша instance ForEach или вызывает `generator`.
142
- *
143
- * @param forEachInstance Instance ForEach, для которого строится дерево элементов.
144
- * @returns Слоты элементов в порядке следования в массиве данных.
145
- */
146
- private generateComponents;
144
+ private buildSyncPayload;
147
145
  /**
148
146
  * Синхронизирует элементы списка с клиентом для одного instance ForEach.
149
147
  *
150
148
  * @param forEachInstance Instance ForEach на клиенте.
151
- * @param currentItemIds Актуальные ключи элементов списка.
152
149
  */
153
150
  private syncForEachInstance;
154
151
  /**
155
- * Отправляет клиенту актуальные конфиги элементов (`ForEachSyncComponentsMessage`).
152
+ * Отправляет клиенту порядок ключей и конфиги новых элементов (`ForEachSyncComponentsMessage`).
156
153
  * Вызывается при onShow и при изменении массива в ref (добавление, удаление, порядок).
157
154
  *
158
155
  * @param onlyIfChanged Если `true`, sync пропускается, когда не изменился набор `track`-ключей.
@@ -5,7 +5,6 @@ const server_component_class_1 = require("@matreshka/client-bff-protocol/enums/s
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
7
  const core_1 = require("../core");
8
- const serialize_component_tree_1 = require("../core/utils/serialize-component-tree");
9
8
  const track_created_instances_1 = require("../core/utils/track-created-instances");
10
9
  const component_1 = require("./component");
11
10
  /** Возвращает массив элементов списка из ref; не-массив даёт пустой массив. */
@@ -84,12 +83,16 @@ class ForEach extends component_1.Component {
84
83
  *
85
84
  * @param forEachInstance Instance ForEach на клиенте (связка client + entry + id).
86
85
  */
86
+ /** Ключ на wire: значение `track` без внутреннего префикса индексного контекста. */
87
+ trackKey(item) {
88
+ return this.config.track(item);
89
+ }
87
90
  getInstanceState(forEachInstance) {
88
91
  let state = this.instanceStates.get(forEachInstance);
89
92
  if (!state) {
90
93
  state = {
91
- itemSyncInstances: [],
92
94
  componentsCache: new Map(),
95
+ serializedByKey: new Map(),
93
96
  };
94
97
  this.instanceStates.set(forEachInstance, state);
95
98
  }
@@ -101,108 +104,126 @@ class ForEach extends component_1.Component {
101
104
  * @param forEachInstance Instance ForEach, инстанс которого прекращено.
102
105
  */
103
106
  releaseInstanceState(forEachInstance) {
104
- this.releaseItemSyncInstances(forEachInstance);
107
+ const state = this.instanceStates.get(forEachInstance);
108
+ if (state) {
109
+ for (const slot of state.serializedByKey.values()) {
110
+ this.releaseTrackedInstances(slot.instances);
111
+ }
112
+ }
105
113
  this.instanceStates.delete(forEachInstance);
106
114
  }
107
- /**
108
- * Снимает instances дочерних компонентов элементов, созданные при последнем preload/sync
109
- * для конкретного instance ForEach.
110
- *
111
- * @param forEachInstance Instance ForEach, для которого снимаются дочерние instances.
112
- */
113
- releaseItemSyncInstances(forEachInstance) {
114
- const state = this.instanceStates.get(forEachInstance);
115
- if (!state || state.itemSyncInstances.length === 0) {
115
+ /** Снимает instances, созданные одной сериализацией слота. */
116
+ releaseTrackedInstances(instances) {
117
+ if (instances.length === 0) {
116
118
  return;
117
119
  }
118
120
  const byComponent = new Map();
119
- for (const instance of state.itemSyncInstances) {
121
+ for (const instance of instances) {
120
122
  const component = instance.component;
121
123
  const list = byComponent.get(component) ?? [];
122
124
  list.push(instance);
123
125
  byComponent.set(component, list);
124
126
  }
125
- for (const [component, instances] of byComponent) {
126
- component.releaseInstances(instances);
127
+ for (const [component, componentInstances] of byComponent) {
128
+ component.releaseInstances(componentInstances);
127
129
  }
128
- state.itemSyncInstances = [];
129
130
  }
130
131
  /**
131
- * Удаляет из кэша элементы, которых больше нет в данных списка.
132
+ * Удаляет слоты, которых больше нет в массиве, и снимает только их instances.
132
133
  *
133
- * @param currentItemIds Актуальные ключи элементов после `track`.
134
- * @param cache Кэш generator для конкретного instance ForEach.
134
+ * @param currentTrackKeys Актуальные значения `track`.
135
+ * @param state Состояние одного instance ForEach.
135
136
  */
136
- evictRemovedItemCaches(currentItemIds, cache) {
137
- for (const itemId of cache.keys()) {
138
- if (!currentItemIds.has(itemId)) {
139
- cache.delete(itemId);
137
+ evictRemovedSlots(currentTrackKeys, state) {
138
+ // Копия ключей: ниже удаляем записи прямо из Map.
139
+ // Слот уже отдан клиенту — снимаем его instances и оба кэша.
140
+ // Ключ дерева — `id` + track, как в {@link itemId}: так strictRef не путает его с индексом.
141
+ for (const trackKey of [...state.serializedByKey.keys()]) {
142
+ if (currentTrackKeys.has(trackKey)) {
143
+ continue;
144
+ }
145
+ const slot = state.serializedByKey.get(trackKey);
146
+ if (slot) {
147
+ this.releaseTrackedInstances(slot.instances);
148
+ }
149
+ state.serializedByKey.delete(trackKey);
150
+ state.componentsCache.delete("id" + trackKey);
151
+ }
152
+ // Дерево без сериализованного слота (generator успел отработать, serialize — нет).
153
+ // slice(2) снимает префикс `id` и возвращает значение track.
154
+ for (const itemId of [...state.componentsCache.keys()]) {
155
+ if (!currentTrackKeys.has(itemId.slice(2))) {
156
+ state.componentsCache.delete(itemId);
140
157
  }
141
158
  }
142
159
  }
143
160
  /**
144
- * Сериализует слоты элементов списка и запоминает созданные instances для последующего снятия.
161
+ * Сериализует слот один раз и запоминает payload вместе с instances.
145
162
  *
146
- * @param components Слоты по одному на элемент (узел или массив узлов).
147
- * @param forEachInstance Instance ForEach, в контексте которого выполняется сериализация.
148
- * @returns Сериализованные конфиги для клиента.
163
+ * @param tree Узлы элемента из кэша generator.
164
+ * @param state Состояние instance ForEach.
165
+ * @param trackKey Значение `track` элемента.
166
+ * @returns Конфиги строки для клиента.
149
167
  */
150
- serializeItemsWithTracking(components, forEachInstance) {
151
- this.releaseItemSyncInstances(forEachInstance);
152
- const state = this.getInstanceState(forEachInstance);
153
- const { result, instances } = (0, track_created_instances_1.runWithCreatedInstanceTracking)(() => (0, serialize_component_tree_1.serializeForEachSlots)(components));
154
- state.itemSyncInstances = instances;
168
+ serializeSlotOnce(tree, state, trackKey) {
169
+ const { result, instances } = (0, track_created_instances_1.runWithCreatedInstanceTracking)(() => (0, core_1.serializeComponentList)(tree));
170
+ state.serializedByKey.set(trackKey, { components: result, instances });
155
171
  return result;
156
172
  }
157
173
  /**
158
- * Строит дерево компонентов по текущему значению ref: обновляет индексы в
159
- * {@link componentContext}, берёт узлы из кэша instance ForEach или вызывает `generator`.
174
+ * Собирает diff списка: полный порядок ключей и конфиги только новых ключей.
175
+ * Индексный контекст обновляется для всех элементов, уже отданные слоты не сериализуются.
160
176
  *
161
- * @param forEachInstance Instance ForEach, для которого строится дерево элементов.
162
- * @returns Слоты элементов в порядке следования в массиве данных.
177
+ * @param forEachInstance Instance ForEach, для которого строится payload.
178
+ * @returns Payload preload и `ForEachSyncComponentsMessage`.
163
179
  */
164
- generateComponents(forEachInstance) {
165
- const cache = this.getInstanceState(forEachInstance).componentsCache;
166
- const value = getForEachValue(this.config.ref);
167
- const itemsCheckSum = value.map(this.config.track).join("|");
168
- this.lastItemsCheckSum = itemsCheckSum;
169
- const items = Array.isArray(value) ? value : [];
180
+ buildSyncPayload(forEachInstance) {
181
+ const state = this.getInstanceState(forEachInstance);
182
+ const items = getForEachValue(this.config.ref);
183
+ const order = items.map((item) => this.trackKey(item));
184
+ this.lastItemsCheckSum = order.join("|");
170
185
  const store = {};
171
186
  for (let index = 0; index < items.length; index++) {
172
187
  store[this.itemId(items[index])] = { index: `${index}` };
173
188
  }
174
189
  this.componentContext.replace(store);
175
- return items.map((item) => {
176
- const itemId = this.itemId(item);
177
- if (cache.has(itemId)) {
178
- return cache.get(itemId);
190
+ this.evictRemovedSlots(new Set(order), state);
191
+ const upserts = [];
192
+ for (let index = 0; index < items.length; index++) {
193
+ const trackKey = order[index];
194
+ if (state.serializedByKey.has(trackKey)) {
195
+ continue;
196
+ }
197
+ const itemId = this.itemId(items[index]);
198
+ let tree = state.componentsCache.get(itemId);
199
+ if (!tree) {
200
+ tree = this.generateItemComponents({
201
+ component: this,
202
+ ref: createForEachItemLink(this.config.ref, this.componentContext.ref(`${itemId}.index`)),
203
+ });
204
+ state.componentsCache.set(itemId, tree);
179
205
  }
180
- const result = this.generateItemComponents({
181
- component: this,
182
- ref: createForEachItemLink(this.config.ref, this.componentContext.ref(`${itemId}.index`)),
206
+ upserts.push({
207
+ key: trackKey,
208
+ components: this.serializeSlotOnce(tree, state, trackKey),
183
209
  });
184
- cache.set(itemId, result);
185
- return result;
186
- });
210
+ }
211
+ return { order, upserts };
187
212
  }
188
213
  /**
189
214
  * Синхронизирует элементы списка с клиентом для одного instance ForEach.
190
215
  *
191
216
  * @param forEachInstance Instance ForEach на клиенте.
192
- * @param currentItemIds Актуальные ключи элементов списка.
193
217
  */
194
- syncForEachInstance(forEachInstance, currentItemIds) {
195
- this.evictRemovedItemCaches(currentItemIds, this.getInstanceState(forEachInstance).componentsCache);
218
+ syncForEachInstance(forEachInstance) {
196
219
  (0, core_1.runWithClient)(forEachInstance.client, () => {
197
220
  (0, core_1.runWithEntryContext)(forEachInstance.entry, forEachInstance.client, () => {
198
- const components = this.generateComponents(forEachInstance);
199
- const serializedComponents = this.serializeItemsWithTracking(components, forEachInstance);
200
- forEachInstance.client.outcomingMessage$.next(new for_each_sync_components_message_1.ForEachSyncComponentsMessage(forEachInstance.id, serializedComponents));
221
+ forEachInstance.client.outcomingMessage$.next(new for_each_sync_components_message_1.ForEachSyncComponentsMessage(forEachInstance.id, this.buildSyncPayload(forEachInstance)));
201
222
  });
202
223
  });
203
224
  }
204
225
  /**
205
- * Отправляет клиенту актуальные конфиги элементов (`ForEachSyncComponentsMessage`).
226
+ * Отправляет клиенту порядок ключей и конфиги новых элементов (`ForEachSyncComponentsMessage`).
206
227
  * Вызывается при onShow и при изменении массива в ref (добавление, удаление, порядок).
207
228
  *
208
229
  * @param onlyIfChanged Если `true`, sync пропускается, когда не изменился набор `track`-ключей.
@@ -216,9 +237,8 @@ class ForEach extends component_1.Component {
216
237
  if (this.instances.length === 0) {
217
238
  return;
218
239
  }
219
- const currentItemIds = new Set(value.map((item) => this.itemId(item)));
220
240
  for (const forEachInstance of this.instances) {
221
- this.syncForEachInstance(forEachInstance, currentItemIds);
241
+ this.syncForEachInstance(forEachInstance);
222
242
  }
223
243
  }
224
244
  /**
@@ -327,7 +347,7 @@ class ForEach extends component_1.Component {
327
347
  if (this.preload && this.properties.ref.context.inited()) {
328
348
  (0, core_1.runWithClient)(instance.client, () => {
329
349
  (0, core_1.runWithEntryContext)(instance.entry, instance.client, () => {
330
- extra.components = this.serializeItemsWithTracking(this.generateComponents(instance), instance);
350
+ extra.components = this.buildSyncPayload(instance);
331
351
  });
332
352
  });
333
353
  }
@@ -1,11 +1,20 @@
1
+ import type { NestedItemBase } from "@matreshka/client-bff-protocol/types/nested-item-base";
2
+ import type { ServerComponentConfig } from "@matreshka/client-bff-protocol/types/server-component-config";
1
3
  import type { ComponentInstance, ComponentTreeNode } from "../../core";
2
4
  import type { ItemList } from "./item-list";
3
5
  import type { NestedItemTreeNode } from "./types";
4
- export declare function isItemList(value: unknown): value is ItemList<any, any>;
5
- export declare function flattenNestedItems<TItem extends NestedItemTreeNode, TSerialized extends TItem & {
6
+ /** Статический элемент слота, сериализованный один раз на host-instance. */
7
+ export type CachedStaticNestedItem = {
8
+ item: NestedItemBase;
9
+ instances: ComponentInstance[];
10
+ };
11
+ export type StaticNestedItemCache = Map<string, CachedStaticNestedItem>;
12
+ export type SerializedNestedSlotItem<TItem extends NestedItemTreeNode> = Omit<TItem, "component"> & {
6
13
  id: string;
7
- component: import("@matreshka/client-bff-protocol/types/server-component-config").ServerComponentConfig;
8
- }>(source: (TItem | ItemList<any, TItem>)[] | undefined, instance: ComponentInstance): TSerialized[];
14
+ component: ServerComponentConfig;
15
+ };
16
+ export declare function isItemList(value: unknown): value is ItemList<any, any>;
17
+ export declare function flattenNestedItems<TItem extends NestedItemTreeNode>(source: (TItem | ItemList<any, TItem>)[] | undefined, instance: ComponentInstance, staticCache?: StaticNestedItemCache): SerializedNestedSlotItem<TItem>[];
9
18
  export declare function collectNestedComponentsFromSource<TItem extends NestedItemTreeNode>(source: (TItem | ItemList<any, TItem>)[] | undefined): ComponentTreeNode[];
10
19
  export declare function releaseItemListInstances(instances: ComponentInstance[]): void;
11
20
  export declare function newItemListSegmentId(): string;
@@ -46,25 +46,31 @@ function isItemList(value) {
46
46
  value !== null &&
47
47
  value.isItemList === true);
48
48
  }
49
- function flattenNestedItems(source, instance) {
49
+ function flattenNestedItems(source, instance, staticCache) {
50
50
  const result = [];
51
51
  for (const entry of source ?? []) {
52
52
  if (isItemList(entry)) {
53
53
  result.push(...entry.buildItems(instance));
54
54
  }
55
55
  else {
56
- result.push(serializeStaticNestedItem(entry, instance));
56
+ result.push(serializeStaticNestedItem(entry, instance, staticCache));
57
57
  }
58
58
  }
59
59
  return result;
60
60
  }
61
- function serializeStaticNestedItem(entry, instance) {
61
+ function serializeStaticNestedItem(entry, instance, staticCache) {
62
+ const id = entry.component.id;
63
+ const cached = staticCache?.get(id);
64
+ if (cached) {
65
+ return cached.item;
66
+ }
62
67
  return (0, core_1.runWithClient)(instance.client, () => (0, core_1.runWithEntryContext)(instance.entry, instance.client, () => {
63
- const { result } = (0, track_created_instances_1.runWithCreatedInstanceTracking)(() => ({
68
+ const { result, instances } = (0, track_created_instances_1.runWithCreatedInstanceTracking)(() => ({
64
69
  ...entry,
65
- id: entry.component.id,
70
+ id,
66
71
  component: entry.component.serialize(),
67
72
  }));
73
+ staticCache?.set(id, { item: result, instances });
68
74
  return result;
69
75
  }));
70
76
  }
@@ -2,6 +2,10 @@ import type { ServerComponentConfig } from "@matreshka/client-bff-protocol/types
2
2
  import { AnySchemaContextRef, ComponentInstance, ComponentTreeNode } from "../../core";
3
3
  import type { ItemListHost } from "./item-list-host";
4
4
  import { type ItemListInitConfig, type NestedItemTreeNode } from "./types";
5
+ type SerializedItemListItem<ItemType extends NestedItemTreeNode> = Omit<ItemType, "component"> & {
6
+ id: string;
7
+ component: ServerComponentConfig;
8
+ };
5
9
  /**
6
10
  * Динамический сегмент nested-элементов (map markers / board items):
7
11
  * читает массив из `Context`, генерирует элементы и синхронизирует host через diff.
@@ -31,11 +35,10 @@ export declare class ItemList<RefType extends AnySchemaContextRef, ItemType exte
31
35
  onHostShow(): void;
32
36
  /** Вызывается host-кomponentом из onHide: отписка, когда host полностью скрыт. */
33
37
  onHostHide(): void;
34
- /** Сериализованные элементы сегмента для flatten / preload. */
35
- buildItems(instance: ComponentInstance): (Omit<ItemType, "component"> & {
36
- id: string;
37
- component: ServerComponentConfig;
38
- })[];
38
+ /** Сериализованные элементы сегмента для flatten / preload. Уже отданные id не сериализуются. */
39
+ buildItems(instance: ComponentInstance): SerializedItemListItem<ItemType>[];
40
+ /** Снимает кэш и instances сегмента, когда host-instance уничтожен. */
41
+ releaseHostInstance(instance: ComponentInstance): void;
39
42
  /**
40
43
  * Дерево nested-кomponentов для walk/registration:
41
44
  * из кэша активных instances или dry-run generator по текущему массиву.
@@ -52,11 +55,13 @@ export declare class ItemList<RefType extends AnySchemaContextRef, ItemType exte
52
55
  private itemCacheKey;
53
56
  /** Публичный id элемента для клиента (без префикса кэша). */
54
57
  private trackId;
55
- /** Lazy-init per-instance state (кэш строк и sync instances). */
58
+ /** Lazy-init per-instance state (кэш строк и уже отданные конфиги). */
56
59
  private getInstanceState;
57
- /** Освобождает временные instances, созданные при прошлой сериализации. */
58
- private releaseItemSyncInstances;
59
- /** Удаляет из кэша строки, которых больше нет в массиве Context. */
60
+ /** Сериализует элемент один раз и сохраняет instances до ухода ключа из массива. */
61
+ private serializeItemOnce;
62
+ /** Снимает instances элементов, которых больше нет в массиве. */
63
+ private evictSerializedItems;
64
+ /** Удаляет из кэша generator строки, которых больше нет в массиве Context. */
60
65
  private evictRemovedItemCaches;
61
66
  /**
62
67
  * Строит элементы сегмента для instance:
@@ -66,3 +71,4 @@ export declare class ItemList<RefType extends AnySchemaContextRef, ItemType exte
66
71
  }
67
72
  /** Factory для DSL: `itemList({ ref, track, generator, preload? })`. */
68
73
  export declare const itemList: <RefType extends AnySchemaContextRef, ItemType extends NestedItemTreeNode = NestedItemTreeNode>(config: ItemListInitConfig<RefType, ItemType>) => ItemList<RefType, ItemType>;
74
+ export {};
@@ -52,28 +52,43 @@ class ItemList {
52
52
  this.contextSubscription = undefined;
53
53
  }
54
54
  }
55
- /** Сериализованные элементы сегмента для flatten / preload. */
55
+ /** Сериализованные элементы сегмента для flatten / preload. Уже отданные id не сериализуются. */
56
56
  buildItems(instance) {
57
57
  if (!instance.client) {
58
58
  return [];
59
59
  }
60
60
  return (0, core_1.runWithClient)(instance.client, () => (0, core_1.runWithEntryContext)(instance.entry, instance.client, () => {
61
- this.releaseItemSyncInstances(instance);
62
61
  const items = this.generateItems(instance);
63
62
  // Индексы элементов живут во внутреннем контексте itemList (strictRef).
64
63
  // Без authorizeClient клиент не получит его и ref вида
65
64
  // `departments.@{…index}.name` резолвится в пустую строку.
66
65
  this.indexContext.authorizeClient(instance.client);
67
66
  const state = this.getInstanceState(instance);
68
- const { result, instances } = (0, track_created_instances_1.runWithCreatedInstanceTracking)(() => items.map(({ id, item }) => ({
69
- ...item,
70
- id,
71
- component: item.component.serialize(),
72
- })));
73
- state.itemSyncInstances = instances;
67
+ this.evictSerializedItems(new Set(items.map((entry) => entry.id)), state);
68
+ const result = [];
69
+ for (const { id, item } of items) {
70
+ const cached = state.serializedById.get(id);
71
+ if (cached) {
72
+ result.push(cached.item);
73
+ continue;
74
+ }
75
+ const serialized = this.serializeItemOnce(id, item, state);
76
+ result.push(serialized);
77
+ }
74
78
  return result;
75
79
  }));
76
80
  }
81
+ /** Снимает кэш и instances сегмента, когда host-instance уничтожен. */
82
+ releaseHostInstance(instance) {
83
+ const state = this.instanceStates.get(instance);
84
+ if (!state) {
85
+ return;
86
+ }
87
+ for (const slot of state.serializedById.values()) {
88
+ (0, flatten_nested_items_1.releaseItemListInstances)(slot.instances);
89
+ }
90
+ this.instanceStates.delete(instance);
91
+ }
77
92
  /**
78
93
  * Дерево nested-кomponentов для walk/registration:
79
94
  * из кэша активных instances или dry-run generator по текущему массиву.
@@ -143,31 +158,46 @@ class ItemList {
143
158
  trackId(item) {
144
159
  return this.config.track(item);
145
160
  }
146
- /** Lazy-init per-instance state (кэш строк и sync instances). */
161
+ /** Lazy-init per-instance state (кэш строк и уже отданные конфиги). */
147
162
  getInstanceState(instance) {
148
163
  let state = this.instanceStates.get(instance);
149
164
  if (!state) {
150
165
  state = {
151
- itemSyncInstances: [],
152
166
  itemsCache: new Map(),
167
+ serializedById: new Map(),
153
168
  };
154
169
  this.instanceStates.set(instance, state);
155
170
  }
156
171
  return state;
157
172
  }
158
- /** Освобождает временные instances, созданные при прошлой сериализации. */
159
- releaseItemSyncInstances(instance) {
160
- const state = this.instanceStates.get(instance);
161
- if (!state || state.itemSyncInstances.length === 0) {
162
- return;
173
+ /** Сериализует элемент один раз и сохраняет instances до ухода ключа из массива. */
174
+ serializeItemOnce(id, item, state) {
175
+ const { result, instances } = (0, track_created_instances_1.runWithCreatedInstanceTracking)(() => ({
176
+ ...item,
177
+ id,
178
+ component: item.component.serialize(),
179
+ }));
180
+ state.serializedById.set(id, { item: result, instances });
181
+ return result;
182
+ }
183
+ /** Снимает instances элементов, которых больше нет в массиве. */
184
+ evictSerializedItems(currentIds, state) {
185
+ for (const id of [...state.serializedById.keys()]) {
186
+ if (currentIds.has(id)) {
187
+ continue;
188
+ }
189
+ const slot = state.serializedById.get(id);
190
+ if (slot) {
191
+ (0, flatten_nested_items_1.releaseItemListInstances)(slot.instances);
192
+ }
193
+ state.serializedById.delete(id);
194
+ state.itemsCache.delete("id" + id);
163
195
  }
164
- (0, flatten_nested_items_1.releaseItemListInstances)(state.itemSyncInstances);
165
- state.itemSyncInstances = [];
166
196
  }
167
- /** Удаляет из кэша строки, которых больше нет в массиве Context. */
197
+ /** Удаляет из кэша generator строки, которых больше нет в массиве Context. */
168
198
  evictRemovedItemCaches(currentItemIds, instance) {
169
199
  const cache = this.getInstanceState(instance).itemsCache;
170
- for (const itemId of cache.keys()) {
200
+ for (const itemId of [...cache.keys()]) {
171
201
  if (!currentItemIds.has(itemId)) {
172
202
  cache.delete(itemId);
173
203
  }
@@ -180,6 +210,9 @@ class ItemList {
180
210
  generateItems(instance) {
181
211
  const cache = this.getInstanceState(instance).itemsCache;
182
212
  const value = (0, types_1.getItemListValue)(this.config.ref);
213
+ this.lastItemsCheckSum = value
214
+ .map((item) => this.config.track(item))
215
+ .join("|");
183
216
  const store = {};
184
217
  for (let index = 0; index < value.length; index++) {
185
218
  const cacheKey = this.itemCacheKey(value[index]);
@@ -1,6 +1,6 @@
1
1
  import type { ComponentInstance } from "../../core";
2
2
  import type { ComponentInitConfig } from "../component";
3
- import { flattenNestedItems } from "./flatten-nested-items";
3
+ import { type SerializedNestedSlotItem, type StaticNestedItemCache } from "./flatten-nested-items";
4
4
  import type { ItemList } from "./item-list";
5
5
  import type { ItemListHost } from "./item-list-host";
6
6
  import type { NestedItemTreeNode } from "./types";
@@ -24,13 +24,23 @@ export declare function attachItemListsToHost<TItem extends NestedItemTreeNode>(
24
24
  * `onShow` / `onHide` пробрасываются в `itemList.onHostShow()` / `onHostHide()`.
25
25
  */
26
26
  export declare function wireNestedItemsHostLifecycle(config: ComponentInitConfig<any>, itemLists: ItemList<any, any>[]): void;
27
+ export type ItemListHostAdapter<TItem extends NestedItemTreeNode = NestedItemTreeNode> = ItemListHost & {
28
+ /** Снимает кэш слота вместе с host-instance. */
29
+ releaseHostInstance(instance: ComponentInstance): void;
30
+ /**
31
+ * Flat-массив для первого ответа страницы.
32
+ * Помечает id как уже отданные, чтобы следующий sync не слал их снова.
33
+ * Сохраняет поля элемента (position, coordinates, …), не только NestedItemBase.
34
+ */
35
+ serializeSlot(instance: ComponentInstance): SerializedNestedSlotItem<TItem>[] | undefined;
36
+ };
27
37
  /**
28
- * Адаптер `ItemListHost` для map/board: отправляет клиенту
29
- * `NestedItemsSyncMessage` всем активным instances host-кomponenta.
38
+ * Адаптер `ItemListHost` для map/board: клиенту уходит порядок id
39
+ * и конфиги только тех элементов, которых у instance ещё нет.
30
40
  */
31
- export declare function createItemListHostAdapter<TItem extends NestedItemTreeNode>(getInstances: () => readonly ComponentInstance[], getSlotState: (slot: string) => NestedItemsSlotState<TItem> | undefined): ItemListHost;
41
+ export declare function createItemListHostAdapter<TItem extends NestedItemTreeNode>(getInstances: () => readonly ComponentInstance[], getSlotState: (slot: string) => NestedItemsSlotState<TItem> | undefined, slotName: string): ItemListHostAdapter<TItem>;
32
42
  /**
33
43
  * Сериализация slot'а в flat-массив для первого ответа страницы:
34
44
  * статика всегда включается, `itemList` — только с `preload: true` и готовыми данными.
35
45
  */
36
- export declare function flattenNestedItemsForSerialize<TItem extends NestedItemTreeNode>(state: NestedItemsSlotState<TItem> | undefined, instance: ComponentInstance): ReturnType<typeof flattenNestedItems<TItem, any>> | undefined;
46
+ export declare function flattenNestedItemsForSerialize<TItem extends NestedItemTreeNode>(state: NestedItemsSlotState<TItem> | undefined, instance: ComponentInstance, staticCache?: StaticNestedItemCache): SerializedNestedSlotItem<TItem>[] | undefined;
@@ -63,17 +63,44 @@ function wireNestedItemsHostLifecycle(config, itemLists) {
63
63
  });
64
64
  }
65
65
  /**
66
- * Адаптер `ItemListHost` для map/board: отправляет клиенту
67
- * `NestedItemsSyncMessage` всем активным instances host-кomponenta.
66
+ * Адаптер `ItemListHost` для map/board: клиенту уходит порядок id
67
+ * и конфиги только тех элементов, которых у instance ещё нет.
68
68
  */
69
- function createItemListHostAdapter(getInstances, getSlotState) {
69
+ function createItemListHostAdapter(getInstances, getSlotState, slotName) {
70
+ const caches = new Map();
71
+ const cacheFor = (instance) => {
72
+ let cache = caches.get(instance);
73
+ if (!cache) {
74
+ cache = { staticById: new Map(), sentIds: new Set() };
75
+ caches.set(instance, cache);
76
+ }
77
+ return cache;
78
+ };
79
+ const publish = (instance, slot, flat) => {
80
+ const cache = cacheFor(instance);
81
+ const order = flat.map((item) => item.id);
82
+ const nextIds = new Set(order);
83
+ for (const id of [...cache.staticById.keys()]) {
84
+ if (nextIds.has(id)) {
85
+ continue;
86
+ }
87
+ const cached = cache.staticById.get(id);
88
+ if (cached) {
89
+ (0, flatten_nested_items_1.releaseItemListInstances)(cached.instances);
90
+ }
91
+ cache.staticById.delete(id);
92
+ }
93
+ const upserts = flat.filter((item) => !cache.sentIds.has(item.id));
94
+ cache.sentIds = nextIds;
95
+ instance.client.outcomingMessage$.next(new nested_items_sync_message_1.NestedItemsSyncMessage(instance.id, { slot, order, upserts }));
96
+ };
70
97
  return {
71
98
  get hostInstances() {
72
99
  return getInstances();
73
100
  },
74
101
  syncNestedItems(slot, items) {
75
102
  for (const instance of getInstances().filter((i) => i.client)) {
76
- instance.client.outcomingMessage$.next(new nested_items_sync_message_1.NestedItemsSyncMessage(instance.id, { slot, items }));
103
+ publish(instance, slot, items);
77
104
  }
78
105
  },
79
106
  resyncNestedSlot(slot) {
@@ -82,9 +109,35 @@ function createItemListHostAdapter(getInstances, getSlotState) {
82
109
  return;
83
110
  }
84
111
  for (const instance of getInstances().filter((i) => i.client)) {
85
- const flat = (0, flatten_nested_items_1.flattenNestedItems)(state.source, instance);
86
- instance.client.outcomingMessage$.next(new nested_items_sync_message_1.NestedItemsSyncMessage(instance.id, { slot, items: flat }));
112
+ const cache = cacheFor(instance);
113
+ const flat = (0, flatten_nested_items_1.flattenNestedItems)(state.source, instance, cache.staticById);
114
+ publish(instance, slot, flat);
115
+ }
116
+ },
117
+ releaseHostInstance(instance) {
118
+ const state = getSlotState(slotName);
119
+ for (const itemList of state?.itemLists ?? []) {
120
+ itemList.releaseHostInstance(instance);
121
+ }
122
+ const cache = caches.get(instance);
123
+ if (cache) {
124
+ for (const cached of cache.staticById.values()) {
125
+ (0, flatten_nested_items_1.releaseItemListInstances)(cached.instances);
126
+ }
127
+ caches.delete(instance);
128
+ }
129
+ },
130
+ serializeSlot(instance) {
131
+ const state = getSlotState(slotName);
132
+ const cache = cacheFor(instance);
133
+ const flat = flattenNestedItemsForSerialize(state, instance, cache.staticById);
134
+ if (!flat) {
135
+ return undefined;
136
+ }
137
+ for (const item of flat) {
138
+ cache.sentIds.add(item.id);
87
139
  }
140
+ return flat;
88
141
  },
89
142
  };
90
143
  }
@@ -92,7 +145,7 @@ function createItemListHostAdapter(getInstances, getSlotState) {
92
145
  * Сериализация slot'а в flat-массив для первого ответа страницы:
93
146
  * статика всегда включается, `itemList` — только с `preload: true` и готовыми данными.
94
147
  */
95
- function flattenNestedItemsForSerialize(state, instance) {
148
+ function flattenNestedItemsForSerialize(state, instance, staticCache) {
96
149
  if (!state || state.source.length === 0) {
97
150
  return undefined;
98
151
  }
@@ -105,5 +158,5 @@ function flattenNestedItemsForSerialize(state, instance) {
105
158
  if (filteredSource.length === 0) {
106
159
  return undefined;
107
160
  }
108
- return (0, flatten_nested_items_1.flattenNestedItems)(filteredSource, instance);
161
+ return (0, flatten_nested_items_1.flattenNestedItems)(filteredSource, instance, staticCache);
109
162
  }
@@ -44,7 +44,10 @@ class Map extends component_1.Component {
44
44
  this.markersSlot.source = markersSlot.source;
45
45
  this.markersSlot.itemLists = markersSlot.itemLists;
46
46
  (0, item_list_1.attachItemListsToHost)(this, "markers", this.markersSlot);
47
- this.itemListHostAdapter = (0, item_list_1.createItemListHostAdapter)(() => this.instances, (slot) => (slot === "markers" ? this.markersSlot : undefined));
47
+ this.itemListHostAdapter = (0, item_list_1.createItemListHostAdapter)(() => this.instances, (slot) => (slot === "markers" ? this.markersSlot : undefined), "markers");
48
+ this.destroyInstance$.subscribe((released) => {
49
+ this.itemListHostAdapter.releaseHostInstance(released);
50
+ });
48
51
  if (config.onCenterChange) {
49
52
  const actions = config.onCenterChange;
50
53
  this.bindActions("center-change", actions);
@@ -94,7 +97,7 @@ class Map extends component_1.Component {
94
97
  instance = this.createInstance();
95
98
  }
96
99
  const result = super.serialize(instance);
97
- const markers = (0, item_list_1.flattenNestedItemsForSerialize)(this.markersSlot, instance);
100
+ const markers = this.itemListHostAdapter.serializeSlot(instance);
98
101
  return {
99
102
  ...result,
100
103
  class: server_component_class_1.ServerComponentClass.Map,
@@ -25,14 +25,14 @@ function assertClientUpdateSchemaSupported(schema, path = "") {
25
25
  function assertClientUpdateFieldSupported(schema, path) {
26
26
  const unwrapped = unwrapOptionalNullable(schema);
27
27
  if (unwrapped instanceof zod_1.z.ZodPipe) {
28
- const inner = unwrapped._def.in;
28
+ const inner = unwrapped.in;
29
29
  if (inner instanceof zod_1.z.ZodObject) {
30
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
31
  }
32
32
  return;
33
33
  }
34
34
  if (unwrapped instanceof zod_1.z.ZodObject) {
35
- const checks = unwrapped._def.checks;
35
+ const checks = unwrapped.def.checks;
36
36
  if (checks && checks.length > 0) {
37
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
38
  }
@@ -4,11 +4,12 @@ import { z } from "zod";
4
4
  import type { SetContext } from "../actions/set-context";
5
5
  import { AnySchemaContextRef, ContextRef, ContextRefValueType } from "../context/context-ref";
6
6
  import type { ContextUpdateDelivery } from "./context-update-delivery";
7
- /** Общая часть ref-типов по значению: маркер типа и чтение. */
7
+ /** Общая часть ref-типов по значению: маркер типа, чтение и запись. */
8
8
  type ValueRefBase<ValueType> = {
9
9
  readonly __valueType?: ValueType;
10
10
  get(): ValueType;
11
11
  set(value: ValueType): Observable<ContextUpdateDelivery>;
12
+ update(updater: (current: ValueType) => ValueType): Observable<ContextUpdateDelivery>;
12
13
  };
13
14
  /**
14
15
  * Ссылка на поле контекста с известным типом значения.
@@ -1,2 +1,9 @@
1
1
  import { z } from "zod";
2
- export declare function zodDeepPick(schema: z.ZodTypeAny, propertyPath: string): z.ZodTypeAny;
2
+ /**
3
+ * Схема конечного поля по dotted-пути клиентского patch.
4
+ *
5
+ * Элемент массива адресуется числовым сегментом (`meters.0.zones.0.value`).
6
+ * Индексом он считается только если текущий узел — `ZodArray`; у `ZodObject`
7
+ * тот же сегмент остаётся строковым ключом (`{ "0": z.string() }`).
8
+ */
9
+ export declare function zodDeepPick(schema: z.ZodType, propertyPath: string): z.ZodType;
@@ -8,68 +8,72 @@ 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) {
11
+ /**
12
+ * Узел схемы, по которому можно идти дальше по пути.
13
+ * Снимает optional/nullable и pipe к object/array (object-level transform).
14
+ */
15
+ function schemaForPathStep(schema) {
13
16
  let current = schema;
14
17
  for (;;) {
15
- if (isZodObject(current)) {
16
- return current;
17
- }
18
18
  if (current instanceof zod_1.z.ZodOptional || current instanceof zod_1.z.ZodNullable) {
19
19
  current = current.unwrap();
20
20
  continue;
21
21
  }
22
22
  if (current instanceof zod_1.z.ZodPipe) {
23
- const inner = current._def.in;
24
- if (isZodObject(inner)) {
25
- return inner;
23
+ const inner = current.in;
24
+ if (isZodObject(inner) || isZodArray(inner)) {
25
+ current = inner;
26
+ continue;
26
27
  }
27
28
  break;
28
29
  }
29
30
  break;
30
31
  }
32
+ return current;
33
+ }
34
+ /** Объектная shape для навигации по dotted-пути (без object-level pipe/transform). */
35
+ function objectShapeForPick(schema) {
36
+ const current = schemaForPathStep(schema);
37
+ if (isZodObject(current)) {
38
+ return current;
39
+ }
31
40
  throw Error("Not a zod object");
32
41
  }
33
42
  function pickObject(schema, path) {
34
43
  const objectSchema = objectShapeForPick(schema);
35
- const newSchema = objectSchema.shape?.[path];
44
+ const shape = objectSchema.shape;
45
+ const newSchema = shape[path];
36
46
  if (!newSchema)
37
47
  throw Error(
38
48
  // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
39
- `${path} does not exist on schema with keys: ${Object.keys(objectSchema.shape)}`);
49
+ `${path} does not exist on schema with keys: ${Object.keys(shape)}`);
40
50
  return newSchema;
41
51
  }
42
52
  function pickArray(schema) {
43
- if (!isZodArray(schema))
53
+ const current = schemaForPathStep(schema);
54
+ if (!isZodArray(current))
44
55
  throw Error("Not a Zod Array");
45
- const newSchema = schema?.element;
56
+ const newSchema = current.element;
46
57
  if (!newSchema)
47
58
  throw Error("No element on Zod Array");
48
59
  return newSchema;
49
60
  }
61
+ /**
62
+ * Схема конечного поля по dotted-пути клиентского patch.
63
+ *
64
+ * Элемент массива адресуется числовым сегментом (`meters.0.zones.0.value`).
65
+ * Индексом он считается только если текущий узел — `ZodArray`; у `ZodObject`
66
+ * тот же сегмент остаётся строковым ключом (`{ "0": z.string() }`).
67
+ */
50
68
  function zodDeepPick(schema, propertyPath) {
51
69
  if (propertyPath === "")
52
70
  return schema;
53
- const numberRegex = new RegExp("[[0-9]+]");
54
- const arrayIndex = propertyPath.search(numberRegex);
55
- const objectIndex = propertyPath.indexOf(".");
56
- const matchedArray = arrayIndex !== -1;
57
- const matchedObject = objectIndex !== -1;
58
- if ((matchedArray && matchedObject && arrayIndex < objectIndex) ||
59
- (matchedArray && !matchedObject)) {
60
- const arraySplit = propertyPath.split(numberRegex);
61
- const restArray = arraySplit.slice(1, arraySplit.length).join("[0]");
62
- if (arrayIndex !== 0) {
63
- return zodDeepPick(pickObject(schema, arraySplit[0]), `[0]${restArray}`);
64
- }
65
- return zodDeepPick(pickArray(schema), restArray.charAt(0) === "."
66
- ? restArray.slice(1, restArray.length)
67
- : restArray);
68
- }
69
- if (matchedObject) {
70
- const objectSplit = propertyPath.split(".");
71
- const restObject = objectSplit.slice(1, objectSplit.length).join(".");
72
- return zodDeepPick(pickObject(schema, objectSplit[0]), restObject);
71
+ const dot = propertyPath.indexOf(".");
72
+ const segment = dot === -1 ? propertyPath : propertyPath.slice(0, dot);
73
+ const rest = dot === -1 ? "" : propertyPath.slice(dot + 1);
74
+ const current = schemaForPathStep(schema);
75
+ if (isZodArray(current) && /^\d+$/.test(segment)) {
76
+ return zodDeepPick(pickArray(current), rest);
73
77
  }
74
- return pickObject(schema, propertyPath);
78
+ return zodDeepPick(pickObject(schema, segment), rest);
75
79
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@matreshka/bff",
3
- "version": "0.33.0",
3
+ "version": "0.34.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/client-bff-protocol": "^0.2.1",
65
+ "@matreshka/client-bff-protocol": "^0.3.0",
66
66
  "@matreshka/gateway-bff-protocol": "^0.1.0",
67
67
  "@matreshka/shared": "^0.25.1",
68
68
  "@simplewebauthn/server": "^13.1.1",