@okf/ootils 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,13 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
6
11
  var __export = (target, all) => {
7
12
  for (var name in all)
8
13
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -15,15 +20,316 @@ var __copyProps = (to, from, except, desc) => {
15
20
  }
16
21
  return to;
17
22
  };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
18
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
32
 
33
+ // src/models/Annotations.js
34
+ var require_Annotations = __commonJS({
35
+ "src/models/Annotations.js"(exports2, module2) {
36
+ "use strict";
37
+ var mongoose2 = require("mongoose");
38
+ var Schema = mongoose2.Schema;
39
+ var AnnotationSchema = new Schema(
40
+ {
41
+ // Tags section - dynamic structure for various tag categories
42
+ tags: {
43
+ type: Map,
44
+ of: {
45
+ data: [
46
+ {
47
+ _id: { type: Schema.Types.ObjectId },
48
+ display: String,
49
+ tagId: String
50
+ }
51
+ ],
52
+ collectionId: String
53
+ }
54
+ },
55
+ // Meta information
56
+ meta: {
57
+ contentType: { type: String, required: true },
58
+ kp_contributed_by: {
59
+ type: Schema.Types.ObjectId,
60
+ ref: "user"
61
+ },
62
+ valuePath: String,
63
+ documentId: {
64
+ type: Schema.Types.ObjectId
65
+ }
66
+ },
67
+ // Main content data - using Schema.Types.Mixed for dynamic structure
68
+ main: {
69
+ type: Schema.Types.Mixed,
70
+ default: {}
71
+ },
72
+ // Annotation specific details
73
+ annotations: {
74
+ tags: {
75
+ type: Map,
76
+ of: {
77
+ collectionId: String,
78
+ data: [
79
+ {
80
+ _id: { type: Schema.Types.ObjectId },
81
+ display: String,
82
+ tagId: String
83
+ }
84
+ ]
85
+ }
86
+ },
87
+ fragment: {
88
+ isLexical: Boolean,
89
+ editorState: Object,
90
+ allText: String
91
+ },
92
+ annoKey: String,
93
+ author: {
94
+ id: { type: Schema.Types.ObjectId },
95
+ name: String
96
+ }
97
+ },
98
+ embeddings: Array,
99
+ contentEnhancedText: String,
100
+ // // Optional chunk related fields
101
+ // chunk: {
102
+ // embeddings: Schema.Types.Mixed,
103
+ // contentEnhancedText: String
104
+ // },
105
+ clusterId: String,
106
+ kp_date_published: Date,
107
+ createdAt: {
108
+ type: Date,
109
+ default: Date.now
110
+ },
111
+ updatedAt: {
112
+ type: Date,
113
+ default: Date.now
114
+ },
115
+ translations: Object
116
+ },
117
+ {
118
+ timestamps: true,
119
+ toJSON: { virtuals: true },
120
+ toObject: { virtuals: true },
121
+ strict: false
122
+ // This allows for flexible document structure beyond the defined schema
123
+ }
124
+ );
125
+ AnnotationSchema.index({ "meta.contentType": 1 });
126
+ AnnotationSchema.index({ "meta.documentId": 1 });
127
+ AnnotationSchema.index({ createdAt: -1 });
128
+ AnnotationSchema.index({ "annotations.annoKey": 1 });
129
+ AnnotationSchema.pre("save", function(next) {
130
+ this.updatedAt = /* @__PURE__ */ new Date();
131
+ next();
132
+ });
133
+ AnnotationSchema.methods.getMainField = function(fieldPath) {
134
+ if (!fieldPath) return null;
135
+ const parts = fieldPath.split(".");
136
+ let value = this.main;
137
+ for (const part of parts) {
138
+ if (!value || typeof value !== "object") return null;
139
+ value = value[part];
140
+ }
141
+ return value;
142
+ };
143
+ AnnotationSchema.virtual("displayTitle").get(function() {
144
+ return this.main.title || "Untitled Annotation";
145
+ });
146
+ module2.exports = AnnotationSchema;
147
+ }
148
+ });
149
+
150
+ // src/models/PlatformConfigs.js
151
+ var require_PlatformConfigs = __commonJS({
152
+ "src/models/PlatformConfigs.js"(exports2, module2) {
153
+ "use strict";
154
+ var mongoose2 = require("mongoose");
155
+ var platformConfigTypes = [
156
+ { id: "roles" },
157
+ { id: "contentTypes" },
158
+ { id: "contentCards" },
159
+ { id: "profileTypes" },
160
+ { id: "nav" },
161
+ { id: "deployment" },
162
+ { id: "userAgreement" },
163
+ { id: "localeData" },
164
+ { id: "theme" },
165
+ { id: "tagTypes" },
166
+ { id: "AI" }
167
+ ];
168
+ var PlatformConfigsSchema2 = new mongoose2.Schema(
169
+ {
170
+ type: {
171
+ type: String,
172
+ enum: platformConfigTypes.map((d) => d.id),
173
+ unique: true
174
+ },
175
+ roles: Array,
176
+ data: Object
177
+ },
178
+ { collection: "platformConfigs" }
179
+ );
180
+ module2.exports = PlatformConfigsSchema2;
181
+ }
182
+ });
183
+
184
+ // src/models/Tpl.js
185
+ var require_Tpl = __commonJS({
186
+ "src/models/Tpl.js"(exports2, module2) {
187
+ "use strict";
188
+ var mongoose2 = require("mongoose");
189
+ var TplSchema2 = new mongoose2.Schema({
190
+ dateFirstPublished: Date,
191
+ dateCreated: Date,
192
+ dateLastPublished: Date,
193
+ dateLastEdited: Date,
194
+ status: {
195
+ type: String,
196
+ default: "published",
197
+ // only cuz we dont want to go and add this property in all databases
198
+ enum: ["unpublished", "editPublished", "published"]
199
+ },
200
+ version: {
201
+ type: Number,
202
+ default: 0
203
+ },
204
+ versionPublishedBy: {
205
+ type: mongoose2.Schema.Types.ObjectId,
206
+ ref: "user"
207
+ // reference to the 'user' model
208
+ },
209
+ firstPublishedBy: {
210
+ type: mongoose2.Schema.Types.ObjectId,
211
+ ref: "user"
212
+ // reference to the 'user' model
213
+ },
214
+ kp_content_type: {
215
+ type: String,
216
+ required: true,
217
+ unique: true
218
+ },
219
+ category: {
220
+ //to deprecate and turn into 'layout'
221
+ type: String,
222
+ default: "knowledgeResources2"
223
+ },
224
+ kp_settings: [
225
+ {
226
+ type: Object
227
+ }
228
+ ],
229
+ kp_templates: {
230
+ type: Object
231
+ },
232
+ tplMeta: Object,
233
+ tplLocales: Object,
234
+ indexed: Object,
235
+ drafts: {
236
+ active: Object
237
+ },
238
+ rollbacks: Object,
239
+ //for 'remembering' hidden configurations
240
+ // OTHER CONFIGS
241
+ listing: Object,
242
+ //listing page configurations. this is new, currently only used in nct
243
+ general: {
244
+ content: {
245
+ title: String,
246
+ singular: String,
247
+ ctaText: String,
248
+ listingDesc: String
249
+ },
250
+ allowQuickTagCreation: { enable: Boolean },
251
+ segment: String,
252
+ settingsUIStyle: String,
253
+ hasUpdateType: Boolean,
254
+ annotation: {
255
+ enable: Boolean
256
+ },
257
+ participantModule: {
258
+ enable: Boolean
259
+ },
260
+ formFieldNumbering: {
261
+ enable: Boolean
262
+ },
263
+ postPblRedirPath: Object,
264
+ templateIndex: Object,
265
+ sharing: {
266
+ enable: Boolean,
267
+ trackShareCount: {
268
+ type: Boolean,
269
+ default: false
270
+ }
271
+ },
272
+ viewsCount: {
273
+ enable: {
274
+ type: Boolean,
275
+ default: false
276
+ }
277
+ },
278
+ comments: {
279
+ enable: Boolean
280
+ },
281
+ reactions: {
282
+ type: Map,
283
+ of: {
284
+ enable: Boolean,
285
+ icon: String
286
+ }
287
+ },
288
+ csvExport: {
289
+ enable: Boolean,
290
+ excludeFields: Array,
291
+ enableUpdateExport: Boolean,
292
+ fieldsToSortAtEnd: Array,
293
+ fetchBatches: {
294
+ enable: Boolean,
295
+ batchSize: Number
296
+ }
297
+ },
298
+ //tci helpers - these exist only to show / not show certain UIs in the tci
299
+ disableKPSettings: Boolean
300
+ }
301
+ //general contenttype configs. mostly the stuff inside platformConfigs > contentTypes
302
+ }, {
303
+ toJSON: { virtuals: true },
304
+ // So `res.json()` and other `JSON.stringify()` functions include virtuals
305
+ toObject: { virtuals: true }
306
+ // So `toObject()` output includes virtuals
307
+ });
308
+ TplSchema2.virtual("layout").get(function() {
309
+ return this.category;
310
+ });
311
+ module2.exports = TplSchema2;
312
+ }
313
+ });
314
+
20
315
  // src/index.ts
