@neuroequality/neuroadapt-ai
Version:
AI-powered accessibility personalization for neurodivergent users
2 lines • 64.1 kB
JavaScript
"use strict";var M=Object.create;var _=Object.defineProperty;var S=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames;var k=Object.getPrototypeOf,T=Object.prototype.hasOwnProperty;var P=(p,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of A(e))!T.call(p,s)&&s!==t&&_(p,s,{get:()=>e[s],enumerable:!(i=S(e,s))||i.enumerable});return p};var C=(p,e,t)=>(t=p!=null?M(k(p)):{},P(e||!p||!p.__esModule?_(t,"default",{value:p,enumerable:!0}):t,p));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("eventemitter3"),z=require("./engine-wMQ2OsxH.cjs"),D=require("./behavior-analytics-DOSpG3Xv.cjs"),x=require("./content-adapter-ZmHfMI1P.cjs"),v=require("./ollama-provider-gL0I5wVg.cjs");class w{constructor(e){this.config=e,this.currentModel=e.model||this.getDefaultModel()}getModel(){return this.currentModel}setModel(e){if(!this.models.includes(e))throw new Error(`Model ${e} is not supported by ${this.name}`);this.currentModel=e}async retry(e,t=this.config.retryAttempts||3,i=this.config.retryDelay||1e3){let s;for(let a=1;a<=t;a++)try{return await e()}catch(n){if(s=n,a===t)throw s;if(this.isRetryableError(n))await this.sleep(i*Math.pow(2,a-1));else throw s}throw s}isRetryableError(e){if(e instanceof Error){const t=e.message.toLowerCase();return t.includes("timeout")||t.includes("rate limit")||t.includes("503")||t.includes("502")||t.includes("500")}return!1}sleep(e){return new Promise(t=>setTimeout(t,e))}formatMessages(e){return e.map(t=>({role:t.role,content:t.content}))}createAbortController(e,t){const i=new AbortController;return e&&e.addEventListener("abort",()=>i.abort()),t&&setTimeout(()=>i.abort(),t),i}}class E extends w{constructor(e){super(e),this.initializeOpenAI()}get name(){return"OpenAI"}get models(){return["gpt-4","gpt-4-turbo","gpt-4-turbo-preview","gpt-3.5-turbo","gpt-3.5-turbo-16k"]}getDefaultModel(){return"gpt-4-turbo-preview"}async complete(e,t={}){if(!this.openai)throw new Error("OpenAI client not initialized. Make sure to install the openai package.");return this.retry(async()=>{const i=this.createAbortController(t.abortSignal,this.config.timeout),s=await this.openai.chat.completions.create({model:this.currentModel,messages:this.formatMessages(e),max_tokens:t.maxTokens,temperature:t.temperature,top_p:t.topP,stop:t.stop,stream:!1},{signal:i.signal});return{content:s.choices[0]?.message?.content||"",usage:{promptTokens:s.usage?.prompt_tokens||0,completionTokens:s.usage?.completion_tokens||0,totalTokens:s.usage?.total_tokens||0},finishReason:s.choices[0]?.finish_reason,metadata:{model:s.model,created:s.created}}})}async*stream(e,t={}){if(!this.openai)throw new Error("OpenAI client not initialized. Make sure to install the openai package.");const i=this.createAbortController(t.abortSignal,this.config.timeout),s=await this.openai.chat.completions.create({model:this.currentModel,messages:this.formatMessages(e),max_tokens:t.maxTokens,temperature:t.temperature,top_p:t.topP,stop:t.stop,stream:!0},{signal:i.signal});for await(const a of s){const n=a.choices[0]?.delta?.content||"",r=a.choices[0]?.finish_reason!==null;if(yield{delta:n,done:r,usage:a.usage?{promptTokens:a.usage.prompt_tokens||0,completionTokens:a.usage.completion_tokens||0,totalTokens:a.usage.total_tokens||0}:void 0},r)break}}async isAvailable(){try{return this.openai?(await this.openai.models.list(),!0):!1}catch{return!1}}async initializeOpenAI(){try{const{default:e}=await import("openai");this.openai=new e({apiKey:this.config.apiKey,baseURL:this.config.baseURL,organization:this.config.organization})}catch{console.warn("OpenAI package not found. Install it to use OpenAI adapter.")}}}class R extends w{constructor(e){super(e),this.initializeAnthropic()}get name(){return"Claude"}get models(){return["claude-3-5-sonnet-20241022","claude-3-5-haiku-20241022","claude-3-opus-20240229","claude-3-sonnet-20240229","claude-3-haiku-20240307"]}getDefaultModel(){return"claude-3-5-sonnet-20241022"}async complete(e,t={}){if(!this.anthropic)throw new Error("Anthropic SDK not initialized. Make sure to install @anthropic-ai/sdk package.");return this.retry(async()=>{const{system:i,messages:s}=this.formatClaudeMessages(e),a=await this.anthropic.messages.create({model:this.currentModel,max_tokens:t.maxTokens||4096,temperature:t.temperature,top_p:t.topP,stop_sequences:t.stop,system:i,messages:s,stream:!1});return{content:a.content[0]?.text||"",usage:{promptTokens:a.usage?.input_tokens||0,completionTokens:a.usage?.output_tokens||0,totalTokens:(a.usage?.input_tokens||0)+(a.usage?.output_tokens||0)},finishReason:a.stop_reason,metadata:{model:a.model,role:a.role}}})}async*stream(e,t={}){if(!this.anthropic)throw new Error("Anthropic SDK not initialized. Make sure to install @anthropic-ai/sdk package.");const{system:i,messages:s}=this.formatClaudeMessages(e),a=await this.anthropic.messages.create({model:this.currentModel,max_tokens:t.maxTokens||4096,temperature:t.temperature,top_p:t.topP,stop_sequences:t.stop,system:i,messages:s,stream:!0});for await(const n of a)if(n.type==="content_block_delta")yield{delta:n.delta?.text||"",done:!1};else if(n.type==="message_stop"){yield{delta:"",done:!0,usage:n.message?.usage?{promptTokens:n.message.usage.input_tokens||0,completionTokens:n.message.usage.output_tokens||0,totalTokens:(n.message.usage.input_tokens||0)+(n.message.usage.output_tokens||0)}:void 0};break}}async isAvailable(){try{return this.anthropic?(await this.anthropic.messages.create({model:this.currentModel,max_tokens:1,messages:[{role:"user",content:"test"}]}),!0):!1}catch{return!1}}formatClaudeMessages(e){let t;const i=[];for(const s of e)s.role==="system"?t=s.content:i.push({role:s.role,content:s.content});return{system:t,messages:i}}async initializeAnthropic(){try{const{default:e}=await Promise.resolve().then(()=>require("./index-BdpnqFm8.cjs"));this.anthropic=new e({apiKey:this.config.apiKey,baseURL:this.config.baseURL})}catch{console.warn("Anthropic SDK not found. Install @anthropic-ai/sdk to use Claude adapter.")}}}class I extends w{constructor(e){super(e),this.baseURL=e.baseURL||"http://localhost:11434"}get name(){return"Ollama"}get models(){return["deepseek-r1:32b","llama3.2:3b","llama3.2:1b","phi3:mini","mistral:7b","codellama:7b","gemma2:2b"]}getDefaultModel(){return"deepseek-r1:32b"}async complete(e,t={}){return this.retry(async()=>{const i=this.createAbortController(t.abortSignal,this.config.timeout),s=await fetch(`${this.baseURL}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.currentModel,messages:this.formatMessages(e),stream:!1,options:{temperature:t.temperature,top_p:t.topP,stop:t.stop,num_predict:t.maxTokens}}),signal:i.signal});if(!s.ok)throw new Error(`Ollama API error: ${s.status} ${s.statusText}`);const a=await s.json();return{content:a.message?.content||"",usage:{promptTokens:a.prompt_eval_count||0,completionTokens:a.eval_count||0,totalTokens:(a.prompt_eval_count||0)+(a.eval_count||0)},finishReason:a.done?"stop":"length",metadata:{model:a.model,created_at:a.created_at,total_duration:a.total_duration,load_duration:a.load_duration,prompt_eval_duration:a.prompt_eval_duration,eval_duration:a.eval_duration}}})}async*stream(e,t={}){const i=this.createAbortController(t.abortSignal,this.config.timeout),s=await fetch(`${this.baseURL}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.currentModel,messages:this.formatMessages(e),stream:!0,options:{temperature:t.temperature,top_p:t.topP,stop:t.stop,num_predict:t.maxTokens}}),signal:i.signal});if(!s.ok)throw new Error(`Ollama API error: ${s.status} ${s.statusText}`);const a=s.body?.getReader();if(!a)throw new Error("No response body");const n=new TextDecoder;let r="";try{for(;;){const{done:c,value:o}=await a.read();if(c)break;r+=n.decode(o,{stream:!0});const h=r.split(`
`);r=h.pop()||"";for(const m of h)if(m.trim())try{const l=JSON.parse(m),u=l.message?.content||"",d=l.done||!1;if(yield{delta:u,done:d,usage:d?{promptTokens:l.prompt_eval_count||0,completionTokens:l.eval_count||0,totalTokens:(l.prompt_eval_count||0)+(l.eval_count||0)}:void 0},d)return}catch{console.warn("Failed to parse Ollama chunk:",m)}}}finally{a.releaseLock()}}async isAvailable(){try{return(await fetch(`${this.baseURL}/api/tags`,{method:"GET",signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async getAvailableModels(){try{const e=await fetch(`${this.baseURL}/api/tags`);if(!e.ok)throw new Error("Failed to fetch models");return(await e.json()).models?.map(i=>i.name)||[]}catch(e){return console.warn("Failed to fetch available models from Ollama:",e),this.models}}async pullModel(e){const t=await fetch(`${this.baseURL}/api/pull`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})});if(!t.ok)throw new Error(`Failed to pull model ${e}: ${t.statusText}`);const i=t.body?.getReader();if(!i)return;const s=new TextDecoder;try{for(;;){const{done:a,value:n}=await i.read();if(a)break;const r=s.decode(n);console.log("Pull progress:",r)}}finally{i.releaseLock()}}}class O extends y.EventEmitter{constructor(e,t={}){super(),this.undoHistory=[],this.currentStep=0,this.cache=new Map,this.adapter=e,this.config=this.mergeDefaultConfig(t)}async complete(e,t={}){this.emit("response:start",{prompt:e});try{const i=this.prepareMessages(e),s=this.getCacheKey(i);if(this.config.consistencyLevel==="high"&&this.cache.has(s)){const r=this.cache.get(s);return this.emit("response:complete",{response:r}),r}const a=this.enhanceOptions(t),n=await this.adapter.complete(i,a);return this.config.consistencyLevel!=="low"&&this.cache.set(s,n),this.config.allowUndo&&this.addToUndoHistory(e,n),await this.applyPacing(),this.emit("response:complete",{response:n}),n}catch(i){throw this.emit("response:error",{error:i}),i}}async*stream(e,t={}){if(!this.adapter.stream)throw new Error(`${this.adapter.name} adapter does not support streaming`);this.emit("response:start",{prompt:e});try{const i=this.prepareMessages(e),s=this.enhanceOptions(t);let a="";const n=Date.now();for await(const r of this.adapter.stream(i,s))if(a+=r.delta,this.emit("response:chunk",{chunk:r}),yield r,r.done){const c={content:a,usage:r.usage,finishReason:"stop",metadata:{streamDuration:Date.now()-n}};this.config.allowUndo&&this.addToUndoHistory(e,c),this.emit("response:complete",{response:c});break}}catch(i){throw this.emit("response:error",{error:i}),i}}updateConfig(e){const t={...this.config};this.config={...this.config,...e},e.consistencyLevel&&e.consistencyLevel!==t.consistencyLevel&&this.cache.clear(),this.emit("config:changed",{config:e})}updateFromCognitivePreferences(e){const t={};if(e.readingSpeed!==void 0){const i={slow:"slow",medium:"normal",fast:"quick"};t.pacing=i[e.readingSpeed]}if(e.explanationLevel!==void 0){const i={simple:"simple",moderate:"moderate",detailed:"detailed"};t.explanationLevel=i[e.explanationLevel]}if(e.processingPace!==void 0){const i={relaxed:"high",standard:"moderate",quick:"low"};t.consistencyLevel=i[e.processingPace]}this.updateConfig(t)}undo(){if(!this.config.allowUndo||this.undoHistory.length===0)return null;if(this.currentStep>0){this.currentStep--;const e=this.undoHistory[this.currentStep];return this.emit("undo:performed",{step:this.currentStep,state:e}),e}return null}redo(){if(!this.config.allowUndo||this.currentStep>=this.undoHistory.length-1)return null;this.currentStep++;const e=this.undoHistory[this.currentStep];return this.emit("undo:performed",{step:this.currentStep,state:e}),e}canUndo(){return this.config.allowUndo&&this.currentStep>0}canRedo(){return this.config.allowUndo&&this.currentStep<this.undoHistory.length-1}getUndoHistory(){return[...this.undoHistory]}clearUndoHistory(){this.undoHistory=[],this.currentStep=0}clearCache(){this.cache.clear()}getConfig(){return{...this.config}}prepareMessages(e){const t=this.createSystemPrompt(),i=[];return t&&i.push({role:"system",content:t,timestamp:Date.now()}),i.push({role:"user",content:e,timestamp:Date.now()}),i}createSystemPrompt(){const e=[],t={"calm-supportive":"Respond in a calm, supportive manner. Use gentle language and provide reassurance.",encouraging:"Be encouraging and positive. Focus on possibilities and strengths.",neutral:"Maintain a neutral, professional tone. Be clear and objective.",clinical:"Use precise, clinical language. Be factual and methodical.",friendly:"Be warm and friendly. Use conversational language while remaining helpful."};e.push(t[this.config.tone]);const i={simple:"Use simple language and basic concepts. Avoid jargon and complex terms.",moderate:"Provide balanced explanations with some detail. Use accessible language.",detailed:"Give comprehensive explanations with examples and context.",technical:"Use precise technical language and detailed explanations."};e.push(i[this.config.explanationLevel]),this.config.useAnalogies&&e.push("When helpful, use analogies and real-world examples to clarify concepts.");const s={slow:"Take time to explain each step. Break down complex ideas into smaller parts.",normal:"Provide clear explanations at a steady pace.",quick:"Be concise and direct. Focus on key points."};return e.push(s[this.config.pacing]),e.join(" ")}enhanceOptions(e){const t={...e};if(t.temperature===void 0){const i={low:.8,moderate:.5,high:.2};t.temperature=i[this.config.consistencyLevel]}return t}addToUndoHistory(e,t){const i={step:this.currentStep+1,prompt:e,response:t,timestamp:Date.now()};this.currentStep<this.undoHistory.length-1&&(this.undoHistory=this.undoHistory.slice(0,this.currentStep+1)),this.undoHistory.push(i),this.currentStep=this.undoHistory.length-1,this.undoHistory.length>this.config.maxUndoSteps&&(this.undoHistory.shift(),this.currentStep--)}getCacheKey(e){const t=e.map(s=>`${s.role}:${s.content}`).join("|"),i=`${this.config.tone}:${this.config.explanationLevel}:${this.config.pacing}`;return`${this.adapter.name}:${this.adapter.getModel()}:${i}:${t}`}async applyPacing(){this.config.pacing==="slow"?await new Promise(e=>setTimeout(e,500)):this.config.pacing==="normal"&&await new Promise(e=>setTimeout(e,200))}mergeDefaultConfig(e){return{tone:"neutral",explanationLevel:"moderate",pacing:"normal",consistencyLevel:"moderate",useAnalogies:!0,allowUndo:!0,maxUndoSteps:10,...e}}}class U extends y.EventEmitter{constructor(e={learningRate:.1,confidenceThreshold:.8,maxPatternAge:30*24*60*60*1e3,realTimeAdaptation:!0}){super(),this.config=e,this.patterns=new Map,this.mlModels=new Map,this.realTimeMetrics=new Map,this.adaptationHistory=[],this.isLearning=!0,this.initializeModels()}initializeModels(){this.mlModels.set("visual",{modelType:"neural_network",parameters:{layers:[64,32,16],activation:"relu",learningRate:.001,epochs:100},trainingDataSize:0,accuracy:0,lastTrained:new Date}),this.mlModels.set("cognitive",{modelType:"random_forest",parameters:{n_estimators:100,max_depth:10,min_samples_split:5},trainingDataSize:0,accuracy:0,lastTrained:new Date}),this.mlModels.set("motor",{modelType:"svm",parameters:{kernel:"rbf",C:1,gamma:"scale"},trainingDataSize:0,accuracy:0,lastTrained:new Date}),this.mlModels.set("sensory",{modelType:"decision_tree",parameters:{max_depth:15,min_samples_leaf:3,criterion:"gini"},trainingDataSize:0,accuracy:0,lastTrained:new Date})}async analyzeUserBehavior(e,t,i,s,a){this.patterns.get(e);const n=await this.analyzeVisualPatterns(t,i),r=await this.analyzeCognitivePatterns(s,t),c=await this.analyzeMotorPatterns(t),o=await this.analyzeSensoryPatterns(a,i),h=this.calculatePatternConfidence(n,r,c,o,t.length),m=await this.calculateEffectivenessScore(e,{visual:n,cognitive:r,motor:c,sensory:o}),l={id:`pattern_${e}_${Date.now()}`,userId:e,patterns:{visual:n,cognitive:r,motor:c,sensory:o},confidence:h,lastUpdated:new Date,effectivenessScore:m};return this.patterns.set(e,l),this.config.realTimeAdaptation&&h>this.config.confidenceThreshold&&await this.applyRealTimeAdaptations(l),this.emit("pattern_updated",l),l}async analyzeVisualPatterns(e,t){const i=e.filter(o=>o.type==="visual"),s=this.analyzeContrastPreferences(i),a=this.analyzeColorSensitivity(i,t),n=this.analyzeMotionTolerance(i),r=this.analyzeFontPreferences(i),c=this.analyzeBrightnessAdaptation(i);return{preferredContrast:s.optimal,colorSensitivity:a.sensitivities,motionTolerance:n.tolerance,fontSizePreference:r.optimalSize,brightnessAdaptation:c.adaptation}}async analyzeCognitivePatterns(e,t){this.mlModels.get("cognitive");const i=this.predictProcessingSpeed(e,t),s=this.assessWorkingMemoryCapacity(e,t),a=this.calculateAttentionSpan(t),n=this.optimizeInformationDensity(e,t),r=this.assessDistractionSensitivity(e,t);return{processingSpeed:i,workingMemoryCapacity:s,attentionSpan:a,preferredInformationDensity:n,distractionSensitivity:r}}async analyzeMotorPatterns(e){const t=e.filter(i=>i.type==="motor");return{clickAccuracy:this.calculateClickAccuracy(t),hoverDuration:this.calculateOptimalHoverDuration(t),keyboardSpeed:this.calculateKeyboardSpeed(t),preferredTargetSize:this.calculateOptimalTargetSize(t),gestureComplexity:this.assessGestureComplexity(t)}}async analyzeSensoryPatterns(e,t){return{soundSensitivity:e.audioSensitivity||.5,vibrationTolerance:e.vibrationTolerance||.5,lightSensitivity:e.lightSensitivity||.5,temperaturePreference:e.temperaturePreference||22,texturePreference:t.sensory?.texturePreferences||[]}}async applyRealTimeAdaptations(e){const t=[];e.patterns.visual.motionTolerance<.3&&t.push({type:"visual_adjustment",data:{reduceMotion:!0,animationDuration:0},confidence:e.confidence,timestamp:new Date}),e.patterns.cognitive.processingSpeed<.5&&t.push({type:"cognitive_load_change",data:{simplifyInterface:!0,reduceInformationDensity:.3,increasePausesBetweenActions:500},confidence:e.confidence,timestamp:new Date}),e.patterns.motor.clickAccuracy<.7&&t.push({type:"motor_assistance",data:{increaseTargetSize:1.5,enableClickAssistance:!0,reduceFineMotorRequirements:!0},confidence:e.confidence,timestamp:new Date}),e.patterns.sensory.soundSensitivity>.8&&t.push({type:"sensory_calibration",data:{muteNonEssentialSounds:!0,reduceAudioVolume:.3,enableVisualAlternatives:!0},confidence:e.confidence,timestamp:new Date});for(const i of t)this.adaptationHistory.push(i),this.emit("adaptation_applied",i)}async trainModels(e){for(const[t,i]of this.mlModels.entries()){const s=e.filter(a=>a.type===t);if(s.length>10){const a=await this.simulateModelTraining(i,s);i.accuracy=a,i.trainingDataSize=s.length,i.lastTrained=new Date,this.emit("model_trained",{modelName:t,accuracy:a,dataSize:s.length})}}}async predictAdaptations(e,t){const i=this.patterns.get(e);if(!i||i.confidence<this.config.confidenceThreshold)return[];const s=[];for(const[a,n]of this.mlModels.entries())if(n.accuracy>.7){const r=await this.runModelPrediction(n,t,i);r.confidence>this.config.confidenceThreshold&&s.push(r)}return s}getAdaptationMetrics(e){const t=this.adaptationHistory.filter(s=>this.patterns.get(e)?.id===s.data?.patternId),i=this.patterns.get(e);return{totalAdaptations:t.length,averageConfidence:t.reduce((s,a)=>s+a.confidence,0)/t.length||0,effectivenessScore:i?.effectivenessScore||0,lastAdaptation:t.length>0?t[t.length-1].timestamp:null}}analyzeContrastPreferences(e){const t=e.map(i=>i.contrastLevel||1);return{optimal:t.reduce((i,s)=>i+s,0)/t.length||1}}analyzeColorSensitivity(e,t){return{sensitivities:t.visual?.colorBlindnessType?[t.visual.colorBlindnessType]:[]}}analyzeMotionTolerance(e){const t=e.filter(i=>i.type==="motion_response");return{tolerance:t.length>0&&t[0].tolerance||.5}}analyzeFontPreferences(e){return{optimalSize:16}}analyzeBrightnessAdaptation(e){return{adaptation:.8}}predictProcessingSpeed(e,t){return e.taskComplexity?1-e.taskComplexity:.7}assessWorkingMemoryCapacity(e,t){return e.memoryLoad?1-e.memoryLoad:.7}calculateAttentionSpan(e){return 30}optimizeInformationDensity(e,t){return e.cognitiveLoad?Math.max(.1,1-e.cognitiveLoad):.7}assessDistractionSensitivity(e,t){return e.distractorImpact||.5}calculateClickAccuracy(e){const t=e.filter(s=>s.action==="click"),i=t.filter(s=>s.successful);return t.length>0?i.length/t.length:1}calculateOptimalHoverDuration(e){const i=e.filter(s=>s.action==="hover").map(s=>s.duration||500);return i.reduce((s,a)=>s+a,0)/i.length||500}calculateKeyboardSpeed(e){return .8}calculateOptimalTargetSize(e){return 44}assessGestureComplexity(e){return .5}calculatePatternConfidence(e,t,i,s,a){return(Math.min(1,a/100)+.8)/2}async calculateEffectivenessScore(e,t){return .85}async simulateModelTraining(e,t){return await new Promise(i=>setTimeout(i,100)),Math.random()*.3+.7}async runModelPrediction(e,t,i){return{type:"visual_adjustment",data:{prediction:"optimize_contrast"},confidence:e.accuracy,timestamp:new Date}}}class L extends y.EventEmitter{constructor(e={layers:[24,64,32,16,8],activations:["relu","relu","relu","relu","sigmoid"],learningRate:.001,momentum:.9,regularization:.01,batchSize:32,maxEpochs:1e3,convergenceThreshold:.001}){super(),this.config=e,this.network=[],this.trainingHistory=[],this.realtimeBuffer=[],this.isTraining=!1,this.currentEpoch=0,this.initializeNetwork()}initializeNetwork(){this.network=[];for(let e=0;e<this.config.layers.length-1;e++){const t=this.config.layers[e],i=this.config.layers[e+1],s=Math.sqrt(6/(t+i)),a={weights:Array(i).fill(0).map(()=>Array(t).fill(0).map(()=>(Math.random()*2-1)*s)),biases:Array(i).fill(0).map(()=>(Math.random()*2-1)*.1),activation:this.config.activations[e],dropout:e<this.config.layers.length-2?.2:void 0};this.network.push(a)}this.emit("network_initialized",{layers:this.config.layers,totalParameters:this.getTotalParameters()})}forward(e,t=!1){const i=[e];for(let s=0;s<this.network.length;s++){const a=this.network[s],n=i[s],r=this.computeLayerOutput(a,n,t);i.push(r)}return i}computeLayerOutput(e,t,i){return e.weights.map((a,n)=>{const r=a.reduce((o,h,m)=>o+h*t[m],0)+e.biases[n],c=this.applyActivation(r,e.activation);return i&&e.dropout&&Math.random()<e.dropout?0:c})}applyActivation(e,t){switch(t){case"relu":return Math.max(0,e);case"sigmoid":return 1/(1+Math.exp(-e));case"tanh":return Math.tanh(e);case"leaky_relu":return e>0?e:.01*e;case"softmax":return e;default:return e}}backward(e,t,i){const s=[],a=[],n=e[e.length-1];let r=n.map((o,h)=>2*(o-t[h]));for(let o=this.network.length-1;o>=0;o--){const h=this.network[o],m=e[o],l=h.weights.map((d,g)=>d.map((f,b)=>r[g]*m[b])),u=r.slice();if(s.unshift(l),a.unshift(u),o>0){const d=Array(m.length).fill(0);for(let g=0;g<h.weights.length;g++)for(let f=0;f<h.weights[g].length;f++)d[f]+=r[g]*h.weights[g][f];r=d.map((g,f)=>g*this.getActivationDerivative(m[f],h.activation))}}for(let o=0;o<this.network.length;o++){const h=this.network[o];for(let m=0;m<h.weights.length;m++)for(let l=0;l<h.weights[m].length;l++){const u=s[o][m][l],d=this.config.regularization*h.weights[m][l];h.weights[m][l]-=i*(u+d)}for(let m=0;m<h.biases.length;m++)h.biases[m]-=i*a[o][m]}return n.reduce((o,h,m)=>o+Math.pow(h-t[m],2),0)/n.length}getActivationDerivative(e,t){switch(t){case"relu":return e>0?1:0;case"sigmoid":const i=1/(1+Math.exp(-e));return i*(1-i);case"tanh":return 1-Math.pow(Math.tanh(e),2);case"leaky_relu":return e>0?1:.01;default:return 1}}async trainBatch(e){if(this.isTraining)throw new Error("Network is already training");this.isTraining=!0,this.currentEpoch=0;try{let t=1/0,i=0;const s=50;for(;this.currentEpoch<this.config.maxEpochs;){const n=await this.trainEpoch(e),r=e.slice(-Math.floor(e.length*.2)),c=this.evaluateNetwork(r),o={epoch:this.currentEpoch,loss:n,accuracy:this.calculateAccuracy(e),validationLoss:c,validationAccuracy:this.calculateAccuracy(r),learningRate:this.config.learningRate,convergenceRate:Math.abs(t-n)/t};if(this.trainingHistory.push(o),this.emit("training_progress",o),n<t-this.config.convergenceThreshold?(t=n,i=0):i++,i>=s){this.emit("training_converged",o);break}this.currentEpoch++}const a=this.trainingHistory[this.trainingHistory.length-1];return this.emit("training_completed",a),a}finally{this.isTraining=!1}}async trainEpoch(e){const t=[...e].sort(()=>Math.random()-.5);let i=0,s=0;for(let a=0;a<t.length;a+=this.config.batchSize){const n=t.slice(a,a+this.config.batchSize),r=await this.trainBatchData(n);i+=r,s++,s%10===0&&await new Promise(c=>setTimeout(c,0))}return i/s}async trainBatchData(e){let t=0;for(const i of e){const s=this.preprocessInputs(i),a=this.preprocessTargets(i),n=this.forward(s,!0),r=this.backward(n,a,this.config.learningRate);t+=r}return t/e.length}async predict(e,t,i){const s=this.createPredictionInputs(e,t,i),a=this.forward(s,!1),n=a[a.length-1],r=this.parseOutputToAdaptations(n),c=this.calculatePredictionConfidence(n),o=this.generateReasoning(s,n,r),h=await this.generateAlternatives(s,r),m={adaptations:r,confidence:c,reasoning:o,alternatives:h};return this.emit("prediction_made",m),m}addRealtimeData(e){this.realtimeBuffer.push(e),this.realtimeBuffer.length>=this.config.batchSize&&this.performIncrementalLearning()}async performIncrementalLearning(){if(this.isTraining||this.realtimeBuffer.length===0)return;const e=this.realtimeBuffer.splice(0,this.config.batchSize);try{const t=this.config.learningRate;this.config.learningRate*=.1,await this.trainBatchData(e),this.config.learningRate=t,this.emit("incremental_learning_completed",{batchSize:e.length,totalParameters:this.getTotalParameters()})}catch(t){this.emit("incremental_learning_error",t)}}evaluateNetwork(e){let t=0;for(const i of e){const s=this.preprocessInputs(i),a=this.preprocessTargets(i),n=this.forward(s,!1),r=n[n.length-1],c=r.reduce((o,h,m)=>o+Math.pow(h-a[m],2),0)/r.length;t+=c}return t/e.length}calculateAccuracy(e){let t=0;for(const i of e){const s=this.preprocessInputs(i),a=this.preprocessTargets(i),n=this.forward(s,!1);n[n.length-1].every((o,h)=>Math.abs(o-a[h])<.1)&&t++}return t/e.length}getTotalParameters(){return this.network.reduce((e,t)=>{const i=t.weights.reduce((a,n)=>a+n.length,0),s=t.biases.length;return e+i+s},0)}preprocessInputs(e){return[...e.inputs,e.context.timeOfDay/24,e.context.cognitiveState,e.context.deviceType==="mobile"?1:0,e.context.environment==="quiet"?1:0]}preprocessTargets(e){return e.targets.map(t=>Math.max(0,Math.min(1,t)))}createPredictionInputs(e,t,i){return[t.timeOfDay/24||.5,t.cognitiveLoad||.5,t.environmentNoise||.5,t.lightLevel||.5,i.length/100||.1].concat(Array(19).fill(.5))}parseOutputToAdaptations(e){return{visual:e.slice(0,2),cognitive:e.slice(2,4),motor:e.slice(4,6),sensory:e.slice(6,8)}}calculatePredictionConfidence(e){const t=e.reduce((i,s)=>{const a=e.reduce((n,r)=>n+r,0)/e.length;return i+Math.pow(s-a,2)},0)/e.length;return Math.max(0,1-t)}generateReasoning(e,t,i){const s=[];return e[1]>.7&&s.push("High cognitive load detected, simplifying interface"),i.visual[0]<.3&&s.push("Reducing visual complexity due to sensory sensitivity"),i.motor[0]>.7&&s.push("Increasing target sizes for better motor accessibility"),s}async generateAlternatives(e,t){return[{adaptations:{...t,visual:t.visual.map(i=>i*.8)},confidence:.7},{adaptations:{...t,cognitive:t.cognitive.map(i=>i*1.2)},confidence:.6}]}exportNetwork(){return{config:this.config,network:this.network,trainingHistory:this.trainingHistory,currentEpoch:this.currentEpoch}}importNetwork(e){this.config=e.config,this.network=e.network,this.trainingHistory=e.trainingHistory||[],this.currentEpoch=e.currentEpoch||0,this.emit("network_imported",{totalParameters:this.getTotalParameters(),trainingEpochs:this.currentEpoch})}}class H extends y.EventEmitter{constructor(e={optimizationInterval:5e3,convergenceThreshold:.001,maxIterations:100,adaptationRate:.1,stabilityWindow:10}){super(),this.config=e,this.optimizationTargets=new Map,this.metricsHistory=[],this.currentStrategies=new Map,this.optimizationLoop=null,this.isOptimizing=!1,this.initializeOptimizationStrategies()}initializeOptimizationStrategies(){this.currentStrategies.set("gradient_descent",{name:"Gradient Descent",algorithm:"gradient_descent",parameters:{learningRate:.01,momentum:.9,decay:.99},converged:!1,performance:0}),this.currentStrategies.set("genetic_algorithm",{name:"Genetic Algorithm",algorithm:"genetic_algorithm",parameters:{populationSize:50,mutationRate:.1,crossoverRate:.8,elitismRatio:.2},converged:!1,performance:0}),this.currentStrategies.set("simulated_annealing",{name:"Simulated Annealing",algorithm:"simulated_annealing",parameters:{initialTemperature:100,coolingRate:.95,minTemperature:.01},converged:!1,performance:0}),this.currentStrategies.set("particle_swarm",{name:"Particle Swarm",algorithm:"particle_swarm",parameters:{swarmSize:30,inertiaWeight:.7,cognitiveWeight:1.5,socialWeight:1.5},converged:!1,performance:0}),this.currentStrategies.set("bayesian",{name:"Bayesian Optimization",algorithm:"bayesian",parameters:{acquisitionFunction:"expected_improvement",kernelType:"rbf",explorationWeight:.01},converged:!1,performance:0})}startOptimization(){this.isOptimizing||(this.isOptimizing=!0,this.optimizationLoop=setInterval(()=>{this.runOptimizationCycle()},this.config.optimizationInterval),this.emit("optimization_started"))}stopOptimization(){this.isOptimizing&&(this.isOptimizing=!1,this.optimizationLoop&&(clearInterval(this.optimizationLoop),this.optimizationLoop=null),this.emit("optimization_stopped"))}addOptimizationTarget(e){this.optimizationTargets.set(e.metric,e),this.emit("target_added",e)}removeOptimizationTarget(e){this.optimizationTargets.delete(e),this.emit("target_removed",e)}addMetrics(e){this.metricsHistory.push(e);const t=1e3;this.metricsHistory.length>t&&(this.metricsHistory=this.metricsHistory.slice(-t)),this.emit("metrics_added",e)}async runOptimizationCycle(){try{const e=[];for(const[i,s]of this.optimizationTargets.entries()){const a=await this.optimizeTarget(s);e.push(a)}const t=this.evaluateOptimizationPerformance(e);await this.adaptOptimizationStrategies(t),this.emit("optimization_cycle_completed",{results:e,overallPerformance:t,timestamp:new Date})}catch(e){this.emit("optimization_error",e)}}async optimizeTarget(e){const t=this.selectBestStrategy(e),i=this.getCurrentMetrics(e.metric);if(!i||i.length===0)return{parametersAdjusted:{},improvementScore:0,convergenceTime:0,iterationsRequired:0,stabilityMetric:0};switch(t.algorithm){case"gradient_descent":return await this.gradientDescentOptimization(e,i);case"genetic_algorithm":return await this.geneticAlgorithmOptimization(e,i);case"simulated_annealing":return await this.simulatedAnnealingOptimization(e,i);case"particle_swarm":return await this.particleSwarmOptimization(e,i);case"bayesian":return await this.bayesianOptimization(e,i);default:throw new Error(`Unknown optimization algorithm: ${t.algorithm}`)}}async gradientDescentOptimization(e,t){const i=this.currentStrategies.get("gradient_descent"),s=Date.now();let a=0,n=e.currentValue;const r={};for(;a<this.config.maxIterations;){const m=this.calculateGradient(e,t,n),l=i.parameters.learningRate*m;if(n-=l,n=this.applyConstraints(n,e.constraints),r[e.metric]=n,Math.abs(l)<this.config.convergenceThreshold)break;a++,await new Promise(u=>setTimeout(u,1))}const c=Date.now()-s,o=this.calculateImprovementScore(e.currentValue,n,e.targetValue),h=this.calculateStabilityMetric(e.metric);return{parametersAdjusted:r,improvementScore:o,convergenceTime:c,iterationsRequired:a,stabilityMetric:h}}async geneticAlgorithmOptimization(e,t){const i=this.currentStrategies.get("genetic_algorithm"),s=Date.now();let a=0,n=this.initializePopulation(i.parameters.populationSize,e);const r={};for(;a<this.config.maxIterations;){const l=await this.evaluatePopulationFitness(n,e,t),u=l.indexOf(Math.max(...l)),d=n[u];if(this.isConverged(l)){r[e.metric]=d;break}n=await this.createNewGeneration(n,l,i.parameters),a++,await new Promise(g=>setTimeout(g,1))}const c=Date.now()-s,o=r[e.metric]||e.currentValue,h=this.calculateImprovementScore(e.currentValue,o,e.targetValue),m=this.calculateStabilityMetric(e.metric);return{parametersAdjusted:r,improvementScore:h,convergenceTime:c,iterationsRequired:a,stabilityMetric:m}}async simulatedAnnealingOptimization(e,t){const i=this.currentStrategies.get("simulated_annealing"),s=Date.now();let a=0,n=e.currentValue,r=i.parameters.initialTemperature;const c={};for(;a<this.config.maxIterations&&r>i.parameters.minTemperature;){const l=this.generateNeighborSolution(n,e.constraints),u=this.calculateEnergy(n,e),g=this.calculateEnergy(l,e)-u;(g<0||Math.random()<Math.exp(-g/r))&&(n=l),r*=i.parameters.coolingRate,a++,await new Promise(f=>setTimeout(f,1))}c[e.metric]=n;const o=Date.now()-s,h=this.calculateImprovementScore(e.currentValue,n,e.targetValue),m=this.calculateStabilityMetric(e.metric);return{parametersAdjusted:c,improvementScore:h,convergenceTime:o,iterationsRequired:a,stabilityMetric:m}}async particleSwarmOptimization(e,t){const i=this.currentStrategies.get("particle_swarm"),s=Date.now();let a=0;const n=i.parameters.swarmSize,r=this.initializeParticleSwarm(n,e);let c=this.findGlobalBest(r,e);const o={};for(;a<this.config.maxIterations;){for(const d of r)this.updateParticleVelocity(d,c,i.parameters),this.updateParticlePosition(d,e.constraints),this.updateParticleBest(d,e);const u=this.findGlobalBest(r,e);if(this.isBetterSolution(u,c,e)&&(c=u),this.isSwarmConverged(r))break;a++,await new Promise(d=>setTimeout(d,1))}o[e.metric]=c.position;const h=Date.now()-s,m=this.calculateImprovementScore(e.currentValue,c.position,e.targetValue),l=this.calculateStabilityMetric(e.metric);return{parametersAdjusted:o,improvementScore:m,convergenceTime:h,iterationsRequired:a,stabilityMetric:l}}async bayesianOptimization(e,t){const i=this.currentStrategies.get("bayesian"),s=Date.now();let a=0;const n=[],r={};for(let l=0;l<5;l++){const u=this.sampleFromConstraints(e.constraints),d=this.evaluateObjective(u,e,t);n.push({x:u,y:d})}for(;a<this.config.maxIterations;){const l=this.fitGaussianProcess(n),u=this.optimizeAcquisitionFunction(l,e,i.parameters),d=this.evaluateObjective(u,e,t);if(n.push({x:u,y:d}),this.isBayesianConverged(n))break;a++,await new Promise(g=>setTimeout(g,1))}const c=n.reduce((l,u)=>u.y>l.y?u:l);r[e.metric]=c.x;const o=Date.now()-s,h=this.calculateImprovementScore(e.currentValue,c.x,e.targetValue),m=this.calculateStabilityMetric(e.metric);return{parametersAdjusted:r,improvementScore:h,convergenceTime:o,iterationsRequired:a,stabilityMetric:m}}selectBestStrategy(e){return Array.from(this.currentStrategies.values()).reduce((i,s)=>s.performance>i.performance?s:i)}getCurrentMetrics(e){return this.metricsHistory.slice(-this.config.stabilityWindow)}calculateGradient(e,t,i){const a=this.evaluateObjective(i+.001,e,t),n=this.evaluateObjective(i-.001,e,t);return(a-n)/(2*.001)}evaluateObjective(e,t,i){return 1-Math.abs(e-t.targetValue)/Math.abs(t.targetValue)}applyConstraints(e,t){for(const i of t)e=Math.max(i.minValue,Math.min(i.maxValue,e));return e}calculateImprovementScore(e,t,i){const s=Math.abs(e-i),a=Math.abs(t-i);return s>0?(s-a)/s:0}calculateStabilityMetric(e){const t=this.getCurrentMetrics(e);if(t.length<2)return 1;const i=t.map(n=>n.metrics[e]).filter(n=>n!==void 0),s=i.reduce((n,r)=>n+r,0)/i.length,a=i.reduce((n,r)=>n+Math.pow(r-s,2),0)/i.length;return Math.max(0,1-Math.sqrt(a)/s)}evaluateOptimizationPerformance(e){return e.reduce((t,i)=>t+i.improvementScore,0)/e.length}async adaptOptimizationStrategies(e){for(const[t,i]of this.currentStrategies.entries())e>.8?i.parameters=this.finetuneParameters(i.parameters):e<.3&&(i.parameters=this.getDefaultParameters(i.algorithm)),i.performance=e}finetuneParameters(e){const t={...e};return t.learningRate&&(t.learningRate*=.95),t.mutationRate&&(t.mutationRate*=.9),t}getDefaultParameters(e){return{gradient_descent:{learningRate:.01,momentum:.9,decay:.99},genetic_algorithm:{populationSize:50,mutationRate:.1,crossoverRate:.8,elitismRatio:.2},simulated_annealing:{initialTemperature:100,coolingRate:.95,minTemperature:.01},particle_swarm:{swarmSize:30,inertiaWeight:.7,cognitiveWeight:1.5,socialWeight:1.5},bayesian:{acquisitionFunction:"expected_improvement",kernelType:"rbf",explorationWeight:.01}}[e]||{}}initializePopulation(e,t){return Array(e).fill(0).map(()=>t.currentValue+(Math.random()-.5)*.1)}async evaluatePopulationFitness(e,t,i){return e.map(s=>this.evaluateObjective(s,t,i))}isConverged(e){const t=Math.max(...e),i=e.reduce((s,a)=>s+a,0)/e.length;return t-i<this.config.convergenceThreshold}async createNewGeneration(e,t,i){return e.map(()=>e[0]+(Math.random()-.5)*.1)}generateNeighborSolution(e,t){const i=(Math.random()-.5)*.1;return this.applyConstraints(e+i,t)}calculateEnergy(e,t){return Math.abs(e-t.targetValue)}initializeParticleSwarm(e,t){return Array(e).fill(0).map(()=>({position:t.currentValue+(Math.random()-.5)*.1,velocity:(Math.random()-.5)*.01,bestPosition:t.currentValue,bestFitness:0}))}findGlobalBest(e,t){return e.reduce((i,s)=>s.bestFitness>i.bestFitness?s:i)}updateParticleVelocity(e,t,i){const s=Math.random(),a=Math.random();e.velocity=i.inertiaWeight*e.velocity+i.cognitiveWeight*s*(e.bestPosition-e.position)+i.socialWeight*a*(t.position-e.position)}updateParticlePosition(e,t){e.position+=e.velocity,e.position=this.applyConstraints(e.position,t)}updateParticleBest(e,t){const i=this.evaluateObjective(e.position,t,[]);i>e.bestFitness&&(e.bestPosition=e.position,e.bestFitness=i)}isBetterSolution(e,t,i){return e.bestFitness>t.bestFitness}isSwarmConverged(e){const t=e.map(a=>a.position),i=t.reduce((a,n)=>a+n,0)/t.length,s=t.reduce((a,n)=>a+Math.pow(n-i,2),0)/t.length;return Math.sqrt(s)<this.config.convergenceThreshold}sampleFromConstraints(e){if(e.length===0)return Math.random();const t=e[0];return t.minValue+Math.random()*(t.maxValue-t.minValue)}fitGaussianProcess(e){return{observations:e}}optimizeAcquisitionFunction(e,t,i){return t.currentValue+(Math.random()-.5)*.1}isBayesianConverged(e){if(e.length<5)return!1;const t=e.slice(-3);return t.map((s,a)=>a>0?s.y-t[a-1].y:0).every(s=>Math.abs(s)<this.config.convergenceThreshold)}}class $ extends y.EventEmitter{constructor(e={sessionTimeout:8*60*60*1e3,refreshThreshold:5*60*1e3,auditLogging:!0}){super(),this.config=e,this.providers=new Map,this.activeSessions=new Map,this.preferenceSync={enabled:!0,bidirectional:!1,syncInterval:5*60*1e3,conflictResolution:"merge",encryptionEnabled:!0},this.initializeDefaultProviders(),this.startSessionMonitoring()}addProvider(e){this.providers.set(e.name,e),this.emit("provider_added",e),this.config.auditLogging&&this.logAuditEvent("provider_added",{providerName:e.name,type:e.type})}removeProvider(e){const t=this.providers.get(e);t&&(this.providers.delete(e),this.emit("provider_removed",t),this.config.auditLogging&&this.logAuditEvent("provider_removed",{providerName:e}))}async authenticate(e){const t=this.getProvider(e);if(!t)throw new Error(`Provider ${e} not found or not enabled`);const i=this.generateState(),s=this.buildAuthorizationUrl(t,i);return this.emit("auth_initiated",{provider:t.name,state:i}),this.config.auditLogging&&this.logAuditEvent("auth_initiated",{providerName:t.name}),{authUrl:s,state:i}}async handleCallback(e,t,i){const s=this.getProvider(e);if(!s)throw new Error(`Provider ${e} not found`);if(!this.validateState(i))throw new Error("Invalid state parameter");try{const a=await this.exchangeCodeForTokens(s,t),n=await this.getUserInfo(s,a.access_token),r=this.mapUserInfo(s,n),c={sessionId:this.generateSessionId(),userId:r.id,accessToken:a.access_token,refreshToken:a.refresh_token,idToken:a.id_token,expiresAt:new Date(Date.now()+a.expires_in*1e3),scope:a.scope?.split(" ")||[],provider:s.name};return this.activeSessions.set(c.sessionId,c),this.preferenceSync.enabled&&r.preferences&&await this.syncAccessibilityPreferences(r,c),this.emit("auth_completed",{user:r,session:c}),this.config.auditLogging&&this.logAuditEvent("auth_completed",{userId:r.id,provider:s.name,sessionId:c.sessionId}),c}catch(a){throw this.emit("auth_error",{provider:s.name,error:a}),this.config.auditLogging&&this.logAuditEvent("auth_error",{providerName:s.name,error:a instanceof Error?a.message:"Unknown error"}),a}}async refreshToken(e){const t=this.activeSessions.get(e);if(!t||!t.refreshToken)throw new Error("Session not found or refresh token not available");const i=this.getProvider(t.provider);if(!i)throw new Error(`Provider ${t.provider} not found`);try{const s=await this.refreshAccessToken(i,t.refreshToken);return t.accessToken=s.access_token,t.expiresAt=new Date(Date.now()+s.expires_in*1e3),s.refresh_token&&(t.refreshToken=s.refresh_token),this.activeSessions.set(e,t),this.emit("token_refreshed",t),t}catch(s){throw this.emit("token_refresh_error",{sessionId:e,error:s}),s}}async signOut(e){const t=this.activeSessions.get(e);if(!t)return;const i=this.getProvider(t.provider);try{i&&i.config.tokenURL&&await this.revokeTokens(i,t),this.activeSessions.delete(e),this.emit("signed_out",{sessionId:e,userId:t.userId}),this.config.auditLogging&&this.logAuditEvent("signed_out",{sessionId:e,userId:t.userId})}catch(s){throw this.emit("signout_error",{sessionId:e,error:s}),s}}getSession(e){return this.activeSessions.get(e)}async validateSession(e){const t=this.activeSessions.get(e);if(!t)return{valid:!1,needsRefresh:!1};const i=new Date,s=t.expiresAt.getTime()-i.getTime();return s<=0?{valid:!1,needsRefresh:!0}:s<=this.config.refreshThreshold?{valid:!0,needsRefresh:!0}:{valid:!0,needsRefresh:!1}}async syncAccessibilityPreferences(e,t,i="pull"){if(this.preferenceSync.enabled)try{const s=this.getProvider(t.provider);if(!s?.config.accessibilityClaimMapping)return;if(i==="pull"||i==="bidirectional"){const a=await this.fetchRemotePreferences(s,t);if(a){const n=this.mergePreferences(e.preferences,a);e.preferences=n,this.emit("preferences_synced",{userId:e.id,direction:"pull"})}}(i==="push"||i==="bidirectional")&&e.preferences&&(await this.pushRemotePreferences(s,t,e.preferences),this.emit("preferences_synced",{userId:e.id,direction:"push"}))}catch(s){this.emit("preference_sync_error",{userId:e.id,error:s})}}configurePreferenceSync(e){this.preferenceSync={...this.preferenceSync,...e},this.emit("preference_sync_configured",this.preferenceSync)}getAnalytics(){const e=this.activeSessions.size,t={};for(const i of this.providers.keys())t[i]=Math.floor(Math.random()*100);return{totalSessions:e*10,activeSessions:e,authenticationsByProvider:t,preferencesSynced:Math.floor(Math.random()*50),averageSessionDuration:2.5*60*60*1e3}}initializeDefaultProviders(){this.addProvider({name:"azure_ad",type:"oidc",config:{redirectURI:"/auth/callback/azure",scopes:["openid","profile","email","accessibility_preferences"],customClaims:{accessibility_needs:"extension_AccessibilityNeeds",accommodations:"extension_Accommodations"}},enabled:!1}),this.addProvider({name:"okta",type:"oidc",config:{redirectURI:"/auth/callback/okta",scopes:["openid","profile","email"],accessibilityClaimMapping:{preferencesClaim:"accessibility_preferences",roleClaim:"role",departmentClaim:"department",accessibilityNeedsClaim:"accessibility_needs",accommodationsClaim:"accommodations"}},enabled:!1})}startSessionMonitoring(){setInterval(()=>{this.cleanupExpiredSessions()},60*1e3)}cleanupExpiredSessions(){const e=new Date,t=[];for(const[i,s]of this.activeSessions.entries())s.expiresAt<=e&&t.push(i);for(const i of t)this.activeSessions.delete(i),this.emit("session_expired",{sessionId:i})}getProvider(e){const t=e||this.config.defaultProvider;if(!t){for(const s of this.providers.values())if(s.enabled)return s;return}const i=this.providers.get(t);return i?.enabled?i:void 0}generateState(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}generateSessionId(){return"sess_"+Math.random().toString(36).substring(2,15)+Date.now().toString(36)}buildAuthorizationUrl(e,t){const i=new URLSearchParams({client_id:e.config.clientId||"",response_type:"code",scope:e.config.scopes.join(" "),redirect_uri:e.config.redirectURI,state:t});return`${e.config.authorizationURL}?${i.toString()}`}validateState(e){return e.length>10}async exchangeCodeForTokens(e,t){return await new Promise(i=>setTimeout(i,100)),{access_token:"access_token_"+Math.random().toString(36),refresh_token:"refresh_token_"+Math.random().toString(36),id_token:"id_token_"+Math.random().toString(36),expires_in:3600,scope:e.config.scopes.join(" ")}}async getUserInfo(e,t){return await new Promise(i=>setTimeout(i,50)),{sub:"user_"+Math.random().toString(36).substring(2,10),email:"user@example.com",name:"Enterprise User",role:["user","accessibility_user"],department:"Engineering",accessibility_needs:["screen_reader","high_contrast"],accommodations:["extended_time","reduced_motion"]}}mapUserInfo(e,t){const i=e.config.accessibilityClaimMapping;return{id:t.sub,email:t.email,name:t.name,roles:Array.isArray(t.role)?t.role:[t.role].filter(Boolean),department:t.department,accessibilityNeeds:t.accessibility_needs||[],accommodations:t.accommodations||[],preferences:this.parseAccessibilityPreferences(t,i),metadata:t}}parseAccessibilityPreferences(e,t){if(!(!t||!e[t.preferencesClaim]))try{const i=typeof e[t.preferencesClaim]=="string"?JSON.parse(e[t.preferencesClaim]):e[t.preferencesClaim];return{visual:{motionReduction:i.motion_reduction||!1,highContrast:i.high_contrast||!1,colorVisionFilter:i.color_vision_filter||"none",fontSize:i.font_size||16,reducedFlashing:i.reduced_flashing||!1,darkMode:i.dark_mode||!1},cognitive:{readingSpeed:i.reading_speed||"medium",explanationLevel:i.explanation_level||"detailed",processingPace:i.processing_pace||"standard",chunkSize:i.chunk_size||5,allowInterruptions:i.allow_interruptions!==!1,preferVisualCues:i.prefer_visual_cues||!1},motor:{keyboardNavigation:i.keyboard_navigation||!1,mouseAlternatives:i.mouse_alternatives||!1,gestureSimplification:i.gesture_simplification||!1,targetSizeIncrease:i.target_size_increase||1,dwellTime:i.dwell_time||1e3,stickyKeys:i.sticky_keys||!1},audio:{enableAudio:i.enable_audio!==!1,volume:i.volume||.8,enableCaptions:i.enable_captions||!1,audioDescription:i.audio_description||!1,reducedAudio:i.reduced_audio||!1},version:"1.1.0",lastUpdated:new Date,metadata:{source:"enterprise_sso",provider:"enterprise"}}}catch{return}}async refreshAccessToken(e,t){return await new Promise(i=>setTimeout(i,100)),{access_token:"new_access_token_"+Math.random().toString(36),expires_in:3600}}async revokeTokens(e,t){await new Promise(i=>setTimeout(i,50))}async fetchRemotePreferences(e,t){await new Promise(i=>setTimeout(i,100))}async pushRemotePreferences(e,t,i){await new Promise(s=>setTimeout(s,100))}mergePreferences(e,t){if(!(!e&&!t)){if(!e)return t;if(!t)return e;switch(this.preferenceSync.conflictResolution){case"local":return e;case"remote":return t;case"merge":return{...t,...e,lastUpdated:new Date,metadata:{...t.metadata,...e.metadata,mergedFrom:"enterprise_sync"}};default:return e}}}logAuditEvent(e,t){const i={timestamp:new Date().toISOString(),event:e,data:t,source:"sso_manager"};console.log("[AUDIT]",JSON.stringify(i))}}class B extends y.EventEmitter{constructor(e={retentionDays:90,autoRefresh:!0,refreshInterval:3e4,alertingEnabled:!0,exportFormats:["json","csv","pdf"]}){super(),this.config=e,this.widgets=new Map,this.alerts=new Map,this.metricsHistory=[],this.initializeDefaultWidgets(),this.initializeDefaultAlerts(),this.config.autoRefresh&&this.startAutoRefresh()}async getAccessibilityMetrics(){return await new Promise(e=>setTimeout(e,100)),{totalUsers:Math.floor(Math.random()*1e4)+5e3,activeUsers:Math.floor(Math.random()*2e3)+1e3,usersWithAdaptations:Math.floor(Math.random()*800)+400,adaptationUsageRate:Math.random()*.4+.6,averageSessionDuration:Math.random()*120+30,mostUsedAdaptations:["high_contrast","font_size_increase","motion_reduction","keyboard_navigation","screen_reader_support"],complianceScore:Math.random()*.2+.8}}async getUsageMetrics(e="30d"){await new Promise(i=>setTimeout(i,150));const t=this.getTimeRangeDays(e);return{dailyActiveUsers:Array(t).fill(0).map(()=>Math.floor(Math.random()*500)+100),weeklyActiveUsers:Array(Math.ceil(t/7)).fill(0).map(()=>Math.floor(Math.random()*2e3)+500),monthlyActiveUsers:Array(Math.ceil(t/30)).fill(0).map(()=>Math.floor(Math.random()*8e3)+2e3),featureUsage:{motion_reduction:Math.floor(Math.random()*1e3)+500,high_contrast:Math.floor(Math.random()*1200)+600,font_size_increase:Math.floor(Math.random()*800)+400,keyboard_navigation:Math.floor(Math.random()*600)+300,screen_reader:Math.floor(Math.random()*400)+200,captions:Math.floor(Math.random()*700)+350,reduced_motion:Math.floor(Math.random()*900)+450},deviceDistribution:{desktop:.65,mobile:.25,tablet:.08,assistive_tech:.02},geographicDistribution:{north_america:.45,europe:.3,asia_pacific:.15,other:.1}}}async getComplianceMetrics(){return await new Promise(e=>setTimeout(e,200)),{wcagCompliance:{levelA:Math.random()*.1+.9,levelAA:Math.random()*.15+.8,levelAAA:Math.random()*.3+.6},adaptationCoverage:{visual:Math.random()*.2+.8,cognitive:Math.random()*.25+.7,motor:Math.random()*.3+.65,audio:Math.random()*.2+.75},userSatisfaction:Math.random()*.15+.8,supportTickets:Math.floor(Math.random()*20)+5,accessibilityIncidents:Math.floor(Math.random()*5)+1}}async getPerformanceMetrics(){return await new Promise(e=>setTimeout(e,100)),{averageLoadTime:Math.random()*1e3+500,adaptationResponseTime:Math.random()*200+50,systemUptime:Math.random()*.05+.95,errorRate:Math.random()*.02+.001,userRetention:Math.random()*.2+.75}}createWidget(e){this.widgets.set(e.id,e),this.emit("widget_created",e)}updateWidget(e,t){const i=this.widgets.get(e);if(i){const s={...i,...t};this.widgets.set(e,s),this.emit("widget_updated",s)}}removeWidget(e){const t=this.widgets.get(e);t&&(this.widgets.delete(e),this.emit("widget_removed",t))}getWidgets(){return Array.from(this.widgets.values())}async generateReport(e,t,i=!0){const[s,a,n,r]=await Promise.all([this.getAccessibilityMetrics(),this.getUsageMetrics(),this.getComplianceMetrics(),this.getPerformanceMetrics()]),c=[{title:"Accessibility Overview",summary:`${s.usersWithAdaptations} users are actively using accessibility features (${(s.adaptationUsageRate*100).toFixed(1)}% adoption rate).`,metrics:{"Total Users":s.totalUsers,"Active Users":s.activeUsers,"Users with Adaptat