inibase 1.0.0-rc.6 → 1.0.0-rc.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1262 @@
1
+ import "dotenv/config";
2
+ import { unlink, rename, mkdir, readdir, open, writeFile, readFile, } from "node:fs/promises";
3
+ import { existsSync, appendFileSync, readFileSync } from "node:fs";
4
+ import { join, parse } from "node:path";
5
+ import { scryptSync, randomBytes } from "node:crypto";
6
+ import { inspect } from "node:util";
7
+ import Inison from "inison";
8
+ import * as File from "./file.js";
9
+ import * as Utils from "./utils.js";
10
+ import * as UtilsServer from "./utils.server.js";
11
+ export default class Inibase {
12
+ pageInfo;
13
+ salt;
14
+ databasePath;
15
+ tables;
16
+ fileExtension = ".txt";
17
+ checkIFunique;
18
+ totalItems;
19
+ constructor(database, mainFolder = ".") {
20
+ this.databasePath = join(mainFolder, database);
21
+ this.tables = {};
22
+ this.totalItems = {};
23
+ this.pageInfo = {};
24
+ this.checkIFunique = {};
25
+ if (!process.env.INIBASE_SECRET) {
26
+ if (existsSync(".env") &&
27
+ readFileSync(".env").includes("INIBASE_SECRET="))
28
+ this.throwError("NO_ENV");
29
+ this.salt = scryptSync(randomBytes(16), randomBytes(16), 32);
30
+ appendFileSync(".env", `\nINIBASE_SECRET=${this.salt.toString("hex")}\n`);
31
+ }
32
+ else
33
+ this.salt = Buffer.from(process.env.INIBASE_SECRET, "hex");
34
+ }
35
+ throwError(code, variable, language = "en") {
36
+ const errorMessages = {
37
+ en: {
38
+ FIELD_UNIQUE: "Field {variable} should be unique, got {variable} instead",
39
+ FIELD_REQUIRED: "Field {variable} is required",
40
+ TABLE_EXISTS: "Table {variable} already exists",
41
+ TABLE_NOT_EXISTS: "Table {variable} doesn't exist",
42
+ NO_SCHEMA: "Table {variable} does't have a schema",
43
+ NO_ITEMS: "Table {variable} is empty",
44
+ NO_RESULTS: "No results found for table {variable}",
45
+ INVALID_ID: "The given ID(s) is/are not valid(s)",
46
+ INVALID_TYPE: "Expect {variable} to be {variable}, got {variable} instead",
47
+ INVALID_PARAMETERS: "The given parameters are not valid",
48
+ NO_ENV: Number(process.versions.node.split(".").reduce((a, b) => a + b)) >= 26
49
+ ? "please run with '--env-file=.env'"
50
+ : "please use dotenv",
51
+ },
52
+ // Add more languages and error messages as needed
53
+ };
54
+ const errorMessage = errorMessages[language][code];
55
+ if (!errorMessage)
56
+ return new Error("ERR");
57
+ return new Error(variable
58
+ ? Array.isArray(variable)
59
+ ? errorMessage.replace(/\{variable\}/g, () => variable.shift()?.toString() ?? "")
60
+ : errorMessage.replaceAll("{variable}", `'${variable.toString()}'`)
61
+ : errorMessage.replaceAll("{variable}", ""));
62
+ }
63
+ getFileExtension = (tableName) => {
64
+ let mainExtension = this.fileExtension;
65
+ // TODO: ADD ENCRYPTION
66
+ // if(this.tables[tableName].config.encryption)
67
+ // mainExtension += ".enc"
68
+ if (this.tables[tableName].config.compression)
69
+ mainExtension += ".gz";
70
+ return mainExtension;
71
+ };
72
+ _schemaToIdsPath = (tableName, schema, prefix = "") => {
73
+ const RETURN = {};
74
+ for (const field of schema)
75
+ if ((field.type === "array" || field.type === "object") &&
76
+ field.children &&
77
+ Utils.isArrayOfObjects(field.children)) {
78
+ Utils.deepMerge(RETURN, this._schemaToIdsPath(tableName, field.children, `${(prefix ?? "") + field.key}.`));
79
+ }
80
+ else if (field.id)
81
+ RETURN[field.id] = `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`;
82
+ return RETURN;
83
+ };
84
+ async createTable(tableName, schema, config) {
85
+ const tablePath = join(this.databasePath, tableName);
86
+ if (await File.isExists(tablePath))
87
+ this.throwError("TABLE_EXISTS", tableName);
88
+ await Promise.all([
89
+ mkdir(tablePath, { recursive: true }),
90
+ mkdir(join(tablePath, ".tmp")),
91
+ mkdir(join(tablePath, ".cache")),
92
+ ]);
93
+ if (config) {
94
+ if (config.compression)
95
+ await open(join(tablePath, ".compression.config"), "w");
96
+ if (config.cache)
97
+ await open(join(tablePath, ".cache.config"), "w");
98
+ if (config.prepend)
99
+ await open(join(tablePath, ".prepend.config"), "w");
100
+ }
101
+ if (schema)
102
+ await writeFile(join(tablePath, "schema.json"), JSON.stringify(UtilsServer.addIdToSchema(schema, 0, this.salt, false), null, 2));
103
+ }
104
+ async updateTable(tableName, schema, config) {
105
+ const table = await this.getTable(tableName), tablePath = join(this.databasePath, tableName);
106
+ if (config) {
107
+ if (config.compression !== undefined) {
108
+ if (!config.compression && table.config.compression) {
109
+ try {
110
+ await UtilsServer.exec(`gunzip -r ${tablePath}/*.txt.gz 2>/dev/null`);
111
+ await unlink(join(tablePath, ".compression.config"));
112
+ }
113
+ catch { }
114
+ }
115
+ else if (config.compression && !table.config.compression) {
116
+ try {
117
+ await UtilsServer.exec(`gzip -r ${tablePath}/*.txt 2>/dev/null`);
118
+ await open(join(tablePath, ".compression.config"), "w");
119
+ }
120
+ catch { }
121
+ }
122
+ }
123
+ if (config.cache !== undefined) {
124
+ if (config.cache && !table.config.cache)
125
+ await open(join(tablePath, ".cache.config"), "w");
126
+ else if (!config.cache && table.config.cache)
127
+ await unlink(join(tablePath, ".cache.config"));
128
+ }
129
+ if (config.prepend !== undefined) {
130
+ if (config.prepend && !table.config.prepend)
131
+ await open(join(tablePath, ".prepend.config"), "w");
132
+ else if (!config.prepend && table.config.prepend)
133
+ await unlink(join(tablePath, ".prepend.config"));
134
+ }
135
+ }
136
+ if (schema) {
137
+ // remove id from schema
138
+ schema = schema.filter(({ key }) => !["id", "createdAt", "updatedAt"].includes(key));
139
+ if (await File.isExists(join(tablePath, "schema.json"))) {
140
+ // update columns files names based on field id
141
+ const currentSchema = await this.getTableSchema(tableName, false);
142
+ schema = UtilsServer.addIdToSchema(schema, currentSchema?.length
143
+ ? UtilsServer.findLastIdNumber(currentSchema, this.salt)
144
+ : 0, this.salt, false);
145
+ if (currentSchema?.length) {
146
+ const replaceOldPathes = Utils.findChangedProperties(this._schemaToIdsPath(tableName, currentSchema), this._schemaToIdsPath(tableName, schema));
147
+ if (replaceOldPathes)
148
+ await Promise.all(Object.entries(replaceOldPathes).map(async ([oldPath, newPath]) => {
149
+ if (await File.isExists(join(tablePath, oldPath)))
150
+ await rename(join(tablePath, oldPath), join(tablePath, newPath));
151
+ }));
152
+ }
153
+ }
154
+ else
155
+ schema = UtilsServer.addIdToSchema(schema, 0, this.salt, false);
156
+ await writeFile(join(tablePath, "schema.json"), JSON.stringify(schema, null, 2));
157
+ delete this.tables[tableName];
158
+ }
159
+ }
160
+ async getTable(tableName) {
161
+ const tablePath = join(this.databasePath, tableName);
162
+ if (!(await File.isExists(tablePath)))
163
+ this.throwError("TABLE_NOT_EXISTS", tableName);
164
+ if (!this.tables[tableName])
165
+ this.tables[tableName] = {
166
+ schema: await this.getTableSchema(tableName),
167
+ config: {
168
+ compression: await File.isExists(join(tablePath, ".compression.config")),
169
+ cache: await File.isExists(join(tablePath, ".cache.config")),
170
+ prepend: await File.isExists(join(tablePath, ".prepend.config")),
171
+ },
172
+ };
173
+ return this.tables[tableName];
174
+ }
175
+ async getTableSchema(tableName, encodeIDs = true) {
176
+ const tableSchemaPath = join(this.databasePath, tableName, "schema.json");
177
+ if (!(await File.isExists(tableSchemaPath)))
178
+ return undefined;
179
+ const schemaFile = await readFile(tableSchemaPath, "utf8");
180
+ if (!schemaFile)
181
+ return undefined;
182
+ const schema = JSON.parse(schemaFile), lastIdNumber = UtilsServer.findLastIdNumber(schema, this.salt);
183
+ if (!encodeIDs)
184
+ return schema;
185
+ return [
186
+ {
187
+ id: UtilsServer.encodeID(0, this.salt),
188
+ key: "id",
189
+ type: "id",
190
+ required: true,
191
+ },
192
+ ...UtilsServer.encodeSchemaID(schema, this.salt),
193
+ {
194
+ id: UtilsServer.encodeID(lastIdNumber + 1, this.salt),
195
+ key: "createdAt",
196
+ type: "date",
197
+ required: true,
198
+ },
199
+ {
200
+ id: UtilsServer.encodeID(lastIdNumber + 2, this.salt),
201
+ key: "updatedAt",
202
+ type: "date",
203
+ required: false,
204
+ },
205
+ ];
206
+ }
207
+ async throwErrorIfTableEmpty(tableName) {
208
+ const table = await this.getTable(tableName);
209
+ if (!table.schema)
210
+ throw this.throwError("NO_SCHEMA", tableName);
211
+ if (!(await File.isExists(join(this.databasePath, tableName, `id${this.getFileExtension(tableName)}`))))
212
+ throw this.throwError("NO_ITEMS", tableName);
213
+ return table;
214
+ }
215
+ validateData(data, schema, skipRequiredField = false) {
216
+ if (Utils.isArrayOfObjects(data))
217
+ for (const single_data of data)
218
+ this.validateData(single_data, schema, skipRequiredField);
219
+ else if (Utils.isObject(data)) {
220
+ for (const field of schema) {
221
+ if (!Object.hasOwn(data, field.key) ||
222
+ data[field.key] === null ||
223
+ data[field.key] === undefined) {
224
+ if (field.required && !skipRequiredField)
225
+ throw this.throwError("FIELD_REQUIRED", field.key);
226
+ return;
227
+ }
228
+ if (Object.hasOwn(data, field.key) &&
229
+ !Utils.validateFieldType(data[field.key], field.type, (field.type === "array" || field.type === "object") &&
230
+ field.children &&
231
+ !Utils.isArrayOfObjects(field.children)
232
+ ? field.children
233
+ : undefined))
234
+ throw this.throwError("INVALID_TYPE", [
235
+ field.key,
236
+ Array.isArray(field.type) ? field.type.join(", ") : field.type,
237
+ typeof data[field.key],
238
+ ]);
239
+ if ((field.type === "array" || field.type === "object") &&
240
+ field.children &&
241
+ Utils.isArrayOfObjects(field.children))
242
+ this.validateData(data[field.key], field.children, skipRequiredField);
243
+ else if (field.unique) {
244
+ if (!this.checkIFunique[field.key])
245
+ this.checkIFunique[field.key] = [];
246
+ this.checkIFunique[`${field.key}`].push(data[field.key]);
247
+ }
248
+ }
249
+ }
250
+ }
251
+ formatField(value, field, formatOnlyAvailiableKeys) {
252
+ if (Array.isArray(field.type))
253
+ field.type = (Utils.detectFieldType(value, field.type) ??
254
+ field.type[0]);
255
+ switch (field.type) {
256
+ case "array":
257
+ if (typeof field.children === "string") {
258
+ if (field.children === "table") {
259
+ if (Array.isArray(value)) {
260
+ if (Utils.isArrayOfObjects(value)) {
261
+ if (value.every((item) => Object.hasOwn(item, "id") &&
262
+ (Utils.isValidID(item.id) || Utils.isNumber(item.id))))
263
+ value.map((item) => item.id
264
+ ? Utils.isNumber(item.id)
265
+ ? Number(item.id)
266
+ : UtilsServer.decodeID(item.id, this.salt)
267
+ : null);
268
+ }
269
+ else if (value.every(Utils.isValidID) ||
270
+ value.every(Utils.isNumber))
271
+ return value.map((item) => Utils.isNumber(item)
272
+ ? Number(item)
273
+ : UtilsServer.decodeID(item, this.salt));
274
+ }
275
+ else if (Utils.isValidID(value))
276
+ return [UtilsServer.decodeID(value, this.salt)];
277
+ else if (Utils.isNumber(value))
278
+ return [Number(value)];
279
+ }
280
+ else
281
+ return Array.isArray(value) ? value : [value];
282
+ }
283
+ else if (Utils.isArrayOfObjects(field.children))
284
+ return this.formatData(value, field.children, formatOnlyAvailiableKeys);
285
+ else if (Array.isArray(field.children))
286
+ return Array.isArray(value) ? value : [value];
287
+ break;
288
+ case "object":
289
+ if (Utils.isArrayOfObjects(field.children))
290
+ return this.formatData(value, field.children, formatOnlyAvailiableKeys);
291
+ break;
292
+ case "table":
293
+ if (Array.isArray(value))
294
+ value = value[0];
295
+ if (Utils.isObject(value)) {
296
+ if (Object.hasOwn(value, "id") &&
297
+ (Utils.isValidID(value.id) ||
298
+ Utils.isNumber(value.id)))
299
+ return Utils.isNumber(value.id)
300
+ ? Number(value.id)
301
+ : UtilsServer.decodeID(value.id, this.salt);
302
+ }
303
+ else if (Utils.isValidID(value) || Utils.isNumber(value))
304
+ return Utils.isNumber(value)
305
+ ? Number(value)
306
+ : UtilsServer.decodeID(value, this.salt);
307
+ break;
308
+ case "password":
309
+ if (Array.isArray(value))
310
+ value = value[0];
311
+ return Utils.isPassword(value)
312
+ ? value
313
+ : UtilsServer.hashPassword(String(value));
314
+ case "number":
315
+ if (Array.isArray(value))
316
+ value = value[0];
317
+ return Utils.isNumber(value) ? Number(value) : null;
318
+ case "id":
319
+ if (Array.isArray(value))
320
+ value = value[0];
321
+ return Utils.isNumber(value)
322
+ ? value
323
+ : UtilsServer.decodeID(value, this.salt);
324
+ case "json":
325
+ return typeof value !== "string" || !Utils.isJSON(value)
326
+ ? Inison.stringify(value)
327
+ : value;
328
+ default:
329
+ return value;
330
+ }
331
+ return null;
332
+ }
333
+ async checkUnique(tableName, schema) {
334
+ const tablePath = join(this.databasePath, tableName);
335
+ for await (const [key, values] of Object.entries(this.checkIFunique)) {
336
+ const field = Utils.getField(key, schema);
337
+ if (!field)
338
+ continue;
339
+ const [searchResult, totalLines] = await File.search(join(tablePath, `${key}${this.getFileExtension(tableName)}`), Array.isArray(values) ? "=" : "[]", values, undefined, field.type, field.children, 1, undefined, false, this.salt);
340
+ if (searchResult && totalLines > 0)
341
+ throw this.throwError("FIELD_UNIQUE", [
342
+ field.key,
343
+ Array.isArray(values) ? values.join(", ") : values,
344
+ ]);
345
+ }
346
+ this.checkIFunique = {};
347
+ }
348
+ formatData(data, schema, formatOnlyAvailiableKeys) {
349
+ if (Utils.isArrayOfObjects(data))
350
+ return data.map((single_data) => this.formatData(single_data, schema, formatOnlyAvailiableKeys));
351
+ if (Utils.isObject(data)) {
352
+ const RETURN = {};
353
+ for (const field of schema) {
354
+ if (!Object.hasOwn(data, field.key)) {
355
+ if (formatOnlyAvailiableKeys || !field.required)
356
+ continue;
357
+ RETURN[field.key] = this.getDefaultValue(field);
358
+ continue;
359
+ }
360
+ RETURN[field.key] = this.formatField(data[field.key], field, formatOnlyAvailiableKeys);
361
+ }
362
+ return RETURN;
363
+ }
364
+ return [];
365
+ }
366
+ getDefaultValue(field) {
367
+ if (Array.isArray(field.type))
368
+ return this.getDefaultValue({
369
+ ...field,
370
+ type: field.type.sort((a, b) => Number(b === "array") - Number(a === "array") ||
371
+ Number(a === "string") - Number(b === "string") ||
372
+ Number(a === "number") - Number(b === "number"))[0],
373
+ });
374
+ switch (field.type) {
375
+ case "array":
376
+ return Utils.isArrayOfObjects(field.children)
377
+ ? [
378
+ this.getDefaultValue({
379
+ ...field,
380
+ type: "object",
381
+ children: field.children,
382
+ }),
383
+ ]
384
+ : null;
385
+ case "object": {
386
+ if (!field.children || !Utils.isArrayOfObjects(field.children))
387
+ return null;
388
+ const RETURN = {};
389
+ for (const f of field.children)
390
+ RETURN[f.key] = this.getDefaultValue(f);
391
+ return RETURN;
392
+ }
393
+ case "boolean":
394
+ return false;
395
+ default:
396
+ return null;
397
+ }
398
+ }
399
+ _combineObjectsToArray = (input) => input.reduce((result, current) => {
400
+ for (const [key, value] of Object.entries(current))
401
+ if (Object.hasOwn(result, key) && Array.isArray(result[key]))
402
+ result[key].push(value);
403
+ else
404
+ result[key] = [value];
405
+ return result;
406
+ }, {});
407
+ _CombineData = (data, prefix) => {
408
+ if (Utils.isArrayOfObjects(data))
409
+ return this._combineObjectsToArray(data.map((single_data) => this._CombineData(single_data)));
410
+ const RETURN = {};
411
+ for (const [key, value] of Object.entries(data)) {
412
+ if (Utils.isObject(value))
413
+ Object.assign(RETURN, this._CombineData(value, `${key}.`));
414
+ else if (Utils.isArrayOfObjects(value)) {
415
+ Object.assign(RETURN, this._CombineData(this._combineObjectsToArray(value), `${(prefix ?? "") + key}.`));
416
+ }
417
+ else if (Utils.isArrayOfArrays(value) &&
418
+ value.every(Utils.isArrayOfObjects))
419
+ Object.assign(RETURN, this._CombineData(this._combineObjectsToArray(value.map(this._combineObjectsToArray)), `${(prefix ?? "") + key}.`));
420
+ else
421
+ RETURN[(prefix ?? "") + key] = File.encode(value);
422
+ }
423
+ return RETURN;
424
+ };
425
+ joinPathesContents(tableName, data) {
426
+ const tablePath = join(this.databasePath, tableName), combinedData = this._CombineData(data);
427
+ const newCombinedData = {};
428
+ for (const [key, value] of Object.entries(combinedData))
429
+ newCombinedData[join(tablePath, `${key}${this.getFileExtension(tableName)}`)] = value;
430
+ return newCombinedData;
431
+ }
432
+ _getItemsFromSchemaHelper(RETURN, item, index, field) {
433
+ if (Utils.isObject(item)) {
434
+ if (!RETURN[index])
435
+ RETURN[index] = {};
436
+ if (!RETURN[index][field.key])
437
+ RETURN[index][field.key] = [];
438
+ for (const child_field of field.children.filter((children) => children.type === "array" &&
439
+ Utils.isArrayOfObjects(children.children))) {
440
+ if (Utils.isObject(item[child_field.key])) {
441
+ for (const [key, value] of Object.entries(item[child_field.key])) {
442
+ for (let _i = 0; _i < value.length; _i++) {
443
+ if ((Array.isArray(value[_i]) && Utils.isArrayOfNulls(value[_i])) ||
444
+ value[_i] === null)
445
+ continue;
446
+ if (!RETURN[index][field.key][_i])
447
+ RETURN[index][field.key][_i] = {};
448
+ if (!RETURN[index][field.key][_i][child_field.key])
449
+ RETURN[index][field.key][_i][child_field.key] = [];
450
+ if (!Array.isArray(value[_i])) {
451
+ if (!RETURN[index][field.key][_i][child_field.key][0])
452
+ RETURN[index][field.key][_i][child_field.key][0] = {};
453
+ RETURN[index][field.key][_i][child_field.key][0][key] =
454
+ value[_i];
455
+ }
456
+ else {
457
+ value[_i].forEach((_element, _index) => {
458
+ // Recursive call
459
+ this._getItemsFromSchemaHelper(RETURN[index][field.key][_i][child_field.key][_index], _element, _index, child_field);
460
+ // Perform property assignments
461
+ if (!RETURN[index][field.key][_i][child_field.key][_index])
462
+ RETURN[index][field.key][_i][child_field.key][_index] = {};
463
+ RETURN[index][field.key][_i][child_field.key][_index][key] =
464
+ _element;
465
+ });
466
+ }
467
+ }
468
+ }
469
+ }
470
+ }
471
+ }
472
+ }
473
+ async getItemsFromSchema(tableName, schema, linesNumber, options, prefix) {
474
+ const tablePath = join(this.databasePath, tableName);
475
+ let RETURN = {};
476
+ for await (const field of schema) {
477
+ if ((field.type === "array" ||
478
+ (Array.isArray(field.type) && field.type.includes("array"))) &&
479
+ field.children) {
480
+ if (Utils.isArrayOfObjects(field.children)) {
481
+ if (field.children.filter((children) => children.type === "array" &&
482
+ Utils.isArrayOfObjects(children.children)).length) {
483
+ // one of children has array field type and has children array of object = Schema
484
+ const childItems = await this.getItemsFromSchema(tableName, field.children.filter((children) => children.type === "array" &&
485
+ Utils.isArrayOfObjects(children.children)), linesNumber, options, `${(prefix ?? "") + field.key}.`);
486
+ if (childItems)
487
+ for (const [index, item] of Object.entries(childItems))
488
+ this._getItemsFromSchemaHelper(RETURN, item, index, field);
489
+ field.children = field.children.filter((children) => children.type !== "array" ||
490
+ !Utils.isArrayOfObjects(children.children));
491
+ }
492
+ const fieldItems = await this.getItemsFromSchema(tableName, field.children, linesNumber, options, `${(prefix ?? "") + field.key}.`);
493
+ if (fieldItems)
494
+ for (const [index, item] of Object.entries(fieldItems)) {
495
+ if (!RETURN[index])
496
+ RETURN[index] = {};
497
+ if (Utils.isObject(item)) {
498
+ if (!Utils.isArrayOfNulls(Object.values(item))) {
499
+ if (RETURN[index][field.key])
500
+ Object.entries(item).forEach(([key, value], _index) => {
501
+ for (let _index = 0; _index < value.length; _index++)
502
+ if (RETURN[index][field.key][_index])
503
+ Object.assign(RETURN[index][field.key][_index], {
504
+ [key]: value[_index],
505
+ });
506
+ else
507
+ RETURN[index][field.key][_index] = {
508
+ [key]: value[_index],
509
+ };
510
+ });
511
+ else if (Object.values(item).every((_i) => Utils.isArrayOfArrays(_i) || Array.isArray(_i)) &&
512
+ prefix)
513
+ RETURN[index][field.key] = item;
514
+ else {
515
+ RETURN[index][field.key] = [];
516
+ Object.entries(item).forEach(([key, value], _ind) => {
517
+ if (!Array.isArray(value)) {
518
+ RETURN[index][field.key][_ind] = {};
519
+ RETURN[index][field.key][_ind][key] = value;
520
+ }
521
+ else
522
+ for (let _i = 0; _i < value.length; _i++) {
523
+ if (value[_i] === null ||
524
+ (Array.isArray(value[_i]) &&
525
+ Utils.isArrayOfNulls(value[_i])))
526
+ continue;
527
+ if (!RETURN[index][field.key][_i])
528
+ RETURN[index][field.key][_i] = {};
529
+ RETURN[index][field.key][_i][key] = value[_i];
530
+ }
531
+ });
532
+ }
533
+ }
534
+ else
535
+ RETURN[index][field.key] = null;
536
+ }
537
+ else
538
+ RETURN[index][field.key] = item;
539
+ }
540
+ }
541
+ else if (field.children === "table" ||
542
+ (Array.isArray(field.type) && field.type.includes("table")) ||
543
+ (Array.isArray(field.children) && field.children.includes("table"))) {
544
+ if (field.table &&
545
+ (await File.isExists(join(this.databasePath, field.table))) &&
546
+ (await File.isExists(join(tablePath, `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`)))) {
547
+ if (options.columns)
548
+ options.columns = options.columns
549
+ .filter((column) => column.includes(`${field.key}.`))
550
+ .map((column) => column.replace(`${field.key}.`, ""));
551
+ const items = await File.get(join(tablePath, `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`), linesNumber, field.type, field.children, this.salt);
552
+ if (items)
553
+ for await (const [index, item] of Object.entries(items)) {
554
+ if (!RETURN[index])
555
+ RETURN[index] = {};
556
+ RETURN[index][field.key] = item
557
+ ? await this.get(field.table, item, options)
558
+ : this.getDefaultValue(field);
559
+ }
560
+ }
561
+ }
562
+ else if (await File.isExists(join(tablePath, `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`))) {
563
+ const items = await File.get(join(tablePath, `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`), linesNumber, field.type, field.children, this.salt);
564
+ if (items)
565
+ for (const [index, item] of Object.entries(items)) {
566
+ if (!RETURN[index])
567
+ RETURN[index] = {};
568
+ RETURN[index][field.key] = item ?? this.getDefaultValue(field);
569
+ }
570
+ }
571
+ }
572
+ else if (field.type === "object") {
573
+ const fieldItems = await this.getItemsFromSchema(tableName, field.children, linesNumber, options, `${(prefix ?? "") + field.key}.`);
574
+ if (fieldItems)
575
+ for (const [index, item] of Object.entries(fieldItems)) {
576
+ if (!RETURN[index])
577
+ RETURN[index] = {};
578
+ if (Utils.isObject(item)) {
579
+ if (!Object.values(item).every((i) => i === null))
580
+ RETURN[index][field.key] = item;
581
+ else
582
+ RETURN[index][field.key] = null;
583
+ }
584
+ else
585
+ RETURN[index][field.key] = null;
586
+ }
587
+ }
588
+ else if (field.type === "table") {
589
+ if (field.table &&
590
+ (await File.isExists(join(this.databasePath, field.table))) &&
591
+ (await File.isExists(join(tablePath, `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`)))) {
592
+ if (options.columns)
593
+ options.columns = options.columns
594
+ .filter((column) => column.includes(`${field.key}.`))
595
+ .map((column) => column.replace(`${field.key}.`, ""));
596
+ const items = await File.get(join(tablePath, `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`), linesNumber, "number", undefined, this.salt);
597
+ if (items)
598
+ for await (const [index, item] of Object.entries(items)) {
599
+ if (!RETURN[index])
600
+ RETURN[index] = {};
601
+ RETURN[index][field.key] = item
602
+ ? await this.get(field.table, item, options)
603
+ : this.getDefaultValue(field);
604
+ }
605
+ }
606
+ }
607
+ else if (await File.isExists(join(tablePath, `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`))) {
608
+ const items = await File.get(join(tablePath, `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`), linesNumber, field.type, field.children, this.salt);
609
+ if (items)
610
+ for (const [index, item] of Object.entries(items)) {
611
+ if (!RETURN[index])
612
+ RETURN[index] = {};
613
+ RETURN[index][field.key] = item ?? this.getDefaultValue(field);
614
+ }
615
+ else
616
+ RETURN = Object.fromEntries(Object.entries(RETURN).map(([index, data]) => [
617
+ index,
618
+ { ...data, [field.key]: this.getDefaultValue(field) },
619
+ ]));
620
+ }
621
+ }
622
+ return RETURN;
623
+ }
624
+ async applyCriteria(tableName, schema, options, criteria, allTrue) {
625
+ const tablePath = join(this.databasePath, tableName);
626
+ let RETURN = {}, RETURN_LineNumbers = null;
627
+ if (!criteria)
628
+ return [null, null];
629
+ if (criteria.and && Utils.isObject(criteria.and)) {
630
+ const [searchResult, lineNumbers] = await this.applyCriteria(tableName, schema, options, criteria.and, true);
631
+ if (searchResult) {
632
+ RETURN = Utils.deepMerge(RETURN, Object.fromEntries(Object.entries(searchResult).filter(([_k, v], _i) => Object.keys(v).length ===
633
+ Object.keys(criteria.and ?? {}).length)));
634
+ delete criteria.and;
635
+ RETURN_LineNumbers = lineNumbers;
636
+ }
637
+ else
638
+ return [null, null];
639
+ }
640
+ if (criteria.or && Utils.isObject(criteria.or)) {
641
+ const [searchResult, lineNumbers] = await this.applyCriteria(tableName, schema, options, criteria.or, false);
642
+ delete criteria.or;
643
+ if (searchResult) {
644
+ RETURN = Utils.deepMerge(RETURN, searchResult);
645
+ RETURN_LineNumbers = lineNumbers;
646
+ }
647
+ }
648
+ if (Object.keys(criteria).length > 0) {
649
+ if (allTrue === undefined)
650
+ allTrue = true;
651
+ let index = -1;
652
+ for await (const [key, value] of Object.entries(criteria)) {
653
+ const field = Utils.getField(key, schema);
654
+ index++;
655
+ let searchOperator = undefined, searchComparedAtValue = undefined, searchLogicalOperator = undefined;
656
+ if (Utils.isObject(value)) {
657
+ if (value?.or &&
658
+ Array.isArray(value?.or)) {
659
+ const searchCriteria = (value?.or)
660
+ .map((single_or) => typeof single_or === "string"
661
+ ? Utils.FormatObjectCriteriaValue(single_or)
662
+ : ["=", single_or])
663
+ .filter((a) => a);
664
+ if (searchCriteria.length > 0) {
665
+ searchOperator = searchCriteria.map((single_or) => single_or[0]);
666
+ searchComparedAtValue = searchCriteria.map((single_or) => single_or[1]);
667
+ searchLogicalOperator = "or";
668
+ }
669
+ delete value.or;
670
+ }
671
+ if (value?.and &&
672
+ Array.isArray(value?.and)) {
673
+ const searchCriteria = (value?.and)
674
+ .map((single_and) => typeof single_and === "string"
675
+ ? Utils.FormatObjectCriteriaValue(single_and)
676
+ : ["=", single_and])
677
+ .filter((a) => a);
678
+ if (searchCriteria.length > 0) {
679
+ searchOperator = searchCriteria.map((single_and) => single_and[0]);
680
+ searchComparedAtValue = searchCriteria.map((single_and) => single_and[1]);
681
+ searchLogicalOperator = "and";
682
+ }
683
+ delete value.and;
684
+ }
685
+ }
686
+ else if (Array.isArray(value)) {
687
+ const searchCriteria = value
688
+ .map((single) => typeof single === "string"
689
+ ? Utils.FormatObjectCriteriaValue(single)
690
+ : ["=", single])
691
+ .filter((a) => a);
692
+ if (searchCriteria.length > 0) {
693
+ searchOperator = searchCriteria.map((single) => single[0]);
694
+ searchComparedAtValue = searchCriteria.map((single) => single[1]);
695
+ searchLogicalOperator = "and";
696
+ }
697
+ }
698
+ else if (typeof value === "string") {
699
+ const ComparisonOperatorValue = Utils.FormatObjectCriteriaValue(value);
700
+ if (ComparisonOperatorValue) {
701
+ searchOperator = ComparisonOperatorValue[0];
702
+ searchComparedAtValue = ComparisonOperatorValue[1];
703
+ }
704
+ }
705
+ else {
706
+ searchOperator = "=";
707
+ searchComparedAtValue = value;
708
+ }
709
+ const [searchResult, totalLines, linesNumbers] = await File.search(join(tablePath, `${key}${this.getFileExtension(tableName)}`), searchOperator ?? "=", searchComparedAtValue ?? null, searchLogicalOperator, field?.type, field?.children, options.perPage, options.page - 1 * options.perPage + 1, true, this.salt);
710
+ if (searchResult) {
711
+ RETURN = Utils.deepMerge(RETURN, Object.fromEntries(Object.entries(searchResult).map(([id, value]) => [
712
+ id,
713
+ {
714
+ [key]: value,
715
+ },
716
+ ])));
717
+ this.totalItems[`${tableName}-${key}`] = totalLines;
718
+ RETURN_LineNumbers = linesNumbers;
719
+ }
720
+ if (allTrue && index > 0) {
721
+ if (!Object.keys(RETURN).length)
722
+ RETURN = {};
723
+ RETURN = Object.fromEntries(Object.entries(RETURN).filter(([_index, item]) => Object.keys(item).length > index));
724
+ if (!Object.keys(RETURN).length)
725
+ RETURN = {};
726
+ }
727
+ }
728
+ }
729
+ return [Object.keys(RETURN).length ? RETURN : null, RETURN_LineNumbers];
730
+ }
731
+ _filterSchemaByColumns(schema, columns) {
732
+ return schema
733
+ .map((field) => {
734
+ if (columns.some((column) => column.startsWith("!")))
735
+ return columns.includes(`!${field.key}`) ? null : field;
736
+ if (columns.includes(field.key) || columns.includes("*"))
737
+ return field;
738
+ if ((field.type === "array" || field.type === "object") &&
739
+ Utils.isArrayOfObjects(field.children) &&
740
+ columns.filter((column) => column.startsWith(`${field.key}.`) ||
741
+ column.startsWith(`!${field.key}.`)).length) {
742
+ field.children = this._filterSchemaByColumns(field.children, columns
743
+ .filter((column) => column.startsWith(`${field.key}.`) ||
744
+ column.startsWith(`!${field.key}.`))
745
+ .map((column) => column.replace(`${field.key}.`, "")));
746
+ return field;
747
+ }
748
+ return null;
749
+ })
750
+ .filter((i) => i);
751
+ }
752
+ async clearCache(tablePath) {
753
+ await Promise.all((await readdir(join(tablePath, ".cache")))
754
+ ?.filter((fileName) => fileName !== `pagination${this.fileExtension}`)
755
+ .map(async (file) => unlink(join(tablePath, ".cache", file))));
756
+ }
757
+ async get(tableName, where, options = {
758
+ page: 1,
759
+ perPage: 15,
760
+ }, onlyOne, onlyLinesNumbers, _skipIdColumn) {
761
+ const tablePath = join(this.databasePath, tableName);
762
+ // Ensure options.columns is an array
763
+ if (options.columns) {
764
+ options.columns = Array.isArray(options.columns)
765
+ ? options.columns
766
+ : [options.columns];
767
+ if (!_skipIdColumn &&
768
+ options.columns.length &&
769
+ !options.columns.includes("id"))
770
+ options.columns.push("id");
771
+ }
772
+ // Default values for page and perPage
773
+ options.page = options.page || 1;
774
+ options.perPage = options.perPage || 15;
775
+ let RETURN;
776
+ let schema = (await this.throwErrorIfTableEmpty(tableName))
777
+ .schema;
778
+ if (options.columns?.length)
779
+ schema = this._filterSchemaByColumns(schema, options.columns);
780
+ if (where &&
781
+ ((Array.isArray(where) && !where.length) ||
782
+ (Utils.isObject(where) && !Object.keys(where).length)))
783
+ where = undefined;
784
+ if (!where) {
785
+ // Display all data
786
+ RETURN = Object.values(await this.getItemsFromSchema(tableName, schema, Array.from({ length: options.perPage }, (_, index) => (options.page - 1) * options.perPage +
787
+ index +
788
+ 1), options));
789
+ if (await File.isExists(join(tablePath, ".pagination")))
790
+ this.totalItems[`${tableName}-*`] = Number((await readFile(join(tablePath, ".pagination"), "utf8")).split(",")[1]);
791
+ else {
792
+ let [lastId, totalItems] = await File.get(join(tablePath, `id${this.getFileExtension(tableName)}`), -1, "number", undefined, this.salt, true);
793
+ if (lastId)
794
+ lastId = Number(Object.keys(lastId)?.[0] ?? 0);
795
+ this.totalItems[`${tableName}-*`] = totalItems;
796
+ await writeFile(join(tablePath, ".pagination"), `${lastId},${totalItems}`);
797
+ }
798
+ }
799
+ else if ((Array.isArray(where) && where.every(Utils.isNumber)) ||
800
+ Utils.isNumber(where)) {
801
+ // "where" in this case, is the line(s) number(s) and not id(s)
802
+ let lineNumbers = where;
803
+ if (!Array.isArray(lineNumbers))
804
+ lineNumbers = [lineNumbers];
805
+ // useless
806
+ if (onlyLinesNumbers)
807
+ return lineNumbers;
808
+ RETURN = Object.values((await this.getItemsFromSchema(tableName, schema, lineNumbers, options)) ?? {});
809
+ if (!this.totalItems[`${tableName}-*`])
810
+ this.totalItems[`${tableName}-*`] = lineNumbers.length;
811
+ if (RETURN?.length && !Array.isArray(where))
812
+ RETURN = RETURN[0];
813
+ }
814
+ else if ((Array.isArray(where) && where.every(Utils.isValidID)) ||
815
+ Utils.isValidID(where)) {
816
+ let Ids = where;
817
+ if (!Array.isArray(Ids))
818
+ Ids = [Ids];
819
+ const [lineNumbers, countItems] = await File.search(join(tablePath, `id${this.getFileExtension(tableName)}`), "[]", Ids.map((id) => Utils.isNumber(id) ? Number(id) : UtilsServer.decodeID(id, this.salt)), undefined, "number", undefined, Ids.length, 0, !this.totalItems[`${tableName}-*`], this.salt);
820
+ if (!lineNumbers)
821
+ throw this.throwError("NO_RESULTS", tableName);
822
+ if (onlyLinesNumbers)
823
+ return Object.keys(lineNumbers).length
824
+ ? Object.keys(lineNumbers).map(Number)
825
+ : null;
826
+ RETURN = Object.values((await this.getItemsFromSchema(tableName, schema, Object.keys(lineNumbers).map(Number), options)) ?? {});
827
+ if (!this.totalItems[`${tableName}-*`])
828
+ this.totalItems[`${tableName}-*`] = countItems;
829
+ if (RETURN?.length && !Array.isArray(where))
830
+ RETURN = RETURN[0];
831
+ }
832
+ else if (Utils.isObject(where)) {
833
+ let cachedFilePath = "";
834
+ // Criteria
835
+ if (this.tables[tableName].config.cache)
836
+ cachedFilePath = join(tablePath, ".cache", `${UtilsServer.hashString(inspect(where, { sorted: true }))}${this.fileExtension}`);
837
+ if (this.tables[tableName].config.cache &&
838
+ (await File.isExists(cachedFilePath))) {
839
+ const cachedItems = (await readFile(cachedFilePath, "utf8")).split(",");
840
+ this.totalItems[`${tableName}-*`] = cachedItems.length;
841
+ if (onlyLinesNumbers)
842
+ return cachedItems.map(Number);
843
+ return this.get(tableName, cachedItems
844
+ .slice((options.page - 1) * options.perPage, options.page * options.perPage)
845
+ .map(Number), options);
846
+ }
847
+ let linesNumbers = null;
848
+ [RETURN, linesNumbers] = await this.applyCriteria(tableName, schema, options, where);
849
+ if (RETURN && linesNumbers) {
850
+ if (onlyLinesNumbers)
851
+ return Object.keys(RETURN).map(Number);
852
+ const alreadyExistsColumns = Object.keys(Object.values(RETURN)[0]);
853
+ RETURN = Object.values(Utils.deepMerge(RETURN, await this.getItemsFromSchema(tableName, schema.filter(({ key }) => !alreadyExistsColumns.includes(key)), Object.keys(RETURN).map(Number), options)));
854
+ if (this.tables[tableName].config.cache)
855
+ await writeFile(cachedFilePath, Array.from(linesNumbers).join(","));
856
+ }
857
+ }
858
+ if (!RETURN ||
859
+ (Utils.isObject(RETURN) && !Object.keys(RETURN).length) ||
860
+ (Array.isArray(RETURN) && !RETURN.length))
861
+ return null;
862
+ const greatestTotalItems = this.totalItems[`${tableName}-*`] ??
863
+ Math.max(...Object.entries(this.totalItems)
864
+ .filter(([k]) => k.startsWith(`${tableName}-`))
865
+ .map(([, v]) => v));
866
+ this.pageInfo[tableName] = {
867
+ ...(({ columns, ...restOfOptions }) => restOfOptions)(options),
868
+ perPage: Array.isArray(RETURN) ? RETURN.length : 1,
869
+ totalPages: Math.ceil(greatestTotalItems / options.perPage),
870
+ total: greatestTotalItems,
871
+ };
872
+ return onlyOne && Array.isArray(RETURN) ? RETURN[0] : RETURN;
873
+ }
874
+ async post(tableName, data, options, returnPostedData) {
875
+ if (!options)
876
+ options = {
877
+ page: 1,
878
+ perPage: 15,
879
+ };
880
+ const tablePath = join(this.databasePath, tableName), schema = (await this.getTable(tableName)).schema;
881
+ if (!schema)
882
+ throw this.throwError("NO_SCHEMA", tableName);
883
+ if (!returnPostedData)
884
+ returnPostedData = false;
885
+ let RETURN;
886
+ const keys = UtilsServer.hashString(Object.keys(Array.isArray(data) ? data[0] : data).join("."));
887
+ let lastId = 0, totalItems = 0, renameList = [];
888
+ try {
889
+ await File.lock(join(tablePath, ".tmp"), keys);
890
+ if (await File.isExists(join(tablePath, `id${this.getFileExtension(tableName)}`))) {
891
+ if (await File.isExists(join(tablePath, ".pagination")))
892
+ [lastId, totalItems] = (await readFile(join(tablePath, ".pagination"), "utf8"))
893
+ .split(",")
894
+ .map(Number);
895
+ else {
896
+ let lastIdObj = null;
897
+ [lastIdObj, totalItems] = await File.get(join(tablePath, `id${this.getFileExtension(tableName)}`), -1, "number", undefined, this.salt, true);
898
+ if (lastIdObj)
899
+ lastId = Number(Object.keys(lastIdObj)?.[0] ?? 0);
900
+ }
901
+ }
902
+ if (Utils.isArrayOfObjects(data))
903
+ RETURN = data.map(({ id, updatedAt, createdAt, ...rest }) => ({
904
+ id: ++lastId,
905
+ ...rest,
906
+ createdAt: Date.now(),
907
+ }));
908
+ else
909
+ RETURN = (({ id, updatedAt, createdAt, ...rest }) => ({
910
+ id: ++lastId,
911
+ ...rest,
912
+ createdAt: Date.now(),
913
+ }))(data);
914
+ this.validateData(RETURN, schema);
915
+ await this.checkUnique(tableName, schema);
916
+ RETURN = this.formatData(RETURN, schema);
917
+ const pathesContents = this.joinPathesContents(tableName, this.tables[tableName].config.prepend
918
+ ? Array.isArray(RETURN)
919
+ ? RETURN.toReversed()
920
+ : RETURN
921
+ : RETURN);
922
+ await Promise.all(Object.entries(pathesContents).map(async ([path, content]) => renameList.push(await File.append(path, content, this.tables[tableName].config.prepend))));
923
+ await Promise.all(renameList.map(async ([tempPath, filePath]) => rename(tempPath, filePath)));
924
+ renameList = [];
925
+ totalItems += Array.isArray(RETURN) ? RETURN.length : 1;
926
+ if (this.tables[tableName].config.cache)
927
+ await this.clearCache(tablePath);
928
+ await writeFile(join(tablePath, ".pagination"), `${lastId},${totalItems}`);
929
+ if (returnPostedData)
930
+ return this.get(tableName, this.tables[tableName].config.prepend
931
+ ? Array.isArray(RETURN)
932
+ ? RETURN.map((_, index) => index + 1)
933
+ : 1
934
+ : Array.isArray(RETURN)
935
+ ? RETURN.map((_, index) => totalItems - index)
936
+ : totalItems, options, !Utils.isArrayOfObjects(data));
937
+ }
938
+ finally {
939
+ if (renameList.length)
940
+ await Promise.allSettled(renameList.map(async ([tempPath, _]) => unlink(tempPath)));
941
+ await File.unlock(join(tablePath, ".tmp"), keys);
942
+ }
943
+ }
944
+ async put(tableName, data, where, options = {
945
+ page: 1,
946
+ perPage: 15,
947
+ }, returnUpdatedData) {
948
+ let renameList = [];
949
+ const tablePath = join(this.databasePath, tableName), schema = (await this.throwErrorIfTableEmpty(tableName)).schema;
950
+ this.validateData(data, schema, true);
951
+ await this.checkUnique(tableName, schema);
952
+ data = this.formatData(data, schema, true);
953
+ if (!where) {
954
+ if (Utils.isArrayOfObjects(data)) {
955
+ if (!data.every((item) => Object.hasOwn(item, "id") && Utils.isValidID(item.id)))
956
+ throw this.throwError("INVALID_ID");
957
+ return this.put(tableName, data, data
958
+ .filter(({ id }) => id !== undefined)
959
+ .map(({ id }) => id));
960
+ }
961
+ if (Object.hasOwn(data, "id")) {
962
+ if (!Utils.isValidID(data.id))
963
+ throw this.throwError("INVALID_ID", data.id);
964
+ return this.put(tableName, data, data.id);
965
+ }
966
+ let totalItems;
967
+ if (await File.isExists(join(tablePath, ".pagination")))
968
+ totalItems = (await readFile(join(tablePath, ".pagination"), "utf8"))
969
+ .split(",")
970
+ .map(Number)[1];
971
+ else
972
+ totalItems = await File.count(join(tablePath, `id${this.getFileExtension(tableName)}`));
973
+ const pathesContents = this.joinPathesContents(tableName, {
974
+ ...(({ id, ...restOfData }) => restOfData)(data),
975
+ updatedAt: Date.now(),
976
+ });
977
+ try {
978
+ await File.lock(join(tablePath, ".tmp"));
979
+ await Promise.all(Object.entries(pathesContents).map(async ([path, content]) => {
980
+ const replacementObject = {};
981
+ for (const index of [...Array(totalItems)].keys())
982
+ replacementObject[`${index + 1}`] = content;
983
+ renameList.push(await File.replace(path, replacementObject));
984
+ }));
985
+ await Promise.all(renameList.map(async ([tempPath, filePath]) => rename(tempPath, filePath)));
986
+ if (this.tables[tableName].config.cache)
987
+ await this.clearCache(join(tablePath, ".cache"));
988
+ if (returnUpdatedData)
989
+ return await this.get(tableName, undefined, options);
990
+ }
991
+ finally {
992
+ if (renameList.length)
993
+ await Promise.allSettled(renameList.map(async ([tempPath, _]) => unlink(tempPath)));
994
+ await File.unlock(join(tablePath, ".tmp"));
995
+ }
996
+ }
997
+ else if ((Array.isArray(where) && where.every(Utils.isValidID)) ||
998
+ Utils.isValidID(where)) {
999
+ const lineNumbers = await this.get(tableName, where, undefined, undefined, true);
1000
+ return this.put(tableName, data, lineNumbers);
1001
+ }
1002
+ else if ((Array.isArray(where) && where.every(Utils.isNumber)) ||
1003
+ Utils.isNumber(where)) {
1004
+ // "where" in this case, is the line(s) number(s) and not id(s)
1005
+ const pathesContents = Object.fromEntries(Object.entries(this.joinPathesContents(tableName, Utils.isArrayOfObjects(data)
1006
+ ? data.map((item) => ({
1007
+ ...item,
1008
+ updatedAt: Date.now(),
1009
+ }))
1010
+ : { ...data, updatedAt: Date.now() })).map(([path, content]) => [
1011
+ path,
1012
+ [...(Array.isArray(where) ? where : [where])].reduce((obj, lineNum, index) => Object.assign(obj, {
1013
+ [lineNum]: Array.isArray(content) ? content[index] : content,
1014
+ }), {}),
1015
+ ]));
1016
+ const keys = UtilsServer.hashString(Object.keys(pathesContents)
1017
+ .map((path) => path.replaceAll(".inib", ""))
1018
+ .join("."));
1019
+ try {
1020
+ await File.lock(join(tablePath, ".tmp"), keys);
1021
+ await Promise.all(Object.entries(pathesContents).map(async ([path, content]) => renameList.push(await File.replace(path, content))));
1022
+ await Promise.all(renameList.map(async ([tempPath, filePath]) => rename(tempPath, filePath)));
1023
+ renameList = [];
1024
+ if (this.tables[tableName].config.cache)
1025
+ await this.clearCache(tablePath);
1026
+ if (returnUpdatedData)
1027
+ return this.get(tableName, where, options, !Array.isArray(where));
1028
+ }
1029
+ finally {
1030
+ if (renameList.length)
1031
+ await Promise.allSettled(renameList.map(async ([tempPath, _]) => unlink(tempPath)));
1032
+ await File.unlock(join(tablePath, ".tmp"), keys);
1033
+ }
1034
+ }
1035
+ else if (Utils.isObject(where)) {
1036
+ const lineNumbers = await this.get(tableName, where, undefined, undefined, true);
1037
+ if (returnUpdatedData)
1038
+ return this.put(tableName, data, lineNumbers, options, returnUpdatedData);
1039
+ await this.put(tableName, data, lineNumbers, options, returnUpdatedData);
1040
+ }
1041
+ else
1042
+ throw this.throwError("INVALID_PARAMETERS");
1043
+ }
1044
+ async delete(tableName, where, _id) {
1045
+ const renameList = [];
1046
+ const tablePath = join(this.databasePath, tableName);
1047
+ await this.throwErrorIfTableEmpty(tableName);
1048
+ if (!where) {
1049
+ try {
1050
+ await File.lock(join(tablePath, ".tmp"));
1051
+ await Promise.all((await readdir(tablePath))
1052
+ ?.filter((fileName) => fileName.endsWith(".inib"))
1053
+ .map(async (file) => unlink(join(tablePath, file))));
1054
+ if (this.tables[tableName].config.cache)
1055
+ await this.clearCache(tablePath);
1056
+ }
1057
+ finally {
1058
+ await File.unlock(join(tablePath, ".tmp"));
1059
+ }
1060
+ return "*";
1061
+ }
1062
+ if ((Array.isArray(where) && where.every(Utils.isValidID)) ||
1063
+ Utils.isValidID(where)) {
1064
+ const lineNumbers = await this.get(tableName, where, undefined, undefined, true);
1065
+ return this.delete(tableName, lineNumbers, where);
1066
+ }
1067
+ if ((Array.isArray(where) && where.every(Utils.isNumber)) ||
1068
+ Utils.isNumber(where)) {
1069
+ // "where" in this case, is the line(s) number(s) and not id(s)
1070
+ const files = (await readdir(tablePath))?.filter((fileName) => fileName.endsWith(this.getFileExtension(tableName)));
1071
+ if (files.length) {
1072
+ try {
1073
+ await File.lock(join(tablePath, ".tmp"));
1074
+ await Promise.all(files.map(async (file) => renameList.push(await File.remove(join(tablePath, file), where))));
1075
+ await Promise.all(renameList.map(async ([tempPath, filePath]) => rename(tempPath, filePath)));
1076
+ if (this.tables[tableName].config.cache)
1077
+ await this.clearCache(tablePath);
1078
+ if (await File.isExists(join(tablePath, ".pagination"))) {
1079
+ const [lastId, totalItems] = (await readFile(join(tablePath, ".pagination"), "utf8"))
1080
+ .split(",")
1081
+ .map(Number);
1082
+ await writeFile(join(tablePath, ".pagination"), `${lastId},${totalItems - (Array.isArray(where) ? where.length : 1)}`);
1083
+ }
1084
+ if (_id)
1085
+ return Array.isArray(_id) && _id.length === 1 ? _id[0] : _id;
1086
+ return where;
1087
+ }
1088
+ finally {
1089
+ if (renameList.length)
1090
+ await Promise.allSettled(renameList.map(async ([tempPath, _]) => unlink(tempPath)));
1091
+ await File.unlock(join(tablePath, ".tmp"));
1092
+ }
1093
+ }
1094
+ }
1095
+ else if (Utils.isObject(where)) {
1096
+ const lineNumbers = await this.get(tableName, where, undefined, undefined, true);
1097
+ return this.delete(tableName, lineNumbers);
1098
+ }
1099
+ else
1100
+ throw this.throwError("INVALID_PARAMETERS");
1101
+ return null;
1102
+ }
1103
+ async sum(tableName, columns, where) {
1104
+ const RETURN = {};
1105
+ const tablePath = join(this.databasePath, tableName);
1106
+ await this.throwErrorIfTableEmpty(tableName);
1107
+ if (!Array.isArray(columns))
1108
+ columns = [columns];
1109
+ for await (const column of columns) {
1110
+ const columnPath = join(tablePath, `${column}${this.getFileExtension(tableName)}`);
1111
+ if (await File.isExists(columnPath)) {
1112
+ if (where) {
1113
+ const lineNumbers = await this.get(tableName, where, undefined, undefined, true);
1114
+ RETURN[column] = lineNumbers
1115
+ ? await File.sum(columnPath, lineNumbers)
1116
+ : 0;
1117
+ }
1118
+ else
1119
+ RETURN[column] = await File.sum(columnPath);
1120
+ }
1121
+ }
1122
+ return Array.isArray(columns) ? RETURN : Object.values(RETURN)[0];
1123
+ }
1124
+ async max(tableName, columns, where) {
1125
+ const RETURN = {};
1126
+ const tablePath = join(this.databasePath, tableName);
1127
+ await this.throwErrorIfTableEmpty(tableName);
1128
+ if (!Array.isArray(columns))
1129
+ columns = [columns];
1130
+ for await (const column of columns) {
1131
+ const columnPath = join(tablePath, `${column}${this.getFileExtension(tableName)}`);
1132
+ if (await File.isExists(columnPath)) {
1133
+ if (where) {
1134
+ const lineNumbers = await this.get(tableName, where, undefined, undefined, true);
1135
+ RETURN[column] = lineNumbers
1136
+ ? await File.max(columnPath, lineNumbers)
1137
+ : 0;
1138
+ }
1139
+ else
1140
+ RETURN[column] = await File.max(columnPath);
1141
+ }
1142
+ }
1143
+ return RETURN;
1144
+ }
1145
+ async min(tableName, columns, where) {
1146
+ const RETURN = {};
1147
+ const tablePath = join(this.databasePath, tableName);
1148
+ await this.throwErrorIfTableEmpty(tableName);
1149
+ if (!Array.isArray(columns))
1150
+ columns = [columns];
1151
+ for await (const column of columns) {
1152
+ const columnPath = join(tablePath, `${column}${this.getFileExtension(tableName)}`);
1153
+ if (await File.isExists(columnPath)) {
1154
+ if (where) {
1155
+ const lineNumbers = await this.get(tableName, where, undefined, undefined, true);
1156
+ RETURN[column] = lineNumbers
1157
+ ? await File.min(columnPath, lineNumbers)
1158
+ : 0;
1159
+ }
1160
+ else
1161
+ RETURN[column] = await File.min(columnPath);
1162
+ }
1163
+ }
1164
+ return RETURN;
1165
+ }
1166
+ async sort(tableName, columns, where, options = {
1167
+ page: 1,
1168
+ perPage: 15,
1169
+ }) {
1170
+ const tablePath = join(this.databasePath, tableName), schema = (await this.throwErrorIfTableEmpty(tableName)).schema;
1171
+ // Default values for page and perPage
1172
+ options.page = options.page || 1;
1173
+ options.perPage = options.perPage || 15;
1174
+ let sortArray, isLineNumbers = true, keepItems = [];
1175
+ if (Utils.isObject(columns) && !Array.isArray(columns)) {
1176
+ // {name: "ASC", age: "DESC"}
1177
+ sortArray = Object.entries(columns).map(([key, value]) => [
1178
+ key,
1179
+ typeof value === "string" ? value.toLowerCase() === "asc" : value > 0,
1180
+ ]);
1181
+ }
1182
+ else {
1183
+ if (!Array.isArray(columns))
1184
+ columns = [columns];
1185
+ sortArray = columns.map((column) => [column, true]);
1186
+ }
1187
+ let cacheKey = "";
1188
+ // Criteria
1189
+ if (this.tables[tableName].config.cache)
1190
+ cacheKey = UtilsServer.hashString(inspect(sortArray, { sorted: true }));
1191
+ if (where) {
1192
+ const lineNumbers = await this.get(tableName, where, undefined, undefined, true);
1193
+ keepItems = Object.values((await File.get(join(tablePath, `id${this.getFileExtension(tableName)}`), lineNumbers, "number", undefined, this.salt)) ?? {}).map(Number);
1194
+ isLineNumbers = false;
1195
+ if (!keepItems.length)
1196
+ throw this.throwError("NO_RESULTS", tableName);
1197
+ keepItems = keepItems.slice((options.page - 1) * options.perPage, options.page * options.perPage);
1198
+ }
1199
+ if (!keepItems.length)
1200
+ keepItems = Array.from({ length: options.perPage }, (_, index) => (options.page - 1) * options.perPage +
1201
+ index +
1202
+ 1);
1203
+ const filesPathes = [["id", true], ...sortArray].map((column) => join(tablePath, `${column[0]}${this.getFileExtension(tableName)}`));
1204
+ // Construct the paste command to merge files and filter lines by IDs
1205
+ const pasteCommand = `paste ${filesPathes.join(" ")}`;
1206
+ // Construct the sort command dynamically based on the number of files for sorting
1207
+ const index = 2;
1208
+ const sortColumns = sortArray
1209
+ .map(([key, ascending], i) => {
1210
+ const field = Utils.getField(key, schema);
1211
+ if (field)
1212
+ return `-k${i + index},${i + index}${field.type === "number" ? "n" : ""}${!ascending ? "r" : ""}`;
1213
+ return "";
1214
+ })
1215
+ .join(" ");
1216
+ const sortCommand = `sort ${sortColumns}`;
1217
+ // Construct the awk command to keep only the specified lines after sorting
1218
+ const awkCommand = isLineNumbers
1219
+ ? `awk '${keepItems.map((line) => `NR==${line}`).join(" || ")}'`
1220
+ : `awk 'NR==${keepItems[0]}${keepItems
1221
+ .map((num) => `||NR==${num}`)
1222
+ .join("")}'`;
1223
+ try {
1224
+ if (cacheKey)
1225
+ await File.lock(join(tablePath, ".tmp"), cacheKey);
1226
+ // Combine the commands
1227
+ // Execute the command synchronously
1228
+ const lines = (await UtilsServer.exec(this.tables[tableName].config.cache
1229
+ ? (await File.isExists(join(tablePath, ".cache", `${cacheKey}${this.fileExtension}`)))
1230
+ ? `${awkCommand} ${join(tablePath, ".cache", `${cacheKey}${this.fileExtension}`)}`
1231
+ : `${pasteCommand} | ${sortCommand} -o ${join(tablePath, ".cache", `${cacheKey}${this.fileExtension}`)} && ${awkCommand} ${join(tablePath, ".cache", `${cacheKey}${this.fileExtension}`)}`
1232
+ : `${pasteCommand} | ${sortCommand} | ${awkCommand}`, {
1233
+ encoding: "utf-8",
1234
+ })).stdout
1235
+ .trim()
1236
+ .split("\n");
1237
+ // Parse the result and extract the specified lines
1238
+ const outputArray = lines.map((line) => {
1239
+ const splitedFileColumns = line.split("\t"); // Assuming tab-separated columns
1240
+ const outputObject = {};
1241
+ // Extract values for each file, including `id${this.getFileExtension(tableName)}`
1242
+ filesPathes.forEach((fileName, index) => {
1243
+ const field = Utils.getField(parse(fileName).name, schema);
1244
+ if (field)
1245
+ outputObject[field.key] = File.decode(splitedFileColumns[index], field?.type, field?.children, this.salt);
1246
+ });
1247
+ return outputObject;
1248
+ });
1249
+ const restOfColumns = await this.get(tableName, outputArray.map(({ id }) => id), options, undefined, undefined, true);
1250
+ return restOfColumns
1251
+ ? outputArray.map((item, index) => ({
1252
+ ...item,
1253
+ ...restOfColumns[index],
1254
+ }))
1255
+ : outputArray;
1256
+ }
1257
+ finally {
1258
+ if (cacheKey)
1259
+ await File.unlock(join(tablePath, ".tmp"), cacheKey);
1260
+ }
1261
+ }
1262
+ }