internxt-crypto 0.0.10-alpha → 0.0.13

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