@librechat/data-schemas 0.0.7 → 0.0.10

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.
Files changed (76) hide show
  1. package/dist/index.cjs +2160 -4
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.es.js +2156 -7
  4. package/dist/index.es.js.map +1 -1
  5. package/dist/types/config/meiliLogger.d.ts +4 -0
  6. package/dist/types/config/parsers.d.ts +32 -0
  7. package/dist/types/config/winston.d.ts +4 -0
  8. package/dist/types/crypto/index.d.ts +3 -0
  9. package/dist/types/index.d.ts +8 -46
  10. package/dist/types/methods/index.d.ts +89 -0
  11. package/dist/types/methods/memory.d.ts +35 -0
  12. package/dist/types/methods/pluginAuth.d.ts +36 -0
  13. package/dist/types/methods/role.d.ts +35 -0
  14. package/dist/types/methods/session.d.ts +48 -0
  15. package/dist/types/methods/share.d.ts +38 -0
  16. package/dist/types/methods/share.test.d.ts +1 -0
  17. package/dist/types/methods/token.d.ts +34 -0
  18. package/dist/types/methods/user.d.ts +39 -0
  19. package/dist/types/methods/user.test.d.ts +1 -0
  20. package/dist/types/models/action.d.ts +30 -0
  21. package/dist/types/models/agent.d.ts +30 -0
  22. package/dist/types/models/assistant.d.ts +30 -0
  23. package/dist/types/models/balance.d.ts +30 -0
  24. package/dist/types/models/banner.d.ts +30 -0
  25. package/dist/types/models/conversationTag.d.ts +30 -0
  26. package/dist/types/models/convo.d.ts +30 -0
  27. package/dist/types/models/file.d.ts +30 -0
  28. package/dist/types/models/index.d.ts +54 -0
  29. package/dist/types/models/key.d.ts +30 -0
  30. package/dist/types/models/memory.d.ts +27 -0
  31. package/dist/types/models/message.d.ts +30 -0
  32. package/dist/types/models/pluginAuth.d.ts +30 -0
  33. package/dist/types/models/plugins/mongoMeili.d.ts +74 -0
  34. package/dist/types/models/preset.d.ts +30 -0
  35. package/dist/types/models/project.d.ts +30 -0
  36. package/dist/types/models/prompt.d.ts +30 -0
  37. package/dist/types/models/promptGroup.d.ts +30 -0
  38. package/dist/types/models/role.d.ts +30 -0
  39. package/dist/types/models/session.d.ts +30 -0
  40. package/dist/types/models/sharedLink.d.ts +30 -0
  41. package/dist/types/models/token.d.ts +30 -0
  42. package/dist/types/models/toolCall.d.ts +30 -0
  43. package/dist/types/models/transaction.d.ts +30 -0
  44. package/dist/types/models/user.d.ts +30 -0
  45. package/dist/types/schema/action.d.ts +2 -27
  46. package/dist/types/schema/agent.d.ts +4 -31
  47. package/dist/types/schema/assistant.d.ts +4 -16
  48. package/dist/types/schema/balance.d.ts +4 -12
  49. package/dist/types/schema/convo.d.ts +2 -49
  50. package/dist/types/schema/file.d.ts +2 -26
  51. package/dist/types/schema/index.d.ts +24 -0
  52. package/dist/types/schema/memory.d.ts +29 -0
  53. package/dist/types/schema/message.d.ts +2 -36
  54. package/dist/types/schema/pluginAuth.d.ts +2 -9
  55. package/dist/types/schema/role.d.ts +2 -5
  56. package/dist/types/schema/session.d.ts +2 -6
  57. package/dist/types/schema/token.d.ts +2 -11
  58. package/dist/types/schema/user.d.ts +5 -36
  59. package/dist/types/types/action.d.ts +52 -0
  60. package/dist/types/types/agent.d.ts +55 -0
  61. package/dist/types/types/assistant.d.ts +39 -0
  62. package/dist/types/types/balance.d.ts +35 -0
  63. package/dist/types/types/banner.d.ts +34 -0
  64. package/dist/types/types/convo.d.ts +74 -0
  65. package/dist/types/types/file.d.ts +51 -0
  66. package/dist/types/types/index.d.ts +42 -0
  67. package/dist/types/types/memory.d.ts +63 -0
  68. package/dist/types/types/message.d.ts +67 -0
  69. package/dist/types/types/pluginAuth.d.ts +59 -0
  70. package/dist/types/types/role.d.ts +30 -0
  71. package/dist/types/types/session.d.ts +61 -0
  72. package/dist/types/types/share.d.ts +82 -0
  73. package/dist/types/types/token.d.ts +62 -0
  74. package/dist/types/types/user.d.ts +94 -0
  75. package/package.json +14 -5
  76. package/README.md +0 -114
package/dist/index.cjs CHANGED
@@ -1,7 +1,26 @@
1
1
  'use strict';
2
2
 
3
+ var jwt = require('jsonwebtoken');
4
+ var node_crypto = require('node:crypto');
3
5
  var mongoose = require('mongoose');
4
6
  var librechatDataProvider = require('librechat-data-provider');
7
+ var _ = require('lodash');
8
+ var meilisearch = require('meilisearch');
9
+ var path = require('path');
10
+ var winston = require('winston');
11
+ require('winston-daily-rotate-file');
12
+ var klona = require('klona');
13
+ var traverse = require('traverse');
14
+ var nanoid = require('nanoid');
15
+
16
+ async function signPayload({ payload, secret, expirationTime, }) {
17
+ return jwt.sign(payload, secret, { expiresIn: expirationTime });
18
+ }
19
+ async function hashToken(str) {
20
+ const data = new TextEncoder().encode(str);
21
+ const hashBuffer = await node_crypto.webcrypto.subtle.digest('SHA-256', data);
22
+ return Buffer.from(hashBuffer).toString('hex');
23
+ }
5
24
 
6
25
  // Define the Auth sub-schema with type-safety.
