@c-rex/core 0.1.13 → 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.
@@ -0,0 +1,670 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/requests.ts
31
+ var requests_exports = {};
32
+ __export(requests_exports, {
33
+ CrexApi: () => CrexApi
34
+ });
35
+ module.exports = __toCommonJS(requests_exports);
36
+ var import_axios = __toESM(require("axios"));
37
+
38
+ // ../constants/src/index.ts
39
+ var ALL = "*";
40
+ var LOG_LEVELS = {
41
+ critical: 2,
42
+ error: 3,
43
+ warning: 4,
44
+ info: 6,
45
+ debug: 7
46
+ };
47
+ var SDK_CONFIG_KEY = "crex-sdk-config";
48
+ var DEFAULT_COOKIE_LIMIT = 30 * 24 * 60 * 60 * 1e3;
49
+ var CREX_TOKEN_HEADER_KEY = "crex-token";
50
+
51
+ // src/requests.ts
52
+ var import_headers2 = require("next/headers");
53
+
54
+ // src/logger.ts
55
+ var import_winston = __toESM(require("winston"));
56
+
57
+ // src/transports/matomo.ts
58
+ var import_winston_transport = __toESM(require("winston-transport"));
59
+ var MatomoTransport = class extends import_winston_transport.default {
60
+ matomoTransport;
61
+ configs;
62
+ /**
63
+ * Creates a new instance of MatomoTransport.
64
+ *
65
+ * @param configs - The application configuration containing logging settings
66
+ */
67
+ constructor(configs) {
68
+ super({
69
+ level: configs.logs.matomo.minimumLevel,
70
+ silent: configs.logs.matomo.silent
71
+ });
72
+ this.matomoTransport = new import_winston_transport.default();
73
+ this.configs = configs;
74
+ }
75
+ /**
76
+ * Logs a message to Matomo if the message category is included in the configured categories.
77
+ *
78
+ * @param info - The log information including level, message, and category
79
+ * @param callback - Callback function to execute after logging
80
+ */
81
+ log(info, callback) {
82
+ const matomoCategory = this.configs.logs.matomo.categoriesLevel;
83
+ if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {
84
+ this.matomoTransport.log(info, callback);
85
+ }
86
+ }
87
+ };
88
+
89
+ // src/transports/graylog.ts
90
+ var import_winston_transport2 = __toESM(require("winston-transport"));
91
+ var import_winston_graylog2 = __toESM(require("winston-graylog2"));
92
+ var GraylogTransport = class extends import_winston_transport2.default {
93
+ graylogTransport;
94
+ configs;
95
+ /**
96
+ * Creates a new instance of GraylogTransport.
97
+ *
98
+ * @param configs - The application configuration containing logging settings
99
+ */
100
+ constructor(configs) {
101
+ if (!configs.logs.graylog.hostname || configs.logs.graylog.port === void 0) {
102
+ throw new Error("Graylog hostname and port must be defined");
103
+ }
104
+ super({
105
+ level: configs.logs.graylog.minimumLevel,
106
+ silent: configs.logs.graylog.silent
107
+ });
108
+ this.configs = configs;
109
+ this.graylogTransport = new import_winston_graylog2.default({
110
+ name: configs.logs.graylog.app,
111
+ silent: configs.logs.graylog.silent,
112
+ handleExceptions: false,
113
+ graylog: {
114
+ servers: [
115
+ { host: configs.logs.graylog.hostname, port: configs.logs.graylog.port }
116
+ ]
117
+ }
118
+ });
119
+ }
120
+ /**
121
+ * Logs a message to Graylog if the message category is included in the configured categories.
122
+ *
123
+ * @param info - The log information including level, message, and category
124
+ * @param callback - Callback function to execute after logging
125
+ */
126
+ log(info, callback) {
127
+ const graylogCategory = this.configs.logs.graylog.categoriesLevel;
128
+ if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {
129
+ this.graylogTransport.log(info, callback);
130
+ }
131
+ }
132
+ };
133
+
134
+ // src/utils.ts
135
+ var formatIssuer = (issuer) => {
136
+ let newIssuer = issuer;
137
+ const lastChar = newIssuer.charAt(newIssuer.length - 1);
138
+ if (lastChar !== "/") {
139
+ newIssuer += "/";
140
+ }
141
+ newIssuer += ".well-known/openid-configuration";
142
+ return newIssuer;
143
+ };
144
+ var formatApiUrl = (apiUrl) => {
145
+ let newApiUrl = apiUrl;
146
+ const lastChar = newApiUrl.charAt(newApiUrl.length - 1);
147
+ if (lastChar !== "/") {
148
+ newApiUrl += "/";
149
+ }
150
+ newApiUrl += "iirds/v1/";
151
+ return newApiUrl;
152
+ };
153
+ var mergeConfigs = (defaultConfig, envVars) => {
154
+ const definedEnvVars = {};
155
+ for (const key in envVars) {
156
+ if (envVars[key] !== void 0) {
157
+ definedEnvVars[key] = envVars[key];
158
+ }
159
+ }
160
+ return {
161
+ ...defaultConfig,
162
+ ...definedEnvVars
163
+ };
164
+ };
165
+ var generateWarnings = (vars) => {
166
+ const warnings = [];
167
+ vars.forEach((variable) => {
168
+ const value = process.env[variable.key];
169
+ if (value === void 0) {
170
+ warnings.push(`Missing environment variable ${variable.key}, using default value: ${variable.default}`);
171
+ }
172
+ });
173
+ return warnings;
174
+ };
175
+ var createUserOIDCConfig = () => {
176
+ const warnings = [];
177
+ const userDefaults = {
178
+ secret: "dummy",
179
+ scope: "openid profile crex.ids.api crex.ids.api.public",
180
+ enabled: true
181
+ };
182
+ const userEnvs = {
183
+ id: process.env.CREX_IDS_ID,
184
+ secret: process.env.CREX_IDS_SECRET,
185
+ scope: process.env.CREX_IDS_USER_SCOPES,
186
+ issuer: process.env.CREX_IDS_ISSUER == void 0 ? void 0 : formatIssuer(process.env.CREX_IDS_ISSUER),
187
+ enabled: process.env.CREX_IDS_USER_LOGIN_ENABLE == void 0 ? void 0 : process.env.CREX_IDS_USER_LOGIN_ENABLE == "true"
188
+ };
189
+ const user = mergeConfigs(userDefaults, userEnvs);
190
+ if (user.enabled) {
191
+ const disableOIDCVars = [
192
+ { key: "CREX_IDS_ID", value: process.env.CREX_IDS_ID },
193
+ { key: "CREX_IDS_ISSUER", value: process.env.CREX_IDS_ISSUER }
194
+ ];
195
+ disableOIDCVars.forEach((variable) => {
196
+ if (variable.value === void 0) {
197
+ user.enabled = false;
198
+ warnings.push(`Missing environment variable ${variable.key}, disabling client and login`);
199
+ }
200
+ });
201
+ }
202
+ if (user.enabled) {
203
+ const userWarningVars = [
204
+ { key: "CREX_IDS_USER_SCOPES", default: user.scope },
205
+ { key: "CREX_IDS_SECRET", default: user.secret },
206
+ { key: "CREX_IDS_USER_LOGIN_ENABLE", default: user.enabled }
207
+ ];
208
+ const aux = generateWarnings(userWarningVars);
209
+ warnings.push(...aux);
210
+ }
211
+ return { user, warnings };
212
+ };
213
+ var createClientOIDCConfig = () => {
214
+ const warnings = [];
215
+ const clientDefault = {
216
+ secret: "dummy",
217
+ enabled: true
218
+ };
219
+ const clientEnvs = {
220
+ id: process.env.CREX_IDS_ID,
221
+ issuer: process.env.CREX_IDS_ISSUER == void 0 ? void 0 : formatIssuer(process.env.CREX_IDS_ISSUER),
222
+ secret: process.env.CREX_IDS_SECRET,
223
+ enabled: process.env.CREX_IDS_CLIENT_LOGIN_ENABLE == void 0 ? void 0 : process.env.CREX_IDS_CLIENT_LOGIN_ENABLE == "true"
224
+ };
225
+ const client = mergeConfigs(clientDefault, clientEnvs);
226
+ if (client.enabled) {
227
+ const disableOIDCVars = [
228
+ { key: "CREX_IDS_ID", value: process.env.CREX_IDS_ID },
229
+ { key: "CREX_IDS_ISSUER", value: process.env.CREX_IDS_ISSUER }
230
+ ];
231
+ disableOIDCVars.forEach((variable) => {
232
+ if (variable.value === void 0) {
233
+ client.enabled = false;
234
+ warnings.push(`Missing environment variable ${variable.key}, disabling client and login`);
235
+ }
236
+ });
237
+ }
238
+ if (client.enabled) {
239
+ const clientWarningVars = [
240
+ { key: "CREX_IDS_SECRET", default: client.secret },
241
+ { key: "CREX_IDS_CLIENT_LOGIN_ENABLE", default: client.enabled }
242
+ ];
243
+ const aux = generateWarnings(clientWarningVars);
244
+ warnings.push(...aux);
245
+ }
246
+ return { client, warnings };
247
+ };
248
+ var createConsoleLoggerConfig = () => {
249
+ const warnings = [];
250
+ const consoleLoggerDefaults = {
251
+ minimumLevel: "info",
252
+ silent: false
253
+ };
254
+ const consoleLoggerEnvs = {
255
+ minimumLevel: process.env.LOG_CONSOLE_LEVEL,
256
+ silent: process.env.LOG_CONSOLE_SILENT == void 0 ? void 0 : process.env.LOG_CONSOLE_SILENT == "true"
257
+ };
258
+ const consoleLogger = mergeConfigs(consoleLoggerDefaults, consoleLoggerEnvs);
259
+ if (consoleLogger.silent == false) {
260
+ const consoleWarningsVars = [
261
+ { key: "LOG_CONSOLE_SILENT", default: consoleLogger.silent },
262
+ { key: "LOG_CONSOLE_LEVEL", default: consoleLogger.minimumLevel }
263
+ ];
264
+ const aux = generateWarnings(consoleWarningsVars);
265
+ warnings.push(...aux);
266
+ }
267
+ return {
268
+ consoleLogger,
269
+ warnings
270
+ };
271
+ };
272
+ var createGraylogLoggerConfig = () => {
273
+ const warnings = [];
274
+ const graylogDefaults = {
275
+ app: "app name not set",
276
+ minimumLevel: "info",
277
+ silent: false,
278
+ hostname: "https://log.c-rex.net",
279
+ port: 12202,
280
+ categoriesLevel: ["NoLicense", "Scenario", "Document", "Search", "Notification", "History", "UserProfile"]
281
+ };
282
+ const graylogEnvs = {
283
+ app: process.env.LOG_GRAYLOG_APP_NAME,
284
+ silent: process.env.LOG_GRAYLOG_SILENT == void 0 ? void 0 : process.env.LOG_GRAYLOG_SILENT == "true",
285
+ hostname: process.env.LOG_GRAYLOG_HOSTNAME,
286
+ port: process.env.LOG_GRAYLOG_PORT == void 0 ? void 0 : Number(process.env.LOG_GRAYLOG_PORT),
287
+ minimumLevel: process.env.LOG_GRAYLOG_LEVEL,
288
+ categoriesLevel: process.env.LOG_GRAYLOG_CATEGORIES == void 0 ? void 0 : process.env.LOG_GRAYLOG_CATEGORIES.split(",")
289
+ };
290
+ const graylog = mergeConfigs(graylogDefaults, graylogEnvs);
291
+ if (graylog.silent == false) {
292
+ const graylogWarningVars = [
293
+ { key: "LOG_GRAYLOG_APP_NAME", default: graylog.app },
294
+ { key: "LOG_GRAYLOG_HOSTNAME", default: graylog.hostname },
295
+ { key: "LOG_GRAYLOG_LEVEL", default: graylog.minimumLevel },
296
+ { key: "LOG_GRAYLOG_SILENT", default: graylog.silent },
297
+ { key: "LOG_GRAYLOG_CATEGORIES", default: graylog.categoriesLevel },
298
+ { key: "LOG_GRAYLOG_PORT", default: graylog.port }
299
+ ];
300
+ const aux = generateWarnings(graylogWarningVars);
301
+ warnings.push(...aux);
302
+ }
303
+ return {
304
+ graylog,
305
+ warnings
306
+ };
307
+ };
308
+ var createMatomoLoggerConfig = () => {
309
+ const warnings = [];
310
+ const matomoDefaults = {
311
+ app: "NextJsProjectName",
312
+ minimumLevel: "info",
313
+ silent: true,
314
+ hostname: "",
315
+ port: 0,
316
+ categoriesLevel: ["NoLicense", "Scenario", "Document", "Search", "Notification", "History", "UserProfile"]
317
+ };
318
+ const matomoEnvs = {
319
+ app: process.env.LOG_MATOMO_APP_NAME,
320
+ silent: process.env.LOG_MATOMO_SILENT == void 0 ? void 0 : process.env.LOG_MATOMO_SILENT == "true",
321
+ hostname: process.env.LOG_MATOMO_HOSTNAME,
322
+ port: process.env.LOG_MATOMO_PORT == void 0 ? void 0 : Number(process.env.LOG_MATOMO_PORT),
323
+ minimumLevel: process.env.LOG_MATOMO_LEVEL,
324
+ categoriesLevel: process.env.LOG_MATOMO_CATEGORIES == void 0 ? void 0 : process.env.LOG_MATOMO_CATEGORIES.split(",")
325
+ };
326
+ const matomo = mergeConfigs(matomoDefaults, matomoEnvs);
327
+ const matomoSilentVars = [
328
+ { key: "LOG_MATOMO_SILENT", value: process.env.LOG_MATOMO_SILENT },
329
+ { key: "LOG_MATOMO_HOSTNAME", value: process.env.LOG_MATOMO_HOSTNAME },
330
+ { key: "LOG_MATOMO_PORT", value: process.env.LOG_MATOMO_PORT }
331
+ ];
332
+ matomoSilentVars.forEach((variable) => {
333
+ if (variable.value === void 0) {
334
+ matomo.silent = true;
335
+ warnings.push(`Missing environment variable ${variable.key}, setting matomo logger to silent`);
336
+ }
337
+ });
338
+ if (matomo.silent == false) {
339
+ const matomoWarningVars = [
340
+ { key: "LOG_MATOMO_APP_NAME", default: matomo.app },
341
+ { key: "LOG_MATOMO_LEVEL", default: matomo.minimumLevel },
342
+ { key: "LOG_MATOMO_CATEGORIES", default: matomo.categoriesLevel }
343
+ ];
344
+ const aux = generateWarnings(matomoWarningVars);
345
+ warnings.push(...aux);
346
+ }
347
+ return {
348
+ matomo,
349
+ warnings
350
+ };
351
+ };
352
+
353
+ // src/sdk.ts
354
+ var import_headers = require("next/headers");
355
+ var CrexSDK = class {
356
+ userAuthConfig;
357
+ customerConfig;
358
+ cookiesConfig;
359
+ async getUserAuthConfig() {
360
+ if (this.userAuthConfig) {
361
+ return this.userAuthConfig;
362
+ }
363
+ if (!this.customerConfig) {
364
+ this.customerConfig = this.getServerConfig();
365
+ }
366
+ const user = this.customerConfig.OIDC.user;
367
+ const userInfoEndPoint = this.customerConfig.OIDC.issuerMetadata?.userinfo_endpoint;
368
+ if (user.enabled) {
369
+ this.userAuthConfig = {
370
+ providers: [
371
+ {
372
+ id: "crex",
373
+ name: "CREX",
374
+ type: "oauth",
375
+ version: "2.0",
376
+ clientId: user.id,
377
+ wellKnown: user.issuer,
378
+ clientSecret: user.secret,
379
+ authorization: {
380
+ params: {
381
+ scope: user.scope,
382
+ prompt: "login"
383
+ }
384
+ },
385
+ idToken: true,
386
+ checks: ["pkce", "state"],
387
+ async profile(_, tokens) {
388
+ const res = await fetch(userInfoEndPoint, {
389
+ headers: {
390
+ Authorization: `Bearer ${tokens.access_token}`
391
+ }
392
+ });
393
+ const userinfo = await res.json();
394
+ return {
395
+ id: userinfo.sub,
396
+ name: userinfo.name,
397
+ email: userinfo.email
398
+ };
399
+ },
400
+ callbacks: {
401
+ async jwt({ token, account }) {
402
+ if (account) {
403
+ token.id_token = account.id_token;
404
+ }
405
+ return token;
406
+ },
407
+ async session({ session, token }) {
408
+ session.id_token = token.id_token;
409
+ return session;
410
+ }
411
+ }
412
+ }
413
+ ]
414
+ };
415
+ }
416
+ ;
417
+ return this.userAuthConfig;
418
+ }
419
+ createCustomerConfig(CUSTOMER_CONFIG, shouldLog) {
420
+ const requiredEnvVars = ["CREX_API_URL", "NEXT_PUBLIC_API_URL"];
421
+ const required = requiredEnvVars.map((key) => {
422
+ const value = process.env[key];
423
+ if (value === void 0) {
424
+ return `Missing required environment variable: ${key}`;
425
+ }
426
+ return "";
427
+ }).filter((item) => item.length > 0);
428
+ const { user, warnings: userWarnings } = createUserOIDCConfig();
429
+ const { client, warnings: clientWarnings } = createClientOIDCConfig();
430
+ const { matomo, warnings: matomoWarnings } = createMatomoLoggerConfig();
431
+ const { graylog, warnings: graylogWarnings } = createGraylogLoggerConfig();
432
+ const { consoleLogger, warnings: consoleWarnings } = createConsoleLoggerConfig();
433
+ const warnings = required.concat(
434
+ consoleWarnings,
435
+ clientWarnings,
436
+ userWarnings,
437
+ graylogWarnings,
438
+ matomoWarnings
439
+ );
440
+ if (shouldLog) {
441
+ if (warnings.length > 0) console.warn(warnings.join("\n"));
442
+ }
443
+ const cookiesConfig = {
444
+ publicNextApiUrl: process.env.NEXT_PUBLIC_API_URL,
445
+ ...CUSTOMER_CONFIG,
446
+ OIDC: {
447
+ clientEnabled: client.enabled,
448
+ userEnabled: user.enabled
449
+ }
450
+ };
451
+ const config = {
452
+ baseUrl: process.env.CREX_API_URL == void 0 ? "" : formatApiUrl(process.env.CREX_API_URL),
453
+ OIDC: { client, user },
454
+ logs: { console: consoleLogger, graylog, matomo },
455
+ ...CUSTOMER_CONFIG
456
+ };
457
+ return { cookiesConfig, config };
458
+ }
459
+ getClientConfig = () => {
460
+ const jsonConfigs = (0, import_headers.cookies)().get(SDK_CONFIG_KEY)?.value;
461
+ if (!jsonConfigs) {
462
+ throw new Error("Configs not found");
463
+ }
464
+ const configs = JSON.parse(jsonConfigs);
465
+ return configs;
466
+ };
467
+ getServerConfig() {
468
+ if (!global.__GLOBAL_CONFIG__) {
469
+ throw new Error("Server config not initialized");
470
+ }
471
+ return global.__GLOBAL_CONFIG__;
472
+ }
473
+ initializeConfig(config) {
474
+ if (global.__GLOBAL_CONFIG__) return global.__GLOBAL_CONFIG__;
475
+ global.__GLOBAL_CONFIG__ = config;
476
+ return global.__GLOBAL_CONFIG__;
477
+ }
478
+ updateConfigProp(key, value) {
479
+ if (!global.__GLOBAL_CONFIG__) {
480
+ throw new Error("Server config not initialized");
481
+ }
482
+ global.__GLOBAL_CONFIG__[key] = value;
483
+ return global.__GLOBAL_CONFIG__;
484
+ }
485
+ };
486
+
487
+ // src/logger.ts
488
+ var CrexLogger = class {
489
+ customerConfig;
490
+ logger;
491
+ /**
492
+ * Initializes the logger instance if it hasn't been initialized yet.
493
+ * Loads customer configuration and creates the logger with appropriate transports.
494
+ *
495
+ * @private
496
+ */
497
+ async initLogger() {
498
+ try {
499
+ if (!this.customerConfig) {
500
+ const sdk = new CrexSDK();
501
+ this.customerConfig = sdk.getServerConfig();
502
+ }
503
+ if (!this.logger) {
504
+ this.logger = this.createLogger();
505
+ }
506
+ } catch (error) {
507
+ console.log("Error initializing logger:", error);
508
+ }
509
+ }
510
+ /**
511
+ * Logs a message with the specified level and optional category.
512
+ *
513
+ * @param options - Logging options
514
+ * @param options.level - The log level (error, warn, info, etc.)
515
+ * @param options.message - The message to log
516
+ * @param options.category - Optional category for the log message
517
+ */
518
+ async log({ level, message, category }) {
519
+ await this.initLogger();
520
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
521
+ const newMessage = `[${timestamp}] ${message}`;
522
+ this.logger.log(level, newMessage, category);
523
+ }
524
+ /**
525
+ * Creates a new Winston logger instance with configured transports.
526
+ *
527
+ * @private
528
+ * @returns A configured Winston logger instance
529
+ */
530
+ createLogger() {
531
+ return import_winston.default.createLogger({
532
+ levels: LOG_LEVELS,
533
+ transports: [
534
+ new import_winston.default.transports.Console({
535
+ level: this.customerConfig.logs.console.minimumLevel,
536
+ silent: this.customerConfig.logs.console.silent
537
+ }),
538
+ new MatomoTransport(this.customerConfig),
539
+ new GraylogTransport(this.customerConfig)
540
+ ]
541
+ });
542
+ }
543
+ };
544
+
545
+ // src/OIDC.ts
546
+ var import_openid_client = require("openid-client");
547
+ var getToken = async () => {
548
+ try {
549
+ const sdk = new CrexSDK();
550
+ const config = sdk.getServerConfig();
551
+ const issuer = await import_openid_client.Issuer.discover(config.OIDC.client.issuer);
552
+ const client = new issuer.Client({
553
+ client_id: config.OIDC.client.id,
554
+ client_secret: config.OIDC.client.secret
555
+ });
556
+ const tokenSet = await client.grant({ grant_type: "client_credentials" });
557
+ const token = tokenSet.access_token;
558
+ const expiresAt = tokenSet.expires_at;
559
+ return { token, expiresAt };
560
+ } catch (error) {
561
+ const logger = new CrexLogger();
562
+ logger.log({
563
+ level: "error",
564
+ message: `getToken error: ${error}`
565
+ });
566
+ return { token: "", expiresAt: 0, error: JSON.stringify(error) };
567
+ }
568
+ };
569
+
570
+ // src/requests.ts
571
+ var CrexApi = class {
572
+ customerConfig;
573
+ apiClient;
574
+ logger;
575
+ /**
576
+ * Initializes the API client if it hasn't been initialized yet.
577
+ * Loads customer configuration, creates the axios instance, and initializes the logger.
578
+ *
579
+ * @private
580
+ */
581
+ async initAPI() {
582
+ this.logger = new CrexLogger();
583
+ if (!this.customerConfig) {
584
+ const sdk = new CrexSDK();
585
+ this.customerConfig = sdk.getServerConfig();
586
+ }
587
+ if (!this.apiClient) {
588
+ if (this.customerConfig.baseUrl.length === 0) {
589
+ throw new Error("CrexAPI.initAPI error: baseUrl is undefined");
590
+ }
591
+ this.apiClient = import_axios.default.create({
592
+ baseURL: this.customerConfig.baseUrl
593
+ });
594
+ }
595
+ }
596
+ async manageToken() {
597
+ try {
598
+ let token = "";
599
+ const hasToken = (0, import_headers2.cookies)().get(CREX_TOKEN_HEADER_KEY);
600
+ if (hasToken == void 0 || hasToken.value === null) {
601
+ const { token: tokenResult } = await getToken();
602
+ if (tokenResult.length === 0) throw new Error("Token is undefined");
603
+ token = tokenResult;
604
+ } else {
605
+ token = hasToken.value;
606
+ }
607
+ return token;
608
+ } catch (error) {
609
+ this.logger.log({
610
+ level: "error",
611
+ message: `CrexAPI.manageToken error: ${error}`
612
+ });
613
+ throw error;
614
+ }
615
+ }
616
+ /**
617
+ * Executes an API request with caching, authentication, and retry logic.
618
+ *
619
+ * @param options - Request options
620
+ * @param options.url - The URL to request
621
+ * @param options.method - The HTTP method to use
622
+ * @param options.params - Optional query parameters
623
+ * @param options.body - Optional request body
624
+ * @param options.headers - Optional request headers
625
+ * @returns The response data
626
+ * @throws Error if the request fails after maximum retries
627
+ */
628
+ async execute({
629
+ url,
630
+ method,
631
+ params,
632
+ body,
633
+ headers = {}
634
+ }) {
635
+ try {
636
+ await this.initAPI();
637
+ let response = void 0;
638
+ if (this.customerConfig.OIDC.client.enabled) {
639
+ const token = await this.manageToken();
640
+ headers = {
641
+ ...headers,
642
+ Authorization: `Bearer ${token}`
643
+ };
644
+ this.apiClient.defaults.headers.common["Authorization"] = `Bearer ${token}`;
645
+ }
646
+ response = await this.apiClient.request({
647
+ url,
648
+ method,
649
+ data: body,
650
+ params,
651
+ headers
652
+ });
653
+ if (response) {
654
+ return response.data;
655
+ }
656
+ throw new Error("API.execute error: Failed to retrieve a valid response");
657
+ } catch (error) {
658
+ this.logger.log({
659
+ level: "error",
660
+ message: `CrexAPI.execute error: ${error}`
661
+ });
662
+ throw error;
663
+ }
664
+ }
665
+ };
666
+ // Annotate the CommonJS export names for ESM import in node:
667
+ 0 && (module.exports = {
668
+ CrexApi
669
+ });
670
+ //# sourceMappingURL=requests.js.map