@okf/ootils 1.3.9 → 1.3.11

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/node.mjs CHANGED
@@ -38,6 +38,613 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
38
38
  ));
39
39
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
40
40
 
41
+ // src/models/Annotations.ts
42
+ var Annotations_exports = {};
43
+ __export(Annotations_exports, {
44
+ default: () => Annotations_default
45
+ });
46
+ import { Schema } from "mongoose";
47
+ var AnnotationSchema, Annotations_default;
48
+ var init_Annotations = __esm({
49
+ "src/models/Annotations.ts"() {
50
+ "use strict";
51
+ AnnotationSchema = new Schema(
52
+ {
53
+ // Tags section - dynamic structure for various tag categories
54
+ tags: {
55
+ type: Map,
56
+ of: new Schema({
57
+ data: [
58
+ {
59
+ _id: { type: Schema.Types.ObjectId },
60
+ display: String,
61
+ tagId: String
62
+ }
63
+ ],
64
+ collectionId: String
65
+ }, {
66
+ _id: false
67
+ })
68
+ },
69
+ // Meta information
70
+ meta: {
71
+ contentType: { type: String, required: true },
72
+ kp_contributed_by: {
73
+ type: Schema.Types.ObjectId,
74
+ ref: "user"
75
+ },
76
+ valuePath: String,
77
+ documentId: {
78
+ type: Schema.Types.ObjectId
79
+ }
80
+ },
81
+ // Main content data - using Schema.Types.Mixed for dynamic structure
82
+ main: {
83
+ type: Schema.Types.Mixed,
84
+ default: {}
85
+ },
86
+ // Annotation specific details
87
+ annotations: {
88
+ tags: {
89
+ type: Map,
90
+ of: new Schema({
91
+ collectionId: String,
92
+ data: [
93
+ {
94
+ _id: { type: Schema.Types.ObjectId },
95
+ display: String,
96
+ tagId: String
97
+ }
98
+ ]
99
+ }, {
100
+ _id: false
101
+ })
102
+ },
103
+ fragment: {
104
+ isLexical: Boolean,
105
+ editorState: Object,
106
+ allText: String
107
+ },
108
+ annoKey: String,
109
+ author: {
110
+ id: { type: Schema.Types.ObjectId },
111
+ name: String
112
+ }
113
+ },
114
+ embeddings: Array,
115
+ contentEnhancedText: String,
116
+ // // Optional chunk related fields
117
+ // chunk: {
118
+ // embeddings: Schema.Types.Mixed,
119
+ // contentEnhancedText: String
120
+ // },
121
+ clusterId: String,
122
+ kp_date_published: Date,
123
+ createdAt: {
124
+ type: Date,
125
+ default: Date.now
126
+ },
127
+ updatedAt: {
128
+ type: Date,
129
+ default: Date.now
130
+ },
131
+ topicId: [{ type: Schema.Types.ObjectId, ref: "generatedTopics" }],
132
+ translations: Object
133
+ },
134
+ {
135
+ timestamps: true,
136
+ toJSON: { virtuals: true },
137
+ toObject: { virtuals: true },
138
+ strict: false
139
+ // This allows for flexible document structure beyond the defined schema
140
+ }
141
+ );
142
+ AnnotationSchema.index({ "meta.contentType": 1 });
143
+ AnnotationSchema.index({ "meta.documentId": 1 });
144
+ AnnotationSchema.index({ createdAt: -1 });
145
+ AnnotationSchema.index({ "annotations.annoKey": 1 });
146
+ AnnotationSchema.index({ "kp_date_published": -1 });
147
+ AnnotationSchema.pre("save", function(next) {
148
+ this.updatedAt = /* @__PURE__ */ new Date();
149
+ next();
150
+ });
151
+ AnnotationSchema.methods.getMainField = function(fieldPath) {
152
+ if (!fieldPath) return null;
153
+ const parts = fieldPath.split(".");
154
+ let value = this.main;
155
+ for (const part of parts) {
156
+ if (!value || typeof value !== "object") return null;
157
+ value = value[part];
158
+ }
159
+ return value;
160
+ };
161
+ AnnotationSchema.virtual("displayTitle").get(function() {
162
+ return this.main?.title || "Untitled Annotation";
163
+ });
164
+ Annotations_default = AnnotationSchema;
165
+ }
166
+ });
167
+
168
+ // src/models/PlatformConfigs.ts
169
+ var PlatformConfigs_exports = {};
170
+ __export(PlatformConfigs_exports, {
171
+ default: () => PlatformConfigs_default
172
+ });
173
+ import mongoose2 from "mongoose";
174
+ var platformConfigTypes, PlatformConfigsSchema, PlatformConfigs_default;
175
+ var init_PlatformConfigs = __esm({
176
+ "src/models/PlatformConfigs.ts"() {
177
+ "use strict";
178
+ platformConfigTypes = [
179
+ "roles",
180
+ "nav",
181
+ "deployment",
182
+ "userAgreement",
183
+ "localeData",
184
+ "theme",
185
+ "AI"
186
+ ];
187
+ PlatformConfigsSchema = new mongoose2.Schema(
188
+ {
189
+ type: {
190
+ type: String,
191
+ enum: platformConfigTypes,
192
+ unique: true
193
+ },
194
+ roles: Array,
195
+ data: Object
196
+ },
197
+ { collection: "platformConfigs" }
198
+ );
199
+ PlatformConfigs_default = PlatformConfigsSchema;
200
+ }
201
+ });
202
+
203
+ // src/models/Tpl.ts
204
+ var Tpl_exports = {};
205
+ __export(Tpl_exports, {
206
+ default: () => Tpl_default
207
+ });
208
+ import mongoose3 from "mongoose";
209
+ var TplSchema, Tpl_default;
210
+ var init_Tpl = __esm({
211
+ "src/models/Tpl.ts"() {
212
+ "use strict";
213
+ TplSchema = new mongoose3.Schema({
214
+ dateFirstPublished: Date,
215
+ dateCreated: Date,
216
+ dateLastPublished: Date,
217
+ dateLastEdited: Date,
218
+ status: {
219
+ type: String,
220
+ default: "published",
221
+ // only cuz we dont want to go and add this property in all databases
222
+ enum: ["unpublished", "editPublished", "published"]
223
+ },
224
+ version: {
225
+ type: Number,
226
+ default: 0
227
+ },
228
+ versionPublishedBy: {
229
+ type: mongoose3.Schema.Types.ObjectId,
230
+ ref: "user"
231
+ // reference to the 'user' model
232
+ },
233
+ firstPublishedBy: {
234
+ type: mongoose3.Schema.Types.ObjectId,
235
+ ref: "user"
236
+ // reference to the 'user' model
237
+ },
238
+ kp_content_type: {
239
+ type: String,
240
+ required: true,
241
+ unique: true
242
+ },
243
+ category: {
244
+ //to deprecate and turn into 'layout'
245
+ type: String,
246
+ default: "knowledgeResources2"
247
+ },
248
+ kp_settings: [
249
+ {
250
+ type: Object
251
+ }
252
+ ],
253
+ kp_templates: {
254
+ type: Object
255
+ },
256
+ tplMeta: Object,
257
+ tplLocales: Object,
258
+ indexed: Object,
259
+ drafts: {
260
+ active: Object
261
+ },
262
+ rollbacks: Object,
263
+ //for 'remembering' hidden configurations
264
+ // OTHER CONFIGS
265
+ listing: Object,
266
+ //listing page configurations. this is new, currently only used in nct
267
+ general: {
268
+ content: {
269
+ title: String,
270
+ singular: String,
271
+ ctaText: String,
272
+ listingDesc: String
273
+ },
274
+ allowQuickTagCreation: { enable: Boolean },
275
+ segment: String,
276
+ settingsUIStyle: String,
277
+ hasUpdateType: Boolean,
278
+ annotation: {
279
+ enable: Boolean
280
+ },
281
+ participantModule: {
282
+ enable: Boolean
283
+ },
284
+ formFieldNumbering: {
285
+ enable: Boolean
286
+ },
287
+ postPblRedirPath: Object,
288
+ templateIndex: Object,
289
+ sharing: {
290
+ enable: Boolean,
291
+ trackShareCount: {
292
+ type: Boolean,
293
+ default: false
294
+ }
295
+ },
296
+ viewsCount: {
297
+ enable: {
298
+ type: Boolean,
299
+ default: false
300
+ }
301
+ },
302
+ comments: {
303
+ enable: Boolean
304
+ },
305
+ reactions: {
306
+ type: Map,
307
+ of: {
308
+ enable: Boolean,
309
+ icon: String
310
+ }
311
+ },
312
+ csvExport: {
313
+ enable: Boolean,
314
+ excludeFields: Array,
315
+ enableUpdateExport: Boolean,
316
+ fieldsToSortAtEnd: Array,
317
+ fetchBatches: {
318
+ enable: Boolean,
319
+ batchSize: Number
320
+ }
321
+ },
322
+ onboardingFlow: Object,
323
+ //only on profile tpls
324
+ selfServeSurveyConfig: Object,
325
+ //tci helpers - these exist only to show / not show certain UIs in the tci
326
+ disableKPSettings: Boolean
327
+ }
328
+ //general contenttype configs. mostly the stuff inside platformConfigs > contentTypes
329
+ }, {
330
+ toJSON: { virtuals: true },
331
+ // So `res.json()` and other `JSON.stringify()` functions include virtuals
332
+ toObject: { virtuals: true }
333
+ // So `toObject()` output includes virtuals
334
+ });
335
+ TplSchema.virtual("layout").get(function() {
336
+ return this.category;
337
+ });
338
+ Tpl_default = TplSchema;
339
+ }
340
+ });
341
+
342
+ // src/db/MongoConnector.js
343
+ var require_MongoConnector = __commonJS({
344
+ "src/db/MongoConnector.js"(exports, module) {
345
+ "use strict";
346
+ var mongoose5 = __require("mongoose");
347
+ var AnnotationsSchema = (init_Annotations(), __toCommonJS(Annotations_exports));
348
+ var PlatformConfigsSchema2 = (init_PlatformConfigs(), __toCommonJS(PlatformConfigs_exports));
349
+ var TplSchema2 = (init_Tpl(), __toCommonJS(Tpl_exports));
350
+ var MongoConnector3 = class _MongoConnector {
351
+ constructor(options) {
352
+ this.clusterConnections = {};
353
+ this.env = options.env;
354
+ this.dbConfigs = options.dbConfigs;
355
+ this.mongoOptions = options.mongoOptions || {
356
+ maxPoolSize: 20,
357
+ serverSelectionTimeoutMS: 5e3,
358
+ socketTimeoutMS: 45e3,
359
+ family: 4
360
+ };
361
+ _MongoConnector.instance = this;
362
+ if (!this.env) {
363
+ throw new Error("Environment must be provided in constructor options");
364
+ }
365
+ if (!this.dbConfigs) {
366
+ throw new Error("dbConfigs must be provided in constructor options");
367
+ }
368
+ }
369
+ /**
370
+ * Creates multiple MongoDB clusterConnections based on configuration (SYNCHRONOUS)
371
+ * @returns Object containing named database clusterConnections
372
+ */
373
+ multiConnectToMongoDB() {
374
+ const { connectTo } = this.dbConfigs[this.env];
375
+ if (!connectTo) {
376
+ throw new Error(
377
+ `No connection configuration found for environment: ${this.env}`
378
+ );
379
+ }
380
+ connectTo.forEach((connectToEnv) => {
381
+ const { CLUSTER_NAME, DB_URI } = this.dbConfigs[connectToEnv];
382
+ if (!CLUSTER_NAME || !DB_URI) {
383
+ throw new Error(
384
+ `Missing CLUSTER_NAME or DB_URI for environment: ${connectToEnv}`
385
+ );
386
+ }
387
+ this.clusterConnections[CLUSTER_NAME] = mongoose5.createConnection(
388
+ DB_URI,
389
+ this.mongoOptions
390
+ );
391
+ this.clusterConnections[CLUSTER_NAME].on("open", () => {
392
+ console.log(`\u2705 Mongoose connection open to ${CLUSTER_NAME}`);
393
+ });
394
+ this.clusterConnections[CLUSTER_NAME].on("error", (err) => {
395
+ console.error(
396
+ `\u274C Mongoose connection error: ${err.message} with connection info ${CLUSTER_NAME}`
397
+ );
398
+ process.exit(1);
399
+ });
400
+ this.clusterConnections[CLUSTER_NAME].on("disconnected", () => {
401
+ console.log(`\u{1F50C} Mongoose disconnected from ${CLUSTER_NAME}`);
402
+ });
403
+ this.clusterConnections[CLUSTER_NAME].on("reconnected", () => {
404
+ console.log(`\u{1F504} Mongoose reconnected to ${CLUSTER_NAME}`);
405
+ });
406
+ });
407
+ console.log(
408
+ `\u{1F389} Connected to ${Object.keys(this.clusterConnections).length} MongoDB databases`
409
+ );
410
+ return this.clusterConnections;
411
+ }
412
+ async multiConnectToMongoDBAsync() {
413
+ const { connectTo } = this.dbConfigs[this.env];
414
+ if (!connectTo) {
415
+ throw new Error(
416
+ `No connection configuration found for environment: ${this.env}`
417
+ );
418
+ }
419
+ await Promise.all(
420
+ connectTo.map(async (connectToEnv) => {
421
+ const { CLUSTER_NAME, DB_URI } = this.dbConfigs[connectToEnv];
422
+ if (!CLUSTER_NAME || !DB_URI) {
423
+ throw new Error(
424
+ `Missing CLUSTER_NAME or DB_URI for environment: ${connectToEnv}`
425
+ );
426
+ }
427
+ this.clusterConnections[CLUSTER_NAME] = await mongoose5.createConnection(
428
+ DB_URI,
429
+ this.mongoOptions
430
+ );
431
+ console.log(`Connected to MongoDB: ${CLUSTER_NAME}`);
432
+ })
433
+ );
434
+ return this.clusterConnections;
435
+ }
436
+ // Static method to get the full instance
437
+ static getInstance() {
438
+ if (!_MongoConnector.instance) {
439
+ throw new Error("MongoConnector not initialized");
440
+ }
441
+ return _MongoConnector.instance;
442
+ }
443
+ // Static method to get connections
444
+ static getClusterConnections() {
445
+ if (!_MongoConnector.instance) {
446
+ throw new Error("MongoConnector not initialized");
447
+ }
448
+ return _MongoConnector.instance.clusterConnections;
449
+ }
450
+ // Static method to get environment
451
+ static getEnv() {
452
+ if (!_MongoConnector.instance) {
453
+ throw new Error("MongoConnector not initialized");
454
+ }
455
+ return _MongoConnector.instance.env;
456
+ }
457
+ // Static method to get db configs
458
+ static getDbConfigs() {
459
+ if (!_MongoConnector.instance) {
460
+ throw new Error("MongoConnector not initialized");
461
+ }
462
+ return _MongoConnector.instance.dbConfigs;
463
+ }
464
+ /**
465
+ * Helper function to close clusterConnections object
466
+ */
467
+ async closeConnectionsObject(clusterConnections) {
468
+ const closePromises = Object.entries(clusterConnections).map(
469
+ async ([clusterName, connection]) => {
470
+ try {
471
+ if (connection.readyState === 1) {
472
+ await connection.close();
473
+ console.log(`\u2705 Closed MongoDB connection: ${clusterName}`);
474
+ }
475
+ } catch (error) {
476
+ console.error(
477
+ `\u274C Error closing MongoDB connection ${clusterName}:`,
478
+ error
479
+ );
480
+ }
481
+ }
482
+ );
483
+ await Promise.all(closePromises);
484
+ }
485
+ /**
486
+ * Graceful shutdown - close all MongoDB clusterConnections
487
+ */
488
+ async closeAllConnections() {
489
+ if (Object.keys(this.clusterConnections).length === 0) {
490
+ console.log("No active MongoDB cluster connections to close");
491
+ return;
492
+ }
493
+ console.log("\u{1F6D1} Closing MongoDB cluster connections gracefully...");
494
+ await this.closeConnectionsObject(this.clusterConnections);
495
+ this.clusterConnections = {};
496
+ console.log("\u{1F389} All MongoDB clusterConnections closed gracefully");
497
+ }
498
+ };
499
+ MongoConnector3.instance = null;
500
+ module.exports = {
501
+ MongoConnector: MongoConnector3
502
+ };
503
+ }
504
+ });
505
+
506
+ // src/db/getDbByTenant.js
507
+ var getDbByTenant_exports = {};
508
+ __export(getDbByTenant_exports, {
509
+ getDbByTenant: () => getDbByTenant
510
+ });
511
+ import { Connection } from "mongoose";
512
+ var import_MongoConnector, getDbByTenant;
513
+ var init_getDbByTenant = __esm({
514
+ "src/db/getDbByTenant.js"() {
515
+ "use strict";
516
+ import_MongoConnector = __toESM(require_MongoConnector());
517
+ getDbByTenant = ({
518
+ tenant,
519
+ env: _env
520
+ }) => {
521
+ if (!tenant) throw new Error("tenant id has not been provided");
522
+ const env = _env || import_MongoConnector.MongoConnector.getEnv();
523
+ const dbConfigs = import_MongoConnector.MongoConnector.getDbConfigs();
524
+ const clusterConnections = import_MongoConnector.MongoConnector.getClusterConnections();
525
+ const { CLUSTER_NAME } = dbConfigs[env];
526
+ const dbName = `${tenant}_${env}`;
527
+ const connection = clusterConnections[CLUSTER_NAME];
528
+ if (!connection) {
529
+ throw new Error(`Connection not found for cluster: ${CLUSTER_NAME}`);
530
+ }
531
+ return connection.useDb(dbName, { useCache: true });
532
+ };
533
+ }
534
+ });
535
+
536
+ // src/models/AIChat.ts
537
+ import mongoose4 from "mongoose";
538
+ var AIChatSchema, AIChat_default;
539
+ var init_AIChat = __esm({
540
+ "src/models/AIChat.ts"() {
541
+ "use strict";
542
+ init_Annotations();
543
+ AIChatSchema = new mongoose4.Schema(
544
+ {
545
+ userId: { type: mongoose4.Schema.Types.ObjectId, index: { unique: true } },
546
+ createdAt: Date,
547
+ lastAcitivity: Date,
548
+ messages: [
549
+ {
550
+ id: String,
551
+ author: {
552
+ type: String,
553
+ enum: ["system", "user", "assistant"]
554
+ },
555
+ content: {
556
+ type: { type: String },
557
+ value: String
558
+ },
559
+ vectorSearchInfo: {
560
+ chunks: [Annotations_default]
561
+ },
562
+ args: {
563
+ query: String,
564
+ reframedQuery: String,
565
+ summary: Object
566
+ },
567
+ userFeedback: {
568
+ reaction: { type: String, enum: ["positive", "negative"] },
569
+ comments: String
570
+ }
571
+ }
572
+ ]
573
+ },
574
+ { collection: "aiChat" }
575
+ );
576
+ AIChat_default = AIChatSchema;
577
+ }
578
+ });
579
+
580
+ // src/models/index.ts
581
+ var models_exports = {};
582
+ __export(models_exports, {
583
+ AIChatSchema: () => AIChat_default,
584
+ AnnotationSchema: () => Annotations_default,
585
+ PlatformConfigsSchema: () => PlatformConfigs_default,
586
+ TplSchema: () => Tpl_default
587
+ });
588
+ var init_models = __esm({
589
+ "src/models/index.ts"() {
590
+ "use strict";
591
+ init_AIChat();
592
+ init_Annotations();
593
+ init_PlatformConfigs();
594
+ init_Tpl();
595
+ }
596
+ });
597
+
598
+ // src/db/getModelByTenant.js
599
+ var require_getModelByTenant = __commonJS({
600
+ "src/db/getModelByTenant.js"(exports, module) {
601
+ "use strict";
602
+ var { getDbByTenant: getDbByTenant2 } = (init_getDbByTenant(), __toCommonJS(getDbByTenant_exports));
603
+ var { AIChatSchema: AIChatSchema2, AnnotationSchema: AnnotationSchema2, PlatformConfigsSchema: PlatformConfigsSchema2, TplSchema: TplSchema2 } = (init_models(), __toCommonJS(models_exports));
604
+ var getModelByTenant2 = ({ tenant, modelName, schema, env }) => {
605
+ if (!tenant) {
606
+ throw new Error("tenant id has not been provided");
607
+ }
608
+ const db = getDbByTenant2({ tenant, env });
609
+ if (!Object.keys(db.models).includes(modelName)) {
610
+ return db.model(modelName, schema);
611
+ }
612
+ return db.model(modelName);
613
+ };
614
+ var getAnnotationsModelByTenant2 = ({ tenant, env, mongodb, dbConfigs, modelName }) => getModelByTenant2({
615
+ tenant,
616
+ modelName: modelName || "annotations",
617
+ schema: AnnotationSchema2,
618
+ env
619
+ });
620
+ var getPlatformConfigsModelByTenant2 = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant2({
621
+ tenant,
622
+ modelName: "platformConfigs",
623
+ schema: PlatformConfigsSchema2,
624
+ env
625
+ });
626
+ var getTplModelByTenant2 = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant2({
627
+ tenant,
628
+ modelName: "tpl",
629
+ schema: TplSchema2,
630
+ env
631
+ });
632
+ var getAIChatModelByTenant2 = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant2({
633
+ tenant,
634
+ modelName: "aiChat",
635
+ schema: AIChatSchema2,
636
+ env
637
+ });
638
+ module.exports = {
639
+ getModelByTenant: getModelByTenant2,
640
+ getAIChatModelByTenant: getAIChatModelByTenant2,
641
+ getAnnotationsModelByTenant: getAnnotationsModelByTenant2,
642
+ getPlatformConfigsModelByTenant: getPlatformConfigsModelByTenant2,
643
+ getTplModelByTenant: getTplModelByTenant2
644
+ };
645
+ }
646
+ });
647
+
41
648
  // src/bullmq/WorkerManager.js
