@matreshka/bff 0.38.0 → 0.40.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 (31) hide show
  1. package/dist/components/file-picker.d.ts +37 -0
  2. package/dist/components/file-picker.js +78 -0
  3. package/dist/components/index.d.ts +1 -1
  4. package/dist/components/index.js +1 -1
  5. package/dist/components/inputs/input-component.d.ts +1 -1
  6. package/dist/core/actions/context-local-action-config.d.ts +13 -0
  7. package/dist/core/actions/context-local-action-config.js +7 -0
  8. package/dist/core/actions/dec-context-value.d.ts +7 -5
  9. package/dist/core/actions/dec-context-value.js +6 -2
  10. package/dist/core/actions/inc-context-value.d.ts +7 -5
  11. package/dist/core/actions/inc-context-value.js +6 -2
  12. package/dist/core/actions/set-context.d.ts +12 -4
  13. package/dist/core/actions/set-context.js +6 -1
  14. package/dist/core/actions/toggle-context-value.d.ts +7 -4
  15. package/dist/core/actions/toggle-context-value.js +6 -1
  16. package/dist/core/context/context-ref.d.ts +45 -11
  17. package/dist/core/context/context.d.ts +46 -10
  18. package/dist/core/types/context-value-ref.d.ts +23 -24
  19. package/dist/platforms/client-platform.d.ts +16 -0
  20. package/dist/platforms/client-platform.js +24 -0
  21. package/dist/platforms/index.d.ts +3 -0
  22. package/dist/platforms/index.js +3 -0
  23. package/dist/platforms/local-file.d.ts +54 -0
  24. package/dist/platforms/local-file.js +106 -0
  25. package/dist/platforms/media-stream-ref.d.ts +29 -0
  26. package/dist/platforms/media-stream-ref.js +78 -0
  27. package/dist/platforms/recording.d.ts +58 -0
  28. package/dist/platforms/recording.js +203 -0
  29. package/package.json +2 -2
  30. package/dist/components/file-upload-area.d.ts +0 -79
  31. package/dist/components/file-upload-area.js +0 -135
