@vulog/aima-client 1.2.29 → 1.2.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js DELETED
@@ -1,330 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- getClient: () => getClient_default
34
- });
35
- module.exports = __toCommonJS(index_exports);
36
-
37
- // src/getClient.ts
38
- var import_axios = __toESM(require("axios"));
39
- var import_es_toolkit = require("es-toolkit");
40
- var import_lru_cache = require("lru-cache");
41
-
42
- // src/CurlHelper.ts
43
- var CurlHelper = class {
44
- request;
45
- constructor(config) {
46
- this.request = config;
47
- }
48
- getHeaders() {
49
- let { headers } = this.request;
50
- let curlHeaders = "";
51
- if (headers.hasOwnProperty("common")) {
52
- headers = this.request.headers[this.request.method];
53
- }
54
- for (const property in this.request.headers) {
55
- if (!["common", "delete", "get", "head", "patch", "post", "put"].includes(property)) {
56
- headers[property] = this.request.headers[property];
57
- }
58
- }
59
- for (const property in headers) {
60
- if ({}.hasOwnProperty.call(headers, property)) {
61
- const header = `${property}:${headers[property]}`;
62
- curlHeaders = `${curlHeaders} -H '${header}'`;
63
- }
64
- }
65
- return curlHeaders.trim();
66
- }
67
- getMethod() {
68
- return `-X ${this.request.method.toUpperCase()}`;
69
- }
70
- getBody() {
71
- if (typeof this.request.data !== "undefined" && this.request.data !== "" && this.request.data !== null && this.request.method.toUpperCase() !== "GET") {
72
- const data = typeof this.request.data === "object" || Object.prototype.toString.call(this.request.data) === "[object Array]" ? JSON.stringify(this.request.data) : this.request.data;
73
- return `--data '${data}'`.trim();
74
- }
75
- return "";
76
- }
77
- getUrl() {
78
- if (this.request.baseURL) {
79
- const baseUrl = this.request.baseURL;
80
- const { url } = this.request;
81
- const finalUrl = url.startsWith("http") ? url : `${baseUrl}/${url}`;
82
- return finalUrl.replace(/\/{2,}/g, "/").replace("http:/", "http://").replace("https:/", "https://");
83
- }
84
- return this.request.url;
85
- }
86
- getQueryString() {
87
- if (this.request.paramsSerializer) {
88
- const params2 = this.request.paramsSerializer(this.request.params);
89
- if (!params2 || params2.length === 0) return "";
90
- if (params2.startsWith("?")) return params2;
91
- return `?${params2}`;
92
- }
93
- let params = "";
94
- let i = 0;
95
- for (const param in this.request.params) {
96
- if ({}.hasOwnProperty.call(this.request.params, param)) {
97
- params += i !== 0 ? `&${param}=${this.request.params[param]}` : `?${param}=${this.request.params[param]}`;
98
- i += 1;
99
- }
100
- }
101
- return params;
102
- }
103
- getBuiltURL() {
104
- let url = this.getUrl();
105
- if (this.getQueryString() !== "") {
106
- url += this.getQueryString();
107
- }
108
- return url.trim();
109
- }
110
- generateCommand() {
111
- return `curl ${this.getMethod()} "${this.getBuiltURL()}" ${this.getHeaders()} ${this.getBody()}`.trim().replace(/\s{2,}/g, " ");
112
- }
113
- };
114
-
115
- // src/getClient.ts
116
- var clientCache = new import_lru_cache.LRUCache({ max: 100 });
117
- var tokenCache = new import_lru_cache.LRUCache({ max: 100 });
118
- var getMemoryStore = (options) => ({
119
- getToken: async () => {
120
- const log = options.onLog ?? console.log;
121
- log("getMemoryStore.getToken", options.name ?? options.fleetId);
122
- if (tokenCache.has(options.name ?? options.fleetId)) {
123
- log("getMemoryStore.getToken", tokenCache.get(options.name ?? options.fleetId));
124
- return tokenCache.get(options.name ?? options.fleetId);
125
- }
126
- return void 0;
127
- },
128
- setToken: async (token) => {
129
- const log = options.onLog ?? console.log;
130
- log("getMemoryStore.setToken", options.name ?? options.fleetId, token);
131
- tokenCache.set(options.name ?? options.fleetId, token);
132
- }
133
- });
134
- var formatError = (error) => {
135
- if (error instanceof import_axios.AxiosError) {
136
- return {
137
- originalError: error.toJSON(),
138
- formattedError: {
139
- status: error.response?.status ?? error.status,
140
- data: error.response?.data,
141
- message: error.message
142
- }
143
- };
144
- }
145
- return {
146
- formattedError: {},
147
- originalError: JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error)))
148
- };
149
- };
150
- var getClient = (options) => {
151
- if (clientCache.has(options.name ?? options.fleetId)) {
152
- const { options: cachedOptions, client: client2 } = clientCache.get(options.fleetId);
153
- if ((0, import_es_toolkit.isEqual)(cachedOptions, options)) {
154
- return client2;
155
- }
156
- }
157
- const client = import_axios.default.create({
158
- baseURL: (0, import_es_toolkit.trimEnd)(options.baseUrl, "/"),
159
- timeout: 3e4,
160
- headers: {
161
- "Cache-Control": "no-cache",
162
- "Content-Type": "application/json",
163
- "X-Api-Key": options.apiKey,
164
- "User-Agent": options.userAgent ?? `aima-node/${"1.2.29"} ${options.fleetId}`
165
- },
166
- withCredentials: false
167
- });
168
- client.clientOptions = options;
169
- const clientCredentialsAuthentification = async () => {
170
- const params = new URLSearchParams();
171
- params.append("client_id", options.clientId);
172
- params.append("client_secret", options.clientSecret);
173
- params.append("securityOptions", "SSL_OP_NO_SSLv3");
174
- params.append("grant_type", "client_credentials");
175
- const { data: token } = await import_axios.default.post(
176
- `${(0, import_es_toolkit.trimEnd)(options.baseUrl, "/")}/auth/realms/${options.fleetMaster ?? options.fleetId}/protocol/openid-connect/token`,
177
- params,
178
- {
179
- timeout: 3e4,
180
- headers: {
181
- "Content-Type": "application/x-www-form-urlencoded"
182
- },
183
- withCredentials: false
184
- }
185
- );
186
- const store = options.store ?? getMemoryStore(options);
187
- await store.setToken({
188
- accessToken: token.access_token,
189
- refreshToken: token.refresh_token
190
- });
191
- return token.access_token;
192
- };
193
- const refreshTokenAuthentification = async () => {
194
- const store = options.store ?? getMemoryStore(options);
195
- const oldToken = await store.getToken();
196
- if (!oldToken?.refreshToken) {
197
- throw new Error("No refresh token available");
198
- }
199
- const params = new URLSearchParams();
200
- params.append("client_id", options.clientId);
201
- params.append("client_secret", options.clientSecret);
202
- params.append("securityOptions", "SSL_OP_NO_SSLv3");
203
- params.append("grant_type", "refresh_token");
204
- params.append("refresh_token", oldToken.refreshToken);
205
- const { data: token } = await import_axios.default.post(
206
- `${(0, import_es_toolkit.trimEnd)(options.baseUrl, "/")}/auth/realms/${options.fleetMaster ?? options.fleetId}/protocol/openid-connect/token`,
207
- params,
208
- {
209
- timeout: 3e4,
210
- headers: {
211
- "Content-Type": "application/x-www-form-urlencoded"
212
- },
213
- withCredentials: false
214
- }
215
- );
216
- await store.setToken({
217
- accessToken: token.access_token,
218
- refreshToken: token.refresh_token
219
- });
220
- return token.access_token;
221
- };
222
- client.signInWithPassword = async (username, password) => {
223
- if (!options.secure) {
224
- throw new Error("Not secure");
225
- }
226
- const params = new URLSearchParams();
227
- params.append("client_id", options.clientId);
228
- params.append("client_secret", options.clientSecret);
229
- params.append("securityOptions", "SSL_OP_NO_SSLv3");
230
- params.append("grant_type", "password");
231
- params.append("username", username);
232
- params.append("password", password);
233
- const { data: token } = await import_axios.default.post(
234
- `${(0, import_es_toolkit.trimEnd)(options.baseUrl, "/")}/auth/realms/${options.fleetMaster ?? options.fleetId}/protocol/openid-connect/token`,
235
- params,
236
- {
237
- timeout: 3e4,
238
- headers: {
239
- "Content-Type": "application/x-www-form-urlencoded"
240
- },
241
- withCredentials: false
242
- }
243
- );
244
- const newToken = {
245
- accessToken: token.access_token,
246
- refreshToken: token.refresh_token
247
- };
248
- const store = options.store ?? getMemoryStore(options);
249
- await store.setToken(newToken);
250
- return newToken;
251
- };
252
- client.interceptors.request.use(async (request) => {
253
- const newRequest = request;
254
- const store = options.store ?? getMemoryStore(options);
255
- const token = await store.getToken();
256
- if (token?.accessToken) {
257
- newRequest.headers.Authorization = `Bearer ${token.accessToken}`;
258
- }
259
- if (options.logCurl) {
260
- const curl = new CurlHelper(newRequest).generateCommand();
261
- if (options.onLog) options.onLog({ curl, message: "getClient > Curl command" });
262
- else console.log({ curl, message: "getClient > Curl command" });
263
- }
264
- return newRequest;
265
- });
266
- let isRefreshing = false;
267
- let refreshSubscribers = [];
268
- const executorRefresh = (config) => {
269
- return new Promise((resolve, reject) => {
270
- refreshSubscribers.push((token, error) => {
271
- if (error) {
272
- reject(formatError(error));
273
- return;
274
- }
275
- resolve(client.request(config));
276
- });
277
- });
278
- };
279
- client.interceptors.response.use(
280
- (response) => {
281
- if (options.logResponse) {
282
- const finalUrl = new CurlHelper(response.config).getBuiltURL();
283
- const { data, headers } = response;
284
- const dataLog = response.config.responseType !== "arraybuffer" && response.config.responseType !== "blob" ? data : "ArrayBuffer or blob";
285
- if (options.onLog) options.onLog({ finalUrl, data: dataLog, headers, message: "getClient > Response" });
286
- else console.log({ finalUrl, data: dataLog, headers, message: "getClient > Response" });
287
- }
288
- return response;
289
- },
290
- (error) => {
291
- const { config, response: { status } = { status: 500 } } = error;
292
- const originalRequest = config;
293
- if (originalRequest.attemptCount === void 0) {
294
- originalRequest.attemptCount = 0;
295
- }
296
- if (originalRequest.attemptCount === 5) {
297
- return Promise.reject(formatError(error));
298
- }
299
- if (status === 401) {
300
- originalRequest.attemptCount += 1;
301
- if (!isRefreshing) {
302
- isRefreshing = true;
303
- let authentification;
304
- if (options.secure) {
305
- authentification = refreshTokenAuthentification;
306
- } else {
307
- authentification = clientCredentialsAuthentification;
308
- }
309
- authentification().then((accessToken) => {
310
- refreshSubscribers.forEach((cb) => cb(accessToken));
311
- }).catch((errorAuth) => {
312
- refreshSubscribers.forEach((cb) => cb(void 0, errorAuth));
313
- }).finally(() => {
314
- isRefreshing = false;
315
- refreshSubscribers = [];
316
- });
317
- }
318
- return executorRefresh(originalRequest);
319
- }
320
- return Promise.reject(formatError(error));
321
- }
322
- );
323
- clientCache.set(options.name ?? options.fleetId, { options, client });
324
- return client;
325
- };
326
- var getClient_default = getClient;
327
- // Annotate the CommonJS export names for ESM import in node:
328
- 0 && (module.exports = {
329
- getClient
330
- });
File without changes