rezilient.js
Version:
Rezilient.js - Revolutionary offline-first framework with AI-awareness, principle-driven development, carbon-conscious computing, and self-healing capabilities
1 lines • 65.4 kB
JavaScript
class e{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 t="undefined"!=typeof process&&"test"===process.env.NODE_ENV,n=async(e,n)=>{if(t)try{const{set:t}=await Promise.resolve().then(function(){return u});return await t(e,n)}catch(e){return}if("undefined"!=typeof window&&"undefined"!=typeof indexedDB)try{return new Promise((t,s)=>{const r=indexedDB.open("aether-store",1);r.onerror=()=>t(),r.onsuccess=s=>{const r=s.target.result.transaction(["keyval"],"readwrite").objectStore("keyval").put(n,e);r.onsuccess=()=>t(),r.onerror=()=>t()},r.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains("keyval")||t.createObjectStore("keyval")}})}catch(e){console.warn("IndexedDB set failed:",e.message)}};class s extends e{constructor(e,t){super(t),this.key=e,this._isInitialized=!1,this._init()}async _init(){try{const e=await(async e=>{if(t)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 s=indexedDB.open("aether-store",1);s.onerror=()=>t(void 0),s.onsuccess=n=>{const s=n.target.result;if(!s.objectStoreNames.contains("keyval"))return void t(void 0);const r=s.transaction(["keyval"],"readonly").objectStore("keyval").get(e);r.onsuccess=()=>t(r.result),r.onerror=()=>t(void 0)},s.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&&n(this.key,e).catch(e=>{console.warn(`PersistentStore(${this.key}): Failed to save to IndexedDB:`,e.message)})}update(e){super.update(e),this._isInitialized&&n(this.key,this._state).catch(e=>{console.warn(`PersistentStore(${this.key}): Failed to save to IndexedDB:`,e.message)})}}function r(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function i(e,t){let n;return(s,i)=>(()=>{if(n)return n;const s=indexedDB.open(e);return s.onupgradeneeded=()=>s.result.createObjectStore(t),n=r(s),n.then(e=>{e.onclose=()=>n=void 0},()=>{}),n})().then(e=>i(e.transaction(t,s).objectStore(t)))}let a;function o(){return a||(a=i("keyval-store","keyval")),a}function c(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},r(e.transaction)}var u=Object.freeze({__proto__:null,clear:function(e=o()){return e("readwrite",e=>(e.clear(),r(e.transaction)))},createStore:i,del:function(e,t=o()){return t("readwrite",t=>(t.delete(e),r(t.transaction)))},delMany:function(e,t=o()){return t("readwrite",t=>(e.forEach(e=>t.delete(e)),r(t.transaction)))},entries:function(e=o()){return e("readonly",t=>{if(t.getAll&&t.getAllKeys)return Promise.all([r(t.getAllKeys()),r(t.getAll())]).then(([e,t])=>e.map((e,n)=>[e,t[n]]));const n=[];return e("readonly",e=>c(e,e=>n.push([e.key,e.value])).then(()=>n))})},get:function(e,t=o()){return t("readonly",t=>r(t.get(e)))},getMany:function(e,t=o()){return t("readonly",t=>Promise.all(e.map(e=>r(t.get(e)))))},keys:function(e=o()){return e("readonly",e=>{if(e.getAllKeys)return r(e.getAllKeys());const t=[];return c(e,e=>t.push(e.key)).then(()=>t)})},promisifyRequest:r,set:function(e,t,n=o()){return n("readwrite",n=>(n.put(t,e),r(n.transaction)))},setMany:function(e,t=o()){return t("readwrite",t=>(e.forEach(e=>t.put(e[1],e[0])),r(t.transaction)))},update:function(e,t,n=o()){return n("readwrite",n=>new Promise((s,i)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),s(r(n.transaction))}catch(e){i(e)}}}))},values:function(e=o()){return e("readonly",e=>{if(e.getAll)return r(e.getAll());const t=[];return c(e,e=>t.push(e.value)).then(()=>t)})}});class l{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 h{static getNavigator(){return l.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(l.isBrowser())try{return window.localStorage}catch(e){return this.createMemoryStorage()}return this.createMemoryStorage()}static getSessionStorage(){if(l.isBrowser())try{return window.sessionStorage}catch(e){return this.createMemoryStorage()}return this.createMemoryStorage()}static getIndexedDB(){return l.isBrowser()?window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB:null}static getDocument(){return l.getGlobal().document||{createElement:()=>({}),getElementById:()=>null,querySelector:()=>null,addEventListener:()=>{},removeEventListener:()=>{}}}static getWindow(){const e=l.getGlobal();return e.window||e}static confirm(e){return l.isBrowser()&&"function"==typeof window.confirm?window.confirm(e):(console.log(`[Aether.js] Auto-confirming: ${e}`),!0)}static alert(e){l.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(e,t={}){if(l.isBrowser()&&"function"==typeof fetch)return fetch(e,t);if(l.isNode())try{const{default:n}=await import("node-fetch");return n(e,t)}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 l.isBrowser()&&"function"==typeof Worker?new Worker(e):{postMessage:e=>console.log("Worker message:",e),terminate:()=>{},addEventListener:()=>{},removeEventListener:()=>{}}}static getPerformance(){return l.getGlobal().performance||{now:()=>Date.now(),mark:()=>{},measure:()=>{},getEntriesByType:()=>[]}}static getCrypto(){const e=l.getGlobal();if(e.crypto&&e.crypto.getRandomValues)return e.crypto;if(l.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 d{static getNetworkInfo(){const e=h.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=l.getGlobal();if(l.isBrowser()){t.addEventListener("online",()=>e({isOnline:!0})),t.addEventListener("offline",()=>e({isOnline:!1}));const n=h.getNavigator().connection;n&&n.addEventListener&&n.addEventListener("change",()=>{e(this.getNetworkInfo())})}}}class p{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:s=!0,maxAge:r=this.options.maxCacheAge}=t,i=await window.caches.keys(),a={invalidated:0,preserved:0,errors:[]};for(const t of i)try{const i=await window.caches.open(t),o=await i.keys();for(const t of o){const o=t.url;if(this.matchesPattern(o,e)){await this.shouldInvalidateEntry(t,i,{force:n,preserveFrequent:s,maxAge:r})?(await i.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(),s=this.getNetworkCondition(),r=this.calculateOptimalDelay(n,s,t);return 0===r?await e():this.scheduleDelayedSync(e,r,t)}async handleRequest(e,t=null){const n=new URL(e.url),s=t||this.determineCacheStrategy(n);switch(this.recordAccess(n.href),s){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),s=await caches.open(n);await this.shouldEvictForSpace()&&await this.evictLeastUsed();const r=this.enhanceResponse(t);await s.put(e,r),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 s=0;switch(e){case"high":s+="low"===n?36e5:18e5;break;case"medium":s+="low"===n?9e5:3e5;break;case"low":s=0}return"slow"===t&&(s+=3e5),s}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 s=this.usagePatterns.get(t);s.count++;const r=s.next.get(e)||0;s.next.set(e,r+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=h.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{h.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 s={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(s),this.stats.tasksScheduled++,"urgent"===t?this.executeTask(s):(this.scheduleOptimalExecution(s),s.id)}async scheduleBatch(e,t="normal",n={}){const s={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(s,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(){if(!this.options.carbonApiUrl)return this.simulateCarbonIntensity();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("Carbon API request failed:",e),this.simulateCarbonIntensity()}}simulateCarbonIntensity(){const e=(new Date).getHours(),t=(new Date).getDay();let n,s;const r=0===t||6===t;return e>=10&&e<=16?(n="low",s=r?150:200):e>=18&&e<=21?(n="high",s=r?350:450):e>=22||e<=6?(n="medium",s=r?250:300):(n="medium",s=r?200:280),{intensity:n,value:s,forecast:this.generateForecast(s),timestamp:Date.now()}}generateForecast(e){const t=[];let n=e;for(let e=1;e<=24;e++){const s=((new Date).getHours()+e)%24,r=50*(Math.random()-.5);n=s>=10&&s<=16?Math.max(100,n-30+r):s>=18&&s<=21?Math.min(500,n+50+r):Math.max(100,Math.min(400,n+r)),t.push({hour:s,value:Math.round(n),intensity:this.valueToIntensity(n)})}return t}valueToIntensity(e){return e<200?"low":e<350?"medium":"high"}updateDeviceConditions(){const e=h.getNavigator(),t=d.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 s=this.carbonData.current.forecast||[];let r=t,i=this.calculateExecutionScore(t,e);for(const a of s){const s=t+60*a.hour*60*1e3;if(s>n)continue;const o=this.calculateExecutionScore(s,e,a);o>i&&(i=o,r=s)}return r}calculateExecutionScore(e,t,n=null){let s=100;switch(n?n.intensity:this.carbonData.current.intensity){case"low":s+=50;break;case"medium":s+=20;break;case"high":s-=30}if(s-=5*((e-Date.now())/36e5),t.options.networkAware)switch(this.conditions.network){case"4g":case"wifi":s+=10;break;case"3g":s+=5;break;case"2g":case"slow-2g":s-=20}return t.options.batteryAware&&"unknown"!==this.conditions.battery&&(this.conditions.charging?s+=15:this.conditions.battery<.2?s-=25:this.conditions.battery<.5&&(s-=10)),s}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 s=0;s<e.tasks.length;s+=n){const r=e.tasks.slice(s,s+n),i=await Promise.allSettled(r.map(e=>e.execute(e.data)));t.push(...i),s+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,s=1.5*e.estimatedCarbonCost,r=e.estimatedCarbonCost*n;return Math.max(0,s-r)}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 g={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 m{constructor(t={}){this.queue=new s("aether-mutation-queue",[]),this.isSyncing=!1,this.conflictStrategy=t.conflictStrategy||"LastWriteWins",this.retryAttempts=t.retryAttempts||3,this.retryDelay=t.retryDelay||1e3,this.enableProgressTracking=!1!==t.enableProgressTracking,this.enableAdvancedCaching=!1!==t.enableAdvancedCaching,this.enableCarbonAware=!1!==t.enableCarbonAware,this.syncState=new e({status:g.IDLE,progress:{current:0,total:0,percentage:0},pending:0,error:null,lastSync:null,retryCount:0}),this.eventListeners=new Map,this.isOnline="undefined"==typeof navigator||navigator.onLine,this.setupEventListeners(),this.initializeSyncState(),this.initializeAdvancedFeatures()}async initializeAdvancedFeatures(){this.enableAdvancedCaching&&(this.cacheManager=new p({enablePredictiveCaching:!0,enableCarbonAware:this.enableCarbonAware})),this.enableCarbonAware&&(this.carbonScheduler=new y({enableCarbonAwareness:!0}))}setupEventListeners(){"undefined"!=typeof window&&window&&window.addEventListener&&(window.addEventListener("online",()=>{this.isOnline=!0,this.updateSyncStatus(g.IDLE),this.processQueue()}),window.addEventListener("offline",()=>{this.isOnline=!1,this.updateSyncStatus(g.OFFLINE)}))}async initializeSyncState(){const e=(await this.queue.get()).length;this.updateSyncState({pending:e,status:this.isOnline?g.IDLE:g.OFFLINE})}updateSyncState(e){this.syncState.update(t=>({...t,...e})),this.emitEvent(f.STATUS_CHANGE,this.syncState.get())}updateSyncStatus(e){this.updateSyncState({status:e})}updateProgress(e,t){if(!this.enableProgressTracking)return;const n={current:e,total:t,percentage:t>0?Math.round(e/t*100):0};this.updateSyncState({progress:n}),this.emitEvent(f.PROGRESS_UPDATE,n)}emitEvent(e,t){(this.eventListeners.get(e)||[]).forEach(n=>{try{n(t)}catch(t){console.error(`Error in sync event listener for ${e}:`,t)}})}addEventListener(e,t){return this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t),()=>{const n=this.eventListeners.get(e)||[],s=n.indexOf(t);s>-1&&n.splice(s,1)}}getSyncState(){return this.syncState.get()}getState(){return this.getSyncState()}subscribeSyncState(e){return this.syncState.subscribe(e)}async addMutation(e){const t={...e,id:e.id||this.generateMutationId(),timestamp:e.timestamp||Date.now(),retryCount:0,status:"pending"},n=[...await this.queue.get()||[],t];await this.queue.set(n),this.updateSyncState({pending:n.length}),this.emitEvent(f.QUEUE_UPDATED,{action:"added",mutation:t,queueLength:n.length}),this.isOnline&&!this.isSyncing&&setTimeout(()=>this.processQueue(),100)}generateMutationId(){return`mutation_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}async processQueue(e={}){if(this.isSyncing)return void console.log("Sync already in progress, skipping...");if(!this.isOnline)return console.log("Device is offline, cannot sync"),void this.updateSyncStatus(g.OFFLINE);const t=await this.queue.get()||[];if(0===t.length)return void this.updateSyncState({status:g.SYNCED,pending:0,error:null});if(this.enableCarbonAware&&this.carbonScheduler&&!e.force)return this.processQueueWithCarbonAwareness(t,e);this.isSyncing=!0,this.updateSyncState({status:g.SYNCING,error:null,retryCount:0});const n=t.length;const s=[],r=[];this.updateProgress(0,n);for(let e=0;e<t.length;e++){const i=t[e];try{this.updateProgress(e,n);const t=await this.processSingleMutation(i);t.success?(r.push(i),this.emitEvent(f.MUTATION_SYNCED,{mutation:i,result:t.data})):s.push({mutation:i,error:t.error,retryCount:i.retryCount||0})}catch(e){console.error("Failed to sync mutation:",i,e),s.push({mutation:i,error:e,retryCount:i.retryCount||0})}}this.updateProgress(n,n),await this.handleSyncResults(r,s),this.isSyncing=!1}async processQueueWithCarbonAwareness(e,t={}){const n=t.priority||"normal",s=this.groupMutationsByType(e);for(const[e,t]of s){const e={type:"sync-batch",data:t,execute:async e=>this.processMutationBatch(e),estimatedDuration:500*t.length};await this.carbonScheduler.scheduleTask(e,n,{carbonAware:!0,networkAware:!0,batteryAware:!0})}}groupMutationsByType(e){const t=new Map;for(const n of e){const e=n.type||"default";t.has(e)||t.set(e,[]),t.get(e).push(n)}return t}async processMutationBatch(e){const t=[];for(const n of e)try{const e=await this.processSingleMutation(n);t.push({mutation:n,result:e})}catch(e){t.push({mutation:n,error:e})}return await this.updateQueueAfterBatch(t),t}async updateQueueAfterBatch(e){const t=await this.queue.get(),n=e.filter(e=>e.result&&e.result.success).map(e=>e.mutation),s=t.filter(e=>!n.some(t=>t.id===e.id));await this.queue.set(s),this.updateSyncState({pending:s.length,status:0===s.length?g.SYNCED:g.IDLE})}async processSingleMutation(e){let t=null;const n=e.retryCount<this.retryAttempts?this.retryAttempts-e.retryCount:0;for(let s=0;s<=n;s++)try{const t=await this.fetchServerState(e);let n=e;if(t&&this.hasConflict(e,t))if("function"==typeof this.conflictStrategy){if(n=this.conflictStrategy(e,t),!n)return{success:!0,data:{skipped:!0,reason:"conflict_resolved"}}}else{if("ServerWins"===this.conflictStrategy)return{success:!0,data:{skipped:!0,reason:"server_wins"}};this.conflictStrategy}return{success:!0,data:await this.syncMutation(n)}}catch(e){if(t=e,s<n){const e=this.retryDelay*Math.pow(2,s);await new Promise(t=>setTimeout(t,e))}}return{success:!1,error:t,retriesExhausted:!0}}async handleSyncResults(e,t){const n=(await this.queue.get()).filter(t=>!e.some(e=>e.id===t.id)),s=t.map(e=>({...e.mutation,retryCount:(e.mutation.retryCount||0)+1,lastError:e.error.message,lastAttempt:Date.now()})).filter(e=>e.retryCount<this.retryAttempts),r=n.map(e=>s.find(t=>t.id===e.id)||e);await this.queue.set(r);const i=t.length>0,a=t.every(e=>e.retriesExhausted);this.updateSyncState({status:i?a?g.ERROR:g.IDLE:g.SYNCED,pending:r.length,error:i?t[0].error:null,lastSync:Date.now()}),i&&t.forEach(e=>{this.emitEvent(f.SYNC_ERROR,{mutation:e.mutation,error:e.error,retryCount:e.mutation.retryCount||0,retriesExhausted:e.retriesExhausted})}),s.length>0&&this.isOnline&&setTimeout(()=>{this.isSyncing||this.processQueue()},2*this.retryDelay)}async fetchServerState(e){return null}hasConflict(e,t){return!1}async syncMutation(e){return console.log("Syncing mutation:",e),new Promise(e=>setTimeout(e,500))}async getQueue(){return(await this.queue.get()).map(e=>({...e,age:Date.now()-(e.timestamp||0),canRetry:(e.retryCount||0)<this.retryAttempts}))}async getQueueStats(){const e=await this.getQueue(),t=Date.now();return{total:e.length,pending:e.filter(e=>"pending"===e.status).length,failed:e.filter(e=>(e.retryCount||0)>=this.retryAttempts).length,retriable:e.filter(e=>e.canRetry).length,oldestMutation:e.length>0?Math.max(...e.map(e=>t-(e.timestamp||0))):0,averageAge:e.length>0?e.reduce((e,n)=>e+(t-(n.timestamp||0)),0)/e.length:0}}async clearQueue(){await this.queue.set([]),this.updateSyncState({pending:0,status:g.IDLE,error:null}),this.emitEvent(f.QUEUE_UPDATED,{action:"cleared",queueLength:0})}async removeMutation(e){const t=await this.queue.get(),n=t.filter(t=>t.id!==e);return n.length!==t.length&&(await this.queue.set(n),this.updateSyncState({pending:n.length}),this.emitEvent(f.QUEUE_UPDATED,{action:"removed",mutationId:e,queueLength:n.length}),!0)}async forceSyncMutation(e){const t=(await this.queue.get()).find(t=>t.id===e);if(!t)return!1;if(!this.isOnline)throw new Error("Cannot force sync while offline");try{const n=await this.processSingleMutation(t);if(n.success)return await this.removeMutation(e),this.emitEvent(f.MUTATION_SYNCED,{mutation:t,result:n.data,forced:!0}),!0;throw n.error}catch(e){throw this.emitEvent(f.SYNC_ERROR,{mutation:t,error:e,forced:!0}),e}}async getHealthStatus(){const e=await this.getQueueStats(),t=this.getSyncState(),n={status:"healthy",issues:[],recommendations:[]};return this.isOnline||(n.status="offline",n.issues.push("Device is offline")),e.failed>0&&(n.status="degraded",n.issues.push(`${e.failed} mutations have failed permanently`),n.recommendations.push("Review failed mutations and consider manual intervention")),e.oldestMutation>864e5&&(n.status="degraded",n.issues.push("Mutations older than 24 hours in queue"),n.recommendations.push("Check network connectivity and server availability")),t.status===g.ERROR&&(n.status="error",n.issues.push("Sync engine is in error state"),n.recommendations.push("Check error details and retry sync")),{...n,stats:e,state:t,timestamp:Date.now()}}getAdvancedStats(){const e={caching:null,carbonScheduling:null,features:{advancedCaching:this.enableAdvancedCaching,carbonAware:this.enableCarbonAware}};return this.cacheManager&&(e.caching=this.cacheManager.getStats()),this.carbonScheduler&&(e.carbonScheduling=this.carbonScheduler.getStats()),e}getCarbonData(){return this.carbonScheduler?this.carbonScheduler.getCarbonData():null}async forceSync(){return this.processQueue({force:!0})}async schedulePredictiveCache(e){if(this.cacheManager)return this.cacheManager.predictivePreCache(e)}async invalidateCache(e,t={}){return this.cacheManager?this.cacheManager.invalidateCache(e,t):{invalidated:0,preserved:0,errors:[]}}destroy(){this.eventListeners.clear(),this.cacheManager,this.carbonScheduler,"undefined"!=typeof window&&console.warn("Window event listeners for SyncEngine cannot be automatically removed"),this.isSyncing=!1,this.updateSyncStatus(g.IDLE)}}class w{constructor(e={}){this.options={autoSync:!0,syncOnOnline:!0,trackSyncState:!0,...e},this.isOnline="undefined"!=typeof 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){}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(g.SYNCING)}get hasSyncErrors(){return!!this.syncState&&this.isSyncStatus(g.ERROR)}get isSynced(){return!!this.syncState&&this.isSyncStatus(g.SYNCED)}get isOfflineMode(){return!!this.syncState&&this.isSyncStatus(g.OFFLINE)}async triggerSync(){if(this.syncEngine&&this.isOnline)return this.syncEngine.processQueue()}async addMutation(e){if(this.syncEngine)return this.syncEngine.addMutation(e)}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 s=()=>{const n=e.get();return t?t(n):n},r=s=>{n.push(s);const r=e.subscribe(e=>{const s=t?t(e):e;n.forEach(e=>{try{e(s)}catch(e){console.error("Error in useAetherStore listener:",e)}})});return()=>{const e=n.indexOf(s);e>-1&&n.splice(e,1),0===n.length&&r()}};return{value:s(),subscribe:r,get:s}}(e,t);const[n,s]=React.useState(()=>{const n=e.get();return t?t(n):n});return React.useEffect(()=>e.subscribe(e=>{const n=t?t(e):e;s(n)}),[e,t]),n}function S(e){if("undefined"==typeof React)return function(e){let t=e.getSyncState(),n=null,s=[];e.getQueueStats().then(e=>{n=e,a()});const r=e.subscribeSyncState(e=>{t=e,a()}),i=e.addEventListener("queue-updated",()=>{e.getQueueStats().then(e=>{n=e,a()})});function a(){s.forEach(e=>{try{e({syncState:t,queueStats:n,isOnline:"offline"!==t.status,isSyncing:"syncing"===t.status,hasErrors:"error"===t.status,pendingCount:t.pending})}catch(e){console.error("Error in useSyncEngine listener:",e)}})}const o=e=>(s.push(e),e({syncState:t,queueStats:n,isOnline:"offline"!==t.status,isSyncing:"syncing"===t.status,hasErrors:"error"===t.status,pendingCount:t.pending}),()=>{const t=s.indexOf(e);t>-1&&s.splice(t,1),0===s.length&&(r(),i())}),c={sync:()=>e.processQueue(),clearQueue:()=>e.clearQueue(),removeMutation:t=>e.removeMutation(t),forceSyncMutation:t=>e.forceSyncMutation(t),getHealthStatus:()=>e.getHealthStatus()};return{subscribe:o,actions:c,getCurrentState:()=>({syncState:t,queueStats:n,isOnline:"offline"!==t.status,isSyncing:"syncing"===t.status,hasErrors:"error"===t.status,pendingCount:t.pending})}}(e);const[t,n]=React.useState(e.getSyncState()),[s,r]=React.useState(null);React.useEffect(()=>{const t=e.subscribeSyncState(n);e.getQueueStats().then(r);const s=e.addEventListener("queue-updated",()=>{e.getQueueStats().then(r)});return()=>{t(),s()}},[e]);return{syncState:t,queueStats:s,actions:React.useMemo(()=>({sync:()=>e.processQueue(),clearQueue:()=>e.clearQueue(),removeMutation:t=>e.removeMutation(t),forceSyncMutation:t=>e.forceSyncMutation(t),getHealthStatus:()=>e.getHealthStatus()}),[e]),isOnline:"offline"!==t.status,isSyncing:"syncing"===t.status,hasErrors:"error"===t.status,pendingCount:t.pending}}function v(e,t,n={}){if("undefined"==typeof React)return function(e,t){const{PersistentStore:n}=require("../data/PersistentStore.js"),s=new n(e,t),r=e=>{"function"==typeof e?s.update(e):s.set(e)};return{store:s,setValue:r,getValue:()=>s.get(),subscribe:e=>s.subscribe(e)}}(e,t,n);const[s]=React.useState(()=>{const{PersistentStore:n}=require("../data/PersistentStore.js");return new n(e,t)});return[b(s),React.useCallback(e=>{"function"==typeof e?s.update(e):s.set(e)},[s]),s]}function E(){if("undefined"==typeof React)return function(){let e="undefined"==typeof navigator||navigator.onLine,t=[];if("undefined"!=typeof window){const t=()=>{e=!0,n()},s=()=>{e=!1,n()};window.addEventListener("online",t),window.addEventListener("offline",s)}function n(){const n={isOnline:e,isOffline:!e,connectionType:"undefined"!=typeof navigator&&navigator.connection?navigator.connection.effectiveType:"unknown"};t.forEach(e=>{try{e(n)}catch(e){console.error("Error in useNetworkState listener:",e)}})}const s=n=>(t.push(n),n({isOnline:e,isOffline:!e,connectionType:"undefined"!=typeof navigator&&navigator.connection?navigator.connection.effectiveType:"unknown"}),()=>{const e=t.indexOf(n);e>-1&&t.splice(e,1)});return{subscribe:s,getCurrentState:()=>({isOnline:e,isOffline:!e,connectionType:"undefined"!=typeof navigator&&navigator.connection?navigator.connection.effectiveType:"unknown"})}}();const[e,t]=React.useState("undefined"==typeof navigator||navigator.onLine);return React.useEffect(()=>{if("undefined"==typeof window)return;const e=()=>t(!0),n=()=>t(!1);return window.addEventListener("online",e),window.addEventListener("offline",n),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",n)}},[]),{isOnline:e,isOffline:!e,connectionType:"undefined"!=typeof navigator&&navigator.connection?navigator.connection.effectiveType:"unknown"}}async function A(e="/kernel.js"){if("serviceWorker"in navigator)try{const t=await navigator.serviceWorker.register(e);console.log("Aether.js Kernel registered with scope:",t.scope),"sync"in t&&(await t.sync.register("aether-sync"),console.log("Aether.js background sync registered."))}catch(e){console.error("Aether.js Kernel registration failed:",e)}else console.warn("Service Workers are not supported in this browser. Aether.js resilience features will be limited.")}const C={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 k{constructor(e=Object.keys(C)){this.enabledPrinciples=e,this.violations=[]}validateComponent(e,t={}){const n=[];for(const s of this.enabledPrinciples){const r=C[s],i=this.validatePrinciple(e,r,t);i.isValid||n.push({principle:s,violations:i.violations,severity:i.severity})}return{isValid:0===n.length,violations:n,score:this.calculateComplianceScore(n)}}validatePrinciple(e,t,n){const s=[];switch(t.name){case"Sustainability First":s.push(...this.validateSustainability(e,n));break;case"Accessibility First":s.push(...this.validateAccessibility(e,n));break;case"Performance First":s.push(...this.validatePerformance(e,n));break;case"Security First":s.push(...this.validateSecurity(e,n));break;case"Resilience First":s.push(...this.validateResilience(e,n));break;case"Privacy First":s.push(...this.validatePrivacy(e,n));break;case"Inclusivity First":s.push(...this.validateInclusivity(e,n))}return{isValid:0===s.length,violations:s,severity:this.calculateSeverity(s)}}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 R(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 k(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 D={NONE:0,BASIC:1,ADAPTIVE:2,PREDICTIVE:3,AUTONOMOUS:4,SYMBIOTIC:5},I={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 P{constructor(e={}){this.aiLevel=e.aiLevel||D.BASIC,this.ethicsConfig={...I,...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>=D.BASIC&&this.setupPatternRecognition(),this.aiLevel>=D.ADAPTIVE&&this.setupAdaptiveLearning(),this.aiLevel>=D.PREDICTIVE&&this.setupPredictiveCapabilities(),this.aiLevel>=D.AUTONOMOUS&&this.setupAutonomousFeatures(),this.aiLevel>=D.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()}),this.logExplanation("pattern_recorded",{pattern:t.key,reason:"User interaction recorded for pattern analysis"})},getCommonPatterns:()=>Array.from(this.behaviorPatterns.entries()).filter(([e,t])=>t.count>=3).sort((e,t)=>t[1].count-e[1].count).slice(0,5)}}setupAdaptiveLearning(){this.adaptiveLearner={adapt:e=>{if(!this.userConsent||!this.learningEnabled)return null;const t=this.patternRecognizer.getCommonPatterns(),n=this.generateAdaptation(t,e);return n&&this.validateAdaptation(n)?(this.adaptationHistory.push({timestamp:Date.now(),adaptation:n,context:e,applied:!1}),this.logExplanation("adaptation_suggested",{adaptation:n.type,reason:n.reasoning,confidence:n.confidence}),n):null},applyAdaptation:(e,t=!1)=>{const n=this.adaptationHistory.find(t=>t.id===e);return!!n&&(!!(t||n.confidence>.8)&&(n.applied=!0,this.logExplanation("adaptation_applied",{adaptation:n.adaptation.type,userApproved:t,reason:"Adaptation applied based on learned patterns"}),!0))}}}setupPredictiveCapabilities(){this.predictor={predictNextAction:e=>{const t=this.patternRecognizer.getCommonPatterns(),n=this.generatePrediction(t,e);return this.logExplanation("prediction_made",{prediction:n.action,confidence:n.confidence,reasoning:n.reasoning}),n},predictUserNeeds:e=>{const t=this.analyzeTemporalPatterns(e),n=this.inferUserNeeds(t);return this.logExplanation("needs_predicted",{needs:n.map(e=>e.type),reasoning:"Based on temporal usage patterns"}),n}}}setupAutonomousFeatures(){this.autonomousAgent={autoOptimize:()=>{if(!this.hasUserPermission("auto_optimize"))return!1;const e=this.identifyOptimizations().filter(e=>"low"===e.risk);return e.forEach(e=>{this.applyOptimization(e),this.logExplanation("auto_optimization",{optimization:e.type,reason:e.reasoning,impact:e.expectedImpact})}),e.length>0},selfHeal:e=>{const t=this.generateHealingStrategy(e);if(t&&t.confidence>.9){const n=this.applyHealing(t);return this.logExplanation("self_healing",{error:e.type,strategy:t.type,success