@matreshka/bff 0.9.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/LICENSE +32 -0
- package/README.md +35 -0
- package/dist/components/actions/server-action.d.ts +30 -0
- package/dist/components/actions/server-action.js +23 -0
- package/dist/components/aliases/button.d.ts +17 -0
- package/dist/components/aliases/button.js +54 -0
- package/dist/components/aliases/column.d.ts +11 -0
- package/dist/components/aliases/column.js +31 -0
- package/dist/components/aliases/row.d.ts +11 -0
- package/dist/components/aliases/row.js +31 -0
- package/dist/components/aliases/surface.d.ts +11 -0
- package/dist/components/aliases/surface.js +30 -0
- package/dist/components/app.d.ts +5 -0
- package/dist/components/app.js +12 -0
- package/dist/components/board.d.ts +58 -0
- package/dist/components/board.js +152 -0
- package/dist/components/boot.d.ts +2 -0
- package/dist/components/boot.js +39 -0
- package/dist/components/camera.d.ts +77 -0
- package/dist/components/camera.js +116 -0
- package/dist/components/charts/bar-chart.d.ts +14 -0
- package/dist/components/charts/bar-chart.js +27 -0
- package/dist/components/charts/chart.d.ts +69 -0
- package/dist/components/charts/chart.js +42 -0
- package/dist/components/charts/doughnut-chart.d.ts +14 -0
- package/dist/components/charts/doughnut-chart.js +27 -0
- package/dist/components/charts/line-chart.d.ts +14 -0
- package/dist/components/charts/line-chart.js +27 -0
- package/dist/components/charts/pie-chart.d.ts +14 -0
- package/dist/components/charts/pie-chart.js +27 -0
- package/dist/components/charts/polar-area-chart.d.ts +14 -0
- package/dist/components/charts/polar-area-chart.js +27 -0
- package/dist/components/charts/radar-chart.d.ts +14 -0
- package/dist/components/charts/radar-chart.js +27 -0
- package/dist/components/component.d.ts +159 -0
- package/dist/components/component.js +380 -0
- package/dist/components/container.d.ts +48 -0
- package/dist/components/container.js +80 -0
- package/dist/components/dialog.d.ts +83 -0
- package/dist/components/dialog.js +120 -0
- package/dist/components/entry-component.d.ts +34 -0
- package/dist/components/entry-component.js +74 -0
- package/dist/components/enum/password-input-kind.d.ts +1 -0
- package/dist/components/enum/password-input-kind.js +5 -0
- package/dist/components/enum/popover-position-area.d.ts +1 -0
- package/dist/components/enum/popover-position-area.js +5 -0
- package/dist/components/enum/text-input-kind.d.ts +1 -0
- package/dist/components/enum/text-input-kind.js +5 -0
- package/dist/components/enum/textarea-resize.d.ts +1 -0
- package/dist/components/enum/textarea-resize.js +5 -0
- package/dist/components/file-upload-area.d.ts +79 -0
- package/dist/components/file-upload-area.js +138 -0
- package/dist/components/for-each.d.ts +188 -0
- package/dist/components/for-each.js +362 -0
- package/dist/components/form.d.ts +62 -0
- package/dist/components/form.js +92 -0
- package/dist/components/grid.d.ts +80 -0
- package/dist/components/grid.js +79 -0
- package/dist/components/index.d.ts +55 -0
- package/dist/components/index.js +76 -0
- package/dist/components/inputs/input-component.d.ts +37 -0
- package/dist/components/inputs/input-component.js +30 -0
- package/dist/components/inputs/number-input.d.ts +45 -0
- package/dist/components/inputs/number-input.js +43 -0
- package/dist/components/inputs/password-input.d.ts +28 -0
- package/dist/components/inputs/password-input.js +42 -0
- package/dist/components/inputs/text-editor.d.ts +91 -0
- package/dist/components/inputs/text-editor.js +282 -0
- package/dist/components/inputs/text-input.d.ts +48 -0
- package/dist/components/inputs/text-input.js +40 -0
- package/dist/components/inputs/textarea.d.ts +36 -0
- package/dist/components/inputs/textarea.js +42 -0
- package/dist/components/item-list/flatten-nested-items.d.ts +11 -0
- package/dist/components/item-list/flatten-nested-items.js +100 -0
- package/dist/components/item-list/index.d.ts +5 -0
- package/dist/components/item-list/index.js +21 -0
- package/dist/components/item-list/item-list-host.d.ts +10 -0
- package/dist/components/item-list/item-list-host.js +2 -0
- package/dist/components/item-list/item-list.d.ts +68 -0
- package/dist/components/item-list/item-list.js +206 -0
- package/dist/components/item-list/list-from-ref-context.d.ts +11 -0
- package/dist/components/item-list/list-from-ref-context.js +27 -0
- package/dist/components/item-list/nested-items-host-support.d.ts +36 -0
- package/dist/components/item-list/nested-items-host-support.js +109 -0
- package/dist/components/item-list/types.d.ts +40 -0
- package/dist/components/item-list/types.js +13 -0
- package/dist/components/line.d.ts +43 -0
- package/dist/components/line.js +35 -0
- package/dist/components/map.d.ts +83 -0
- package/dist/components/map.js +146 -0
- package/dist/components/outputs/currency.d.ts +63 -0
- package/dist/components/outputs/currency.js +42 -0
- package/dist/components/outputs/datetime.d.ts +69 -0
- package/dist/components/outputs/datetime.js +49 -0
- package/dist/components/outputs/icon.d.ts +43 -0
- package/dist/components/outputs/icon.js +38 -0
- package/dist/components/outputs/iframe.d.ts +48 -0
- package/dist/components/outputs/iframe.js +44 -0
- package/dist/components/outputs/image.d.ts +73 -0
- package/dist/components/outputs/image.js +63 -0
- package/dist/components/outputs/number.d.ts +39 -0
- package/dist/components/outputs/number.js +47 -0
- package/dist/components/outputs/output-component.d.ts +58 -0
- package/dist/components/outputs/output-component.js +50 -0
- package/dist/components/outputs/progress-bar.d.ts +33 -0
- package/dist/components/outputs/progress-bar.js +42 -0
- package/dist/components/outputs/progress-spinner.d.ts +37 -0
- package/dist/components/outputs/progress-spinner.js +43 -0
- package/dist/components/outputs/qr-code.d.ts +28 -0
- package/dist/components/outputs/qr-code.js +40 -0
- package/dist/components/outputs/text.d.ts +57 -0
- package/dist/components/outputs/text.js +78 -0
- package/dist/components/outputs/vector.d.ts +47 -0
- package/dist/components/outputs/vector.js +53 -0
- package/dist/components/page.d.ts +96 -0
- package/dist/components/page.js +127 -0
- package/dist/components/popover.d.ts +63 -0
- package/dist/components/popover.js +96 -0
- package/dist/components/stack.d.ts +158 -0
- package/dist/components/stack.js +146 -0
- package/dist/components/types/component-sequence.d.ts +3 -0
- package/dist/components/types/component-sequence.js +2 -0
- package/dist/components/types/container-overlay.d.ts +3 -0
- package/dist/components/types/container-overlay.js +2 -0
- package/dist/components/utils/component-factory-shared.d.ts +4 -0
- package/dist/components/utils/component-factory-shared.js +12 -0
- package/dist/core/actions/action.d.ts +35 -0
- package/dist/core/actions/action.js +45 -0
- package/dist/core/actions/animate-component.d.ts +58 -0
- package/dist/core/actions/animate-component.js +57 -0
- package/dist/core/actions/local-action.d.ts +8 -0
- package/dist/core/actions/local-action.js +12 -0
- package/dist/core/actions/set-context-value.d.ts +18 -0
- package/dist/core/actions/set-context-value.js +32 -0
- package/dist/core/actions/set-context-values.d.ts +34 -0
- package/dist/core/actions/set-context-values.js +30 -0
- package/dist/core/actions/toggle-context-value.d.ts +21 -0
- package/dist/core/actions/toggle-context-value.js +30 -0
- package/dist/core/actions/write-text-to-clipboard.d.ts +30 -0
- package/dist/core/actions/write-text-to-clipboard.js +44 -0
- package/dist/core/boot.d.ts +2 -0
- package/dist/core/boot.js +8 -0
- package/dist/core/client-context.d.ts +7 -0
- package/dist/core/client-context.js +20 -0
- package/dist/core/client.d.ts +133 -0
- package/dist/core/client.js +292 -0
- package/dist/core/conditions/condition-group.d.ts +14 -0
- package/dist/core/conditions/condition-group.js +30 -0
- package/dist/core/conditions/condition-operand.d.ts +27 -0
- package/dist/core/conditions/condition-operand.js +15 -0
- package/dist/core/conditions/condition.d.ts +27 -0
- package/dist/core/conditions/condition.js +35 -0
- package/dist/core/conditions/context-array-includes.d.ts +32 -0
- package/dist/core/conditions/context-array-includes.js +52 -0
- package/dist/core/conditions/context-array-length.d.ts +86 -0
- package/dist/core/conditions/context-array-length.js +155 -0
- package/dist/core/conditions/context-value-defined.d.ts +12 -0
- package/dist/core/conditions/context-value-defined.js +21 -0
- package/dist/core/conditions/context-value-equal.d.ts +14 -0
- package/dist/core/conditions/context-value-equal.js +26 -0
- package/dist/core/conditions/context-value-in.d.ts +17 -0
- package/dist/core/conditions/context-value-in.js +26 -0
- package/dist/core/conditions/context-value-not-equal.d.ts +14 -0
- package/dist/core/conditions/context-value-not-equal.js +26 -0
- package/dist/core/conditions/context-value-undefined.d.ts +12 -0
- package/dist/core/conditions/context-value-undefined.js +21 -0
- package/dist/core/conditions/desktop-device.d.ts +11 -0
- package/dist/core/conditions/desktop-device.js +21 -0
- package/dist/core/conditions/groups.d.ts +71 -0
- package/dist/core/conditions/groups.js +74 -0
- package/dist/core/conditions/index.d.ts +17 -0
- package/dist/core/conditions/index.js +33 -0
- package/dist/core/conditions/mobile-device.d.ts +11 -0
- package/dist/core/conditions/mobile-device.js +21 -0
- package/dist/core/conditions/not-desktop-device.d.ts +11 -0
- package/dist/core/conditions/not-desktop-device.js +21 -0
- package/dist/core/conditions/not-mobile-device.d.ts +11 -0
- package/dist/core/conditions/not-mobile-device.js +21 -0
- package/dist/core/conditions/not-tablet-device.d.ts +11 -0
- package/dist/core/conditions/not-tablet-device.js +21 -0
- package/dist/core/conditions/tablet-device.d.ts +11 -0
- package/dist/core/conditions/tablet-device.js +21 -0
- package/dist/core/context/context-ref.d.ts +48 -0
- package/dist/core/context/context-ref.js +58 -0
- package/dist/core/context/context.d.ts +121 -0
- package/dist/core/context/context.js +353 -0
- package/dist/core/entry-context.d.ts +14 -0
- package/dist/core/entry-context.js +31 -0
- package/dist/core/gateway-connection.d.ts +29 -0
- package/dist/core/gateway-connection.js +146 -0
- package/dist/core/index.d.ts +30 -0
- package/dist/core/index.js +46 -0
- package/dist/core/matreshka.d.ts +61 -0
- package/dist/core/matreshka.js +186 -0
- package/dist/core/router.d.ts +38 -0
- package/dist/core/router.js +116 -0
- package/dist/core/types/client-settings.d.ts +31 -0
- package/dist/core/types/client-settings.js +2 -0
- package/dist/core/types/component-instance.d.ts +25 -0
- package/dist/core/types/component-instance.js +42 -0
- package/dist/core/types/component-tree-node.d.ts +11 -0
- package/dist/core/types/component-tree-node.js +18 -0
- package/dist/core/types/componentable.d.ts +21 -0
- package/dist/core/types/componentable.js +2 -0
- package/dist/core/types/context-ref-primitive-value.d.ts +5 -0
- package/dist/core/types/context-ref-primitive-value.js +2 -0
- package/dist/core/types/message.d.ts +15 -0
- package/dist/core/types/message.js +2 -0
- package/dist/core/types/mixed-with-callbacks-array.d.ts +9 -0
- package/dist/core/types/mixed-with-callbacks-array.js +2 -0
- package/dist/core/types/native-picker-context-ref.d.ts +7 -0
- package/dist/core/types/native-picker-context-ref.js +2 -0
- package/dist/core/types/pageable.d.ts +15 -0
- package/dist/core/types/pageable.js +2 -0
- package/dist/core/types/standalone-component.d.ts +9 -0
- package/dist/core/types/standalone-component.js +2 -0
- package/dist/core/types/status-code.d.ts +319 -0
- package/dist/core/types/status-code.js +322 -0
- package/dist/core/utils/calculate-components.d.ts +13 -0
- package/dist/core/utils/calculate-components.js +40 -0
- package/dist/core/utils/color-token-id.d.ts +11 -0
- package/dist/core/utils/color-token-id.js +24 -0
- package/dist/core/utils/deep-pick.d.ts +2 -0
- package/dist/core/utils/deep-pick.js +54 -0
- package/dist/core/utils/hex-to-hsl.d.ts +14 -0
- package/dist/core/utils/hex-to-hsl.js +49 -0
- package/dist/core/utils/incoming-message-observer.d.ts +9 -0
- package/dist/core/utils/incoming-message-observer.js +23 -0
- package/dist/core/utils/merge-deep.d.ts +8 -0
- package/dist/core/utils/merge-deep.js +39 -0
- package/dist/core/utils/objects-diff.d.ts +13 -0
- package/dist/core/utils/objects-diff.js +56 -0
- package/dist/core/utils/parse-context-path.d.ts +4 -0
- package/dist/core/utils/parse-context-path.js +16 -0
- package/dist/core/utils/replace-context-keys.d.ts +12 -0
- package/dist/core/utils/replace-context-keys.js +90 -0
- package/dist/core/utils/serialize-component-tree.d.ts +9 -0
- package/dist/core/utils/serialize-component-tree.js +24 -0
- package/dist/core/utils/set-object-property.d.ts +2 -0
- package/dist/core/utils/set-object-property.js +29 -0
- package/dist/core/utils/track-created-instances.d.ts +10 -0
- package/dist/core/utils/track-created-instances.js +18 -0
- package/dist/core/version.d.ts +1 -0
- package/dist/core/version.js +21 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +19 -0
- package/dist/platforms/android-platform.d.ts +6 -0
- package/dist/platforms/android-platform.js +10 -0
- package/dist/platforms/browser-platform.d.ts +79 -0
- package/dist/platforms/browser-platform.js +143 -0
- package/dist/platforms/client-platform.d.ts +6 -0
- package/dist/platforms/client-platform.js +10 -0
- package/dist/platforms/index.d.ts +12 -0
- package/dist/platforms/index.js +28 -0
- package/dist/platforms/ios-platform.d.ts +6 -0
- package/dist/platforms/ios-platform.js +10 -0
- package/dist/platforms/max-mini-app-platform.d.ts +45 -0
- package/dist/platforms/max-mini-app-platform.js +87 -0
- package/dist/platforms/mobile-platform.d.ts +117 -0
- package/dist/platforms/mobile-platform.js +316 -0
- package/dist/platforms/platform.d.ts +109 -0
- package/dist/platforms/platform.js +224 -0
- package/dist/platforms/pwa-platform.d.ts +6 -0
- package/dist/platforms/pwa-platform.js +10 -0
- package/dist/platforms/server-platform.d.ts +6 -0
- package/dist/platforms/server-platform.js +10 -0
- package/dist/platforms/telegram-mini-app-platform.d.ts +87 -0
- package/dist/platforms/telegram-mini-app-platform.js +166 -0
- package/dist/platforms/utils/client-platform.d.ts +4 -0
- package/dist/platforms/utils/client-platform.js +38 -0
- package/dist/platforms/utils/mobile-ble-services.d.ts +3 -0
- package/dist/platforms/utils/mobile-ble-services.js +31 -0
- package/dist/platforms/web-platform.d.ts +9 -0
- package/dist/platforms/web-platform.js +13 -0
- package/package.json +109 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.GatewayConnection = void 0;
|
|
7
|
+
exports.buildGatewayWebSocketUrl = buildGatewayWebSocketUrl;
|
|
8
|
+
const bff_message_1 = require("@matreshka/shared/messages/bff-to-gateway/bff-message");
|
|
9
|
+
const client_message_1 = require("@matreshka/shared/messages/gateway-to-bff/client-message");
|
|
10
|
+
const connected_message_1 = require("@matreshka/shared/messages/gateway-to-bff/connected-message");
|
|
11
|
+
const error_message_1 = require("@matreshka/shared/messages/gateway-to-bff/error-message");
|
|
12
|
+
const parse_gateway_to_bff_message_1 = require("@matreshka/shared/messages/gateway-to-bff/parse-gateway-to-bff-message");
|
|
13
|
+
const session_close_message_1 = require("@matreshka/shared/messages/gateway-to-bff/session-close-message");
|
|
14
|
+
const session_open_message_1 = require("@matreshka/shared/messages/gateway-to-bff/session-open-message");
|
|
15
|
+
const register_gateway_messages_1 = require("@matreshka/shared/messages/register-gateway-messages");
|
|
16
|
+
const rxjs_1 = require("rxjs");
|
|
17
|
+
const ws_1 = __importDefault(require("ws"));
|
|
18
|
+
const version_1 = require("./version");
|
|
19
|
+
/** WebSocket-подключение BFF к gateway. */
|
|
20
|
+
class GatewayConnection {
|
|
21
|
+
constructor(matreshka, input) {
|
|
22
|
+
this.matreshka = matreshka;
|
|
23
|
+
this.sessions = new Map();
|
|
24
|
+
this.subscriptions = [];
|
|
25
|
+
this.closed = false;
|
|
26
|
+
this.connected$ = new rxjs_1.Subject();
|
|
27
|
+
this.disconnected$ = new rxjs_1.Subject();
|
|
28
|
+
this.error$ = new rxjs_1.Subject();
|
|
29
|
+
(0, register_gateway_messages_1.registerGatewayMessages)();
|
|
30
|
+
this.resolveClientSettings = input.resolveClientSettings;
|
|
31
|
+
this.socket = new ws_1.default(buildGatewayWebSocketUrl(input.url, input.token));
|
|
32
|
+
this.bindSocketEvents();
|
|
33
|
+
}
|
|
34
|
+
disconnect() {
|
|
35
|
+
if (this.closed) {
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
this.closed = true;
|
|
39
|
+
this.socket.close();
|
|
40
|
+
}
|
|
41
|
+
bindSocketEvents() {
|
|
42
|
+
this.socket.on("open", () => {
|
|
43
|
+
// Ждём ConnectedMessage от gateway.
|
|
44
|
+
});
|
|
45
|
+
this.socket.on("message", (data) => {
|
|
46
|
+
try {
|
|
47
|
+
this.handleGatewayMessage(data.toString());
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
this.error$.next(error);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
this.socket.on("error", (error) => {
|
|
54
|
+
this.error$.next(error);
|
|
55
|
+
});
|
|
56
|
+
this.socket.on("close", () => {
|
|
57
|
+
this.closeAllSessions();
|
|
58
|
+
this.unsubscribeAll();
|
|
59
|
+
this.disconnected$.next();
|
|
60
|
+
this.disconnected$.complete();
|
|
61
|
+
this.connected$.complete();
|
|
62
|
+
this.error$.complete();
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
handleGatewayMessage(raw) {
|
|
66
|
+
const message = (0, parse_gateway_to_bff_message_1.parseGatewayToBffMessage)(JSON.parse(raw));
|
|
67
|
+
if (message instanceof connected_message_1.ConnectedMessage) {
|
|
68
|
+
this.connected$.next();
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
if (message instanceof error_message_1.ErrorMessage) {
|
|
72
|
+
this.error$.next(new Error(message.payload.message));
|
|
73
|
+
this.disconnect();
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (message instanceof session_open_message_1.SessionOpenMessage) {
|
|
77
|
+
this.openSession(message);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (message instanceof client_message_1.ClientMessage) {
|
|
81
|
+
this.sessions
|
|
82
|
+
.get(message.payload.sessionId)
|
|
83
|
+
?.newMessage(message.payload.message);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (message instanceof session_close_message_1.SessionCloseMessage) {
|
|
87
|
+
this.closeSession(message.payload.sessionId);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
openSession(message) {
|
|
91
|
+
const { sessionId, reconnectToken } = message.payload;
|
|
92
|
+
const params = new URLSearchParams();
|
|
93
|
+
if (reconnectToken) {
|
|
94
|
+
params.set("token", reconnectToken);
|
|
95
|
+
}
|
|
96
|
+
const client = this.matreshka.getClient(params);
|
|
97
|
+
const errorSubscription = client.error$.subscribe((error) => {
|
|
98
|
+
this.error$.next(error);
|
|
99
|
+
});
|
|
100
|
+
client.attachTransport((outgoing) => {
|
|
101
|
+
this.sendToGateway(new bff_message_1.BffMessage({
|
|
102
|
+
sessionId,
|
|
103
|
+
message: JSON.stringify(outgoing.toJSON()),
|
|
104
|
+
}));
|
|
105
|
+
});
|
|
106
|
+
this.sessions.set(sessionId, client);
|
|
107
|
+
this.subscriptions.push(errorSubscription);
|
|
108
|
+
this.matreshka.initClient(client, params, this.resolveClientSettings);
|
|
109
|
+
}
|
|
110
|
+
closeSession(sessionId) {
|
|
111
|
+
const client = this.sessions.get(sessionId);
|
|
112
|
+
if (!client) {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
client.detachTransport();
|
|
116
|
+
this.matreshka.clientDisconnect$.next(client);
|
|
117
|
+
this.sessions.delete(sessionId);
|
|
118
|
+
}
|
|
119
|
+
closeAllSessions() {
|
|
120
|
+
for (const sessionId of [...this.sessions.keys()]) {
|
|
121
|
+
this.closeSession(sessionId);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
sendToGateway(message) {
|
|
125
|
+
if (this.socket.readyState !== ws_1.default.OPEN) {
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
this.socket.send(JSON.stringify(message.toJSON()));
|
|
129
|
+
}
|
|
130
|
+
unsubscribeAll() {
|
|
131
|
+
for (const subscription of this.subscriptions) {
|
|
132
|
+
subscription.unsubscribe();
|
|
133
|
+
}
|
|
134
|
+
this.subscriptions.length = 0;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
exports.GatewayConnection = GatewayConnection;
|
|
138
|
+
function buildGatewayWebSocketUrl(serverUrl, token) {
|
|
139
|
+
const url = new URL(serverUrl);
|
|
140
|
+
if (url.pathname === "/" || url.pathname === "") {
|
|
141
|
+
url.pathname = "/bff";
|
|
142
|
+
}
|
|
143
|
+
url.searchParams.set("token", token);
|
|
144
|
+
url.searchParams.set("version", version_1.version);
|
|
145
|
+
return url.toString();
|
|
146
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export * from "./actions/action";
|
|
2
|
+
export * from "./actions/animate-component";
|
|
3
|
+
export * from "./actions/local-action";
|
|
4
|
+
export * from "./actions/set-context-value";
|
|
5
|
+
export * from "./actions/set-context-values";
|
|
6
|
+
export * from "./actions/toggle-context-value";
|
|
7
|
+
export * from "./actions/write-text-to-clipboard";
|
|
8
|
+
export * from "./boot";
|
|
9
|
+
export * from "./client";
|
|
10
|
+
export * from "./client-context";
|
|
11
|
+
export * from "./entry-context";
|
|
12
|
+
export * from "./gateway-connection";
|
|
13
|
+
export * from "./matreshka";
|
|
14
|
+
export * from "./conditions";
|
|
15
|
+
export * from "./context/context";
|
|
16
|
+
export * from "./context/context-ref";
|
|
17
|
+
export * from "./utils/calculate-components";
|
|
18
|
+
export * from "./utils/color-token-id";
|
|
19
|
+
export * from "./utils/serialize-component-tree";
|
|
20
|
+
export * from "@matreshka/shared/types/json";
|
|
21
|
+
export * from "./types/component-instance";
|
|
22
|
+
export * from "./types/component-tree-node";
|
|
23
|
+
export * from "./types/componentable";
|
|
24
|
+
export * from "./types/message";
|
|
25
|
+
export * from "./types/mixed-with-callbacks-array";
|
|
26
|
+
export * from "./types/native-picker-context-ref";
|
|
27
|
+
export * from "./types/pageable";
|
|
28
|
+
export * from "./types/standalone-component";
|
|
29
|
+
export * from "./types/status-code";
|
|
30
|
+
export * from "./version";
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./actions/action"), exports);
|
|
18
|
+
__exportStar(require("./actions/animate-component"), exports);
|
|
19
|
+
__exportStar(require("./actions/local-action"), exports);
|
|
20
|
+
__exportStar(require("./actions/set-context-value"), exports);
|
|
21
|
+
__exportStar(require("./actions/set-context-values"), exports);
|
|
22
|
+
__exportStar(require("./actions/toggle-context-value"), exports);
|
|
23
|
+
__exportStar(require("./actions/write-text-to-clipboard"), exports);
|
|
24
|
+
__exportStar(require("./boot"), exports);
|
|
25
|
+
__exportStar(require("./client"), exports);
|
|
26
|
+
__exportStar(require("./client-context"), exports);
|
|
27
|
+
__exportStar(require("./entry-context"), exports);
|
|
28
|
+
__exportStar(require("./gateway-connection"), exports);
|
|
29
|
+
__exportStar(require("./matreshka"), exports);
|
|
30
|
+
__exportStar(require("./conditions"), exports);
|
|
31
|
+
__exportStar(require("./context/context"), exports);
|
|
32
|
+
__exportStar(require("./context/context-ref"), exports);
|
|
33
|
+
__exportStar(require("./utils/calculate-components"), exports);
|
|
34
|
+
__exportStar(require("./utils/color-token-id"), exports);
|
|
35
|
+
__exportStar(require("./utils/serialize-component-tree"), exports);
|
|
36
|
+
__exportStar(require("@matreshka/shared/types/json"), exports);
|
|
37
|
+
__exportStar(require("./types/component-instance"), exports);
|
|
38
|
+
__exportStar(require("./types/component-tree-node"), exports);
|
|
39
|
+
__exportStar(require("./types/componentable"), exports);
|
|
40
|
+
__exportStar(require("./types/message"), exports);
|
|
41
|
+
__exportStar(require("./types/mixed-with-callbacks-array"), exports);
|
|
42
|
+
__exportStar(require("./types/native-picker-context-ref"), exports);
|
|
43
|
+
__exportStar(require("./types/pageable"), exports);
|
|
44
|
+
__exportStar(require("./types/standalone-component"), exports);
|
|
45
|
+
__exportStar(require("./types/status-code"), exports);
|
|
46
|
+
__exportStar(require("./version"), exports);
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { Subject } from "rxjs";
|
|
2
|
+
import { Client } from "./client";
|
|
3
|
+
import { GatewayConnection } from "./gateway-connection";
|
|
4
|
+
import { Router } from "./router";
|
|
5
|
+
import { ClientSettings } from "./types/client-settings";
|
|
6
|
+
export type ClientSettingsResolver = (applicationId: string) => ClientSettings;
|
|
7
|
+
/**
|
|
8
|
+
* Основной класс приложения, управляющий жизненным циклом клиентов и маршрутизацией.
|
|
9
|
+
*/
|
|
10
|
+
export declare class Matreshka {
|
|
11
|
+
private _clients;
|
|
12
|
+
readonly router: Router;
|
|
13
|
+
private readonly instanceId;
|
|
14
|
+
private destroyTimers;
|
|
15
|
+
private destroyTimeout;
|
|
16
|
+
private pendingHandshakeSubscriptions;
|
|
17
|
+
readonly clientConnect$: Subject<Client>;
|
|
18
|
+
readonly clientReconnect$: Subject<Client>;
|
|
19
|
+
readonly clientDisconnect$: Subject<Client>;
|
|
20
|
+
readonly clientDestroy$: Subject<Client>;
|
|
21
|
+
/**
|
|
22
|
+
* Создает экземпляр Matreshka.
|
|
23
|
+
*
|
|
24
|
+
*/
|
|
25
|
+
constructor();
|
|
26
|
+
/**
|
|
27
|
+
* Получает клиента по параметрам запроса. Если клиент найден — возвращает его,
|
|
28
|
+
* иначе создает нового клиента из состояния.
|
|
29
|
+
*
|
|
30
|
+
* @param params Параметры URL, содержащие токен и сериализованное состояние.
|
|
31
|
+
* @returns Экземпляр клиента.
|
|
32
|
+
*/
|
|
33
|
+
getClient(params: URLSearchParams): Client;
|
|
34
|
+
/**
|
|
35
|
+
* Возвращает клиента по токену, если он существует.
|
|
36
|
+
*
|
|
37
|
+
* @param token Уникальный токен клиента.
|
|
38
|
+
* @returns Экземпляр клиента или undefined.
|
|
39
|
+
*/
|
|
40
|
+
findClient(token: string): Client | undefined;
|
|
41
|
+
/**
|
|
42
|
+
* Подключает BFF к gateway по WebSocket.
|
|
43
|
+
*
|
|
44
|
+
* @param serverUrl Адрес gateway (`ws://127.0.0.1:3002` или с path `/bff`).
|
|
45
|
+
* @param token Токен BFF из конфигурации gateway (`id:secret`).
|
|
46
|
+
* @param resolveClientSettings Настройки для BFF handshake по `applicationId`.
|
|
47
|
+
*
|
|
48
|
+
* Версия пакета `@matreshka/bff` добавляется в query автоматически.
|
|
49
|
+
*/
|
|
50
|
+
connectGateway(serverUrl: string, token: string, resolveClientSettings: ClientSettingsResolver): GatewayConnection;
|
|
51
|
+
/**
|
|
52
|
+
* Инициализирует клиента: либо подключает нового, либо обрабатывает реконнект.
|
|
53
|
+
*
|
|
54
|
+
* @param client Экземпляр клиента.
|
|
55
|
+
* @param params Параметры URL (могут содержать token).
|
|
56
|
+
* @param resolveClientSettings Настройки для BFF handshake по `applicationId`.
|
|
57
|
+
*/
|
|
58
|
+
initClient(client: Client, params: URLSearchParams, resolveClientSettings: ClientSettingsResolver): void;
|
|
59
|
+
private waitForClientHandshake;
|
|
60
|
+
private sendHandshake;
|
|
61
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
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.Matreshka = void 0;
|
|
37
|
+
const index_1 = require("@matreshka/shared/messages/bff-to-client/app/index");
|
|
38
|
+
const handshake_message_1 = require("@matreshka/shared/messages/client-to-bff/app/handshake-message");
|
|
39
|
+
const crypto = __importStar(require("crypto"));
|
|
40
|
+
const rxjs_1 = require("rxjs");
|
|
41
|
+
const client_1 = require("./client");
|
|
42
|
+
const gateway_connection_1 = require("./gateway-connection");
|
|
43
|
+
const router_1 = require("./router");
|
|
44
|
+
const color_token_id_1 = require("./utils/color-token-id");
|
|
45
|
+
const CLIENT_DESTROY_TIMEOUT_MS = 15 * 60 * 1000; // 15 минут
|
|
46
|
+
/**
|
|
47
|
+
* Основной класс приложения, управляющий жизненным циклом клиентов и маршрутизацией.
|
|
48
|
+
*/
|
|
49
|
+
class Matreshka {
|
|
50
|
+
/**
|
|
51
|
+
* Создает экземпляр Matreshka.
|
|
52
|
+
*
|
|
53
|
+
*/
|
|
54
|
+
constructor() {
|
|
55
|
+
this._clients = new Map();
|
|
56
|
+
this.router = new router_1.Router();
|
|
57
|
+
this.instanceId = crypto.randomUUID();
|
|
58
|
+
this.destroyTimers = new Map();
|
|
59
|
+
this.destroyTimeout = CLIENT_DESTROY_TIMEOUT_MS;
|
|
60
|
+
this.pendingHandshakeSubscriptions = new WeakMap();
|
|
61
|
+
this.clientConnect$ = new rxjs_1.Subject();
|
|
62
|
+
this.clientReconnect$ = new rxjs_1.Subject();
|
|
63
|
+
this.clientDisconnect$ = new rxjs_1.Subject();
|
|
64
|
+
this.clientDestroy$ = new rxjs_1.Subject();
|
|
65
|
+
this.clientReconnect$.subscribe((client) => {
|
|
66
|
+
client.reconnect$.next();
|
|
67
|
+
});
|
|
68
|
+
this.clientDisconnect$.subscribe((client) => {
|
|
69
|
+
client.disconnect$.next();
|
|
70
|
+
const entry = [...this._clients.entries()].find((x) => x[1] === client);
|
|
71
|
+
if (entry) {
|
|
72
|
+
const token = entry[0];
|
|
73
|
+
this.destroyTimers.set(token, setTimeout(() => {
|
|
74
|
+
this._clients.delete(token);
|
|
75
|
+
client.destroy();
|
|
76
|
+
this.clientDestroy$.next(client);
|
|
77
|
+
}, this.destroyTimeout));
|
|
78
|
+
}
|
|
79
|
+
// Запуск таймера удаления
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Получает клиента по параметрам запроса. Если клиент найден — возвращает его,
|
|
84
|
+
* иначе создает нового клиента из состояния.
|
|
85
|
+
*
|
|
86
|
+
* @param params Параметры URL, содержащие токен и сериализованное состояние.
|
|
87
|
+
* @returns Экземпляр клиента.
|
|
88
|
+
*/
|
|
89
|
+
getClient(params) {
|
|
90
|
+
const token = params.get("token");
|
|
91
|
+
return token && this._clients.has(token)
|
|
92
|
+
? this._clients.get(token)
|
|
93
|
+
: new client_1.Client();
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Возвращает клиента по токену, если он существует.
|
|
97
|
+
*
|
|
98
|
+
* @param token Уникальный токен клиента.
|
|
99
|
+
* @returns Экземпляр клиента или undefined.
|
|
100
|
+
*/
|
|
101
|
+
findClient(token) {
|
|
102
|
+
return this._clients.get(token);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Подключает BFF к gateway по WebSocket.
|
|
106
|
+
*
|
|
107
|
+
* @param serverUrl Адрес gateway (`ws://127.0.0.1:3002` или с path `/bff`).
|
|
108
|
+
* @param token Токен BFF из конфигурации gateway (`id:secret`).
|
|
109
|
+
* @param resolveClientSettings Настройки для BFF handshake по `applicationId`.
|
|
110
|
+
*
|
|
111
|
+
* Версия пакета `@matreshka/bff` добавляется в query автоматически.
|
|
112
|
+
*/
|
|
113
|
+
connectGateway(serverUrl, token, resolveClientSettings) {
|
|
114
|
+
return new gateway_connection_1.GatewayConnection(this, {
|
|
115
|
+
url: serverUrl,
|
|
116
|
+
token,
|
|
117
|
+
resolveClientSettings,
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Инициализирует клиента: либо подключает нового, либо обрабатывает реконнект.
|
|
122
|
+
*
|
|
123
|
+
* @param client Экземпляр клиента.
|
|
124
|
+
* @param params Параметры URL (могут содержать token).
|
|
125
|
+
* @param resolveClientSettings Настройки для BFF handshake по `applicationId`.
|
|
126
|
+
*/
|
|
127
|
+
initClient(client, params, resolveClientSettings) {
|
|
128
|
+
const token = params.get("token"); // Токен передается только при реконнекте
|
|
129
|
+
const needReload = token && !this._clients.has(token);
|
|
130
|
+
if (token && this.destroyTimers.has(token)) {
|
|
131
|
+
// Отмена удаления клиента по таймауту, так как он подключился
|
|
132
|
+
clearTimeout(this.destroyTimers.get(token));
|
|
133
|
+
this.destroyTimers.delete(token);
|
|
134
|
+
this.clientReconnect$.next(client);
|
|
135
|
+
}
|
|
136
|
+
if (token) {
|
|
137
|
+
// Реконнект нужен в случае если по какой-то причине на клиенте отключился сокет (бывает из-за настроек NGINX, возможно отключается при потере сети на телефоне)
|
|
138
|
+
if (needReload) {
|
|
139
|
+
// Данные клиента удалены из памяти, нужно перезагрузить страницу
|
|
140
|
+
this.clientDisconnect$.next(client);
|
|
141
|
+
const message = new index_1.AppReloadMessage();
|
|
142
|
+
client.outcomingMessage$.next(message);
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
// Отправка id текущего инстанса чтобы клиент был уверен, что версия сервера не изменилась
|
|
146
|
+
const message = new index_1.AppReconnectInfoMessage({
|
|
147
|
+
serverInstanceId: this.instanceId,
|
|
148
|
+
});
|
|
149
|
+
client.outcomingMessage$.next(message);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
this.clientConnect$.next(client);
|
|
154
|
+
this.waitForClientHandshake(client, resolveClientSettings);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
waitForClientHandshake(client, resolveSettings) {
|
|
158
|
+
this.pendingHandshakeSubscriptions.get(client)?.unsubscribe();
|
|
159
|
+
const subscription = client.incomingMessage$
|
|
160
|
+
.pipe((0, rxjs_1.filter)((message) => message instanceof handshake_message_1.HandshakeMessage), (0, rxjs_1.take)(1))
|
|
161
|
+
.subscribe((message) => {
|
|
162
|
+
this.pendingHandshakeSubscriptions.delete(client);
|
|
163
|
+
this.sendHandshake(client, resolveSettings(message.payload.applicationId), message.payload.applicationId);
|
|
164
|
+
});
|
|
165
|
+
this.pendingHandshakeSubscriptions.set(client, subscription);
|
|
166
|
+
}
|
|
167
|
+
sendHandshake(client, settings, applicationId) {
|
|
168
|
+
const newClientToken = crypto.randomUUID();
|
|
169
|
+
client.applicationId$.next(applicationId);
|
|
170
|
+
this._clients.set(newClientToken, client);
|
|
171
|
+
const message = new index_1.HandshakeMessage({
|
|
172
|
+
serverInstanceId: this.instanceId,
|
|
173
|
+
token: newClientToken,
|
|
174
|
+
clientDestroyTimeoutMs: CLIENT_DESTROY_TIMEOUT_MS,
|
|
175
|
+
settings: {
|
|
176
|
+
...settings,
|
|
177
|
+
colors: settings.colors.reduce((acc, cur) => {
|
|
178
|
+
acc[(0, color_token_id_1.colorTokenId)(cur)] = cur;
|
|
179
|
+
return acc;
|
|
180
|
+
}, {}),
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
client.outcomingMessage$.next(message);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
exports.Matreshka = Matreshka;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { Client } from "./client";
|
|
2
|
+
import { Pageable } from "./types/pageable";
|
|
3
|
+
/**
|
|
4
|
+
* Отвечает за маршрутизацию и авторизацию клиентов по заданным маскам маршрутов.
|
|
5
|
+
*/
|
|
6
|
+
export declare class Router {
|
|
7
|
+
private routes;
|
|
8
|
+
/**
|
|
9
|
+
* Регистрирует страницу и маску маршрута с функцией авторизации.
|
|
10
|
+
*
|
|
11
|
+
* @param route_mask Маска маршрута, например: "user/{id}".
|
|
12
|
+
* @param callback Функция, возвращающая класс страницы, реализующий интерфейс Pageable.
|
|
13
|
+
* @returns Текущий экземпляр Router.
|
|
14
|
+
*/
|
|
15
|
+
addPage(route_mask: string, callback: (client: Client, params: Record<string, string>) => Promise<Pageable | undefined>): this;
|
|
16
|
+
/**
|
|
17
|
+
* Регистрирует маску маршрута и связанную с ней страницу.
|
|
18
|
+
*
|
|
19
|
+
* @param route_mask Маска маршрута.
|
|
20
|
+
* @param callback Функция, возвращающая класс страницы, реализующий интерфейс Pageable.
|
|
21
|
+
*/
|
|
22
|
+
private registerRouteMask;
|
|
23
|
+
/**
|
|
24
|
+
* Преобразует маску маршрута в строку регулярного выражения.
|
|
25
|
+
*
|
|
26
|
+
* @param route_mask Маска маршрута.
|
|
27
|
+
* @returns Строка с регулярным выражением.
|
|
28
|
+
*/
|
|
29
|
+
private generateRouteMaskRegex;
|
|
30
|
+
/**
|
|
31
|
+
* Выполняет поиск страницы по маршруту, проверяя авторизацию клиента.
|
|
32
|
+
*
|
|
33
|
+
* @param client Клиент, для которого выполняется поиск.
|
|
34
|
+
* @param route Запрашиваемый маршрут.
|
|
35
|
+
* @returns Pageable | undefined Объект страницы.
|
|
36
|
+
*/
|
|
37
|
+
findByRoute(client: Client, route: string): Promise<Pageable | undefined>;
|
|
38
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Router = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Отвечает за маршрутизацию и авторизацию клиентов по заданным маскам маршрутов.
|
|
6
|
+
*/
|
|
7
|
+
class Router {
|
|
8
|
+
constructor() {
|
|
9
|
+
this.routes = new Map();
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Регистрирует страницу и маску маршрута с функцией авторизации.
|
|
13
|
+
*
|
|
14
|
+
* @param route_mask Маска маршрута, например: "user/{id}".
|
|
15
|
+
* @param callback Функция, возвращающая класс страницы, реализующий интерфейс Pageable.
|
|
16
|
+
* @returns Текущий экземпляр Router.
|
|
17
|
+
*/
|
|
18
|
+
addPage(route_mask, callback) {
|
|
19
|
+
route_mask = route_mask.replace(/^\/|\/$/g, "");
|
|
20
|
+
this.registerRouteMask(route_mask, callback);
|
|
21
|
+
return this;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Регистрирует маску маршрута и связанную с ней страницу.
|
|
25
|
+
*
|
|
26
|
+
* @param route_mask Маска маршрута.
|
|
27
|
+
* @param callback Функция, возвращающая класс страницы, реализующий интерфейс Pageable.
|
|
28
|
+
*/
|
|
29
|
+
registerRouteMask(route_mask, callback) {
|
|
30
|
+
route_mask = route_mask.replace(/\/{2,}/, "/");
|
|
31
|
+
const route_mask_regex = this.generateRouteMaskRegex(route_mask);
|
|
32
|
+
if (!this.routes.has(route_mask_regex)) {
|
|
33
|
+
this.routes.set(route_mask_regex, []);
|
|
34
|
+
}
|
|
35
|
+
const route_entities = this.routes.get(route_mask_regex) || [];
|
|
36
|
+
route_entities.push({
|
|
37
|
+
route_mask,
|
|
38
|
+
callback,
|
|
39
|
+
});
|
|
40
|
+
this.routes.set(route_mask_regex, route_entities);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Преобразует маску маршрута в строку регулярного выражения.
|
|
44
|
+
*
|
|
45
|
+
* @param route_mask Маска маршрута.
|
|
46
|
+
* @returns Строка с регулярным выражением.
|
|
47
|
+
*/
|
|
48
|
+
generateRouteMaskRegex(route_mask) {
|
|
49
|
+
// Спец-маска "всё" (используется как fallback / 404)
|
|
50
|
+
if (route_mask === "**") {
|
|
51
|
+
return ".*";
|
|
52
|
+
}
|
|
53
|
+
const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
54
|
+
const parts = route_mask.split("/");
|
|
55
|
+
const regexParts = parts.map((part) => {
|
|
56
|
+
if (part === "**") {
|
|
57
|
+
return ".*";
|
|
58
|
+
}
|
|
59
|
+
if (part === "*") {
|
|
60
|
+
return "[^/]+";
|
|
61
|
+
}
|
|
62
|
+
// Поддержка параметров в сегменте: "cards/{id}" или "foo-{id}"
|
|
63
|
+
const paramTokens = [];
|
|
64
|
+
let tokenIdx = 0;
|
|
65
|
+
const withTokens = part.replace(/{(.*?)}/g, () => {
|
|
66
|
+
const token = `___PARAM_${tokenIdx++}___`;
|
|
67
|
+
paramTokens.push(token);
|
|
68
|
+
return token;
|
|
69
|
+
});
|
|
70
|
+
let escaped = escapeRegExp(withTokens);
|
|
71
|
+
for (const token of paramTokens) {
|
|
72
|
+
// Токен тоже нужно заменить в экранированной строке
|
|
73
|
+
escaped = escaped.replace(escapeRegExp(token), "([^/]+)");
|
|
74
|
+
}
|
|
75
|
+
return escaped;
|
|
76
|
+
});
|
|
77
|
+
return regexParts.join("/");
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Выполняет поиск страницы по маршруту, проверяя авторизацию клиента.
|
|
81
|
+
*
|
|
82
|
+
* @param client Клиент, для которого выполняется поиск.
|
|
83
|
+
* @param route Запрашиваемый маршрут.
|
|
84
|
+
* @returns Pageable | undefined Объект страницы.
|
|
85
|
+
*/
|
|
86
|
+
async findByRoute(client, route) {
|
|
87
|
+
// С какой страницей ассоциируется маршрут
|
|
88
|
+
route = route.replace(/^\/|\/$/g, "");
|
|
89
|
+
for (const route_mask_regex of this.routes.keys()) {
|
|
90
|
+
const regex = new RegExp(`^${route_mask_regex}$`, "g");
|
|
91
|
+
if (route.match(regex)) {
|
|
92
|
+
const route_regex_data = [...route.matchAll(regex)];
|
|
93
|
+
const params = {};
|
|
94
|
+
const matches = this.routes.get(route_mask_regex) || [];
|
|
95
|
+
for (const config of matches) {
|
|
96
|
+
const params_names = config.route_mask.matchAll(/{(.*?)}/g);
|
|
97
|
+
[...params_names].forEach((regex_match, index) => {
|
|
98
|
+
params[regex_match[1]] = route_regex_data[0][index + 1];
|
|
99
|
+
});
|
|
100
|
+
const page = await config.callback(client, params);
|
|
101
|
+
if (page) {
|
|
102
|
+
return page;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
// Защита от бесконечной рекурсии, если fallback-страница не зарегистрирована
|
|
108
|
+
if (route !== "**") {
|
|
109
|
+
const notFoundPage = await this.findByRoute(client, "**");
|
|
110
|
+
if (notFoundPage) {
|
|
111
|
+
return notFoundPage;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
exports.Router = Router;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { ColorToken } from "@matreshka/shared/types/color-token";
|
|
2
|
+
import { AppFontsConfig } from "@matreshka/shared/types/fonts";
|
|
3
|
+
/**
|
|
4
|
+
* Настройки интерфейса приложения, передаваемые клиенту.
|
|
5
|
+
*
|
|
6
|
+
* @property appName Название приложения.
|
|
7
|
+
* @property appShortName Короткое название приложения.
|
|
8
|
+
* @property faviconUrl Ссылки на иконки favicon.
|
|
9
|
+
* @property pwaIconUrl Ссылки на иконки для установки как PWA.
|
|
10
|
+
* @property fonts Реестр и стек шрифтов интерфейса.
|
|
11
|
+
* @property colors Цветовые схемы интерфейса.
|
|
12
|
+
*/
|
|
13
|
+
export type ClientSettings = {
|
|
14
|
+
appName: string;
|
|
15
|
+
appShortName?: string;
|
|
16
|
+
analytics?: {
|
|
17
|
+
yandex?: {
|
|
18
|
+
id: string;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
faviconUrl?: {
|
|
22
|
+
png: string;
|
|
23
|
+
svg?: string;
|
|
24
|
+
};
|
|
25
|
+
pwaIconUrl?: {
|
|
26
|
+
png: string;
|
|
27
|
+
svg?: string;
|
|
28
|
+
};
|
|
29
|
+
fonts: AppFontsConfig;
|
|
30
|
+
colors: ColorToken[];
|
|
31
|
+
};
|