@@ -0,0 +1,203 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Recording = exports.MediaKind = void 0;
4
+ const media_kind_1 = require("@matreshka/client-bff-protocol/enums/media-kind");
5
+ Object.defineProperty(exports, "MediaKind", { enumerable: true, get: function () { return media_kind_1.MediaKind; } });
6
+ const recording_create_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/recording-create-message");
7
+ const recording_destroy_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/recording-destroy-message");
8
+ const recording_pause_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/recording-pause-message");
9
+ const recording_resume_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/recording-resume-message");
10
+ const recording_start_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/recording-start-message");
11
+ const recording_stop_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/platforms/recording-stop-message");
12
+ const recording_event_messages_1 = require("@matreshka/client-bff-protocol/messages/client-to-bff/platforms/recording-event-messages");
13
+ const recording_stop_success_message_1 = require("@matreshka/client-bff-protocol/messages/client-to-bff/platforms/recording-stop-success-message");
14
+ const rxjs_1 = require("rxjs");
15
+ const zod_1 = require("zod");
16
+ const server_action_1 = require("../components/actions/server-action");
17
+ const action_1 = require("../core/actions/action");
18
+ const local_action_1 = require("../core/actions/local-action");
19
+ const client_context_1 = require("../core/client-context");
20
+ const incoming_message_observer_1 = require("../core/utils/incoming-message-observer");
21
+ const local_file_1 = require("./local-file");
22
+ const targeted_client_platform_action_1 = require("./utils/targeted-client-platform-action");
23
+ function isRecordingIncomingEvent(message) {
24
+ return (message instanceof recording_event_messages_1.RecordingStartEventMessage ||
25
+ message instanceof recording_event_messages_1.RecordingPauseEventMessage ||
26
+ message instanceof recording_event_messages_1.RecordingResumeEventMessage ||
27
+ message instanceof recording_event_messages_1.RecordingStopEventMessage ||
28
+ message instanceof recording_event_messages_1.RecordingTimeUpdateEventMessage ||
29
+ message instanceof recording_event_messages_1.RecordingErrorEventMessage);
30
+ }
31
+ const recordingHandlersSchema = zod_1.z.array(zod_1.z.number().int().nonnegative());
32
+ const recordingProgressEventSchema = zod_1.z.strictObject({
33
+ duration: zod_1.z.number(),
34
+ handlers: recordingHandlersSchema,
35
+ });
36
+ const recordingErrorEventSchema = zod_1.z.strictObject({
37
+ message: zod_1.z.string(),
38
+ handlers: recordingHandlersSchema,
39
+ });
40
+ function recordingEventSchema(message) {
41
+ if (message instanceof recording_event_messages_1.RecordingErrorEventMessage) {
42
+ return recordingErrorEventSchema;
43
+ }
44
+ return recordingProgressEventSchema;
45
+ }
46
+ function recordingEventName(message) {
47
+ if (message instanceof recording_event_messages_1.RecordingStartEventMessage) {
48
+ return "start";
49
+ }
50
+ if (message instanceof recording_event_messages_1.RecordingPauseEventMessage) {
51
+ return "pause";
52
+ }
53
+ if (message instanceof recording_event_messages_1.RecordingResumeEventMessage) {
54
+ return "resume";
55
+ }
56
+ if (message instanceof recording_event_messages_1.RecordingStopEventMessage) {
57
+ return "stop";
58
+ }
59
+ if (message instanceof recording_event_messages_1.RecordingTimeUpdateEventMessage) {
60
+ return "timeupdate";
61
+ }
62
+ return "error";
63
+ }
64
+ const EVENT_FIELDS = {
65
+ onStart: "start",
66
+ onPause: "pause",
67
+ onResume: "resume",
68
+ onStop: "stop",
69
+ onError: "error",
70
+ onTimeUpdate: "timeupdate",
71
+ };
72
+ /**
73
+ * Сессия `MediaRecorder` на клиенте поверх одного или нескольких `MediaStreamRef`.
74
+ */
75
+ class Recording {
76
+ constructor(client, config) {
77
+ this.client = client;
78
+ this.id = "recording-" + crypto.randomUUID();
79
+ this.handlers = new Map();
80
+ this.ended = false;
81
+ const streams = Array.isArray(config.streams)
82
+ ? config.streams
83
+ : [config.streams];
84
+ if (streams.length === 0) {
85
+ throw new Error("Recording requires at least one MediaStreamRef");
86
+ }
87
+ this.streamIds = streams.map((stream) => stream.id);
88
+ this.mimeType = config.mimeType;
89
+ this.bindEvents(config);
90
+ }
91
+ start() {
92
+ return this.send((scope) => new recording_start_message_1.RecordingStartMessage(scope, { recordingId: this.id }));
93
+ }
94
+ pause() {
95
+ return this.send((scope) => new recording_pause_message_1.RecordingPauseMessage(scope, { recordingId: this.id }));
96
+ }
97
+ resume() {
98
+ return this.send((scope) => new recording_resume_message_1.RecordingResumeMessage(scope, { recordingId: this.id }));
99
+ }
100
+ stop() {
101
+ return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
102
+ outgoingMessage: (scope) => new recording_stop_message_1.RecordingStopMessage(scope, { recordingId: this.id }),
103
+ parseSuccess: (unsafeMessage) => {
104
+ if (!(unsafeMessage instanceof recording_stop_success_message_1.RecordingStopSuccessMessage)) {
105
+ return;
106
+ }
107
+ return new local_file_1.LocalFile(this.client, unsafeMessage.payload);
108
+ },
109
+ });
110
+ }
111
+ destroy() {
112
+ if (this.ended) {
113
+ return (0, rxjs_1.of)(undefined);
114
+ }
115
+ return this.send((scope) => new recording_destroy_message_1.RecordingDestroyMessage(scope, { recordingId: this.id })).pipe((0, rxjs_1.tap)(() => this.endSession()));
116
+ }
117
+ /** @internal */
118
+ open() {
119
+ return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
120
+ outgoingMessage: (scope) => (0, client_context_1.runWithClient)(this.client, () => new recording_create_message_1.RecordingCreateMessage(scope, {
121
+ recordingId: this.id,
122
+ streamIds: this.streamIds,
123
+ mimeType: this.mimeType,
124
+ interactions: this.serializeInteractions(),
125
+ })),
126
+ }).pipe((0, rxjs_1.tap)(() => this.startSession()));
127
+ }
128
+ send(outgoingMessage) {
129
+ return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
130
+ outgoingMessage,
131
+ });
132
+ }
133
+ bindEvents(config) {
134
+ Object.keys(EVENT_FIELDS).forEach((field) => {
135
+ const actions = config[field];
136
+ if (actions === undefined) {
137
+ return;
138
+ }
139
+ const list = (Array.isArray(actions) ? actions : [actions]).map((action) => this.parseAction(action));
140
+ this.handlers.set(EVENT_FIELDS[field], list);
141
+ });
142
+ }
143
+ parseAction(action) {
144
+ if (action instanceof local_action_1.LocalAction || action instanceof server_action_1.ServerAction) {
145
+ return action;
146
+ }
147
+ if (action instanceof action_1.Action) {
148
+ throw new Error("Recording events accept LocalAction, ServerAction, or a server function");
149
+ }
150
+ return new server_action_1.ServerAction(action);
151
+ }
152
+ serializeInteractions() {
153
+ const interactions = {};
154
+ this.handlers.forEach((actions, event) => {
155
+ interactions[event] = actions.map((action) => action.toJSON());
156
+ });
157
+ return interactions;
158
+ }
159
+ startSession() {
160
+ if (this.sessionSubscription || this.ended) {
161
+ return;
162
+ }
163
+ this.sessionSubscription = this.client.incomingMessage$
164
+ .pipe((0, rxjs_1.filter)((message) => isRecordingIncomingEvent(message) && message.target === this.id))
165
+ .subscribe((0, incoming_message_observer_1.incomingMessageObserver)(this.client, (message) => {
166
+ const parsed = recordingEventSchema(message).safeParse(message.payload);
167
+ if (!parsed.success) {
168
+ this.client.error$.next(`Invalid recording event payload: ${message.type}`);
169
+ return;
170
+ }
171
+ const { handlers, ...payload } = parsed.data;
172
+ this.emit(recordingEventName(message), payload, handlers);
173
+ }));
174
+ this.clientDestroySubscription = this.client.destroy$
175
+ .pipe((0, rxjs_1.take)(1))
176
+ .subscribe(() => this.endSession());
177
+ }
178
+ emit(event, payload, handlers) {
179
+ const actions = this.handlers.get(event);
180
+ if (!actions) {
181
+ return;
182
+ }
183
+ for (const index of handlers) {
184
+ const action = actions[index];
185
+ if (!(action instanceof server_action_1.ServerAction)) {
186
+ continue;
187
+ }
188
+ action.execute({
189
+ payload,
190
+ instance: { client: this.client },
191
+ });
192
+ }
193
+ }
194
+ endSession() {
195
+ if (this.ended) {
196
+ return;
197
+ }
198
+ this.ended = true;
199
+ this.sessionSubscription?.unsubscribe();
200
+ this.clientDestroySubscription?.unsubscribe();
201
+ }
202
+ }
203
+ exports.Recording = Recording;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@matreshka/bff",
3
- "version": "0.38.0",
3
+ "version": "0.40.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/client-bff-protocol": "^0.7.0",
65
+ "@matreshka/client-bff-protocol": "^0.8.0",
66
66
  "@matreshka/gateway-bff-protocol": "^0.1.0",
