export const ensure=(ok,msg)=>{if(!ok)throw new Error(msg)}; export const finite=(v)=>{ensure(String(v).trim()!==''&&Number.isFinite(Number(v))&&Math.abs(Number(v))<=1e12,'Introduce números finitos (magnitud máxima 10¹²).');return Number(v)}; export const round=(v,n=6)=>Number.isFinite(v)?Number(v.toFixed(n)):null; export const avg=a=>a.reduce((s,x)=>s+x,0)/a.length; export function numbers(text){let a=text.trim().split(/[\s,;]+/).map(finite);ensure(a.length>=2&&a.length<=10000,'Se requieren 2–10000 valores.');return a} export function stats(a){ensure(a.length>=2,'Se requieren al menos dos valores.');let m=avg(a),sd=Math.sqrt(a.reduce((s,x)=>s+(x-m)**2,0)/(a.length-1)),sorted=[...a].sort((a,b)=>a-b);return {n:a.length,media:round(m),mediana:round((sorted[Math.floor((a.length-1)/2)]+sorted[Math.ceil((a.length-1)/2)])/2),min:sorted[0],max:sorted.at(-1),desviacion_muestral:round(sd),error_estandar_media:round(sd/Math.sqrt(a.length))}} export function pairs(text){let rows=text.trim().split(/\r?\n/).filter(x=>x.trim()).map((line,i)=>{let a=line.trim().split(/[,;\s]+/);ensure(a.length===2,`Fila ${i+1}: se requieren dos columnas numéricas.`);return a.map(finite)});ensure(rows.length>=2&&rows.length<=10000,'Se requieren 2–10000 filas.');return rows} export function regression(rows){let x=rows.map(r=>r[0]),y=rows.map(r=>r[1]),mx=avg(x),my=avg(y),sxx=x.reduce((s,v)=>s+(v-mx)**2,0);ensure(sxx>0,'X debe tener variación.');let b=x.reduce((s,v,i)=>s+(v-mx)*(y[i]-my),0)/sxx,a=my-b*mx,res=rows.map(([x,y])=>y-(a+b*x)),sse=res.reduce((s,v)=>s+v*v,0),sst=y.reduce((s,v)=>s+(v-my)**2,0);return {n:rows.length,intercepto:round(a),pendiente:round(b),r2:sst===0?null:round(1-sse/sst),rmse:round(Math.sqrt(sse/rows.length)),residuos:res.map(v=>round(v)),a,b}} export function adc(bits,vref,raw){ensure(Number.isInteger(bits)&&bits>=1&&bits<=24&&vref>0&&vref<=100,'Resolución 1–24 bits, referencia positiva hasta 100 V.');let max=2**bits-1;ensure(Number.isInteger(raw)&&raw>=0&&raw<=max,`Código válido: 0 a ${max}.`);return {codigo:raw,codigo_max:max,paso_ideal_V:round(vref/2**bits),voltaje_estimado_V:round(raw*vref/max),porcentaje_escala:round(raw/max*100)}} export function moving(a,w){ensure(Number.isInteger(w)&&w>=1&&w<=a.length,'Ventana entera entre 1 y longitud de la serie.');let s=0;return a.map((v,i)=>{s+=v;if(i>=w)s-=a[i-w];return i>=w-1?round(s/w):null})} const rad=d=>d*Math.PI/180; export function distance(a,b){for(const p of [a,b])ensure(p.length===2&&Math.abs(p[0])<=90&&Math.abs(p[1])<=180,'Latitud −90 a 90, longitud −180 a 180.');let h=Math.sin(rad(b[0]-a[0])/2)**2+Math.cos(rad(a[0]))*Math.cos(rad(b[0]))*Math.sin(rad(b[1]-a[1])/2)**2;return 2*6371.0088*Math.asin(Math.sqrt(Math.min(1,Math.max(0,h))))} export function route(rows){let ds=rows.slice(1).map((p,i)=>distance(rows[i],p));let features=rows.map((p,i)=>({type:'Feature',properties:{punto:i+1},geometry:{type:'Point',coordinates:[p[1],p[0]]}}));return {distancia_km:round(ds.reduce((s,v)=>s+v,0),3),tramos_km:ds.map(v=>round(v,3)),geojson:{type:'FeatureCollection',features}}} export const words=s=>(s.toLocaleLowerCase('es').normalize('NFC').match(/[\p{L}\p{N}]+/gu)||[]); export function textStats(s){let w=words(s),freq=new Map;for(let t of w)freq.set(t,(freq.get(t)||0)+1);return {caracteres_unicode:[...s].length,bytes_utf8:new TextEncoder().encode(s).length,palabras:w.length,lineas:s?s.split(/\r\n|\r|\n/).length:0,terminos_distintos:freq.size,frecuencias:[...freq].sort((a,b)=>b[1]-a[1]||a[0].localeCompare(b[0])).slice(0,30)}} export function trainClassifier(training){ensure(Array.isArray(training)&&training.length>=2&&training.length<=2000,'Dataset de 2–2000 registros.');let labels=new Map,vocab=new Set;for(const r of training){ensure(r&&typeof r.label==='string'&&r.label.trim()&&typeof r.text==='string'&&r.text.trim(),'Cada registro requiere label y text.');ensure(r.text.length<=100000&&r.label.length<=100,'Registro demasiado largo.');let t=words(r.text);ensure(t.length&&t.length<=5000,'Documento de entrenamiento: 1–5000 términos.');let c=labels.get(r.label)||{docs:0,total:0,counts:new Map};c.docs++;for(let w of t){vocab.add(w);c.total++;c.counts.set(w,(c.counts.get(w)||0)+1)}labels.set(r.label,c)}ensure(labels.size>=2,'Se requieren al menos dos clases.');return {labels,vocab,total:training.length}} export function predictClassifier(model,query){let {labels,vocab,total}=model;ensure(typeof query==='string'&&query.length<=100000,'Consulta demasiado larga.');let q=words(query);ensure(q.length&&q.length<=5000,'Consulta de 1–5000 términos.');let known=q.filter(w=>vocab.has(w));ensure(known.length,'No hay términos conocidos; amplía el entrenamiento.');let logits=[...labels].map(([label,c])=>({label,log:Math.log(c.docs/total)+known.reduce((s,w)=>s+Math.log(((c.counts.get(w)||0)+1)/(c.total+vocab.size)),0)}));let max=Math.max(...logits.map(x=>x.log)),sum=logits.reduce((s,x)=>s+Math.exp(x.log-max),0);let scores=logits.map(x=>({clase:x.label,puntuacion:round(Math.exp(x.log-max)/sum)})).sort((a,b)=>b.puntuacion-a.puntuacion);return {prediccion:scores[0].clase,puntuaciones:scores,terminos_conocidos:known.length,terminos_ignorados:q.length-known.length,vocabulario:vocab.size}} export function classify(training,query){return predictClassifier(trainClassifier(training),query)} export function evaluate(train,test){ensure(Array.isArray(test)&&test.length>0&&test.length<=200,'Prueba de 1–200 ejemplos.');let model=trainClassifier(train),classes=new Set(model.labels.keys()),correct=0;let rows=test.map(r=>{ensure(r&&classes.has(r.label)&&typeof r.text==='string','Etiqueta de prueba desconocida o texto inválido.');let p;try{p=predictClassifier(model,r.text).prediccion}catch(e){if(e.message.startsWith('No hay términos'))p=null;else throw e}correct+=p===r.label?1:0;return {esperado:r.label,predicho:p,correcto:p===r.label}});return {n:test.length,aciertos:correct,exactitud:round(correct/test.length),resultados:rows}} export function pixels(data,mode,threshold){ensure(['gray','binary','invert'].includes(mode),'Modo inválido.');ensure(threshold>=0&&threshold<=255,'Umbral 0–255.');let hist=Array(256).fill(0),white=0;for(let i=0;i=threshold)white++;if(mode==='invert'){for(let c=0;c<3;c++)data[i+c]=255-data[i+c]}else{let v=mode==='binary'?(g>=threshold?255:0):g;data[i]=data[i+1]=data[i+2]=v}}return {pixeles:data.length/4,porcentaje_sobre_umbral:round(white/(data.length/4)*100),histograma_original:hist}} export function urlInfo(input){let u=new URL(input);ensure(['https:','http:'].includes(u.protocol),'Solo HTTP o HTTPS.');ensure(!u.username&&!u.password,'No se admiten credenciales en URL.');return {protocolo:u.protocol,host:u.hostname,puerto:u.port|| (u.protocol==='https:'?'443':'80'),origen:u.origin,ruta:u.pathname,parametros:[...u.searchParams.keys()],fragmento_presente:!!u.hash,https:u.protocol==='https:'}} export async function hash(data,algorithm='SHA-256'){ensure(['SHA-256','SHA-384','SHA-512'].includes(algorithm),'Algoritmo no permitido.');ensure(globalThis.crypto?.subtle,'Web Crypto requiere HTTPS o localhost.');let h=await crypto.subtle.digest(algorithm,data);return [...new Uint8Array(h)].map(x=>x.toString(16).padStart(2,'0')).join('')} export function jsonStats(s){ensure(typeof s==='string'&&s.length<=2*1024*1024,'JSON máximo 2 MiB.');let obj=JSON.parse(s),nodes=0,depth=0,types=Object.create(null),stack=[[obj,0]];while(stack.length){let [v,d]=stack.pop();nodes++;depth=Math.max(depth,d);ensure(depth<=100,'Profundidad máxima 100.');let t=v===null?'null':Array.isArray(v)?'array':typeof v;types[t]=(types[t]||0)+1;if(v!==null&&typeof v==='object')for(let child of Object.values(v))stack.push([child,d+1]);ensure(nodes<=100000,'Máximo 100000 nodos.')}return {valido:true,nodos:nodes,profundidad_maxima:depth,tipos:types,formato:JSON.stringify(obj,null,depth<=20?2:0)}} const enc=new TextEncoder(),dec=new TextDecoder(); const hex=b=>Array.from(b,x=>x.toString(16).padStart(2,'0')).join(''); const unhex=s=>{ensure(typeof s==='string'&&s.length%2===0&&/^[0-9a-f]+$/i.test(s),'Hexadecimal inválido.');return Uint8Array.from(s.match(/../g),x=>parseInt(x,16))}; async function key(pass,salt){ensure(crypto?.subtle,'Se requiere HTTPS o localhost.');ensure(pass.length>=12&&pass.length<=256,'Frase de 12–256 caracteres.');let k=await crypto.subtle.importKey('raw',enc.encode(pass),'PBKDF2',false,['deriveKey']);return crypto.subtle.deriveKey({name:'PBKDF2',salt,iterations:600000,hash:'SHA-256'},k,{name:'AES-GCM',length:256},false,['encrypt','decrypt'])} export async function aesPractice(mode,pass,s){ensure(['encrypt','decrypt'].includes(mode),'Modo inválido.');ensure(globalThis.crypto?.subtle,'Web Crypto requiere HTTPS o localhost.');ensure(typeof pass==='string','Frase inválida.');ensure(typeof s==='string'&&s.length<=(mode==='encrypt'?200000:1800000),'Entrada demasiado larga.');if(mode==='encrypt'){let salt=crypto.getRandomValues(new Uint8Array(16)),iv=crypto.getRandomValues(new Uint8Array(12)),k=await key(pass,salt),c=new Uint8Array(await crypto.subtle.encrypt({name:'AES-GCM',iv},k,enc.encode(s)));return {version:1,kdf:'PBKDF2-SHA256',iteraciones:600000,alg:'AES-256-GCM',salt:hex(salt),iv:hex(iv),cifrado:hex(c)}}let p=JSON.parse(s);ensure(p.version===1&&p.kdf==='PBKDF2-SHA256'&&p.iteraciones===600000&&p.alg==='AES-256-GCM','Formato de paquete incompatible.');let salt=unhex(p.salt),iv=unhex(p.iv),c=unhex(p.cifrado);ensure(salt.length===16&&iv.length===12&&c.length>=16,'Parámetros inválidos.');let k=await key(pass,salt);try{return {texto:dec.decode(await crypto.subtle.decrypt({name:'AES-GCM',iv},k,c))}}catch{throw new Error('No se pudo autenticar: frase incorrecta o paquete alterado.')}}