42
649
  var require_WorkerManager = __commonJS({
43
650
  "src/bullmq/WorkerManager.js"(exports, module) {
@@ -277,8 +884,32 @@ var init_GLOBAL_BULLMQ_CONFIG = __esm({
277
884
  }
278
885
  },
279
886
  // Chunk Processing Queue
280
- CHUNK_PROCESSING_QUEUE: {
281
- id: "chunk-processing-queue",
887
+ CREATE_CHUNKS_QUEUE: {
888
+ id: "create-chunks-queue",
889
+ queueConfig: {
890
+ defaultJobOptions: {
891
+ backoff: {
892
+ type: "exponential",
893
+ delay: 2e3
894
+ },
895
+ attempts: 3,
896
+ removeOnComplete: 100,
897
+ removeOnFail: 50
898
+ }
899
+ },
900
+ workerConfig: {
901
+ concurrency: 10,
902
+ // Process 10 jobs at once for chunk processing
903
+ limiter: {
904
+ max: 5,
905
+ // Max 50 jobs per...
906
+ duration: 6e4
907
+ // ...60 seconds (higher throughput for chunking)
908
+ }
909
+ }
910
+ },
911
+ CREATE_ANNOS_QUEUE: {
912
+ id: "create-annos-queue",
282
913
  queueConfig: {
283
914
  defaultJobOptions: {
284
915
  backoff: {
@@ -614,18 +1245,12 @@ var _extractBlocksFromSomeBuilders = ({
614
1245
  }
615
1246
  };
616
1247
 
617
- // src/db/mongodb.ts
618
- import mongoose from "mongoose";
1248
+ // src/node.ts
1249
+ var import_MongoConnector2 = __toESM(require_MongoConnector());
1250
+ init_getDbByTenant();
619
1251
 
620
1252
  // src/db/getGlobalConfig.ts
621
1253
  var globalConfig = {};
622
- var getGlobalConfig = () => {
623
- return {
624
- env: globalConfig.env,
625
- dbConfigs: globalConfig.dbConfigs ? { ...globalConfig.dbConfigs } : void 0,
626
- mongodb: globalConfig.mongodb ? { ...globalConfig.mongodb } : void 0
627
- };
628
- };
629
1254
  var initializeGlobalConfig = (config) => {
630
1255
  globalConfig = {
631
1256
  env: config.env,
@@ -645,429 +1270,11 @@ var updateGlobalConfig = (updates) => {
645
1270
  console.log("Global config updated:", Object.keys(updates));
646
1271
  };
647
1272
 
648
- // src/db/mongodb.ts
649
- var mongoOptions = {
650
- // Note: These legacy options are no longer needed in newer versions of mongoose
651
- // useUnifiedTopology, useNewUrlParser, useCreateIndex, useFindAndModify are deprecated
652
- maxPoolSize: 20
653
- // replaces poolSize
654
- };
655
- var multiConnectToMongoDB = ({ env, dbConfigs } = {}) => {
656
- const globalConfig2 = getGlobalConfig();
657
- const actualEnv = env || globalConfig2.env;
658
- const actualDbConfigs = dbConfigs || globalConfig2.dbConfigs;
659
- if (!actualEnv) {
660
- throw new Error("Environment not provided and not found in global config");
661
- }
662
- if (!actualDbConfigs) {
663
- throw new Error("dbConfigs not provided and not found in global config");
664
- }
665
- const { connectTo } = actualDbConfigs[actualEnv];
666
- if (!connectTo) {
667
- throw new Error(`No connection configuration found for environment: ${actualEnv}`);
668
- }
669
- const dbConnections = {};
670
- connectTo.forEach((connectToEnv) => {
671
- const { CLUSTER_NAME, DB_URI } = actualDbConfigs[connectToEnv];
672
- if (!CLUSTER_NAME || !DB_URI) {
673
- throw new Error(`Missing CLUSTER_NAME or DB_URI for environment: ${connectToEnv}`);
674
- }
675
- dbConnections[CLUSTER_NAME] = mongoose.createConnection(DB_URI, mongoOptions);
676
- dbConnections[CLUSTER_NAME].on("open", () => {
677
- console.log(`Mongoose connection open to ${CLUSTER_NAME}`);
678
- });
679
- dbConnections[CLUSTER_NAME].on("error", (err) => {
680
- console.log(`Mongoose connection error: ${err.message} with connection info ${CLUSTER_NAME}`);
681
- process.exit(1);
682
- });
683
- });
684
- return dbConnections;
685
- };
686
-
687
- // src/db/getDbByTenant.ts
688
- var getDbByTenant = ({
689
- tenant,
690
- env
691
- }) => {
692
- if (!tenant) throw new Error("tenant id has not been provided");
693
- const globalConfig2 = getGlobalConfig();
694
- const actualEnv = env || globalConfig2.env;
695
- const dbConfigs = globalConfig2.dbConfigs;
696
- const mongodb = globalConfig2.mongodb;
697
- if (!dbConfigs) {
698
- throw new Error("dbConfigs not found in global config");
699
- }
700
- if (!actualEnv) {
701
- throw new Error("env not provided and not found in global config");
702
- }
703
- const { CLUSTER_NAME } = dbConfigs[actualEnv];
704
- const dbName = `${tenant}_${actualEnv}`;
705
- if (mongodb) {
706
- const db = mongodb[CLUSTER_NAME].useDb(dbName, { useCache: true });
707
- return db;
708
- }
709
- throw new Error("getDbByTenant : mongodb object doesnt exist");
710
- };
711
-
712
- // src/models/AIChat.ts
713
- import mongoose3 from "mongoose";
714
-
715
- // src/models/Annotations.ts
716
- import { Schema } from "mongoose";
717
- var AnnotationSchema = new Schema(
718
- {
719
- // Tags section - dynamic structure for various tag categories
720
- tags: {
721
- type: Map,
722
- of: new Schema({
723
- data: [
724
- {
725
- _id: { type: Schema.Types.ObjectId },
726
- display: String,
727
- tagId: String
728
- }
729
- ],
730
- collectionId: String
731
- }, {
732
- _id: false
733
- })
734
- },
735
- // Meta information
736
- meta: {
737
- contentType: { type: String, required: true },
738
- kp_contributed_by: {
739
- type: Schema.Types.ObjectId,
740
- ref: "user"
741
- },
742
- valuePath: String,
743
- documentId: {
744
- type: Schema.Types.ObjectId
745
- }
746
- },
747
- // Main content data - using Schema.Types.Mixed for dynamic structure
748
- main: {
749
- type: Schema.Types.Mixed,
750
- default: {}
751
- },
752
- // Annotation specific details
753
- annotations: {
754
- tags: {
755
- type: Map,
756
- of: new Schema({
757
- collectionId: String,
758
- data: [
759
- {
760
- _id: { type: Schema.Types.ObjectId },
761
- display: String,
762
- tagId: String
763
- }
764
- ]
765
- }, {
766
- _id: false
767
- })
768
- },
769
- fragment: {
770
- isLexical: Boolean,
771
- editorState: Object,
772
- allText: String
773
- },
774
- annoKey: String,
775
- author: {
776
- id: { type: Schema.Types.ObjectId },
777
- name: String
778
- }
779
- },
780
- embeddings: Array,
781
- contentEnhancedText: String,
782
- // // Optional chunk related fields
783
- // chunk: {
784
- // embeddings: Schema.Types.Mixed,
785
- // contentEnhancedText: String
786
- // },
787
- clusterId: String,
788
- kp_date_published: Date,
789
- createdAt: {
790
- type: Date,
791
- default: Date.now
792
- },
793
- updatedAt: {
794
- type: Date,
795
- default: Date.now
796
- },
797
- topicId: [{ type: Schema.Types.ObjectId, ref: "generatedTopics" }],
798
- translations: Object
799
- },
800
- {
801
- timestamps: true,
802
- toJSON: { virtuals: true },
803
- toObject: { virtuals: true },
804
- strict: false
805
- // This allows for flexible document structure beyond the defined schema
806
- }
807
- );
808
- AnnotationSchema.index({ "meta.contentType": 1 });
809
- AnnotationSchema.index({ "meta.documentId": 1 });
810
- AnnotationSchema.index({ createdAt: -1 });
811
- AnnotationSchema.index({ "annotations.annoKey": 1 });
812
- AnnotationSchema.index({ "kp_date_published": -1 });
813
- AnnotationSchema.pre("save", function(next) {
814
- this.updatedAt = /* @__PURE__ */ new Date();
815
- next();
816
- });
817
- AnnotationSchema.methods.getMainField = function(fieldPath) {
818
- if (!fieldPath) return null;
819
- const parts = fieldPath.split(".");
820
- let value = this.main;
821
- for (const part of parts) {
822
- if (!value || typeof value !== "object") return null;
823
- value = value[part];
824
- }
825
- return value;
826
- };
827
- AnnotationSchema.virtual("displayTitle").get(function() {
828
- return this.main?.title || "Untitled Annotation";
829
- });
830
- var Annotations_default = AnnotationSchema;
831
-
832
- // src/models/AIChat.ts
833
- var AIChatSchema = new mongoose3.Schema(
834
- {
835
- userId: { type: mongoose3.Schema.Types.ObjectId, index: { unique: true } },
836
- createdAt: Date,
837
- lastAcitivity: Date,
838
- messages: [
839
- {
840
- id: String,
841
- author: {
842
- type: String,
843
- enum: ["system", "user", "assistant"]
844
- },
845
- content: {
846
- type: { type: String },
847
- value: String
848
- },
849
- vectorSearchInfo: {
850
- chunks: [Annotations_default]
851
- },
852
- args: {
853
- query: String,
854
- reframedQuery: String,
855
- summary: Object
856
- },
857
- userFeedback: {
858
- reaction: { type: String, enum: ["positive", "negative"] },
859
- comments: String
860
- }
861
- }
862
- ]
863
- },
864
- { collection: "aiChat" }
865
- );
866
- var AIChat_default = AIChatSchema;
867
-
868
- // src/models/PlatformConfigs.ts
869
- import mongoose4 from "mongoose";
870
- var platformConfigTypes = [
871
- "roles",
872
- "nav",
873
- "deployment",
874
- "userAgreement",
875
- "localeData",
876
- "theme",
877
- "AI"
878
- ];
879
- var PlatformConfigsSchema = new mongoose4.Schema(
880
- {
881
- type: {
882
- type: String,
883
- enum: platformConfigTypes,
884
- unique: true
885
- },
886
- roles: Array,
887
- data: Object
888
- },
889
- { collection: "platformConfigs" }
890
- );
891
- var PlatformConfigs_default = PlatformConfigsSchema;
892
-
893
- // src/models/Tpl.ts
894
- import mongoose5 from "mongoose";
895
- var TplSchema = new mongoose5.Schema({
896
- dateFirstPublished: Date,
897
- dateCreated: Date,
898
- dateLastPublished: Date,
899
- dateLastEdited: Date,
900
- status: {
901
- type: String,
902
- default: "published",
903
- // only cuz we dont want to go and add this property in all databases
904
- enum: ["unpublished", "editPublished", "published"]
905
- },
906
- version: {
907
- type: Number,
908
- default: 0
909
- },
910
- versionPublishedBy: {
911
- type: mongoose5.Schema.Types.ObjectId,
912
- ref: "user"
913
- // reference to the 'user' model
914
- },
915
- firstPublishedBy: {
916
- type: mongoose5.Schema.Types.ObjectId,
917
- ref: "user"
918
- // reference to the 'user' model
919
- },
920
- kp_content_type: {
921
- type: String,
922
- required: true,
923
- unique: true
924
- },
925
- category: {
926
- //to deprecate and turn into 'layout'
927
- type: String,
928
- default: "knowledgeResources2"
929
- },
930
- kp_settings: [
931
- {
932
- type: Object
933
- }
934
- ],
935
- kp_templates: {
936
- type: Object
937
- },
938
- tplMeta: Object,
939
- tplLocales: Object,
940
- indexed: Object,
941
- drafts: {
942
- active: Object
943
- },
944
- rollbacks: Object,
945
- //for 'remembering' hidden configurations
946
- // OTHER CONFIGS
947
- listing: Object,
948
- //listing page configurations. this is new, currently only used in nct
949
- general: {
950
- content: {
951
- title: String,
952
- singular: String,
953
- ctaText: String,
954
- listingDesc: String
955
- },
956
- allowQuickTagCreation: { enable: Boolean },
957
- segment: String,
958
- settingsUIStyle: String,
959
- hasUpdateType: Boolean,
960
- annotation: {
961
- enable: Boolean
962
- },
963
- participantModule: {
964
- enable: Boolean
965
- },
966
- formFieldNumbering: {
967
- enable: Boolean
968
- },
969
- postPblRedirPath: Object,
970
- templateIndex: Object,
971
- sharing: {
972
- enable: Boolean,
973
- trackShareCount: {
974
- type: Boolean,
975
- default: false
976
- }
977
- },
978
- viewsCount: {
979
- enable: {
980
- type: Boolean,
981
- default: false
982
- }
983
- },
984
- comments: {
985
- enable: Boolean
986
- },
987
- reactions: {
988
- type: Map,
989
- of: {
990
- enable: Boolean,
991
- icon: String
992
- }
993
- },
994
- csvExport: {
995
- enable: Boolean,
996
- excludeFields: Array,
997
- enableUpdateExport: Boolean,
998
- fieldsToSortAtEnd: Array,
999
- fetchBatches: {
1000
- enable: Boolean,
1001
- batchSize: Number
1002
- }
1003
- },
1004
- onboardingFlow: Object,
1005
- //only on profile tpls
1006
- selfServeSurveyConfig: Object,
1007
- //tci helpers - these exist only to show / not show certain UIs in the tci
1008
- disableKPSettings: Boolean
1009
- }
1010
- //general contenttype configs. mostly the stuff inside platformConfigs > contentTypes
1011
- }, {
1012
- toJSON: { virtuals: true },
1013
- // So `res.json()` and other `JSON.stringify()` functions include virtuals
1014
- toObject: { virtuals: true }
1015
- // So `toObject()` output includes virtuals
1016
- });
1017
- TplSchema.virtual("layout").get(function() {
1018
- return this.category;
1019
- });
1020
- var Tpl_default = TplSchema;
1273
+ // src/node.ts
1274
+ var import_getModelByTenant = __toESM(require_getModelByTenant());
1021
1275
 
1022
- // src/db/getModelByTenant.ts
1023
- var getModelByTenant = ({
1024
- tenant,
1025
- modelName,
1026
- schema,
1027
- env
1028
- }) => {
1029
- if (!tenant) {
1030
- throw new Error("tenant id has not been provided");
1031
- }
1032
- const db = getDbByTenant({
1033
- tenant,
1034
- env
1035
- });
1036
- if (!Object.keys(db.models).includes(modelName)) {
1037
- return db.model(modelName, schema);
1038
- }
1039
- return db.model(modelName);
1040
- };
1041
- var getAnnotationsModelByTenant = ({ tenant, env, mongodb, dbConfigs, modelName }) => getModelByTenant({
1042
- tenant,
1043
- modelName: modelName || "annotations",
1044
- schema: Annotations_default,
1045
- env
1046
- });
1047
- var getChunksModelByTenant = ({ tenant, env, mongodb, dbConfigs, modelName }) => getModelByTenant({
1048
- tenant,
1049
- modelName: modelName || "chunks",
1050
- schema: Annotations_default,
1051
- env
1052
- });
1053
- var getPlatformConfigsModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
1054
- tenant,
1055
- modelName: "platformConfigs",
1056
- schema: PlatformConfigs_default,
1057
- env
1058
- });
1059
- var getTplModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
1060
- tenant,
1061
- modelName: "tpl",
1062
- schema: Tpl_default,
1063
- env
1064
- });
1065
- var getAIChatModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
1066
- tenant,
1067
- modelName: "aiChat",
1068
- schema: AIChat_default,
1069
- env
1070
- });
1276
+ // src/redis/functions.ts
1277
+ init_getDbByTenant();
1071
1278
 
1072
1279
  // src/redis/index.ts
1073
1280
  import IORedis from "ioredis";
@@ -1177,6 +1384,7 @@ var getAIConfigs = async ({
1177
1384
  };
1178
1385
 
1179
1386
  // src/node.ts
1387
+ init_models();
1180
1388
  var import_WorkerManager = __toESM(require_WorkerManager());
1181
1389
  var import_BaseProducer = __toESM(require_BaseProducer());
1182
1390
  var import_BaseWorker = __toESM(require_BaseWorker());
@@ -1184,13 +1392,20 @@ var import_GET_GLOBAL_BULLMQ_CONFIG = __toESM(require_GET_GLOBAL_BULLMQ_CONFIG()
1184
1392
  var export_BaseProducer = import_BaseProducer.BaseProducer;
1185
1393
  var export_BaseWorker = import_BaseWorker.BaseWorker;
1186
1394
  var export_GET_GLOBAL_BULLMQ_CONFIG = import_GET_GLOBAL_BULLMQ_CONFIG.GET_GLOBAL_BULLMQ_CONFIG;
1395
+ var export_MongoConnector = import_MongoConnector2.MongoConnector;
1187
1396
  var export_WorkerManager = import_WorkerManager.WorkerManager;
1397
+ var export_getAIChatModelByTenant = import_getModelByTenant.getAIChatModelByTenant;
1398
+ var export_getAnnotationsModelByTenant = import_getModelByTenant.getAnnotationsModelByTenant;
1399
+ var export_getModelByTenant = import_getModelByTenant.getModelByTenant;
1400
+ var export_getPlatformConfigsModelByTenant = import_getModelByTenant.getPlatformConfigsModelByTenant;
1401
+ var export_getTplModelByTenant = import_getModelByTenant.getTplModelByTenant;
1188
1402
  export {
1189
1403
  AIChat_default as AIChatSchema,
1190
1404
  Annotations_default as AnnotationSchema,
1191
1405
  export_BaseProducer as BaseProducer,
1192
1406
  export_BaseWorker as BaseWorker,
1193
1407
  export_GET_GLOBAL_BULLMQ_CONFIG as GET_GLOBAL_BULLMQ_CONFIG,
1408
+ export_MongoConnector as MongoConnector,
1194
1409
  PlatformConfigs_default as PlatformConfigsSchema,
1195
1410
  Tpl_default as TplSchema,
1196
1411
  export_WorkerManager as WorkerManager,
@@ -1198,19 +1413,17 @@ export {
1198
1413
  deleteVal,
1199
1414
  extractAllBlocksFromTpl,
1200
1415
  genTagId,
1201
- getAIChatModelByTenant,
1416
+ export_getAIChatModelByTenant as getAIChatModelByTenant,
1202
1417
  getAIConfigs,
1203
- getAnnotationsModelByTenant,
1204
- getChunksModelByTenant,
1418
+ export_getAnnotationsModelByTenant as getAnnotationsModelByTenant,
1205
1419
  getDbByTenant,
1206
- getModelByTenant,
1207
- getPlatformConfigsModelByTenant,
1420
+ export_getModelByTenant as getModelByTenant,
1421
+ export_getPlatformConfigsModelByTenant as getPlatformConfigsModelByTenant,
1208
1422
  getRedisClient,
1209
1423
  getTpl,
1210
- getTplModelByTenant,
1424
+ export_getTplModelByTenant as getTplModelByTenant,
1211
1425
  getVal,
1212
1426
  initializeGlobalConfig,
1213
- multiConnectToMongoDB,
1214
1427
  _recursExtractBlocks as recursivelyExtractBlocks,
1215
1428
  setVal,
1216
1429
  toArray,