@okf/ootils 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,113 @@
1
+ import { Connection, Document, Schema, Model } from 'mongoose';
2
+
1
3
  declare function add(a: number, b: number): number;
2
4
 
5
+ interface DbConnections {
6
+ [clusterName: string]: Connection;
7
+ }
8
+ interface DatabaseConfig {
9
+ connectTo: string[];
10
+ CLUSTER_NAME: string;
11
+ DB_URI: string;
12
+ }
13
+ interface DbConfigs {
14
+ [env: string]: DatabaseConfig;
15
+ }
16
+ interface MultiConnectParams {
17
+ env?: string;
18
+ dbConfigs?: DbConfigs;
19
+ }
20
+ /**
21
+ * Creates multiple MongoDB connections based on environment configuration
22
+ * @param params - Object containing env and dbConfigs (optional, uses global config if not provided)
23
+ * @param params.env - Environment string (e.g., 'development', 'production', 'staging')
24
+ * @param params.dbConfigs - Database configuration object
25
+ * @returns Object containing named database connections
26
+ */
27
+ declare const multiConnectToMongoDB: ({ env, dbConfigs }?: MultiConnectParams) => DbConnections;
28
+
29
+ /**
30
+ * passing env is optional.
31
+ * cuz it usually defaults to 'this env' provided by .env file.
32
+ *
33
+ * However, in some cases where we are syncing tpls &
34
+ * configs across envs, we need to be able to specify env
35
+ * as well
36
+ */
37
+ declare const getDbByTenant: ({ tenant, env }: {
38
+ tenant: string;
39
+ env?: string;
40
+ }) => Connection;
41
+
42
+ interface GlobalConfigType {
43
+ env?: string;
44
+ dbConfigs?: {
45
+ [env: string]: {
46
+ CLUSTER_NAME: string;
47
+ DB_URI: string;
48
+ connectTo?: string[];
49
+ };
50
+ };
51
+ mongodb?: {
52
+ [clusterName: string]: Connection;
53
+ };
54
+ }
55
+ /**
56
+ * Initialize the global configuration (replaces entire config)
57
+ */
58
+ declare const initializeGlobalConfig: (config: GlobalConfigType) => void;
59
+ /**
60
+ * Update specific parts of the global configuration (merges with existing)
61
+ */
62
+ declare const updateGlobalConfig: (updates: Partial<GlobalConfigType>) => void;
63
+
64
+ interface GetModelByTenantParams {
65
+ tenant: string;
66
+ modelName: string;
67
+ schema: Schema;
68
+ env?: string;
69
+ mongodb?: {
70
+ [clusterName: string]: Connection;
71
+ };
72
+ dbConfigs?: {
73
+ [env: string]: {
74
+ CLUSTER_NAME: string;
75
+ DB_URI: string;
76
+ connectTo?: string[];
77
+ };
78
+ };
79
+ }
80
+ interface GetModelShortParams {
81
+ tenant: string;
82
+ env?: string;
83
+ mongodb?: {
84
+ [clusterName: string]: Connection;
85
+ };
86
+ dbConfigs?: {
87
+ [env: string]: {
88
+ CLUSTER_NAME: string;
89
+ DB_URI: string;
90
+ connectTo?: string[];
91
+ };
92
+ };
93
+ }
94
+ declare const getModelByTenant: <T extends Document = Document>({ tenant, modelName, schema, env, }: GetModelByTenantParams) => Model<T>;
95
+ declare const getAnnotationsModelByTenant: ({ tenant, env, mongodb, dbConfigs }: GetModelShortParams) => Model<Document<unknown, any, any, Record<string, any>>, {}, {}, {}, Document<unknown, {}, Document<unknown, any, any, Record<string, any>>, {}> & Document<unknown, any, any, Record<string, any>> & Required<{
96
+ _id: unknown;
97
+ }> & {
98
+ __v: number;
99
+ }, any>;
100
+ declare const getPlatformConfigsModelByTenant: ({ tenant, env, mongodb, dbConfigs }: GetModelShortParams) => Model<Document<unknown, any, any, Record<string, any>>, {}, {}, {}, Document<unknown, {}, Document<unknown, any, any, Record<string, any>>, {}> & Document<unknown, any, any, Record<string, any>> & Required<{
101
+ _id: unknown;
102
+ }> & {
103
+ __v: number;
104
+ }, any>;
105
+ declare const getTplModelByTenant: ({ tenant, env, mongodb, dbConfigs }: GetModelShortParams) => Model<Document<unknown, any, any, Record<string, any>>, {}, {}, {}, Document<unknown, {}, Document<unknown, any, any, Record<string, any>>, {}> & Document<unknown, any, any, Record<string, any>> & Required<{
106
+ _id: unknown;
107
+ }> & {
108
+ __v: number;
109
+ }, any>;
110
+
3
111
  declare const deleteVal: (data: any, valuePath: string) => any;