7
26
  const AuthSchema = new mongoose.Schema({
@@ -133,6 +152,10 @@ const agentSchema = new mongoose.Schema({
133
152
  ref: 'Project',
134
153
  index: true,
135
154
  },
155
+ versions: {
156
+ type: [mongoose.Schema.Types.Mixed],
157
+ default: [],
158
+ },
136
159
  }, {
137
160
  timestamps: true,
138
161
  });
@@ -619,6 +642,25 @@ const messageSchema = new mongoose.Schema({
619
642
  finish_reason: {
620
643
  type: String,
621
644
  },
645
+ feedback: {
646
+ type: {
647
+ rating: {
648
+ type: String,
649
+ enum: ['thumbsUp', 'thumbsDown'],
650
+ required: true,
651
+ },
652
+ tag: {
653
+ type: mongoose.Schema.Types.Mixed,
654
+ required: false,
655
+ },
656
+ text: {
657
+ type: String,
658
+ required: false,
659
+ },
660
+ },
661
+ default: undefined,
662
+ required: false,
663
+ },
622
664
  _meiliIndex: {
623
665
  type: Boolean,
624
666
  required: false,
@@ -829,7 +871,7 @@ const promptGroupSchema = new mongoose.Schema({
829
871
  validator: function (v) {
830
872
  return v === undefined || v === null || v === '' || /^[a-z0-9-]+$/.test(v);
831
873
  },
832
- message: (props) => `${props.value} is not a valid command. Only lowercase alphanumeric characters and hyphens are allowed.`,
874
+ message: (props) => { var _a; return `${(_a = props === null || props === void 0 ? void 0 : props.value) !== null && _a !== void 0 ? _a : 'Value'} is not a valid command. Only lowercase alphanumeric characters and hyphens are allowed.`; },
833
875
  },
834
876
  maxlength: [
835
877
  librechatDataProvider.Constants.COMMANDS_MAX_LENGTH,
@@ -851,6 +893,13 @@ const rolePermissionsSchema = new mongoose.Schema({
851
893
  [librechatDataProvider.Permissions.USE]: { type: Boolean, default: true },
852
894
  [librechatDataProvider.Permissions.CREATE]: { type: Boolean, default: true },
853
895
  },
896
+ [librechatDataProvider.PermissionTypes.MEMORIES]: {
897
+ [librechatDataProvider.Permissions.USE]: { type: Boolean, default: true },
898
+ [librechatDataProvider.Permissions.CREATE]: { type: Boolean, default: true },
899
+ [librechatDataProvider.Permissions.UPDATE]: { type: Boolean, default: true },
900
+ [librechatDataProvider.Permissions.READ]: { type: Boolean, default: true },
901
+ [librechatDataProvider.Permissions.OPT_OUT]: { type: Boolean, default: true },
902
+ },
854
903
  [librechatDataProvider.PermissionTypes.AGENTS]: {
855
904
  [librechatDataProvider.Permissions.SHARED_GLOBAL]: { type: Boolean, default: false },
856
905
  [librechatDataProvider.Permissions.USE]: { type: Boolean, default: true },
@@ -865,6 +914,9 @@ const rolePermissionsSchema = new mongoose.Schema({
865
914
  [librechatDataProvider.PermissionTypes.RUN_CODE]: {
866
915
  [librechatDataProvider.Permissions.USE]: { type: Boolean, default: true },
867
916
  },
917
+ [librechatDataProvider.PermissionTypes.WEB_SEARCH]: {
918
+ [librechatDataProvider.Permissions.USE]: { type: Boolean, default: true },
919
+ },
868
920
  }, { _id: false });
869
921
  const roleSchema = new mongoose.Schema({
870
922
  name: { type: String, required: true, unique: true, index: true },
@@ -877,6 +929,12 @@ const roleSchema = new mongoose.Schema({
877
929
  [librechatDataProvider.Permissions.USE]: true,
878
930
  [librechatDataProvider.Permissions.CREATE]: true,
879
931
  },
932
+ [librechatDataProvider.PermissionTypes.MEMORIES]: {
933
+ [librechatDataProvider.Permissions.USE]: true,
934
+ [librechatDataProvider.Permissions.CREATE]: true,
935
+ [librechatDataProvider.Permissions.UPDATE]: true,
936
+ [librechatDataProvider.Permissions.READ]: true,
937
+ },
880
938
  [librechatDataProvider.PermissionTypes.AGENTS]: {
881
939
  [librechatDataProvider.Permissions.SHARED_GLOBAL]: false,
882
940
  [librechatDataProvider.Permissions.USE]: true,
@@ -885,6 +943,7 @@ const roleSchema = new mongoose.Schema({
885
943
  [librechatDataProvider.PermissionTypes.MULTI_CONVO]: { [librechatDataProvider.Permissions.USE]: true },
886
944
  [librechatDataProvider.PermissionTypes.TEMPORARY_CHAT]: { [librechatDataProvider.Permissions.USE]: true },
887
945
  [librechatDataProvider.PermissionTypes.RUN_CODE]: { [librechatDataProvider.Permissions.USE]: true },
946
+ [librechatDataProvider.PermissionTypes.WEB_SEARCH]: { [librechatDataProvider.Permissions.USE]: true },
888
947
  }),
889
948
  },
890
949
  });
@@ -1048,7 +1107,7 @@ const BackupCodeSchema = new mongoose.Schema({
1048
1107
  used: { type: Boolean, default: false },
1049
1108
  usedAt: { type: Date, default: null },
1050
1109
  }, { _id: false });
1051
- const User = new mongoose.Schema({
1110
+ const userSchema = new mongoose.Schema({
1052
1111
  name: {
1053
1112
  type: String,
1054
1113
  },
@@ -1059,7 +1118,7 @@ const User = new mongoose.Schema({
1059
1118
  },
1060
1119
  email: {
1061
1120
  type: String,
1062
- required: [true, 'can\'t be blank'],
1121
+ required: [true, "can't be blank"],
1063
1122
  lowercase: true,
1064
1123
  unique: true,
1065
1124
  match: [/\S+@\S+\.\S+/, 'is invalid'],
@@ -1104,6 +1163,11 @@ const User = new mongoose.Schema({
1104
1163
  unique: true,
1105
1164
  sparse: true,
1106
1165
  },
1166
+ samlId: {
1167
+ type: String,
1168
+ unique: true,
1169
+ sparse: true,
1170
+ },
1107
1171
  ldapId: {
1108
1172
  type: String,
1109
1173
  unique: true,
@@ -1148,8 +1212,2093 @@ const User = new mongoose.Schema({
1148
1212
  type: Boolean,
1149
1213
  default: false,
1150
1214
  },
1215
+ personalization: {
1216
+ type: {
1217
+ memories: {
1218
+ type: Boolean,
1219
+ default: true,
1220
+ },
1221
+ },
1222
+ default: {},
1223
+ },
1151
1224
  }, { timestamps: true });
1152
1225
 
1226
+ const MemoryEntrySchema = new mongoose.Schema({
1227
+ userId: {
1228
+ type: mongoose.Schema.Types.ObjectId,
1229
+ ref: 'User',
1230
+ index: true,
1231
+ required: true,
1232
+ },
1233
+ key: {
1234
+ type: String,
1235
+ required: true,
1236
+ validate: {
1237
+ validator: (v) => /^[a-z_]+$/.test(v),
1238
+ message: 'Key must only contain lowercase letters and underscores',
1239
+ },
1240
+ },
1241
+ value: {
1242
+ type: String,
1243
+ required: true,
1244
+ },
1245
+ tokenCount: {
1246
+ type: Number,
1247
+ default: 0,
1248
+ },
1249
+ updated_at: {
1250
+ type: Date,
1251
+ default: Date.now,
1252
+ },
1253
+ });
1254
+
1255
+ /**
1256
+ * Creates or returns the User model using the provided mongoose instance and schema
1257
+ */
1258
+ function createUserModel(mongoose) {
1259
+ return mongoose.models.User || mongoose.model('User', userSchema);
1260
+ }
1261
+
1262
+ /**
1263
+ * Creates or returns the Token model using the provided mongoose instance and schema
1264
+ */
1265
+ function createTokenModel(mongoose) {
1266
+ return mongoose.models.Token || mongoose.model('Token', tokenSchema);
1267
+ }
1268
+
1269
+ /**
1270
+ * Creates or returns the Session model using the provided mongoose instance and schema
1271
+ */
1272
+ function createSessionModel(mongoose) {
1273
+ return mongoose.models.Session || mongoose.model('Session', sessionSchema);
1274
+ }
1275
+
1276
+ /**
1277
+ * Creates or returns the Balance model using the provided mongoose instance and schema
1278
+ */
1279
+ function createBalanceModel(mongoose) {
1280
+ return mongoose.models.Balance || mongoose.model('Balance', balanceSchema);
1281
+ }
1282
+
1283
+ const logDir$1 = path.join(__dirname, '..', '..', '..', 'api', 'logs');
1284
+ const { NODE_ENV: NODE_ENV$1, DEBUG_LOGGING: DEBUG_LOGGING$1 = 'false' } = process.env;
1285
+ const useDebugLogging$1 = (typeof DEBUG_LOGGING$1 === 'string' && DEBUG_LOGGING$1.toLowerCase() === 'true') ||
1286
+ DEBUG_LOGGING$1 === 'true';
1287
+ const levels$1 = {
1288
+ error: 0,
1289
+ warn: 1,
1290
+ info: 2,
1291
+ http: 3,
1292
+ verbose: 4,
1293
+ debug: 5,
1294
+ activity: 6,
1295
+ silly: 7,
1296
+ };
1297
+ winston.addColors({
1298
+ info: 'green',
1299
+ warn: 'italic yellow',
1300
+ error: 'red',
1301
+ debug: 'blue',
1302
+ });
1303
+ const level$1 = () => {
1304
+ const env = NODE_ENV$1 || 'development';
1305
+ const isDevelopment = env === 'development';
1306
+ return isDevelopment ? 'debug' : 'warn';
1307
+ };
1308
+ const fileFormat$1 = winston.format.combine(winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), winston.format.errors({ stack: true }), winston.format.splat());
1309
+ const logLevel = useDebugLogging$1 ? 'debug' : 'error';
1310
+ const transports$1 = [
1311
+ new winston.transports.DailyRotateFile({
1312
+ level: logLevel,
1313
+ filename: `${logDir$1}/meiliSync-%DATE%.log`,
1314
+ datePattern: 'YYYY-MM-DD',
1315
+ zippedArchive: true,
1316
+ maxSize: '20m',
1317
+ maxFiles: '14d',
1318
+ format: fileFormat$1,
1319
+ }),
1320
+ ];
1321
+ const consoleFormat$1 = winston.format.combine(winston.format.colorize({ all: true }), winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), winston.format.printf((info) => `${info.timestamp} ${info.level}: ${info.message}`));
1322
+ transports$1.push(new winston.transports.Console({
1323
+ level: 'info',
1324
+ format: consoleFormat$1,
1325
+ }));
1326
+ const logger$1 = winston.createLogger({
1327
+ level: level$1(),
1328
+ levels: levels$1,
1329
+ transports: transports$1,
1330
+ });
1331
+
1332
+ // Environment flags
1333
+ /**
1334
+ * Flag to indicate if search is enabled based on environment variables.
1335
+ */
1336
+ const searchEnabled = process.env.SEARCH != null && process.env.SEARCH.toLowerCase() === 'true';
1337
+ /**
1338
+ * Flag to indicate if MeiliSearch is enabled based on required environment variables.
1339
+ */
1340
+ const meiliEnabled = process.env.MEILI_HOST != null && process.env.MEILI_MASTER_KEY != null && searchEnabled;
1341
+ /**
1342
+ * Local implementation of parseTextParts to avoid dependency on librechat-data-provider
1343
+ * Extracts text content from an array of content items
1344
+ */
1345
+ const parseTextParts = (content) => {
1346
+ if (!Array.isArray(content)) {
1347
+ return '';
1348
+ }
1349
+ return content
1350
+ .filter((item) => item.type === 'text' && typeof item.text === 'string')
1351
+ .map((item) => item.text)
1352
+ .join(' ')
1353
+ .trim();
1354
+ };
1355
+ /**
1356
+ * Local implementation to handle Bing convoId conversion
1357
+ */
1358
+ const cleanUpPrimaryKeyValue = (value) => {
1359
+ return value.replace(/--/g, '|');
1360
+ };
1361
+ /**
1362
+ * Validates the required options for configuring the mongoMeili plugin.
1363
+ */
1364
+ const validateOptions = (options) => {
1365
+ const requiredKeys = ['host', 'apiKey', 'indexName'];
1366
+ requiredKeys.forEach((key) => {
1367
+ if (!options[key]) {
1368
+ throw new Error(`Missing mongoMeili Option: ${key}`);
1369
+ }
1370
+ });
1371
+ };
1372
+ /**
1373
+ * Factory function to create a MeiliMongooseModel class which extends a Mongoose model.
1374
+ * This class contains static and instance methods to synchronize and manage the MeiliSearch index
1375
+ * corresponding to the MongoDB collection.
1376
+ *
1377
+ * @param config - Configuration object.
1378
+ * @param config.index - The MeiliSearch index object.
1379
+ * @param config.attributesToIndex - List of attributes to index.
1380
+ * @returns A class definition that will be loaded into the Mongoose schema.
1381
+ */
1382
+ const createMeiliMongooseModel = ({ index, attributesToIndex, }) => {
1383
+ const primaryKey = attributesToIndex[0];
1384
+ class MeiliMongooseModel {
1385
+ /**
1386
+ * Synchronizes the data between the MongoDB collection and the MeiliSearch index.
1387
+ *
1388
+ * The synchronization process involves:
1389
+ * 1. Fetching all documents from the MongoDB collection and MeiliSearch index.
1390
+ * 2. Comparing documents from both sources.
1391
+ * 3. Deleting documents from MeiliSearch that no longer exist in MongoDB.
1392
+ * 4. Adding documents to MeiliSearch that exist in MongoDB but not in the index.
1393
+ * 5. Updating documents in MeiliSearch if key fields (such as `text` or `title`) differ.
1394
+ * 6. Updating the `_meiliIndex` field in MongoDB to indicate the indexing status.
1395
+ *
1396
+ * Note: The function processes documents in batches because MeiliSearch's
1397
+ * `index.getDocuments` requires an exact limit and `index.addDocuments` does not handle
1398
+ * partial failures in a batch.
1399
+ *
1400
+ * @returns {Promise<void>} Resolves when the synchronization is complete.
1401
+ */
1402
+ static async syncWithMeili() {
1403
+ try {
1404
+ let moreDocuments = true;
1405
+ const mongoDocuments = await this.find().lean();
1406
+ const format = (doc) => _.omitBy(_.pick(doc, attributesToIndex), (v, k) => k.startsWith('$'));
1407
+ const mongoMap = new Map(mongoDocuments.map((doc) => {
1408
+ const typedDoc = doc;
1409
+ return [typedDoc[primaryKey], format(typedDoc)];
1410
+ }));
1411
+ const indexMap = new Map();
1412
+ let offset = 0;
1413
+ const batchSize = 1000;
1414
+ while (moreDocuments) {
1415
+ const batch = await index.getDocuments({ limit: batchSize, offset });
1416
+ if (batch.results.length === 0) {
1417
+ moreDocuments = false;
1418
+ }
1419
+ for (const doc of batch.results) {
1420
+ indexMap.set(doc[primaryKey], format(doc));
1421
+ }
1422
+ offset += batchSize;
1423
+ }
1424
+ logger$1.debug('[syncWithMeili]', { indexMap: indexMap.size, mongoMap: mongoMap.size });
1425
+ const updateOps = [];
1426
+ // Process documents present in the MeiliSearch index
1427
+ for (const [id, doc] of indexMap) {
1428
+ const update = {};
1429
+ update[primaryKey] = id;
1430
+ if (mongoMap.has(id)) {
1431
+ const mongoDoc = mongoMap.get(id);
1432
+ if ((doc.text && doc.text !== (mongoDoc === null || mongoDoc === void 0 ? void 0 : mongoDoc.text)) ||
1433
+ (doc.title && doc.title !== (mongoDoc === null || mongoDoc === void 0 ? void 0 : mongoDoc.title))) {
1434
+ logger$1.debug(`[syncWithMeili] ${id} had document discrepancy in ${doc.text ? 'text' : 'title'} field`);
1435
+ updateOps.push({
1436
+ updateOne: { filter: update, update: { $set: { _meiliIndex: true } } },
1437
+ });
1438
+ await index.addDocuments([doc]);
1439
+ }
1440
+ }
1441
+ else {
1442
+ await index.deleteDocument(id);
1443
+ updateOps.push({
1444
+ updateOne: { filter: update, update: { $set: { _meiliIndex: false } } },
1445
+ });
1446
+ }
1447
+ }
1448
+ // Process documents present in MongoDB
1449
+ for (const [id, doc] of mongoMap) {
1450
+ const update = {};
1451
+ update[primaryKey] = id;
1452
+ if (!indexMap.has(id)) {
1453
+ await index.addDocuments([doc]);
1454
+ updateOps.push({
1455
+ updateOne: { filter: update, update: { $set: { _meiliIndex: true } } },
1456
+ });
1457
+ }
1458
+ else if (doc._meiliIndex === false) {
1459
+ updateOps.push({
1460
+ updateOne: { filter: update, update: { $set: { _meiliIndex: true } } },
1461
+ });
1462
+ }
1463
+ }
1464
+ if (updateOps.length > 0) {
1465
+ await this.collection.bulkWrite(updateOps);
1466
+ logger$1.debug(`[syncWithMeili] Finished indexing ${primaryKey === 'messageId' ? 'messages' : 'conversations'}`);
1467
+ }
1468
+ }
1469
+ catch (error) {
1470
+ logger$1.error('[syncWithMeili] Error adding document to Meili:', error);
1471
+ }
1472
+ }
1473
+ /**
1474
+ * Updates settings for the MeiliSearch index
1475
+ */
1476
+ static async setMeiliIndexSettings(settings) {
1477
+ return await index.updateSettings(settings);
1478
+ }
1479
+ /**
1480
+ * Searches the MeiliSearch index and optionally populates results
1481
+ */
1482
+ static async meiliSearch(q, params, populate) {
1483
+ const data = await index.search(q, params);
1484
+ if (populate) {
1485
+ const query = {};
1486
+ query[primaryKey] = _.map(data.hits, (hit) => cleanUpPrimaryKeyValue(hit[primaryKey]));
1487
+ const projection = Object.keys(this.schema.obj).reduce((results, key) => {
1488
+ if (!key.startsWith('$')) {
1489
+ results[key] = 1;
1490
+ }
1491
+ return results;
1492
+ }, { _id: 1, __v: 1 });
1493
+ const hitsFromMongoose = await this.find(query, projection).lean();
1494
+ const populatedHits = data.hits.map((hit) => {
1495
+ hit[primaryKey];
1496
+ const originalHit = _.find(hitsFromMongoose, (item) => {
1497
+ const typedItem = item;
1498
+ return typedItem[primaryKey] === hit[primaryKey];
1499
+ });
1500
+ return {
1501
+ ...(originalHit && typeof originalHit === 'object' ? originalHit : {}),
1502
+ ...hit,
1503
+ };
1504
+ });
1505
+ data.hits = populatedHits;
1506
+ }
1507
+ return data;
1508
+ }
1509
+ /**
1510
+ * Preprocesses the current document for indexing
1511
+ */
1512
+ preprocessObjectForIndex() {
1513
+ const object = _.omitBy(_.pick(this.toJSON(), attributesToIndex), (v, k) => k.startsWith('$'));
1514
+ if (object.conversationId &&
1515
+ typeof object.conversationId === 'string' &&
1516
+ object.conversationId.includes('|')) {
1517
+ object.conversationId = object.conversationId.replace(/\|/g, '--');
1518
+ }
1519
+ if (object.content && Array.isArray(object.content)) {
1520
+ object.text = parseTextParts(object.content);
1521
+ delete object.content;
1522
+ }
1523
+ return object;
1524
+ }
1525
+ /**
1526
+ * Adds the current document to the MeiliSearch index
1527
+ */
1528
+ async addObjectToMeili(next) {
1529
+ const object = this.preprocessObjectForIndex();
1530
+ try {
1531
+ await index.addDocuments([object]);
1532
+ }
1533
+ catch (error) {
1534
+ logger$1.error('[addObjectToMeili] Error adding document to Meili:', error);
1535
+ return next();
1536
+ }
1537
+ try {
1538
+ await this.collection.updateMany({ _id: this._id }, { $set: { _meiliIndex: true } });
1539
+ }
1540
+ catch (error) {
1541
+ logger$1.error('[addObjectToMeili] Error updating _meiliIndex field:', error);
1542
+ return next();
1543
+ }
1544
+ next();
1545
+ }
1546
+ /**
1547
+ * Updates the current document in the MeiliSearch index
1548
+ */
1549
+ async updateObjectToMeili(next) {
1550
+ try {
1551
+ const object = _.omitBy(_.pick(this.toJSON(), attributesToIndex), (v, k) => k.startsWith('$'));
1552
+ await index.updateDocuments([object]);
1553
+ next();
1554
+ }
1555
+ catch (error) {
1556
+ logger$1.error('[updateObjectToMeili] Error updating document in Meili:', error);
1557
+ return next();
1558
+ }
1559
+ }
1560
+ /**
1561
+ * Deletes the current document from the MeiliSearch index.
1562
+ *
1563
+ * @returns {Promise<void>}
1564
+ */
1565
+ async deleteObjectFromMeili(next) {
1566
+ try {
1567
+ await index.deleteDocument(this._id);
1568
+ next();
1569
+ }
1570
+ catch (error) {
1571
+ logger$1.error('[deleteObjectFromMeili] Error deleting document from Meili:', error);
1572
+ return next();
1573
+ }
1574
+ }
1575
+ /**
1576
+ * Post-save hook to synchronize the document with MeiliSearch.
1577
+ *
1578
+ * If the document is already indexed (i.e. `_meiliIndex` is true), it updates it;
1579
+ * otherwise, it adds the document to the index.
1580
+ */
1581
+ postSaveHook(next) {
1582
+ if (this._meiliIndex) {
1583
+ this.updateObjectToMeili(next);
1584
+ }
1585
+ else {
1586
+ this.addObjectToMeili(next);
1587
+ }
1588
+ }
1589
+ /**
1590
+ * Post-update hook to update the document in MeiliSearch.
1591
+ *
1592
+ * This hook is triggered after a document update, ensuring that changes are
1593
+ * propagated to the MeiliSearch index if the document is indexed.
1594
+ */
1595
+ postUpdateHook(next) {
1596
+ if (this._meiliIndex) {
1597
+ this.updateObjectToMeili(next);
1598
+ }
1599
+ else {
1600
+ next();
1601
+ }
1602
+ }
1603
+ /**
1604
+ * Post-remove hook to delete the document from MeiliSearch.
1605
+ *
1606
+ * This hook is triggered after a document is removed, ensuring that the document
1607
+ * is also removed from the MeiliSearch index if it was previously indexed.
1608
+ */
1609
+ postRemoveHook(next) {
1610
+ if (this._meiliIndex) {
1611
+ this.deleteObjectFromMeili(next);
1612
+ }
1613
+ else {
1614
+ next();
1615
+ }
1616
+ }
1617
+ }
1618
+ return MeiliMongooseModel;
1619
+ };
1620
+ /**
1621
+ * Mongoose plugin to synchronize MongoDB collections with a MeiliSearch index.
1622
+ *
1623
+ * This plugin:
1624
+ * - Validates the provided options.
1625
+ * - Adds a `_meiliIndex` field to the schema to track indexing status.
1626
+ * - Sets up a MeiliSearch client and creates an index if it doesn't already exist.
1627
+ * - Loads class methods for syncing, searching, and managing documents in MeiliSearch.
1628
+ * - Registers Mongoose hooks (post-save, post-update, post-remove, etc.) to maintain index consistency.
1629
+ *
1630
+ * @param schema - The Mongoose schema to which the plugin is applied.
1631
+ * @param options - Configuration options.
1632
+ * @param options.host - The MeiliSearch host.
1633
+ * @param options.apiKey - The MeiliSearch API key.
1634
+ * @param options.indexName - The name of the MeiliSearch index.
1635
+ * @param options.primaryKey - The primary key field for indexing.
1636
+ */
1637
+ function mongoMeili(schema, options) {
1638
+ const mongoose = options.mongoose;
1639
+ validateOptions(options);
1640
+ // Add _meiliIndex field to the schema to track if a document has been indexed in MeiliSearch.
1641
+ schema.add({
1642
+ _meiliIndex: {
1643
+ type: Boolean,
1644
+ required: false,
1645
+ select: false,
1646
+ default: false,
1647
+ },
1648
+ });
1649
+ const { host, apiKey, indexName, primaryKey } = options;
1650
+ const client = new meilisearch.MeiliSearch({ host, apiKey });
1651
+ client.createIndex(indexName, { primaryKey });
1652
+ const index = client.index(indexName);
1653
+ // Collect attributes from the schema that should be indexed
1654
+ const attributesToIndex = [
1655
+ ...Object.entries(schema.obj).reduce((results, [key, value]) => {
1656
+ const schemaValue = value;
1657
+ return schemaValue.meiliIndex ? [...results, key] : results;
1658
+ }, []),
1659
+ ];
1660
+ schema.loadClass(createMeiliMongooseModel({ index, attributesToIndex }));
1661
+ // Register Mongoose hooks
1662
+ schema.post('save', function (doc, next) {
1663
+ var _a;
1664
+ (_a = doc.postSaveHook) === null || _a === void 0 ? void 0 : _a.call(doc, next);
1665
+ });
1666
+ schema.post('updateOne', function (doc, next) {
1667
+ var _a;
1668
+ (_a = doc.postUpdateHook) === null || _a === void 0 ? void 0 : _a.call(doc, next);
1669
+ });
1670
+ schema.post('deleteOne', function (doc, next) {
1671
+ var _a;
1672
+ (_a = doc.postRemoveHook) === null || _a === void 0 ? void 0 : _a.call(doc, next);
1673
+ });
1674
+ // Pre-deleteMany hook: remove corresponding documents from MeiliSearch when multiple documents are deleted.
1675
+ schema.pre('deleteMany', async function (next) {
1676
+ if (!meiliEnabled) {
1677
+ return next();
1678
+ }
1679
+ try {
1680
+ const conditions = this.getQuery();
1681
+ if (Object.prototype.hasOwnProperty.call(schema.obj, 'messages')) {
1682
+ const convoIndex = client.index('convos');
1683
+ const deletedConvos = await mongoose
1684
+ .model('Conversation')
1685
+ .find(conditions)
1686
+ .lean();
1687
+ const promises = deletedConvos.map((convo) => convoIndex.deleteDocument(convo.conversationId));
1688
+ await Promise.all(promises);
1689
+ }
1690
+ if (Object.prototype.hasOwnProperty.call(schema.obj, 'messageId')) {
1691
+ const messageIndex = client.index('messages');
1692
+ const deletedMessages = await mongoose
1693
+ .model('Message')
1694
+ .find(conditions)
1695
+ .lean();
1696
+ const promises = deletedMessages.map((message) => messageIndex.deleteDocument(message.messageId));
1697
+ await Promise.all(promises);
1698
+ }
1699
+ return next();
1700
+ }
1701
+ catch (error) {
1702
+ if (meiliEnabled) {
1703
+ logger$1.error('[MeiliMongooseModel.deleteMany] There was an issue deleting conversation indexes upon deletion. Next startup may be slow due to syncing.', error);
1704
+ }
1705
+ return next();
1706
+ }
1707
+ });
1708
+ // Post-findOneAndUpdate hook
1709
+ schema.post('findOneAndUpdate', async function (doc, next) {
1710
+ var _a;
1711
+ if (!meiliEnabled) {
1712
+ return next();
1713
+ }
1714
+ if (doc.unfinished) {
1715
+ return next();
1716
+ }
1717
+ let meiliDoc;
1718
+ if (doc.messages) {
1719
+ try {
1720
+ meiliDoc = await client.index('convos').getDocument(doc.conversationId);
1721
+ }
1722
+ catch (error) {
1723
+ logger$1.debug('[MeiliMongooseModel.findOneAndUpdate] Convo not found in MeiliSearch and will index ' +
1724
+ doc.conversationId, error);
1725
+ }
1726
+ }
1727
+ if (meiliDoc && meiliDoc.title === doc.title) {
1728
+ return next();
1729
+ }
1730
+ (_a = doc.postSaveHook) === null || _a === void 0 ? void 0 : _a.call(doc, next);
1731
+ });
1732
+ }
1733
+
1734
+ /**
1735
+ * Creates or returns the Conversation model using the provided mongoose instance and schema
1736
+ */
1737
+ function createConversationModel(mongoose) {
1738
+ if (process.env.MEILI_HOST && process.env.MEILI_MASTER_KEY) {
1739
+ convoSchema.plugin(mongoMeili, {
1740
+ mongoose,
1741
+ host: process.env.MEILI_HOST,
1742
+ apiKey: process.env.MEILI_MASTER_KEY,
1743
+ /** Note: Will get created automatically if it doesn't exist already */
1744
+ indexName: 'convos',
1745
+ primaryKey: 'conversationId',
1746
+ });
1747
+ }
1748
+ return (mongoose.models.Conversation || mongoose.model('Conversation', convoSchema));
1749
+ }
1750
+
1751
+ /**
1752
+ * Creates or returns the Message model using the provided mongoose instance and schema
1753
+ */
1754
+ function createMessageModel(mongoose) {
1755
+ if (process.env.MEILI_HOST && process.env.MEILI_MASTER_KEY) {
1756
+ messageSchema.plugin(mongoMeili, {
1757
+ mongoose,
1758
+ host: process.env.MEILI_HOST,
1759
+ apiKey: process.env.MEILI_MASTER_KEY,
1760
+ indexName: 'messages',
1761
+ primaryKey: 'messageId',
1762
+ });
1763
+ }
1764
+ return mongoose.models.Message || mongoose.model('Message', messageSchema);
1765
+ }
1766
+
1767
+ /**
1768
+ * Creates or returns the Agent model using the provided mongoose instance and schema
1769
+ */
1770
+ function createAgentModel(mongoose) {
1771
+ return mongoose.models.Agent || mongoose.model('Agent', agentSchema);
1772
+ }
1773
+
1774
+ /**
1775
+ * Creates or returns the Role model using the provided mongoose instance and schema
1776
+ */
1777
+ function createRoleModel(mongoose) {
1778
+ return mongoose.models.Role || mongoose.model('Role', roleSchema);
1779
+ }
1780
+
1781
+ /**
1782
+ * Creates or returns the Action model using the provided mongoose instance and schema
1783
+ */
1784
+ function createActionModel(mongoose) {
1785
+ return mongoose.models.Action || mongoose.model('Action', Action);
1786
+ }
1787
+
1788
+ /**
1789
+ * Creates or returns the Assistant model using the provided mongoose instance and schema
1790
+ */
1791
+ function createAssistantModel(mongoose) {
1792
+ return mongoose.models.Assistant || mongoose.model('Assistant', assistantSchema);
1793
+ }
1794
+
1795
+ /**
1796
+ * Creates or returns the File model using the provided mongoose instance and schema
1797
+ */
1798
+ function createFileModel(mongoose) {
1799
+ return mongoose.models.File || mongoose.model('File', file);
1800
+ }
1801
+
1802
+ /**
1803
+ * Creates or returns the Banner model using the provided mongoose instance and schema
1804
+ */
1805
+ function createBannerModel(mongoose) {
1806
+ return mongoose.models.Banner || mongoose.model('Banner', bannerSchema);
1807
+ }
1808
+
1809
+ /**
1810
+ * Creates or returns the Project model using the provided mongoose instance and schema
1811
+ */
1812
+ function createProjectModel(mongoose) {
1813
+ return mongoose.models.Project || mongoose.model('Project', projectSchema);
1814
+ }
1815
+
1816
+ /**
1817
+ * Creates or returns the Key model using the provided mongoose instance and schema
1818
+ */
1819
+ function createKeyModel(mongoose) {
1820
+ return mongoose.models.Key || mongoose.model('Key', keySchema);
1821
+ }
1822
+
1823
+ /**
1824
+ * Creates or returns the PluginAuth model using the provided mongoose instance and schema
1825
+ */
1826
+ function createPluginAuthModel(mongoose) {
1827
+ return mongoose.models.PluginAuth || mongoose.model('PluginAuth', pluginAuthSchema);
1828
+ }
1829
+
1830
+ /**
1831
+ * Creates or returns the Transaction model using the provided mongoose instance and schema
1832
+ */
1833
+ function createTransactionModel(mongoose) {
1834
+ return (mongoose.models.Transaction || mongoose.model('Transaction', transactionSchema));
1835
+ }
1836
+
1837
+ /**
1838
+ * Creates or returns the Preset model using the provided mongoose instance and schema
1839
+ */
1840
+ function createPresetModel(mongoose) {
1841
+ return mongoose.models.Preset || mongoose.model('Preset', presetSchema);
1842
+ }
1843
+
1844
+ /**
1845
+ * Creates or returns the Prompt model using the provided mongoose instance and schema
1846
+ */
1847
+ function createPromptModel(mongoose) {
1848
+ return mongoose.models.Prompt || mongoose.model('Prompt', promptSchema);
1849
+ }
1850
+
1851
+ /**
1852
+ * Creates or returns the PromptGroup model using the provided mongoose instance and schema
1853
+ */
1854
+ function createPromptGroupModel(mongoose) {
1855
+ return (mongoose.models.PromptGroup ||
1856
+ mongoose.model('PromptGroup', promptGroupSchema));
1857
+ }
1858
+
1859
+ /**
1860
+ * Creates or returns the ConversationTag model using the provided mongoose instance and schema
1861
+ */
1862
+ function createConversationTagModel(mongoose) {
1863
+ return (mongoose.models.ConversationTag ||
1864
+ mongoose.model('ConversationTag', conversationTag));
1865
+ }
1866
+
1867
+ /**
1868
+ * Creates or returns the SharedLink model using the provided mongoose instance and schema
1869
+ */
1870
+ function createSharedLinkModel(mongoose) {
1871
+ return mongoose.models.SharedLink || mongoose.model('SharedLink', shareSchema);
1872
+ }
1873
+
1874
+ /**
1875
+ * Creates or returns the ToolCall model using the provided mongoose instance and schema
1876
+ */
1877
+ function createToolCallModel(mongoose) {
1878
+ return mongoose.models.ToolCall || mongoose.model('ToolCall', toolCallSchema);
1879
+ }
1880
+
1881
+ function createMemoryModel(mongoose) {
1882
+ return mongoose.models.MemoryEntry || mongoose.model('MemoryEntry', MemoryEntrySchema);
1883
+ }
1884
+
1885
+ /**
1886
+ * Creates all database models for all collections
1887
+ */
1888
+ function createModels(mongoose) {
1889
+ return {
1890
+ User: createUserModel(mongoose),
1891
+ Token: createTokenModel(mongoose),
1892
+ Session: createSessionModel(mongoose),
1893
+ Balance: createBalanceModel(mongoose),
1894
+ Conversation: createConversationModel(mongoose),
1895
+ Message: createMessageModel(mongoose),
1896
+ Agent: createAgentModel(mongoose),
1897
+ Role: createRoleModel(mongoose),
1898
+ Action: createActionModel(mongoose),
1899
+ Assistant: createAssistantModel(mongoose),
1900
+ File: createFileModel(mongoose),
1901
+ Banner: createBannerModel(mongoose),
1902
+ Project: createProjectModel(mongoose),
1903
+ Key: createKeyModel(mongoose),
1904
+ PluginAuth: createPluginAuthModel(mongoose),
1905
+ Transaction: createTransactionModel(mongoose),
1906
+ Preset: createPresetModel(mongoose),
1907
+ Prompt: createPromptModel(mongoose),
1908
+ PromptGroup: createPromptGroupModel(mongoose),
1909
+ ConversationTag: createConversationTagModel(mongoose),
1910
+ SharedLink: createSharedLinkModel(mongoose),
1911
+ ToolCall: createToolCallModel(mongoose),
1912
+ MemoryEntry: createMemoryModel(mongoose),
1913
+ };
1914
+ }
1915
+
1916
+ /** Factory function that takes mongoose instance and returns the methods */
1917
+ function createUserMethods(mongoose) {
1918
+ /**
1919
+ * Search for a single user based on partial data and return matching user document as plain object.
1920
+ */
1921
+ async function findUser(searchCriteria, fieldsToSelect) {
1922
+ const User = mongoose.models.User;
1923
+ const query = User.findOne(searchCriteria);
1924
+ if (fieldsToSelect) {
1925
+ query.select(fieldsToSelect);
1926
+ }
1927
+ return (await query.lean());
1928
+ }
1929
+ /**
1930
+ * Count the number of user documents in the collection based on the provided filter.
1931
+ */
1932
+ async function countUsers(filter = {}) {
1933
+ const User = mongoose.models.User;
1934
+ return await User.countDocuments(filter);
1935
+ }
1936
+ /**
1937
+ * Creates a new user, optionally with a TTL of 1 week.
1938
+ */
1939
+ async function createUser(data, balanceConfig, disableTTL = true, returnUser = false) {
1940
+ const User = mongoose.models.User;
1941
+ const Balance = mongoose.models.Balance;
1942
+ const userData = {
1943
+ ...data,
1944
+ expiresAt: disableTTL ? undefined : new Date(Date.now() + 604800 * 1000), // 1 week in milliseconds
1945
+ };
1946
+ if (disableTTL) {
1947
+ delete userData.expiresAt;
1948
+ }
1949
+ const user = await User.create(userData);
1950
+ // If balance is enabled, create or update a balance record for the user
1951
+ if ((balanceConfig === null || balanceConfig === void 0 ? void 0 : balanceConfig.enabled) && (balanceConfig === null || balanceConfig === void 0 ? void 0 : balanceConfig.startBalance)) {
1952
+ const update = {
1953
+ $inc: { tokenCredits: balanceConfig.startBalance },
1954
+ };
1955
+ if (balanceConfig.autoRefillEnabled &&
1956
+ balanceConfig.refillIntervalValue != null &&
1957
+ balanceConfig.refillIntervalUnit != null &&
1958
+ balanceConfig.refillAmount != null) {
1959
+ update.$set = {
1960
+ autoRefillEnabled: true,
1961
+ refillIntervalValue: balanceConfig.refillIntervalValue,
1962
+ refillIntervalUnit: balanceConfig.refillIntervalUnit,
1963
+ refillAmount: balanceConfig.refillAmount,
1964
+ };
1965
+ }
1966
+ await Balance.findOneAndUpdate({ user: user._id }, update, {
1967
+ upsert: true,
1968
+ new: true,
1969
+ }).lean();
1970
+ }
1971
+ if (returnUser) {
1972
+ return user.toObject();
1973
+ }
1974
+ return user._id;
1975
+ }
1976
+ /**
1977
+ * Update a user with new data without overwriting existing properties.
1978
+ */
1979
+ async function updateUser(userId, updateData) {
1980
+ const User = mongoose.models.User;
1981
+ const updateOperation = {
1982
+ $set: updateData,
1983
+ $unset: { expiresAt: '' }, // Remove the expiresAt field to prevent TTL
1984
+ };
1985
+ return (await User.findByIdAndUpdate(userId, updateOperation, {
1986
+ new: true,
1987
+ runValidators: true,
1988
+ }).lean());
1989
+ }
1990
+ /**
1991
+ * Retrieve a user by ID and convert the found user document to a plain object.
1992
+ */
1993
+ async function getUserById(userId, fieldsToSelect) {
1994
+ const User = mongoose.models.User;
1995
+ const query = User.findById(userId);
1996
+ if (fieldsToSelect) {
1997
+ query.select(fieldsToSelect);
1998
+ }
1999
+ return (await query.lean());
2000
+ }
2001
+ /**
2002
+ * Delete a user by their unique ID.
2003
+ */
2004
+ async function deleteUserById(userId) {
2005
+ try {
2006
+ const User = mongoose.models.User;
2007
+ const result = await User.deleteOne({ _id: userId });
2008
+ if (result.deletedCount === 0) {
2009
+ return { deletedCount: 0, message: 'No user found with that ID.' };
2010
+ }
2011
+ return { deletedCount: result.deletedCount, message: 'User was deleted successfully.' };
2012
+ }
2013
+ catch (error) {
2014
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
2015
+ throw new Error('Error deleting user: ' + errorMessage);
2016
+ }
2017
+ }
2018
+ /**
2019
+ * Generates a JWT token for a given user.
2020
+ */
2021
+ async function generateToken(user) {
2022
+ if (!user) {
2023
+ throw new Error('No user provided');
2024
+ }
2025
+ let expires = 1000 * 60 * 15;
2026
+ if (process.env.SESSION_EXPIRY !== undefined && process.env.SESSION_EXPIRY !== '') {
2027
+ try {
2028
+ const evaluated = eval(process.env.SESSION_EXPIRY);
2029
+ if (evaluated) {
2030
+ expires = evaluated;
2031
+ }
2032
+ }
2033
+ catch (error) {
2034
+ console.warn('Invalid SESSION_EXPIRY expression, using default:', error);
2035
+ }
2036
+ }
2037
+ return await signPayload({
2038
+ payload: {
2039
+ id: user._id,
2040
+ username: user.username,
2041
+ provider: user.provider,
2042
+ email: user.email,
2043
+ },
2044
+ secret: process.env.JWT_SECRET,
2045
+ expirationTime: expires / 1000,
2046
+ });
2047
+ }
2048
+ /**
2049
+ * Update a user's personalization memories setting.
2050
+ * Handles the edge case where the personalization object doesn't exist.
2051
+ */
2052
+ async function toggleUserMemories(userId, memoriesEnabled) {
2053
+ const User = mongoose.models.User;
2054
+ // First, ensure the personalization object exists
2055
+ const user = await User.findById(userId);
2056
+ if (!user) {
2057
+ return null;
2058
+ }
2059
+ // Use $set to update the nested field, which will create the personalization object if it doesn't exist
2060
+ const updateOperation = {
2061
+ $set: {
2062
+ 'personalization.memories': memoriesEnabled,
2063
+ },
2064
+ };
2065
+ return (await User.findByIdAndUpdate(userId, updateOperation, {
2066
+ new: true,
2067
+ runValidators: true,
2068
+ }).lean());
2069
+ }
2070
+ // Return all methods
2071
+ return {
2072
+ findUser,
2073
+ countUsers,
2074
+ createUser,
2075
+ updateUser,
2076
+ getUserById,
2077
+ deleteUserById,
2078
+ generateToken,
2079
+ toggleUserMemories,
2080
+ };
2081
+ }
2082
+
2083
+ const SPLAT_SYMBOL = Symbol.for('splat');
2084
+ const MESSAGE_SYMBOL = Symbol.for('message');
2085
+ const CONSOLE_JSON_STRING_LENGTH = parseInt(process.env.CONSOLE_JSON_STRING_LENGTH || '', 10) || 255;
2086
+ const sensitiveKeys = [
2087
+ /^(sk-)[^\s]+/, // OpenAI API key pattern
2088
+ /(Bearer )[^\s]+/, // Header: Bearer token pattern
2089
+ /(api-key:? )[^\s]+/, // Header: API key pattern
2090
+ /(key=)[^\s]+/, // URL query param: sensitive key pattern (Google)
2091
+ ];
2092
+ /**
2093
+ * Determines if a given value string is sensitive and returns matching regex patterns.
2094
+ *
2095
+ * @param valueStr - The value string to check.
2096
+ * @returns An array of regex patterns that match the value string.
2097
+ */
2098
+ function getMatchingSensitivePatterns(valueStr) {
2099
+ if (valueStr) {
2100
+ // Filter and return all regex patterns that match the value string
2101
+ return sensitiveKeys.filter((regex) => regex.test(valueStr));
2102
+ }
2103
+ return [];
2104
+ }
2105
+ /**
2106
+ * Redacts sensitive information from a console message and trims it to a specified length if provided.
2107
+ * @param str - The console message to be redacted.
2108
+ * @param trimLength - The optional length at which to trim the redacted message.
2109
+ * @returns The redacted and optionally trimmed console message.
2110
+ */
2111
+ function redactMessage(str, trimLength) {
2112
+ if (!str) {
2113
+ return '';
2114
+ }
2115
+ const patterns = getMatchingSensitivePatterns(str);
2116
+ patterns.forEach((pattern) => {
2117
+ str = str.replace(pattern, '$1[REDACTED]');
2118
+ });
2119
+ return str;
2120
+ }
2121
+ /**
2122
+ * Redacts sensitive information from log messages if the log level is 'error'.
2123
+ * Note: Intentionally mutates the object.
2124
+ * @param info - The log information object.
2125
+ * @returns The modified log information object.
2126
+ */
2127
+ const redactFormat = winston.format((info) => {
2128
+ if (info.level === 'error') {
2129
+ // Type guard to ensure message is a string
2130
+ if (typeof info.message === 'string') {
2131
+ info.message = redactMessage(info.message);
2132
+ }
2133
+ // Handle MESSAGE_SYMBOL with type safety
2134
+ const symbolValue = info[MESSAGE_SYMBOL];
2135
+ if (typeof symbolValue === 'string') {
2136
+ info[MESSAGE_SYMBOL] = redactMessage(symbolValue);
2137
+ }
2138
+ }
2139
+ return info;
2140
+ });
2141
+ /**
2142
+ * Truncates long strings, especially base64 image data, within log messages.
2143
+ *
2144
+ * @param value - The value to be inspected and potentially truncated.
2145
+ * @param length - The length at which to truncate the value. Default: 100.
2146
+ * @returns The truncated or original value.
2147
+ */
2148
+ const truncateLongStrings = (value, length = 100) => {
2149
+ if (typeof value === 'string') {
2150
+ return value.length > length ? value.substring(0, length) + '... [truncated]' : value;
2151
+ }
2152
+ return value;
2153
+ };
2154
+ /**
2155
+ * An array mapping function that truncates long strings (objects converted to JSON strings).
2156
+ * @param item - The item to be condensed.
2157
+ * @returns The condensed item.
2158
+ */
2159
+ const condenseArray = (item) => {
2160
+ if (typeof item === 'string') {
2161
+ return truncateLongStrings(JSON.stringify(item));
2162
+ }
2163
+ else if (typeof item === 'object') {
2164
+ return truncateLongStrings(JSON.stringify(item));
2165
+ }
2166
+ return item;
2167
+ };
2168
+ /**
2169
+ * Formats log messages for debugging purposes.
2170
+ * - Truncates long strings within log messages.
2171
+ * - Condenses arrays by truncating long strings and objects as strings within array items.
2172
+ * - Redacts sensitive information from log messages if the log level is 'error'.
2173
+ * - Converts log information object to a formatted string.
2174
+ *
2175
+ * @param options - The options for formatting log messages.
2176
+ * @returns The formatted log message.
2177
+ */
2178
+ const debugTraverse = winston.format.printf(({ level, message, timestamp, ...metadata }) => {
2179
+ if (!message) {
2180
+ return `${timestamp} ${level}`;
2181
+ }
2182
+ // Type-safe version of the CJS logic: !message?.trim || typeof message !== 'string'
2183
+ if (typeof message !== 'string' || !message.trim) {
2184
+ return `${timestamp} ${level}: ${JSON.stringify(message)}`;
2185
+ }
2186
+ let msg = `${timestamp} ${level}: ${truncateLongStrings(message.trim(), 150)}`;
2187
+ try {
2188
+ if (level !== 'debug') {
2189
+ return msg;
2190
+ }
2191
+ if (!metadata) {
2192
+ return msg;
2193
+ }
2194
+ // Type-safe access to SPLAT_SYMBOL using bracket notation
2195
+ const metadataRecord = metadata;
2196
+ const splatArray = metadataRecord[SPLAT_SYMBOL];
2197
+ const debugValue = Array.isArray(splatArray) ? splatArray[0] : undefined;
2198
+ if (!debugValue) {
2199
+ return msg;
2200
+ }
2201
+ if (debugValue && Array.isArray(debugValue)) {
2202
+ msg += `\n${JSON.stringify(debugValue.map(condenseArray))}`;
2203
+ return msg;
2204
+ }
2205
+ if (typeof debugValue !== 'object') {
2206
+ return (msg += ` ${debugValue}`);
2207
+ }
2208
+ msg += '\n{';
2209
+ const copy = klona.klona(metadata);
2210
+ traverse(copy).forEach(function (value) {
2211
+ var _a;
2212
+ if (typeof (this === null || this === void 0 ? void 0 : this.key) === 'symbol') {
2213
+ return;
2214
+ }
2215
+ let _parentKey = '';
2216
+ const parent = this.parent;
2217
+ if (typeof (parent === null || parent === void 0 ? void 0 : parent.key) !== 'symbol' && (parent === null || parent === void 0 ? void 0 : parent.key)) {
2218
+ _parentKey = parent.key;
2219
+ }
2220
+ const parentKey = `${parent && parent.notRoot ? _parentKey + '.' : ''}`;
2221
+ const tabs = `${parent && parent.notRoot ? ' ' : ' '}`;
2222
+ const currentKey = (_a = this === null || this === void 0 ? void 0 : this.key) !== null && _a !== void 0 ? _a : 'unknown';
2223
+ if (this.isLeaf && typeof value === 'string') {
2224
+ const truncatedText = truncateLongStrings(value);
2225
+ msg += `\n${tabs}${parentKey}${currentKey}: ${JSON.stringify(truncatedText)},`;
2226
+ }
2227
+ else if (this.notLeaf && Array.isArray(value) && value.length > 0) {
2228
+ const currentMessage = `\n${tabs}// ${value.length} ${currentKey.replace(/s$/, '')}(s)`;
2229
+ this.update(currentMessage, true);
2230
+ msg += currentMessage;
2231
+ const stringifiedArray = value.map(condenseArray);
2232
+ msg += `\n${tabs}${parentKey}${currentKey}: [${stringifiedArray}],`;
2233
+ }
2234
+ else if (this.isLeaf && typeof value === 'function') {
2235
+ msg += `\n${tabs}${parentKey}${currentKey}: function,`;
2236
+ }
2237
+ else if (this.isLeaf) {
2238
+ msg += `\n${tabs}${parentKey}${currentKey}: ${value},`;
2239
+ }
2240
+ });
2241
+ msg += '\n}';
2242
+ return msg;
2243
+ }
2244
+ catch (e) {
2245
+ const errorMessage = e instanceof Error ? e.message : 'Unknown error';
2246
+ return (msg += `\n[LOGGER PARSING ERROR] ${errorMessage}`);
2247
+ }
2248
+ });
2249
+ /**
2250
+ * Truncates long string values in JSON log objects.
2251
+ * Prevents outputting extremely long values (e.g., base64, blobs).
2252
+ */
2253
+ const jsonTruncateFormat = winston.format((info) => {
2254
+ const truncateLongStrings = (str, maxLength) => str.length > maxLength ? str.substring(0, maxLength) + '...' : str;
2255
+ const seen = new WeakSet();
2256
+ const truncateObject = (obj) => {
2257
+ if (typeof obj !== 'object' || obj === null) {
2258
+ return obj;
2259
+ }
2260
+ // Handle circular references - now with proper object type
2261
+ if (seen.has(obj)) {
2262
+ return '[Circular]';
2263
+ }
2264
+ seen.add(obj);
2265
+ if (Array.isArray(obj)) {
2266
+ return obj.map((item) => truncateObject(item));
2267
+ }
2268
+ // We know this is an object at this point
2269
+ const objectRecord = obj;
2270
+ const newObj = {};
2271
+ Object.entries(objectRecord).forEach(([key, value]) => {
2272
+ if (typeof value === 'string') {
2273
+ newObj[key] = truncateLongStrings(value, CONSOLE_JSON_STRING_LENGTH);
2274
+ }
2275
+ else {
2276
+ newObj[key] = truncateObject(value);
2277
+ }
2278
+ });
2279
+ return newObj;
2280
+ };
2281
+ return truncateObject(info);
2282
+ });
2283
+
2284
+ const logDir = path.join(__dirname, '..', '..', '..', 'api', 'logs');
2285
+ const { NODE_ENV, DEBUG_LOGGING, CONSOLE_JSON, DEBUG_CONSOLE } = process.env;
2286
+ const useConsoleJson = typeof CONSOLE_JSON === 'string' && CONSOLE_JSON.toLowerCase() === 'true';
2287
+ const useDebugConsole = typeof DEBUG_CONSOLE === 'string' && DEBUG_CONSOLE.toLowerCase() === 'true';
2288
+ const useDebugLogging = typeof DEBUG_LOGGING === 'string' && DEBUG_LOGGING.toLowerCase() === 'true';
2289
+ const levels = {
2290
+ error: 0,
2291
+ warn: 1,
2292
+ info: 2,
2293
+ http: 3,
2294
+ verbose: 4,
2295
+ debug: 5,
2296
+ activity: 6,
2297
+ silly: 7,
2298
+ };
2299
+ winston.addColors({
2300
+ info: 'green',
2301
+ warn: 'italic yellow',
2302
+ error: 'red',
2303
+ debug: 'blue',
2304
+ });
2305
+ const level = () => {
2306
+ const env = NODE_ENV || 'development';
2307
+ return env === 'development' ? 'debug' : 'warn';
2308
+ };
2309
+ const fileFormat = winston.format.combine(redactFormat(), winston.format.timestamp({ format: () => new Date().toISOString() }), winston.format.errors({ stack: true }), winston.format.splat());
2310
+ const transports = [
2311
+ new winston.transports.DailyRotateFile({
2312
+ level: 'error',
2313
+ filename: `${logDir}/error-%DATE%.log`,
2314
+ datePattern: 'YYYY-MM-DD',
2315
+ zippedArchive: true,
2316
+ maxSize: '20m',
2317
+ maxFiles: '14d',
2318
+ format: fileFormat,
2319
+ }),
2320
+ ];
2321
+ if (useDebugLogging) {
2322
+ transports.push(new winston.transports.DailyRotateFile({
2323
+ level: 'debug',
2324
+ filename: `${logDir}/debug-%DATE%.log`,
2325
+ datePattern: 'YYYY-MM-DD',
2326
+ zippedArchive: true,
2327
+ maxSize: '20m',
2328
+ maxFiles: '14d',
2329
+ format: winston.format.combine(fileFormat, debugTraverse),
2330
+ }));
2331
+ }
2332
+ const consoleFormat = winston.format.combine(redactFormat(), winston.format.colorize({ all: true }), winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), winston.format.printf((info) => {
2333
+ const message = `${info.timestamp} ${info.level}: ${info.message}`;
2334
+ return info.level.includes('error') ? redactMessage(message) : message;
2335
+ }));
2336
+ let consoleLogLevel = 'info';
2337
+ if (useDebugConsole) {
2338
+ consoleLogLevel = 'debug';
2339
+ }
2340
+ // Add console transport
2341
+ if (useDebugConsole) {
2342
+ transports.push(new winston.transports.Console({
2343
+ level: consoleLogLevel,
2344
+ format: useConsoleJson
2345
+ ? winston.format.combine(fileFormat, jsonTruncateFormat(), winston.format.json())
2346
+ : winston.format.combine(fileFormat, debugTraverse),
2347
+ }));
2348
+ }
2349
+ else if (useConsoleJson) {
2350
+ transports.push(new winston.transports.Console({
2351
+ level: consoleLogLevel,
2352
+ format: winston.format.combine(fileFormat, jsonTruncateFormat(), winston.format.json()),
2353
+ }));
2354
+ }
2355
+ else {
2356
+ transports.push(new winston.transports.Console({
2357
+ level: consoleLogLevel,
2358
+ format: consoleFormat,
2359
+ }));
2360
+ }
2361
+ // Create logger
2362
+ const logger = winston.createLogger({
2363
+ level: level(),
2364
+ levels,
2365
+ transports,
2366
+ });
2367
+
2368
+ var _a;
2369
+ class SessionError extends Error {
2370
+ constructor(message, code = 'SESSION_ERROR') {
2371
+ super(message);
2372
+ this.name = 'SessionError';
2373
+ this.code = code;
2374
+ }
2375
+ }
2376
+ const { REFRESH_TOKEN_EXPIRY } = (_a = process.env) !== null && _a !== void 0 ? _a : {};
2377
+ const expires = REFRESH_TOKEN_EXPIRY
2378
+ ? eval(REFRESH_TOKEN_EXPIRY)
2379
+ : 1000 * 60 * 60 * 24 * 7; // 7 days default
2380
+ // Factory function that takes mongoose instance and returns the methods
2381
+ function createSessionMethods(mongoose) {
2382
+ const Session = mongoose.models.Session;
2383
+ /**
2384
+ * Creates a new session for a user
2385
+ */
2386
+ async function createSession(userId, options = {}) {
2387
+ if (!userId) {
2388
+ throw new SessionError('User ID is required', 'INVALID_USER_ID');
2389
+ }
2390
+ try {
2391
+ const session = new Session({
2392
+ user: userId,
2393
+ expiration: options.expiration || new Date(Date.now() + expires),
2394
+ });
2395
+ const refreshToken = await generateRefreshToken(session);
2396
+ return { session, refreshToken };
2397
+ }
2398
+ catch (error) {
2399
+ logger.error('[createSession] Error creating session:', error);
2400
+ throw new SessionError('Failed to create session', 'CREATE_SESSION_FAILED');
2401
+ }
2402
+ }
2403
+ /**
2404
+ * Finds a session by various parameters
2405
+ */
2406
+ async function findSession(params, options = { lean: true }) {
2407
+ try {
2408
+ const query = {};
2409
+ if (!params.refreshToken && !params.userId && !params.sessionId) {
2410
+ throw new SessionError('At least one search parameter is required', 'INVALID_SEARCH_PARAMS');
2411
+ }
2412
+ if (params.refreshToken) {
2413
+ const tokenHash = await hashToken(params.refreshToken);
2414
+ query.refreshTokenHash = tokenHash;
2415
+ }
2416
+ if (params.userId) {
2417
+ query.user = params.userId;
2418
+ }
2419
+ if (params.sessionId) {
2420
+ const sessionId = typeof params.sessionId === 'object' &&
2421
+ params.sessionId !== null &&
2422
+ 'sessionId' in params.sessionId
2423
+ ? params.sessionId.sessionId
2424
+ : params.sessionId;
2425
+ if (!mongoose.Types.ObjectId.isValid(sessionId)) {
2426
+ throw new SessionError('Invalid session ID format', 'INVALID_SESSION_ID');
2427
+ }
2428
+ query._id = sessionId;
2429
+ }
2430
+ // Add expiration check to only return valid sessions
2431
+ query.expiration = { $gt: new Date() };
2432
+ const sessionQuery = Session.findOne(query);
2433
+ if (options.lean) {
2434
+ return (await sessionQuery.lean());
2435
+ }
2436
+ return await sessionQuery.exec();
2437
+ }
2438
+ catch (error) {
2439
+ logger.error('[findSession] Error finding session:', error);
2440
+ throw new SessionError('Failed to find session', 'FIND_SESSION_FAILED');
2441
+ }
2442
+ }
2443
+ /**
2444
+ * Updates session expiration
2445
+ */
2446
+ async function updateExpiration(session, newExpiration) {
2447
+ try {
2448
+ const sessionDoc = typeof session === 'string' ? await Session.findById(session) : session;
2449
+ if (!sessionDoc) {
2450
+ throw new SessionError('Session not found', 'SESSION_NOT_FOUND');
2451
+ }
2452
+ sessionDoc.expiration = newExpiration || new Date(Date.now() + expires);
2453
+ return await sessionDoc.save();
2454
+ }
2455
+ catch (error) {
2456
+ logger.error('[updateExpiration] Error updating session:', error);
2457
+ throw new SessionError('Failed to update session expiration', 'UPDATE_EXPIRATION_FAILED');
2458
+ }
2459
+ }
2460
+ /**
2461
+ * Deletes a session by refresh token or session ID
2462
+ */
2463
+ async function deleteSession(params) {
2464
+ try {
2465
+ if (!params.refreshToken && !params.sessionId) {
2466
+ throw new SessionError('Either refreshToken or sessionId is required', 'INVALID_DELETE_PARAMS');
2467
+ }
2468
+ const query = {};
2469
+ if (params.refreshToken) {
2470
+ query.refreshTokenHash = await hashToken(params.refreshToken);
2471
+ }
2472
+ if (params.sessionId) {
2473
+ query._id = params.sessionId;
2474
+ }
2475
+ const result = await Session.deleteOne(query);
2476
+ if (result.deletedCount === 0) {
2477
+ logger.warn('[deleteSession] No session found to delete');
2478
+ }
2479
+ return result;
2480
+ }
2481
+ catch (error) {
2482
+ logger.error('[deleteSession] Error deleting session:', error);
2483
+ throw new SessionError('Failed to delete session', 'DELETE_SESSION_FAILED');
2484
+ }
2485
+ }
2486
+ /**
2487
+ * Deletes all sessions for a user
2488
+ */
2489
+ async function deleteAllUserSessions(userId, options = {}) {
2490
+ try {
2491
+ if (!userId) {
2492
+ throw new SessionError('User ID is required', 'INVALID_USER_ID');
2493
+ }
2494
+ const userIdString = typeof userId === 'object' && userId !== null ? userId.userId : userId;
2495
+ if (!mongoose.Types.ObjectId.isValid(userIdString)) {
2496
+ throw new SessionError('Invalid user ID format', 'INVALID_USER_ID_FORMAT');
2497
+ }
2498
+ const query = { user: userIdString };
2499
+ if (options.excludeCurrentSession && options.currentSessionId) {
2500
+ query._id = { $ne: options.currentSessionId };
2501
+ }
2502
+ const result = await Session.deleteMany(query);
2503
+ if (result.deletedCount && result.deletedCount > 0) {
2504
+ logger.debug(`[deleteAllUserSessions] Deleted ${result.deletedCount} sessions for user ${userIdString}.`);
2505
+ }
2506
+ return result;
2507
+ }
2508
+ catch (error) {
2509
+ logger.error('[deleteAllUserSessions] Error deleting user sessions:', error);
2510
+ throw new SessionError('Failed to delete user sessions', 'DELETE_ALL_SESSIONS_FAILED');
2511
+ }
2512
+ }
2513
+ /**
2514
+ * Generates a refresh token for a session
2515
+ */
2516
+ async function generateRefreshToken(session) {
2517
+ if (!session || !session.user) {
2518
+ throw new SessionError('Invalid session object', 'INVALID_SESSION');
2519
+ }
2520
+ try {
2521
+ const expiresIn = session.expiration ? session.expiration.getTime() : Date.now() + expires;
2522
+ if (!session.expiration) {
2523
+ session.expiration = new Date(expiresIn);
2524
+ }
2525
+ const refreshToken = await signPayload({
2526
+ payload: {
2527
+ id: session.user,
2528
+ sessionId: session._id,
2529
+ },
2530
+ secret: process.env.JWT_REFRESH_SECRET,
2531
+ expirationTime: Math.floor((expiresIn - Date.now()) / 1000),
2532
+ });
2533
+ session.refreshTokenHash = await hashToken(refreshToken);
2534
+ await session.save();
2535
+ return refreshToken;
2536
+ }
2537
+ catch (error) {
2538
+ logger.error('[generateRefreshToken] Error generating refresh token:', error);
2539
+ throw new SessionError('Failed to generate refresh token', 'GENERATE_TOKEN_FAILED');
2540
+ }
2541
+ }
2542
+ /**
2543
+ * Counts active sessions for a user
2544
+ */
2545
+ async function countActiveSessions(userId) {
2546
+ try {
2547
+ if (!userId) {
2548
+ throw new SessionError('User ID is required', 'INVALID_USER_ID');
2549
+ }
2550
+ return await Session.countDocuments({
2551
+ user: userId,
2552
+ expiration: { $gt: new Date() },
2553
+ });
2554
+ }
2555
+ catch (error) {
2556
+ logger.error('[countActiveSessions] Error counting active sessions:', error);
2557
+ throw new SessionError('Failed to count active sessions', 'COUNT_SESSIONS_FAILED');
2558
+ }
2559
+ }
2560
+ return {
2561
+ findSession,
2562
+ SessionError,
2563
+ deleteSession,
2564
+ createSession,
2565
+ updateExpiration,
2566
+ countActiveSessions,
2567
+ generateRefreshToken,
2568
+ deleteAllUserSessions,
2569
+ };
2570
+ }
2571
+
2572
+ // Factory function that takes mongoose instance and returns the methods
2573
+ function createTokenMethods(mongoose) {
2574
+ /**
2575
+ * Creates a new Token instance.
2576
+ */
2577
+ async function createToken(tokenData) {
2578
+ try {
2579
+ const Token = mongoose.models.Token;
2580
+ const currentTime = new Date();
2581
+ const expiresAt = new Date(currentTime.getTime() + tokenData.expiresIn * 1000);
2582
+ const newTokenData = {
2583
+ ...tokenData,
2584
+ createdAt: currentTime,
2585
+ expiresAt,
2586
+ };
2587
+ return await Token.create(newTokenData);
2588
+ }
2589
+ catch (error) {
2590
+ logger.debug('An error occurred while creating token:', error);
2591
+ throw error;
2592
+ }
2593
+ }
2594
+ /**
2595
+ * Updates a Token document that matches the provided query.
2596
+ */
2597
+ async function updateToken(query, updateData) {
2598
+ try {
2599
+ const Token = mongoose.models.Token;
2600
+ return await Token.findOneAndUpdate(query, updateData, { new: true });
2601
+ }
2602
+ catch (error) {
2603
+ logger.debug('An error occurred while updating token:', error);
2604
+ throw error;
2605
+ }
2606
+ }
2607
+ /**
2608
+ * Deletes all Token documents that match the provided token, user ID, or email.
2609
+ */
2610
+ async function deleteTokens(query) {
2611
+ try {
2612
+ const Token = mongoose.models.Token;
2613
+ return await Token.deleteMany({
2614
+ $or: [
2615
+ { userId: query.userId },
2616
+ { token: query.token },
2617
+ { email: query.email },
2618
+ { identifier: query.identifier },
2619
+ ],
2620
+ });
2621
+ }
2622
+ catch (error) {
2623
+ logger.debug('An error occurred while deleting tokens:', error);
2624
+ throw error;
2625
+ }
2626
+ }
2627
+ /**
2628
+ * Finds a Token document that matches the provided query.
2629
+ */
2630
+ async function findToken(query) {
2631
+ try {
2632
+ const Token = mongoose.models.Token;
2633
+ const conditions = [];
2634
+ if (query.userId) {
2635
+ conditions.push({ userId: query.userId });
2636
+ }
2637
+ if (query.token) {
2638
+ conditions.push({ token: query.token });
2639
+ }
2640
+ if (query.email) {
2641
+ conditions.push({ email: query.email });
2642
+ }
2643
+ if (query.identifier) {
2644
+ conditions.push({ identifier: query.identifier });
2645
+ }
2646
+ const token = await Token.findOne({
2647
+ $and: conditions,
2648
+ }).lean();
2649
+ return token;
2650
+ }
2651
+ catch (error) {
2652
+ logger.debug('An error occurred while finding token:', error);
2653
+ throw error;
2654
+ }
2655
+ }
2656
+ // Return all methods
2657
+ return {
2658
+ findToken,
2659
+ createToken,
2660
+ updateToken,
2661
+ deleteTokens,
2662
+ };
2663
+ }
2664
+
2665
+ // Factory function that takes mongoose instance and returns the methods
2666
+ function createRoleMethods(mongoose) {
2667
+ /**
2668
+ * Initialize default roles in the system.
2669
+ * Creates the default roles (ADMIN, USER) if they don't exist in the database.
2670
+ * Updates existing roles with new permission types if they're missing.
2671
+ */
2672
+ async function initializeRoles() {
2673
+ const Role = mongoose.models.Role;
2674
+ for (const roleName of [librechatDataProvider.SystemRoles.ADMIN, librechatDataProvider.SystemRoles.USER]) {
2675
+ let role = await Role.findOne({ name: roleName });
2676
+ const defaultPerms = librechatDataProvider.roleDefaults[roleName].permissions;
2677
+ if (!role) {
2678
+ // Create new role if it doesn't exist.
2679
+ role = new Role(librechatDataProvider.roleDefaults[roleName]);
2680
+ }
2681
+ else {
2682
+ // Ensure role.permissions is defined.
2683
+ role.permissions = role.permissions || {};
2684
+ // For each permission type in defaults, add it if missing.
2685
+ for (const permType of Object.keys(defaultPerms)) {
2686
+ if (role.permissions[permType] == null) {
2687
+ role.permissions[permType] = defaultPerms[permType];
2688
+ }
2689
+ }
2690
+ }
2691
+ await role.save();
2692
+ }
2693
+ }
2694
+ /**
2695
+ * List all roles in the system (for testing purposes)
2696
+ * Returns an array of all roles with their names and permissions
2697
+ */
2698
+ async function listRoles() {
2699
+ const Role = mongoose.models.Role;
2700
+ return await Role.find({}).select('name permissions').lean();
2701
+ }
2702
+ // Return all methods you want to expose
2703
+ return {
2704
+ listRoles,
2705
+ initializeRoles,
2706
+ };
2707
+ }
2708
+
2709
+ /**
2710
+ * Formats a date in YYYY-MM-DD format
2711
+ */
2712
+ const formatDate = (date) => {
2713
+ return date.toISOString().split('T')[0];
2714
+ };
2715
+ // Factory function that takes mongoose instance and returns the methods
2716
+ function createMemoryMethods(mongoose) {
2717
+ const MemoryEntry = mongoose.models.MemoryEntry;
2718
+ /**
2719
+ * Creates a new memory entry for a user
2720
+ * Throws an error if a memory with the same key already exists
2721
+ */
2722
+ async function createMemory({ userId, key, value, tokenCount = 0, }) {
2723
+ try {
2724
+ if ((key === null || key === void 0 ? void 0 : key.toLowerCase()) === 'nothing') {
2725
+ return { ok: false };
2726
+ }
2727
+ const existingMemory = await MemoryEntry.findOne({ userId, key });
2728
+ if (existingMemory) {
2729
+ throw new Error('Memory with this key already exists');
2730
+ }
2731
+ await MemoryEntry.create({
2732
+ userId,
2733
+ key,
2734
+ value,
2735
+ tokenCount,
2736
+ updated_at: new Date(),
2737
+ });
2738
+ return { ok: true };
2739
+ }
2740
+ catch (error) {
2741
+ throw new Error(`Failed to create memory: ${error instanceof Error ? error.message : 'Unknown error'}`);
2742
+ }
2743
+ }
2744
+ /**
2745
+ * Sets or updates a memory entry for a user
2746
+ */
2747
+ async function setMemory({ userId, key, value, tokenCount = 0, }) {
2748
+ try {
2749
+ if ((key === null || key === void 0 ? void 0 : key.toLowerCase()) === 'nothing') {
2750
+ return { ok: false };
2751
+ }
2752
+ await MemoryEntry.findOneAndUpdate({ userId, key }, {
2753
+ value,
2754
+ tokenCount,
2755
+ updated_at: new Date(),
2756
+ }, {
2757
+ upsert: true,
2758
+ new: true,
2759
+ });
2760
+ return { ok: true };
2761
+ }
2762
+ catch (error) {
2763
+ throw new Error(`Failed to set memory: ${error instanceof Error ? error.message : 'Unknown error'}`);
2764
+ }
2765
+ }
2766
+ /**
2767
+ * Deletes a specific memory entry for a user
2768
+ */
2769
+ async function deleteMemory({ userId, key }) {
2770
+ try {
2771
+ const result = await MemoryEntry.findOneAndDelete({ userId, key });
2772
+ return { ok: !!result };
2773
+ }
2774
+ catch (error) {
2775
+ throw new Error(`Failed to delete memory: ${error instanceof Error ? error.message : 'Unknown error'}`);
2776
+ }
2777
+ }
2778
+ /**
2779
+ * Gets all memory entries for a user
2780
+ */
2781
+ async function getAllUserMemories(userId) {
2782
+ try {
2783
+ return (await MemoryEntry.find({ userId }).lean());
2784
+ }
2785
+ catch (error) {
2786
+ throw new Error(`Failed to get all memories: ${error instanceof Error ? error.message : 'Unknown error'}`);
2787
+ }
2788
+ }
2789
+ /**
2790
+ * Gets and formats all memories for a user in two different formats
2791
+ */
2792
+ async function getFormattedMemories({ userId, }) {
2793
+ try {
2794
+ const memories = await getAllUserMemories(userId);
2795
+ if (!memories || memories.length === 0) {
2796
+ return { withKeys: '', withoutKeys: '', totalTokens: 0 };
2797
+ }
2798
+ const sortedMemories = memories.sort((a, b) => new Date(a.updated_at).getTime() - new Date(b.updated_at).getTime());
2799
+ const totalTokens = sortedMemories.reduce((sum, memory) => {
2800
+ return sum + (memory.tokenCount || 0);
2801
+ }, 0);
2802
+ const withKeys = sortedMemories
2803
+ .map((memory, index) => {
2804
+ const date = formatDate(new Date(memory.updated_at));
2805
+ const tokenInfo = memory.tokenCount ? ` [${memory.tokenCount} tokens]` : '';
2806
+ return `${index + 1}. [${date}]. ["key": "${memory.key}"]${tokenInfo}. ["value": "${memory.value}"]`;
2807
+ })
2808
+ .join('\n\n');
2809
+ const withoutKeys = sortedMemories
2810
+ .map((memory, index) => {
2811
+ const date = formatDate(new Date(memory.updated_at));
2812
+ return `${index + 1}. [${date}]. ${memory.value}`;
2813
+ })
2814
+ .join('\n\n');
2815
+ return { withKeys, withoutKeys, totalTokens };
2816
+ }
2817
+ catch (error) {
2818
+ logger.error('Failed to get formatted memories:', error);
2819
+ return { withKeys: '', withoutKeys: '', totalTokens: 0 };
2820
+ }
2821
+ }
2822
+ return {
2823
+ setMemory,
2824
+ createMemory,
2825
+ deleteMemory,
2826
+ getAllUserMemories,
2827
+ getFormattedMemories,
2828
+ };
2829
+ }
2830
+
2831
+ class ShareServiceError extends Error {
2832
+ constructor(message, code) {
2833
+ super(message);
2834
+ this.name = 'ShareServiceError';
2835
+ this.code = code;
2836
+ }
2837
+ }
2838
+ function memoizedAnonymizeId(prefix) {
2839
+ const memo = new Map();
2840
+ return (id) => {
2841
+ if (!memo.has(id)) {
2842
+ memo.set(id, `${prefix}_${nanoid.nanoid()}`);
2843
+ }
2844
+ return memo.get(id);
2845
+ };
2846
+ }
2847
+ const anonymizeConvoId = memoizedAnonymizeId('convo');
2848
+ const anonymizeAssistantId = memoizedAnonymizeId('a');
2849
+ const anonymizeMessageId = (id) => id === librechatDataProvider.Constants.NO_PARENT ? id : memoizedAnonymizeId('msg')(id);
2850
+ function anonymizeConvo(conversation) {
2851
+ if (!conversation) {
2852
+ return null;
2853
+ }
2854
+ const newConvo = { ...conversation };
2855
+ if (newConvo.assistant_id) {
2856
+ newConvo.assistant_id = anonymizeAssistantId(newConvo.assistant_id);
2857
+ }
2858
+ return newConvo;
2859
+ }
2860
+ function anonymizeMessages(messages, newConvoId) {
2861
+ if (!Array.isArray(messages)) {
2862
+ return [];
2863
+ }
2864
+ const idMap = new Map();
2865
+ return messages.map((message) => {
2866
+ var _a, _b;
2867
+ const newMessageId = anonymizeMessageId(message.messageId);
2868
+ idMap.set(message.messageId, newMessageId);
2869
+ const anonymizedAttachments = (_a = message.attachments) === null || _a === void 0 ? void 0 : _a.map((attachment) => {
2870
+ return {
2871
+ ...attachment,
2872
+ messageId: newMessageId,
2873
+ conversationId: newConvoId,
2874
+ };
2875
+ });
2876
+ return {
2877
+ ...message,
2878
+ messageId: newMessageId,
2879
+ parentMessageId: idMap.get(message.parentMessageId || '') ||
2880
+ anonymizeMessageId(message.parentMessageId || ''),
2881
+ conversationId: newConvoId,
2882
+ model: ((_b = message.model) === null || _b === void 0 ? void 0 : _b.startsWith('asst_'))
2883
+ ? anonymizeAssistantId(message.model)
2884
+ : message.model,
2885
+ attachments: anonymizedAttachments,
2886
+ };
2887
+ });
2888
+ }
2889
+ /** Factory function that takes mongoose instance and returns the methods */
2890
+ function createShareMethods(mongoose) {
2891
+ /**
2892
+ * Get shared messages for a public share link
2893
+ */
2894
+ async function getSharedMessages(shareId) {
2895
+ try {
2896
+ const SharedLink = mongoose.models.SharedLink;
2897
+ const share = (await SharedLink.findOne({ shareId, isPublic: true })
2898
+ .populate({
2899
+ path: 'messages',
2900
+ select: '-_id -__v -user',
2901
+ })
2902
+ .select('-_id -__v -user')
2903
+ .lean());
2904
+ if (!(share === null || share === void 0 ? void 0 : share.conversationId) || !share.isPublic) {
2905
+ return null;
2906
+ }
2907
+ const newConvoId = anonymizeConvoId(share.conversationId);
2908
+ const result = {
2909
+ shareId: share.shareId || shareId,
2910
+ title: share.title,
2911
+ isPublic: share.isPublic,
2912
+ createdAt: share.createdAt,
2913
+ updatedAt: share.updatedAt,
2914
+ conversationId: newConvoId,
2915
+ messages: anonymizeMessages(share.messages, newConvoId),
2916
+ };
2917
+ return result;
2918
+ }
2919
+ catch (error) {
2920
+ logger.error('[getSharedMessages] Error getting share link', {
2921
+ error: error instanceof Error ? error.message : 'Unknown error',
2922
+ shareId,
2923
+ });
2924
+ throw new ShareServiceError('Error getting share link', 'SHARE_FETCH_ERROR');
2925
+ }
2926
+ }
2927
+ /**
2928
+ * Get shared links for a specific user with pagination and search
2929
+ */
2930
+ async function getSharedLinks(user, pageParam, pageSize = 10, isPublic = true, sortBy = 'createdAt', sortDirection = 'desc', search) {
2931
+ var _a;
2932
+ try {
2933
+ const SharedLink = mongoose.models.SharedLink;
2934
+ const Conversation = mongoose.models.Conversation;
2935
+ const query = { user, isPublic };
2936
+ if (pageParam) {
2937
+ if (sortDirection === 'desc') {
2938
+ query[sortBy] = { $lt: pageParam };
2939
+ }
2940
+ else {
2941
+ query[sortBy] = { $gt: pageParam };
2942
+ }
2943
+ }
2944
+ if (search && search.trim()) {
2945
+ try {
2946
+ const searchResults = await Conversation.meiliSearch(search);
2947
+ if (!((_a = searchResults === null || searchResults === void 0 ? void 0 : searchResults.hits) === null || _a === void 0 ? void 0 : _a.length)) {
2948
+ return {
2949
+ links: [],
2950
+ nextCursor: undefined,
2951
+ hasNextPage: false,
2952
+ };
2953
+ }
2954
+ const conversationIds = searchResults.hits.map((hit) => hit.conversationId);
2955
+ query['conversationId'] = { $in: conversationIds };
2956
+ }
2957
+ catch (searchError) {
2958
+ logger.error('[getSharedLinks] Meilisearch error', {
2959
+ error: searchError instanceof Error ? searchError.message : 'Unknown error',
2960
+ user,
2961
+ });
2962
+ return {
2963
+ links: [],
2964
+ nextCursor: undefined,
2965
+ hasNextPage: false,
2966
+ };
2967
+ }
2968
+ }
2969
+ const sort = {};
2970
+ sort[sortBy] = sortDirection === 'desc' ? -1 : 1;
2971
+ const sharedLinks = await SharedLink.find(query)
2972
+ .sort(sort)
2973
+ .limit(pageSize + 1)
2974
+ .select('-__v -user')
2975
+ .lean();
2976
+ const hasNextPage = sharedLinks.length > pageSize;
2977
+ const links = sharedLinks.slice(0, pageSize);
2978
+ const nextCursor = hasNextPage
2979
+ ? links[links.length - 1][sortBy]
2980
+ : undefined;
2981
+ return {
2982
+ links: links.map((link) => ({
2983
+ shareId: link.shareId || '',
2984
+ title: (link === null || link === void 0 ? void 0 : link.title) || 'Untitled',
2985
+ isPublic: link.isPublic,
2986
+ createdAt: link.createdAt || new Date(),
2987
+ conversationId: link.conversationId,
2988
+ })),
2989
+ nextCursor,
2990
+ hasNextPage,
2991
+ };
2992
+ }
2993
+ catch (error) {
2994
+ logger.error('[getSharedLinks] Error getting shares', {
2995
+ error: error instanceof Error ? error.message : 'Unknown error',
2996
+ user,
2997
+ });
2998
+ throw new ShareServiceError('Error getting shares', 'SHARES_FETCH_ERROR');
2999
+ }
3000
+ }
3001
+ /**
3002
+ * Delete all shared links for a user
3003
+ */
3004
+ async function deleteAllSharedLinks(user) {
3005
+ try {
3006
+ const SharedLink = mongoose.models.SharedLink;
3007
+ const result = await SharedLink.deleteMany({ user });
3008
+ return {
3009
+ message: 'All shared links deleted successfully',
3010
+ deletedCount: result.deletedCount,
3011
+ };
3012
+ }
3013
+ catch (error) {
3014
+ logger.error('[deleteAllSharedLinks] Error deleting shared links', {
3015
+ error: error instanceof Error ? error.message : 'Unknown error',
3016
+ user,
3017
+ });
3018
+ throw new ShareServiceError('Error deleting shared links', 'BULK_DELETE_ERROR');
3019
+ }
3020
+ }
3021
+ /**
3022
+ * Create a new shared link for a conversation
3023
+ */
3024
+ async function createSharedLink(user, conversationId) {
3025
+ if (!user || !conversationId) {
3026
+ throw new ShareServiceError('Missing required parameters', 'INVALID_PARAMS');
3027
+ }
3028
+ try {
3029
+ const Message = mongoose.models.Message;
3030
+ const SharedLink = mongoose.models.SharedLink;
3031
+ const Conversation = mongoose.models.Conversation;
3032
+ const [existingShare, conversationMessages] = await Promise.all([
3033
+ SharedLink.findOne({ conversationId, user, isPublic: true })
3034
+ .select('-_id -__v -user')
3035
+ .lean(),
3036
+ Message.find({ conversationId, user }).sort({ createdAt: 1 }).lean(),
3037
+ ]);
3038
+ if (existingShare && existingShare.isPublic) {
3039
+ logger.error('[createSharedLink] Share already exists', {
3040
+ user,
3041
+ conversationId,
3042
+ });
3043
+ throw new ShareServiceError('Share already exists', 'SHARE_EXISTS');
3044
+ }
3045
+ else if (existingShare) {
3046
+ await SharedLink.deleteOne({ conversationId, user });
3047
+ }
3048
+ const conversation = (await Conversation.findOne({ conversationId, user }).lean());
3049
+ // Check if user owns the conversation
3050
+ if (!conversation) {
3051
+ throw new ShareServiceError('Conversation not found or access denied', 'CONVERSATION_NOT_FOUND');
3052
+ }
3053
+ // Check if there are any messages to share
3054
+ if (!conversationMessages || conversationMessages.length === 0) {
3055
+ throw new ShareServiceError('No messages to share', 'NO_MESSAGES');
3056
+ }
3057
+ const title = conversation.title || 'Untitled';
3058
+ const shareId = nanoid.nanoid();
3059
+ await SharedLink.create({
3060
+ shareId,
3061
+ conversationId,
3062
+ messages: conversationMessages,
3063
+ title,
3064
+ user,
3065
+ });
3066
+ return { shareId, conversationId };
3067
+ }
3068
+ catch (error) {
3069
+ if (error instanceof ShareServiceError) {
3070
+ throw error;
3071
+ }
3072
+ logger.error('[createSharedLink] Error creating shared link', {
3073
+ error: error instanceof Error ? error.message : 'Unknown error',
3074
+ user,
3075
+ conversationId,
3076
+ });
3077
+ throw new ShareServiceError('Error creating shared link', 'SHARE_CREATE_ERROR');
3078
+ }
3079
+ }
3080
+ /**
3081
+ * Get a shared link for a conversation
3082
+ */
3083
+ async function getSharedLink(user, conversationId) {
3084
+ if (!user || !conversationId) {
3085
+ throw new ShareServiceError('Missing required parameters', 'INVALID_PARAMS');
3086
+ }
3087
+ try {
3088
+ const SharedLink = mongoose.models.SharedLink;
3089
+ const share = (await SharedLink.findOne({ conversationId, user, isPublic: true })
3090
+ .select('shareId -_id')
3091
+ .lean());
3092
+ if (!share) {
3093
+ return { shareId: null, success: false };
3094
+ }
3095
+ return { shareId: share.shareId || null, success: true };
3096
+ }
3097
+ catch (error) {
3098
+ logger.error('[getSharedLink] Error getting shared link', {
3099
+ error: error instanceof Error ? error.message : 'Unknown error',
3100
+ user,
3101
+ conversationId,
3102
+ });
3103
+ throw new ShareServiceError('Error getting shared link', 'SHARE_FETCH_ERROR');
3104
+ }
3105
+ }
3106
+ /**
3107
+ * Update a shared link with new messages
3108
+ */
3109
+ async function updateSharedLink(user, shareId) {
3110
+ if (!user || !shareId) {
3111
+ throw new ShareServiceError('Missing required parameters', 'INVALID_PARAMS');
3112
+ }
3113
+ try {
3114
+ const SharedLink = mongoose.models.SharedLink;
3115
+ const Message = mongoose.models.Message;
3116
+ const share = (await SharedLink.findOne({ shareId, user })
3117
+ .select('-_id -__v -user')
3118
+ .lean());
3119
+ if (!share) {
3120
+ throw new ShareServiceError('Share not found', 'SHARE_NOT_FOUND');
3121
+ }
3122
+ const updatedMessages = await Message.find({ conversationId: share.conversationId, user })
3123
+ .sort({ createdAt: 1 })
3124
+ .lean();
3125
+ const newShareId = nanoid.nanoid();
3126
+ const update = {
3127
+ messages: updatedMessages,
3128
+ user,
3129
+ shareId: newShareId,
3130
+ };
3131
+ const updatedShare = (await SharedLink.findOneAndUpdate({ shareId, user }, update, {
3132
+ new: true,
3133
+ upsert: false,
3134
+ runValidators: true,
3135
+ }).lean());
3136
+ if (!updatedShare) {
3137
+ throw new ShareServiceError('Share update failed', 'SHARE_UPDATE_ERROR');
3138
+ }
3139
+ anonymizeConvo(updatedShare);
3140
+ return { shareId: newShareId, conversationId: updatedShare.conversationId };
3141
+ }
3142
+ catch (error) {
3143
+ logger.error('[updateSharedLink] Error updating shared link', {
3144
+ error: error instanceof Error ? error.message : 'Unknown error',
3145
+ user,
3146
+ shareId,
3147
+ });
3148
+ throw new ShareServiceError(error instanceof ShareServiceError ? error.message : 'Error updating shared link', error instanceof ShareServiceError ? error.code : 'SHARE_UPDATE_ERROR');
3149
+ }
3150
+ }
3151
+ /**
3152
+ * Delete a shared link
3153
+ */
3154
+ async function deleteSharedLink(user, shareId) {
3155
+ if (!user || !shareId) {
3156
+ throw new ShareServiceError('Missing required parameters', 'INVALID_PARAMS');
3157
+ }
3158
+ try {
3159
+ const SharedLink = mongoose.models.SharedLink;
3160
+ const result = await SharedLink.findOneAndDelete({ shareId, user }).lean();
3161
+ if (!result) {
3162
+ return null;
3163
+ }
3164
+ return {
3165
+ success: true,
3166
+ shareId,
3167
+ message: 'Share deleted successfully',
3168
+ };
3169
+ }
3170
+ catch (error) {
3171
+ logger.error('[deleteSharedLink] Error deleting shared link', {
3172
+ error: error instanceof Error ? error.message : 'Unknown error',
3173
+ user,
3174
+ shareId,
3175
+ });
3176
+ throw new ShareServiceError('Error deleting shared link', 'SHARE_DELETE_ERROR');
3177
+ }
3178
+ }
3179
+ // Return all methods
3180
+ return {
3181
+ getSharedLink,
3182
+ getSharedLinks,
3183
+ createSharedLink,
3184
+ updateSharedLink,
3185
+ deleteSharedLink,
3186
+ getSharedMessages,
3187
+ deleteAllSharedLinks,
3188
+ };
3189
+ }
3190
+
3191
+ // Factory function that takes mongoose instance and returns the methods
3192
+ function createPluginAuthMethods(mongoose) {
3193
+ const PluginAuth = mongoose.models.PluginAuth;
3194
+ /**
3195
+ * Finds a single plugin auth entry by userId and authField
3196
+ */
3197
+ async function findOnePluginAuth({ userId, authField, }) {
3198
+ try {
3199
+ return await PluginAuth.findOne({ userId, authField }).lean();
3200
+ }
3201
+ catch (error) {
3202
+ throw new Error(`Failed to find plugin auth: ${error instanceof Error ? error.message : 'Unknown error'}`);
3203
+ }
3204
+ }
3205
+ /**
3206
+ * Finds multiple plugin auth entries by userId and pluginKeys
3207
+ */
3208
+ async function findPluginAuthsByKeys({ userId, pluginKeys, }) {
3209
+ try {
3210
+ if (!pluginKeys || pluginKeys.length === 0) {
3211
+ return [];
3212
+ }
3213
+ return await PluginAuth.find({
3214
+ userId,
3215
+ pluginKey: { $in: pluginKeys },
3216
+ }).lean();
3217
+ }
3218
+ catch (error) {
3219
+ throw new Error(`Failed to find plugin auths: ${error instanceof Error ? error.message : 'Unknown error'}`);
3220
+ }
3221
+ }
3222
+ /**
3223
+ * Updates or creates a plugin auth entry
3224
+ */
3225
+ async function updatePluginAuth({ userId, authField, pluginKey, value, }) {
3226
+ try {
3227
+ const existingAuth = await PluginAuth.findOne({ userId, pluginKey, authField }).lean();
3228
+ if (existingAuth) {
3229
+ return await PluginAuth.findOneAndUpdate({ userId, pluginKey, authField }, { $set: { value } }, { new: true, upsert: true }).lean();
3230
+ }
3231
+ else {
3232
+ const newPluginAuth = await new PluginAuth({
3233
+ userId,
3234
+ authField,
3235
+ value,
3236
+ pluginKey,
3237
+ });
3238
+ await newPluginAuth.save();
3239
+ return newPluginAuth.toObject();
3240
+ }
3241
+ }
3242
+ catch (error) {
3243
+ throw new Error(`Failed to update plugin auth: ${error instanceof Error ? error.message : 'Unknown error'}`);
3244
+ }
3245
+ }
3246
+ /**
3247
+ * Deletes plugin auth entries based on provided parameters
3248
+ */
3249
+ async function deletePluginAuth({ userId, authField, pluginKey, all = false, }) {
3250
+ try {
3251
+ if (all) {
3252
+ const filter = { userId };
3253
+ if (pluginKey) {
3254
+ filter.pluginKey = pluginKey;
3255
+ }
3256
+ return await PluginAuth.deleteMany(filter);
3257
+ }
3258
+ if (!authField) {
3259
+ throw new Error('authField is required when all is false');
3260
+ }
3261
+ return await PluginAuth.deleteOne({ userId, authField });
3262
+ }
3263
+ catch (error) {
3264
+ throw new Error(`Failed to delete plugin auth: ${error instanceof Error ? error.message : 'Unknown error'}`);
3265
+ }
3266
+ }
3267
+ /**
3268
+ * Deletes all plugin auth entries for a user
3269
+ */
3270
+ async function deleteAllUserPluginAuths(userId) {
3271
+ try {
3272
+ return await PluginAuth.deleteMany({ userId });
3273
+ }
3274
+ catch (error) {
3275
+ throw new Error(`Failed to delete all user plugin auths: ${error instanceof Error ? error.message : 'Unknown error'}`);
3276
+ }
3277
+ }
3278
+ return {
3279
+ findOnePluginAuth,
3280
+ findPluginAuthsByKeys,
3281
+ updatePluginAuth,
3282
+ deletePluginAuth,
3283
+ deleteAllUserPluginAuths,
3284
+ };
3285
+ }
3286
+
3287
+ /**
3288
+ * Creates all database methods for all collections
3289
+ */
3290
+ function createMethods(mongoose) {
3291
+ return {
3292
+ ...createUserMethods(mongoose),
3293
+ ...createSessionMethods(mongoose),
3294
+ ...createTokenMethods(mongoose),
3295
+ ...createRoleMethods(mongoose),
3296
+ ...createMemoryMethods(mongoose),
3297
+ ...createShareMethods(mongoose),
3298
+ ...createPluginAuthMethods(mongoose),
3299
+ };
3300
+ }
3301
+
1153
3302
  exports.actionSchema = Action;
1154
3303
  exports.agentSchema = agentSchema;
1155
3304
  exports.assistantSchema = assistantSchema;
@@ -1158,8 +3307,14 @@ exports.bannerSchema = bannerSchema;
1158
3307
  exports.categoriesSchema = categoriesSchema;
1159
3308
  exports.conversationTagSchema = conversationTag;
1160
3309
  exports.convoSchema = convoSchema;
3310
+ exports.createMethods = createMethods;
3311
+ exports.createModels = createModels;
1161
3312
  exports.fileSchema = file;
3313
+ exports.hashToken = hashToken;
1162
3314
  exports.keySchema = keySchema;
3315
+ exports.logger = logger;
3316
+ exports.meiliLogger = logger$1;
3317
+ exports.memorySchema = MemoryEntrySchema;
1163
3318
  exports.messageSchema = messageSchema;
1164
3319
  exports.pluginAuthSchema = pluginAuthSchema;
1165
3320
  exports.presetSchema = presetSchema;
@@ -1169,8 +3324,9 @@ exports.promptSchema = promptSchema;
1169
3324
  exports.roleSchema = roleSchema;
1170
3325
  exports.sessionSchema = sessionSchema;
1171
3326
  exports.shareSchema = shareSchema;
3327
+ exports.signPayload = signPayload;
1172
3328
  exports.tokenSchema = tokenSchema;
1173
3329
  exports.toolCallSchema = toolCallSchema;
1174
3330
  exports.transactionSchema = transactionSchema;
1175
- exports.userSchema = User;
3331
+ exports.userSchema = userSchema;
1176
3332
  //# sourceMappingURL=index.cjs.map