internxt-crypto 0.0.14 → 1.0.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.
Files changed (144) hide show
  1. package/README.md +44 -72
  2. package/dist/aes-B8TA-JKq.mjs +49 -0
  3. package/dist/aes-B8TA-JKq.mjs.map +1 -0
  4. package/dist/aes-CuW_SPl-.js +67 -0
  5. package/dist/aes-CuW_SPl-.js.map +1 -0
  6. package/dist/asymmetric-crypto.d.mts +8 -31
  7. package/dist/asymmetric-crypto.d.mts.map +1 -1
  8. package/dist/asymmetric-crypto.d.ts +8 -31
  9. package/dist/asymmetric-crypto.d.ts.map +1 -1
  10. package/dist/asymmetric-crypto.js +30 -7
  11. package/dist/asymmetric-crypto.js.map +1 -0
  12. package/dist/asymmetric-crypto.mjs +28 -2
  13. package/dist/asymmetric-crypto.mjs.map +1 -0
  14. package/dist/constants.d.mts +3 -10
  15. package/dist/constants.d.mts.map +1 -1
  16. package/dist/constants.d.ts +3 -10
  17. package/dist/constants.d.ts.map +1 -1
  18. package/dist/constants.js +3 -17
  19. package/dist/constants.js.map +1 -1
  20. package/dist/constants.mjs +3 -10
  21. package/dist/constants.mjs.map +1 -1
  22. package/dist/core-Bj26rNdA.js +227 -0
  23. package/dist/core-Bj26rNdA.js.map +1 -0
  24. package/dist/core-pEGygy6S.mjs +173 -0
  25. package/dist/core-pEGygy6S.mjs.map +1 -0
  26. package/dist/derive-key.d.mts +1 -74
  27. package/dist/derive-key.d.mts.map +1 -1
  28. package/dist/derive-key.d.ts +1 -74
  29. package/dist/derive-key.d.ts.map +1 -1
  30. package/dist/derive-key.js +3 -11
  31. package/dist/derive-key.mjs +2 -2
  32. package/dist/derive-password.d.mts +22 -0
  33. package/dist/derive-password.d.mts.map +1 -0
  34. package/dist/derive-password.d.ts +22 -0
  35. package/dist/derive-password.d.ts.map +1 -0
  36. package/dist/derive-password.js +5 -0
  37. package/dist/derive-password.mjs +3 -0
  38. package/dist/deriveKeysFromKey-C4McqO6_.js +47 -0
  39. package/dist/deriveKeysFromKey-C4McqO6_.js.map +1 -0
  40. package/dist/deriveKeysFromKey-DPU_h7wr.mjs +35 -0
  41. package/dist/deriveKeysFromKey-DPU_h7wr.mjs.map +1 -0
  42. package/dist/{deriveKeysFromPassword-BYaiSGKL.js → deriveKeysFromPassword-C7xAGGsh.js} +5 -172
  43. package/dist/deriveKeysFromPassword-C7xAGGsh.js.map +1 -0
  44. package/dist/{deriveKeysFromPassword-XIwzErlL.mjs → deriveKeysFromPassword-DXgSvTNC.mjs} +6 -125
  45. package/dist/deriveKeysFromPassword-DXgSvTNC.mjs.map +1 -0
  46. package/dist/email-crypto.d.mts +24 -46
  47. package/dist/email-crypto.d.mts.map +1 -1
  48. package/dist/email-crypto.d.ts +24 -46
  49. package/dist/email-crypto.d.ts.map +1 -1
  50. package/dist/email-crypto.js +121 -12
  51. package/dist/email-crypto.js.map +1 -0
  52. package/dist/email-crypto.mjs +115 -2
  53. package/dist/email-crypto.mjs.map +1 -0
  54. package/dist/email-search.d.mts.map +1 -1
  55. package/dist/email-search.d.ts.map +1 -1
  56. package/dist/email-search.js +25 -597
  57. package/dist/email-search.mjs +2 -573
  58. package/dist/{emailEncryptionKey-B9xHw1h_.mjs → emailEncryptionKey-BtSPYd9M.mjs} +22 -45
  59. package/dist/emailEncryptionKey-BtSPYd9M.mjs.map +1 -0
  60. package/dist/{emailEncryptionKey-CQNe5W_T.js → emailEncryptionKey-C4X1Bwy4.js} +22 -45
  61. package/dist/emailEncryptionKey-C4X1Bwy4.js.map +1 -0
  62. package/dist/{genID-3Er5IowC.mjs → genID-D08K7JPr.mjs} +4 -40
  63. package/dist/genID-D08K7JPr.mjs.map +1 -0
  64. package/dist/{genID-YJSl3YhL.js → genID-cWOPmspk.js} +2 -50
  65. package/dist/genID-cWOPmspk.js.map +1 -0
  66. package/dist/hash.d.mts +24 -36
  67. package/dist/hash.d.mts.map +1 -1
  68. package/dist/hash.d.ts +24 -36
  69. package/dist/hash.d.ts.map +1 -1
  70. package/dist/hash.js +88 -10
  71. package/dist/hash.js.map +1 -0
  72. package/dist/hash.mjs +82 -2
  73. package/dist/hash.mjs.map +1 -0
  74. package/dist/index.d.mts +9 -8
  75. package/dist/index.d.mts.map +1 -1
  76. package/dist/index.d.ts +9 -8
  77. package/dist/index.d.ts.map +1 -1
  78. package/dist/index.js +56 -79
  79. package/dist/index.mjs +13 -11
  80. package/dist/keystore-crypto.d.mts +6 -6
  81. package/dist/keystore-crypto.d.mts.map +1 -1
  82. package/dist/keystore-crypto.d.ts +6 -6
  83. package/dist/keystore-crypto.d.ts.map +1 -1
  84. package/dist/keystore-crypto.js +1 -1
  85. package/dist/keystore-crypto.mjs +1 -1
  86. package/dist/post-quantum-crypto.js +49 -4
  87. package/dist/post-quantum-crypto.js.map +1 -0
  88. package/dist/post-quantum-crypto.mjs +46 -2
  89. package/dist/post-quantum-crypto.mjs.map +1 -0
  90. package/dist/search-B9YM3XAA.mjs +587 -0
  91. package/dist/search-B9YM3XAA.mjs.map +1 -0
  92. package/dist/search-DUTm4-rN.js +731 -0
  93. package/dist/search-DUTm4-rN.js.map +1 -0
  94. package/dist/symmetric-crypto.d.mts +11 -40
  95. package/dist/symmetric-crypto.d.mts.map +1 -1
  96. package/dist/symmetric-crypto.d.ts +11 -40
  97. package/dist/symmetric-crypto.d.ts.map +1 -1
  98. package/dist/symmetric-crypto.js +2 -6
  99. package/dist/symmetric-crypto.mjs +2 -2
  100. package/dist/types.d.mts +13 -40
  101. package/dist/types.d.mts.map +1 -1
  102. package/dist/types.d.ts +13 -40
  103. package/dist/types.d.ts.map +1 -1
  104. package/dist/types.js.map +1 -1
  105. package/dist/types.mjs.map +1 -1
  106. package/dist/utils.d.mts +1 -19
  107. package/dist/utils.d.mts.map +1 -1
  108. package/dist/utils.d.ts +1 -19
  109. package/dist/utils.d.ts.map +1 -1
  110. package/dist/utils.js +1 -3
  111. package/dist/utils.mjs +2 -2
  112. package/dist/xwing-CQmQX6hn.mjs +16 -0
  113. package/dist/xwing-CQmQX6hn.mjs.map +1 -0
  114. package/dist/xwing-iRWVRtNE.js +34 -0
  115. package/dist/xwing-iRWVRtNE.js.map +1 -0
  116. package/package.json +4 -3
  117. package/dist/aes-DCb9dJqb.mjs +0 -161
  118. package/dist/aes-DCb9dJqb.mjs.map +0 -1
  119. package/dist/aes-DQo1MyCz.js +0 -203
  120. package/dist/aes-DQo1MyCz.js.map +0 -1
  121. package/dist/deriveKeysFromPassword-BYaiSGKL.js.map +0 -1
  122. package/dist/deriveKeysFromPassword-XIwzErlL.mjs.map +0 -1
  123. package/dist/email-search.js.map +0 -1
  124. package/dist/email-search.mjs.map +0 -1
  125. package/dist/emailEncryptionKey-B9xHw1h_.mjs.map +0 -1
  126. package/dist/emailEncryptionKey-CQNe5W_T.js.map +0 -1
  127. package/dist/emailKeys-C0KhtfNP.js +0 -572
  128. package/dist/emailKeys-C0KhtfNP.js.map +0 -1
  129. package/dist/emailKeys-D4lp9NRv.mjs +0 -488
  130. package/dist/emailKeys-D4lp9NRv.mjs.map +0 -1
  131. package/dist/genID-3Er5IowC.mjs.map +0 -1
  132. package/dist/genID-YJSl3YhL.js.map +0 -1
  133. package/dist/keys-BfcaiAOv.mjs +0 -90
  134. package/dist/keys-BfcaiAOv.mjs.map +0 -1
  135. package/dist/keys-CinT7kEY.js +0 -125
  136. package/dist/keys-CinT7kEY.js.map +0 -1
  137. package/dist/kyber768-SXnIo-Nw.mjs +0 -47
  138. package/dist/kyber768-SXnIo-Nw.mjs.map +0 -1
  139. package/dist/kyber768-WUVc2fIR.js +0 -65
  140. package/dist/kyber768-WUVc2fIR.js.map +0 -1
  141. package/dist/mac-BMb1F0dN.js +0 -170
  142. package/dist/mac-BMb1F0dN.js.map +0 -1
  143. package/dist/mac-ZpRlx8Fs.mjs +0 -116
  144. package/dist/mac-ZpRlx8Fs.mjs.map +0 -1
