@alwatr/nitrobase-engine 7.8.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/README.md CHANGED
@@ -78,12 +78,6 @@ Explore the provided demo code (`collection.mjs`, `document.mjs`, `benchmark.mjs
78
78
 
79
79
  The following companies, organizations, and individuals support Nitrobase ongoing maintenance and development. Become a Sponsor to get your logo on our README and website.
80
80
 
81
- [![Exir Studio](https://avatars.githubusercontent.com/u/181194967?s=200&v=4)](https://exirstudio.com)
82
-
83
81
  ### Contributing
84
82
 
85
83
  Contributions are welcome! Please read our [contribution guidelines](https://github.com/Alwatr/.github/blob/next/CONTRIBUTING.md) before submitting a pull request.
86
-
87
- ### License
88
-
89
- This project is licensed under the [AGPL-3.0 License](LICENSE).
@@ -120,7 +120,7 @@ export declare class AlwatrNitrobase {
120
120
  * @param stat nitrobase file stat
121
121
  * @param data initial data for the document
122
122
  */
123
- newStoreFile_(stat: StoreFileStat, data?: DictionaryOpt): void;
123
+ private newStoreFile__;
124
124
  /**
125
125
  * Open a document with the given id and create and return a DocumentReference.
126
126
  * If the document not exists or its not a document, an error is thrown.
@@ -1 +1 @@
1
- {"version":3,"file":"alwatr-nitrobase.d.ts","sourceRoot":"","sources":["../src/alwatr-nitrobase.ts"],"names":[],"mappings":"AAIA,OAAO,EAAC,mBAAmB,EAAE,iBAAiB,EAAC,MAAM,6BAA6B,CAAC;AACnF,OAAO,EAIL,KAAK,aAAa,EAIlB,KAAK,WAAW,EAChB,KAAK,cAAc,EACpB,MAAM,yBAAyB,CAAC;AAMjC;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;;;OAIG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAE/B;;;OAGG;IACH,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACnC;AAED;;;;;GAKG;AACH,qBAAa,eAAe;IA0Cd,QAA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Y,IAAI,cAAc,CAAC,IAAI,CAAC,aAAa,EAAE,WAAW,CAAC,CAAC,EAAE;CAI1E"}
@@ -1 +1 @@
1
- {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,MAAM,uCAAiD,CAAC"}
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,MAAM,uCAAiD,CAAC"}
package/dist/main.cjs CHANGED
@@ -1,447 +1,4 @@
1
- /* @alwatr/nitrobase-engine v7.8.0 */
2
- "use strict";
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
-
21
- // src/main.ts
22
- var main_exports = {};
23
- __export(main_exports, {
24
- AlwatrNitrobase: () => AlwatrNitrobase
25
- });
26
- module.exports = __toCommonJS(main_exports);
27
-
28
- // src/alwatr-nitrobase.ts
29
- var import_nanolib2 = require("@alwatr/nanolib");
30
- var import_exit_hook = require("@alwatr/nanolib/exit-hook");
31
- var import_node_fs = require("@alwatr/nanolib/node-fs");
32
- var import_nitrobase_helper = require("@alwatr/nitrobase-helper");
33
- var import_nitrobase_reference = require("@alwatr/nitrobase-reference");
34
- var import_nitrobase_types = require("@alwatr/nitrobase-types");
35
-
36
- // src/logger.ts
37
- var import_nanolib = require("@alwatr/nanolib");
38
- __dev_mode__: import_nanolib.packageTracer.add("@alwatr/nitrobase-engine", "7.8.0");
39
- var logger = /* @__PURE__ */ (0, import_nanolib.createLogger)("@alwatr/nitrobase-engine");
40
-
41
- // src/alwatr-nitrobase.ts
42
- __dev_mode__: logger.logFileModule?.("alwatr-nitrobase");
43
- var _AlwatrNitrobase = class _AlwatrNitrobase {
44
- /**
45
- * Constructs an AlwatrNitrobase instance with the provided configuration.
46
- *
47
- * @param config The configuration of the AlwatrNitrobase engine.
48
- * @example
49
- * ```typescript
50
- * const alwatrStore = new AlwatrNitrobase({
51
- * rootPath: './db',
52
- * saveDebounce: 40,
53
- * });
54
- * ```
55
- */
56
- constructor(config) {
57
- this.config = config;
58
- /**
59
- * Keep all loaded nitrobase file context loaded in memory.
60
- */
61
- this.cacheReferences__ = {};
62
- var _a;
63
- this.storeChanged_ = this.storeChanged_.bind(this);
64
- logger.logMethodArgs?.("new", config);
65
- (_a = this.config).defaultChangeDebounce ?? (_a.defaultChangeDebounce = 40);
66
- this.rootDb__ = this.loadRootDb__();
67
- (0, import_exit_hook.exitHook)(this.exitHook__.bind(this));
68
- }
69
- /**
70
- * Checks if a nitrobase file with the given ID exists.
71
- *
72
- * @param storeId - The ID of the nitrobase file to check.
73
- * @returns `true` if the nitrobase file exists, `false` otherwise.
74
- * @example
75
- * ```typescript
76
- * if (!alwatrStore.hasStore('user1/profile')) {
77
- * alwatrStore.defineDocument(...)
78
- * }
79
- * ```
80
- */
81
- hasStore(storeId) {
82
- const id_ = (0, import_nitrobase_helper.getStoreId)(storeId);
83
- const exists = this.rootDb__.hasItem(id_);
84
- logger.logMethodFull?.("hasStore", id_, exists);
85
- return exists;
86
- }
87
- /**
88
- * Defines a new document with the given configuration and initial data.
89
- * If a document with the same ID already exists, an error is thrown.
90
- *
91
- * @param stat nitrobase file stat
92
- * @param data initial data for the document
93
- * @template TDoc document data type
94
- * @example
95
- * ```typescript
96
- * await alwatrStore.newDocument<Order>(
97
- * {
98
- * name: 'profile',
99
- * region: Region.PerUser,
100
- * ownerId: 'user1',
101
- * },
102
- * {
103
- * name: 'Ali',
104
- * email: 'ali@alwatr.io',
105
- * }
106
- * );
107
- * ```
108
- */
109
- newDocument(stat, data) {
110
- logger.logMethodArgs?.("newDocument", stat);
111
- return this.newStoreFile_(
112
- {
113
- ...stat,
114
- type: import_nitrobase_types.StoreFileType.Document
115
- },
116
- data
117
- );
118
- }
119
- /**
120
- * Defines a new collection with the given configuration and initial data.
121
- * If a collection with the same ID already exists, an error is thrown.
122
- *
123
- * @param stat nitrobase file stat
124
- * @example
125
- * ```typescript
126
- * await alwatrStore.newCollection<Order>(
127
- * {
128
- * name: 'orders',
129
- * region: Region.PerUser,
130
- * ownerId: 'user1',
131
- * }
132
- * );
133
- * ```
134
- */
135
- newCollection(stat) {
136
- logger.logMethodArgs?.("newCollection", stat);
137
- return this.newStoreFile_(
138
- {
139
- ...stat,
140
- type: import_nitrobase_types.StoreFileType.Collection
141
- }
142
- );
143
- }
144
- /**
145
- * Defines a AlwatrNitrobaseFile with the given configuration and initial data.
146
- *
147
- * @param stat nitrobase file stat
148
- * @param data initial data for the document
149
- */
150
- newStoreFile_(stat, data) {
151
- logger.logMethodArgs?.("newStoreFile_", stat);
152
- stat.changeDebounce ?? (stat.changeDebounce = this.config.defaultChangeDebounce);
153
- let fileStoreRef;
154
- if (stat.type === import_nitrobase_types.StoreFileType.Document) {
155
- if (data === void 0) {
156
- logger.accident("newStoreFile_", "document_data_required", stat);
157
- throw new Error("document_data_required", { cause: stat });
158
- }
159
- fileStoreRef = import_nitrobase_reference.DocumentReference.newRefFromData(stat, data, this.storeChanged_);
160
- } else if (stat.type === import_nitrobase_types.StoreFileType.Collection) {
161
- fileStoreRef = import_nitrobase_reference.CollectionReference.newRefFromData(stat, this.storeChanged_);
162
- } else {
163
- logger.accident("newStoreFile_", "store_file_type_not_supported", stat);
164
- throw new Error("store_file_type_not_supported", { cause: stat });
165
- }
166
- if (this.rootDb__.hasItem(fileStoreRef.id)) {
167
- logger.accident("newStoreFile_", "store_file_already_defined", stat);
168
- throw new Error("store_file_already_defined", { cause: stat });
169
- }
170
- this.rootDb__.addItem(fileStoreRef.id, stat);
171
- this.cacheReferences__[fileStoreRef.id] = fileStoreRef;
172
- this.storeChanged_(fileStoreRef);
173
- }
174
- /**
175
- * Open a document with the given id and create and return a DocumentReference.
176
- * If the document not exists or its not a document, an error is thrown.
177
- *
178
- * @template TDoc document data type
179
- * @param documentId document id {@link StoreFileId}
180
- * @returns document reference {@link DocumentReference}
181
- * @example
182
- * ```typescript
183
- * const userProfile = await alwatrStore.openDocument<User>({
184
- * name: 'user1/profile',
185
- * region: Region.PerUser,
186
- * ownerId: 'user1',
187
- * });
188
- * userProfile.update({name: 'ali'});
189
- * ```
190
- */
191
- async openDocument(documentId) {
192
- const id = (0, import_nitrobase_helper.getStoreId)(documentId);
193
- logger.logMethodArgs?.("openDocument", id);
194
- if (Object.hasOwn(this.cacheReferences__, id)) {
195
- const ref = this.cacheReferences__[id];
196
- if (!(ref instanceof import_nitrobase_reference.DocumentReference)) {
197
- logger.accident("openDocument", "document_wrong_type", id);
198
- throw new Error("document_wrong_type", { cause: id });
199
- }
200
- return this.cacheReferences__[id];
201
- }
202
- if (!this.rootDb__.hasItem(id)) {
203
- logger.accident("openDocument", "document_not_found", id);
204
- throw new Error("document_not_found", { cause: id });
205
- }
206
- const storeStat = this.rootDb__.getItemData(id);
207
- if (storeStat.type != import_nitrobase_types.StoreFileType.Document) {
208
- logger.accident("openDocument", "document_wrong_type", id);
209
- throw new Error("document_wrong_type", { cause: id });
210
- }
211
- const context = await this.readContext__(storeStat);
212
- const docRef = import_nitrobase_reference.DocumentReference.newRefFromContext(context, this.storeChanged_);
213
- this.cacheReferences__[id] = docRef;
214
- return docRef;
215
- }
216
- /**
217
- * Open a collection with the given id and create and return a CollectionReference.
218
- * If the collection not exists or its not a collection, an error is thrown.
219
- *
220
- * @template TItem collection item data type
221
- * @param collectionId collection id {@link StoreFileId}
222
- * @returns collection reference {@link CollectionReference}
223
- * @example
224
- * ```typescript
225
- * const orders = await alwatrStore.openCollection<Order>({
226
- * name: 'orders',
227
- * region: Region.PerUser,
228
- * ownerId: 'user1',
229
- * });
230
- * orders.append({name: 'order 1'});
231
- * ```
232
- */
233
- async openCollection(collectionId) {
234
- const id = (0, import_nitrobase_helper.getStoreId)(collectionId);
235
- logger.logMethodArgs?.("openCollection", id);
236
- if (Object.hasOwn(this.cacheReferences__, id)) {
237
- const ref = this.cacheReferences__[id];
238
- if (!(ref instanceof import_nitrobase_reference.CollectionReference)) {
239
- logger.accident("openCollection", "collection_wrong_type", id);
240
- throw new Error("collection_wrong_type", { cause: id });
241
- }
242
- return this.cacheReferences__[id];
243
- }
244
- if (!this.rootDb__.hasItem(id)) {
245
- logger.accident("openCollection", "collection_not_found", id);
246
- throw new Error("collection_not_found", { cause: id });
247
- }
248
- const storeStat = this.rootDb__.getItemData(id);
249
- if (storeStat.type != import_nitrobase_types.StoreFileType.Collection) {
250
- logger.accident("openCollection", "collection_wrong_type", id);
251
- throw new Error("collection_not_found", { cause: id });
252
- }
253
- const context = await this.readContext__(storeStat);
254
- const colRef = import_nitrobase_reference.CollectionReference.newRefFromContext(context, this.storeChanged_);
255
- this.cacheReferences__[id] = colRef;
256
- return colRef;
257
- }
258
- /**
259
- * Unloads the nitrobase file with the given id from memory.
260
- *
261
- * @param storeId The unique identifier of the nitrobase file. {@link StoreFileId}
262
- * @example
263
- * ```typescript
264
- * alwatrStore.unloadStore({name: 'user-list', region: Region.Secret});
265
- * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // true
266
- * ```
267
- */
268
- unloadStore(storeId) {
269
- const id_ = (0, import_nitrobase_helper.getStoreId)(storeId);
270
- logger.logMethodArgs?.("unloadStore", id_);
271
- const ref = this.cacheReferences__[id_];
272
- if (ref === void 0) return;
273
- if (ref.hasUnprocessedChanges_ === true) {
274
- ref.updateDelayed_ = false;
275
- this.storeChanged_(ref);
276
- }
277
- delete this.cacheReferences__[id_];
278
- }
279
- /**
280
- * Remove document or collection from nitrobase and delete the file from disk.
281
- * If the file is not found, an error is thrown.
282
- * If the file is not unloaded, it will be unloaded first.
283
- * You don't need to await this method to complete unless you want to make sure the file is deleted on disk.
284
- *
285
- * @param storeId The ID of the file to delete. {@link StoreFileId}
286
- * @returns A Promise that resolves when the file is deleted.
287
- * @example
288
- * ```typescript
289
- * alwatrStore.removeStore({name: 'user-list', region: Region.Secret});
290
- * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // false
291
- * ```
292
- */
293
- async removeStore(storeId) {
294
- const id_ = (0, import_nitrobase_helper.getStoreId)(storeId);
295
- logger.logMethodArgs?.("removeStore", id_);
296
- if (!this.rootDb__.hasItem(id_)) {
297
- logger.accident("removeStore", "document_not_found", id_);
298
- throw new Error("document_not_found", { cause: id_ });
299
- }
300
- const ref = this.cacheReferences__[id_];
301
- if (ref !== void 0) {
302
- ref.freeze = true;
303
- ref.updateDelayed_ = false;
304
- ref.hasUnprocessedChanges_ = false;
305
- delete this.cacheReferences__[id_];
306
- }
307
- const path = (0, import_nitrobase_helper.getStorePath)(this.rootDb__.getItemData(id_));
308
- this.rootDb__.removeItem(id_);
309
- await import_nanolib2.delay.by(0);
310
- try {
311
- await (0, import_node_fs.unlink)((0, import_node_fs.resolve)(this.config.rootPath, path));
312
- } catch (error) {
313
- logger.error("removeStore", "remove_file_failed", error, { id: storeId, path });
314
- }
315
- }
316
- /**
317
- * Saves all changes in the nitrobase.
318
- *
319
- * @returns A Promise that resolves when all changes are saved.
320
- * @example
321
- * ```typescript
322
- * await alwatrStore.saveAll();
323
- * ```
324
- */
325
- async saveAll() {
326
- logger.logMethod?.("saveAll");
327
- for (const ref of Object.values(this.cacheReferences__)) {
328
- if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {
329
- ref.updateDelayed_ = false;
330
- await this.storeChanged_(ref);
331
- }
332
- }
333
- }
334
- /**
335
- * Reads the context from a given path or StoreFileStat object.
336
- *
337
- * @param path The path or StoreFileStat object from which to read the context.
338
- * @returns A promise that resolves to the context object.
339
- */
340
- async readContext__(path) {
341
- if (typeof path !== "string") path = (0, import_nitrobase_helper.getStorePath)(path);
342
- logger.logMethodArgs?.("readContext__", path);
343
- logger.time?.(`readContext__time(${path})`);
344
- const context = await (0, import_node_fs.readJson)((0, import_node_fs.resolve)(this.config.rootPath, path));
345
- logger.timeEnd?.(`readContext__time(${path})`);
346
- return context;
347
- }
348
- /**
349
- * Writes the context to the specified path.
350
- *
351
- * @template T The type of the context.
352
- * @param path The path where the context will be written.
353
- * @param context The context to be written.
354
- * @param sync Indicates whether the write operation should be synchronous.
355
- * @returns A promise that resolves when the write operation is complete.
356
- */
357
- writeContext__(path, context) {
358
- if (typeof path !== "string") path = (0, import_nitrobase_helper.getStorePath)(path);
359
- logger.logMethodArgs?.("writeContext__", path);
360
- return (0, import_node_fs.writeJson)((0, import_node_fs.resolve)(this.config.rootPath, path), context);
361
- }
362
- /**
363
- * Write nitrobase file context.
364
- *
365
- * @param from nitrobase file reference
366
- * @returns A promise that resolves when the write operation is complete.
367
- */
368
- async storeChanged_(from) {
369
- logger.logMethodArgs?.("storeChanged__", from.id);
370
- const rev = from.getStoreMeta().rev;
371
- try {
372
- await this.writeContext__(from.path, from.getFullContext_());
373
- if (rev === from.getStoreMeta().rev) {
374
- from.hasUnprocessedChanges_ = false;
375
- }
376
- } catch (error) {
377
- logger.error("storeChanged__", "write_context_failed", { id: from.id, error });
378
- }
379
- }
380
- /**
381
- * Load storeFilesCollection or create new one.
382
- */
383
- loadRootDb__() {
384
- logger.logMethod?.("loadRootDb__");
385
- const fullPath = (0, import_node_fs.resolve)(this.config.rootPath, (0, import_nitrobase_helper.getStorePath)(_AlwatrNitrobase.rootDbStat__));
386
- if (!(0, import_node_fs.existsSync)(fullPath)) {
387
- if (this.config.errorWhenNotInitialized === true) {
388
- throw new Error("store_not_found", { cause: "Nitrobase not initialized" });
389
- }
390
- logger.banner("Initialize new alwatr-nitrobase");
391
- return import_nitrobase_reference.CollectionReference.newRefFromData(_AlwatrNitrobase.rootDbStat__, this.storeChanged_);
392
- }
393
- const context = (0, import_node_fs.readJson)(fullPath, true);
394
- return import_nitrobase_reference.CollectionReference.newRefFromContext(context, this.storeChanged_, "root-db");
395
- }
396
- /**
397
- * Save all nitrobase files.
398
- */
399
- exitHook__() {
400
- logger.logMethod?.("exitHook__");
401
- for (const ref of Object.values(this.cacheReferences__)) {
402
- logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`, ref.hasUnprocessedChanges_);
403
- if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {
404
- logger.incident?.("exitHook__", "rescue_unsaved_context", { id: ref.id });
405
- (0, import_node_fs.writeJson)((0, import_node_fs.resolve)(this.config.rootPath, ref.path), ref.getFullContext_(), true);
406
- ref.hasUnprocessedChanges_ = false;
407
- }
408
- }
409
- }
410
- /**
411
- * Get all nitrobase files.
412
- *
413
- * @returns all nitrobase files.
414
- * @example
415
- * ```typescript
416
- * const storeList = alwatrStore.getStoreList();
417
- * for (const nitrobase of storeList) {
418
- * console.log(nitrobase.meta.id, nitrobase.data);
419
- * }
420
- */
421
- getStoreList() {
422
- logger.logMethod?.("getStoreList");
423
- return this.rootDb__.values();
424
- }
425
- };
426
- /**
427
- * The Alwatr Nitrobase version string.
428
- *
429
- * Use for nitrobase file format version for check compatibility.
430
- */
431
- _AlwatrNitrobase.version = "7.8.0";
432
- /**
433
- * The root nitrobase file stat.
434
- */
435
- _AlwatrNitrobase.rootDbStat__ = {
436
- name: ".nitrobase",
437
- region: import_nitrobase_types.Region.Secret,
438
- type: import_nitrobase_types.StoreFileType.Collection,
439
- extension: import_nitrobase_types.StoreFileExtension.Json,
440
- changeDebounce: 40
441
- };
442
- var AlwatrNitrobase = _AlwatrNitrobase;
443
- // Annotate the CommonJS export names for ESM import in node:
444
- 0 && (module.exports = {
445
- AlwatrNitrobase
446
- });
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});
447
4
  //# sourceMappingURL=main.cjs.map