apexify.js 2.4.4 → 3.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 (71) hide show
  1. package/README.md +9 -715
  2. package/dataSQL/data.sql +5 -0
  3. package/dataSQL/dataName.sql +0 -0
  4. package/dataSQL/example_table.sql +1 -0
  5. package/index.js +3 -78
  6. package/lib/ai/apexAI.js +2 -2
  7. package/lib/{discord/events/handler → ai/buttons}/tools.js +1 -1
  8. package/lib/utils.js +2 -72
  9. package/package.json +2 -81
  10. package/lib/canvas/themes/level ara.ttf +0 -0
  11. package/lib/canvas/themes/levelFont.ttf +0 -0
  12. package/lib/canvas/themes/levels-card.js +0 -884
  13. package/lib/canvas/themes/music-card.js +0 -342
  14. package/lib/canvas/themes/numbers.ttf +0 -0
  15. package/lib/canvas/themes/tajawal.ttf +0 -0
  16. package/lib/database/MongoDB.js +0 -126
  17. package/lib/database/NanoDB.js +0 -1341
  18. package/lib/database/mongoDb/aggregate.js +0 -120
  19. package/lib/database/mongoDb/countDocs.js +0 -115
  20. package/lib/database/mongoDb/createCollection.js +0 -125
  21. package/lib/database/mongoDb/dataSize.js +0 -89
  22. package/lib/database/mongoDb/distinct.js +0 -110
  23. package/lib/database/mongoDb/drop.js +0 -76
  24. package/lib/database/mongoDb/find.js +0 -122
  25. package/lib/database/mongoDb/geoNear.js +0 -91
  26. package/lib/database/mongoDb/index.js +0 -71
  27. package/lib/database/mongoDb/listCollections.js +0 -81
  28. package/lib/database/mongoDb/migrateAndPrune.js +0 -89
  29. package/lib/database/mongoDb/migrateData.js +0 -79
  30. package/lib/database/mongoDb/remove.js +0 -73
  31. package/lib/database/mongoDb/removeMany.js +0 -73
  32. package/lib/database/mongoDb/removeManyExcept.js +0 -91
  33. package/lib/database/mongoDb/removeSpecific.js +0 -93
  34. package/lib/database/mongoDb/save.js +0 -94
  35. package/lib/database/mongoDb/searchMany.js +0 -109
  36. package/lib/database/mongoDb/textSearch.js +0 -88
  37. package/lib/database/mongoDb/updateAll.js +0 -80
  38. package/lib/database/mongoDb/updateAllExcept.js +0 -108
  39. package/lib/database/mongoDb/updateData.js +0 -106
  40. package/lib/database/nanoDb/fetchData.js +0 -39
  41. package/lib/database/nanoDb/removeField.js +0 -46
  42. package/lib/database/nanoDb/saveData.js +0 -68
  43. package/lib/database/nanoDb/updateFilter.js +0 -24
  44. package/lib/database/ready-schemas.js +0 -245
  45. package/lib/database/utils.js +0 -58
  46. package/lib/discord/discord-build/commands-(prefix)/music/functions/buttons.js +0 -361
  47. package/lib/discord/discord-build/commands-(prefix)/music/functions/end.js +0 -58
  48. package/lib/discord/discord-build/commands-(prefix)/music/functions/start.js +0 -115
  49. package/lib/discord/discord-build/commands-(prefix)/music/play.js +0 -152
  50. package/lib/discord/discord-build/commands-(prefix)/music/previous.js +0 -82
  51. package/lib/discord/discord-build/commands-(prefix)/music/resume.js +0 -93
  52. package/lib/discord/discord-build/commands-(prefix)/music/skip.js +0 -82
  53. package/lib/discord/discord-build/commands-(prefix)/music/stop.js +0 -79
  54. package/lib/discord/discord-build/components/buttons.js +0 -75
  55. package/lib/discord/discord-build/components/menus.js +0 -81
  56. package/lib/discord/discord-build/components/paginator.js +0 -156
  57. package/lib/discord/discord-build/components/permsChecker.js +0 -81
  58. package/lib/discord/discord-build/levelingSystem/cLevel.js +0 -829
  59. package/lib/discord/discord-build/levelingSystem/cLevelsArray.json +0 -104
  60. package/lib/discord/discord-build/utils.js +0 -23
  61. package/lib/discord/events/eventer.js +0 -145
  62. package/lib/discord/events/prefixRegister.js +0 -148
  63. package/lib/discord/events/prefixResponder.js +0 -163
  64. package/lib/discord/events/slashRegister.js +0 -183
  65. package/lib/discord/events/slashResponder.js +0 -108
  66. package/lib/discord/events/starter.js +0 -441
  67. package/lib/discord/functions/perms.js +0 -19
  68. package/lib/discord/utils.js +0 -6
  69. package/lib/general-functions/discord/typeWriter.js +0 -77
  70. package/lib/general-functions/utils.js +0 -19
  71. /package/lib/{discord/events/handler → ai/buttons}/drawMenu.js +0 -0
