@c-rex/core 0.1.2 → 0.1.3

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.mjs CHANGED
@@ -10,9 +10,7 @@ var API = {
10
10
  }
11
11
  };
12
12
  var DEFAULT_COOKIE_LIMIT = 7 * 24 * 60 * 60 * 1e3;
13
-
14
- // src/requests.ts
15
- import { Issuer } from "openid-client";
13
+ var CREX_TOKEN_HEADER_KEY = "crex-token";
16
14
 
17
15
  // ../utils/src/utils.ts
18
16
  var call = async (method, params) => {
@@ -20,7 +18,8 @@ var call = async (method, params) => {
20
18
  const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/rpc`, {
21
19
  method: "POST",
22
20
  headers: { "Content-Type": "application/json" },
23
- body: JSON.stringify({ method, params })
21
+ body: JSON.stringify({ method, params }),
22
+ credentials: "include"
24
23
  });
25
24
  const json = await res.json();
26
25
  if (!res.ok) throw new Error(json.error || "Unknown error");
@@ -32,83 +31,162 @@ var call = async (method, params) => {
32
31
  };
33
32
 
34
33
  // ../utils/src/memory.ts
35
- function isBrowser() {
36
- return typeof window !== "undefined" && typeof document !== "undefined";
37
- }
38
- function saveInMemory(value, key) {
39
- if (isBrowser()) throw new Error("saveInMemory is not supported in browser");
40
- if (typeof global !== "undefined" && !(key in global)) {
41
- global[key] = null;
34
+ var getCookie = async (key) => {
35
+ const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/cookies?key=${key}`);
36
+ if (!res.ok) {
37
+ return { key, value: null };
42
38
  }
43
- const globalConfig = global[key];
44
- if (globalConfig === null) {
45
- global[key] = value;
39
+ const json = await res.json();
40
+ return json;
41
+ };
42
+ var setCookie = async (key, value, maxAge) => {
43
+ try {
44
+ if (maxAge === void 0) {
45
+ maxAge = DEFAULT_COOKIE_LIMIT;
46
+ }
47
+ await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/cookies`, {
48
+ method: "POST",
49
+ credentials: "include",
50
+ body: JSON.stringify({
51
+ key,
52
+ value,
53
+ maxAge
54
+ })
55
+ });
56
+ } catch (error) {
57
+ call("CrexLogger.log", {
58
+ level: "error",
59
+ message: `utils.setCookie error: ${error}`
60
+ });
46
61
  }
47
- }
48
- function getFromMemory(key) {
49
- if (isBrowser()) throw new Error("getFromMemory is not supported in browser");
50
- return global[key];
51
- }
62
+ };
52
63
 
53
64
  // ../utils/src/classMerge.ts
54
65
  import { clsx } from "clsx";
55
66
  import { twMerge } from "tailwind-merge";
56
67
 
57
- // ../utils/src/treeOfContent.ts
58
- import { DirectoryNodesService } from "@c-rex/services";
59
-
60
- // ../utils/src/articles.ts
61
- import { InformationUnitsService, RenditionsService } from "@c-rex/services";
68
+ // ../utils/src/token.ts
69
+ var updateToken = async () => {
70
+ try {
71
+ const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/token`, {
72
+ method: "POST",
73
+ credentials: "include"
74
+ });
75
+ const cookies = response.headers.get("set-cookie");
76
+ if (cookies === null) return null;
77
+ const aux = cookies.split(`${CREX_TOKEN_HEADER_KEY}=`);
78
+ if (aux.length == 0) return null;
79
+ const token = aux[1].split(";")[0];
80
+ if (token === void 0) throw new Error("Token is undefined");
81
+ return token;
82
+ } catch (error) {
83
+ call("CrexLogger.log", {
84
+ level: "error",
85
+ message: `utils.updateToken error: ${error}`
86
+ });
87
+ return null;
88
+ }
89
+ };
90
+ var manageToken = async () => {
91
+ try {
92
+ const hasToken = await getCookie(CREX_TOKEN_HEADER_KEY);
93
+ let token = hasToken.value;
94
+ if (hasToken.value === null) {
95
+ const tokenResult = await updateToken();
96
+ if (tokenResult === null) throw new Error("Token is undefined");
97
+ token = tokenResult;
98
+ }
99
+ return token;
100
+ } catch (error) {
101
+ call("CrexLogger.log", {
102
+ level: "error",
103
+ message: `utils.manageToken error: ${error}`
104
+ });
105
+ return null;
106
+ }
107
+ };
62
108
 
