@c-rex/services 0.1.12 → 0.1.14

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.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { CrexApi } from '@c-rex/core';
1
+ import { CrexApi } from '@c-rex/core/requests';
2
2
  import { Method } from 'axios';
3
3
  import { informationUnitsRenditions, DirectoryNodes, DirectoryNodesResponse, informationUnitsResponse, informationUnitsItems, LanguageAndCountries, DefaultResponse, TopicsResponseItem } from '@c-rex/interfaces';
4
4
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { CrexApi } from '@c-rex/core';
1
+ import { CrexApi } from '@c-rex/core/requests';
2
2
  import { Method } from 'axios';
3
3
  import { informationUnitsRenditions, DirectoryNodes, DirectoryNodesResponse, informationUnitsResponse, informationUnitsItems, LanguageAndCountries, DefaultResponse, TopicsResponseItem } from '@c-rex/interfaces';
4
4
 
package/dist/index.js CHANGED
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,14 +15,6 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
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
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
 
30
20
  // src/index.ts
@@ -39,19 +29,10 @@ __export(index_exports, {
39
29
  });
40
30
  module.exports = __toCommonJS(index_exports);
41
31
 
42
- // ../core/src/requests.ts
43
- var import_axios = __toESM(require("axios"));
32
+ // src/baseService.ts
33
+ var import_requests = require("@c-rex/core/requests");
44
34
 
45
35
  // ../constants/src/index.ts
46
- var ALL = "*";
47
- var LOG_LEVELS = {
48
- critical: 2,
49
- error: 3,
50
- warning: 4,
51
- info: 6,
52
- debug: 7
53
- };
54
- var SDK_CONFIG_KEY = "crex-sdk-config";
55
36
  var CONTENT_LANG_KEY = "CONTENT_LANG_KEY";
56
37
  var UI_LANG_KEY = "UI_LANG_KEY";
