@sermas/sermas-toolkit-node-sdk 1.0.0-alpha.9 → 1.0.0-alpha.91

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 (41) hide show
  1. package/README.md +16 -0
  2. package/index.cjs +2 -0
  3. package/index.cjs.map +1 -0
  4. package/index.d.cts +150 -0
  5. package/index.d.ts +150 -0
  6. package/index.js +2 -0
  7. package/index.js.map +1 -0
  8. package/package.json +15 -16
  9. package/dist/cjs/config/defaults.js +0 -18
  10. package/dist/cjs/config/logger.js +0 -10
  11. package/dist/cjs/config/util.js +0 -70
  12. package/dist/cjs/dto/session.js +0 -2
  13. package/dist/cjs/index.js +0 -16
  14. package/dist/cjs/modules/auth.js +0 -238
  15. package/dist/cjs/modules/openai.js +0 -63
  16. package/dist/cjs/modules/sermas.js +0 -233
  17. package/dist/cjs/modules/store.js +0 -177
  18. package/dist/cjs/modules/tools.js +0 -44
  19. package/dist/cjs/modules/ui.js +0 -124
  20. package/dist/esm/config/defaults.js +0 -15
  21. package/dist/esm/config/logger.js +0 -6
  22. package/dist/esm/config/util.js +0 -39
  23. package/dist/esm/dto/session.js +0 -1
  24. package/dist/esm/index.js +0 -6
  25. package/dist/esm/modules/auth.js +0 -210
  26. package/dist/esm/modules/openai.js +0 -57
  27. package/dist/esm/modules/sermas.js +0 -230
  28. package/dist/esm/modules/store.js +0 -174
  29. package/dist/esm/modules/tools.js +0 -41
  30. package/dist/esm/modules/ui.js +0 -121
  31. package/dist/types/config/defaults.d.ts +0 -15
  32. package/dist/types/config/logger.d.ts +0 -1
  33. package/dist/types/config/util.d.ts +0 -6
  34. package/dist/types/dto/session.d.ts +0 -7
  35. package/dist/types/index.d.ts +0 -8
  36. package/dist/types/modules/auth.d.ts +0 -30
  37. package/dist/types/modules/openai.d.ts +0 -18
  38. package/dist/types/modules/sermas.d.ts +0 -36
  39. package/dist/types/modules/store.d.ts +0 -21
  40. package/dist/types/modules/tools.d.ts +0 -15
  41. package/dist/types/modules/ui.d.ts +0 -24
