@c-rex/core 0.0.9 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -9,22 +9,19 @@ interface CallParams {
9
9
  params?: any;
10
10
  }
11
11
  declare class CrexApi {
12
- private config;
12
+ private customerConfig;
13
13
  private apiClient;
14
- private logger;
15
- constructor(config: ConfigInterface, logger: any);
16
14
  private manageToken;
17
15
  private getToken;
16
+ private initAPI;
18
17
  execute<T>({ url, method, params, body, headers, }: CallParams): Promise<T>;
19
18
  }
20
19
 
21
20
  declare class CrexSDK {
22
- api: CrexApi;
23
- logger: any;
24
21
  userAuthConfig: any;
25
22
  customerConfig: ConfigInterface;
26
- constructor();
27
- static setConfig(config: ConfigInterface): void;
23
+ private getConfig;
24
+ getUserAuthConfig(): Promise<any>;
28
25
  }
29
26
 
30
27
  export { CrexApi, CrexSDK };
package/dist/index.d.ts CHANGED
@@ -9,22 +9,19 @@ interface CallParams {
9
9
  params?: any;
10
10
  }
11
11
  declare class CrexApi {
12
- private config;
12
+ private customerConfig;
13
13
  private apiClient;
14
- private logger;
15
- constructor(config: ConfigInterface, logger: any);
16
14
  private manageToken;
17
15
  private getToken;
16
+ private initAPI;
18
17
  execute<T>({ url, method, params, body, headers, }: CallParams): Promise<T>;
19
18
  }
20
19
 
21
20
  declare class CrexSDK {
22
- api: CrexApi;
23
- logger: any;
24
21
  userAuthConfig: any;
25
22
  customerConfig: ConfigInterface;
26
- constructor();
27
- static setConfig(config: ConfigInterface): void;
23
+ private getConfig;
24
+ getUserAuthConfig(): Promise<any>;
28
25
  }
29
26
 
30
27
  export { CrexApi, CrexSDK };