4
112
 
5
113
  type ValuePath = string | string[];
@@ -22,4 +130,4 @@ declare const setVal: (data: any, valuePath: string, value: DataValue) => any;
22
130
  */
23
131
  declare const getVal: (data: any, valuePath: ValuePath, options?: GetValOptions, depthIdx?: number) => any;
24
132
 
25
- export { add, deleteVal, getVal, setVal };
133
+ export { add, deleteVal, getAnnotationsModelByTenant, getDbByTenant, getModelByTenant, getPlatformConfigsModelByTenant, getTplModelByTenant, getVal, initializeGlobalConfig, multiConnectToMongoDB, setVal, updateGlobalConfig };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,113 @@
1
+ import { Connection, Document, Schema, Model } from 'mongoose';
2
+
1
3
  declare function add(a: number, b: number): number;
2
4
 
5
+ interface DbConnections {
6
+ [clusterName: string]: Connection;
7
+ }
8
+ interface DatabaseConfig {
9
+ connectTo: string[];
10
+ CLUSTER_NAME: string;
11
+ DB_URI: string;
12
+ }
13
+ interface DbConfigs {
14
+ [env: string]: DatabaseConfig;
15
+ }
16
+ interface MultiConnectParams {
17
+ env?: string;
18
+ dbConfigs?: DbConfigs;
19
+ }
20
+ /**
21
+ * Creates multiple MongoDB connections based on environment configuration
22
+ * @param params - Object containing env and dbConfigs (optional, uses global config if not provided)
23
+ * @param params.env - Environment string (e.g., 'development', 'production', 'staging')
24
+ * @param params.dbConfigs - Database configuration object
25
+ * @returns Object containing named database connections
26
+ */
27
+ declare const multiConnectToMongoDB: ({ env, dbConfigs }?: MultiConnectParams) => DbConnections;
28
+
29
+ /**
30
+ * passing env is optional.
31
+ * cuz it usually defaults to 'this env' provided by .env file.
32
+ *
33
+ * However, in some cases where we are syncing tpls &
34
+ * configs across envs, we need to be able to specify env
35
+ * as well
36
+ */
37
+ declare const getDbByTenant: ({ tenant, env }: {
38
+ tenant: string;
39
+ env?: string;
40
+ }) => Connection;
41
+
42
+ interface GlobalConfigType {
43
+ env?: string;
44
+ dbConfigs?: {
45
+ [env: string]: {
46
+ CLUSTER_NAME: string;
47
+ DB_URI: string;
48
+ connectTo?: string[];
49
+ };
50
+ };
51
+ mongodb?: {
52
+ [clusterName: string]: Connection;
53
+ };
54
+ }
55
+ /**
56
+ * Initialize the global configuration (replaces entire config)
57
+ */
58
+ declare const initializeGlobalConfig: (config: GlobalConfigType) => void;
59
+ /**
60
+ * Update specific parts of the global configuration (merges with existing)
61
+ */
62
+ declare const updateGlobalConfig: (updates: Partial<GlobalConfigType>) => void;
63
+
64
+ interface GetModelByTenantParams {
65
+ tenant: string;
66
+ modelName: string;
67
+ schema: Schema;
68
+ env?: string;
69
+ mongodb?: {
70
+ [clusterName: string]: Connection;
71
+ };
72
+ dbConfigs?: {
73
+ [env: string]: {
74
+ CLUSTER_NAME: string;
75
+ DB_URI: string;
76
+ connectTo?: string[];
77
+ };
78
+ };
79
+ }
80
+ interface GetModelShortParams {
81
+ tenant: string;
82
+ env?: string;
83
+ mongodb?: {
84
+ [clusterName: string]: Connection;
85
+ };
86
+ dbConfigs?: {
87
+ [env: string]: {
88
+ CLUSTER_NAME: string;
89
+ DB_URI: string;
90
+ connectTo?: string[];
91
+ };
92
+ };
93
+ }
94
+ declare const getModelByTenant: <T extends Document = Document>({ tenant, modelName, schema, env, }: GetModelByTenantParams) => Model<T>;
95
+ declare const getAnnotationsModelByTenant: ({ tenant, env, mongodb, dbConfigs }: GetModelShortParams) => Model<Document<unknown, any, any, Record<string, any>>, {}, {}, {}, Document<unknown, {}, Document<unknown, any, any, Record<string, any>>, {}> & Document<unknown, any, any, Record<string, any>> & Required<{
96
+ _id: unknown;
97
+ }> & {
98
+ __v: number;
99
+ }, any>;
100
+ declare const getPlatformConfigsModelByTenant: ({ tenant, env, mongodb, dbConfigs }: GetModelShortParams) => Model<Document<unknown, any, any, Record<string, any>>, {}, {}, {}, Document<unknown, {}, Document<unknown, any, any, Record<string, any>>, {}> & Document<unknown, any, any, Record<string, any>> & Required<{
101
+ _id: unknown;
102
+ }> & {
103
+ __v: number;
104
+ }, any>;
105
+ declare const getTplModelByTenant: ({ tenant, env, mongodb, dbConfigs }: GetModelShortParams) => Model<Document<unknown, any, any, Record<string, any>>, {}, {}, {}, Document<unknown, {}, Document<unknown, any, any, Record<string, any>>, {}> & Document<unknown, any, any, Record<string, any>> & Required<{
106
+ _id: unknown;
107
+ }> & {
108
+ __v: number;
109
+ }, any>;
110
+
3
111
  declare const deleteVal: (data: any, valuePath: string) => any;
