@matreshka/bff 0.32.0 → 0.33.2
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/dialog.d.ts +1 -2
- package/dist/components/entry-component.d.ts +8 -10
- package/dist/components/entry-component.js +22 -22
- package/dist/components/for-each.d.ts +1 -1
- package/dist/components/page.d.ts +2 -5
- package/dist/components/page.js +3 -6
- package/dist/core/context/assert-client-update-schema.js +2 -2
- package/dist/core/context/context-ref.d.ts +7 -0
- package/dist/core/context/context-ref.js +15 -0
- package/dist/core/context/context.d.ts +9 -1
- package/dist/core/context/context.js +11 -1
- package/dist/core/types/context-value-ref.d.ts +2 -1
- package/dist/core/utils/deep-pick.d.ts +8 -1
- package/dist/core/utils/deep-pick.js +37 -33
- package/package.json +1 -1
|
@@ -6,7 +6,6 @@ import { Componentable, ComponentInstance, ComponentTreeNode, MixedWithCallbacks
|
|
|
6
6
|
import type { ActionConfig } from "../core/actions/action";
|
|
7
7
|
import type { AnimateComponent } from "../core/actions/animate-component";
|
|
8
8
|
import { EntryComponent, EntryComponentInitConfig, EntryComponentProperties } from "./entry-component";
|
|
9
|
-
import type { Overlay } from "./types/container-overlay";
|
|
10
9
|
/** Анимации подложки модального диалога при инициализации. */
|
|
11
10
|
export type DialogBackdropInitConfig = {
|
|
12
11
|
onEnter?: AnimateComponent | AnimateComponent[];
|
|
@@ -89,7 +88,7 @@ export declare class Dialog<InitConfigType extends DialogInitConfig<any> = Defau
|
|
|
89
88
|
/**
|
|
90
89
|
* Оверлеи диалога. По умолчанию — `overlays` конструктора.
|
|
91
90
|
*/
|
|
92
|
-
protected overlays():
|
|
91
|
+
protected overlays(): InitConfigType["overlays"];
|
|
93
92
|
/**
|
|
94
93
|
* Возвращает уникальный идентификатор класса компонента.
|
|
95
94
|
* @returns Строка "dialog".
|
|
@@ -26,16 +26,16 @@ type DefaultInitConfigType = EntryComponentInitConfig<EntryComponent>;
|
|
|
26
26
|
export declare abstract class EntryComponent<InitConfigType extends EntryComponentInitConfig<any> = DefaultInitConfigType, PropertiesType extends EntryComponentProperties = EntryComponentProperties, SerializedConfigType extends EntryServerComponentConfig = EntryServerComponentConfig> extends Component<InitConfigType, PropertiesType> {
|
|
27
27
|
private readonly registeredTools;
|
|
28
28
|
private declaredToolsRegistered;
|
|
29
|
-
private
|
|
29
|
+
private entryInteractionsRegistered;
|
|
30
30
|
constructor(config: InitConfigType);
|
|
31
31
|
/**
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
32
|
+
* Декларативная карта interaction entry: имя события → обработчики.
|
|
33
|
+
* Наследники расширяют её через `{ ...super.entryInteractions(), scroll: ... }`.
|
|
34
|
+
* Вызывается лениво (после конструктора наследника), поэтому поля подкласса доступны.
|
|
35
35
|
*/
|
|
36
|
-
protected
|
|
37
|
-
/**
|
|
38
|
-
|
|
36
|
+
protected entryInteractions(): Record<string, ServerComponentAction<any, any> | ServerComponentAction<any, any>[] | undefined>;
|
|
37
|
+
/** Идемпотентная регистрация {@link entryInteractions}. */
|
|
38
|
+
private registerEntryInteractions;
|
|
39
39
|
/**
|
|
40
40
|
* Показ entry. По умолчанию — `onEnter` конструктора.
|
|
41
41
|
*/
|
|
@@ -52,8 +52,6 @@ export declare abstract class EntryComponent<InitConfigType extends EntryCompone
|
|
|
52
52
|
/** Сохранённые WebMCP-тулзы. execute не сериализуется и не вызывается до сообщения вызова. */
|
|
53
53
|
get entryTools(): readonly WebMcpTool[];
|
|
54
54
|
protected registerEntryTools(tools: readonly WebMcpTool[] | undefined): void;
|
|
55
|
-
/** Привязка обработчиков к имени взаимодействия. */
|
|
56
|
-
protected bindDeclaredInteraction(event: string, handlers: ServerComponentAction<any, any> | ServerComponentAction<any, any>[] | undefined): void;
|
|
57
55
|
/**
|
|
58
56
|
* Тулзы читают поля наследника, поэтому регистрируются после конструктора:
|
|
59
57
|
* при первом чтении списка и перед сериализацией.
|
|
@@ -72,7 +70,7 @@ export declare abstract class EntryComponent<InitConfigType extends EntryCompone
|
|
|
72
70
|
beginSerializationContext(): ComponentInstance<this>;
|
|
73
71
|
/**
|
|
74
72
|
* Явное создание instance entry (редко для Page/Dialog; для App-оверлеев см.
|
|
75
|
-
* {@link beginSerializationContext}).
|
|
73
|
+
* {@link beginSerializationContext}). Interaction entry регистрируются здесь же.
|
|
76
74
|
*/
|
|
77
75
|
createInstance(): ComponentInstance<this>;
|
|
78
76
|
protected createSelfEntry(): ComponentInstance<this>;
|
|
@@ -18,24 +18,31 @@ class EntryComponent extends component_1.Component {
|
|
|
18
18
|
super(config);
|
|
19
19
|
this.registeredTools = [];
|
|
20
20
|
this.declaredToolsRegistered = false;
|
|
21
|
-
this.
|
|
21
|
+
this.entryInteractionsRegistered = false;
|
|
22
22
|
}
|
|
23
23
|
/**
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
24
|
+
* Декларативная карта interaction entry: имя события → обработчики.
|
|
25
|
+
* Наследники расширяют её через `{ ...super.entryInteractions(), scroll: ... }`.
|
|
26
|
+
* Вызывается лениво (после конструктора наследника), поэтому поля подкласса доступны.
|
|
27
27
|
*/
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
entryInteractions() {
|
|
29
|
+
return {
|
|
30
|
+
enter: this.onEnter(),
|
|
31
|
+
leave: this.onLeave(),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** Идемпотентная регистрация {@link entryInteractions}. */
|
|
35
|
+
registerEntryInteractions() {
|
|
36
|
+
if (this.entryInteractionsRegistered) {
|
|
30
37
|
return;
|
|
31
38
|
}
|
|
32
|
-
this.
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
39
|
+
this.entryInteractionsRegistered = true;
|
|
40
|
+
for (const [event, handlers] of Object.entries(this.entryInteractions())) {
|
|
41
|
+
if (handlers !== undefined) {
|
|
42
|
+
this.bindActions(event, handlers);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
36
45
|
}
|
|
37
|
-
/** Хук для наследников: один раз сразу после enter/leave (см. {@link registerEntryLifecycleInteractions}). */
|
|
38
|
-
registerEntryLifecycleInteractionsExtra() { }
|
|
39
46
|
/**
|
|
40
47
|
* Показ entry. По умолчанию — `onEnter` конструктора.
|
|
41
48
|
*/
|
|
@@ -66,13 +73,6 @@ class EntryComponent extends component_1.Component {
|
|
|
66
73
|
}
|
|
67
74
|
this.registeredTools.push(...tools);
|
|
68
75
|
}
|
|
69
|
-
/** Привязка обработчиков к имени взаимодействия. */
|
|
70
|
-
bindDeclaredInteraction(event, handlers) {
|
|
71
|
-
if (handlers === undefined) {
|
|
72
|
-
return;
|
|
73
|
-
}
|
|
74
|
-
this.bindActions(event, handlers);
|
|
75
|
-
}
|
|
76
76
|
/**
|
|
77
77
|
* Тулзы читают поля наследника, поэтому регистрируются после конструктора:
|
|
78
78
|
* при первом чтении списка и перед сериализацией.
|
|
@@ -159,14 +159,14 @@ class EntryComponent extends component_1.Component {
|
|
|
159
159
|
}
|
|
160
160
|
/**
|
|
161
161
|
* Явное создание instance entry (редко для Page/Dialog; для App-оверлеев см.
|
|
162
|
-
* {@link beginSerializationContext}).
|
|
162
|
+
* {@link beginSerializationContext}). Interaction entry регистрируются здесь же.
|
|
163
163
|
*/
|
|
164
164
|
createInstance() {
|
|
165
|
-
this.
|
|
165
|
+
this.registerEntryInteractions();
|
|
166
166
|
return super.createInstance();
|
|
167
167
|
}
|
|
168
168
|
createSelfEntry() {
|
|
169
|
-
this.
|
|
169
|
+
this.registerEntryInteractions();
|
|
170
170
|
const instance = super.createSelfEntry();
|
|
171
171
|
const client = (0, client_context_1.currentClient)();
|
|
172
172
|
// Подписка на leave и прочие interaction до commitSerialization instance.entry.
|
|
@@ -1,8 +1,8 @@
|
|
|
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 { AnySchemaContextRef, ComponentInstance, ComponentTreeNode, Context, ContextRef, ContextRefLocalActions, ContextRefValueType, JsonObject, StandaloneComponent, WritableContextRefOfValue } from "../core";
|
|
5
4
|
import type { z } from "zod";
|
|
5
|
+
import { AnySchemaContextRef, ComponentInstance, ComponentTreeNode, Context, ContextRef, ContextRefLocalActions, ContextRefValueType, JsonObject, StandaloneComponent, WritableContextRefOfValue } from "../core";
|
|
6
6
|
import { Component, ComponentInitConfig, ComponentProperties } from "./component";
|
|
7
7
|
type ForEachArrayValue = readonly unknown[] | unknown[];
|
|
8
8
|
type ForEachItemArray<RefType extends AnySchemaContextRef> = Extract<ContextRefValueType<RefType>, ForEachArrayValue>;
|
|
@@ -28,11 +28,8 @@ type DefaultInitConfigType = PageInitConfig<Page>;
|
|
|
28
28
|
*/
|
|
29
29
|
export declare abstract class Page<InitConfigType extends PageInitConfig<any> = DefaultInitConfigType, PropertiesType extends PageProperties = PageProperties> extends EntryComponent<InitConfigType, PropertiesType, PageConfig> implements Pageable {
|
|
30
30
|
constructor();
|
|
31
|
-
/**
|
|
32
|
-
|
|
33
|
-
* когда доступны поля подкласса (см. {@link EntryComponent.registerEntryLifecycleInteractions}).
|
|
34
|
-
*/
|
|
35
|
-
protected registerEntryLifecycleInteractionsExtra(): void;
|
|
31
|
+
/** Добавляет `scroll` к стандартным enter/leave (см. {@link EntryComponent.entryInteractions}). */
|
|
32
|
+
protected entryInteractions(): ReturnType<EntryComponent["entryInteractions"]>;
|
|
36
33
|
/**
|
|
37
34
|
* Возвращает HTTP-статус страницы.
|
|
38
35
|
* @returns Статус страницы (по умолчанию 200 OK).
|
package/dist/components/page.js
CHANGED
|
@@ -15,12 +15,9 @@ class Page extends entry_component_1.EntryComponent {
|
|
|
15
15
|
// @ts-expect-error Page задаёт content в boot(), а не через конфиг конструктора Component.
|
|
16
16
|
super({});
|
|
17
17
|
}
|
|
18
|
-
/**
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
*/
|
|
22
|
-
registerEntryLifecycleInteractionsExtra() {
|
|
23
|
-
this.bindDeclaredInteraction("scroll", this.onScroll());
|
|
18
|
+
/** Добавляет `scroll` к стандартным enter/leave (см. {@link EntryComponent.entryInteractions}). */
|
|
19
|
+
entryInteractions() {
|
|
20
|
+
return { ...super.entryInteractions(), scroll: this.onScroll() };
|
|
24
21
|
}
|
|
25
22
|
/**
|
|
26
23
|
* Возвращает HTTP-статус страницы.
|
|
@@ -25,14 +25,14 @@ function assertClientUpdateSchemaSupported(schema, path = "") {
|
|
|
25
25
|
function assertClientUpdateFieldSupported(schema, path) {
|
|
26
26
|
const unwrapped = unwrapOptionalNullable(schema);
|
|
27
27
|
if (unwrapped instanceof zod_1.z.ZodPipe) {
|
|
28
|
-
const inner = unwrapped.
|
|
28
|
+
const inner = unwrapped.in;
|
|
29
29
|
if (inner instanceof zod_1.z.ZodObject) {
|
|
30
30
|
throw new Error(`Context validation schema: object-level transform at "${formatPath(path)}" is not supported for dotted-path client updates. Use leaf-level transforms only.`);
|
|
31
31
|
}
|
|
32
32
|
return;
|
|
33
33
|
}
|
|
34
34
|
if (unwrapped instanceof zod_1.z.ZodObject) {
|
|
35
|
-
const checks = unwrapped.
|
|
35
|
+
const checks = unwrapped.def.checks;
|
|
36
36
|
if (checks && checks.length > 0) {
|
|
37
37
|
throw new Error(`Context validation schema: object-level refine at "${formatPath(path)}" is not supported for dotted-path client updates. Use leaf-level refinements only.`);
|
|
38
38
|
}
|
|
@@ -75,6 +75,13 @@ export declare class ContextRef<ContextType extends JsonObject = JsonObject, Pat
|
|
|
75
75
|
* та же ошибка, что у {@link Context.set}.
|
|
76
76
|
*/
|
|
77
77
|
set(value: PathValue<ContextType, PathType>): Observable<ContextUpdateDelivery>;
|
|
78
|
+
/**
|
|
79
|
+
* Следующее значение по текущему пути из текущего снимка.
|
|
80
|
+
*
|
|
81
|
+
* Callback получает то же, что {@link get}, и возвращает значение того же типа.
|
|
82
|
+
* Запись идёт через {@link set}.
|
|
83
|
+
*/
|
|
84
|
+
update(updater: (current: PathValue<ContextType, PathType>) => PathValue<ContextType, PathType>): Observable<ContextUpdateDelivery>;
|
|
78
85
|
toString(): string;
|
|
79
86
|
toJSON(): string;
|
|
80
87
|
}
|
|
@@ -6,6 +6,12 @@ const inc_context_value_1 = require("../actions/inc-context-value");
|
|
|
6
6
|
const set_context_1 = require("../actions/set-context");
|
|
7
7
|
const toggle_context_value_1 = require("../actions/toggle-context-value");
|
|
8
8
|
const client_context_1 = require("../client-context");
|
|
9
|
+
function cloneContextValue(value) {
|
|
10
|
+
if (value !== null && typeof value === "object") {
|
|
11
|
+
return structuredClone(value);
|
|
12
|
+
}
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
9
15
|
class ContextRef {
|
|
10
16
|
constructor(context, path) {
|
|
11
17
|
this.context = context;
|
|
@@ -72,6 +78,15 @@ class ContextRef {
|
|
|
72
78
|
[this.path]: value,
|
|
73
79
|
});
|
|
74
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* Следующее значение по текущему пути из текущего снимка.
|
|
83
|
+
*
|
|
84
|
+
* Callback получает то же, что {@link get}, и возвращает значение того же типа.
|
|
85
|
+
* Запись идёт через {@link set}.
|
|
86
|
+
*/
|
|
87
|
+
update(updater) {
|
|
88
|
+
return this.set(cloneContextValue(updater(this.get())));
|
|
89
|
+
}
|
|
75
90
|
toString() {
|
|
76
91
|
return `@{${this.context.id}.${this.path}}`;
|
|
77
92
|
}
|
|
@@ -178,6 +178,14 @@ export declare class Context<T extends JsonObject, S extends z.ZodObject | undef
|
|
|
178
178
|
* Возвращает тот же hot {@link Observable}, что и {@link set}.
|
|
179
179
|
*/
|
|
180
180
|
replace(data: T): Observable<ContextUpdateDelivery>;
|
|
181
|
+
/**
|
|
182
|
+
* Следующее состояние целиком из текущего снимка `T`.
|
|
183
|
+
*
|
|
184
|
+
* Callback получает копию текущих данных и возвращает значение того же типа.
|
|
185
|
+
* Результат сохраняется как structured clone, как в {@link replace}.
|
|
186
|
+
* Возвращает тот же hot {@link Observable}, что и {@link set}.
|
|
187
|
+
*/
|
|
188
|
+
update(updater: (current: T) => T): Observable<ContextUpdateDelivery>;
|
|
181
189
|
/**
|
|
182
190
|
* Глубокая копия всего `T` (structured clone корня).
|
|
183
191
|
*
|
|
@@ -193,7 +201,7 @@ export declare class Context<T extends JsonObject, S extends z.ZodObject | undef
|
|
|
193
201
|
* поток завершается без эмиссий.
|
|
194
202
|
*
|
|
195
203
|
* После подключения сразу эмитит текущее состояние, затем каждое обновление
|
|
196
|
-
* через {@link set}, {@link replace} и т.п.
|
|
204
|
+
* через {@link set}, {@link replace}, {@link update} и т.п.
|
|
197
205
|
*/
|
|
198
206
|
watch(): Observable<T>;
|
|
199
207
|
/**
|
|
@@ -517,6 +517,16 @@ class Context {
|
|
|
517
517
|
replace(data) {
|
|
518
518
|
return this.updateDataAndWait(() => structuredClone(data));
|
|
519
519
|
}
|
|
520
|
+
/**
|
|
521
|
+
* Следующее состояние целиком из текущего снимка `T`.
|
|
522
|
+
*
|
|
523
|
+
* Callback получает копию текущих данных и возвращает значение того же типа.
|
|
524
|
+
* Результат сохраняется как structured clone, как в {@link replace}.
|
|
525
|
+
* Возвращает тот же hot {@link Observable}, что и {@link set}.
|
|
526
|
+
*/
|
|
527
|
+
update(updater) {
|
|
528
|
+
return this.updateDataAndWait((current) => structuredClone(updater(current)));
|
|
529
|
+
}
|
|
520
530
|
/**
|
|
521
531
|
* Глубокая копия всего `T` (structured clone корня).
|
|
522
532
|
*
|
|
@@ -536,7 +546,7 @@ class Context {
|
|
|
536
546
|
* поток завершается без эмиссий.
|
|
537
547
|
*
|
|
538
548
|
* После подключения сразу эмитит текущее состояние, затем каждое обновление
|
|
539
|
-
* через {@link set}, {@link replace} и т.п.
|
|
549
|
+
* через {@link set}, {@link replace}, {@link update} и т.п.
|
|
540
550
|
*/
|
|
541
551
|
watch() {
|
|
542
552
|
this.assertNotDestroyed();
|
|
@@ -4,11 +4,12 @@ import { z } from "zod";
|
|
|
4
4
|
import type { SetContext } from "../actions/set-context";
|
|
5
5
|
import { AnySchemaContextRef, ContextRef, ContextRefValueType } from "../context/context-ref";
|
|
6
6
|
import type { ContextUpdateDelivery } from "./context-update-delivery";
|
|
7
|
-
/** Общая часть ref-типов по значению: маркер
|
|
7
|
+
/** Общая часть ref-типов по значению: маркер типа, чтение и запись. */
|
|
8
8
|
type ValueRefBase<ValueType> = {
|
|
9
9
|
readonly __valueType?: ValueType;
|
|
10
10
|
get(): ValueType;
|
|
11
11
|
set(value: ValueType): Observable<ContextUpdateDelivery>;
|
|
12
|
+
update(updater: (current: ValueType) => ValueType): Observable<ContextUpdateDelivery>;
|
|
12
13
|
};
|
|
13
14
|
/**
|
|
14
15
|
* Ссылка на поле контекста с известным типом значения.
|
|
@@ -1,2 +1,9 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* Схема конечного поля по dotted-пути клиентского patch.
|
|
4
|
+
*
|
|
5
|
+
* Элемент массива адресуется числовым сегментом (`meters.0.zones.0.value`).
|
|
6
|
+
* Индексом он считается только если текущий узел — `ZodArray`; у `ZodObject`
|
|
7
|
+
* тот же сегмент остаётся строковым ключом (`{ "0": z.string() }`).
|
|
8
|
+
*/
|
|
9
|
+
export declare function zodDeepPick(schema: z.ZodType, propertyPath: string): z.ZodType;
|
|
@@ -8,68 +8,72 @@ function isZodObject(schema) {
|
|
|
8
8
|
function isZodArray(schema) {
|
|
9
9
|
return schema instanceof zod_1.z.ZodArray;
|
|
10
10
|
}
|
|
11
|
-
/**
|
|
12
|
-
|
|
11
|
+
/**
|
|
12
|
+
* Узел схемы, по которому можно идти дальше по пути.
|
|
13
|
+
* Снимает optional/nullable и pipe к object/array (object-level transform).
|
|
14
|
+
*/
|
|
15
|
+
function schemaForPathStep(schema) {
|
|
13
16
|
let current = schema;
|
|
14
17
|
for (;;) {
|
|
15
|
-
if (isZodObject(current)) {
|
|
16
|
-
return current;
|
|
17
|
-
}
|
|
18
18
|
if (current instanceof zod_1.z.ZodOptional || current instanceof zod_1.z.ZodNullable) {
|
|
19
19
|
current = current.unwrap();
|
|
20
20
|
continue;
|
|
21
21
|
}
|
|
22
22
|
if (current instanceof zod_1.z.ZodPipe) {
|
|
23
|
-
const inner = current.
|
|
24
|
-
if (isZodObject(inner)) {
|
|
25
|
-
|
|
23
|
+
const inner = current.in;
|
|
24
|
+
if (isZodObject(inner) || isZodArray(inner)) {
|
|
25
|
+
current = inner;
|
|
26
|
+
continue;
|
|
26
27
|
}
|
|
27
28
|
break;
|
|
28
29
|
}
|
|
29
30
|
break;
|
|
30
31
|
}
|
|
32
|
+
return current;
|
|
33
|
+
}
|
|
34
|
+
/** Объектная shape для навигации по dotted-пути (без object-level pipe/transform). */
|
|
35
|
+
function objectShapeForPick(schema) {
|
|
36
|
+
const current = schemaForPathStep(schema);
|
|
37
|
+
if (isZodObject(current)) {
|
|
38
|
+
return current;
|
|
39
|
+
}
|
|
31
40
|
throw Error("Not a zod object");
|
|
32
41
|
}
|
|
33
42
|
function pickObject(schema, path) {
|
|
34
43
|
const objectSchema = objectShapeForPick(schema);
|
|
35
|
-
const
|
|
44
|
+
const shape = objectSchema.shape;
|
|
45
|
+
const newSchema = shape[path];
|
|
36
46
|
if (!newSchema)
|
|
37
47
|
throw Error(
|
|
38
48
|
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
39
|
-
`${path} does not exist on schema with keys: ${Object.keys(
|
|
49
|
+
`${path} does not exist on schema with keys: ${Object.keys(shape)}`);
|
|
40
50
|
return newSchema;
|
|
41
51
|
}
|
|
42
52
|
function pickArray(schema) {
|
|
43
|
-
|
|
53
|
+
const current = schemaForPathStep(schema);
|
|
54
|
+
if (!isZodArray(current))
|
|
44
55
|
throw Error("Not a Zod Array");
|
|
45
|
-
const newSchema =
|
|
56
|
+
const newSchema = current.element;
|
|
46
57
|
if (!newSchema)
|
|
47
58
|
throw Error("No element on Zod Array");
|
|
48
59
|
return newSchema;
|
|
49
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* Схема конечного поля по dotted-пути клиентского patch.
|
|
63
|
+
*
|
|
64
|
+
* Элемент массива адресуется числовым сегментом (`meters.0.zones.0.value`).
|
|
65
|
+
* Индексом он считается только если текущий узел — `ZodArray`; у `ZodObject`
|
|
66
|
+
* тот же сегмент остаётся строковым ключом (`{ "0": z.string() }`).
|
|
67
|
+
*/
|
|
50
68
|
function zodDeepPick(schema, propertyPath) {
|
|
51
69
|
if (propertyPath === "")
|
|
52
70
|
return schema;
|
|
53
|
-
const
|
|
54
|
-
const
|
|
55
|
-
const
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
(matchedArray && !matchedObject)) {
|
|
60
|
-
const arraySplit = propertyPath.split(numberRegex);
|
|
61
|
-
const restArray = arraySplit.slice(1, arraySplit.length).join("[0]");
|
|
62
|
-
if (arrayIndex !== 0) {
|
|
63
|
-
return zodDeepPick(pickObject(schema, arraySplit[0]), `[0]${restArray}`);
|
|
64
|
-
}
|
|
65
|
-
return zodDeepPick(pickArray(schema), restArray.charAt(0) === "."
|
|
66
|
-
? restArray.slice(1, restArray.length)
|
|
67
|
-
: restArray);
|
|
68
|
-
}
|
|
69
|
-
if (matchedObject) {
|
|
70
|
-
const objectSplit = propertyPath.split(".");
|
|
71
|
-
const restObject = objectSplit.slice(1, objectSplit.length).join(".");
|
|
72
|
-
return zodDeepPick(pickObject(schema, objectSplit[0]), restObject);
|
|
71
|
+
const dot = propertyPath.indexOf(".");
|
|
72
|
+
const segment = dot === -1 ? propertyPath : propertyPath.slice(0, dot);
|
|
73
|
+
const rest = dot === -1 ? "" : propertyPath.slice(dot + 1);
|
|
74
|
+
const current = schemaForPathStep(schema);
|
|
75
|
+
if (isZodArray(current) && /^\d+$/.test(segment)) {
|
|
76
|
+
return zodDeepPick(pickArray(current), rest);
|
|
73
77
|
}
|
|
74
|
-
return pickObject(schema,
|
|
78
|
+
return zodDeepPick(pickObject(schema, segment), rest);
|
|
75
79
|
}
|
package/package.json
CHANGED