@c-rex/core 0.1.3 → 0.1.4
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 +5 -4
- package/dist/api/cookies.js.map +1 -1
- package/dist/api/cookies.mjs +5 -4
- package/dist/api/cookies.mjs.map +1 -1
- package/dist/api/rpc.js +9 -4
- package/dist/api/rpc.js.map +1 -1
- package/dist/api/rpc.mjs +9 -4
- package/dist/api/rpc.mjs.map +1 -1
- package/dist/api/token.js +3 -3
- package/dist/api/token.js.map +1 -1
- package/dist/api/token.mjs +3 -3
- package/dist/api/token.mjs.map +1 -1
- package/dist/index.d.mts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +173 -144
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +173 -144
- package/dist/index.mjs.map +1 -1
- package/dist/logger.js +9 -4
- package/dist/logger.js.map +1 -1
- package/dist/logger.mjs +9 -4
- package/dist/logger.mjs.map +1 -1
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -39,6 +39,14 @@ module.exports = __toCommonJS(index_exports);
|
|
|
39
39
|
var import_axios = __toESM(require("axios"));
|
|
40
40
|
|
|
41
41
|
// ../constants/src/index.ts
|
|
42
|
+
var ALL = "*";
|
|
43
|
+
var LOG_LEVELS = {
|
|
44
|
+
critical: 2,
|
|
45
|
+
error: 3,
|
|
46
|
+
warning: 4,
|
|
47
|
+
info: 6,
|
|
48
|
+
debug: 7
|
|
49
|
+
};
|
|
42
50
|
var API = {
|
|
43
51
|
MAX_RETRY: 3,
|
|
44
52
|
API_TIMEOUT: 1e4,
|
|
@@ -46,170 +54,146 @@ var API = {
|
|
|
46
54
|
"content-Type": "application/json"
|
|
47
55
|
}
|
|
48
56
|
};
|
|
57
|
+
var SDK_CONFIG_KEY = "crex-sdk-config";
|
|
49
58
|
var DEFAULT_COOKIE_LIMIT = 7 * 24 * 60 * 60 * 1e3;
|
|
50
59
|
var CREX_TOKEN_HEADER_KEY = "crex-token";
|
|
51
60
|
|
|
52
|
-
//
|
|
53
|
-
var
|
|
54
|
-
try {
|
|
55
|
-
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/rpc`, {
|
|
56
|
-
method: "POST",
|
|
57
|
-
headers: { "Content-Type": "application/json" },
|
|
58
|
-
body: JSON.stringify({ method, params }),
|
|
59
|
-
credentials: "include"
|
|
60
|
-
});
|
|
61
|
-
const json = await res.json();
|
|
62
|
-
if (!res.ok) throw new Error(json.error || "Unknown error");
|
|
63
|
-
return json.data;
|
|
64
|
-
} catch (error) {
|
|
65
|
-
console.error(error);
|
|
66
|
-
return null;
|
|
67
|
-
}
|
|
68
|
-
};
|
|
61
|
+
// src/requests.ts
|
|
62
|
+
var import_headers = require("next/headers");
|
|
69
63
|
|
|
70
|
-
//
|
|
71
|
-
var
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
64
|
+
// src/logger.ts
|
|
65
|
+
var import_winston = __toESM(require("winston"));
|
|
66
|
+
|
|
67
|
+
// src/transports/matomo.ts
|
|
68
|
+
var import_winston_transport = __toESM(require("winston-transport"));
|
|
69
|
+
var MatomoTransport = class extends import_winston_transport.default {
|
|
70
|
+
matomoTransport;
|
|
71
|
+
configs;
|
|
72
|
+
/**
|
|
73
|
+
* Creates a new instance of MatomoTransport.
|
|
74
|
+
*
|
|
75
|
+
* @param configs - The application configuration containing logging settings
|
|
76
|
+
*/
|
|
77
|
+
constructor(configs) {
|
|
78
|
+
super({
|
|
79
|
+
level: configs.logs.matomo.minimumLevel,
|
|
80
|
+
silent: configs.logs.matomo.silent
|
|
81
|
+
});
|
|
82
|
+
this.matomoTransport = new import_winston_transport.default();
|
|
83
|
+
this.configs = configs;
|
|
75
84
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
85
|
+
/**
|
|
86
|
+
* Logs a message to Matomo if the message category is included in the configured categories.
|
|
87
|
+
*
|
|
88
|
+
* @param info - The log information including level, message, and category
|
|
89
|
+
* @param callback - Callback function to execute after logging
|
|
90
|
+
*/
|
|
91
|
+
log(info, callback) {
|
|
92
|
+
const matomoCategory = this.configs.logs.matomo.categoriesLevel;
|
|
93
|
+
if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {
|
|
94
|
+
this.matomoTransport.log(info, callback);
|
|
83
95
|
}
|
|
84
|
-
await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/cookies`, {
|
|
85
|
-
method: "POST",
|
|
86
|
-
credentials: "include",
|
|
87
|
-
body: JSON.stringify({
|
|
88
|
-
key,
|
|
89
|
-
value,
|
|
90
|
-
maxAge
|
|
91
|
-
})
|
|
92
|
-
});
|
|
93
|
-
} catch (error) {
|
|
94
|
-
call("CrexLogger.log", {
|
|
95
|
-
level: "error",
|
|
96
|
-
message: `utils.setCookie error: ${error}`
|
|
97
|
-
});
|
|
98
96
|
}
|
|
99
97
|
};
|
|
100
98
|
|
|
101
|
-
//
|
|
102
|
-
var
|
|
103
|
-
var
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
99
|
+
// src/transports/graylog.ts
|
|
100
|
+
var import_winston_transport2 = __toESM(require("winston-transport"));
|
|
101
|
+
var import_winston_graylog2 = __toESM(require("winston-graylog2"));
|
|
102
|
+
var GraylogTransport = class extends import_winston_transport2.default {
|
|
103
|
+
graylogTransport;
|
|
104
|
+
configs;
|
|
105
|
+
/**
|
|
106
|
+
* Creates a new instance of GraylogTransport.
|
|
107
|
+
*
|
|
108
|
+
* @param configs - The application configuration containing logging settings
|
|
109
|
+
*/
|
|
110
|
+
constructor(configs) {
|
|
111
|
+
super({
|
|
112
|
+
level: configs.logs.graylog.minimumLevel,
|
|
113
|
+
silent: configs.logs.graylog.silent
|
|
111
114
|
});
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
115
|
+
this.configs = configs;
|
|
116
|
+
this.graylogTransport = new import_winston_graylog2.default({
|
|
117
|
+
name: "crex.net.documentation",
|
|
118
|
+
//name: "crex.net.blog",
|
|
119
|
+
silent: false,
|
|
120
|
+
handleExceptions: false,
|
|
121
|
+
graylog: {
|
|
122
|
+
servers: [
|
|
123
|
+
{ host: "localhost", port: 12201 },
|
|
124
|
+
{ host: "https://log.c-rex.net", port: 12202 }
|
|
125
|
+
//TODO: check the URL => https://log.c-rex.net:12202/gelf" GELF??
|
|
126
|
+
]
|
|
127
|
+
}
|
|
123
128
|
});
|
|
124
|
-
return null;
|
|
125
129
|
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
130
|
+
/**
|
|
131
|
+
* Logs a message to Graylog if the message category is included in the configured categories.
|
|
132
|
+
*
|
|
133
|
+
* @param info - The log information including level, message, and category
|
|
134
|
+
* @param callback - Callback function to execute after logging
|
|
135
|
+
*/
|
|
136
|
+
log(info, callback) {
|
|
137
|
+
const graylogCategory = this.configs.logs.graylog.categoriesLevel;
|
|
138
|
+
if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {
|
|
139
|
+
this.graylogTransport.log(info, callback);
|
|
135
140
|
}
|
|
136
|
-
return token;
|
|
137
|
-
} catch (error) {
|
|
138
|
-
call("CrexLogger.log", {
|
|
139
|
-
level: "error",
|
|
140
|
-
message: `utils.manageToken error: ${error}`
|
|
141
|
-
});
|
|
142
|
-
return null;
|
|
143
141
|
}
|
|
144
142
|
};
|
|
145
143
|
|
|
146
|
-
// src/
|
|
144
|
+
// src/logger.ts
|
|
147
145
|
var import_next_cookies = require("@c-rex/utils/next-cookies");
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* Retrieves a value from the cache by key.
|
|
153
|
-
*
|
|
154
|
-
* @param key - The cache key to retrieve
|
|
155
|
-
* @returns The cached value as a string, or null if not found
|
|
156
|
-
*/
|
|
157
|
-
async get(key) {
|
|
158
|
-
const cookie = await getCookie(key);
|
|
159
|
-
return cookie.value;
|
|
160
|
-
}
|
|
146
|
+
var CrexLogger = class {
|
|
147
|
+
customerConfig;
|
|
148
|
+
logger;
|
|
161
149
|
/**
|
|
162
|
-
*
|
|
163
|
-
*
|
|
150
|
+
* Initializes the logger instance if it hasn't been initialized yet.
|
|
151
|
+
* Loads customer configuration and creates the logger with appropriate transports.
|
|
164
152
|
*
|
|
165
|
-
* @
|
|
166
|
-
* @param value - The value to store
|
|
153
|
+
* @private
|
|
167
154
|
*/
|
|
168
|
-
async
|
|
155
|
+
async initLogger() {
|
|
169
156
|
try {
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
157
|
+
if (!this.customerConfig) {
|
|
158
|
+
this.customerConfig = await (0, import_next_cookies.getConfigs)();
|
|
159
|
+
}
|
|
160
|
+
if (!this.logger) {
|
|
161
|
+
this.logger = this.createLogger();
|
|
175
162
|
}
|
|
176
163
|
} catch (error) {
|
|
177
|
-
|
|
178
|
-
level: "error",
|
|
179
|
-
message: `CrexCache.set error: ${error}`
|
|
180
|
-
});
|
|
164
|
+
console.error("Error initializing logger:", error);
|
|
181
165
|
}
|
|
182
166
|
}
|
|
183
167
|
/**
|
|
184
|
-
*
|
|
185
|
-
* Combines URL, method, and optionally params, body, and headers into a single string key.
|
|
168
|
+
* Logs a message with the specified level and optional category.
|
|
186
169
|
*
|
|
187
|
-
* @param options -
|
|
188
|
-
* @param options.
|
|
189
|
-
* @param options.
|
|
190
|
-
* @param options.
|
|
191
|
-
* @param options.params - Optional query parameters
|
|
192
|
-
* @param options.headers - Optional request headers
|
|
193
|
-
* @returns A string cache key
|
|
170
|
+
* @param options - Logging options
|
|
171
|
+
* @param options.level - The log level (error, warn, info, etc.)
|
|
172
|
+
* @param options.message - The message to log
|
|
173
|
+
* @param options.category - Optional category for the log message
|
|
194
174
|
*/
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
175
|
+
async log({ level, message, category }) {
|
|
176
|
+
await this.initLogger();
|
|
177
|
+
this.logger.log(level, message, category);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Creates a new Winston logger instance with configured transports.
|
|
181
|
+
*
|
|
182
|
+
* @private
|
|
183
|
+
* @returns A configured Winston logger instance
|
|
184
|
+
*/
|
|
185
|
+
createLogger() {
|
|
186
|
+
return import_winston.default.createLogger({
|
|
187
|
+
levels: LOG_LEVELS,
|
|
188
|
+
transports: [
|
|
189
|
+
new import_winston.default.transports.Console({
|
|
190
|
+
level: this.customerConfig.logs.console.minimumLevel,
|
|
191
|
+
silent: this.customerConfig.logs.console.silent
|
|
192
|
+
}),
|
|
193
|
+
new MatomoTransport(this.customerConfig),
|
|
194
|
+
new GraylogTransport(this.customerConfig)
|
|
195
|
+
]
|
|
196
|
+
});
|
|
213
197
|
}
|
|
214
198
|
};
|
|
215
199
|
|
|
@@ -217,24 +201,67 @@ var CrexCache = class {
|
|
|
217
201
|
var CrexApi = class {
|
|
218
202
|
customerConfig;
|
|
219
203
|
apiClient;
|
|
220
|
-
|
|
204
|
+
logger;
|
|
221
205
|
/**
|
|
222
206
|
* Initializes the API client if it hasn't been initialized yet.
|
|
223
|
-
* Loads customer configuration, creates the axios instance, and initializes the
|
|
207
|
+
* Loads customer configuration, creates the axios instance, and initializes the logger.
|
|
224
208
|
*
|
|
225
209
|
* @private
|
|
226
210
|
*/
|
|
227
211
|
async initAPI() {
|
|
212
|
+
this.logger = new CrexLogger();
|
|
228
213
|
if (!this.customerConfig) {
|
|
229
|
-
|
|
214
|
+
const aux = (0, import_headers.cookies)().get(SDK_CONFIG_KEY);
|
|
215
|
+
if (aux != void 0) {
|
|
216
|
+
this.customerConfig = JSON.parse(aux.value);
|
|
217
|
+
} else {
|
|
218
|
+
this.logger.log({
|
|
219
|
+
level: "error",
|
|
220
|
+
message: `utils.initAPI error: Config cookie not available`
|
|
221
|
+
});
|
|
222
|
+
throw new Error("Config cookie not available");
|
|
223
|
+
}
|
|
230
224
|
}
|
|
231
225
|
if (!this.apiClient) {
|
|
232
226
|
this.apiClient = import_axios.default.create({
|
|
233
227
|
baseURL: this.customerConfig.baseUrl
|
|
234
228
|
});
|
|
235
229
|
}
|
|
236
|
-
|
|
237
|
-
|
|
230
|
+
}
|
|
231
|
+
async getToken() {
|
|
232
|
+
try {
|
|
233
|
+
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/token`, {
|
|
234
|
+
method: "POST",
|
|
235
|
+
credentials: "include"
|
|
236
|
+
});
|
|
237
|
+
const { token } = await response.json();
|
|
238
|
+
return token;
|
|
239
|
+
} catch (error) {
|
|
240
|
+
this.logger.log({
|
|
241
|
+
level: "error",
|
|
242
|
+
message: `utils.getToken error: ${error}`
|
|
243
|
+
});
|
|
244
|
+
throw error;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
async manageToken() {
|
|
248
|
+
try {
|
|
249
|
+
let token = "";
|
|
250
|
+
const hasToken = (0, import_headers.cookies)().get(CREX_TOKEN_HEADER_KEY);
|
|
251
|
+
if (hasToken == void 0 || hasToken.value === null) {
|
|
252
|
+
const tokenResult = await this.getToken();
|
|
253
|
+
if (tokenResult === null) throw new Error("Token is undefined");
|
|
254
|
+
token = tokenResult;
|
|
255
|
+
} else {
|
|
256
|
+
token = hasToken.value;
|
|
257
|
+
}
|
|
258
|
+
return token;
|
|
259
|
+
} catch (error) {
|
|
260
|
+
this.logger.log({
|
|
261
|
+
level: "error",
|
|
262
|
+
message: `utils.manageToken error: ${error}`
|
|
263
|
+
});
|
|
264
|
+
throw error;
|
|
238
265
|
}
|
|
239
266
|
}
|
|
240
267
|
/**
|
|
@@ -259,7 +286,7 @@ var CrexApi = class {
|
|
|
259
286
|
await this.initAPI();
|
|
260
287
|
let response = void 0;
|
|
261
288
|
if (this.customerConfig.OIDC.client.enabled) {
|
|
262
|
-
const token = await manageToken();
|
|
289
|
+
const token = await this.manageToken();
|
|
263
290
|
headers = {
|
|
264
291
|
...headers,
|
|
265
292
|
Authorization: `Bearer ${token}`
|
|
@@ -277,7 +304,7 @@ var CrexApi = class {
|
|
|
277
304
|
});
|
|
278
305
|
break;
|
|
279
306
|
} catch (error) {
|
|
280
|
-
|
|
307
|
+
this.logger.log({
|
|
281
308
|
level: "error",
|
|
282
309
|
message: `API.execute ${retry + 1}\xBA error when request ${url}. Error: ${error}`
|
|
283
310
|
});
|
|
@@ -331,7 +358,9 @@ var CrexSDK = class {
|
|
|
331
358
|
clientId: user.id,
|
|
332
359
|
wellKnown: user.issuer,
|
|
333
360
|
clientSecret: user.secret,
|
|
334
|
-
authorization: {
|
|
361
|
+
authorization: {
|
|
362
|
+
params: { scope: user.scope }
|
|
363
|
+
},
|
|
335
364
|
profile(profile) {
|
|
336
365
|
return {
|
|
337
366
|
id: profile.id || "fake Id",
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/requests.ts","../../constants/src/index.ts","../../utils/src/utils.ts","../../utils/src/memory.ts","../../utils/src/classMerge.ts","../../utils/src/token.ts","../src/cache.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 } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { call, manageToken } from \"@c-rex/utils\";\nimport { getConfigs } from \"@c-rex/utils/next-cookies\";\nimport { CrexCache } from \"./cache\";\n\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 cache!: CrexCache;\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 cache.\n * \n * @private\n */\n private async initAPI() {\n if (!this.customerConfig) {\n this.customerConfig = await getConfigs();\n }\n if (!this.apiClient) {\n this.apiClient = axios.create({\n baseURL: this.customerConfig.baseUrl,\n })\n }\n if (!this.cache) {\n this.cache = new CrexCache();\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 const cacheKey = this.cache.generateCacheKey({ url, method, body, params, headers });\n\n if (method.toUpperCase() === \"GET\") {\n const cachedResponse = await this.cache.get(cacheKey);\n\n if (cachedResponse) {\n\n return JSON.parse(cachedResponse) as T;\n }\n }\n */\n\n if (this.customerConfig.OIDC.client.enabled) {\n const token = await 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 call(\"CrexLogger.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 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 DOCUMENTS_TYPE_AND_LINK = \"documents\";\n\nexport const TOPIC = \"TOPIC\";\nexport const DOCUMENT = \"DOCUMENT\";\nexport const PACKAGE = \"PACKAGE\";\n\nexport const RESULT_TYPES = {\n TOPIC: TOPIC,\n DOCUMENT: DOCUMENT,\n PACKAGE: PACKAGE,\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 = 7 * 24 * 60 * 60 * 1000; // 7 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\";","import { FLAGS_BY_LANG } from \"@c-rex/constants\";\n\n/**\n * Makes an asynchronous RPC API call to the server.\n * @param method - The RPC method name to call\n * @param params - Optional parameters to pass to the method\n * @returns A Promise resolving to the response data of type T, or null if an error occurs\n */\nexport const call = async<T = unknown>(method: string, params?: any): Promise<T> => {\n try {\n const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/rpc`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ method, params }),\n credentials: 'include',\n });\n\n const json = await res.json();\n\n if (!res.ok) throw new Error(json.error || 'Unknown error');\n\n return json.data;\n } catch (error) {\n //TODO: add logger\n console.error(error);\n return null as T;\n }\n}\n\n/**\n * Retrieves the country code associated with a given language code.\n * @param lang - The language code to look up (e.g., \"en-US\")\n * @returns The corresponding country code, or the original language code if not found\n */\nexport const getCountryCodeByLang = (lang: string): string => {\n const mappedKeys = Object.keys(FLAGS_BY_LANG);\n\n if (!mappedKeys.includes(lang)) {\n return lang\n }\n\n type LangKey = keyof typeof FLAGS_BY_LANG;\n const country = FLAGS_BY_LANG[lang as LangKey]\n\n return country\n}\n\nexport const getFromCookieString = (cookieString: string, key: string): string => {\n const cookies = cookieString.split(';')\n\n for (const cookie of cookies) {\n const [cookieKey, cookieValue] = cookie.trim().split('=')\n\n if (cookieKey === key) {\n return cookieValue as string;\n }\n }\n\n return ''\n}\n","import { DEFAULT_COOKIE_LIMIT } from \"@c-rex/constants\";\nimport { call } from \"./utils\";\n\n/**\n * Fetches a cookie value from the server API in client-side code.\n * @param key - The key of the cookie to retrieve\n * @returns A Promise resolving to an object containing the key and value of the cookie\n */\nexport const getCookie = async (key: string): Promise<{ key: string, value: string | null }> => {\n const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/cookies?key=${key}`);\n\n if (!res.ok) {\n return { key: key, value: null };\n }\n const json = await res.json();\n\n return json;\n}\n\n/**\n * Sets a cookie value through the server API in client-side code.\n * @param key - The key of the cookie to set\n * @param value - The value to store in the cookie\n * @param maxAge - Optional maximum age of the cookie in seconds. Defaults to DEFAULT_COOKIE_LIMIT if not specified.\n * @returns A Promise that resolves when the cookie has been set\n */\nexport const setCookie = async (key: string, value: string, maxAge?: number): Promise<void> => {\n try {\n\n if (maxAge === undefined) {\n maxAge = DEFAULT_COOKIE_LIMIT;\n }\n\n await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/cookies`, {\n method: 'POST',\n credentials: 'include',\n body: JSON.stringify({\n key: key,\n value: value,\n maxAge: maxAge,\n }),\n });\n } catch (error) {\n call(\"CrexLogger.log\", {\n level: \"error\",\n message: `utils.setCookie error: ${error}`\n });\n }\n}\n\n","import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\n/**\n * Merges multiple class values into a single string using clsx and tailwind-merge.\n * Useful for conditionally applying Tailwind CSS classes.\n * @param inputs - Any number of class values (strings, objects, arrays, etc.)\n * @returns A merged string of class names optimized for Tailwind CSS\n */\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n","import { CREX_TOKEN_HEADER_KEY } from \"@c-rex/constants\";\nimport { getCookie } from \"./memory\";\nimport { call } from \"./utils\";\n\nconst updateToken = async (): Promise<string | null> => {\n try {\n const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/token`, {\n method: 'POST',\n credentials: 'include',\n });\n\n const cookies = response.headers.get(\"set-cookie\");\n if (cookies === null) return null\n\n const aux = cookies.split(`${CREX_TOKEN_HEADER_KEY}=`);\n if (aux.length == 0) return null\n\n const token = aux[1].split(\";\")[0];\n if (token === undefined) throw new Error(\"Token is undefined\");\n\n return token;\n } catch (error) {\n call(\"CrexLogger.log\", {\n level: \"error\",\n message: `utils.updateToken error: ${error}`\n });\n return null\n }\n}\n\nexport const manageToken = async (): Promise<string | null> => {\n try {\n\n const hasToken = await getCookie(CREX_TOKEN_HEADER_KEY);\n let token = hasToken.value!;\n\n if (hasToken.value === null) {\n const tokenResult = await updateToken();\n\n if (tokenResult === null) throw new Error(\"Token is undefined\");\n\n token = tokenResult;\n }\n\n return token;\n } catch (error) {\n call(\"CrexLogger.log\", {\n level: \"error\",\n message: `utils.manageToken error: ${error}`\n });\n\n return null\n }\n}","import { call, getCookie, setCookie } from \"@c-rex/utils\";\n\n/**\n * Cache class for the CREX application.\n * Provides cookie-based caching functionality for API responses.\n */\nexport class CrexCache {\n /**\n * Retrieves a value from the cache by key.\n * \n * @param key - The cache key to retrieve\n * @returns The cached value as a string, or null if not found\n */\n public async get(key: string): Promise<string | null> {\n const cookie = await getCookie(key);\n\n return cookie.value;\n }\n\n /**\n * Stores a value in the cache with the specified key.\n * Checks if the value size is within cookie size limits (4KB).\n * \n * @param key - The cache key\n * @param value - The value to store\n */\n public async set(key: string, value: string): Promise<void> {\n try {\n const byteLength = new TextEncoder().encode(value).length;\n\n if (byteLength <= 4096) {\n await setCookie(key, value);\n } else {\n console.warn(`Cookie ${key} value is too large to be stored in a single cookie`);\n }\n\n } catch (error) {\n call(\"CrexLogger.log\", {\n level: \"error\",\n message: `CrexCache.set error: ${error}`\n });\n }\n }\n\n /**\n * Generates a cache key based on request parameters.\n * Combines URL, method, and optionally params, body, and headers into a single string key.\n * \n * @param options - Request options to generate key from\n * @param options.url - The request URL\n * @param options.method - The HTTP method\n * @param options.body - Optional request body\n * @param options.params - Optional query parameters\n * @param options.headers - Optional request headers\n * @returns A string cache key\n */\n public generateCacheKey({\n url,\n method,\n body,\n params,\n headers,\n }: any) {\n let cacheKey = `${url}-${method}`\n\n if (params !== undefined && Object.keys(params).length > 0) {\n cacheKey += `-${JSON.stringify(params)}`\n }\n if (body !== undefined && Object.keys(body).length > 0) {\n cacheKey += `-${JSON.stringify(body)}`\n }\n if (headers !== undefined && Object.keys(headers).length > 0) {\n cacheKey += `-${JSON.stringify(headers)}`\n }\n\n return cacheKey;\n }\n}","import { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getConfigs } from \"@c-rex/utils/next-cookies\";\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 getConfigs()\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 clientId: user.id,\n wellKnown: user.issuer,\n clientSecret: user.secret,\n authorization: { params: { scope: user.scope } },\n profile(profile: any) {\n return {\n id: profile.id || \"fake Id\",\n name: profile.name || \"Fake Name\",\n email: profile.email || \"fake Email\",\n image: profile.image || \"fake Image\",\n }\n },\n },\n ]\n }\n };\n\n return this.userAuthConfig;\n }\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAA4D;;;AC4BrD,IAAM,MAAM;AAAA,EACf,WAAW;AAAA,EACX,aAAa;AAAA,EACb,aAAa;AAAA,IACT,gBAAgB;AAAA,EACpB;AACJ;AAuCO,IAAM,uBAAuB,IAAI,KAAK,KAAK,KAAK;AAQhD,IAAM,wBAAwB;;;ACzE9B,IAAM,OAAO,OAAmB,QAAg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Aa,oBAAoB;AAC7B,QAAI,KAAK,gBAAgB;AACrB,aAAO,KAAK;AAAA,IAChB;AAEA,UAAM,KAAK,UAAU;AAErB,UAAM,OAAO,KAAK,eAAe,KAAK;AACtC,QAAI,KAAK,SAAS;AACd,WAAK,iBAAiB;AAAA,QAClB,WAAW;AAAA,UACP;AAAA,YACI,IAAI;AAAA,YACJ,MAAM;AAAA,YACN,MAAM;AAAA,YACN,UAAU,KAAK;AAAA,YACf,WAAW,KAAK;AAAA,YAChB,cAAc,KAAK;AAAA,YACnB,eAAe,EAAE,QAAQ,EAAE,OAAO,KAAK,MAAM,EAAE;AAAA,YAC/C,QAAQ,SAAc;AAClB,qBAAO;AAAA,gBACH,IAAI,QAAQ,MAAM;AAAA,gBAClB,MAAM,QAAQ,QAAQ;AAAA,gBACtB,OAAO,QAAQ,SAAS;AAAA,gBACxB,OAAO,QAAQ,SAAS;AAAA,cAC5B;AAAA,YACJ;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAC;AAED,WAAO,KAAK;AAAA,EAChB;AACJ;","names":["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/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\";\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 const aux = cookies().get(SDK_CONFIG_KEY);\n if (aux != undefined) {\n this.customerConfig = JSON.parse(aux.value);\n } else {\n this.logger.log({\n level: \"error\",\n message: `utils.initAPI error: Config cookie not available`\n });\n\n throw new Error(\"Config cookie not available\");\n }\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 try {\n const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/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 error: ${error}`\n });\n\n throw error\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: `utils.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 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\";\n\nexport const RESULT_TYPES = {\n TOPIC: TOPIC,\n DOCUMENT: DOCUMENT,\n PACKAGE: PACKAGE,\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 = 7 * 24 * 60 * 60 * 1000; // 7 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\";","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 { getConfigs } 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 getConfigs();\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 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: \"crex.net.documentation\",\n //name: \"crex.net.blog\",\n silent: false,\n handleExceptions: false,\n graylog: {\n servers: [\n { host: \"localhost\", port: 12201 },\n { host: \"https://log.c-rex.net\", port: 12202 }\n\n //TODO: check the URL => https://log.c-rex.net:12202/gelf\" GELF??\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 { getConfigs } 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 getConfigs()\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 clientId: user.id,\n wellKnown: user.issuer,\n clientSecret: user.secret,\n authorization: {\n params: { scope: user.scope }\n },\n profile(profile: any) {\n return {\n id: profile.id || \"fake Id\",\n name: profile.name || \"Fake Name\",\n email: profile.email || \"fake Email\",\n image: profile.image || \"fake Image\",\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,IACT,gBAAgB;AAAA,EACpB;AACJ;AAEO,IAAM,iBAAiB;AAsCvB,IAAM,uBAAuB,IAAI,KAAK,KAAK,KAAK;AAQhD,IAAM,wBAAwB;;;AD/ErC,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,OAAO;AAAA,IAChC,CAAC;AAED,SAAK,kBAAkB,IAAI,yBAAAA,QAAU;AACrC,SAAK,UAAU;AAAA,EACnB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,IACI,MACA,UACI;AACJ,UAAM,iBAAiB,KAAK,QAAQ,KAAK,OAAO;AAEhD,QAAI,eAAe,SAAS,KAAK,QAAQ,KAAK,eAAe,SAAS,GAAG,GAAG;AACxE,WAAK,gBAAgB,IAAI,MAAM,QAAQ;AAAA,IAC3C;AAAA,EACJ;AACJ;;;AC5CA,IAAAC,4BAAsB;AACtB,8BAA8B;AASvB,IAAM,mBAAN,cAA+B,0BAAAC,QAAU;AAAA,EACrC;AAAA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AA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAC;AAED,WAAO,KAAK;AAAA,EAChB;AACJ;","names":["Transport","import_winston_transport","Transport","Graylog2Transport","winston","axios","import_next_cookies"]}
|