4
112
 
5
113
  type ValuePath = string | string[];
@@ -22,4 +130,4 @@ declare const setVal: (data: any, valuePath: string, value: DataValue) => any;
22
130
  */
23
131
  declare const getVal: (data: any, valuePath: ValuePath, options?: GetValOptions, depthIdx?: number) => any;
24
132
 
25
- export { add, deleteVal, getVal, setVal };
133
+ export { add, deleteVal, getAnnotationsModelByTenant, getDbByTenant, getModelByTenant, getPlatformConfigsModelByTenant, getTplModelByTenant, getVal, initializeGlobalConfig, multiConnectToMongoDB, setVal, updateGlobalConfig };
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,313 @@ 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,
24
319
  deleteVal: () => deleteVal,
320
+ getAnnotationsModelByTenant: () => getAnnotationsModelByTenant,
321
+ getDbByTenant: () => getDbByTenant,
322
+ getModelByTenant: () => getModelByTenant,
323
+ getPlatformConfigsModelByTenant: () => getPlatformConfigsModelByTenant,
324
+ getTplModelByTenant: () => getTplModelByTenant,
25
325
  getVal: () => getVal,
26
- setVal: () => setVal
326
+ initializeGlobalConfig: () => initializeGlobalConfig,
327
+ multiConnectToMongoDB: () => multiConnectToMongoDB,
328
+ setVal: () => setVal,
329
+ updateGlobalConfig: () => updateGlobalConfig
27
330
  });
28
331
  module.exports = __toCommonJS(index_exports);
29
332
 
@@ -32,6 +335,142 @@ function add(a, b) {
32
335
  return a + b;
33
336
  }
34
337
 