63
109
  // src/requests.ts
64
110
  import { getConfigs } from "@c-rex/utils/next-cookies";
65
- var CREX_TOKEN_HEADER_KEY = "crex-token";
66
- var CREX_TOKEN_EXPIRY_HEADER_KEY = "crex-token-expiry";
67
- var CrexApi = class {
68
- customerConfig;
69
- apiClient;
70
- async manageToken() {
71
- const headersAux = {};
72
- if (this.customerConfig.OIDC.client.enabled) {
73
- let token = getFromMemory(CREX_TOKEN_HEADER_KEY);
74
- const tokenExpiry = Number(
75
- getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY)
76
- );
77
- const now = Math.floor(Date.now() / 1e3);
78
- if (!(token && tokenExpiry > now + 60)) {
79
- const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();
80
- token = tokenAux;
81
- saveInMemory(token, CREX_TOKEN_HEADER_KEY);
82
- saveInMemory(tokenExpiryAux.toString(), CREX_TOKEN_EXPIRY_HEADER_KEY);
83
- }
84
- headersAux["Authorization"] = `Bearer ${token}`;
85
- }
86
- return headersAux;
111
+
112
+ // src/cache.ts
113
+ var CrexCache = class {
114
+ /**
115
+ * Retrieves a value from the cache by key.
116
+ *
117
+ * @param key - The cache key to retrieve
118
+ * @returns The cached value as a string, or null if not found
119
+ */
120
+ async get(key) {
121
+ const cookie = await getCookie(key);
122
+ return cookie.value;
87
123
  }
88
- async getToken() {
89
- let token = "";
90
- let tokenExpiry = 0;
124
+ /**
125
+ * Stores a value in the cache with the specified key.
126
+ * Checks if the value size is within cookie size limits (4KB).
127
+ *
128
+ * @param key - The cache key
129
+ * @param value - The value to store
130
+ */
131
+ async set(key, value) {
91
132
  try {
92
- const now = Math.floor(Date.now() / 1e3);
93
- const issuer = await Issuer.discover(this.customerConfig.OIDC.client.issuer);
94
- const client = new issuer.Client({
95
- client_id: this.customerConfig.OIDC.client.id,
96
- client_secret: this.customerConfig.OIDC.client.secret
97
- });
98
- const tokenSet = await client.grant({ grant_type: "client_credentials" });
99
- token = tokenSet.access_token;
100
- tokenExpiry = now + tokenSet.expires_at;
133
+ const byteLength = new TextEncoder().encode(value).length;
134
+ if (byteLength <= 4096) {
135
+ await setCookie(key, value);
136
+ } else {
137
+ console.warn(`Cookie ${key} value is too large to be stored in a single cookie`);
138
+ }
101
139
  } catch (error) {
102
140
  call("CrexLogger.log", {
103
141
  level: "error",
104
- message: `API.getToken error when request ${this.customerConfig.OIDC.client.issuer}. Error: ${error}`
142
+ message: `CrexCache.set error: ${error}`
105
143
  });
106
144
  }
107
- return {
108
- token,
109
- tokenExpiry
110
- };
111
145
  }
146
+ /**
147
+ * Generates a cache key based on request parameters.
148
+ * Combines URL, method, and optionally params, body, and headers into a single string key.
149
+ *
150
+ * @param options - Request options to generate key from
151
+ * @param options.url - The request URL
152
+ * @param options.method - The HTTP method
153
+ * @param options.body - Optional request body
154
+ * @param options.params - Optional query parameters
155
+ * @param options.headers - Optional request headers
156
+ * @returns A string cache key
157
+ */
158
+ generateCacheKey({
159
+ url,
160
+ method,
161
+ body,
162
+ params,
163
+ headers
164
+ }) {
165
+ let cacheKey = `${url}-${method}`;
166
+ if (params !== void 0 && Object.keys(params).length > 0) {
167
+ cacheKey += `-${JSON.stringify(params)}`;
168
+ }
169
+ if (body !== void 0 && Object.keys(body).length > 0) {
170
+ cacheKey += `-${JSON.stringify(body)}`;
171
+ }
172
+ if (headers !== void 0 && Object.keys(headers).length > 0) {
173
+ cacheKey += `-${JSON.stringify(headers)}`;
174
+ }
175
+ return cacheKey;
176
+ }
177
+ };
178
+
179
+ // src/requests.ts
180
+ var CrexApi = class {
181
+ customerConfig;
182
+ apiClient;
183
+ cache;
184
+ /**
185
+ * Initializes the API client if it hasn't been initialized yet.
186
+ * Loads customer configuration, creates the axios instance, and initializes the cache.
187
+ *
188
+ * @private
189
+ */
112
190
  async initAPI() {
113
191
  if (!this.customerConfig) {
114
192
  this.customerConfig = await getConfigs();
@@ -118,7 +196,22 @@ var CrexApi = class {
118
196
  baseURL: this.customerConfig.baseUrl
119
197
  });
120
198
  }
199
+ if (!this.cache) {
200
+ this.cache = new CrexCache();
201
+ }
121
202
  }
203
+ /**
204
+ * Executes an API request with caching, authentication, and retry logic.
205
+ *
206
+ * @param options - Request options
207
+ * @param options.url - The URL to request
208
+ * @param options.method - The HTTP method to use
209
+ * @param options.params - Optional query parameters
210
+ * @param options.body - Optional request body
211
+ * @param options.headers - Optional request headers
212
+ * @returns The response data
213
+ * @throws Error if the request fails after maximum retries
214
+ */
122
215
  async execute({
123
216
  url,
124
217
  method,
@@ -128,10 +221,14 @@ var CrexApi = class {
128
221
  }) {
129
222
  await this.initAPI();
130
223
  let response = void 0;
131
- headers = {
132
- ...headers,
133
- ...await this.manageToken()
134
- };
224
+ if (this.customerConfig.OIDC.client.enabled) {
225
+ const token = await manageToken();
226
+ headers = {
227
+ ...headers,
228
+ Authorization: `Bearer ${token}`
229
+ };
230
+ this.apiClient.defaults.headers.common["Authorization"] = `Bearer ${token}`;
231
+ }
135
232
  for (let retry = 0; retry < API.MAX_RETRY; retry++) {
136
233
  try {
137
234
  response = await this.apiClient.request({
@@ -164,11 +261,23 @@ import { getConfigs as getConfigs2 } from "@c-rex/utils/next-cookies";
164
261
  var CrexSDK = class {
165
262
  userAuthConfig;
166
263
  customerConfig;
264
+ /**
265
+ * Retrieves the customer configuration if it hasn't been loaded yet.
266
+ *
267
+ * @private
268
+ */
167
269
  async getConfig() {
168
270
  if (!this.customerConfig) {
169
271
  this.customerConfig = await getConfigs2();
170
272
  }
171
273
  }
274
+ /**
275
+ * Retrieves the user authentication configuration.
276
+ * If not already loaded, it will load the customer configuration and
277
+ * create the auth config based on OIDC settings.
278
+ *
279
+ * @returns The user authentication configuration object
280
+ */
172
281
  async getUserAuthConfig() {
173
282
  if (this.userAuthConfig) {
174
283
  return this.userAuthConfig;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/requests.ts","../../constants/src/index.ts","../../utils/src/utils.ts","../../utils/src/memory.ts","../../utils/src/classMerge.ts","../../utils/src/treeOfContent.ts","../../utils/src/articles.ts","../src/sdk.ts"],"sourcesContent":["import axios, { AxiosResponse, Method, AxiosInstance } from \"axios\";\nimport { API } from \"@c-rex/constants\";\nimport { Issuer } from \"openid-client\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { call, getFromMemory, saveInMemory } from \"@c-rex/utils\";\nimport { getConfigs } from \"@c-rex/utils/next-cookies\";\n\nconst CREX_TOKEN_HEADER_KEY = \"crex-token\";\nconst CREX_TOKEN_EXPIRY_HEADER_KEY = \"crex-token-expiry\";\n\ninterface APIGenericResponse<T> extends AxiosResponse {\n data: T;\n statusCode: number;\n}\n\ninterface CallParams {\n url: string;\n method: Method;\n body?: any;\n headers?: any;\n params?: any;\n}\n\nexport class CrexApi {\n private customerConfig!: ConfigInterface;\n private apiClient!: AxiosInstance;\n\n private async manageToken() {\n const headersAux: Record<string, string> = {};\n\n if (this.customerConfig.OIDC.client.enabled) {\n let token = getFromMemory(CREX_TOKEN_HEADER_KEY);\n const tokenExpiry = Number(\n getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY)\n )\n\n const now = Math.floor(Date.now() / 1000);\n\n if (!(token && tokenExpiry > now + 60)) {\n const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();\n\n token = tokenAux;\n\n saveInMemory(token, CREX_TOKEN_HEADER_KEY);\n saveInMemory(tokenExpiryAux.toString(), CREX_TOKEN_EXPIRY_HEADER_KEY);\n }\n\n headersAux['Authorization'] = `Bearer ${token}`;\n }\n\n return headersAux;\n }\n\n private async getToken(): Promise<{ token: string; tokenExpiry: number; }> {\n let token = \"\";\n let tokenExpiry = 0;\n\n try {\n const now = Math.floor(Date.now() / 1000);\n const issuer = await Issuer.discover(this.customerConfig.OIDC.client.issuer);\n const client = new issuer.Client({\n client_id: this.customerConfig.OIDC.client.id,\n client_secret: this.customerConfig.OIDC.client.secret,\n });\n const tokenSet = await client.grant({ grant_type: 'client_credentials' });\n\n token = tokenSet.access_token!;\n tokenExpiry = now + tokenSet.expires_at!;\n } catch (error) {\n call(\"CrexLogger.log\", {\n level: \"error\",\n message: `API.getToken error when request ${this.customerConfig.OIDC.client.issuer}. Error: ${error}`\n });\n }\n\n return {\n token,\n tokenExpiry\n };\n }\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 }\n\n async execute<T>({\n url,\n method,\n params,\n body,\n headers = {},\n }: CallParams): Promise<T> {\n\n await this.initAPI();\n\n let response: APIGenericResponse<T> | undefined = undefined;\n\n headers = {\n ...headers,\n ...await this.manageToken(),\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 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\";","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 });\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 * Checks if the current environment is a browser.\n * @returns True if running in a browser environment, false otherwise\n */\nfunction isBrowser() {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\n/**\n * Saves a value in memory on the server side.\n * @param value - The string value to save\n * @param key - The key under which to store the value\n * @throws Error if called in a browser environment\n */\nexport function saveInMemory(value: string, key: string) {\n if (isBrowser()) throw new Error(\"saveInMemory is not supported in browser\");\n\n if (typeof global !== 'undefined' && !(key in global)) {\n (global as any)[key] = null;\n }\n\n const globalConfig = (global as any)[key] as any;\n\n if (globalConfig === null) {\n (global as any)[key] = value;\n }\n}\n\n/**\n * Retrieves a value from memory on the server side.\n * @param key - The key of the value to retrieve\n * @returns The stored string value\n * @throws Error if called in a browser environment\n */\nexport function getFromMemory(key: string): string {\n if (isBrowser()) throw new Error(\"getFromMemory is not supported in browser\");\n\n return (global as any)[key];\n}\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 getCookieInFront = 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 cache: 'no-store',\n });\n const json = await res.json();\n\n return json;\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 { DirectoryNodesService } from \"@c-rex/services\";\nimport { DirectoryNodes, informationUnitsDirectories, TreeOfContent } from \"@c-rex/interfaces\";\n\ntype ReturnType = {\n rootNode: DirectoryNodes | null,\n result: TreeOfContent[],\n}\n\n/**\n * Generates a hierarchical tree of content from directory nodes.\n * @param directoryNodes - Array of DirectoryNodes to build the tree from\n * @returns A Promise resolving to an object containing the root node and the resulting tree structure\n */\nexport const generateTreeOfContent = async (directoryNodes: DirectoryNodes[]): Promise<ReturnType> => {\n const service = new DirectoryNodesService();\n\n if (directoryNodes.length == 0 || directoryNodes[0] == undefined) {\n return { rootNode: null, result: [] };\n }\n\n let id = directoryNodes[0].shortId;\n let response = await service.getItem(id);\n const childList = await getChildrenInfo(response.childNodes);\n let result: TreeOfContent[] = childList;\n\n while (response.parents != undefined) {\n\n const hasInfo = (response.informationUnits != undefined) && (response.informationUnits[0] != undefined);\n const hasLabel = (response.labels != undefined) && (response.labels[0] != undefined);\n const hasParent = (response.parents != undefined) && (response.parents[0] != undefined);\n if (!hasInfo || !hasLabel || !hasParent) {\n return { rootNode: null, result: result };\n }\n\n const infoId = response.informationUnits[0].shortId;\n const aux = {\n active: true,\n label: response.labels[0].value,\n id: response.shortId,\n link: `/topics/${infoId}`,\n children: [...result],\n };\n id = response.parents[0].shortId;\n response = await service.getItem(id);\n\n const tree = await getChildrenInfo(response.childNodes, aux);\n\n result = [...tree];\n }\n\n return { rootNode: response, result: result };\n};\n\n/**\n * Processes child directory nodes and returns an array of TreeOfContent objects.\n * @param childNodes - Array of information units directories to process\n * @param childItem - Optional TreeOfContent item to include in the result if it matches a child node\n * @returns A Promise resolving to an array of TreeOfContent objects\n */\nconst getChildrenInfo = async (\n childNodes: informationUnitsDirectories[],\n childItem?: TreeOfContent,\n): Promise<TreeOfContent[]> => {\n const result: TreeOfContent[] = [];\n if (childNodes == undefined) return result;\n\n for (const item of childNodes) {\n if (item.labels == undefined || item.labels[0] == undefined) break;\n\n const infoId = await getLink(item.shortId);\n let resultItem: TreeOfContent = {\n active: false,\n label: item.labels[0].value,\n link: `/topics/${infoId}`,\n id: item.shortId,\n children: [],\n };\n\n if (childItem?.id == item.shortId) {\n resultItem = childItem;\n }\n result.push(resultItem);\n }\n return result;\n};\n\n/**\n * Gets the information unit ID from a directory node ID.\n * @param directoryNodeID - The ID of the directory node\n * @returns A Promise resolving to the information unit ID, or an empty string if not found\n */\nexport const getLink = async (directoryNodeID: string): Promise<string> => {\n const service = new DirectoryNodesService();\n const response = await service.getItem(directoryNodeID);\n\n if (response.informationUnits == undefined) return \"\";\n if (response.informationUnits[0] == undefined) return \"\";\n\n return response.informationUnits[0].shortId;\n};","import { InformationUnitsService, RenditionsService } from \"@c-rex/services\";\nimport { generateBreadcrumbItems, generateTreeOfContent, getLink } from \"./\";\nimport { TreeOfContent } from \"@c-rex/interfaces\";\n\nconst DOCUMENT = \"documents\";\nconst TOPIC = \"topics\";\n\n/**\n * Loads article data including content, tree structure, breadcrumbs, and available versions.\n * @param id - The ID of the article to load\n * @param type - The type of article (\"documents\" or \"topics\", defaults to \"documents\")\n * @returns A Promise resolving to an object containing the article data\n */\nexport const loadArticleData = async (id: string, type: string = DOCUMENT) => {\n const renditionService = new RenditionsService();\n const informationService = new InformationUnitsService();\n const informationUnitsItem = await informationService.getItem({ id });\n\n const { rootNode, result: treeOfContent } = await generateTreeOfContent(informationUnitsItem.directoryNodes);\n\n const articleLanguage = informationUnitsItem.languages[0]\n const versionOf = informationUnitsItem.versionOf.shortId\n\n const versions = await informationService.getList({\n filters: [`versionOf.shortId=${versionOf}`],\n fields: [\"renditions\", \"class\", \"languages\", \"labels\"],\n })\n const availableVersions = versions.items.map((item) => {\n return {\n shortId: item.shortId,\n link: `/${type}/${item.shortId}`,\n lang: item.language,\n country: item.language.split(\"-\")[1],\n active: item.language === articleLanguage,\n }\n }).sort((a, b) => {\n if (a.lang < b.lang) return -1;\n if (a.lang > b.lang) return 1;\n return 0;\n });\n\n let title = informationUnitsItem.labels[0].value\n let documents = renditionService.getFileRenditions(informationUnitsItem.renditions);\n let htmlContent = \"\"\n let rootNodeInfoID = \"\";\n let breadcrumbItems: TreeOfContent[]\n\n if (rootNode != null) {\n title = rootNode.informationUnits[0].labels[0].value;\n rootNodeInfoID = rootNode.informationUnits[0].shortId;\n\n const childInformationUnit = await informationService.getItem({ id: rootNodeInfoID });\n documents = renditionService.getFileRenditions(childInformationUnit.renditions);\n }\n\n if (type == TOPIC) {\n htmlContent = await renditionService.getHTMLRendition(informationUnitsItem.renditions);\n breadcrumbItems = generateBreadcrumbItems(treeOfContent);\n } else {\n\n if (rootNode != null) {\n const directoryId = rootNode.childNodes[0].shortId;\n const infoId = await getLink(directoryId);\n const childInformationUnit = await informationService.getItem({ id: infoId });\n htmlContent = await renditionService.getHTMLRendition(childInformationUnit.renditions);\n }\n\n treeOfContent[0].active = true;\n\n breadcrumbItems = [{\n link: \"/\",\n label: title,\n id: \"title\",\n active: false,\n children: [],\n }]\n }\n\n return {\n htmlContent,\n treeOfContent,\n breadcrumbItems,\n availableVersions,\n documents,\n title,\n articleLanguage\n }\n};","import { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getConfigs } from \"@c-rex/utils/next-cookies\";\n\nexport class CrexSDK {\n public userAuthConfig!: any;\n public customerConfig!: ConfigInterface;\n\n private async getConfig() {\n if (!this.customerConfig) {\n this.customerConfig = await getConfigs()\n }\n }\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,OAAO,WAAqD;;;AC4BrD,IAAM,MAAM;AAAA,EACf,WAAW;AAAA,EACX,aAAa;AAAA,EACb,aAAa;AAAA,IACT,gBAAgB;AAAA,EACpB;AACJ;AAgCO,IAAM,uBAAuB,IAAI,KAAK,KAAK,KAAK;;;ADhEvD,SAAS,cAAc;;;AEMhB,IAAM,OAAO,OAAmB,QAAgB,WAA6B;AAChF,MAAI;AACA,UAAM,MAAM,MAAM,MAAM,GAAG,QAAQ,IA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c,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":["getConfigs"]}
1
+ {"version":3,"sources":["../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":["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,OAAO,WAAqD;;;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,QAAgB,WAA6B;AAChF,MAAI;AACA,UAAM,MAAM,MAAM,MAAM,GAAG,QAAQ,IAAI,mBAAmB,YAAY;AAAA,MAClE,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,MAC9C,MAAM,KAAK,UAAU,EAAE,QAAQ,OAAO,CAAC;AAAA,MACvC,aAAa;AAAA,IACjB,CAAC;AAED,UAAM,OAAO,MAAM,IAAI,KAAK;AAE5B,QAAI,CAAC,IAAI,GAAI,OAAM,IAAI,MAAM,KAAK,SAAS,eAAe;AAE1D,WAAO,KAAK;AAAA,EAChB,SAAS,OAAO;AAEZ,YAAQ,MAAM,KAAK;AACnB,WAAO;AAAA,EACX;AACJ;;;ACnBO,IAAM,YAAY,OAAO,QAAgE;AAC5F,QAAM,MAAM,MAAM,MAAM,GAAG,QAAQ,IAAI,mBAAmB,oBAAoB,GAAG,EAAE;AAEnF,MAAI,CAAC,IAAI,IAAI;AACT,WAAO,EAAE,KAAU,OAAO,KAAK;AAAA,EACnC;AACA,QAAM,OAAO,MAAM,IAAI,KAAK;AAE5B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AChB;AACJ;","names":["getConfigs"]}
package/dist/logger.d.mts CHANGED
@@ -1,15 +1,39 @@
1
1
  import winston from 'winston';
2
2
  import { LogLevelType, LogCategoriesType } from '@c-rex/types';
3
3
 
4
+ /**
5
+ * Logger class for the CREX application.
6
+ * Provides logging functionality with multiple transports (Console, Matomo, Graylog).
7
+ */
4
8
  declare class CrexLogger {
5
9
  private customerConfig;
6
10
  logger: winston.Logger;
11
+ /**
12
+ * Initializes the logger instance if it hasn't been initialized yet.
13
+ * Loads customer configuration and creates the logger with appropriate transports.
14
+ *
15
+ * @private
16
+ */
7
17
  private initLogger;
18
+ /**
19
+ * Logs a message with the specified level and optional category.
20
+ *
21
+ * @param options - Logging options
22
+ * @param options.level - The log level (error, warn, info, etc.)
23
+ * @param options.message - The message to log
24
+ * @param options.category - Optional category for the log message
25
+ */
8
26
  log({ level, message, category }: {
9
27
  level: LogLevelType;
10
28
  message: string;
11
29
  category?: LogCategoriesType;
12
30
  }): Promise<void>;
31
+ /**
32
+ * Creates a new Winston logger instance with configured transports.
33
+ *
34
+ * @private
35
+ * @returns A configured Winston logger instance
36
+ */
13
37
  private createLogger;
14
38
  }
15
39
 
package/dist/logger.d.ts CHANGED
@@ -1,15 +1,39 @@
1
1
  import winston from 'winston';
2
2
  import { LogLevelType, LogCategoriesType } from '@c-rex/types';
3
3
 
4
+ /**
5
+ * Logger class for the CREX application.
6
+ * Provides logging functionality with multiple transports (Console, Matomo, Graylog).
7
+ */
4
8
  declare class CrexLogger {
5
9
  private customerConfig;
6
10
  logger: winston.Logger;
11
+ /**
12
+ * Initializes the logger instance if it hasn't been initialized yet.
13
+ * Loads customer configuration and creates the logger with appropriate transports.
14
+ *
15
+ * @private
16
+ */
7
17
  private initLogger;
18
+ /**
19
+ * Logs a message with the specified level and optional category.
20
+ *
21
+ * @param options - Logging options
22
+ * @param options.level - The log level (error, warn, info, etc.)
23
+ * @param options.message - The message to log
24
+ * @param options.category - Optional category for the log message
25
+ */
8
26
  log({ level, message, category }: {
9
27
  level: LogLevelType;
10
28
  message: string;
11
29
  category?: LogCategoriesType;
12
30
  }): Promise<void>;
31
+ /**
32
+ * Creates a new Winston logger instance with configured transports.
33
+ *
34
+ * @private
35
+ * @returns A configured Winston logger instance
36
+ */
13
37
  private createLogger;
14
38
  }
15
39
 
package/dist/logger.js CHANGED
@@ -53,6 +53,11 @@ var DEFAULT_COOKIE_LIMIT = 7 * 24 * 60 * 60 * 1e3;
53
53
  var MatomoTransport = class extends import_winston_transport.default {
54
54
  matomoTransport;
55
55
  configs;
56
+ /**
57
+ * Creates a new instance of MatomoTransport.
58
+ *
59
+ * @param configs - The application configuration containing logging settings
60
+ */
56
61
  constructor(configs) {
57
62
  super({
58
63
  level: configs.logs.console.minimumLevel,
@@ -61,6 +66,12 @@ var MatomoTransport = class extends import_winston_transport.default {
61
66
  this.matomoTransport = new import_winston_transport.default();
62
67
  this.configs = configs;
63
68
  }
69
+ /**
70
+ * Logs a message to Matomo if the message category is included in the configured categories.
71
+ *
72
+ * @param info - The log information including level, message, and category
73
+ * @param callback - Callback function to execute after logging
74
+ */
64
75
  log(info, callback) {
65
76
  const matomoCategory = this.configs.logs.matomo.categoriesLevel;
66
77
  if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {
@@ -75,6 +86,11 @@ var import_winston_graylog2 = __toESM(require("winston-graylog2"));
75
86
  var GraylogTransport = class extends import_winston_transport2.default {
76
87
  graylogTransport;
77
88
  configs;
89
+ /**
90
+ * Creates a new instance of GraylogTransport.
91
+ *
92
+ * @param configs - The application configuration containing logging settings
93
+ */
78
94
  constructor(configs) {
79
95
  super({
80
96
  level: configs.logs.graylog.minimumLevel,
@@ -90,6 +106,12 @@ var GraylogTransport = class extends import_winston_transport2.default {
90
106
  }
91
107
  });
92
108
  }
109
+ /**
110
+ * Logs a message to Graylog 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
+ */
93
115
  log(info, callback) {
94
116
  const graylogCategory = this.configs.logs.graylog.categoriesLevel;
95
117
  if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {
@@ -103,18 +125,42 @@ var import_next_cookies = require("@c-rex/utils/next-cookies");
103
125
  var CrexLogger = class {
104
126
  customerConfig;
105
127
  logger;
128
+ /**
129
+ * Initializes the logger instance if it hasn't been initialized yet.
130
+ * Loads customer configuration and creates the logger with appropriate transports.
131
+ *
132
+ * @private
133
+ */
106
134
  async initLogger() {
107
- if (!this.customerConfig) {
108
- this.customerConfig = await (0, import_next_cookies.getConfigs)();
109
- }
110
- if (!this.logger) {
111
- this.logger = this.createLogger();
135
+ try {
136
+ if (!this.customerConfig) {
137
+ this.customerConfig = await (0, import_next_cookies.getConfigs)();
138
+ }
139
+ if (!this.logger) {
140
+ this.logger = this.createLogger();
141
+ }
142
+ } catch (error) {
143
+ console.error("Error initializing logger:", error);
112
144
  }
113
145
  }
146
+ /**
147
+ * Logs a message with the specified level and optional category.
148
+ *
149
+ * @param options - Logging options
150
+ * @param options.level - The log level (error, warn, info, etc.)
151
+ * @param options.message - The message to log
152
+ * @param options.category - Optional category for the log message
153
+ */
114
154
  async log({ level, message, category }) {
115
155
  await this.initLogger();
116
156
  this.logger.log(level, message, category);
117
157
  }
158
+ /**
159
+ * Creates a new Winston logger instance with configured transports.
160
+ *
161
+ * @private
162
+ * @returns A configured Winston logger instance
163
+ */
118
164
  createLogger() {
119
165
  return import_winston.default.createLogger({
120
166
  levels: LOG_LEVELS,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/logger.ts","../src/transports/matomo.ts","../../constants/src/index.ts","../src/transports/graylog.ts"],"sourcesContent":["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\nexport class CrexLogger {\n private customerConfig!: ConfigInterface;\n public logger!: winston.Logger;\n\n private async initLogger() {\n if (!this.customerConfig) {\n this.customerConfig = await getConfigs();\n }\n\n if (!this.logger) {\n this.logger = this.createLogger();\n }\n }\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 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\nexport class MatomoTransport extends Transport {\n public matomoTransport: any;\n private configs: ConfigInterface;\n\n constructor(configs: ConfigInterface) {\n super({\n level: configs.logs.console.minimumLevel,\n silent: configs.logs.console.silent,\n });\n\n this.matomoTransport = new Transport();\n this.configs = configs;\n }\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\n this.matomoTransport.log(info, callback);\n }\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] 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 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\";","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\nexport class GraylogTransport extends Transport {\n public graylogTransport: any;\n public configs: ConfigInterface\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: \"Periotto-TEST\",\n silent: false,\n handleExceptions: false,\n graylog: {\n servers: [{ host: \"localhost\", port: 12201 }],\n },\n });\n }\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 (graylogCateg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AM,aAAa,MAAM,MAAM,CAAC;AAAA,MAChD;AAAA,IACJ,CAAC;AAAA,EACL;AAAA,EAEA,IACI,MACA,UACI;AACJ,UAAM,kBAAkB,KAAK,QAAQ,KAAK,QAAQ;AAElD,QAAI,gBAAgB,SAAS,KAAK,QAAQ,KAAK,gBAAgB,SAAS,GAAG,GAAG;AAC1E,WAAK,iBAAiB,IAAI,MAAM,QAAQ;AAAA,IAC5C;AAAA,EACJ;AACJ;;;AH/BA,0BAA2B;AAEpB,IAAM,aAAN,MAAiB;AAAA,EACZ;AAAA,EACD;AAAA,EAEP,MAAc,aAAa;AACvB,QAAI,CAAC,KAAK,gBAAgB;AACtB,WAAK,iBAAiB,UAAM,gCAAW;AAAA,IAC3C;AAEA,QAAI,CAAC,KAAK,QAAQ;AACd,WAAK,SAAS,KAAK,aAAa;AAAA,IACpC;AAAA,EACJ;AAAA,EAEA,MAAa,IAAI,EAAE,OAAO,SAAS,SAAS,GAIzC;AACC,UAAM,KAAK,WAAW;AACtB,SAAK,OAAO,IAAI,OAAO,SAAS,QAAQ;AAAA,EAC5C;AAAA,EAEQ,eAAe;AACnB,WAAO,eAAAC,QAAQ,aAAa;AAAA,MACxB,QAAQ;AAAA,MACR,YAAY;AAAA,QACR,IAAI,eAAAA,QAAQ,WAAW,QAAQ;AAAA,UAC3B,OAAO,KAAK,eAAe,KAAK,QAAQ;AAAA,UACxC,QAAQ,KAAK,eAAe,KAAK,QAAQ;AAAA,QAC7C,CAAC;AAAA,QACD,IAAI,gBAAgB,KAAK,cAAc;AAAA,QACvC,IAAI,iBAAiB,KAAK,cAAc;AAAA,MAC5C;AAAA,IACJ,CAAC;AAAA,EACL;AACJ;","names":["Transport","import_winston_transport","Transport","Graylog2Transport","winston"]}
1
+ {"version":3,"sources":["../src/logger.ts","../src/transports/matomo.ts","../../constants/src/index.ts","../src/transports/graylog.ts"],"sourcesContent":["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\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.console.minimumLevel,\n silent: configs.logs.console.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","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 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 public 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: \"Periotto-TEST\",\n silent: false,\n handleExceptions: false,\n graylog: {\n servers: [{ host: \"localhost\", port: 12201 }],\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;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