@@ -1,210 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import axios, { isAxiosError } from "axios";
11
- import * as https from "https";
12
- import { defaults } from "../config/defaults.js";
13
- import { createLogger } from "../config/logger.js";
14
- const httpsAgent = new https.Agent({
15
- rejectUnauthorized: process.env.NODE_ENV !== "development",
16
- });
17
- /**
18
- * Returns access and refresh tokens for the given appId
19
- * @param {string} appId null by default
20
- * @param {AuthConfig} authConfig
21
- */
22
- export const getAvatarToken = (...args_1) => __awaiter(void 0, [...args_1], void 0, function* (appId = null, authConfig = defaults.auth) {
23
- const logger = createLogger("getAvatarToken");
24
- const tokens = {};
25
- let kioskToken = null;
26
- const PUBLIC_AUTH_URL = authConfig.PUBLIC_AUTH_URL || defaults.auth.PUBLIC_AUTH_URL;
27
- const PUBLIC_AUTH_REALM = authConfig.PUBLIC_AUTH_REALM || defaults.auth.PUBLIC_AUTH_REALM;
28
- const PRIVATE_AUTH_CLIENT_ID = authConfig.PRIVATE_AUTH_CLIENT_ID || defaults.auth.PRIVATE_AUTH_CLIENT_ID;
29
- const PRIVATE_AUTH_CLIENT_SECRET = authConfig.PRIVATE_AUTH_CLIENT_SECRET ||
30
- defaults.auth.PRIVATE_AUTH_CLIENT_SECRET;
31
- const PRIVATE_API_BASE_URL = authConfig.PRIVATE_API_BASE_URL || defaults.auth.PRIVATE_API_BASE_URL;
32
- const getAvatarToken = (...args_2) => __awaiter(void 0, [...args_2], void 0, function* (appId = null) {
33
- yield getSystemAccessToken();
34
- let appToken = null;
35
- if (appId) {
36
- appToken = yield getAppAccessToken(appId);
37
- }
38
- return Object.assign(Object.assign({}, (appToken || {})), { appId });
39
- });
40
- const getAppAccessToken = (appId_1, ...args_3) => __awaiter(void 0, [appId_1, ...args_3], void 0, function* (appId, clientId = "avatar") {
41
- var _a, _b;
42
- logger.info(`Fetch app token for appId=${appId} clientId=${clientId}`);
43
- const cacheKey = `${appId}-${clientId}`;
44
- tokens[cacheKey] = tokens[cacheKey] || null;
45
- if (tokens[cacheKey]) {
46
- const expiresIn = (_a = tokens[cacheKey]) === null || _a === void 0 ? void 0 : _a.expiresIn;
47
- if (!expiresIn || new Date(expiresIn).getTime() - 30000 < Date.now()) {
48
- tokens[cacheKey] = null;
49
- }
50
- }
51
- if (tokens[cacheKey]) {
52
- logger.info(`Using cached token for ${cacheKey}`);
53
- return tokens[cacheKey];
54
- }
55
- try {
56
- const url = `${PRIVATE_API_BASE_URL}/platform/token`;
57
- const data = {
58
- appId,
59
- clientId,
60
- };
61
- logger.debug(`Requesting to ${url}`);
62
- const res = yield axios.post(url, data, {
63
- httpsAgent,
64
- headers: {
65
- Authorization: `Bearer ${kioskToken === null || kioskToken === void 0 ? void 0 : kioskToken.accessToken}`,
66
- },
67
- });
68
- // expires 1min before
69
- const expiresIn = res.data.expires_in * 1000;
70
- logger.info(`Token for ${appId} expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`);
71
- const { access_token, refresh_token } = res.data;
72
- const token = {
73
- accessToken: access_token,
74
- refreshToken: refresh_token,
75
- expiresIn: new Date(Date.now() + expiresIn),
76
- };
77
- tokens[cacheKey] = token;
78
- return token;
79
- }
80
- catch (e) {
81
- if (e instanceof Error)
82
- logger.error(`Request failed ${e === null || e === void 0 ? void 0 : e.message}`);
83
- if (isAxiosError(e)) {
84
- logger.error((_b = e.response) === null || _b === void 0 ? void 0 : _b.data);
85
- delete tokens[cacheKey];
86
- }
87
- }
88
- return null;
89
- });
90
- const getSystemAccessToken = () => __awaiter(void 0, void 0, void 0, function* () {
91
- var _c, _d;
92
- const cacheKey = "___kiosk___";
93
- if (tokens[cacheKey]) {
94
- const expiresIn = (_c = tokens[cacheKey]) === null || _c === void 0 ? void 0 : _c.expiresIn;
95
- if (!expiresIn || new Date(expiresIn).getTime() - 30000 < Date.now()) {
96
- tokens[cacheKey] = null;
97
- }
98
- }
99
- if (tokens[cacheKey])
100
- return tokens[cacheKey];
101
- logger.debug(`Load kiosk access token`);
102
- const url = `${PUBLIC_AUTH_URL}/realms/${PUBLIC_AUTH_REALM}/protocol/openid-connect/token`;
103
- const data = {
104
- client_id: PRIVATE_AUTH_CLIENT_ID,
105
- client_secret: PRIVATE_AUTH_CLIENT_SECRET,
106
- grant_type: "client_credentials",
107
- };
108
- try {
109
- logger.debug(`Requesting to ${url}`);
110
- const res = yield axios.post(url, data, {
111
- headers: {
112
- "Content-Type": "application/x-www-form-urlencoded",
113
- Authorization: `Bearer ${btoa(PRIVATE_AUTH_CLIENT_ID + ":" + PRIVATE_AUTH_CLIENT_SECRET)}`,
114
- },
115
- });
116
- // expires 1min before
117
- const expiresIn = res.data.expires_in * 1000;
118
- logger.debug(`kioskToken expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`);
119
- // const access_token = await getAuthorizationToken(res.data.access_token)
120
- const { access_token, refresh_token } = res.data;
121
- kioskToken = {
122
- accessToken: access_token,
123
- refreshToken: refresh_token,
124
- expiresIn: new Date(Date.now() + expiresIn),
125
- };
126
- tokens["__kiosk"] = kioskToken;
127
- return kioskToken;
128
- }
129
- catch (e) {
130
- kioskToken = null;
131
- if (e instanceof Error)
132
- logger.error(`Request failed ${e.message}`);
133
- if (isAxiosError(e)) {
134
- logger.error((_d = e.response) === null || _d === void 0 ? void 0 : _d.data);
135
- }
136
- }
137
- return null;
138
- });
139
- return yield getAvatarToken(appId);
140
- });
141
- /**
142
- * Returns access and refresh tokens for the given appId
143
- * @param {string} appId null by default
144
- * @param {AuthConfig} authConfig only PRIVATE_API_BASE_URL and PRIVATE_AUTH_CLIENT_ID are used
145
- * @param {string} clientSecret needed for server2server authentication
146
- */
147
- export const getAvatarTokenWithClientSecret = (...args_4) => __awaiter(void 0, [...args_4], void 0, function* (appId = null, authConfig = defaults.auth, clientSecret = "") {
148
- const logger = createLogger("getAvatarTokenWithClientSecret");
149
- const tokens = {};
150
- const PRIVATE_API_BASE_URL = authConfig.PRIVATE_API_BASE_URL || defaults.auth.PRIVATE_API_BASE_URL;
151
- const PRIVATE_AUTH_CLIENT_ID = authConfig.PRIVATE_AUTH_CLIENT_ID || defaults.auth.PRIVATE_AUTH_CLIENT_ID;
152
- const getAppAccessTokenWithClientSecret = (appId_2, ...args_5) => __awaiter(void 0, [appId_2, ...args_5], void 0, function* (appId, clientId = "avatar", clientSecret = "") {
153
- var _e, _f;
154
- logger.info(`Fetch app token for appId=${appId} clientId=${clientId} clientSecret=${clientSecret}`);
155
- const cacheKey = `${appId}-${clientId}`;
156
- tokens[cacheKey] = tokens[cacheKey] || null;
157
- if (tokens[cacheKey]) {
158
- const expiresIn = (_e = tokens[cacheKey]) === null || _e === void 0 ? void 0 : _e.expiresIn;
159
- if (!expiresIn ||
160
- new Date(expiresIn).getTime() - 60 * 1000 < Date.now()) {
161
- tokens[cacheKey] = null;
162
- }
163
- }
164
- if (tokens[cacheKey]) {
165
- logger.info(`Using cached token for ${cacheKey}`);
166
- return tokens[cacheKey];
167
- }
168
- try {
169
- const url = `${PRIVATE_API_BASE_URL}/platform/token/access_token`;
170
- logger.debug(`Requesting to ${url}`);
171
- const data = {
172
- appId,
173
- clientId,
174
- clientSecret,
175
- };
176
- logger.debug(`get token from ${url}`);
177
- const res = yield axios.post(url, data, {
178
- httpsAgent,
179
- });
180
- // expires 1min before
181
- const expiresIn = res.data.expires_in * 1000;
182
- logger.info(`Token for ${appId} expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`);
183
- const { access_token, refresh_token } = res.data;
184
- const token = {
185
- accessToken: access_token,
186
- refreshToken: refresh_token,
187
- expiresIn: new Date(Date.now() + expiresIn),
188
- };
189
- tokens[cacheKey] = token;
190
- return token;
191
- }
192
- catch (e) {
193
- if (e instanceof Error)
194
- logger.error(`Request failed ${e.message}`);
195
- if (isAxiosError(e)) {
196
- logger.error((_f = e.response) === null || _f === void 0 ? void 0 : _f.data);
197
- delete tokens[cacheKey];
198
- }
199
- }
200
- return null;
201
- });
202
- const getAvatarTokenWithClientSecret = (...args_6) => __awaiter(void 0, [...args_6], void 0, function* (appId = null, clientId = "", clientSecret = "") {
203
- let appToken = null;
204
- if (appId) {
205
- appToken = yield getAppAccessTokenWithClientSecret(appId, clientId, clientSecret);
206
- }
207
- return Object.assign(Object.assign({}, (appToken || {})), { appId });
208
- });
209
- return yield getAvatarTokenWithClientSecret(appId, PRIVATE_AUTH_CLIENT_ID, clientSecret);
210
- });
@@ -1,57 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { createLogger } from "../config/logger.js";
11
- import OpenAI from "openai";
12
- /**
13
- * Wrapper for OpenAI client to implement sermas functionalities
14
- */
15
- class OpenAIClient {
16
- constructor(openAIConfig) {
17
- this.logger = createLogger(OpenAIClient.name);
18
- if (!openAIConfig.apiKey)
19
- this.logger.warn("No API key provided for OpenAIClient");
20
- this.openAI = new OpenAI(openAIConfig);
21
- }
22
- chat(body, options) {
23
- return __awaiter(this, void 0, void 0, function* () {
24
- try {
25
- const result = yield this.openAI.chat.completions.create(Object.assign({ model: "gpt-3.5-turbo" }, (typeof body === "string"
26
- ? { messages: [{ role: "user", content: body }] }
27
- : body)), options);
28
- return result.choices[0].message.content;
29
- }
30
- catch (e) {
31
- if (e instanceof Error)
32
- this.logger.error(`OpenAI request failed: ${e.stack}`);
33
- return null;
34
- }
35
- });
36
- }
37
- json(body, options) {
38
- return __awaiter(this, void 0, void 0, function* () {
39
- let text = yield this.chat(body, options);
40
- if (text === null)
41
- return;
42
- try {
43
- if (text.startsWith("```json")) {
44
- text = text.replace("```json", "").replace("```", "");
45
- }
46
- return JSON.parse(text);
47
- }
48
- catch (e) {
49
- if (e instanceof Error)
50
- this.logger.error(`Failed to parse content: ${e.stack}`);
51
- this.logger.debug(`Content: ${text}`);
52
- return null;
53
- }
54
- });
55
- }
56
- }
57
- export { OpenAIClient };
@@ -1,230 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { createLogger } from "../config/logger.js";
11
- import { EventEmitter2 } from "eventemitter2";
12
- import { SermasApiClient, } from "@sermas/api-client";
13
- import { defaults } from "../config/defaults.js";
14
- class SermasApp {
15
- constructor(sermasConfig) {
16
- this.logger = createLogger(SermasApp.name);
17
- this.app = null;
18
- this.subs = [];
19
- this.baseUrl =
20
- sermasConfig.SERMAS_BASE_URL || defaults.sermas.SERMAS_BASE_URL;
21
- this.appId = sermasConfig.SERMAS_APPID || defaults.sermas.SERMAS_CLIENT_ID;
22
- this.clientId =
23
- sermasConfig.SERMAS_CLIENT_ID || defaults.sermas.SERMAS_CLIENT_SECRET;
24
- this.clientSecret =
25
- sermasConfig.SERMAS_CLIENT_SECRET || defaults.sermas.SERMAS_APPID;
26
- console.log("object");
27
- this.emitter = new EventEmitter2();
28
- this.initialize();
29
- this.client = new SermasApiClient({
30
- baseURL: this.getBaseUrl(),
31
- appId: this.appId,
32
- logger: createLogger("sermas-api-client"),
33
- });
34
- this.getApp();
35
- }
36
- getBaseUrl() {
37
- return this.baseUrl;
38
- }
39
- initialize() {
40
- return __awaiter(this, void 0, void 0, function* () {
41
- // return await this.getClientCredentials();
42
- yield this.setupSermasClient();
43
- this.addSub(() => __awaiter(this, void 0, void 0, function* () {
44
- return yield this.client.events.auth.onUserLogin((ev) => {
45
- this.logger.debug(`User login: ${ev}`);
46
- });
47
- }));
48
- this.addSub(() => __awaiter(this, void 0, void 0, function* () {
49
- return yield this.client.events.session.onSessionChanged((ev) => {
50
- this.logger.debug(`session changed ${ev.operation.toUpperCase()} sessionId=${ev.record.sessionId}`);
51
- this.emitter.emit(`session`, ev);
52
- });
53
- }));
54
- this.addSub(() => __awaiter(this, void 0, void 0, function* () {
55
- return yield this.client.events.dialogue.onToolTriggered((event) => {
56
- this.logger.debug("Tool triggered: " + event.name);
57
- this.emitter.emit(`tool`, event);
58
- });
59
- }));
60
- this.addSub(() => __awaiter(this, void 0, void 0, function* () {
61
- return yield this.client.events.ui.onInteraction((event) => {
62
- // this.logger.debug('UI interaction: ' + event.interaction);
63
- this.emitter.emit(`ui.interaction`, event);
64
- });
65
- }));
66
- this.addSub(() => __awaiter(this, void 0, void 0, function* () {
67
- return yield this.client.events.session.onAgentChanged((event) => {
68
- this.logger.debug("Agent changed: " + event.operation);
69
- this.emitter.emit(`agent.changed`, event);
70
- });
71
- }));
72
- this.logger.info("Sermas initialization completed");
73
- });
74
- }
75
- setupSermasClient() {
76
- return __awaiter(this, void 0, void 0, function* () {
77
- this.logger.debug("Initializing sermas client.");
78
- try {
79
- this.logger.debug(`Loading token`);
80
- yield this.client.loadToken(this.clientId, this.clientSecret);
81
- }
82
- catch (e) {
83
- this.logger.error(`Failed to load token, retrying`);
84
- if (e instanceof Error)
85
- this.logger.debug(e.stack);
86
- setTimeout(() => this.setupSermasClient(), 1000);
87
- return;
88
- }
89
- this.logger.debug(`sermas client ready`);
90
- this.emitter.emit("sermas.ready");
91
- });
92
- }
93
- addSub(sub) {
94
- sub()
95
- .then((fn) => {
96
- this.subs.push(fn);
97
- })
98
- .catch((e) => {
99
- this.logger.error(`Subscribe failed: ${e.stack}`);
100
- });
101
- }
102
- sendChatMessage(ev) {
103
- return __awaiter(this, void 0, void 0, function* () {
104
- yield this.client.api.dialogue.chatMessage({
105
- appId: ev.appId,
106
- sessionId: ev.sessionId,
107
- requestBody: ev,
108
- });
109
- });
110
- }
111
- sendUiContent(ev) {
112
- return __awaiter(this, void 0, void 0, function* () {
113
- yield this.client.events.ui.content(ev);
114
- });
115
- }
116
- getApp() {
117
- return __awaiter(this, void 0, void 0, function* () {
118
- if (this.app)
119
- return this.app;
120
- this.logger.debug(`Load app ${this.appId}`);
121
- try {
122
- this.app = yield this.client.api.platform.readApp({ appId: this.appId });
123
- return this.app;
124
- }
125
- catch (e) {
126
- if (e instanceof Error)
127
- this.logger.error(`Failed to load app ${this.appId}: ${e.stack}`);
128
- return null;
129
- }
130
- });
131
- }
132
- updateAppTools(tools) {
133
- return __awaiter(this, void 0, void 0, function* () {
134
- yield this.client.api.platform.updateAppTools({
135
- appId: this.appId,
136
- requestBody: tools,
137
- });
138
- this.logger.debug("Updated tools");
139
- });
140
- }
141
- setTools(repositoryId, tools) {
142
- return __awaiter(this, void 0, void 0, function* () {
143
- yield this.client.api.dialogue.setTools({
144
- repositoryId,
145
- requestBody: {
146
- repositoryId,
147
- appId: this.appId,
148
- tools,
149
- },
150
- });
151
- this.logger.debug("Updated tools");
152
- });
153
- }
154
- addTools(repositoryId, tools, options) {
155
- return __awaiter(this, void 0, void 0, function* () {
156
- yield this.client.api.dialogue.addTools({
157
- repositoryId,
158
- requestBody: { repositoryId, appId: this.appId, tools, options },
159
- });
160
- this.logger.debug("Updated tools");
161
- });
162
- }
163
- readSession(sessionId) {
164
- return __awaiter(this, void 0, void 0, function* () {
165
- try {
166
- return yield this.client.api.session.readSession({ sessionId });
167
- }
168
- catch (e) {
169
- if (e instanceof Error)
170
- this.logger.error(`Failed to readSession: ${e.stack}`);
171
- return null;
172
- }
173
- });
174
- }
175
- getRecord(storageId) {
176
- return __awaiter(this, void 0, void 0, function* () {
177
- try {
178
- return yield this.client.api.session.getRecord({ storageId });
179
- }
180
- catch (e) {
181
- if (e instanceof Error && e.message.indexOf("Not Found") === -1)
182
- this.logger.error(`Failed to getRecord: ${e.stack}`);
183
- return null;
184
- }
185
- });
186
- }
187
- findRecords(query) {
188
- return __awaiter(this, void 0, void 0, function* () {
189
- try {
190
- return yield this.client.api.session.findRecords({
191
- requestBody: query,
192
- });
193
- }
194
- catch (e) {
195
- if (e instanceof Error)
196
- this.logger.error(`Failed to findRecords: ${e.stack}`);
197
- return null;
198
- }
199
- });
200
- }
201
- setRecord(storage) {
202
- return __awaiter(this, void 0, void 0, function* () {
203
- try {
204
- return yield this.client.api.session.setRecord({
205
- requestBody: storage,
206
- });
207
- }
208
- catch (e) {
209
- if (e instanceof Error)
210
- this.logger.error(`Failed to setRecord: ${e.stack}`);
211
- return null;
212
- }
213
- });
214
- }
215
- generateQRCode(data) {
216
- return __awaiter(this, void 0, void 0, function* () {
217
- try {
218
- return yield this.client.api.ui.generateQrCode({
219
- requestBody: { version: 5, data },
220
- });
221
- }
222
- catch (e) {
223
- if (e instanceof Error)
224
- this.logger.error(`Failed to generate QR code: ${e.stack}`);
225
- return null;
226
- }
227
- });
228
- }
229
- }
230
- export { SermasApp };
@@ -1,174 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { createLogger } from "../config/logger.js";
11
- import { uuidv4 } from "../config/util.js";
12
- class Store {
13
- constructor(sermas) {
14
- this.logger = createLogger(Store.name);
15
- this.sessions = {};
16
- this.locks = {};
17
- this.sermas = sermas;
18
- this.sermas.emitter.on("session", this.onSessionChange.bind(this));
19
- }
20
- // @OnEvent("session")
21
- onSessionChange(ev) {
22
- return __awaiter(this, void 0, void 0, function* () {
23
- if (!ev.record.sessionId)
24
- return;
25
- const session = yield this.saveSessionWrapper(ev);
26
- switch (ev.operation) {
27
- case "created":
28
- if (!session) {
29
- this.logger.warn(`Failed to get session for sessionId=${ev.record.sessionId}`);
30
- return;
31
- }
32
- this.sermas.emitter.emit("session.started", session);
33
- break;
34
- case "updated":
35
- yield this.saveSessionWrapper(ev);
36
- break;
37
- case "removed":
38
- if (!this.sessions[ev.record.sessionId])
39
- return;
40
- delete this.sessions[ev.record.sessionId];
41
- break;
42
- }
43
- });
44
- }
45
- lock(sessionId, fn) {
46
- return __awaiter(this, void 0, void 0, function* () {
47
- // eslint-disable-next-line no-async-promise-executor
48
- this.locks[sessionId] = new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
49
- try {
50
- resolve(yield fn());
51
- }
52
- catch (e) {
53
- reject(e);
54
- }
55
- }));
56
- try {
57
- const res = yield this.locks[sessionId];
58
- return res;
59
- }
60
- catch (e) {
61
- if (e instanceof Error)
62
- this.logger.error(`lock failure: ${e.stack}`);
63
- return null;
64
- }
65
- finally {
66
- delete this.locks[sessionId];
67
- }
68
- });
69
- }
70
- loadSessionWrapper(context) {
71
- return __awaiter(this, void 0, void 0, function* () {
72
- const opId = `[${performance.now()}] `;
73
- if (yield this.locks[context.sessionId]) {
74
- this.logger.debug(`${opId} Wait lock for sessionId=${context.sessionId}`);
75
- yield this.locks[context.sessionId];
76
- this.logger.debug(`${opId} Lock released for sessionId=${context.sessionId}`);
77
- }
78
- return yield this.lock(context.sessionId, () => __awaiter(this, void 0, void 0, function* () {
79
- this.logger.debug(`${opId} Loading wrapper for sessionId=${context.sessionId}`);
80
- const records = yield this.sermas.findRecords({
81
- appId: "",
82
- sessionId: [context.sessionId],
83
- userId: undefined,
84
- });
85
- if (records && records.length) {
86
- this.logger.debug(`${opId} Wrapper exists for sessionId=${context.sessionId}`);
87
- return records[0].data;
88
- }
89
- else {
90
- this.logger.debug(`${opId} Wrapper not found for sessionId=${context.sessionId}`);
91
- }
92
- this.logger.debug(`${opId} Creating new session wrapper store sessionId=${context.sessionId} appId=${context.appId} userId=${context.userId}`);
93
- const storageId = uuidv4();
94
- const sessionWrapper = Object.assign(Object.assign({}, context), { appId: context.appId, sessionId: context.sessionId, userId: context.userId, storageId });
95
- if (!sessionWrapper.appId || !sessionWrapper.userId) {
96
- this.logger.debug(`${opId} Load session record sessionId=${sessionWrapper.sessionId}`);
97
- const session = yield this.sermas.readSession(sessionWrapper.sessionId);
98
- if (session) {
99
- if (!sessionWrapper.appId)
100
- sessionWrapper.appId = session.appId;
101
- if (!sessionWrapper.userId)
102
- sessionWrapper.userId = session.userId;
103
- }
104
- else {
105
- this.logger.warn(`${opId} Failed to load sessionId=${sessionWrapper.sessionId}`);
106
- }
107
- }
108
- const record = {
109
- appId: sessionWrapper.appId,
110
- sessionId: sessionWrapper.sessionId,
111
- data: sessionWrapper,
112
- userId: sessionWrapper.userId || undefined,
113
- storageId,
114
- };
115
- yield this.sermas.setRecord(record);
116
- this.logger.debug(`${opId} Saved store storageId=${record.storageId} for sessionId=${record.sessionId} appId=${record.appId} userId=${record.userId}`);
117
- return sessionWrapper;
118
- }));
119
- });
120
- }
121
- saveSession(session) {
122
- return __awaiter(this, void 0, void 0, function* () {
123
- let record = yield this.sermas.getRecord(session.storageId);
124
- if (!record) {
125
- this.logger.warn(`sessionId=${session.sessionId} storageId=${session.storageId} not found, creating new record`);
126
- const newSession = yield this.loadSessionWrapper(Object.assign({}, session));
127
- record = yield this.sermas.getRecord(newSession.storageId);
128
- }
129
- if (!record) {
130
- this.logger.error(`Cannot save sessionId=${session.sessionId}, storage not found`);
131
- return null;
132
- }
133
- record.data = Object.assign(Object.assign({}, session), { storageId: record.storageId });
134
- const res = yield this.sermas.setRecord(record);
135
- this.logger.debug(`Saved record for sessionId=${record.sessionId} storageId=${record.storageId}`);
136
- return res === null || res === void 0 ? void 0 : res.data;
137
- });
138
- }
139
- getSessionWrapper(sessionId) {
140
- return __awaiter(this, void 0, void 0, function* () {
141
- if (!sessionId) {
142
- this.logger.debug(`sessionId is empty`);
143
- return;
144
- }
145
- if (!this.sessions[sessionId]) {
146
- const session = yield this.loadSessionWrapper({
147
- sessionId,
148
- });
149
- this.logger.debug(`loaded sessionId=${sessionId}`);
150
- this.sessions[sessionId] = session;
151
- }
152
- return this.sessions[sessionId];
153
- });
154
- }
155
- saveSessionWrapper(ev) {
156
- return __awaiter(this, void 0, void 0, function* () {
157
- if (!ev.appId)
158
- return;
159
- if (!ev.record.sessionId)
160
- return;
161
- if (this.sessions[ev.record.sessionId])
162
- return;
163
- const wrapper = yield this.loadSessionWrapper({
164
- userId: ev.userId,
165
- appId: ev.appId,
166
- sessionId: ev.record.sessionId,
167
- });
168
- this.sessions[wrapper.sessionId] = wrapper;
169
- this.logger.info(`Added session ${wrapper.sessionId}`);
170
- return this.sessions[wrapper.sessionId];
171
- });
172
- }
173
- }
174
- export { Store };