@@ -1,1341 +0,0 @@
1
- "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
- var __assign = (this && this.__assign) || function () {
18
- __assign = Object.assign || function(t) {
19
- for (var s, i = 1, n = arguments.length; i < n; i++) {
20
- s = arguments[i];
21
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
22
- t[p] = s[p];
23
- }
24
- return t;
25
- };
26
- return __assign.apply(this, arguments);
27
- };
28
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
29
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
30
- return new (P || (P = Promise))(function (resolve, reject) {
31
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
32
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
33
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
34
- step((generator = generator.apply(thisArg, _arguments || [])).next());
35
- });
36
- };
37
- var __generator = (this && this.__generator) || function (thisArg, body) {
38
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
39
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
40
- function verb(n) { return function (v) { return step([n, v]); }; }
41
- function step(op) {
42
- if (f) throw new TypeError("Generator is already executing.");
43
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
44
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
45
- if (y = 0, t) op = [op[0] & 2, t.value];
46
- switch (op[0]) {
47
- case 0: case 1: t = op; break;
48
- case 4: _.label++; return { value: op[1], done: false };
49
- case 5: _.label++; y = op[1]; op = [0]; continue;
50
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
51
- default:
52
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
53
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
54
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
55
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
56
- if (t[2]) _.ops.pop();
57
- _.trys.pop(); continue;
58
- }
59
- op = body.call(thisArg, _);
60
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
61
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
62
- }
63
- };
64
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
65
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
66
- if (ar || !(i in from)) {
67
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
68
- ar[i] = from[i];
69
- }
70
- }
71
- return to.concat(ar || Array.prototype.slice.call(from));
72
- };
73
- Object.defineProperty(exports, "__esModule", { value: true });
74
- exports.NanoDb = void 0;
75
- var events_1 = require("events");
76
- var utils_1 = require("./utils");
77
- var fs = require("fs");
78
- var fs_1 = require("fs");
79
- var zlib = require("zlib");
80
- var archiver = require("archiver");
81
- var path = require("path");
82
- var crypto = require("crypto");
83
- var NanoDb = /** @class */ (function (_super) {
84
- __extends(NanoDb, _super);
85
- function NanoDb(filePath) {
86
- var _this = _super.call(this) || this;
87
- _this.indexes = new Map();
88
- if (!filePath)
89
- throw new Error("Error: filePath is required. Usage: new NanoDb('./data.json')");
90
- _this.filePath = filePath;
91
- _this.dataPromise = _this.loadData();
92
- return _this;
93
- }
94
- NanoDb.prototype.loadData = function () {
95
- return __awaiter(this, void 0, void 0, function () {
96
- var data, err_1;
97
- return __generator(this, function (_a) {
98
- switch (_a.label) {
99
- case 0:
100
- _a.trys.push([0, 2, , 3]);
101
- return [4 /*yield*/, fs_1.promises.readFile(this.filePath, 'utf8')];
102
- case 1:
103
- data = _a.sent();
104
- return [2 /*return*/, JSON.parse(data)];
105
- case 2:
106
- err_1 = _a.sent();
107
- return [2 /*return*/, []];
108
- case 3: return [2 /*return*/];
109
- }
110
- });
111
- });
112
- };
113
- NanoDb.prototype.addOne = function (newData, options) {
114
- return __awaiter(this, void 0, void 0, function () {
115
- var result, error_1;
116
- return __generator(this, function (_a) {
117
- switch (_a.label) {
118
- case 0:
119
- _a.trys.push([0, 2, , 3]);
120
- return [4 /*yield*/, (0, utils_1.saveData)(this.filePath, newData, options && options.uniqueKeys)];
121
- case 1:
122
- result = _a.sent();
123
- if (result.success) {
124
- this.emit('dataInserted', newData);
125
- }
126
- this.dataPromise = this.loadData();
127
- return [2 /*return*/, result];
128
- case 2:
129
- error_1 = _a.sent();
130
- return [2 /*return*/, {
131
- success: false,
132
- message: 'Error saving data',
133
- errorMessage: error_1.message,
134
- documentsCount: 0,
135
- }];
136
- case 3: return [2 /*return*/];
137
- }
138
- });
139
- });
140
- };
141
- NanoDb.prototype.displayData = function (options) {
142
- return __awaiter(this, void 0, void 0, function () {
143
- var data, filteredData, sortBy_1, sortOrder_1, page, pageSize, startIndex, endIndex, paginatedData, error_2;
144
- return __generator(this, function (_a) {
145
- switch (_a.label) {
146
- case 0:
147
- _a.trys.push([0, 2, , 3]);
148
- return [4 /*yield*/, this.dataPromise];
149
- case 1:
150
- data = _a.sent();
151
- filteredData = data;
152
- if (options === null || options === void 0 ? void 0 : options.filters) {
153
- filteredData = data.filter(function (document) { return (0, utils_1.matchesFilterQuery)(document, options.filters); });
154
- }
155
- sortBy_1 = options === null || options === void 0 ? void 0 : options.sortBy;
156
- sortOrder_1 = (options === null || options === void 0 ? void 0 : options.sortOrder) === 'desc' ? -1 : 1;
157
- if (sortBy_1) {
158
- filteredData.sort(function (a, b) { return (a[sortBy_1] > b[sortBy_1] ? sortOrder_1 : -sortOrder_1); });
159
- }
160
- page = (options === null || options === void 0 ? void 0 : options.page) || 1;
161
- pageSize = (options === null || options === void 0 ? void 0 : options.pageSize) || 10;
162
- startIndex = (page - 1) * pageSize;
163
- endIndex = startIndex + pageSize;
164
- paginatedData = filteredData.slice(startIndex, endIndex);
165
- return [2 /*return*/, {
166
- success: true,
167
- message: 'Data displayed successfully',
168
- documentsCount: paginatedData.length,
169
- displayedResults: paginatedData,
170
- }];
171
- case 2:
172
- error_2 = _a.sent();
173
- return [2 /*return*/, {
174
- success: false,
175
- message: 'Error displaying data',
176
- errorMessage: error_2.message,
177
- documentsCount: 0,
178
- displayedResults: [],
179
- }];
180
- case 3: return [2 /*return*/];
181
- }
182
- });
183
- });
184
- };
185
- NanoDb.prototype.removeOne = function (filterQuery, removeFilter) {
186
- return __awaiter(this, void 0, void 0, function () {
187
- var data, result, error_3;
188
- return __generator(this, function (_a) {
189
- switch (_a.label) {
190
- case 0:
191
- _a.trys.push([0, 3, , 4]);
192
- return [4 /*yield*/, this.dataPromise];
193
- case 1:
194
- data = _a.sent();
195
- result = (0, utils_1.removeFields)(data, filterQuery, removeFilter);
196
- return [4 /*yield*/, fs_1.promises.writeFile(this.filePath, JSON.stringify(result, null, 2), 'utf8')];
197
- case 2:
198
- _a.sent();
199
- this.emit('dataRemoved', {
200
- success: true,
201
- message: 'Successfully removed the specified field(s) from a single document.',
202
- documentsCount: result.length,
203
- });
204
- return [2 /*return*/, {
205
- success: true,
206
- message: 'Successfully removed the specified field(s) from a single document.',
207
- documentsCount: result.length,
208
- }];
209
- case 3:
210
- error_3 = _a.sent();
211
- this.emit('dataRemoveError', {
212
- success: false,
213
- message: 'Error removing field(s) from a single document.',
214
- errorMessage: error_3.message,
215
- documentsCount: 0,
216
- });
217
- return [2 /*return*/, {
218
- success: false,
219
- message: 'Error removing field(s) from a single document.',
220
- errorMessage: error_3.message,
221
- documentsCount: 0,
222
- }];
223
- case 4: return [2 /*return*/];
224
- }
225
- });
226
- });
227
- };
228
- NanoDb.prototype.removeDoc = function (filterQuery) {
229
- return __awaiter(this, void 0, void 0, function () {
230
- var data, indexToRemove, error_4;
231
- return __generator(this, function (_a) {
232
- switch (_a.label) {
233
- case 0:
234
- _a.trys.push([0, 5, , 6]);
235
- return [4 /*yield*/, this.dataPromise];
236
- case 1:
237
- data = _a.sent();
238
- indexToRemove = void 0;
239
- if (Object.keys(filterQuery).length === 0) {
240
- indexToRemove = 0;
241
- }
242
- else {
243
- indexToRemove = data.findIndex(function (document) { return (0, utils_1.matchesFilterQuery)(document, filterQuery); });
244
- }
245
- if (!(indexToRemove !== -1)) return [3 /*break*/, 3];
246
- data.splice(indexToRemove, 1);
247
- return [4 /*yield*/, fs_1.promises.writeFile(this.filePath, JSON.stringify(data, null, 2), 'utf8')];
248
- case 2:
249
- _a.sent();
250
- return [2 /*return*/, {
251
- success: true,
252
- message: 'Successfully removed the specified document.',
253
- documentsCount: data.length,
254
- }];
255
- case 3: return [2 /*return*/, {
256
- success: false,
257
- message: 'Document not found for removal.',
258
- documentsCount: data.length,
259
- fileSizeInBytes: 0,
260
- }];
261
- case 4: return [3 /*break*/, 6];
262
- case 5:
263
- error_4 = _a.sent();
264
- return [2 /*return*/, {
265
- success: false,
266
- message: 'Error removing document.',
267
- errorMessage: error_4.message,
268
- documentsCount: 0,
269
- fileSizeInBytes: 0,
270
- }];
271
- case 6: return [2 /*return*/];
272
- }
273
- });
274
- });
275
- };
276
- NanoDb.prototype.updateData = function (filterQuery, updateOptions, uniqueKeys, upsert) {
277
- if (uniqueKeys === void 0) { uniqueKeys = []; }
278
- if (upsert === void 0) { upsert = false; }
279
- return __awaiter(this, void 0, void 0, function () {
280
- var data, existingDocumentsWithUniqueKeys, indexToUpdate, updatedDocument, newDocument, error_5;
281
- return __generator(this, function (_a) {
282
- switch (_a.label) {
283
- case 0:
284
- _a.trys.push([0, 6, , 7]);
285
- return [4 /*yield*/, this.dataPromise];
286
- case 1:
287
- data = _a.sent();
288
- if (uniqueKeys.length > 0) {
289
- existingDocumentsWithUniqueKeys = data.filter(function (document) {
290
- return uniqueKeys.every(function (key) {
291
- return document.unique && document.unique[key] === updateOptions[key];
292
- });
293
- });
294
- if (existingDocumentsWithUniqueKeys.length > 0) {
295
- this.emit('dataUpdateError', {
296
- success: false,
297
- message: "Update violates uniqueness for specified keys: ".concat(uniqueKeys.join(', '), "."),
298
- documentsCount: data.length,
299
- fileSizeInBytes: 0,
300
- });
301
- return [2 /*return*/, {
302
- success: false,
303
- message: "Update violates uniqueness for specified keys: ".concat(uniqueKeys.join(', '), "."),
304
- documentsCount: data.length,
305
- fileSizeInBytes: 0,
306
- }];
307
- }
308
- }
309
- indexToUpdate = data.findIndex(function (document) { return (0, utils_1.matchesFilterQuery)(document, filterQuery); });
310
- if (!(indexToUpdate !== -1)) return [3 /*break*/, 3];
311
- return [4 /*yield*/, (0, utils_1.updateOption)(data[indexToUpdate], updateOptions)];
312
- case 2:
313
- updatedDocument = _a.sent();
314
- data[indexToUpdate] = updatedDocument;
315
- this.emit('dataUpdated', {
316
- success: true,
317
- message: 'Successfully updated the specified document.',
318
- documentsCount: data.length,
319
- fileSizeInBytes: 0,
320
- });
321
- return [3 /*break*/, 4];
322
- case 3:
323
- if (upsert) {
324
- newDocument = __assign(__assign({}, filterQuery), updateOptions);
325
- data.push(newDocument);
326
- this.emit('dataInserted', {
327
- success: true,
328
- message: 'Successfully inserted the specified document.',
329
- documentsCount: data.length,
330
- fileSizeInBytes: 0,
331
- });
332
- }
333
- else {
334
- this.emit('dataUpdateError', {
335
- success: false,
336
- message: 'Document not found for update.',
337
- documentsCount: data.length,
338
- fileSizeInBytes: 0,
339
- });
340
- return [2 /*return*/, {
341
- success: false,
342
- message: 'Document not found for update.',
343
- documentsCount: data.length,
344
- fileSizeInBytes: 0,
345
- }];
346
- }
347
- _a.label = 4;
348
- case 4: return [4 /*yield*/, fs_1.promises.writeFile(this.filePath, JSON.stringify(data, null, 2), 'utf8')];
349
- case 5:
350
- _a.sent();
351
- return [2 /*return*/, {
352
- success: true,
353
- message: 'Successfully updated/inserted the specified document.',
354
- documentsCount: data.length,
355
- fileSizeInBytes: 0,
356
- }];
357
- case 6:
358
- error_5 = _a.sent();
359
- this.emit('dataUpdateError', {
360
- success: false,
361
- message: 'Error updating/inserting document.',
362
- errorMessage: error_5.message,
363
- documentsCount: 0,
364
- fileSizeInBytes: 0,
365
- });
366
- return [2 /*return*/, {
367
- success: false,
368
- message: 'Error updating/inserting document.',
369
- errorMessage: error_5.message,
370
- documentsCount: 0,
371
- fileSizeInBytes: 0,
372
- }];
373
- case 7: return [2 /*return*/];
374
- }
375
- });
376
- });
377
- };
378
- NanoDb.prototype.findData = function (query) {
379
- return __awaiter(this, void 0, void 0, function () {
380
- var data, foundResult, _i, data_1, document_1, isMatch, key, documentValue, queryValue, error_6;
381
- return __generator(this, function (_a) {
382
- switch (_a.label) {
383
- case 0:
384
- _a.trys.push([0, 2, , 3]);
385
- return [4 /*yield*/, this.dataPromise];
386
- case 1:
387
- data = _a.sent();
388
- foundResult = null;
389
- for (_i = 0, data_1 = data; _i < data_1.length; _i++) {
390
- document_1 = data_1[_i];
391
- isMatch = true;
392
- for (key in query) {
393
- documentValue = String(document_1[key]).toLowerCase();
394
- queryValue = String(query[key]).toLowerCase();
395
- if (query[key] !== 'any' && documentValue !== queryValue) {
396
- isMatch = false;
397
- break;
398
- }
399
- }
400
- if (isMatch) {
401
- foundResult = __assign({}, document_1);
402
- break;
403
- }
404
- }
405
- if (!foundResult) {
406
- return [2 /*return*/, {
407
- success: false,
408
- message: 'No data found matching the search.',
409
- documentsCount: 0,
410
- foundResults: null,
411
- fileSizeInBytes: 0,
412
- }];
413
- }
414
- return [2 /*return*/, {
415
- success: true,
416
- message: 'Data found successfully',
417
- documentsCount: 1,
418
- foundResults: [foundResult],
419
- fileSizeInBytes: 0,
420
- }];
421
- case 2:
422
- error_6 = _a.sent();
423
- return [2 /*return*/, {
424
- success: false,
425
- message: 'Error finding data',
426
- errorMessage: error_6.message,
427
- documentsCount: 0,
428
- foundResults: [],
429
- fileSizeInBytes: 0,
430
- }];
431
- case 3: return [2 /*return*/];
432
- }
433
- });
434
- });
435
- };
436
- NanoDb.prototype.updateMany = function (filterQuery, updateOptions, upsert) {
437
- if (upsert === void 0) { upsert = false; }
438
- return __awaiter(this, void 0, void 0, function () {
439
- var data, matchingDocuments, _loop_1, _i, matchingDocuments_1, matchingDocument, newDocument, error_7;
440
- return __generator(this, function (_a) {
441
- switch (_a.label) {
442
- case 0:
443
- _a.trys.push([0, 9, , 10]);
444
- return [4 /*yield*/, this.dataPromise];
445
- case 1:
446
- data = _a.sent();
447
- matchingDocuments = data.filter(function (document) { return (0, utils_1.matchesFilterQuery)(document, filterQuery); });
448
- if (!(matchingDocuments.length > 0)) return [3 /*break*/, 6];
449
- _loop_1 = function (matchingDocument) {
450
- var indexToUpdate, updatedDocument;
451
- return __generator(this, function (_b) {
452
- switch (_b.label) {
453
- case 0:
454
- indexToUpdate = data.findIndex(function (doc) { return doc === matchingDocument; });
455
- return [4 /*yield*/, (0, utils_1.updateOption)(matchingDocument, updateOptions)];
456
- case 1:
457
- updatedDocument = _b.sent();
458
- data[indexToUpdate] = updatedDocument;
459
- return [2 /*return*/];
460
- }
461
- });
462
- };
463
- _i = 0, matchingDocuments_1 = matchingDocuments;
464
- _a.label = 2;
465
- case 2:
466
- if (!(_i < matchingDocuments_1.length)) return [3 /*break*/, 5];
467
- matchingDocument = matchingDocuments_1[_i];
468
- return [5 /*yield**/, _loop_1(matchingDocument)];
469
- case 3:
470
- _a.sent();
471
- _a.label = 4;
472
- case 4:
473
- _i++;
474
- return [3 /*break*/, 2];
475
- case 5:
476
- this.emit('dataUpdated', {
477
- filterQuery: filterQuery,
478
- updateOptions: updateOptions,
479
- updatedCount: matchingDocuments.length,
480
- });
481
- return [3 /*break*/, 7];
482
- case 6:
483
- if (upsert) {
484
- newDocument = __assign(__assign({}, filterQuery), updateOptions);
485
- data.push(newDocument);
486
- }
487
- else {
488
- return [2 /*return*/, {
489
- success: false,
490
- message: 'No documents found for update.',
491
- documentsCount: data.length,
492
- fileSizeInBytes: 0,
493
- }];
494
- }
495
- _a.label = 7;
496
- case 7: return [4 /*yield*/, fs_1.promises.writeFile(this.filePath, JSON.stringify(data, null, 2), 'utf8')];
497
- case 8:
498
- _a.sent();
499
- return [2 /*return*/, {
500
- success: true,
501
- message: 'Successfully updated/inserted the specified documents.',
502
- documentsCount: data.length,
503
- fileSizeInBytes: 0,
504
- }];
505
- case 9:
506
- error_7 = _a.sent();
507
- this.emit('dataUpdateError', {
508
- error: error_7,
509
- methodName: 'updateMany',
510
- });
511
- return [2 /*return*/, {
512
- success: false,
513
- message: 'Error updating/inserting documents.',
514
- errorMessage: error_7.message,
515
- documentsCount: 0,
516
- fileSizeInBytes: 0,
517
- }];
518
- case 10: return [2 /*return*/];
519
- }
520
- });
521
- });
522
- };
523
- NanoDb.prototype.drop = function () {
524
- return __awaiter(this, void 0, void 0, function () {
525
- var error_8;
526
- return __generator(this, function (_a) {
527
- switch (_a.label) {
528
- case 0:
529
- _a.trys.push([0, 2, , 3]);
530
- return [4 /*yield*/, fs_1.promises.writeFile(this.filePath, '[]', 'utf8')];
531
- case 1:
532
- _a.sent();
533
- this.dataPromise = this.loadData();
534
- this.emit('dataDropped', {
535
- methodName: 'drop',
536
- });
537
- return [2 /*return*/, {
538
- success: true,
539
- message: 'Data dropped successfully',
540
- documentsCount: 0,
541
- fileSizeInBytes: 0,
542
- }];
543
- case 2:
544
- error_8 = _a.sent();
545
- this.emit('dataUpdateError', {
546
- error: error_8,
547
- methodName: 'drop',
548
- });
549
- return [2 /*return*/, {
550
- success: false,
551
- message: 'Error dropping data',
552
- errorMessage: error_8.message,
553
- documentsCount: 0,
554
- fileSizeInBytes: 0,
555
- }];
556
- case 3: return [2 /*return*/];
557
- }
558
- });
559
- });
560
- };
561
- NanoDb.prototype.countDoc = function () {
562
- return __awaiter(this, void 0, void 0, function () {
563
- var data, documentCount, error_9;
564
- return __generator(this, function (_a) {
565
- switch (_a.label) {
566
- case 0:
567
- _a.trys.push([0, 2, , 3]);
568
- return [4 /*yield*/, this.dataPromise];
569
- case 1:
570
- data = _a.sent();
571
- documentCount = data.length;
572
- return [2 /*return*/, {
573
- success: true,
574
- message: 'Document count retrieved successfully.',
575
- documentsCount: documentCount,
576
- fileSizeInBytes: 0,
577
- }];
578
- case 2:
579
- error_9 = _a.sent();
580
- return [2 /*return*/, {
581
- success: false,
582
- message: 'Error counting documents.',
583
- errorMessage: error_9.message,
584
- documentsCount: 0,
585
- fileSizeInBytes: 0,
586
- }];
587
- case 3: return [2 /*return*/];
588
- }
589
- });
590
- });
591
- };
592
- NanoDb.prototype.dataSize = function () {
593
- return __awaiter(this, void 0, void 0, function () {
594
- var fileStats, fileSizeInBytes, error_10;
595
- return __generator(this, function (_a) {
596
- switch (_a.label) {
597
- case 0:
598
- _a.trys.push([0, 2, , 3]);
599
- return [4 /*yield*/, fs_1.promises.stat(this.filePath)];
600
- case 1:
601
- fileStats = _a.sent();
602
- fileSizeInBytes = fileStats.size;
603
- return [2 /*return*/, {
604
- success: true,
605
- message: 'Data file size retrieved successfully.',
606
- fileSizeInBytes: fileSizeInBytes,
607
- documentsCount: 0,
608
- }];
609
- case 2:
610
- error_10 = _a.sent();
611
- return [2 /*return*/, {
612
- success: false,
613
- message: 'Error retrieving data file size.',
614
- errorMessage: error_10.message,
615
- fileSizeInBytes: 0,
616
- documentsCount: 0,
617
- }];
618
- case 3: return [2 /*return*/];
619
- }
620
- });
621
- });
622
- };
623
- NanoDb.prototype.transferData = function (destinationFilePath) {
624
- return __awaiter(this, void 0, void 0, function () {
625
- var sourceData, destinationExists, destinationData, _a, _b, mergedData, error_11;
626
- return __generator(this, function (_c) {
627
- switch (_c.label) {
628
- case 0:
629
- _c.trys.push([0, 8, , 9]);
630
- return [4 /*yield*/, this.dataPromise];
631
- case 1:
632
- sourceData = _c.sent();
633
- return [4 /*yield*/, this.fileExists(destinationFilePath)];
634
- case 2:
635
- destinationExists = _c.sent();
636
- destinationData = [];
637
- if (!destinationExists) return [3 /*break*/, 4];
638
- _b = (_a = JSON).parse;
639
- return [4 /*yield*/, fs_1.promises.readFile(destinationFilePath, 'utf8')];
640
- case 3:
641
- destinationData = _b.apply(_a, [_c.sent()]);
642
- return [3 /*break*/, 6];
643
- case 4: return [4 /*yield*/, fs_1.promises.writeFile(destinationFilePath, '[]', 'utf8')];
644
- case 5:
645
- _c.sent();
646
- _c.label = 6;
647
- case 6:
648
- mergedData = __spreadArray(__spreadArray([], destinationData, true), sourceData, true);
649
- return [4 /*yield*/, fs_1.promises.writeFile(destinationFilePath, JSON.stringify(mergedData, null, 2), 'utf8')];
650
- case 7:
651
- _c.sent();
652
- this.emit('dataTransferred', {
653
- success: true,
654
- message: 'Data transferred and added to existing data successfully.',
655
- documentsCount: mergedData.length,
656
- destinationFilePath: destinationFilePath,
657
- fileSizeInBytes: 0,
658
- });
659
- return [2 /*return*/, {
660
- success: true,
661
- message: 'Data transferred and added to existing data successfully.',
662
- documentsCount: mergedData.length,
663
- destinationFilePath: destinationFilePath,
664
- fileSizeInBytes: 0,
665
- }];
666
- case 8:
667
- error_11 = _c.sent();
668
- this.emit('transferError', {
669
- success: false,
670
- message: 'Error transferring and adding data.',
671
- errorMessage: error_11.message,
672
- documentsCount: 0,
673
- fileSizeInBytes: 0,
674
- });
675
- return [2 /*return*/, {
676
- success: false,
677
- message: 'Error transferring and adding data.',
678
- errorMessage: error_11.message,
679
- documentsCount: 0,
680
- fileSizeInBytes: 0,
681
- }];
682
- case 9: return [2 /*return*/];
683
- }
684
- });
685
- });
686
- };
687
- NanoDb.prototype.fileExists = function (filePath) {
688
- return __awaiter(this, void 0, void 0, function () {
689
- var _a;
690
- return __generator(this, function (_b) {
691
- switch (_b.label) {
692
- case 0:
693
- _b.trys.push([0, 2, , 3]);
694
- return [4 /*yield*/, fs_1.promises.access(filePath)];
695
- case 1:
696
- _b.sent();
697
- return [2 /*return*/, true];
698
- case 2:
699
- _a = _b.sent();
700
- return [2 /*return*/, false];
701
- case 3: return [2 /*return*/];
702
- }
703
- });
704
- });
705
- };
706
- NanoDb.prototype.distinct = function (field) {
707
- return __awaiter(this, void 0, void 0, function () {
708
- var data, distinctValues, valueSet, _i, data_2, document_2, fieldValue, error_12;
709
- return __generator(this, function (_a) {
710
- switch (_a.label) {
711
- case 0:
712
- _a.trys.push([0, 2, , 3]);
713
- return [4 /*yield*/, this.dataPromise];
714
- case 1:
715
- data = _a.sent();
716
- distinctValues = [];
717
- valueSet = new Set();
718
- for (_i = 0, data_2 = data; _i < data_2.length; _i++) {
719
- document_2 = data_2[_i];
720
- fieldValue = document_2[field];
721
- if (fieldValue === undefined || fieldValue === null) {
722
- return [2 /*return*/, {
723
- success: false,
724
- message: "Error retrieving distinct values. Field with the name '".concat(field, "' not found in some documents."),
725
- documentsCount: 0,
726
- distinctValues: [],
727
- fileSizeInBytes: 0,
728
- }];
729
- }
730
- if (!valueSet.has(fieldValue)) {
731
- valueSet.add(fieldValue);
732
- distinctValues.push(fieldValue);
733
- }
734
- }
735
- return [2 /*return*/, {
736
- success: true,
737
- message: 'Distinct values retrieved successfully.',
738
- documentsCount: distinctValues.length,
739
- distinctValues: distinctValues,
740
- fileSizeInBytes: 0,
741
- }];
742
- case 2:
743
- error_12 = _a.sent();
744
- return [2 /*return*/, {
745
- success: false,
746
- message: 'Error retrieving distinct values.',
747
- errorMessage: error_12.message,
748
- documentsCount: 0,
749
- distinctValues: [],
750
- fileSizeInBytes: 0,
751
- }];
752
- case 3: return [2 /*return*/];
753
- }
754
- });
755
- });
756
- };
757
- NanoDb.prototype.indexData = function (data) {
758
- for (var field in data) {
759
- if (!this.indexes.has(field)) {
760
- this.indexes.set(field, new Map());
761
- }
762
- var fieldValue = data[field];
763
- if (!this.indexes.get(field).has(fieldValue)) {
764
- this.indexes.get(field).set(fieldValue, []);
765
- }
766
- this.indexes.get(field).get(fieldValue).push(data);
767
- }
768
- };
769
- NanoDb.prototype.backup = function (filePathToJsonData, typeOfCompression, options) {
770
- if (options === void 0) { options = {}; }
771
- var compressionTypes = ['zip', 'json', 'gzip', 'txt'];
772
- if (!compressionTypes.includes(typeOfCompression)) {
773
- throw new Error('Invalid compression type');
774
- }
775
- var outputPath = options.outputPath, _a = options.encrypted, encrypted = _a === void 0 ? false : _a, key = options.key;
776
- if (encrypted && !key) {
777
- throw new Error('Encryption key is required for encryption');
778
- }
779
- var jsonData = fs.readFileSync(filePathToJsonData, 'utf-8');
780
- var encryptedData = jsonData;
781
- if (encrypted) {
782
- var algorithm = 'aes-256-cbc';
783
- var iv = crypto.randomBytes(16);
784
- var cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv);
785
- encryptedData = JSON.stringify({
786
- iv: iv.toString('hex'),
787
- content: cipher.update(jsonData, 'utf8', 'hex') + cipher.final('hex'),
788
- });
789
- }
790
- if (typeOfCompression === 'zip') {
791
- this.createZipBackup(encryptedData, outputPath);
792
- }
793
- else if (typeOfCompression === 'gzip') {
794
- this.createGzipBackup(jsonData, encryptedData, outputPath, encrypted, key);
795
- }
796
- else if (typeOfCompression === 'txt' || typeOfCompression === 'json') {
797
- this.createTextOrJsonBackup(encryptedData, outputPath);
798
- }
799
- else {
800
- throw new Error('Unsupported compression format');
801
- }
802
- };
803
- NanoDb.prototype.createZipBackup = function (data, outputPath) {
804
- return new Promise(function (resolve, reject) {
805
- try {
806
- var archive = archiver('zip', { zlib: { level: 9 } });
807
- var outputStream = outputPath ? fs.createWriteStream(outputPath) : process.stdout;
808
- archive.pipe(outputStream);
809
- archive.append(data, { name: 'backup.json' });
810
- archive.finalize();
811
- outputStream.on('close', function () {
812
- resolve({
813
- success: true,
814
- message: "Backup created successfully: ".concat(outputPath || 'stdout'),
815
- documentsCount: null
816
- });
817
- });
818
- }
819
- catch (error) {
820
- console.error(error.message);
821
- reject({
822
- success: false,
823
- message: 'Error performing backup.',
824
- errorMessage: error.message,
825
- });
826
- }
827
- });
828
- };
829
- NanoDb.prototype.createGzipBackup = function (jsonData, encryptedData, outputPath, encrypted, key) {
830
- return new Promise(function (resolve, reject) {
831
- try {
832
- var gzip = zlib.createGzip({ level: 9 });
833
- var cipher = encrypted
834
- ? crypto.createCipheriv('aes-256-cbc', Buffer.from(key), crypto.randomBytes(16))
835
- : null;
836
- var inputStream = encrypted
837
- ? fs.createReadStream('./data2.json').pipe(cipher)
838
- : fs.createReadStream(Buffer.from(jsonData, 'utf-8'));
839
- var outputStream = outputPath ? fs.createWriteStream(outputPath) : process.stdout;
840
- var pipeline = inputStream.pipe(gzip).pipe(outputStream);
841
- pipeline.on('finish', function () {
842
- resolve({
843
- success: true,
844
- message: "Backup created successfully: ".concat(outputPath || 'stdout'),
845
- documentsCount: null
846
- });
847
- });
848
- }
849
- catch (error) {
850
- console.error(error.message);
851
- reject({
852
- success: false,
853
- message: 'Error performing backup.',
854
- errorMessage: error.message,
855
- });
856
- }
857
- });
858
- };
859
- NanoDb.prototype.createTextOrJsonBackup = function (encryptedData, outputPath) {
860
- return new Promise(function (resolve, reject) {
861
- try {
862
- var dataToWrite = encryptedData;
863
- if (outputPath) {
864
- fs.writeFileSync(outputPath, dataToWrite, 'utf-8');
865
- resolve({
866
- success: true,
867
- message: "Backup created successfully: ".concat(outputPath || 'stdout'),
868
- documentsCount: null
869
- });
870
- }
871
- else {
872
- resolve({
873
- success: false,
874
- message: "No output path specified. Backup content: ".concat(dataToWrite),
875
- documentsCount: null
876
- });
877
- }
878
- }
879
- catch (error) {
880
- console.error(error.message);
881
- reject({
882
- success: false,
883
- message: 'Error performing backup.',
884
- errorMessage: error.message,
885
- });
886
- }
887
- });
888
- };
889
- NanoDb.prototype.decrypt = function (encryptedData, decryptKey) {
890
- if (!decryptKey) {
891
- throw new Error('Encryption key is required for decryption.');
892
- }
893
- var algorithm = 'aes-256-cbc';
894
- var key = Buffer.from(decryptKey, 'utf8');
895
- var decipher = crypto.createDecipheriv(algorithm, key, Buffer.alloc(16));
896
- var decrypted = decipher.update(encryptedData, 'hex', 'utf8');
897
- decrypted += decipher.final('utf8');
898
- return decrypted;
899
- };
900
- NanoDb.prototype.nanoSize = function () {
901
- return __awaiter(this, void 0, void 0, function () {
902
- var projectRoot, totalSize, fileSizes, files, _i, files_1, file, filePath, stats, subFiles, _a, subFiles_1, subFile, subFilePath, subFileStats, subFileSize, fileSize, error_13;
903
- return __generator(this, function (_b) {
904
- switch (_b.label) {
905
- case 0:
906
- projectRoot = process.cwd();
907
- totalSize = 0;
908
- fileSizes = {};
909
- _b.label = 1;
910
- case 1:
911
- _b.trys.push([1, 13, , 14]);
912
- return [4 /*yield*/, fs_1.promises.readdir(projectRoot)];
913
- case 2:
914
- files = _b.sent();
915
- _i = 0, files_1 = files;
916
- _b.label = 3;
917
- case 3:
918
- if (!(_i < files_1.length)) return [3 /*break*/, 12];
919
- file = files_1[_i];
920
- filePath = path.join(projectRoot, file);
921
- return [4 /*yield*/, fs_1.promises.stat(filePath)];
922
- case 4:
923
- stats = _b.sent();
924
- if (!(stats.isDirectory() && !filePath.includes('node_modules'))) return [3 /*break*/, 10];
925
- return [4 /*yield*/, fs_1.promises.readdir(filePath)];
926
- case 5:
927
- subFiles = _b.sent();
928
- _a = 0, subFiles_1 = subFiles;
929
- _b.label = 6;
930
- case 6:
931
- if (!(_a < subFiles_1.length)) return [3 /*break*/, 9];
932
- subFile = subFiles_1[_a];
933
- subFilePath = path.join(filePath, subFile);
934
- return [4 /*yield*/, fs_1.promises.stat(subFilePath)];
935
- case 7:
936
- subFileStats = _b.sent();
937
- if (subFileStats.isFile() && path.extname(subFilePath).toLowerCase() === '.json') {
938
- subFileSize = subFileStats.size;
939
- totalSize += subFileSize;
940
- fileSizes[subFile] = subFileSize;
941
- }
942
- _b.label = 8;
943
- case 8:
944
- _a++;
945
- return [3 /*break*/, 6];
946
- case 9: return [3 /*break*/, 11];
947
- case 10:
948
- if (stats.isFile() && path.extname(filePath).toLowerCase() === '.json') {
949
- fileSize = stats.size;
950
- totalSize += fileSize;
951
- fileSizes[file] = fileSize;
952
- }
953
- _b.label = 11;
954
- case 11:
955
- _i++;
956
- return [3 /*break*/, 3];
957
- case 12: return [2 /*return*/, { totalSize: totalSize, fileSizes: fileSizes }];
958
- case 13:
959
- error_13 = _b.sent();
960
- console.error('Error calculating total size:', error_13.message);
961
- return [2 /*return*/, { totalSize: 0, fileSizes: {} }];
962
- case 14: return [2 /*return*/];
963
- }
964
- });
965
- });
966
- };
967
- NanoDb.prototype.replicate = function (sourceFilePath, targetFilePath) {
968
- try {
969
- var sourceData = fs.readFileSync(sourceFilePath, 'utf8');
970
- var jsonData = JSON.parse(sourceData);
971
- fs.writeFileSync(targetFilePath, JSON.stringify(jsonData, null, 2), 'utf8');
972
- var documentCount = jsonData.length;
973
- var fileSize = Buffer.from(JSON.stringify(jsonData)).length;
974
- return {
975
- success: true,
976
- message: 'Data replicated successfully.',
977
- documentCount: documentCount,
978
- fileSize: fileSize,
979
- };
980
- }
981
- catch (error) {
982
- if (error.code === 'ENOENT') {
983
- console.error('Target file not found.');
984
- return {
985
- success: false,
986
- message: 'Target file not found.',
987
- };
988
- }
989
- else {
990
- console.error(error.message);
991
- return {
992
- success: false,
993
- message: "Error replicating data: ".concat(error.message),
994
- };
995
- }
996
- }
997
- };
998
- NanoDb.prototype.aggregate = function (pipeline) {
999
- return __awaiter(this, void 0, void 0, function () {
1000
- var data_3, result, error_14;
1001
- return __generator(this, function (_a) {
1002
- switch (_a.label) {
1003
- case 0:
1004
- _a.trys.push([0, 2, , 3]);
1005
- return [4 /*yield*/, this.dataPromise];
1006
- case 1:
1007
- data_3 = _a.sent();
1008
- result = pipeline.reduce(function (acc, stage) {
1009
- if (stage.$match) {
1010
- acc = acc.filter(function (document) { return (0, utils_1.matchesFilterQuery)(document, stage.$match); });
1011
- }
1012
- else if (stage.$group) {
1013
- var groupedData_1 = new Map();
1014
- var key_1 = stage.$group._id;
1015
- acc.forEach(function (document) {
1016
- var keyValue = String(document[key_1]);
1017
- if (!groupedData_1.has(keyValue)) {
1018
- groupedData_1.set(keyValue, []);
1019
- }
1020
- groupedData_1.get(keyValue).push(document);
1021
- });
1022
- acc = Array.from(groupedData_1.values(), function (value) {
1023
- var _a;
1024
- return (_a = {}, _a[key_1] = value, _a);
1025
- });
1026
- }
1027
- else if (stage.$project) {
1028
- acc = acc.map(function (document) {
1029
- var projectedDocument = {};
1030
- for (var field in stage.$project) {
1031
- var fieldPath = stage.$project[field];
1032
- var fieldValue = fieldPath.split('.').reduce(function (obj, key) { return obj[key]; }, document);
1033
- projectedDocument[field] = fieldValue;
1034
- }
1035
- return projectedDocument;
1036
- });
1037
- }
1038
- else if (stage.$sort) {
1039
- var sortBy_2 = stage.$sort.field;
1040
- var sortOrder_2 = stage.$sort.order === 'desc' ? -1 : 1;
1041
- acc.sort(function (a, b) { return (a[sortBy_2] > b[sortBy_2] ? sortOrder_2 : -sortOrder_2); });
1042
- }
1043
- else if (stage.$skip) {
1044
- var skipCount = stage.$skip;
1045
- acc = acc.slice(skipCount);
1046
- }
1047
- else if (stage.$limit) {
1048
- var limitCount = stage.$limit;
1049
- acc = acc.slice(0, limitCount);
1050
- }
1051
- else if (stage.$unwind) {
1052
- var unwindField_1 = stage.$unwind;
1053
- acc = acc.flatMap(function (document) {
1054
- var unwindArray = document[unwindField_1] || [];
1055
- return unwindArray.map(function (arrayElement) {
1056
- var _a;
1057
- return (__assign(__assign({}, document), (_a = {}, _a[unwindField_1] = arrayElement, _a)));
1058
- });
1059
- });
1060
- }
1061
- else if (stage.$lookup) {
1062
- var localField_1 = stage.$lookup.localField;
1063
- var foreignField_1 = stage.$lookup.foreignField;
1064
- var asField_1 = stage.$lookup.as;
1065
- acc = acc.map(function (document) {
1066
- var _a;
1067
- var lookupValue = document[localField_1];
1068
- var matchingDocuments = data_3.filter(function (lookupDoc) { return lookupDoc[foreignField_1] === lookupValue; });
1069
- return __assign(__assign({}, document), (_a = {}, _a[asField_1] = matchingDocuments, _a));
1070
- });
1071
- }
1072
- else if (stage.$addFields) {
1073
- var newFields_1 = stage.$addFields;
1074
- acc = acc.map(function (document) {
1075
- for (var field in newFields_1) {
1076
- document[field] = newFields_1[field];
1077
- }
1078
- return document;
1079
- });
1080
- }
1081
- else if (stage.$replaceRoot) {
1082
- var newRootField_1 = stage.$replaceRoot.newRoot;
1083
- acc = acc.map(function (document) { return document[newRootField_1]; });
1084
- }
1085
- else if (stage.$count) {
1086
- acc = [{ count: acc.length }];
1087
- }
1088
- return acc;
1089
- }, data_3);
1090
- return [2 /*return*/, {
1091
- success: true,
1092
- message: 'Aggregation completed successfully.',
1093
- documentsCount: result.length,
1094
- aggregatedResults: result,
1095
- }];
1096
- case 2:
1097
- error_14 = _a.sent();
1098
- return [2 /*return*/, {
1099
- success: false,
1100
- message: 'Error performing aggregation.',
1101
- errorMessage: error_14.message,
1102
- documentsCount: 0,
1103
- aggregatedResults: [],
1104
- }];
1105
- case 3: return [2 /*return*/];
1106
- }
1107
- });
1108
- });
1109
- };
1110
- NanoDb.prototype.encryptData = function (encryptKey) {
1111
- return __awaiter(this, void 0, void 0, function () {
1112
- var data, algorithm, iv, cipher, encryptedData, encryptedDataObject, error_15;
1113
- return __generator(this, function (_a) {
1114
- switch (_a.label) {
1115
- case 0:
1116
- _a.trys.push([0, 3, , 4]);
1117
- return [4 /*yield*/, this.dataPromise];
1118
- case 1:
1119
- data = _a.sent();
1120
- algorithm = 'aes-256-cbc';
1121
- iv = crypto.randomBytes(16);
1122
- cipher = crypto.createCipheriv(algorithm, Buffer.from(encryptKey), iv);
1123
- encryptedData = cipher.update(JSON.stringify(data), 'utf8', 'hex');
1124
- encryptedData += cipher.final('hex');
1125
- encryptedDataObject = {
1126
- iv: iv.toString('hex'),
1127
- encryptedData: encryptedData,
1128
- };
1129
- this.dataPromise = Promise.resolve([encryptedDataObject]);
1130
- return [4 /*yield*/, fs_1.promises.writeFile(this.filePath, JSON.stringify([encryptedDataObject], null, 2), 'utf8')];
1131
- case 2:
1132
- _a.sent();
1133
- return [2 /*return*/, {
1134
- success: true,
1135
- message: 'Data encrypted and written to file successfully.',
1136
- documentsCount: data.length,
1137
- }];
1138
- case 3:
1139
- error_15 = _a.sent();
1140
- return [2 /*return*/, {
1141
- success: false,
1142
- message: 'Error encrypting and writing data to file.',
1143
- documentsCount: 0,
1144
- errorMessage: error_15.message,
1145
- }];
1146
- case 4: return [2 /*return*/];
1147
- }
1148
- });
1149
- });
1150
- };
1151
- NanoDb.prototype.decryptData = function (encryptKey) {
1152
- return __awaiter(this, void 0, void 0, function () {
1153
- var encryptedDataArray, encryptedDataObject, algorithm, decipher, decryptedData, error_16;
1154
- return __generator(this, function (_a) {
1155
- switch (_a.label) {
1156
- case 0:
1157
- _a.trys.push([0, 3, , 4]);
1158
- return [4 /*yield*/, fs_1.promises.readFile(this.filePath, 'utf8')];
1159
- case 1:
1160
- encryptedDataArray = _a.sent();
1161
- encryptedDataObject = JSON.parse(encryptedDataArray)[0];
1162
- algorithm = 'aes-256-cbc';
1163
- decipher = crypto.createDecipheriv(algorithm, Buffer.from(encryptKey), Buffer.from(encryptedDataObject.iv, 'hex'));
1164
- decryptedData = decipher.update(encryptedDataObject.encryptedData, 'hex', 'utf8');
1165
- decryptedData += decipher.final('utf8');
1166
- this.dataPromise = Promise.resolve(JSON.parse(decryptedData));
1167
- return [4 /*yield*/, fs_1.promises.writeFile(this.filePath, JSON.stringify(JSON.parse(decryptedData), null, 2), 'utf8')];
1168
- case 2:
1169
- _a.sent();
1170
- return [2 /*return*/, {
1171
- success: true,
1172
- message: 'Data decrypted and written to file successfully.',
1173
- documentsCount: JSON.parse(decryptedData).length,
1174
- }];
1175
- case 3:
1176
- error_16 = _a.sent();
1177
- return [2 /*return*/, {
1178
- success: false,
1179
- message: 'Error decrypting data.',
1180
- documentsCount: 0,
1181
- errorMessage: error_16.message,
1182
- }];
1183
- case 4: return [2 /*return*/];
1184
- }
1185
- });
1186
- });
1187
- };
1188
- NanoDb.prototype.fullTextSearch = function (query) {
1189
- return __awaiter(this, void 0, void 0, function () {
1190
- var data, foundResults, error_17;
1191
- return __generator(this, function (_a) {
1192
- switch (_a.label) {
1193
- case 0:
1194
- _a.trys.push([0, 2, , 3]);
1195
- return [4 /*yield*/, this.dataPromise];
1196
- case 1:
1197
- data = _a.sent();
1198
- foundResults = data.filter(function (document) {
1199
- for (var key in document) {
1200
- var fieldValue = String(document[key]);
1201
- if (fieldValue.toLowerCase().includes(query.toLowerCase())) {
1202
- return true;
1203
- }
1204
- }
1205
- return false;
1206
- });
1207
- return [2 /*return*/, {
1208
- success: true,
1209
- message: 'Full-text search completed successfully.',
1210
- documentsCount: foundResults.length,
1211
- foundResults: foundResults,
1212
- }];
1213
- case 2:
1214
- error_17 = _a.sent();
1215
- return [2 /*return*/, {
1216
- success: false,
1217
- message: 'Error performing full-text search.',
1218
- documentsCount: 0,
1219
- foundResults: [],
1220
- }];
1221
- case 3: return [2 /*return*/];
1222
- }
1223
- });
1224
- });
1225
- };
1226
- NanoDb.prototype.takeSnapshot = function (snapshotPathWithFileName) {
1227
- return __awaiter(this, void 0, void 0, function () {
1228
- var data, snapshotPathComponents, snapshotFileName, snapshotPath, snapshotFilePath, error_18;
1229
- return __generator(this, function (_a) {
1230
- switch (_a.label) {
1231
- case 0:
1232
- _a.trys.push([0, 3, , 4]);
1233
- return [4 /*yield*/, this.dataPromise];
1234
- case 1:
1235
- data = _a.sent();
1236
- snapshotPathComponents = snapshotPathWithFileName.split('/');
1237
- snapshotFileName = snapshotPathComponents.pop() || "snapshot-".concat(Date.now(), ".json");
1238
- snapshotPath = snapshotPathComponents.join('/');
1239
- snapshotFilePath = "".concat(snapshotPath, "/").concat(snapshotFileName);
1240
- return [4 /*yield*/, fs_1.promises.writeFile(snapshotFilePath, JSON.stringify(data, null, 2), 'utf8')];
1241
- case 2:
1242
- _a.sent();
1243
- this.emit('snapshotTaken', {
1244
- success: true,
1245
- message: 'Snapshot taken successfully.',
1246
- documentsCount: data.length,
1247
- snapshotFilePath: snapshotFilePath,
1248
- fileSizeInBytes: Buffer.from(JSON.stringify(data, null, 2)).length,
1249
- });
1250
- return [2 /*return*/, {
1251
- success: true,
1252
- message: 'Snapshot taken successfully.',
1253
- documentsCount: data.length,
1254
- snapshotFilePath: snapshotFilePath,
1255
- fileSizeInBytes: Buffer.from(JSON.stringify(data, null, 2)).length,
1256
- }];
1257
- case 3:
1258
- error_18 = _a.sent();
1259
- this.emit('snapshotError', {
1260
- success: false,
1261
- message: 'Error taking snapshot.',
1262
- errorMessage: error_18.message,
1263
- documentsCount: 0,
1264
- fileSizeInBytes: 0,
1265
- });
1266
- return [2 /*return*/, {
1267
- success: false,
1268
- message: 'Error taking snapshot.',
1269
- errorMessage: error_18.message,
1270
- documentsCount: 0,
1271
- fileSizeInBytes: 0,
1272
- }];
1273
- case 4: return [2 /*return*/];
1274
- }
1275
- });
1276
- });
1277
- };
1278
- NanoDb.prototype.restoreSnapshot = function (snapshotIndex, filePath) {
1279
- return __awaiter(this, void 0, void 0, function () {
1280
- var directoryPath, fileName, snapshotFiles, snapshotRegex_1, matchingSnapshots, snapshotFilePath, snapshotData, error_19;
1281
- return __generator(this, function (_a) {
1282
- switch (_a.label) {
1283
- case 0:
1284
- _a.trys.push([0, 4, , 5]);
1285
- directoryPath = path.dirname(filePath);
1286
- fileName = path.basename(filePath);
1287
- return [4 /*yield*/, fs_1.promises.readdir(directoryPath)];
1288
- case 1:
1289
- snapshotFiles = _a.sent();
1290
- snapshotRegex_1 = new RegExp("^".concat(fileName, "\\.snapshot-\\d+\\.json$"));
1291
- matchingSnapshots = snapshotFiles.filter(function (file) { return snapshotRegex_1.test(file); });
1292
- if (matchingSnapshots.length === 0) {
1293
- return [2 /*return*/, {
1294
- success: false,
1295
- message: 'No snapshots found for restoration.',
1296
- documentsCount: 0,
1297
- }];
1298
- }
1299
- matchingSnapshots.sort();
1300
- if (snapshotIndex < 0 || snapshotIndex >= matchingSnapshots.length) {
1301
- return [2 /*return*/, {
1302
- success: false,
1303
- message: 'Invalid snapshot index.',
1304
- documentsCount: 0,
1305
- }];
1306
- }
1307
- snapshotFilePath = path.join(directoryPath, matchingSnapshots[snapshotIndex]);
1308
- return [4 /*yield*/, fs_1.promises.readFile(snapshotFilePath, 'utf8')];
1309
- case 2:
1310
- snapshotData = _a.sent();
1311
- return [4 /*yield*/, fs_1.promises.writeFile(filePath, snapshotData, 'utf8')];
1312
- case 3:
1313
- _a.sent();
1314
- this.emit('snapshotRestored', {
1315
- success: true,
1316
- message: 'Snapshot restored successfully.',
1317
- documentsCount: JSON.parse(snapshotData).length,
1318
- snapshotFilePath: snapshotFilePath,
1319
- });
1320
- return [2 /*return*/, {
1321
- success: true,
1322
- message: 'Snapshot restored successfully.',
1323
- documentsCount: JSON.parse(snapshotData).length,
1324
- snapshotFilePath: snapshotFilePath,
1325
- }];
1326
- case 4:
1327
- error_19 = _a.sent();
1328
- return [2 /*return*/, {
1329
- success: false,
1330
- message: 'Error restoring snapshot.',
1331
- errorMessage: error_19.message,
1332
- documentsCount: 0,
1333
- }];
1334
- case 5: return [2 /*return*/];
1335
- }
1336
- });
1337
- });
1338
- };
1339
- return NanoDb;
1340
- }(events_1.EventEmitter));
1341
- exports.NanoDb = NanoDb;