@alwatr/nitrobase-engine 7.10.0 โ†’ 7.10.1

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,18 @@
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.10.1](https://github.com/Alwatr/nitrobase/compare/v7.10.0...v7.10.1) (2025-12-14)
7
+
8
+ ### ๐Ÿงน Miscellaneous Chores
9
+
10
+ * update tsconfig extends to use @alwatr/nanolib ([ffbc8ce](https://github.com/Alwatr/nitrobase/commit/ffbc8ce74d47d7f4e1ff0061722df10f68af11cc))
11
+
12
+ ### ๐Ÿ”— Dependencies update
13
+
14
+ * replace '@alwatr/nano-build' with '@alwatr/nanolib' in logger imports ([9a355b9](https://github.com/Alwatr/nitrobase/commit/9a355b92b27434a3cd132e7e52df5c2e112ca97e))
15
+ * update `@alwatr/nanolib` and `@types/node` dependencies across all packages. ([bc6d96f](https://github.com/Alwatr/nitrobase/commit/bc6d96f4fd423bcfb817d74b526596669d8a8aed))
16
+ * update dependencies and switch prettier config to @alwatr/nanolib ([e2c9ffb](https://github.com/Alwatr/nitrobase/commit/e2c9ffb5f62d88a1ddaef77886d41c0cb7df604d))
17
+
6
18
  ## [7.10.0](https://github.com/Alwatr/nitrobase/compare/v7.9.0...v7.10.0) (2025-09-21)
7
19
 
8
20
  ### ๐Ÿ› Bug Fixes
package/dist/main.cjs CHANGED
@@ -1,4 +1,4 @@
1
- /** ๐Ÿ“ฆ @alwatr/nitrobase-engine v7.10.0 */
2
- __dev_mode__: console.debug("๐Ÿ“ฆ @alwatr/nitrobase-engine v7.10.0");
3
- "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var main_exports={};__export(main_exports,{AlwatrNitrobase:()=>AlwatrNitrobase});module.exports=__toCommonJS(main_exports);var import_delay=require("@alwatr/delay");var import_exit_hook=require("@alwatr/exit-hook");var import_nitrobase_helper=require("@alwatr/nitrobase-helper");var import_nitrobase_reference=require("@alwatr/nitrobase-reference");var import_nitrobase_types=require("@alwatr/nitrobase-types");var import_node_fs=require("@alwatr/node-fs");var import_logger=require("@alwatr/logger");var logger=(0,import_logger.createLogger)("@alwatr/nitrobase-engine");__dev_mode__:logger.logFileModule?.("alwatr-nitrobase");var AlwatrNitrobase=class _AlwatrNitrobase{constructor(config){this.config=config;this.cacheReferences__={};this.storeChanged_=this.storeChanged_.bind(this);logger.logMethodArgs?.("new",config);this.config.defaultChangeDebounce??=40;this.rootDb__=this.loadRootDb__();(0,import_exit_hook.exitHook)(this.exitHook__.bind(this))}static{this.version="7.10.0"}static{this.rootDbStat__={name:".nitrobase",region:import_nitrobase_types.Region.Secret,type:import_nitrobase_types.StoreFileType.Collection,extension:import_nitrobase_types.StoreFileExtension.Json,changeDebounce:40}}hasStore(storeId){const id_=(0,import_nitrobase_helper.getStoreId)(storeId);const exists=this.rootDb__.hasItem(id_);logger.logMethodFull?.("hasStore",id_,exists);return exists}newDocument(stat,data){logger.logMethodArgs?.("newDocument",stat);return this.newStoreFile__({...stat,type:import_nitrobase_types.StoreFileType.Document},data)}newCollection(stat){logger.logMethodArgs?.("newCollection",stat);return this.newStoreFile__({...stat,type:import_nitrobase_types.StoreFileType.Collection})}newStoreFile__(stat,data){logger.logMethodArgs?.("newStoreFile__",stat);stat.changeDebounce??=this.config.defaultChangeDebounce;let fileStoreRef;if(stat.type===import_nitrobase_types.StoreFileType.Document){if(data===void 0){logger.accident("newStoreFile__","document_data_required",stat);throw new Error("document_data_required",{cause:stat})}fileStoreRef=import_nitrobase_reference.DocumentReference.newRefFromData(stat,data,this.storeChanged_)}else if(stat.type===import_nitrobase_types.StoreFileType.Collection){fileStoreRef=import_nitrobase_reference.CollectionReference.newRefFromData(stat,this.storeChanged_)}else{logger.accident("newStoreFile__","store_file_type_not_supported",stat);throw new Error("store_file_type_not_supported",{cause:stat})}if(this.rootDb__.hasItem(fileStoreRef.id)){logger.accident("newStoreFile__","store_file_already_defined",stat);throw new Error("store_file_already_defined",{cause:stat})}this.rootDb__.addItem(fileStoreRef.id,stat);this.cacheReferences__[fileStoreRef.id]=fileStoreRef;this.storeChanged_(fileStoreRef)}async openDocument(documentId){const id=(0,import_nitrobase_helper.getStoreId)(documentId);logger.logMethodArgs?.("openDocument",id);if(Object.hasOwn(this.cacheReferences__,id)){const ref=this.cacheReferences__[id];if(!(ref instanceof import_nitrobase_reference.DocumentReference)){logger.accident("openDocument","document_wrong_type",id);throw new Error("document_wrong_type",{cause:id})}return this.cacheReferences__[id]}if(!this.rootDb__.hasItem(id)){logger.accident("openDocument","document_not_found",id);throw new Error("document_not_found",{cause:id})}const storeStat=this.rootDb__.getItemData(id);if(storeStat.type!=import_nitrobase_types.StoreFileType.Document){logger.accident("openDocument","document_wrong_type",id);throw new Error("document_wrong_type",{cause:id})}const context=await this.readContext__(storeStat);const docRef=import_nitrobase_reference.DocumentReference.newRefFromContext(context,this.storeChanged_);this.cacheReferences__[id]=docRef;return docRef}async openCollection(collectionId){const id=(0,import_nitrobase_helper.getStoreId)(collectionId);logger.logMethodArgs?.("openCollection",id);if(Object.hasOwn(this.cacheReferences__,id)){const ref=this.cacheReferences__[id];if(!(ref instanceof import_nitrobase_reference.CollectionReference)){logger.accident("openCollection","collection_wrong_type",id);throw new Error("collection_wrong_type",{cause:id})}return this.cacheReferences__[id]}if(!this.rootDb__.hasItem(id)){logger.accident("openCollection","collection_not_found",id);throw new Error("collection_not_found",{cause:id})}const storeStat=this.rootDb__.getItemData(id);if(storeStat.type!=import_nitrobase_types.StoreFileType.Collection){logger.accident("openCollection","collection_wrong_type",id);throw new Error("collection_not_found",{cause:id})}const context=await this.readContext__(storeStat);const colRef=import_nitrobase_reference.CollectionReference.newRefFromContext(context,this.storeChanged_);this.cacheReferences__[id]=colRef;return colRef}unloadStore(storeId){const id_=(0,import_nitrobase_helper.getStoreId)(storeId);logger.logMethodArgs?.("unloadStore",id_);const ref=this.cacheReferences__[id_];if(ref===void 0)return;if(ref.hasUnprocessedChanges_===true){ref.updateDelayed_=false;this.storeChanged_(ref)}delete this.cacheReferences__[id_]}async removeStore(storeId){const id_=(0,import_nitrobase_helper.getStoreId)(storeId);logger.logMethodArgs?.("removeStore",id_);if(!this.rootDb__.hasItem(id_)){logger.accident("removeStore","document_not_found",id_);throw new Error("document_not_found",{cause:id_})}const ref=this.cacheReferences__[id_];if(ref!==void 0){ref.freeze=true;ref.updateDelayed_=false;ref.hasUnprocessedChanges_=false;delete this.cacheReferences__[id_]}const path=(0,import_nitrobase_helper.getStorePath)(this.rootDb__.getItemData(id_));this.rootDb__.removeItem(id_);await import_delay.delay.by(0);try{await(0,import_node_fs.unlink)((0,import_node_fs.resolve)(this.config.rootPath,path))}catch(error){logger.error("removeStore","remove_file_failed",error,{id:storeId,path})}}async saveAll(){logger.logMethod?.("saveAll");for(const ref of Object.values(this.cacheReferences__)){if(ref.hasUnprocessedChanges_===true&&ref.freeze!==true){ref.updateDelayed_=false;await this.storeChanged_(ref)}}}async readContext__(path){if(typeof path!=="string")path=(0,import_nitrobase_helper.getStorePath)(path);logger.logMethodArgs?.("readContext__",path);logger.time?.(`readContext__time(${path})`);const context=await(0,import_node_fs.readJson)((0,import_node_fs.resolve)(this.config.rootPath,path));logger.timeEnd?.(`readContext__time(${path})`);return context}writeContext__(path,context){if(typeof path!=="string")path=(0,import_nitrobase_helper.getStorePath)(path);logger.logMethodArgs?.("writeContext__",path);return(0,import_node_fs.writeJson)((0,import_node_fs.resolve)(this.config.rootPath,path),context)}async storeChanged_(from){logger.logMethodArgs?.("storeChanged__",from.id);const rev=from.getStoreMeta().rev;try{await this.writeContext__(from.path,from.getFullContext_());if(rev===from.getStoreMeta().rev){from.hasUnprocessedChanges_=false}}catch(error){logger.error("storeChanged__","write_context_failed",{id:from.id,error})}}loadRootDb__(){logger.logMethod?.("loadRootDb__");const fullPath=(0,import_node_fs.resolve)(this.config.rootPath,(0,import_nitrobase_helper.getStorePath)(_AlwatrNitrobase.rootDbStat__));if(!(0,import_node_fs.existsSync)(fullPath)){if(this.config.errorWhenNotInitialized===true){throw new Error("store_not_found",{cause:"Nitrobase not initialized"})}logger.banner("Initialize new alwatr-nitrobase");return import_nitrobase_reference.CollectionReference.newRefFromData(_AlwatrNitrobase.rootDbStat__,this.storeChanged_)}const context=(0,import_node_fs.readJson)(fullPath,true);return import_nitrobase_reference.CollectionReference.newRefFromContext(context,this.storeChanged_,"root-db")}exitHook__(){logger.logMethod?.("exitHook__");for(const ref of Object.values(this.cacheReferences__)){logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`,ref.hasUnprocessedChanges_);if(ref.hasUnprocessedChanges_===true&&ref.freeze!==true){logger.incident?.("exitHook__","rescue_unsaved_context",{id:ref.id});(0,import_node_fs.writeJson)((0,import_node_fs.resolve)(this.config.rootPath,ref.path),ref.getFullContext_(),true);ref.hasUnprocessedChanges_=false}}}getStoreList(){logger.logMethod?.("getStoreList");return this.rootDb__.values()}};0&&(module.exports={AlwatrNitrobase});
1
+ /** ๐Ÿ“ฆ @alwatr/nitrobase-engine v7.10.1 */
2
+ __dev_mode__: console.debug("๐Ÿ“ฆ @alwatr/nitrobase-engine v7.10.1");
3
+ "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var main_exports={};__export(main_exports,{AlwatrNitrobase:()=>AlwatrNitrobase});module.exports=__toCommonJS(main_exports);var import_delay=require("@alwatr/delay");var import_exit_hook=require("@alwatr/exit-hook");var import_nitrobase_helper=require("@alwatr/nitrobase-helper");var import_nitrobase_reference=require("@alwatr/nitrobase-reference");var import_nitrobase_types=require("@alwatr/nitrobase-types");var import_node_fs=require("@alwatr/node-fs");var import_logger=require("@alwatr/logger");var logger=(0,import_logger.createLogger)("@alwatr/nitrobase-engine");__dev_mode__:logger.logFileModule?.("alwatr-nitrobase");var AlwatrNitrobase=class _AlwatrNitrobase{constructor(config){this.config=config;this.cacheReferences__={};this.storeChanged_=this.storeChanged_.bind(this);logger.logMethodArgs?.("new",config);this.config.defaultChangeDebounce??=40;this.rootDb__=this.loadRootDb__();(0,import_exit_hook.exitHook)(this.exitHook__.bind(this))}static{this.version="7.10.1"}static{this.rootDbStat__={name:".nitrobase",region:import_nitrobase_types.Region.Secret,type:import_nitrobase_types.StoreFileType.Collection,extension:import_nitrobase_types.StoreFileExtension.Json,changeDebounce:40}}hasStore(storeId){const id_=(0,import_nitrobase_helper.getStoreId)(storeId);const exists=this.rootDb__.hasItem(id_);logger.logMethodFull?.("hasStore",id_,exists);return exists}newDocument(stat,data){logger.logMethodArgs?.("newDocument",stat);return this.newStoreFile__({...stat,type:import_nitrobase_types.StoreFileType.Document},data)}newCollection(stat){logger.logMethodArgs?.("newCollection",stat);return this.newStoreFile__({...stat,type:import_nitrobase_types.StoreFileType.Collection})}newStoreFile__(stat,data){logger.logMethodArgs?.("newStoreFile__",stat);stat.changeDebounce??=this.config.defaultChangeDebounce;let fileStoreRef;if(stat.type===import_nitrobase_types.StoreFileType.Document){if(data===void 0){logger.accident("newStoreFile__","document_data_required",stat);throw new Error("document_data_required",{cause:stat})}fileStoreRef=import_nitrobase_reference.DocumentReference.newRefFromData(stat,data,this.storeChanged_)}else if(stat.type===import_nitrobase_types.StoreFileType.Collection){fileStoreRef=import_nitrobase_reference.CollectionReference.newRefFromData(stat,this.storeChanged_)}else{logger.accident("newStoreFile__","store_file_type_not_supported",stat);throw new Error("store_file_type_not_supported",{cause:stat})}if(this.rootDb__.hasItem(fileStoreRef.id)){logger.accident("newStoreFile__","store_file_already_defined",stat);throw new Error("store_file_already_defined",{cause:stat})}this.rootDb__.addItem(fileStoreRef.id,stat);this.cacheReferences__[fileStoreRef.id]=fileStoreRef;this.storeChanged_(fileStoreRef)}async openDocument(documentId){const id=(0,import_nitrobase_helper.getStoreId)(documentId);logger.logMethodArgs?.("openDocument",id);if(Object.hasOwn(this.cacheReferences__,id)){const ref=this.cacheReferences__[id];if(!(ref instanceof import_nitrobase_reference.DocumentReference)){logger.accident("openDocument","document_wrong_type",id);throw new Error("document_wrong_type",{cause:id})}return this.cacheReferences__[id]}if(!this.rootDb__.hasItem(id)){logger.accident("openDocument","document_not_found",id);throw new Error("document_not_found",{cause:id})}const storeStat=this.rootDb__.getItemData(id);if(storeStat.type!=import_nitrobase_types.StoreFileType.Document){logger.accident("openDocument","document_wrong_type",id);throw new Error("document_wrong_type",{cause:id})}const context=await this.readContext__(storeStat);const docRef=import_nitrobase_reference.DocumentReference.newRefFromContext(context,this.storeChanged_);this.cacheReferences__[id]=docRef;return docRef}async openCollection(collectionId){const id=(0,import_nitrobase_helper.getStoreId)(collectionId);logger.logMethodArgs?.("openCollection",id);if(Object.hasOwn(this.cacheReferences__,id)){const ref=this.cacheReferences__[id];if(!(ref instanceof import_nitrobase_reference.CollectionReference)){logger.accident("openCollection","collection_wrong_type",id);throw new Error("collection_wrong_type",{cause:id})}return this.cacheReferences__[id]}if(!this.rootDb__.hasItem(id)){logger.accident("openCollection","collection_not_found",id);throw new Error("collection_not_found",{cause:id})}const storeStat=this.rootDb__.getItemData(id);if(storeStat.type!=import_nitrobase_types.StoreFileType.Collection){logger.accident("openCollection","collection_wrong_type",id);throw new Error("collection_not_found",{cause:id})}const context=await this.readContext__(storeStat);const colRef=import_nitrobase_reference.CollectionReference.newRefFromContext(context,this.storeChanged_);this.cacheReferences__[id]=colRef;return colRef}unloadStore(storeId){const id_=(0,import_nitrobase_helper.getStoreId)(storeId);logger.logMethodArgs?.("unloadStore",id_);const ref=this.cacheReferences__[id_];if(ref===void 0)return;if(ref.hasUnprocessedChanges_===true){ref.updateDelayed_=false;this.storeChanged_(ref)}delete this.cacheReferences__[id_]}async removeStore(storeId){const id_=(0,import_nitrobase_helper.getStoreId)(storeId);logger.logMethodArgs?.("removeStore",id_);if(!this.rootDb__.hasItem(id_)){logger.accident("removeStore","document_not_found",id_);throw new Error("document_not_found",{cause:id_})}const ref=this.cacheReferences__[id_];if(ref!==void 0){ref.freeze=true;ref.updateDelayed_=false;ref.hasUnprocessedChanges_=false;delete this.cacheReferences__[id_]}const path=(0,import_nitrobase_helper.getStorePath)(this.rootDb__.getItemData(id_));this.rootDb__.removeItem(id_);await import_delay.delay.by(0);try{await(0,import_node_fs.unlink)((0,import_node_fs.resolve)(this.config.rootPath,path))}catch(error){logger.error("removeStore","remove_file_failed",error,{id:storeId,path})}}async saveAll(){logger.logMethod?.("saveAll");for(const ref of Object.values(this.cacheReferences__)){if(ref.hasUnprocessedChanges_===true&&ref.freeze!==true){ref.updateDelayed_=false;await this.storeChanged_(ref)}}}async readContext__(path){if(typeof path!=="string")path=(0,import_nitrobase_helper.getStorePath)(path);logger.logMethodArgs?.("readContext__",path);logger.time?.(`readContext__time(${path})`);const context=await(0,import_node_fs.readJson)((0,import_node_fs.resolve)(this.config.rootPath,path));logger.timeEnd?.(`readContext__time(${path})`);return context}writeContext__(path,context){if(typeof path!=="string")path=(0,import_nitrobase_helper.getStorePath)(path);logger.logMethodArgs?.("writeContext__",path);return(0,import_node_fs.writeJson)((0,import_node_fs.resolve)(this.config.rootPath,path),context)}async storeChanged_(from){logger.logMethodArgs?.("storeChanged__",from.id);const rev=from.getStoreMeta().rev;try{await this.writeContext__(from.path,from.getFullContext_());if(rev===from.getStoreMeta().rev){from.hasUnprocessedChanges_=false}}catch(error){logger.error("storeChanged__","write_context_failed",{id:from.id,error})}}loadRootDb__(){logger.logMethod?.("loadRootDb__");const fullPath=(0,import_node_fs.resolve)(this.config.rootPath,(0,import_nitrobase_helper.getStorePath)(_AlwatrNitrobase.rootDbStat__));if(!(0,import_node_fs.existsSync)(fullPath)){if(this.config.errorWhenNotInitialized===true){throw new Error("store_not_found",{cause:"Nitrobase not initialized"})}logger.banner("Initialize new alwatr-nitrobase");return import_nitrobase_reference.CollectionReference.newRefFromData(_AlwatrNitrobase.rootDbStat__,this.storeChanged_)}const context=(0,import_node_fs.readJson)(fullPath,true);return import_nitrobase_reference.CollectionReference.newRefFromContext(context,this.storeChanged_,"root-db")}exitHook__(){logger.logMethod?.("exitHook__");for(const ref of Object.values(this.cacheReferences__)){logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`,ref.hasUnprocessedChanges_);if(ref.hasUnprocessedChanges_===true&&ref.freeze!==true){logger.incident?.("exitHook__","rescue_unsaved_context",{id:ref.id});(0,import_node_fs.writeJson)((0,import_node_fs.resolve)(this.config.rootPath,ref.path),ref.getFullContext_(),true);ref.hasUnprocessedChanges_=false}}}getStoreList(){logger.logMethod?.("getStoreList");return this.rootDb__.values()}};0&&(module.exports={AlwatrNitrobase});
4
4
  //# sourceMappingURL=main.cjs.map
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/delay';\nimport {exitHook} from '@alwatr/exit-hook';\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';\nimport {existsSync, readJson, resolve, unlink, writeJson} from '@alwatr/node-fs';\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 public 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(public readonly config: AlwatrNitrobaseConfig) {\n this.storeChanged_ = this.storeChanged_.bind(this);\n\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 public 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 data 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 public newDocument<TDoc extends JsonObject = JsonObject>(stat: Omit<StoreFileStat, 'type'>, data: TDoc): void {\n logger.logMethodArgs?.('newDocument', stat);\n return this.newStoreFile__(\n {\n ...stat,\n type: StoreFileType.Document,\n },\n data,\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 * @example\n * ```typescript\n * await alwatrStore.newCollection<Order>(\n * {\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * }\n * );\n * ```\n */\n public newCollection(stat: Omit<StoreFileStat, 'type'>): void {\n logger.logMethodArgs?.('newCollection', stat);\n return this.newStoreFile__({\n ...stat,\n type: StoreFileType.Collection,\n });\n }\n\n /**\n * Defines a AlwatrNitrobaseFile with the given configuration and initial data.\n *\n * @param stat nitrobase file stat\n * @param data initial data for the document\n */\n private newStoreFile__(stat: StoreFileStat, data?: DictionaryOpt): 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 if (data === undefined) {\n logger.accident('newStoreFile__', 'document_data_required', stat);\n throw new Error('document_data_required', {cause: stat});\n }\n fileStoreRef = DocumentReference.newRefFromData(stat, data, this.storeChanged_);\n }\n else if (stat.type === StoreFileType.Collection) {\n fileStoreRef = CollectionReference.newRefFromData(stat, this.storeChanged_);\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 public 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_);\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 public 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_);\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 public 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 public 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 public 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__, this.storeChanged_);\n }\n // else\n const context = readJson<CollectionContext<StoreFileStat>>(fullPath, true);\n return CollectionReference.newRefFromContext(context, this.storeChanged_, '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 public getStoreList(): CollectionItem<Omit<StoreFileStat, 'schemaVer'>>[] {\n logger.logMethod?.('getStoreList');\n return this.rootDb__.values();\n }\n}\n", "import {createLogger} from '@alwatr/logger';\n\nimport type {} from '@alwatr/nano-build';\nimport type {} from '@alwatr/type-helper';\n\nexport const logger = /* #__PURE__ */ createLogger(__package_name__);\n"],
4
+ "sourcesContent": ["export * from './alwatr-nitrobase.js';\n", "import {delay} from '@alwatr/delay';\nimport {exitHook} from '@alwatr/exit-hook';\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';\nimport {existsSync, readJson, resolve, unlink, writeJson} from '@alwatr/node-fs';\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 public 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(public readonly config: AlwatrNitrobaseConfig) {\n this.storeChanged_ = this.storeChanged_.bind(this);\n\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 public 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 data 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 public newDocument<TDoc extends JsonObject = JsonObject>(stat: Omit<StoreFileStat, 'type'>, data: TDoc): void {\n logger.logMethodArgs?.('newDocument', stat);\n return this.newStoreFile__(\n {\n ...stat,\n type: StoreFileType.Document,\n },\n data,\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 * @example\n * ```typescript\n * await alwatrStore.newCollection<Order>(\n * {\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * }\n * );\n * ```\n */\n public newCollection(stat: Omit<StoreFileStat, 'type'>): void {\n logger.logMethodArgs?.('newCollection', stat);\n return this.newStoreFile__({\n ...stat,\n type: StoreFileType.Collection,\n });\n }\n\n /**\n * Defines a AlwatrNitrobaseFile with the given configuration and initial data.\n *\n * @param stat nitrobase file stat\n * @param data initial data for the document\n */\n private newStoreFile__(stat: StoreFileStat, data?: DictionaryOpt): 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 if (data === undefined) {\n logger.accident('newStoreFile__', 'document_data_required', stat);\n throw new Error('document_data_required', {cause: stat});\n }\n fileStoreRef = DocumentReference.newRefFromData(stat, data, this.storeChanged_);\n }\n else if (stat.type === StoreFileType.Collection) {\n fileStoreRef = CollectionReference.newRefFromData(stat, this.storeChanged_);\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 public 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_);\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 public 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_);\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 public 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 public 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 public 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__, this.storeChanged_);\n }\n // else\n const context = readJson<CollectionContext<StoreFileStat>>(fullPath, true);\n return CollectionReference.newRefFromContext(context, this.storeChanged_, '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 public getStoreList(): CollectionItem<Omit<StoreFileStat, 'schemaVer'>>[] {\n logger.logMethod?.('getStoreList');\n return this.rootDb__.values();\n }\n}\n", "import {createLogger} from '@alwatr/logger';\n\nimport type {} from '@alwatr/nanolib';\nimport type {} from '@alwatr/type-helper';\n\nexport const logger = /* #__PURE__ */ createLogger(__package_name__);\n"],
5
5
  "mappings": ";;qqBAAA,2HCAA,iBAAoB,yBACpB,qBAAuB,6BACvB,4BAAuC,oCACvC,+BAAqD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AAI,EAAG,IAAI,gBAAgB,EAAG,IAAI,EAC9E,IAAI,uBAAyB,KAC/B,CACF,CACF,CAaO,cAAmE,CACxE,OAAO,YAAY,cAAc,EACjC,OAAO,KAAK,SAAS,OAAO,CAC9B,CACF",
6
6
  "names": []
7
7
  }
package/dist/main.mjs CHANGED
@@ -1,4 +1,4 @@
1
- /** ๐Ÿ“ฆ @alwatr/nitrobase-engine v7.10.0 */
2
- __dev_mode__: console.debug("๐Ÿ“ฆ @alwatr/nitrobase-engine v7.10.0");
3
- import{delay}from"@alwatr/delay";import{exitHook}from"@alwatr/exit-hook";import{getStoreId,getStorePath}from"@alwatr/nitrobase-helper";import{CollectionReference,DocumentReference}from"@alwatr/nitrobase-reference";import{StoreFileType,StoreFileExtension,Region}from"@alwatr/nitrobase-types";import{existsSync,readJson,resolve,unlink,writeJson}from"@alwatr/node-fs";import{createLogger}from"@alwatr/logger";var logger=createLogger("@alwatr/nitrobase-engine");__dev_mode__:logger.logFileModule?.("alwatr-nitrobase");var AlwatrNitrobase=class _AlwatrNitrobase{constructor(config){this.config=config;this.cacheReferences__={};this.storeChanged_=this.storeChanged_.bind(this);logger.logMethodArgs?.("new",config);this.config.defaultChangeDebounce??=40;this.rootDb__=this.loadRootDb__();exitHook(this.exitHook__.bind(this))}static{this.version="7.10.0"}static{this.rootDbStat__={name:".nitrobase",region:Region.Secret,type:StoreFileType.Collection,extension:StoreFileExtension.Json,changeDebounce:40}}hasStore(storeId){const id_=getStoreId(storeId);const exists=this.rootDb__.hasItem(id_);logger.logMethodFull?.("hasStore",id_,exists);return exists}newDocument(stat,data){logger.logMethodArgs?.("newDocument",stat);return this.newStoreFile__({...stat,type:StoreFileType.Document},data)}newCollection(stat){logger.logMethodArgs?.("newCollection",stat);return this.newStoreFile__({...stat,type:StoreFileType.Collection})}newStoreFile__(stat,data){logger.logMethodArgs?.("newStoreFile__",stat);stat.changeDebounce??=this.config.defaultChangeDebounce;let fileStoreRef;if(stat.type===StoreFileType.Document){if(data===void 0){logger.accident("newStoreFile__","document_data_required",stat);throw new Error("document_data_required",{cause:stat})}fileStoreRef=DocumentReference.newRefFromData(stat,data,this.storeChanged_)}else if(stat.type===StoreFileType.Collection){fileStoreRef=CollectionReference.newRefFromData(stat,this.storeChanged_)}else{logger.accident("newStoreFile__","store_file_type_not_supported",stat);throw new Error("store_file_type_not_supported",{cause:stat})}if(this.rootDb__.hasItem(fileStoreRef.id)){logger.accident("newStoreFile__","store_file_already_defined",stat);throw new Error("store_file_already_defined",{cause:stat})}this.rootDb__.addItem(fileStoreRef.id,stat);this.cacheReferences__[fileStoreRef.id]=fileStoreRef;this.storeChanged_(fileStoreRef)}async openDocument(documentId){const id=getStoreId(documentId);logger.logMethodArgs?.("openDocument",id);if(Object.hasOwn(this.cacheReferences__,id)){const ref=this.cacheReferences__[id];if(!(ref instanceof DocumentReference)){logger.accident("openDocument","document_wrong_type",id);throw new Error("document_wrong_type",{cause:id})}return this.cacheReferences__[id]}if(!this.rootDb__.hasItem(id)){logger.accident("openDocument","document_not_found",id);throw new Error("document_not_found",{cause:id})}const storeStat=this.rootDb__.getItemData(id);if(storeStat.type!=StoreFileType.Document){logger.accident("openDocument","document_wrong_type",id);throw new Error("document_wrong_type",{cause:id})}const context=await this.readContext__(storeStat);const docRef=DocumentReference.newRefFromContext(context,this.storeChanged_);this.cacheReferences__[id]=docRef;return docRef}async openCollection(collectionId){const id=getStoreId(collectionId);logger.logMethodArgs?.("openCollection",id);if(Object.hasOwn(this.cacheReferences__,id)){const ref=this.cacheReferences__[id];if(!(ref instanceof CollectionReference)){logger.accident("openCollection","collection_wrong_type",id);throw new Error("collection_wrong_type",{cause:id})}return this.cacheReferences__[id]}if(!this.rootDb__.hasItem(id)){logger.accident("openCollection","collection_not_found",id);throw new Error("collection_not_found",{cause:id})}const storeStat=this.rootDb__.getItemData(id);if(storeStat.type!=StoreFileType.Collection){logger.accident("openCollection","collection_wrong_type",id);throw new Error("collection_not_found",{cause:id})}const context=await this.readContext__(storeStat);const colRef=CollectionReference.newRefFromContext(context,this.storeChanged_);this.cacheReferences__[id]=colRef;return colRef}unloadStore(storeId){const id_=getStoreId(storeId);logger.logMethodArgs?.("unloadStore",id_);const ref=this.cacheReferences__[id_];if(ref===void 0)return;if(ref.hasUnprocessedChanges_===true){ref.updateDelayed_=false;this.storeChanged_(ref)}delete this.cacheReferences__[id_]}async removeStore(storeId){const id_=getStoreId(storeId);logger.logMethodArgs?.("removeStore",id_);if(!this.rootDb__.hasItem(id_)){logger.accident("removeStore","document_not_found",id_);throw new Error("document_not_found",{cause:id_})}const ref=this.cacheReferences__[id_];if(ref!==void 0){ref.freeze=true;ref.updateDelayed_=false;ref.hasUnprocessedChanges_=false;delete this.cacheReferences__[id_]}const path=getStorePath(this.rootDb__.getItemData(id_));this.rootDb__.removeItem(id_);await delay.by(0);try{await unlink(resolve(this.config.rootPath,path))}catch(error){logger.error("removeStore","remove_file_failed",error,{id:storeId,path})}}async saveAll(){logger.logMethod?.("saveAll");for(const ref of Object.values(this.cacheReferences__)){if(ref.hasUnprocessedChanges_===true&&ref.freeze!==true){ref.updateDelayed_=false;await this.storeChanged_(ref)}}}async readContext__(path){if(typeof path!=="string")path=getStorePath(path);logger.logMethodArgs?.("readContext__",path);logger.time?.(`readContext__time(${path})`);const context=await readJson(resolve(this.config.rootPath,path));logger.timeEnd?.(`readContext__time(${path})`);return context}writeContext__(path,context){if(typeof path!=="string")path=getStorePath(path);logger.logMethodArgs?.("writeContext__",path);return writeJson(resolve(this.config.rootPath,path),context)}async storeChanged_(from){logger.logMethodArgs?.("storeChanged__",from.id);const rev=from.getStoreMeta().rev;try{await this.writeContext__(from.path,from.getFullContext_());if(rev===from.getStoreMeta().rev){from.hasUnprocessedChanges_=false}}catch(error){logger.error("storeChanged__","write_context_failed",{id:from.id,error})}}loadRootDb__(){logger.logMethod?.("loadRootDb__");const fullPath=resolve(this.config.rootPath,getStorePath(_AlwatrNitrobase.rootDbStat__));if(!existsSync(fullPath)){if(this.config.errorWhenNotInitialized===true){throw new Error("store_not_found",{cause:"Nitrobase not initialized"})}logger.banner("Initialize new alwatr-nitrobase");return CollectionReference.newRefFromData(_AlwatrNitrobase.rootDbStat__,this.storeChanged_)}const context=readJson(fullPath,true);return CollectionReference.newRefFromContext(context,this.storeChanged_,"root-db")}exitHook__(){logger.logMethod?.("exitHook__");for(const ref of Object.values(this.cacheReferences__)){logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`,ref.hasUnprocessedChanges_);if(ref.hasUnprocessedChanges_===true&&ref.freeze!==true){logger.incident?.("exitHook__","rescue_unsaved_context",{id:ref.id});writeJson(resolve(this.config.rootPath,ref.path),ref.getFullContext_(),true);ref.hasUnprocessedChanges_=false}}}getStoreList(){logger.logMethod?.("getStoreList");return this.rootDb__.values()}};export{AlwatrNitrobase};
1
+ /** ๐Ÿ“ฆ @alwatr/nitrobase-engine v7.10.1 */
2
+ __dev_mode__: console.debug("๐Ÿ“ฆ @alwatr/nitrobase-engine v7.10.1");
3
+ import{delay}from"@alwatr/delay";import{exitHook}from"@alwatr/exit-hook";import{getStoreId,getStorePath}from"@alwatr/nitrobase-helper";import{CollectionReference,DocumentReference}from"@alwatr/nitrobase-reference";import{StoreFileType,StoreFileExtension,Region}from"@alwatr/nitrobase-types";import{existsSync,readJson,resolve,unlink,writeJson}from"@alwatr/node-fs";import{createLogger}from"@alwatr/logger";var logger=createLogger("@alwatr/nitrobase-engine");__dev_mode__:logger.logFileModule?.("alwatr-nitrobase");var AlwatrNitrobase=class _AlwatrNitrobase{constructor(config){this.config=config;this.cacheReferences__={};this.storeChanged_=this.storeChanged_.bind(this);logger.logMethodArgs?.("new",config);this.config.defaultChangeDebounce??=40;this.rootDb__=this.loadRootDb__();exitHook(this.exitHook__.bind(this))}static{this.version="7.10.1"}static{this.rootDbStat__={name:".nitrobase",region:Region.Secret,type:StoreFileType.Collection,extension:StoreFileExtension.Json,changeDebounce:40}}hasStore(storeId){const id_=getStoreId(storeId);const exists=this.rootDb__.hasItem(id_);logger.logMethodFull?.("hasStore",id_,exists);return exists}newDocument(stat,data){logger.logMethodArgs?.("newDocument",stat);return this.newStoreFile__({...stat,type:StoreFileType.Document},data)}newCollection(stat){logger.logMethodArgs?.("newCollection",stat);return this.newStoreFile__({...stat,type:StoreFileType.Collection})}newStoreFile__(stat,data){logger.logMethodArgs?.("newStoreFile__",stat);stat.changeDebounce??=this.config.defaultChangeDebounce;let fileStoreRef;if(stat.type===StoreFileType.Document){if(data===void 0){logger.accident("newStoreFile__","document_data_required",stat);throw new Error("document_data_required",{cause:stat})}fileStoreRef=DocumentReference.newRefFromData(stat,data,this.storeChanged_)}else if(stat.type===StoreFileType.Collection){fileStoreRef=CollectionReference.newRefFromData(stat,this.storeChanged_)}else{logger.accident("newStoreFile__","store_file_type_not_supported",stat);throw new Error("store_file_type_not_supported",{cause:stat})}if(this.rootDb__.hasItem(fileStoreRef.id)){logger.accident("newStoreFile__","store_file_already_defined",stat);throw new Error("store_file_already_defined",{cause:stat})}this.rootDb__.addItem(fileStoreRef.id,stat);this.cacheReferences__[fileStoreRef.id]=fileStoreRef;this.storeChanged_(fileStoreRef)}async openDocument(documentId){const id=getStoreId(documentId);logger.logMethodArgs?.("openDocument",id);if(Object.hasOwn(this.cacheReferences__,id)){const ref=this.cacheReferences__[id];if(!(ref instanceof DocumentReference)){logger.accident("openDocument","document_wrong_type",id);throw new Error("document_wrong_type",{cause:id})}return this.cacheReferences__[id]}if(!this.rootDb__.hasItem(id)){logger.accident("openDocument","document_not_found",id);throw new Error("document_not_found",{cause:id})}const storeStat=this.rootDb__.getItemData(id);if(storeStat.type!=StoreFileType.Document){logger.accident("openDocument","document_wrong_type",id);throw new Error("document_wrong_type",{cause:id})}const context=await this.readContext__(storeStat);const docRef=DocumentReference.newRefFromContext(context,this.storeChanged_);this.cacheReferences__[id]=docRef;return docRef}async openCollection(collectionId){const id=getStoreId(collectionId);logger.logMethodArgs?.("openCollection",id);if(Object.hasOwn(this.cacheReferences__,id)){const ref=this.cacheReferences__[id];if(!(ref instanceof CollectionReference)){logger.accident("openCollection","collection_wrong_type",id);throw new Error("collection_wrong_type",{cause:id})}return this.cacheReferences__[id]}if(!this.rootDb__.hasItem(id)){logger.accident("openCollection","collection_not_found",id);throw new Error("collection_not_found",{cause:id})}const storeStat=this.rootDb__.getItemData(id);if(storeStat.type!=StoreFileType.Collection){logger.accident("openCollection","collection_wrong_type",id);throw new Error("collection_not_found",{cause:id})}const context=await this.readContext__(storeStat);const colRef=CollectionReference.newRefFromContext(context,this.storeChanged_);this.cacheReferences__[id]=colRef;return colRef}unloadStore(storeId){const id_=getStoreId(storeId);logger.logMethodArgs?.("unloadStore",id_);const ref=this.cacheReferences__[id_];if(ref===void 0)return;if(ref.hasUnprocessedChanges_===true){ref.updateDelayed_=false;this.storeChanged_(ref)}delete this.cacheReferences__[id_]}async removeStore(storeId){const id_=getStoreId(storeId);logger.logMethodArgs?.("removeStore",id_);if(!this.rootDb__.hasItem(id_)){logger.accident("removeStore","document_not_found",id_);throw new Error("document_not_found",{cause:id_})}const ref=this.cacheReferences__[id_];if(ref!==void 0){ref.freeze=true;ref.updateDelayed_=false;ref.hasUnprocessedChanges_=false;delete this.cacheReferences__[id_]}const path=getStorePath(this.rootDb__.getItemData(id_));this.rootDb__.removeItem(id_);await delay.by(0);try{await unlink(resolve(this.config.rootPath,path))}catch(error){logger.error("removeStore","remove_file_failed",error,{id:storeId,path})}}async saveAll(){logger.logMethod?.("saveAll");for(const ref of Object.values(this.cacheReferences__)){if(ref.hasUnprocessedChanges_===true&&ref.freeze!==true){ref.updateDelayed_=false;await this.storeChanged_(ref)}}}async readContext__(path){if(typeof path!=="string")path=getStorePath(path);logger.logMethodArgs?.("readContext__",path);logger.time?.(`readContext__time(${path})`);const context=await readJson(resolve(this.config.rootPath,path));logger.timeEnd?.(`readContext__time(${path})`);return context}writeContext__(path,context){if(typeof path!=="string")path=getStorePath(path);logger.logMethodArgs?.("writeContext__",path);return writeJson(resolve(this.config.rootPath,path),context)}async storeChanged_(from){logger.logMethodArgs?.("storeChanged__",from.id);const rev=from.getStoreMeta().rev;try{await this.writeContext__(from.path,from.getFullContext_());if(rev===from.getStoreMeta().rev){from.hasUnprocessedChanges_=false}}catch(error){logger.error("storeChanged__","write_context_failed",{id:from.id,error})}}loadRootDb__(){logger.logMethod?.("loadRootDb__");const fullPath=resolve(this.config.rootPath,getStorePath(_AlwatrNitrobase.rootDbStat__));if(!existsSync(fullPath)){if(this.config.errorWhenNotInitialized===true){throw new Error("store_not_found",{cause:"Nitrobase not initialized"})}logger.banner("Initialize new alwatr-nitrobase");return CollectionReference.newRefFromData(_AlwatrNitrobase.rootDbStat__,this.storeChanged_)}const context=readJson(fullPath,true);return CollectionReference.newRefFromContext(context,this.storeChanged_,"root-db")}exitHook__(){logger.logMethod?.("exitHook__");for(const ref of Object.values(this.cacheReferences__)){logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`,ref.hasUnprocessedChanges_);if(ref.hasUnprocessedChanges_===true&&ref.freeze!==true){logger.incident?.("exitHook__","rescue_unsaved_context",{id:ref.id});writeJson(resolve(this.config.rootPath,ref.path),ref.getFullContext_(),true);ref.hasUnprocessedChanges_=false}}}getStoreList(){logger.logMethod?.("getStoreList");return this.rootDb__.values()}};export{AlwatrNitrobase};
4
4
  //# sourceMappingURL=main.mjs.map
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/delay';\nimport {exitHook} from '@alwatr/exit-hook';\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';\nimport {existsSync, readJson, resolve, unlink, writeJson} from '@alwatr/node-fs';\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 public 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(public readonly config: AlwatrNitrobaseConfig) {\n this.storeChanged_ = this.storeChanged_.bind(this);\n\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 public 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 data 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 public newDocument<TDoc extends JsonObject = JsonObject>(stat: Omit<StoreFileStat, 'type'>, data: TDoc): void {\n logger.logMethodArgs?.('newDocument', stat);\n return this.newStoreFile__(\n {\n ...stat,\n type: StoreFileType.Document,\n },\n data,\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 * @example\n * ```typescript\n * await alwatrStore.newCollection<Order>(\n * {\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * }\n * );\n * ```\n */\n public newCollection(stat: Omit<StoreFileStat, 'type'>): void {\n logger.logMethodArgs?.('newCollection', stat);\n return this.newStoreFile__({\n ...stat,\n type: StoreFileType.Collection,\n });\n }\n\n /**\n * Defines a AlwatrNitrobaseFile with the given configuration and initial data.\n *\n * @param stat nitrobase file stat\n * @param data initial data for the document\n */\n private newStoreFile__(stat: StoreFileStat, data?: DictionaryOpt): 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 if (data === undefined) {\n logger.accident('newStoreFile__', 'document_data_required', stat);\n throw new Error('document_data_required', {cause: stat});\n }\n fileStoreRef = DocumentReference.newRefFromData(stat, data, this.storeChanged_);\n }\n else if (stat.type === StoreFileType.Collection) {\n fileStoreRef = CollectionReference.newRefFromData(stat, this.storeChanged_);\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 public 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_);\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 public 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_);\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 public 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 public 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 public 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__, this.storeChanged_);\n }\n // else\n const context = readJson<CollectionContext<StoreFileStat>>(fullPath, true);\n return CollectionReference.newRefFromContext(context, this.storeChanged_, '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 public getStoreList(): CollectionItem<Omit<StoreFileStat, 'schemaVer'>>[] {\n logger.logMethod?.('getStoreList');\n return this.rootDb__.values();\n }\n}\n", "import {createLogger} from '@alwatr/logger';\n\nimport type {} from '@alwatr/nano-build';\nimport type {} from '@alwatr/type-helper';\n\nexport const logger = /* #__PURE__ */ createLogger(__package_name__);\n"],
4
+ "sourcesContent": ["import {delay} from '@alwatr/delay';\nimport {exitHook} from '@alwatr/exit-hook';\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';\nimport {existsSync, readJson, resolve, unlink, writeJson} from '@alwatr/node-fs';\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 public 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(public readonly config: AlwatrNitrobaseConfig) {\n this.storeChanged_ = this.storeChanged_.bind(this);\n\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 public 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 data 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 public newDocument<TDoc extends JsonObject = JsonObject>(stat: Omit<StoreFileStat, 'type'>, data: TDoc): void {\n logger.logMethodArgs?.('newDocument', stat);\n return this.newStoreFile__(\n {\n ...stat,\n type: StoreFileType.Document,\n },\n data,\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 * @example\n * ```typescript\n * await alwatrStore.newCollection<Order>(\n * {\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * }\n * );\n * ```\n */\n public newCollection(stat: Omit<StoreFileStat, 'type'>): void {\n logger.logMethodArgs?.('newCollection', stat);\n return this.newStoreFile__({\n ...stat,\n type: StoreFileType.Collection,\n });\n }\n\n /**\n * Defines a AlwatrNitrobaseFile with the given configuration and initial data.\n *\n * @param stat nitrobase file stat\n * @param data initial data for the document\n */\n private newStoreFile__(stat: StoreFileStat, data?: DictionaryOpt): 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 if (data === undefined) {\n logger.accident('newStoreFile__', 'document_data_required', stat);\n throw new Error('document_data_required', {cause: stat});\n }\n fileStoreRef = DocumentReference.newRefFromData(stat, data, this.storeChanged_);\n }\n else if (stat.type === StoreFileType.Collection) {\n fileStoreRef = CollectionReference.newRefFromData(stat, this.storeChanged_);\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 public 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_);\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 public 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_);\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 public 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 public 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 public 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__, this.storeChanged_);\n }\n // else\n const context = readJson<CollectionContext<StoreFileStat>>(fullPath, true);\n return CollectionReference.newRefFromContext(context, this.storeChanged_, '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 public getStoreList(): CollectionItem<Omit<StoreFileStat, 'schemaVer'>>[] {\n logger.logMethod?.('getStoreList');\n return this.rootDb__.values();\n }\n}\n", "import {createLogger} from '@alwatr/logger';\n\nimport type {} from '@alwatr/nanolib';\nimport type {} from '@alwatr/type-helper';\n\nexport const logger = /* #__PURE__ */ createLogger(__package_name__);\n"],
5
5
  "mappings": ";;AAAA,OAAQ,UAAY,gBACpB,OAAQ,aAAe,oBACvB,OAAQ,WAAY,iBAAmB,2BACvC,OAAQ,oBAAqB,sBAAwB,8BACrD,OACE,cACA,mBACA,WAOK,0BACP,OAAQ,WAAY,SAAU,QAAS,OAAQ,cAAgB,kBCf/D,OAAQ,iBAAmB,iBAKpB,IAAM,OAAyB,aAAa,0BAAgB,EDcnE,aAAc,OAAO,gBAAgB,kBAAkB,EAgChD,IAAM,gBAAN,MAAM,gBAAgB,CA0C3B,YAA4B,OAA+B,CAA/B,mBAd5B,KAAQ,kBAA4E,CAAC,EAenF,KAAK,cAAgB,KAAK,cA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weight 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.",
4
- "version": "7.10.0",
4
+ "version": "7.10.1",
5
5
  "author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
6
6
  "bugs": "https://github.com/Alwatr/nitrobase/issues",
7
7
  "dependencies": {
8
- "@alwatr/delay": "^6.0.8",
9
- "@alwatr/exit-hook": "^5.5.16",
10
- "@alwatr/logger": "^6.0.5",
11
- "@alwatr/nitrobase-helper": "^7.10.0",
12
- "@alwatr/nitrobase-reference": "^7.10.0",
13
- "@alwatr/nitrobase-types": "^7.10.0",
14
- "@alwatr/node-fs": "^5.5.19"
8
+ "@alwatr/delay": "^6.0.18",
9
+ "@alwatr/exit-hook": "^5.5.26",
10
+ "@alwatr/logger": "^6.0.15",
11
+ "@alwatr/nitrobase-helper": "^7.10.1",
12
+ "@alwatr/nitrobase-reference": "^7.10.1",
13
+ "@alwatr/nitrobase-types": "^7.10.1",
14
+ "@alwatr/node-fs": "^5.5.29",
15
+ "@alwatr/type-helper": "^7.0.0"
15
16
  },
16
17
  "devDependencies": {
17
- "@alwatr/nano-build": "^6.3.1",
18
- "@alwatr/prettier-config": "^5.0.4",
19
- "@alwatr/tsconfig-base": "^6.0.2",
20
- "@alwatr/type-helper": "^6.1.1",
21
- "@types/node": "^22.18.6",
22
- "typescript": "^5.9.2"
18
+ "@alwatr/nanolib": "^7.3.4",
19
+ "@types/node": "^24.10.4",
20
+ "typescript": "^5.9.3"
23
21
  },
24
22
  "exports": {
25
23
  ".": {
@@ -49,7 +47,7 @@
49
47
  "license": "MPL-2.0",
50
48
  "main": "./dist/main.cjs",
51
49
  "module": "./dist/main.mjs",
52
- "prettier": "@alwatr/prettier-config",
50
+ "prettier": "@alwatr/nanolib/prettier-config",
53
51
  "publishConfig": {
54
52
  "access": "public"
55
53
  },
@@ -75,5 +73,5 @@
75
73
  "sideEffects": false,
76
74
  "type": "module",
77
75
  "types": "./dist/main.d.ts",
78
- "gitHead": "4079c7884711b767ac812d14d4ec7eafe6e19081"
76
+ "gitHead": "e23943a279d6b0905b205c0c17b2b3249efab226"
79
77
  }