package/dist/index.js CHANGED
@@ -1,35 +1,120 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _class;// src/requests.ts
2
- var _axios = require('axios'); var _axios2 = _interopRequireDefault(_axios);
3
- var _constants = require('@c-rex/constants');
4
- var _openidclient = require('openid-client');
5
- var _utils = require('@c-rex/utils');
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ CrexApi: () => CrexApi,
34
+ CrexSDK: () => CrexSDK
35
+ });
36
+ module.exports = __toCommonJS(index_exports);
37
+
38
+ // src/requests.ts
39
+ var import_axios = __toESM(require("axios"));
40
+
41
+ // ../constants/src/index.ts
42
+ var API = {
43
+ MAX_RETRY: 3,
44
+ API_TIMEOUT: 1e4,
45
+ API_HEADERS: {
46
+ "content-Type": "application/json"
47
+ }
48
+ };
49
+ var SDK_CONFIG_KEY = "crex-sdk-config";
50
+
51
+ // src/requests.ts
52
+ var import_openid_client = require("openid-client");
53
+
54
+ // ../utils/src/utils.ts
55
+ var call = async (method, params) => {
56
+ try {
57
+ const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/rpc`, {
58
+ method: "POST",
59
+ headers: { "Content-Type": "application/json" },
60
+ body: JSON.stringify({ method, params })
61
+ });
62
+ const json = await res.json();
63
+ if (!res.ok) throw new Error(json.error || "Unknown error");
64
+ return json.data;
65
+ } catch (error) {
66
+ console.error(error);
67
+ return null;
68
+ }
69
+ };
70
+
71
+ // ../utils/src/memory.ts
72
+ function isBrowser() {
73
+ return typeof window !== "undefined" && typeof document !== "undefined";
74
+ }
75
+ function saveInMemory(value, key) {
76
+ if (isBrowser()) throw new Error("saveInMemory is not supported in browser");
77
+ if (typeof global !== "undefined" && !(key in global)) {
78
+ global[key] = null;
79
+ }
80
+ const globalConfig = global[key];
81
+ if (globalConfig === null) {
82
+ global[key] = value;
83
+ }
84
+ }
85
+ function getFromMemory(key) {
86
+ if (isBrowser()) throw new Error("getFromMemory is not supported in browser");
87
+ return global[key];
88
+ }
89
+
90
+ // ../utils/src/classMerge.ts
91
+ var import_clsx = require("clsx");
92
+ var import_tailwind_merge = require("tailwind-merge");
93
+
94
+ // ../utils/src/treeOfContent.ts
95
+ var import_services = require("@c-rex/services");
96
+
97
+ // ../utils/src/articles.ts
98
+ var import_services2 = require("@c-rex/services");
99
+
100
+ // src/requests.ts
101
+ var import_next_cookies = require("@c-rex/utils/next-cookies");
6
102
  var CREX_TOKEN_HEADER_KEY = "crex-token";
7
103
  var CREX_TOKEN_EXPIRY_HEADER_KEY = "crex-token-expiry";
8
104
  var CrexApi = class {
9
-
10
-
11
-
12
- constructor(config, logger) {
13
- this.apiClient = _axios2.default.create({
14
- baseURL: config.baseUrl,
15
- headers: {
16
- "content-Type": "application/json"
17
- }
18
- });
19
- this.config = config;
20
- this.logger = logger;
21
- }
105
+ customerConfig;
106
+ apiClient;
22
107
  async manageToken() {
23
108
  const headersAux = {};
24
- if (this.config.OIDC.client.enabled) {
25
- let token = _utils.getFromMemory.call(void 0, CREX_TOKEN_HEADER_KEY);
26
- let tokenExpiry = _utils.getFromMemory.call(void 0, CREX_TOKEN_EXPIRY_HEADER_KEY);
109
+ if (this.customerConfig.OIDC.client.enabled) {
110
+ let token = getFromMemory(CREX_TOKEN_HEADER_KEY);
111
+ let tokenExpiry = getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY);
27
112
  const now = Math.floor(Date.now() / 1e3);
28
113
  if (!(token && tokenExpiry > now + 60)) {
29
114
  const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();
30
115
  token = tokenAux;
31
- _utils.saveInMemory.call(void 0, token, CREX_TOKEN_HEADER_KEY);
32
- _utils.saveInMemory.call(void 0, tokenExpiryAux, CREX_TOKEN_EXPIRY_HEADER_KEY);
116
+ saveInMemory(token, CREX_TOKEN_HEADER_KEY);
117
+ saveInMemory(tokenExpiryAux, CREX_TOKEN_EXPIRY_HEADER_KEY);
33
118
  }
34
119
  headersAux["Authorization"] = `Bearer ${token}`;
35
120
  }
@@ -40,21 +125,40 @@ var CrexApi = class {
40
125
  let tokenExpiry = 0;
41
126
  try {
42
127
  const now = Math.floor(Date.now() / 1e3);
43
- const issuer = await _openidclient.Issuer.discover(this.config.OIDC.client.issuer);
128
+ const issuer = await import_openid_client.Issuer.discover(this.customerConfig.OIDC.client.issuer);
44
129
  const client = new issuer.Client({
45
- client_id: this.config.OIDC.client.id,
46
- client_secret: this.config.OIDC.client.secret
130
+ client_id: this.customerConfig.OIDC.client.id,
131
+ client_secret: this.customerConfig.OIDC.client.secret
47
132
  });
48
133
  const tokenSet = await client.grant({ grant_type: "client_credentials" });
49
- token = tokenSet.access_token, tokenExpiry = now + tokenSet.expires_at;
134
+ token = tokenSet.access_token;
135
+ tokenExpiry = now + tokenSet.expires_at;
136
+ console.log("token", token);
50
137
  } catch (error) {
51
- console.log("error", `API.getToken error when request ${this.config.OIDC.client.issuer}. Error: ${error}`);
138
+ call("CrexLogger.log", {
139
+ level: "error",
140
+ message: `API.getToken error when request ${this.customerConfig.OIDC.client.issuer}. Error: ${error}`
141
+ });
52
142
  }
53
143
  return {
54
144
  token,
55
145
  tokenExpiry
56
146
  };
57
147
  }
148
+ async initAPI() {
149
+ if (!this.customerConfig) {
150
+ const jsonConfigs = await (0, import_next_cookies.getCookie)(SDK_CONFIG_KEY);
151
+ if (!jsonConfigs) {
152
+ throw new Error("SDK not initialized");
153
+ }
154
+ this.customerConfig = JSON.parse(jsonConfigs);
155
+ }
156
+ if (!this.apiClient) {
157
+ this.apiClient = import_axios.default.create({
158
+ baseURL: this.customerConfig.baseUrl
159
+ });
160
+ }
161
+ }
58
162
  async execute({
59
163
  url,
60
164
  method,
@@ -62,12 +166,13 @@ var CrexApi = class {
62
166
  body,
63
167
  headers = {}
64
168
  }) {
169
+ await this.initAPI();
65
170
  let response = void 0;
66
171
  headers = {
67
172
  ...headers,
68
173
  ...await this.manageToken()
69
174
  };
70
- for (let retry = 0; retry < _constants.API.MAX_RETRY; retry++) {
175
+ for (let retry = 0; retry < API.MAX_RETRY; retry++) {
71
176
  try {
72
177
  response = await this.apiClient.request({
73
178
  url,
@@ -82,7 +187,7 @@ var CrexApi = class {
82
187
  "error",
83
188
  `API.execute ${retry + 1}\xBA error when request ${url}. Error: ${error}`
84
189
  );
85
- if (retry === _constants.API.MAX_RETRY - 1) {
190
+ if (retry === API.MAX_RETRY - 1) {
86
191
  throw error;
87
192
  }
88
193
  }
@@ -95,46 +200,55 @@ var CrexApi = class {
95
200
  };
96
201
 
97
202
  // src/sdk.ts
98
-
99
-
100
- var CrexSDK = (_class = class {
101
-
102
-
103
- __init() {this.userAuthConfig = {}}
104
-
105
- constructor() {;_class.prototype.__init.call(this);
106
- const config = _utils.getFromMemory.call(void 0, _constants.SDK_CONFIG_KEY);
107
- this.customerConfig = config;
108
- this.api = new CrexApi(this.customerConfig, null);
203
+ var import_next_cookies2 = require("@c-rex/utils/next-cookies");
204
+ var CrexSDK = class {
205
+ userAuthConfig;
206
+ customerConfig;
207
+ async getConfig() {
208
+ if (!this.customerConfig) {
209
+ const jsonConfigs = await (0, import_next_cookies2.getCookie)(SDK_CONFIG_KEY);
210
+ if (!jsonConfigs) {
211
+ throw new Error("SDK not initialized");
212
+ }
213
+ this.customerConfig = JSON.parse(jsonConfigs);
214
+ }
215
+ }
216
+ async getUserAuthConfig() {
217
+ if (this.userAuthConfig) {
218
+ return this.userAuthConfig;
219
+ }
220
+ await this.getConfig();
109
221
  const user = this.customerConfig.OIDC.user;
110
- this.userAuthConfig = {
111
- providers: [
112
- {
113
- id: "crex",
114
- name: "CREX",
115
- type: "oauth",
116
- clientId: user.id,
117
- wellKnown: user.issuer,
118
- clientSecret: user.secret,
119
- authorization: { params: { scope: user.scope } },
120
- profile(profile) {
121
- return {
122
- id: profile.id || "fake Id",
123
- name: profile.name || "Fake Name",
124
- email: profile.email || "fake Email",
125
- image: profile.image || "fake Image"
126
- };
222
+ if (user.enabled) {
223
+ this.userAuthConfig = {
224
+ providers: [
225
+ {
226
+ id: "crex",
227
+ name: "CREX",
228
+ type: "oauth",
229
+ clientId: user.id,
230
+ wellKnown: user.issuer,
231
+ clientSecret: user.secret,
232
+ authorization: { params: { scope: user.scope } },
233
+ profile(profile) {
234
+ return {
235
+ id: profile.id || "fake Id",
236
+ name: profile.name || "Fake Name",
237
+ email: profile.email || "fake Email",
238
+ image: profile.image || "fake Image"
239
+ };
240
+ }
127
241
  }
128
- }
129
- ]
130
- };
131
- }
132
- static setConfig(config) {
133
- _utils.saveInMemory.call(void 0, config, _constants.SDK_CONFIG_KEY);
242
+ ]
243
+ };
244
+ }
245
+ ;
246
+ return this.userAuthConfig;
134
247
  }
135
- }, _class);
136
-
137
-
138
-
139
- exports.CrexApi = CrexApi; exports.CrexSDK = CrexSDK;
248
+ };
249
+ // Annotate the CommonJS export names for ESM import in node:
250
+ 0 && (module.exports = {
251
+ CrexApi,
252
+ CrexSDK
253
+ });
140
254
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/periotto/Desktop/workspace/c-rex.net-web-client-foundation/packages/core/dist/index.js","../src/requests.ts","../src/sdk.ts"],"names":[],"mappings":"AAAA;ACAA,4EAA4D;AAC5D,6CAAoB;AACpB,6CAAuB;AAEvB,qCAA4C;AAE5C,IAAM,sBAAA,EAAwB,YAAA;AAC9B,IAAM,6BAAA,EAA+B,mBAAA;AAe9B,IAAM,QAAA,EAAN,MAAc;AAAA,EACT;AAAA,EACA;AAAA,EACA;AAAA,EAED,WAAA,CAAY,MAAA,EAAyB,MAAA,EAAa;AACrD,IAAA,IAAA,CAAK,UAAA,EAAY,eAAA,CAAM,MAAA,CAAO;AAAA,MAC1B,OAAA,EAAS,MAAA,CAAO,OAAA;AAAA,MAChB,OAAA,EAAS;AAAA,QACL,cAAA,EAAgB;AAAA,MACpB;AAAA,IACJ,CAAC,CAAA;AAED,IAAA,IAAA,CAAK,OAAA,EAAS,MAAA;AACd,IAAA,IAAA,CAAK,OAAA,EAAS,MAAA;AAAA,EAClB;AAAA,EAEA,MAAc,WAAA,CAAA,EAAc;AACxB,IAAA,MAAM,WAAA,EAAqC,CAAC,CAAA;AAE5C,IAAA,GAAA,CAAI,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,OAAA,EAAS;AACjC,MAAA,IAAI,MAAA,EAAQ,kCAAA,qBAAmC,CAAA;AAC/C,MAAA,IAAI,YAAA,EAAc,kCAAA,4BAA0C,CAAA;AAE5D,MAAA,MAAM,IAAA,EAAM,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,GAAA,CAAI,EAAA,EAAI,GAAI,CAAA;AAExC,MAAA,GAAA,CAAI,CAAA,CAAE,MAAA,GAAS,YAAA,EAAc,IAAA,EAAM,EAAA,CAAA,EAAK;AACpC,QAAA,MAAM,EAAE,KAAA,EAAO,QAA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,UAAA;AACoB,UAAA;AACjB,UAAA;AACX,YAAA;AACe,cAAA;AACI,cAAA;AACE,cAAA;AACA,cAAA;AAC5B,YAAA;AACJ,UAAA;AACJ,QAAA;AACJ,MAAA;AACJ,IAAA;AACJ,EAAA;AAEiD,EAAA;AACV,IAAA;AACvC,EAAA;AACJ;AF0FoD;AACA;AACA;AACA","file":"/Users/periotto/Desktop/workspace/c-rex.net-web-client-foundation/packages/core/dist/index.js","sourcesContent":[null,"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 { getFromMemory, saveInMemory } from \"@c-rex/utils\";\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 config: ConfigInterface;\n private apiClient: AxiosInstance;\n private logger: any;\n\n public constructor(config: ConfigInterface, logger: any) {\n this.apiClient = axios.create({\n baseURL: config.baseUrl,\n headers: {\n \"content-Type\": \"application/json\",\n },\n });\n\n this.config = config;\n this.logger = logger;\n }\n\n private async manageToken() {\n const headersAux: Record<string, string> = {};\n\n if (this.config.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.config.OIDC.client.issuer);\n const client = new issuer.Client({\n client_id: this.config.OIDC.client.id,\n client_secret: this.config.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 console.log(\"error\", `API.getToken error when request ${this.config.OIDC.client.issuer}. Error: ${error}`);\n }\n\n return {\n token,\n tokenExpiry\n };\n }\n\n async execute<T>({\n url,\n method,\n params,\n body,\n headers = {},\n }: CallParams): Promise<T> {\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 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}","import { SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { CrexApi } from \"./requests\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getFromMemory, saveInMemory } from \"@c-rex/utils\";\n\n\nexport class CrexSDK {\n public api!: CrexApi;\n public logger!: any;\n public userAuthConfig: any = {};\n public customerConfig!: ConfigInterface;\n\n public constructor() {\n const config = getFromMemory(SDK_CONFIG_KEY);\n\n this.customerConfig = config as ConfigInterface;\n this.api = new CrexApi(this.customerConfig, null);\n\n const user = this.customerConfig.OIDC.user;\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 public static setConfig(config: ConfigInterface) {\n saveInMemory(config, SDK_CONFIG_KEY);\n }\n}"]}
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, 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\n console.log('token', token);\n\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 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_UI_LANG = \"en\";\n\nexport const UI_LANG_OPTIONS = [\"en\", \"de\"];\n\nexport const RESULT_TYPES = {\n TOPIC: \"TOPIC\",\n DOCUMENT: \"DOCUMENT\",\n PACKAGE: \"PACKAGE\",\n} as const;","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(`${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 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 { InformationUnitsService, RenditionsService } from \"@c-rex/services\";\nimport { generateBreadcrumbItems, generateTreeOfContent } from \"@c-rex/utils\";\nimport { SidebarAvailableVersionsInterface, TreeOfContent } from \"@c-rex/interfaces\";\n\nexport const loadArticleData = async (id: string) => {\n const renditionService = new RenditionsService();\n const informationService = new InformationUnitsService();\n const informationUnitsItem = await informationService.getItem({ id });\n\n let title = \"\";\n let versionOf = \"\";\n let documentURL = \"\";\n let htmlContent = \"\";\n let treeOfContent: TreeOfContent[] = [];\n let breadcrumbItems: TreeOfContent[] = [];\n let availableVersions: Omit<SidebarAvailableVersionsInterface, \"link\">[] = [];\n\n if (informationUnitsItem != null) {\n if (informationUnitsItem.versionOf != undefined) {\n versionOf = informationUnitsItem.versionOf.shortId\n }\n if (informationUnitsItem.titles != undefined && informationUnitsItem.titles[0] != undefined) {\n title = informationUnitsItem.titles[0].value\n }\n }\n\n if (versionOf != undefined) {\n const versions = await informationService.getList({\n filters: [`versionOf.shortId=${versionOf}`],\n fields: [\"labels\"],\n })\n\n availableVersions = versions.items.map((item) => {\n return {\n shortId: item.shortId,\n lang: item.labels[0]?.language as string,\n country: item.labels[0]?.language.split(\"-\")[1] as string,\n }\n }).sort((a, b) => {\n if (a.lang < b.lang) {\n return -1;\n }\n if (a.lang > b.lang) {\n return 1;\n }\n return 0;\n })\n }\n\n if (informationUnitsItem?.renditions != undefined) {\n htmlContent = await renditionService.getHTMLRendition(informationUnitsItem.renditions)\n documentURL = await renditionService.getDocumentRendition(informationUnitsItem.renditions, \"pdf\")\n\n if (informationUnitsItem?.directoryNodes != undefined) {\n treeOfContent = await generateTreeOfContent(informationUnitsItem.directoryNodes);\n breadcrumbItems = generateBreadcrumbItems(treeOfContent);\n }\n }\n\n return {\n htmlContent,\n treeOfContent,\n breadcrumbItems,\n availableVersions,\n documentURL,\n title\n }\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 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;AAEO,IAAM,iB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,KAAK,gBAAgB;AACrB,aAAO,KAAK;AAAA,IAChB;AAEA,UAAM,KAAK,UAAU;AAErB,UAAM,OAAO,KAAK,eAAe,KAAK;AACtC,QAAI,KAAK,SAAS;AACd,WAAK,iBAAiB;AAAA,QAClB,WAAW;AAAA,UACP;AAAA,YACI,IAAI;AAAA,YACJ,MAAM;AAAA,YACN,MAAM;AAAA,YACN,UAAU,KAAK;AAAA,YACf,WAAW,KAAK;AAAA,YAChB,cAAc,KAAK;AAAA,YACnB,eAAe,EAAE,QAAQ,EAAE,OAAO,KAAK,MAAM,EAAE;AAAA,YAC/C,QAAQ,SAAc;AAClB,qBAAO;AAAA,gBACH,IAAI,QAAQ,MAAM;AAAA,gBAClB,MAAM,QAAQ,QAAQ;AAAA,gBACtB,OAAO,QAAQ,SAAS;AAAA,gBACxB,OAAO,QAAQ,SAAS;AAAA,cAC5B;AAAA,YACJ;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAC;AAED,WAAO,KAAK;AAAA,EAChB;AACJ;","names":["import_services","axios","import_next_cookies"]}
package/dist/index.mjs CHANGED
@@ -1,27 +1,75 @@
1
1
  // src/requests.ts
2
2
  import axios from "axios";
3
- import { API } from "@c-rex/constants";
3
+
4
+ // ../constants/src/index.ts
5
+ var API = {
6
+ MAX_RETRY: 3,
7
+ API_TIMEOUT: 1e4,
8
+ API_HEADERS: {
9
+ "content-Type": "application/json"
10
+ }
11
+ };
12
+ var SDK_CONFIG_KEY = "crex-sdk-config";
13
+
14
+ // src/requests.ts
4
15
  import { Issuer } from "openid-client";
5
- import { getFromMemory, saveInMemory } from "@c-rex/utils";
16
+
17
+ // ../utils/src/utils.ts
18
+ var call = async (method, params) => {
19
+ try {
20
+ const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/rpc`, {
21
+ method: "POST",
22
+ headers: { "Content-Type": "application/json" },
23
+ body: JSON.stringify({ method, params })
24
+ });
25
+ const json = await res.json();
26
+ if (!res.ok) throw new Error(json.error || "Unknown error");
27
+ return json.data;
28
+ } catch (error) {
29
+ console.error(error);
30
+ return null;
31
+ }
32
+ };
33
+
34
+ // ../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;
42
+ }
43
+ const globalConfig = global[key];
44
+ if (globalConfig === null) {
45
+ global[key] = value;
46
+ }
47
+ }
48
+ function getFromMemory(key) {
49
+ if (isBrowser()) throw new Error("getFromMemory is not supported in browser");
50
+ return global[key];
51
+ }
52
+
53
+ // ../utils/src/classMerge.ts
54
+ import { clsx } from "clsx";
55
+ import { twMerge } from "tailwind-merge";
56
+
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";
62
+
63
+ // src/requests.ts
64
+ import { getCookie } from "@c-rex/utils/next-cookies";
6
65
  var CREX_TOKEN_HEADER_KEY = "crex-token";
7
66
  var CREX_TOKEN_EXPIRY_HEADER_KEY = "crex-token-expiry";
8
67
  var CrexApi = class {
9
- config;
68
+ customerConfig;
10
69
  apiClient;
11
- logger;
12
- constructor(config, logger) {
13
- this.apiClient = axios.create({
14
- baseURL: config.baseUrl,
15
- headers: {
16
- "content-Type": "application/json"
17
- }
18
- });
19
- this.config = config;
20
- this.logger = logger;
21
- }
22
70
  async manageToken() {
23
71
  const headersAux = {};
24
- if (this.config.OIDC.client.enabled) {
72
+ if (this.customerConfig.OIDC.client.enabled) {
25
73
  let token = getFromMemory(CREX_TOKEN_HEADER_KEY);
26
74
  let tokenExpiry = getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY);
27
75
  const now = Math.floor(Date.now() / 1e3);
@@ -40,21 +88,40 @@ var CrexApi = class {
40
88
  let tokenExpiry = 0;
41
89
  try {
42
90
  const now = Math.floor(Date.now() / 1e3);
43
- const issuer = await Issuer.discover(this.config.OIDC.client.issuer);
91
+ const issuer = await Issuer.discover(this.customerConfig.OIDC.client.issuer);
44
92
  const client = new issuer.Client({
45
- client_id: this.config.OIDC.client.id,
46
- client_secret: this.config.OIDC.client.secret
93
+ client_id: this.customerConfig.OIDC.client.id,
94
+ client_secret: this.customerConfig.OIDC.client.secret
47
95
  });
48
96
  const tokenSet = await client.grant({ grant_type: "client_credentials" });
49
- token = tokenSet.access_token, tokenExpiry = now + tokenSet.expires_at;
97
+ token = tokenSet.access_token;
98
+ tokenExpiry = now + tokenSet.expires_at;
99
+ console.log("token", token);
50
100
  } catch (error) {
51
- console.log("error", `API.getToken error when request ${this.config.OIDC.client.issuer}. Error: ${error}`);
101
+ call("CrexLogger.log", {
102
+ level: "error",
103
+ message: `API.getToken error when request ${this.customerConfig.OIDC.client.issuer}. Error: ${error}`
104
+ });
52
105
  }
53
106
  return {
54
107
  token,
55
108
  tokenExpiry
56
109
  };
57
110
  }
111
+ async initAPI() {
112
+ if (!this.customerConfig) {
113
+ const jsonConfigs = await getCookie(SDK_CONFIG_KEY);
114
+ if (!jsonConfigs) {
115
+ throw new Error("SDK not initialized");
116
+ }
117
+ this.customerConfig = JSON.parse(jsonConfigs);
118
+ }
119
+ if (!this.apiClient) {
120
+ this.apiClient = axios.create({
121
+ baseURL: this.customerConfig.baseUrl
122
+ });
123
+ }
124
+ }
58
125
  async execute({
59
126
  url,
60
127
  method,
@@ -62,6 +129,7 @@ var CrexApi = class {
62
129
  body,
63
130
  headers = {}
64
131
  }) {
132
+ await this.initAPI();
65
133
  let response = void 0;
66
134
  headers = {
67
135
  ...headers,
@@ -95,42 +163,50 @@ var CrexApi = class {
95
163
  };
96
164
 
97
165
  // src/sdk.ts
98
- import { SDK_CONFIG_KEY } from "@c-rex/constants";
99
- import { getFromMemory as getFromMemory2, saveInMemory as saveInMemory2 } from "@c-rex/utils";
166
+ import { getCookie as getCookie2 } from "@c-rex/utils/next-cookies";
100
167
  var CrexSDK = class {
101
- api;
102
- logger;
103
- userAuthConfig = {};
168
+ userAuthConfig;
104
169
  customerConfig;
105
- constructor() {
106
- const config = getFromMemory2(SDK_CONFIG_KEY);
107
- this.customerConfig = config;
108
- this.api = new CrexApi(this.customerConfig, null);
170
+ async getConfig() {
171
+ if (!this.customerConfig) {
172
+ const jsonConfigs = await getCookie2(SDK_CONFIG_KEY);
173
+ if (!jsonConfigs) {
174
+ throw new Error("SDK not initialized");
175
+ }
176
+ this.customerConfig = JSON.parse(jsonConfigs);
177
+ }
178
+ }
179
+ async getUserAuthConfig() {
180
+ if (this.userAuthConfig) {
181
+ return this.userAuthConfig;
182
+ }
183
+ await this.getConfig();
109
184
  const user = this.customerConfig.OIDC.user;
110
- this.userAuthConfig = {
111
- providers: [
112
- {
113
- id: "crex",
114
- name: "CREX",
115
- type: "oauth",
116
- clientId: user.id,
117
- wellKnown: user.issuer,
118
- clientSecret: user.secret,
119
- authorization: { params: { scope: user.scope } },
120
- profile(profile) {
121
- return {
122
- id: profile.id || "fake Id",
123
- name: profile.name || "Fake Name",
124
- email: profile.email || "fake Email",
125
- image: profile.image || "fake Image"
126
- };
185
+ if (user.enabled) {
186
+ this.userAuthConfig = {
187
+ providers: [
188
+ {
189
+ id: "crex",
190
+ name: "CREX",
191
+ type: "oauth",
192
+ clientId: user.id,
193
+ wellKnown: user.issuer,
194
+ clientSecret: user.secret,
195
+ authorization: { params: { scope: user.scope } },
196
+ profile(profile) {
197
+ return {
198
+ id: profile.id || "fake Id",
199
+ name: profile.name || "Fake Name",
200
+ email: profile.email || "fake Email",
201
+ image: profile.image || "fake Image"
202
+ };
203
+ }
127
204
  }
128
- }
129
- ]
130
- };
131
- }
132
- static setConfig(config) {
133
- saveInMemory2(config, SDK_CONFIG_KEY);
205
+ ]
206
+ };
207
+ }
208
+ ;
209
+ return this.userAuthConfig;
134
210
  }
135
211
  };
136
212
  export {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/requests.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 { getFromMemory, saveInMemory } from \"@c-rex/utils\";\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 config: ConfigInterface;\n private apiClient: AxiosInstance;\n private logger: any;\n\n public constructor(config: ConfigInterface, logger: any) {\n this.apiClient = axios.create({\n baseURL: config.baseUrl,\n headers: {\n \"content-Type\": \"application/json\",\n },\n });\n\n this.config = config;\n this.logger = logger;\n }\n\n private async manageToken() {\n const headersAux: Record<string, string> = {};\n\n if (this.config.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.config.OIDC.client.issuer);\n const client = new issuer.Client({\n client_id: this.config.OIDC.client.id,\n client_secret: this.config.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 console.log(\"error\", `API.getToken error when request ${this.config.OIDC.client.issuer}. Error: ${error}`);\n }\n\n return {\n token,\n tokenExpiry\n };\n }\n\n async execute<T>({\n url,\n method,\n params,\n body,\n headers = {},\n }: CallParams): Promise<T> {\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 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}","import { SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { CrexApi } from \"./requests\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getFromMemory, saveInMemory } from \"@c-rex/utils\";\n\n\nexport class CrexSDK {\n public api!: CrexApi;\n public logger!: any;\n public userAuthConfig: any = {};\n public customerConfig!: ConfigInterface;\n\n public constructor() {\n const config = getFromMemory(SDK_CONFIG_KEY);\n\n this.customerConfig = config as ConfigInterface;\n this.api = new CrexApi(this.customerConfig, null);\n\n const user = this.customerConfig.OIDC.user;\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 public static setConfig(config: ConfigInterface) {\n saveInMem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AAK,gBAAgB,IAAI;AAEhD,UAAM,OAAO,KAAK,eAAe,KAAK;AACtC,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;AAAA,EACJ;AAAA,EAEA,OAAc,UAAU,QAAyB;AAC7C,IAAAC,cAAa,QAAQ,cAAc;AAAA,EACvC;AACJ;","names":["getFromMemory","saveInMemory"]}
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, 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\n console.log('token', token);\n\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 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_UI_LANG = \"en\";\n\nexport const UI_LANG_OPTIONS = [\"en\", \"de\"];\n\nexport const RESULT_TYPES = {\n TOPIC: \"TOPIC\",\n DOCUMENT: \"DOCUMENT\",\n PACKAGE: \"PACKAGE\",\n} as const;","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(`${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 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 { InformationUnitsService, RenditionsService } from \"@c-rex/services\";\nimport { generateBreadcrumbItems, generateTreeOfContent } from \"@c-rex/utils\";\nimport { SidebarAvailableVersionsInterface, TreeOfContent } from \"@c-rex/interfaces\";\n\nexport const loadArticleData = async (id: string) => {\n const renditionService = new RenditionsService();\n const informationService = new InformationUnitsService();\n const informationUnitsItem = await informationService.getItem({ id });\n\n let title = \"\";\n let versionOf = \"\";\n let documentURL = \"\";\n let htmlContent = \"\";\n let treeOfContent: TreeOfContent[] = [];\n let breadcrumbItems: TreeOfContent[] = [];\n let availableVersions: Omit<SidebarAvailableVersionsInterface, \"link\">[] = [];\n\n if (informationUnitsItem != null) {\n if (informationUnitsItem.versionOf != undefined) {\n versionOf = informationUnitsItem.versionOf.shortId\n }\n if (informationUnitsItem.titles != undefined && informationUnitsItem.titles[0] != undefined) {\n title = informationUnitsItem.titles[0].value\n }\n }\n\n if (versionOf != undefined) {\n const versions = await informationService.getList({\n filters: [`versionOf.shortId=${versionOf}`],\n fields: [\"labels\"],\n })\n\n availableVersions = versions.items.map((item) => {\n return {\n shortId: item.shortId,\n lang: item.labels[0]?.language as string,\n country: item.labels[0]?.language.split(\"-\")[1] as string,\n }\n }).sort((a, b) => {\n if (a.lang < b.lang) {\n return -1;\n }\n if (a.lang > b.lang) {\n return 1;\n }\n return 0;\n })\n }\n\n if (informationUnitsItem?.renditions != undefined) {\n htmlContent = await renditionService.getHTMLRendition(informationUnitsItem.renditions)\n documentURL = await renditionService.getDocumentRendition(informationUnitsItem.renditions, \"pdf\")\n\n if (informationUnitsItem?.directoryNodes != undefined) {\n treeOfContent = await generateTreeOfContent(informationUnitsItem.directoryNodes);\n breadcrumbItems = generateBreadcrumbItems(treeOfContent);\n }\n }\n\n return {\n htmlContent,\n treeOfContent,\n breadcrumbItems,\n availableVersions,\n documentURL,\n title\n }\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 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: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c,YAAY;AACtB,QAAI,CAAC,KAAK,gBAAgB;AACtB,YAAM,cAAc,MAAMA,WAAU,cAAc;AAClD,UAAI,CAAC,aAAa;AACd,cAAM,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;AACtC,QAAI,KAAK,SAAS;AACd,WAAK,iBAAiB;AAAA,QAClB,WAAW;AAAA,UACP;AAAA,YACI,IAAI;AAAA,YACJ,MAAM;AAAA,YACN,MAAM;AAAA,YACN,UAAU,KAAK;AAAA,YACf,WAAW,KAAK;AAAA,YAChB,cAAc,KAAK;AAAA,YACnB,eAAe,EAAE,QAAQ,EAAE,OAAO,KAAK,MAAM,EAAE;AAAA,YAC/C,QAAQ,SAAc;AAClB,qBAAO;AAAA,gBACH,IAAI,QAAQ,MAAM;AAAA,gBAClB,MAAM,QAAQ,QAAQ;AAAA,gBACtB,OAAO,QAAQ,SAAS;AAAA,gBACxB,OAAO,QAAQ,SAAS;AAAA,cAC5B;AAAA,YACJ;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAC;AAED,WAAO,KAAK;AAAA,EAChB;AACJ;","names":["getCookie"]}
@@ -0,0 +1,16 @@
1
+ import winston from 'winston';
2
+ import { LogLevelType, LogCategoriesType } from '@c-rex/types';
3
+
4
+ declare class CrexLogger {
5
+ private customerConfig;
6
+ logger: winston.Logger;
7
+ private initLogger;
8
+ log({ level, message, category }: {
9
+ level: LogLevelType;
10
+ message: string;
11
+ category?: LogCategoriesType;
12
+ }): Promise<void>;
13
+ private createLogger;
14
+ }
15
+
16
+ export { CrexLogger };
@@ -0,0 +1,16 @@
1
+ import winston from 'winston';
2
+ import { LogLevelType, LogCategoriesType } from '@c-rex/types';
3
+
4
+ declare class CrexLogger {
5
+ private customerConfig;
6
+ logger: winston.Logger;
7
+ private initLogger;
8
+ log({ level, message, category }: {
9
+ level: LogLevelType;
10
+ message: string;
11
+ category?: LogCategoriesType;
12
+ }): Promise<void>;
13
+ private createLogger;
14
+ }
15
+
16
+ export { CrexLogger };
package/dist/logger.js ADDED
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/logger.ts
31
+ var logger_exports = {};
32
+ __export(logger_exports, {
33
+ CrexLogger: () => CrexLogger
34
+ });
35
+ module.exports = __toCommonJS(logger_exports);
36
+ var import_winston = __toESM(require("winston"));
37
+
38
+ // src/transports/matomo.ts
39
+ var import_winston_transport = __toESM(require("winston-transport"));
40
+
41
+ // ../constants/src/index.ts
42
+ var ALL = "*";
43
+ var LOG_LEVELS = {
44
+ critical: 2,
45
+ error: 3,
46
+ warning: 4,
47
+ info: 6,
48
+ debug: 7
49
+ };
50
+ var SDK_CONFIG_KEY = "crex-sdk-config";
51
+
52
+ // src/transports/matomo.ts
53
+ var MatomoTransport = class extends import_winston_transport.default {
54
+ matomoTransport;
55
+ configs;
56
+ constructor(configs) {
57
+ super({
58
+ level: configs.logs.console.minimumLevel,
59
+ silent: configs.logs.console.silent
60
+ });
61
+ this.matomoTransport = new import_winston_transport.default();
62
+ this.configs = configs;
63
+ }
64
+ log(info, callback) {
65
+ const matomoCategory = this.configs.logs.matomo.categoriesLevel;
66
+ if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {
67
+ this.matomoTransport.log(info, callback);
68
+ }
69
+ }
70
+ };
71
+
72
+ // src/transports/graylog.ts
73
+ var import_winston_transport2 = __toESM(require("winston-transport"));
74
+ var import_winston_graylog2 = __toESM(require("winston-graylog2"));
75
+ var GraylogTransport = class extends import_winston_transport2.default {
76
+ graylogTransport;
77
+ configs;
78
+ constructor(configs) {
79
+ super({
80
+ level: configs.logs.graylog.minimumLevel,
81
+ silent: configs.logs.graylog.silent
82
+ });
83
+ this.configs = configs;
84
+ this.graylogTransport = new import_winston_graylog2.default({
85
+ name: "Periotto-TEST",
86
+ silent: false,
87
+ handleExceptions: false,
88
+ graylog: {
89
+ servers: [{ host: "localhost", port: 12201 }]
90
+ }
91
+ });
92
+ }
93
+ log(info, callback) {
94
+ const graylogCategory = this.configs.logs.graylog.categoriesLevel;
95
+ if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {
96
+ this.graylogTransport.log(info, callback);
97
+ }
98
+ }
99
+ };
100
+
101
+ // src/logger.ts
102
+ var import_next_cookies = require("@c-rex/utils/next-cookies");
103
+ var CrexLogger = class {
104
+ customerConfig;
105
+ logger;
106
+ async initLogger() {
107
+ if (!this.customerConfig) {
108
+ const jsonConfigs = await (0, import_next_cookies.getCookie)(SDK_CONFIG_KEY);
109
+ if (!jsonConfigs) {
110
+ throw new Error("SDK not initialized");
111
+ }
112
+ this.customerConfig = JSON.parse(jsonConfigs);
113
+ }
114
+ if (!this.logger) {
115
+ this.logger = this.createLogger();
116
+ }
117
+ }
118
+ async log({ level, message, category }) {
119
+ await this.initLogger();
120
+ this.logger.log(level, message, category);
121
+ }
122
+ createLogger() {
123
+ return import_winston.default.createLogger({
124
+ levels: LOG_LEVELS,
125
+ transports: [
126
+ new import_winston.default.transports.Console({
127
+ level: this.customerConfig.logs.console.minimumLevel,
128
+ silent: this.customerConfig.logs.console.silent
129
+ }),
130
+ new MatomoTransport(this.customerConfig),
131
+ new GraylogTransport(this.customerConfig)
132
+ ]
133
+ });
134
+ }
135
+ };
136
+ // Annotate the CommonJS export names for ESM import in node:
137
+ 0 && (module.exports = {
138
+ CrexLogger
139
+ });
140
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +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, SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { getCookie } 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 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 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_UI_LANG = \"en\";\n\nexport const UI_LANG_OPTIONS = [\"en\", \"de\"];\n\nexport const RESULT_TYPES = {\n TOPIC: \"TOPIC\",\n DOCUMENT: \"DOCUMENT\",\n PACKAGE: \"PACKAGE\",\n} as const;","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 (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {\n this.graylogTransport.log(info, callback);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAoB;;;ACApB,+BAAsB;;;ACAf,IAAM,MAAM;AAeZ,IAAM,aAAa;AAAA,EACtB,UAAU;AAAA,EACV,OAAO;AAAA,EACP,SAAS;AAAA,EACT,MAAM;AAAA,EACN,OAAO;AACX;AAeO,IAAM,iBAAiB;;;AD/BvB,IAAM,kBAAN,cAA8B,yBAAAA,QAAU;AAAA,EACpC;AAAA,EACC;AAAA,EAER,YAAY,SAA0B;AAClC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c;AAClD,UAAI,CAAC,aAAa;AACd,cAAM,IAAI,MAAM,qBAAqB;AAAA,MACzC;AACA,WAAK,iBAAiB,KAAK,MAAM,WAAW;AAAA,IAChD;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"]}
@@ -0,0 +1,105 @@
1
+ // src/logger.ts
2
+ import winston from "winston";
3
+
4
+ // src/transports/matomo.ts
5
+ import Transport from "winston-transport";
6
+
7
+ // ../constants/src/index.ts
8
+ var ALL = "*";
9
+ var LOG_LEVELS = {
10
+ critical: 2,
11
+ error: 3,
12
+ warning: 4,
13
+ info: 6,
14
+ debug: 7
15
+ };
16
+ var SDK_CONFIG_KEY = "crex-sdk-config";
17
+
18
+ // src/transports/matomo.ts
19
+ var MatomoTransport = class extends Transport {
20
+ matomoTransport;
21
+ configs;
22
+ constructor(configs) {
23
+ super({
24
+ level: configs.logs.console.minimumLevel,
25
+ silent: configs.logs.console.silent
26
+ });
27
+ this.matomoTransport = new Transport();
28
+ this.configs = configs;
29
+ }
30
+ log(info, callback) {
31
+ const matomoCategory = this.configs.logs.matomo.categoriesLevel;
32
+ if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {
33
+ this.matomoTransport.log(info, callback);
34
+ }
35
+ }
36
+ };
37
+
38
+ // src/transports/graylog.ts
39
+ import Transport2 from "winston-transport";
40
+ import Graylog2Transport from "winston-graylog2";
41
+ var GraylogTransport = class extends Transport2 {
42
+ graylogTransport;
43
+ configs;
44
+ constructor(configs) {
45
+ super({
46
+ level: configs.logs.graylog.minimumLevel,
47
+ silent: configs.logs.graylog.silent
48
+ });
49
+ this.configs = configs;
50
+ this.graylogTransport = new Graylog2Transport({
51
+ name: "Periotto-TEST",
52
+ silent: false,
53
+ handleExceptions: false,
54
+ graylog: {
55
+ servers: [{ host: "localhost", port: 12201 }]
56
+ }
57
+ });
58
+ }
59
+ log(info, callback) {
60
+ const graylogCategory = this.configs.logs.graylog.categoriesLevel;
61
+ if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {
62
+ this.graylogTransport.log(info, callback);
63
+ }
64
+ }
65
+ };
66
+
67
+ // src/logger.ts
68
+ import { getCookie } from "@c-rex/utils/next-cookies";
69
+ var CrexLogger = class {
70
+ customerConfig;
71
+ logger;
72
+ async initLogger() {
73
+ if (!this.customerConfig) {
74
+ const jsonConfigs = await getCookie(SDK_CONFIG_KEY);
75
+ if (!jsonConfigs) {
76
+ throw new Error("SDK not initialized");
77
+ }
78
+ this.customerConfig = JSON.parse(jsonConfigs);
79
+ }
80
+ if (!this.logger) {
81
+ this.logger = this.createLogger();
82
+ }
83
+ }
84
+ async log({ level, message, category }) {
85
+ await this.initLogger();
86
+ this.logger.log(level, message, category);
87
+ }
88
+ createLogger() {
89
+ return winston.createLogger({
90
+ levels: LOG_LEVELS,
91
+ transports: [
92
+ new winston.transports.Console({
93
+ level: this.customerConfig.logs.console.minimumLevel,
94
+ silent: this.customerConfig.logs.console.silent
95
+ }),
96
+ new MatomoTransport(this.customerConfig),
97
+ new GraylogTransport(this.customerConfig)
98
+ ]
99
+ });
100
+ }
101
+ };
102
+ export {
103
+ CrexLogger
104
+ };
105
+ //# sourceMappingURL=logger.mjs.map
@@ -0,0 +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, SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { getCookie } 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 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 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_UI_LANG = \"en\";\n\nexport const UI_LANG_OPTIONS = [\"en\", \"de\"];\n\nexport const RESULT_TYPES = {\n TOPIC: \"TOPIC\",\n DOCUMENT: \"DOCUMENT\",\n PACKAGE: \"PACKAGE\",\n} as const;","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 (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {\n this.graylogTransport.log(info, callback);\n }\n }\n}\n"],"mappings":";AAAA,OAAO,aAAa;;;ACApB,OAAO,eAAe;;;ACAf,IAAM,MAAM;AAeZ,IAAM,aAAa;AAAA,EACtB,UAAU;AAAA,EACV,OAAO;AAAA,EACP,SAAS;AAAA,EACT,MAAM;AAAA,EACN,OAAO;AACX;AAeO,IAAM,iBAAiB;;;AD/BvB,IAAM,kBAAN,cAA8B,UAAU;AAAA,EACpC;AAAA,EACC;AAAA,EAER,YAAY,SAA0B;AAClC,UAAM;AAAA,MACF,OAAO,QAAQ,KAAK,QAAQ;AAAA,MAC5B,QAAQ,QAAQ,KAAK,QAAQ;AAAA,IACjC,CAAC;AAED,SAAK,kBAAkB,IAAI,UAAU;AACrC,SAAK,UAAU;AAAA,EACnB;AAAA,EAEA,IACI,MACA,UACI;AACJ,UAAM,iBAAiB,KAAK,QAAQ,KAAK,OAAO;AAEhD,QAAI,eAAe,SAAS,KAAK,QAAQ,KAAK,eAAe,SAAS,GAAG,GAAG;AAExE,WAAK,gBAAgB,IAAI,MAAM,QAAQ;AAAA,IAC3C;AAAA,EACJ;AACJ;;;AE9BA,OAAOA,gBAAe;AACtB,OAAO,uBAAuB;AAKvB,IAAM,mBAAN,cAA+BC,WAAU;AAAA,EACrC;AAAA,EACA;AAAA,EAEP,YAAY,SAA0B;AAClC,UAAM;AAAA,MACF,OAAO,QAAQ,KAAK,QAAQ;AAAA,MAC5B,QAAQ,QAAQ,KAAK,QAAQ;AAAA,IACjC,CAAC;AAED,SAAK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AAc;AAAA,MAC5C;AAAA,IACJ,CAAC;AAAA,EACL;AACJ;","names":["Transport","Transport"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@c-rex/core",
3
- "version": "0.0.9",
3
+ "version": "0.1.1",
4
4
  "main": "dist/index.js",
5
5
  "module": "dist/index.mjs",
6
6
  "types": "dist/index.d.ts",
@@ -18,17 +18,21 @@
18
18
  "default": "./dist/index.js"
19
19
  },
20
20
  "./package.json": "./package.json",
21
- "./logger.server": {
22
- "import": "./dist/logger.server.mjs",
23
- "require": "./dist/logger.server.cjs"
21
+ "./logger": {
22
+ "types": "./dist/logger.d.ts",
23
+ "import": "./dist/logger.mjs",
24
+ "require": "./dist/logger.js",
25
+ "default": "./dist/logger.js"
24
26
  }
25
27
  },
26
28
  "sideEffects": false,
27
29
  "scripts": {
28
- "dev": "tsup src/index.ts --splitting --format cjs,esm --dts --watch",
29
- "build": "tsup src/index.ts --splitting --format cjs,esm --dts",
30
+ "dev": "tsup --watch",
31
+ "build": "tsup",
30
32
  "test:watch": "jest --watch",
31
- "test": "jest"
33
+ "test": "jest",
34
+ "lint": "eslint .",
35
+ "lint:fix": "eslint . --fix"
32
36
  },
33
37
  "devDependencies": {
34
38
  "@c-rex/eslint-config": "*",