@alwatr/nitrobase-engine 7.4.0 → 7.5.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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,12 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [7.5.0](https://github.com/Alwatr/nitrobase/compare/v7.4.1...v7.5.0) (2024-11-09)
7
+
8
+ ### Code Refactoring
9
+
10
+ * **engine:** make `config` as a public property ([6453540](https://github.com/Alwatr/nitrobase/commit/6453540aac42340cfe3b7ac9e4c26f904aaccdcc)) by @mohammadhonarvar
11
+
6
12
  ## [7.4.0](https://github.com/Alwatr/nitrobase/compare/v7.3.1...v7.4.0) (2024-11-08)
7
13
 
8
14
  ### Dependencies update
@@ -28,7 +28,7 @@ export interface AlwatrNitrobaseConfig {
28
28
  * It also provides methods to interact with `documents` and `collections` in the nitrobase.
29
29
  */
30
30
  export declare class AlwatrNitrobase {
31
- private readonly config__;
31
+ readonly config: AlwatrNitrobaseConfig;
32
32
  /**
33
33
  * The Alwatr Nitrobase version string.
34
34
  *
@@ -51,7 +51,7 @@ export declare class AlwatrNitrobase {
51
51
  /**
52
52
  * Constructs an AlwatrNitrobase instance with the provided configuration.
53
53
  *
54
- * @param config__ The configuration of the AlwatrNitrobase engine.
54
+ * @param config The configuration of the AlwatrNitrobase engine.
55
55
  * @example
56
56
  * ```typescript
57
57
  * const alwatrStore = new AlwatrNitrobase({
@@ -60,7 +60,7 @@ export declare class AlwatrNitrobase {
60
60
  * });
61
61
  * ```
62
62
  */
63
- constructor(config__: AlwatrNitrobaseConfig);
63
+ constructor(config: AlwatrNitrobaseConfig);
64
64
  /**
65
65
  * Checks if a nitrobase file with the given ID exists.
66
66
  *
@@ -1 +1 @@
1
- {"version":3,"file":"alwatr-nitrobase.d.ts","sourceRoot":"","sources":["../src/alwatr-nitrobase.ts"],"names":[],"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InE"}
package/dist/main.cjs CHANGED
@@ -1,4 +1,4 @@
1
- /* @alwatr/nitrobase-engine v7.4.0 */
1
+ /* @alwatr/nitrobase-engine v7.5.0 */
2
2
  "use strict";
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -35,7 +35,7 @@ var import_nitrobase_types = require("@alwatr/nitrobase-types");
35
35
 
36
36
  // src/logger.ts
37
37
  var import_nanolib = require("@alwatr/nanolib");
38
- __dev_mode__: import_nanolib.packageTracer.add("@alwatr/nitrobase-engine", "7.4.0");
38
+ __dev_mode__: import_nanolib.packageTracer.add("@alwatr/nitrobase-engine", "7.5.0");
39
39
  var logger = /* @__PURE__ */ (0, import_nanolib.createLogger)("@alwatr/nitrobase-engine");
40
40
 
41
41
  // src/alwatr-nitrobase.ts
@@ -44,7 +44,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
44
44
  /**
45
45
  * Constructs an AlwatrNitrobase instance with the provided configuration.
46
46
  *
47
- * @param config__ The configuration of the AlwatrNitrobase engine.
47
+ * @param config The configuration of the AlwatrNitrobase engine.
48
48
  * @example
49
49
  * ```typescript
50
50
  * const alwatrStore = new AlwatrNitrobase({
@@ -53,15 +53,15 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
53
53
  * });
54
54
  * ```
55
55
  */
56
- constructor(config__) {
57
- this.config__ = config__;
56
+ constructor(config) {
57
+ this.config = config;
58
58
  /**
59
59
  * Keep all loaded nitrobase file context loaded in memory.
60
60
  */
61
61
  this.cacheReferences__ = {};
62
62
  var _a;
63
- logger.logMethodArgs?.("new", config__);
64
- (_a = this.config__).defaultChangeDebounce ?? (_a.defaultChangeDebounce = 40);
63
+ logger.logMethodArgs?.("new", config);
64
+ (_a = this.config).defaultChangeDebounce ?? (_a.defaultChangeDebounce = 40);
65
65
  this.rootDb__ = this.loadRootDb__();
66
66
  (0, import_exit_hook.exitHook)(this.exitHook__.bind(this));
67
67
  }
@@ -152,7 +152,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
152
152
  */
153
153
  newStoreFile_(stat, initialData = null) {
154
154
  logger.logMethodArgs?.("newStoreFile_", stat);
155
- stat.changeDebounce ?? (stat.changeDebounce = this.config__.defaultChangeDebounce);
155
+ stat.changeDebounce ?? (stat.changeDebounce = this.config.defaultChangeDebounce);
156
156
  let fileStoreRef;
157
157
  if (stat.type === import_nitrobase_types.StoreFileType.Document) {
158
158
  fileStoreRef = import_nitrobase_reference.DocumentReference.newRefFromData(stat, initialData, this.storeChanged_.bind(this));
@@ -307,7 +307,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
307
307
  this.rootDb__.removeItem(id_);
308
308
  await import_nanolib2.delay.by(0);
309
309
  try {
310
- await (0, import_node_fs.unlink)((0, import_node_fs.resolve)(this.config__.rootPath, path));
310
+ await (0, import_node_fs.unlink)((0, import_node_fs.resolve)(this.config.rootPath, path));
311
311
  } catch (error) {
312
312
  logger.error("removeStore", "remove_file_failed", error, { id: storeId, path });
313
313
  }
@@ -340,7 +340,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
340
340
  if (typeof path !== "string") path = (0, import_nitrobase_helper.getStorePath)(path);
341
341
  logger.logMethodArgs?.("readContext__", path);
342
342
  logger.time?.(`readContext__time(${path})`);
343
- const context = await (0, import_node_fs.readJson)((0, import_node_fs.resolve)(this.config__.rootPath, path));
343
+ const context = await (0, import_node_fs.readJson)((0, import_node_fs.resolve)(this.config.rootPath, path));
344
344
  logger.timeEnd?.(`readContext__time(${path})`);
345
345
  return context;
346
346
  }
@@ -356,7 +356,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
356
356
  writeContext__(path, context) {
357
357
  if (typeof path !== "string") path = (0, import_nitrobase_helper.getStorePath)(path);
358
358
  logger.logMethodArgs?.("writeContext__", path);
359
- return (0, import_node_fs.writeJson)((0, import_node_fs.resolve)(this.config__.rootPath, path), context);
359
+ return (0, import_node_fs.writeJson)((0, import_node_fs.resolve)(this.config.rootPath, path), context);
360
360
  }
361
361
  /**
362
362
  * Write nitrobase file context.
@@ -381,9 +381,9 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
381
381
  */
382
382
  loadRootDb__() {
383
383
  logger.logMethod?.("loadRootDb__");
384
- const fullPath = (0, import_node_fs.resolve)(this.config__.rootPath, (0, import_nitrobase_helper.getStorePath)(_AlwatrNitrobase.rootDbStat__));
384
+ const fullPath = (0, import_node_fs.resolve)(this.config.rootPath, (0, import_nitrobase_helper.getStorePath)(_AlwatrNitrobase.rootDbStat__));
385
385
  if (!(0, import_node_fs.existsSync)(fullPath)) {
386
- if (this.config__.errorWhenNotInitialized === true) {
386
+ if (this.config.errorWhenNotInitialized === true) {
387
387
  throw new Error("store_not_found", { cause: "Nitrobase not initialized" });
388
388
  }
389
389
  logger.banner("Initialize new alwatr-nitrobase");
@@ -401,7 +401,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
401
401
  logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`, ref.hasUnprocessedChanges_);
402
402
  if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {
403
403
  logger.incident?.("exitHook__", "rescue_unsaved_context", { id: ref.id });
404
- (0, import_node_fs.writeJson)((0, import_node_fs.resolve)(this.config__.rootPath, ref.path), ref.getFullContext_(), true);
404
+ (0, import_node_fs.writeJson)((0, import_node_fs.resolve)(this.config.rootPath, ref.path), ref.getFullContext_(), true);
405
405
  ref.hasUnprocessedChanges_ = false;
406
406
  }
407
407
  }
@@ -427,7 +427,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
427
427
  *
428
428
  * Use for nitrobase file format version for check compatibility.
429
429
  */
430
- _AlwatrNitrobase.version = "7.4.0";
430
+ _AlwatrNitrobase.version = "7.5.0";
431
431
  /**
432
432
  * The root nitrobase file stat.
433
433
  */
package/dist/main.cjs.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/main.ts", "../src/alwatr-nitrobase.ts", "../src/logger.ts"],
4
- "sourcesContent": ["export * from './alwatr-nitrobase.js';\n", "import {delay} from '@alwatr/nanolib';\nimport {exitHook} from '@alwatr/nanolib/exit-hook';\nimport {existsSync, readJson, resolve, unlink, writeJson} from '@alwatr/nanolib/node-fs';\nimport {getStoreId, getStorePath} from '@alwatr/nitrobase-helper';\nimport {CollectionReference, DocumentReference} from '@alwatr/nitrobase-reference';\nimport {\n StoreFileType,\n StoreFileExtension,\n Region,\n type StoreFileStat,\n type StoreFileContext,\n type CollectionContext,\n type DocumentContext,\n type StoreFileId,\n type CollectionItem,\n} from '@alwatr/nitrobase-types';\n\nimport {logger} from './logger.js';\n\n__dev_mode__: logger.logFileModule?.('alwatr-nitrobase');\n\n/**\n * AlwatrNitrobase configuration.\n */\nexport interface AlwatrNitrobaseConfig {\n /**\n * The root path of the storage.\n * This is where the AlwatrNitrobase will nitrobase its data.\n */\n rootPath: string;\n\n /**\n * The save debounce timeout in milliseconds for minimal disk I/O usage.\n * This is used to limit the frequency of disk writes for performance reasons.\n * The recommended value is `40`.\n */\n defaultChangeDebounce?: number;\n\n /**\n * If true, an error will be thrown when trying to read or write to a nitrobase file that is not initialized (new storage).\n * The default value is `false` but highly recommended to set it to `true` in production to prevent data loss.\n */\n errorWhenNotInitialized?: boolean;\n}\n\n/**\n * AlwatrNitrobase engine.\n *\n * It provides methods to read, write, validate, and manage nitrobase files.\n * It also provides methods to interact with `documents` and `collections` in the nitrobase.\n */\nexport class AlwatrNitrobase {\n /**\n * The Alwatr Nitrobase version string.\n *\n * Use for nitrobase file format version for check compatibility.\n */\n static readonly version = __package_version__;\n\n /**\n * The root nitrobase file stat.\n */\n private static readonly rootDbStat__: StoreFileStat = {\n name: '.nitrobase',\n region: Region.Secret,\n type: StoreFileType.Collection,\n extension: StoreFileExtension.Json,\n changeDebounce: 40,\n };\n\n /**\n * `collectionReference` of all `storeFileStat`s.\n * This is the root nitrobase collection.\n */\n private rootDb__;\n\n /**\n * Keep all loaded nitrobase file context loaded in memory.\n */\n private cacheReferences__: DictionaryReq<DocumentReference | CollectionReference> = {};\n\n /**\n * Constructs an AlwatrNitrobase instance with the provided configuration.\n *\n * @param config__ The configuration of the AlwatrNitrobase engine.\n * @example\n * ```typescript\n * const alwatrStore = new AlwatrNitrobase({\n * rootPath: './db',\n * saveDebounce: 40,\n * });\n * ```\n */\n constructor(private readonly config__: AlwatrNitrobaseConfig) {\n logger.logMethodArgs?.('new', config__);\n this.config__.defaultChangeDebounce ??= 40;\n this.rootDb__ = this.loadRootDb__();\n exitHook(this.exitHook__.bind(this));\n }\n\n /**\n * Checks if a nitrobase file with the given ID exists.\n *\n * @param storeId - The ID of the nitrobase file to check.\n * @returns `true` if the nitrobase file exists, `false` otherwise.\n * @example\n * ```typescript\n * if (!alwatrStore.hasStore('user1/profile')) {\n * alwatrStore.defineDocument(...)\n * }\n * ```\n */\n hasStore(storeId: StoreFileId): boolean {\n const id_ = getStoreId(storeId);\n const exists = this.rootDb__.hasItem(id_);\n logger.logMethodFull?.('hasStore', id_, exists);\n return exists;\n }\n\n /**\n * Defines a new document with the given configuration and initial data.\n * If a document with the same ID already exists, an error is thrown.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the document\n * @template TDoc document data type\n * @example\n * ```typescript\n * await alwatrStore.newDocument<Order>(\n * {\n * name: 'profile',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * },\n * {\n * name: 'Ali',\n * email: 'ali@alwatr.io',\n * }\n * );\n * ```\n */\n newDocument<T extends JsonObject = JsonObject>(\n stat: Omit<StoreFileStat, 'type'>,\n initialData: DocumentContext<T>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newDocument', stat);\n return this.newStoreFile_(\n {\n ...stat,\n type: StoreFileType.Document,\n },\n initialData,\n );\n }\n\n /**\n * Defines a new collection with the given configuration and initial data.\n * If a collection with the same ID already exists, an error is thrown.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the collection\n * @template TItem collection item data type\n * @example\n * ```typescript\n * await alwatrStore.newCollection<Order>(\n * {\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * }\n * );\n * ```\n */\n newCollection<TItem extends JsonObject = JsonObject>(\n stat: Omit<StoreFileStat, 'type'>,\n initialData: CollectionContext<TItem>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newCollection', stat);\n return this.newStoreFile_(\n {\n ...stat,\n type: StoreFileType.Collection,\n },\n initialData,\n );\n }\n\n /**\n * Defines a AlwatrNitrobaseFile with the given configuration and initial data.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the document\n * @template TDoc document data type\n */\n newStoreFile_<T extends JsonObject = JsonObject>(\n stat: StoreFileStat,\n initialData: DocumentContext<T>['data'] | CollectionContext<T>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newStoreFile_', stat);\n\n (stat.changeDebounce as number | undefined) ??= this.config__.defaultChangeDebounce;\n\n let fileStoreRef: DocumentReference | CollectionReference;\n if (stat.type === StoreFileType.Document) {\n fileStoreRef = DocumentReference.newRefFromData(stat, initialData as DocumentContext['data'], this.storeChanged_.bind(this));\n }\n else if (stat.type === StoreFileType.Collection) {\n fileStoreRef = CollectionReference.newRefFromData(stat, initialData as CollectionContext['data'], this.storeChanged_.bind(this));\n }\n else {\n logger.accident('newStoreFile_', 'store_file_type_not_supported', stat);\n throw new Error('store_file_type_not_supported', {cause: stat});\n }\n\n if (this.rootDb__.hasItem(fileStoreRef.id)) {\n logger.accident('newStoreFile_', 'store_file_already_defined', stat);\n throw new Error('store_file_already_defined', {cause: stat});\n }\n\n this.rootDb__.addItem(fileStoreRef.id, stat);\n this.cacheReferences__[fileStoreRef.id] = fileStoreRef;\n\n // fileStoreRef.save();\n this.storeChanged_(fileStoreRef);\n }\n\n /**\n * Open a document with the given id and create and return a DocumentReference.\n * If the document not exists or its not a document, an error is thrown.\n *\n * @template TDoc document data type\n * @param documentId document id {@link StoreFileId}\n * @returns document reference {@link DocumentReference}\n * @example\n * ```typescript\n * const userProfile = await alwatrStore.openDocument<User>({\n * name: 'user1/profile',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * });\n * userProfile.update({name: 'ali'});\n * ```\n */\n async openDocument<TDoc extends JsonObject>(documentId: StoreFileId): Promise<DocumentReference<TDoc>> {\n const id = getStoreId(documentId);\n logger.logMethodArgs?.('openDocument', id);\n\n if (Object.hasOwn(this.cacheReferences__, id)) {\n const ref = this.cacheReferences__[id];\n if (!(ref instanceof DocumentReference)) {\n logger.accident('openDocument', 'document_wrong_type', id);\n throw new Error('document_wrong_type', {cause: id});\n }\n return this.cacheReferences__[id] as unknown as DocumentReference<TDoc>;\n }\n\n if (!this.rootDb__.hasItem(id)) {\n logger.accident('openDocument', 'document_not_found', id);\n throw new Error('document_not_found', {cause: id});\n }\n\n const storeStat = this.rootDb__.getItemData(id);\n\n if (storeStat.type != StoreFileType.Document) {\n logger.accident('openDocument', 'document_wrong_type', id);\n throw new Error('document_wrong_type', {cause: id});\n }\n\n const context = await this.readContext__<DocumentContext<TDoc>>(storeStat);\n const docRef = DocumentReference.newRefFromContext(context, this.storeChanged_.bind(this));\n this.cacheReferences__[id] = docRef as unknown as DocumentReference;\n return docRef;\n }\n\n /**\n * Open a collection with the given id and create and return a CollectionReference.\n * If the collection not exists or its not a collection, an error is thrown.\n *\n * @template TItem collection item data type\n * @param collectionId collection id {@link StoreFileId}\n * @returns collection reference {@link CollectionReference}\n * @example\n * ```typescript\n * const orders = await alwatrStore.openCollection<Order>({\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * });\n * orders.append({name: 'order 1'});\n * ```\n */\n async openCollection<TItem extends JsonObject>(collectionId: StoreFileId): Promise<CollectionReference<TItem>> {\n const id = getStoreId(collectionId);\n logger.logMethodArgs?.('openCollection', id);\n\n // try to get from cache\n if (Object.hasOwn(this.cacheReferences__, id)) {\n const ref = this.cacheReferences__[id];\n if (!(ref instanceof CollectionReference)) {\n logger.accident('openCollection', 'collection_wrong_type', id);\n throw new Error('collection_wrong_type', {cause: id});\n }\n return this.cacheReferences__[id] as unknown as CollectionReference<TItem>;\n }\n\n // load and create new collection reference\n if (!this.rootDb__.hasItem(id)) {\n logger.accident('openCollection', 'collection_not_found', id);\n throw new Error('collection_not_found', {cause: id});\n }\n\n const storeStat = this.rootDb__.getItemData(id);\n\n if (storeStat.type != StoreFileType.Collection) {\n logger.accident('openCollection', 'collection_wrong_type', id);\n throw new Error('collection_not_found', {cause: id});\n }\n\n const context = await this.readContext__<CollectionContext<TItem>>(storeStat);\n const colRef = CollectionReference.newRefFromContext(context, this.storeChanged_.bind(this));\n this.cacheReferences__[id] = colRef as unknown as CollectionReference;\n return colRef;\n }\n\n /**\n * Unloads the nitrobase file with the given id from memory.\n *\n * @param storeId The unique identifier of the nitrobase file. {@link StoreFileId}\n * @example\n * ```typescript\n * alwatrStore.unloadStore({name: 'user-list', region: Region.Secret});\n * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // true\n * ```\n */\n unloadStore(storeId: StoreFileId): void {\n const id_ = getStoreId(storeId);\n logger.logMethodArgs?.('unloadStore', id_);\n const ref = this.cacheReferences__[id_];\n if (ref === undefined) return;\n if (ref.hasUnprocessedChanges_ === true) {\n ref.updateDelayed_ = false;\n this.storeChanged_(ref);\n }\n delete this.cacheReferences__[id_];\n }\n\n /**\n * Remove document or collection from nitrobase and delete the file from disk.\n * If the file is not found, an error is thrown.\n * If the file is not unloaded, it will be unloaded first.\n * You don't need to await this method to complete unless you want to make sure the file is deleted on disk.\n *\n * @param storeId The ID of the file to delete. {@link StoreFileId}\n * @returns A Promise that resolves when the file is deleted.\n * @example\n * ```typescript\n * alwatrStore.removeStore({name: 'user-list', region: Region.Secret});\n * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // false\n * ```\n */\n async removeStore(storeId: StoreFileId): Promise<void> {\n const id_ = getStoreId(storeId);\n logger.logMethodArgs?.('removeStore', id_);\n if (!this.rootDb__.hasItem(id_)) {\n logger.accident('removeStore', 'document_not_found', id_);\n throw new Error('document_not_found', {cause: id_});\n }\n const ref = this.cacheReferences__[id_];\n if (ref !== undefined) {\n // direct unload to prevent save\n ref.freeze = true;\n ref.updateDelayed_ = false;\n ref.hasUnprocessedChanges_ = false;\n delete this.cacheReferences__[id_]; // unload\n }\n const path = getStorePath(this.rootDb__.getItemData(id_));\n this.rootDb__.removeItem(id_);\n await delay.by(0);\n try {\n await unlink(resolve(this.config__.rootPath, path));\n }\n catch (error) {\n logger.error('removeStore', 'remove_file_failed', error, {id: storeId, path});\n }\n }\n\n /**\n * Saves all changes in the nitrobase.\n *\n * @returns A Promise that resolves when all changes are saved.\n * @example\n * ```typescript\n * await alwatrStore.saveAll();\n * ```\n */\n async saveAll(): Promise<void> {\n logger.logMethod?.('saveAll');\n for (const ref of Object.values(this.cacheReferences__)) {\n if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {\n ref.updateDelayed_ = false;\n await this.storeChanged_(ref);\n }\n }\n }\n\n /**\n * Reads the context from a given path or StoreFileStat object.\n *\n * @param path The path or StoreFileStat object from which to read the context.\n * @returns A promise that resolves to the context object.\n */\n private async readContext__<T extends StoreFileContext>(path: string | StoreFileStat): Promise<T> {\n if (typeof path !== 'string') path = getStorePath(path);\n logger.logMethodArgs?.('readContext__', path);\n logger.time?.(`readContext__time(${path})`);\n const context = (await readJson(resolve(this.config__.rootPath, path))) as T;\n logger.timeEnd?.(`readContext__time(${path})`);\n return context;\n }\n\n /**\n * Writes the context to the specified path.\n *\n * @template T The type of the context.\n * @param path The path where the context will be written.\n * @param context The context to be written.\n * @param sync Indicates whether the write operation should be synchronous.\n * @returns A promise that resolves when the write operation is complete.\n */\n private writeContext__<T extends StoreFileContext>(path: string | StoreFileStat, context: T): Promise<void> {\n if (typeof path !== 'string') path = getStorePath(path);\n logger.logMethodArgs?.('writeContext__', path);\n return writeJson(resolve(this.config__.rootPath, path), context);\n }\n\n /**\n * Write nitrobase file context.\n *\n * @param from nitrobase file reference\n * @returns A promise that resolves when the write operation is complete.\n */\n protected async storeChanged_<T extends JsonObject>(from: DocumentReference<T> | CollectionReference<T>): Promise<void> {\n logger.logMethodArgs?.('storeChanged__', from.id);\n const rev = from.getStoreMeta().rev;\n try {\n await this.writeContext__(from.path, from.getFullContext_());\n if (rev === from.getStoreMeta().rev) {\n // Context not changed during saving\n from.hasUnprocessedChanges_ = false;\n }\n }\n catch (error) {\n logger.error('storeChanged__', 'write_context_failed', {id: from.id, error});\n }\n }\n\n /**\n * Load storeFilesCollection or create new one.\n */\n private loadRootDb__(): CollectionReference<StoreFileStat> {\n logger.logMethod?.('loadRootDb__');\n const fullPath = resolve(this.config__.rootPath, getStorePath(AlwatrNitrobase.rootDbStat__));\n if (!existsSync(fullPath)) {\n if (this.config__.errorWhenNotInitialized === true) {\n throw new Error('store_not_found', {cause: 'Nitrobase not initialized'});\n }\n\n logger.banner('Initialize new alwatr-nitrobase');\n return CollectionReference.newRefFromData(AlwatrNitrobase.rootDbStat__, null, this.storeChanged_.bind(this));\n }\n // else\n const context = readJson<CollectionContext<StoreFileStat>>(fullPath, true);\n return CollectionReference.newRefFromContext(context, this.storeChanged_.bind(this), 'root-db');\n }\n\n /**\n * Save all nitrobase files.\n */\n private exitHook__(): void {\n logger.logMethod?.('exitHook__');\n for (const ref of Object.values(this.cacheReferences__)) {\n logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`, ref.hasUnprocessedChanges_);\n if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {\n logger.incident?.('exitHook__', 'rescue_unsaved_context', {id: ref.id});\n writeJson(resolve(this.config__.rootPath, ref.path), ref.getFullContext_(), true);\n ref.hasUnprocessedChanges_ = false;\n }\n }\n }\n\n /**\n * Get all nitrobase files.\n *\n * @returns all nitrobase files.\n * @example\n * ```typescript\n * const storeList = alwatrStore.getStoreList();\n * for (const nitrobase of storeList) {\n * console.log(nitrobase.meta.id, nitrobase.data);\n * }\n */\n getStoreList(): CollectionItem<Omit<StoreFileStat, 'schemaVer'>>[] {\n logger.logMethod?.('getStoreList');\n return this.rootDb__.values();\n }\n}\n", "import {createLogger, packageTracer} from '@alwatr/nanolib';\n\n__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\nexport const logger = /* #__PURE__ */ createLogger(__package_name__);\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,kBAAoB;AACpB,uBAAuB;AACvB,qBAA+D;AAC/D,8BAAuC;AACvC,iCAAqD;AACrD,6BAUO;;;ACfP,qBAA0C;AAE1C,aAAc,8BAAc,IAAI,4BAAkB,OAAmB;AAE9D,IAAM,SAAyB,iDAAa,0BAAgB;;;ADenE,aAAc,QAAO,gBAAgB,kBAAkB;AAgChD,IAAM,mBAAN,MAAM,iBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA0C3B,YAA6B,UAAiC;AAAjC;AAd7B;AAAA;AAAA;AAAA,SAAQ,oBAA4E,CAAC;AA/EvF;AA8FI,WAAO,gBAAgB,OAAO,QAAQ;AACtC,eAAK,UAAS,0BAAd,GAAc,wBAA0B;AACxC,SAAK,WAAW,KAAK,aAAa;AAClC,mCAAS,KAAK,WAAW,KAAK,IAAI,CAAC;AAAA,EACrC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,SAAS,SAA+B;AACtC,UAAM,UAAM,oCAAW,OAAO;AAC9B,UAAM,SAAS,KAAK,SAAS,QAAQ,GAAG;AACxC,WAAO,gBAAgB,YAAY,KAAK,MAAM;AAC9C,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAwBA,YACE,MACA,cAAiD,MA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kBAAkB,SAAS,KAAK,cAAc,KAAK,IAAI,GAAG,SAAS;AAAA,EAChG;AAAA;AAAA;AAAA;AAAA,EAKQ,aAAmB;AACzB,WAAO,YAAY,YAAY;AAC/B,eAAW,OAAO,OAAO,OAAO,KAAK,iBAAiB,GAAG;AACvD,aAAO,cAAc,aAAa,IAAI,EAAE,0BAA0B,IAAI,sBAAsB;AAC5F,UAAI,IAAI,2BAA2B,QAAQ,IAAI,WAAW,MAAM;AAC9D,eAAO,WAAW,cAAc,0BAA0B,EAAC,IAAI,IAAI,GAAE,CAAC;AACtE,0CAAU,wBAAQ,KAAK,SAAS,UAAU,IAAI,IAAI,GAAG,IAAI,gBAAgB,GAAG,IAAI;AAChF,YAAI,yBAAyB;AAAA,MAC/B;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,eAAmE;AACjE,WAAO,YAAY,cAAc;AACjC,WAAO,KAAK,SAAS,OAAO;AAAA,EAC9B;AACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAtca,iBAMK,UAAU;AAAA;AAAA;AAAA;AANf,iBAWa,eAA8B;AAAA,EACpD,MAAM;AAAA,EACN,QAAQ,8BAAO;AAAA,EACf,MAAM,qCAAc;AAAA,EACpB,WAAW,0CAAmB;AAAA,EAC9B,gBAAgB;AAClB;AAjBK,IAAM,kBAAN;",
4
+ "sourcesContent": ["export * from './alwatr-nitrobase.js';\n", "import {delay} from '@alwatr/nanolib';\nimport {exitHook} from '@alwatr/nanolib/exit-hook';\nimport {existsSync, readJson, resolve, unlink, writeJson} from '@alwatr/nanolib/node-fs';\nimport {getStoreId, getStorePath} from '@alwatr/nitrobase-helper';\nimport {CollectionReference, DocumentReference} from '@alwatr/nitrobase-reference';\nimport {\n StoreFileType,\n StoreFileExtension,\n Region,\n type StoreFileStat,\n type StoreFileContext,\n type CollectionContext,\n type DocumentContext,\n type StoreFileId,\n type CollectionItem,\n} from '@alwatr/nitrobase-types';\n\nimport {logger} from './logger.js';\n\n__dev_mode__: logger.logFileModule?.('alwatr-nitrobase');\n\n/**\n * AlwatrNitrobase configuration.\n */\nexport interface AlwatrNitrobaseConfig {\n /**\n * The root path of the storage.\n * This is where the AlwatrNitrobase will nitrobase its data.\n */\n rootPath: string;\n\n /**\n * The save debounce timeout in milliseconds for minimal disk I/O usage.\n * This is used to limit the frequency of disk writes for performance reasons.\n * The recommended value is `40`.\n */\n defaultChangeDebounce?: number;\n\n /**\n * If true, an error will be thrown when trying to read or write to a nitrobase file that is not initialized (new storage).\n * The default value is `false` but highly recommended to set it to `true` in production to prevent data loss.\n */\n errorWhenNotInitialized?: boolean;\n}\n\n/**\n * AlwatrNitrobase engine.\n *\n * It provides methods to read, write, validate, and manage nitrobase files.\n * It also provides methods to interact with `documents` and `collections` in the nitrobase.\n */\nexport class AlwatrNitrobase {\n /**\n * The Alwatr Nitrobase version string.\n *\n * Use for nitrobase file format version for check compatibility.\n */\n static readonly version = __package_version__;\n\n /**\n * The root nitrobase file stat.\n */\n private static readonly rootDbStat__: StoreFileStat = {\n name: '.nitrobase',\n region: Region.Secret,\n type: StoreFileType.Collection,\n extension: StoreFileExtension.Json,\n changeDebounce: 40,\n };\n\n /**\n * `collectionReference` of all `storeFileStat`s.\n * This is the root nitrobase collection.\n */\n private rootDb__;\n\n /**\n * Keep all loaded nitrobase file context loaded in memory.\n */\n private cacheReferences__: DictionaryReq<DocumentReference | CollectionReference> = {};\n\n /**\n * Constructs an AlwatrNitrobase instance with the provided configuration.\n *\n * @param config The configuration of the AlwatrNitrobase engine.\n * @example\n * ```typescript\n * const alwatrStore = new AlwatrNitrobase({\n * rootPath: './db',\n * saveDebounce: 40,\n * });\n * ```\n */\n constructor(readonly config: AlwatrNitrobaseConfig) {\n logger.logMethodArgs?.('new', config);\n this.config.defaultChangeDebounce ??= 40;\n this.rootDb__ = this.loadRootDb__();\n exitHook(this.exitHook__.bind(this));\n }\n\n /**\n * Checks if a nitrobase file with the given ID exists.\n *\n * @param storeId - The ID of the nitrobase file to check.\n * @returns `true` if the nitrobase file exists, `false` otherwise.\n * @example\n * ```typescript\n * if (!alwatrStore.hasStore('user1/profile')) {\n * alwatrStore.defineDocument(...)\n * }\n * ```\n */\n hasStore(storeId: StoreFileId): boolean {\n const id_ = getStoreId(storeId);\n const exists = this.rootDb__.hasItem(id_);\n logger.logMethodFull?.('hasStore', id_, exists);\n return exists;\n }\n\n /**\n * Defines a new document with the given configuration and initial data.\n * If a document with the same ID already exists, an error is thrown.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the document\n * @template TDoc document data type\n * @example\n * ```typescript\n * await alwatrStore.newDocument<Order>(\n * {\n * name: 'profile',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * },\n * {\n * name: 'Ali',\n * email: 'ali@alwatr.io',\n * }\n * );\n * ```\n */\n newDocument<T extends JsonObject = JsonObject>(\n stat: Omit<StoreFileStat, 'type'>,\n initialData: DocumentContext<T>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newDocument', stat);\n return this.newStoreFile_(\n {\n ...stat,\n type: StoreFileType.Document,\n },\n initialData,\n );\n }\n\n /**\n * Defines a new collection with the given configuration and initial data.\n * If a collection with the same ID already exists, an error is thrown.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the collection\n * @template TItem collection item data type\n * @example\n * ```typescript\n * await alwatrStore.newCollection<Order>(\n * {\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * }\n * );\n * ```\n */\n newCollection<TItem extends JsonObject = JsonObject>(\n stat: Omit<StoreFileStat, 'type'>,\n initialData: CollectionContext<TItem>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newCollection', stat);\n return this.newStoreFile_(\n {\n ...stat,\n type: StoreFileType.Collection,\n },\n initialData,\n );\n }\n\n /**\n * Defines a AlwatrNitrobaseFile with the given configuration and initial data.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the document\n * @template TDoc document data type\n */\n newStoreFile_<T extends JsonObject = JsonObject>(\n stat: StoreFileStat,\n initialData: DocumentContext<T>['data'] | CollectionContext<T>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newStoreFile_', stat);\n\n (stat.changeDebounce as number | undefined) ??= this.config.defaultChangeDebounce;\n\n let fileStoreRef: DocumentReference | CollectionReference;\n if (stat.type === StoreFileType.Document) {\n fileStoreRef = DocumentReference.newRefFromData(stat, initialData as DocumentContext['data'], this.storeChanged_.bind(this));\n }\n else if (stat.type === StoreFileType.Collection) {\n fileStoreRef = CollectionReference.newRefFromData(stat, initialData as CollectionContext['data'], this.storeChanged_.bind(this));\n }\n else {\n logger.accident('newStoreFile_', 'store_file_type_not_supported', stat);\n throw new Error('store_file_type_not_supported', {cause: stat});\n }\n\n if (this.rootDb__.hasItem(fileStoreRef.id)) {\n logger.accident('newStoreFile_', 'store_file_already_defined', stat);\n throw new Error('store_file_already_defined', {cause: stat});\n }\n\n this.rootDb__.addItem(fileStoreRef.id, stat);\n this.cacheReferences__[fileStoreRef.id] = fileStoreRef;\n\n // fileStoreRef.save();\n this.storeChanged_(fileStoreRef);\n }\n\n /**\n * Open a document with the given id and create and return a DocumentReference.\n * If the document not exists or its not a document, an error is thrown.\n *\n * @template TDoc document data type\n * @param documentId document id {@link StoreFileId}\n * @returns document reference {@link DocumentReference}\n * @example\n * ```typescript\n * const userProfile = await alwatrStore.openDocument<User>({\n * name: 'user1/profile',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * });\n * userProfile.update({name: 'ali'});\n * ```\n */\n async openDocument<TDoc extends JsonObject>(documentId: StoreFileId): Promise<DocumentReference<TDoc>> {\n const id = getStoreId(documentId);\n logger.logMethodArgs?.('openDocument', id);\n\n if (Object.hasOwn(this.cacheReferences__, id)) {\n const ref = this.cacheReferences__[id];\n if (!(ref instanceof DocumentReference)) {\n logger.accident('openDocument', 'document_wrong_type', id);\n throw new Error('document_wrong_type', {cause: id});\n }\n return this.cacheReferences__[id] as unknown as DocumentReference<TDoc>;\n }\n\n if (!this.rootDb__.hasItem(id)) {\n logger.accident('openDocument', 'document_not_found', id);\n throw new Error('document_not_found', {cause: id});\n }\n\n const storeStat = this.rootDb__.getItemData(id);\n\n if (storeStat.type != StoreFileType.Document) {\n logger.accident('openDocument', 'document_wrong_type', id);\n throw new Error('document_wrong_type', {cause: id});\n }\n\n const context = await this.readContext__<DocumentContext<TDoc>>(storeStat);\n const docRef = DocumentReference.newRefFromContext(context, this.storeChanged_.bind(this));\n this.cacheReferences__[id] = docRef as unknown as DocumentReference;\n return docRef;\n }\n\n /**\n * Open a collection with the given id and create and return a CollectionReference.\n * If the collection not exists or its not a collection, an error is thrown.\n *\n * @template TItem collection item data type\n * @param collectionId collection id {@link StoreFileId}\n * @returns collection reference {@link CollectionReference}\n * @example\n * ```typescript\n * const orders = await alwatrStore.openCollection<Order>({\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * });\n * orders.append({name: 'order 1'});\n * ```\n */\n async openCollection<TItem extends JsonObject>(collectionId: StoreFileId): Promise<CollectionReference<TItem>> {\n const id = getStoreId(collectionId);\n logger.logMethodArgs?.('openCollection', id);\n\n // try to get from cache\n if (Object.hasOwn(this.cacheReferences__, id)) {\n const ref = this.cacheReferences__[id];\n if (!(ref instanceof CollectionReference)) {\n logger.accident('openCollection', 'collection_wrong_type', id);\n throw new Error('collection_wrong_type', {cause: id});\n }\n return this.cacheReferences__[id] as unknown as CollectionReference<TItem>;\n }\n\n // load and create new collection reference\n if (!this.rootDb__.hasItem(id)) {\n logger.accident('openCollection', 'collection_not_found', id);\n throw new Error('collection_not_found', {cause: id});\n }\n\n const storeStat = this.rootDb__.getItemData(id);\n\n if (storeStat.type != StoreFileType.Collection) {\n logger.accident('openCollection', 'collection_wrong_type', id);\n throw new Error('collection_not_found', {cause: id});\n }\n\n const context = await this.readContext__<CollectionContext<TItem>>(storeStat);\n const colRef = CollectionReference.newRefFromContext(context, this.storeChanged_.bind(this));\n this.cacheReferences__[id] = colRef as unknown as CollectionReference;\n return colRef;\n }\n\n /**\n * Unloads the nitrobase file with the given id from memory.\n *\n * @param storeId The unique identifier of the nitrobase file. {@link StoreFileId}\n * @example\n * ```typescript\n * alwatrStore.unloadStore({name: 'user-list', region: Region.Secret});\n * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // true\n * ```\n */\n unloadStore(storeId: StoreFileId): void {\n const id_ = getStoreId(storeId);\n logger.logMethodArgs?.('unloadStore', id_);\n const ref = this.cacheReferences__[id_];\n if (ref === undefined) return;\n if (ref.hasUnprocessedChanges_ === true) {\n ref.updateDelayed_ = false;\n this.storeChanged_(ref);\n }\n delete this.cacheReferences__[id_];\n }\n\n /**\n * Remove document or collection from nitrobase and delete the file from disk.\n * If the file is not found, an error is thrown.\n * If the file is not unloaded, it will be unloaded first.\n * You don't need to await this method to complete unless you want to make sure the file is deleted on disk.\n *\n * @param storeId The ID of the file to delete. {@link StoreFileId}\n * @returns A Promise that resolves when the file is deleted.\n * @example\n * ```typescript\n * alwatrStore.removeStore({name: 'user-list', region: Region.Secret});\n * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // false\n * ```\n */\n async removeStore(storeId: StoreFileId): Promise<void> {\n const id_ = getStoreId(storeId);\n logger.logMethodArgs?.('removeStore', id_);\n if (!this.rootDb__.hasItem(id_)) {\n logger.accident('removeStore', 'document_not_found', id_);\n throw new Error('document_not_found', {cause: id_});\n }\n const ref = this.cacheReferences__[id_];\n if (ref !== undefined) {\n // direct unload to prevent save\n ref.freeze = true;\n ref.updateDelayed_ = false;\n ref.hasUnprocessedChanges_ = false;\n delete this.cacheReferences__[id_]; // unload\n }\n const path = getStorePath(this.rootDb__.getItemData(id_));\n this.rootDb__.removeItem(id_);\n await delay.by(0);\n try {\n await unlink(resolve(this.config.rootPath, path));\n }\n catch (error) {\n logger.error('removeStore', 'remove_file_failed', error, {id: storeId, path});\n }\n }\n\n /**\n * Saves all changes in the nitrobase.\n *\n * @returns A Promise that resolves when all changes are saved.\n * @example\n * ```typescript\n * await alwatrStore.saveAll();\n * ```\n */\n async saveAll(): Promise<void> {\n logger.logMethod?.('saveAll');\n for (const ref of Object.values(this.cacheReferences__)) {\n if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {\n ref.updateDelayed_ = false;\n await this.storeChanged_(ref);\n }\n }\n }\n\n /**\n * Reads the context from a given path or StoreFileStat object.\n *\n * @param path The path or StoreFileStat object from which to read the context.\n * @returns A promise that resolves to the context object.\n */\n private async readContext__<T extends StoreFileContext>(path: string | StoreFileStat): Promise<T> {\n if (typeof path !== 'string') path = getStorePath(path);\n logger.logMethodArgs?.('readContext__', path);\n logger.time?.(`readContext__time(${path})`);\n const context = (await readJson(resolve(this.config.rootPath, path))) as T;\n logger.timeEnd?.(`readContext__time(${path})`);\n return context;\n }\n\n /**\n * Writes the context to the specified path.\n *\n * @template T The type of the context.\n * @param path The path where the context will be written.\n * @param context The context to be written.\n * @param sync Indicates whether the write operation should be synchronous.\n * @returns A promise that resolves when the write operation is complete.\n */\n private writeContext__<T extends StoreFileContext>(path: string | StoreFileStat, context: T): Promise<void> {\n if (typeof path !== 'string') path = getStorePath(path);\n logger.logMethodArgs?.('writeContext__', path);\n return writeJson(resolve(this.config.rootPath, path), context);\n }\n\n /**\n * Write nitrobase file context.\n *\n * @param from nitrobase file reference\n * @returns A promise that resolves when the write operation is complete.\n */\n protected async storeChanged_<T extends JsonObject>(from: DocumentReference<T> | CollectionReference<T>): Promise<void> {\n logger.logMethodArgs?.('storeChanged__', from.id);\n const rev = from.getStoreMeta().rev;\n try {\n await this.writeContext__(from.path, from.getFullContext_());\n if (rev === from.getStoreMeta().rev) {\n // Context not changed during saving\n from.hasUnprocessedChanges_ = false;\n }\n }\n catch (error) {\n logger.error('storeChanged__', 'write_context_failed', {id: from.id, error});\n }\n }\n\n /**\n * Load storeFilesCollection or create new one.\n */\n private loadRootDb__(): CollectionReference<StoreFileStat> {\n logger.logMethod?.('loadRootDb__');\n const fullPath = resolve(this.config.rootPath, getStorePath(AlwatrNitrobase.rootDbStat__));\n if (!existsSync(fullPath)) {\n if (this.config.errorWhenNotInitialized === true) {\n throw new Error('store_not_found', {cause: 'Nitrobase not initialized'});\n }\n\n logger.banner('Initialize new alwatr-nitrobase');\n return CollectionReference.newRefFromData(AlwatrNitrobase.rootDbStat__, null, this.storeChanged_.bind(this));\n }\n // else\n const context = readJson<CollectionContext<StoreFileStat>>(fullPath, true);\n return CollectionReference.newRefFromContext(context, this.storeChanged_.bind(this), 'root-db');\n }\n\n /**\n * Save all nitrobase files.\n */\n private exitHook__(): void {\n logger.logMethod?.('exitHook__');\n for (const ref of Object.values(this.cacheReferences__)) {\n logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`, ref.hasUnprocessedChanges_);\n if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {\n logger.incident?.('exitHook__', 'rescue_unsaved_context', {id: ref.id});\n writeJson(resolve(this.config.rootPath, ref.path), ref.getFullContext_(), true);\n ref.hasUnprocessedChanges_ = false;\n }\n }\n }\n\n /**\n * Get all nitrobase files.\n *\n * @returns all nitrobase files.\n * @example\n * ```typescript\n * const storeList = alwatrStore.getStoreList();\n * for (const nitrobase of storeList) {\n * console.log(nitrobase.meta.id, nitrobase.data);\n * }\n */\n getStoreList(): CollectionItem<Omit<StoreFileStat, 'schemaVer'>>[] {\n logger.logMethod?.('getStoreList');\n return this.rootDb__.values();\n }\n}\n", "import {createLogger, packageTracer} from '@alwatr/nanolib';\n\n__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\nexport const logger = /* #__PURE__ */ createLogger(__package_name__);\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,kBAAoB;AACpB,uBAAuB;AACvB,qBAA+D;AAC/D,8BAAuC;AACvC,iCAAqD;AACrD,6BAUO;;;ACfP,qBAA0C;AAE1C,aAAc,8BAAc,IAAI,4BAAkB,OAAm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,IAAI,GAAG,IAAI,gBAAgB,GAAG,IAAI;AAC9E,YAAI,yBAAyB;AAAA,MAC/B;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,eAAmE;AACjE,WAAO,YAAY,cAAc;AACjC,WAAO,KAAK,SAAS,OAAO;AAAA,EAC9B;AACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAtca,iBAMK,UAAU;AAAA;AAAA;AAAA;AANf,iBAWa,eAA8B;AAAA,EACpD,MAAM;AAAA,EACN,QAAQ,8BAAO;AAAA,EACf,MAAM,qCAAc;AAAA,EACpB,WAAW,0CAAmB;AAAA,EAC9B,gBAAgB;AAClB;AAjBK,IAAM,kBAAN;",
6
6
  "names": ["import_nanolib"]
7
7
  }
package/dist/main.mjs CHANGED
@@ -1,4 +1,4 @@
1
- /* @alwatr/nitrobase-engine v7.4.0 */
1
+ /* @alwatr/nitrobase-engine v7.5.0 */
2
2
 
3
3
  // src/alwatr-nitrobase.ts
4
4
  import { delay } from "@alwatr/nanolib";
@@ -14,7 +14,7 @@ import {
14
14
 
15
15
  // src/logger.ts
16
16
  import { createLogger, packageTracer } from "@alwatr/nanolib";
17
- __dev_mode__: packageTracer.add("@alwatr/nitrobase-engine", "7.4.0");
17
+ __dev_mode__: packageTracer.add("@alwatr/nitrobase-engine", "7.5.0");
18
18
  var logger = /* @__PURE__ */ createLogger("@alwatr/nitrobase-engine");
19
19
 
20
20
  // src/alwatr-nitrobase.ts
@@ -23,7 +23,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
23
23
  /**
24
24
  * Constructs an AlwatrNitrobase instance with the provided configuration.
25
25
  *
26
- * @param config__ The configuration of the AlwatrNitrobase engine.
26
+ * @param config The configuration of the AlwatrNitrobase engine.
27
27
  * @example
28
28
  * ```typescript
29
29
  * const alwatrStore = new AlwatrNitrobase({
@@ -32,15 +32,15 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
32
32
  * });
33
33
  * ```
34
34
  */
35
- constructor(config__) {
36
- this.config__ = config__;
35
+ constructor(config) {
36
+ this.config = config;
37
37
  /**
38
38
  * Keep all loaded nitrobase file context loaded in memory.
39
39
  */
40
40
  this.cacheReferences__ = {};
41
41
  var _a;
42
- logger.logMethodArgs?.("new", config__);
43
- (_a = this.config__).defaultChangeDebounce ?? (_a.defaultChangeDebounce = 40);
42
+ logger.logMethodArgs?.("new", config);
43
+ (_a = this.config).defaultChangeDebounce ?? (_a.defaultChangeDebounce = 40);
44
44
  this.rootDb__ = this.loadRootDb__();
45
45
  exitHook(this.exitHook__.bind(this));
46
46
  }
@@ -131,7 +131,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
131
131
  */
132
132
  newStoreFile_(stat, initialData = null) {
133
133
  logger.logMethodArgs?.("newStoreFile_", stat);
134
- stat.changeDebounce ?? (stat.changeDebounce = this.config__.defaultChangeDebounce);
134
+ stat.changeDebounce ?? (stat.changeDebounce = this.config.defaultChangeDebounce);
135
135
  let fileStoreRef;
136
136
  if (stat.type === StoreFileType.Document) {
137
137
  fileStoreRef = DocumentReference.newRefFromData(stat, initialData, this.storeChanged_.bind(this));
@@ -286,7 +286,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
286
286
  this.rootDb__.removeItem(id_);
287
287
  await delay.by(0);
288
288
  try {
289
- await unlink(resolve(this.config__.rootPath, path));
289
+ await unlink(resolve(this.config.rootPath, path));
290
290
  } catch (error) {
291
291
  logger.error("removeStore", "remove_file_failed", error, { id: storeId, path });
292
292
  }
@@ -319,7 +319,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
319
319
  if (typeof path !== "string") path = getStorePath(path);
320
320
  logger.logMethodArgs?.("readContext__", path);
321
321
  logger.time?.(`readContext__time(${path})`);
322
- const context = await readJson(resolve(this.config__.rootPath, path));
322
+ const context = await readJson(resolve(this.config.rootPath, path));
323
323
  logger.timeEnd?.(`readContext__time(${path})`);
324
324
  return context;
325
325
  }
@@ -335,7 +335,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
335
335
  writeContext__(path, context) {
336
336
  if (typeof path !== "string") path = getStorePath(path);
337
337
  logger.logMethodArgs?.("writeContext__", path);
338
- return writeJson(resolve(this.config__.rootPath, path), context);
338
+ return writeJson(resolve(this.config.rootPath, path), context);
339
339
  }
340
340
  /**
341
341
  * Write nitrobase file context.
@@ -360,9 +360,9 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
360
360
  */
361
361
  loadRootDb__() {
362
362
  logger.logMethod?.("loadRootDb__");
363
- const fullPath = resolve(this.config__.rootPath, getStorePath(_AlwatrNitrobase.rootDbStat__));
363
+ const fullPath = resolve(this.config.rootPath, getStorePath(_AlwatrNitrobase.rootDbStat__));
364
364
  if (!existsSync(fullPath)) {
365
- if (this.config__.errorWhenNotInitialized === true) {
365
+ if (this.config.errorWhenNotInitialized === true) {
366
366
  throw new Error("store_not_found", { cause: "Nitrobase not initialized" });
367
367
  }
368
368
  logger.banner("Initialize new alwatr-nitrobase");
@@ -380,7 +380,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
380
380
  logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`, ref.hasUnprocessedChanges_);
381
381
  if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {
382
382
  logger.incident?.("exitHook__", "rescue_unsaved_context", { id: ref.id });
383
- writeJson(resolve(this.config__.rootPath, ref.path), ref.getFullContext_(), true);
383
+ writeJson(resolve(this.config.rootPath, ref.path), ref.getFullContext_(), true);
384
384
  ref.hasUnprocessedChanges_ = false;
385
385
  }
386
386
  }
@@ -406,7 +406,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
406
406
  *
407
407
  * Use for nitrobase file format version for check compatibility.
408
408
  */
409
- _AlwatrNitrobase.version = "7.4.0";
409
+ _AlwatrNitrobase.version = "7.5.0";
410
410
  /**
411
411
  * The root nitrobase file stat.
412
412
  */
package/dist/main.mjs.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/alwatr-nitrobase.ts", "../src/logger.ts"],
4
- "sourcesContent": ["import {delay} from '@alwatr/nanolib';\nimport {exitHook} from '@alwatr/nanolib/exit-hook';\nimport {existsSync, readJson, resolve, unlink, writeJson} from '@alwatr/nanolib/node-fs';\nimport {getStoreId, getStorePath} from '@alwatr/nitrobase-helper';\nimport {CollectionReference, DocumentReference} from '@alwatr/nitrobase-reference';\nimport {\n StoreFileType,\n StoreFileExtension,\n Region,\n type StoreFileStat,\n type StoreFileContext,\n type CollectionContext,\n type DocumentContext,\n type StoreFileId,\n type CollectionItem,\n} from '@alwatr/nitrobase-types';\n\nimport {logger} from './logger.js';\n\n__dev_mode__: logger.logFileModule?.('alwatr-nitrobase');\n\n/**\n * AlwatrNitrobase configuration.\n */\nexport interface AlwatrNitrobaseConfig {\n /**\n * The root path of the storage.\n * This is where the AlwatrNitrobase will nitrobase its data.\n */\n rootPath: string;\n\n /**\n * The save debounce timeout in milliseconds for minimal disk I/O usage.\n * This is used to limit the frequency of disk writes for performance reasons.\n * The recommended value is `40`.\n */\n defaultChangeDebounce?: number;\n\n /**\n * If true, an error will be thrown when trying to read or write to a nitrobase file that is not initialized (new storage).\n * The default value is `false` but highly recommended to set it to `true` in production to prevent data loss.\n */\n errorWhenNotInitialized?: boolean;\n}\n\n/**\n * AlwatrNitrobase engine.\n *\n * It provides methods to read, write, validate, and manage nitrobase files.\n * It also provides methods to interact with `documents` and `collections` in the nitrobase.\n */\nexport class AlwatrNitrobase {\n /**\n * The Alwatr Nitrobase version string.\n *\n * Use for nitrobase file format version for check compatibility.\n */\n static readonly version = __package_version__;\n\n /**\n * The root nitrobase file stat.\n */\n private static readonly rootDbStat__: StoreFileStat = {\n name: '.nitrobase',\n region: Region.Secret,\n type: StoreFileType.Collection,\n extension: StoreFileExtension.Json,\n changeDebounce: 40,\n };\n\n /**\n * `collectionReference` of all `storeFileStat`s.\n * This is the root nitrobase collection.\n */\n private rootDb__;\n\n /**\n * Keep all loaded nitrobase file context loaded in memory.\n */\n private cacheReferences__: DictionaryReq<DocumentReference | CollectionReference> = {};\n\n /**\n * Constructs an AlwatrNitrobase instance with the provided configuration.\n *\n * @param config__ The configuration of the AlwatrNitrobase engine.\n * @example\n * ```typescript\n * const alwatrStore = new AlwatrNitrobase({\n * rootPath: './db',\n * saveDebounce: 40,\n * });\n * ```\n */\n constructor(private readonly config__: AlwatrNitrobaseConfig) {\n logger.logMethodArgs?.('new', config__);\n this.config__.defaultChangeDebounce ??= 40;\n this.rootDb__ = this.loadRootDb__();\n exitHook(this.exitHook__.bind(this));\n }\n\n /**\n * Checks if a nitrobase file with the given ID exists.\n *\n * @param storeId - The ID of the nitrobase file to check.\n * @returns `true` if the nitrobase file exists, `false` otherwise.\n * @example\n * ```typescript\n * if (!alwatrStore.hasStore('user1/profile')) {\n * alwatrStore.defineDocument(...)\n * }\n * ```\n */\n hasStore(storeId: StoreFileId): boolean {\n const id_ = getStoreId(storeId);\n const exists = this.rootDb__.hasItem(id_);\n logger.logMethodFull?.('hasStore', id_, exists);\n return exists;\n }\n\n /**\n * Defines a new document with the given configuration and initial data.\n * If a document with the same ID already exists, an error is thrown.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the document\n * @template TDoc document data type\n * @example\n * ```typescript\n * await alwatrStore.newDocument<Order>(\n * {\n * name: 'profile',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * },\n * {\n * name: 'Ali',\n * email: 'ali@alwatr.io',\n * }\n * );\n * ```\n */\n newDocument<T extends JsonObject = JsonObject>(\n stat: Omit<StoreFileStat, 'type'>,\n initialData: DocumentContext<T>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newDocument', stat);\n return this.newStoreFile_(\n {\n ...stat,\n type: StoreFileType.Document,\n },\n initialData,\n );\n }\n\n /**\n * Defines a new collection with the given configuration and initial data.\n * If a collection with the same ID already exists, an error is thrown.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the collection\n * @template TItem collection item data type\n * @example\n * ```typescript\n * await alwatrStore.newCollection<Order>(\n * {\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * }\n * );\n * ```\n */\n newCollection<TItem extends JsonObject = JsonObject>(\n stat: Omit<StoreFileStat, 'type'>,\n initialData: CollectionContext<TItem>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newCollection', stat);\n return this.newStoreFile_(\n {\n ...stat,\n type: StoreFileType.Collection,\n },\n initialData,\n );\n }\n\n /**\n * Defines a AlwatrNitrobaseFile with the given configuration and initial data.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the document\n * @template TDoc document data type\n */\n newStoreFile_<T extends JsonObject = JsonObject>(\n stat: StoreFileStat,\n initialData: DocumentContext<T>['data'] | CollectionContext<T>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newStoreFile_', stat);\n\n (stat.changeDebounce as number | undefined) ??= this.config__.defaultChangeDebounce;\n\n let fileStoreRef: DocumentReference | CollectionReference;\n if (stat.type === StoreFileType.Document) {\n fileStoreRef = DocumentReference.newRefFromData(stat, initialData as DocumentContext['data'], this.storeChanged_.bind(this));\n }\n else if (stat.type === StoreFileType.Collection) {\n fileStoreRef = CollectionReference.newRefFromData(stat, initialData as CollectionContext['data'], this.storeChanged_.bind(this));\n }\n else {\n logger.accident('newStoreFile_', 'store_file_type_not_supported', stat);\n throw new Error('store_file_type_not_supported', {cause: stat});\n }\n\n if (this.rootDb__.hasItem(fileStoreRef.id)) {\n logger.accident('newStoreFile_', 'store_file_already_defined', stat);\n throw new Error('store_file_already_defined', {cause: stat});\n }\n\n this.rootDb__.addItem(fileStoreRef.id, stat);\n this.cacheReferences__[fileStoreRef.id] = fileStoreRef;\n\n // fileStoreRef.save();\n this.storeChanged_(fileStoreRef);\n }\n\n /**\n * Open a document with the given id and create and return a DocumentReference.\n * If the document not exists or its not a document, an error is thrown.\n *\n * @template TDoc document data type\n * @param documentId document id {@link StoreFileId}\n * @returns document reference {@link DocumentReference}\n * @example\n * ```typescript\n * const userProfile = await alwatrStore.openDocument<User>({\n * name: 'user1/profile',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * });\n * userProfile.update({name: 'ali'});\n * ```\n */\n async openDocument<TDoc extends JsonObject>(documentId: StoreFileId): Promise<DocumentReference<TDoc>> {\n const id = getStoreId(documentId);\n logger.logMethodArgs?.('openDocument', id);\n\n if (Object.hasOwn(this.cacheReferences__, id)) {\n const ref = this.cacheReferences__[id];\n if (!(ref instanceof DocumentReference)) {\n logger.accident('openDocument', 'document_wrong_type', id);\n throw new Error('document_wrong_type', {cause: id});\n }\n return this.cacheReferences__[id] as unknown as DocumentReference<TDoc>;\n }\n\n if (!this.rootDb__.hasItem(id)) {\n logger.accident('openDocument', 'document_not_found', id);\n throw new Error('document_not_found', {cause: id});\n }\n\n const storeStat = this.rootDb__.getItemData(id);\n\n if (storeStat.type != StoreFileType.Document) {\n logger.accident('openDocument', 'document_wrong_type', id);\n throw new Error('document_wrong_type', {cause: id});\n }\n\n const context = await this.readContext__<DocumentContext<TDoc>>(storeStat);\n const docRef = DocumentReference.newRefFromContext(context, this.storeChanged_.bind(this));\n this.cacheReferences__[id] = docRef as unknown as DocumentReference;\n return docRef;\n }\n\n /**\n * Open a collection with the given id and create and return a CollectionReference.\n * If the collection not exists or its not a collection, an error is thrown.\n *\n * @template TItem collection item data type\n * @param collectionId collection id {@link StoreFileId}\n * @returns collection reference {@link CollectionReference}\n * @example\n * ```typescript\n * const orders = await alwatrStore.openCollection<Order>({\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * });\n * orders.append({name: 'order 1'});\n * ```\n */\n async openCollection<TItem extends JsonObject>(collectionId: StoreFileId): Promise<CollectionReference<TItem>> {\n const id = getStoreId(collectionId);\n logger.logMethodArgs?.('openCollection', id);\n\n // try to get from cache\n if (Object.hasOwn(this.cacheReferences__, id)) {\n const ref = this.cacheReferences__[id];\n if (!(ref instanceof CollectionReference)) {\n logger.accident('openCollection', 'collection_wrong_type', id);\n throw new Error('collection_wrong_type', {cause: id});\n }\n return this.cacheReferences__[id] as unknown as CollectionReference<TItem>;\n }\n\n // load and create new collection reference\n if (!this.rootDb__.hasItem(id)) {\n logger.accident('openCollection', 'collection_not_found', id);\n throw new Error('collection_not_found', {cause: id});\n }\n\n const storeStat = this.rootDb__.getItemData(id);\n\n if (storeStat.type != StoreFileType.Collection) {\n logger.accident('openCollection', 'collection_wrong_type', id);\n throw new Error('collection_not_found', {cause: id});\n }\n\n const context = await this.readContext__<CollectionContext<TItem>>(storeStat);\n const colRef = CollectionReference.newRefFromContext(context, this.storeChanged_.bind(this));\n this.cacheReferences__[id] = colRef as unknown as CollectionReference;\n return colRef;\n }\n\n /**\n * Unloads the nitrobase file with the given id from memory.\n *\n * @param storeId The unique identifier of the nitrobase file. {@link StoreFileId}\n * @example\n * ```typescript\n * alwatrStore.unloadStore({name: 'user-list', region: Region.Secret});\n * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // true\n * ```\n */\n unloadStore(storeId: StoreFileId): void {\n const id_ = getStoreId(storeId);\n logger.logMethodArgs?.('unloadStore', id_);\n const ref = this.cacheReferences__[id_];\n if (ref === undefined) return;\n if (ref.hasUnprocessedChanges_ === true) {\n ref.updateDelayed_ = false;\n this.storeChanged_(ref);\n }\n delete this.cacheReferences__[id_];\n }\n\n /**\n * Remove document or collection from nitrobase and delete the file from disk.\n * If the file is not found, an error is thrown.\n * If the file is not unloaded, it will be unloaded first.\n * You don't need to await this method to complete unless you want to make sure the file is deleted on disk.\n *\n * @param storeId The ID of the file to delete. {@link StoreFileId}\n * @returns A Promise that resolves when the file is deleted.\n * @example\n * ```typescript\n * alwatrStore.removeStore({name: 'user-list', region: Region.Secret});\n * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // false\n * ```\n */\n async removeStore(storeId: StoreFileId): Promise<void> {\n const id_ = getStoreId(storeId);\n logger.logMethodArgs?.('removeStore', id_);\n if (!this.rootDb__.hasItem(id_)) {\n logger.accident('removeStore', 'document_not_found', id_);\n throw new Error('document_not_found', {cause: id_});\n }\n const ref = this.cacheReferences__[id_];\n if (ref !== undefined) {\n // direct unload to prevent save\n ref.freeze = true;\n ref.updateDelayed_ = false;\n ref.hasUnprocessedChanges_ = false;\n delete this.cacheReferences__[id_]; // unload\n }\n const path = getStorePath(this.rootDb__.getItemData(id_));\n this.rootDb__.removeItem(id_);\n await delay.by(0);\n try {\n await unlink(resolve(this.config__.rootPath, path));\n }\n catch (error) {\n logger.error('removeStore', 'remove_file_failed', error, {id: storeId, path});\n }\n }\n\n /**\n * Saves all changes in the nitrobase.\n *\n * @returns A Promise that resolves when all changes are saved.\n * @example\n * ```typescript\n * await alwatrStore.saveAll();\n * ```\n */\n async saveAll(): Promise<void> {\n logger.logMethod?.('saveAll');\n for (const ref of Object.values(this.cacheReferences__)) {\n if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {\n ref.updateDelayed_ = false;\n await this.storeChanged_(ref);\n }\n }\n }\n\n /**\n * Reads the context from a given path or StoreFileStat object.\n *\n * @param path The path or StoreFileStat object from which to read the context.\n * @returns A promise that resolves to the context object.\n */\n private async readContext__<T extends StoreFileContext>(path: string | StoreFileStat): Promise<T> {\n if (typeof path !== 'string') path = getStorePath(path);\n logger.logMethodArgs?.('readContext__', path);\n logger.time?.(`readContext__time(${path})`);\n const context = (await readJson(resolve(this.config__.rootPath, path))) as T;\n logger.timeEnd?.(`readContext__time(${path})`);\n return context;\n }\n\n /**\n * Writes the context to the specified path.\n *\n * @template T The type of the context.\n * @param path The path where the context will be written.\n * @param context The context to be written.\n * @param sync Indicates whether the write operation should be synchronous.\n * @returns A promise that resolves when the write operation is complete.\n */\n private writeContext__<T extends StoreFileContext>(path: string | StoreFileStat, context: T): Promise<void> {\n if (typeof path !== 'string') path = getStorePath(path);\n logger.logMethodArgs?.('writeContext__', path);\n return writeJson(resolve(this.config__.rootPath, path), context);\n }\n\n /**\n * Write nitrobase file context.\n *\n * @param from nitrobase file reference\n * @returns A promise that resolves when the write operation is complete.\n */\n protected async storeChanged_<T extends JsonObject>(from: DocumentReference<T> | CollectionReference<T>): Promise<void> {\n logger.logMethodArgs?.('storeChanged__', from.id);\n const rev = from.getStoreMeta().rev;\n try {\n await this.writeContext__(from.path, from.getFullContext_());\n if (rev === from.getStoreMeta().rev) {\n // Context not changed during saving\n from.hasUnprocessedChanges_ = false;\n }\n }\n catch (error) {\n logger.error('storeChanged__', 'write_context_failed', {id: from.id, error});\n }\n }\n\n /**\n * Load storeFilesCollection or create new one.\n */\n private loadRootDb__(): CollectionReference<StoreFileStat> {\n logger.logMethod?.('loadRootDb__');\n const fullPath = resolve(this.config__.rootPath, getStorePath(AlwatrNitrobase.rootDbStat__));\n if (!existsSync(fullPath)) {\n if (this.config__.errorWhenNotInitialized === true) {\n throw new Error('store_not_found', {cause: 'Nitrobase not initialized'});\n }\n\n logger.banner('Initialize new alwatr-nitrobase');\n return CollectionReference.newRefFromData(AlwatrNitrobase.rootDbStat__, null, this.storeChanged_.bind(this));\n }\n // else\n const context = readJson<CollectionContext<StoreFileStat>>(fullPath, true);\n return CollectionReference.newRefFromContext(context, this.storeChanged_.bind(this), 'root-db');\n }\n\n /**\n * Save all nitrobase files.\n */\n private exitHook__(): void {\n logger.logMethod?.('exitHook__');\n for (const ref of Object.values(this.cacheReferences__)) {\n logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`, ref.hasUnprocessedChanges_);\n if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {\n logger.incident?.('exitHook__', 'rescue_unsaved_context', {id: ref.id});\n writeJson(resolve(this.config__.rootPath, ref.path), ref.getFullContext_(), true);\n ref.hasUnprocessedChanges_ = false;\n }\n }\n }\n\n /**\n * Get all nitrobase files.\n *\n * @returns all nitrobase files.\n * @example\n * ```typescript\n * const storeList = alwatrStore.getStoreList();\n * for (const nitrobase of storeList) {\n * console.log(nitrobase.meta.id, nitrobase.data);\n * }\n */\n getStoreList(): CollectionItem<Omit<StoreFileStat, 'schemaVer'>>[] {\n logger.logMethod?.('getStoreList');\n return this.rootDb__.values();\n }\n}\n", "import {createLogger, packageTracer} from '@alwatr/nanolib';\n\n__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\nexport const logger = /* #__PURE__ */ createLogger(__package_name__);\n"],
5
- "mappings": ";;;AAAA,SAAQ,aAAY;AACpB,SAAQ,gBAAe;AACvB,SAAQ,YAAY,UAAU,SAAS,QAAQ,iBAAgB;AAC/D,SAAQ,YAAY,oBAAmB;AACvC,SAAQ,qBAAqB,yBAAwB;AACrD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAOK;;;ACfP,SAAQ,cAAc,qBAAoB;AAE1C,aAAc,eAAc,IAAI,4BAAkB,OAAmB;AAE9D,IAAM,SAAyB,6BAAa,0BAAgB;;;ADenE,aAAc,QAAO,gBAAgB,kBAAkB;AAgChD,IAAM,mBAAN,MAAM,iBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA0C3B,YAA6B,UAAiC;AAAjC;AAd7B;AAAA;AAAA;AAAA,SAAQ,oBAA4E,CAAC;AA/EvF;AA8FI,WAAO,gBAAgB,OAAO,QAAQ;AACtC,eAAK,UAAS,0BAAd,GAAc,wBAA0B;AACxC,SAAK,WAAW,KAAK,aAAa;AAClC,aAAS,KAAK,WAAW,KAAK,IAAI,CAAC;AAAA,EACrC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,SAAS,SAA+B;AACtC,UAAM,MAAM,WAAW,OAAO;AAC9B,UAAM,SAAS,KAAK,SAAS,QAAQ,GAAG;AACxC,WAAO,gBAAgB,YAAY,KAAK,MAAM;AAC9C,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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,IAC7G;AAEA,UAAM,UAAU,SAA2C,UAAU,IAAI;AACzE,WAAO,oBAAoB,kBAAkB,SAAS,KAAK,cAAc,KAAK,IAAI,GAAG,SAAS;AAAA,EAChG;AAAA;AAAA;AAAA;AAAA,EAKQ,aAAmB;AACzB,WAAO,YAAY,YAAY;AAC/B,eAAW,OAAO,OAAO,OAAO,KAAK,iBAAiB,GAAG;AACvD,aAAO,cAAc,aAAa,IAAI,EAAE,0BAA0B,IAAI,sBAAsB;AAC5F,UAAI,IAAI,2BAA2B,QAAQ,IAAI,WAAW,MAAM;AAC9D,eAAO,WAAW,cAAc,0BAA0B,EAAC,IAAI,IAAI,GAAE,CAAC;AACtE,kBAAU,QAAQ,KAAK,SAAS,UAAU,IAAI,IAAI,GAAG,IAAI,gBAAgB,GAAG,IAAI;AAChF,YAAI,yBAAyB;AAAA,MAC/B;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,eAAmE;AACjE,WAAO,YAAY,cAAc;AACjC,WAAO,KAAK,SAAS,OAAO;AAAA,EAC9B;AACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAtca,iBAMK,UAAU;AAAA;AAAA;AAAA;AANf,iBAWa,eAA8B;AAAA,EACpD,MAAM;AAAA,EACN,QAAQ,OAAO;AAAA,EACf,MAAM,cAAc;AAAA,EACpB,WAAW,mBAAmB;AAAA,EAC9B,gBAAgB;AAClB;AAjBK,IAAM,kBAAN;",
4
+ "sourcesContent": ["import {delay} from '@alwatr/nanolib';\nimport {exitHook} from '@alwatr/nanolib/exit-hook';\nimport {existsSync, readJson, resolve, unlink, writeJson} from '@alwatr/nanolib/node-fs';\nimport {getStoreId, getStorePath} from '@alwatr/nitrobase-helper';\nimport {CollectionReference, DocumentReference} from '@alwatr/nitrobase-reference';\nimport {\n StoreFileType,\n StoreFileExtension,\n Region,\n type StoreFileStat,\n type StoreFileContext,\n type CollectionContext,\n type DocumentContext,\n type StoreFileId,\n type CollectionItem,\n} from '@alwatr/nitrobase-types';\n\nimport {logger} from './logger.js';\n\n__dev_mode__: logger.logFileModule?.('alwatr-nitrobase');\n\n/**\n * AlwatrNitrobase configuration.\n */\nexport interface AlwatrNitrobaseConfig {\n /**\n * The root path of the storage.\n * This is where the AlwatrNitrobase will nitrobase its data.\n */\n rootPath: string;\n\n /**\n * The save debounce timeout in milliseconds for minimal disk I/O usage.\n * This is used to limit the frequency of disk writes for performance reasons.\n * The recommended value is `40`.\n */\n defaultChangeDebounce?: number;\n\n /**\n * If true, an error will be thrown when trying to read or write to a nitrobase file that is not initialized (new storage).\n * The default value is `false` but highly recommended to set it to `true` in production to prevent data loss.\n */\n errorWhenNotInitialized?: boolean;\n}\n\n/**\n * AlwatrNitrobase engine.\n *\n * It provides methods to read, write, validate, and manage nitrobase files.\n * It also provides methods to interact with `documents` and `collections` in the nitrobase.\n */\nexport class AlwatrNitrobase {\n /**\n * The Alwatr Nitrobase version string.\n *\n * Use for nitrobase file format version for check compatibility.\n */\n static readonly version = __package_version__;\n\n /**\n * The root nitrobase file stat.\n */\n private static readonly rootDbStat__: StoreFileStat = {\n name: '.nitrobase',\n region: Region.Secret,\n type: StoreFileType.Collection,\n extension: StoreFileExtension.Json,\n changeDebounce: 40,\n };\n\n /**\n * `collectionReference` of all `storeFileStat`s.\n * This is the root nitrobase collection.\n */\n private rootDb__;\n\n /**\n * Keep all loaded nitrobase file context loaded in memory.\n */\n private cacheReferences__: DictionaryReq<DocumentReference | CollectionReference> = {};\n\n /**\n * Constructs an AlwatrNitrobase instance with the provided configuration.\n *\n * @param config The configuration of the AlwatrNitrobase engine.\n * @example\n * ```typescript\n * const alwatrStore = new AlwatrNitrobase({\n * rootPath: './db',\n * saveDebounce: 40,\n * });\n * ```\n */\n constructor(readonly config: AlwatrNitrobaseConfig) {\n logger.logMethodArgs?.('new', config);\n this.config.defaultChangeDebounce ??= 40;\n this.rootDb__ = this.loadRootDb__();\n exitHook(this.exitHook__.bind(this));\n }\n\n /**\n * Checks if a nitrobase file with the given ID exists.\n *\n * @param storeId - The ID of the nitrobase file to check.\n * @returns `true` if the nitrobase file exists, `false` otherwise.\n * @example\n * ```typescript\n * if (!alwatrStore.hasStore('user1/profile')) {\n * alwatrStore.defineDocument(...)\n * }\n * ```\n */\n hasStore(storeId: StoreFileId): boolean {\n const id_ = getStoreId(storeId);\n const exists = this.rootDb__.hasItem(id_);\n logger.logMethodFull?.('hasStore', id_, exists);\n return exists;\n }\n\n /**\n * Defines a new document with the given configuration and initial data.\n * If a document with the same ID already exists, an error is thrown.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the document\n * @template TDoc document data type\n * @example\n * ```typescript\n * await alwatrStore.newDocument<Order>(\n * {\n * name: 'profile',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * },\n * {\n * name: 'Ali',\n * email: 'ali@alwatr.io',\n * }\n * );\n * ```\n */\n newDocument<T extends JsonObject = JsonObject>(\n stat: Omit<StoreFileStat, 'type'>,\n initialData: DocumentContext<T>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newDocument', stat);\n return this.newStoreFile_(\n {\n ...stat,\n type: StoreFileType.Document,\n },\n initialData,\n );\n }\n\n /**\n * Defines a new collection with the given configuration and initial data.\n * If a collection with the same ID already exists, an error is thrown.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the collection\n * @template TItem collection item data type\n * @example\n * ```typescript\n * await alwatrStore.newCollection<Order>(\n * {\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * }\n * );\n * ```\n */\n newCollection<TItem extends JsonObject = JsonObject>(\n stat: Omit<StoreFileStat, 'type'>,\n initialData: CollectionContext<TItem>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newCollection', stat);\n return this.newStoreFile_(\n {\n ...stat,\n type: StoreFileType.Collection,\n },\n initialData,\n );\n }\n\n /**\n * Defines a AlwatrNitrobaseFile with the given configuration and initial data.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the document\n * @template TDoc document data type\n */\n newStoreFile_<T extends JsonObject = JsonObject>(\n stat: StoreFileStat,\n initialData: DocumentContext<T>['data'] | CollectionContext<T>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newStoreFile_', stat);\n\n (stat.changeDebounce as number | undefined) ??= this.config.defaultChangeDebounce;\n\n let fileStoreRef: DocumentReference | CollectionReference;\n if (stat.type === StoreFileType.Document) {\n fileStoreRef = DocumentReference.newRefFromData(stat, initialData as DocumentContext['data'], this.storeChanged_.bind(this));\n }\n else if (stat.type === StoreFileType.Collection) {\n fileStoreRef = CollectionReference.newRefFromData(stat, initialData as CollectionContext['data'], this.storeChanged_.bind(this));\n }\n else {\n logger.accident('newStoreFile_', 'store_file_type_not_supported', stat);\n throw new Error('store_file_type_not_supported', {cause: stat});\n }\n\n if (this.rootDb__.hasItem(fileStoreRef.id)) {\n logger.accident('newStoreFile_', 'store_file_already_defined', stat);\n throw new Error('store_file_already_defined', {cause: stat});\n }\n\n this.rootDb__.addItem(fileStoreRef.id, stat);\n this.cacheReferences__[fileStoreRef.id] = fileStoreRef;\n\n // fileStoreRef.save();\n this.storeChanged_(fileStoreRef);\n }\n\n /**\n * Open a document with the given id and create and return a DocumentReference.\n * If the document not exists or its not a document, an error is thrown.\n *\n * @template TDoc document data type\n * @param documentId document id {@link StoreFileId}\n * @returns document reference {@link DocumentReference}\n * @example\n * ```typescript\n * const userProfile = await alwatrStore.openDocument<User>({\n * name: 'user1/profile',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * });\n * userProfile.update({name: 'ali'});\n * ```\n */\n async openDocument<TDoc extends JsonObject>(documentId: StoreFileId): Promise<DocumentReference<TDoc>> {\n const id = getStoreId(documentId);\n logger.logMethodArgs?.('openDocument', id);\n\n if (Object.hasOwn(this.cacheReferences__, id)) {\n const ref = this.cacheReferences__[id];\n if (!(ref instanceof DocumentReference)) {\n logger.accident('openDocument', 'document_wrong_type', id);\n throw new Error('document_wrong_type', {cause: id});\n }\n return this.cacheReferences__[id] as unknown as DocumentReference<TDoc>;\n }\n\n if (!this.rootDb__.hasItem(id)) {\n logger.accident('openDocument', 'document_not_found', id);\n throw new Error('document_not_found', {cause: id});\n }\n\n const storeStat = this.rootDb__.getItemData(id);\n\n if (storeStat.type != StoreFileType.Document) {\n logger.accident('openDocument', 'document_wrong_type', id);\n throw new Error('document_wrong_type', {cause: id});\n }\n\n const context = await this.readContext__<DocumentContext<TDoc>>(storeStat);\n const docRef = DocumentReference.newRefFromContext(context, this.storeChanged_.bind(this));\n this.cacheReferences__[id] = docRef as unknown as DocumentReference;\n return docRef;\n }\n\n /**\n * Open a collection with the given id and create and return a CollectionReference.\n * If the collection not exists or its not a collection, an error is thrown.\n *\n * @template TItem collection item data type\n * @param collectionId collection id {@link StoreFileId}\n * @returns collection reference {@link CollectionReference}\n * @example\n * ```typescript\n * const orders = await alwatrStore.openCollection<Order>({\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * });\n * orders.append({name: 'order 1'});\n * ```\n */\n async openCollection<TItem extends JsonObject>(collectionId: StoreFileId): Promise<CollectionReference<TItem>> {\n const id = getStoreId(collectionId);\n logger.logMethodArgs?.('openCollection', id);\n\n // try to get from cache\n if (Object.hasOwn(this.cacheReferences__, id)) {\n const ref = this.cacheReferences__[id];\n if (!(ref instanceof CollectionReference)) {\n logger.accident('openCollection', 'collection_wrong_type', id);\n throw new Error('collection_wrong_type', {cause: id});\n }\n return this.cacheReferences__[id] as unknown as CollectionReference<TItem>;\n }\n\n // load and create new collection reference\n if (!this.rootDb__.hasItem(id)) {\n logger.accident('openCollection', 'collection_not_found', id);\n throw new Error('collection_not_found', {cause: id});\n }\n\n const storeStat = this.rootDb__.getItemData(id);\n\n if (storeStat.type != StoreFileType.Collection) {\n logger.accident('openCollection', 'collection_wrong_type', id);\n throw new Error('collection_not_found', {cause: id});\n }\n\n const context = await this.readContext__<CollectionContext<TItem>>(storeStat);\n const colRef = CollectionReference.newRefFromContext(context, this.storeChanged_.bind(this));\n this.cacheReferences__[id] = colRef as unknown as CollectionReference;\n return colRef;\n }\n\n /**\n * Unloads the nitrobase file with the given id from memory.\n *\n * @param storeId The unique identifier of the nitrobase file. {@link StoreFileId}\n * @example\n * ```typescript\n * alwatrStore.unloadStore({name: 'user-list', region: Region.Secret});\n * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // true\n * ```\n */\n unloadStore(storeId: StoreFileId): void {\n const id_ = getStoreId(storeId);\n logger.logMethodArgs?.('unloadStore', id_);\n const ref = this.cacheReferences__[id_];\n if (ref === undefined) return;\n if (ref.hasUnprocessedChanges_ === true) {\n ref.updateDelayed_ = false;\n this.storeChanged_(ref);\n }\n delete this.cacheReferences__[id_];\n }\n\n /**\n * Remove document or collection from nitrobase and delete the file from disk.\n * If the file is not found, an error is thrown.\n * If the file is not unloaded, it will be unloaded first.\n * You don't need to await this method to complete unless you want to make sure the file is deleted on disk.\n *\n * @param storeId The ID of the file to delete. {@link StoreFileId}\n * @returns A Promise that resolves when the file is deleted.\n * @example\n * ```typescript\n * alwatrStore.removeStore({name: 'user-list', region: Region.Secret});\n * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // false\n * ```\n */\n async removeStore(storeId: StoreFileId): Promise<void> {\n const id_ = getStoreId(storeId);\n logger.logMethodArgs?.('removeStore', id_);\n if (!this.rootDb__.hasItem(id_)) {\n logger.accident('removeStore', 'document_not_found', id_);\n throw new Error('document_not_found', {cause: id_});\n }\n const ref = this.cacheReferences__[id_];\n if (ref !== undefined) {\n // direct unload to prevent save\n ref.freeze = true;\n ref.updateDelayed_ = false;\n ref.hasUnprocessedChanges_ = false;\n delete this.cacheReferences__[id_]; // unload\n }\n const path = getStorePath(this.rootDb__.getItemData(id_));\n this.rootDb__.removeItem(id_);\n await delay.by(0);\n try {\n await unlink(resolve(this.config.rootPath, path));\n }\n catch (error) {\n logger.error('removeStore', 'remove_file_failed', error, {id: storeId, path});\n }\n }\n\n /**\n * Saves all changes in the nitrobase.\n *\n * @returns A Promise that resolves when all changes are saved.\n * @example\n * ```typescript\n * await alwatrStore.saveAll();\n * ```\n */\n async saveAll(): Promise<void> {\n logger.logMethod?.('saveAll');\n for (const ref of Object.values(this.cacheReferences__)) {\n if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {\n ref.updateDelayed_ = false;\n await this.storeChanged_(ref);\n }\n }\n }\n\n /**\n * Reads the context from a given path or StoreFileStat object.\n *\n * @param path The path or StoreFileStat object from which to read the context.\n * @returns A promise that resolves to the context object.\n */\n private async readContext__<T extends StoreFileContext>(path: string | StoreFileStat): Promise<T> {\n if (typeof path !== 'string') path = getStorePath(path);\n logger.logMethodArgs?.('readContext__', path);\n logger.time?.(`readContext__time(${path})`);\n const context = (await readJson(resolve(this.config.rootPath, path))) as T;\n logger.timeEnd?.(`readContext__time(${path})`);\n return context;\n }\n\n /**\n * Writes the context to the specified path.\n *\n * @template T The type of the context.\n * @param path The path where the context will be written.\n * @param context The context to be written.\n * @param sync Indicates whether the write operation should be synchronous.\n * @returns A promise that resolves when the write operation is complete.\n */\n private writeContext__<T extends StoreFileContext>(path: string | StoreFileStat, context: T): Promise<void> {\n if (typeof path !== 'string') path = getStorePath(path);\n logger.logMethodArgs?.('writeContext__', path);\n return writeJson(resolve(this.config.rootPath, path), context);\n }\n\n /**\n * Write nitrobase file context.\n *\n * @param from nitrobase file reference\n * @returns A promise that resolves when the write operation is complete.\n */\n protected async storeChanged_<T extends JsonObject>(from: DocumentReference<T> | CollectionReference<T>): Promise<void> {\n logger.logMethodArgs?.('storeChanged__', from.id);\n const rev = from.getStoreMeta().rev;\n try {\n await this.writeContext__(from.path, from.getFullContext_());\n if (rev === from.getStoreMeta().rev) {\n // Context not changed during saving\n from.hasUnprocessedChanges_ = false;\n }\n }\n catch (error) {\n logger.error('storeChanged__', 'write_context_failed', {id: from.id, error});\n }\n }\n\n /**\n * Load storeFilesCollection or create new one.\n */\n private loadRootDb__(): CollectionReference<StoreFileStat> {\n logger.logMethod?.('loadRootDb__');\n const fullPath = resolve(this.config.rootPath, getStorePath(AlwatrNitrobase.rootDbStat__));\n if (!existsSync(fullPath)) {\n if (this.config.errorWhenNotInitialized === true) {\n throw new Error('store_not_found', {cause: 'Nitrobase not initialized'});\n }\n\n logger.banner('Initialize new alwatr-nitrobase');\n return CollectionReference.newRefFromData(AlwatrNitrobase.rootDbStat__, null, this.storeChanged_.bind(this));\n }\n // else\n const context = readJson<CollectionContext<StoreFileStat>>(fullPath, true);\n return CollectionReference.newRefFromContext(context, this.storeChanged_.bind(this), 'root-db');\n }\n\n /**\n * Save all nitrobase files.\n */\n private exitHook__(): void {\n logger.logMethod?.('exitHook__');\n for (const ref of Object.values(this.cacheReferences__)) {\n logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`, ref.hasUnprocessedChanges_);\n if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {\n logger.incident?.('exitHook__', 'rescue_unsaved_context', {id: ref.id});\n writeJson(resolve(this.config.rootPath, ref.path), ref.getFullContext_(), true);\n ref.hasUnprocessedChanges_ = false;\n }\n }\n }\n\n /**\n * Get all nitrobase files.\n *\n * @returns all nitrobase files.\n * @example\n * ```typescript\n * const storeList = alwatrStore.getStoreList();\n * for (const nitrobase of storeList) {\n * console.log(nitrobase.meta.id, nitrobase.data);\n * }\n */\n getStoreList(): CollectionItem<Omit<StoreFileStat, 'schemaVer'>>[] {\n logger.logMethod?.('getStoreList');\n return this.rootDb__.values();\n }\n}\n", "import {createLogger, packageTracer} from '@alwatr/nanolib';\n\n__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\nexport const logger = /* #__PURE__ */ createLogger(__package_name__);\n"],
5
+ "mappings": ";;;AAAA,SAAQ,aAAY;AACpB,SAAQ,gBAAe;AACvB,SAAQ,YAAY,UAAU,SAAS,QAAQ,iBAAgB;AAC/D,SAAQ,YAAY,oBAAmB;AACvC,SAAQ,qBAAqB,yBAAwB;AACrD;AAAA,EACE;AAAA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I,IAAI,GAAE,CAAC;AACtE,kBAAU,QAAQ,KAAK,OAAO,UAAU,IAAI,IAAI,GAAG,IAAI,gBAAgB,GAAG,IAAI;AAC9E,YAAI,yBAAyB;AAAA,MAC/B;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,eAAmE;AACjE,WAAO,YAAY,cAAc;AACjC,WAAO,KAAK,SAAS,OAAO;AAAA,EAC9B;AACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAtca,iBAMK,UAAU;AAAA;AAAA;AAAA;AANf,iBAWa,eAA8B;AAAA,EACpD,MAAM;AAAA,EACN,QAAQ,OAAO;AAAA,EACf,MAAM,cAAc;AAAA,EACpB,WAAW,mBAAmB;AAAA,EAC9B,gBAAgB;AAClB;AAjBK,IAAM,kBAAN;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alwatr/nitrobase-engine",
3
- "version": "7.4.0",
3
+ "version": "7.5.0",
4
4
  "description": "Nitrobase is a blazingly fast, lightweight database built on JSON. It stores data entirely in memory for lightning-quick access, while also providing a JSON file backup for persistence. You can easily serve your data over the web using our high-performance accelerated Nginx server.",
5
5
  "author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
6
6
  "keywords": [
@@ -61,9 +61,9 @@
61
61
  },
62
62
  "dependencies": {
63
63
  "@alwatr/nanolib": "^5.2.1",
64
- "@alwatr/nitrobase-helper": "^7.4.0",
65
- "@alwatr/nitrobase-reference": "^7.4.0",
66
- "@alwatr/nitrobase-types": "^7.4.0"
64
+ "@alwatr/nitrobase-helper": "^7.5.0",
65
+ "@alwatr/nitrobase-reference": "^7.5.0",
66
+ "@alwatr/nitrobase-types": "^7.5.0"
67
67
  },
68
68
  "devDependencies": {
69
69
  "@alwatr/nano-build": "^5.0.0",
@@ -73,5 +73,5 @@
73
73
  "@types/node": "^22.9.0",
74
74
  "typescript": "^5.6.3"
75
75
  },
76
- "gitHead": "ac284c47ccbd75f187bd5f4da4e990b1f92b52f5"
76
+ "gitHead": "cb82a2f1ffa090db44cf7476fe68a2e4d8b0f67a"
77
77
  }