UNPKG

@mriridescent/rezilient

Version:

REZILIENT.js - Revolutionary framework for scaffolding complete production-ready resilient applications. Features offline-first architecture, AI-awareness, carbon-conscious computing, quantum-ready patterns, and self-healing capabilities.

1 lines 111 kB
"use strict";function e(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}Object.defineProperty(exports,"__esModule",{value:!0});class t{constructor(e){this._state=e,this._subscribers=new Set}subscribe(e){return this._subscribers.add(e),e(this._state),()=>{this._subscribers.delete(e)}}set(e){e!==this._state&&(this._state=e,this._notify())}update(e){this.set(e(this._state))}_notify(){for(const e of this._subscribers)e(this._state)}get(){return this._state}}const n="undefined"!=typeof process&&"test"===process.env.NODE_ENV,r=async(e,t)=>{if(n)try{const{set:n}=await Promise.resolve().then(function(){return u});return await n(e,t)}catch(e){return}if("undefined"!=typeof window&&"undefined"!=typeof indexedDB)try{return new Promise((n,r)=>{const i=indexedDB.open("aether-store",1);i.onerror=()=>n(),i.onsuccess=r=>{const i=r.target.result.transaction(["keyval"],"readwrite").objectStore("keyval").put(t,e);i.onsuccess=()=>n(),i.onerror=()=>n()},i.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains("keyval")||t.createObjectStore("keyval")}})}catch(e){console.warn("IndexedDB set failed:",e.message)}};class i extends t{constructor(e,t){super(t),this.key=e,this._isInitialized=!1,this._init()}async _init(){try{const e=await(async e=>{if(n)try{const{get:t}=await Promise.resolve().then(function(){return u});return await t(e)}catch(e){return}if("undefined"!=typeof window&&"undefined"!=typeof indexedDB)try{return new Promise((t,n)=>{const r=indexedDB.open("aether-store",1);r.onerror=()=>t(void 0),r.onsuccess=n=>{const r=n.target.result;if(!r.objectStoreNames.contains("keyval"))return void t(void 0);const i=r.transaction(["keyval"],"readonly").objectStore("keyval").get(e);i.onsuccess=()=>t(i.result),i.onerror=()=>t(void 0)},r.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains("keyval")||t.createObjectStore("keyval")}})}catch(e){return void console.warn("IndexedDB get failed:",e.message)}})(this.key);void 0!==e&&(this._state=e)}catch(e){console.warn(`PersistentStore(${this.key}): Failed to load from storage:`,e.message)}this._isInitialized=!0,this._notify()}set(e){super.set(e),this._isInitialized&&r(this.key,e).catch(e=>{console.warn(`PersistentStore(${this.key}): Failed to save to IndexedDB:`,e.message)})}update(e){super.update(e),this._isInitialized&&r(this.key,this._state).catch(e=>{console.warn(`PersistentStore(${this.key}): Failed to save to IndexedDB:`,e.message)})}}function s(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function a(e,t){let n;return(r,i)=>(()=>{if(n)return n;const r=indexedDB.open(e);return r.onupgradeneeded=()=>r.result.createObjectStore(t),n=s(r),n.then(e=>{e.onclose=()=>n=void 0},()=>{}),n})().then(e=>i(e.transaction(t,r).objectStore(t)))}let o;function c(){return o||(o=a("keyval-store","keyval")),o}function l(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},s(e.transaction)}var u=Object.freeze({__proto__:null,clear:function(e=c()){return e("readwrite",e=>(e.clear(),s(e.transaction)))},createStore:a,del:function(e,t=c()){return t("readwrite",t=>(t.delete(e),s(t.transaction)))},delMany:function(e,t=c()){return t("readwrite",t=>(e.forEach(e=>t.delete(e)),s(t.transaction)))},entries:function(e=c()){return e("readonly",t=>{if(t.getAll&&t.getAllKeys)return Promise.all([s(t.getAllKeys()),s(t.getAll())]).then(([e,t])=>e.map((e,n)=>[e,t[n]]));const n=[];return e("readonly",e=>l(e,e=>n.push([e.key,e.value])).then(()=>n))})},get:function(e,t=c()){return t("readonly",t=>s(t.get(e)))},getMany:function(e,t=c()){return t("readonly",t=>Promise.all(e.map(e=>s(t.get(e)))))},keys:function(e=c()){return e("readonly",e=>{if(e.getAllKeys)return s(e.getAllKeys());const t=[];return l(e,e=>t.push(e.key)).then(()=>t)})},promisifyRequest:s,set:function(e,t,n=c()){return n("readwrite",n=>(n.put(t,e),s(n.transaction)))},setMany:function(e,t=c()){return t("readwrite",t=>(e.forEach(e=>t.put(e[1],e[0])),s(t.transaction)))},update:function(e,t,n=c()){return n("readwrite",n=>new Promise((r,i)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),r(s(n.transaction))}catch(e){i(e)}}}))},values:function(e=c()){return e("readonly",e=>{if(e.getAll)return s(e.getAll());const t=[];return l(e,e=>t.push(e.value)).then(()=>t)})}});class h{static _cache=new Map;static getEnvironment(){if(this._cache.has("environment"))return this._cache.get("environment");let e="unknown";return"undefined"!=typeof process&&process.versions&&process.versions.node?e="node":"undefined"!=typeof window&&"undefined"!=typeof document?e="browser":"undefined"!=typeof self&&"function"==typeof importScripts?e="webworker":"undefined"!=typeof navigator&&"ReactNative"===navigator.product&&(e="react-native"),this._cache.set("environment",e),e}static isBrowser(){return"browser"===this.getEnvironment()}static isNode(){return"node"===this.getEnvironment()}static isWebWorker(){return"webworker"===this.getEnvironment()}static isReactNative(){return"react-native"===this.getEnvironment()}static getGlobal(){if(this._cache.has("global"))return this._cache.get("global");let e;return e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},this._cache.set("global",e),e}}class d{static getNavigator(){return h.getGlobal().navigator||{userAgent:"Aether.js/Node.js",platform:"node",onLine:!0,connection:{effectiveType:"4g"},permissions:{query:()=>Promise.resolve({state:"granted"})},mediaDevices:{getUserMedia:()=>Promise.reject(new Error("Media not available in Node.js"))}}}static getLocalStorage(){if(h.isBrowser())try{return window.localStorage}catch(e){return this.createMemoryStorage()}return this.createMemoryStorage()}static getSessionStorage(){if(h.isBrowser())try{return window.sessionStorage}catch(e){return this.createMemoryStorage()}return this.createMemoryStorage()}static getIndexedDB(){return h.isBrowser()?window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB:null}static getDocument(){return h.getGlobal().document||{createElement:()=>({}),getElementById:()=>null,querySelector:()=>null,addEventListener:()=>{},removeEventListener:()=>{}}}static getWindow(){const e=h.getGlobal();return e.window||e}static confirm(e){return h.isBrowser()&&"function"==typeof window.confirm?window.confirm(e):(console.log(`[Aether.js] Auto-confirming: ${e}`),!0)}static alert(e){h.isBrowser()&&"function"==typeof window.alert?window.alert(e):console.log(`[Aether.js] Alert: ${e}`)}static createMemoryStorage(){const e=new Map;return{getItem:t=>e.get(t)||null,setItem:(t,n)=>e.set(t,String(n)),removeItem:t=>e.delete(t),clear:()=>e.clear(),get length(){return e.size},key:t=>Array.from(e.keys())[t]||null}}static async fetch(t,n={}){if(h.isBrowser()&&"function"==typeof fetch)return fetch(t,n);if(h.isNode())try{const{default:r}=await Promise.resolve().then(function(){return e(require("node-fetch"))});return r(t,n)}catch(e){throw new Error("Fetch not available in Node.js environment")}throw new Error("Fetch not available in current environment")}static getWebXR(){return this.getNavigator().xr||{isSessionSupported:()=>Promise.resolve(!1),requestSession:()=>Promise.reject(new Error("WebXR not supported"))}}static createWorker(e){return h.isBrowser()&&"function"==typeof Worker?new Worker(e):{postMessage:e=>console.log("Worker message:",e),terminate:()=>{},addEventListener:()=>{},removeEventListener:()=>{}}}static getPerformance(){return h.getGlobal().performance||{now:()=>Date.now(),mark:()=>{},measure:()=>{},getEntriesByType:()=>[]}}static getCrypto(){const e=h.getGlobal();if(e.crypto&&e.crypto.getRandomValues)return e.crypto;if(h.isNode())try{const e=require("crypto");return{getRandomValues:t=>{const n=e.randomBytes(t.length);for(let e=0;e<t.length;e++)t[e]=n[e];return t},subtle:e.webcrypto?.subtle||null}}catch(e){}return{getRandomValues:e=>{for(let t=0;t<e.length;t++)e[t]=Math.floor(256*Math.random());return e},subtle:null}}}class p{static getNetworkInfo(){const e=d.getNavigator(),t=e.connection||e.mozConnection||e.webkitConnection;return{isOnline:!1!==e.onLine,effectiveType:t?.effectiveType||"4g",downlink:t?.downlink||10,rtt:t?.rtt||100,saveData:t?.saveData||!1}}static addNetworkListener(e){const t=h.getGlobal();if(h.isBrowser()){t.addEventListener("online",()=>e({isOnline:!0})),t.addEventListener("offline",()=>e({isOnline:!1}));const n=d.getNavigator().connection;n&&n.addEventListener&&n.addEventListener("change",()=>{e(this.getNetworkInfo())})}}}class g{constructor(e={}){this.options={maxCacheSize:e.maxCacheSize||52428800,maxCacheAge:e.maxCacheAge||6048e5,enablePredictiveCaching:!1!==e.enablePredictiveCaching,enableCarbonAware:!1!==e.enableCarbonAware,cacheStrategies:{static:"cache-first",api:"stale-while-revalidate",dynamic:"network-first",...e.cacheStrategies}},this.stats={hits:0,misses:0,evictions:0,totalSize:0,lastCleanup:Date.now()},this.usagePatterns=new Map,this.accessHistory=[],this.carbonData={lastUpdate:0,intensity:"medium",renewablePercentage:50},this.initialize()}async initialize(){await this.loadCacheStats(),await this.loadUsagePatterns(),await this.updateCarbonData(),this.setupMaintenanceSchedule(),this.setupCarbonUpdates()}async invalidateCache(e,t={}){const{force:n=!1,preserveFrequent:r=!0,maxAge:i=this.options.maxCacheAge}=t,s=await window.caches.keys(),a={invalidated:0,preserved:0,errors:[]};for(const t of s)try{const s=await window.caches.open(t),o=await s.keys();for(const t of o){const o=t.url;if(this.matchesPattern(o,e)){await this.shouldInvalidateEntry(t,s,{force:n,preserveFrequent:r,maxAge:i})?(await s.delete(t),a.invalidated++):a.preserved++}}}catch(e){a.errors.push({cacheName:t,error:e.message})}return this.stats.evictions+=a.invalidated,await this.saveCacheStats(),a}async predictivePreCache(e){if(!this.options.enablePredictiveCaching)return;this.recordAccess(e);const t=this.analyzePredictions(e);this.shouldPreCache()&&await this.preCacheResources(t)}async scheduleSync(e,t="normal"){const n=await this.getCarbonIntensity(),r=this.getNetworkCondition(),i=this.calculateOptimalDelay(n,r,t);return 0===i?await e():this.scheduleDelayedSync(e,i,t)}async handleRequest(e,t=null){const n=new URL(e.url),r=t||this.determineCacheStrategy(n);switch(this.recordAccess(n.href),r){case"cache-first":return this.cacheFirstStrategy(e);case"network-first":return this.networkFirstStrategy(e);case"stale-while-revalidate":default:return this.staleWhileRevalidateStrategy(e);case"cache-only":return this.cacheOnlyStrategy(e);case"network-only":return this.networkOnlyStrategy(e)}}async cacheFirstStrategy(e){try{const t=await caches.match(e);if(t)return this.stats.hits++,this.isStale(t)&&this.scheduleBackgroundUpdate(e),t;this.stats.misses++;const n=await fetch(e);return n.ok&&await this.cacheResponse(e,n.clone()),n}catch(t){const n=await this.getStaleResponse(e);if(n)return n;throw t}}async staleWhileRevalidateStrategy(e){const t=await caches.match(e);if(t){this.stats.hits++;const n=Promise.resolve(t);return this.shouldRevalidate()&&this.revalidateInBackground(e),n}this.stats.misses++;const n=await fetch(e);return n.ok&&await this.cacheResponse(e,n.clone()),n}async networkFirstStrategy(e){try{const t=await fetch(e);return t.ok&&await this.cacheResponse(e,t.clone()),t}catch(t){const n=await caches.match(e);if(n)return this.stats.hits++,n;throw this.stats.misses++,t}}async cacheResponse(e,t){const n=this.determineCacheName(e),r=await caches.open(n);await this.shouldEvictForSpace()&&await this.evictLeastUsed();const i=this.enhanceResponse(t);await r.put(e,i),this.updateCacheStats(e,t)}determineCacheStrategy(e){return this.isStaticAsset(e)?this.options.cacheStrategies.static:this.isApiEndpoint(e)?this.options.cacheStrategies.api:this.options.cacheStrategies.dynamic}async getCarbonIntensity(){return Date.now()-this.carbonData.lastUpdate>36e5&&await this.updateCarbonData(),this.carbonData.intensity}async updateCarbonData(){if(this.options.enableCarbonAware)try{const e=(new Date).getHours();e>=10&&e<=16?(this.carbonData.intensity="low",this.carbonData.renewablePercentage=70):e>=6&&e<=22?(this.carbonData.intensity="medium",this.carbonData.renewablePercentage=50):(this.carbonData.intensity="high",this.carbonData.renewablePercentage=30),this.carbonData.lastUpdate=Date.now()}catch(e){console.warn("Failed to update carbon data:",e)}}calculateOptimalDelay(e,t,n){if("urgent"===n)return 0;let r=0;switch(e){case"high":r+="low"===n?36e5:18e5;break;case"medium":r+="low"===n?9e5:3e5;break;case"low":r=0}return"slow"===t&&(r+=3e5),r}analyzePredictions(e){const t=this.usagePatterns.get(e)||{next:new Map,count:0};return Array.from(t.next.entries()).sort((e,t)=>t[1]-e[1]).slice(0,5).map(([e,t])=>({url:e,probability:t}))}recordAccess(e){const t=Date.now();this.accessHistory.push({url:e,timestamp:t}),this.accessHistory.length>1e3&&(this.accessHistory=this.accessHistory.slice(-1e3)),this.updateUsagePatterns(e)}updateUsagePatterns(e){const t=this.accessHistory.slice(-10),n=t[t.length-2];if(n){const t=n.url;this.usagePatterns.has(t)||this.usagePatterns.set(t,{next:new Map,count:0});const r=this.usagePatterns.get(t);r.count++;const i=r.next.get(e)||0;r.next.set(e,i+1)}}isStaticAsset(e){return/\.(js|css|png|jpg|jpeg|gif|svg|woff|woff2|ttf|ico)$/i.test(e.pathname)}isApiEndpoint(e){return e.pathname.startsWith("/api/")||e.pathname.startsWith("/graphql")}matchesPattern(e,t){return"string"==typeof t?e.includes(t):t instanceof RegExp&&t.test(e)}shouldPreCache(){return"low"===this.carbonData.intensity&&navigator.onLine}shouldRevalidate(){return"high"!==this.carbonData.intensity&&navigator.onLine}getNetworkCondition(){if(navigator.connection){const e=navigator.connection.effectiveType;return["slow-2g","2g"].includes(e)?"slow":"fast"}return"unknown"}setupMaintenanceSchedule(){setInterval(()=>{this.performMaintenance()},36e5)}setupCarbonUpdates(){setInterval(()=>{this.updateCarbonData()},18e5)}async performMaintenance(){await this.cleanupExpiredEntries(),await this.optimizeCacheSize(),await this.saveCacheStats(),await this.saveUsagePatterns()}async loadCacheStats(){try{const e=d.getLocalStorage().getItem("aether-cache-stats");e&&(this.stats={...this.stats,...JSON.parse(e)})}catch(e){console.warn("Failed to load cache stats:",e)}}async saveCacheStats(){try{d.getLocalStorage().setItem("aether-cache-stats",JSON.stringify(this.stats))}catch(e){console.warn("Failed to save cache stats:",e)}}async loadUsagePatterns(){try{const e=localStorage.getItem("aether-usage-patterns");if(e){const t=JSON.parse(e);this.usagePatterns=new Map(t)}}catch(e){console.warn("Failed to load usage patterns:",e)}}async saveUsagePatterns(){try{const e=Array.from(this.usagePatterns.entries());localStorage.setItem("aether-usage-patterns",JSON.stringify(e))}catch(e){console.warn("Failed to save usage patterns:",e)}}getStats(){const e=this.stats.hits/(this.stats.hits+this.stats.misses)||0;return{...this.stats,hitRate:Math.round(100*e),carbonIntensity:this.carbonData.intensity,renewablePercentage:this.carbonData.renewablePercentage,patternsLearned:this.usagePatterns.size,recentAccesses:this.accessHistory.length}}}class y{constructor(e={}){this.options={enableCarbonAwareness:!1!==e.enableCarbonAwareness,carbonApiKey:e.carbonApiKey,carbonApiUrl:e.carbonApiUrl||"https://api.carbonintensity.org.uk",maxDelayHours:e.maxDelayHours||24,urgentThreshold:e.urgentThreshold||3e5,batchSize:e.batchSize||10,...e},this.taskQueue={urgent:[],high:[],normal:[],low:[],background:[]},this.carbonData={current:{intensity:"medium",forecast:[]},lastUpdate:0,updateInterval:18e5,history:[]},this.conditions={network:"unknown",battery:"unknown",charging:!1,connectionType:"unknown"},this.stats={tasksScheduled:0,tasksExecuted:0,carbonSaved:0,energySaved:0,averageDelay:0},this.initialize()}async initialize(){await this.updateCarbonData(),this.updateDeviceConditions(),this.setupPeriodicUpdates(),this.startScheduler()}async scheduleTask(e,t="normal",n={}){["urgent","high","normal","low","background"].includes(t)||(console.warn(`Invalid priority "${t}", using "normal" instead`),t="normal");const r={id:this.generateTaskId(),...e,priority:t,scheduledAt:Date.now(),options:{maxDelay:n.maxDelay||this.getMaxDelayForPriority(t),carbonAware:!1!==n.carbonAware,networkAware:!1!==n.networkAware,batteryAware:!1!==n.batteryAware,...n},attempts:0,lastAttempt:null,estimatedCarbonCost:this.estimateCarbonCost(e),estimatedDuration:n.estimatedDuration||1e3};return this.taskQueue[t].push(r),this.stats.tasksScheduled++,"urgent"===t?this.executeTask(r):(this.scheduleOptimalExecution(r),r.id)}async scheduleBatch(e,t="normal",n={}){const r={id:this.generateTaskId(),type:"batch",tasks:e,priority:t,scheduledAt:Date.now(),options:{batchSize:n.batchSize||this.options.batchSize,...n},estimatedCarbonCost:e.reduce((e,t)=>e+this.estimateCarbonCost(t),0),estimatedDuration:e.reduce((e,t)=>e+(t.estimatedDuration||1e3),0)};return this.scheduleTask(r,t,n)}async updateCarbonData(){if(this.options.enableCarbonAwareness)try{const e=await this.fetchCarbonIntensity();if(e){this.carbonData.current=e,this.carbonData.lastUpdate=Date.now(),this.carbonData.history.push({timestamp:Date.now(),intensity:e.intensity,value:e.value||0});const t=Date.now()-864e5;this.carbonData.history=this.carbonData.history.filter(e=>e.timestamp>t)}}catch(e){console.warn("Failed to update carbon data, using fallback:",e),this.useFallbackCarbonData()}else this.carbonData.current.intensity="medium"}async fetchCarbonIntensity(){const e=await this.getRealCarbonIntensity();return null!==e?e:this.simulateCarbonIntensity()}async getRealCarbonIntensity(){try{const e=await this.fetchUKGridCarbon();if(e)return e;if(this.options.carbonApiKey){const e=await this.fetchCO2Signal();if(e)return e}if(this.options.wattTimeToken){const e=await this.fetchWattTimeAPI();if(e)return e}if(this.options.carbonInterfaceKey){const e=await this.fetchCarbonInterfaceAPI();if(e)return e}if(this.options.carbonApiUrl){const e=await this.fetchCustomCarbonAPI();if(e)return e}return null}catch(e){return console.warn(`Real carbon API error: ${e.message}`),null}}async calculateCarbonFootprint(e,t=1e3){const n=await this.fetchCarbonIntensity(),r={"cpu-intensive":t/1e3*1e-4,"network-request":t/1e3*1e-6,"storage-write":t/1e3*1e-5,"gpu-render":t/1e3*.001,idle:t/1e3*1e-5,default:t/1e3*5e-5},i=r[e]||r.default,s=n.value||400;return{operation:e,duration:t,energyUsed:i,carbonIntensity:s,carbonFootprint:i*s,timestamp:Date.now(),source:n.source||"simulation"}}async getOptimalSchedulingTime(e=24){try{const t=await fetch("https://api.carbonintensity.org.uk/intensity/date");if(t.ok){const n=(await t.json()).data||[];let r=null,i=1/0;const s=new Date,a=new Date(s.getTime()+60*e*60*1e3);return n.forEach(e=>{const t=new Date(e.from),n=e.intensity.forecast;t>=s&&t<=a&&n<i&&(i=n,r=t)}),{optimalTime:r,currentIntensity:n[0]?.intensity?.actual||n[0]?.intensity?.forecast,optimalIntensity:i,potentialSavings:((n[0]?.intensity?.forecast||400)-i)/(n[0]?.intensity?.forecast||400),delayMinutes:r?Math.round((r-s)/6e4):0}}}catch(e){console.warn("Carbon forecast error:",e)}return this.getHeuristicOptimalTime()}getHeuristicOptimalTime(){const e=new Date,t=e.getHours();let n;n=t<10?12:t<16?14:12;const r=new Date(e);return r.setHours(n,0,0,0),r<=e&&r.setDate(r.getDate()+1),{optimalTime:r,currentIntensity:400,optimalIntensity:200,potentialSavings:.5,delayMinutes:Math.round((r-e)/6e4)}}async fetchUKGridCarbon(){try{const e=await fetch("https://api.carbonintensity.org.uk/intensity");if(e.ok){const t=await e.json();if(t.data&&t.data.length>0){const e=t.data[0].intensity.actual||t.data[0].intensity.forecast,n=this.valueToIntensity(e);return console.log(`🌱 Real carbon intensity from UK Grid: ${e} gCO2/kWh (${n})`),{intensity:n,value:e,timestamp:Date.now(),source:"uk-grid"}}}}catch(e){console.warn(`UK Grid Carbon API error: ${e.message}`)}return null}async fetchCO2Signal(){try{const e=["US","GB","DE","FR","CA"];for(const t of e){const e=await fetch(`https://api.co2signal.com/v1/latest?countryCode=${t}`,{headers:{"auth-token":this.options.carbonApiKey}});if(e.ok){const n=await e.json(),r=n.data.carbonIntensity,i=this.valueToIntensity(r);return console.log(`🌱 Real carbon intensity from CO2 Signal (${t}): ${r} gCO2eq/kWh (${i})`),{intensity:i,value:r,timestamp:Date.now(),source:"co2signal",region:t,fossilFuelPercentage:n.data.fossilFuelPercentage||0,renewablePercentage:100-(n.data.fossilFuelPercentage||0)}}}}catch(e){console.warn(`CO2 Signal API error: ${e.message}`)}return null}async fetchWattTimeAPI(){if(!this.options.wattTimeToken)return null;try{const e=await fetch("https://api2.watttime.org/v2/marginal",{headers:{Authorization:`Bearer ${this.options.wattTimeToken}`}});if(e.ok){const t=await e.json(),n=t.marginal_carbon_intensity,r=this.valueToIntensity(n);return console.log(`🌱 Real marginal carbon intensity from WattTime: ${n} lbs CO2/MWh (${r})`),{intensity:r,value:.453592*n,timestamp:Date.now(),source:"watttime",marginalIntensity:n,region:t.region||"unknown"}}}catch(e){console.warn(`WattTime API error: ${e.message}`)}return null}async fetchCarbonInterfaceAPI(){if(!this.options.carbonInterfaceKey)return null;try{const e=await fetch("https://www.carboninterface.com/api/v1/estimates",{method:"POST",headers:{Authorization:`Bearer ${this.options.carbonInterfaceKey}`,"Content-Type":"application/json"},body:JSON.stringify({type:"electricity",electricity_unit:"kwh",electricity_value:1,country:"us",state:"ca"})});if(e.ok){const t=await e.json(),n=1e3*t.data.attributes.carbon_kg,r=this.valueToIntensity(n);return console.log(`🌱 Real carbon intensity from Carbon Interface: ${n} gCO2/kWh (${r})`),{intensity:r,value:n,timestamp:Date.now(),source:"carbon-interface",carbonKg:t.data.attributes.carbon_kg,carbonLb:t.data.attributes.carbon_lb}}}catch(e){console.warn(`Carbon Interface API error: ${e.message}`)}return null}async fetchCustomCarbonAPI(){try{const e=await fetch(`${this.options.carbonApiUrl}/intensity`,{headers:this.options.carbonApiKey?{Authorization:`Bearer ${this.options.carbonApiKey}`}:{}});if(!e.ok)throw new Error(`Carbon API error: ${e.status}`);const t=await e.json();return this.parseCarbonApiResponse(t)}catch(e){return console.warn("Custom Carbon API request failed:",e),null}}simulateCarbonIntensity(){const e=(new Date).getHours(),t=(new Date).getDay();let n,r;const i=0===t||6===t;return e>=10&&e<=16?(n="low",r=i?150:200):e>=18&&e<=21?(n="high",r=i?350:450):e>=22||e<=6?(n="medium",r=i?250:300):(n="medium",r=i?200:280),{intensity:n,value:r,forecast:this.generateForecast(r),timestamp:Date.now()}}generateForecast(e){const t=[];let n=e;for(let e=1;e<=24;e++){const r=((new Date).getHours()+e)%24,i=50*(Math.random()-.5);n=r>=10&&r<=16?Math.max(100,n-30+i):r>=18&&r<=21?Math.min(500,n+50+i):Math.max(100,Math.min(400,n+i)),t.push({hour:r,value:Math.round(n),intensity:this.valueToIntensity(n)})}return t}valueToIntensity(e){return e<200?"low":e<350?"medium":"high"}updateDeviceConditions(){const e=d.getNavigator(),t=p.getNetworkInfo();this.conditions.network=t.effectiveType,this.conditions.connectionType=t.effectiveType,e.getBattery?e.getBattery().then(e=>{this.conditions.battery=e.level,this.conditions.charging=e.charging}).catch(()=>{this.conditions.battery=1,this.conditions.charging=!0}):(this.conditions.battery=1,this.conditions.charging=!0)}scheduleOptimalExecution(e){const t=this.findOptimalExecutionTime(e),n=Math.max(0,t-Date.now());0===n?this.executeTask(e):setTimeout(()=>{this.executeTask(e)},n)}findOptimalExecutionTime(e){const t=Date.now(),n=t+e.options.maxDelay;if("urgent"===e.priority)return t;if(!e.options.carbonAware)return t+this.getPriorityDelay(e.priority);const r=this.carbonData.current.forecast||[];let i=t,s=this.calculateExecutionScore(t,e);for(const a of r){const r=t+60*a.hour*60*1e3;if(r>n)continue;const o=this.calculateExecutionScore(r,e,a);o>s&&(s=o,i=r)}return i}calculateExecutionScore(e,t,n=null){let r=100;switch(n?n.intensity:this.carbonData.current.intensity){case"low":r+=50;break;case"medium":r+=20;break;case"high":r-=30}if(r-=5*((e-Date.now())/36e5),t.options.networkAware)switch(this.conditions.network){case"4g":case"wifi":r+=10;break;case"3g":r+=5;break;case"2g":case"slow-2g":r-=20}return t.options.batteryAware&&"unknown"!==this.conditions.battery&&(this.conditions.charging?r+=15:this.conditions.battery<.2?r-=25:this.conditions.battery<.5&&(r-=10)),r}async executeTask(e){try{let t;return e.attempts++,e.lastAttempt=Date.now(),console.log(`🚀 Executing task ${e.id} (${e.type}) - Carbon: ${this.carbonData.current.intensity}`),t="batch"===e.type?await this.executeBatchTask(e):await e.execute(e.data),this.stats.tasksExecuted++,this.updateCarbonSavings(e),this.removeTaskFromQueue(e),console.log(`✅ Task ${e.id} completed successfully`),t}catch(t){if(console.error(`❌ Task ${e.id} failed:`,t),!(e.attempts<3))throw this.removeTaskFromQueue(e),t;{const t=1e3*Math.pow(2,e.attempts);setTimeout(()=>{this.executeTask(e)},t)}}}async executeBatchTask(e){const t=[],n=e.options.batchSize;for(let r=0;r<e.tasks.length;r+=n){const i=e.tasks.slice(r,r+n),s=await Promise.allSettled(i.map(e=>e.execute(e.data)));t.push(...s),r+n<e.tasks.length&&await new Promise(e=>setTimeout(e,100))}return t}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}getMaxDelayForPriority(e){switch(e){case"urgent":return 0;case"high":return 36e5;case"normal":default:return 216e5;case"low":return 864e5;case"background":return 6048e5}}getPriorityDelay(e){switch(e){case"urgent":return 0;case"high":return 3e5;case"normal":default:return 18e5;case"low":return 72e5;case"background":return 216e5}}estimateCarbonCost(e){return 10*this.getTaskTypeFactor(e.type)*((e.estimatedDuration||1e3)/1e3)}getTaskTypeFactor(e){const t={sync:2,upload:3,download:2.5,compute:1.5,batch:2.5,default:1};return t[e]||t.default}updateCarbonSavings(e){const t=this.carbonData.current.intensity,n=this.calculateCarbonSavings(e,t);this.stats.carbonSaved+=n}calculateCarbonSavings(e,t){const n="low"===t?.7:"medium"===t?1:1.3,r=1.5*e.estimatedCarbonCost,i=e.estimatedCarbonCost*n;return Math.max(0,r-i)}removeTaskFromQueue(e){for(const t in this.taskQueue){const n=this.taskQueue[t].findIndex(t=>t.id===e.id);if(-1!==n){this.taskQueue[t].splice(n,1);break}}}setupPeriodicUpdates(){setInterval(()=>{this.updateCarbonData()},this.carbonData.updateInterval),setInterval(()=>{this.updateDeviceConditions()},3e5)}startScheduler(){setInterval(()=>{this.processQueues()},6e4)}processQueues(){for(const e in this.taskQueue){const t=this.taskQueue[e];for(const e of t){this.shouldExecuteNow(e)&&this.executeTask(e)}}}shouldExecuteNow(e){const t=Date.now();if(t>=e.scheduledAt+e.options.maxDelay)return!0;return this.calculateExecutionScore(t,e)>80}useFallbackCarbonData(){this.carbonData.current=this.simulateCarbonIntensity()}parseCarbonApiResponse(e){return{intensity:this.valueToIntensity(e.intensity),value:e.intensity,forecast:e.forecast||[],timestamp:Date.now()}}getStats(){const e={};let t=0;for(const n in this.taskQueue)e[n]=this.taskQueue[n].length,t+=this.taskQueue[n].length;return{...this.stats,queueSizes:e,totalQueued:t,carbonIntensity:this.carbonData.current.intensity,carbonValue:this.carbonData.current.value,lastCarbonUpdate:this.carbonData.lastUpdate,conditions:this.conditions}}getCarbonData(){return this.carbonData.current}async forceExecuteAll(){const e=[];for(const t in this.taskQueue)e.push(...this.taskQueue[t]),this.taskQueue[t]=[];return await Promise.allSettled(e.map(e=>this.executeTask(e)))}async enableCityWideOptimization(e){return console.log("🌱🏙️ Enabling city-wide carbon optimization..."),this.cityWideOptimization={...e,enabled:!0},this.cityWideOptimization}async configureRenewableOptimization(e){return console.log("🌱⚡ Configuring renewable energy optimization..."),this.renewableOptimization={...e,configured:!0},this.renewableOptimization}async enableCarbonNeutralityTracking(e){return console.log("🌱📊 Enabling carbon neutrality tracking..."),this.carbonNeutralityTracking={...e,enabled:!0},this.carbonNeutralityTracking}async monitorCarbonEmissions(){return{totalEmissions:1e3+500*Math.random(),emissionRate:50+30*Math.random(),reductionTarget:.5,currentReduction:.3+.2*Math.random()}}async checkRenewableStatus(){return{solarGeneration:200+100*Math.random(),windGeneration:150+80*Math.random(),renewablePercentage:.6+.3*Math.random(),gridStability:"stable"}}async calculateSustainabilityMetrics(){return{carbonFootprint:800+400*Math.random(),energyEfficiency:.8+.15*Math.random(),renewableRatio:.7+.2*Math.random(),sustainabilityScore:85+10*Math.random()}}async optimizeEmergencyOperations(e){return console.log("🚨 Optimizing emergency operations for carbon efficiency..."),{emergencyType:e.type||"general",carbonOptimizedRouting:"enabled",renewableEmergencyPower:"activated",sustainableResponse:"prioritized",carbonImpact:"minimized"}}getStatus(){return this.getStats()}}const m={IDLE:"idle",SYNCING:"syncing",ERROR:"error",SYNCED:"synced",OFFLINE:"offline"},f={STATUS_CHANGE:"sync-status-change",PROGRESS_UPDATE:"sync-progress-update",MUTATION_SYNCED:"mutation-synced",SYNC_ERROR:"sync-error",QUEUE_UPDATED:"queue-updated"};class w{constructor(e={}){this.options={autoSync:!0,syncOnOnline:!0,trackSyncState:!0,...e},this.isOnline="undefined"!=typeof window&&null!==window&&void 0!==window&&"undefined"!=typeof navigator&&navigator.onLine,this.syncEngine=null,this.syncState=null,this.eventListeners=[],this.setupNetworkListeners(),this.initialize()}initialize(){}setupNetworkListeners(){if("undefined"!=typeof window&&window&&window.addEventListener){const e=()=>{this.isOnline=!0,this.onOnline(),this.options.syncOnOnline&&this.syncEngine&&this.syncEngine.processQueue()},t=()=>{this.isOnline=!1,this.onOffline()};window.addEventListener("online",e),window.addEventListener("offline",t),this.eventListeners.push({element:window,event:"online",handler:e},{element:window,event:"offline",handler:t})}}connectSyncEngine(e){if(this.disconnectSyncEngine(),this.syncEngine=e,this.options.trackSyncState){const t=e.subscribeSyncState(e=>{this.syncState=e,this.onSyncStateChange(e)}),n=[e.addEventListener(f.STATUS_CHANGE,e=>{this.onSyncStatusChange(e.status,e)}),e.addEventListener(f.PROGRESS_UPDATE,e=>{this.onSyncProgress(e)}),e.addEventListener(f.SYNC_ERROR,e=>{this.onSyncError(e)}),e.addEventListener(f.MUTATION_SYNCED,e=>{this.onMutationSynced(e)})];this.syncUnsubscribers=[t,...n]}}disconnectSyncEngine(){this.syncUnsubscribers&&(this.syncUnsubscribers.forEach(e=>e()),this.syncUnsubscribers=null),this.syncEngine=null,this.syncState=null}onOffline(){}onOnline(){}onSyncStateChange(e){}onSyncStatusChange(e,t){}onSyncProgress(e){}onSyncError(e){}onMutationSynced(e){}setState(e={}){return this.state={...this.state||{},...e},this.state}getNetworkState(){return{isOnline:this.isOnline,isOffline:!this.isOnline,connectionType:"undefined"!=typeof navigator&&navigator.connection?navigator.connection.effectiveType:"unknown"}}getSyncState(){return this.syncState}isSyncStatus(e){return this.syncState&&this.syncState.status===e}get isSyncing(){return!!this.syncState&&this.isSyncStatus(m.SYNCING)}get hasSyncErrors(){return!!this.syncState&&this.isSyncStatus(m.ERROR)}get isSynced(){return!!this.syncState&&this.isSyncStatus(m.SYNCED)}get isOfflineMode(){return!!this.syncState&&this.isSyncStatus(m.OFFLINE)}async triggerSync(){if(this.syncEngine&&this.isOnline)return this.syncEngine.processQueue()}async addMutation(e){if(this.syncEngine)return this.syncEngine.addMutation(e)}heal(){console.log("🔧 Enhanced self-healing mechanism activated");const e=this.performHealthCheck(),t=this.predictPotentialIssues(),n=this.applyHealingStrategies(e,t);this.optimizePerformance(),this.updateHealingMetrics(n);const r=n.success;return console.log(r?"✅ Enhanced self-healing successful":"❌ Self-healing partially failed"),r}performHealthCheck(){const e={memory:this.checkMemoryHealth(),performance:this.checkPerformanceHealth(),connectivity:this.checkConnectivityHealth(),errors:this.checkErrorPatterns()},t=Object.values(e).reduce((e,t)=>e+(t.score||.5),0)/Object.keys(e).length;return{overall:t,metrics:e,status:t>.8?"HEALTHY":t>.6?"DEGRADED":"CRITICAL"}}checkMemoryHealth(){if("undefined"!=typeof performance&&performance.memory){const e=performance.memory,t=e.usedJSHeapSize/e.totalJSHeapSize;return{score:t<.8?1:t<.9?.7:.3,usage:t,issues:t>.9?["HIGH_MEMORY_USAGE"]:[]}}return{score:.8,usage:"unknown",issues:[]}}checkPerformanceHealth(){const e=this.avgResponseTime||100,t=this.errorCount/Math.max(this.operationCount||1,1);let n=1;const r=[];return e>1e3&&(n-=.3,r.push("SLOW_RESPONSE_TIME")),t>.05&&(n-=.4,r.push("HIGH_ERROR_RATE")),{score:Math.max(n,.1),responseTime:e,errorRate:t,issues:r}}checkConnectivityHealth(){return{score:this.isOnline?1:.5,online:this.isOnline,issues:this.isOnline?[]:["OFFLINE"]}}checkErrorPatterns(){const e=this.errorCount/10;return{score:e<.01?1:e<.05?.7:.3,frequency:e,issues:e>.05?["HIGH_ERROR_FREQUENCY"]:[]}}predictPotentialIssues(){const e=[];return this.avgResponseTime>500&&e.push({type:"PERFORMANCE_DEGRADATION",probability:Math.min(this.avgResponseTime/1e3,.9),timeToIssue:Math.max(30-this.avgResponseTime/50,5)}),this.errorCount>3&&e.push({type:"ERROR_CASCADE",probability:Math.min(this.errorCount/10,.8),timeToIssue:Math.max(15-this.errorCount,2)}),e}applyHealingStrategies(e,t){const n=[];let r=!0;e.metrics.performance.score<.5&&n.push(()=>this.applyPerformanceHealing()),e.metrics.errors.score<.5&&n.push(()=>this.applyErrorHealing()),e.metrics.connectivity.online||n.push(()=>this.applyConnectivityHealing());const i=n.map(e=>{try{return e()}catch(e){return console.error("Healing strategy failed:",e),r=!1,{success:!1,error:e.message}}});return{success:r&&i.every(e=>!1!==e.success),strategies:i,appliedCount:n.length}}applyPerformanceHealing(){return this.avgResponseTime=100,this.operationCount=0,this.cache&&this.cache.clear(),console.log("🚀 Performance healing applied"),{success:!0,type:"performance"}}applyErrorHealing(){this.errorCount=0,this.errorState=null;try{return this.initialize&&"function"==typeof this.initialize&&this.initialize(),console.log("🔧 Error healing applied"),{success:!0,type:"error"}}catch(e){return console.error("Error healing failed:",e),{success:!1,type:"error",error:e.message}}}applyConnectivityHealing(){return this.syncEngine&&!this.isOnline?(console.log("📡 Connectivity healing: queuing operations"),{success:!0,type:"connectivity"}):{success:!0,type:"connectivity"}}optimizePerformance(){"undefined"!=typeof requestIdleCallback&&requestIdleCallback(()=>{this.performIdleOptimizations()})}performIdleOptimizations(){if(this.cache&&this.cache.size>100){const e=Array.from(this.cache.entries());e.slice(0,e.length-50).forEach(([e])=>{this.cache.delete(e)})}}updateHealingMetrics(e){this.healingMetrics||(this.healingMetrics=[]),this.healingMetrics.push({timestamp:Date.now(),success:e.success,strategiesApplied:e.appliedCount,results:e.strategies}),this.healingMetrics.length>10&&(this.healingMetrics=this.healingMetrics.slice(-10)),this.trainErrorPredictionModel()}trainErrorPredictionModel(){if(this.healingMetrics.length<5)return;const e=this.healingMetrics.map(e=>({features:[e.strategiesApplied,e.results.filter(e=>e.success).length,Date.now()-e.timestamp],outcome:e.success?1:0}));this.errorPredictionModel={patterns:e,accuracy:this.calculateModelAccuracy(e),lastTrained:Date.now()},console.log(`🤖 Error prediction model trained with ${e.length} samples (accuracy: ${(100*this.errorPredictionModel.accuracy).toFixed(1)}%)`)}calculateModelAccuracy(e){if(e.length<3)return.5;let t=0;return e.forEach((n,r)=>{const i=e.filter((e,t)=>t!==r);(this.predictErrorProbability(n.features,i)>.5?1:0)===n.outcome&&t++}),t/e.length}predictErrorProbability(e,t=null){const n=t||this.errorPredictionModel?.patterns||[];if(0===n.length)return.5;const r=n.map(t=>({distance:this.calculateEuclideanDistance(e,t.features),outcome:t.outcome}));r.sort((e,t)=>e.distance-t.distance);const i=Math.min(3,r.length);return r.slice(0,i).reduce((e,t)=>e+t.outcome,0)/i}calculateEuclideanDistance(e,t){return Math.sqrt(e.reduce((e,n,r)=>e+Math.pow(n-(t[r]||0),2),0))}async resolveDependencies(){console.log("🔧 Resolving dependencies automatically...");const e=this.analyzeDependencies(),t=this.createResolutionPlan(e);for(const e of t)try{await this.executeResolutionStep(e),console.log(`✅ Resolved: ${e.description}`)}catch(t){console.error(`❌ Failed to resolve: ${e.description}`,t)}return t}analyzeDependencies(){const e={missing:[],outdated:[],conflicting:[],circular:[]};return this.syncEngine&&!this.syncEngine.isConnected&&e.missing.push({name:"syncEngine",type:"connection",severity:"high"}),this.store&&!this.store.subscribers&&e.missing.push({name:"store",type:"initialization",severity:"critical"}),this.lastUpdate&&Date.now()-this.lastUpdate>3e5&&e.outdated.push({name:"component",type:"stale",severity:"medium"}),e}createResolutionPlan(e){const t=[];return e.missing.filter(e=>"critical"===e.severity).forEach(e=>{t.push({type:"reinitialize",target:e.name,description:`Reinitialize ${e.name}`,priority:1})}),e.missing.filter(e=>"high"===e.severity).forEach(e=>{t.push({type:"reconnect",target:e.name,description:`Reconnect ${e.name}`,priority:2})}),e.outdated.forEach(e=>{t.push({type:"refresh",target:e.name,description:`Refresh ${e.name}`,priority:3})}),t.sort((e,t)=>e.priority-t.priority)}async executeResolutionStep(e){switch(e.type){case"reinitialize":return this.reinitializeComponent(e.target);case"reconnect":return this.reconnectComponent(e.target);case"refresh":return this.refreshComponent(e.target);default:throw new Error(`Unknown resolution step: ${e.type}`)}}async reinitializeComponent(e){switch(e){case"store":this.store&&"function"==typeof this.store.initialize&&await this.store.initialize();break;case"syncEngine":this.syncEngine&&"function"==typeof this.syncEngine.initialize&&await this.syncEngine.initialize();break;default:console.warn(`Unknown component for reinitialization: ${e}`)}}async reconnectComponent(e){if("syncEngine"===e)this.syncEngine&&"function"==typeof this.syncEngine.connect&&await this.syncEngine.connect();else console.warn(`Unknown component for reconnection: ${e}`)}async refreshComponent(e){if("component"===e)this.lastUpdate=Date.now(),"function"==typeof this.onRefresh&&await this.onRefresh();else console.warn(`Unknown component for refresh: ${e}`)}createCheckpoint(e="auto"){this.checkpoints||(this.checkpoints=[]);const t={name:e,timestamp:Date.now(),state:this.store?JSON.parse(JSON.stringify(this.store.get())):null,errorCount:this.errorCount,isOnline:this.isOnline,metadata:{version:this.version||"1.0.0",healingAttempts:this.healingMetrics?.length||0}};return this.checkpoints.push(t),this.checkpoints.length>5&&(this.checkpoints=this.checkpoints.slice(-5)),console.log(`📸 Checkpoint created: ${e}`),t}async rollbackToCheckpoint(e=null){if(!this.checkpoints||0===this.checkpoints.length)throw new Error("No checkpoints available for rollback");const t=e?this.checkpoints.find(t=>t.name===e):this.checkpoints[this.checkpoints.length-1];if(!t)throw new Error(`Checkpoint not found: ${e}`);return console.log(`🔄 Rolling back to checkpoint: ${t.name}`),t.state&&this.store&&this.store.set(t.state),this.errorCount=t.errorCount,this.isOnline=t.isOnline,this.errorState=null,console.log(`✅ Rollback completed to ${t.name} (${new Date(t.timestamp).toISOString()})`),t}async coordinateDistributedHealing(){console.log("🌐 Coordinating distributed healing...");const e={components:this.getConnectedComponents(),healingPlan:[],results:[]};for(const t of e.components){const n=await this.analyzeComponentHealth(t);n.needsHealing&&e.healingPlan.push({component:t.id,issues:n.issues,priority:n.priority})}return e.healingPlan.sort((e,t)=>e.priority-t.priority).forEach(async t=>{try{const n=await this.healComponent(t.component,t.issues);e.results.push({...t,result:n,success:!0})}catch(n){e.results.push({...t,error:n.message,success:!1})}}),e}getConnectedComponents(){const e=[];return this.store&&e.push({id:"store",instance:this.store}),this.syncEngine&&e.push({id:"syncEngine",instance:this.syncEngine}),e}async analyzeComponentHealth(e){const t={needsHealing:!1,issues:[],priority:5};try{if(e.instance&&"function"==typeof e.instance.healthCheck){const n=await e.instance.healthCheck();"healthy"!==n.status&&(t.needsHealing=!0,t.issues=n.issues||[],t.priority=n.priority||3)}else"store"!==e.id||e.instance.subscribers||(t.needsHealing=!0,t.issues.push("No subscribers"),t.priority=2),"syncEngine"!==e.id||e.instance.isConnected||(t.needsHealing=!0,t.issues.push("Not connected"),t.priority=1)}catch(e){t.needsHealing=!0,t.issues.push(`Health check failed: ${e.message}`),t.priority=1}return t}async healComponent(e,t){console.log(`🔧 Healing component: ${e}`);const n=this.getConnectedComponents().find(t=>t.id===e);if(!n)throw new Error(`Component not found: ${e}`);const r=[];for(const e of t)try{const t=await this.applyComponentHealing(n,e);r.push({issue:e,result:t,success:!0})}catch(t){r.push({issue:e,error:t.message,success:!1})}return r}async applyComponentHealing(e,t){switch(t){case"No subscribers":if(e.instance&&"function"==typeof e.instance.resubscribe)return await e.instance.resubscribe();break;case"Not connected":if(e.instance&&"function"==typeof e.instance.connect)return await e.instance.connect();break;default:if(e.instance&&"function"==typeof e.instance.heal)return await e.instance.heal()}return{message:`Applied generic healing for: ${t}`}}destroy(){this.disconnectSyncEngine(),this.eventListeners.forEach(({element:e,event:t,handler:n})=>{e.removeEventListener(t,n)}),this.eventListeners=[],this.onDestroy()}onDestroy(){}}function b(e,t=null){if("undefined"==typeof React)return function(e,t=null){e.get();let n=[];const r=()=>{const n=e.get();return t?t(n):n},i=r=>{n.push(r);const i=e.subscribe(e=>{const r=t?t(e):e;n.forEach(e=>{try{e(r)}catch(e){console.error("Error in useAetherStore listener:",e)}})});return()=>{const e=n.indexOf(r);e>-1&&n.splice(e,1),0===n.length&&i()}};return{value:r(),subscribe:i,get:r}}(e,t);const[n,r]=React.useState(()=>{const n=e.get();return t?t(n):n});return React.useEffect(()=>e.subscribe(e=>{const n=t?t(e):e;r(n)}),[e,t]),n}function v(e,t,n={}){if("undefined"==typeof React)return function(e,t){const{PersistentStore:n}=require("../data/PersistentStore.js"),r=new n(e,t),i=e=>{"function"==typeof e?r.update(e):r.set(e)};return{store:r,setValue:i,getValue:()=>r.get(),subscribe:e=>r.subscribe(e)}}(e,t,n);const[r]=React.useState(()=>{const{PersistentStore:n}=require("../data/PersistentStore.js");return new n(e,t)});return[b(r),React.useCallback(e=>{"function"==typeof e?r.update(e):r.set(e)},[r]),r]}const S={SUSTAINABILITY:{name:"Sustainability First",description:"Carbon-aware computing and green software practices",priority:1,features:["carbon-aware-scheduling","energy-efficient-algorithms","green-metrics-tracking","renewable-energy-optimization"]},ACCESSIBILITY:{name:"Accessibility First",description:"Universal design and inclusive user experiences",priority:1,features:["wcag-compliance","screen-reader-optimization","keyboard-navigation","cognitive-accessibility","multi-modal-interfaces"]},PERFORMANCE:{name:"Performance First",description:"Quantum-ready optimization and edge computing",priority:1,features:["quantum-algorithms","edge-computing-optimization","predictive-caching","adaptive-performance-scaling"]},SECURITY:{name:"Security First",description:"Zero-trust architecture and quantum-resistant encryption",priority:1,features:["zero-trust-by-default","quantum-resistant-crypto","homomorphic-encryption","secure-multi-party-computation"]},RESILIENCE:{name:"Resilience First",description:"Fault-tolerant systems and graceful degradation",priority:1,features:["chaos-engineering","graceful-degradation","self-healing-systems","distributed-consensus"]},PRIVACY:{name:"Privacy First",description:"Data sovereignty and user control",priority:1,features:["differential-privacy","federated-learning","local-first-data","user-controlled-sharing"]},INCLUSIVITY:{name:"Inclusivity First",description:"Bias-free AI and equitable technology",priority:1,features:["bias-detection","fairness-metrics","diverse-training-data","ethical-ai-guidelines"]}};class E{constructor(e=Object.keys(S)){this.enabledPrinciples=e,this.violations=[]}validateComponent(e,t={}){const n=[];for(const r of this.enabledPrinciples){const i=S[r],s=this.validatePrinciple(e,i,t);s.isValid||n.push({principle:r,violations:s.violations,severity:s.severity})}return{isValid:0===n.length,violations:n,score:this.calculateComplianceScore(n)}}validatePrinciple(e,t,n){const r=[];switch(t.name){case"Sustainability First":r.push(...this.validateSustainability(e,n));break;case"Accessibility First":r.push(...this.validateAccessibility(e,n));break;case"Performance First":r.push(...this.validatePerformance(e,n));break;case"Security First":r.push(...this.validateSecurity(e,n));break;case"Resilience First":r.push(...this.validateResilience(e,n));break;case"Privacy First":r.push(...this.validatePrivacy(e,n));break;case"Inclusivity First":r.push(...this.validateInclusivity(e,n))}return{isValid:0===r.length,violations:r,severity:this.calculateSeverity(r)}}validateSustainability(e,t){const n=[];return e.carbonAwareScheduler||t.skipCarbonAware||n.push({type:"missing-carbon-awareness",message:"Component should use carbon-aware scheduling",suggestion:"Add CarbonAwareScheduler integration"}),e.energyProfile&&e.energyProfile.efficiency<.7&&n.push({type:"low-energy-efficiency",message:"Component energy efficiency below threshold",suggestion:"Optimize algorithms for lower energy consumption"}),n}validateAccessibility(e,t){const n=[];return e.render&&!t.hasAriaSupport&&n.push({type:"missing-aria-support",message:"Component should include ARIA attributes",suggestion:"Add proper ARIA labels and roles"}),e.interactive&&!t.keyboardAccessible&&n.push({type:"missing-keyboard-support",message:"Interactive component should support keyboard navigation",suggestion:"Add keyboard event handlers and focus management"}),n}validatePerformance(e,t){const n=[];return e.performanceMonitor||t.skipPerformanceMonitoring||n.push({type:"missing-performance-monitoring",message:"Component should include performance monitoring",suggestion:"Add PerformanceOptimizer integration"}),n}validateSecurity(e,t){const n=[];return e.acceptsInput&&!t.hasInputValidation&&n.push({type:"missing-input-validation",message:"Component should validate all inputs",suggestion:"Add comprehensive input sanitization"}),n}validateResilience(e,t){const n=[];return e.errorBoundary||t.hasErrorHandling||n.push({type:"missing-error-boundary",message:"Component should include error boundaries",suggestion:"Add comprehensive error handling"}),n}validatePrivacy(e,t){const n=[];return e.handlesUserData&&!t.hasPrivacyControls&&n.push({type:"missing-privacy-controls",message:"Component should include privacy controls",suggestion:"Add user consent and data control mechanisms"}),n}validateInclusivity(e,t){const n=[];return e.usesAI&&!t.hasBiasDetection&&n.push({type:"missing-bias-detection",message:"AI components should include bias detection",suggestion:"Add fairness metrics and bias monitoring"}),n}calculateComplianceScore(e){if(0===e.length)return 100;const t=5*this.enabledPrinciples.length,n=e.reduce((e,t)=>e+t.violations.length,0);return Math.max(0,Math.round(100*(1-n/t)))}calculateSeverity(e){return 0===e.length?"none":e.length<=2?"low":e.length<=5?"medium":"high"}}function C(e={}){return function(t){if("function"!=typeof t)throw new Error("withPrinciples decorator can only be applied to classes or functions");class n extends t{constructor(...n){super(...n),this.principleValidator=new E(e.enabledPrinciples),this.principleMetadata={...e.metadata,componentName:t.name},this.validatePrinciples()}validatePrinciples(){const t=this.principleValidator.validateComponent(this,this.principleMetadata);if(!t.isValid&&e.strict)throw new Error(`Component ${this.principleMetadata.componentName} violates Aether principles: ${t.violations.map(e=>e.violations.map(e=>e.message).join(", ")).join("; ")}`);return this.principleCompliance=t,t}getPrincipleCompliance(){return this.principleCompliance}}return Object.defineProperty(n,"name",{value:`PrincipleAware${t.name}`,configurable:!0}),n}}const A={NONE:0,BASIC:1,ADAPTIVE:2,PREDICTIVE:3,AUTONOMOUS:4,SYMBIOTIC:5},k={TRANSPARENCY:"AI decisions must be explainable",FAIRNESS:"AI must not discriminate or show bias",PRIVACY:"AI must respect user privacy and data sovereignty",AGENCY:"Users must maintain control and override capability",BENEFICENCE:"AI must benefit users and society",NON_MALEFICENCE:"AI must not cause harm"};class R{constructor(e={}){this.aiLevel=e.aiLevel||A.BASIC,this.ethicsConfig={...k,...e.ethics},this.learningEnabled=!1!==e.learningEnabled,this.userConsent=e.userConsent||!1,this.behaviorPatterns=new Map,this.userPreferences=new Map,this.adaptationHistory=[],this.biasMetrics=new Map,this.humanOverrides=new Map,this.explainabilityLog=[],this.initializeAI()}initializeAI(){this.aiLevel>=A.BASIC&&this.setupPatternRecognition(),this.aiLevel>=A.ADAPTIVE&&this.setupAdaptiveLearning(),this.aiLevel>=A.PREDICTIVE&&this.setupPredictiveCapabilities(),this.aiLevel>=A.AUTONOMOUS&&this.setupAutonomousFeatures(),this.aiLevel>=A.SYMBIOTIC&&this.setupSymbioticInterface()}setupPatternRecognition(){this.patternRecognizer={recordInteraction:e=>{const t=this.extractPattern(e),n=this.behaviorPatterns.get(t.key)||{count:0,contexts:[]};this.behaviorPatterns.set(t.key,{count:n.count+1,contexts:[...n.contexts,t.context].slice(-10),lastSeen:Date.now()}),