@matreshka/bff 0.30.2 → 0.32.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.
Files changed (34) hide show
  1. package/dist/components/for-each.d.ts +19 -11
  2. package/dist/components/inputs/input-component.d.ts +5 -5
  3. package/dist/components/inputs/number-input.js +3 -1
  4. package/dist/components/inputs/password-input.js +3 -1
  5. package/dist/components/inputs/text-editor.js +3 -1
  6. package/dist/components/inputs/text-input.js +3 -1
  7. package/dist/components/inputs/textarea.js +3 -1
  8. package/dist/components/item-list/item-list.d.ts +3 -3
  9. package/dist/components/item-list/list-from-ref-context.d.ts +2 -2
  10. package/dist/components/item-list/types.d.ts +18 -13
  11. package/dist/components/outputs/output-component.d.ts +5 -5
  12. package/dist/components/types/component-sequence.d.ts +2 -2
  13. package/dist/core/actions/dec-context-value.d.ts +3 -3
  14. package/dist/core/actions/inc-context-value.d.ts +4 -4
  15. package/dist/core/actions/set-context.d.ts +8 -7
  16. package/dist/core/actions/toggle-context-value.d.ts +3 -3
  17. package/dist/core/conditions/condition-operand.d.ts +9 -9
  18. package/dist/core/conditions/context-array-includes.d.ts +4 -4
  19. package/dist/core/conditions/context-array-length.d.ts +15 -15
  20. package/dist/core/conditions/context-value-defined.d.ts +3 -3
  21. package/dist/core/conditions/context-value-defined.js +1 -1
  22. package/dist/core/conditions/context-value-equal.d.ts +2 -2
  23. package/dist/core/conditions/context-value-in.d.ts +2 -2
  24. package/dist/core/conditions/context-value-not-equal.d.ts +2 -2
  25. package/dist/core/conditions/context-value-undefined.d.ts +3 -3
  26. package/dist/core/conditions/context-value-undefined.js +1 -1
  27. package/dist/core/context/context-create.d.ts +91 -0
  28. package/dist/core/context/context-create.js +7 -0
  29. package/dist/core/context/context-ref.d.ts +20 -17
  30. package/dist/core/context/context.d.ts +35 -91
  31. package/dist/core/context/context.js +25 -4
  32. package/dist/core/types/context-value-ref.d.ts +54 -10
  33. package/dist/platforms/platform.d.ts +5 -5
  34. package/package.json +1 -1
@@ -7,8 +7,8 @@ import { ConditionOperand } from "./condition-operand";
7
7
  *
8
8
  * @internal Используйте {@link contextValueIn} / {@link when.oneOf}.
9
9
  */