57
38
  var FLAGS_BY_LANG = {
@@ -70,7 +51,6 @@ var RESULT_TYPES = {
70
51
  FRAGMENT
71
52
  };
72
53
  var DEFAULT_COOKIE_LIMIT = 30 * 24 * 60 * 60 * 1e3;
73
- var CREX_TOKEN_HEADER_KEY = "crex-token";
74
54
  var WILD_CARD_OPTIONS = {
75
55
  BOTH: "BOTH",
76
56
  END: "END",
@@ -82,275 +62,6 @@ var OPERATOR_OPTIONS = {
82
62
  OR: "OR"
83
63
  };
84
64
 
85
- // ../core/src/requests.ts
86
- var import_headers2 = require("next/headers");
87
-
88
- // ../core/src/logger.ts
89
- var import_winston = __toESM(require("winston"));
90
-
91
- // ../core/src/transports/matomo.ts
92
- var import_winston_transport = __toESM(require("winston-transport"));
93
- var MatomoTransport = class extends import_winston_transport.default {
94
- matomoTransport;
95
- configs;
96
- /**
97
- * Creates a new instance of MatomoTransport.
98
- *
99
- * @param configs - The application configuration containing logging settings
100
- */
101
- constructor(configs) {
102
- super({
103
- level: configs.logs.matomo.minimumLevel,
104
- silent: configs.logs.matomo.silent
105
- });
106
- this.matomoTransport = new import_winston_transport.default();
107
- this.configs = configs;
108
- }
109
- /**
110
- * Logs a message to Matomo if the message category is included in the configured categories.
111
- *
112
- * @param info - The log information including level, message, and category
113
- * @param callback - Callback function to execute after logging
114
- */
115
- log(info, callback) {
116
- const matomoCategory = this.configs.logs.matomo.categoriesLevel;
117
- if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {
118
- this.matomoTransport.log(info, callback);
119
- }
120
- }
121
- };
122
-
123
- // ../core/src/transports/graylog.ts
124
- var import_winston_transport2 = __toESM(require("winston-transport"));
125
- var import_winston_graylog2 = __toESM(require("winston-graylog2"));
126
- var GraylogTransport = class extends import_winston_transport2.default {
127
- graylogTransport;
128
- configs;
129
- /**
130
- * Creates a new instance of GraylogTransport.
131
- *
132
- * @param configs - The application configuration containing logging settings
133
- */
134
- constructor(configs) {
135
- if (!configs.logs.graylog.hostname || configs.logs.graylog.port === void 0) {
136
- throw new Error("Graylog hostname and port must be defined");
137
- }
138
- super({
139
- level: configs.logs.graylog.minimumLevel,
140
- silent: configs.logs.graylog.silent
141
- });
142
- this.configs = configs;
143
- this.graylogTransport = new import_winston_graylog2.default({
144
- name: configs.logs.graylog.app,
145
- silent: configs.logs.graylog.silent,
146
- handleExceptions: false,
147
- graylog: {
148
- servers: [
149
- { host: "localhost", port: 12201 },
150
- { host: configs.logs.graylog.hostname, port: configs.logs.graylog.port }
151
- ]
152
- }
153
- });
154
- }
155
- /**
156
- * Logs a message to Graylog if the message category is included in the configured categories.
157
- *
158
- * @param info - The log information including level, message, and category
159
- * @param callback - Callback function to execute after logging
160
- */
161
- log(info, callback) {
162
- const graylogCategory = this.configs.logs.graylog.categoriesLevel;
163
- if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {
164
- this.graylogTransport.log(info, callback);
165
- }
166
- }
167
- };
168
-
169
- // ../core/src/config.ts
170
- var import_headers = require("next/headers");
171
- var getClientConfig = () => {
172
- const jsonConfigs = (0, import_headers.cookies)().get(SDK_CONFIG_KEY)?.value;
173
- if (!jsonConfigs) {
174
- throw new Error("Configs not found");
175
- }
176
- const configs = JSON.parse(jsonConfigs);
177
- return configs;
178
- };
179
- function getServerConfig() {
180
- if (!global.__GLOBAL_CONFIG__) {
181
- throw new Error("Server config not initialized");
182
- }
183
- return global.__GLOBAL_CONFIG__;
184
- }
185
-
186
- // ../core/src/logger.ts
187
- var CrexLogger = class {
188
- customerConfig;
189
- logger;
190
- /**
191
- * Initializes the logger instance if it hasn't been initialized yet.
192
- * Loads customer configuration and creates the logger with appropriate transports.
193
- *
194
- * @private
195
- */
196
- async initLogger() {
197
- try {
198
- if (!this.customerConfig) {
199
- this.customerConfig = getServerConfig();
200
- }
201
- if (!this.logger) {
202
- this.logger = this.createLogger();
203
- }
204
- } catch (error) {
205
- console.log("Error initializing logger:", error);
206
- }
207
- }
208
- /**
209
- * Logs a message with the specified level and optional category.
210
- *
211
- * @param options - Logging options
212
- * @param options.level - The log level (error, warn, info, etc.)
213
- * @param options.message - The message to log
214
- * @param options.category - Optional category for the log message
215
- */
216
- async log({ level, message, category }) {
217
- await this.initLogger();
218
- this.logger.log(level, message, category);
219
- }
220
- /**
221
- * Creates a new Winston logger instance with configured transports.
222
- *
223
- * @private
224
- * @returns A configured Winston logger instance
225
- */
226
- createLogger() {
227
- return import_winston.default.createLogger({
228
- levels: LOG_LEVELS,
229
- transports: [
230
- new import_winston.default.transports.Console({
231
- level: this.customerConfig.logs.console.minimumLevel,
232
- silent: this.customerConfig.logs.console.silent
233
- }),
234
- new MatomoTransport(this.customerConfig),
235
- new GraylogTransport(this.customerConfig)
236
- ]
237
- });
238
- }
239
- };
240
-
241
- // ../core/src/token.ts
242
- var import_openid_client = require("openid-client");
243
- var getToken = async () => {
244
- console.log("veio buscar");
245
- const config = getServerConfig();
246
- const issuer = await import_openid_client.Issuer.discover(config.OIDC.client.issuer);
247
- const client = new issuer.Client({
248
- client_id: config.OIDC.client.id,
249
- client_secret: config.OIDC.client.secret
250
- });
251
- const tokenSet = await client.grant({ grant_type: "client_credentials" });
252
- const token = tokenSet.access_token;
253
- const expiresAt = tokenSet.expires_at;
254
- if (!token) {
255
- throw new Error("Failed to get token");
256
- }
257
- return { token, expiresAt };
258
- };
259
-
260
- // ../core/src/requests.ts
261
- var CrexApi = class {
262
- customerConfig;
263
- apiClient;
264
- logger;
265
- publicNextApiUrl;
266
- /**
267
- * Initializes the API client if it hasn't been initialized yet.
268
- * Loads customer configuration, creates the axios instance, and initializes the logger.
269
- *
270
- * @private
271
- */
272
- async initAPI() {
273
- this.logger = new CrexLogger();
274
- if (!this.customerConfig) {
275
- this.customerConfig = getServerConfig();
276
- }
277
- if (!this.publicNextApiUrl) {
278
- this.publicNextApiUrl = "http://localhost:3002";
279
- }
280
- if (!this.apiClient) {
281
- this.apiClient = import_axios.default.create({
282
- baseURL: this.customerConfig.baseUrl
283
- });
284
- }
285
- }
286
- async manageToken() {
287
- try {
288
- let token = "";
289
- const hasToken = (0, import_headers2.cookies)().get(CREX_TOKEN_HEADER_KEY);
290
- if (hasToken == void 0 || hasToken.value === null) {
291
- const { token: tokenResult } = await getToken();
292
- if (tokenResult === null) throw new Error("Token is undefined");
293
- token = tokenResult;
294
- } else {
295
- console.log("j\xE1 tinha o token");
296
- token = hasToken.value;
297
- }
298
- return token;
299
- } catch (error) {
300
- this.logger.log({
301
- level: "error",
302
- message: `CrexAPI.manageToken error: ${error}`
303
- });
304
- throw error;
305
- }
306
- }
307
- /**
308
- * Executes an API request with caching, authentication, and retry logic.
309
- *
310
- * @param options - Request options
311
- * @param options.url - The URL to request
312
- * @param options.method - The HTTP method to use
313
- * @param options.params - Optional query parameters
314
- * @param options.body - Optional request body
315
- * @param options.headers - Optional request headers
316
- * @returns The response data
317
- * @throws Error if the request fails after maximum retries
318
- */
319
- async execute({
320
- url,
321
- method,
322
- params,
323
- body,
324
- headers = {}
325
- }) {
326
- try {
327
- await this.initAPI();
328
- let response = void 0;
329
- if (this.customerConfig.OIDC.client.enabled) {
330
- const token = await this.manageToken();
331
- headers = {
332
- ...headers,
333
- Authorization: `Bearer ${token}`
334
- };
335
- this.apiClient.defaults.headers.common["Authorization"] = `Bearer ${token}`;
336
- }
337
- response = await this.apiClient.request({
338
- url,
339
- method,
340
- data: body,
341
- params,
342
- headers
343
- });
344
- if (response) {
345
- return response.data;
346
- }
347
- } catch (error) {
348
- console.log("erro brabo", error);
349
- }
350
- throw new Error("API.execute error: Failed to retrieve a valid response");
351
- }
352
- };
353
-
354
65
  // ../utils/src/utils.ts
355
66
  var getCountryCodeByLang = (lang) => {
356
67
  const mappedKeys = Object.keys(FLAGS_BY_LANG);
@@ -427,7 +138,7 @@ var BaseService = class {
427
138
  * @param endpoint - The API endpoint URL for this service
428
139
  */
429
140
  constructor(endpoint) {
430
- this.api = new CrexApi();
141
+ this.api = new import_requests.CrexApi();
431
142
  this.endpoint = endpoint;
432
143
  }
433
144
  /**
@@ -533,11 +244,13 @@ var DirectoryNodesService = class extends BaseService {
533
244
  };
534
245
 
535
246
  // src/transforms/documentTypes.ts
536
- var import_headers3 = require("next/headers");
247
+ var import_sdk = require("@c-rex/core/sdk");
248
+ var import_headers = require("next/headers");
537
249
  var transformDocumentTypes = async (data) => {
538
250
  const labels = [];
539
- const config = getClientConfig();
540
- const contentLanguage = (0, import_headers3.cookies)().get(CONTENT_LANG_KEY)?.value || config.languageSwitcher.default;
251
+ const sdk = new import_sdk.CrexSDK();
252
+ const config = sdk.getClientConfig();
253
+ const contentLanguage = (0, import_headers.cookies)().get(CONTENT_LANG_KEY)?.value || config.languageSwitcher.default;
541
254
  const language = contentLanguage.split("-")[0];
542
255
  data.items.forEach((documentItem) => {
543
256
  const label = documentItem.labels.find((item) => item.language.toLowerCase() === language.toLowerCase());
@@ -572,12 +285,14 @@ var DocumentTypesService = class extends BaseService {
572
285
  };
573
286
 
574
287
  // src/transforms/information.ts
575
- var import_headers4 = require("next/headers");
576
- var import_logger2 = require("@c-rex/core/logger");
288
+ var import_headers2 = require("next/headers");
289
+ var import_logger = require("@c-rex/core/logger");
290
+ var import_sdk2 = require("@c-rex/core/sdk");
577
291
  var transformInformationUnits = async (data) => {
578
- const logger = new import_logger2.CrexLogger();
579
- const frontEndConfig = getClientConfig();
580
- const backEndConfig = getServerConfig();
292
+ const logger = new import_logger.CrexLogger();
293
+ const sdk = new import_sdk2.CrexSDK();
294
+ const frontEndConfig = sdk.getClientConfig();
295
+ const backEndConfig = sdk.getServerConfig();
581
296
  const filteredTags = {};
582
297
  const items = data.items.map((item) => {
583
298
  const type = item.class.labels.filter((item2) => item2.language === EN_LANG)[0].value.toUpperCase();
@@ -616,7 +331,7 @@ var transformInformationUnits = async (data) => {
616
331
  };
617
332
  });
618
333
  if (data.tags) {
619
- const contentLang = ((0, import_headers4.cookies)().get(CONTENT_LANG_KEY)?.value || EN_LANG).toLowerCase();
334
+ const contentLang = ((0, import_headers2.cookies)().get(CONTENT_LANG_KEY)?.value || EN_LANG).toLowerCase();
620
335
  const splittedContentLang = contentLang.split("-")[0];
621
336
  for (const [key, value] of Object.entries(data.tags)) {
622
337
  if (!value || !value.items || value.items.length === 0) {
@@ -793,9 +508,11 @@ var InformationUnitsService = class extends BaseService {
793
508
  };
794
509
 
795
510
  // src/language.ts
511
+ var import_sdk3 = require("@c-rex/core/sdk");
796
512
  var LanguageService = class extends BaseService {
797
513
  constructor() {
798
- const configs = getClientConfig();
514
+ const sdk = new import_sdk3.CrexSDK();
515
+ const configs = sdk.getClientConfig();
799
516
  super(configs.languageSwitcher.endpoint);
800
517
  }
801
518
  /**
@@ -832,12 +549,14 @@ var LanguageService = class extends BaseService {
832
549
  };
833
550
 
834
551
  // src/transforms/topics.ts
835
- var import_headers5 = require("next/headers");
836
- var import_logger3 = require("@c-rex/core/logger");
552
+ var import_headers3 = require("next/headers");
553
+ var import_logger2 = require("@c-rex/core/logger");
554
+ var import_sdk4 = require("@c-rex/core/sdk");
837
555
  var transformTopics = async (data) => {
838
- const logger = new import_logger3.CrexLogger();
839
- const config = getClientConfig();
840
- const uiLang = ((0, import_headers5.cookies)().get(UI_LANG_KEY)?.value || config.languageSwitcher.default).toLowerCase();
556
+ const logger = new import_logger2.CrexLogger();
557
+ const sdk = new import_sdk4.CrexSDK();
558
+ const config = sdk.getClientConfig();
559
+ const uiLang = ((0, import_headers3.cookies)().get(UI_LANG_KEY)?.value || config.languageSwitcher.default).toLowerCase();
841
560
  const items = data.items.map((item) => {
842
561
  const type = item.class.labels.filter((item2) => item2.language === EN_LANG)[0].value.toUpperCase();
843
562
  let link = `/topics/${item.shortId}`;