@forgenex/cli 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -42
- package/dist/forgenex.js +51 -20
- package/ejemplos/escuela-natacion/README.md +3 -3
- package/ejemplos/hola-alpine/interfaz/index.html +4 -1
- package/licencias.txt +1 -1
- package/package.json +1 -1
package/dist/forgenex.js
CHANGED
|
@@ -1,27 +1,39 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __fgxRequire } from "node:module"; const require = __fgxRequire(import.meta.url);
|
|
3
|
-
var bb=Object.defineProperty;var f=(e,o,t)=>()=>{if(t)throw t[0];try{return e&&(o=e(e=0)),o}catch(n){throw t=[n],n}};var ll=(e,o)=>{for(var t in o)bb(e,t,{get:o[t],enumerable:!0})};import{AsyncLocalStorage as _b}from"node:async_hooks";import{readdirSync as Nb}from"node:fs";import{createRequire as $b}from"node:module";import{fileURLToPath as xb}from"node:url";function co(e,o){let n=dl[e]?.[o];if(n!==void 0)return n;for(let r of Sb[e]??[]){let a=r.regex.exec(o);if(a)return r.traduccion.replace(/%\{([\w]+)\}/g,(s,c)=>{let d=r.nombres.indexOf(c);return d<0?s:a[d+1]})}return o}var Cb,jb,dl,Sb,Ob,Lo,mn=f(()=>{Cb=Nb(new URL("./locales/",import.meta.url)).filter(e=>/\.(?:ts|js)$/.test(e)&&!e.endsWith(".d.ts")),jb=$b(import.meta.url),dl=Object.fromEntries(Cb.map(e=>[e.replace(/\.(?:ts|js)$/,""),jb(xb(new URL(`./locales/${e}`,import.meta.url))).default])),Sb=Object.fromEntries(Object.entries(dl).map(([e,o])=>[e,Object.entries(o).filter(([t])=>t.includes("%{")).map(([t,n])=>{let r=[],a=0,s="";for(let c of t.matchAll(/%\{([\w]+)\}/g)){let d=c.index;s+=t.slice(a,d).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"([\\s\\S]*?)",r.push(c[1]),a=d+c[0].length}return s+=t.slice(a).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),{regex:new RegExp(`^${s}$`),nombres:r,traduccion:n,especificidad:t.replace(/%\{[\w]+\}/g,"").length}}).sort((t,n)=>n.especificidad-t.especificidad)])),Ob=new _b,Lo=()=>Ob.getStore()?.idioma??"es"});var z,i,q=f(()=>{mn();z=class extends Error{constructor(t,n,r,a=!0,s){super(a?co(Lo(),r):r);this.estado=t;this.codigo=n;this.datos=s}estado;codigo;datos},i=(e,o=!0)=>new z(400,"peticion_invalida",e,o)});import{inflateRawSync as Ab}from"node:zlib";function Eb(e){let o=Buffer.from(e.buffer,e.byteOffset,e.byteLength);if(o.length>ea)throw i("El paquete pasa de 5 MB.");if(o.length<22||o.readUInt32LE(0)!==67324752)throw i("El paquete no es un .zip.");let t=-1;for(let d=o.length-22;d>=Math.max(0,o.length-22-65535);d--)if(o.readUInt32LE(d)===101010256&&d+22+o.readUInt16LE(d+20)===o.length){t=d;break}if(t<0)throw i("El .zip est\xE1 da\xF1ado (sin directorio).");let n=o.readUInt16LE(t+10),r=o.readUInt32LE(t+16),a=o.readUInt32LE(t+12);if(o.readUInt16LE(t+4)!==0||o.readUInt16LE(t+6)!==0||o.readUInt16LE(t+8)!==n||t+22+o.readUInt16LE(t+20)!==o.length||r+a!==t)throw i("El .zip est\xE1 da\xF1ado (directorio inv\xE1lido).");if(n>ml)throw i(`El paquete trae m\xE1s de ${ml} ficheros.`);let s=new Map,c=r;for(let d=0;d<n;d++){if(c+46>t||o.readUInt32LE(c)!==33639248)throw i("El .zip est\xE1 da\xF1ado.");let u=o.readUInt16LE(c+8),p=o.readUInt16LE(c+10),m=o.readUInt32LE(c+20),h=o.readUInt32LE(c+24),b=o.readUInt16LE(c+28),y=o.readUInt16LE(c+30),v=o.readUInt16LE(c+32);if((o.readUInt32LE(c+38)>>>16&61440)===40960)throw i("El paquete no admite enlaces simb\xF3licos.");let N=o.readUInt32LE(c+42);if(c+46+b+y+v>t)throw i("El .zip est\xE1 da\xF1ado.");let j=o.subarray(c+46,c+46+b),S=j.toString("utf8");if(c+=46+b+y+v,!S.endsWith("/")){if(!S||S.includes("\\")||S.startsWith("/")||S.split("/").some(R=>R===".."||R==="."||R==="")||/[\x00-\x1f]/.test(S))throw i(`El paquete trae un nombre de fichero no admitido (\xAB${S.slice(0,80)}\xBB).`);if(s.has(S))throw i(`El paquete trae \xAB${S.slice(0,80)}\xBB dos veces.`);if(u&1)throw i("El paquete no puede ir cifrado.");s.set(S,()=>{if(h>pl)throw i(`\xAB${S}\xBB pasa de 2 MB.`);if(N+30>o.length||o.readUInt32LE(N)!==67324752)throw i("El .zip est\xE1 da\xF1ado.");let R=o.readUInt16LE(N+26),F=N+30+R+o.readUInt16LE(N+28);if(F>r||F+m>r||o.readUInt16LE(N+6)!==u||o.readUInt16LE(N+8)!==p||!o.subarray(N+30,N+30+R).equals(j))throw i("El .zip est\xE1 da\xF1ado.");let I=o.subarray(F,F+m);if(I.length!==m)throw i("El .zip est\xE1 da\xF1ado.");let _;if(p===0)_=I;else if(p===8)try{_=Ab(I,{maxOutputLength:pl})}catch{throw i(`\xAB${S}\xBB no se puede descomprimir (o pasa de 2 MB).`)}else throw i(`\xAB${S}\xBB va comprimido de una forma no admitida (solo \xABstore\xBB y \xABdeflate\xBB).`);if(_.length!==h)throw i("El .zip est\xE1 da\xF1ado.");return _})}}if(c!==t)throw i("El .zip est\xE1 da\xF1ado (directorio inv\xE1lido).");return s}function zo(e){let o=new Map,t=0;for(let[n,r]of Eb(e)){let a=r();if(t+=a.length,t>qb)throw i("Los ficheros del paquete pasan de 10 MB al descomprimirlos.");o.set(n,a)}return o}var ea,pl,ml,qb,vr=f(()=>{q();ea=5*1024*1024,pl=2*1024*1024,ml=500;qb=10*1024*1024});function fl(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>20)throw i("La app admite hasta 20 conexiones.");let o=new Set;return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t)||typeof t.clave!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(t.clave)||o.has(t.clave)||typeof t.base!="string"||t.base.length>1e3||typeof t.operacion!="string"||!/^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$/.test(t.operacion))throw i("Declaraci\xF3n de conexi\xF3n de app no v\xE1lida.");let n=["clave","base","operacion","tipo",...t.tipo==="api_key"?["lugar","nombre"]:[]];if(Object.keys(t).some(c=>!n.includes(c)))throw i("La declaraci\xF3n de conexi\xF3n no admite campos adicionales.");let r;try{r=new URL(t.base)}catch{throw i("La conexi\xF3n necesita una base HTTPS.")}if(!(process.env.NODE_ENV==="test"&&process.env.CRM_CONEXIONES_PRUEBA_LOCAL==="1"&&r.protocol==="http:"&&r.hostname==="127.0.0.1")&&(r.protocol!=="https:"||r.port)||r.username||r.password||r.search||r.hash)throw i("La conexi\xF3n necesita una base HTTPS sin credenciales, query ni fragmento.");o.add(t.clave);let s={clave:t.clave,base:r.href,operacion:t.operacion};if(t.tipo==="api_key"&&(t.lugar==="cabecera"||t.lugar==="query")&&typeof t.nombre=="string"&&/^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$/.test(t.nombre))return{...s,tipo:t.tipo,lugar:t.lugar,nombre:t.nombre};if(t.tipo==="bearer"||t.tipo==="basic"||t.tipo==="oauth2")return{...s,tipo:t.tipo};throw i("Autenticaci\xF3n de conexi\xF3n de app no v\xE1lida.")})}var hl=f(()=>{q()});var Y,Rb,gl,bl=f(()=>{Y={id:"Id del registro."},Rb=[{nombre:"contacto.creado",descripcion:"Se ha creado un contacto.",datos:Y},{nombre:"contacto.actualizado",descripcion:"Han cambiado datos de un contacto.",datos:{...Y,campos:"Qu\xE9 columnas (si se sabe).",lote:"La acci\xF3n, si fue en lote."}},{nombre:"contacto.borrado",descripcion:"Se ha borrado un contacto (tambi\xE9n al fusionarlo en otro).",datos:{...Y,fusionado_en:"Si se fusion\xF3: en cu\xE1l."}},{nombre:"empresa.creada",descripcion:"Se ha creado una empresa.",datos:Y},{nombre:"empresa.actualizada",descripcion:"Han cambiado datos de una empresa.",datos:{...Y,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"empresa.borrada",descripcion:"Se ha borrado una empresa.",datos:Y},{nombre:"contacto.fusionado",descripcion:"Un contacto se ha fusionado en otro: quien guarde su id, que lo cambie por el que queda.",datos:{...Y,se_va:"El que se fue.",queda:"El que queda (= id)."}},{nombre:"empresa.fusionada",descripcion:"Una empresa se ha fusionado en otra: quien guarde su id, que lo cambie por la que queda.",datos:{...Y,se_va:"La que se fue.",queda:"La que queda (= id)."}},{nombre:"oportunidad.creada",descripcion:"Se ha creado una oportunidad.",datos:Y},{nombre:"oportunidad.actualizada",descripcion:"Han cambiado datos de una oportunidad (no la etapa).",datos:{...Y,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"oportunidad.etapa_cambiada",descripcion:"Una oportunidad ha cambiado de etapa.",datos:{...Y,de:"Etapa anterior.",a:"Etapa nueva."}},{nombre:"oportunidad.ganada",descripcion:"Una oportunidad ha pasado a ganada (adem\xE1s de etapa_cambiada).",datos:{...Y,de:"Etapa anterior.",a:"won",origen:"\xABcrm\xBB (una persona o la API) o \xABfacturacion\xBB (su presupuesto principal se acept\xF3).",quien:"Nombre de quien la movi\xF3 (persona del espacio o due\xF1o de la clave), si se sabe."}},{nombre:"oportunidad.perdida",descripcion:"Una oportunidad ha pasado a perdida (adem\xE1s de etapa_cambiada).",datos:{...Y,de:"Etapa anterior.",a:"lost",origen:"\xABcrm\xBB o \xABfacturacion\xBB (su presupuesto principal se rechaz\xF3).",motivo:"El motivo de p\xE9rdida, si se dio.",quien:"Nombre de quien la movi\xF3 (persona del espacio o due\xF1o de la clave), si se sabe."}},{nombre:"oportunidad.archivada",descripcion:"Una oportunidad ha salido del embudo al archivo.",datos:Y},{nombre:"oportunidad.borrada",descripcion:"Se ha borrado una oportunidad.",datos:Y},{nombre:"nota.creada",descripcion:"Nueva nota en el hilo de un contacto o de una oportunidad.",datos:{...Y,contacto_id:"Si es de un contacto.",oportunidad_id:"Si es de una oportunidad."}},{nombre:"nota.actualizada",descripcion:"Se ha editado una nota.",datos:Y},{nombre:"nota.borrada",descripcion:"Se ha borrado una nota.",datos:Y},{nombre:"nota.mencion",descripcion:"Una nota menciona (@) a miembros del espacio: al crearla, o al editarla con menciones nuevas. Solo miembros activos (la base filtra el resto).",datos:{...Y,contacto_id:"Si es de un contacto.",oportunidad_id:"Si es de una oportunidad.",mencionados:"Ids de los miembros mencionados por primera vez en esta nota (miembros.listar)."}},{nombre:"tarea.creada",descripcion:"Se ha creado una tarea.",datos:{...Y,contacto_id:"Su contacto."}},{nombre:"tarea.actualizada",descripcion:"Ha cambiado una tarea (o se ha reabierto).",datos:{...Y,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"tarea.completada",descripcion:"Se ha completado una tarea.",datos:Y},{nombre:"tarea.borrada",descripcion:"Se ha borrado una tarea.",datos:Y},{nombre:"contacto.etiquetado",descripcion:"Una Persona ha recibido una etiqueta (una vez por etiqueta a\xF1adida, venga de donde venga).",datos:{...Y,etiqueta:"El nombre de la etiqueta.",etiqueta_id:"Su id."}},{nombre:"lead.recibido",descripcion:"Ha entrado un lead desde una web (leads.crear): el id es el de su Persona.",datos:{...Y,origen:"De d\xF3nde viene (\xABlanding:<slug>\xBB).",oportunidad_id:"La oportunidad que abri\xF3."}},{nombre:"formulario.respuesta",descripcion:"Alguien ha respondido un formulario p\xFAblico del CRM.",datos:{...Y,formulario_id:"El formulario.",contacto_id:"Su contacto.",oportunidad_id:"La oportunidad, si el formulario la abre."}},{nombre:"registro.creado",descripcion:"Se ha creado un registro de un m\xF3dulo del cliente.",datos:{...Y,modulo:"La clave del m\xF3dulo (mod_<clave> en la API v1).",origen:"\xABformulario\xBB o \xABimportacion\xBB, si no vino de la interfaz o la API."}},{nombre:"registro.actualizado",descripcion:"Han cambiado datos de un registro de un m\xF3dulo.",datos:{...Y,modulo:"La clave del m\xF3dulo.",campos:"Qu\xE9 campos."}},{nombre:"registro.borrado",descripcion:"Se ha borrado un registro de un m\xF3dulo.",datos:{...Y,modulo:"La clave del m\xF3dulo."}}],gl=Rb.map(e=>e.nombre)});function Pb(e,[o,t]){let n=new Set;for(let r of e.split(",")){let a=/^(\*|(\d{1,2})(?:-(\d{1,2}))?)(?:\/(\d{1,2}))?$/.exec(r);if(!a)return null;let s=a[1]==="*"?o:Number(a[2]),c=a[1]==="*"?t:a[3]!==void 0?Number(a[3]):a[4]!==void 0?t:s,d=a[4]!==void 0?Number(a[4]):1;if(s<o||c>t||s>c||d<1)return null;for(let u=s;u<=c;u+=d)n.add(u)}return n}function wl(e){let o=e.trim().split(/\s+/);if(o.length!==5)return null;let t=o.map((r,a)=>Pb(r,kb[a]));if(t.some(r=>!r))return null;let n=new Set([...t[4]].map(r=>r===7?0:r));return{minutos:t[0],horas:t[1],dias:t[2],meses:t[3],semana:n,diaLibre:o[2]==="*",semanaLibre:o[4]==="*"}}function vl(e){let o=[...e.horas].sort((a,s)=>a-s),t=[...e.minutos].sort((a,s)=>a-s),n=o.flatMap(a=>t.map(s=>a*60+s));if(n.length<=1)return 1440;let r=1440-n.at(-1)+n[0];for(let a=1;a<n.length;a++)r=Math.min(r,n[a]-n[a-1]);return r}var kb,v0,yl=f(()=>{kb=[[0,59],[0,23],[1,31],[1,12],[0,7]];v0=new Intl.DateTimeFormat("en-GB",{timeZone:"Europe/Madrid",hourCycle:"h23",minute:"numeric",hour:"numeric",day:"numeric",month:"numeric",weekday:"short"})});function _l(e){let o=(t,n)=>Number.isInteger(t)?Math.min(n.max,Math.max(n.min,t)):n.defecto;return{ms:o(e?.tope?.ms,W.ms),memoriaMb:o(e?.tope?.memoria_mb,W.memoriaMb)}}var W,yr=f(()=>{W={simultaneas:2,ms:{defecto:5e3,min:100,max:3e4},memoriaMb:{defecto:64,min:16,max:256},pilaBytes:1048576,margenMs:2e3,llamadasApi:100,llamadasRed:10,llamadaCaracteres:327680,llamadasEnVuelo:8,codigoBytes:262144,entradaBytes:65536,salidaBytes:65536,red:{cuerpoBytes:262144,respuestaBytes:1048576,plazoMs:5e3},webhookBytes:65536,cronMinutos:15}});function Nl(e){if(!e.startsWith("*."))return!1;let o=e.slice(2).toLowerCase();if(Mb.has(o)||Ib.test(o))return!0;let t=o.split(".");return t.length===2&&t[1].length===2&&Tb.has(t[0])}var Tb,Mb,Ib,$l=f(()=>{Tb=new Set(["co","com","net","org","gov","gob","edu","ac","nom","mil","ltd","plc","me","or","ne","go","info","biz","int"]),Mb=new Set(["github.io","gitlab.io","pages.dev","workers.dev","vercel.app","netlify.app","web.app","firebaseapp.com","herokuapp.com","appspot.com","azurewebsites.net","cloudfront.net","amazonaws.com","blogspot.com","wordpress.com","glitch.me","onrender.com","fly.dev","repl.co","ngrok.io","ngrok-free.app","trycloudflare.com","r2.dev","supabase.co","myshopify.com","firebaseio.com","duckdns.org","no-ip.org","ddns.net","netlify.com","blob.core.windows.net","web.core.windows.net"]),Ib=/^(s3([.-][a-z0-9-]+)?\.amazonaws\.com|blogspot\.[a-z]{2,3}(\.[a-z]{2})?)$/});function na(e,o=0){if(o>20)throw i("El manifiesto anida demasiado.");if(Array.isArray(e))return e.forEach(t=>na(t,o+1));if(me(e))for(let t of Object.keys(e)){if(Db.has(t))throw i(`Clave no admitida \xAB${t}\xBB.`);na(e[t],o+1)}}function Ne(e,o,t){for(let n of Object.keys(e))if(!o.includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`)}function Ub(e,o,t={}){return Bb.test(e.replace(Vb,""))?`\xAB${o}\xBB: lleva caracteres de control, invisibles o de direcci\xF3n del texto.`:t.reservar&&!t.firmada&&aa(e)?`\xAB${o}\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.`:null}function G(e,o,t,n=!0){if(e!=null&&typeof e!="string")throw i(`\xAB${o}\xBB: texto de hasta ${t} caracteres.`);let r=typeof e=="string"?e.trim():"";if(r===""){if(n)throw i(`Falta \xAB${o}\xBB.`);return""}if(r.length>t)throw i(`\xAB${o}\xBB: texto de hasta ${t} caracteres.`);let a=Ub(r,o);if(a)throw i(a);return r}function Gb(e){return e.normalize("NFKC").replace(new RegExp("(\\p{Ll})(?=\\p{Lu})","gu"),"$1 ").replace(new RegExp("(\\p{Lu})(?=\\p{Lu}\\p{Ll})","gu"),"$1 ").split(/[^\p{L}\p{N}\p{M}]+/u).map(ia).filter(Boolean)}function Ml(e,o,t){let n=K(e,o,Rl,t);if(Nl(n))throw i(`\xAB${o}\xBB: \xAB${n}\xBB abarca dominios de cualquiera; pon el dominio de tu servicio (\xAB*.api.ejemplo.co.uk\xBB o \xABapi.ejemplo.co.uk\xBB).`);return n}function K(e,o,t,n){if(typeof e!="string"||!t.test(e))throw i(`\xAB${o}\xBB: ${n}.`);return e}function ce(e,o,t){if(e==null)return[];if(!Array.isArray(e))throw i(`\xAB${o}\xBB: una lista.`);if(e.length>t)throw i(`\xAB${o}\xBB: como mucho ${t}.`);return e}function we(e,o,t){let n=new Set;for(let r of e){let a=o(r);if(n.has(a))throw i(`\xAB${t}\xBB: \xAB${a}\xBB est\xE1 repetido.`);n.add(a)}return e}function ta(e,o){let t=G(e,o,500),n;try{n=new URL(t)}catch{throw i(`\xAB${o}\xBB: una direcci\xF3n https.`)}if(n.protocol!=="https:"||n.username||n.password||!Rl.test(n.hostname)||n.hostname.startsWith("*."))throw i(`\xAB${o}\xBB: una direcci\xF3n https con nombre de dominio (ni IP ni localhost).`);return n.toString()}function Hb(e){let[o,t]=e.split(".");return ia(o??"")==="forgenex"||ia(t??"")==="forgenex"}function lo(e){if(Object.hasOwn(Bo,e))return e;let o=e.startsWith("mod_")?e.slice(4):e;return Fb.test(o)?`mod_${o}`:null}function Al(e,o,t){if(!me(e))throw i(`\xAB${o}\xBB: un nombre de contrato, o { contrato, modulos, eventos, herramientas }.`);Ne(e,["contrato","titulo","modulos","eventos","herramientas",...t],o);let n=K(e.contrato,`${o}.contrato`,ra,"un nombre de contrato (\xABtaller.vehiculos\xBB)"),r=e.titulo===void 0?null:G(e.titulo,`${o}.titulo`,80),a={};if(e.modulos!==void 0){if(!me(e.modulos))throw i(`\xAB${o}.modulos\xBB: un objeto { m\xF3dulo: [operaciones] }.`);let d=Object.entries(e.modulos);if(d.length>20)throw i(`\xAB${o}.modulos\xBB: como mucho 20 m\xF3dulos.`);for(let[u,p]of d){let m=lo(u);if(!m)throw i(`\xAB${o}.modulos\xBB: \xAB${u.slice(0,60)}\xBB no es un m\xF3dulo (min\xFAsculas, n\xFAmeros y _).`);if(a[m])throw i(`\xAB${o}.modulos\xBB: \xAB${u}\xBB est\xE1 repetido.`);let h=ce(p,`${o}.modulos.${u}`,4);if(!h.length||h.some(y=>typeof y!="string"||!Wo.includes(y)))throw i(`\xAB${o}.modulos.${u}\xBB: operaciones ${Wo.join(", ")}.`);let b=new Set(h);if((b.has("editar")||b.has("borrar"))&&!b.has("ver"))throw i(`\xAB${o}.modulos.${u}\xBB: para \xABeditar\xBB o \xABborrar\xBB hace falta \xABver\xBB.`);a[m]=Wo.filter(y=>b.has(y))}}let s=we(ce(e.eventos,`${o}.eventos`,3).map((d,u)=>{if(typeof d!="string"||!xl.includes(d))throw i(`\xAB${o}.eventos[${u}]\xBB: ${xl.join(", ")} (los de los registros de sus m\xF3dulos).`);return d}),d=>d,`${o}.eventos`).sort();if(s.length&&!Object.values(a).some(d=>d.includes("ver")))throw i(`\xAB${o}.eventos\xBB: los eventos son de sus m\xF3dulos; hace falta \xABver\xBB de alguno en \xAB${o}.modulos\xBB.`);let c=we(ce(e.herramientas,`${o}.herramientas`,20).map((d,u)=>K(d,`${o}.herramientas[${u}]`,/^[a-z][a-z0-9_]{2,40}$/,"el nombre de una herramienta")),d=>d,`${o}.herramientas`);if(!Object.keys(a).length&&!s.length&&!c.length)throw i(`\xAB${o}\xBB: di qu\xE9 lleva el contrato (m\xF3dulos, eventos o herramientas).`);return{contrato:n,titulo:r,modulos:a,eventos:s,herramientas:c}}function Xb(e){if(e===void 0)return{modulos:{},almacen:!1,red_hacia:[],eventos:[],archivos:[]};if(!me(e))throw i("\xABpermisos\xBB: un objeto.");Ne(e,["modulos","almacen","red_hacia","eventos","archivos"],"Permisos");let o={};if(e.modulos!==void 0){if(!me(e.modulos))throw i("\xABpermisos.modulos\xBB: un objeto { m\xF3dulo: [operaciones] }.");let a=Object.entries(e.modulos);if(a.length>40)throw i("\xABpermisos.modulos\xBB: como mucho 40 m\xF3dulos.");for(let[s,c]of a){let d=lo(s);if(!d)throw i(`\xABpermisos.modulos\xBB: \xAB${s.slice(0,60)}\xBB no es un m\xF3dulo (min\xFAsculas, n\xFAmeros y _).`);if(o[d])throw i(`\xABpermisos.modulos\xBB: \xAB${s}\xBB est\xE1 repetido.`);let u=Bo[d]?.ops??Wo,p=ce(c,`permisos.modulos.${s}`,4);if(!p.length)throw i(`\xABpermisos.modulos.${s}\xBB: di qu\xE9 operaciones (${u.join(", ")}).`);for(let h of p)if(typeof h!="string"||!u.includes(h))throw i(`\xABpermisos.modulos.${s}\xBB: operaciones ${u.join(", ")}.`);let m=new Set(p);if((m.has("editar")||m.has("borrar"))&&!m.has("ver"))throw i(`\xABpermisos.modulos.${s}\xBB: para \xABeditar\xBB o \xABborrar\xBB hace falta \xABver\xBB.`);o[d]=Wo.filter(h=>m.has(h))}}if(e.almacen!==void 0&&typeof e.almacen!="boolean")throw i("\xABpermisos.almacen\xBB: s\xED o no (true/false).");let t=we(ce(e.red_hacia,"permisos.red_hacia",20).map((a,s)=>Ml(a,`permisos.red_hacia[${s}]`,"un dominio (\xABapi.ejemplo.com\xBB o \xAB*.ejemplo.com\xBB; ni IP ni localhost)")),a=>a,"permisos.red_hacia").sort(),n=we(ce(e.eventos,"permisos.eventos",40).map((a,s)=>{if(typeof a!="string"||!gl.includes(a))throw i(`\xABpermisos.eventos[${s}]\xBB: un evento del cat\xE1logo (GET /api/v1/eventos).`);return a}),a=>a,"permisos.eventos").sort(),r=ce(e.archivos,"permisos.archivos",2);for(let a of r)if(typeof a!="string"||!Cl.includes(a))throw i('\xABpermisos.archivos\xBB: ["leer"] o ["leer", "escribir"].');if(r.includes("escribir")&&!r.includes("leer"))throw i("\xABpermisos.archivos\xBB: para \xABescribir\xBB hace falta \xABleer\xBB.");return{modulos:Object.fromEntries(Object.entries(o).sort(([a],[s])=>a.localeCompare(s))),almacen:e.almacen===!0,red_hacia:t,eventos:n,archivos:Cl.filter(a=>r.includes(a))}}function El(e,o){let t=o.lastIndexOf(".");if(t<1)return!1;let n=lo(o.slice(0,t));return!!n&&(e.modulos[n]??[]).includes(o.slice(t+1))}function ql(e,o){let t={};if(e===void 0)return t;if(!me(e)||Object.keys(e).length>20)throw i(`\xAB${o}\xBB: { campo: { tipo, desc } }, como mucho 20.`);for(let[n,r]of Object.entries(e)){if(K(n,o,Fo,"nombres de campo en min\xFAsculas y _"),!me(r))throw i(`\xAB${o}.${n}\xBB: { tipo, desc }.`);Ne(r,["tipo","desc","requerido"],`${o}.${n}`);let a=G(r.tipo,`${o}.${n}.tipo`,10);if(!["texto","numero","si_no","fecha"].includes(a))throw i(`\xAB${o}.${n}.tipo\xBB: texto, numero, si_no o fecha.`);t[n]={tipo:a,desc:G(r.desc,`${o}.${n}.desc`,200),requerido:r.requerido===!0}}return t}function Vo(e,o={}){if(typeof e=="string"){if(e.length>hn)throw i("El manifiesto pasa de 256 KB.");try{e=JSON.parse(e)}catch{throw i("El manifiesto no es un JSON v\xE1lido.")}}else if(JSON.stringify(e??null).length>hn)throw i("El manifiesto pasa de 256 KB.");if(!me(e))throw i("El manifiesto tiene que ser un objeto.");if(na(e),e.formato!==at)throw i(`No es una app (formato \xAB${at}\xBB).`);if(Ne(e,["$schema","formato","formato_version","id","nombre","descripcion","version","autor","icono","idiomas","compatible_crm","licencia","politica_datos","depende_de","ofrece","usa","solucion","montajes","funciones","servidor","herramientas_ia","ajustes","secretos","conexiones","permisos"],"App"),!Number.isInteger(e.formato_version)||e.formato_version<1)throw i("\xABformato_version\xBB: un entero (1).");if(e.formato_version>wn)throw i("La app es de una versi\xF3n del formato m\xE1s nueva que este CRM.");let t=K(e.id,"id",fn,"dominio inverso en min\xFAsculas (\xABcom.tuempresa.mi-extension\xBB)");if(t.length>200)throw i("\xABid\xBB: como mucho 200 caracteres.");if(!o.firmada&&Hb(t))throw i("\xABid\xBB: los que empiezan por \xABcom.forgenex.\xBB o \xABforgenex.\xBB est\xE1n reservados a lo que publica ForgeNEX; usa el dominio de tu empresa (\xABcom.tuempresa.mi-extension\xBB).");let n=G(e.nombre,"nombre",80),r=K(e.version,"version",Lb,"versi\xF3n semver (\xAB1.0.0\xBB)"),a;if(typeof e.autor=="string")a={nombre:G(e.autor,"autor",120)};else if(me(e.autor))Ne(e.autor,["nombre","web"],"Autor"),a={nombre:G(e.autor.nombre,"autor.nombre",120),...e.autor.web!==void 0?{web:ta(e.autor.web,"autor.web")}:{}};else throw i("Falta \xABautor\xBB (un nombre, o { nombre, web }).");if(!o.firmada){if(aa(n))throw i("\xABnombre\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.");if(aa(a.nombre))throw i("\xABautor\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.")}let s=e.icono===void 0?"puzzle":K(e.icono,"icono",Sl,"un icono de lucide (\xABpuzzle\xBB)"),c=we(ce(e.idiomas,"idiomas",30).map((_,E)=>K(_,`idiomas[${E}]`,zb,"un c\xF3digo de idioma (\xABes\xBB, \xABen\xBB, \xABpt-BR\xBB)")),_=>_,"idiomas"),d=null;if(e.compatible_crm!==void 0){let E=G(e.compatible_crm,"compatible_crm",80).split(/\s+/);if(E.length>2||!E.every(g=>jl.test(g)))throw i("\xABcompatible_crm\xBB: un rango (\xAB>=1.6.0-284\xBB, \xAB>=1.6.0-284 <2.0.0\xBB).");d=E.join(" ")}let u=e.licencia===void 0?null:G(e.licencia,"licencia",40),p=e.politica_datos===void 0?{}:{politica_datos:ta(e.politica_datos,"politica_datos")},m=we(ce(e.depende_de,"depende_de",20).map((_,E)=>{if(typeof _=="string")return{id:K(_,`depende_de[${E}]`,fn,"el id de otra app"),version:null};if(!me(_))throw i(`\xABdepende_de[${E}]\xBB: el id de otra app, o { id, version }.`);Ne(_,["id","version"],`depende_de[${E}]`);let g=_.version===void 0?null:G(_.version,`depende_de[${E}].version`,80);if(g!==null&&!g.split(/\s+/).every(x=>jl.test(x)))throw i(`\xABdepende_de[${E}].version\xBB: un rango (\xAB>=1.0.0\xBB).`);return{id:K(_.id,`depende_de[${E}].id`,fn,"el id de otra app"),version:g}}),_=>_.id,"depende_de");if(m.some(_=>_.id===t))throw i("\xABdepende_de\xBB: una app no depende de s\xED misma.");let h=Xb(e.permisos),b=we(ce(e.usa,"usa",20).map((_,E)=>{let g=`usa[${E}]`;if(typeof _=="string")return{...Ol(K(_,g,ra,"un nombre de contrato (\xABtaller.citas\xBB)")),de:null};let x=Al(_,g,["de"]),O=K(_.de,`${g}.de`,fn,"el id de la app que lo ofrece (\xABcom.taller.vehiculos\xBB)");if(O===t)throw i(`\xAB${g}.de\xBB: una app no se usa a s\xED misma.`);return{...x,de:O}}),_=>`${_.de??""}/${_.contrato}`,"usa"),y=e.solucion===void 0||e.solucion===null?null:K(e.solucion,"solucion",oa,"el fichero de la soluci\xF3n dentro del paquete (\xABsolucion.json\xBB)");if(y!==null&&!y.endsWith(".json"))throw i("\xABsolucion\xBB: un fichero .json del paquete.");let v=we(ce(e.montajes,"montajes",20).map((_,E)=>{let g=`montajes[${E}]`;if(!me(_))throw i(`\xAB${g}\xBB: un objeto.`);Ne(_,["id","punto","entrada","titulo","icono","modulo","permiso","funciones"],g);let x=G(_.punto,`${g}.punto`,20);if(!Pt.includes(x))throw i(`\xAB${g}.punto\xBB: ${Pt.join(", ")}.`);let O=null;if(_r.has(x)){if(O=lo(G(_.modulo,`${g}.modulo`,64)),!O)throw i(`\xAB${g}.modulo\xBB: el m\xF3dulo donde se cuelga.`);if(!(h.modulos[O]??[]).includes("ver"))throw i(`\xAB${g}\xBB: se cuelga de \xAB${_.modulo}\xBB, as\xED que \xABpermisos.modulos\xBB tiene que pedir verlo.`)}else if(_.modulo!==void 0)throw i(`\xAB${g}.modulo\xBB: solo en ${[..._r].join(", ")}.`);let k=_.permiso===void 0?null:G(_.permiso,`${g}.permiso`,80);if(k!==null&&!El(h,k))throw i(`\xAB${g}.permiso\xBB: \xAB${k}\xBB no est\xE1 en \xABpermisos.modulos\xBB.`);if(x==="publica"&&k!==null)throw i(`\xAB${g}.permiso\xBB: la p\xE1gina p\xFAblica no lleva permiso (la ve cualquiera con el enlace).`);let L;if(x==="publica")L=we(ce(_.funciones,`${g}.funciones`,10).map((V,U)=>K(V,`${g}.funciones[${U}]`,Fo,"el nombre de una funci\xF3n")),V=>V,`${g}.funciones`);else if(_.funciones!==void 0)throw i(`\xAB${g}.funciones\xBB: solo en el montaje \xABpublica\xBB.`);return{id:K(_.id,`${g}.id`,/^[a-z][a-z0-9_-]{0,40}$/,"min\xFAsculas, n\xFAmeros, _ y -"),punto:x,entrada:K(_.entrada,`${g}.entrada`,oa,"un fichero del paquete (\xABinterfaz/index.html\xBB)"),titulo:G(_.titulo,`${g}.titulo`,60),icono:_.icono===void 0?null:K(_.icono,`${g}.icono`,Sl,"un icono de lucide"),modulo:O,permiso:k,...L?{funciones:L}:{}}}),_=>_.id,"montajes");if(v.filter(_=>_.punto==="publica").length>1)throw i("\xABmontajes\xBB: una app tiene como mucho una p\xE1gina p\xFAblica.");let w=we(ce(e.funciones,"funciones",20).map((_,E)=>{let g=`funciones[${E}]`;if(!me(_))throw i(`\xAB${g}\xBB: un objeto.`);if(Ne(_,["nombre","titulo","descripcion","entrada","disparador","tope","red","parametros","salida"],g),!me(_.disparador))throw i(`\xAB${g}.disparador\xBB: { tipo, \u2026 }.`);Ne(_.disparador,["tipo","evento","cron"],`${g}.disparador`);let x=G(_.disparador.tipo,`${g}.disparador.tipo`,20);if(!gn.includes(x))throw i(`\xAB${g}.disparador.tipo\xBB: ${gn.join(", ")}.`);let O={tipo:x};if(x==="evento"){let X=G(_.disparador.evento,`${g}.disparador.evento`,80);if(!h.eventos.includes(X)&&!b.some(Ve=>Ve.eventos.includes(X)))throw i(`\xAB${g}.disparador.evento\xBB: \xAB${X}\xBB tiene que estar en \xABpermisos.eventos\xBB (o en los \xABeventos\xBB de un contrato de \xABusa\xBB).`);O.evento=X}if(x==="programada"){O.cron=K(_.disparador.cron,`${g}.disparador.cron`,Wb,"un cron de 5 campos (\xAB0 7 * * 1-5\xBB)");let X=wl(O.cron);if(!X)throw i(`\xAB${g}.disparador.cron\xBB: un cron de 5 campos v\xE1lido (minuto 0-59, hora 0-23, d\xEDa 1-31, mes 1-12, semana 0-7).`);if(vl(X)<W.cronMinutos)throw i(`\xAB${g}.disparador.cron\xBB: como mucho una vez cada ${W.cronMinutos} minutos.`)}let k=me(_.tope)?_.tope:{};_.tope!==void 0&&Ne(k,["ms","memoria_mb"],`${g}.tope`);let L=k.ms===void 0?5e3:Number(k.ms),V=k.memoria_mb===void 0?64:Number(k.memoria_mb);if(!Number.isInteger(L)||L<W.ms.min||L>W.ms.max)throw i(`\xAB${g}.tope.ms\xBB: de ${W.ms.min} a ${W.ms.max}.`);if(!Number.isInteger(V)||V<W.memoriaMb.min||V>W.memoriaMb.max)throw i(`\xAB${g}.tope.memoria_mb\xBB: de ${W.memoriaMb.min} a ${W.memoriaMb.max}.`);let U=ce(_.red,`${g}.red`,10).map((X,Ve)=>Ml(X,`${g}.red[${Ve}]`,"un dominio"));for(let X of U)if(!Yb(h.red_hacia,X))throw i(`\xAB${g}.red\xBB: \xAB${X}\xBB tiene que estar en \xABpermisos.red_hacia\xBB.`);let be=ql(_.parametros,`${g}.parametros`),Be={},br=we(ce(_.salida,`${g}.salida`,30).map((X,Ve)=>{let Ue=`${g}.salida[${Ve}]`;if(!me(X))return K(X,Ue,Fo,"nombres en min\xFAsculas y _ (o { clave, titulo })");Ne(X,["clave","titulo"],Ue);let Do=K(X.clave,`${Ue}.clave`,Fo,"nombres en min\xFAsculas y _");return X.titulo!==void 0&&(Be[Do]=G(X.titulo,`${Ue}.titulo`,60)),Do}),X=>X,`${g}.salida`);if(x==="publica"&&U.length)throw i(`\xAB${g}.red\xBB: una funci\xF3n \xABpublica\xBB no sale a la red (solo lee el CRM).`);if(Object.keys(be).length&&x!=="automatizacion")throw i(`\xAB${g}.parametros\xBB: solo en las de disparador \xABautomatizacion\xBB (las dem\xE1s reciben su evento, su minuto o su webhook).`);return{nombre:K(_.nombre,`${g}.nombre`,Fo,"min\xFAsculas, n\xFAmeros y _"),titulo:_.titulo===void 0?null:G(_.titulo,`${g}.titulo`,80),descripcion:_.descripcion===void 0?null:G(_.descripcion,`${g}.descripcion`,300,!1),entrada:K(_.entrada,`${g}.entrada`,oa,"un fichero del paquete (\xABfunciones/calcular.js\xBB)"),disparador:O,tope:{ms:L,memoria_mb:V},red:U,parametros:be,salida:br,titulos_salida:Be}}),_=>_.nombre,"funciones"),N=null;if(e.servidor!==void 0&&e.servidor!==null){if(!me(e.servidor))throw i("\xABservidor\xBB: { url, webhooks }.");Ne(e.servidor,["url","webhooks"],"Servidor");let _=we(ce(e.servidor.webhooks,"servidor.webhooks",40).map((E,g)=>{if(typeof E!="string"||!h.eventos.includes(E))throw i(`\xABservidor.webhooks[${g}]\xBB: un evento que est\xE9 en \xABpermisos.eventos\xBB.`);return E}),E=>E,"servidor.webhooks");N={url:ta(e.servidor.url,"servidor.url"),webhooks:_}}let j=new Set(w.map(_=>_.nombre));for(let _ of v)for(let[E,g]of(_.funciones??[]).entries()){let x=w.find(O=>O.nombre===g);if(!x)throw i(`\xABmontajes\xBB.\xAB${_.id}\xBB.funciones[${E}]: \xAB${g}\xBB tiene que estar en \xABfunciones\xBB.`);if(x.disparador.tipo!=="publica")throw i(`\xABmontajes\xBB.\xAB${_.id}\xBB.funciones[${E}]: \xAB${g}\xBB tiene que ser de disparador \xABpublica\xBB.`)}let S=we(ce(e.herramientas_ia,"herramientas_ia",20).map((_,E)=>{let g=`herramientas_ia[${E}]`;if(!me(_))throw i(`\xAB${g}\xBB: un objeto.`);Ne(_,["nombre","descripcion","entrada","salida","riesgo","funcion","escribe","permiso"],g);let x=ql(_.entrada,`${g}.entrada`),O=G(_.riesgo,`${g}.riesgo`,10);if(!["bajo","medio","alto"].includes(O))throw i(`\xAB${g}.riesgo\xBB: bajo, medio o alto.`);let k=G(_.funcion,`${g}.funcion`,41);if(!j.has(k))throw i(`\xAB${g}.funcion\xBB: \xAB${k}\xBB tiene que estar en \xABfunciones\xBB.`);if(!["herramienta","calculo"].includes(w.find(V=>V.nombre===k)?.disparador.tipo??""))throw i(`\xAB${g}.funcion\xBB: \xAB${k}\xBB tiene que ser de disparador \xABherramienta\xBB (o \xABcalculo\xBB).`);if(_.escribe!==void 0&&typeof _.escribe!="boolean")throw i(`\xAB${g}.escribe\xBB: true o false.`);let L=null;if(_.permiso!==void 0){let V=G(_.permiso,`${g}.permiso`,80),U=V.lastIndexOf("."),be=U>0?lo(V.slice(0,U)):null;if(!be||!El(h,V))throw i(`\xAB${g}.permiso\xBB: \xAB${V}\xBB no est\xE1 en \xABpermisos.modulos\xBB.`);L=`${be}.${V.slice(U+1)}`}return{nombre:K(_.nombre,`${g}.nombre`,/^[a-z][a-z0-9_]{2,40}$/,"min\xFAsculas, n\xFAmeros y _ (3 a 41)"),descripcion:G(_.descripcion,`${g}.descripcion`,500),entrada:x,salida:we(ce(_.salida,`${g}.salida`,30).map((V,U)=>K(V,`${g}.salida[${U}]`,Fo,"nombres de campo")),V=>V,`${g}.salida`),riesgo:O,funcion:k,escribe:_.escribe===!0,permiso:L}}),_=>_.nombre,"herramientas_ia"),R=we(ce(e.ofrece,"ofrece",20).map((_,E)=>{let g=`ofrece[${E}]`;if(typeof _=="string")return Ol(K(_,g,ra,"un nombre de contrato (\xABtaller.citas\xBB)"));let x=Al(_,g,[]);for(let[O,k]of Object.entries(x.modulos)){if(!O.startsWith("mod_"))throw i(`\xAB${g}.modulos\xBB: \xAB${O}\xBB es de serie; un contrato solo comparte m\xF3dulos de la soluci\xF3n de la app.`);let L=h.modulos[O]??[],V=k.find(U=>!L.includes(U));if(V)throw i(`\xAB${g}.modulos.${O.slice(4)}\xBB: ofrece \xAB${V}\xBB y \xABpermisos.modulos\xBB no lo pide (nadie da lo que no tiene).`)}for(let O of x.eventos)if(!h.eventos.includes(O))throw i(`\xAB${g}.eventos\xBB: \xAB${O}\xBB tiene que estar en \xABpermisos.eventos\xBB.`);for(let O of x.herramientas){let k=S.find(L=>L.nombre===O);if(!k)throw i(`\xAB${g}.herramientas\xBB: \xAB${O}\xBB tiene que estar en \xABherramientas_ia\xBB.`);if(k.escribe)throw i(`\xAB${g}.herramientas\xBB: \xAB${O}\xBB escribe; un contrato solo comparte herramientas que consultan.`)}return x}),_=>_.contrato,"ofrece"),F=we(ce(e.ajustes,"ajustes",40).map((_,E)=>{let g=`ajustes[${E}]`;if(!me(_))throw i(`\xAB${g}\xBB: un objeto.`);Ne(_,["clave","etiqueta","tipo","opciones","requerido"],g);let x=G(_.tipo,`${g}.tipo`,10);if(!bn.includes(x))throw i(`\xAB${g}.tipo\xBB: ${bn.join(", ")}.`);let O=ce(_.opciones,`${g}.opciones`,50).map((k,L)=>{if(!me(k))throw i(`\xAB${g}.opciones[${L}]\xBB: { valor, etiqueta }.`);return Ne(k,["valor","etiqueta"],`${g}.opciones[${L}]`),{valor:G(k.valor,`${g}.opciones[${L}].valor`,60),etiqueta:G(k.etiqueta,`${g}.opciones[${L}].etiqueta`,80)}});if(x==="opcion"&&!O.length)throw i(`\xAB${g}.opciones\xBB: un ajuste de tipo opci\xF3n necesita sus opciones.`);if(x!=="opcion"&&O.length)throw i(`\xAB${g}.opciones\xBB: solo en los de tipo opci\xF3n.`);return{clave:K(_.clave,`${g}.clave`,Fo,"min\xFAsculas, n\xFAmeros y _"),etiqueta:G(_.etiqueta,`${g}.etiqueta`,80),tipo:x,opciones:we(O,k=>k.valor,`${g}.opciones`),requerido:_.requerido===!0}}),_=>_.clave,"ajustes"),I=we(ce(e.secretos,"secretos",10).map((_,E)=>{let g=`secretos[${E}]`;if(!me(_))throw i(`\xAB${g}\xBB: un objeto.`);return Ne(_,["clave","etiqueta","descripcion"],g),{clave:K(_.clave,`${g}.clave`,Fo,"min\xFAsculas, n\xFAmeros y _"),etiqueta:G(_.etiqueta,`${g}.etiqueta`,80),descripcion:G(_.descripcion,`${g}.descripcion`,300,!1)}}),_=>_.clave,"secretos");return{formato:at,formato_version:e.formato_version,id:t,nombre:n,descripcion:G(e.descripcion,"descripcion",500,!1),version:r,autor:a,icono:s,idiomas:c,compatible_crm:d,licencia:u,...p,depende_de:m,ofrece:R,usa:b,solucion:y,montajes:v,funciones:w,servidor:N,herramientas_ia:S,ajustes:F,secretos:I,...e.conexiones!==void 0?{conexiones:fl(e.conexiones)}:{},permisos:h}}var at,wn,hn,Bo,Wo,Pt,vn,_r,gn,bn,xl,Cl,Db,fn,Lb,jl,Sl,zb,ra,Fo,Fb,oa,Rl,Wb,me,kl,Bb,A0,Vb,Pl,Tl,Jb,Qb,ia,aa,Ol,Yb,Tt=f(()=>{hl();q();bl();yl();yr();$l();at="forgenex.extension",wn=1,hn=256e3,Bo={contactos:{nombre:"Personas",ops:["ver","crear","editar","borrar"]},empresas:{nombre:"Empresas",ops:["ver","crear","editar","borrar"]},oportunidades:{nombre:"Oportunidades",ops:["ver","crear","editar","borrar"]},tareas:{nombre:"Tareas",ops:["ver","crear","editar","borrar"]},notas:{nombre:"Notas",ops:["ver","editar"]}},Wo=["ver","crear","editar","borrar"],Pt=["pagina","ficha_pestana","ficha_bloque","inicio_bloque","accion_ficha","accion_tabla","vista","ajustes","publica"],vn=new Set(["pagina","ficha_pestana","ficha_bloque","inicio_bloque","accion_ficha","accion_tabla","vista","ajustes","publica"]),_r=new Set(["ficha_pestana","ficha_bloque","accion_ficha","accion_tabla","vista"]),gn=["evento","programada","webhook","automatizacion","calculo","herramienta","publica"],bn=["texto","numero","si_no","opcion","modulo","campo"],xl=["registro.creado","registro.actualizado","registro.borrado"],Cl=["leer","escribir"],Db=new Set(["__proto__","constructor","prototype"]),fn=/^[a-z][a-z0-9-]{0,62}(\.[a-z0-9][a-z0-9-]{0,62}){1,6}$/,Lb=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})(-[0-9a-z.-]{1,30})?$/,jl=/^(>=|<=|>|<|=|\^|~)?(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})(-[0-9a-z.-]{1,30})?$/,Sl=/^[a-z0-9-]{1,40}$/,zb=/^[a-z]{2,3}(-[A-Z]{2})?$/,ra=/^[a-z][a-z0-9_.-]{0,79}$/,Fo=/^[a-z][a-z0-9_]{0,40}$/,Fb=/^[a-z][a-z0-9_]{0,59}$/,oa=/^(?!\/)(?!.*\/\/)(?!.*(^|\/)\.\.?(\/|$))[A-Za-z0-9_.\/-]{1,200}$/,Rl=/^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,Wb=/^[0-9*,\/-]+( [0-9*,\/-]+){4}$/,me=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);kl=String.raw`[\p{Cc}\p{Cf}\u2028\u2029\u034F\u115F\u1160\u2800\u3164\uFFA0]|(?<!\p{Emoji})[\uFE00-\uFE0F]|(?<=[0-9#*])[\uFE00-\uFE0F](?!\u20E3)`,Bb=new RegExp(kl,"u"),A0=new RegExp(kl,"gu"),Vb=new RegExp("(?<=\\p{Extended_Pictographic}[\\uFE0F\\p{Emoji_Modifier}]?)\\u200D(?=\\p{Extended_Pictographic})","gu");Pl={\u0391:"a",\u0392:"b",\u0395:"e",\u0396:"z",\u0397:"h",\u0399:"i",\u039A:"k",\u039C:"m",\u039D:"n",\u039F:"o",\u03A1:"p",\u03A4:"t",\u03A5:"y",\u03A7:"x",\u0410:"a",\u0412:"b",\u0415:"e",\u0405:"s",\u0406:"i",\u0408:"j",\u041A:"k",\u041C:"m",\u041D:"h",\u041E:"o",\u0420:"p",\u0421:"c",\u0422:"t",\u0425:"x",\u04AE:"y","\u050C":"g","\u051A":"q","\u051C":"w"},Tl={\u03B1:"a",\u03B2:"b",\u03B3:"y",\u03B5:"e",\u03B7:"n",\u03B9:"i",\u03BA:"k",\u03BD:"v",\u03BF:"o",\u03C1:"p",\u03C4:"t",\u03C5:"u",\u03C7:"x",\u03C9:"w",\u0430:"a",\u0435:"e",\u0451:"e",\u043E:"o",\u0440:"p",\u0441:"c",\u0443:"y",\u0445:"x",\u0455:"s",\u0456:"i",\u0457:"i",\u0458:"j","\u0501":"d",\u04BB:"h","\u04CF":"l","\u051B":"q","\u051D":"w",\u0261:"g",\u0433:"r",\u043F:"n",\u049D:"k",\u043A:"k",\u0131:"i","\u0237":"j",0:"o","\u1D00":"a",\u0299:"b","\u1D04":"c","\u1D05":"d","\u1D07":"e","\uA730":"f",\u0262:"g",\u029C:"h",\u026A:"i","\u1D0A":"j","\u1D0B":"k",\u029F:"l","\u1D0D":"m",\u0274:"n","\u1D0F":"o","\u1D18":"p",\u0280:"r","\uA731":"s","\u1D1B":"t","\u1D1C":"u","\u1D20":"v","\u1D21":"w",\u028F:"y","\u1D22":"z",\u0585:"o","\uA4EE":"a","\uA4D0":"b","\uA4DA":"c","\uA4D3":"d","\uA4F0":"e","\uA4DD":"f","\uA4D6":"g","\uA4E7":"h","\uA4F2":"i","\uA4D9":"j","\uA4D7":"k","\uA4E1":"l","\uA4DF":"m","\uA4E0":"n","\uA4F3":"o","\uA4D1":"p","\uA4E3":"r","\uA4E2":"s","\uA4D4":"t","\uA4F4":"u","\uA4E6":"v","\uA4EA":"w","\uA4EB":"x","\uA4EC":"y","\uA4DC":"z"},Jb=new RegExp(`[${Object.keys(Pl).join("")}]`,"gu"),Qb=new RegExp(`[${Object.keys(Tl).join("")}]`,"gu"),ia=e=>e.normalize("NFKC").replace(Jb,o=>Pl[o]).toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"").replace(Qb,o=>Tl[o]).replace(/[^\p{L}\p{N}]/gu,"");aa=e=>{let o=Gb(e);for(let t=0;t<o.length;t++){let n="";for(let r=t;r<o.length&&n.length<8;r++)if(n+=o[r],n==="forgenex")return!0}return!1};Ol=e=>({contrato:e,titulo:null,modulos:{},eventos:[],herramientas:[]});Yb=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1)))});function $o(e){return typeof e>"u"||e===void 0}function H(e){return typeof e=="string"}function uo(e){return typeof e=="number"}function st(e){return typeof e=="boolean"}function ct(e){return e===null}function sa(e){return e instanceof Date}function lt(e){return typeof e=="bigint"}function Il(e){return typeof Buffer<"u"&&Buffer.isBuffer(e)}function $e(e){return typeof e=="function"}function je(e){return typeof e=="object"&&e!==null}function l(e){return Object.freeze(e)}function Nr(e){return ke(e)?e:[e]}function ke(e){return Array.isArray(e)}function Dl(e){return e instanceof Error?e.message:String(e)}var $=f(()=>{});var k0,Ll=f(()=>{$();k0=l({is(e){return e.kind==="AlterTableNode"},create(e){return l({kind:"AlterTableNode",table:e})},cloneWithTableProps(e,o){return l({...e,...o})},cloneWithColumnAlteration(e,o){return l({...e,columnAlterations:e.columnAlterations?[...e.columnAlterations,o]:[o]})}})});var M,ne=f(()=>{$();M=l({is(e){return e.kind==="IdentifierNode"},create(e){return l({kind:"IdentifierNode",name:e})}})});var L0,zl=f(()=>{$();ne();L0=l({is(e){return e.kind==="CreateIndexNode"},create(e){return l({kind:"CreateIndexNode",name:M.create(e)})},cloneWith(e,o){return l({...e,...o})},cloneWithColumns(e,o){return l({...e,columns:[...e.columns||[],...o]})}})});var B0,Fl=f(()=>{$();ne();B0=l({is(e){return e.kind==="CreateSchemaNode"},create(e,o){return l({kind:"CreateSchemaNode",schema:M.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var J0,Wl=f(()=>{$();J0=l({is(e){return e.kind==="CreateTableNode"},create(e){return l({kind:"CreateTableNode",table:e,columns:l([])})},cloneWithColumn(e,o){return l({...e,columns:l([...e.columns,o])})},cloneWithConstraint(e,o){return l({...e,constraints:e.constraints?l([...e.constraints,o]):l([o])})},cloneWithIndex(e,o){return l({...e,indexes:e.indexes?l([...e.indexes,o]):l([o])})},cloneWithFrontModifier(e,o){return l({...e,frontModifiers:e.frontModifiers?l([...e.frontModifiers,o]):l([o])})},cloneWithEndModifier(e,o){return l({...e,endModifiers:e.endModifiers?l([...e.endModifiers,o]):l([o])})},cloneWith(e,o){return l({...e,...o})}})});var Ye,ut=f(()=>{$();ne();Ye=l({is(e){return e.kind==="SchemableIdentifierNode"},create(e){return l({kind:"SchemableIdentifierNode",identifier:M.create(e)})},createWithSchema(e,o){return l({kind:"SchemableIdentifierNode",schema:M.create(e),identifier:M.create(o)})}})});var Z0,Bl=f(()=>{$();ut();Z0=l({is(e){return e.kind==="DropIndexNode"},create(e,o){return l({kind:"DropIndexNode",name:Ye.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var rN,Vl=f(()=>{$();ne();rN=l({is(e){return e.kind==="DropSchemaNode"},create(e,o){return l({kind:"DropSchemaNode",schema:M.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var aN,Ul=f(()=>{$();aN=l({is(e){return e.kind==="DropTableNode"},create(e,o){return l({kind:"DropTableNode",table:e,...o})},cloneWith(e,o){return l({...e,...o})}})});var Pe,xo=f(()=>{$();Pe=l({is(e){return e.kind==="AliasNode"},create(e,o){return l({kind:"AliasNode",node:e,alias:o})}})});var Uo,$r=f(()=>{$();ut();Uo=l({is(e){return e.kind==="TableNode"},create(e){return l({kind:"TableNode",table:Ye.create(e)})},createWithSchema(e,o){return l({kind:"TableNode",table:Ye.createWithSchema(e,o)})}})});function ie(e){return je(e)&&$e(e.toOperationNode)}var Je=f(()=>{$()});function yn(e){return je(e)&&"expressionType"in e&&ie(e)}function Jl(e){return je(e)&&"expression"in e&&H(e.alias)&&ie(e)}var _n=f(()=>{Je();$()});var po,ca=f(()=>{$();po=l({is(e){return e.kind==="SelectModifierNode"},create(e,o){return l({kind:"SelectModifierNode",modifier:e,of:o})},createWithExpression(e){return l({kind:"SelectModifierNode",rawModifier:e})}})});var Te,Jo=f(()=>{$();Te=l({is(e){return e.kind==="AndNode"},create(e,o){return l({kind:"AndNode",left:e,right:o})}})});var Ke,dt=f(()=>{$();Ke=l({is(e){return e.kind==="OrNode"},create(e,o){return l({kind:"OrNode",left:e,right:o})}})});var Nn,la=f(()=>{$();Jo();dt();Nn=l({is(e){return e.kind==="OnNode"},create(e){return l({kind:"OnNode",on:e})},cloneWithOperation(e,o,t){return l({...e,on:o==="And"?Te.create(e.on,t):Ke.create(e.on,t)})}})});var Co,xr=f(()=>{$();la();Co=l({is(e){return e.kind==="JoinNode"},create(e,o){return l({kind:"JoinNode",joinType:e,table:o,on:void 0})},createWithOn(e,o,t){return l({kind:"JoinNode",joinType:e,table:o,on:Nn.create(t)})},cloneWithOn(e,o){return l({...e,on:e.on?Nn.cloneWithOperation(e.on,"And",o):Nn.create(o)})}})});var Qo,$n=f(()=>{$();Qo=l({is(e){return e.kind==="BinaryOperationNode"},create(e,o,t){return l({kind:"BinaryOperationNode",leftOperand:e,operator:o,rightOperand:t})}})});function Zl(e){return H(e)&&Xl[e]}function eu(e){return H(e)&&Hl[e]}function ou(e){return H(e)&&Kl[e]}var Ql,PN,Gl,TN,Hl,Kb,Xl,Zb,Yl,MN,Kl,ew,IN,Ze,Mt=f(()=>{$();Ql=l({"=":!0,"==":!0,"!=":!0,"<>":!0,">":!0,">=":!0,"<":!0,"<=":!0,in:!0,"not in":!0,is:!0,"is not":!0,like:!0,"not like":!0,match:!0,ilike:!0,"not ilike":!0,"@>":!0,"<@":!0,"^@":!0,"&&":!0,"?":!0,"?&":!0,"?|":!0,"!<":!0,"!>":!0,"<=>":!0,"!~":!0,"~":!0,"~*":!0,"!~*":!0,"@@":!0,"@@@":!0,"!!":!0,"<->":!0,regexp:!0,"is distinct from":!0,"is not distinct from":!0}),PN=Object.keys(Ql),Gl=l({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0}),TN=Object.keys(Gl),Hl=l({"->":!0,"->>":!0}),Kb=Object.keys(Hl),Xl=l({...Ql,...Gl,"||":!0}),Zb=Object.keys(Xl),Yl=l({exists:!0,"not exists":!0}),MN=Object.keys(Yl),Kl=l({...Yl,"-":!0,not:!0}),ew=Object.keys(Kl),IN=[...Zb,...Kb,...ew,"between","between symmetric"],Ze=l({is(e){return e.kind==="OperatorNode"},create(e){return l({kind:"OperatorNode",operator:e})}})});var ue,eo=f(()=>{$();ne();ue=l({is(e){return e.kind==="ColumnNode"},create(e){return l({kind:"ColumnNode",column:M.create(e)})}})});var xn,Cn=f(()=>{$();xn=l({is(e){return e.kind==="SelectAllNode"},create(){return l({kind:"SelectAllNode"})}})});var It,jn=f(()=>{Cn();$();It=l({is(e){return e.kind==="ReferenceNode"},create(e,o){return l({kind:"ReferenceNode",table:o,column:e})},createSelectAll(e){return l({kind:"ReferenceNode",table:e,column:xn.create()})}})});function Sn(e){return je(e)&&ie(e)&&H(e.dynamicReference)}var On=f(()=>{Je();$()});var oo,An=f(()=>{$();oo=l({is(e){return e.kind==="OrderByItemNode"},create(e,o){return l({kind:"OrderByItemNode",orderBy:e,direction:o})},cloneWith(e,o){return l({...e,...o})}})});var de,pt=f(()=>{$();de=l({is(e){return e.kind==="RawNode"},create(e,o){return l({kind:"RawNode",sqlFragments:l(e),parameters:l(o)})},createWithSql(e){return de.create([e],[])},createWithChild(e){return de.create(["",""],[e])},createWithChildren(e){return de.create(new Array(e.length+1).fill(""),e)}})});var tu,ua=f(()=>{$();ne();tu=l({is(e){return e.kind==="CollateNode"},create(e){return l({kind:"CollateNode",collation:M.create(e)})}})});var En,da=f(()=>{ua();An();pt();$();En=class e{#e;constructor(o){this.#e=l(o)}desc(){return new e({node:oo.cloneWith(this.#e.node,{direction:de.createWithSql("desc")})})}asc(){return new e({node:oo.cloneWith(this.#e.node,{direction:de.createWithSql("asc")})})}nullsLast(){return new e({node:oo.cloneWith(this.#e.node,{nulls:"last"})})}nullsFirst(){return new e({node:oo.cloneWith(this.#e.node,{nulls:"first"})})}collate(o){return new e({node:oo.cloneWith(this.#e.node,{collation:tu.create(o)})})}toOperationNode(){return this.#e.node}}});function Dt(e){ru.has(e)||(ru.add(e),console.log(e))}var ru,pa=f(()=>{ru=new Set});function ow(e){return e==="asc"||e==="desc"}function to(e){if(e.length===2)return[ma(e[0],e[1])];if(e.length===1){let[o]=e;return Array.isArray(o)?(Dt("orderBy(array) is deprecated, use multiple orderBy calls instead."),o.map(t=>ma(t))):[ma(o)]}throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${e.length}`)}function ma(e,o){let t=tw(e);if(oo.is(t)){if(o)throw new Error("Cannot specify direction twice!");return t}return nu(t,o)}function tw(e){if(mt(e))return Go(e);if(Sn(e))return e.toOperationNode();let[o,t]=e.split(" ");return t?(Dt("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),nu(Qe(o),t)):Qe(e)}function nu(e,o){if(typeof o=="string"){if(!ow(o))throw new Error(`Invalid order by direction: ${o}`);return oo.create(e,de.createWithSql(o))}if(yn(o))return Dt("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),oo.create(e,o.toOperationNode());let t=oo.create(e);return o?o(new En({node:t})).toOperationNode():t}var Lt=f(()=>{On();_n();An();pt();da();pa();ft();Ie()});var zt,qn=f(()=>{$();zt=l({is(e){return e.kind==="JSONReferenceNode"},create(e,o){return l({kind:"JSONReferenceNode",reference:e,traversal:o})},cloneWithTraversal(e,o){return l({...e,traversal:o})}})});var Rn,kn=f(()=>{$();Rn=l({is(e){return e.kind==="JSONOperatorChainNode"},create(e){return l({kind:"JSONOperatorChainNode",operator:e,values:l([])})},cloneWithValue(e,o){return l({...e,values:l([...e.values,o])})}})});var Ho,Cr=f(()=>{$();Ho=l({is(e){return e.kind==="JSONPathNode"},create(e){return l({kind:"JSONPathNode",inOperator:e,pathLegs:l([])})},cloneWithLeg(e,o){return l({...e,pathLegs:l([...e.pathLegs,o])})}})});function rw(e){return H(e)?Qe(e):e.toOperationNode()}function jo(e){return ke(e)?e.map(o=>fe(o)):[fe(e)]}function fe(e){return mt(e)?Go(e):rw(e)}function iu(e,o){if(eu(o))return zt.create(Qe(e),Rn.create(Ze.create(o)));if(o==="->$"||o==="->>$")return zt.create(Qe(e),Ho.create(Ze.create(o.slice(0,-1))));throw new Error(`Invalid JSON operator: ${o}`)}function Qe(e){if(!e.includes("."))return It.create(ue.create(e));let t=e.split(".").map(su);if(t.length===3)return nw(t);if(t.length===2)return iw(t);throw new Error(`invalid column reference ${e}`)}function au(e){let o=" as ";if(e.includes(o)){let[t,n]=e.split(o).map(su);return Pe.create(Qe(t),M.create(n))}else return Qe(e)}function nw(e){let[o,t,n]=e;return It.create(ue.create(n),Uo.createWithSchema(o,t))}function iw(e){let[o,t]=e;return It.create(ue.create(t),Uo.create(o))}function su(e){return e.trim()}var Ie=f(()=>{xo();eo();jn();$r();$();ft();ne();Mt();qn();kn();Cr()});var cu,fa=f(()=>{$();cu=l({is(e){return e.kind==="PrimitiveValueListNode"},create(e){return l({kind:"PrimitiveValueListNode",values:l([...e])})}})});var Pn,Tn=f(()=>{$();Pn=l({is(e){return e.kind==="ValueListNode"},create(e){return l({kind:"ValueListNode",values:l(e)})}})});var Se,Xo=f(()=>{$();Se=l({is(e){return e.kind==="ValueNode"},create(e){return l({kind:"ValueNode",value:e})},createImmediate(e){return l({kind:"ValueNode",value:e,immediate:!0})}})});function lu(e){return ke(e)?aw(e):Z(e)}function Z(e){return mt(e)?Go(e):Se.create(e)}function Mn(e){return uo(e)||st(e)||ct(e)}function jr(e){if(!Mn(e))throw new Error(`unsafe immediate value ${JSON.stringify(e)}`);return Se.createImmediate(e)}function aw(e){return e.some(mt)?Pn.create(e.map(o=>Z(o))):cu.create(e)}var So=f(()=>{fa();Tn();Xo();$();ft()});var Yo,Sr=f(()=>{$();Yo=l({is(e){return e.kind==="ParensNode"},create(e){return l({kind:"ParensNode",node:e})}})});function pe(e){if(e.length===3)return In(e[0],e[1],e[2]);if(e.length===1)return Z(e[0]);throw new Error(`invalid arguments: ${JSON.stringify(e)}`)}function In(e,o,t){return sw(o)&&du(t)?Qo.create(fe(e),ha(o),Se.createImmediate(t)):Qo.create(fe(e),ha(o),lu(t))}function xe(e,o,t){return Qo.create(fe(e),ha(o),fe(t))}function ga(e,o){return Dn(Object.entries(e).filter(([,t])=>!$o(t)).map(([t,n])=>In(t,du(n)?"is":"=",n)),o)}function Dn(e,o,t=!0){let n=o==="and"?Te.create:Ke.create;if(e.length===0)return Qo.create(Se.createImmediate(1),Ze.create("="),Se.createImmediate(o==="and"?1:0));let r=uu(e[0]);for(let a=1;a<e.length;++a)r=n(r,uu(e[a]));return e.length>1&&t?Yo.create(r):r}function sw(e){return e==="is"||e==="is not"}function du(e){return ct(e)||st(e)}function ha(e){if(Zl(e))return Ze.create(e);if(ie(e))return e.toOperationNode();throw new Error(`invalid operator ${JSON.stringify(e)}`)}function uu(e){return ie(e)?e.toOperationNode():e}var mo=f(()=>{$n();$();Je();Mt();Ie();So();Xo();Jo();Sr();dt()});var Oo,Or=f(()=>{$();Oo=l({is(e){return e.kind==="OrderByNode"},create(e){return l({kind:"OrderByNode",items:l([...e])})},cloneWithItems(e,o){return l({...e,items:l([...e.items,...o])})}})});var ba,wa=f(()=>{$();ba=l({is(e){return e.kind==="PartitionByNode"},create(e){return l({kind:"PartitionByNode",items:l(e)})},cloneWithItems(e,o){return l({...e,items:l([...e.items,...o])})}})});var Ar,Ln=f(()=>{$();Or();wa();Ar=l({is(e){return e.kind==="OverNode"},create(){return l({kind:"OverNode"})},cloneWithOrderByItems(e,o){return l({...e,orderBy:e.orderBy?Oo.cloneWithItems(e.orderBy,o):Oo.create(o)})},cloneWithPartitionByItems(e,o){return l({...e,partitionBy:e.partitionBy?ba.cloneWithItems(e.partitionBy,o):ba.create(o)})}})});var ht,Er=f(()=>{$();ht=l({is(e){return e.kind==="FromNode"},create(e){return l({kind:"FromNode",froms:l(e)})},cloneWithFroms(e,o){return l({...e,froms:l([...e.froms,...o])})}})});var va,ya=f(()=>{$();va=l({is(e){return e.kind==="GroupByNode"},create(e){return l({kind:"GroupByNode",items:l(e)})},cloneWithItems(e,o){return l({...e,items:l([...e.items,...o])})}})});var _a,Na=f(()=>{$();Jo();dt();_a=l({is(e){return e.kind==="HavingNode"},create(e){return l({kind:"HavingNode",having:e})},cloneWithOperation(e,o,t){return l({...e,having:o==="And"?Te.create(e.having,t):Ke.create(e.having,t)})}})});var pu,$a=f(()=>{$();pu=l({is(e){return e.kind==="InsertQueryNode"},create(e,o,t){return l({kind:"InsertQueryNode",into:e,...o&&{with:o},replace:t})},createWithoutInto(){return l({kind:"InsertQueryNode"})},cloneWith(e,o){return l({...e,...o})}})});var mu,xa=f(()=>{$();mu=l({is(e){return e.kind==="ListNode"},create(e){return l({kind:"ListNode",items:l(e)})}})});var Ft,zn=f(()=>{$();Er();xa();Ft=l({is(e){return e.kind==="UpdateQueryNode"},create(e,o){return l({kind:"UpdateQueryNode",table:e.length===1?e[0]:mu.create(e),...o&&{with:o}})},createWithoutTable(){return l({kind:"UpdateQueryNode"})},cloneWithFromItems(e,o){return l({...e,from:e.from?ht.cloneWithFroms(e.from,o):ht.create(o)})},cloneWithUpdates(e,o){return l({...e,updates:e.updates?l([...e.updates,...o]):o})},cloneWithLimit(e,o){return l({...e,limit:o})}})});var Ca,ja=f(()=>{$();Ca=l({is(e){return e.kind==="UsingNode"},create(e){return l({kind:"UsingNode",tables:l(e)})},cloneWithTables(e,o){return l({...e,tables:l([...e.tables,...o])})}})});var Wt,Fn=f(()=>{$();Er();ja();Ao();Wt=l({is(e){return e.kind==="DeleteQueryNode"},create(e,o){return l({kind:"DeleteQueryNode",from:ht.create(e),...o&&{with:o}})},cloneWithOrderByItems:(e,o)=>P.cloneWithOrderByItems(e,o),cloneWithoutOrderBy:e=>P.cloneWithoutOrderBy(e),cloneWithLimit(e,o){return l({...e,limit:o})},cloneWithoutLimit(e){return l({...e,limit:void 0})},cloneWithUsing(e,o){return l({...e,using:e.using!==void 0?Ca.cloneWithTables(e.using,o):Ca.create(o)})}})});var ye,qr=f(()=>{$();Jo();dt();ye=l({is(e){return e.kind==="WhereNode"},create(e){return l({kind:"WhereNode",where:e})},cloneWithOperation(e,o,t){return l({...e,where:o==="And"?Te.create(e.where,t):Ke.create(e.where,t)})}})});var Sa,Oa=f(()=>{$();Sa=l({is(e){return e.kind==="ReturningNode"},create(e){return l({kind:"ReturningNode",selections:l(e)})},cloneWithSelections(e,o){return l({...e,selections:e.selections?l([...e.selections,...o]):l(o)})}})});var fu,Aa=f(()=>{$();fu=l({is(e){return e.kind==="ExplainNode"},create(e,o){return l({kind:"ExplainNode",format:e,options:o})}})});var Eo,Rr=f(()=>{$();Eo=l({is(e){return e.kind==="WhenNode"},create(e){return l({kind:"WhenNode",condition:e})},cloneWithResult(e,o){return l({...e,result:o})}})});var hu,Ea=f(()=>{$();Rr();hu=l({is(e){return e.kind==="MergeQueryNode"},create(e,o){return l({kind:"MergeQueryNode",into:e,...o&&{with:o}})},cloneWithUsing(e,o){return l({...e,using:o})},cloneWithWhen(e,o){return l({...e,whens:e.whens?l([...e.whens,o]):l([o])})},cloneWithThen(e,o){return l({...e,whens:e.whens?l([...e.whens.slice(0,-1),Eo.cloneWithResult(e.whens[e.whens.length-1],o)]):void 0})}})});var qa,Ra=f(()=>{$();qa=l({is(e){return e.kind==="OutputNode"},create(e){return l({kind:"OutputNode",selections:l(e)})},cloneWithSelections(e,o){return l({...e,selections:e.selections?l([...e.selections,...o]):l(o)})}})});var P,Ao=f(()=>{$a();kr();zn();Fn();qr();$();Oa();Aa();Ea();Ra();Or();P=l({is(e){return ee.is(e)||pu.is(e)||Ft.is(e)||Wt.is(e)||hu.is(e)},cloneWithEndModifier(e,o){return l({...e,endModifiers:e.endModifiers?l([...e.endModifiers,o]):l([o])})},cloneWithWhere(e,o){return l({...e,where:e.where?ye.cloneWithOperation(e.where,"And",o):ye.create(o)})},cloneWithJoin(e,o){return l({...e,joins:e.joins?l([...e.joins,o]):l([o])})},cloneWithReturning(e,o){return l({...e,returning:e.returning?Sa.cloneWithSelections(e.returning,o):Sa.create(o)})},cloneWithoutReturning(e){return l({...e,returning:void 0})},cloneWithoutWhere(e){return l({...e,where:void 0})},cloneWithExplain(e,o,t){return l({...e,explain:fu.create(o,t?.toOperationNode())})},cloneWithTop(e,o){return l({...e,top:o})},cloneWithOutput(e,o){return l({...e,output:e.output?qa.cloneWithSelections(e.output,o):qa.create(o)})},cloneWithOrderByItems(e,o){return l({...e,orderBy:e.orderBy?Oo.cloneWithItems(e.orderBy,o):Oo.create(o)})},cloneWithoutOrderBy(e){return l({...e,orderBy:void 0})}})});var ee,kr=f(()=>{$();Er();ya();Na();Ao();ee=l({is(e){return e.kind==="SelectQueryNode"},create(e){return l({kind:"SelectQueryNode",...e&&{with:e}})},createFrom(e,o){return l({kind:"SelectQueryNode",from:ht.create(e),...o&&{with:o}})},cloneWithSelections(e,o){return l({...e,selections:e.selections?l([...e.selections,...o]):l(o)})},cloneWithDistinctOn(e,o){return l({...e,distinctOn:e.distinctOn?l([...e.distinctOn,...o]):l(o)})},cloneWithFrontModifier(e,o){return l({...e,frontModifiers:e.frontModifiers?l([...e.frontModifiers,o]):l([o])})},cloneWithOrderByItems:(e,o)=>P.cloneWithOrderByItems(e,o),cloneWithGroupByItems(e,o){return l({...e,groupBy:e.groupBy?va.cloneWithItems(e.groupBy,o):va.create(o)})},cloneWithLimit(e,o){return l({...e,limit:o})},cloneWithOffset(e,o){return l({...e,offset:o})},cloneWithFetch(e,o){return l({...e,fetch:o})},cloneWithHaving(e,o){return l({...e,having:e.having?_a.cloneWithOperation(e.having,"And",o):_a.create(o)})},cloneWithSetOperations(e,o){return l({...e,setOperations:e.setOperations?l([...e.setOperations,...o]):l([...o])})},cloneWithoutSelections(e){return l({...e,selections:[]})},cloneWithoutLimit(e){return l({...e,limit:void 0})},cloneWithoutOffset(e){return l({...e,offset:void 0})},cloneWithoutOrderBy:e=>P.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return l({...e,groupBy:void 0})}})});var Wn,ka=f(()=>{xr();pt();mo();$();Wn=class e{#e;constructor(o){this.#e=l(o)}on(...o){return new e({...this.#e,joinNode:Co.cloneWithOn(this.#e.joinNode,pe(o))})}onRef(o,t,n){return new e({...this.#e,joinNode:Co.cloneWithOn(this.#e.joinNode,xe(o,t,n))})}onTrue(){return new e({...this.#e,joinNode:Co.cloneWithOn(this.#e.joinNode,de.createWithSql("true"))})}$call(o){return o(this)}toOperationNode(){return this.#e.joinNode}}});var gu,Pa=f(()=>{$();gu=l({is(e){return e.kind==="PartitionByItemNode"},create(e){return l({kind:"PartitionByItemNode",partitionBy:e})}})});function bu(e){return jo(e).map(gu.create)}var wu=f(()=>{Pa();Ie()});var Bn,vu=f(()=>{Ln();Ao();Lt();wu();$();Bn=class e{#e;constructor(o){this.#e=l(o)}orderBy(...o){return new e({overNode:Ar.cloneWithOrderByItems(this.#e.overNode,to(o))})}clearOrderBy(){return new e({overNode:P.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(o){return new e({overNode:Ar.cloneWithPartitionByItems(this.#e.overNode,bu(o))})}$call(o){return o(this)}toOperationNode(){return this.#e.overNode}}});var Bt,Ta=f(()=>{$();jn();Cn();Bt=l({is(e){return e.kind==="SelectionNode"},create(e){return l({kind:"SelectionNode",selection:e})},createSelectAll(){return l({kind:"SelectionNode",selection:xn.create()})},createSelectAllFromTable(e){return l({kind:"SelectionNode",selection:It.createSelectAll(e)})}})});function qo(e){return $e(e)?qo(e(Ro())):ke(e)?e.map(o=>yu(o)):[yu(e)]}function yu(e){return H(e)?Bt.create(au(e)):Sn(e)?Bt.create(e.toOperationNode()):Bt.create(Vn(e))}function fo(e){return e?Array.isArray(e)?e.map(_u):[_u(e)]:[Bt.createSelectAll()]}function _u(e){if(H(e))return Bt.createSelectAllFromTable(Ce(e));throw new Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}var Pr=f(()=>{$();Ta();Ie();On();ft();ho();Vt()});var JC,Nu=f(()=>{$();JC=l({is(e){return e.kind==="ValuesNode"},create(e){return l({kind:"ValuesNode",values:l(e)})}})});var HC,$u=f(()=>{$();HC=l({is(e){return e.kind==="DefaultInsertValueNode"},create(){return l({kind:"DefaultInsertValueNode"})}})});var Ma,Ia=f(()=>{$();Ma=l({is(e){return e.kind==="ColumnUpdateNode"},create(e,o){return l({kind:"ColumnUpdateNode",column:e,value:o})}})});function xu(...e){return e.length===2?[Ma.create(fe(e[0]),Z(e[1]))]:cw(e[0])}function cw(e){let o=$e(e)?e(Ro()):e;return Object.entries(o).filter(([t,n])=>n!==void 0).map(([t,n])=>Ma.create(ue.create(t),Z(n)))}var Cu=f(()=>{eo();Ia();Vt();$();So();Ie()});var sj,ju=f(()=>{$();sj=l({is(e){return e.kind==="OnDuplicateKeyNode"},create(e){return l({kind:"OnDuplicateKeyNode",updates:e})}})});var Su=f(()=>{});function Ut(e){return Object.prototype.hasOwnProperty.call(e,"prototype")}var Ko,Tr=f(()=>{Ko=class extends Error{node;constructor(o){super("no result"),this.node=o}}});var mj,Ou=f(()=>{$();qr();mj=l({is(e){return e.kind==="OnConflictNode"},create(){return l({kind:"OnConflictNode"})},cloneWith(e,o){return l({...e,...o})},cloneWithIndexWhere(e,o){return l({...e,indexWhere:e.indexWhere?ye.cloneWithOperation(e.indexWhere,"And",o):ye.create(o)})},cloneWithIndexOrWhere(e,o){return l({...e,indexWhere:e.indexWhere?ye.cloneWithOperation(e.indexWhere,"Or",o):ye.create(o)})},cloneWithUpdateWhere(e,o){return l({...e,updateWhere:e.updateWhere?ye.cloneWithOperation(e.updateWhere,"And",o):ye.create(o)})},cloneWithUpdateOrWhere(e,o){return l({...e,updateWhere:e.updateWhere?ye.cloneWithOperation(e.updateWhere,"Or",o):ye.create(o)})},cloneWithoutIndexWhere(e){return l({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return l({...e,updateWhere:void 0})}})});var Au=f(()=>{});var Eu,Da=f(()=>{$();Eu=l({is(e){return e.kind==="TopNode"},create(e,o){return l({kind:"TopNode",expression:e,modifiers:o})}})});function Jt(e,o){if(!uo(e)&&!lt(e))throw new Error(`Invalid top expression: ${e}`);if(!$o(o)&&!lw(o))throw new Error(`Invalid top modifiers: ${o}`);return Eu.create(e,o)}function lw(e){return e==="percent"||e==="with ties"||e==="percent with ties"}var Un=f(()=>{Da();$()});var Nj,qu=f(()=>{$();Nj=l({is(e){return e.kind==="OrActionNode"},create(e){return l({kind:"OrActionNode",action:e})}})});var Ru=f(()=>{});var Jn,La=f(()=>{Jn=class{numDeletedRows;constructor(o){this.numDeletedRows=o}}});var Qt,Mr=f(()=>{$();Qt=l({is(e){return e.kind==="LimitNode"},create(e){return l({kind:"LimitNode",limit:e})}})});var ae,za,ku=f(()=>{Qn();ho();Pr();Ao();$();Tr();La();Fn();Mr();Lt();mo();So();Un();za=class{#e;constructor(o){this.#e=l(o)}where(...o){return new ae({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,pe(o))})}whereRef(o,t,n){return new ae({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,xe(o,t,n))})}clearWhere(){return new ae({...this.#e,queryNode:P.cloneWithoutWhere(this.#e.queryNode)})}top(o,t){return new ae({...this.#e,queryNode:P.cloneWithTop(this.#e.queryNode,Jt(o,t))})}using(o){return new ae({...this.#e,queryNode:Wt.cloneWithUsing(this.#e.queryNode,gt(o))})}innerJoin(...o){return this.#o("InnerJoin",o)}leftJoin(...o){return this.#o("LeftJoin",o)}rightJoin(...o){return this.#o("RightJoin",o)}fullJoin(...o){return this.#o("FullJoin",o)}#o(o,t){return new ae({...this.#e,queryNode:P.cloneWithJoin(this.#e.queryNode,Gt(o,t))})}returning(o){return new ae({...this.#e,queryNode:P.cloneWithReturning(this.#e.queryNode,qo(o))})}returningAll(o){return new ae({...this.#e,queryNode:P.cloneWithReturning(this.#e.queryNode,fo(o))})}output(o){return new ae({...this.#e,queryNode:P.cloneWithOutput(this.#e.queryNode,qo(o))})}outputAll(o){return new ae({...this.#e,queryNode:P.cloneWithOutput(this.#e.queryNode,fo(o))})}clearReturning(){return new ae({...this.#e,queryNode:P.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new ae({...this.#e,queryNode:Wt.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...o){return new ae({...this.#e,queryNode:P.cloneWithOrderByItems(this.#e.queryNode,to(o))})}clearOrderBy(){return new ae({...this.#e,queryNode:P.cloneWithoutOrderBy(this.#e.queryNode)})}limit(o){return new ae({...this.#e,queryNode:Wt.cloneWithLimit(this.#e.queryNode,Qt.create(Z(o)))})}modifyEnd(o){return new ae({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,o.toOperationNode())})}$call(o){return o(this)}$if(o,t){return o?t(this):new ae({...this.#e})}$castTo(){return new ae(this.#e)}$narrowType(){return new ae(this.#e)}$assertType(){return new ae(this.#e)}withPlugin(o){return new ae({...this.#e,executor:this.#e.executor.withPlugin(o)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(o){let t=this.compile(),n=await this.#e.executor.executeQuery(t,o),{adapter:r}=this.#e.executor,a=t.query;return a.returning&&r.supportsReturning||a.output&&r.supportsOutput?n.rows:[new Jn(n.numAffectedRows??BigInt(0))]}async executeTakeFirst(o){let[t]=await this.execute(o);return t}async executeTakeFirstOrThrow(o){typeof o=="function"&&(o={errorConstructor:o});let t=await this.executeTakeFirst(o);if(t===void 0){let n=o?.errorConstructor??Ko;throw Ut(n)?new n(this.toOperationNode()):n(this.toOperationNode())}return t}async*stream(o){typeof o!="object"&&(o={chunkSize:o});let t=this.compile(),n=this.#e.executor.stream(t,o.chunkSize??100,o);for await(let r of n)yield*r.rows}async explain(o,t){return await new ae({...this.#e,queryNode:P.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};ae=za});var Gn,Fa=f(()=>{Gn=class{numUpdatedRows;numChangedRows;constructor(o,t){this.numUpdatedRows=o,this.numChangedRows=t}}});var se,Wa,Pu=f(()=>{Qn();ho();Pr();Ao();zn();Cu();$();Fa();Tr();mo();So();Mr();Un();Lt();Wa=class{#e;constructor(o){this.#e=l(o)}where(...o){return new se({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,pe(o))})}whereRef(o,t,n){return new se({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,xe(o,t,n))})}clearWhere(){return new se({...this.#e,queryNode:P.cloneWithoutWhere(this.#e.queryNode)})}top(o,t){return new se({...this.#e,queryNode:P.cloneWithTop(this.#e.queryNode,Jt(o,t))})}from(o){return new se({...this.#e,queryNode:Ft.cloneWithFromItems(this.#e.queryNode,gt(o))})}innerJoin(...o){return this.#o("InnerJoin",o)}leftJoin(...o){return this.#o("LeftJoin",o)}rightJoin(...o){return this.#o("RightJoin",o)}fullJoin(...o){return this.#o("FullJoin",o)}#o(o,t){return new se({...this.#e,queryNode:P.cloneWithJoin(this.#e.queryNode,Gt(o,t))})}orderBy(...o){return new se({...this.#e,queryNode:P.cloneWithOrderByItems(this.#e.queryNode,to(o))})}clearOrderBy(){return new se({...this.#e,queryNode:P.cloneWithoutOrderBy(this.#e.queryNode)})}limit(o){return new se({...this.#e,queryNode:Ft.cloneWithLimit(this.#e.queryNode,Qt.create(Z(o)))})}set(...o){return new se({...this.#e,queryNode:Ft.cloneWithUpdates(this.#e.queryNode,xu(...o))})}returning(o){return new se({...this.#e,queryNode:P.cloneWithReturning(this.#e.queryNode,qo(o))})}returningAll(o){return new se({...this.#e,queryNode:P.cloneWithReturning(this.#e.queryNode,fo(o))})}output(o){return new se({...this.#e,queryNode:P.cloneWithOutput(this.#e.queryNode,qo(o))})}outputAll(o){return new se({...this.#e,queryNode:P.cloneWithOutput(this.#e.queryNode,fo(o))})}modifyEnd(o){return new se({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,o.toOperationNode())})}clearReturning(){return new se({...this.#e,queryNode:P.cloneWithoutReturning(this.#e.queryNode)})}$call(o){return o(this)}$if(o,t){return o?t(this):new se({...this.#e})}$castTo(){return new se(this.#e)}$narrowType(){return new se(this.#e)}$assertType(){return new se(this.#e)}withPlugin(o){return new se({...this.#e,executor:this.#e.executor.withPlugin(o)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(o){let t=this.compile(),n=await this.#e.executor.executeQuery(t,o),{adapter:r}=this.#e.executor,a=t.query;return a.returning&&r.supportsReturning||a.output&&r.supportsOutput?n.rows:[new Gn(n.numAffectedRows??BigInt(0),n.numChangedRows)]}async executeTakeFirst(o){let[t]=await this.execute(o);return t}async executeTakeFirstOrThrow(o){typeof o=="function"&&(o={errorConstructor:o});let t=await this.executeTakeFirst(o);if(t===void 0){let n=o?.errorConstructor??Ko;throw Ut(n)?new n(this.toOperationNode()):n(this.toOperationNode())}return t}async*stream(o){typeof o!="object"&&(o={chunkSize:o});let t=this.compile(),n=this.#e.executor.stream(t,o.chunkSize??100,o);for await(let r of n)yield*r.rows}async explain(o,t){return await new se({...this.#e,queryNode:P.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};se=Wa});var sS,Tu=f(()=>{$();eo();$r();sS=l({is(e){return e.kind==="CommonTableExpressionNameNode"},create(e,o){return l({kind:"CommonTableExpressionNameNode",table:Uo.create(e),columns:o?l(o.map(ue.create)):void 0})}})});var uS,Mu=f(()=>{$();uS=l({is(e){return e.kind==="CommonTableExpressionNode"},create(e,o){return l({kind:"CommonTableExpressionNode",name:e,expression:o})},cloneWith(e,o){return l({...e,...o})}})});var mS,Iu=f(()=>{$();mS=l({is(e){return e.kind==="WithNode"},create(e,o){return l({kind:"WithNode",expressions:l([e]),...o})},cloneWithExpression(e,o){return l({...e,expressions:l([...e.expressions,o])})}})});function Hn(e){let o="";for(let t=0;t<e;++t)o+=uw();return o}function uw(){return Du[~~(Math.random()*Du.length)]}var Du,Ba=f(()=>{Du=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"]});function De(){return new Va}var Va,Xn=f(()=>{Ba();Va=class{#e;get queryId(){return this.#e===void 0&&(this.#e=Hn(8)),this.#e}}});var Lu=f(()=>{});var zu=f(()=>{});var _S,Fu=f(()=>{$();_S=l({is(e){return e.kind==="MatchedNode"},create(e,o=!1){return l({kind:"MatchedNode",not:e,bySource:o})}})});var Oe,Ir=f(()=>{Oe=class{#e;#o;#r;constructor(){this.#e=new Promise((o,t)=>{this.#r=t,this.#o=o})}get promise(){return this.#e}resolve=o=>{this.#o?.(o),this.#o=this.#r=void 0};reject=o=>{this.#r?.(o),this.#r=this.#o=void 0}}});async function Yn(e,o){let t=new Oe,n=new Oe;return e.provideConnection(async r=>(t.resolve(r),await n.promise),o).catch(r=>t.reject(r)),l({connection:await t.promise,release:n.resolve})}var Wu=f(()=>{Ir();$()});function Vu(e="ignore query",o,t){if(e!=="ignore query"){if(e==="cancel query"){let n=o.cancelQuery;return n||(t(),Bu(e,o.killSession?"kill session":void 0)),n.bind(o)}if(e==="kill session"){let n=o.killSession;return n||(t(),Bu(e,o.cancelQuery?"cancel query":void 0)),n.bind(o)}throw t(),new Error(`Unexpected \`inflightQueryAbortStrategy\`: "${e}"`)}}function Bu(e,o){throw new Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${e}". Use "ignore query"${o?` or "${o}"`:""} instead.`)}function bt(e,o,t){e?.aborted&&(t?.(),wt(e.reason,o))}function wt(e,o){throw dw(e,o),e}function vt(e){return o=>console.error(`\`${e}\` failed in the background after abortion: ${Dl(o)}`)}function dw(e,o){e!==null&&typeof e=="object"&&!Object.isFrozen(e)&&Object.defineProperty(e,"__kysely_timing__",{configurable:!0,enumerable:!1,value:o,writable:!1})}var go,Uu=f(()=>{$();go={}});var pw,Kn,Ju=f(()=>{$();Wu();Uu();Ir();pw=l([]),Kn=class{#e;constructor(o=pw){this.#e=o}get plugins(){return this.#e}transformQuery(o,t){for(let n of this.#e){let r=n.transformQuery({node:o,queryId:t});if(r.kind===o.kind)o=r;else throw new Error(["KyselyPlugin.transformQuery must return a node","of the same kind that was given to it.",`The plugin was given a ${o.kind}`,`but it returned a ${r.kind}`].join(" "))}return o}async executeQuery(o,t){let{inflightQueryAbortStrategy:n="ignore query",signal:r}=t||{};if(!r){let m=await this.provideConnection(async h=>await h.executeQuery(o),t);return await this.#o(m,o.queryId)}bt(r,"before query execution"),t=l({signal:r});let{connection:a,release:s}=await Yn(this,t),c=this.provideConnection.bind(this),{promise:d,resolve:u}=new Oe,p=()=>u(go);r.addEventListener("abort",p,{once:!0});try{bt(r,"before query execution",s);let m=Vu(n,a,s);if(m&&a.collectSessionInfo){bt(r,"before query execution",s);let w=a.collectSessionInfo();await Promise.race([d,w]).catch(j=>{throw s(),j})===go&&(w.catch(vt("collectSessionInfo")).finally(s),wt(r.reason,"before query execution"))}let h=a.executeQuery(o,t),b=await Promise.race([d,h]).catch(w=>{throw s(),w});b===go?(Promise.allSettled([h.catch(vt("query")),m?.(c).catch(vt("inflightQueryAbortHandler"))]).finally(s),wt(r.reason,"during query execution")):s();let y=this.#o(b,o.queryId,t),v=await Promise.race([d,y]);return v===go&&(y.catch(vt("plugins.transformResult")),wt(r.reason,"during result transformation")),v}finally{u(go),r.removeEventListener("abort",p)}}async*stream(o,t,n){let{signal:r}=n||{};if(!r){let{connection:b,release:y}=await Yn(this);try{for await(let v of b.streamQuery(o,t))yield await this.#o(v,o.queryId,n)}finally{y()}return}n=l({signal:r}),bt(r,"before connection acquisition");let{connection:a,release:s}=await Yn(this,n),{promise:c,resolve:d}=new Oe,u=()=>d(go);r.addEventListener("abort",u,{once:!0});let p,m;bt(r,"before query streaming",s);let{queryId:h}=o;try{for(p=a.streamQuery(o,t,n);;){bt(r,"during query streaming");let b=p.next(),y=await Promise.race([c,b]);if(y===go&&(m=b.catch(vt("iterator.next")),wt(r.reason,"during query streaming")),y.done)break;let v=this.#o(y.value,h,n),w=await Promise.race([c,v]);w===go&&(m=v.catch(vt("plugins.transformResult")),wt(r.reason,"during result transformation")),yield w}}finally{d(go),r.removeEventListener("abort",u);let b=(p?.return?.()||Promise.resolve()).finally(()=>m).finally(s);m||await b}}async#o(o,t,n){let{signal:r}=n||{};for(let a of this.#e)o=await a.transformResult(l({queryId:t,result:o,signal:r}));return o}}});var Ua,Zn,ei=f(()=>{Ju();Ua=class e extends Kn{get adapter(){throw new Error("this query cannot be compiled to SQL")}compileQuery(){throw new Error("this query cannot be compiled to SQL")}provideConnection(){throw new Error("this query cannot be executed")}withConnectionProvider(){throw new Error("this query cannot have a connection provider")}withPlugin(o){return new e([...this.plugins,o])}withPlugins(o){return new e([...this.plugins,...o])}withPluginAtFront(o){return new e([o,...this.plugins])}withoutPlugins(){return new e([])}},Zn=new Ua});var Qu=f(()=>{});var Gu=f(()=>{});var Hu=f(()=>{});function Xu(e,o){return new Wn({joinNode:Co.create(e,yt(o))})}function Yu(){return new Bn({overNode:Ar.create()})}var Ja=f(()=>{xr();Ln();ka();vu();ho()});function Gt(e,o){if(o.length===3)return fw(e,o[0],o[1],o[2]);if(o.length===2)return mw(e,o[0],o[1]);if(o.length===1)return hw(e,o[0]);throw new Error("not implemented")}function mw(e,o,t){return t(Xu(e,o)).toOperationNode()}function fw(e,o,t,n){return Co.createWithOn(e,yt(o),xe(t,"=",n))}function hw(e,o){return Co.create(e,yt(o))}var Qn=f(()=>{xr();mo();Ja();ho()});var Ku,Qa=f(()=>{$();Ku=l({is(e){return e.kind==="OffsetNode"},create(e){return l({kind:"OffsetNode",offset:e})}})});var Zu,Ga=f(()=>{$();Zu=l({is(e){return e.kind==="GroupByItemNode"},create(e){return l({kind:"GroupByItemNode",groupBy:e})}})});function ed(e){return e=$e(e)?e(Ro()):e,jo(e).map(Zu.create)}var od=f(()=>{Ga();Vt();$();Ie()});var td,Ha=f(()=>{$();td=l({is(e){return e.kind==="SetOperationNode"},create(e,o,t){return l({kind:"SetOperationNode",operator:e,expression:o,all:t})}})});function _t(e,o,t){return $e(o)&&(o=o(Xa())),ke(o)||(o=[o]),o.map(n=>td.create(e,Go(n),t))}var rd=f(()=>{Vt();Ha();$();ft()});var Q,Dr,Ya,Ka,Ht=f(()=>{xo();Jo();ne();Je();dt();Sr();mo();Q=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Dr(this,o)}or(...o){return new Ya(Ke.create(this.#e,pe(o)))}and(...o){return new Ka(Te.create(this.#e,pe(o)))}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},Dr=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Pe.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():M.create(this.#o))}},Ya=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Dr(this,o)}or(...o){return new e(Ke.create(this.#e,pe(o)))}$castTo(){return new e(this.#e)}toOperationNode(){return Yo.create(this.#e)}},Ka=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Dr(this,o)}and(...o){return new e(Te.create(this.#e,pe(o)))}$castTo(){return new e(this.#e)}toOperationNode(){return Yo.create(this.#e)}}});var nd,Za=f(()=>{$();Xo();nd=l({is(e){return e.kind==="FetchNode"},create(e,o){return{kind:"FetchNode",rowCount:Se.create(e),modifier:o}}})});function id(e,o){if(!uo(e)&&!lt(e))throw new Error(`Invalid fetch row count: ${e}`);if(!gw(o))throw new Error(`Invalid fetch modifier: ${o}`);return nd.create(e,o)}function gw(e){return e==="only"||e==="with ties"}var ad=f(()=>{Za();$()});function sd(e){return new oi(e)}var D,oi,es,os=f(()=>{xo();ca();Qn();ho();Pr();Ie();kr();Ao();Lt();Mr();Qa();$();od();Tr();ne();rd();mo();Ht();So();ad();Un();oi=class{#e;constructor(o){this.#e=l(o)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...o){return new D({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,pe(o))})}whereRef(o,t,n){return new D({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,xe(o,t,n))})}having(...o){return new D({...this.#e,queryNode:ee.cloneWithHaving(this.#e.queryNode,pe(o))})}havingRef(o,t,n){return new D({...this.#e,queryNode:ee.cloneWithHaving(this.#e.queryNode,xe(o,t,n))})}select(o){return new D({...this.#e,queryNode:ee.cloneWithSelections(this.#e.queryNode,qo(o))})}distinctOn(o){return new D({...this.#e,queryNode:ee.cloneWithDistinctOn(this.#e.queryNode,jo(o))})}modifyFront(o){return new D({...this.#e,queryNode:ee.cloneWithFrontModifier(this.#e.queryNode,po.createWithExpression(o.toOperationNode()))})}modifyEnd(o){return new D({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,po.createWithExpression(o.toOperationNode()))})}distinct(){return new D({...this.#e,queryNode:ee.cloneWithFrontModifier(this.#e.queryNode,po.create("Distinct"))})}forUpdate(o){return new D({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,po.create("ForUpdate",o?Nr(o).map(Ce):void 0))})}forShare(o){return new D({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,po.create("ForShare",o?Nr(o).map(Ce):void 0))})}forKeyShare(o){return new D({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,po.create("ForKeyShare",o?Nr(o).map(Ce):void 0))})}forNoKeyUpdate(o){return new D({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,po.create("ForNoKeyUpdate",o?Nr(o).map(Ce):void 0))})}skipLocked(){return new D({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,po.create("SkipLocked"))})}noWait(){return new D({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,po.create("NoWait"))})}selectAll(o){return new D({...this.#e,queryNode:ee.cloneWithSelections(this.#e.queryNode,fo(o))})}innerJoin(...o){return this.#o("InnerJoin",o)}leftJoin(...o){return this.#o("LeftJoin",o)}rightJoin(...o){return this.#o("RightJoin",o)}fullJoin(...o){return this.#o("FullJoin",o)}crossJoin(...o){return this.#o("CrossJoin",o)}innerJoinLateral(...o){return this.#o("LateralInnerJoin",o)}leftJoinLateral(...o){return this.#o("LateralLeftJoin",o)}crossJoinLateral(...o){return this.#o("LateralCrossJoin",o)}crossApply(...o){return this.#o("CrossApply",o)}outerApply(...o){return this.#o("OuterApply",o)}#o(o,t){return new D({...this.#e,queryNode:P.cloneWithJoin(this.#e.queryNode,Gt(o,t))})}orderBy(...o){return new D({...this.#e,queryNode:P.cloneWithOrderByItems(this.#e.queryNode,to(o))})}groupBy(o){return new D({...this.#e,queryNode:ee.cloneWithGroupByItems(this.#e.queryNode,ed(o))})}limit(o){return new D({...this.#e,queryNode:ee.cloneWithLimit(this.#e.queryNode,Qt.create(Z(o)))})}offset(o){return new D({...this.#e,queryNode:ee.cloneWithOffset(this.#e.queryNode,Ku.create(Z(o)))})}fetch(o,t="only"){return new D({...this.#e,queryNode:ee.cloneWithFetch(this.#e.queryNode,id(o,t))})}top(o,t){return new D({...this.#e,queryNode:P.cloneWithTop(this.#e.queryNode,Jt(o,t))})}union(o){return new D({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("union",o,!1))})}unionAll(o){return new D({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("union",o,!0))})}intersect(o){return new D({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("intersect",o,!1))})}intersectAll(o){return new D({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("intersect",o,!0))})}except(o){return new D({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("except",o,!1))})}exceptAll(o){return new D({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("except",o,!0))})}as(o){return new es(this,o)}clearSelect(){return new D({...this.#e,queryNode:ee.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new D({...this.#e,queryNode:P.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new D({...this.#e,queryNode:ee.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new D({...this.#e,queryNode:ee.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new D({...this.#e,queryNode:P.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new D({...this.#e,queryNode:ee.cloneWithoutGroupBy(this.#e.queryNode)})}$call(o){return o(this)}$if(o,t){return o?t(this):new D({...this.#e})}$castTo(){return new D(this.#e)}$narrowType(){return new D(this.#e)}$assertType(){return new D(this.#e)}$asTuple(){return new Q(this.toOperationNode())}$asScalar(){return new Q(this.toOperationNode())}withPlugin(o){return new D({...this.#e,executor:this.#e.executor.withPlugin(o)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(o){let t=this.compile();return(await this.#e.executor.executeQuery(t,o)).rows}async executeTakeFirst(o){let[t]=await this.execute(o);return t}async executeTakeFirstOrThrow(o){typeof o=="function"&&(o={errorConstructor:o});let t=await this.executeTakeFirst(o);if(t===void 0){let n=o?.errorConstructor??Ko;throw Ut(n)?new n(this.toOperationNode()):n(this.toOperationNode())}return t}async*stream(o){typeof o!="object"&&(o={chunkSize:o});let t=this.compile(),n=this.#e.executor.stream(t,o.chunkSize??100,o);for await(let r of n)yield*r.rows}async explain(o,t){return await new D({...this.#e,queryNode:P.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};D=oi;es=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return Pe.create(this.#e.toOperationNode(),M.create(this.#o))}}});var bo,ti=f(()=>{$();qr();Or();bo=l({is(e){return e.kind==="AggregateFunctionNode"},create(e,o=[]){return l({kind:"AggregateFunctionNode",func:e,aggregated:o})},cloneWithDistinct(e){return l({...e,distinct:!0})},cloneWithOrderBy(e,o,t=!1){let n=t?"withinGroup":"orderBy";return l({...e,[n]:e[n]?Oo.cloneWithItems(e[n],o):Oo.create(o)})},cloneWithFilter(e,o){return l({...e,filter:e.filter?ye.cloneWithOperation(e.filter,"And",o):ye.create(o)})},cloneWithOrFilter(e,o){return l({...e,filter:e.filter?ye.cloneWithOperation(e.filter,"Or",o):ye.create(o)})},cloneWithOver(e,o){return l({...e,over:o})}})});var ts,rs=f(()=>{$();ts=l({is(e){return e.kind==="FunctionNode"},create(e,o){return l({kind:"FunctionNode",func:e,arguments:o})}})});var Xt,ns,is=f(()=>{$();ti();xo();ne();Ja();mo();Lt();Ao();Xt=class e{#e;constructor(o){this.#e=l(o)}get expressionType(){}as(o){return new ns(this,o)}distinct(){return new e({...this.#e,aggregateFunctionNode:bo.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...o){return new e({...this.#e,aggregateFunctionNode:P.cloneWithOrderByItems(this.#e.aggregateFunctionNode,to(o))})}clearOrderBy(){return new e({...this.#e,aggregateFunctionNode:P.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...o){return new e({...this.#e,aggregateFunctionNode:bo.cloneWithOrderBy(this.#e.aggregateFunctionNode,to(o),!0)})}filterWhere(...o){return new e({...this.#e,aggregateFunctionNode:bo.cloneWithFilter(this.#e.aggregateFunctionNode,pe(o))})}filterWhereRef(o,t,n){return new e({...this.#e,aggregateFunctionNode:bo.cloneWithFilter(this.#e.aggregateFunctionNode,xe(o,t,n))})}over(o){let t=Yu();return new e({...this.#e,aggregateFunctionNode:bo.cloneWithOver(this.#e.aggregateFunctionNode,(o?o(t):t).toOperationNode())})}$call(o){return o(this)}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e.aggregateFunctionNode}},ns=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Pe.create(this.#e.toOperationNode(),M.create(this.#o))}}});function cd(){let e=(t,n)=>new Q(ts.create(t,jo(n??[]))),o=(t,n)=>new Xt({aggregateFunctionNode:bo.create(t,n?jo(n):void 0)});return Object.assign(e,{agg:o,avg(t){return o("avg",[t])},coalesce(...t){return e("coalesce",t)},count(t){return o("count",[t])},countAll(t){return new Xt({aggregateFunctionNode:bo.create("count",fo(t))})},max(t){return o("max",[t])},min(t){return o("min",[t])},sum(t){return o("sum",[t])},any(t){return e("any",[t])},jsonAgg(t){return new Xt({aggregateFunctionNode:bo.create("json_agg",[H(t)?Ce(t):t.toOperationNode()])})},toJson(t){return new Q(ts.create("to_json",[H(t)?Ce(t):t.toOperationNode()]))}})}var as=f(()=>{Ht();ti();rs();Ie();Pr();is();$();ho()});var ld,ss=f(()=>{$();ld=l({is(e){return e.kind==="UnaryOperationNode"},create(e,o){return l({kind:"UnaryOperationNode",operator:e,operand:o})}})});function ud(e,o){if(ou(e))return ld.create(Ze.create(e),fe(o));throw new Error(`invalid unary operator ${JSON.stringify(e)}`)}var dd=f(()=>{Mt();ss();Ie()});var Ae,ri=f(()=>{$();Rr();Ae=l({is(e){return e.kind==="CaseNode"},create(e){return l({kind:"CaseNode",value:e})},cloneWithWhen(e,o){return l({...e,when:l(e.when?[...e.when,o]:[o])})},cloneWithThen(e,o){return l({...e,when:e.when?l([...e.when.slice(0,-1),Eo.cloneWithResult(e.when[e.when.length-1],o)]):void 0})},cloneWith(e,o){return l({...e,...o})}})});var ni,Yt,ii,ai,cs=f(()=>{Ht();$();Ie();ri();Rr();mo();So();ni=class{#e;constructor(o){this.#e=l(o)}when(...o){return new Yt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Eo.create(pe(o)))})}whenRef(o,t,n){return new Yt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Eo.create(xe(o,t,n)))})}},Yt=class{#e;constructor(o){this.#e=l(o)}then(o){return new ii({...this.#e,node:Ae.cloneWithThen(this.#e.node,Mn(o)?jr(o):Z(o))})}thenRef(o){return new ii({...this.#e,node:Ae.cloneWithThen(this.#e.node,fe(o))})}},ii=class{#e;constructor(o){this.#e=l(o)}when(...o){return new Yt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Eo.create(pe(o)))})}whenRef(o,t,n){return new Yt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Eo.create(xe(o,t,n)))})}else(o){return new ai({...this.#e,node:Ae.cloneWith(this.#e.node,{else:Mn(o)?jr(o):Z(o)})})}elseRef(o){return new ai({...this.#e,node:Ae.cloneWith(this.#e.node,{else:fe(o)})})}end(){return new Q(Ae.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new Q(Ae.cloneWith(this.#e.node,{isStatement:!0}))}},ai=class{#e;constructor(o){this.#e=l(o)}end(){return new Q(Ae.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new Q(Ae.cloneWith(this.#e.node,{isStatement:!0}))}}});var ls,us=f(()=>{$();ls=l({is(e){return e.kind==="JSONPathLegNode"},create(e,o){return l({kind:"JSONPathLegNode",type:e,value:o})}})});var bw,Kt,si,ds,ps=f(()=>{xo();ne();kn();us();Cr();qn();Je();Xo();bw=/^#-\d+$/,Kt=class{#e;constructor(o){this.#e=o}at(o){if(typeof o!="number"&&typeof o!="string"||typeof o=="number"&&!Number.isInteger(o)||typeof o=="string"&&o!=="last"&&!bw.test(o))throw new Error(`Unexpected index value in .at(...): ${o}`);return this.#o("ArrayLocation",o)}key(o){return this.#o("Member",o)}#o(o,t){return zt.is(this.#e)?new si(zt.cloneWithTraversal(this.#e,Ho.is(this.#e.traversal)?Ho.cloneWithLeg(this.#e.traversal,ls.create(o,t)):Rn.cloneWithValue(this.#e.traversal,Se.createImmediate(t)))):new si(Ho.cloneWithLeg(this.#e,ls.create(o,t)))}},si=class e extends Kt{#e;constructor(o){super(o),this.#e=o}get expressionType(){}as(o){return new ds(this,o)}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},ds=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Pe.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():M.create(this.#o))}}});var ms,fs=f(()=>{$();ms=l({is(e){return e.kind==="TupleNode"},create(e){return l({kind:"TupleNode",values:l(e)})}})});function md(e){return ww[e]||vw.some(o=>o.test(e))}var ww,vw,pd,hs=f(()=>{$();ww=l({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),vw=l([/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^datetime2\(\d+\)$/,/^varbinary\(\d+\)$/]),pd=l({is(e){return e.kind==="DataTypeNode"},create(e){return l({kind:"DataTypeNode",dataType:e})}})});function fd(e){if(ie(e))return e.toOperationNode();if(md(e))return pd.create(e);throw new Error(`invalid column data type ${JSON.stringify(e)}`)}var hd=f(()=>{hs();Je()});var gd,gs=f(()=>{$();gd=l({is(e){return e.kind==="CastNode"},create(e,o){return l({kind:"CastNode",expression:e,dataType:o})}})});function Xa(e=Zn){function o(r,a,s){return new Q(In(r,a,s))}function t(r,a){return new Q(ud(r,a))}let n=Object.assign(o,{fn:void 0,eb:void 0,selectFrom(r){return sd({queryId:De(),executor:e,queryNode:ee.createFrom(gt(r))})},case(r){return new ni({node:Ae.create($o(r)?void 0:fe(r))})},ref(r,a){return $o(a)?new Q(Qe(r)):new Kt(iu(r,a))},jsonPath(){return new Kt(Ho.create())},table(r){return new Q(Ce(r))},val(r){return new Q(Z(r))},refTuple(...r){return new Q(ms.create(r.map(fe)))},tuple(...r){return new Q(ms.create(r.map(Z)))},lit(r){return new Q(jr(r))},unary:t,not(r){return t("not",r)},exists(r){return t("exists",r)},neg(r){return t("-",r)},between(r,a,s){return new Q(Qo.create(fe(r),Ze.create("between"),Te.create(Z(a),Z(s))))},betweenSymmetric(r,a,s){return new Q(Qo.create(fe(r),Ze.create("between symmetric"),Te.create(Z(a),Z(s))))},and(r){return ke(r)?new Q(Dn(r,"and")):new Q(ga(r,"and"))},or(r){return ke(r)?new Q(Dn(r,"or")):new Q(ga(r,"or"))},parens(...r){let a=pe(r);return Yo.is(a)?new Q(a):new Q(Yo.create(a))},cast(r,a){return new Q(gd.create(fe(r),fd(a)))}});return n.fn=cd(),n.eb=n,n}function Ro(e){return Xa()}var Vt=f(()=>{os();kr();ho();Xn();as();Ie();mo();Sr();Ht();Mt();dd();So();ei();cs();ri();$();ps();$n();Jo();fs();Cr();hd();gs()});function Go(e){if(ie(e))return e.toOperationNode();if($e(e))return e(Ro()).toOperationNode();throw new Error(`invalid expression: ${JSON.stringify(e)}`)}function Vn(e){if(ie(e))return e.toOperationNode();if($e(e))return e(Ro()).toOperationNode();throw new Error(`invalid aliased expression: ${JSON.stringify(e)}`)}function mt(e){return yn(e)||Jl(e)||$e(e)}var ft=f(()=>{_n();Je();Vt();$()});function bd(e){return je(e)&&ie(e)&&H(e.table)&&H(e.alias)}var bs=f(()=>{Je();$()});function gt(e){return ke(e)?e.map(o=>yt(o)):[yt(e)]}function yt(e){return H(e)?yw(e):bd(e)?e.toOperationNode():Vn(e)}function yw(e){let o=" as ";if(e.includes(o)){let[t,n]=e.split(o).map(wd);return Pe.create(Ce(t),M.create(n))}else return Ce(e)}function Ce(e){if(e.includes(".")){let[t,n]=e.split(".").map(wd);return Uo.createWithSchema(t,n)}else return Uo.create(e)}function wd(e){return e.trim()}var ho=f(()=>{$();xo();$r();ft();ne();bs()});var FE,vd=f(()=>{$();FE=l({is(e){return e.kind==="AddColumnNode"},create(e){return l({kind:"AddColumnNode",column:e})}})});var UE,yd=f(()=>{$();eo();UE=l({is(e){return e.kind==="ColumnDefinitionNode"},create(e,o){return l({kind:"ColumnDefinitionNode",column:ue.create(e),dataType:o})},cloneWithFrontModifier(e,o){return l({...e,frontModifiers:e.frontModifiers?l([...e.frontModifiers,o]):[o]})},cloneWithEndModifier(e,o){return l({...e,endModifiers:e.endModifiers?l([...e.endModifiers,o]):[o]})},cloneWith(e,o){return l({...e,...o})}})});var HE,_d=f(()=>{$();eo();HE=l({is(e){return e.kind==="DropColumnNode"},create(e){return l({kind:"DropColumnNode",column:ue.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var ZE,Nd=f(()=>{$();eo();ZE=l({is(e){return e.kind==="RenameColumnNode"},create(e,o){return l({kind:"RenameColumnNode",column:ue.create(e),renameTo:ue.create(o)})}})});var rq,$d=f(()=>{$();ne();rq=l({is(e){return e.kind==="CheckConstraintNode"},create(e,o){return l({kind:"CheckConstraintNode",expression:e,name:o?M.create(o):void 0})}})});var _w,aq,xd,ws=f(()=>{$();_w=l({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0}),aq=Object.keys(_w),xd=l({is(e){return e.kind==="ReferencesNode"},create(e,o){return l({kind:"ReferencesNode",table:e,columns:l([...o])})},cloneWithOnDelete(e,o){return l({...e,onDelete:o})},cloneWithOnUpdate(e,o){return l({...e,onUpdate:o})}})});var lq,Cd=f(()=>{$();lq=l({is(e){return e.kind==="GeneratedNode"},create(e){return l({kind:"GeneratedNode",...e})},createWithExpression(e){return l({kind:"GeneratedNode",always:!0,expression:e})},cloneWith(e,o){return l({...e,...o})}})});var pq,jd=f(()=>{$();pq=l({is(e){return e.kind==="DefaultValueNode"},create(e){return l({kind:"DefaultValueNode",defaultValue:e})}})});var Sd=f(()=>{});var gq,Od=f(()=>{$();gq=l({is(e){return e.kind==="ModifyColumnNode"},create(e){return l({kind:"ModifyColumnNode",column:e})}})});var _q,Ad=f(()=>{$();ne();ws();_q=l({is(e){return e.kind==="ForeignKeyConstraintNode"},create(e,o,t,n){return l({kind:"ForeignKeyConstraintNode",columns:e,references:xd.create(o,t),name:n?M.create(n):void 0})},cloneWith(e,o){return l({...e,...o})}})});var Ed=f(()=>{});var Cq,qd=f(()=>{$();Cq=l({is(e){return e.kind==="AddConstraintNode"},create(e){return l({kind:"AddConstraintNode",constraint:e})}})});var qq,Rd=f(()=>{pa();$();eo();ne();qq=l({is(e){return e.kind==="UniqueConstraintNode"},create(e,o,t){return H(e.at(0))&&(Dt("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),e=e.map(ue.create)),l({kind:"UniqueConstraintNode",columns:l(e),name:o?M.create(o):void 0,nullsNotDistinct:t})},cloneWith(e,o){return l({...e,...o})}})});var Tq,kd=f(()=>{$();ne();Tq=l({is(e){return e.kind==="DropConstraintNode"},create(e){return l({kind:"DropConstraintNode",constraintName:M.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var Lq,Pd=f(()=>{$();eo();Lq=l({is(e){return e.kind==="AlterColumnNode"},create(e,o,t){return l({kind:"AlterColumnNode",column:ue.create(e),[o]:t})}})});var Td=f(()=>{});var Uq,Md=f(()=>{$();eo();ne();Uq=l({is(e){return e.kind==="PrimaryKeyConstraintNode"},create(e,o){return l({kind:"PrimaryKeyConstraintNode",columns:l(e.map(ue.create)),name:o?M.create(o):void 0})},cloneWith(e,o){return l({...e,...o})}})});var Hq,Id=f(()=>{$();ne();Hq=l({is(e){return e.kind==="AddIndexNode"},create(e){return l({kind:"AddIndexNode",name:M.create(e)})},cloneWith(e,o){return l({...e,...o})},cloneWithColumns(e,o){return l({...e,columns:[...e.columns||[],...o]})}})});var Zq,Dd=f(()=>{$();ne();Zq=l({is(e){return e.kind==="RenameConstraintNode"},create(e,o){return l({kind:"RenameConstraintNode",oldName:M.create(e),newName:M.create(o)})}})});var Ld=f(()=>{});var zd=f(()=>{});var Fd=f(()=>{});var Wd=f(()=>{});var Bd=f(()=>{});var Vd=f(()=>{});var Ud=f(()=>{});var Jd=f(()=>{});var dR,Qd=f(()=>{$();ut();dR=l({is(e){return e.kind==="CreateViewNode"},create(e){return l({kind:"CreateViewNode",name:Ye.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var Gd=f(()=>{});var gR,Hd=f(()=>{$();ut();gR=l({is(e){return e.kind==="DropViewNode"},create(e){return l({kind:"DropViewNode",name:Ye.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var Xd=f(()=>{});var NR,Yd=f(()=>{$();Tn();Xo();NR=l({is(e){return e.kind==="CreateTypeNode"},create(e){return l({kind:"CreateTypeNode",name:e})},cloneWithEnum(e,o){return l({...e,enum:Pn.create(o.map(Se.createImmediate))})}})});var Kd=f(()=>{});var jR,Zd=f(()=>{$();jR=l({is(e){return e.kind==="DropTypeNode"},create(e){return Array.isArray(e)||(e=[e]),l({kind:"DropTypeNode",name:e[0],additionalNames:e.slice(1)})},cloneWith(e,o){return l({...e,...o})}})});var ep=f(()=>{});var qR,op=f(()=>{$();ut();qR=l({is(e){return e.kind==="RefreshMaterializedViewNode"},create(e){return l({kind:"RefreshMaterializedViewNode",name:Ye.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var tp=f(()=>{});var TR,rp=f(()=>{$();TR=l({is(e){return e.kind==="AlterTypeNode"},create(e){return l({kind:"AlterTypeNode",name:e})},cloneWith(e,o){return l({...e,...o})}})});var DR,np=f(()=>{$();DR=l({is(e){return e.kind==="AddValueNode"},create(e){return l({kind:"AddValueNode",value:e})},cloneWith(e,o){return l({...e,...o})}})});var ip=f(()=>{});var WR,ap=f(()=>{$();WR=l({is(e){return e.kind==="RenameValueNode"},create(e,o){return l({kind:"RenameValueNode",oldValue:e,newValue:o})}})});var sp=f(()=>{});var cp=f(()=>{});var lp=f(()=>{});var up=f(()=>{});var dp=f(()=>{});var pp=f(()=>{});var Nw,YR,mp=f(()=>{$();Nw=["query","error"],YR=l(Nw)});var fp=f(()=>{});var hp=f(()=>{Symbol.asyncDispose??=Symbol("Symbol.asyncDispose")});function ko(e){return new vs(e)}var vs,ys,_s=f(()=>{xo();$();ei();ne();Je();vs=class e{#e;constructor(o){this.#e=l(o)}get expressionType(){}get isRawBuilder(){return!0}as(o){return new ys(this,o)}$castTo(){return new e({...this.#e})}$notNull(){return new e(this.#e)}withPlugin(o){return new e({...this.#e,plugins:this.#e.plugins!==void 0?l([...this.#e.plugins,o]):l([o])})}toOperationNode(){return this.#r(this.#o())}compile(o){return this.#t(this.#o(o))}async execute(o,t){let n=this.#o(o);return n.executeQuery(this.#t(n),t)}#o(o){let t=o!==void 0?o.getExecutor():Zn;return this.#e.plugins!==void 0?t.withPlugins(this.#e.plugins):t}#r(o){return o.transformQuery(this.#e.rawNode,this.#e.queryId)}#t(o){return o.compileQuery(this.#r(o),this.#e.queryId)}};ys=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}get rawBuilder(){return this.#e}toOperationNode(){return Pe.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():M.create(this.#o))}}});function gp(e){return ie(e)?e.toOperationNode():Z(e)}var A,bp=f(()=>{ne();Je();pt();Xo();Ie();ho();So();Xn();_s();A=Object.assign((e,...o)=>ko({queryId:De(),rawNode:de.create(e,o?.map(gp)??[])}),{ref(e){return ko({queryId:De(),rawNode:de.createWithChild(Qe(e))})},val(e){return ko({queryId:De(),rawNode:de.createWithChild(Z(e))})},table(e){return ko({queryId:De(),rawNode:de.createWithChild(Ce(e))})},id(...e){let o=new Array(e.length+1).fill(".");return o[0]="",o[o.length-1]="",ko({queryId:De(),rawNode:de.create(o,e.map(M.create))})},lit(e){return ko({queryId:De(),rawNode:de.createWithChild(Se.createImmediate(e))})},raw(e){return ko({queryId:De(),rawNode:de.createWithSql(e)})},join(e,o=A`, `){let t=new Array(Math.max(2*e.length-1,0)),n=o.toOperationNode();for(let r=0;r<e.length;++r)t[2*r]=gp(e[r]),r!==e.length-1&&(t[2*r+1]=n);return ko({queryId:De(),rawNode:de.createWithChildren(t)})}})});var wp=f(()=>{});var vk,yk,_k,Ns=f(()=>{$();vk=l({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),yk=l({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),_k=l({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"})});var Nt,Lr=f(()=>{pt();$();Xn();Nt=l({raw(e,o=[]){return l({sql:e,query:de.createWithSql(e),parameters:l(o),queryId:De()})}})});var vp=f(()=>{});var yp=f(()=>{});var _p=f(()=>{});var Np=f(()=>{});var $p=f(()=>{});var xp=f(()=>{});var Cp=f(()=>{});function Zo(e,o){if($w(e)&&o.stack){let t=o.stack.split(`
|
|
3
|
+
var Fb=Object.defineProperty;var f=(e,o,t)=>()=>{if(t)throw t[0];try{return e&&(o=e(e=0)),o}catch(n){throw t=[n],n}};var bl=(e,o)=>{for(var t in o)Fb(e,t,{get:o[t],enumerable:!0})};import{AsyncLocalStorage as Vb}from"node:async_hooks";import{readdirSync as Jb}from"node:fs";import{createRequire as Qb}from"node:module";import{fileURLToPath as Gb}from"node:url";function so(e,o){let n=vl[e]?.[o];if(n!==void 0)return n;for(let r of Yb[e]??[]){let a=r.regex.exec(o);if(a)return r.traduccion.replace(/%\{([\w]+)\}/g,(s,c)=>{let d=r.nombres.indexOf(c);return d<0?s:a[d+1]})}return o}var Hb,Xb,vl,Yb,Kb,Do,fn=f(()=>{Hb=Jb(new URL("./locales/",import.meta.url)).filter(e=>/\.(?:ts|js)$/.test(e)&&!e.endsWith(".d.ts")),Xb=Qb(import.meta.url),vl=Object.fromEntries(Hb.map(e=>[e.replace(/\.(?:ts|js)$/,""),Xb(Gb(new URL(`./locales/${e}`,import.meta.url))).default])),Yb=Object.fromEntries(Object.entries(vl).map(([e,o])=>[e,Object.entries(o).filter(([t])=>t.includes("%{")).map(([t,n])=>{let r=[],a=0,s="";for(let c of t.matchAll(/%\{([\w]+)\}/g)){let d=c.index;s+=t.slice(a,d).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"([\\s\\S]*?)",r.push(c[1]),a=d+c[0].length}return s+=t.slice(a).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),{regex:new RegExp(`^${s}$`),nombres:r,traduccion:n,especificidad:t.replace(/%\{[\w]+\}/g,"").length}}).sort((t,n)=>n.especificidad-t.especificidad)])),Kb=new Vb,Do=()=>Kb.getStore()?.idioma??"es"});var z,i,R=f(()=>{fn();z=class extends Error{constructor(t,n,r,a=!0,s){super(a?so(Do(),r):r);this.estado=t;this.codigo=n;this.datos=s}estado;codigo;datos},i=(e,o=!0)=>new z(400,"peticion_invalida",e,o)});import{inflateRawSync as Zb}from"node:zlib";function ew(e){let o=Buffer.from(e.buffer,e.byteOffset,e.byteLength);if(o.length>na)throw i("El paquete pasa de 5 MB.");if(o.length<22||o.readUInt32LE(0)!==67324752)throw i("El paquete no es un .zip.");let t=-1;for(let d=o.length-22;d>=Math.max(0,o.length-22-65535);d--)if(o.readUInt32LE(d)===101010256&&d+22+o.readUInt16LE(d+20)===o.length){t=d;break}if(t<0)throw i("El .zip est\xE1 da\xF1ado (sin directorio).");let n=o.readUInt16LE(t+10),r=o.readUInt32LE(t+16),a=o.readUInt32LE(t+12);if(o.readUInt16LE(t+4)!==0||o.readUInt16LE(t+6)!==0||o.readUInt16LE(t+8)!==n||t+22+o.readUInt16LE(t+20)!==o.length||r+a!==t)throw i("El .zip est\xE1 da\xF1ado (directorio inv\xE1lido).");if(n>_l)throw i(`El paquete trae m\xE1s de ${_l} ficheros.`);let s=new Map,c=r;for(let d=0;d<n;d++){if(c+46>t||o.readUInt32LE(c)!==33639248)throw i("El .zip est\xE1 da\xF1ado.");let u=o.readUInt16LE(c+8),p=o.readUInt16LE(c+10),m=o.readUInt32LE(c+20),h=o.readUInt32LE(c+24),b=o.readUInt16LE(c+28),y=o.readUInt16LE(c+30),v=o.readUInt16LE(c+32);if((o.readUInt32LE(c+38)>>>16&61440)===40960)throw i("El paquete no admite enlaces simb\xF3licos.");let N=o.readUInt32LE(c+42);if(c+46+b+y+v>t)throw i("El .zip est\xE1 da\xF1ado.");let j=o.subarray(c+46,c+46+b),S=j.toString("utf8");if(c+=46+b+y+v,!S.endsWith("/")){if(!S||S.includes("\\")||S.startsWith("/")||S.split("/").some(q=>q===".."||q==="."||q==="")||/[\x00-\x1f]/.test(S))throw i(`El paquete trae un nombre de fichero no admitido (\xAB${S.slice(0,80)}\xBB).`);if(s.has(S))throw i(`El paquete trae \xAB${S.slice(0,80)}\xBB dos veces.`);if(u&1)throw i("El paquete no puede ir cifrado.");s.set(S,()=>{if(h>yl)throw i(`\xAB${S}\xBB pasa de 2 MB.`);if(N+30>o.length||o.readUInt32LE(N)!==67324752)throw i("El .zip est\xE1 da\xF1ado.");let q=o.readUInt16LE(N+26),F=N+30+q+o.readUInt16LE(N+28);if(F>r||F+m>r||o.readUInt16LE(N+6)!==u||o.readUInt16LE(N+8)!==p||!o.subarray(N+30,N+30+q).equals(j))throw i("El .zip est\xE1 da\xF1ado.");let I=o.subarray(F,F+m);if(I.length!==m)throw i("El .zip est\xE1 da\xF1ado.");let _;if(p===0)_=I;else if(p===8)try{_=Zb(I,{maxOutputLength:yl})}catch{throw i(`\xAB${S}\xBB no se puede descomprimir (o pasa de 2 MB).`)}else throw i(`\xAB${S}\xBB va comprimido de una forma no admitida (solo \xABstore\xBB y \xABdeflate\xBB).`);if(_.length!==h)throw i("El .zip est\xE1 da\xF1ado.");return _})}}if(c!==t)throw i("El .zip est\xE1 da\xF1ado (directorio inv\xE1lido).");return s}function zo(e){let o=new Map,t=0;for(let[n,r]of ew(e)){let a=r();if(t+=a.length,t>ow)throw i("Los ficheros del paquete pasan de 10 MB al descomprimirlos.");o.set(n,a)}return o}var na,yl,_l,ow,yr=f(()=>{R();na=5*1024*1024,yl=2*1024*1024,_l=500;ow=10*1024*1024});function Nl(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>20)throw i("La app admite hasta 20 conexiones.");let o=new Set;return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t)||typeof t.clave!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(t.clave)||o.has(t.clave)||typeof t.base!="string"||t.base.length>1e3||typeof t.operacion!="string"||!/^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$/.test(t.operacion))throw i("Declaraci\xF3n de conexi\xF3n de app no v\xE1lida.");let n=["clave","base","operacion","tipo",...t.tipo==="api_key"?["lugar","nombre"]:[]];if(Object.keys(t).some(c=>!n.includes(c)))throw i("La declaraci\xF3n de conexi\xF3n no admite campos adicionales.");let r;try{r=new URL(t.base)}catch{throw i("La conexi\xF3n necesita una base HTTPS.")}if(!(process.env.NODE_ENV==="test"&&process.env.CRM_CONEXIONES_PRUEBA_LOCAL==="1"&&r.protocol==="http:"&&r.hostname==="127.0.0.1")&&(r.protocol!=="https:"||r.port)||r.username||r.password||r.search||r.hash)throw i("La conexi\xF3n necesita una base HTTPS sin credenciales, query ni fragmento.");o.add(t.clave);let s={clave:t.clave,base:r.href,operacion:t.operacion};if(t.tipo==="api_key"&&(t.lugar==="cabecera"||t.lugar==="query")&&typeof t.nombre=="string"&&/^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$/.test(t.nombre))return{...s,tipo:t.tipo,lugar:t.lugar,nombre:t.nombre};if(t.tipo==="bearer"||t.tipo==="basic"||t.tipo==="oauth2")return{...s,tipo:t.tipo};throw i("Autenticaci\xF3n de conexi\xF3n de app no v\xE1lida.")})}var $l=f(()=>{R()});var Y,tw,xl,Cl=f(()=>{Y={id:"Id del registro."},tw=[{nombre:"contacto.creado",descripcion:"Se ha creado un contacto.",datos:Y},{nombre:"contacto.actualizado",descripcion:"Han cambiado datos de un contacto.",datos:{...Y,campos:"Qu\xE9 columnas (si se sabe).",lote:"La acci\xF3n, si fue en lote."}},{nombre:"contacto.borrado",descripcion:"Se ha borrado un contacto (tambi\xE9n al fusionarlo en otro).",datos:{...Y,fusionado_en:"Si se fusion\xF3: en cu\xE1l."}},{nombre:"empresa.creada",descripcion:"Se ha creado una empresa.",datos:Y},{nombre:"empresa.actualizada",descripcion:"Han cambiado datos de una empresa.",datos:{...Y,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"empresa.borrada",descripcion:"Se ha borrado una empresa.",datos:Y},{nombre:"contacto.fusionado",descripcion:"Un contacto se ha fusionado en otro: quien guarde su id, que lo cambie por el que queda.",datos:{...Y,se_va:"El que se fue.",queda:"El que queda (= id)."}},{nombre:"empresa.fusionada",descripcion:"Una empresa se ha fusionado en otra: quien guarde su id, que lo cambie por la que queda.",datos:{...Y,se_va:"La que se fue.",queda:"La que queda (= id)."}},{nombre:"oportunidad.creada",descripcion:"Se ha creado una oportunidad.",datos:Y},{nombre:"oportunidad.actualizada",descripcion:"Han cambiado datos de una oportunidad (no la etapa).",datos:{...Y,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"oportunidad.etapa_cambiada",descripcion:"Una oportunidad ha cambiado de etapa.",datos:{...Y,de:"Etapa anterior.",a:"Etapa nueva."}},{nombre:"oportunidad.ganada",descripcion:"Una oportunidad ha pasado a ganada (adem\xE1s de etapa_cambiada).",datos:{...Y,de:"Etapa anterior.",a:"won",origen:"\xABcrm\xBB (una persona o la API) o \xABfacturacion\xBB (su presupuesto principal se acept\xF3).",quien:"Nombre de quien la movi\xF3 (persona del espacio o due\xF1o de la clave), si se sabe."}},{nombre:"oportunidad.perdida",descripcion:"Una oportunidad ha pasado a perdida (adem\xE1s de etapa_cambiada).",datos:{...Y,de:"Etapa anterior.",a:"lost",origen:"\xABcrm\xBB o \xABfacturacion\xBB (su presupuesto principal se rechaz\xF3).",motivo:"El motivo de p\xE9rdida, si se dio.",quien:"Nombre de quien la movi\xF3 (persona del espacio o due\xF1o de la clave), si se sabe."}},{nombre:"oportunidad.archivada",descripcion:"Una oportunidad ha salido del embudo al archivo.",datos:Y},{nombre:"oportunidad.borrada",descripcion:"Se ha borrado una oportunidad.",datos:Y},{nombre:"nota.creada",descripcion:"Nueva nota en el hilo de un contacto o de una oportunidad.",datos:{...Y,contacto_id:"Si es de un contacto.",oportunidad_id:"Si es de una oportunidad."}},{nombre:"nota.actualizada",descripcion:"Se ha editado una nota.",datos:Y},{nombre:"nota.borrada",descripcion:"Se ha borrado una nota.",datos:Y},{nombre:"nota.mencion",descripcion:"Una nota menciona (@) a miembros del espacio: al crearla, o al editarla con menciones nuevas. Solo miembros activos (la base filtra el resto).",datos:{...Y,contacto_id:"Si es de un contacto.",oportunidad_id:"Si es de una oportunidad.",mencionados:"Ids de los miembros mencionados por primera vez en esta nota (miembros.listar)."}},{nombre:"tarea.creada",descripcion:"Se ha creado una tarea.",datos:{...Y,contacto_id:"Su contacto."}},{nombre:"tarea.actualizada",descripcion:"Ha cambiado una tarea (o se ha reabierto).",datos:{...Y,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"tarea.completada",descripcion:"Se ha completado una tarea.",datos:Y},{nombre:"tarea.borrada",descripcion:"Se ha borrado una tarea.",datos:Y},{nombre:"contacto.etiquetado",descripcion:"Una Persona ha recibido una etiqueta (una vez por etiqueta a\xF1adida, venga de donde venga).",datos:{...Y,etiqueta:"El nombre de la etiqueta.",etiqueta_id:"Su id."}},{nombre:"lead.recibido",descripcion:"Ha entrado un lead desde una web (leads.crear): el id es el de su Persona.",datos:{...Y,origen:"De d\xF3nde viene (\xABlanding:<slug>\xBB).",oportunidad_id:"La oportunidad que abri\xF3."}},{nombre:"formulario.respuesta",descripcion:"Alguien ha respondido un formulario p\xFAblico del CRM.",datos:{...Y,formulario_id:"El formulario.",contacto_id:"Su contacto.",oportunidad_id:"La oportunidad, si el formulario la abre."}},{nombre:"registro.creado",descripcion:"Se ha creado un registro de un m\xF3dulo del cliente.",datos:{...Y,modulo:"La clave del m\xF3dulo (mod_<clave> en la API v1).",origen:"\xABformulario\xBB o \xABimportacion\xBB, si no vino de la interfaz o la API."}},{nombre:"registro.actualizado",descripcion:"Han cambiado datos de un registro de un m\xF3dulo.",datos:{...Y,modulo:"La clave del m\xF3dulo.",campos:"Qu\xE9 campos."}},{nombre:"registro.borrado",descripcion:"Se ha borrado un registro de un m\xF3dulo.",datos:{...Y,modulo:"La clave del m\xF3dulo."}}],xl=tw.map(e=>e.nombre)});function nw(e,[o,t]){let n=new Set;for(let r of e.split(",")){let a=/^(\*|(\d{1,2})(?:-(\d{1,2}))?)(?:\/(\d{1,2}))?$/.exec(r);if(!a)return null;let s=a[1]==="*"?o:Number(a[2]),c=a[1]==="*"?t:a[3]!==void 0?Number(a[3]):a[4]!==void 0?t:s,d=a[4]!==void 0?Number(a[4]):1;if(s<o||c>t||s>c||d<1)return null;for(let u=s;u<=c;u+=d)n.add(u)}return n}function jl(e){let o=e.trim().split(/\s+/);if(o.length!==5)return null;let t=o.map((r,a)=>nw(r,rw[a]));if(t.some(r=>!r))return null;let n=new Set([...t[4]].map(r=>r===7?0:r));return{minutos:t[0],horas:t[1],dias:t[2],meses:t[3],semana:n,diaLibre:o[2]==="*",semanaLibre:o[4]==="*"}}function Sl(e){let o=[...e.horas].sort((a,s)=>a-s),t=[...e.minutos].sort((a,s)=>a-s),n=o.flatMap(a=>t.map(s=>a*60+s));if(n.length<=1)return 1440;let r=1440-n.at(-1)+n[0];for(let a=1;a<n.length;a++)r=Math.min(r,n[a]-n[a-1]);return r}var rw,Y0,Ol=f(()=>{rw=[[0,59],[0,23],[1,31],[1,12],[0,7]];Y0=new Intl.DateTimeFormat("en-GB",{timeZone:"Europe/Madrid",hourCycle:"h23",minute:"numeric",hour:"numeric",day:"numeric",month:"numeric",weekday:"short"})});function Al(e){let o=(t,n)=>Number.isInteger(t)?Math.min(n.max,Math.max(n.min,t)):n.defecto;return{ms:o(e?.tope?.ms,W.ms),memoriaMb:o(e?.tope?.memoria_mb,W.memoriaMb)}}var W,_r=f(()=>{W={simultaneas:2,ms:{defecto:5e3,min:100,max:3e4},memoriaMb:{defecto:64,min:16,max:256},pilaBytes:1048576,margenMs:2e3,llamadasApi:100,llamadasRed:10,llamadaCaracteres:327680,llamadasEnVuelo:8,codigoBytes:262144,entradaBytes:65536,salidaBytes:65536,red:{cuerpoBytes:262144,respuestaBytes:1048576,plazoMs:5e3},webhookBytes:65536,cronMinutos:15}});function El(e){if(!e.startsWith("*."))return!1;let o=e.slice(2).toLowerCase();if(aw.has(o)||sw.test(o))return!0;let t=o.split(".");return t.length===2&&t[1].length===2&&iw.has(t[0])}var iw,aw,sw,Rl=f(()=>{iw=new Set(["co","com","net","org","gov","gob","edu","ac","nom","mil","ltd","plc","me","or","ne","go","info","biz","int"]),aw=new Set(["github.io","gitlab.io","pages.dev","workers.dev","vercel.app","netlify.app","web.app","firebaseapp.com","herokuapp.com","appspot.com","azurewebsites.net","cloudfront.net","amazonaws.com","blogspot.com","wordpress.com","glitch.me","onrender.com","fly.dev","repl.co","ngrok.io","ngrok-free.app","trycloudflare.com","r2.dev","supabase.co","myshopify.com","firebaseio.com","duckdns.org","no-ip.org","ddns.net","netlify.com","blob.core.windows.net","web.core.windows.net"]),sw=/^(s3([.-][a-z0-9-]+)?\.amazonaws\.com|blogspot\.[a-z]{2,3}(\.[a-z]{2})?)$/});function ca(e,o=0){if(o>20)throw i("El manifiesto anida demasiado.");if(Array.isArray(e))return e.forEach(t=>ca(t,o+1));if(me(e))for(let t of Object.keys(e)){if(cw.has(t))throw i(`Clave no admitida \xAB${t}\xBB.`);ca(e[t],o+1)}}function Ne(e,o,t){for(let n of Object.keys(e))if(!o.includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`)}function hw(e,o,t={}){return mw.test(e.replace(fw,""))?`\xAB${o}\xBB: lleva caracteres de control, invisibles o de direcci\xF3n del texto.`:t.reservar&&!t.firmada&&ua(e)?`\xAB${o}\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.`:null}function G(e,o,t,n=!0){if(e!=null&&typeof e!="string")throw i(`\xAB${o}\xBB: texto de hasta ${t} caracteres.`);let r=typeof e=="string"?e.trim():"";if(r===""){if(n)throw i(`Falta \xAB${o}\xBB.`);return""}if(r.length>t)throw i(`\xAB${o}\xBB: texto de hasta ${t} caracteres.`);let a=hw(r,o);if(a)throw i(a);return r}function ww(e){return e.normalize("NFKC").replace(new RegExp("(\\p{Ll})(?=\\p{Lu})","gu"),"$1 ").replace(new RegExp("(\\p{Lu})(?=\\p{Lu}\\p{Ll})","gu"),"$1 ").split(/[^\p{L}\p{N}\p{M}]+/u).map(la).filter(Boolean)}function Ul(e,o,t){let n=K(e,o,zl,t);if(El(n))throw i(`\xAB${o}\xBB: \xAB${n}\xBB abarca dominios de cualquiera; pon el dominio de tu servicio (\xAB*.api.ejemplo.co.uk\xBB o \xABapi.ejemplo.co.uk\xBB).`);return n}function K(e,o,t,n){if(typeof e!="string"||!t.test(e))throw i(`\xAB${o}\xBB: ${n}.`);return e}function ce(e,o,t){if(e==null)return[];if(!Array.isArray(e))throw i(`\xAB${o}\xBB: una lista.`);if(e.length>t)throw i(`\xAB${o}\xBB: como mucho ${t}.`);return e}function we(e,o,t){let n=new Set;for(let r of e){let a=o(r);if(n.has(a))throw i(`\xAB${t}\xBB: \xAB${a}\xBB est\xE1 repetido.`);n.add(a)}return e}function aa(e,o){let t=G(e,o,500),n;try{n=new URL(t)}catch{throw i(`\xAB${o}\xBB: una direcci\xF3n https.`)}if(n.protocol!=="https:"||n.username||n.password||!zl.test(n.hostname)||n.hostname.startsWith("*."))throw i(`\xAB${o}\xBB: una direcci\xF3n https con nombre de dominio (ni IP ni localhost).`);return n.toString()}function vw(e){let[o,t]=e.split(".");return la(o??"")==="forgenex"||la(t??"")==="forgenex"}function co(e){if(Object.hasOwn(Bo,e))return e;let o=e.startsWith("mod_")?e.slice(4):e;return dw.test(o)?`mod_${o}`:null}function Il(e,o,t){if(!me(e))throw i(`\xAB${o}\xBB: un nombre de contrato, o { contrato, modulos, eventos, herramientas }.`);Ne(e,["contrato","titulo","modulos","eventos","herramientas",...t],o);let n=K(e.contrato,`${o}.contrato`,sa,"un nombre de contrato (\xABtaller.vehiculos\xBB)"),r=e.titulo===void 0?null:G(e.titulo,`${o}.titulo`,80),a={};if(e.modulos!==void 0){if(!me(e.modulos))throw i(`\xAB${o}.modulos\xBB: un objeto { m\xF3dulo: [operaciones] }.`);let d=Object.entries(e.modulos);if(d.length>20)throw i(`\xAB${o}.modulos\xBB: como mucho 20 m\xF3dulos.`);for(let[u,p]of d){let m=co(u);if(!m)throw i(`\xAB${o}.modulos\xBB: \xAB${u.slice(0,60)}\xBB no es un m\xF3dulo (min\xFAsculas, n\xFAmeros y _).`);if(a[m])throw i(`\xAB${o}.modulos\xBB: \xAB${u}\xBB est\xE1 repetido.`);let h=ce(p,`${o}.modulos.${u}`,4);if(!h.length||h.some(y=>typeof y!="string"||!Wo.includes(y)))throw i(`\xAB${o}.modulos.${u}\xBB: operaciones ${Wo.join(", ")}.`);let b=new Set(h);if((b.has("editar")||b.has("borrar"))&&!b.has("ver"))throw i(`\xAB${o}.modulos.${u}\xBB: para \xABeditar\xBB o \xABborrar\xBB hace falta \xABver\xBB.`);a[m]=Wo.filter(y=>b.has(y))}}let s=we(ce(e.eventos,`${o}.eventos`,3).map((d,u)=>{if(typeof d!="string"||!ql.includes(d))throw i(`\xAB${o}.eventos[${u}]\xBB: ${ql.join(", ")} (los de los registros de sus m\xF3dulos).`);return d}),d=>d,`${o}.eventos`).sort();if(s.length&&!Object.values(a).some(d=>d.includes("ver")))throw i(`\xAB${o}.eventos\xBB: los eventos son de sus m\xF3dulos; hace falta \xABver\xBB de alguno en \xAB${o}.modulos\xBB.`);let c=we(ce(e.herramientas,`${o}.herramientas`,20).map((d,u)=>K(d,`${o}.herramientas[${u}]`,/^[a-z][a-z0-9_]{2,40}$/,"el nombre de una herramienta")),d=>d,`${o}.herramientas`);if(!Object.keys(a).length&&!s.length&&!c.length)throw i(`\xAB${o}\xBB: di qu\xE9 lleva el contrato (m\xF3dulos, eventos o herramientas).`);return{contrato:n,titulo:r,modulos:a,eventos:s,herramientas:c}}function yw(e){if(e===void 0)return{modulos:{},almacen:!1,red_hacia:[],eventos:[],archivos:[]};if(!me(e))throw i("\xABpermisos\xBB: un objeto.");Ne(e,["modulos","almacen","red_hacia","eventos","archivos"],"Permisos");let o={};if(e.modulos!==void 0){if(!me(e.modulos))throw i("\xABpermisos.modulos\xBB: un objeto { m\xF3dulo: [operaciones] }.");let a=Object.entries(e.modulos);if(a.length>40)throw i("\xABpermisos.modulos\xBB: como mucho 40 m\xF3dulos.");for(let[s,c]of a){let d=co(s);if(!d)throw i(`\xABpermisos.modulos\xBB: \xAB${s.slice(0,60)}\xBB no es un m\xF3dulo (min\xFAsculas, n\xFAmeros y _).`);if(o[d])throw i(`\xABpermisos.modulos\xBB: \xAB${s}\xBB est\xE1 repetido.`);let u=Bo[d]?.ops??Wo,p=ce(c,`permisos.modulos.${s}`,4);if(!p.length)throw i(`\xABpermisos.modulos.${s}\xBB: di qu\xE9 operaciones (${u.join(", ")}).`);for(let h of p)if(typeof h!="string"||!u.includes(h))throw i(`\xABpermisos.modulos.${s}\xBB: operaciones ${u.join(", ")}.`);let m=new Set(p);if((m.has("editar")||m.has("borrar"))&&!m.has("ver"))throw i(`\xABpermisos.modulos.${s}\xBB: para \xABeditar\xBB o \xABborrar\xBB hace falta \xABver\xBB.`);o[d]=Wo.filter(h=>m.has(h))}}if(e.almacen!==void 0&&typeof e.almacen!="boolean")throw i("\xABpermisos.almacen\xBB: s\xED o no (true/false).");let t=we(ce(e.red_hacia,"permisos.red_hacia",20).map((a,s)=>Ul(a,`permisos.red_hacia[${s}]`,"un dominio (\xABapi.ejemplo.com\xBB o \xAB*.ejemplo.com\xBB; ni IP ni localhost)")),a=>a,"permisos.red_hacia").sort(),n=we(ce(e.eventos,"permisos.eventos",40).map((a,s)=>{if(typeof a!="string"||!xl.includes(a))throw i(`\xABpermisos.eventos[${s}]\xBB: un evento del cat\xE1logo (GET /api/v1/eventos).`);return a}),a=>a,"permisos.eventos").sort(),r=ce(e.archivos,"permisos.archivos",2);for(let a of r)if(typeof a!="string"||!kl.includes(a))throw i('\xABpermisos.archivos\xBB: ["leer"] o ["leer", "escribir"].');if(r.includes("escribir")&&!r.includes("leer"))throw i("\xABpermisos.archivos\xBB: para \xABescribir\xBB hace falta \xABleer\xBB.");return{modulos:Object.fromEntries(Object.entries(o).sort(([a],[s])=>a.localeCompare(s))),almacen:e.almacen===!0,red_hacia:t,eventos:n,archivos:kl.filter(a=>r.includes(a))}}function Ll(e,o){let t=o.lastIndexOf(".");if(t<1)return!1;let n=co(o.slice(0,t));return!!n&&(e.modulos[n]??[]).includes(o.slice(t+1))}function Dl(e,o){let t={};if(e===void 0)return t;if(!me(e)||Object.keys(e).length>20)throw i(`\xAB${o}\xBB: { campo: { tipo, desc } }, como mucho 20.`);for(let[n,r]of Object.entries(e)){if(K(n,o,Fo,"nombres de campo en min\xFAsculas y _"),!me(r))throw i(`\xAB${o}.${n}\xBB: { tipo, desc }.`);Ne(r,["tipo","desc","requerido"],`${o}.${n}`);let a=G(r.tipo,`${o}.${n}.tipo`,10);if(!["texto","numero","si_no","fecha"].includes(a))throw i(`\xAB${o}.${n}.tipo\xBB: texto, numero, si_no o fecha.`);t[n]={tipo:a,desc:G(r.desc,`${o}.${n}.desc`,200),requerido:r.requerido===!0}}return t}function Uo(e,o={}){if(typeof e=="string"){if(e.length>gn)throw i("El manifiesto pasa de 256 KB.");try{e=JSON.parse(e)}catch{throw i("El manifiesto no es un JSON v\xE1lido.")}}else if(JSON.stringify(e??null).length>gn)throw i("El manifiesto pasa de 256 KB.");if(!me(e))throw i("El manifiesto tiene que ser un objeto.");if(ca(e),e.formato!==at)throw i(`No es una app (formato \xAB${at}\xBB).`);if(Ne(e,["$schema","formato","formato_version","id","nombre","descripcion","version","autor","icono","idiomas","compatible_crm","licencia","politica_datos","depende_de","ofrece","usa","solucion","montajes","funciones","servidor","herramientas_ia","ajustes","secretos","conexiones","permisos"],"App"),!Number.isInteger(e.formato_version)||e.formato_version<1)throw i("\xABformato_version\xBB: un entero (1).");if(e.formato_version>vn)throw i("La app es de una versi\xF3n del formato m\xE1s nueva que este CRM.");let t=K(e.id,"id",hn,"dominio inverso en min\xFAsculas (\xABcom.tuempresa.mi-extension\xBB)");if(t.length>200)throw i("\xABid\xBB: como mucho 200 caracteres.");if(!o.firmada&&vw(t))throw i("\xABid\xBB: los que empiezan por \xABcom.forgenex.\xBB o \xABforgenex.\xBB est\xE1n reservados a lo que publica ForgeNEX; usa el dominio de tu empresa (\xABcom.tuempresa.mi-extension\xBB).");let n=G(e.nombre,"nombre",80),r=K(e.version,"version",lw,"versi\xF3n semver (\xAB1.0.0\xBB)"),a;if(typeof e.autor=="string")a={nombre:G(e.autor,"autor",120)};else if(me(e.autor))Ne(e.autor,["nombre","web"],"Autor"),a={nombre:G(e.autor.nombre,"autor.nombre",120),...e.autor.web!==void 0?{web:aa(e.autor.web,"autor.web")}:{}};else throw i("Falta \xABautor\xBB (un nombre, o { nombre, web }).");if(!o.firmada){if(ua(n))throw i("\xABnombre\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.");if(ua(a.nombre))throw i("\xABautor\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.")}let s=e.icono===void 0?"puzzle":K(e.icono,"icono",Tl,"un icono de lucide (\xABpuzzle\xBB)"),c=we(ce(e.idiomas,"idiomas",30).map((_,E)=>K(_,`idiomas[${E}]`,uw,"un c\xF3digo de idioma (\xABes\xBB, \xABen\xBB, \xABpt-BR\xBB)")),_=>_,"idiomas"),d=null;if(e.compatible_crm!==void 0){let E=G(e.compatible_crm,"compatible_crm",80).split(/\s+/);if(E.length>2||!E.every(g=>Pl.test(g)))throw i("\xABcompatible_crm\xBB: un rango (\xAB>=1.6.0-284\xBB, \xAB>=1.6.0-284 <2.0.0\xBB).");d=E.join(" ")}let u=e.licencia===void 0?null:G(e.licencia,"licencia",40),p=e.politica_datos===void 0?{}:{politica_datos:aa(e.politica_datos,"politica_datos")},m=we(ce(e.depende_de,"depende_de",20).map((_,E)=>{if(typeof _=="string")return{id:K(_,`depende_de[${E}]`,hn,"el id de otra app"),version:null};if(!me(_))throw i(`\xABdepende_de[${E}]\xBB: el id de otra app, o { id, version }.`);Ne(_,["id","version"],`depende_de[${E}]`);let g=_.version===void 0?null:G(_.version,`depende_de[${E}].version`,80);if(g!==null&&!g.split(/\s+/).every(x=>Pl.test(x)))throw i(`\xABdepende_de[${E}].version\xBB: un rango (\xAB>=1.0.0\xBB).`);return{id:K(_.id,`depende_de[${E}].id`,hn,"el id de otra app"),version:g}}),_=>_.id,"depende_de");if(m.some(_=>_.id===t))throw i("\xABdepende_de\xBB: una app no depende de s\xED misma.");let h=yw(e.permisos),b=we(ce(e.usa,"usa",20).map((_,E)=>{let g=`usa[${E}]`;if(typeof _=="string")return{...Ml(K(_,g,sa,"un nombre de contrato (\xABtaller.citas\xBB)")),de:null};let x=Il(_,g,["de"]),O=K(_.de,`${g}.de`,hn,"el id de la app que lo ofrece (\xABcom.taller.vehiculos\xBB)");if(O===t)throw i(`\xAB${g}.de\xBB: una app no se usa a s\xED misma.`);return{...x,de:O}}),_=>`${_.de??""}/${_.contrato}`,"usa"),y=e.solucion===void 0||e.solucion===null?null:K(e.solucion,"solucion",ia,"el fichero de la soluci\xF3n dentro del paquete (\xABsolucion.json\xBB)");if(y!==null&&!y.endsWith(".json"))throw i("\xABsolucion\xBB: un fichero .json del paquete.");let v=we(ce(e.montajes,"montajes",20).map((_,E)=>{let g=`montajes[${E}]`;if(!me(_))throw i(`\xAB${g}\xBB: un objeto.`);Ne(_,["id","punto","entrada","titulo","icono","modulo","permiso","funciones"],g);let x=G(_.punto,`${g}.punto`,20);if(!Tt.includes(x))throw i(`\xAB${g}.punto\xBB: ${Tt.join(", ")}.`);let O=null;if(Nr.has(x)){if(O=co(G(_.modulo,`${g}.modulo`,64)),!O)throw i(`\xAB${g}.modulo\xBB: el m\xF3dulo donde se cuelga.`);if(!(h.modulos[O]??[]).includes("ver"))throw i(`\xAB${g}\xBB: se cuelga de \xAB${_.modulo}\xBB, as\xED que \xABpermisos.modulos\xBB tiene que pedir verlo.`)}else if(_.modulo!==void 0)throw i(`\xAB${g}.modulo\xBB: solo en ${[...Nr].join(", ")}.`);let k=_.permiso===void 0?null:G(_.permiso,`${g}.permiso`,80);if(k!==null&&!Ll(h,k))throw i(`\xAB${g}.permiso\xBB: \xAB${k}\xBB no est\xE1 en \xABpermisos.modulos\xBB.`);if(x==="publica"&&k!==null)throw i(`\xAB${g}.permiso\xBB: la p\xE1gina p\xFAblica no lleva permiso (la ve cualquiera con el enlace).`);let D;if(x==="publica")D=we(ce(_.funciones,`${g}.funciones`,10).map((B,U)=>K(B,`${g}.funciones[${U}]`,Fo,"el nombre de una funci\xF3n")),B=>B,`${g}.funciones`);else if(_.funciones!==void 0)throw i(`\xAB${g}.funciones\xBB: solo en el montaje \xABpublica\xBB.`);return{id:K(_.id,`${g}.id`,/^[a-z][a-z0-9_-]{0,40}$/,"min\xFAsculas, n\xFAmeros, _ y -"),punto:x,entrada:K(_.entrada,`${g}.entrada`,ia,"un fichero del paquete (\xABinterfaz/index.html\xBB)"),titulo:G(_.titulo,`${g}.titulo`,60),icono:_.icono===void 0?null:K(_.icono,`${g}.icono`,Tl,"un icono de lucide"),modulo:O,permiso:k,...D?{funciones:D}:{}}}),_=>_.id,"montajes");if(v.filter(_=>_.punto==="publica").length>1)throw i("\xABmontajes\xBB: una app tiene como mucho una p\xE1gina p\xFAblica.");let w=we(ce(e.funciones,"funciones",20).map((_,E)=>{let g=`funciones[${E}]`;if(!me(_))throw i(`\xAB${g}\xBB: un objeto.`);if(Ne(_,["nombre","titulo","descripcion","entrada","disparador","tope","red","parametros","salida"],g),!me(_.disparador))throw i(`\xAB${g}.disparador\xBB: { tipo, \u2026 }.`);Ne(_.disparador,["tipo","evento","cron"],`${g}.disparador`);let x=G(_.disparador.tipo,`${g}.disparador.tipo`,20);if(!bn.includes(x))throw i(`\xAB${g}.disparador.tipo\xBB: ${bn.join(", ")}.`);let O={tipo:x};if(x==="evento"){let X=G(_.disparador.evento,`${g}.disparador.evento`,80);if(!h.eventos.includes(X)&&!b.some(Ue=>Ue.eventos.includes(X)))throw i(`\xAB${g}.disparador.evento\xBB: \xAB${X}\xBB tiene que estar en \xABpermisos.eventos\xBB (o en los \xABeventos\xBB de un contrato de \xABusa\xBB).`);O.evento=X}if(x==="programada"){O.cron=K(_.disparador.cron,`${g}.disparador.cron`,pw,"un cron de 5 campos (\xAB0 7 * * 1-5\xBB)");let X=jl(O.cron);if(!X)throw i(`\xAB${g}.disparador.cron\xBB: un cron de 5 campos v\xE1lido (minuto 0-59, hora 0-23, d\xEDa 1-31, mes 1-12, semana 0-7).`);if(Sl(X)<W.cronMinutos)throw i(`\xAB${g}.disparador.cron\xBB: como mucho una vez cada ${W.cronMinutos} minutos.`)}let k=me(_.tope)?_.tope:{};_.tope!==void 0&&Ne(k,["ms","memoria_mb"],`${g}.tope`);let D=k.ms===void 0?5e3:Number(k.ms),B=k.memoria_mb===void 0?64:Number(k.memoria_mb);if(!Number.isInteger(D)||D<W.ms.min||D>W.ms.max)throw i(`\xAB${g}.tope.ms\xBB: de ${W.ms.min} a ${W.ms.max}.`);if(!Number.isInteger(B)||B<W.memoriaMb.min||B>W.memoriaMb.max)throw i(`\xAB${g}.tope.memoria_mb\xBB: de ${W.memoriaMb.min} a ${W.memoriaMb.max}.`);let U=ce(_.red,`${g}.red`,10).map((X,Ue)=>Ul(X,`${g}.red[${Ue}]`,"un dominio"));for(let X of U)if(!_w(h.red_hacia,X))throw i(`\xAB${g}.red\xBB: \xAB${X}\xBB tiene que estar en \xABpermisos.red_hacia\xBB.`);let be=Dl(_.parametros,`${g}.parametros`),Be={},wr=we(ce(_.salida,`${g}.salida`,30).map((X,Ue)=>{let Ve=`${g}.salida[${Ue}]`;if(!me(X))return K(X,Ve,Fo,"nombres en min\xFAsculas y _ (o { clave, titulo })");Ne(X,["clave","titulo"],Ve);let Lo=K(X.clave,`${Ve}.clave`,Fo,"nombres en min\xFAsculas y _");return X.titulo!==void 0&&(Be[Lo]=G(X.titulo,`${Ve}.titulo`,60)),Lo}),X=>X,`${g}.salida`);if(x==="publica"&&U.length)throw i(`\xAB${g}.red\xBB: una funci\xF3n \xABpublica\xBB no sale a la red (solo lee el CRM).`);if(Object.keys(be).length&&x!=="automatizacion")throw i(`\xAB${g}.parametros\xBB: solo en las de disparador \xABautomatizacion\xBB (las dem\xE1s reciben su evento, su minuto o su webhook).`);return{nombre:K(_.nombre,`${g}.nombre`,Fo,"min\xFAsculas, n\xFAmeros y _"),titulo:_.titulo===void 0?null:G(_.titulo,`${g}.titulo`,80),descripcion:_.descripcion===void 0?null:G(_.descripcion,`${g}.descripcion`,300,!1),entrada:K(_.entrada,`${g}.entrada`,ia,"un fichero del paquete (\xABfunciones/calcular.js\xBB)"),disparador:O,tope:{ms:D,memoria_mb:B},red:U,parametros:be,salida:wr,titulos_salida:Be}}),_=>_.nombre,"funciones"),N=null;if(e.servidor!==void 0&&e.servidor!==null){if(!me(e.servidor))throw i("\xABservidor\xBB: { url, webhooks }.");Ne(e.servidor,["url","webhooks"],"Servidor");let _=we(ce(e.servidor.webhooks,"servidor.webhooks",40).map((E,g)=>{if(typeof E!="string"||!h.eventos.includes(E))throw i(`\xABservidor.webhooks[${g}]\xBB: un evento que est\xE9 en \xABpermisos.eventos\xBB.`);return E}),E=>E,"servidor.webhooks");N={url:aa(e.servidor.url,"servidor.url"),webhooks:_}}let j=new Set(w.map(_=>_.nombre));for(let _ of v)for(let[E,g]of(_.funciones??[]).entries()){let x=w.find(O=>O.nombre===g);if(!x)throw i(`\xABmontajes\xBB.\xAB${_.id}\xBB.funciones[${E}]: \xAB${g}\xBB tiene que estar en \xABfunciones\xBB.`);if(x.disparador.tipo!=="publica")throw i(`\xABmontajes\xBB.\xAB${_.id}\xBB.funciones[${E}]: \xAB${g}\xBB tiene que ser de disparador \xABpublica\xBB.`)}let S=we(ce(e.herramientas_ia,"herramientas_ia",20).map((_,E)=>{let g=`herramientas_ia[${E}]`;if(!me(_))throw i(`\xAB${g}\xBB: un objeto.`);Ne(_,["nombre","descripcion","entrada","salida","riesgo","funcion","escribe","permiso"],g);let x=Dl(_.entrada,`${g}.entrada`),O=G(_.riesgo,`${g}.riesgo`,10);if(!["bajo","medio","alto"].includes(O))throw i(`\xAB${g}.riesgo\xBB: bajo, medio o alto.`);let k=G(_.funcion,`${g}.funcion`,41);if(!j.has(k))throw i(`\xAB${g}.funcion\xBB: \xAB${k}\xBB tiene que estar en \xABfunciones\xBB.`);if(!["herramienta","calculo"].includes(w.find(B=>B.nombre===k)?.disparador.tipo??""))throw i(`\xAB${g}.funcion\xBB: \xAB${k}\xBB tiene que ser de disparador \xABherramienta\xBB (o \xABcalculo\xBB).`);if(_.escribe!==void 0&&typeof _.escribe!="boolean")throw i(`\xAB${g}.escribe\xBB: true o false.`);let D=null;if(_.permiso!==void 0){let B=G(_.permiso,`${g}.permiso`,80),U=B.lastIndexOf("."),be=U>0?co(B.slice(0,U)):null;if(!be||!Ll(h,B))throw i(`\xAB${g}.permiso\xBB: \xAB${B}\xBB no est\xE1 en \xABpermisos.modulos\xBB.`);D=`${be}.${B.slice(U+1)}`}return{nombre:K(_.nombre,`${g}.nombre`,/^[a-z][a-z0-9_]{2,40}$/,"min\xFAsculas, n\xFAmeros y _ (3 a 41)"),descripcion:G(_.descripcion,`${g}.descripcion`,500),entrada:x,salida:we(ce(_.salida,`${g}.salida`,30).map((B,U)=>K(B,`${g}.salida[${U}]`,Fo,"nombres de campo")),B=>B,`${g}.salida`),riesgo:O,funcion:k,escribe:_.escribe===!0,permiso:D}}),_=>_.nombre,"herramientas_ia"),q=we(ce(e.ofrece,"ofrece",20).map((_,E)=>{let g=`ofrece[${E}]`;if(typeof _=="string")return Ml(K(_,g,sa,"un nombre de contrato (\xABtaller.citas\xBB)"));let x=Il(_,g,[]);for(let[O,k]of Object.entries(x.modulos)){if(!O.startsWith("mod_"))throw i(`\xAB${g}.modulos\xBB: \xAB${O}\xBB es de serie; un contrato solo comparte m\xF3dulos de la soluci\xF3n de la app.`);let D=h.modulos[O]??[],B=k.find(U=>!D.includes(U));if(B)throw i(`\xAB${g}.modulos.${O.slice(4)}\xBB: ofrece \xAB${B}\xBB y \xABpermisos.modulos\xBB no lo pide (nadie da lo que no tiene).`)}for(let O of x.eventos)if(!h.eventos.includes(O))throw i(`\xAB${g}.eventos\xBB: \xAB${O}\xBB tiene que estar en \xABpermisos.eventos\xBB.`);for(let O of x.herramientas){let k=S.find(D=>D.nombre===O);if(!k)throw i(`\xAB${g}.herramientas\xBB: \xAB${O}\xBB tiene que estar en \xABherramientas_ia\xBB.`);if(k.escribe)throw i(`\xAB${g}.herramientas\xBB: \xAB${O}\xBB escribe; un contrato solo comparte herramientas que consultan.`)}return x}),_=>_.contrato,"ofrece"),F=we(ce(e.ajustes,"ajustes",40).map((_,E)=>{let g=`ajustes[${E}]`;if(!me(_))throw i(`\xAB${g}\xBB: un objeto.`);Ne(_,["clave","etiqueta","tipo","opciones","requerido"],g);let x=G(_.tipo,`${g}.tipo`,10);if(!wn.includes(x))throw i(`\xAB${g}.tipo\xBB: ${wn.join(", ")}.`);let O=ce(_.opciones,`${g}.opciones`,50).map((k,D)=>{if(!me(k))throw i(`\xAB${g}.opciones[${D}]\xBB: { valor, etiqueta }.`);return Ne(k,["valor","etiqueta"],`${g}.opciones[${D}]`),{valor:G(k.valor,`${g}.opciones[${D}].valor`,60),etiqueta:G(k.etiqueta,`${g}.opciones[${D}].etiqueta`,80)}});if(x==="opcion"&&!O.length)throw i(`\xAB${g}.opciones\xBB: un ajuste de tipo opci\xF3n necesita sus opciones.`);if(x!=="opcion"&&O.length)throw i(`\xAB${g}.opciones\xBB: solo en los de tipo opci\xF3n.`);return{clave:K(_.clave,`${g}.clave`,Fo,"min\xFAsculas, n\xFAmeros y _"),etiqueta:G(_.etiqueta,`${g}.etiqueta`,80),tipo:x,opciones:we(O,k=>k.valor,`${g}.opciones`),requerido:_.requerido===!0}}),_=>_.clave,"ajustes"),I=we(ce(e.secretos,"secretos",10).map((_,E)=>{let g=`secretos[${E}]`;if(!me(_))throw i(`\xAB${g}\xBB: un objeto.`);return Ne(_,["clave","etiqueta","descripcion"],g),{clave:K(_.clave,`${g}.clave`,Fo,"min\xFAsculas, n\xFAmeros y _"),etiqueta:G(_.etiqueta,`${g}.etiqueta`,80),descripcion:G(_.descripcion,`${g}.descripcion`,300,!1)}}),_=>_.clave,"secretos");return{formato:at,formato_version:e.formato_version,id:t,nombre:n,descripcion:G(e.descripcion,"descripcion",500,!1),version:r,autor:a,icono:s,idiomas:c,compatible_crm:d,licencia:u,...p,depende_de:m,ofrece:q,usa:b,solucion:y,montajes:v,funciones:w,servidor:N,herramientas_ia:S,ajustes:F,secretos:I,...e.conexiones!==void 0?{conexiones:Nl(e.conexiones)}:{},permisos:h}}var at,vn,gn,Bo,Wo,Tt,yn,Nr,bn,wn,ql,kl,cw,hn,lw,Pl,Tl,uw,sa,Fo,dw,ia,zl,pw,me,Fl,mw,sN,fw,Wl,Bl,gw,bw,la,ua,Ml,_w,Mt=f(()=>{$l();R();Cl();Ol();_r();Rl();at="forgenex.extension",vn=1,gn=256e3,Bo={contactos:{nombre:"Personas",ops:["ver","crear","editar","borrar"]},empresas:{nombre:"Empresas",ops:["ver","crear","editar","borrar"]},oportunidades:{nombre:"Oportunidades",ops:["ver","crear","editar","borrar"]},tareas:{nombre:"Tareas",ops:["ver","crear","editar","borrar"]},notas:{nombre:"Notas",ops:["ver","editar"]}},Wo=["ver","crear","editar","borrar"],Tt=["pagina","ficha_pestana","ficha_bloque","inicio_bloque","accion_ficha","accion_tabla","vista","ajustes","publica"],yn=new Set(["pagina","ficha_pestana","ficha_bloque","inicio_bloque","accion_ficha","accion_tabla","vista","ajustes","publica"]),Nr=new Set(["ficha_pestana","ficha_bloque","accion_ficha","accion_tabla","vista"]),bn=["evento","programada","webhook","automatizacion","calculo","herramienta","publica"],wn=["texto","numero","si_no","opcion","modulo","campo"],ql=["registro.creado","registro.actualizado","registro.borrado"],kl=["leer","escribir"],cw=new Set(["__proto__","constructor","prototype"]),hn=/^[a-z][a-z0-9-]{0,62}(\.[a-z0-9][a-z0-9-]{0,62}){1,6}$/,lw=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})(-[0-9a-z.-]{1,30})?$/,Pl=/^(>=|<=|>|<|=|\^|~)?(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})(-[0-9a-z.-]{1,30})?$/,Tl=/^[a-z0-9-]{1,40}$/,uw=/^[a-z]{2,3}(-[A-Z]{2})?$/,sa=/^[a-z][a-z0-9_.-]{0,79}$/,Fo=/^[a-z][a-z0-9_]{0,40}$/,dw=/^[a-z][a-z0-9_]{0,59}$/,ia=/^(?!\/)(?!.*\/\/)(?!.*(^|\/)\.\.?(\/|$))[A-Za-z0-9_.\/-]{1,200}$/,zl=/^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,pw=/^[0-9*,\/-]+( [0-9*,\/-]+){4}$/,me=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);Fl=String.raw`[\p{Cc}\p{Cf}\u2028\u2029\u034F\u115F\u1160\u2800\u3164\uFFA0]|(?<!\p{Emoji})[\uFE00-\uFE0F]|(?<=[0-9#*])[\uFE00-\uFE0F](?!\u20E3)`,mw=new RegExp(Fl,"u"),sN=new RegExp(Fl,"gu"),fw=new RegExp("(?<=\\p{Extended_Pictographic}[\\uFE0F\\p{Emoji_Modifier}]?)\\u200D(?=\\p{Extended_Pictographic})","gu");Wl={\u0391:"a",\u0392:"b",\u0395:"e",\u0396:"z",\u0397:"h",\u0399:"i",\u039A:"k",\u039C:"m",\u039D:"n",\u039F:"o",\u03A1:"p",\u03A4:"t",\u03A5:"y",\u03A7:"x",\u0410:"a",\u0412:"b",\u0415:"e",\u0405:"s",\u0406:"i",\u0408:"j",\u041A:"k",\u041C:"m",\u041D:"h",\u041E:"o",\u0420:"p",\u0421:"c",\u0422:"t",\u0425:"x",\u04AE:"y","\u050C":"g","\u051A":"q","\u051C":"w"},Bl={\u03B1:"a",\u03B2:"b",\u03B3:"y",\u03B5:"e",\u03B7:"n",\u03B9:"i",\u03BA:"k",\u03BD:"v",\u03BF:"o",\u03C1:"p",\u03C4:"t",\u03C5:"u",\u03C7:"x",\u03C9:"w",\u0430:"a",\u0435:"e",\u0451:"e",\u043E:"o",\u0440:"p",\u0441:"c",\u0443:"y",\u0445:"x",\u0455:"s",\u0456:"i",\u0457:"i",\u0458:"j","\u0501":"d",\u04BB:"h","\u04CF":"l","\u051B":"q","\u051D":"w",\u0261:"g",\u0433:"r",\u043F:"n",\u049D:"k",\u043A:"k",\u0131:"i","\u0237":"j",0:"o","\u1D00":"a",\u0299:"b","\u1D04":"c","\u1D05":"d","\u1D07":"e","\uA730":"f",\u0262:"g",\u029C:"h",\u026A:"i","\u1D0A":"j","\u1D0B":"k",\u029F:"l","\u1D0D":"m",\u0274:"n","\u1D0F":"o","\u1D18":"p",\u0280:"r","\uA731":"s","\u1D1B":"t","\u1D1C":"u","\u1D20":"v","\u1D21":"w",\u028F:"y","\u1D22":"z",\u0585:"o","\uA4EE":"a","\uA4D0":"b","\uA4DA":"c","\uA4D3":"d","\uA4F0":"e","\uA4DD":"f","\uA4D6":"g","\uA4E7":"h","\uA4F2":"i","\uA4D9":"j","\uA4D7":"k","\uA4E1":"l","\uA4DF":"m","\uA4E0":"n","\uA4F3":"o","\uA4D1":"p","\uA4E3":"r","\uA4E2":"s","\uA4D4":"t","\uA4F4":"u","\uA4E6":"v","\uA4EA":"w","\uA4EB":"x","\uA4EC":"y","\uA4DC":"z"},gw=new RegExp(`[${Object.keys(Wl).join("")}]`,"gu"),bw=new RegExp(`[${Object.keys(Bl).join("")}]`,"gu"),la=e=>e.normalize("NFKC").replace(gw,o=>Wl[o]).toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"").replace(bw,o=>Bl[o]).replace(/[^\p{L}\p{N}]/gu,"");ua=e=>{let o=ww(e);for(let t=0;t<o.length;t++){let n="";for(let r=t;r<o.length&&n.length<8;r++)if(n+=o[r],n==="forgenex")return!0}return!1};Ml=e=>({contrato:e,titulo:null,modulos:{},eventos:[],herramientas:[]});_w=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1)))});function No(e){return typeof e>"u"||e===void 0}function H(e){return typeof e=="string"}function lo(e){return typeof e=="number"}function st(e){return typeof e=="boolean"}function ct(e){return e===null}function da(e){return e instanceof Date}function lt(e){return typeof e=="bigint"}function Vl(e){return typeof Buffer<"u"&&Buffer.isBuffer(e)}function $e(e){return typeof e=="function"}function je(e){return typeof e=="object"&&e!==null}function l(e){return Object.freeze(e)}function $r(e){return ke(e)?e:[e]}function ke(e){return Array.isArray(e)}function Jl(e){return e instanceof Error?e.message:String(e)}var $=f(()=>{});var dN,Ql=f(()=>{$();dN=l({is(e){return e.kind==="AlterTableNode"},create(e){return l({kind:"AlterTableNode",table:e})},cloneWithTableProps(e,o){return l({...e,...o})},cloneWithColumnAlteration(e,o){return l({...e,columnAlterations:e.columnAlterations?[...e.columnAlterations,o]:[o]})}})});var M,ne=f(()=>{$();M=l({is(e){return e.kind==="IdentifierNode"},create(e){return l({kind:"IdentifierNode",name:e})}})});var bN,Gl=f(()=>{$();ne();bN=l({is(e){return e.kind==="CreateIndexNode"},create(e){return l({kind:"CreateIndexNode",name:M.create(e)})},cloneWith(e,o){return l({...e,...o})},cloneWithColumns(e,o){return l({...e,columns:[...e.columns||[],...o]})}})});var _N,Hl=f(()=>{$();ne();_N=l({is(e){return e.kind==="CreateSchemaNode"},create(e,o){return l({kind:"CreateSchemaNode",schema:M.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var xN,Xl=f(()=>{$();xN=l({is(e){return e.kind==="CreateTableNode"},create(e){return l({kind:"CreateTableNode",table:e,columns:l([])})},cloneWithColumn(e,o){return l({...e,columns:l([...e.columns,o])})},cloneWithConstraint(e,o){return l({...e,constraints:e.constraints?l([...e.constraints,o]):l([o])})},cloneWithIndex(e,o){return l({...e,indexes:e.indexes?l([...e.indexes,o]):l([o])})},cloneWithFrontModifier(e,o){return l({...e,frontModifiers:e.frontModifiers?l([...e.frontModifiers,o]):l([o])})},cloneWithEndModifier(e,o){return l({...e,endModifiers:e.endModifiers?l([...e.endModifiers,o]):l([o])})},cloneWith(e,o){return l({...e,...o})}})});var Ye,ut=f(()=>{$();ne();Ye=l({is(e){return e.kind==="SchemableIdentifierNode"},create(e){return l({kind:"SchemableIdentifierNode",identifier:M.create(e)})},createWithSchema(e,o){return l({kind:"SchemableIdentifierNode",schema:M.create(e),identifier:M.create(o)})}})});var RN,Yl=f(()=>{$();ut();RN=l({is(e){return e.kind==="DropIndexNode"},create(e,o){return l({kind:"DropIndexNode",name:Ye.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var TN,Kl=f(()=>{$();ne();TN=l({is(e){return e.kind==="DropSchemaNode"},create(e,o){return l({kind:"DropSchemaNode",schema:M.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var LN,Zl=f(()=>{$();LN=l({is(e){return e.kind==="DropTableNode"},create(e,o){return l({kind:"DropTableNode",table:e,...o})},cloneWith(e,o){return l({...e,...o})}})});var Pe,$o=f(()=>{$();Pe=l({is(e){return e.kind==="AliasNode"},create(e,o){return l({kind:"AliasNode",node:e,alias:o})}})});var Vo,xr=f(()=>{$();ut();Vo=l({is(e){return e.kind==="TableNode"},create(e){return l({kind:"TableNode",table:Ye.create(e)})},createWithSchema(e,o){return l({kind:"TableNode",table:Ye.createWithSchema(e,o)})}})});function ie(e){return je(e)&&$e(e.toOperationNode)}var Je=f(()=>{$()});function _n(e){return je(e)&&"expressionType"in e&&ie(e)}function eu(e){return je(e)&&"expression"in e&&H(e.alias)&&ie(e)}var Nn=f(()=>{Je();$()});var uo,pa=f(()=>{$();uo=l({is(e){return e.kind==="SelectModifierNode"},create(e,o){return l({kind:"SelectModifierNode",modifier:e,of:o})},createWithExpression(e){return l({kind:"SelectModifierNode",rawModifier:e})}})});var Te,Jo=f(()=>{$();Te=l({is(e){return e.kind==="AndNode"},create(e,o){return l({kind:"AndNode",left:e,right:o})}})});var Ke,dt=f(()=>{$();Ke=l({is(e){return e.kind==="OrNode"},create(e,o){return l({kind:"OrNode",left:e,right:o})}})});var $n,ma=f(()=>{$();Jo();dt();$n=l({is(e){return e.kind==="OnNode"},create(e){return l({kind:"OnNode",on:e})},cloneWithOperation(e,o,t){return l({...e,on:o==="And"?Te.create(e.on,t):Ke.create(e.on,t)})}})});var xo,Cr=f(()=>{$();ma();xo=l({is(e){return e.kind==="JoinNode"},create(e,o){return l({kind:"JoinNode",joinType:e,table:o,on:void 0})},createWithOn(e,o,t){return l({kind:"JoinNode",joinType:e,table:o,on:$n.create(t)})},cloneWithOn(e,o){return l({...e,on:e.on?$n.cloneWithOperation(e.on,"And",o):$n.create(o)})}})});var Qo,xn=f(()=>{$();Qo=l({is(e){return e.kind==="BinaryOperationNode"},create(e,o,t){return l({kind:"BinaryOperationNode",leftOperand:e,operator:o,rightOperand:t})}})});function su(e){return H(e)&&nu[e]}function cu(e){return H(e)&&ru[e]}function lu(e){return H(e)&&au[e]}var ou,p$,tu,m$,ru,Nw,nu,$w,iu,f$,au,xw,h$,Ze,It=f(()=>{$();ou=l({"=":!0,"==":!0,"!=":!0,"<>":!0,">":!0,">=":!0,"<":!0,"<=":!0,in:!0,"not in":!0,is:!0,"is not":!0,like:!0,"not like":!0,match:!0,ilike:!0,"not ilike":!0,"@>":!0,"<@":!0,"^@":!0,"&&":!0,"?":!0,"?&":!0,"?|":!0,"!<":!0,"!>":!0,"<=>":!0,"!~":!0,"~":!0,"~*":!0,"!~*":!0,"@@":!0,"@@@":!0,"!!":!0,"<->":!0,regexp:!0,"is distinct from":!0,"is not distinct from":!0}),p$=Object.keys(ou),tu=l({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0}),m$=Object.keys(tu),ru=l({"->":!0,"->>":!0}),Nw=Object.keys(ru),nu=l({...ou,...tu,"||":!0}),$w=Object.keys(nu),iu=l({exists:!0,"not exists":!0}),f$=Object.keys(iu),au=l({...iu,"-":!0,not:!0}),xw=Object.keys(au),h$=[...$w,...Nw,...xw,"between","between symmetric"],Ze=l({is(e){return e.kind==="OperatorNode"},create(e){return l({kind:"OperatorNode",operator:e})}})});var ue,eo=f(()=>{$();ne();ue=l({is(e){return e.kind==="ColumnNode"},create(e){return l({kind:"ColumnNode",column:M.create(e)})}})});var Cn,jn=f(()=>{$();Cn=l({is(e){return e.kind==="SelectAllNode"},create(){return l({kind:"SelectAllNode"})}})});var Lt,Sn=f(()=>{jn();$();Lt=l({is(e){return e.kind==="ReferenceNode"},create(e,o){return l({kind:"ReferenceNode",table:o,column:e})},createSelectAll(e){return l({kind:"ReferenceNode",table:e,column:Cn.create()})}})});function On(e){return je(e)&&ie(e)&&H(e.dynamicReference)}var An=f(()=>{Je();$()});var oo,En=f(()=>{$();oo=l({is(e){return e.kind==="OrderByItemNode"},create(e,o){return l({kind:"OrderByItemNode",orderBy:e,direction:o})},cloneWith(e,o){return l({...e,...o})}})});var de,pt=f(()=>{$();de=l({is(e){return e.kind==="RawNode"},create(e,o){return l({kind:"RawNode",sqlFragments:l(e),parameters:l(o)})},createWithSql(e){return de.create([e],[])},createWithChild(e){return de.create(["",""],[e])},createWithChildren(e){return de.create(new Array(e.length+1).fill(""),e)}})});var uu,fa=f(()=>{$();ne();uu=l({is(e){return e.kind==="CollateNode"},create(e){return l({kind:"CollateNode",collation:M.create(e)})}})});var Rn,ha=f(()=>{fa();En();pt();$();Rn=class e{#e;constructor(o){this.#e=l(o)}desc(){return new e({node:oo.cloneWith(this.#e.node,{direction:de.createWithSql("desc")})})}asc(){return new e({node:oo.cloneWith(this.#e.node,{direction:de.createWithSql("asc")})})}nullsLast(){return new e({node:oo.cloneWith(this.#e.node,{nulls:"last"})})}nullsFirst(){return new e({node:oo.cloneWith(this.#e.node,{nulls:"first"})})}collate(o){return new e({node:oo.cloneWith(this.#e.node,{collation:uu.create(o)})})}toOperationNode(){return this.#e.node}}});function Dt(e){du.has(e)||(du.add(e),console.log(e))}var du,ga=f(()=>{du=new Set});function Cw(e){return e==="asc"||e==="desc"}function to(e){if(e.length===2)return[ba(e[0],e[1])];if(e.length===1){let[o]=e;return Array.isArray(o)?(Dt("orderBy(array) is deprecated, use multiple orderBy calls instead."),o.map(t=>ba(t))):[ba(o)]}throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${e.length}`)}function ba(e,o){let t=jw(e);if(oo.is(t)){if(o)throw new Error("Cannot specify direction twice!");return t}return pu(t,o)}function jw(e){if(mt(e))return Go(e);if(On(e))return e.toOperationNode();let[o,t]=e.split(" ");return t?(Dt("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),pu(Qe(o),t)):Qe(e)}function pu(e,o){if(typeof o=="string"){if(!Cw(o))throw new Error(`Invalid order by direction: ${o}`);return oo.create(e,de.createWithSql(o))}if(_n(o))return Dt("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),oo.create(e,o.toOperationNode());let t=oo.create(e);return o?o(new Rn({node:t})).toOperationNode():t}var zt=f(()=>{An();Nn();En();pt();ha();ga();ft();Ie()});var Ft,qn=f(()=>{$();Ft=l({is(e){return e.kind==="JSONReferenceNode"},create(e,o){return l({kind:"JSONReferenceNode",reference:e,traversal:o})},cloneWithTraversal(e,o){return l({...e,traversal:o})}})});var kn,Pn=f(()=>{$();kn=l({is(e){return e.kind==="JSONOperatorChainNode"},create(e){return l({kind:"JSONOperatorChainNode",operator:e,values:l([])})},cloneWithValue(e,o){return l({...e,values:l([...e.values,o])})}})});var Ho,jr=f(()=>{$();Ho=l({is(e){return e.kind==="JSONPathNode"},create(e){return l({kind:"JSONPathNode",inOperator:e,pathLegs:l([])})},cloneWithLeg(e,o){return l({...e,pathLegs:l([...e.pathLegs,o])})}})});function Sw(e){return H(e)?Qe(e):e.toOperationNode()}function Co(e){return ke(e)?e.map(o=>fe(o)):[fe(e)]}function fe(e){return mt(e)?Go(e):Sw(e)}function mu(e,o){if(cu(o))return Ft.create(Qe(e),kn.create(Ze.create(o)));if(o==="->$"||o==="->>$")return Ft.create(Qe(e),Ho.create(Ze.create(o.slice(0,-1))));throw new Error(`Invalid JSON operator: ${o}`)}function Qe(e){if(!e.includes("."))return Lt.create(ue.create(e));let t=e.split(".").map(hu);if(t.length===3)return Ow(t);if(t.length===2)return Aw(t);throw new Error(`invalid column reference ${e}`)}function fu(e){let o=" as ";if(e.includes(o)){let[t,n]=e.split(o).map(hu);return Pe.create(Qe(t),M.create(n))}else return Qe(e)}function Ow(e){let[o,t,n]=e;return Lt.create(ue.create(n),Vo.createWithSchema(o,t))}function Aw(e){let[o,t]=e;return Lt.create(ue.create(t),Vo.create(o))}function hu(e){return e.trim()}var Ie=f(()=>{$o();eo();Sn();xr();$();ft();ne();It();qn();Pn();jr()});var gu,wa=f(()=>{$();gu=l({is(e){return e.kind==="PrimitiveValueListNode"},create(e){return l({kind:"PrimitiveValueListNode",values:l([...e])})}})});var Tn,Mn=f(()=>{$();Tn=l({is(e){return e.kind==="ValueListNode"},create(e){return l({kind:"ValueListNode",values:l(e)})}})});var Se,Xo=f(()=>{$();Se=l({is(e){return e.kind==="ValueNode"},create(e){return l({kind:"ValueNode",value:e})},createImmediate(e){return l({kind:"ValueNode",value:e,immediate:!0})}})});function bu(e){return ke(e)?Ew(e):Z(e)}function Z(e){return mt(e)?Go(e):Se.create(e)}function In(e){return lo(e)||st(e)||ct(e)}function Sr(e){if(!In(e))throw new Error(`unsafe immediate value ${JSON.stringify(e)}`);return Se.createImmediate(e)}function Ew(e){return e.some(mt)?Tn.create(e.map(o=>Z(o))):gu.create(e)}var jo=f(()=>{wa();Mn();Xo();$();ft()});var Yo,Or=f(()=>{$();Yo=l({is(e){return e.kind==="ParensNode"},create(e){return l({kind:"ParensNode",node:e})}})});function pe(e){if(e.length===3)return Ln(e[0],e[1],e[2]);if(e.length===1)return Z(e[0]);throw new Error(`invalid arguments: ${JSON.stringify(e)}`)}function Ln(e,o,t){return Rw(o)&&vu(t)?Qo.create(fe(e),va(o),Se.createImmediate(t)):Qo.create(fe(e),va(o),bu(t))}function xe(e,o,t){return Qo.create(fe(e),va(o),fe(t))}function ya(e,o){return Dn(Object.entries(e).filter(([,t])=>!No(t)).map(([t,n])=>Ln(t,vu(n)?"is":"=",n)),o)}function Dn(e,o,t=!0){let n=o==="and"?Te.create:Ke.create;if(e.length===0)return Qo.create(Se.createImmediate(1),Ze.create("="),Se.createImmediate(o==="and"?1:0));let r=wu(e[0]);for(let a=1;a<e.length;++a)r=n(r,wu(e[a]));return e.length>1&&t?Yo.create(r):r}function Rw(e){return e==="is"||e==="is not"}function vu(e){return ct(e)||st(e)}function va(e){if(su(e))return Ze.create(e);if(ie(e))return e.toOperationNode();throw new Error(`invalid operator ${JSON.stringify(e)}`)}function wu(e){return ie(e)?e.toOperationNode():e}var po=f(()=>{xn();$();Je();It();Ie();jo();Xo();Jo();Or();dt()});var So,Ar=f(()=>{$();So=l({is(e){return e.kind==="OrderByNode"},create(e){return l({kind:"OrderByNode",items:l([...e])})},cloneWithItems(e,o){return l({...e,items:l([...e.items,...o])})}})});var _a,Na=f(()=>{$();_a=l({is(e){return e.kind==="PartitionByNode"},create(e){return l({kind:"PartitionByNode",items:l(e)})},cloneWithItems(e,o){return l({...e,items:l([...e.items,...o])})}})});var Er,zn=f(()=>{$();Ar();Na();Er=l({is(e){return e.kind==="OverNode"},create(){return l({kind:"OverNode"})},cloneWithOrderByItems(e,o){return l({...e,orderBy:e.orderBy?So.cloneWithItems(e.orderBy,o):So.create(o)})},cloneWithPartitionByItems(e,o){return l({...e,partitionBy:e.partitionBy?_a.cloneWithItems(e.partitionBy,o):_a.create(o)})}})});var ht,Rr=f(()=>{$();ht=l({is(e){return e.kind==="FromNode"},create(e){return l({kind:"FromNode",froms:l(e)})},cloneWithFroms(e,o){return l({...e,froms:l([...e.froms,...o])})}})});var $a,xa=f(()=>{$();$a=l({is(e){return e.kind==="GroupByNode"},create(e){return l({kind:"GroupByNode",items:l(e)})},cloneWithItems(e,o){return l({...e,items:l([...e.items,...o])})}})});var Ca,ja=f(()=>{$();Jo();dt();Ca=l({is(e){return e.kind==="HavingNode"},create(e){return l({kind:"HavingNode",having:e})},cloneWithOperation(e,o,t){return l({...e,having:o==="And"?Te.create(e.having,t):Ke.create(e.having,t)})}})});var yu,Sa=f(()=>{$();yu=l({is(e){return e.kind==="InsertQueryNode"},create(e,o,t){return l({kind:"InsertQueryNode",into:e,...o&&{with:o},replace:t})},createWithoutInto(){return l({kind:"InsertQueryNode"})},cloneWith(e,o){return l({...e,...o})}})});var _u,Oa=f(()=>{$();_u=l({is(e){return e.kind==="ListNode"},create(e){return l({kind:"ListNode",items:l(e)})}})});var Wt,Fn=f(()=>{$();Rr();Oa();Wt=l({is(e){return e.kind==="UpdateQueryNode"},create(e,o){return l({kind:"UpdateQueryNode",table:e.length===1?e[0]:_u.create(e),...o&&{with:o}})},createWithoutTable(){return l({kind:"UpdateQueryNode"})},cloneWithFromItems(e,o){return l({...e,from:e.from?ht.cloneWithFroms(e.from,o):ht.create(o)})},cloneWithUpdates(e,o){return l({...e,updates:e.updates?l([...e.updates,...o]):o})},cloneWithLimit(e,o){return l({...e,limit:o})}})});var Aa,Ea=f(()=>{$();Aa=l({is(e){return e.kind==="UsingNode"},create(e){return l({kind:"UsingNode",tables:l(e)})},cloneWithTables(e,o){return l({...e,tables:l([...e.tables,...o])})}})});var Bt,Wn=f(()=>{$();Rr();Ea();Oo();Bt=l({is(e){return e.kind==="DeleteQueryNode"},create(e,o){return l({kind:"DeleteQueryNode",from:ht.create(e),...o&&{with:o}})},cloneWithOrderByItems:(e,o)=>P.cloneWithOrderByItems(e,o),cloneWithoutOrderBy:e=>P.cloneWithoutOrderBy(e),cloneWithLimit(e,o){return l({...e,limit:o})},cloneWithoutLimit(e){return l({...e,limit:void 0})},cloneWithUsing(e,o){return l({...e,using:e.using!==void 0?Aa.cloneWithTables(e.using,o):Aa.create(o)})}})});var ye,qr=f(()=>{$();Jo();dt();ye=l({is(e){return e.kind==="WhereNode"},create(e){return l({kind:"WhereNode",where:e})},cloneWithOperation(e,o,t){return l({...e,where:o==="And"?Te.create(e.where,t):Ke.create(e.where,t)})}})});var Ra,qa=f(()=>{$();Ra=l({is(e){return e.kind==="ReturningNode"},create(e){return l({kind:"ReturningNode",selections:l(e)})},cloneWithSelections(e,o){return l({...e,selections:e.selections?l([...e.selections,...o]):l(o)})}})});var Nu,ka=f(()=>{$();Nu=l({is(e){return e.kind==="ExplainNode"},create(e,o){return l({kind:"ExplainNode",format:e,options:o})}})});var Ao,kr=f(()=>{$();Ao=l({is(e){return e.kind==="WhenNode"},create(e){return l({kind:"WhenNode",condition:e})},cloneWithResult(e,o){return l({...e,result:o})}})});var $u,Pa=f(()=>{$();kr();$u=l({is(e){return e.kind==="MergeQueryNode"},create(e,o){return l({kind:"MergeQueryNode",into:e,...o&&{with:o}})},cloneWithUsing(e,o){return l({...e,using:o})},cloneWithWhen(e,o){return l({...e,whens:e.whens?l([...e.whens,o]):l([o])})},cloneWithThen(e,o){return l({...e,whens:e.whens?l([...e.whens.slice(0,-1),Ao.cloneWithResult(e.whens[e.whens.length-1],o)]):void 0})}})});var Ta,Ma=f(()=>{$();Ta=l({is(e){return e.kind==="OutputNode"},create(e){return l({kind:"OutputNode",selections:l(e)})},cloneWithSelections(e,o){return l({...e,selections:e.selections?l([...e.selections,...o]):l(o)})}})});var P,Oo=f(()=>{Sa();Pr();Fn();Wn();qr();$();qa();ka();Pa();Ma();Ar();P=l({is(e){return ee.is(e)||yu.is(e)||Wt.is(e)||Bt.is(e)||$u.is(e)},cloneWithEndModifier(e,o){return l({...e,endModifiers:e.endModifiers?l([...e.endModifiers,o]):l([o])})},cloneWithWhere(e,o){return l({...e,where:e.where?ye.cloneWithOperation(e.where,"And",o):ye.create(o)})},cloneWithJoin(e,o){return l({...e,joins:e.joins?l([...e.joins,o]):l([o])})},cloneWithReturning(e,o){return l({...e,returning:e.returning?Ra.cloneWithSelections(e.returning,o):Ra.create(o)})},cloneWithoutReturning(e){return l({...e,returning:void 0})},cloneWithoutWhere(e){return l({...e,where:void 0})},cloneWithExplain(e,o,t){return l({...e,explain:Nu.create(o,t?.toOperationNode())})},cloneWithTop(e,o){return l({...e,top:o})},cloneWithOutput(e,o){return l({...e,output:e.output?Ta.cloneWithSelections(e.output,o):Ta.create(o)})},cloneWithOrderByItems(e,o){return l({...e,orderBy:e.orderBy?So.cloneWithItems(e.orderBy,o):So.create(o)})},cloneWithoutOrderBy(e){return l({...e,orderBy:void 0})}})});var ee,Pr=f(()=>{$();Rr();xa();ja();Oo();ee=l({is(e){return e.kind==="SelectQueryNode"},create(e){return l({kind:"SelectQueryNode",...e&&{with:e}})},createFrom(e,o){return l({kind:"SelectQueryNode",from:ht.create(e),...o&&{with:o}})},cloneWithSelections(e,o){return l({...e,selections:e.selections?l([...e.selections,...o]):l(o)})},cloneWithDistinctOn(e,o){return l({...e,distinctOn:e.distinctOn?l([...e.distinctOn,...o]):l(o)})},cloneWithFrontModifier(e,o){return l({...e,frontModifiers:e.frontModifiers?l([...e.frontModifiers,o]):l([o])})},cloneWithOrderByItems:(e,o)=>P.cloneWithOrderByItems(e,o),cloneWithGroupByItems(e,o){return l({...e,groupBy:e.groupBy?$a.cloneWithItems(e.groupBy,o):$a.create(o)})},cloneWithLimit(e,o){return l({...e,limit:o})},cloneWithOffset(e,o){return l({...e,offset:o})},cloneWithFetch(e,o){return l({...e,fetch:o})},cloneWithHaving(e,o){return l({...e,having:e.having?Ca.cloneWithOperation(e.having,"And",o):Ca.create(o)})},cloneWithSetOperations(e,o){return l({...e,setOperations:e.setOperations?l([...e.setOperations,...o]):l([...o])})},cloneWithoutSelections(e){return l({...e,selections:[]})},cloneWithoutLimit(e){return l({...e,limit:void 0})},cloneWithoutOffset(e){return l({...e,offset:void 0})},cloneWithoutOrderBy:e=>P.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return l({...e,groupBy:void 0})}})});var Bn,Ia=f(()=>{Cr();pt();po();$();Bn=class e{#e;constructor(o){this.#e=l(o)}on(...o){return new e({...this.#e,joinNode:xo.cloneWithOn(this.#e.joinNode,pe(o))})}onRef(o,t,n){return new e({...this.#e,joinNode:xo.cloneWithOn(this.#e.joinNode,xe(o,t,n))})}onTrue(){return new e({...this.#e,joinNode:xo.cloneWithOn(this.#e.joinNode,de.createWithSql("true"))})}$call(o){return o(this)}toOperationNode(){return this.#e.joinNode}}});var xu,La=f(()=>{$();xu=l({is(e){return e.kind==="PartitionByItemNode"},create(e){return l({kind:"PartitionByItemNode",partitionBy:e})}})});function Cu(e){return Co(e).map(xu.create)}var ju=f(()=>{La();Ie()});var Un,Su=f(()=>{zn();Oo();zt();ju();$();Un=class e{#e;constructor(o){this.#e=l(o)}orderBy(...o){return new e({overNode:Er.cloneWithOrderByItems(this.#e.overNode,to(o))})}clearOrderBy(){return new e({overNode:P.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(o){return new e({overNode:Er.cloneWithPartitionByItems(this.#e.overNode,Cu(o))})}$call(o){return o(this)}toOperationNode(){return this.#e.overNode}}});var Ut,Da=f(()=>{$();Sn();jn();Ut=l({is(e){return e.kind==="SelectionNode"},create(e){return l({kind:"SelectionNode",selection:e})},createSelectAll(){return l({kind:"SelectionNode",selection:Cn.create()})},createSelectAllFromTable(e){return l({kind:"SelectionNode",selection:Lt.createSelectAll(e)})}})});function Eo(e){return $e(e)?Eo(e(Ro())):ke(e)?e.map(o=>Ou(o)):[Ou(e)]}function Ou(e){return H(e)?Ut.create(fu(e)):On(e)?Ut.create(e.toOperationNode()):Ut.create(Vn(e))}function mo(e){return e?Array.isArray(e)?e.map(Au):[Au(e)]:[Ut.createSelectAll()]}function Au(e){if(H(e))return Ut.createSelectAllFromTable(Ce(e));throw new Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}var Tr=f(()=>{$();Da();Ie();An();ft();fo();Vt()});var xj,Eu=f(()=>{$();xj=l({is(e){return e.kind==="ValuesNode"},create(e){return l({kind:"ValuesNode",values:l(e)})}})});var Sj,Ru=f(()=>{$();Sj=l({is(e){return e.kind==="DefaultInsertValueNode"},create(){return l({kind:"DefaultInsertValueNode"})}})});var za,Fa=f(()=>{$();za=l({is(e){return e.kind==="ColumnUpdateNode"},create(e,o){return l({kind:"ColumnUpdateNode",column:e,value:o})}})});function qu(...e){return e.length===2?[za.create(fe(e[0]),Z(e[1]))]:qw(e[0])}function qw(e){let o=$e(e)?e(Ro()):e;return Object.entries(o).filter(([t,n])=>n!==void 0).map(([t,n])=>za.create(ue.create(t),Z(n)))}var ku=f(()=>{eo();Fa();Vt();$();jo();Ie()});var Dj,Pu=f(()=>{$();Dj=l({is(e){return e.kind==="OnDuplicateKeyNode"},create(e){return l({kind:"OnDuplicateKeyNode",updates:e})}})});var Tu=f(()=>{});function Jt(e){return Object.prototype.hasOwnProperty.call(e,"prototype")}var Ko,Mr=f(()=>{Ko=class extends Error{node;constructor(o){super("no result"),this.node=o}}});var Vj,Mu=f(()=>{$();qr();Vj=l({is(e){return e.kind==="OnConflictNode"},create(){return l({kind:"OnConflictNode"})},cloneWith(e,o){return l({...e,...o})},cloneWithIndexWhere(e,o){return l({...e,indexWhere:e.indexWhere?ye.cloneWithOperation(e.indexWhere,"And",o):ye.create(o)})},cloneWithIndexOrWhere(e,o){return l({...e,indexWhere:e.indexWhere?ye.cloneWithOperation(e.indexWhere,"Or",o):ye.create(o)})},cloneWithUpdateWhere(e,o){return l({...e,updateWhere:e.updateWhere?ye.cloneWithOperation(e.updateWhere,"And",o):ye.create(o)})},cloneWithUpdateOrWhere(e,o){return l({...e,updateWhere:e.updateWhere?ye.cloneWithOperation(e.updateWhere,"Or",o):ye.create(o)})},cloneWithoutIndexWhere(e){return l({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return l({...e,updateWhere:void 0})}})});var Iu=f(()=>{});var Lu,Wa=f(()=>{$();Lu=l({is(e){return e.kind==="TopNode"},create(e,o){return l({kind:"TopNode",expression:e,modifiers:o})}})});function Qt(e,o){if(!lo(e)&&!lt(e))throw new Error(`Invalid top expression: ${e}`);if(!No(o)&&!kw(o))throw new Error(`Invalid top modifiers: ${o}`);return Lu.create(e,o)}function kw(e){return e==="percent"||e==="with ties"||e==="percent with ties"}var Jn=f(()=>{Wa();$()});var eS,Du=f(()=>{$();eS=l({is(e){return e.kind==="OrActionNode"},create(e){return l({kind:"OrActionNode",action:e})}})});var zu=f(()=>{});var Qn,Ba=f(()=>{Qn=class{numDeletedRows;constructor(o){this.numDeletedRows=o}}});var Gt,Ir=f(()=>{$();Gt=l({is(e){return e.kind==="LimitNode"},create(e){return l({kind:"LimitNode",limit:e})}})});var ae,Ua,Fu=f(()=>{Gn();fo();Tr();Oo();$();Mr();Ba();Wn();Ir();zt();po();jo();Jn();Ua=class{#e;constructor(o){this.#e=l(o)}where(...o){return new ae({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,pe(o))})}whereRef(o,t,n){return new ae({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,xe(o,t,n))})}clearWhere(){return new ae({...this.#e,queryNode:P.cloneWithoutWhere(this.#e.queryNode)})}top(o,t){return new ae({...this.#e,queryNode:P.cloneWithTop(this.#e.queryNode,Qt(o,t))})}using(o){return new ae({...this.#e,queryNode:Bt.cloneWithUsing(this.#e.queryNode,gt(o))})}innerJoin(...o){return this.#o("InnerJoin",o)}leftJoin(...o){return this.#o("LeftJoin",o)}rightJoin(...o){return this.#o("RightJoin",o)}fullJoin(...o){return this.#o("FullJoin",o)}#o(o,t){return new ae({...this.#e,queryNode:P.cloneWithJoin(this.#e.queryNode,Ht(o,t))})}returning(o){return new ae({...this.#e,queryNode:P.cloneWithReturning(this.#e.queryNode,Eo(o))})}returningAll(o){return new ae({...this.#e,queryNode:P.cloneWithReturning(this.#e.queryNode,mo(o))})}output(o){return new ae({...this.#e,queryNode:P.cloneWithOutput(this.#e.queryNode,Eo(o))})}outputAll(o){return new ae({...this.#e,queryNode:P.cloneWithOutput(this.#e.queryNode,mo(o))})}clearReturning(){return new ae({...this.#e,queryNode:P.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new ae({...this.#e,queryNode:Bt.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...o){return new ae({...this.#e,queryNode:P.cloneWithOrderByItems(this.#e.queryNode,to(o))})}clearOrderBy(){return new ae({...this.#e,queryNode:P.cloneWithoutOrderBy(this.#e.queryNode)})}limit(o){return new ae({...this.#e,queryNode:Bt.cloneWithLimit(this.#e.queryNode,Gt.create(Z(o)))})}modifyEnd(o){return new ae({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,o.toOperationNode())})}$call(o){return o(this)}$if(o,t){return o?t(this):new ae({...this.#e})}$castTo(){return new ae(this.#e)}$narrowType(){return new ae(this.#e)}$assertType(){return new ae(this.#e)}withPlugin(o){return new ae({...this.#e,executor:this.#e.executor.withPlugin(o)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(o){let t=this.compile(),n=await this.#e.executor.executeQuery(t,o),{adapter:r}=this.#e.executor,a=t.query;return a.returning&&r.supportsReturning||a.output&&r.supportsOutput?n.rows:[new Qn(n.numAffectedRows??BigInt(0))]}async executeTakeFirst(o){let[t]=await this.execute(o);return t}async executeTakeFirstOrThrow(o){typeof o=="function"&&(o={errorConstructor:o});let t=await this.executeTakeFirst(o);if(t===void 0){let n=o?.errorConstructor??Ko;throw Jt(n)?new n(this.toOperationNode()):n(this.toOperationNode())}return t}async*stream(o){typeof o!="object"&&(o={chunkSize:o});let t=this.compile(),n=this.#e.executor.stream(t,o.chunkSize??100,o);for await(let r of n)yield*r.rows}async explain(o,t){return await new ae({...this.#e,queryNode:P.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};ae=Ua});var Hn,Va=f(()=>{Hn=class{numUpdatedRows;numChangedRows;constructor(o,t){this.numUpdatedRows=o,this.numChangedRows=t}}});var se,Ja,Wu=f(()=>{Gn();fo();Tr();Oo();Fn();ku();$();Va();Mr();po();jo();Ir();Jn();zt();Ja=class{#e;constructor(o){this.#e=l(o)}where(...o){return new se({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,pe(o))})}whereRef(o,t,n){return new se({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,xe(o,t,n))})}clearWhere(){return new se({...this.#e,queryNode:P.cloneWithoutWhere(this.#e.queryNode)})}top(o,t){return new se({...this.#e,queryNode:P.cloneWithTop(this.#e.queryNode,Qt(o,t))})}from(o){return new se({...this.#e,queryNode:Wt.cloneWithFromItems(this.#e.queryNode,gt(o))})}innerJoin(...o){return this.#o("InnerJoin",o)}leftJoin(...o){return this.#o("LeftJoin",o)}rightJoin(...o){return this.#o("RightJoin",o)}fullJoin(...o){return this.#o("FullJoin",o)}#o(o,t){return new se({...this.#e,queryNode:P.cloneWithJoin(this.#e.queryNode,Ht(o,t))})}orderBy(...o){return new se({...this.#e,queryNode:P.cloneWithOrderByItems(this.#e.queryNode,to(o))})}clearOrderBy(){return new se({...this.#e,queryNode:P.cloneWithoutOrderBy(this.#e.queryNode)})}limit(o){return new se({...this.#e,queryNode:Wt.cloneWithLimit(this.#e.queryNode,Gt.create(Z(o)))})}set(...o){return new se({...this.#e,queryNode:Wt.cloneWithUpdates(this.#e.queryNode,qu(...o))})}returning(o){return new se({...this.#e,queryNode:P.cloneWithReturning(this.#e.queryNode,Eo(o))})}returningAll(o){return new se({...this.#e,queryNode:P.cloneWithReturning(this.#e.queryNode,mo(o))})}output(o){return new se({...this.#e,queryNode:P.cloneWithOutput(this.#e.queryNode,Eo(o))})}outputAll(o){return new se({...this.#e,queryNode:P.cloneWithOutput(this.#e.queryNode,mo(o))})}modifyEnd(o){return new se({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,o.toOperationNode())})}clearReturning(){return new se({...this.#e,queryNode:P.cloneWithoutReturning(this.#e.queryNode)})}$call(o){return o(this)}$if(o,t){return o?t(this):new se({...this.#e})}$castTo(){return new se(this.#e)}$narrowType(){return new se(this.#e)}$assertType(){return new se(this.#e)}withPlugin(o){return new se({...this.#e,executor:this.#e.executor.withPlugin(o)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(o){let t=this.compile(),n=await this.#e.executor.executeQuery(t,o),{adapter:r}=this.#e.executor,a=t.query;return a.returning&&r.supportsReturning||a.output&&r.supportsOutput?n.rows:[new Hn(n.numAffectedRows??BigInt(0),n.numChangedRows)]}async executeTakeFirst(o){let[t]=await this.execute(o);return t}async executeTakeFirstOrThrow(o){typeof o=="function"&&(o={errorConstructor:o});let t=await this.executeTakeFirst(o);if(t===void 0){let n=o?.errorConstructor??Ko;throw Jt(n)?new n(this.toOperationNode()):n(this.toOperationNode())}return t}async*stream(o){typeof o!="object"&&(o={chunkSize:o});let t=this.compile(),n=this.#e.executor.stream(t,o.chunkSize??100,o);for await(let r of n)yield*r.rows}async explain(o,t){return await new se({...this.#e,queryNode:P.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};se=Ja});var DS,Bu=f(()=>{$();eo();xr();DS=l({is(e){return e.kind==="CommonTableExpressionNameNode"},create(e,o){return l({kind:"CommonTableExpressionNameNode",table:Vo.create(e),columns:o?l(o.map(ue.create)):void 0})}})});var WS,Uu=f(()=>{$();WS=l({is(e){return e.kind==="CommonTableExpressionNode"},create(e,o){return l({kind:"CommonTableExpressionNode",name:e,expression:o})},cloneWith(e,o){return l({...e,...o})}})});var VS,Vu=f(()=>{$();VS=l({is(e){return e.kind==="WithNode"},create(e,o){return l({kind:"WithNode",expressions:l([e]),...o})},cloneWithExpression(e,o){return l({...e,expressions:l([...e.expressions,o])})}})});function Xn(e){let o="";for(let t=0;t<e;++t)o+=Pw();return o}function Pw(){return Ju[~~(Math.random()*Ju.length)]}var Ju,Qa=f(()=>{Ju=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"]});function Le(){return new Ga}var Ga,Yn=f(()=>{Qa();Ga=class{#e;get queryId(){return this.#e===void 0&&(this.#e=Xn(8)),this.#e}}});var Qu=f(()=>{});var Gu=f(()=>{});var ZS,Hu=f(()=>{$();ZS=l({is(e){return e.kind==="MatchedNode"},create(e,o=!1){return l({kind:"MatchedNode",not:e,bySource:o})}})});var Oe,Lr=f(()=>{Oe=class{#e;#o;#r;constructor(){this.#e=new Promise((o,t)=>{this.#r=t,this.#o=o})}get promise(){return this.#e}resolve=o=>{this.#o?.(o),this.#o=this.#r=void 0};reject=o=>{this.#r?.(o),this.#r=this.#o=void 0}}});async function Kn(e,o){let t=new Oe,n=new Oe;return e.provideConnection(async r=>(t.resolve(r),await n.promise),o).catch(r=>t.reject(r)),l({connection:await t.promise,release:n.resolve})}var Xu=f(()=>{Lr();$()});function Ku(e="ignore query",o,t){if(e!=="ignore query"){if(e==="cancel query"){let n=o.cancelQuery;return n||(t(),Yu(e,o.killSession?"kill session":void 0)),n.bind(o)}if(e==="kill session"){let n=o.killSession;return n||(t(),Yu(e,o.cancelQuery?"cancel query":void 0)),n.bind(o)}throw t(),new Error(`Unexpected \`inflightQueryAbortStrategy\`: "${e}"`)}}function Yu(e,o){throw new Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${e}". Use "ignore query"${o?` or "${o}"`:""} instead.`)}function bt(e,o,t){e?.aborted&&(t?.(),wt(e.reason,o))}function wt(e,o){throw Tw(e,o),e}function vt(e){return o=>console.error(`\`${e}\` failed in the background after abortion: ${Jl(o)}`)}function Tw(e,o){e!==null&&typeof e=="object"&&!Object.isFrozen(e)&&Object.defineProperty(e,"__kysely_timing__",{configurable:!0,enumerable:!1,value:o,writable:!1})}var ho,Zu=f(()=>{$();ho={}});var Mw,Zn,ed=f(()=>{$();Xu();Zu();Lr();Mw=l([]),Zn=class{#e;constructor(o=Mw){this.#e=o}get plugins(){return this.#e}transformQuery(o,t){for(let n of this.#e){let r=n.transformQuery({node:o,queryId:t});if(r.kind===o.kind)o=r;else throw new Error(["KyselyPlugin.transformQuery must return a node","of the same kind that was given to it.",`The plugin was given a ${o.kind}`,`but it returned a ${r.kind}`].join(" "))}return o}async executeQuery(o,t){let{inflightQueryAbortStrategy:n="ignore query",signal:r}=t||{};if(!r){let m=await this.provideConnection(async h=>await h.executeQuery(o),t);return await this.#o(m,o.queryId)}bt(r,"before query execution"),t=l({signal:r});let{connection:a,release:s}=await Kn(this,t),c=this.provideConnection.bind(this),{promise:d,resolve:u}=new Oe,p=()=>u(ho);r.addEventListener("abort",p,{once:!0});try{bt(r,"before query execution",s);let m=Ku(n,a,s);if(m&&a.collectSessionInfo){bt(r,"before query execution",s);let w=a.collectSessionInfo();await Promise.race([d,w]).catch(j=>{throw s(),j})===ho&&(w.catch(vt("collectSessionInfo")).finally(s),wt(r.reason,"before query execution"))}let h=a.executeQuery(o,t),b=await Promise.race([d,h]).catch(w=>{throw s(),w});b===ho?(Promise.allSettled([h.catch(vt("query")),m?.(c).catch(vt("inflightQueryAbortHandler"))]).finally(s),wt(r.reason,"during query execution")):s();let y=this.#o(b,o.queryId,t),v=await Promise.race([d,y]);return v===ho&&(y.catch(vt("plugins.transformResult")),wt(r.reason,"during result transformation")),v}finally{u(ho),r.removeEventListener("abort",p)}}async*stream(o,t,n){let{signal:r}=n||{};if(!r){let{connection:b,release:y}=await Kn(this);try{for await(let v of b.streamQuery(o,t))yield await this.#o(v,o.queryId,n)}finally{y()}return}n=l({signal:r}),bt(r,"before connection acquisition");let{connection:a,release:s}=await Kn(this,n),{promise:c,resolve:d}=new Oe,u=()=>d(ho);r.addEventListener("abort",u,{once:!0});let p,m;bt(r,"before query streaming",s);let{queryId:h}=o;try{for(p=a.streamQuery(o,t,n);;){bt(r,"during query streaming");let b=p.next(),y=await Promise.race([c,b]);if(y===ho&&(m=b.catch(vt("iterator.next")),wt(r.reason,"during query streaming")),y.done)break;let v=this.#o(y.value,h,n),w=await Promise.race([c,v]);w===ho&&(m=v.catch(vt("plugins.transformResult")),wt(r.reason,"during result transformation")),yield w}}finally{d(ho),r.removeEventListener("abort",u);let b=(p?.return?.()||Promise.resolve()).finally(()=>m).finally(s);m||await b}}async#o(o,t,n){let{signal:r}=n||{};for(let a of this.#e)o=await a.transformResult(l({queryId:t,result:o,signal:r}));return o}}});var Ha,ei,oi=f(()=>{ed();Ha=class e extends Zn{get adapter(){throw new Error("this query cannot be compiled to SQL")}compileQuery(){throw new Error("this query cannot be compiled to SQL")}provideConnection(){throw new Error("this query cannot be executed")}withConnectionProvider(){throw new Error("this query cannot have a connection provider")}withPlugin(o){return new e([...this.plugins,o])}withPlugins(o){return new e([...this.plugins,...o])}withPluginAtFront(o){return new e([o,...this.plugins])}withoutPlugins(){return new e([])}},ei=new Ha});var od=f(()=>{});var td=f(()=>{});var rd=f(()=>{});function nd(e,o){return new Bn({joinNode:xo.create(e,yt(o))})}function id(){return new Un({overNode:Er.create()})}var Xa=f(()=>{Cr();zn();Ia();Su();fo()});function Ht(e,o){if(o.length===3)return Lw(e,o[0],o[1],o[2]);if(o.length===2)return Iw(e,o[0],o[1]);if(o.length===1)return Dw(e,o[0]);throw new Error("not implemented")}function Iw(e,o,t){return t(nd(e,o)).toOperationNode()}function Lw(e,o,t,n){return xo.createWithOn(e,yt(o),xe(t,"=",n))}function Dw(e,o){return xo.create(e,yt(o))}var Gn=f(()=>{Cr();po();Xa();fo()});var ad,Ya=f(()=>{$();ad=l({is(e){return e.kind==="OffsetNode"},create(e){return l({kind:"OffsetNode",offset:e})}})});var sd,Ka=f(()=>{$();sd=l({is(e){return e.kind==="GroupByItemNode"},create(e){return l({kind:"GroupByItemNode",groupBy:e})}})});function cd(e){return e=$e(e)?e(Ro()):e,Co(e).map(sd.create)}var ld=f(()=>{Ka();Vt();$();Ie()});var ud,Za=f(()=>{$();ud=l({is(e){return e.kind==="SetOperationNode"},create(e,o,t){return l({kind:"SetOperationNode",operator:e,expression:o,all:t})}})});function _t(e,o,t){return $e(o)&&(o=o(es())),ke(o)||(o=[o]),o.map(n=>ud.create(e,Go(n),t))}var dd=f(()=>{Vt();Za();$();ft()});var J,Dr,os,ts,Xt=f(()=>{$o();Jo();ne();Je();dt();Or();po();J=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Dr(this,o)}or(...o){return new os(Ke.create(this.#e,pe(o)))}and(...o){return new ts(Te.create(this.#e,pe(o)))}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},Dr=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Pe.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():M.create(this.#o))}},os=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Dr(this,o)}or(...o){return new e(Ke.create(this.#e,pe(o)))}$castTo(){return new e(this.#e)}toOperationNode(){return Yo.create(this.#e)}},ts=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Dr(this,o)}and(...o){return new e(Te.create(this.#e,pe(o)))}$castTo(){return new e(this.#e)}toOperationNode(){return Yo.create(this.#e)}}});var pd,rs=f(()=>{$();Xo();pd=l({is(e){return e.kind==="FetchNode"},create(e,o){return{kind:"FetchNode",rowCount:Se.create(e),modifier:o}}})});function md(e,o){if(!lo(e)&&!lt(e))throw new Error(`Invalid fetch row count: ${e}`);if(!zw(o))throw new Error(`Invalid fetch modifier: ${o}`);return pd.create(e,o)}function zw(e){return e==="only"||e==="with ties"}var fd=f(()=>{rs();$()});function hd(e){return new ti(e)}var L,ti,ns,is=f(()=>{$o();pa();Gn();fo();Tr();Ie();Pr();Oo();zt();Ir();Ya();$();ld();Mr();ne();dd();po();Xt();jo();fd();Jn();ti=class{#e;constructor(o){this.#e=l(o)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...o){return new L({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,pe(o))})}whereRef(o,t,n){return new L({...this.#e,queryNode:P.cloneWithWhere(this.#e.queryNode,xe(o,t,n))})}having(...o){return new L({...this.#e,queryNode:ee.cloneWithHaving(this.#e.queryNode,pe(o))})}havingRef(o,t,n){return new L({...this.#e,queryNode:ee.cloneWithHaving(this.#e.queryNode,xe(o,t,n))})}select(o){return new L({...this.#e,queryNode:ee.cloneWithSelections(this.#e.queryNode,Eo(o))})}distinctOn(o){return new L({...this.#e,queryNode:ee.cloneWithDistinctOn(this.#e.queryNode,Co(o))})}modifyFront(o){return new L({...this.#e,queryNode:ee.cloneWithFrontModifier(this.#e.queryNode,uo.createWithExpression(o.toOperationNode()))})}modifyEnd(o){return new L({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,uo.createWithExpression(o.toOperationNode()))})}distinct(){return new L({...this.#e,queryNode:ee.cloneWithFrontModifier(this.#e.queryNode,uo.create("Distinct"))})}forUpdate(o){return new L({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,uo.create("ForUpdate",o?$r(o).map(Ce):void 0))})}forShare(o){return new L({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,uo.create("ForShare",o?$r(o).map(Ce):void 0))})}forKeyShare(o){return new L({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,uo.create("ForKeyShare",o?$r(o).map(Ce):void 0))})}forNoKeyUpdate(o){return new L({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,uo.create("ForNoKeyUpdate",o?$r(o).map(Ce):void 0))})}skipLocked(){return new L({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,uo.create("SkipLocked"))})}noWait(){return new L({...this.#e,queryNode:P.cloneWithEndModifier(this.#e.queryNode,uo.create("NoWait"))})}selectAll(o){return new L({...this.#e,queryNode:ee.cloneWithSelections(this.#e.queryNode,mo(o))})}innerJoin(...o){return this.#o("InnerJoin",o)}leftJoin(...o){return this.#o("LeftJoin",o)}rightJoin(...o){return this.#o("RightJoin",o)}fullJoin(...o){return this.#o("FullJoin",o)}crossJoin(...o){return this.#o("CrossJoin",o)}innerJoinLateral(...o){return this.#o("LateralInnerJoin",o)}leftJoinLateral(...o){return this.#o("LateralLeftJoin",o)}crossJoinLateral(...o){return this.#o("LateralCrossJoin",o)}crossApply(...o){return this.#o("CrossApply",o)}outerApply(...o){return this.#o("OuterApply",o)}#o(o,t){return new L({...this.#e,queryNode:P.cloneWithJoin(this.#e.queryNode,Ht(o,t))})}orderBy(...o){return new L({...this.#e,queryNode:P.cloneWithOrderByItems(this.#e.queryNode,to(o))})}groupBy(o){return new L({...this.#e,queryNode:ee.cloneWithGroupByItems(this.#e.queryNode,cd(o))})}limit(o){return new L({...this.#e,queryNode:ee.cloneWithLimit(this.#e.queryNode,Gt.create(Z(o)))})}offset(o){return new L({...this.#e,queryNode:ee.cloneWithOffset(this.#e.queryNode,ad.create(Z(o)))})}fetch(o,t="only"){return new L({...this.#e,queryNode:ee.cloneWithFetch(this.#e.queryNode,md(o,t))})}top(o,t){return new L({...this.#e,queryNode:P.cloneWithTop(this.#e.queryNode,Qt(o,t))})}union(o){return new L({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("union",o,!1))})}unionAll(o){return new L({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("union",o,!0))})}intersect(o){return new L({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("intersect",o,!1))})}intersectAll(o){return new L({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("intersect",o,!0))})}except(o){return new L({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("except",o,!1))})}exceptAll(o){return new L({...this.#e,queryNode:ee.cloneWithSetOperations(this.#e.queryNode,_t("except",o,!0))})}as(o){return new ns(this,o)}clearSelect(){return new L({...this.#e,queryNode:ee.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new L({...this.#e,queryNode:P.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new L({...this.#e,queryNode:ee.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new L({...this.#e,queryNode:ee.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new L({...this.#e,queryNode:P.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new L({...this.#e,queryNode:ee.cloneWithoutGroupBy(this.#e.queryNode)})}$call(o){return o(this)}$if(o,t){return o?t(this):new L({...this.#e})}$castTo(){return new L(this.#e)}$narrowType(){return new L(this.#e)}$assertType(){return new L(this.#e)}$asTuple(){return new J(this.toOperationNode())}$asScalar(){return new J(this.toOperationNode())}withPlugin(o){return new L({...this.#e,executor:this.#e.executor.withPlugin(o)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(o){let t=this.compile();return(await this.#e.executor.executeQuery(t,o)).rows}async executeTakeFirst(o){let[t]=await this.execute(o);return t}async executeTakeFirstOrThrow(o){typeof o=="function"&&(o={errorConstructor:o});let t=await this.executeTakeFirst(o);if(t===void 0){let n=o?.errorConstructor??Ko;throw Jt(n)?new n(this.toOperationNode()):n(this.toOperationNode())}return t}async*stream(o){typeof o!="object"&&(o={chunkSize:o});let t=this.compile(),n=this.#e.executor.stream(t,o.chunkSize??100,o);for await(let r of n)yield*r.rows}async explain(o,t){return await new L({...this.#e,queryNode:P.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};L=ti;ns=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return Pe.create(this.#e.toOperationNode(),M.create(this.#o))}}});var go,ri=f(()=>{$();qr();Ar();go=l({is(e){return e.kind==="AggregateFunctionNode"},create(e,o=[]){return l({kind:"AggregateFunctionNode",func:e,aggregated:o})},cloneWithDistinct(e){return l({...e,distinct:!0})},cloneWithOrderBy(e,o,t=!1){let n=t?"withinGroup":"orderBy";return l({...e,[n]:e[n]?So.cloneWithItems(e[n],o):So.create(o)})},cloneWithFilter(e,o){return l({...e,filter:e.filter?ye.cloneWithOperation(e.filter,"And",o):ye.create(o)})},cloneWithOrFilter(e,o){return l({...e,filter:e.filter?ye.cloneWithOperation(e.filter,"Or",o):ye.create(o)})},cloneWithOver(e,o){return l({...e,over:o})}})});var as,ss=f(()=>{$();as=l({is(e){return e.kind==="FunctionNode"},create(e,o){return l({kind:"FunctionNode",func:e,arguments:o})}})});var Yt,cs,ls=f(()=>{$();ri();$o();ne();Xa();po();zt();Oo();Yt=class e{#e;constructor(o){this.#e=l(o)}get expressionType(){}as(o){return new cs(this,o)}distinct(){return new e({...this.#e,aggregateFunctionNode:go.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...o){return new e({...this.#e,aggregateFunctionNode:P.cloneWithOrderByItems(this.#e.aggregateFunctionNode,to(o))})}clearOrderBy(){return new e({...this.#e,aggregateFunctionNode:P.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...o){return new e({...this.#e,aggregateFunctionNode:go.cloneWithOrderBy(this.#e.aggregateFunctionNode,to(o),!0)})}filterWhere(...o){return new e({...this.#e,aggregateFunctionNode:go.cloneWithFilter(this.#e.aggregateFunctionNode,pe(o))})}filterWhereRef(o,t,n){return new e({...this.#e,aggregateFunctionNode:go.cloneWithFilter(this.#e.aggregateFunctionNode,xe(o,t,n))})}over(o){let t=id();return new e({...this.#e,aggregateFunctionNode:go.cloneWithOver(this.#e.aggregateFunctionNode,(o?o(t):t).toOperationNode())})}$call(o){return o(this)}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e.aggregateFunctionNode}},cs=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Pe.create(this.#e.toOperationNode(),M.create(this.#o))}}});function gd(){let e=(t,n)=>new J(as.create(t,Co(n??[]))),o=(t,n)=>new Yt({aggregateFunctionNode:go.create(t,n?Co(n):void 0)});return Object.assign(e,{agg:o,avg(t){return o("avg",[t])},coalesce(...t){return e("coalesce",t)},count(t){return o("count",[t])},countAll(t){return new Yt({aggregateFunctionNode:go.create("count",mo(t))})},max(t){return o("max",[t])},min(t){return o("min",[t])},sum(t){return o("sum",[t])},any(t){return e("any",[t])},jsonAgg(t){return new Yt({aggregateFunctionNode:go.create("json_agg",[H(t)?Ce(t):t.toOperationNode()])})},toJson(t){return new J(as.create("to_json",[H(t)?Ce(t):t.toOperationNode()]))}})}var us=f(()=>{Xt();ri();ss();Ie();Tr();ls();$();fo()});var bd,ds=f(()=>{$();bd=l({is(e){return e.kind==="UnaryOperationNode"},create(e,o){return l({kind:"UnaryOperationNode",operator:e,operand:o})}})});function wd(e,o){if(lu(e))return bd.create(Ze.create(e),fe(o));throw new Error(`invalid unary operator ${JSON.stringify(e)}`)}var vd=f(()=>{It();ds();Ie()});var Ae,ni=f(()=>{$();kr();Ae=l({is(e){return e.kind==="CaseNode"},create(e){return l({kind:"CaseNode",value:e})},cloneWithWhen(e,o){return l({...e,when:l(e.when?[...e.when,o]:[o])})},cloneWithThen(e,o){return l({...e,when:e.when?l([...e.when.slice(0,-1),Ao.cloneWithResult(e.when[e.when.length-1],o)]):void 0})},cloneWith(e,o){return l({...e,...o})}})});var ii,Kt,ai,si,ps=f(()=>{Xt();$();Ie();ni();kr();po();jo();ii=class{#e;constructor(o){this.#e=l(o)}when(...o){return new Kt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Ao.create(pe(o)))})}whenRef(o,t,n){return new Kt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Ao.create(xe(o,t,n)))})}},Kt=class{#e;constructor(o){this.#e=l(o)}then(o){return new ai({...this.#e,node:Ae.cloneWithThen(this.#e.node,In(o)?Sr(o):Z(o))})}thenRef(o){return new ai({...this.#e,node:Ae.cloneWithThen(this.#e.node,fe(o))})}},ai=class{#e;constructor(o){this.#e=l(o)}when(...o){return new Kt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Ao.create(pe(o)))})}whenRef(o,t,n){return new Kt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Ao.create(xe(o,t,n)))})}else(o){return new si({...this.#e,node:Ae.cloneWith(this.#e.node,{else:In(o)?Sr(o):Z(o)})})}elseRef(o){return new si({...this.#e,node:Ae.cloneWith(this.#e.node,{else:fe(o)})})}end(){return new J(Ae.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new J(Ae.cloneWith(this.#e.node,{isStatement:!0}))}},si=class{#e;constructor(o){this.#e=l(o)}end(){return new J(Ae.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new J(Ae.cloneWith(this.#e.node,{isStatement:!0}))}}});var ms,fs=f(()=>{$();ms=l({is(e){return e.kind==="JSONPathLegNode"},create(e,o){return l({kind:"JSONPathLegNode",type:e,value:o})}})});var Fw,Zt,ci,hs,gs=f(()=>{$o();ne();Pn();fs();jr();qn();Je();Xo();Fw=/^#-\d+$/,Zt=class{#e;constructor(o){this.#e=o}at(o){if(typeof o!="number"&&typeof o!="string"||typeof o=="number"&&!Number.isInteger(o)||typeof o=="string"&&o!=="last"&&!Fw.test(o))throw new Error(`Unexpected index value in .at(...): ${o}`);return this.#o("ArrayLocation",o)}key(o){return this.#o("Member",o)}#o(o,t){return Ft.is(this.#e)?new ci(Ft.cloneWithTraversal(this.#e,Ho.is(this.#e.traversal)?Ho.cloneWithLeg(this.#e.traversal,ms.create(o,t)):kn.cloneWithValue(this.#e.traversal,Se.createImmediate(t)))):new ci(Ho.cloneWithLeg(this.#e,ms.create(o,t)))}},ci=class e extends Zt{#e;constructor(o){super(o),this.#e=o}get expressionType(){}as(o){return new hs(this,o)}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},hs=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Pe.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():M.create(this.#o))}}});var bs,ws=f(()=>{$();bs=l({is(e){return e.kind==="TupleNode"},create(e){return l({kind:"TupleNode",values:l(e)})}})});function _d(e){return Ww[e]||Bw.some(o=>o.test(e))}var Ww,Bw,yd,vs=f(()=>{$();Ww=l({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),Bw=l([/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^datetime2\(\d+\)$/,/^varbinary\(\d+\)$/]),yd=l({is(e){return e.kind==="DataTypeNode"},create(e){return l({kind:"DataTypeNode",dataType:e})}})});function Nd(e){if(ie(e))return e.toOperationNode();if(_d(e))return yd.create(e);throw new Error(`invalid column data type ${JSON.stringify(e)}`)}var $d=f(()=>{vs();Je()});var xd,ys=f(()=>{$();xd=l({is(e){return e.kind==="CastNode"},create(e,o){return l({kind:"CastNode",expression:e,dataType:o})}})});function es(e=ei){function o(r,a,s){return new J(Ln(r,a,s))}function t(r,a){return new J(wd(r,a))}let n=Object.assign(o,{fn:void 0,eb:void 0,selectFrom(r){return hd({queryId:Le(),executor:e,queryNode:ee.createFrom(gt(r))})},case(r){return new ii({node:Ae.create(No(r)?void 0:fe(r))})},ref(r,a){return No(a)?new J(Qe(r)):new Zt(mu(r,a))},jsonPath(){return new Zt(Ho.create())},table(r){return new J(Ce(r))},val(r){return new J(Z(r))},refTuple(...r){return new J(bs.create(r.map(fe)))},tuple(...r){return new J(bs.create(r.map(Z)))},lit(r){return new J(Sr(r))},unary:t,not(r){return t("not",r)},exists(r){return t("exists",r)},neg(r){return t("-",r)},between(r,a,s){return new J(Qo.create(fe(r),Ze.create("between"),Te.create(Z(a),Z(s))))},betweenSymmetric(r,a,s){return new J(Qo.create(fe(r),Ze.create("between symmetric"),Te.create(Z(a),Z(s))))},and(r){return ke(r)?new J(Dn(r,"and")):new J(ya(r,"and"))},or(r){return ke(r)?new J(Dn(r,"or")):new J(ya(r,"or"))},parens(...r){let a=pe(r);return Yo.is(a)?new J(a):new J(Yo.create(a))},cast(r,a){return new J(xd.create(fe(r),Nd(a)))}});return n.fn=gd(),n.eb=n,n}function Ro(e){return es()}var Vt=f(()=>{is();Pr();fo();Yn();us();Ie();po();Or();Xt();It();vd();jo();oi();ps();ni();$();gs();xn();Jo();ws();jr();$d();ys()});function Go(e){if(ie(e))return e.toOperationNode();if($e(e))return e(Ro()).toOperationNode();throw new Error(`invalid expression: ${JSON.stringify(e)}`)}function Vn(e){if(ie(e))return e.toOperationNode();if($e(e))return e(Ro()).toOperationNode();throw new Error(`invalid aliased expression: ${JSON.stringify(e)}`)}function mt(e){return _n(e)||eu(e)||$e(e)}var ft=f(()=>{Nn();Je();Vt();$()});function Cd(e){return je(e)&&ie(e)&&H(e.table)&&H(e.alias)}var _s=f(()=>{Je();$()});function gt(e){return ke(e)?e.map(o=>yt(o)):[yt(e)]}function yt(e){return H(e)?Uw(e):Cd(e)?e.toOperationNode():Vn(e)}function Uw(e){let o=" as ";if(e.includes(o)){let[t,n]=e.split(o).map(jd);return Pe.create(Ce(t),M.create(n))}else return Ce(e)}function Ce(e){if(e.includes(".")){let[t,n]=e.split(".").map(jd);return Vo.createWithSchema(t,n)}else return Vo.create(e)}function jd(e){return e.trim()}var fo=f(()=>{$();$o();xr();ft();ne();_s()});var vR,Sd=f(()=>{$();vR=l({is(e){return e.kind==="AddColumnNode"},create(e){return l({kind:"AddColumnNode",column:e})}})});var $R,Od=f(()=>{$();eo();$R=l({is(e){return e.kind==="ColumnDefinitionNode"},create(e,o){return l({kind:"ColumnDefinitionNode",column:ue.create(e),dataType:o})},cloneWithFrontModifier(e,o){return l({...e,frontModifiers:e.frontModifiers?l([...e.frontModifiers,o]):[o]})},cloneWithEndModifier(e,o){return l({...e,endModifiers:e.endModifiers?l([...e.endModifiers,o]):[o]})},cloneWith(e,o){return l({...e,...o})}})});var SR,Ad=f(()=>{$();eo();SR=l({is(e){return e.kind==="DropColumnNode"},create(e){return l({kind:"DropColumnNode",column:ue.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var RR,Ed=f(()=>{$();eo();RR=l({is(e){return e.kind==="RenameColumnNode"},create(e,o){return l({kind:"RenameColumnNode",column:ue.create(e),renameTo:ue.create(o)})}})});var TR,Rd=f(()=>{$();ne();TR=l({is(e){return e.kind==="CheckConstraintNode"},create(e,o){return l({kind:"CheckConstraintNode",expression:e,name:o?M.create(o):void 0})}})});var Vw,LR,qd,Ns=f(()=>{$();Vw=l({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0}),LR=Object.keys(Vw),qd=l({is(e){return e.kind==="ReferencesNode"},create(e,o){return l({kind:"ReferencesNode",table:e,columns:l([...o])})},cloneWithOnDelete(e,o){return l({...e,onDelete:o})},cloneWithOnUpdate(e,o){return l({...e,onUpdate:o})}})});var FR,kd=f(()=>{$();FR=l({is(e){return e.kind==="GeneratedNode"},create(e){return l({kind:"GeneratedNode",...e})},createWithExpression(e){return l({kind:"GeneratedNode",always:!0,expression:e})},cloneWith(e,o){return l({...e,...o})}})});var UR,Pd=f(()=>{$();UR=l({is(e){return e.kind==="DefaultValueNode"},create(e){return l({kind:"DefaultValueNode",defaultValue:e})}})});var Td=f(()=>{});var GR,Md=f(()=>{$();GR=l({is(e){return e.kind==="ModifyColumnNode"},create(e){return l({kind:"ModifyColumnNode",column:e})}})});var ZR,Id=f(()=>{$();ne();Ns();ZR=l({is(e){return e.kind==="ForeignKeyConstraintNode"},create(e,o,t,n){return l({kind:"ForeignKeyConstraintNode",columns:e,references:qd.create(o,t),name:n?M.create(n):void 0})},cloneWith(e,o){return l({...e,...o})}})});var Ld=f(()=>{});var rq,Dd=f(()=>{$();rq=l({is(e){return e.kind==="AddConstraintNode"},create(e){return l({kind:"AddConstraintNode",constraint:e})}})});var lq,zd=f(()=>{ga();$();eo();ne();lq=l({is(e){return e.kind==="UniqueConstraintNode"},create(e,o,t){return H(e.at(0))&&(Dt("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),e=e.map(ue.create)),l({kind:"UniqueConstraintNode",columns:l(e),name:o?M.create(o):void 0,nullsNotDistinct:t})},cloneWith(e,o){return l({...e,...o})}})});var mq,Fd=f(()=>{$();ne();mq=l({is(e){return e.kind==="DropConstraintNode"},create(e){return l({kind:"DropConstraintNode",constraintName:M.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var bq,Wd=f(()=>{$();eo();bq=l({is(e){return e.kind==="AlterColumnNode"},create(e,o,t){return l({kind:"AlterColumnNode",column:ue.create(e),[o]:t})}})});var Bd=f(()=>{});var $q,Ud=f(()=>{$();eo();ne();$q=l({is(e){return e.kind==="PrimaryKeyConstraintNode"},create(e,o){return l({kind:"PrimaryKeyConstraintNode",columns:l(e.map(ue.create)),name:o?M.create(o):void 0})},cloneWith(e,o){return l({...e,...o})}})});var Sq,Vd=f(()=>{$();ne();Sq=l({is(e){return e.kind==="AddIndexNode"},create(e){return l({kind:"AddIndexNode",name:M.create(e)})},cloneWith(e,o){return l({...e,...o})},cloneWithColumns(e,o){return l({...e,columns:[...e.columns||[],...o]})}})});var Rq,Jd=f(()=>{$();ne();Rq=l({is(e){return e.kind==="RenameConstraintNode"},create(e,o){return l({kind:"RenameConstraintNode",oldName:M.create(e),newName:M.create(o)})}})});var Qd=f(()=>{});var Gd=f(()=>{});var Hd=f(()=>{});var Xd=f(()=>{});var Yd=f(()=>{});var Kd=f(()=>{});var Zd=f(()=>{});var ep=f(()=>{});var Bq,op=f(()=>{$();ut();Bq=l({is(e){return e.kind==="CreateViewNode"},create(e){return l({kind:"CreateViewNode",name:Ye.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var tp=f(()=>{});var Gq,rp=f(()=>{$();ut();Gq=l({is(e){return e.kind==="DropViewNode"},create(e){return l({kind:"DropViewNode",name:Ye.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var np=f(()=>{});var ek,ip=f(()=>{$();Mn();Xo();ek=l({is(e){return e.kind==="CreateTypeNode"},create(e){return l({kind:"CreateTypeNode",name:e})},cloneWithEnum(e,o){return l({...e,enum:Tn.create(o.map(Se.createImmediate))})}})});var ap=f(()=>{});var nk,sp=f(()=>{$();nk=l({is(e){return e.kind==="DropTypeNode"},create(e){return Array.isArray(e)||(e=[e]),l({kind:"DropTypeNode",name:e[0],additionalNames:e.slice(1)})},cloneWith(e,o){return l({...e,...o})}})});var cp=f(()=>{});var lk,lp=f(()=>{$();ut();lk=l({is(e){return e.kind==="RefreshMaterializedViewNode"},create(e){return l({kind:"RefreshMaterializedViewNode",name:Ye.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var up=f(()=>{});var mk,dp=f(()=>{$();mk=l({is(e){return e.kind==="AlterTypeNode"},create(e){return l({kind:"AlterTypeNode",name:e})},cloneWith(e,o){return l({...e,...o})}})});var gk,pp=f(()=>{$();gk=l({is(e){return e.kind==="AddValueNode"},create(e){return l({kind:"AddValueNode",value:e})},cloneWith(e,o){return l({...e,...o})}})});var mp=f(()=>{});var yk,fp=f(()=>{$();yk=l({is(e){return e.kind==="RenameValueNode"},create(e,o){return l({kind:"RenameValueNode",oldValue:e,newValue:o})}})});var hp=f(()=>{});var gp=f(()=>{});var bp=f(()=>{});var wp=f(()=>{});var vp=f(()=>{});var yp=f(()=>{});var Jw,Ak,_p=f(()=>{$();Jw=["query","error"],Ak=l(Jw)});var Np=f(()=>{});var $p=f(()=>{Symbol.asyncDispose??=Symbol("Symbol.asyncDispose")});function qo(e){return new $s(e)}var $s,xs,Cs=f(()=>{$o();$();oi();ne();Je();$s=class e{#e;constructor(o){this.#e=l(o)}get expressionType(){}get isRawBuilder(){return!0}as(o){return new xs(this,o)}$castTo(){return new e({...this.#e})}$notNull(){return new e(this.#e)}withPlugin(o){return new e({...this.#e,plugins:this.#e.plugins!==void 0?l([...this.#e.plugins,o]):l([o])})}toOperationNode(){return this.#r(this.#o())}compile(o){return this.#t(this.#o(o))}async execute(o,t){let n=this.#o(o);return n.executeQuery(this.#t(n),t)}#o(o){let t=o!==void 0?o.getExecutor():ei;return this.#e.plugins!==void 0?t.withPlugins(this.#e.plugins):t}#r(o){return o.transformQuery(this.#e.rawNode,this.#e.queryId)}#t(o){return o.compileQuery(this.#r(o),this.#e.queryId)}};xs=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}get rawBuilder(){return this.#e}toOperationNode(){return Pe.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():M.create(this.#o))}}});function xp(e){return ie(e)?e.toOperationNode():Z(e)}var A,Cp=f(()=>{ne();Je();pt();Xo();Ie();fo();jo();Yn();Cs();A=Object.assign((e,...o)=>qo({queryId:Le(),rawNode:de.create(e,o?.map(xp)??[])}),{ref(e){return qo({queryId:Le(),rawNode:de.createWithChild(Qe(e))})},val(e){return qo({queryId:Le(),rawNode:de.createWithChild(Z(e))})},table(e){return qo({queryId:Le(),rawNode:de.createWithChild(Ce(e))})},id(...e){let o=new Array(e.length+1).fill(".");return o[0]="",o[o.length-1]="",qo({queryId:Le(),rawNode:de.create(o,e.map(M.create))})},lit(e){return qo({queryId:Le(),rawNode:de.createWithChild(Se.createImmediate(e))})},raw(e){return qo({queryId:Le(),rawNode:de.createWithSql(e)})},join(e,o=A`, `){let t=new Array(Math.max(2*e.length-1,0)),n=o.toOperationNode();for(let r=0;r<e.length;++r)t[2*r]=xp(e[r]),r!==e.length-1&&(t[2*r+1]=n);return qo({queryId:Le(),rawNode:de.createWithChildren(t)})}})});var jp=f(()=>{});var Yk,Kk,Zk,js=f(()=>{$();Yk=l({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),Kk=l({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),Zk=l({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"})});var Nt,zr=f(()=>{pt();$();Yn();Nt=l({raw(e,o=[]){return l({sql:e,query:de.createWithSql(e),parameters:l(o),queryId:Le()})}})});var Sp=f(()=>{});var Op=f(()=>{});var Ap=f(()=>{});var Ep=f(()=>{});var Rp=f(()=>{});var qp=f(()=>{});var kp=f(()=>{});function Zo(e,o){if(Qw(e)&&o.stack){let t=o.stack.split(`
|
|
4
4
|
`).slice(1).join(`
|
|
5
5
|
`);return e.stack+=`
|
|
6
|
-
${t}`,e}return e}function $w(e){return je(e)&&H(e.stack)}var zr=f(()=>{$()});function Cw(e){return je(e)&&"insertId"in e&&"affectedRows"in e}var xw,jp,Sp=f(()=>{Lr();$();zr();xw=Symbol();jp=class{#e;#o;#r;#t;constructor(o,t){this.#e=o,this.#o=t}async cancelQuery(o){await this.#i(`kill query ${this.#r}`,o)}async collectSessionInfo(){if(this.#r)return;let{threadId:o}=this.#e;if(o!=null)this.#r=o;else{let[{cid:t}]=await this.#n(Nt.raw("select connection_id() as cid"));this.#r=Number(t)}}async executeQuery(o){try{this.#t=o.queryId;let t=await this.#n(o);if(!Cw(t))return{rows:Array.isArray(t)?t:[]};let{insertId:n,affectedRows:r,changedRows:a}=t;return{insertId:n!=null&&n.toString()!=="0"?BigInt(n):void 0,numAffectedRows:r!=null?BigInt(r):void 0,numChangedRows:a!=null?BigInt(a):void 0,rows:[]}}catch(t){throw Zo(t,new Error)}finally{this.#t=void 0}}async killSession(o){try{this.#e.destroy()}catch{}await this.#i(`kill connection ${this.#r}`,o)}async*streamQuery(o,t){this.#t=o.queryId;let n=this.#e.query(o.sql,o.parameters).stream({objectMode:!0});try{for await(let r of n)yield{rows:[r]}}catch(r){if(je(r)&&"code"in r&&r.code==="ERR_STREAM_PREMATURE_CLOSE")return;throw r}finally{this.#t=void 0}}[xw](){this.#e.release()}#n(o){return new Promise((t,n)=>{this.#e.query(o.sql,o.parameters,(r,a)=>{r?n(r):t(a)})})}async#i(o,t){if(!this.#t)return;let{config:n}=this.#e,r=this.#t;if(!this.#o||!n)return await t(async u=>{r.queryId===this.#t?.queryId&&await u.executeQuery(Nt.raw(o,[]))});let{clientFlags:a,maxPacketSize:s,...c}=n,d=this.#o(c);try{await new Promise((u,p)=>{d.connect(m=>{if(m)return p(m);if(r.queryId!==this.#t?.queryId)return u();d.query(o,[],h=>{if(h)return p(h);u()})})})}finally{d.destroy()}}}});var Op=f(()=>{});var Ap=f(()=>{});var Ep=f(()=>{});var qp=f(()=>{});var jw,Rp,kp=f(()=>{Lr();zr();jw=Symbol(),Rp=class{#e;#o;#r;#t;constructor(o,t){this.#e=o,this.#o=t}async cancelQuery(o){return await this.#n(`select pg_cancel_backend(${this.#t})`,o)}async collectSessionInfo(){if(this.#t)return;let{processID:o}=this.#e;if(o)this.#t=o;else{let{rows:[{pid:t}]}=await this.#e.query("select pg_backend_pid() as pid",[]);this.#t=Number(t)}}async executeQuery(o){try{this.#r=o.queryId;let t=await this.#e.query(o.sql,o.parameters),{command:n,rowCount:r,rows:a}=t;return{numAffectedRows:n==="INSERT"||n==="UPDATE"||n==="DELETE"||n==="MERGE"?BigInt(r):void 0,rows:a??[]}}catch(t){throw Zo(t,new Error)}finally{this.#r=void 0}}async killSession(o){return await this.#n(`select pg_terminate_backend(${this.#t})`,o)}async*streamQuery(o,t){if(!this.#o.cursor)throw new Error("`cursor` is not present in your postgres dialect config. It's required to make streaming work in postgres.");this.#r=o.queryId;let n=this.#e.query(new this.#o.cursor(o.sql,o.parameters.slice()));try{for(;;){let r=await n.read(t);if(r.length===0)break;yield{rows:r}}}finally{await n.close(),this.#r=void 0}}[jw](){this.#e.release()}async#n(o,t){if(!this.#r)return;let{controlClient:n,poolOptions:r}=this.#o,a=this.#r;if(!n)return await t(async c=>{a.queryId===this.#r?.queryId&&await c.executeQuery(Nt.raw(o,[]))});let s=new n({...r,password:"password"in r?r.password:void 0});try{if(await s.connect(),a.queryId!==this.#r.queryId)return;await s.query(o,[])}finally{s.end()}}}});var Pp=f(()=>{});var Tp=f(()=>{});var Hk,Xk,Mp=f(()=>{Hk=BigInt("3853314791062309107"),Xk=3600*1e3});var Ip=f(()=>{});var Dp=f(()=>{});var Sw,Ow,Aw,Lp,Fr,zp=f(()=>{$();Lr();zr();Ba();Ir();Sw=Symbol(),Ow=Symbol(),Aw=Symbol(),Lp=class{#e;#o;#r;#t;constructor(o,t){this.#e=o,this.#o=!1,this.#r=t}async beginTransaction(o){let{isolationLevel:t}=o;await new Promise((n,r)=>this.#e.beginTransaction(a=>{a?r(a):n(void 0)},t?Hn(8):void 0,t?this.#n(t):void 0))}async cancelQuery(){if(this.#t)return new Promise(o=>{this.#t?.request.once("requestCompleted",o),this.#e.cancel()||(this.#t?.request.off("requestCompleted",o),o())})}async commitTransaction(){await new Promise((o,t)=>this.#e.commitTransaction(n=>{n?t(n):o(void 0)}))}async connect(){let{promise:o,reject:t,resolve:n}=new Oe;this.#e.connect(a=>{if(a)return t(a);n()}),this.#e.on("error",a=>{a instanceof Error&&"code"in a&&a.code==="ESOCKET"&&(this.#o=!0),console.error(a),t(a)});function r(){t(new Error("The connection ended without ever completing the connection"))}return this.#e.once("end",r),await o,this.#e.off("end",r),this}async executeQuery(o){try{let t=new Oe;this.#t=new Fr({compiledQuery:o,tedious:this.#r,onDone:t}),this.#e.execSql(this.#t.request);let{rowCount:n,rows:r}=await t.promise;return{numAffectedRows:n!==void 0?BigInt(n):void 0,rows:r}}catch(t){throw Zo(t,new Error)}finally{this.#t=void 0}}async rollbackTransaction(o){await new Promise((t,n)=>this.#e.rollbackTransaction(r=>{r?n(r):t(void 0)},o))}async savepoint(o){await new Promise((t,n)=>this.#e.saveTransaction(r=>{r?n(r):t(void 0)},o))}async*streamQuery(o,t){this.#t=new Fr({compiledQuery:o,streamChunkSize:t,tedious:this.#r}),this.#e.execSql(this.#t.request);try{for(;;){let n=await this.#t.readChunk();if(n.length===0||(yield{rows:n},n.length<t))break}}finally{await this.cancelQuery(),this.#t=void 0}}#n(o){let{ISOLATION_LEVEL:t}=this.#r,r={"read committed":t.READ_COMMITTED,"read uncommitted":t.READ_UNCOMMITTED,"repeatable read":t.REPEATABLE_READ,serializable:t.SERIALIZABLE,snapshot:t.SNAPSHOT}[o];if(r===void 0)throw new Error(`Unknown isolation level: ${o}`);return r}[Ow](){return"closed"in this.#e&&this.#e.closed?Promise.resolve():new Promise(o=>{this.#e.once("end",o),this.#e.close()})}async[Sw](){await new Promise((o,t)=>{this.#e.reset(n=>{if(n)return t(n);o()})})}async[Aw](){if(this.#o||this.#i())return!1;try{let o=new Oe,t=new Fr({compiledQuery:Nt.raw("select 1"),onDone:o,tedious:this.#r});return this.#e.execSql(t.request),await o.promise,!0}catch{return!1}}#i(){return"closed"in this.#e&&!!this.#e.closed}},Fr=class{#e;#o;#r;#t;#n;#i;constructor(o){let{compiledQuery:t,onDone:n,streamChunkSize:r,tedious:a}=o;if(this.#o=[],this.#r=r,this.#t={},this.#n=a,n){let s="onDone";this.#t[s]=(c,d)=>{if(c!=="chunkReady"){if(delete this.#t[s],c==="error")return n.reject(d);n.resolve({rowCount:this.#i,rows:this.#o})}}}this.#e=new this.#n.Request(t.sql,(s,c)=>{if(s)return Object.values(this.#t).forEach(d=>d("error",s instanceof AggregateError?s.errors:s));this.#i=c}),this.#a(t.parameters),this.#s()}get request(){return this.#e}readChunk(){let o=this.readChunk.name;return new Promise((t,n)=>{this.#t[o]=(r,a)=>{if(delete this.#t[o],r==="error")return n(a);t(this.#o.splice(0,this.#r))},this.#e.resume()})}#a(o){for(let t=0;t<o.length;t++){let n=o[t];this.#e.addParameter(String(t+1),this.#c(n),n)}}#s(){let o=this.#r?()=>{this.#r<=this.#o.length&&(this.#e.pause(),Object.values(this.#t).forEach(n=>n("chunkReady")))}:()=>{},t=n=>{let r={};for(let a of n)r[a.metadata.colName]=a.value;this.#o.push(r),o()};this.#e.on("row",t),this.#e.once("requestCompleted",()=>{Object.values(this.#t).forEach(n=>n("completed")),this.#e.off("row",t)})}#c(o){return ct(o)||$o(o)||H(o)?this.#n.TYPES.NVarChar:lt(o)||uo(o)&&o%1===0?o<-2147483648||o>2147483647?this.#n.TYPES.BigInt:this.#n.TYPES.Int:uo(o)?this.#n.TYPES.Float:st(o)?this.#n.TYPES.Bit:sa(o)?this.#n.TYPES.DateTime:Il(o)?this.#n.TYPES.VarBinary:this.#n.TYPES.NVarChar}}});var Fp=f(()=>{});var Wp=f(()=>{});var Bp=f(()=>{});var Vp=f(()=>{});var Ew,qw,Rw,Up,Jp=f(()=>{Ir();zr();Ew=Symbol(),qw=Symbol(),Rw=Symbol(),Up=class{#e;#o;#r;#t;#n;constructor(o){this.#e=o}async executeQuery(o){try{let{affectedRows:t,rows:n}=await(this.#t||this.#e).query(o.sql,o.parameters,{rowMode:"object"});return{numAffectedRows:t!=null?BigInt(t):void 0,rows:n||[]}}catch(t){throw Zo(t,new Error)}}async*streamQuery(){throw new Error("Streaming is not supported by PGlite.")}async[Ew](){let{promise:o,reject:t,resolve:n}=new Oe,{promise:r,resolve:a}=new Oe;this.#o=n,this.#r=t,this.#n=this.#e.transaction(async s=>{this.#t=s,a(),await o}),await r}async[qw](){this.#o?.(),await this.#n,this.#o=void 0,this.#r=void 0,this.#t=void 0,this.#n=void 0}async[Rw](){this.#r?.(),await this.#n?.catch(()=>{}),this.#o=void 0,this.#r=void 0,this.#t=void 0,this.#n=void 0}}});var Qp=f(()=>{});var Gp=f(()=>{});var Hp=f(()=>{});var Xp=f(()=>{});var Yp=f(()=>{});var Kp=f(()=>{});var Zp=f(()=>{});var em=f(()=>{});var om=f(()=>{});var ci=f(()=>{hp();Hu();ip();_n();Ht();os();Ru();Pu();ku();Tr();ka();as();Su();La();Fa();Au();is();cs();ps();Gu();Qu();da();_s();bp();up();ei();Ns();Lr();sp();Bd();Kd();Jd();ep();Fd();Vd();Wd();Ud();Sd();Ed();zd();Gd();tp();Xd();Td();Ld();cp();On();bs();pp();lp();dp();vp();yp();Cp();_p();Np();$p();xp();qp();Sp();Op();Ap();Ep();kp();Ip();Tp();Pp();Mp();Dp();Bp();zp();Fp();Wp();Vp();Jp();Qp();Ns();Gp();Hp();zu();Xp();Yp();Kp();Zp();vd();qd();Id();ti();xo();Pd();Ll();Jo();$n();ri();gs();$d();ua();yd();eo();Ia();Tu();Mu();em();zl();Fl();Wl();Yd();Qd();op();hs();$u();jd();Fn();_d();kd();Bl();Vl();Ul();Zd();Hd();Aa();Za();Ad();Er();rs();Cd();Ga();ya();Na();ne();$a();xr();kn();us();Cr();qn();Mr();xa();Fu();Ea();Od();Qa();Ou();ju();la();Je();Lu();wp();Mt();qu();dt();An();Or();Ra();Ln();Sr();Pa();wa();Md();fa();Ao();pt();jn();ws();Nd();Dd();Oa();ut();Cn();ca();kr();Ta();Ha();om();$r();Da();fs();ss();Rd();zn();ja();Tn();Xo();Nu();Rr();qr();Iu();rp();np();ap();fp();mp()});import{BlockList as tm,isIP as kw}from"node:net";var rm,nm,im,am=f(()=>{rm=new tm,nm=new tm;for(let[e,o]of[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.88.99.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]])rm.addSubnet(e,o,"ipv4");for(let[e,o]of[["::",128],["::1",128],["::ffff:0:0",96],["::",96],["64:ff9b::",96],["64:ff9b:1::",48],["100::",64],["2001::",32],["2001:db8::",32],["2002::",16],["fc00::",7],["fe80::",10],["fec0::",10],["ff00::",8]])nm.addSubnet(e,o,"ipv6");im=e=>{let o=kw(e);return o===4?rm.check(e,"ipv4"):o===6?nm.check(e,"ipv6"):!0}});function Wr(e,o){if(!Array.isArray(o)||o.length<1||o.length>100)throw i("Una lista lleva entre 1 y 100 elementos.");let t=new Set,n=o.map((r,a)=>{let s=r&&typeof r=="object"?r:{},c=typeof s.value=="string"?s.value.trim():"",d=typeof s.label=="string"?s.label.trim():"";if(!c||c.length>80||!$s(c))throw i(`El elemento ${a+1} no tiene una clave v\xE1lida.`);if(!d||d.length>80||!$s(d))throw i(`El elemento ${a+1} necesita un nombre (hasta 80 caracteres).`);if(t.has(c))throw i(`La clave \xAB${c}\xBB est\xE1 repetida.`);t.add(c);let u={value:c,label:d};if(s.color!==void 0&&s.color!==null&&s.color!==""){if(typeof s.color!="string"||!Mw.test(s.color))throw i(`El color de \xAB${d}\xBB no es v\xE1lido.`);u.color=s.color}return s.archivado===!0&&(u.archivado=!0),e==="contactTypes"&&Object.assign(u,Iw(s,d)),u});if(!n.some(r=>!r.archivado))throw i("Una lista necesita al menos un elemento sin archivar.");if(e==="dealStages")for(let r of Pw){let a=n.find(s=>s.value===r);if(!a)throw new z(400,"etapa_fija","Las etapas \xABGanada\xBB y \xABPerdida\xBB no se pueden quitar; se pueden renombrar.");if(a.archivado)throw new z(400,"etapa_fija","Las etapas \xABGanada\xBB y \xABPerdida\xBB no se pueden archivar; se pueden renombrar.")}if(e==="contactTypes"){for(let s of sm){let c=n.find(d=>d.value===s);if(!c)throw new z(400,"tipo_fijo","Los tipos \xABCliente\xBB y \xABProveedor\xBB no se pueden quitar; se pueden renombrar.");if(c.archivado)throw new z(400,"tipo_fijo","Los tipos \xABCliente\xBB y \xABProveedor\xBB no se pueden archivar; se pueden renombrar.")}let r=n.find(s=>!/^[a-z0-9][a-z0-9-]{0,59}$/.test(s.value));if(r)throw i(`La clave \xAB${r.value}\xBB de un tipo: min\xFAsculas, n\xFAmeros y guiones.`);let a=n.find(s=>s.de&&sm.includes(s.value));if(a)throw i(`\xAB${a.label}\xBB no puede ser un tipo de otro.`)}if(e==="legalForms"){let r=n.find(a=>!/^[a-z0-9][a-z0-9-]{0,59}$/.test(a.value));if(r)throw i(`La clave \xAB${r.value}\xBB de una forma jur\xEDdica: min\xFAsculas, n\xFAmeros y guiones.`)}return n}function Iw(e,o){let t=typeof e.plural=="string"&&e.plural.trim()?e.plural.trim():o;if(t.length>80||!$s(t))throw i(`El plural de \xAB${o}\xBB: hasta 80 caracteres.`);let n={plural:t,objeto:e.objeto==="companies"?"companies":"contacts",menu:e.menu===!0};if(e.objetos!==void 0){if(!Array.isArray(e.objetos)||e.objetos.length<1||e.objetos.length>2||new Set(e.objetos).size!==e.objetos.length||!e.objetos.includes(n.objeto)||e.objetos.some(r=>r!=="contacts"&&r!=="companies"))throw i("Las listas del tipo deben incluir su objeto principal y solo Personas o Empresas, sin repetir.");n.objetos=e.objetos}if(e.de!==void 0&&e.de!==null&&e.de!==""){if(e.de!=="cliente"&&e.de!=="proveedor")throw i(`\xAB${o}\xBB: solo puede ser un tipo de Cliente o de Proveedor.`);n.de=e.de}if(e.campoNif!==void 0){if(typeof e.campoNif!="string"||!/^[a-z][a-z0-9_]*$/.test(e.campoNif))throw i("El campo del NIF debe ser una clave de campo propio.");n.campoNif=e.campoNif}if(e.icono!==void 0&&e.icono!==null&&e.icono!==""){if(typeof e.icono!="string"||!Tw.test(e.icono))throw i(`El icono de \xAB${o}\xBB no es v\xE1lido.`);n.icono=e.icono}return n}var Pw,sm,Tw,$s,Mw,xs=f(()=>{q();Pw=["won","lost"],sm=["cliente","proveedor"],Tw=/^[a-z0-9-]{1,40}$/,$s=e=>!/[\u0000-\u001f\u007f]/.test(e),Mw=/^#[0-9a-fA-F]{3,8}$|^[a-z]{3,20}$/});function cm(e){let o=new Map(e.filter(s=>!s.archivado&&s.completarDesde).map(s=>[s.clave,s])),t=new Map,n=new Set,r=[],a=s=>{if(n.has(s.clave))throw i("El autocompletado necesita dependencias sin ciclos y hasta seis pasos.");if(t.has(s.clave))return t.get(s.clave);n.add(s.clave);let c=0;for(let d of Cs(s)){let u=o.get(d.relacion);u&&(c=Math.max(c,a(u)+1))}if(c>6)throw i("El autocompletado necesita dependencias sin ciclos y hasta seis pasos.");return n.delete(s.clave),t.set(s.clave,c),r.push(s),c};for(let s of o.values())a(s);return r}var Cs,lm=f(()=>{q();Cs=e=>e.completarDesde?[e.completarDesde,...e.completarDesde.alternativa?[e.completarDesde.alternativa]:[]]:[]});function um(e,o,t){if(e.propiedad!==void 0){if(!Ee(e.propiedad)||o.tipo!=="seleccion"||!o.obligatorio||e.formas!==void 0||e.etiquetas!==void 0||e.vacio!==void 0)throw i("La clasificaci\xF3n propia necesita una selecci\xF3n obligatoria, sin alternativas fiscales, etiquetas ni valor vac\xEDo.");return{propiedad:e.propiedad}}if(e.formas!==void 0&&!Dw(e.formas))throw i("Las formas de clasificaci\xF3n necesitan opciones de Empresa y claves fiscales v\xE1lidas.");let n={};for(let[a,s]of Object.entries(e.formas??{})){if(!Object.hasOwn(t,a)||t[a]!=="companies"||typeof s!="string"||s!==s.trim())throw i("Las formas de clasificaci\xF3n necesitan opciones de Empresa y claves fiscales v\xE1lidas.");Wr("legalForms",[{value:s,label:js(o,a)}]),n[a]=s}if(e.etiquetas!==void 0&&(!Array.isArray(e.etiquetas)||new Set(e.etiquetas).size!==e.etiquetas.length||e.etiquetas.some(a=>typeof a!="string"||!Object.hasOwn(t,a)||t[a]!=="contacts")))throw i("Las etiquetas de clasificaci\xF3n necesitan opciones distintas de Persona.");let r=e.etiquetas??[];for(let a of r){let s=o.opciones?.find(c=>c.valor===a);if(js(o,a).length>60||s?.color&&!/^#[0-9a-fA-F]{6}$/.test(s.color))throw i("La etiqueta de clasificaci\xF3n necesita nombre de hasta 60 caracteres y color #rrggbb.")}for(let a of["contacts","companies"])if(Object.entries(t).filter(([c,d])=>d===a&&!Object.hasOwn(n,c)&&!r.includes(c)).length>1)throw i("Las opciones que comparten objeto necesitan forma jur\xEDdica o etiqueta para conservar su significado.");return{...e.formas!==void 0?{formas:n}:{},...e.etiquetas!==void 0?{etiquetas:r}:{}}}function dm(e,o){if(!o?.formas)return[];let t=e.find(a=>a.clave===o.campo),n=Object.entries(o.formas).map(([a,s])=>({value:s,label:js(t,a),...t.opciones?.find(c=>c.valor===a)?.color?{color:t.opciones.find(c=>c.valor===a).color}:{}})),r=new Map;for(let a of n){let s=r.get(a.value);if(s&&(s.label!==a.label||s.color!==a.color))throw i("Una forma jur\xEDdica de clasificaci\xF3n tiene etiquetas contradictorias.");r.set(a.value,a)}return Wr("legalForms",[...r.values()])}function pm(e,o,t){return o?.propiedad?e.map(n=>n.clave===o.campo?{...n,opciones:n.opciones?.filter(r=>o.valores[r.valor]===t)}:n):e}var Dw,js,mm=f(()=>{q();xs();Br();Dw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);js=(e,o)=>e.opciones?.find(t=>t.valor===o)?.etiqueta??e.etiqueta});var C,fm,hm=f(()=>{C=(e,o,t={})=>({clave:e,tipo:o,enTabla:!1,ordenable:o!=="texto_largo",filtrable:!1,editable:!["contador","fecha_hora","correos","telefonos","etiquetas"].includes(o),...t}),fm=[{clave:"companies",icono:"building-2",campoTitulo:"name",campos:[C("name","texto",{enTabla:!0,ancho:240}),C("website","url",{enTabla:!0,ancho:200}),C("sector","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:companySectors"}),C("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"companies",ancho:160,migracion:"0466_etiquetas_por_objeto.sql"}),C("size","seleccion",{enTabla:!0,filtrable:!0,opciones:[{valor:"1",etiqueta:"1"},{valor:"10",etiqueta:"2-9"},{valor:"50",etiqueta:"10-49"},{valor:"250",etiqueta:"50-249"},{valor:"500",etiqueta:"250+"}],ancho:110}),C("city","texto",{enTabla:!0,ancho:140}),C("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),C("nb_contacts","contador",{enTabla:!0,ancho:110}),C("nb_deals","contador",{enTabla:!0,ancho:130}),C("created_at","fecha_hora",{enTabla:!0,ancho:140}),C("proveedor","booleano",{filtrable:!0,ancho:110}),C("has_newsletter","booleano",{etiqueta:"Comunicaciones",filtrable:!0,migracion:"0490_comunicaciones_empresa.sql"}),C("tipos","seleccion_multiple",{enTabla:!0,ordenable:!1,editable:!1,opciones:"config:contactTypes",ancho:170,migracion:"0439_tipos_contactos.sql"}),C("ubicacion","ubicacion",{etiqueta:"Ubicaci\xF3n",editable:!1,ordenable:!1,migracion:"0452_ubicacion_nativa.sql"}),C("phone_number","telefono",{ancho:150}),C("country","texto",{ancho:130}),C("address","texto"),C("state_abbr","texto",{soloFicha:!0,etiqueta:"Provincia"}),C("zipcode","texto",{ancho:110}),C("linkedin_url","url"),C("revenue","texto",{ancho:130}),C("tax_identifier","texto",{ancho:140}),C("razon_social","texto",{ancho:220,migracion:"0440_datos_fiscales.sql"}),C("forma_juridica","seleccion",{filtrable:!0,opciones:"config:legalForms",ancho:160,migracion:"0440_datos_fiscales.sql"}),C("correo_facturacion","correo",{ancho:220,migracion:"0440_datos_fiscales.sql"}),C("pais_fiscal","texto",{filtrable:!0,editable:!1,ancho:90,migracion:"0440_datos_fiscales.sql"}),C("description","texto_largo",{ancho:260})]},{clave:"contacts",icono:"users",campoTitulo:"first_name",camposTitulo:["first_name","last_name"],campos:[C("ubicacion","ubicacion",{etiqueta:"Ubicaci\xF3n",editable:!1,ordenable:!1,migracion:"0452_ubicacion_nativa.sql"}),C("first_name","texto",{enTabla:!0,ancho:220}),C("last_name","texto",{ancho:150}),C("title","texto",{enTabla:!0,ancho:150}),C("company_id","relacion",{enTabla:!0,relacion:"companies",ancho:180}),C("email_jsonb","correos",{enTabla:!0,ordenable:!1,editable:!0,ancho:220}),C("phone_jsonb","telefonos",{enTabla:!0,ordenable:!1,editable:!0,ancho:150}),C("status","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:noteStatuses",ancho:130}),C("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"contacts",ancho:160}),C("tipos","seleccion_multiple",{enTabla:!0,ordenable:!1,editable:!1,opciones:"config:contactTypes",ancho:170,migracion:"0439_tipos_contactos.sql"}),C("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),C("last_seen","fecha_hora",{enTabla:!0,ancho:140}),C("nb_tasks","contador",{ancho:110}),C("first_seen","fecha_hora",{ancho:140}),C("linkedin_url","url"),C("background","texto_largo",{ancho:260}),C("nif","texto",{soloFicha:!0,sensible:!0,etiqueta:"Identificador fiscal",migracion:"0005_datos_es.sql"}),C("iban","texto",{soloFicha:!0,sensible:!0,etiqueta:"IBAN",migracion:"0005_datos_es.sql"}),C("birthday","fecha",{soloFicha:!0,etiqueta:"Fecha de nacimiento",migracion:"0005_datos_es.sql"}),C("address","texto",{soloFicha:!0,etiqueta:"Direcci\xF3n",migracion:"0005_datos_es.sql"}),C("zipcode","texto",{soloFicha:!0,etiqueta:"C\xF3digo postal",migracion:"0005_datos_es.sql"}),C("city","texto",{soloFicha:!0,etiqueta:"Ciudad",migracion:"0005_datos_es.sql"}),C("province","texto",{soloFicha:!0,etiqueta:"Provincia",migracion:"0005_datos_es.sql"}),C("country","texto",{soloFicha:!0,etiqueta:"Pa\xEDs",migracion:"0005_datos_es.sql"}),C("has_newsletter","booleano",{soloFicha:!0,migracion:"0005_datos_es.sql"}),C("pais_fiscal","texto",{filtrable:!0,editable:!1,ancho:90,migracion:"0440_datos_fiscales.sql"})]},{clave:"deals",icono:"handshake",campoTitulo:"name",campos:[C("name","texto",{enTabla:!0,ancho:240}),C("company_id","relacion",{enTabla:!0,relacion:"companies",ancho:180}),C("stage","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:dealStages",ancho:160}),C("amount","importe",{enTabla:!0,ancho:120}),C("expected_closing_date","fecha",{enTabla:!0,ancho:140}),C("category","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:dealCategories",ancho:150}),C("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"deals",ancho:160,migracion:"0466_etiquetas_por_objeto.sql"}),C("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),C("origen_lead","texto",{etiqueta:"Origen",filtrable:!0,editable:!1,ancho:170,migracion:"0467_oportunidades_origen_actividad.sql"}),C("ultima_actividad","fecha_hora",{etiqueta:"\xDAltima actividad",editable:!1,ancho:150,migracion:"0467_oportunidades_origen_actividad.sql"}),C("created_at","fecha_hora",{ancho:140}),C("updated_at","fecha_hora",{ancho:140}),C("description","texto_largo",{ancho:260})]},{clave:"proyectos",icono:"folder-kanban",campoTitulo:"nombre",campos:[C("nombre","texto",{enTabla:!0,ancho:220}),C("clave","texto",{enTabla:!0,ancho:110,editable:!1}),C("estado","seleccion",{etiqueta:"Estado",enTabla:!0,filtrable:!0,opciones:[{valor:"activo",etiqueta:"Activo",color:"#16a34a"},{valor:"completado",etiqueta:"Completado",color:"#2563eb"},{valor:"archivado",etiqueta:"Archivado",color:"#64748b"}],ancho:120}),C("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),C("fecha_inicio","fecha",{enTabla:!0,ancho:130}),C("fecha_fin","fecha",{enTabla:!0,ancho:130}),C("requiere_aceptacion","booleano",{ancho:120}),C("color","texto",{ancho:100}),C("icono","texto",{ancho:100}),C("descripcion","texto_largo",{ancho:260}),C("creado","fecha_hora",{ancho:140}),C("actualizado","fecha_hora",{ancho:140})]},{clave:"tareas",campoEstado:"columna_id",icono:"check-square",campoTitulo:"titulo",campos:[C("titulo","texto",{enTabla:!0,ancho:240}),C("codigo_corto","texto",{enTabla:!0,ancho:110,editable:!1}),C("proyecto_id","relacion",{enTabla:!0,filtrable:!0,relacion:"proyectos",ancho:170,editable:!1}),C("columna_id","texto",{etiqueta:"Estado",enTabla:!0,filtrable:!0,ancho:130}),C("prioridad","seleccion",{enTabla:!0,filtrable:!0,opciones:[{valor:"baja",etiqueta:"Baja"},{valor:"media",etiqueta:"Media"},{valor:"alta",etiqueta:"Alta"},{valor:"urgente",etiqueta:"Urgente"}],ancho:110}),C("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),C("fecha_entrega","fecha",{enTabla:!0,ancho:130}),C("fecha_inicio","fecha",{ancho:130}),C("estimacion_minutos","numero",{ancho:110}),C("hecho","fecha_hora",{enTabla:!0,editable:!0,marca:!0,ancho:120}),C("contact_id","relacion",{filtrable:!0,relacion:"contacts",ancho:160}),C("descripcion","texto_largo",{ancho:260}),C("creado","fecha_hora",{ancho:140}),C("actualizado","fecha_hora",{ancho:140})]}]});function Ss(e){return/^funciones\.([a-z0-9][a-z0-9-]{0,59})\.[a-z][a-z0-9_]{0,40}$/.exec(e)?.[1]}function zw(e,o){return e==="contacts"&&/^(correo|telefono)(_(trabajo|personal))?$/.test(o)?o.startsWith("correo")?"email_jsonb":"phone_jsonb":Lw[e].includes(o)||/^datos\.[a-z][a-z0-9_]{0,40}$/.test(o)||Ss(o)?o:null}function gm(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>100)throw i("Identidades: hasta 100 restricciones por tipo.");let o=new Set;return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t))throw i("Restricci\xF3n de identidad no v\xE1lida.");let n=t;if(Object.keys(n).some(c=>!["objeto","tipo","nivel","campos"].includes(c))||!["contacts","companies"].includes(String(n.objeto))||typeof n.tipo!="string"||n.tipo!=="*"&&!/^[a-z0-9][a-z0-9-]{0,59}$/.test(n.tipo)||n.tipo==="*"&&n.nivel!==void 0||n.nivel!==void 0&&!["normal","no","lectura"].includes(String(n.nivel)))throw i("Restricci\xF3n de identidad no v\xE1lida.");let r=n.objeto,a=`${r}:${n.tipo}`;if(o.has(a))throw i("Restricci\xF3n de identidad repetida.");o.add(a);let s={};if(n.campos!==void 0){if(!n.campos||typeof n.campos!="object"||Array.isArray(n.campos)||Object.keys(n.campos).length>100)throw i("M\xE1scaras de identidad no v\xE1lidas.");for(let[c,d]of Object.entries(n.campos)){let u=zw(r,c);if(!u||Ss(u)&&Ss(u)!==n.tipo||!["normal","lectura","oculto"].includes(String(d))||Object.hasOwn(s,u))throw i("Campo o nivel de identidad no v\xE1lido.");s[u]=d}}return{objeto:r,tipo:n.tipo,...n.nivel!==void 0?{nivel:n.nivel}:{},...Object.keys(s).length?{campos:s}:{}}})}var Lw,bm=f(()=>{q();Lw={contacts:["nif","iban","birthday","gender","address","zipcode","city","province","country","email_jsonb","phone_jsonb"],companies:["tax_identifier","iban","phone_number","correo_facturacion","address","zipcode","city","state_abbr","country"]}});function wm(e){if(e==null)return;let o=ui(e,["destino","anterior","ciclo","copiar","fechas","estado","precios"]);if(!o.copiar||typeof o.copiar!="object"||Array.isArray(o.copiar)||Object.keys(o.copiar).length>50||!Array.isArray(o.fechas)||!o.fechas.length||o.fechas.length>10)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");let t={anterior:Le(o.anterior),ciclo:Le(o.ciclo),copiar:Object.fromEntries(Object.entries(o.copiar).map(([n,r])=>[Le(n),Le(r)])),fechas:o.fechas.map(n=>{let r=ui(n,["campo","desde","meses"]);if(typeof r.meses!="number"||!Number.isInteger(r.meses)||r.meses<1||r.meses>120)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return{campo:Le(r.campo),desde:Le(r.desde),meses:r.meses}})};if(o.destino!==void 0&&(t.destino=Le(o.destino)),o.estado){let n=ui(o.estado,["campo","valor"]);if(typeof n.valor!="string"||n.valor.length>100)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");t.estado={campo:Le(n.campo),valor:n.valor}}if(o.precios){let n=ui(o.precios,["tabla","fecha","claves","valor","destino"]);if(!Array.isArray(n.claves)||n.claves.length<1||n.claves.length>3)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");t.precios={tabla:Le(n.tabla),fecha:Le(n.fecha),claves:n.claves.map(Le),valor:Le(n.valor),destino:Le(n.destino)}}if(new Set(t.fechas.map(n=>n.campo)).size!==t.fechas.length)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return t}var Le,ui,vm=f(()=>{q();Le=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(e))throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return e},ui=(e,o)=>{if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(t=>!o.includes(t)))throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return e}});var Vr,p1,Fw,ym=f(()=>{Vr=class e{n;d;constructor(o,t=1n){if(t===0n)throw new Error("decimal_division_cero");t<0n&&(o=-o,t=-t);let n=(a,s)=>s===0n?a<0n?-a:a:n(s,a%s),r=n(o,t);this.n=o/r,this.d=t/r}static leer(o){if(typeof o!="string"||!/^-?\d{1,18}(\.\d{1,6})?$/.test(o))throw new Error("decimal_invalido");let[t,n=""]=o.split(".");return new e(BigInt(t+n),10n**BigInt(n.length))}sumar(o){return new e(this.n*o.d+o.n*this.d,this.d*o.d)}restar(o){return this.sumar(new e(-o.n,o.d))}por(o){return new e(this.n*o.n,this.d*o.d)}entre(o){return new e(this.n*o.d,this.d*o.n)}comparar(o){let t=this.n*o.d-o.n*this.d;return t<0n?-1:t>0n?1:0}centimos(){let t=((this.n<0n?-this.n:this.n)*100n*2n+this.d)/(this.d*2n);return this.n<0n?-t:t}texto(){return Fw(this.centimos())}},p1=new Vr(0n),Fw=e=>`${e<0n?"-":""}${(e<0n?-e:e)/100n}.${String((e<0n?-e:e)%100n).padStart(2,"0")}`});function Nm(e,o){if(e==null)return;let t=ve(e,["version","beneficiariosPeriodo","origen","fecha","importe","moneda","unidad","grupo","mantenimiento","ciclo","recuperacion","beneficiarios","motor","documento","cuentan","precios","unidad_recuento","componentes"]),n=ve(t.motor,["reglas","combinar","margenNegativo","equipoPropio","principal","minimo","objetivo","fijoPeriodo"]),r=ve(t.documento,["periodo","estado","total","beneficiario","lineas"]);if(t.version!==2||typeof t.origen!="string"||!/^mod_[a-z][a-z0-9_]{0,40}$/.test(t.origen))throw i("Liquidaci\xF3n v2: versi\xF3n u origen inv\xE1lido.");let a=(v,w)=>{let N=te(v);if(!o.some(j=>j.clave===N&&!j.archivado&&j.tipo===w))throw i("Liquidaci\xF3n v2: campo de documento inv\xE1lido.");return N},s=Object.fromEntries(Object.entries(ve(t.beneficiarios)).map(([v,w])=>{let N=ve(w,["tipo","campo"]);return[te(v),{tipo:xt(N.tipo,["miembro","contacts","companies","registro"]),campo:N.campo==="_dueno"?"_dueno":te(N.campo)}]}));if(!Object.keys(s).length||Object.keys(s).length>20)throw i("Liquidaci\xF3n v2: beneficiarios inv\xE1lidos.");let c=v=>{let w=ve(v,["clave","beneficiario","fijo","porcentaje","resto","equipo","minimo"]),N=te(w.beneficiario);if(!s[N])throw i("Liquidaci\xF3n v2: beneficiario desconocido.");return{clave:te(w.clave),beneficiario:N,...w.fijo!==void 0?{fijo:$t(w.fijo)}:{},...w.porcentaje!==void 0?{porcentaje:Os(w.porcentaje)}:{},...w.resto===!0?{resto:!0}:{},...w.equipo===!0?{equipo:!0}:{},...typeof w.minimo=="boolean"?{minimo:w.minimo}:{}}},d=et(n.reglas).map(v=>{let w=ve(v,["clave","prioridad","modo","desde","hasta","moneda","unidad","si","bolsa","retencion","receptores"]);if(!_m(w.desde)||w.hasta!==void 0&&(!_m(w.hasta)||w.hasta<=w.desde))throw i("Liquidaci\xF3n v2: vigencia inv\xE1lida.");if(typeof w.moneda!="string"||!/^[A-Z]{3}$/.test(w.moneda)||typeof w.unidad!="string"||!w.unidad||w.unidad.length>60)throw i("Liquidaci\xF3n v2: moneda o unidad inv\xE1lida.");let N=w.si===void 0?void 0:ve(w.si,["campo","valores"]);return{clave:te(w.clave),prioridad:di(w.prioridad),modo:xt(w.modo,["exclusiva","acumulable"]),desde:w.desde,...w.hasta?{hasta:w.hasta}:{},moneda:w.moneda,unidad:w.unidad,receptores:et(w.receptores).map(c),...w.bolsa!==void 0?{bolsa:$t(w.bolsa)}:{},...w.retencion!==void 0?{retencion:$t(w.retencion)}:{},...N?{si:{campo:te(N.campo),valores:et(N.valores).map(j=>String(j).slice(0,100))}}:{}}});if(new Set(d.map(v=>v.clave)).size!==d.length)throw i("Liquidaci\xF3n v2: regla duplicada.");let u;if(n.objetivo){let v=ve(n.objetivo,["beneficiario","medida","modo","tramos","consumirBolsa"]),w=et(v.tramos).map(N=>{let j=ve(N,["desde","tasa","garantia","bonus"]);return{desde:di(j.desde),tasa:v.medida==="recuento"?$t(j.tasa):Os(j.tasa),...j.garantia!==void 0?{garantia:$t(j.garantia)}:{},...j.bonus!==void 0?{bonus:$t(j.bonus)}:{}}});if(!w.length||w[0].desde!==0||w.some((N,j)=>j>0&&N.desde<=w[j-1].desde))throw i("Liquidaci\xF3n v2: umbrales inv\xE1lidos.");u={beneficiario:te(v.beneficiario),medida:xt(v.medida,["recuento","importe"]),modo:xt(v.modo,["alcanzado","marginal"]),tramos:w,consumirBolsa:v.consumirBolsa===!0}}let p=n.minimo?ve(n.minimo,["cantidad","modo"]):void 0,m=n.fijoPeriodo?et(n.fijoPeriodo).map(v=>{let w=ve(v,["beneficiario","importe"]);return{beneficiario:te(w.beneficiario),importe:$t(w.importe)}}):void 0;if(m&&new Set(m.map(v=>v.beneficiario)).size!==m.length)throw i("Liquidaci\xF3n v2: fijo de periodo duplicado.");let h={version:2,origen:t.origen,fecha:te(t.fecha),importe:te(t.importe),moneda:te(t.moneda),unidad:te(t.unidad),grupo:t.grupo==="_dueno"?"_dueno":te(t.grupo),beneficiarios:s,motor:{reglas:d,combinar:n.combinar===!0,margenNegativo:n.margenNegativo===!0,equipoPropio:n.equipoPropio===!0,...n.principal?{principal:te(n.principal)}:{},...p?{minimo:{cantidad:di(p.cantidad),modo:xt(p.modo,["umbral","franquicia"])}}:{},...u?{objetivo:u}:{},...m?{fijoPeriodo:m}:{}},documento:{periodo:a(r.periodo,"texto"),estado:a(r.estado,"seleccion"),total:a(r.total,"texto"),beneficiario:a(r.beneficiario,"texto"),lineas:a(r.lineas,"subtabla")},...t.mantenimiento?{mantenimiento:te(t.mantenimiento)}:{}};if(t.beneficiariosPeriodo!==void 0&&(h.beneficiariosPeriodo=et(t.beneficiariosPeriodo,1e4).map(v=>{let w=ve(v,["grupo","beneficiarios"]);if(typeof w.grupo!="string"||!w.grupo||w.grupo.length>100)throw i("Liquidaci\xF3n v2: grupo de periodo inv\xE1lido.");let N=Object.fromEntries(Object.entries(ve(w.beneficiarios)).map(([j,S])=>{if(!s[j]||typeof S!="number"||!Number.isSafeInteger(S)||S<1)throw i("Liquidaci\xF3n v2: beneficiario de periodo inv\xE1lido.");return[j,S]}));return{grupo:w.grupo,beneficiarios:N}}),new Set(h.beneficiariosPeriodo.map(v=>v.grupo)).size!==h.beneficiariosPeriodo.length))throw i("Liquidaci\xF3n v2: grupo de periodo duplicado.");if(t.cuentan){let v=ve(t.cuentan,["campo","valores"]);h.cuentan={campo:te(v.campo),valores:et(v.valores).map(String)}}if(t.unidad_recuento&&(h.unidad_recuento=te(t.unidad_recuento)),t.componentes){let v=ve(t.componentes,["modo","campo"]);h.componentes={modo:xt(v.modo,["todos","principal"]),campo:te(v.campo)}}if(t.precios){let v=ve(t.precios,["tabla","fecha","claves","valor"]);if(h.precios={tabla:te(v.tabla),fecha:te(v.fecha),claves:et(v.claves,3).map(te),valor:te(v.valor)},!h.precios.claves.length)throw i("Liquidaci\xF3n v2: claves de precio ausentes.")}if(t.ciclo&&(h.ciclo=te(t.ciclo)),t.recuperacion){let v=ve(t.recuperacion,["modo","plazo"]);if(h.recuperacion={modo:xt(v.modo,["total","proporcional_dias"]),plazo:di(v.plazo)},h.recuperacion.plazo===0)throw i("Liquidaci\xF3n v2: plazo inv\xE1lido.")}if([h.motor.principal,h.motor.objetivo?.beneficiario,...(h.motor.fijoPeriodo??[]).map(v=>v.beneficiario)].some(v=>v&&!s[v]))throw i("Liquidaci\xF3n v2: beneficiario desconocido.");let b=o.find(v=>v.clave===h.documento.lineas);if(["fuente","concepto","importe"].some(v=>!b.columnas?.some(w=>w.clave===v&&w.tipo==="texto"&&!w.archivado)))throw i("Liquidaci\xF3n v2: columnas de resumen inv\xE1lidas.");let y=o.find(v=>v.clave===h.documento.estado);if(["borrador","aprobada","cerrada","pagada"].some(v=>!y.opciones?.some(w=>w.valor===v)))throw i("Liquidaci\xF3n v2: estados inv\xE1lidos.");return h}var ve,_m,te,Os,$t,et,xt,di,$m=f(()=>{q();ym();ve=(e,o)=>{if(!e||typeof e!="object"||Array.isArray(e))throw i("Liquidaci\xF3n v2: objeto inv\xE1lido.");if(o&&Object.keys(e).some(t=>!o.includes(t)))throw i("Liquidaci\xF3n v2: propiedad desconocida.");return e},_m=e=>typeof e=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(e)&&Number.isFinite(Date.parse(e+"T00:00:00Z"))&&new Date(e+"T00:00:00Z").toISOString().slice(0,10)===e,te=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(e))throw i("Liquidaci\xF3n v2: clave inv\xE1lida.");return e},Os=e=>{if(typeof e!="string")throw i("Liquidaci\xF3n v2: decimal como cadena.");try{if(Vr.leer(e).n<0n)throw new Error("negativo")}catch{throw i("Liquidaci\xF3n v2: decimal inv\xE1lido.")}return e},$t=e=>{let o=Os(e);if(!/^\d{1,18}(?:\.\d{1,2})?$/.test(o))throw i("Liquidaci\xF3n v2: el importe manual admite como m\xE1ximo dos decimales.");return o},et=(e,o=20)=>{if(!Array.isArray(e)||e.length>o)throw i("Liquidaci\xF3n v2: lista inv\xE1lida.");return e},xt=(e,o)=>{if(!o.includes(e))throw i("Liquidaci\xF3n v2: opci\xF3n inv\xE1lida.");return e},di=e=>{if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw i("Liquidaci\xF3n v2: entero inv\xE1lido.");return e}});function xm(e,o){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw i("precios: un objeto.");let t=e,n=["claves","desde","hasta","prioridad","moneda","unidad","valores","solape","falta"];if(Object.keys(t).some(s=>!n.includes(s)))throw i("precios: propiedad desconocida.");let r=(s,c)=>{let d=o.find(u=>u.clave===s&&!u.archivado);if(!d||!c.includes(d.tipo)||d.multiple)throw i("precios: campo inv\xE1lido.");return d.clave},a=(s,c,d)=>{if(!Array.isArray(s)||!s.length||s.length>d||new Set(s).size!==s.length)throw i("precios: lista vac\xEDa, duplicada o demasiado larga.");return s.map(u=>r(u,c))};if(!["bloquear","prioridad"].includes(String(t.solape))||!["bloquear","pendiente"].includes(String(t.falta)))throw i("precios: pol\xEDtica inv\xE1lida.");return{claves:a(t.claves,["texto","seleccion","relacion","numero"],3),desde:r(t.desde,["fecha"]),...t.hasta?{hasta:r(t.hasta,["fecha"])}:{},prioridad:r(t.prioridad,["numero"]),moneda:r(t.moneda,["texto","seleccion"]),unidad:r(t.unidad,["texto","seleccion"]),valores:a(t.valores,["importe","numero","porcentaje"],20),solape:t.solape,falta:t.falta}}var Cm=f(()=>{q()});var jm,Ww,v1,Sm,Om=f(()=>{jm=new Set(["texto","texto_largo","numero","importe","porcentaje","fecha","fecha_hora","hora","duracion","booleano","seleccion","seleccion_multiple","url","correo","telefono","color","codigo","valoracion","autonumero"]),Ww=new Set([...jm,"relacion"]),v1=new Set([...jm,"relacion"]),Sm=new Set([...Ww,"busqueda"])});function Am(e){if(!e||typeof e!="object"||Array.isArray(e))throw i("Fuente operativa no v\xE1lida.");let o=e;if(Object.keys(o).some(t=>!["objeto","tipo"].includes(t)))throw i("Fuente operativa no v\xE1lida.");if(typeof o.objeto=="string"&&Bw.test(o.objeto)&&!Object.hasOwn(o,"tipo"))return{objeto:o.objeto};if((o.objeto==="contacts"||o.objeto==="companies")&&(o.tipo===null||typeof o.tipo=="string"&&Vw.test(o.tipo)))return{objeto:o.objeto,tipo:o.tipo};if(o.objeto==="deals"&&o.tipo===null)return{objeto:"deals",tipo:null};throw i("Fuente operativa no v\xE1lida.")}var Bw,Vw,Em=f(()=>{q();Bw=/^mod_[a-z][a-z0-9_]{0,40}$/,Vw=/^[a-z0-9][a-z0-9-]{0,59}$/});function mi(e,o){if(e==null)return;if(!Ur(e))throw i("\xABrecurso\xBB: un objeto.");pi(e,["capacidad","capacidad_campo","persona"],"recurso");let t={};if(e.capacidad_campo!==void 0&&e.capacidad_campo!==null&&e.capacidad_campo!==""){let n=o.find(r=>r.clave===e.capacidad_campo&&!r.archivado);if(n?.tipo!=="numero")throw i("\xABrecurso.capacidad_campo\xBB: un n\xFAmero de este m\xF3dulo.");t.capacidad_campo=n.clave}if(e.capacidad!==void 0&&e.capacidad!==null){let n=Number(e.capacidad);if(!Number.isInteger(n)||n<1||n>1e4)throw i("\xABrecurso.capacidad\xBB: de 1 a 10 000.");t.capacidad=n}if(e.persona!==void 0&&e.persona!==null){if(e.persona!=="responsable")throw i("\xABrecurso.persona\xBB: \xABresponsable\xBB.");t.persona="responsable"}return t}function fi(e,o){if(e==null)return;if(!Ur(e))throw i("\xABreserva\xBB: un objeto.");pi(e,["fuente_recurso","recurso","modo","inicio","fin","duracion","duracion_fija","plazas","no_ocupan","fuera_de_horario","margen","cupo","acceso","dia","hora_inicio","hora_fin","vigencia_desde","vigencia_hasta"],"reserva");let t=m=>o.find(h=>h.clave===m&&!h.archivado),n=(m,h,b)=>{let y=t(m);if(!y||!h.includes(y.tipo))throw i(`\xABreserva.${b}\xBB: ${h.join(" o ")} de este m\xF3dulo.`);return y},r=n(e.recurso,["relacion"],"recurso"),a=e.fuente_recurso===void 0?void 0:Am(e.fuente_recurso);if(a&&(a.objeto!==r.relacion||!("tipo"in a)||r.tipoContacto&&a.tipo!==r.tipoContacto))throw i("La fuente del recurso no coincide con la relaci\xF3n.");if(!a&&!r.relacion?.startsWith("mod_"))throw i("Una relaci\xF3n nativa requiere su fuente de recurso expl\xEDcita.");let s=e.modo??"puntual";if(s!=="puntual"&&s!=="semanal")throw i("\xABreserva.modo\xBB: \xABpuntual\xBB o \xABsemanal\xBB.");let c={...a?{fuente_recurso:a}:{},recurso:r.clave,modo:s,fuera_de_horario:e.fuera_de_horario==="permitir"?"permitir":"impedir"};if(s==="puntual")c.inicio=n(e.inicio,["fecha_hora","fecha"],"inicio").clave;else{let m=n(e.dia,["seleccion"],"dia");if(!(m.opciones??[]).length||(m.opciones??[]).some(h=>Uw(h.valor)===null))throw i("\xABreserva.dia\xBB: una selecci\xF3n con los d\xEDas de la semana (1\u20137, \xABlunes\xBB\u2026 o L M X J V S D).");c.dia=m.clave,c.hora_inicio=n(e.hora_inicio,["hora"],"hora_inicio").clave,e.vigencia_desde&&(c.vigencia_desde=n(e.vigencia_desde,["fecha"],"vigencia_desde").clave),e.vigencia_hasta&&(c.vigencia_hasta=n(e.vigencia_hasta,["fecha"],"vigencia_hasta").clave)}if(e.fuera_de_horario!==void 0&&e.fuera_de_horario!=="impedir"&&e.fuera_de_horario!=="permitir")throw i("\xABreserva.fuera_de_horario\xBB: \xABimpedir\xBB o \xABpermitir\xBB.");if([s==="semanal"?e.hora_fin:e.fin,e.duracion,e.duracion_fija].filter(m=>m!=null&&m!=="").length!==1)throw i(`\xABreserva\xBB: ${s==="semanal"?"una hora de fin":"un fin"}, una duraci\xF3n o una duraci\xF3n fija (solo una).`);if(s==="semanal"&&e.fin)throw i("\xABreserva.fin\xBB: en una semanal, \xABhora_fin\xBB.");if(s==="puntual"&&e.hora_fin)throw i("\xABreserva.hora_fin\xBB: en una puntual, \xABfin\xBB.");if(e.hora_fin)c.hora_fin=n(e.hora_fin,["hora"],"hora_fin").clave;else if(e.fin)c.fin=n(e.fin,["fecha_hora","fecha"],"fin").clave;else if(e.duracion)c.duracion=n(e.duracion,["duracion","numero"],"duracion").clave;else{let m=Number(e.duracion_fija);if(!Number.isInteger(m)||m<1||m>1440)throw i("\xABreserva.duracion_fija\xBB: de 1 a 1440 minutos.");c.duracion_fija=m}let u=m=>t(m)?.tipo==="fecha";if(s==="puntual"&&u(c.inicio)!==(c.fin?u(c.fin):!1))throw i("\xABreserva\xBB: por d\xEDas, la entrada y la salida son dos fechas (sin hora); con hora, las dos con hora (o una duraci\xF3n).");if(e.plazas&&(c.plazas=n(e.plazas,["numero"],"plazas").clave),e.cupo&&(c.cupo=n(e.cupo,["numero"],"cupo").clave),e.margen!==void 0&&e.margen!==null){let m=Number(e.margen);if(!Number.isInteger(m)||m<0||m>240)throw i("\xABreserva.margen\xBB: de 0 a 240 minutos.");m&&(c.margen=m)}function p(m,h){let b=Ur(m)?m:{},y=n(b.campo,["seleccion"],`${h}.campo`),v=Array.isArray(b.valores)?b.valores:[];if(!y||!v.length||v.some(w=>!y.opciones?.some(N=>N.valor===w)))throw i(`\xABreserva.${h}\xBB: una selecci\xF3n y algunas de sus opciones.`);return{campo:y.clave,valores:[...new Set(v)]}}if(e.acceso!==void 0&&e.acceso!==null){if(!Ur(e.acceso))throw i("\xABreserva.acceso\xBB: un objeto.");pi(e.acceso,["antes","despues","bloqueado","puerta_extra_obligatoria"],"reserva.acceso");let m=y=>{let v=y===void 0?0:Number(y);if(!Number.isInteger(v)||v<0||v>240)throw i("\xABreserva.acceso\xBB: de 0 a 240 minutos.");return v},h={antes:m(e.acceso.antes),despues:m(e.acceso.despues)};e.acceso.bloqueado!==void 0&&(h.bloqueado=p(e.acceso.bloqueado,"acceso.bloqueado"));let b=e.acceso.puerta_extra_obligatoria;if(b!==void 0){if(!Ur(b)||typeof b.campo!="string"||!/^[a-z][a-z0-9_]{0,39}$/.test(b.campo))throw i("\xABreserva.acceso.puerta_extra_obligatoria\xBB: clave de un campo TTLock del recurso.");if(pi(b,["campo","mismo_codigo"],"reserva.acceso.puerta_extra_obligatoria"),b.mismo_codigo!==void 0&&typeof b.mismo_codigo!="boolean")throw i("\xABreserva.acceso.puerta_extra_obligatoria.mismo_codigo\xBB: un booleano.");h.puerta_extra_obligatoria={campo:b.campo,...b.mismo_codigo?{mismo_codigo:!0}:{}}}(h.antes||h.despues||h.bloqueado||h.puerta_extra_obligatoria)&&(c.acceso=h)}return e.no_ocupan!==void 0&&e.no_ocupan!==null&&(c.no_ocupan=p(e.no_ocupan,"no_ocupan")),c}function Uw(e){let o=String(e??"").trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"");return{1:1,lunes:1,l:1,lun:1,monday:1,2:2,martes:2,m:2,mar:2,tuesday:2,3:3,miercoles:3,x:3,mie:3,wednesday:3,4:4,jueves:4,j:4,jue:4,thursday:4,5:5,viernes:5,v:5,vie:5,friday:5,6:6,sabado:6,s:6,sab:6,saturday:6,7:7,domingo:7,d:7,dom:7,sunday:7}[o]??null}var Ur,pi,As=f(()=>{q();Em();Ur=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pi=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`\xAB${t}\xBB: clave no admitida \xAB${n.slice(0,40)}\xBB.`)}});function Qw(e){let o=[],t=0;for(;t<e.length;){let n=e[t];if(/\s/.test(n)){t++;continue}if(o.length>=qm)throw i(`F\xF3rmula demasiado larga: como mucho ${qm} piezas.`);if(/[0-9]/.test(n)||n==="."&&/[0-9]/.test(e[t+1]??"")){let s=/^[0-9]*\.?[0-9]+|^[0-9]+/.exec(e.slice(t));if(s[0].length>20)throw i("F\xF3rmula: n\xFAmero demasiado largo.");o.push({t:"num",v:s[0]}),t+=s[0].length;continue}if(n==='"'||n==="'"){let s="",c=t+1;for(;;){if(c>=e.length)throw i("F\xF3rmula: falta cerrar unas comillas.");if(e[c]===n){if(e[c+1]===n){s+=n,c+=2;continue}break}s+=e[c],c++}if(s.length>500)throw i("F\xF3rmula: un texto de como mucho 500 caracteres.");o.push({t:"txt",v:s}),t=c+1;continue}if(n==="{"){let s=e.indexOf("}",t);if(s<0)throw i("F\xF3rmula: falta cerrar una llave \xAB}\xBB.");let c=e.slice(t+1,s).trim();if(!c||c.length>80)throw i("F\xF3rmula: un campo entre llaves no v\xE1lido.");o.push({t:"campo",v:c}),t=s+1;continue}let r=/^[A-Za-zÁÉÍÓÚÜÑáéíóúüñ_][A-Za-z0-9ÁÉÍÓÚÜÑáéíóúüñ_.]*/.exec(e.slice(t));if(r){if(r[0].length>40)throw i("F\xF3rmula: nombre demasiado largo.");o.push({t:"id",v:r[0]}),t+=r[0].length;continue}let a=Jw.find(s=>e.startsWith(s,t));if(!a)throw i(`F\xF3rmula: no se entiende \xAB${n}\xBB.`);o.push({t:"op",v:a==="!="?"<>":a===";"?",":a}),t+=a.length}return o.push({t:"fin"}),o}function Hw(e){let o=Qw(e),t=0,n=0,r=()=>o[t],a=w=>r().t==="op"&&r().v===w,s=w=>{if(!a(w))throw i(`F\xF3rmula: se esperaba \xAB${w}\xBB.`);t++},c=w=>{if(++n>Rm)throw i(`F\xF3rmula: como mucho ${Rm} niveles de anidaci\xF3n.`);try{return w()}finally{n--}},d=(w,N,j=!1)=>()=>{let S=N();for(;r().t==="op"&&w.includes(r().v)&&(S={k:"bin",op:o[t++].v,a:S,b:N()},!j););return S},u=()=>c(()=>{let w=r();if(w.t==="num")return t++,{k:"num",v:w.v};if(w.t==="txt")return t++,{k:"txt",v:w.v};if(w.t==="campo")return t++,{k:"campo",v:w.v};if(w.t==="op"&&w.v==="-")return t++,{k:"neg",a:u()};if(w.t==="op"&&w.v==="("){t++;let N=y();return s(")"),N}if(w.t==="id"){t++;let N=Gw(w.v);if(!a("(")){if(N==="VERDADERO"||N==="TRUE")return{k:"bool",v:!0};if(N==="FALSO"||N==="FALSE")return{k:"bool",v:!1};throw i(`F\xF3rmula: \xAB${w.v}\xBB no es una funci\xF3n (los campos van entre llaves: {${w.v}}).`)}t++;let j=[];if(!a(")"))for(;;){if(j.push(y()),j.length>Pm)throw i(`F\xF3rmula: como mucho ${Pm} argumentos.`);if(a(",")){t++;continue}break}return s(")"),{k:"fn",f:N,args:j}}throw i(w.t==="fin"?"F\xF3rmula incompleta.":"F\xF3rmula: algo sobra o falta.")}),p=d(["*","/"],u),m=d(["+","-"],p),h=d(["&"],m),b=d(["=","<>","<","<=",">",">="],h,!0),y=()=>c(b),v=y();if(r().t!=="fin")throw i("F\xF3rmula: algo sobra al final.");return v}function Es(e){if(!ro(e,0))throw i("F\xF3rmula: A\xD1O, MES y DIA necesitan una fecha.");return"numero"}function Mm(e){let o=e[0];for(let t of e.slice(1))o=or(o,t);if(o!=="numero"&&o!=="fecha"&&o!=="fecha_hora")throw i("F\xF3rmula: MIN y MAX, con n\xFAmeros o fechas.");return o}function or(e,o){if(e===o)return e;if(ro([e,o],0)&&ro([e,o],1))return"fecha_hora";throw i(`F\xF3rmula: no se mezclan ${jt[e]} y ${jt[o]}.`)}function hi(e){if(!e)return 0;if(e.k!=="num"||!/^\d+$/.test(e.v)||Number(e.v)>10)throw i("F\xF3rmula: REDONDEAR, con 0 a 10 decimales.");return Number(e.v)}function qs(e,o){let t=Ms(e),n=t.find(r=>r.clave===o)??t.find(r=>r.etiqueta.trim().toLowerCase()===o.trim().toLowerCase());if(!n)throw i(`F\xF3rmula: no hay un campo \xAB${o}\xBB.`);return n}function Rs(e,o,t){if(!o.includes("."))return null;let n=o.trim().toLowerCase();if(Ms(e).some(a=>a.clave===o||a.etiqueta.trim().toLowerCase()===n))return null;let r=t?.[o];if(!r)throw i(`F\xF3rmula: no hay un campo \xAB${o}\xBB.`);return r}function Kw(e){let o=e.saltos.at(-1).modulo;if(Lm[o]){let t=Ee(e.campo)?e.campos.find(r=>r.clave===e.campo&&!r.archivado):void 0,n=t?Ts[t.tipo]:Im[Qr(o).find(r=>r.clave===e.campo)?.tipo??""];if(!n)throw i(`F\xF3rmula: \xAB${e.campo}\xBB no se puede usar en una f\xF3rmula.`);return n}return Dm({campos:e.campos},Yw(e),[])}function Dm(e,o,t){if(o.tipo==="formula")return zm(e,o,t).tipo;let n=o.tipo==="busqueda"||o.tipo==="resumen"?o.origen?.tipo??"":o.tipo,r=Ts[n];if(!r)throw i(`F\xF3rmula: el campo \xAB${o.etiqueta}\xBB no se puede usar en una f\xF3rmula.`);return o.tipo==="busqueda"&&Zw(e,o),r}function Zw(e,o){let t=Ms(e).find(n=>n.clave===o.desde);if(!t?.relacion||t.multiple)throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB trae varios valores y no se usa en una f\xF3rmula.`);if(o.origen?.encadenada)throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB ya va encadenada y no se usa en una f\xF3rmula.`);if(t.relacion.startsWith("mod_")){if(!/^[a-z][a-z0-9_]{0,40}$/.test(o.campo??"")||ev.has(o.origen?.tipo??""))throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB no es v\xE1lida.`)}else{let n=Qr(t.relacion).find(r=>r.clave===o.campo)??(Ee(o.campo)&&o.origen?{tipo:o.origen.tipo}:void 0);if(!n||!(Ee(o.campo)?Ts[n.tipo]:Im[n.tipo])||!Lm[t.relacion])throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB no se puede usar en una f\xF3rmula.`)}return{rel:t}}function zm(e,o,t){if(t.includes(o.clave))throw i(`F\xF3rmula: \xAB${o.etiqueta}\xBB se usa a s\xED misma (en cadena).`);if(t.length>=km)throw i(`F\xF3rmula: como mucho ${km} f\xF3rmulas encadenadas.`);return ov(e,o.formula??"",[...t,o.clave],o.origen?.rutas)}function ov(e,o,t,n){if(typeof o!="string"||!o.trim())throw i("F\xF3rmula vac\xEDa.");if(o.length>no)throw i(`F\xF3rmula de como mucho ${no} caracteres.`);let r=Hw(o),a=new Map,s=u=>{let p=d(u);return a.set(u,p),p},c=(u,p,m)=>{let h=s(u);if(h!==p){if(u.k==="campo"){let y=Rs(e,u.v,n)?u.v:qs(e,u.v).etiqueta;throw i(`F\xF3rmula: \xAB${y}\xBB no es ${jt[p]}, es ${jt[h]} (${m} necesita ${jt[p]}).`)}throw i(`F\xF3rmula: ${m} necesita ${jt[p]} y hay ${jt[h]}.`)}},d=u=>{switch(u.k){case"num":return"numero";case"txt":return"texto";case"bool":return"booleano";case"campo":{let p=Rs(e,u.v,n);return p?Kw(p):Dm(e,qs(e,u.v),t)}case"neg":return c(u.a,"numero","\xAB-\xBB"),"numero";case"bin":return u.op==="&"?(s(u.a),s(u.b),"texto"):["+","-","*","/"].includes(u.op)?(c(u.a,"numero",`\xAB${u.op}\xBB`),c(u.b,"numero",`\xAB${u.op}\xBB`),"numero"):(or(s(u.a),s(u.b)),"booleano");case"fn":{let p=Xw[u.f]??u.f,m=Ps[p];if(!m)throw i(`F\xF3rmula: la funci\xF3n \xAB${u.f}\xBB no existe.`);if(p==="REDONDEAR"&&hi(u.args[1]),p==="PRECIO_VIGENTE"&&(u.args.length<4||u.args.length>6||u.args[0]?.k!=="txt"||u.args[2]?.k!=="txt"))throw i("PRECIO_VIGENTE: tabla y valor literales, fecha y de una a tres claves.");let h=m.args.length-(m.opcionales??0);if(u.args.length<Math.max(h,m.resto?1:0)||!m.resto&&u.args.length>m.args.length)throw i(`F\xF3rmula: ${p} no lleva ${u.args.length} argumentos.`);let b=u.args.map((y,v)=>{let w=m.args[v]??m.resto;return w==="cualquiera"?s(y):(c(y,w,p),w)});return m.tipo(b)}}};return{tipo:s(r),arbol:r,tipos:a,...n?{rutas:n}:{}}}function gi(e){let o={campos:e};return e.map(t=>{if(t.tipo!=="formula"||t.archivado)return t;let n=zm(o,t,[]),r=t.origen?.rutas&&Object.keys(t.origen.rutas).length?t.origen.rutas:void 0;return{...t,formula:tv(o,t.formula,r),origen:{tipo:n.tipo,...r?{rutas:r}:{}}}})}function tv(e,o,t){let n="",r=0;for(;r<o.length;){let a=o[r];if(a==='"'||a==="'"){let s=r+1;for(;s<o.length;)if(o[s]===a&&o[s+1]===a)s+=2;else{if(o[s]===a)break;s++}n+=o.slice(r,s+1),r=s+1;continue}if(a==="{"){let s=o.indexOf("}",r),c=o.slice(r+1,s).trim();n+=`{${Rs(e,c,t)?c:qs(e,c).clave}}`,r=s+1;continue}n+=a,r++}return n}var no,qm,Rm,km,Pm,ks,Jw,Gw,ro,Ct,Tm,er,Ps,Xw,E1,jt,Ts,Im,q1,Ms,Yw,ev,Lm,bi=f(()=>{Br();ci();q();wi();no=1e3,qm=300,Rm=20,km=5,Pm=20,ks="Europe/Madrid",Jw=["<>","!=","<=",">=","=","<",">","+","-","*","/","&","(",")",",",";"];Gw=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").toUpperCase();ro=(e,o)=>e[o]==="fecha"||e[o]==="fecha_hora",Ct=(e,o)=>o==="fecha_hora"?A`(${e} at time zone ${ks})::date`:e,Tm=e=>A`(${e})::text`,er=(e,o)=>A`(least(greatest(${e}, ${-o}::numeric), ${o}::numeric))::int`,Ps={PRECIO_VIGENTE:{args:["texto","fecha","texto","cualquiera"],resto:"cualquiera",tipo:()=>"numero",sql:e=>A`((crm_precio_formula(${e[0]}, ${e[1]}::date, jsonb_build_array(${A.join(e.slice(3).map(o=>A`(${o})::text`),A`, `)}))->'valores'->>${e[2]})::numeric)`},SI:{args:["booleano","cualquiera","cualquiera"],opcionales:1,tipo:e=>or(e[1],e[2]??e[1]),sql:e=>e[2]?A`(case when ${e[0]} then ${e[1]} else ${e[2]} end)`:A`(case when ${e[0]} then ${e[1]} end)`},Y:{args:[],resto:"booleano",tipo:()=>"booleano",sql:e=>A`(${A.join(e,A` and `)})`},O:{args:[],resto:"booleano",tipo:()=>"booleano",sql:e=>A`(${A.join(e,A` or `)})`},NO:{args:["booleano"],tipo:()=>"booleano",sql:e=>A`(not ${e[0]})`},VACIO:{args:["cualquiera"],tipo:()=>"booleano",sql:(e,o)=>o[0]==="texto"?A`(${e[0]} is null or ${e[0]} = '')`:A`(${e[0]} is null)`},REDONDEAR:{args:["numero","numero"],opcionales:1,tipo:()=>"numero",sql:(e,o,t)=>A`round(${e[0]}, ${hi(t[1])}::int)`},ABS:{args:["numero"],tipo:()=>"numero",sql:e=>A`abs(${e[0]})`},MIN:{args:["cualquiera"],resto:"cualquiera",tipo:e=>Mm(e),sql:e=>A`least(${A.join(e)})`},MAX:{args:["cualquiera"],resto:"cualquiera",tipo:e=>Mm(e),sql:e=>A`greatest(${A.join(e)})`},CONCAT:{args:[],resto:"cualquiera",tipo:()=>"texto",sql:e=>A`concat(${A.join(e.map(Tm))})`},MAYUSCULAS:{args:["texto"],tipo:()=>"texto",sql:e=>A`upper(${e[0]})`},MINUSCULAS:{args:["texto"],tipo:()=>"texto",sql:e=>A`lower(${e[0]})`},IZQUIERDA:{args:["texto","numero"],tipo:()=>"texto",sql:e=>A`left(${e[0]}, ${er(e[1],1e4)})`},DERECHA:{args:["texto","numero"],tipo:()=>"texto",sql:e=>A`right(${e[0]}, ${er(e[1],1e4)})`},LARGO:{args:["texto"],tipo:()=>"numero",sql:e=>A`(length(${e[0]}))::numeric`},RECORTAR:{args:["texto"],tipo:()=>"texto",sql:e=>A`btrim(${e[0]})`},TEXTO:{args:["cualquiera"],tipo:()=>"texto",sql:e=>Tm(e[0])},HOY:{args:[],tipo:()=>"fecha",sql:()=>A`(now() at time zone ${ks})::date`},AHORA:{args:[],tipo:()=>"fecha_hora",sql:()=>A`now()`},DIAS_ENTRE:{args:["cualquiera","cualquiera"],tipo:e=>{if(!ro(e,0)||!ro(e,1))throw i("F\xF3rmula: DIAS_ENTRE necesita dos fechas.");return"numero"},sql:(e,o)=>A`((${Ct(e[1],o[1])}) - (${Ct(e[0],o[0])}))::numeric`},ANADIR_DIAS:{args:["cualquiera","numero"],tipo:e=>{if(!ro(e,0))throw i("F\xF3rmula: A\xD1ADIR_DIAS necesita una fecha.");return e[0]},sql:(e,o)=>o[0]==="fecha"?A`(${e[0]} + ${er(e[1],1e5)})`:A`(${e[0]} + make_interval(days => ${er(e[1],1e5)}))`},ANO:{args:["cualquiera"],tipo:e=>Es(e),sql:(e,o)=>A`(extract(year from ${Ct(e[0],o[0])}))::numeric`},MES:{args:["cualquiera"],tipo:e=>Es(e),sql:(e,o)=>A`(extract(month from ${Ct(e[0],o[0])}))::numeric`},DIA:{args:["cualquiera"],tipo:e=>Es(e),sql:(e,o)=>A`(extract(day from ${Ct(e[0],o[0])}))::numeric`},POTENCIA:{args:["numero","numero"],tipo:()=>"numero",sql:e=>A`(case when ${e[0]} is null or ${e[1]} is null then null
|
|
6
|
+
${t}`,e}return e}function Qw(e){return je(e)&&H(e.stack)}var Fr=f(()=>{$()});function Hw(e){return je(e)&&"insertId"in e&&"affectedRows"in e}var Gw,Pp,Tp=f(()=>{zr();$();Fr();Gw=Symbol();Pp=class{#e;#o;#r;#t;constructor(o,t){this.#e=o,this.#o=t}async cancelQuery(o){await this.#i(`kill query ${this.#r}`,o)}async collectSessionInfo(){if(this.#r)return;let{threadId:o}=this.#e;if(o!=null)this.#r=o;else{let[{cid:t}]=await this.#n(Nt.raw("select connection_id() as cid"));this.#r=Number(t)}}async executeQuery(o){try{this.#t=o.queryId;let t=await this.#n(o);if(!Hw(t))return{rows:Array.isArray(t)?t:[]};let{insertId:n,affectedRows:r,changedRows:a}=t;return{insertId:n!=null&&n.toString()!=="0"?BigInt(n):void 0,numAffectedRows:r!=null?BigInt(r):void 0,numChangedRows:a!=null?BigInt(a):void 0,rows:[]}}catch(t){throw Zo(t,new Error)}finally{this.#t=void 0}}async killSession(o){try{this.#e.destroy()}catch{}await this.#i(`kill connection ${this.#r}`,o)}async*streamQuery(o,t){this.#t=o.queryId;let n=this.#e.query(o.sql,o.parameters).stream({objectMode:!0});try{for await(let r of n)yield{rows:[r]}}catch(r){if(je(r)&&"code"in r&&r.code==="ERR_STREAM_PREMATURE_CLOSE")return;throw r}finally{this.#t=void 0}}[Gw](){this.#e.release()}#n(o){return new Promise((t,n)=>{this.#e.query(o.sql,o.parameters,(r,a)=>{r?n(r):t(a)})})}async#i(o,t){if(!this.#t)return;let{config:n}=this.#e,r=this.#t;if(!this.#o||!n)return await t(async u=>{r.queryId===this.#t?.queryId&&await u.executeQuery(Nt.raw(o,[]))});let{clientFlags:a,maxPacketSize:s,...c}=n,d=this.#o(c);try{await new Promise((u,p)=>{d.connect(m=>{if(m)return p(m);if(r.queryId!==this.#t?.queryId)return u();d.query(o,[],h=>{if(h)return p(h);u()})})})}finally{d.destroy()}}}});var Mp=f(()=>{});var Ip=f(()=>{});var Lp=f(()=>{});var Dp=f(()=>{});var Xw,zp,Fp=f(()=>{zr();Fr();Xw=Symbol(),zp=class{#e;#o;#r;#t;constructor(o,t){this.#e=o,this.#o=t}async cancelQuery(o){return await this.#n(`select pg_cancel_backend(${this.#t})`,o)}async collectSessionInfo(){if(this.#t)return;let{processID:o}=this.#e;if(o)this.#t=o;else{let{rows:[{pid:t}]}=await this.#e.query("select pg_backend_pid() as pid",[]);this.#t=Number(t)}}async executeQuery(o){try{this.#r=o.queryId;let t=await this.#e.query(o.sql,o.parameters),{command:n,rowCount:r,rows:a}=t;return{numAffectedRows:n==="INSERT"||n==="UPDATE"||n==="DELETE"||n==="MERGE"?BigInt(r):void 0,rows:a??[]}}catch(t){throw Zo(t,new Error)}finally{this.#r=void 0}}async killSession(o){return await this.#n(`select pg_terminate_backend(${this.#t})`,o)}async*streamQuery(o,t){if(!this.#o.cursor)throw new Error("`cursor` is not present in your postgres dialect config. It's required to make streaming work in postgres.");this.#r=o.queryId;let n=this.#e.query(new this.#o.cursor(o.sql,o.parameters.slice()));try{for(;;){let r=await n.read(t);if(r.length===0)break;yield{rows:r}}}finally{await n.close(),this.#r=void 0}}[Xw](){this.#e.release()}async#n(o,t){if(!this.#r)return;let{controlClient:n,poolOptions:r}=this.#o,a=this.#r;if(!n)return await t(async c=>{a.queryId===this.#r?.queryId&&await c.executeQuery(Nt.raw(o,[]))});let s=new n({...r,password:"password"in r?r.password:void 0});try{if(await s.connect(),a.queryId!==this.#r.queryId)return;await s.query(o,[])}finally{s.end()}}}});var Wp=f(()=>{});var Bp=f(()=>{});var SP,OP,Up=f(()=>{SP=BigInt("3853314791062309107"),OP=3600*1e3});var Vp=f(()=>{});var Jp=f(()=>{});var Yw,Kw,Zw,Qp,Wr,Gp=f(()=>{$();zr();Fr();Qa();Lr();Yw=Symbol(),Kw=Symbol(),Zw=Symbol(),Qp=class{#e;#o;#r;#t;constructor(o,t){this.#e=o,this.#o=!1,this.#r=t}async beginTransaction(o){let{isolationLevel:t}=o;await new Promise((n,r)=>this.#e.beginTransaction(a=>{a?r(a):n(void 0)},t?Xn(8):void 0,t?this.#n(t):void 0))}async cancelQuery(){if(this.#t)return new Promise(o=>{this.#t?.request.once("requestCompleted",o),this.#e.cancel()||(this.#t?.request.off("requestCompleted",o),o())})}async commitTransaction(){await new Promise((o,t)=>this.#e.commitTransaction(n=>{n?t(n):o(void 0)}))}async connect(){let{promise:o,reject:t,resolve:n}=new Oe;this.#e.connect(a=>{if(a)return t(a);n()}),this.#e.on("error",a=>{a instanceof Error&&"code"in a&&a.code==="ESOCKET"&&(this.#o=!0),console.error(a),t(a)});function r(){t(new Error("The connection ended without ever completing the connection"))}return this.#e.once("end",r),await o,this.#e.off("end",r),this}async executeQuery(o){try{let t=new Oe;this.#t=new Wr({compiledQuery:o,tedious:this.#r,onDone:t}),this.#e.execSql(this.#t.request);let{rowCount:n,rows:r}=await t.promise;return{numAffectedRows:n!==void 0?BigInt(n):void 0,rows:r}}catch(t){throw Zo(t,new Error)}finally{this.#t=void 0}}async rollbackTransaction(o){await new Promise((t,n)=>this.#e.rollbackTransaction(r=>{r?n(r):t(void 0)},o))}async savepoint(o){await new Promise((t,n)=>this.#e.saveTransaction(r=>{r?n(r):t(void 0)},o))}async*streamQuery(o,t){this.#t=new Wr({compiledQuery:o,streamChunkSize:t,tedious:this.#r}),this.#e.execSql(this.#t.request);try{for(;;){let n=await this.#t.readChunk();if(n.length===0||(yield{rows:n},n.length<t))break}}finally{await this.cancelQuery(),this.#t=void 0}}#n(o){let{ISOLATION_LEVEL:t}=this.#r,r={"read committed":t.READ_COMMITTED,"read uncommitted":t.READ_UNCOMMITTED,"repeatable read":t.REPEATABLE_READ,serializable:t.SERIALIZABLE,snapshot:t.SNAPSHOT}[o];if(r===void 0)throw new Error(`Unknown isolation level: ${o}`);return r}[Kw](){return"closed"in this.#e&&this.#e.closed?Promise.resolve():new Promise(o=>{this.#e.once("end",o),this.#e.close()})}async[Yw](){await new Promise((o,t)=>{this.#e.reset(n=>{if(n)return t(n);o()})})}async[Zw](){if(this.#o||this.#i())return!1;try{let o=new Oe,t=new Wr({compiledQuery:Nt.raw("select 1"),onDone:o,tedious:this.#r});return this.#e.execSql(t.request),await o.promise,!0}catch{return!1}}#i(){return"closed"in this.#e&&!!this.#e.closed}},Wr=class{#e;#o;#r;#t;#n;#i;constructor(o){let{compiledQuery:t,onDone:n,streamChunkSize:r,tedious:a}=o;if(this.#o=[],this.#r=r,this.#t={},this.#n=a,n){let s="onDone";this.#t[s]=(c,d)=>{if(c!=="chunkReady"){if(delete this.#t[s],c==="error")return n.reject(d);n.resolve({rowCount:this.#i,rows:this.#o})}}}this.#e=new this.#n.Request(t.sql,(s,c)=>{if(s)return Object.values(this.#t).forEach(d=>d("error",s instanceof AggregateError?s.errors:s));this.#i=c}),this.#a(t.parameters),this.#s()}get request(){return this.#e}readChunk(){let o=this.readChunk.name;return new Promise((t,n)=>{this.#t[o]=(r,a)=>{if(delete this.#t[o],r==="error")return n(a);t(this.#o.splice(0,this.#r))},this.#e.resume()})}#a(o){for(let t=0;t<o.length;t++){let n=o[t];this.#e.addParameter(String(t+1),this.#c(n),n)}}#s(){let o=this.#r?()=>{this.#r<=this.#o.length&&(this.#e.pause(),Object.values(this.#t).forEach(n=>n("chunkReady")))}:()=>{},t=n=>{let r={};for(let a of n)r[a.metadata.colName]=a.value;this.#o.push(r),o()};this.#e.on("row",t),this.#e.once("requestCompleted",()=>{Object.values(this.#t).forEach(n=>n("completed")),this.#e.off("row",t)})}#c(o){return ct(o)||No(o)||H(o)?this.#n.TYPES.NVarChar:lt(o)||lo(o)&&o%1===0?o<-2147483648||o>2147483647?this.#n.TYPES.BigInt:this.#n.TYPES.Int:lo(o)?this.#n.TYPES.Float:st(o)?this.#n.TYPES.Bit:da(o)?this.#n.TYPES.DateTime:Vl(o)?this.#n.TYPES.VarBinary:this.#n.TYPES.NVarChar}}});var Hp=f(()=>{});var Xp=f(()=>{});var Yp=f(()=>{});var Kp=f(()=>{});var ev,ov,tv,Zp,em=f(()=>{Lr();Fr();ev=Symbol(),ov=Symbol(),tv=Symbol(),Zp=class{#e;#o;#r;#t;#n;constructor(o){this.#e=o}async executeQuery(o){try{let{affectedRows:t,rows:n}=await(this.#t||this.#e).query(o.sql,o.parameters,{rowMode:"object"});return{numAffectedRows:t!=null?BigInt(t):void 0,rows:n||[]}}catch(t){throw Zo(t,new Error)}}async*streamQuery(){throw new Error("Streaming is not supported by PGlite.")}async[ev](){let{promise:o,reject:t,resolve:n}=new Oe,{promise:r,resolve:a}=new Oe;this.#o=n,this.#r=t,this.#n=this.#e.transaction(async s=>{this.#t=s,a(),await o}),await r}async[ov](){this.#o?.(),await this.#n,this.#o=void 0,this.#r=void 0,this.#t=void 0,this.#n=void 0}async[tv](){this.#r?.(),await this.#n?.catch(()=>{}),this.#o=void 0,this.#r=void 0,this.#t=void 0,this.#n=void 0}}});var om=f(()=>{});var tm=f(()=>{});var rm=f(()=>{});var nm=f(()=>{});var im=f(()=>{});var am=f(()=>{});var sm=f(()=>{});var cm=f(()=>{});var lm=f(()=>{});var li=f(()=>{$p();rd();mp();Nn();Xt();is();zu();Wu();Fu();Mr();Ia();us();Tu();Ba();Va();Iu();ls();ps();gs();td();od();ha();Cs();Cp();wp();oi();js();zr();hp();Yd();ap();ep();cp();Hd();Kd();Xd();Zd();Td();Ld();Gd();tp();up();np();Bd();Qd();gp();An();_s();yp();bp();vp();Sp();Op();kp();Ap();Ep();Rp();qp();Dp();Tp();Mp();Ip();Lp();Fp();Vp();Bp();Wp();Up();Jp();Yp();Gp();Hp();Xp();Kp();em();om();js();tm();rm();Gu();nm();im();am();sm();Sd();Dd();Vd();ri();$o();Wd();Ql();Jo();xn();ni();ys();Rd();fa();Od();eo();Fa();Bu();Uu();cm();Gl();Hl();Xl();ip();op();lp();vs();Ru();Pd();Wn();Ad();Fd();Yl();Kl();Zl();sp();rp();ka();rs();Id();Rr();ss();kd();Ka();xa();ja();ne();Sa();Cr();Pn();fs();jr();qn();Ir();Oa();Hu();Pa();Md();Ya();Mu();Pu();ma();Je();Qu();jp();It();Du();dt();En();Ar();Ma();zn();Or();La();Na();Ud();wa();Oo();pt();Sn();Ns();Ed();Jd();qa();ut();jn();pa();Pr();Da();Za();lm();xr();Wa();ws();ds();zd();Fn();Ea();Mn();Xo();Eu();kr();qr();Vu();dp();pp();fp();Np();_p()});import{BlockList as um,isIP as rv}from"node:net";var dm,pm,mm,fm=f(()=>{dm=new um,pm=new um;for(let[e,o]of[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.88.99.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]])dm.addSubnet(e,o,"ipv4");for(let[e,o]of[["::",128],["::1",128],["::ffff:0:0",96],["::",96],["64:ff9b::",96],["64:ff9b:1::",48],["100::",64],["2001::",32],["2001:db8::",32],["2002::",16],["fc00::",7],["fe80::",10],["fec0::",10],["ff00::",8]])pm.addSubnet(e,o,"ipv6");mm=e=>{let o=rv(e);return o===4?dm.check(e,"ipv4"):o===6?pm.check(e,"ipv6"):!0}});function Br(e,o){if(!Array.isArray(o)||o.length<1||o.length>100)throw i("Una lista lleva entre 1 y 100 elementos.");let t=new Set,n=o.map((r,a)=>{let s=r&&typeof r=="object"?r:{},c=typeof s.value=="string"?s.value.trim():"",d=typeof s.label=="string"?s.label.trim():"";if(!c||c.length>80||!Ss(c))throw i(`El elemento ${a+1} no tiene una clave v\xE1lida.`);if(!d||d.length>80||!Ss(d))throw i(`El elemento ${a+1} necesita un nombre (hasta 80 caracteres).`);if(t.has(c))throw i(`La clave \xAB${c}\xBB est\xE1 repetida.`);t.add(c);let u={value:c,label:d};if(s.color!==void 0&&s.color!==null&&s.color!==""){if(typeof s.color!="string"||!av.test(s.color))throw i(`El color de \xAB${d}\xBB no es v\xE1lido.`);u.color=s.color}return s.archivado===!0&&(u.archivado=!0),e==="contactTypes"&&Object.assign(u,sv(s,d)),u});if(!n.some(r=>!r.archivado))throw i("Una lista necesita al menos un elemento sin archivar.");if(e==="dealStages")for(let r of nv){let a=n.find(s=>s.value===r);if(!a)throw new z(400,"etapa_fija","Las etapas \xABGanada\xBB y \xABPerdida\xBB no se pueden quitar; se pueden renombrar.");if(a.archivado)throw new z(400,"etapa_fija","Las etapas \xABGanada\xBB y \xABPerdida\xBB no se pueden archivar; se pueden renombrar.")}if(e==="contactTypes"){for(let s of hm){let c=n.find(d=>d.value===s);if(!c)throw new z(400,"tipo_fijo","Los tipos \xABCliente\xBB y \xABProveedor\xBB no se pueden quitar; se pueden renombrar.");if(c.archivado)throw new z(400,"tipo_fijo","Los tipos \xABCliente\xBB y \xABProveedor\xBB no se pueden archivar; se pueden renombrar.")}let r=n.find(s=>!/^[a-z0-9][a-z0-9-]{0,59}$/.test(s.value));if(r)throw i(`La clave \xAB${r.value}\xBB de un tipo: min\xFAsculas, n\xFAmeros y guiones.`);let a=n.find(s=>s.de&&hm.includes(s.value));if(a)throw i(`\xAB${a.label}\xBB no puede ser un tipo de otro.`)}if(e==="legalForms"){let r=n.find(a=>!/^[a-z0-9][a-z0-9-]{0,59}$/.test(a.value));if(r)throw i(`La clave \xAB${r.value}\xBB de una forma jur\xEDdica: min\xFAsculas, n\xFAmeros y guiones.`)}return n}function sv(e,o){let t=typeof e.plural=="string"&&e.plural.trim()?e.plural.trim():o;if(t.length>80||!Ss(t))throw i(`El plural de \xAB${o}\xBB: hasta 80 caracteres.`);let n={plural:t,objeto:e.objeto==="companies"?"companies":"contacts",menu:e.menu===!0};if(e.objetos!==void 0){if(!Array.isArray(e.objetos)||e.objetos.length<1||e.objetos.length>2||new Set(e.objetos).size!==e.objetos.length||!e.objetos.includes(n.objeto)||e.objetos.some(r=>r!=="contacts"&&r!=="companies"))throw i("Las listas del tipo deben incluir su objeto principal y solo Personas o Empresas, sin repetir.");n.objetos=e.objetos}if(e.de!==void 0&&e.de!==null&&e.de!==""){if(e.de!=="cliente"&&e.de!=="proveedor")throw i(`\xAB${o}\xBB: solo puede ser un tipo de Cliente o de Proveedor.`);n.de=e.de}if(e.campoNif!==void 0){if(typeof e.campoNif!="string"||!/^[a-z][a-z0-9_]*$/.test(e.campoNif))throw i("El campo del NIF debe ser una clave de campo propio.");n.campoNif=e.campoNif}if(e.icono!==void 0&&e.icono!==null&&e.icono!==""){if(typeof e.icono!="string"||!iv.test(e.icono))throw i(`El icono de \xAB${o}\xBB no es v\xE1lido.`);n.icono=e.icono}return n}var nv,hm,iv,Ss,av,Os=f(()=>{R();nv=["won","lost"],hm=["cliente","proveedor"],iv=/^[a-z0-9-]{1,40}$/,Ss=e=>!/[\u0000-\u001f\u007f]/.test(e),av=/^#[0-9a-fA-F]{3,8}$|^[a-z]{3,20}$/});function gm(e){let o=new Map(e.filter(s=>!s.archivado&&s.completarDesde).map(s=>[s.clave,s])),t=new Map,n=new Set,r=[],a=s=>{if(n.has(s.clave))throw i("El autocompletado necesita dependencias sin ciclos y hasta seis pasos.");if(t.has(s.clave))return t.get(s.clave);n.add(s.clave);let c=0;for(let d of As(s)){let u=o.get(d.relacion);u&&(c=Math.max(c,a(u)+1))}if(c>6)throw i("El autocompletado necesita dependencias sin ciclos y hasta seis pasos.");return n.delete(s.clave),t.set(s.clave,c),r.push(s),c};for(let s of o.values())a(s);return r}var As,bm=f(()=>{R();As=e=>e.completarDesde?[e.completarDesde,...e.completarDesde.alternativa?[e.completarDesde.alternativa]:[]]:[]});function wm(e,o,t){if(e.propiedad!==void 0){if(!Ee(e.propiedad)||o.tipo!=="seleccion"||!o.obligatorio||e.formas!==void 0||e.etiquetas!==void 0||e.vacio!==void 0)throw i("La clasificaci\xF3n propia necesita una selecci\xF3n obligatoria, sin alternativas fiscales, etiquetas ni valor vac\xEDo.");return{propiedad:e.propiedad}}if(e.formas!==void 0&&!cv(e.formas))throw i("Las formas de clasificaci\xF3n necesitan opciones de Empresa y claves fiscales v\xE1lidas.");let n={};for(let[a,s]of Object.entries(e.formas??{})){if(!Object.hasOwn(t,a)||t[a]!=="companies"||typeof s!="string"||s!==s.trim())throw i("Las formas de clasificaci\xF3n necesitan opciones de Empresa y claves fiscales v\xE1lidas.");Br("legalForms",[{value:s,label:Es(o,a)}]),n[a]=s}if(e.etiquetas!==void 0&&(!Array.isArray(e.etiquetas)||new Set(e.etiquetas).size!==e.etiquetas.length||e.etiquetas.some(a=>typeof a!="string"||!Object.hasOwn(t,a)||t[a]!=="contacts")))throw i("Las etiquetas de clasificaci\xF3n necesitan opciones distintas de Persona.");let r=e.etiquetas??[];for(let a of r){let s=o.opciones?.find(c=>c.valor===a);if(Es(o,a).length>60||s?.color&&!/^#[0-9a-fA-F]{6}$/.test(s.color))throw i("La etiqueta de clasificaci\xF3n necesita nombre de hasta 60 caracteres y color #rrggbb.")}for(let a of["contacts","companies"])if(Object.entries(t).filter(([c,d])=>d===a&&!Object.hasOwn(n,c)&&!r.includes(c)).length>1)throw i("Las opciones que comparten objeto necesitan forma jur\xEDdica o etiqueta para conservar su significado.");return{...e.formas!==void 0?{formas:n}:{},...e.etiquetas!==void 0?{etiquetas:r}:{}}}function vm(e,o){if(!o?.formas)return[];let t=e.find(a=>a.clave===o.campo),n=Object.entries(o.formas).map(([a,s])=>({value:s,label:Es(t,a),...t.opciones?.find(c=>c.valor===a)?.color?{color:t.opciones.find(c=>c.valor===a).color}:{}})),r=new Map;for(let a of n){let s=r.get(a.value);if(s&&(s.label!==a.label||s.color!==a.color))throw i("Una forma jur\xEDdica de clasificaci\xF3n tiene etiquetas contradictorias.");r.set(a.value,a)}return Br("legalForms",[...r.values()])}function ym(e,o,t){return o?.propiedad?e.map(n=>n.clave===o.campo?{...n,opciones:n.opciones?.filter(r=>o.valores[r.valor]===t)}:n):e}var cv,Es,_m=f(()=>{R();Os();Ur();cv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);Es=(e,o)=>e.opciones?.find(t=>t.valor===o)?.etiqueta??e.etiqueta});var C,Nm,$m=f(()=>{C=(e,o,t={})=>({clave:e,tipo:o,enTabla:!1,ordenable:o!=="texto_largo",filtrable:!1,editable:!["contador","fecha_hora","correos","telefonos","etiquetas"].includes(o),...t}),Nm=[{clave:"companies",icono:"building-2",campoTitulo:"name",campos:[C("name","texto",{enTabla:!0,ancho:240}),C("website","url",{enTabla:!0,ancho:200}),C("sector","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:companySectors"}),C("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"companies",ancho:160,migracion:"0466_etiquetas_por_objeto.sql"}),C("size","seleccion",{enTabla:!0,filtrable:!0,opciones:[{valor:"1",etiqueta:"1"},{valor:"10",etiqueta:"2-9"},{valor:"50",etiqueta:"10-49"},{valor:"250",etiqueta:"50-249"},{valor:"500",etiqueta:"250+"}],ancho:110}),C("city","texto",{enTabla:!0,ancho:140}),C("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),C("nb_contacts","contador",{enTabla:!0,ancho:110}),C("nb_deals","contador",{enTabla:!0,ancho:130}),C("created_at","fecha_hora",{enTabla:!0,ancho:140}),C("proveedor","booleano",{filtrable:!0,ancho:110}),C("has_newsletter","booleano",{etiqueta:"Comunicaciones",filtrable:!0,migracion:"0490_comunicaciones_empresa.sql"}),C("tipos","seleccion_multiple",{enTabla:!0,ordenable:!1,editable:!1,opciones:"config:contactTypes",ancho:170,migracion:"0439_tipos_contactos.sql"}),C("ubicacion","ubicacion",{etiqueta:"Ubicaci\xF3n",editable:!1,ordenable:!1,migracion:"0452_ubicacion_nativa.sql"}),C("phone_number","telefono",{ancho:150}),C("country","texto",{ancho:130}),C("address","texto"),C("state_abbr","texto",{soloFicha:!0,etiqueta:"Provincia"}),C("zipcode","texto",{ancho:110}),C("linkedin_url","url"),C("revenue","texto",{ancho:130}),C("tax_identifier","texto",{ancho:140}),C("razon_social","texto",{ancho:220,migracion:"0440_datos_fiscales.sql"}),C("forma_juridica","seleccion",{filtrable:!0,opciones:"config:legalForms",ancho:160,migracion:"0440_datos_fiscales.sql"}),C("correo_facturacion","correo",{ancho:220,migracion:"0440_datos_fiscales.sql"}),C("pais_fiscal","texto",{filtrable:!0,editable:!1,ancho:90,migracion:"0440_datos_fiscales.sql"}),C("description","texto_largo",{ancho:260})]},{clave:"contacts",icono:"users",campoTitulo:"first_name",camposTitulo:["first_name","last_name"],campos:[C("ubicacion","ubicacion",{etiqueta:"Ubicaci\xF3n",editable:!1,ordenable:!1,migracion:"0452_ubicacion_nativa.sql"}),C("first_name","texto",{enTabla:!0,ancho:220}),C("last_name","texto",{ancho:150}),C("title","texto",{enTabla:!0,ancho:150}),C("company_id","relacion",{enTabla:!0,relacion:"companies",ancho:180}),C("email_jsonb","correos",{enTabla:!0,ordenable:!1,editable:!0,ancho:220}),C("phone_jsonb","telefonos",{enTabla:!0,ordenable:!1,editable:!0,ancho:150}),C("status","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:noteStatuses",ancho:130}),C("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"contacts",ancho:160}),C("tipos","seleccion_multiple",{enTabla:!0,ordenable:!1,editable:!1,opciones:"config:contactTypes",ancho:170,migracion:"0439_tipos_contactos.sql"}),C("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),C("last_seen","fecha_hora",{enTabla:!0,ancho:140}),C("nb_tasks","contador",{ancho:110}),C("first_seen","fecha_hora",{ancho:140}),C("linkedin_url","url"),C("background","texto_largo",{ancho:260}),C("nif","texto",{soloFicha:!0,sensible:!0,etiqueta:"Identificador fiscal",migracion:"0005_datos_es.sql"}),C("iban","texto",{soloFicha:!0,sensible:!0,etiqueta:"IBAN",migracion:"0005_datos_es.sql"}),C("birthday","fecha",{soloFicha:!0,etiqueta:"Fecha de nacimiento",migracion:"0005_datos_es.sql"}),C("address","texto",{soloFicha:!0,etiqueta:"Direcci\xF3n",migracion:"0005_datos_es.sql"}),C("zipcode","texto",{soloFicha:!0,etiqueta:"C\xF3digo postal",migracion:"0005_datos_es.sql"}),C("city","texto",{soloFicha:!0,etiqueta:"Ciudad",migracion:"0005_datos_es.sql"}),C("province","texto",{soloFicha:!0,etiqueta:"Provincia",migracion:"0005_datos_es.sql"}),C("country","texto",{soloFicha:!0,etiqueta:"Pa\xEDs",migracion:"0005_datos_es.sql"}),C("has_newsletter","booleano",{soloFicha:!0,migracion:"0005_datos_es.sql"}),C("pais_fiscal","texto",{filtrable:!0,editable:!1,ancho:90,migracion:"0440_datos_fiscales.sql"})]},{clave:"deals",icono:"handshake",campoTitulo:"name",campos:[C("name","texto",{enTabla:!0,ancho:240}),C("company_id","relacion",{enTabla:!0,relacion:"companies",ancho:180}),C("stage","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:dealStages",ancho:160}),C("amount","importe",{enTabla:!0,ancho:120}),C("expected_closing_date","fecha",{enTabla:!0,ancho:140}),C("category","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:dealCategories",ancho:150}),C("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"deals",ancho:160,migracion:"0466_etiquetas_por_objeto.sql"}),C("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),C("origen_lead","texto",{etiqueta:"Origen",filtrable:!0,editable:!1,ancho:170,migracion:"0467_oportunidades_origen_actividad.sql"}),C("ultima_actividad","fecha_hora",{etiqueta:"\xDAltima actividad",editable:!1,ancho:150,migracion:"0467_oportunidades_origen_actividad.sql"}),C("created_at","fecha_hora",{ancho:140}),C("updated_at","fecha_hora",{ancho:140}),C("description","texto_largo",{ancho:260})]},{clave:"proyectos",icono:"folder-kanban",campoTitulo:"nombre",campos:[C("nombre","texto",{enTabla:!0,ancho:220}),C("clave","texto",{enTabla:!0,ancho:110,editable:!1}),C("estado","seleccion",{etiqueta:"Estado",enTabla:!0,filtrable:!0,opciones:[{valor:"activo",etiqueta:"Activo",color:"#16a34a"},{valor:"completado",etiqueta:"Completado",color:"#2563eb"},{valor:"archivado",etiqueta:"Archivado",color:"#64748b"}],ancho:120}),C("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),C("fecha_inicio","fecha",{enTabla:!0,ancho:130}),C("fecha_fin","fecha",{enTabla:!0,ancho:130}),C("requiere_aceptacion","booleano",{ancho:120}),C("color","texto",{ancho:100}),C("icono","texto",{ancho:100}),C("descripcion","texto_largo",{ancho:260}),C("creado","fecha_hora",{ancho:140}),C("actualizado","fecha_hora",{ancho:140})]},{clave:"tareas",campoEstado:"columna_id",icono:"check-square",campoTitulo:"titulo",campos:[C("titulo","texto",{enTabla:!0,ancho:240}),C("codigo_corto","texto",{enTabla:!0,ancho:110,editable:!1}),C("proyecto_id","relacion",{enTabla:!0,filtrable:!0,relacion:"proyectos",ancho:170,editable:!1}),C("columna_id","texto",{etiqueta:"Estado",enTabla:!0,filtrable:!0,ancho:130}),C("prioridad","seleccion",{enTabla:!0,filtrable:!0,opciones:[{valor:"baja",etiqueta:"Baja"},{valor:"media",etiqueta:"Media"},{valor:"alta",etiqueta:"Alta"},{valor:"urgente",etiqueta:"Urgente"}],ancho:110}),C("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),C("fecha_entrega","fecha",{enTabla:!0,ancho:130}),C("fecha_inicio","fecha",{ancho:130}),C("estimacion_minutos","numero",{ancho:110}),C("hecho","fecha_hora",{enTabla:!0,editable:!0,marca:!0,ancho:120}),C("contact_id","relacion",{filtrable:!0,relacion:"contacts",ancho:160}),C("descripcion","texto_largo",{ancho:260}),C("creado","fecha_hora",{ancho:140}),C("actualizado","fecha_hora",{ancho:140})]}]});function Rs(e){return/^funciones\.([a-z0-9][a-z0-9-]{0,59})\.[a-z][a-z0-9_]{0,40}$/.exec(e)?.[1]}function uv(e,o){return e==="contacts"&&/^(correo|telefono)(_(trabajo|personal))?$/.test(o)?o.startsWith("correo")?"email_jsonb":"phone_jsonb":lv[e].includes(o)||/^datos\.[a-z][a-z0-9_]{0,40}$/.test(o)||Rs(o)?o:null}function xm(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>100)throw i("Identidades: hasta 100 restricciones por tipo.");let o=new Set;return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t))throw i("Restricci\xF3n de identidad no v\xE1lida.");let n=t;if(Object.keys(n).some(c=>!["objeto","tipo","nivel","campos"].includes(c))||!["contacts","companies"].includes(String(n.objeto))||typeof n.tipo!="string"||n.tipo!=="*"&&!/^[a-z0-9][a-z0-9-]{0,59}$/.test(n.tipo)||n.tipo==="*"&&n.nivel!==void 0||n.nivel!==void 0&&!["normal","no","lectura"].includes(String(n.nivel)))throw i("Restricci\xF3n de identidad no v\xE1lida.");let r=n.objeto,a=`${r}:${n.tipo}`;if(o.has(a))throw i("Restricci\xF3n de identidad repetida.");o.add(a);let s={};if(n.campos!==void 0){if(!n.campos||typeof n.campos!="object"||Array.isArray(n.campos)||Object.keys(n.campos).length>100)throw i("M\xE1scaras de identidad no v\xE1lidas.");for(let[c,d]of Object.entries(n.campos)){let u=uv(r,c);if(!u||Rs(u)&&Rs(u)!==n.tipo||!["normal","lectura","oculto"].includes(String(d))||Object.hasOwn(s,u))throw i("Campo o nivel de identidad no v\xE1lido.");s[u]=d}}return{objeto:r,tipo:n.tipo,...n.nivel!==void 0?{nivel:n.nivel}:{},...Object.keys(s).length?{campos:s}:{}}})}var lv,Cm=f(()=>{R();lv={contacts:["nif","iban","birthday","gender","address","zipcode","city","province","country","email_jsonb","phone_jsonb"],companies:["tax_identifier","iban","phone_number","correo_facturacion","address","zipcode","city","state_abbr","country"]}});function jm(e){if(e==null)return;let o=di(e,["destino","anterior","ciclo","copiar","fechas","estado","precios"]);if(!o.copiar||typeof o.copiar!="object"||Array.isArray(o.copiar)||Object.keys(o.copiar).length>50||!Array.isArray(o.fechas)||!o.fechas.length||o.fechas.length>10)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");let t={anterior:De(o.anterior),ciclo:De(o.ciclo),copiar:Object.fromEntries(Object.entries(o.copiar).map(([n,r])=>[De(n),De(r)])),fechas:o.fechas.map(n=>{let r=di(n,["campo","desde","meses"]);if(typeof r.meses!="number"||!Number.isInteger(r.meses)||r.meses<1||r.meses>120)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return{campo:De(r.campo),desde:De(r.desde),meses:r.meses}})};if(o.destino!==void 0&&(t.destino=De(o.destino)),o.estado){let n=di(o.estado,["campo","valor"]);if(typeof n.valor!="string"||n.valor.length>100)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");t.estado={campo:De(n.campo),valor:n.valor}}if(o.precios){let n=di(o.precios,["tabla","fecha","claves","valor","destino"]);if(!Array.isArray(n.claves)||n.claves.length<1||n.claves.length>3)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");t.precios={tabla:De(n.tabla),fecha:De(n.fecha),claves:n.claves.map(De),valor:De(n.valor),destino:De(n.destino)}}if(new Set(t.fechas.map(n=>n.campo)).size!==t.fechas.length)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return t}var De,di,Sm=f(()=>{R();De=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(e))throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return e},di=(e,o)=>{if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(t=>!o.includes(t)))throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return e}});var Vr,U1,dv,Om=f(()=>{Vr=class e{n;d;constructor(o,t=1n){if(t===0n)throw new Error("decimal_division_cero");t<0n&&(o=-o,t=-t);let n=(a,s)=>s===0n?a<0n?-a:a:n(s,a%s),r=n(o,t);this.n=o/r,this.d=t/r}static leer(o){if(typeof o!="string"||!/^-?\d{1,18}(\.\d{1,6})?$/.test(o))throw new Error("decimal_invalido");let[t,n=""]=o.split(".");return new e(BigInt(t+n),10n**BigInt(n.length))}sumar(o){return new e(this.n*o.d+o.n*this.d,this.d*o.d)}restar(o){return this.sumar(new e(-o.n,o.d))}por(o){return new e(this.n*o.n,this.d*o.d)}entre(o){return new e(this.n*o.d,this.d*o.n)}comparar(o){let t=this.n*o.d-o.n*this.d;return t<0n?-1:t>0n?1:0}centimos(){let t=((this.n<0n?-this.n:this.n)*100n*2n+this.d)/(this.d*2n);return this.n<0n?-t:t}texto(){return dv(this.centimos())}},U1=new Vr(0n),dv=e=>`${e<0n?"-":""}${(e<0n?-e:e)/100n}.${String((e<0n?-e:e)%100n).padStart(2,"0")}`});function Em(e,o){if(e==null)return;let t=ve(e,["version","beneficiariosPeriodo","origen","fecha","importe","moneda","unidad","grupo","mantenimiento","ciclo","recuperacion","beneficiarios","motor","documento","cuentan","precios","unidad_recuento","componentes"]),n=ve(t.motor,["reglas","combinar","margenNegativo","equipoPropio","principal","minimo","objetivo","fijoPeriodo"]),r=ve(t.documento,["periodo","estado","total","beneficiario","lineas"]);if(t.version!==2||typeof t.origen!="string"||!/^mod_[a-z][a-z0-9_]{0,40}$/.test(t.origen))throw i("Liquidaci\xF3n v2: versi\xF3n u origen inv\xE1lido.");let a=(v,w)=>{let N=te(v);if(!o.some(j=>j.clave===N&&!j.archivado&&j.tipo===w))throw i("Liquidaci\xF3n v2: campo de documento inv\xE1lido.");return N},s=Object.fromEntries(Object.entries(ve(t.beneficiarios)).map(([v,w])=>{let N=ve(w,["tipo","campo"]);return[te(v),{tipo:xt(N.tipo,["miembro","contacts","companies","registro"]),campo:N.campo==="_dueno"?"_dueno":te(N.campo)}]}));if(!Object.keys(s).length||Object.keys(s).length>20)throw i("Liquidaci\xF3n v2: beneficiarios inv\xE1lidos.");let c=v=>{let w=ve(v,["clave","beneficiario","fijo","porcentaje","resto","equipo","minimo"]),N=te(w.beneficiario);if(!s[N])throw i("Liquidaci\xF3n v2: beneficiario desconocido.");return{clave:te(w.clave),beneficiario:N,...w.fijo!==void 0?{fijo:$t(w.fijo)}:{},...w.porcentaje!==void 0?{porcentaje:qs(w.porcentaje)}:{},...w.resto===!0?{resto:!0}:{},...w.equipo===!0?{equipo:!0}:{},...typeof w.minimo=="boolean"?{minimo:w.minimo}:{}}},d=et(n.reglas).map(v=>{let w=ve(v,["clave","prioridad","modo","desde","hasta","moneda","unidad","si","bolsa","retencion","receptores"]);if(!Am(w.desde)||w.hasta!==void 0&&(!Am(w.hasta)||w.hasta<=w.desde))throw i("Liquidaci\xF3n v2: vigencia inv\xE1lida.");if(typeof w.moneda!="string"||!/^[A-Z]{3}$/.test(w.moneda)||typeof w.unidad!="string"||!w.unidad||w.unidad.length>60)throw i("Liquidaci\xF3n v2: moneda o unidad inv\xE1lida.");let N=w.si===void 0?void 0:ve(w.si,["campo","valores"]);return{clave:te(w.clave),prioridad:pi(w.prioridad),modo:xt(w.modo,["exclusiva","acumulable"]),desde:w.desde,...w.hasta?{hasta:w.hasta}:{},moneda:w.moneda,unidad:w.unidad,receptores:et(w.receptores).map(c),...w.bolsa!==void 0?{bolsa:$t(w.bolsa)}:{},...w.retencion!==void 0?{retencion:$t(w.retencion)}:{},...N?{si:{campo:te(N.campo),valores:et(N.valores).map(j=>String(j).slice(0,100))}}:{}}});if(new Set(d.map(v=>v.clave)).size!==d.length)throw i("Liquidaci\xF3n v2: regla duplicada.");let u;if(n.objetivo){let v=ve(n.objetivo,["beneficiario","medida","modo","tramos","consumirBolsa"]),w=et(v.tramos).map(N=>{let j=ve(N,["desde","tasa","garantia","bonus"]);return{desde:pi(j.desde),tasa:v.medida==="recuento"?$t(j.tasa):qs(j.tasa),...j.garantia!==void 0?{garantia:$t(j.garantia)}:{},...j.bonus!==void 0?{bonus:$t(j.bonus)}:{}}});if(!w.length||w[0].desde!==0||w.some((N,j)=>j>0&&N.desde<=w[j-1].desde))throw i("Liquidaci\xF3n v2: umbrales inv\xE1lidos.");u={beneficiario:te(v.beneficiario),medida:xt(v.medida,["recuento","importe"]),modo:xt(v.modo,["alcanzado","marginal"]),tramos:w,consumirBolsa:v.consumirBolsa===!0}}let p=n.minimo?ve(n.minimo,["cantidad","modo"]):void 0,m=n.fijoPeriodo?et(n.fijoPeriodo).map(v=>{let w=ve(v,["beneficiario","importe"]);return{beneficiario:te(w.beneficiario),importe:$t(w.importe)}}):void 0;if(m&&new Set(m.map(v=>v.beneficiario)).size!==m.length)throw i("Liquidaci\xF3n v2: fijo de periodo duplicado.");let h={version:2,origen:t.origen,fecha:te(t.fecha),importe:te(t.importe),moneda:te(t.moneda),unidad:te(t.unidad),grupo:t.grupo==="_dueno"?"_dueno":te(t.grupo),beneficiarios:s,motor:{reglas:d,combinar:n.combinar===!0,margenNegativo:n.margenNegativo===!0,equipoPropio:n.equipoPropio===!0,...n.principal?{principal:te(n.principal)}:{},...p?{minimo:{cantidad:pi(p.cantidad),modo:xt(p.modo,["umbral","franquicia"])}}:{},...u?{objetivo:u}:{},...m?{fijoPeriodo:m}:{}},documento:{periodo:a(r.periodo,"texto"),estado:a(r.estado,"seleccion"),total:a(r.total,"texto"),beneficiario:a(r.beneficiario,"texto"),lineas:a(r.lineas,"subtabla")},...t.mantenimiento?{mantenimiento:te(t.mantenimiento)}:{}};if(t.beneficiariosPeriodo!==void 0&&(h.beneficiariosPeriodo=et(t.beneficiariosPeriodo,1e4).map(v=>{let w=ve(v,["grupo","beneficiarios"]);if(typeof w.grupo!="string"||!w.grupo||w.grupo.length>100)throw i("Liquidaci\xF3n v2: grupo de periodo inv\xE1lido.");let N=Object.fromEntries(Object.entries(ve(w.beneficiarios)).map(([j,S])=>{if(!s[j]||typeof S!="number"||!Number.isSafeInteger(S)||S<1)throw i("Liquidaci\xF3n v2: beneficiario de periodo inv\xE1lido.");return[j,S]}));return{grupo:w.grupo,beneficiarios:N}}),new Set(h.beneficiariosPeriodo.map(v=>v.grupo)).size!==h.beneficiariosPeriodo.length))throw i("Liquidaci\xF3n v2: grupo de periodo duplicado.");if(t.cuentan){let v=ve(t.cuentan,["campo","valores"]);h.cuentan={campo:te(v.campo),valores:et(v.valores).map(String)}}if(t.unidad_recuento&&(h.unidad_recuento=te(t.unidad_recuento)),t.componentes){let v=ve(t.componentes,["modo","campo"]);h.componentes={modo:xt(v.modo,["todos","principal"]),campo:te(v.campo)}}if(t.precios){let v=ve(t.precios,["tabla","fecha","claves","valor"]);if(h.precios={tabla:te(v.tabla),fecha:te(v.fecha),claves:et(v.claves,3).map(te),valor:te(v.valor)},!h.precios.claves.length)throw i("Liquidaci\xF3n v2: claves de precio ausentes.")}if(t.ciclo&&(h.ciclo=te(t.ciclo)),t.recuperacion){let v=ve(t.recuperacion,["modo","plazo"]);if(h.recuperacion={modo:xt(v.modo,["total","proporcional_dias"]),plazo:pi(v.plazo)},h.recuperacion.plazo===0)throw i("Liquidaci\xF3n v2: plazo inv\xE1lido.")}if([h.motor.principal,h.motor.objetivo?.beneficiario,...(h.motor.fijoPeriodo??[]).map(v=>v.beneficiario)].some(v=>v&&!s[v]))throw i("Liquidaci\xF3n v2: beneficiario desconocido.");let b=o.find(v=>v.clave===h.documento.lineas);if(["fuente","concepto","importe"].some(v=>!b.columnas?.some(w=>w.clave===v&&w.tipo==="texto"&&!w.archivado)))throw i("Liquidaci\xF3n v2: columnas de resumen inv\xE1lidas.");let y=o.find(v=>v.clave===h.documento.estado);if(["borrador","aprobada","cerrada","pagada"].some(v=>!y.opciones?.some(w=>w.valor===v)))throw i("Liquidaci\xF3n v2: estados inv\xE1lidos.");return h}var ve,Am,te,qs,$t,et,xt,pi,Rm=f(()=>{R();Om();ve=(e,o)=>{if(!e||typeof e!="object"||Array.isArray(e))throw i("Liquidaci\xF3n v2: objeto inv\xE1lido.");if(o&&Object.keys(e).some(t=>!o.includes(t)))throw i("Liquidaci\xF3n v2: propiedad desconocida.");return e},Am=e=>typeof e=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(e)&&Number.isFinite(Date.parse(e+"T00:00:00Z"))&&new Date(e+"T00:00:00Z").toISOString().slice(0,10)===e,te=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(e))throw i("Liquidaci\xF3n v2: clave inv\xE1lida.");return e},qs=e=>{if(typeof e!="string")throw i("Liquidaci\xF3n v2: decimal como cadena.");try{if(Vr.leer(e).n<0n)throw new Error("negativo")}catch{throw i("Liquidaci\xF3n v2: decimal inv\xE1lido.")}return e},$t=e=>{let o=qs(e);if(!/^\d{1,18}(?:\.\d{1,2})?$/.test(o))throw i("Liquidaci\xF3n v2: el importe manual admite como m\xE1ximo dos decimales.");return o},et=(e,o=20)=>{if(!Array.isArray(e)||e.length>o)throw i("Liquidaci\xF3n v2: lista inv\xE1lida.");return e},xt=(e,o)=>{if(!o.includes(e))throw i("Liquidaci\xF3n v2: opci\xF3n inv\xE1lida.");return e},pi=e=>{if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw i("Liquidaci\xF3n v2: entero inv\xE1lido.");return e}});function qm(e,o){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw i("precios: un objeto.");let t=e,n=["claves","desde","hasta","prioridad","moneda","unidad","valores","solape","falta"];if(Object.keys(t).some(s=>!n.includes(s)))throw i("precios: propiedad desconocida.");let r=(s,c)=>{let d=o.find(u=>u.clave===s&&!u.archivado);if(!d||!c.includes(d.tipo)||d.multiple)throw i("precios: campo inv\xE1lido.");return d.clave},a=(s,c,d)=>{if(!Array.isArray(s)||!s.length||s.length>d||new Set(s).size!==s.length)throw i("precios: lista vac\xEDa, duplicada o demasiado larga.");return s.map(u=>r(u,c))};if(!["bloquear","prioridad"].includes(String(t.solape))||!["bloquear","pendiente"].includes(String(t.falta)))throw i("precios: pol\xEDtica inv\xE1lida.");return{claves:a(t.claves,["texto","seleccion","relacion","numero"],3),desde:r(t.desde,["fecha"]),...t.hasta?{hasta:r(t.hasta,["fecha"])}:{},prioridad:r(t.prioridad,["numero"]),moneda:r(t.moneda,["texto","seleccion"]),unidad:r(t.unidad,["texto","seleccion"]),valores:a(t.valores,["importe","numero","porcentaje"],20),solape:t.solape,falta:t.falta}}var km=f(()=>{R()});var Pm,pv,Y1,Tm,Mm=f(()=>{Pm=new Set(["texto","texto_largo","numero","importe","porcentaje","fecha","fecha_hora","hora","duracion","booleano","seleccion","seleccion_multiple","url","correo","telefono","color","codigo","valoracion","autonumero"]),pv=new Set([...Pm,"relacion"]),Y1=new Set([...Pm,"relacion"]),Tm=new Set([...pv,"busqueda"])});function Im(e){if(!e||typeof e!="object"||Array.isArray(e))throw i("Fuente operativa no v\xE1lida.");let o=e;if(Object.keys(o).some(t=>!["objeto","tipo"].includes(t)))throw i("Fuente operativa no v\xE1lida.");if(typeof o.objeto=="string"&&mv.test(o.objeto)&&!Object.hasOwn(o,"tipo"))return{objeto:o.objeto};if((o.objeto==="contacts"||o.objeto==="companies")&&(o.tipo===null||typeof o.tipo=="string"&&fv.test(o.tipo)))return{objeto:o.objeto,tipo:o.tipo};if(o.objeto==="deals"&&o.tipo===null)return{objeto:"deals",tipo:null};throw i("Fuente operativa no v\xE1lida.")}var mv,fv,Lm=f(()=>{R();mv=/^mod_[a-z][a-z0-9_]{0,40}$/,fv=/^[a-z0-9][a-z0-9-]{0,59}$/});function fi(e,o){if(e==null)return;if(!Jr(e))throw i("\xABrecurso\xBB: un objeto.");mi(e,["capacidad","capacidad_campo","persona"],"recurso");let t={};if(e.capacidad_campo!==void 0&&e.capacidad_campo!==null&&e.capacidad_campo!==""){let n=o.find(r=>r.clave===e.capacidad_campo&&!r.archivado);if(n?.tipo!=="numero")throw i("\xABrecurso.capacidad_campo\xBB: un n\xFAmero de este m\xF3dulo.");t.capacidad_campo=n.clave}if(e.capacidad!==void 0&&e.capacidad!==null){let n=Number(e.capacidad);if(!Number.isInteger(n)||n<1||n>1e4)throw i("\xABrecurso.capacidad\xBB: de 1 a 10 000.");t.capacidad=n}if(e.persona!==void 0&&e.persona!==null){if(e.persona!=="responsable")throw i("\xABrecurso.persona\xBB: \xABresponsable\xBB.");t.persona="responsable"}return t}function hi(e,o){if(e==null)return;if(!Jr(e))throw i("\xABreserva\xBB: un objeto.");mi(e,["fuente_recurso","recurso","modo","inicio","fin","duracion","duracion_fija","plazas","no_ocupan","fuera_de_horario","margen","cupo","acceso","dia","hora_inicio","hora_fin","vigencia_desde","vigencia_hasta"],"reserva");let t=m=>o.find(h=>h.clave===m&&!h.archivado),n=(m,h,b)=>{let y=t(m);if(!y||!h.includes(y.tipo))throw i(`\xABreserva.${b}\xBB: ${h.join(" o ")} de este m\xF3dulo.`);return y},r=n(e.recurso,["relacion"],"recurso"),a=e.fuente_recurso===void 0?void 0:Im(e.fuente_recurso);if(a&&(a.objeto!==r.relacion||!("tipo"in a)||r.tipoContacto&&a.tipo!==r.tipoContacto))throw i("La fuente del recurso no coincide con la relaci\xF3n.");if(!a&&!r.relacion?.startsWith("mod_"))throw i("Una relaci\xF3n nativa requiere su fuente de recurso expl\xEDcita.");let s=e.modo??"puntual";if(s!=="puntual"&&s!=="semanal")throw i("\xABreserva.modo\xBB: \xABpuntual\xBB o \xABsemanal\xBB.");let c={...a?{fuente_recurso:a}:{},recurso:r.clave,modo:s,fuera_de_horario:e.fuera_de_horario==="permitir"?"permitir":"impedir"};if(s==="puntual")c.inicio=n(e.inicio,["fecha_hora","fecha"],"inicio").clave;else{let m=n(e.dia,["seleccion"],"dia");if(!(m.opciones??[]).length||(m.opciones??[]).some(h=>hv(h.valor)===null))throw i("\xABreserva.dia\xBB: una selecci\xF3n con los d\xEDas de la semana (1\u20137, \xABlunes\xBB\u2026 o L M X J V S D).");c.dia=m.clave,c.hora_inicio=n(e.hora_inicio,["hora"],"hora_inicio").clave,e.vigencia_desde&&(c.vigencia_desde=n(e.vigencia_desde,["fecha"],"vigencia_desde").clave),e.vigencia_hasta&&(c.vigencia_hasta=n(e.vigencia_hasta,["fecha"],"vigencia_hasta").clave)}if(e.fuera_de_horario!==void 0&&e.fuera_de_horario!=="impedir"&&e.fuera_de_horario!=="permitir")throw i("\xABreserva.fuera_de_horario\xBB: \xABimpedir\xBB o \xABpermitir\xBB.");if([s==="semanal"?e.hora_fin:e.fin,e.duracion,e.duracion_fija].filter(m=>m!=null&&m!=="").length!==1)throw i(`\xABreserva\xBB: ${s==="semanal"?"una hora de fin":"un fin"}, una duraci\xF3n o una duraci\xF3n fija (solo una).`);if(s==="semanal"&&e.fin)throw i("\xABreserva.fin\xBB: en una semanal, \xABhora_fin\xBB.");if(s==="puntual"&&e.hora_fin)throw i("\xABreserva.hora_fin\xBB: en una puntual, \xABfin\xBB.");if(e.hora_fin)c.hora_fin=n(e.hora_fin,["hora"],"hora_fin").clave;else if(e.fin)c.fin=n(e.fin,["fecha_hora","fecha"],"fin").clave;else if(e.duracion)c.duracion=n(e.duracion,["duracion","numero"],"duracion").clave;else{let m=Number(e.duracion_fija);if(!Number.isInteger(m)||m<1||m>1440)throw i("\xABreserva.duracion_fija\xBB: de 1 a 1440 minutos.");c.duracion_fija=m}let u=m=>t(m)?.tipo==="fecha";if(s==="puntual"&&u(c.inicio)!==(c.fin?u(c.fin):!1))throw i("\xABreserva\xBB: por d\xEDas, la entrada y la salida son dos fechas (sin hora); con hora, las dos con hora (o una duraci\xF3n).");if(e.plazas&&(c.plazas=n(e.plazas,["numero"],"plazas").clave),e.cupo&&(c.cupo=n(e.cupo,["numero"],"cupo").clave),e.margen!==void 0&&e.margen!==null){let m=Number(e.margen);if(!Number.isInteger(m)||m<0||m>240)throw i("\xABreserva.margen\xBB: de 0 a 240 minutos.");m&&(c.margen=m)}function p(m,h){let b=Jr(m)?m:{},y=n(b.campo,["seleccion"],`${h}.campo`),v=Array.isArray(b.valores)?b.valores:[];if(!y||!v.length||v.some(w=>!y.opciones?.some(N=>N.valor===w)))throw i(`\xABreserva.${h}\xBB: una selecci\xF3n y algunas de sus opciones.`);return{campo:y.clave,valores:[...new Set(v)]}}if(e.acceso!==void 0&&e.acceso!==null){if(!Jr(e.acceso))throw i("\xABreserva.acceso\xBB: un objeto.");mi(e.acceso,["antes","despues","bloqueado","puerta_extra_obligatoria"],"reserva.acceso");let m=y=>{let v=y===void 0?0:Number(y);if(!Number.isInteger(v)||v<0||v>240)throw i("\xABreserva.acceso\xBB: de 0 a 240 minutos.");return v},h={antes:m(e.acceso.antes),despues:m(e.acceso.despues)};e.acceso.bloqueado!==void 0&&(h.bloqueado=p(e.acceso.bloqueado,"acceso.bloqueado"));let b=e.acceso.puerta_extra_obligatoria;if(b!==void 0){if(!Jr(b)||typeof b.campo!="string"||!/^[a-z][a-z0-9_]{0,39}$/.test(b.campo))throw i("\xABreserva.acceso.puerta_extra_obligatoria\xBB: clave de un campo TTLock del recurso.");if(mi(b,["campo","mismo_codigo"],"reserva.acceso.puerta_extra_obligatoria"),b.mismo_codigo!==void 0&&typeof b.mismo_codigo!="boolean")throw i("\xABreserva.acceso.puerta_extra_obligatoria.mismo_codigo\xBB: un booleano.");h.puerta_extra_obligatoria={campo:b.campo,...b.mismo_codigo?{mismo_codigo:!0}:{}}}(h.antes||h.despues||h.bloqueado||h.puerta_extra_obligatoria)&&(c.acceso=h)}return e.no_ocupan!==void 0&&e.no_ocupan!==null&&(c.no_ocupan=p(e.no_ocupan,"no_ocupan")),c}function hv(e){let o=String(e??"").trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"");return{1:1,lunes:1,l:1,lun:1,monday:1,2:2,martes:2,m:2,mar:2,tuesday:2,3:3,miercoles:3,x:3,mie:3,wednesday:3,4:4,jueves:4,j:4,jue:4,thursday:4,5:5,viernes:5,v:5,vie:5,friday:5,6:6,sabado:6,s:6,sab:6,saturday:6,7:7,domingo:7,d:7,dom:7,sunday:7}[o]??null}var Jr,mi,ks=f(()=>{R();Lm();Jr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),mi=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`\xAB${t}\xBB: clave no admitida \xAB${n.slice(0,40)}\xBB.`)}});function bv(e){let o=[],t=0;for(;t<e.length;){let n=e[t];if(/\s/.test(n)){t++;continue}if(o.length>=Dm)throw i(`F\xF3rmula demasiado larga: como mucho ${Dm} piezas.`);if(/[0-9]/.test(n)||n==="."&&/[0-9]/.test(e[t+1]??"")){let s=/^[0-9]*\.?[0-9]+|^[0-9]+/.exec(e.slice(t));if(s[0].length>20)throw i("F\xF3rmula: n\xFAmero demasiado largo.");o.push({t:"num",v:s[0]}),t+=s[0].length;continue}if(n==='"'||n==="'"){let s="",c=t+1;for(;;){if(c>=e.length)throw i("F\xF3rmula: falta cerrar unas comillas.");if(e[c]===n){if(e[c+1]===n){s+=n,c+=2;continue}break}s+=e[c],c++}if(s.length>500)throw i("F\xF3rmula: un texto de como mucho 500 caracteres.");o.push({t:"txt",v:s}),t=c+1;continue}if(n==="{"){let s=e.indexOf("}",t);if(s<0)throw i("F\xF3rmula: falta cerrar una llave \xAB}\xBB.");let c=e.slice(t+1,s).trim();if(!c||c.length>80)throw i("F\xF3rmula: un campo entre llaves no v\xE1lido.");o.push({t:"campo",v:c}),t=s+1;continue}let r=/^[A-Za-zÁÉÍÓÚÜÑáéíóúüñ_][A-Za-z0-9ÁÉÍÓÚÜÑáéíóúüñ_.]*/.exec(e.slice(t));if(r){if(r[0].length>40)throw i("F\xF3rmula: nombre demasiado largo.");o.push({t:"id",v:r[0]}),t+=r[0].length;continue}let a=gv.find(s=>e.startsWith(s,t));if(!a)throw i(`F\xF3rmula: no se entiende \xAB${n}\xBB.`);o.push({t:"op",v:a==="!="?"<>":a===";"?",":a}),t+=a.length}return o.push({t:"fin"}),o}function vv(e){let o=bv(e),t=0,n=0,r=()=>o[t],a=w=>r().t==="op"&&r().v===w,s=w=>{if(!a(w))throw i(`F\xF3rmula: se esperaba \xAB${w}\xBB.`);t++},c=w=>{if(++n>zm)throw i(`F\xF3rmula: como mucho ${zm} niveles de anidaci\xF3n.`);try{return w()}finally{n--}},d=(w,N,j=!1)=>()=>{let S=N();for(;r().t==="op"&&w.includes(r().v)&&(S={k:"bin",op:o[t++].v,a:S,b:N()},!j););return S},u=()=>c(()=>{let w=r();if(w.t==="num")return t++,{k:"num",v:w.v};if(w.t==="txt")return t++,{k:"txt",v:w.v};if(w.t==="campo")return t++,{k:"campo",v:w.v};if(w.t==="op"&&w.v==="-")return t++,{k:"neg",a:u()};if(w.t==="op"&&w.v==="("){t++;let N=y();return s(")"),N}if(w.t==="id"){t++;let N=wv(w.v);if(!a("(")){if(N==="VERDADERO"||N==="TRUE")return{k:"bool",v:!0};if(N==="FALSO"||N==="FALSE")return{k:"bool",v:!1};throw i(`F\xF3rmula: \xAB${w.v}\xBB no es una funci\xF3n (los campos van entre llaves: {${w.v}}).`)}t++;let j=[];if(!a(")"))for(;;){if(j.push(y()),j.length>Wm)throw i(`F\xF3rmula: como mucho ${Wm} argumentos.`);if(a(",")){t++;continue}break}return s(")"),{k:"fn",f:N,args:j}}throw i(w.t==="fin"?"F\xF3rmula incompleta.":"F\xF3rmula: algo sobra o falta.")}),p=d(["*","/"],u),m=d(["+","-"],p),h=d(["&"],m),b=d(["=","<>","<","<=",">",">="],h,!0),y=()=>c(b),v=y();if(r().t!=="fin")throw i("F\xF3rmula: algo sobra al final.");return v}function Ps(e){if(!ro(e,0))throw i("F\xF3rmula: A\xD1O, MES y DIA necesitan una fecha.");return"numero"}function Um(e){let o=e[0];for(let t of e.slice(1))o=tr(o,t);if(o!=="numero"&&o!=="fecha"&&o!=="fecha_hora")throw i("F\xF3rmula: MIN y MAX, con n\xFAmeros o fechas.");return o}function tr(e,o){if(e===o)return e;if(ro([e,o],0)&&ro([e,o],1))return"fecha_hora";throw i(`F\xF3rmula: no se mezclan ${jt[e]} y ${jt[o]}.`)}function gi(e){if(!e)return 0;if(e.k!=="num"||!/^\d+$/.test(e.v)||Number(e.v)>10)throw i("F\xF3rmula: REDONDEAR, con 0 a 10 decimales.");return Number(e.v)}function Ts(e,o){let t=zs(e),n=t.find(r=>r.clave===o)??t.find(r=>r.etiqueta.trim().toLowerCase()===o.trim().toLowerCase());if(!n)throw i(`F\xF3rmula: no hay un campo \xAB${o}\xBB.`);return n}function Ms(e,o,t){if(!o.includes("."))return null;let n=o.trim().toLowerCase();if(zs(e).some(a=>a.clave===o||a.etiqueta.trim().toLowerCase()===n))return null;let r=t?.[o];if(!r)throw i(`F\xF3rmula: no hay un campo \xAB${o}\xBB.`);return r}function Nv(e){let o=e.saltos.at(-1).modulo;if(Qm[o]){let t=Ee(e.campo)?e.campos.find(r=>r.clave===e.campo&&!r.archivado):void 0,n=t?Ds[t.tipo]:Vm[Gr(o).find(r=>r.clave===e.campo)?.tipo??""];if(!n)throw i(`F\xF3rmula: \xAB${e.campo}\xBB no se puede usar en una f\xF3rmula.`);return n}return Jm({campos:e.campos},_v(e),[])}function Jm(e,o,t){if(o.tipo==="formula")return Gm(e,o,t).tipo;let n=o.tipo==="busqueda"||o.tipo==="resumen"?o.origen?.tipo??"":o.tipo,r=Ds[n];if(!r)throw i(`F\xF3rmula: el campo \xAB${o.etiqueta}\xBB no se puede usar en una f\xF3rmula.`);return o.tipo==="busqueda"&&$v(e,o),r}function $v(e,o){let t=zs(e).find(n=>n.clave===o.desde);if(!t?.relacion||t.multiple)throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB trae varios valores y no se usa en una f\xF3rmula.`);if(o.origen?.encadenada)throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB ya va encadenada y no se usa en una f\xF3rmula.`);if(t.relacion.startsWith("mod_")){if(!/^[a-z][a-z0-9_]{0,40}$/.test(o.campo??"")||xv.has(o.origen?.tipo??""))throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB no es v\xE1lida.`)}else{let n=Gr(t.relacion).find(r=>r.clave===o.campo)??(Ee(o.campo)&&o.origen?{tipo:o.origen.tipo}:void 0);if(!n||!(Ee(o.campo)?Ds[n.tipo]:Vm[n.tipo])||!Qm[t.relacion])throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB no se puede usar en una f\xF3rmula.`)}return{rel:t}}function Gm(e,o,t){if(t.includes(o.clave))throw i(`F\xF3rmula: \xAB${o.etiqueta}\xBB se usa a s\xED misma (en cadena).`);if(t.length>=Fm)throw i(`F\xF3rmula: como mucho ${Fm} f\xF3rmulas encadenadas.`);return Cv(e,o.formula??"",[...t,o.clave],o.origen?.rutas)}function Cv(e,o,t,n){if(typeof o!="string"||!o.trim())throw i("F\xF3rmula vac\xEDa.");if(o.length>no)throw i(`F\xF3rmula de como mucho ${no} caracteres.`);let r=vv(o),a=new Map,s=u=>{let p=d(u);return a.set(u,p),p},c=(u,p,m)=>{let h=s(u);if(h!==p){if(u.k==="campo"){let y=Ms(e,u.v,n)?u.v:Ts(e,u.v).etiqueta;throw i(`F\xF3rmula: \xAB${y}\xBB no es ${jt[p]}, es ${jt[h]} (${m} necesita ${jt[p]}).`)}throw i(`F\xF3rmula: ${m} necesita ${jt[p]} y hay ${jt[h]}.`)}},d=u=>{switch(u.k){case"num":return"numero";case"txt":return"texto";case"bool":return"booleano";case"campo":{let p=Ms(e,u.v,n);return p?Nv(p):Jm(e,Ts(e,u.v),t)}case"neg":return c(u.a,"numero","\xAB-\xBB"),"numero";case"bin":return u.op==="&"?(s(u.a),s(u.b),"texto"):["+","-","*","/"].includes(u.op)?(c(u.a,"numero",`\xAB${u.op}\xBB`),c(u.b,"numero",`\xAB${u.op}\xBB`),"numero"):(tr(s(u.a),s(u.b)),"booleano");case"fn":{let p=yv[u.f]??u.f,m=Ls[p];if(!m)throw i(`F\xF3rmula: la funci\xF3n \xAB${u.f}\xBB no existe.`);if(p==="REDONDEAR"&&gi(u.args[1]),p==="PRECIO_VIGENTE"&&(u.args.length<4||u.args.length>6||u.args[0]?.k!=="txt"||u.args[2]?.k!=="txt"))throw i("PRECIO_VIGENTE: tabla y valor literales, fecha y de una a tres claves.");let h=m.args.length-(m.opcionales??0);if(u.args.length<Math.max(h,m.resto?1:0)||!m.resto&&u.args.length>m.args.length)throw i(`F\xF3rmula: ${p} no lleva ${u.args.length} argumentos.`);let b=u.args.map((y,v)=>{let w=m.args[v]??m.resto;return w==="cualquiera"?s(y):(c(y,w,p),w)});return m.tipo(b)}}};return{tipo:s(r),arbol:r,tipos:a,...n?{rutas:n}:{}}}function bi(e){let o={campos:e};return e.map(t=>{if(t.tipo!=="formula"||t.archivado)return t;let n=Gm(o,t,[]),r=t.origen?.rutas&&Object.keys(t.origen.rutas).length?t.origen.rutas:void 0;return{...t,formula:jv(o,t.formula,r),origen:{tipo:n.tipo,...r?{rutas:r}:{}}}})}function jv(e,o,t){let n="",r=0;for(;r<o.length;){let a=o[r];if(a==='"'||a==="'"){let s=r+1;for(;s<o.length;)if(o[s]===a&&o[s+1]===a)s+=2;else{if(o[s]===a)break;s++}n+=o.slice(r,s+1),r=s+1;continue}if(a==="{"){let s=o.indexOf("}",r),c=o.slice(r+1,s).trim();n+=`{${Ms(e,c,t)?c:Ts(e,c).clave}}`,r=s+1;continue}n+=a,r++}return n}var no,Dm,zm,Fm,Wm,Is,gv,wv,ro,Ct,Bm,or,Ls,yv,cL,jt,Ds,Vm,lL,zs,_v,xv,Qm,wi=f(()=>{Ur();li();R();vi();no=1e3,Dm=300,zm=20,Fm=5,Wm=20,Is="Europe/Madrid",gv=["<>","!=","<=",">=","=","<",">","+","-","*","/","&","(",")",",",";"];wv=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").toUpperCase();ro=(e,o)=>e[o]==="fecha"||e[o]==="fecha_hora",Ct=(e,o)=>o==="fecha_hora"?A`(${e} at time zone ${Is})::date`:e,Bm=e=>A`(${e})::text`,or=(e,o)=>A`(least(greatest(${e}, ${-o}::numeric), ${o}::numeric))::int`,Ls={PRECIO_VIGENTE:{args:["texto","fecha","texto","cualquiera"],resto:"cualquiera",tipo:()=>"numero",sql:e=>A`((crm_precio_formula(${e[0]}, ${e[1]}::date, jsonb_build_array(${A.join(e.slice(3).map(o=>A`(${o})::text`),A`, `)}))->'valores'->>${e[2]})::numeric)`},SI:{args:["booleano","cualquiera","cualquiera"],opcionales:1,tipo:e=>tr(e[1],e[2]??e[1]),sql:e=>e[2]?A`(case when ${e[0]} then ${e[1]} else ${e[2]} end)`:A`(case when ${e[0]} then ${e[1]} end)`},Y:{args:[],resto:"booleano",tipo:()=>"booleano",sql:e=>A`(${A.join(e,A` and `)})`},O:{args:[],resto:"booleano",tipo:()=>"booleano",sql:e=>A`(${A.join(e,A` or `)})`},NO:{args:["booleano"],tipo:()=>"booleano",sql:e=>A`(not ${e[0]})`},VACIO:{args:["cualquiera"],tipo:()=>"booleano",sql:(e,o)=>o[0]==="texto"?A`(${e[0]} is null or ${e[0]} = '')`:A`(${e[0]} is null)`},REDONDEAR:{args:["numero","numero"],opcionales:1,tipo:()=>"numero",sql:(e,o,t)=>A`round(${e[0]}, ${gi(t[1])}::int)`},ABS:{args:["numero"],tipo:()=>"numero",sql:e=>A`abs(${e[0]})`},MIN:{args:["cualquiera"],resto:"cualquiera",tipo:e=>Um(e),sql:e=>A`least(${A.join(e)})`},MAX:{args:["cualquiera"],resto:"cualquiera",tipo:e=>Um(e),sql:e=>A`greatest(${A.join(e)})`},CONCAT:{args:[],resto:"cualquiera",tipo:()=>"texto",sql:e=>A`concat(${A.join(e.map(Bm))})`},MAYUSCULAS:{args:["texto"],tipo:()=>"texto",sql:e=>A`upper(${e[0]})`},MINUSCULAS:{args:["texto"],tipo:()=>"texto",sql:e=>A`lower(${e[0]})`},IZQUIERDA:{args:["texto","numero"],tipo:()=>"texto",sql:e=>A`left(${e[0]}, ${or(e[1],1e4)})`},DERECHA:{args:["texto","numero"],tipo:()=>"texto",sql:e=>A`right(${e[0]}, ${or(e[1],1e4)})`},LARGO:{args:["texto"],tipo:()=>"numero",sql:e=>A`(length(${e[0]}))::numeric`},RECORTAR:{args:["texto"],tipo:()=>"texto",sql:e=>A`btrim(${e[0]})`},TEXTO:{args:["cualquiera"],tipo:()=>"texto",sql:e=>Bm(e[0])},HOY:{args:[],tipo:()=>"fecha",sql:()=>A`(now() at time zone ${Is})::date`},AHORA:{args:[],tipo:()=>"fecha_hora",sql:()=>A`now()`},DIAS_ENTRE:{args:["cualquiera","cualquiera"],tipo:e=>{if(!ro(e,0)||!ro(e,1))throw i("F\xF3rmula: DIAS_ENTRE necesita dos fechas.");return"numero"},sql:(e,o)=>A`((${Ct(e[1],o[1])}) - (${Ct(e[0],o[0])}))::numeric`},ANADIR_DIAS:{args:["cualquiera","numero"],tipo:e=>{if(!ro(e,0))throw i("F\xF3rmula: A\xD1ADIR_DIAS necesita una fecha.");return e[0]},sql:(e,o)=>o[0]==="fecha"?A`(${e[0]} + ${or(e[1],1e5)})`:A`(${e[0]} + make_interval(days => ${or(e[1],1e5)}))`},ANO:{args:["cualquiera"],tipo:e=>Ps(e),sql:(e,o)=>A`(extract(year from ${Ct(e[0],o[0])}))::numeric`},MES:{args:["cualquiera"],tipo:e=>Ps(e),sql:(e,o)=>A`(extract(month from ${Ct(e[0],o[0])}))::numeric`},DIA:{args:["cualquiera"],tipo:e=>Ps(e),sql:(e,o)=>A`(extract(day from ${Ct(e[0],o[0])}))::numeric`},POTENCIA:{args:["numero","numero"],tipo:()=>"numero",sql:e=>A`(case when ${e[0]} is null or ${e[1]} is null then null
|
|
7
7
|
when abs(${e[1]}) > 64 or abs(${e[0]}) > 1000000000 then null
|
|
8
8
|
when ${e[0]} = 0 and ${e[1]} < 0 then null
|
|
9
9
|
when ${e[0]} < 0 and ${e[1]} <> trunc(${e[1]}) then null
|
|
10
10
|
else power((${e[0]})::numeric, (${e[1]})::numeric) end)`},PAGO:{args:["numero","numero","numero"],tipo:()=>"numero",sql:e=>A`(case when ${e[0]} is null or ${e[1]} is null or ${e[2]} is null then null
|
|
11
11
|
when ${e[1]} < 1 or ${e[1]} > 1200 or ${e[0]} <= -1 or ${e[0]} > 10 then null
|
|
12
12
|
when ${e[0]} = 0 then (${e[2]})::numeric / trunc(${e[1]})
|
|
13
|
-
else (${e[2]})::numeric * (${e[0]})::numeric / (1 - power(1 + (${e[0]})::numeric, -trunc(${e[1]})::numeric)) end)`},REDONDEAR_ARRIBA:{args:["numero","numero"],opcionales:1,tipo:()=>"numero",sql:(e,o,t)=>{let n=
|
|
13
|
+
else (${e[2]})::numeric * (${e[0]})::numeric / (1 - power(1 + (${e[0]})::numeric, -trunc(${e[1]})::numeric)) end)`},REDONDEAR_ARRIBA:{args:["numero","numero"],opcionales:1,tipo:()=>"numero",sql:(e,o,t)=>{let n=gi(t[1]);return n?A`(ceil((${e[0]})::numeric * ${10**n}::numeric) / ${10**n}::numeric)`:A`ceil((${e[0]})::numeric)`}},REDONDEAR_ABAJO:{args:["numero","numero"],opcionales:1,tipo:()=>"numero",sql:(e,o,t)=>{let n=gi(t[1]);return n?A`(floor((${e[0]})::numeric * ${10**n}::numeric) / ${10**n}::numeric)`:A`floor((${e[0]})::numeric)`}},DIAS_HABILES:{args:["cualquiera","cualquiera"],tipo:e=>{if(!ro(e,0)||!ro(e,1))throw i("F\xF3rmula: DIAS_HABILES necesita dos fechas.");return"numero"},sql:(e,o)=>{let t=Ct(e[0],o[0]),n=Ct(e[1],o[1]);return A`(case when ${t} is null or ${n} is null then null
|
|
14
14
|
when abs((${n})::date - (${t})::date) > 3660 then null
|
|
15
15
|
else (case when (${n})::date < (${t})::date then -1 else 1 end) * (
|
|
16
16
|
select count(*) from generate_series(least((${t})::date, (${n})::date)::timestamp, greatest((${t})::date, (${n})::date)::timestamp, interval '1 day') as g(d)
|
|
17
17
|
where extract(isodow from g.d) < 6
|
|
18
|
-
and not exists (select 1 from festivos f where f.espacio_id = crm_espacio() and f.fecha = g.d::date))::numeric end)`}}};Object.assign(Ps,{RESTO:{args:["numero","numero"],tipo:()=>"numero",sql:e=>A`mod((${e[0]})::numeric, nullif((${e[1]})::numeric, 0))`},CAMBIAR:{args:["cualquiera"],resto:"cualquiera",tipo:e=>{if(e.length<3)throw i("F\xF3rmula: CAMBIAR lleva el valor y, al menos, un caso y su resultado.");let o=null;for(let t=1;t<e.length;t+=2)t+1<e.length?(or(e[0],e[t]),o=o?or(o,e[t+1]):e[t+1]):o=o?or(o,e[t]):e[t];return o},sql:e=>{let o=[];for(let n=1;n+1<e.length;n+=2)o.push(A`when ${e[0]} = ${e[n]} then ${e[n+1]}`);let t=(e.length-1)%2===1?A`else ${e[e.length-1]}`:A``;return A`(case ${A.join(o,A` `)} ${t} end)`}},CONTIENE:{args:["texto","texto"],tipo:()=>"booleano",sql:e=>A`(strpos(lower(${e[0]}), lower(${e[1]})) > 0)`},SUSTITUIR:{args:["texto","texto","texto"],tipo:()=>"texto",sql:e=>A`replace(${e[0]}, ${e[1]}, coalesce(${e[2]}, ''))`},ANADIR_MESES:{args:["cualquiera","numero"],tipo:e=>{if(!ro(e,0))throw i("F\xF3rmula: A\xD1ADIR_MESES necesita una fecha.");return e[0]},sql:(e,o)=>o[0]==="fecha"?A`((${e[0]} + make_interval(months => ${er(e[1],12e3)}))::date)`:A`(${e[0]} + make_interval(months => ${er(e[1],12e3)}))`},HORAS_ENTRE:{args:["cualquiera","cualquiera"],tipo:e=>{if(!ro(e,0)||!ro(e,1))throw i("F\xF3rmula: HORAS_ENTRE necesita dos fechas (o fechas y horas).");return"numero"},sql:(e,o)=>{let t=(n,r)=>r==="fecha"?A`((${n})::timestamp at time zone ${ks})`:n;return A`round((extract(epoch from (${t(e[1],o[1])} - ${t(e[0],o[0])})) / 3600)::numeric, 6)`}}});Xw={IF:"SI",AND:"Y",OR:"O",NOT:"NO",ISBLANK:"VACIO",ESBLANCO:"VACIO",ROUND:"REDONDEAR",CONCATENAR:"CONCAT",UPPER:"MAYUSCULAS",LOWER:"MINUSCULAS",LEFT:"IZQUIERDA",RIGHT:"DERECHA",LEN:"LARGO",TRIM:"RECORTAR",TEXT:"TEXTO",TODAY:"HOY",NOW:"AHORA",DATETIME_DIFF:"DIAS_ENTRE",DAYS:"DIAS_ENTRE",DATEADD:"ANADIR_DIAS",YEAR:"ANO",MONTH:"MES",DAY:"DIA",POWER:"POTENCIA",PMT:"PAGO",CEIL:"REDONDEAR_ARRIBA",CEILING:"REDONDEAR_ARRIBA",FLOOR:"REDONDEAR_ABAJO",NETWORKDAYS:"DIAS_HABILES",DIAS_LAB:"DIAS_HABILES",MOD:"RESTO",SWITCH:"CAMBIAR",SUBSTITUTE:"SUSTITUIR",EDATE:"ANADIR_MESES",ADDMONTHS:"ANADIR_MESES"},E1=Object.keys(Ps);jt={numero:"un n\xFAmero",texto:"un texto",fecha:"una fecha",fecha_hora:"una fecha y hora",booleano:"un s\xED/no"};Ts={numero:"numero",importe:"numero",duracion:"numero",porcentaje:"numero",valoracion:"numero",contador:"numero",cronometro:"numero",texto:"texto",texto_largo:"texto",correo:"texto",telefono:"texto",url:"texto",color:"texto",codigo:"texto",seleccion:"texto",autonumero:"texto",fecha:"fecha",fecha_hora:"fecha_hora",hecho:"fecha_hora",creado_el:"fecha_hora",modificado_el:"fecha_hora",booleano:"booleano"},Im={texto:"texto",texto_largo:"texto",correo:"texto",telefono:"texto",url:"texto",seleccion:"texto",numero:"numero",importe:"numero",fecha:"fecha",fecha_hora:"fecha_hora",booleano:"booleano"},q1={numero:A`numeric`,texto:A`text`,fecha:A`date`,fecha_hora:A`timestamptz`,booleano:A`boolean`},Ms=e=>e.campos.filter(o=>!o.archivado);Yw=e=>{let o=e.campos.find(t=>t.clave===e.campo&&!t.archivado);if(!o)throw i(`F\xF3rmula: \xAB${e.campo}\xBB ya no est\xE1 en el otro m\xF3dulo.`);return o};ev=new Set(["creado_el","creado_por","modificado_el","modificado_por","autonumero"]),Lm={companies:"companies_summary",contacts:"contacts_summary",deals:"deals"}});function Fm(e,o){if(e==null)return;if(!Gr(e))throw i("\xABerp\xBB: un objeto.");let t=(r,a,s=!1)=>{if(!(r===void 0&&s)){if(typeof r!="string"||!o.some(c=>c.clave===r&&c.tipo!=="subtabla"))throw i(`ERP: \xAB${a}\xBB no es un campo del m\xF3dulo.`);return r}},n={};if(e.presupuesto!==void 0){let r=e.presupuesto;if(!Gr(r)||!Gr(r.lineas))throw i("ERP: \xABpresupuesto\xBB con \xABcliente\xBB y \xABlineas\xBB.");let a=o.find(d=>d.clave===r.lineas.subtabla&&d.tipo==="subtabla");if(!a)throw i("ERP: \xABlineas.subtabla\xBB no es una subtabla del m\xF3dulo.");let s=r.lineas,c=(d,u,p=!1)=>{if(!(d===void 0&&p)){if(typeof d!="string"||!(a.columnas??[]).some(m=>m.clave===d))throw i(`ERP: \xAB${u}\xBB no es una columna de la subtabla.`);return d}};if(s.articulo!==void 0&&!(a.columnas??[]).some(d=>d.clave===s.articulo&&d.tipo==="articulo"))throw i("ERP: \xABarticulo\xBB, una columna de art\xEDculo de la subtabla.");if(r.tipo!==void 0&&r.tipo!=="presupuesto"&&r.tipo!=="factura")throw i("ERP: \xABtipo\xBB, presupuesto o factura.");if(r.clienteAlternativo!==void 0&&r.clienteAlternativo===r.cliente)throw i("ERP: las relaciones de cliente deben ser distintas.");n.presupuesto={...r.tipo?{tipo:r.tipo}:{},cliente:t(r.cliente,"cliente"),...r.clienteAlternativo!==void 0?{clienteAlternativo:t(r.clienteAlternativo,"clienteAlternativo")}:{},lineas:{subtabla:a.clave,descripcion:c(s.descripcion,"descripcion"),precio:c(s.precio,"precio"),...s.cantidad!==void 0?{cantidad:c(s.cantidad,"cantidad")}:{},...s.iva!==void 0?{iva:c(s.iva,"iva")}:{},...s.articulo!==void 0?{articulo:s.articulo}:{}}}}if(e.gasto!==void 0){let r=e.gasto;if(!Gr(r))throw i("ERP: \xABgasto\xBB, un objeto.");if(r.tipo!==void 0&&r.tipo!=="factura"&&r.tipo!=="ticket")throw i("ERP: el gasto es factura o ticket.");n.gasto={...r.tipo?{tipo:r.tipo}:{},proveedor:t(r.proveedor,"proveedor"),fecha:t(r.fecha,"fecha"),base:t(r.base,"base"),...r.nif!==void 0?{nif:t(r.nif,"nif")}:{},...r.numero!==void 0?{numero:t(r.numero,"numero")}:{},...r.iva!==void 0?{iva:t(r.iva,"iva")}:{}}}if(e.horas!==void 0){let r=e.horas;if(!Gr(r))throw i("ERP: \xABhoras\xBB, un objeto.");let a=t(r.guardarEn,"guardarEn",!0);if(a&&!o.some(s=>s.clave===a&&["numero","duracion"].includes(s.tipo)))throw i("ERP: \xABguardarEn\xBB, un campo num\xE9rico.");n.horas={desde:t(r.desde,"desde"),hasta:t(r.hasta,"hasta"),...r.persona!==void 0?{persona:t(r.persona,"persona")}:{},...a?{guardarEn:a}:{}}}return Object.keys(n).length?n:void 0}var Gr,Wm=f(()=>{q();Gr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Um(e,o){if(e==null)return;if(!Po(e))throw i("\xABimpresion\xBB: un objeto.");let{ejemplares:t,cuerpo:n,...r}=e;if(r.subtabla!==void 0)throw i("Impresi\xF3n: clave no admitida \xABsubtabla\xBB.");let a=Hr(r,o)??{},s=rr(n,"El texto del documento",Jm);if(s){for(let c of s.matchAll(/\{\{\s*([^}]*?)\s*\}\}/g)){let d=c[1].split("|")[0].trim();if(d!=="hoy"&&d!=="espacio.nombre"&&!/^padre\.[a-z][a-z0-9_]{0,40}$/.test(d)&&!o.some(u=>u.clave===d&&!u.archivado))throw i(`El texto del documento: \xAB{{${d.slice(0,40)}}}\xBB no es una columna de la l\xEDnea ni \xABpadre.<campo>\xBB.`)}a.cuerpo=s}if(t!=null){if(!Array.isArray(t)||t.length>3||t.some(c=>typeof c!="string"||!c.trim()||c.length>60))throw i("\xABejemplares\xBB: hasta 3, cada uno con su r\xF3tulo (hasta 60).");t.length&&(a.ejemplares=t.map(c=>c.trim()))}return Object.keys(a).length?a:void 0}function tr(e,o,t){for(let n of Object.keys(e))if(!o.includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`)}function rr(e,o,t){if(!(e==null||e==="")){if(typeof e!="string"||e.length>t)throw i(`${o}: texto de hasta ${t} caracteres.`);return e.trim()||void 0}}function St(e,o,t,n,r=()=>!0){if(e==null)return;if(!Array.isArray(e)||e.length>t||!e.every(s=>typeof s=="string"))throw i(`${n}: hasta ${t} claves de campo.`);let a=new Set(o.filter(s=>!s.archivado&&r(s)).map(s=>s.clave));return[...new Set(e)].filter(s=>a.has(s))}function Bm(e,o){if(e===void 0)return;if(!Po(e))throw i("La condici\xF3n de ficha necesita un campo y un valor.");tr(e,["campo","valor"],"Condici\xF3n de ficha");let t=o.find(n=>n.clave===e.campo&&!n.archivado);if(t?.tipo==="seleccion"&&typeof e.valor=="string"&&t.opciones?.some(n=>n.valor===e.valor))return{campo:t.clave,valor:e.valor};if(t?.tipo==="booleano"&&typeof e.valor=="boolean")return{campo:t.clave,valor:e.valor};throw i("La condici\xF3n de ficha necesita una opci\xF3n del campo o un valor de s\xED/no.")}function vi(e,o){if(e==null)return;if(!Po(e))throw i("\xABficha\xBB: un objeto.");tr(e,["cabecera","columnas","pestanas","grupos","relacionadas","erp","sin_conexion","rapido","duplicados","tarjeta","en_crear","filtros","principal","plegar_vacios"],"Ficha");let t={},n=St(e.cabecera,o,4,"La cabecera",p=>!["subtabla","boton","archivos","texto_largo"].includes(p.tipo));if(n?.length&&(t.cabecera=n),e.columnas!==void 0){if(e.columnas!==1&&e.columnas!==2&&e.columnas!==3)throw i("\xABcolumnas\xBB: 1, 2 o 3.");e.columnas>1&&(t.columnas=e.columnas)}if(e.pestanas!==void 0){if(!Array.isArray(e.pestanas)||e.pestanas.length>6)throw i("Hasta 6 pesta\xF1as.");let p=e.pestanas.map((m,h)=>{if(!Po(m))throw i(`Pesta\xF1a ${h+1}: un objeto.`);tr(m,["titulo","secciones","artefacto","cuando"],`Pesta\xF1a ${h+1}`);let b=rr(m.titulo,`Pesta\xF1a ${h+1}`,40);if(!b)throw i(`Pesta\xF1a ${h+1}: falta el t\xEDtulo.`);let y=Bm(m.cuando,o);if(m.artefacto!==void 0){let v=Number(m.artefacto);if(!Number.isSafeInteger(v)||v<1)throw i(`Pesta\xF1a ${h+1}: el artefacto no es v\xE1lido.`);return{titulo:b,secciones:[],artefacto:v,...y?{cuando:y}:{}}}if(!Array.isArray(m.secciones)||m.secciones.length>20||!m.secciones.every(v=>typeof v=="string"&&v.length<=60))throw i(`Pesta\xF1a ${h+1}: sus secciones, hasta 20.`);return{titulo:b,secciones:[...new Set(m.secciones)],...y?{cuando:y}:{}}});p.length&&(t.pestanas=p)}if(e.grupos!==void 0){if(!Array.isArray(e.grupos)||e.grupos.length>40)throw i("Hasta 40 grupos de ficha.");let p=new Set(o.filter(b=>!b.archivado).map(b=>b.seccion??"")),m=new Set,h=e.grupos.map(b=>{if(!Po(b))throw i("Grupo de ficha: un objeto.");if(tr(b,["seccion","cuando","plegado"],"Grupo de ficha"),typeof b.seccion!="string"||!p.has(b.seccion)||m.has(b.seccion))throw i("El grupo debe corresponder a una secci\xF3n distinta de la ficha.");if(b.plegado!==void 0&&typeof b.plegado!="boolean")throw i("Grupo plegado: s\xED o no.");m.add(b.seccion);let y=Bm(b.cuando,o);return{seccion:b.seccion,...y?{cuando:y}:{},...b.plegado!==void 0?{plegado:b.plegado}:{}}});h.length&&(t.grupos=h)}if(e.relacionadas!==void 0){if(e.relacionadas!=="abajo"&&e.relacionadas!=="pestana")throw i("\xABrelacionadas\xBB: abajo o pestana.");e.relacionadas==="pestana"&&(t.relacionadas="pestana")}let r=Fm(e.erp,o);if(r&&(t.erp=r),e.sin_conexion!==void 0){if(typeof e.sin_conexion!="boolean")throw i("\xABsin_conexion\xBB: s\xED o no.");e.sin_conexion&&(t.sin_conexion=!0)}let a=St(e.rapido,o,3,"El registro r\xE1pido",p=>!["subtabla","boton","archivos","firma","busqueda","resumen","formula","autonumero","creado_el","creado_por","modificado_el","modificado_por"].includes(p.tipo));a?.length&&(t.rapido=a);let s=St(e.duplicados,o,3,"Los campos de duplicados",p=>rv.includes(p.tipo));s?.length&&(t.duplicados=s);let c=St(e.tarjeta,o,3,"La tarjeta",p=>!["subtabla","boton","archivos","texto_largo","firma"].includes(p.tipo));if(c?.length&&(t.tarjeta=c),e.en_crear!==void 0){if(typeof e.en_crear!="boolean")throw i("\xABen_crear\xBB: s\xED o no.");e.en_crear&&(t.en_crear=!0)}let d=St(e.filtros,o,4,"Los filtros de arriba",p=>nv.includes(p.tipo));d?.length&&(t.filtros=d);let u=St(e.principal,o,8,"El contenido principal",p=>p.tipo!=="boton");if(u?.length&&(t.principal=u),e.plegar_vacios!==void 0){if(typeof e.plegar_vacios!="boolean")throw i("\xABplegar_vacios\xBB: s\xED o no.");e.plegar_vacios||(t.plegar_vacios=!1)}return Object.keys(t).length?t:void 0}function Hr(e,o){if(e==null)return;if(!Po(e))throw i("\xABimpresion\xBB: un objeto.");tr(e,["titulo","campos","subtabla","subtablaVacia","pie","logo","orientacion","cuerpo","color","firmas"],"Impresi\xF3n");let t={},n=rr(e.titulo,"El t\xEDtulo de la impresi\xF3n",80);n&&(t.titulo=n);let r=St(e.campos,o,40,"Los campos de la impresi\xF3n",c=>!["subtabla","boton"].includes(c.tipo));if(r?.length&&(t.campos=r),e.subtabla!==void 0&&e.subtabla!==null&&e.subtabla!==""){if(typeof e.subtabla!="string")throw i("\xABsubtabla\xBB: la clave de una subtabla.");o.some(c=>c.clave===e.subtabla&&c.tipo==="subtabla"&&!c.archivado)&&(t.subtabla=e.subtabla)}if(t.subtabla&&e.subtablaVacia!=null&&e.subtablaVacia!==""){if(typeof e.subtablaVacia!="string"||e.subtablaVacia.length>120)throw i("El texto de la subtabla vac\xEDa admite hasta 120 caracteres.");e.subtablaVacia.trim()&&(t.subtablaVacia=e.subtablaVacia.trim())}let a=rr(e.pie,"El pie de la impresi\xF3n",500);if(a&&(t.pie=a),e.logo!==void 0){if(typeof e.logo!="boolean")throw i("\xABlogo\xBB: s\xED o no.");e.logo&&(t.logo=!0)}if(e.orientacion!==void 0){if(e.orientacion!=="vertical"&&e.orientacion!=="horizontal")throw i("\xABorientacion\xBB: vertical u horizontal.");e.orientacion==="horizontal"&&(t.orientacion="horizontal")}let s=rr(e.cuerpo,"El texto del documento",Jm);if(s){for(let c of s.matchAll(/\{\{\s*([^}]*?)\s*\}\}/g)){let d=c[1].split("|")[0].trim();if(d!=="hoy"&&d!=="espacio.nombre"&&!o.some(u=>u.clave===d&&!u.archivado))throw i(`El texto del documento: \xAB{{${d.slice(0,40)}}}\xBB no es un campo del m\xF3dulo.`)}t.cuerpo=s}if(e.color!==void 0&&e.color!==null&&e.color!==""){if(typeof e.color!="string"||!/^#[0-9a-fA-F]{6}$/.test(e.color))throw i("\xABcolor\xBB: #rrggbb.");t.color=e.color.toLowerCase()}if(e.firmas!==void 0&&e.firmas!==null){if(!Array.isArray(e.firmas)||e.firmas.length>4||e.firmas.some(c=>typeof c!="string"||!c.trim()||c.length>60))throw i("\xABfirmas\xBB: hasta 4 casillas, cada una con su texto (hasta 60).");e.firmas.length&&(t.firmas=e.firmas.map(c=>c.trim()))}return Object.keys(t).length?t:void 0}function Is(e,o=0){return o>10?!1:Array.isArray(e)?e.every(t=>Is(t,o+1)):Po(e)?Object.keys(e).every(t=>!iv.has(t)&&Is(e[t],o+1)):!0}function Qm(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>10)throw i("\xABvistas\xBB: hasta 10.");let t=e.map((n,r)=>{if(!Po(n))throw i(`Vista ${r+1}: un objeto.`);tr(n,["nombre","tipo","config"],`Vista ${r+1}`);let a=rr(n.nombre,`Vista ${r+1}`,60);if(!a)throw i(`Vista ${r+1}: falta el nombre.`);if(typeof n.tipo!="string"||!Vm.includes(n.tipo))throw i(`Vista ${r+1}: tipo ${Vm.join(", ")}.`);if(n.config!==void 0&&(!Po(n.config)||!Is(n.config)||JSON.stringify(n.config).length>4e3))throw i(`Vista ${r+1}: \xABconfig\xBB, un objeto de hasta 4 KB.`);let s=n.config;if(n.tipo==="kanban"&&s?.segundo!==void 0){let c=o.find(d=>d.clave===s.segundo&&!d.archivado);if(!c||c.clave===s.agrupar||!(c.tipo==="seleccion"&&c.opciones?.length||c.tipo==="relacion"&&!c.multiple))throw i("El segundo campo del kanban debe ser una selecci\xF3n o una relaci\xF3n simple distinta de la primera.")}return{nombre:a,tipo:n.tipo,...n.config?{config:n.config}:{}}});return t.length?t:void 0}var Po,rv,nv,Jm,Vm,iv,Ds=f(()=>{q();Wm();Po=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);rv=["texto","correo","telefono","codigo","url"],nv=["seleccion","seleccion_multiple","etiquetas","booleano","hecho","creado_por","modificado_por","relacion","texto","texto_largo","correo","telefono","url","codigo","autonumero","ubicacion","numero","importe","porcentaje","fecha","fecha_hora","duracion","valoracion"];Jm=12e3;Vm=["kanban","calendario","linea","mapa","galeria","tablero","cuadrante","dia"],iv=new Set(["__proto__","constructor","prototype"])});var Xr,Gm=f(()=>{Xr=e=>e==="@contacts"||e==="@companies"});function Ni(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>yi)throw i(`\xABrelacionadas\xBB: hasta ${yi} columnas.`);if(!e.length)return;let t=new Set;return e.map((n,r)=>{let a=`Columna relacionada ${r+1}`;if(!zs(n))throw i(`${a}: un objeto.`);Xm(n,["clave","etiqueta","via","campo","de","calculo","filtro","siVacio"],a);let s=Ot(n.clave,`${a}.clave`);if(t.has(s)||o.some(u=>u.clave===s))throw i(`${a}: la clave \xAB${s}\xBB ya la usa otra columna o un campo.`);if(t.add(s),typeof n.etiqueta!="string"||!n.etiqueta.trim()||n.etiqueta.length>80)throw i(`${a}: \xABetiqueta\xBB, de 1 a 80 caracteres.`);let c=Xr(String(n.de))&&typeof n.via=="string"&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(n.via)?n.via:Ot(n.via,`${a}.via`);if(n.de!==void 0){if(n.siVacio!==void 0)throw i("\xABsiVacio\xBB solo se admite al traer un valor escalar.");let u=typeof n.de=="string"&&Xr(n.de)?n.de:Ot(n.de,`${a}.de`);if(typeof n.calculo!="string"||!Hm.includes(n.calculo))throw i(`${a}: \xABcalculo\xBB, uno de ${Hm.join(", ")}.`);let p=n.calculo,m=p==="recuento"?void 0:Xr(u)&&typeof n.campo=="string"&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(n.campo)?n.campo:Ot(n.campo,`${a}.campo`),h=Yr(n.filtro,a,Xr(u));return{clave:s,etiqueta:n.etiqueta.trim(),via:c,de:u,calculo:p,...m?{campo:m}:{},...h?{filtro:h}:{}}}if(n.calculo!==void 0||n.filtro!==void 0)throw i(`${a}: \xABcalculo\xBB y \xABfiltro\xBB solo con \xABde\xBB (los hijos).`);let d=o.find(u=>u.clave===c&&!u.archivado);if(!d||d.tipo!=="relacion")throw i(`${a}: \xAB${c}\xBB no es una relaci\xF3n de este m\xF3dulo.`);if(d.multiple&&n.siVacio!==void 0)throw i("Una colecci\xF3n no tiene alternativa escalar.");if(typeof n.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(n.campo))throw i(`${a}: campo no v\xE1lido.`);return{clave:s,etiqueta:n.etiqueta.trim(),via:c,campo:n.campo,...n.siVacio!==void 0?{siVacio:Ot(n.siVacio,`${a}.siVacio`)}:{}}})}function $i(e){if(e==null)return;if(!Array.isArray(e)||e.length>_i)throw i(`\xABsiguientes\xBB: hasta ${_i} pasos.`);if(!e.length)return;let o=new Set;return e.map((t,n)=>{let r=`Siguiente paso ${n+1}`;if(!zs(t))throw i(`${r}: un objeto.`);Xm(t,["clave","nombre","destino","enlace","campos"],r);let a=Ot(t.clave,`${r}.clave`);if(o.has(a))throw i(`${r}: \xABclave\xBB repetida.`);if(o.add(a),typeof t.nombre!="string"||!t.nombre.trim()||t.nombre.length>60)throw i(`${r}: el nombre del bot\xF3n (1\u201360).`);if(typeof t.destino!="string"||!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(t.destino))throw i(`${r}: \xABdestino\xBB, mod_<clave>.`);let s=Ot(t.enlace,`${r}.enlace`),c;if(t.campos!==void 0&&t.campos!==null){if(!zs(t.campos)||Object.keys(t.campos).length>40)throw i(`${r}: \xABcampos\xBB, un objeto destino \u2192 origen (hasta 40).`);for(let[d,u]of Object.entries(t.campos))if(!Ls.test(d)||typeof u!="string"||!Ls.test(u))throw i(`${r}: \xABcampos.${d.slice(0,40)}\xBB no es v\xE1lido.`);c=t.campos}return{clave:a,nombre:t.nombre.trim(),destino:t.destino,enlace:s,...c&&Object.keys(c).length?{campos:c}:{}}})}var Hm,yi,_i,Ls,zs,Xm,Ot,xi=f(()=>{Gm();q();Kr();Hm=["recuento","suma","minimo","maximo","ultimo","media"],yi=20,_i=5,Ls=/^[a-z][a-z0-9_]{0,40}$/,zs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Xm=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`)},Ot=(e,o)=>{if(typeof e!="string"||!Ls.test(e))throw i(`${o}: falta o no es v\xE1lido.`);return e}});function Fs(e,o){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw i("La configuraci\xF3n de ra\xEDces necesita objetos expl\xEDcitos.");let t={};for(let[n,r]of Object.entries(e)){if(!["contacts","companies"].includes(n)||!r||typeof r!="object"||Array.isArray(r))throw i("La configuraci\xF3n de ra\xEDces necesita contacts o companies.");let a={};for(let[s,c]of Object.entries(r)){if(!["ficha","impresion","relacionadas","siguientes","recurso","reserva"].includes(s))throw i("Configura ficha, impresi\xF3n, relacionadas, siguientes, recurso o reserva.");Object.assign(a,{[s]:(s==="ficha"?vi(c,o):s==="impresion"?Hr(c,o):s==="relacionadas"?Ni(c,o):s==="recurso"?mi(c,o):s==="reserva"?fi(c,o):$i(c))??null})}t[n]=a}return t}var Km=f(()=>{As();q();Ds();xi()});function Zm(e){if(e!==void 0){if(!e||typeof e!="object"||Array.isArray(e))throw i("Los ajustes nativos necesitan objetos expl\xEDcitos.");for(let[o,t]of Object.entries(e))if(!["contacts","companies"].includes(o)||!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(n=>!Ws.includes(n)))throw i("Un ajuste nativo no cambia la identidad de la relaci\xF3n.");return structuredClone(e)}}var Ws,Bs=f(()=>{q();Ws=["etiqueta","ayuda","enTabla","obligatorio","visibleSi","obligatorioSi","permisos","siVacio","completarDesde"]});function ef(e,o,t={}){for(let[r,a]of Object.entries(t)){let s=e.find(u=>u.clave===r&&!u.archivado),c=o[r],d=s?.opciones??[];if(s?.tipo!=="seleccion"||!c||!Object.hasOwn(Vs,c)||Object.keys(a).length!==d.length||!d.length||d.some(u=>!Object.hasOwn(a,u.valor))||Object.values(a).some(u=>typeof u!="string"||!u||u!==u.trim())||new Set(Object.values(a)).size!==d.length)throw i("Las conversiones nativas necesitan un mapa de selecciones completo.")}let n=new Map;for(let r of e){let a=o[r.clave];if(r.archivado||r.tipo!=="seleccion"||!a||!Object.hasOwn(Vs,a))continue;let s=Vs[a];if(r.opciones?.some(c=>c.hecho||c.requisito||c.pide?.length||c.limiteDias!==void 0||c.aprobacion))throw i("Las opciones de Personas/Empresas no pueden perder reglas de etapas.");n.set(s,Wr(s,(r.opciones??[]).map(c=>({value:Object.hasOwn(t,r.clave)?t[r.clave][c.valor]:c.valor,label:c.etiqueta,...c.color?{color:c.color}:{}}))))}return n}var Vs,of=f(()=>{q();xs();Vs={sector:"companySectors",forma_juridica:"legalForms"}});function Js(e,o){if(e===void 0)return;if(!To(e))throw i("\xABpersonas\xBB: un objeto.");if(Us(e,["objeto","tipo","de","campoNif","etiqueta","plural","icono","campos","conversiones","alternativa","clasificacion","configuracion"],"\xABpersonas\xBB"),e.alternativa!==void 0||e.clasificacion!==void 0)return sv(e,o);if(e.objeto==="deals"&&o.some(m=>m.tipo==="autonumero"))throw i("Los auton\xFAmeros propios no est\xE1n disponibles en Oportunidades.");if(e.objeto==="deals"&&o.some(m=>m.unico))throw i("Los campos propios \xFAnicos no est\xE1n disponibles en Oportunidades.");if(e.objeto!=="contacts"&&e.objeto!=="companies")throw i("\xABpersonas.objeto\xBB: contacts o companies.");let t=Ci(e.tipo,"tipo",60);if(!av.test(t))throw i("\xABpersonas.tipo\xBB: una clave de tipo.");if(e.de!==void 0&&e.de!=="cliente"&&e.de!=="proveedor")throw i("\xABpersonas.de\xBB: cliente o proveedor.");if(e.de===t||(t==="cliente"||t==="proveedor")&&e.de!==void 0)throw i("\xABpersonas.de\xBB: un tipo base no puede ser un subtipo.");let n=Ci(e.icono,"icono",40);if(!/^[a-z0-9-]+$/.test(n))throw i("\xABpersonas.icono\xBB: una clave de icono.");if(!To(e.campos))throw i("\xABpersonas.campos\xBB: un mapa expl\xEDcito de campos nativos.");let r={},a=new Map;for(let[m,h]of Object.entries(e.campos)){let b=o.find(w=>w.clave===m&&!w.archivado),y=typeof h=="string"&&Object.hasOwn(rf[e.objeto],h)?rf[e.objeto][h]:void 0,v=Ee(h);if(!b||!(v?Sm.has(b.tipo):y?.includes(b.tipo)))throw i(`\xABpersonas.campos.${m.slice(0,40)}\xBB: campo nativo o tipo incompatible.`);if(b.unico&&typeof h=="string"&&h.startsWith("persona."))throw i("El campo propio necesita conservar sus reglas antes de convertir la ra\xEDz.");if(a.has(h)&&h!=="nif"&&h!=="tax_identifier")throw i(`\xABpersonas.campos\xBB: dos campos apuntan a \xAB${h}\xBB.`);a.set(h,m),r[m]=h}let s=e.objeto==="contacts"?"first_name":"name";if(!a.has(s))throw i(`\xABpersonas.campos\xBB: falta el nombre nativo \xAB${s}\xBB.`);let c=o.filter(m=>!m.archivado);for(let m of c)if(!Object.hasOwn(r,m.clave)&&m.tipo!=="resumen"&&m.tipo!=="formula")throw i(`\xABpersonas.campos\xBB: falta destino para \xAB${m.clave}\xBB; no se puede perder un campo.`);if(e.conversiones!==void 0&&!To(e.conversiones))throw i("Las conversiones nativas necesitan un mapa de selecciones completo.");let d={};for(let[m,h]of Object.entries(e.conversiones??{})){if(!To(h)||Object.values(h).some(b=>typeof b!="string"))throw i("Las conversiones nativas necesitan un mapa de selecciones completo.");Object.defineProperty(d,m,{value:{...h},enumerable:!0})}let u=e.campoNif;if(u!==void 0&&(e.objeto!=="contacts"||typeof u!="string"||!Object.hasOwn(r,u)||!r[u]?.startsWith("datos.")||!o.some(m=>m.clave===u&&["texto","codigo"].includes(m.tipo))))throw i("\xABpersonas.campoNif\xBB: elige un campo propio de texto de Personas.");af(o,r,t),ef(o,r,d);let p=Fs(e.configuracion,o);if(p&&Object.keys(p).some(m=>m!==e.objeto))throw i("La configuraci\xF3n cita un objeto que esta ra\xEDz no declara.");return{objeto:e.objeto,tipo:t,...typeof u=="string"?{campoNif:u}:{},...e.de?{de:e.de}:{},...p?{configuracion:p}:{},etiqueta:Ci(e.etiqueta,"etiqueta",60),plural:Ci(e.plural,"plural",60),icono:n,campos:r,...e.conversiones!==void 0?{conversiones:d}:{}}}function sv(e,o){let t=e.alternativa,n=e.clasificacion;if(e.objeto!=="contacts"||!To(t)||t.objeto!=="companies"||!To(t.campos)||!To(n))throw i("Los destinos dobles necesitan Persona, Empresa y clasificaci\xF3n expl\xEDcita.");Us(t,["objeto","campos","conversiones"],"\xABpersonas.alternativa\xBB"),Us(n,["campo","valores","vacio","formas","etiquetas","propiedad"],"\xABpersonas.clasificacion\xBB");let r=o.find(v=>v.clave===n.campo&&!v.archivado);if(!r||!["seleccion","booleano"].includes(r.tipo)||!To(n.valores)||n.vacio!==void 0&&n.vacio!=="contacts"&&n.vacio!=="companies")throw i("La clasificaci\xF3n necesita todas las opciones de una selecci\xF3n o booleano.");if(r.opciones?.some(v=>v.hecho||v.requisito||v.pide?.length||v.limiteDias!==void 0||v.aprobacion))throw i("La clasificaci\xF3n no puede perder permisos ni reglas de etapas.");let a=r.tipo==="booleano"?["true","false"]:(r.opciones??[]).map(v=>v.valor);if(!a.length||Object.keys(n.valores).length!==a.length||a.some(v=>!Object.hasOwn(n.valores,v))||Object.values(n.valores).some(v=>v!=="contacts"&&v!=="companies")||!Object.values(n.valores).includes("contacts")||!Object.values(n.valores).includes("companies"))throw i("La clasificaci\xF3n necesita todas las opciones de una selecci\xF3n o booleano.");let s=um(n,r,n.valores),c={campo:r.clave,valores:{...n.valores},...n.vacio?{vacio:n.vacio}:{},...s},{alternativa:d,clasificacion:u,configuracion:p,...m}=e,h=v=>Js(v,pm(o,c,v.objeto).filter(w=>To(v.campos)&&Object.hasOwn(v.campos,w.clave)||w.tipo==="resumen"||w.tipo==="formula")),b=h(m),y=h({...m,objeto:"companies",campoNif:void 0,campos:t.campos,conversiones:t.conversiones});if(c.propiedad){if(b.campos[r.clave]!==c.propiedad||y.campos[r.clave]!==c.propiedad||b.conversiones?.[r.clave]||y.conversiones?.[r.clave])throw i("La clasificaci\xF3n propia necesita el mismo destino tipado en ambas ramas, sin conversiones.")}else if(Object.hasOwn(b.campos,r.clave)||Object.hasOwn(y.campos,r.clave))throw i("El discriminante de identidad no es un campo nativo.");for(let v of o.filter(w=>!w.archivado&&w.clave!==r.clave&&w.tipo!=="resumen"&&w.tipo!=="formula"))if(!Object.hasOwn(b.campos,v.clave)&&!Object.hasOwn(y.campos,v.clave))throw i("Los destinos deben conservar todos los campos del origen salvo el discriminante.");return dm(o,c),{...b,alternativa:{objeto:"companies",campos:y.campos,...y.conversiones?{conversiones:y.conversiones}:{}},clasificacion:c,...e.configuracion!==void 0?{configuracion:Fs(e.configuracion,o)}:{}}}var tf,rf,To,av,Ci,Us,nf=f(()=>{Br();Om();Km();q();mm();of();tf={ubicacion:["ubicacion"],address:["texto","texto_largo"],zipcode:["texto","codigo"],city:["texto"],country:["texto"],pais_fiscal:["texto","seleccion"],iban:["texto"]},rf={contacts:{...tf,province:["texto"],first_name:["texto"],last_name:["texto"],title:["texto"],correo:["correo"],telefono:["telefono"],background:["texto_largo","texto"],nif:["texto"],birthday:["fecha"],first_seen:["fecha","fecha_hora"],has_newsletter:["booleano"]},companies:{...tf,state_abbr:["texto"],name:["texto"],razon_social:["texto"],tax_identifier:["texto"],phone_number:["telefono"],website:["url"],description:["texto_largo","texto"],sector:["seleccion","texto"],forma_juridica:["seleccion","texto"],correo_facturacion:["correo"],has_newsletter:["booleano"],"persona.first_name":["texto"],"persona.last_name":["texto"],"persona.correo":["correo"],"persona.telefono":["telefono"]}},To=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),av=/^[a-z0-9][a-z0-9-]{0,59}$/,Ci=(e,o,t)=>{if(typeof e!="string"||!e.trim()||e.trim().length>t)throw i(`\xABpersonas.${o}\xBB: texto de 1 a ${t} caracteres.`);return e.trim()},Us=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`)}});import{createContext as cv,Script as lv}from"node:vm";function ji(e,o){if(e!=null){if(!Array.isArray(e)||e.length>sf)throw i(`\xAB${o}\xBB: como mucho ${sf} condiciones.`);if(e.length)return e.map(t=>{let n=t;if(typeof n!="object"||n===null||typeof n.campo!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(n.campo))throw i(`\xAB${o}\xBB: una condici\xF3n no es v\xE1lida.`);let r=n.op;if(!uv.includes(r))throw i(`\xAB${o}\xBB: condici\xF3n no v\xE1lida (${String(n.op).slice(0,20)}).`);let a={campo:n.campo,op:r};if(r==="igual"||r==="distinto"){if(!dv(n.valor))throw i(`\xAB${o}\xBB: la condici\xF3n necesita un valor.`);a.valor=n.valor}if(r==="uno_de"){if(!Array.isArray(n.valor)||!n.valor.length||n.valor.length>50||!n.valor.every(s=>typeof s=="string"||typeof s=="number"))throw i(`\xAB${o}\xBB: \xABuno de\xBB necesita una lista de valores.`);a.valor=n.valor}return a})}}function pf(e,o){if(!(e==null||e==="")){if(typeof e!="string"||e.length>cf)throw i(`\xAB${o}\xBB: el patr\xF3n, hasta ${cf} caracteres.`);if(/\\[1-9]|\\k<|\(\?<[=!]/.test(e))throw i(`\xAB${o}\xBB: el patr\xF3n no admite retroreferencias ni lookbehind.`);if(pv(e))throw i(`\xAB${o}\xBB: el patr\xF3n tiene un grupo repetido que se puede disparar (p. ej. \xAB(a+)+\xBB); simplif\xEDcalo.`);try{new RegExp(e,"u")}catch{throw i(`\xAB${o}\xBB: el patr\xF3n no es una expresi\xF3n regular v\xE1lida.`)}return e}}function pv(e){let o=[],t=!1;for(let n=0;n<e.length;n++){let r=e[n];if(r==="\\"){n++;continue}if(t){r==="]"&&(t=!1);continue}if(r==="["){t=!0;continue}if(r==="("){o.push(!1);continue}if(r===")"){let a=o.pop()??!1,s=e.slice(n+1),c=/^(?:[+*]|\{\d*,)/.test(s)||/^\{(\d+)\}/.test(s)&&Number(/^\{(\d+)\}/.exec(s)[1])>1;if(a&&c)return!0;o.length&&(a||c)&&(o[o.length-1]=!0);continue}(r==="+"||r==="*"||r==="?"||r==="{"||r==="|")&&o.length&&(o[o.length-1]=!0)}return!1}function mf(e,o){if(e==null)return;let t=e,n=t?.tipo;if(typeof t!="object"||!lf[n])throw i(`\xAB${o.etiqueta}\xBB: valor por defecto no v\xE1lido.`);if(!lf[n].includes(o.tipo))throw i(`\xAB${o.etiqueta}\xBB: ese valor por defecto no vale para este tipo.`);if(n==="fijo")return{tipo:n,valor:t.valor};if(n==="formula"){if(typeof t.formula!="string"||!t.formula.trim()||t.formula.length>1e3)throw i(`\xAB${o.etiqueta}\xBB: escribe la f\xF3rmula por defecto.`);return{tipo:n,formula:t.formula.trim()}}return{tipo:n}}var uv,sf,cf,uf,df,lf,dv,uD,dD,ff=f(()=>{q();uv=["igual","distinto","vacio","lleno","uno_de"],sf=10,cf=200,uf=["texto","correo","telefono","url","codigo"],df=["texto","correo","telefono","url","codigo","numero","importe"],lf={fijo:["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","seleccion_multiple","url","correo","telefono","duracion","porcentaje","valoracion","contador","cronometro","color","codigo","hora"],hoy:["fecha","fecha_hora"],ahora:["fecha_hora"],yo:["texto","correo"],formula:["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","porcentaje","duracion"]},dv=e=>typeof e=="string"&&e.length<=200||typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean";uD=cv({p:"",v:""}),dD=new lv("new RegExp(p, 'u').test(v)")});function gf(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>hf)throw i(`\xABvalidaciones\xBB: hasta ${hf}.`);let t=[];for(let[n,r]of e.entries()){if(!fv(r))throw i(`Validaci\xF3n ${n+1}: un objeto.`);for(let s of Object.keys(r))if(s!=="formula"&&s!=="mensaje")throw i(`Validaci\xF3n ${n+1}: clave no admitida \xAB${s.slice(0,40)}\xBB.`);if(typeof r.formula!="string"||!r.formula.trim()||r.formula.length>no)throw i(`Validaci\xF3n ${n+1}: la f\xF3rmula, de 1 a ${no} caracteres.`);if(typeof r.mensaje!="string"||!r.mensaje.trim()||r.mensaje.length>200)throw i(`Validaci\xF3n ${n+1}: el mensaje, de 1 a 200 caracteres.`);let a;try{a=gi([...o,hv(n,r.formula)]).at(-1)}catch(s){throw i(`Validaci\xF3n ${n+1}: ${s instanceof Error?s.message:"la f\xF3rmula no vale"}`)}if(a.origen?.tipo!=="booleano")throw i(`Validaci\xF3n ${n+1}: la f\xF3rmula tiene que dar s\xED o no (una comparaci\xF3n, Y(), O()\u2026).`);t.push({formula:a.formula,mensaje:r.mensaje.trim()})}return t.length?t:void 0}var hf,fv,hv,bf=f(()=>{q();bi();hf=20,fv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hv=(e,o)=>({clave:`validacion_${e}`,etiqueta:`Validaci\xF3n ${e+1}`,tipo:"formula",formula:o})});function yf(e,o){if(e==null)return;let t=`\xAB${o.etiqueta}\xBB`;if(o.tipo!=="seleccion"&&o.tipo!=="relacion")throw i(`${t}: solo una selecci\xF3n o una relaci\xF3n pueden depender de otro campo.`);if(!vf(e))throw i(`${t}: \xABdepende\xBB, un objeto.`);for(let n of Object.keys(e))if(!["campo","opciones","via"].includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`);if(typeof e.campo!="string"||!wf.test(e.campo))throw i(`${t}: \xBFde qu\xE9 campo depende?`);if(o.tipo==="seleccion"){if(!vf(e.opciones)||Object.keys(e.opciones).length>200)throw i(`${t}: qu\xE9 opciones valen para cada valor del otro campo (hasta 200).`);let n={};for(let[r,a]of Object.entries(e.opciones)){if(r.length>100||!Array.isArray(a)||a.length>200||!a.every(s=>typeof s=="string"&&s.length<=100))throw i(`${t}: las opciones de \xAB${r.slice(0,40)}\xBB, una lista de valores.`);n[r]=[...new Set(a)]}return{campo:e.campo,opciones:n}}if(typeof e.via!="string"||!wf.test(e.via))throw i(`${t}: por qu\xE9 campo del otro m\xF3dulo se filtra (\xABvia\xBB).`);return{campo:e.campo,via:e.via}}function _f(e){let o=e.filter(t=>!t.archivado);for(let t of o.filter(n=>n.depende)){let n=t.depende,r=o.find(a=>a.clave===n.campo);if(!r||r.clave===t.clave)throw i(`\xAB${t.etiqueta}\xBB: depende de un campo que no existe.`);if(t.tipo==="seleccion"){if(r.tipo!=="seleccion")throw i(`\xAB${t.etiqueta}\xBB: una selecci\xF3n depende de otra selecci\xF3n.`);let a=new Set((r.opciones??[]).map(c=>c.valor)),s=new Set((t.opciones??[]).map(c=>c.valor));for(let[c,d]of Object.entries(n.opciones??{})){if(!a.has(c))throw i(`\xAB${t.etiqueta}\xBB: \xAB${c.slice(0,40)}\xBB no es una opci\xF3n de \xAB${r.etiqueta}\xBB.`);let u=d.find(p=>!s.has(p));if(u!==void 0)throw i(`\xAB${t.etiqueta}\xBB: \xAB${u.slice(0,40)}\xBB no es una de sus opciones.`)}}else if(r.tipo!=="relacion"||r.multiple||t.multiple)throw i(`\xAB${t.etiqueta}\xBB: una relaci\xF3n (de uno) depende de otra relaci\xF3n de uno de este m\xF3dulo.`)}for(let t of o.filter(n=>n.depende)){let n=new Set([t.clave]);for(let r=o.find(a=>a.clave===t.depende.campo);r?.depende;r=o.find(a=>a.clave===r.depende.campo)){if(n.has(r.clave))throw i(`\xAB${t.etiqueta}\xBB: las dependencias forman un c\xEDrculo.`);n.add(r.clave)}}}var wf,vf,Nf=f(()=>{q();wf=/^[a-z][a-z0-9_]{0,39}$/,vf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function xf(e,o){if(!Array.isArray(e)||e.length>300)throw i("Hasta 300 transiciones por campo.");let t=new Set(o.opciones?.map(r=>r.valor)),n=new Set;return e.map(r=>{if(!$f(r)||r.desde!==null&&!t.has(r.desde)||!t.has(r.hasta)||r.desde===r.hasta)throw i("El origen y el destino deben ser estados diferentes del campo; el origen vac\xEDo representa el alta.");let a=JSON.stringify([r.desde,r.hasta]);if(n.has(a))throw i("Transici\xF3n repetida.");n.add(a);let s={desde:r.desde,hasta:r.hasta};if(s.papeles=Qs(r.papeles,30,/^(titular|administrador|miembro|lectura|p_[a-z]{1,12})$/),s.pide=Qs(r.pide,30,/^[a-z][a-z0-9_]{0,40}$/),s.acciones=Qs(r.acciones,10),r.aprobacion!==void 0){let c=r.aprobacion;if(!$f(c)||c.papel!==void 0&&(typeof c.papel!="string"||!/^[a-z_]{1,40}$/.test(c.papel))||c.personas!==void 0&&(!Number.isInteger(c.personas)||Number(c.personas)<1||Number(c.personas)>10))throw i("Aprobaci\xF3n de transici\xF3n no v\xE1lida.");s.aprobacion={papel:c.papel,personas:c.personas}}return s})}function Cf(e){for(let o of e)for(let t of o.transiciones??[])for(let n of t.pide??[]){let r=e.find(a=>a.clave===n&&!a.archivado);if(!r||["formula","resumen","busqueda","subtabla","boton","autonumero","creado_el","creado_por","modificado_el","modificado_por"].includes(r.tipo))throw i("La guarda debe referirse a un campo editable del m\xF3dulo.")}return e}var $f,Qs,jf=f(()=>{q();$f=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Qs=(e,o,t)=>{if(e!==void 0){if(!Array.isArray(e)||e.length>o||e.some(n=>typeof n!="string"||!n.trim()||n.length>80||t&&!t.test(n)))throw i("Lista de transici\xF3n no v\xE1lida.");if(new Set(e).size!==e.length)throw i("La transici\xF3n contiene valores repetidos.");return e}}});function Sf(e,o,t){if(e.aprobacion===void 0||e.aprobacion===null)return;let n=e.aprobacion;if(typeof n!="object"||Array.isArray(n))throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: la aprobaci\xF3n, un objeto.`);let r=n.papel===void 0||n.papel===null||n.papel===""?void 0:n.papel;if(r!==void 0&&(typeof r!="string"||!/^[a-z_]{1,40}$/.test(r)))throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: el papel que aprueba no es v\xE1lido.`);let a=n.personas===void 0||n.personas===null?1:n.personas;if(!Number.isInteger(a)||a<1||a>10)throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: de 1 a 10 personas.`);o.aprobacion={...r?{papel:r}:{},personas:a}}var ND,Of=f(()=>{ci();q();ND=A`select a.*, m.clave,
|
|
18
|
+
and not exists (select 1 from festivos f where f.espacio_id = crm_espacio() and f.fecha = g.d::date))::numeric end)`}}};Object.assign(Ls,{RESTO:{args:["numero","numero"],tipo:()=>"numero",sql:e=>A`mod((${e[0]})::numeric, nullif((${e[1]})::numeric, 0))`},CAMBIAR:{args:["cualquiera"],resto:"cualquiera",tipo:e=>{if(e.length<3)throw i("F\xF3rmula: CAMBIAR lleva el valor y, al menos, un caso y su resultado.");let o=null;for(let t=1;t<e.length;t+=2)t+1<e.length?(tr(e[0],e[t]),o=o?tr(o,e[t+1]):e[t+1]):o=o?tr(o,e[t]):e[t];return o},sql:e=>{let o=[];for(let n=1;n+1<e.length;n+=2)o.push(A`when ${e[0]} = ${e[n]} then ${e[n+1]}`);let t=(e.length-1)%2===1?A`else ${e[e.length-1]}`:A``;return A`(case ${A.join(o,A` `)} ${t} end)`}},CONTIENE:{args:["texto","texto"],tipo:()=>"booleano",sql:e=>A`(strpos(lower(${e[0]}), lower(${e[1]})) > 0)`},SUSTITUIR:{args:["texto","texto","texto"],tipo:()=>"texto",sql:e=>A`replace(${e[0]}, ${e[1]}, coalesce(${e[2]}, ''))`},ANADIR_MESES:{args:["cualquiera","numero"],tipo:e=>{if(!ro(e,0))throw i("F\xF3rmula: A\xD1ADIR_MESES necesita una fecha.");return e[0]},sql:(e,o)=>o[0]==="fecha"?A`((${e[0]} + make_interval(months => ${or(e[1],12e3)}))::date)`:A`(${e[0]} + make_interval(months => ${or(e[1],12e3)}))`},HORAS_ENTRE:{args:["cualquiera","cualquiera"],tipo:e=>{if(!ro(e,0)||!ro(e,1))throw i("F\xF3rmula: HORAS_ENTRE necesita dos fechas (o fechas y horas).");return"numero"},sql:(e,o)=>{let t=(n,r)=>r==="fecha"?A`((${n})::timestamp at time zone ${Is})`:n;return A`round((extract(epoch from (${t(e[1],o[1])} - ${t(e[0],o[0])})) / 3600)::numeric, 6)`}}});yv={IF:"SI",AND:"Y",OR:"O",NOT:"NO",ISBLANK:"VACIO",ESBLANCO:"VACIO",ROUND:"REDONDEAR",CONCATENAR:"CONCAT",UPPER:"MAYUSCULAS",LOWER:"MINUSCULAS",LEFT:"IZQUIERDA",RIGHT:"DERECHA",LEN:"LARGO",TRIM:"RECORTAR",TEXT:"TEXTO",TODAY:"HOY",NOW:"AHORA",DATETIME_DIFF:"DIAS_ENTRE",DAYS:"DIAS_ENTRE",DATEADD:"ANADIR_DIAS",YEAR:"ANO",MONTH:"MES",DAY:"DIA",POWER:"POTENCIA",PMT:"PAGO",CEIL:"REDONDEAR_ARRIBA",CEILING:"REDONDEAR_ARRIBA",FLOOR:"REDONDEAR_ABAJO",NETWORKDAYS:"DIAS_HABILES",DIAS_LAB:"DIAS_HABILES",MOD:"RESTO",SWITCH:"CAMBIAR",SUBSTITUTE:"SUSTITUIR",EDATE:"ANADIR_MESES",ADDMONTHS:"ANADIR_MESES"},cL=Object.keys(Ls);jt={numero:"un n\xFAmero",texto:"un texto",fecha:"una fecha",fecha_hora:"una fecha y hora",booleano:"un s\xED/no"};Ds={numero:"numero",importe:"numero",duracion:"numero",porcentaje:"numero",valoracion:"numero",contador:"numero",cronometro:"numero",texto:"texto",texto_largo:"texto",correo:"texto",telefono:"texto",url:"texto",color:"texto",codigo:"texto",seleccion:"texto",autonumero:"texto",fecha:"fecha",fecha_hora:"fecha_hora",hecho:"fecha_hora",creado_el:"fecha_hora",modificado_el:"fecha_hora",booleano:"booleano"},Vm={texto:"texto",texto_largo:"texto",correo:"texto",telefono:"texto",url:"texto",seleccion:"texto",numero:"numero",importe:"numero",fecha:"fecha",fecha_hora:"fecha_hora",booleano:"booleano"},lL={numero:A`numeric`,texto:A`text`,fecha:A`date`,fecha_hora:A`timestamptz`,booleano:A`boolean`},zs=e=>e.campos.filter(o=>!o.archivado);_v=e=>{let o=e.campos.find(t=>t.clave===e.campo&&!t.archivado);if(!o)throw i(`F\xF3rmula: \xAB${e.campo}\xBB ya no est\xE1 en el otro m\xF3dulo.`);return o};xv=new Set(["creado_el","creado_por","modificado_el","modificado_por","autonumero"]),Qm={companies:"companies_summary",contacts:"contacts_summary",deals:"deals"}});function Hm(e,o){if(e==null)return;if(!Hr(e))throw i("\xABerp\xBB: un objeto.");let t=(r,a,s=!1)=>{if(!(r===void 0&&s)){if(typeof r!="string"||!o.some(c=>c.clave===r&&c.tipo!=="subtabla"))throw i(`ERP: \xAB${a}\xBB no es un campo del m\xF3dulo.`);return r}},n={};if(e.presupuesto!==void 0){let r=e.presupuesto;if(!Hr(r)||!Hr(r.lineas))throw i("ERP: \xABpresupuesto\xBB con \xABcliente\xBB y \xABlineas\xBB.");let a=o.find(d=>d.clave===r.lineas.subtabla&&d.tipo==="subtabla");if(!a)throw i("ERP: \xABlineas.subtabla\xBB no es una subtabla del m\xF3dulo.");let s=r.lineas,c=(d,u,p=!1)=>{if(!(d===void 0&&p)){if(typeof d!="string"||!(a.columnas??[]).some(m=>m.clave===d))throw i(`ERP: \xAB${u}\xBB no es una columna de la subtabla.`);return d}};if(s.articulo!==void 0&&!(a.columnas??[]).some(d=>d.clave===s.articulo&&d.tipo==="articulo"))throw i("ERP: \xABarticulo\xBB, una columna de art\xEDculo de la subtabla.");if(r.tipo!==void 0&&r.tipo!=="presupuesto"&&r.tipo!=="factura")throw i("ERP: \xABtipo\xBB, presupuesto o factura.");if(r.clienteAlternativo!==void 0&&r.clienteAlternativo===r.cliente)throw i("ERP: las relaciones de cliente deben ser distintas.");n.presupuesto={...r.tipo?{tipo:r.tipo}:{},cliente:t(r.cliente,"cliente"),...r.clienteAlternativo!==void 0?{clienteAlternativo:t(r.clienteAlternativo,"clienteAlternativo")}:{},lineas:{subtabla:a.clave,descripcion:c(s.descripcion,"descripcion"),precio:c(s.precio,"precio"),...s.cantidad!==void 0?{cantidad:c(s.cantidad,"cantidad")}:{},...s.iva!==void 0?{iva:c(s.iva,"iva")}:{},...s.articulo!==void 0?{articulo:s.articulo}:{}}}}if(e.gasto!==void 0){let r=e.gasto;if(!Hr(r))throw i("ERP: \xABgasto\xBB, un objeto.");if(r.tipo!==void 0&&r.tipo!=="factura"&&r.tipo!=="ticket")throw i("ERP: el gasto es factura o ticket.");n.gasto={...r.tipo?{tipo:r.tipo}:{},proveedor:t(r.proveedor,"proveedor"),fecha:t(r.fecha,"fecha"),base:t(r.base,"base"),...r.nif!==void 0?{nif:t(r.nif,"nif")}:{},...r.numero!==void 0?{numero:t(r.numero,"numero")}:{},...r.iva!==void 0?{iva:t(r.iva,"iva")}:{}}}if(e.horas!==void 0){let r=e.horas;if(!Hr(r))throw i("ERP: \xABhoras\xBB, un objeto.");let a=t(r.guardarEn,"guardarEn",!0);if(a&&!o.some(s=>s.clave===a&&["numero","duracion"].includes(s.tipo)))throw i("ERP: \xABguardarEn\xBB, un campo num\xE9rico.");n.horas={desde:t(r.desde,"desde"),hasta:t(r.hasta,"hasta"),...r.persona!==void 0?{persona:t(r.persona,"persona")}:{},...a?{guardarEn:a}:{}}}return Object.keys(n).length?n:void 0}var Hr,Xm=f(()=>{R();Hr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Zm(e,o){if(e==null)return;if(!ko(e))throw i("\xABimpresion\xBB: un objeto.");let{ejemplares:t,cuerpo:n,...r}=e;if(r.subtabla!==void 0)throw i("Impresi\xF3n: clave no admitida \xABsubtabla\xBB.");let a=Xr(r,o)??{},s=nr(n,"El texto del documento",ef);if(s){for(let c of s.matchAll(/\{\{\s*([^}]*?)\s*\}\}/g)){let d=c[1].split("|")[0].trim();if(d!=="hoy"&&d!=="espacio.nombre"&&!/^padre\.[a-z][a-z0-9_]{0,40}$/.test(d)&&!o.some(u=>u.clave===d&&!u.archivado))throw i(`El texto del documento: \xAB{{${d.slice(0,40)}}}\xBB no es una columna de la l\xEDnea ni \xABpadre.<campo>\xBB.`)}a.cuerpo=s}if(t!=null){if(!Array.isArray(t)||t.length>3||t.some(c=>typeof c!="string"||!c.trim()||c.length>60))throw i("\xABejemplares\xBB: hasta 3, cada uno con su r\xF3tulo (hasta 60).");t.length&&(a.ejemplares=t.map(c=>c.trim()))}return Object.keys(a).length?a:void 0}function rr(e,o,t){for(let n of Object.keys(e))if(!o.includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`)}function nr(e,o,t){if(!(e==null||e==="")){if(typeof e!="string"||e.length>t)throw i(`${o}: texto de hasta ${t} caracteres.`);return e.trim()||void 0}}function St(e,o,t,n,r=()=>!0){if(e==null)return;if(!Array.isArray(e)||e.length>t||!e.every(s=>typeof s=="string"))throw i(`${n}: hasta ${t} claves de campo.`);let a=new Set(o.filter(s=>!s.archivado&&r(s)).map(s=>s.clave));return[...new Set(e)].filter(s=>a.has(s))}function Ym(e,o){if(e===void 0)return;if(!ko(e))throw i("La condici\xF3n de ficha necesita un campo y un valor.");rr(e,["campo","valor"],"Condici\xF3n de ficha");let t=o.find(n=>n.clave===e.campo&&!n.archivado);if(t?.tipo==="seleccion"&&typeof e.valor=="string"&&t.opciones?.some(n=>n.valor===e.valor))return{campo:t.clave,valor:e.valor};if(t?.tipo==="booleano"&&typeof e.valor=="boolean")return{campo:t.clave,valor:e.valor};throw i("La condici\xF3n de ficha necesita una opci\xF3n del campo o un valor de s\xED/no.")}function yi(e,o){if(e==null)return;if(!ko(e))throw i("\xABficha\xBB: un objeto.");rr(e,["cabecera","columnas","pestanas","grupos","relacionadas","erp","sin_conexion","rapido","duplicados","tarjeta","en_crear","filtros","principal","plegar_vacios"],"Ficha");let t={},n=St(e.cabecera,o,4,"La cabecera",p=>!["subtabla","boton","archivos","texto_largo"].includes(p.tipo));if(n?.length&&(t.cabecera=n),e.columnas!==void 0){if(e.columnas!==1&&e.columnas!==2&&e.columnas!==3)throw i("\xABcolumnas\xBB: 1, 2 o 3.");e.columnas>1&&(t.columnas=e.columnas)}if(e.pestanas!==void 0){if(!Array.isArray(e.pestanas)||e.pestanas.length>6)throw i("Hasta 6 pesta\xF1as.");let p=e.pestanas.map((m,h)=>{if(!ko(m))throw i(`Pesta\xF1a ${h+1}: un objeto.`);rr(m,["titulo","secciones","artefacto","cuando"],`Pesta\xF1a ${h+1}`);let b=nr(m.titulo,`Pesta\xF1a ${h+1}`,40);if(!b)throw i(`Pesta\xF1a ${h+1}: falta el t\xEDtulo.`);let y=Ym(m.cuando,o);if(m.artefacto!==void 0){let v=Number(m.artefacto);if(!Number.isSafeInteger(v)||v<1)throw i(`Pesta\xF1a ${h+1}: el artefacto no es v\xE1lido.`);return{titulo:b,secciones:[],artefacto:v,...y?{cuando:y}:{}}}if(!Array.isArray(m.secciones)||m.secciones.length>20||!m.secciones.every(v=>typeof v=="string"&&v.length<=60))throw i(`Pesta\xF1a ${h+1}: sus secciones, hasta 20.`);return{titulo:b,secciones:[...new Set(m.secciones)],...y?{cuando:y}:{}}});p.length&&(t.pestanas=p)}if(e.grupos!==void 0){if(!Array.isArray(e.grupos)||e.grupos.length>40)throw i("Hasta 40 grupos de ficha.");let p=new Set(o.filter(b=>!b.archivado).map(b=>b.seccion??"")),m=new Set,h=e.grupos.map(b=>{if(!ko(b))throw i("Grupo de ficha: un objeto.");if(rr(b,["seccion","cuando","plegado"],"Grupo de ficha"),typeof b.seccion!="string"||!p.has(b.seccion)||m.has(b.seccion))throw i("El grupo debe corresponder a una secci\xF3n distinta de la ficha.");if(b.plegado!==void 0&&typeof b.plegado!="boolean")throw i("Grupo plegado: s\xED o no.");m.add(b.seccion);let y=Ym(b.cuando,o);return{seccion:b.seccion,...y?{cuando:y}:{},...b.plegado!==void 0?{plegado:b.plegado}:{}}});h.length&&(t.grupos=h)}if(e.relacionadas!==void 0){if(e.relacionadas!=="abajo"&&e.relacionadas!=="pestana")throw i("\xABrelacionadas\xBB: abajo o pestana.");e.relacionadas==="pestana"&&(t.relacionadas="pestana")}let r=Hm(e.erp,o);if(r&&(t.erp=r),e.sin_conexion!==void 0){if(typeof e.sin_conexion!="boolean")throw i("\xABsin_conexion\xBB: s\xED o no.");e.sin_conexion&&(t.sin_conexion=!0)}let a=St(e.rapido,o,3,"El registro r\xE1pido",p=>!["subtabla","boton","archivos","firma","busqueda","resumen","formula","autonumero","creado_el","creado_por","modificado_el","modificado_por"].includes(p.tipo));a?.length&&(t.rapido=a);let s=St(e.duplicados,o,3,"Los campos de duplicados",p=>Sv.includes(p.tipo));s?.length&&(t.duplicados=s);let c=St(e.tarjeta,o,3,"La tarjeta",p=>!["subtabla","boton","archivos","texto_largo","firma"].includes(p.tipo));if(c?.length&&(t.tarjeta=c),e.en_crear!==void 0){if(typeof e.en_crear!="boolean")throw i("\xABen_crear\xBB: s\xED o no.");e.en_crear&&(t.en_crear=!0)}let d=St(e.filtros,o,4,"Los filtros de arriba",p=>Ov.includes(p.tipo));d?.length&&(t.filtros=d);let u=St(e.principal,o,8,"El contenido principal",p=>p.tipo!=="boton");if(u?.length&&(t.principal=u),e.plegar_vacios!==void 0){if(typeof e.plegar_vacios!="boolean")throw i("\xABplegar_vacios\xBB: s\xED o no.");e.plegar_vacios||(t.plegar_vacios=!1)}return Object.keys(t).length?t:void 0}function Xr(e,o){if(e==null)return;if(!ko(e))throw i("\xABimpresion\xBB: un objeto.");rr(e,["titulo","campos","subtabla","subtablaVacia","pie","logo","orientacion","cuerpo","color","firmas"],"Impresi\xF3n");let t={},n=nr(e.titulo,"El t\xEDtulo de la impresi\xF3n",80);n&&(t.titulo=n);let r=St(e.campos,o,40,"Los campos de la impresi\xF3n",c=>!["subtabla","boton"].includes(c.tipo));if(r?.length&&(t.campos=r),e.subtabla!==void 0&&e.subtabla!==null&&e.subtabla!==""){if(typeof e.subtabla!="string")throw i("\xABsubtabla\xBB: la clave de una subtabla.");o.some(c=>c.clave===e.subtabla&&c.tipo==="subtabla"&&!c.archivado)&&(t.subtabla=e.subtabla)}if(t.subtabla&&e.subtablaVacia!=null&&e.subtablaVacia!==""){if(typeof e.subtablaVacia!="string"||e.subtablaVacia.length>120)throw i("El texto de la subtabla vac\xEDa admite hasta 120 caracteres.");e.subtablaVacia.trim()&&(t.subtablaVacia=e.subtablaVacia.trim())}let a=nr(e.pie,"El pie de la impresi\xF3n",500);if(a&&(t.pie=a),e.logo!==void 0){if(typeof e.logo!="boolean")throw i("\xABlogo\xBB: s\xED o no.");e.logo&&(t.logo=!0)}if(e.orientacion!==void 0){if(e.orientacion!=="vertical"&&e.orientacion!=="horizontal")throw i("\xABorientacion\xBB: vertical u horizontal.");e.orientacion==="horizontal"&&(t.orientacion="horizontal")}let s=nr(e.cuerpo,"El texto del documento",ef);if(s){for(let c of s.matchAll(/\{\{\s*([^}]*?)\s*\}\}/g)){let d=c[1].split("|")[0].trim();if(d!=="hoy"&&d!=="espacio.nombre"&&!o.some(u=>u.clave===d&&!u.archivado))throw i(`El texto del documento: \xAB{{${d.slice(0,40)}}}\xBB no es un campo del m\xF3dulo.`)}t.cuerpo=s}if(e.color!==void 0&&e.color!==null&&e.color!==""){if(typeof e.color!="string"||!/^#[0-9a-fA-F]{6}$/.test(e.color))throw i("\xABcolor\xBB: #rrggbb.");t.color=e.color.toLowerCase()}if(e.firmas!==void 0&&e.firmas!==null){if(!Array.isArray(e.firmas)||e.firmas.length>4||e.firmas.some(c=>typeof c!="string"||!c.trim()||c.length>60))throw i("\xABfirmas\xBB: hasta 4 casillas, cada una con su texto (hasta 60).");e.firmas.length&&(t.firmas=e.firmas.map(c=>c.trim()))}return Object.keys(t).length?t:void 0}function Fs(e,o=0){return o>10?!1:Array.isArray(e)?e.every(t=>Fs(t,o+1)):ko(e)?Object.keys(e).every(t=>!Av.has(t)&&Fs(e[t],o+1)):!0}function of(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>10)throw i("\xABvistas\xBB: hasta 10.");let t=e.map((n,r)=>{if(!ko(n))throw i(`Vista ${r+1}: un objeto.`);rr(n,["nombre","tipo","config"],`Vista ${r+1}`);let a=nr(n.nombre,`Vista ${r+1}`,60);if(!a)throw i(`Vista ${r+1}: falta el nombre.`);if(typeof n.tipo!="string"||!Km.includes(n.tipo))throw i(`Vista ${r+1}: tipo ${Km.join(", ")}.`);if(n.config!==void 0&&(!ko(n.config)||!Fs(n.config)||JSON.stringify(n.config).length>4e3))throw i(`Vista ${r+1}: \xABconfig\xBB, un objeto de hasta 4 KB.`);let s=n.config;if(n.tipo==="kanban"&&s?.segundo!==void 0){let c=o.find(d=>d.clave===s.segundo&&!d.archivado);if(!c||c.clave===s.agrupar||!(c.tipo==="seleccion"&&c.opciones?.length||c.tipo==="relacion"&&!c.multiple))throw i("El segundo campo del kanban debe ser una selecci\xF3n o una relaci\xF3n simple distinta de la primera.")}return{nombre:a,tipo:n.tipo,...n.config?{config:n.config}:{}}});return t.length?t:void 0}var ko,Sv,Ov,ef,Km,Av,Ws=f(()=>{R();Xm();ko=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);Sv=["texto","correo","telefono","codigo","url"],Ov=["seleccion","seleccion_multiple","etiquetas","booleano","hecho","creado_por","modificado_por","relacion","texto","texto_largo","correo","telefono","url","codigo","autonumero","ubicacion","numero","importe","porcentaje","fecha","fecha_hora","duracion","valoracion"];ef=12e3;Km=["kanban","calendario","linea","mapa","galeria","tablero","cuadrante","dia"],Av=new Set(["__proto__","constructor","prototype"])});var Yr,tf=f(()=>{Yr=e=>e==="@contacts"||e==="@companies"});function $i(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>_i)throw i(`\xABrelacionadas\xBB: hasta ${_i} columnas.`);if(!e.length)return;let t=new Set;return e.map((n,r)=>{let a=`Columna relacionada ${r+1}`;if(!Us(n))throw i(`${a}: un objeto.`);nf(n,["clave","etiqueta","via","campo","de","calculo","filtro","siVacio"],a);let s=Ot(n.clave,`${a}.clave`);if(t.has(s)||o.some(u=>u.clave===s))throw i(`${a}: la clave \xAB${s}\xBB ya la usa otra columna o un campo.`);if(t.add(s),typeof n.etiqueta!="string"||!n.etiqueta.trim()||n.etiqueta.length>80)throw i(`${a}: \xABetiqueta\xBB, de 1 a 80 caracteres.`);let c=Yr(String(n.de))&&typeof n.via=="string"&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(n.via)?n.via:Ot(n.via,`${a}.via`);if(n.de!==void 0){if(n.siVacio!==void 0)throw i("\xABsiVacio\xBB solo se admite al traer un valor escalar.");let u=typeof n.de=="string"&&Yr(n.de)?n.de:Ot(n.de,`${a}.de`);if(typeof n.calculo!="string"||!rf.includes(n.calculo))throw i(`${a}: \xABcalculo\xBB, uno de ${rf.join(", ")}.`);let p=n.calculo,m=p==="recuento"?void 0:Yr(u)&&typeof n.campo=="string"&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(n.campo)?n.campo:Ot(n.campo,`${a}.campo`),h=Kr(n.filtro,a,Yr(u));return{clave:s,etiqueta:n.etiqueta.trim(),via:c,de:u,calculo:p,...m?{campo:m}:{},...h?{filtro:h}:{}}}if(n.calculo!==void 0||n.filtro!==void 0)throw i(`${a}: \xABcalculo\xBB y \xABfiltro\xBB solo con \xABde\xBB (los hijos).`);let d=o.find(u=>u.clave===c&&!u.archivado);if(!d||d.tipo!=="relacion")throw i(`${a}: \xAB${c}\xBB no es una relaci\xF3n de este m\xF3dulo.`);if(d.multiple&&n.siVacio!==void 0)throw i("Una colecci\xF3n no tiene alternativa escalar.");if(typeof n.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(n.campo))throw i(`${a}: campo no v\xE1lido.`);return{clave:s,etiqueta:n.etiqueta.trim(),via:c,campo:n.campo,...n.siVacio!==void 0?{siVacio:Ot(n.siVacio,`${a}.siVacio`)}:{}}})}function xi(e){if(e==null)return;if(!Array.isArray(e)||e.length>Ni)throw i(`\xABsiguientes\xBB: hasta ${Ni} pasos.`);if(!e.length)return;let o=new Set;return e.map((t,n)=>{let r=`Siguiente paso ${n+1}`;if(!Us(t))throw i(`${r}: un objeto.`);nf(t,["clave","nombre","destino","enlace","campos"],r);let a=Ot(t.clave,`${r}.clave`);if(o.has(a))throw i(`${r}: \xABclave\xBB repetida.`);if(o.add(a),typeof t.nombre!="string"||!t.nombre.trim()||t.nombre.length>60)throw i(`${r}: el nombre del bot\xF3n (1\u201360).`);if(typeof t.destino!="string"||!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(t.destino))throw i(`${r}: \xABdestino\xBB, mod_<clave>.`);let s=Ot(t.enlace,`${r}.enlace`),c;if(t.campos!==void 0&&t.campos!==null){if(!Us(t.campos)||Object.keys(t.campos).length>40)throw i(`${r}: \xABcampos\xBB, un objeto destino \u2192 origen (hasta 40).`);for(let[d,u]of Object.entries(t.campos))if(!Bs.test(d)||typeof u!="string"||!Bs.test(u))throw i(`${r}: \xABcampos.${d.slice(0,40)}\xBB no es v\xE1lido.`);c=t.campos}return{clave:a,nombre:t.nombre.trim(),destino:t.destino,enlace:s,...c&&Object.keys(c).length?{campos:c}:{}}})}var rf,_i,Ni,Bs,Us,nf,Ot,Ci=f(()=>{tf();R();Zr();rf=["recuento","suma","minimo","maximo","ultimo","media"],_i=20,Ni=5,Bs=/^[a-z][a-z0-9_]{0,40}$/,Us=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nf=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`)},Ot=(e,o)=>{if(typeof e!="string"||!Bs.test(e))throw i(`${o}: falta o no es v\xE1lido.`);return e}});function Vs(e,o){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw i("La configuraci\xF3n de ra\xEDces necesita objetos expl\xEDcitos.");let t={};for(let[n,r]of Object.entries(e)){if(!["contacts","companies"].includes(n)||!r||typeof r!="object"||Array.isArray(r))throw i("La configuraci\xF3n de ra\xEDces necesita contacts o companies.");let a={};for(let[s,c]of Object.entries(r)){if(!["ficha","impresion","relacionadas","siguientes","recurso","reserva"].includes(s))throw i("Configura ficha, impresi\xF3n, relacionadas, siguientes, recurso o reserva.");Object.assign(a,{[s]:(s==="ficha"?yi(c,o):s==="impresion"?Xr(c,o):s==="relacionadas"?$i(c,o):s==="recurso"?fi(c,o):s==="reserva"?hi(c,o):xi(c))??null})}t[n]=a}return t}var sf=f(()=>{ks();R();Ws();Ci()});function cf(e){if(e!==void 0){if(!e||typeof e!="object"||Array.isArray(e))throw i("Los ajustes nativos necesitan objetos expl\xEDcitos.");for(let[o,t]of Object.entries(e))if(!["contacts","companies"].includes(o)||!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(n=>!Js.includes(n)))throw i("Un ajuste nativo no cambia la identidad de la relaci\xF3n.");return structuredClone(e)}}var Js,Qs=f(()=>{R();Js=["etiqueta","ayuda","enTabla","obligatorio","visibleSi","obligatorioSi","permisos","siVacio","completarDesde"]});function lf(e,o,t={}){for(let[r,a]of Object.entries(t)){let s=e.find(u=>u.clave===r&&!u.archivado),c=o[r],d=s?.opciones??[];if(s?.tipo!=="seleccion"||!c||!Object.hasOwn(Gs,c)||Object.keys(a).length!==d.length||!d.length||d.some(u=>!Object.hasOwn(a,u.valor))||Object.values(a).some(u=>typeof u!="string"||!u||u!==u.trim())||new Set(Object.values(a)).size!==d.length)throw i("Las conversiones nativas necesitan un mapa de selecciones completo.")}let n=new Map;for(let r of e){let a=o[r.clave];if(r.archivado||r.tipo!=="seleccion"||!a||!Object.hasOwn(Gs,a))continue;let s=Gs[a];if(r.opciones?.some(c=>c.hecho||c.requisito||c.pide?.length||c.limiteDias!==void 0||c.aprobacion))throw i("Las opciones de Personas/Empresas no pueden perder reglas de etapas.");n.set(s,Br(s,(r.opciones??[]).map(c=>({value:Object.hasOwn(t,r.clave)?t[r.clave][c.valor]:c.valor,label:c.etiqueta,...c.color?{color:c.color}:{}}))))}return n}var Gs,uf=f(()=>{R();Os();Gs={sector:"companySectors",forma_juridica:"legalForms"}});function Xs(e,o){if(e===void 0)return;if(!Po(e))throw i("\xABpersonas\xBB: un objeto.");if(Hs(e,["objeto","tipo","de","campoNif","etiqueta","plural","icono","campos","conversiones","alternativa","clasificacion","configuracion"],"\xABpersonas\xBB"),e.alternativa!==void 0||e.clasificacion!==void 0)return Rv(e,o);if(e.objeto==="deals"&&o.some(m=>m.tipo==="autonumero"))throw i("Los auton\xFAmeros propios no est\xE1n disponibles en Oportunidades.");if(e.objeto==="deals"&&o.some(m=>m.unico))throw i("Los campos propios \xFAnicos no est\xE1n disponibles en Oportunidades.");if(e.objeto!=="contacts"&&e.objeto!=="companies")throw i("\xABpersonas.objeto\xBB: contacts o companies.");let t=ji(e.tipo,"tipo",60);if(!Ev.test(t))throw i("\xABpersonas.tipo\xBB: una clave de tipo.");if(e.de!==void 0&&e.de!=="cliente"&&e.de!=="proveedor")throw i("\xABpersonas.de\xBB: cliente o proveedor.");if(e.de===t||(t==="cliente"||t==="proveedor")&&e.de!==void 0)throw i("\xABpersonas.de\xBB: un tipo base no puede ser un subtipo.");let n=ji(e.icono,"icono",40);if(!/^[a-z0-9-]+$/.test(n))throw i("\xABpersonas.icono\xBB: una clave de icono.");if(!Po(e.campos))throw i("\xABpersonas.campos\xBB: un mapa expl\xEDcito de campos nativos.");let r={},a=new Map;for(let[m,h]of Object.entries(e.campos)){let b=o.find(w=>w.clave===m&&!w.archivado),y=typeof h=="string"&&Object.hasOwn(pf[e.objeto],h)?pf[e.objeto][h]:void 0,v=Ee(h);if(!b||!(v?Tm.has(b.tipo):y?.includes(b.tipo)))throw i(`\xABpersonas.campos.${m.slice(0,40)}\xBB: campo nativo o tipo incompatible.`);if(b.unico&&typeof h=="string"&&h.startsWith("persona."))throw i("El campo propio necesita conservar sus reglas antes de convertir la ra\xEDz.");if(a.has(h)&&h!=="nif"&&h!=="tax_identifier")throw i(`\xABpersonas.campos\xBB: dos campos apuntan a \xAB${h}\xBB.`);a.set(h,m),r[m]=h}let s=e.objeto==="contacts"?"first_name":"name";if(!a.has(s))throw i(`\xABpersonas.campos\xBB: falta el nombre nativo \xAB${s}\xBB.`);let c=o.filter(m=>!m.archivado);for(let m of c)if(!Object.hasOwn(r,m.clave)&&m.tipo!=="resumen"&&m.tipo!=="formula")throw i(`\xABpersonas.campos\xBB: falta destino para \xAB${m.clave}\xBB; no se puede perder un campo.`);if(e.conversiones!==void 0&&!Po(e.conversiones))throw i("Las conversiones nativas necesitan un mapa de selecciones completo.");let d={};for(let[m,h]of Object.entries(e.conversiones??{})){if(!Po(h)||Object.values(h).some(b=>typeof b!="string"))throw i("Las conversiones nativas necesitan un mapa de selecciones completo.");Object.defineProperty(d,m,{value:{...h},enumerable:!0})}let u=e.campoNif;if(u!==void 0&&(e.objeto!=="contacts"||typeof u!="string"||!Object.hasOwn(r,u)||!r[u]?.startsWith("datos.")||!o.some(m=>m.clave===u&&["texto","codigo"].includes(m.tipo))))throw i("\xABpersonas.campoNif\xBB: elige un campo propio de texto de Personas.");ff(o,r,t),lf(o,r,d);let p=Vs(e.configuracion,o);if(p&&Object.keys(p).some(m=>m!==e.objeto))throw i("La configuraci\xF3n cita un objeto que esta ra\xEDz no declara.");return{objeto:e.objeto,tipo:t,...typeof u=="string"?{campoNif:u}:{},...e.de?{de:e.de}:{},...p?{configuracion:p}:{},etiqueta:ji(e.etiqueta,"etiqueta",60),plural:ji(e.plural,"plural",60),icono:n,campos:r,...e.conversiones!==void 0?{conversiones:d}:{}}}function Rv(e,o){let t=e.alternativa,n=e.clasificacion;if(e.objeto!=="contacts"||!Po(t)||t.objeto!=="companies"||!Po(t.campos)||!Po(n))throw i("Los destinos dobles necesitan Persona, Empresa y clasificaci\xF3n expl\xEDcita.");Hs(t,["objeto","campos","conversiones"],"\xABpersonas.alternativa\xBB"),Hs(n,["campo","valores","vacio","formas","etiquetas","propiedad"],"\xABpersonas.clasificacion\xBB");let r=o.find(v=>v.clave===n.campo&&!v.archivado);if(!r||!["seleccion","booleano"].includes(r.tipo)||!Po(n.valores)||n.vacio!==void 0&&n.vacio!=="contacts"&&n.vacio!=="companies")throw i("La clasificaci\xF3n necesita todas las opciones de una selecci\xF3n o booleano.");if(r.opciones?.some(v=>v.hecho||v.requisito||v.pide?.length||v.limiteDias!==void 0||v.aprobacion))throw i("La clasificaci\xF3n no puede perder permisos ni reglas de etapas.");let a=r.tipo==="booleano"?["true","false"]:(r.opciones??[]).map(v=>v.valor);if(!a.length||Object.keys(n.valores).length!==a.length||a.some(v=>!Object.hasOwn(n.valores,v))||Object.values(n.valores).some(v=>v!=="contacts"&&v!=="companies")||!Object.values(n.valores).includes("contacts")||!Object.values(n.valores).includes("companies"))throw i("La clasificaci\xF3n necesita todas las opciones de una selecci\xF3n o booleano.");let s=wm(n,r,n.valores),c={campo:r.clave,valores:{...n.valores},...n.vacio?{vacio:n.vacio}:{},...s},{alternativa:d,clasificacion:u,configuracion:p,...m}=e,h=v=>Xs(v,ym(o,c,v.objeto).filter(w=>Po(v.campos)&&Object.hasOwn(v.campos,w.clave)||w.tipo==="resumen"||w.tipo==="formula")),b=h(m),y=h({...m,objeto:"companies",campoNif:void 0,campos:t.campos,conversiones:t.conversiones});if(c.propiedad){if(b.campos[r.clave]!==c.propiedad||y.campos[r.clave]!==c.propiedad||b.conversiones?.[r.clave]||y.conversiones?.[r.clave])throw i("La clasificaci\xF3n propia necesita el mismo destino tipado en ambas ramas, sin conversiones.")}else if(Object.hasOwn(b.campos,r.clave)||Object.hasOwn(y.campos,r.clave))throw i("El discriminante de identidad no es un campo nativo.");for(let v of o.filter(w=>!w.archivado&&w.clave!==r.clave&&w.tipo!=="resumen"&&w.tipo!=="formula"))if(!Object.hasOwn(b.campos,v.clave)&&!Object.hasOwn(y.campos,v.clave))throw i("Los destinos deben conservar todos los campos del origen salvo el discriminante.");return vm(o,c),{...b,alternativa:{objeto:"companies",campos:y.campos,...y.conversiones?{conversiones:y.conversiones}:{}},clasificacion:c,...e.configuracion!==void 0?{configuracion:Vs(e.configuracion,o)}:{}}}var df,pf,Po,Ev,ji,Hs,mf=f(()=>{Ur();Mm();sf();R();_m();uf();df={ubicacion:["ubicacion"],address:["texto","texto_largo"],zipcode:["texto","codigo"],city:["texto"],country:["texto"],pais_fiscal:["texto","seleccion"],iban:["texto"]},pf={contacts:{...df,province:["texto"],first_name:["texto"],last_name:["texto"],title:["texto"],correo:["correo"],telefono:["telefono"],background:["texto_largo","texto"],nif:["texto"],birthday:["fecha"],first_seen:["fecha","fecha_hora"],has_newsletter:["booleano"]},companies:{...df,state_abbr:["texto"],name:["texto"],razon_social:["texto"],tax_identifier:["texto"],phone_number:["telefono"],website:["url"],description:["texto_largo","texto"],sector:["seleccion","texto"],forma_juridica:["seleccion","texto"],correo_facturacion:["correo"],has_newsletter:["booleano"],"persona.first_name":["texto"],"persona.last_name":["texto"],"persona.correo":["correo"],"persona.telefono":["telefono"]}},Po=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ev=/^[a-z0-9][a-z0-9-]{0,59}$/,ji=(e,o,t)=>{if(typeof e!="string"||!e.trim()||e.trim().length>t)throw i(`\xABpersonas.${o}\xBB: texto de 1 a ${t} caracteres.`);return e.trim()},Hs=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`)}});import{createContext as qv,Script as kv}from"node:vm";function Si(e,o){if(e!=null){if(!Array.isArray(e)||e.length>hf)throw i(`\xAB${o}\xBB: como mucho ${hf} condiciones.`);if(e.length)return e.map(t=>{let n=t;if(typeof n!="object"||n===null||typeof n.campo!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(n.campo))throw i(`\xAB${o}\xBB: una condici\xF3n no es v\xE1lida.`);let r=n.op;if(!Pv.includes(r))throw i(`\xAB${o}\xBB: condici\xF3n no v\xE1lida (${String(n.op).slice(0,20)}).`);let a={campo:n.campo,op:r};if(r==="igual"||r==="distinto"){if(!Tv(n.valor))throw i(`\xAB${o}\xBB: la condici\xF3n necesita un valor.`);a.valor=n.valor}if(r==="uno_de"){if(!Array.isArray(n.valor)||!n.valor.length||n.valor.length>50||!n.valor.every(s=>typeof s=="string"||typeof s=="number"))throw i(`\xAB${o}\xBB: \xABuno de\xBB necesita una lista de valores.`);a.valor=n.valor}return a})}}function yf(e,o){if(!(e==null||e==="")){if(typeof e!="string"||e.length>gf)throw i(`\xAB${o}\xBB: el patr\xF3n, hasta ${gf} caracteres.`);if(/\\[1-9]|\\k<|\(\?<[=!]/.test(e))throw i(`\xAB${o}\xBB: el patr\xF3n no admite retroreferencias ni lookbehind.`);if(Mv(e))throw i(`\xAB${o}\xBB: el patr\xF3n tiene un grupo repetido que se puede disparar (p. ej. \xAB(a+)+\xBB); simplif\xEDcalo.`);try{new RegExp(e,"u")}catch{throw i(`\xAB${o}\xBB: el patr\xF3n no es una expresi\xF3n regular v\xE1lida.`)}return e}}function Mv(e){let o=[],t=!1;for(let n=0;n<e.length;n++){let r=e[n];if(r==="\\"){n++;continue}if(t){r==="]"&&(t=!1);continue}if(r==="["){t=!0;continue}if(r==="("){o.push(!1);continue}if(r===")"){let a=o.pop()??!1,s=e.slice(n+1),c=/^(?:[+*]|\{\d*,)/.test(s)||/^\{(\d+)\}/.test(s)&&Number(/^\{(\d+)\}/.exec(s)[1])>1;if(a&&c)return!0;o.length&&(a||c)&&(o[o.length-1]=!0);continue}(r==="+"||r==="*"||r==="?"||r==="{"||r==="|")&&o.length&&(o[o.length-1]=!0)}return!1}function _f(e,o){if(e==null)return;let t=e,n=t?.tipo;if(typeof t!="object"||!bf[n])throw i(`\xAB${o.etiqueta}\xBB: valor por defecto no v\xE1lido.`);if(!bf[n].includes(o.tipo))throw i(`\xAB${o.etiqueta}\xBB: ese valor por defecto no vale para este tipo.`);if(n==="fijo")return{tipo:n,valor:t.valor};if(n==="formula"){if(typeof t.formula!="string"||!t.formula.trim()||t.formula.length>1e3)throw i(`\xAB${o.etiqueta}\xBB: escribe la f\xF3rmula por defecto.`);return{tipo:n,formula:t.formula.trim()}}return{tipo:n}}var Pv,hf,gf,wf,vf,bf,Tv,WL,BL,Nf=f(()=>{R();Pv=["igual","distinto","vacio","lleno","uno_de"],hf=10,gf=200,wf=["texto","correo","telefono","url","codigo"],vf=["texto","correo","telefono","url","codigo","numero","importe"],bf={fijo:["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","seleccion_multiple","url","correo","telefono","duracion","porcentaje","valoracion","contador","cronometro","color","codigo","hora"],hoy:["fecha","fecha_hora"],ahora:["fecha_hora"],yo:["texto","correo"],formula:["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","porcentaje","duracion"]},Tv=e=>typeof e=="string"&&e.length<=200||typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean";WL=qv({p:"",v:""}),BL=new kv("new RegExp(p, 'u').test(v)")});function xf(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>$f)throw i(`\xABvalidaciones\xBB: hasta ${$f}.`);let t=[];for(let[n,r]of e.entries()){if(!Lv(r))throw i(`Validaci\xF3n ${n+1}: un objeto.`);for(let s of Object.keys(r))if(s!=="formula"&&s!=="mensaje")throw i(`Validaci\xF3n ${n+1}: clave no admitida \xAB${s.slice(0,40)}\xBB.`);if(typeof r.formula!="string"||!r.formula.trim()||r.formula.length>no)throw i(`Validaci\xF3n ${n+1}: la f\xF3rmula, de 1 a ${no} caracteres.`);if(typeof r.mensaje!="string"||!r.mensaje.trim()||r.mensaje.length>200)throw i(`Validaci\xF3n ${n+1}: el mensaje, de 1 a 200 caracteres.`);let a;try{a=bi([...o,Dv(n,r.formula)]).at(-1)}catch(s){throw i(`Validaci\xF3n ${n+1}: ${s instanceof Error?s.message:"la f\xF3rmula no vale"}`)}if(a.origen?.tipo!=="booleano")throw i(`Validaci\xF3n ${n+1}: la f\xF3rmula tiene que dar s\xED o no (una comparaci\xF3n, Y(), O()\u2026).`);t.push({formula:a.formula,mensaje:r.mensaje.trim()})}return t.length?t:void 0}var $f,Lv,Dv,Cf=f(()=>{R();wi();$f=20,Lv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Dv=(e,o)=>({clave:`validacion_${e}`,etiqueta:`Validaci\xF3n ${e+1}`,tipo:"formula",formula:o})});function Of(e,o){if(e==null)return;let t=`\xAB${o.etiqueta}\xBB`;if(o.tipo!=="seleccion"&&o.tipo!=="relacion")throw i(`${t}: solo una selecci\xF3n o una relaci\xF3n pueden depender de otro campo.`);if(!Sf(e))throw i(`${t}: \xABdepende\xBB, un objeto.`);for(let n of Object.keys(e))if(!["campo","opciones","via"].includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`);if(typeof e.campo!="string"||!jf.test(e.campo))throw i(`${t}: \xBFde qu\xE9 campo depende?`);if(o.tipo==="seleccion"){if(!Sf(e.opciones)||Object.keys(e.opciones).length>200)throw i(`${t}: qu\xE9 opciones valen para cada valor del otro campo (hasta 200).`);let n={};for(let[r,a]of Object.entries(e.opciones)){if(r.length>100||!Array.isArray(a)||a.length>200||!a.every(s=>typeof s=="string"&&s.length<=100))throw i(`${t}: las opciones de \xAB${r.slice(0,40)}\xBB, una lista de valores.`);n[r]=[...new Set(a)]}return{campo:e.campo,opciones:n}}if(typeof e.via!="string"||!jf.test(e.via))throw i(`${t}: por qu\xE9 campo del otro m\xF3dulo se filtra (\xABvia\xBB).`);return{campo:e.campo,via:e.via}}function Af(e){let o=e.filter(t=>!t.archivado);for(let t of o.filter(n=>n.depende)){let n=t.depende,r=o.find(a=>a.clave===n.campo);if(!r||r.clave===t.clave)throw i(`\xAB${t.etiqueta}\xBB: depende de un campo que no existe.`);if(t.tipo==="seleccion"){if(r.tipo!=="seleccion")throw i(`\xAB${t.etiqueta}\xBB: una selecci\xF3n depende de otra selecci\xF3n.`);let a=new Set((r.opciones??[]).map(c=>c.valor)),s=new Set((t.opciones??[]).map(c=>c.valor));for(let[c,d]of Object.entries(n.opciones??{})){if(!a.has(c))throw i(`\xAB${t.etiqueta}\xBB: \xAB${c.slice(0,40)}\xBB no es una opci\xF3n de \xAB${r.etiqueta}\xBB.`);let u=d.find(p=>!s.has(p));if(u!==void 0)throw i(`\xAB${t.etiqueta}\xBB: \xAB${u.slice(0,40)}\xBB no es una de sus opciones.`)}}else if(r.tipo!=="relacion"||r.multiple||t.multiple)throw i(`\xAB${t.etiqueta}\xBB: una relaci\xF3n (de uno) depende de otra relaci\xF3n de uno de este m\xF3dulo.`)}for(let t of o.filter(n=>n.depende)){let n=new Set([t.clave]);for(let r=o.find(a=>a.clave===t.depende.campo);r?.depende;r=o.find(a=>a.clave===r.depende.campo)){if(n.has(r.clave))throw i(`\xAB${t.etiqueta}\xBB: las dependencias forman un c\xEDrculo.`);n.add(r.clave)}}}var jf,Sf,Ef=f(()=>{R();jf=/^[a-z][a-z0-9_]{0,39}$/,Sf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function qf(e,o){if(!Array.isArray(e)||e.length>300)throw i("Hasta 300 transiciones por campo.");let t=new Set(o.opciones?.map(r=>r.valor)),n=new Set;return e.map(r=>{if(!Rf(r)||r.desde!==null&&!t.has(r.desde)||!t.has(r.hasta)||r.desde===r.hasta)throw i("El origen y el destino deben ser estados diferentes del campo; el origen vac\xEDo representa el alta.");let a=JSON.stringify([r.desde,r.hasta]);if(n.has(a))throw i("Transici\xF3n repetida.");n.add(a);let s={desde:r.desde,hasta:r.hasta};if(s.papeles=Ys(r.papeles,30,/^(titular|administrador|miembro|lectura|p_[a-z]{1,12})$/),s.pide=Ys(r.pide,30,/^[a-z][a-z0-9_]{0,40}$/),s.acciones=Ys(r.acciones,10),r.aprobacion!==void 0){let c=r.aprobacion;if(!Rf(c)||c.papel!==void 0&&(typeof c.papel!="string"||!/^[a-z_]{1,40}$/.test(c.papel))||c.personas!==void 0&&(!Number.isInteger(c.personas)||Number(c.personas)<1||Number(c.personas)>10))throw i("Aprobaci\xF3n de transici\xF3n no v\xE1lida.");s.aprobacion={papel:c.papel,personas:c.personas}}return s})}function kf(e){for(let o of e)for(let t of o.transiciones??[])for(let n of t.pide??[]){let r=e.find(a=>a.clave===n&&!a.archivado);if(!r||["formula","resumen","busqueda","subtabla","boton","autonumero","creado_el","creado_por","modificado_el","modificado_por"].includes(r.tipo))throw i("La guarda debe referirse a un campo editable del m\xF3dulo.")}return e}var Rf,Ys,Pf=f(()=>{R();Rf=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ys=(e,o,t)=>{if(e!==void 0){if(!Array.isArray(e)||e.length>o||e.some(n=>typeof n!="string"||!n.trim()||n.length>80||t&&!t.test(n)))throw i("Lista de transici\xF3n no v\xE1lida.");if(new Set(e).size!==e.length)throw i("La transici\xF3n contiene valores repetidos.");return e}}});function Tf(e,o,t){if(e.aprobacion===void 0||e.aprobacion===null)return;let n=e.aprobacion;if(typeof n!="object"||Array.isArray(n))throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: la aprobaci\xF3n, un objeto.`);let r=n.papel===void 0||n.papel===null||n.papel===""?void 0:n.papel;if(r!==void 0&&(typeof r!="string"||!/^[a-z_]{1,40}$/.test(r)))throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: el papel que aprueba no es v\xE1lido.`);let a=n.personas===void 0||n.personas===null?1:n.personas;if(!Number.isInteger(a)||a<1||a>10)throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: de 1 a 10 personas.`);o.aprobacion={...r?{papel:r}:{},personas:a}}var eD,Mf=f(()=>{li();R();eD=A`select a.*, m.clave,
|
|
19
19
|
(a.estado = 'pendiente' and crm_aprobacion_puede(a.papel, a.pedida_por, a.espacio_id, crm_yo(), a.autor)
|
|
20
20
|
and not exists (select 1 from jsonb_array_elements(a.votos) v where (v->>'sales_id')::bigint = crm_yo())) as puedo
|
|
21
|
-
from aprobaciones a join modulos m on m.id = a.modulo_id`});function Ef(e,o,t){if(e.requisito!==void 0&&e.requisito!==null){let n=e.requisito;if(!gv(n)||typeof n.formula!="string"||!n.formula.trim()||n.formula.length>no||typeof n.mensaje!="string"||!n.mensaje.trim()||n.mensaje.length>200)throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: el requisito lleva una f\xF3rmula y un mensaje (hasta 200 caracteres).`);o.requisito={formula:n.formula.trim(),mensaje:n.mensaje.trim()}}if(e.pide!==void 0&&e.pide!==null){if(!Array.isArray(e.pide)||e.pide.length>Af||e.pide.some(n=>typeof n!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(n)))throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: \xABpide\xBB, hasta ${Af} campos.`);e.pide.length&&(o.pide=[...new Set(e.pide)])}if(Sf(e,o,t),e.limiteDias!==void 0&&e.limiteDias!==null){if(!Number.isInteger(e.limiteDias)||e.limiteDias<1||e.limiteDias>3650)throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: el l\xEDmite de d\xEDas, de 1 a 3650.`);o.limiteDias=e.limiteDias}}function qf(e){let o=e.filter(t=>!t.archivado);return e.map(t=>{if(t.tipo!=="seleccion"||!t.opciones?.some(r=>r.requisito||r.pide||r.limiteDias))return t;let n=t.opciones.map((r,a)=>{for(let c of r.pide??[]){let d=o.find(u=>u.clave===c);if(!d||["formula","resumen","busqueda","subtabla","boton","autonumero","creado_el","creado_por","modificado_el","modificado_por"].includes(d.tipo))throw i(`\xAB${t.etiqueta}\xBB, \xAB${r.etiqueta}\xBB: pide \xAB${c}\xBB, que no es un campo que se rellene.`)}if(!r.requisito)return r;let s;try{s=gi([...o,bv(t.clave,a,r.requisito.formula)]).at(-1)}catch(c){throw i(`\xAB${t.etiqueta}\xBB, \xAB${r.etiqueta}\xBB: ${c instanceof Error?c.message:"la f\xF3rmula no vale"}`)}if(s.origen?.tipo!=="booleano")throw i(`\xAB${t.etiqueta}\xBB, \xAB${r.etiqueta}\xBB: el requisito tiene que dar s\xED o no.`);return{...r,requisito:{...r.requisito,formula:s.formula}}});return{...t,opciones:n}})}var Af,gv,bv,Rf=f(()=>{q();bi();Of();Af=5,gv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bv=(e,o,t)=>({clave:`etapa_${e}_${o}`,etiqueta:`Requisito ${o+1}`,tipo:"formula",formula:t})});function Tf(e){if(e==null)return;if(!Array.isArray(e)||e.length>kf)throw i(`\xABconversiones\xBB: hasta ${kf}.`);let o=new Set,t=e.map((n,r)=>{let a=`Conversi\xF3n ${r+1}`;if(!Si(n))throw i(`${a}: un objeto.`);for(let c of Object.keys(n))if(!["clave","nombre","destino","campos","enlaceDestino","enlaceOrigen","lineas","etapa"].includes(c))throw i(`${a}: clave no admitida \xAB${c.slice(0,40)}\xBB.`);if(typeof n.clave!="string"||!At.test(n.clave)||o.has(n.clave))throw i(`${a}: \xABclave\xBB (min\xFAsculas y _), sin repetir.`);if(o.add(n.clave),typeof n.nombre!="string"||!n.nombre.trim()||n.nombre.length>60)throw i(`${a}: el nombre del bot\xF3n (1\u201360).`);if(typeof n.destino!="string"||!(wv.includes(n.destino)||/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(n.destino)))throw i(`${a}: \xABdestino\xBB, contacts, companies, deals o mod_<clave>.`);let s={clave:n.clave,nombre:n.nombre.trim(),destino:n.destino,campos:Pf(n.campos,a)};for(let c of["enlaceDestino","enlaceOrigen"])if(!(n[c]===void 0||n[c]===null||n[c]==="")){if(typeof n[c]!="string"||!At.test(n[c]))throw i(`${a}: \xAB${c}\xBB no es un campo v\xE1lido.`);s[c]=n[c]}if(n.lineas!==void 0){if(!Array.isArray(n.lineas)||n.lineas.length>5)throw i(`${a}: \xABlineas\xBB, hasta 5.`);s.lineas=n.lineas.map(c=>{if(!Si(c)||typeof c.desde!="string"||!At.test(c.desde)||typeof c.a!="string"||!At.test(c.a))throw i(`${a}: cada \xABlineas\xBB, {desde, a, campos}.`);return{desde:c.desde,a:c.a,campos:Pf(c.campos,a)}})}if(n.etapa!==void 0&&n.etapa!==null){if(!Si(n.etapa)||typeof n.etapa.campo!="string"||!At.test(n.etapa.campo)||typeof n.etapa.valor!="string")throw i(`${a}: \xABetapa\xBB, {campo, valor}.`);s.etapa={campo:n.etapa.campo,valor:n.etapa.valor}}return s});return t.length?t:void 0}var kf,At,wv,Si,Pf,Mf=f(()=>{q();kf=5,At=/^[a-z][a-z0-9_]{0,40}$/,wv=["contacts","companies","deals"],Si=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Pf=(e,o)=>{if(e===void 0)return{};if(!Si(e)||Object.keys(e).length>100)throw i(`${o}: \xABcampos\xBB, un objeto destino \u2192 origen.`);for(let[t,n]of Object.entries(e))if(!At.test(t)||typeof n!="string"||!At.test(n))throw i(`${o}: el campo \xAB${t.slice(0,40)}\xBB no es v\xE1lido.`);return e}});function Lf(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>If)throw i(`\xABencadenar\xBB: hasta ${If}.`);let t=new Set,n=e.map((r,a)=>{let s=`\xABencadenar\xBB ${a+1}`;if(!Et(r))throw i(`${s}: un objeto.`);for(let w of Object.keys(r))if(!["clave","nombre","destino","enlace","campos","lineas","estado","no_cuentan","permitir_exceso","juntar"].includes(w))throw i(`${s}: clave no admitida \xAB${w.slice(0,40)}\xBB.`);let c=ot(r.clave,`${s}.clave`);if(t.has(c))throw i(`${s}: \xABclave\xBB repetida.`);if(c==="juntar")throw i(`${s}: \xABjuntar\xBB no vale como clave.`);if(t.add(c),typeof r.nombre!="string"||!r.nombre.trim()||r.nombre.length>60)throw i(`${s}: el nombre del bot\xF3n (1\u201360).`);if(typeof r.destino!="string"||!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(r.destino))throw i(`${s}: \xABdestino\xBB, mod_<clave>.`);if(!Et(r.lineas))throw i(`${s}: \xABlineas\xBB {desde, a, cantidad: {origen, destino}}.`);let d=r.lineas,u=ot(d.desde,`${s}.lineas.desde`),p=yv(o,u);if(!p)throw i(`${s}: \xAB${u}\xBB no es una subtabla de este m\xF3dulo.`);if(!Et(d.cantidad))throw i(`${s}: \xABlineas.cantidad\xBB {origen, destino}.`);let m=ot(d.cantidad.origen,`${s}.lineas.cantidad.origen`),h=(p.columnas??[]).find(w=>w.clave===m&&!w.archivado);if(!h||!(vv.includes(h.tipo)||h.tipo==="formula"&&h.origen?.tipo==="numero"))throw i(`${s}: la cantidad \xAB${m}\xBB tiene que ser una columna num\xE9rica de \xAB${u}\xBB.`);let b={clave:c,nombre:r.nombre.trim(),destino:r.destino,enlace:ot(r.enlace,`${s}.enlace`),lineas:{desde:u,a:ot(d.a,`${s}.lineas.a`),cantidad:{origen:m,destino:ot(d.cantidad.destino,`${s}.lineas.cantidad.destino`)}}},y=Df(d.campos,`${s}.lineas.campos`);if(y){for(let w of Object.values(y))if(!(p.columnas??[]).some(N=>N.clave===w&&!N.archivado))throw i(`${s}: \xAB${w}\xBB no es una columna de \xAB${u}\xBB.`);b.lineas.campos=y}let v=Df(r.campos,`${s}.campos`);if(v){for(let w of Object.values(v))if(!o.some(N=>N.clave===w&&!N.archivado))throw i(`${s}: \xAB${w}\xBB no es un campo de este m\xF3dulo.`);b.campos=v}if(r.estado!==void 0&&r.estado!==null){let w=r.estado;if(!Et(w))throw i(`${s}: \xABestado\xBB {campo, parcial, completo, pendiente?}.`);let N=o.find(S=>S.clave===w.campo&&S.tipo==="seleccion"&&!S.archivado);if(!N)throw i(`${s}: \xABestado.campo\xBB tiene que ser una selecci\xF3n de este m\xF3dulo.`);let j=new Set((N.opciones??[]).map(S=>S.valor));for(let S of["parcial","completo","pendiente"]){let R=w[S];if(!(R===void 0&&S==="pendiente")&&(typeof R!="string"||!j.has(R)))throw i(`${s}: \xABestado.${S}\xBB tiene que ser una opci\xF3n de \xAB${N.etiqueta}\xBB.`)}b.estado={campo:N.clave,parcial:w.parcial,completo:w.completo,...typeof w.pendiente=="string"?{pendiente:w.pendiente}:{}}}if(r.no_cuentan!==void 0&&r.no_cuentan!==null){let w=r.no_cuentan;if(!Et(w)||!Array.isArray(w.valores)||w.valores.length>20||!w.valores.every(N=>typeof N=="string"&&N.length<=60))throw i(`${s}: \xABno_cuentan\xBB {campo, valores}.`);b.no_cuentan={campo:ot(w.campo,`${s}.no_cuentan.campo`),valores:w.valores}}if(r.permitir_exceso===!0&&(b.permitir_exceso=!0),r.juntar!==void 0&&r.juntar!==null&&r.juntar!==!1){let w=r.juntar===!0?{}:r.juntar;if(!Et(w))throw i(`${s}: \xABjuntar\xBB {iguales?, enlace_varios?}.`);for(let j of Object.keys(w))if(!["iguales","enlace_varios"].includes(j))throw i(`${s}: \xABjuntar\xBB: clave no admitida \xAB${j.slice(0,40)}\xBB.`);let N=w.iguales===void 0?[]:w.iguales;if(!Array.isArray(N)||N.length>10||!N.every(j=>typeof j=="string"&&o.some(S=>S.clave===j&&!S.archivado)))throw i(`${s}: \xABjuntar.iguales\xBB, campos de este m\xF3dulo (hasta 10).`);b.juntar={...N.length?{iguales:N}:{},...w.enlace_varios?{enlace_varios:ot(w.enlace_varios,`${s}.juntar.enlace_varios`)}:{}}}return b});return n.length?n:void 0}var If,Gs,vv,Et,Df,ot,yv,zf=f(()=>{q();If=5,Gs=/^[a-z][a-z0-9_]{0,40}$/,vv=["numero","importe","duracion","porcentaje"],Et=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Df=(e,o)=>{if(e!=null){if(!Et(e)||Object.keys(e).length>60)throw i(`${o}: un objeto destino \u2192 origen.`);for(let[t,n]of Object.entries(e))if(!Gs.test(t)||typeof n!="string"||!Gs.test(n))throw i(`${o}: \xAB${t.slice(0,40)}\xBB no es v\xE1lido.`);return e}},ot=(e,o)=>{if(typeof e!="string"||!Gs.test(e))throw i(`${o}: falta o no es v\xE1lido.`);return e},yv=(e,o)=>e.find(t=>t.clave===o&&t.tipo==="subtabla"&&!t.archivado)});function Bf(e){if(e==null)return;if(!Array.isArray(e)||e.length>Ff)throw i(`\xABplantillas_hijos\xBB: hasta ${Ff}.`);let o=new Set,t=e.map((n,r)=>{let a=`Plantilla de hijos ${r+1}`;if(!Hs(n))throw i(`${a}: un objeto.`);for(let d of Object.keys(n))if(!["clave","nombre","cuando","subtabla","modulo","via","registros"].includes(d))throw i(`${a}: clave no admitida \xAB${d.slice(0,40)}\xBB.`);if(typeof n.clave!="string"||!Oi.test(n.clave)||o.has(n.clave))throw i(`${a}: \xABclave\xBB (min\xFAsculas y _), sin repetir.`);if(o.add(n.clave),typeof n.nombre!="string"||!n.nombre.trim()||n.nombre.length>60)throw i(`${a}: el nombre (1\u201360).`);let s=n.cuando===void 0?[]:n.cuando;if(!Array.isArray(s)||s.length>3)throw i(`${a}: \xABcuando\xBB, hasta 3 condiciones.`);let c={clave:n.clave,nombre:n.nombre.trim(),cuando:s.map(d=>{if(!Hs(d)||typeof d.campo!="string"||!Oi.test(d.campo)||!(typeof d.valor=="string"||typeof d.valor=="boolean"))throw i(`${a}: cada condici\xF3n, {campo, valor}.`);return{campo:d.campo,valor:d.valor}}),registros:[]};if(typeof n.subtabla=="string"&&n.subtabla){if(!Oi.test(n.subtabla))throw i(`${a}: \xABsubtabla\xBB no v\xE1lida.`);c.subtabla=n.subtabla}else{if(typeof n.modulo!="string"||!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(n.modulo)||typeof n.via!="string"||!Oi.test(n.via))throw i(`${a}: una \xABsubtabla\xBB de este m\xF3dulo, o un \xABmodulo\xBB (mod_<clave>) y su relaci\xF3n \xABvia\xBB con este.`);c.modulo=n.modulo,c.via=n.via}if(!Array.isArray(n.registros)||!n.registros.length||n.registros.length>Wf)throw i(`${a}: \xABregistros\xBB, de 1 a ${Wf}.`);return c.registros=n.registros.map(d=>{if(!Hs(d)||JSON.stringify(d).length>4e3)throw i(`${a}: cada registro, un objeto (de hasta 4000 caracteres).`);return d}),c});return t.length?t:void 0}var Ff,Wf,Oi,Hs,Vf=f(()=>{q();Ff=10,Wf=50,Oi=/^[a-z][a-z0-9_]{0,40}$/,Hs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Jf(e,o){if(e==null)return;if(!wo(e))throw i("\xABpertenencia\xBB: un objeto.");let t=(n,r,a,s=!1)=>{let c=o.find(d=>d.clave===n&&!d.archivado);if(!c||!r.includes(c.tipo)||s&&c.multiple)throw i(`\xABpertenencia.${a}\xBB: ${r.join(" o ")}${s?" simple":""} de este m\xF3dulo.`);return c.clave};return{demanda:t(e.demanda,["relacion"],"demanda",!0),oferta:t(e.oferta,["relacion"],"oferta",!0),desde:t(e.desde,["fecha"],"desde"),...e.hasta?{hasta:t(e.hasta,["fecha"],"hasta")}:{},...e.correccion_dias!==void 0&&e.correccion_dias!==null?{correccion_dias:_v(e.correccion_dias)}:{}}}function Qf(e,o){if(e==null)return;if(!wo(e))throw i("\xABasignacion\xBB: un objeto.");if(typeof e.oferta!="string"||!Ei.test(e.oferta))throw i("\xABasignacion.oferta\xBB: la clave del m\xF3dulo de la oferta.");let t=e.destino,n;if(wo(t)&&t.forma==="pertenencia"&&typeof t.modulo=="string"&&Ei.test(t.modulo))n={forma:"pertenencia",modulo:t.modulo};else if(wo(t)&&t.forma==="relacion"){let r=o.find(a=>a.clave===t.campo&&!a.archivado);if(r?.tipo!=="relacion"||r.multiple||r.relacion!==`mod_${e.oferta}`)throw i("\xABasignacion.destino.campo\xBB: una relaci\xF3n simple de este m\xF3dulo a la oferta.");n={forma:"relacion",campo:r.clave}}else throw i("\xABasignacion.destino\xBB: {forma: \xABpertenencia\xBB, modulo} o {forma: \xABrelacion\xBB, campo}.");if(typeof e.cupo!="string"||!Ei.test(e.cupo))throw i("\xABasignacion.cupo\xBB: un campo num\xE9rico de la oferta.");return{oferta:e.oferta,destino:n,...$v({...e,cupo_fijo:void 0},o),cupo:e.cupo}}function $v(e,o,t=!1){let n=(p,m,h)=>{let b=o.find(y=>y.clave===p&&!y.archivado);if(!b||h&&!h.includes(b.tipo))throw i(`\xABasignacion\xBB: ${m}, ${h?h.join(" o "):"un campo"} de este m\xF3dulo.`);return b.clave},r=(p,m)=>{if(t){if(typeof p!="string"||!/^[a-z][a-z0-9_]{0,40}(\.[a-z][a-z0-9_]{0,40}){0,3}$/.test(p))throw i(`${m}: campo de oferta no v\xE1lido.`);return p}return Nv(p,m)},a=t?Uf:Ei,s=t&&e.cupo_fijo!==void 0;if(s?e.cupo!==void 0||!Number.isInteger(e.cupo_fijo)||Number(e.cupo_fijo)<1||Number(e.cupo_fijo)>1e4:typeof e.cupo!="string"||!a.test(e.cupo))throw i("\xABasignacion.cupo\xBB: un n\xFAmero de la oferta o un cupo fijo de 1 a 10000.");let c={...s?{cupo_fijo:Number(e.cupo_fijo)}:{cupo:e.cupo},filtros:[],puntos:[]};if(e.orden!==void 0&&e.orden!==null){let p=e.orden;if(!wo(p))throw i("\xABasignacion.orden\xBB: {campo, sentido}.");c.orden={campo:p.campo==="numero"?"numero":n(p.campo,"\xABorden.campo\xBB"),...p.sentido==="desc"?{sentido:"desc"}:{}}}if(e.plazas_por!==void 0&&e.plazas_por!==null){let p=e.plazas_por;if(!wo(p)||typeof p.oferta!="string"||!a.test(p.oferta))throw i("\xABasignacion.plazas_por\xBB: {demanda (selecci\xF3n m\xFAltiple), oferta (su campo)}.");c.plazas_por={demanda:n(p.demanda,"\xABplazas_por.demanda\xBB",["seleccion_multiple","seleccion"]),oferta:p.oferta}}e.inicio&&(c.inicio=n(e.inicio,"\xABinicio\xBB",["fecha"]));let d=Array.isArray(e.filtros)?e.filtros:[],u=Array.isArray(e.puntos)?e.puntos:[];if(d.length>Ai||u.length>Ai)throw i(`\xABasignacion\xBB: hasta ${Ai} filtros y ${Ai} puntos.`);if(c.filtros=d.map((p,m)=>{let h=`Filtro ${m+1}`;if(!wo(p))throw i(`${h}: un objeto.`);if(p.tipo==="igual"||p.tipo==="contiene")return{tipo:p.tipo,demanda:n(p.demanda,`${h}, \xABdemanda\xBB`),oferta:r(p.oferta,h)};if(p.tipo==="entre")return{tipo:"entre",demanda:n(p.demanda,`${h}, \xABdemanda\xBB`,["numero","importe","porcentaje","fecha","hora"]),min:r(p.min,h),max:r(p.max,h)};throw i(`${h}: \xABtipo\xBB igual, contiene o entre.`)}),c.puntos=u.map((p,m)=>{let h=`Punto ${m+1}`;if(!wo(p))throw i(`${h}: un objeto.`);switch(p.tipo){case"base":case"carga":return{tipo:p.tipo,peso:qt(p.peso,h)};case"dentro":return{tipo:"dentro",demanda:n(p.demanda,`${h}, \xABdemanda\xBB`,["hora","numero","fecha","fecha_hora"]),desde:r(p.desde,h),hasta:r(p.hasta,h),peso:qt(p.peso,h)};case"igual":case"contiene":return{tipo:p.tipo,demanda:n(p.demanda,`${h}, \xABdemanda\xBB`),oferta:r(p.oferta,h),peso:qt(p.peso,h)};case"junto":{let b=o.find(v=>v.clave===p.relacion&&!v.archivado);if(b?.tipo!=="relacion")throw i(`${h}: \xABrelacion\xBB, una relaci\xF3n de este m\xF3dulo con otras demandas (los hermanos).`);let y=p.mismo_campo;return{tipo:"junto",relacion:b.clave,misma:qt(p.misma,h),...wo(y)?{mismo_campo:{oferta:r(y.oferta,h),peso:qt(y.peso,h)}}:{},...p.mismo_valor!==void 0?{mismo_valor:qt(p.mismo_valor,h)}:{}}}case"si_no":if(typeof p.contiene!="string"||!p.contiene||p.contiene.length>100)throw i(`${h}: \xABcontiene\xBB, el valor que la oferta deber\xEDa tener.`);return{tipo:"si_no",demanda:n(p.demanda,`${h}, \xABdemanda\xBB`,["booleano"]),oferta:r(p.oferta,h),contiene:p.contiene,peso:qt(p.peso,h)};default:throw i(`${h}: \xABtipo\xBB base, carga, dentro, igual, contiene, junto o si_no.`)}}),e.cercania!==void 0&&e.cercania!==null){let p=e.cercania;if(!wo(p))throw i("\xABasignacion.cercania\xBB: {demanda, oferta}.");c.cercania={demanda:n(p.demanda,"\xABcercania.demanda\xBB",["hora","numero","fecha","fecha_hora"]),oferta:r(p.oferta,"\xABcercania\xBB")}}return c}var wo,Ei,Uf,Ai,_v,qt,Nv,Gf=f(()=>{q();wo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ei=/^[a-z][a-z0-9_]{0,40}$/,Uf=/^[a-z][a-z0-9_]{0,40}(\.[a-z][a-z0-9_]{0,40})?$/,Ai=20,_v=e=>{let o=Number(e);if(!Number.isInteger(o)||o<0||o>60)throw i("\xABpertenencia.correccion_dias\xBB: un entero de 0 a 60.");return o};qt=(e,o)=>{let t=Number(e);if(!Number.isFinite(t)||Math.abs(t)>1e4)throw i(`${o}: \xABpeso\xBB, un n\xFAmero (\xB110 000).`);return t},Nv=(e,o)=>{if(typeof e!="string"||!Uf.test(e))throw i(`${o}: un campo de la oferta (\xABcampo\xBB o \xABrelacion.campo\xBB).`);return e}});function Hf(e,o){if(e==null)return;if(!qi(e))throw i("\xABpublico\xBB: un objeto.");for(let r of Object.keys(e))if(!["campos","titulo","acciones","caducaDias"].includes(r))throw i(`\xABpublico\xBB: clave no admitida \xAB${r.slice(0,40)}\xBB.`);let t=r=>o.find(a=>a.clave===r&&!a.archivado);if(!Array.isArray(e.campos)||!e.campos.length||e.campos.length>20)throw i("\xABpublico.campos\xBB: de 1 a 20 campos.");for(let r of e.campos){let a=t(r);if(!a)throw i(`\xABpublico\xBB: \xAB${String(r).slice(0,40)}\xBB no es un campo del m\xF3dulo.`);if(Cv.includes(a.tipo))throw i(`\xABpublico\xBB: \xAB${a.etiqueta}\xBB no se ense\xF1a en una p\xE1gina p\xFAblica.`)}let n={campos:[...new Set(e.campos)]};if(e.titulo!==void 0&&e.titulo!==null&&e.titulo!==""){let r=t(e.titulo);if(r?.tipo!=="texto"&&r?.tipo!=="autonumero")throw i("\xABpublico.titulo\xBB: un texto del m\xF3dulo.");n.titulo=r.clave}if(e.caducaDias!==void 0){let r=Number(e.caducaDias);if(!Number.isInteger(r)||r<1||r>180)throw i("\xABpublico.caducaDias\xBB: de 1 a 180.");n.caducaDias=r}if(e.acciones!==void 0){if(!Array.isArray(e.acciones)||e.acciones.length>3)throw i("\xABpublico.acciones\xBB: hasta 3.");let r=new Set;if(n.acciones=e.acciones.map((a,s)=>{let c=`Acci\xF3n p\xFAblica ${s+1}`;if(!qi(a)||typeof a.clave!="string"||!xv.test(a.clave)||r.has(a.clave))throw i(`${c}: \xABclave\xBB (min\xFAsculas y _), sin repetir.`);if(r.add(a.clave),typeof a.etiqueta!="string"||!a.etiqueta.trim()||a.etiqueta.length>60)throw i(`${c}: el texto del bot\xF3n (1\u201360).`);let d={clave:a.clave,etiqueta:a.etiqueta.trim(),...a.una_vez===!0?{una_vez:!0}:{}};if(a.campo!==void 0&&a.campo!==null&&a.campo!==""){let u=t(a.campo);if(u?.tipo==="seleccion"){let p=u.opciones?.find(m=>m.valor===a.valor);if(!p)throw i(`${c}: el valor tiene que ser una opci\xF3n de \xAB${u.etiqueta}\xBB.`);if(u.embudo&&(p.requisito||p.pide?.length||p.aprobacion))throw i(`${c}: \xAB${p.etiqueta}\xBB tiene requisito o aprobaci\xF3n: no se puede poner desde fuera.`)}else if(u?.tipo==="booleano"){if(typeof a.valor!="boolean")throw i(`${c}: el valor, s\xED o no.`)}else if(u?.tipo==="hecho"){if(a.valor!==!0)throw i(`${c}: un \xABhecho\xBB se marca (true).`)}else throw i(`${c}: el campo, una selecci\xF3n, un s\xED/no o un \xABhecho\xBB.`);d.campo=u.clave,d.valor=a.valor}if(a.lineas!==void 0&&a.lineas!==null){let u=a.lineas,p=qi(u)?t(u.subtabla):void 0,m=p?.tipo==="subtabla"?(p.columnas??[]).find(h=>h.clave===u.columna&&!h.archivado):void 0;if(m?.tipo!=="booleano")throw i(`${c}: \xABlineas\xBB, una subtabla del m\xF3dulo y una columna s\xED/no suya.`);if(!n.campos.includes(p.clave))throw i(`${c}: la subtabla de \xABlineas\xBB tiene que ense\xF1arse en la p\xE1gina.`);d.lineas={subtabla:p.clave,columna:m.clave}}if(a.firma!==void 0&&a.firma!==null&&a.firma!==!1){let u=a.firma===!0?{}:a.firma;if(!qi(u))throw i(`${c}: \xABfirma\xBB, {archivos}.`);for(let p of Object.keys(u))if(p!=="archivos")throw i(`${c}: \xABfirma\xBB, clave no admitida \xAB${p.slice(0,40)}\xBB.`);if(u.archivos!==void 0&&u.archivos!==null&&u.archivos!==""){if(t(u.archivos)?.tipo!=="archivos")throw i(`${c}: \xABfirma.archivos\xBB, un campo de archivos del m\xF3dulo (donde queda el firmado).`);d.firma={archivos:u.archivos}}else d.firma={}}if(!d.campo&&!d.lineas&&!d.firma)throw i(`${c}: un campo, unas l\xEDneas o la firma.`);return d}),n.acciones.filter(a=>a.firma).length>1)throw i("\xABpublico.acciones\xBB: solo una firma el documento.")}return n}var xv,qi,Cv,Xf=f(()=>{q();xv=/^[a-z][a-z0-9_]{0,40}$/,qi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Cv=["secreto","boton","firma"]});function Zf(e,o){if(he(e))return;if(!vo(e))throw i("\xABstock\xBB: un objeto {articulo?, ubicacion?, movimiento?}.");tt(e,["articulo","ubicacion","movimiento","reponer"],"stock");let t=s=>o.find(c=>c.clave===s&&!c.archivado),n=(s,c,d,u)=>{let p=t(s);if(!p||!d(p))throw i(`\xABstock.${c}\xBB: ${u} de este m\xF3dulo.`);return p.clave},r=s=>s.tipo==="relacion"&&!s.multiple&&!!s.relacion?.startsWith("mod_"),a={};if(!he(e.articulo)){let s=e.articulo;if(!vo(s))throw i("\xABstock.articulo\xBB: un objeto.");tt(s,["minimo","reponer","proveedor","permitir_negativo","lotes"],"stock.articulo");let c={};if(he(s.minimo)||(c.minimo=n(s.minimo,"articulo.minimo",d=>d.tipo==="numero","un n\xFAmero")),he(s.reponer)||(c.reponer=n(s.reponer,"articulo.reponer",d=>d.tipo==="numero","un n\xFAmero")),he(s.proveedor)||(c.proveedor=n(s.proveedor,"articulo.proveedor",d=>r(d)||d.tipo==="relacion"&&!d.multiple&&["contacts","companies"].includes(d.relacion??""),"una relaci\xF3n simple a un proveedor")),s.permitir_negativo===!0)c.permitir_negativo=!0;else if(typeof s.permitir_negativo=="string"&&s.permitir_negativo)c.permitir_negativo=n(s.permitir_negativo,"articulo.permitir_negativo",d=>d.tipo==="booleano","un s\xED/no");else if(!he(s.permitir_negativo)&&s.permitir_negativo!==!1)throw i("\xABstock.articulo.permitir_negativo\xBB: true o un s\xED/no del art\xEDculo.");if(!he(s.lotes)){if(s.lotes!=="lote"&&s.lotes!=="serie")throw i("\xABstock.articulo.lotes\xBB: lote o serie.");if(c.permitir_negativo)throw i("\xABstock.articulo\xBB: con lotes o series no se admiten negativos.");c.lotes=s.lotes}a.articulo=c}if(!he(e.ubicacion)){let s=e.ubicacion;if(!vo(s))throw i("\xABstock.ubicacion\xBB: un objeto.");tt(s,["almacen"],"stock.ubicacion"),a.ubicacion=he(s.almacen)?{}:{almacen:n(s.almacen,"ubicacion.almacen",r,"una relaci\xF3n simple a otro m\xF3dulo")}}if(!he(e.movimiento)){let s=e.movimiento;if(!vo(s))throw i("\xABstock.movimiento\xBB: un objeto.");if(tt(s,["tipo","lineas","ubicacion","ubicacion_destino","cuando"],"stock.movimiento"),!Yf.includes(s.tipo))throw i(`\xABstock.movimiento.tipo\xBB: ${Yf.join(", ")}.`);if(!vo(s.lineas))throw i("\xABstock.movimiento.lineas\xBB: {subtabla, articulo, cantidad, ubicacion?, coste?}.");let c=s.lineas;tt(c,["subtabla","articulo","cantidad","ubicacion","ubicacion_destino","coste","lote","caducidad"],"stock.movimiento.lineas");let d=t(c.subtabla);if(d?.tipo!=="subtabla")throw i("\xABstock.movimiento.lineas.subtabla\xBB: una subtabla de este m\xF3dulo.");let u=(d.columnas??[]).filter(v=>!v.archivado),p=(v,w,N,j)=>{let S=u.find(R=>R.clave===v);if(!S||!N(S))throw i(`\xABstock.movimiento.lineas.${w}\xBB: ${j} de \xAB${d.etiqueta}\xBB.`);return S.clave},m={tipo:s.tipo,lineas:{subtabla:d.clave,articulo:p(c.articulo,"articulo",r,"la columna de producto (una relaci\xF3n simple)"),cantidad:p(c.cantidad,"cantidad",v=>Kf.includes(v.tipo),"una columna num\xE9rica")},cuando:{campo:"",valores:[]}};if(he(c.ubicacion)||(m.lineas.ubicacion=p(c.ubicacion,"ubicacion",r,"una relaci\xF3n simple")),he(c.coste)||(m.lineas.coste=p(c.coste,"coste",v=>Kf.includes(v.tipo),"una columna num\xE9rica")),he(c.lote)||(m.lineas.lote=p(c.lote,"lote",v=>v.tipo==="texto"||v.tipo==="codigo","una columna de texto")),he(c.caducidad)||(m.lineas.caducidad=p(c.caducidad,"caducidad",v=>v.tipo==="fecha","una columna de fecha")),he(s.ubicacion)||(m.ubicacion=n(s.ubicacion,"movimiento.ubicacion",r,"una relaci\xF3n simple")),!m.lineas.ubicacion&&!m.ubicacion)throw i("\xABstock.movimiento\xBB: la ubicaci\xF3n, en la l\xEDnea (\xABlineas.ubicacion\xBB) o en el documento (\xABubicacion\xBB).");if(he(c.ubicacion_destino)||(m.lineas.ubicacion_destino=p(c.ubicacion_destino,"ubicacion_destino",r,"una relaci\xF3n simple")),he(s.ubicacion_destino)||(m.ubicacion_destino=n(s.ubicacion_destino,"movimiento.ubicacion_destino",r,"una relaci\xF3n simple")),m.tipo==="traspaso"&&!m.lineas.ubicacion_destino&&!m.ubicacion_destino)throw i("\xABstock.movimiento\xBB: un traspaso necesita la ubicaci\xF3n de destino, en la l\xEDnea (\xABlineas.ubicacion_destino\xBB) o en el documento (\xABubicacion_destino\xBB).");if(m.tipo!=="traspaso"&&(m.lineas.ubicacion_destino||m.ubicacion_destino))throw i("\xABstock.movimiento\xBB: la ubicaci\xF3n de destino es solo de un traspaso.");if(!vo(s.cuando))throw i("\xABstock.movimiento.cuando\xBB: {campo, valor} o {campo, valores}.");tt(s.cuando,["campo","valor","valores"],"stock.movimiento.cuando");let h=t(s.cuando.campo);if(h?.tipo!=="seleccion")throw i("\xABstock.movimiento.cuando.campo\xBB: una selecci\xF3n de este m\xF3dulo.");let b=Array.isArray(s.cuando.valores)?s.cuando.valores:[s.cuando.valor],y=new Set((h.opciones??[]).map(v=>v.valor));if(!b.length||b.length>20||!b.every(v=>typeof v=="string"&&y.has(v)))throw i(`\xABstock.movimiento.cuando\xBB: opciones de \xAB${h.etiqueta}\xBB.`);m.cuando={campo:h.clave,valores:[...new Set(b)]},a.movimiento=m}if(!he(e.reponer)){let s=e.reponer;if(!vo(s))throw i("\xABstock.reponer\xBB: {destino, proveedor, lineas: {subtabla, articulo, cantidad}, estado?}.");if(tt(s,["destino","proveedor","lineas","estado","en_camino"],"stock.reponer"),!a.articulo?.minimo||!a.articulo.reponer||!a.articulo.proveedor)throw i("\xABstock.reponer\xBB: el art\xEDculo necesita su m\xEDnimo, su \xABreponer hasta\xBB y su proveedor.");if(typeof s.destino!="string"||!/^mod_(?!sub_)[a-z][a-z_]{1,30}$/.test(s.destino))throw i("\xABstock.reponer.destino\xBB: mod_<clave> del m\xF3dulo de compras.");if(typeof s.proveedor!="string"||!Xs.test(s.proveedor))throw i("\xABstock.reponer.proveedor\xBB: la relaci\xF3n de las compras al proveedor.");if(!vo(s.lineas))throw i("\xABstock.reponer.lineas\xBB: {subtabla, articulo, cantidad}.");tt(s.lineas,["subtabla","articulo","cantidad"],"stock.reponer.lineas");for(let d of["subtabla","articulo","cantidad"])if(typeof s.lineas[d]!="string"||!Xs.test(s.lineas[d]))throw i(`\xABstock.reponer.lineas.${d}\xBB: falta o no es v\xE1lida.`);let c={destino:s.destino,proveedor:s.proveedor,lineas:{subtabla:s.lineas.subtabla,articulo:s.lineas.articulo,cantidad:s.lineas.cantidad}};if(!he(s.estado)){if(!vo(s.estado)||typeof s.estado.campo!="string"||typeof s.estado.valor!="string")throw i("\xABstock.reponer.estado\xBB: {campo, valor}.");c.estado={campo:s.estado.campo,valor:s.estado.valor}}if(!he(s.en_camino)){let d=s.en_camino;if(!vo(d)||typeof d.campo!="string"||!Xs.test(d.campo)||!Array.isArray(d.valores)||!d.valores.length||d.valores.length>20||!d.valores.every(u=>typeof u=="string"&&u.length<=80))throw i("\xABstock.reponer.en_camino\xBB: {campo, valores} (los estados de la compra pedida y a\xFAn no recibida).");c.en_camino={campo:d.campo,valores:[...new Set(d.valores)]}}a.reponer=c}return Object.keys(a).length?a:void 0}var Yf,vo,tt,Kf,he,Xs,eh=f(()=>{q();Yf=["entrada","salida","ajuste","traspaso","recuento","reserva"],vo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tt=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`\xAB${t}\xBB: clave no admitida \xAB${n.slice(0,40)}\xBB.`)},Kf=["numero","importe","duracion","porcentaje"],he=e=>e==null||e==="";Xs=/^[a-z][a-z0-9_]{0,40}$/});function Sv(e,o){let t=`liquidacion.reglas[${o}]`;if(!rt(e))throw i(`\xAB${t}\xBB: un objeto.`);if(nt(e,["nombre","si","calculo","valor","tramos"],t),typeof e.nombre!="string"||!e.nombre.trim()||e.nombre.length>60)throw i(`\xAB${t}.nombre\xBB: de 1 a 60 caracteres.`);if(e.calculo!=="porcentaje"&&e.calculo!=="fijo")throw i(`\xAB${t}.calculo\xBB: porcentaje o fijo.`);let n={nombre:e.nombre.trim(),calculo:e.calculo};if(Rt(e.si)||(n.si=rh(e.si,`${t}.si`)),Rt(e.tramos))n.valor=Zs(e.valor,`${t}.valor`);else{let r=e.tramos;if(!rt(r))throw i(`\xAB${t}.tramos\xBB: {por, lista}.`);if(nt(r,["por","modo","lista"],`${t}.tramos`),r.por!=="acumulado"&&r.por!=="importe")throw i(`\xAB${t}.tramos.por\xBB: acumulado o importe.`);if(r.modo!==void 0&&r.modo!==null&&r.modo!=="marginal"&&r.modo!=="alcanzado")throw i(`\xAB${t}.tramos.modo\xBB: marginal o alcanzado.`);if(!Array.isArray(r.lista)||!r.lista.length||r.lista.length>th)throw i(`\xAB${t}.tramos.lista\xBB: de 1 a ${th} tramos {desde, valor}.`);let a=r.lista.map((s,c)=>{if(!rt(s))throw i(`\xAB${t}.tramos.lista[${c}]\xBB: {desde, valor}.`);return nt(s,["desde","valor"],`${t}.tramos.lista[${c}]`),{desde:Zs(s.desde,`${t}.tramos.lista[${c}].desde`,0),valor:Zs(s.valor,`${t}.tramos.lista[${c}].valor`)}}).sort((s,c)=>s.desde-c.desde);if(a[0].desde!==0)throw i(`\xAB${t}.tramos\xBB: el primer tramo empieza en 0.`);if(new Set(a.map(s=>s.desde)).size!==a.length)throw i(`\xAB${t}.tramos\xBB: dos tramos con el mismo \xABdesde\xBB.`);if(n.tramos={por:r.por,modo:r.modo==="alcanzado"?"alcanzado":"marginal",lista:a},!Rt(e.valor))throw i(`\xAB${t}\xBB: con tramos, el valor va en cada tramo.`)}return n}function nh(e,o){if(Rt(e))return;if(!rt(e))throw i("\xABliquidacion\xBB: un objeto {origen, importe, fecha, agente, campos, estados, lineas, reglas}.");if(nt(e,["origen","importe","fecha","agente","cuentan","campos","estados","lineas","reglas"],"liquidacion"),typeof e.origen!="string"||!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(e.origen))throw i("\xABliquidacion.origen\xBB: mod_<clave> del m\xF3dulo de origen.");let t=e.agente==="_dueno"?"_dueno":Ri(e.agente,"liquidacion.agente"),n=N=>o.find(j=>j.clave===N&&!j.archivado),r=(N,j,S,R)=>{let F=n(N);if(!F||!S(F))throw i(`\xABliquidacion.${j}\xBB: ${R} de este m\xF3dulo.`);return F.clave},a=N=>N.tipo==="relacion"&&!N.multiple&&!!N.relacion?.startsWith("mod_"),s=N=>a(N)||N.tipo==="relacion"&&!N.multiple&&["contacts","companies"].includes(N.relacion??"");if(!rt(e.campos))throw i("\xABliquidacion.campos\xBB: {agente?, periodo, estado, total}.");nt(e.campos,["agente","periodo","estado","total"],"liquidacion.campos");let c={periodo:r(e.campos.periodo,"campos.periodo",N=>N.tipo==="texto","un texto"),estado:r(e.campos.estado,"campos.estado",N=>N.tipo==="seleccion","una selecci\xF3n"),total:r(e.campos.total,"campos.total",N=>Ks.includes(N.tipo),"un n\xFAmero o importe")};if(Rt(e.campos.agente)||(c.agente=r(e.campos.agente,"campos.agente",s,"una relaci\xF3n simple")),t!=="_dueno"&&!c.agente)throw i("\xABliquidacion.campos.agente\xBB: con el agente en una relaci\xF3n del origen, la relaci\xF3n de aqu\xED al mismo m\xF3dulo.");let d=n(c.estado),u=new Set((d.opciones??[]).map(N=>N.valor));if(!rt(e.estados))throw i("\xABliquidacion.estados\xBB: {borrador, aprobada, cerrada, pagada} con opciones de su selecci\xF3n.");nt(e.estados,[...Ys],"liquidacion.estados");let p={};for(let N of Ys){let j=e.estados[N];if(typeof j!="string"||!u.has(j))throw i(`\xABliquidacion.estados.${N}\xBB: una opci\xF3n de \xAB${d.etiqueta}\xBB.`);p[N]=j}if(new Set(Object.values(p)).size!==Ys.length)throw i("\xABliquidacion.estados\xBB: una opci\xF3n distinta para cada estado.");if(!rt(e.lineas))throw i("\xABliquidacion.lineas\xBB: {subtabla, origen, base, comision, regla?}.");nt(e.lineas,["subtabla","origen","base","comision","regla"],"liquidacion.lineas");let m=n(e.lineas.subtabla);if(m?.tipo!=="subtabla")throw i("\xABliquidacion.lineas.subtabla\xBB: una subtabla de este m\xF3dulo.");let h=(m.columnas??[]).filter(N=>!N.archivado),b=(N,j,S,R)=>{let F=h.find(I=>I.clave===N);if(!F||!S(F))throw i(`\xABliquidacion.lineas.${j}\xBB: ${R} de \xAB${m.etiqueta}\xBB.`);return F.clave},y={subtabla:m.clave,origen:b(e.lineas.origen,"origen",N=>a(N)&&N.relacion===e.origen,`la relaci\xF3n simple a ${String(e.origen)}`),base:b(e.lineas.base,"base",N=>Ks.includes(N.tipo),"una columna num\xE9rica"),comision:b(e.lineas.comision,"comision",N=>Ks.includes(N.tipo),"una columna num\xE9rica")};if(Rt(e.lineas.regla)||(y.regla=b(e.lineas.regla,"regla",N=>N.tipo==="texto","una columna de texto")),!Array.isArray(e.reglas)||!e.reglas.length||e.reglas.length>oh)throw i(`\xABliquidacion.reglas\xBB: de 1 a ${oh}.`);let v=e.reglas.map(Sv),w={origen:e.origen,importe:Ri(e.importe,"liquidacion.importe"),fecha:Ri(e.fecha,"liquidacion.fecha"),agente:t,campos:c,estados:p,lineas:y,reglas:v};return Rt(e.cuentan)||(w.cuentan=rh(e.cuentan,"liquidacion.cuentan")),w}var Ys,oh,th,Ks,jv,rt,Rt,nt,Ri,rh,Zs,ih=f(()=>{q();Ys=["borrador","aprobada","cerrada","pagada"],oh=20,th=20,Ks=["numero","importe","porcentaje"],jv=/^[a-z][a-z0-9_]{0,40}$/,rt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Rt=e=>e==null||e==="",nt=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`\xAB${t}\xBB: clave no admitida \xAB${n.slice(0,40)}\xBB.`)},Ri=(e,o)=>{if(typeof e!="string"||!jv.test(e))throw i(`\xAB${o}\xBB: falta o no es v\xE1lido.`);return e},rh=(e,o)=>{if(!rt(e))throw i(`\xAB${o}\xBB: {campo, valores}.`);if(nt(e,["campo","valores"],o),!Array.isArray(e.valores)||!e.valores.length||e.valores.length>20||!e.valores.every(t=>typeof t=="string"&&t.length<=60))throw i(`\xAB${o}.valores\xBB: de 1 a 20 opciones.`);return{campo:Ri(e.campo,`${o}.campo`),valores:[...new Set(e.valores)]}},Zs=(e,o,t=-1e12)=>{if(typeof e!="number"||!Number.isFinite(e)||e<t||e>1e12)throw i(`\xAB${o}\xBB: un n\xFAmero.`);return e}});function sh(e,o){if(ah(e))return;if(!ec(e))throw i("\xABcuota\xBB: un objeto {proxima, periodicidad, hasta?}.");for(let a of Object.keys(e))if(!["proxima","periodicidad","hasta"].includes(a))throw i(`\xABcuota\xBB: clave no admitida \xAB${a.slice(0,40)}\xBB.`);let t=a=>o.find(s=>s.clave===a&&!s.archivado),n=(a,s)=>{let c=t(a);if(c?.tipo!=="fecha")throw i(`\xABcuota.${s}\xBB: una fecha de este m\xF3dulo.`);return c.clave},r={proxima:n(e.proxima,"proxima"),periodicidad:"mensual"};if(typeof e.periodicidad=="string"){if(!Zr.includes(e.periodicidad))throw i(`\xABcuota.periodicidad\xBB: ${Zr.join(", ")} (o {campo, valores}).`);r.periodicidad=e.periodicidad}else if(ec(e.periodicidad)){let a=e.periodicidad,s=t(a.campo);if(s?.tipo!=="seleccion")throw i("\xABcuota.periodicidad.campo\xBB: una selecci\xF3n de este m\xF3dulo.");if(!ec(a.valores)||!Object.keys(a.valores).length)throw i("\xABcuota.periodicidad.valores\xBB: {opci\xF3n: periodo}.");let c=new Set((s.opciones??[]).map(d=>d.valor));for(let[d,u]of Object.entries(a.valores)){if(!c.has(d))throw i(`\xABcuota.periodicidad.valores\xBB: \xAB${d.slice(0,40)}\xBB no es una opci\xF3n de \xAB${s.etiqueta}\xBB.`);if(!Zr.includes(u))throw i(`\xABcuota.periodicidad.valores.${d.slice(0,40)}\xBB: ${Zr.join(", ")}.`)}r.periodicidad={campo:s.clave,valores:a.valores}}else throw i(`\xABcuota.periodicidad\xBB: ${Zr.join(", ")} o {campo, valores}.`);if(!ah(e.hasta)&&(r.hasta=n(e.hasta,"hasta"),r.hasta===r.proxima))throw i("\xABcuota.hasta\xBB: otra fecha que la pr\xF3xima.");return r}var Zr,ec,ah,ch=f(()=>{q();Zr=["semanal","quincenal","mensual","bimestral","trimestral","semestral","anual"],ec=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ah=e=>e==null||e===""});function dh(e,o){if(e==null)return;if(!uh(e))throw i("\xABpapel\xBB: {tipo, campos} o null.");let t=Object.keys(e).find(c=>c!=="tipo"&&c!=="campos"&&c!=="atributos");if(t)throw i(`\xABpapel\xBB: \xAB${t}\xBB no se reconoce.`);let n=typeof e.tipo=="string"?oc[e.tipo]:void 0;if(!n||!Object.hasOwn(oc,e.tipo))throw i(`\xABpapel.tipo\xBB: uno de ${Object.keys(oc).join(", ")}.`);let r=e.campos??{};if(!uh(r))throw i("\xABpapel.campos\xBB: {campo est\xE1ndar: clave del campo}.");let a={};for(let[c,d]of Object.entries(r)){let u=Object.hasOwn(n.campos,c)?n.campos[c]:void 0;if(!u)throw i(`\xABpapel.campos\xBB: \xAB${c}\xBB no es un campo de \xAB${n.etiqueta}\xBB (${Object.keys(n.campos).join(", ")}).`);if(d==null||d==="")continue;let p=o.find(m=>m.clave===d&&!m.archivado);if(!p)throw i(`\xABpapel\xBB: ${u.etiqueta} apunta a \xAB${String(d)}\xBB, que no es un campo vivo de este m\xF3dulo.`);if(!u.tipos.includes(p.tipo))throw i(`\xABpapel\xBB: ${u.etiqueta} tiene que ser un campo de tipo ${u.tipos.join(" o ")} (\xAB${p.etiqueta}\xBB es ${p.tipo}).`);a[c]=p.clave}for(let[c,d]of Object.entries(n.campos))if(d.obligatorio&&!a[c])throw i(`\xABpapel\xBB: falta el campo de ${d.etiqueta}.`);let s=Av(n,e.atributos,o);return s?{tipo:e.tipo,campos:a,atributos:s}:{tipo:e.tipo,campos:a}}function Av(e,o,t){if(o==null)return;let n=e.atributos;if(!n)throw i(`\xABpapel.atributos\xBB: \xAB${e.etiqueta}\xBB no tiene atributos.`);if(!Array.isArray(o))throw i("\xABpapel.atributos\xBB: una lista de claves de campo.");if(o.length>n.max)throw i(`\xABpapel.atributos\xBB: como mucho ${n.max}.`);let r=[];for(let a of o){let s=typeof a=="string"?t.find(c=>c.clave===a&&!c.archivado):void 0;if(!s)throw i(`\xABpapel.atributos\xBB: \xAB${String(a)}\xBB no es un campo vivo de este m\xF3dulo.`);if(!n.tipos.includes(s.tipo))throw i(`\xABpapel.atributos\xBB: \xAB${s.etiqueta}\xBB es ${s.tipo}; vale ${n.tipos.join(", ")}.`);r.includes(s.clave)||r.push(s.clave)}return r.length?r:void 0}var lh,Ov,oc,uh,ph=f(()=>{q();lh={nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},correo:{etiqueta:"Correo",tipos:["correo"]},telefono:{etiqueta:"Tel\xE9fono",tipos:["telefono"]},nif:{etiqueta:"NIF",tipos:["texto"]},direccion:{etiqueta:"Direcci\xF3n",tipos:["texto","texto_largo"]}},Ov={nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},precio:{etiqueta:"Precio",tipos:["importe","numero"]},foto:{etiqueta:"Foto",tipos:["url"]},enlace:{etiqueta:"Enlace",tipos:["url"]},stock:{etiqueta:"Stock",tipos:["numero","contador"]},descripcion:{etiqueta:"Descripci\xF3n",tipos:["texto","texto_largo"]},categoria:{etiqueta:"Categor\xEDa",tipos:["seleccion","seleccion_multiple","texto"]},varianteId:{etiqueta:"Id de variante",tipos:["texto","numero"]}},oc={cerradura:{etiqueta:"Cerradura",campos:{nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},identificador:{etiqueta:"Identificador",tipos:["texto","codigo","numero","dispositivo"]},ubicacion:{etiqueta:"Ubicaci\xF3n",tipos:["texto"]}}},dispositivo:{etiqueta:"Dispositivo",campos:{nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},identificador:{etiqueta:"Identificador",tipos:["texto","codigo","dispositivo"]},canal:{etiqueta:"Canal",tipos:["numero"]}}},clientes:{etiqueta:"Clientes",campos:lh},proveedores:{etiqueta:"Proveedores",campos:lh},catalogo:{etiqueta:"Cat\xE1logo",campos:Ov,atributos:{etiqueta:"Atributos",tipos:["texto","seleccion","seleccion_multiple","numero","importe","porcentaje","booleano"],max:16}},producto:{etiqueta:"Producto",campos:{nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},sku:{etiqueta:"SKU",tipos:["texto","codigo"]},precio:{etiqueta:"Precio",tipos:["numero","importe"]},existencias:{etiqueta:"Existencias",tipos:["numero","contador"]}}},pedido:{etiqueta:"Pedido",campos:{numero:{etiqueta:"N\xFAmero",tipos:["texto","codigo"]},estado:{etiqueta:"Estado",tipos:["texto","seleccion"]},total:{etiqueta:"Total",tipos:["numero","importe"]}}}},uh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Yr(e,o,t=!1){if(e!=null){if(!Array.isArray(e)||e.length>fh)throw i(`${o}: el filtro, una lista de hasta ${fh} condiciones.`);if(e.length)return e.map((n,r)=>{let a=`${o}, condici\xF3n ${r+1}`;if(typeof n!="object"||n===null||Array.isArray(n))throw i(`${a}: {campo, op, valor}.`);let s=n;for(let u of Object.keys(s))if(!["campo","op","valor"].includes(u))throw i(`${a}: clave no admitida \xAB${u.slice(0,40)}\xBB.`);if(typeof s.campo!="string"||!(Ge.test(s.campo)||t&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(s.campo)))throw i(`${a}: \xABcampo\xBB, la clave de un campo del m\xF3dulo que resume.`);if(typeof s.op!="string"||!mh.includes(s.op))throw i(`${a}: \xABop\xBB, una de ${mh.join(", ")}.`);let c=s.op;if(c==="vacio"||c==="no_vacio")return{campo:s.campo,op:c};let d=u=>typeof u=="string"&&u.length<=200||typeof u=="number"&&Number.isFinite(u)||typeof u=="boolean";if(c==="en"||c==="no_en"){if(!Array.isArray(s.valor)||!s.valor.length||s.valor.length>50||!s.valor.every(u=>d(u)&&typeof u!="boolean"))throw i(`${a}: \xAB${c}\xBB lleva una lista de valores (hasta 50).`);return{campo:s.campo,op:c,valor:s.valor}}if(!d(s.valor))throw i(`${a}: \xAB${c}\xBB lleva un valor (texto, n\xFAmero o s\xED/no).`);return{campo:s.campo,op:c,valor:s.valor}})}}function _h(e,o=!1){if(typeof e=="string"&&(vh.has(e)||Pv.has(e)))throw i(`La clave del m\xF3dulo \xAB${e.slice(0,40)}\xBB es una palabra reservada: usa otra (p. ej. \xAB${e.slice(0,30)}_crm\xBB o un sin\xF3nimo).`);if(typeof e!="string"||!yh.test(e))throw i(`La clave del m\xF3dulo${typeof e=="string"?` \xAB${e.slice(0,40)}\xBB`:""}: min\xFAsculas y \xAB_\xBB, de 2 a 31, sin palabras reservadas.`);if(e.startsWith("sub_")!==o)throw i(o?"Clave interna no v\xE1lida.":"La clave del m\xF3dulo no puede empezar por \xABsub_\xBB.");return e}function ac(e,o,t=!1){if(typeof e!="object"||e===null||Array.isArray(e))throw i("Definici\xF3n no v\xE1lida.");let n=e,r=_h(n.clave,t);if(!Array.isArray(n.campos))throw i("Faltan los campos.");let a=n.campos.map((s,c)=>nr(s,c,o,r));if(a.filter(s=>s.esCodigo&&!s.archivado).length>1)throw i("Solo un campo puede ser el c\xF3digo de la ficha.");return a}function $h(e,o){if(typeof e!="object"||e===null||Array.isArray(e))throw i("Definici\xF3n no v\xE1lida.");let t=e,n=_h(t.clave,o.interno===!0),r=it(t.nombre,"el nombre",60),a=it(t.nombre_plural??t.nombre,"el nombre en plural",60),s=it(t.descripcion??"","la descripci\xF3n",500,!0),c=typeof t.icono=="string"&&ic.includes(t.icono)?t.icono:"box",d;if(t.color===null||t.color==="")d=null;else if(t.color!==void 0){if(typeof t.color!="string"||!/^#[0-9a-f]{6}$/i.test(t.color))throw i("\xABcolor\xBB: un color #rrggbb.");d=t.color.toLowerCase()}let u=xh(ac(t,o.modulosDelEspacio,o.interno),n,o.camposRelacion);if(u.filter(T=>!T.archivado&&T.opciones?.some(J=>J.hecho)).length>1)throw i("Solo una selecci\xF3n puede marcar estados como \xABhechos\xBB.");if(u.filter(T=>!T.archivado&&T.proximaAccion).length>1)throw i("Solo una fecha puede ser la de la pr\xF3xima acci\xF3n.");let p=new Set;for(let T of u){if(p.has(T.clave))throw i(`El campo \xAB${T.clave}\xBB est\xE1 repetido.`);p.add(T.clave)}let m=u.filter(T=>!T.archivado);for(let T of m)for(let J of Cs(T)){let le=m.find(No=>No.clave===J.relacion);if(!le||le.clave===T.clave||le.tipo!=="relacion"||le.multiple&&!T.multiple)throw i(`\xAB${T.etiqueta}\xBB: un origen m\xFAltiple necesita tambi\xE9n un destino m\xFAltiple.`)}if(cm(m),m.length===0)throw i("El m\xF3dulo necesita al menos un campo.");for(let T of m.filter(J=>J.tipo==="busqueda")){let J=m.find(le=>le.clave===T.desde);if(!J||J.tipo!=="relacion")throw i(`\xAB${T.etiqueta}\xBB: tiene que salir de un campo de relaci\xF3n de este m\xF3dulo.`)}for(let T of m.filter(J=>J.tipo==="qr"&&J.destino==="campo"&&J.campo))if(!m.find(le=>le.clave===T.campo))throw i(`\xAB${T.etiqueta}\xBB: el campo \xAB${T.campo}\xBB no existe en este m\xF3dulo.`);if(m.length>o.topeCampos)throw new z(400,"tope_campos",`Como mucho ${o.topeCampos} campos por m\xF3dulo en tu plan.`,!0,{topePlan:{clave:"campos",tope:o.topeCampos,solicitado:m.length}});for(let T of o.anterior??[]){let J=u.find(le=>le.clave===T.clave);if(!J)throw i(`El campo \xAB${T.etiqueta}\xBB no se quita: se archiva.`);if(J.tipo!==T.tipo&&!Wv(T.tipo,J.tipo))throw i(`\xAB${T.etiqueta}\xBB no puede pasar de ${T.tipo} a ${J.tipo}.`)}let h=t.articulo==="un"||t.articulo==="una"?t.articulo:null,b=vi(t.ficha,u),y=Hr(t.impresion,u),v=gf(t.validaciones,u.filter(T=>!T.archivado));_f(u);for(let T of u){if(T.tipo!=="contador"||!T.alMarcar)continue;let J=u.find(le=>le.clave===T.alMarcar&&!le.archivado);if(J?.tipo!=="booleano"&&J?.tipo!=="hecho")throw i(`\xAB${T.etiqueta}\xBB: \xABal marcar\xBB tiene que ser un s\xED/no o un \xABhecho\xBB de este m\xF3dulo.`)}let w=Qm(t.vistas,u),N=Tf(t.conversiones),j=Lf(t.encadenar,u),S=Bf(t.plantillas_hijos),R=zv(t.campo_ambito,u),F=Hf(t.publico,u),I=mi(t.recurso,u),_=fi(t.reserva,u),E=Qf(t.asignacion,u),g=Jf(t.pertenencia,u),x=Zf(t.stock,u),O=nh(t.liquidacion,u),k=wm(t.sucesion),L=Nm(t.liquidacion_v2,u);if(O&&L)throw i("Elige una versi\xF3n de liquidaci\xF3n por m\xF3dulo.");let V=sh(t.cuota,u),U=xm(t.precios,u),be=Ni(t.relacionadas,u),Be=$i(t.siguientes),br=dh(t.papel,u),X=Js(t.personas,u);if(t.portal!==void 0&&t.portal!==null&&!["suyos_ver","suyos_anadir","suyos_editar","todos_ver"].includes(t.portal))throw i("\xABportal\xBB: suyos_ver, suyos_anadir, suyos_editar o todos_ver.");let Ve=t.portal??void 0,Ue;if(t.portal_campos!==void 0&&t.portal_campos!==null){let T=t.portal_campos;if(!Ve)throw i("\xABportal_campos\xBB va con \xABportal\xBB.");if(typeof T!="object"||Array.isArray(T)||Object.keys(T).length>u.length)throw i("\xABportal_campos\xBB: clave del campo \u2192 rellenar, ver o no.");for(let[J,le]of Object.entries(T)){if(!u.some(No=>No.clave===J))throw i(`\xABportal_campos\xBB: el m\xF3dulo no tiene el campo \xAB${J.slice(0,40)}\xBB.`);if(le!=="rellenar"&&le!=="ver"&&le!=="no")throw i(`\xABportal_campos.${J.slice(0,40)}\xBB: rellenar, ver o no.`)}Ue={...T}}let Do;if(t.funcionesNativas!==void 0){if(!t.funcionesNativas||typeof t.funcionesNativas!="object"||Array.isArray(t.funcionesNativas)||Object.entries(t.funcionesNativas).some(([T,J])=>!["relacionadas","siguientes"].includes(T)||!Array.isArray(J)||J.length>(T==="relacionadas"?20:5)))throw i("Las funciones nativas necesitan relacionadas o siguientes declarados.");Do=structuredClone(t.funcionesNativas)}return{clave:n,nombre:r,nombre_plural:a,articulo:h,descripcion:s,icono:c,...d!==void 0?{color:d}:{},campos:Cf(qf(u)).map(T=>{if(T.tipo!=="busqueda")return T;let{origen:J,...le}=T;return le}),paginas:t.paginas===!0,...b?{ficha:b}:{},...y?{impresion:y}:{},...v?{validaciones:v}:{},...w?{vistas:w}:{},...N?{conversiones:N}:{},...j?{encadenar:j}:{},...S?{plantillas_hijos:S}:{},...R?{campo_ambito:R}:{},...F?{publico:F}:{},...I?{recurso:I}:{},..._?{reserva:_}:{},...E?{asignacion:E}:{},...g?{pertenencia:g}:{},...x?{stock:x}:{},...O?{liquidacion:O}:{},...k?{sucesion:k}:{},...L?{liquidacion_v2:L}:{},...V?{cuota:V}:{},...U?{precios:U}:{},...be?{relacionadas:be}:{},...Be?{siguientes:Be}:{},...br?{papel:br}:{},...X?{personas:X}:{},...Ve?{portal:Ve}:{},...Ue&&Object.keys(Ue).length?{portal_campos:Ue}:{},...Do?{funcionesNativas:Do}:{}}}function zv(e,o){if(e==null||e==="")return;let t=o.find(n=>n.clave===e&&!n.archivado);if(!t||!(t.tipo==="seleccion"||t.tipo==="relacion"&&!t.multiple))throw i("\xABcampo_ambito\xBB: una selecci\xF3n o una relaci\xF3n simple de este m\xF3dulo.");return t.clave}function nr(e,o,t,n){if(typeof e!="object"||e===null||Array.isArray(e))throw i(`Campo ${o+1} no v\xE1lido.`);let r=e;if(r.destinos!==void 0){if(r.tipo!=="relacion"||r.multiple===!0||r.camposVinculo!==void 0||!Array.isArray(r.destinos)||!r.destinos.length||r.destinos.length>8||r.destinos.some(y=>typeof y!="string")||new Set(r.destinos).size!==r.destinos.length)throw i("La relaci\xF3n polim\xF3rfica necesita entre 1 y 8 destinos distintos y un solo registro.");let{destinos:u,relacion:p,multiple:m,alBorrar:h,...b}=r;return nr({...b,tipo:"subtabla",polimorfica:!0,columnas:u.map(y=>({clave:`a_${y}`,etiqueta:y,tipo:"relacion",relacion:y,alBorrar:h}))},o,t,n)}if(r.camposVinculo!==void 0){if(r.tipo!=="relacion"||r.multiple!==!0||!Array.isArray(r.camposVinculo)||!r.camposVinculo.length||r.camposVinculo.length>=tc)throw i("Los datos del v\xEDnculo necesitan una relaci\xF3n m\xFAltiple y entre 1 y 29 campos.");let{camposVinculo:u,relacion:p,tipoContacto:m,alBorrar:h,multiple:b,...y}=r;return nr({...y,tipo:"subtabla",vinculo:!0,columnas:[{clave:"destino",etiqueta:r.etiqueta,tipo:"relacion",relacion:p,tipoContacto:m,alBorrar:h,obligatorio:!0},...u]},o,t,n)}if(typeof r.clave=="string"&&vh.has(r.clave))throw i(`La clave \xAB${r.clave.slice(0,40)}\xBB del campo ${o+1}${n?` de \xAB${n}\xBB`:""} es una palabra reservada: usa otra (p. ej. \xAB${r.clave.slice(0,30)}_campo\xBB o un sin\xF3nimo).`);if(typeof r.clave!="string"||!Ge.test(r.clave))throw i(`La clave del campo ${o+1}${n?` de \xAB${n}\xBB`:""}${typeof r.clave=="string"?` (\xAB${r.clave.slice(0,40)}\xBB)`:""}: min\xFAsculas, n\xFAmeros y \xAB_\xBB, sin palabras reservadas.`);let a=r.tipo;if(!rc.includes(a))throw i(`Tipo de campo no v\xE1lido: ${String(r.tipo)}.`);let s={clave:r.clave,etiqueta:it(r.etiqueta,`la etiqueta del campo ${o+1}`,80),tipo:a};if(r.ajustesNativos!==void 0){if(a!=="relacion"&&a!=="busqueda")throw i("Solo las relaciones y b\xFAsquedas declaradas tienen ajustes nativos.");s.ajustesNativos=Zm(r.ajustesNativos);for(let u of Object.values(s.ajustesNativos??{})){let p={...r,...u,ajustesNativos:void 0};for(let[m,h]of Object.entries(u))h===null&&delete p[m];nr(p,o,t,n)}}for(let u of["formulaNativa","defectoNativo"])if(r[u]!==void 0){if(typeof r[u]!="string"||!r[u].trim()||r[u].length>no||u==="formulaNativa"&&a!=="formula")throw i("La variante nativa necesita una f\xF3rmula v\xE1lida y acotada.");s[u]=r[u]}if(r.obligatorio===!0&&(s.obligatorio=!0),s.enTabla=r.enTabla!==!1,r.sensible!==void 0&&typeof r.sensible!="boolean")throw i("\xABsensible\xBB debe ser s\xED o no.");if(r.sensible===!0&&(s.sensible=!0),r.semantica!==void 0){if(!["dato","firma","consentimiento","credencial","auditoria","financiero"].includes(String(r.semantica)))throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");s.semantica=r.semantica}if(r.archivado===!0&&(s.archivado=!0),r.seccion!==void 0&&r.seccion!==""&&(s.seccion=it(r.seccion,"la secci\xF3n",60)),r.ayuda!==void 0&&r.ayuda!==""&&(s.ayuda=it(r.ayuda,"la ayuda",200)),(a==="fecha"||a==="fecha_hora")&&r.proximaAccion===!0&&(s.proximaAccion=!0),a==="numero"&&r.sinMiles===!0&&(s.sinMiles=!0),r.pasoMinutos!==void 0&&r.pasoMinutos!==null){let u=r.pasoMinutos;if(a!=="hora"||typeof u!="number"||!Number.isInteger(u)||u<1||u>60||60%u!==0)throw i(`\xAB${s.etiqueta}\xBB: el paso de la hora, en minutos que dividan la hora (1, 5, 10, 15, 30 o 60).`);u>1&&(s.pasoMinutos=u)}if(r.puertaExtra!==void 0&&typeof r.puertaExtra!="boolean")throw i("\xABpuertaExtra\xBB debe ser s\xED o no.");a==="dispositivo"&&r.conector==="ttlock"&&r.puertaExtra===!0&&(s.puertaExtra=!0);for(let u of["minimo","maximo"])if(r[u]!==void 0&&r[u]!==null){if(typeof r[u]!="number"||!Number.isFinite(r[u]))throw i(`\xAB${u}\xBB tiene que ser un n\xFAmero.`);s[u]=r[u]}if(r.transiciones!==void 0&&a!=="seleccion")throw i("Las transiciones requieren una selecci\xF3n.");if(a==="seleccion"||a==="seleccion_multiple"){if(!Array.isArray(r.opciones)||r.opciones.length===0||r.opciones.length>100)throw i(`\xAB${s.etiqueta}\xBB: entre 1 y 100 opciones.`);let u=new Set;if(s.opciones=r.opciones.map(p=>{let m=typeof p=="string"?{valor:p,etiqueta:p}:p,h=it(m.valor??m.etiqueta,"el valor de una opci\xF3n",80);if(u.has(h))throw i(`\xAB${s.etiqueta}\xBB: la opci\xF3n \xAB${h}\xBB est\xE1 repetida.`);u.add(h);let b={valor:h,etiqueta:it(m.etiqueta??h,"una opci\xF3n",80)};return typeof m.color=="string"&&Tv.test(m.color)&&(b.color=m.color),a==="seleccion"&&m.hecho===!0&&(b.hecho=!0),a==="seleccion"&&r.embudo===!0&&Ef(m,b,s.etiqueta),b}),a==="seleccion"&&r.embudo===!0&&(s.embudo=!0),r.transiciones!==void 0){if(a!=="seleccion")throw i("Las transiciones requieren una selecci\xF3n.");s.transiciones=xf(r.transiciones,s)}}if(a==="relacion"){let u=r.relacion;if(!(typeof u=="string"&&(qv.includes(u)||u.startsWith("mod_")&&(t.includes(u.slice(4))||u.slice(4)===n))))throw i(`\xAB${s.etiqueta}\xBB: relaci\xF3n con algo que no existe.`);if(s.relacion=u,r.tipoContacto!==void 0&&r.tipoContacto!==null&&r.tipoContacto!==""){if(u!=="contacts"&&u!=="companies")throw i(`\xAB${s.etiqueta}\xBB: el tipo solo vale en una relaci\xF3n con Personas o Empresas.`);if(typeof r.tipoContacto!="string"||!Bv.test(r.tipoContacto))throw i(`\xAB${s.etiqueta}\xBB: el tipo no es una clave v\xE1lida.`);s.tipoContacto=r.tipoContacto}if(r.mostrarTareasEnFichaRelacionada===!0){if(r.multiple===!0)throw i(`\xAB${s.etiqueta}\xBB: mostrar tareas relacionadas requiere una relaci\xF3n simple.`);s.mostrarTareasEnFichaRelacionada=!0}}else if(r.mostrarTareasEnFichaRelacionada===!0)throw i(`\xAB${s.etiqueta}\xBB: la opci\xF3n de tareas relacionadas solo sirve en campos de relaci\xF3n.`);if(r.completarDesde!==void 0&&r.completarDesde!==null){if(!["relacion","texto","texto_largo","numero","importe","porcentaje","correo","telefono","url","codigo","fecha","fecha_hora","booleano","seleccion","ubicacion"].includes(a))throw i("Ese tipo de campo no admite autocompletado.");let u=r.completarDesde;if(typeof u!="object"||Array.isArray(u)||Object.keys(u).some(m=>!["relacion","campo","alternativa"].includes(m))||typeof u.relacion!="string"||!Ge.test(u.relacion)||typeof u.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(u.campo))throw i(`\xAB${s.etiqueta}\xBB: completarDesde requiere relacion y campo.`);let p;if(u.alternativa!==void 0){let m=u.alternativa;if(!m||typeof m!="object"||Array.isArray(m)||Object.keys(m).some(h=>h!=="relacion"&&h!=="campo")||typeof m.relacion!="string"||!Ge.test(m.relacion)||typeof m.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(m.campo))throw i("La alternativa de autocompletado necesita relacion y campo.");p={relacion:m.relacion,campo:m.campo}}s.completarDesde={relacion:u.relacion,campo:u.campo,...p?{alternativa:p}:{}}}if(r.completarNativo!==void 0){if(a==="relacion")throw i("La relaci\xF3n conserva su autocompletado en ajustesNativos.");if(r.completarNativo===null)s.completarNativo=null;else{let u=nr({...r,completarDesde:r.completarNativo,completarNativo:void 0},o,t,n).completarDesde;if(!u)throw i("La variante de autocompletado no es v\xE1lida.");s.completarNativo=u}}if((a==="relacion"||a==="archivos")&&r.multiple===!0&&(s.multiple=!0),a==="archivos"&&r.soloImagenes===!0&&(s.soloImagenes=!0),a==="texto_largo"&&r.sinFormato===!0&&(s.sinFormato=!0),(a==="formula"||a==="resumen")&&r.formato!==void 0&&r.formato!==null&&r.formato!=="automatico"){if(r.formato!=="numero"&&r.formato!=="importe"&&r.formato!=="porcentaje")throw i(`\xAB${s.etiqueta}\xBB: el formato es autom\xE1tico, n\xFAmero, importe o porcentaje.`);s.formato=r.formato}if(a==="archivos"&&r.versiones===!0&&(s.versiones=!0),a==="secreto"&&delete s.obligatorio,a==="contador"&&typeof r.alMarcar=="string"&&r.alMarcar){if(!Ge.test(r.alMarcar))throw i(`\xAB${s.etiqueta}\xBB: \xABal marcar\xBB no es un campo v\xE1lido.`);s.alMarcar=r.alMarcar}if(a==="busqueda"){if(typeof r.desde!="string"||!Ge.test(r.desde)||typeof r.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(r.campo))throw i(`\xAB${s.etiqueta}\xBB: elige la relaci\xF3n y el campo que trae.`);if(r.siVacio!==void 0){if(typeof r.siVacio!="string"||!Ge.test(r.siVacio))throw i("La alternativa necesita otra b\xFAsqueda escalar del mismo tipo, sin cadenas.");s.siVacio=r.siVacio}s.desde=r.desde,s.campo=r.campo,delete s.obligatorio}if(a==="relacion"&&r.alBorrar!==void 0&&r.alBorrar!=="avisar"){if(!Ev.includes(r.alBorrar))throw i(`\xAB${s.etiqueta}\xBB: \xABal borrar\xBB no v\xE1lido.`);s.alBorrar=r.alBorrar}if(a==="valoracion"){let u=r.maximo===void 0||r.maximo===null?5:r.maximo;if(typeof u!="number"||!Number.isInteger(u)||u<3||u>10)throw i(`\xAB${s.etiqueta}\xBB: entre 3 y 10 estrellas.`);s.maximo=u,delete s.minimo}if(a==="autonumero"){let u=typeof r.prefijo=="string"?r.prefijo.trim():"";if(!/^[A-Za-z0-9_-]{0,10}$/.test(u))throw i(`\xAB${s.etiqueta}\xBB: el prefijo, hasta 10 letras, n\xFAmeros, \xAB-\xBB o \xAB_\xBB.`);let p=r.digitos===void 0||r.digitos===null?4:r.digitos;if(typeof p!="number"||!Number.isInteger(p)||p<1||p>10)throw i(`\xAB${s.etiqueta}\xBB: de 1 a 10 d\xEDgitos.`);u&&(s.prefijo=u),s.digitos=p,r.anual===!0?s.anual=!0:delete s.anual}if(wh.includes(a)&&delete s.obligatorio,a==="subtabla"){if(!Array.isArray(r.columnas)||r.columnas.length===0||r.columnas.length>tc)throw i(`\xAB${s.etiqueta}\xBB: entre 1 y ${tc} columnas.`);let u=new Set(["padre"]);if(s.columnas=r.columnas.map((h,b)=>{let y=nr(h,b,t,n);if(!Lv.includes(y.tipo))throw i(`\xAB${s.etiqueta}\xBB: una columna no puede ser de tipo ${y.tipo}.`);if(u.has(y.clave))throw i(`\xAB${s.etiqueta}\xBB: la columna \xAB${y.clave}\xBB est\xE1 repetida o es reservada.`);if(u.add(y.clave),y.tipo==="subtabla"&&1+Nh(y)>gh)throw i(`\xAB${s.etiqueta}\xBB: como mucho ${gh} niveles de subtablas (cap\xEDtulo \u2192 subcap\xEDtulo \u2192 partidas).`);if(y.tipo==="relacion"){if(y.multiple)throw i(`\xAB${s.etiqueta}\xBB: una columna de relaci\xF3n es de un solo registro.`);if(!y.relacion?.startsWith("mod_")&&y.relacion!=="contacts"&&y.relacion!=="companies")throw i(`\xAB${s.etiqueta}\xBB: una columna de relaci\xF3n apunta a un m\xF3dulo, Persona o Empresa.`)}return y}),r.vinculo!==void 0){if(r.vinculo!==!0)throw i("\xABvinculo\xBB debe ser true.");let h=s.columnas[0];if(h?.clave!=="destino"||h.tipo!=="relacion"||h.multiple||h.archivado||!h.obligatorio||s.columnas.slice(1).some(b=>["relacion","subtabla","resumen","formula"].includes(b.tipo)))throw i("El v\xEDnculo necesita primero una relaci\xF3n obligatoria \xABdestino\xBB y despu\xE9s sus campos de datos.");s.vinculo=!0}if(r.polimorfica!==void 0){if(r.polimorfica!==!0||r.vinculo||s.columnas.length>8||s.columnas.some(h=>h.tipo!=="relacion"||h.multiple||h.obligatorio||h.archivado)||new Set(s.columnas.map(h=>h.relacion)).size!==s.columnas.length)throw i("La relaci\xF3n polim\xF3rfica lleva hasta ocho columnas de relaci\xF3n simple opcionales y distintas.");s.polimorfica=!0}for(let h of s.columnas)if(h.tipo==="resumen"&&!s.columnas.some(b=>b.tipo==="subtabla"&&(b.clave===h.de||!!b.hijo&&b.hijo===h.de)))throw i(`\xAB${s.etiqueta}\xBB: el total \xAB${h.etiqueta}\xBB tiene que ser de una subtabla de la l\xEDnea.`);let p=r.columnas;s.columnas=s.columnas.map((h,b)=>{let y=p[b]?.copiar;if(y==null)return h;let v=`\xAB${s.etiqueta}\xBB, columna \xAB${h.etiqueta}\xBB`;if(h.tipo!=="relacion")throw i(`${v}: \xABcopiar\xBB va en una columna de relaci\xF3n.`);if(typeof y!="object"||Array.isArray(y)||Object.keys(y).length>hh)throw i(`${v}: \xABcopiar\xBB, un objeto columna \u2192 campo (hasta ${hh}).`);for(let[w,N]of Object.entries(y)){let j=s.columnas.find(S=>S.clave===w);if(!j||j.tipo==="relacion"||j.tipo==="formula")throw i(`${v}: \xAB${w.slice(0,40)}\xBB no es una columna que se pueda rellenar.`);if(typeof N!="string"||!Ge.test(N))throw i(`${v}: el campo de \xAB${w}\xBB no es v\xE1lido.`)}return Object.keys(y).length?{...h,copiar:{...y}}:h}),s.columnas=s.columnas.map((h,b)=>{let y=p[b]?.rellenar;if(y==null)return h;let v=`\xAB${s.etiqueta}\xBB, columna \xAB${h.etiqueta}\xBB`;if(h.tipo!=="articulo")throw i(`${v}: \xABrellenar\xBB va en una columna de art\xEDculo.`);if(typeof y!="object"||Array.isArray(y)||Object.keys(y).length>bh.length*2)throw i(`${v}: \xABrellenar\xBB, un objeto columna \u2192 dato del art\xEDculo.`);for(let[w,N]of Object.entries(y)){let j=s.columnas.find(S=>S.clave===w);if(!j||["relacion","articulo","formula","subtabla","resumen"].includes(j.tipo))throw i(`${v}: \xAB${w.slice(0,40)}\xBB no es una columna que se pueda rellenar.`);if(!bh.includes(N))throw i(`${v}: \xAB${w.slice(0,40)}\xBB se rellena con nombre, referencia, codigo, precio o iva_pct.`)}return Object.keys(y).length?{...h,rellenar:{...y}}:h}),typeof r.hijo=="string"&&Dv.test(r.hijo)&&(s.hijo=r.hijo);let m=Um(r.impresion,s.columnas);m&&(s.impresion=m),delete s.obligatorio}if(a==="autonumero"){let u=ji(r.visibleSi,s.etiqueta);u&&(s.visibleSi=u)}if(!Ym({tipo:a})){let u=ji(r.visibleSi,s.etiqueta);u&&(s.visibleSi=u);let p=ji(r.obligatorioSi,s.etiqueta);if(p&&(s.obligatorioSi=p),r.patron!==void 0&&r.patron!==null&&r.patron!==""){if(!uf.includes(a))throw i(`\xAB${s.etiqueta}\xBB: un patr\xF3n solo vale para textos, correos, tel\xE9fonos, webs y c\xF3digos.`);let h=pf(r.patron,s.etiqueta);h&&(s.patron=h)}if(r.unico===!0){if(!df.includes(a))throw i(`\xAB${s.etiqueta}\xBB: \xAB\xFAnico\xBB solo vale para textos, correos, tel\xE9fonos, webs, c\xF3digos y n\xFAmeros.`);s.unico=!0}if(r.esCodigo===!0){if(!s.unico)throw i(`\xAB${s.etiqueta}\xBB: el c\xF3digo de la ficha tiene que ser \xFAnico.`);s.esCodigo=!0}let m=mf(r.porDefecto,s);m&&(s.porDefecto=m)}let c=jh(r.permisos,s.etiqueta);if(c&&(s.permisos=c),r.grupo!==void 0&&r.grupo!==null&&r.grupo!==""){if(typeof r.grupo!="string"||!Mv.test(r.grupo))throw i(`\xAB${s.etiqueta}\xBB: el grupo, en min\xFAsculas y sin espacios (p. ej. \xABfinanzas\xBB).`);s.grupo=r.grupo}if(r.enmascarado===!0){if(!Iv.includes(a))throw i(`\xAB${s.etiqueta}\xBB: solo se enmascaran textos, correos, tel\xE9fonos y c\xF3digos.`);s.enmascarado=!0}let d=yf(r.depende,s);if(d&&(s.depende=d),a==="archivo"&&(s.enTabla=!1,delete s.obligatorio),a==="boton"){let u=r.automatizacion;if(typeof u!="number"||!Number.isSafeInteger(u)||u<=0)throw i(`\xAB${s.etiqueta}\xBB: elige la automatizaci\xF3n del bot\xF3n.`);s.automatizacion=u,s.enTabla=!1,delete s.obligatorio}if(a==="formula"){if(typeof r.formula!="string"||!r.formula.trim()||r.formula.length>no)throw i(`\xAB${s.etiqueta}\xBB: escribe la f\xF3rmula (hasta ${no} caracteres).`);s.formula=r.formula.trim(),delete s.obligatorio}if(a==="resumen"){let u=r.calculo;if(typeof r.de!="string"||!yh.test(r.de)||typeof r.via!="string"||!Ge.test(r.via)||!nc.includes(u))throw i(`\xAB${s.etiqueta}\xBB: elige de qu\xE9 m\xF3dulo, por qu\xE9 relaci\xF3n y qu\xE9 c\xE1lculo.`);if(s.de=r.de,s.via=r.via,s.calculo=u,u!=="recuento"){if(typeof r.campo!="string"||!Ge.test(r.campo))throw i(`\xAB${s.etiqueta}\xBB: elige el campo que resume.`);s.campo=r.campo}if(u==="media_ponderada"){if(typeof r.peso!="string"||!Ge.test(r.peso))throw i(`\xAB${s.etiqueta}\xBB: elige el campo que pondera la media.`);s.peso=r.peso}else delete s.peso;let p=Yr(r.filtro,`\xAB${s.etiqueta}\xBB`);p?s.filtro=p:delete s.filtro,delete s.obligatorio}if(a==="dispositivo"){if(!Rv.includes(r.conector))throw i(`\xAB${s.etiqueta}\xBB: elige de qu\xE9 conexi\xF3n es el aparato (TTLock o Shelly).`);s.conector=r.conector}if(a==="qr"){let u=r.destino==="campo"||typeof r.campo=="string"&&r.campo&&r.destino!=="ficha"?"campo":"ficha";if(s.destino=u,u==="campo"){if(typeof r.campo!="string"||!Ge.test(r.campo))throw i(`\xAB${s.etiqueta}\xBB: elige el campo que resalta al escanear.`);s.campo=r.campo}else delete s.campo;delete s.obligatorio}return s}var rc,wh,nc,mh,fh,Ev,qv,Rv,kv,vh,Pv,ic,Ge,yh,Tv,Mv,Iv,it,Dv,Lv,hh,gh,Nh,bh,tc,Fv,Wv,Bv,Ym,Kr=f(()=>{vm();$m();Cm();nf();Bs();lm();q();bi();ff();Sh();Ds();bf();Nf();jf();Rf();Mf();zf();Vf();Xf();As();Gf();eh();ih();ch();xi();ph();Ch();rc=["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","seleccion_multiple","etiquetas","url","correo","telefono","relacion","archivos","archivo","busqueda","resumen","duracion","hecho","porcentaje","valoracion","contador","cronometro","secreto","color","ubicacion","checklist","codigo","firma","hora","articulo","dispositivo","creado_el","creado_por","modificado_el","modificado_por","autonumero","formula","subtabla","boton","qr"],wh=["creado_el","creado_por","modificado_el","modificado_por","autonumero"],nc=["recuento","suma","minimo","maximo","ultimo","media","media_ponderada"],mh=["igual","distinto","en","no_en","vacio","no_vacio","mayor","menor"],fh=5;Ev=["avisar","desvincular","impedir"],qv=["companies","contacts","deals"],Rv=["ttlock","shelly"],kv=["id","numero","sales_id","creado","actualizado","espacio_id","modulo_id","datos","_color_tarjeta"],vh=new Set([...kv,"q","filter","sort","order","page","perpage","limit","offset","select","from","where","insert","update","delete","drop","table","union","join","and","or","not","null","true","false","order","group","having","into","values","create","alter","grant","revoke","truncate","exec","execute","function","user","listar","ver","crear","actualizar","borrar","enlazar","buscar","exportar","importar","confirmar","idempotencia","operacion","tools","list","call","resources","prompts","__proto__","constructor","prototype","es_plantilla"]),Pv=new Set(["companies","contacts","deals","sales","tasks","tags","notas","tareas","empresas","contactos","oportunidades","formularios","ajustes","miembros","configuracion","modulos","registros","objetos","adjuntos","api","rpc","v1","mcp"]),ic=["box","boxes","package","folder","folder-open","file-text","clipboard-list","list-checks","calendar","calendar-days","clock","map-pin","truck","car","wrench","hammer","hard-hat","building","home","store","warehouse","factory","briefcase","shopping-cart","receipt","wallet","credit-card","piggy-bank","tag","tags","star","heart","flag","bookmark","user","users","graduation-cap","stethoscope","pill","utensils","coffee","shirt","camera","image","monitor","smartphone","server","database","key","shield","leaf","paw-print","dumbbell","ticket","gift","megaphone","mail","phone","message-square"],Ge=/^[a-z][a-z0-9_]{0,40}$/,yh=/^[a-z][a-z_]{1,30}$/,Tv=/^#[0-9a-fA-F]{6}$/,Mv=/^[a-z][a-z_]{0,29}$/,Iv=["texto","correo","telefono","codigo"],it=(e,o,t,n=!1)=>{if(typeof e!="string")throw i(`Falta ${o}.`);let r=e.trim();if(!n&&!r||r.length>t)throw i(`${o}: entre ${n?0:1} y ${t} caracteres.`);return r};Dv=/^sub_[a-z]{8}$/,Lv=["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","url","correo","telefono","duracion","porcentaje","valoracion","color","codigo","formula","hora","relacion","articulo","subtabla","resumen"],hh=20,gh=3,Nh=e=>e.tipo!=="subtabla"?0:1+Math.max(0,...(e.columnas??[]).map(o=>Nh(o))),bh=["nombre","referencia","codigo","precio","iva_pct"],tc=30;Fv=[["texto","texto_largo"],["texto_largo","texto"],["texto","seleccion"],["seleccion","texto"],["numero","importe"],["importe","numero"],["texto","correo"],["texto","telefono"],["texto","url"],["correo","texto"],["telefono","texto"],["url","texto"],["fecha","fecha_hora"],["texto","dispositivo"],["dispositivo","texto"]],Wv=(e,o)=>Fv.some(([t,n])=>t===e&&n===o),Bv=/^[a-z0-9][a-z0-9-]{0,59}$/;Ym=e=>e.tipo==="busqueda"||e.tipo==="resumen"||e.tipo==="formula"||e.tipo==="subtabla"||e.tipo==="boton"||e.tipo==="qr"||e.tipo==="archivo"||wh.includes(e.tipo)});function Oh(e){let o=Lo(),t=(e==="contacts"?Vv:Uv).map(([n,r])=>({clave:n,etiqueta:co(o,r),tipo:["correo","correo_facturacion"].includes(n)?"correo":["telefono","phone_number"].includes(n)?"telefono":["background","description"].includes(n)?"texto_largo":n==="website"?"url":"texto",obligatorio:n==="first_name"||n==="name",...Jv(e).has(n)?{}:{permisos:{administrador:"lectura",miembro:"lectura",lectura:"lectura"}}}));return{id:0,clave:`@${e}`,nombre:co(o,e==="contacts"?"Persona":"Empresa"),nombre_plural:co(o,e==="contacts"?"Personas":"Empresas"),descripcion:"",icono:e==="contacts"?"users":"building-2",estado:"publicado",campos:t}}var ki,Vv,Uv,Jv,Ah=f(()=>{mn();ki=[["address","Direcci\xF3n"],["zipcode","C\xF3digo postal"],["city","Ciudad"],["country","Pa\xEDs"]],Vv=[["first_name","Nombre"],["last_name","Apellidos"],["title","Cargo"],["correo","Correo"],["telefono","Tel\xE9fono"],...ki,["background","Contexto"],["nif","Identificador fiscal"],["pais_fiscal","Pa\xEDs fiscal"]],Uv=[["name","Nombre"],["phone_number","Tel\xE9fono"],["website","Web"],...ki,["description","Descripci\xF3n"],["persona_first_name","Nombre de la persona"],["correo_facturacion","Correo de facturaci\xF3n"],["tax_identifier","Identificador fiscal"],["razon_social","Raz\xF3n social"],["pais_fiscal","Pa\xEDs fiscal"]],Jv=e=>new Set(e==="contacts"?["first_name","last_name","title","telefono",...ki.map(([o])=>o),"background"]:["name","phone_number","website",...ki.map(([o])=>o),"description","persona_first_name"])});function Qr(e){let o=new Map(Jr(e)?Oh(e).campos.map(a=>[a.clave,a.etiqueta]):[]),t={ubicacion:"Ubicaci\xF3n",nif:"Identificador fiscal",birthday:"Fecha de nacimiento",iban:"IBAN",province:"Provincia",state_abbr:"Provincia",has_newsletter:"Comunicaciones"},n=(fm.find(a=>a.clave===e)?.campos??[]).map(a=>({...a,...o.has(a.clave)?{etiqueta:o.get(a.clave)}:Object.hasOwn(t,a.clave)?{etiqueta:co(Lo(),t[a.clave])}:{}})),r=Jr(e)?Xv(e).map(a=>({...a,etiqueta:co(Lo(),a.etiqueta),editable:!1,ordenable:!1,filtrable:!1,enTabla:!1})):[];return[...n,...r,...e==="companies"?Gv.map(a=>({...a,etiqueta:co(Lo(),a.etiqueta),editable:!1,ordenable:!1,filtrable:!1,enTabla:!1})):[]]}var Jr,Qv,Gv,Hv,Xv,wi=f(()=>{hm();Ah();mn();Jr=e=>e==="contacts"||e==="companies",Qv=[{clave:"nombre",tipo:"texto",etiqueta:"Nombre completo"},{clave:"direccion",tipo:"texto",etiqueta:"Direcci\xF3n completa"},{clave:"correo",tipo:"correo",etiqueta:"Primer correo"},{clave:"correo_trabajo",tipo:"correo",etiqueta:"Correo del trabajo"},{clave:"correo_personal",tipo:"correo",etiqueta:"Correo personal"},{clave:"telefono",tipo:"telefono",etiqueta:"Primer tel\xE9fono"},{clave:"telefono_trabajo",tipo:"telefono",etiqueta:"Tel\xE9fono del trabajo"},{clave:"telefono_personal",tipo:"telefono",etiqueta:"Tel\xE9fono personal"}],Gv=[{clave:"persona.first_name",tipo:"texto",etiqueta:"Nombre"},{clave:"persona.last_name",tipo:"texto",etiqueta:"Apellidos"},{clave:"persona.correo",tipo:"correo",etiqueta:"Correo"},{clave:"persona.telefono",tipo:"telefono",etiqueta:"Tel\xE9fono"}],Hv=[{clave:"persona_referencia_id",tipo:"relacion",etiqueta:"Persona de referencia",relacion:"contacts"},{clave:"persona_first_name",tipo:"texto",etiqueta:"Nombre de la persona"},{clave:"persona_last_name",tipo:"texto",etiqueta:"Apellidos de la persona"},{clave:"persona_correo",tipo:"correo",etiqueta:"Correo de la persona"},{clave:"persona_telefono",tipo:"telefono",etiqueta:"Tel\xE9fono de la persona"}],Xv=e=>[...Qv.filter(o=>e==="contacts"||["nombre","direccion"].includes(o.clave)),...e==="companies"?Hv:[]]});function xh(e,o,t){let n=(a,s,c,d)=>{if(a.tipo!=="busqueda"||a.archivado)return a;let u=`${c}.${a.clave}`;if(d.length>=2||d.includes(u))throw i(`\xAB${a.etiqueta}\xBB: solo se encadena una b\xFAsqueda a un nivel.`);let p=s.find(b=>b.clave===a.desde&&!b.archivado&&b.tipo==="relacion");if(!p?.relacion)return a;let m=p.relacion,h;if(m.startsWith("mod_")){let b=m.slice(4),y=b===o?e:t?.get(b);if(!y)return a;if(h=y.find(v=>v.clave===a.campo&&!v.archivado),!h)throw i(`\xAB${a.etiqueta}\xBB: el campo que trae ya no existe al otro lado.`);h=n(h,y,b,[...d,u])}else{let b=Qr(m).find(y=>y.clave===a.campo)??t?.get(`@${m}`)?.find(y=>y.clave===a.campo&&!y.archivado);if(!b&&Ee(a.campo)&&!t?.has(`@${m}`))return a;if(!b)throw i(`\xAB${a.etiqueta}\xBB: ese campo no existe en ${m}.`);h={clave:a.campo,etiqueta:a.etiqueta,tipo:b.tipo,...Array.isArray(b.opciones)?{opciones:b.opciones}:{},...b.relacion?{relacion:b.relacion}:{},..."origen"in b&&b.origen?{origen:b.origen}:{}}}if(h.tipo==="archivos")throw i(`\xAB${a.etiqueta}\xBB: los ficheros no se traen en una b\xFAsqueda.`);if(h.tipo==="secreto")throw i(`\xAB${a.etiqueta}\xBB: un secreto no se trae en una b\xFAsqueda.`);if(h.tipo==="formula")throw i(`\xAB${a.etiqueta}\xBB: una f\xF3rmula no se trae en una b\xFAsqueda.`);if(h.tipo==="busqueda"){let b=h.origen;if(!b)throw i(`\xAB${a.etiqueta}\xBB: el campo que trae no est\xE1 listo.`);if(b.encadenada)throw i(`\xAB${a.etiqueta}\xBB: solo se encadena una b\xFAsqueda a un nivel.`);return{...a,origen:{...b,encadenada:!0}}}return{...a,origen:{tipo:h.tipo,...h.opciones?{opciones:h.opciones}:{},...h.relacion?{relacion:h.relacion}:{}}}},r=e.map(a=>n(a,e,o,[]));return Yv(r),r}function Yv(e){let o=new Set(["texto","texto_largo","correo","telefono","url","codigo","numero","importe","porcentaje","fecha","fecha_hora","booleano"]);for(let t of e.filter(n=>!n.archivado&&n.tipo==="busqueda"&&n.siVacio)){let n=e.find(a=>a.clave===t.siVacio&&!a.archivado),r=a=>!e.find(s=>s.clave===a.desde)?.multiple;if(!n||n===t||n.tipo!=="busqueda"||n.siVacio||!r(t)||!r(n)||!t.origen||!n.origen||!o.has(t.origen.tipo)||t.origen.tipo!==n.origen.tipo||t.origen.encadenada||n.origen.encadenada)throw i("La alternativa necesita otra b\xFAsqueda escalar del mismo tipo, sin cadenas.")}}var Ch=f(()=>{Br();q();wi()});function Ee(e){if(typeof e!="string"||!/^datos\.[a-z][a-z0-9_]{0,40}$/.test(e))return null;let o=e.slice(6);return o==="tipos"?null:o}function af(e,o,t){let n=r=>{let a=Object.hasOwn(o,r.campo)?Ee(o[r.campo]):null;if(!a)throw i("La condici\xF3n del campo propio necesita otro campo propio de la misma ra\xEDz.");return{...r,campo:a}};return e.filter(r=>!r.archivado&&Object.hasOwn(o,r.clave)&&Ee(o[r.clave])).map(r=>{if(r.tipo==="relacion"&&(Object.keys(r.copiar??{}).length||r.mostrarTareasEnFichaRelacionada||r.alBorrar&&r.alBorrar!=="avisar")||r.porDefecto||r.depende||r.completarDesde||r.alMarcar||r.embudo||r.transiciones||r.opciones?.some(u=>u.requisito||u.pide?.length||u.limiteDias!==void 0||u.aprobacion))throw i("El campo propio necesita conservar sus reglas antes de convertir la ra\xEDz.");let s=[{campo:"tipos",op:"igual",valor:t},...(r.visibleSi??[]).map(n)];if(s.length>10)throw i("El campo propio supera las diez condiciones al a\xF1adir su tipo.");let c=r.tipo==="busqueda"?Ee(o[r.desde??""]):null,d=r.siVacio?Ee(o[r.siVacio]):null;if(r.tipo==="busqueda"&&(!c||r.siVacio&&!d))throw i("La b\xFAsqueda propia necesita relaciones y alternativas propias de la misma ra\xEDz.");return{...structuredClone(r),...c?{desde:c}:{},...d?{siVacio:d}:{},clave:Ee(o[r.clave]),visibleSi:s,...r.obligatorioSi?{obligatorioSi:r.obligatorioSi.map(n)}:{}}})}var Br=f(()=>{q()});function jh(e,o){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new z(400,"peticion_invalida",`\xAB${o}\xBB: permisos no v\xE1lidos.`);let t={};for(let[n,r]of Object.entries(e))if(!(r==null||r==="normal")){if(!ey(n))throw new z(400,"peticion_invalida",`\xAB${o}\xBB: el papel \xAB${n.slice(0,30)}\xBB no se puede restringir.`);if(!Kv.includes(r))throw new z(400,"peticion_invalida",`\xAB${o}\xBB: nivel de permiso no v\xE1lido.`);t[n]=r}return Object.keys(t).length?t:void 0}var Kv,Zv,ey,PL,sc,TL,Sh=f(()=>{ci();q();Kv=["oculto","lectura"],Zv=["administrador","miembro","lectura"],ey=e=>Zv.includes(e)||/^p_[a-z]{1,12}$/.test(e),PL=A`coalesce(current_setting('app.extension', true), '') <> ''`,sc=class extends Map{get(){return"no"}},TL=new sc});function Eh(e){if(!e||typeof e!="object"||Array.isArray(e))throw i("F\xF3rmula proyectada no v\xE1lida.");let o=e;if(Object.keys(o).some(a=>!["expresion","campos"].includes(a))||typeof o.expresion!="string"||o.expresion.length>2e3||!Array.isArray(o.campos)||o.campos.length>40)throw i("F\xF3rmula proyectada no v\xE1lida.");let t=["texto","texto_largo","correo","telefono","url","codigo","color","numero","importe","duracion","porcentaje","valoracion","fecha","fecha_hora","booleano","seleccion","ubicacion","formula"],n=new Set,r=o.campos.map(a=>{if(!a||typeof a!="object"||typeof a.clave!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(a.clave)||n.has(a.clave)||typeof a.etiqueta!="string"||a.etiqueta.length>80||!t.includes(a.tipo)||a.tipo==="formula"&&(typeof a.formula!="string"||a.formula.length>2e3))throw i("F\xF3rmula proyectada no v\xE1lida.");return n.add(a.clave),{clave:a.clave,etiqueta:a.etiqueta,tipo:a.tipo,...a.tipo==="formula"?{formula:a.formula}:{}}});return{expresion:o.expresion,campos:r}}var qh=f(()=>{q()});function Rh(e){if(!e||typeof e!="object"||Array.isArray(e))throw i("Resumen proyectado no v\xE1lido.");let o=e;if(Object.keys(o).some(t=>!["fuente","tipo","via","calculo","campo","peso","filtro"].includes(t))||o.tipo!==void 0&&(!["contacts","companies"].includes(o.fuente)||typeof o.tipo!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(o.tipo))||typeof o.fuente!="string"||!/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/.test(o.fuente)||!nc.includes(o.calculo)||[o.via,...o.calculo!=="recuento"?[o.campo]:[],...o.calculo==="media_ponderada"?[o.peso]:[]].some(t=>typeof t!="string"||!(/^[a-z][a-z0-9_]{0,40}$/.test(t)||["contacts","companies"].includes(o.fuente)&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(t))))throw i("Resumen proyectado no v\xE1lido.");Yr(o.filtro,"Resumen")}var kh=f(()=>{q();Kr()});function Ph(e,o){if(!Array.isArray(e)||!e.length||e.length>100||e.some(t=>!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(n=>!["campo","es","etiqueta","valor"].includes(n))||typeof t.valor!="string"||t.valor.length>100||(t.etiqueta!==void 0?typeof t.etiqueta!="string"||!t.etiqueta||t.etiqueta.length>60||t.campo!==void 0||t.es!==void 0:typeof t.campo!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(t.campo)||typeof t.es!="string"||t.es.length>100))||o!==void 0&&(typeof o!="string"||o.length>100))throw i("Casos de proyecci\xF3n no v\xE1lidos.")}var Th=f(()=>{q()});var Mh,Ih=f(()=>{Mh=/^funciones\.[a-z0-9][a-z0-9-]{0,59}\.[a-z][a-z0-9_]{0,40}$/});function ir(e){if(e===void 0)return;if(JSON.stringify(e).length>6e4)throw i("La fuente combinada es demasiado grande.");if(!Array.isArray(e)||e.length<1||e.length>4)throw i("Una fuente combinada necesita de uno a cuatro or\xEDgenes.");let o=new Set;return e.map(t=>{if(!Mo(t)||Object.keys(t).some(r=>!["fuente","filtro","campos"].includes(r))||typeof t.fuente!="string"||!ty.test(t.fuente)||o.has(t.fuente))throw i("Origen combinado no v\xE1lido o repetido.");if(o.add(t.fuente),t.filtro!==void 0&&(!Mo(t.filtro)||JSON.stringify(t.filtro).length>4e3))throw i("Filtro de origen no v\xE1lido.");if(!Mo(t.campos)||Object.keys(t.campos).length>40)throw i("Proyecci\xF3n de origen no v\xE1lida.");let n=Object.fromEntries(Object.entries(t.campos).map(([r,a])=>{if(!oy.test(r)||["id","objeto"].includes(r)||!Mo(a)||Object.keys(a).some(c=>!["resumen","formula","permiso","casos","defecto","campo","soloFiltro","valor","alternativas","conversiones","condicion","equivalencias","etiqueta","opciones"].includes(c))||["campo","valor","alternativas","condicion","casos","resumen","formula"].filter(c=>Object.hasOwn(a,c)).length!==1||a.campo!==void 0&&(typeof a.campo!="string"||a.campo.length>125)||Object.hasOwn(a,"valor")&&a.valor!==null&&!["string","number","boolean"].includes(typeof a.valor)||a.alternativas!==void 0&&(!Array.isArray(a.alternativas)||a.alternativas.length!==2||a.alternativas.some(c=>typeof c!="string"||c.length>125))||a.condicion!==void 0&&(!Mo(a.condicion)||JSON.stringify(a.condicion).length>4e3)||a.conversiones!==void 0&&(!Mo(a.conversiones)||!Array.isArray(a.alternativas)||Object.entries(a.conversiones).some(([c,d])=>!a.alternativas.includes(c)||!Mo(d)||Object.keys(d).length>100||Object.values(d).some(u=>typeof u!="string")))||a.permiso!==void 0&&(typeof a.permiso!="string"||!Mh.test(a.permiso)||!["contacts","companies"].includes(t.fuente)||!a.formula&&!a.resumen)||a.soloFiltro!==void 0&&typeof a.soloFiltro!="boolean"||a.etiqueta!==void 0&&(typeof a.etiqueta!="string"||a.etiqueta.length>80)||a.opciones!==void 0&&(!Mo(a.opciones)||Object.keys(a.opciones).length>100||Object.values(a.opciones).some(c=>typeof c!="string"))||a.equivalencias!==void 0&&(!Mo(a.equivalencias)||!a.campo||Object.keys(a.equivalencias).length>100||Object.values(a.equivalencias).some(c=>typeof c!="string")))throw i("Campo de proyecci\xF3n no v\xE1lido.");a.resumen!==void 0&&Rh(a.resumen);let s=a.formula===void 0?void 0:Eh(a.formula);if(a.casos!==void 0)Ph(a.casos,a.defecto);else if(a.defecto!==void 0)throw i("El defecto necesita casos de proyecci\xF3n.");return[r,{...structuredClone(a),...s?{formula:s}:{}}]}));return{fuente:t.fuente,campos:n,...t.filtro?{filtro:structuredClone(t.filtro)}:{}}})}var Mo,oy,ty,Pi=f(()=>{qh();kh();Th();q();Ih();Mo=e=>!!e&&typeof e=="object"&&!Array.isArray(e),oy=/^[a-z][a-z0-9_]{0,40}$/,ty=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/});function zh(e){let o=_e(e,"definici\xF3n");ze(o,["titulo","fuente","origenes","metrica","agrupar","dividir","filtro","periodo","grafico","top","comparar","meta","tendencia","ejes_burbujas",...Dh],"definici\xF3n");let t=qe(o.fuente,"fuente",60),n=ir(o.origenes);if(t==="combinada"!=!!n)throw i("La fuente combinada necesita sus or\xEDgenes.");if(t!=="combinada"&&!lc.includes(t)&&!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(t))throw i("\xABfuente\xBB no v\xE1lida.");let r=_e(o.metrica,"metrica");ze(r,["tipo","campo","por","filtro_a","filtro_b"],"metrica");let a=He(r.tipo,cc,"metrica.tipo"),s={tipo:a,...r.campo!==void 0?{campo:qe(r.campo,"metrica.campo",60)}:{},...r.por!==void 0?{por:qe(r.por,"metrica.por",60)}:{},...r.filtro_a!==void 0&&r.filtro_a!==null?{filtro_a:_e(r.filtro_a,"metrica.filtro_a")}:{},...r.filtro_b!==void 0&&r.filtro_b!==null?{filtro_b:_e(r.filtro_b,"metrica.filtro_b")}:{}};if(["suma","media","min","max","minimo","maximo","mediana"].includes(a)&&!s.campo)throw i("Esa m\xE9trica necesita un campo.");if(a==="tasa_conversion"&&(r.filtro_a===void 0||r.filtro_b===void 0))throw i("\xABtasa_conversion\xBB necesita \xABfiltro_a\xBB y \xABfiltro_b\xBB.");if((a==="media_por"||a==="valor_medio_por")&&!s.por)throw i("\xABmedia_por\xBB necesita indicar el campo \xABpor\xBB para dividir.");let c;if(o.agrupar!==void 0&&o.agrupar!==null){let R=_e(o.agrupar,"agrupar");ze(R,["campo","paso"],"agrupar"),c={campo:qe(R.campo,"agrupar.campo",60),...R.paso!==void 0?{paso:He(R.paso,ar,"agrupar.paso")}:{}}}let d;if(o.dividir!==void 0&&o.dividir!==null){let R=_e(o.dividir,"dividir");ze(R,["campo","paso"],"dividir"),d={campo:qe(R.campo,"dividir.campo",60),...R.paso!==void 0?{paso:He(R.paso,ar,"dividir.paso")}:{}}}if(d&&!c)throw i("\xABDividir por\xBB solo se puede usar si se agrupa.");if(c&&d&&c.campo===d.campo)throw i("No se puede agrupar y dividir por el mismo campo.");let u;if(o.meta!==void 0&&o.meta!==null){if(typeof o.meta!="number"||Number.isNaN(o.meta)||o.meta<=0)throw i("\xABmeta\xBB: n\xFAmero mayor que 0.");u=o.meta}let p=o.periodo!==void 0&&o.periodo!==null?uc(o.periodo):void 0,m=He(o.grafico,ry,"grafico"),h={},b={doble_eje:m==="combinado",etiquetas:["barras","barras_horizontales","barras_100","barras_apiladas","barras_agrupadas","cascada","dona","tarta","embudo"].includes(m),zoom:!!c?.paso&&["barras","barras_100","barras_apiladas","barras_agrupadas","lineas","area","area_apilada","area_100","varias_lineas","combinado","cascada"].includes(m),escalonada:m==="lineas"||m==="varias_lineas"};for(let R of Dh){let F=o[R];if(F!==void 0){if(typeof F!="boolean")throw i(`\xAB${R}\xBB: s\xED o no.`);if(!b[R])throw i(`\xAB${R}\xBB no se admite en este gr\xE1fico.`);h[R]=F}}let y;if(m==="burbujas"){let R=_e(o.ejes_burbujas,"ejes_burbujas");ze(R,["x","z"],"ejes_burbujas"),y={x:qe(R.x,"ejes_burbujas.x",60),z:qe(R.z,"ejes_burbujas.z",60)}}else if(o.ejes_burbujas!==void 0)throw i("\xABejes_burbujas\xBB solo se usa en burbujas.");let v=["numero","medidor","numero_tendencia"],w=["cascada","treemap","barras_radiales","burbujas","barras","barras_horizontales","lineas","area","dona","tabla","embudo","tarta","radar","dispersion"],N=["sankey","area_apilada","area_100","barras_100","barras_apiladas","barras_agrupadas","varias_lineas","tabla_dinamica","mapa_calor","combinado"];if(v.includes(m)){if(c)throw i("Un n\xFAmero no se agrupa.");if(d)throw i("Un n\xFAmero no se divide.");if(m==="medidor"&&u===void 0)throw i("El medidor necesita una \xABmeta\xBB num\xE9rica.");if(m==="numero_tendencia"&&!p)throw i("\xABnumero_tendencia\xBB necesita un periodo.")}else if(w.includes(m)){if(!c)throw i("Ese gr\xE1fico necesita \xABagrupar\xBB.");if(d)throw i("Ese gr\xE1fico no admite \xABdividir por\xBB.")}else if(N.includes(m)){if(!c)throw i("Ese gr\xE1fico necesita \xABagrupar\xBB.");if(!d)throw i("Ese gr\xE1fico necesita \xABdividir por\xBB un segundo campo.")}if((m==="area_apilada"||m==="area_100")&&!c?.paso)throw i("Las \xE1reas apiladas requieren agrupar por fecha.");if(o.tendencia!==void 0&&typeof o.tendencia!="boolean")throw i("\xABtendencia\xBB: s\xED o no.");if(o.tendencia&&(m!=="tabla"||!c?.paso))throw i("\xABtendencia\xBB requiere una tabla agrupada por fecha.");if(o.top!==void 0&&(!Number.isSafeInteger(o.top)||o.top<1||o.top>Lh))throw i(`\xABtop\xBB: de 1 a ${Lh}.`);let j=o.comparar==null||typeof o.comparar=="boolean"?o.comparar:He(o.comparar,ny,"comparar");if(typeof j=="string"&&m!=="numero"&&m!=="numero_tendencia"&&(!["barras","lineas","area","varias_lineas"].includes(m)||!c?.paso))throw i("\xABcomparar\xBB requiere agrupar por fecha en un gr\xE1fico temporal.");if(o.comparar&&!p)throw i("Para comparar hace falta un periodo.");if(o.comparar&&p?.proximos)throw i("\xABproximos\xBB no se compara (no hay periodo anterior).");if(typeof j=="string"&&p&&!p.ultimos&&(!p.desde||!p.hasta))throw i("Para comparar hacen falta las dos fechas del periodo.");if(o.comparar&&p?.preset)throw i("\xABpreset\xBB no se compara (todav\xEDa no se ha acabado).");let S=o.filtro===void 0||o.filtro===null?void 0:_e(o.filtro,"filtro");if(S&&JSON.stringify(S).length>4e3)throw i("\xABfiltro\xBB demasiado grande.");return{titulo:qe(o.titulo??"","titulo"),fuente:t,...n?{origenes:n}:{},metrica:s,...y?{ejes_burbujas:y}:{},...c?{agrupar:c}:{},...d?{dividir:d}:{},...u!==void 0?{meta:u}:{},...S?{filtro:S}:{},...p?{periodo:p}:{},grafico:m,...h,...o.top!==void 0?{top:o.top}:{},...j||j===null?{comparar:j}:{},...o.tendencia?{tendencia:!0}:{}}}function uc(e){let o=_e(e,"periodo");ze(o,["campo","ultimos","proximos","preset","desde","hasta"],"periodo");let t={campo:qe(o.campo,"periodo.campo",60)};if(o.preset!==void 0&&(t.preset=He(o.preset,iy,"periodo.preset")),o.ultimos!==void 0){let r=_e(o.ultimos,"periodo.ultimos");if(ze(r,["n","unidad"],"periodo.ultimos"),!Number.isSafeInteger(r.n)||r.n<1||r.n>3660)throw i("\xABperiodo.ultimos.n\xBB no v\xE1lido.");t.ultimos={n:r.n,unidad:He(r.unidad,ar,"periodo.ultimos.unidad")}}for(let r of["desde","hasta"])if(o[r]!==void 0){if(typeof o[r]!="string"||!ay.test(o[r])||Number.isNaN(Date.parse(o[r])))throw i(`\xABperiodo.${r}\xBB: AAAA-MM-DD.`);t[r]=o[r]}if(o.proximos!==void 0){let r=_e(o.proximos,"periodo.proximos");if(ze(r,["n","unidad"],"periodo.proximos"),!Number.isSafeInteger(r.n)||r.n<1||r.n>3660)throw i("\xABperiodo.proximos.n\xBB no v\xE1lido.");t.proximos={n:r.n,unidad:He(r.unidad,ar,"periodo.proximos.unidad")}}let n=[!!t.ultimos,!!t.proximos,!!t.preset,!!(t.desde||t.hasta)].filter(Boolean).length;if(!n)throw i("\xABperiodo\xBB: di \xABultimos\xBB, \xABproximos\xBB, \xABpreset\xBB o \xABdesde\xBB/\xABhasta\xBB.");if(n>1)throw i("\xABperiodo\xBB: solo una de \xABultimos\xBB, \xABproximos\xBB, \xABpreset\xBB o \xABdesde\xBB/\xABhasta\xBB.");return t}var cc,ry,ar,lc,ny,Dh,iy,Lh,ay,_e,ze,He,qe,dc=f(()=>{Pi();q();cc=["recuento","suma","media","min","max","minimo","maximo","mediana","porcentaje_total","acumulado","tasa_conversion","media_por","valor_medio_por"],ry=["numero","cascada","treemap","sankey","barras_radiales","burbujas","barras","lineas","dona","tabla","barras_horizontales","barras_100","barras_apiladas","barras_agrupadas","area","area_apilada","area_100","varias_lineas","embudo","medidor","numero_tendencia","tabla_dinamica","mapa_calor","tarta","radar","dispersion","combinado"],ar=["dia","semana","mes","anio"],lc=["companies","contacts","deals","tareas","proyectos"],ny=["anterior","anio_anterior"],Dh=["escalonada","zoom","etiquetas","doble_eje"],iy=["hoy","semana","mes","trimestre","anio"],Lh=50,ay=/^\d{4}-\d{2}-\d{2}$/,_e=(e,o)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw i(`\xAB${o}\xBB tiene que ser un objeto.`);return e},ze=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`\xAB${t}\xBB: clave no admitida \xAB${n.slice(0,40)}\xBB.`)},He=(e,o,t)=>{if(typeof e!="string"||!o.includes(e))throw i(`\xAB${t}\xBB no v\xE1lido.`);return e},qe=(e,o,t=80)=>{if(typeof e!="string"||e.length>t)throw i(`\xAB${o}\xBB no v\xE1lido.`);return e}});var pc,Fh=f(()=>{pc=["nada","recientes","vistas"]});function Wh(e,o,t){if(e===void 0)return[];if(!Array.isArray(e)||e.length>o.length)throw i("Fuentes de m\xF3dulo no v\xE1lidas.");let n=new Set;return e.map(r=>{if(!mc(r)||typeof r.modulo!="string"||n.has(r.modulo)||typeof r.conexion!="string"||!t.some(d=>d.clave===r.conexion&&d.tipo==="api")||typeof r.operacion!="string"||!/^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$/.test(r.operacion)||r.filas!==""&&!Ti(r.filas)||!mc(r.mapeo))throw i("La fuente necesita un m\xF3dulo, una conexi\xF3n API, una operaci\xF3n y un mapeo.");let a=o.find(d=>d.clave===r.modulo),s=Object.entries(r.mapeo);if(!a||a.personas||!s.length||s.some(([d,u])=>!a.campos.some(p=>p.clave===d&&cy(p))||!Ti(u)))throw i("La fuente debe mapear campos de datos de un m\xF3dulo propio.");n.add(r.modulo);let c={modulo:r.modulo,conexion:r.conexion,operacion:r.operacion,filas:r.filas,mapeo:Object.fromEntries(s)};if(r.modo==="vivo")return{...c,modo:r.modo};if(r.modo!=="espejo"||typeof r.minutos!="number"||!Number.isInteger(r.minutos)||r.minutos<5||r.minutos>10080||!Ti(r.id_externo)||!mc(r.cursor)||!Ti(r.cursor.ruta)||typeof r.cursor.parametro!="string"||!/^[a-zA-Z_][a-zA-Z0-9_.-]{0,79}$/.test(r.cursor.parametro))throw i("El espejo necesita una clave externa, un cursor y un intervalo entre 5 minutos y 7 d\xEDas.");return{...c,modo:r.modo,minutos:r.minutos,id_externo:r.id_externo,cursor:{ruta:r.cursor.ruta,parametro:r.cursor.parametro}}})}var sy,Ti,mc,cy,Bh=f(()=>{q();sy=new Set(["texto","texto_largo","correo","telefono","codigo","numero","importe","fecha","fecha_hora","booleano","seleccion"]),Ti=e=>typeof e=="string"&&e.length<=160&&/^[a-zA-Z_][a-zA-Z0-9_-]*(\.[a-zA-Z_][a-zA-Z0-9_-]*){0,7}$/.test(e),mc=e=>!!e&&typeof e=="object"&&!Array.isArray(e),cy=e=>!e.archivado&&sy.has(e.tipo)});function Vh(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>20)throw i("La soluci\xF3n admite hasta 20 conexiones.");let o=new Set;return e.map(t=>{if(!ly(t)||typeof t.clave!="string"||!/^[a-z][a-z0-9_]{0,39}$/.test(t.clave)||["constructor","prototype"].includes(t.clave)||o.has(t.clave)||typeof t.nombre!="string"||!t.nombre.trim()||t.nombre.length>120||t.tipo!=="api"&&t.tipo!=="mcp")throw i("Requisito de conexi\xF3n no v\xE1lido.");return o.add(t.clave),{clave:t.clave,nombre:t.nombre.trim(),tipo:t.tipo}})}var ly,Uh=f(()=>{q();ly=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});function Mi(e){return typeof e=="number"?Number.isInteger(e)&&e>=1&&e<=2147483647:typeof e=="string"&&e.length<=120&&Jh.test(e)}function Qh(e,o){let t=c=>Jh.exec(typeof c=="number"?`${c}.0.0`:c),n=t(e),r=t(o);for(let c=1;c<=3;c++){let d=BigInt(n[c])-BigInt(r[c]);if(d)return d>0?1:-1}if(!n[4]||!r[4])return+!n[4]-+!r[4];let a=n[4].split("."),s=r[4].split(".");for(let c=0;c<Math.min(a.length,s.length);c++){let d=a[c],u=s[c];if(d===u)continue;let p=/^\d+$/.test(d),m=/^\d+$/.test(u);return p&&m?BigInt(d)>BigInt(u)?1:-1:p!==m?p?-1:1:d>u?1:-1}return a.length-s.length}var Jh,fc=f(()=>{Jh=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][\da-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][\da-zA-Z-]*))*))?(?:\+([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?$/});function Gh(e,o){if(e===void 0)return;if(!hc(e)||Object.keys(e).some(r=>r!=="desde"&&r!=="pasos")||!Mi(e.desde)||Qh(e.desde,o)>=0||!Array.isArray(e.pasos)||!e.pasos.length||e.pasos.length>50)throw i("La migraci\xF3n necesita una versi\xF3n anterior y entre 1 y 50 pasos.");let t=new Set,n=e.pasos.map(r=>{if(!hc(r)||Object.keys(r).some(m=>!["tipo","modulo","origen","destino","conversion","equivalencias"].includes(m))||r.tipo!=="renombrar"&&r.tipo!=="convertir"&&r.tipo!=="mover"||!gc(r.modulo)||!gc(r.origen)||!gc(r.destino))throw i("Paso de migraci\xF3n inv\xE1lido.");let{tipo:a,modulo:s,origen:c,destino:d,conversion:u,equivalencias:p}=r;if(a==="convertir"&&(typeof u!="string"||!uy.has(u)))throw i("Conversi\xF3n de migraci\xF3n desconocida.");if(a!=="convertir"&&(u!==void 0||c===d))throw i("El paso necesita dos campos distintos.");if(u==="seleccion"?!hc(p)||!Object.keys(p).length||Object.values(p).some(m=>typeof m!="string"||!m):p!==void 0)throw i("La conversi\xF3n a selecci\xF3n necesita una tabla de equivalencias.");for(let m of new Set([c,d])){let h=`${s}:${m}`;if(t.has(h))throw i("Cada campo puede participar en un solo paso por versi\xF3n.");t.add(h)}return{tipo:a,modulo:s,origen:c,destino:d,...u?{conversion:u}:{},...p?{equivalencias:p}:{}}});return{desde:e.desde,pasos:n}}var hc,gc,uy,Hh=f(()=>{q();fc();hc=e=>!!e&&typeof e=="object"&&!Array.isArray(e),gc=e=>typeof e=="string"&&/^[a-z][a-z0-9_]{0,59}$/.test(e),uy=new Set(["numero","seleccion","fecha"])});function Xh(e){let o=sr(e,["version","origen","entidades"]);if(o.version!==1)throw i("Perfil relacional inv\xE1lido.");let t=en(o.entidades,60).map(r=>{let a=sr(r,["clave","destino","clave_externa","campos","referencias","procedencia","responsable","tipos","tiposColumna","acl","archivos"]);if(typeof a.destino!="string"||!(["contacts","companies","deals"].includes(a.destino)||/^mod_[a-z][a-z0-9_]{0,40}$/.test(a.destino)))throw i("Perfil relacional inv\xE1lido.");let s=Object.fromEntries(Object.entries(sr(a.campos)).map(([b,y])=>(bc(b),[b,cr(y)])));if(Object.keys(s).length>100)throw i("Perfil relacional inv\xE1lido.");let c=en(a.referencias??[],30).map(b=>{let y=sr(b,["campo","entidad","clave","obligatoria"]);if(y.obligatoria!==void 0&&typeof y.obligatoria!="boolean")throw i("Perfil relacional inv\xE1lido.");return{campo:bc(y.campo),entidad:Ii(y.entidad),clave:wc(y.clave),obligatoria:y.obligatoria===!0}}),d=a.archivos===void 0?void 0:en(a.archivos,20).map(b=>{let y=sr(b,["campo","columna","obligatorio"]);if(y.obligatorio!==void 0&&typeof y.obligatorio!="boolean")throw i("Perfil relacional inv\xE1lido.");return{campo:bc(y.campo),columna:cr(y.columna),obligatorio:y.obligatorio===!0}});if(d?.length&&!a.destino.startsWith("mod_"))throw i("Perfil relacional inv\xE1lido.");let u=[...(d??[]).map(b=>b.campo),...Object.keys(s),...c.map(b=>b.campo)];if(new Set(u).size!==u.length)throw i("Perfil relacional inv\xE1lido.");let p=a.procedencia===void 0?void 0:Object.fromEntries(Object.entries(sr(a.procedencia,["autor","creado","actualizado"])).map(([b,y])=>[b,cr(y)])),m=a.responsable===void 0?void 0:wc(a.responsable),h=a.tipos===void 0?void 0:en(a.tipos,20).map(b=>{if(typeof b!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(b))throw i("Perfil relacional inv\xE1lido.");return b});if(h&&!["contacts","companies"].includes(a.destino))throw i("Perfil relacional inv\xE1lido.");if(a.tiposColumna!==void 0&&(!h?.length||new Set(h).size!==h.length))throw i("Perfil relacional inv\xE1lido.");return{clave:Ii(a.clave),...a.acl!==void 0?{acl:cr(a.acl)}:{},...d?{archivos:d}:{},destino:a.destino,...p?{procedencia:p}:{},...m?{responsable:m}:{},...h?{tipos:h}:{},...a.tiposColumna!==void 0?{tiposColumna:cr(a.tiposColumna)}:{},clave_externa:wc(a.clave_externa),campos:s,referencias:c}}),n=new Map(t.map(r=>[r.clave,r]));if(!t.length||n.size!==t.length||t.some(r=>r.referencias.some(a=>!n.has(a.entidad)||n.get(a.entidad).clave_externa.length!==a.clave.length)))throw i("Perfil relacional inv\xE1lido.");return{version:1,origen:Ii(o.origen),entidades:t}}var Ii,bc,cr,sr,en,wc,Yh=f(()=>{q();Ii=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,60}$/.test(e))throw i("Perfil relacional inv\xE1lido.");return e},bc=e=>{let o=typeof e=="string"&&/^datos\.[a-z][a-z0-9_]{0,60}$/.test(e)?e:Ii(e);if(["id","sales_id","espacio_id","modulo_id","creado_por","actualizado_por","responsable_id"].includes(o))throw i("Perfil relacional inv\xE1lido.");return o},cr=e=>{if(typeof e!="string"||!/^[a-zA-Z][a-zA-Z0-9_]{0,79}$/.test(e)||/password|passwd|token|(^|_)pin($|_)|secret/i.test(e)||["constructor","prototype","__proto__"].includes(e))throw i("Perfil relacional inv\xE1lido.");return e},sr=(e,o)=>{if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(t=>["__proto__","constructor","prototype"].includes(t)||o&&!o.includes(t)))throw i("Perfil relacional inv\xE1lido.");return e},en=(e,o)=>{if(!Array.isArray(e)||e.length>o)throw i("Perfil relacional inv\xE1lido.");return e},wc=e=>{let o=en(e,3).map(cr);if(!o.length||new Set(o).size!==o.length)throw i("Perfil relacional inv\xE1lido.");return o}});function Kh(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>30)throw i("Perfiles de importaci\xF3n inv\xE1lidos.");let o=new Set;return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(r=>!["clave","perfil"].includes(r)))throw i("Perfiles de importaci\xF3n inv\xE1lidos.");let n=t;if(typeof n.clave!="string"||!/^[a-z][a-z0-9_]{0,60}$/.test(n.clave)||o.has(n.clave))throw i("Perfiles de importaci\xF3n inv\xE1lidos.");return o.add(n.clave),{clave:n.clave,perfil:Xh(n.perfil)}})}var Zh=f(()=>{q();Yh()});function eg(e,o){if(o==null||o==="")return null;if(!["contacts","companies"].includes(e)||typeof o!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(o))throw i("El \xE1mbito de tipo necesita Personas o Empresas y una clave v\xE1lida.");return o}var og=f(()=>{q()});function ag(e,o){if(e===null)return null;if(!Io(e))throw i("La disposici\xF3n no es v\xE1lida.");if(!hy.test(o))throw i("Esta tabla no admite widgets.");for(let d of Object.keys(e))if(d!=="zonas"&&d!=="widgets")throw i("La disposici\xF3n no es v\xE1lida.");if(!Io(e.zonas))throw ig();let t=e.zonas,n=Io(e.widgets)?e.widgets:{};for(let d of Object.keys(t))if(!tg.includes(d))throw i("Zona no v\xE1lida.");let r={},a=new Set;for(let d of tg){let u=t[d]??[];if(!Array.isArray(u))throw i("Zona no v\xE1lida.");r[d]=u.map(p=>{if(typeof p!="string"||p!==vc&&!fy.test(p))throw i("Bloque no v\xE1lido.");if(a.has(p))throw i("Un bloque solo puede estar en un sitio.");return a.add(p),p})}if(!a.has(vc))throw ig();if(r.arriba.length>ng)throw i(`Arriba caben como mucho ${ng} bloques.`);let s={};for(let[d,u]of Object.entries(n)){if(!a.has(d))continue;if(!Io(u))throw i("Widget no v\xE1lido.");let p=zh(u.definicion);if(u.via!==void 0&&(typeof u.via!="string"||!gy.test(u.via)))throw i("\xABvia\xBB no v\xE1lida.");if(u.via===void 0&&p.fuente!==o)throw i("Un widget de esta tabla solo mide esta tabla o sus relaciones.");s[d]={definicion:p,seguir_filtros:u.seguir_filtros!==!1,...u.via!==void 0?{via:u.via}:{}}}for(let d of a)if(d!==vc&&!s[d])throw i("Falta la definici\xF3n de un widget.");if(Object.keys(s).length>rg)throw i(`Como mucho ${rg} widgets por vista.`);let c={zonas:r,widgets:s};if(JSON.stringify(c).length>6e4)throw i("La disposici\xF3n es demasiado grande.");return c}function by(e){if(!(e==null||e==="")){if(typeof e!="string"||!/^[a-z0-9][a-z0-9_:.-]{0,79}$/.test(e))throw i("El \xE1mbito de la vista no es v\xE1lido.");return e}}function sg(e){if(!Io(e))throw i("La vista no es v\xE1lida.");let o=Io(e.pref)?Object.fromEntries(Object.entries(e.pref).filter(([d])=>py.has(d))):{};if(o.vistaOrigen!==void 0&&(typeof o.vistaOrigen!="string"||o.vistaOrigen.length>160))throw i("La vista de origen no es v\xE1lida.");if(o.vista!==void 0&&!my.has(String(o.vista)))throw i("El tipo de vista no es v\xE1lido.");let t=Io(e.filtros)?e.filtros:{};if(Object.keys(t).length>40||Object.keys(t).some(d=>!/^[a-zA-Z0-9_@.:-]{1,80}$/.test(d)))throw i("Los filtros de la vista no son v\xE1lidos.");let n=null;if(Io(e.orden)){let{field:d,order:u}=e.orden;if(typeof d!="string"||!/^[a-zA-Z0-9_.]{1,80}(,[a-zA-Z0-9_.]{1,80}){0,2}$/.test(d)||typeof u!="string"||!/^(ASC|DESC)(,(ASC|DESC)){0,2}$/.test(u))throw i("El orden de la vista no es v\xE1lido.");n={field:d,order:u}}let r=e.origenes===void 0?void 0:ir(e.origenes),a;if(r||e.columnasCalculadas!==void 0){if(!r||r.length!==1||!["contacts","companies"].includes(r[0].fuente)||!Io(e.columnasCalculadas)||Object.keys(e.columnasCalculadas).length>40||Object.entries(e.columnasCalculadas).some(([d,u])=>!/^calc_[a-f0-9]{24}$/.test(d)||typeof u!="string"||!Object.hasOwn(r[0].campos,u)))throw i("Columnas calculadas de vista no v\xE1lidas.");a=e.columnasCalculadas}let s=by(e.ambito),c={pref:o,filtros:t,orden:n,...s?{ambito:s}:{},...r?{origenes:r,columnasCalculadas:a}:{}};if(JSON.stringify(c).length>3e4)throw i("La vista es demasiado grande.");return c}var dy,py,my,tg,vc,fy,rg,ng,hy,gy,ig,Io,cg=f(()=>{Pi();q();dc();dy=/^(contacts|companies|deals|tareas|proyectos|mod_(?!sub_)[a-z][a-z0-9_]{1,40})$/,py=new Set(["vistaOrigen","vista","visibles","orden","anchos","fijadas","calculos","agrupar","grupo","vistas","separar"]),my=new Set(["tabla","lista","kanban","calendario","galeria","linea","mapa"]),tg=["arriba","izquierda","centro","derecha","abajo"],vc="tabla",fy=/^w_[a-z0-9]{1,24}$/,rg=24,ng=6,hy=dy,gy=/^[a-z][a-z0-9_]{0,59}$/,ig=()=>new z(400,"tabla_obligatoria","La tabla no se puede quitar de la vista: mu\xE9vela, pero d\xE9jala.");Io=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function lg(e){let o=new Set,t=n=>{typeof n=="string"&&n.startsWith("mod_")&&o.add(n.slice(4))};if(yc(e.personas)&&t(e.personas.modulo),Array.isArray(e.secciones)){for(let n of e.secciones)if(yc(n)&&(t(n.modulo),Array.isArray(n.camino)))for(let r of n.camino)yc(r)&&t(r.modulo)}return o}var yc,ug=f(()=>{yc=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});function yy(e){if(typeof e!="string"||!vy.test(e))throw i("\xABrecurso\xBB: contacts, companies, deals o mod_<clave>.");return e}function _y(e){if(!wy.includes(e))throw i("\xABcanal\xBB: whatsapp o correo.");return e}function dg(e,o="Plantilla"){if(!e||typeof e!="object"||Array.isArray(e))throw i(`${o}: un objeto.`);let t=e;for(let s of Object.keys(t))if(!["recurso","tipoContacto","canal","nombre","asunto","texto"].includes(s))throw i(`${o}: clave no admitida \xAB${s.slice(0,40)}\xBB.`);let n=yy(t.recurso);if(t.tipoContacto!==void 0&&t.tipoContacto!==null&&(!Jr(n)||typeof t.tipoContacto!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(t.tipoContacto)))throw i("El tipo de una plantilla necesita Personas o Empresas y una clave de tipo v\xE1lida.");let r=_y(t.canal),a=r==="correo"?_c(t.asunto,`${o}, asunto`,300,!1):void 0;return{recurso:n,...t.tipoContacto?{tipoContacto:t.tipoContacto}:{},canal:r,nombre:_c(t.nombre,`${o}, nombre`,80),...a?{asunto:a}:{},texto:_c(t.texto,`${o}, texto`,5e3)}}var wy,Di,vy,_c,Nc=f(()=>{wi();q();wy=["whatsapp","correo"],Di=50,vy=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/,_c=(e,o,t,n=!0)=>{if(e==null||e===""){if(n)throw i(`${o}: obligatorio.`);return}if(typeof e!="string"||e.trim().length>t)throw i(`${o}: un texto de hasta ${t} caracteres.`);return e.trim()}});function fg(e){let o=_e(e,"informe");ze(o,["fuente","origenes","filtro","periodo","columnas","agrupar","agregados","orden"],"informe");let t=qe(o.fuente,"fuente",60),n=ir(o.origenes);if(t==="combinada"!=!!n)throw i("La fuente combinada necesita sus or\xEDgenes.");if(t!=="combinada"&&!lc.includes(t)&&!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(t))throw i("\xABfuente\xBB no v\xE1lida.");let r={fuente:t,...n?{origenes:n}:{}};if(o.filtro!==void 0&&o.filtro!==null&&(r.filtro=_e(o.filtro,"filtro"),JSON.stringify(r.filtro).length>4e3))throw i("\xABfiltro\xBB demasiado grande.");if(o.periodo!==void 0&&o.periodo!==null&&(r.periodo=uc(o.periodo)),o.columnas!==void 0&&o.columnas!==null){if(!Array.isArray(o.columnas)||o.columnas.length>pg)throw i(`\xABcolumnas\xBB: una lista de hasta ${pg}.`);r.columnas=[...new Set(o.columnas.map((a,s)=>qe(a,`columnas[${s}]`,60)))]}if(o.agrupar!==void 0&&o.agrupar!==null){let a=_e(o.agrupar,"agrupar");ze(a,["campo","paso"],"agrupar"),r.agrupar={campo:qe(a.campo,"agrupar.campo",60),...a.paso!==void 0?{paso:He(a.paso,ar,"agrupar.paso")}:{}}}if(o.agregados!==void 0&&o.agregados!==null){if(!Array.isArray(o.agregados)||o.agregados.length>mg)throw i(`\xABagregados\xBB: una lista de hasta ${mg}.`);r.agregados=o.agregados.map((a,s)=>{let c=_e(a,`agregados[${s}]`);ze(c,["tipo","campo"],`agregados[${s}]`);let d=He(c.tipo,cc,`agregados[${s}].tipo`);if(d!=="recuento"&&c.campo===void 0)throw i(`\xABagregados[${s}]\xBB: esa operaci\xF3n necesita un campo.`);return{tipo:d,...d!=="recuento"?{campo:qe(c.campo,`agregados[${s}].campo`,60)}:{}}})}if(r.agrupar&&!r.agregados?.length&&(r.agregados=[{tipo:"recuento"}]),o.orden!==void 0&&o.orden!==null){let a=_e(o.orden,"orden");ze(a,["por","sentido"],"orden"),r.orden={por:qe(a.por,"orden.por",60),sentido:He(a.sentido??"asc",["asc","desc"],"orden.sentido")}}return r}var pg,mg,hg=f(()=>{Pi();q();dc();pg=30,mg=6});var $c,Ny,gg,bg=f(()=>{$c=[{clave:"leo",nombre:"Leo",puesto:"Marketing"},{clave:"marina",nombre:"Marina",puesto:"Administrativa"},{clave:"dario",nombre:"Dar\xEDo",puesto:"Comercial"},{clave:"nora",nombre:"Nora",puesto:"Finanzas"},{clave:"irene",nombre:"Irene",puesto:"Consultora de procesos"}],Ny=e=>`pix.agente_${e}`,gg=e=>$c.some(o=>Ny(o.clave)===e)});var wg,vg=f(()=>{wg=["contacts","companies","deals","tareas","proyectos"]});function yg(e,o,t){if(typeof e!="string"||!e.trim())throw i(`Falta \xAB${o}\xBB.`);let n=e.trim();if(n.length>t)throw i(`\xAB${o}\xBB: como mucho ${t} caracteres.`);return n}function _g(e){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw i("\xABpix\xBB: un objeto.");let o=e;for(let r of Object.keys(o))if(r!=="personalidad")throw i(`\xABpix\xBB: no admite \xAB${r.slice(0,40)}\xBB.`);let t=o.personalidad;if(!t||typeof t!="object"||Array.isArray(t))throw i("\xABpix.personalidad\xBB: un objeto con nombre e instrucciones.");let n=t;for(let r of Object.keys(n))if(r!=="nombre"&&r!=="instrucciones")throw i(`\xABpix.personalidad\xBB: no admite \xAB${r.slice(0,40)}\xBB.`);return{personalidad:{nombre:yg(n.nombre,"pix.personalidad.nombre",xy),instrucciones:yg(n.instrucciones,"pix.personalidad.instrucciones",$y)}}}var $y,xy,Ng=f(()=>{q();$y=2e3,xy=60});function $g(e,o){if(e===void 0)return[];if(!Array.isArray(e)||e.length>on)throw i(`\xABinformes\xBB: una lista de hasta ${on}.`);let t=new Set;return e.map((n,r)=>{if(!Cy(n))throw i(`Informe ${r+1}: un objeto.`);for(let c of Object.keys(n))if(!["nombre","descripcion","definicion"].includes(c))throw i(`Informe ${r+1}: clave no admitida \xAB${c.slice(0,40)}\xBB.`);if(typeof n.nombre!="string"||!n.nombre.trim()||n.nombre.length>80)throw i(`Informe ${r+1}: un nombre de hasta 80 caracteres.`);if(n.descripcion!==void 0&&(typeof n.descripcion!="string"||n.descripcion.length>500))throw i(`Informe ${r+1}: la descripci\xF3n, hasta 500 caracteres.`);let a=n.nombre.trim();if(t.has(a))throw i(`Dos informes se llaman \xAB${a}\xBB.`);t.add(a);let s=fg(n.definicion);if([s.fuente,...s.origenes?.map(c=>c.fuente)??[]].some(c=>c.startsWith("mod_")&&!o.includes(c.slice(4))))throw i(`Informe \xAB${a}\xBB: su fuente no es un m\xF3dulo de la soluci\xF3n.`);return{nombre:a,...n.descripcion?{descripcion:n.descripcion}:{},definicion:s}})}var on,Cy,xc=f(()=>{q();hg();on=30,Cy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var xg,yo,lr,ur,oe,Cc,dr,tF,jy,Li,Sy,Oy,rF,nF,Cg=f(()=>{bg();xg={ver:["si","no","suyos","equipo","ambito","jerarquia"],editar:["si","no","suyos","equipo","ambito","jerarquia"],borrar:["si","no","suyos","equipo","ambito","jerarquia"],exportar:["si","no","suyos"],importar:["si","no"],crear:["si","no","suyos","equipo","ambito","jerarquia"],reasignar:["si","no","suyos","jerarquia"],estado:["si","no","suyos","equipo","ambito","jerarquia"],descargar:["si","no"],revelar:["si","no"]},yo=["si","no","suyos"],lr=["si","no","suyos","equipo","jerarquia"],ur=["si","no","suyos","jerarquia"],oe=["si","no"],Cc=(e,o,t=!0)=>[{clave:`${e}.ver`,descripcion:`Ver ${o}`,valores:ur},{clave:`${e}.crear`,descripcion:`Dar de alta ${o}`,valores:ur},{clave:`${e}.editar`,descripcion:`Editar ${o}`,valores:ur},{clave:`${e}.reasignar`,descripcion:`Cambiar el responsable de ${o}`,valores:ur},...t?[{clave:`${e}.estado`,descripcion:`Cambiar el estado de ${o}`,valores:ur}]:[],{clave:`${e}.descargar`,descripcion:`Bajar los ficheros de ${o}`,valores:oe},{clave:`${e}.borrar`,descripcion:`Borrar ${o}`,valores:ur},{clave:`${e}.exportar`,descripcion:`Exportar ${o}`,valores:yo},{clave:`${e}.importar`,descripcion:`Importar ${o} desde una hoja`,valores:oe}],dr=[...Cc("contactos","contactos"),...Cc("empresas","empresas",!1),...Cc("oportunidades","oportunidades"),{clave:"proyectos.ver",descripcion:"Ver proyectos",valores:lr},{clave:"proyectos.editar",descripcion:"Editar los datos del proyecto",valores:lr},{clave:"proyectos.borrar",descripcion:"Borrar proyectos",valores:lr},{clave:"proyectos.exportar",descripcion:"Exportar proyectos",valores:yo},{clave:"proyectos.crear",descripcion:"Crear proyectos",valores:oe},{clave:"proyectos.gestionar",descripcion:"Cambiar el estado, el responsable, los participantes, las columnas y los ajustes de los proyectos, y gestionar plantillas",valores:oe},{clave:"tareas.ver",descripcion:"Ver tareas",valores:lr},{clave:"tareas.crear",descripcion:"Crear tareas",valores:oe},{clave:"tareas.editar",descripcion:"Editar y completar tareas",valores:lr},{clave:"tareas.borrar",descripcion:"Borrar tareas",valores:lr},{clave:"tareas.exportar",descripcion:"Exportar tareas visibles",valores:yo},{clave:"notas.ver",descripcion:"Ver notas",valores:yo},{clave:"notas.editar",descripcion:"Escribir, editar y borrar notas",valores:yo},{clave:"adjuntos.ver",descripcion:"Ver y descargar adjuntos",valores:yo},{clave:"adjuntos.subir",descripcion:"Subir adjuntos",valores:yo},{clave:"miembros.gestionar",descripcion:"Invitar, cambiar el papel y desactivar miembros",valores:oe},{clave:"conectores.accionar",descripcion:"Ejecutar acciones f\xEDsicas de conectores",valores:oe},{clave:"configuracion.gestionar",descripcion:"Cambiar la configuraci\xF3n del espacio y los permisos",valores:oe},{clave:"formularios.gestionar",descripcion:"Crear, editar y borrar formularios (y sus respuestas)",valores:oe},{clave:"formularios.ver_respuestas",descripcion:"Ver las respuestas de los formularios",valores:yo},{clave:"modulos.configurar",descripcion:"Dise\xF1ar, publicar y archivar m\xF3dulos",valores:oe},{clave:"paneles.ver",descripcion:"Ver los paneles de m\xE9tricas",valores:oe},{clave:"paneles.editar",descripcion:"Crear, cambiar y borrar paneles de m\xE9tricas",valores:oe},{clave:"paneles.compartir",descripcion:"Compartir paneles con el equipo y cambiar o borrar los de equipo",valores:oe},{clave:"automatizaciones.gestionar",descripcion:"Crear y cambiar automatizaciones, y ver sus ejecuciones",valores:oe},{clave:"campanas.gestionar",descripcion:"Crear y enviar campa\xF1as de correo, y gestionar consentimientos y supresiones",valores:oe},{clave:"agenda.ver",descripcion:"Ver las citas de la agenda",valores:yo},{clave:"agenda.editar",descripcion:"Crear, mover y cancelar citas",valores:yo},{clave:"agenda.configurar",descripcion:"Configurar la agenda: tipos de cita, d\xEDas cerrados, horarios, reserva p\xFAblica y los recursos (horarios y aprobar ausencias)",valores:oe},{clave:"analisis.ver",descripcion:"Usar An\xE1lisis: informes de lo que ya puede ver",valores:oe},{clave:"analisis.compartir",descripcion:"Compartir informes con el equipo y cambiar o borrar los de equipo",valores:oe},{clave:"secretos.ver",descripcion:"Ver los campos secretos (cada vez queda registrado qui\xE9n lo vio)",valores:oe},{clave:"liquidaciones.gestionar",descripcion:"Generar, aprobar, cerrar, pagar y reabrir liquidaciones de comisiones",valores:oe},{clave:"portales.gestionar",descripcion:"Configurar los portales, invitar a ellos y revocar el acceso",valores:oe},{clave:"auditoria.ver",descripcion:"Ver la auditor\xEDa del espacio (qui\xE9n hizo qu\xE9 y cu\xE1ndo)",valores:oe},{clave:"publico.compartir",descripcion:"Compartir la p\xE1gina p\xFAblica de un registro (un enlace que caduca)",valores:oe},{clave:"pix.memoria_espacio",descripcion:"Escribir lo que Pix recuerda para todo el espacio",valores:oe},...$c.map(e=>({clave:`pix.agente_${e.clave}`,descripcion:`Usar a ${e.nombre} (${e.puesto}) del Equipo IA`,valores:oe}))],tF=new Set(dr.map(e=>e.clave)),jy=e=>/\.(exportar|importar)$/.test(e),Li=e=>Object.fromEntries(dr.map(o=>[o.clave,e(o)])),Sy=e=>e.clave.startsWith("miembros.")||e.clave.startsWith("configuracion.")||e.clave==="formularios.gestionar"||e.clave.startsWith("proyectos.")&&e.clave!=="proyectos.ver"&&e.clave!=="proyectos.exportar"||e.clave==="modulos.configurar"||e.clave==="agenda.configurar"||e.clave==="paneles.compartir"||e.clave==="automatizaciones.gestionar"||e.clave==="campanas.gestionar"||e.clave==="analisis.compartir"||e.clave==="liquidaciones.gestionar"||e.clave==="portales.gestionar"||e.clave==="auditoria.ver"||e.clave==="pix.memoria_espacio"||gg(e.clave),Oy={titular:Li(()=>"si"),administrador:Li(e=>e.clave==="conectores.accionar"?"no":"si"),miembro:Li(e=>Sy(e)||e.clave==="conectores.accionar"||e.clave==="secretos.ver"||jy(e.clave)?"no":"si"),lectura:Li(e=>e.clave.endsWith(".ver")&&e.clave!=="secretos.ver"&&e.clave!=="auditoria.ver"||e.clave.endsWith(".descargar")?"si":e.clave.endsWith(".reasignar")?"suyos":"no")},rF=dr.filter(e=>/^((contactos|empresas|oportunidades|proyectos|tareas|notas|adjuntos)\.|agenda\.(ver|editar)$)/.test(e.clave)&&e.valores.includes("suyos")&&Oy.miembro[e.clave]!=="no").map(e=>e.clave),nF=dr.filter(e=>/^((contactos|empresas|oportunidades|proyectos|tareas|notas|adjuntos)\.|agenda\.(ver|editar)$)/.test(e.clave)&&e.valores.includes("suyos")).map(e=>e.clave)});function Og(e){if(!Array.isArray(e))throw i("Los sin\xF3nimos van en una lista de palabras.");let o=[],t=new Set;for(let n of e){if(typeof n!="string")throw i("Cada sin\xF3nimo es un texto.");let r=n.replace(/\s+/g," ").trim();if(r){if(r.length>jg)throw i(`\xAB${r.slice(0,20)}\u2026\xBB: como mucho ${jg} caracteres.`);if(!jc(r))throw i(`\xAB${r}\xBB no es una palabra.`);t.has(jc(r))||(t.add(jc(r)),o.push(r))}}if(o.length>Sc)throw i(`Como mucho ${Sc} sin\xF3nimos por m\xF3dulo.`);return o}var Sg,Sc,jg,jc,Ag=f(()=>{q();Sg=["contacts","companies","deals","tasks"],Sc=20,jg=40,jc=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9ñ\s-]/g," ").replace(/\s+/g," ").trim()});function qy(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>5)throw i("Conexiones de la soluci\xF3n no v\xE1lidas.");return e.map(o=>{if(!re(o)||o.tipo!=="conector"||typeof o.conector!="string"||!/^[a-z][a-z0-9_-]{0,39}$/.test(o.conector))throw i("Conexi\xF3n de la soluci\xF3n no v\xE1lida.");let t=_o(o.nombre,"nombre de la conexi\xF3n",80,!1)||o.conector;return{clave:o.conector,nombre:t,tipo:"conector",conector:o.conector}})}function ky(e){if(e===void 0)return[];if(!Array.isArray(e))throw i("Conexiones de la soluci\xF3n no v\xE1lidas.");let o=s=>re(s)&&s.tipo==="conector",t=qy(e.filter(o)),n=Vh(e.filter(s=>!o(s))),r=0,a=0;return e.map(s=>o(s)?t[r++]:n[a++])}function Ty(e){if(e==null)return null;if(!re(e))throw i("\xABagenda\xBB: un objeto.");Xe(e,["tipos"],"Agenda");let o=new Set,t=io(e.tipos,Py,"agenda.tipos").map((n,r)=>{let a=`Tipo de cita ${r+1}`;if(!re(n))throw i(`${a}: un objeto.`);Xe(n,["nombre","duracion","color","reserva_publica","quien_atiende","cambio_horas","crear_persona"],a);let s=_o(n.nombre,`nombre del ${a.toLowerCase()}`,80);if(o.has(s.toLowerCase()))throw i(`${a}: nombre repetido.`);if(o.add(s.toLowerCase()),!Number.isInteger(n.duracion)||n.duracion<5||n.duracion>1440)throw i(`${a}: \xABduracion\xBB, de 5 a 1440 minutos.`);if(n.color!==void 0&&(typeof n.color!="string"||!/^#[0-9a-f]{6}$/i.test(n.color)))throw i(`${a}: \xABcolor\xBB, #rrggbb.`);for(let c of["reserva_publica","crear_persona"])if(n[c]!==void 0&&typeof n[c]!="boolean")throw i(`${a}: \xAB${c}\xBB, s\xED o no.`);if(n.quien_atiende!==void 0&&n.quien_atiende!=="cualquiera"&&n.quien_atiende!=="cliente")throw i(`${a}: \xABquien_atiende\xBB, cualquiera o cliente.`);if(n.cambio_horas!==void 0&&(!Number.isInteger(n.cambio_horas)||n.cambio_horas<0||n.cambio_horas>720))throw i(`${a}: \xABcambio_horas\xBB, de 0 a 720.`);return{nombre:s,duracion:n.duracion,...n.color!==void 0?{color:n.color.toLowerCase()}:{},...n.reserva_publica!==void 0?{reserva_publica:n.reserva_publica}:{},...n.quien_atiende!==void 0?{quien_atiende:n.quien_atiende}:{},...n.cambio_horas!==void 0?{cambio_horas:n.cambio_horas}:{},...n.crear_persona!==void 0?{crear_persona:n.crear_persona}:{}}});return t.length?{tipos:t}:null}function My(e,o){return io(e,Ec,"vistasTabla").map((t,n)=>{let r=`Vista de tabla ${n+1}`;if(!re(t))throw i(`${r}: un objeto.`);Xe(t,["objeto","tipoContacto","nombre","config","disposicion"],r);let a=typeof t.objeto=="string"?t.objeto:"";if(!["contacts","companies"].includes(a)&&(!a.startsWith("mod_")||!o.includes(a.slice(4))))throw i(`${r}: de un m\xF3dulo de la soluci\xF3n (mod_<clave>).`);let s=ag(t.disposicion??null,a),c=eg(a,t.tipoContacto);return{objeto:a,...c?{tipoContacto:c}:{},nombre:_o(t.nombre,`nombre de la ${r.toLowerCase()}`,60),...t.config!==void 0?{config:sg(t.config)}:{},disposicion:s}})}function zy(e,o,t=[]){let n=new Set;return io(e,Rc,"papeles").map((r,a)=>{let s=`Papel ${a+1}`;if(!re(r))throw i(`${s}: un objeto.`);Xe(r,["nombre","base","permisos","ocultos","lectura","identidades"],s);let c=_o(r.nombre,`nombre del ${s.toLowerCase()}`,40);if(n.has(c.toLowerCase()))throw i(`${s}: nombre repetido.`);if(n.add(c.toLowerCase()),typeof r.base!="string"||!Dy.includes(r.base))throw i(`${s}: \xABbase\xBB, administrador, miembro o lectura.`);let d={};if(r.permisos!==void 0){if(!re(r.permisos))throw i(`${s}: \xABpermisos\xBB, un objeto.`);for(let[b,y]of Object.entries(r.permisos)){if(b==="miembros.gestionar"||b==="configuracion.gestionar")throw i(`${s}: \xAB${b}\xBB no se da en un papel personalizado.`);let v=Ly.exec(b),w=dr.find(j=>j.clave===b);if(v?!o.includes(v[1]):!w)throw i(`${s}: permiso desconocido \xAB${b.slice(0,60)}\xBB.`);let N=w?w.valores:xg[v[2]];if(typeof y!="string"||!N.includes(y))throw i(`${s}: valor no v\xE1lido para \xAB${b.slice(0,60)}\xBB.`);d[b]=y}}let u=(b,y)=>{if(b===void 0)return[];if(!Array.isArray(b)||b.length>100)throw i(`${s}: \xAB${y}\xBB, una lista (hasta 100) de \xABmod_<clave>.<campo>\xBB.`);return b.map(v=>{let w=typeof v=="string"?Iy.exec(v):null,N=w?t.find(j=>j.clave===w[1]):void 0;if(!w||!N||!N.campos.some(j=>j.clave===w[2]))throw i(`${s}: \xAB${String(v).slice(0,60)}\xBB no es un campo de un m\xF3dulo de la soluci\xF3n.`);return v})},p=u(r.ocultos,"ocultos"),m=u(r.lectura,"lectura"),h=gm(r.identidades);return{nombre:c,base:r.base,...Object.keys(d).length?{permisos:d}:{},...p.length?{ocultos:p}:{},...m.length?{lectura:m}:{},...h.length?{identidades:h}:{}}})}function Oc(e,o=0){if(o>30)throw i("La soluci\xF3n anida demasiado.");if(Array.isArray(e))return e.forEach(t=>Oc(t,o+1));if(re(e))for(let t of Object.keys(e)){if(Ey.has(t))throw i(`Clave no admitida \xAB${t}\xBB.`);Oc(e[t],o+1)}}function Xe(e,o,t){for(let n of Object.keys(e))if(!o.includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`)}function _o(e,o,t,n=!0){if(e==null||e===""){if(n)throw i(`Falta \xAB${o}\xBB.`);return""}if(typeof e!="string"||e.length>t)throw i(`\xAB${o}\xBB: texto de hasta ${t} caracteres.`);return e.trim()}function tn(e,o){if(typeof e=="string"){if(e.length>Fi)throw i("La soluci\xF3n pasa de 1 MB.");try{e=JSON.parse(e)}catch{throw i("La soluci\xF3n no es un JSON v\xE1lido.")}}else if(JSON.stringify(e??null).length>Fi)throw i("La soluci\xF3n pasa de 1 MB.");if(!re(e))throw i("La soluci\xF3n tiene que ser un objeto.");Oc(e),Xe(e,["formato","version","plantilla","nombre","descripcion","icono","modulos","paneles","automatizaciones","ejemplos","informes","principal","mensajes","papeles","portales","vistasTabla","separadores","menu","sinonimos","perfilesImportacion","conexiones","fuentesExternas","senales","pix","agenda"],"Soluci\xF3n");let t;if(e.plantilla!==void 0){let g=e.plantilla;if(!re(g))throw i("\xABplantilla\xBB: un objeto.");if(Xe(g,["id","version","sector","nivel","dependencias","migracion"],"Plantilla"),typeof g.id!="string"||!/^[a-z][a-z0-9_]{0,59}$/.test(g.id))throw i("\xABplantilla.id\xBB: min\xFAsculas, n\xFAmeros y _.");if(!Mi(g.version))throw i("\xABplantilla.version\xBB: usa una versi\xF3n sem\xE1ntica v\xE1lida.");if(typeof g.sector!="string"||!/^[a-z][a-z0-9_]{0,39}$/.test(g.sector))throw i("\xABplantilla.sector\xBB: min\xFAsculas y _.");if(g.nivel!==void 0&&g.nivel!=="completa"&&g.nivel!=="basica")throw i("\xABplantilla.nivel\xBB: completa o basica.");let x=g.dependencias;if(x!==void 0&&(!Array.isArray(x)||x.length>30||x.some(k=>typeof k!="string"||!/^[a-z][a-z0-9_]{0,59}$/.test(k)||k===g.id)||new Set(x).size!==x.length))throw i("\xABplantilla.dependencias\xBB: usa identificadores distintos de otras soluciones.");let O=Gh(g.migracion,g.version);t={...O?{migracion:O}:{},id:g.id,version:g.version,sector:g.sector,...x?{dependencias:x}:{},...g.nivel==="basica"?{nivel:"basica"}:{}}}if(e.formato!==kt)throw i(`No es una soluci\xF3n (formato \xAB${kt}\xBB).`);if(!Number.isInteger(e.version)||e.version<1)throw i("\xABversion\xBB: un entero.");if(e.version>pr)throw i("La soluci\xF3n es de una versi\xF3n m\xE1s nueva del CRM.");let n=_o(e.icono,"icono",40,!1)||"boxes";if(!Eg.test(n))throw i("\xABicono\xBB: un icono de lucide.");if(!Array.isArray(e.modulos)||e.modulos.length<1||e.modulos.length>zi)throw i(`Una soluci\xF3n lleva de 1 a ${zi} m\xF3dulos.`);let r=e.modulos.map(g=>re(g)&&typeof g.clave=="string"?g.clave:"");if(new Set(r).size!==r.length)throw i("Dos m\xF3dulos de la soluci\xF3n con la misma clave.");let a=new Map([...o.externos??[]].filter(([g])=>!r.includes(g))),s=[...r,...a.keys()],c=new Map([...a,...e.modulos.map((g,x)=>[r[x],ac(g,s)])]),d=e.modulos.map(g=>{let x=$h(g,{topeCampos:o.topeCampos,modulosDelEspacio:s,camposRelacion:c}),O=re(g)?g.sin_coste:void 0;if(O!==void 0&&O!==!0)throw i(`\xAB${x.nombre_plural}\xBB: \xABsin_coste\xBB solo puede ser true.`);return O===!0?{...x,sin_coste:!0}:x}),u=io(e.paneles,Ac,"paneles").map((g,x)=>{if(!re(g))throw i(`Panel ${x+1}: un objeto.`);if(Xe(g,["nombre","icono","widgets"],`Panel ${x+1}`),!Array.isArray(g.widgets)||g.widgets.length>20)throw i(`Panel ${x+1}: hasta 20 widgets.`);let O=_o(g.icono,"icono",40,!1);if(O&&!Eg.test(O))throw i(`Panel ${x+1}: icono no v\xE1lido.`);return{nombre:_o(g.nombre,"nombre del panel",60),...O?{icono:O}:{},widgets:g.widgets}}),p=io(e.automatizaciones,qc,"automatizaciones").map((g,x)=>{if(!re(g))throw i(`Automatizaci\xF3n ${x+1}: un objeto.`);if(Xe(g,["nombre","definicion"],`Automatizaci\xF3n ${x+1}`),!re(g.definicion))throw i(`Automatizaci\xF3n ${x+1}: falta su definici\xF3n.`);return{nombre:_o(g.nombre,"nombre de la automatizaci\xF3n",80),definicion:g.definicion}}),m=io(e.senales,20,"senales").map((g,x)=>{if(!re(g))throw i(`Se\xF1al ${x+1}: un objeto.`);Xe(g,["fuente","regla"],`Se\xF1al ${x+1}`);let O=typeof g.fuente=="string"?g.fuente:"";if(!(O.startsWith("mod_")?r.includes(O.slice(4)):wg.includes(O)))throw i(`Se\xF1al ${x+1}: \xABfuente\xBB, un m\xF3dulo de la soluci\xF3n (mod_<clave>) o un nativo.`);if(!re(g.regla))throw i(`Se\xF1al ${x+1}: falta su regla.`);return{fuente:O,regla:g.regla}}),h=_g(e.pix),b=$g(e.informes,r);if(e.principal!==void 0&&(typeof e.principal!="string"||!r.includes(e.principal)))throw i("\xABprincipal\xBB: la clave de uno de sus m\xF3dulos.");let y=io(e.mensajes,Di,"mensajes").map((g,x)=>{let O=dg(g,`Mensaje ${x+1}`);if(O.recurso.startsWith("mod_")&&!r.includes(O.recurso.slice(4)))throw i(`Mensaje ${x+1}: de un m\xF3dulo que no est\xE1 en la soluci\xF3n.`);return O}),v=zy(e.papeles,r,d),w=Wy(e.portales,r),N=Ty(e.agenda),j=My(e.vistasTabla,r),S=io(e.separadores??[],kc,"separadores").map((g,x)=>{if(!re(g))throw i(`Separador ${x+1}: un objeto.`);if(Xe(g,["antes","titulo"],`Separador ${x+1}`),g.antes!==null&&(typeof g.antes!="string"||!r.includes(g.antes)))throw i(`Separador ${x+1}: \xABantes\xBB, la clave de uno de sus m\xF3dulos.`);if(g.titulo!==void 0&&g.titulo!==null&&(typeof g.titulo!="string"||!g.titulo.trim()||g.titulo.trim().length>40))throw i(`Separador ${x+1}: \xABtitulo\xBB, de 1 a 40 caracteres (o null: solo la l\xEDnea).`);return{antes:g.antes,titulo:typeof g.titulo=="string"?g.titulo.trim():null}}),R=io(e.menu??[],100,"menu").map((g,x)=>{if(!re(g))throw i(`Men\xFA ${x+1}: un objeto.`);if(Xe(g,["entrada","padre","recientes","despliega"],`Men\xFA ${x+1}`),typeof g.entrada!="string"||!r.includes(g.entrada))throw i(`Men\xFA ${x+1}: \xABentrada\xBB, la clave de uno de sus m\xF3dulos.`);if(g.padre!==void 0&&g.padre!==null&&(typeof g.padre!="string"||!r.includes(g.padre)||g.padre===g.entrada))throw i(`Men\xFA ${x+1}: \xABpadre\xBB, otro de sus m\xF3dulos (o null).`);if(g.recientes!==void 0&&(!Number.isSafeInteger(g.recientes)||g.recientes<0||g.recientes>10))throw i(`Men\xFA ${x+1}: \xABrecientes\xBB, de 0 a 10.`);if(g.despliega!==void 0&&(typeof g.despliega!="string"||!pc.includes(g.despliega)))throw i(`Men\xFA ${x+1}: \xABdespliega\xBB, ${pc.join(", ")}.`);return{entrada:g.entrada,...g.padre!==void 0?{padre:g.padre}:{},...g.recientes!==void 0?{recientes:g.recientes}:{},...g.despliega!==void 0?{despliega:g.despliega}:{}}});for(let g of R)if(g.padre&&(R.some(x=>x.entrada===g.padre&&x.padre)||R.some(x=>x.padre===g.entrada)))throw i(`Men\xFA: \xAB${g.entrada}\xBB, un solo nivel (ni su padre va dentro de otro ni tiene otros dentro).`);if(new Set(R.map(g=>g.entrada)).size!==R.length)throw i("Men\xFA: cada m\xF3dulo, una vez.");let F={};if(e.ejemplos!==void 0){if(!re(e.ejemplos))throw i("\xABejemplos\xBB: un objeto por m\xF3dulo.");for(let[g,x]of Object.entries(e.ejemplos)){if(!r.includes(g))throw i(`Ejemplos de un m\xF3dulo que no est\xE1 en la soluci\xF3n (\xAB${g.slice(0,40)}\xBB).`);let O=new Set;F[g]=io(x,Wi,`ejemplos de ${g}`).map((k,L)=>{if(!re(k))throw i(`Ejemplo ${L+1} de ${g}: un objeto.`);if(k._ref!==void 0&&!Number.isSafeInteger(k._ref))throw i(`Ejemplo ${L+1} de ${g}: \xAB_ref\xBB es un entero.`);if(typeof k._ref=="number"){if(O.has(k._ref))throw i(`\xAB${g}\xBB: referencia de ejemplo repetida.`);O.add(k._ref)}if((d.find(U=>U.clave===g)?.campos??[]).filter(U=>U.tipo==="secreto").map(U=>U.clave).some(U=>U in k))throw i(`Ejemplo ${L+1} de ${g}: un ejemplo no lleva el valor de un campo secreto.`);return k})}}let I=ky(e.conexiones),_=Wh(e.fuentesExternas,d,I.filter(Ry));if(_.some(g=>g.modo==="vivo"&&F[g.modulo]?.length))throw i("Un m\xF3dulo con fuente en vivo no puede tener ejemplos.");let E=Kh(e.perfilesImportacion);if(E.some(g=>g.perfil.entidades.some(x=>x.destino.startsWith("mod_")&&!d.some(O=>`mod_${O.clave}`===x.destino))))throw i("El perfil apunta fuera de la soluci\xF3n.");return{formato:kt,...E.length?{perfilesImportacion:E}:{},...I.length?{conexiones:I}:{},..._.length?{fuentesExternas:_}:{},version:e.version,...t?{plantilla:t}:{},nombre:_o(e.nombre,"nombre",80),descripcion:_o(e.descripcion,"descripcion",500,!1),icono:n,modulos:d,paneles:u,automatizaciones:p,ejemplos:F,...m.length?{senales:m}:{},...h?{pix:h}:{},...b.length?{informes:b}:{},...typeof e.principal=="string"?{principal:e.principal}:{},...y.length?{mensajes:y}:{},...v.length?{papeles:v}:{},...w.length?{portales:w}:{},...N?{agenda:N}:{},...j.length?{vistasTabla:j}:{},...S.length?{separadores:S}:{},...R.length?{menu:R}:{},...Fy(e.sinonimos,d.map(g=>g.clave))}}function Fy(e,o){if(e===void 0)return{};if(!re(e))throw i("\xABsinonimos\xBB: un objeto (clave del m\xF3dulo \u2192 lista de palabras).");let t={};for(let[n,r]of Object.entries(e)){if(!o.includes(n)&&!Sg.includes(n))throw i(`\xABsinonimos\xBB: \xAB${n.slice(0,40)}\xBB no es un m\xF3dulo de la soluci\xF3n ni uno nativo.`);let a=Og(r);a.length&&(t[n]=a)}return Object.keys(t).length?{sinonimos:t}:{}}function Wy(e,o){return io(e,Pc,"portales").map((t,n)=>{let r=`Portal ${n+1}`;if(!re(t))throw i(`${r}: un objeto.`);Xe(t,["clave","nombre","activo","personas","secciones","textos","marca"],r);let a=[...lg(t)].filter(p=>!o.includes(p));if(a.length)throw i(`${r}: usa un m\xF3dulo que no est\xE1 en la soluci\xF3n (\xABmod_${a[0].slice(0,40)}\xBB).`);if(!Array.isArray(t.secciones)||!t.secciones.length)throw i(`${r}: al menos una secci\xF3n.`);let{activo:s,marca:c,...d}=t,u=re(c)&&typeof c.color=="string"?c.color:void 0;return{...d,...u?{marca:{color:u}}:{}}})}function io(e,o,t){if(e===void 0)return[];if(!Array.isArray(e)||e.length>o)throw i(`\xAB${t}\xBB: una lista de hasta ${o}.`);return e}var kt,pr,zi,Ac,Ec,qc,Wi,Fi,Eg,Ey,Ry,Py,Rc,Iy,Dy,Ly,re,kc,Pc,Tc=f(()=>{Bh();Uh();Hh();fc();Zh();bm();ug();og();Nc();q();vg();Ng();xc();Kr();Fh();Cg();cg();Ag();kt="forgenex.solucion",pr=2,zi=30,Ac=10,Ec=20,qc=40,Wi=50,Fi=1e6,Eg=/^[a-z0-9-]{1,40}$/,Ey=new Set(["__proto__","constructor","prototype"]);Ry=e=>e.tipo!=="conector";Py=10;Rc=10,Iy=/^mod_([a-z][a-z0-9_]{0,40})\.([a-z][a-z0-9_]{0,40})$/,Dy=["administrador","miembro","lectura"],Ly=/^mod_([a-z][a-z0-9_]{0,40})\.(ver|editar|borrar|exportar|importar|crear|reasignar|estado|descargar|revelar)$/;re=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);kc=20,Pc=10});function Rg(e,o){let t=new Map(e);for(let[n,r]of e){if(!/^(interfaz|funciones)\/.+\.ts$/.test(n))continue;let a=n.replace(/\.ts$/,".js");if(e.has(a))throw qg([{ruta:n,linea:null,motivo:`El fichero coincide con la salida \xAB${a}\xBB.`}]);try{let{code:s}=o(r.toString("utf8"),{loader:"ts",sourcefile:n,target:"es2020",format:"esm"});t.set(a,Buffer.from(s)),t.delete(n)}catch(s){let c=s?.errors;throw qg(c?.length?c.slice(0,12).map(({location:d,text:u})=>({ruta:n,linea:d?.line??null,motivo:u})):[{ruta:n,linea:null,motivo:"El compilador no pudo procesar el fichero."}])}}return t}function qg(e){let{ruta:o,linea:t,motivo:n}=e[0];return new z(422,"build_app",`${o}${t?`:${t}`:""}: ${n}`,!1,{errores:e})}var kg=f(()=>{q()});import{createHash as Pg,createPublicKey as By,sign as Vy,verify as FF}from"node:crypto";function Uy(e){let o=By(e);if(o.asymmetricKeyType!=="ed25519")throw i("La clave p\xFAblica tiene que ser ed25519.");let t=o.export({type:"spki",format:"der"});return{pem:o.export({type:"spki",format:"pem"}).toString(),id:Pg("sha256").update(t).digest("hex")}}function Jy(e){return Buffer.from(JSON.stringify(["forgenex.fgx.v1",[...e].filter(([o])=>o!==rn).sort(([o],[t])=>o<t?-1:o>t?1:0).map(([o,t])=>[o,Pg("sha256").update(t).digest("hex")])]))}function Tg(e,o,t){let{id:n}=Uy(t);return Buffer.from(JSON.stringify({formato:"forgenex.firma",version:1,clave:n,firma:Vy(null,Jy(e),o).toString("base64")}))}var rn,Mc=f(()=>{q();rn="firma.json"});function Ic(e){let o=Array.from({length:256},(c,d)=>{let u=d;for(let p=0;p<8;p++)u=u&1?3988292384^u>>>1:u>>>1;return u>>>0}),t=[],n=[],r=0;for(let[c,d]of e){let u=Buffer.from(c),p=4294967295;for(let b of d)p=o[(p^b)&255]^p>>>8;p=(p^4294967295)>>>0;let m=Buffer.alloc(30),h=Buffer.alloc(46);m.writeUInt32LE(67324752),m.writeUInt16LE(20,4),m.writeUInt16LE(2048,6),m.writeUInt32LE(p,14),m.writeUInt32LE(d.length,18),m.writeUInt32LE(d.length,22),m.writeUInt16LE(u.length,26),h.writeUInt32LE(33639248),h.writeUInt16LE(20,4),h.writeUInt16LE(20,6),h.writeUInt16LE(2048,8),h.writeUInt32LE(p,16),h.writeUInt32LE(d.length,20),h.writeUInt32LE(d.length,24),h.writeUInt16LE(u.length,28),h.writeUInt32LE(r,42),t.push(m,u,d),n.push(h,u),r+=m.length+u.length+d.length}let a=Buffer.concat(n),s=Buffer.alloc(22);return s.writeUInt32LE(101010256),s.writeUInt16LE(e.size,8),s.writeUInt16LE(e.size,10),s.writeUInt32LE(a.length,12),s.writeUInt32LE(r,16),Buffer.concat([...t,a,s])}var Mg=f(()=>{});import{existsSync as Qy,cpSync as Gy,copyFileSync as nn,mkdirSync as Dc,readFileSync as mr,readdirSync as an,realpathSync as Ig,writeFileSync as Dg}from"node:fs";import{dirname as Hy,join as B,resolve as Xy,sep as Yy}from"node:path";import{fileURLToPath as Ky}from"node:url";import{createRequire as Bi}from"node:module";function Vi(e,o="html",t=process.cwd()){if(!/^[a-z][a-z0-9-]{1,59}$/.test(e))throw new Error("El nombre debe tener de 2 a 60 letras min\xFAsculas, n\xFAmeros o guiones y empezar por letra.");if(!["html","react","archivos","natacion"].includes(o))throw new Error("Plantilla: html, react, archivos o natacion.");let n=B(t,e);Dc(n);for(let c of["interfaz","funciones"])Dc(B(n,c));let r=(c,d)=>Dg(B(n,c),typeof d=="string"?d:JSON.stringify(d,null,2)+`
|
|
22
|
-
|
|
23
|
-
`)
|
|
24
|
-
|
|
21
|
+
from aprobaciones a join modulos m on m.id = a.modulo_id`});function Lf(e,o,t){if(e.requisito!==void 0&&e.requisito!==null){let n=e.requisito;if(!zv(n)||typeof n.formula!="string"||!n.formula.trim()||n.formula.length>no||typeof n.mensaje!="string"||!n.mensaje.trim()||n.mensaje.length>200)throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: el requisito lleva una f\xF3rmula y un mensaje (hasta 200 caracteres).`);o.requisito={formula:n.formula.trim(),mensaje:n.mensaje.trim()}}if(e.pide!==void 0&&e.pide!==null){if(!Array.isArray(e.pide)||e.pide.length>If||e.pide.some(n=>typeof n!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(n)))throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: \xABpide\xBB, hasta ${If} campos.`);e.pide.length&&(o.pide=[...new Set(e.pide)])}if(Tf(e,o,t),e.limiteDias!==void 0&&e.limiteDias!==null){if(!Number.isInteger(e.limiteDias)||e.limiteDias<1||e.limiteDias>3650)throw i(`\xAB${t}\xBB, \xAB${o.etiqueta}\xBB: el l\xEDmite de d\xEDas, de 1 a 3650.`);o.limiteDias=e.limiteDias}}function Df(e){let o=e.filter(t=>!t.archivado);return e.map(t=>{if(t.tipo!=="seleccion"||!t.opciones?.some(r=>r.requisito||r.pide||r.limiteDias))return t;let n=t.opciones.map((r,a)=>{for(let c of r.pide??[]){let d=o.find(u=>u.clave===c);if(!d||["formula","resumen","busqueda","subtabla","boton","autonumero","creado_el","creado_por","modificado_el","modificado_por"].includes(d.tipo))throw i(`\xAB${t.etiqueta}\xBB, \xAB${r.etiqueta}\xBB: pide \xAB${c}\xBB, que no es un campo que se rellene.`)}if(!r.requisito)return r;let s;try{s=bi([...o,Fv(t.clave,a,r.requisito.formula)]).at(-1)}catch(c){throw i(`\xAB${t.etiqueta}\xBB, \xAB${r.etiqueta}\xBB: ${c instanceof Error?c.message:"la f\xF3rmula no vale"}`)}if(s.origen?.tipo!=="booleano")throw i(`\xAB${t.etiqueta}\xBB, \xAB${r.etiqueta}\xBB: el requisito tiene que dar s\xED o no.`);return{...r,requisito:{...r.requisito,formula:s.formula}}});return{...t,opciones:n}})}var If,zv,Fv,zf=f(()=>{R();wi();Mf();If=5,zv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Fv=(e,o,t)=>({clave:`etapa_${e}_${o}`,etiqueta:`Requisito ${o+1}`,tipo:"formula",formula:t})});function Bf(e){if(e==null)return;if(!Array.isArray(e)||e.length>Ff)throw i(`\xABconversiones\xBB: hasta ${Ff}.`);let o=new Set,t=e.map((n,r)=>{let a=`Conversi\xF3n ${r+1}`;if(!Oi(n))throw i(`${a}: un objeto.`);for(let c of Object.keys(n))if(!["clave","nombre","destino","campos","enlaceDestino","enlaceOrigen","lineas","etapa"].includes(c))throw i(`${a}: clave no admitida \xAB${c.slice(0,40)}\xBB.`);if(typeof n.clave!="string"||!At.test(n.clave)||o.has(n.clave))throw i(`${a}: \xABclave\xBB (min\xFAsculas y _), sin repetir.`);if(o.add(n.clave),typeof n.nombre!="string"||!n.nombre.trim()||n.nombre.length>60)throw i(`${a}: el nombre del bot\xF3n (1\u201360).`);if(typeof n.destino!="string"||!(Wv.includes(n.destino)||/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(n.destino)))throw i(`${a}: \xABdestino\xBB, contacts, companies, deals o mod_<clave>.`);let s={clave:n.clave,nombre:n.nombre.trim(),destino:n.destino,campos:Wf(n.campos,a)};for(let c of["enlaceDestino","enlaceOrigen"])if(!(n[c]===void 0||n[c]===null||n[c]==="")){if(typeof n[c]!="string"||!At.test(n[c]))throw i(`${a}: \xAB${c}\xBB no es un campo v\xE1lido.`);s[c]=n[c]}if(n.lineas!==void 0){if(!Array.isArray(n.lineas)||n.lineas.length>5)throw i(`${a}: \xABlineas\xBB, hasta 5.`);s.lineas=n.lineas.map(c=>{if(!Oi(c)||typeof c.desde!="string"||!At.test(c.desde)||typeof c.a!="string"||!At.test(c.a))throw i(`${a}: cada \xABlineas\xBB, {desde, a, campos}.`);return{desde:c.desde,a:c.a,campos:Wf(c.campos,a)}})}if(n.etapa!==void 0&&n.etapa!==null){if(!Oi(n.etapa)||typeof n.etapa.campo!="string"||!At.test(n.etapa.campo)||typeof n.etapa.valor!="string")throw i(`${a}: \xABetapa\xBB, {campo, valor}.`);s.etapa={campo:n.etapa.campo,valor:n.etapa.valor}}return s});return t.length?t:void 0}var Ff,At,Wv,Oi,Wf,Uf=f(()=>{R();Ff=5,At=/^[a-z][a-z0-9_]{0,40}$/,Wv=["contacts","companies","deals"],Oi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Wf=(e,o)=>{if(e===void 0)return{};if(!Oi(e)||Object.keys(e).length>100)throw i(`${o}: \xABcampos\xBB, un objeto destino \u2192 origen.`);for(let[t,n]of Object.entries(e))if(!At.test(t)||typeof n!="string"||!At.test(n))throw i(`${o}: el campo \xAB${t.slice(0,40)}\xBB no es v\xE1lido.`);return e}});function Qf(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>Vf)throw i(`\xABencadenar\xBB: hasta ${Vf}.`);let t=new Set,n=e.map((r,a)=>{let s=`\xABencadenar\xBB ${a+1}`;if(!Et(r))throw i(`${s}: un objeto.`);for(let w of Object.keys(r))if(!["clave","nombre","destino","enlace","campos","lineas","estado","no_cuentan","permitir_exceso","juntar"].includes(w))throw i(`${s}: clave no admitida \xAB${w.slice(0,40)}\xBB.`);let c=ot(r.clave,`${s}.clave`);if(t.has(c))throw i(`${s}: \xABclave\xBB repetida.`);if(c==="juntar")throw i(`${s}: \xABjuntar\xBB no vale como clave.`);if(t.add(c),typeof r.nombre!="string"||!r.nombre.trim()||r.nombre.length>60)throw i(`${s}: el nombre del bot\xF3n (1\u201360).`);if(typeof r.destino!="string"||!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(r.destino))throw i(`${s}: \xABdestino\xBB, mod_<clave>.`);if(!Et(r.lineas))throw i(`${s}: \xABlineas\xBB {desde, a, cantidad: {origen, destino}}.`);let d=r.lineas,u=ot(d.desde,`${s}.lineas.desde`),p=Uv(o,u);if(!p)throw i(`${s}: \xAB${u}\xBB no es una subtabla de este m\xF3dulo.`);if(!Et(d.cantidad))throw i(`${s}: \xABlineas.cantidad\xBB {origen, destino}.`);let m=ot(d.cantidad.origen,`${s}.lineas.cantidad.origen`),h=(p.columnas??[]).find(w=>w.clave===m&&!w.archivado);if(!h||!(Bv.includes(h.tipo)||h.tipo==="formula"&&h.origen?.tipo==="numero"))throw i(`${s}: la cantidad \xAB${m}\xBB tiene que ser una columna num\xE9rica de \xAB${u}\xBB.`);let b={clave:c,nombre:r.nombre.trim(),destino:r.destino,enlace:ot(r.enlace,`${s}.enlace`),lineas:{desde:u,a:ot(d.a,`${s}.lineas.a`),cantidad:{origen:m,destino:ot(d.cantidad.destino,`${s}.lineas.cantidad.destino`)}}},y=Jf(d.campos,`${s}.lineas.campos`);if(y){for(let w of Object.values(y))if(!(p.columnas??[]).some(N=>N.clave===w&&!N.archivado))throw i(`${s}: \xAB${w}\xBB no es una columna de \xAB${u}\xBB.`);b.lineas.campos=y}let v=Jf(r.campos,`${s}.campos`);if(v){for(let w of Object.values(v))if(!o.some(N=>N.clave===w&&!N.archivado))throw i(`${s}: \xAB${w}\xBB no es un campo de este m\xF3dulo.`);b.campos=v}if(r.estado!==void 0&&r.estado!==null){let w=r.estado;if(!Et(w))throw i(`${s}: \xABestado\xBB {campo, parcial, completo, pendiente?}.`);let N=o.find(S=>S.clave===w.campo&&S.tipo==="seleccion"&&!S.archivado);if(!N)throw i(`${s}: \xABestado.campo\xBB tiene que ser una selecci\xF3n de este m\xF3dulo.`);let j=new Set((N.opciones??[]).map(S=>S.valor));for(let S of["parcial","completo","pendiente"]){let q=w[S];if(!(q===void 0&&S==="pendiente")&&(typeof q!="string"||!j.has(q)))throw i(`${s}: \xABestado.${S}\xBB tiene que ser una opci\xF3n de \xAB${N.etiqueta}\xBB.`)}b.estado={campo:N.clave,parcial:w.parcial,completo:w.completo,...typeof w.pendiente=="string"?{pendiente:w.pendiente}:{}}}if(r.no_cuentan!==void 0&&r.no_cuentan!==null){let w=r.no_cuentan;if(!Et(w)||!Array.isArray(w.valores)||w.valores.length>20||!w.valores.every(N=>typeof N=="string"&&N.length<=60))throw i(`${s}: \xABno_cuentan\xBB {campo, valores}.`);b.no_cuentan={campo:ot(w.campo,`${s}.no_cuentan.campo`),valores:w.valores}}if(r.permitir_exceso===!0&&(b.permitir_exceso=!0),r.juntar!==void 0&&r.juntar!==null&&r.juntar!==!1){let w=r.juntar===!0?{}:r.juntar;if(!Et(w))throw i(`${s}: \xABjuntar\xBB {iguales?, enlace_varios?}.`);for(let j of Object.keys(w))if(!["iguales","enlace_varios"].includes(j))throw i(`${s}: \xABjuntar\xBB: clave no admitida \xAB${j.slice(0,40)}\xBB.`);let N=w.iguales===void 0?[]:w.iguales;if(!Array.isArray(N)||N.length>10||!N.every(j=>typeof j=="string"&&o.some(S=>S.clave===j&&!S.archivado)))throw i(`${s}: \xABjuntar.iguales\xBB, campos de este m\xF3dulo (hasta 10).`);b.juntar={...N.length?{iguales:N}:{},...w.enlace_varios?{enlace_varios:ot(w.enlace_varios,`${s}.juntar.enlace_varios`)}:{}}}return b});return n.length?n:void 0}var Vf,Ks,Bv,Et,Jf,ot,Uv,Gf=f(()=>{R();Vf=5,Ks=/^[a-z][a-z0-9_]{0,40}$/,Bv=["numero","importe","duracion","porcentaje"],Et=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jf=(e,o)=>{if(e!=null){if(!Et(e)||Object.keys(e).length>60)throw i(`${o}: un objeto destino \u2192 origen.`);for(let[t,n]of Object.entries(e))if(!Ks.test(t)||typeof n!="string"||!Ks.test(n))throw i(`${o}: \xAB${t.slice(0,40)}\xBB no es v\xE1lido.`);return e}},ot=(e,o)=>{if(typeof e!="string"||!Ks.test(e))throw i(`${o}: falta o no es v\xE1lido.`);return e},Uv=(e,o)=>e.find(t=>t.clave===o&&t.tipo==="subtabla"&&!t.archivado)});function Yf(e){if(e==null)return;if(!Array.isArray(e)||e.length>Hf)throw i(`\xABplantillas_hijos\xBB: hasta ${Hf}.`);let o=new Set,t=e.map((n,r)=>{let a=`Plantilla de hijos ${r+1}`;if(!Zs(n))throw i(`${a}: un objeto.`);for(let d of Object.keys(n))if(!["clave","nombre","cuando","subtabla","modulo","via","registros"].includes(d))throw i(`${a}: clave no admitida \xAB${d.slice(0,40)}\xBB.`);if(typeof n.clave!="string"||!Ai.test(n.clave)||o.has(n.clave))throw i(`${a}: \xABclave\xBB (min\xFAsculas y _), sin repetir.`);if(o.add(n.clave),typeof n.nombre!="string"||!n.nombre.trim()||n.nombre.length>60)throw i(`${a}: el nombre (1\u201360).`);let s=n.cuando===void 0?[]:n.cuando;if(!Array.isArray(s)||s.length>3)throw i(`${a}: \xABcuando\xBB, hasta 3 condiciones.`);let c={clave:n.clave,nombre:n.nombre.trim(),cuando:s.map(d=>{if(!Zs(d)||typeof d.campo!="string"||!Ai.test(d.campo)||!(typeof d.valor=="string"||typeof d.valor=="boolean"))throw i(`${a}: cada condici\xF3n, {campo, valor}.`);return{campo:d.campo,valor:d.valor}}),registros:[]};if(typeof n.subtabla=="string"&&n.subtabla){if(!Ai.test(n.subtabla))throw i(`${a}: \xABsubtabla\xBB no v\xE1lida.`);c.subtabla=n.subtabla}else{if(typeof n.modulo!="string"||!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(n.modulo)||typeof n.via!="string"||!Ai.test(n.via))throw i(`${a}: una \xABsubtabla\xBB de este m\xF3dulo, o un \xABmodulo\xBB (mod_<clave>) y su relaci\xF3n \xABvia\xBB con este.`);c.modulo=n.modulo,c.via=n.via}if(!Array.isArray(n.registros)||!n.registros.length||n.registros.length>Xf)throw i(`${a}: \xABregistros\xBB, de 1 a ${Xf}.`);return c.registros=n.registros.map(d=>{if(!Zs(d)||JSON.stringify(d).length>4e3)throw i(`${a}: cada registro, un objeto (de hasta 4000 caracteres).`);return d}),c});return t.length?t:void 0}var Hf,Xf,Ai,Zs,Kf=f(()=>{R();Hf=10,Xf=50,Ai=/^[a-z][a-z0-9_]{0,40}$/,Zs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function eh(e,o){if(e==null)return;if(!bo(e))throw i("\xABpertenencia\xBB: un objeto.");let t=(n,r,a,s=!1)=>{let c=o.find(d=>d.clave===n&&!d.archivado);if(!c||!r.includes(c.tipo)||s&&c.multiple)throw i(`\xABpertenencia.${a}\xBB: ${r.join(" o ")}${s?" simple":""} de este m\xF3dulo.`);return c.clave};return{demanda:t(e.demanda,["relacion"],"demanda",!0),oferta:t(e.oferta,["relacion"],"oferta",!0),desde:t(e.desde,["fecha"],"desde"),...e.hasta?{hasta:t(e.hasta,["fecha"],"hasta")}:{},...e.correccion_dias!==void 0&&e.correccion_dias!==null?{correccion_dias:Vv(e.correccion_dias)}:{}}}function oh(e,o){if(e==null)return;if(!bo(e))throw i("\xABasignacion\xBB: un objeto.");if(typeof e.oferta!="string"||!Ri.test(e.oferta))throw i("\xABasignacion.oferta\xBB: la clave del m\xF3dulo de la oferta.");let t=e.destino,n;if(bo(t)&&t.forma==="pertenencia"&&typeof t.modulo=="string"&&Ri.test(t.modulo))n={forma:"pertenencia",modulo:t.modulo};else if(bo(t)&&t.forma==="relacion"){let r=o.find(a=>a.clave===t.campo&&!a.archivado);if(r?.tipo!=="relacion"||r.multiple||r.relacion!==`mod_${e.oferta}`)throw i("\xABasignacion.destino.campo\xBB: una relaci\xF3n simple de este m\xF3dulo a la oferta.");n={forma:"relacion",campo:r.clave}}else throw i("\xABasignacion.destino\xBB: {forma: \xABpertenencia\xBB, modulo} o {forma: \xABrelacion\xBB, campo}.");if(typeof e.cupo!="string"||!Ri.test(e.cupo))throw i("\xABasignacion.cupo\xBB: un campo num\xE9rico de la oferta.");return{oferta:e.oferta,destino:n,...Qv({...e,cupo_fijo:void 0},o),cupo:e.cupo}}function Qv(e,o,t=!1){let n=(p,m,h)=>{let b=o.find(y=>y.clave===p&&!y.archivado);if(!b||h&&!h.includes(b.tipo))throw i(`\xABasignacion\xBB: ${m}, ${h?h.join(" o "):"un campo"} de este m\xF3dulo.`);return b.clave},r=(p,m)=>{if(t){if(typeof p!="string"||!/^[a-z][a-z0-9_]{0,40}(\.[a-z][a-z0-9_]{0,40}){0,3}$/.test(p))throw i(`${m}: campo de oferta no v\xE1lido.`);return p}return Jv(p,m)},a=t?Zf:Ri,s=t&&e.cupo_fijo!==void 0;if(s?e.cupo!==void 0||!Number.isInteger(e.cupo_fijo)||Number(e.cupo_fijo)<1||Number(e.cupo_fijo)>1e4:typeof e.cupo!="string"||!a.test(e.cupo))throw i("\xABasignacion.cupo\xBB: un n\xFAmero de la oferta o un cupo fijo de 1 a 10000.");let c={...s?{cupo_fijo:Number(e.cupo_fijo)}:{cupo:e.cupo},filtros:[],puntos:[]};if(e.orden!==void 0&&e.orden!==null){let p=e.orden;if(!bo(p))throw i("\xABasignacion.orden\xBB: {campo, sentido}.");c.orden={campo:p.campo==="numero"?"numero":n(p.campo,"\xABorden.campo\xBB"),...p.sentido==="desc"?{sentido:"desc"}:{}}}if(e.plazas_por!==void 0&&e.plazas_por!==null){let p=e.plazas_por;if(!bo(p)||typeof p.oferta!="string"||!a.test(p.oferta))throw i("\xABasignacion.plazas_por\xBB: {demanda (selecci\xF3n m\xFAltiple), oferta (su campo)}.");c.plazas_por={demanda:n(p.demanda,"\xABplazas_por.demanda\xBB",["seleccion_multiple","seleccion"]),oferta:p.oferta}}e.inicio&&(c.inicio=n(e.inicio,"\xABinicio\xBB",["fecha"]));let d=Array.isArray(e.filtros)?e.filtros:[],u=Array.isArray(e.puntos)?e.puntos:[];if(d.length>Ei||u.length>Ei)throw i(`\xABasignacion\xBB: hasta ${Ei} filtros y ${Ei} puntos.`);if(c.filtros=d.map((p,m)=>{let h=`Filtro ${m+1}`;if(!bo(p))throw i(`${h}: un objeto.`);if(p.tipo==="igual"||p.tipo==="contiene")return{tipo:p.tipo,demanda:n(p.demanda,`${h}, \xABdemanda\xBB`),oferta:r(p.oferta,h)};if(p.tipo==="entre")return{tipo:"entre",demanda:n(p.demanda,`${h}, \xABdemanda\xBB`,["numero","importe","porcentaje","fecha","hora"]),min:r(p.min,h),max:r(p.max,h)};throw i(`${h}: \xABtipo\xBB igual, contiene o entre.`)}),c.puntos=u.map((p,m)=>{let h=`Punto ${m+1}`;if(!bo(p))throw i(`${h}: un objeto.`);switch(p.tipo){case"base":case"carga":return{tipo:p.tipo,peso:Rt(p.peso,h)};case"dentro":return{tipo:"dentro",demanda:n(p.demanda,`${h}, \xABdemanda\xBB`,["hora","numero","fecha","fecha_hora"]),desde:r(p.desde,h),hasta:r(p.hasta,h),peso:Rt(p.peso,h)};case"igual":case"contiene":return{tipo:p.tipo,demanda:n(p.demanda,`${h}, \xABdemanda\xBB`),oferta:r(p.oferta,h),peso:Rt(p.peso,h)};case"junto":{let b=o.find(v=>v.clave===p.relacion&&!v.archivado);if(b?.tipo!=="relacion")throw i(`${h}: \xABrelacion\xBB, una relaci\xF3n de este m\xF3dulo con otras demandas (los hermanos).`);let y=p.mismo_campo;return{tipo:"junto",relacion:b.clave,misma:Rt(p.misma,h),...bo(y)?{mismo_campo:{oferta:r(y.oferta,h),peso:Rt(y.peso,h)}}:{},...p.mismo_valor!==void 0?{mismo_valor:Rt(p.mismo_valor,h)}:{}}}case"si_no":if(typeof p.contiene!="string"||!p.contiene||p.contiene.length>100)throw i(`${h}: \xABcontiene\xBB, el valor que la oferta deber\xEDa tener.`);return{tipo:"si_no",demanda:n(p.demanda,`${h}, \xABdemanda\xBB`,["booleano"]),oferta:r(p.oferta,h),contiene:p.contiene,peso:Rt(p.peso,h)};default:throw i(`${h}: \xABtipo\xBB base, carga, dentro, igual, contiene, junto o si_no.`)}}),e.cercania!==void 0&&e.cercania!==null){let p=e.cercania;if(!bo(p))throw i("\xABasignacion.cercania\xBB: {demanda, oferta}.");c.cercania={demanda:n(p.demanda,"\xABcercania.demanda\xBB",["hora","numero","fecha","fecha_hora"]),oferta:r(p.oferta,"\xABcercania\xBB")}}return c}var bo,Ri,Zf,Ei,Vv,Rt,Jv,th=f(()=>{R();bo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ri=/^[a-z][a-z0-9_]{0,40}$/,Zf=/^[a-z][a-z0-9_]{0,40}(\.[a-z][a-z0-9_]{0,40})?$/,Ei=20,Vv=e=>{let o=Number(e);if(!Number.isInteger(o)||o<0||o>60)throw i("\xABpertenencia.correccion_dias\xBB: un entero de 0 a 60.");return o};Rt=(e,o)=>{let t=Number(e);if(!Number.isFinite(t)||Math.abs(t)>1e4)throw i(`${o}: \xABpeso\xBB, un n\xFAmero (\xB110 000).`);return t},Jv=(e,o)=>{if(typeof e!="string"||!Zf.test(e))throw i(`${o}: un campo de la oferta (\xABcampo\xBB o \xABrelacion.campo\xBB).`);return e}});function rh(e,o){if(e==null)return;if(!qi(e))throw i("\xABpublico\xBB: un objeto.");for(let r of Object.keys(e))if(!["campos","titulo","acciones","caducaDias"].includes(r))throw i(`\xABpublico\xBB: clave no admitida \xAB${r.slice(0,40)}\xBB.`);let t=r=>o.find(a=>a.clave===r&&!a.archivado);if(!Array.isArray(e.campos)||!e.campos.length||e.campos.length>20)throw i("\xABpublico.campos\xBB: de 1 a 20 campos.");for(let r of e.campos){let a=t(r);if(!a)throw i(`\xABpublico\xBB: \xAB${String(r).slice(0,40)}\xBB no es un campo del m\xF3dulo.`);if(Hv.includes(a.tipo))throw i(`\xABpublico\xBB: \xAB${a.etiqueta}\xBB no se ense\xF1a en una p\xE1gina p\xFAblica.`)}let n={campos:[...new Set(e.campos)]};if(e.titulo!==void 0&&e.titulo!==null&&e.titulo!==""){let r=t(e.titulo);if(r?.tipo!=="texto"&&r?.tipo!=="autonumero")throw i("\xABpublico.titulo\xBB: un texto del m\xF3dulo.");n.titulo=r.clave}if(e.caducaDias!==void 0){let r=Number(e.caducaDias);if(!Number.isInteger(r)||r<1||r>180)throw i("\xABpublico.caducaDias\xBB: de 1 a 180.");n.caducaDias=r}if(e.acciones!==void 0){if(!Array.isArray(e.acciones)||e.acciones.length>3)throw i("\xABpublico.acciones\xBB: hasta 3.");let r=new Set;if(n.acciones=e.acciones.map((a,s)=>{let c=`Acci\xF3n p\xFAblica ${s+1}`;if(!qi(a)||typeof a.clave!="string"||!Gv.test(a.clave)||r.has(a.clave))throw i(`${c}: \xABclave\xBB (min\xFAsculas y _), sin repetir.`);if(r.add(a.clave),typeof a.etiqueta!="string"||!a.etiqueta.trim()||a.etiqueta.length>60)throw i(`${c}: el texto del bot\xF3n (1\u201360).`);let d={clave:a.clave,etiqueta:a.etiqueta.trim(),...a.una_vez===!0?{una_vez:!0}:{}};if(a.campo!==void 0&&a.campo!==null&&a.campo!==""){let u=t(a.campo);if(u?.tipo==="seleccion"){let p=u.opciones?.find(m=>m.valor===a.valor);if(!p)throw i(`${c}: el valor tiene que ser una opci\xF3n de \xAB${u.etiqueta}\xBB.`);if(u.embudo&&(p.requisito||p.pide?.length||p.aprobacion))throw i(`${c}: \xAB${p.etiqueta}\xBB tiene requisito o aprobaci\xF3n: no se puede poner desde fuera.`)}else if(u?.tipo==="booleano"){if(typeof a.valor!="boolean")throw i(`${c}: el valor, s\xED o no.`)}else if(u?.tipo==="hecho"){if(a.valor!==!0)throw i(`${c}: un \xABhecho\xBB se marca (true).`)}else throw i(`${c}: el campo, una selecci\xF3n, un s\xED/no o un \xABhecho\xBB.`);d.campo=u.clave,d.valor=a.valor}if(a.lineas!==void 0&&a.lineas!==null){let u=a.lineas,p=qi(u)?t(u.subtabla):void 0,m=p?.tipo==="subtabla"?(p.columnas??[]).find(h=>h.clave===u.columna&&!h.archivado):void 0;if(m?.tipo!=="booleano")throw i(`${c}: \xABlineas\xBB, una subtabla del m\xF3dulo y una columna s\xED/no suya.`);if(!n.campos.includes(p.clave))throw i(`${c}: la subtabla de \xABlineas\xBB tiene que ense\xF1arse en la p\xE1gina.`);d.lineas={subtabla:p.clave,columna:m.clave}}if(a.firma!==void 0&&a.firma!==null&&a.firma!==!1){let u=a.firma===!0?{}:a.firma;if(!qi(u))throw i(`${c}: \xABfirma\xBB, {archivos}.`);for(let p of Object.keys(u))if(p!=="archivos")throw i(`${c}: \xABfirma\xBB, clave no admitida \xAB${p.slice(0,40)}\xBB.`);if(u.archivos!==void 0&&u.archivos!==null&&u.archivos!==""){if(t(u.archivos)?.tipo!=="archivos")throw i(`${c}: \xABfirma.archivos\xBB, un campo de archivos del m\xF3dulo (donde queda el firmado).`);d.firma={archivos:u.archivos}}else d.firma={}}if(!d.campo&&!d.lineas&&!d.firma)throw i(`${c}: un campo, unas l\xEDneas o la firma.`);return d}),n.acciones.filter(a=>a.firma).length>1)throw i("\xABpublico.acciones\xBB: solo una firma el documento.")}return n}var Gv,qi,Hv,nh=f(()=>{R();Gv=/^[a-z][a-z0-9_]{0,40}$/,qi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Hv=["secreto","boton","firma"]});function sh(e,o){if(he(e))return;if(!wo(e))throw i("\xABstock\xBB: un objeto {articulo?, ubicacion?, movimiento?}.");tt(e,["articulo","ubicacion","movimiento","reponer"],"stock");let t=s=>o.find(c=>c.clave===s&&!c.archivado),n=(s,c,d,u)=>{let p=t(s);if(!p||!d(p))throw i(`\xABstock.${c}\xBB: ${u} de este m\xF3dulo.`);return p.clave},r=s=>s.tipo==="relacion"&&!s.multiple&&!!s.relacion?.startsWith("mod_"),a={};if(!he(e.articulo)){let s=e.articulo;if(!wo(s))throw i("\xABstock.articulo\xBB: un objeto.");tt(s,["minimo","reponer","proveedor","permitir_negativo","lotes"],"stock.articulo");let c={};if(he(s.minimo)||(c.minimo=n(s.minimo,"articulo.minimo",d=>d.tipo==="numero","un n\xFAmero")),he(s.reponer)||(c.reponer=n(s.reponer,"articulo.reponer",d=>d.tipo==="numero","un n\xFAmero")),he(s.proveedor)||(c.proveedor=n(s.proveedor,"articulo.proveedor",d=>r(d)||d.tipo==="relacion"&&!d.multiple&&["contacts","companies"].includes(d.relacion??""),"una relaci\xF3n simple a un proveedor")),s.permitir_negativo===!0)c.permitir_negativo=!0;else if(typeof s.permitir_negativo=="string"&&s.permitir_negativo)c.permitir_negativo=n(s.permitir_negativo,"articulo.permitir_negativo",d=>d.tipo==="booleano","un s\xED/no");else if(!he(s.permitir_negativo)&&s.permitir_negativo!==!1)throw i("\xABstock.articulo.permitir_negativo\xBB: true o un s\xED/no del art\xEDculo.");if(!he(s.lotes)){if(s.lotes!=="lote"&&s.lotes!=="serie")throw i("\xABstock.articulo.lotes\xBB: lote o serie.");if(c.permitir_negativo)throw i("\xABstock.articulo\xBB: con lotes o series no se admiten negativos.");c.lotes=s.lotes}a.articulo=c}if(!he(e.ubicacion)){let s=e.ubicacion;if(!wo(s))throw i("\xABstock.ubicacion\xBB: un objeto.");tt(s,["almacen"],"stock.ubicacion"),a.ubicacion=he(s.almacen)?{}:{almacen:n(s.almacen,"ubicacion.almacen",r,"una relaci\xF3n simple a otro m\xF3dulo")}}if(!he(e.movimiento)){let s=e.movimiento;if(!wo(s))throw i("\xABstock.movimiento\xBB: un objeto.");if(tt(s,["tipo","lineas","ubicacion","ubicacion_destino","cuando"],"stock.movimiento"),!ih.includes(s.tipo))throw i(`\xABstock.movimiento.tipo\xBB: ${ih.join(", ")}.`);if(!wo(s.lineas))throw i("\xABstock.movimiento.lineas\xBB: {subtabla, articulo, cantidad, ubicacion?, coste?}.");let c=s.lineas;tt(c,["subtabla","articulo","cantidad","ubicacion","ubicacion_destino","coste","lote","caducidad"],"stock.movimiento.lineas");let d=t(c.subtabla);if(d?.tipo!=="subtabla")throw i("\xABstock.movimiento.lineas.subtabla\xBB: una subtabla de este m\xF3dulo.");let u=(d.columnas??[]).filter(v=>!v.archivado),p=(v,w,N,j)=>{let S=u.find(q=>q.clave===v);if(!S||!N(S))throw i(`\xABstock.movimiento.lineas.${w}\xBB: ${j} de \xAB${d.etiqueta}\xBB.`);return S.clave},m={tipo:s.tipo,lineas:{subtabla:d.clave,articulo:p(c.articulo,"articulo",r,"la columna de producto (una relaci\xF3n simple)"),cantidad:p(c.cantidad,"cantidad",v=>ah.includes(v.tipo),"una columna num\xE9rica")},cuando:{campo:"",valores:[]}};if(he(c.ubicacion)||(m.lineas.ubicacion=p(c.ubicacion,"ubicacion",r,"una relaci\xF3n simple")),he(c.coste)||(m.lineas.coste=p(c.coste,"coste",v=>ah.includes(v.tipo),"una columna num\xE9rica")),he(c.lote)||(m.lineas.lote=p(c.lote,"lote",v=>v.tipo==="texto"||v.tipo==="codigo","una columna de texto")),he(c.caducidad)||(m.lineas.caducidad=p(c.caducidad,"caducidad",v=>v.tipo==="fecha","una columna de fecha")),he(s.ubicacion)||(m.ubicacion=n(s.ubicacion,"movimiento.ubicacion",r,"una relaci\xF3n simple")),!m.lineas.ubicacion&&!m.ubicacion)throw i("\xABstock.movimiento\xBB: la ubicaci\xF3n, en la l\xEDnea (\xABlineas.ubicacion\xBB) o en el documento (\xABubicacion\xBB).");if(he(c.ubicacion_destino)||(m.lineas.ubicacion_destino=p(c.ubicacion_destino,"ubicacion_destino",r,"una relaci\xF3n simple")),he(s.ubicacion_destino)||(m.ubicacion_destino=n(s.ubicacion_destino,"movimiento.ubicacion_destino",r,"una relaci\xF3n simple")),m.tipo==="traspaso"&&!m.lineas.ubicacion_destino&&!m.ubicacion_destino)throw i("\xABstock.movimiento\xBB: un traspaso necesita la ubicaci\xF3n de destino, en la l\xEDnea (\xABlineas.ubicacion_destino\xBB) o en el documento (\xABubicacion_destino\xBB).");if(m.tipo!=="traspaso"&&(m.lineas.ubicacion_destino||m.ubicacion_destino))throw i("\xABstock.movimiento\xBB: la ubicaci\xF3n de destino es solo de un traspaso.");if(!wo(s.cuando))throw i("\xABstock.movimiento.cuando\xBB: {campo, valor} o {campo, valores}.");tt(s.cuando,["campo","valor","valores"],"stock.movimiento.cuando");let h=t(s.cuando.campo);if(h?.tipo!=="seleccion")throw i("\xABstock.movimiento.cuando.campo\xBB: una selecci\xF3n de este m\xF3dulo.");let b=Array.isArray(s.cuando.valores)?s.cuando.valores:[s.cuando.valor],y=new Set((h.opciones??[]).map(v=>v.valor));if(!b.length||b.length>20||!b.every(v=>typeof v=="string"&&y.has(v)))throw i(`\xABstock.movimiento.cuando\xBB: opciones de \xAB${h.etiqueta}\xBB.`);m.cuando={campo:h.clave,valores:[...new Set(b)]},a.movimiento=m}if(!he(e.reponer)){let s=e.reponer;if(!wo(s))throw i("\xABstock.reponer\xBB: {destino, proveedor, lineas: {subtabla, articulo, cantidad}, estado?}.");if(tt(s,["destino","proveedor","lineas","estado","en_camino"],"stock.reponer"),!a.articulo?.minimo||!a.articulo.reponer||!a.articulo.proveedor)throw i("\xABstock.reponer\xBB: el art\xEDculo necesita su m\xEDnimo, su \xABreponer hasta\xBB y su proveedor.");if(typeof s.destino!="string"||!/^mod_(?!sub_)[a-z][a-z_]{1,30}$/.test(s.destino))throw i("\xABstock.reponer.destino\xBB: mod_<clave> del m\xF3dulo de compras.");if(typeof s.proveedor!="string"||!ec.test(s.proveedor))throw i("\xABstock.reponer.proveedor\xBB: la relaci\xF3n de las compras al proveedor.");if(!wo(s.lineas))throw i("\xABstock.reponer.lineas\xBB: {subtabla, articulo, cantidad}.");tt(s.lineas,["subtabla","articulo","cantidad"],"stock.reponer.lineas");for(let d of["subtabla","articulo","cantidad"])if(typeof s.lineas[d]!="string"||!ec.test(s.lineas[d]))throw i(`\xABstock.reponer.lineas.${d}\xBB: falta o no es v\xE1lida.`);let c={destino:s.destino,proveedor:s.proveedor,lineas:{subtabla:s.lineas.subtabla,articulo:s.lineas.articulo,cantidad:s.lineas.cantidad}};if(!he(s.estado)){if(!wo(s.estado)||typeof s.estado.campo!="string"||typeof s.estado.valor!="string")throw i("\xABstock.reponer.estado\xBB: {campo, valor}.");c.estado={campo:s.estado.campo,valor:s.estado.valor}}if(!he(s.en_camino)){let d=s.en_camino;if(!wo(d)||typeof d.campo!="string"||!ec.test(d.campo)||!Array.isArray(d.valores)||!d.valores.length||d.valores.length>20||!d.valores.every(u=>typeof u=="string"&&u.length<=80))throw i("\xABstock.reponer.en_camino\xBB: {campo, valores} (los estados de la compra pedida y a\xFAn no recibida).");c.en_camino={campo:d.campo,valores:[...new Set(d.valores)]}}a.reponer=c}return Object.keys(a).length?a:void 0}var ih,wo,tt,ah,he,ec,ch=f(()=>{R();ih=["entrada","salida","ajuste","traspaso","recuento","reserva"],wo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tt=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`\xAB${t}\xBB: clave no admitida \xAB${n.slice(0,40)}\xBB.`)},ah=["numero","importe","duracion","porcentaje"],he=e=>e==null||e==="";ec=/^[a-z][a-z0-9_]{0,40}$/});function Yv(e,o){let t=`liquidacion.reglas[${o}]`;if(!rt(e))throw i(`\xAB${t}\xBB: un objeto.`);if(nt(e,["nombre","si","calculo","valor","tramos"],t),typeof e.nombre!="string"||!e.nombre.trim()||e.nombre.length>60)throw i(`\xAB${t}.nombre\xBB: de 1 a 60 caracteres.`);if(e.calculo!=="porcentaje"&&e.calculo!=="fijo")throw i(`\xAB${t}.calculo\xBB: porcentaje o fijo.`);let n={nombre:e.nombre.trim(),calculo:e.calculo};if(qt(e.si)||(n.si=dh(e.si,`${t}.si`)),qt(e.tramos))n.valor=rc(e.valor,`${t}.valor`);else{let r=e.tramos;if(!rt(r))throw i(`\xAB${t}.tramos\xBB: {por, lista}.`);if(nt(r,["por","modo","lista"],`${t}.tramos`),r.por!=="acumulado"&&r.por!=="importe")throw i(`\xAB${t}.tramos.por\xBB: acumulado o importe.`);if(r.modo!==void 0&&r.modo!==null&&r.modo!=="marginal"&&r.modo!=="alcanzado")throw i(`\xAB${t}.tramos.modo\xBB: marginal o alcanzado.`);if(!Array.isArray(r.lista)||!r.lista.length||r.lista.length>uh)throw i(`\xAB${t}.tramos.lista\xBB: de 1 a ${uh} tramos {desde, valor}.`);let a=r.lista.map((s,c)=>{if(!rt(s))throw i(`\xAB${t}.tramos.lista[${c}]\xBB: {desde, valor}.`);return nt(s,["desde","valor"],`${t}.tramos.lista[${c}]`),{desde:rc(s.desde,`${t}.tramos.lista[${c}].desde`,0),valor:rc(s.valor,`${t}.tramos.lista[${c}].valor`)}}).sort((s,c)=>s.desde-c.desde);if(a[0].desde!==0)throw i(`\xAB${t}.tramos\xBB: el primer tramo empieza en 0.`);if(new Set(a.map(s=>s.desde)).size!==a.length)throw i(`\xAB${t}.tramos\xBB: dos tramos con el mismo \xABdesde\xBB.`);if(n.tramos={por:r.por,modo:r.modo==="alcanzado"?"alcanzado":"marginal",lista:a},!qt(e.valor))throw i(`\xAB${t}\xBB: con tramos, el valor va en cada tramo.`)}return n}function ph(e,o){if(qt(e))return;if(!rt(e))throw i("\xABliquidacion\xBB: un objeto {origen, importe, fecha, agente, campos, estados, lineas, reglas}.");if(nt(e,["origen","importe","fecha","agente","cuentan","campos","estados","lineas","reglas"],"liquidacion"),typeof e.origen!="string"||!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(e.origen))throw i("\xABliquidacion.origen\xBB: mod_<clave> del m\xF3dulo de origen.");let t=e.agente==="_dueno"?"_dueno":ki(e.agente,"liquidacion.agente"),n=N=>o.find(j=>j.clave===N&&!j.archivado),r=(N,j,S,q)=>{let F=n(N);if(!F||!S(F))throw i(`\xABliquidacion.${j}\xBB: ${q} de este m\xF3dulo.`);return F.clave},a=N=>N.tipo==="relacion"&&!N.multiple&&!!N.relacion?.startsWith("mod_"),s=N=>a(N)||N.tipo==="relacion"&&!N.multiple&&["contacts","companies"].includes(N.relacion??"");if(!rt(e.campos))throw i("\xABliquidacion.campos\xBB: {agente?, periodo, estado, total}.");nt(e.campos,["agente","periodo","estado","total"],"liquidacion.campos");let c={periodo:r(e.campos.periodo,"campos.periodo",N=>N.tipo==="texto","un texto"),estado:r(e.campos.estado,"campos.estado",N=>N.tipo==="seleccion","una selecci\xF3n"),total:r(e.campos.total,"campos.total",N=>tc.includes(N.tipo),"un n\xFAmero o importe")};if(qt(e.campos.agente)||(c.agente=r(e.campos.agente,"campos.agente",s,"una relaci\xF3n simple")),t!=="_dueno"&&!c.agente)throw i("\xABliquidacion.campos.agente\xBB: con el agente en una relaci\xF3n del origen, la relaci\xF3n de aqu\xED al mismo m\xF3dulo.");let d=n(c.estado),u=new Set((d.opciones??[]).map(N=>N.valor));if(!rt(e.estados))throw i("\xABliquidacion.estados\xBB: {borrador, aprobada, cerrada, pagada} con opciones de su selecci\xF3n.");nt(e.estados,[...oc],"liquidacion.estados");let p={};for(let N of oc){let j=e.estados[N];if(typeof j!="string"||!u.has(j))throw i(`\xABliquidacion.estados.${N}\xBB: una opci\xF3n de \xAB${d.etiqueta}\xBB.`);p[N]=j}if(new Set(Object.values(p)).size!==oc.length)throw i("\xABliquidacion.estados\xBB: una opci\xF3n distinta para cada estado.");if(!rt(e.lineas))throw i("\xABliquidacion.lineas\xBB: {subtabla, origen, base, comision, regla?}.");nt(e.lineas,["subtabla","origen","base","comision","regla"],"liquidacion.lineas");let m=n(e.lineas.subtabla);if(m?.tipo!=="subtabla")throw i("\xABliquidacion.lineas.subtabla\xBB: una subtabla de este m\xF3dulo.");let h=(m.columnas??[]).filter(N=>!N.archivado),b=(N,j,S,q)=>{let F=h.find(I=>I.clave===N);if(!F||!S(F))throw i(`\xABliquidacion.lineas.${j}\xBB: ${q} de \xAB${m.etiqueta}\xBB.`);return F.clave},y={subtabla:m.clave,origen:b(e.lineas.origen,"origen",N=>a(N)&&N.relacion===e.origen,`la relaci\xF3n simple a ${String(e.origen)}`),base:b(e.lineas.base,"base",N=>tc.includes(N.tipo),"una columna num\xE9rica"),comision:b(e.lineas.comision,"comision",N=>tc.includes(N.tipo),"una columna num\xE9rica")};if(qt(e.lineas.regla)||(y.regla=b(e.lineas.regla,"regla",N=>N.tipo==="texto","una columna de texto")),!Array.isArray(e.reglas)||!e.reglas.length||e.reglas.length>lh)throw i(`\xABliquidacion.reglas\xBB: de 1 a ${lh}.`);let v=e.reglas.map(Yv),w={origen:e.origen,importe:ki(e.importe,"liquidacion.importe"),fecha:ki(e.fecha,"liquidacion.fecha"),agente:t,campos:c,estados:p,lineas:y,reglas:v};return qt(e.cuentan)||(w.cuentan=dh(e.cuentan,"liquidacion.cuentan")),w}var oc,lh,uh,tc,Xv,rt,qt,nt,ki,dh,rc,mh=f(()=>{R();oc=["borrador","aprobada","cerrada","pagada"],lh=20,uh=20,tc=["numero","importe","porcentaje"],Xv=/^[a-z][a-z0-9_]{0,40}$/,rt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qt=e=>e==null||e==="",nt=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`\xAB${t}\xBB: clave no admitida \xAB${n.slice(0,40)}\xBB.`)},ki=(e,o)=>{if(typeof e!="string"||!Xv.test(e))throw i(`\xAB${o}\xBB: falta o no es v\xE1lido.`);return e},dh=(e,o)=>{if(!rt(e))throw i(`\xAB${o}\xBB: {campo, valores}.`);if(nt(e,["campo","valores"],o),!Array.isArray(e.valores)||!e.valores.length||e.valores.length>20||!e.valores.every(t=>typeof t=="string"&&t.length<=60))throw i(`\xAB${o}.valores\xBB: de 1 a 20 opciones.`);return{campo:ki(e.campo,`${o}.campo`),valores:[...new Set(e.valores)]}},rc=(e,o,t=-1e12)=>{if(typeof e!="number"||!Number.isFinite(e)||e<t||e>1e12)throw i(`\xAB${o}\xBB: un n\xFAmero.`);return e}});function hh(e,o){if(fh(e))return;if(!nc(e))throw i("\xABcuota\xBB: un objeto {proxima, periodicidad, hasta?}.");for(let a of Object.keys(e))if(!["proxima","periodicidad","hasta"].includes(a))throw i(`\xABcuota\xBB: clave no admitida \xAB${a.slice(0,40)}\xBB.`);let t=a=>o.find(s=>s.clave===a&&!s.archivado),n=(a,s)=>{let c=t(a);if(c?.tipo!=="fecha")throw i(`\xABcuota.${s}\xBB: una fecha de este m\xF3dulo.`);return c.clave},r={proxima:n(e.proxima,"proxima"),periodicidad:"mensual"};if(typeof e.periodicidad=="string"){if(!en.includes(e.periodicidad))throw i(`\xABcuota.periodicidad\xBB: ${en.join(", ")} (o {campo, valores}).`);r.periodicidad=e.periodicidad}else if(nc(e.periodicidad)){let a=e.periodicidad,s=t(a.campo);if(s?.tipo!=="seleccion")throw i("\xABcuota.periodicidad.campo\xBB: una selecci\xF3n de este m\xF3dulo.");if(!nc(a.valores)||!Object.keys(a.valores).length)throw i("\xABcuota.periodicidad.valores\xBB: {opci\xF3n: periodo}.");let c=new Set((s.opciones??[]).map(d=>d.valor));for(let[d,u]of Object.entries(a.valores)){if(!c.has(d))throw i(`\xABcuota.periodicidad.valores\xBB: \xAB${d.slice(0,40)}\xBB no es una opci\xF3n de \xAB${s.etiqueta}\xBB.`);if(!en.includes(u))throw i(`\xABcuota.periodicidad.valores.${d.slice(0,40)}\xBB: ${en.join(", ")}.`)}r.periodicidad={campo:s.clave,valores:a.valores}}else throw i(`\xABcuota.periodicidad\xBB: ${en.join(", ")} o {campo, valores}.`);if(!fh(e.hasta)&&(r.hasta=n(e.hasta,"hasta"),r.hasta===r.proxima))throw i("\xABcuota.hasta\xBB: otra fecha que la pr\xF3xima.");return r}var en,nc,fh,gh=f(()=>{R();en=["semanal","quincenal","mensual","bimestral","trimestral","semestral","anual"],nc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),fh=e=>e==null||e===""});function vh(e,o){if(e==null)return;if(!wh(e))throw i("\xABpapel\xBB: {tipo, campos} o null.");let t=Object.keys(e).find(c=>c!=="tipo"&&c!=="campos"&&c!=="atributos");if(t)throw i(`\xABpapel\xBB: \xAB${t}\xBB no se reconoce.`);let n=typeof e.tipo=="string"?ic[e.tipo]:void 0;if(!n||!Object.hasOwn(ic,e.tipo))throw i(`\xABpapel.tipo\xBB: uno de ${Object.keys(ic).join(", ")}.`);let r=e.campos??{};if(!wh(r))throw i("\xABpapel.campos\xBB: {campo est\xE1ndar: clave del campo}.");let a={};for(let[c,d]of Object.entries(r)){let u=Object.hasOwn(n.campos,c)?n.campos[c]:void 0;if(!u)throw i(`\xABpapel.campos\xBB: \xAB${c}\xBB no es un campo de \xAB${n.etiqueta}\xBB (${Object.keys(n.campos).join(", ")}).`);if(d==null||d==="")continue;let p=o.find(m=>m.clave===d&&!m.archivado);if(!p)throw i(`\xABpapel\xBB: ${u.etiqueta} apunta a \xAB${String(d)}\xBB, que no es un campo vivo de este m\xF3dulo.`);if(!u.tipos.includes(p.tipo))throw i(`\xABpapel\xBB: ${u.etiqueta} tiene que ser un campo de tipo ${u.tipos.join(" o ")} (\xAB${p.etiqueta}\xBB es ${p.tipo}).`);a[c]=p.clave}for(let[c,d]of Object.entries(n.campos))if(d.obligatorio&&!a[c])throw i(`\xABpapel\xBB: falta el campo de ${d.etiqueta}.`);let s=Zv(n,e.atributos,o);return s?{tipo:e.tipo,campos:a,atributos:s}:{tipo:e.tipo,campos:a}}function Zv(e,o,t){if(o==null)return;let n=e.atributos;if(!n)throw i(`\xABpapel.atributos\xBB: \xAB${e.etiqueta}\xBB no tiene atributos.`);if(!Array.isArray(o))throw i("\xABpapel.atributos\xBB: una lista de claves de campo.");if(o.length>n.max)throw i(`\xABpapel.atributos\xBB: como mucho ${n.max}.`);let r=[];for(let a of o){let s=typeof a=="string"?t.find(c=>c.clave===a&&!c.archivado):void 0;if(!s)throw i(`\xABpapel.atributos\xBB: \xAB${String(a)}\xBB no es un campo vivo de este m\xF3dulo.`);if(!n.tipos.includes(s.tipo))throw i(`\xABpapel.atributos\xBB: \xAB${s.etiqueta}\xBB es ${s.tipo}; vale ${n.tipos.join(", ")}.`);r.includes(s.clave)||r.push(s.clave)}return r.length?r:void 0}var bh,Kv,ic,wh,yh=f(()=>{R();bh={nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},correo:{etiqueta:"Correo",tipos:["correo"]},telefono:{etiqueta:"Tel\xE9fono",tipos:["telefono"]},nif:{etiqueta:"NIF",tipos:["texto"]},direccion:{etiqueta:"Direcci\xF3n",tipos:["texto","texto_largo"]}},Kv={nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},precio:{etiqueta:"Precio",tipos:["importe","numero"]},foto:{etiqueta:"Foto",tipos:["url"]},enlace:{etiqueta:"Enlace",tipos:["url"]},stock:{etiqueta:"Stock",tipos:["numero","contador"]},descripcion:{etiqueta:"Descripci\xF3n",tipos:["texto","texto_largo"]},categoria:{etiqueta:"Categor\xEDa",tipos:["seleccion","seleccion_multiple","texto"]},varianteId:{etiqueta:"Id de variante",tipos:["texto","numero"]}},ic={cerradura:{etiqueta:"Cerradura",campos:{nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},identificador:{etiqueta:"Identificador",tipos:["texto","codigo","numero","dispositivo"]},ubicacion:{etiqueta:"Ubicaci\xF3n",tipos:["texto"]}}},dispositivo:{etiqueta:"Dispositivo",campos:{nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},identificador:{etiqueta:"Identificador",tipos:["texto","codigo","dispositivo"]},canal:{etiqueta:"Canal",tipos:["numero"]}}},clientes:{etiqueta:"Clientes",campos:bh},proveedores:{etiqueta:"Proveedores",campos:bh},catalogo:{etiqueta:"Cat\xE1logo",campos:Kv,atributos:{etiqueta:"Atributos",tipos:["texto","seleccion","seleccion_multiple","numero","importe","porcentaje","booleano"],max:16}},producto:{etiqueta:"Producto",campos:{nombre:{etiqueta:"Nombre",tipos:["texto"],obligatorio:!0},sku:{etiqueta:"SKU",tipos:["texto","codigo"]},precio:{etiqueta:"Precio",tipos:["numero","importe"]},existencias:{etiqueta:"Existencias",tipos:["numero","contador"]}}},pedido:{etiqueta:"Pedido",campos:{numero:{etiqueta:"N\xFAmero",tipos:["texto","codigo"]},estado:{etiqueta:"Estado",tipos:["texto","seleccion"]},total:{etiqueta:"Total",tipos:["numero","importe"]}}}},wh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Kr(e,o,t=!1){if(e!=null){if(!Array.isArray(e)||e.length>Nh)throw i(`${o}: el filtro, una lista de hasta ${Nh} condiciones.`);if(e.length)return e.map((n,r)=>{let a=`${o}, condici\xF3n ${r+1}`;if(typeof n!="object"||n===null||Array.isArray(n))throw i(`${a}: {campo, op, valor}.`);let s=n;for(let u of Object.keys(s))if(!["campo","op","valor"].includes(u))throw i(`${a}: clave no admitida \xAB${u.slice(0,40)}\xBB.`);if(typeof s.campo!="string"||!(Ge.test(s.campo)||t&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(s.campo)))throw i(`${a}: \xABcampo\xBB, la clave de un campo del m\xF3dulo que resume.`);if(typeof s.op!="string"||!_h.includes(s.op))throw i(`${a}: \xABop\xBB, una de ${_h.join(", ")}.`);let c=s.op;if(c==="vacio"||c==="no_vacio")return{campo:s.campo,op:c};let d=u=>typeof u=="string"&&u.length<=200||typeof u=="number"&&Number.isFinite(u)||typeof u=="boolean";if(c==="en"||c==="no_en"){if(!Array.isArray(s.valor)||!s.valor.length||s.valor.length>50||!s.valor.every(u=>d(u)&&typeof u!="boolean"))throw i(`${a}: \xAB${c}\xBB lleva una lista de valores (hasta 50).`);return{campo:s.campo,op:c,valor:s.valor}}if(!d(s.valor))throw i(`${a}: \xAB${c}\xBB lleva un valor (texto, n\xFAmero o s\xED/no).`);return{campo:s.campo,op:c,valor:s.valor}})}}function Ah(e,o=!1){if(typeof e=="string"&&(Sh.has(e)||ny.has(e)))throw i(`La clave del m\xF3dulo \xAB${e.slice(0,40)}\xBB es una palabra reservada: usa otra (p. ej. \xAB${e.slice(0,30)}_crm\xBB o un sin\xF3nimo).`);if(typeof e!="string"||!Oh.test(e))throw i(`La clave del m\xF3dulo${typeof e=="string"?` \xAB${e.slice(0,40)}\xBB`:""}: min\xFAsculas y \xAB_\xBB, de 2 a 31, sin palabras reservadas.`);if(e.startsWith("sub_")!==o)throw i(o?"Clave interna no v\xE1lida.":"La clave del m\xF3dulo no puede empezar por \xABsub_\xBB.");return e}function uc(e,o,t=!1){if(typeof e!="object"||e===null||Array.isArray(e))throw i("Definici\xF3n no v\xE1lida.");let n=e,r=Ah(n.clave,t);if(!Array.isArray(n.campos))throw i("Faltan los campos.");let a=n.campos.map((s,c)=>ir(s,c,o,r));if(a.filter(s=>s.esCodigo&&!s.archivado).length>1)throw i("Solo un campo puede ser el c\xF3digo de la ficha.");return a}function Rh(e,o){if(typeof e!="object"||e===null||Array.isArray(e))throw i("Definici\xF3n no v\xE1lida.");let t=e,n=Ah(t.clave,o.interno===!0),r=it(t.nombre,"el nombre",60),a=it(t.nombre_plural??t.nombre,"el nombre en plural",60),s=it(t.descripcion??"","la descripci\xF3n",500,!0),c=typeof t.icono=="string"&&lc.includes(t.icono)?t.icono:"box",d;if(t.color===null||t.color==="")d=null;else if(t.color!==void 0){if(typeof t.color!="string"||!/^#[0-9a-f]{6}$/i.test(t.color))throw i("\xABcolor\xBB: un color #rrggbb.");d=t.color.toLowerCase()}let u=qh(uc(t,o.modulosDelEspacio,o.interno),n,o.camposRelacion);if(u.filter(T=>!T.archivado&&T.opciones?.some(V=>V.hecho)).length>1)throw i("Solo una selecci\xF3n puede marcar estados como \xABhechos\xBB.");if(u.filter(T=>!T.archivado&&T.proximaAccion).length>1)throw i("Solo una fecha puede ser la de la pr\xF3xima acci\xF3n.");let p=new Set;for(let T of u){if(p.has(T.clave))throw i(`El campo \xAB${T.clave}\xBB est\xE1 repetido.`);p.add(T.clave)}let m=u.filter(T=>!T.archivado);for(let T of m)for(let V of As(T)){let le=m.find(_o=>_o.clave===V.relacion);if(!le||le.clave===T.clave||le.tipo!=="relacion"||le.multiple&&!T.multiple)throw i(`\xAB${T.etiqueta}\xBB: un origen m\xFAltiple necesita tambi\xE9n un destino m\xFAltiple.`)}if(gm(m),m.length===0)throw i("El m\xF3dulo necesita al menos un campo.");for(let T of m.filter(V=>V.tipo==="busqueda")){let V=m.find(le=>le.clave===T.desde);if(!V||V.tipo!=="relacion")throw i(`\xAB${T.etiqueta}\xBB: tiene que salir de un campo de relaci\xF3n de este m\xF3dulo.`)}for(let T of m.filter(V=>V.tipo==="qr"&&V.destino==="campo"&&V.campo))if(!m.find(le=>le.clave===T.campo))throw i(`\xAB${T.etiqueta}\xBB: el campo \xAB${T.campo}\xBB no existe en este m\xF3dulo.`);if(m.length>o.topeCampos)throw new z(400,"tope_campos",`Como mucho ${o.topeCampos} campos por m\xF3dulo en tu plan.`,!0,{topePlan:{clave:"campos",tope:o.topeCampos,solicitado:m.length}});for(let T of o.anterior??[]){let V=u.find(le=>le.clave===T.clave);if(!V)throw i(`El campo \xAB${T.etiqueta}\xBB no se quita: se archiva.`);if(V.tipo!==T.tipo&&!py(T.tipo,V.tipo))throw i(`\xAB${T.etiqueta}\xBB no puede pasar de ${T.tipo} a ${V.tipo}.`)}let h=t.articulo==="un"||t.articulo==="una"?t.articulo:null,b=yi(t.ficha,u),y=Xr(t.impresion,u),v=xf(t.validaciones,u.filter(T=>!T.archivado));Af(u);for(let T of u){if(T.tipo!=="contador"||!T.alMarcar)continue;let V=u.find(le=>le.clave===T.alMarcar&&!le.archivado);if(V?.tipo!=="booleano"&&V?.tipo!=="hecho")throw i(`\xAB${T.etiqueta}\xBB: \xABal marcar\xBB tiene que ser un s\xED/no o un \xABhecho\xBB de este m\xF3dulo.`)}let w=of(t.vistas,u),N=Bf(t.conversiones),j=Qf(t.encadenar,u),S=Yf(t.plantillas_hijos),q=uy(t.campo_ambito,u),F=rh(t.publico,u),I=fi(t.recurso,u),_=hi(t.reserva,u),E=oh(t.asignacion,u),g=eh(t.pertenencia,u),x=sh(t.stock,u),O=ph(t.liquidacion,u),k=jm(t.sucesion),D=Em(t.liquidacion_v2,u);if(O&&D)throw i("Elige una versi\xF3n de liquidaci\xF3n por m\xF3dulo.");let B=hh(t.cuota,u),U=qm(t.precios,u),be=$i(t.relacionadas,u),Be=xi(t.siguientes),wr=vh(t.papel,u),X=Xs(t.personas,u);if(t.portal!==void 0&&t.portal!==null&&!["suyos_ver","suyos_anadir","suyos_editar","todos_ver"].includes(t.portal))throw i("\xABportal\xBB: suyos_ver, suyos_anadir, suyos_editar o todos_ver.");let Ue=t.portal??void 0,Ve;if(t.portal_campos!==void 0&&t.portal_campos!==null){let T=t.portal_campos;if(!Ue)throw i("\xABportal_campos\xBB va con \xABportal\xBB.");if(typeof T!="object"||Array.isArray(T)||Object.keys(T).length>u.length)throw i("\xABportal_campos\xBB: clave del campo \u2192 rellenar, ver o no.");for(let[V,le]of Object.entries(T)){if(!u.some(_o=>_o.clave===V))throw i(`\xABportal_campos\xBB: el m\xF3dulo no tiene el campo \xAB${V.slice(0,40)}\xBB.`);if(le!=="rellenar"&&le!=="ver"&&le!=="no")throw i(`\xABportal_campos.${V.slice(0,40)}\xBB: rellenar, ver o no.`)}Ve={...T}}let Lo;if(t.funcionesNativas!==void 0){if(!t.funcionesNativas||typeof t.funcionesNativas!="object"||Array.isArray(t.funcionesNativas)||Object.entries(t.funcionesNativas).some(([T,V])=>!["relacionadas","siguientes"].includes(T)||!Array.isArray(V)||V.length>(T==="relacionadas"?20:5)))throw i("Las funciones nativas necesitan relacionadas o siguientes declarados.");Lo=structuredClone(t.funcionesNativas)}return{clave:n,nombre:r,nombre_plural:a,articulo:h,descripcion:s,icono:c,...d!==void 0?{color:d}:{},campos:kf(Df(u)).map(T=>{if(T.tipo!=="busqueda")return T;let{origen:V,...le}=T;return le}),paginas:t.paginas===!0,...b?{ficha:b}:{},...y?{impresion:y}:{},...v?{validaciones:v}:{},...w?{vistas:w}:{},...N?{conversiones:N}:{},...j?{encadenar:j}:{},...S?{plantillas_hijos:S}:{},...q?{campo_ambito:q}:{},...F?{publico:F}:{},...I?{recurso:I}:{},..._?{reserva:_}:{},...E?{asignacion:E}:{},...g?{pertenencia:g}:{},...x?{stock:x}:{},...O?{liquidacion:O}:{},...k?{sucesion:k}:{},...D?{liquidacion_v2:D}:{},...B?{cuota:B}:{},...U?{precios:U}:{},...be?{relacionadas:be}:{},...Be?{siguientes:Be}:{},...wr?{papel:wr}:{},...X?{personas:X}:{},...Ue?{portal:Ue}:{},...Ve&&Object.keys(Ve).length?{portal_campos:Ve}:{},...Lo?{funcionesNativas:Lo}:{}}}function uy(e,o){if(e==null||e==="")return;let t=o.find(n=>n.clave===e&&!n.archivado);if(!t||!(t.tipo==="seleccion"||t.tipo==="relacion"&&!t.multiple))throw i("\xABcampo_ambito\xBB: una selecci\xF3n o una relaci\xF3n simple de este m\xF3dulo.");return t.clave}function ir(e,o,t,n){if(typeof e!="object"||e===null||Array.isArray(e))throw i(`Campo ${o+1} no v\xE1lido.`);let r=e;if(r.destinos!==void 0){if(r.tipo!=="relacion"||r.multiple===!0||r.camposVinculo!==void 0||!Array.isArray(r.destinos)||!r.destinos.length||r.destinos.length>8||r.destinos.some(y=>typeof y!="string")||new Set(r.destinos).size!==r.destinos.length)throw i("La relaci\xF3n polim\xF3rfica necesita entre 1 y 8 destinos distintos y un solo registro.");let{destinos:u,relacion:p,multiple:m,alBorrar:h,...b}=r;return ir({...b,tipo:"subtabla",polimorfica:!0,columnas:u.map(y=>({clave:`a_${y}`,etiqueta:y,tipo:"relacion",relacion:y,alBorrar:h}))},o,t,n)}if(r.camposVinculo!==void 0){if(r.tipo!=="relacion"||r.multiple!==!0||!Array.isArray(r.camposVinculo)||!r.camposVinculo.length||r.camposVinculo.length>=ac)throw i("Los datos del v\xEDnculo necesitan una relaci\xF3n m\xFAltiple y entre 1 y 29 campos.");let{camposVinculo:u,relacion:p,tipoContacto:m,alBorrar:h,multiple:b,...y}=r;return ir({...y,tipo:"subtabla",vinculo:!0,columnas:[{clave:"destino",etiqueta:r.etiqueta,tipo:"relacion",relacion:p,tipoContacto:m,alBorrar:h,obligatorio:!0},...u]},o,t,n)}if(typeof r.clave=="string"&&Sh.has(r.clave))throw i(`La clave \xAB${r.clave.slice(0,40)}\xBB del campo ${o+1}${n?` de \xAB${n}\xBB`:""} es una palabra reservada: usa otra (p. ej. \xAB${r.clave.slice(0,30)}_campo\xBB o un sin\xF3nimo).`);if(typeof r.clave!="string"||!Ge.test(r.clave))throw i(`La clave del campo ${o+1}${n?` de \xAB${n}\xBB`:""}${typeof r.clave=="string"?` (\xAB${r.clave.slice(0,40)}\xBB)`:""}: min\xFAsculas, n\xFAmeros y \xAB_\xBB, sin palabras reservadas.`);let a=r.tipo;if(!sc.includes(a))throw i(`Tipo de campo no v\xE1lido: ${String(r.tipo)}.`);let s={clave:r.clave,etiqueta:it(r.etiqueta,`la etiqueta del campo ${o+1}`,80),tipo:a};if(r.ajustesNativos!==void 0){if(a!=="relacion"&&a!=="busqueda")throw i("Solo las relaciones y b\xFAsquedas declaradas tienen ajustes nativos.");s.ajustesNativos=cf(r.ajustesNativos);for(let u of Object.values(s.ajustesNativos??{})){let p={...r,...u,ajustesNativos:void 0};for(let[m,h]of Object.entries(u))h===null&&delete p[m];ir(p,o,t,n)}}for(let u of["formulaNativa","defectoNativo"])if(r[u]!==void 0){if(typeof r[u]!="string"||!r[u].trim()||r[u].length>no||u==="formulaNativa"&&a!=="formula")throw i("La variante nativa necesita una f\xF3rmula v\xE1lida y acotada.");s[u]=r[u]}if(r.obligatorio===!0&&(s.obligatorio=!0),s.enTabla=r.enTabla!==!1,r.sensible!==void 0&&typeof r.sensible!="boolean")throw i("\xABsensible\xBB debe ser s\xED o no.");if(r.sensible===!0&&(s.sensible=!0),r.semantica!==void 0){if(!["dato","firma","consentimiento","credencial","auditoria","financiero"].includes(String(r.semantica)))throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");s.semantica=r.semantica}if(r.archivado===!0&&(s.archivado=!0),r.seccion!==void 0&&r.seccion!==""&&(s.seccion=it(r.seccion,"la secci\xF3n",60)),r.ayuda!==void 0&&r.ayuda!==""&&(s.ayuda=it(r.ayuda,"la ayuda",200)),(a==="fecha"||a==="fecha_hora")&&r.proximaAccion===!0&&(s.proximaAccion=!0),a==="numero"&&r.sinMiles===!0&&(s.sinMiles=!0),r.pasoMinutos!==void 0&&r.pasoMinutos!==null){let u=r.pasoMinutos;if(a!=="hora"||typeof u!="number"||!Number.isInteger(u)||u<1||u>60||60%u!==0)throw i(`\xAB${s.etiqueta}\xBB: el paso de la hora, en minutos que dividan la hora (1, 5, 10, 15, 30 o 60).`);u>1&&(s.pasoMinutos=u)}if(r.puertaExtra!==void 0&&typeof r.puertaExtra!="boolean")throw i("\xABpuertaExtra\xBB debe ser s\xED o no.");a==="dispositivo"&&r.conector==="ttlock"&&r.puertaExtra===!0&&(s.puertaExtra=!0);for(let u of["minimo","maximo"])if(r[u]!==void 0&&r[u]!==null){if(typeof r[u]!="number"||!Number.isFinite(r[u]))throw i(`\xAB${u}\xBB tiene que ser un n\xFAmero.`);s[u]=r[u]}if(r.transiciones!==void 0&&a!=="seleccion")throw i("Las transiciones requieren una selecci\xF3n.");if(a==="seleccion"||a==="seleccion_multiple"){if(!Array.isArray(r.opciones)||r.opciones.length===0||r.opciones.length>100)throw i(`\xAB${s.etiqueta}\xBB: entre 1 y 100 opciones.`);let u=new Set;if(s.opciones=r.opciones.map(p=>{let m=typeof p=="string"?{valor:p,etiqueta:p}:p,h=it(m.valor??m.etiqueta,"el valor de una opci\xF3n",80);if(u.has(h))throw i(`\xAB${s.etiqueta}\xBB: la opci\xF3n \xAB${h}\xBB est\xE1 repetida.`);u.add(h);let b={valor:h,etiqueta:it(m.etiqueta??h,"una opci\xF3n",80)};return typeof m.color=="string"&&iy.test(m.color)&&(b.color=m.color),a==="seleccion"&&m.hecho===!0&&(b.hecho=!0),a==="seleccion"&&r.embudo===!0&&Lf(m,b,s.etiqueta),b}),a==="seleccion"&&r.embudo===!0&&(s.embudo=!0),r.transiciones!==void 0){if(a!=="seleccion")throw i("Las transiciones requieren una selecci\xF3n.");s.transiciones=qf(r.transiciones,s)}}if(a==="relacion"){let u=r.relacion;if(!(typeof u=="string"&&(oy.includes(u)||u.startsWith("mod_")&&(t.includes(u.slice(4))||u.slice(4)===n))))throw i(`\xAB${s.etiqueta}\xBB: relaci\xF3n con algo que no existe.`);if(s.relacion=u,r.tipoContacto!==void 0&&r.tipoContacto!==null&&r.tipoContacto!==""){if(u!=="contacts"&&u!=="companies")throw i(`\xAB${s.etiqueta}\xBB: el tipo solo vale en una relaci\xF3n con Personas o Empresas.`);if(typeof r.tipoContacto!="string"||!my.test(r.tipoContacto))throw i(`\xAB${s.etiqueta}\xBB: el tipo no es una clave v\xE1lida.`);s.tipoContacto=r.tipoContacto}if(r.mostrarTareasEnFichaRelacionada===!0){if(r.multiple===!0)throw i(`\xAB${s.etiqueta}\xBB: mostrar tareas relacionadas requiere una relaci\xF3n simple.`);s.mostrarTareasEnFichaRelacionada=!0}}else if(r.mostrarTareasEnFichaRelacionada===!0)throw i(`\xAB${s.etiqueta}\xBB: la opci\xF3n de tareas relacionadas solo sirve en campos de relaci\xF3n.`);if(r.completarDesde!==void 0&&r.completarDesde!==null){if(!["relacion","texto","texto_largo","numero","importe","porcentaje","correo","telefono","url","codigo","fecha","fecha_hora","booleano","seleccion","ubicacion"].includes(a))throw i("Ese tipo de campo no admite autocompletado.");let u=r.completarDesde;if(typeof u!="object"||Array.isArray(u)||Object.keys(u).some(m=>!["relacion","campo","alternativa"].includes(m))||typeof u.relacion!="string"||!Ge.test(u.relacion)||typeof u.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(u.campo))throw i(`\xAB${s.etiqueta}\xBB: completarDesde requiere relacion y campo.`);let p;if(u.alternativa!==void 0){let m=u.alternativa;if(!m||typeof m!="object"||Array.isArray(m)||Object.keys(m).some(h=>h!=="relacion"&&h!=="campo")||typeof m.relacion!="string"||!Ge.test(m.relacion)||typeof m.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(m.campo))throw i("La alternativa de autocompletado necesita relacion y campo.");p={relacion:m.relacion,campo:m.campo}}s.completarDesde={relacion:u.relacion,campo:u.campo,...p?{alternativa:p}:{}}}if(r.completarNativo!==void 0){if(a==="relacion")throw i("La relaci\xF3n conserva su autocompletado en ajustesNativos.");if(r.completarNativo===null)s.completarNativo=null;else{let u=ir({...r,completarDesde:r.completarNativo,completarNativo:void 0},o,t,n).completarDesde;if(!u)throw i("La variante de autocompletado no es v\xE1lida.");s.completarNativo=u}}if((a==="relacion"||a==="archivos")&&r.multiple===!0&&(s.multiple=!0),a==="archivos"&&r.soloImagenes===!0&&(s.soloImagenes=!0),a==="texto_largo"&&r.sinFormato===!0&&(s.sinFormato=!0),(a==="formula"||a==="resumen")&&r.formato!==void 0&&r.formato!==null&&r.formato!=="automatico"){if(r.formato!=="numero"&&r.formato!=="importe"&&r.formato!=="porcentaje")throw i(`\xAB${s.etiqueta}\xBB: el formato es autom\xE1tico, n\xFAmero, importe o porcentaje.`);s.formato=r.formato}if(a==="archivos"&&r.versiones===!0&&(s.versiones=!0),a==="secreto"&&delete s.obligatorio,a==="contador"&&typeof r.alMarcar=="string"&&r.alMarcar){if(!Ge.test(r.alMarcar))throw i(`\xAB${s.etiqueta}\xBB: \xABal marcar\xBB no es un campo v\xE1lido.`);s.alMarcar=r.alMarcar}if(a==="busqueda"){if(typeof r.desde!="string"||!Ge.test(r.desde)||typeof r.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(r.campo))throw i(`\xAB${s.etiqueta}\xBB: elige la relaci\xF3n y el campo que trae.`);if(r.siVacio!==void 0){if(typeof r.siVacio!="string"||!Ge.test(r.siVacio))throw i("La alternativa necesita otra b\xFAsqueda escalar del mismo tipo, sin cadenas.");s.siVacio=r.siVacio}s.desde=r.desde,s.campo=r.campo,delete s.obligatorio}if(a==="relacion"&&r.alBorrar!==void 0&&r.alBorrar!=="avisar"){if(!ey.includes(r.alBorrar))throw i(`\xAB${s.etiqueta}\xBB: \xABal borrar\xBB no v\xE1lido.`);s.alBorrar=r.alBorrar}if(a==="valoracion"){let u=r.maximo===void 0||r.maximo===null?5:r.maximo;if(typeof u!="number"||!Number.isInteger(u)||u<3||u>10)throw i(`\xAB${s.etiqueta}\xBB: entre 3 y 10 estrellas.`);s.maximo=u,delete s.minimo}if(a==="autonumero"){let u=typeof r.prefijo=="string"?r.prefijo.trim():"";if(!/^[A-Za-z0-9_-]{0,10}$/.test(u))throw i(`\xAB${s.etiqueta}\xBB: el prefijo, hasta 10 letras, n\xFAmeros, \xAB-\xBB o \xAB_\xBB.`);let p=r.digitos===void 0||r.digitos===null?4:r.digitos;if(typeof p!="number"||!Number.isInteger(p)||p<1||p>10)throw i(`\xAB${s.etiqueta}\xBB: de 1 a 10 d\xEDgitos.`);u&&(s.prefijo=u),s.digitos=p,r.anual===!0?s.anual=!0:delete s.anual}if(jh.includes(a)&&delete s.obligatorio,a==="subtabla"){if(!Array.isArray(r.columnas)||r.columnas.length===0||r.columnas.length>ac)throw i(`\xAB${s.etiqueta}\xBB: entre 1 y ${ac} columnas.`);let u=new Set(["padre"]);if(s.columnas=r.columnas.map((h,b)=>{let y=ir(h,b,t,n);if(!ly.includes(y.tipo))throw i(`\xAB${s.etiqueta}\xBB: una columna no puede ser de tipo ${y.tipo}.`);if(u.has(y.clave))throw i(`\xAB${s.etiqueta}\xBB: la columna \xAB${y.clave}\xBB est\xE1 repetida o es reservada.`);if(u.add(y.clave),y.tipo==="subtabla"&&1+Eh(y)>xh)throw i(`\xAB${s.etiqueta}\xBB: como mucho ${xh} niveles de subtablas (cap\xEDtulo \u2192 subcap\xEDtulo \u2192 partidas).`);if(y.tipo==="relacion"){if(y.multiple)throw i(`\xAB${s.etiqueta}\xBB: una columna de relaci\xF3n es de un solo registro.`);if(!y.relacion?.startsWith("mod_")&&y.relacion!=="contacts"&&y.relacion!=="companies")throw i(`\xAB${s.etiqueta}\xBB: una columna de relaci\xF3n apunta a un m\xF3dulo, Persona o Empresa.`)}return y}),r.vinculo!==void 0){if(r.vinculo!==!0)throw i("\xABvinculo\xBB debe ser true.");let h=s.columnas[0];if(h?.clave!=="destino"||h.tipo!=="relacion"||h.multiple||h.archivado||!h.obligatorio||s.columnas.slice(1).some(b=>["relacion","subtabla","resumen","formula"].includes(b.tipo)))throw i("El v\xEDnculo necesita primero una relaci\xF3n obligatoria \xABdestino\xBB y despu\xE9s sus campos de datos.");s.vinculo=!0}if(r.polimorfica!==void 0){if(r.polimorfica!==!0||r.vinculo||s.columnas.length>8||s.columnas.some(h=>h.tipo!=="relacion"||h.multiple||h.obligatorio||h.archivado)||new Set(s.columnas.map(h=>h.relacion)).size!==s.columnas.length)throw i("La relaci\xF3n polim\xF3rfica lleva hasta ocho columnas de relaci\xF3n simple opcionales y distintas.");s.polimorfica=!0}for(let h of s.columnas)if(h.tipo==="resumen"&&!s.columnas.some(b=>b.tipo==="subtabla"&&(b.clave===h.de||!!b.hijo&&b.hijo===h.de)))throw i(`\xAB${s.etiqueta}\xBB: el total \xAB${h.etiqueta}\xBB tiene que ser de una subtabla de la l\xEDnea.`);let p=r.columnas;s.columnas=s.columnas.map((h,b)=>{let y=p[b]?.copiar;if(y==null)return h;let v=`\xAB${s.etiqueta}\xBB, columna \xAB${h.etiqueta}\xBB`;if(h.tipo!=="relacion")throw i(`${v}: \xABcopiar\xBB va en una columna de relaci\xF3n.`);if(typeof y!="object"||Array.isArray(y)||Object.keys(y).length>$h)throw i(`${v}: \xABcopiar\xBB, un objeto columna \u2192 campo (hasta ${$h}).`);for(let[w,N]of Object.entries(y)){let j=s.columnas.find(S=>S.clave===w);if(!j||j.tipo==="relacion"||j.tipo==="formula")throw i(`${v}: \xAB${w.slice(0,40)}\xBB no es una columna que se pueda rellenar.`);if(typeof N!="string"||!Ge.test(N))throw i(`${v}: el campo de \xAB${w}\xBB no es v\xE1lido.`)}return Object.keys(y).length?{...h,copiar:{...y}}:h}),s.columnas=s.columnas.map((h,b)=>{let y=p[b]?.rellenar;if(y==null)return h;let v=`\xAB${s.etiqueta}\xBB, columna \xAB${h.etiqueta}\xBB`;if(h.tipo!=="articulo")throw i(`${v}: \xABrellenar\xBB va en una columna de art\xEDculo.`);if(typeof y!="object"||Array.isArray(y)||Object.keys(y).length>Ch.length*2)throw i(`${v}: \xABrellenar\xBB, un objeto columna \u2192 dato del art\xEDculo.`);for(let[w,N]of Object.entries(y)){let j=s.columnas.find(S=>S.clave===w);if(!j||["relacion","articulo","formula","subtabla","resumen"].includes(j.tipo))throw i(`${v}: \xAB${w.slice(0,40)}\xBB no es una columna que se pueda rellenar.`);if(!Ch.includes(N))throw i(`${v}: \xAB${w.slice(0,40)}\xBB se rellena con nombre, referencia, codigo, precio o iva_pct.`)}return Object.keys(y).length?{...h,rellenar:{...y}}:h}),typeof r.hijo=="string"&&cy.test(r.hijo)&&(s.hijo=r.hijo);let m=Zm(r.impresion,s.columnas);m&&(s.impresion=m),delete s.obligatorio}if(a==="autonumero"){let u=Si(r.visibleSi,s.etiqueta);u&&(s.visibleSi=u)}if(!af({tipo:a})){let u=Si(r.visibleSi,s.etiqueta);u&&(s.visibleSi=u);let p=Si(r.obligatorioSi,s.etiqueta);if(p&&(s.obligatorioSi=p),r.patron!==void 0&&r.patron!==null&&r.patron!==""){if(!wf.includes(a))throw i(`\xAB${s.etiqueta}\xBB: un patr\xF3n solo vale para textos, correos, tel\xE9fonos, webs y c\xF3digos.`);let h=yf(r.patron,s.etiqueta);h&&(s.patron=h)}if(r.unico===!0){if(!vf.includes(a))throw i(`\xAB${s.etiqueta}\xBB: \xAB\xFAnico\xBB solo vale para textos, correos, tel\xE9fonos, webs, c\xF3digos y n\xFAmeros.`);s.unico=!0}if(r.esCodigo===!0){if(!s.unico)throw i(`\xAB${s.etiqueta}\xBB: el c\xF3digo de la ficha tiene que ser \xFAnico.`);s.esCodigo=!0}let m=_f(r.porDefecto,s);m&&(s.porDefecto=m)}let c=Ph(r.permisos,s.etiqueta);if(c&&(s.permisos=c),r.grupo!==void 0&&r.grupo!==null&&r.grupo!==""){if(typeof r.grupo!="string"||!ay.test(r.grupo))throw i(`\xAB${s.etiqueta}\xBB: el grupo, en min\xFAsculas y sin espacios (p. ej. \xABfinanzas\xBB).`);s.grupo=r.grupo}if(r.enmascarado===!0){if(!sy.includes(a))throw i(`\xAB${s.etiqueta}\xBB: solo se enmascaran textos, correos, tel\xE9fonos y c\xF3digos.`);s.enmascarado=!0}let d=Of(r.depende,s);if(d&&(s.depende=d),a==="archivo"&&(s.enTabla=!1,delete s.obligatorio),a==="boton"){let u=r.automatizacion;if(typeof u!="number"||!Number.isSafeInteger(u)||u<=0)throw i(`\xAB${s.etiqueta}\xBB: elige la automatizaci\xF3n del bot\xF3n.`);s.automatizacion=u,s.enTabla=!1,delete s.obligatorio}if(a==="formula"){if(typeof r.formula!="string"||!r.formula.trim()||r.formula.length>no)throw i(`\xAB${s.etiqueta}\xBB: escribe la f\xF3rmula (hasta ${no} caracteres).`);s.formula=r.formula.trim(),delete s.obligatorio}if(a==="resumen"){let u=r.calculo;if(typeof r.de!="string"||!Oh.test(r.de)||typeof r.via!="string"||!Ge.test(r.via)||!cc.includes(u))throw i(`\xAB${s.etiqueta}\xBB: elige de qu\xE9 m\xF3dulo, por qu\xE9 relaci\xF3n y qu\xE9 c\xE1lculo.`);if(s.de=r.de,s.via=r.via,s.calculo=u,u!=="recuento"){if(typeof r.campo!="string"||!Ge.test(r.campo))throw i(`\xAB${s.etiqueta}\xBB: elige el campo que resume.`);s.campo=r.campo}if(u==="media_ponderada"){if(typeof r.peso!="string"||!Ge.test(r.peso))throw i(`\xAB${s.etiqueta}\xBB: elige el campo que pondera la media.`);s.peso=r.peso}else delete s.peso;let p=Kr(r.filtro,`\xAB${s.etiqueta}\xBB`);p?s.filtro=p:delete s.filtro,delete s.obligatorio}if(a==="dispositivo"){if(!ty.includes(r.conector))throw i(`\xAB${s.etiqueta}\xBB: elige de qu\xE9 conexi\xF3n es el aparato (TTLock o Shelly).`);s.conector=r.conector}if(a==="qr"){let u=r.destino==="campo"||typeof r.campo=="string"&&r.campo&&r.destino!=="ficha"?"campo":"ficha";if(s.destino=u,u==="campo"){if(typeof r.campo!="string"||!Ge.test(r.campo))throw i(`\xAB${s.etiqueta}\xBB: elige el campo que resalta al escanear.`);s.campo=r.campo}else delete s.campo;delete s.obligatorio}return s}var sc,jh,cc,_h,Nh,ey,oy,ty,ry,Sh,ny,lc,Ge,Oh,iy,ay,sy,it,cy,ly,$h,xh,Eh,Ch,ac,dy,py,my,af,Zr=f(()=>{Sm();Rm();km();mf();Qs();bm();R();wi();Nf();Th();Ws();Cf();Ef();Pf();zf();Uf();Gf();Kf();nh();ks();th();ch();mh();gh();Ci();yh();kh();sc=["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","seleccion_multiple","etiquetas","url","correo","telefono","relacion","archivos","archivo","busqueda","resumen","duracion","hecho","porcentaje","valoracion","contador","cronometro","secreto","color","ubicacion","checklist","codigo","firma","hora","articulo","dispositivo","creado_el","creado_por","modificado_el","modificado_por","autonumero","formula","subtabla","boton","qr"],jh=["creado_el","creado_por","modificado_el","modificado_por","autonumero"],cc=["recuento","suma","minimo","maximo","ultimo","media","media_ponderada"],_h=["igual","distinto","en","no_en","vacio","no_vacio","mayor","menor"],Nh=5;ey=["avisar","desvincular","impedir"],oy=["companies","contacts","deals"],ty=["ttlock","shelly"],ry=["id","numero","sales_id","creado","actualizado","espacio_id","modulo_id","datos","_color_tarjeta"],Sh=new Set([...ry,"q","filter","sort","order","page","perpage","limit","offset","select","from","where","insert","update","delete","drop","table","union","join","and","or","not","null","true","false","order","group","having","into","values","create","alter","grant","revoke","truncate","exec","execute","function","user","listar","ver","crear","actualizar","borrar","enlazar","buscar","exportar","importar","confirmar","idempotencia","operacion","tools","list","call","resources","prompts","__proto__","constructor","prototype","es_plantilla"]),ny=new Set(["companies","contacts","deals","sales","tasks","tags","notas","tareas","empresas","contactos","oportunidades","formularios","ajustes","miembros","configuracion","modulos","registros","objetos","adjuntos","api","rpc","v1","mcp"]),lc=["box","boxes","package","folder","folder-open","file-text","clipboard-list","list-checks","calendar","calendar-days","clock","map-pin","truck","car","wrench","hammer","hard-hat","building","home","store","warehouse","factory","briefcase","shopping-cart","receipt","wallet","credit-card","piggy-bank","tag","tags","star","heart","flag","bookmark","user","users","graduation-cap","stethoscope","pill","utensils","coffee","shirt","camera","image","monitor","smartphone","server","database","key","shield","leaf","paw-print","dumbbell","ticket","gift","megaphone","mail","phone","message-square"],Ge=/^[a-z][a-z0-9_]{0,40}$/,Oh=/^[a-z][a-z_]{1,30}$/,iy=/^#[0-9a-fA-F]{6}$/,ay=/^[a-z][a-z_]{0,29}$/,sy=["texto","correo","telefono","codigo"],it=(e,o,t,n=!1)=>{if(typeof e!="string")throw i(`Falta ${o}.`);let r=e.trim();if(!n&&!r||r.length>t)throw i(`${o}: entre ${n?0:1} y ${t} caracteres.`);return r};cy=/^sub_[a-z]{8}$/,ly=["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","url","correo","telefono","duracion","porcentaje","valoracion","color","codigo","formula","hora","relacion","articulo","subtabla","resumen"],$h=20,xh=3,Eh=e=>e.tipo!=="subtabla"?0:1+Math.max(0,...(e.columnas??[]).map(o=>Eh(o))),Ch=["nombre","referencia","codigo","precio","iva_pct"],ac=30;dy=[["texto","texto_largo"],["texto_largo","texto"],["texto","seleccion"],["seleccion","texto"],["numero","importe"],["importe","numero"],["texto","correo"],["texto","telefono"],["texto","url"],["correo","texto"],["telefono","texto"],["url","texto"],["fecha","fecha_hora"],["texto","dispositivo"],["dispositivo","texto"]],py=(e,o)=>dy.some(([t,n])=>t===e&&n===o),my=/^[a-z0-9][a-z0-9-]{0,59}$/;af=e=>e.tipo==="busqueda"||e.tipo==="resumen"||e.tipo==="formula"||e.tipo==="subtabla"||e.tipo==="boton"||e.tipo==="qr"||e.tipo==="archivo"||jh.includes(e.tipo)});function Mh(e){let o=Do(),t=(e==="contacts"?fy:hy).map(([n,r])=>({clave:n,etiqueta:so(o,r),tipo:["correo","correo_facturacion"].includes(n)?"correo":["telefono","phone_number"].includes(n)?"telefono":["background","description"].includes(n)?"texto_largo":n==="website"?"url":"texto",obligatorio:n==="first_name"||n==="name",...gy(e).has(n)?{}:{permisos:{administrador:"lectura",miembro:"lectura",lectura:"lectura"}}}));return{id:0,clave:`@${e}`,nombre:so(o,e==="contacts"?"Persona":"Empresa"),nombre_plural:so(o,e==="contacts"?"Personas":"Empresas"),descripcion:"",icono:e==="contacts"?"users":"building-2",estado:"publicado",campos:t}}var Pi,fy,hy,gy,Ih=f(()=>{fn();Pi=[["address","Direcci\xF3n"],["zipcode","C\xF3digo postal"],["city","Ciudad"],["country","Pa\xEDs"]],fy=[["first_name","Nombre"],["last_name","Apellidos"],["title","Cargo"],["correo","Correo"],["telefono","Tel\xE9fono"],...Pi,["background","Contexto"],["nif","Identificador fiscal"],["pais_fiscal","Pa\xEDs fiscal"]],hy=[["name","Nombre"],["phone_number","Tel\xE9fono"],["website","Web"],...Pi,["description","Descripci\xF3n"],["persona_first_name","Nombre de la persona"],["correo_facturacion","Correo de facturaci\xF3n"],["tax_identifier","Identificador fiscal"],["razon_social","Raz\xF3n social"],["pais_fiscal","Pa\xEDs fiscal"]],gy=e=>new Set(e==="contacts"?["first_name","last_name","title","telefono",...Pi.map(([o])=>o),"background"]:["name","phone_number","website",...Pi.map(([o])=>o),"description","persona_first_name"])});function Gr(e){let o=new Map(Qr(e)?Mh(e).campos.map(a=>[a.clave,a.etiqueta]):[]),t={ubicacion:"Ubicaci\xF3n",nif:"Identificador fiscal",birthday:"Fecha de nacimiento",iban:"IBAN",province:"Provincia",state_abbr:"Provincia",has_newsletter:"Comunicaciones"},n=(Nm.find(a=>a.clave===e)?.campos??[]).map(a=>({...a,...o.has(a.clave)?{etiqueta:o.get(a.clave)}:Object.hasOwn(t,a.clave)?{etiqueta:so(Do(),t[a.clave])}:{}})),r=Qr(e)?yy(e).map(a=>({...a,etiqueta:so(Do(),a.etiqueta),editable:!1,ordenable:!1,filtrable:!1,enTabla:!1})):[];return[...n,...r,...e==="companies"?wy.map(a=>({...a,etiqueta:so(Do(),a.etiqueta),editable:!1,ordenable:!1,filtrable:!1,enTabla:!1})):[]]}var Qr,by,wy,vy,yy,vi=f(()=>{$m();Ih();fn();Qr=e=>e==="contacts"||e==="companies",by=[{clave:"nombre",tipo:"texto",etiqueta:"Nombre completo"},{clave:"direccion",tipo:"texto",etiqueta:"Direcci\xF3n completa"},{clave:"correo",tipo:"correo",etiqueta:"Primer correo"},{clave:"correo_trabajo",tipo:"correo",etiqueta:"Correo del trabajo"},{clave:"correo_personal",tipo:"correo",etiqueta:"Correo personal"},{clave:"telefono",tipo:"telefono",etiqueta:"Primer tel\xE9fono"},{clave:"telefono_trabajo",tipo:"telefono",etiqueta:"Tel\xE9fono del trabajo"},{clave:"telefono_personal",tipo:"telefono",etiqueta:"Tel\xE9fono personal"}],wy=[{clave:"persona.first_name",tipo:"texto",etiqueta:"Nombre"},{clave:"persona.last_name",tipo:"texto",etiqueta:"Apellidos"},{clave:"persona.correo",tipo:"correo",etiqueta:"Correo"},{clave:"persona.telefono",tipo:"telefono",etiqueta:"Tel\xE9fono"}],vy=[{clave:"persona_referencia_id",tipo:"relacion",etiqueta:"Persona de referencia",relacion:"contacts"},{clave:"persona_first_name",tipo:"texto",etiqueta:"Nombre de la persona"},{clave:"persona_last_name",tipo:"texto",etiqueta:"Apellidos de la persona"},{clave:"persona_correo",tipo:"correo",etiqueta:"Correo de la persona"},{clave:"persona_telefono",tipo:"telefono",etiqueta:"Tel\xE9fono de la persona"}],yy=e=>[...by.filter(o=>e==="contacts"||["nombre","direccion"].includes(o.clave)),...e==="companies"?vy:[]]});function qh(e,o,t){let n=(a,s,c,d)=>{if(a.tipo!=="busqueda"||a.archivado)return a;let u=`${c}.${a.clave}`;if(d.length>=2||d.includes(u))throw i(`\xAB${a.etiqueta}\xBB: solo se encadena una b\xFAsqueda a un nivel.`);let p=s.find(b=>b.clave===a.desde&&!b.archivado&&b.tipo==="relacion");if(!p?.relacion)return a;let m=p.relacion,h;if(m.startsWith("mod_")){let b=m.slice(4),y=b===o?e:t?.get(b);if(!y)return a;if(h=y.find(v=>v.clave===a.campo&&!v.archivado),!h)throw i(`\xAB${a.etiqueta}\xBB: el campo que trae ya no existe al otro lado.`);h=n(h,y,b,[...d,u])}else{let b=Gr(m).find(y=>y.clave===a.campo)??t?.get(`@${m}`)?.find(y=>y.clave===a.campo&&!y.archivado);if(!b&&Ee(a.campo)&&!t?.has(`@${m}`))return a;if(!b)throw i(`\xAB${a.etiqueta}\xBB: ese campo no existe en ${m}.`);h={clave:a.campo,etiqueta:a.etiqueta,tipo:b.tipo,...Array.isArray(b.opciones)?{opciones:b.opciones}:{},...b.relacion?{relacion:b.relacion}:{},..."origen"in b&&b.origen?{origen:b.origen}:{}}}if(h.tipo==="archivos")throw i(`\xAB${a.etiqueta}\xBB: los ficheros no se traen en una b\xFAsqueda.`);if(h.tipo==="secreto")throw i(`\xAB${a.etiqueta}\xBB: un secreto no se trae en una b\xFAsqueda.`);if(h.tipo==="formula")throw i(`\xAB${a.etiqueta}\xBB: una f\xF3rmula no se trae en una b\xFAsqueda.`);if(h.tipo==="busqueda"){let b=h.origen;if(!b)throw i(`\xAB${a.etiqueta}\xBB: el campo que trae no est\xE1 listo.`);if(b.encadenada)throw i(`\xAB${a.etiqueta}\xBB: solo se encadena una b\xFAsqueda a un nivel.`);return{...a,origen:{...b,encadenada:!0}}}return{...a,origen:{tipo:h.tipo,...h.opciones?{opciones:h.opciones}:{},...h.relacion?{relacion:h.relacion}:{}}}},r=e.map(a=>n(a,e,o,[]));return _y(r),r}function _y(e){let o=new Set(["texto","texto_largo","correo","telefono","url","codigo","numero","importe","porcentaje","fecha","fecha_hora","booleano"]);for(let t of e.filter(n=>!n.archivado&&n.tipo==="busqueda"&&n.siVacio)){let n=e.find(a=>a.clave===t.siVacio&&!a.archivado),r=a=>!e.find(s=>s.clave===a.desde)?.multiple;if(!n||n===t||n.tipo!=="busqueda"||n.siVacio||!r(t)||!r(n)||!t.origen||!n.origen||!o.has(t.origen.tipo)||t.origen.tipo!==n.origen.tipo||t.origen.encadenada||n.origen.encadenada)throw i("La alternativa necesita otra b\xFAsqueda escalar del mismo tipo, sin cadenas.")}}var kh=f(()=>{Ur();R();vi()});function Ee(e){if(typeof e!="string"||!/^datos\.[a-z][a-z0-9_]{0,40}$/.test(e))return null;let o=e.slice(6);return o==="tipos"?null:o}function ff(e,o,t){let n=r=>{let a=Object.hasOwn(o,r.campo)?Ee(o[r.campo]):null;if(!a)throw i("La condici\xF3n del campo propio necesita otro campo propio de la misma ra\xEDz.");return{...r,campo:a}};return e.filter(r=>!r.archivado&&Object.hasOwn(o,r.clave)&&Ee(o[r.clave])).map(r=>{if(r.tipo==="relacion"&&(Object.keys(r.copiar??{}).length||r.mostrarTareasEnFichaRelacionada||r.alBorrar&&r.alBorrar!=="avisar")||r.porDefecto||r.depende||r.completarDesde||r.alMarcar||r.embudo||r.transiciones||r.opciones?.some(u=>u.requisito||u.pide?.length||u.limiteDias!==void 0||u.aprobacion))throw i("El campo propio necesita conservar sus reglas antes de convertir la ra\xEDz.");let s=[{campo:"tipos",op:"igual",valor:t},...(r.visibleSi??[]).map(n)];if(s.length>10)throw i("El campo propio supera las diez condiciones al a\xF1adir su tipo.");let c=r.tipo==="busqueda"?Ee(o[r.desde??""]):null,d=r.siVacio?Ee(o[r.siVacio]):null;if(r.tipo==="busqueda"&&(!c||r.siVacio&&!d))throw i("La b\xFAsqueda propia necesita relaciones y alternativas propias de la misma ra\xEDz.");return{...structuredClone(r),...c?{desde:c}:{},...d?{siVacio:d}:{},clave:Ee(o[r.clave]),visibleSi:s,...r.obligatorioSi?{obligatorioSi:r.obligatorioSi.map(n)}:{}}})}var Ur=f(()=>{R()});function Ph(e,o){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new z(400,"peticion_invalida",`\xAB${o}\xBB: permisos no v\xE1lidos.`);let t={};for(let[n,r]of Object.entries(e))if(!(r==null||r==="normal")){if(!xy(n))throw new z(400,"peticion_invalida",`\xAB${o}\xBB: el papel \xAB${n.slice(0,30)}\xBB no se puede restringir.`);if(!Ny.includes(r))throw new z(400,"peticion_invalida",`\xAB${o}\xBB: nivel de permiso no v\xE1lido.`);t[n]=r}return Object.keys(t).length?t:void 0}var Ny,$y,xy,pz,dc,mz,Th=f(()=>{li();R();Ny=["oculto","lectura"],$y=["administrador","miembro","lectura"],xy=e=>$y.includes(e)||/^p_[a-z]{1,12}$/.test(e),pz=A`coalesce(current_setting('app.extension', true), '') <> ''`,dc=class extends Map{get(){return"no"}},mz=new dc});function Lh(e){if(!e||typeof e!="object"||Array.isArray(e))throw i("F\xF3rmula proyectada no v\xE1lida.");let o=e;if(Object.keys(o).some(a=>!["expresion","campos"].includes(a))||typeof o.expresion!="string"||o.expresion.length>2e3||!Array.isArray(o.campos)||o.campos.length>40)throw i("F\xF3rmula proyectada no v\xE1lida.");let t=["texto","texto_largo","correo","telefono","url","codigo","color","numero","importe","duracion","porcentaje","valoracion","fecha","fecha_hora","booleano","seleccion","ubicacion","formula"],n=new Set,r=o.campos.map(a=>{if(!a||typeof a!="object"||typeof a.clave!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(a.clave)||n.has(a.clave)||typeof a.etiqueta!="string"||a.etiqueta.length>80||!t.includes(a.tipo)||a.tipo==="formula"&&(typeof a.formula!="string"||a.formula.length>2e3))throw i("F\xF3rmula proyectada no v\xE1lida.");return n.add(a.clave),{clave:a.clave,etiqueta:a.etiqueta,tipo:a.tipo,...a.tipo==="formula"?{formula:a.formula}:{}}});return{expresion:o.expresion,campos:r}}var Dh=f(()=>{R()});function zh(e){if(!e||typeof e!="object"||Array.isArray(e))throw i("Resumen proyectado no v\xE1lido.");let o=e;if(Object.keys(o).some(t=>!["fuente","tipo","via","calculo","campo","peso","filtro"].includes(t))||o.tipo!==void 0&&(!["contacts","companies"].includes(o.fuente)||typeof o.tipo!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(o.tipo))||typeof o.fuente!="string"||!/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/.test(o.fuente)||!cc.includes(o.calculo)||[o.via,...o.calculo!=="recuento"?[o.campo]:[],...o.calculo==="media_ponderada"?[o.peso]:[]].some(t=>typeof t!="string"||!(/^[a-z][a-z0-9_]{0,40}$/.test(t)||["contacts","companies"].includes(o.fuente)&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(t))))throw i("Resumen proyectado no v\xE1lido.");Kr(o.filtro,"Resumen")}var Fh=f(()=>{R();Zr()});function Wh(e,o){if(!Array.isArray(e)||!e.length||e.length>100||e.some(t=>!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(n=>!["campo","es","etiqueta","valor"].includes(n))||typeof t.valor!="string"||t.valor.length>100||(t.etiqueta!==void 0?typeof t.etiqueta!="string"||!t.etiqueta||t.etiqueta.length>60||t.campo!==void 0||t.es!==void 0:typeof t.campo!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(t.campo)||typeof t.es!="string"||t.es.length>100))||o!==void 0&&(typeof o!="string"||o.length>100))throw i("Casos de proyecci\xF3n no v\xE1lidos.")}var Bh=f(()=>{R()});var Uh,Vh=f(()=>{Uh=/^funciones\.[a-z0-9][a-z0-9-]{0,59}\.[a-z][a-z0-9_]{0,40}$/});function ar(e){if(e===void 0)return;if(JSON.stringify(e).length>6e4)throw i("La fuente combinada es demasiado grande.");if(!Array.isArray(e)||e.length<1||e.length>4)throw i("Una fuente combinada necesita de uno a cuatro or\xEDgenes.");let o=new Set;return e.map(t=>{if(!To(t)||Object.keys(t).some(r=>!["fuente","filtro","campos"].includes(r))||typeof t.fuente!="string"||!jy.test(t.fuente)||o.has(t.fuente))throw i("Origen combinado no v\xE1lido o repetido.");if(o.add(t.fuente),t.filtro!==void 0&&(!To(t.filtro)||JSON.stringify(t.filtro).length>4e3))throw i("Filtro de origen no v\xE1lido.");if(!To(t.campos)||Object.keys(t.campos).length>40)throw i("Proyecci\xF3n de origen no v\xE1lida.");let n=Object.fromEntries(Object.entries(t.campos).map(([r,a])=>{if(!Cy.test(r)||["id","objeto"].includes(r)||!To(a)||Object.keys(a).some(c=>!["resumen","formula","permiso","casos","defecto","campo","soloFiltro","valor","alternativas","conversiones","condicion","equivalencias","etiqueta","opciones"].includes(c))||["campo","valor","alternativas","condicion","casos","resumen","formula"].filter(c=>Object.hasOwn(a,c)).length!==1||a.campo!==void 0&&(typeof a.campo!="string"||a.campo.length>125)||Object.hasOwn(a,"valor")&&a.valor!==null&&!["string","number","boolean"].includes(typeof a.valor)||a.alternativas!==void 0&&(!Array.isArray(a.alternativas)||a.alternativas.length!==2||a.alternativas.some(c=>typeof c!="string"||c.length>125))||a.condicion!==void 0&&(!To(a.condicion)||JSON.stringify(a.condicion).length>4e3)||a.conversiones!==void 0&&(!To(a.conversiones)||!Array.isArray(a.alternativas)||Object.entries(a.conversiones).some(([c,d])=>!a.alternativas.includes(c)||!To(d)||Object.keys(d).length>100||Object.values(d).some(u=>typeof u!="string")))||a.permiso!==void 0&&(typeof a.permiso!="string"||!Uh.test(a.permiso)||!["contacts","companies"].includes(t.fuente)||!a.formula&&!a.resumen)||a.soloFiltro!==void 0&&typeof a.soloFiltro!="boolean"||a.etiqueta!==void 0&&(typeof a.etiqueta!="string"||a.etiqueta.length>80)||a.opciones!==void 0&&(!To(a.opciones)||Object.keys(a.opciones).length>100||Object.values(a.opciones).some(c=>typeof c!="string"))||a.equivalencias!==void 0&&(!To(a.equivalencias)||!a.campo||Object.keys(a.equivalencias).length>100||Object.values(a.equivalencias).some(c=>typeof c!="string")))throw i("Campo de proyecci\xF3n no v\xE1lido.");a.resumen!==void 0&&zh(a.resumen);let s=a.formula===void 0?void 0:Lh(a.formula);if(a.casos!==void 0)Wh(a.casos,a.defecto);else if(a.defecto!==void 0)throw i("El defecto necesita casos de proyecci\xF3n.");return[r,{...structuredClone(a),...s?{formula:s}:{}}]}));return{fuente:t.fuente,campos:n,...t.filtro?{filtro:structuredClone(t.filtro)}:{}}})}var To,Cy,jy,Ti=f(()=>{Dh();Fh();Bh();R();Vh();To=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Cy=/^[a-z][a-z0-9_]{0,40}$/,jy=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/});function Gh(e){let o=_e(e,"definici\xF3n");ze(o,["titulo","fuente","origenes","metrica","agrupar","dividir","filtro","periodo","grafico","top","comparar","meta","tendencia","ejes_burbujas",...Jh],"definici\xF3n");let t=Re(o.fuente,"fuente",60),n=ar(o.origenes);if(t==="combinada"!=!!n)throw i("La fuente combinada necesita sus or\xEDgenes.");if(t!=="combinada"&&!mc.includes(t)&&!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(t))throw i("\xABfuente\xBB no v\xE1lida.");let r=_e(o.metrica,"metrica");ze(r,["tipo","campo","por","filtro_a","filtro_b"],"metrica");let a=He(r.tipo,pc,"metrica.tipo"),s={tipo:a,...r.campo!==void 0?{campo:Re(r.campo,"metrica.campo",60)}:{},...r.por!==void 0?{por:Re(r.por,"metrica.por",60)}:{},...r.filtro_a!==void 0&&r.filtro_a!==null?{filtro_a:_e(r.filtro_a,"metrica.filtro_a")}:{},...r.filtro_b!==void 0&&r.filtro_b!==null?{filtro_b:_e(r.filtro_b,"metrica.filtro_b")}:{}};if(["suma","media","min","max","minimo","maximo","mediana"].includes(a)&&!s.campo)throw i("Esa m\xE9trica necesita un campo.");if(a==="tasa_conversion"&&(r.filtro_a===void 0||r.filtro_b===void 0))throw i("\xABtasa_conversion\xBB necesita \xABfiltro_a\xBB y \xABfiltro_b\xBB.");if((a==="media_por"||a==="valor_medio_por")&&!s.por)throw i("\xABmedia_por\xBB necesita indicar el campo \xABpor\xBB para dividir.");let c;if(o.agrupar!==void 0&&o.agrupar!==null){let q=_e(o.agrupar,"agrupar");ze(q,["campo","paso"],"agrupar"),c={campo:Re(q.campo,"agrupar.campo",60),...q.paso!==void 0?{paso:He(q.paso,sr,"agrupar.paso")}:{}}}let d;if(o.dividir!==void 0&&o.dividir!==null){let q=_e(o.dividir,"dividir");ze(q,["campo","paso"],"dividir"),d={campo:Re(q.campo,"dividir.campo",60),...q.paso!==void 0?{paso:He(q.paso,sr,"dividir.paso")}:{}}}if(d&&!c)throw i("\xABDividir por\xBB solo se puede usar si se agrupa.");if(c&&d&&c.campo===d.campo)throw i("No se puede agrupar y dividir por el mismo campo.");let u;if(o.meta!==void 0&&o.meta!==null){if(typeof o.meta!="number"||Number.isNaN(o.meta)||o.meta<=0)throw i("\xABmeta\xBB: n\xFAmero mayor que 0.");u=o.meta}let p=o.periodo!==void 0&&o.periodo!==null?fc(o.periodo):void 0,m=He(o.grafico,Sy,"grafico"),h={},b={doble_eje:m==="combinado",etiquetas:["barras","barras_horizontales","barras_100","barras_apiladas","barras_agrupadas","cascada","dona","tarta","embudo"].includes(m),zoom:!!c?.paso&&["barras","barras_100","barras_apiladas","barras_agrupadas","lineas","area","area_apilada","area_100","varias_lineas","combinado","cascada"].includes(m),escalonada:m==="lineas"||m==="varias_lineas"};for(let q of Jh){let F=o[q];if(F!==void 0){if(typeof F!="boolean")throw i(`\xAB${q}\xBB: s\xED o no.`);if(!b[q])throw i(`\xAB${q}\xBB no se admite en este gr\xE1fico.`);h[q]=F}}let y;if(m==="burbujas"){let q=_e(o.ejes_burbujas,"ejes_burbujas");ze(q,["x","z"],"ejes_burbujas"),y={x:Re(q.x,"ejes_burbujas.x",60),z:Re(q.z,"ejes_burbujas.z",60)}}else if(o.ejes_burbujas!==void 0)throw i("\xABejes_burbujas\xBB solo se usa en burbujas.");let v=["numero","medidor","numero_tendencia"],w=["cascada","treemap","barras_radiales","burbujas","barras","barras_horizontales","lineas","area","dona","tabla","embudo","tarta","radar","dispersion"],N=["sankey","area_apilada","area_100","barras_100","barras_apiladas","barras_agrupadas","varias_lineas","tabla_dinamica","mapa_calor","combinado"];if(v.includes(m)){if(c)throw i("Un n\xFAmero no se agrupa.");if(d)throw i("Un n\xFAmero no se divide.");if(m==="medidor"&&u===void 0)throw i("El medidor necesita una \xABmeta\xBB num\xE9rica.");if(m==="numero_tendencia"&&!p)throw i("\xABnumero_tendencia\xBB necesita un periodo.")}else if(w.includes(m)){if(!c)throw i("Ese gr\xE1fico necesita \xABagrupar\xBB.");if(d)throw i("Ese gr\xE1fico no admite \xABdividir por\xBB.")}else if(N.includes(m)){if(!c)throw i("Ese gr\xE1fico necesita \xABagrupar\xBB.");if(!d)throw i("Ese gr\xE1fico necesita \xABdividir por\xBB un segundo campo.")}if((m==="area_apilada"||m==="area_100")&&!c?.paso)throw i("Las \xE1reas apiladas requieren agrupar por fecha.");if(o.tendencia!==void 0&&typeof o.tendencia!="boolean")throw i("\xABtendencia\xBB: s\xED o no.");if(o.tendencia&&(m!=="tabla"||!c?.paso))throw i("\xABtendencia\xBB requiere una tabla agrupada por fecha.");if(o.top!==void 0&&(!Number.isSafeInteger(o.top)||o.top<1||o.top>Qh))throw i(`\xABtop\xBB: de 1 a ${Qh}.`);let j=o.comparar==null||typeof o.comparar=="boolean"?o.comparar:He(o.comparar,Oy,"comparar");if(typeof j=="string"&&m!=="numero"&&m!=="numero_tendencia"&&(!["barras","lineas","area","varias_lineas"].includes(m)||!c?.paso))throw i("\xABcomparar\xBB requiere agrupar por fecha en un gr\xE1fico temporal.");if(o.comparar&&!p)throw i("Para comparar hace falta un periodo.");if(o.comparar&&p?.proximos)throw i("\xABproximos\xBB no se compara (no hay periodo anterior).");if(typeof j=="string"&&p&&!p.ultimos&&(!p.desde||!p.hasta))throw i("Para comparar hacen falta las dos fechas del periodo.");if(o.comparar&&p?.preset)throw i("\xABpreset\xBB no se compara (todav\xEDa no se ha acabado).");let S=o.filtro===void 0||o.filtro===null?void 0:_e(o.filtro,"filtro");if(S&&JSON.stringify(S).length>4e3)throw i("\xABfiltro\xBB demasiado grande.");return{titulo:Re(o.titulo??"","titulo"),fuente:t,...n?{origenes:n}:{},metrica:s,...y?{ejes_burbujas:y}:{},...c?{agrupar:c}:{},...d?{dividir:d}:{},...u!==void 0?{meta:u}:{},...S?{filtro:S}:{},...p?{periodo:p}:{},grafico:m,...h,...o.top!==void 0?{top:o.top}:{},...j||j===null?{comparar:j}:{},...o.tendencia?{tendencia:!0}:{}}}function fc(e){let o=_e(e,"periodo");ze(o,["campo","ultimos","proximos","preset","desde","hasta"],"periodo");let t={campo:Re(o.campo,"periodo.campo",60)};if(o.preset!==void 0&&(t.preset=He(o.preset,Ay,"periodo.preset")),o.ultimos!==void 0){let r=_e(o.ultimos,"periodo.ultimos");if(ze(r,["n","unidad"],"periodo.ultimos"),!Number.isSafeInteger(r.n)||r.n<1||r.n>3660)throw i("\xABperiodo.ultimos.n\xBB no v\xE1lido.");t.ultimos={n:r.n,unidad:He(r.unidad,sr,"periodo.ultimos.unidad")}}for(let r of["desde","hasta"])if(o[r]!==void 0){if(typeof o[r]!="string"||!Ey.test(o[r])||Number.isNaN(Date.parse(o[r])))throw i(`\xABperiodo.${r}\xBB: AAAA-MM-DD.`);t[r]=o[r]}if(o.proximos!==void 0){let r=_e(o.proximos,"periodo.proximos");if(ze(r,["n","unidad"],"periodo.proximos"),!Number.isSafeInteger(r.n)||r.n<1||r.n>3660)throw i("\xABperiodo.proximos.n\xBB no v\xE1lido.");t.proximos={n:r.n,unidad:He(r.unidad,sr,"periodo.proximos.unidad")}}let n=[!!t.ultimos,!!t.proximos,!!t.preset,!!(t.desde||t.hasta)].filter(Boolean).length;if(!n)throw i("\xABperiodo\xBB: di \xABultimos\xBB, \xABproximos\xBB, \xABpreset\xBB o \xABdesde\xBB/\xABhasta\xBB.");if(n>1)throw i("\xABperiodo\xBB: solo una de \xABultimos\xBB, \xABproximos\xBB, \xABpreset\xBB o \xABdesde\xBB/\xABhasta\xBB.");return t}var pc,Sy,sr,mc,Oy,Jh,Ay,Qh,Ey,_e,ze,He,Re,hc=f(()=>{Ti();R();pc=["recuento","suma","media","min","max","minimo","maximo","mediana","porcentaje_total","acumulado","tasa_conversion","media_por","valor_medio_por"],Sy=["numero","cascada","treemap","sankey","barras_radiales","burbujas","barras","lineas","dona","tabla","barras_horizontales","barras_100","barras_apiladas","barras_agrupadas","area","area_apilada","area_100","varias_lineas","embudo","medidor","numero_tendencia","tabla_dinamica","mapa_calor","tarta","radar","dispersion","combinado"],sr=["dia","semana","mes","anio"],mc=["companies","contacts","deals","tareas","proyectos"],Oy=["anterior","anio_anterior"],Jh=["escalonada","zoom","etiquetas","doble_eje"],Ay=["hoy","semana","mes","trimestre","anio"],Qh=50,Ey=/^\d{4}-\d{2}-\d{2}$/,_e=(e,o)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw i(`\xAB${o}\xBB tiene que ser un objeto.`);return e},ze=(e,o,t)=>{for(let n of Object.keys(e))if(!o.includes(n))throw i(`\xAB${t}\xBB: clave no admitida \xAB${n.slice(0,40)}\xBB.`)},He=(e,o,t)=>{if(typeof e!="string"||!o.includes(e))throw i(`\xAB${t}\xBB no v\xE1lido.`);return e},Re=(e,o,t=80)=>{if(typeof e!="string"||e.length>t)throw i(`\xAB${o}\xBB no v\xE1lido.`);return e}});var gc,Hh=f(()=>{gc=["nada","recientes","vistas"]});function Xh(e,o,t){if(e===void 0)return[];if(!Array.isArray(e)||e.length>o.length)throw i("Fuentes de m\xF3dulo no v\xE1lidas.");let n=new Set;return e.map(r=>{if(!bc(r)||typeof r.modulo!="string"||n.has(r.modulo)||typeof r.conexion!="string"||!t.some(d=>d.clave===r.conexion&&d.tipo==="api")||typeof r.operacion!="string"||!/^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$/.test(r.operacion)||r.filas!==""&&!Mi(r.filas)||!bc(r.mapeo))throw i("La fuente necesita un m\xF3dulo, una conexi\xF3n API, una operaci\xF3n y un mapeo.");let a=o.find(d=>d.clave===r.modulo),s=Object.entries(r.mapeo);if(!a||a.personas||!s.length||s.some(([d,u])=>!a.campos.some(p=>p.clave===d&&qy(p))||!Mi(u)))throw i("La fuente debe mapear campos de datos de un m\xF3dulo propio.");n.add(r.modulo);let c={modulo:r.modulo,conexion:r.conexion,operacion:r.operacion,filas:r.filas,mapeo:Object.fromEntries(s)};if(r.modo==="vivo")return{...c,modo:r.modo};if(r.modo!=="espejo"||typeof r.minutos!="number"||!Number.isInteger(r.minutos)||r.minutos<5||r.minutos>10080||!Mi(r.id_externo)||!bc(r.cursor)||!Mi(r.cursor.ruta)||typeof r.cursor.parametro!="string"||!/^[a-zA-Z_][a-zA-Z0-9_.-]{0,79}$/.test(r.cursor.parametro))throw i("El espejo necesita una clave externa, un cursor y un intervalo entre 5 minutos y 7 d\xEDas.");return{...c,modo:r.modo,minutos:r.minutos,id_externo:r.id_externo,cursor:{ruta:r.cursor.ruta,parametro:r.cursor.parametro}}})}var Ry,Mi,bc,qy,Yh=f(()=>{R();Ry=new Set(["texto","texto_largo","correo","telefono","codigo","numero","importe","fecha","fecha_hora","booleano","seleccion"]),Mi=e=>typeof e=="string"&&e.length<=160&&/^[a-zA-Z_][a-zA-Z0-9_-]*(\.[a-zA-Z_][a-zA-Z0-9_-]*){0,7}$/.test(e),bc=e=>!!e&&typeof e=="object"&&!Array.isArray(e),qy=e=>!e.archivado&&Ry.has(e.tipo)});function Kh(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>20)throw i("La soluci\xF3n admite hasta 20 conexiones.");let o=new Set;return e.map(t=>{if(!ky(t)||typeof t.clave!="string"||!/^[a-z][a-z0-9_]{0,39}$/.test(t.clave)||["constructor","prototype"].includes(t.clave)||o.has(t.clave)||typeof t.nombre!="string"||!t.nombre.trim()||t.nombre.length>120||t.tipo!=="api"&&t.tipo!=="mcp")throw i("Requisito de conexi\xF3n no v\xE1lido.");return o.add(t.clave),{clave:t.clave,nombre:t.nombre.trim(),tipo:t.tipo}})}var ky,Zh=f(()=>{R();ky=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});function Ii(e){return typeof e=="number"?Number.isInteger(e)&&e>=1&&e<=2147483647:typeof e=="string"&&e.length<=120&&eg.test(e)}function og(e,o){let t=c=>eg.exec(typeof c=="number"?`${c}.0.0`:c),n=t(e),r=t(o);for(let c=1;c<=3;c++){let d=BigInt(n[c])-BigInt(r[c]);if(d)return d>0?1:-1}if(!n[4]||!r[4])return+!n[4]-+!r[4];let a=n[4].split("."),s=r[4].split(".");for(let c=0;c<Math.min(a.length,s.length);c++){let d=a[c],u=s[c];if(d===u)continue;let p=/^\d+$/.test(d),m=/^\d+$/.test(u);return p&&m?BigInt(d)>BigInt(u)?1:-1:p!==m?p?-1:1:d>u?1:-1}return a.length-s.length}var eg,wc=f(()=>{eg=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][\da-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][\da-zA-Z-]*))*))?(?:\+([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?$/});function tg(e,o){if(e===void 0)return;if(!vc(e)||Object.keys(e).some(r=>r!=="desde"&&r!=="pasos")||!Ii(e.desde)||og(e.desde,o)>=0||!Array.isArray(e.pasos)||!e.pasos.length||e.pasos.length>50)throw i("La migraci\xF3n necesita una versi\xF3n anterior y entre 1 y 50 pasos.");let t=new Set,n=e.pasos.map(r=>{if(!vc(r)||Object.keys(r).some(m=>!["tipo","modulo","origen","destino","conversion","equivalencias"].includes(m))||r.tipo!=="renombrar"&&r.tipo!=="convertir"&&r.tipo!=="mover"||!yc(r.modulo)||!yc(r.origen)||!yc(r.destino))throw i("Paso de migraci\xF3n inv\xE1lido.");let{tipo:a,modulo:s,origen:c,destino:d,conversion:u,equivalencias:p}=r;if(a==="convertir"&&(typeof u!="string"||!Py.has(u)))throw i("Conversi\xF3n de migraci\xF3n desconocida.");if(a!=="convertir"&&(u!==void 0||c===d))throw i("El paso necesita dos campos distintos.");if(u==="seleccion"?!vc(p)||!Object.keys(p).length||Object.values(p).some(m=>typeof m!="string"||!m):p!==void 0)throw i("La conversi\xF3n a selecci\xF3n necesita una tabla de equivalencias.");for(let m of new Set([c,d])){let h=`${s}:${m}`;if(t.has(h))throw i("Cada campo puede participar en un solo paso por versi\xF3n.");t.add(h)}return{tipo:a,modulo:s,origen:c,destino:d,...u?{conversion:u}:{},...p?{equivalencias:p}:{}}});return{desde:e.desde,pasos:n}}var vc,yc,Py,rg=f(()=>{R();wc();vc=e=>!!e&&typeof e=="object"&&!Array.isArray(e),yc=e=>typeof e=="string"&&/^[a-z][a-z0-9_]{0,59}$/.test(e),Py=new Set(["numero","seleccion","fecha"])});function ng(e){let o=cr(e,["version","origen","entidades"]);if(o.version!==1)throw i("Perfil relacional inv\xE1lido.");let t=on(o.entidades,60).map(r=>{let a=cr(r,["clave","destino","clave_externa","campos","referencias","procedencia","responsable","tipos","tiposColumna","acl","archivos"]);if(typeof a.destino!="string"||!(["contacts","companies","deals"].includes(a.destino)||/^mod_[a-z][a-z0-9_]{0,40}$/.test(a.destino)))throw i("Perfil relacional inv\xE1lido.");let s=Object.fromEntries(Object.entries(cr(a.campos)).map(([b,y])=>(_c(b),[b,lr(y)])));if(Object.keys(s).length>100)throw i("Perfil relacional inv\xE1lido.");let c=on(a.referencias??[],30).map(b=>{let y=cr(b,["campo","entidad","clave","obligatoria"]);if(y.obligatoria!==void 0&&typeof y.obligatoria!="boolean")throw i("Perfil relacional inv\xE1lido.");return{campo:_c(y.campo),entidad:Li(y.entidad),clave:Nc(y.clave),obligatoria:y.obligatoria===!0}}),d=a.archivos===void 0?void 0:on(a.archivos,20).map(b=>{let y=cr(b,["campo","columna","obligatorio"]);if(y.obligatorio!==void 0&&typeof y.obligatorio!="boolean")throw i("Perfil relacional inv\xE1lido.");return{campo:_c(y.campo),columna:lr(y.columna),obligatorio:y.obligatorio===!0}});if(d?.length&&!a.destino.startsWith("mod_"))throw i("Perfil relacional inv\xE1lido.");let u=[...(d??[]).map(b=>b.campo),...Object.keys(s),...c.map(b=>b.campo)];if(new Set(u).size!==u.length)throw i("Perfil relacional inv\xE1lido.");let p=a.procedencia===void 0?void 0:Object.fromEntries(Object.entries(cr(a.procedencia,["autor","creado","actualizado"])).map(([b,y])=>[b,lr(y)])),m=a.responsable===void 0?void 0:Nc(a.responsable),h=a.tipos===void 0?void 0:on(a.tipos,20).map(b=>{if(typeof b!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(b))throw i("Perfil relacional inv\xE1lido.");return b});if(h&&!["contacts","companies"].includes(a.destino))throw i("Perfil relacional inv\xE1lido.");if(a.tiposColumna!==void 0&&(!h?.length||new Set(h).size!==h.length))throw i("Perfil relacional inv\xE1lido.");return{clave:Li(a.clave),...a.acl!==void 0?{acl:lr(a.acl)}:{},...d?{archivos:d}:{},destino:a.destino,...p?{procedencia:p}:{},...m?{responsable:m}:{},...h?{tipos:h}:{},...a.tiposColumna!==void 0?{tiposColumna:lr(a.tiposColumna)}:{},clave_externa:Nc(a.clave_externa),campos:s,referencias:c}}),n=new Map(t.map(r=>[r.clave,r]));if(!t.length||n.size!==t.length||t.some(r=>r.referencias.some(a=>!n.has(a.entidad)||n.get(a.entidad).clave_externa.length!==a.clave.length)))throw i("Perfil relacional inv\xE1lido.");return{version:1,origen:Li(o.origen),entidades:t}}var Li,_c,lr,cr,on,Nc,ig=f(()=>{R();Li=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,60}$/.test(e))throw i("Perfil relacional inv\xE1lido.");return e},_c=e=>{let o=typeof e=="string"&&/^datos\.[a-z][a-z0-9_]{0,60}$/.test(e)?e:Li(e);if(["id","sales_id","espacio_id","modulo_id","creado_por","actualizado_por","responsable_id"].includes(o))throw i("Perfil relacional inv\xE1lido.");return o},lr=e=>{if(typeof e!="string"||!/^[a-zA-Z][a-zA-Z0-9_]{0,79}$/.test(e)||/password|passwd|token|(^|_)pin($|_)|secret/i.test(e)||["constructor","prototype","__proto__"].includes(e))throw i("Perfil relacional inv\xE1lido.");return e},cr=(e,o)=>{if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(t=>["__proto__","constructor","prototype"].includes(t)||o&&!o.includes(t)))throw i("Perfil relacional inv\xE1lido.");return e},on=(e,o)=>{if(!Array.isArray(e)||e.length>o)throw i("Perfil relacional inv\xE1lido.");return e},Nc=e=>{let o=on(e,3).map(lr);if(!o.length||new Set(o).size!==o.length)throw i("Perfil relacional inv\xE1lido.");return o}});function ag(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>30)throw i("Perfiles de importaci\xF3n inv\xE1lidos.");let o=new Set;return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(r=>!["clave","perfil"].includes(r)))throw i("Perfiles de importaci\xF3n inv\xE1lidos.");let n=t;if(typeof n.clave!="string"||!/^[a-z][a-z0-9_]{0,60}$/.test(n.clave)||o.has(n.clave))throw i("Perfiles de importaci\xF3n inv\xE1lidos.");return o.add(n.clave),{clave:n.clave,perfil:ng(n.perfil)}})}var sg=f(()=>{R();ig()});function cg(e,o){if(o==null||o==="")return null;if(!["contacts","companies"].includes(e)||typeof o!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(o))throw i("El \xE1mbito de tipo necesita Personas o Empresas y una clave v\xE1lida.");return o}var lg=f(()=>{R()});function fg(e,o){if(e===null)return null;if(!Mo(e))throw i("La disposici\xF3n no es v\xE1lida.");if(!Dy.test(o))throw i("Esta tabla no admite widgets.");for(let d of Object.keys(e))if(d!=="zonas"&&d!=="widgets")throw i("La disposici\xF3n no es v\xE1lida.");if(!Mo(e.zonas))throw mg();let t=e.zonas,n=Mo(e.widgets)?e.widgets:{};for(let d of Object.keys(t))if(!ug.includes(d))throw i("Zona no v\xE1lida.");let r={},a=new Set;for(let d of ug){let u=t[d]??[];if(!Array.isArray(u))throw i("Zona no v\xE1lida.");r[d]=u.map(p=>{if(typeof p!="string"||p!==$c&&!Ly.test(p))throw i("Bloque no v\xE1lido.");if(a.has(p))throw i("Un bloque solo puede estar en un sitio.");return a.add(p),p})}if(!a.has($c))throw mg();if(r.arriba.length>pg)throw i(`Arriba caben como mucho ${pg} bloques.`);let s={};for(let[d,u]of Object.entries(n)){if(!a.has(d))continue;if(!Mo(u))throw i("Widget no v\xE1lido.");let p=Gh(u.definicion);if(u.via!==void 0&&(typeof u.via!="string"||!zy.test(u.via)))throw i("\xABvia\xBB no v\xE1lida.");if(u.via===void 0&&p.fuente!==o)throw i("Un widget de esta tabla solo mide esta tabla o sus relaciones.");s[d]={definicion:p,seguir_filtros:u.seguir_filtros!==!1,...u.via!==void 0?{via:u.via}:{}}}for(let d of a)if(d!==$c&&!s[d])throw i("Falta la definici\xF3n de un widget.");if(Object.keys(s).length>dg)throw i(`Como mucho ${dg} widgets por vista.`);let c={zonas:r,widgets:s};if(JSON.stringify(c).length>6e4)throw i("La disposici\xF3n es demasiado grande.");return c}function Fy(e){if(!(e==null||e==="")){if(typeof e!="string"||!/^[a-z0-9][a-z0-9_:.-]{0,79}$/.test(e))throw i("El \xE1mbito de la vista no es v\xE1lido.");return e}}function hg(e){if(!Mo(e))throw i("La vista no es v\xE1lida.");let o=Mo(e.pref)?Object.fromEntries(Object.entries(e.pref).filter(([d])=>My.has(d))):{};if(o.vistaOrigen!==void 0&&(typeof o.vistaOrigen!="string"||o.vistaOrigen.length>160))throw i("La vista de origen no es v\xE1lida.");if(o.vista!==void 0&&!Iy.has(String(o.vista)))throw i("El tipo de vista no es v\xE1lido.");let t=Mo(e.filtros)?e.filtros:{};if(Object.keys(t).length>40||Object.keys(t).some(d=>!/^[a-zA-Z0-9_@.:-]{1,80}$/.test(d)))throw i("Los filtros de la vista no son v\xE1lidos.");let n=null;if(Mo(e.orden)){let{field:d,order:u}=e.orden;if(typeof d!="string"||!/^[a-zA-Z0-9_.]{1,80}(,[a-zA-Z0-9_.]{1,80}){0,2}$/.test(d)||typeof u!="string"||!/^(ASC|DESC)(,(ASC|DESC)){0,2}$/.test(u))throw i("El orden de la vista no es v\xE1lido.");n={field:d,order:u}}let r=e.origenes===void 0?void 0:ar(e.origenes),a;if(r||e.columnasCalculadas!==void 0){if(!r||r.length!==1||!["contacts","companies"].includes(r[0].fuente)||!Mo(e.columnasCalculadas)||Object.keys(e.columnasCalculadas).length>40||Object.entries(e.columnasCalculadas).some(([d,u])=>!/^calc_[a-f0-9]{24}$/.test(d)||typeof u!="string"||!Object.hasOwn(r[0].campos,u)))throw i("Columnas calculadas de vista no v\xE1lidas.");a=e.columnasCalculadas}let s=Fy(e.ambito),c={pref:o,filtros:t,orden:n,...s?{ambito:s}:{},...r?{origenes:r,columnasCalculadas:a}:{}};if(JSON.stringify(c).length>3e4)throw i("La vista es demasiado grande.");return c}var Ty,My,Iy,ug,$c,Ly,dg,pg,Dy,zy,mg,Mo,gg=f(()=>{Ti();R();hc();Ty=/^(contacts|companies|deals|tareas|proyectos|mod_(?!sub_)[a-z][a-z0-9_]{1,40})$/,My=new Set(["vistaOrigen","vista","visibles","orden","anchos","fijadas","calculos","agrupar","grupo","vistas","separar"]),Iy=new Set(["tabla","lista","kanban","calendario","galeria","linea","mapa"]),ug=["arriba","izquierda","centro","derecha","abajo"],$c="tabla",Ly=/^w_[a-z0-9]{1,24}$/,dg=24,pg=6,Dy=Ty,zy=/^[a-z][a-z0-9_]{0,59}$/,mg=()=>new z(400,"tabla_obligatoria","La tabla no se puede quitar de la vista: mu\xE9vela, pero d\xE9jala.");Mo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function bg(e){let o=new Set,t=n=>{typeof n=="string"&&n.startsWith("mod_")&&o.add(n.slice(4))};if(xc(e.personas)&&t(e.personas.modulo),Array.isArray(e.secciones)){for(let n of e.secciones)if(xc(n)&&(t(n.modulo),Array.isArray(n.camino)))for(let r of n.camino)xc(r)&&t(r.modulo)}return o}var xc,wg=f(()=>{xc=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});function Uy(e){if(typeof e!="string"||!By.test(e))throw i("\xABrecurso\xBB: contacts, companies, deals o mod_<clave>.");return e}function Vy(e){if(!Wy.includes(e))throw i("\xABcanal\xBB: whatsapp o correo.");return e}function vg(e,o="Plantilla"){if(!e||typeof e!="object"||Array.isArray(e))throw i(`${o}: un objeto.`);let t=e;for(let s of Object.keys(t))if(!["recurso","tipoContacto","canal","nombre","asunto","texto"].includes(s))throw i(`${o}: clave no admitida \xAB${s.slice(0,40)}\xBB.`);let n=Uy(t.recurso);if(t.tipoContacto!==void 0&&t.tipoContacto!==null&&(!Qr(n)||typeof t.tipoContacto!="string"||!/^[a-z0-9][a-z0-9-]{0,59}$/.test(t.tipoContacto)))throw i("El tipo de una plantilla necesita Personas o Empresas y una clave de tipo v\xE1lida.");let r=Vy(t.canal),a=r==="correo"?Cc(t.asunto,`${o}, asunto`,300,!1):void 0;return{recurso:n,...t.tipoContacto?{tipoContacto:t.tipoContacto}:{},canal:r,nombre:Cc(t.nombre,`${o}, nombre`,80),...a?{asunto:a}:{},texto:Cc(t.texto,`${o}, texto`,5e3)}}var Wy,Di,By,Cc,jc=f(()=>{vi();R();Wy=["whatsapp","correo"],Di=50,By=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/,Cc=(e,o,t,n=!0)=>{if(e==null||e===""){if(n)throw i(`${o}: obligatorio.`);return}if(typeof e!="string"||e.trim().length>t)throw i(`${o}: un texto de hasta ${t} caracteres.`);return e.trim()}});function Ng(e){let o=_e(e,"informe");ze(o,["fuente","origenes","filtro","periodo","columnas","agrupar","agregados","orden"],"informe");let t=Re(o.fuente,"fuente",60),n=ar(o.origenes);if(t==="combinada"!=!!n)throw i("La fuente combinada necesita sus or\xEDgenes.");if(t!=="combinada"&&!mc.includes(t)&&!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(t))throw i("\xABfuente\xBB no v\xE1lida.");let r={fuente:t,...n?{origenes:n}:{}};if(o.filtro!==void 0&&o.filtro!==null&&(r.filtro=_e(o.filtro,"filtro"),JSON.stringify(r.filtro).length>4e3))throw i("\xABfiltro\xBB demasiado grande.");if(o.periodo!==void 0&&o.periodo!==null&&(r.periodo=fc(o.periodo)),o.columnas!==void 0&&o.columnas!==null){if(!Array.isArray(o.columnas)||o.columnas.length>yg)throw i(`\xABcolumnas\xBB: una lista de hasta ${yg}.`);r.columnas=[...new Set(o.columnas.map((a,s)=>Re(a,`columnas[${s}]`,60)))]}if(o.agrupar!==void 0&&o.agrupar!==null){let a=_e(o.agrupar,"agrupar");ze(a,["campo","paso"],"agrupar"),r.agrupar={campo:Re(a.campo,"agrupar.campo",60),...a.paso!==void 0?{paso:He(a.paso,sr,"agrupar.paso")}:{}}}if(o.agregados!==void 0&&o.agregados!==null){if(!Array.isArray(o.agregados)||o.agregados.length>_g)throw i(`\xABagregados\xBB: una lista de hasta ${_g}.`);r.agregados=o.agregados.map((a,s)=>{let c=_e(a,`agregados[${s}]`);ze(c,["tipo","campo"],`agregados[${s}]`);let d=He(c.tipo,pc,`agregados[${s}].tipo`);if(d!=="recuento"&&c.campo===void 0)throw i(`\xABagregados[${s}]\xBB: esa operaci\xF3n necesita un campo.`);return{tipo:d,...d!=="recuento"?{campo:Re(c.campo,`agregados[${s}].campo`,60)}:{}}})}if(r.agrupar&&!r.agregados?.length&&(r.agregados=[{tipo:"recuento"}]),o.orden!==void 0&&o.orden!==null){let a=_e(o.orden,"orden");ze(a,["por","sentido"],"orden"),r.orden={por:Re(a.por,"orden.por",60),sentido:He(a.sentido??"asc",["asc","desc"],"orden.sentido")}}return r}var yg,_g,$g=f(()=>{Ti();R();hc();yg=30,_g=6});var Sc,Jy,xg,Cg=f(()=>{Sc=[{clave:"leo",nombre:"Leo",puesto:"Marketing"},{clave:"marina",nombre:"Marina",puesto:"Administrativa"},{clave:"dario",nombre:"Dar\xEDo",puesto:"Comercial"},{clave:"nora",nombre:"Nora",puesto:"Finanzas"},{clave:"irene",nombre:"Irene",puesto:"Consultora de procesos"}],Jy=e=>`pix.agente_${e}`,xg=e=>Sc.some(o=>Jy(o.clave)===e)});var jg,Sg=f(()=>{jg=["contacts","companies","deals","tareas","proyectos"]});function Og(e,o,t){if(typeof e!="string"||!e.trim())throw i(`Falta \xAB${o}\xBB.`);let n=e.trim();if(n.length>t)throw i(`\xAB${o}\xBB: como mucho ${t} caracteres.`);return n}function Ag(e){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw i("\xABpix\xBB: un objeto.");let o=e;for(let r of Object.keys(o))if(r!=="personalidad")throw i(`\xABpix\xBB: no admite \xAB${r.slice(0,40)}\xBB.`);let t=o.personalidad;if(!t||typeof t!="object"||Array.isArray(t))throw i("\xABpix.personalidad\xBB: un objeto con nombre e instrucciones.");let n=t;for(let r of Object.keys(n))if(r!=="nombre"&&r!=="instrucciones")throw i(`\xABpix.personalidad\xBB: no admite \xAB${r.slice(0,40)}\xBB.`);return{personalidad:{nombre:Og(n.nombre,"pix.personalidad.nombre",Gy),instrucciones:Og(n.instrucciones,"pix.personalidad.instrucciones",Qy)}}}var Qy,Gy,Eg=f(()=>{R();Qy=2e3,Gy=60});function Rg(e,o){if(e===void 0)return[];if(!Array.isArray(e)||e.length>tn)throw i(`\xABinformes\xBB: una lista de hasta ${tn}.`);let t=new Set;return e.map((n,r)=>{if(!Hy(n))throw i(`Informe ${r+1}: un objeto.`);for(let c of Object.keys(n))if(!["nombre","descripcion","definicion"].includes(c))throw i(`Informe ${r+1}: clave no admitida \xAB${c.slice(0,40)}\xBB.`);if(typeof n.nombre!="string"||!n.nombre.trim()||n.nombre.length>80)throw i(`Informe ${r+1}: un nombre de hasta 80 caracteres.`);if(n.descripcion!==void 0&&(typeof n.descripcion!="string"||n.descripcion.length>500))throw i(`Informe ${r+1}: la descripci\xF3n, hasta 500 caracteres.`);let a=n.nombre.trim();if(t.has(a))throw i(`Dos informes se llaman \xAB${a}\xBB.`);t.add(a);let s=Ng(n.definicion);if([s.fuente,...s.origenes?.map(c=>c.fuente)??[]].some(c=>c.startsWith("mod_")&&!o.includes(c.slice(4))))throw i(`Informe \xAB${a}\xBB: su fuente no es un m\xF3dulo de la soluci\xF3n.`);return{nombre:a,...n.descripcion?{descripcion:n.descripcion}:{},definicion:s}})}var tn,Hy,Oc=f(()=>{R();$g();tn=30,Hy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var qg,vo,ur,dr,oe,Ac,pr,PF,Xy,zi,Yy,Ky,TF,MF,kg=f(()=>{Cg();qg={ver:["si","no","suyos","equipo","ambito","jerarquia"],editar:["si","no","suyos","equipo","ambito","jerarquia"],borrar:["si","no","suyos","equipo","ambito","jerarquia"],exportar:["si","no","suyos"],importar:["si","no"],crear:["si","no","suyos","equipo","ambito","jerarquia"],reasignar:["si","no","suyos","jerarquia"],estado:["si","no","suyos","equipo","ambito","jerarquia"],descargar:["si","no"],revelar:["si","no"]},vo=["si","no","suyos"],ur=["si","no","suyos","equipo","jerarquia"],dr=["si","no","suyos","jerarquia"],oe=["si","no"],Ac=(e,o,t=!0)=>[{clave:`${e}.ver`,descripcion:`Ver ${o}`,valores:dr},{clave:`${e}.crear`,descripcion:`Dar de alta ${o}`,valores:dr},{clave:`${e}.editar`,descripcion:`Editar ${o}`,valores:dr},{clave:`${e}.reasignar`,descripcion:`Cambiar el responsable de ${o}`,valores:dr},...t?[{clave:`${e}.estado`,descripcion:`Cambiar el estado de ${o}`,valores:dr}]:[],{clave:`${e}.descargar`,descripcion:`Bajar los ficheros de ${o}`,valores:oe},{clave:`${e}.borrar`,descripcion:`Borrar ${o}`,valores:dr},{clave:`${e}.exportar`,descripcion:`Exportar ${o}`,valores:vo},{clave:`${e}.importar`,descripcion:`Importar ${o} desde una hoja`,valores:oe}],pr=[...Ac("contactos","contactos"),...Ac("empresas","empresas",!1),...Ac("oportunidades","oportunidades"),{clave:"proyectos.ver",descripcion:"Ver proyectos",valores:ur},{clave:"proyectos.editar",descripcion:"Editar los datos del proyecto",valores:ur},{clave:"proyectos.borrar",descripcion:"Borrar proyectos",valores:ur},{clave:"proyectos.exportar",descripcion:"Exportar proyectos",valores:vo},{clave:"proyectos.crear",descripcion:"Crear proyectos",valores:oe},{clave:"proyectos.gestionar",descripcion:"Cambiar el estado, el responsable, los participantes, las columnas y los ajustes de los proyectos, y gestionar plantillas",valores:oe},{clave:"tareas.ver",descripcion:"Ver tareas",valores:ur},{clave:"tareas.crear",descripcion:"Crear tareas",valores:oe},{clave:"tareas.editar",descripcion:"Editar y completar tareas",valores:ur},{clave:"tareas.borrar",descripcion:"Borrar tareas",valores:ur},{clave:"tareas.exportar",descripcion:"Exportar tareas visibles",valores:vo},{clave:"notas.ver",descripcion:"Ver notas",valores:vo},{clave:"notas.editar",descripcion:"Escribir, editar y borrar notas",valores:vo},{clave:"adjuntos.ver",descripcion:"Ver y descargar adjuntos",valores:vo},{clave:"adjuntos.subir",descripcion:"Subir adjuntos",valores:vo},{clave:"miembros.gestionar",descripcion:"Invitar, cambiar el papel y desactivar miembros",valores:oe},{clave:"conectores.accionar",descripcion:"Ejecutar acciones f\xEDsicas de conectores",valores:oe},{clave:"configuracion.gestionar",descripcion:"Cambiar la configuraci\xF3n del espacio y los permisos",valores:oe},{clave:"formularios.gestionar",descripcion:"Crear, editar y borrar formularios (y sus respuestas)",valores:oe},{clave:"formularios.ver_respuestas",descripcion:"Ver las respuestas de los formularios",valores:vo},{clave:"modulos.configurar",descripcion:"Dise\xF1ar, publicar y archivar m\xF3dulos",valores:oe},{clave:"paneles.ver",descripcion:"Ver los paneles de m\xE9tricas",valores:oe},{clave:"paneles.editar",descripcion:"Crear, cambiar y borrar paneles de m\xE9tricas",valores:oe},{clave:"paneles.compartir",descripcion:"Compartir paneles con el equipo y cambiar o borrar los de equipo",valores:oe},{clave:"automatizaciones.gestionar",descripcion:"Crear y cambiar automatizaciones, y ver sus ejecuciones",valores:oe},{clave:"campanas.gestionar",descripcion:"Crear y enviar campa\xF1as de correo, y gestionar consentimientos y supresiones",valores:oe},{clave:"agenda.ver",descripcion:"Ver las citas de la agenda",valores:vo},{clave:"agenda.editar",descripcion:"Crear, mover y cancelar citas",valores:vo},{clave:"agenda.configurar",descripcion:"Configurar la agenda: tipos de cita, d\xEDas cerrados, horarios, reserva p\xFAblica y los recursos (horarios y aprobar ausencias)",valores:oe},{clave:"analisis.ver",descripcion:"Usar An\xE1lisis: informes de lo que ya puede ver",valores:oe},{clave:"analisis.compartir",descripcion:"Compartir informes con el equipo y cambiar o borrar los de equipo",valores:oe},{clave:"secretos.ver",descripcion:"Ver los campos secretos (cada vez queda registrado qui\xE9n lo vio)",valores:oe},{clave:"liquidaciones.gestionar",descripcion:"Generar, aprobar, cerrar, pagar y reabrir liquidaciones de comisiones",valores:oe},{clave:"portales.gestionar",descripcion:"Configurar los portales, invitar a ellos y revocar el acceso",valores:oe},{clave:"auditoria.ver",descripcion:"Ver la auditor\xEDa del espacio (qui\xE9n hizo qu\xE9 y cu\xE1ndo)",valores:oe},{clave:"publico.compartir",descripcion:"Compartir la p\xE1gina p\xFAblica de un registro (un enlace que caduca)",valores:oe},{clave:"pix.memoria_espacio",descripcion:"Escribir lo que Pix recuerda para todo el espacio",valores:oe},...Sc.map(e=>({clave:`pix.agente_${e.clave}`,descripcion:`Usar a ${e.nombre} (${e.puesto}) del Equipo IA`,valores:oe}))],PF=new Set(pr.map(e=>e.clave)),Xy=e=>/\.(exportar|importar)$/.test(e),zi=e=>Object.fromEntries(pr.map(o=>[o.clave,e(o)])),Yy=e=>e.clave.startsWith("miembros.")||e.clave.startsWith("configuracion.")||e.clave==="formularios.gestionar"||e.clave.startsWith("proyectos.")&&e.clave!=="proyectos.ver"&&e.clave!=="proyectos.exportar"||e.clave==="modulos.configurar"||e.clave==="agenda.configurar"||e.clave==="paneles.compartir"||e.clave==="automatizaciones.gestionar"||e.clave==="campanas.gestionar"||e.clave==="analisis.compartir"||e.clave==="liquidaciones.gestionar"||e.clave==="portales.gestionar"||e.clave==="auditoria.ver"||e.clave==="pix.memoria_espacio"||xg(e.clave),Ky={titular:zi(()=>"si"),administrador:zi(e=>e.clave==="conectores.accionar"?"no":"si"),miembro:zi(e=>Yy(e)||e.clave==="conectores.accionar"||e.clave==="secretos.ver"||Xy(e.clave)?"no":"si"),lectura:zi(e=>e.clave.endsWith(".ver")&&e.clave!=="secretos.ver"&&e.clave!=="auditoria.ver"||e.clave.endsWith(".descargar")?"si":e.clave.endsWith(".reasignar")?"suyos":"no")},TF=pr.filter(e=>/^((contactos|empresas|oportunidades|proyectos|tareas|notas|adjuntos)\.|agenda\.(ver|editar)$)/.test(e.clave)&&e.valores.includes("suyos")&&Ky.miembro[e.clave]!=="no").map(e=>e.clave),MF=pr.filter(e=>/^((contactos|empresas|oportunidades|proyectos|tareas|notas|adjuntos)\.|agenda\.(ver|editar)$)/.test(e.clave)&&e.valores.includes("suyos")).map(e=>e.clave)});function Mg(e){if(!Array.isArray(e))throw i("Los sin\xF3nimos van en una lista de palabras.");let o=[],t=new Set;for(let n of e){if(typeof n!="string")throw i("Cada sin\xF3nimo es un texto.");let r=n.replace(/\s+/g," ").trim();if(r){if(r.length>Pg)throw i(`\xAB${r.slice(0,20)}\u2026\xBB: como mucho ${Pg} caracteres.`);if(!Ec(r))throw i(`\xAB${r}\xBB no es una palabra.`);t.has(Ec(r))||(t.add(Ec(r)),o.push(r))}}if(o.length>Rc)throw i(`Como mucho ${Rc} sin\xF3nimos por m\xF3dulo.`);return o}var Tg,Rc,Pg,Ec,Ig=f(()=>{R();Tg=["contacts","companies","deals","tasks"],Rc=20,Pg=40,Ec=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9ñ\s-]/g," ").replace(/\s+/g," ").trim()});function o_(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>5)throw i("Conexiones de la soluci\xF3n no v\xE1lidas.");return e.map(o=>{if(!re(o)||o.tipo!=="conector"||typeof o.conector!="string"||!/^[a-z][a-z0-9_-]{0,39}$/.test(o.conector))throw i("Conexi\xF3n de la soluci\xF3n no v\xE1lida.");let t=yo(o.nombre,"nombre de la conexi\xF3n",80,!1)||o.conector;return{clave:o.conector,nombre:t,tipo:"conector",conector:o.conector}})}function r_(e){if(e===void 0)return[];if(!Array.isArray(e))throw i("Conexiones de la soluci\xF3n no v\xE1lidas.");let o=s=>re(s)&&s.tipo==="conector",t=o_(e.filter(o)),n=Kh(e.filter(s=>!o(s))),r=0,a=0;return e.map(s=>o(s)?t[r++]:n[a++])}function i_(e){if(e==null)return null;if(!re(e))throw i("\xABagenda\xBB: un objeto.");Xe(e,["tipos"],"Agenda");let o=new Set,t=io(e.tipos,n_,"agenda.tipos").map((n,r)=>{let a=`Tipo de cita ${r+1}`;if(!re(n))throw i(`${a}: un objeto.`);Xe(n,["nombre","duracion","color","reserva_publica","quien_atiende","cambio_horas","crear_persona"],a);let s=yo(n.nombre,`nombre del ${a.toLowerCase()}`,80);if(o.has(s.toLowerCase()))throw i(`${a}: nombre repetido.`);if(o.add(s.toLowerCase()),!Number.isInteger(n.duracion)||n.duracion<5||n.duracion>1440)throw i(`${a}: \xABduracion\xBB, de 5 a 1440 minutos.`);if(n.color!==void 0&&(typeof n.color!="string"||!/^#[0-9a-f]{6}$/i.test(n.color)))throw i(`${a}: \xABcolor\xBB, #rrggbb.`);for(let c of["reserva_publica","crear_persona"])if(n[c]!==void 0&&typeof n[c]!="boolean")throw i(`${a}: \xAB${c}\xBB, s\xED o no.`);if(n.quien_atiende!==void 0&&n.quien_atiende!=="cualquiera"&&n.quien_atiende!=="cliente")throw i(`${a}: \xABquien_atiende\xBB, cualquiera o cliente.`);if(n.cambio_horas!==void 0&&(!Number.isInteger(n.cambio_horas)||n.cambio_horas<0||n.cambio_horas>720))throw i(`${a}: \xABcambio_horas\xBB, de 0 a 720.`);return{nombre:s,duracion:n.duracion,...n.color!==void 0?{color:n.color.toLowerCase()}:{},...n.reserva_publica!==void 0?{reserva_publica:n.reserva_publica}:{},...n.quien_atiende!==void 0?{quien_atiende:n.quien_atiende}:{},...n.cambio_horas!==void 0?{cambio_horas:n.cambio_horas}:{},...n.crear_persona!==void 0?{crear_persona:n.crear_persona}:{}}});return t.length?{tipos:t}:null}function a_(e,o){return io(e,Pc,"vistasTabla").map((t,n)=>{let r=`Vista de tabla ${n+1}`;if(!re(t))throw i(`${r}: un objeto.`);Xe(t,["objeto","tipoContacto","nombre","config","disposicion"],r);let a=typeof t.objeto=="string"?t.objeto:"";if(!["contacts","companies"].includes(a)&&(!a.startsWith("mod_")||!o.includes(a.slice(4))))throw i(`${r}: de un m\xF3dulo de la soluci\xF3n (mod_<clave>).`);let s=fg(t.disposicion??null,a),c=cg(a,t.tipoContacto);return{objeto:a,...c?{tipoContacto:c}:{},nombre:yo(t.nombre,`nombre de la ${r.toLowerCase()}`,60),...t.config!==void 0?{config:hg(t.config)}:{},disposicion:s}})}function u_(e,o,t=[]){let n=new Set;return io(e,Mc,"papeles").map((r,a)=>{let s=`Papel ${a+1}`;if(!re(r))throw i(`${s}: un objeto.`);Xe(r,["nombre","base","permisos","ocultos","lectura","identidades"],s);let c=yo(r.nombre,`nombre del ${s.toLowerCase()}`,40);if(n.has(c.toLowerCase()))throw i(`${s}: nombre repetido.`);if(n.add(c.toLowerCase()),typeof r.base!="string"||!c_.includes(r.base))throw i(`${s}: \xABbase\xBB, administrador, miembro o lectura.`);let d={};if(r.permisos!==void 0){if(!re(r.permisos))throw i(`${s}: \xABpermisos\xBB, un objeto.`);for(let[b,y]of Object.entries(r.permisos)){if(b==="miembros.gestionar"||b==="configuracion.gestionar")throw i(`${s}: \xAB${b}\xBB no se da en un papel personalizado.`);let v=l_.exec(b),w=pr.find(j=>j.clave===b);if(v?!o.includes(v[1]):!w)throw i(`${s}: permiso desconocido \xAB${b.slice(0,60)}\xBB.`);let N=w?w.valores:qg[v[2]];if(typeof y!="string"||!N.includes(y))throw i(`${s}: valor no v\xE1lido para \xAB${b.slice(0,60)}\xBB.`);d[b]=y}}let u=(b,y)=>{if(b===void 0)return[];if(!Array.isArray(b)||b.length>100)throw i(`${s}: \xAB${y}\xBB, una lista (hasta 100) de \xABmod_<clave>.<campo>\xBB.`);return b.map(v=>{let w=typeof v=="string"?s_.exec(v):null,N=w?t.find(j=>j.clave===w[1]):void 0;if(!w||!N||!N.campos.some(j=>j.clave===w[2]))throw i(`${s}: \xAB${String(v).slice(0,60)}\xBB no es un campo de un m\xF3dulo de la soluci\xF3n.`);return v})},p=u(r.ocultos,"ocultos"),m=u(r.lectura,"lectura"),h=xm(r.identidades);return{nombre:c,base:r.base,...Object.keys(d).length?{permisos:d}:{},...p.length?{ocultos:p}:{},...m.length?{lectura:m}:{},...h.length?{identidades:h}:{}}})}function qc(e,o=0){if(o>30)throw i("La soluci\xF3n anida demasiado.");if(Array.isArray(e))return e.forEach(t=>qc(t,o+1));if(re(e))for(let t of Object.keys(e)){if(e_.has(t))throw i(`Clave no admitida \xAB${t}\xBB.`);qc(e[t],o+1)}}function Xe(e,o,t){for(let n of Object.keys(e))if(!o.includes(n))throw i(`${t}: clave no admitida \xAB${n.slice(0,40)}\xBB.`)}function yo(e,o,t,n=!0){if(e==null||e===""){if(n)throw i(`Falta \xAB${o}\xBB.`);return""}if(typeof e!="string"||e.length>t)throw i(`\xAB${o}\xBB: texto de hasta ${t} caracteres.`);return e.trim()}function rn(e,o){if(typeof e=="string"){if(e.length>Wi)throw i("La soluci\xF3n pasa de 1 MB.");try{e=JSON.parse(e)}catch{throw i("La soluci\xF3n no es un JSON v\xE1lido.")}}else if(JSON.stringify(e??null).length>Wi)throw i("La soluci\xF3n pasa de 1 MB.");if(!re(e))throw i("La soluci\xF3n tiene que ser un objeto.");qc(e),Xe(e,["formato","version","plantilla","nombre","descripcion","icono","modulos","paneles","automatizaciones","ejemplos","informes","principal","mensajes","papeles","portales","vistasTabla","separadores","menu","sinonimos","perfilesImportacion","conexiones","fuentesExternas","senales","pix","agenda"],"Soluci\xF3n");let t;if(e.plantilla!==void 0){let g=e.plantilla;if(!re(g))throw i("\xABplantilla\xBB: un objeto.");if(Xe(g,["id","version","sector","nivel","dependencias","migracion"],"Plantilla"),typeof g.id!="string"||!/^[a-z][a-z0-9_]{0,59}$/.test(g.id))throw i("\xABplantilla.id\xBB: min\xFAsculas, n\xFAmeros y _.");if(!Ii(g.version))throw i("\xABplantilla.version\xBB: usa una versi\xF3n sem\xE1ntica v\xE1lida.");if(typeof g.sector!="string"||!/^[a-z][a-z0-9_]{0,39}$/.test(g.sector))throw i("\xABplantilla.sector\xBB: min\xFAsculas y _.");if(g.nivel!==void 0&&g.nivel!=="completa"&&g.nivel!=="basica")throw i("\xABplantilla.nivel\xBB: completa o basica.");let x=g.dependencias;if(x!==void 0&&(!Array.isArray(x)||x.length>30||x.some(k=>typeof k!="string"||!/^[a-z][a-z0-9_]{0,59}$/.test(k)||k===g.id)||new Set(x).size!==x.length))throw i("\xABplantilla.dependencias\xBB: usa identificadores distintos de otras soluciones.");let O=tg(g.migracion,g.version);t={...O?{migracion:O}:{},id:g.id,version:g.version,sector:g.sector,...x?{dependencias:x}:{},...g.nivel==="basica"?{nivel:"basica"}:{}}}if(e.formato!==kt)throw i(`No es una soluci\xF3n (formato \xAB${kt}\xBB).`);if(!Number.isInteger(e.version)||e.version<1)throw i("\xABversion\xBB: un entero.");if(e.version>mr)throw i("La soluci\xF3n es de una versi\xF3n m\xE1s nueva del CRM.");let n=yo(e.icono,"icono",40,!1)||"boxes";if(!Lg.test(n))throw i("\xABicono\xBB: un icono de lucide.");if(!Array.isArray(e.modulos)||e.modulos.length<1||e.modulos.length>Fi)throw i(`Una soluci\xF3n lleva de 1 a ${Fi} m\xF3dulos.`);let r=e.modulos.map(g=>re(g)&&typeof g.clave=="string"?g.clave:"");if(new Set(r).size!==r.length)throw i("Dos m\xF3dulos de la soluci\xF3n con la misma clave.");let a=new Map([...o.externos??[]].filter(([g])=>!r.includes(g))),s=[...r,...a.keys()],c=new Map([...a,...e.modulos.map((g,x)=>[r[x],uc(g,s)])]),d=e.modulos.map(g=>{let x=Rh(g,{topeCampos:o.topeCampos,modulosDelEspacio:s,camposRelacion:c}),O=re(g)?g.sin_coste:void 0;if(O!==void 0&&O!==!0)throw i(`\xAB${x.nombre_plural}\xBB: \xABsin_coste\xBB solo puede ser true.`);return O===!0?{...x,sin_coste:!0}:x}),u=io(e.paneles,kc,"paneles").map((g,x)=>{if(!re(g))throw i(`Panel ${x+1}: un objeto.`);if(Xe(g,["nombre","icono","widgets"],`Panel ${x+1}`),!Array.isArray(g.widgets)||g.widgets.length>20)throw i(`Panel ${x+1}: hasta 20 widgets.`);let O=yo(g.icono,"icono",40,!1);if(O&&!Lg.test(O))throw i(`Panel ${x+1}: icono no v\xE1lido.`);return{nombre:yo(g.nombre,"nombre del panel",60),...O?{icono:O}:{},widgets:g.widgets}}),p=io(e.automatizaciones,Tc,"automatizaciones").map((g,x)=>{if(!re(g))throw i(`Automatizaci\xF3n ${x+1}: un objeto.`);if(Xe(g,["nombre","definicion"],`Automatizaci\xF3n ${x+1}`),!re(g.definicion))throw i(`Automatizaci\xF3n ${x+1}: falta su definici\xF3n.`);return{nombre:yo(g.nombre,"nombre de la automatizaci\xF3n",80),definicion:g.definicion}}),m=io(e.senales,20,"senales").map((g,x)=>{if(!re(g))throw i(`Se\xF1al ${x+1}: un objeto.`);Xe(g,["fuente","regla"],`Se\xF1al ${x+1}`);let O=typeof g.fuente=="string"?g.fuente:"";if(!(O.startsWith("mod_")?r.includes(O.slice(4)):jg.includes(O)))throw i(`Se\xF1al ${x+1}: \xABfuente\xBB, un m\xF3dulo de la soluci\xF3n (mod_<clave>) o un nativo.`);if(!re(g.regla))throw i(`Se\xF1al ${x+1}: falta su regla.`);return{fuente:O,regla:g.regla}}),h=Ag(e.pix),b=Rg(e.informes,r);if(e.principal!==void 0&&(typeof e.principal!="string"||!r.includes(e.principal)))throw i("\xABprincipal\xBB: la clave de uno de sus m\xF3dulos.");let y=io(e.mensajes,Di,"mensajes").map((g,x)=>{let O=vg(g,`Mensaje ${x+1}`);if(O.recurso.startsWith("mod_")&&!r.includes(O.recurso.slice(4)))throw i(`Mensaje ${x+1}: de un m\xF3dulo que no est\xE1 en la soluci\xF3n.`);return O}),v=u_(e.papeles,r,d),w=p_(e.portales,r),N=i_(e.agenda),j=a_(e.vistasTabla,r),S=io(e.separadores??[],Ic,"separadores").map((g,x)=>{if(!re(g))throw i(`Separador ${x+1}: un objeto.`);if(Xe(g,["antes","titulo"],`Separador ${x+1}`),g.antes!==null&&(typeof g.antes!="string"||!r.includes(g.antes)))throw i(`Separador ${x+1}: \xABantes\xBB, la clave de uno de sus m\xF3dulos.`);if(g.titulo!==void 0&&g.titulo!==null&&(typeof g.titulo!="string"||!g.titulo.trim()||g.titulo.trim().length>40))throw i(`Separador ${x+1}: \xABtitulo\xBB, de 1 a 40 caracteres (o null: solo la l\xEDnea).`);return{antes:g.antes,titulo:typeof g.titulo=="string"?g.titulo.trim():null}}),q=io(e.menu??[],100,"menu").map((g,x)=>{if(!re(g))throw i(`Men\xFA ${x+1}: un objeto.`);if(Xe(g,["entrada","padre","recientes","despliega"],`Men\xFA ${x+1}`),typeof g.entrada!="string"||!r.includes(g.entrada))throw i(`Men\xFA ${x+1}: \xABentrada\xBB, la clave de uno de sus m\xF3dulos.`);if(g.padre!==void 0&&g.padre!==null&&(typeof g.padre!="string"||!r.includes(g.padre)||g.padre===g.entrada))throw i(`Men\xFA ${x+1}: \xABpadre\xBB, otro de sus m\xF3dulos (o null).`);if(g.recientes!==void 0&&(!Number.isSafeInteger(g.recientes)||g.recientes<0||g.recientes>10))throw i(`Men\xFA ${x+1}: \xABrecientes\xBB, de 0 a 10.`);if(g.despliega!==void 0&&(typeof g.despliega!="string"||!gc.includes(g.despliega)))throw i(`Men\xFA ${x+1}: \xABdespliega\xBB, ${gc.join(", ")}.`);return{entrada:g.entrada,...g.padre!==void 0?{padre:g.padre}:{},...g.recientes!==void 0?{recientes:g.recientes}:{},...g.despliega!==void 0?{despliega:g.despliega}:{}}});for(let g of q)if(g.padre&&(q.some(x=>x.entrada===g.padre&&x.padre)||q.some(x=>x.padre===g.entrada)))throw i(`Men\xFA: \xAB${g.entrada}\xBB, un solo nivel (ni su padre va dentro de otro ni tiene otros dentro).`);if(new Set(q.map(g=>g.entrada)).size!==q.length)throw i("Men\xFA: cada m\xF3dulo, una vez.");let F={};if(e.ejemplos!==void 0){if(!re(e.ejemplos))throw i("\xABejemplos\xBB: un objeto por m\xF3dulo.");for(let[g,x]of Object.entries(e.ejemplos)){if(!r.includes(g))throw i(`Ejemplos de un m\xF3dulo que no est\xE1 en la soluci\xF3n (\xAB${g.slice(0,40)}\xBB).`);let O=new Set;F[g]=io(x,Bi,`ejemplos de ${g}`).map((k,D)=>{if(!re(k))throw i(`Ejemplo ${D+1} de ${g}: un objeto.`);if(k._ref!==void 0&&!Number.isSafeInteger(k._ref))throw i(`Ejemplo ${D+1} de ${g}: \xAB_ref\xBB es un entero.`);if(typeof k._ref=="number"){if(O.has(k._ref))throw i(`\xAB${g}\xBB: referencia de ejemplo repetida.`);O.add(k._ref)}if((d.find(U=>U.clave===g)?.campos??[]).filter(U=>U.tipo==="secreto").map(U=>U.clave).some(U=>U in k))throw i(`Ejemplo ${D+1} de ${g}: un ejemplo no lleva el valor de un campo secreto.`);return k})}}let I=r_(e.conexiones),_=Xh(e.fuentesExternas,d,I.filter(t_));if(_.some(g=>g.modo==="vivo"&&F[g.modulo]?.length))throw i("Un m\xF3dulo con fuente en vivo no puede tener ejemplos.");let E=ag(e.perfilesImportacion);if(E.some(g=>g.perfil.entidades.some(x=>x.destino.startsWith("mod_")&&!d.some(O=>`mod_${O.clave}`===x.destino))))throw i("El perfil apunta fuera de la soluci\xF3n.");return{formato:kt,...E.length?{perfilesImportacion:E}:{},...I.length?{conexiones:I}:{},..._.length?{fuentesExternas:_}:{},version:e.version,...t?{plantilla:t}:{},nombre:yo(e.nombre,"nombre",80),descripcion:yo(e.descripcion,"descripcion",500,!1),icono:n,modulos:d,paneles:u,automatizaciones:p,ejemplos:F,...m.length?{senales:m}:{},...h?{pix:h}:{},...b.length?{informes:b}:{},...typeof e.principal=="string"?{principal:e.principal}:{},...y.length?{mensajes:y}:{},...v.length?{papeles:v}:{},...w.length?{portales:w}:{},...N?{agenda:N}:{},...j.length?{vistasTabla:j}:{},...S.length?{separadores:S}:{},...q.length?{menu:q}:{},...d_(e.sinonimos,d.map(g=>g.clave))}}function d_(e,o){if(e===void 0)return{};if(!re(e))throw i("\xABsinonimos\xBB: un objeto (clave del m\xF3dulo \u2192 lista de palabras).");let t={};for(let[n,r]of Object.entries(e)){if(!o.includes(n)&&!Tg.includes(n))throw i(`\xABsinonimos\xBB: \xAB${n.slice(0,40)}\xBB no es un m\xF3dulo de la soluci\xF3n ni uno nativo.`);let a=Mg(r);a.length&&(t[n]=a)}return Object.keys(t).length?{sinonimos:t}:{}}function p_(e,o){return io(e,Lc,"portales").map((t,n)=>{let r=`Portal ${n+1}`;if(!re(t))throw i(`${r}: un objeto.`);Xe(t,["clave","nombre","activo","personas","secciones","textos","marca"],r);let a=[...bg(t)].filter(p=>!o.includes(p));if(a.length)throw i(`${r}: usa un m\xF3dulo que no est\xE1 en la soluci\xF3n (\xABmod_${a[0].slice(0,40)}\xBB).`);if(!Array.isArray(t.secciones)||!t.secciones.length)throw i(`${r}: al menos una secci\xF3n.`);let{activo:s,marca:c,...d}=t,u=re(c)&&typeof c.color=="string"?c.color:void 0;return{...d,...u?{marca:{color:u}}:{}}})}function io(e,o,t){if(e===void 0)return[];if(!Array.isArray(e)||e.length>o)throw i(`\xAB${t}\xBB: una lista de hasta ${o}.`);return e}var kt,mr,Fi,kc,Pc,Tc,Bi,Wi,Lg,e_,t_,n_,Mc,s_,c_,l_,re,Ic,Lc,Dc=f(()=>{Yh();Zh();rg();wc();sg();Cm();wg();lg();jc();R();Sg();Eg();Oc();Zr();Hh();kg();gg();Ig();kt="forgenex.solucion",mr=2,Fi=30,kc=10,Pc=20,Tc=40,Bi=50,Wi=1e6,Lg=/^[a-z0-9-]{1,40}$/,e_=new Set(["__proto__","constructor","prototype"]);t_=e=>e.tipo!=="conector";n_=10;Mc=10,s_=/^mod_([a-z][a-z0-9_]{0,40})\.([a-z][a-z0-9_]{0,40})$/,c_=["administrador","miembro","lectura"],l_=/^mod_([a-z][a-z0-9_]{0,40})\.(ver|editar|borrar|exportar|importar|crear|reasignar|estado|descargar|revelar)$/;re=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);Ic=20,Lc=10});function zg(e,o){let t=new Map(e);for(let[n,r]of e){if(!/^(interfaz|funciones)\/.+\.ts$/.test(n))continue;let a=n.replace(/\.ts$/,".js");if(e.has(a))throw Dg([{ruta:n,linea:null,motivo:`El fichero coincide con la salida \xAB${a}\xBB.`}]);try{let{code:s}=o(r.toString("utf8"),{loader:"ts",sourcefile:n,target:"es2020",format:"esm"});t.set(a,Buffer.from(s)),t.delete(n)}catch(s){let c=s?.errors;throw Dg(c?.length?c.slice(0,12).map(({location:d,text:u})=>({ruta:n,linea:d?.line??null,motivo:u})):[{ruta:n,linea:null,motivo:"El compilador no pudo procesar el fichero."}])}}return t}function Dg(e){let{ruta:o,linea:t,motivo:n}=e[0];return new z(422,"build_app",`${o}${t?`:${t}`:""}: ${n}`,!1,{errores:e})}var Fg=f(()=>{R()});import{createHash as Wg,createPublicKey as m_,sign as f_,verify as v2}from"node:crypto";function h_(e){let o=m_(e);if(o.asymmetricKeyType!=="ed25519")throw i("La clave p\xFAblica tiene que ser ed25519.");let t=o.export({type:"spki",format:"der"});return{pem:o.export({type:"spki",format:"pem"}).toString(),id:Wg("sha256").update(t).digest("hex")}}function g_(e){return Buffer.from(JSON.stringify(["forgenex.fgx.v1",[...e].filter(([o])=>o!==nn).sort(([o],[t])=>o<t?-1:o>t?1:0).map(([o,t])=>[o,Wg("sha256").update(t).digest("hex")])]))}function Bg(e,o,t){let{id:n}=h_(t);return Buffer.from(JSON.stringify({formato:"forgenex.firma",version:1,clave:n,firma:f_(null,g_(e),o).toString("base64")}))}var nn,zc=f(()=>{R();nn="firma.json"});function Fc(e){let o=Array.from({length:256},(c,d)=>{let u=d;for(let p=0;p<8;p++)u=u&1?3988292384^u>>>1:u>>>1;return u>>>0}),t=[],n=[],r=0;for(let[c,d]of e){let u=Buffer.from(c),p=4294967295;for(let b of d)p=o[(p^b)&255]^p>>>8;p=(p^4294967295)>>>0;let m=Buffer.alloc(30),h=Buffer.alloc(46);m.writeUInt32LE(67324752),m.writeUInt16LE(20,4),m.writeUInt16LE(2048,6),m.writeUInt32LE(p,14),m.writeUInt32LE(d.length,18),m.writeUInt32LE(d.length,22),m.writeUInt16LE(u.length,26),h.writeUInt32LE(33639248),h.writeUInt16LE(20,4),h.writeUInt16LE(20,6),h.writeUInt16LE(2048,8),h.writeUInt32LE(p,16),h.writeUInt32LE(d.length,20),h.writeUInt32LE(d.length,24),h.writeUInt16LE(u.length,28),h.writeUInt32LE(r,42),t.push(m,u,d),n.push(h,u),r+=m.length+u.length+d.length}let a=Buffer.concat(n),s=Buffer.alloc(22);return s.writeUInt32LE(101010256),s.writeUInt16LE(e.size,8),s.writeUInt16LE(e.size,10),s.writeUInt32LE(a.length,12),s.writeUInt32LE(r,16),Buffer.concat([...t,a,s])}var Ug=f(()=>{});var Jg,Vg=f(()=>{Jg={name:"forgenex",version:"0.6.0",description:"Atajo de @forgenex/cli: `npx forgenex crear-app mi-app`.",type:"module",bin:{forgenex:"forgenex.js"},engines:{node:">=20.19"},license:"MIT",dependencies:{"@forgenex/cli":"0.6.0"},files:["forgenex.js","README.md","LICENSE"]}});import{createHash as w_}from"node:crypto";import{lstatSync as Uc,readFileSync as Vc,writeFileSync as Wc}from"node:fs";import{dirname as v_,join as Pt,resolve as y_}from"node:path";import{fileURLToPath as __}from"node:url";function Yg(e){return e.match(Xg)?.[1]??$_[w_("sha256").update(e.replaceAll(`\r
|
|
22
|
+
`,`
|
|
23
|
+
`)).digest("hex")]}function sn(e){let o=Pt(e,"GUIA-IA.md");if(!Uc(o,{throwIfNoEntry:!1})?.isFile())return;let t=Vc(o,"utf8"),n=Yg(t);if(n){let r=Jc.split(".").map(Number);(n.split(".").map(Number).map((c,d)=>c-r[d]).find(c=>c!==0)??0)<0&&console.warn(`Tu gu\xEDa es de la ${n}; ejecuta \`npx forgenex actualizar\`.`)}else console.warn("Tu gu\xEDa no indica su versi\xF3n; ejecuta `npx forgenex actualizar` para ponerla al d\xEDa.")}function Qg(e,o){let t=Pt(e,o),n=Uc(t,{throwIfNoEntry:!1});if(n){if(!n.isFile()||n.nlink!==1)throw new Error(`\xAB${o}\xBB no es un archivo normal del proyecto. Revisa el enlace antes de actualizar.`);return Vc(t,"utf8")}}function Kg(e){let o=Vc(Pt(N_,e),"utf8");return e.endsWith(".json")?o.replace(/^\{\r?\n/,`{
|
|
24
|
+
"$comment": "${an}",
|
|
25
|
+
`):e.endsWith(".md")?`<!-- ${an} -->
|
|
26
|
+
${o}`:`// ${an}
|
|
27
|
+
${o}`}function Ui(e,o){for(let t of Bc)Wc(Pt(e,t),Kg(t));o&&Wc(Pt(e,"AGENTS.md"),`<!-- ${an} -->
|
|
28
|
+
${o==="archivos"?Hg:Gg}`)}function Zg(e){if(!Uc(Pt(e,"extension.json"),{throwIfNoEntry:!1})?.isFile())throw new Error("Aqu\xED falta extension.json. Entra en la carpeta de tu app y ejecuta \xABforgenex actualizar\xBB.");let o=new Map(Bc.map(c=>[c,Qg(e,c)])),t=o.get("GUIA-IA.md"),n=Qg(e,"AGENTS.md"),r=new Map(Bc.map(c=>[c,Kg(c)]));if(n!==void 0){let c=n.replace(Xg,"").replaceAll(`\r
|
|
29
|
+
`,`
|
|
30
|
+
`);c===Gg||c===Hg?(o.set("AGENTS.md",n),r.set("AGENTS.md",`<!-- ${an} -->
|
|
31
|
+
${c}`)):console.log("AGENTS.md tiene cambios propios y se conserva.")}let a=[];for(let[c,d]of r)o.get(c)!==d&&(Wc(Pt(e,c),d),a.push(c));let s=t===void 0?"sin gu\xEDa":Yg(t)??"gu\xEDa sin versi\xF3n";console.log(`Gu\xEDa de la app: ${s} \u2192 ${Jc}.`),console.log(a.length?`Renovados: ${a.join(", ")}.`:"Los archivos de la CLI ya est\xE1n al d\xEDa.")}var N_,Jc,an,Bc,$_,Gg,Hg,Xg,Vi=f(()=>{Vg();N_=y_(v_(__(import.meta.url)),".."),Jc=Jg.dependencies["@forgenex/cli"],an=`@forgenex/cli ${Jc}`,Bc=["GUIA-IA.md","extension.schema.json","solucion.schema.json","puente-extension.d.ts","puente-extension.mjs"],$_={"91cd7d85f2e95dc581b15794b300d648031e585562f3f4bb90f54906a06a57e3":"0.4.0","7b2a3ef59a3b529fdf43fe7b74ad0ce14da6413ee66ed5a007a1827be6729f8c":"0.5.0",d6a238dd1da813ecd3da36717c789e39e2c928b7d0917bca1651a483f1a5f8de:"0.4.0","88289f8a17fe43cfa2dba6c782756f1bfd09bed4c6bbb2c62ce5194c894577e8":"0.4.1"},Gg=`Lee GUIA-IA.md. Usa el puente del CRM y los m\xF3dulos enlazados a Personas y Empresas. Pide permisos m\xEDnimos. Valida antes de empaquetar. Nunca incluyas claves ni datos reales.
|
|
32
|
+
`,Hg=`Lee GUIA-IA.md (secci\xF3n \xABArchivos\xBB). La app solo recibe lo que la persona elige con crm.archivos.elegir(): nunca pidas tokens del almacenamiento. Pide permisos m\xEDnimos. Valida antes de empaquetar.
|
|
33
|
+
`,Xg=/^<!-- @forgenex\/cli (\d+\.\d+\.\d+) -->\r?\n/});import{existsSync as eb,cpSync as x_,copyFileSync as Qc,mkdirSync as Ji,readFileSync as fr,readdirSync as cn,realpathSync as ob,writeFileSync as tb}from"node:fs";import{dirname as C_,join as Q,resolve as j_,sep as S_}from"node:path";import{fileURLToPath as O_}from"node:url";import{createRequire as Qi}from"node:module";function Gi(e,o="html",t=process.cwd()){if(!/^[a-z][a-z0-9-]{1,59}$/.test(e))throw new Error("El nombre debe tener de 2 a 60 letras min\xFAsculas, n\xFAmeros o guiones y empezar por letra. Prueba \xABforgenex crear-app mi-app\xBB.");if(!["html","react","archivos","natacion"].includes(o))throw new Error("Plantilla desconocida. Elige --plantilla html, react, archivos o natacion.");let n=Q(t,e);try{Ji(n)}catch(c){throw c.code!=="EEXIST"?c:new Error(`\xAB${e}\xBB ya existe. Elige otro nombre o entra en esa carpeta para seguir trabajando.`)}for(let c of["interfaz","funciones"])Ji(Q(n,c));let r=(c,d)=>tb(Q(n,c),typeof d=="string"?d:JSON.stringify(d,null,2)+`
|
|
34
|
+
`);if(o==="natacion"){x_(Q(Io,"ejemplos","escuela-natacion"),n,{recursive:!0,filter:d=>!d.endsWith(".fgx")});let c=JSON.parse(fr(Q(n,"extension.json"),"utf8"));return r("extension.json",{...c,id:`com.ejemplo.${e}`}),r(".gitignore",`*.fgx
|
|
35
|
+
*.pem
|
|
36
|
+
`),Ui(n),Fe(n),n}let a=`ext_${e.replace(/[^a-z]/g,"_").slice(0,27)}`;if(o==="archivos"){let c=JSON.parse(fr(Q(Io,"ejemplos/archivos-ficha/extension.json"),"utf8"));return r("extension.json",{...c,id:`com.ejemplo.${e}`,nombre:e,autor:{nombre:"Mi empresa"}}),Qc(Q(Io,"ejemplos/archivos-ficha/interfaz/index.html"),Q(n,"interfaz/index.html")),Ui(n,"archivos"),r(".gitignore",`node_modules/
|
|
25
37
|
*.fgx
|
|
26
38
|
*.pem
|
|
27
39
|
.keys/
|
|
@@ -30,21 +42,40 @@ ${t}`,e}return e}function $w(e){return je(e)&&H(e.stack)}var zr=f(()=>{$()});fun
|
|
|
30
42
|
await crm.almacen.guardar("ultimo_resumen", resumen);
|
|
31
43
|
return resumen;
|
|
32
44
|
}
|
|
33
|
-
`)
|
|
34
|
-
|
|
45
|
+
`),Ui(n,"app"),Ji(Q(n,"pruebas")),r("pruebas/resumir.test.mjs",`import assert from "node:assert/strict";
|
|
46
|
+
import { readFile } from "node:fs/promises";
|
|
47
|
+
import test from "node:test";
|
|
48
|
+
|
|
49
|
+
test("el comando resume y guarda el mensaje", async () => {
|
|
50
|
+
const codigo = await readFile(new URL("../funciones/resumir.js", import.meta.url), "utf8");
|
|
51
|
+
const { default: resumir } = await import(\`data:text/javascript,\${encodeURIComponent(codigo)}\`);
|
|
52
|
+
const datos = new Map();
|
|
53
|
+
globalThis.crm = { almacen: { guardar: (clave, valor) => datos.set(clave, valor) } };
|
|
54
|
+
try {
|
|
55
|
+
const salida = await resumir({ cuerpo: { mensaje: "Hola" } });
|
|
56
|
+
assert.deepEqual(salida, { mensaje: "Hola", total: 1 });
|
|
57
|
+
assert.deepEqual(datos.get("ultimo_resumen"), salida);
|
|
58
|
+
} finally {
|
|
59
|
+
delete globalThis.crm;
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
`),r("README.md","# "+e+`
|
|
63
|
+
|
|
64
|
+
Ejecuta la prueba del comando resumir con \`node --test\`. Consulta GUIA-IA.md para instalar la app en tu CRM.
|
|
65
|
+
`);let s=o==="html"?"hola-alpine":"hola-react";for(let c of cn(Q(Io,"ejemplos",s,"interfaz")))Qc(Q(Io,"ejemplos",s,"interfaz",c),Q(n,"interfaz",c));return o==="react"&&(Ji(Q(n,"src")),Qc(Q(Io,"ejemplos/hola-react/src/main.jsx"),Q(n,"src/main.jsx")),r("package.json",{private:!0,type:"module",scripts:{build:"vite build"},dependencies:{react:"19.1.0","react-dom":"19.1.0"},devDependencies:{vite:"7.3.2"}}),r("vite.config.js",`import { defineConfig } from "vite";
|
|
35
66
|
export default defineConfig({ build: { outDir: "interfaz", emptyOutDir: false, rollupOptions: { input: "src/main.jsx", external: ["@forgenex/crm-sdk", "@forgenex/forja", "@forgenex/kit"], output: { entryFileNames: "app.js", inlineDynamicImports: true } } } });
|
|
36
67
|
`)),r(".gitignore",`node_modules/
|
|
37
68
|
*.fgx
|
|
38
69
|
*.pem
|
|
39
70
|
.keys/
|
|
40
|
-
`),Fe(n),n}function Fe(e){let o=
|
|
71
|
+
`),Fe(n),n}function Fe(e){let o=Q(e,"extension.json");if(!eb(o))throw new Error("Falta extension.json. Entra en la carpeta de tu app o crea una con \xABforgenex crear-app mi-app\xBB.");let t=Uo(fr(o,"utf8"));t.solucion&&rn(fr(Q(e,t.solucion),"utf8"),{topeCampos:200});for(let n of[...t.montajes,...t.funciones]){let r=Q(e,n.entrada),a=n.entrada.replace(/\.js$/,".ts");fr(a!==n.entrada&&!eb(r)?Q(e,a):r)}return t}function rb(e){let o=zo(e),t=a=>{let s=o.get(a);if(!s)throw new Error(`Al paquete le falta \xAB${a}\xBB.`);return s.toString("utf8")},n=t("extension.json"),r=Uo(n);r.solucion&&rn(t(r.solucion),{topeCampos:200});for(let a of[...r.montajes,...r.funciones])t(a.entrada);return n}async function hr(e){if(!cn(e).includes("src")||!cn(Q(e,"src")).includes("main.jsx"))return;let o=Qi(Q(e,"package.json")),t;try{t=o("esbuild")}catch{try{t=Qi(Q(Io,"../src/package.json"))("esbuild")}catch{throw new Error("La plantilla react necesita sus dependencias: ejecuta antes \xABnpm install\xBB en la carpeta de la app.")}}await t.build({entryPoints:[Q(e,"src/main.jsx")],outfile:Q(e,"interfaz/app.js"),bundle:!0,format:"esm",minify:!0,jsx:"automatic",target:"es2020",external:["@forgenex/crm-sdk","@forgenex/forja","@forgenex/kit"],nodePaths:[Q(Io,"../src/node_modules")],define:{"process.env.NODE_ENV":'"production"'},legalComments:"none"})}function Gc(e){let o=Fe(e),t=new Map,n=ob(e),r=u=>{let p=Q(e,u);if(!ob(p).startsWith(n+S_))throw new Error("El paquete no admite enlaces fuera del proyecto.");t.set(u,fr(p))},a=u=>{for(let p of cn(Q(e,u),{withFileTypes:!0})){if(p.isSymbolicLink())throw new Error("El paquete no admite enlaces simb\xF3licos.");p.isDirectory()?a(`${u}/${p.name}`):r(`${u}/${p.name}`)}};r("extension.json"),o.solucion&&r(o.solucion);for(let u of["interfaz","funciones"])cn(e).includes(u)&&a(u);let s=Qi(Q(e,"package.json")),c=Qi(Q(Io,"../api/package.json")),d=zg(t,(u,p)=>{let m;try{m=s("esbuild")}catch{m=c("esbuild")}return m.transformSync(u,p)});return zo(Fc(d)),d}async function ln(e,...o){await hr(e);let t=Gc(e);o.length&&t.set(nn,Bg(t,...o));let n=Fc(t);zo(n);let r=Fe(e),a=`${r.id.split(".").at(-1)}-${r.version}.fgx`;return tb(Q(e,a),n),Q(e,a)}var Io,un=f(()=>{Mt();Dc();Fg();yr();zc();Ug();Vi();Io=j_(C_(O_(import.meta.url)),"..")});function q_(e,o){let t=[],n=[],r=s=>{if(E_.has(s)||R_.has(s))return;let[c,d]=s.split(".");if(c==="almacen")return t.push({prefijo:"almacen",op:"almacen",donde:o});if(c==="archivos")return d==="leer"||d==="elegir"?t.push({prefijo:"archivos",op:"leer",donde:o}):d==="vincular_elegido"?t.push({prefijo:"archivos",op:"escribir",donde:o}):n.push(s);let u=Object.hasOwn(Bo,c)?c:c.startsWith("mod_")?co(c):null,p=Object.hasOwn(Xc,d)?Xc[d]:null;if(!u||!p)return n.push(s);t.push({prefijo:u,op:u==="notas"&&p!=="ver"?"editar":p,donde:o})};for(let s of e.matchAll(/\.(?:pedir|llamar)\(\s*["'`]([a-z][a-z0-9_]*\.[a-z_]+)["'`]/g))r(s[1]);for(let s of e.matchAll(/\bcrm\.(ver|buscar|crear|actualizar)\(\s*["'`]([a-z][a-z0-9_]*)["'`]/g)){let c=co(s[2]);c&&t.push({prefijo:c,op:Xc[s[1]],donde:o})}/\bcrm\.almacen\.(leer|listar|guardar|borrar)\(/.test(e)&&t.push({prefijo:"almacen",op:"almacen",donde:o}),/\.archivos\.(elegir|leer)\(/.test(e)&&t.push({prefijo:"archivos",op:"leer",donde:o}),/\.archivos\.vincular\(/.test(e)&&t.push({prefijo:"archivos",op:"escribir",donde:o});let a=/\.(?:pedir|llamar)\(\s*[A-Za-z_$]/.test(e)||/\bcrm\.(ver|buscar|crear|actualizar)\(\s*[A-Za-z_$]/.test(e);return{usos:t,desconocidas:n,dinamicas:a}}function k_(e,o){let t=[],n=[],r=new Set,a=!1;for(let[s,c]of o){let d=q_(c,s);a||=d.dinamicas;for(let u of d.desconocidas)n.push(`${s} llama a \xAB${u}\xBB, que una app no puede usar: el CRM le contestar\xE1 que no tiene permiso.`);for(let u of d.usos)r.add(`${u.prefijo}:${u.op}`),u.prefijo==="almacen"?e.permisos.almacen||t.push(`${u.donde} guarda datos de la app y no pide \xABalmacen\xBB.`):u.prefijo==="archivos"?(e.permisos.archivos??[]).includes(u.op)||t.push(`${u.donde} usa archivos (\xAB${u.op}\xBB) y no lo pide en \xABpermisos.archivos\xBB.`):(e.permisos.modulos[u.prefijo]??[]).includes(u.op)||t.push(`${u.donde} necesita ${ib[u.op]} ${ab(u.prefijo)} y no lo pide en \xABpermisos.modulos\xBB.`)}if(a)n.push("El c\xF3digo construye algunas llamadas al CRM en tiempo de ejecuci\xF3n: no se puede comprobar que solo use lo que pide.");else{for(let[s,c]of Object.entries(e.permisos.modulos))for(let d of c)d==="ver"&&c.some(u=>r.has(`${s}:${u}`))||r.has(`${s}:${d}`)||n.push(`Pide ${ib[d]} ${ab(s)} y el c\xF3digo no parece usarlo: pide solo lo que usa.`);e.permisos.almacen&&!r.has("almacen:almacen")&&n.push("Pide guardar datos (\xABalmacen\xBB) y el c\xF3digo no parece usarlo.")}return We("permisos","Permisos coherentes con lo que el c\xF3digo usa",t,n,"Usa solo lo que pide.")}function I_(e,o){let t=[],n=[],r=e.permisos.red_hacia,a=new Map(e.funciones.map(c=>[c.entrada,c])),s=r.length>0;for(let[c,d]of o){for(let u of d.matchAll(/(?:\b(?:https?|wss?):)?\/\/([a-z0-9](?:[a-z0-9-]{0,62}\.)+[a-z]{2,63})(?=[:/"'`)\s?#]|$)/gi)){let p=u[1].toLowerCase();if(T_.has(p))continue;let m=u[0].includes(":"),h=d.slice(Math.max(0,u.index-40),u.index),b=P_.test(h);if(!(!m&&!/(?:src|href)\s*=\s*["']?$/i.test(h)))if(b){s=!0;let y=a.get(c);Yc(r,p)?y&&!Yc(y.red,p)&&t.push(`La funci\xF3n \xAB${y.nombre}\xBB llama a ${p} y no lo tiene en su \xABred\xBB.`):t.push(`${c} llama a ${p} y no est\xE1 en \xABpermisos.red_hacia\xBB.`)}else!Yc(r,p)&&!M_.test(c)&&n.push(`${c} nombra ${p} (no se ve que llame): si la app se conecta ah\xED, decl\xE1ralo.`)}/\b(?:fetch|new\s+WebSocket|new\s+EventSource|sendBeacon)\s*\(\s*(?:[A-Za-z_$]|["'][^"'\n]*["']\s*\+|`[^`]*\$\{)/.test(d)&&(s=!0,n.push(`${c} se conecta a una direcci\xF3n que construye en tiempo de ejecuci\xF3n: solo podr\xE1 ir a lo declarado en \xABpermisos.red_hacia\xBB.`))}return{red:We("red","Red declarada",t,n,r.length?`Solo se conecta a lo declarado (${r.join(", ")}).`:"No se conecta fuera del CRM."),usaRed:s}}function dn(e){let o=e.trim().toLowerCase(),t=/^#([0-9a-f]{3,8})$/.exec(o);if(t){let r=t[1];return r.length===3||r.length===4?[0,1,2].map(a=>parseInt(r[a]+r[a],16)):r.length===6||r.length===8?[0,2,4].map(a=>parseInt(r.slice(a,a+2),16)):null}let n=/^rgba?\(\s*(\d{1,3})[\s,]+(\d{1,3})[\s,]+(\d{1,3})/.exec(o);return n?[Number(n[1]),Number(n[2]),Number(n[3])]:Object.hasOwn(sb,o)?sb[o]:null}function z_(e){let o=e.replace(/!important/i,"").trim();if(L_.test(o))return{tema:!1,color:null,neutro:!0};let t=/^var\(\s*--[\w-]+\s*(?:,\s*(.+))?\)$/i.exec(o);if(t)return{tema:!0,color:t[1]?dn(t[1]):null,neutro:!1};let n=o.split(/\s+/).find(r=>dn(r)!==null);return{tema:/var\(--/.test(o),color:dn(n||o),neutro:!n&&!dn(o)&&!/var\(--/.test(o)}}function F_(e){let o="";for(let t=0;;){let n=e.indexOf("/*",t);if(n<0)return o+e.slice(t);o+=e.slice(t,n);let r=e.indexOf("*/",n+2);if(r<0)return o;t=r+2}}function W_(e){let o=[],t=0,n=-1,r=0;for(let a=0;a<e.length;a++){let s=e.charCodeAt(a);s===123?(n=a,r=t,t=a+1):s===125&&(n>=0&&n>r&&o.push([e.slice(r,n),e.slice(n+1,a)]),n=-1,t=a+1)}return o}function B_(e){let o=[],t=/<style/gi,n=/<\/style>/gi;for(;;){let r=t.exec(e);if(!r)return o;let a=e.indexOf(">",r.index+6);if(a<0)return o;n.lastIndex=a+1;let s=n.exec(e);if(!s)return o;o.push(e.slice(a+1,s.index)),t.lastIndex=s.index+s[0].length}}function U_(e,o){let t=[],n=[],r=[],a=!1,s=!1;for(let[d,u]of o){if(!/\.(css|html?)$/i.test(d)){let m=[...u.matchAll(/\b(?:color|background(?:Color)?)\s*:\s*["'](#[0-9a-f]{3,8}|rgba?\([^)]{0,80}\))["']/gi)].length;m&&n.push(`${d} pone ${m} color(es) fijos en estilos del c\xF3digo: con el tema oscuro pueden no verse.`),/var\(--[\w-]+/.test(u)&&(a=!0);continue}let p=/\.css$/i.test(d)?u:B_(u).join(`
|
|
41
72
|
`)+[...u.matchAll(/\sstyle\s*=\s*"([^"]*)"/gi)].map(m=>`x{${m[1]}}`).join(`
|
|
42
|
-
`);if(p.trim()){s=!0;for(let[m,h]of p_(d_(p))){let b=m.trim().replace(/\s+/g," "),y=null,v=null;for(let w of h.matchAll(/(?:^|;)\s*(color|background-color|background)\s*:\s*([^;]+)/gi)){let N=u_(w[2]);N.tema&&(a=!0),w[1].toLowerCase()==="color"?y=N:v=N,!N.tema&&!N.neutro&&N.color&&(/(^|,)\s*(html|body|:root)\s*(,|$)/i.test(b)?t.push(`${d}: \xAB${b}\xBB fija ${w[1]} (${w[2].trim()}): la p\xE1gina no seguir\xE1 el tema claro y oscuro del CRM. Usa var(--background) y var(--foreground).`):n.push(`${d}: \xAB${b}\xBB usa un color fijo en ${w[1]} (${w[2].trim()}).`))}if(y?.color&&v?.color){let w=l_(y.color,v.color);w<4.5&&r.push(`${d}: \xAB${b}\xBB tiene un contraste de ${w.toFixed(2)}:1 entre el texto y el fondo (hace falta 4,5:1).`)}}}}let c=e.montajes.length>0;return c&&s&&!a&&t.push("La interfaz no usa ninguna variable del tema (var(--background), var(--foreground), var(--primary)\u2026): no parecer\xE1 del CRM ni seguir\xE1 el modo oscuro."),[We("forja","Forja: colores del tema",t,n,c?"Toma los colores del tema del CRM.":"No trae interfaz."),We("contraste","Contraste del texto (\u2265 4,5:1)",r,[],"Los colores fijos que se pueden medir tienen contraste suficiente.")]}function so(e,o){for(let t=0;t<3;t++)if((e[t]??0)!==o[t])return(e[t]??0)<o[t];return!1}function b_(e,o,t){let n=[],r=new Set,a=(c,d,u)=>{let p=c.toLowerCase().replace(/\.js$/,"");r.add(`${p} ${d}`);let m=d.split(".").map(Number);for(let h of h_)h.nombre.test(p)&&h.malas(m)&&n.push(`${u} trae ${h.etiqueta} ${d}, con un fallo de seguridad conocido: usa la ${h.arreglo} o posterior.`)};for(let c of o){let d=/(?:^|\/)([a-z][a-z.]*?)[-.@]v?(\d{1,3}\.\d{1,3}\.\d{1,3})(?:\.min)?\.m?js$/i.exec(c);d&&a(d[1],d[2],c)}for(let[c,d]of t)for(let u of d.matchAll(/\/\*[!*][\s\S]{0,600}?\*\//g))for(let p of u[0].matchAll(g_))a(p[1],p[2],c);let s=e.depende_de.map(c=>`Necesita la app \xAB${c.id}\xBB${c.version?` (${c.version})`:""} instalada antes.`);return We("dependencias","Dependencias sin fallos conocidos",n,s,r.size?`Librer\xEDas vistas: ${[...r].join(", ")}.`:"No se ven librer\xEDas de terceros con versi\xF3n.")}function w_(e){let o=[];for(let[t,n]of e)/\.(m?js|cjs|jsx|html?)$/i.test(t)&&(/\beval\s*\(|\bnew\s+Function\s*\(/.test(n)&&o.push(`${t} ejecuta c\xF3digo construido en tiempo de ejecuci\xF3n (eval o new Function).`),/\b(?:window\.)?(?:top|parent)\.location\b|\bdocument\.cookie\b/.test(n)&&o.push(`${t} toca la ventana de arriba o las cookies (el CRM lo impide; se mira en la revisi\xF3n).`));return We("codigo","C\xF3digo para la revisi\xF3n humana",[],o,"Nada que marcar.")}function Bc(e){let o=[...e.recursos.keys()].sort(),t=o.filter(p=>Zy.test(p)).map(p=>[p,e.recursos.get(p).toString("utf8")]),{red:n,usaRed:r}=s_(e.ext,t),a=r||!!e.ext.conexiones?.length||e.ext.servidor!==null,s=w_(t),c=e.sinRed?[...a||e.ext.funciones.some(p=>p.red.length)?["La app no puede usar red ni conexiones externas."]:[],...t.flatMap(([p,m])=>/\b(?:fetch|XMLHttpRequest|WebSocket|EventSource|sendBeacon|importScripts)\b|\bimport\s*\(/.test(m)?[`${p} intenta usar una conexi\xF3n fuera del puente del CRM.`]:[]),...n.estado==="aviso"?n.detalles:[]]:[],d=[We("esquema","Manifiesto y soluci\xF3n v\xE1lidos",[],[],"El manifiesto y su soluci\xF3n pasan el validador del CRM."),e.dePix?We("firma","Montada por el CRM",[],[],"La ha montado el CRM en este espacio: no viaja a otros ni a la tienda."):We("firma","Firmada por su desarrollador",e.firmada?[]:["El paquete no va firmado: `forgenex empaquetar` con tu clave registrada."],[],e.enLocal?"Se firma al empaquetar con tu clave (la tienda exige firma).":"Firma v\xE1lida de una clave registrada."),We("tamano","Tama\xF1o",e.bytes>ea?["El paquete pasa de 5 MB."]:[],[],`${(e.bytes/1024).toFixed(0)} KB de 5 MB.`),r_(e.ext,t),...f_(e.ext,t),c.length?We("red",n.titulo,c):n,We("politica","Pol\xEDtica de datos",a&&!e.ext.politica_datos?["La app se conecta fuera del CRM: a\xF1ade \xABpolitica_datos\xBB (una direcci\xF3n https con tu pol\xEDtica de datos) al manifiesto."]:[],[],e.ext.politica_datos?`Pol\xEDtica de datos: ${e.ext.politica_datos}`:"No hace falta: no se conecta fuera."),b_(e.ext,o,t),e.sinRed&&s.estado==="aviso"?We("codigo",s.titulo,s.detalles):s],u=d.filter(p=>p.estado==="falla").length;return{ok:u===0,version:1,puntos:d,fallas:u,avisos:d.filter(p=>p.estado==="aviso").length}}var Zy,zc,zg,We,Fc,e_,o_,Fg,Wg,n_,i_,a_,Wc,Bg,c_,Vg,l_,h_,g_,Ug=f(()=>{Tt();vr();Zy=/\.(m?js|cjs|jsx|html?|css|svg)$/i,zc=12,zg=e=>{let o=[...new Set(e)];return o.length>zc?[...o.slice(0,zc),`\u2026 y ${o.length-zc} m\xE1s`]:o},We=(e,o,t,n=[],r="")=>({clave:e,titulo:o,estado:t.length?"falla":n.length?"aviso":"ok",detalles:t.length?zg(t):n.length?zg(n):r?[r]:[]}),Fc={buscar:"ver",ver:"ver",listar:"ver",obtener:"ver",pdf:"ver",crear:"crear",actualizar:"editar",mover:"editar",completar:"editar",borrar:"borrar"},e_=new Set(["contexto.actual","publica.llamar","app.ajustes","extensiones.calcular"]),o_=new Set(["registros.relacionadas","registros.historial","registros.opciones","registros.adjuntar","mensajes.proponer","metricas.calcular"]);Fg={ver:"ver",crear:"crear",editar:"cambiar",borrar:"borrar",almacen:"guardar datos",leer:"leer",escribir:"vincular"},Wg=e=>Object.hasOwn(Bo,e)?Bo[e].nombre:`\xAB${e.replace(/^mod_/,"")}\xBB`;n_=/(fetch|WebSocket|EventSource|sendBeacon|\.open|import|axios(?:\.[a-z]+)?|\$\.(?:get|post|ajax|getJSON))\s*\(\s*["'`]?$|(?:src|href|action|srcset|poster|data)\s*=\s*["']?$|url\(\s*["']?$|@import\s+(?:url\()?["']?$/i,i_=new Set(["www.w3.org","w3.org"]),a_=/(?:\.min\.(?:m?js|css)$)|(?:^|\/)(?:jquery|lodash|alpine|react|vue|preact|chart|d3|moment|axios|dompurify|underscore|bootstrap|handlebars)[^/]*\.m?js$/i,Wc=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1)));Bg={white:[255,255,255],black:[0,0,0],red:[255,0,0],green:[0,128,0],blue:[0,0,255],gray:[128,128,128],grey:[128,128,128],silver:[192,192,192],yellow:[255,255,0],orange:[255,165,0],navy:[0,0,128],purple:[128,0,128],lightgray:[211,211,211],lightgrey:[211,211,211],darkgray:[169,169,169],darkgrey:[169,169,169],whitesmoke:[245,245,245],gainsboro:[220,220,220]},c_=/^(transparent|inherit|initial|unset|revert|currentcolor|none)$/i;Vg=([e,o,t])=>{let n=r=>{let a=r/255;return a<=.03928?a/12.92:((a+.055)/1.055)**2.4};return .2126*n(e)+.7152*n(o)+.0722*n(t)},l_=(e,o)=>{let[t,n]=[Vg(e),Vg(o)].sort((r,a)=>a-r);return(t+.05)/(n+.05)};h_=[{nombre:/^jquery$/i,etiqueta:"jQuery",malas:e=>so(e,[3,5,0]),arreglo:"3.5.0 (CVE-2020-11022)"},{nombre:/^lodash$/i,etiqueta:"Lodash",malas:e=>so(e,[4,17,21]),arreglo:"4.17.21 (CVE-2021-23337)"},{nombre:/^moment$/i,etiqueta:"Moment.js",malas:e=>so(e,[2,29,4]),arreglo:"2.29.4 (CVE-2022-31129)"},{nombre:/^handlebars$/i,etiqueta:"Handlebars",malas:e=>so(e,[4,7,7]),arreglo:"4.7.7 (CVE-2021-23369)"},{nombre:/^bootstrap$/i,etiqueta:"Bootstrap",malas:e=>so(e,[3,4,1])||e[0]===4&&so(e,[4,3,1]),arreglo:"3.4.1 o 4.3.1 (CVE-2019-8331)"},{nombre:/^angular(js)?$/i,etiqueta:"AngularJS",malas:e=>e[0]===1,arreglo:"ninguna: AngularJS 1.x ya no recibe arreglos"},{nombre:/^dompurify$/i,etiqueta:"DOMPurify",malas:e=>e[0]===2?so(e,[2,5,4]):so(e,[3,1,3]),arreglo:"2.5.4 o 3.1.3 (CVE-2024-45801)"},{nombre:/^axios$/i,etiqueta:"Axios",malas:e=>e[0]===0?so(e,[0,28,0]):so(e,[1,6,0]),arreglo:"0.28.0 o 1.6.0 (CVE-2023-45857)"},{nombre:/^underscore$/i,etiqueta:"Underscore",malas:e=>so(e,[1,12,1]),arreglo:"1.12.1 (CVE-2021-23358)"}];g_=/\b(jquery|lodash|moment|handlebars|bootstrap|angularjs|angular|dompurify|axios|underscore|alpine(?:js)?|react|vue|preact|chart\.js|d3)(?:\.js)?(?:\s+javascript\s+library)?[\s@:,-]*v?(\d{1,3}\.\d{1,3}\.\d{1,3})\b/gi});import{Worker as v_}from"node:worker_threads";var y_,Vc,Ui,Jg=f(()=>{yr();y_=new URL(import.meta.url.endsWith(".ts")?"./caja.ts":"./caja.js",import.meta.url),Vc=class{w=null;ocupada=!1;worker(){return this.w?this.w:(this.w=new v_(y_,{resourceLimits:{maxOldGenerationSizeMb:96,maxYoungGenerationSizeMb:16,stackSizeMb:4},env:{},stdout:!0,stderr:!0}),this.w.stdout.resume(),this.w.stderr.resume(),this.w.unref(),this.w)}matar(){let o=this.w;this.w=null,o&&o.terminate().catch(()=>{})}correr(o){this.ocupada=!0;let t=Date.now(),n=this.worker();return new Promise(r=>{let a=!1,s=0,c=(b,y)=>{a||(a=!0,clearTimeout(m),n.off("message",d),n.off("error",u),n.off("exit",p),y&&this.matar(),this.ocupada=!1,r(b))},d=b=>{if(b.tipo==="llamar"){if(a)return;if(typeof b.datos!="string"||b.datos.length>W.llamadaCaracteres||s>=W.llamadasEnVuelo){n.postMessage({tipo:"respuesta",n:b.n,ok:!1,valor:typeof b.datos=="string"&&b.datos.length<=W.llamadaCaracteres?"demasiadas llamadas a la vez":"lo que se manda al CRM es demasiado grande"});return}let v=null;try{v=JSON.parse(b.datos)}catch{}s++,o.manejar(b.que,v).finally(()=>{s--}).then(w=>!a&&n.postMessage({tipo:"respuesta",n:b.n,ok:!0,valor:JSON.stringify(w??null)}),w=>!a&&n.postMessage({tipo:"respuesta",n:b.n,ok:!1,valor:w instanceof Error?w.message:String(w)}));return}let y=Date.now()-t;b.ok?c({ok:!0,salida:b.salida,ms:y},!1):c({ok:!1,corte:b.corte,clase:b.clase,mensaje:b.mensaje,ms:y},b.corte!==null)},u=b=>c({ok:!1,corte:/memory|heap/i.test(b.message)?"memoria":null,clase:"Error",mensaje:"la caja se ha cerrado",ms:Date.now()-t},!0),p=()=>c({ok:!1,corte:null,clase:"Error",mensaje:"la caja se ha cerrado",ms:Date.now()-t},!0),m=setTimeout(()=>c({ok:!1,corte:"tiempo",clase:"InternalError",mensaje:"interrupted",ms:Date.now()-t},!0),o.ms+W.margenMs);n.on("message",d),n.on("error",u),n.on("exit",p);let h={tipo:"correr",codigo:o.codigo,fichero:o.fichero,entrada:o.entrada,contexto:o.contexto,ms:o.ms,memoriaMb:o.memoriaMb,pilaBytes:W.pilaBytes,salidaBytes:W.salidaBytes,llamadaCaracteres:W.llamadaCaracteres,enVuelo:W.llamadasEnVuelo};n.postMessage(h)})}cerrar(){this.matar()}},Ui=class{ranuras;cola=[];constructor(o=W.simultaneas){this.ranuras=Array.from({length:Math.max(1,o)},()=>new Vc)}get libres(){return this.ranuras.filter(o=>!o.ocupada).length}async correr(o){let t=this.ranuras.find(n=>!n.ocupada);for(;!t;)await new Promise(n=>this.cola.push(n)),t=this.ranuras.find(n=>!n.ocupada);t.ocupada=!0;try{return await t.correr(o)}finally{this.cola.shift()?.()}}intentar(o){return this.ranuras.some(t=>!t.ocupada)?this.correr(o):null}cerrarSiLibre(){!this.cola.length&&this.ranuras.every(o=>!o.ocupada)&&this.cerrar()}cerrar(){for(let o of this.ranuras)o.cerrar()}}});import{lookup as __}from"node:dns/promises";import{request as N_}from"node:https";import{isIP as $_}from"node:net";async function Jc(e,o,t={}){let n;try{n=new URL(e.url)}catch{throw new ge("direcci\xF3n no v\xE1lida")}if(n.protocol!=="https:")throw new ge("solo https");if(n.username||n.password)throw new ge("sin usuario ni clave en la direcci\xF3n");if(n.port&&n.port!=="443")throw new ge("solo al puerto 443");let r=n.hostname.toLowerCase().replace(/\.$/,"");if($_(r.replace(/^\[|\]$/g,""))||!Uc(o,r))throw new ge("el dominio no est\xE1 entre los dominios aceptados");let a=String(e.metodo||"GET").toUpperCase();if(!Qg.has(a))throw new ge("m\xE9todo no admitido");let s={};if(e.cabeceras&&typeof e.cabeceras=="object")for(let[m,h]of Object.entries(e.cabeceras).slice(0,30)){let b=m.toLowerCase();if(!C_.test(m)||x_.has(b)||b.startsWith("x-crm-")||b.startsWith("x-forgenex"))continue;let y=String(h);/[\r\n\0]/.test(y)||y.length>4096||(s[b]=y)}s["user-agent"]="ForgeNEX-CRM-Extension/1";let c=e.cuerpo===null||e.cuerpo===void 0?null:String(e.cuerpo);if(c!==null&&Buffer.byteLength(c)>W.red.cuerpoBytes)throw new ge(`el cuerpo pasa de ${W.red.cuerpoBytes/1024} KB`);if(c!==null&&(a==="GET"||a==="HEAD"))throw new ge("GET y HEAD no llevan cuerpo");let d=await(t.resolver??(m=>__(m,{all:!0,verbatim:!0})))(r).catch(()=>[]);if(!d.length)throw new ge(`${r.slice(0,80)} no resuelve`);if(d.some(m=>im(m.address)))throw new ge(`${r.slice(0,80)} apunta a una red interna`);let u={url:n,ip:d[0].address,familia:d[0].family===6?6:4},p=await(t.transporte??S_)(u,{metodo:a,cabeceras:s,cuerpo:c});return{host:r,respuesta:p}}function S_(e,o){return new Promise((t,n)=>{let r={...o.cabeceras,...o.cuerpo!==null?{"content-length":String(Buffer.byteLength(o.cuerpo))}:{}},a=N_({protocol:"https:",hostname:e.url.hostname,servername:e.url.hostname,port:443,path:`${e.url.pathname}${e.url.search}`,method:o.metodo,headers:r,lookup:((c,d,u)=>d?.all?u(null,[{address:e.ip,family:e.familia}]):u(null,e.ip,e.familia)),timeout:W.red.plazoMs,agent:!1},c=>{let d=[],u=0;c.on("data",p=>{if(u+=p.length,u>W.red.respuestaBytes){c.destroy(),n(new ge(`la respuesta pasa de ${W.red.respuestaBytes/1024/1024} MB`));return}d.push(p)}),c.on("end",()=>{clearTimeout(s);let p={};for(let m of j_){let h=c.headers[m];typeof h=="string"&&(p[m]=h.slice(0,2e3))}t({status:c.statusCode??0,headers:p,cuerpo:Buffer.concat(d).toString("utf8")})}),c.on("error",()=>n(new ge("la respuesta se cort\xF3")))}),s=setTimeout(()=>a.destroy(new ge("sin respuesta a tiempo")),W.red.plazoMs);a.on("timeout",()=>a.destroy(new ge("sin respuesta a tiempo"))),a.on("error",c=>{clearTimeout(s),n(c instanceof ge?c:new ge("no se ha podido conectar"))}),a.end(o.cuerpo??void 0)})}var ge,Qg,x_,C_,j_,Uc,Qc=f(()=>{am();yr();ge=class extends Error{constructor(t){super(`fetch: ${t}`);this.motivo=t}motivo},Qg=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD"]),x_=new Set(["host","connection","content-length","transfer-encoding","upgrade","te","trailer","keep-alive","proxy-authorization","proxy-connection","expect","cookie","x-forwarded-for","x-real-ip","forwarded"]),C_=/^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$/,j_=["content-type","location","retry-after","etag","last-modified"],Uc=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1))&&o.length>t.length-1)});function Hg(e,o){if(typeof o!="string"||typeof e!="string")return null;let n=(Object.hasOwn(Gg,o)?Gg[o]:null)??lo(o);if(!n)return null;let r=n.startsWith("mod_");switch(e){case"ver":return r?`${n}.ver`:O_[n]??`${n}.ver`;case"buscar":return r?`${n}.listar`:A_[n]??`${n}.buscar`;case"crear":return`${n}.crear`;case"actualizar":return`${n}.actualizar`;default:return null}}function Xg(e,o){return e.filter(t=>Uc(o,t.startsWith("*.")?`x${t.slice(1)}`:t)&&(!t.startsWith("*.")||o.includes(t)))}var Gg,O_,A_,Yg=f(()=>{Tt();Qc();Gg={contactos:"contactos",contacts:"contactos",empresas:"empresas",companies:"empresas",oportunidades:"oportunidades",deals:"oportunidades",tareas:"tareas",tasks:"tareas",notas:"notas"},O_={tareas:"tareas.obtener"},A_={tareas:"tareas.listar",notas:"notas.listar"}});var eb={};ll(eb,{iniciarDev:()=>Gc});import{createServer as E_}from"node:http";import{randomBytes as Kg}from"node:crypto";import{readFileSync as q_,realpathSync as Zg,watch as R_}from"node:fs";import{join as k_,sep as P_}from"node:path";async function Gc(e,o){let t=o?.conexion??gr(e),n=Number(Re(e,"puerto")??5173),r=Zg(process.cwd());if(!Number.isInteger(n)||n<1||n>65535)throw new Error("Puerto no v\xE1lido.");let a=Fe(r),s=(I,_)=>hr(t.api,t.clave,"/api/desarrollador/desarrollo",{espacio:t.espacio,ext_id:a.id,pase:I,funcion:_}),c=await s();await fr(r);let d=new Ui(1),u=Kg(24).toString("hex"),p=o?.cookie,m=1,h=null,b,y=R_(r,{recursive:!0},(I,_)=>{let E=String(_??"");/node_modules|\.fgx$|\.pem|^\.git[\/\\]/.test(E)||E==="interfaz/app.js"||(clearTimeout(b),b=setTimeout(()=>{h=fr(r).then(()=>{Fe(r),m++,console.log("App actualizada.")}).catch(g=>console.error("Error de desarrollo:",g.message)).finally(()=>{h=null})},100))}),v=E_(async(I,_)=>{let E=(g,x)=>{_.writeHead(g,{"content-type":"application/json","cache-control":"no-store"}),_.end(JSON.stringify(x))};try{if(![`127.0.0.1:${n}`,`localhost:${n}`].includes(I.headers.host??""))return E(403,{error:"host_no_permitido"});let g=I.headers.origin;if(g&&g!==t.api)return E(403,{error:"origen_no_permitido"});if(g===t.api&&(_.setHeader("access-control-allow-origin",t.api),_.setHeader("vary","origin")),_.setHeader("access-control-allow-methods","GET, POST, OPTIONS"),_.setHeader("access-control-allow-headers","content-type, authorization"),I.method==="OPTIONS"){_.writeHead(204),_.end();return}let x=new URL(I.url??"/",`http://127.0.0.1:${n}`),O=decodeURIComponent(x.pathname);if(!O.startsWith(`/${u}/`))return E(404,{error:"no_encontrado"});let k=O.slice(u.length+2);if(k==="__sandbox/entrar"&&I.method==="GET"&&p){_.writeHead(303,{"set-cookie":p,location:F,"cache-control":"no-store","referrer-policy":"no-referrer"}),p=void 0,_.end();return}if(k==="__forgenex/version"&&I.method==="GET")return E(200,{version:m});if(k.startsWith("__forgenex/funcion/")&&I.method==="POST"){if(g!==t.api)return E(403,{error:"origen_no_permitido"});let U=(I.headers.authorization??"").replace(/^Bearer /,"");if(!U.startsWith("crmui_"))return E(401,{error:"falta_pase"});if(!d.libres)return E(429,{error:"funcion_ocupada"});let be=k.slice(19),Be=await s(U,be),X=Fe(r).funciones.find(wr=>wr.nombre===be),Ve=Be.manifiesto.funciones.find(wr=>wr.nombre===be);if(!X||!Ve)return E(403,{error:"funcion_no_instalada"});let Ue=await fetch(`${t.api}/api/v1/capabilities`,{redirect:"error",headers:{authorization:`Bearer ${U}`,"x-espacio":String(t.espacio)}});if(!Ue.ok)return E(Ue.status,{error:"pase_revocado"});let Do=await T_(I),T=Kg(12).toString("hex"),J=0,le=0,No=await d.correr({codigo:w(X.entrada).toString("utf8"),fichero:X.entrada,entrada:Do,contexto:{extension:a.id,version:a.version,funcion:be,disparo:"desarrollo",ejecucion:T},..._l(X),manejar:async(wr,tl)=>{if(wr==="red"){if(++le>W.llamadasRed)throw new Error("Demasiadas peticiones de red.");return(await Jc(tl,Xg(Ve.red,Be.aceptados.red_hacia))).respuesta}if(++J>W.llamadasApi)throw new Error("Demasiadas llamadas al CRM.");let dn=tl,pn=dn.op??Hg(dn.accion,dn.modulo);if(!pn||!/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/.test(pn))throw new Error("Operaci\xF3n no v\xE1lida.");let rl=await fetch(`${t.api}/api/v1/capabilities`,{redirect:"error",headers:{authorization:`Bearer ${U}`,"x-espacio":String(t.espacio)}});if(!rl.ok)throw new Error("Pase caducado o revocado.");let nl=await rl.json(),il=(nl.data?.operaciones??nl.operaciones??[]).find(Ki=>Ki.id===pn);if(!il)throw new Error("Operaci\xF3n no aceptada por el administrador.");let Yi=il.metodo,al=dn.args??{},hb=Yi==="GET"?`?${new URLSearchParams(Object.entries(al).map(([Ki,gb])=>[Ki,String(gb)]))}`:"",sl=await fetch(`${t.api}/api/v1/op/${pn}${hb}`,{method:Yi,redirect:"error",headers:{authorization:`Bearer ${U}`,"x-espacio":String(t.espacio),"content-type":"application/json","idempotency-key":`dev-${T}-${J}`},...Yi==="POST"?{body:JSON.stringify(al)}:{}}),cl=await sl.json();if(!sl.ok)throw new Error(cl.error?.mensaje??"El CRM rechaz\xF3 la operaci\xF3n.");return cl.data}});return No.ok||console.error(`Funci\xF3n ${be}: ${No.clase}: ${No.mensaje}`),E(No.ok?200:422,No)}if(I.method!=="GET")return E(405,{error:"metodo_no_permitido"});if(await h,!k.startsWith("interfaz/"))return E(404,{error:"no_encontrado"});let L=w(k),V=k.endsWith(".html")?"text/html":k.endsWith(".js")?"text/javascript":k.endsWith(".css")?"text/css":"application/octet-stream";_.writeHead(200,{"content-type":V,"cache-control":"no-store"}),_.end(L)}catch(g){console.error("Error de desarrollo:",g.message),E(400,{error:"desarrollo_error",mensaje:g.message})}});function w(I){if(I.includes("\\")||I.split("/").some(g=>g===".."||g==="."||!g))throw new Error("Ruta no admitida.");let _=Zg(k_(r,I));if(!_.startsWith(r+P_))throw new Error("Ruta fuera del proyecto.");let E=q_(_);if(E.length>2*1024*1024)throw new Error("Recurso demasiado grande.");return E}let N,j=new Promise(I=>{N=I}),S=()=>{clearTimeout(b),y.close(),d.cerrar(),v.closeAllConnections(),v.close(N)},R=`http://127.0.0.1:${n}/${u}`,F=`${t.api}/#/ajustes/extensiones?desarrollo=${c.id}&local=${encodeURIComponent(R)}`;v.on("error",I=>{console.error(I.message),S(),process.exitCode=1}),process.once("SIGINT",S),process.once("SIGTERM",S),await new Promise((I,_)=>{v.once("error",_),v.listen(n,"127.0.0.1",I)}),console.log(`Desarrollo: ${R}
|
|
43
|
-
Abrir CRM: ${t.api}/#/ajustes/extensiones?desarrollo=${c.id}&local=${encodeURIComponent(
|
|
44
|
-
Recarga al guardar. Funciones: crm.pedir("desarrollo.funcion", { nombre, entrada }, { metodo: "POST", idempotencia: crypto.randomUUID() }).`),o&&(console.log(`Entrar como titular de prueba: ${
|
|
45
|
-
`).at(-1);throw new Error(`Docker ${e[0]} fall\xF3${r?`: ${r}`:"."}`)}}function
|
|
46
|
-
`).filter(Boolean))try{Me([t,"rm",...r?["-f","-v"]:[],s])}catch(c){let d=c.message;if(r&&/removal .* already in progress/i.test(d))await
|
|
47
|
-
Credencial de desarrollador local: ${x}`),
|
|
48
|
-
`)}function
|
|
49
|
-
P\xFAblica: ${t}.pub`),0}if(e==="registrar-clave"){let t=
|
|
50
|
-
`);return wb.test(n)||vb.test(s)||yb.test(s)?[`${t}: el anfitri\xF3n sustituye <html> y <body>. Pon los atributos de la app en un elemento interior.`]:[]})}vr();Ji();cn();Kr();Bs();Tc();xc();xi();Nc();Tt();var el=200;function Y_(e,o){try{return{archivo:e,ok:!0,solucion:tn(o,{topeCampos:el})}}catch(t){return{archivo:e,ok:!1,error:t instanceof Error?t.message:String(t)}}}function K_(e){try{let o=JSON.parse(e);return typeof o=="object"&&o!==null&&o.formato===at}catch{return!1}}function Z_(e,o){try{return{archivo:e,ok:!0,extension:Vo(o)}}catch(t){return{archivo:e,ok:!1,error:t instanceof Error?t.message:String(t)}}}function e0(){let e=n=>n.length>1?`${n.slice(0,-1).join(", ")} y ${n.at(-1)}`:n[0]??"",o=Pt.filter(n=>vn.has(n)).map(n=>`\xAB${n}\xBB`),t=Pt.filter(n=>!vn.has(n)).map(n=>`\xAB${n}\xBB`);return`D\xF3nde se cuelga su interfaz, en una caja aislada (iframe sin origen). Se pintan ${e(o)}${t.length?`; ${e(t)} se validan, pero todav\xEDa no se pintan`:""}. \xABpublica\xBB es la p\xE1gina sin sesi\xF3n (/app/<enlace>), con sus \xABfunciones\xBB.`}function o0(){let e=c=>({type:"string",maxLength:c}),o={type:"string",pattern:"^(\\*\\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$"},t={type:"string",maxLength:200,pattern:"^[A-Za-z0-9_./-]{1,200}$",description:"Un fichero del paquete (relativo, sin \xAB..\xBB)."},n={type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},r="Se valida, pero todav\xEDa no se ejecuta (llega en una fase siguiente de las apps).",a={type:"string",pattern:"^[a-z][a-z0-9_.-]{0,79}$",description:"Un nombre de contrato suelto (como antes de la R5): no ofrece ni pide nada."},s=c=>({type:"object",additionalProperties:!1,required:c?["contrato","de"]:["contrato"],properties:{contrato:{type:"string",pattern:"^[a-z][a-z0-9_.-]{0,79}$",description:"Su nombre (\xABtaller.vehiculos\xBB)."},...c?{de:{type:"string",description:"El id de la app que lo ofrece (\xABcom.taller.vehiculos\xBB)."}}:{},titulo:{type:"string",maxLength:80,description:"C\xF3mo se llama en la pantalla de permisos (\xABVeh\xEDculos del taller\xBB)."},modulos:{type:"object",maxProperties:20,additionalProperties:{type:"array",minItems:1,maxItems:4,items:{enum:["ver","crear","editar","borrar"]}},description:"M\xF3dulos de la soluci\xF3n de la app que lo ofrece, con su clave del manifiesto (\xABvehiculos\xBB), y sus operaciones."},eventos:{type:"array",maxItems:3,items:{enum:["registro.creado","registro.actualizado","registro.borrado"]},description:"Los de los registros de sus m\xF3dulos (con \xABver\xBB de alguno)."},herramientas:{type:"array",maxItems:20,items:{type:"string",pattern:"^[a-z][a-z0-9_]{2,40}$"},description:"Herramientas (herramientas_ia) que no escriben; se usan con la operaci\xF3n v1 \xABapp.usar_herramienta\xBB."}}});return{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://forgenex.com/sdk/extension-v1.schema.json",title:"App del CRM ForgeNEX",description:`Formato \xAB${at}\xBB, versi\xF3n ${wn}. Valida la forma; \xABforgenex-sdk validar\xBB valida todo (el mismo validador que el CRM).`,type:"object",additionalProperties:!1,required:["formato","formato_version","id","nombre","version","autor"],properties:{$schema:{type:"string"},formato:{const:at},formato_version:{type:"integer",minimum:1,maximum:wn,description:"Versi\xF3n del FORMATO (no de la app)."},id:{type:"string",maxLength:200,pattern:"^[a-z][a-z0-9-]{0,62}(\\.[a-z0-9][a-z0-9-]{0,62}){1,6}$",description:"Dominio inverso: com.tuempresa.mi-extension. No cambia nunca."},nombre:e(80),descripcion:e(500),version:{type:"string",pattern:"^(0|[1-9][0-9]{0,5})\\.(0|[1-9][0-9]{0,5})\\.(0|[1-9][0-9]{0,5})(-[0-9a-z.-]{1,30})?$",description:"La versi\xF3n de la app (semver)."},autor:{oneOf:[e(120),{type:"object",additionalProperties:!1,required:["nombre"],properties:{nombre:e(120),web:{type:"string",format:"uri",description:"https"}}}]},icono:{type:"string",pattern:"^[a-z0-9-]{1,40}$",description:"Un icono de lucide."},idiomas:{type:"array",maxItems:30,items:{type:"string",pattern:"^[a-z]{2,3}(-[A-Z]{2})?$"}},compatible_crm:{type:"string",maxLength:80,description:"Rango de versiones del CRM: \xAB>=1.6.0-284\xBB o \xAB>=1.6.0-284 <2.0.0\xBB."},licencia:e(40),politica_datos:{type:"string",format:"uri",description:"https: tu pol\xEDtica de datos. Obligatoria para entrar en la tienda si la app usa red (permisos.red_hacia)."},depende_de:{type:"array",maxItems:20,description:"Otras apps que tienen que estar instaladas.",items:{oneOf:[{type:"string"},{type:"object",additionalProperties:!1,required:["id"],properties:{id:{type:"string"},version:{type:"string"}}}]}},ofrece:{type:"array",maxItems:20,description:"Contratos que publica para otras apps: m\xF3dulos de SU soluci\xF3n (con operaciones que ella misma pide), eventos de registro de esos m\xF3dulos (que ella escucha) y herramientas suyas que no escriben. Otra app los usa con \xABusa\xBB y el permiso del administrador.",items:{oneOf:[a,s(!1)]}},usa:{type:"array",maxItems:20,description:"Contratos de otras apps que usa: \xABde\xBB es el id de la app que lo ofrece; lo que se concede es lo que esa app ofrece \u2229 lo que se pide, si el administrador lo acepta. Sin eso, 403.",items:{oneOf:[a,s(!0)]}},solucion:{...t,description:"El fichero de la soluci\xF3n del paquete (\xABsolucion.json\xBB, formato forgenex.solucion): sus m\xF3dulos se instalan como copia."},montajes:{type:"array",maxItems:20,description:e0(),items:{type:"object",additionalProperties:!1,required:["id","punto","entrada","titulo"],properties:{id:{type:"string",pattern:"^[a-z][a-z0-9_-]{0,40}$"},punto:{enum:[...Pt]},entrada:t,titulo:e(60),icono:{type:"string"},modulo:{type:"string",description:`Solo en ${[..._r].join(", ")}: el m\xF3dulo donde se cuelga (permisos.modulos tiene que pedir verlo).`},permiso:{type:"string",description:"<m\xF3dulo>.<operaci\xF3n>, dentro de \xABpermisos\xBB. No en \xABpublica\xBB."},funciones:{type:"array",maxItems:10,uniqueItems:!0,items:n,description:"Solo en \xABpublica\xBB: las funciones (de disparador \xABpublica\xBB) que su p\xE1gina puede llamar."}},allOf:[{if:{properties:{punto:{const:"publica"}},required:["punto"]},then:{not:{required:["permiso"]}},else:{not:{required:["funciones"]}}},{if:{properties:{punto:{enum:[..._r]}},required:["punto"]},then:{required:["modulo"]},else:{not:{required:["modulo"]}}}]}},funciones:{type:"array",maxItems:20,description:"Funciones JS que corren aisladas en el servidor del CRM (QuickJS), con `crm` (la API v1 recortada a lo aceptado) y `fetch` (solo a su \xABred\xBB aceptada). Las de \xABcalculo\xBB se llaman desde su interfaz por extensiones.calcular, solo con lecturas del CRM y sin red.",items:{type:"object",additionalProperties:!1,required:["nombre","entrada","disparador"],properties:{nombre:n,titulo:e(80),descripcion:e(300),entrada:{...t,description:"Su fichero .js del paquete: `export default async function (entrada, contexto) { \u2026 }`."},disparador:{type:"object",additionalProperties:!1,required:["tipo"],description:"evento (con \xABevento\xBB, que est\xE9 en permisos.eventos), programada (con \xABcron\xBB de 5 campos, como poco cada 15 min, hora de Madrid), webhook, automatizacion (un paso del dise\xF1ador) o calculo.",properties:{tipo:{enum:[...gn]},evento:{type:"string"},cron:{type:"string"}}},tope:{type:"object",additionalProperties:!1,description:"Por llamada. Por defecto, 5000 ms y 64 MB.",properties:{ms:{type:"integer",minimum:100,maximum:3e4},memoria_mb:{type:"integer",minimum:16,maximum:256}}},red:{type:"array",maxItems:10,items:o,description:"Los dominios a los que llama (dentro de permisos.red_hacia). Solo https y sin seguir redirecciones."},parametros:{type:"object",maxProperties:20,description:"Solo en las de \xABautomatizacion\xBB: su entrada en el paso del dise\xF1ador.",additionalProperties:{type:"object",additionalProperties:!1,required:["tipo","desc"],properties:{tipo:{enum:["texto","numero","si_no","fecha"]},desc:e(200),requerido:{type:"boolean"}}}},salida:{type:"array",maxItems:30,description:"Las claves que devuelve (el paso deja guardar cada una en un campo). Con { clave, titulo }, el dise\xF1ador ense\xF1a el t\xEDtulo (\xABD\xEDas h\xE1biles\xBB).",items:{anyOf:[n,{type:"object",additionalProperties:!1,required:["clave"],properties:{clave:n,titulo:e(60)}}]}}}}},servidor:{type:"object",additionalProperties:!1,required:["url"],description:`El servidor propio del desarrollador. ${r}`,properties:{url:{type:"string",format:"uri"},webhooks:{type:"array",items:{type:"string"}}}},herramientas_ia:{type:"array",maxItems:20,description:"Herramientas para Pix (1.9.0). Cada una apunta a una funci\xF3n de disparador \xABherramienta\xBB, que recibe su \xABentrada\xBB y devuelve solo las claves de su \xABsalida\xBB. Corre como la app recortada a la persona que habla con Pix. \xABescribe\xBB: la persona confirma antes; sin \xE9l, si intenta escribir, tambi\xE9n. \xABpermiso\xBB (\xABvehiculos.ver\xBB, dentro de permisos.modulos): quien no lo tiene en su papel no la ve; sin \xE9l, solo la ve quien puede ver todos los m\xF3dulos que la app tiene aceptados.",items:{type:"object",additionalProperties:!1,required:["nombre","descripcion","riesgo","funcion"],properties:{nombre:{type:"string",pattern:"^[a-z][a-z0-9_]{2,40}$"},descripcion:e(500),entrada:{type:"object",maxProperties:20,description:"Lo que Pix (o el MCP) le pasa: { campo: { tipo, desc, requerido? } }, como los \xABparametros\xBB de una funci\xF3n. Tipos: texto, numero, si_no o fecha (en el MCP salen como string, number, boolean y string con fecha). No es un JSON Schema.",additionalProperties:{type:"object",additionalProperties:!1,required:["tipo","desc"],properties:{tipo:{enum:["texto","numero","si_no","fecha"]},desc:e(200),requerido:{type:"boolean"}}}},salida:{type:"array",items:n},riesgo:{enum:["bajo","medio","alto"]},funcion:n,escribe:{type:"boolean"},permiso:{type:"string",maxLength:80}}}},ajustes:{type:"array",maxItems:40,description:"Ajustes (1.13.0): un formulario en Ajustes \u203A Apps \u203A la app, con valores POR ESPACIO (cada instalaci\xF3n los suyos; al instalar, vac\xEDos). La app los lee con la operaci\xF3n v1 `app.ajustes` y sus funciones en `contexto.ajustes`. \xABrequerido\xBB marca el campo en el formulario, pero la app se activa igual sin \xE9l: compru\xE9balo en la funci\xF3n. \xABopcion\xBB lleva \xABopciones\xBB: [{ valor, etiqueta }]; el valor de \xABmodulo\xBB es la clave de un m\xF3dulo del espacio y el de \xABcampo\xBB, \xABmodulo.campo\xBB.",items:{type:"object",additionalProperties:!1,required:["clave","etiqueta","tipo"],properties:{clave:n,etiqueta:e(80),tipo:{enum:[...bn]},opciones:{type:"array",items:{type:"object",additionalProperties:!1,required:["valor","etiqueta"],properties:{valor:e(60),etiqueta:e(80)}}},requerido:{type:"boolean"}}}},secretos:{type:"array",maxItems:10,description:"Secretos (1.13.0): claves de terceros que pone el administrador de CADA espacio en Ajustes \u203A Apps \u203A la app; van cifradas y SOLO las recibe una funci\xF3n de servidor mientras corre (`contexto.secretos`). Nunca la interfaz, la v1, el MCP ni una exportaci\xF3n.",items:{type:"object",additionalProperties:!1,required:["clave","etiqueta"],properties:{clave:n,etiqueta:e(80),descripcion:e(300)}}},conexiones:{type:"array",maxItems:20,items:{type:"object",additionalProperties:!1,required:["clave","base","tipo","operacion"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},base:{type:"string",pattern:"^https://",maxLength:1e3},tipo:{enum:["api_key","bearer","basic","oauth2"]},operacion:{type:"string",pattern:"^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$"},lugar:{enum:["cabecera","query"]},nombre:{type:"string",pattern:"^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$"}},if:{properties:{tipo:{const:"api_key"}}},then:{required:["lugar","nombre"]},else:{not:{anyOf:[{required:["lugar"]},{required:["nombre"]}]}}}},permisos:{type:"object",additionalProperties:!1,description:"Lo que pide. El administrador lo ve y lo acepta al instalar; la clave de la app nunca puede m\xE1s (ni m\xE1s que el papel de su responsable).",properties:{modulos:{type:"object",maxProperties:40,description:`M\xF3dulo \u2192 operaciones. De serie: ${Object.entries(Bo).map(([c,d])=>`${c} (${d.ops.join(", ")})`).join("; ")}. Los de su soluci\xF3n o del espacio, por su clave: ${Wo.join(", ")}.`,additionalProperties:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{enum:[...Wo]}}},almacen:{type:"boolean",description:"Guardar sus datos internos (clave-valor JSON) en el almac\xE9n de la app."},red_hacia:{type:"array",maxItems:20,items:o,description:"Los dominios a los que pueden conectarse sus funciones (\xAB*.ejemplo.com\xBB cubre sus subdominios). El administrador acepta cada uno."},eventos:{type:"array",maxItems:40,items:{type:"string"},description:"Los eventos del CRM de los que se entera (registro.creado, registro.actualizado\u2026). El administrador acepta cada uno."},archivos:{type:"array",maxItems:2,uniqueItems:!0,items:{enum:["leer","escribir"]},description:"1.17.0: los archivos del almacenamiento del espacio que la persona ELIGE con archivos.elegir() (el explorador del CRM). \xABleer\xBB: verlos (archivos.leer); \xABescribir\xBB (pide tambi\xE9n \xABleer\xBB): vincularlos a una ficha (archivos.vincular). Nunca ve el \xE1rbol ni recibe tokens de OneDrive o Google."}}}},"x-forgenex":{tamanoMaximoBytes:hn}}}function fb(e){return{nombre:e.nombre,plantilla:e.plantilla??null,modulos:e.modulos.map(o=>({clave:o.clave,nombre:o.nombre_plural,campos:o.campos.length,relaciones:o.campos.filter(t=>t.tipo==="relacion").map(t=>t.relacion??"").filter(Boolean),vistas:o.vistas?.length??0})),paneles:e.paneles?.length??0,automatizaciones:e.automatizaciones?.length??0,informes:e.informes?.length??0,mensajes:e.mensajes?.length??0,papeles:(e.papeles??[]).map(o=>`${o.nombre} (${o.base})`),portales:(e.portales??[]).map(o=>String(o.nombre??o.clave??"")),principal:e.principal??null,ejemplos:Object.fromEntries(Object.entries(e.ejemplos??{}).map(([o,t])=>[o,t.length]))}}function t0(){let e=o=>({type:"string",maxLength:o});return{$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://forgenex.com/sdk/solucion-v${pr}.schema.json`,title:"Soluci\xF3n del CRM ForgeNEX",description:`Formato \xAB${kt}\xBB, versi\xF3n ${pr}. Valida la forma; \xABforgenex-sdk validar\xBB valida todo (el mismo validador que el CRM).`,type:"object",additionalProperties:!1,required:["formato","version","nombre","modulos"],properties:{formato:{const:kt},version:{type:"integer",minimum:1,maximum:pr,description:"Versi\xF3n del FORMATO (el CRM lee esta y las anteriores)."},plantilla:{type:"object",additionalProperties:!1,required:["id","version","sector"],properties:{id:{type:"string",pattern:"^[a-z][a-z0-9_]{0,59}$"},version:{type:"integer",minimum:1},sector:{type:"string",pattern:"^[a-z][a-z0-9_]{0,39}$"},nivel:{enum:["completa","basica"]}}},nombre:e(80),descripcion:e(500),icono:{type:"string",pattern:"^[a-z0-9-]{1,40}$"},conexiones:{type:"array",maxItems:25,items:{oneOf:[{type:"object",additionalProperties:!1,required:["tipo","conector"],properties:{clave:{type:"string"},nombre:{type:"string",maxLength:80},tipo:{const:"conector"},conector:{type:"string",pattern:"^[a-z][a-z0-9_-]{0,39}$"}}},{type:"object",additionalProperties:!1,required:["clave","nombre","tipo"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,39}$"},nombre:{type:"string",minLength:1,maxLength:120},tipo:{enum:["api","mcp"]}}}]}},fuentesExternas:{type:"array",maxItems:30,items:{type:"object",additionalProperties:!1,required:["modulo","conexion","operacion","filas","mapeo","modo"],properties:{modulo:{type:"string"},conexion:{type:"string"},operacion:{type:"string"},filas:{type:"string",maxLength:160},mapeo:{type:"object",minProperties:1,additionalProperties:{type:"string",maxLength:160}},modo:{enum:["vivo","espejo"]},minutos:{type:"integer",minimum:5,maximum:10080},id_externo:{type:"string",maxLength:160},cursor:{type:"object",additionalProperties:!1,required:["ruta","parametro"],properties:{ruta:{type:"string",maxLength:160},parametro:{type:"string",maxLength:80}}}},if:{properties:{modo:{const:"espejo"}}},then:{required:["minutos","id_externo","cursor"]}}},modulos:{type:"array",minItems:1,maxItems:zi,items:{type:"object",required:["clave","nombre","nombre_plural","campos"],properties:{clave:{type:"string",pattern:"^[a-z][a-z_]{1,40}$"},nombre:e(60),nombre_plural:e(60),articulo:{enum:["un","una",null]},descripcion:e(500),icono:{enum:[...ic]},campos:{type:"array",maxItems:el,items:{type:"object",required:["clave","etiqueta","tipo"],properties:{clave:{type:"string"},etiqueta:e(80),tipo:{enum:[...rc]},formulaNativa:e(4e3),defectoNativo:e(4e3),completarNativo:{type:["object","null"],description:"Variante compilada de una copia nativa personalizada, sin alterar el autocompletado hist\xF3rico."},ajustesNativos:{type:"object",additionalProperties:!1,properties:Object.fromEntries(["contacts","companies"].map(o=>[o,{type:"object",additionalProperties:!1,properties:Object.fromEntries(Ws.map(t=>[t,{}]))}]))},siVacio:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$",description:"B\xFAsqueda escalar alternativa del mismo tipo, sin cadenas, si el valor es nulo o texto vac\xEDo. Conserva RLS y m\xE1scaras de ambos caminos."},completarDesde:{type:"object",additionalProperties:!1,required:["relacion","campo"],properties:{relacion:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},campo:{type:"string",pattern:"^[a-z][a-z0-9_.]{0,80}$"},alternativa:{type:"object",additionalProperties:!1,required:["relacion","campo"],properties:{relacion:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},campo:{type:"string",pattern:"^[a-z][a-z0-9_.]{0,80}$"}}}},description:"Copia al destino vac\xEDo un campo del mismo tipo desde una relaci\xF3n, con permisos de fila y campo. Un origen m\xFAltiple exige relaci\xF3n destino m\xFAltiple; el portal solo copia campos de sus secciones visibles."}}}},paginas:{type:"boolean"},ficha:{type:"object"},impresion:{type:"object"},validaciones:{type:"array"},vistas:{type:"array"},funcionesNativas:{type:"object",additionalProperties:!1,properties:{relacionadas:{type:"array",maxItems:20},siguientes:{type:"array",maxItems:5}}},recurso:{type:"object",description:"Sus registros son recursos (capacidad, persona): ver la gu\xEDa, \xABRecursos y reservas\xBB."},reserva:{type:"object",description:"Cada registro ocupa un recurso (puntual o semanal): ver la gu\xEDa, \xABRecursos y reservas\xBB."},asignacion:{type:"object",description:"\xABAsignar al mejor con hueco\xBB (en la demanda): ver la gu\xEDa, \xABAsignar con cupo y puntos\xBB."},pertenencia:{type:"object",description:"Un m\xF3dulo de pertenencias (demanda, oferta, desde, hasta, correccion_dias): ver la gu\xEDa."},stock:{type:"object",description:"El stock: art\xEDculo (con lotes o series), ubicaci\xF3n, documento que lo mueve (entrada, salida, ajuste, traspaso, recuento, reserva) y punto de pedido (con lo que est\xE1 en camino): ver la gu\xEDa, \xABStock\xBB."},liquidacion:{type:"object",description:"Liquidaciones de comisiones (en el m\xF3dulo de liquidaciones): origen, importe, fecha, agente, reglas con tramos y d\xF3nde va cada cosa: ver la gu\xEDa, \xABLiquidaciones\xBB."},cuota:{type:"object",description:"Cuotas peri\xF3dicas por registro: {proxima: fecha, periodicidad: semanal|quincenal|mensual|bimestral|trimestral|semestral|anual o {campo, valores}, hasta?: fecha}: ver la gu\xEDa, \xABCuotas\xBB."},relacionadas:{type:"array",maxItems:yi,description:"Columnas de OTROS m\xF3dulos en la tabla (se calculan al leer, con lo que ve quien mira): {clave, etiqueta, via, campo} trae un campo del relacionado (editable desde la tabla); {clave, etiqueta, de, via, calculo: recuento|suma|media|minimo|maximo|ultimo, campo?, filtro?} calcula sobre los que citan a este.",items:{type:"object",additionalProperties:!1,required:["clave","etiqueta","via"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},etiqueta:e(80),via:{type:"string"},siVacio:{type:"string",description:"Otra columna de traer escalar del mismo tipo, sin cadenas. Conserva el origen de edici\xF3n por fila."},campo:{type:"string"},de:{type:"string"},calculo:{enum:["recuento","suma","minimo","maximo","ultimo","media"]},filtro:{type:"array",maxItems:5}}}},siguientes:{type:"array",maxItems:_i,description:"Siguientes pasos del proceso: un bot\xF3n que crea el registro siguiente en \xABdestino\xBB (mod_<clave>), enlazado por \xABenlace\xBB (la relaci\xF3n del destino a este) y con \xABcampos\xBB copiados {campo del destino: campo de aqu\xED}.",items:{type:"object",additionalProperties:!1,required:["clave","nombre","destino","enlace"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},nombre:e(60),destino:{type:"string",pattern:"^mod_[a-z][a-z0-9_]{0,40}$"},enlace:{type:"string"},campos:{type:"object",additionalProperties:{type:"string"}}}}},personas:{type:"object",additionalProperties:!1,required:["objeto","tipo","etiqueta","plural","icono","campos"],properties:{objeto:{enum:["contacts","companies"]},tipo:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$"},de:{enum:["cliente","proveedor"]},etiqueta:{type:"string",minLength:1,maxLength:60},plural:{type:"string",minLength:1,maxLength:60},icono:{type:"string",pattern:"^[a-z0-9-]{1,40}$"},campos:{type:"object",minProperties:1,additionalProperties:{type:"string"}},configuracion:{type:"object",additionalProperties:!1,description:"Ficha, impresi\xF3n, columnas relacionadas y siguientes por objeto. Claves de origen de la soluci\xF3n, sin ids del espacio.",properties:Object.fromEntries(["contacts","companies"].map(o=>[o,{type:"object",additionalProperties:!1,properties:Object.fromEntries(["ficha","impresion","relacionadas","siguientes"].map(t=>[t,{type:t==="relacionadas"||t==="siguientes"?["array","null"]:["object","null"]}]))}]))},alternativa:{type:"object",additionalProperties:!1,required:["objeto","campos"],description:"Segundo destino separado. El principal es contacts; cada relaci\xF3n se expande en su clave de Persona y <clave>_empresa. No es una relaci\xF3n polim\xF3rfica.",properties:{objeto:{const:"companies"},campos:{type:"object",minProperties:1,additionalProperties:{type:"string"}},conversiones:{type:"object",additionalProperties:{type:"object",additionalProperties:{type:"string"}}}}},clasificacion:{type:"object",additionalProperties:!1,required:["campo","valores"],description:"Todas las opciones de una selecci\xF3n, o true/false de un booleano, a contacts/companies. vacio decide expl\xEDcitamente el valor ausente. Nunca se adivina por nombre o identificador.",properties:{campo:{type:"string"},valores:{type:"object",minProperties:2,additionalProperties:{enum:["contacts","companies"]}},vacio:{enum:["contacts","companies"]},formas:{type:"object",description:"Opciones de Empresa a claves de legalForms. Conserva etiqueta y color de la opci\xF3n hist\xF3rica, sin pisar listas existentes.",additionalProperties:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$"}},etiquetas:{type:"array",uniqueItems:!0,description:"Opciones de Persona que conservan su significado como etiqueta, con nombre y color de la opci\xF3n hist\xF3rica.",items:{type:"string"}}}},conversiones:{type:"object",description:"Mapa completo e inyectivo de opciones hist\xF3ricas a claves nativas de sector o forma jur\xEDdica. Conserva etiquetas/colores del campo. No clasifica objetos.",additionalProperties:{type:"object",minProperties:1,maxProperties:100,additionalProperties:{type:"string",minLength:1,maxLength:80}}}}}}}},vistasTabla:{type:"array",maxItems:Ec,items:{type:"object",additionalProperties:!1,required:["objeto","nombre","disposicion"],properties:{objeto:{type:"string",pattern:"^(contacts|companies|mod_[a-z][a-z0-9_]{0,40})$"},tipoContacto:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$"},nombre:e(60),config:{type:"object"},disposicion:{type:["object","null"]}}},description:"Vistas por objeto/tipo con preferencias y widgets. Un m\xF3dulo omitido con dos destinos crea una vista por objeto. Actualizaci\xF3n aditiva sin reponer bajas ni pisar personalizaciones."},separadores:{type:"array",maxItems:kc,items:{type:"object",additionalProperties:!1,required:["antes"],properties:{antes:{type:["string","null"],description:"Clave de m\xF3dulo de la soluci\xF3n, o null al final. Si se omite el m\xF3dulo, se conserva delante del siguiente m\xF3dulo real."},titulo:{type:["string","null"],maxLength:40}}}},paneles:{type:"array",maxItems:Ac,description:"Paneles de m\xE9tricas (n\xFAmero, barras, barras horizontales/apiladas/agrupadas, l\xEDneas, \xE1rea, varias l\xEDneas, dona, embudo, medidor con meta, tendencia, tabla, tabla din\xE1mica, mapa de calor; c\xE1lculos de recuento, suma, media, min, max, mediana, % del total, acumulado, tasa de conversi\xF3n, media por)."},automatizaciones:{type:"array",maxItems:qc,description:"Se instalan APAGADAS: una persona las revisa y las enciende."},ejemplos:{type:"object",description:`Datos de ejemplo por clave de m\xF3dulo (hasta ${Wi} cada uno).`,additionalProperties:{type:"array",maxItems:Wi}},informes:{type:"array",maxItems:on,description:"Informes de An\xE1lisis que se crean al publicar (de equipo).",items:{type:"object",additionalProperties:!1,required:["nombre","definicion"],properties:{nombre:e(80),descripcion:e(500),definicion:{type:"object"}}}},principal:{type:"string",description:"La clave de su m\xF3dulo PRINCIPAL (ah\xED se abre el importador al acabar la bienvenida)."},mensajes:{type:"array",maxItems:Di,description:"Plantillas de mensaje (WhatsApp o correo) de sus m\xF3dulos (mod_<clave>) o de contacts, companies y deals.",items:{type:"object",additionalProperties:!1,required:["recurso","canal","nombre","texto"],properties:{recurso:{type:"string"},tipoContacto:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$",description:"\xC1mbito opcional de una plantilla de Personas o Empresas."},canal:{enum:["whatsapp","correo"]},nombre:e(80),asunto:e(300),texto:e(5e3)}}},papeles:{type:"array",maxItems:Rc,description:"Papeles personalizados que se crean al publicar: a partir de uno de serie, con permisos de la matriz o de sus m\xF3dulos (mod_<clave>.ver|editar|borrar|exportar). Nunca gestionar miembros ni la configuraci\xF3n.",items:{type:"object",additionalProperties:!1,required:["nombre","base"],properties:{nombre:e(40),base:{enum:["administrador","miembro","lectura"]},permisos:{type:"object",additionalProperties:{enum:["si","no","suyos"]}}}}},portales:{type:"array",maxItems:Pc,description:"PORTALES (P15): personas de fuera (clientes, propietarios, hu\xE9spedes, familias, trabajadores) que entran con su usuario y ven SOLO lo alcanzable desde su ficha. Se crean al publicar, DESACTIVADOS (los activa una persona). Ver la gu\xEDa, \xABPortal\xBB.",items:{type:"object",additionalProperties:!1,required:["clave","nombre","personas","secciones"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,30}$"},nombre:e(80),personas:{oneOf:[{type:"object",additionalProperties:!1,required:["modulo","correo"],properties:{modulo:{type:"string",description:"mod_<clave> del m\xF3dulo de personas."},correo:{type:"string",description:"Su campo de correo (tipo correo)."}}},{type:"object",additionalProperties:!1,required:["objeto"],properties:{objeto:{enum:["contacts","companies"]},tipo:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$"}}}]},secciones:{type:"array",minItems:1,maxItems:10,items:{type:"object",additionalProperties:!1,required:["clave","titulo","campos"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,30}$"},titulo:e(60),modulo:{type:"string",description:"mod_<clave> (opcional: lo dice el camino)."},camino:{type:"array",maxItems:2,description:"Desde la ficha de la persona, cada paso por una relaci\xF3n: {modulo: el que TIENE el campo, campo}. Vac\xEDo: su propia ficha.",items:{type:"object",additionalProperties:!1,required:["modulo","campo"],properties:{modulo:{type:"string"},campo:{type:"string"}}}},campos:{type:"array",items:{type:"string"},maxItems:40,description:"La LISTA BLANCA de lo que se ve (nunca un secreto, un bot\xF3n ni una b\xFAsqueda)."},subtablas:{type:"object",additionalProperties:{type:"array",items:{type:"string"}}},crear:{type:"object",additionalProperties:!1,required:["campos"],properties:{campos:{type:"array",items:{type:"string"}}}},editar:{type:"object",additionalProperties:!1,required:["campos"],properties:{campos:{type:"array",items:{type:"string"}},estado:{type:"object",additionalProperties:!1,required:["campo","valores"],properties:{campo:{type:"string"},valores:{type:"array",items:{type:"string"}}}}}},adjuntar:{type:"object",additionalProperties:!1,required:["campo"],properties:{campo:{type:"string"},tipos:{type:"array",items:{enum:["image/png","image/jpeg","image/webp","image/gif","application/pdf"]}},max_mb:{type:"integer",minimum:1,maximum:25}}},comentar:{type:"boolean"}}}},textos:{type:"object",additionalProperties:!1,properties:{titulo:e(80),bienvenida:e(2e3),pie:e(500)}},marca:{type:"object",additionalProperties:!1,properties:{color:{type:"string",pattern:"^#[0-9a-fA-F]{6}$"}}}}}},proyectos:{type:"array",items:{type:"object",required:["clave","nombre"],properties:{clave:{type:"string",pattern:"^[A-Z0-9]{2,10}$"},nombre:e(100),descripcion:e(500),color:{type:"string"},icono:{type:"string"},columnas:{type:"array"}}}},plantillas_proyecto:{type:"array",items:{type:"object",required:["nombre"],properties:{nombre:e(200),clave_sugerida:{type:"string",pattern:"^[A-Z0-9]{2,10}$"},descripcion:e(500),categoria:e(50),color:{type:"string"},icono:{type:"string"},columnas:{type:"array"},tareas:{type:"array"}}}}},"x-forgenex":{tamanoMaximoBytes:Fi,topeCampos:el}}}async function ol(e){let[o,...t]=e,n=await pb(o,t);if(n!==null)return n;let r=t.includes("--json"),a=t.filter(s=>s!=="--json");if(o==="validar"&&a.length===0&&a.push("."),o==="version")return console.log(`${kt} v${pr}`),0;if(o==="esquema")return console.log(JSON.stringify(t0(),null,2)),0;if(o==="esquema-extension")return console.log(JSON.stringify(o0(),null,2)),0;if((o==="validar"||o==="previsualizar")&&a.length){let s=a.map(c=>{try{let d=H_(c).isDirectory(),u=o==="validar"&&!d&&c.toLowerCase().endsWith(".fgx")?Zc(c):null;d&&Fe(c);let p=u?Lg(u):Zc(d?mb(c,"extension.json"):c,"utf8");if(!K_(p))return Y_(c,p);let m=Z_(c,p);if(!m.ok||o!=="validar")return m;let h=u?zo(u):null,b=ul(m.extension,y=>{if(h)return h.get(y)?.toString("utf8");try{return Zc(mb(d?c:X_(c),y),"utf8")}catch{return}});return{...m,avisos:b}}catch(d){return{archivo:c,ok:!1,error:d instanceof Error?d.message:String(d)}}});if(r)console.log(JSON.stringify(s.map(c=>c.ok?"extension"in c?{archivo:c.archivo,ok:!0,extension:c.extension,..."avisos"in c&&c.avisos.length?{avisos:c.avisos}:{}}:{archivo:c.archivo,ok:!0,resumen:fb(c.solucion)}:c)));else for(let c of s){if(!c.ok){console.log(`\u2717 ${c.archivo}: ${c.error}`);continue}if("extension"in c){let d=c.extension;if("avisos"in c)for(let m of c.avisos)console.log(` ! ${m}`);console.log(`\u2713 ${c.archivo}: app \xAB${d.nombre}\xBB ${d.version} (${d.id})`);for(let[m,h]of Object.entries(d.permisos.modulos))console.log(` \xB7 pide ${m}: ${h.join(", ")}`);d.permisos.almacen&&console.log(" \xB7 pide su almac\xE9n"),d.permisos.archivos?.length&&console.log(` \xB7 pide archivos (lo que la persona elija): ${d.permisos.archivos.join(", ")}`);let u=[...new Set(d.montajes.filter(m=>!vn.has(m.punto)).map(m=>`montajes.${m.punto}`))];for(let m of d.funciones)console.log(` \xB7 funci\xF3n ${m.nombre} (${m.disparador.tipo}${m.disparador.evento?`: ${m.disparador.evento}`:m.disparador.cron?`: ${m.disparador.cron}`:""})`);for(let m of d.permisos.red_hacia)console.log(` \xB7 se conecta a ${m}`);let p=[...u,d.servidor&&"servidor"].filter(Boolean);p.length&&console.log(` (v\xE1lidos, pero a\xFAn no se ejecutan: ${p.join(", ")})`);continue}if(console.log(`\u2713 ${c.archivo}: \xAB${c.solucion.nombre}\xBB, ${c.solucion.modulos.length} m\xF3dulos`),o==="previsualizar"){let d=fb(c.solucion);for(let u of d.modulos)console.log(` \xB7 ${u.nombre} (${u.clave}): ${u.campos} campos${u.relaciones.length?`, \u2192 ${u.relaciones.join(", ")}`:""}${u.vistas?`, ${u.vistas} vistas`:""}`);console.log(` paneles: ${d.paneles} \xB7 automatizaciones: ${d.automatizaciones} (se instalan apagadas)`)}}return s.every(c=>c.ok)?0:1}return console.log("Uso: forgenex sandbox [parar] [--puerto <n>] \xB7 crear-app <nombre> [--plantilla html|react|archivos|natacion] \xB7 validar [directorio|archivo.json|archivo.fgx \u2026] [--json] \xB7 dev --espacio <id> \xB7 empaquetar [--sin-firmar] \xB7 instalar --espacio <id> (--app <id> | --paquete <archivo.fgx>) \xB7 publicar --espacio <id> --paquete <archivo.fgx> [--tienda] \xB7 revisar [--paquete <archivo.fgx>] [--json] \xB7 claves crear \xB7 registrar-clave \xB7 revocar-clave \xB7 previsualizar \xB7 esquema \xB7 esquema-extension \xB7 version"),2}process.argv[1]?.endsWith("cli.ts")&&ol(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});ol(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
|
|
73
|
+
`);if(p.trim()){s=!0;for(let[m,h]of W_(F_(p))){let b=m.trim().replace(/\s+/g," "),y=null,v=null;for(let w of h.matchAll(/(?:^|;)\s*(color|background-color|background)\s*:\s*([^;]+)/gi)){let N=z_(w[2]);N.tema&&(a=!0),w[1].toLowerCase()==="color"?y=N:v=N,!N.tema&&!N.neutro&&N.color&&(/(^|,)\s*(html|body|:root)\s*(,|$)/i.test(b)?t.push(`${d}: \xAB${b}\xBB fija ${w[1]} (${w[2].trim()}): la p\xE1gina no seguir\xE1 el tema claro y oscuro del CRM. Usa var(--background) y var(--foreground).`):n.push(`${d}: \xAB${b}\xBB usa un color fijo en ${w[1]} (${w[2].trim()}).`))}if(y?.color&&v?.color){let w=D_(y.color,v.color);w<4.5&&r.push(`${d}: \xAB${b}\xBB tiene un contraste de ${w.toFixed(2)}:1 entre el texto y el fondo (hace falta 4,5:1).`)}}}}let c=e.montajes.length>0;return c&&s&&!a&&t.push("La interfaz no usa ninguna variable del tema (var(--background), var(--foreground), var(--primary)\u2026): no parecer\xE1 del CRM ni seguir\xE1 el modo oscuro."),[We("forja","Forja: colores del tema",t,n,c?"Toma los colores del tema del CRM.":"No trae interfaz."),We("contraste","Contraste del texto (\u2265 4,5:1)",r,[],"Los colores fijos que se pueden medir tienen contraste suficiente.")]}function ao(e,o){for(let t=0;t<3;t++)if((e[t]??0)!==o[t])return(e[t]??0)<o[t];return!1}function Q_(e,o,t){let n=[],r=new Set,a=(c,d,u)=>{let p=c.toLowerCase().replace(/\.js$/,"");r.add(`${p} ${d}`);let m=d.split(".").map(Number);for(let h of V_)h.nombre.test(p)&&h.malas(m)&&n.push(`${u} trae ${h.etiqueta} ${d}, con un fallo de seguridad conocido: usa la ${h.arreglo} o posterior.`)};for(let c of o){let d=/(?:^|\/)([a-z][a-z.]*?)[-.@]v?(\d{1,3}\.\d{1,3}\.\d{1,3})(?:\.min)?\.m?js$/i.exec(c);d&&a(d[1],d[2],c)}for(let[c,d]of t)for(let u of d.matchAll(/\/\*[!*][\s\S]{0,600}?\*\//g))for(let p of u[0].matchAll(J_))a(p[1],p[2],c);let s=e.depende_de.map(c=>`Necesita la app \xAB${c.id}\xBB${c.version?` (${c.version})`:""} instalada antes.`);return We("dependencias","Dependencias sin fallos conocidos",n,s,r.size?`Librer\xEDas vistas: ${[...r].join(", ")}.`:"No se ven librer\xEDas de terceros con versi\xF3n.")}function G_(e){let o=[];for(let[t,n]of e)/\.(m?js|cjs|jsx|html?)$/i.test(t)&&(/\beval\s*\(|\bnew\s+Function\s*\(/.test(n)&&o.push(`${t} ejecuta c\xF3digo construido en tiempo de ejecuci\xF3n (eval o new Function).`),/\b(?:window\.)?(?:top|parent)\.location\b|\bdocument\.cookie\b/.test(n)&&o.push(`${t} toca la ventana de arriba o las cookies (el CRM lo impide; se mira en la revisi\xF3n).`));return We("codigo","C\xF3digo para la revisi\xF3n humana",[],o,"Nada que marcar.")}function Kc(e){let o=[...e.recursos.keys()].sort(),t=o.filter(p=>A_.test(p)).map(p=>[p,e.recursos.get(p).toString("utf8")]),{red:n,usaRed:r}=I_(e.ext,t),a=r||!!e.ext.conexiones?.length||e.ext.servidor!==null,s=G_(t),c=e.sinRed?[...a||e.ext.funciones.some(p=>p.red.length)?["La app no puede usar red ni conexiones externas."]:[],...t.flatMap(([p,m])=>/\b(?:fetch|XMLHttpRequest|WebSocket|EventSource|sendBeacon|importScripts)\b|\bimport\s*\(/.test(m)?[`${p} intenta usar una conexi\xF3n fuera del puente del CRM.`]:[]),...n.estado==="aviso"?n.detalles:[]]:[],d=[We("esquema","Manifiesto y soluci\xF3n v\xE1lidos",[],[],"El manifiesto y su soluci\xF3n pasan el validador del CRM."),e.dePix?We("firma","Montada por el CRM",[],[],"La ha montado el CRM en este espacio: no viaja a otros ni a la tienda."):We("firma","Firmada por su desarrollador",e.firmada?[]:["El paquete no va firmado: `forgenex empaquetar` con tu clave registrada."],[],e.enLocal?"Se firma al empaquetar con tu clave (la tienda exige firma).":"Firma v\xE1lida de una clave registrada."),We("tamano","Tama\xF1o",e.bytes>na?["El paquete pasa de 5 MB."]:[],[],`${(e.bytes/1024).toFixed(0)} KB de 5 MB.`),k_(e.ext,t),...U_(e.ext,t),c.length?We("red",n.titulo,c):n,We("politica","Pol\xEDtica de datos",a&&!e.ext.politica_datos?["La app se conecta fuera del CRM: a\xF1ade \xABpolitica_datos\xBB (una direcci\xF3n https con tu pol\xEDtica de datos) al manifiesto."]:[],[],e.ext.politica_datos?`Pol\xEDtica de datos: ${e.ext.politica_datos}`:"No hace falta: no se conecta fuera."),Q_(e.ext,o,t),e.sinRed&&s.estado==="aviso"?We("codigo",s.titulo,s.detalles):s],u=d.filter(p=>p.estado==="falla").length;return{ok:u===0,version:1,puntos:d,fallas:u,avisos:d.filter(p=>p.estado==="aviso").length}}var A_,Hc,nb,We,Xc,E_,R_,ib,ab,P_,T_,M_,Yc,sb,L_,cb,D_,V_,J_,lb=f(()=>{Mt();yr();A_=/\.(m?js|cjs|jsx|html?|css|svg)$/i,Hc=12,nb=e=>{let o=[...new Set(e)];return o.length>Hc?[...o.slice(0,Hc),`\u2026 y ${o.length-Hc} m\xE1s`]:o},We=(e,o,t,n=[],r="")=>({clave:e,titulo:o,estado:t.length?"falla":n.length?"aviso":"ok",detalles:t.length?nb(t):n.length?nb(n):r?[r]:[]}),Xc={buscar:"ver",ver:"ver",listar:"ver",obtener:"ver",pdf:"ver",crear:"crear",actualizar:"editar",mover:"editar",completar:"editar",borrar:"borrar"},E_=new Set(["contexto.actual","publica.llamar","app.ajustes","extensiones.calcular"]),R_=new Set(["registros.relacionadas","registros.historial","registros.opciones","registros.adjuntar","mensajes.proponer","metricas.calcular"]);ib={ver:"ver",crear:"crear",editar:"cambiar",borrar:"borrar",almacen:"guardar datos",leer:"leer",escribir:"vincular"},ab=e=>Object.hasOwn(Bo,e)?Bo[e].nombre:`\xAB${e.replace(/^mod_/,"")}\xBB`;P_=/(fetch|WebSocket|EventSource|sendBeacon|\.open|import|axios(?:\.[a-z]+)?|\$\.(?:get|post|ajax|getJSON))\s*\(\s*["'`]?$|(?:src|href|action|srcset|poster|data)\s*=\s*["']?$|url\(\s*["']?$|@import\s+(?:url\()?["']?$/i,T_=new Set(["www.w3.org","w3.org"]),M_=/(?:\.min\.(?:m?js|css)$)|(?:^|\/)(?:jquery|lodash|alpine|react|vue|preact|chart|d3|moment|axios|dompurify|underscore|bootstrap|handlebars)[^/]*\.m?js$/i,Yc=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1)));sb={white:[255,255,255],black:[0,0,0],red:[255,0,0],green:[0,128,0],blue:[0,0,255],gray:[128,128,128],grey:[128,128,128],silver:[192,192,192],yellow:[255,255,0],orange:[255,165,0],navy:[0,0,128],purple:[128,0,128],lightgray:[211,211,211],lightgrey:[211,211,211],darkgray:[169,169,169],darkgrey:[169,169,169],whitesmoke:[245,245,245],gainsboro:[220,220,220]},L_=/^(transparent|inherit|initial|unset|revert|currentcolor|none)$/i;cb=([e,o,t])=>{let n=r=>{let a=r/255;return a<=.03928?a/12.92:((a+.055)/1.055)**2.4};return .2126*n(e)+.7152*n(o)+.0722*n(t)},D_=(e,o)=>{let[t,n]=[cb(e),cb(o)].sort((r,a)=>a-r);return(t+.05)/(n+.05)};V_=[{nombre:/^jquery$/i,etiqueta:"jQuery",malas:e=>ao(e,[3,5,0]),arreglo:"3.5.0 (CVE-2020-11022)"},{nombre:/^lodash$/i,etiqueta:"Lodash",malas:e=>ao(e,[4,17,21]),arreglo:"4.17.21 (CVE-2021-23337)"},{nombre:/^moment$/i,etiqueta:"Moment.js",malas:e=>ao(e,[2,29,4]),arreglo:"2.29.4 (CVE-2022-31129)"},{nombre:/^handlebars$/i,etiqueta:"Handlebars",malas:e=>ao(e,[4,7,7]),arreglo:"4.7.7 (CVE-2021-23369)"},{nombre:/^bootstrap$/i,etiqueta:"Bootstrap",malas:e=>ao(e,[3,4,1])||e[0]===4&&ao(e,[4,3,1]),arreglo:"3.4.1 o 4.3.1 (CVE-2019-8331)"},{nombre:/^angular(js)?$/i,etiqueta:"AngularJS",malas:e=>e[0]===1,arreglo:"ninguna: AngularJS 1.x ya no recibe arreglos"},{nombre:/^dompurify$/i,etiqueta:"DOMPurify",malas:e=>e[0]===2?ao(e,[2,5,4]):ao(e,[3,1,3]),arreglo:"2.5.4 o 3.1.3 (CVE-2024-45801)"},{nombre:/^axios$/i,etiqueta:"Axios",malas:e=>e[0]===0?ao(e,[0,28,0]):ao(e,[1,6,0]),arreglo:"0.28.0 o 1.6.0 (CVE-2023-45857)"},{nombre:/^underscore$/i,etiqueta:"Underscore",malas:e=>ao(e,[1,12,1]),arreglo:"1.12.1 (CVE-2021-23358)"}];J_=/\b(jquery|lodash|moment|handlebars|bootstrap|angularjs|angular|dompurify|axios|underscore|alpine(?:js)?|react|vue|preact|chart\.js|d3)(?:\.js)?(?:\s+javascript\s+library)?[\s@:,-]*v?(\d{1,3}\.\d{1,3}\.\d{1,3})\b/gi});import{Worker as H_}from"node:worker_threads";var X_,Zc,Hi,ub=f(()=>{_r();X_=new URL(import.meta.url.endsWith(".ts")?"./caja.ts":"./caja.js",import.meta.url),Zc=class{w=null;ocupada=!1;worker(){return this.w?this.w:(this.w=new H_(X_,{resourceLimits:{maxOldGenerationSizeMb:96,maxYoungGenerationSizeMb:16,stackSizeMb:4},env:{},stdout:!0,stderr:!0}),this.w.stdout.resume(),this.w.stderr.resume(),this.w.unref(),this.w)}matar(){let o=this.w;this.w=null,o&&o.terminate().catch(()=>{})}correr(o){this.ocupada=!0;let t=Date.now(),n=this.worker();return new Promise(r=>{let a=!1,s=0,c=(b,y)=>{a||(a=!0,clearTimeout(m),n.off("message",d),n.off("error",u),n.off("exit",p),y&&this.matar(),this.ocupada=!1,r(b))},d=b=>{if(b.tipo==="llamar"){if(a)return;if(typeof b.datos!="string"||b.datos.length>W.llamadaCaracteres||s>=W.llamadasEnVuelo){n.postMessage({tipo:"respuesta",n:b.n,ok:!1,valor:typeof b.datos=="string"&&b.datos.length<=W.llamadaCaracteres?"demasiadas llamadas a la vez":"lo que se manda al CRM es demasiado grande"});return}let v=null;try{v=JSON.parse(b.datos)}catch{}s++,o.manejar(b.que,v).finally(()=>{s--}).then(w=>!a&&n.postMessage({tipo:"respuesta",n:b.n,ok:!0,valor:JSON.stringify(w??null)}),w=>!a&&n.postMessage({tipo:"respuesta",n:b.n,ok:!1,valor:w instanceof Error?w.message:String(w)}));return}let y=Date.now()-t;b.ok?c({ok:!0,salida:b.salida,ms:y},!1):c({ok:!1,corte:b.corte,clase:b.clase,mensaje:b.mensaje,ms:y},b.corte!==null)},u=b=>c({ok:!1,corte:/memory|heap/i.test(b.message)?"memoria":null,clase:"Error",mensaje:"la caja se ha cerrado",ms:Date.now()-t},!0),p=()=>c({ok:!1,corte:null,clase:"Error",mensaje:"la caja se ha cerrado",ms:Date.now()-t},!0),m=setTimeout(()=>c({ok:!1,corte:"tiempo",clase:"InternalError",mensaje:"interrupted",ms:Date.now()-t},!0),o.ms+W.margenMs);n.on("message",d),n.on("error",u),n.on("exit",p);let h={tipo:"correr",codigo:o.codigo,fichero:o.fichero,entrada:o.entrada,contexto:o.contexto,ms:o.ms,memoriaMb:o.memoriaMb,pilaBytes:W.pilaBytes,salidaBytes:W.salidaBytes,llamadaCaracteres:W.llamadaCaracteres,enVuelo:W.llamadasEnVuelo};n.postMessage(h)})}cerrar(){this.matar()}},Hi=class{ranuras;cola=[];constructor(o=W.simultaneas){this.ranuras=Array.from({length:Math.max(1,o)},()=>new Zc)}get libres(){return this.ranuras.filter(o=>!o.ocupada).length}async correr(o){let t=this.ranuras.find(n=>!n.ocupada);for(;!t;)await new Promise(n=>this.cola.push(n)),t=this.ranuras.find(n=>!n.ocupada);t.ocupada=!0;try{return await t.correr(o)}finally{this.cola.shift()?.()}}intentar(o){return this.ranuras.some(t=>!t.ocupada)?this.correr(o):null}cerrarSiLibre(){!this.cola.length&&this.ranuras.every(o=>!o.ocupada)&&this.cerrar()}cerrar(){for(let o of this.ranuras)o.cerrar()}}});import{lookup as Y_}from"node:dns/promises";import{request as K_}from"node:https";import{isIP as Z_}from"node:net";async function ol(e,o,t={}){let n;try{n=new URL(e.url)}catch{throw new ge("direcci\xF3n no v\xE1lida")}if(n.protocol!=="https:")throw new ge("solo https");if(n.username||n.password)throw new ge("sin usuario ni clave en la direcci\xF3n");if(n.port&&n.port!=="443")throw new ge("solo al puerto 443");let r=n.hostname.toLowerCase().replace(/\.$/,"");if(Z_(r.replace(/^\[|\]$/g,""))||!el(o,r))throw new ge("el dominio no est\xE1 entre los dominios aceptados");let a=String(e.metodo||"GET").toUpperCase();if(!db.has(a))throw new ge("m\xE9todo no admitido");let s={};if(e.cabeceras&&typeof e.cabeceras=="object")for(let[m,h]of Object.entries(e.cabeceras).slice(0,30)){let b=m.toLowerCase();if(!o0.test(m)||e0.has(b)||b.startsWith("x-crm-")||b.startsWith("x-forgenex"))continue;let y=String(h);/[\r\n\0]/.test(y)||y.length>4096||(s[b]=y)}s["user-agent"]="ForgeNEX-CRM-Extension/1";let c=e.cuerpo===null||e.cuerpo===void 0?null:String(e.cuerpo);if(c!==null&&Buffer.byteLength(c)>W.red.cuerpoBytes)throw new ge(`el cuerpo pasa de ${W.red.cuerpoBytes/1024} KB`);if(c!==null&&(a==="GET"||a==="HEAD"))throw new ge("GET y HEAD no llevan cuerpo");let d=await(t.resolver??(m=>Y_(m,{all:!0,verbatim:!0})))(r).catch(()=>[]);if(!d.length)throw new ge(`${r.slice(0,80)} no resuelve`);if(d.some(m=>mm(m.address)))throw new ge(`${r.slice(0,80)} apunta a una red interna`);let u={url:n,ip:d[0].address,familia:d[0].family===6?6:4},p=await(t.transporte??r0)(u,{metodo:a,cabeceras:s,cuerpo:c});return{host:r,respuesta:p}}function r0(e,o){return new Promise((t,n)=>{let r={...o.cabeceras,...o.cuerpo!==null?{"content-length":String(Buffer.byteLength(o.cuerpo))}:{}},a=K_({protocol:"https:",hostname:e.url.hostname,servername:e.url.hostname,port:443,path:`${e.url.pathname}${e.url.search}`,method:o.metodo,headers:r,lookup:((c,d,u)=>d?.all?u(null,[{address:e.ip,family:e.familia}]):u(null,e.ip,e.familia)),timeout:W.red.plazoMs,agent:!1},c=>{let d=[],u=0;c.on("data",p=>{if(u+=p.length,u>W.red.respuestaBytes){c.destroy(),n(new ge(`la respuesta pasa de ${W.red.respuestaBytes/1024/1024} MB`));return}d.push(p)}),c.on("end",()=>{clearTimeout(s);let p={};for(let m of t0){let h=c.headers[m];typeof h=="string"&&(p[m]=h.slice(0,2e3))}t({status:c.statusCode??0,headers:p,cuerpo:Buffer.concat(d).toString("utf8")})}),c.on("error",()=>n(new ge("la respuesta se cort\xF3")))}),s=setTimeout(()=>a.destroy(new ge("sin respuesta a tiempo")),W.red.plazoMs);a.on("timeout",()=>a.destroy(new ge("sin respuesta a tiempo"))),a.on("error",c=>{clearTimeout(s),n(c instanceof ge?c:new ge("no se ha podido conectar"))}),a.end(o.cuerpo??void 0)})}var ge,db,e0,o0,t0,el,tl=f(()=>{fm();_r();ge=class extends Error{constructor(t){super(`fetch: ${t}`);this.motivo=t}motivo},db=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD"]),e0=new Set(["host","connection","content-length","transfer-encoding","upgrade","te","trailer","keep-alive","proxy-authorization","proxy-connection","expect","cookie","x-forwarded-for","x-real-ip","forwarded"]),o0=/^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$/,t0=["content-type","location","retry-after","etag","last-modified"],el=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1))&&o.length>t.length-1)});function mb(e,o){if(typeof o!="string"||typeof e!="string")return null;let n=(Object.hasOwn(pb,o)?pb[o]:null)??co(o);if(!n)return null;let r=n.startsWith("mod_");switch(e){case"ver":return r?`${n}.ver`:n0[n]??`${n}.ver`;case"buscar":return r?`${n}.listar`:i0[n]??`${n}.buscar`;case"crear":return`${n}.crear`;case"actualizar":return`${n}.actualizar`;default:return null}}function fb(e,o){return e.filter(t=>el(o,t.startsWith("*.")?`x${t.slice(1)}`:t)&&(!t.startsWith("*.")||o.includes(t)))}var pb,n0,i0,hb=f(()=>{Mt();tl();pb={contactos:"contactos",contacts:"contactos",empresas:"empresas",companies:"empresas",oportunidades:"oportunidades",deals:"oportunidades",tareas:"tareas",tasks:"tareas",notas:"notas"},n0={tareas:"tareas.obtener"},i0={tareas:"tareas.listar",notas:"notas.listar"}});var wb={};bl(wb,{iniciarDev:()=>rl});import{createServer as a0}from"node:http";import{randomBytes as gb}from"node:crypto";import{readFileSync as s0,realpathSync as bb,watch as c0}from"node:fs";import{join as l0,sep as u0}from"node:path";async function rl(e,o){let t=o?.conexion??br(e),n=Number(qe(e,"puerto")??5173),r=bb(process.cwd());if(!Number.isInteger(n)||n<1||n>65535)throw new Error("Puerto no v\xE1lido.");let a=Fe(r),s=(I,_)=>gr(t.api,t.clave,"/api/desarrollador/desarrollo",{espacio:t.espacio,ext_id:a.id,pase:I,funcion:_}),c=await s();await hr(r);let d=new Hi(1),u=gb(24).toString("hex"),p=o?.cookie,m=1,h=null,b,y=c0(r,{recursive:!0},(I,_)=>{let E=String(_??"");/node_modules|\.fgx$|\.pem|^\.git[\/\\]/.test(E)||E==="interfaz/app.js"||(clearTimeout(b),b=setTimeout(()=>{h=hr(r).then(()=>{Fe(r),m++,console.log("App actualizada.")}).catch(g=>console.error("Error de desarrollo:",g.message)).finally(()=>{h=null})},100))}),v=a0(async(I,_)=>{let E=(g,x)=>{_.writeHead(g,{"content-type":"application/json","cache-control":"no-store"}),_.end(JSON.stringify(x))};try{if(![`127.0.0.1:${n}`,`localhost:${n}`].includes(I.headers.host??""))return E(403,{error:"host_no_permitido"});let g=I.headers.origin;if(g&&g!==t.api)return E(403,{error:"origen_no_permitido"});if(g===t.api&&(_.setHeader("access-control-allow-origin",t.api),_.setHeader("vary","origin")),_.setHeader("access-control-allow-methods","GET, POST, OPTIONS"),_.setHeader("access-control-allow-headers","content-type, authorization"),I.method==="OPTIONS"){_.writeHead(204),_.end();return}let x=new URL(I.url??"/",`http://127.0.0.1:${n}`),O=decodeURIComponent(x.pathname);if(!O.startsWith(`/${u}/`))return E(404,{error:"no_encontrado"});let k=O.slice(u.length+2);if(k==="__sandbox/entrar"&&I.method==="GET"&&p){_.writeHead(303,{"set-cookie":p,location:F,"cache-control":"no-store","referrer-policy":"no-referrer"}),p=void 0,_.end();return}if(k==="__forgenex/version"&&I.method==="GET")return E(200,{version:m});if(k.startsWith("__forgenex/funcion/")&&I.method==="POST"){if(g!==t.api)return E(403,{error:"origen_no_permitido"});let U=(I.headers.authorization??"").replace(/^Bearer /,"");if(!U.startsWith("crmui_"))return E(401,{error:"falta_pase"});if(!d.libres)return E(429,{error:"funcion_ocupada"});let be=k.slice(19),Be=await s(U,be),X=Fe(r).funciones.find(vr=>vr.nombre===be),Ue=Be.manifiesto.funciones.find(vr=>vr.nombre===be);if(!X||!Ue)return E(403,{error:"funcion_no_instalada"});let Ve=await fetch(`${t.api}/api/v1/capabilities`,{redirect:"error",headers:{authorization:`Bearer ${U}`,"x-espacio":String(t.espacio)}});if(!Ve.ok)return E(Ve.status,{error:"pase_revocado"});let Lo=await d0(I),T=gb(12).toString("hex"),V=0,le=0,_o=await d.correr({codigo:w(X.entrada).toString("utf8"),fichero:X.entrada,entrada:Lo,contexto:{extension:a.id,version:a.version,funcion:be,disparo:"desarrollo",ejecucion:T},...Al(X),manejar:async(vr,ul)=>{if(vr==="red"){if(++le>W.llamadasRed)throw new Error("Demasiadas peticiones de red.");return(await ol(ul,fb(Ue.red,Be.aceptados.red_hacia))).respuesta}if(++V>W.llamadasApi)throw new Error("Demasiadas llamadas al CRM.");let pn=ul,mn=pn.op??mb(pn.accion,pn.modulo);if(!mn||!/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/.test(mn))throw new Error("Operaci\xF3n no v\xE1lida.");let dl=await fetch(`${t.api}/api/v1/capabilities`,{redirect:"error",headers:{authorization:`Bearer ${U}`,"x-espacio":String(t.espacio)}});if(!dl.ok)throw new Error("Pase caducado o revocado.");let pl=await dl.json(),ml=(pl.data?.operaciones??pl.operaciones??[]).find(ta=>ta.id===mn);if(!ml)throw new Error("Operaci\xF3n no aceptada por el administrador.");let oa=ml.metodo,fl=pn.args??{},Db=oa==="GET"?`?${new URLSearchParams(Object.entries(fl).map(([ta,zb])=>[ta,String(zb)]))}`:"",hl=await fetch(`${t.api}/api/v1/op/${mn}${Db}`,{method:oa,redirect:"error",headers:{authorization:`Bearer ${U}`,"x-espacio":String(t.espacio),"content-type":"application/json","idempotency-key":`dev-${T}-${V}`},...oa==="POST"?{body:JSON.stringify(fl)}:{}}),gl=await hl.json();if(!hl.ok)throw new Error(gl.error?.mensaje??"El CRM rechaz\xF3 la operaci\xF3n.");return gl.data}});return _o.ok||console.error(`Funci\xF3n ${be}: ${_o.clase}: ${_o.mensaje}`),E(_o.ok?200:422,_o)}if(I.method!=="GET")return E(405,{error:"metodo_no_permitido"});if(await h,!k.startsWith("interfaz/"))return E(404,{error:"no_encontrado"});let D=w(k),B=k.endsWith(".html")?"text/html":k.endsWith(".js")?"text/javascript":k.endsWith(".css")?"text/css":"application/octet-stream";_.writeHead(200,{"content-type":B,"cache-control":"no-store"}),_.end(D)}catch(g){console.error("Error de desarrollo:",g.message),E(400,{error:"desarrollo_error",mensaje:g.message})}});function w(I){if(I.includes("\\")||I.split("/").some(g=>g===".."||g==="."||!g))throw new Error("Ruta no admitida.");let _=bb(l0(r,I));if(!_.startsWith(r+u0))throw new Error("Ruta fuera del proyecto.");let E=s0(_);if(E.length>2*1024*1024)throw new Error("Recurso demasiado grande.");return E}let N,j=new Promise(I=>{N=I}),S=()=>{clearTimeout(b),y.close(),d.cerrar(),v.closeAllConnections(),v.close(N)},q=`http://127.0.0.1:${n}/${u}`,F=`${t.api}/#/ajustes/extensiones?desarrollo=${c.id}&local=${encodeURIComponent(q)}`;v.on("error",I=>{console.error(I.message),S(),process.exitCode=1}),process.once("SIGINT",S),process.once("SIGTERM",S),await new Promise((I,_)=>{v.once("error",_),v.listen(n,"127.0.0.1",I)}),console.log(`Desarrollo: ${q}
|
|
74
|
+
Abrir CRM: ${t.api}/#/ajustes/extensiones?desarrollo=${c.id}&local=${encodeURIComponent(q)}
|
|
75
|
+
Recarga al guardar. Funciones: crm.pedir("desarrollo.funcion", { nombre, entrada }, { metodo: "POST", idempotencia: crypto.randomUUID() }).`),o&&(console.log(`Entrar como titular de prueba: ${q}/__sandbox/entrar`),o.signal.aborted?S():o.signal.addEventListener("abort",S,{once:!0}),await j)}async function d0(e){let o=[],t=0;for await(let n of e){if(t+=n.length,t>W.webhookBytes)throw new Error("Entrada demasiado grande.");o.push(n)}return JSON.parse(Buffer.concat(o).toString("utf8")||"null")}var nl=f(()=>{ub();_r();hb();tl();Xi();un()});var xb={};bl(xb,{sandbox:()=>v0});import{execFileSync as p0}from"node:child_process";import{randomBytes as $b}from"node:crypto";import{existsSync as vb,readFileSync as m0,readdirSync as f0}from"node:fs";import{createServer as h0}from"node:net";import{fileURLToPath as g0}from"node:url";import{setTimeout as b0}from"node:timers/promises";function Me(e,o=30){try{return p0("docker",e,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:o*1e3}).trim()}catch(t){let n=t,r=(n.stderr||n.stdout||"").trim().split(`
|
|
76
|
+
`).at(-1);throw new Error(`Docker ${e[0]} fall\xF3${r?`: ${r}`:"."}`)}}function w0(){try{let o=(process.env.DOCKER_CONTEXT?void 0:process.env.DOCKER_HOST)||Me(["context","inspect","--format","{{.Endpoints.docker.Host}}"]);if(!/^(unix|npipe):\/\//.test(o))throw new Error("contexto remoto");Me(["info","--format","{{.ServerVersion}}"])}catch{throw new Error("Hace falta Docker en marcha con un contexto local. Inicia Docker y selecciona su contexto local.")}}function yb(e){let o=Number(e);if(!Number.isInteger(o)||o<1024||o>65535)throw new Error("Usa un puerto entre 1024 y 65535.");return o}async function _b(e){let o=h0();await new Promise((t,n)=>{o.once("error",()=>n(new Error(`El puerto ${e} est\xE1 ocupado. Cierra el proceso que lo usa o elige otro con --puerto y --puerto-dev.`))),o.listen(e,Zi,()=>o.close(()=>t()))})}async function Nb(e,o){for(let t of["container","network"]){let n=["--filter",`label=${ea}=${e}`];o&&n.push("--filter",`label=${ea}.instancia=${o}`);let r=t==="container",a=Me([t,"ls","-q",...r?["-a"]:[],...n]);for(let s of a.split(`
|
|
77
|
+
`).filter(Boolean))try{Me([t,"rm",...r?["-f","-v"]:[],s])}catch(c){let d=c.message;if(r&&/removal .* already in progress/i.test(d))await il(()=>!Me(["container","ls","-aq","--filter",`id=${s}`]),`Docker sigue retirando el contenedor ${s}.`);else if(!/No such (container|network)|network .* not found/i.test(d))throw c}}}async function il(e,o){for(let t=0;t<90;t++){try{if(await e())return}catch{}await b0(500)}throw new Error(o)}async function v0(e){let[o=0,t=0]=process.versions.node.split(".").map(Number);if(o<20||o===20&&t<19||o===21||o===22&&t<12)throw new Error("Instala Node 22 LTS (22.12 o superior).");w0();let n=yb(qe(e,"puerto")??process.env.CRM_PUERTO??15504),r=`forgenex-sandbox-${n}`;if(e[0]==="parar"){await Nb(r),console.log(`Sandbox ${n} parado.`);return}let a=yb(qe(e,"puerto-dev")??n+1);if(n===a)throw new Error("El CRM y la recarga necesitan puertos distintos.");await Promise.all([_b(n),_b(a)]);try{Me(["image","inspect",Yi])}catch{let F=g0(new URL("../sandbox-local.tar.gz",import.meta.url));if(!vb(F))throw new Error(`Falta la imagen local ${Yi}. Todav\xEDa no es p\xFAblica (ver \xABSandbox\xBB en el README del paquete).`);console.log("Importando las im\xE1genes incluidas en el paquete privado\u2026"),Me(["image","load","--input",F],240)}if(!vb("extension.json")){if(f0(".").length)throw new Error("Ejecuta sandbox en la carpeta de una app o en una carpeta vac\xEDa.");process.chdir(Gi("escuela-natacion","natacion")),console.log("Proyecto creado en escuela-natacion/.")}let s=Fe(process.cwd()),c=m0(await ln(process.cwd())).toString("base64"),d=$b(8).toString("hex"),u=["--label",`${ea}=${r}`,"--label",`${ea}.instancia=${d}`],p=`${r}-red`,m=`${r}-pg`,h=`${r}-crm`,b=Ki(),y=Ki(),v=Ki(),w=`http://${Zi}:${n}`,N=(F,I)=>`postgres://${F}:${I}@${m}:5432/postgres`,j=new AbortController,S=()=>j.abort(),q;Me(["network","create",...u,p]),process.once("SIGINT",S),process.once("SIGTERM",S);try{console.log("Preparando Postgres desechable\u2026"),Me(["run","-d","--name",m,"--network",p,...u,"-e",`POSTGRES_PASSWORD=${b}`,"postgres:17"],180),await il(()=>Me(["exec",m,"pg_isready","-h",Zi,"-U","postgres"]),"Postgres no est\xE1 listo."),Me(["exec",m,"psql","-U","postgres","-v","ON_ERROR_STOP=1","-c",`create role crm_app login password '${y}'; create role crm_portal nologin noinherit; grant crm_portal to crm_app; create role crm_trabajador nologin;`]),console.log("Aplicando el esquema del CRM\u2026"),Me(["run","--rm","--name",`${r}-migrar`,"--network",p,...u,"-e",`CRM_DB_DUENO_URL=${N("postgres",b)}`,Yi,"node","dist/migrar.js"],180),Me(["run","-d","--name",h,"--network",p,...u,"-p",`${Zi}:${n}:3000`,"-e","NODE_ENV=development","-e","CRM_MODO_PRUEBAS=1","-e","CRM_WEBHOOKS=0","-e",`CRM_ENTRADA_SANDBOX=${v}`,"-e",`CRM_SECRETO=${Ki()}`,"-e",`CRM_URL=${w}`,"-e",`CRM_DB_URL=${N("crm_app",y)}`,Yi]),await il(async()=>(await fetch(`${w}/api/salud`,{signal:AbortSignal.timeout(2e3)})).ok,`El CRM no est\xE1 listo. Revisa docker logs ${h} mientras arranca.`);let F={sub:"sandbox-titular",email:"titular@demo.invalid",nombre:"Titular de prueba",apellidos:""},I=await fetch(`${w}/api/pruebas/entrar`,{method:"POST",redirect:"error",headers:{"content-type":"application/json","x-crm-pruebas":v},body:JSON.stringify(F)}),_=I.headers.getSetCookie()[0];if(!I.ok||!_)throw new Error(`El CRM rechaz\xF3 la sesi\xF3n de prueba (${I.status}).`);async function E(D,B,U="POST"){let be=await fetch(w+D,{redirect:"error",headers:{cookie:_.split(";",1)[0],"content-type":"application/json",origin:w},...B===void 0?{}:{method:U,body:JSON.stringify(B)}}),Be=await be.json();if(!be.ok)throw new Error(`${D} (${be.status}): ${Be.error?.mensaje??"CRM rechaz\xF3 la petici\xF3n"}`);return Be.data??Be}let g=await E("/api/yo");await E("/api/aceptaciones",{version:"extensiones-desarrollador-v1"}),await E("/api/preferencias/onboarding",{valor:{bienvenida:"saltada",recorrido:"saltado"}},"PUT"),await E("/api/preferencias/novedades",{valor:{visto:99999}},"PUT");let{clave:x}=await E("/api/extensiones/desarrollador/credencial",{}),O=Number(g.espacio.id);if(!Number.isSafeInteger(O)||O<1)throw new Error("El CRM no cre\xF3 el espacio de prueba.");Me(["exec",m,"psql","-U","postgres","-v","ON_ERROR_STOP=1","-c",`update espacios set tope_modulos = 30, metadatos = jsonb_set(metadatos, '{plan}', '{"estado":"cortesia"}') where id = ${O}`]);let{id:k}=await E("/api/extensiones/instalar",{paquete:c,aceptados:{...s.permisos,red_hacia:[]}});if(s.montajes.some(D=>D.punto==="publica")){let{direccion:D}=await E(`/api/extensiones/${k}/publica/crear`,{});console.log(`P\xE1gina p\xFAblica de prueba: ${D}`)}console.log(`Espacio de prueba: ${O}
|
|
78
|
+
Credencial de desarrollador local: ${x}`),q=setInterval(async()=>{try{await fetch(`${w}/api/salud`,{signal:AbortSignal.timeout(1500)})}catch{S()}},2e3),await rl(["--puerto",String(a)],{conexion:{api:w,clave:x,espacio:O},cookie:_,signal:j.signal})}finally{clearInterval(q),process.removeListener("SIGINT",S),process.removeListener("SIGTERM",S),await Nb(r,d)}}var Yi,ea,Zi,Ki,Cb=f(()=>{Xi();nl();un();Yi="forgenex-crm-sandbox:1.78.0",ea="com.forgenex.cli.sandbox",Zi="127.0.0.1",Ki=()=>$b(32).toString("hex")});import{generateKeyPairSync as y0,createPrivateKey as _0,createPublicKey as N0}from"node:crypto";import{mkdirSync as $0,readFileSync as Eb,writeFileSync as jb}from"node:fs";import{homedir as x0}from"node:os";import{join as C0,resolve as Rb}from"node:path";function qe(e,o){let t=e.indexOf(`--${o}`);if(t<0)return;let n=e[t+1];if(!n||n.startsWith("--"))throw new Error(`Falta el valor de --${o}. Consulta \xABforgenex --help\xBB para ver el uso.`);return n}function qb(e){let o;try{o=new URL(e)}catch{throw new Error("La direcci\xF3n del CRM no es v\xE1lida. Configura FORGENEX_API con la URL completa de tu CRM.")}if(o.username||o.password||o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1"].includes(o.hostname)))throw new Error("Configura FORGENEX_API con la direcci\xF3n HTTPS de tu CRM, sin usuario ni contrase\xF1a. Para pruebas locales puedes usar HTTP en localhost.");return o.origin}async function gr(e,o,t,n){let r=qb(e),a;try{a=await fetch(`${r}${t}`,{method:"POST",redirect:"error",headers:{authorization:`Bearer ${o}`,"content-type":"application/json"},body:JSON.stringify(n)})}catch{throw new Error(`No se pudo conectar con ${r}. Abre tu CRM en el navegador y comprueba FORGENEX_API.`)}let s=await a.json().catch(()=>null);if(!s)throw new Error(`El CRM respondi\xF3 con HTTP ${a.status} sin datos de la API. Comprueba FORGENEX_API y vuelve a intentarlo.`);if(!a.ok){s.error?.datos?.informe&&console.log(al(s.error.datos.informe));let c=a.status===401||a.status===403?"Comprueba la credencial, el id del espacio y que tienes acceso de desarrollador.":"Revisa el mensaje del CRM antes de repetir el comando.";throw new Error(`${a.status}: ${s.error?.mensaje??"El CRM rechaz\xF3 la petici\xF3n."} ${c}`)}return s.data}function al(e){let o=[e.ok?`Revisi\xF3n autom\xE1tica: PASA (${e.avisos} aviso(s)).`:`Revisi\xF3n autom\xE1tica: NO PASA (${e.fallas} punto(s) que corregir).`];for(let t of e.puntos){o.push(`${j0[t.estado]} ${t.titulo}`);for(let n of t.detalles)o.push(` ${n}`)}return o.join(`
|
|
79
|
+
`)}function kb(e){return Rb(qe(e,"clave-firma")??process.env.FORGENEX_CLAVE_FIRMA??C0(x0(),".forgenex/desarrollador.pem"))}function Pb(e,o){try{return Eb(e)}catch(t){throw new Error(`No se pudo leer \xAB${e}\xBB (${t.code}). ${o}`)}}function Sb(e){return Pb(kb(e),"Ejecuta \xABforgenex claves crear\xBB o indica tu clave existente con --clave-firma.").toString("utf8")}function Ob(e){try{let o=N0(_0(e));if(o.asymmetricKeyType==="ed25519")return o.export({type:"spki",format:"pem"}).toString()}catch{}throw new Error("La clave de firma debe ser una clave privada Ed25519 en PEM. Indica la ruta correcta con --clave-firma o crea una con \xABforgenex claves crear\xBB.")}function Ab(e){return Pb(e,"Comprueba la ruta o genera el .fgx con \xABforgenex empaquetar\xBB.")}function br(e){let o=qe(e,"api")??process.env.FORGENEX_API,t=process.env.FORGENEX_CLAVE_DESARROLLADOR,n=Number(qe(e,"espacio"));if(!o||!t||!Number.isSafeInteger(n)||n<1)throw new Error("Configura FORGENEX_API, FORGENEX_CLAVE_DESARROLLADOR y --espacio <id>.");return{api:qb(o),clave:t,espacio:n}}async function Tb(e,o){if(e==="crear-app"||e==="crear"||e==="crear-extension")return console.log(Gi(o[0]??"",qe(o,"plantilla"))),0;if(e==="actualizar")return Zg(process.cwd()),0;if(e==="claves"&&o[0]==="crear"){let t=kb(o);$0(Rb(t,".."),{recursive:!0,mode:448});let n=y0("ed25519");try{jb(t,n.privateKey.export({type:"pkcs8",format:"pem"}),{flag:"wx",mode:384})}catch(r){let a=r.code;throw a==="EEXIST"?new Error(`Ya tienes una clave en \xAB${t}\xBB. Usa \xABforgenex registrar-clave\xBB o elige otra ruta con --clave-firma.`):new Error(`No se pudo guardar la clave en \xAB${t}\xBB (${a}). Elige una ruta con permiso de escritura con --clave-firma.`)}return jb(`${t}.pub`,n.publicKey.export({type:"spki",format:"pem"}),{flag:"wx",mode:420}),console.log(`Clave privada: ${t}
|
|
80
|
+
P\xFAblica: ${t}.pub`),0}if(e==="registrar-clave"){let t=br(o),n=Sb(o);return console.log(JSON.stringify(await gr(t.api,t.clave,"/api/desarrollador/claves",{espacio:t.espacio,publica:Ob(n)}))),0}if(e==="revocar-clave"){let t=br(o),n=qe(o,"huella");if(!n||!/^[a-f0-9]{64}$/.test(n))throw new Error("Falta --huella <id de clave p\xFAblica>.");return console.log(JSON.stringify(await gr(t.api,t.clave,"/api/desarrollador/revocar-clave",{espacio:t.espacio,id:n}))),0}if(e==="empaquetar"){if(sn(process.cwd()),o.includes("--sin-firmar")){let n=await ln(process.cwd());return console.log(`${n} \xB7 Para \xABSubir paquete\xBB con el modo desarrollador encendido.`),0}let t=Sb(o);return console.log(await ln(process.cwd(),t,Ob(t))),0}if(e==="instalar"){let t=br(o),n=qe(o,"paquete"),r=qe(o,"app"),a=qe(o,"version");if(n&&r)throw new Error("Elige --paquete para un .fgx local o --app para una app publicada.");if(!n&&!r)throw new Error("Falta --app <id de la app publicada> o --paquete <archivo.fgx>.");let s=r?{espacio:t.espacio,app:r,version:a}:{espacio:t.espacio,paquete:Ab(n).toString("base64")},c=await gr(t.api,t.clave,"/api/desarrollador/instalar",s);return console.log(JSON.stringify(c)),c?.pendiente_permisos!==!1&&console.log("La app queda en espera. Entra en Ajustes \u203A Apps y pide al administrador que revise y acepte sus permisos."),0}if(e==="revisar"){let t=qe(o,"paquete"),n;if(t){let r=Eb(t),a=zo(r),s=a.get("extension.json");if(!s)throw new Error("Al paquete le falta \xABextension.json\xBB.");n=Kc({ext:Uo(s.toString("utf8")),recursos:a,firmada:a.has(nn),bytes:r.length,enLocal:!0})}else{let r=process.cwd();await hr(r);let a=Gc(r),s=Uo(a.get("extension.json").toString("utf8"));n=Kc({ext:s,recursos:a,firmada:!0,bytes:[...a.values()].reduce((c,d)=>c+d.length,0),enLocal:!0})}return console.log(o.includes("--json")?JSON.stringify(n,null,2):al(n)),n.ok?0:1}if(e==="publicar"){let t=br(o),n=qe(o,"paquete"),r=o.includes("--tienda");if(!n)throw new Error("Falta --paquete <archivo.fgx> (lo hace `forgenex empaquetar`).");let a=await gr(t.api,t.clave,"/api/desarrollador/publicar",{espacio:t.espacio,paquete:Ab(n).toString("base64"),...r?{tienda:!0}:{}});console.log(JSON.stringify({...a,tienda:a.tienda?{estado:a.tienda.estado,humana:a.tienda.humana,porcentaje:a.tienda.porcentaje}:void 0}));let s=c=>a.espacios.filter(d=>d.resultado===c).length;return console.log(`Publicada ${a.ext_id} ${a.version} en tus apps.`),a.tienda&&(console.log(al(a.tienda.informe)),console.log(a.tienda.estado==="aprobada"?`\xB7 En la tienda: publicada sola (no pide m\xE1s que la versi\xF3n anterior), al ${a.tienda.porcentaje} % de los espacios; sube al 100 % en 24 h si no da errores.`:`\xB7 En la tienda: en revisi\xF3n (${a.tienda.humana.map(c=>({primera:"es la primera versi\xF3n",permisos:"pide permisos nuevos",red:"se conecta a un dominio nuevo",publica:"trae una p\xE1gina p\xFAblica nueva",todas:"por ahora se revisa cada versi\xF3n"})[c]??c).join(", ")}). Te avisamos al decidir; el estado sale en el panel, Perfil \u203A Desarrollador.`)),s("activa")&&console.log(`\xB7 Actualizada sola en ${s("activa")} espacio(s): no pide m\xE1s permisos.`),s("pendiente_permisos")&&console.log(`\xB7 En ${s("pendiente_permisos")} espacio(s) pide m\xE1s permisos: su administrador los acepta en Ajustes \u203A Apps.`),s("a_mano")&&console.log(`\xB7 En ${s("a_mano")} espacio(s) no se aplica sola (cambian sus m\xF3dulos, o lo instalado all\xED no sali\xF3 de \xABMis apps\xBB): actual\xEDzala con \`forgenex instalar --app ${a.ext_id} --espacio <id>\`.`),s("modo_desarrollador")&&console.log(`\xB7 En ${s("modo_desarrollador")} espacio(s) el modo desarrollador est\xE1 apagado: no se ha tocado.`),s("error")&&console.log(`\xB7 En ${s("error")} espacio(s) no se ha podido actualizar: prueba con \`forgenex instalar --app\`.`),s("cliente_ajeno")&&console.log(`\xB7 En ${s("cliente_ajeno")} espacio(s) no se ha tocado: en ForgeNEX ya no son tuyos ni de un cliente tuyo.`),s("panel_no_disponible")&&console.log(`\xB7 En ${s("panel_no_disponible")} espacio(s) no se ha tocado porque no se ha podido comprobar con ForgeNEX: vuelve a publicar en un momento o usa \`forgenex instalar --app\`.`),0}if(e==="sandbox"&&o.includes("--help"))return console.log("Uso: forgenex sandbox [parar] [--puerto <n>] [--puerto-dev <n>]. Requiere una imagen que ForgeNEX entrega aparte y que a\xFAn no es p\xFAblica. Para probar en tu propio CRM usa dev, empaquetar e instalar."),0;if(e==="sandbox"){let{sandbox:t}=await Promise.resolve().then(()=>(Cb(),xb));return await t(o),0}if(e==="dev"){sn(process.cwd());let{iniciarDev:t}=await Promise.resolve().then(()=>(nl(),wb));return await t(o),0}return null}var j0,Xi=f(()=>{un();Vi();Mt();yr();zc();lb();j0={ok:"\u2713",aviso:"!",falla:"\u2717"}});import{readFileSync as sl,statSync as S0}from"node:fs";import{basename as O0,dirname as Mb,join as Ib}from"node:path";import{posix as ra}from"node:path";var Wb=/<(?:html|body)\b[^>]*\s(?:id|class|data-[\w-]+|style|lang|dir|on\w+)\s*=/i,Bb=/\b(?:document\s*\.\s*(?:body|documentElement)|(?:querySelector|matches)\s*\(\s*["'`](?:html|body)\b)\s*(?:\?\.|\.)?\s*(?:dataset|classList|className|getAttribute|id\b|style\b|lang\b|dir\b)/,Ub=/(?:^|[\s,{])(?:html|body)(?=[.#\[])/m;function wl(e,o){return e.montajes.flatMap(({entrada:t})=>{let n=o(t);if(!n)return[];let a=[...n.matchAll(/<(?:link|script)\b[^>]*\s(?:href|src)\s*=\s*["']([\w./-]+)["']/gi)].map(([,c])=>ra.normalize(ra.join(ra.dirname(t),c??""))),s=[n,...a.filter(c=>c.startsWith("interfaz/")).map(o)].join(`
|
|
81
|
+
`);return Wb.test(n)||Bb.test(s)||Ub.test(s)?[`${t}: el anfitri\xF3n sustituye <html> y <body>. Pon los atributos de la app en un elemento interior.`]:[]})}yr();Xi();Vi();un();Zr();Qs();Dc();Oc();Ci();jc();Mt();var cl=200;function A0(e,o){try{return{archivo:e,ok:!0,solucion:rn(o,{topeCampos:cl})}}catch(t){return{archivo:e,ok:!1,error:t instanceof Error?t.message:String(t)}}}function E0(e){try{let o=JSON.parse(e);return typeof o=="object"&&o!==null&&o.formato===at}catch{return!1}}function R0(e,o){try{return{archivo:e,ok:!0,extension:Uo(o)}}catch(t){return{archivo:e,ok:!1,error:t instanceof Error?t.message:String(t)}}}function q0(){let e=n=>n.length>1?`${n.slice(0,-1).join(", ")} y ${n.at(-1)}`:n[0]??"",o=Tt.filter(n=>yn.has(n)).map(n=>`\xAB${n}\xBB`),t=Tt.filter(n=>!yn.has(n)).map(n=>`\xAB${n}\xBB`);return`D\xF3nde se cuelga su interfaz, en una caja aislada (iframe sin origen). Se pintan ${e(o)}${t.length?`; ${e(t)} se validan, pero todav\xEDa no se pintan`:""}. \xABpublica\xBB es la p\xE1gina sin sesi\xF3n (/app/<enlace>), con sus \xABfunciones\xBB.`}function k0(){let e=c=>({type:"string",maxLength:c}),o={type:"string",pattern:"^(\\*\\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$"},t={type:"string",maxLength:200,pattern:"^[A-Za-z0-9_./-]{1,200}$",description:"Un fichero del paquete (relativo, sin \xAB..\xBB)."},n={type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},r="Se valida, pero todav\xEDa no se ejecuta (llega en una fase siguiente de las apps).",a={type:"string",pattern:"^[a-z][a-z0-9_.-]{0,79}$",description:"Un nombre de contrato suelto (como antes de la R5): no ofrece ni pide nada."},s=c=>({type:"object",additionalProperties:!1,required:c?["contrato","de"]:["contrato"],properties:{contrato:{type:"string",pattern:"^[a-z][a-z0-9_.-]{0,79}$",description:"Su nombre (\xABtaller.vehiculos\xBB)."},...c?{de:{type:"string",description:"El id de la app que lo ofrece (\xABcom.taller.vehiculos\xBB)."}}:{},titulo:{type:"string",maxLength:80,description:"C\xF3mo se llama en la pantalla de permisos (\xABVeh\xEDculos del taller\xBB)."},modulos:{type:"object",maxProperties:20,additionalProperties:{type:"array",minItems:1,maxItems:4,items:{enum:["ver","crear","editar","borrar"]}},description:"M\xF3dulos de la soluci\xF3n de la app que lo ofrece, con su clave del manifiesto (\xABvehiculos\xBB), y sus operaciones."},eventos:{type:"array",maxItems:3,items:{enum:["registro.creado","registro.actualizado","registro.borrado"]},description:"Los de los registros de sus m\xF3dulos (con \xABver\xBB de alguno)."},herramientas:{type:"array",maxItems:20,items:{type:"string",pattern:"^[a-z][a-z0-9_]{2,40}$"},description:"Herramientas (herramientas_ia) que no escriben; se usan con la operaci\xF3n v1 \xABapp.usar_herramienta\xBB."}}});return{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://forgenex.com/sdk/extension-v1.schema.json",title:"App del CRM ForgeNEX",description:`Formato \xAB${at}\xBB, versi\xF3n ${vn}. Valida la forma; \xABforgenex-sdk validar\xBB valida todo (el mismo validador que el CRM).`,type:"object",additionalProperties:!1,required:["formato","formato_version","id","nombre","version","autor"],properties:{$schema:{type:"string"},formato:{const:at},formato_version:{type:"integer",minimum:1,maximum:vn,description:"Versi\xF3n del FORMATO (no de la app)."},id:{type:"string",maxLength:200,pattern:"^[a-z][a-z0-9-]{0,62}(\\.[a-z0-9][a-z0-9-]{0,62}){1,6}$",description:"Dominio inverso: com.tuempresa.mi-extension. No cambia nunca."},nombre:e(80),descripcion:e(500),version:{type:"string",pattern:"^(0|[1-9][0-9]{0,5})\\.(0|[1-9][0-9]{0,5})\\.(0|[1-9][0-9]{0,5})(-[0-9a-z.-]{1,30})?$",description:"La versi\xF3n de la app (semver)."},autor:{oneOf:[e(120),{type:"object",additionalProperties:!1,required:["nombre"],properties:{nombre:e(120),web:{type:"string",format:"uri",description:"https"}}}]},icono:{type:"string",pattern:"^[a-z0-9-]{1,40}$",description:"Un icono de lucide."},idiomas:{type:"array",maxItems:30,items:{type:"string",pattern:"^[a-z]{2,3}(-[A-Z]{2})?$"}},compatible_crm:{type:"string",maxLength:80,description:"Rango de versiones del CRM: \xAB>=1.6.0-284\xBB o \xAB>=1.6.0-284 <2.0.0\xBB."},licencia:e(40),politica_datos:{type:"string",format:"uri",description:"https: tu pol\xEDtica de datos. Obligatoria para entrar en la tienda si la app usa red (permisos.red_hacia)."},depende_de:{type:"array",maxItems:20,description:"Otras apps que tienen que estar instaladas.",items:{oneOf:[{type:"string"},{type:"object",additionalProperties:!1,required:["id"],properties:{id:{type:"string"},version:{type:"string"}}}]}},ofrece:{type:"array",maxItems:20,description:"Contratos que publica para otras apps: m\xF3dulos de SU soluci\xF3n (con operaciones que ella misma pide), eventos de registro de esos m\xF3dulos (que ella escucha) y herramientas suyas que no escriben. Otra app los usa con \xABusa\xBB y el permiso del administrador.",items:{oneOf:[a,s(!1)]}},usa:{type:"array",maxItems:20,description:"Contratos de otras apps que usa: \xABde\xBB es el id de la app que lo ofrece; lo que se concede es lo que esa app ofrece \u2229 lo que se pide, si el administrador lo acepta. Sin eso, 403.",items:{oneOf:[a,s(!0)]}},solucion:{...t,description:"El fichero de la soluci\xF3n del paquete (\xABsolucion.json\xBB, formato forgenex.solucion): sus m\xF3dulos se instalan como copia."},montajes:{type:"array",maxItems:20,description:q0(),items:{type:"object",additionalProperties:!1,required:["id","punto","entrada","titulo"],properties:{id:{type:"string",pattern:"^[a-z][a-z0-9_-]{0,40}$"},punto:{enum:[...Tt]},entrada:t,titulo:e(60),icono:{type:"string"},modulo:{type:"string",description:`Solo en ${[...Nr].join(", ")}: el m\xF3dulo donde se cuelga (permisos.modulos tiene que pedir verlo).`},permiso:{type:"string",description:"<m\xF3dulo>.<operaci\xF3n>, dentro de \xABpermisos\xBB. No en \xABpublica\xBB."},funciones:{type:"array",maxItems:10,uniqueItems:!0,items:n,description:"Solo en \xABpublica\xBB: las funciones (de disparador \xABpublica\xBB) que su p\xE1gina puede llamar."}},allOf:[{if:{properties:{punto:{const:"publica"}},required:["punto"]},then:{not:{required:["permiso"]}},else:{not:{required:["funciones"]}}},{if:{properties:{punto:{enum:[...Nr]}},required:["punto"]},then:{required:["modulo"]},else:{not:{required:["modulo"]}}}]}},funciones:{type:"array",maxItems:20,description:"Funciones JS que corren aisladas en el servidor del CRM (QuickJS), con `crm` (la API v1 recortada a lo aceptado) y `fetch` (solo a su \xABred\xBB aceptada). Las de \xABcalculo\xBB se llaman desde su interfaz por extensiones.calcular, solo con lecturas del CRM y sin red.",items:{type:"object",additionalProperties:!1,required:["nombre","entrada","disparador"],properties:{nombre:n,titulo:e(80),descripcion:e(300),entrada:{...t,description:"Su fichero .js del paquete: `export default async function (entrada, contexto) { \u2026 }`."},disparador:{type:"object",additionalProperties:!1,required:["tipo"],description:"evento (con \xABevento\xBB, que est\xE9 en permisos.eventos), programada (con \xABcron\xBB de 5 campos, como poco cada 15 min, hora de Madrid), webhook, automatizacion (un paso del dise\xF1ador) o calculo.",properties:{tipo:{enum:[...bn]},evento:{type:"string"},cron:{type:"string"}}},tope:{type:"object",additionalProperties:!1,description:"Por llamada. Por defecto, 5000 ms y 64 MB.",properties:{ms:{type:"integer",minimum:100,maximum:3e4},memoria_mb:{type:"integer",minimum:16,maximum:256}}},red:{type:"array",maxItems:10,items:o,description:"Los dominios a los que llama (dentro de permisos.red_hacia). Solo https y sin seguir redirecciones."},parametros:{type:"object",maxProperties:20,description:"Solo en las de \xABautomatizacion\xBB: su entrada en el paso del dise\xF1ador.",additionalProperties:{type:"object",additionalProperties:!1,required:["tipo","desc"],properties:{tipo:{enum:["texto","numero","si_no","fecha"]},desc:e(200),requerido:{type:"boolean"}}}},salida:{type:"array",maxItems:30,description:"Las claves que devuelve (el paso deja guardar cada una en un campo). Con { clave, titulo }, el dise\xF1ador ense\xF1a el t\xEDtulo (\xABD\xEDas h\xE1biles\xBB).",items:{anyOf:[n,{type:"object",additionalProperties:!1,required:["clave"],properties:{clave:n,titulo:e(60)}}]}}}}},servidor:{type:"object",additionalProperties:!1,required:["url"],description:`El servidor propio del desarrollador. ${r}`,properties:{url:{type:"string",format:"uri"},webhooks:{type:"array",items:{type:"string"}}}},herramientas_ia:{type:"array",maxItems:20,description:"Herramientas para Pix (1.9.0). Cada una apunta a una funci\xF3n de disparador \xABherramienta\xBB, que recibe su \xABentrada\xBB y devuelve solo las claves de su \xABsalida\xBB. Corre como la app recortada a la persona que habla con Pix. \xABescribe\xBB: la persona confirma antes; sin \xE9l, si intenta escribir, tambi\xE9n. \xABpermiso\xBB (\xABvehiculos.ver\xBB, dentro de permisos.modulos): quien no lo tiene en su papel no la ve; sin \xE9l, solo la ve quien puede ver todos los m\xF3dulos que la app tiene aceptados.",items:{type:"object",additionalProperties:!1,required:["nombre","descripcion","riesgo","funcion"],properties:{nombre:{type:"string",pattern:"^[a-z][a-z0-9_]{2,40}$"},descripcion:e(500),entrada:{type:"object",maxProperties:20,description:"Lo que Pix (o el MCP) le pasa: { campo: { tipo, desc, requerido? } }, como los \xABparametros\xBB de una funci\xF3n. Tipos: texto, numero, si_no o fecha (en el MCP salen como string, number, boolean y string con fecha). No es un JSON Schema.",additionalProperties:{type:"object",additionalProperties:!1,required:["tipo","desc"],properties:{tipo:{enum:["texto","numero","si_no","fecha"]},desc:e(200),requerido:{type:"boolean"}}}},salida:{type:"array",items:n},riesgo:{enum:["bajo","medio","alto"]},funcion:n,escribe:{type:"boolean"},permiso:{type:"string",maxLength:80}}}},ajustes:{type:"array",maxItems:40,description:"Ajustes (1.13.0): un formulario en Ajustes \u203A Apps \u203A la app, con valores POR ESPACIO (cada instalaci\xF3n los suyos; al instalar, vac\xEDos). La app los lee con la operaci\xF3n v1 `app.ajustes` y sus funciones en `contexto.ajustes`. \xABrequerido\xBB marca el campo en el formulario, pero la app se activa igual sin \xE9l: compru\xE9balo en la funci\xF3n. \xABopcion\xBB lleva \xABopciones\xBB: [{ valor, etiqueta }]; el valor de \xABmodulo\xBB es la clave de un m\xF3dulo del espacio y el de \xABcampo\xBB, \xABmodulo.campo\xBB.",items:{type:"object",additionalProperties:!1,required:["clave","etiqueta","tipo"],properties:{clave:n,etiqueta:e(80),tipo:{enum:[...wn]},opciones:{type:"array",items:{type:"object",additionalProperties:!1,required:["valor","etiqueta"],properties:{valor:e(60),etiqueta:e(80)}}},requerido:{type:"boolean"}}}},secretos:{type:"array",maxItems:10,description:"Secretos (1.13.0): claves de terceros que pone el administrador de CADA espacio en Ajustes \u203A Apps \u203A la app; van cifradas y SOLO las recibe una funci\xF3n de servidor mientras corre (`contexto.secretos`). Nunca la interfaz, la v1, el MCP ni una exportaci\xF3n.",items:{type:"object",additionalProperties:!1,required:["clave","etiqueta"],properties:{clave:n,etiqueta:e(80),descripcion:e(300)}}},conexiones:{type:"array",maxItems:20,items:{type:"object",additionalProperties:!1,required:["clave","base","tipo","operacion"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},base:{type:"string",pattern:"^https://",maxLength:1e3},tipo:{enum:["api_key","bearer","basic","oauth2"]},operacion:{type:"string",pattern:"^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$"},lugar:{enum:["cabecera","query"]},nombre:{type:"string",pattern:"^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$"}},if:{properties:{tipo:{const:"api_key"}}},then:{required:["lugar","nombre"]},else:{not:{anyOf:[{required:["lugar"]},{required:["nombre"]}]}}}},permisos:{type:"object",additionalProperties:!1,description:"Lo que pide. El administrador lo ve y lo acepta al instalar; la clave de la app nunca puede m\xE1s (ni m\xE1s que el papel de su responsable).",properties:{modulos:{type:"object",maxProperties:40,description:`M\xF3dulo \u2192 operaciones. De serie: ${Object.entries(Bo).map(([c,d])=>`${c} (${d.ops.join(", ")})`).join("; ")}. Los de su soluci\xF3n o del espacio, por su clave: ${Wo.join(", ")}.`,additionalProperties:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{enum:[...Wo]}}},almacen:{type:"boolean",description:"Guardar sus datos internos (clave-valor JSON) en el almac\xE9n de la app."},red_hacia:{type:"array",maxItems:20,items:o,description:"Los dominios a los que pueden conectarse sus funciones (\xAB*.ejemplo.com\xBB cubre sus subdominios). El administrador acepta cada uno."},eventos:{type:"array",maxItems:40,items:{type:"string"},description:"Los eventos del CRM de los que se entera (registro.creado, registro.actualizado\u2026). El administrador acepta cada uno."},archivos:{type:"array",maxItems:2,uniqueItems:!0,items:{enum:["leer","escribir"]},description:"1.17.0: los archivos del almacenamiento del espacio que la persona ELIGE con archivos.elegir() (el explorador del CRM). \xABleer\xBB: verlos (archivos.leer); \xABescribir\xBB (pide tambi\xE9n \xABleer\xBB): vincularlos a una ficha (archivos.vincular). Nunca ve el \xE1rbol ni recibe tokens de OneDrive o Google."}}}},"x-forgenex":{tamanoMaximoBytes:gn}}}function Lb(e){return{nombre:e.nombre,plantilla:e.plantilla??null,modulos:e.modulos.map(o=>({clave:o.clave,nombre:o.nombre_plural,campos:o.campos.length,relaciones:o.campos.filter(t=>t.tipo==="relacion").map(t=>t.relacion??"").filter(Boolean),vistas:o.vistas?.length??0})),paneles:e.paneles?.length??0,automatizaciones:e.automatizaciones?.length??0,informes:e.informes?.length??0,mensajes:e.mensajes?.length??0,papeles:(e.papeles??[]).map(o=>`${o.nombre} (${o.base})`),portales:(e.portales??[]).map(o=>String(o.nombre??o.clave??"")),principal:e.principal??null,ejemplos:Object.fromEntries(Object.entries(e.ejemplos??{}).map(([o,t])=>[o,t.length]))}}function P0(){let e=o=>({type:"string",maxLength:o});return{$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://forgenex.com/sdk/solucion-v${mr}.schema.json`,title:"Soluci\xF3n del CRM ForgeNEX",description:`Formato \xAB${kt}\xBB, versi\xF3n ${mr}. Valida la forma; \xABforgenex-sdk validar\xBB valida todo (el mismo validador que el CRM).`,type:"object",additionalProperties:!1,required:["formato","version","nombre","modulos"],properties:{formato:{const:kt},version:{type:"integer",minimum:1,maximum:mr,description:"Versi\xF3n del FORMATO (el CRM lee esta y las anteriores)."},plantilla:{type:"object",additionalProperties:!1,required:["id","version","sector"],properties:{id:{type:"string",pattern:"^[a-z][a-z0-9_]{0,59}$"},version:{type:"integer",minimum:1},sector:{type:"string",pattern:"^[a-z][a-z0-9_]{0,39}$"},nivel:{enum:["completa","basica"]}}},nombre:e(80),descripcion:e(500),icono:{type:"string",pattern:"^[a-z0-9-]{1,40}$"},conexiones:{type:"array",maxItems:25,items:{oneOf:[{type:"object",additionalProperties:!1,required:["tipo","conector"],properties:{clave:{type:"string"},nombre:{type:"string",maxLength:80},tipo:{const:"conector"},conector:{type:"string",pattern:"^[a-z][a-z0-9_-]{0,39}$"}}},{type:"object",additionalProperties:!1,required:["clave","nombre","tipo"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,39}$"},nombre:{type:"string",minLength:1,maxLength:120},tipo:{enum:["api","mcp"]}}}]}},fuentesExternas:{type:"array",maxItems:30,items:{type:"object",additionalProperties:!1,required:["modulo","conexion","operacion","filas","mapeo","modo"],properties:{modulo:{type:"string"},conexion:{type:"string"},operacion:{type:"string"},filas:{type:"string",maxLength:160},mapeo:{type:"object",minProperties:1,additionalProperties:{type:"string",maxLength:160}},modo:{enum:["vivo","espejo"]},minutos:{type:"integer",minimum:5,maximum:10080},id_externo:{type:"string",maxLength:160},cursor:{type:"object",additionalProperties:!1,required:["ruta","parametro"],properties:{ruta:{type:"string",maxLength:160},parametro:{type:"string",maxLength:80}}}},if:{properties:{modo:{const:"espejo"}}},then:{required:["minutos","id_externo","cursor"]}}},modulos:{type:"array",minItems:1,maxItems:Fi,items:{type:"object",required:["clave","nombre","nombre_plural","campos"],properties:{clave:{type:"string",pattern:"^[a-z][a-z_]{1,40}$"},nombre:e(60),nombre_plural:e(60),articulo:{enum:["un","una",null]},descripcion:e(500),icono:{enum:[...lc]},campos:{type:"array",maxItems:cl,items:{type:"object",required:["clave","etiqueta","tipo"],properties:{clave:{type:"string"},etiqueta:e(80),tipo:{enum:[...sc]},formulaNativa:e(4e3),defectoNativo:e(4e3),completarNativo:{type:["object","null"],description:"Variante compilada de una copia nativa personalizada, sin alterar el autocompletado hist\xF3rico."},ajustesNativos:{type:"object",additionalProperties:!1,properties:Object.fromEntries(["contacts","companies"].map(o=>[o,{type:"object",additionalProperties:!1,properties:Object.fromEntries(Js.map(t=>[t,{}]))}]))},siVacio:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$",description:"B\xFAsqueda escalar alternativa del mismo tipo, sin cadenas, si el valor es nulo o texto vac\xEDo. Conserva RLS y m\xE1scaras de ambos caminos."},completarDesde:{type:"object",additionalProperties:!1,required:["relacion","campo"],properties:{relacion:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},campo:{type:"string",pattern:"^[a-z][a-z0-9_.]{0,80}$"},alternativa:{type:"object",additionalProperties:!1,required:["relacion","campo"],properties:{relacion:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},campo:{type:"string",pattern:"^[a-z][a-z0-9_.]{0,80}$"}}}},description:"Copia al destino vac\xEDo un campo del mismo tipo desde una relaci\xF3n, con permisos de fila y campo. Un origen m\xFAltiple exige relaci\xF3n destino m\xFAltiple; el portal solo copia campos de sus secciones visibles."}}}},paginas:{type:"boolean"},ficha:{type:"object"},impresion:{type:"object"},validaciones:{type:"array"},vistas:{type:"array"},funcionesNativas:{type:"object",additionalProperties:!1,properties:{relacionadas:{type:"array",maxItems:20},siguientes:{type:"array",maxItems:5}}},recurso:{type:"object",description:"Sus registros son recursos (capacidad, persona): ver la gu\xEDa, \xABRecursos y reservas\xBB."},reserva:{type:"object",description:"Cada registro ocupa un recurso (puntual o semanal): ver la gu\xEDa, \xABRecursos y reservas\xBB."},asignacion:{type:"object",description:"\xABAsignar al mejor con hueco\xBB (en la demanda): ver la gu\xEDa, \xABAsignar con cupo y puntos\xBB."},pertenencia:{type:"object",description:"Un m\xF3dulo de pertenencias (demanda, oferta, desde, hasta, correccion_dias): ver la gu\xEDa."},stock:{type:"object",description:"El stock: art\xEDculo (con lotes o series), ubicaci\xF3n, documento que lo mueve (entrada, salida, ajuste, traspaso, recuento, reserva) y punto de pedido (con lo que est\xE1 en camino): ver la gu\xEDa, \xABStock\xBB."},liquidacion:{type:"object",description:"Liquidaciones de comisiones (en el m\xF3dulo de liquidaciones): origen, importe, fecha, agente, reglas con tramos y d\xF3nde va cada cosa: ver la gu\xEDa, \xABLiquidaciones\xBB."},cuota:{type:"object",description:"Cuotas peri\xF3dicas por registro: {proxima: fecha, periodicidad: semanal|quincenal|mensual|bimestral|trimestral|semestral|anual o {campo, valores}, hasta?: fecha}: ver la gu\xEDa, \xABCuotas\xBB."},relacionadas:{type:"array",maxItems:_i,description:"Columnas de OTROS m\xF3dulos en la tabla (se calculan al leer, con lo que ve quien mira): {clave, etiqueta, via, campo} trae un campo del relacionado (editable desde la tabla); {clave, etiqueta, de, via, calculo: recuento|suma|media|minimo|maximo|ultimo, campo?, filtro?} calcula sobre los que citan a este.",items:{type:"object",additionalProperties:!1,required:["clave","etiqueta","via"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},etiqueta:e(80),via:{type:"string"},siVacio:{type:"string",description:"Otra columna de traer escalar del mismo tipo, sin cadenas. Conserva el origen de edici\xF3n por fila."},campo:{type:"string"},de:{type:"string"},calculo:{enum:["recuento","suma","minimo","maximo","ultimo","media"]},filtro:{type:"array",maxItems:5}}}},siguientes:{type:"array",maxItems:Ni,description:"Siguientes pasos del proceso: un bot\xF3n que crea el registro siguiente en \xABdestino\xBB (mod_<clave>), enlazado por \xABenlace\xBB (la relaci\xF3n del destino a este) y con \xABcampos\xBB copiados {campo del destino: campo de aqu\xED}.",items:{type:"object",additionalProperties:!1,required:["clave","nombre","destino","enlace"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,40}$"},nombre:e(60),destino:{type:"string",pattern:"^mod_[a-z][a-z0-9_]{0,40}$"},enlace:{type:"string"},campos:{type:"object",additionalProperties:{type:"string"}}}}},personas:{type:"object",additionalProperties:!1,required:["objeto","tipo","etiqueta","plural","icono","campos"],properties:{objeto:{enum:["contacts","companies"]},tipo:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$"},de:{enum:["cliente","proveedor"]},etiqueta:{type:"string",minLength:1,maxLength:60},plural:{type:"string",minLength:1,maxLength:60},icono:{type:"string",pattern:"^[a-z0-9-]{1,40}$"},campos:{type:"object",minProperties:1,additionalProperties:{type:"string"}},configuracion:{type:"object",additionalProperties:!1,description:"Ficha, impresi\xF3n, columnas relacionadas y siguientes por objeto. Claves de origen de la soluci\xF3n, sin ids del espacio.",properties:Object.fromEntries(["contacts","companies"].map(o=>[o,{type:"object",additionalProperties:!1,properties:Object.fromEntries(["ficha","impresion","relacionadas","siguientes"].map(t=>[t,{type:t==="relacionadas"||t==="siguientes"?["array","null"]:["object","null"]}]))}]))},alternativa:{type:"object",additionalProperties:!1,required:["objeto","campos"],description:"Segundo destino separado. El principal es contacts; cada relaci\xF3n se expande en su clave de Persona y <clave>_empresa. No es una relaci\xF3n polim\xF3rfica.",properties:{objeto:{const:"companies"},campos:{type:"object",minProperties:1,additionalProperties:{type:"string"}},conversiones:{type:"object",additionalProperties:{type:"object",additionalProperties:{type:"string"}}}}},clasificacion:{type:"object",additionalProperties:!1,required:["campo","valores"],description:"Todas las opciones de una selecci\xF3n, o true/false de un booleano, a contacts/companies. vacio decide expl\xEDcitamente el valor ausente. Nunca se adivina por nombre o identificador.",properties:{campo:{type:"string"},valores:{type:"object",minProperties:2,additionalProperties:{enum:["contacts","companies"]}},vacio:{enum:["contacts","companies"]},formas:{type:"object",description:"Opciones de Empresa a claves de legalForms. Conserva etiqueta y color de la opci\xF3n hist\xF3rica, sin pisar listas existentes.",additionalProperties:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$"}},etiquetas:{type:"array",uniqueItems:!0,description:"Opciones de Persona que conservan su significado como etiqueta, con nombre y color de la opci\xF3n hist\xF3rica.",items:{type:"string"}}}},conversiones:{type:"object",description:"Mapa completo e inyectivo de opciones hist\xF3ricas a claves nativas de sector o forma jur\xEDdica. Conserva etiquetas/colores del campo. No clasifica objetos.",additionalProperties:{type:"object",minProperties:1,maxProperties:100,additionalProperties:{type:"string",minLength:1,maxLength:80}}}}}}}},vistasTabla:{type:"array",maxItems:Pc,items:{type:"object",additionalProperties:!1,required:["objeto","nombre","disposicion"],properties:{objeto:{type:"string",pattern:"^(contacts|companies|mod_[a-z][a-z0-9_]{0,40})$"},tipoContacto:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$"},nombre:e(60),config:{type:"object"},disposicion:{type:["object","null"]}}},description:"Vistas por objeto/tipo con preferencias y widgets. Un m\xF3dulo omitido con dos destinos crea una vista por objeto. Actualizaci\xF3n aditiva sin reponer bajas ni pisar personalizaciones."},separadores:{type:"array",maxItems:Ic,items:{type:"object",additionalProperties:!1,required:["antes"],properties:{antes:{type:["string","null"],description:"Clave de m\xF3dulo de la soluci\xF3n, o null al final. Si se omite el m\xF3dulo, se conserva delante del siguiente m\xF3dulo real."},titulo:{type:["string","null"],maxLength:40}}}},paneles:{type:"array",maxItems:kc,description:"Paneles de m\xE9tricas (n\xFAmero, barras, barras horizontales/apiladas/agrupadas, l\xEDneas, \xE1rea, varias l\xEDneas, dona, embudo, medidor con meta, tendencia, tabla, tabla din\xE1mica, mapa de calor; c\xE1lculos de recuento, suma, media, min, max, mediana, % del total, acumulado, tasa de conversi\xF3n, media por)."},automatizaciones:{type:"array",maxItems:Tc,description:"Se instalan APAGADAS: una persona las revisa y las enciende."},ejemplos:{type:"object",description:`Datos de ejemplo por clave de m\xF3dulo (hasta ${Bi} cada uno).`,additionalProperties:{type:"array",maxItems:Bi}},informes:{type:"array",maxItems:tn,description:"Informes de An\xE1lisis que se crean al publicar (de equipo).",items:{type:"object",additionalProperties:!1,required:["nombre","definicion"],properties:{nombre:e(80),descripcion:e(500),definicion:{type:"object"}}}},principal:{type:"string",description:"La clave de su m\xF3dulo PRINCIPAL (ah\xED se abre el importador al acabar la bienvenida)."},mensajes:{type:"array",maxItems:Di,description:"Plantillas de mensaje (WhatsApp o correo) de sus m\xF3dulos (mod_<clave>) o de contacts, companies y deals.",items:{type:"object",additionalProperties:!1,required:["recurso","canal","nombre","texto"],properties:{recurso:{type:"string"},tipoContacto:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$",description:"\xC1mbito opcional de una plantilla de Personas o Empresas."},canal:{enum:["whatsapp","correo"]},nombre:e(80),asunto:e(300),texto:e(5e3)}}},papeles:{type:"array",maxItems:Mc,description:"Papeles personalizados que se crean al publicar: a partir de uno de serie, con permisos de la matriz o de sus m\xF3dulos (mod_<clave>.ver|editar|borrar|exportar). Nunca gestionar miembros ni la configuraci\xF3n.",items:{type:"object",additionalProperties:!1,required:["nombre","base"],properties:{nombre:e(40),base:{enum:["administrador","miembro","lectura"]},permisos:{type:"object",additionalProperties:{enum:["si","no","suyos"]}}}}},portales:{type:"array",maxItems:Lc,description:"PORTALES (P15): personas de fuera (clientes, propietarios, hu\xE9spedes, familias, trabajadores) que entran con su usuario y ven SOLO lo alcanzable desde su ficha. Se crean al publicar, DESACTIVADOS (los activa una persona). Ver la gu\xEDa, \xABPortal\xBB.",items:{type:"object",additionalProperties:!1,required:["clave","nombre","personas","secciones"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,30}$"},nombre:e(80),personas:{oneOf:[{type:"object",additionalProperties:!1,required:["modulo","correo"],properties:{modulo:{type:"string",description:"mod_<clave> del m\xF3dulo de personas."},correo:{type:"string",description:"Su campo de correo (tipo correo)."}}},{type:"object",additionalProperties:!1,required:["objeto"],properties:{objeto:{enum:["contacts","companies"]},tipo:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,59}$"}}}]},secciones:{type:"array",minItems:1,maxItems:10,items:{type:"object",additionalProperties:!1,required:["clave","titulo","campos"],properties:{clave:{type:"string",pattern:"^[a-z][a-z0-9_]{0,30}$"},titulo:e(60),modulo:{type:"string",description:"mod_<clave> (opcional: lo dice el camino)."},camino:{type:"array",maxItems:2,description:"Desde la ficha de la persona, cada paso por una relaci\xF3n: {modulo: el que TIENE el campo, campo}. Vac\xEDo: su propia ficha.",items:{type:"object",additionalProperties:!1,required:["modulo","campo"],properties:{modulo:{type:"string"},campo:{type:"string"}}}},campos:{type:"array",items:{type:"string"},maxItems:40,description:"La LISTA BLANCA de lo que se ve (nunca un secreto, un bot\xF3n ni una b\xFAsqueda)."},subtablas:{type:"object",additionalProperties:{type:"array",items:{type:"string"}}},crear:{type:"object",additionalProperties:!1,required:["campos"],properties:{campos:{type:"array",items:{type:"string"}}}},editar:{type:"object",additionalProperties:!1,required:["campos"],properties:{campos:{type:"array",items:{type:"string"}},estado:{type:"object",additionalProperties:!1,required:["campo","valores"],properties:{campo:{type:"string"},valores:{type:"array",items:{type:"string"}}}}}},adjuntar:{type:"object",additionalProperties:!1,required:["campo"],properties:{campo:{type:"string"},tipos:{type:"array",items:{enum:["image/png","image/jpeg","image/webp","image/gif","application/pdf"]}},max_mb:{type:"integer",minimum:1,maximum:25}}},comentar:{type:"boolean"}}}},textos:{type:"object",additionalProperties:!1,properties:{titulo:e(80),bienvenida:e(2e3),pie:e(500)}},marca:{type:"object",additionalProperties:!1,properties:{color:{type:"string",pattern:"^#[0-9a-fA-F]{6}$"}}}}}},proyectos:{type:"array",items:{type:"object",required:["clave","nombre"],properties:{clave:{type:"string",pattern:"^[A-Z0-9]{2,10}$"},nombre:e(100),descripcion:e(500),color:{type:"string"},icono:{type:"string"},columnas:{type:"array"}}}},plantillas_proyecto:{type:"array",items:{type:"object",required:["nombre"],properties:{nombre:e(200),clave_sugerida:{type:"string",pattern:"^[A-Z0-9]{2,10}$"},descripcion:e(500),categoria:e(50),color:{type:"string"},icono:{type:"string"},columnas:{type:"array"},tareas:{type:"array"}}}}},"x-forgenex":{tamanoMaximoBytes:Wi,topeCampos:cl}}}async function ll(e){let[o,...t]=e,n=await Tb(o,t);if(n!==null)return n;let r=t.includes("--json"),a=t.filter(s=>s!=="--json");if(o==="validar"&&a.length===0&&a.push("."),o==="version")return console.log(`${kt} v${mr}`),0;if(o==="esquema")return console.log(JSON.stringify(P0(),null,2)),0;if(o==="esquema-extension")return console.log(JSON.stringify(k0(),null,2)),0;if((o==="validar"||o==="previsualizar")&&a.length){let s=a.map(d=>{try{let u=S0(d).isDirectory(),p=o==="validar"&&!u&&d.toLowerCase().endsWith(".fgx")?sl(d):null;o==="validar"&&!p&&sn(u?d:Mb(d)),u&&Fe(d);let m=p?rb(p):sl(u?Ib(d,"extension.json"):d,"utf8");if(!(u||p||O0(d)==="extension.json"||E0(m)))return A0(d,m);let h=R0(d,m);if(!h.ok||o!=="validar")return h;let b=p?zo(p):null,y=wl(h.extension,v=>{if(b)return b.get(v)?.toString("utf8");try{return sl(Ib(u?d:Mb(d),v),"utf8")}catch{return}});return{...h,avisos:y}}catch(u){let p=u instanceof Error?u.message:String(u);return{archivo:d,ok:!1,error:p}}}),c=d=>o!=="validar"?d:d.includes("ENOENT")?`${d} Comprueba la ruta y que la entrada declarada en el manifiesto exista.`:d.includes("versi\xF3n del formato m\xE1s nueva")?`${d} Adapta el manifiesto a la versi\xF3n de formato indicada en extension.schema.json y revisa sus campos antes de cambiar formato_version.`:`${d} Corrige el campo indicado seg\xFAn extension.schema.json o solucion.schema.json y vuelve a validar.`;if(r)console.log(JSON.stringify(s.map(d=>d.ok?"extension"in d?{archivo:d.archivo,ok:!0,extension:d.extension,..."avisos"in d&&d.avisos.length?{avisos:d.avisos}:{}}:{archivo:d.archivo,ok:!0,resumen:Lb(d.solucion)}:{...d,error:c(d.error)})));else for(let d of s){if(!d.ok){console.log(`\u2717 ${d.archivo}: ${c(d.error)}`);continue}if("extension"in d){let u=d.extension;if("avisos"in d)for(let h of d.avisos)console.log(` ! ${h}`);console.log(`\u2713 ${d.archivo}: app \xAB${u.nombre}\xBB ${u.version} (${u.id})`);for(let[h,b]of Object.entries(u.permisos.modulos))console.log(` \xB7 pide ${h}: ${b.join(", ")}`);u.permisos.almacen&&console.log(" \xB7 pide su almac\xE9n"),u.permisos.archivos?.length&&console.log(` \xB7 pide archivos (lo que la persona elija): ${u.permisos.archivos.join(", ")}`);let p=[...new Set(u.montajes.filter(h=>!yn.has(h.punto)).map(h=>`montajes.${h.punto}`))];for(let h of u.funciones)console.log(` \xB7 funci\xF3n ${h.nombre} (${h.disparador.tipo}${h.disparador.evento?`: ${h.disparador.evento}`:h.disparador.cron?`: ${h.disparador.cron}`:""})`);for(let h of u.permisos.red_hacia)console.log(` \xB7 se conecta a ${h}`);let m=[...p,u.servidor&&"servidor"].filter(Boolean);m.length&&console.log(` (v\xE1lidos, pero a\xFAn no se ejecutan: ${m.join(", ")})`);continue}if(console.log(`\u2713 ${d.archivo}: \xAB${d.solucion.nombre}\xBB, ${d.solucion.modulos.length} m\xF3dulos`),o==="previsualizar"){let u=Lb(d.solucion);for(let p of u.modulos)console.log(` \xB7 ${p.nombre} (${p.clave}): ${p.campos} campos${p.relaciones.length?`, \u2192 ${p.relaciones.join(", ")}`:""}${p.vistas?`, ${p.vistas} vistas`:""}`);console.log(` paneles: ${u.paneles} \xB7 automatizaciones: ${u.automatizaciones} (se instalan apagadas)`)}}return s.every(d=>d.ok)?0:1}return console.log("Uso: forgenex sandbox [parar] [--puerto <n>] \xB7 crear-app (o crear) <nombre> [--plantilla html|react|archivos|natacion] \xB7 validar [directorio|archivo.json|archivo.fgx \u2026] [--json] \xB7 dev --espacio <id> \xB7 actualizar \xB7 empaquetar [--sin-firmar] \xB7 instalar --espacio <id> (--app <id> | --paquete <archivo.fgx>) \xB7 publicar --espacio <id> --paquete <archivo.fgx> [--tienda] \xB7 revisar [--paquete <archivo.fgx>] [--json] \xB7 claves crear \xB7 registrar-clave \xB7 revocar-clave \xB7 previsualizar \xB7 esquema \xB7 esquema-extension \xB7 version"),o==="--help"||o==="-h"||!o?0:2}process.argv[1]?.endsWith("cli.ts")&&ll(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});ll(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
|