@@ -1,599 +1,27 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_chunk = require('./chunk-EbLFQX5m.js');
3
- const require_constants = require('./constants.js');
4
- const require_deriveKeysFromPassword = require('./deriveKeysFromPassword-BYaiSGKL.js');
5
- const require_emailKeys = require('./emailKeys-C0KhtfNP.js');
6
- let idb = require("idb");
7
- let flexsearch = require("flexsearch");
2
+ const require_search = require('./search-DUTm4-rN.js');
8
3
 
9
- //#region src/email-search/indexedDB.ts
10
- /**
11
- * Returns IndexedDB database name for the given user
12
- *
13
- * @param userID - The user ID
14
- * @returns The database name
15
- */
16
- const getDatabaseName = (userID) => {
17
- return `ES:${userID}:DB`;
18
- };
19
- /**
20
- * Opens IndexedDB database for the given user
21
- *
22
- * @param userID - The user ID
23
- * @returns The database
24
- */
25
- const openDatabase = async (userID) => {
26
- try {
27
- return (0, idb.openDB)(getDatabaseName(userID), require_constants.DB_VERSION, { upgrade(db) {
28
- if (!db.objectStoreNames.contains(require_constants.DB_LABEL)) db.createObjectStore(require_constants.DB_LABEL, { keyPath: "id" }).createIndex("byTime", "params.createdAt");
29
- } });
30
- } catch (error) {
31
- throw new Error(`Cannot open a database for the user ${userID}`, { cause: error });
32
- }
33
- };
34
- /**
35
- * Closes the IndexedDB database
36
- *
37
- * @param esDB - The database
38
- */
39
- const closeDatabase = (esDB) => {
40
- return esDB.close();
41
- };
42
- /**
43
- * Deletes IndexedDB database for the given user
44
- *
45
- * @param userID - The user ID
46
- * @returns The database
47
- */
48
- const deleteDatabase = async (userID) => {
49
- return (0, idb.deleteDB)(getDatabaseName(userID));
50
- };
51
- /**
52
- * Derives database encryption key for the given user
53
- *
54
- * @param userID - The user ID
55
- * @returns The symmetric key for protecting database
56
- */
57
- const deriveIndexKey = async (baseKey) => {
58
- return require_deriveKeysFromPassword.deriveSymmetricKeyFromContext(require_constants.CONTEXT_INDEX, baseKey);
59
- };
60
- /**
61
- * Encrypts the given email and stores it in the IndexedDB database
62
- *
63
- * @param newEmailToStore - The email for storing
64
- * @param indexKey - The symmetric key for protecting database
65
- * @param esDB - The database
66
- */
67
- const encryptAndStoreEmail = async (newEmailToStore, indexKey, esDB) => {
68
- try {
69
- const aux = require_emailKeys.getAux(newEmailToStore.params, false);
70
- const encryptedEmail = {
71
- enc: await require_emailKeys.encryptEmailContentSymmetricallyWithKey(newEmailToStore.body, indexKey, aux, newEmailToStore.id),
72
- params: newEmailToStore.params,
73
- id: newEmailToStore.id
74
- };
75
- await esDB.put(require_constants.DB_LABEL, encryptedEmail);
76
- } catch (error) {
77
- throw new Error("Cannot encrypt and add the given email to the database", { cause: error });
78
- }
79
- };
80
- /**
81
- * Encrypts the given set of emails and stores it in the IndexedDB database
82
- *
83
- * @param newEmailsToStore - The set of emails for storing
84
- * @param indexKey - The symmetric key key for protecting database
85
- * @param esDB - The database
86
- */
87
- const encryptAndStoreManyEmail = async (newEmailsToStore, indexKey, esDB) => {
88
- try {
89
- const encryptedEmails = await Promise.all(newEmailsToStore.map(async (email) => {
90
- const aux = require_emailKeys.getAux(email.params, false);
91
- return {
92
- enc: await require_emailKeys.encryptEmailContentSymmetricallyWithKey(email.body, indexKey, aux, email.id),
93
- params: email.params,
94
- id: email.id
95
- };
96
- }));
97
- const tr = esDB.transaction(require_constants.DB_LABEL, "readwrite");
98
- await Promise.all([...encryptedEmails.map((encEmail) => tr.store.put(encEmail)), tr.done]);
99
- } catch (error) {
100
- throw new Error("Cannot encrypt and add emails to the database", { cause: error });
101
- }
102
- };
103
- /**
104
- * Decrypts the given email
105
- *
106
- * @param indexKey - The symmetric key key for protecting database
107
- * @param encryptedEmail - The encrypted email
108
- * @returns The decrypted email
109
- */
110
- const decryptEmail = async (indexKey, encryptedEmail) => {
111
- try {
112
- return {
113
- body: await require_emailKeys.decryptEmailSymmetrically(indexKey, require_emailKeys.getAux(encryptedEmail.params, false), encryptedEmail.enc),
114
- params: encryptedEmail.params,
115
- id: encryptedEmail.id
116
- };
117
- } catch (error) {
118
- throw new Error("Cannot decrypt the given email", { cause: error });
119
- }
120
- };
121
- /**
122
- * Fetches the email from the database and decrypts it
123
- *
124
- * @param emailID - The email identifier
125
- * @param indexKey - The symmetric key key for protecting database
126
- * @param encryptedEmail - The encrypted email
127
- * @returns The decrypted email
128
- */
129
- const getAndDecryptEmail = async (emailID, indexKey, esDB) => {
130
- try {
131
- const encryptedEmail = await esDB.get(require_constants.DB_LABEL, emailID);
132
- if (!encryptedEmail) throw new Error(`DB cannot find email with id ${emailID}`);
133
- return decryptEmail(indexKey, encryptedEmail);
134
- } catch (error) {
135
- throw new Error(`Cannot fetch the email ${emailID} from the database`, { cause: error });
136
- }
137
- };
138
- /**
139
- * Fetches all email from the database and decrypts them
140
- *
141
- * @param indexKey - The symmetric key key for protecting database
142
- * @param esDB - The database
143
- * @returns The decrypted emails
144
- */
145
- const getAndDecryptAllEmails = async (indexKey, esDB) => {
146
- try {
147
- const encryptedEmails = await esDB.getAll(require_constants.DB_LABEL);
148
- return (await Promise.all(encryptedEmails.map(async (encEmail) => {
149
- return {
150
- body: await require_emailKeys.decryptEmailSymmetrically(indexKey, require_emailKeys.getAux(encEmail.params, false), encEmail.enc),
151
- params: encEmail.params,
152
- id: encEmail.id
153
- };
154
- }))).filter((email) => email !== null);
155
- } catch (error) {
156
- throw new Error("Cannot fetch and decrypt all emails from the database", { cause: error });
157
- }
158
- };
159
- /**
160
- * Deletes the email from the database
161
- *
162
- * @param emailID - The email identifier
163
- * @param esDB - The database
164
- */
165
- const deleteEmail = async (emailID, esDB) => {
166
- await esDB.delete(require_constants.DB_LABEL, emailID);
167
- };
168
- /**
169
- * Returns the number of stored email
170
- *
171
- * @param esDB - The database
172
- * @returns The number of stored emails
173
- */
174
- const getEmailCount = async (esDB) => {
175
- return await esDB.count(require_constants.DB_LABEL);
176
- };
177
- /**
178
- * Removes the given number of oldests emails from the database
179
- *
180
- * @param emailsToDelete - The number of emails to delete
181
- * @param esDB - The database
182
- */
183
- const deleteOldestEmails = async (emailsToDelete, esDB) => {
184
- try {
185
- const tx = esDB.transaction(require_constants.DB_LABEL, "readwrite");
186
- let cursor = await tx.store.index("byTime").openCursor();
187
- let deletedCount = 0;
188
- while (cursor && deletedCount < emailsToDelete) {
189
- await cursor.delete();
190
- deletedCount++;
191
- cursor = await cursor.continue();
192
- }
193
- await tx.done;
194
- } catch (error) {
195
- throw new Error(`Cannot delete ${emailsToDelete} oldests emails from the database`, { cause: error });
196
- }
197
- };
198
- /**
199
- * Enforces the maximum email number in the database
200
- *
201
- * @param esDB - The database
202
- * @param max - The maximum allowed number of emails
203
- */
204
- const enforceMaxEmailNumber = async (esDB, max) => {
205
- try {
206
- const currentCount = await getEmailCount(esDB);
207
- if (currentCount <= max) return;
208
- await deleteOldestEmails(currentCount - max, esDB);
209
- } catch (error) {
210
- throw new Error(`Cannot enforce the maximum of ${max} emails on the database`, { cause: error });
211
- }
212
- };
213
- /**
214
- * Fetches all emails from the database, decrypts them and sortes the results in the specified order
215
- *
216
- * @param esDB - The database
217
- * @param indexKey - The symmetric key key for protecting database
218
- * @param direction - The order of sorting. If 'next' - oldest first, if 'prev' - newest first
219
- * @returns Decryped emails in the specified order
220
- */
221
- const fetchEmails = async (esDB, indexKey, direction) => {
222
- try {
223
- const index = esDB.transaction(require_constants.DB_LABEL, "readonly").store.index("byTime");
224
- const encryptedEmails = [];
225
- let cursor = await index.openCursor(null, direction);
226
- while (cursor) {
227
- encryptedEmails.push(cursor.value);
228
- cursor = await cursor.continue();
229
- }
230
- return await Promise.all(encryptedEmails.map((encryptedEmail) => decryptEmail(indexKey, encryptedEmail)));
231
- } catch (error) {
232
- throw new Error("Cannot fetch emails from database", { cause: error });
233
- }
234
- };
235
- /**
236
- * Fetches all emails from the database, decrypts them and sortes the results based on the creation time (newest first)
237
- *
238
- * @param esDB - The database
239
- * @param indexKey - The symmetric Uint8Array key for protecting database
240
- * @returns The number of stored emails
241
- */
242
- const getAllEmailsSortedNewestFirst = async (esDB, indexKey) => {
243
- return fetchEmails(esDB, indexKey, "prev");
244
- };
245
- /**
246
- * Fetches all emails from the database, decrypts them and sortes the results based on the creation time (oldest first)
247
- *
248
- * @param esDB - The database
249
- * @param indexKey - The symmetric key for protecting database
250
- * @returns The number of stored emails
251
- */
252
- const getAllEmailsSortedOldestFirst = async (esDB, indexKey) => {
253
- return fetchEmails(esDB, indexKey, "next");
254
- };
255
- /**
256
- * Fetches a batch of emails from the database, decrypts them and sortes the results based on the creation time (newest first)
257
- *
258
- * @param esDB - The database
259
- * @param indexKey - The symmetric key for protecting database
260
- * @param batchSize - The size of the batch
261
- * @param startCursor - The starting point (optional). If not given, starts from the beginning
262
- * @returns The number of stored emails
263
- */
264
- const getEmailBatch = async (esDB, indexKey, batchSize, startCursor) => {
265
- try {
266
- const index = esDB.transaction(require_constants.DB_LABEL, "readonly").store.index("byTime");
267
- const encryptedEmails = [];
268
- let cursor;
269
- if (startCursor) {
270
- const range = IDBKeyRange.upperBound(startCursor, true);
271
- cursor = await index.openCursor(range, "prev");
272
- } else cursor = await index.openCursor(null, "prev");
273
- let count = 0;
274
- let nextCursor;
275
- while (cursor && count < batchSize) {
276
- encryptedEmails.push(cursor.value);
277
- nextCursor = cursor.key;
278
- count++;
279
- cursor = await cursor.continue();
280
- }
281
- return {
282
- emails: await Promise.all(encryptedEmails.map((encryptedEmail) => decryptEmail(indexKey, encryptedEmail))),
283
- nextCursor: count === batchSize ? nextCursor : void 0
284
- };
285
- } catch (error) {
286
- throw new Error(`Cannot fetch email batch of ${batchSize} from the database`, { cause: error });
287
- }
288
- };
289
-
290
- //#endregion
291
- //#region src/email-search/mailCache.ts
292
- /**
293
- * Estimates the email size in the memory
294
- *
295
- * @param email - The email
296
- * @returns The estimation of the email size
297
- */
298
- function sizeOfEmail(email) {
299
- return require_emailKeys.emailToBinary(email).byteLength;
300
- }
301
- /**
302
- * Creates an empty cache variable
303
- *
304
- * @returns The empty cache
305
- */
306
- function createEmptyCache() {
307
- return {
308
- esCache: /* @__PURE__ */ new Map(),
309
- cacheSize: 0,
310
- isCacheLimited: false,
311
- isCacheReady: true
312
- };
313
- }
314
- /**
315
- * Fetches all emails from the database in batches and cahces them
316
- *
317
- * @param indexKey - The symmetric key for protecting database
318
- * @param esCache - The cache to add emails too
319
- * @param esDB - The database
320
- */
321
- const createCacheFromDB = async (indexKey, esDB) => {
322
- const esCache = createEmptyCache();
323
- esCache.isCacheReady = false;
324
- try {
325
- const count = await getEmailCount(esDB);
326
- if (!count) {
327
- esCache.isCacheReady = true;
328
- return esCache;
329
- }
330
- if (count <= require_constants.MAX_EMAIL_PER_BATCH) addEmailsToCache(await getAllEmailsSortedNewestFirst(esDB, indexKey), esCache);
331
- else {
332
- let nextCursor = void 0;
333
- let cacheFull = false;
334
- while (!cacheFull) {
335
- const { emails, nextCursor: newCursor } = await getEmailBatch(esDB, indexKey, require_constants.MAX_EMAIL_PER_BATCH, nextCursor);
336
- if (!newCursor || !emails.length) break;
337
- nextCursor = newCursor;
338
- if (!addEmailsToCache(emails, esCache)) cacheFull = true;
339
- }
340
- }
341
- return esCache;
342
- } catch (error) {
343
- throw new Error(`Email caching failed: ${error}`, { cause: error });
344
- }
345
- };
346
- /**
347
- * Gets an email from the cache
348
- *
349
- * @param emailID - The email identifier
350
- * @param esCache - The email cache
351
- * @returns The found email or throws an error
352
- */
353
- const getEmailFromCache = async (emailID, esCache) => {
354
- const email = esCache.esCache.get(emailID);
355
- if (!email) throw new Error(`Email not found in cache for ID: ${emailID}`);
356
- return email;
357
- };
358
- /**
359
- * Removes the email from cache
360
- *
361
- * @param emailID - The email identifier
362
- * @param esCache - The email cache
363
- */
364
- const deleteEmailFromCache = async (emailID, esCache) => {
365
- try {
366
- const size = sizeOfEmail(await getEmailFromCache(emailID, esCache));
367
- if (esCache.esCache.delete(emailID)) esCache.cacheSize -= size;
368
- } catch (error) {
369
- throw new Error(`Failed to delete email with ID ${emailID}`, { cause: error });
370
- }
371
- };
372
- /**
373
- * Adds emails to the cache
374
- *
375
- * @param emails - The emails to add
376
- * @param esCache - The email cache
377
- * @returns TRUE if all emails were added sucessfully, or FALSE and error reason.
378
- */
379
- function addEmailsToCache(emails, esCache) {
380
- try {
381
- for (const email of emails) {
382
- const result = addEmailToCache(email, esCache);
383
- if (!result.success) return result;
384
- }
385
- return { success: true };
386
- } catch (error) {
387
- throw new Error("Failed to add emails to the cache", { cause: error });
388
- }
389
- }
390
- /**
391
- * Adds email to the cache
392
- *
393
- * @param email - The email to add
394
- * @param esCache - The email cache
395
- * @returns TRUE if the email was added sucessfully, or FALSE and error reason.
396
- */
397
- const addEmailToCache = (email, esCache) => {
398
- try {
399
- if (esCache.esCache.has(email.id)) return {
400
- success: false,
401
- reason: "email already exists in cache"
402
- };
403
- const emailSize = sizeOfEmail(email);
404
- if (esCache.cacheSize + emailSize > require_constants.MAX_CACHE_SIZE) {
405
- esCache.isCacheLimited = true;
406
- return {
407
- success: false,
408
- reason: "hit cache limit"
409
- };
410
- }
411
- esCache.esCache.set(email.id, email);
412
- esCache.cacheSize += emailSize;
413
- return { success: true };
414
- } catch (error) {
415
- throw new Error("Failed to add email to the cache", { cause: error });
416
- }
417
- };
418
-
419
- //#endregion
420
- //#region src/email-search/search.ts
421
- const SUBJECT_OPTIONS = {
422
- preset: "match",
423
- tokenize: "forward",
424
- resolution: 9,
425
- minlength: 2,
426
- optimize: true,
427
- fastupdate: true,
428
- cache: true
429
- };
430
- const BODY_OPTIONS = {
431
- ...SUBJECT_OPTIONS,
432
- minlength: 3,
433
- resolution: 6
434
- };
435
- const FROM_OPTIONS = {
436
- ...SUBJECT_OPTIONS,
437
- tokenize: "strict",
438
- minlength: 1
439
- };
440
- const TO_OPTIONS = {
441
- ...SUBJECT_OPTIONS,
442
- tokenize: "strict",
443
- minlength: 1
444
- };
445
- /**
446
- * Creates new email search index
447
- *
448
- * @returns The email search index
449
- */
450
- const createSearchIndex = () => ({
451
- subjectIndex: new flexsearch.Index(SUBJECT_OPTIONS),
452
- bodyIndex: new flexsearch.Index(BODY_OPTIONS),
453
- fromIndex: new flexsearch.Index(FROM_OPTIONS),
454
- toIndex: new flexsearch.Index(TO_OPTIONS),
455
- isReady: false
456
- });
457
- /**
458
- * Adds the given email to the email search index
459
- *
460
- * @param email - The email to add
461
- * @param searchIndex - The email search index
462
- */
463
- const addEmailToSearchIndex = (email, searchIndex) => {
464
- try {
465
- const emailId = email.id;
466
- if (email.params.subject) searchIndex.subjectIndex.add(emailId, email.params.subject);
467
- if (email.body?.text) searchIndex.bodyIndex.add(emailId, email.body.text);
468
- if (email.params.sender) {
469
- const senderText = `${email.params.sender.name || ""} ${email.params.sender.email || ""}`.trim();
470
- searchIndex.fromIndex.add(emailId, senderText);
471
- }
472
- const recipientsText = (email.params.recipients?.length ? email.params.recipients : [email.params.recipient]).map((recipient) => `${recipient.name || ""} ${recipient.email || ""}`.trim()).join(" ");
473
- searchIndex.toIndex.add(emailId, recipientsText);
474
- } catch (error) {
475
- throw new Error("Failed to add email to the search index", { cause: error });
476
- }
477
- };
478
- /**
479
- * Removes the email from the email search index
480
- *
481
- * @param emailID - The email identifier
482
- * @param searchIndex - The email search index
483
- */
484
- const removeEmailFromSearchIndex = (emailID, searchIndex) => {
485
- try {
486
- searchIndex.subjectIndex.remove(emailID);
487
- searchIndex.bodyIndex.remove(emailID);
488
- searchIndex.fromIndex.remove(emailID);
489
- searchIndex.toIndex.remove(emailID);
490
- } catch (error) {
491
- throw new Error(`Failed to remove email with ID ${emailID} from the search index`, { cause: error });
492
- }
493
- };
494
- /**
495
- * Buils the email search index from the email cache
496
- *
497
- * @param esCache - The email cache
498
- * @returns The email search index
499
- */
500
- const buildSearchIndexFromCache = async (esCache) => {
501
- try {
502
- const searchIndex = createSearchIndex();
503
- searchIndex.isReady = false;
504
- for (const email of esCache.esCache.values()) addEmailToSearchIndex(email, searchIndex);
505
- searchIndex.isReady = true;
506
- return searchIndex;
507
- } catch (error) {
508
- throw new Error("Failed build an email search index from the cache", { cause: error });
509
- }
510
- };
511
- /**
512
- * Searches in teh
513
- *
514
- * @param query - The string to search for
515
- * @param esCache - The email cache
516
- * @param searchIndex - The email search index
517
- * @param opetions - The optional search limitations
518
- * @returns The result of the email search (emails ans their corresponding result weights)
519
- */
520
- const searchEmails = async (query, esCache, searchIndex, options = {}) => {
521
- try {
522
- if (!searchIndex.isReady || !query.trim()) return [];
523
- const { fields = [
524
- "subject",
525
- "body",
526
- "from",
527
- "to"
528
- ], limit = 50, boost = {
529
- subject: 3,
530
- body: 1,
531
- from: 2,
532
- to: 2
533
- } } = options;
534
- const results = /* @__PURE__ */ new Map();
535
- const searchPromises = fields.map(async (field) => {
536
- let fieldResults;
537
- switch (field) {
538
- case "subject":
539
- fieldResults = await searchIndex.subjectIndex.searchAsync(query);
540
- break;
541
- case "body":
542
- fieldResults = await searchIndex.bodyIndex.searchAsync(query);
543
- break;
544
- case "from":
545
- fieldResults = await searchIndex.fromIndex.searchAsync(query);
546
- break;
547
- case "to":
548
- fieldResults = await searchIndex.toIndex.searchAsync(query);
549
- break;
550
- default: return;
551
- }
552
- const fieldBoost = boost[field] || 1;
553
- fieldResults.forEach((emailId) => {
554
- const currentScore = results.get(String(emailId)) || 0;
555
- results.set(String(emailId), currentScore + fieldBoost);
556
- });
557
- });
558
- await Promise.all(searchPromises);
559
- const emailResults = [];
560
- for (const [emailId, score] of results) {
561
- const email = esCache.esCache.get(emailId);
562
- if (email) emailResults.push({
563
- email,
564
- score
565
- });
566
- }
567
- emailResults.sort((a, b) => (b.score || 0) - (a.score || 0));
568
- return emailResults.slice(0, limit);
569
- } catch (error) {
570
- throw new Error("Email search failed", { cause: error });
571
- }
572
- };
573
-
574
- //#endregion
575
- exports.addEmailToCache = addEmailToCache;
576
- exports.addEmailToSearchIndex = addEmailToSearchIndex;
577
- exports.addEmailsToCache = addEmailsToCache;
578
- exports.buildSearchIndexFromCache = buildSearchIndexFromCache;
579
- exports.closeDatabase = closeDatabase;
580
- exports.createCacheFromDB = createCacheFromDB;
581
- exports.deleteDatabase = deleteDatabase;
582
- exports.deleteEmail = deleteEmail;
583
- exports.deleteEmailFromCache = deleteEmailFromCache;
584
- exports.deleteOldestEmails = deleteOldestEmails;
585
- exports.deriveIndexKey = deriveIndexKey;
586
- exports.encryptAndStoreEmail = encryptAndStoreEmail;
587
- exports.encryptAndStoreManyEmail = encryptAndStoreManyEmail;
588
- exports.enforceMaxEmailNumber = enforceMaxEmailNumber;
589
- exports.getAllEmailsSortedNewestFirst = getAllEmailsSortedNewestFirst;
590
- exports.getAllEmailsSortedOldestFirst = getAllEmailsSortedOldestFirst;
591
- exports.getAndDecryptAllEmails = getAndDecryptAllEmails;
592
- exports.getAndDecryptEmail = getAndDecryptEmail;
593
- exports.getEmailBatch = getEmailBatch;
594
- exports.getEmailCount = getEmailCount;
595
- exports.getEmailFromCache = getEmailFromCache;
596
- exports.openDatabase = openDatabase;
597
- exports.removeEmailFromSearchIndex = removeEmailFromSearchIndex;
598
- exports.searchEmails = searchEmails;
599
- //# sourceMappingURL=email-search.js.map
4
+ exports.addEmailToCache = require_search.addEmailToCache;
5
+ exports.addEmailToSearchIndex = require_search.addEmailToSearchIndex;
6
+ exports.addEmailsToCache = require_search.addEmailsToCache;
7
+ exports.buildSearchIndexFromCache = require_search.buildSearchIndexFromCache;
8
+ exports.closeDatabase = require_search.closeDatabase;
9
+ exports.createCacheFromDB = require_search.createCacheFromDB;
10
+ exports.deleteDatabase = require_search.deleteDatabase;
11
+ exports.deleteEmail = require_search.deleteEmail;
12
+ exports.deleteEmailFromCache = require_search.deleteEmailFromCache;
13
+ exports.deleteOldestEmails = require_search.deleteOldestEmails;
14
+ exports.deriveIndexKey = require_search.deriveIndexKey;
15
+ exports.encryptAndStoreEmail = require_search.encryptAndStoreEmail;
16
+ exports.encryptAndStoreManyEmail = require_search.encryptAndStoreManyEmail;
17
+ exports.enforceMaxEmailNumber = require_search.enforceMaxEmailNumber;
18
+ exports.getAllEmailsSortedNewestFirst = require_search.getAllEmailsSortedNewestFirst;
19
+ exports.getAllEmailsSortedOldestFirst = require_search.getAllEmailsSortedOldestFirst;
20
+ exports.getAndDecryptAllEmails = require_search.getAndDecryptAllEmails;
21
+ exports.getAndDecryptEmail = require_search.getAndDecryptEmail;
22
+ exports.getEmailBatch = require_search.getEmailBatch;
23
+ exports.getEmailCount = require_search.getEmailCount;
24
+ exports.getEmailFromCache = require_search.getEmailFromCache;
25
+ exports.openDatabase = require_search.openDatabase;
26
+ exports.removeEmailFromSearchIndex = require_search.removeEmailFromSearchIndex;
27
+ exports.searchEmails = require_search.searchEmails;