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using Terser v5.37.0.\n * Original file: /npm/memoz@4.2.0/build/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","(function (global, factory) {\n    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('fs'), require('path')) :\n    typeof define === 'function' && define.amd ? define(['exports', 'fs', 'path'], factory) :\n    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.memoz = {}, global.fs, global.path));\n})(this, (function (exports, fs, path) { 'use strict';\n\n    function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\n\n    var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);\n    var path__default = /*#__PURE__*/_interopDefaultLegacy(path);\n\n    /******************************************************************************\r\n    Copyright (c) Microsoft Corporation.\r\n\r\n    Permission to use, copy, modify, and/or distribute this software for any\r\n    purpose with or without fee is hereby granted.\r\n\r\n    THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\n    REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\n    AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\n    INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\n    LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\n    OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\n    PERFORMANCE OF THIS SOFTWARE.\r\n    ***************************************************************************** */\r\n\r\n    function __awaiter(thisArg, _arguments, P, generator) {\r\n        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n        return new (P || (P = Promise))(function (resolve, reject) {\r\n            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n            function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n            step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n        });\r\n    }\r\n\r\n    typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n        var e = new Error(message);\r\n        return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n    };\n\n    const MEMOZ_ID_PATTERN = /^[A-F\\d]{8}-[A-F\\d]{4}-4[A-F\\d]{3}-[89AB][A-F\\d]{3}-[A-F\\d]{12}-[A-Za-z0-9]{9}$/i;\n    const MEMOZ_ID_TEMPLATE = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';\n\n    /**\n     *\n     * @param {string} memozId - The MEMOZID string to be validated.\n     * @returns {boolean} `true` if the MEMOZID is valid; otherwise, `false`.\n     *\n     * @example\n     * console.log(isValidMemozId('123e4567-e89b-12d3-a456-426614174000')); // Output: true\n     * console.log(isValidMemozId('invalid-memozId')); // Output: false\n     */\n    const isValidMemozId = (memozId) => memozId.length >= 36 && MEMOZ_ID_PATTERN.test(memozId);\n\n    /**\n     * Generates a MEMOZID string based on a template and current timestamp.\n     *\n     * @returns {String}\n     */\n    function memozId() {\n        const generatedMemozId = MEMOZ_ID_TEMPLATE.replace(/[xy]/g, (char) => {\n            const random = Math.floor(Math.random() * 16); // Generate a random number between 0 and 15\n            const value = char === 'x' ? random : (random % 4) + 8; // For 'y', ensure the range is [8-11]\n            return value.toString(16);\n        });\n        // Append the current timestamp as a base-32 string\n        const timestamp = Date.now().toString(32);\n        const id = `${generatedMemozId}-${timestamp}`;\n        if (!isValidMemozId(id)) {\n            throw new Error('Generated MEMOZID is not valid');\n        }\n        return id;\n    }\n\n    /**\n     * Checks if the provided value is a non-null object with at least one own property (excluding arrays).\n     *\n     * @param {unknown} value - The value to be checked.\n     * @returns {boolean} `true` if the value is a non-null object with at least one property; otherwise, `false`.\n     *\n     * @example\n     * console.log(isObject({})); // Output: false\n     * console.log(isObject({ key: 'value' })); // Output: true\n     * console.log(isObject(null)); // Output: false\n     * console.log(isObject([])); // Output: false\n     */\n    const isObject = (value) => typeof value === 'object'\n        && value !== null\n        && !Array.isArray(value)\n        && Reflect.ownKeys(value).length > 0;\n\n    class LRUCache {\n        constructor(options) {\n            this.cache = new Map();\n            this.hitCount = 0;\n            this.missCount = 0;\n            this.cleanupInterval = 60000; // 1 minute cleanup interval\n            const { maxSize, ttl, onEvict, evictionStrategy = 'LRU', stayAlive = false, } = options;\n            if (maxSize <= 0) {\n                throw new Error('maxSize must be greater than 0');\n            }\n            this.maxSize = maxSize;\n            this.ttl = ttl;\n            this.onEvict = onEvict;\n            this.evictionStrategy = evictionStrategy;\n            if (stayAlive) {\n                this.startCleanup();\n            }\n        }\n        reorder(key) {\n            if (this.evictionStrategy === 'LRU') {\n                const entry = this.cache.get(key);\n                if (!entry)\n                    return;\n                this.cache.delete(key); // Remove the entry\n                this.cache.set(key, entry); // Re-insert to update the position\n            }\n        }\n        // eslint-disable-next-line class-methods-use-this\n        isExpired(entry) {\n            if (entry.expiry === undefined)\n                return false;\n            return performance.now() > entry.expiry;\n        }\n        cleanupExpiredEntries() {\n            const now = performance.now();\n            Array.from(this.cache.entries()).forEach(([key, entry]) => {\n                if (entry.expiry !== undefined && now > entry.expiry) {\n                    this.cache.delete(key);\n                    if (this.onEvict) {\n                        this.onEvict(key, entry.value);\n                    }\n                }\n            });\n        }\n        startCleanup() {\n            if (this.cleanupInterval) {\n                this.cleanupTimer = setInterval(() => this.cleanupExpiredEntries(), this.cleanupInterval);\n            }\n        }\n        stopCleanup() {\n            if (this.cleanupTimer) {\n                clearInterval(this.cleanupTimer);\n            }\n        }\n        get(key) {\n            const entry = this.cache.get(key);\n            if (!entry) {\n                this.missCount += 1;\n                return undefined;\n            }\n            if (this.isExpired(entry)) {\n                this.cache.delete(key);\n                this.missCount += 1;\n                return undefined;\n            }\n            this.hitCount += 1;\n            this.reorder(key);\n            return entry.value;\n        }\n        set(key, value, ttl) {\n            if (this.cache.has(key)) {\n                this.reorder(key);\n            }\n            else if (this.cache.size === this.maxSize) {\n                let oldestKey;\n                if (this.evictionStrategy === 'LRU') {\n                    // Get the first key for LRU strategy\n                    oldestKey = this.cache.keys().next().value;\n                }\n                else if (this.evictionStrategy === 'FIFO') {\n                    // Get the oldest key for FIFO strategy\n                    oldestKey = [...this.cache.keys()].shift();\n                }\n                if (oldestKey !== undefined) {\n                    const oldestEntry = this.cache.get(oldestKey);\n                    this.cache.delete(oldestKey);\n                    if (this.onEvict && oldestEntry) {\n                        this.onEvict(oldestKey, oldestEntry.value);\n                    }\n                }\n            }\n            // Avoid nested ternaries by using simple conditionals\n            let expiry;\n            if (ttl !== undefined) {\n                expiry = performance.now() + ttl;\n            }\n            else if (this.ttl !== undefined) {\n                expiry = performance.now() + this.ttl;\n            }\n            this.cache.set(key, { value, expiry });\n        }\n        delete(key) {\n            return this.cache.delete(key);\n        }\n        clear() {\n            this.cache.clear();\n        }\n        get size() {\n            return this.cache.size;\n        }\n        has(key) {\n            const entry = this.cache.get(key);\n            if (!entry)\n                return false;\n            if (this.isExpired(entry)) {\n                this.cache.delete(key);\n                return false;\n            }\n            return true;\n        }\n        entries() {\n            return Array.from(this.cache.entries())\n                .filter(([, entry]) => !this.isExpired(entry))\n                .map(([key, entry]) => [key, entry.value]);\n        }\n        serialize() {\n            const entries = this.entries();\n            return JSON.stringify(entries);\n        }\n        deserialize(serializedCache) {\n            const entries = JSON.parse(serializedCache);\n            this.cache.clear();\n            entries.forEach(([key, value]) => {\n                this.set(key, value);\n            });\n        }\n        get hitRate() {\n            const total = this.hitCount + this.missCount;\n            return total === 0 ? 0 : this.hitCount / total;\n        }\n        get missRate() {\n            const total = this.hitCount + this.missCount;\n            return total === 0 ? 0 : this.missCount / total;\n        }\n        getAsync(key, fetchFn) {\n            return __awaiter(this, void 0, void 0, function* () {\n                const cached = this.get(key);\n                if (cached) {\n                    return cached;\n                }\n                const result = yield fetchFn();\n                this.set(key, result);\n                return result;\n            });\n        }\n    }\n\n    class QueryCache {\n        /**\n           * Initializes the QueryCache with optional maxSize, TTL, and eviction strategy.\n           * @param options - Object containing maxSize, TTL, and eviction strategy.\n           */\n        constructor(options) {\n            // Metrics for cache hits and misses\n            this.cacheHits = 0;\n            this.cacheMisses = 0;\n            const { maxSize = 1000, ttl, evictionStrategy = 'LRU' } = options || {};\n            this.cache = new LRUCache({\n                maxSize,\n                ttl,\n                evictionStrategy,\n            });\n        }\n        /**\n           * Retrieves a list of documents by the given key from the cache.\n           * Tracks cache hits and misses.\n           * @param key - The key to retrieve.\n           * @returns The array of DocumentWithId<T> associated with the key, or undefined if not found or expired.\n           */\n        get(key) {\n            const result = this.cache.get(key);\n            if (result) {\n                this.cacheHits += 1;\n            }\n            else {\n                this.cacheMisses += 1;\n            }\n            return result;\n        }\n        /**\n           * Adds or updates a list of documents in the cache.\n           * Supports custom TTL for each entry.\n           * @param key - The key of the cache entry.\n           * @param value - The array of DocumentWithId<T> to cache.\n           * @param ttl - Optional TTL for this specific entry, overriding global TTL.\n           */\n        set(key, value, ttl) {\n            this.cache.set(key, value, ttl); // Allow custom TTL per entry\n        }\n        /**\n           * Invalidates (removes) a cache entry by key, or clears the entire cache if no key is provided.\n           * @param key - Optional key to remove from the cache. If not provided, the entire cache is cleared.\n           */\n        invalidate(key) {\n            if (key) {\n                this.cache.delete(key);\n            }\n            else {\n                this.cache.clear();\n            }\n        }\n        /**\n           * Returns cache hit/miss statistics.\n           * @returns An object with hit and miss counts.\n           */\n        getStats() {\n            return {\n                hits: this.cacheHits,\n                misses: this.cacheMisses,\n            };\n        }\n    }\n\n    class TransactionManager {\n        constructor(db) {\n            this.transactionDb = null;\n            this.dbSnapshot = null;\n            this.db = db;\n        }\n        beginTransaction() {\n            if (this.transactionDb) {\n                throw new Error('Transaction already in progress');\n            }\n            // Take a snapshot of the current state before the transaction begins\n            this.dbSnapshot = new Map(this.db);\n            // Initialize a transaction state, which will hold temporary changes\n            this.transactionDb = new Map(this.db);\n        }\n        commitTransaction() {\n            if (!this.transactionDb) {\n                throw new Error('No transaction in progress');\n            }\n            // Apply the changes made in the transaction to the main db\n            this.db = this.transactionDb;\n            this.transactionDb = null;\n            this.dbSnapshot = null; // Clear the snapshot after committing\n        }\n        rollbackTransaction() {\n            if (!this.transactionDb) {\n                throw new Error('No transaction in progress');\n            }\n            if (!this.dbSnapshot) {\n                throw new Error('No snapshot available for rollback');\n            }\n            // Restore the original db state from the snapshot\n            this.db = this.dbSnapshot;\n            this.transactionDb = null;\n            this.dbSnapshot = null; // Clear the snapshot after rollback\n        }\n        getCurrentDb() {\n            return this.transactionDb || this.db;\n        }\n    }\n\n    /**\n     * A class to manage persistence of data in a Map structure, allowing\n     * for saving to and loading from disk.\n     *\n     * @template T - The type of documents stored in the Map.\n     */\n    class PersistenceManager {\n        /**\n         * Creates an instance of PersistenceManager.\n         *\n         * @param {Map<MEMOZID, DocumentWithId<T>>} db - The initial database as a Map.\n         * @param {string | undefined} filePath - The path to the file for persistence.\n         * @param {boolean} [persistToDisk] - Flag indicating whether to persist data to disk.\n         */\n        constructor(db, filePath, persistToDisk) {\n            this.db = db;\n            this.filePath = filePath ? path__default[\"default\"].resolve(filePath) : './data.json';\n            this.persistToDisk = persistToDisk;\n        }\n        /**\n         * Saves the current state of the Map to disk as a JSON file.\n         *\n         * @returns {Promise<void>} A promise that resolves when the operation is complete.\n         *\n         * @throws {Error} If there is an error writing to the file.\n         */\n        saveToDisk() {\n            return __awaiter(this, void 0, void 0, function* () {\n                if (this.persistToDisk && this.filePath) {\n                    const dir = path__default[\"default\"].dirname(this.filePath);\n                    yield fs.promises.mkdir(dir, { recursive: true });\n                    const writeStream = fs__default[\"default\"].createWriteStream(this.filePath);\n                    writeStream.write(JSON.stringify(Array.from(this.db.entries())));\n                    writeStream.end();\n                }\n            });\n        }\n        /**\n         * Loads data from disk into the Map.\n         *\n         * @returns {Promise<void>} A promise that resolves when the operation is complete.\n         *\n         * @throws {Error} If there is an error reading the file or parsing the JSON data.\n         */\n        loadFromDisk() {\n            return __awaiter(this, void 0, void 0, function* () {\n                // if filePath is provide and node exists create the file\n                if (this.filePath && !fs__default[\"default\"].existsSync(this.filePath)) {\n                    yield fs.promises.writeFile(this.filePath, []);\n                }\n                if (this.filePath && this.persistToDisk) {\n                    // Check if the file exists\n                    yield fs.promises.access(this.filePath);\n                    // Load the file contents\n                    const data = yield fs.promises.readFile(this.filePath, 'utf8');\n                    if (data) {\n                        const entries = JSON.parse(data);\n                        this.db.clear(); // Clear the original Map reference\n                        entries.forEach(([key, value]) => {\n                            this.db.set(key, value); // Populate the original Map\n                        });\n                    }\n                }\n            });\n        }\n    }\n\n    /**\n     * The `IndexManager` class manages indexing for documents of type `T`.\n     * It provides functionalities to update indexes with new documents,\n     * retrieve indexes based on fields, query documents using indexes, and clear all indexes.\n     *\n     * @template T - The document type.\n     */\n    class IndexManager {\n        constructor() {\n            /**\n               * A map that stores indexes by field names.\n               * The key is a string formed by joining field names with an underscore.\n               */\n            this.indexes = new Map();\n        }\n        /**\n           * Updates all existing indexes by adding the provided document.\n           *\n           * @param {DocumentWithId<T>} doc - The document to add to the indexes.\n           */\n        updateIndexes(doc) {\n            this.indexes.forEach((index) => {\n                index.addDocument(doc);\n            });\n        }\n        /**\n           * Retrieves an index based on the specified fields.\n           *\n           * @param {string[]} fields - The array of field names used to identify the index.\n           * @returns {Indexing<T> | undefined} - The index for the specified fields, or undefined if not found.\n           */\n        getIndex(fields) {\n            return this.indexes.get(fields.join('_'));\n        }\n        /**\n          * Retrieves documents from the index based on the query object.\n          * If an index exists for the query fields, it uses that index to fetch documents from the database.\n          *\n          * @param {ConditionNode<Partial<T>>} query - The query object containing conditions for fields and values to search for.\n          * @param {Map<MEMOZID, DocumentWithId<T>>} db - A Map representing the database of documents.\n          * @returns {DocumentWithId<T>[]} - An array of documents that match the query.\n          */\n        getFromIndex(query, db) {\n            const results = new Set();\n            const index = this.getIndex(Object.keys(query));\n            if (index) {\n                const indexedIds = index.query(query);\n                indexedIds.forEach((id) => {\n                    const doc = db.get(id); // Access the db Map passed as an argument\n                    if (doc)\n                        results.add(doc);\n                });\n            }\n            return [...results];\n        }\n        /**\n           * Clears all indexes managed by the `IndexManager`.\n           *\n           * @returns {void}\n           */\n        clear() {\n            return this.indexes.clear();\n        }\n    }\n\n    /**\n     * Evaluates a condition against a given datum (data object).\n     *\n     * This function supports various comparison operators including equality,\n     * inequality, greater than, less than, inclusion/exclusion in a set,\n     * and regular expression matching.\n     *\n     * @template T - The type of the data object being evaluated.\n     * @param datum - The data object to evaluate the condition against.\n     * @param condition - The condition to evaluate, which must be of type SimpleCondition<T>.\n     * @returns A boolean indicating whether the condition is satisfied for the given datum.\n     */\n    const evaluateCondition = (datum, condition) => {\n        const { field, operator, value, customCompare, } = condition;\n        // If a custom comparison function is provided, use it.\n        if (customCompare) {\n            return customCompare(datum[field], value);\n        }\n        switch (operator) {\n            case '$eq':\n                return datum[field] === value;\n            case '$neq':\n                return datum[field] !== value;\n            case '$gt':\n                return datum[field] > value;\n            case '$gte':\n                return datum[field] >= value;\n            case '$lt':\n                return datum[field] < value;\n            case '$lte':\n                return datum[field] <= value;\n            case '$in':\n                return Array.isArray(value) && value.includes(datum[field]);\n            case '$nin':\n                return Array.isArray(value) && !value.includes(datum[field]);\n            case '$regex': {\n                if (value && typeof value === 'object' && ('$regex' in value)) {\n                    const regexCondition = value; // Cast value to RegexCondition\n                    const regex = regexCondition.$regex instanceof RegExp\n                        ? regexCondition.$regex\n                        : new RegExp(regexCondition.$regex, regexCondition.$options || ''); // Apply options if $regex is a string\n                    // Check if the field is a string before testing\n                    const fieldValue = datum[field];\n                    return typeof fieldValue === 'string' ? regex.test(fieldValue) : false;\n                }\n                return false; // Invalid regex condition\n            }\n            default:\n                return false; // Unsupported operator\n        }\n    };\n\n    /**\n     * A cache that maps a datum to a Map of condition nodes and their evaluation results.\n     * The `WeakMap` ensures that the cache is memory-safe and automatically cleans up\n     * when the datum is no longer in use.\n     */\n    const memoCache = new WeakMap();\n    /**\n     * Evaluates a logical condition node against a given datum (data object) with memoization.\n     *\n     * This function supports both AND and OR logical operations:\n     * - For AND (`$and`), all conditions must evaluate to true.\n     * - For OR (`$or`), at least one condition must evaluate to true.\n     * If the node is a simple condition, it will be evaluated directly.\n     *\n     * Memoization is applied to avoid redundant computations of the same condition for the same datum.\n     *\n     * @template T - The type of the data object being evaluated.\n     * @param datum - The data object to evaluate against the condition node.\n     * @param node - The condition node containing logical operations and/or conditions.\n     * @returns A boolean indicating whether the condition node is satisfied by the datum.\n     */\n    const evaluateNode = (datum, node) => {\n        // Retrieve or initialize the cache for the current datum, ensuring type safety\n        let datumCache = memoCache.get(datum);\n        if (!datumCache) {\n            datumCache = new Map();\n            memoCache.set(datum, datumCache);\n        }\n        // Check if the result is already cached for this condition node\n        if (datumCache.has(node)) {\n            return datumCache.get(node); // Use the cached result, safely asserting it exists\n        }\n        let result;\n        // Evaluate the condition\n        if ('$and' in node) {\n            // AND logic: all conditions must pass\n            result = node.$and.every((subNode) => evaluateNode(datum, subNode));\n        }\n        else if ('$or' in node) {\n            // OR logic: at least one condition must pass\n            result = node.$or.some((subNode) => evaluateNode(datum, subNode));\n        }\n        else {\n            // Handle simple condition\n            result = evaluateCondition(datum, node);\n        }\n        // Cache the result for the current node and datum\n        datumCache.set(node, result);\n        return result;\n    };\n\n    /**\n     * Finds the first item in the dataset that matches the provided condition node.\n     *\n     * This function uses `evaluateNode` to efficiently evaluate each datum against\n     * the condition node, stopping as soon as a match is found to improve performance.\n     *\n     * @template T - The type of the objects in the dataset.\n     * @param {T[]} data - The dataset to search through.\n     * @param {ConditionNode<T>} query - The query object containing nested AND/OR logic and conditions.\n     * @returns {T | undefined} - Returns the first matching item, or undefined if no match is found.\n     */\n    const getOne = (data, query) => data.find((datum) => evaluateNode(datum, query));\n\n    /**\n     * Filters the dataset to find all items that match the provided condition node.\n     *\n     * This function uses `evaluateNode` to efficiently evaluate each datum against\n     * the condition node, leveraging memoization to avoid redundant computations.\n     *\n     * @template T - The type of the objects in the dataset.\n     * @param {T[]} data - The dataset to filter.\n     * @param {ConditionNode<T>} query - The query object containing nested AND/OR logic and conditions.\n     * @returns {T[]} - Returns an array of matching items.\n     */\n    const getMany = (data, query) => data.filter((datum) => evaluateNode(datum, query));\n\n    class Mutex {\n        constructor() {\n            this.mutex = Promise.resolve();\n        }\n        lock(callback) {\n            // Locking mechanism: Wait for the current mutex chain to resolve,\n            // then run the callback and capture its result\n            const resultPromise = this.mutex.then(() => callback());\n            // Update the mutex to wait for the current operation to finish\n            this.mutex = resultPromise.then(() => undefined, () => undefined);\n            // Return the result of the callback, so the caller gets its value\n            return resultPromise;\n        }\n    }\n\n    /**\n     * Splits an array into smaller chunks of a specified size.\n     *\n     * @template T\n     * @param {T[]} array - The array to split into chunks.\n     * @param {number} size - The size of each chunk.\n     * @returns {T[][]} - An array of chunks.\n     */\n    function chunkArray(array, size) {\n        const chunks = [];\n        for (let i = 0; i < array.length; i += size) {\n            chunks.push(array.slice(i, i + size));\n        }\n        return chunks;\n    }\n\n    class QueryBuilder {\n        constructor(result, queryCache, queryKey) {\n            this.result = [];\n            this.sortConditions = [];\n            this.skipCount = 0;\n            this.limitCount = Number.MAX_SAFE_INTEGER;\n            this.isResolved = false;\n            if (result instanceof Promise) {\n                this.resultPromise = result;\n            }\n            else {\n                this.result = result;\n                this.isResolved = true;\n            }\n            this.queryCache = queryCache;\n            this.queryKey = queryKey;\n        }\n        // Resolves the result if it's a promise, otherwise returns the result\n        resolveResult() {\n            return __awaiter(this, void 0, void 0, function* () {\n                if (!this.isResolved && this.resultPromise) {\n                    this.result = yield this.resultPromise;\n                    this.isResolved = true;\n                }\n                return this.result;\n            });\n        }\n        sort(sortConditions) {\n            if (sortConditions) {\n                // If sortConditions is an array, use it as is, otherwise wrap it in an array\n                this.sortConditions = Array.isArray(sortConditions) ? sortConditions : [sortConditions];\n            }\n            return this;\n        }\n        skip(skipCount) {\n            this.skipCount = skipCount;\n            return this;\n        }\n        limit(limitCount) {\n            this.limitCount = limitCount;\n            return this;\n        }\n        exec() {\n            return __awaiter(this, void 0, void 0, function* () {\n                const resolvedResult = yield this.resolveResult();\n                // Apply sorting if needed\n                if (this.sortConditions.length > 0) {\n                    resolvedResult.sort((a, b) => {\n                        let comparisonResult = 0;\n                        this.sortConditions.forEach((sortObj) => {\n                            Object.entries(sortObj).forEach(([key, order]) => {\n                                const typedKey = key; // Ensure the key is treated as keyof T\n                                const aValue = a[typedKey];\n                                const bValue = b[typedKey];\n                                // Skip undefined or null values\n                                if (aValue === undefined || bValue === undefined || aValue === null || bValue === null)\n                                    return;\n                                if (aValue < bValue) {\n                                    comparisonResult = order === 'asc' ? -1 : 1;\n                                    return; // Exit inner loop after determining order\n                                }\n                                if (aValue > bValue) {\n                                    comparisonResult = order === 'asc' ? 1 : -1;\n                                    // Exit inner loop after determining order\n                                }\n                            });\n                        });\n                        return comparisonResult;\n                    });\n                }\n                // Apply pagination\n                const paginatedResult = resolvedResult.slice(this.skipCount, this.skipCount + this.limitCount);\n                // Cache the result only if it's different\n                if (JSON.stringify(this.result) !== JSON.stringify(paginatedResult)) {\n                    this.queryCache.set(this.queryKey, paginatedResult);\n                }\n                return paginatedResult;\n            });\n        }\n        then(onfulfilled, onrejected) {\n            return this.exec().then(onfulfilled, onrejected);\n        }\n        catch(onrejected) {\n            return this.exec().catch(onrejected);\n        }\n        finally(onfinally) {\n            return this.exec().finally(onfinally);\n        }\n        // Mark the class as Promise-like for chaining purposes\n        // eslint-disable-next-line class-methods-use-this\n        get [Symbol.toStringTag]() {\n            return 'Promise';\n        }\n    }\n    // Proxy to enable chaining and ensure correct promise-like behavior\n    function createQueryBuilderProxy(builder) {\n        return new Proxy(builder, {\n            get(target, prop, receiver) {\n                const value = Reflect.get(target, prop, receiver);\n                if (typeof value === 'function') {\n                    return (...args) => {\n                        const result = value.apply(target, args);\n                        return result instanceof QueryBuilder ? createQueryBuilderProxy(result) : result;\n                    };\n                }\n                if (prop === 'then') {\n                    return (...args) => builder.then(...args);\n                }\n                if (prop === 'catch') {\n                    return (onrejected) => builder.exec().catch(onrejected);\n                }\n                return builder.exec();\n            },\n        });\n    }\n\n    /**\n     * Removes accents from characters in a string.\n     * This function converts accented characters (diacritics) to their base form.\n     */\n    function removeAccents(text) {\n        return text.normalize('NFD').replace(/[\\u0300-\\u036f]/g, ''); // Unicode normalization + regex to strip accents\n    }\n    class SearchEngine {\n        constructor(db) {\n            this.db = db;\n            this.levenshteinCache = new Map();\n            this.normalizationCache = new Map();\n            this.resultLimit = null; // Default limit to null (no limit)\n        }\n        /**\n         * Normalize the string by lowercasing, removing accents, and trimming whitespace.\n         * Extended to remove punctuation and accents. Cached for performance.\n         */\n        static normalizeWithCache(text, cache) {\n            if (!cache.has(text)) {\n                const normalized = removeAccents(text.toLowerCase().trim()).replace(/[^\\w\\s]|_/g, '');\n                cache.set(text, normalized);\n            }\n            return cache.get(text);\n        }\n        /**\n         * Tokenizes the input string into words or terms.\n         * Supports n-grams and can be expanded to apply stemming/lemmatization.\n         */\n        static tokenize(text, n = 1) {\n            const words = text.split(/\\s+/); // Splits by whitespace\n            // Generate n-grams if requested\n            if (n > 1) {\n                const nGrams = [];\n                for (let i = 0; i <= words.length - n; i += 1) {\n                    nGrams.push(words.slice(i, i + n).join(' '));\n                }\n                return nGrams;\n            }\n            return words;\n        }\n        /**\n         * Optimized Levenshtein Distance implementation\n         * Uses two rows instead of a full matrix to save memory\n         */\n        levenshteinDistance(a, b, maxDistance) {\n            const cacheKey = JSON.stringify([a, b]);\n            if (this.levenshteinCache.has(cacheKey)) {\n                return this.levenshteinCache.get(cacheKey);\n            }\n            if (Math.abs(a.length - b.length) > maxDistance) {\n                return maxDistance + 1; // Early exit if difference exceeds maxDistance\n            }\n            let prevRow = Array(a.length + 1).fill(0);\n            let currRow = Array(a.length + 1).fill(0);\n            for (let i = 0; i <= a.length; i += 1)\n                prevRow[i] = i;\n            for (let i = 1; i <= b.length; i += 1) {\n                currRow[0] = i;\n                for (let j = 1; j <= a.length; j += 1) {\n                    const cost = b[i - 1] === a[j - 1] ? 0 : 1;\n                    currRow[j] = Math.min(prevRow[j] + 1, // Deletion\n                    currRow[j - 1] + 1, // Insertion\n                    prevRow[j - 1] + cost);\n                }\n                // Swap rows\n                [prevRow, currRow] = [currRow, prevRow];\n            }\n            const result = prevRow[a.length];\n            this.levenshteinCache.set(cacheKey, result);\n            return result;\n        }\n        /**\n         * Main search function which performs fuzzy search based on the search term.\n         * @param searchTerm - The term the user is searching for.\n         * @param fields - The fields to search within the objects.\n         * @param options - Options to configure max distance, field weights, n-grams, etc.\n         * @returns Array of results with relevance score.\n         */\n        search(searchTerm, fields, options = { maxDistance: 2, nGramSize: 1 }) {\n            const normalizedSearchTerm = SearchEngine.normalizeWithCache(searchTerm, this.normalizationCache);\n            const searchTokens = SearchEngine.tokenize(normalizedSearchTerm, options.nGramSize);\n            const results = [];\n            const { maxDistance = 2, fieldWeights = {}, nGramSize = 1, scoringStrategy = 'default', customScoringFn, } = options;\n            Array.from(this.db.values()).forEach((item) => {\n                let score = 0;\n                fields.forEach((field) => {\n                    const fieldValue = item[field];\n                    if (typeof fieldValue === 'string') {\n                        const normalizedFieldValue = SearchEngine.normalizeWithCache(fieldValue, this.normalizationCache);\n                        const fieldTokens = SearchEngine.tokenize(normalizedFieldValue, nGramSize);\n                        const fieldWeight = fieldWeights[field] || 1;\n                        searchTokens.forEach((token) => {\n                            fieldTokens.forEach((fieldToken) => {\n                                const distance = this.levenshteinDistance(token, fieldToken, maxDistance);\n                                if (distance <= maxDistance) {\n                                    // Custom scoring logic\n                                    switch (scoringStrategy) {\n                                        case 'default':\n                                            score += (maxDistance - distance) * fieldWeight;\n                                            break;\n                                        case 'tokenCount':\n                                            score += fieldWeight; // Score based on the number of matching tokens\n                                            break;\n                                        case 'custom':\n                                            if (customScoringFn) {\n                                                score += customScoringFn(token, fieldToken, distance, fieldWeight, options);\n                                            }\n                                            break;\n                                        default:\n                                            score += (maxDistance - distance) * fieldWeight;\n                                    }\n                                }\n                            });\n                        });\n                    }\n                });\n                if (score > 0) {\n                    results.push({ item, score });\n                }\n            });\n            // Sort results by highest score\n            const sortedResults = results.sort((a, b) => b.score - a.score);\n            // Apply limit if set\n            return this.resultLimit ? sortedResults.slice(0, this.resultLimit) : sortedResults;\n        }\n        /**\n         * Sets a limit on the number of results returned.\n         * @param limit - The maximum number of results to return. default max number of results\n         * @returns The SearchEngine instance for chaining.\n         */\n        limit(limit = Number.MAX_SAFE_INTEGER) {\n            this.resultLimit = limit;\n            return this;\n        }\n    }\n\n    /**\n     * The Memoz class is an in-memory document store with optional persistence to disk.\n     * It supports transactional operations, querying, indexing, and caching.\n     *\n     * @template T - The type of documents being stored.\n     */\n    class Memoz {\n        /**\n       *\n       * @param memozOptions - Options for the Memoz instance\n       * @param memozOptions.filePath - The file path to save the database to -default is in-memory\n       * @param memozOptions.persistToDisk - Whether to persist the database to disk - default is false\n       * @param memozOptions.useMutex - Whether to use a mutex for thread safety - default is false\n       */\n        constructor(memozOptions = {}) {\n            /**\n             * In-memory database storing documents keyed by MEMOZID.\n             * @private\n             * @type {Map<MEMOZID, DocumentWithId<T>>}\n             */\n            this.db = new Map();\n            this.mutex = null; // Nullable mutex (null if not used)\n            const { storagePath, useMutex = false, persistToDisk = false } = memozOptions;\n            if (useMutex) {\n                this.mutex = new Mutex(); // Only initialize mutex if enabled\n            }\n            this.transactionManager = new TransactionManager(this.db);\n            this.persistenceManager = new PersistenceManager(this.db, storagePath, persistToDisk);\n            this.indexManager = new IndexManager();\n            this.queryCache = new QueryCache();\n            // Initialize the search engine with the db\n            this.searchEngine = new SearchEngine(this.db);\n            this.ready = persistToDisk ? this.persistenceManager.loadFromDisk() : Promise.resolve();\n        }\n        beginTransaction() {\n            return __awaiter(this, void 0, void 0, function* () {\n                yield this.ready;\n                this.transactionManager.beginTransaction();\n            });\n        }\n        commitTransaction() {\n            return __awaiter(this, void 0, void 0, function* () {\n                yield this.ready;\n                this.transactionManager.commitTransaction();\n                yield this.persistenceManager.saveToDisk();\n            });\n        }\n        rollbackTransaction() {\n            return __awaiter(this, void 0, void 0, function* () {\n                yield this.ready;\n                this.transactionManager.rollbackTransaction();\n            });\n        }\n        /**\n         * Performs a fuzzy search on the documents in the database.\n         * @param searchTerm - The term to search for.\n         * @param fields - The fields to search within the documents.\n         * @param options - Options to configure max distance, field weights, etc.\n         * @param limit - The maximum number of results to return.\n         * @returns Array of results with relevance score.\n         */\n        fuzzySearch(searchTerm, fields, options, limit = Number.MAX_SAFE_INTEGER) {\n            return __awaiter(this, void 0, void 0, function* () {\n                yield this.ready;\n                return this.searchEngine.limit(limit).search(searchTerm, fields, options);\n            });\n        }\n        /**\n         * Inserts a new document into the database, assigning it a unique ID, and updating relevant indexes and cache.\n         * This method handles transactional operations and ensures that the document is saved persistently to disk.\n         *\n         * @template T - The type of the document being inserted.\n         * @param {T} document - The document to insert into the database.\n         * @returns {Promise<DocumentWithId<T>>} - A promise that resolves to the document with an added unique ID.\n         *\n         * @throws {Error} If the provided document is not a valid object.\n         *\n         * @example\n         * const newDocument = await db.createOne({ name: 'Sample Document' });\n         *\n         * @remarks\n         * This method uses a mutex to prevent race conditions in concurrent environments.\n         * If a transaction is active, the document is inserted into the transactional database.\n         */\n        createOne(document) {\n            return __awaiter(this, void 0, void 0, function* () {\n                const operation = () => __awaiter(this, void 0, void 0, function* () {\n                    yield this.ready;\n                    // Invalidate cache before inserting the document\n                    this.queryCache.invalidate();\n                    // Ensure the document is a valid object\n                    if (!isObject(document)) {\n                        throw new Error('The document must be a valid object');\n                    }\n                    // Generate a unique ID for the document\n                    const id = memozId();\n                    const dbDocument = Object.assign(Object.assign({}, document), { id });\n                    // Use transactional database if available\n                    const targetDb = this.transactionManager.getCurrentDb();\n                    targetDb.set(id, dbDocument);\n                    // Update indexes for the new document\n                    this.indexManager.updateIndexes(dbDocument);\n                    // Persist the document to disk\n                    yield this.persistenceManager.saveToDisk();\n                    // Return the newly created document with its ID\n                    return dbDocument;\n                });\n                // Execute the operation with mutex lock if available\n                return this.mutex ? this.mutex.lock(operation) : operation();\n            });\n        }\n        /**\n       * Inserts multiple documents into the database in batches, assigning each one a unique ID,\n       * and updating relevant indexes and cache. This method handles transactional operations\n       * and ensures that documents are saved persistently to disk in chunks to avoid performance issues.\n       *\n       * @template T - The type of the documents being inserted.\n       * @param {T[]} documents - The array of documents to insert into the database.\n       * @param {number} [batchSize=100] - The maximum number of documents to process in each batch.\n       * @returns {Promise<DocumentWithId<T>[]>} - A promise that resolves to an array of documents, each with a unique ID assigned.\n       *\n       * @throws {Error} If any document in the provided array is not a valid object.\n       *\n       * @example\n       * const newDocuments = await db.createMany([{ name: 'Doc 1' }, { name: 'Doc 2' }], 50);\n       *\n       * @remarks\n       * This method processes documents in batches to avoid performance bottlenecks.\n       * The batch size is configurable, with a default of 100 documents per batch.\n       */\n        createMany(documents, batchSize = 100) {\n            return __awaiter(this, void 0, void 0, function* () {\n                const operation = () => __awaiter(this, void 0, void 0, function* () {\n                    yield this.ready;\n                    // Invalidate cache before inserting the documents\n                    this.queryCache.invalidate();\n                    // Validate all documents first to avoid partial batch processing\n                    documents.forEach((document) => {\n                        if (!isObject(document)) {\n                            throw new Error('Each document must be a valid object');\n                        }\n                    });\n                    // Chunk documents into batches and process each batch\n                    const allCreatedDocuments = [];\n                    const chunks = chunkArray(documents, batchSize);\n                    // Process each chunk with async/await in sequence\n                    yield chunks.reduce((prevPromise, chunk) => __awaiter(this, void 0, void 0, function* () {\n                        yield prevPromise; // Ensure sequential execution of batches\n                        const createdDocuments = chunk.map((document) => {\n                            const id = memozId(); // Generate unique ID for each document\n                            return Object.assign(Object.assign({}, document), { id });\n                        });\n                        // Insert each document in the current chunk into the database\n                        createdDocuments.forEach((doc) => {\n                            const targetDb = this.transactionManager.getCurrentDb();\n                            targetDb.set(doc.id, doc); // Set document in DB\n                            this.indexManager.updateIndexes(doc); // Update index for each document\n                        });\n                        // Persist chunk to disk\n                        yield this.persistenceManager.saveToDisk();\n                        // Collect all created documents\n                        allCreatedDocuments.push(...createdDocuments);\n                    }), Promise.resolve()); // Start the chain with an immediately resolved Promise\n                    // Return all the created documents with IDs\n                    return allCreatedDocuments;\n                });\n                // Execute the operation with mutex lock if available\n                return this.mutex ? this.mutex.lock(operation) : operation();\n            });\n        }\n        /**\n         * Retrieves a document from the database using its unique identifier (MEMOZID).\n         *\n         * @template T - The type of the document being retrieved.\n         * @param {MEMOZID} id - The unique identifier of the document to retrieve.\n         * @returns {Promise<DocumentWithId<T> | undefined>} - A promise that resolves to the\n         * document with the specified ID if found, or undefined if no document matches the ID.\n         *\n         * @throws {Error} If the provided ID is not valid.\n         *\n         * @example\n         * const document = await db.getById('some-valid-id');\n         * if (document) {\n         *   console.log('Document found:', document);\n         * } else {\n         *   console.log('No document found with that ID.');\n         * }\n         *\n         * @remarks\n         * Ensure that the provided ID follows the expected MEMOZID format.\n         */\n        getById(id) {\n            return __awaiter(this, void 0, void 0, function* () {\n                yield this.ready;\n                // Validate the provided ID\n                if (!isValidMemozId(id)) {\n                    throw new Error('The ID must be valid');\n                }\n                // Retrieve the document from the current database\n                return this.transactionManager.getCurrentDb().get(id);\n            });\n        }\n        /**\n       * Retrieves a single document from the database that matches the provided query.\n       *\n       * This method first checks the query cache for a result. If a cached result is found, it returns that.\n       * If no cached result exists, it checks the index for matching documents. If none are found,\n       * it retrieves the document directly from the database.\n       *\n       * @template T - The type of the document being retrieved.\n       * @param {ConditionNode<Partial<T>>} [query] - The optional query condition used to find the document.\n       * If not provided, the first document from the current database is returned.\n       * @returns {Promise<DocumentWithId<T> | undefined>} - A promise that resolves to the document that matches the query,\n       * or undefined if no document is found.\n       *\n       * @throws {Error} If the provided query is not a valid object.\n       *\n       * @example\n       * const document = await db.getOne({ name: 'Example Document' });\n       * if (document) {\n       *   console.log('Document found:', document);\n       * } else {\n       *   console.log('No document found matching the query.');\n       * }\n       *\n       * @remarks\n       * Ensure that the provided query object is structured correctly to match documents in the database.\n       * If no query is provided, the method will return the first document in the database or undefined\n       * if the database is empty. Caching is utilized to optimize subsequent retrievals of the same document.\n       */\n        getOne(query) {\n            return __awaiter(this, void 0, void 0, function* () {\n                yield this.ready;\n                // Handle optional query\n                if (query === undefined) {\n                    // If no query is provided, return the first document or undefined if not found\n                    const firstDocument = this.transactionManager.getCurrentDb().values().next().value; // Adjust based on your data structure\n                    return firstDocument || undefined; // Return the first document or undefined if not found\n                }\n                const queryKey = JSON.stringify(query);\n                const cachedResult = this.queryCache.get(queryKey);\n                if (cachedResult) {\n                    return cachedResult[0]; // Return the first cached result if available\n                }\n                // Validate the provided query\n                if (!isObject(query)) {\n                    throw new Error('Invalid query: The query must be a valid object');\n                }\n                const indexedResults = this.getFromIndex(query);\n                const result = indexedResults.length > 0 ? indexedResults[0] : getOne([...this.transactionManager.getCurrentDb().values()], query);\n                if (result) {\n                    this.queryCache.set(queryKey, [result]); // Cache the result for future use\n                }\n                return result; // Return the retrieved document or undefined if not found\n            });\n        }\n        /**\n       * Retrieves multiple documents from the database that match the provided query.\n       * Supports sorting, pagination, and caching with chainable methods.\n       *\n       * @param {ConditionNode<Partial<T>>} query - The query condition to match documents.\n       * @returns {QueryBuilder<DocumentWithId<T>>} - A QueryBuilder instance with chaining support.\n       */\n        /**\n       * Retrieves multiple documents from the database that match the provided query.\n       * Supports sorting, pagination, and caching with chainable methods.\n       *\n       * @param {ConditionNode<Partial<T>>} [query] - The optional query condition to match documents.\n       * @returns {QueryBuilder<DocumentWithId<T>>} - A QueryBuilder instance with chaining support.\n       */\n        getMany(query) {\n            const operation = () => __awaiter(this, void 0, void 0, function* () {\n                yield this.ready;\n                const queryKey = query ? JSON.stringify(query) : 'default-query-key';\n                if (query && !isObject(query)) {\n                    throw new Error('Invalid query: The query must be a valid object');\n                }\n                let initialResult;\n                // If query is provided, use it, otherwise return all documents\n                if (query) {\n                    initialResult = this.getFromIndex(query).length > 0\n                        ? this.getFromIndex(query)\n                        : getMany([...this.transactionManager.getCurrentDb().values()], query);\n                }\n                else {\n                    // Fetch all documents if no query is provided\n                    initialResult = [...this.transactionManager.getCurrentDb().values()];\n                }\n                this.queryCache.set(queryKey, initialResult);\n                return initialResult;\n            });\n            const resultsPromise = operation();\n            // Return the QueryBuilder with the promise result\n            return createQueryBuilderProxy(new QueryBuilder(resultsPromise, this.queryCache, query ? JSON.stringify(query) : 'default-query-key'));\n        }\n        /**\n       * Updates an existing object by its ID with the provided new data.\n       *\n       * This method retrieves the object associated with the given ID, merges it with the\n       * new data, updates the database, reindexes the object, and persists the changes to disk.\n       *\n       * @template T - The type of the object being updated.\n       * @param {MEMOZID} id - The unique identifier of the object to update.\n       * @param {Partial<T>} newData - The partial object containing the new data to update the object with.\n       * @returns {Promise<DocumentWithId<T>>} - A promise that resolves to the updated object with its ID.\n       * @throws {Error} If the provided ID is not valid.\n       * @throws {Error} If the new data is not a valid object.\n       * @throws {Error} If the object with the provided ID does not exist.\n       *\n       * @example\n       * const updatedObject = await updateById('someId', { name: 'Updated Name' });\n       * console.log(updatedObject);\n       */\n        updateById(id, newData) {\n            return __awaiter(this, void 0, void 0, function* () {\n                const operation = () => __awaiter(this, void 0, void 0, function* () {\n                    yield this.ready;\n                    this.queryCache.invalidate();\n                    if (!isValidMemozId(id)) {\n                        throw new Error('The ID must be valid');\n                    }\n                    if (!isObject(newData)) {\n                        throw new Error('The new data must be a valid object');\n                    }\n                    const existingObject = yield this.getById(id);\n                    if (!existingObject) {\n                        throw new Error('This ID does not exist');\n                    }\n                    const updatedObject = Object.assign(Object.assign({}, existingObject), newData);\n                    this.transactionManager.getCurrentDb().set(id, updatedObject);\n                    this.indexManager.updateIndexes(updatedObject);\n                    yield this.persistenceManager.saveToDisk();\n                    return updatedObject;\n                });\n                return this.mutex ? this.mutex.lock(operation) : operation();\n            });\n        }\n        /**\n       * Updates a single document in the database based on the provided query and new data.\n       *\n       * @param {ConditionNode<Partial<T>>} query - The query used to find the document to update.\n       * @param {Partial<T>} newData - The new data to merge with the existing document.\n       * @returns {Promise<DocumentWithId<T>>} - A promise that resolves to the updated document.\n       * @throws {Error} - Throws an error if the query or newData is not a valid object, or if no document matches the query.\n       */\n        updateOne(query, newData) {\n            return __awaiter(this, void 0, void 0, function* () {\n                const operation = () => __awaiter(this, void 0, void 0, function* () {\n                    yield this.ready;\n                    this.queryCache.invalidate();\n                    if (!isObject(query)) {\n                        throw new Error('The query must be a valid object');\n                    }\n                    if (!isObject(newData)) {\n                        throw new Error('The new data must be a valid object');\n                    }\n                    const existingObject = yield this.getOne(query);\n                    if (!existingObject) {\n                        throw new Error('No document matches the query');\n                    }\n                    const updatedObject = Object.assign(Object.assign({}, existingObject), newData);\n                    const targetDb = this.transactionManager.getCurrentDb();\n                    targetDb.set(existingObject.id, updatedObject);\n                    this.indexManager.updateIndexes(updatedObject); // Update indexes after modifying\n                    yield this.persistenceManager.saveToDisk();\n                    return updatedObject;\n                });\n                return this.mutex ? this.mutex.lock(operation) : operation();\n            });\n        }\n        /**\n       * Updates multiple documents in the database based on the provided query and new data.\n       *\n       * @param {ConditionNode<Partial<T>>} query - The query used to find the documents to update.\n       * @param {Partial<T>} newData - The new data to merge with the existing documents.\n       * @returns {Promise<UpdateManyResult<T>>} - A promise that resolves to an object containing update results, including:\n       *   - `updated`: A boolean indicating if the update was successful.\n       *   - `n`: The number of documents that were updated.\n       *   - `documents`: An array of the updated documents.\n       * @throws {Error} - Throws an error if either the query or newData is not a valid object.\n       */\n        updateMany(query, newData) {\n            return __awaiter(this, void 0, void 0, function* () {\n                const operation = () => __awaiter(this, void 0, void 0, function* () {\n                    yield this.ready;\n                    this.queryCache.invalidate();\n                    if (!isObject(query) || !isObject(newData)) {\n                        throw new Error('Both query and new data must be valid objects');\n                    }\n                    const documents = yield this.getMany(query);\n                    documents.forEach((document) => this.updateById(document.id, newData));\n                    yield this.persistenceManager.saveToDisk();\n                    return { updated: true, n: documents.length, documents };\n                });\n                return this.mutex ? this.mutex.lock(operation) : operation();\n            });\n        }\n        /**\n       * Deletes a document from the database based on the provided ID.\n       *\n       * @param {MEMOZID} id - The ID of the document to be deleted. Must be a valid ID.\n       * @returns {Promise<DocumentWithId<T> | undefined>} - A promise that resolves to the deleted document, or undefined if no document was found with the given ID.\n       * @throws {Error} - Throws an error if the provided ID is not valid.\n       */\n        deleteById(id) {\n            return __awaiter(this, void 0, void 0, function* () {\n                const operation = () => __awaiter(this, void 0, void 0, function* () {\n                    yield this.ready;\n                    this.queryCache.invalidate();\n                    if (!isValidMemozId(id)) {\n                        throw new Error('The ID must be valid');\n                    }\n                    const targetDb = this.transactionManager.getCurrentDb();\n                    const documentToDelete = targetDb.get(id);\n                    if (documentToDelete) {\n                        // Update indexes efficiently\n                        this.indexManager.updateIndexes(documentToDelete);\n                        // Remove the document from the main database\n                        targetDb.delete(id);\n                        yield this.persistenceManager.saveToDisk();\n                    }\n                    return documentToDelete;\n                });\n                return this.mutex ? this.mutex.lock(operation) : operation();\n            });\n        }\n        /**\n           * Deletes all documents from the database.\n           *\n           * @returns {Promise<{ deleted: boolean; n: number; }>} - A promise that resolves to an object containing:\n           *   - `deleted`: A boolean indicating that the deletion was successful.\n           *   - `n`: The number of documents that were deleted.\n           */\n        deleteAll() {\n            return __awaiter(this, void 0, void 0, function* () {\n                const operation = () => __awaiter(this, void 0, void 0, function* () {\n                    yield this.ready;\n                    const targetDb = this.transactionManager.getCurrentDb();\n                    const { size } = targetDb;\n                    targetDb.clear();\n                    this.indexManager.clear();\n                    yield this.persistenceManager.saveToDisk();\n                    return { deleted: true, n: size };\n                });\n                return this.mutex ? this.mutex.lock(operation) : operation();\n            });\n        }\n        /**\n       * Deletes a single document from the database based on the provided query.\n       *\n       * @param {ConditionNode<Partial<T>>} query - The query used to find the document to delete. Must be a valid object.\n       * @returns {Promise<DocumentWithId<T> | undefined>} - A promise that resolves to the deleted document, or undefined if no document was found matching the query.\n       * @throws {Error} - Throws an error if the query is not a valid object.\n       */\n        deleteOne(query) {\n            return __awaiter(this, void 0, void 0, function* () {\n                yield this.ready;\n                this.queryCache.invalidate();\n                if (!isObject(query)) {\n                    throw new Error('The query must be a valid object');\n                }\n                const objectToDelete = yield this.getOne(query);\n                if (!objectToDelete)\n                    return undefined;\n                this.deleteById(objectToDelete.id);\n                yield this.persistenceManager.saveToDisk();\n                return objectToDelete;\n            });\n        }\n        /**\n       * Deletes multiple documents from the database based on the provided query.\n       *\n       * @param {ConditionNode<Partial<T>>} query - The query used to find the documents to delete. Must be a valid object.\n       * @returns {Promise<{ deleted: boolean; n: number; }>} - A promise that resolves to an object containing:\n       *   - `deleted`: A boolean indicating that the deletion was successful.\n       *   - `n`: The number of documents that were deleted.\n       * @throws {Error} - Throws an error if the query is not a valid object.\n       */\n        deleteMany(query) {\n            return __awaiter(this, void 0, void 0, function* () {\n                yield this.ready;\n                this.queryCache.invalidate();\n                if (!isObject(query)) {\n                    throw new Error('The query must be a valid object');\n                }\n                const documents = yield this.getMany(query);\n                documents.forEach((doc) => this.deleteById(doc.id));\n                yield this.persistenceManager.saveToDisk();\n                return { deleted: true, n: documents.length };\n            });\n        }\n        /**\n       * Counts the number of documents in the database, optionally filtered by a query.\n       *\n       * @param {ConditionNode<Partial<T>>} [query] - An optional query to filter the documents to count. Must be a valid object if provided.\n       * @returns {Promise<number>} - A promise that resolves to the number of documents matching the query, or the total number of documents if no query is provided.\n       * @throws {Error} - Throws an error if the query is provided and is not a valid object.\n       */\n        countDocuments(query) {\n            return __awaiter(this, void 0, void 0, function* () {\n                yield this.ready;\n                if (query && !isObject(query)) {\n                    throw new Error('The query must be a valid object');\n                }\n                return query && Object.keys(query).length ? (yield this.getMany(query)).length : this.transactionManager.getCurrentDb().size;\n            });\n        }\n        /**\n       * Generates and returns a new unique identifier (MEMOZID).\n       *\n       * @returns {MEMOZID} - A newly generated unique identifier.\n       */\n        static id() {\n            return memozId();\n        }\n        /**\n       * Validates whether the provided ID is a valid MEMOZID.\n       *\n       * @param {MEMOZID} id - The ID to validate.\n       * @returns {boolean} - Returns true if the ID is valid, otherwise false.\n       */\n        static isValidId(id) {\n            return isValidMemozId(id);\n        }\n        getFromIndex(query) {\n            return this.indexManager.getFromIndex(query, this.transactionManager.getCurrentDb());\n        }\n    }\n\n    exports.Memoz = Memoz;\n\n    Object.defineProperty(exports, '__esModule', { value: true });\n\n}));\n"]}