@c-rex/core 0.1.1 → 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/api/cookies.d.mts +10 -0
- package/dist/api/cookies.d.ts +10 -0
- package/dist/api/cookies.js +38 -0
- package/dist/api/cookies.js.map +1 -0
- package/dist/api/cookies.mjs +13 -0
- package/dist/api/cookies.mjs.map +1 -0
- package/dist/api/rpc.d.mts +9 -0
- package/dist/api/rpc.d.ts +9 -0
- package/dist/api/rpc.js +212 -0
- package/dist/api/rpc.js.map +1 -0
- package/dist/api/rpc.mjs +175 -0
- package/dist/api/rpc.mjs.map +1 -0
- package/dist/index.js +11 -18
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +13 -20
- package/dist/index.mjs.map +1 -1
- package/dist/logger.js +2 -6
- package/dist/logger.js.map +1 -1
- package/dist/logger.mjs +3 -7
- package/dist/logger.mjs.map +1 -1
- package/package.json +13 -5
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/api/cookies.ts
|
|
21
|
+
var cookies_exports = {};
|
|
22
|
+
__export(cookies_exports, {
|
|
23
|
+
GET: () => GET
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(cookies_exports);
|
|
26
|
+
var import_server = require("next/server");
|
|
27
|
+
var import_next_cookies = require("@c-rex/utils/next-cookies");
|
|
28
|
+
var GET = async (req) => {
|
|
29
|
+
const key = req.nextUrl.searchParams.get("key");
|
|
30
|
+
if (!key) return import_server.NextResponse.json({ error: "Missing key" }, { status: 400 });
|
|
31
|
+
const value = (0, import_next_cookies.getCookieFromBack)(key);
|
|
32
|
+
return import_server.NextResponse.json({ key, value: value ?? null });
|
|
33
|
+
};
|
|
34
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
35
|
+
0 && (module.exports = {
|
|
36
|
+
GET
|
|
37
|
+
});
|
|
38
|
+
//# sourceMappingURL=cookies.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/api/cookies.ts"],"sourcesContent":["import { NextRequest, NextResponse } from 'next/server';\nimport { getCookieFromBack } from \"@c-rex/utils/next-cookies\";\n\nexport const GET = async (req: NextRequest) => {\n const key = req.nextUrl.searchParams.get('key');\n if (!key) return NextResponse.json({ error: 'Missing key' }, { status: 400 });\n\n const value = getCookieFromBack(key);\n\n return NextResponse.json({ key, value: value ?? null });\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA0C;AAC1C,0BAAkC;AAE3B,IAAM,MAAM,OAAO,QAAqB;AAC3C,QAAM,MAAM,IAAI,QAAQ,aAAa,IAAI,KAAK;AAC9C,MAAI,CAAC,IAAK,QAAO,2BAAa,KAAK,EAAE,OAAO,cAAc,GAAG,EAAE,QAAQ,IAAI,CAAC;AAE5E,QAAM,YAAQ,uCAAkB,GAAG;AAEnC,SAAO,2BAAa,KAAK,EAAE,KAAK,OAAO,SAAS,KAAK,CAAC;AAC1D;","names":[]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// src/api/cookies.ts
|
|
2
|
+
import { NextResponse } from "next/server";
|
|
3
|
+
import { getCookieFromBack } from "@c-rex/utils/next-cookies";
|
|
4
|
+
var GET = async (req) => {
|
|
5
|
+
const key = req.nextUrl.searchParams.get("key");
|
|
6
|
+
if (!key) return NextResponse.json({ error: "Missing key" }, { status: 400 });
|
|
7
|
+
const value = getCookieFromBack(key);
|
|
8
|
+
return NextResponse.json({ key, value: value ?? null });
|
|
9
|
+
};
|
|
10
|
+
export {
|
|
11
|
+
GET
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=cookies.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/api/cookies.ts"],"sourcesContent":["import { NextRequest, NextResponse } from 'next/server';\nimport { getCookieFromBack } from \"@c-rex/utils/next-cookies\";\n\nexport const GET = async (req: NextRequest) => {\n const key = req.nextUrl.searchParams.get('key');\n if (!key) return NextResponse.json({ error: 'Missing key' }, { status: 400 });\n\n const value = getCookieFromBack(key);\n\n return NextResponse.json({ key, value: value ?? null });\n}"],"mappings":";AAAA,SAAsB,oBAAoB;AAC1C,SAAS,yBAAyB;AAE3B,IAAM,MAAM,OAAO,QAAqB;AAC3C,QAAM,MAAM,IAAI,QAAQ,aAAa,IAAI,KAAK;AAC9C,MAAI,CAAC,IAAK,QAAO,aAAa,KAAK,EAAE,OAAO,cAAc,GAAG,EAAE,QAAQ,IAAI,CAAC;AAE5E,QAAM,QAAQ,kBAAkB,GAAG;AAEnC,SAAO,aAAa,KAAK,EAAE,KAAK,OAAO,SAAS,KAAK,CAAC;AAC1D;","names":[]}
|
package/dist/api/rpc.js
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
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/api/rpc.ts
|
|
31
|
+
var rpc_exports = {};
|
|
32
|
+
__export(rpc_exports, {
|
|
33
|
+
POST: () => POST
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(rpc_exports);
|
|
36
|
+
|
|
37
|
+
// ../constants/src/index.ts
|
|
38
|
+
var ALL = "*";
|
|
39
|
+
var LOG_LEVELS = {
|
|
40
|
+
critical: 2,
|
|
41
|
+
error: 3,
|
|
42
|
+
warning: 4,
|
|
43
|
+
info: 6,
|
|
44
|
+
debug: 7
|
|
45
|
+
};
|
|
46
|
+
var DEFAULT_COOKIE_LIMIT = 7 * 24 * 60 * 60 * 1e3;
|
|
47
|
+
|
|
48
|
+
// src/sdk.ts
|
|
49
|
+
var import_next_cookies = require("@c-rex/utils/next-cookies");
|
|
50
|
+
var CrexSDK = class {
|
|
51
|
+
userAuthConfig;
|
|
52
|
+
customerConfig;
|
|
53
|
+
async getConfig() {
|
|
54
|
+
if (!this.customerConfig) {
|
|
55
|
+
this.customerConfig = await (0, import_next_cookies.getConfigs)();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
async getUserAuthConfig() {
|
|
59
|
+
if (this.userAuthConfig) {
|
|
60
|
+
return this.userAuthConfig;
|
|
61
|
+
}
|
|
62
|
+
await this.getConfig();
|
|
63
|
+
const user = this.customerConfig.OIDC.user;
|
|
64
|
+
if (user.enabled) {
|
|
65
|
+
this.userAuthConfig = {
|
|
66
|
+
providers: [
|
|
67
|
+
{
|
|
68
|
+
id: "crex",
|
|
69
|
+
name: "CREX",
|
|
70
|
+
type: "oauth",
|
|
71
|
+
clientId: user.id,
|
|
72
|
+
wellKnown: user.issuer,
|
|
73
|
+
clientSecret: user.secret,
|
|
74
|
+
authorization: { params: { scope: user.scope } },
|
|
75
|
+
profile(profile) {
|
|
76
|
+
return {
|
|
77
|
+
id: profile.id || "fake Id",
|
|
78
|
+
name: profile.name || "Fake Name",
|
|
79
|
+
email: profile.email || "fake Email",
|
|
80
|
+
image: profile.image || "fake Image"
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
]
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
;
|
|
88
|
+
return this.userAuthConfig;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
// src/logger.ts
|
|
93
|
+
var import_winston = __toESM(require("winston"));
|
|
94
|
+
|
|
95
|
+
// src/transports/matomo.ts
|
|
96
|
+
var import_winston_transport = __toESM(require("winston-transport"));
|
|
97
|
+
var MatomoTransport = class extends import_winston_transport.default {
|
|
98
|
+
matomoTransport;
|
|
99
|
+
configs;
|
|
100
|
+
constructor(configs) {
|
|
101
|
+
super({
|
|
102
|
+
level: configs.logs.console.minimumLevel,
|
|
103
|
+
silent: configs.logs.console.silent
|
|
104
|
+
});
|
|
105
|
+
this.matomoTransport = new import_winston_transport.default();
|
|
106
|
+
this.configs = configs;
|
|
107
|
+
}
|
|
108
|
+
log(info, callback) {
|
|
109
|
+
const matomoCategory = this.configs.logs.matomo.categoriesLevel;
|
|
110
|
+
if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {
|
|
111
|
+
this.matomoTransport.log(info, callback);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
// src/transports/graylog.ts
|
|
117
|
+
var import_winston_transport2 = __toESM(require("winston-transport"));
|
|
118
|
+
var import_winston_graylog2 = __toESM(require("winston-graylog2"));
|
|
119
|
+
var GraylogTransport = class extends import_winston_transport2.default {
|
|
120
|
+
graylogTransport;
|
|
121
|
+
configs;
|
|
122
|
+
constructor(configs) {
|
|
123
|
+
super({
|
|
124
|
+
level: configs.logs.graylog.minimumLevel,
|
|
125
|
+
silent: configs.logs.graylog.silent
|
|
126
|
+
});
|
|
127
|
+
this.configs = configs;
|
|
128
|
+
this.graylogTransport = new import_winston_graylog2.default({
|
|
129
|
+
name: "Periotto-TEST",
|
|
130
|
+
silent: false,
|
|
131
|
+
handleExceptions: false,
|
|
132
|
+
graylog: {
|
|
133
|
+
servers: [{ host: "localhost", port: 12201 }]
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
log(info, callback) {
|
|
138
|
+
const graylogCategory = this.configs.logs.graylog.categoriesLevel;
|
|
139
|
+
if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {
|
|
140
|
+
this.graylogTransport.log(info, callback);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
// src/logger.ts
|
|
146
|
+
var import_next_cookies2 = require("@c-rex/utils/next-cookies");
|
|
147
|
+
var CrexLogger = class {
|
|
148
|
+
customerConfig;
|
|
149
|
+
logger;
|
|
150
|
+
async initLogger() {
|
|
151
|
+
if (!this.customerConfig) {
|
|
152
|
+
this.customerConfig = await (0, import_next_cookies2.getConfigs)();
|
|
153
|
+
}
|
|
154
|
+
if (!this.logger) {
|
|
155
|
+
this.logger = this.createLogger();
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
async log({ level, message, category }) {
|
|
159
|
+
await this.initLogger();
|
|
160
|
+
this.logger.log(level, message, category);
|
|
161
|
+
}
|
|
162
|
+
createLogger() {
|
|
163
|
+
return import_winston.default.createLogger({
|
|
164
|
+
levels: LOG_LEVELS,
|
|
165
|
+
transports: [
|
|
166
|
+
new import_winston.default.transports.Console({
|
|
167
|
+
level: this.customerConfig.logs.console.minimumLevel,
|
|
168
|
+
silent: this.customerConfig.logs.console.silent
|
|
169
|
+
}),
|
|
170
|
+
new MatomoTransport(this.customerConfig),
|
|
171
|
+
new GraylogTransport(this.customerConfig)
|
|
172
|
+
]
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
// src/api/rpc.ts
|
|
178
|
+
var import_services = require("@c-rex/services");
|
|
179
|
+
var import_server = require("next/server");
|
|
180
|
+
var serviceRegistry = {
|
|
181
|
+
InformationUnitsService: import_services.InformationUnitsService,
|
|
182
|
+
DocumentTypesService: import_services.DocumentTypesService,
|
|
183
|
+
DirectoryNodesService: import_services.DirectoryNodesService,
|
|
184
|
+
RenditionsService: import_services.RenditionsService,
|
|
185
|
+
CrexLogger,
|
|
186
|
+
CrexSDK
|
|
187
|
+
};
|
|
188
|
+
var POST = async (req) => {
|
|
189
|
+
try {
|
|
190
|
+
const { method, params } = await req.json();
|
|
191
|
+
const [serviceName, methodName] = method.split(".");
|
|
192
|
+
const ServiceClass = serviceRegistry[serviceName];
|
|
193
|
+
if (!ServiceClass) {
|
|
194
|
+
return import_server.NextResponse.json({ error: `Service '${serviceName}' not found` }, { status: 404 });
|
|
195
|
+
}
|
|
196
|
+
const serviceInstance = new ServiceClass();
|
|
197
|
+
const handler = serviceInstance[methodName];
|
|
198
|
+
if (typeof handler !== "function") {
|
|
199
|
+
return import_server.NextResponse.json({ error: `Method '${methodName}' not found on '${serviceName}'` }, { status: 404 });
|
|
200
|
+
}
|
|
201
|
+
const result = await handler.call(serviceInstance, params);
|
|
202
|
+
return import_server.NextResponse.json({ data: result });
|
|
203
|
+
} catch (err) {
|
|
204
|
+
console.error(err);
|
|
205
|
+
return import_server.NextResponse.json({ error: String(err) }, { status: 500 });
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
209
|
+
0 && (module.exports = {
|
|
210
|
+
POST
|
|
211
|
+
});
|
|
212
|
+
//# sourceMappingURL=rpc.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/api/rpc.ts","../../../constants/src/index.ts","../../src/sdk.ts","../../src/logger.ts","../../src/transports/matomo.ts","../../src/transports/graylog.ts"],"sourcesContent":["import { CrexSDK } from '../';\nimport { CrexLogger } from '../logger';\nimport { DirectoryNodesService, DocumentTypesService, InformationUnitsService, RenditionsService } from '@c-rex/services';\nimport { NextRequest, NextResponse } from 'next/server';\n\nconst serviceRegistry = {\n InformationUnitsService,\n DocumentTypesService,\n DirectoryNodesService,\n RenditionsService,\n CrexLogger,\n CrexSDK,\n};\n\ntype RpcPayload = {\n method: string;\n params: any;\n};\n\nexport const POST = async (req: NextRequest) => {\n try {\n const { method, params }: RpcPayload = await req.json();\n const [serviceName, methodName] = method.split('.');\n const ServiceClass = serviceRegistry[serviceName as keyof typeof serviceRegistry];\n\n if (!ServiceClass) {\n return NextResponse.json({ error: `Service '${serviceName}' not found` }, { status: 404 });\n }\n\n const serviceInstance = new ServiceClass();\n const handler = (serviceInstance as any)[methodName as any];\n\n if (typeof handler !== 'function') {\n return NextResponse.json({ error: `Method '${methodName}' not found on '${serviceName}'` }, { status: 404 });\n }\n\n const result = await handler.call(serviceInstance, params);\n return NextResponse.json({ data: result });\n } catch (err) {\n console.error(err);\n return NextResponse.json({ error: String(err) }, { status: 500 });\n }\n}\n","export const ALL = \"*\"\n\nexport const LOG_CATEGORIES = [\n \"NoLicense\",\n \"Scenario\",\n \"Favorites\",\n \"Subscription\",\n \"Share\",\n \"Document\",\n \"Search\",\n \"History\",\n \"Notification\",\n \"UserProfile\",\n] as const;\n\nexport const LOG_LEVELS = {\n critical: 2,\n error: 3,\n warning: 4,\n info: 6,\n debug: 7,\n} as const;\n\nexport const RESULT_VIEW_STYLES = [\n \"cards\",\n \"table\",\n] as const;\n\nexport const API = {\n MAX_RETRY: 3,\n API_TIMEOUT: 10000,\n API_HEADERS: {\n \"content-Type\": \"application/json\",\n },\n};\n\nexport const SDK_CONFIG_KEY = \"crex-sdk-config\";\n\nexport const CONTENT_LANG_KEY = \"CONTENT_LANG_KEY\";\n\nexport const AVAILABLE_CONTENT_LANG_KEY = \"AVAILABLE_CONTENT_LANG_KEY\";\n\nexport const UI_LANG_KEY = \"UI_LANG_KEY\";\n\nexport const FLAGS_BY_LANG = {\n \"en\": \"US\",\n \"de\": \"DE\",\n};\n\nexport const DEFAULT_LANG = \"en-US\";\n\nexport const EN_LANG = \"en\";\n\nexport const UI_LANG_OPTIONS = [\"en-us\", \"de-de\"];\n\nexport const RESULT_TYPES = {\n TOPIC: \"TOPIC\",\n DOCUMENT: \"DOCUMENT\",\n PACKAGE: \"PACKAGE\",\n} as const;\n\nexport const FILES_EXTENSIONS = {\n PDF: \"application/pdf\",\n HTML: \"text/html\",\n} as const;\n\nexport const DEFAULT_COOKIE_LIMIT = 7 * 24 * 60 * 60 * 1000; // 7 days in milliseconds\n\nexport const ICONS_BY_FILE_EXTENSION = {\n \"application/pdf\": \"FaFilePdf\",\n} as const;\n\nexport const DEFAULT_ICON = \"file\";","import { 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}","import winston from \"winston\";\nimport { MatomoTransport } from \"./transports/matomo\";\nimport { GraylogTransport } from \"./transports/graylog\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { LOG_LEVELS } from \"@c-rex/constants\";\nimport { getConfigs } from \"@c-rex/utils/next-cookies\";\n\nexport class CrexLogger {\n private customerConfig!: ConfigInterface;\n public logger!: winston.Logger;\n\n private async initLogger() {\n if (!this.customerConfig) {\n this.customerConfig = await getConfigs();\n }\n\n if (!this.logger) {\n this.logger = this.createLogger();\n }\n }\n\n public async log({ level, message, category }: {\n level: LogLevelType,\n message: string,\n category?: LogCategoriesType\n }) {\n await this.initLogger();\n this.logger.log(level, message, category);\n }\n\n private createLogger() {\n return winston.createLogger({\n levels: LOG_LEVELS,\n transports: [\n new winston.transports.Console({\n level: this.customerConfig.logs.console.minimumLevel,\n silent: this.customerConfig.logs.console.silent,\n }),\n new MatomoTransport(this.customerConfig),\n new GraylogTransport(this.customerConfig),\n ],\n });\n }\n}","import Transport from \"winston-transport\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { ALL } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\n\nexport class MatomoTransport extends Transport {\n public matomoTransport: any;\n private configs: ConfigInterface;\n\n constructor(configs: ConfigInterface) {\n super({\n level: configs.logs.console.minimumLevel,\n silent: configs.logs.console.silent,\n });\n\n this.matomoTransport = new Transport();\n this.configs = configs;\n }\n\n log(\n info: { level: LogLevelType, message: string, category: LogCategoriesType },\n callback: () => void,\n ): void {\n const matomoCategory = this.configs.logs.matomo.categoriesLevel\n\n if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {\n\n this.matomoTransport.log(info, callback);\n }\n }\n}\n","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;;;ACAO,IAAM,MAAM;AAeZ,IAAM,aAAa;AAAA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M,OAAO,CAAC;AAAA,EAC7C,SAAS,KAAK;AACV,YAAQ,MAAM,GAAG;AACjB,WAAO,2BAAa,KAAK,EAAE,OAAO,OAAO,GAAG,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACpE;AACJ;","names":["Transport","import_winston_transport","Transport","Graylog2Transport","import_next_cookies","winston"]}
|
package/dist/api/rpc.mjs
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// ../constants/src/index.ts
|
|
2
|
+
var ALL = "*";
|
|
3
|
+
var LOG_LEVELS = {
|
|
4
|
+
critical: 2,
|
|
5
|
+
error: 3,
|
|
6
|
+
warning: 4,
|
|
7
|
+
info: 6,
|
|
8
|
+
debug: 7
|
|
9
|
+
};
|
|
10
|
+
var DEFAULT_COOKIE_LIMIT = 7 * 24 * 60 * 60 * 1e3;
|
|
11
|
+
|
|
12
|
+
// src/sdk.ts
|
|
13
|
+
import { getConfigs } from "@c-rex/utils/next-cookies";
|
|
14
|
+
var CrexSDK = class {
|
|
15
|
+
userAuthConfig;
|
|
16
|
+
customerConfig;
|
|
17
|
+
async getConfig() {
|
|
18
|
+
if (!this.customerConfig) {
|
|
19
|
+
this.customerConfig = await getConfigs();
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
async getUserAuthConfig() {
|
|
23
|
+
if (this.userAuthConfig) {
|
|
24
|
+
return this.userAuthConfig;
|
|
25
|
+
}
|
|
26
|
+
await this.getConfig();
|
|
27
|
+
const user = this.customerConfig.OIDC.user;
|
|
28
|
+
if (user.enabled) {
|
|
29
|
+
this.userAuthConfig = {
|
|
30
|
+
providers: [
|
|
31
|
+
{
|
|
32
|
+
id: "crex",
|
|
33
|
+
name: "CREX",
|
|
34
|
+
type: "oauth",
|
|
35
|
+
clientId: user.id,
|
|
36
|
+
wellKnown: user.issuer,
|
|
37
|
+
clientSecret: user.secret,
|
|
38
|
+
authorization: { params: { scope: user.scope } },
|
|
39
|
+
profile(profile) {
|
|
40
|
+
return {
|
|
41
|
+
id: profile.id || "fake Id",
|
|
42
|
+
name: profile.name || "Fake Name",
|
|
43
|
+
email: profile.email || "fake Email",
|
|
44
|
+
image: profile.image || "fake Image"
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
]
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
;
|
|
52
|
+
return this.userAuthConfig;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// src/logger.ts
|
|
57
|
+
import winston from "winston";
|
|
58
|
+
|
|
59
|
+
// src/transports/matomo.ts
|
|
60
|
+
import Transport from "winston-transport";
|
|
61
|
+
var MatomoTransport = class extends Transport {
|
|
62
|
+
matomoTransport;
|
|
63
|
+
configs;
|
|
64
|
+
constructor(configs) {
|
|
65
|
+
super({
|
|
66
|
+
level: configs.logs.console.minimumLevel,
|
|
67
|
+
silent: configs.logs.console.silent
|
|
68
|
+
});
|
|
69
|
+
this.matomoTransport = new Transport();
|
|
70
|
+
this.configs = configs;
|
|
71
|
+
}
|
|
72
|
+
log(info, callback) {
|
|
73
|
+
const matomoCategory = this.configs.logs.matomo.categoriesLevel;
|
|
74
|
+
if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {
|
|
75
|
+
this.matomoTransport.log(info, callback);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
// src/transports/graylog.ts
|
|
81
|
+
import Transport2 from "winston-transport";
|
|
82
|
+
import Graylog2Transport from "winston-graylog2";
|
|
83
|
+
var GraylogTransport = class extends Transport2 {
|
|
84
|
+
graylogTransport;
|
|
85
|
+
configs;
|
|
86
|
+
constructor(configs) {
|
|
87
|
+
super({
|
|
88
|
+
level: configs.logs.graylog.minimumLevel,
|
|
89
|
+
silent: configs.logs.graylog.silent
|
|
90
|
+
});
|
|
91
|
+
this.configs = configs;
|
|
92
|
+
this.graylogTransport = new Graylog2Transport({
|
|
93
|
+
name: "Periotto-TEST",
|
|
94
|
+
silent: false,
|
|
95
|
+
handleExceptions: false,
|
|
96
|
+
graylog: {
|
|
97
|
+
servers: [{ host: "localhost", port: 12201 }]
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
log(info, callback) {
|
|
102
|
+
const graylogCategory = this.configs.logs.graylog.categoriesLevel;
|
|
103
|
+
if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {
|
|
104
|
+
this.graylogTransport.log(info, callback);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
// src/logger.ts
|
|
110
|
+
import { getConfigs as getConfigs2 } from "@c-rex/utils/next-cookies";
|
|
111
|
+
var CrexLogger = class {
|
|
112
|
+
customerConfig;
|
|
113
|
+
logger;
|
|
114
|
+
async initLogger() {
|
|
115
|
+
if (!this.customerConfig) {
|
|
116
|
+
this.customerConfig = await getConfigs2();
|
|
117
|
+
}
|
|
118
|
+
if (!this.logger) {
|
|
119
|
+
this.logger = this.createLogger();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
async log({ level, message, category }) {
|
|
123
|
+
await this.initLogger();
|
|
124
|
+
this.logger.log(level, message, category);
|
|
125
|
+
}
|
|
126
|
+
createLogger() {
|
|
127
|
+
return winston.createLogger({
|
|
128
|
+
levels: LOG_LEVELS,
|
|
129
|
+
transports: [
|
|
130
|
+
new winston.transports.Console({
|
|
131
|
+
level: this.customerConfig.logs.console.minimumLevel,
|
|
132
|
+
silent: this.customerConfig.logs.console.silent
|
|
133
|
+
}),
|
|
134
|
+
new MatomoTransport(this.customerConfig),
|
|
135
|
+
new GraylogTransport(this.customerConfig)
|
|
136
|
+
]
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
// src/api/rpc.ts
|
|
142
|
+
import { DirectoryNodesService, DocumentTypesService, InformationUnitsService, RenditionsService } from "@c-rex/services";
|
|
143
|
+
import { NextResponse } from "next/server";
|
|
144
|
+
var serviceRegistry = {
|
|
145
|
+
InformationUnitsService,
|
|
146
|
+
DocumentTypesService,
|
|
147
|
+
DirectoryNodesService,
|
|
148
|
+
RenditionsService,
|
|
149
|
+
CrexLogger,
|
|
150
|
+
CrexSDK
|
|
151
|
+
};
|
|
152
|
+
var POST = async (req) => {
|
|
153
|
+
try {
|
|
154
|
+
const { method, params } = await req.json();
|
|
155
|
+
const [serviceName, methodName] = method.split(".");
|
|
156
|
+
const ServiceClass = serviceRegistry[serviceName];
|
|
157
|
+
if (!ServiceClass) {
|
|
158
|
+
return NextResponse.json({ error: `Service '${serviceName}' not found` }, { status: 404 });
|
|
159
|
+
}
|
|
160
|
+
const serviceInstance = new ServiceClass();
|
|
161
|
+
const handler = serviceInstance[methodName];
|
|
162
|
+
if (typeof handler !== "function") {
|
|
163
|
+
return NextResponse.json({ error: `Method '${methodName}' not found on '${serviceName}'` }, { status: 404 });
|
|
164
|
+
}
|
|
165
|
+
const result = await handler.call(serviceInstance, params);
|
|
166
|
+
return NextResponse.json({ data: result });
|
|
167
|
+
} catch (err) {
|
|
168
|
+
console.error(err);
|
|
169
|
+
return NextResponse.json({ error: String(err) }, { status: 500 });
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
export {
|
|
173
|
+
POST
|
|
174
|
+
};
|
|
175
|
+
//# sourceMappingURL=rpc.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../constants/src/index.ts","../../src/sdk.ts","../../src/logger.ts","../../src/transports/matomo.ts","../../src/transports/graylog.ts","../../src/api/rpc.ts"],"sourcesContent":["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 { 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}","import winston from \"winston\";\nimport { MatomoTransport } from \"./transports/matomo\";\nimport { GraylogTransport } from \"./transports/graylog\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { LOG_LEVELS } from \"@c-rex/constants\";\nimport { getConfigs } from \"@c-rex/utils/next-cookies\";\n\nexport class CrexLogger {\n private customerConfig!: ConfigInterface;\n public logger!: winston.Logger;\n\n private async initLogger() {\n if (!this.customerConfig) {\n this.customerConfig = await getConfigs();\n }\n\n if (!this.logger) {\n this.logger = this.createLogger();\n }\n }\n\n public async log({ level, message, category }: {\n level: LogLevelType,\n message: string,\n category?: LogCategoriesType\n }) {\n await this.initLogger();\n this.logger.log(level, message, category);\n }\n\n private createLogger() {\n return winston.createLogger({\n levels: LOG_LEVELS,\n transports: [\n new winston.transports.Console({\n level: this.customerConfig.logs.console.minimumLevel,\n silent: this.customerConfig.logs.console.silent,\n }),\n new MatomoTransport(this.customerConfig),\n new GraylogTransport(this.customerConfig),\n ],\n });\n }\n}","import Transport from \"winston-transport\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { ALL } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\n\nexport class MatomoTransport extends Transport {\n public matomoTransport: any;\n private configs: ConfigInterface;\n\n constructor(configs: ConfigInterface) {\n super({\n level: configs.logs.console.minimumLevel,\n silent: configs.logs.console.silent,\n });\n\n this.matomoTransport = new Transport();\n this.configs = configs;\n }\n\n log(\n info: { level: LogLevelType, message: string, category: LogCategoriesType },\n callback: () => void,\n ): void {\n const matomoCategory = this.configs.logs.matomo.categoriesLevel\n\n if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {\n\n this.matomoTransport.log(info, callback);\n }\n }\n}\n","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","import { CrexSDK } from '../';\nimport { CrexLogger } from '../logger';\nimport { DirectoryNodesService, DocumentTypesService, InformationUnitsService, RenditionsService } from '@c-rex/services';\nimport { NextRequest, NextResponse } from 'next/server';\n\nconst serviceRegistry = {\n InformationUnitsService,\n DocumentTypesService,\n DirectoryNodesService,\n RenditionsService,\n CrexLogger,\n CrexSDK,\n};\n\ntype RpcPayload = {\n method: string;\n params: any;\n};\n\nexport const POST = async (req: NextRequest) => {\n try {\n const { method, params }: RpcPayload = await req.json();\n const [serviceName, methodName] = method.split('.');\n const ServiceClass = serviceRegistry[serviceName as keyof typeof serviceRegistry];\n\n if (!ServiceClass) {\n return NextResponse.json({ error: `Service '${serviceName}' not found` }, { status: 404 });\n }\n\n const serviceInstance = new ServiceClass();\n const handler = (serviceInstance as any)[methodName as any];\n\n if (typeof handler !== 'function') {\n return NextResponse.json({ error: `Method '${methodName}' not found on '${serviceName}'` }, { status: 404 });\n }\n\n const result = await handler.call(serviceInstance, params);\n return NextResponse.json({ data: result });\n } catch (err) {\n console.error(err);\n return NextResponse.json({ error: String(err) }, { status: 500 });\n }\n}\n"],"mappings":";AAAO,IAAM,MAAM;AAeZ,IAAM,aAAa;AAAA,EACtB,UAAU;AAAA,EACV,OAAO;AAAA,EACP,SAAS;AAAA,EACT,MAAM;AAAA,EACN,OAAO;AACX;AA6CO,IAAM,uBAAuB,IAAI,KAAK,KAAK,KAAK;;;ACjEvD,SAAS,kBAAkB;AAEpB,IAAM,UAAN,MAAc;AAAA,EACV;AAAA,EACA;AAAA,EAEP,MAAc,YAAY;AACtB,QAAI,CAAC,KAAK,gBAAgB;AACtB,WAAK,iBAAiB,MAAM,WAAW;AAAA,IAC3C;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;;;AC/CA,OAAO,aAAa;;;ACApB,OAAO,eAAe;AAKf,IAAM,kBAAN,cAA8B,UAAU;AAAA,EACpC;AAAA,EACC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AmB,WAAW,IAAI,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC/G;AAEA,UAAM,SAAS,MAAM,QAAQ,KAAK,iBAAiB,MAAM;AACzD,WAAO,aAAa,KAAK,EAAE,MAAM,OAAO,CAAC;AAAA,EAC7C,SAAS,KAAK;AACV,YAAQ,MAAM,GAAG;AACjB,WAAO,aAAa,KAAK,EAAE,OAAO,OAAO,GAAG,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACpE;AACJ;","names":["Transport","Transport","getConfigs"]}
|
package/dist/index.js
CHANGED
|
@@ -46,7 +46,7 @@ var API = {
|
|
|
46
46
|
"content-Type": "application/json"
|
|
47
47
|
}
|
|
48
48
|
};
|
|
49
|
-
var
|
|
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");
|
|
@@ -108,13 +108,15 @@ var CrexApi = class {
|
|
|
108
108
|
const headersAux = {};
|
|
109
109
|
if (this.customerConfig.OIDC.client.enabled) {
|
|
110
110
|
let token = getFromMemory(CREX_TOKEN_HEADER_KEY);
|
|
111
|
-
|
|
111
|
+
const tokenExpiry = Number(
|
|
112
|
+
getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY)
|
|
113
|
+
);
|
|
112
114
|
const now = Math.floor(Date.now() / 1e3);
|
|
113
115
|
if (!(token && tokenExpiry > now + 60)) {
|
|
114
116
|
const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();
|
|
115
117
|
token = tokenAux;
|
|
116
118
|
saveInMemory(token, CREX_TOKEN_HEADER_KEY);
|
|
117
|
-
saveInMemory(tokenExpiryAux, CREX_TOKEN_EXPIRY_HEADER_KEY);
|
|
119
|
+
saveInMemory(tokenExpiryAux.toString(), CREX_TOKEN_EXPIRY_HEADER_KEY);
|
|
118
120
|
}
|
|
119
121
|
headersAux["Authorization"] = `Bearer ${token}`;
|
|
120
122
|
}
|
|
@@ -133,7 +135,6 @@ var CrexApi = class {
|
|
|
133
135
|
const tokenSet = await client.grant({ grant_type: "client_credentials" });
|
|
134
136
|
token = tokenSet.access_token;
|
|
135
137
|
tokenExpiry = now + tokenSet.expires_at;
|
|
136
|
-
console.log("token", token);
|
|
137
138
|
} catch (error) {
|
|
138
139
|
call("CrexLogger.log", {
|
|
139
140
|
level: "error",
|
|
@@ -147,11 +148,7 @@ var CrexApi = class {
|
|
|
147
148
|
}
|
|
148
149
|
async initAPI() {
|
|
149
150
|
if (!this.customerConfig) {
|
|
150
|
-
|
|
151
|
-
if (!jsonConfigs) {
|
|
152
|
-
throw new Error("SDK not initialized");
|
|
153
|
-
}
|
|
154
|
-
this.customerConfig = JSON.parse(jsonConfigs);
|
|
151
|
+
this.customerConfig = await (0, import_next_cookies.getConfigs)();
|
|
155
152
|
}
|
|
156
153
|
if (!this.apiClient) {
|
|
157
154
|
this.apiClient = import_axios.default.create({
|
|
@@ -183,10 +180,10 @@ var CrexApi = class {
|
|
|
183
180
|
});
|
|
184
181
|
break;
|
|
185
182
|
} catch (error) {
|
|
186
|
-
|
|
187
|
-
"error",
|
|
188
|
-
`API.execute ${retry + 1}\xBA error when request ${url}. Error: ${error}`
|
|
189
|
-
);
|
|
183
|
+
call("CrexLogger.log", {
|
|
184
|
+
level: "error",
|
|
185
|
+
message: `API.execute ${retry + 1}\xBA error when request ${url}. Error: ${error}`
|
|
186
|
+
});
|
|
190
187
|
if (retry === API.MAX_RETRY - 1) {
|
|
191
188
|
throw error;
|
|
192
189
|
}
|
|
@@ -206,11 +203,7 @@ var CrexSDK = class {
|
|
|
206
203
|
customerConfig;
|
|
207
204
|
async getConfig() {
|
|
208
205
|
if (!this.customerConfig) {
|
|
209
|
-
|
|
210
|
-
if (!jsonConfigs) {
|
|
211
|
-
throw new Error("SDK not initialized");
|
|
212
|
-
}
|
|
213
|
-
this.customerConfig = JSON.parse(jsonConfigs);
|
|
206
|
+
this.customerConfig = await (0, import_next_cookies2.getConfigs)();
|
|
214
207
|
}
|
|
215
208
|
}
|
|
216
209
|
async getUserAuthConfig() {
|
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","../../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,iBAAiB;;;ADlC9B,2BAAuB;;;AEAhB,IAAM,OAAO,OAAmB,QAAgB,WAA6B;AAChF,MAAI;AACA,UAAM,MAAM,MAAM,MAAM,GAAG,QAAQ,IAAI,mBAA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,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"]}
|
|
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,OAAM,IAAI,MAAM,KAAK,SAAS,eAAe;AAE1D,WAAO,KAAK;AAAA,EAChB,SAAS,OAAO;AAEZ,YAAQ,MAAM,KAAK;AACnB,WAAO;AAAA,EACX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_cookies"]}
|
package/dist/index.mjs
CHANGED
|
@@ -9,7 +9,7 @@ var API = {
|
|
|
9
9
|
"content-Type": "application/json"
|
|
10
10
|
}
|
|
11
11
|
};
|
|
12
|
-
var
|
|
12
|
+
var DEFAULT_COOKIE_LIMIT = 7 * 24 * 60 * 60 * 1e3;
|
|
13
13
|
|
|
14
14
|
// src/requests.ts
|
|
15
15
|
import { Issuer } from "openid-client";
|
|
@@ -61,7 +61,7 @@ import { DirectoryNodesService } from "@c-rex/services";
|
|
|
61
61
|
import { InformationUnitsService, RenditionsService } from "@c-rex/services";
|
|
62
62
|
|
|
63
63
|
// src/requests.ts
|
|
64
|
-
import {
|
|
64
|
+
import { getConfigs } from "@c-rex/utils/next-cookies";
|
|
65
65
|
var CREX_TOKEN_HEADER_KEY = "crex-token";
|
|
66
66
|
var CREX_TOKEN_EXPIRY_HEADER_KEY = "crex-token-expiry";
|
|
67
67
|
var CrexApi = class {
|
|
@@ -71,13 +71,15 @@ var CrexApi = class {
|
|
|
71
71
|
const headersAux = {};
|
|
72
72
|
if (this.customerConfig.OIDC.client.enabled) {
|
|
73
73
|
let token = getFromMemory(CREX_TOKEN_HEADER_KEY);
|
|
74
|
-
|
|
74
|
+
const tokenExpiry = Number(
|
|
75
|
+
getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY)
|
|
76
|
+
);
|
|
75
77
|
const now = Math.floor(Date.now() / 1e3);
|
|
76
78
|
if (!(token && tokenExpiry > now + 60)) {
|
|
77
79
|
const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();
|
|
78
80
|
token = tokenAux;
|
|
79
81
|
saveInMemory(token, CREX_TOKEN_HEADER_KEY);
|
|
80
|
-
saveInMemory(tokenExpiryAux, CREX_TOKEN_EXPIRY_HEADER_KEY);
|
|
82
|
+
saveInMemory(tokenExpiryAux.toString(), CREX_TOKEN_EXPIRY_HEADER_KEY);
|
|
81
83
|
}
|
|
82
84
|
headersAux["Authorization"] = `Bearer ${token}`;
|
|
83
85
|
}
|
|
@@ -96,7 +98,6 @@ var CrexApi = class {
|
|
|
96
98
|
const tokenSet = await client.grant({ grant_type: "client_credentials" });
|
|
97
99
|
token = tokenSet.access_token;
|
|
98
100
|
tokenExpiry = now + tokenSet.expires_at;
|
|
99
|
-
console.log("token", token);
|
|
100
101
|
} catch (error) {
|
|
101
102
|
call("CrexLogger.log", {
|
|
102
103
|
level: "error",
|
|
@@ -110,11 +111,7 @@ var CrexApi = class {
|
|
|
110
111
|
}
|
|
111
112
|
async initAPI() {
|
|
112
113
|
if (!this.customerConfig) {
|
|
113
|
-
|
|
114
|
-
if (!jsonConfigs) {
|
|
115
|
-
throw new Error("SDK not initialized");
|
|
116
|
-
}
|
|
117
|
-
this.customerConfig = JSON.parse(jsonConfigs);
|
|
114
|
+
this.customerConfig = await getConfigs();
|
|
118
115
|
}
|
|
119
116
|
if (!this.apiClient) {
|
|
120
117
|
this.apiClient = axios.create({
|
|
@@ -146,10 +143,10 @@ var CrexApi = class {
|
|
|
146
143
|
});
|
|
147
144
|
break;
|
|
148
145
|
} catch (error) {
|
|
149
|
-
|
|
150
|
-
"error",
|
|
151
|
-
`API.execute ${retry + 1}\xBA error when request ${url}. Error: ${error}`
|
|
152
|
-
);
|
|
146
|
+
call("CrexLogger.log", {
|
|
147
|
+
level: "error",
|
|
148
|
+
message: `API.execute ${retry + 1}\xBA error when request ${url}. Error: ${error}`
|
|
149
|
+
});
|
|
153
150
|
if (retry === API.MAX_RETRY - 1) {
|
|
154
151
|
throw error;
|
|
155
152
|
}
|
|
@@ -163,17 +160,13 @@ var CrexApi = class {
|
|
|
163
160
|
};
|
|
164
161
|
|
|
165
162
|
// src/sdk.ts
|
|
166
|
-
import {
|
|
163
|
+
import { getConfigs as getConfigs2 } from "@c-rex/utils/next-cookies";
|
|
167
164
|
var CrexSDK = class {
|
|
168
165
|
userAuthConfig;
|
|
169
166
|
customerConfig;
|
|
170
167
|
async getConfig() {
|
|
171
168
|
if (!this.customerConfig) {
|
|
172
|
-
|
|
173
|
-
if (!jsonConfigs) {
|
|
174
|
-
throw new Error("SDK not initialized");
|
|
175
|
-
}
|
|
176
|
-
this.customerConfig = JSON.parse(jsonConfigs);
|
|
169
|
+
this.customerConfig = await getConfigs2();
|
|
177
170
|
}
|
|
178
171
|
}
|
|
179
172
|
async getUserAuthConfig() {
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/requests.ts","../../constants/src/index.ts","../../utils/src/utils.ts","../../utils/src/memory.ts","../../utils/src/classMerge.ts","../../utils/src/treeOfContent.ts","../../utils/src/articles.ts","../src/sdk.ts"],"sourcesContent":["import axios, { AxiosResponse, Method, AxiosInstance } from \"axios\";\nimport { API, 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,OAAO,WAAqD;;;AC4BrD,IAAM,MAAM;AAAA,EACf,WAAW;AAAA,EACX,aAAa;AAAA,EACb,aAAa;AAAA,IACT,gBAAgB;AAAA,EACpB;AACJ;AAEO,IAAM,iBAAiB;;;ADlC9B,SAAS,cAAc;;;AEAhB,IAAM,OAAO,OAAmB,QAAgB,WAA6B;AAChF,MAAI;AACA,UAAM,MAAM,MAAM,MAAM,GAAG,QAAQ,IAAI,mBAAmB,YAAY;AAAA,M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AS;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"]}
|
|
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,SAAS,OAAO;AAEZ,YAAQ,MAAM,KAAK;AACnB,WAAO;AAAA,EACX;AACJ;;;ACtBA,SAAS,YAAY;AACjB,SAAO,OAAO,WAAW,eAAe,OAAO,aAAa;AAChE;AAQO,SAAS,aAAa,OAAe,KAAa;AACrD,MAAI,UAAU,EAAG,OAAM,IAAI,MAAM,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var
|
|
50
|
+
var DEFAULT_COOKIE_LIMIT = 7 * 24 * 60 * 60 * 1e3;
|
|
51
51
|
|
|
52
52
|
// src/transports/matomo.ts
|
|
53
53
|
var MatomoTransport = class extends import_winston_transport.default {
|
|
@@ -105,11 +105,7 @@ var CrexLogger = class {
|
|
|
105
105
|
logger;
|
|
106
106
|
async initLogger() {
|
|
107
107
|
if (!this.customerConfig) {
|
|
108
|
-
|
|
109
|
-
if (!jsonConfigs) {
|
|
110
|
-
throw new Error("SDK not initialized");
|
|
111
|
-
}
|
|
112
|
-
this.customerConfig = JSON.parse(jsonConfigs);
|
|
108
|
+
this.customerConfig = await (0, import_next_cookies.getConfigs)();
|
|
113
109
|
}
|
|
114
110
|
if (!this.logger) {
|
|
115
111
|
this.logger = this.createLogger();
|
package/dist/logger.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/logger.ts","../src/transports/matomo.ts","../../constants/src/index.ts","../src/transports/graylog.ts"],"sourcesContent":["import winston from \"winston\";\nimport { MatomoTransport } from \"./transports/matomo\";\nimport { GraylogTransport } from \"./transports/graylog\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { LOG_LEVELS
|
|
1
|
+
{"version":3,"sources":["../src/logger.ts","../src/transports/matomo.ts","../../constants/src/index.ts","../src/transports/graylog.ts"],"sourcesContent":["import winston from \"winston\";\nimport { MatomoTransport } from \"./transports/matomo\";\nimport { GraylogTransport } from \"./transports/graylog\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { LOG_LEVELS } from \"@c-rex/constants\";\nimport { getConfigs } from \"@c-rex/utils/next-cookies\";\n\nexport class CrexLogger {\n private customerConfig!: ConfigInterface;\n public logger!: winston.Logger;\n\n private async initLogger() {\n if (!this.customerConfig) {\n this.customerConfig = await getConfigs();\n }\n\n if (!this.logger) {\n this.logger = this.createLogger();\n }\n }\n\n public async log({ level, message, category }: {\n level: LogLevelType,\n message: string,\n category?: LogCategoriesType\n }) {\n await this.initLogger();\n this.logger.log(level, message, category);\n }\n\n private createLogger() {\n return winston.createLogger({\n levels: LOG_LEVELS,\n transports: [\n new winston.transports.Console({\n level: this.customerConfig.logs.console.minimumLevel,\n silent: this.customerConfig.logs.console.silent,\n }),\n new MatomoTransport(this.customerConfig),\n new GraylogTransport(this.customerConfig),\n ],\n });\n }\n}","import Transport from \"winston-transport\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { ALL } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\n\nexport class MatomoTransport extends Transport {\n public matomoTransport: any;\n private configs: ConfigInterface;\n\n constructor(configs: ConfigInterface) {\n super({\n level: configs.logs.console.minimumLevel,\n silent: configs.logs.console.silent,\n });\n\n this.matomoTransport = new Transport();\n this.configs = configs;\n }\n\n log(\n info: { level: LogLevelType, message: string, category: LogCategoriesType },\n callback: () => void,\n ): void {\n const matomoCategory = this.configs.logs.matomo.categoriesLevel\n\n if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {\n\n this.matomoTransport.log(info, callback);\n }\n }\n}\n","export const ALL = \"*\"\n\nexport const LOG_CATEGORIES = [\n \"NoLicense\",\n \"Scenario\",\n \"Favorites\",\n \"Subscription\",\n \"Share\",\n \"Document\",\n \"Search\",\n \"History\",\n \"Notification\",\n \"UserProfile\",\n] as const;\n\nexport const LOG_LEVELS = {\n critical: 2,\n error: 3,\n warning: 4,\n info: 6,\n debug: 7,\n} as const;\n\nexport const RESULT_VIEW_STYLES = [\n \"cards\",\n \"table\",\n] as const;\n\nexport const API = {\n MAX_RETRY: 3,\n API_TIMEOUT: 10000,\n API_HEADERS: {\n \"content-Type\": \"application/json\",\n },\n};\n\nexport const SDK_CONFIG_KEY = \"crex-sdk-config\";\n\nexport const CONTENT_LANG_KEY = \"CONTENT_LANG_KEY\";\n\nexport const AVAILABLE_CONTENT_LANG_KEY = \"AVAILABLE_CONTENT_LANG_KEY\";\n\nexport const UI_LANG_KEY = \"UI_LANG_KEY\";\n\nexport const FLAGS_BY_LANG = {\n \"en\": \"US\",\n \"de\": \"DE\",\n};\n\nexport const DEFAULT_LANG = \"en-US\";\n\nexport const EN_LANG = \"en\";\n\nexport const UI_LANG_OPTIONS = [\"en-us\", \"de-de\"];\n\nexport const RESULT_TYPES = {\n TOPIC: \"TOPIC\",\n DOCUMENT: \"DOCUMENT\",\n PACKAGE: \"PACKAGE\",\n} as const;\n\nexport const FILES_EXTENSIONS = {\n PDF: \"application/pdf\",\n HTML: \"text/html\",\n} as const;\n\nexport const DEFAULT_COOKIE_LIMIT = 7 * 24 * 60 * 60 * 1000; // 7 days in milliseconds\n\nexport const ICONS_BY_FILE_EXTENSION = {\n \"application/pdf\": \"FaFilePdf\",\n} as const;\n\nexport const DEFAULT_ICON = \"file\";","import Transport from \"winston-transport\";\nimport Graylog2Transport from \"winston-graylog2\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { ALL } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\n\nexport class GraylogTransport extends Transport {\n public graylogTransport: any;\n public configs: ConfigInterface\n\n constructor(configs: ConfigInterface) {\n super({\n level: configs.logs.graylog.minimumLevel,\n silent: configs.logs.graylog.silent,\n });\n\n this.configs = configs;\n this.graylogTransport = new Graylog2Transport({\n name: \"Periotto-TEST\",\n silent: false,\n handleExceptions: false,\n graylog: {\n servers: [{ host: \"localhost\", port: 12201 }],\n },\n });\n }\n\n log(\n info: { level: LogLevelType, message: string, category: LogCategoriesType },\n callback: () => void,\n ): void {\n const graylogCategory = this.configs.logs.graylog.categoriesLevel\n\n if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {\n this.graylogTransport.log(info, callback);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;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;AAElD,QAAI,gBAAgB,SAAS,KAAK,QAAQ,KAAK,gBAAgB,SAAS,GAAG,GAAG;AAC1E,WAAK,iBAAiB,IAAI,MAAM,QAAQ;AAAA,IAC5C;AAAA,EACJ;AACJ;;;AH/BA,0BAA2B;AAEpB,IAAM,aAAN,MAAiB;AAAA,EACZ;AAAA,EACD;AAAA,EAEP,MAAc,aAAa;AACvB,QAAI,CAAC,KAAK,gBAAgB;AACtB,WAAK,iBAAiB,UAAM,gCAAW;AAAA,IAC3C;AAEA,QAAI,CAAC,KAAK,QAAQ;AACd,WAAK,SAAS,KAAK,aAAa;AAAA,IACpC;AAAA,EACJ;AAAA,EAEA,MAAa,IAAI,EAAE,OAAO,SAAS,SAAS,GAIzC;AACC,UAAM,KAAK,WAAW;AACtB,SAAK,OAAO,IAAI,OAAO,SAAS,QAAQ;AAAA,EAC5C;AAAA,EAEQ,eAAe;AACnB,WAAO,eAAAC,QAAQ,aAAa;AAAA,MACxB,QAAQ;AAAA,MACR,YAAY;AAAA,QACR,IAAI,eAAAA,QAAQ,WAAW,QAAQ;AAAA,UAC3B,OAAO,KAAK,eAAe,KAAK,QAAQ;AAAA,UACxC,QAAQ,KAAK,eAAe,KAAK,QAAQ;AAAA,QAC7C,CAAC;AAAA,QACD,IAAI,gBAAgB,KAAK,cAAc;AAAA,QACvC,IAAI,iBAAiB,KAAK,cAAc;AAAA,MAC5C;AAAA,IACJ,CAAC;AAAA,EACL;AACJ;","names":["Transport","import_winston_transport","Transport","Graylog2Transport","winston"]}
|
package/dist/logger.mjs
CHANGED
|
@@ -13,7 +13,7 @@ var LOG_LEVELS = {
|
|
|
13
13
|
info: 6,
|
|
14
14
|
debug: 7
|
|
15
15
|
};
|
|
16
|
-
var
|
|
16
|
+
var DEFAULT_COOKIE_LIMIT = 7 * 24 * 60 * 60 * 1e3;
|
|
17
17
|
|
|
18
18
|
// src/transports/matomo.ts
|
|
19
19
|
var MatomoTransport = class extends Transport {
|
|
@@ -65,17 +65,13 @@ var GraylogTransport = class extends Transport2 {
|
|
|
65
65
|
};
|
|
66
66
|
|
|
67
67
|
// src/logger.ts
|
|
68
|
-
import {
|
|
68
|
+
import { getConfigs } from "@c-rex/utils/next-cookies";
|
|
69
69
|
var CrexLogger = class {
|
|
70
70
|
customerConfig;
|
|
71
71
|
logger;
|
|
72
72
|
async initLogger() {
|
|
73
73
|
if (!this.customerConfig) {
|
|
74
|
-
|
|
75
|
-
if (!jsonConfigs) {
|
|
76
|
-
throw new Error("SDK not initialized");
|
|
77
|
-
}
|
|
78
|
-
this.customerConfig = JSON.parse(jsonConfigs);
|
|
74
|
+
this.customerConfig = await getConfigs();
|
|
79
75
|
}
|
|
80
76
|
if (!this.logger) {
|
|
81
77
|
this.logger = this.createLogger();
|
package/dist/logger.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/logger.ts","../src/transports/matomo.ts","../../constants/src/index.ts","../src/transports/graylog.ts"],"sourcesContent":["import winston from \"winston\";\nimport { MatomoTransport } from \"./transports/matomo\";\nimport { GraylogTransport } from \"./transports/graylog\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { LOG_LEVELS
|
|
1
|
+
{"version":3,"sources":["../src/logger.ts","../src/transports/matomo.ts","../../constants/src/index.ts","../src/transports/graylog.ts"],"sourcesContent":["import winston from \"winston\";\nimport { MatomoTransport } from \"./transports/matomo\";\nimport { GraylogTransport } from \"./transports/graylog\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { LOG_LEVELS } from \"@c-rex/constants\";\nimport { getConfigs } from \"@c-rex/utils/next-cookies\";\n\nexport class CrexLogger {\n private customerConfig!: ConfigInterface;\n public logger!: winston.Logger;\n\n private async initLogger() {\n if (!this.customerConfig) {\n this.customerConfig = await getConfigs();\n }\n\n if (!this.logger) {\n this.logger = this.createLogger();\n }\n }\n\n public async log({ level, message, category }: {\n level: LogLevelType,\n message: string,\n category?: LogCategoriesType\n }) {\n await this.initLogger();\n this.logger.log(level, message, category);\n }\n\n private createLogger() {\n return winston.createLogger({\n levels: LOG_LEVELS,\n transports: [\n new winston.transports.Console({\n level: this.customerConfig.logs.console.minimumLevel,\n silent: this.customerConfig.logs.console.silent,\n }),\n new MatomoTransport(this.customerConfig),\n new GraylogTransport(this.customerConfig),\n ],\n });\n }\n}","import Transport from \"winston-transport\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { ALL } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\n\nexport class MatomoTransport extends Transport {\n public matomoTransport: any;\n private configs: ConfigInterface;\n\n constructor(configs: ConfigInterface) {\n super({\n level: configs.logs.console.minimumLevel,\n silent: configs.logs.console.silent,\n });\n\n this.matomoTransport = new Transport();\n this.configs = configs;\n }\n\n log(\n info: { level: LogLevelType, message: string, category: LogCategoriesType },\n callback: () => void,\n ): void {\n const matomoCategory = this.configs.logs.matomo.categoriesLevel\n\n if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {\n\n this.matomoTransport.log(info, callback);\n }\n }\n}\n","export const ALL = \"*\"\n\nexport const LOG_CATEGORIES = [\n \"NoLicense\",\n \"Scenario\",\n \"Favorites\",\n \"Subscription\",\n \"Share\",\n \"Document\",\n \"Search\",\n \"History\",\n \"Notification\",\n \"UserProfile\",\n] as const;\n\nexport const LOG_LEVELS = {\n critical: 2,\n error: 3,\n warning: 4,\n info: 6,\n debug: 7,\n} as const;\n\nexport const RESULT_VIEW_STYLES = [\n \"cards\",\n \"table\",\n] as const;\n\nexport const API = {\n MAX_RETRY: 3,\n API_TIMEOUT: 10000,\n API_HEADERS: {\n \"content-Type\": \"application/json\",\n },\n};\n\nexport const SDK_CONFIG_KEY = \"crex-sdk-config\";\n\nexport const CONTENT_LANG_KEY = \"CONTENT_LANG_KEY\";\n\nexport const AVAILABLE_CONTENT_LANG_KEY = \"AVAILABLE_CONTENT_LANG_KEY\";\n\nexport const UI_LANG_KEY = \"UI_LANG_KEY\";\n\nexport const FLAGS_BY_LANG = {\n \"en\": \"US\",\n \"de\": \"DE\",\n};\n\nexport const DEFAULT_LANG = \"en-US\";\n\nexport const EN_LANG = \"en\";\n\nexport const UI_LANG_OPTIONS = [\"en-us\", \"de-de\"];\n\nexport const RESULT_TYPES = {\n TOPIC: \"TOPIC\",\n DOCUMENT: \"DOCUMENT\",\n PACKAGE: \"PACKAGE\",\n} as const;\n\nexport const FILES_EXTENSIONS = {\n PDF: \"application/pdf\",\n HTML: \"text/html\",\n} as const;\n\nexport const DEFAULT_COOKIE_LIMIT = 7 * 24 * 60 * 60 * 1000; // 7 days in milliseconds\n\nexport const ICONS_BY_FILE_EXTENSION = {\n \"application/pdf\": \"FaFilePdf\",\n} as const;\n\nexport const DEFAULT_ICON = \"file\";","import Transport from \"winston-transport\";\nimport Graylog2Transport from \"winston-graylog2\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { ALL } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\n\nexport class GraylogTransport extends Transport {\n public graylogTransport: any;\n public configs: ConfigInterface\n\n constructor(configs: ConfigInterface) {\n super({\n level: configs.logs.graylog.minimumLevel,\n silent: configs.logs.graylog.silent,\n });\n\n this.configs = configs;\n this.graylogTransport = new Graylog2Transport({\n name: \"Periotto-TEST\",\n silent: false,\n handleExceptions: false,\n graylog: {\n servers: [{ host: \"localhost\", port: 12201 }],\n },\n });\n }\n\n log(\n info: { level: LogLevelType, message: string, category: LogCategoriesType },\n callback: () => void,\n ): void {\n const graylogCategory = this.configs.logs.graylog.categoriesLevel\n\n if (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;AAA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MAAM,QAAQ;AAAA,IAC5C;AAAA,EACJ;AACJ;;;AH/BA,SAAS,kBAAkB;AAEpB,IAAM,aAAN,MAAiB;AAAA,EACZ;AAAA,EACD;AAAA,EAEP,MAAc,aAAa;AACvB,QAAI,CAAC,KAAK,gBAAgB;AACtB,WAAK,iBAAiB,MAAM,WAAW;AAAA,IAC3C;AAEA,QAAI,CAAC,KAAK,QAAQ;AACd,WAAK,SAAS,KAAK,aAAa;AAAA,IACpC;AAAA,EACJ;AAAA,EAEA,MAAa,IAAI,EAAE,OAAO,SAAS,SAAS,GAIzC;AACC,UAAM,KAAK,WAAW;AACtB,SAAK,OAAO,IAAI,OAAO,SAAS,QAAQ;AAAA,EAC5C;AAAA,EAEQ,eAAe;AACnB,WAAO,QAAQ,aAAa;AAAA,MACxB,QAAQ;AAAA,MACR,YAAY;AAAA,QACR,IAAI,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","Transport"]}
|
package/package.json
CHANGED
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@c-rex/core",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"main": "dist/index.js",
|
|
5
|
-
"module": "dist/index.mjs",
|
|
6
|
-
"types": "dist/index.d.ts",
|
|
3
|
+
"version": "0.1.2",
|
|
7
4
|
"files": [
|
|
8
5
|
"dist"
|
|
9
6
|
],
|
|
@@ -17,12 +14,23 @@
|
|
|
17
14
|
"require": "./dist/index.js",
|
|
18
15
|
"default": "./dist/index.js"
|
|
19
16
|
},
|
|
20
|
-
"./package.json": "./package.json",
|
|
21
17
|
"./logger": {
|
|
22
18
|
"types": "./dist/logger.d.ts",
|
|
23
19
|
"import": "./dist/logger.mjs",
|
|
24
20
|
"require": "./dist/logger.js",
|
|
25
21
|
"default": "./dist/logger.js"
|
|
22
|
+
},
|
|
23
|
+
"./cookies": {
|
|
24
|
+
"types": "./dist/api/cookies.d.ts",
|
|
25
|
+
"import": "./dist/api/cookies.mjs",
|
|
26
|
+
"require": "./dist/api/cookies.js",
|
|
27
|
+
"default": "./dist/api/cookies.js"
|
|
28
|
+
},
|
|
29
|
+
"./rpc": {
|
|
30
|
+
"types": "./dist/api/rpc.d.ts",
|
|
31
|
+
"import": "./dist/api/rpc.mjs",
|
|
32
|
+
"require": "./dist/api/rpc.js",
|
|
33
|
+
"default": "./dist/api/rpc.js"
|
|
26
34
|
}
|
|
27
35
|
},
|
|
28
36
|
"sideEffects": false,
|