@matreshka/bff 0.24.0 → 0.25.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/components/component.js +1 -2
- package/dist/components/dialog.d.ts +30 -5
- package/dist/components/dialog.js +44 -27
- package/dist/components/entry-component.d.ts +39 -3
- package/dist/components/entry-component.js +111 -5
- package/dist/components/index.d.ts +2 -0
- package/dist/components/index.js +5 -1
- package/dist/components/page.d.ts +2 -17
- package/dist/components/page.js +1 -50
- package/dist/components/popover.d.ts +24 -5
- package/dist/components/popover.js +36 -26
- package/dist/components/webmcp/web-mcp-tool.d.ts +57 -0
- package/dist/components/webmcp/web-mcp-tool.js +150 -0
- package/dist/platforms/platform.d.ts +12 -0
- package/dist/platforms/platform.js +45 -0
- package/package.json +2 -2
|
@@ -355,8 +355,7 @@ class Component {
|
|
|
355
355
|
.subscribe((0, incoming_message_observer_1.incomingMessageObserver)(client, (message) => {
|
|
356
356
|
const instance = this.instances.find((x) => x.id === message.target);
|
|
357
357
|
if (!instance) {
|
|
358
|
-
client.error$.next(
|
|
359
|
-
this.class());
|
|
358
|
+
client.error$.next(`Component interaction call, component instance not found. Component class: ${this.class()}, interaction type: ${message.eventType}`);
|
|
360
359
|
return;
|
|
361
360
|
}
|
|
362
361
|
if (instance.client !== client) {
|
|
@@ -6,6 +6,7 @@ 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";
|
|
9
10
|
/** Анимации подложки модального диалога при инициализации. */
|
|
10
11
|
export type DialogBackdropInitConfig = {
|
|
11
12
|
onEnter?: AnimateComponent | AnimateComponent[];
|
|
@@ -53,15 +54,42 @@ export declare function dialog(content: DialogContent): Dialog;
|
|
|
53
54
|
export declare function dialog(options: DialogOptions, content: DialogContent): Dialog;
|
|
54
55
|
export declare function dialog(config: DefaultInitConfigType): Dialog;
|
|
55
56
|
/**
|
|
56
|
-
*
|
|
57
|
+
* Базовый класс диалога.
|
|
58
|
+
*
|
|
59
|
+
* Фабрика {@link dialog} и `new Dialog(config)` задают диалог конфигурацией.
|
|
60
|
+
* Наследник задаёт те же поля методами, как Page, и не обязан передавать их в `super`.
|
|
61
|
+
* Метод по умолчанию возвращает значение из конфигурации конструктора.
|
|
62
|
+
* Переопределение заменяет его; `super.метод()` по-прежнему читает конструктор.
|
|
57
63
|
*
|
|
58
64
|
* @template InitConfigType Тип конфигурации инициализации.
|
|
59
65
|
*/
|
|
60
|
-
export declare class Dialog<InitConfigType extends DialogInitConfig<any> = DefaultInitConfigType, PropertiesType extends DialogProperties = DialogProperties> extends EntryComponent<InitConfigType, PropertiesType> implements Componentable {
|
|
66
|
+
export declare class Dialog<InitConfigType extends DialogInitConfig<any> = DefaultInitConfigType, PropertiesType extends DialogProperties = DialogProperties> extends EntryComponent<InitConfigType, PropertiesType, DialogConfig> implements Componentable {
|
|
61
67
|
/** Локальные (client-only) действия entry-диалога. */
|
|
62
68
|
readonly local: {
|
|
63
69
|
close: (config?: ActionConfig) => import("../core/actions/close-entry").CloseEntry;
|
|
64
70
|
};
|
|
71
|
+
constructor(config?: Partial<InitConfigType>);
|
|
72
|
+
/**
|
|
73
|
+
* Содержимое диалога. По умолчанию — `content` конструктора.
|
|
74
|
+
*/
|
|
75
|
+
protected content(): InitConfigType["content"];
|
|
76
|
+
/**
|
|
77
|
+
* Якоря позиционирования. По умолчанию — `anchors` конструктора.
|
|
78
|
+
* Обычный массив, чтобы литерал `[OverlayAnchor.Center]` в наследнике не требовал кортеж.
|
|
79
|
+
*/
|
|
80
|
+
protected anchors(): readonly OverlayAnchor[] | undefined;
|
|
81
|
+
/**
|
|
82
|
+
* Модальность. По умолчанию — `modal` конструктора.
|
|
83
|
+
*/
|
|
84
|
+
protected modal(): InitConfigType["modal"];
|
|
85
|
+
/**
|
|
86
|
+
* Анимации подложки. По умолчанию — `backdrop` конструктора.
|
|
87
|
+
*/
|
|
88
|
+
protected backdrop(): InitConfigType["backdrop"];
|
|
89
|
+
/**
|
|
90
|
+
* Оверлеи диалога. По умолчанию — `overlays` конструктора.
|
|
91
|
+
*/
|
|
92
|
+
protected overlays(): Overlay[] | undefined;
|
|
65
93
|
/**
|
|
66
94
|
* Возвращает уникальный идентификатор класса компонента.
|
|
67
95
|
* @returns Строка "dialog".
|
|
@@ -78,8 +106,5 @@ export declare class Dialog<InitConfigType extends DialogInitConfig<any> = Defau
|
|
|
78
106
|
* Закрывает диалог, инициируя событие взаимодействия "close".
|
|
79
107
|
*/
|
|
80
108
|
close(instances?: ComponentInstance[]): import("rxjs").Observable<void>;
|
|
81
|
-
protected serializeRuleOverrides(overrides: Partial<PropertiesType>): Record<string, unknown>;
|
|
82
|
-
protected serializeEntry(instance: ComponentInstance<this>): DialogConfig;
|
|
83
|
-
serialize(instance?: ComponentInstance<this>): DialogConfig;
|
|
84
109
|
}
|
|
85
110
|
export {};
|
|
@@ -48,18 +48,54 @@ function dialog(arg0, arg1) {
|
|
|
48
48
|
return new Dialog({ content: single });
|
|
49
49
|
}
|
|
50
50
|
/**
|
|
51
|
-
*
|
|
51
|
+
* Базовый класс диалога.
|
|
52
|
+
*
|
|
53
|
+
* Фабрика {@link dialog} и `new Dialog(config)` задают диалог конфигурацией.
|
|
54
|
+
* Наследник задаёт те же поля методами, как Page, и не обязан передавать их в `super`.
|
|
55
|
+
* Метод по умолчанию возвращает значение из конфигурации конструктора.
|
|
56
|
+
* Переопределение заменяет его; `super.метод()` по-прежнему читает конструктор.
|
|
52
57
|
*
|
|
53
58
|
* @template InitConfigType Тип конфигурации инициализации.
|
|
54
59
|
*/
|
|
55
60
|
class Dialog extends entry_component_1.EntryComponent {
|
|
56
|
-
constructor() {
|
|
57
|
-
super(
|
|
61
|
+
constructor(config) {
|
|
62
|
+
super((config ?? {}));
|
|
58
63
|
/** Локальные (client-only) действия entry-диалога. */
|
|
59
64
|
this.local = {
|
|
60
65
|
close: (config) => (0, close_entry_1.closeEntry)(this, config),
|
|
61
66
|
};
|
|
62
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* Содержимое диалога. По умолчанию — `content` конструктора.
|
|
70
|
+
*/
|
|
71
|
+
content() {
|
|
72
|
+
return this.config.content;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Якоря позиционирования. По умолчанию — `anchors` конструктора.
|
|
76
|
+
* Обычный массив, чтобы литерал `[OverlayAnchor.Center]` в наследнике не требовал кортеж.
|
|
77
|
+
*/
|
|
78
|
+
anchors() {
|
|
79
|
+
return this.config.anchors;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Модальность. По умолчанию — `modal` конструктора.
|
|
83
|
+
*/
|
|
84
|
+
modal() {
|
|
85
|
+
return this.config.modal;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Анимации подложки. По умолчанию — `backdrop` конструктора.
|
|
89
|
+
*/
|
|
90
|
+
backdrop() {
|
|
91
|
+
return this.config.backdrop;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Оверлеи диалога. По умолчанию — `overlays` конструктора.
|
|
95
|
+
*/
|
|
96
|
+
overlays() {
|
|
97
|
+
return this.config.overlays;
|
|
98
|
+
}
|
|
63
99
|
/**
|
|
64
100
|
* Возвращает уникальный идентификатор класса компонента.
|
|
65
101
|
* @returns Строка "dialog".
|
|
@@ -76,10 +112,11 @@ class Dialog extends entry_component_1.EntryComponent {
|
|
|
76
112
|
initProperties(initValues) {
|
|
77
113
|
return {
|
|
78
114
|
...super.initProperties(initValues),
|
|
79
|
-
content: (0, core_1.calculateComponents)(
|
|
80
|
-
anchors:
|
|
81
|
-
modal:
|
|
82
|
-
backdrop: serializeDialogBackdrop(
|
|
115
|
+
content: (0, core_1.calculateComponents)(this.content()),
|
|
116
|
+
anchors: this.anchors(),
|
|
117
|
+
modal: this.modal(),
|
|
118
|
+
backdrop: serializeDialogBackdrop(this.backdrop()),
|
|
119
|
+
overlays: this.overlays(),
|
|
83
120
|
};
|
|
84
121
|
}
|
|
85
122
|
/**
|
|
@@ -88,25 +125,5 @@ class Dialog extends entry_component_1.EntryComponent {
|
|
|
88
125
|
close(instances) {
|
|
89
126
|
return this.dispatchComponentCommand(instances, (target, actionScope) => new dialog_close_message_1.DialogCloseMessage(target, { actionScope }));
|
|
90
127
|
}
|
|
91
|
-
serializeRuleOverrides(overrides) {
|
|
92
|
-
const out = super.serializeRuleOverrides(overrides);
|
|
93
|
-
if (overrides.content !== undefined) {
|
|
94
|
-
out.content = (0, core_1.serializeComponentList)(overrides.content);
|
|
95
|
-
}
|
|
96
|
-
return out;
|
|
97
|
-
}
|
|
98
|
-
serializeEntry(instance) {
|
|
99
|
-
const result = super.serializeEntry(instance);
|
|
100
|
-
return {
|
|
101
|
-
...result,
|
|
102
|
-
class: server_component_class_1.ServerComponentClass.Dialog,
|
|
103
|
-
properties: this.buildPropertiesForClient({
|
|
104
|
-
content: (0, core_1.serializeComponentList)(this.properties.content),
|
|
105
|
-
}),
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
serialize(instance) {
|
|
109
|
-
return this.withEntrySerializationContext(instance, (resolvedInstance) => this.serializeEntry(resolvedInstance));
|
|
110
|
-
}
|
|
111
128
|
}
|
|
112
129
|
exports.Dialog = Dialog;
|
|
@@ -1,12 +1,16 @@
|
|
|
1
|
+
import type { EntryServerComponentConfig } from "@matreshka/shared/types/entry-server-component-config";
|
|
2
|
+
import type { Client } from "../core/client";
|
|
1
3
|
import type { ComponentInstance } from "../core/types/component-instance";
|
|
2
4
|
import type { Componentable } from "../core/types/componentable";
|
|
3
5
|
import { Component, ComponentInitConfig, ComponentProperties, ServerComponentAction } from "./component";
|
|
6
|
+
import { type WebMcpTool } from "./webmcp/web-mcp-tool";
|
|
4
7
|
/**
|
|
5
8
|
* Конфигурация инициализации для EntryComponent без поля conditions
|
|
6
9
|
*/
|
|
7
10
|
export type EntryComponentInitConfig<ComponentType extends Componentable, PropertiesType extends EntryComponentProperties = EntryComponentProperties> = Omit<ComponentInitConfig<ComponentType, PropertiesType>, "conditions" | "onShow" | "onHide"> & {
|
|
8
11
|
onEnter?: EntryComponentAction<ComponentType> | EntryComponentAction<ComponentType>[];
|
|
9
12
|
onLeave?: EntryLeaveAction<ComponentType> | EntryLeaveAction<ComponentType>[];
|
|
13
|
+
tools?: WebMcpTool[];
|
|
10
14
|
};
|
|
11
15
|
export type EntryComponentAction<ComponentType extends Componentable> = ServerComponentAction<ComponentType, undefined>;
|
|
12
16
|
export type EntryLeaveAction<ComponentType extends Componentable> = ServerComponentAction<ComponentType, undefined>;
|
|
@@ -19,12 +23,44 @@ type DefaultInitConfigType = EntryComponentInitConfig<EntryComponent>;
|
|
|
19
23
|
* Абстрактный компонент-входная точка, наследует поведение базового Component
|
|
20
24
|
* и типы состояний/свойств/инициализации (кроме поля conditions).
|
|
21
25
|
*/
|
|
22
|
-
export declare abstract class EntryComponent<InitConfigType extends EntryComponentInitConfig<any> = DefaultInitConfigType, PropertiesType extends EntryComponentProperties = EntryComponentProperties> extends Component<InitConfigType, PropertiesType> {
|
|
26
|
+
export declare abstract class EntryComponent<InitConfigType extends EntryComponentInitConfig<any> = DefaultInitConfigType, PropertiesType extends EntryComponentProperties = EntryComponentProperties, SerializedConfigType extends EntryServerComponentConfig = EntryServerComponentConfig> extends Component<InitConfigType, PropertiesType> {
|
|
27
|
+
private readonly registeredTools;
|
|
28
|
+
private declaredToolsRegistered;
|
|
23
29
|
constructor(config: InitConfigType);
|
|
24
|
-
|
|
30
|
+
/**
|
|
31
|
+
* Показ entry. По умолчанию — `onEnter` конструктора.
|
|
32
|
+
* Читается в конструкторе, до полей наследника.
|
|
33
|
+
*/
|
|
34
|
+
protected onEnter(): InitConfigType["onEnter"];
|
|
35
|
+
/**
|
|
36
|
+
* Начало ухода entry. По умолчанию — `onLeave` конструктора.
|
|
37
|
+
* Читается в конструкторе, до полей наследника.
|
|
38
|
+
*/
|
|
39
|
+
protected onLeave(): InitConfigType["onLeave"];
|
|
40
|
+
/**
|
|
41
|
+
* WebMCP-тулзы entry. По умолчанию — `tools` конструктора.
|
|
42
|
+
* Читается после конструктора наследника: поля наследника уже есть.
|
|
43
|
+
*/
|
|
44
|
+
protected tools(): readonly WebMcpTool[] | undefined;
|
|
45
|
+
/** Сохранённые WebMCP-тулзы. execute не сериализуется и не вызывается до сообщения вызова. */
|
|
46
|
+
get entryTools(): readonly WebMcpTool[];
|
|
47
|
+
protected registerEntryTools(tools: readonly WebMcpTool[] | undefined): void;
|
|
48
|
+
/** Привязка обработчиков к имени взаимодействия. */
|
|
49
|
+
protected bindDeclaredInteraction(event: string, handlers: ServerComponentAction<any, any> | ServerComponentAction<any, any>[] | undefined): void;
|
|
50
|
+
/**
|
|
51
|
+
* Тулзы читают поля наследника, поэтому регистрируются после конструктора:
|
|
52
|
+
* при первом чтении списка и перед сериализацией.
|
|
53
|
+
* Флаг ставится до чтения, чтобы `tools()` мог обратиться к `entryTools`.
|
|
54
|
+
*/
|
|
55
|
+
private registerDeclaredTools;
|
|
56
|
+
serialize(instance?: ComponentInstance<this>): SerializedConfigType;
|
|
25
57
|
/** @internal */
|
|
26
58
|
protected withEntrySerializationContext<T>(instance: ComponentInstance<this> | undefined, fn: (instance: ComponentInstance<this>) => T): T;
|
|
27
|
-
protected serializeEntry(instance: ComponentInstance<this>):
|
|
59
|
+
protected serializeEntry(instance: ComponentInstance<this>): SerializedConfigType;
|
|
60
|
+
protected serializeRuleOverrides(overrides: Partial<PropertiesType>): Record<string, unknown>;
|
|
61
|
+
/** Сырое дерево content, если наследник его задаёт. */
|
|
62
|
+
private entryContent;
|
|
63
|
+
protected subscribeClientEvents(client: Client): void;
|
|
28
64
|
/** Контекст сериализации дочерних компонентов без полной serialize entry. @internal */
|
|
29
65
|
beginSerializationContext(): ComponentInstance<this>;
|
|
30
66
|
protected createSelfEntry(): ComponentInstance<this>;
|
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.EntryComponent = void 0;
|
|
4
|
+
const web_mcp_tool_call_message_1 = require("@matreshka/shared/messages/client-to-bff/webmcp/web-mcp-tool-call-message");
|
|
5
|
+
const rxjs_1 = require("rxjs");
|
|
4
6
|
const client_context_1 = require("../core/client-context");
|
|
5
7
|
const entry_context_1 = require("../core/entry-context");
|
|
8
|
+
const incoming_message_observer_1 = require("../core/utils/incoming-message-observer");
|
|
9
|
+
const serialize_component_tree_1 = require("../core/utils/serialize-component-tree");
|
|
6
10
|
const component_1 = require("./component");
|
|
11
|
+
const web_mcp_tool_1 = require("./webmcp/web-mcp-tool");
|
|
7
12
|
/**
|
|
8
13
|
* Абстрактный компонент-входная точка, наследует поведение базового Component
|
|
9
14
|
* и типы состояний/свойств/инициализации (кроме поля conditions).
|
|
@@ -11,12 +16,62 @@ const component_1 = require("./component");
|
|
|
11
16
|
class EntryComponent extends component_1.Component {
|
|
12
17
|
constructor(config) {
|
|
13
18
|
super(config);
|
|
14
|
-
|
|
15
|
-
|
|
19
|
+
this.registeredTools = [];
|
|
20
|
+
this.declaredToolsRegistered = false;
|
|
21
|
+
// До полей наследника. В отложенном обработчике this уже собран.
|
|
22
|
+
this.bindDeclaredInteraction("enter", this.onEnter());
|
|
23
|
+
this.bindDeclaredInteraction("leave", this.onLeave());
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Показ entry. По умолчанию — `onEnter` конструктора.
|
|
27
|
+
* Читается в конструкторе, до полей наследника.
|
|
28
|
+
*/
|
|
29
|
+
onEnter() {
|
|
30
|
+
return this.config.onEnter;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Начало ухода entry. По умолчанию — `onLeave` конструктора.
|
|
34
|
+
* Читается в конструкторе, до полей наследника.
|
|
35
|
+
*/
|
|
36
|
+
onLeave() {
|
|
37
|
+
return this.config.onLeave;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* WebMCP-тулзы entry. По умолчанию — `tools` конструктора.
|
|
41
|
+
* Читается после конструктора наследника: поля наследника уже есть.
|
|
42
|
+
*/
|
|
43
|
+
tools() {
|
|
44
|
+
return this.config.tools;
|
|
45
|
+
}
|
|
46
|
+
/** Сохранённые WebMCP-тулзы. execute не сериализуется и не вызывается до сообщения вызова. */
|
|
47
|
+
get entryTools() {
|
|
48
|
+
this.registerDeclaredTools();
|
|
49
|
+
return this.registeredTools;
|
|
50
|
+
}
|
|
51
|
+
registerEntryTools(tools) {
|
|
52
|
+
if (!tools) {
|
|
53
|
+
return;
|
|
16
54
|
}
|
|
17
|
-
|
|
18
|
-
|
|
55
|
+
this.registeredTools.push(...tools);
|
|
56
|
+
}
|
|
57
|
+
/** Привязка обработчиков к имени взаимодействия. */
|
|
58
|
+
bindDeclaredInteraction(event, handlers) {
|
|
59
|
+
if (handlers === undefined) {
|
|
60
|
+
return;
|
|
19
61
|
}
|
|
62
|
+
this.bindActions(event, handlers);
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Тулзы читают поля наследника, поэтому регистрируются после конструктора:
|
|
66
|
+
* при первом чтении списка и перед сериализацией.
|
|
67
|
+
* Флаг ставится до чтения, чтобы `tools()` мог обратиться к `entryTools`.
|
|
68
|
+
*/
|
|
69
|
+
registerDeclaredTools() {
|
|
70
|
+
if (this.declaredToolsRegistered) {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
this.declaredToolsRegistered = true;
|
|
74
|
+
this.registerEntryTools(this.tools());
|
|
20
75
|
}
|
|
21
76
|
serialize(instance) {
|
|
22
77
|
return this.withEntrySerializationContext(instance, (resolvedInstance) => this.serializeEntry(resolvedInstance));
|
|
@@ -33,7 +88,58 @@ class EntryComponent extends component_1.Component {
|
|
|
33
88
|
return fn(instance);
|
|
34
89
|
}
|
|
35
90
|
serializeEntry(instance) {
|
|
36
|
-
|
|
91
|
+
this.registerDeclaredTools();
|
|
92
|
+
const result = super.serialize(instance);
|
|
93
|
+
const content = this.entryContent();
|
|
94
|
+
return {
|
|
95
|
+
...result,
|
|
96
|
+
...(this.registeredTools.length > 0
|
|
97
|
+
? {
|
|
98
|
+
tools: this.registeredTools.map((tool) => tool.serialize()),
|
|
99
|
+
}
|
|
100
|
+
: {}),
|
|
101
|
+
...(content
|
|
102
|
+
? {
|
|
103
|
+
properties: this.buildPropertiesForClient({
|
|
104
|
+
content: (0, serialize_component_tree_1.serializeComponentList)(content),
|
|
105
|
+
}),
|
|
106
|
+
}
|
|
107
|
+
: {}),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
serializeRuleOverrides(overrides) {
|
|
111
|
+
const out = super.serializeRuleOverrides(overrides);
|
|
112
|
+
const content = overrides
|
|
113
|
+
.content;
|
|
114
|
+
if (content !== undefined) {
|
|
115
|
+
out.content = (0, serialize_component_tree_1.serializeComponentList)(content);
|
|
116
|
+
}
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
/** Сырое дерево content, если наследник его задаёт. */
|
|
120
|
+
entryContent() {
|
|
121
|
+
const content = this.properties.content;
|
|
122
|
+
return Array.isArray(content)
|
|
123
|
+
? content
|
|
124
|
+
: undefined;
|
|
125
|
+
}
|
|
126
|
+
subscribeClientEvents(client) {
|
|
127
|
+
super.subscribeClientEvents(client);
|
|
128
|
+
const sub = this.clientSubscriptions.get(client);
|
|
129
|
+
if (!sub) {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
sub.add(client.incomingMessage$
|
|
133
|
+
.pipe((0, rxjs_1.filter)((message) => message instanceof web_mcp_tool_call_message_1.WebMcpToolCallMessage))
|
|
134
|
+
.subscribe((0, incoming_message_observer_1.incomingMessageObserver)(client, (message) => {
|
|
135
|
+
const tool = this.registeredTools.find((item) => item.id === message.target);
|
|
136
|
+
if (!tool) {
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
void (0, web_mcp_tool_1.dispatchWebMcpToolCall)(client, tool, message.id, message.payload?.input).catch((error) => {
|
|
140
|
+
client.error$.next(error);
|
|
141
|
+
});
|
|
142
|
+
})));
|
|
37
143
|
}
|
|
38
144
|
/** Контекст сериализации дочерних компонентов без полной serialize entry. @internal */
|
|
39
145
|
beginSerializationContext() {
|
|
@@ -54,3 +54,5 @@ export * from "./map";
|
|
|
54
54
|
export * from "./popover";
|
|
55
55
|
export * from "./stack";
|
|
56
56
|
export { isStandaloneComponentLike } from "./utils/component-factory-shared";
|
|
57
|
+
export { WebMcpTool, WebMcpToolAnnotation, webMcpTool, } from "./webmcp/web-mcp-tool";
|
|
58
|
+
export type { WebMcpToolExecute, WebMcpToolInit, WebMcpToolWithInput, WebMcpToolWithoutInput, } from "./webmcp/web-mcp-tool";
|
package/dist/components/index.js
CHANGED
|
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.isStandaloneComponentLike = exports.scrollDistanceToEnd = exports.needsMore = exports.OverlayAnchor = void 0;
|
|
17
|
+
exports.webMcpTool = exports.WebMcpToolAnnotation = exports.WebMcpTool = exports.isStandaloneComponentLike = exports.scrollDistanceToEnd = exports.needsMore = exports.OverlayAnchor = void 0;
|
|
18
18
|
__exportStar(require("./actions/server-action"), exports);
|
|
19
19
|
var container_overlay_1 = require("@matreshka/shared/types/container-overlay");
|
|
20
20
|
Object.defineProperty(exports, "OverlayAnchor", { enumerable: true, get: function () { return container_overlay_1.OverlayAnchor; } });
|
|
@@ -75,3 +75,7 @@ __exportStar(require("./popover"), exports);
|
|
|
75
75
|
__exportStar(require("./stack"), exports);
|
|
76
76
|
var component_factory_shared_1 = require("./utils/component-factory-shared");
|
|
77
77
|
Object.defineProperty(exports, "isStandaloneComponentLike", { enumerable: true, get: function () { return component_factory_shared_1.isStandaloneComponentLike; } });
|
|
78
|
+
var web_mcp_tool_1 = require("./webmcp/web-mcp-tool");
|
|
79
|
+
Object.defineProperty(exports, "WebMcpTool", { enumerable: true, get: function () { return web_mcp_tool_1.WebMcpTool; } });
|
|
80
|
+
Object.defineProperty(exports, "WebMcpToolAnnotation", { enumerable: true, get: function () { return web_mcp_tool_1.WebMcpToolAnnotation; } });
|
|
81
|
+
Object.defineProperty(exports, "webMcpTool", { enumerable: true, get: function () { return web_mcp_tool_1.webMcpTool; } });
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ServerComponentClass } from "@matreshka/shared/enums/server-component-class";
|
|
2
2
|
import type { ComponentScrollPayload } from "@matreshka/shared/messages/client-to-bff/components/component-scroll-message";
|
|
3
3
|
import type { PageConfig } from "@matreshka/shared/types/page-config";
|
|
4
|
-
import { Componentable,
|
|
4
|
+
import { Componentable, ComponentTreeNode, MixedWithCallbacksArray, Pageable } from "../core";
|
|
5
5
|
import StatusCode from "../core/types/status-code";
|
|
6
6
|
import { ServerComponentAction } from "./component";
|
|
7
7
|
import { EntryComponent, EntryComponentInitConfig, EntryComponentProperties } from "./entry-component";
|
|
@@ -26,12 +26,8 @@ type DefaultInitConfigType = PageInitConfig<Page>;
|
|
|
26
26
|
/**
|
|
27
27
|
* Абстрактный базовый класс страницы.
|
|
28
28
|
*/
|
|
29
|
-
export declare abstract class Page<InitConfigType extends PageInitConfig<any> = DefaultInitConfigType, PropertiesType extends PageProperties = PageProperties> extends EntryComponent<InitConfigType, PropertiesType> implements Pageable {
|
|
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
|
-
/** Привязка обработчиков страницы к имени взаимодействия (как на клиенте в `interact`). */
|
|
32
|
-
private bindPageInteraction;
|
|
33
|
-
/** Привязка lifecycle entry-страницы к имени взаимодействия. */
|
|
34
|
-
private bindPageEntryInteraction;
|
|
35
31
|
/**
|
|
36
32
|
* Возвращает HTTP-статус страницы.
|
|
37
33
|
* @returns Статус страницы (по умолчанию 200 OK).
|
|
@@ -67,14 +63,6 @@ export declare abstract class Page<InitConfigType extends PageInitConfig<any> =
|
|
|
67
63
|
* Переопредели в наследнике для дозагрузки списков и т.п.
|
|
68
64
|
*/
|
|
69
65
|
protected onScroll(): ServerComponentAction<Page, ComponentScrollPayload> | ServerComponentAction<Page, ComponentScrollPayload>[] | undefined;
|
|
70
|
-
/**
|
|
71
|
-
* Обработчики показа хоста страницы (`app-page`), после готовности представления на клиенте.
|
|
72
|
-
*/
|
|
73
|
-
protected onEnter(): ServerComponentAction<Page, undefined> | ServerComponentAction<Page, undefined>[] | undefined;
|
|
74
|
-
/**
|
|
75
|
-
* Обработчики скрытия / уничтожения хоста страницы на клиенте.
|
|
76
|
-
*/
|
|
77
|
-
protected onLeave(): ServerComponentAction<Page, undefined> | ServerComponentAction<Page, undefined>[] | undefined;
|
|
78
66
|
/**
|
|
79
67
|
* Инициализирует свойства страницы.
|
|
80
68
|
*
|
|
@@ -88,8 +76,5 @@ export declare abstract class Page<InitConfigType extends PageInitConfig<any> =
|
|
|
88
76
|
* @returns Строка "page".
|
|
89
77
|
*/
|
|
90
78
|
protected class(): ServerComponentClass;
|
|
91
|
-
protected serializeRuleOverrides(overrides: Partial<PropertiesType>): Record<string, unknown>;
|
|
92
|
-
protected serializeEntry(instance: ComponentInstance<this>): PageConfig;
|
|
93
|
-
serialize(instance?: ComponentInstance<this>): PageConfig;
|
|
94
79
|
}
|
|
95
80
|
export {};
|
package/dist/components/page.js
CHANGED
|
@@ -6,7 +6,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
6
6
|
exports.Page = void 0;
|
|
7
7
|
const server_component_class_1 = require("@matreshka/shared/enums/server-component-class");
|
|
8
8
|
const status_code_1 = __importDefault(require("../core/types/status-code"));
|
|
9
|
-
const serialize_component_tree_1 = require("../core/utils/serialize-component-tree");
|
|
10
9
|
const entry_component_1 = require("./entry-component");
|
|
11
10
|
/**
|
|
12
11
|
* Абстрактный базовый класс страницы.
|
|
@@ -15,23 +14,7 @@ class Page extends entry_component_1.EntryComponent {
|
|
|
15
14
|
constructor() {
|
|
16
15
|
// @ts-expect-error Page задаёт content в boot(), а не через конфиг конструктора Component.
|
|
17
16
|
super({});
|
|
18
|
-
this.
|
|
19
|
-
this.bindPageEntryInteraction("enter", this.onEnter());
|
|
20
|
-
this.bindPageEntryInteraction("leave", this.onLeave());
|
|
21
|
-
}
|
|
22
|
-
/** Привязка обработчиков страницы к имени взаимодействия (как на клиенте в `interact`). */
|
|
23
|
-
bindPageInteraction(event, handlers) {
|
|
24
|
-
if (handlers === undefined) {
|
|
25
|
-
return;
|
|
26
|
-
}
|
|
27
|
-
this.bindActions(event, handlers);
|
|
28
|
-
}
|
|
29
|
-
/** Привязка lifecycle entry-страницы к имени взаимодействия. */
|
|
30
|
-
bindPageEntryInteraction(event, handlers) {
|
|
31
|
-
if (handlers === undefined) {
|
|
32
|
-
return;
|
|
33
|
-
}
|
|
34
|
-
this.bindActions(event, handlers);
|
|
17
|
+
this.bindDeclaredInteraction("scroll", this.onScroll());
|
|
35
18
|
}
|
|
36
19
|
/**
|
|
37
20
|
* Возвращает HTTP-статус страницы.
|
|
@@ -62,18 +45,6 @@ class Page extends entry_component_1.EntryComponent {
|
|
|
62
45
|
onScroll() {
|
|
63
46
|
return undefined;
|
|
64
47
|
}
|
|
65
|
-
/**
|
|
66
|
-
* Обработчики показа хоста страницы (`app-page`), после готовности представления на клиенте.
|
|
67
|
-
*/
|
|
68
|
-
onEnter() {
|
|
69
|
-
return undefined;
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
|
-
* Обработчики скрытия / уничтожения хоста страницы на клиенте.
|
|
73
|
-
*/
|
|
74
|
-
onLeave() {
|
|
75
|
-
return undefined;
|
|
76
|
-
}
|
|
77
48
|
/**
|
|
78
49
|
* Инициализирует свойства страницы.
|
|
79
50
|
*
|
|
@@ -97,25 +68,5 @@ class Page extends entry_component_1.EntryComponent {
|
|
|
97
68
|
class() {
|
|
98
69
|
return server_component_class_1.ServerComponentClass.Page;
|
|
99
70
|
}
|
|
100
|
-
serializeRuleOverrides(overrides) {
|
|
101
|
-
const out = super.serializeRuleOverrides(overrides);
|
|
102
|
-
if (overrides.content !== undefined) {
|
|
103
|
-
out.content = (0, serialize_component_tree_1.serializeComponentList)(overrides.content);
|
|
104
|
-
}
|
|
105
|
-
return out;
|
|
106
|
-
}
|
|
107
|
-
serializeEntry(instance) {
|
|
108
|
-
const result = super.serializeEntry(instance);
|
|
109
|
-
return {
|
|
110
|
-
...result,
|
|
111
|
-
class: server_component_class_1.ServerComponentClass.Page,
|
|
112
|
-
properties: this.buildPropertiesForClient({
|
|
113
|
-
content: (0, serialize_component_tree_1.serializeComponentList)(this.properties.content),
|
|
114
|
-
}),
|
|
115
|
-
};
|
|
116
|
-
}
|
|
117
|
-
serialize(instance) {
|
|
118
|
-
return this.withEntrySerializationContext(instance, (resolvedInstance) => this.serializeEntry(resolvedInstance));
|
|
119
|
-
}
|
|
120
71
|
}
|
|
121
72
|
exports.Page = Page;
|
|
@@ -32,15 +32,37 @@ export declare function popover(content: PopoverContent): Popover;
|
|
|
32
32
|
export declare function popover(options: PopoverOptions, content: PopoverContent): Popover;
|
|
33
33
|
export declare function popover(config: DefaultInitConfigType): Popover;
|
|
34
34
|
/**
|
|
35
|
-
*
|
|
35
|
+
* Всплывающая панель.
|
|
36
36
|
*
|
|
37
37
|
* На клиенте рендерится через [Popover API](https://doka.guide/html/popover/) (`popover="auto"`).
|
|
38
|
+
*
|
|
39
|
+
* Фабрика {@link popover} и `new Popover(config)` задают панель конфигурацией.
|
|
40
|
+
* Наследник задаёт те же поля методами, как Page, и не обязан передавать их в `super`.
|
|
41
|
+
* Метод по умолчанию возвращает значение из конфигурации конструктора.
|
|
42
|
+
* Переопределение заменяет его; `super.метод()` по-прежнему читает конструктор.
|
|
38
43
|
*/
|
|
39
|
-
export declare class Popover<InitConfigType extends PopoverInitConfig<any> = DefaultInitConfigType, PropertiesType extends PopoverProperties = PopoverProperties> extends EntryComponent<InitConfigType, PropertiesType> {
|
|
44
|
+
export declare class Popover<InitConfigType extends PopoverInitConfig<any> = DefaultInitConfigType, PropertiesType extends PopoverProperties = PopoverProperties> extends EntryComponent<InitConfigType, PropertiesType, PopoverConfig> {
|
|
40
45
|
/** Локальные (client-only) действия entry-popover. */
|
|
41
46
|
readonly local: {
|
|
42
47
|
close: (config?: ActionConfig) => import("../core/actions/close-entry").CloseEntry;
|
|
43
48
|
};
|
|
49
|
+
constructor(config?: Partial<InitConfigType>);
|
|
50
|
+
/**
|
|
51
|
+
* Содержимое popover. По умолчанию — `content` конструктора.
|
|
52
|
+
*/
|
|
53
|
+
protected content(): InitConfigType["content"];
|
|
54
|
+
/**
|
|
55
|
+
* Привязка к якорю. По умолчанию — `positionArea` конструктора.
|
|
56
|
+
*/
|
|
57
|
+
protected positionArea(): InitConfigType["positionArea"];
|
|
58
|
+
/**
|
|
59
|
+
* Ширина popover. По умолчанию — `size` конструктора.
|
|
60
|
+
*/
|
|
61
|
+
protected size(): InitConfigType["size"];
|
|
62
|
+
/**
|
|
63
|
+
* Оверлеи popover. По умолчанию — `overlays` конструктора.
|
|
64
|
+
*/
|
|
65
|
+
protected overlays(): InitConfigType["overlays"];
|
|
44
66
|
/**
|
|
45
67
|
* Возвращает уникальный идентификатор класса компонента.
|
|
46
68
|
*
|
|
@@ -58,8 +80,5 @@ export declare class Popover<InitConfigType extends PopoverInitConfig<any> = Def
|
|
|
58
80
|
* @returns Объект со свойствами компонента.
|
|
59
81
|
*/
|
|
60
82
|
protected initProperties(initValues: InitConfigType): PropertiesType;
|
|
61
|
-
protected serializeRuleOverrides(overrides: Partial<PropertiesType>): Record<string, unknown>;
|
|
62
|
-
protected serializeEntry(instance: ComponentInstance<this>): PopoverConfig;
|
|
63
|
-
serialize(instance?: ComponentInstance<this>): PopoverConfig;
|
|
64
83
|
}
|
|
65
84
|
export {};
|
|
@@ -24,18 +24,47 @@ function popover(arg0, arg1) {
|
|
|
24
24
|
return new Popover({ content: single });
|
|
25
25
|
}
|
|
26
26
|
/**
|
|
27
|
-
*
|
|
27
|
+
* Всплывающая панель.
|
|
28
28
|
*
|
|
29
29
|
* На клиенте рендерится через [Popover API](https://doka.guide/html/popover/) (`popover="auto"`).
|
|
30
|
+
*
|
|
31
|
+
* Фабрика {@link popover} и `new Popover(config)` задают панель конфигурацией.
|
|
32
|
+
* Наследник задаёт те же поля методами, как Page, и не обязан передавать их в `super`.
|
|
33
|
+
* Метод по умолчанию возвращает значение из конфигурации конструктора.
|
|
34
|
+
* Переопределение заменяет его; `super.метод()` по-прежнему читает конструктор.
|
|
30
35
|
*/
|
|
31
36
|
class Popover extends entry_component_1.EntryComponent {
|
|
32
|
-
constructor() {
|
|
33
|
-
super(
|
|
37
|
+
constructor(config) {
|
|
38
|
+
super((config ?? {}));
|
|
34
39
|
/** Локальные (client-only) действия entry-popover. */
|
|
35
40
|
this.local = {
|
|
36
41
|
close: (config) => (0, close_entry_1.closeEntry)(this, config),
|
|
37
42
|
};
|
|
38
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* Содержимое popover. По умолчанию — `content` конструктора.
|
|
46
|
+
*/
|
|
47
|
+
content() {
|
|
48
|
+
return this.config.content;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Привязка к якорю. По умолчанию — `positionArea` конструктора.
|
|
52
|
+
*/
|
|
53
|
+
positionArea() {
|
|
54
|
+
return this.config.positionArea;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Ширина popover. По умолчанию — `size` конструктора.
|
|
58
|
+
*/
|
|
59
|
+
size() {
|
|
60
|
+
return this.config.size;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Оверлеи popover. По умолчанию — `overlays` конструктора.
|
|
64
|
+
*/
|
|
65
|
+
overlays() {
|
|
66
|
+
return this.config.overlays;
|
|
67
|
+
}
|
|
39
68
|
/**
|
|
40
69
|
* Возвращает уникальный идентификатор класса компонента.
|
|
41
70
|
*
|
|
@@ -59,30 +88,11 @@ class Popover extends entry_component_1.EntryComponent {
|
|
|
59
88
|
initProperties(initValues) {
|
|
60
89
|
return {
|
|
61
90
|
...super.initProperties(initValues),
|
|
62
|
-
content: (0, core_1.calculateComponents)(
|
|
63
|
-
positionArea:
|
|
64
|
-
size:
|
|
91
|
+
content: (0, core_1.calculateComponents)(this.content()),
|
|
92
|
+
positionArea: this.positionArea(),
|
|
93
|
+
size: this.size(),
|
|
94
|
+
overlays: this.overlays(),
|
|
65
95
|
};
|
|
66
96
|
}
|
|
67
|
-
serializeRuleOverrides(overrides) {
|
|
68
|
-
const out = super.serializeRuleOverrides(overrides);
|
|
69
|
-
if (overrides.content !== undefined) {
|
|
70
|
-
out.content = (0, core_1.serializeComponentList)(overrides.content);
|
|
71
|
-
}
|
|
72
|
-
return out;
|
|
73
|
-
}
|
|
74
|
-
serializeEntry(instance) {
|
|
75
|
-
const result = super.serializeEntry(instance);
|
|
76
|
-
return {
|
|
77
|
-
...result,
|
|
78
|
-
class: server_component_class_1.ServerComponentClass.Popover,
|
|
79
|
-
properties: this.buildPropertiesForClient({
|
|
80
|
-
content: (0, core_1.serializeComponentList)(this.properties.content),
|
|
81
|
-
}),
|
|
82
|
-
};
|
|
83
|
-
}
|
|
84
|
-
serialize(instance) {
|
|
85
|
-
return this.withEntrySerializationContext(instance, (resolvedInstance) => this.serializeEntry(resolvedInstance));
|
|
86
|
-
}
|
|
87
97
|
}
|
|
88
98
|
exports.Popover = Popover;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { WebMcpToolAnnotation } from "@matreshka/shared/enums/web-mcp-tool-annotation";
|
|
2
|
+
import type { Condition as SerializedCondition } from "@matreshka/shared/types/condition";
|
|
3
|
+
import type { WebMcpToolConfig } from "@matreshka/shared/types/web-mcp-tool-config";
|
|
4
|
+
import { z } from "zod/v4";
|
|
5
|
+
import type { Client } from "../../core/client";
|
|
6
|
+
import { Condition } from "../../core/conditions/condition";
|
|
7
|
+
export { WebMcpToolAnnotation };
|
|
8
|
+
export type WebMcpToolExecute = () => Promise<string>;
|
|
9
|
+
export type WebMcpToolConditions = Condition[] | (() => Condition[]);
|
|
10
|
+
type WebMcpToolBase = {
|
|
11
|
+
name: string;
|
|
12
|
+
description: string;
|
|
13
|
+
annotations?: readonly WebMcpToolAnnotation[];
|
|
14
|
+
conditions?: WebMcpToolConditions;
|
|
15
|
+
};
|
|
16
|
+
/** Тулз со схемой аргументов. Тип `execute` выводится из схемы. */
|
|
17
|
+
export type WebMcpToolWithInput<TSchema extends z.ZodType> = WebMcpToolBase & {
|
|
18
|
+
inputSchema: TSchema;
|
|
19
|
+
execute: (input: z.output<TSchema>) => Promise<string>;
|
|
20
|
+
};
|
|
21
|
+
/** Тулз без аргументов. */
|
|
22
|
+
export type WebMcpToolWithoutInput = WebMcpToolBase & {
|
|
23
|
+
inputSchema?: undefined;
|
|
24
|
+
execute: WebMcpToolExecute;
|
|
25
|
+
};
|
|
26
|
+
/** Аргумент `webMcpTool()` и `new WebMcpTool()`. */
|
|
27
|
+
export type WebMcpToolInit<TSchema extends z.ZodType | undefined = undefined> = TSchema extends z.ZodType ? WebMcpToolWithInput<TSchema> : WebMcpToolWithoutInput;
|
|
28
|
+
type StoredExecute = (input?: unknown) => Promise<string>;
|
|
29
|
+
/**
|
|
30
|
+
* WebMCP-тулз entry или платформы.
|
|
31
|
+
* `webMcpTool({ ... })` и `new WebMcpTool({ ... })` создают один и тот же класс.
|
|
32
|
+
* id назначается при создании, автор его не задаёт.
|
|
33
|
+
* По `inputSchema` TypeScript выводит тип аргумента `execute`.
|
|
34
|
+
*
|
|
35
|
+
* Параметр схемы по умолчанию `any`, чтобы тулз с конкретной схемой
|
|
36
|
+
* можно было положить в `WebMcpTool[]`.
|
|
37
|
+
*/
|
|
38
|
+
export declare class WebMcpTool<TSchema extends z.ZodType | undefined = any> {
|
|
39
|
+
readonly id: string;
|
|
40
|
+
readonly name: string;
|
|
41
|
+
readonly description: string;
|
|
42
|
+
readonly annotations: readonly WebMcpToolAnnotation[];
|
|
43
|
+
readonly execute: StoredExecute;
|
|
44
|
+
readonly inputSchema?: z.ZodType;
|
|
45
|
+
readonly conditions: SerializedCondition[];
|
|
46
|
+
constructor(init: WebMcpToolInit<TSchema>);
|
|
47
|
+
/**
|
|
48
|
+
* Метаданные тулза для клиента. `execute` не включается.
|
|
49
|
+
*/
|
|
50
|
+
serialize(): WebMcpToolConfig;
|
|
51
|
+
}
|
|
52
|
+
/** Функциональный вызов {@link WebMcpTool}. */
|
|
53
|
+
export declare function webMcpTool<TSchema extends z.ZodType | undefined = undefined>(init: WebMcpToolInit<TSchema>): WebMcpTool<TSchema>;
|
|
54
|
+
export declare function webMcpInputJsonSchema(schema: z.ZodType): Record<string, unknown>;
|
|
55
|
+
/** Проверяет input, вызывает execute и отвечает клиенту результатом или ошибкой. */
|
|
56
|
+
export declare function dispatchWebMcpToolCall(client: Client, tool: WebMcpTool, callId: string, input: unknown): Promise<void>;
|
|
57
|
+
export declare function webMcpToolErrorText(error: unknown): string;
|
|
@@ -0,0 +1,150 @@
|
|
|
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.WebMcpTool = exports.WebMcpToolAnnotation = void 0;
|
|
37
|
+
exports.webMcpTool = webMcpTool;
|
|
38
|
+
exports.webMcpInputJsonSchema = webMcpInputJsonSchema;
|
|
39
|
+
exports.dispatchWebMcpToolCall = dispatchWebMcpToolCall;
|
|
40
|
+
exports.webMcpToolErrorText = webMcpToolErrorText;
|
|
41
|
+
const web_mcp_tool_annotation_1 = require("@matreshka/shared/enums/web-mcp-tool-annotation");
|
|
42
|
+
Object.defineProperty(exports, "WebMcpToolAnnotation", { enumerable: true, get: function () { return web_mcp_tool_annotation_1.WebMcpToolAnnotation; } });
|
|
43
|
+
const web_mcp_tool_error_message_1 = require("@matreshka/shared/messages/bff-to-client/webmcp/web-mcp-tool-error-message");
|
|
44
|
+
const web_mcp_tool_result_message_1 = require("@matreshka/shared/messages/bff-to-client/webmcp/web-mcp-tool-result-message");
|
|
45
|
+
const crypto = __importStar(require("node:crypto"));
|
|
46
|
+
const zod_1 = require("zod");
|
|
47
|
+
const v4_1 = require("zod/v4");
|
|
48
|
+
const webMcpToolSchema = zod_1.z.object({
|
|
49
|
+
name: zod_1.z.string().trim().min(1),
|
|
50
|
+
description: zod_1.z.string().trim().min(1),
|
|
51
|
+
annotations: zod_1.z
|
|
52
|
+
.array(zod_1.z.custom(() => true))
|
|
53
|
+
.refine((items) => new Set(items).size === items.length, {
|
|
54
|
+
message: "Annotations must be unique",
|
|
55
|
+
})
|
|
56
|
+
.optional()
|
|
57
|
+
.default([]),
|
|
58
|
+
});
|
|
59
|
+
/**
|
|
60
|
+
* WebMCP-тулз entry или платформы.
|
|
61
|
+
* `webMcpTool({ ... })` и `new WebMcpTool({ ... })` создают один и тот же класс.
|
|
62
|
+
* id назначается при создании, автор его не задаёт.
|
|
63
|
+
* По `inputSchema` TypeScript выводит тип аргумента `execute`.
|
|
64
|
+
*
|
|
65
|
+
* Параметр схемы по умолчанию `any`, чтобы тулз с конкретной схемой
|
|
66
|
+
* можно было положить в `WebMcpTool[]`.
|
|
67
|
+
*/
|
|
68
|
+
class WebMcpTool {
|
|
69
|
+
constructor(init) {
|
|
70
|
+
const parsed = webMcpToolSchema.parse({
|
|
71
|
+
name: init.name,
|
|
72
|
+
description: init.description,
|
|
73
|
+
annotations: init.annotations,
|
|
74
|
+
});
|
|
75
|
+
this.id = crypto.randomUUID();
|
|
76
|
+
this.name = parsed.name;
|
|
77
|
+
this.description = parsed.description;
|
|
78
|
+
this.annotations = parsed.annotations;
|
|
79
|
+
this.execute = init.execute;
|
|
80
|
+
this.inputSchema = init.inputSchema;
|
|
81
|
+
this.conditions = resolveWebMcpToolConditions(init.conditions);
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Метаданные тулза для клиента. `execute` не включается.
|
|
85
|
+
*/
|
|
86
|
+
serialize() {
|
|
87
|
+
return {
|
|
88
|
+
id: this.id,
|
|
89
|
+
name: this.name,
|
|
90
|
+
description: this.description,
|
|
91
|
+
annotations: [...this.annotations],
|
|
92
|
+
...(this.inputSchema
|
|
93
|
+
? { inputSchema: webMcpInputJsonSchema(this.inputSchema) }
|
|
94
|
+
: {}),
|
|
95
|
+
...(this.conditions.length > 0 ? { conditions: this.conditions } : {}),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
exports.WebMcpTool = WebMcpTool;
|
|
100
|
+
/** Функциональный вызов {@link WebMcpTool}. */
|
|
101
|
+
function webMcpTool(init) {
|
|
102
|
+
return new WebMcpTool(init);
|
|
103
|
+
}
|
|
104
|
+
function resolveWebMcpToolConditions(conditions) {
|
|
105
|
+
const list = typeof conditions === "function" ? conditions() : (conditions ?? []);
|
|
106
|
+
return list.map((condition) => condition.toJSON());
|
|
107
|
+
}
|
|
108
|
+
function webMcpInputJsonSchema(schema) {
|
|
109
|
+
return v4_1.z.toJSONSchema(schema);
|
|
110
|
+
}
|
|
111
|
+
/** Проверяет input, вызывает execute и отвечает клиенту результатом или ошибкой. */
|
|
112
|
+
async function dispatchWebMcpToolCall(client, tool, callId, input) {
|
|
113
|
+
let parsedInput;
|
|
114
|
+
if (tool.inputSchema) {
|
|
115
|
+
const parsed = tool.inputSchema.safeParse(input);
|
|
116
|
+
if (!parsed.success) {
|
|
117
|
+
client.outcomingMessage$.next(new web_mcp_tool_error_message_1.WebMcpToolErrorMessage(tool.id, {
|
|
118
|
+
message: parsed.error.message,
|
|
119
|
+
callId,
|
|
120
|
+
}));
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
parsedInput = parsed.data;
|
|
124
|
+
}
|
|
125
|
+
try {
|
|
126
|
+
const result = tool.inputSchema
|
|
127
|
+
? await tool.execute(parsedInput)
|
|
128
|
+
: await tool.execute();
|
|
129
|
+
if (typeof result !== "string") {
|
|
130
|
+
client.outcomingMessage$.next(new web_mcp_tool_error_message_1.WebMcpToolErrorMessage(tool.id, {
|
|
131
|
+
message: "WebMCP tool execute must resolve to a string",
|
|
132
|
+
callId,
|
|
133
|
+
}));
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
client.outcomingMessage$.next(new web_mcp_tool_result_message_1.WebMcpToolResultMessage(tool.id, { result, callId }));
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
client.outcomingMessage$.next(new web_mcp_tool_error_message_1.WebMcpToolErrorMessage(tool.id, {
|
|
140
|
+
message: webMcpToolErrorText(error),
|
|
141
|
+
callId,
|
|
142
|
+
}));
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function webMcpToolErrorText(error) {
|
|
146
|
+
if (error instanceof Error) {
|
|
147
|
+
return error.message;
|
|
148
|
+
}
|
|
149
|
+
return String(error);
|
|
150
|
+
}
|
|
@@ -2,6 +2,7 @@ import type { PlatformEnumeratedDevice } from "@matreshka/shared/messages/client
|
|
|
2
2
|
import type { Observable } from "rxjs";
|
|
3
3
|
import { Dialog, Popover } from "../components";
|
|
4
4
|
import { Overlay } from "../components/types/container-overlay";
|
|
5
|
+
import { type WebMcpTool } from "../components/webmcp/web-mcp-tool";
|
|
5
6
|
import { Client, Componentable, ComponentInstance, ContextValueRef } from "../core";
|
|
6
7
|
import { type PopoverShowComponent, type PopoverShowPlacement } from "./popover-show";
|
|
7
8
|
import { type NavigateResult } from "./utils/client-navigate-platform-action";
|
|
@@ -12,6 +13,8 @@ export type { NavigateResult };
|
|
|
12
13
|
export declare abstract class Platform {
|
|
13
14
|
protected readonly client: Client;
|
|
14
15
|
private platformOverlays;
|
|
16
|
+
private platformTools;
|
|
17
|
+
private platformToolsSubscription?;
|
|
15
18
|
/**
|
|
16
19
|
* Активный клиент, связанный с платформой.
|
|
17
20
|
*/
|
|
@@ -57,6 +60,15 @@ export declare abstract class Platform {
|
|
|
57
60
|
showTimePicker(anchor: ComponentInstance | Componentable, ref: ContextValueRef<string | undefined>): Observable<void>;
|
|
58
61
|
showDateTimePicker(anchor: ComponentInstance | Componentable, ref: ContextValueRef<string | undefined>): Observable<void>;
|
|
59
62
|
private showNativePicker;
|
|
63
|
+
/**
|
|
64
|
+
* Задаёт платформенные WebMCP-тулзы. Новый список заменяет предыдущий.
|
|
65
|
+
* Пустой массив снимает глобальные тулзы. Тулзы страницы не затрагиваются.
|
|
66
|
+
* Вызов execute остаётся на BFF.
|
|
67
|
+
*/
|
|
68
|
+
setTools(tools: readonly WebMcpTool[]): Observable<void>;
|
|
69
|
+
/** Текущие платформенные WebMCP-тулзы. */
|
|
70
|
+
getTools(): readonly WebMcpTool[];
|
|
71
|
+
private ensurePlatformToolsListener;
|
|
60
72
|
/**
|
|
61
73
|
* Задаёт платформенные оверлеи (anchors + component). Вложенные компоненты участвуют в поиске на сервере;
|
|
62
74
|
* на клиент уходит массив конфигов, как у `properties.overlays` страницы.
|
|
@@ -8,10 +8,15 @@ const enable_privacy_mode_message_1 = require("@matreshka/shared/messages/bff-to
|
|
|
8
8
|
const platform_enumerate_devices_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/platform-enumerate-devices-message");
|
|
9
9
|
const platform_set_color_scheme_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/platform-set-color-scheme-message");
|
|
10
10
|
const platform_set_overlays_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/platform-set-overlays-message");
|
|
11
|
+
const platform_set_tools_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/platform-set-tools-message");
|
|
11
12
|
const platform_show_native_picker_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/platform-show-native-picker-message");
|
|
12
13
|
const platform_enumerate_devices_success_message_1 = require("@matreshka/shared/messages/client-to-bff/platforms/platform-enumerate-devices-success-message");
|
|
14
|
+
const web_mcp_tool_call_message_1 = require("@matreshka/shared/messages/client-to-bff/webmcp/web-mcp-tool-call-message");
|
|
15
|
+
const rxjs_1 = require("rxjs");
|
|
13
16
|
const v4_1 = require("zod/v4");
|
|
17
|
+
const web_mcp_tool_1 = require("../components/webmcp/web-mcp-tool");
|
|
14
18
|
const core_1 = require("../core");
|
|
19
|
+
const incoming_message_observer_1 = require("../core/utils/incoming-message-observer");
|
|
15
20
|
const popover_show_1 = require("./popover-show");
|
|
16
21
|
const client_back_platform_action_1 = require("./utils/client-back-platform-action");
|
|
17
22
|
const client_navigate_platform_action_1 = require("./utils/client-navigate-platform-action");
|
|
@@ -35,6 +40,7 @@ class Platform {
|
|
|
35
40
|
constructor(client) {
|
|
36
41
|
this.client = client;
|
|
37
42
|
this.platformOverlays = [];
|
|
43
|
+
this.platformTools = [];
|
|
38
44
|
}
|
|
39
45
|
/**
|
|
40
46
|
* Выполняет навигацию по указанному пути.
|
|
@@ -130,6 +136,45 @@ class Platform {
|
|
|
130
136
|
}),
|
|
131
137
|
});
|
|
132
138
|
}
|
|
139
|
+
/**
|
|
140
|
+
* Задаёт платформенные WebMCP-тулзы. Новый список заменяет предыдущий.
|
|
141
|
+
* Пустой массив снимает глобальные тулзы. Тулзы страницы не затрагиваются.
|
|
142
|
+
* Вызов execute остаётся на BFF.
|
|
143
|
+
*/
|
|
144
|
+
setTools(tools) {
|
|
145
|
+
this.platformTools = [...tools];
|
|
146
|
+
this.ensurePlatformToolsListener();
|
|
147
|
+
return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
|
|
148
|
+
outgoingMessage: (scope) => new platform_set_tools_message_1.PlatformSetToolsMessage(scope, {
|
|
149
|
+
tools: this.platformTools.map((tool) => tool.serialize()),
|
|
150
|
+
}),
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
/** Текущие платформенные WebMCP-тулзы. */
|
|
154
|
+
getTools() {
|
|
155
|
+
return this.platformTools;
|
|
156
|
+
}
|
|
157
|
+
ensurePlatformToolsListener() {
|
|
158
|
+
if (this.platformToolsSubscription) {
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const subscription = this.client.incomingMessage$
|
|
162
|
+
.pipe((0, rxjs_1.filter)((message) => message instanceof web_mcp_tool_call_message_1.WebMcpToolCallMessage))
|
|
163
|
+
.subscribe((0, incoming_message_observer_1.incomingMessageObserver)(this.client, (message) => {
|
|
164
|
+
const tool = this.platformTools.find((item) => item.id === message.target);
|
|
165
|
+
if (!tool) {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
void (0, web_mcp_tool_1.dispatchWebMcpToolCall)(this.client, tool, message.id, message.payload?.input).catch((error) => {
|
|
169
|
+
this.client.error$.next(error);
|
|
170
|
+
});
|
|
171
|
+
}));
|
|
172
|
+
this.platformToolsSubscription = subscription;
|
|
173
|
+
this.client.destroy$.subscribe(() => {
|
|
174
|
+
subscription.unsubscribe();
|
|
175
|
+
this.platformToolsSubscription = undefined;
|
|
176
|
+
});
|
|
177
|
+
}
|
|
133
178
|
/**
|
|
134
179
|
* Задаёт платформенные оверлеи (anchors + component). Вложенные компоненты участвуют в поиске на сервере;
|
|
135
180
|
* на клиент уходит массив конфигов, как у `properties.overlays` страницы.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@matreshka/bff",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.25.0",
|
|
4
4
|
"description": "Matreshka BFF: server-driven UI runtime — routing, pages, context, component DSL, and platform APIs",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
"vitest": "^4.1.0"
|
|
63
63
|
},
|
|
64
64
|
"dependencies": {
|
|
65
|
-
"@matreshka/shared": "^0.
|
|
65
|
+
"@matreshka/shared": "^0.23.0",
|
|
66
66
|
"@simplewebauthn/server": "^13.1.1",
|
|
67
67
|
"@simplewebauthn/types": "^12.0.0",
|
|
68
68
|
"fast-xml-parser": "^5.3.3",
|