@nmakarov/cli-toolkit 0.1.4 → 0.3.0

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.
@@ -0,0 +1,908 @@
1
+ // src/filedatabase/index.ts
2
+ import fs3 from "fs";
3
+ import path3 from "path";
4
+
5
+ // src/utils/os-utils.ts
6
+ import fs from "fs";
7
+ import path from "path";
8
+ import { execSync } from "child_process";
9
+ function getFreeDiskSpace(targetPath) {
10
+ try {
11
+ let pathToCheck = targetPath;
12
+ if (!fs.existsSync(targetPath)) {
13
+ const parentDir = path.dirname(targetPath);
14
+ if (fs.existsSync(parentDir)) {
15
+ pathToCheck = parentDir;
16
+ } else {
17
+ pathToCheck = process.platform === "win32" ? "C:\\" : "/";
18
+ }
19
+ }
20
+ if (process.platform === "win32") {
21
+ return null;
22
+ } else {
23
+ const stdout = execSync(`df -k "${pathToCheck}"`, { encoding: "utf8" });
24
+ const lines = stdout.trim().split("\n");
25
+ const parts = lines[1].split(/\s+/);
26
+ const freeKb = parseInt(parts[3], 10);
27
+ return freeKb * 1024;
28
+ }
29
+ } catch (error) {
30
+ return null;
31
+ }
32
+ }
33
+
34
+ // src/utils/fs-utils.ts
35
+ import fs2 from "fs";
36
+ import path2 from "path";
37
+ async function ensurePath(...pathParts) {
38
+ const fullPath = path2.resolve(...pathParts);
39
+ if (!fs2.existsSync(fullPath)) {
40
+ await fs2.promises.mkdir(fullPath, { recursive: true });
41
+ }
42
+ return fullPath;
43
+ }
44
+ function getFileExtension(dataType) {
45
+ switch (dataType) {
46
+ case "json-array":
47
+ case "json-object":
48
+ return "json";
49
+ case "text":
50
+ return "txt";
51
+ case "xml":
52
+ return "xml";
53
+ default:
54
+ return "json";
55
+ }
56
+ }
57
+
58
+ // src/utils/format-utils.ts
59
+ function bytesToHumanReadable(bytes) {
60
+ if (bytes === 0) return "0 B";
61
+ const k = 1024;
62
+ const sizes = ["B", "KB", "MB", "GB", "TB", "PB"];
63
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
64
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
65
+ }
66
+
67
+ // src/utils/date-utils.ts
68
+ function isTimestampFolder(folderName) {
69
+ const isoRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(Z|\.\d{3}Z)$/;
70
+ if (!isoRegex.test(folderName)) {
71
+ return false;
72
+ }
73
+ const date = new Date(folderName);
74
+ return !isNaN(date.getTime()) && date.getTime() > 0;
75
+ }
76
+
77
+ // src/filedatabase/serializers.ts
78
+ function detectDataType(data) {
79
+ if (Array.isArray(data)) {
80
+ return "json-array";
81
+ } else if (typeof data === "object" && data !== null) {
82
+ return "json-object";
83
+ } else if (typeof data === "string") {
84
+ const trimmed = data.trim();
85
+ if (trimmed.startsWith("<?xml") || trimmed.startsWith("<")) {
86
+ return "xml";
87
+ }
88
+ return "text";
89
+ } else {
90
+ return "text";
91
+ }
92
+ }
93
+ function serializeData(data) {
94
+ const dataType = detectDataType(data);
95
+ if (dataType === "json-array" || dataType === "json-object") {
96
+ return JSON.stringify(data, null, 4);
97
+ } else {
98
+ return String(data);
99
+ }
100
+ }
101
+ function deserializeData(rawData, dataType) {
102
+ if (dataType === "json-array" || dataType === "json-object") {
103
+ return JSON.parse(rawData);
104
+ } else {
105
+ return rawData;
106
+ }
107
+ }
108
+
109
+ // src/errors.ts
110
+ var FrameworkError = class extends Error {
111
+ constructor(message) {
112
+ super(message);
113
+ this.name = "FrameworkError";
114
+ }
115
+ };
116
+ var ParamError = class extends FrameworkError {
117
+ constructor(message) {
118
+ super(message);
119
+ this.name = "ParamError";
120
+ }
121
+ };
122
+
123
+ // src/filedatabase/synopsis-functions.ts
124
+ function defaultFileSynopsisFunction(fileEntry, data) {
125
+ if (!Array.isArray(data) || data.length === 0) {
126
+ return { ...fileEntry };
127
+ }
128
+ const timestamps = [];
129
+ const statusCounts = {};
130
+ for (const item of data) {
131
+ let ts = null;
132
+ let status = null;
133
+ for (const [key, value] of Object.entries(item)) {
134
+ const k = key.toLowerCase();
135
+ if (k === "modificationtimestamp") {
136
+ ts = new Date(value).getTime();
137
+ }
138
+ if (k === "standardstatus") {
139
+ status = value;
140
+ }
141
+ }
142
+ if (ts && !isNaN(ts)) {
143
+ timestamps.push(ts);
144
+ }
145
+ if (status !== null && status !== void 0) {
146
+ statusCounts[status] = (statusCounts[status] || 0) + 1;
147
+ }
148
+ }
149
+ const result = { ...fileEntry };
150
+ if (timestamps.length) {
151
+ result.minModificationTimestamp = new Date(Math.min(...timestamps)).toISOString();
152
+ result.maxModificationTimestamp = new Date(Math.max(...timestamps)).toISOString();
153
+ }
154
+ if (Object.keys(statusCounts).length) {
155
+ result.StandardStatuses = statusCounts;
156
+ }
157
+ return result;
158
+ }
159
+ function defaultVersionSynopsisFunction(metadata) {
160
+ if (!metadata?.files || !Array.isArray(metadata.files)) {
161
+ return metadata;
162
+ }
163
+ const timestamps = [];
164
+ const statusCounts = {};
165
+ for (const file of metadata.files) {
166
+ if (file.minModificationTimestamp) {
167
+ const minTs = new Date(file.minModificationTimestamp).getTime();
168
+ if (!isNaN(minTs)) timestamps.push(minTs);
169
+ }
170
+ if (file.maxModificationTimestamp) {
171
+ const maxTs = new Date(file.maxModificationTimestamp).getTime();
172
+ if (!isNaN(maxTs)) timestamps.push(maxTs);
173
+ }
174
+ if (file.StandardStatuses && typeof file.StandardStatuses === "object") {
175
+ for (const [status, count] of Object.entries(file.StandardStatuses)) {
176
+ statusCounts[status] = (statusCounts[status] || 0) + count;
177
+ }
178
+ }
179
+ }
180
+ const result = { ...metadata };
181
+ if (timestamps.length) {
182
+ result.minModificationTimestamp = new Date(Math.min(...timestamps)).toISOString();
183
+ result.maxModificationTimestamp = new Date(Math.max(...timestamps)).toISOString();
184
+ }
185
+ if (Object.keys(statusCounts).length > 0) {
186
+ result.StandardStatuses = statusCounts;
187
+ }
188
+ return result;
189
+ }
190
+
191
+ // src/filedatabase/index.ts
192
+ var FileDatabaseError = class extends Error {
193
+ constructor(message) {
194
+ super(message);
195
+ this.name = "FileDatabaseError";
196
+ }
197
+ };
198
+ var FileDatabase = class {
199
+ basePath;
200
+ namespace;
201
+ tableName = null;
202
+ versioned;
203
+ maxVersions;
204
+ pageSize;
205
+ useMetadata;
206
+ freeSpaceThreshold;
207
+ logger;
208
+ // Current operation state
209
+ currentVersion = null;
210
+ currentVersionFolder = null;
211
+ currentFileNumber = 0;
212
+ currentRecord = 0;
213
+ hasReadFirstPage = false;
214
+ lastFileData = null;
215
+ metadata;
216
+ // Synopsis calculation functions
217
+ fileSynopsisFunction = null;
218
+ versionSynopsisFunction = null;
219
+ constructor(config) {
220
+ if (!config.basePath) {
221
+ throw new ParamError("[FileDatabase] basePath is required");
222
+ }
223
+ this.basePath = config.basePath;
224
+ this.namespace = config.namespace || "default";
225
+ this.tableName = config.tableName || null;
226
+ this.versioned = config.versioned ?? true;
227
+ this.maxVersions = config.maxVersions || 5;
228
+ this.pageSize = config.pageSize || 5e3;
229
+ this.useMetadata = config.useMetadata !== false;
230
+ this.freeSpaceThreshold = config.freeSpaceThreshold || 100 * 1024 * 1024;
231
+ this.logger = config.logger || console;
232
+ this.metadata = this.getDefaultMetadata();
233
+ }
234
+ /**
235
+ * Get default metadata structure
236
+ */
237
+ getDefaultMetadata() {
238
+ return {
239
+ version: this.currentVersion || null,
240
+ files: [],
241
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
242
+ modifiedAt: (/* @__PURE__ */ new Date()).toISOString(),
243
+ totalRecords: 0,
244
+ synopsis: null,
245
+ dataType: null
246
+ };
247
+ }
248
+ /**
249
+ * Get the destination path (basePath/namespace/tableName[/version])
250
+ */
251
+ getDestinationPath(version) {
252
+ const errors = ["basePath", "namespace", "tableName"].filter((prop) => !this[prop]).map((prop) => `${prop} is not set`);
253
+ if (errors.length) {
254
+ throw new FileDatabaseError(`[FileDatabase] ${errors.join("; ")}`);
255
+ }
256
+ let parts = [this.basePath, this.namespace];
257
+ if (this.tableName) {
258
+ parts.push(...this.tableName.split("/"));
259
+ }
260
+ if (this.versioned && version) {
261
+ parts.push(version);
262
+ }
263
+ return path3.resolve(...parts);
264
+ }
265
+ /**
266
+ * Set current version and version folder
267
+ */
268
+ async setCurrentVersion(version) {
269
+ this.currentVersion = version;
270
+ this.currentVersionFolder = await ensurePath(this.getDestinationPath(), version);
271
+ }
272
+ /**
273
+ * Create a new version folder with comprehensive timestamp logic
274
+ * Only works in versioned mode
275
+ */
276
+ async makeNewVersion() {
277
+ if (!this.versioned) {
278
+ throw new FileDatabaseError("makeNewVersion() only works in versioned mode");
279
+ }
280
+ this.metadata = this.getDefaultMetadata();
281
+ const existingVersions = await this.getVersions();
282
+ let versionName;
283
+ if (existingVersions.length > 0) {
284
+ const maxTimestamp = existingVersions.reduce((max, version) => {
285
+ const versionDate = new Date(version.replace("Z", ""));
286
+ const maxDate2 = new Date(max.replace("Z", ""));
287
+ return versionDate > maxDate2 ? version : max;
288
+ });
289
+ const maxDate = new Date(maxTimestamp.replace("Z", ""));
290
+ const nextDate = new Date(maxDate.getTime() + 1e3);
291
+ versionName = nextDate.toISOString().split(".")[0] + "Z";
292
+ } else {
293
+ const now = /* @__PURE__ */ new Date();
294
+ versionName = now.toISOString().split(".")[0] + "Z";
295
+ }
296
+ await this.setCurrentVersion(versionName);
297
+ this.currentFileNumber = 0;
298
+ const versions = await this.getVersions();
299
+ while (versions.length > this.maxVersions) {
300
+ const versionToDelete = path3.resolve(this.getDestinationPath(), versions.shift());
301
+ this.logger.debug?.(`[FileDatabase] Deleting old version: ${versionToDelete}`);
302
+ await fs3.promises.rm(versionToDelete, { recursive: true, force: true });
303
+ }
304
+ return versionName;
305
+ }
306
+ /**
307
+ * Get list of all versions (sorted chronologically)
308
+ * Only works in versioned mode
309
+ */
310
+ async getVersions() {
311
+ if (!this.versioned) {
312
+ return [];
313
+ }
314
+ const destPath = this.getDestinationPath();
315
+ try {
316
+ await ensurePath(destPath);
317
+ const items = await fs3.promises.readdir(destPath);
318
+ const versions = items.filter((item) => {
319
+ const itemPath = path3.join(destPath, item);
320
+ const stat = fs3.statSync(itemPath);
321
+ return stat.isDirectory() && isTimestampFolder(item);
322
+ });
323
+ return versions.sort();
324
+ } catch (error) {
325
+ return [];
326
+ }
327
+ }
328
+ /**
329
+ * Get the latest version (most recent timestamp)
330
+ * Only works in versioned mode
331
+ * @returns Latest version string or null if no versions
332
+ */
333
+ async getLatestVersion() {
334
+ if (!this.versioned) {
335
+ throw new FileDatabaseError("getLatestVersion() only works in versioned mode");
336
+ }
337
+ const versions = await this.getVersions();
338
+ if (versions.length === 0) {
339
+ return null;
340
+ }
341
+ return versions[versions.length - 1];
342
+ }
343
+ /**
344
+ * Check if any data exists in this table
345
+ * Works for both versioned and non-versioned modes
346
+ * @returns true if data exists
347
+ */
348
+ async hasData() {
349
+ const tablePath = this.getDestinationPath();
350
+ if (!fs3.existsSync(tablePath)) {
351
+ return false;
352
+ }
353
+ if (this.versioned) {
354
+ const versions = await this.getVersions();
355
+ return versions.length > 0;
356
+ } else {
357
+ const items = await fs3.promises.readdir(tablePath);
358
+ return items.some(
359
+ (item) => item === "metadata.json" || item.match(/^\d{6}\.(json|txt|xml)$/) || item.endsWith(".json")
360
+ );
361
+ }
362
+ }
363
+ /**
364
+ * Auto-detect the data format in this table
365
+ * Used when reading existing data
366
+ * @returns Format detection result
367
+ */
368
+ async detectDataFormat() {
369
+ const tablePath = this.getDestinationPath();
370
+ if (!fs3.existsSync(tablePath)) {
371
+ return { versioned: false, hasMetadata: false, dataType: null };
372
+ }
373
+ const items = await fs3.promises.readdir(tablePath);
374
+ if (items.includes("metadata.json")) {
375
+ const metadata = JSON.parse(
376
+ await fs3.promises.readFile(path3.join(tablePath, "metadata.json"), "utf8")
377
+ );
378
+ return {
379
+ versioned: false,
380
+ hasMetadata: true,
381
+ dataType: metadata.dataType || null
382
+ };
383
+ }
384
+ const versionFolders = items.filter((item) => {
385
+ const itemPath = path3.join(tablePath, item);
386
+ const stat = fs3.statSync(itemPath);
387
+ return stat.isDirectory() && isTimestampFolder(item);
388
+ });
389
+ if (versionFolders.length > 0) {
390
+ const latestVersion = versionFolders.sort().pop();
391
+ const versionMetadataPath = path3.join(tablePath, latestVersion, "metadata.json");
392
+ return {
393
+ versioned: true,
394
+ hasMetadata: fs3.existsSync(versionMetadataPath),
395
+ dataType: null
396
+ };
397
+ }
398
+ const dataFiles = items.filter((f) => f.match(/^\d{6}\.(json|txt|xml)$/));
399
+ if (dataFiles.length > 0) {
400
+ return {
401
+ versioned: false,
402
+ hasMetadata: false,
403
+ dataType: null
404
+ };
405
+ }
406
+ return { versioned: false, hasMetadata: false, dataType: null };
407
+ }
408
+ /**
409
+ * Load metadata from JSON file
410
+ */
411
+ async loadMetadataJson(version) {
412
+ const metadataFile = path3.join(this.getDestinationPath(), version, "metadata.json");
413
+ if (fs3.existsSync(metadataFile)) {
414
+ try {
415
+ const rawData = await fs3.promises.readFile(metadataFile, "utf8");
416
+ return JSON.parse(rawData);
417
+ } catch (e) {
418
+ throw new FileDatabaseError(`Failed to read metadata for version "${version}": ${e.message}`);
419
+ }
420
+ }
421
+ return null;
422
+ }
423
+ /**
424
+ * Build metadata by scanning files in a version folder (backward compatibility)
425
+ * Reads all files to get accurate counts - used when synopsis calculation is needed
426
+ */
427
+ async figureMetadataFromVersionFiles(version) {
428
+ const versionPath = path3.join(this.getDestinationPath(), version);
429
+ if (!fs3.existsSync(versionPath)) {
430
+ return this.getDefaultMetadata();
431
+ }
432
+ const files = (await fs3.promises.readdir(versionPath)).filter((file) => file !== "metadata.json" && !file.startsWith(".")).sort();
433
+ const metadata = this.getDefaultMetadata();
434
+ metadata.version = version;
435
+ metadata.files = [];
436
+ let totalRecords = 0;
437
+ let detectedDataType = null;
438
+ for (let i = 0; i < files.length; i++) {
439
+ const fileName = files[i];
440
+ const filePath = path3.join(versionPath, fileName);
441
+ try {
442
+ const rawData = await fs3.promises.readFile(filePath, "utf8");
443
+ const extension = path3.extname(fileName).toLowerCase();
444
+ let dataType = "text";
445
+ if (extension === ".json") {
446
+ dataType = "json-array";
447
+ } else if (extension === ".xml") {
448
+ dataType = "xml";
449
+ }
450
+ const fileData = deserializeData(rawData, dataType);
451
+ const recordsCount = Array.isArray(fileData) ? fileData.length : 1;
452
+ if (detectedDataType === null) {
453
+ detectedDataType = detectDataType(fileData);
454
+ }
455
+ const fileInfo = {
456
+ number: i + 1,
457
+ recordsCount,
458
+ fileName
459
+ };
460
+ metadata.files.push(fileInfo);
461
+ totalRecords += recordsCount;
462
+ } catch (error) {
463
+ this.logger.error?.(`[FileDatabase] Failed to read file ${fileName}: ${error.message}`);
464
+ }
465
+ }
466
+ metadata.totalRecords = totalRecords;
467
+ metadata.dataType = detectedDataType;
468
+ return metadata;
469
+ }
470
+ /**
471
+ * Build metadata optimized - only reads first and last files
472
+ * Assumes all middle files have the same record count as the first file
473
+ * Much faster for large datasets with many files
474
+ */
475
+ async buildMetadataOptimized(version) {
476
+ const versionPath = path3.join(this.getDestinationPath(), version);
477
+ if (!fs3.existsSync(versionPath)) {
478
+ return this.getDefaultMetadata();
479
+ }
480
+ const files = (await fs3.promises.readdir(versionPath)).filter((file) => file !== "metadata.json" && !file.startsWith(".")).sort();
481
+ if (files.length === 0) {
482
+ return this.getDefaultMetadata();
483
+ }
484
+ const metadata = this.getDefaultMetadata();
485
+ metadata.version = version;
486
+ metadata.files = files.map((fileName, index) => ({
487
+ number: index + 1,
488
+ recordsCount: 0,
489
+ fileName
490
+ }));
491
+ const firstFile = metadata.files[0];
492
+ const firstFilePath = path3.join(versionPath, firstFile.fileName);
493
+ const firstFileRaw = await fs3.promises.readFile(firstFilePath, "utf8");
494
+ let firstFileData;
495
+ try {
496
+ firstFileData = JSON.parse(firstFileRaw);
497
+ } catch (e) {
498
+ firstFileData = firstFileRaw;
499
+ }
500
+ metadata.dataType = detectDataType(firstFileData);
501
+ if (metadata.dataType === "json-array") {
502
+ const firstFileCount = Array.isArray(firstFileData) ? firstFileData.length : 1;
503
+ firstFile.recordsCount = firstFileCount;
504
+ for (let i = 1; i < metadata.files.length - 1; i++) {
505
+ metadata.files[i].recordsCount = firstFileCount;
506
+ }
507
+ if (files.length > 1) {
508
+ const lastFile = metadata.files[metadata.files.length - 1];
509
+ const lastFilePath = path3.join(versionPath, lastFile.fileName);
510
+ const lastFileRaw = await fs3.promises.readFile(lastFilePath, "utf8");
511
+ const lastFileData = deserializeData(lastFileRaw, metadata.dataType);
512
+ lastFile.recordsCount = Array.isArray(lastFileData) ? lastFileData.length : 1;
513
+ }
514
+ metadata.totalRecords = metadata.files.reduce((sum, file) => sum + file.recordsCount, 0);
515
+ } else {
516
+ metadata.files.forEach((file) => {
517
+ file.recordsCount = 1;
518
+ });
519
+ metadata.totalRecords = files.length;
520
+ }
521
+ return metadata;
522
+ }
523
+ /**
524
+ * Figure out metadata - tries JSON first, then builds from files
525
+ * Uses optimized building when no synopsis calculation is needed
526
+ */
527
+ async figureMetadata(version, useOptimized = true) {
528
+ if (this.useMetadata) {
529
+ const metadata = await this.loadMetadataJson(version);
530
+ if (metadata) {
531
+ return metadata;
532
+ }
533
+ }
534
+ if (useOptimized && !this.fileSynopsisFunction && !this.versionSynopsisFunction) {
535
+ return await this.buildMetadataOptimized(version);
536
+ }
537
+ return await this.figureMetadataFromVersionFiles(version);
538
+ }
539
+ /**
540
+ * Load version metadata (main entry point for loading)
541
+ */
542
+ async loadVersionMetadata(version) {
543
+ const metadata = await this.figureMetadata(version);
544
+ this.metadata = metadata;
545
+ return metadata;
546
+ }
547
+ /**
548
+ * Save version metadata to file
549
+ */
550
+ async saveVersionMetadata(metadata) {
551
+ if (!this.useMetadata) {
552
+ return;
553
+ }
554
+ const metadataToSave = metadata || this.metadata;
555
+ let metadataFile;
556
+ if (this.versioned) {
557
+ if (!this.currentVersion) {
558
+ return;
559
+ }
560
+ metadataFile = path3.join(this.getDestinationPath(), this.currentVersion, "metadata.json");
561
+ } else {
562
+ metadataFile = path3.join(this.getDestinationPath(), "metadata.json");
563
+ }
564
+ await fs3.promises.writeFile(metadataFile, JSON.stringify(metadataToSave, null, 4), "utf8");
565
+ }
566
+ /**
567
+ * Create a new file entry in metadata
568
+ */
569
+ makeNewFile() {
570
+ this.currentFileNumber = (this.currentFileNumber || 0) + 1;
571
+ const dataType = this.metadata.dataType || "json-array";
572
+ const fileEntry = {
573
+ number: this.currentFileNumber,
574
+ recordsCount: 0,
575
+ fileName: `${this.currentFileNumber.toString().padStart(6, "0")}.${getFileExtension(dataType)}`
576
+ };
577
+ this.metadata.files.push(fileEntry);
578
+ this.lastFileData = null;
579
+ this.logger.debug?.(`[FileDatabase] Created new file: ${fileEntry.fileName}, fileNumber: ${this.currentFileNumber}`);
580
+ }
581
+ /**
582
+ * Figure out what data to write and which file to use (for pagination)
583
+ */
584
+ figureOutDataAndFileToWrite(data) {
585
+ let dataToWrite;
586
+ let dataLeftOver;
587
+ const lastFile = this.metadata.files[this.metadata.files.length - 1];
588
+ const lastFileRecordsCount = lastFile.recordsCount;
589
+ if (Array.isArray(data)) {
590
+ if (lastFileRecordsCount < this.pageSize) {
591
+ dataToWrite = [...this.lastFileData || [], ...data.slice(0, this.pageSize - lastFileRecordsCount)];
592
+ dataLeftOver = data.slice(this.pageSize - lastFileRecordsCount);
593
+ } else {
594
+ this.makeNewFile();
595
+ dataToWrite = data.slice(0, this.pageSize);
596
+ dataLeftOver = data.slice(this.pageSize);
597
+ }
598
+ this.lastFileData = dataToWrite;
599
+ } else {
600
+ dataToWrite = data;
601
+ dataLeftOver = null;
602
+ }
603
+ const fileName = this.metadata.files[this.metadata.files.length - 1].fileName;
604
+ this.logger.debug?.(
605
+ `[FileDatabase] figureOutDataAndFileToWrite: filename=${fileName}, dataToWrite.length=${Array.isArray(dataToWrite) ? dataToWrite.length : "N/A"}, lastFileRecordsCount=${lastFileRecordsCount}`
606
+ );
607
+ return { dataToWrite, dataLeftOver, fileName };
608
+ }
609
+ /**
610
+ * Calculate file-level synopsis if function is set
611
+ */
612
+ calculateFileSynopsis(data, fileIndex = this.metadata.files.length - 1) {
613
+ if (!this.fileSynopsisFunction) {
614
+ return;
615
+ }
616
+ const fileInfo = this.metadata.files[fileIndex];
617
+ const enhancedFileInfo = this.fileSynopsisFunction(fileInfo, data);
618
+ this.metadata.files[fileIndex] = enhancedFileInfo;
619
+ }
620
+ /**
621
+ * Calculate version-level synopsis if function is set
622
+ */
623
+ calculateVersionSynopsis() {
624
+ if (!this.versionSynopsisFunction) {
625
+ return;
626
+ }
627
+ const enhancedMetadata = this.versionSynopsisFunction(this.metadata);
628
+ this.metadata = enhancedMetadata;
629
+ }
630
+ /**
631
+ * Update metadata after writing data
632
+ */
633
+ updateMetadata(dataToWrite, fileName) {
634
+ let currentFile;
635
+ if (fileName) {
636
+ const foundFile = this.metadata.files.find((file) => file.fileName === fileName);
637
+ if (!foundFile) {
638
+ this.logger.warn?.(`[FileDatabase] File ${fileName} not found in metadata, using last file`);
639
+ currentFile = this.metadata.files[this.metadata.files.length - 1];
640
+ } else {
641
+ currentFile = foundFile;
642
+ }
643
+ } else {
644
+ currentFile = this.metadata.files[this.metadata.files.length - 1];
645
+ }
646
+ const recordsCount = Array.isArray(dataToWrite) ? dataToWrite.length : 1;
647
+ currentFile.recordsCount = recordsCount;
648
+ const fileIndex = this.metadata.files.indexOf(currentFile);
649
+ if (fileIndex !== -1) {
650
+ this.calculateFileSynopsis(dataToWrite, fileIndex);
651
+ }
652
+ this.metadata.version = this.currentVersion;
653
+ this.metadata.modifiedAt = (/* @__PURE__ */ new Date()).toISOString();
654
+ this.metadata.dataType = detectDataType(dataToWrite);
655
+ this.metadata.totalRecords = this.metadata.files.reduce((sum, file) => sum + (file.recordsCount || 0), 0);
656
+ this.logger.debug?.(
657
+ `[FileDatabase] Updated metadata for file ${currentFile.fileName}: recordsCount=${recordsCount}, totalRecords=${this.metadata.totalRecords}`
658
+ );
659
+ }
660
+ /**
661
+ * Safe write with disk space check
662
+ */
663
+ async safeWrite(filePath, data) {
664
+ const serializedData = serializeData(data);
665
+ const dir = path3.dirname(filePath);
666
+ const requiredBytes = Buffer.byteLength(serializedData, "utf8");
667
+ const freeBytes = getFreeDiskSpace(dir);
668
+ if (freeBytes !== null) {
669
+ if (freeBytes < requiredBytes) {
670
+ throw new FileDatabaseError(
671
+ `Not enough disk space. Required: ${bytesToHumanReadable(requiredBytes)}, Free: ${bytesToHumanReadable(freeBytes)}`
672
+ );
673
+ }
674
+ if (freeBytes < this.freeSpaceThreshold) {
675
+ this.logger.warn?.(`Low disk space warning: only ${bytesToHumanReadable(freeBytes)} left`);
676
+ }
677
+ }
678
+ try {
679
+ await fs3.promises.writeFile(filePath, serializedData, "utf8");
680
+ this.logger.debug?.(`[FileDatabase] Wrote ${bytesToHumanReadable(requiredBytes)} to ${filePath}`);
681
+ } catch (error) {
682
+ throw new FileDatabaseError(`Failed to write file ${filePath}: ${error.message}`);
683
+ }
684
+ }
685
+ /**
686
+ * Prepare the instance for read or write operations
687
+ * This discovers state and sets up internal members based on mode and current data
688
+ */
689
+ async prepare({ write, read, version }) {
690
+ if (write) {
691
+ if (this.versioned) {
692
+ if (this.currentVersion === null) {
693
+ await this.makeNewVersion();
694
+ this.metadata = this.getDefaultMetadata();
695
+ this.metadata.version = this.currentVersion;
696
+ this.makeNewFile();
697
+ } else {
698
+ if (!this.metadata.files.length) {
699
+ this.metadata = await this.figureMetadata(this.currentVersion);
700
+ }
701
+ }
702
+ } else {
703
+ await ensurePath(this.getDestinationPath());
704
+ if (this.useMetadata === true) {
705
+ const metadataPath = path3.join(this.getDestinationPath(), "metadata.json");
706
+ if (fs3.existsSync(metadataPath)) {
707
+ try {
708
+ const rawData = await fs3.promises.readFile(metadataPath, "utf8");
709
+ this.metadata = JSON.parse(rawData);
710
+ } catch (e) {
711
+ this.metadata = this.getDefaultMetadata();
712
+ }
713
+ } else {
714
+ this.metadata = this.getDefaultMetadata();
715
+ this.makeNewFile();
716
+ }
717
+ } else {
718
+ this.metadata = this.getDefaultMetadata();
719
+ this.makeNewFile();
720
+ }
721
+ }
722
+ } else if (read) {
723
+ if (this.versioned) {
724
+ const versions = await this.getVersions();
725
+ if (versions.length === 0) {
726
+ throw new FileDatabaseError("[FileDatabase] No versions found, cannot read");
727
+ }
728
+ if (version) {
729
+ if (!versions.includes(version)) {
730
+ throw new FileDatabaseError(`[FileDatabase] Version "${version}" not found`);
731
+ }
732
+ await this.setCurrentVersion(version);
733
+ } else {
734
+ await this.setCurrentVersion(versions[versions.length - 1]);
735
+ }
736
+ if (!this.metadata.files.length) {
737
+ this.metadata = await this.figureMetadata(this.currentVersion);
738
+ }
739
+ } else {
740
+ this.currentVersion = null;
741
+ if (this.useMetadata === void 0) {
742
+ const format = await this.detectDataFormat();
743
+ this.useMetadata = format.hasMetadata;
744
+ }
745
+ if (this.useMetadata) {
746
+ const metadataPath = path3.join(this.getDestinationPath(), "metadata.json");
747
+ if (fs3.existsSync(metadataPath)) {
748
+ try {
749
+ const rawData = await fs3.promises.readFile(metadataPath, "utf8");
750
+ this.metadata = JSON.parse(rawData);
751
+ } catch (e) {
752
+ throw new FileDatabaseError(`Failed to read metadata: ${e.message}`);
753
+ }
754
+ } else {
755
+ throw new FileDatabaseError("[FileDatabase] No metadata found in non-versioned mode");
756
+ }
757
+ } else {
758
+ this.metadata = await this.figureMetadataFromVersionFiles("");
759
+ }
760
+ }
761
+ }
762
+ }
763
+ /**
764
+ * Write data to the file database
765
+ */
766
+ async write(data, options = {}) {
767
+ if (options.forceNewVersion && !this.versioned) {
768
+ throw new FileDatabaseError("Cannot use forceNewVersion in non-versioned mode");
769
+ }
770
+ await this.prepare({ write: true });
771
+ if (options.forceNewVersion) {
772
+ await this.makeNewVersion();
773
+ this.metadata = this.getDefaultMetadata();
774
+ this.metadata.version = this.currentVersion;
775
+ this.makeNewFile();
776
+ }
777
+ let { dataToWrite, dataLeftOver, fileName } = this.figureOutDataAndFileToWrite(data);
778
+ const destPath = this.getDestinationPath(this.currentVersion || void 0);
779
+ await this.safeWrite(path3.join(destPath, fileName), dataToWrite);
780
+ this.updateMetadata(dataToWrite, fileName);
781
+ while (dataLeftOver && dataLeftOver.length > 0) {
782
+ const writeContext = this.figureOutDataAndFileToWrite(dataLeftOver);
783
+ await this.safeWrite(path3.join(destPath, writeContext.fileName), writeContext.dataToWrite);
784
+ this.updateMetadata(writeContext.dataToWrite, writeContext.fileName);
785
+ dataLeftOver = writeContext.dataLeftOver;
786
+ }
787
+ this.calculateVersionSynopsis();
788
+ if (this.useMetadata) {
789
+ await this.saveVersionMetadata(this.metadata);
790
+ }
791
+ }
792
+ /**
793
+ * Read data from the file database
794
+ */
795
+ async read(options = {}) {
796
+ const { version, nextPage = false, pageSize } = options;
797
+ await this.prepare({ read: true, version });
798
+ const isNonPaginatedData = this.metadata.dataType === "text" || this.metadata.dataType === "xml" || this.metadata.dataType === "json-object";
799
+ if (isNonPaginatedData) {
800
+ const file = this.metadata.files[0];
801
+ const filePath = path3.join(this.getDestinationPath(this.currentVersion || void 0), file.fileName);
802
+ try {
803
+ const rawData = await fs3.promises.readFile(filePath, "utf8");
804
+ return deserializeData(rawData, this.metadata.dataType);
805
+ } catch (error) {
806
+ throw new FileDatabaseError(`Failed to read file ${file.fileName}: ${error.message}`);
807
+ }
808
+ }
809
+ let effectivePageSize;
810
+ if (nextPage && this.hasReadFirstPage) {
811
+ effectivePageSize = pageSize || this.pageSize;
812
+ this.currentRecord += effectivePageSize;
813
+ } else if (!nextPage) {
814
+ effectivePageSize = pageSize !== void 0 ? pageSize : this.metadata.totalRecords;
815
+ this.currentRecord = 0;
816
+ } else {
817
+ effectivePageSize = pageSize || this.pageSize;
818
+ }
819
+ if (this.currentRecord >= this.metadata.totalRecords) {
820
+ return [];
821
+ }
822
+ const result = [];
823
+ let recordsRead = 0;
824
+ let currentFileIndex = 0;
825
+ let currentFileOffset = 0;
826
+ let totalRecords = 0;
827
+ for (let i = 0; i < this.metadata.files.length; i++) {
828
+ const file = this.metadata.files[i];
829
+ if (this.currentRecord < totalRecords + file.recordsCount) {
830
+ currentFileIndex = i;
831
+ currentFileOffset = totalRecords;
832
+ break;
833
+ }
834
+ totalRecords += file.recordsCount;
835
+ }
836
+ let cumulativeRecords = currentFileOffset;
837
+ for (let i = currentFileIndex; i < this.metadata.files.length && recordsRead < effectivePageSize; i++) {
838
+ const file = this.metadata.files[i];
839
+ const filePath = path3.join(this.getDestinationPath(this.currentVersion || void 0), file.fileName);
840
+ try {
841
+ const rawData = await fs3.promises.readFile(filePath, "utf8");
842
+ const fileData = deserializeData(rawData, this.metadata.dataType);
843
+ let startIndex = 0;
844
+ if (i === currentFileIndex) {
845
+ startIndex = this.currentRecord - cumulativeRecords;
846
+ }
847
+ const endIndex = Math.min(startIndex + (effectivePageSize - recordsRead), fileData.length);
848
+ const recordsFromThisFile = fileData.slice(startIndex, endIndex);
849
+ result.push(...recordsFromThisFile);
850
+ recordsRead += recordsFromThisFile.length;
851
+ cumulativeRecords += file.recordsCount;
852
+ } catch (error) {
853
+ throw new FileDatabaseError(`Failed to read file ${file.fileName}: ${error.message}`);
854
+ }
855
+ }
856
+ if (result.length > 0) {
857
+ if (nextPage || pageSize !== void 0 && pageSize < this.metadata.totalRecords) {
858
+ this.hasReadFirstPage = true;
859
+ }
860
+ }
861
+ return result;
862
+ }
863
+ /**
864
+ * Set the starting record for pagination (1-based index)
865
+ */
866
+ setStartRecord(startRecord) {
867
+ this.currentRecord = startRecord - 1;
868
+ this.hasReadFirstPage = false;
869
+ }
870
+ /**
871
+ * Reset read pagination state
872
+ */
873
+ resetPagination() {
874
+ this.currentRecord = 0;
875
+ this.hasReadFirstPage = false;
876
+ }
877
+ /**
878
+ * Set file-level synopsis calculation function
879
+ */
880
+ setFileSynopsisFunction(fn) {
881
+ this.fileSynopsisFunction = fn;
882
+ }
883
+ /**
884
+ * Set version-level synopsis calculation function
885
+ */
886
+ setVersionSynopsisFunction(fn) {
887
+ this.versionSynopsisFunction = fn;
888
+ }
889
+ /**
890
+ * Get current version name
891
+ */
892
+ getCurrentVersion() {
893
+ return this.currentVersion;
894
+ }
895
+ /**
896
+ * Get current metadata
897
+ */
898
+ getMetadata() {
899
+ return { ...this.metadata };
900
+ }
901
+ };
902
+ export {
903
+ FileDatabase,
904
+ FileDatabaseError,
905
+ defaultFileSynopsisFunction,
906
+ defaultVersionSynopsisFunction
907
+ };
908
+ //# sourceMappingURL=filedatabase.js.map