inibase 1.0.0-rc.12 → 1.0.0-rc.120

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