@sermas/sermas-toolkit-node-sdk 1.0.0-alpha.32 → 1.0.0-alpha.34

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sermas/sermas-toolkit-node-sdk",
3
- "version": "1.0.0-alpha.32",
3
+ "version": "1.0.0-alpha.34",
4
4
  "description": "Sermas toolkit node SDK",
5
5
  "type": "module",
6
6
  "main": "./index.cjs",
@@ -26,7 +26,7 @@
26
26
  "dev": "tsx watch src/index.ts"
27
27
  },
28
28
  "dependencies": {
29
- "@sermas/api-client": "^1.0.0-alpha.79",
29
+ "@sermas/api-client": "^1.0.0-alpha.83",
30
30
  "axios": "^1.7.1",
31
31
  "eventemitter2": "^6.4.9",
32
32
  "openai": "^4.47.2",
package/.eslintrc.cjs DELETED
@@ -1,32 +0,0 @@
1
- module.exports = {
2
- env: {
3
- es2021: true,
4
- node: true,
5
- },
6
- extends: [
7
- "eslint:recommended",
8
- "plugin:@typescript-eslint/recommended",
9
- "plugin:prettier/recommended",
10
- ],
11
- ignorePatterns: ["dist"],
12
- overrides: [
13
- {
14
- env: {
15
- node: true,
16
- },
17
- files: [".eslintrc.{js,cjs}"],
18
- parserOptions: {
19
- sourceType: "script",
20
- },
21
- },
22
- ],
23
- parser: "@typescript-eslint/parser",
24
- parserOptions: {
25
- ecmaVersion: "latest",
26
- sourceType: "module",
27
- },
28
- plugins: ["@typescript-eslint"],
29
- rules: {
30
- "@typescript-eslint/no-explicit-any": "off",
31
- },
32
- };
@@ -1,22 +0,0 @@
1
- name: Release npm latest package
2
-
3
- on:
4
- push:
5
- tags:
6
- - 'v*.*.*'
7
-
8
- jobs:
9
- npm-release:
10
- runs-on: ubuntu-latest
11
- steps:
12
- - uses: actions/checkout@v4
13
- # Setup .npmrc file to publish to npm
14
- - uses: actions/setup-node@v3
15
- with:
16
- node-version: '20.x'
17
- registry-url: 'https://registry.npmjs.org'
18
- - run: npm install
19
- - run: npm run build
20
- - run: npm publish --access public --tag latest
21
- env:
22
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
package/.prettierrc DELETED
File without changes
@@ -1,15 +0,0 @@
1
- export const defaults = {
2
- auth: {
3
- PUBLIC_AUTH_URL: "http://172.17.0.1:8080/keycloak",
4
- PUBLIC_AUTH_REALM: "sermas-local",
5
- PRIVATE_AUTH_CLIENT_ID: "platform",
6
- PRIVATE_AUTH_CLIENT_SECRET: "platform",
7
- PRIVATE_API_BASE_URL: "http://api:3000/api",
8
- },
9
- sermas: {
10
- SERMAS_BASE_URL: "http://localhost:8080",
11
- SERMAS_CLIENT_ID: "sermas-client",
12
- SERMAS_CLIENT_SECRET: "s3cr3t",
13
- SERMAS_APPID: "sermas",
14
- },
15
- } as const;
@@ -1,35 +0,0 @@
1
- import * as fs from "fs/promises";
2
- import { Logger } from "@sermas/api-client";
3
-
4
- export { v4 as uuidv4 } from "uuid";
5
-
6
- const logger = new Logger("util");
7
-
8
- export const saveJSON = (filename: string, dataset: Record<string, unknown>) =>
9
- fs.writeFile(filename, JSON.stringify(dataset, null, 2));
10
-
11
- export const loadJSON = async <T = Record<string, unknown>>(
12
- filename: string,
13
- ) => {
14
- try {
15
- const raw = await loadFile(filename);
16
- if (raw === null) return null;
17
- return JSON.parse(raw) as T;
18
- } catch (e: unknown) {
19
- if (e instanceof Error) logger.error(`Failed to load dataset: ${e.stack}`);
20
- return null;
21
- }
22
- };
23
-
24
- export const loadFile = async (filename: string) => {
25
- try {
26
- const raw = await fs.readFile(filename);
27
- return raw.toString();
28
- } catch (e: unknown) {
29
- if (e instanceof Error) logger.error(`Failed to load dataset: ${e.stack}`);
30
- return null;
31
- }
32
- };
33
-
34
- export const saveFile = (filename: string, dataset: string | Buffer) =>
35
- fs.writeFile(filename, dataset);
@@ -1,7 +0,0 @@
1
- export interface BaseSessionWrapper {
2
- [key: string]: unknown;
3
- storageId: string;
4
- appId: string;
5
- sessionId: string;
6
- userId: string;
7
- }
package/src/index.ts DELETED
@@ -1,14 +0,0 @@
1
- export {
2
- getAvatarToken,
3
- getAvatarTokenWithClientSecret,
4
- } from "./modules/auth.js";
5
- export { OpenAIClient } from "./modules/openai.js";
6
- export { Store } from "./modules/store.js";
7
- export { UI } from "./modules/ui.js";
8
- export { Tools } from "./modules/tools.js";
9
- export { SermasApp } from "./modules/sermas.js";
10
-
11
- export type { OpenAIConfig } from "./modules/openai.js";
12
- export type { SermasConfig } from "./modules/sermas.js";
13
-
14
- export { BaseSessionWrapper } from "./dto/session.js";
@@ -1,300 +0,0 @@
1
- import axios, { isAxiosError } from "axios";
2
- import * as https from "https";
3
- import { defaults } from "../config/defaults.js";
4
- import { Logger } from "@sermas/api-client";
5
-
6
- export type AuthConfig = {
7
- PUBLIC_AUTH_URL?: string;
8
- PUBLIC_AUTH_REALM?: string;
9
- PRIVATE_AUTH_CLIENT_ID?: string;
10
- PRIVATE_AUTH_CLIENT_SECRET?: string;
11
- PRIVATE_API_BASE_URL?: string;
12
- };
13
-
14
- type TokenResponse = {
15
- accessToken: string;
16
- refreshToken: string;
17
- expiresIn: Date;
18
- };
19
-
20
- const httpsAgent = new https.Agent({
21
- rejectUnauthorized: process.env.NODE_ENV !== "development",
22
- });
23
-
24
- /**
25
- * Returns access and refresh tokens for the given appId
26
- * @param {string} appId null by default
27
- * @param {AuthConfig} authConfig
28
- */
29
- export const getAvatarToken = async (
30
- appId: string | null = null,
31
- authConfig: AuthConfig = defaults.auth,
32
- ) => {
33
- const logger = new Logger("getAvatarToken");
34
- const tokens: Record<string, TokenResponse | null> = {};
35
- let kioskToken: TokenResponse | null = null;
36
-
37
- const PUBLIC_AUTH_URL =
38
- authConfig.PUBLIC_AUTH_URL || defaults.auth.PUBLIC_AUTH_URL;
39
- const PUBLIC_AUTH_REALM =
40
- authConfig.PUBLIC_AUTH_REALM || defaults.auth.PUBLIC_AUTH_REALM;
41
- const PRIVATE_AUTH_CLIENT_ID =
42
- authConfig.PRIVATE_AUTH_CLIENT_ID || defaults.auth.PRIVATE_AUTH_CLIENT_ID;
43
- const PRIVATE_AUTH_CLIENT_SECRET =
44
- authConfig.PRIVATE_AUTH_CLIENT_SECRET ||
45
- defaults.auth.PRIVATE_AUTH_CLIENT_SECRET;
46
- const PRIVATE_API_BASE_URL =
47
- authConfig.PRIVATE_API_BASE_URL || defaults.auth.PRIVATE_API_BASE_URL;
48
-
49
- const getAvatarToken = async (appId: string | null = null) => {
50
- await getSystemAccessToken();
51
-
52
- let appToken: TokenResponse | null = null;
53
- if (appId) {
54
- appToken = await getAppAccessToken(appId);
55
- }
56
-
57
- return {
58
- ...(appToken || {}),
59
- appId,
60
- };
61
- };
62
-
63
- const getAppAccessToken = async (
64
- appId: string,
65
- clientId = "avatar",
66
- ): Promise<TokenResponse | null> => {
67
- logger.debug(`Fetch app token for appId=${appId} clientId=${clientId}`);
68
-
69
- const cacheKey = `${appId}-${clientId}`;
70
-
71
- tokens[cacheKey] = tokens[cacheKey] || null;
72
-
73
- if (tokens[cacheKey]) {
74
- const expiresIn = tokens[cacheKey]?.expiresIn;
75
- if (!expiresIn || new Date(expiresIn).getTime() - 30000 < Date.now()) {
76
- tokens[cacheKey] = null;
77
- }
78
- }
79
-
80
- if (tokens[cacheKey]) {
81
- logger.debug(`Using cached token for ${cacheKey}`);
82
- return tokens[cacheKey];
83
- }
84
-
85
- try {
86
- const url = `${PRIVATE_API_BASE_URL}/platform/token`;
87
- const data = {
88
- appId,
89
- clientId,
90
- };
91
-
92
- logger.debug(`Requesting to ${url}`);
93
- const res = await axios.post(url, data, {
94
- httpsAgent,
95
- headers: {
96
- Authorization: `Bearer ${kioskToken?.accessToken}`,
97
- },
98
- });
99
-
100
- // expires 1min before
101
- const expiresIn = res.data.expires_in * 1000;
102
- logger.debug(
103
- `Token for ${appId} expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`,
104
- );
105
-
106
- const { access_token, refresh_token } = res.data;
107
-
108
- const token = {
109
- accessToken: access_token,
110
- refreshToken: refresh_token,
111
- expiresIn: new Date(Date.now() + expiresIn),
112
- };
113
-
114
- tokens[cacheKey] = token;
115
-
116
- return token;
117
- } catch (e) {
118
- if (e instanceof Error) logger.error(`Request failed ${e?.message}`);
119
- if (isAxiosError(e)) {
120
- logger.error(e.response?.data);
121
- delete tokens[cacheKey];
122
- }
123
- }
124
- return null;
125
- };
126
-
127
- const getSystemAccessToken = async (): Promise<TokenResponse | null> => {
128
- const cacheKey = "___kiosk___";
129
-
130
- if (tokens[cacheKey]) {
131
- const expiresIn = tokens[cacheKey]?.expiresIn;
132
- if (!expiresIn || new Date(expiresIn).getTime() - 30000 < Date.now()) {
133
- tokens[cacheKey] = null;
134
- }
135
- }
136
-
137
- if (tokens[cacheKey]) return tokens[cacheKey];
138
-
139
- logger.debug(`Load kiosk access token`);
140
-
141
- const url = `${PUBLIC_AUTH_URL}/realms/${PUBLIC_AUTH_REALM}/protocol/openid-connect/token`;
142
- const data = {
143
- client_id: PRIVATE_AUTH_CLIENT_ID,
144
- client_secret: PRIVATE_AUTH_CLIENT_SECRET,
145
- grant_type: "client_credentials",
146
- };
147
-
148
- try {
149
- logger.debug(`Requesting to ${url}`);
150
- const res = await axios.post(url, data, {
151
- headers: {
152
- "Content-Type": "application/x-www-form-urlencoded",
153
- Authorization: `Bearer ${btoa(PRIVATE_AUTH_CLIENT_ID + ":" + PRIVATE_AUTH_CLIENT_SECRET)}`,
154
- },
155
- });
156
-
157
- // expires 1min before
158
- const expiresIn = res.data.expires_in * 1000;
159
- logger.debug(
160
- `kioskToken expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`,
161
- );
162
-
163
- // const access_token = await getAuthorizationToken(res.data.access_token)
164
- const { access_token, refresh_token } = res.data;
165
-
166
- kioskToken = {
167
- accessToken: access_token,
168
- refreshToken: refresh_token,
169
- expiresIn: new Date(Date.now() + expiresIn),
170
- };
171
-
172
- tokens["__kiosk"] = kioskToken;
173
-
174
- return kioskToken;
175
- } catch (e) {
176
- kioskToken = null;
177
- if (e instanceof Error) logger.error(`Request failed ${e.message}`);
178
- if (isAxiosError(e)) {
179
- logger.error(e.response?.data);
180
- }
181
- }
182
- return null;
183
- };
184
-
185
- return await getAvatarToken(appId);
186
- };
187
-
188
- /**
189
- * Returns access and refresh tokens for the given appId
190
- * @param {string} appId null by default
191
- * @param {AuthConfig} authConfig only PRIVATE_API_BASE_URL and PRIVATE_AUTH_CLIENT_ID are used
192
- * @param {string} clientSecret needed for server2server authentication
193
- */
194
- export const getAvatarTokenWithClientSecret = async (
195
- appId: string | null = null,
196
- authConfig: AuthConfig = defaults.auth,
197
- clientSecret: string = "",
198
- ) => {
199
- const logger = new Logger("getAvatarTokenWithClientSecret");
200
- const tokens: Record<string, TokenResponse | null> = {};
201
-
202
- const PRIVATE_API_BASE_URL =
203
- authConfig.PRIVATE_API_BASE_URL || defaults.auth.PRIVATE_API_BASE_URL;
204
- const PRIVATE_AUTH_CLIENT_ID =
205
- authConfig.PRIVATE_AUTH_CLIENT_ID || defaults.auth.PRIVATE_AUTH_CLIENT_ID;
206
-
207
- const getAppAccessTokenWithClientSecret = async (
208
- appId: string,
209
- clientId = "avatar",
210
- clientSecret = "",
211
- ): Promise<TokenResponse | null> => {
212
- logger.debug(
213
- `Fetch app token for appId=${appId} clientId=${clientId} clientSecret=${clientSecret}`,
214
- );
215
-
216
- const cacheKey = `${appId}-${clientId}`;
217
-
218
- tokens[cacheKey] = tokens[cacheKey] || null;
219
-
220
- if (tokens[cacheKey]) {
221
- const expiresIn = tokens[cacheKey]?.expiresIn;
222
- if (
223
- !expiresIn ||
224
- new Date(expiresIn).getTime() - 60 * 1000 < Date.now()
225
- ) {
226
- tokens[cacheKey] = null;
227
- }
228
- }
229
-
230
- if (tokens[cacheKey]) {
231
- logger.debug(`Using cached token for ${cacheKey}`);
232
- return tokens[cacheKey];
233
- }
234
-
235
- try {
236
- const url = `${PRIVATE_API_BASE_URL}/platform/token/access_token`;
237
- logger.debug(`Requesting to ${url}`);
238
- const data = {
239
- appId,
240
- clientId,
241
- clientSecret,
242
- };
243
- logger.debug(`get token from ${url}`);
244
- const res = await axios.post(url, data, {
245
- httpsAgent,
246
- });
247
-
248
- // expires 1min before
249
- const expiresIn = res.data.expires_in * 1000;
250
- logger.debug(
251
- `Token for ${appId} expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`,
252
- );
253
-
254
- const { access_token, refresh_token } = res.data;
255
-
256
- const token = {
257
- accessToken: access_token,
258
- refreshToken: refresh_token,
259
- expiresIn: new Date(Date.now() + expiresIn),
260
- };
261
-
262
- tokens[cacheKey] = token;
263
-
264
- return token;
265
- } catch (e) {
266
- if (e instanceof Error) logger.error(`Request failed ${e.message}`);
267
- if (isAxiosError(e)) {
268
- logger.error(e.response?.data);
269
- delete tokens[cacheKey];
270
- }
271
- }
272
- return null;
273
- };
274
-
275
- const getAvatarTokenWithClientSecret = async (
276
- appId: string | null = null,
277
- clientId: string = "",
278
- clientSecret = "",
279
- ) => {
280
- let appToken: TokenResponse | null = null;
281
- if (appId) {
282
- appToken = await getAppAccessTokenWithClientSecret(
283
- appId,
284
- clientId,
285
- clientSecret,
286
- );
287
- }
288
-
289
- return {
290
- ...(appToken || {}),
291
- appId,
292
- };
293
- };
294
-
295
- return await getAvatarTokenWithClientSecret(
296
- appId,
297
- PRIVATE_AUTH_CLIENT_ID,
298
- clientSecret,
299
- );
300
- };
@@ -1,69 +0,0 @@
1
- import { Logger } from "@sermas/api-client";
2
- import OpenAI, { ClientOptions } from "openai";
3
-
4
- export type OpenAIConfig = {
5
- apiKey: string;
6
- } & ClientOptions;
7
-
8
- type ChatCompletionMessage = {
9
- messages: Array<OpenAI.Chat.ChatCompletionMessageParam>;
10
- };
11
-
12
- /**
13
- * Wrapper for OpenAI client to implement sermas functionalities
14
- */
15
- class OpenAIClient {
16
- private logger = new Logger(`SERMAS SDK OpenAIClient`);
17
- private openAI: OpenAI;
18
-
19
- constructor(openAIConfig: OpenAIConfig) {
20
- if (!openAIConfig.apiKey)
21
- this.logger.warn("No API key provided for OpenAIClient");
22
- this.openAI = new OpenAI(openAIConfig);
23
- }
24
-
25
- async chat(
26
- body: string | ChatCompletionMessage,
27
- options?: OpenAI.RequestOptions<unknown>,
28
- ) {
29
- try {
30
- const result: OpenAI.Chat.ChatCompletion =
31
- await this.openAI.chat.completions.create(
32
- {
33
- model: "gpt-3.5-turbo",
34
- ...(typeof body === "string"
35
- ? { messages: [{ role: "user", content: body }] }
36
- : body),
37
- },
38
- options,
39
- );
40
- return result.choices[0].message.content;
41
- } catch (e: unknown) {
42
- if (e instanceof Error)
43
- this.logger.error(`OpenAI request failed: ${e.stack}`);
44
- return null;
45
- }
46
- }
47
-
48
- async json<T = Record<string, unknown>>(
49
- body: string | OpenAI.Chat.ChatCompletionCreateParams,
50
- options?: OpenAI.RequestOptions<unknown>,
51
- ) {
52
- let text = await this.chat(body, options);
53
- if (text === null) return;
54
- try {
55
- if (text.startsWith("```json")) {
56
- text = text.replace("```json", "").replace("```", "");
57
- }
58
-
59
- return JSON.parse(text) as T;
60
- } catch (e: unknown) {
61
- if (e instanceof Error)
62
- this.logger.error(`Failed to parse content: ${e.stack}`);
63
- this.logger.debug(`Content: ${text}`);
64
- return null;
65
- }
66
- }
67
- }
68
-
69
- export { OpenAIClient };