@c-rex/core 0.1.11 → 0.1.12
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/api/cookies.js.map +1 -1
- package/dist/api/cookies.mjs.map +1 -1
- package/dist/api/rpc.js +11 -3
- package/dist/api/rpc.js.map +1 -1
- package/dist/api/rpc.mjs +11 -3
- package/dist/api/rpc.mjs.map +1 -1
- package/dist/api/token.js +32 -11
- package/dist/api/token.js.map +1 -1
- package/dist/api/token.mjs +32 -11
- package/dist/api/token.mjs.map +1 -1
- package/dist/index.d.mts +15 -4
- package/dist/index.d.ts +15 -4
- package/dist/index.js +83 -75
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +79 -74
- package/dist/index.mjs.map +1 -1
- package/dist/logger.js +11 -3
- package/dist/logger.js.map +1 -1
- package/dist/logger.mjs +11 -3
- package/dist/logger.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -31,7 +31,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
31
31
|
var index_exports = {};
|
|
32
32
|
__export(index_exports, {
|
|
33
33
|
CrexApi: () => CrexApi,
|
|
34
|
-
CrexSDK: () => CrexSDK
|
|
34
|
+
CrexSDK: () => CrexSDK,
|
|
35
|
+
getClientConfig: () => getClientConfig,
|
|
36
|
+
getServerConfig: () => getServerConfig,
|
|
37
|
+
initializeConfig: () => initializeConfig
|
|
35
38
|
});
|
|
36
39
|
module.exports = __toCommonJS(index_exports);
|
|
37
40
|
|
|
@@ -47,19 +50,12 @@ var LOG_LEVELS = {
|
|
|
47
50
|
info: 6,
|
|
48
51
|
debug: 7
|
|
49
52
|
};
|
|
50
|
-
var
|
|
51
|
-
MAX_RETRY: 3,
|
|
52
|
-
API_TIMEOUT: 1e4,
|
|
53
|
-
RETRY_DELAY: 500,
|
|
54
|
-
API_HEADERS: {
|
|
55
|
-
"content-Type": "application/json"
|
|
56
|
-
}
|
|
57
|
-
};
|
|
53
|
+
var SDK_CONFIG_KEY = "crex-sdk-config";
|
|
58
54
|
var DEFAULT_COOKIE_LIMIT = 30 * 24 * 60 * 60 * 1e3;
|
|
59
55
|
var CREX_TOKEN_HEADER_KEY = "crex-token";
|
|
60
56
|
|
|
61
57
|
// src/requests.ts
|
|
62
|
-
var
|
|
58
|
+
var import_headers2 = require("next/headers");
|
|
63
59
|
|
|
64
60
|
// src/logger.ts
|
|
65
61
|
var import_winston = __toESM(require("winston"));
|
|
@@ -142,8 +138,29 @@ var GraylogTransport = class extends import_winston_transport2.default {
|
|
|
142
138
|
}
|
|
143
139
|
};
|
|
144
140
|
|
|
141
|
+
// src/config.ts
|
|
142
|
+
var import_headers = require("next/headers");
|
|
143
|
+
var getClientConfig = () => {
|
|
144
|
+
const jsonConfigs = (0, import_headers.cookies)().get(SDK_CONFIG_KEY)?.value;
|
|
145
|
+
if (!jsonConfigs) {
|
|
146
|
+
throw new Error("Configs not found");
|
|
147
|
+
}
|
|
148
|
+
const configs = JSON.parse(jsonConfigs);
|
|
149
|
+
return configs;
|
|
150
|
+
};
|
|
151
|
+
function initializeConfig(config) {
|
|
152
|
+
if (global.__GLOBAL_CONFIG__) return global.__GLOBAL_CONFIG__;
|
|
153
|
+
global.__GLOBAL_CONFIG__ = config;
|
|
154
|
+
return global.__GLOBAL_CONFIG__;
|
|
155
|
+
}
|
|
156
|
+
function getServerConfig() {
|
|
157
|
+
if (!global.__GLOBAL_CONFIG__) {
|
|
158
|
+
throw new Error("Server config not initialized");
|
|
159
|
+
}
|
|
160
|
+
return global.__GLOBAL_CONFIG__;
|
|
161
|
+
}
|
|
162
|
+
|
|
145
163
|
// src/logger.ts
|
|
146
|
-
var import_next_cookies = require("@c-rex/utils/next-cookies");
|
|
147
164
|
var CrexLogger = class {
|
|
148
165
|
customerConfig;
|
|
149
166
|
logger;
|
|
@@ -156,13 +173,13 @@ var CrexLogger = class {
|
|
|
156
173
|
async initLogger() {
|
|
157
174
|
try {
|
|
158
175
|
if (!this.customerConfig) {
|
|
159
|
-
this.customerConfig =
|
|
176
|
+
this.customerConfig = getServerConfig();
|
|
160
177
|
}
|
|
161
178
|
if (!this.logger) {
|
|
162
179
|
this.logger = this.createLogger();
|
|
163
180
|
}
|
|
164
181
|
} catch (error) {
|
|
165
|
-
console.
|
|
182
|
+
console.log("Error initializing logger:", error);
|
|
166
183
|
}
|
|
167
184
|
}
|
|
168
185
|
/**
|
|
@@ -198,8 +215,26 @@ var CrexLogger = class {
|
|
|
198
215
|
}
|
|
199
216
|
};
|
|
200
217
|
|
|
218
|
+
// src/token.ts
|
|
219
|
+
var import_openid_client = require("openid-client");
|
|
220
|
+
var getToken = async () => {
|
|
221
|
+
console.log("veio buscar");
|
|
222
|
+
const config = getServerConfig();
|
|
223
|
+
const issuer = await import_openid_client.Issuer.discover(config.OIDC.client.issuer);
|
|
224
|
+
const client = new issuer.Client({
|
|
225
|
+
client_id: config.OIDC.client.id,
|
|
226
|
+
client_secret: config.OIDC.client.secret
|
|
227
|
+
});
|
|
228
|
+
const tokenSet = await client.grant({ grant_type: "client_credentials" });
|
|
229
|
+
const token = tokenSet.access_token;
|
|
230
|
+
const expiresAt = tokenSet.expires_at;
|
|
231
|
+
if (!token) {
|
|
232
|
+
throw new Error("Failed to get token");
|
|
233
|
+
}
|
|
234
|
+
return { token, expiresAt };
|
|
235
|
+
};
|
|
236
|
+
|
|
201
237
|
// src/requests.ts
|
|
202
|
-
var import_next_cookies2 = require("@c-rex/utils/next-cookies");
|
|
203
238
|
var CrexApi = class {
|
|
204
239
|
customerConfig;
|
|
205
240
|
apiClient;
|
|
@@ -214,10 +249,10 @@ var CrexApi = class {
|
|
|
214
249
|
async initAPI() {
|
|
215
250
|
this.logger = new CrexLogger();
|
|
216
251
|
if (!this.customerConfig) {
|
|
217
|
-
this.customerConfig =
|
|
252
|
+
this.customerConfig = getServerConfig();
|
|
218
253
|
}
|
|
219
254
|
if (!this.publicNextApiUrl) {
|
|
220
|
-
this.publicNextApiUrl =
|
|
255
|
+
this.publicNextApiUrl = "http://localhost:3002";
|
|
221
256
|
}
|
|
222
257
|
if (!this.apiClient) {
|
|
223
258
|
this.apiClient = import_axios.default.create({
|
|
@@ -225,36 +260,16 @@ var CrexApi = class {
|
|
|
225
260
|
});
|
|
226
261
|
}
|
|
227
262
|
}
|
|
228
|
-
async getToken() {
|
|
229
|
-
for (let retry = 0; retry < API.MAX_RETRY; retry++) {
|
|
230
|
-
try {
|
|
231
|
-
const response = await fetch(`${this.publicNextApiUrl}/api/token`, {
|
|
232
|
-
method: "POST",
|
|
233
|
-
credentials: "include"
|
|
234
|
-
});
|
|
235
|
-
const { token } = await response.json();
|
|
236
|
-
return token;
|
|
237
|
-
} catch (error) {
|
|
238
|
-
this.logger.log({
|
|
239
|
-
level: "error",
|
|
240
|
-
message: `utils.getToken ${retry + 1}\xBA error when request token. Error: ${error}`
|
|
241
|
-
});
|
|
242
|
-
await new Promise((resolve) => setTimeout(resolve, API.RETRY_DELAY));
|
|
243
|
-
if (retry === API.MAX_RETRY) {
|
|
244
|
-
throw error;
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
263
|
async manageToken() {
|
|
250
264
|
try {
|
|
251
265
|
let token = "";
|
|
252
|
-
const hasToken = (0,
|
|
266
|
+
const hasToken = (0, import_headers2.cookies)().get(CREX_TOKEN_HEADER_KEY);
|
|
253
267
|
if (hasToken == void 0 || hasToken.value === null) {
|
|
254
|
-
const tokenResult = await
|
|
268
|
+
const { token: tokenResult } = await getToken();
|
|
255
269
|
if (tokenResult === null) throw new Error("Token is undefined");
|
|
256
270
|
token = tokenResult;
|
|
257
271
|
} else {
|
|
272
|
+
console.log("j\xE1 tinha o token");
|
|
258
273
|
token = hasToken.value;
|
|
259
274
|
}
|
|
260
275
|
return token;
|
|
@@ -285,45 +300,35 @@ var CrexApi = class {
|
|
|
285
300
|
body,
|
|
286
301
|
headers = {}
|
|
287
302
|
}) {
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
for (let retry = 0; retry < API.MAX_RETRY; retry++) {
|
|
299
|
-
try {
|
|
300
|
-
response = await this.apiClient.request({
|
|
301
|
-
url,
|
|
302
|
-
method,
|
|
303
|
-
data: body,
|
|
304
|
-
params,
|
|
305
|
-
headers
|
|
306
|
-
});
|
|
307
|
-
break;
|
|
308
|
-
} catch (error) {
|
|
309
|
-
this.logger.log({
|
|
310
|
-
level: "error",
|
|
311
|
-
message: `API.execute ${retry + 1}\xBA error when request ${url}. Error: ${error}`
|
|
312
|
-
});
|
|
313
|
-
if (retry === API.MAX_RETRY - 1) {
|
|
314
|
-
throw error;
|
|
315
|
-
}
|
|
303
|
+
try {
|
|
304
|
+
await this.initAPI();
|
|
305
|
+
let response = void 0;
|
|
306
|
+
if (this.customerConfig.OIDC.client.enabled) {
|
|
307
|
+
const token = await this.manageToken();
|
|
308
|
+
headers = {
|
|
309
|
+
...headers,
|
|
310
|
+
Authorization: `Bearer ${token}`
|
|
311
|
+
};
|
|
312
|
+
this.apiClient.defaults.headers.common["Authorization"] = `Bearer ${token}`;
|
|
316
313
|
}
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
314
|
+
response = await this.apiClient.request({
|
|
315
|
+
url,
|
|
316
|
+
method,
|
|
317
|
+
data: body,
|
|
318
|
+
params,
|
|
319
|
+
headers
|
|
320
|
+
});
|
|
321
|
+
if (response) {
|
|
322
|
+
return response.data;
|
|
323
|
+
}
|
|
324
|
+
} catch (error) {
|
|
325
|
+
console.log("erro brabo", error);
|
|
320
326
|
}
|
|
321
327
|
throw new Error("API.execute error: Failed to retrieve a valid response");
|
|
322
328
|
}
|
|
323
329
|
};
|
|
324
330
|
|
|
325
331
|
// src/sdk.ts
|
|
326
|
-
var import_next_cookies3 = require("@c-rex/utils/next-cookies");
|
|
327
332
|
var CrexSDK = class {
|
|
328
333
|
userAuthConfig;
|
|
329
334
|
customerConfig;
|
|
@@ -332,9 +337,9 @@ var CrexSDK = class {
|
|
|
332
337
|
*
|
|
333
338
|
* @private
|
|
334
339
|
*/
|
|
335
|
-
async
|
|
340
|
+
async getServerConfig() {
|
|
336
341
|
if (!this.customerConfig) {
|
|
337
|
-
this.customerConfig =
|
|
342
|
+
this.customerConfig = getServerConfig();
|
|
338
343
|
}
|
|
339
344
|
}
|
|
340
345
|
/**
|
|
@@ -348,7 +353,7 @@ var CrexSDK = class {
|
|
|
348
353
|
if (this.userAuthConfig) {
|
|
349
354
|
return this.userAuthConfig;
|
|
350
355
|
}
|
|
351
|
-
await this.
|
|
356
|
+
await this.getServerConfig();
|
|
352
357
|
const user = this.customerConfig.OIDC.user;
|
|
353
358
|
if (user.enabled) {
|
|
354
359
|
this.userAuthConfig = {
|
|
@@ -405,6 +410,9 @@ var CrexSDK = class {
|
|
|
405
410
|
// Annotate the CommonJS export names for ESM import in node:
|
|
406
411
|
0 && (module.exports = {
|
|
407
412
|
CrexApi,
|
|
408
|
-
CrexSDK
|
|
413
|
+
CrexSDK,
|
|
414
|
+
getClientConfig,
|
|
415
|
+
getServerConfig,
|
|
416
|
+
initializeConfig
|
|
409
417
|
});
|
|
410
418
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/requests.ts","../../constants/src/index.ts","../src/logger.ts","../src/transports/matomo.ts","../src/transports/graylog.ts","../src/sdk.ts"],"sourcesContent":["//Do not export logger.ts. Logger must be exported as an another entrypoint on package.json\nexport * from \"./requests\";\nexport * from \"./sdk\";","import axios, { AxiosResponse, Method, AxiosInstance } from \"axios\";\nimport { API, CREX_TOKEN_HEADER_KEY, SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { cookies } from \"next/headers\";\nimport { CrexLogger } from \"./logger\";\nimport { getServerConfigs, getClientConfigs } from \"@c-rex/utils/next-cookies\";\n\n/**\n * Interface for API response with generic data type.\n */\ninterface APIGenericResponse<T> extends AxiosResponse {\n data: T;\n statusCode: number;\n}\n\n/**\n * Interface for API call parameters.\n */\ninterface CallParams {\n url: string;\n method: Method;\n body?: any;\n headers?: any;\n params?: any;\n}\n\n/**\n * API client class for the CREX application.\n * Handles API requests with caching, authentication, and retry logic.\n */\nexport class CrexApi {\n private customerConfig!: ConfigInterface;\n private apiClient!: AxiosInstance;\n private logger!: CrexLogger;\n private publicNextApiUrl!: string;\n\n /**\n * Initializes the API client if it hasn't been initialized yet.\n * Loads customer configuration, creates the axios instance, and initializes the logger.\n * \n * @private\n */\n private async initAPI() {\n this.logger = new CrexLogger();\n\n if (!this.customerConfig) {\n this.customerConfig = await getServerConfigs();\n }\n\n if (!this.publicNextApiUrl) {\n this.publicNextApiUrl = await getClientConfigs().publicNextApiUrl;\n }\n\n if (!this.apiClient) {\n this.apiClient = axios.create({\n baseURL: this.customerConfig.baseUrl,\n })\n }\n }\n\n private async getToken() {\n for (let retry = 0; retry < API.MAX_RETRY; retry++) {\n try {\n const response = await fetch(`${this.publicNextApiUrl}/api/token`, {\n method: 'POST',\n credentials: 'include',\n });\n\n const { token } = await response.json();\n\n return token;\n } catch (error) {\n this.logger.log({\n level: \"error\",\n message: `utils.getToken ${retry + 1}º error when request token. Error: ${error}`\n });\n\n await new Promise(resolve => setTimeout(resolve, API.RETRY_DELAY));\n\n if (retry === API.MAX_RETRY) {\n throw error;\n }\n }\n }\n }\n\n private async manageToken() {\n try {\n let token = \"\";\n const hasToken = cookies().get(CREX_TOKEN_HEADER_KEY);\n\n if (hasToken == undefined || hasToken.value === null) {\n const tokenResult = await this.getToken();\n\n if (tokenResult === null) throw new Error(\"Token is undefined\");\n\n token = tokenResult;\n } else {\n token = hasToken.value;\n }\n\n return token;\n } catch (error) {\n this.logger.log({\n level: \"error\",\n message: `CrexAPI.manageToken error: ${error}`\n });\n\n throw error\n }\n }\n\n /**\n * Executes an API request with caching, authentication, and retry logic.\n * \n * @param options - Request options\n * @param options.url - The URL to request\n * @param options.method - The HTTP method to use\n * @param options.params - Optional query parameters\n * @param options.body - Optional request body\n * @param options.headers - Optional request headers\n * @returns The response data\n * @throws Error if the request fails after maximum retries\n */\n async execute<T>({\n url,\n method,\n params,\n body,\n headers = {},\n }: CallParams): Promise<T> {\n await this.initAPI();\n\n let response: APIGenericResponse<T> | undefined = undefined;\n\n if (this.customerConfig.OIDC.client.enabled) {\n const token = await this.manageToken();\n\n headers = {\n ...headers,\n Authorization: `Bearer ${token}`,\n };\n\n this.apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`;\n }\n\n for (let retry = 0; retry < API.MAX_RETRY; retry++) {\n try {\n response = await this.apiClient.request({\n url,\n method,\n data: body,\n params,\n headers,\n });\n\n break;\n } catch (error) {\n this.logger.log({\n level: \"error\",\n message: `API.execute ${retry + 1}º error when request ${url}. Error: ${error}`\n });\n\n if (retry === API.MAX_RETRY - 1) {\n throw error;\n }\n }\n }\n\n if (response) {\n return response.data;\n }\n\n throw new Error(\"API.execute error: Failed to retrieve a valid response\");\n }\n}","export const ALL = \"*\"\n\nexport const LOG_CATEGORIES = [\n \"NoLicense\",\n \"Scenario\",\n \"Favorites\",\n \"Subscription\",\n \"Share\",\n \"Document\",\n \"Search\",\n \"History\",\n \"Notification\",\n \"UserProfile\",\n] as const;\n\nexport const LOG_LEVELS = {\n critical: 2,\n error: 3,\n warning: 4,\n info: 6,\n debug: 7,\n} as const;\n\nexport const RESULT_VIEW_STYLES = [\n \"cards\",\n \"table\",\n] as const;\n\nexport const API = {\n MAX_RETRY: 3,\n API_TIMEOUT: 10000,\n RETRY_DELAY: 500,\n API_HEADERS: {\n \"content-Type\": \"application/json\",\n },\n};\n\nexport const SDK_CONFIG_KEY = \"crex-sdk-config\";\n\nexport const CONTENT_LANG_KEY = \"CONTENT_LANG_KEY\";\n\nexport const AVAILABLE_CONTENT_LANG_KEY = \"AVAILABLE_CONTENT_LANG_KEY\";\n\nexport const UI_LANG_KEY = \"UI_LANG_KEY\";\n\nexport const FLAGS_BY_LANG = {\n \"en\": \"US\",\n \"de\": \"DE\",\n};\n\nexport const DEFAULT_LANG = \"en-US\";\n\nexport const EN_LANG = \"en\";\n\nexport const UI_LANG_OPTIONS = [\"en-us\", \"de-de\"];\n\nexport const TOPICS_TYPE_AND_LINK = \"topics\";\nexport const BLOG_TYPE_AND_LINK = \"blog\";\nexport const DOCUMENTS_TYPE_AND_LINK = \"documents\";\n\nexport const TOPIC = \"TOPIC\";\nexport const DOCUMENT = \"DOCUMENT\";\nexport const PACKAGE = \"PACKAGE\";\nexport const FRAGMENT = \"FRAGMENT\";\n\nexport const RESULT_TYPES = {\n TOPIC: TOPIC,\n DOCUMENT: DOCUMENT,\n PACKAGE: PACKAGE,\n FRAGMENT: FRAGMENT\n} as const;\n\nexport const FILES_EXTENSIONS = {\n PDF: \"application/pdf\",\n HTML: \"text/html\",\n} as const;\n\nexport const DEFAULT_COOKIE_LIMIT = 30 * 24 * 60 * 60 * 1000; // 30 days in milliseconds\n\nexport const ICONS_BY_FILE_EXTENSION = {\n \"application/pdf\": \"FaFilePdf\",\n} as const;\n\nexport const DEFAULT_ICON = \"file\";\n\nexport const CREX_TOKEN_HEADER_KEY = \"crex-token\";\n\nexport const WILD_CARD_OPTIONS = {\n BOTH: \"BOTH\",\n END: \"END\",\n START: \"START\",\n NONE: \"NONE\",\n} as const;\n\nexport const OPERATOR_OPTIONS = {\n AND: \"AND\",\n OR: \"OR\",\n} as const;\n\nexport const ARTICLE_PAGE_LAYOUT = {\n BLOG: \"BLOG\",\n DOCUMENT: \"DOCUMENT\",\n} as const;\n\nexport const DEVICE_OPTIONS = {\n MOBILE: \"mobile\",\n TABLET: \"tablet\",\n DESKTOP: \"desktop\",\n}\nexport const BREAKPOINTS = {\n sm: 640,\n md: 768,\n lg: 1024,\n xl: 1280,\n \"2xl\": 1536,\n};","import winston from \"winston\";\nimport { MatomoTransport } from \"./transports/matomo\";\nimport { GraylogTransport } from \"./transports/graylog\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { LOG_LEVELS } from \"@c-rex/constants\";\nimport { getServerConfigs } from \"@c-rex/utils/next-cookies\";\n\n/**\n * Logger class for the CREX application.\n * Provides logging functionality with multiple transports (Console, Matomo, Graylog).\n */\nexport class CrexLogger {\n private customerConfig!: ConfigInterface;\n public logger!: winston.Logger;\n\n /**\n * Initializes the logger instance if it hasn't been initialized yet.\n * Loads customer configuration and creates the logger with appropriate transports.\n * \n * @private\n */\n private async initLogger() {\n try {\n if (!this.customerConfig) {\n this.customerConfig = await getServerConfigs();\n }\n if (!this.logger) {\n this.logger = this.createLogger();\n }\n } catch (error) {\n console.error(\"Error initializing logger:\", error);\n }\n }\n\n /**\n * Logs a message with the specified level and optional category.\n * \n * @param options - Logging options\n * @param options.level - The log level (error, warn, info, etc.)\n * @param options.message - The message to log\n * @param options.category - Optional category for the log message\n */\n public async log({ level, message, category }: {\n level: LogLevelType,\n message: string,\n category?: LogCategoriesType\n }) {\n await this.initLogger();\n this.logger.log(level, message, category);\n }\n\n /**\n * Creates a new Winston logger instance with configured transports.\n * \n * @private\n * @returns A configured Winston logger instance\n */\n private createLogger() {\n return winston.createLogger({\n levels: LOG_LEVELS,\n transports: [\n new winston.transports.Console({\n level: this.customerConfig.logs.console.minimumLevel,\n silent: this.customerConfig.logs.console.silent,\n }),\n new MatomoTransport(this.customerConfig),\n new GraylogTransport(this.customerConfig),\n ],\n });\n }\n}","import Transport from \"winston-transport\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { ALL } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\n\n/**\n * Winston transport for sending logs to Matomo analytics.\n * Extends the base Winston transport with Matomo-specific functionality.\n */\nexport class MatomoTransport extends Transport {\n public matomoTransport: any;\n private configs: ConfigInterface;\n\n /**\n * Creates a new instance of MatomoTransport.\n * \n * @param configs - The application configuration containing logging settings\n */\n constructor(configs: ConfigInterface) {\n super({\n level: configs.logs.matomo.minimumLevel,\n silent: configs.logs.matomo.silent,\n });\n\n this.matomoTransport = new Transport();\n this.configs = configs;\n }\n\n /**\n * Logs a message to Matomo if the message category is included in the configured categories.\n * \n * @param info - The log information including level, message, and category\n * @param callback - Callback function to execute after logging\n */\n log(\n info: { level: LogLevelType, message: string, category: LogCategoriesType },\n callback: () => void,\n ): void {\n const matomoCategory = this.configs.logs.matomo.categoriesLevel\n\n if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {\n this.matomoTransport.log(info, callback);\n }\n }\n}\n","import Transport from \"winston-transport\";\nimport Graylog2Transport from \"winston-graylog2\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { ALL } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\n\n/**\n * Winston transport for sending logs to Graylog.\n * Extends the base Winston transport with Graylog-specific functionality.\n */\nexport class GraylogTransport extends Transport {\n public graylogTransport: any;\n private configs: ConfigInterface\n\n /**\n * Creates a new instance of GraylogTransport.\n * \n * @param configs - The application configuration containing logging settings\n */\n constructor(configs: ConfigInterface) {\n if (!configs.logs.graylog.hostname || configs.logs.graylog.port === undefined) {\n throw new Error(\"Graylog hostname and port must be defined\");\n }\n\n super({\n level: configs.logs.graylog.minimumLevel,\n silent: configs.logs.graylog.silent,\n });\n\n this.configs = configs;\n this.graylogTransport = new Graylog2Transport({\n name: configs.logs.graylog.app,\n silent: configs.logs.graylog.silent,\n handleExceptions: false,\n graylog: {\n servers: [\n { host: \"localhost\", port: 12201 },\n { host: configs.logs.graylog.hostname, port: configs.logs.graylog.port }\n ],\n },\n });\n }\n\n /**\n * Logs a message to Graylog if the message category is included in the configured categories.\n * \n * @param info - The log information including level, message, and category\n * @param callback - Callback function to execute after logging\n */\n log(\n info: { level: LogLevelType, message: string, category: LogCategoriesType },\n callback: () => void,\n ): void {\n const graylogCategory = this.configs.logs.graylog.categoriesLevel\n\n if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {\n this.graylogTransport.log(info, callback);\n }\n }\n}\n","import { getServerConfigs } from \"@c-rex/utils/next-cookies\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\n\n/**\n * SDK class for the CREX application.\n * Provides configuration and authentication functionality.\n */\nexport class CrexSDK {\n public userAuthConfig!: any;\n public customerConfig!: ConfigInterface;\n\n /**\n * Retrieves the customer configuration if it hasn't been loaded yet.\n * \n * @private\n */\n private async getConfig() {\n if (!this.customerConfig) {\n this.customerConfig = await getServerConfigs()\n }\n }\n\n /**\n * Retrieves the user authentication configuration.\n * If not already loaded, it will load the customer configuration and\n * create the auth config based on OIDC settings.\n * \n * @returns The user authentication configuration object\n */\n public async getUserAuthConfig() {\n if (this.userAuthConfig) {\n return this.userAuthConfig;\n }\n\n await this.getConfig();\n\n const user = this.customerConfig.OIDC.user;\n if (user.enabled) {\n this.userAuthConfig = {\n providers: [\n {\n id: \"crex\",\n name: \"CREX\",\n type: \"oauth\",\n version: \"2.0\",\n clientId: user.id,\n wellKnown: user.issuer,\n clientSecret: user.secret,\n authorization: {\n params: {\n scope: user.scope,\n prompt: \"login\"\n }\n },\n idToken: true,\n checks: [\"pkce\", \"state\"],\n async profile(_: any, tokens: any) {\n const res = await fetch(user.userInfoEndPoint!, {\n headers: {\n Authorization: `Bearer ${tokens.access_token}`,\n },\n });\n\n const userinfo = await res.json();\n\n return {\n id: userinfo.sub,\n name: userinfo.name,\n email: userinfo.email,\n };\n },\n callbacks: {\n async jwt({ token, account }: any) {\n if (account) {\n token.id_token = account.id_token;\n }\n return token;\n },\n async session({ session, token }: any) {\n session.id_token = token.id_token;\n return session;\n },\n }\n },\n ]\n }\n };\n\n return this.userAuthConfig;\n }\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;A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YACxB,MAAM,QAAQ,GAAQ,QAAa;AAC/B,oBAAM,MAAM,MAAM,MAAM,KAAK,kBAAmB;AAAA,gBAC5C,SAAS;AAAA,kBACL,eAAe,UAAU,OAAO,YAAY;AAAA,gBAChD;AAAA,cACJ,CAAC;AAED,oBAAM,WAAW,MAAM,IAAI,KAAK;AAEhC,qBAAO;AAAA,gBACH,IAAI,SAAS;AAAA,gBACb,MAAM,SAAS;AAAA,gBACf,OAAO,SAAS;AAAA,cACpB;AAAA,YACJ;AAAA,YACA,WAAW;AAAA,cACP,MAAM,IAAI,EAAE,OAAO,QAAQ,GAAQ;AAC/B,oBAAI,SAAS;AACT,wBAAM,WAAW,QAAQ;AAAA,gBAC7B;AACA,uBAAO;AAAA,cACX;AAAA,cACA,MAAM,QAAQ,EAAE,SAAS,MAAM,GAAQ;AACnC,wBAAQ,WAAW,MAAM;AACzB,uBAAO;AAAA,cACX;AAAA,YACJ;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAC;AAED,WAAO,KAAK;AAAA,EAChB;AACJ;","names":["Transport","import_winston_transport","Transport","Graylog2Transport","winston","import_next_cookies","axios","import_next_cookies"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/requests.ts","../../constants/src/index.ts","../src/logger.ts","../src/transports/matomo.ts","../src/transports/graylog.ts","../src/config.ts","../src/token.ts","../src/sdk.ts"],"sourcesContent":["//Do not export logger.ts. Logger must be exported as an another entrypoint on package.json\nexport * from \"./requests\";\nexport * from \"./sdk\";\nexport * from \"./config\";","import axios, { AxiosResponse, Method, AxiosInstance } from \"axios\";\nimport { CREX_TOKEN_HEADER_KEY } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { cookies } from \"next/headers\";\nimport { CrexLogger } from \"./logger\";\nimport { getServerConfig } from \"./config\";\nimport { getToken } from \"./token\";\n\n/**\n * Interface for API response with generic data type.\n */\ninterface APIGenericResponse<T> extends AxiosResponse {\n data: T;\n statusCode: number;\n}\n\n/**\n * Interface for API call parameters.\n */\ninterface CallParams {\n url: string;\n method: Method;\n body?: any;\n headers?: any;\n params?: any;\n}\n\n/**\n * API client class for the CREX application.\n * Handles API requests with caching, authentication, and retry logic.\n */\nexport class CrexApi {\n private customerConfig!: ConfigInterface;\n private apiClient!: AxiosInstance;\n private logger!: CrexLogger;\n private publicNextApiUrl!: string;\n\n /**\n * Initializes the API client if it hasn't been initialized yet.\n * Loads customer configuration, creates the axios instance, and initializes the logger.\n * \n * @private\n */\n private async initAPI() {\n this.logger = new CrexLogger();\n\n if (!this.customerConfig) {\n this.customerConfig = getServerConfig();\n }\n\n if (!this.publicNextApiUrl) {\n this.publicNextApiUrl = \"http://localhost:3002\"//getClientConfig().publicNextApiUrl;\n }\n\n if (!this.apiClient) {\n this.apiClient = axios.create({\n baseURL: this.customerConfig.baseUrl,\n })\n }\n }\n\n private async manageToken() {\n try {\n let token = \"\";\n const hasToken = cookies().get(CREX_TOKEN_HEADER_KEY);\n\n if (hasToken == undefined || hasToken.value === null) {\n const { token: tokenResult } = await getToken();\n\n if (tokenResult === null) throw new Error(\"Token is undefined\");\n\n token = tokenResult;\n } else {\n console.log(\"já tinha o token\")\n token = hasToken.value;\n }\n\n return token;\n } catch (error) {\n this.logger.log({\n level: \"error\",\n message: `CrexAPI.manageToken error: ${error}`\n });\n\n throw error\n }\n }\n\n /**\n * Executes an API request with caching, authentication, and retry logic.\n * \n * @param options - Request options\n * @param options.url - The URL to request\n * @param options.method - The HTTP method to use\n * @param options.params - Optional query parameters\n * @param options.body - Optional request body\n * @param options.headers - Optional request headers\n * @returns The response data\n * @throws Error if the request fails after maximum retries\n */\n async execute<T>({\n url,\n method,\n params,\n body,\n headers = {},\n }: CallParams): Promise<T> {\n try {\n await this.initAPI();\n\n let response: APIGenericResponse<T> | undefined = undefined;\n\n if (this.customerConfig.OIDC.client.enabled) {\n const token = await this.manageToken();\n\n headers = {\n ...headers,\n Authorization: `Bearer ${token}`,\n };\n\n this.apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`;\n }\n\n response = await this.apiClient.request({\n url,\n method,\n data: body,\n params,\n headers,\n });\n\n if (response) {\n return response.data;\n }\n } catch (error) {\n\n console.log(\"erro brabo\", error);\n\n }\n\n\n throw new Error(\"API.execute error: Failed to retrieve a valid response\");\n }\n}","export const ALL = \"*\"\n\nexport const LOG_CATEGORIES = [\n \"NoLicense\",\n \"Scenario\",\n \"Favorites\",\n \"Subscription\",\n \"Share\",\n \"Document\",\n \"Search\",\n \"History\",\n \"Notification\",\n \"UserProfile\",\n] as const;\n\nexport const LOG_LEVELS = {\n critical: 2,\n error: 3,\n warning: 4,\n info: 6,\n debug: 7,\n} as const;\n\nexport const RESULT_VIEW_STYLES = [\n \"cards\",\n \"table\",\n \"table-with-images\",\n] as const;\n\nexport const API = {\n MAX_RETRY: 3,\n API_TIMEOUT: 10000,\n RETRY_DELAY: 500,\n API_HEADERS: {\n \"content-Type\": \"application/json\",\n },\n};\n\nexport const SDK_CONFIG_KEY = \"crex-sdk-config\";\n\nexport const CONTENT_LANG_KEY = \"CONTENT_LANG_KEY\";\n\nexport const AVAILABLE_CONTENT_LANG_KEY = \"AVAILABLE_CONTENT_LANG_KEY\";\n\nexport const UI_LANG_KEY = \"UI_LANG_KEY\";\n\nexport const FLAGS_BY_LANG = {\n \"en\": \"US\",\n \"de\": \"DE\",\n};\n\nexport const DEFAULT_LANG = \"en-US\";\n\nexport const EN_LANG = \"en\";\n\nexport const UI_LANG_OPTIONS = [\"en-us\", \"de-de\"];\n\nexport const TOPICS_TYPE_AND_LINK = \"topics\";\nexport const BLOG_TYPE_AND_LINK = \"blog\";\nexport const DOCUMENTS_TYPE_AND_LINK = \"documents\";\n\nexport const TOPIC = \"TOPIC\";\nexport const DOCUMENT = \"DOCUMENT\";\nexport const PACKAGE = \"PACKAGE\";\nexport const FRAGMENT = \"FRAGMENT\";\n\nexport const RESULT_TYPES = {\n TOPIC: TOPIC,\n DOCUMENT: DOCUMENT,\n PACKAGE: PACKAGE,\n FRAGMENT: FRAGMENT\n} as const;\n\nexport const FILES_EXTENSIONS = {\n PDF: \"application/pdf\",\n HTML: \"text/html\",\n} as const;\n\nexport const DEFAULT_COOKIE_LIMIT = 30 * 24 * 60 * 60 * 1000; // 30 days in milliseconds\n\nexport const ICONS_BY_FILE_EXTENSION = {\n \"application/pdf\": \"FaFilePdf\",\n} as const;\n\nexport const DEFAULT_ICON = \"file\";\n\nexport const CREX_TOKEN_HEADER_KEY = \"crex-token\";\n\nexport const WILD_CARD_OPTIONS = {\n BOTH: \"BOTH\",\n END: \"END\",\n START: \"START\",\n NONE: \"NONE\",\n} as const;\n\nexport const OPERATOR_OPTIONS = {\n AND: \"AND\",\n OR: \"OR\",\n} as const;\n\nexport const ARTICLE_PAGE_LAYOUT = {\n BLOG: \"BLOG\",\n DOCUMENT: \"DOCUMENT\",\n} as const;\n\nexport const DEVICE_OPTIONS = {\n MOBILE: \"mobile\",\n TABLET: \"tablet\",\n DESKTOP: \"desktop\",\n}\nexport const BREAKPOINTS = {\n sm: 640,\n md: 768,\n lg: 1024,\n xl: 1280,\n \"2xl\": 1536,\n};","import winston from \"winston\";\nimport { MatomoTransport } from \"./transports/matomo\";\nimport { GraylogTransport } from \"./transports/graylog\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { LOG_LEVELS } from \"@c-rex/constants\";\nimport { getServerConfig } from \"./config\";\n\n\n/**\n * Logger class for the CREX application.\n * Provides logging functionality with multiple transports (Console, Matomo, Graylog).\n */\nexport class CrexLogger {\n private customerConfig!: ConfigInterface;\n public logger!: winston.Logger;\n\n /**\n * Initializes the logger instance if it hasn't been initialized yet.\n * Loads customer configuration and creates the logger with appropriate transports.\n * \n * @private\n */\n private async initLogger() {\n try {\n if (!this.customerConfig) {\n this.customerConfig = getServerConfig();\n }\n if (!this.logger) {\n this.logger = this.createLogger();\n }\n } catch (error) {\n console.log(\"Error initializing logger:\", error);\n }\n }\n\n /**\n * Logs a message with the specified level and optional category.\n * \n * @param options - Logging options\n * @param options.level - The log level (error, warn, info, etc.)\n * @param options.message - The message to log\n * @param options.category - Optional category for the log message\n */\n public async log({ level, message, category }: {\n level: LogLevelType,\n message: string,\n category?: LogCategoriesType\n }) {\n await this.initLogger();\n this.logger.log(level, message, category);\n }\n\n /**\n * Creates a new Winston logger instance with configured transports.\n * \n * @private\n * @returns A configured Winston logger instance\n */\n private createLogger() {\n return winston.createLogger({\n levels: LOG_LEVELS,\n transports: [\n new winston.transports.Console({\n level: this.customerConfig.logs.console.minimumLevel,\n silent: this.customerConfig.logs.console.silent,\n }),\n new MatomoTransport(this.customerConfig),\n new GraylogTransport(this.customerConfig),\n ],\n });\n }\n}","import Transport from \"winston-transport\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { ALL } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\n\n/**\n * Winston transport for sending logs to Matomo analytics.\n * Extends the base Winston transport with Matomo-specific functionality.\n */\nexport class MatomoTransport extends Transport {\n public matomoTransport: any;\n private configs: ConfigInterface;\n\n /**\n * Creates a new instance of MatomoTransport.\n * \n * @param configs - The application configuration containing logging settings\n */\n constructor(configs: ConfigInterface) {\n super({\n level: configs.logs.matomo.minimumLevel,\n silent: configs.logs.matomo.silent,\n });\n\n this.matomoTransport = new Transport();\n this.configs = configs;\n }\n\n /**\n * Logs a message to Matomo if the message category is included in the configured categories.\n * \n * @param info - The log information including level, message, and category\n * @param callback - Callback function to execute after logging\n */\n log(\n info: { level: LogLevelType, message: string, category: LogCategoriesType },\n callback: () => void,\n ): void {\n const matomoCategory = this.configs.logs.matomo.categoriesLevel\n\n if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {\n this.matomoTransport.log(info, callback);\n }\n }\n}\n","import Transport from \"winston-transport\";\nimport Graylog2Transport from \"winston-graylog2\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { ALL } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\n\n/**\n * Winston transport for sending logs to Graylog.\n * Extends the base Winston transport with Graylog-specific functionality.\n */\nexport class GraylogTransport extends Transport {\n public graylogTransport: any;\n private configs: ConfigInterface\n\n /**\n * Creates a new instance of GraylogTransport.\n * \n * @param configs - The application configuration containing logging settings\n */\n constructor(configs: ConfigInterface) {\n if (!configs.logs.graylog.hostname || configs.logs.graylog.port === undefined) {\n throw new Error(\"Graylog hostname and port must be defined\");\n }\n\n super({\n level: configs.logs.graylog.minimumLevel,\n silent: configs.logs.graylog.silent,\n });\n\n this.configs = configs;\n this.graylogTransport = new Graylog2Transport({\n name: configs.logs.graylog.app,\n silent: configs.logs.graylog.silent,\n handleExceptions: false,\n graylog: {\n servers: [\n { host: \"localhost\", port: 12201 },\n { host: configs.logs.graylog.hostname, port: configs.logs.graylog.port }\n ],\n },\n });\n }\n\n /**\n * Logs a message to Graylog if the message category is included in the configured categories.\n * \n * @param info - The log information including level, message, and category\n * @param callback - Callback function to execute after logging\n */\n log(\n info: { level: LogLevelType, message: string, category: LogCategoriesType },\n callback: () => void,\n ): void {\n const graylogCategory = this.configs.logs.graylog.categoriesLevel\n\n if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {\n this.graylogTransport.log(info, callback);\n }\n }\n}\n","import { ConfigInterface } from \"@c-rex/interfaces\";\nimport { SDK_CONFIG_KEY } from '@c-rex/constants';\nimport { CookiesConfigs } from '@c-rex/interfaces';\nimport { cookies } from 'next/headers';\n\n/**\n * Retrieves and parses configuration data from a cookie.\n * @returns The parsed configuration object\n * @throws Error if the configuration cookie is not found or cannot be parsed\n */\nexport const getClientConfig = (): CookiesConfigs => {\n const jsonConfigs = cookies().get(SDK_CONFIG_KEY)?.value;\n if (!jsonConfigs) {\n throw new Error('Configs not found');\n }\n\n const configs: CookiesConfigs = JSON.parse(jsonConfigs);\n\n return configs;\n}\n\ndeclare global {\n // eslint-disable-next-line no-var\n var __GLOBAL_CONFIG__: ConfigInterface | null;\n}\n\nexport function initializeConfig(config: ConfigInterface) {\n if (global.__GLOBAL_CONFIG__) return global.__GLOBAL_CONFIG__;\n global.__GLOBAL_CONFIG__ = config;\n return global.__GLOBAL_CONFIG__;\n}\n\nexport function getServerConfig() {\n if (!global.__GLOBAL_CONFIG__) {\n throw new Error('Server config not initialized');\n }\n return global.__GLOBAL_CONFIG__;\n}","import { Issuer } from 'openid-client';\nimport { getServerConfig } from './config';\n\n/**\n * Retrieves an access token using client credentials flow from the configured OIDC provider\n * \n * @returns NextResponse with success status or error message\n * @throws Error if token retrieval fails\n */\nexport const getToken = async (): Promise<{ token: string; expiresAt: number }> => {\n\n console.log(\"veio buscar\")\n\n const config = getServerConfig();\n\n const issuer = await Issuer.discover(config.OIDC.client.issuer);\n const client = new issuer.Client({\n client_id: config.OIDC.client.id,\n client_secret: config.OIDC.client.secret,\n });\n const tokenSet = await client.grant({ grant_type: 'client_credentials' });\n\n const token = tokenSet.access_token!;\n const expiresAt = tokenSet.expires_at!;\n\n if (!token) {\n throw new Error('Failed to get token');\n }\n\n return { token, expiresAt };\n}\n","import { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getServerConfig } from \"./config\";\n\n/**\n * SDK class for the CREX application.\n * Provides configuration and authentication functionality.\n */\nexport class CrexSDK {\n public userAuthConfig!: any;\n public customerConfig!: ConfigInterface;\n\n /**\n * Retrieves the customer configuration if it hasn't been loaded yet.\n * \n * @private\n */\n private async getServerConfig() {\n if (!this.customerConfig) {\n this.customerConfig = getServerConfig()\n }\n }\n\n /**\n * Retrieves the user authentication configuration.\n * If not already loaded, it will load the customer configuration and\n * create the auth config based on OIDC settings.\n * \n * @returns The user authentication configuration object\n */\n public async getUserAuthConfig() {\n if (this.userAuthConfig) {\n return this.userAuthConfig;\n }\n\n await this.getServerConfig();\n\n const user = this.customerConfig.OIDC.user;\n if (user.enabled) {\n this.userAuthConfig = {\n providers: [\n {\n id: \"crex\",\n name: \"CREX\",\n type: \"oauth\",\n version: \"2.0\",\n clientId: user.id,\n wellKnown: user.issuer,\n clientSecret: user.secret,\n authorization: {\n params: {\n scope: user.scope,\n prompt: \"login\"\n }\n },\n idToken: true,\n checks: [\"pkce\", \"state\"],\n async profile(_: any, tokens: any) {\n const res = await fetch(user.userInfoEndPoint!, {\n headers: {\n Authorization: `Bearer ${tokens.access_token}`,\n },\n });\n\n const userinfo = await res.json();\n\n return {\n id: userinfo.sub,\n name: userinfo.name,\n email: userinfo.email,\n };\n },\n callbacks: {\n async jwt({ token, account }: any) {\n if (account) {\n token.id_token = account.id_token;\n }\n return token;\n },\n async session({ session, token }: any) {\n session.id_token = token.id_token;\n return session;\n },\n }\n },\n ]\n }\n };\n\n return this.userAuthConfig;\n }\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAA4D;;;ACArD,IAAM,MAAM;AAeZ,IAAM,aAAa;AAAA,EACtB,UAAU;AAAA,EACV,OAAO;AAAA,EACP,SAAS;AAAA,EACT,MAAM;AAAA,EACN,OAAO;AACX;AAiBO,IAAM,iBAAiB;AAwCvB,IAAM,uBAAuB,KAAK,KAAK,KAAK,KAAK;AAQjD,IAAM,wBAAwB;;;ADnFrC,IAAAA,kBAAwB;;;AEHxB,qBAAoB;;;ACApB,+BAAsB;AASf,IAAM,kBAAN,cAA8B,yBAAAC,QAAU;AAAA,EACpC;AAAA,EACC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOR,YAAY,SAA0B;AAClC,UAAM;AAAA,MACF,OAAO,QAAQ,KAAK,OAAO;AAAA,MAC3B,QAAQ,QAAQ,KAAK,OAAO;AAAA,IAChC,CAAC;AAED,SAAK,kBAAkB,IAAI,yBAAAA,QAAU;AACrC,SAAK,UAAU;AAAA,EACnB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,IACI,MAC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A,MACJ;AAAA,IACJ;AAAC;AAED,WAAO,KAAK;AAAA,EAChB;AACJ;","names":["import_headers","Transport","import_winston_transport","Transport","Graylog2Transport","winston","axios"]}
|
package/dist/index.mjs
CHANGED
|
@@ -10,19 +10,12 @@ var LOG_LEVELS = {
|
|
|
10
10
|
info: 6,
|
|
11
11
|
debug: 7
|
|
12
12
|
};
|
|
13
|
-
var
|
|
14
|
-
MAX_RETRY: 3,
|
|
15
|
-
API_TIMEOUT: 1e4,
|
|
16
|
-
RETRY_DELAY: 500,
|
|
17
|
-
API_HEADERS: {
|
|
18
|
-
"content-Type": "application/json"
|
|
19
|
-
}
|
|
20
|
-
};
|
|
13
|
+
var SDK_CONFIG_KEY = "crex-sdk-config";
|
|
21
14
|
var DEFAULT_COOKIE_LIMIT = 30 * 24 * 60 * 60 * 1e3;
|
|
22
15
|
var CREX_TOKEN_HEADER_KEY = "crex-token";
|
|
23
16
|
|
|
24
17
|
// src/requests.ts
|
|
25
|
-
import { cookies } from "next/headers";
|
|
18
|
+
import { cookies as cookies2 } from "next/headers";
|
|
26
19
|
|
|
27
20
|
// src/logger.ts
|
|
28
21
|
import winston from "winston";
|
|
@@ -105,8 +98,29 @@ var GraylogTransport = class extends Transport2 {
|
|
|
105
98
|
}
|
|
106
99
|
};
|
|
107
100
|
|
|
101
|
+
// src/config.ts
|
|
102
|
+
import { cookies } from "next/headers";
|
|
103
|
+
var getClientConfig = () => {
|
|
104
|
+
const jsonConfigs = cookies().get(SDK_CONFIG_KEY)?.value;
|
|
105
|
+
if (!jsonConfigs) {
|
|
106
|
+
throw new Error("Configs not found");
|
|
107
|
+
}
|
|
108
|
+
const configs = JSON.parse(jsonConfigs);
|
|
109
|
+
return configs;
|
|
110
|
+
};
|
|
111
|
+
function initializeConfig(config) {
|
|
112
|
+
if (global.__GLOBAL_CONFIG__) return global.__GLOBAL_CONFIG__;
|
|
113
|
+
global.__GLOBAL_CONFIG__ = config;
|
|
114
|
+
return global.__GLOBAL_CONFIG__;
|
|
115
|
+
}
|
|
116
|
+
function getServerConfig() {
|
|
117
|
+
if (!global.__GLOBAL_CONFIG__) {
|
|
118
|
+
throw new Error("Server config not initialized");
|
|
119
|
+
}
|
|
120
|
+
return global.__GLOBAL_CONFIG__;
|
|
121
|
+
}
|
|
122
|
+
|
|
108
123
|
// src/logger.ts
|
|
109
|
-
import { getServerConfigs } from "@c-rex/utils/next-cookies";
|
|
110
124
|
var CrexLogger = class {
|
|
111
125
|
customerConfig;
|
|
112
126
|
logger;
|
|
@@ -119,13 +133,13 @@ var CrexLogger = class {
|
|
|
119
133
|
async initLogger() {
|
|
120
134
|
try {
|
|
121
135
|
if (!this.customerConfig) {
|
|
122
|
-
this.customerConfig =
|
|
136
|
+
this.customerConfig = getServerConfig();
|
|
123
137
|
}
|
|
124
138
|
if (!this.logger) {
|
|
125
139
|
this.logger = this.createLogger();
|
|
126
140
|
}
|
|
127
141
|
} catch (error) {
|
|
128
|
-
console.
|
|
142
|
+
console.log("Error initializing logger:", error);
|
|
129
143
|
}
|
|
130
144
|
}
|
|
131
145
|
/**
|
|
@@ -161,8 +175,26 @@ var CrexLogger = class {
|
|
|
161
175
|
}
|
|
162
176
|
};
|
|
163
177
|
|
|
178
|
+
// src/token.ts
|
|
179
|
+
import { Issuer } from "openid-client";
|
|
180
|
+
var getToken = async () => {
|
|
181
|
+
console.log("veio buscar");
|
|
182
|
+
const config = getServerConfig();
|
|
183
|
+
const issuer = await Issuer.discover(config.OIDC.client.issuer);
|
|
184
|
+
const client = new issuer.Client({
|
|
185
|
+
client_id: config.OIDC.client.id,
|
|
186
|
+
client_secret: config.OIDC.client.secret
|
|
187
|
+
});
|
|
188
|
+
const tokenSet = await client.grant({ grant_type: "client_credentials" });
|
|
189
|
+
const token = tokenSet.access_token;
|
|
190
|
+
const expiresAt = tokenSet.expires_at;
|
|
191
|
+
if (!token) {
|
|
192
|
+
throw new Error("Failed to get token");
|
|
193
|
+
}
|
|
194
|
+
return { token, expiresAt };
|
|
195
|
+
};
|
|
196
|
+
|
|
164
197
|
// src/requests.ts
|
|
165
|
-
import { getServerConfigs as getServerConfigs2, getClientConfigs } from "@c-rex/utils/next-cookies";
|
|
166
198
|
var CrexApi = class {
|
|
167
199
|
customerConfig;
|
|
168
200
|
apiClient;
|
|
@@ -177,10 +209,10 @@ var CrexApi = class {
|
|
|
177
209
|
async initAPI() {
|
|
178
210
|
this.logger = new CrexLogger();
|
|
179
211
|
if (!this.customerConfig) {
|
|
180
|
-
this.customerConfig =
|
|
212
|
+
this.customerConfig = getServerConfig();
|
|
181
213
|
}
|
|
182
214
|
if (!this.publicNextApiUrl) {
|
|
183
|
-
this.publicNextApiUrl =
|
|
215
|
+
this.publicNextApiUrl = "http://localhost:3002";
|
|
184
216
|
}
|
|
185
217
|
if (!this.apiClient) {
|
|
186
218
|
this.apiClient = axios.create({
|
|
@@ -188,36 +220,16 @@ var CrexApi = class {
|
|
|
188
220
|
});
|
|
189
221
|
}
|
|
190
222
|
}
|
|
191
|
-
async getToken() {
|
|
192
|
-
for (let retry = 0; retry < API.MAX_RETRY; retry++) {
|
|
193
|
-
try {
|
|
194
|
-
const response = await fetch(`${this.publicNextApiUrl}/api/token`, {
|
|
195
|
-
method: "POST",
|
|
196
|
-
credentials: "include"
|
|
197
|
-
});
|
|
198
|
-
const { token } = await response.json();
|
|
199
|
-
return token;
|
|
200
|
-
} catch (error) {
|
|
201
|
-
this.logger.log({
|
|
202
|
-
level: "error",
|
|
203
|
-
message: `utils.getToken ${retry + 1}\xBA error when request token. Error: ${error}`
|
|
204
|
-
});
|
|
205
|
-
await new Promise((resolve) => setTimeout(resolve, API.RETRY_DELAY));
|
|
206
|
-
if (retry === API.MAX_RETRY) {
|
|
207
|
-
throw error;
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
223
|
async manageToken() {
|
|
213
224
|
try {
|
|
214
225
|
let token = "";
|
|
215
|
-
const hasToken =
|
|
226
|
+
const hasToken = cookies2().get(CREX_TOKEN_HEADER_KEY);
|
|
216
227
|
if (hasToken == void 0 || hasToken.value === null) {
|
|
217
|
-
const tokenResult = await
|
|
228
|
+
const { token: tokenResult } = await getToken();
|
|
218
229
|
if (tokenResult === null) throw new Error("Token is undefined");
|
|
219
230
|
token = tokenResult;
|
|
220
231
|
} else {
|
|
232
|
+
console.log("j\xE1 tinha o token");
|
|
221
233
|
token = hasToken.value;
|
|
222
234
|
}
|
|
223
235
|
return token;
|
|
@@ -248,45 +260,35 @@ var CrexApi = class {
|
|
|
248
260
|
body,
|
|
249
261
|
headers = {}
|
|
250
262
|
}) {
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
for (let retry = 0; retry < API.MAX_RETRY; retry++) {
|
|
262
|
-
try {
|
|
263
|
-
response = await this.apiClient.request({
|
|
264
|
-
url,
|
|
265
|
-
method,
|
|
266
|
-
data: body,
|
|
267
|
-
params,
|
|
268
|
-
headers
|
|
269
|
-
});
|
|
270
|
-
break;
|
|
271
|
-
} catch (error) {
|
|
272
|
-
this.logger.log({
|
|
273
|
-
level: "error",
|
|
274
|
-
message: `API.execute ${retry + 1}\xBA error when request ${url}. Error: ${error}`
|
|
275
|
-
});
|
|
276
|
-
if (retry === API.MAX_RETRY - 1) {
|
|
277
|
-
throw error;
|
|
278
|
-
}
|
|
263
|
+
try {
|
|
264
|
+
await this.initAPI();
|
|
265
|
+
let response = void 0;
|
|
266
|
+
if (this.customerConfig.OIDC.client.enabled) {
|
|
267
|
+
const token = await this.manageToken();
|
|
268
|
+
headers = {
|
|
269
|
+
...headers,
|
|
270
|
+
Authorization: `Bearer ${token}`
|
|
271
|
+
};
|
|
272
|
+
this.apiClient.defaults.headers.common["Authorization"] = `Bearer ${token}`;
|
|
279
273
|
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
274
|
+
response = await this.apiClient.request({
|
|
275
|
+
url,
|
|
276
|
+
method,
|
|
277
|
+
data: body,
|
|
278
|
+
params,
|
|
279
|
+
headers
|
|
280
|
+
});
|
|
281
|
+
if (response) {
|
|
282
|
+
return response.data;
|
|
283
|
+
}
|
|
284
|
+
} catch (error) {
|
|
285
|
+
console.log("erro brabo", error);
|
|
283
286
|
}
|
|
284
287
|
throw new Error("API.execute error: Failed to retrieve a valid response");
|
|
285
288
|
}
|
|
286
289
|
};
|
|
287
290
|
|
|
288
291
|
// src/sdk.ts
|
|
289
|
-
import { getServerConfigs as getServerConfigs3 } from "@c-rex/utils/next-cookies";
|
|
290
292
|
var CrexSDK = class {
|
|
291
293
|
userAuthConfig;
|
|
292
294
|
customerConfig;
|
|
@@ -295,9 +297,9 @@ var CrexSDK = class {
|
|
|
295
297
|
*
|
|
296
298
|
* @private
|
|
297
299
|
*/
|
|
298
|
-
async
|
|
300
|
+
async getServerConfig() {
|
|
299
301
|
if (!this.customerConfig) {
|
|
300
|
-
this.customerConfig =
|
|
302
|
+
this.customerConfig = getServerConfig();
|
|
301
303
|
}
|
|
302
304
|
}
|
|
303
305
|
/**
|
|
@@ -311,7 +313,7 @@ var CrexSDK = class {
|
|
|
311
313
|
if (this.userAuthConfig) {
|
|
312
314
|
return this.userAuthConfig;
|
|
313
315
|
}
|
|
314
|
-
await this.
|
|
316
|
+
await this.getServerConfig();
|
|
315
317
|
const user = this.customerConfig.OIDC.user;
|
|
316
318
|
if (user.enabled) {
|
|
317
319
|
this.userAuthConfig = {
|
|
@@ -367,6 +369,9 @@ var CrexSDK = class {
|
|
|
367
369
|
};
|
|
368
370
|
export {
|
|
369
371
|
CrexApi,
|
|
370
|
-
CrexSDK
|
|
372
|
+
CrexSDK,
|
|
373
|
+
getClientConfig,
|
|
374
|
+
getServerConfig,
|
|
375
|
+
initializeConfig
|
|
371
376
|
};
|
|
372
377
|
//# sourceMappingURL=index.mjs.map
|