inibase 1.0.0-rc.9 → 1.0.0-rc.90

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