21
316
  var index_exports = {};
22
317
  __export(index_exports, {
23
318
  add: () => add,
319
+ connectToRedis: () => connectToRedis,
24
320
  deleteVal: () => deleteVal,
321
+ getAIConfigs: () => getAIConfigs,
322
+ getAnnotationsModelByTenant: () => getAnnotationsModelByTenant,
323
+ getDbByTenant: () => getDbByTenant,
324
+ getModelByTenant: () => getModelByTenant,
325
+ getPlatformConfigsModelByTenant: () => getPlatformConfigsModelByTenant,
326
+ getTpl: () => getTpl,
327
+ getTplModelByTenant: () => getTplModelByTenant,
25
328
  getVal: () => getVal,
26
- setVal: () => setVal
329
+ initializeGlobalConfig: () => initializeGlobalConfig,
330
+ multiConnectToMongoDB: () => multiConnectToMongoDB,
331
+ setVal: () => setVal,
332
+ updateGlobalConfig: () => updateGlobalConfig
27
333
  });
28
334
  module.exports = __toCommonJS(index_exports);
29
335
 
@@ -32,6 +338,142 @@ function add(a, b) {
32
338
  return a + b;
33
339
  }
34
340
 
341
+ // src/db/mongodb.ts
342
+ var import_mongoose = __toESM(require("mongoose"));
343
+
344
+ // src/db/getGlobalConfig.ts
345
+ var globalConfig = {};
346
+ var getGlobalConfig = () => {
347
+ return {
348
+ env: globalConfig.env,
349
+ dbConfigs: globalConfig.dbConfigs ? { ...globalConfig.dbConfigs } : void 0,
350
+ mongodb: globalConfig.mongodb ? { ...globalConfig.mongodb } : void 0
351
+ };
352
+ };
353
+ var initializeGlobalConfig = (config) => {
354
+ globalConfig = {
355
+ env: config.env,
356
+ dbConfigs: config.dbConfigs ? { ...config.dbConfigs } : void 0,
357
+ mongodb: config.mongodb ? { ...config.mongodb } : void 0
358
+ };
359
+ console.log(`Global config initialized for environment: ${config.env}`);
360
+ };
361
+ var updateGlobalConfig = (updates) => {
362
+ globalConfig = {
363
+ ...globalConfig,
364
+ ...updates,
365
+ // Handle nested objects properly
366
+ dbConfigs: updates.dbConfigs ? { ...globalConfig.dbConfigs, ...updates.dbConfigs } : globalConfig.dbConfigs,
367
+ mongodb: updates.mongodb ? { ...globalConfig.mongodb, ...updates.mongodb } : globalConfig.mongodb
368
+ };
369
+ console.log("Global config updated:", Object.keys(updates));
370
+ };
371
+
372
+ // src/db/mongodb.ts
373
+ var mongoOptions = {
374
+ // Note: These legacy options are no longer needed in newer versions of mongoose
375
+ // useUnifiedTopology, useNewUrlParser, useCreateIndex, useFindAndModify are deprecated
376
+ maxPoolSize: 10
377
+ // replaces poolSize
378
+ };
379
+ var multiConnectToMongoDB = ({ env, dbConfigs } = {}) => {
380
+ const globalConfig2 = getGlobalConfig();
381
+ const actualEnv = env || globalConfig2.env;
382
+ const actualDbConfigs = dbConfigs || globalConfig2.dbConfigs;
383
+ if (!actualEnv) {
384
+ throw new Error("Environment not provided and not found in global config");
385
+ }
386
+ if (!actualDbConfigs) {
387
+ throw new Error("dbConfigs not provided and not found in global config");
388
+ }
389
+ const { connectTo } = actualDbConfigs[actualEnv];
390
+ if (!connectTo) {
391
+ throw new Error(`No connection configuration found for environment: ${actualEnv}`);
392
+ }
393
+ const dbConnections = {};
394
+ connectTo.forEach((connectToEnv) => {
395
+ const { CLUSTER_NAME, DB_URI } = actualDbConfigs[connectToEnv];
396
+ if (!CLUSTER_NAME || !DB_URI) {
397
+ throw new Error(`Missing CLUSTER_NAME or DB_URI for environment: ${connectToEnv}`);
398
+ }
399
+ dbConnections[CLUSTER_NAME] = import_mongoose.default.createConnection(DB_URI, mongoOptions);
400
+ dbConnections[CLUSTER_NAME].on("open", () => {
401
+ console.log(`Mongoose connection open to ${CLUSTER_NAME}`);
402
+ });
403
+ dbConnections[CLUSTER_NAME].on("error", (err) => {
404
+ console.log(`Mongoose connection error: ${err.message} with connection info ${CLUSTER_NAME}`);
405
+ process.exit(1);
406
+ });
407
+ });
408
+ return dbConnections;
409
+ };
410
+
411
+ // src/db/getDbByTenant.ts
412
+ var getDbByTenant = ({
413
+ tenant,
414
+ env
415
+ }) => {
416
+ if (!tenant) throw new Error("tenant id has not been provided");
417
+ const globalConfig2 = getGlobalConfig();
418
+ const actualEnv = env || globalConfig2.env;
419
+ const dbConfigs = globalConfig2.dbConfigs;
420
+ const mongodb = globalConfig2.mongodb;
421
+ if (!dbConfigs) {
422
+ throw new Error("dbConfigs not found in global config");
423
+ }
424
+ if (!actualEnv) {
425
+ throw new Error("env not provided and not found in global config");
426
+ }
427
+ const { CLUSTER_NAME } = dbConfigs[actualEnv];
428
+ const dbName = `${tenant}_${actualEnv}`;
429
+ if (mongodb) {
430
+ const db = mongodb[CLUSTER_NAME].useDb(dbName, { useCache: true });
431
+ return db;
432
+ }
433
+ throw new Error("getDbByTenant : mongodb object doesnt exist");
434
+ };
435
+
436
+ // src/db/getModelByTenant.ts
437
+ var AnnotationsSchema = require_Annotations();
438
+ var PlatformConfigsSchema = require_PlatformConfigs();
439
+ var TplSchema = require_Tpl();
440
+ var getModelByTenant = ({
441
+ tenant,
442
+ modelName,
443
+ schema,
444
+ env
445
+ }) => {
446
+ if (!tenant) {
447
+ throw new Error("tenant id has not been provided");
448
+ }
449
+ const db = getDbByTenant({
450
+ tenant,
451
+ env
452
+ });
453
+ if (!Object.keys(db.models).includes(modelName)) {
454
+ return db.model(modelName, schema);
455
+ }
456
+ return db.model(modelName);
457
+ };
458
+ var getAnnotationsModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
459
+ tenant,
460
+ modelName: "annotations",
461
+ schema: AnnotationsSchema,
462
+ env
463
+ });
464
+ var getPlatformConfigsModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
465
+ tenant,
466
+ modelName: "platformConfigs",
467
+ schema: PlatformConfigsSchema,
468
+ env
469
+ });
470
+ var getTplModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
471
+ tenant,
472
+ modelName: "tpl",
473
+ schema: TplSchema,
474
+ env
475
+ });
476
+
35
477
  // src/utils/getterSetterDeleter/utils/set_deleteVal.ts
