UNPKG

turbo-map

Version:

High-performance, type-safe Map implementation supporting complex nested objects as keys, fully compatible with ES Map API

3 lines (2 loc) 44.4 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TurboMap={})}(this,function(e){"use strict";class t{static isPrimitive(e){return null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e||"symbol"==typeof e||"bigint"==typeof e}static isSimpleObject(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;if(e instanceof Date||e instanceof RegExp||e instanceof Error||e instanceof Map||e instanceof Set)return!1;if("function"==typeof e)return!1;try{const t=Object.keys(e);if(t.length>0){const r=t[0];if(void 0!==r){const t=Object.getOwnPropertyDescriptor(e,r);if(t&&(t.get||t.set))return!1}}return t.length<=5&&t.every(t=>{const r=e[t];return!(!this.isPrimitive(r)&&null!==r)||"object"==typeof r&&null!==r&&this.isSimpleObject(r)})}catch{return!1}}static getObjectSignature(e){if(this.isPrimitive(e))return"primitive:"+typeof e;if(Array.isArray(e)){const t=e.map(e=>"string"==typeof e?`str:${e}`:"number"==typeof e?`num:${e}`:"boolean"==typeof e?`bool:${e}`:null===e?"null":"object"==typeof e?this.getObjectSignature(e):typeof e).join(",");return`array:${e.length}:${t}`}if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp";if(e instanceof Error)return"error";if("function"==typeof e)return"function";try{const t=Object.keys(e).sort(),r=t.slice(0,3).join(","),i=t.slice(0,2).map(t=>{const r=e[t];return"string"==typeof r?`str:${r}`:"number"==typeof r?`num:${r}`:"boolean"==typeof r?`bool:${r}`:null===r?"null":"object"==typeof r?this.getObjectSignature(r):typeof r}).join(",");return`object:${t.length}:${r}:${i}`}catch{return"unknown"}}static safeAccess(e,t,r){try{if(null==e)return r;const i=t();return void 0!==i?i:r}catch{return r}}static isSerializable(e,t=new WeakSet){try{return this.isPrimitive(e)?"symbol"!=typeof e&&void 0!==e:"object"==typeof e&&null!==e&&(!t.has(e)&&(t.add(e),Array.isArray(e)?e.every(e=>this.isSerializable(e,t)):Object.values(e).every(e=>this.isSerializable(e,t))))}catch{return!1}}}class r{weakSetPool=[];mapPool=[];arrayPool=[];objectPool=[];maxPoolSize=50;getWeakSet(){const e=this.weakSetPool.pop();return e||new WeakSet}releaseWeakSet(e){try{this.weakSetPool.length<this.maxPoolSize&&this.weakSetPool.push(e)}catch(e){}}getMap(){const e=this.mapPool.pop();return e?(e.clear(),e):new Map}releaseMap(e){try{this.mapPool.length<this.maxPoolSize&&(e.clear(),this.mapPool.push(e))}catch(e){}}getArray(){const e=this.arrayPool.pop();return e?(e.length=0,e):[]}releaseArray(e){try{this.arrayPool.length<this.maxPoolSize&&(e.length=0,this.arrayPool.push(e))}catch(e){}}getObject(){const e=this.objectPool.pop();if(e){for(const t in e)delete e[t];return e}return{}}releaseObject(e){try{if(this.objectPool.length<this.maxPoolSize){for(const t in e)delete e[t];this.objectPool.push(e)}}catch(e){}}getStats(){return{weakSetPool:this.weakSetPool.length,mapPool:this.mapPool.length,arrayPool:this.arrayPool.length,objectPool:this.objectPool.length,totalSize:this.weakSetPool.length+this.mapPool.length+this.arrayPool.length+this.objectPool.length}}clear(){this.weakSetPool.length=0,this.mapPool.length=0,this.arrayPool.length=0,this.objectPool.length=0}}const i=new r;class s{strategyCache=new Map;hitCount=0;totalCount=0;constructor(){this.initializeStrategies()}initializeStrategies(){this.strategyCache.set("primitive:number",e=>`num:${e}`),this.strategyCache.set("primitive:string",e=>`str:${e}`),this.strategyCache.set("primitive:boolean",e=>`bool:${e}`),this.strategyCache.set("primitive:null",()=>"null"),this.strategyCache.set("primitive:undefined",()=>"undefined"),this.strategyCache.set("primitive:symbol",e=>`sym:${e.toString()}`),this.strategyCache.set("primitive:bigint",e=>`big:${e.toString()}`),this.strategyCache.set("date",e=>`d:${e.getTime()}`),this.strategyCache.set("regexp",e=>`r:${e.toString()}`),this.strategyCache.set("error",e=>`err:${e.name}:${e.message}`),this.strategyCache.set("function",e=>`fn:${e.name||"anonymous"}:${e.length}`),this.strategyCache.set("array",e=>{const t=e;if(0===t.length)return"arr:[]";const r=t.map(e=>this.isPrimitive(e)?String(e):"complex");return`arr:${t.length}:${r.join(",")}`});for(let e=0;e<=5;e++)this.strategyCache.set(`object:${e}:`,e=>this.hashSimpleObject(e))}isPrimitive(e){return null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e||"symbol"==typeof e||"bigint"==typeof e}fastHash(e){this.totalCount++;try{const r=t.getObjectSignature(e),i=this.strategyCache.get(r);if(i){const t=i(e);if(t)return this.hitCount++,t}if(this.isPrimitive(e)){const t=null===e?"null":typeof e,i=this.strategyCache.get(`primitive:${t}`);if(i){const t=i(e);if(t)return this.strategyCache.set(r,i),t}}if(e instanceof Date){const t=this.strategyCache.get("date");if(t){const i=t(e);if(i)return this.strategyCache.set(r,t),i}}if(e instanceof RegExp){const t=this.strategyCache.get("regexp");if(t){const i=t(e);if(i)return this.strategyCache.set(r,t),i}}if(e instanceof Error){const t=this.strategyCache.get("error");if(t){const i=t(e);if(i)return this.strategyCache.set(r,t),i}}if("function"==typeof e){const t=this.strategyCache.get("function");if(t){const i=t(e);if(i)return this.strategyCache.set(r,t),i}}if(Array.isArray(e)){const t=this.strategyCache.get("array");if(t){const i=t(e);if(i)return this.strategyCache.set(r,t),i}const i=this.hashSimpleArray(e);if(i)return this.strategyCache.set(r,e=>this.hashSimpleArray(e)),i}if("object"==typeof e&&null!==e){const t=Object.keys(e);for(let i=0;i<=5;i++)if(t.length<=i){const t=this.strategyCache.get(`object:${i}:`);if(t){const i=t(e);if(i)return this.strategyCache.set(r,t),i}}}for(const[t,i]of this.strategyCache.entries())if(!t.startsWith("object:")&&!t.startsWith("primitive:")){const t=i(e);if(t)return this.strategyCache.set(r,i),t}const s=this.hashSimpleObject(e);return s?(this.strategyCache.set(r,e=>this.hashSimpleObject(e)),s):null}catch{return null}}hashSimpleObject(e,t=0,r=new WeakSet){try{if(t>10)return"obj:max_depth";if("object"!=typeof e||null===e)return null;if(r.has(e)){return`obj:circular:${this.getObjectId(e)}`}r.add(e);const i=Object.keys(e).sort();if(0===i.length)return"obj:{}";return`obj:{${i.map(i=>{const s=e[i];if(this.isPrimitive(s))return`${i}:${s}`;if("object"==typeof s&&null!==s){if(Array.isArray(s)){return`${i}:${this.hashSimpleArray(s)||"complex"}`}return`${i}:${this.hashSimpleObject(s,t+1,r)||"complex"}`}return`${i}:complex`}).join(",")}}`}catch{return null}}hashSimpleArray(e){try{if(0===e.length)return"arr:[]";const t=e.map(e=>this.isPrimitive(e)?String(e):"complex");return`arr:${e.length}:${t.join(",")}`}catch{return null}}getObjectId(e){return`ref_${Math.random().toString(36).substr(2,9)}_${Date.now()}`}getStats(){return{hitCount:this.hitCount,totalCount:this.totalCount,hitRate:this.totalCount>0?this.hitCount/this.totalCount:0,strategies:this.strategyCache.size}}resetStats(){this.hitCount=0,this.totalCount=0}addStrategy(e,t){try{"string"==typeof e&&"function"==typeof t&&this.strategyCache.set(e,t)}catch(e){}}}const a=new s,n=globalThis,o=(e,t)=>n.setTimeout(e,t),c=e=>n.clearTimeout(e);var l,h;e.RecoveryAction=void 0,(l=e.RecoveryAction||(e.RecoveryAction={})).RETRY="retry",l.FALLBACK_MODE="fallback",l.SKIP="skip",l.ABORT="abort",e.ErrorType=void 0,(h=e.ErrorType||(e.ErrorType={})).SERIALIZATION="serialization",h.CACHE="cache",h.ITERATION="iteration",h.PLUGIN="plugin",h.MEMORY="memory",h.UNKNOWN="unknown";class u{errorHistory=new Map;errorStats;policies=new Map;globalFallbackMode=!1;constructor(){this.errorStats={total:0,byType:Object.fromEntries(Object.values(e.ErrorType).map(e=>[e,0])),byOperation:{},recoveryActions:Object.fromEntries(Object.values(e.RecoveryAction).map(e=>[e,0]))},this.initializePolicies()}initializePolicies(){this.policies.set(e.ErrorType.SERIALIZATION,{maxRetries:2,retryDelay:0,escalationThreshold:5,fallbackMode:!0}),this.policies.set(e.ErrorType.CACHE,{maxRetries:3,retryDelay:10,escalationThreshold:10,fallbackMode:!0}),this.policies.set(e.ErrorType.ITERATION,{maxRetries:1,retryDelay:0,escalationThreshold:3,fallbackMode:!0}),this.policies.set(e.ErrorType.PLUGIN,{maxRetries:0,retryDelay:0,escalationThreshold:1,fallbackMode:!1}),this.policies.set(e.ErrorType.MEMORY,{maxRetries:0,retryDelay:0,escalationThreshold:1,fallbackMode:!0}),this.policies.set(e.ErrorType.UNKNOWN,{maxRetries:1,retryDelay:100,escalationThreshold:5,fallbackMode:!0})}handleError(t,r,i=e.ErrorType.UNKNOWN){try{if(this.updateStats(t,r,i),this.globalFallbackMode)return this.errorStats.recoveryActions[e.RecoveryAction.FALLBACK_MODE]++,e.RecoveryAction.FALLBACK_MODE;const s=this.policies.get(i)||this.policies.get(e.ErrorType.UNKNOWN),a=`${r}:${i}`,n=this.errorHistory.get(a)||0;let o;return this.errorHistory.set(a,n+1),n>=s.escalationThreshold?s.fallbackMode?(o=e.RecoveryAction.FALLBACK_MODE,this.globalFallbackMode=!0):o=e.RecoveryAction.SKIP:n<s.maxRetries?(o=e.RecoveryAction.RETRY,s.retryDelay):o=s.fallbackMode?e.RecoveryAction.FALLBACK_MODE:e.RecoveryAction.SKIP,this.errorStats.recoveryActions[o]++,o}catch(t){return this.errorStats.recoveryActions[e.RecoveryAction.ABORT]++,e.RecoveryAction.ABORT}}updateStats(e,t,r){try{this.errorStats.total++,this.errorStats.byType[r]++,this.errorStats.byOperation[t]=(this.errorStats.byOperation[t]||0)+1,this.errorStats.lastError={type:r,operation:t,message:e.message,timestamp:Date.now()}}catch(e){}}executeWithRecovery(t,r,i,s=e.ErrorType.UNKNOWN){try{return t()}catch(a){switch(this.handleError(a,i,s)){case e.RecoveryAction.RETRY:try{return t()}catch(e){return r()}case e.RecoveryAction.FALLBACK_MODE:case e.RecoveryAction.SKIP:return r();case e.RecoveryAction.ABORT:default:throw a}}}async executeAsyncWithRecovery(t,r,i,s=e.ErrorType.UNKNOWN){try{return await t()}catch(a){switch(this.handleError(a,i,s)){case e.RecoveryAction.RETRY:try{const e=this.policies.get(s);return e&&e.retryDelay>0&&await this.delay(e.retryDelay),await t()}catch(e){return await r()}case e.RecoveryAction.FALLBACK_MODE:case e.RecoveryAction.SKIP:return await r();case e.RecoveryAction.ABORT:default:throw a}}}delay(e){return new Promise(t=>o(t,e))}resetErrorHistory(e,t){try{if(e&&t){const r=`${e}:${t}`;this.errorHistory.delete(r)}else if(e)for(const t of this.errorHistory.keys())t.startsWith(`${e}:`)&&this.errorHistory.delete(t);else this.errorHistory.clear(),this.globalFallbackMode=!1}catch(e){}}getStats(){return{...this.errorStats}}setPolicy(e,t){try{this.policies.set(e,{...t})}catch(e){}}getPolicy(e){try{const t=this.policies.get(e);return t?{...t}:void 0}catch(e){return}}isInFallbackMode(){return this.globalFallbackMode}exitFallbackMode(){this.globalFallbackMode=!1,this.errorHistory.clear()}getHealthStatus(){try{const t=Object.values(this.errorStats.byOperation).reduce((e,t)=>e+t,0),r=t>0?this.errorStats.total/t:0;return{healthy:r<.1&&!this.globalFallbackMode,errorRate:r,totalErrors:this.errorStats.total,inFallbackMode:this.globalFallbackMode,criticalErrors:this.errorStats.byType[e.ErrorType.MEMORY]+this.errorStats.byType[e.ErrorType.UNKNOWN],status:this.globalFallbackMode?"degraded":r>.2?"warning":r>.1?"caution":"healthy"}}catch(e){return{healthy:!1,errorRate:1,totalErrors:this.errorStats.total,inFallbackMode:!0,criticalErrors:999,status:"unknown"}}}}const y=new u;class p{cache=new Map;head;tail;maxSize;stats;constructor(e=1e3){this.maxSize=e,this.stats={hits:0,misses:0,sets:0,deletes:0,evictions:0,hitRate:0,size:0,maxSize:e}}get(e){try{const t=this.cache.get(e);return t?(this.stats.hits++,this.updateAccess(t),this.moveToHead(t),t.value):(this.stats.misses++,void this.updateHitRate())}catch(e){return this.stats.misses++,void this.updateHitRate()}}set(e,t){try{this.stats.sets++;const r=this.cache.get(e);if(r)return r.value=t,this.updateAccess(r),void this.moveToHead(r);const i={key:e,value:t,prev:void 0,next:void 0,frequency:1,lastAccess:Date.now()};this.cache.set(e,i),this.addToHead(i),this.stats.size++,this.cache.size>this.maxSize&&this.removeTail(),this.updateHitRate()}catch(e){}}delete(e){try{const t=this.cache.get(e);return!!t&&(this.removeNode(t),this.cache.delete(e),this.stats.deletes++,this.stats.size--,this.updateHitRate(),!0)}catch(e){return!1}}updateAccess(e){try{e.frequency=(e.frequency||0)+1,e.lastAccess=Date.now()}catch(e){}}moveToHead(e){try{if(!e)return;this.removeNode(e),this.addToHead(e)}catch(e){}}addToHead(e){try{if(!e)return;e.prev=void 0,e.next=this.head,this.head&&(this.head.prev=e),this.head=e,this.tail||(this.tail=e)}catch(e){}}removeNode(e){try{if(!e)return;e.prev?e.prev.next=e.next:this.head=e.next,e.next?e.next.prev=e.prev:this.tail=e.prev}catch(e){}}removeTail(){try{this.tail&&(this.cache.delete(this.tail.key),this.removeNode(this.tail),this.stats.evictions++,this.stats.size--)}catch(e){}}updateHitRate(){const e=this.stats.hits+this.stats.misses;this.stats.hitRate=e>0?this.stats.hits/e:0}getStats(){return{...this.stats}}clear(){try{this.cache.clear(),this.head=void 0,this.tail=void 0,this.stats.size=0}catch(e){}}get size(){return this.cache.size}}class g{l1Cache;l2Cache;promoteThreshold;accessCounts=new Map;constructor(e){const t=Math.max(1,e.l1CacheSize||100),r=Math.max(1,e.l2CacheSize||1e3),i=Math.max(1,e.promoteThreshold||3);this.l1Cache=new p(t),this.l2Cache=new p(r),this.promoteThreshold=i}get(e){try{let t=this.l1Cache.get(e);return void 0!==t?t:(t=this.l2Cache.get(e),void 0!==t?(this.trackAccess(e),t):void 0)}catch(e){return}}set(e,t){try{this.l2Cache.set(e,t)}catch(e){}}trackAccess(e){try{const t=(this.accessCounts.get(e)||0)+1;if(this.accessCounts.set(e,t),t>=this.promoteThreshold){const t=this.l2Cache.get(e);void 0!==t&&this.l1Cache.set(e,t),this.accessCounts.delete(e)}}catch(e){}}delete(e){try{const t=this.l1Cache.delete(e),r=this.l2Cache.delete(e);return this.accessCounts.delete(e),t||r}catch(e){return!1}}getStats(){try{const e=this.l1Cache.getStats(),t=this.l2Cache.getStats();return{l1:e,l2:t,combined:{hits:e.hits+t.hits,misses:e.misses+t.misses,hitRate:(e.hits+t.hits)/(e.hits+t.hits+e.misses+t.misses),totalSize:e.size+t.size,pendingPromotions:this.accessCounts.size}}}catch(e){return{l1:this.l1Cache.getStats(),l2:this.l2Cache.getStats(),combined:{hits:0,misses:0,hitRate:0,totalSize:0,pendingPromotions:0}}}}clear(){try{this.l1Cache.clear(),this.l2Cache.clear(),this.accessCounts.clear()}catch(e){}}}class m{strategies=new Map;strategyStats=new Map;cache;enableMetrics;objectIdMap=new WeakMap;constructor(e=!0,t=!0){this.cache=e?new g({l1CacheSize:1e3,l2CacheSize:5e3,promoteThreshold:3}):void 0,this.enableMetrics=t,this.initializeStrategies()}initializeStrategies(){this.addStrategy({name:"primitive",priority:100,canHandle:e=>t.isPrimitive(e),serialize:e=>null===e?"null":void 0===e?"undefined":"string"==typeof e?`"${e}"`:"symbol"==typeof e?this.serializeSymbol(e):"bigint"==typeof e?`${e}n`:String(e)}),this.addStrategy({name:"simpleObject",priority:95,canHandle:e=>t.isSimpleObject(e),serialize:(e,t)=>{try{const r=Object.keys(e).sort();return`{${r.map(r=>{const i=e[r];return`"${r}":${this.serializeValue(i,t)}`}).join(",")}}`}catch{return this.fallbackSerialize(e)}}}),this.addStrategy({name:"simpleArray",priority:90,canHandle:e=>Array.isArray(e)&&e.length<=10&&e.every(e=>t.isPrimitive(e)),serialize:e=>`[${e.map(e=>null===e?"null":void 0===e?"undefined":"string"==typeof e?`"${e}"`:String(e)).join(",")}]`}),this.addStrategy({name:"date",priority:85,canHandle:e=>e instanceof Date,serialize:e=>`[Date:${e.getTime()}]`}),this.addStrategy({name:"regexp",priority:85,canHandle:e=>e instanceof RegExp,serialize:e=>`[RegExp:${e.toString()}]`}),this.addStrategy({name:"error",priority:85,canHandle:e=>e instanceof Error,serialize:e=>`[Error:${e.name}:${e.message}]`}),this.addStrategy({name:"function",priority:80,canHandle:e=>"function"==typeof e,serialize:e=>`[Function:${e.name||"anonymous"}:${e.length}]`}),this.addStrategy({name:"complex",priority:75,canHandle:()=>!0,serialize:(e,t)=>this.deepSerialize(e,t)}),this.addStrategy({name:"fastHash",priority:10,canHandle:e=>null!==a.fastHash(e),serialize:e=>a.fastHash(e)||this.fallbackSerialize(e)})}addStrategy(e){try{this.strategies.set(e.name,e),this.strategyStats.set(e.name,{usage:0,avgTime:0})}catch(e){}}serialize(e){try{if(this.cache&&"object"==typeof e&&null!==e){const t=this.cache.get(this.getObjectId(e));if(void 0!==t)return t}const t={visited:new WeakSet,cache:this.cache,depth:0,maxDepth:50};try{const r=this.serializeValue(e,t);return this.cache&&"object"==typeof e&&null!==e&&this.cache.set(this.getObjectId(e),r),r}finally{}}catch(t){return this.fallbackSerialize(e)}}serializeValue(e,t){try{if(t.depth>t.maxDepth)return"[MaxDepthExceeded]";if("object"==typeof e&&null!==e&&t.visited.has(e)){return`[Circular:${this.getObjectId(e)}]`}const r=Array.from(this.strategies.values()).sort((e,t)=>t.priority-e.priority);for(const i of r)try{if(i.canHandle(e)){const r=this.enableMetrics?performance.now():0;"object"==typeof e&&null!==e&&t.visited.add(e);const s=i.serialize(e,{...t,depth:t.depth+1});return this.enableMetrics&&this.updateStrategyStats(i.name,performance.now()-r),s}}catch(e){continue}return this.fallbackSerialize(e)}catch(t){return this.fallbackSerialize(e)}}deepSerialize(e,t){try{if(Array.isArray(e)){return`[${e.map(e=>this.serializeValue(e,t)).join(",")}]`}if(e&&"object"==typeof e){const r=Object.keys(e).sort();return`{${r.map(r=>{try{return`"${r}":${this.serializeValue(e[r],t)}`}catch{return`"${r}":"[SerializationError]"`}}).join(",")}}`}return this.fallbackSerialize(e)}catch{return this.fallbackSerialize(e)}}fallbackSerialize(e){try{if(null===e)return"null";if(void 0===e)return"undefined";if("string"==typeof e)return`"${e}"`;if("number"==typeof e)return String(e);if("boolean"==typeof e)return String(e);if("symbol"==typeof e)return this.serializeSymbol(e);if("bigint"==typeof e)return`${e}n`;try{return JSON.stringify(e)||"[UnserializableObject]"}catch{return`[${typeof e}:${Object.prototype.toString.call(e)}]`}}catch{return"[CriticalSerializationError]"}}serializeSymbol(e){try{const t=Symbol.keyFor(e);return void 0!==t?`Symbol.for("${t}")`:"Symbol()"}catch{return`Symbol(${e.toString()})`}}getObjectId(e){try{if("object"==typeof e&&null!==e){if(this.objectIdMap.has(e))return this.objectIdMap.get(e);const t=`obj_${Math.random().toString(36).substr(2,9)}`;return this.objectIdMap.set(e,t),t}return`obj_${t.getObjectSignature(e)}`}catch{return"obj_unknown"}}updateStrategyStats(e,t){try{const r=this.strategyStats.get(e);r&&(r.usage++,r.avgTime=(r.avgTime*(r.usage-1)+t)/r.usage)}catch(e){}}getStats(){try{const e=Object.fromEntries(this.strategyStats),t=this.cache?.getStats();return{strategies:e,cache:t,fastHash:a.getStats(),totalStrategies:this.strategies.size}}catch(e){return{strategies:{},cache:null,fastHash:null,totalStrategies:0}}}resetStats(){try{this.strategyStats.forEach(e=>{e.usage=0,e.avgTime=0}),this.cache?.clear(),a.resetStats()}catch(e){}}clearCache(){try{this.cache?.clear()}catch(e){}}}const d=new m;class f{syncMap;options;constructor(e,t={}){this.syncMap=e,this.options={batchSize:100,delayBetweenBatches:1,maxConcurrency:10,timeoutMs:3e4,enableProgress:!1,...t}}async setAsync(t,r){return y.executeAsyncWithRecovery(async()=>(await this.nextTick(),this.syncMap.set(t,r),this),async()=>this,"setAsync",e.ErrorType.UNKNOWN)}async getAsync(t){return y.executeAsyncWithRecovery(async()=>(await this.nextTick(),this.syncMap.get(t)),async()=>{},"getAsync",e.ErrorType.UNKNOWN)}async hasAsync(t){return y.executeAsyncWithRecovery(async()=>(await this.nextTick(),this.syncMap.has(t)),async()=>!1,"hasAsync",e.ErrorType.UNKNOWN)}async deleteAsync(t){return y.executeAsyncWithRecovery(async()=>(await this.nextTick(),this.syncMap.delete(t)),async()=>!1,"deleteAsync",e.ErrorType.UNKNOWN)}async clearAsync(){return y.executeAsyncWithRecovery(async()=>{await this.nextTick(),this.syncMap.clear()},async()=>{},"clearAsync",e.ErrorType.UNKNOWN)}async batchExecute(t){return y.executeAsyncWithRecovery(async()=>{const e=[],{batchSize:r=100,delayBetweenBatches:i=1}=this.options;for(let s=0;s<t.length;s+=r){const a=t.slice(s,s+r),n=await this.processBatch(a);e.push(...n),s+r<t.length&&i>0&&await this.delay(i)}return e},async()=>[],"batchExecute",e.ErrorType.UNKNOWN)}async processBatch(e){const t=[];for(const r of e)try{let e,i=!0;switch(r.type){case"set":void 0!==r.value?(this.syncMap.set(r.key,r.value),e=!0):i=!1;break;case"get":e=this.syncMap.get(r.key);break;case"delete":e=this.syncMap.delete(r.key);break;case"has":e=this.syncMap.has(r.key);break;default:i=!1}t.push({id:r.id,success:i,data:e,error:void 0})}catch(e){t.push({id:r.id,success:!1,data:void 0,error:e})}return t}async setAllAsync(t){return y.executeAsyncWithRecovery(async()=>{const e=t.map(([e,t],r)=>({type:"set",key:e,value:t,id:r}));return await this.batchExecute(e),this},async()=>this,"setAllAsync",e.ErrorType.UNKNOWN)}async getAllAsync(t){return y.executeAsyncWithRecovery(async()=>{const e=t.map((e,t)=>({type:"get",key:e,value:void 0,id:t}));return(await this.batchExecute(e)).map(e=>e.data)},async()=>[],"getAllAsync",e.ErrorType.UNKNOWN)}async deleteAllAsync(t){return y.executeAsyncWithRecovery(async()=>{const e=t.map((e,t)=>({type:"delete",key:e,value:void 0,id:t}));return(await this.batchExecute(e)).map(e=>e.data)},async()=>[],"deleteAllAsync",e.ErrorType.UNKNOWN)}async sizeAsync(){return y.executeAsyncWithRecovery(async()=>(await this.nextTick(),this.syncMap.size),async()=>0,"sizeAsync",e.ErrorType.UNKNOWN)}stream(){return new b(this.syncMap,this.options)}async*entriesAsync(){try{const e=Array.from(this.syncMap.entries()),{batchSize:t=100,delayBetweenBatches:r=1}=this.options;for(let i=0;i<e.length;i+=t){const s=e.slice(i,i+t);for(const e of s)yield e;i+t<e.length&&r>0&&await this.delay(r)}}catch(e){}}async*keysAsync(){for await(const[e]of this.entriesAsync())yield e}async*valuesAsync(){for await(const[,e]of this.entriesAsync())yield e}async nextTick(){return new Promise(e=>o(e,0))}async delay(e){return new Promise(t=>o(t,e))}}class b{entries;options;constructor(e,t){this.entries=Array.from(e.entries()),this.options=t}filter(e){const t=new b(new Map,this.options);return t.filterPredicate=e,t.sourceEntries=this.entries,t}map(e){const t=new b(new Map,this.options);return t.mapTransform=e,t.sourceEntries=this.entries,t}async forEach(t){return y.executeAsyncWithRecovery(async()=>{const{batchSize:e=100,delayBetweenBatches:r=1}=this.options;for(let i=0;i<this.entries.length;i+=e){const s=this.entries.slice(i,i+e);for(const e of s)await t(e);i+e<this.entries.length&&r>0&&await this.delay(r)}},async()=>{},"streamForEach",e.ErrorType.ITERATION)}async collect(){return y.executeAsyncWithRecovery(async()=>new Map(this.entries),async()=>new Map,"streamCollect",e.ErrorType.UNKNOWN)}async toArray(){return y.executeAsyncWithRecovery(async()=>[...this.entries],async()=>[],"streamToArray",e.ErrorType.UNKNOWN)}async reduce(t,r){return y.executeAsyncWithRecovery(async()=>{let e=r;const{batchSize:i=100,delayBetweenBatches:s=1}=this.options;for(let r=0;r<this.entries.length;r+=i){const a=this.entries.slice(r,r+i);for(const r of a)e=await t(e,r);r+i<this.entries.length&&s>0&&await this.delay(s)}return e},async()=>r,"streamReduce",e.ErrorType.UNKNOWN)}async delay(e){return new Promise(t=>o(t,e))}}class S{plugins=new Map;pluginStats=new Map;options;globalEnabled=!0;constructor(e={}){this.options={enableStats:!0,maxExecutionTime:100,enableErrorRecovery:!0,pluginTimeout:5e3,...e}}async addPlugin(t){return y.executeAsyncWithRecovery(async()=>{if(!t||"object"!=typeof t)throw new Error("Invalid plugin: must be an object");if(!t.name||"string"!=typeof t.name)throw new Error("Invalid plugin: must have a string name property");return this.plugins.has(t.name),t.onInstall&&await this.executeWithTimeout(()=>t.onInstall(),this.options.pluginTimeout,`install:${t.name}`),t.enabled=!1!==t.enabled,t.priority=t.priority||0,this.plugins.set(t.name,t),this.pluginStats.set(t.name,{name:t.name,executions:0,errors:0,totalTime:0,averageTime:0,enabled:t.enabled}),t.enabled&&t.onEnable&&await this.executeWithTimeout(()=>t.onEnable(),this.options.pluginTimeout,`enable:${t.name}`),!0},async()=>!1,"addPlugin",e.ErrorType.PLUGIN)}async removePlugin(t){return y.executeAsyncWithRecovery(async()=>{if("string"!=typeof t)throw new Error("Plugin name must be a string");const e=this.plugins.get(t);return!!e&&(e.enabled&&e.onDisable&&await this.executeWithTimeout(()=>e.onDisable(),this.options.pluginTimeout,`disable:${t}`),e.onUninstall&&await this.executeWithTimeout(()=>e.onUninstall(),this.options.pluginTimeout,`uninstall:${t}`),this.plugins.delete(t),this.pluginStats.delete(t),!0)},async()=>!1,"removePlugin",e.ErrorType.PLUGIN)}async enablePlugin(t){return y.executeAsyncWithRecovery(async()=>{const e=this.plugins.get(t);if(!e)return!1;if(e.enabled)return!0;e.enabled=!0,e.onEnable&&await this.executeWithTimeout(()=>e.onEnable(),this.options.pluginTimeout,`enable:${t}`);const r=this.pluginStats.get(t);return r&&(r.enabled=!0),!0},async()=>!1,"enablePlugin",e.ErrorType.PLUGIN)}async disablePlugin(t){return y.executeAsyncWithRecovery(async()=>{const e=this.plugins.get(t);if(!e)return!1;if(!e.enabled)return!0;e.enabled=!1,e.onDisable&&await this.executeWithTimeout(()=>e.onDisable(),this.options.pluginTimeout,`disable:${t}`);const r=this.pluginStats.get(t);return r&&(r.enabled=!1),!0},async()=>!1,"disablePlugin",e.ErrorType.PLUGIN)}executeBefore(e,t,...r){if(!this.globalEnabled)return r[0];const i=this.getActivePlugins();let s=r[0];for(const a of i)try{const t=a[e];if("function"==typeof t){const e=performance.now(),i=t.apply(a,r);null!=i&&(s=i),this.options.enableStats&&this.updateStats(a.name,performance.now()-e,!1)}}catch(e){this.handlePluginError(a,e,t)}return s}executeAfter(e,t,...r){if(!this.globalEnabled)return r[0];const i=this.getActivePlugins();let s=r[0];for(const a of i)try{const t=a[e];if("function"==typeof t){const e=performance.now(),i=t.apply(a,r);null!=i&&(s=i),this.options.enableStats&&this.updateStats(a.name,performance.now()-e,!1)}}catch(e){this.handlePluginError(a,e,t)}return s}getActivePlugins(){return Array.from(this.plugins.values()).filter(e=>!1!==e.enabled).sort((e,t)=>(t.priority||0)-(e.priority||0))}handlePluginError(t,r,i){if(this.options.enableStats&&this.updateStats(t.name,0,!0),this.options.enableErrorRecovery){y.handleError(r,`plugin:${t.name}:${i.operation}`,e.ErrorType.PLUGIN)===y.constructor.name&&(t.enabled=!1)}try{t.onError&&t.onError(r,i.operation,i.key)}catch(e){}}updateStats(e,t,r){try{const i=this.pluginStats.get(e);i&&(i.executions++,r?i.errors++:(i.totalTime+=t,i.averageTime=i.totalTime/(i.executions-i.errors)),i.lastExecution=Date.now())}catch(e){}}async executeWithTimeout(e,t,r){return new Promise((i,s)=>{const a=o(()=>{s(new Error(`Plugin operation timed out: ${r}`))},t);try{const t=e();t instanceof Promise?t.then(e=>{c(a),i(e)}).catch(e=>{c(a),s(e)}):(c(a),i(t))}catch(e){c(a),s(e)}})}getPlugin(e){return this.plugins.get(e)}getAllPlugins(){return Array.from(this.plugins.values())}getPluginStats(e){if(e){const t=this.pluginStats.get(e);return t?{...t}:{name:e,executions:0,errors:0,totalTime:0,averageTime:0,enabled:!1}}return Array.from(this.pluginStats.values()).map(e=>({...e}))}clearStats(){for(const e of this.pluginStats.values())e.executions=0,e.errors=0,e.totalTime=0,e.averageTime=0,delete e.lastExecution}setGlobalEnabled(e){this.globalEnabled=e}isGlobalEnabled(){return this.globalEnabled}getStatus(){const e=Array.from(this.plugins.values()),t=Array.from(this.pluginStats.values());return{totalPlugins:e.length,enabledPlugins:e.filter(e=>!1!==e.enabled).length,totalExecutions:t.reduce((e,t)=>e+t.executions,0),totalErrors:t.reduce((e,t)=>e+t.errors,0),globalEnabled:this.globalEnabled,averageExecutionTime:this.calculateAverageExecutionTime(),errorRate:this.calculateErrorRate()}}calculateAverageExecutionTime(){const e=Array.from(this.pluginStats.values()),t=e.reduce((e,t)=>e+t.totalTime,0),r=e.reduce((e,t)=>e+(t.executions-t.errors),0);return r>0?t/r:0}calculateErrorRate(){const e=Array.from(this.pluginStats.values()),t=e.reduce((e,t)=>e+t.errors,0),r=e.reduce((e,t)=>e+t.executions,0);return r>0?t/r:0}}class v{operations=new Map;trends=[];maxTrendEntries=1e3;trackOperation(e,t){try{const r=this.operations.get(e),i=Date.now();r?(r.count++,r.totalTime+=t,r.minTime=Math.min(r.minTime,t),r.maxTime=Math.max(r.maxTime,t),r.lastExecuted=i):this.operations.set(e,{count:1,totalTime:t,minTime:t,maxTime:t,lastExecuted:i}),this.trends.push({timestamp:i,operation:e,duration:t}),this.trends.length>this.maxTrendEntries&&(this.trends=this.trends.slice(-this.maxTrendEntries))}catch(e){}}getProfile(){try{const e={};for(const[t,r]of this.operations)e[t]={count:r.count,totalTime:r.totalTime,averageTime:r.totalTime/r.count,minTime:r.minTime,maxTime:r.maxTime,lastExecuted:r.lastExecuted};return{operations:e,hotspots:Array.from(this.operations.entries()).map(([e,t])=>({operation:e,averageTime:t.totalTime/t.count,count:t.count})).sort((e,t)=>t.averageTime-e.averageTime).slice(0,10),trends:[...this.trends]}}catch(e){return{operations:{},hotspots:[],trends:[]}}}reset(){this.operations.clear(),this.trends.length=0}getOperationStats(e){const t=this.operations.get(e);return t?{count:t.count,totalTime:t.totalTime,averageTime:t.totalTime/t.count,minTime:t.minTime,maxTime:t.maxTime,lastExecuted:t.lastExecuted}:null}}class T{memoryTrend=[];maxTrendEntries=500;analyzeMap(e){try{const t=this.getNodeMemoryUsage(),r=this.estimateMapSize(e),i=this.analyzeKeyDistribution(e),s=this.findLargestKeys(e);return this.updateMemoryTrend(t.heapUsed),{heapUsed:t.heapUsed,heapTotal:t.heapTotal,external:t.external,estimatedMapSize:r,keyDistribution:i,largestKeys:s,memoryTrend:[...this.memoryTrend]}}catch(e){return{heapUsed:0,heapTotal:0,external:0,estimatedMapSize:0,keyDistribution:{},largestKeys:[],memoryTrend:[]}}}getNodeMemoryUsage(){try{const e=globalThis;if(void 0!==e.process&&e.process.memoryUsage)return e.process.memoryUsage()}catch{}return{heapUsed:0,heapTotal:0,external:0,rss:0}}estimateMapSize(e){try{if(0===e.size)return 0;const t=Math.min(10,e.size);let r=0,i=0;for(const[s,a]of e){if(i>=t)break;const e=this.estimateObjectSize(s);r+=e+this.estimateObjectSize(a),i++}return(i>0?r/i:0)*e.size}catch(e){return 0}}estimateObjectSize(e){try{if(null==e)return 8;switch(typeof e){case"string":return 2*e.length+24;case"number":case"boolean":return 8;case"bigint":return 16;case"symbol":return 24;case"object":if(Array.isArray(e))return 24+8*e.length+e.reduce((e,t)=>e+this.estimateObjectSize(t),0);try{return 2*JSON.stringify(e).length+64}catch{return 256}case"function":return 2*e.toString().length+64;default:return 64}}catch{return 64}}analyzeKeyDistribution(e){try{const t={};for(const r of e.keys()){const e=this.getDetailedType(r);t[e]=(t[e]||0)+1}return t}catch(e){return{}}}getDetailedType(e){if(null===e)return"null";if(void 0===e)return"undefined";const t=typeof e;return"object"!==t?t:Array.isArray(e)?"array":e instanceof Date?"date":e instanceof RegExp?"regexp":e instanceof Error?"error":"object"}findLargestKeys(e){try{const t=[];for(const r of e.keys()){const e=this.estimateObjectSize(r),i=this.keyToString(r);t.push({key:i,size:e})}return t.sort((e,t)=>t.size-e.size).slice(0,10)}catch(e){return[]}}keyToString(e){try{if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return String(e);if(null===e)return"null";if(void 0===e)return"undefined";try{const t=JSON.stringify(e);return t.length>100?t.substring(0,97)+"...":t}catch{return Object.prototype.toString.call(e)}}catch{return"[UnknownKey]"}}updateMemoryTrend(e){try{this.memoryTrend.push({timestamp:Date.now(),usage:e}),this.memoryTrend.length>this.maxTrendEntries&&(this.memoryTrend=this.memoryTrend.slice(-this.maxTrendEntries))}catch(e){}}}class A{performanceMonitor=new v;memoryAnalyzer=new T;generateReport(e,t,r,i){try{const s=this.performanceMonitor.getProfile(),a=this.memoryAnalyzer.analyzeMap(e),n=this.generateErrorAnalysis(t),o=this.generateOptimizationSuggestions(s,a,n,r,i),c=this.calculateHealthScore(s,a,n);return{performanceProfile:s,memoryUsage:a,errorAnalysis:n,optimizationSuggestions:o,healthScore:c,recommendations:this.generateRecommendations(o)}}catch(e){return this.getEmptyReport()}}trackOperation(e,t){this.performanceMonitor.trackOperation(e,t)}generateErrorAnalysis(e){return e?{totalErrors:e.total||0,errorsByType:e.byType||{},errorsByOperation:e.byOperation||{},recentErrors:e.recentErrors||[],errorTrends:e.trends||[]}:{totalErrors:0,errorsByType:{},errorsByOperation:{},recentErrors:[],errorTrends:[]}}generateOptimizationSuggestions(e,t,r,i,s){const a=[];if(e.hotspots.length>0){const t=e.hotspots[0];t&&t.averageTime>10&&a.push({type:"performance",priority:"high",title:"慢操作优化",description:`操作 "${t.operation}" 平均执行时间为 ${t.averageTime.toFixed(2)}ms`,action:"考虑优化此操作的实现或添加缓存",impact:"可显著提高整体性能",effort:"medium"})}return t.estimatedMapSize>52428800&&a.push({type:"memory",priority:"high",title:"内存使用过高",description:`估计内存使用量为 ${(t.estimatedMapSize/1024/1024).toFixed(2)}MB`,action:"考虑实现LRU缓存或数据压缩",impact:"减少内存占用,提高系统稳定性",effort:"high"}),r.totalErrors>100&&a.push({type:"error",priority:"high",title:"错误频率过高",description:`总错误数为 ${r.totalErrors}`,action:"检查错误日志,修复主要错误源",impact:"提高系统稳定性和可靠性",effort:"medium"}),i&&i.hitRate<.5&&a.push({type:"performance",priority:"medium",title:"缓存命中率低",description:`缓存命中率为 ${(100*i.hitRate).toFixed(1)}%`,action:"调整缓存策略或增加缓存大小",impact:"提高数据访问速度",effort:"low"}),a}calculateHealthScore(e,t,r){try{let i=100;const s=Object.values(e.operations).reduce((e,t)=>e+t.averageTime,0)/Object.keys(e.operations).length;s>10?i-=20:s>5&&(i-=10);const a=t.estimatedMapSize/1024/1024;a>100?i-=30:a>50&&(i-=15);const n=Object.values(e.operations).reduce((e,t)=>e+t.count,0),o=n>0?r.totalErrors/n:0;return o>.1?i-=25:o>.05?i-=15:o>.01&&(i-=5),Math.max(0,Math.min(100,i))}catch{return 50}}generateRecommendations(e){const t=e.filter(e=>"high"===e.priority),r=[];return 0===t.length?r.push("系统运行状况良好,无需立即优化"):(r.push(`发现 ${t.length} 个高优先级优化机会`),r.push(...t.slice(0,3).map(e=>e.title))),r}getEmptyReport(){return{performanceProfile:{operations:{},hotspots:[],trends:[]},memoryUsage:{heapUsed:0,heapTotal:0,external:0,estimatedMapSize:0,keyDistribution:{},largestKeys:[],memoryTrend:[]},errorAnalysis:{totalErrors:0,errorsByType:{},errorsByOperation:{},recentErrors:[],errorTrends:[]},optimizationSuggestions:[],healthScore:0,recommendations:["无法生成诊断报告"]}}reset(){this.performanceMonitor.reset()}}const E=new A;function x(t,r){let i=null,s={};t&&Symbol.iterator in Object(t)?(i=t,s=r||{}):t&&"object"==typeof t&&(s=t);const n={enableCache:!0,cacheMaxSize:1e4,enableAdaptiveSerialization:!0,enableMetrics:!0,enableAutoCleanup:!0,cleanupInterval:3e5,enableTieredCache:!0,l1CacheSize:1e3,l2CacheSize:5e3,promoteThreshold:3,enableErrorRecovery:!0,maxRetries:3,fallbackMode:!0,enablePlugins:!0,pluginTimeout:5e3,enableDiagnostics:!0,trackPerformance:!0,enableAsync:!0,batchSize:100,maxConcurrency:10,...s};return y.executeWithRecovery(()=>function(t,r){const i=new Map,s=new Map,n=r.enablePlugins?new S({enableStats:r.enableDiagnostics,maxExecutionTime:100,enableErrorRecovery:r.enableErrorRecovery,pluginTimeout:r.pluginTimeout}):null,o=r.enableTieredCache?new g({l1CacheSize:r.l1CacheSize,l2CacheSize:r.l2CacheSize,promoteThreshold:r.promoteThreshold}):null;let c=0,l=0,h=0,u=0;const p=t=>y.executeWithRecovery(()=>{const e=r.trackPerformance?performance.now():0;if(o){let e;if(e="object"==typeof t&&null!==t?`obj_${a.fastHash(t)||Date.now()}_${Math.random()}`:"symbol"==typeof t?`symbol_skip_${Math.random()}`:String(t),"symbol"!=typeof t){const t=o.get(e);if(void 0!==t)return l++,t}h++}const i=r.enableAdaptiveSerialization?d.serialize(t):JSON.stringify(t);if(o&&"symbol"!=typeof t){const e="object"==typeof t&&null!==t?`obj_${a.fastHash(t)||Date.now()}_${Math.random()}`:String(t);o.set(e,i)}return r.trackPerformance&&E.trackOperation("serialize",performance.now()-e),i},()=>{u++;try{return JSON.stringify(t)}catch{return`[SerializationError:${typeof t}:${Date.now()}]`}},"serialize",e.ErrorType.SERIALIZATION),m={[Symbol.toStringTag]:"EnhancedTurboMap",get size(){return i.size},set:(t,a)=>y.executeWithRecovery(()=>{c++;const e=r.trackPerformance?performance.now():0,o=n?.executeBefore("beforeSet",{operation:"set",key:t,value:a,metadata:void 0,timestamp:Date.now()},t,a),l=o?.key??t,h=o?.value??a,u=p(l);return i.set(u,h),s.set(u,l),n?.executeAfter("afterSet",{operation:"set",key:l,value:h,metadata:void 0,timestamp:Date.now()},l,h),r.trackPerformance&&E.trackOperation("set",performance.now()-e),m},()=>(u++,m),"set",e.ErrorType.UNKNOWN),get:t=>y.executeWithRecovery(()=>{c++;const e=r.trackPerformance?performance.now():0,s=n?.executeBefore("beforeGet",{operation:"get",key:t,value:void 0,metadata:void 0,timestamp:Date.now()},t),a=s??t,o=p(a),l=i.get(o);let h=l;if(n&&n.getAllPlugins().length>0){h=n.executeAfter("afterGet",{operation:"get",key:a,value:l,metadata:void 0,timestamp:Date.now()},a,l)??l}return r.trackPerformance&&E.trackOperation("get",performance.now()-e),h},()=>{u++},"get",e.ErrorType.UNKNOWN),has:t=>y.executeWithRecovery(()=>{c++;const e=p(t);return i.has(e)},()=>(u++,!1),"has",e.ErrorType.UNKNOWN),delete:t=>y.executeWithRecovery(()=>{c++;const e=r.trackPerformance?performance.now():0,a=n?.executeBefore("beforeDelete",{operation:"delete",key:t,value:void 0,metadata:void 0,timestamp:Date.now()},t),o=a??t,l=p(o),h=i.delete(l);return h&&s.delete(l),n?.executeAfter("afterDelete",{operation:"delete",key:o,value:void 0,metadata:void 0,timestamp:Date.now()},o,h),r.trackPerformance&&E.trackOperation("delete",performance.now()-e),h},()=>(u++,!1),"delete",e.ErrorType.UNKNOWN),clear(){y.executeWithRecovery(()=>{c++;!1!==n?.executeBefore("beforeClear",{operation:"clear",key:void 0,value:void 0,metadata:void 0,timestamp:Date.now()})&&(i.clear(),s.clear(),n?.executeAfter("afterClear",{operation:"clear",key:void 0,value:void 0,metadata:void 0,timestamp:Date.now()}))},()=>{u++},"clear",e.ErrorType.UNKNOWN)},getSerializedKey:e=>p(e),setAll(t){return y.executeWithRecovery(()=>{if(!Array.isArray(t))throw new Error("setAll requires an array of entries");for(const[e,r]of t)this.set(e,r);return m},()=>(u++,m),"setAll",e.ErrorType.UNKNOWN)},getAll(t){return y.executeWithRecovery(()=>{if(!Array.isArray(t))throw new Error("getAll requires an array of keys");return t.map(e=>this.get(e))},()=>(u++,[]),"getAll",e.ErrorType.UNKNOWN)},deleteAll(t){return y.executeWithRecovery(()=>{if(!Array.isArray(t))throw new Error("deleteAll requires an array of keys");return t.map(e=>this.delete(e))},()=>(u++,[]),"deleteAll",e.ErrorType.UNKNOWN)},findByValue(t){return y.executeWithRecovery(()=>{if("function"!=typeof t)throw new Error("findByValue requires a function predicate");for(const[e,r]of this.entries())if(t(r,e))return[e,r]},()=>{u++},"findByValue",e.ErrorType.UNKNOWN)},filter(t){return y.executeWithRecovery(()=>{const e=[];for(const[r,i]of this.entries())t(i,r)&&e.push([r,i]);return e},()=>(u++,[]),"filter",e.ErrorType.UNKNOWN)},mapValues(t){return y.executeWithRecovery(()=>{const e=x([],r);for(const[r,i]of this.entries())e.set(r,t(i,r));return e},()=>(u++,x([],r)),"mapValues",e.ErrorType.UNKNOWN)},*entries(){try{for(const[e,t]of i.entries()){const r=s.get(e);void 0!==r&&(yield[r,t])}}catch(e){u++}},*keys(){for(const[e]of this.entries())yield e},*values(){for(const[,e]of this.entries())yield e},forEach(e){try{for(const[t,r]of this.entries())e(r,t,m)}catch(e){u++}},[Symbol.iterator](){return this.entries()},getMetrics(){return{size:this.size,operationCount:c,cacheHits:l,cacheMisses:h,cacheHitRate:c>0?l/c:0,errorCount:u,errorRate:c>0?u/c:0,pluginStats:n?.getStatus(),cacheStats:o?.getStats(),serializerStats:r.enableAdaptiveSerialization?d.getStats():null}},debug(){return{size:this.size,internalMapSize:i.size,keyMapSize:s.size,config:r,health:this.getHealthStatus(),diagnostics:this.getDiagnostics()}},getDiagnostics(){if(!r.enableDiagnostics)return null;const e=o?.getStats();return E.generateReport(i,y.getStats(),e?.combined?{hits:e.combined.hits,misses:e.combined.misses,hitRate:e.combined.hitRate,size:e.combined.totalSize}:void 0,n?.getStatus())},getHealthStatus(){const e=c>0?u/c:0,t=c>0?l/c:0;return{healthy:e<.05&&!y.isInFallbackMode(),errorRate:e,cacheHitRate:t,inFallbackMode:y.isInFallbackMode(),score:this.getDiagnostics()?.healthScore||0}},addPlugin:async e=>!!n&&n.addPlugin(e),removePlugin:async e=>!!n&&n.removePlugin(e),enablePlugin:async e=>!!n&&n.enablePlugin(e),disablePlugin:async e=>!!n&&n.disablePlugin(e),getPluginStats:()=>n?.getStatus()||null,toAsync(){if(!r.enableAsync)throw new Error("Async operations not enabled");const e=new Map;for(const[t,r]of m.entries())e.set(t,r);return new f(e,{batchSize:r.batchSize,maxConcurrency:r.maxConcurrency})},optimize(){y.executeWithRecovery(()=>{o?.clear(),d.clearCache(),y.resetErrorHistory()},()=>{},"optimize",e.ErrorType.UNKNOWN)},reset(){y.executeWithRecovery(()=>{this.clear(),c=0,l=0,h=0,u=0,o?.clear(),d.resetStats(),E.reset(),y.resetErrorHistory()},()=>{},"reset",e.ErrorType.UNKNOWN)},serialize(){return y.executeWithRecovery(()=>{const e=Array.from(this.entries());return JSON.stringify(e)},()=>"[]","serialize",e.ErrorType.SERIALIZATION)},clone:()=>y.executeWithRecovery(()=>{const e=[];for(const[t,r]of m.entries())e.push([t,r]);return x(e,r)},()=>x([],r),"clone",e.ErrorType.UNKNOWN),cleanup(){y.executeWithRecovery(()=>{o?.clear(),d.clearCache(),void 0!==globalThis.global&&globalThis.global?.gc&&globalThis.global.gc()},()=>{},"cleanup",e.ErrorType.MEMORY)},compact(){y.executeWithRecovery(()=>{const e=[];for(const t of i.keys())s.has(t)||e.push(t);for(const t of e)i.delete(t)},()=>{},"compact",e.ErrorType.UNKNOWN)}};if(t)try{for(const[e,r]of t)m.set(e,r)}catch(e){u++}r.enableAutoCleanup&&setInterval(()=>{m.cleanup()},r.cleanupInterval);return m}(i,n),()=>z(),"createEnhancedTurboMap",e.ErrorType.UNKNOWN)}function z(){const e=new Map;return{[Symbol.toStringTag]:"EnhancedTurboMap",get size(){return e.size},set:function(t,r){return e.set(t,r),this},get:t=>e.get(t),has:t=>e.has(t),delete:t=>e.delete(t),clear:()=>e.clear(),entries:()=>e.entries(),keys:()=>e.keys(),values:()=>e.values(),forEach:function(t){e.forEach((e,r)=>t(e,r,this))},[Symbol.iterator]:()=>e[Symbol.iterator](),getSerializedKey:e=>JSON.stringify(e),setAll:function(t){return t.forEach(([t,r])=>e.set(t,r)),this},getAll:t=>t.map(t=>e.get(t)),deleteAll:t=>t.map(t=>e.delete(t)),findByValue:()=>{},filter:()=>[],mapValues:()=>z(),getMetrics:()=>({size:e.size,operationCount:0,cacheHits:0,cacheMisses:0,cacheHitRate:0,errorCount:1,errorRate:1,fallbackMode:!0}),debug:()=>({size:e.size,internalMapSize:e.size,keyMapSize:e.size,config:{fallbackMode:!0},health:{healthy:!1,fallbackMode:!0},diagnostics:null,fallbackMode:!0}),getDiagnostics:()=>null,getHealthStatus:()=>({healthy:!1,errorRate:1,cacheHitRate:0,inFallbackMode:!0,score:0,fallbackMode:!0}),addPlugin:async()=>!1,removePlugin:async()=>!1,enablePlugin:async()=>!1,disablePlugin:async()=>!1,getPluginStats:()=>null,toAsync:()=>{throw new Error("Async not available in fallback mode")},optimize:()=>{},reset:()=>e.clear(),serialize:()=>"[]",clone:()=>z(),cleanup:()=>{},compact:()=>{}}}e.AdaptiveSerializer=m,e.AsyncTurboMap=f,e.DiagnosticAnalyzer=A,e.EnhancedLRUCache=p,e.EnhancedObjectPool=r,e.ErrorRecoveryManager=u,e.FastHasher=s,e.MemoryAnalyzer=T,e.ObjectPool=class{pool=[];createFn;resetFn;maxSize;constructor(e,t=()=>{},r=100){this.createFn=e,this.resetFn=t,this.maxSize=r}acquire(){const e=this.pool.pop();return e||this.createFn()}release(e){try{this.pool.length<this.maxSize&&(this.resetFn(e),this.pool.push(e))}catch(e){}}get size(){return this.pool.length}clear(){this.pool.length=0}},e.PerformanceMonitor=v,e.PluginManager=S,e.TieredCacheManager=g,e.TypeUtils=t,e.createEnhancedTurboMap=x,e.createTurboMap=x,e.globalDiagnostic=E,e.globalErrorRecovery=y,e.globalFastHasher=a,e.globalObjectPool=i,e.globalSerializer=d}); //# sourceMappingURL=index.umd.min.js.map