338
+ // src/db/mongodb.ts
339
+ var import_mongoose = __toESM(require("mongoose"));
340
+
341
+ // src/db/getGlobalConfig.ts
342
+ var globalConfig = {};
343
+ var getGlobalConfig = () => {
344
+ return {
345
+ env: globalConfig.env,
346
+ dbConfigs: globalConfig.dbConfigs ? { ...globalConfig.dbConfigs } : void 0,
347
+ mongodb: globalConfig.mongodb ? { ...globalConfig.mongodb } : void 0
348
+ };
349
+ };
350
+ var initializeGlobalConfig = (config) => {
351
+ globalConfig = {
352
+ env: config.env,
353
+ dbConfigs: config.dbConfigs ? { ...config.dbConfigs } : void 0,
354
+ mongodb: config.mongodb ? { ...config.mongodb } : void 0
355
+ };
356
+ console.log(`Global config initialized for environment: ${config.env}`);
357
+ };
358
+ var updateGlobalConfig = (updates) => {
359
+ globalConfig = {
360
+ ...globalConfig,
361
+ ...updates,
362
+ // Handle nested objects properly
363
+ dbConfigs: updates.dbConfigs ? { ...globalConfig.dbConfigs, ...updates.dbConfigs } : globalConfig.dbConfigs,
364
+ mongodb: updates.mongodb ? { ...globalConfig.mongodb, ...updates.mongodb } : globalConfig.mongodb
365
+ };
366
+ console.log("Global config updated:", Object.keys(updates));
367
+ };
368
+
369
+ // src/db/mongodb.ts
370
+ var mongoOptions = {
371
+ // Note: These legacy options are no longer needed in newer versions of mongoose
372
+ // useUnifiedTopology, useNewUrlParser, useCreateIndex, useFindAndModify are deprecated
373
+ maxPoolSize: 10
374
+ // replaces poolSize
375
+ };
376
+ var multiConnectToMongoDB = ({ env, dbConfigs } = {}) => {
377
+ const globalConfig2 = getGlobalConfig();
378
+ const actualEnv = env || globalConfig2.env;
379
+ const actualDbConfigs = dbConfigs || globalConfig2.dbConfigs;
380
+ if (!actualEnv) {
381
+ throw new Error("Environment not provided and not found in global config");
382
+ }
383
+ if (!actualDbConfigs) {
384
+ throw new Error("dbConfigs not provided and not found in global config");
385
+ }
386
+ const { connectTo } = actualDbConfigs[actualEnv];
387
+ if (!connectTo) {
388
+ throw new Error(`No connection configuration found for environment: ${actualEnv}`);
389
+ }
390
+ const dbConnections = {};
391
+ connectTo.forEach((connectToEnv) => {
392
+ const { CLUSTER_NAME, DB_URI } = actualDbConfigs[connectToEnv];
393
+ if (!CLUSTER_NAME || !DB_URI) {
394
+ throw new Error(`Missing CLUSTER_NAME or DB_URI for environment: ${connectToEnv}`);
395
+ }
396
+ dbConnections[CLUSTER_NAME] = import_mongoose.default.createConnection(DB_URI, mongoOptions);
397
+ dbConnections[CLUSTER_NAME].on("open", () => {
398
+ console.log(`Mongoose connection open to ${CLUSTER_NAME}`);
399
+ });
400
+ dbConnections[CLUSTER_NAME].on("error", (err) => {
401
+ console.log(`Mongoose connection error: ${err.message} with connection info ${CLUSTER_NAME}`);
402
+ process.exit(1);
403
+ });
404
+ });
405
+ return dbConnections;
406
+ };
407
+
408
+ // src/db/getDbByTenant.ts
409
+ var getDbByTenant = ({
410
+ tenant,
411
+ env
412
+ }) => {
413
+ if (!tenant) throw new Error("tenant id has not been provided");
414
+ const globalConfig2 = getGlobalConfig();
415
+ const actualEnv = env || globalConfig2.env;
416
+ const dbConfigs = globalConfig2.dbConfigs;
417
+ const mongodb = globalConfig2.mongodb;
418
+ if (!dbConfigs) {
419
+ throw new Error("dbConfigs not found in global config");
420
+ }
421
+ if (!actualEnv) {
422
+ throw new Error("env not provided and not found in global config");
423
+ }
424
+ const { CLUSTER_NAME } = dbConfigs[actualEnv];
425
+ const dbName = `${tenant}_${actualEnv}`;
426
+ if (mongodb) {
427
+ const db = mongodb[CLUSTER_NAME].useDb(dbName, { useCache: true });
428
+ return db;
429
+ }
430
+ throw new Error("getDbByTenant : mongodb object doesnt exist");
431
+ };
432
+
433
+ // src/db/getModelByTenant.ts
434
+ var AnnotationsSchema = require_Annotations();
435
+ var PlatformConfigsSchema = require_PlatformConfigs();
436
+ var TplSchema = require_Tpl();
437
+ var getModelByTenant = ({
438
+ tenant,
439
+ modelName,
440
+ schema,
441
+ env
442
+ }) => {
443
+ if (!tenant) {
444
+ throw new Error("tenant id has not been provided");
445
+ }
446
+ const db = getDbByTenant({
447
+ tenant,
448
+ env
449
+ });
450
+ if (!Object.keys(db.models).includes(modelName)) {
451
+ return db.model(modelName, schema);
452
+ }
453
+ return db.model(modelName);
454
+ };
455
+ var getAnnotationsModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
456
+ tenant,
457
+ modelName: "annotations",
458
+ schema: AnnotationsSchema,
459
+ env
460
+ });
461
+ var getPlatformConfigsModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
462
+ tenant,
463
+ modelName: "platformConfigs",
464
+ schema: PlatformConfigsSchema,
465
+ env
466
+ });
467
+ var getTplModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
468
+ tenant,
469
+ modelName: "tpl",
470
+ schema: TplSchema,
471
+ env
472
+ });
473
+
35
474
  // src/utils/getterSetterDeleter/utils/set_deleteVal.ts