36
478
  var set_deleteVal = (action, data, valuePath, value) => {
37
479
  if (valuePath === void 0) return;
@@ -162,10 +604,128 @@ var getValV2_getter = (data, valuePath, options, depthIdx) => {
162
604
  }
163
605
  return dataRef[keysArray[len - 1]];
164
606
  };
607
+
608
+ // src/redis/index.ts
609
+ var import_ioredis = __toESM(require("ioredis"));
610
+ var redisClient = null;
611
+ var REDIS_CONFIG = {
612
+ port: Number(process.env.REDIS_PORT),
613
+ host: process.env.REDIS_HOST || "",
614
+ username: process.env.REDIS_USERNAME || "",
615
+ password: process.env.REDIS_PASSWORD || ""
616
+ };
617
+ var connectToRedis = async () => {
618
+ try {
619
+ redisClient = new import_ioredis.default(REDIS_CONFIG);
620
+ await redisClient.ping();
621
+ console.log("Redis connected successfully");
622
+ } catch (error) {
623
+ console.error(
624
+ "Redis connection failed:",
625
+ error instanceof Error && error.message
626
+ );
627
+ if (redisClient) {
628
+ redisClient.disconnect();
629
+ }
630
+ throw error;
631
+ }
632
+ };
633
+ var getRedisClient = () => {
634
+ if (!redisClient) {
635
+ throw new Error("Redis client not initialized. Call connectToRedis first.");
636
+ }
637
+ return redisClient;
638
+ };
639
+
640
+ // src/redis/functions.ts
641
+ var findInCache = async ({
642
+ tenant,
643
+ modelName,
644
+ type,
645
+ query = {}
646
+ }) => {
647
+ const key = `${process.env.ENV}:${tenant}:${modelName}:${type}`;
648
+ try {
649
+ const redisClient2 = getRedisClient();
650
+ const value = await redisClient2.get(key);
651
+ if (value) {
652
+ return JSON.parse(value);
653
+ }
654
+ } catch (error) {
655
+ console.warn(
656
+ `redis read failed for key ${key}`,
657
+ error instanceof Error && error.message
658
+ );
659
+ }
660
+ try {
661
+ const collection = getDbByTenant({
662
+ tenant,
663
+ env: process.env.ENV
664
+ }).collection(modelName);
665
+ const value = await collection.findOne(query);
666
+ if (!value) {
667
+ throw new Error(`${type} value not found in ${modelName} for ${tenant}`);
668
+ }
669
+ try {
670
+ const redisClient2 = getRedisClient();
671
+ await redisClient2.set(key, JSON.stringify(value));
672
+ } catch (error) {
673
+ console.warn(
674
+ `redis write failed for key ${key}:`,
675
+ error instanceof Error && error.message
676
+ );
677
+ }
678
+ return value;
679
+ } catch (error) {
680
+ throw new Error(
681
+ `db read failed: ${error instanceof Error && error.message}`
682
+ );
683
+ }
684
+ };
685
+ var getTpl = async ({ name, tenant }) => {
686
+ if (!name || !tenant) {
687
+ throw new Error("Missing required parameters: name or tenant");
688
+ }
689
+ return await findInCache({
690
+ modelName: "tpls",
691
+ type: name,
692
+ tenant,
693
+ query: {
694
+ kp_content_type: name,
695
+ status: { $in: ["published", "editPublished"] }
696
+ }
697
+ });
698
+ };
699
+ var getAIConfigs = async ({
700
+ tenant
701
+ }) => {
702
+ if (!tenant) {
703
+ throw new Error("Missing required parameter: tenant");
704
+ }
705
+ return await findInCache({
706
+ modelName: "platformConfigs",
707
+ type: "ai",
708
+ tenant,
709
+ query: {
710
+ type: "ai"
711
+ }
712
+ });
713
+ };
165
714
  // Annotate the CommonJS export names for ESM import in node:
166
715
  0 && (module.exports = {
167
716
  add,
717
+ connectToRedis,
168
718
  deleteVal,
719
+ getAIConfigs,
720
+ getAnnotationsModelByTenant,
721
+ getDbByTenant,
722
+ getModelByTenant,
723
+ getPlatformConfigsModelByTenant,
724
+ getTpl,
725
+ getTplModelByTenant,
169
726
  getVal,
170
- setVal
727
+ initializeGlobalConfig,
728
+ multiConnectToMongoDB,
729
+ setVal,
730
+ updateGlobalConfig
171
731
  });