@c-rex/core 0.1.11 → 0.1.13

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 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
+ getClientConfig: () => getClientConfig,
35
+ getServerConfig: () => getServerConfig,
36
+ initializeConfig: () => initializeConfig,
37
+ updateConfigProp: () => updateConfigProp
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 API = {
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 import_headers = require("next/headers");
58
+ var import_headers2 = require("next/headers");
63
59
 
64
60
  // src/logger.ts
65
61
  var import_winston = __toESM(require("winston"));
@@ -122,7 +118,6 @@ var GraylogTransport = class extends import_winston_transport2.default {
122
118
  handleExceptions: false,
123
119
  graylog: {
124
120
  servers: [
125
- { host: "localhost", port: 12201 },
126
121
  { host: configs.logs.graylog.hostname, port: configs.logs.graylog.port }
127
122
  ]
128
123
  }
@@ -142,8 +137,36 @@ var GraylogTransport = class extends import_winston_transport2.default {
142
137
  }
143
138
  };
144
139
 
140
+ // src/config.ts
141
+ var import_headers = require("next/headers");
142
+ var getClientConfig = () => {
143
+ const jsonConfigs = (0, import_headers.cookies)().get(SDK_CONFIG_KEY)?.value;
144
+ if (!jsonConfigs) {
145
+ throw new Error("Configs not found");
146
+ }
147
+ const configs = JSON.parse(jsonConfigs);
148
+ return configs;
149
+ };
150
+ function initializeConfig(config) {
151
+ if (global.__GLOBAL_CONFIG__) return global.__GLOBAL_CONFIG__;
152
+ global.__GLOBAL_CONFIG__ = config;
153
+ return global.__GLOBAL_CONFIG__;
154
+ }
155
+ function getServerConfig() {
156
+ if (!global.__GLOBAL_CONFIG__) {
157
+ throw new Error("Server config not initialized");
158
+ }
159
+ return global.__GLOBAL_CONFIG__;
160
+ }
161
+ function updateConfigProp(key, value) {
162
+ if (!global.__GLOBAL_CONFIG__) {
163
+ throw new Error("Server config not initialized");
164
+ }
165
+ global.__GLOBAL_CONFIG__[key] = value;
166
+ return global.__GLOBAL_CONFIG__;
167
+ }
168
+
145
169
  // src/logger.ts
146
- var import_next_cookies = require("@c-rex/utils/next-cookies");
147
170
  var CrexLogger = class {
148
171
  customerConfig;
149
172
  logger;
@@ -156,13 +179,13 @@ var CrexLogger = class {
156
179
  async initLogger() {
157
180
  try {
158
181
  if (!this.customerConfig) {
159
- this.customerConfig = await (0, import_next_cookies.getServerConfigs)();
182
+ this.customerConfig = getServerConfig();
160
183
  }
161
184
  if (!this.logger) {
162
185
  this.logger = this.createLogger();
163
186
  }
164
187
  } catch (error) {
165
- console.error("Error initializing logger:", error);
188
+ console.log("Error initializing logger:", error);
166
189
  }
167
190
  }
168
191
  /**
@@ -175,7 +198,9 @@ var CrexLogger = class {
175
198
  */
176
199
  async log({ level, message, category }) {
177
200
  await this.initLogger();
178
- this.logger.log(level, message, category);
201
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
202
+ const newMessage = `[${timestamp}] ${message}`;
203
+ this.logger.log(level, newMessage, category);
179
204
  }
180
205
  /**
181
206
  * Creates a new Winston logger instance with configured transports.
@@ -198,13 +223,35 @@ var CrexLogger = class {
198
223
  }
199
224
  };
200
225
 
226
+ // src/OIDC.ts
227
+ var import_openid_client = require("openid-client");
228
+ var getToken = async () => {
229
+ try {
230
+ const config = getServerConfig();
231
+ const issuer = await import_openid_client.Issuer.discover(config.OIDC.client.issuer);
232
+ const client = new issuer.Client({
233
+ client_id: config.OIDC.client.id,
234
+ client_secret: config.OIDC.client.secret
235
+ });
236
+ const tokenSet = await client.grant({ grant_type: "client_credentials" });
237
+ const token = tokenSet.access_token;
238
+ const expiresAt = tokenSet.expires_at;
239
+ return { token, expiresAt };
240
+ } catch (error) {
241
+ const logger = new CrexLogger();
242
+ logger.log({
243
+ level: "error",
244
+ message: `getToken error: ${error}`
245
+ });
246
+ return { token: "", expiresAt: 0, error: JSON.stringify(error) };
247
+ }
248
+ };
249
+
201
250
  // src/requests.ts
202
- var import_next_cookies2 = require("@c-rex/utils/next-cookies");
203
251
  var CrexApi = class {
204
252
  customerConfig;
205
253
  apiClient;
206
254
  logger;
207
- publicNextApiUrl;
208
255
  /**
209
256
  * Initializes the API client if it hasn't been initialized yet.
210
257
  * Loads customer configuration, creates the axios instance, and initializes the logger.
@@ -214,10 +261,7 @@ var CrexApi = class {
214
261
  async initAPI() {
215
262
  this.logger = new CrexLogger();
216
263
  if (!this.customerConfig) {
217
- this.customerConfig = await (0, import_next_cookies2.getServerConfigs)();
218
- }
219
- if (!this.publicNextApiUrl) {
220
- this.publicNextApiUrl = await (0, import_next_cookies2.getClientConfigs)().publicNextApiUrl;
264
+ this.customerConfig = getServerConfig();
221
265
  }
222
266
  if (!this.apiClient) {
223
267
  this.apiClient = import_axios.default.create({
@@ -225,34 +269,13 @@ var CrexApi = class {
225
269
  });
226
270
  }
227
271
  }
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
272
  async manageToken() {
250
273
  try {
251
274
  let token = "";
252
- const hasToken = (0, import_headers.cookies)().get(CREX_TOKEN_HEADER_KEY);
275
+ const hasToken = (0, import_headers2.cookies)().get(CREX_TOKEN_HEADER_KEY);
253
276
  if (hasToken == void 0 || hasToken.value === null) {
254
- const tokenResult = await this.getToken();
255
- if (tokenResult === null) throw new Error("Token is undefined");
277
+ const { token: tokenResult } = await getToken();
278
+ if (tokenResult.length === 0) throw new Error("Token is undefined");
256
279
  token = tokenResult;
257
280
  } else {
258
281
  token = hasToken.value;
@@ -285,126 +308,43 @@ var CrexApi = class {
285
308
  body,
286
309
  headers = {}
287
310
  }) {
288
- await this.initAPI();
289
- let response = void 0;
290
- if (this.customerConfig.OIDC.client.enabled) {
291
- const token = await this.manageToken();
292
- headers = {
293
- ...headers,
294
- Authorization: `Bearer ${token}`
295
- };
296
- this.apiClient.defaults.headers.common["Authorization"] = `Bearer ${token}`;
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
- }
311
+ try {
312
+ await this.initAPI();
313
+ let response = void 0;
314
+ if (this.customerConfig.OIDC.client.enabled) {
315
+ const token = await this.manageToken();
316
+ headers = {
317
+ ...headers,
318
+ Authorization: `Bearer ${token}`
319
+ };
320
+ this.apiClient.defaults.headers.common["Authorization"] = `Bearer ${token}`;
316
321
  }
322
+ response = await this.apiClient.request({
323
+ url,
324
+ method,
325
+ data: body,
326
+ params,
327
+ headers
328
+ });
329
+ if (response) {
330
+ return response.data;
331
+ }
332
+ throw new Error("API.execute error: Failed to retrieve a valid response");
333
+ } catch (error) {
334
+ this.logger.log({
335
+ level: "error",
336
+ message: `CrexAPI.execute error: ${error}`
337
+ });
338
+ throw error;
317
339
  }
318
- if (response) {
319
- return response.data;
320
- }
321
- throw new Error("API.execute error: Failed to retrieve a valid response");
322
- }
323
- };
324
-
325
- // src/sdk.ts
326
- var import_next_cookies3 = require("@c-rex/utils/next-cookies");
327
- var CrexSDK = class {
328
- userAuthConfig;
329
- customerConfig;
330
- /**
331
- * Retrieves the customer configuration if it hasn't been loaded yet.
332
- *
333
- * @private
334
- */
335
- async getConfig() {
336
- if (!this.customerConfig) {
337
- this.customerConfig = await (0, import_next_cookies3.getServerConfigs)();
338
- }
339
- }
340
- /**
341
- * Retrieves the user authentication configuration.
342
- * If not already loaded, it will load the customer configuration and
343
- * create the auth config based on OIDC settings.
344
- *
345
- * @returns The user authentication configuration object
346
- */
347
- async getUserAuthConfig() {
348
- if (this.userAuthConfig) {
349
- return this.userAuthConfig;
350
- }
351
- await this.getConfig();
352
- const user = this.customerConfig.OIDC.user;
353
- if (user.enabled) {
354
- this.userAuthConfig = {
355
- providers: [
356
- {
357
- id: "crex",
358
- name: "CREX",
359
- type: "oauth",
360
- version: "2.0",
361
- clientId: user.id,
362
- wellKnown: user.issuer,
363
- clientSecret: user.secret,
364
- authorization: {
365
- params: {
366
- scope: user.scope,
367
- prompt: "login"
368
- }
369
- },
370
- idToken: true,
371
- checks: ["pkce", "state"],
372
- async profile(_, tokens) {
373
- const res = await fetch(user.userInfoEndPoint, {
374
- headers: {
375
- Authorization: `Bearer ${tokens.access_token}`
376
- }
377
- });
378
- const userinfo = await res.json();
379
- return {
380
- id: userinfo.sub,
381
- name: userinfo.name,
382
- email: userinfo.email
383
- };
384
- },
385
- callbacks: {
386
- async jwt({ token, account }) {
387
- if (account) {
388
- token.id_token = account.id_token;
389
- }
390
- return token;
391
- },
392
- async session({ session, token }) {
393
- session.id_token = token.id_token;
394
- return session;
395
- }
396
- }
397
- }
398
- ]
399
- };
400
- }
401
- ;
402
- return this.userAuthConfig;
403
340
  }
404
341
  };
405
342
  // Annotate the CommonJS export names for ESM import in node:
406
343
  0 && (module.exports = {
407
344
  CrexApi,
408
- CrexSDK
345
+ getClientConfig,
346
+ getServerConfig,
347
+ initializeConfig,
348
+ updateConfigProp
409
349
  });
410
350
  //# 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;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;AAOO,IAAM,MAAM;AAAA,EACf,WAAW;AAAA,EACX,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,IACT,gBAAgB;AAAA,EACpB;AACJ;AA0CO,IAAM,uBAAuB,KAAK,KAAK,KAAK,KAAK;AAQjD,IAAM,wBAAwB;;;ADlFrC,qBAAwB;;;AEHxB,qBAAoB;;;ACApB,+BAAsB;AASf,IAAM,kBAAN,cAA8B,yBAAAA,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,OA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;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/OIDC.ts"],"sourcesContent":["//Do not export logger.ts. Logger must be exported as an another entrypoint on package.json\nexport * from \"./requests\";\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 \"./OIDC\";\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\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\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.length === 0) 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 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\n throw new Error(\"API.execute error: Failed to retrieve a valid response\");\n } catch (error) {\n this.logger.log({\n level: \"error\",\n message: `CrexAPI.execute error: ${error}`\n });\n throw error;\n }\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};\n\nexport const MARKER_COLORS = [\n \"red-500\",\n \"orange-500\",\n \"yellow-400\",\n \"green-500\",\n \"teal-500\",\n \"blue-500\",\n \"sky-500\",\n \"purple-500\",\n \"pink-500\",\n \"gray-500\",\n \"neutral-800\",\n \"cyan-500\",\n \"lime-500\",\n \"amber-500\",\n \"indigo-500\",\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 const timestamp = new Date().toISOString();\n const newMessage = `[${timestamp}] ${message}`;\n this.logger.log(level, newMessage, 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: 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, CookiesConfigs } from \"@c-rex/interfaces\";\nimport { SDK_CONFIG_KEY } from '@c-rex/constants';\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}\n\nexport function updateConfigProp(key: keyof ConfigInterface, value: any) {\n if (!global.__GLOBAL_CONFIG__) {\n throw new Error('Server config not initialized');\n }\n global.__GLOBAL_CONFIG__[key] = value;\n return global.__GLOBAL_CONFIG__;\n}","import { Issuer } from 'openid-client';\nimport { getServerConfig } from './config';\nimport { CrexLogger } from './logger';\nimport { CrexSDK } from './sdk';\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; error?: string }> => {\n try {\n const config = getServerConfig();\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 return { token, expiresAt };\n\n } catch (error) {\n const logger = new CrexLogger()\n logger.log({\n level: \"error\",\n message: `getToken error: ${error}`\n })\n return { token: '', expiresAt: 0, error: JSON.stringify(error) };\n\n }\n}\n\nexport const getIssuerMetadata = async (): Promise<any> => {\n const sdk = new CrexSDK();\n const config = sdk.getServerConfig();\n const issuer = await Issuer.discover(config.OIDC.client.issuer);\n return issuer.metadata;\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,IAA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AA,QACA,MAAM;AAAA,QACN;AAAA,QACA;AAAA,MACJ,CAAC;AAED,UAAI,UAAU;AACV,eAAO,SAAS;AAAA,MACpB;AAEA,YAAM,IAAI,MAAM,wDAAwD;AAAA,IAC5E,SAAS,OAAO;AACZ,WAAK,OAAO,IAAI;AAAA,QACZ,OAAO;AAAA,QACP,SAAS,0BAA0B,KAAK;AAAA,MAC5C,CAAC;AACD,YAAM;AAAA,IACV;AAAA,EACJ;AACJ;","names":["import_headers","Transport","import_winston_transport","Transport","Graylog2Transport","winston","axios"]}