@matreshka/bff 0.36.0 → 0.38.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.
- package/dist/core/context/context-diff.d.ts +14 -0
- package/dist/core/context/context-diff.js +672 -0
- package/dist/core/context/context.js +17 -16
- package/dist/platforms/client-platform.d.ts +12 -0
- package/dist/platforms/client-platform.js +18 -0
- package/dist/platforms/index.d.ts +1 -0
- package/dist/platforms/index.js +1 -0
- package/dist/platforms/media.d.ts +89 -0
- package/dist/platforms/media.js +315 -0
- package/package.json +3 -3
- package/dist/core/utils/objects-diff.d.ts +0 -13
- package/dist/core/utils/objects-diff.js +0 -56
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ContextDiffBranch, ContextDiffNode } from "@matreshka/client-bff-protocol/messages/bff-to-client/context/context-values-message";
|
|
2
|
+
import type { Json } from "@matreshka/client-bff-protocol/types/json";
|
|
3
|
+
/** Сравнение элементов массива. По умолчанию — уникальный id, затем глубокое равенство. */
|
|
4
|
+
export type ContextDiffIdentity = (previous: Json, next: Json) => boolean;
|
|
5
|
+
/**
|
|
6
|
+
* Partial tree между двумя JSON-значениями.
|
|
7
|
+
*
|
|
8
|
+
* undefined — изменений нет.
|
|
9
|
+
*
|
|
10
|
+
* Входные значения не мутируются.
|
|
11
|
+
*/
|
|
12
|
+
export declare function createContextDiff(previous: Json, next: Json, identity?: ContextDiffIdentity): ContextDiffNode | undefined;
|
|
13
|
+
export declare function isContextDiffBranch(diff: ContextDiffNode): diff is ContextDiffBranch;
|
|
14
|
+
export declare function isEmptyContextDiff(diff: ContextDiffNode | undefined): boolean;
|
|
@@ -0,0 +1,672 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createContextDiff = createContextDiff;
|
|
4
|
+
exports.isContextDiffBranch = isContextDiffBranch;
|
|
5
|
+
exports.isEmptyContextDiff = isEmptyContextDiff;
|
|
6
|
+
const objects_diff_1 = require("@matreshka/shared/utils/objects-diff");
|
|
7
|
+
/**
|
|
8
|
+
* Partial tree между двумя JSON-значениями.
|
|
9
|
+
*
|
|
10
|
+
* undefined — изменений нет.
|
|
11
|
+
*
|
|
12
|
+
* Входные значения не мутируются.
|
|
13
|
+
*/
|
|
14
|
+
function createContextDiff(previous, next, identity) {
|
|
15
|
+
return createNodeDiff(toJsonData(previous), toJsonData(next), identity);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Убирает свойства со значением undefined.
|
|
19
|
+
*
|
|
20
|
+
* В JSON такого значения нет. Иначе diff получает {$set: undefined}
|
|
21
|
+
* и applyContextDiff бросает ContextDiffError.
|
|
22
|
+
* Дыра в массиве становится null, как при JSON.stringify.
|
|
23
|
+
*/
|
|
24
|
+
function toJsonData(value) {
|
|
25
|
+
if (Array.isArray(value)) {
|
|
26
|
+
let copy;
|
|
27
|
+
for (let index = 0; index < value.length; index++) {
|
|
28
|
+
const item = value[index];
|
|
29
|
+
const normalized = item === undefined ? null : toJsonData(item);
|
|
30
|
+
if (copy) {
|
|
31
|
+
copy.push(normalized);
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if (normalized !== item) {
|
|
35
|
+
copy = value.slice(0, index);
|
|
36
|
+
copy.push(normalized);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return copy ?? value;
|
|
40
|
+
}
|
|
41
|
+
if (!isPlainObject(value)) {
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
let copy;
|
|
45
|
+
for (const key of Object.keys(value)) {
|
|
46
|
+
const item = value[key];
|
|
47
|
+
if (item === undefined) {
|
|
48
|
+
copy ?? (copy = { ...value });
|
|
49
|
+
delete copy[key];
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
const normalized = toJsonData(item);
|
|
53
|
+
if (normalized !== item) {
|
|
54
|
+
copy ?? (copy = { ...value });
|
|
55
|
+
copy[key] = normalized;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return copy ?? value;
|
|
59
|
+
}
|
|
60
|
+
function isContextDiffBranch(diff) {
|
|
61
|
+
return isPlainObject(diff);
|
|
62
|
+
}
|
|
63
|
+
function isEmptyContextDiff(diff) {
|
|
64
|
+
if (diff === undefined) {
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
if (Array.isArray(diff)) {
|
|
68
|
+
return diff.length === 0;
|
|
69
|
+
}
|
|
70
|
+
if (isPlainObject(diff)) {
|
|
71
|
+
return Object.keys(diff).length === 0;
|
|
72
|
+
}
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Создаёт diff для одного узла.
|
|
77
|
+
*
|
|
78
|
+
* Генерирует несколько допустимых вариантов и выбирает
|
|
79
|
+
* наиболее компактный по размеру JSON.
|
|
80
|
+
*/
|
|
81
|
+
function createNodeDiff(previous, next, identity) {
|
|
82
|
+
if (deepEqual(previous, next)) {
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
const candidates = [toCandidate(createSetNode(next), 2)];
|
|
86
|
+
if (isPlainObject(previous) && isPlainObject(next)) {
|
|
87
|
+
const partial = createObjectCandidate(previous, next, identity);
|
|
88
|
+
if (partial && verifyDiff(previous, next, partial)) {
|
|
89
|
+
candidates.push(toCandidate(partial, 0));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (Array.isArray(previous) && Array.isArray(next)) {
|
|
93
|
+
for (const partial of createArrayCandidates(previous, next, identity)) {
|
|
94
|
+
if (verifyDiff(previous, next, partial)) {
|
|
95
|
+
candidates.push(toCandidate(partial, 0));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return selectBestCandidate(candidates).diff;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Создаёт представление полной замены узла.
|
|
103
|
+
*
|
|
104
|
+
* Примитивы передаются непосредственно.
|
|
105
|
+
* Массивы и полная замена объекта требуют явного $set:
|
|
106
|
+
* массив в partial tree обновляет элементы по позиции.
|
|
107
|
+
*/
|
|
108
|
+
function createSetNode(next) {
|
|
109
|
+
if (isJsonPrimitive(next)) {
|
|
110
|
+
return next;
|
|
111
|
+
}
|
|
112
|
+
return { $set: structuredClone(next) };
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Запись нового значения.
|
|
116
|
+
*
|
|
117
|
+
* Новый объект — частичное дерево свойств от пустого объекта,
|
|
118
|
+
* если оно короче $set. Пустой объект и массив остаются $set.
|
|
119
|
+
*/
|
|
120
|
+
function createAssignment(next, identity) {
|
|
121
|
+
if (!isPlainObject(next)) {
|
|
122
|
+
return createSetNode(next);
|
|
123
|
+
}
|
|
124
|
+
return createNodeDiff({}, next, identity) ?? createSetNode(next);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Создаёт частичное обновление объекта.
|
|
128
|
+
*
|
|
129
|
+
* $remove содержит имена непосредственно удаляемых свойств.
|
|
130
|
+
* Остальные свойства содержат дочерние diff.
|
|
131
|
+
*/
|
|
132
|
+
function createObjectCandidate(previous, next, identity) {
|
|
133
|
+
const remove = [];
|
|
134
|
+
const children = new Map();
|
|
135
|
+
for (const key of uniqueKeys(previous, next).sort()) {
|
|
136
|
+
const inPrevious = Object.prototype.hasOwnProperty.call(previous, key);
|
|
137
|
+
const inNext = Object.prototype.hasOwnProperty.call(next, key);
|
|
138
|
+
if (inPrevious && !inNext) {
|
|
139
|
+
remove.push(key);
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
if (!inPrevious && inNext) {
|
|
143
|
+
if (isReservedKey(key)) {
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
children.set(key, createAssignment(next[key], identity));
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
if (deepEqual(previous[key], next[key])) {
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (isReservedKey(key)) {
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
const child = createNodeDiff(previous[key], next[key], identity);
|
|
156
|
+
if (child !== undefined) {
|
|
157
|
+
children.set(key, child);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (remove.length === 0 && children.size === 0) {
|
|
161
|
+
return undefined;
|
|
162
|
+
}
|
|
163
|
+
const node = {};
|
|
164
|
+
if (remove.length > 0) {
|
|
165
|
+
node.$remove = remove;
|
|
166
|
+
}
|
|
167
|
+
for (const key of [...children.keys()].sort()) {
|
|
168
|
+
node[key] = children.get(key);
|
|
169
|
+
}
|
|
170
|
+
return node;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Создаёт кандидаты частичного обновления массива.
|
|
174
|
+
*
|
|
175
|
+
* Поддерживаются:
|
|
176
|
+
* - удаление;
|
|
177
|
+
* - перемещение;
|
|
178
|
+
* - вставка последовательности;
|
|
179
|
+
* - обновление существующих элементов;
|
|
180
|
+
* - добавление элементов в конец.
|
|
181
|
+
*
|
|
182
|
+
* Если преобразование невозможно представить корректно,
|
|
183
|
+
* возвращается пустой список кандидатов.
|
|
184
|
+
*/
|
|
185
|
+
function createArrayCandidates(previous, next, identity) {
|
|
186
|
+
const pairs = matchArrayElements(previous, next, identity);
|
|
187
|
+
if (!pairs) {
|
|
188
|
+
return [];
|
|
189
|
+
}
|
|
190
|
+
const removed = detectRemovals(previous.length, pairs);
|
|
191
|
+
const moves = detectMoves(pairs);
|
|
192
|
+
if (!moves) {
|
|
193
|
+
return [];
|
|
194
|
+
}
|
|
195
|
+
const updates = createIndexedUpdates(previous, next, pairs, identity);
|
|
196
|
+
const inserts = detectInserts(next, pairs);
|
|
197
|
+
const candidates = [];
|
|
198
|
+
const branch = createArrayBranch(removed, moves, inserts, updates);
|
|
199
|
+
if (branch) {
|
|
200
|
+
candidates.push(branch);
|
|
201
|
+
}
|
|
202
|
+
if (isPureSuffix(inserts, pairs, next.length)) {
|
|
203
|
+
const suffix = createArrayBranch(removed, moves, [], [...updates, ...suffixUpdates(inserts, identity)]);
|
|
204
|
+
if (suffix) {
|
|
205
|
+
candidates.push(suffix);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
if (removed.length === 0 &&
|
|
209
|
+
moves.length === 0 &&
|
|
210
|
+
next.length === previous.length) {
|
|
211
|
+
const positional = createPositionalArray(updates);
|
|
212
|
+
if (positional) {
|
|
213
|
+
candidates.push(positional);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return candidates;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Плотный префикс до последнего изменённого элемента.
|
|
220
|
+
*
|
|
221
|
+
* {} сохраняет элемент. Хвост без изменений в diff не входит.
|
|
222
|
+
* Используется только для обновления на тех же позициях:
|
|
223
|
+
* удаления и перемещения представляются отдельной веткой.
|
|
224
|
+
*/
|
|
225
|
+
function createPositionalArray(updates) {
|
|
226
|
+
if (updates.length === 0) {
|
|
227
|
+
return undefined;
|
|
228
|
+
}
|
|
229
|
+
const lastIndex = updates[updates.length - 1].index;
|
|
230
|
+
const slots = [];
|
|
231
|
+
for (let index = 0; index <= lastIndex; index++) {
|
|
232
|
+
slots.push({});
|
|
233
|
+
}
|
|
234
|
+
for (const update of updates) {
|
|
235
|
+
slots[update.index] = update.diff;
|
|
236
|
+
}
|
|
237
|
+
return slots;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Сопоставляет элементы старого и нового массивов.
|
|
241
|
+
*
|
|
242
|
+
* Приоритет:
|
|
243
|
+
* 1. Пользовательская identity-функция.
|
|
244
|
+
* 2. Уникальный id.
|
|
245
|
+
* 3. Глубокое равенство.
|
|
246
|
+
* 4. Позиционное сопоставление оставшихся элементов.
|
|
247
|
+
*
|
|
248
|
+
* Несопоставленные элементы нового массива становятся вставками.
|
|
249
|
+
* Соседние вставки схлопываются в одну последовательность.
|
|
250
|
+
*/
|
|
251
|
+
function matchArrayElements(previous, next, identity) {
|
|
252
|
+
const used = new Set();
|
|
253
|
+
const pairs = [];
|
|
254
|
+
const unmatched = [];
|
|
255
|
+
const ids = identity ? undefined : uniqueIds(previous, next);
|
|
256
|
+
for (let newIndex = 0; newIndex < next.length; newIndex++) {
|
|
257
|
+
const oldIndex = findIdentityMatch(previous, next[newIndex], used, identity, ids);
|
|
258
|
+
if (oldIndex === undefined) {
|
|
259
|
+
unmatched.push(newIndex);
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
used.add(oldIndex);
|
|
263
|
+
pairs.push({
|
|
264
|
+
oldIndex,
|
|
265
|
+
newIndex,
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
const leftovers = [];
|
|
269
|
+
for (const newIndex of unmatched) {
|
|
270
|
+
const oldIndex = findEqualMatch(previous, next[newIndex], used);
|
|
271
|
+
if (oldIndex === undefined) {
|
|
272
|
+
leftovers.push(newIndex);
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
used.add(oldIndex);
|
|
276
|
+
pairs.push({
|
|
277
|
+
oldIndex,
|
|
278
|
+
newIndex,
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
for (const newIndex of leftovers) {
|
|
282
|
+
const oldIndex = findUnused(previous.length, used);
|
|
283
|
+
if (oldIndex === undefined) {
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
used.add(oldIndex);
|
|
287
|
+
pairs.push({
|
|
288
|
+
oldIndex,
|
|
289
|
+
newIndex,
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
return pairs;
|
|
293
|
+
}
|
|
294
|
+
function findIdentityMatch(previous, nextItem, used, identity, ids) {
|
|
295
|
+
if (identity) {
|
|
296
|
+
for (let oldIndex = 0; oldIndex < previous.length; oldIndex++) {
|
|
297
|
+
if (used.has(oldIndex)) {
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if (identity(previous[oldIndex], nextItem)) {
|
|
301
|
+
return oldIndex;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return undefined;
|
|
305
|
+
}
|
|
306
|
+
const id = readId(nextItem);
|
|
307
|
+
if (id === undefined || !ids) {
|
|
308
|
+
return undefined;
|
|
309
|
+
}
|
|
310
|
+
const oldIndex = ids.get(idKey(id));
|
|
311
|
+
if (oldIndex === undefined || used.has(oldIndex)) {
|
|
312
|
+
return undefined;
|
|
313
|
+
}
|
|
314
|
+
return oldIndex;
|
|
315
|
+
}
|
|
316
|
+
function findEqualMatch(previous, nextItem, used) {
|
|
317
|
+
for (let oldIndex = 0; oldIndex < previous.length; oldIndex++) {
|
|
318
|
+
if (used.has(oldIndex)) {
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
if (deepEqual(previous[oldIndex], nextItem)) {
|
|
322
|
+
return oldIndex;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return undefined;
|
|
326
|
+
}
|
|
327
|
+
function findUnused(length, used) {
|
|
328
|
+
for (let oldIndex = 0; oldIndex < length; oldIndex++) {
|
|
329
|
+
if (!used.has(oldIndex)) {
|
|
330
|
+
return oldIndex;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
return undefined;
|
|
334
|
+
}
|
|
335
|
+
function uniqueIds(previous, next) {
|
|
336
|
+
const previousCounts = countIds(previous);
|
|
337
|
+
const nextCounts = countIds(next);
|
|
338
|
+
const matches = new Map();
|
|
339
|
+
previous.forEach((item, index) => {
|
|
340
|
+
const id = readId(item);
|
|
341
|
+
if (id === undefined) {
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
const key = idKey(id);
|
|
345
|
+
if (previousCounts.get(key) !== 1 || nextCounts.get(key) !== 1) {
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
matches.set(key, index);
|
|
349
|
+
});
|
|
350
|
+
return matches;
|
|
351
|
+
}
|
|
352
|
+
function countIds(items) {
|
|
353
|
+
const counts = new Map();
|
|
354
|
+
for (const item of items) {
|
|
355
|
+
const id = readId(item);
|
|
356
|
+
if (id === undefined) {
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
const key = idKey(id);
|
|
360
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
361
|
+
}
|
|
362
|
+
return counts;
|
|
363
|
+
}
|
|
364
|
+
function readId(value) {
|
|
365
|
+
if (!isPlainObject(value)) {
|
|
366
|
+
return undefined;
|
|
367
|
+
}
|
|
368
|
+
const id = value.id;
|
|
369
|
+
if (typeof id === "string") {
|
|
370
|
+
return id;
|
|
371
|
+
}
|
|
372
|
+
if (typeof id === "number" && Number.isFinite(id)) {
|
|
373
|
+
return id;
|
|
374
|
+
}
|
|
375
|
+
return undefined;
|
|
376
|
+
}
|
|
377
|
+
function idKey(id) {
|
|
378
|
+
return typeof id === "number" ? `n:${id}` : `s:${id}`;
|
|
379
|
+
}
|
|
380
|
+
function detectRemovals(length, pairs) {
|
|
381
|
+
const used = new Set(pairs.map((pair) => pair.oldIndex));
|
|
382
|
+
const removed = [];
|
|
383
|
+
for (let index = 0; index < length; index++) {
|
|
384
|
+
if (!used.has(index)) {
|
|
385
|
+
removed.push(index);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
return removed;
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Вычисляет минимальный набор перемещений.
|
|
392
|
+
*
|
|
393
|
+
* Индексы операций относятся к массиву после удаления
|
|
394
|
+
* и применяются последовательно.
|
|
395
|
+
*/
|
|
396
|
+
function detectMoves(pairs) {
|
|
397
|
+
const afterRemove = pairs
|
|
398
|
+
.slice()
|
|
399
|
+
.sort((left, right) => left.oldIndex - right.oldIndex)
|
|
400
|
+
.map((pair) => pair.oldIndex);
|
|
401
|
+
const target = pairs
|
|
402
|
+
.slice()
|
|
403
|
+
.sort((left, right) => left.newIndex - right.newIndex)
|
|
404
|
+
.map((pair) => pair.oldIndex);
|
|
405
|
+
const lisMoves = movesByLis(afterRemove, target);
|
|
406
|
+
const greedyMoves = movesByGreedy(afterRemove, target);
|
|
407
|
+
const workable = [lisMoves, greedyMoves].filter((moves) => sameOrder(simulateMoves(afterRemove, moves), target));
|
|
408
|
+
if (workable.length === 0) {
|
|
409
|
+
return undefined;
|
|
410
|
+
}
|
|
411
|
+
workable.sort((left, right) => left.length - right.length);
|
|
412
|
+
return workable[0];
|
|
413
|
+
}
|
|
414
|
+
function movesByLis(source, target) {
|
|
415
|
+
if (source.length === 0) {
|
|
416
|
+
return [];
|
|
417
|
+
}
|
|
418
|
+
const targetPos = new Map();
|
|
419
|
+
target.forEach((id, index) => {
|
|
420
|
+
targetPos.set(id, index);
|
|
421
|
+
});
|
|
422
|
+
const ranks = source.map((id) => targetPos.get(id) ?? 0);
|
|
423
|
+
const frozen = new Set(lisIndices(ranks).map((index) => source[index]));
|
|
424
|
+
const items = source.slice();
|
|
425
|
+
const moves = [];
|
|
426
|
+
for (const item of target) {
|
|
427
|
+
if (frozen.has(item)) {
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
const from = items.indexOf(item);
|
|
431
|
+
const to = targetPos.get(item) ?? 0;
|
|
432
|
+
if (from === to) {
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
items.splice(from, 1);
|
|
436
|
+
items.splice(to, 0, item);
|
|
437
|
+
moves.push([from, to]);
|
|
438
|
+
}
|
|
439
|
+
return moves;
|
|
440
|
+
}
|
|
441
|
+
function movesByGreedy(source, target) {
|
|
442
|
+
const items = source.slice();
|
|
443
|
+
const moves = [];
|
|
444
|
+
for (let index = 0; index < target.length; index++) {
|
|
445
|
+
if (items[index] === target[index]) {
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
const from = items.indexOf(target[index]);
|
|
449
|
+
const [item] = items.splice(from, 1);
|
|
450
|
+
items.splice(index, 0, item);
|
|
451
|
+
moves.push([from, index]);
|
|
452
|
+
}
|
|
453
|
+
return moves;
|
|
454
|
+
}
|
|
455
|
+
function simulateMoves(source, moves) {
|
|
456
|
+
const items = source.slice();
|
|
457
|
+
for (const [from, to] of moves) {
|
|
458
|
+
if (from < 0 || from >= items.length || to < 0 || to >= items.length) {
|
|
459
|
+
return [];
|
|
460
|
+
}
|
|
461
|
+
const [item] = items.splice(from, 1);
|
|
462
|
+
items.splice(to, 0, item);
|
|
463
|
+
}
|
|
464
|
+
return items;
|
|
465
|
+
}
|
|
466
|
+
function sameOrder(left, right) {
|
|
467
|
+
if (left.length !== right.length) {
|
|
468
|
+
return false;
|
|
469
|
+
}
|
|
470
|
+
return left.every((item, index) => item === right[index]);
|
|
471
|
+
}
|
|
472
|
+
function lisIndices(values) {
|
|
473
|
+
const tails = [];
|
|
474
|
+
const previous = new Array(values.length).fill(-1);
|
|
475
|
+
for (let index = 0; index < values.length; index++) {
|
|
476
|
+
let low = 0;
|
|
477
|
+
let high = tails.length;
|
|
478
|
+
while (low < high) {
|
|
479
|
+
const mid = (low + high) >> 1;
|
|
480
|
+
if (values[tails[mid]] < values[index]) {
|
|
481
|
+
low = mid + 1;
|
|
482
|
+
}
|
|
483
|
+
else {
|
|
484
|
+
high = mid;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
if (low > 0) {
|
|
488
|
+
previous[index] = tails[low - 1];
|
|
489
|
+
}
|
|
490
|
+
if (low === tails.length) {
|
|
491
|
+
tails.push(index);
|
|
492
|
+
}
|
|
493
|
+
else {
|
|
494
|
+
tails[low] = index;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
const result = [];
|
|
498
|
+
if (tails.length === 0) {
|
|
499
|
+
return result;
|
|
500
|
+
}
|
|
501
|
+
for (let index = tails[tails.length - 1]; index !== -1; index = previous[index]) {
|
|
502
|
+
result.push(index);
|
|
503
|
+
}
|
|
504
|
+
result.reverse();
|
|
505
|
+
return result;
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Создаёт обновления элементов массива.
|
|
509
|
+
*
|
|
510
|
+
* Существующие элементы адресуются по итоговым индексам.
|
|
511
|
+
* Новые элементы передаются отдельно через $insert.
|
|
512
|
+
*/
|
|
513
|
+
function createIndexedUpdates(previous, next, pairs, identity) {
|
|
514
|
+
const updates = [];
|
|
515
|
+
for (const pair of pairs) {
|
|
516
|
+
const child = createNodeDiff(previous[pair.oldIndex], next[pair.newIndex], identity);
|
|
517
|
+
if (child !== undefined) {
|
|
518
|
+
updates.push({
|
|
519
|
+
index: pair.newIndex,
|
|
520
|
+
diff: child,
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
updates.sort((left, right) => left.index - right.index);
|
|
525
|
+
return updates;
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Группирует соседние несопоставленные элементы.
|
|
529
|
+
*
|
|
530
|
+
* Индекс — позиция в итоговом массиве. При последовательном применении
|
|
531
|
+
* снизу вверх он совпадает с позицией после предыдущих вставок.
|
|
532
|
+
*/
|
|
533
|
+
function detectInserts(next, pairs) {
|
|
534
|
+
const matched = new Set(pairs.map((pair) => pair.newIndex));
|
|
535
|
+
const inserts = [];
|
|
536
|
+
let index = 0;
|
|
537
|
+
while (index < next.length) {
|
|
538
|
+
if (matched.has(index)) {
|
|
539
|
+
index += 1;
|
|
540
|
+
continue;
|
|
541
|
+
}
|
|
542
|
+
const start = index;
|
|
543
|
+
const elements = [];
|
|
544
|
+
while (index < next.length && !matched.has(index)) {
|
|
545
|
+
elements.push(structuredClone(next[index]));
|
|
546
|
+
index += 1;
|
|
547
|
+
}
|
|
548
|
+
inserts.push([start, elements]);
|
|
549
|
+
}
|
|
550
|
+
return inserts;
|
|
551
|
+
}
|
|
552
|
+
function isPureSuffix(inserts, pairs, nextLength) {
|
|
553
|
+
if (inserts.length !== 1) {
|
|
554
|
+
return false;
|
|
555
|
+
}
|
|
556
|
+
const [index, elements] = inserts[0];
|
|
557
|
+
return index === pairs.length && index + elements.length === nextLength;
|
|
558
|
+
}
|
|
559
|
+
function suffixUpdates(inserts, identity) {
|
|
560
|
+
const [start, elements] = inserts[0];
|
|
561
|
+
return elements.map((element, offset) => ({
|
|
562
|
+
index: start + offset,
|
|
563
|
+
diff: createAssignment(element, identity),
|
|
564
|
+
}));
|
|
565
|
+
}
|
|
566
|
+
function createArrayBranch(removed, moves, inserts, updates) {
|
|
567
|
+
if (removed.length === 0 &&
|
|
568
|
+
moves.length === 0 &&
|
|
569
|
+
inserts.length === 0 &&
|
|
570
|
+
updates.length === 0) {
|
|
571
|
+
return undefined;
|
|
572
|
+
}
|
|
573
|
+
const node = {};
|
|
574
|
+
if (removed.length > 0) {
|
|
575
|
+
node.$remove = removed;
|
|
576
|
+
}
|
|
577
|
+
if (moves.length > 0) {
|
|
578
|
+
node.$move = moves;
|
|
579
|
+
}
|
|
580
|
+
if (inserts.length > 0) {
|
|
581
|
+
node.$insert = inserts;
|
|
582
|
+
}
|
|
583
|
+
for (const update of updates) {
|
|
584
|
+
node[String(update.index)] = update.diff;
|
|
585
|
+
}
|
|
586
|
+
return node;
|
|
587
|
+
}
|
|
588
|
+
function verifyDiff(previous, next, diff) {
|
|
589
|
+
return deepEqual((0, objects_diff_1.applyContextDiff)(previous, diff), next);
|
|
590
|
+
}
|
|
591
|
+
function toCandidate(diff, order) {
|
|
592
|
+
return {
|
|
593
|
+
diff,
|
|
594
|
+
size: serializedSize(diff),
|
|
595
|
+
priority: priorityOf(diff),
|
|
596
|
+
order,
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
function selectBestCandidate(candidates) {
|
|
600
|
+
return candidates.sort((left, right) => {
|
|
601
|
+
if (left.size !== right.size) {
|
|
602
|
+
return left.size - right.size;
|
|
603
|
+
}
|
|
604
|
+
if (left.priority !== right.priority) {
|
|
605
|
+
return left.priority - right.priority;
|
|
606
|
+
}
|
|
607
|
+
return left.order - right.order;
|
|
608
|
+
})[0];
|
|
609
|
+
}
|
|
610
|
+
function priorityOf(diff) {
|
|
611
|
+
if (isJsonPrimitive(diff)) {
|
|
612
|
+
return 3;
|
|
613
|
+
}
|
|
614
|
+
if (Array.isArray(diff)) {
|
|
615
|
+
return 1;
|
|
616
|
+
}
|
|
617
|
+
if (Object.prototype.hasOwnProperty.call(diff, "$set")) {
|
|
618
|
+
return 3;
|
|
619
|
+
}
|
|
620
|
+
if (diff.$remove !== undefined ||
|
|
621
|
+
diff.$move !== undefined ||
|
|
622
|
+
diff.$insert !== undefined) {
|
|
623
|
+
return 2;
|
|
624
|
+
}
|
|
625
|
+
return 1;
|
|
626
|
+
}
|
|
627
|
+
function serializedSize(value) {
|
|
628
|
+
return Buffer.byteLength(JSON.stringify(value), "utf8");
|
|
629
|
+
}
|
|
630
|
+
function uniqueKeys(previous, next) {
|
|
631
|
+
return [...new Set([...Object.keys(previous), ...Object.keys(next)])];
|
|
632
|
+
}
|
|
633
|
+
function isReservedKey(key) {
|
|
634
|
+
return key.startsWith("$");
|
|
635
|
+
}
|
|
636
|
+
function deepEqual(left, right) {
|
|
637
|
+
if (Object.is(left, right)) {
|
|
638
|
+
return true;
|
|
639
|
+
}
|
|
640
|
+
if (Array.isArray(left) && Array.isArray(right)) {
|
|
641
|
+
if (left.length !== right.length) {
|
|
642
|
+
return false;
|
|
643
|
+
}
|
|
644
|
+
return left.every((item, index) => deepEqual(item, right[index]));
|
|
645
|
+
}
|
|
646
|
+
if (isPlainObject(left) && isPlainObject(right)) {
|
|
647
|
+
const leftKeys = Object.keys(left);
|
|
648
|
+
const rightKeys = Object.keys(right);
|
|
649
|
+
if (leftKeys.length !== rightKeys.length) {
|
|
650
|
+
return false;
|
|
651
|
+
}
|
|
652
|
+
return leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) &&
|
|
653
|
+
deepEqual(left[key], right[key]));
|
|
654
|
+
}
|
|
655
|
+
return false;
|
|
656
|
+
}
|
|
657
|
+
function isJsonPrimitive(value) {
|
|
658
|
+
if (value === null) {
|
|
659
|
+
return true;
|
|
660
|
+
}
|
|
661
|
+
if (typeof value === "number") {
|
|
662
|
+
return Number.isFinite(value);
|
|
663
|
+
}
|
|
664
|
+
return typeof value === "string" || typeof value === "boolean";
|
|
665
|
+
}
|
|
666
|
+
function isPlainObject(value) {
|
|
667
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
668
|
+
return false;
|
|
669
|
+
}
|
|
670
|
+
const prototype = Object.getPrototypeOf(value);
|
|
671
|
+
return prototype === Object.prototype || prototype === null;
|
|
672
|
+
}
|
|
@@ -30,9 +30,9 @@ const client_context_1 = require("../client-context");
|
|
|
30
30
|
const assert_non_overlapping_context_paths_1 = require("../utils/assert-non-overlapping-context-paths");
|
|
31
31
|
const assert_safe_dotted_path_1 = require("../utils/assert-safe-dotted-path");
|
|
32
32
|
const deep_pick_1 = require("../utils/deep-pick");
|
|
33
|
-
const objects_diff_1 = require("../utils/objects-diff");
|
|
34
33
|
const replace_context_keys_1 = require("../utils/replace-context-keys");
|
|
35
34
|
const assert_client_update_schema_1 = require("./assert-client-update-schema");
|
|
35
|
+
const context_diff_1 = require("./context-diff");
|
|
36
36
|
const context_ref_1 = require("./context-ref");
|
|
37
37
|
__exportStar(require("./context-create"), exports);
|
|
38
38
|
/** @see ContextClientUpdatesForbiddenSchema */
|
|
@@ -322,24 +322,27 @@ class Context {
|
|
|
322
322
|
// Во время init() не шлём diff (сохраняем текущую семантику: первая "реальная" установка данных не должна рассылаться как изменения).
|
|
323
323
|
if (!this.initializing && prevData) {
|
|
324
324
|
let diff;
|
|
325
|
+
let diffReady = false;
|
|
325
326
|
getRegistryEntry(this.id)?.clients.forEach((_, client) => {
|
|
326
327
|
if (this.dataChangedByClient !== client) {
|
|
327
328
|
// Не первое присваивание
|
|
328
329
|
// Сравнение двух объектов, поиск измененных ключей
|
|
329
|
-
if (
|
|
330
|
-
diff = (0,
|
|
330
|
+
if (!diffReady) {
|
|
331
|
+
diff = (0, context_diff_1.createContextDiff)(prevData, data);
|
|
332
|
+
diffReady = true;
|
|
331
333
|
}
|
|
332
|
-
if (
|
|
334
|
+
if (diff &&
|
|
335
|
+
(0, context_diff_1.isContextDiffBranch)(diff) &&
|
|
336
|
+
!(0, context_diff_1.isEmptyContextDiff)(diff)) {
|
|
333
337
|
// Изменения есть
|
|
334
|
-
client.outcomingMessage$.next(new index_1.ContextValuesMessage(this.id,
|
|
335
|
-
key,
|
|
336
|
-
value,
|
|
337
|
-
}))));
|
|
338
|
+
client.outcomingMessage$.next(new index_1.ContextValuesMessage(this.id, diff));
|
|
338
339
|
}
|
|
339
340
|
}
|
|
340
341
|
});
|
|
341
342
|
}
|
|
342
343
|
this.dataChangedByClient = undefined;
|
|
344
|
+
// Снимок отделён от сравнения: копия защищает prev от последующей мутации,
|
|
345
|
+
// а createContextDiff сравнивает структуру, а не ссылки внутри копии.
|
|
343
346
|
prevData = structuredClone(data);
|
|
344
347
|
});
|
|
345
348
|
}
|
|
@@ -361,13 +364,12 @@ class Context {
|
|
|
361
364
|
emitDiffAndWait(diff) {
|
|
362
365
|
const recipients = this.recipientsForDiff();
|
|
363
366
|
this.dataChangedByClient = undefined;
|
|
364
|
-
if (
|
|
367
|
+
if (!diff ||
|
|
368
|
+
!(0, context_diff_1.isContextDiffBranch)(diff) ||
|
|
369
|
+
(0, context_diff_1.isEmptyContextDiff)(diff) ||
|
|
370
|
+
recipients.length === 0) {
|
|
365
371
|
return this.completeImmediately();
|
|
366
372
|
}
|
|
367
|
-
const payload = Object.entries(diff).map(([key, value]) => ({
|
|
368
|
-
key,
|
|
369
|
-
value,
|
|
370
|
-
}));
|
|
371
373
|
const result$ = new rxjs_1.ReplaySubject(recipients.length);
|
|
372
374
|
const delivered = [];
|
|
373
375
|
let finalized = false;
|
|
@@ -393,7 +395,7 @@ class Context {
|
|
|
393
395
|
}
|
|
394
396
|
};
|
|
395
397
|
for (const client of recipients) {
|
|
396
|
-
const message = new index_1.ContextValuesMessage(this.id,
|
|
398
|
+
const message = new index_1.ContextValuesMessage(this.id, diff);
|
|
397
399
|
subscriptions.add(client.waitForDelivery(message).subscribe({
|
|
398
400
|
next: () => finishSuccess(client),
|
|
399
401
|
error: (error) => finishError(error),
|
|
@@ -406,9 +408,8 @@ class Context {
|
|
|
406
408
|
this.assertNotDestroyed();
|
|
407
409
|
this.assertInitialized();
|
|
408
410
|
const currentData = this.data$.getValue();
|
|
409
|
-
const prevData = structuredClone(currentData);
|
|
410
411
|
const nextData = mutator(structuredClone(currentData));
|
|
411
|
-
const diff = (0,
|
|
412
|
+
const diff = (0, context_diff_1.createContextDiff)(currentData, nextData);
|
|
412
413
|
this.skipNextDataSync = true;
|
|
413
414
|
this.data$.next(nextData);
|
|
414
415
|
return this.emitDiffAndWait(diff);
|
|
@@ -1,6 +1,18 @@
|
|
|
1
|
+
import { Observable } from "rxjs";
|
|
2
|
+
import { Audio, MediaConfig, Video } from "./media";
|
|
1
3
|
import { Platform } from "./platform";
|
|
2
4
|
/**
|
|
3
5
|
* Абстрактный класс, реализующий любую клиентскую платформу.
|
|
4
6
|
*/
|
|
5
7
|
export declare abstract class ClientPlatform extends Platform {
|
|
8
|
+
/**
|
|
9
|
+
* Создаёт `HTMLAudioElement` на клиенте вне DOM.
|
|
10
|
+
* Hot: элемент создаётся при вызове. Observable эмитит объект после ack.
|
|
11
|
+
*/
|
|
12
|
+
createAudio(config?: MediaConfig): Observable<Audio>;
|
|
13
|
+
/**
|
|
14
|
+
* Создаёт `HTMLVideoElement` на клиенте вне DOM.
|
|
15
|
+
* `Video.id` — ключ реестра, который позже сможет забрать видеокомпонент.
|
|
16
|
+
*/
|
|
17
|
+
createVideo(config?: MediaConfig): Observable<Video>;
|
|
6
18
|
}
|
|
@@ -1,10 +1,28 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.ClientPlatform = void 0;
|
|
4
|
+
const rxjs_1 = require("rxjs");
|
|
5
|
+
const media_1 = require("./media");
|
|
4
6
|
const platform_1 = require("./platform");
|
|
5
7
|
/**
|
|
6
8
|
* Абстрактный класс, реализующий любую клиентскую платформу.
|
|
7
9
|
*/
|
|
8
10
|
class ClientPlatform extends platform_1.Platform {
|
|
11
|
+
/**
|
|
12
|
+
* Создаёт `HTMLAudioElement` на клиенте вне DOM.
|
|
13
|
+
* Hot: элемент создаётся при вызове. Observable эмитит объект после ack.
|
|
14
|
+
*/
|
|
15
|
+
createAudio(config = {}) {
|
|
16
|
+
const audio = new media_1.Audio(this.client, config);
|
|
17
|
+
return audio.open().pipe((0, rxjs_1.map)(() => audio));
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Создаёт `HTMLVideoElement` на клиенте вне DOM.
|
|
21
|
+
* `Video.id` — ключ реестра, который позже сможет забрать видеокомпонент.
|
|
22
|
+
*/
|
|
23
|
+
createVideo(config = {}) {
|
|
24
|
+
const video = new media_1.Video(this.client, config);
|
|
25
|
+
return video.open().pipe((0, rxjs_1.map)(() => video));
|
|
26
|
+
}
|
|
9
27
|
}
|
|
10
28
|
exports.ClientPlatform = ClientPlatform;
|
|
@@ -3,6 +3,7 @@ export * from "./browser-platform";
|
|
|
3
3
|
export * from "./client-platform";
|
|
4
4
|
export * from "./ios-platform";
|
|
5
5
|
export * from "./max-mini-app-platform";
|
|
6
|
+
export * from "./media";
|
|
6
7
|
export * from "./mobile-platform";
|
|
7
8
|
export * from "./platform";
|
|
8
9
|
export * from "./popover-show";
|
package/dist/platforms/index.js
CHANGED
|
@@ -19,6 +19,7 @@ __exportStar(require("./browser-platform"), exports);
|
|
|
19
19
|
__exportStar(require("./client-platform"), exports);
|
|
20
20
|
__exportStar(require("./ios-platform"), exports);
|
|
21
21
|
__exportStar(require("./max-mini-app-platform"), exports);
|
|
22
|
+
__exportStar(require("./media"), exports);
|
|
22
23
|
__exportStar(require("./mobile-platform"), exports);
|
|
23
24
|
__exportStar(require("./platform"), exports);
|
|
24
25
|
__exportStar(require("./popover-show"), exports);
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { MediaCrossOrigin } from "@matreshka/client-bff-protocol/enums/media-cross-origin";
|
|
2
|
+
import { MediaKind } from "@matreshka/client-bff-protocol/enums/media-kind";
|
|
3
|
+
import { MediaPreload } from "@matreshka/client-bff-protocol/enums/media-preload";
|
|
4
|
+
import { AnyBffToClientMessage } from "@matreshka/client-bff-protocol/messages/bff-to-client/bff-to-client-message";
|
|
5
|
+
import type { MediaElementConfig } from "@matreshka/client-bff-protocol/messages/bff-to-client/platforms/media-create-message";
|
|
6
|
+
import { Observable } from "rxjs";
|
|
7
|
+
import { ServerAction, type ServerActionHandler } from "../components/actions/server-action";
|
|
8
|
+
import { LocalAction } from "../core/actions/local-action";
|
|
9
|
+
import type { Client } from "../core/client";
|
|
10
|
+
import type { Componentable } from "../core/types/componentable";
|
|
11
|
+
export { MediaCrossOrigin, MediaKind, MediaPreload };
|
|
12
|
+
export type MediaProgressPayload = {
|
|
13
|
+
currentTime: number;
|
|
14
|
+
duration: number;
|
|
15
|
+
};
|
|
16
|
+
export type MediaVolumePayload = {
|
|
17
|
+
volume: number;
|
|
18
|
+
muted: boolean;
|
|
19
|
+
};
|
|
20
|
+
export type MediaRatePayload = {
|
|
21
|
+
playbackRate: number;
|
|
22
|
+
};
|
|
23
|
+
export type MediaErrorPayload = {
|
|
24
|
+
message: string;
|
|
25
|
+
};
|
|
26
|
+
/** Одно действие или массив локальных и серверных, как `onClick` у компонента. */
|
|
27
|
+
export type MediaAction<Payload> = ServerAction<Componentable, Payload> | ServerActionHandler<Componentable, Payload> | LocalAction;
|
|
28
|
+
export type MediaActionList<Payload> = MediaAction<Payload> | MediaAction<Payload>[];
|
|
29
|
+
export type MediaEventConfig = {
|
|
30
|
+
onPlay?: MediaActionList<MediaProgressPayload>;
|
|
31
|
+
onPause?: MediaActionList<MediaProgressPayload>;
|
|
32
|
+
onPlaying?: MediaActionList<MediaProgressPayload>;
|
|
33
|
+
onWaiting?: MediaActionList<MediaProgressPayload>;
|
|
34
|
+
onEnded?: MediaActionList<MediaProgressPayload>;
|
|
35
|
+
onError?: MediaActionList<MediaErrorPayload>;
|
|
36
|
+
onLoadedMetadata?: MediaActionList<MediaProgressPayload>;
|
|
37
|
+
onSeeking?: MediaActionList<MediaProgressPayload>;
|
|
38
|
+
onSeeked?: MediaActionList<MediaProgressPayload>;
|
|
39
|
+
onVolumeChange?: MediaActionList<MediaVolumePayload>;
|
|
40
|
+
onRateChange?: MediaActionList<MediaRatePayload>;
|
|
41
|
+
onTimeUpdate?: MediaActionList<MediaProgressPayload>;
|
|
42
|
+
onEnterPictureInPicture?: MediaActionList<Record<string, never>>;
|
|
43
|
+
onLeavePictureInPicture?: MediaActionList<Record<string, never>>;
|
|
44
|
+
};
|
|
45
|
+
export type MediaConfig = MediaElementConfig & MediaEventConfig;
|
|
46
|
+
/**
|
|
47
|
+
* Сессия `HTMLMediaElement` на клиенте. Элемент не входит в дерево компонентов.
|
|
48
|
+
* `id` — ключ клиентского реестра для будущего видеокомпонента.
|
|
49
|
+
*/
|
|
50
|
+
export declare abstract class Media {
|
|
51
|
+
protected readonly client: Client;
|
|
52
|
+
private readonly kind;
|
|
53
|
+
readonly id: string;
|
|
54
|
+
private readonly handlers;
|
|
55
|
+
private readonly rawConfig;
|
|
56
|
+
private sessionSubscription?;
|
|
57
|
+
private clientDestroySubscription?;
|
|
58
|
+
private ended;
|
|
59
|
+
constructor(client: Client, config: MediaConfig, kind: MediaKind);
|
|
60
|
+
play(): Observable<void>;
|
|
61
|
+
pause(): Observable<void>;
|
|
62
|
+
load(): Observable<void>;
|
|
63
|
+
seek(time: number): Observable<void>;
|
|
64
|
+
setSrc(src: string): Observable<void>;
|
|
65
|
+
setVolume(volume: number): Observable<void>;
|
|
66
|
+
setMuted(muted: boolean): Observable<void>;
|
|
67
|
+
setPlaybackRate(playbackRate: number): Observable<void>;
|
|
68
|
+
setLoop(loop: boolean): Observable<void>;
|
|
69
|
+
setPreload(preload: MediaPreload): Observable<void>;
|
|
70
|
+
destroy(): Observable<void>;
|
|
71
|
+
/** @internal */
|
|
72
|
+
open(): Observable<void>;
|
|
73
|
+
protected send(outgoingMessage: (scope: string) => AnyBffToClientMessage): Observable<void>;
|
|
74
|
+
private elementConfig;
|
|
75
|
+
private bindEvents;
|
|
76
|
+
private parseAction;
|
|
77
|
+
private serializeInteractions;
|
|
78
|
+
private startSession;
|
|
79
|
+
private emit;
|
|
80
|
+
private endSession;
|
|
81
|
+
}
|
|
82
|
+
export declare class Audio extends Media {
|
|
83
|
+
constructor(client: Client, config: MediaConfig);
|
|
84
|
+
}
|
|
85
|
+
export declare class Video extends Media {
|
|
86
|
+
constructor(client: Client, config: MediaConfig);
|
|
87
|
+
requestPictureInPicture(): Observable<void>;
|
|
88
|
+
exitPictureInPicture(): Observable<void>;
|
|
89
|
+
}
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Video = exports.Audio = exports.Media = exports.MediaPreload = exports.MediaKind = exports.MediaCrossOrigin = void 0;
|
|
4
|
+
const media_cross_origin_1 = require("@matreshka/client-bff-protocol/enums/media-cross-origin");
|
|
5
|
+
Object.defineProperty(exports, "MediaCrossOrigin", { enumerable: true, get: function () { return media_cross_origin_1.MediaCrossOrigin; } });
|
|
6
|
+
const media_kind_1 = require("@matreshka/client-bff-protocol/enums/media-kind");
|
|
7
|
+
Object.defineProperty(exports, "MediaKind", { enumerable: true, get: function () { return media_kind_1.MediaKind; } });
|
|
8
|
+
const media_preload_1 = require("@matreshka/client-bff-protocol/enums/media-preload");
|
|
9
|
+
Object.defineProperty(exports, "MediaPreload", { enumerable: true, get: function () { return media_preload_1.MediaPreload; } });
|
|
10
|
+
const media_create_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/media-create-message");
|
|
11
|
+
const media_destroy_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/media-destroy-message");
|
|
12
|
+
const media_exit_picture_in_picture_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/media-exit-picture-in-picture-message");
|
|
13
|
+
const media_load_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/media-load-message");
|
|
14
|
+
const media_pause_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/media-pause-message");
|
|
15
|
+
const media_play_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/media-play-message");
|
|
16
|
+
const media_request_picture_in_picture_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/media-request-picture-in-picture-message");
|
|
17
|
+
const media_seek_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/media-seek-message");
|
|
18
|
+
const media_set_loop_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/media-set-loop-message");
|
|
19
|
+
const media_set_muted_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/media-set-muted-message");
|
|
20
|
+
const media_set_playback_rate_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/media-set-playback-rate-message");
|
|
21
|
+
const media_set_preload_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/media-set-preload-message");
|
|
22
|
+
const media_set_src_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/media-set-src-message");
|
|
23
|
+
const media_set_volume_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/media-set-volume-message");
|
|
24
|
+
const media_event_messages_1 = require("@matreshka/client-bff-protocol/messages/client-to-bff/platforms/media-event-messages");
|
|
25
|
+
const rxjs_1 = require("rxjs");
|
|
26
|
+
const zod_1 = require("zod");
|
|
27
|
+
const server_action_1 = require("../components/actions/server-action");
|
|
28
|
+
const action_1 = require("../core/actions/action");
|
|
29
|
+
const local_action_1 = require("../core/actions/local-action");
|
|
30
|
+
const client_context_1 = require("../core/client-context");
|
|
31
|
+
const incoming_message_observer_1 = require("../core/utils/incoming-message-observer");
|
|
32
|
+
const targeted_client_platform_action_1 = require("./utils/targeted-client-platform-action");
|
|
33
|
+
function isMediaIncomingEvent(message) {
|
|
34
|
+
return (message instanceof media_event_messages_1.MediaPlayEventMessage ||
|
|
35
|
+
message instanceof media_event_messages_1.MediaPauseEventMessage ||
|
|
36
|
+
message instanceof media_event_messages_1.MediaPlayingEventMessage ||
|
|
37
|
+
message instanceof media_event_messages_1.MediaWaitingEventMessage ||
|
|
38
|
+
message instanceof media_event_messages_1.MediaEndedEventMessage ||
|
|
39
|
+
message instanceof media_event_messages_1.MediaLoadedMetadataEventMessage ||
|
|
40
|
+
message instanceof media_event_messages_1.MediaSeekingEventMessage ||
|
|
41
|
+
message instanceof media_event_messages_1.MediaSeekedEventMessage ||
|
|
42
|
+
message instanceof media_event_messages_1.MediaTimeUpdateEventMessage ||
|
|
43
|
+
message instanceof media_event_messages_1.MediaVolumeChangeEventMessage ||
|
|
44
|
+
message instanceof media_event_messages_1.MediaRateChangeEventMessage ||
|
|
45
|
+
message instanceof media_event_messages_1.MediaErrorEventMessage ||
|
|
46
|
+
message instanceof media_event_messages_1.MediaEnterPictureInPictureEventMessage ||
|
|
47
|
+
message instanceof media_event_messages_1.MediaLeavePictureInPictureEventMessage);
|
|
48
|
+
}
|
|
49
|
+
const mediaHandlersSchema = zod_1.z.array(zod_1.z.number().int().nonnegative());
|
|
50
|
+
const mediaProgressEventSchema = zod_1.z.strictObject({
|
|
51
|
+
currentTime: zod_1.z.number(),
|
|
52
|
+
duration: zod_1.z.number(),
|
|
53
|
+
handlers: mediaHandlersSchema,
|
|
54
|
+
});
|
|
55
|
+
const mediaVolumeEventSchema = zod_1.z.strictObject({
|
|
56
|
+
volume: zod_1.z.number(),
|
|
57
|
+
muted: zod_1.z.boolean(),
|
|
58
|
+
handlers: mediaHandlersSchema,
|
|
59
|
+
});
|
|
60
|
+
const mediaRateEventSchema = zod_1.z.strictObject({
|
|
61
|
+
playbackRate: zod_1.z.number(),
|
|
62
|
+
handlers: mediaHandlersSchema,
|
|
63
|
+
});
|
|
64
|
+
const mediaErrorEventSchema = zod_1.z.strictObject({
|
|
65
|
+
message: zod_1.z.string(),
|
|
66
|
+
handlers: mediaHandlersSchema,
|
|
67
|
+
});
|
|
68
|
+
const mediaPictureInPictureEventSchema = zod_1.z.strictObject({
|
|
69
|
+
handlers: mediaHandlersSchema,
|
|
70
|
+
});
|
|
71
|
+
function mediaEventSchema(message) {
|
|
72
|
+
if (message instanceof media_event_messages_1.MediaVolumeChangeEventMessage) {
|
|
73
|
+
return mediaVolumeEventSchema;
|
|
74
|
+
}
|
|
75
|
+
if (message instanceof media_event_messages_1.MediaRateChangeEventMessage) {
|
|
76
|
+
return mediaRateEventSchema;
|
|
77
|
+
}
|
|
78
|
+
if (message instanceof media_event_messages_1.MediaErrorEventMessage) {
|
|
79
|
+
return mediaErrorEventSchema;
|
|
80
|
+
}
|
|
81
|
+
if (message instanceof media_event_messages_1.MediaEnterPictureInPictureEventMessage ||
|
|
82
|
+
message instanceof media_event_messages_1.MediaLeavePictureInPictureEventMessage) {
|
|
83
|
+
return mediaPictureInPictureEventSchema;
|
|
84
|
+
}
|
|
85
|
+
return mediaProgressEventSchema;
|
|
86
|
+
}
|
|
87
|
+
function mediaEventName(message) {
|
|
88
|
+
if (message instanceof media_event_messages_1.MediaPlayEventMessage) {
|
|
89
|
+
return "play";
|
|
90
|
+
}
|
|
91
|
+
if (message instanceof media_event_messages_1.MediaPauseEventMessage) {
|
|
92
|
+
return "pause";
|
|
93
|
+
}
|
|
94
|
+
if (message instanceof media_event_messages_1.MediaPlayingEventMessage) {
|
|
95
|
+
return "playing";
|
|
96
|
+
}
|
|
97
|
+
if (message instanceof media_event_messages_1.MediaWaitingEventMessage) {
|
|
98
|
+
return "waiting";
|
|
99
|
+
}
|
|
100
|
+
if (message instanceof media_event_messages_1.MediaEndedEventMessage) {
|
|
101
|
+
return "ended";
|
|
102
|
+
}
|
|
103
|
+
if (message instanceof media_event_messages_1.MediaLoadedMetadataEventMessage) {
|
|
104
|
+
return "loadedmetadata";
|
|
105
|
+
}
|
|
106
|
+
if (message instanceof media_event_messages_1.MediaSeekingEventMessage) {
|
|
107
|
+
return "seeking";
|
|
108
|
+
}
|
|
109
|
+
if (message instanceof media_event_messages_1.MediaSeekedEventMessage) {
|
|
110
|
+
return "seeked";
|
|
111
|
+
}
|
|
112
|
+
if (message instanceof media_event_messages_1.MediaTimeUpdateEventMessage) {
|
|
113
|
+
return "timeupdate";
|
|
114
|
+
}
|
|
115
|
+
if (message instanceof media_event_messages_1.MediaVolumeChangeEventMessage) {
|
|
116
|
+
return "volumechange";
|
|
117
|
+
}
|
|
118
|
+
if (message instanceof media_event_messages_1.MediaRateChangeEventMessage) {
|
|
119
|
+
return "ratechange";
|
|
120
|
+
}
|
|
121
|
+
if (message instanceof media_event_messages_1.MediaErrorEventMessage) {
|
|
122
|
+
return "error";
|
|
123
|
+
}
|
|
124
|
+
if (message instanceof media_event_messages_1.MediaEnterPictureInPictureEventMessage) {
|
|
125
|
+
return "enterpictureinpicture";
|
|
126
|
+
}
|
|
127
|
+
return "leavepictureinpicture";
|
|
128
|
+
}
|
|
129
|
+
const EVENT_FIELDS = {
|
|
130
|
+
onPlay: "play",
|
|
131
|
+
onPause: "pause",
|
|
132
|
+
onPlaying: "playing",
|
|
133
|
+
onWaiting: "waiting",
|
|
134
|
+
onEnded: "ended",
|
|
135
|
+
onError: "error",
|
|
136
|
+
onLoadedMetadata: "loadedmetadata",
|
|
137
|
+
onSeeking: "seeking",
|
|
138
|
+
onSeeked: "seeked",
|
|
139
|
+
onVolumeChange: "volumechange",
|
|
140
|
+
onRateChange: "ratechange",
|
|
141
|
+
onTimeUpdate: "timeupdate",
|
|
142
|
+
onEnterPictureInPicture: "enterpictureinpicture",
|
|
143
|
+
onLeavePictureInPicture: "leavepictureinpicture",
|
|
144
|
+
};
|
|
145
|
+
/**
|
|
146
|
+
* Сессия `HTMLMediaElement` на клиенте. Элемент не входит в дерево компонентов.
|
|
147
|
+
* `id` — ключ клиентского реестра для будущего видеокомпонента.
|
|
148
|
+
*/
|
|
149
|
+
class Media {
|
|
150
|
+
constructor(client, config, kind) {
|
|
151
|
+
this.client = client;
|
|
152
|
+
this.kind = kind;
|
|
153
|
+
this.id = "media-" + crypto.randomUUID();
|
|
154
|
+
this.handlers = new Map();
|
|
155
|
+
this.ended = false;
|
|
156
|
+
this.rawConfig = config;
|
|
157
|
+
this.bindEvents(config);
|
|
158
|
+
}
|
|
159
|
+
play() {
|
|
160
|
+
return this.send((scope) => new media_play_message_1.MediaPlayMessage(scope, { mediaId: this.id }));
|
|
161
|
+
}
|
|
162
|
+
pause() {
|
|
163
|
+
return this.send((scope) => new media_pause_message_1.MediaPauseMessage(scope, { mediaId: this.id }));
|
|
164
|
+
}
|
|
165
|
+
load() {
|
|
166
|
+
return this.send((scope) => new media_load_message_1.MediaLoadMessage(scope, { mediaId: this.id }));
|
|
167
|
+
}
|
|
168
|
+
seek(time) {
|
|
169
|
+
return this.send((scope) => new media_seek_message_1.MediaSeekMessage(scope, { mediaId: this.id, time }));
|
|
170
|
+
}
|
|
171
|
+
setSrc(src) {
|
|
172
|
+
return this.send((scope) => new media_set_src_message_1.MediaSetSrcMessage(scope, { mediaId: this.id, src }));
|
|
173
|
+
}
|
|
174
|
+
setVolume(volume) {
|
|
175
|
+
return this.send((scope) => new media_set_volume_message_1.MediaSetVolumeMessage(scope, { mediaId: this.id, volume }));
|
|
176
|
+
}
|
|
177
|
+
setMuted(muted) {
|
|
178
|
+
return this.send((scope) => new media_set_muted_message_1.MediaSetMutedMessage(scope, { mediaId: this.id, muted }));
|
|
179
|
+
}
|
|
180
|
+
setPlaybackRate(playbackRate) {
|
|
181
|
+
return this.send((scope) => new media_set_playback_rate_message_1.MediaSetPlaybackRateMessage(scope, {
|
|
182
|
+
mediaId: this.id,
|
|
183
|
+
playbackRate,
|
|
184
|
+
}));
|
|
185
|
+
}
|
|
186
|
+
setLoop(loop) {
|
|
187
|
+
return this.send((scope) => new media_set_loop_message_1.MediaSetLoopMessage(scope, { mediaId: this.id, loop }));
|
|
188
|
+
}
|
|
189
|
+
setPreload(preload) {
|
|
190
|
+
return this.send((scope) => new media_set_preload_message_1.MediaSetPreloadMessage(scope, { mediaId: this.id, preload }));
|
|
191
|
+
}
|
|
192
|
+
destroy() {
|
|
193
|
+
if (this.ended) {
|
|
194
|
+
return (0, rxjs_1.of)(undefined);
|
|
195
|
+
}
|
|
196
|
+
return this.send((scope) => new media_destroy_message_1.MediaDestroyMessage(scope, { mediaId: this.id })).pipe((0, rxjs_1.tap)(() => this.endSession()));
|
|
197
|
+
}
|
|
198
|
+
/** @internal */
|
|
199
|
+
open() {
|
|
200
|
+
return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
|
|
201
|
+
outgoingMessage: (scope) => (0, client_context_1.runWithClient)(this.client, () => new media_create_message_1.MediaCreateMessage(scope, {
|
|
202
|
+
mediaId: this.id,
|
|
203
|
+
kind: this.kind,
|
|
204
|
+
config: this.elementConfig(),
|
|
205
|
+
interactions: this.serializeInteractions(),
|
|
206
|
+
})),
|
|
207
|
+
}).pipe((0, rxjs_1.tap)(() => this.startSession()));
|
|
208
|
+
}
|
|
209
|
+
send(outgoingMessage) {
|
|
210
|
+
return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
|
|
211
|
+
outgoingMessage,
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
elementConfig() {
|
|
215
|
+
const config = this.rawConfig;
|
|
216
|
+
return {
|
|
217
|
+
src: config.src,
|
|
218
|
+
volume: config.volume,
|
|
219
|
+
muted: config.muted,
|
|
220
|
+
loop: config.loop,
|
|
221
|
+
playbackRate: config.playbackRate,
|
|
222
|
+
preload: config.preload,
|
|
223
|
+
crossOrigin: config.crossOrigin,
|
|
224
|
+
autoplay: config.autoplay,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
bindEvents(config) {
|
|
228
|
+
Object.keys(EVENT_FIELDS).forEach((field) => {
|
|
229
|
+
const actions = config[field];
|
|
230
|
+
if (actions === undefined) {
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
const list = (Array.isArray(actions) ? actions : [actions]).map((action) => this.parseAction(action));
|
|
234
|
+
this.handlers.set(EVENT_FIELDS[field], list);
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
parseAction(action) {
|
|
238
|
+
if (action instanceof local_action_1.LocalAction || action instanceof server_action_1.ServerAction) {
|
|
239
|
+
return action;
|
|
240
|
+
}
|
|
241
|
+
if (action instanceof action_1.Action) {
|
|
242
|
+
throw new Error("Media events accept LocalAction, ServerAction, or a server function");
|
|
243
|
+
}
|
|
244
|
+
return new server_action_1.ServerAction(action);
|
|
245
|
+
}
|
|
246
|
+
serializeInteractions() {
|
|
247
|
+
const interactions = {};
|
|
248
|
+
this.handlers.forEach((actions, event) => {
|
|
249
|
+
interactions[event] = actions.map((action) => action.toJSON());
|
|
250
|
+
});
|
|
251
|
+
return interactions;
|
|
252
|
+
}
|
|
253
|
+
startSession() {
|
|
254
|
+
if (this.sessionSubscription || this.ended) {
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
this.sessionSubscription = this.client.incomingMessage$
|
|
258
|
+
.pipe((0, rxjs_1.filter)((message) => isMediaIncomingEvent(message) && message.target === this.id))
|
|
259
|
+
.subscribe((0, incoming_message_observer_1.incomingMessageObserver)(this.client, (message) => {
|
|
260
|
+
const parsed = mediaEventSchema(message).safeParse(message.payload);
|
|
261
|
+
if (!parsed.success) {
|
|
262
|
+
this.client.error$.next(`Invalid media event payload: ${message.type}`);
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
const { handlers, ...payload } = parsed.data;
|
|
266
|
+
this.emit(mediaEventName(message), payload, handlers);
|
|
267
|
+
}));
|
|
268
|
+
this.clientDestroySubscription = this.client.destroy$
|
|
269
|
+
.pipe((0, rxjs_1.take)(1))
|
|
270
|
+
.subscribe(() => this.endSession());
|
|
271
|
+
}
|
|
272
|
+
emit(event, payload, handlers) {
|
|
273
|
+
const actions = this.handlers.get(event);
|
|
274
|
+
if (!actions) {
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
for (const index of handlers) {
|
|
278
|
+
const action = actions[index];
|
|
279
|
+
if (!(action instanceof server_action_1.ServerAction)) {
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
action.execute({
|
|
283
|
+
payload,
|
|
284
|
+
instance: { client: this.client },
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
endSession() {
|
|
289
|
+
if (this.ended) {
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
this.ended = true;
|
|
293
|
+
this.sessionSubscription?.unsubscribe();
|
|
294
|
+
this.clientDestroySubscription?.unsubscribe();
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
exports.Media = Media;
|
|
298
|
+
class Audio extends Media {
|
|
299
|
+
constructor(client, config) {
|
|
300
|
+
super(client, config, media_kind_1.MediaKind.Audio);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
exports.Audio = Audio;
|
|
304
|
+
class Video extends Media {
|
|
305
|
+
constructor(client, config) {
|
|
306
|
+
super(client, config, media_kind_1.MediaKind.Video);
|
|
307
|
+
}
|
|
308
|
+
requestPictureInPicture() {
|
|
309
|
+
return this.send((scope) => new media_request_picture_in_picture_message_1.MediaRequestPictureInPictureMessage(scope, { mediaId: this.id }));
|
|
310
|
+
}
|
|
311
|
+
exitPictureInPicture() {
|
|
312
|
+
return this.send((scope) => new media_exit_picture_in_picture_message_1.MediaExitPictureInPictureMessage(scope, { mediaId: this.id }));
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
exports.Video = Video;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@matreshka/bff",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.38.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,9 +62,9 @@
|
|
|
62
62
|
"vitest": "^4.1.0"
|
|
63
63
|
},
|
|
64
64
|
"dependencies": {
|
|
65
|
-
"@matreshka/client-bff-protocol": "^0.
|
|
65
|
+
"@matreshka/client-bff-protocol": "^0.7.0",
|
|
66
66
|
"@matreshka/gateway-bff-protocol": "^0.1.0",
|
|
67
|
-
"@matreshka/shared": "^0.
|
|
67
|
+
"@matreshka/shared": "^0.26.0",
|
|
68
68
|
"@simplewebauthn/server": "^13.1.1",
|
|
69
69
|
"@simplewebauthn/types": "^12.0.0",
|
|
70
70
|
"fast-xml-parser": "^5.3.3",
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Вычисляет разницу между двумя объектами и возвращает изменённые поля.
|
|
3
|
-
*
|
|
4
|
-
* Поддерживает вложенные объекты. Если изменились все поля вложенного объекта —
|
|
5
|
-
* возвращает его целиком. В противном случае возвращает только изменённые поля.
|
|
6
|
-
*
|
|
7
|
-
* @param oldObj Исходный объект.
|
|
8
|
-
* @param newObj Новый объект.
|
|
9
|
-
* @param prefix Префикс для формирования ключей (используется при рекурсии).
|
|
10
|
-
* @param diff Промежуточное хранилище отличий (используется при рекурсии).
|
|
11
|
-
* @returns Объект с отличиями, где ключ — путь к полю, значение — новое значение.
|
|
12
|
-
*/
|
|
13
|
-
export declare const objectsDiff: (oldObj: Record<string, any>, newObj: Record<string, any>, prefix?: string, diff?: Record<string, unknown>) => Record<string, unknown>;
|
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.objectsDiff = void 0;
|
|
4
|
-
/**
|
|
5
|
-
* Вычисляет разницу между двумя объектами и возвращает изменённые поля.
|
|
6
|
-
*
|
|
7
|
-
* Поддерживает вложенные объекты. Если изменились все поля вложенного объекта —
|
|
8
|
-
* возвращает его целиком. В противном случае возвращает только изменённые поля.
|
|
9
|
-
*
|
|
10
|
-
* @param oldObj Исходный объект.
|
|
11
|
-
* @param newObj Новый объект.
|
|
12
|
-
* @param prefix Префикс для формирования ключей (используется при рекурсии).
|
|
13
|
-
* @param diff Промежуточное хранилище отличий (используется при рекурсии).
|
|
14
|
-
* @returns Объект с отличиями, где ключ — путь к полю, значение — новое значение.
|
|
15
|
-
*/
|
|
16
|
-
const objectsDiff = (oldObj, newObj, prefix = "", diff = {}) => {
|
|
17
|
-
const oldObjectsKeys = Object.keys(oldObj);
|
|
18
|
-
const newObjectsKeys = Object.keys(newObj);
|
|
19
|
-
new Set(oldObjectsKeys.concat(newObjectsKeys)).forEach((key) => {
|
|
20
|
-
// Перебор всех ключей
|
|
21
|
-
if (typeof oldObj[key] === "object" &&
|
|
22
|
-
typeof newObj[key] === "object" &&
|
|
23
|
-
oldObj[key] !== null &&
|
|
24
|
-
newObj[key] !== null) {
|
|
25
|
-
// Проверка на массивы - если это массивы, сравниваем их по ссылке
|
|
26
|
-
if (Array.isArray(oldObj[key]) || Array.isArray(newObj[key])) {
|
|
27
|
-
// Если один из них массив, а другой нет, или это разные ссылки - считаем измененным
|
|
28
|
-
if (Array.isArray(oldObj[key]) !== Array.isArray(newObj[key]) ||
|
|
29
|
-
oldObj[key] !== newObj[key]) {
|
|
30
|
-
diff[prefix + key] = newObj[key];
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
else {
|
|
34
|
-
// если они оба объекты, могли измениться поля внутри
|
|
35
|
-
const nestedDiff = (0, exports.objectsDiff)(oldObj[key], newObj[key], prefix + key + ".");
|
|
36
|
-
if (Object.keys(nestedDiff).length) {
|
|
37
|
-
// Важно понять тип полей, которые изменились
|
|
38
|
-
if (Object.keys(nestedDiff).length >=
|
|
39
|
-
Math.max(Object.keys(oldObj[key]).length, Object.keys(newObj[key]).length) /
|
|
40
|
-
2) {
|
|
41
|
-
// Изменилось больше половины свойств объекта (можно менять условия), тогда меняем сущность целиком для экономии трафика
|
|
42
|
-
diff[prefix + key] = newObj[key];
|
|
43
|
-
}
|
|
44
|
-
else {
|
|
45
|
-
diff = { ...diff, ...nestedDiff };
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
else if (oldObj[key] !== newObj[key]) {
|
|
51
|
-
diff[prefix + key] = newObj[key];
|
|
52
|
-
}
|
|
53
|
-
});
|
|
54
|
-
return diff;
|
|
55
|
-
};
|
|
56
|
-
exports.objectsDiff = objectsDiff;
|