67
67
  "@matreshka/shared": "^0.26.0",
68
68
  "@simplewebauthn/server": "^13.1.1",
@@ -1,79 +0,0 @@
1
- import { ServerComponentClass } from "@matreshka/client-bff-protocol/enums/server-component-class";
2
- import type { FileUploadAreaConfig } from "@matreshka/client-bff-protocol/types/file-upload-area-config";
3
- import { Componentable, ComponentTreeNode, MixedWithCallbacksArray, StandaloneComponent } from "../core";
4
- import { Component, ComponentInitConfig, ComponentProperties } from "./component";
5
- /**
6
- * Свойства компонента загрузки файла.
7
- *
8
- * @property upload Конфигурация загрузки.
9
- * @property multiple Можно ли загружать несколько файлов.
10
- * @property label Метка для поля загрузки.
11
- * @property url Ссылка для загрузки файлов (POST запрос).
12
- * @property accept MIME типы файлов, а также расширения файлов, которые можно загружать.
13
- */
14
- export type FileUploadAreaProperties = {
15
- multiple: boolean;
16
- content: ComponentTreeNode[];
17
- url: string;
18
- accept?: string;
19
- } & ComponentProperties;
20
- /**
21
- * Конфигурация инициализации компонента загрузки файла.
22
- *
23
- * @property upload Настройки загрузки
24
- */
25
- export type FileUploadAreaInitConfig<ComponentType extends Componentable = FileUploadArea, PropertiesType extends FileUploadAreaProperties = FileUploadAreaProperties> = {
26
- multiple: boolean;
27
- content: MixedWithCallbacksArray<ComponentTreeNode>;
28
- url: string;
29
- errorKey?: string;
30
- accept?: string;
31
- onStart?: (file: FileInfo) => void;
32
- onComplete?: (config: {
33
- file: FileInfo;
34
- response: unknown;
35
- }) => void;
36
- onError?: (config: {
37
- file: FileInfo;
38
- response: unknown;
39
- code: number;
40
- }) => void;
41
- onProgress?: (config: {
42
- file: FileInfo;
43
- progress: number;
44
- }) => void;
45
- } & ComponentInitConfig<ComponentType, PropertiesType>;
46
- type DefaultInitConfigType = FileUploadAreaInitConfig<FileUploadArea>;
47
- export declare function fileUploadArea(options: Omit<DefaultInitConfigType, "content">, content: DefaultInitConfigType["content"]): FileUploadArea;
48
- export declare function fileUploadArea(config: DefaultInitConfigType): FileUploadArea;
49
- export type FileInfo = {
50
- id: string;
51
- type: string;
52
- size: number;
53
- name: string;
54
- lastModified: number;
55
- url: string;
56
- };
57
- /**
58
- * Компонент загрузки файлов.
59
- */
60
- export declare class FileUploadArea<InitConfigType extends FileUploadAreaInitConfig<any> = DefaultInitConfigType, PropertiesType extends FileUploadAreaProperties = FileUploadAreaProperties> extends Component<InitConfigType, PropertiesType> implements StandaloneComponent {
61
- private uploadMap;
62
- constructor(config: InitConfigType);
63
- standalone(): true;
64
- /**
65
- * Возвращает уникальный идентификатор класса компонента.
66
- * @returns Строка "file-upload-area".
67
- */
68
- protected class(): ServerComponentClass;
69
- /**
70
- * Инициализирует свойства компонента загрузки.
71
- *
72
- * @param initValues Конфигурация инициализации компонента.
73
- * @returns Объект свойств компонента.
74
- */
75
- protected initProperties(initValues: InitConfigType): PropertiesType;
76
- protected serializeRuleOverrides(overrides: Partial<PropertiesType>): Record<string, unknown>;
77
- serialize(): FileUploadAreaConfig;
78
- }
79
- export {};
@@ -1,135 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FileUploadArea = void 0;
4
- exports.fileUploadArea = fileUploadArea;
5
- const server_component_class_1 = require("@matreshka/client-bff-protocol/enums/server-component-class");
6
- const zod_1 = require("zod");
7
- const core_1 = require("../core");
8
- const component_1 = require("./component");
9
- function fileUploadArea(arg0, arg1) {
10
- if (arg1 !== undefined) {
11
- return new FileUploadArea({
12
- ...arg0,
13
- content: arg1,
14
- });
15
- }
16
- return new FileUploadArea(arg0);
17
- }
18
- /**
19
- * Компонент загрузки файлов.
20
- */
21
- class FileUploadArea extends component_1.Component {
22
- constructor(config) {
23
- super(config);
24
- this.uploadMap = new Map();
25
- this.onInteraction("start", ({ payload }) => {
26
- const schema = zod_1.z.strictObject({
27
- id: zod_1.z.string(),
28
- type: zod_1.z.string(),
29
- size: zod_1.z.number(),
30
- name: zod_1.z.string(),
31
- lastModified: zod_1.z.number(),
32
- url: zod_1.z.string().refine((val) => val.startsWith("blob:"), {
33
- message: "url must be a blob",
34
- }),
35
- });
36
- const safePayload = schema.parse(payload);
37
- this.uploadMap.set(safePayload.id, safePayload);
38
- this.config.onStart?.(safePayload);
39
- });
40
- this.onInteraction("progress", ({ payload }) => {
41
- const schema = zod_1.z
42
- .strictObject({
43
- id: zod_1.z.string(),
44
- progress: zod_1.z.number().min(0).max(100),
45
- })
46
- .refine((data) => this.uploadMap.has(data.id), {
47
- message: "Unknown upload id",
48
- path: ["id"],
49
- });
50
- const safePayload = schema.parse(payload);
51
- this.config.onProgress?.({
52
- file: this.uploadMap.get(safePayload.id),
53
- progress: safePayload.progress,
54
- });
55
- });
56
- this.onInteraction("complete", ({ payload }) => {
57
- const schema = zod_1.z
58
- .strictObject({
59
- id: zod_1.z.string(),
60
- response: zod_1.z.unknown(),
61
- })
62
- .refine((data) => this.uploadMap.has(data.id), {
63
- message: "Unknown upload id",
64
- path: ["id"],
65
- });
66
- const safePayload = schema.parse(payload);
67
- this.config.onComplete?.({
68
- file: this.uploadMap.get(safePayload.id),
69
- response: safePayload.response,
70
- });
71
- });
72
- this.onInteraction("error", ({ payload }) => {
73
- const schema = zod_1.z
74
- .strictObject({
75
- id: zod_1.z.string(),
76
- response: zod_1.z.unknown(),
77
- code: zod_1.z.number(), // Не StatusCode, потому что может быть 0, который не содержится в словаре
78
- })
79
- .refine((data) => this.uploadMap.has(data.id), {
80
- message: "Unknown upload id",
81
- path: ["id"],
82
- });
83
- const safePayload = schema.parse(payload);
84
- this.config.onError?.({
85
- file: this.uploadMap.get(safePayload.id),
86
- response: safePayload.response,
87
- code: safePayload.code,
88
- });
89
- this.uploadMap.delete(safePayload.id);
90
- });
91
- }
92
- standalone() {
93
- return true;
94
- }
95
- /**
96
- * Возвращает уникальный идентификатор класса компонента.
97
- * @returns Строка "file-upload-area".
98
- */
99
- class() {
100
- return server_component_class_1.ServerComponentClass.FileUploadArea;
101
- }
102
- /**
103
- * Инициализирует свойства компонента загрузки.
104
- *
105
- * @param initValues Конфигурация инициализации компонента.
106
- * @returns Объект свойств компонента.
107
- */
108
- initProperties(initValues) {
109
- return {
110
- ...super.initProperties(initValues),
111
- content: (0, core_1.calculateComponents)(initValues.content),
112
- url: initValues.url,
113
- accept: initValues.accept,
114
- multiple: initValues.multiple,
115
- };
116
- }
117
- serializeRuleOverrides(overrides) {
118
- const out = super.serializeRuleOverrides(overrides);
119
- if (overrides.content !== undefined) {
120
- out.content = (0, core_1.serializeComponentList)(overrides.content);
121
- }
122
- return out;
123
- }
124
- serialize() {
125
- const result = super.serialize();
126
- return {
127
- ...result,
128
- class: server_component_class_1.ServerComponentClass.FileUploadArea,
129
- properties: this.buildPropertiesForClient({
130
- content: (0, core_1.serializeComponentList)(this.properties.content),
131
- }),
132
- };
133
- }
134
- }
135
- exports.FileUploadArea = FileUploadArea;