10
- export declare class ContextValueIn<R extends ContextRef<any, any>> extends Condition {
10
+ export declare class ContextValueIn<R extends ContextRef<any, any, any>> extends Condition {
11
11
  constructor(ref: R, value: ConditionOperand<R>[]);
12
12
  }
13
13
  /** Функциональная форма {@link ContextValueIn}. */
14
- export declare function contextValueIn<R extends ContextRef<any, any>>(ref: R, value: ConditionOperand<R>[]): ContextValueIn<R>;
14
+ export declare function contextValueIn<R extends ContextRef<any, any, any>>(ref: R, value: ConditionOperand<R>[]): ContextValueIn<R>;
@@ -7,8 +7,8 @@ import { ConditionOperand } from "./condition-operand";
7
7
  *
8
8
  * @internal Используйте {@link contextValueNotEqual} / {@link when.notEquals}.
9
9
  */
10
- export declare class ContextValueNotEqual<R extends ContextRef<any, any>> extends Condition {
10
+ export declare class ContextValueNotEqual<R extends ContextRef<any, any, any>> extends Condition {
11
11
  constructor(ref: R, value: ConditionOperand<R>);
12
12
  }
13
13
  /** Функциональная форма {@link ContextValueNotEqual}. */
14
- export declare function contextValueNotEqual<R extends ContextRef<any, any>>(ref: R, value: ConditionOperand<R>): ContextValueNotEqual<R>;
14
+ export declare function contextValueNotEqual<R extends ContextRef<any, any, any>>(ref: R, value: ConditionOperand<R>): ContextValueNotEqual<R>;
@@ -3,7 +3,7 @@ import { Condition } from "./condition";
3
3
  /**
4
4
  * Условие, означающее, что значение в контексте по заданному ключу не определено.
5
5
  *
6
- * Параметр — `R extends ContextRef<any, any>`. Голый `ContextRef` раскрывается
6
+ * Параметр — `R extends ContextRef<any, any, any>`. Голый `ContextRef` раскрывается
7
7
  * в `ContextRef<JsonObject, string>`. Метод `local.set` принимает значение по пути,
8
8
  * поэтому ссылка инвариантна: при `strictFunctionTypes` конкретный ref страницы
9
9
  * в этот параметр не входит. `any` в ограничении выводит `R` из аргумента
@@ -11,8 +11,8 @@ import { Condition } from "./condition";
11
11
  *
12
12
  * @internal Используйте {@link contextValueUndefined} / {@link when.notDefined}.
13
13
  */
14
- export declare class ContextValueUndefined<R extends ContextRef<any, any>> extends Condition {
14
+ export declare class ContextValueUndefined<R extends ContextRef<any, any, any>> extends Condition {
15
15
  constructor(ref: R);
16
16
  }
17
17
  /** Функциональная форма {@link ContextValueUndefined}. */
18
- export declare function contextValueUndefined<R extends ContextRef<any, any>>(ref: R): ContextValueUndefined<R>;
18
+ export declare function contextValueUndefined<R extends ContextRef<any, any, any>>(ref: R): ContextValueUndefined<R>;
@@ -7,7 +7,7 @@ const condition_1 = require("./condition");
7
7
  /**
8
8
  * Условие, означающее, что значение в контексте по заданному ключу не определено.
9
9
  *
10
- * Параметр — `R extends ContextRef<any, any>`. Голый `ContextRef` раскрывается
10
+ * Параметр — `R extends ContextRef<any, any, any>`. Голый `ContextRef` раскрывается
11
11
  * в `ContextRef<JsonObject, string>`. Метод `local.set` принимает значение по пути,
12
12
  * поэтому ссылка инвариантна: при `strictFunctionTypes` конкретный ref страницы
13
13
  * в этот параметр не входит. `any` в ограничении выводит `R` из аргумента
@@ -0,0 +1,91 @@
1
+ import { JsonObject } from "@matreshka/client-bff-protocol/types/json";
2
+ import { z } from "zod";
3
+ import { Context } from "./context";
4
+ /** Карта файла:
5
+ * 1) type-хелперы валидации schema↔data (extra-keys, compatibility)
6
+ * 2) публичные типы createContext
7
+ * 3) overload-ы и runtime-реализация createContext
8
+ */
9
+ type StripNullish<T> = Exclude<T, null | undefined>;
10
+ type ArrayElement<T> = T extends readonly (infer E)[] ? E : never;
11
+ type FieldExtraSchemaKeysOne<TField, IField> = [StripNullish<IField>] extends [
12
+ readonly unknown[]
13
+ ] ? [StripNullish<TField>] extends [readonly unknown[]] ? ExtraSchemaKeys<ArrayElement<StripNullish<TField>>, ArrayElement<StripNullish<IField>>> : never : [StripNullish<IField>] extends [JsonObject] ? [StripNullish<TField>] extends [JsonObject] ? ExtraSchemaKeys<StripNullish<TField>, StripNullish<IField>> : never : never;
14
+ /** Лишние ключи внутри поля (union, optional/nullable, массивы объектов). */
15
+ type FieldExtraSchemaKeys<TField, IField> = IField extends any ? FieldExtraSchemaKeysOne<TField, IField> : never;
16
+ /** Лишние ключи для одной пары object-веток (коррелированные поля). `true` — есть лишние ключи. */
17
+ type ExtraSchemaKeysObjectExact<T extends JsonObject, Input extends JsonObject> = Exclude<keyof Input, keyof T> extends never ? {
18
+ [K in keyof Input & keyof T]: FieldExtraSchemaKeys<T[K], Input[K]>;
19
+ }[keyof Input & keyof T] extends never ? never : true : true;
20
+ /** Есть ветка `T`, для которой `Input` не содержит лишних ключей. */
21
+ type SomeExtraSchemaKeysBranchOk<T, Input extends JsonObject> = T extends JsonObject ? ExtraSchemaKeysObjectExact<T, Input> extends never ? true : never : never;
22
+ /**
23
+ * Лишние ключи в shape схемы относительно `T` (рекурсивно).
24
+ * Union в `Input` и `T` проверяется по отдельным веткам. `true` — есть лишние ключи.
25
+ */
26
+ type ExtraSchemaKeys<T, Input> = Input extends JsonObject ? SomeExtraSchemaKeysBranchOk<T, Input> extends true ? never : true : never;
27
+ type DeepPartial<T> = T extends readonly (infer E)[] ? readonly DeepPartial<E>[] : T extends object ? {
28
+ [K in keyof T]?: DeepPartial<T[K]>;
29
+ } : T;
30
+ type SchemaOutputCompatible<T extends JsonObject, S extends z.ZodObject> = z.output<S> extends DeepPartial<T> ? true : false;
31
+ /**
32
+ * Zod-схема для {@link createContext}: без лишних ключей во {@link z.input} и {@link z.output}
33
+ * ({@link ExtraSchemaKeys}, union по веткам); {@link z.output} совместим с `T`
34
+ * ({@link SchemaOutputCompatible}, через deep partial). В контекст попадает output после `parse()`.
35
+ */
36
+ export type ContextSchema<T extends JsonObject, S extends z.ZodObject> = SchemaOutputCompatible<T, S> extends false ? never : ExtraSchemaKeys<T, z.input<S>> extends never ? ExtraSchemaKeys<T, z.output<S>> extends never ? S : never : never;
37
+ /** Конфиг {@link createContext} без клиентской Zod-схемы. */
38
+ export type ContextInitWithoutSchema<T extends JsonObject> = {
39
+ data: () => Promise<T>;
40
+ schema?: undefined;
41
+ preload?: boolean;
42
+ persistent?: boolean;
43
+ };
44
+ /** Конфиг {@link createContext} с Zod-схемой клиентских изменений. */
45
+ export type ContextInitWithSchema<T extends JsonObject, S extends z.ZodObject> = {
46
+ data: () => Promise<T>;
47
+ schema: ContextSchema<T, S>;
48
+ preload?: boolean;
49
+ persistent?: boolean;
50
+ };
51
+ /** Конфигурация {@link createContext} (единственный аргумент). */
52
+ export type ContextInitConfig<T extends JsonObject, S extends z.ZodObject | undefined = undefined> = S extends z.ZodObject ? ContextInitWithSchema<T, S> : ContextInitWithoutSchema<T>;
53
+ /** Минимальная форма аргумента {@link createContext}. */
54
+ type ContextInitShape = {
55
+ data: () => Promise<JsonObject>;
56
+ schema?: z.ZodObject;
57
+ preload?: boolean;
58
+ persistent?: boolean;
59
+ };
60
+ /** Тип данных `T` из поля `data` конфига. */
61
+ export type ContextDataFromInit<C extends ContextInitShape> = Awaited<ReturnType<C["data"]>>;
62
+ /** Zod-схема из поля `schema` конфига (или `undefined`). */
63
+ export type ContextSchemaFromInit<C extends ContextInitShape> = C extends {
64
+ schema: z.ZodObject;
65
+ } ? C["schema"] : undefined;
66
+ /** Экземпляр {@link Context} по форме конфига {@link createContext}. */
67
+ export type ContextFromInit<C extends ContextInitShape> = Context<ContextDataFromInit<C>, ContextSchemaFromInit<C>>;
68
+ type ContextSchemaCompatibilityGuard<C extends ContextInitShape> = C extends {
69
+ schema: z.ZodObject;
70
+ } ? ContextSchema<ContextDataFromInit<C>, NoInfer<C["schema"]>> extends never ? {
71
+ /**
72
+ * Type helper for better diagnostics:
73
+ * schema must be a subset of data keys and have output-compatible field types.
74
+ */
75
+ __contextSchemaError__: "createContext(schema): schema is incompatible with data";
76
+ } : unknown : unknown;
77
+ type ContextCreateConfig<C extends ContextInitShape> = C & ContextSchemaCompatibilityGuard<C>;
78
+ /**
79
+ * Создаёт контекст данных BFF: хранилище состояния с синхронизацией клиент ↔ сервер.
80
+ *
81
+ * Тип данных выводится из `data`, тип Zod-схемы — из `schema`. Связь проверяется через
82
+ * {@link ContextSchema}.
83
+ *
84
+ * Если в начальном `data` нет части полей (например опциональных), укажите тип на колбэке:
85
+ * `data: async (): Promise<MyT> => ({ … })`.
86
+ */
87
+ export declare function createContext<const T extends JsonObject>(config: ContextInitWithoutSchema<T>): Context<T, undefined>;
88
+ export declare function createContext<const C extends ContextInitShape & {
89
+ schema: z.ZodObject;
90
+ }>(config: ContextCreateConfig<C>): Context<ContextDataFromInit<C>, ContextSchemaFromInit<C>>;
91
+ export {};
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createContext = createContext;
4
+ const context_1 = require("./context");
5
+ function createContext(config) {
6
+ return context_1.Context.createRuntime(config);
7
+ }
@@ -1,45 +1,48 @@
1
1
  import { JsonObject } from "@matreshka/client-bff-protocol/types/json";
2
2
  import { Observable } from "rxjs";
3
3
  import { Paths, PathValue } from "ts-essentials";
4
+ import { z } from "zod";
4
5
  import { ActionConfig } from "../actions/action";
5
6
  import { DecContextValue } from "../actions/dec-context-value";
6
7
  import { IncContextValue } from "../actions/inc-context-value";
7
8
  import { SetContext } from "../actions/set-context";
8
9
  import { ToggleContextValue } from "../actions/toggle-context-value";
9
10
  import type { ContextUpdateDelivery } from "../types/context-update-delivery";
10
- import { ContextValueOrRef } from "../types/context-value-ref";
11
- import { Context } from "./context";
12
- type ContextRefLocalSet<ContextType extends JsonObject, PathType extends string> = {
13
- set: (value: ContextValueOrRef<PathValue<ContextType, PathType>>, config?: ActionConfig) => SetContext<ContextType>;
14
- };
11
+ import { ValueOrContextRef } from "../types/context-value-ref";
12
+ import { Context, WritableContextPath, WritablePathValue } from "./context";
13
+ type ContextRefLocalSet<ContextType extends JsonObject, PathType extends string, SchemaType extends z.ZodObject | undefined> = PathType extends WritableContextPath<ContextType, SchemaType> ? {
14
+ set: (value: ValueOrContextRef<WritablePathValue<SchemaType, PathType>>, config?: ActionConfig) => SetContext<ContextType, SchemaType>;
15
+ } : {};
15
16
  type ContextRefLocalToggle = {
16
17
  toggle: (config?: ActionConfig) => ToggleContextValue;
17
18
  };
18
19
  type ContextRefLocalNumeric = {
19
- inc: (step?: ContextValueOrRef<number>, config?: ActionConfig) => IncContextValue;
20
- dec: (step?: ContextValueOrRef<number>, config?: ActionConfig) => DecContextValue;
20
+ inc: (step?: ValueOrContextRef<number>, config?: ActionConfig) => IncContextValue;
21
+ dec: (step?: ValueOrContextRef<number>, config?: ActionConfig) => DecContextValue;
21
22
  };
22
23
  /** Локальные действия по ref; `toggle` / `inc` / `dec` — по типу значения по пути. */
23
- export type ContextRefLocalActions<ContextType extends JsonObject, PathType extends string> = ContextRefLocalSet<ContextType, PathType> & (PathValue<ContextType, PathType> extends boolean | undefined ? ContextRefLocalToggle : {}) & (PathValue<ContextType, PathType> extends number | undefined ? ContextRefLocalNumeric : {});
24
- export type ContextRefValue<R extends ContextRef> = R extends {
24
+ export type ContextRefLocalActions<ContextType extends JsonObject, PathType extends string, SchemaType extends z.ZodObject | undefined> = ContextRefLocalSet<ContextType, PathType, SchemaType> & (PathType extends WritableContextPath<ContextType, SchemaType> ? WritablePathValue<SchemaType, PathType> extends boolean | undefined ? ContextRefLocalToggle : {} : {}) & (PathType extends WritableContextPath<ContextType, SchemaType> ? WritablePathValue<SchemaType, PathType> extends number | undefined ? ContextRefLocalNumeric : {} : {});
25
+ export type AnySchemaContextRef<ContextType extends JsonObject = any, PathType extends string = any> = ContextRef<ContextType, PathType, undefined> | ContextRef<ContextType, PathType, z.ZodObject>;
26
+ export type ContextRefValueType<R extends AnySchemaContextRef> = R extends {
25
27
  readonly __valueType?: infer ValueType;
26
- } ? Exclude<ValueType, undefined> : R extends ContextRef<infer ContextType, infer PathType> ? PathValue<ContextType, PathType> : never;
27
- export declare class ContextRef<ContextType extends JsonObject = JsonObject, PathType extends string = string> {
28
- readonly context: Context<ContextType>;
28
+ } ? Exclude<ValueType, undefined> : R extends ContextRef<infer ContextType, infer PathType, any> ? PathValue<ContextType, PathType> : never;
29
+ export declare class ContextRef<ContextType extends JsonObject = JsonObject, PathType extends string = string, SchemaType extends z.ZodObject | undefined = any> {
30
+ readonly context: Context<ContextType, SchemaType>;
29
31
  readonly path: PathType;
32
+ readonly __schemaType?: SchemaType;
30
33
  /** Локальные (client-only) действия по этому ref. */
31
- readonly local: ContextRefLocalActions<ContextType, PathType>;
32
- constructor(context: Context<ContextType>, path: PathType);
34
+ readonly local: ContextRefLocalActions<ContextType, PathType, SchemaType>;
35
+ constructor(context: Context<ContextType, SchemaType>, path: PathType);
33
36
  /**
34
37
  * Продолжение пути в рамках того же контекста.
35
38
  * Строго типизировано: K должен быть путём внутри значения по текущему PathType.
36
39
  */
37
- ref<K extends Paths<PathValue<ContextType, PathType>>>(path: K): ContextRef<ContextType, `${PathType}.${K}`>;
40
+ ref<K extends Paths<PathValue<ContextType, PathType>>>(path: K): ContextRef<ContextType, `${PathType}.${K}`, SchemaType>;
38
41
  /**
39
42
  * Продолжение пути, если передан другой ContextRef того же контекста.
40
43
  * В этом случае итоговый путь становится `${PathType}.${P2}`.
41
44
  */
42
- ref<P2 extends string>(path: ContextRef<ContextType, P2>): ContextRef<ContextType, `${PathType}.${P2}`>;
45
+ ref<P2 extends string, OtherSchemaType extends z.ZodObject | undefined>(path: ContextRef<ContextType, P2, OtherSchemaType>): ContextRef<ContextType, `${PathType}.${P2}`, SchemaType>;
43
46
  /**
44
47
  * Дописывает к текущему пути **плейсхолдер** второго контекста: строку вида
45
48
  * `@{<id контекста other>.<путь other>}` (через `other.toString()`), без подстановки
@@ -63,7 +66,7 @@ export declare class ContextRef<ContextType extends JsonObject = JsonObject, Pat
63
66
  *
64
67
  * @experimental
65
68
  */
66
- strictRef<OtherContextType extends JsonObject, OtherPathType extends Paths<OtherContextType>>(other: ContextRef<OtherContextType, OtherPathType>): ContextRef<ContextType, `${PathType}.${PathValue<OtherContextType, OtherPathType> & string}`>;
69
+ strictRef<OtherContextType extends JsonObject, OtherSchemaType extends z.ZodObject | undefined, OtherPathType extends Paths<OtherContextType>>(other: ContextRef<OtherContextType, OtherPathType, OtherSchemaType>): ContextRef<ContextType, `${PathType}.${PathValue<OtherContextType, OtherPathType> & string}`, SchemaType>;
67
70
  /** Значение по текущему пути (делегирует {@link Context.get}). */
68
71
  get(): PathValue<ContextType, PathType>;
69
72
  /**
@@ -3,16 +3,29 @@ import { BehaviorSubject, Observable } from "rxjs";
3
3
  import { Paths, PathValue } from "ts-essentials";
4
4
  import { z } from "zod";
5
5
  import { ActionConfig } from "../actions/action";
6
+ import { DecContextValue } from "../actions/dec-context-value";
7
+ import { IncContextValue } from "../actions/inc-context-value";
6
8
  import { LocalContextPathPatch } from "../actions/set-context";
9
+ import { ToggleContextValue } from "../actions/toggle-context-value";
7
10
  import type { Client } from "../client";
8
11
  import { ContextUpdateDelivery } from "../types/context-update-delivery";
9
- import { ContextValueOrRef } from "../types/context-value-ref";
12
+ import type { ValueOrContextRef } from "../types/context-value-ref";
10
13
  import { ContextRef } from "./context-ref";
11
14
  export type { ContextUpdateDelivery } from "../types/context-update-delivery";
15
+ export * from "./context-create";
12
16
  /** Частичное обновление данных контекста по dotted-путям (см. {@link Context.set}). */
13
17
  export type ContextPathPatch<T extends JsonObject> = Partial<{
14
18
  [K in Paths<T>]: PathValue<T, K>;
15
19
  }>;
20
+ /** Входная форма данных, которые клиент может отправить в `context-values`. */
21
+ export type WritableSchemaInput<S extends z.ZodObject | undefined> = S extends z.ZodObject ? z.input<S> extends JsonObject ? z.input<S> : never : never;
22
+ /** Dotted-пути, разрешённые для клиентской записи (по `schema`). */
23
+ type IsAny<T> = 0 extends 1 & T ? true : false;
24
+ export type WritablePath<S extends z.ZodObject | undefined> = IsAny<S> extends true ? string : S extends z.ZodObject ? Paths<WritableSchemaInput<S>> : never;
25
+ /** Тип значения по writable-пути `P` (из `schema` input). */
26
+ export type WritablePathValue<S extends z.ZodObject | undefined, P extends string> = IsAny<S> extends true ? unknown : S extends z.ZodObject ? P extends Paths<WritableSchemaInput<S>> ? PathValue<WritableSchemaInput<S>, P> : never : never;
27
+ /** Пересечение путей контекста и путей `schema`, доступных для client write. */
28
+ export type WritableContextPath<T extends JsonObject, S extends z.ZodObject | undefined> = Extract<Paths<T>, WritablePath<S>>;
16
29
  /**
17
30
  * Пустая strict-схема: клиент не может менять данные контекста через `context-values`.
18
31
  * Используется во внутренних контекстах (ForEach, ItemList).
@@ -22,72 +35,12 @@ export type ContextClientUpdatesForbiddenSchema = z.ZodObject<Record<string, nev
22
35
  };
23
36
  /** @see ContextClientUpdatesForbiddenSchema */
24
37
  export declare const contextClientUpdatesForbiddenSchema: ContextClientUpdatesForbiddenSchema;
25
- type StripNullish<T> = Exclude<T, null | undefined>;
26
- type ArrayElement<T> = T extends readonly (infer E)[] ? E : never;
27
- type FieldExtraSchemaKeysOne<TField, IField> = [StripNullish<IField>] extends [
28
- readonly unknown[]
29
- ] ? [StripNullish<TField>] extends [readonly unknown[]] ? ExtraSchemaKeys<ArrayElement<StripNullish<TField>>, ArrayElement<StripNullish<IField>>> : never : [StripNullish<IField>] extends [JsonObject] ? [StripNullish<TField>] extends [JsonObject] ? ExtraSchemaKeys<StripNullish<TField>, StripNullish<IField>> : never : never;
30
- /** Лишние ключи внутри поля (union, optional/nullable, массивы объектов). */
31
- type FieldExtraSchemaKeys<TField, IField> = IField extends any ? FieldExtraSchemaKeysOne<TField, IField> : never;
32
- /** Лишние ключи для одной пары object-веток (коррелированные поля). `true` — есть лишние ключи. */
33
- type ExtraSchemaKeysObjectExact<T extends JsonObject, Input extends JsonObject> = Exclude<keyof Input, keyof T> extends never ? {
34
- [K in keyof Input & keyof T]: FieldExtraSchemaKeys<T[K], Input[K]>;
35
- }[keyof Input & keyof T] extends never ? never : true : true;
36
- /** Есть ветка `T`, для которой `Input` не содержит лишних ключей. */
37
- type SomeExtraSchemaKeysBranchOk<T, Input extends JsonObject> = T extends JsonObject ? ExtraSchemaKeysObjectExact<T, Input> extends never ? true : never : never;
38
- /**
39
- * Лишние ключи в shape схемы относительно `T` (рекурсивно).
40
- * Union в `Input` и `T` проверяется по отдельным веткам. `true` — есть лишние ключи.
41
- */
42
- type ExtraSchemaKeys<T, Input> = Input extends JsonObject ? SomeExtraSchemaKeysBranchOk<T, Input> extends true ? never : true : never;
43
- type SchemaInputKeysSubset<T extends JsonObject, S extends z.ZodObject> = Exclude<keyof z.input<S>, keyof T> extends never ? true : false;
44
- type DeepPartial<T> = T extends readonly (infer E)[] ? readonly DeepPartial<E>[] : T extends object ? {
45
- [K in keyof T]?: DeepPartial<T[K]>;
46
- } : T;
47
- type SchemaOutputCompatible<T extends JsonObject, S extends z.ZodObject> = z.output<S> extends DeepPartial<T> ? true : false;
48
- /**
49
- * Zod-схема для {@link createContext}: без лишних ключей во {@link z.input} и {@link z.output}
50
- * ({@link ExtraSchemaKeys}, union по веткам); {@link z.output} совместим с `T`
51
- * ({@link SchemaCompatible}, вложенные подмножества). В контекст попадает output после `parse()`.
52
- */
53
- export type ContextSchema<T extends JsonObject, S extends z.ZodObject> = SchemaOutputCompatible<T, S> extends false ? never : SchemaInputKeysSubset<T, S> extends false ? never : ExtraSchemaKeys<T, z.input<S>> extends never ? ExtraSchemaKeys<T, z.output<S>> extends never ? S : never : never;
54
- /** Конфиг {@link createContext} без клиентской Zod-схемы. */
55
- export type ContextInitWithoutSchema<T extends JsonObject> = {
38
+ type ContextRuntimeInit<T extends JsonObject, S extends z.ZodObject | undefined> = {
56
39
  data: () => Promise<T>;
57
- schema?: undefined;
40
+ schema?: S;
58
41
  preload?: boolean;
59
42
  persistent?: boolean;
60
43
  };
61
- /** Конфиг {@link createContext} с Zod-схемой клиентских изменений. */
62
- export type ContextInitWithSchema<T extends JsonObject, S extends z.ZodObject> = {
63
- data: () => Promise<T>;
64
- schema: ContextSchema<T, S>;
65
- preload?: boolean;
66
- persistent?: boolean;
67
- };
68
- /** Конфигурация {@link createContext} (единственный аргумент). */
69
- export type ContextInitConfig<T extends JsonObject, S extends z.ZodObject | undefined = undefined> = S extends z.ZodObject ? ContextInitWithSchema<T, S> : ContextInitWithoutSchema<T>;
70
- /** Минимальная форма аргумента {@link createContext}. */
71
- type ContextInitShape = {
72
- data: () => Promise<JsonObject>;
73
- schema?: z.ZodObject;
74
- preload?: boolean;
75
- persistent?: boolean;
76
- };
77
- type ContextRuntimeInit<T extends JsonObject> = {
78
- data: () => Promise<T>;
79
- schema?: z.ZodObject;
80
- preload?: boolean;
81
- persistent?: boolean;
82
- };
83
- /** Тип данных `T` из поля `data` конфига. */
84
- export type ContextDataFromInit<C extends ContextInitShape> = Awaited<ReturnType<C["data"]>>;
85
- /** Zod-схема из поля `schema` конфига (или `undefined`). */
86
- export type ContextSchemaFromInit<C extends ContextInitShape> = C extends {
87
- schema: z.ZodObject;
88
- } ? C["schema"] : undefined;
89
- /** Экземпляр {@link Context} по форме конфига {@link createContext}. */
90
- export type ContextFromInit<C extends ContextInitShape> = Context<ContextDataFromInit<C>>;
91
44
  /**
92
45
  * Контекст данных, связанных с клиентом.
93
46
  *
@@ -98,13 +51,13 @@ export type ContextFromInit<C extends ContextInitShape> = Context<ContextDataFro
98
51
  * Zod-схема клиентских изменений задаётся в {@link createContext} через поле `schema`,
99
52
  * а не вторым type-параметром: так проще согласовать runtime-схему и тип данных.
100
53
  */
101
- export declare class Context<T extends JsonObject> {
54
+ export declare class Context<T extends JsonObject, S extends z.ZodObject | undefined = any> {
102
55
  /** Уникальный идентификатор контекста */
103
56
  readonly id: `${string}-${string}-${string}-${string}-${string}`;
104
57
  /** Реактивное хранилище данных контекста. */
105
58
  protected data$?: BehaviorSubject<T>;
106
59
  /** Схема валидации данных контекста */
107
- readonly schema?: z.ZodObject;
60
+ readonly schema?: S;
108
61
  /** Флаг, указывающий, что контекст должен быть инициализирован при авторизации клиента */
109
62
  readonly preload: boolean;
110
63
  /**
@@ -114,10 +67,10 @@ export declare class Context<T extends JsonObject> {
114
67
  readonly persistent: boolean;
115
68
  /** Локальные (client-only) действия над данными этого контекста. */
116
69
  readonly local: {
117
- set: (patch: LocalContextPathPatch<T>, config?: ActionConfig) => import("../actions/set-context").SetContext<T>;
118
- toggle: <K extends Paths<T>>(path: PathValue<T, K> extends boolean | undefined ? K : never, config?: ActionConfig) => import("../actions/toggle-context-value").ToggleContextValue;
119
- inc: <K extends Paths<T>>(path: PathValue<T, K> extends number | undefined ? K : never, step?: ContextValueOrRef<number>, config?: ActionConfig) => import("../actions/inc-context-value").IncContextValue;
120
- dec: <K extends Paths<T>>(path: PathValue<T, K> extends number | undefined ? K : never, step?: ContextValueOrRef<number>, config?: ActionConfig) => import("../actions/dec-context-value").DecContextValue;
70
+ set: (patch: LocalContextPathPatch<T, S>, config?: ActionConfig) => import("../actions/set-context").SetContext<T, S>;
71
+ toggle: <K extends WritableContextPath<T, S>>(path: PathValue<T, K> extends boolean | undefined ? WritablePathValue<S, K> extends boolean | undefined ? K : never : never, config?: ActionConfig) => ToggleContextValue;
72
+ inc: <K extends WritableContextPath<T, S>>(path: PathValue<T, K> extends number | undefined ? WritablePathValue<S, K> extends number | undefined ? K : never : never, step?: ValueOrContextRef<number>, config?: ActionConfig) => IncContextValue;
73
+ dec: <K extends WritableContextPath<T, S>>(path: PathValue<T, K> extends number | undefined ? WritablePathValue<S, K> extends number | undefined ? K : never : never, step?: ValueOrContextRef<number>, config?: ActionConfig) => DecContextValue;
121
74
  };
122
75
  /** Реактивное хранилище инициализации контекста */
123
76
  private _init$;
@@ -150,13 +103,21 @@ export declare class Context<T extends JsonObject> {
150
103
  private handleTargetedClientMessage;
151
104
  /** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
152
105
  private reportInitFailureToClients;
106
+ /**
107
+ * Фабричный runtime-вход для {@link createContext}.
108
+ * Не используйте напрямую в прикладном коде — это обходит compile-time проверку schema↔data.
109
+ *
110
+ * @internal
111
+ * @deprecated Internal API. Use createContext(...) instead.
112
+ */
113
+ static createRuntime<U extends JsonObject, SchemaType extends z.ZodObject | undefined>(config: ContextRuntimeInit<U, SchemaType>): Context<U, SchemaType>;
153
114
  /**
154
115
  * Создаёт экземпляр контекста, привязанный к конкретному клиенту.
155
116
  *
156
117
  * Подписывается на входящие сообщения от клиента и ошибки, связанные с этим контекстом.
157
118
 
158
119
  */
159
- constructor(config: ContextRuntimeInit<T>);
120
+ protected constructor(config: ContextRuntimeInit<T, S>);
160
121
  /** `data$` создан (init мог ещё выполняться — см. {@link init}). */
161
122
  inited(): boolean;
162
123
  /** Данные загружены: `initDataCallback` завершился. */
@@ -240,7 +201,7 @@ export declare class Context<T extends JsonObject> {
240
201
  * @param path Путь до значения.
241
202
  * @returns Плейсхолдер для использования в шаблонах и компонентах.
242
203
  */
243
- ref<K extends Paths<T>>(path: K): ContextRef<T, K>;
204
+ ref<K extends Paths<T>>(path: K): ContextRef<T, K, S>;
244
205
  /**
245
206
  * Ссылка на значение в **этом** контексте по пути, который задаётся **во втором**
246
207
  * контексте строкой и меняется во времени.
@@ -262,26 +223,9 @@ export declare class Context<T extends JsonObject> {
262
223
  *
263
224
  * @experimental
264
225
  */
265
- strictRef<OtherContextType extends JsonObject, OtherPathType extends Paths<OtherContextType>>(other: ContextRef<OtherContextType, OtherPathType>): ContextRef<T, PathValue<OtherContextType, OtherPathType> & Paths<T>>;
226
+ strictRef<OtherContextType extends JsonObject, OtherSchemaType extends z.ZodObject | undefined, OtherPathType extends Paths<OtherContextType>>(other: ContextRef<OtherContextType, OtherPathType, OtherSchemaType>): ContextRef<T, PathValue<OtherContextType, OtherPathType> & Paths<T>, S>;
266
227
  toJSON(): `${string}-${string}-${string}-${string}-${string}`;
267
228
  }
229
+ export type AnySchemaContext<T extends JsonObject = JsonObject> = Context<T, z.ZodObject | undefined>;
268
230
  /** Любой зарегистрированный контекст (с Zod-схемой или без). */
269
- export type AnyContext = Context<any>;
270
- /**
271
- * Создаёт контекст данных BFF: хранилище состояния с синхронизацией клиент ↔ сервер.
272
- *
273
- * Тип данных выводится из `data`, тип Zod-схемы — из `schema`. Связь проверяется через
274
- * {@link ContextSchema}.
275
- *
276
- * Если в начальном `data` нет части полей (например опциональных), укажите тип на колбэке:
277
- * `data: async (): Promise<MyT> => ({ … })`.
278
- */
279
- type ContextWithSchemaInit = {
280
- data: () => Promise<unknown>;
281
- schema: z.ZodObject;
282
- preload?: boolean;
283
- persistent?: boolean;
284
- };
285
- type ContextDataForSchema<C extends ContextWithSchemaInit> = Awaited<ReturnType<C["data"]>> extends infer T ? T extends JsonObject ? T : never : never;
286
- export declare function createContext<const C extends ContextWithSchemaInit>(config: C, ...validation: ContextSchema<ContextDataForSchema<C>, NoInfer<C["schema"]>> extends never ? [schemaMismatch: never] : []): Context<ContextDataForSchema<C>>;
287
- export declare function createContext<const T extends JsonObject>(config: ContextInitWithoutSchema<T>): Context<T>;
231
+ export type AnyContext = Context<any, any>;
@@ -1,7 +1,20 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
2
16
  Object.defineProperty(exports, "__esModule", { value: true });
3
17
  exports.Context = exports.contextClientUpdatesForbiddenSchema = void 0;
4
- exports.createContext = createContext;
5
18
  const index_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/context/index");
6
19
  const index_2 = require("@matreshka/client-bff-protocol/messages/client-to-bff/context/index");
7
20
  const targeted_message_1 = require("@matreshka/client-bff-protocol/messages/targeted-message");
@@ -21,6 +34,7 @@ const objects_diff_1 = require("../utils/objects-diff");
21
34
  const replace_context_keys_1 = require("../utils/replace-context-keys");
22
35
  const assert_client_update_schema_1 = require("./assert-client-update-schema");
23
36
  const context_ref_1 = require("./context-ref");
37
+ __exportStar(require("./context-create"), exports);
24
38
  /** @see ContextClientUpdatesForbiddenSchema */
25
39
  exports.contextClientUpdatesForbiddenSchema = zod_1.z.strictObject({});
26
40
  /** Отделяет чтение через {@link Context.get} от живого дерева в хранилище. */
@@ -156,6 +170,16 @@ class Context {
156
170
  client.error$.next(error);
157
171
  });
158
172
  }
173
+ /**
174
+ * Фабричный runtime-вход для {@link createContext}.
175
+ * Не используйте напрямую в прикладном коде — это обходит compile-time проверку schema↔data.
176
+ *
177
+ * @internal
178
+ * @deprecated Internal API. Use createContext(...) instead.
179
+ */
180
+ static createRuntime(config) {
181
+ return new Context(config);
182
+ }
159
183
  /**
160
184
  * Создаёт экземпляр контекста, привязанный к конкретному клиенту.
161
185
  *
@@ -573,6 +597,3 @@ class Context {
573
597
  }
574
598
  }
575
599
  exports.Context = Context;
576
- function createContext(config, ..._validation) {
577
- return new Context(config);
578
- }
@@ -1,4 +1,15 @@
1
- import { ContextRef, ContextRefValue } from "../context/context-ref";
1
+ import type { JsonObject } from "@matreshka/client-bff-protocol/types/json";
2
+ import type { Observable } from "rxjs";
3
+ import { z } from "zod";
4
+ import type { SetContext } from "../actions/set-context";
5
+ import { AnySchemaContextRef, ContextRef, ContextRefValueType } from "../context/context-ref";
6
+ import type { ContextUpdateDelivery } from "./context-update-delivery";
7
+ /** Общая часть ref-типов по значению: маркер типа и чтение. */
8
+ type ValueRefBase<ValueType> = {
9
+ readonly __valueType?: ValueType;
10
+ get(): ValueType;
11
+ set(value: ValueType): Observable<ContextUpdateDelivery>;
12
+ };
2
13
  /**
3
14
  * Ссылка на поле контекста с известным типом значения.
4
15
  *
@@ -8,27 +19,60 @@ import { ContextRef, ContextRefValue } from "../context/context-ref";
8
19
  *
9
20
  * @example
10
21
  * ```ts
11
- * function bindAmount(ref: ContextValueRef<number | undefined>) {
22
+ * function bindAmount(ref: ContextRefOfValue<number | undefined>) {
12
23
  * ref.get(); // number | undefined
13
24
  * }
14
25
  *
15
26
  * bindAmount(pageContext.ref("amount"));
16
27
  * ```
17
28
  */
18
- export type ContextValueRef<ValueType> = ContextRef<any, any> & {
19
- readonly __valueType?: ValueType;
20
- get(): ValueType;
21
- set(value: ValueType): void;
22
- };
29
+ export type ContextRefOfValue<ValueType> = ValueRefBase<ValueType> & ContextRef<any, any, any>;
23
30
  /**
24
31
  * Ref `R` совместим с ожидаемым типом значения `ValueType` (проверка на call site).
25
32
  */
26
- export type CompatibleContextValueRef<ValueType, R extends ContextRef> = ValueType extends ContextRefValue<R> ? R : never;
33
+ export type CompatibleContextRefOfValue<ValueType, R extends AnySchemaContextRef> = ValueType extends ContextRefValueType<R> ? R : never;
34
+ /**
35
+ * Эталонный writable ref для значения `ValueType`: путь `k` гарантированно есть
36
+ * в schema. Из него выводится `local`, так что при добавлении
37
+ * методов в `ContextRef.local` типы вручную переписывать не нужно.
38
+ */
39
+ type WritableReferenceRef<ValueType> = ContextRef<{
40
+ k: Exclude<ValueType, undefined>;
41
+ } extends infer C extends JsonObject ? C : never, "k", z.ZodObject<{
42
+ k: z.ZodType<Exclude<ValueType, undefined>, Exclude<ValueType, undefined>>;
43
+ }>>;
44
+ /**
45
+ * Стирает привязку `SetContext` к конкретному контексту/schema, остальные
46
+ * сигнатуры `local` остаются как у `ContextRef.local`.
47
+ */
48
+ type EraseLocalContext<Local> = {
49
+ [K in keyof Local]: Local[K] extends (...args: infer Args) => infer Result ? Result extends SetContext<any, any> ? (...args: Args) => SetContext<any, any> : Local[K] : Local[K];
50
+ };
51
+ /**
52
+ * Writable-ref с известным типом значения без generic по ref.
53
+ *
54
+ * Структурно совместим с `ContextRef` (остальные члены берутся из
55
+ * `ContextRef<any, any, any>`), а `local` берётся из `ContextRef.local`
56
+ * для эталонного writable ref, поэтому ref с путём вне schema не пройдёт
57
+ * проверку на call site.
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * function setTrue(ref: WritableContextRefOfValue<boolean | undefined>) {
62
+ * ref.local.set(true);
63
+ * ref.local.toggle();
64
+ * }
65
+ * ```
66
+ */
67
+ export type WritableContextRefOfValue<ValueType> = ContextRefOfValue<ValueType> & {
68
+ readonly local: EraseLocalContext<WritableReferenceRef<ValueType>["local"]>;
69
+ };
27
70
  /** Статическое значение или ссылка на совместимое значение в контексте. */
28
- export type ContextValueOrRef<ValueType> = ValueType | ContextValueRef<Exclude<ValueType, undefined>>;
71
+ export type ValueOrContextRef<ValueType> = ValueType | ContextRefOfValue<Exclude<ValueType, undefined>>;
29
72
  /**
30
73
  * Ссылка на массив элементов в контексте (`ItemType[] | undefined`).
31
74
  *
32
75
  * Generic задаёт тип **элемента**, как в {@link CompatibleForEachRef} / `forEach`.
33
76
  */
34
- export type ContextArrayRef<ItemType> = ContextValueRef<ItemType[] | undefined>;
77
+ export type ContextArrayValueRef<ItemType> = ContextRefOfValue<ItemType[] | undefined>;
78
+ export {};
@@ -3,7 +3,7 @@ import type { Observable } from "rxjs";
3
3
  import { Dialog, Popover } from "../components";
4
4
  import { Overlay } from "../components/types/container-overlay";
5
5
  import { type WebMcpTool } from "../components/webmcp/web-mcp-tool";
6
- import { Client, Componentable, ComponentInstance, ContextValueRef } from "../core";
6
+ import { Client, Componentable, ComponentInstance, ContextRefOfValue } from "../core";
7
7
  import { type PopoverShowComponent, type PopoverShowPlacement } from "./popover-show";
8
8
  import { type NavigateResult } from "./utils/client-navigate-platform-action";
9
9
  export type { NavigateResult };
@@ -55,10 +55,10 @@ export declare abstract class Platform {
55
55
  */
56
56
  showPopover(source: PopoverShowComponent, popover: Popover): Observable<void>;
57
57
  showPopover(placement: PopoverShowPlacement, popover: Popover): Observable<void>;
58
- showDatePicker(anchor: ComponentInstance | Componentable, ref: ContextValueRef<string | undefined>): Observable<void>;
59
- showColorPicker(anchor: ComponentInstance | Componentable, ref: ContextValueRef<string | undefined>): Observable<void>;
60
- showTimePicker(anchor: ComponentInstance | Componentable, ref: ContextValueRef<string | undefined>): Observable<void>;
61
- showDateTimePicker(anchor: ComponentInstance | Componentable, ref: ContextValueRef<string | undefined>): Observable<void>;
58
+ showDatePicker(anchor: ComponentInstance | Componentable, ref: ContextRefOfValue<string | undefined>): Observable<void>;
59
+ showColorPicker(anchor: ComponentInstance | Componentable, ref: ContextRefOfValue<string | undefined>): Observable<void>;
60
+ showTimePicker(anchor: ComponentInstance | Componentable, ref: ContextRefOfValue<string | undefined>): Observable<void>;
61
+ showDateTimePicker(anchor: ComponentInstance | Componentable, ref: ContextRefOfValue<string | undefined>): Observable<void>;
62
62
  private showNativePicker;
63
63
  /**
64
64
  * Задаёт платформенные WebMCP-тулзы. Новый список заменяет предыдущий.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@matreshka/bff",
3
- "version": "0.30.2",
3
+ "version": "0.32.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",