36
475
  var set_deleteVal = (action, data, valuePath, value) => {
37
476
  if (valuePath === void 0) return;
@@ -166,6 +605,14 @@ var getValV2_getter = (data, valuePath, options, depthIdx) => {
166
605
  0 && (module.exports = {
167
606
  add,
168
607
  deleteVal,
608
+ getAnnotationsModelByTenant,
609
+ getDbByTenant,
610
+ getModelByTenant,
611
+ getPlatformConfigsModelByTenant,
612
+ getTplModelByTenant,
169
613
  getVal,
170
- setVal
614
+ initializeGlobalConfig,
615
+ multiConnectToMongoDB,
616
+ setVal,
617
+ updateGlobalConfig
171
618
  });
package/dist/index.mjs CHANGED
@@ -1,8 +1,437 @@
1
+ var __getOwnPropNames = Object.getOwnPropertyNames;
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+ var __commonJS = (cb, mod) => function __require2() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+
12
+ // src/models/Annotations.js
13
+ var require_Annotations = __commonJS({
14
+ "src/models/Annotations.js"(exports, module) {
15
+ "use strict";
16
+ var mongoose2 = __require("mongoose");
17
+ var Schema = mongoose2.Schema;
18
+ var AnnotationSchema = new Schema(
19
+ {
20
+ // Tags section - dynamic structure for various tag categories
21
+ tags: {
22
+ type: Map,
23
+ of: {
24
+ data: [
25
+ {
26
+ _id: { type: Schema.Types.ObjectId },
27
+ display: String,
28
+ tagId: String
29
+ }
30
+ ],
31
+ collectionId: String
32
+ }
33
+ },
34
+ // Meta information
35
+ meta: {
36
+ contentType: { type: String, required: true },
37
+ kp_contributed_by: {
38
+ type: Schema.Types.ObjectId,
39
+ ref: "user"
40
+ },
41
+ valuePath: String,
42
+ documentId: {
43
+ type: Schema.Types.ObjectId
44
+ }
45
+ },
46
+ // Main content data - using Schema.Types.Mixed for dynamic structure
47
+ main: {
48
+ type: Schema.Types.Mixed,
49
+ default: {}
50
+ },
51
+ // Annotation specific details
52
+ annotations: {
53
+ tags: {
54
+ type: Map,
55
+ of: {
56
+ collectionId: String,
57
+ data: [
58
+ {
59
+ _id: { type: Schema.Types.ObjectId },
60
+ display: String,
61
+ tagId: String
62
+ }
63
+ ]
64
+ }
65
+ },
66
+ fragment: {
67
+ isLexical: Boolean,
68
+ editorState: Object,
69
+ allText: String
70
+ },
71
+ annoKey: String,
72
+ author: {
73
+ id: { type: Schema.Types.ObjectId },
74
+ name: String
75
+ }
76
+ },
77
+ embeddings: Array,
78
+ contentEnhancedText: String,
79
+ // // Optional chunk related fields
80
+ // chunk: {
81
+ // embeddings: Schema.Types.Mixed,
82
+ // contentEnhancedText: String
83
+ // },
84
+ clusterId: String,
85
+ kp_date_published: Date,
86
+ createdAt: {
87
+ type: Date,
88
+ default: Date.now
89
+ },
90
+ updatedAt: {
91
+ type: Date,
92
+ default: Date.now
93
+ },
94
+ translations: Object
95
+ },
96
+ {
97
+ timestamps: true,
98
+ toJSON: { virtuals: true },
99
+ toObject: { virtuals: true },
100
+ strict: false
101
+ // This allows for flexible document structure beyond the defined schema
102
+ }
103
+ );
104
+ AnnotationSchema.index({ "meta.contentType": 1 });
105
+ AnnotationSchema.index({ "meta.documentId": 1 });
106
+ AnnotationSchema.index({ createdAt: -1 });
107
+ AnnotationSchema.index({ "annotations.annoKey": 1 });
108
+ AnnotationSchema.pre("save", function(next) {
109
+ this.updatedAt = /* @__PURE__ */ new Date();
110
+ next();
111
+ });
112
+ AnnotationSchema.methods.getMainField = function(fieldPath) {
113
+ if (!fieldPath) return null;
114
+ const parts = fieldPath.split(".");
115
+ let value = this.main;
116
+ for (const part of parts) {
117
+ if (!value || typeof value !== "object") return null;
118
+ value = value[part];
119
+ }
120
+ return value;
121
+ };
122
+ AnnotationSchema.virtual("displayTitle").get(function() {
123
+ return this.main.title || "Untitled Annotation";
124
+ });
125
+ module.exports = AnnotationSchema;
126
+ }
127
+ });
128
+
129
+ // src/models/PlatformConfigs.js
130
+ var require_PlatformConfigs = __commonJS({
131
+ "src/models/PlatformConfigs.js"(exports, module) {
132
+ "use strict";
133
+ var mongoose2 = __require("mongoose");
134
+ var platformConfigTypes = [
135
+ { id: "roles" },
136
+ { id: "contentTypes" },
137
+ { id: "contentCards" },
138
+ { id: "profileTypes" },
139
+ { id: "nav" },
140
+ { id: "deployment" },
141
+ { id: "userAgreement" },
142
+ { id: "localeData" },
143
+ { id: "theme" },
144
+ { id: "tagTypes" },
145
+ { id: "AI" }
146
+ ];
147
+ var PlatformConfigsSchema2 = new mongoose2.Schema(
148
+ {
149
+ type: {
150
+ type: String,
151
+ enum: platformConfigTypes.map((d) => d.id),
152
+ unique: true
153
+ },
154
+ roles: Array,
155
+ data: Object
156
+ },
157
+ { collection: "platformConfigs" }
158
+ );
159
+ module.exports = PlatformConfigsSchema2;
160
+ }
161
+ });
162
+
163
+ // src/models/Tpl.js
164
+ var require_Tpl = __commonJS({
165
+ "src/models/Tpl.js"(exports, module) {
166
+ "use strict";
167
+ var mongoose2 = __require("mongoose");
168
+ var TplSchema2 = new mongoose2.Schema({
169
+ dateFirstPublished: Date,
170
+ dateCreated: Date,
171
+ dateLastPublished: Date,
172
+ dateLastEdited: Date,
173
+ status: {
174
+ type: String,
175
+ default: "published",
176
+ // only cuz we dont want to go and add this property in all databases
177
+ enum: ["unpublished", "editPublished", "published"]
178
+ },
179
+ version: {
180
+ type: Number,
181
+ default: 0
182
+ },
183
+ versionPublishedBy: {
184
+ type: mongoose2.Schema.Types.ObjectId,
185
+ ref: "user"
186
+ // reference to the 'user' model
187
+ },
188
+ firstPublishedBy: {
189
+ type: mongoose2.Schema.Types.ObjectId,
190
+ ref: "user"
191
+ // reference to the 'user' model
192
+ },
193
+ kp_content_type: {
194
+ type: String,
195
+ required: true,
196
+ unique: true
197
+ },
198
+ category: {
199
+ //to deprecate and turn into 'layout'
200
+ type: String,
201
+ default: "knowledgeResources2"
202
+ },
203
+ kp_settings: [
204
+ {
205
+ type: Object
206
+ }
207
+ ],
208
+ kp_templates: {
209
+ type: Object
210
+ },
211
+ tplMeta: Object,
212
+ tplLocales: Object,
213
+ indexed: Object,
214
+ drafts: {
215
+ active: Object
216
+ },
217
+ rollbacks: Object,
218
+ //for 'remembering' hidden configurations
219
+ // OTHER CONFIGS
220
+ listing: Object,
221
+ //listing page configurations. this is new, currently only used in nct
222
+ general: {
223
+ content: {
224
+ title: String,
225
+ singular: String,
226
+ ctaText: String,
227
+ listingDesc: String
228
+ },
229
+ allowQuickTagCreation: { enable: Boolean },
230
+ segment: String,
231
+ settingsUIStyle: String,
232
+ hasUpdateType: Boolean,
233
+ annotation: {
234
+ enable: Boolean
235
+ },
236
+ participantModule: {
237
+ enable: Boolean
238
+ },
239
+ formFieldNumbering: {
240
+ enable: Boolean
241
+ },
242
+ postPblRedirPath: Object,
243
+ templateIndex: Object,
244
+ sharing: {
245
+ enable: Boolean,
246
+ trackShareCount: {
247
+ type: Boolean,
248
+ default: false
249
+ }
250
+ },
251
+ viewsCount: {
252
+ enable: {
253
+ type: Boolean,
254
+ default: false
255
+ }
256
+ },
257
+ comments: {
258
+ enable: Boolean
259
+ },
260
+ reactions: {
261
+ type: Map,
262
+ of: {
263
+ enable: Boolean,
264
+ icon: String
265
+ }
266
+ },
267
+ csvExport: {
268
+ enable: Boolean,
269
+ excludeFields: Array,
270
+ enableUpdateExport: Boolean,
271
+ fieldsToSortAtEnd: Array,
272
+ fetchBatches: {
273
+ enable: Boolean,
274
+ batchSize: Number
275
+ }
276
+ },
277
+ //tci helpers - these exist only to show / not show certain UIs in the tci
278
+ disableKPSettings: Boolean
279
+ }
280
+ //general contenttype configs. mostly the stuff inside platformConfigs > contentTypes
281
+ }, {
282
+ toJSON: { virtuals: true },
283
+ // So `res.json()` and other `JSON.stringify()` functions include virtuals
284
+ toObject: { virtuals: true }
285
+ // So `toObject()` output includes virtuals
286
+ });
287
+ TplSchema2.virtual("layout").get(function() {
288
+ return this.category;
289
+ });
290
+ module.exports = TplSchema2;
291
+ }
292
+ });
293
+
1
294
  // src/utils/testFn.ts
2
295
  function add(a, b) {
3
296
  return a + b;
4
297
  }
5
298
 
299
+ // src/db/mongodb.ts
300
+ import mongoose from "mongoose";
301
+
302
+ // src/db/getGlobalConfig.ts
303
+ var globalConfig = {};
304
+ var getGlobalConfig = () => {
305
+ return {
306
+ env: globalConfig.env,
307
+ dbConfigs: globalConfig.dbConfigs ? { ...globalConfig.dbConfigs } : void 0,
308
+ mongodb: globalConfig.mongodb ? { ...globalConfig.mongodb } : void 0
309
+ };
310
+ };
311
+ var initializeGlobalConfig = (config) => {
312
+ globalConfig = {
313
+ env: config.env,
314
+ dbConfigs: config.dbConfigs ? { ...config.dbConfigs } : void 0,
315
+ mongodb: config.mongodb ? { ...config.mongodb } : void 0
316
+ };
317
+ console.log(`Global config initialized for environment: ${config.env}`);
318
+ };
319
+ var updateGlobalConfig = (updates) => {
320
+ globalConfig = {
321
+ ...globalConfig,
322
+ ...updates,
323
+ // Handle nested objects properly
324
+ dbConfigs: updates.dbConfigs ? { ...globalConfig.dbConfigs, ...updates.dbConfigs } : globalConfig.dbConfigs,
325
+ mongodb: updates.mongodb ? { ...globalConfig.mongodb, ...updates.mongodb } : globalConfig.mongodb
326
+ };
327
+ console.log("Global config updated:", Object.keys(updates));
328
+ };
329
+
330
+ // src/db/mongodb.ts
331
+ var mongoOptions = {
332
+ // Note: These legacy options are no longer needed in newer versions of mongoose
333
+ // useUnifiedTopology, useNewUrlParser, useCreateIndex, useFindAndModify are deprecated
334
+ maxPoolSize: 10
335
+ // replaces poolSize
336
+ };
337
+ var multiConnectToMongoDB = ({ env, dbConfigs } = {}) => {
338
+ const globalConfig2 = getGlobalConfig();
339
+ const actualEnv = env || globalConfig2.env;
340
+ const actualDbConfigs = dbConfigs || globalConfig2.dbConfigs;
341
+ if (!actualEnv) {
342
+ throw new Error("Environment not provided and not found in global config");
343
+ }
344
+ if (!actualDbConfigs) {
345
+ throw new Error("dbConfigs not provided and not found in global config");
346
+ }
347
+ const { connectTo } = actualDbConfigs[actualEnv];
348
+ if (!connectTo) {
349
+ throw new Error(`No connection configuration found for environment: ${actualEnv}`);
350
+ }
351
+ const dbConnections = {};
352
+ connectTo.forEach((connectToEnv) => {
353
+ const { CLUSTER_NAME, DB_URI } = actualDbConfigs[connectToEnv];
354
+ if (!CLUSTER_NAME || !DB_URI) {
355
+ throw new Error(`Missing CLUSTER_NAME or DB_URI for environment: ${connectToEnv}`);
356
+ }
357
+ dbConnections[CLUSTER_NAME] = mongoose.createConnection(DB_URI, mongoOptions);
358
+ dbConnections[CLUSTER_NAME].on("open", () => {
359
+ console.log(`Mongoose connection open to ${CLUSTER_NAME}`);
360
+ });
361
+ dbConnections[CLUSTER_NAME].on("error", (err) => {
362
+ console.log(`Mongoose connection error: ${err.message} with connection info ${CLUSTER_NAME}`);
363
+ process.exit(1);
364
+ });
365
+ });
366
+ return dbConnections;
367
+ };
368
+
369
+ // src/db/getDbByTenant.ts
370
+ var getDbByTenant = ({
371
+ tenant,
372
+ env
373
+ }) => {
374
+ if (!tenant) throw new Error("tenant id has not been provided");
375
+ const globalConfig2 = getGlobalConfig();
376
+ const actualEnv = env || globalConfig2.env;
377
+ const dbConfigs = globalConfig2.dbConfigs;
378
+ const mongodb = globalConfig2.mongodb;
379
+ if (!dbConfigs) {
380
+ throw new Error("dbConfigs not found in global config");
381
+ }
382
+ if (!actualEnv) {
383
+ throw new Error("env not provided and not found in global config");
384
+ }
385
+ const { CLUSTER_NAME } = dbConfigs[actualEnv];
386
+ const dbName = `${tenant}_${actualEnv}`;
387
+ if (mongodb) {
388
+ const db = mongodb[CLUSTER_NAME].useDb(dbName, { useCache: true });
389
+ return db;
390
+ }
391
+ throw new Error("getDbByTenant : mongodb object doesnt exist");
392
+ };
393
+
394
+ // src/db/getModelByTenant.ts
395
+ var AnnotationsSchema = require_Annotations();
396
+ var PlatformConfigsSchema = require_PlatformConfigs();
397
+ var TplSchema = require_Tpl();
398
+ var getModelByTenant = ({
399
+ tenant,
400
+ modelName,
401
+ schema,
402
+ env
403
+ }) => {
404
+ if (!tenant) {
405
+ throw new Error("tenant id has not been provided");
406
+ }
407
+ const db = getDbByTenant({
408
+ tenant,
409
+ env
410
+ });
411
+ if (!Object.keys(db.models).includes(modelName)) {
412
+ return db.model(modelName, schema);
413
+ }
414
+ return db.model(modelName);
415
+ };
416
+ var getAnnotationsModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
417
+ tenant,
418
+ modelName: "annotations",
419
+ schema: AnnotationsSchema,
420
+ env
421
+ });
422
+ var getPlatformConfigsModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
423
+ tenant,
424
+ modelName: "platformConfigs",
425
+ schema: PlatformConfigsSchema,
426
+ env
427
+ });
428
+ var getTplModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
429
+ tenant,
430
+ modelName: "tpl",
431
+ schema: TplSchema,
432
+ env
433
+ });
434
+
6
435
  // src/utils/getterSetterDeleter/utils/set_deleteVal.ts
7
436
  var set_deleteVal = (action, data, valuePath, value) => {
8
437
  if (valuePath === void 0) return;
@@ -136,6 +565,14 @@ var getValV2_getter = (data, valuePath, options, depthIdx) => {
136
565
  export {
137
566
  add,
138
567
  deleteVal,
568
+ getAnnotationsModelByTenant,
569
+ getDbByTenant,
570
+ getModelByTenant,
571
+ getPlatformConfigsModelByTenant,
572
+ getTplModelByTenant,
139
573
  getVal,
140
- setVal
574
+ initializeGlobalConfig,
575
+ multiConnectToMongoDB,
576
+ setVal,
577
+ updateGlobalConfig
141
578
  };
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.2.0",
6
+ "version": "1.2.1",
7
7
  "description": "Utility functions for both browser and Node.js",
8
8
  "main": "dist/index.js",
9
9
  "module": "dist/index.mjs",
@@ -40,5 +40,8 @@
40
40
  "semantic-release": "^24.2.3",
41
41
  "tsup": "^8.4.0",
42
42
  "typescript": "^5.8.2"
43
+ },
44
+ "dependencies": {
45
+ "mongoose": "^8.15.1"
43
46
  }
44
47
  }