@c-rex/core 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -46,7 +46,7 @@ var API = {
46
46
  "content-Type": "application/json"
47
47
  }
48
48
  };
49
- var SDK_CONFIG_KEY = "crex-sdk-config";
49
+ var DEFAULT_COOKIE_LIMIT = 7 * 24 * 60 * 60 * 1e3;
50
50
 
51
51
  // src/requests.ts
52
52
  var import_openid_client = require("openid-client");
@@ -54,7 +54,7 @@ var import_openid_client = require("openid-client");
54
54
  // ../utils/src/utils.ts
55
55
  var call = async (method, params) => {
56
56
  try {
57
- const res = await fetch(`/api/rpc`, {
57
+ const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/rpc`, {
58
58
  method: "POST",
59
59
  headers: { "Content-Type": "application/json" },
60
60
  body: JSON.stringify({ method, params })
@@ -94,6 +94,9 @@ var import_tailwind_merge = require("tailwind-merge");
94
94
  // ../utils/src/treeOfContent.ts
95
95
  var import_services = require("@c-rex/services");
96
96
 
97
+ // ../utils/src/articles.ts
98
+ var import_services2 = require("@c-rex/services");
99
+
97
100
  // src/requests.ts
98
101
  var import_next_cookies = require("@c-rex/utils/next-cookies");
99
102
  var CREX_TOKEN_HEADER_KEY = "crex-token";
@@ -105,13 +108,15 @@ var CrexApi = class {
105
108
  const headersAux = {};
106
109
  if (this.customerConfig.OIDC.client.enabled) {
107
110
  let token = getFromMemory(CREX_TOKEN_HEADER_KEY);
108
- let tokenExpiry = getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY);
111
+ const tokenExpiry = Number(
112
+ getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY)
113
+ );
109
114
  const now = Math.floor(Date.now() / 1e3);
110
115
  if (!(token && tokenExpiry > now + 60)) {
111
116
  const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();
112
117
  token = tokenAux;
113
118
  saveInMemory(token, CREX_TOKEN_HEADER_KEY);
114
- saveInMemory(tokenExpiryAux, CREX_TOKEN_EXPIRY_HEADER_KEY);
119
+ saveInMemory(tokenExpiryAux.toString(), CREX_TOKEN_EXPIRY_HEADER_KEY);
115
120
  }
116
121
  headersAux["Authorization"] = `Bearer ${token}`;
117
122
  }
@@ -143,11 +148,7 @@ var CrexApi = class {
143
148
  }
144
149
  async initAPI() {
145
150
  if (!this.customerConfig) {
146
- const jsonConfigs = await (0, import_next_cookies.getCookie)(SDK_CONFIG_KEY);
147
- if (!jsonConfigs) {
148
- throw new Error("SDK not initialized");
149
- }
150
- this.customerConfig = JSON.parse(jsonConfigs);
151
+ this.customerConfig = await (0, import_next_cookies.getConfigs)();
151
152
  }
152
153
  if (!this.apiClient) {
153
154
  this.apiClient = import_axios.default.create({
@@ -179,10 +180,10 @@ var CrexApi = class {
179
180
  });
180
181
  break;
181
182
  } catch (error) {
182
- console.log(
183
- "error",
184
- `API.execute ${retry + 1}\xBA error when request ${url}. Error: ${error}`
185
- );
183
+ call("CrexLogger.log", {
184
+ level: "error",
185
+ message: `API.execute ${retry + 1}\xBA error when request ${url}. Error: ${error}`
186
+ });
186
187
  if (retry === API.MAX_RETRY - 1) {
187
188
  throw error;
188
189
  }
@@ -202,11 +203,7 @@ var CrexSDK = class {
202
203
  customerConfig;
203
204
  async getConfig() {
204
205
  if (!this.customerConfig) {
205
- const jsonConfigs = await (0, import_next_cookies2.getCookie)(SDK_CONFIG_KEY);
206
- if (!jsonConfigs) {
207
- throw new Error("SDK not initialized");
208
- }
209
- this.customerConfig = JSON.parse(jsonConfigs);
206
+ this.customerConfig = await (0, import_next_cookies2.getConfigs)();
210
207
  }
211
208
  }
212
209
  async getUserAuthConfig() {
@@ -215,27 +212,30 @@ var CrexSDK = class {
215
212
  }
216
213
  await this.getConfig();
217
214
  const user = this.customerConfig.OIDC.user;
218
- this.userAuthConfig = {
219
- providers: [
220
- {
221
- id: "crex",
222
- name: "CREX",
223
- type: "oauth",
224
- clientId: user.id,
225
- wellKnown: user.issuer,
226
- clientSecret: user.secret,
227
- authorization: { params: { scope: user.scope } },
228
- profile(profile) {
229
- return {
230
- id: profile.id || "fake Id",
231
- name: profile.name || "Fake Name",
232
- email: profile.email || "fake Email",
233
- image: profile.image || "fake Image"
234
- };
215
+ if (user.enabled) {
216
+ this.userAuthConfig = {
217
+ providers: [
218
+ {
219
+ id: "crex",
220
+ name: "CREX",
221
+ type: "oauth",
222
+ clientId: user.id,
223
+ wellKnown: user.issuer,
224
+ clientSecret: user.secret,
225
+ authorization: { params: { scope: user.scope } },
226
+ profile(profile) {
227
+ return {
228
+ id: profile.id || "fake Id",
229
+ name: profile.name || "Fake Name",
230
+ email: profile.email || "fake Email",
231
+ image: profile.image || "fake Image"
232
+ };
233
+ }
235
234
  }
236
- }
237
- ]
238
- };
235
+ ]
236
+ };
237
+ }
238
+ ;
239
239
  return this.userAuthConfig;
240
240
  }
241
241
  };
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/treeOfContent.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, SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { Issuer } from \"openid-client\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { call, getFromMemory, saveInMemory } from \"@c-rex/utils\";\nimport { getCookie } 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 let tokenExpiry = getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY);\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, CREX_TOKEN_EXPIRY_HEADER_KEY);\n }\n\n headersAux['Authorization'] = `Bearer ${token}`;\n }\n\n return headersAux;\n }\n\n private async getToken(): Promise<{\n token: string;\n tokenExpiry: number;\n }> {\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 const jsonConfigs = await getCookie(SDK_CONFIG_KEY);\n if (!jsonConfigs) {\n throw new Error(\"SDK not initialized\");\n }\n this.customerConfig = JSON.parse(jsonConfigs) as ConfigInterface;\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 //TODO: add logger\n console.log(\n \"error\",\n `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 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 UI_LANG_KEY = \"UI_LANG_KEY\";\n\nexport const FLAGS_BY_LANG = {\n \"en\": \"US\",\n \"de\": \"DE\",\n};\n\nexport const DEFAULT_UI_LANG = \"en\";\nexport const UI_LANG_OPTIONS = [\"en\", \"de\"];","import { FLAGS_BY_LANG } from \"@c-rex/constants\";\n\nexport const call = async<T = unknown>(method: string, params?: any): Promise<T> => {\n try {\n const res = await fetch(`/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 console.error(error);\n return null as any;\n }\n}\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}","export function isBrowser() {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\nexport function saveInMemory(value: any, 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\nexport function getFromMemory(key: string): any {\n if (isBrowser()) throw new Error(\"getFromMemory is not supported in browser\");\n\n return (global as any)[key];\n}\n","import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\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\nexport const generateTreeOfContent = async (\n directoryNodes: DirectoryNodes[],\n): Promise<TreeOfContent[]> => {\n\n const service = new DirectoryNodesService();\n\n if (directoryNodes.length == 0) return [];\n if (directoryNodes[0] == undefined) return [];\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 if (response.informationUnits[0] == undefined) return result;\n if (response.labels[0] == undefined) return result;\n if (response.parents[0] == undefined) return result;\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: `/info/${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 result;\n};\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[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: `/info/${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\n return result;\n};\n\nconst getLink = async (id: string): Promise<string> => {\n const service = new DirectoryNodesService();\n const response = await service.getItem(id);\n\n if (response.informationUnits == undefined) return \"\";\n if (response.informationUnits[0] == undefined) return \"\";\n\n return response.informationUnits[0].shortId;\n};","import { SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getCookie } 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 const jsonConfigs = await getCookie(SDK_CONFIG_KEY);\n if (!jsonConfigs) {\n throw new Error(\"SDK not initialized\");\n }\n this.customerConfig = JSON.parse(jsonConfigs) as ConfigInterface;\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\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 return this.userAuthConfig;\n }\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,m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,EACJ;AAAA,EAEA,MAAa,oBAAoB;AAC7B,QAAI,KAAK,gBAAgB;AACrB,aAAO,KAAK;AAAA,IAChB;AAEA,UAAM,KAAK,UAAU;AAErB,UAAM,OAAO,KAAK,eAAe,KAAK;AAEtC,SAAK,iBAAiB;AAAA,MAClB,WAAW;AAAA,QACP;AAAA,UACI,IAAI;AAAA,UACJ,MAAM;AAAA,UACN,MAAM;AAAA,UACN,UAAU,KAAK;AAAA,UACf,WAAW,KAAK;AAAA,UAChB,cAAc,KAAK;AAAA,UACnB,eAAe,EAAE,QAAQ,EAAE,OAAO,KAAK,MAAM,EAAE;AAAA,UAC/C,QAAQ,SAAc;AAClB,mBAAO;AAAA,cACH,IAAI,QAAQ,MAAM;AAAA,cAClB,MAAM,QAAQ,QAAQ;AAAA,cACtB,OAAO,QAAQ,SAAS;AAAA,cACxB,OAAO,QAAQ,SAAS;AAAA,YAC5B;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAEA,WAAO,KAAK;AAAA,EAChB;AACJ;","names":["axios","import_next_cookies"]}
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/treeOfContent.ts","../../utils/src/articles.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 { 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;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;AAgCO,IAAM,uBAAuB,IAAI,KAAK,KAAK,KAAK;;;ADhEvD,2BAAuB;;;AEMhB,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,IAC3C,CAAC;AAED,UAAM,OAAO,MAAM,IAAI,KAAK;AAE5B,QAAI,CAAC,IAAI,GAAI,OAA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AC5B;AAAA,YACJ;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAC;AAED,WAAO,KAAK;AAAA,EAChB;AACJ;","names":["import_services","axios","import_next_cookies"]}
package/dist/index.mjs CHANGED
@@ -9,7 +9,7 @@ var API = {
9
9
  "content-Type": "application/json"
10
10
  }
11
11
  };
12
- var SDK_CONFIG_KEY = "crex-sdk-config";
12
+ var DEFAULT_COOKIE_LIMIT = 7 * 24 * 60 * 60 * 1e3;
13
13
 
14
14
  // src/requests.ts
15
15
  import { Issuer } from "openid-client";
@@ -17,7 +17,7 @@ import { Issuer } from "openid-client";
17
17
  // ../utils/src/utils.ts
18
18
  var call = async (method, params) => {
19
19
  try {
20
- const res = await fetch(`/api/rpc`, {
20
+ const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/rpc`, {
21
21
  method: "POST",
22
22
  headers: { "Content-Type": "application/json" },
23
23
  body: JSON.stringify({ method, params })
@@ -57,8 +57,11 @@ import { twMerge } from "tailwind-merge";
57
57
  // ../utils/src/treeOfContent.ts
58
58
  import { DirectoryNodesService } from "@c-rex/services";
59
59
 
60
+ // ../utils/src/articles.ts
61
+ import { InformationUnitsService, RenditionsService } from "@c-rex/services";
62
+
60
63
  // src/requests.ts
61
- import { getCookie } from "@c-rex/utils/next-cookies";
64
+ import { getConfigs } from "@c-rex/utils/next-cookies";
62
65
  var CREX_TOKEN_HEADER_KEY = "crex-token";
63
66
  var CREX_TOKEN_EXPIRY_HEADER_KEY = "crex-token-expiry";
64
67
  var CrexApi = class {
@@ -68,13 +71,15 @@ var CrexApi = class {
68
71
  const headersAux = {};
69
72
  if (this.customerConfig.OIDC.client.enabled) {
70
73
  let token = getFromMemory(CREX_TOKEN_HEADER_KEY);
71
- let tokenExpiry = getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY);
74
+ const tokenExpiry = Number(
75
+ getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY)
76
+ );
72
77
  const now = Math.floor(Date.now() / 1e3);
73
78
  if (!(token && tokenExpiry > now + 60)) {
74
79
  const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();
75
80
  token = tokenAux;
76
81
  saveInMemory(token, CREX_TOKEN_HEADER_KEY);
77
- saveInMemory(tokenExpiryAux, CREX_TOKEN_EXPIRY_HEADER_KEY);
82
+ saveInMemory(tokenExpiryAux.toString(), CREX_TOKEN_EXPIRY_HEADER_KEY);
78
83
  }
79
84
  headersAux["Authorization"] = `Bearer ${token}`;
80
85
  }
@@ -106,11 +111,7 @@ var CrexApi = class {
106
111
  }
107
112
  async initAPI() {
108
113
  if (!this.customerConfig) {
109
- const jsonConfigs = await getCookie(SDK_CONFIG_KEY);
110
- if (!jsonConfigs) {
111
- throw new Error("SDK not initialized");
112
- }
113
- this.customerConfig = JSON.parse(jsonConfigs);
114
+ this.customerConfig = await getConfigs();
114
115
  }
115
116
  if (!this.apiClient) {
116
117
  this.apiClient = axios.create({
@@ -142,10 +143,10 @@ var CrexApi = class {
142
143
  });
143
144
  break;
144
145
  } catch (error) {
145
- console.log(
146
- "error",
147
- `API.execute ${retry + 1}\xBA error when request ${url}. Error: ${error}`
148
- );
146
+ call("CrexLogger.log", {
147
+ level: "error",
148
+ message: `API.execute ${retry + 1}\xBA error when request ${url}. Error: ${error}`
149
+ });
149
150
  if (retry === API.MAX_RETRY - 1) {
150
151
  throw error;
151
152
  }
@@ -159,17 +160,13 @@ var CrexApi = class {
159
160
  };
160
161
 
161
162
  // src/sdk.ts
162
- import { getCookie as getCookie2 } from "@c-rex/utils/next-cookies";
163
+ import { getConfigs as getConfigs2 } from "@c-rex/utils/next-cookies";
163
164
  var CrexSDK = class {
164
165
  userAuthConfig;
165
166
  customerConfig;
166
167
  async getConfig() {
167
168
  if (!this.customerConfig) {
168
- const jsonConfigs = await getCookie2(SDK_CONFIG_KEY);
169
- if (!jsonConfigs) {
170
- throw new Error("SDK not initialized");
171
- }
172
- this.customerConfig = JSON.parse(jsonConfigs);
169
+ this.customerConfig = await getConfigs2();
173
170
  }
174
171
  }
175
172
  async getUserAuthConfig() {
@@ -178,27 +175,30 @@ var CrexSDK = class {
178
175
  }
179
176
  await this.getConfig();
180
177
  const user = this.customerConfig.OIDC.user;
181
- this.userAuthConfig = {
182
- providers: [
183
- {
184
- id: "crex",
185
- name: "CREX",
186
- type: "oauth",
187
- clientId: user.id,
188
- wellKnown: user.issuer,
189
- clientSecret: user.secret,
190
- authorization: { params: { scope: user.scope } },
191
- profile(profile) {
192
- return {
193
- id: profile.id || "fake Id",
194
- name: profile.name || "Fake Name",
195
- email: profile.email || "fake Email",
196
- image: profile.image || "fake Image"
197
- };
178
+ if (user.enabled) {
179
+ this.userAuthConfig = {
180
+ providers: [
181
+ {
182
+ id: "crex",
183
+ name: "CREX",
184
+ type: "oauth",
185
+ clientId: user.id,
186
+ wellKnown: user.issuer,
187
+ clientSecret: user.secret,
188
+ authorization: { params: { scope: user.scope } },
189
+ profile(profile) {
190
+ return {
191
+ id: profile.id || "fake Id",
192
+ name: profile.name || "Fake Name",
193
+ email: profile.email || "fake Email",
194
+ image: profile.image || "fake Image"
195
+ };
196
+ }
198
197
  }
199
- }
200
- ]
201
- };
198
+ ]
199
+ };
200
+ }
201
+ ;
202
202
  return this.userAuthConfig;
203
203
  }
204
204
  };
@@ -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","../src/sdk.ts"],"sourcesContent":["import axios, { AxiosResponse, Method, AxiosInstance } from \"axios\";\nimport { API, SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { Issuer } from \"openid-client\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { call, getFromMemory, saveInMemory } from \"@c-rex/utils\";\nimport { getCookie } 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 let tokenExpiry = getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY);\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, CREX_TOKEN_EXPIRY_HEADER_KEY);\n }\n\n headersAux['Authorization'] = `Bearer ${token}`;\n }\n\n return headersAux;\n }\n\n private async getToken(): Promise<{\n token: string;\n tokenExpiry: number;\n }> {\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 const jsonConfigs = await getCookie(SDK_CONFIG_KEY);\n if (!jsonConfigs) {\n throw new Error(\"SDK not initialized\");\n }\n this.customerConfig = JSON.parse(jsonConfigs) as ConfigInterface;\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 //TODO: add logger\n console.log(\n \"error\",\n `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 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 UI_LANG_KEY = \"UI_LANG_KEY\";\n\nexport const FLAGS_BY_LANG = {\n \"en\": \"US\",\n \"de\": \"DE\",\n};\n\nexport const DEFAULT_UI_LANG = \"en\";\nexport const UI_LANG_OPTIONS = [\"en\", \"de\"];","import { FLAGS_BY_LANG } from \"@c-rex/constants\";\n\nexport const call = async<T = unknown>(method: string, params?: any): Promise<T> => {\n try {\n const res = await fetch(`/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 console.error(error);\n return null as any;\n }\n}\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}","export function isBrowser() {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\nexport function saveInMemory(value: any, 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\nexport function getFromMemory(key: string): any {\n if (isBrowser()) throw new Error(\"getFromMemory is not supported in browser\");\n\n return (global as any)[key];\n}\n","import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\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\nexport const generateTreeOfContent = async (\n directoryNodes: DirectoryNodes[],\n): Promise<TreeOfContent[]> => {\n\n const service = new DirectoryNodesService();\n\n if (directoryNodes.length == 0) return [];\n if (directoryNodes[0] == undefined) return [];\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 if (response.informationUnits[0] == undefined) return result;\n if (response.labels[0] == undefined) return result;\n if (response.parents[0] == undefined) return result;\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: `/info/${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 result;\n};\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[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: `/info/${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\n return result;\n};\n\nconst getLink = async (id: string): Promise<string> => {\n const service = new DirectoryNodesService();\n const response = await service.getItem(id);\n\n if (response.informationUnits == undefined) return \"\";\n if (response.informationUnits[0] == undefined) return \"\";\n\n return response.informationUnits[0].shortId;\n};","import { SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getCookie } 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 const jsonConfigs = await getCookie(SDK_CONFIG_KEY);\n if (!jsonConfigs) {\n throw new Error(\"SDK not initialized\");\n }\n this.customerConfig = JSON.parse(jsonConfigs) as ConfigInterface;\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\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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M,IAAI,MAAM,qBAAqB;AAAA,MACzC;AACA,WAAK,iBAAiB,KAAK,MAAM,WAAW;AAAA,IAChD;AAAA,EACJ;AAAA,EAEA,MAAa,oBAAoB;AAC7B,QAAI,KAAK,gBAAgB;AACrB,aAAO,KAAK;AAAA,IAChB;AAEA,UAAM,KAAK,UAAU;AAErB,UAAM,OAAO,KAAK,eAAe,KAAK;AAEtC,SAAK,iBAAiB;AAAA,MAClB,WAAW;AAAA,QACP;AAAA,UACI,IAAI;AAAA,UACJ,MAAM;AAAA,UACN,MAAM;AAAA,UACN,UAAU,KAAK;AAAA,UACf,WAAW,KAAK;AAAA,UAChB,cAAc,KAAK;AAAA,UACnB,eAAe,EAAE,QAAQ,EAAE,OAAO,KAAK,MAAM,EAAE;AAAA,UAC/C,QAAQ,SAAc;AAClB,mBAAO;AAAA,cACH,IAAI,QAAQ,MAAM;AAAA,cAClB,MAAM,QAAQ,QAAQ;AAAA,cACtB,OAAO,QAAQ,SAAS;AAAA,cACxB,OAAO,QAAQ,SAAS;AAAA,YAC5B;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAEA,WAAO,KAAK;AAAA,EAChB;AACJ;","names":["getCookie"]}
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,IAAI,mBAAmB,YAAY;AAAA,MAClE,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,MAC9C,MAAM,KAAK,UAAU,EAAE,QAAQ,OAAO,CAAC;AAAA,IAC3C,CAAC;AAED,UAAM,OAAO,MAAM,IAAI,KAAK;AAE5B,QAAI,CAAC,IAAI,GAAI,OAAM,IAAI,MAAM,KAAK,SAAS,eAAe;AAE1D,WAAO,KAAK;AAAA,EAChB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J;AAAA,MACJ;AAAA,IACJ;AAAC;AAED,WAAO,KAAK;AAAA,EAChB;AACJ;","names":["getConfigs"]}
package/dist/logger.js CHANGED
@@ -47,63 +47,22 @@ var LOG_LEVELS = {
47
47
  info: 6,
48
48
  debug: 7
49
49
  };
50
- var SDK_CONFIG_KEY = "crex-sdk-config";
51
-
52
- // src/sdk.ts
53
- var import_next_cookies = require("@c-rex/utils/next-cookies");
54
- var CrexSDK = class {
55
- userAuthConfig;
56
- customerConfig;
57
- async getConfig() {
58
- if (!this.customerConfig) {
59
- const jsonConfigs = await (0, import_next_cookies.getCookie)(SDK_CONFIG_KEY);
60
- if (!jsonConfigs) {
61
- throw new Error("SDK not initialized");
62
- }
63
- this.customerConfig = JSON.parse(jsonConfigs);
64
- }
65
- }
66
- async getUserAuthConfig() {
67
- if (this.userAuthConfig) {
68
- return this.userAuthConfig;
69
- }
70
- await this.getConfig();
71
- const user = this.customerConfig.OIDC.user;
72
- this.userAuthConfig = {
73
- providers: [
74
- {
75
- id: "crex",
76
- name: "CREX",
77
- type: "oauth",
78
- clientId: user.id,
79
- wellKnown: user.issuer,
80
- clientSecret: user.secret,
81
- authorization: { params: { scope: user.scope } },
82
- profile(profile) {
83
- return {
84
- id: profile.id || "fake Id",
85
- name: profile.name || "Fake Name",
86
- email: profile.email || "fake Email",
87
- image: profile.image || "fake Image"
88
- };
89
- }
90
- }
91
- ]
92
- };
93
- return this.userAuthConfig;
94
- }
95
- };
50
+ var DEFAULT_COOKIE_LIMIT = 7 * 24 * 60 * 60 * 1e3;
96
51
 
97
52
  // src/transports/matomo.ts
98
53
  var MatomoTransport = class extends import_winston_transport.default {
99
54
  matomoTransport;
100
- constructor(opts) {
101
- super(opts);
55
+ configs;
56
+ constructor(configs) {
57
+ super({
58
+ level: configs.logs.console.minimumLevel,
59
+ silent: configs.logs.console.silent
60
+ });
102
61
  this.matomoTransport = new import_winston_transport.default();
62
+ this.configs = configs;
103
63
  }
104
64
  log(info, callback) {
105
- const SDK = CrexSDK.getInstance();
106
- const matomoCategory = SDK.customerConfig.logs.matomo.categoriesLevel;
65
+ const matomoCategory = this.configs.logs.matomo.categoriesLevel;
107
66
  if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {
108
67
  this.matomoTransport.log(info, callback);
109
68
  }
@@ -115,8 +74,13 @@ var import_winston_transport2 = __toESM(require("winston-transport"));
115
74
  var import_winston_graylog2 = __toESM(require("winston-graylog2"));
116
75
  var GraylogTransport = class extends import_winston_transport2.default {
117
76
  graylogTransport;
118
- constructor(opts) {
119
- super(opts);
77
+ configs;
78
+ constructor(configs) {
79
+ super({
80
+ level: configs.logs.graylog.minimumLevel,
81
+ silent: configs.logs.graylog.silent
82
+ });
83
+ this.configs = configs;
120
84
  this.graylogTransport = new import_winston_graylog2.default({
121
85
  name: "Periotto-TEST",
122
86
  silent: false,
@@ -127,8 +91,7 @@ var GraylogTransport = class extends import_winston_transport2.default {
127
91
  });
128
92
  }
129
93
  log(info, callback) {
130
- const SDK = CrexSDK.getInstance();
131
- const graylogCategory = SDK.customerConfig.logs.graylog.categoriesLevel;
94
+ const graylogCategory = this.configs.logs.graylog.categoriesLevel;
132
95
  if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {
133
96
  this.graylogTransport.log(info, callback);
134
97
  }
@@ -136,17 +99,13 @@ var GraylogTransport = class extends import_winston_transport2.default {
136
99
  };
137
100
 
138
101
  // src/logger.ts
139
- var import_next_cookies2 = require("@c-rex/utils/next-cookies");
102
+ var import_next_cookies = require("@c-rex/utils/next-cookies");
140
103
  var CrexLogger = class {
141
104
  customerConfig;
142
105
  logger;
143
106
  async initLogger() {
144
107
  if (!this.customerConfig) {
145
- const jsonConfigs = await (0, import_next_cookies2.getCookie)(SDK_CONFIG_KEY);
146
- if (!jsonConfigs) {
147
- throw new Error("SDK not initialized");
148
- }
149
- this.customerConfig = JSON.parse(jsonConfigs);
108
+ this.customerConfig = await (0, import_next_cookies.getConfigs)();
150
109
  }
151
110
  if (!this.logger) {
152
111
  this.logger = this.createLogger();
@@ -164,14 +123,8 @@ var CrexLogger = class {
164
123
  level: this.customerConfig.logs.console.minimumLevel,
165
124
  silent: this.customerConfig.logs.console.silent
166
125
  }),
167
- new MatomoTransport({
168
- level: this.customerConfig.logs.console.minimumLevel,
169
- silent: this.customerConfig.logs.console.silent
170
- }),
171
- new GraylogTransport({
172
- level: this.customerConfig.logs.graylog.minimumLevel,
173
- silent: this.customerConfig.logs.graylog.silent
174
- })
126
+ new MatomoTransport(this.customerConfig),
127
+ new GraylogTransport(this.customerConfig)
175
128
  ]
176
129
  });
177
130
  }