@matreshka/bff 0.27.1 → 0.28.1
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/components/for-each.d.ts +2 -2
- package/dist/components/for-each.js +1 -2
- package/dist/components/item-list/list-from-ref-context.d.ts +2 -2
- package/dist/components/item-list/list-from-ref-context.js +1 -2
- package/dist/core/actions/set-context.d.ts +3 -2
- package/dist/core/context/context-ref.d.ts +3 -3
- package/dist/core/context/context.d.ts +45 -9
- package/dist/core/context/context.js +29 -8
- package/dist/core/utils/replace-context-keys.d.ts +2 -2
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ServerComponentClass } from "@matreshka/client-bff-protocol/enums/server-component-class";
|
|
2
2
|
import type { ForEachConfig } from "@matreshka/client-bff-protocol/types/for-each-config";
|
|
3
3
|
import { Paths, PathValue } from "ts-essentials";
|
|
4
|
-
import { ComponentInstance, ComponentTreeNode, Context, ContextRef, ContextRefValue, JsonObject, StandaloneComponent } from "../core";
|
|
4
|
+
import { AnyContext, ComponentInstance, ComponentTreeNode, Context, ContextRef, ContextRefValue, JsonObject, StandaloneComponent } from "../core";
|
|
5
5
|
import { Component, ComponentInitConfig, ComponentProperties } from "./component";
|
|
6
6
|
type ForEachArrayValue = readonly unknown[] | unknown[];
|
|
7
7
|
type ForEachItemArray<RefType extends ContextRef<any, any>> = Extract<ContextRefValue<RefType>, ForEachArrayValue>;
|
|
@@ -36,7 +36,7 @@ export type ForEachGeneratorProperties<RefType extends ContextRef<any, any>, Com
|
|
|
36
36
|
*/
|
|
37
37
|
export type ForEachProperties = {
|
|
38
38
|
ref: ContextRef;
|
|
39
|
-
componentContext:
|
|
39
|
+
componentContext: AnyContext;
|
|
40
40
|
components?: (ComponentTreeNode | ComponentTreeNode[])[];
|
|
41
41
|
divider?: ComponentTreeNode[];
|
|
42
42
|
} & ComponentProperties;
|
|
@@ -4,7 +4,6 @@ exports.ForEach = exports.forEach = void 0;
|
|
|
4
4
|
const server_component_class_1 = require("@matreshka/client-bff-protocol/enums/server-component-class");
|
|
5
5
|
const for_each_sync_components_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/components/for-each/for-each-sync-components-message");
|
|
6
6
|
const rxjs_1 = require("rxjs");
|
|
7
|
-
const zod_1 = require("zod");
|
|
8
7
|
const core_1 = require("../core");
|
|
9
8
|
const serialize_component_tree_1 = require("../core/utils/serialize-component-tree");
|
|
10
9
|
const track_created_instances_1 = require("../core/utils/track-created-instances");
|
|
@@ -47,7 +46,7 @@ class ForEachContext extends core_1.Context {
|
|
|
47
46
|
super({
|
|
48
47
|
data: async () => ({}),
|
|
49
48
|
preload: preload,
|
|
50
|
-
schema:
|
|
49
|
+
schema: core_1.forbiddenUpdatesSchema, // Запрет изменения из внешних источников
|
|
51
50
|
});
|
|
52
51
|
}
|
|
53
52
|
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { Context, type JsonObject } from "../../core";
|
|
1
|
+
import { Context, type ForbiddenUpdatesSchema, type JsonObject } from "../../core";
|
|
2
2
|
type ItemListIndexContext = Record<string, {
|
|
3
3
|
index: `${number}`;
|
|
4
4
|
}>;
|
|
5
5
|
/** Контекст индексов элементов ItemList; данные не загружаются снаружи. */
|
|
6
|
-
export declare class ItemListIndexStore<T extends JsonObject = ItemListIndexContext> extends Context<T> {
|
|
6
|
+
export declare class ItemListIndexStore<T extends JsonObject = ItemListIndexContext> extends Context<T, ForbiddenUpdatesSchema> {
|
|
7
7
|
/**
|
|
8
8
|
* Синхронно поднимает хранилище до async {@link init}, чтобы `replace` в serialize
|
|
9
9
|
* не перезаписывался пустым `{}` из `initDataCallback`.
|
|
@@ -2,7 +2,6 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.ItemListIndexStore = void 0;
|
|
4
4
|
const rxjs_1 = require("rxjs");
|
|
5
|
-
const zod_1 = require("zod");
|
|
6
5
|
const core_1 = require("../../core");
|
|
7
6
|
/** Контекст индексов элементов ItemList; данные не загружаются снаружи. */
|
|
8
7
|
class ItemListIndexStore extends core_1.Context {
|
|
@@ -22,7 +21,7 @@ class ItemListIndexStore extends core_1.Context {
|
|
|
22
21
|
super({
|
|
23
22
|
data: async () => ({}),
|
|
24
23
|
preload,
|
|
25
|
-
schema:
|
|
24
|
+
schema: core_1.forbiddenUpdatesSchema,
|
|
26
25
|
});
|
|
27
26
|
}
|
|
28
27
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { JsonObject } from "@matreshka/client-bff-protocol/types/json";
|
|
2
|
+
import { z } from "zod";
|
|
2
3
|
import { Context, ContextPathPatch } from "../context/context";
|
|
3
4
|
import { ContextValueOrRef } from "../types/context-value-ref";
|
|
4
5
|
import { ActionConfig } from "./action";
|
|
@@ -12,9 +13,9 @@ export type LocalContextPathPatch<T extends JsonObject> = Partial<{
|
|
|
12
13
|
export declare class SetContext<T extends JsonObject> extends LocalAction {
|
|
13
14
|
private readonly context;
|
|
14
15
|
private readonly patch;
|
|
15
|
-
constructor(context: Context<T>, patch: LocalContextPathPatch<T>, config?: ActionConfig);
|
|
16
|
+
constructor(context: Context<T, z.ZodObject | undefined>, patch: LocalContextPathPatch<T>, config?: ActionConfig);
|
|
16
17
|
class(): string;
|
|
17
18
|
payload(): object;
|
|
18
19
|
}
|
|
19
20
|
/** @internal */
|
|
20
|
-
export declare function createSetContext<T extends JsonObject>(context: Context<T>, patch: LocalContextPathPatch<T>, config?: ActionConfig): SetContext<T>;
|
|
21
|
+
export declare function createSetContext<T extends JsonObject>(context: Context<T, z.ZodObject | undefined>, patch: LocalContextPathPatch<T>, config?: ActionConfig): SetContext<T>;
|
|
@@ -8,7 +8,7 @@ import { SetContext } from "../actions/set-context";
|
|
|
8
8
|
import { ToggleContextValue } from "../actions/toggle-context-value";
|
|
9
9
|
import type { ContextUpdateDelivery } from "../types/context-update-delivery";
|
|
10
10
|
import { ContextValueOrRef } from "../types/context-value-ref";
|
|
11
|
-
import {
|
|
11
|
+
import { AnyContext } from "./context";
|
|
12
12
|
type ContextRefLocalSet<ContextType extends JsonObject, PathType extends string> = {
|
|
13
13
|
set: (value: ContextValueOrRef<PathValue<ContextType, PathType>>, config?: ActionConfig) => SetContext<ContextType>;
|
|
14
14
|
};
|
|
@@ -25,11 +25,11 @@ export type ContextRefValue<R extends ContextRef> = R extends {
|
|
|
25
25
|
readonly __valueType?: infer ValueType;
|
|
26
26
|
} ? Exclude<ValueType, undefined> : R extends ContextRef<infer ContextType, infer PathType> ? PathValue<ContextType, PathType> : never;
|
|
27
27
|
export declare class ContextRef<ContextType extends JsonObject = JsonObject, PathType extends string = string> {
|
|
28
|
-
readonly context:
|
|
28
|
+
readonly context: AnyContext;
|
|
29
29
|
readonly path: PathType;
|
|
30
30
|
/** Локальные (client-only) действия по этому ref. */
|
|
31
31
|
readonly local: ContextRefLocalActions<ContextType, PathType>;
|
|
32
|
-
constructor(context:
|
|
32
|
+
constructor(context: AnyContext, path: PathType);
|
|
33
33
|
/**
|
|
34
34
|
* Продолжение пути в рамках того же контекста.
|
|
35
35
|
* Строго типизировано: K должен быть путём внутри значения по текущему PathType.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { JsonObject } from "@matreshka/client-bff-protocol/types/json";
|
|
2
2
|
import { BehaviorSubject, Observable } from "rxjs";
|
|
3
3
|
import { Paths, PathValue } from "ts-essentials";
|
|
4
|
-
import {
|
|
4
|
+
import { z } from "zod";
|
|
5
5
|
import { ActionConfig } from "../actions/action";
|
|
6
6
|
import { LocalContextPathPatch } from "../actions/set-context";
|
|
7
7
|
import type { Client } from "../client";
|
|
@@ -13,6 +13,40 @@ export type { ContextUpdateDelivery } from "../types/context-update-delivery";
|
|
|
13
13
|
export type ContextPathPatch<T extends JsonObject> = Partial<{
|
|
14
14
|
[K in Paths<T>]: PathValue<T, K>;
|
|
15
15
|
}>;
|
|
16
|
+
/**
|
|
17
|
+
* Пустая strict-схема: клиент не может менять данные контекста через `context-values`.
|
|
18
|
+
* Используется во внутренних контекстах (ForEach, ItemList).
|
|
19
|
+
*/
|
|
20
|
+
export type ForbiddenUpdatesSchema = z.ZodObject<Record<string, never>, z.core.$strict> & {
|
|
21
|
+
readonly __forbiddenUpdatesSchema?: unique symbol;
|
|
22
|
+
};
|
|
23
|
+
/** @see ForbiddenUpdatesSchema */
|
|
24
|
+
export declare const forbiddenUpdatesSchema: ForbiddenUpdatesSchema;
|
|
25
|
+
/**
|
|
26
|
+
* Zod-схема для {@link Context}: описывает подмножество полей `T` без лишних ключей;
|
|
27
|
+
* типы полей согласованы с {@link z.input} схемы и `Partial<T>`.
|
|
28
|
+
*/
|
|
29
|
+
export type ContextSchema<T extends JsonObject, S extends z.ZodObject> = [
|
|
30
|
+
S
|
|
31
|
+
] extends [ForbiddenUpdatesSchema] ? S : Exclude<keyof z.input<S>, keyof T> extends never ? z.input<S> extends Partial<T> ? S : never : never;
|
|
32
|
+
/** Конфиг {@link Context} без клиентской Zod-схемы. */
|
|
33
|
+
export type ContextInitWithoutSchema<T extends JsonObject> = {
|
|
34
|
+
data: () => Promise<T>;
|
|
35
|
+
schema?: undefined;
|
|
36
|
+
preload?: boolean;
|
|
37
|
+
persistent?: boolean;
|
|
38
|
+
};
|
|
39
|
+
/** Конфиг {@link Context} с Zod-схемой клиентских изменений. */
|
|
40
|
+
export type ContextInitWithSchema<T extends JsonObject, S extends z.ZodObject> = {
|
|
41
|
+
data: () => Promise<T>;
|
|
42
|
+
schema: ContextSchema<T, S>;
|
|
43
|
+
preload?: boolean;
|
|
44
|
+
persistent?: boolean;
|
|
45
|
+
};
|
|
46
|
+
/** Конфигурация {@link Context} (один аргумент конструктора). */
|
|
47
|
+
export type ContextInitConfig<T extends JsonObject, S extends z.ZodObject | undefined = undefined> = S extends z.ZodObject ? ContextInitWithSchema<T, S> : ContextInitWithoutSchema<T>;
|
|
48
|
+
/** Любой зарегистрированный контекст (с Zod-схемой или без). */
|
|
49
|
+
export type AnyContext = Context<any, any>;
|
|
16
50
|
/**
|
|
17
51
|
* Контекст данных, связанных с клиентом.
|
|
18
52
|
*
|
|
@@ -20,14 +54,15 @@ export type ContextPathPatch<T extends JsonObject> = Partial<{
|
|
|
20
54
|
* а также для отслеживания ошибок валидации и управления реактивными изменениями.
|
|
21
55
|
*
|
|
22
56
|
* @template T Тип структуры данных контекста.
|
|
57
|
+
* @template S Zod-схема валидации клиентских изменений (см. {@link ContextSchema}).
|
|
23
58
|
*/
|
|
24
|
-
export declare class Context<T extends JsonObject> {
|
|
59
|
+
export declare class Context<T extends JsonObject, S extends z.ZodObject | undefined = undefined> {
|
|
25
60
|
/** Уникальный идентификатор контекста */
|
|
26
61
|
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
27
62
|
/** Реактивное хранилище данных контекста. */
|
|
28
63
|
protected data$?: BehaviorSubject<T>;
|
|
29
64
|
/** Схема валидации данных контекста */
|
|
30
|
-
readonly schema?: ZodObject;
|
|
65
|
+
readonly schema?: S extends z.ZodObject ? S : undefined;
|
|
31
66
|
/** Флаг, указывающий, что контекст должен быть инициализирован при авторизации клиента */
|
|
32
67
|
readonly preload: boolean;
|
|
33
68
|
/**
|
|
@@ -61,6 +96,12 @@ export declare class Context<T extends JsonObject> {
|
|
|
61
96
|
private skipNextDataSync;
|
|
62
97
|
private assertNotDestroyed;
|
|
63
98
|
private assertInitialized;
|
|
99
|
+
/**
|
|
100
|
+
* Клиентское `context-values` разрешено только по ключам {@link schema}.
|
|
101
|
+
* Нет схемы или ключ вне неё — `Error`, patch не применяется.
|
|
102
|
+
* Несовпадение типа остаётся `ZodError` из `parse`.
|
|
103
|
+
*/
|
|
104
|
+
private assertClientChangeAllowed;
|
|
64
105
|
/** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
|
|
65
106
|
private reportInitFailureToClients;
|
|
66
107
|
/**
|
|
@@ -69,12 +110,7 @@ export declare class Context<T extends JsonObject> {
|
|
|
69
110
|
* Подписывается на входящие сообщения от клиента и ошибки, связанные с этим контекстом.
|
|
70
111
|
|
|
71
112
|
*/
|
|
72
|
-
constructor(config:
|
|
73
|
-
data: () => Promise<T>;
|
|
74
|
-
schema?: ZodObject;
|
|
75
|
-
preload?: boolean;
|
|
76
|
-
persistent?: boolean;
|
|
77
|
-
});
|
|
113
|
+
constructor(config: S extends z.ZodObject ? ContextInitWithSchema<T, S> : ContextInitWithoutSchema<T>);
|
|
78
114
|
/** `data$` создан (init мог ещё выполняться — см. {@link init}). */
|
|
79
115
|
inited(): boolean;
|
|
80
116
|
/** Данные загружены: `initDataCallback` завершился. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.Context = void 0;
|
|
3
|
+
exports.Context = exports.forbiddenUpdatesSchema = void 0;
|
|
4
4
|
const index_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/context/index");
|
|
5
5
|
const index_2 = require("@matreshka/client-bff-protocol/messages/client-to-bff/context/index");
|
|
6
6
|
const targeted_message_1 = require("@matreshka/client-bff-protocol/messages/targeted-message");
|
|
@@ -18,6 +18,8 @@ const incoming_message_observer_1 = require("../utils/incoming-message-observer"
|
|
|
18
18
|
const objects_diff_1 = require("../utils/objects-diff");
|
|
19
19
|
const replace_context_keys_1 = require("../utils/replace-context-keys");
|
|
20
20
|
const context_ref_1 = require("./context-ref");
|
|
21
|
+
/** @see ForbiddenUpdatesSchema */
|
|
22
|
+
exports.forbiddenUpdatesSchema = zod_1.z.strictObject({});
|
|
21
23
|
/** Отделяет чтение через {@link Context.get} от живого дерева в хранилище. */
|
|
22
24
|
function cloneGetResult(value) {
|
|
23
25
|
if (value !== null && typeof value === "object") {
|
|
@@ -74,6 +76,7 @@ function unbindClient(contextId, client) {
|
|
|
74
76
|
* а также для отслеживания ошибок валидации и управления реактивными изменениями.
|
|
75
77
|
*
|
|
76
78
|
* @template T Тип структуры данных контекста.
|
|
79
|
+
* @template S Zod-схема валидации клиентских изменений (см. {@link ContextSchema}).
|
|
77
80
|
*/
|
|
78
81
|
class Context {
|
|
79
82
|
assertNotDestroyed() {
|
|
@@ -86,6 +89,25 @@ class Context {
|
|
|
86
89
|
throw new Error(`Context ${this.id} is not initialized`);
|
|
87
90
|
}
|
|
88
91
|
}
|
|
92
|
+
/**
|
|
93
|
+
* Клиентское `context-values` разрешено только по ключам {@link schema}.
|
|
94
|
+
* Нет схемы или ключ вне неё — `Error`, patch не применяется.
|
|
95
|
+
* Несовпадение типа остаётся `ZodError` из `parse`.
|
|
96
|
+
*/
|
|
97
|
+
assertClientChangeAllowed(key, value) {
|
|
98
|
+
if (!this.schema) {
|
|
99
|
+
throw new Error(`Context ${this.id} rejected client update for "${key}": validation schema is not set`);
|
|
100
|
+
}
|
|
101
|
+
let keySchema;
|
|
102
|
+
try {
|
|
103
|
+
keySchema = (0, deep_pick_1.zodDeepPick)(this.schema, key);
|
|
104
|
+
}
|
|
105
|
+
catch (cause) {
|
|
106
|
+
const reason = cause instanceof Error ? cause.message : String(cause);
|
|
107
|
+
throw new Error(`Context ${this.id} rejected client update for "${key}": key is not described in the validation schema (${reason})`);
|
|
108
|
+
}
|
|
109
|
+
keySchema.parse(value);
|
|
110
|
+
}
|
|
89
111
|
/** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
|
|
90
112
|
reportInitFailureToClients(error) {
|
|
91
113
|
getRegistryEntry(this.id)?.clients.forEach((_, client) => {
|
|
@@ -117,7 +139,7 @@ class Context {
|
|
|
117
139
|
this.clientSubscriptions = new Map();
|
|
118
140
|
/** Серверный set/replace уже сам отправил diff; в subscribeToDataChanges повторять не нужно. */
|
|
119
141
|
this.skipNextDataSync = false;
|
|
120
|
-
this.schema = config.schema;
|
|
142
|
+
this.schema = ("schema" in config ? config.schema : undefined);
|
|
121
143
|
registerContext(this);
|
|
122
144
|
this.initDataCallback = config.data;
|
|
123
145
|
this.preload = config.preload ?? false;
|
|
@@ -217,14 +239,13 @@ class Context {
|
|
|
217
239
|
if (unsafeMessage instanceof index_2.ContextValuesMessage) {
|
|
218
240
|
const payloadSchema = zod_1.z.array(zod_1.z.strictObject({ key: zod_1.z.string(), value: zod_1.z.unknown() }));
|
|
219
241
|
const changes = payloadSchema.parse(unsafeMessage.payload);
|
|
242
|
+
for (const change of changes) {
|
|
243
|
+
this.assertClientChangeAllowed(change.key, change.value);
|
|
244
|
+
}
|
|
220
245
|
const patch = {};
|
|
221
|
-
|
|
222
|
-
if (this.schema) {
|
|
223
|
-
const keySchema = (0, deep_pick_1.zodDeepPick)(this.schema, change.key);
|
|
224
|
-
keySchema.parse(change.value);
|
|
225
|
-
}
|
|
246
|
+
for (const change of changes) {
|
|
226
247
|
patch[change.key] = change.value;
|
|
227
|
-
}
|
|
248
|
+
}
|
|
228
249
|
this.dataChangedByClient = client;
|
|
229
250
|
this.set(patch);
|
|
230
251
|
return;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { AnyContext } from "../context/context";
|
|
2
2
|
/**
|
|
3
3
|
* Заменяет плейсхолдеры вида `@{ключ}` в строке значениями из объекта контекста.
|
|
4
4
|
*
|
|
@@ -9,4 +9,4 @@ import type { Context } from "../context/context";
|
|
|
9
9
|
* @param resolveContext Поиск контекста по id.
|
|
10
10
|
* @returns Строка с заменёнными плейсхолдерами.
|
|
11
11
|
*/
|
|
12
|
-
export declare function replaceContextKeys(str: string, resolveContext: (contextId: string) =>
|
|
12
|
+
export declare function replaceContextKeys(str: string, resolveContext: (contextId: string) => AnyContext | undefined): string;
|
package/package.json
CHANGED